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
pallet/src/mock.rs
maciejnems/aleph-node
24fe79f21530e4436b4bc350ba022af825f3a15f
#![cfg(test)] use super::*; use crate as pallet_aleph; use frame_support::{ construct_runtime, parameter_types, sp_io, traits::{OnFinalize, OnInitialize}, weights::RuntimeDbWeight, }; use primitives::AuthorityId; use sp_core::H256; use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, Perbill, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; pub(crate) type AccountId = u64; construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aleph: pallet_aleph::{Pallet, Call, Config<T>, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, } ); impl_opaque_keys! { pub struct TestSessionKeys { pub aleph: super::Pallet<Test>, } } parameter_types! { pub const BlockHashCount: u64 = 250; pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(1024); pub const TestDbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 25, write: 100 }; } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type DbWeight = TestDbWeight; type Version = (); type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData<u128>; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); type OnSetCode = (); } parameter_types! { pub const Period: u64 = 1; pub const Offset: u64 = 0; pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type Balance = u128; type MaxReserves = (); type ReserveIdentifier = [u8; 8]; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); type MaxLocks = (); } impl pallet_session::Config for Test { type Event = Event; type ValidatorId = u64; type ValidatorIdOf = ConvertInto; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>; type SessionManager = pallet_aleph::AlephSessionManager<Self>; type SessionHandler = <TestSessionKeys as OpaqueKeys>::KeyTypeIdProviders; type Keys = TestSessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); } impl<C> frame_system::offchain::SendTransactionTypes<C> for Test where Call: From<C>, { type Extrinsic = TestXt<Call, ()>; type OverarchingCall = Call; } parameter_types! { pub const MinimumPeriod: u64 = 3; } impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! {} impl Config for Test { type AuthorityId = AuthorityId; type Event = Event; } pub fn to_authorities(authorities: &[u64]) -> Vec<AuthorityId> { authorities .iter() .map(|id| UintAuthorityId(*id).to_public_key::<AuthorityId>()) .collect() } pub fn new_test_ext(authorities: &[(u64, u64)]) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); let balances: Vec<_> = (0..authorities.len()) .map(|i| (i as u64, 10_000_000)) .collect(); pallet_balances::GenesisConfig::<Test> { balances } .assimilate_storage(&mut t) .unwrap(); let session_keys: Vec<_> = authorities .iter() .map(|(id, weight)| (UintAuthorityId(*id).to_public_key::<AuthorityId>(), weight)) .enumerate() .map(|(i, (k, _))| (i as u64, i as u64, TestSessionKeys { aleph: k })) .collect(); pallet_session::GenesisConfig::<Test> { keys: session_keys } .assimilate_storage(&mut t) .unwrap(); t.into() } pub(crate) fn run_session(n: u64) { while System::block_number() < n { Session::on_finalize(System::block_number()); Aleph::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::initialize( &(System::block_number() + 1), &System::parent_hash(), &Default::default(), Default::default(), ); System::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aleph::on_initialize(System::block_number()); } } pub(crate) fn initialize_session() { System::initialize( &1, &System::parent_hash(), &Default::default(), Default::default(), ); System::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aleph::on_initialize(System::block_number()); }
#![cfg(test)] use super::*; use crate as pallet_aleph; use frame_support::{ construct_runtime, parameter_types, sp_io, traits::{OnFinalize, OnInitialize}, weights::RuntimeDbWeight, }; use primitives::AuthorityId; use sp_core::H256; use sp_runtime::{ impl_opaque_keys, testing::{Header, TestXt, UintAuthorityId}, traits::{ConvertInto, IdentityLookup, OpaqueKeys}, Perbill, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; pub(crate) type AccountId = u64; construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Pallet, Call, Config, Storage, Event<T>}, Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>}, Session: pallet_session::{Pallet, Call, Storage, Event, Config<T>}, Aleph: pallet_aleph::{Pallet, Call, Config<T>, Storage, Event<T>}, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent}, } ); impl_opaque_keys! { pub struct TestSessionKeys { pub aleph: super::Pallet<Test>, } } parameter_types! { pub const BlockHashCount: u64 = 250; pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(1024); pub const TestDbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 25, write: 100 }; } impl frame_system::Config for Test { type BaseCallFilter = frame_support::traits::Everything; type BlockWeights = (); type BlockLength = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = sp_runtime::traits::BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type DbWeight = TestDbWeight; type Version = (); type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData<u128>; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); type OnSetCode = (); } parameter_types! { pub const Period: u64 = 1; pub const Offset: u64 = 0; pub const DisabledValidatorsThreshold: Perbill = Perbill::from_percent(17); } parameter_types! { pub const ExistentialDeposit: u128 = 1; } impl pallet_balances::Config for Test { type Balance = u128; type MaxReserves = (); type ReserveIdentifier = [u8; 8]; type DustRemoval = (); type Event = Event; type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); type MaxLocks = (); } impl pallet_session::Config for Test { type Event = Event; type ValidatorId = u64; type ValidatorIdOf = ConvertInto; type ShouldEndSession = pallet_session::PeriodicSessions<Period, Offset>; type NextSessionRotation = pallet_session::PeriodicSessions<Period, Offset>; type SessionManager = pallet_aleph::AlephSessionMa
lect() } pub fn new_test_ext(authorities: &[(u64, u64)]) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); let balances: Vec<_> = (0..authorities.len()) .map(|i| (i as u64, 10_000_000)) .collect(); pallet_balances::GenesisConfig::<Test> { balances } .assimilate_storage(&mut t) .unwrap(); let session_keys: Vec<_> = authorities .iter() .map(|(id, weight)| (UintAuthorityId(*id).to_public_key::<AuthorityId>(), weight)) .enumerate() .map(|(i, (k, _))| (i as u64, i as u64, TestSessionKeys { aleph: k })) .collect(); pallet_session::GenesisConfig::<Test> { keys: session_keys } .assimilate_storage(&mut t) .unwrap(); t.into() } pub(crate) fn run_session(n: u64) { while System::block_number() < n { Session::on_finalize(System::block_number()); Aleph::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::initialize( &(System::block_number() + 1), &System::parent_hash(), &Default::default(), Default::default(), ); System::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aleph::on_initialize(System::block_number()); } } pub(crate) fn initialize_session() { System::initialize( &1, &System::parent_hash(), &Default::default(), Default::default(), ); System::on_initialize(System::block_number()); Session::on_initialize(System::block_number()); Aleph::on_initialize(System::block_number()); }
nager<Self>; type SessionHandler = <TestSessionKeys as OpaqueKeys>::KeyTypeIdProviders; type Keys = TestSessionKeys; type DisabledValidatorsThreshold = DisabledValidatorsThreshold; type WeightInfo = (); } impl<C> frame_system::offchain::SendTransactionTypes<C> for Test where Call: From<C>, { type Extrinsic = TestXt<Call, ()>; type OverarchingCall = Call; } parameter_types! { pub const MinimumPeriod: u64 = 3; } impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } parameter_types! {} impl Config for Test { type AuthorityId = AuthorityId; type Event = Event; } pub fn to_authorities(authorities: &[u64]) -> Vec<AuthorityId> { authorities .iter() .map(|id| UintAuthorityId(*id).to_public_key::<AuthorityId>()) .col
random
[ { "content": "pub fn session_id_from_block_num<B: Block>(num: NumberFor<B>, period: SessionPeriod) -> SessionId {\n\n SessionId(num.saturated_into::<u32>() / period.0)\n\n}\n\n\n\npub struct AlephConfig<B: Block, N, C, SC> {\n\n pub network: N,\n\n pub client: Arc<C>,\n\n pub select_chain: SC,\n\n pub spawn_handle: SpawnTaskHandle,\n\n pub keystore: Arc<dyn CryptoStore>,\n\n pub justification_rx: mpsc::UnboundedReceiver<JustificationNotification<B>>,\n\n pub metrics: Option<Metrics<<B::Header as Header>::Hash>>,\n\n pub session_period: SessionPeriod,\n\n pub millisecs_per_block: MillisecsPerBlock,\n\n pub unit_creation_delay: UnitCreationDelay,\n\n}\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 0, "score": 225782.36331579808 }, { "content": "type CallArgs = (THash, TNumber);\n\n\n\n#[derive(Clone)]\n\npub(crate) struct MockedBlockRequester {\n\n mock: SingleActionMock<CallArgs>,\n\n}\n\n\n\nimpl MockedBlockRequester {\n\n pub(crate) fn new() -> Self {\n\n Self {\n\n mock: Default::default(),\n\n }\n\n }\n\n\n\n pub(crate) async fn has_not_been_invoked(&self) -> bool {\n\n self.mock.has_not_been_invoked().await\n\n }\n\n\n\n pub(crate) async fn has_been_invoked_with(&self, block: TBlock) -> bool {\n\n self.mock\n", "file_path": "finality-aleph/src/testing/mocks/block_request.rs", "rank": 2, "score": 211579.74956993584 }, { "content": " #[pallet::config]\n\n pub trait Config: frame_system::Config + pallet_session::Config {\n\n type AuthorityId: Member\n\n + Parameter\n\n + RuntimeAppPublic\n\n + Default\n\n + MaybeSerializeDeserialize;\n\n type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;\n\n }\n\n\n\n #[pallet::event]\n\n #[pallet::metadata(T::AccountId = \"AccountId\")]\n\n #[pallet::generate_deposit(pub(super) fn deposit_event)]\n\n pub enum Event<T: Config> {\n\n ChangeValidators(Vec<T::AccountId>, u32),\n\n }\n\n\n\n pub struct AlephSessionManager<T>(sp_std::marker::PhantomData<T>);\n\n\n\n #[pallet::pallet]\n\n #[pallet::storage_version(STORAGE_VERSION)]\n", "file_path": "pallet/src/lib.rs", "rank": 3, "score": 208767.55597576645 }, { "content": "type Header = generic::Header<BlockNumber, BlakeTwo256>;\n", "file_path": "e2e-tests/src/lib.rs", "rank": 4, "score": 200846.5695618604 }, { "content": "type CallArgs = (THash, TNumber, Option<Justification>);\n\n\n\n#[derive(Clone)]\n\npub(crate) struct MockedBlockFinalizer {\n\n mock: SingleActionMock<CallArgs>,\n\n}\n\n\n\nimpl MockedBlockFinalizer {\n\n pub(crate) fn new() -> Self {\n\n Self {\n\n mock: Default::default(),\n\n }\n\n }\n\n\n\n pub(crate) async fn has_not_been_invoked(&self) -> bool {\n\n self.mock.has_not_been_invoked().await\n\n }\n\n\n\n pub(crate) async fn has_been_invoked_with(&self, block: TBlock) -> bool {\n\n self.mock\n", "file_path": "finality-aleph/src/testing/mocks/block_finalizer.rs", "rank": 5, "score": 199344.57391639936 }, { "content": "type Block = generic::Block<Header, OpaqueExtrinsic>;\n\n\n", "file_path": "flooder/src/main.rs", "rank": 6, "score": 197661.762171514 }, { "content": "pub fn last_block_of_session<B: Block>(\n\n session_id: SessionId,\n\n period: SessionPeriod,\n\n) -> NumberFor<B> {\n\n ((session_id.0 + 1) * period.0 - 1).into()\n\n}\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 7, "score": 191196.90823556978 }, { "content": "type MockData = Vec<u8>;\n\n\n", "file_path": "finality-aleph/src/testing/network.rs", "rank": 8, "score": 187808.68301996976 }, { "content": "#[derive(Debug, Decode, Copy, Clone)]\n\nstruct NewSessionEvent {\n\n session_index: u32,\n\n}\n\n\n", "file_path": "e2e-tests/src/test/validators_change.rs", "rank": 10, "score": 182867.647488957 }, { "content": "type RmcMessage<B> = Message<SignableHash<<B as Block>::Hash>, Signature, SignatureSet<Signature>>;\n\n/// A wrapper around an RMC returning the signed hashes in the order of the [`ReliableMulticast::start_rmc`] calls.\n\npub(crate) struct BlockSignatureAggregator<'a, B: Block, MK: MultiKeychain> {\n\n messages_for_rmc: mpsc::UnboundedSender<RmcMessage<B>>,\n\n messages_from_rmc: mpsc::UnboundedReceiver<RmcMessage<B>>,\n\n signatures: HashMap<B::Hash, MK::PartialMultisignature>,\n\n hash_queue: VecDeque<B::Hash>,\n\n network: RmcNetwork<B>,\n\n rmc: ReliableMulticast<'a, SignableHash<B::Hash>, MK>,\n\n last_hash_placed: bool,\n\n started_hashes: HashSet<B::Hash>,\n\n metrics: Option<Metrics<<B::Header as Header>::Hash>>,\n\n}\n\n\n\nimpl<\n\n 'a,\n\n B: Block,\n\n MK: MultiKeychain<Signature = Signature, PartialMultisignature = SignatureSet<Signature>>,\n\n > BlockSignatureAggregator<'a, B, MK>\n\n{\n", "file_path": "finality-aleph/src/aggregator.rs", "rank": 11, "score": 172114.85962411162 }, { "content": "type Header = generic::Header<BlockNumber, BlakeTwo256>;\n", "file_path": "flooder/src/main.rs", "rank": 12, "score": 171303.46520639805 }, { "content": "pub fn token_transfer(config: Config) -> anyhow::Result<()> {\n\n let (connection, _, to) = setup_for_transfer(config);\n\n\n\n let balance_before = get_free_balance(&to, &connection);\n\n info!(\"[+] Account {} balance before tx: {}\", to, balance_before);\n\n\n\n let transfer_value = 1000u128;\n\n transfer(&to, transfer_value, &connection);\n\n\n\n let balance_after = get_free_balance(&to, &connection);\n\n info!(\"[+] Account {} balance after tx: {}\", to, balance_after);\n\n\n\n assert_eq!(\n\n balance_before + transfer_value,\n\n balance_after,\n\n \"before = {}, after = {}, tx = {}\",\n\n balance_before,\n\n balance_after,\n\n transfer_value\n\n );\n\n\n\n Ok(())\n\n}\n", "file_path": "e2e-tests/src/test/transfer.rs", "rank": 13, "score": 170975.3446825625 }, { "content": "pub fn channeling_fee(config: Config) -> anyhow::Result<()> {\n\n let (connection, _, to) = setup_for_transfer(config);\n\n let treasury = get_treasury_account(&connection);\n\n\n\n let treasury_balance_before = get_free_balance(&treasury, &connection);\n\n let issuance_before = get_total_issuance(&connection);\n\n info!(\n\n \"[+] Treasury balance before tx: {}. Total issuance: {}.\",\n\n treasury_balance_before, issuance_before\n\n );\n\n\n\n let tx = transfer(&to, 1000u128, &connection);\n\n\n\n let treasury_balance_after = get_free_balance(&treasury, &connection);\n\n let issuance_after = get_total_issuance(&connection);\n\n info!(\n\n \"[+] Treasury balance after tx: {}. Total issuance: {}.\",\n\n treasury_balance_after, issuance_after\n\n );\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 14, "score": 170975.3446825625 }, { "content": "pub fn treasury_access(config: Config) -> anyhow::Result<()> {\n\n let Config { node, seeds, .. } = config.clone();\n\n\n\n let proposer = accounts_from_seeds(seeds)[0].to_owned();\n\n let beneficiary = AccountId::from(proposer.public());\n\n let connection = create_connection(node).set_signer(proposer);\n\n\n\n propose_treasury_spend(10u128, &beneficiary, &connection);\n\n propose_treasury_spend(100u128, &beneficiary, &connection);\n\n let proposals_counter = get_proposals_counter(&connection);\n\n assert!(proposals_counter >= 2, \"Proposal was not created\");\n\n\n\n let sudo = get_sudo(config);\n\n let connection = connection.set_signer(sudo);\n\n\n\n treasury_approve(proposals_counter - 2, &connection)?;\n\n treasury_reject(proposals_counter - 1, &connection)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 15, "score": 170975.3446825625 }, { "content": "pub fn fee_calculation(config: Config) -> anyhow::Result<()> {\n\n let (connection, from, to) = setup_for_transfer(config);\n\n\n\n let balance_before = get_free_balance(&from, &connection);\n\n info!(\"[+] Account {} balance before tx: {}\", to, balance_before);\n\n\n\n let transfer_value = 1000u128;\n\n let tx = transfer(&to, transfer_value, &connection);\n\n\n\n let balance_after = get_free_balance(&from, &connection);\n\n info!(\"[+] Account {} balance after tx: {}\", to, balance_after);\n\n\n\n let FeeInfo {\n\n fee_without_weight,\n\n unadjusted_weight,\n\n adjusted_weight,\n\n } = get_tx_fee_info(&connection, &tx);\n\n let multiplier = 1; // corresponds to `ConstantFeeMultiplierUpdate`\n\n assert_eq!(\n\n multiplier * unadjusted_weight,\n", "file_path": "e2e-tests/src/test/transfer.rs", "rank": 16, "score": 170975.3446825625 }, { "content": "#[derive(Clone)]\n\nstruct TestBlockRequester<B: BlockT> {\n\n blocks: mpsc::UnboundedSender<AlephDataFor<B>>,\n\n justifications: mpsc::UnboundedSender<AlephDataFor<B>>,\n\n}\n\n\n\nimpl<B: BlockT> TestBlockRequester<B> {\n\n fn new() -> (\n\n Self,\n\n mpsc::UnboundedReceiver<AlephDataFor<B>>,\n\n mpsc::UnboundedReceiver<AlephDataFor<B>>,\n\n ) {\n\n let (blocks_tx, blocks_rx) = mpsc::unbounded();\n\n let (justifications_tx, justifications_rx) = mpsc::unbounded();\n\n (\n\n TestBlockRequester {\n\n blocks: blocks_tx,\n\n justifications: justifications_tx,\n\n },\n\n blocks_rx,\n\n justifications_rx,\n", "file_path": "finality-aleph/src/testing/data_io.rs", "rank": 17, "score": 170956.7368175905 }, { "content": "pub fn change_validators(config: Config) -> anyhow::Result<()> {\n\n let Config { node, seeds, .. } = config.clone();\n\n\n\n let accounts = accounts_from_seeds(seeds);\n\n let sudo = get_sudo(config);\n\n\n\n let connection = create_connection(node).set_signer(sudo);\n\n\n\n let validators_before: Vec<AccountId> = connection\n\n .get_storage_value(\"Session\", \"Validators\", None)?\n\n .unwrap();\n\n\n\n info!(\"[+] Validators before tx: {:#?}\", validators_before);\n\n\n\n let new_validators: Vec<AccountId> = accounts\n\n .into_iter()\n\n .map(|pair| pair.public().into())\n\n .chain(iter::once(\n\n AccountId::from_ss58check(\"5EHkv1FCd4jeQmVrbYhrETL1EAr8NJxNbukDRT4FaYWbjW8f\").unwrap(),\n\n ))\n", "file_path": "e2e-tests/src/test/validators_change.rs", "rank": 18, "score": 168842.08998797816 }, { "content": "pub fn finalization(config: Config) -> anyhow::Result<u32> {\n\n let connection = create_connection(config.node);\n\n wait_for_finalized_block(&connection, 1)\n\n}\n", "file_path": "e2e-tests/src/test/finalization.rs", "rank": 19, "score": 168235.75083506227 }, { "content": "#[derive(Clone)]\n\nstruct TestNetwork<B: BlockT> {\n\n event_sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<Event>>>>,\n\n oneshot_sender: Arc<Mutex<Option<oneshot::Sender<()>>>>,\n\n report_peer: Channel<(PeerId, ReputationChange)>,\n\n disconnect_peer: Channel<(PeerId, Cow<'static, str>)>,\n\n send_message: Channel<(PeerId, Cow<'static, str>, Vec<u8>)>,\n\n announce: Channel<(B::Hash, Option<Vec<u8>>)>,\n\n add_set_reserved: Channel<(PeerId, Cow<'static, str>)>,\n\n remove_set_reserved: Channel<(PeerId, Cow<'static, str>)>,\n\n request_justification: Channel<(B::Hash, NumberFor<B>)>,\n\n peer_id: PeerId,\n\n}\n\n\n\nimpl<B: BlockT> TestNetwork<B> {\n\n fn new(peer_id: PeerId, tx: oneshot::Sender<()>) -> Self {\n\n TestNetwork {\n\n event_sinks: Arc::new(Mutex::new(vec![])),\n\n oneshot_sender: Arc::new(Mutex::new(Some(tx))),\n\n report_peer: channel(),\n\n disconnect_peer: channel(),\n", "file_path": "finality-aleph/src/testing/network.rs", "rank": 20, "score": 166255.5567159514 }, { "content": "pub fn get_sudo(config: Config) -> KeyPair {\n\n match config.sudo {\n\n Some(seed) => keypair_from_string(seed),\n\n None => accounts_from_seeds(config.seeds)[0].to_owned(),\n\n }\n\n}\n\n\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 21, "score": 166137.2237870373 }, { "content": "#[derive(Debug)]\n\nenum SendJustificationError<Block>\n\nwhere\n\n Block: BlockT,\n\n{\n\n Send(TrySendError<JustificationNotification<Block>>),\n\n Consensus(Box<ConsensusError>),\n\n Decode,\n\n}\n\n\n\nimpl<Block, Be, I> AlephBlockImport<Block, Be, I>\n\nwhere\n\n Block: BlockT,\n\n Be: Backend<Block>,\n\n I: crate::ClientForAleph<Block, Be>,\n\n{\n\n pub fn new(\n\n inner: Arc<I>,\n\n justification_tx: UnboundedSender<JustificationNotification<Block>>,\n\n metrics: Option<Metrics<<Block::Header as Header>::Hash>>,\n\n ) -> AlephBlockImport<Block, Be, I> {\n", "file_path": "finality-aleph/src/import.rs", "rank": 22, "score": 162053.25943692547 }, { "content": "type MessageId = u64;\n\nconst REFRESH_INTERVAL: u64 = 100;\n\nconst AVAILABLE_BLOCKS_CACHE_SIZE: usize = 1000;\n\nconst MESSAGE_ID_BOUNDARY: MessageId = 100_000;\n\nconst PERIODIC_MAINTENANCE_INTERVAL: Duration = Duration::from_secs(60);\n\nconst REQUEST_FORK_AFTER: Duration = Duration::from_secs(100);\n\n\n\n/// The data ordered by the Aleph consensus.\n\n#[derive(Copy, PartialEq, Eq, Clone, Debug, Encode, Decode, Hash)]\n\npub struct AlephData<H, N> {\n\n pub hash: H,\n\n pub number: N,\n\n}\n\n\n\nimpl<H, N> AlephData<H, N> {\n\n pub(crate) fn new(block_hash: H, block_number: N) -> Self {\n\n AlephData {\n\n hash: block_hash,\n\n number: block_number,\n\n }\n", "file_path": "finality-aleph/src/data_io.rs", "rank": 23, "score": 161677.0738162051 }, { "content": "pub fn migrate<T: Config, P: GetStorageVersion + PalletInfoAccess>() -> Weight {\n\n let on_chain_storage_version = <P as GetStorageVersion>::on_chain_storage_version();\n\n let current_storage_version = <P as GetStorageVersion>::current_storage_version();\n\n\n\n if on_chain_storage_version == StorageVersion::default() && current_storage_version == 1 {\n\n log::info!(target: \"pallet_aleph\", \"Running migration from STORAGE_VERSION 0 to 1\");\n\n\n\n let mut writes = 0;\n\n\n\n match crate::SessionForValidatorsChange::<T>::translate(\n\n |old: Option<Option<u32>>| -> Option<u32> {\n\n log::info!(target: \"pallet_aleph\", \"Current storage value for SessionForValidatorsChange {:?}\", old);\n\n match old {\n\n Some(Some(x)) => Some(x),\n\n _ => None,\n\n }\n\n },\n\n ) {\n\n Ok(_) => {\n\n writes += 1;\n", "file_path": "pallet/src/migrations/v0_to_v1.rs", "rank": 24, "score": 156260.1694806366 }, { "content": "pub fn setup_for_transfer(config: Config) -> (Connection, AccountId32, AccountId32) {\n\n let Config { node, seeds, .. } = config;\n\n\n\n let accounts = accounts_from_seeds(seeds);\n\n let (from, to) = (accounts[0].to_owned(), accounts[1].to_owned());\n\n\n\n let connection = create_connection(node).set_signer(from.clone());\n\n let from = AccountId::from(from.public());\n\n let to = AccountId::from(to.public());\n\n (connection, from, to)\n\n}\n\n\n", "file_path": "e2e-tests/src/transfer.rs", "rank": 25, "score": 153675.69127692914 }, { "content": "struct Session<D: Data> {\n\n handler: SessionHandler,\n\n discovery: Discovery,\n\n data_for_user: Option<mpsc::UnboundedSender<D>>,\n\n}\n\n\n\n/// The connection manager service.\n\npub struct Service<NI: NetworkIdentity, D: Data> {\n\n network_identity: NI,\n\n connections: Connections,\n\n sessions: HashMap<SessionId, Session<D>>,\n\n}\n\n\n\nimpl<NI: NetworkIdentity, D: Data> Service<NI, D> {\n\n /// Create a new connection manager service.\n\n pub fn new(network_identity: NI) -> Self {\n\n Service {\n\n network_identity,\n\n connections: Connections::new(),\n\n sessions: HashMap::new(),\n", "file_path": "finality-aleph/src/new_network/manager/service.rs", "rank": 26, "score": 151229.4189937532 }, { "content": "#[derive(Debug, Decode, Copy, Clone)]\n\nstruct ProposalRejectedEvent {\n\n proposal_id: u32,\n\n _slashed: u128,\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 27, "score": 150271.49626575527 }, { "content": "type Hasher = hash::Wrapper<BlakeTwo256>;\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 28, "score": 149826.46452457597 }, { "content": "type GovernanceTransaction = UncheckedExtrinsicV4<([u8; 2], Compact<u32>)>;\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 29, "score": 149650.4712399108 }, { "content": "type Sender = UnboundedSender<JustificationNotification<TBlock>>;\n", "file_path": "finality-aleph/src/testing/justification.rs", "rank": 30, "score": 147858.3671022733 }, { "content": "struct TestData {\n\n network: TestNetwork<Block>,\n\n authorities: Vec<Authority>,\n\n consensus_network_handle: tokio::task::JoinHandle<()>,\n\n data_network: DataNetwork<MockData>,\n\n}\n\n\n\nimpl TestData {\n\n // consumes the test data asserting there are no unread messages in the channels\n\n // and awaits for the consensus_network task.\n\n async fn complete(mut self) {\n\n self.network.close_channels();\n\n assert!(self.data_network.next().await.is_none());\n\n self.consensus_network_handle.await.unwrap();\n\n }\n\n}\n\n\n\nconst PROTOCOL_NAME: &str = \"/test/1\";\n\n\n\nasync fn prepare_one_session_test_data() -> TestData {\n", "file_path": "finality-aleph/src/testing/network.rs", "rank": 32, "score": 144458.20226945315 }, { "content": "type BlockNumber = u32;\n", "file_path": "e2e-tests/src/lib.rs", "rank": 33, "score": 140354.4695431012 }, { "content": "#[derive(Copy, Clone, Debug, Eq, PartialEq)]\n\nenum SessionStatus {\n\n InProgress,\n\n Terminated,\n\n}\n\n\n\n#[derive(Clone, Copy, Encode, Decode, Debug, Eq, PartialEq)]\n\npub(crate) enum Recipient<T: Clone + Encode + Decode + Eq + PartialEq> {\n\n All,\n\n Target(T),\n\n}\n\n\n\nimpl From<aleph_bft::Recipient> for Recipient<NodeIndex> {\n\n fn from(recipient: aleph_bft::Recipient) -> Self {\n\n match recipient {\n\n aleph_bft::Recipient::Everyone => Recipient::All,\n\n aleph_bft::Recipient::Node(node) => Recipient::Target(node),\n\n }\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/network.rs", "rank": 34, "score": 140302.4882167553 }, { "content": "pub trait Key: Hash + Eq + Debug + Copy {}\n\nimpl<T: Hash + Eq + Debug + Copy> Key for T {}\n\n\n", "file_path": "finality-aleph/src/metrics.rs", "rank": 35, "score": 139919.77571361788 }, { "content": "#[derive(Debug)]\n\nstruct TestNetworkData {\n\n data: Vec<AlephDataFor<Block>>,\n\n}\n\n\n\nimpl AlephNetworkMessage<Block> for TestNetworkData {\n\n fn included_blocks(&self) -> Vec<AlephDataFor<Block>> {\n\n self.data.clone()\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/testing/data_io.rs", "rank": 36, "score": 139431.01296525286 }, { "content": "struct Authority {\n\n peer_id: PeerId,\n\n keychain: KeyBox,\n\n}\n\n\n\nasync fn generate_authorities(ss: &[String]) -> Vec<Authority> {\n\n let key_store = Arc::new(KeyStore::new());\n\n let mut auth_ids = Vec::with_capacity(ss.len());\n\n for s in ss {\n\n let pk = key_store\n\n .ed25519_generate_new(KEY_TYPE, Some(s))\n\n .await\n\n .unwrap();\n\n auth_ids.push(AuthorityId::from(pk));\n\n }\n\n let mut result = Vec::with_capacity(ss.len());\n\n for i in 0..ss.len() {\n\n let keychain = KeyBox::new(\n\n NodeIndex(i),\n\n AuthorityVerifier::new(auth_ids.clone()),\n", "file_path": "finality-aleph/src/testing/network.rs", "rank": 37, "score": 137837.0374682116 }, { "content": "type Environment = (\n\n TJustHandler,\n\n Client,\n\n MockedBlockRequester,\n\n MockedBlockFinalizer,\n\n JustificationRequestDelayImpl,\n\n);\n\n\n", "file_path": "finality-aleph/src/testing/justification.rs", "rank": 38, "score": 137797.65934603038 }, { "content": "pub fn run_aleph_consensus<B: Block, BE, C, N, SC>(\n\n config: AlephConfig<B, N, C, SC>,\n\n) -> impl Future<Output = ()>\n\nwhere\n\n BE: Backend<B> + 'static,\n\n N: network::Network<B> + network::RequestBlocks<B> + 'static,\n\n C: ClientForAleph<B, BE> + Send + Sync + 'static,\n\n C::Api: aleph_primitives::AlephSessionApi<B>,\n\n SC: SelectChain<B> + 'static,\n\n{\n\n run_consensus_party(AlephParams { config })\n\n}\n", "file_path": "finality-aleph/src/lib.rs", "rank": 39, "score": 136094.4651391668 }, { "content": "/// Abstraction for requesting justifications for finalized blocks and stale blocks.\n\npub trait RequestBlocks<B: Block>: Clone + Send + Sync + 'static {\n\n /// Request the justification for the given block\n\n fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>);\n\n\n\n /// Request the given block -- this is supposed to be used only for \"old forks\".\n\n fn request_stale_block(&self, hash: B::Hash, number: NumberFor<B>);\n\n}\n\n\n\n/// What do do with a specific piece of data.\n\n/// Note that broadcast does not specify the protocol, as we only broadcast Generic messages in this sense.\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum DataCommand {\n\n Broadcast,\n\n SendTo(PeerId, Protocol),\n\n}\n\n\n\n/// Commands for manipulating the reserved peers set.\n\n#[derive(Debug, PartialEq)]\n\npub enum ConnectionCommand {\n\n AddReserved(HashSet<Multiaddr>),\n\n DelReserved(HashSet<PeerId>),\n\n}\n\n\n\n/// Returned when something went wrong when sending data using a DataNetwork.\n\npub enum SendError {\n\n SendFailed,\n\n}\n\n\n", "file_path": "finality-aleph/src/new_network/mod.rs", "rank": 40, "score": 134631.02937435787 }, { "content": "struct JustificationRequestDelayImpl {\n\n last_request_time: Instant,\n\n last_finalization_time: Instant,\n\n delay: Duration,\n\n}\n\n\n\nimpl JustificationRequestDelayImpl {\n\n fn new(session_period: &SessionPeriod, millisecs_per_block: &MillisecsPerBlock) -> Self {\n\n Self {\n\n last_request_time: Instant::now(),\n\n last_finalization_time: Instant::now(),\n\n delay: Duration::from_millis(min(\n\n millisecs_per_block.0 * 2,\n\n millisecs_per_block.0 * session_period.0 as u64 / 10,\n\n )),\n\n }\n\n }\n\n}\n\n\n\nimpl JustificationRequestDelay for JustificationRequestDelayImpl {\n", "file_path": "finality-aleph/src/party.rs", "rank": 41, "score": 134224.37718941717 }, { "content": "type NetworkEventStream = Pin<Box<dyn Stream<Item = Event> + Send>>;\n\n\n\n/// Abstraction over a network.\n", "file_path": "finality-aleph/src/new_network/mod.rs", "rank": 42, "score": 133717.80588639854 }, { "content": "struct SessionData<D> {\n\n data_for_user: mpsc::UnboundedSender<D>,\n\n status: SessionStatus,\n\n keychain: KeyBox,\n\n auth_data: AuthData,\n\n auth_signature: Signature,\n\n}\n\n\n", "file_path": "finality-aleph/src/network.rs", "rank": 43, "score": 133639.57770107425 }, { "content": " pub trait AlephSessionApi\n\n {\n\n fn next_session_authorities() -> Result<Vec<AuthorityId>, ApiError>;\n\n fn authorities() -> Vec<AuthorityId>;\n\n fn session_period() -> u32;\n\n fn millisecs_per_block() -> u64;\n\n }\n\n}\n", "file_path": "primitives/src/lib.rs", "rank": 44, "score": 132802.03486719046 }, { "content": "type Channel<T> = (\n\n Arc<Mutex<mpsc::UnboundedSender<T>>>,\n\n Arc<Mutex<mpsc::UnboundedReceiver<T>>>,\n\n);\n\n\n", "file_path": "finality-aleph/src/testing/network.rs", "rank": 45, "score": 131942.49085264292 }, { "content": "pub fn peers_set_config(protocol: Option<new_network::Protocol>) -> sc_network::config::NonDefaultSetConfig {\n\n let name = match protocol {\n\n Some(ref p) => p.name(),\n\n _ => network::ALEPH_PROTOCOL_NAME.into(),\n\n };\n\n\n\n let mut config = sc_network::config::NonDefaultSetConfig::new(\n\n name,\n\n // max_notification_size should be larger than the maximum possible honest message size (in bytes).\n\n // Max size of alert is UNIT_SIZE * MAX_UNITS_IN_ALERT ~ 100 * 5000 = 50000 bytes\n\n // Max size of parents response UNIT_SIZE * N_MEMBERS ~ 100 * N_MEMBERS\n\n // When adding other (large) message types we need to make sure this limit is fine.\n\n 1024 * 1024,\n\n );\n\n\n\n config.set_config = match protocol {\n\n Some(new_network::Protocol::Validator) => {\n\n sc_network::config::SetConfig {\n\n in_peers: 25,\n\n out_peers: 0,\n", "file_path": "finality-aleph/src/lib.rs", "rank": 46, "score": 130068.43042559377 }, { "content": "pub fn read_phrase(phrase: String) -> String {\n\n let file = PathBuf::from(&phrase);\n\n if file.is_file() {\n\n fs::read_to_string(phrase).unwrap().trim_end().to_owned()\n\n } else {\n\n phrase\n\n }\n\n}\n", "file_path": "flooder/src/config.rs", "rank": 47, "score": 129627.84646466615 }, { "content": "struct DataStoreChannels {\n\n store_tx: UnboundedSender<TestNetworkData>,\n\n store_rx: UnboundedReceiver<TestNetworkData>,\n\n block_requests_rx: UnboundedReceiver<AlephDataFor<Block>>,\n\n exit_data_store_tx: oneshot::Sender<()>,\n\n}\n\n\n", "file_path": "finality-aleph/src/testing/data_io.rs", "rank": 48, "score": 129561.37288659842 }, { "content": "pub fn transfer(target: &AccountId32, value: u128, connection: &Connection) -> TransferTransaction {\n\n crate::send_extrinsic!(\n\n connection,\n\n \"Balances\",\n\n \"transfer\",\n\n |tx_hash| info!(\"[+] Transfer transaction hash: {}\", tx_hash),\n\n GenericAddress::Id(target.clone()),\n\n Compact(value)\n\n )\n\n}\n", "file_path": "e2e-tests/src/transfer.rs", "rank": 49, "score": 127117.34312837472 }, { "content": "type TJustHandler = JustificationHandler<\n\n TBlock,\n\n VerifierWrapper,\n\n MockedBlockRequester,\n\n Client,\n\n JustificationRequestDelayImpl,\n\n SessionInfoProviderImpl,\n\n MockedBlockFinalizer,\n\n>;\n", "file_path": "finality-aleph/src/testing/justification.rs", "rank": 50, "score": 124102.9899564864 }, { "content": "fn create_justification_notification_for(block: TBlock) -> JustificationNotification<TBlock> {\n\n JustificationNotification {\n\n justification: AlephJustification {\n\n signature: SignatureSet::with_size(0.into()),\n\n },\n\n hash: block.hash(),\n\n number: block.header.number,\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/testing/justification.rs", "rank": 51, "score": 124025.6100726054 }, { "content": "pub fn get_free_balance(account: &AccountId32, connection: &Connection) -> Balance {\n\n connection.get_account_data(account).unwrap().unwrap().free\n\n}\n", "file_path": "e2e-tests/src/accounts.rs", "rank": 52, "score": 123750.83819203486 }, { "content": "fn get_session_info_provider<B: Block>(\n\n session_authorities: Arc<Mutex<HashMap<SessionId, Vec<AuthorityId>>>>,\n\n session_period: SessionPeriod,\n\n) -> impl SessionInfoProvider<B, AuthorityVerifier> {\n\n move |block_num| {\n\n let current_session = session_id_from_block_num::<B>(block_num, session_period);\n\n let last_block_height = last_block_of_session::<B>(current_session, session_period);\n\n let verifier = session_authorities\n\n .lock()\n\n .get(&current_session)\n\n .map(|sa: &Vec<AuthorityId>| AuthorityVerifier::new(sa.to_vec()));\n\n\n\n SessionInfo {\n\n current_session,\n\n last_block_height,\n\n verifier,\n\n }\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/party.rs", "rank": 53, "score": 123552.80459076098 }, { "content": "#[derive(Clone, Encode, Decode)]\n\nenum SessionCommand<D: Clone + Encode + Decode> {\n\n Meta(MetaMessage, Recipient<PeerId>),\n\n Data(SessionId, D, Recipient<NodeIndex>),\n\n Control(ControlCommand),\n\n}\n\n\n\nimpl<D: Clone + Codec> SessionCommand<D> {\n\n fn map<E: Clone + Codec, F: FnOnce(D) -> E>(self, f: F) -> SessionCommand<E> {\n\n use SessionCommand::*;\n\n match self {\n\n Meta(message, recipient) => Meta(message, recipient),\n\n Data(session_id, data, recipient) => Data(session_id, f(data), recipient),\n\n Control(cc) => Control(cc),\n\n }\n\n }\n\n}\n\n\n\npub(crate) struct SessionManager<D: Clone + Codec> {\n\n peer_id: PeerId,\n\n sessions: Arc<Mutex<HashMap<SessionId, SessionData<D>>>>,\n", "file_path": "finality-aleph/src/network.rs", "rank": 54, "score": 119906.78533039385 }, { "content": "/// blocks the main thread waiting for a block with a number at least `block_number`\n\npub fn wait_for_finalized_block(connection: &Connection, block_number: u32) -> anyhow::Result<u32> {\n\n let (sender, receiver) = channel();\n\n connection.subscribe_finalized_heads(sender)?;\n\n\n\n while let Ok(header) = receiver\n\n .recv()\n\n .map(|h| serde_json::from_str::<Header>(&h).unwrap())\n\n {\n\n info!(\"[+] Received header for a block number {:?}\", header.number);\n\n\n\n if header.number.ge(&block_number) {\n\n return Ok(block_number);\n\n }\n\n }\n\n\n\n Err(anyhow::anyhow!(\"Giving up\"))\n\n}\n", "file_path": "e2e-tests/src/waiting.rs", "rank": 55, "score": 117273.10932569517 }, { "content": "pub trait RequestBlocks<B: BlockT>: Clone + Send + Sync + 'static {\n\n /// Request the justification for the given block\n\n fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>);\n\n\n\n /// Request the given block -- this is supposed to be used only for \"old forks\".\n\n fn request_stale_block(&self, hash: B::Hash, number: NumberFor<B>);\n\n}\n\n\n\nimpl<B: BlockT, H: ExHashT> RequestBlocks<B> for Arc<NetworkService<B, H>> {\n\n fn request_justification(&self, hash: &B::Hash, number: NumberFor<B>) {\n\n NetworkService::request_justification(self, hash, number)\n\n }\n\n\n\n fn request_stale_block(&self, hash: B::Hash, number: NumberFor<B>) {\n\n // The below comment is adapted from substrate:\n\n // Notifies the sync service to try and sync the given block from the given peers. If the given vector\n\n // of peers is empty (as in our case) then the underlying implementation should make a best effort to fetch\n\n // the block from any peers it is connected to.\n\n NetworkService::set_sync_fork_request(self, Vec::new(), hash, number)\n\n }\n", "file_path": "finality-aleph/src/network.rs", "rank": 56, "score": 116841.23866722707 }, { "content": "type ProposalTransaction =\n\n UncheckedExtrinsicV4<([u8; 2], Compact<u128>, MultiAddress<AccountId, ()>)>;\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 57, "score": 115381.15709482826 }, { "content": "pub fn wait_for_event<E: Decode + Clone, P: Fn(E) -> bool>(\n\n connection: &Connection,\n\n event: (&str, &str),\n\n predicate: P,\n\n) -> anyhow::Result<E> {\n\n let (module, variant) = event;\n\n info!(\"[+] Creating event subscription {}/{}\", module, variant);\n\n\n\n let (events_in, events_out) = channel();\n\n connection.subscribe_events(events_in)?;\n\n\n\n loop {\n\n let args: ApiResult<E> = connection.wait_for_event(module, variant, None, &events_out);\n\n match args {\n\n Ok(event) if predicate(event.clone()) => return Ok(event),\n\n Ok(_) => (),\n\n Err(why) => error!(\"Error {:?}\", why),\n\n }\n\n }\n\n}\n\n\n", "file_path": "e2e-tests/src/waiting.rs", "rank": 59, "score": 110511.64778956855 }, { "content": "pub fn address(text: &str) -> ScMultiaddr {\n\n text.parse().unwrap()\n\n}\n\n\n", "file_path": "finality-aleph/src/new_network/manager/testing.rs", "rank": 60, "score": 110403.05180831414 }, { "content": "fn prepare_data_store() -> (impl Future<Output = ()>, Arc<TestClient>, DataStoreChannels) {\n\n let client = Arc::new(TestClientBuilder::new().build());\n\n\n\n let (aleph_network_tx, data_store_rx) = mpsc::unbounded();\n\n let (data_store_tx, aleph_network_rx) = mpsc::unbounded();\n\n let (block_requester, block_requests_rx, _justification_requests_rx) =\n\n TestBlockRequester::new();\n\n\n\n let data_store_config = DataStoreConfig {\n\n available_blocks_cache_capacity: 1000,\n\n message_id_boundary: 100_000,\n\n periodic_maintenance_interval: Duration::from_millis(30),\n\n request_block_after: Duration::from_millis(50),\n\n };\n\n let mut data_store =\n\n DataStore::<Block, TestClient, Backend, TestBlockRequester<Block>, TestNetworkData>::new(\n\n client.clone(),\n\n block_requester,\n\n data_store_tx,\n\n data_store_rx,\n", "file_path": "finality-aleph/src/testing/data_io.rs", "rank": 61, "score": 109986.94728348142 }, { "content": "/// blocking wait, if ongoing session index is >= new_session_index returns the current\n\nfn wait_for_session(connection: &Connection, new_session_index: u32) -> anyhow::Result<u32> {\n\n wait_for_event(\n\n connection,\n\n (\"Session\", \"NewSession\"),\n\n |e: NewSessionEvent| {\n\n let session_index = e.session_index;\n\n info!(\"[+] NewSession event: session index {:?}\", session_index);\n\n session_index.ge(&new_session_index)\n\n },\n\n )\n\n .map(|e| e.session_index)\n\n}\n", "file_path": "e2e-tests/src/test/validators_change.rs", "rank": 62, "score": 108016.8943543123 }, { "content": "/// Abstraction over a network.\n\npub trait Network<B: BlockT>: Clone + Send + Sync + 'static {\n\n /// Returns a stream of events representing what happens on the network.\n\n fn event_stream(&self) -> Pin<Box<dyn Stream<Item = Event> + Send>>;\n\n\n\n /// Adjust the reputation of a node.\n\n fn _report_peer(&self, peer_id: PeerId, reputation: ReputationChange);\n\n\n\n /// Force-disconnect a peer.\n\n fn _disconnect_peer(&self, peer_id: PeerId, protocol: Cow<'static, str>);\n\n\n\n /// Send a message to a given peer.\n\n fn send_message(&self, peer_id: PeerId, protocol: Cow<'static, str>, message: Vec<u8>);\n\n\n\n /// Notify everyone we're connected to that we have the given block.\n\n /// This might be useful in the future.\n\n fn _announce(&self, block: B::Hash, associated_data: Option<Vec<u8>>);\n\n\n\n /// TODO: figure out what does this actually do...\n\n fn add_set_reserved(&self, who: PeerId, protocol: Cow<'static, str>);\n\n\n\n /// TODO: figure out what does this actually do...\n\n fn remove_set_reserved(&self, who: PeerId, protocol: Cow<'static, str>);\n\n\n\n /// The PeerId of this node.\n\n fn peer_id(&self) -> PeerId;\n\n}\n\n\n", "file_path": "finality-aleph/src/network.rs", "rank": 63, "score": 107985.5416711281 }, { "content": "type TransferTransaction =\n\n UncheckedExtrinsicV4<([u8; 2], MultiAddress<AccountId, ()>, Compact<u128>)>;\n\n\n\n#[macro_export]\n\nmacro_rules! send_extrinsic {\n\n\t($connection: expr,\n\n\t$module: expr,\n\n\t$call: expr,\n\n $hash_log: expr\n\n\t$(, $args: expr) *) => {\n\n\t\t{\n\n use substrate_api_client::{compose_extrinsic, UncheckedExtrinsicV4, XtStatus};\n\n\n\n let tx: UncheckedExtrinsicV4<_> = compose_extrinsic!(\n\n $connection,\n\n $module,\n\n $call\n\n $(, ($args)) *\n\n );\n\n\n", "file_path": "e2e-tests/src/lib.rs", "rank": 64, "score": 107931.50998564804 }, { "content": "type BlockNumber = u32;\n", "file_path": "flooder/src/main.rs", "rank": 65, "score": 106926.09136282245 }, { "content": "struct Args {\n\n /// Seed phrase of the Sudo account\n\n #[structopt(long, short, name = \"PHRASE\")]\n\n sudo_phrase: String,\n\n\n\n /// WS address of a node\n\n #[structopt(long, short, name = \"ADDRESS\")]\n\n url: String,\n\n\n\n /// Path to a file with WASM runtime.\n\n #[structopt(name = \"FILE\")]\n\n runtime: String,\n\n}\n\n\n", "file_path": "local-tests/send-runtime/src/main.rs", "rank": 66, "score": 105887.56811804717 }, { "content": "#[derive(Clone, Debug, Encode, Decode)]\n\nenum Error {\n\n SendData,\n\n}\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 67, "score": 104028.59497403848 }, { "content": "struct Peers {\n\n all_peers: HashMap<PeerId, PeerInfo>,\n\n to_peer: HashMap<SessionId, HashMap<NodeIndex, PeerId>>,\n\n}\n\n\n\nimpl Peers {\n\n fn new() -> Self {\n\n Peers {\n\n all_peers: HashMap::new(),\n\n to_peer: HashMap::new(),\n\n }\n\n }\n\n\n\n fn insert(&mut self, peer: PeerId) {\n\n self.all_peers.insert(peer, PeerInfo::new());\n\n }\n\n\n\n fn is_authenticated(&self, peer: &PeerId, session_id: &SessionId) -> bool {\n\n match self.all_peers.get(peer) {\n\n Some(info) => info.authenticated_for(session_id),\n", "file_path": "finality-aleph/src/network.rs", "rank": 68, "score": 103265.97207026735 }, { "content": " },\n\n extrinsics: vec![],\n\n }\n\n}\n\n\n\nconst GENESIS_HASH: [u8; 32] = [0u8; 32];\n\n\n\nimpl Client {\n\n pub(crate) fn new(finalized_height: u64) -> Self {\n\n let mut blocks: Vec<TBlock> = vec![];\n\n\n\n for n in 1u64..=finalized_height {\n\n let parent_hash = match n {\n\n 1 => GENESIS_HASH.into(),\n\n _ => blocks.last().unwrap().header.hash(),\n\n };\n\n blocks.push(create_block(parent_hash, n));\n\n }\n\n\n\n let next_block_to_finalize =\n", "file_path": "finality-aleph/src/testing/mocks/header_backend.rs", "rank": 69, "score": 102257.51169232244 }, { "content": "use sp_api::BlockId;\n\nuse sp_blockchain::{BlockStatus, HeaderBackend, Info};\n\nuse sp_runtime::traits::Block;\n\n\n\nuse crate::testing::mocks::{TBlock, THash, THeader, TNumber};\n\n\n\n#[derive(Clone)]\n\npub(crate) struct Client {\n\n blocks: Vec<TBlock>,\n\n next_block_to_finalize: TBlock,\n\n}\n\n\n\npub(crate) fn create_block(parent_hash: THash, number: TNumber) -> TBlock {\n\n TBlock {\n\n header: THeader {\n\n parent_hash,\n\n number,\n\n state_root: Default::default(),\n\n extrinsics_root: Default::default(),\n\n digest: Default::default(),\n", "file_path": "finality-aleph/src/testing/mocks/header_backend.rs", "rank": 70, "score": 102255.05222808824 }, { "content": " create_block(blocks.last().unwrap().hash(), finalized_height + 1);\n\n\n\n Client {\n\n blocks,\n\n next_block_to_finalize,\n\n }\n\n }\n\n\n\n pub(crate) fn next_block_to_finalize(&self) -> TBlock {\n\n self.next_block_to_finalize.clone()\n\n }\n\n\n\n pub(crate) fn get_block(&self, id: BlockId<TBlock>) -> Option<TBlock> {\n\n match id {\n\n BlockId::Hash(h) => {\n\n if self.next_block_to_finalize.hash() == h {\n\n Some(self.next_block_to_finalize.clone())\n\n } else {\n\n self.blocks.iter().find(|b| b.header.hash().eq(&h)).cloned()\n\n }\n", "file_path": "finality-aleph/src/testing/mocks/header_backend.rs", "rank": 71, "score": 102247.16833211579 }, { "content": " best_number: self.next_block_to_finalize.header.number,\n\n finalized_hash: self.blocks.last().unwrap().hash(),\n\n finalized_number: self.blocks.len() as u64,\n\n genesis_hash: GENESIS_HASH.into(),\n\n number_leaves: Default::default(),\n\n finalized_state: None,\n\n }\n\n }\n\n\n\n fn status(&self, id: BlockId<TBlock>) -> sp_blockchain::Result<BlockStatus> {\n\n Ok(match self.get_block(id) {\n\n Some(_) => BlockStatus::InChain,\n\n _ => BlockStatus::Unknown,\n\n })\n\n }\n\n\n\n fn number(&self, hash: THash) -> sp_blockchain::Result<Option<TNumber>> {\n\n Ok(self.get_block(BlockId::hash(hash)).map(|b| b.header.number))\n\n }\n\n\n\n fn hash(&self, number: TNumber) -> sp_blockchain::Result<Option<THash>> {\n\n Ok(self.get_block(BlockId::Number(number)).map(|b| b.hash()))\n\n }\n\n}\n\n\n\nunsafe impl Send for Client {}\n\n\n\nunsafe impl Sync for Client {}\n", "file_path": "finality-aleph/src/testing/mocks/header_backend.rs", "rank": 72, "score": 102245.54131753936 }, { "content": " }\n\n BlockId::Number(n) => {\n\n if self.next_block_to_finalize.header.number == n {\n\n Some(self.next_block_to_finalize.clone())\n\n } else {\n\n self.blocks.get((n - 1) as usize).cloned()\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl HeaderBackend<TBlock> for Client {\n\n fn header(&self, id: BlockId<TBlock>) -> sp_blockchain::Result<Option<THeader>> {\n\n Ok(self.get_block(id).map(|b| b.header))\n\n }\n\n\n\n fn info(&self) -> Info<TBlock> {\n\n Info {\n\n best_hash: self.next_block_to_finalize.hash(),\n", "file_path": "finality-aleph/src/testing/mocks/header_backend.rs", "rank": 73, "score": 102243.76497868724 }, { "content": "def query_runtime_version(nodes):\n\n print('Current version:')\n\n for i, node in enumerate(nodes):\n\n sys = node.rpc('system_version').result\n\n rt = node.rpc('state_getRuntimeVersion').result['specVersion']\n", "file_path": "local-tests/test_update.py", "rank": 74, "score": 102186.68881311908 }, { "content": "use sp_runtime::traits::Block;\n\n\n\nuse crate::network::RequestBlocks;\n\nuse crate::testing::mocks::single_action_mock::SingleActionMock;\n\nuse crate::testing::mocks::{TBlock, THash, TNumber};\n\n\n", "file_path": "finality-aleph/src/testing/mocks/block_request.rs", "rank": 75, "score": 102075.47421071558 }, { "content": "use sp_blockchain::Error;\n\nuse sp_runtime::traits::Block;\n\nuse sp_runtime::Justification;\n\n\n\nuse crate::finalization::BlockFinalizer;\n\nuse crate::testing::mocks::single_action_mock::SingleActionMock;\n\nuse crate::testing::mocks::{TBlock, THash, TNumber};\n\n\n", "file_path": "finality-aleph/src/testing/mocks/block_finalizer.rs", "rank": 76, "score": 102074.94707584303 }, { "content": " .has_been_invoked_with(|(hash, number, _)| {\n\n block.hash() == hash && block.header.number == number\n\n })\n\n .await\n\n }\n\n}\n\n\n\nimpl BlockFinalizer<TBlock> for MockedBlockFinalizer {\n\n fn finalize_block(\n\n &self,\n\n hash: THash,\n\n block_number: TNumber,\n\n justification: Option<Justification>,\n\n ) -> Result<(), Error> {\n\n self.mock.invoke_with((hash, block_number, justification));\n\n Ok(())\n\n }\n\n}\n", "file_path": "finality-aleph/src/testing/mocks/block_finalizer.rs", "rank": 77, "score": 102070.01438203527 }, { "content": " .has_been_invoked_with(|(hash, number)| {\n\n block.hash() == hash && block.header.number == number\n\n })\n\n .await\n\n }\n\n}\n\n\n\nimpl RequestBlocks<TBlock> for MockedBlockRequester {\n\n fn request_justification(&self, hash: &THash, number: TNumber) {\n\n self.mock.invoke_with((*hash, number))\n\n }\n\n\n\n fn request_stale_block(&self, _hash: THash, _number: TNumber) {\n\n panic!(\"`request_stale_block` not implemented!\")\n\n }\n\n}\n", "file_path": "finality-aleph/src/testing/mocks/block_request.rs", "rank": 78, "score": 102069.77021243733 }, { "content": "use std::sync::{Arc, Mutex};\n\n\n\nuse crate::justification::{AlephJustification, SessionInfo, SessionInfoProvider, Verifier};\n\nuse crate::testing::mocks::{AcceptancePolicy, TBlock, THash, TNumber};\n\nuse crate::{last_block_of_session, session_id_from_block_num, SessionPeriod};\n\n\n\npub(crate) struct VerifierWrapper {\n\n acceptance_policy: Arc<Mutex<AcceptancePolicy>>,\n\n}\n\n\n\nimpl Verifier<TBlock> for VerifierWrapper {\n\n fn verify(&self, _justification: &AlephJustification, _hash: THash) -> bool {\n\n self.acceptance_policy.lock().unwrap().accepts()\n\n }\n\n}\n\n\n\npub(crate) struct SessionInfoProviderImpl {\n\n session_period: SessionPeriod,\n\n acceptance_policy: Arc<Mutex<AcceptancePolicy>>,\n\n}\n", "file_path": "finality-aleph/src/testing/mocks/session_info.rs", "rank": 79, "score": 101867.50344748759 }, { "content": "\n\nimpl SessionInfoProviderImpl {\n\n pub(crate) fn new(session_period: SessionPeriod, acceptance_policy: AcceptancePolicy) -> Self {\n\n Self {\n\n session_period,\n\n acceptance_policy: Arc::new(Mutex::new(acceptance_policy)),\n\n }\n\n }\n\n}\n\n\n\nimpl SessionInfoProvider<TBlock, VerifierWrapper> for SessionInfoProviderImpl {\n\n fn for_block_num(&self, number: TNumber) -> SessionInfo<TBlock, VerifierWrapper> {\n\n let current_session = session_id_from_block_num::<TBlock>(number, self.session_period);\n\n SessionInfo {\n\n current_session,\n\n last_block_height: last_block_of_session::<TBlock>(\n\n current_session,\n\n self.session_period,\n\n ),\n\n verifier: match &*self.acceptance_policy.lock().unwrap() {\n\n AcceptancePolicy::Unavailable => None,\n\n _ => Some(VerifierWrapper {\n\n acceptance_policy: self.acceptance_policy.clone(),\n\n }),\n\n },\n\n }\n\n }\n\n}\n", "file_path": "finality-aleph/src/testing/mocks/session_info.rs", "rank": 80, "score": 101852.3792438254 }, { "content": "fn get_total_issuance(connection: &Connection) -> u128 {\n\n connection\n\n .get_storage_value(\"Balances\", \"TotalIssuance\", None)\n\n .unwrap()\n\n .unwrap()\n\n}\n\n\n", "file_path": "e2e-tests/src/test/treasury.rs", "rank": 81, "score": 101852.37130939607 }, { "content": "#[derive(Debug)]\n\nstruct PeerInfo {\n\n authentications: HashMap<SessionId, NodeIndex>,\n\n}\n\n\n\nimpl PeerInfo {\n\n fn new() -> Self {\n\n PeerInfo {\n\n authentications: HashMap::new(),\n\n }\n\n }\n\n\n\n fn authenticated_for(&self, session_id: &SessionId) -> bool {\n\n self.authentications.get(session_id).is_some()\n\n }\n\n\n\n fn authenticate(&mut self, session_id: SessionId, node_id: NodeIndex) {\n\n self.authentications.insert(session_id, node_id);\n\n }\n\n\n\n fn iter(&self) -> impl Iterator<Item = (&SessionId, &NodeIndex)> {\n\n self.authentications.iter()\n\n }\n\n\n\n fn remove_session(&mut self, session_id: &SessionId) {\n\n self.authentications.remove(session_id);\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/network.rs", "rank": 82, "score": 101257.4264180201 }, { "content": "use std::sync::{Arc, Mutex};\n\nuse std::time::Duration;\n\n\n\nuse crate::justification::{JustificationHandlerConfig, JustificationRequestDelay};\n\nuse crate::testing::mocks::single_action_mock::SingleActionMock;\n\nuse crate::testing::mocks::{AcceptancePolicy, TBlock};\n\n\n\n#[derive(Clone)]\n\npub(crate) struct JustificationRequestDelayImpl {\n\n acceptance_policy: Arc<Mutex<AcceptancePolicy>>,\n\n fin_reporter: SingleActionMock<()>,\n\n req_reporter: SingleActionMock<()>,\n\n}\n\n\n\nimpl JustificationRequestDelayImpl {\n\n pub(crate) fn new(acceptance_policy: AcceptancePolicy) -> Self {\n\n Self {\n\n acceptance_policy: Arc::new(Mutex::new(acceptance_policy)),\n\n fin_reporter: Default::default(),\n\n req_reporter: Default::default(),\n", "file_path": "finality-aleph/src/testing/mocks/justification_handler_config.rs", "rank": 83, "score": 99391.51001563837 }, { "content": "\n\n fn on_block_finalized(&mut self) {\n\n self.fin_reporter.invoke_with(());\n\n }\n\n\n\n fn on_request_sent(&mut self) {\n\n self.req_reporter.invoke_with(());\n\n }\n\n}\n\n\n\nconst DEFAULT_VERIFIER_TIMEOUT_MS: u64 = 10u64;\n\nconst DEFAULT_NOTIFICATION_TIMEOUT_MS: u64 = 10u64;\n\n\n\nimpl JustificationHandlerConfig<TBlock, JustificationRequestDelayImpl> {\n\n pub(crate) fn new(request_policy: AcceptancePolicy) -> Self {\n\n JustificationHandlerConfig {\n\n justification_request_delay: JustificationRequestDelayImpl::new(request_policy),\n\n metrics: None,\n\n verifier_timeout: Duration::from_millis(DEFAULT_VERIFIER_TIMEOUT_MS),\n\n notification_timeout: Duration::from_millis(DEFAULT_NOTIFICATION_TIMEOUT_MS),\n", "file_path": "finality-aleph/src/testing/mocks/justification_handler_config.rs", "rank": 84, "score": 99388.22276448678 }, { "content": " }\n\n }\n\n\n\n pub(crate) fn update_policy(&self, policy: AcceptancePolicy) {\n\n *self.acceptance_policy.lock().unwrap() = policy;\n\n }\n\n\n\n pub(crate) async fn has_been_finalized(&self) -> bool {\n\n self.fin_reporter.has_been_invoked_with(|_| true).await\n\n }\n\n\n\n pub(crate) async fn has_been_requested(&self) -> bool {\n\n self.req_reporter.has_been_invoked_with(|_| true).await\n\n }\n\n}\n\n\n\nimpl JustificationRequestDelay for JustificationRequestDelayImpl {\n\n fn can_request_now(&self) -> bool {\n\n self.acceptance_policy.lock().unwrap().accepts()\n\n }\n", "file_path": "finality-aleph/src/testing/mocks/justification_handler_config.rs", "rank": 85, "score": 99380.3348123439 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl Clone for JustificationHandlerConfig<TBlock, JustificationRequestDelayImpl> {\n\n fn clone(&self) -> Self {\n\n Self {\n\n justification_request_delay: self.justification_request_delay.clone(),\n\n metrics: self.metrics.clone(),\n\n verifier_timeout: self.verifier_timeout,\n\n notification_timeout: self.notification_timeout,\n\n }\n\n }\n\n}\n", "file_path": "finality-aleph/src/testing/mocks/justification_handler_config.rs", "rank": 86, "score": 99378.46913869328 }, { "content": "type KeyPair = sr25519::Pair;\n", "file_path": "e2e-tests/src/lib.rs", "rank": 87, "score": 98474.75346488884 }, { "content": "struct LeftNetwork<\n\n LeftData: Data,\n\n RightData: Data,\n\n S: SenderComponent<Split<LeftData, RightData>>,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n> {\n\n sender: LeftSender<LeftData, RightData, S>,\n\n receiver: Arc<Mutex<LeftReceiver<LeftData, RightData, R>>>,\n\n}\n\n\n\nimpl<\n\n LeftData: Data,\n\n RightData: Data,\n\n S: SenderComponent<Split<LeftData, RightData>>,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n > ComponentNetwork<LeftData> for LeftNetwork<LeftData, RightData, S, R>\n\n{\n\n type S = LeftSender<LeftData, RightData, S>;\n\n type R = LeftReceiver<LeftData, RightData, R>;\n\n fn sender(&self) -> &Self::S {\n\n &self.sender\n\n }\n\n fn receiver(&self) -> Arc<Mutex<Self::R>> {\n\n self.receiver.clone()\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/new_network/split.rs", "rank": 88, "score": 97565.51698363898 }, { "content": "struct RightNetwork<\n\n LeftData: Data,\n\n RightData: Data,\n\n S: SenderComponent<Split<LeftData, RightData>>,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n> {\n\n sender: RightSender<LeftData, RightData, S>,\n\n receiver: Arc<Mutex<RightReceiver<LeftData, RightData, R>>>,\n\n}\n\n\n\nimpl<\n\n LeftData: Data,\n\n RightData: Data,\n\n S: SenderComponent<Split<LeftData, RightData>>,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n > ComponentNetwork<RightData> for RightNetwork<LeftData, RightData, S, R>\n\n{\n\n type S = RightSender<LeftData, RightData, S>;\n\n type R = RightReceiver<LeftData, RightData, R>;\n\n fn sender(&self) -> &Self::S {\n\n &self.sender\n\n }\n\n fn receiver(&self) -> Arc<Mutex<Self::R>> {\n\n self.receiver.clone()\n\n }\n\n}\n\n\n", "file_path": "finality-aleph/src/new_network/split.rs", "rank": 89, "score": 97565.51698363898 }, { "content": "struct RightReceiver<\n\n LeftData: Data,\n\n RightData: Data,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n> {\n\n receiver: Arc<Mutex<R>>,\n\n translated_receiver: mpsc::UnboundedReceiver<RightData>,\n\n left_sender: mpsc::UnboundedSender<LeftData>,\n\n right_sender: mpsc::UnboundedSender<RightData>,\n\n}\n\n\n\nasync fn forward_or_wait<\n\n LeftData: Data,\n\n RightData: Data,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n>(\n\n receiver: &Arc<Mutex<R>>,\n\n left_sender: &mpsc::UnboundedSender<LeftData>,\n\n right_sender: &mpsc::UnboundedSender<RightData>,\n\n) {\n", "file_path": "finality-aleph/src/new_network/split.rs", "rank": 90, "score": 97565.51698363898 }, { "content": "struct LeftReceiver<\n\n LeftData: Data,\n\n RightData: Data,\n\n R: ReceiverComponent<Split<LeftData, RightData>>,\n\n> {\n\n receiver: Arc<Mutex<R>>,\n\n translated_receiver: mpsc::UnboundedReceiver<LeftData>,\n\n left_sender: mpsc::UnboundedSender<LeftData>,\n\n right_sender: mpsc::UnboundedSender<RightData>,\n\n}\n\n\n", "file_path": "finality-aleph/src/new_network/split.rs", "rank": 91, "score": 97565.51698363898 }, { "content": "pub trait ClientForAleph<B, BE>:\n\n LockImportRun<B, BE>\n\n + Finalizer<B, BE>\n\n + ProvideRuntimeApi<B>\n\n + BlockImport<B, Transaction = TransactionFor<BE, B>, Error = sp_consensus::Error>\n\n + HeaderBackend<B>\n\n + HeaderMetadata<B, Error = sp_blockchain::Error>\n\n + BlockchainEvents<B>\n\nwhere\n\n BE: Backend<B>,\n\n B: Block,\n\n{\n\n}\n\n\n\nimpl<B, BE, T> ClientForAleph<B, BE> for T\n\nwhere\n\n BE: Backend<B>,\n\n B: Block,\n\n T: LockImportRun<B, BE>\n\n + Finalizer<B, BE>\n\n + ProvideRuntimeApi<B>\n\n + HeaderBackend<B>\n\n + HeaderMetadata<B, Error = sp_blockchain::Error>\n\n + BlockchainEvents<B>\n\n + BlockImport<B, Transaction = TransactionFor<BE, B>, Error = sp_consensus::Error>,\n\n{\n\n}\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 92, "score": 97266.35631251987 }, { "content": "pub fn exponential_slowdown(\n\n t: usize,\n\n base_delay: f64,\n\n start_exp_delay: usize,\n\n exp_base: f64,\n\n) -> Duration {\n\n // This gives:\n\n // base_delay, for t <= start_exp_delay,\n\n // base_delay * exp_base^(t - start_exp_delay), for t > start_exp_delay.\n\n let delay = if t < start_exp_delay {\n\n base_delay\n\n } else {\n\n let power = t - start_exp_delay;\n\n base_delay * exp_base.powf(power as f64)\n\n };\n\n let delay = delay.round() as u64;\n\n // the above will make it u64::MAX if it exceeds u64\n\n Duration::from_millis(delay)\n\n}\n\n\n\n// TODO: :(\n\n#[cfg(test)]\n\nmod tests {}\n", "file_path": "finality-aleph/src/party.rs", "rank": 93, "score": 95576.14756612838 }, { "content": "enum UniquePeerId {\n\n Unique(PeerId),\n\n NotUnique,\n\n Unknown,\n\n}\n\n\n\nimpl UniquePeerId {\n\n fn into_option(self) -> Option<PeerId> {\n\n use UniquePeerId::*;\n\n match self {\n\n Unique(peer_id) => Some(peer_id),\n\n _ => None,\n\n }\n\n }\n\n\n\n fn accumulate(self, maybe_peer_id: Option<PeerId>) -> UniquePeerId {\n\n use UniquePeerId::*;\n\n match self {\n\n Unique(old_peer_id) => match maybe_peer_id {\n\n Some(peer_id) => {\n", "file_path": "finality-aleph/src/new_network/manager/addresses.rs", "rank": 94, "score": 94990.86967443867 }, { "content": "#!/bin/env python\n\nimport os\n\nimport subprocess\n\nfrom os.path import join\n\nfrom time import sleep\n\n\n\nfrom chainrunner import Chain, Seq, generate_keys\n\n\n\n# Path to working directory, where chainspec, logs and nodes' dbs are written:\n\nworkdir = os.getenv('WORKDIR', '/tmp/workdir')\n\n# Path to the pre-update aleph-node binary:\n\noldbin = os.getenv('OLD_BINARY', join(workdir, 'aleph-node-old'))\n\n# Path to the post-update aleph-node binary:\n\nnewbin = os.getenv('NEW_BINARY', join(workdir, 'aleph-node-new'))\n\n# Path to the post-update compiled runtime:\n\nruntime = os.getenv('NEW_RUNTIME', join(workdir, 'aleph_runtime.compact.wasm'))\n\n# Path to the send-runtime binary (which lives in aleph-node/local-tests/send-runtime):\n\nSEND_RUNTIME = 'send-runtime/target/release/send_runtime'\n\n\n\n\n\ndef query_runtime_version(nodes):\n\n print('Current version:')\n\n for i, node in enumerate(nodes):\n\n sys = node.rpc('system_version').result\n\n rt = node.rpc('state_getRuntimeVersion').result['specVersion']\n\n print(f' Node {i}: system: {sys} runtime: {rt}')\n\n\n\n\n\ndef check_highest(nodes):\n\n results = [node.highest_block() for node in nodes]\n\n highest, finalized = zip(*results)\n\n print('Blocks seen by nodes:')\n\n print(' Highest: ', *highest)\n\n print(' Finalized: ', *finalized)\n\n\n\n\n\nphrases = ['//Cartman', '//Stan', '//Kyle', '//Kenny']\n\nkeys = generate_keys(newbin, phrases)\n\n\n\nchain = Chain(workdir)\n\nprint('Bootstraping the chain with old binary')\n\nchain.bootstrap(oldbin,\n\n keys.values(),\n\n sudo_account_id=keys[phrases[0]],\n\n chain_type='local',\n\n millisecs_per_block=2000,\n\n session_period=40)\n\n\n\nchain.set_flags('validator',\n\n port=Seq(30334),\n\n ws_port=Seq(9944),\n\n rpc_port=Seq(9933),\n\n unit_creation_delay=200,\n\n execution='Native')\n\n\n\nprint('Starting the chain with old binary')\n\nchain.start('old')\n\n\n\nprint('Waiting a minute')\n\nsleep(60)\n\n\n\ncheck_highest(chain)\n\nquery_runtime_version(chain)\n\n\n\nprint('Killing node 3 and deleting its database')\n\nchain[3].stop() # OH MY GOD THEY KILLED KENNY!\n\nchain[3].purge()\n\n\n\nprint('Restarting node 3 with new binary')\n\nchain[3].binary = newbin\n\nchain[3].start('new3')\n\n\n\nprint('Waiting a minute')\n\nsleep(60)\n\n\n\ncheck_highest(chain)\n\nquery_runtime_version(chain)\n\n\n\nprint('Submitting extrinsic with new runtime')\n\nsubprocess.check_call(\n\n [SEND_RUNTIME, '--url', 'localhost:9945', '--sudo-phrase', phrases[0], runtime])\n\n\n\nprint('Waiting a bit')\n\nsleep(15)\n\n\n\ncheck_highest(chain)\n\nquery_runtime_version(chain)\n\n\n\nprint('Restarting remaining nodes with new binary')\n\nchain.stop(nodes=[0, 1, 2])\n\nchain.set_binary(newbin, nodes=[0, 1, 2])\n\nchain.start('new', nodes=[0, 1, 2])\n\n\n\nprint('Waiting a minute')\n\nsleep(60)\n\n\n\ncheck_highest(chain)\n\nquery_runtime_version(chain)\n\n\n\nprint('Stopping the chain')\n\nchain.stop()\n\n\n\nhf = min(node.highest_block()[1] for node in chain)\n\nprint(f'Sanity check: the highest finalized block is {hf}. '\n\n f'Comparing exported states after that block:')\n\nif chain[0].state(hf) == chain[1].state(hf) == chain[2].state(hf) == chain[3].state(hf):\n\n print(\"The same :)\")\n\nelse:\n\n print(\"DIFFERENT!\")\n", "file_path": "local-tests/test_update.py", "rank": 95, "score": 94946.3720129386 }, { "content": "type Channel<T> = (\n\n Arc<Mutex<mpsc::UnboundedSender<T>>>,\n\n Arc<Mutex<mpsc::UnboundedReceiver<T>>>,\n\n);\n\n\n", "file_path": "finality-aleph/src/new_network/mock.rs", "rank": 96, "score": 94582.75918351741 }, { "content": " def highest_block(self):\n\n \"\"\"Find in the logs the height of the most recent block.\n\n Returns two ints: highest block and highest finalized block.\"\"\"\n\n results = self.greplog(r'best: #(\\d+) .+ finalized #(\\d+)')\n\n if results:\n\n a, b = results[-1]\n\n return int(a), int(b)\n", "file_path": "local-tests/chainrunner/node.py", "rank": 97, "score": 94219.95778269852 }, { "content": "struct Inner<H: Key> {\n\n prev: HashMap<Checkpoint, Checkpoint>,\n\n gauges: HashMap<Checkpoint, Gauge<U64>>,\n\n starts: HashMap<Checkpoint, LruCache<H, Instant>>,\n\n}\n\n\n\nimpl<H: Key> Inner<H> {\n\n fn report_block(&mut self, hash: H, checkpoint_time: Instant, checkpoint_type: Checkpoint) {\n\n trace!(target: \"afa\", \"Reporting block stage: {:?} (hash: {:?}, at: {:?}\", checkpoint_type, hash, checkpoint_time);\n\n\n\n self.starts.entry(checkpoint_type).and_modify(|starts| {\n\n starts.put(hash, checkpoint_time);\n\n });\n\n\n\n if let Some(prev_checkpoint_type) = self.prev.get(&checkpoint_type) {\n\n if let Some(start) = self\n\n .starts\n\n .get_mut(prev_checkpoint_type)\n\n .expect(\"All checkpoint types were initialized\")\n\n .get(&hash)\n", "file_path": "finality-aleph/src/metrics.rs", "rank": 98, "score": 93952.24844678293 }, { "content": "#[derive(Clone)]\n\nstruct SpawnHandle(SpawnTaskHandle);\n\n\n\nimpl From<SpawnTaskHandle> for SpawnHandle {\n\n fn from(sth: SpawnTaskHandle) -> Self {\n\n SpawnHandle(sth)\n\n }\n\n}\n\n\n\nimpl aleph_bft::SpawnHandle for SpawnHandle {\n\n fn spawn(&self, name: &'static str, task: impl Future<Output = ()> + Send + 'static) {\n\n self.0.spawn(name, task)\n\n }\n\n\n\n fn spawn_essential(\n\n &self,\n\n name: &'static str,\n\n task: impl Future<Output = ()> + Send + 'static,\n\n ) -> TaskHandle {\n\n let (tx, rx) = oneshot::channel();\n\n self.spawn(name, async move {\n\n task.await;\n\n let _ = tx.send(());\n\n });\n\n Box::pin(rx.map_err(|_| ()))\n\n }\n\n}\n\n\n\npub type SessionMap = HashMap<SessionId, Vec<AuthorityId>>;\n\n\n", "file_path": "finality-aleph/src/lib.rs", "rank": 99, "score": 92918.47514658366 } ]
Rust
src/systems/collision.rs
Jazarro/space-menace
8be706d2e993d594557ec3f88d5ac2d331b955d7
use amethyst::{ core::{math::Vector2, Named, Transform}, ecs::{Entities, Join, LazyUpdate, ReadExpect, ReadStorage, System, WriteStorage}, }; use crate::{ components::{ Boundary, Bullet, Collidee, CollideeDetails, Collider, Direction, Directions, Flier, FlierAi, Marine, Motion, Pincer, PincerAi, }, entities::{show_bullet_impact, show_explosion}, resources::{AssetType, Context, PrefabList}, }; pub struct CollisionSystem; impl<'s> System<'s> for CollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Collider>, WriteStorage<'s, Collidee>, ReadStorage<'s, Boundary>, ReadStorage<'s, Motion>, ReadStorage<'s, Named>, ); fn run(&mut self, data: Self::SystemData) { let (entities, colliders, mut collidees, boundaries, motions, names) = data; for (entity_a, collider_a, collidee, boundary, motion_a) in (&entities, &colliders, &mut collidees, &boundaries, &motions).join() { let velocity_a = motion_a.velocity; let bbox_a = &collider_a.bounding_box; let position_a_x = bbox_a.position.x; let half_size_a_x = bbox_a.half_size.x; let correction; if velocity_a.x != 0. || velocity_a.y != 0. && collider_a.is_collidable { for (entity_b, collider_b, motion_b, name_b) in (&entities, &colliders, &motions, &names).join() { let velocity_b = motion_b.velocity; let use_hit_box = (velocity_a.x * velocity_b.x != 0.) || (velocity_a.y * velocity_b.y != 0.); if entity_a != entity_b && collider_a.is_overlapping_with(collider_b, use_hit_box) { collidee.set_collidee_details( name_b.name.to_string(), collider_a, collider_b, velocity_a, velocity_b, use_hit_box, ); } } } correction = if (position_a_x - half_size_a_x) <= boundary.left { (position_a_x - half_size_a_x) - boundary.left } else if (position_a_x + half_size_a_x) >= boundary.right { (position_a_x + half_size_a_x) - boundary.right } else { 0. }; if correction != 0. { collidee.horizontal = Some(CollideeDetails { name: String::from("Boundary"), position: Vector2::new(0., 0.), half_size: Vector2::new(0., 0.), correction, }); } } } } pub struct PincerCollisionSystem; impl<'s> System<'s> for PincerCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Marine>, WriteStorage<'s, Pincer>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadStorage<'s, Transform>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, marines, mut pincers, collidees, mut dirs, mut motions, prefab_list, transforms, lazy_update, ctx, ) = data; let marine_opt = (&entities, &marines) .join() .map(|(entity, _)| entity) .next(); for (entity, pincer, collidee, dir, motion, transform) in ( &*entities, &mut pincers, &collidees, &mut dirs, &mut motions, &transforms, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => { pincer.ai = PincerAi::Patrolling; motion.velocity.x *= -1.; dir.set_x_velocity(motion.velocity.x); } "Bullet" => { if let Some(marine) = marine_opt { pincer.ai = PincerAi::Attacking { target: marine }; } pincer.hit_count += 1; if pincer.hit_count == 4 { let small_explosion_prefab_handle = { prefab_list.get(AssetType::SmallExplosion).unwrap().clone() }; let pincer_translation = transform.translation(); show_explosion( &entities, small_explosion_prefab_handle, pincer_translation.x, pincer_translation.y, &lazy_update, &ctx, ); let _ = entities.delete(entity); } } _ => {} } } } } } pub struct FlierCollisionSystem; impl<'s> System<'s> for FlierCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Marine>, WriteStorage<'s, Flier>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadStorage<'s, Transform>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, marines, mut fliers, collidees, mut dirs, mut motions, prefab_list, transforms, lazy_update, ctx, ) = data; let marine_opt = (&entities, &marines) .join() .map(|(entity, _)| entity) .next(); for (entity, flier, collidee, dir, motion, transform) in ( &*entities, &mut fliers, &collidees, &mut dirs, &mut motions, &transforms, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => { flier.ai = FlierAi::Patrolling; motion.velocity.x *= -1.; dir.set_x_velocity(motion.velocity.x); } "Bullet" => { if let Some(marine) = marine_opt { flier.ai = FlierAi::Attacking { target: marine }; } flier.hit_count += 1; if flier.hit_count == 6 { let small_explosion_prefab_handle = { prefab_list.get(AssetType::SmallExplosion).unwrap().clone() }; let flier_translation = transform.translation(); show_explosion( &entities, small_explosion_prefab_handle, flier_translation.x, flier_translation.y, &lazy_update, &ctx, ); let _ = entities.delete(entity); } } _ => {} } } } } } pub struct BulletCollisionSystem; impl<'s> System<'s> for BulletCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Bullet>, ReadStorage<'s, Collider>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, bullets, colliders, collidees, mut dirs, mut motions, prefab_list, lazy_update, ctx, ) = data; for (entity, _, collider, collidee, dir, motion) in ( &*entities, &bullets, &colliders, &collidees, &mut dirs, &mut motions, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => {} _ => { let bullet_impact_prefab_handle = { prefab_list.get(AssetType::BulletImpact).unwrap().clone() }; let impact_position_x = match dir.x { Directions::Right => { collidee_horizontal.position.x - collidee_horizontal.half_size.x } Directions::Left => { collidee_horizontal.position.x + collidee_horizontal.half_size.x } _ => 0., }; show_bullet_impact( &entities, bullet_impact_prefab_handle, impact_position_x, collider.bounding_box.position.y, motion.velocity.x, &lazy_update, &ctx, ); } } let _ = entities.delete(entity); } } } } pub struct MarineCollisionSystem; impl<'s> System<'s> for MarineCollisionSystem { type SystemData = ( ReadStorage<'s, Marine>, WriteStorage<'s, Collider>, ReadStorage<'s, Collidee>, ); fn run(&mut self, data: Self::SystemData) { let (marines, mut colliders, collidees) = data; for (_, collider, collidee) in (&marines, &mut colliders, &collidees).join() { if let Some(collidee_horizontal) = &collidee.horizontal { if let "Pincer" = collidee_horizontal.name.as_ref() { collider.is_collidable = false; } if let "Flier" = collidee_horizontal.name.as_ref() { collider.is_collidable = false; } } } } }
use amethyst::{ core::{math::Vector2, Named, Transform}, ecs::{Entities, Join, LazyUpdate, ReadExpect, ReadStorage, System, WriteStorage}, }; use crate::{ components::{ Boundary, Bullet, Collidee, CollideeDetails, Collider, Direction, Directions, Flier, FlierAi, Marine, Motion, Pincer, PincerAi, }, entities::{show_bullet_impact, show_explosion}, resources::{AssetType, Context, PrefabList}, }; pub struct CollisionSystem; impl<'s> System<'s> for CollisionSystem {
ider_a.is_collidable { for (entity_b, collider_b, motion_b, name_b) in (&entities, &colliders, &motions, &names).join() { let velocity_b = motion_b.velocity; let use_hit_box = (velocity_a.x * velocity_b.x != 0.) || (velocity_a.y * velocity_b.y != 0.); if entity_a != entity_b && collider_a.is_overlapping_with(collider_b, use_hit_box) { collidee.set_collidee_details( name_b.name.to_string(), collider_a, collider_b, velocity_a, velocity_b, use_hit_box, ); } } } correction = if (position_a_x - half_size_a_x) <= boundary.left { (position_a_x - half_size_a_x) - boundary.left } else if (position_a_x + half_size_a_x) >= boundary.right { (position_a_x + half_size_a_x) - boundary.right } else { 0. }; if correction != 0. { collidee.horizontal = Some(CollideeDetails { name: String::from("Boundary"), position: Vector2::new(0., 0.), half_size: Vector2::new(0., 0.), correction, }); } } } } pub struct PincerCollisionSystem; impl<'s> System<'s> for PincerCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Marine>, WriteStorage<'s, Pincer>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadStorage<'s, Transform>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, marines, mut pincers, collidees, mut dirs, mut motions, prefab_list, transforms, lazy_update, ctx, ) = data; let marine_opt = (&entities, &marines) .join() .map(|(entity, _)| entity) .next(); for (entity, pincer, collidee, dir, motion, transform) in ( &*entities, &mut pincers, &collidees, &mut dirs, &mut motions, &transforms, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => { pincer.ai = PincerAi::Patrolling; motion.velocity.x *= -1.; dir.set_x_velocity(motion.velocity.x); } "Bullet" => { if let Some(marine) = marine_opt { pincer.ai = PincerAi::Attacking { target: marine }; } pincer.hit_count += 1; if pincer.hit_count == 4 { let small_explosion_prefab_handle = { prefab_list.get(AssetType::SmallExplosion).unwrap().clone() }; let pincer_translation = transform.translation(); show_explosion( &entities, small_explosion_prefab_handle, pincer_translation.x, pincer_translation.y, &lazy_update, &ctx, ); let _ = entities.delete(entity); } } _ => {} } } } } } pub struct FlierCollisionSystem; impl<'s> System<'s> for FlierCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Marine>, WriteStorage<'s, Flier>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadStorage<'s, Transform>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, marines, mut fliers, collidees, mut dirs, mut motions, prefab_list, transforms, lazy_update, ctx, ) = data; let marine_opt = (&entities, &marines) .join() .map(|(entity, _)| entity) .next(); for (entity, flier, collidee, dir, motion, transform) in ( &*entities, &mut fliers, &collidees, &mut dirs, &mut motions, &transforms, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => { flier.ai = FlierAi::Patrolling; motion.velocity.x *= -1.; dir.set_x_velocity(motion.velocity.x); } "Bullet" => { if let Some(marine) = marine_opt { flier.ai = FlierAi::Attacking { target: marine }; } flier.hit_count += 1; if flier.hit_count == 6 { let small_explosion_prefab_handle = { prefab_list.get(AssetType::SmallExplosion).unwrap().clone() }; let flier_translation = transform.translation(); show_explosion( &entities, small_explosion_prefab_handle, flier_translation.x, flier_translation.y, &lazy_update, &ctx, ); let _ = entities.delete(entity); } } _ => {} } } } } } pub struct BulletCollisionSystem; impl<'s> System<'s> for BulletCollisionSystem { type SystemData = ( Entities<'s>, ReadStorage<'s, Bullet>, ReadStorage<'s, Collider>, ReadStorage<'s, Collidee>, WriteStorage<'s, Direction>, WriteStorage<'s, Motion>, ReadExpect<'s, PrefabList>, ReadExpect<'s, LazyUpdate>, ReadExpect<'s, Context>, ); fn run(&mut self, data: Self::SystemData) { let ( entities, bullets, colliders, collidees, mut dirs, mut motions, prefab_list, lazy_update, ctx, ) = data; for (entity, _, collider, collidee, dir, motion) in ( &*entities, &bullets, &colliders, &collidees, &mut dirs, &mut motions, ) .join() { if let Some(collidee_horizontal) = &collidee.horizontal { match collidee_horizontal.name.as_ref() { "Boundary" => {} _ => { let bullet_impact_prefab_handle = { prefab_list.get(AssetType::BulletImpact).unwrap().clone() }; let impact_position_x = match dir.x { Directions::Right => { collidee_horizontal.position.x - collidee_horizontal.half_size.x } Directions::Left => { collidee_horizontal.position.x + collidee_horizontal.half_size.x } _ => 0., }; show_bullet_impact( &entities, bullet_impact_prefab_handle, impact_position_x, collider.bounding_box.position.y, motion.velocity.x, &lazy_update, &ctx, ); } } let _ = entities.delete(entity); } } } } pub struct MarineCollisionSystem; impl<'s> System<'s> for MarineCollisionSystem { type SystemData = ( ReadStorage<'s, Marine>, WriteStorage<'s, Collider>, ReadStorage<'s, Collidee>, ); fn run(&mut self, data: Self::SystemData) { let (marines, mut colliders, collidees) = data; for (_, collider, collidee) in (&marines, &mut colliders, &collidees).join() { if let Some(collidee_horizontal) = &collidee.horizontal { if let "Pincer" = collidee_horizontal.name.as_ref() { collider.is_collidable = false; } if let "Flier" = collidee_horizontal.name.as_ref() { collider.is_collidable = false; } } } } }
type SystemData = ( Entities<'s>, ReadStorage<'s, Collider>, WriteStorage<'s, Collidee>, ReadStorage<'s, Boundary>, ReadStorage<'s, Motion>, ReadStorage<'s, Named>, ); fn run(&mut self, data: Self::SystemData) { let (entities, colliders, mut collidees, boundaries, motions, names) = data; for (entity_a, collider_a, collidee, boundary, motion_a) in (&entities, &colliders, &mut collidees, &boundaries, &motions).join() { let velocity_a = motion_a.velocity; let bbox_a = &collider_a.bounding_box; let position_a_x = bbox_a.position.x; let half_size_a_x = bbox_a.half_size.x; let correction; if velocity_a.x != 0. || velocity_a.y != 0. && coll
random
[ { "content": "pub fn load_marine(world: &mut World, prefab: Handle<Prefab<AnimationPrefabData>>, ctx: &Context) {\n\n let scale = ctx.scale;\n\n let mut transform = Transform::default();\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n transform.set_translation_x(384.);\n\n transform.set_translation_y(176.);\n\n\n\n let mut collider = Collider::new(32. * scale, 36. * scale);\n\n let bbox = &mut collider.bounding_box;\n\n bbox.position = Vector2::new(384., 176.);\n\n bbox.old_position = bbox.position;\n\n\n\n let motion = Motion::new();\n\n collider.set_hit_box_position(motion.velocity);\n\n\n\n world\n\n .create_entity()\n\n .with(Marine::new())\n\n .named(\"Marine\")\n\n .with(collider)\n", "file_path": "src/entities/marine.rs", "rank": 0, "score": 72904.0228789914 }, { "content": "pub fn load_flier(world: &mut World, prefab: Handle<Prefab<AnimationPrefabData>>, ctx: &Context) {\n\n // wing offset\n\n let flier_sprite_x_offset = 22.;\n\n // reduce the width of the flier to compensate of the extra width of the wings\n\n let flier_width = 54. - flier_sprite_x_offset;\n\n let flier_height = 64.;\n\n\n\n let flier_start_x_pos = 1800.;\n\n let flier_start_y_pos = 156.;\n\n let mut transform = Transform::default();\n\n let scale = ctx.scale;\n\n println!(\"load_flier: scale = {}\", scale);\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n\n\n let mut collider = Collider::new(flier_width * scale, flier_height * scale);\n\n\n\n // adjust the x offset to compensate for the reduction of width\n\n collider.hit_box_offset.x = flier_sprite_x_offset;\n\n\n\n let bbox = &mut collider.bounding_box;\n", "file_path": "src/entities/flier.rs", "rank": 1, "score": 72741.53916821015 }, { "content": "pub fn load_pincer(world: &mut World, prefab: Handle<Prefab<AnimationPrefabData>>, ctx: &Context) {\n\n let mut transform = Transform::default();\n\n let scale = ctx.scale;\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n\n\n let mut collider = Collider::new(40. * scale, 30. * scale);\n\n\n\n collider.hit_box = GenericBox::new(40. * scale - 30., 30. * scale);\n\n collider.hit_box_offset.x = 15.;\n\n\n\n let bbox = &mut collider.bounding_box;\n\n bbox.position = Vector2::new(1040., 16.);\n\n bbox.old_position = bbox.position;\n\n\n\n transform.set_translation_x(1040.);\n\n transform.set_translation_y(16.);\n\n\n\n let mut motion = Motion::new();\n\n motion.velocity.x = -3.;\n\n collider.set_hit_box_position(motion.velocity);\n", "file_path": "src/entities/pincer.rs", "rank": 2, "score": 72741.53916821015 }, { "content": "pub fn spawn_bullet(\n\n entities: &Entities,\n\n sprite_sheet_handle: SpriteSheetHandle,\n\n shoot_start_position: f32,\n\n marine_dir: &Direction,\n\n marine_bottom: f32,\n\n lazy_update: &ReadExpect<LazyUpdate>,\n\n ctx: &Context,\n\n) {\n\n let bullet_entity: Entity = entities.create();\n\n let scale = ctx.scale;\n\n\n\n let mut transform = Transform::default();\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n\n\n let sprite_render = SpriteRender {\n\n sprite_sheet: sprite_sheet_handle,\n\n sprite_number: 0,\n\n };\n\n let mut motion = Motion::new();\n", "file_path": "src/entities/bullet.rs", "rank": 3, "score": 66531.05634588771 }, { "content": "pub fn show_bullet_impact(\n\n entities: &Entities,\n\n prefab_handle: Handle<Prefab<AnimationPrefabData>>,\n\n impact_position: f32,\n\n bullet_position_y: f32,\n\n bullet_velocity: f32,\n\n lazy_update: &ReadExpect<LazyUpdate>,\n\n ctx: &Context,\n\n) {\n\n let bullet_impact_entity: Entity = entities.create();\n\n let scale = ctx.scale;\n\n\n\n let mut direction = Direction::new(\n\n Directions::Right,\n\n Directions::Neutral,\n\n Directions::Neutral,\n\n Directions::Neutral,\n\n );\n\n\n\n let impact_position_x = if bullet_velocity > 0. {\n", "file_path": "src/entities/bullet.rs", "rank": 4, "score": 64491.874428542375 }, { "content": "use amethyst::{\n\n core::math::Vector2,\n\n ecs::{Component, DenseVecStorage},\n\n};\n\n\n\nuse crate::components::{Direction, Directions};\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Motion {\n\n pub velocity: Vector2<f32>,\n\n pub has_jumped: bool,\n\n}\n\n\n\nimpl Motion {\n\n pub fn new() -> Self {\n\n Motion {\n\n velocity: Vector2::new(0., 0.),\n\n has_jumped: false,\n\n }\n", "file_path": "src/components/motion.rs", "rank": 5, "score": 56450.3331346131 }, { "content": " }\n\n\n\n pub fn update_velocity(\n\n &mut self,\n\n acceleration: Vector2<f32>,\n\n dir: &Direction,\n\n min_limit: f32,\n\n max_limit: f32,\n\n ) {\n\n match dir.x {\n\n Directions::Right => {\n\n self.velocity.x += acceleration.x;\n\n if acceleration.x <= 0. {\n\n self.velocity.x = self.velocity.x.max(min_limit);\n\n } else {\n\n self.velocity.x = self.velocity.x.min(max_limit);\n\n }\n\n }\n\n Directions::Left => {\n\n self.velocity.x -= acceleration.x;\n", "file_path": "src/components/motion.rs", "rank": 6, "score": 56433.55557480934 }, { "content": " if acceleration.x <= 0. {\n\n self.velocity.x = self.velocity.x.min(-min_limit);\n\n } else {\n\n self.velocity.x = self.velocity.x.max(-max_limit);\n\n }\n\n }\n\n _ => {}\n\n }\n\n self.velocity.y += acceleration.y;\n\n }\n\n}\n", "file_path": "src/components/motion.rs", "rank": 7, "score": 56428.05430328424 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage};\n\n\n\n#[derive(Eq, Hash, PartialEq, Clone, Copy)]\n\npub enum MarineState {\n\n Dying,\n\n Idling,\n\n Jumping,\n\n Running,\n\n Shooting,\n\n}\n\n\n\nimpl Default for MarineState {\n\n fn default() -> Self {\n\n MarineState::Idling\n\n }\n\n}\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Marine {\n", "file_path": "src/components/marine.rs", "rank": 8, "score": 56369.64356626247 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage};\n\n\n\n// Remove this allow annotation when the Up and Down variants are taken in use.\n\n#[allow(dead_code)]\n\n#[derive(PartialEq, Clone, Copy)]\n\npub enum Directions {\n\n Right,\n\n Left,\n\n Up,\n\n Down,\n\n Neutral,\n\n}\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Direction {\n\n pub default_x: Directions,\n\n pub default_y: Directions,\n\n pub x: Directions,\n\n pub y: Directions,\n", "file_path": "src/components/direction.rs", "rank": 9, "score": 56369.059973126445 }, { "content": "}\n\n\n\nimpl Default for Direction {\n\n fn default() -> Self {\n\n Self {\n\n default_x: Directions::Neutral,\n\n default_y: Directions::Neutral,\n\n x: Directions::Neutral,\n\n y: Directions::Neutral,\n\n }\n\n }\n\n}\n\n\n\nimpl Direction {\n\n pub fn new(default_x: Directions, default_y: Directions, x: Directions, y: Directions) -> Self {\n\n Direction {\n\n default_x,\n\n default_y,\n\n x,\n\n y,\n", "file_path": "src/components/direction.rs", "rank": 10, "score": 56363.45266115266 }, { "content": " pub state: MarineState,\n\n pub is_shooting: bool,\n\n pub has_shot: bool,\n\n pub max_ground_speed: f32,\n\n pub max_air_speed: f32,\n\n}\n\n\n\nimpl Marine {\n\n pub fn new() -> Self {\n\n Marine {\n\n state: MarineState::Idling,\n\n is_shooting: false,\n\n has_shot: false,\n\n max_ground_speed: 6.,\n\n max_air_speed: 12.,\n\n }\n\n }\n\n}\n", "file_path": "src/components/marine.rs", "rank": 11, "score": 56363.19778445874 }, { "content": " }\n\n }\n\n\n\n /// Changes the horizontal direction based on the x velocity.\n\n pub fn set_x_velocity(&mut self, x_velocity: f32) {\n\n self.x = if x_velocity.abs() < std::f32::EPSILON {\n\n Directions::Neutral\n\n } else if x_velocity > 0. {\n\n Directions::Right\n\n } else {\n\n Directions::Left\n\n };\n\n }\n\n}\n", "file_path": "src/components/direction.rs", "rank": 12, "score": 56360.09175428526 }, { "content": "use amethyst::ecs::{Component, NullStorage};\n\n\n\n#[derive(Component, Default)]\n\n#[storage(NullStorage)]\n\npub struct BulletImpact;\n\n\n\n#[derive(Component, Default)]\n\n#[storage(NullStorage)]\n\npub struct Bullet;\n", "file_path": "src/components/bullet.rs", "rank": 13, "score": 56295.01037455098 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage, Entity};\n\n\n\n/// Flier AI is a simple state machine. Pincer either patrols its designated area or\n\n/// attacks its target.\n\n#[derive(Eq, Hash, PartialEq, Clone, Copy)]\n\npub enum FlierAi {\n\n Patrolling,\n\n Attacking { target: Entity },\n\n}\n\n\n\nimpl Default for FlierAi {\n\n fn default() -> Self {\n\n FlierAi::Patrolling\n\n }\n\n}\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Flier {\n\n pub ai: FlierAi,\n", "file_path": "src/components/flier.rs", "rank": 14, "score": 56183.91336116632 }, { "content": "use amethyst::ecs::{Component, DenseVecStorage, Entity};\n\n\n\n/// Pincer AI is a simple state machine. Pincer either patrols its designated area or\n\n/// attacks its target.\n\n#[derive(Eq, Hash, PartialEq, Clone, Copy)]\n\npub enum PincerAi {\n\n Patrolling,\n\n Attacking { target: Entity },\n\n}\n\n\n\nimpl Default for PincerAi {\n\n fn default() -> Self {\n\n PincerAi::Patrolling\n\n }\n\n}\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Pincer {\n\n pub ai: PincerAi,\n", "file_path": "src/components/pincer.rs", "rank": 15, "score": 56182.110813402855 }, { "content": " pub hit_count: u32,\n\n}\n\n\n\nimpl Flier {\n\n pub fn new() -> Self {\n\n Flier {\n\n ai: FlierAi::Patrolling,\n\n hit_count: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/components/flier.rs", "rank": 16, "score": 56177.12243711705 }, { "content": " pub hit_count: u32,\n\n}\n\n\n\nimpl Pincer {\n\n pub fn new() -> Self {\n\n Pincer {\n\n ai: PincerAi::Patrolling,\n\n hit_count: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/components/pincer.rs", "rank": 17, "score": 56177.080346387615 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Join, ReadExpect, ReadStorage, System, WriteStorage},\n\n};\n\n\n\nuse crate::{\n\n components::{Bullet, Collidee, Collider, Marine, Motion, Subject},\n\n resources::Context,\n\n};\n\n\n\npub struct TransformationSystem;\n\n\n\nimpl<'s> System<'s> for TransformationSystem {\n\n type SystemData = (\n\n WriteStorage<'s, Collider>,\n\n WriteStorage<'s, Collidee>,\n\n WriteStorage<'s, Motion>,\n\n WriteStorage<'s, Transform>,\n\n );\n\n\n", "file_path": "src/systems/transformation.rs", "rank": 18, "score": 54590.494979487616 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Entities, Join, ReadStorage, System, WriteStorage},\n\n};\n\n\n\nuse std::f32::consts::PI;\n\n\n\nuse crate::components::{Direction, Directions};\n\n\n\npub struct DirectionSystem;\n\n\n\nimpl<'s> System<'s> for DirectionSystem {\n\n type SystemData = (\n\n Entities<'s>,\n\n ReadStorage<'s, Direction>,\n\n WriteStorage<'s, Transform>,\n\n );\n\n\n\n fn run(&mut self, (entities, directions, mut transforms): Self::SystemData) {\n\n // Iterate over entities having direction and transform components\n", "file_path": "src/systems/direction.rs", "rank": 19, "score": 54580.201136154144 }, { "content": "\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (bullets, mut transforms) = data;\n\n\n\n for (_, transform) in (&bullets, &mut transforms).join() {\n\n transform.set_translation_z(0.);\n\n }\n\n }\n\n}\n\n\n\npub struct CameraTransformationSystem;\n\n\n\nimpl<'s> System<'s> for CameraTransformationSystem {\n\n type SystemData = (\n\n ReadStorage<'s, Marine>,\n\n ReadStorage<'s, Subject>,\n\n WriteStorage<'s, Transform>,\n\n ReadExpect<'s, Context>,\n\n );\n\n\n", "file_path": "src/systems/transformation.rs", "rank": 20, "score": 54574.87940874717 }, { "content": " if collidee_vertical.correction < 0. {\n\n collider.on_ground = true;\n\n }\n\n }\n\n // FIXME: Due to the take() operation above, collidee.vertical will always be NONE.\n\n // Might indicate a bug.\n\n if collidee.vertical.is_none() && velocity.y != 0. {\n\n collider.on_ground = false;\n\n }\n\n transform.set_translation_x(bbox.position.x);\n\n transform.set_translation_y(bbox.position.y);\n\n collider.set_hit_box_position(*velocity);\n\n }\n\n }\n\n}\n\n\n\npub struct BulletTransformationSystem;\n\n\n\nimpl<'s> System<'s> for BulletTransformationSystem {\n\n type SystemData = (ReadStorage<'s, Bullet>, WriteStorage<'s, Transform>);\n", "file_path": "src/systems/transformation.rs", "rank": 21, "score": 54573.186987481626 }, { "content": " fn run(&mut self, data: Self::SystemData) {\n\n let (mut colliders, mut collidees, mut motions, mut transforms) = data;\n\n\n\n for (collider, collidee, motion, transform) in (\n\n &mut colliders,\n\n &mut collidees,\n\n &mut motions,\n\n &mut transforms,\n\n )\n\n .join()\n\n {\n\n let bbox = &mut collider.bounding_box;\n\n let velocity = &mut motion.velocity;\n\n\n\n if let Some(collidee_horizontal) = collidee.horizontal.take() {\n\n bbox.position.x -= collidee_horizontal.correction;\n\n }\n\n if let Some(collidee_vertical) = collidee.vertical.take() {\n\n bbox.position.y -= collidee_vertical.correction;\n\n velocity.y = 0.;\n", "file_path": "src/systems/transformation.rs", "rank": 22, "score": 54570.256048221345 }, { "content": " fn run(&mut self, (marines, subject_tags, mut transforms, ctx): Self::SystemData) {\n\n let mut marine_x = 0.;\n\n let map_width = ctx.map_width;\n\n let background_width = ctx.bg_width;\n\n\n\n for (_marine, transform) in (&marines, &transforms).join() {\n\n marine_x = transform.translation().x;\n\n }\n\n\n\n for (_subject_tag, transform) in (&subject_tags, &mut transforms).join() {\n\n if marine_x >= background_width && marine_x <= map_width - background_width {\n\n transform.set_translation_x(marine_x);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/transformation.rs", "rank": 23, "score": 54566.12539912786 }, { "content": " for (_, direction, transform) in (&entities, &directions, &mut transforms).join() {\n\n if direction.x == direction.default_x {\n\n // Rotate by 0 deg along y-axis if direction is right\n\n // as right is the default direction\n\n transform.set_rotation_y_axis(0.);\n\n } else if direction.x != Directions::Neutral && direction.x != direction.default_x {\n\n // Rotate by 180 deg along y-axis if direction is left\n\n transform.set_rotation_y_axis(PI);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/direction.rs", "rank": 24, "score": 54563.60907835489 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Join, ReadStorage, System, WriteStorage},\n\n renderer::{palette::Srgba, resources::Tint},\n\n};\n\n\n\nuse crate::components::{Collider, Direction, Flier, FlierAi, FlierAi::Attacking, Motion};\n\n\n\n/// Maximum distance over which a pincer will track its target.\n\n/// When the distance between the pincer and its target becomes greater than this constant,\n\n/// the pincer will lose interest and will revert back to patrolling.\n\n/// TODO: Arbitrarily picked, maybe later properly tune this variable.\n\nconst MAX_TRACKING_DISTANCE: f32 = 10000.0;\n\n\n\npub struct FlierAiSystem;\n\n\n\n/// Execute Pincer AI logic.\n\n///\n\n/// Attack logic is simple. Check the direction of the target and change the sign of\n\n/// the pincer's velocity to make it run towards the target.\n", "file_path": "src/systems/flier.rs", "rank": 25, "score": 54393.72056731069 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Join, ReadStorage, System, WriteStorage},\n\n renderer::{palette::Srgba, resources::Tint},\n\n};\n\n\n\nuse crate::components::{Collider, Direction, Motion, Pincer, PincerAi, PincerAi::Attacking};\n\n\n\n/// Maximum distance over which a pincer will track its target.\n\n/// When the distance between the pincer and its target becomes greater than this constant,\n\n/// the pincer will lose interest and will revert back to patrolling.\n\n/// TODO: Arbitrarily picked, maybe later properly tune this variable.\n\nconst MAX_TRACKING_DISTANCE: f32 = 10000.0;\n\n\n\npub struct PincerAiSystem;\n\n\n\n/// Execute Pincer AI logic.\n\n///\n\n/// Attack logic is simple. Check the direction of the target and change the sign of\n\n/// the pincer's velocity to make it run towards the target.\n", "file_path": "src/systems/pincer.rs", "rank": 26, "score": 54391.09039391258 }, { "content": "///\n\n/// There is one exception; the pincer won't change its direction while the target is jumping.\n\n/// This is to give the player a fair chance to jump over the pincer without the pincer's\n\n/// millisecond-reflexes screwing up the player's plans.\n\n///\n\n/// Finally, this system changes the pincer's color tint depending on whether it's aggro or not.\n\nimpl<'s> System<'s> for FlierAiSystem {\n\n type SystemData = (\n\n WriteStorage<'s, Flier>,\n\n WriteStorage<'s, Direction>,\n\n WriteStorage<'s, Motion>,\n\n WriteStorage<'s, Tint>,\n\n ReadStorage<'s, Transform>,\n\n ReadStorage<'s, Collider>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (mut fliers, mut directions, mut motions, mut tints, transforms, colliders): Self::SystemData,\n\n ) {\n", "file_path": "src/systems/flier.rs", "rank": 27, "score": 54390.58467466496 }, { "content": "///\n\n/// There is one exception; the pincer won't change its direction while the target is jumping.\n\n/// This is to give the player a fair chance to jump over the pincer without the pincer's\n\n/// millisecond-reflexes screwing up the player's plans.\n\n///\n\n/// Finally, this system changes the pincer's color tint depending on whether it's aggro or not.\n\nimpl<'s> System<'s> for PincerAiSystem {\n\n type SystemData = (\n\n WriteStorage<'s, Pincer>,\n\n WriteStorage<'s, Direction>,\n\n WriteStorage<'s, Motion>,\n\n WriteStorage<'s, Tint>,\n\n ReadStorage<'s, Transform>,\n\n ReadStorage<'s, Collider>,\n\n );\n\n\n\n fn run(\n\n &mut self,\n\n (mut pincers, mut directions, mut motions, mut tints, transforms, colliders): Self::SystemData,\n\n ) {\n", "file_path": "src/systems/pincer.rs", "rank": 28, "score": 54388.139530654196 }, { "content": " for (flier, direction, motion, transform, tint) in (\n\n &mut fliers,\n\n &mut directions,\n\n &mut motions,\n\n &transforms,\n\n &mut tints,\n\n )\n\n .join()\n\n {\n\n if let Attacking { target } = flier.ai {\n\n if let (Some(target_transform), Some(target_collider)) =\n\n (transforms.get(target), colliders.get(target))\n\n {\n\n let distance = target_transform.translation().x - transform.translation().x;\n\n if distance.abs() > MAX_TRACKING_DISTANCE {\n\n // The target is out of range, go back to patrolling.\n\n flier.ai = FlierAi::Patrolling;\n\n } else if target_collider.on_ground {\n\n let distance = target_transform.translation().x - transform.translation().x;\n\n motion.velocity.x = distance.signum() * motion.velocity.x.abs();\n", "file_path": "src/systems/flier.rs", "rank": 29, "score": 54387.441842649154 }, { "content": " for (pincer, direction, motion, transform, tint) in (\n\n &mut pincers,\n\n &mut directions,\n\n &mut motions,\n\n &transforms,\n\n &mut tints,\n\n )\n\n .join()\n\n {\n\n if let Attacking { target } = pincer.ai {\n\n if let (Some(target_transform), Some(target_collider)) =\n\n (transforms.get(target), colliders.get(target))\n\n {\n\n let distance = target_transform.translation().x - transform.translation().x;\n\n if distance.abs() > MAX_TRACKING_DISTANCE {\n\n // The target is out of range, go back to patrolling.\n\n pincer.ai = PincerAi::Patrolling;\n\n } else if target_collider.on_ground {\n\n let distance = target_transform.translation().x - transform.translation().x;\n\n motion.velocity.x = distance.signum() * motion.velocity.x.abs();\n", "file_path": "src/systems/pincer.rs", "rank": 30, "score": 54387.40396231893 }, { "content": " direction.set_x_velocity(motion.velocity.x);\n\n }\n\n } else {\n\n // The target no longer exists, go back to patrolling.\n\n flier.ai = FlierAi::Patrolling;\n\n }\n\n }\n\n\n\n // Give flier a red tint if they are attacking, or no tint if they're not.\n\n tint.0 = match flier.ai {\n\n FlierAi::Attacking { .. } => Srgba::new(1.0, 0.0, 0.0, 1.0),\n\n _ => Srgba::new(1.0, 1.0, 1.0, 1.0),\n\n };\n\n }\n\n }\n\n}\n", "file_path": "src/systems/flier.rs", "rank": 31, "score": 54375.41657968323 }, { "content": " direction.set_x_velocity(motion.velocity.x);\n\n }\n\n } else {\n\n // The target no longer exists, go back to patrolling.\n\n pincer.ai = PincerAi::Patrolling;\n\n }\n\n }\n\n\n\n // Give pincer a red tint if they are attacking, or no tint if they're not.\n\n tint.0 = match pincer.ai {\n\n PincerAi::Attacking { .. } => Srgba::new(1.0, 0.0, 0.0, 1.0),\n\n _ => Srgba::new(1.0, 1.0, 1.0, 1.0),\n\n };\n\n }\n\n }\n\n}\n", "file_path": "src/systems/pincer.rs", "rank": 32, "score": 54375.37423600937 }, { "content": "fn main() -> amethyst::Result<()> {\n\n amethyst::start_logger(Default::default());\n\n\n\n let root = application_root_dir()?;\n\n let display_config_path = root.join(\"resources/display_config.ron\");\n\n let assets_path = root.join(\"assets\");\n\n let input_bundle = InputBundle::<StringBindings>::new()\n\n .with_bindings_from_file(root.join(\"resources/bindings_config.ron\"))?;\n\n\n\n let prefab_loader_system_desc = PrefabLoaderSystemDesc::<AnimationPrefabData>::default();\n\n\n\n let game_data = GameDataBuilder::default()\n\n .with_system_desc(prefab_loader_system_desc, \"scene_loader\", &[])\n\n .with_bundle(AnimationBundle::<AnimationId, SpriteRender>::new(\n\n \"sprite_animation_control\",\n\n \"sprite_sampler_interpolation\",\n\n ))?\n\n .with_bundle(\n\n TransformBundle::new()\n\n .with_dep(&[\"sprite_animation_control\", \"sprite_sampler_interpolation\"]),\n", "file_path": "src/main.rs", "rank": 33, "score": 41189.45775638605 }, { "content": "pub fn show_explosion(\n\n entities: &Entities,\n\n prefab_handle: Handle<Prefab<AnimationPrefabData>>,\n\n transform_x: f32,\n\n transform_y: f32,\n\n lazy_update: &ReadExpect<LazyUpdate>,\n\n ctx: &Context,\n\n) {\n\n let exposion_entity: Entity = entities.create();\n\n let scale = ctx.scale;\n\n\n\n let mut transform = Transform::default();\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n transform.set_translation_xyz(transform_x, scale.mul_add(32. - 15., transform_y), 0.);\n\n\n\n lazy_update.insert(exposion_entity, Explosion::default());\n\n lazy_update.insert(\n\n exposion_entity,\n\n Animation::new(AnimationId::Explode, vec![AnimationId::Explode]),\n\n );\n\n lazy_update.insert(exposion_entity, prefab_handle);\n\n lazy_update.insert(exposion_entity, transform);\n\n lazy_update.insert(exposion_entity, Transparent);\n\n}\n", "file_path": "src/entities/explosion.rs", "rank": 34, "score": 33322.175000515854 }, { "content": "/// Returns a `SpriteSheetHandle` for the given texture and ron files.\n\npub fn get_sprite_sheet_handle(\n\n world: &World,\n\n texture_path: &str,\n\n ron_path: &str,\n\n progress_counter: &mut ProgressCounter,\n\n) -> SpriteSheetHandle {\n\n // Load the sprite sheet necessary to render the graphics.\n\n // The texture is the pixel data\n\n // `sprite_sheet` is the layout of the sprites on the image\n\n // `texture_handle` is a cloneable reference to the texture\n\n let texture_handle = {\n\n let loader = &world.read_resource::<Loader>();\n\n let texture_storage = &world.read_resource::<AssetStorage<Texture>>();\n\n loader.load(texture_path, ImageFormat::default(), (), &texture_storage)\n\n };\n\n let loader = &world.read_resource::<Loader>();\n\n let sprite_sheet_store = &world.read_resource::<AssetStorage<SpriteSheet>>();\n\n loader.load(\n\n ron_path,\n\n SpriteSheetFormat(texture_handle),\n\n progress_counter,\n\n &sprite_sheet_store,\n\n )\n\n}\n\n\n", "file_path": "src/resources/asset.rs", "rank": 35, "score": 31280.97850140753 }, { "content": "use amethyst::{\n\n assets::{Handle, Prefab},\n\n core::{\n\n math::{Vector2, Vector3},\n\n Transform, WithNamed,\n\n },\n\n ecs::prelude::World,\n\n prelude::{Builder, WorldExt},\n\n renderer::transparent::Transparent,\n\n};\n\n\n\nuse crate::{\n\n components::{\n\n Animation, AnimationId, AnimationPrefabData, Boundary, Collidee, Collider, Direction,\n\n Directions, Marine, Motion,\n\n },\n\n resources::Context,\n\n};\n\n\n", "file_path": "src/entities/marine.rs", "rank": 36, "score": 28748.36820406539 }, { "content": " .with(Boundary::new(ctx.x_correction, ctx.map_width, 352., 0.))\n\n .with(Collidee::default())\n\n .with(transform)\n\n .with(motion)\n\n .with(Animation::new(\n\n AnimationId::Idle,\n\n vec![\n\n AnimationId::Die,\n\n AnimationId::Idle,\n\n AnimationId::Jump,\n\n AnimationId::Move,\n\n AnimationId::Shoot,\n\n ],\n\n ))\n\n .with(prefab)\n\n .with(Direction::new(\n\n Directions::Right,\n\n Directions::Neutral,\n\n Directions::Right,\n\n Directions::Neutral,\n\n ))\n\n .with(Transparent) // Necessary for ordered layering\n\n .build();\n\n}\n", "file_path": "src/entities/marine.rs", "rank": 37, "score": 28728.12939565997 }, { "content": "#[derive(Clone, Copy, Default)]\n\npub struct Context {\n\n pub map_width: f32,\n\n pub bg_width: f32,\n\n pub bg_height: f32,\n\n pub x_correction: f32,\n\n pub y_correction: f32,\n\n pub bg_z_translation: f32,\n\n pub truss_z_translation: f32,\n\n pub platform_z_translation: f32,\n\n pub scale: f32,\n\n}\n\n\n\nimpl Context {\n\n pub fn new() -> Self {\n\n Context {\n\n map_width: 4608.,\n\n bg_width: 384.,\n\n bg_height: 352.,\n\n x_correction: -(1200. / 2. - 384.), // - (screen_width / 2. - background_width)\n\n y_correction: -176., // (background_height / 2.) * -1.\n\n bg_z_translation: -50.,\n\n truss_z_translation: -40.,\n\n platform_z_translation: -10.,\n\n scale: 2.,\n\n }\n\n }\n\n}\n", "file_path": "src/resources/context.rs", "rank": 38, "score": 28690.050936576863 }, { "content": "use amethyst::{\n\n assets::{Handle, Prefab},\n\n core::{\n\n math::{Vector2, Vector3},\n\n Named, Transform,\n\n },\n\n ecs::{Entities, Entity, LazyUpdate, ReadExpect},\n\n renderer::{sprite::SpriteSheetHandle, transparent::Transparent, SpriteRender},\n\n};\n\n\n\nuse crate::{\n\n components::{\n\n Animation, AnimationId, AnimationPrefabData, Boundary, Bullet, BulletImpact, Collidee,\n\n Collider, Direction, Directions, Motion,\n\n },\n\n resources::Context,\n\n};\n\n\n", "file_path": "src/entities/bullet.rs", "rank": 39, "score": 28672.880041372355 }, { "content": " let bbox = &mut collider.bounding_box;\n\n bbox.position = Vector2::new(bullet_start_position, marine_bottom + 48.);\n\n bbox.old_position = bbox.position;\n\n\n\n transform.set_translation_x(bullet_start_position);\n\n transform.set_translation_y(marine_bottom + 48.);\n\n // bullet should be shown only after making sure that there is no collision at the spawn position\n\n transform.set_translation_z(-60.);\n\n\n\n collider.set_hit_box_position(motion.velocity);\n\n\n\n lazy_update.insert(bullet_entity, Bullet::default());\n\n lazy_update.insert(bullet_entity, Named::new(\"Bullet\"));\n\n lazy_update.insert(bullet_entity, collider);\n\n lazy_update.insert(\n\n bullet_entity,\n\n Boundary::new(ctx.x_correction, ctx.map_width, 352., 0.),\n\n );\n\n lazy_update.insert(bullet_entity, Collidee::default());\n\n lazy_update.insert(bullet_entity, sprite_render);\n\n lazy_update.insert(bullet_entity, motion);\n\n lazy_update.insert(bullet_entity, transform);\n\n lazy_update.insert(bullet_entity, direction);\n\n lazy_update.insert(bullet_entity, Transparent);\n\n}\n\n\n", "file_path": "src/entities/bullet.rs", "rank": 40, "score": 28663.029656404357 }, { "content": "\n\n let mut direction = Direction::new(\n\n Directions::Right,\n\n Directions::Neutral,\n\n Directions::Neutral,\n\n Directions::Neutral,\n\n );\n\n\n\n let mut bullet_start_position = 0.;\n\n if marine_dir.x == Directions::Right {\n\n motion.velocity.x = 20.;\n\n direction.x = Directions::Right;\n\n bullet_start_position = shoot_start_position + 22.;\n\n } else if marine_dir.x == Directions::Left {\n\n motion.velocity.x = -20.;\n\n direction.x = Directions::Left;\n\n bullet_start_position = shoot_start_position - 22.;\n\n }\n\n\n\n let mut collider = Collider::new(22. * scale, 4. * scale);\n", "file_path": "src/entities/bullet.rs", "rank": 41, "score": 28662.34310921576 }, { "content": " direction.x = Directions::Right;\n\n scale.mul_add(-8., impact_position)\n\n } else {\n\n direction.x = Directions::Left;\n\n scale.mul_add(8., impact_position)\n\n };\n\n\n\n let mut transform = Transform::default();\n\n transform.set_scale(Vector3::new(scale, scale, scale));\n\n transform.set_translation_x(impact_position_x);\n\n transform.set_translation_y(bullet_position_y);\n\n transform.set_translation_z(-10.);\n\n\n\n lazy_update.insert(bullet_impact_entity, BulletImpact::default());\n\n lazy_update.insert(\n\n bullet_impact_entity,\n\n Animation::new(AnimationId::BulletImpact, vec![AnimationId::BulletImpact]),\n\n );\n\n lazy_update.insert(bullet_impact_entity, prefab_handle);\n\n lazy_update.insert(bullet_impact_entity, transform);\n\n lazy_update.insert(bullet_impact_entity, direction);\n\n lazy_update.insert(bullet_impact_entity, Transparent);\n\n}\n", "file_path": "src/entities/bullet.rs", "rank": 42, "score": 28654.655244815654 }, { "content": "use amethyst::{\n\n assets::{Handle, Prefab},\n\n core::{\n\n math::{Vector2, Vector3},\n\n Transform, WithNamed,\n\n },\n\n ecs::prelude::World,\n\n prelude::{Builder, WorldExt},\n\n renderer::{palette::Srgba, resources::Tint, transparent::Transparent},\n\n};\n\n\n\nuse crate::{\n\n components::{\n\n Animation, AnimationId, AnimationPrefabData, Boundary, Collidee, Collider, Direction,\n\n Directions, Flier, GenericBox, Motion,\n\n },\n\n resources::Context,\n\n};\n\n\n", "file_path": "src/entities/flier.rs", "rank": 43, "score": 28560.045091328848 }, { "content": "use amethyst::{\n\n assets::{Handle, Prefab},\n\n core::{\n\n math::{Vector2, Vector3},\n\n Transform, WithNamed,\n\n },\n\n ecs::prelude::World,\n\n prelude::{Builder, WorldExt},\n\n renderer::{palette::Srgba, resources::Tint, transparent::Transparent},\n\n};\n\n\n\nuse crate::{\n\n components::{\n\n Animation, AnimationId, AnimationPrefabData, Boundary, Collidee, Collider, Direction,\n\n Directions, GenericBox, Motion, Pincer,\n\n },\n\n resources::Context,\n\n};\n\n\n", "file_path": "src/entities/pincer.rs", "rank": 44, "score": 28560.022821038165 }, { "content": " let tint = Tint(Srgba::new(1.0, 1.0, 1.0, 1.0));\n\n\n\n world\n\n .create_entity()\n\n .with(Flier::new())\n\n .named(\"Flier\")\n\n .with(collider)\n\n .with(tint)\n\n .with(Boundary::new(1800., 2575., 352., 0.))\n\n .with(Collidee::default())\n\n .with(transform)\n\n .with(motion)\n\n .with(Animation::new(\n\n AnimationId::Flying,\n\n vec![AnimationId::Flying],\n\n ))\n\n .with(prefab)\n\n .with(direction)\n\n .with(Transparent) // Necessary for ordered layering\n\n .build();\n\n}\n", "file_path": "src/entities/flier.rs", "rank": 45, "score": 28550.667708484703 }, { "content": " bbox.position = Vector2::new(flier_start_x_pos, flier_start_y_pos);\n\n bbox.old_position = bbox.position;\n\n\n\n transform.set_translation_x(flier_start_x_pos);\n\n transform.set_translation_y(flier_start_y_pos);\n\n\n\n let mut motion = Motion::new();\n\n // Make the flier a teeny bit faster than the pincer since its easier to dodge\n\n motion.velocity.x = -4.;\n\n collider.set_hit_box_position(motion.velocity);\n\n\n\n let direction = Direction::new(\n\n Directions::Left,\n\n Directions::Neutral,\n\n Directions::Left,\n\n Directions::Neutral,\n\n );\n\n\n\n // White shows the sprite as normal.\n\n // You can change the color at any point to modify the sprite's tint.\n", "file_path": "src/entities/flier.rs", "rank": 46, "score": 28549.132980853225 }, { "content": "\n\n let direction = Direction::new(\n\n Directions::Left,\n\n Directions::Neutral,\n\n Directions::Left,\n\n Directions::Neutral,\n\n );\n\n\n\n // White shows the sprite as normal.\n\n // You can change the color at any point to modify the sprite's tint.\n\n let tint = Tint(Srgba::new(1.0, 1.0, 1.0, 1.0));\n\n\n\n world\n\n .create_entity()\n\n .with(Pincer::new())\n\n .named(\"Pincer\")\n\n .with(collider)\n\n .with(tint)\n\n .with(Boundary::new(800., 1832., 352., 0.))\n\n .with(Collidee::default())\n", "file_path": "src/entities/pincer.rs", "rank": 47, "score": 28547.401887349035 }, { "content": " .with(transform)\n\n .with(motion)\n\n .with(Animation::new(\n\n AnimationId::Idle,\n\n vec![AnimationId::Idle, AnimationId::Walk],\n\n ))\n\n .with(prefab)\n\n .with(direction)\n\n .with(Transparent) // Necessary for ordered layering\n\n .build();\n\n}\n", "file_path": "src/entities/pincer.rs", "rank": 48, "score": 28539.60292894191 }, { "content": "pub use self::collision::Collider;\n\npub use self::collision::GenericBox;\n\npub use self::direction::Direction;\n\npub use self::direction::Directions;\n\npub use self::explosion::Explosion;\n\npub use self::flier::Flier;\n\npub use self::flier::FlierAi;\n\npub use self::marine::Marine;\n\npub use self::marine::MarineState;\n\npub use self::motion::Motion;\n\npub use self::parallax::Parallax;\n\npub use self::pincer::Pincer;\n\npub use self::pincer::PincerAi;\n\npub use self::subject::Subject;\n", "file_path": "src/components/mod.rs", "rank": 49, "score": 27662.743542916534 }, { "content": "mod animation;\n\nmod bullet;\n\nmod collision;\n\nmod direction;\n\nmod explosion;\n\nmod flier;\n\nmod marine;\n\nmod motion;\n\nmod parallax;\n\nmod pincer;\n\nmod subject;\n\n\n\npub use self::animation::Animation;\n\npub use self::animation::AnimationId;\n\npub use self::animation::AnimationPrefabData;\n\npub use self::bullet::Bullet;\n\npub use self::bullet::BulletImpact;\n\npub use self::collision::Boundary;\n\npub use self::collision::Collidee;\n\npub use self::collision::CollideeDetails;\n", "file_path": "src/components/mod.rs", "rank": 50, "score": 27657.219059401647 }, { "content": "use amethyst::{\n\n core::math::Vector2,\n\n ecs::{Component, DenseVecStorage},\n\n};\n\n\n\n#[derive(Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Boundary {\n\n pub left: f32,\n\n pub right: f32,\n\n pub top: f32,\n\n pub bottom: f32,\n\n}\n\n\n\nimpl Boundary {\n\n pub fn new(left: f32, right: f32, top: f32, bottom: f32) -> Self {\n\n Self {\n\n left,\n\n right,\n\n top,\n", "file_path": "src/components/collision.rs", "rank": 51, "score": 27650.62632735904 }, { "content": "#[storage(DenseVecStorage)]\n\npub struct Collidee {\n\n pub horizontal: Option<CollideeDetails>,\n\n pub vertical: Option<CollideeDetails>,\n\n}\n\n\n\nimpl Default for Collidee {\n\n fn default() -> Self {\n\n Self {\n\n horizontal: None,\n\n vertical: None,\n\n }\n\n }\n\n}\n\n\n\nimpl Collidee {\n\n pub fn set_collidee_details(\n\n &mut self,\n\n name: String,\n\n collider_a: &Collider,\n", "file_path": "src/components/collision.rs", "rank": 52, "score": 27649.903068959124 }, { "content": " pub is_collidable: bool,\n\n}\n\n\n\nimpl Default for Collider {\n\n fn default() -> Self {\n\n Self {\n\n bounding_box: GenericBox::default(),\n\n hit_box: GenericBox::default(),\n\n hit_box_offset: Vector2::new(0., 0.),\n\n on_ground: false,\n\n hit_box_offset_front: 0.,\n\n hit_box_offset_back: 0.,\n\n is_collidable: true,\n\n }\n\n }\n\n}\n\n\n\nimpl Collider {\n\n pub fn new(width: f32, height: f32) -> Self {\n\n Collider {\n", "file_path": "src/components/collision.rs", "rank": 53, "score": 27648.04284875836 }, { "content": "use amethyst::ecs::{Component, NullStorage};\n\n\n\n#[derive(Component, Default)]\n\n#[storage(NullStorage)]\n\npub struct Subject;\n", "file_path": "src/components/subject.rs", "rank": 54, "score": 27647.45059454624 }, { "content": "use amethyst::ecs::{Component, NullStorage};\n\n\n\n#[derive(Component, Default)]\n\n#[storage(NullStorage)]\n\npub struct Explosion;\n", "file_path": "src/components/explosion.rs", "rank": 55, "score": 27647.45059454624 }, { "content": "use amethyst::ecs::{Component, NullStorage};\n\n\n\n#[derive(Component, Default)]\n\n#[storage(NullStorage)]\n\npub struct Parallax;\n", "file_path": "src/components/parallax.rs", "rank": 56, "score": 27647.45059454624 }, { "content": " correction.y = overlap.y * speed_ratio_a.y;\n\n self.vertical = Some(CollideeDetails {\n\n name,\n\n position: box_b.position,\n\n half_size: box_b.half_size,\n\n correction: correction.y,\n\n });\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Component)]\n\n#[storage(DenseVecStorage)]\n\npub struct Collider {\n\n pub bounding_box: GenericBox,\n\n pub hit_box: GenericBox,\n\n pub hit_box_offset: Vector2<f32>,\n\n pub on_ground: bool,\n\n pub hit_box_offset_front: f32,\n\n pub hit_box_offset_back: f32,\n", "file_path": "src/components/collision.rs", "rank": 57, "score": 27646.12948295089 }, { "content": "use amethyst::{\n\n animation::AnimationSetPrefab,\n\n assets::{PrefabData, ProgressCounter},\n\n derive::PrefabData,\n\n ecs::Entity,\n\n ecs::{Component, DenseVecStorage},\n\n error::Error,\n\n renderer::sprite::{prefab::SpriteScenePrefab, SpriteRender},\n\n};\n\n\n\nuse serde::{Deserialize, Serialize};\n\n\n\n/// `AnimationId` is the ID used in an `AnimationSet`, used to identify which\n\n/// animation to play.\n\n#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Serialize)]\n\npub enum AnimationId {\n\n BulletImpact,\n\n Die,\n\n Explode,\n\n Jump,\n", "file_path": "src/components/animation.rs", "rank": 58, "score": 27645.266262790843 }, { "content": "}\n\n\n\nimpl GenericBox {\n\n pub fn new(width: f32, height: f32) -> Self {\n\n GenericBox {\n\n half_size: Vector2::new(width / 2., height / 2.),\n\n position: Vector2::new(0., 0.),\n\n old_position: Vector2::new(0., 0.),\n\n }\n\n }\n\n}\n\n\n\npub struct CollideeDetails {\n\n pub name: String,\n\n pub position: Vector2<f32>,\n\n pub half_size: Vector2<f32>,\n\n pub correction: f32,\n\n}\n\n\n\n#[derive(Component)]\n", "file_path": "src/components/collision.rs", "rank": 59, "score": 27645.08747426805 }, { "content": " collider_b: &Collider,\n\n velocity_a: Vector2<f32>,\n\n velocity_b: Vector2<f32>,\n\n use_hit_box: bool,\n\n ) {\n\n let (box_a, box_b) = if use_hit_box {\n\n (&collider_a.hit_box, &collider_b.hit_box)\n\n } else {\n\n (&collider_a.bounding_box, &collider_b.bounding_box)\n\n };\n\n\n\n let mut correction = Vector2::new(0., 0.);\n\n\n\n let speed_sum = Vector2::new(\n\n (velocity_a.x - velocity_b.x).abs(),\n\n (velocity_a.y - velocity_b.y).abs(),\n\n );\n\n let speed_ratio_a = Vector2::new(velocity_a.x / speed_sum.x, velocity_a.y / speed_sum.y);\n\n let speed_ratio_b = Vector2::new(velocity_b.x / speed_sum.x, velocity_b.y / speed_sum.y);\n\n\n", "file_path": "src/components/collision.rs", "rank": 60, "score": 27644.949887271512 }, { "content": " } else {\n\n bbox_position.y - self.hit_box_offset.y\n\n };\n\n }\n\n\n\n pub fn is_overlapping_with(&self, other: &Collider, use_hit_box: bool) -> bool {\n\n let (self_box, other_box) = if use_hit_box {\n\n (&self.hit_box, &other.hit_box)\n\n } else {\n\n (&self.bounding_box, &other.bounding_box)\n\n };\n\n !((self_box.position.x - other_box.position.x).abs()\n\n >= (self_box.half_size.x + other_box.half_size.x).abs()\n\n || (self_box.position.y - other_box.position.y).abs()\n\n >= (self_box.half_size.y + other_box.half_size.y).abs())\n\n }\n\n}\n", "file_path": "src/components/collision.rs", "rank": 61, "score": 27643.628004563838 }, { "content": " }\n\n // No correction (correction = 0.) is required if collider is slower\n\n // and both bodies are moving in the same direction\n\n self.horizontal = Some(CollideeDetails {\n\n name,\n\n position: box_b.position,\n\n half_size: box_b.half_size,\n\n correction: correction.x,\n\n });\n\n } else if x_overlapped && y_overlapped {\n\n // Might happen when an entity is added at run time.\n\n // As per the current game design, no correction (correction = 0.) is required for this scenario\n\n // This might have to be changed in future\n\n self.horizontal = Some(CollideeDetails {\n\n name,\n\n position: box_b.position,\n\n half_size: box_b.half_size,\n\n correction: correction.x,\n\n });\n\n } else {\n", "file_path": "src/components/collision.rs", "rank": 62, "score": 27643.48799326169 }, { "content": " Move,\n\n Idle,\n\n Shoot,\n\n Walk,\n\n Flying,\n\n}\n\n\n\n/// `AnimationPrefabData` type used for loading of `SpriteScene`s and their\n\n/// `AnimationSet`s.\n\n#[derive(Clone, Debug, Deserialize, PrefabData)]\n\npub struct AnimationPrefabData {\n\n /// Information for rendering a scene with sprites.\n\n sprite_scene: SpriteScenePrefab,\n\n /// Аll animations that can be run on the `Entity`.\n\n animation_set: AnimationSetPrefab<AnimationId, SpriteRender>,\n\n}\n\n\n\n#[derive(Component, Debug)]\n\n#[storage(DenseVecStorage)]\n\npub struct Animation {\n", "file_path": "src/components/animation.rs", "rank": 63, "score": 27641.42977213951 }, { "content": " pub current: AnimationId,\n\n pub types: Vec<AnimationId>,\n\n pub show: bool,\n\n}\n\n\n\nimpl Animation {\n\n pub fn new(current: AnimationId, types: Vec<AnimationId>) -> Self {\n\n Self {\n\n current,\n\n types,\n\n show: true,\n\n }\n\n }\n\n}\n", "file_path": "src/components/animation.rs", "rank": 64, "score": 27641.3778211218 }, { "content": " bottom,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct GenericBox {\n\n pub half_size: Vector2<f32>,\n\n pub position: Vector2<f32>,\n\n pub old_position: Vector2<f32>,\n\n}\n\n\n\nimpl Default for GenericBox {\n\n fn default() -> Self {\n\n Self {\n\n half_size: Vector2::new(0., 0.),\n\n position: Vector2::new(0., 0.),\n\n old_position: Vector2::new(0., 0.),\n\n }\n\n }\n", "file_path": "src/components/collision.rs", "rank": 65, "score": 27640.87863724175 }, { "content": " bounding_box: GenericBox::new(width, height),\n\n hit_box: GenericBox::new(width, height),\n\n hit_box_offset: Vector2::new(0., 0.),\n\n on_ground: false,\n\n hit_box_offset_front: 0.,\n\n hit_box_offset_back: 0.,\n\n is_collidable: true,\n\n }\n\n }\n\n\n\n pub fn set_hit_box_position(&mut self, velocity: Vector2<f32>) {\n\n let hbox_position = &mut self.hit_box.position;\n\n let bbox_position = self.bounding_box.position;\n\n hbox_position.x = if velocity.x >= 0. {\n\n bbox_position.x + self.hit_box_offset.x\n\n } else {\n\n bbox_position.x - self.hit_box_offset.x\n\n };\n\n hbox_position.y = if velocity.y >= 0. {\n\n bbox_position.y + self.hit_box_offset.y\n", "file_path": "src/components/collision.rs", "rank": 66, "score": 27639.962298347888 }, { "content": " let min_safe_distance = Vector2::new(\n\n box_a.half_size.x + box_b.half_size.x,\n\n box_a.half_size.y + box_b.half_size.y,\n\n );\n\n let overlap = Vector2::new(\n\n min_safe_distance.x - (box_a.position.x - box_b.position.x).abs(),\n\n min_safe_distance.y - (box_a.position.y - box_b.position.y).abs(),\n\n );\n\n\n\n // TODO: Reuse is_overlapping_with logic?\n\n let x_overlapped = (box_a.old_position.x - box_b.old_position.x).abs()\n\n < box_a.half_size.x + box_b.half_size.x;\n\n let y_overlapped = (box_a.old_position.y - box_b.old_position.y).abs()\n\n < box_a.half_size.y + box_b.half_size.y;\n\n\n\n let same_direction = velocity_a.x * velocity_b.x > 0.;\n\n let faster = speed_ratio_a.x.abs() > speed_ratio_b.x.abs();\n\n if (y_overlapped || overlap.x.abs() <= overlap.y.abs()) && !x_overlapped {\n\n if faster || !same_direction {\n\n correction.x = overlap.x * speed_ratio_a.x;\n", "file_path": "src/components/collision.rs", "rank": 67, "score": 27637.40251660781 }, { "content": "pub fn load_camera_subject(world: &mut World) -> Entity {\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(384., 176., 0.);\n\n\n\n world\n\n .create_entity()\n\n .with(transform)\n\n .with(Subject::default())\n\n .with(Transparent)\n\n .build()\n\n}\n", "file_path": "src/entities/camera_subject.rs", "rank": 68, "score": 26278.207850294988 }, { "content": "pub fn load_camera(world: &mut World, camera_subject: Entity) {\n\n let (width, height) = {\n\n let dim = world.fetch::<ScreenDimensions>();\n\n (dim.width(), dim.height())\n\n };\n\n let mut transform = Transform::default();\n\n transform.set_translation_xyz(0.0, 0.0, 1.0);\n\n\n\n world\n\n .create_entity()\n\n .with(Camera::standard_2d(width, height))\n\n .with(Parent {\n\n entity: camera_subject,\n\n })\n\n .with(transform)\n\n .build();\n\n}\n", "file_path": "src/entities/camera.rs", "rank": 69, "score": 25940.78927638725 }, { "content": "use amethyst::{\n\n ecs::{Entities, Join, LazyUpdate, Read, ReadExpect, ReadStorage, System, WriteStorage},\n\n input::{InputHandler, StringBindings},\n\n};\n\n\n\nuse crate::{\n\n components::{Collider, Direction, Directions, Marine, MarineState, Motion},\n\n entities::spawn_bullet,\n\n resources::{AssetType, Context, SpriteSheetList},\n\n};\n\n\n\npub struct AttackSystem;\n\n\n\nimpl<'s> System<'s> for AttackSystem {\n\n type SystemData = (\n\n Entities<'s>,\n\n ReadStorage<'s, Collider>,\n\n WriteStorage<'s, Marine>,\n\n ReadStorage<'s, Motion>,\n\n ReadStorage<'s, Direction>,\n", "file_path": "src/systems/attack.rs", "rank": 71, "score": 25868.74191071507 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Join, ReadStorage, System, WriteStorage},\n\n};\n\n\n\nuse crate::components::{Collider, Marine, Motion, Parallax};\n\n\n\n#[derive(Default)]\n\npub struct ParallaxSystem;\n\n\n\nimpl<'s> System<'s> for ParallaxSystem {\n\n type SystemData = (\n\n ReadStorage<'s, Parallax>,\n\n ReadStorage<'s, Marine>,\n\n ReadStorage<'s, Motion>,\n\n ReadStorage<'s, Collider>,\n\n WriteStorage<'s, Transform>,\n\n );\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (parallaxes, marines, motions, colliders, mut transforms) = data;\n", "file_path": "src/systems/parallax.rs", "rank": 72, "score": 25867.574425341034 }, { "content": "use amethyst::{\n\n core::math::Vector2,\n\n ecs::{Join, ReadStorage, System, WriteStorage},\n\n};\n\n\n\nuse crate::components::{Collider, Direction, Marine, MarineState, Motion};\n\n\n\npub struct KinematicsSystem;\n\n\n\nimpl<'s> System<'s> for KinematicsSystem {\n\n type SystemData = (WriteStorage<'s, Collider>, ReadStorage<'s, Motion>);\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (mut colliders, motions) = data;\n\n\n\n for (collider, motion) in (&mut colliders, &motions).join() {\n\n let bbox = &mut collider.bounding_box;\n\n bbox.old_position = bbox.position;\n\n bbox.position.x += motion.velocity.x;\n\n bbox.position.y += motion.velocity.y;\n", "file_path": "src/systems/kinematics.rs", "rank": 73, "score": 25866.508403594333 }, { "content": "use amethyst::{\n\n ecs::{Join, Read, System, WriteStorage},\n\n input::{InputHandler, StringBindings},\n\n};\n\n\n\nuse crate::components::{Collider, Direction, Directions, Marine, MarineState};\n\n\n\npub struct MarineInputSystem;\n\n\n\nimpl<'s> System<'s> for MarineInputSystem {\n\n type SystemData = (\n\n WriteStorage<'s, Direction>,\n\n WriteStorage<'s, Marine>,\n\n WriteStorage<'s, Collider>,\n\n Read<'s, InputHandler<StringBindings>>,\n\n );\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (mut dir, mut marines, mut colliders, input) = data;\n\n\n", "file_path": "src/systems/input.rs", "rank": 74, "score": 25864.518690957702 }, { "content": "pub use self::collision::BulletCollisionSystem;\n\npub use self::collision::CollisionSystem;\n\npub use self::collision::FlierCollisionSystem;\n\npub use self::collision::MarineCollisionSystem;\n\npub use self::collision::PincerCollisionSystem;\n\npub use self::death::MarineDeathSystem;\n\npub use self::direction::DirectionSystem;\n\npub use self::flier::FlierAiSystem;\n\npub use self::input::MarineInputSystem;\n\npub use self::kinematics::KinematicsSystem;\n\npub use self::kinematics::MarineKinematicsSystem;\n\npub use self::parallax::ParallaxSystem;\n\npub use self::pincer::PincerAiSystem;\n\npub use self::transformation::BulletTransformationSystem;\n\npub use self::transformation::CameraTransformationSystem;\n\npub use self::transformation::TransformationSystem;\n\npub use self::ui::*;\n", "file_path": "src/systems/mod.rs", "rank": 75, "score": 25862.91309898918 }, { "content": "use amethyst::{\n\n animation::{\n\n get_animation_set, AnimationCommand, AnimationControlSet, AnimationSet, EndControl,\n\n },\n\n ecs::{Entities, Join, ReadStorage, System, WriteStorage},\n\n renderer::SpriteRender,\n\n};\n\n\n\nuse crate::components::{\n\n Animation, AnimationId, BulletImpact, Explosion, Flier, Marine, MarineState, Motion, Pincer,\n\n};\n\n\n\npub struct BulletImpactAnimationSystem;\n\n\n\nimpl<'s> System<'s> for BulletImpactAnimationSystem {\n\n type SystemData = (\n\n Entities<'s>,\n\n ReadStorage<'s, BulletImpact>,\n\n WriteStorage<'s, Animation>,\n\n WriteStorage<'s, AnimationControlSet<AnimationId, SpriteRender>>,\n", "file_path": "src/systems/animation.rs", "rank": 76, "score": 25861.24954449331 }, { "content": "use amethyst::{\n\n core::Transform,\n\n ecs::{Entities, Join, ReadStorage, System},\n\n};\n\n\n\nuse crate::components::Marine;\n\n\n\npub struct MarineDeathSystem;\n\n\n\nimpl<'s> System<'s> for MarineDeathSystem {\n\n type SystemData = (\n\n Entities<'s>,\n\n ReadStorage<'s, Marine>,\n\n ReadStorage<'s, Transform>,\n\n );\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (entities, marines, transforms) = data;\n\n for (entity, _, transform) in (&entities, &marines, &transforms).join() {\n\n if transform.translation().y < -999. {\n\n let _ = entities.delete(entity);\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/death.rs", "rank": 77, "score": 25861.13668411139 }, { "content": "mod animation;\n\nmod attack;\n\nmod collision;\n\nmod death;\n\nmod direction;\n\nmod flier;\n\nmod input;\n\nmod kinematics;\n\nmod parallax;\n\nmod pincer;\n\nmod transformation;\n\nmod ui;\n\n\n\npub use self::animation::AnimationControlSystem;\n\npub use self::animation::BulletImpactAnimationSystem;\n\npub use self::animation::ExplosionAnimationSystem;\n\npub use self::animation::FlierAnimationSystem;\n\npub use self::animation::MarineAnimationSystem;\n\npub use self::animation::PincerAnimationSystem;\n\npub use self::attack::AttackSystem;\n", "file_path": "src/systems/mod.rs", "rank": 79, "score": 25857.890931000227 }, { "content": "\n\n let hbox = &mut collider.hit_box;\n\n hbox.old_position = hbox.position;\n\n collider.set_hit_box_position(motion.velocity);\n\n }\n\n }\n\n}\n\n\n\npub struct MarineKinematicsSystem;\n\n\n\nimpl<'s> System<'s> for MarineKinematicsSystem {\n\n type SystemData = (\n\n WriteStorage<'s, Collider>,\n\n ReadStorage<'s, Direction>,\n\n ReadStorage<'s, Marine>,\n\n WriteStorage<'s, Motion>,\n\n );\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (mut colliders, dirs, marines, mut motions) = data;\n", "file_path": "src/systems/kinematics.rs", "rank": 80, "score": 25857.526055438386 }, { "content": " let mut marine_velocity_x = 0.;\n\n let mut marine_moved = false;\n\n\n\n for (_, motion, collider) in (&marines, &motions, &colliders).join() {\n\n marine_velocity_x = motion.velocity.x;\n\n let bbox = &collider.bounding_box;\n\n marine_moved = (bbox.position.x - bbox.old_position.x).abs() > std::f32::EPSILON;\n\n }\n\n\n\n for (_, transform) in (&parallaxes, &mut transforms).join() {\n\n if marine_moved {\n\n transform.set_translation_x(\n\n transform.translation().x\n\n + marine_velocity_x / (transform.translation().z.abs() * 4. / 10.),\n\n );\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/parallax.rs", "rank": 89, "score": 25854.908942056954 }, { "content": " (&mut marines, &motions, &colliders, &directions).join()\n\n {\n\n let shoot_input = input.action_is_down(\"shoot\").expect(\"shoot action exists\");\n\n\n\n // Currently shooting is possible only when marine is static\n\n if marine.state == MarineState::Shooting && !marine.is_shooting {\n\n marine.is_shooting = true;\n\n\n\n let mut shoot_start_position = 0.;\n\n let bbox = &collider.bounding_box;\n\n if direction.x == Directions::Left {\n\n shoot_start_position = bbox.position.x - 64.;\n\n } else if direction.x == Directions::Right {\n\n shoot_start_position = bbox.position.x + 64.;\n\n }\n\n\n\n let bullet_sprite_sheet_handle =\n\n { sprite_sheet_list.get(AssetType::Bullet).unwrap().clone() };\n\n spawn_bullet(\n\n &entities,\n", "file_path": "src/systems/attack.rs", "rank": 93, "score": 25853.10743914592 }, { "content": " ReadExpect<'s, SpriteSheetList>,\n\n ReadExpect<'s, LazyUpdate>,\n\n Read<'s, InputHandler<StringBindings>>,\n\n ReadExpect<'s, Context>,\n\n );\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (\n\n entities,\n\n colliders,\n\n mut marines,\n\n motions,\n\n directions,\n\n sprite_sheet_list,\n\n lazy_update,\n\n input,\n\n ctx,\n\n ) = data;\n\n\n\n for (mut marine, _, collider, direction) in\n", "file_path": "src/systems/attack.rs", "rank": 94, "score": 25853.089028989103 }, { "content": "\n\n for (collider, dir, marine, motion) in\n\n (&mut colliders, &dirs, &marines, &mut motions).join()\n\n {\n\n let mut acceleration = Vector2::new(0., 0.);\n\n match marine.state {\n\n MarineState::Idling => {\n\n let acceleration_x = if motion.velocity.x != 0. { -0.6 } else { 0. };\n\n acceleration = Vector2::new(acceleration_x, -0.6);\n\n }\n\n MarineState::Running => {\n\n acceleration = Vector2::new(0.6, -0.6);\n\n }\n\n MarineState::Jumping => {\n\n if collider.on_ground {\n\n motion.velocity.y = 14.;\n\n collider.on_ground = false;\n\n }\n\n let acceleration_x = if motion.velocity.x != 0. { -0.06 } else { 0. };\n\n acceleration = Vector2::new(acceleration_x, -0.6);\n", "file_path": "src/systems/kinematics.rs", "rank": 95, "score": 25851.26644513585 }, { "content": " for (dir, marine, collider) in (&mut dir, &mut marines, &mut colliders).join() {\n\n let run_input = input.axis_value(\"run\").expect(\"Run action exists\");\n\n let jump_input = input.action_is_down(\"jump\").expect(\"Jump action exists\");\n\n let shoot_input = input.action_is_down(\"shoot\").expect(\"Shoot action exists\");\n\n\n\n // TODO: check simultaneous button press\n\n marine.state = if !collider.is_collidable {\n\n MarineState::Dying\n\n } else if jump_input || !collider.on_ground {\n\n MarineState::Jumping\n\n } else if run_input > 0. {\n\n dir.x = Directions::Right;\n\n MarineState::Running\n\n } else if run_input < 0. {\n\n dir.x = Directions::Left;\n\n MarineState::Running\n\n } else if shoot_input && marine.state != MarineState::Shooting && !marine.is_shooting {\n\n MarineState::Shooting\n\n } else {\n\n MarineState::Idling\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/input.rs", "rank": 96, "score": 25849.087918018507 }, { "content": " }\n\n }\n\n}\n\n\n\n#[derive(Default)]\n\npub struct FlierAnimationSystem;\n\n\n\nimpl<'s> System<'s> for FlierAnimationSystem {\n\n type SystemData = (\n\n Entities<'s>,\n\n ReadStorage<'s, Flier>,\n\n ReadStorage<'s, Motion>,\n\n WriteStorage<'s, Animation>,\n\n WriteStorage<'s, AnimationControlSet<AnimationId, SpriteRender>>,\n\n );\n\n\n\n fn run(&mut self, data: Self::SystemData) {\n\n let (entities, fliers, motions, mut animations, mut animation_control_sets) = data;\n\n\n\n for (entity, _flier, _motion, mut animation, animation_control_set) in (\n", "file_path": "src/systems/animation.rs", "rank": 97, "score": 25849.004915182428 }, { "content": " }\n\n MarineState::Dying => {\n\n if collider.on_ground {\n\n motion.velocity.x = 0.;\n\n motion.velocity.y = 8.;\n\n collider.on_ground = false;\n\n }\n\n acceleration = Vector2::new(0., -0.6);\n\n }\n\n _ => {}\n\n }\n\n motion.update_velocity(acceleration, dir, 0., marine.max_ground_speed);\n\n }\n\n }\n\n}\n", "file_path": "src/systems/kinematics.rs", "rank": 98, "score": 25848.59605443409 } ]
Rust
day_12/src/main.rs
kimpers/advent-of-code-2020
50750317b691717e211c03c67b99708edccddfc3
use shared; #[derive(Debug)] struct NavigatorV1<'a> { facing_direction: &'a str, north: usize, west: usize, east: usize, south: usize, } impl NavigatorV1<'_> { fn new(facing_direction: &str) -> NavigatorV1 { NavigatorV1 { facing_direction, north: 0, west: 0, east: 0, south: 0, } } fn rotate(&mut self, direction: &str, deg: usize) { let num_shifts = deg / 90; let all_directions = ["N", "E", "S", "W"]; let mut current_idx = all_directions .iter() .position(|&d| d == self.facing_direction) .unwrap(); for _i in 0..num_shifts { match direction { "R" => { current_idx = (current_idx + 1) % all_directions.len(); } "L" => { if current_idx as isize - 1 >= 0 { current_idx -= 1; } else { current_idx = all_directions.len() - 1; } } _ => panic!("Unknown direction {}", direction), } } self.facing_direction = all_directions[current_idx]; } pub fn nav(&mut self, action: &str) { let cmd = &action[0..1]; let distance = action[1..].parse::<usize>().unwrap(); match cmd { "N" => { let new_south = self.south as isize - distance as isize; if new_south > 0 { self.south = new_south as usize; } else { self.north += distance - self.south; self.south = 0; } } "S" => { let new_north = self.north as isize - distance as isize; if new_north > 0 { self.north = new_north as usize; } else { self.south += distance - self.north; self.north = 0; } } "E" => { let new_west = self.west as isize - distance as isize; if new_west > 0 { self.west = new_west as usize; } else { self.east += distance - self.west; self.west = 0; } } "W" => { let new_east = self.east as isize - distance as isize; if new_east > 0 { self.east = new_east as usize; } else { self.west += distance - self.east; self.east = 0; } } "L" | "R" => self.rotate(cmd, distance), "F" => { let new_action = format!("{}{}", self.facing_direction, distance); self.nav(&new_action); } _ => panic!("Unknown command {}", cmd), } } pub fn manhattan_distance(&self) -> usize { self.north + self.west + self.east + self.south } } #[derive(Debug)] struct Point { pub north: usize, pub west: usize, pub east: usize, pub south: usize, } impl Point { pub fn set_direction(&mut self, direction: &str, value: usize) { match direction { "N" => self.north = value, "W" => self.west = value, "E" => self.east = value, "S" => self.south = value, _ => panic!("Unknown direction {}", direction), } } pub fn get_direction(&self, direction: &str) -> usize { match direction { "N" => self.north, "W" => self.west, "E" => self.east, "S" => self.south, _ => panic!("Unknown direction {}", direction), } } } #[derive(Debug)] struct NavigatorV2<'a> { facing_direction: &'a str, ship: Point, waypoint: Point, } impl NavigatorV2<'_> { fn new(facing_direction: &str) -> NavigatorV2 { let ship = Point { north: 0, west: 0, east: 0, south: 0, }; let waypoint = Point { north: 1, west: 0, east: 10, south: 0, }; NavigatorV2 { facing_direction, ship, waypoint, } } fn rotate(&mut self, direction: &str, deg: usize) { let num_shifts = deg / 90; let all_directions = ["N", "E", "S", "W"]; let mut new_waypoint = Point { north: 0, west: 0, east: 0, south: 0, }; for curr_dir in all_directions.iter() { let mut current_idx = all_directions.iter().position(|&d| d == *curr_dir).unwrap(); for _i in 0..num_shifts { match direction { "R" => { current_idx = (current_idx + 1) % all_directions.len(); } "L" => { if current_idx as isize - 1 >= 0 { current_idx -= 1; } else { current_idx = all_directions.len() - 1; } } _ => panic!("Unknown rotation {}", direction), } } let curr_value = self.waypoint.get_direction(curr_dir); let new_direction = all_directions[current_idx]; new_waypoint.set_direction(new_direction, curr_value); } self.waypoint = new_waypoint; } pub fn nav(&mut self, action: &str) { let cmd = &action[0..1]; let amount = action[1..].parse::<usize>().unwrap(); match cmd { "N" => { let new_south = self.waypoint.south as isize - amount as isize; if new_south > 0 { self.waypoint.south = new_south as usize; } else { self.waypoint.north += amount - self.waypoint.south; self.waypoint.south = 0; } } "S" => { let new_north = self.waypoint.north as isize - amount as isize; if new_north > 0 { self.waypoint.north = new_north as usize; } else { self.waypoint.south += amount - self.waypoint.north; self.waypoint.north = 0; } } "E" => { let new_west = self.waypoint.west as isize - amount as isize; if new_west > 0 { self.waypoint.west = new_west as usize; } else { self.waypoint.east += amount - self.waypoint.west; self.waypoint.west = 0; } } "W" => { let new_east = self.waypoint.east as isize - amount as isize; if new_east > 0 { self.waypoint.east = new_east as usize; } else { self.waypoint.west += amount - self.waypoint.east; self.waypoint.east = 0; } } "L" | "R" => self.rotate(cmd, amount), "F" => { self.ship.north = self.ship.north + amount * self.waypoint.north; self.ship.south = self.ship.south + amount * self.waypoint.south; if self.ship.north >= self.ship.south { self.ship.north = self.ship.north - self.ship.south; self.ship.south = 0; } else { self.ship.south = self.ship.south - self.ship.north; self.ship.north = 0; } self.ship.east = self.ship.east + amount * self.waypoint.east; self.ship.west = self.ship.west + amount * self.waypoint.west; if self.ship.east >= self.ship.west { self.ship.east = self.ship.east - self.ship.west; self.ship.west = 0; } else { self.ship.west = self.ship.west - self.ship.east; self.ship.east = 0; } } _ => panic!("Unknown command {}", cmd), } } pub fn manhattan_distance(&self) -> usize { self.ship.north + self.ship.west + self.ship.east + self.ship.south } } fn main() { let actions = shared::read_file("input.txt"); let mut navigator = NavigatorV1::new("E"); for action in actions { navigator.nav(&action); } println!( "Manhattan distance between location and starting position using method 1 is {}", navigator.manhattan_distance() ); let actions = shared::read_file("input.txt"); let mut navigator2 = NavigatorV2::new("E"); for action in actions { navigator2.nav(&action); } println!( "Manhattan distance between location and starting position using method 2 is {}", navigator2.manhattan_distance() ); } #[cfg(test)] mod tests { use super::*; #[test] fn it_calculates_manhattan_distance() { let actions = shared::parse_input_to_string_vec( " F10 N3 F7 R90 F11", ); let mut navigator = NavigatorV1::new("E"); for action in actions { navigator.nav(&action); } assert_eq!(navigator.manhattan_distance(), 25); } #[test] fn it_calculates_v2_manhattan_distance() { let actions = shared::parse_input_to_string_vec( " F10 N3 F7 R90 F11", ); let mut navigator = NavigatorV2::new("E"); for action in actions { navigator.nav(&action); } assert_eq!(navigator.manhattan_distance(), 286); } }
use shared; #[derive(Debug)] struct NavigatorV1<'a> { facing_direction: &'a str, north: usize, west: usize, east: usize, south: usize, } impl NavigatorV1<'_> { fn new(facing_direction: &str) -> NavigatorV1 { NavigatorV1 { facing_direction, north: 0, west: 0, east: 0, south: 0, } } fn rotate(&mut self, direction: &str, deg: usize) { let num_shifts = deg / 90; let all_directions = ["N", "E", "S", "W"]; let mut current_idx = all_directions .iter() .position(|&d| d == self.facing_direction) .unwrap(); for _i in 0..num_shifts { match direction { "R" => { current_idx = (current_idx + 1) % all_directions.len(); } "L" => { if current_idx as isize - 1 >= 0 { current_idx -= 1; } else { current_idx = all_directions.len() - 1; } } _ => panic!("Unknown direction {}", direction), } } self.facing_direction = all_directions[current_idx]; } pub fn nav(&mut self, action: &str) { let cmd = &action[0..1]; let distance = action[1..].parse::<usize>().unwrap(); match cmd { "N" => { let new_south = self.south as isize - distance as isize; if new_south > 0 { self.south = new_south as usize;
println!( "Manhattan distance between location and starting position using method 2 is {}", navigator2.manhattan_distance() ); } #[cfg(test)] mod tests { use super::*; #[test] fn it_calculates_manhattan_distance() { let actions = shared::parse_input_to_string_vec( " F10 N3 F7 R90 F11", ); let mut navigator = NavigatorV1::new("E"); for action in actions { navigator.nav(&action); } assert_eq!(navigator.manhattan_distance(), 25); } #[test] fn it_calculates_v2_manhattan_distance() { let actions = shared::parse_input_to_string_vec( " F10 N3 F7 R90 F11", ); let mut navigator = NavigatorV2::new("E"); for action in actions { navigator.nav(&action); } assert_eq!(navigator.manhattan_distance(), 286); } }
} else { self.north += distance - self.south; self.south = 0; } } "S" => { let new_north = self.north as isize - distance as isize; if new_north > 0 { self.north = new_north as usize; } else { self.south += distance - self.north; self.north = 0; } } "E" => { let new_west = self.west as isize - distance as isize; if new_west > 0 { self.west = new_west as usize; } else { self.east += distance - self.west; self.west = 0; } } "W" => { let new_east = self.east as isize - distance as isize; if new_east > 0 { self.east = new_east as usize; } else { self.west += distance - self.east; self.east = 0; } } "L" | "R" => self.rotate(cmd, distance), "F" => { let new_action = format!("{}{}", self.facing_direction, distance); self.nav(&new_action); } _ => panic!("Unknown command {}", cmd), } } pub fn manhattan_distance(&self) -> usize { self.north + self.west + self.east + self.south } } #[derive(Debug)] struct Point { pub north: usize, pub west: usize, pub east: usize, pub south: usize, } impl Point { pub fn set_direction(&mut self, direction: &str, value: usize) { match direction { "N" => self.north = value, "W" => self.west = value, "E" => self.east = value, "S" => self.south = value, _ => panic!("Unknown direction {}", direction), } } pub fn get_direction(&self, direction: &str) -> usize { match direction { "N" => self.north, "W" => self.west, "E" => self.east, "S" => self.south, _ => panic!("Unknown direction {}", direction), } } } #[derive(Debug)] struct NavigatorV2<'a> { facing_direction: &'a str, ship: Point, waypoint: Point, } impl NavigatorV2<'_> { fn new(facing_direction: &str) -> NavigatorV2 { let ship = Point { north: 0, west: 0, east: 0, south: 0, }; let waypoint = Point { north: 1, west: 0, east: 10, south: 0, }; NavigatorV2 { facing_direction, ship, waypoint, } } fn rotate(&mut self, direction: &str, deg: usize) { let num_shifts = deg / 90; let all_directions = ["N", "E", "S", "W"]; let mut new_waypoint = Point { north: 0, west: 0, east: 0, south: 0, }; for curr_dir in all_directions.iter() { let mut current_idx = all_directions.iter().position(|&d| d == *curr_dir).unwrap(); for _i in 0..num_shifts { match direction { "R" => { current_idx = (current_idx + 1) % all_directions.len(); } "L" => { if current_idx as isize - 1 >= 0 { current_idx -= 1; } else { current_idx = all_directions.len() - 1; } } _ => panic!("Unknown rotation {}", direction), } } let curr_value = self.waypoint.get_direction(curr_dir); let new_direction = all_directions[current_idx]; new_waypoint.set_direction(new_direction, curr_value); } self.waypoint = new_waypoint; } pub fn nav(&mut self, action: &str) { let cmd = &action[0..1]; let amount = action[1..].parse::<usize>().unwrap(); match cmd { "N" => { let new_south = self.waypoint.south as isize - amount as isize; if new_south > 0 { self.waypoint.south = new_south as usize; } else { self.waypoint.north += amount - self.waypoint.south; self.waypoint.south = 0; } } "S" => { let new_north = self.waypoint.north as isize - amount as isize; if new_north > 0 { self.waypoint.north = new_north as usize; } else { self.waypoint.south += amount - self.waypoint.north; self.waypoint.north = 0; } } "E" => { let new_west = self.waypoint.west as isize - amount as isize; if new_west > 0 { self.waypoint.west = new_west as usize; } else { self.waypoint.east += amount - self.waypoint.west; self.waypoint.west = 0; } } "W" => { let new_east = self.waypoint.east as isize - amount as isize; if new_east > 0 { self.waypoint.east = new_east as usize; } else { self.waypoint.west += amount - self.waypoint.east; self.waypoint.east = 0; } } "L" | "R" => self.rotate(cmd, amount), "F" => { self.ship.north = self.ship.north + amount * self.waypoint.north; self.ship.south = self.ship.south + amount * self.waypoint.south; if self.ship.north >= self.ship.south { self.ship.north = self.ship.north - self.ship.south; self.ship.south = 0; } else { self.ship.south = self.ship.south - self.ship.north; self.ship.north = 0; } self.ship.east = self.ship.east + amount * self.waypoint.east; self.ship.west = self.ship.west + amount * self.waypoint.west; if self.ship.east >= self.ship.west { self.ship.east = self.ship.east - self.ship.west; self.ship.west = 0; } else { self.ship.west = self.ship.west - self.ship.east; self.ship.east = 0; } } _ => panic!("Unknown command {}", cmd), } } pub fn manhattan_distance(&self) -> usize { self.ship.north + self.ship.west + self.ship.east + self.ship.south } } fn main() { let actions = shared::read_file("input.txt"); let mut navigator = NavigatorV1::new("E"); for action in actions { navigator.nav(&action); } println!( "Manhattan distance between location and starting position using method 1 is {}", navigator.manhattan_distance() ); let actions = shared::read_file("input.txt"); let mut navigator2 = NavigatorV2::new("E"); for action in actions { navigator2.nav(&action); }
random
[ { "content": "pub fn read_file(filename: &str) -> Vec<String> {\n\n let mut file = File::open(filename).unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n let lines = contents\n\n .lines()\n\n .map(|l| l.to_string())\n\n .collect::<Vec<String>>();\n\n\n\n lines\n\n}\n\n\n", "file_path": "shared/src/lib.rs", "rank": 0, "score": 140607.36606008039 }, { "content": "pub fn parse_input_to_string_vec(input: &str) -> Vec<String> {\n\n input\n\n .split(\"\\n\")\n\n .map(|row| row.trim())\n\n .filter(|row| row.len() > 0)\n\n .map(|r| r.to_string())\n\n .collect::<Vec<String>>()\n\n}\n", "file_path": "shared/src/lib.rs", "rank": 1, "score": 134988.3654185711 }, { "content": "pub fn parse_input_to_character_matrix(input: &str) -> Vec<Vec<String>> {\n\n input\n\n .split(\"\\n\")\n\n .map(|row| row.trim())\n\n .filter(|row| row.len() > 0)\n\n .map(|line| line.chars().map(|c| c.to_string()).collect())\n\n .collect::<Vec<Vec<String>>>()\n\n}\n\n\n", "file_path": "shared/src/lib.rs", "rank": 2, "score": 129645.01458579277 }, { "content": "fn from_binary(binary_representation: &str) -> usize {\n\n usize::from_str_radix(binary_representation, 2).unwrap()\n\n}\n\n\n", "file_path": "day_14/src/main.rs", "rank": 3, "score": 106755.66038004309 }, { "content": "fn find_seat_details(row_encoding: &str) -> (usize, usize) {\n\n let chars = row_encoding\n\n .chars()\n\n .map(|c| c.to_string())\n\n .collect::<Vec<String>>();\n\n let mut start_row = 0;\n\n let mut end_row = 127;\n\n let mut start_col = 0;\n\n let mut end_col = 7;\n\n\n\n for char in chars {\n\n let chr: &str = &char;\n\n let half_row = (end_row - start_row) / 2;\n\n let half_col = (end_col - start_col) / 2;\n\n match chr {\n\n \"F\" => end_row = end_row - half_row - 1,\n\n \"L\" => end_col = end_col - half_col - 1,\n\n \"B\" => start_row = start_row + half_row + 1,\n\n \"R\" => start_col = start_col + half_col + 1,\n\n _ => {\n", "file_path": "day_5/src/main.rs", "rank": 4, "score": 106049.22208003113 }, { "content": "fn parse_input(filename: &str) -> Vec<usize> {\n\n shared::read_file(filename)\n\n .iter()\n\n .map(|line| line.parse::<usize>().unwrap())\n\n .collect::<Vec<usize>>()\n\n}\n\n\n", "file_path": "day_10/src/main.rs", "rank": 5, "score": 102105.16020406979 }, { "content": "fn count_valid_entries(entries: &Vec<String>, validate_fn: &dyn Fn(&str) -> bool) -> usize {\n\n entries.iter().filter(|entry| validate_fn(entry)).count()\n\n}\n\n\n", "file_path": "day_4/src/main.rs", "rank": 6, "score": 98077.61800725227 }, { "content": "fn apply_mask_to_value(mask: &str, value: usize) -> String {\n\n let mask_chars = mask.chars().rev().collect::<Vec<char>>();\n\n let binary_value = parse_to_36bit_binary(value);\n\n let binary_value_chars = binary_value.chars().rev().collect::<Vec<char>>();\n\n\n\n let mut masked_binary_value = String::from(\"\");\n\n for i in 0..mask.len() {\n\n let curr: &str = &mask_chars[i].to_string().to_owned();\n\n let new_bit: String = match curr {\n\n \"X\" => binary_value_chars[i].to_string(),\n\n \"0\" => \"0\".to_string(),\n\n \"1\" => \"1\".to_string(),\n\n _ => panic!(\"Unhandled char\"),\n\n };\n\n\n\n masked_binary_value.push_str(&new_bit)\n\n }\n\n\n\n return masked_binary_value.chars().rev().collect::<String>();\n\n}\n\n\n", "file_path": "day_14/src/main.rs", "rank": 7, "score": 95742.23535588928 }, { "content": "fn apply_mask_to_memory_address(mask: &str, memory_address: usize) -> Vec<String> {\n\n let mask_chars = mask.chars().rev().collect::<Vec<char>>();\n\n let binary_memory_address = parse_to_36bit_binary(memory_address);\n\n let binary_memory_address_chars = binary_memory_address.chars().rev().collect::<Vec<char>>();\n\n\n\n let mut masked_binary_addresses = vec![String::from(\"\")];\n\n for i in 0..mask.len() {\n\n masked_binary_addresses =\n\n masked_binary_addresses\n\n .iter()\n\n .fold(vec![], |mut memo, curr_adr| {\n\n let curr: &str = &mask_chars[i].to_string().to_owned();\n\n\n\n match curr {\n\n \"X\" => {\n\n memo.push(format!(\"{}{}\", curr_adr, 1));\n\n memo.push(format!(\"{}{}\", curr_adr, 0));\n\n }\n\n \"0\" => {\n\n memo.push(format!(\"{}{}\", curr_adr, binary_memory_address_chars[i]));\n", "file_path": "day_14/src/main.rs", "rank": 8, "score": 88347.10360412666 }, { "content": "fn execute_until_loop(tm: &mut TuringMachine) {\n\n let mut set: HashSet<usize> = HashSet::new();\n\n\n\n loop {\n\n match set.get(&tm.instruction_counter) {\n\n Some(_instruction) => return,\n\n None => {\n\n set.insert(tm.instruction_counter);\n\n tm.execute(true);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "day_8/src/main.rs", "rank": 9, "score": 82360.11864991375 }, { "content": "fn has_all_required_fields(entry: &str) -> bool {\n\n let required_fields = [\"byr\", \"iyr\", \"eyr\", \"hgt\", \"hcl\", \"ecl\", \"pid\"];\n\n\n\n required_fields.iter().all(|field| entry.contains(field))\n\n}\n\n\n", "file_path": "day_4/src/main.rs", "rank": 10, "score": 82198.10340090757 }, { "content": "#[allow(unused_assignments)]\n\nfn find_terminating_sequence(tm: &mut TuringMachine) {\n\n let mut set: HashSet<usize> = HashSet::new();\n\n let mut skippable_instructions = vec![];\n\n\n\n loop {\n\n match set.get(&tm.instruction_counter) {\n\n Some(_instruction) => break,\n\n None => {\n\n let code = &tm.execution_code[tm.instruction_counter];\n\n if code.contains(\"nop\") || code.contains(\"jmp\") {\n\n skippable_instructions.push(tm.instruction_counter);\n\n }\n\n set.insert(tm.instruction_counter);\n\n tm.execute(true);\n\n }\n\n }\n\n }\n\n\n\n let mut is_loop = false;\n\n for skippable in skippable_instructions {\n", "file_path": "day_8/src/main.rs", "rank": 11, "score": 80835.41537372881 }, { "content": "fn has_valid_field_data(entry: &str) -> bool {\n\n let cleaned_entry = entry.replace(\"\\n\", \" \");\n\n\n\n let fields: HashMap<&str, &str> =\n\n cleaned_entry\n\n .split(\" \")\n\n .fold(HashMap::new(), |mut map, raw_entry| {\n\n let kv_pairs = raw_entry.split(\" \");\n\n\n\n for kv_pair in kv_pairs {\n\n let kv = kv_pair.split(\":\").collect::<Vec<&str>>();\n\n if kv.len() == 2 {\n\n map.insert(kv[0], kv[1]);\n\n }\n\n }\n\n\n\n map\n\n });\n\n\n\n match fields.get(\"byr\") {\n", "file_path": "day_4/src/main.rs", "rank": 12, "score": 80584.5307372782 }, { "content": "fn count_bags_that_can_fit_color(bag_rule_map: &HashMap<String, Bag>, bag_color: &str) -> usize {\n\n let mut count = 0;\n\n for (_key, bag) in bag_rule_map.iter() {\n\n if bag.can_fit_color(&bag_rule_map, bag_color) == true {\n\n count += 1;\n\n }\n\n }\n\n\n\n return count;\n\n}\n\n\n", "file_path": "day_7/src/main.rs", "rank": 13, "score": 79263.14575393719 }, { "content": "fn parse_input_file(filename: &str) -> Vec<String> {\n\n let mut file = File::open(filename).unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n\n\n let entries = contents\n\n .split(\"\\n\\n\")\n\n .map(|entry| entry.to_string())\n\n .collect::<Vec<String>>();\n\n entries\n\n}\n\n\n", "file_path": "day_4/src/main.rs", "rank": 14, "score": 76867.97421909751 }, { "content": "fn parse_input_file(filename: &str) -> Vec<Vec<String>> {\n\n let mut file = File::open(filename).unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n let lines = contents.lines().collect::<Vec<&str>>();\n\n\n\n let matrix = lines.iter().fold(vec![], |mut rows, line| {\n\n let char_row = line.chars().map(|c| c.to_string()).collect::<Vec<String>>();\n\n\n\n rows.push(char_row);\n\n\n\n rows\n\n });\n\n\n\n matrix\n\n}\n\n\n", "file_path": "day_3/src/main.rs", "rank": 16, "score": 73513.35912019707 }, { "content": "fn parse_seating_layout(filename: &str) -> Vec<Vec<String>> {\n\n let lines = shared::read_file(filename);\n\n\n\n lines\n\n .iter()\n\n .map(|line| line.chars().map(|c| c.to_string()).collect())\n\n .collect::<Vec<Vec<String>>>()\n\n}\n\n\n", "file_path": "day_11/src/main.rs", "rank": 17, "score": 73513.35912019707 }, { "content": "fn parse_groups_from_file(filename: &str) -> Vec<Vec<String>> {\n\n let lines = shared::read_file(filename);\n\n let mut groups: Vec<Vec<String>> = vec![];\n\n let mut current_group = vec![];\n\n\n\n for line in lines {\n\n if line == \"\" {\n\n if current_group.len() > 0 {\n\n groups.push(current_group);\n\n }\n\n\n\n current_group = vec![];\n\n } else {\n\n current_group.push(line)\n\n }\n\n }\n\n\n\n // Last group\n\n groups.push(current_group);\n\n\n\n groups\n\n}\n\n\n", "file_path": "day_6/src/main.rs", "rank": 18, "score": 73513.35912019707 }, { "content": "fn parse_rules_to_map(rules: &Vec<&str>) -> HashMap<String, Bag> {\n\n let mut bag_rule_map: HashMap<String, Bag> = HashMap::new();\n\n\n\n for rule in rules {\n\n let bag = Bag::parse_luggage_rule(rule);\n\n\n\n let color = bag.color.clone();\n\n bag_rule_map.insert(color, bag);\n\n }\n\n\n\n bag_rule_map\n\n}\n\n\n", "file_path": "day_7/src/main.rs", "rank": 19, "score": 69218.94315832647 }, { "content": "fn calculate_seat_id((row, col): (usize, usize)) -> usize {\n\n row * 8 + col\n\n}\n\n\n", "file_path": "day_5/src/main.rs", "rank": 20, "score": 68528.4423532565 }, { "content": "fn calculate_diff_multiplier(adaptors: &Vec<usize>) -> usize {\n\n let outlet_joltage = 0;\n\n let device_joltage = adaptors.iter().max().unwrap() + 3;\n\n\n\n let mut sorted_adaptors = adaptors.clone();\n\n sorted_adaptors.sort();\n\n\n\n let mut all_adaptors = vec![outlet_joltage];\n\n for adaptor in sorted_adaptors {\n\n all_adaptors.push(adaptor)\n\n }\n\n all_adaptors.push(device_joltage);\n\n\n\n let mut one_diff_count = 0;\n\n let mut three_diff_count = 0;\n\n\n\n for i in 0..all_adaptors.len() - 1 {\n\n if all_adaptors[i] + 1 == all_adaptors[i + 1] {\n\n one_diff_count += 1;\n\n } else if all_adaptors[i] + 3 == all_adaptors[i + 1] {\n\n three_diff_count += 1;\n\n }\n\n }\n\n\n\n one_diff_count * three_diff_count\n\n}\n\n\n", "file_path": "day_10/src/main.rs", "rank": 21, "score": 66313.18785634948 }, { "content": "fn calculate_adapter_configurations(adaptors: &Vec<usize>) -> usize {\n\n let outlet_joltage = 0;\n\n let device_joltage = adaptors.iter().max().unwrap() + 3;\n\n\n\n let mut sorted_adaptors = adaptors.clone();\n\n sorted_adaptors.sort();\n\n\n\n let mut all_adaptors = vec![outlet_joltage];\n\n for adaptor in sorted_adaptors {\n\n all_adaptors.push(adaptor)\n\n }\n\n all_adaptors.push(device_joltage);\n\n\n\n let mut product = 1;\n\n let mut consecutive_numbers = 0;\n\n for i in 1..all_adaptors.len() {\n\n let prev = all_adaptors[i - 1] as isize;\n\n let curr = all_adaptors[i] as isize;\n\n\n\n match curr - prev {\n", "file_path": "day_10/src/main.rs", "rank": 22, "score": 66313.18785634948 }, { "content": "fn multiplier_for_consecutive_nums(consecutive_num_count: usize) -> usize {\n\n match consecutive_num_count {\n\n 0 => return 1,\n\n 1 => return 1,\n\n 2 => return 2,\n\n 3 => return 4,\n\n 4 => return 7, // HACK: Input file contains max 4 consecutive numbers\n\n _ => panic!(\"Not handled count of {}\", consecutive_num_count),\n\n }\n\n}\n\n\n", "file_path": "day_10/src/main.rs", "rank": 23, "score": 65868.48289748302 }, { "content": "fn check_item(item: &String, (num_vacant, num_taken): (usize, usize)) -> (usize, usize) {\n\n if item == \"L\" {\n\n return (num_vacant + 1, num_taken);\n\n } else if item == \"#\" {\n\n return (num_vacant, num_taken + 1);\n\n }\n\n\n\n (num_vacant, num_taken)\n\n}\n\n\n", "file_path": "day_11/src/main.rs", "rank": 24, "score": 65032.02109136071 }, { "content": "fn find_first_non_empty_seat_in_direction(\n\n layout: &Vec<Vec<String>>,\n\n start_row: usize,\n\n start_col: usize,\n\n row_direction: Direction,\n\n col_direction: Direction,\n\n) -> (usize, usize) {\n\n let row_length = layout.len();\n\n let col_length = layout[0].len();\n\n\n\n let mut current_row = start_row;\n\n let mut current_col = start_col;\n\n\n\n loop {\n\n let new_row: isize = current_row as isize + row_direction as isize;\n\n let new_col: isize = current_col as isize + col_direction as isize;\n\n\n\n if new_row < 0 || new_row >= row_length as isize {\n\n return (current_row, current_col);\n\n } else if new_col < 0 || new_col >= col_length as isize {\n", "file_path": "day_11/src/main.rs", "rank": 25, "score": 64741.55591119232 }, { "content": "fn trees_for_paths_multiplied(map: &Vec<Vec<String>>, paths: &Vec<(usize, usize)>) -> usize {\n\n let tree_counts = paths.iter().fold(1, |counts, paths| {\n\n counts * count_trees(map, paths.0, paths.1)\n\n });\n\n\n\n tree_counts\n\n}\n\n\n", "file_path": "day_3/src/main.rs", "rank": 26, "score": 61551.98354687508 }, { "content": "fn count_trees(map: &Vec<Vec<String>>, right_count: usize, down_count: usize) -> usize {\n\n let max_cols = map[0].len();\n\n let max_rows = map.len();\n\n\n\n let mut num_trees = 0;\n\n let mut i = 0;\n\n let mut j = 0;\n\n while i < max_rows {\n\n if map[i][j] == \"#\" {\n\n num_trees += 1;\n\n }\n\n\n\n j = (j + right_count) % max_cols;\n\n i += down_count;\n\n }\n\n\n\n num_trees\n\n}\n\n\n", "file_path": "day_3/src/main.rs", "rank": 27, "score": 61551.98354687508 }, { "content": "fn find_available_seat_id(sorted_seat_ids: &Vec<usize>) -> Option<usize> {\n\n let mut i = 0;\n\n while i < sorted_seat_ids.len() - 1 {\n\n if sorted_seat_ids[i] + 1 != sorted_seat_ids[i + 1] {\n\n let available_seat_id = sorted_seat_ids[i] + 1;\n\n return Some(available_seat_id);\n\n }\n\n i += 1;\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "day_5/src/main.rs", "rank": 28, "score": 60450.82494604255 }, { "content": "fn parse_to_36bit_binary(value: usize) -> String {\n\n let binary_representation = format!(\"{:036b}\", value);\n\n\n\n binary_representation\n\n}\n\n\n", "file_path": "day_14/src/main.rs", "rank": 29, "score": 60417.62019076141 }, { "content": "fn count_occupied(layout: &Vec<Vec<String>>) -> usize {\n\n let mut count = 0;\n\n for row in layout {\n\n for seat in row {\n\n if seat == \"#\" {\n\n count += 1;\n\n }\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "day_11/src/main.rs", "rank": 30, "score": 57184.57783730395 }, { "content": "fn count_any_yes_anwer(group_answers: &Vec<String>) -> usize {\n\n let mut unique_answers = HashSet::new();\n\n\n\n for person_answers in group_answers {\n\n for answer in person_answers.chars() {\n\n unique_answers.insert(answer);\n\n }\n\n }\n\n\n\n unique_answers.len()\n\n}\n\n\n", "file_path": "day_6/src/main.rs", "rank": 31, "score": 56583.56849200472 }, { "content": "fn count_all_yes_anwer(group_answers: &Vec<String>) -> usize {\n\n let mut answer_count = HashMap::new();\n\n\n\n for person_answers in group_answers {\n\n for answer in person_answers.chars() {\n\n match answer_count.get_mut(&answer) {\n\n Some(count) => {\n\n *count += 1;\n\n }\n\n _ => {\n\n answer_count.insert(answer, 1);\n\n }\n\n }\n\n }\n\n }\n\n\n\n let num_participants = group_answers.len();\n\n answer_count\n\n .iter()\n\n .filter(|(_key, value)| **value == num_participants)\n\n .count()\n\n}\n\n\n", "file_path": "day_6/src/main.rs", "rank": 32, "score": 56583.56849200472 }, { "content": "fn decode_program(lines: &Vec<String>, version: Version) -> usize {\n\n let mut mem_map = HashMap::new();\n\n let mut mask = \"\";\n\n for line in lines {\n\n let line_items = line.split(\"=\").collect::<Vec<&str>>();\n\n let instruction = line_items[0].trim();\n\n let value = line_items[1].trim();\n\n\n\n match instruction {\n\n \"mask\" => {\n\n mask = value;\n\n }\n\n mem => {\n\n let mem_idx = mem.split(\"[\").collect::<Vec<&str>>()[1]\n\n .replace(\"]\", \"\")\n\n .parse::<usize>()\n\n .unwrap();\n\n\n\n let value_numeric = value.parse::<usize>().unwrap();\n\n match version {\n", "file_path": "day_14/src/main.rs", "rank": 33, "score": 55058.37602112391 }, { "content": "#[derive(Debug)]\n\nstruct Bag {\n\n pub color: String,\n\n pub contents: Vec<BagContent>,\n\n}\n", "file_path": "day_7/src/main.rs", "rank": 35, "score": 55015.5885905051 }, { "content": "#[derive(Debug)]\n\nstruct Timetable {\n\n pub timestamp: usize,\n\n pub notes: Vec<String>,\n\n}\n\n\n\nimpl Timetable {\n\n pub fn read_from_file(filename: &str) -> Timetable {\n\n let contents = shared::read_file(filename);\n\n let timestamp = contents[0].parse::<usize>().unwrap();\n\n let notes = contents[1].split(\",\").collect::<Vec<&str>>();\n\n\n\n Timetable {\n\n timestamp,\n\n notes: notes.iter().map(|e| e.to_string()).collect::<Vec<String>>(),\n\n }\n\n }\n\n\n\n pub fn find_earliest_matching_bus(&self) -> (usize, usize) {\n\n let valid_bus_ids = self\n\n .notes\n", "file_path": "day_13/src/main.rs", "rank": 36, "score": 55015.5885905051 }, { "content": "#[derive(Debug)]\n\nstruct Password {\n\n start: usize,\n\n end: usize,\n\n requirement: String,\n\n password: String,\n\n}\n\n\n\nimpl Password {\n\n pub fn parse_password(line: &str) -> Password {\n\n let results = line.split(\" \").collect::<Vec<&str>>();\n\n assert!(results.len() == 3, \"could not parse password line\");\n\n let requirements = results[0]\n\n .split(\"-\")\n\n .map(|r| r.trim())\n\n .collect::<Vec<&str>>();\n\n assert!(requirements.len() == 2, \"invalid password requirements\");\n\n let (start, end) = (\n\n requirements[0].parse().unwrap(),\n\n requirements[1].parse().unwrap(),\n\n );\n", "file_path": "day_2/src/main.rs", "rank": 37, "score": 55015.5885905051 }, { "content": "#[derive(Debug)]\n\nstruct BagContent {\n\n pub color: String,\n\n pub amount: usize,\n\n}\n\n\n\nimpl Bag {\n\n pub fn parse_luggage_rule(rule: &str) -> Bag {\n\n let splt = rule.split(\" contain \").collect::<Vec<&str>>();\n\n let bag_color = splt[0].replace(\" bags\", \"\");\n\n\n\n let contains_strs = splt[1]\n\n .split(\",\")\n\n .map(|text| {\n\n text.replace(\"bags\", \"\")\n\n .replace(\"bag\", \"\")\n\n .replace(\".\", \"\")\n\n .trim()\n\n .to_string()\n\n })\n\n .collect::<Vec<String>>();\n", "file_path": "day_7/src/main.rs", "rank": 38, "score": 53885.92345326855 }, { "content": "struct XMASCypher {\n\n pub data: Vec<usize>,\n\n pub preamble_length: usize,\n\n}\n\n\n\nimpl XMASCypher {\n\n fn parse_cypher(filename: &str, preamble_length: usize) -> XMASCypher {\n\n let data = shared::read_file(filename)\n\n .iter()\n\n .map(|line| line.trim().parse::<usize>().unwrap())\n\n .collect::<Vec<usize>>();\n\n\n\n XMASCypher {\n\n data,\n\n preamble_length,\n\n }\n\n }\n\n\n\n fn has_pair_with_sum(&self, numbers: &[usize], desired_sum: usize) -> bool {\n\n for i in 0..numbers.len() {\n", "file_path": "day_9/src/main.rs", "rank": 39, "score": 53885.92345326855 }, { "content": "#[derive(Debug)]\n\nstruct SequenceMemory {\n\n turn_spoken: HashMap<usize, usize>,\n\n pub turn: usize,\n\n pub next_num: usize,\n\n}\n\n\n\nimpl SequenceMemory {\n\n fn new(initial_sequence: Vec<usize>) -> SequenceMemory {\n\n let mut turn = 1 as usize;\n\n let mut turn_spoken: HashMap<usize, usize> = HashMap::new();\n\n let mut next_num = 0;\n\n\n\n for num in initial_sequence {\n\n turn_spoken.insert(num, turn);\n\n turn += 1;\n\n next_num = num;\n\n }\n\n\n\n SequenceMemory {\n\n turn,\n", "file_path": "day_15/src/main.rs", "rank": 40, "score": 53885.92345326855 }, { "content": "#[derive(Debug)]\n\nstruct TuringMachine<'a> {\n\n pub instruction_counter: usize,\n\n pub accumulator: isize,\n\n\n\n pub execution_code: &'a Vec<String>,\n\n}\n\n\n\nimpl TuringMachine<'_> {\n\n fn new<'a>(execution_code: &'a Vec<String>) -> TuringMachine<'a> {\n\n TuringMachine {\n\n instruction_counter: 0,\n\n accumulator: 0,\n\n execution_code,\n\n }\n\n }\n\n\n\n pub fn execute(&mut self, persist: bool) -> (usize, isize) {\n\n let data = self.execution_code[self.instruction_counter]\n\n .split(\" \")\n\n .collect::<Vec<&str>>();\n", "file_path": "day_8/src/main.rs", "rank": 42, "score": 51812.666150914476 }, { "content": "fn find_matching_number_pair(arr: &Vec<i32>, desired_sum: i32) -> Option<i32> {\n\n let mut sorted = arr.clone();\n\n sorted.sort();\n\n\n\n let mut reverse_sorted = sorted.clone();\n\n reverse_sorted.reverse();\n\n\n\n for expense_low in sorted.iter() {\n\n for expense_high in reverse_sorted.iter() {\n\n if expense_high + expense_low == desired_sum {\n\n return Some(expense_high * expense_low);\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "day_1/src/main.rs", "rank": 43, "score": 50079.59677818556 }, { "content": "fn find_matching_3_number_sequence(arr: &Vec<i32>, desired_sum: i32) -> Option<i32> {\n\n // NOTE: assumption numbers are unique. Holds true for test set but in reality duplicates would\n\n // be expected\n\n let numbers_set: HashSet<i32> = HashSet::from_iter(arr.iter().cloned());\n\n\n\n for (i, expense) in arr.iter().enumerate() {\n\n for j in i + 1..arr.len() {\n\n let expense_2 = arr[j];\n\n\n\n let remaining = desired_sum - expense - expense_2;\n\n if numbers_set.contains(&remaining) {\n\n return Some(expense * expense_2 * remaining);\n\n }\n\n }\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "day_1/src/main.rs", "rank": 44, "score": 50079.59677818556 }, { "content": "fn main() {\n\n let timetable = Timetable::read_from_file(\"input.txt\");\n\n let (timestamp, bus_number) = timetable.find_earliest_matching_bus();\n\n let timing_value = timetable.calc_timing_value(timestamp, bus_number);\n\n println!(\"Schedule timing value is {}\", timing_value)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_parses_the_time_table() {\n\n let timetable = Timetable::read_from_file(\"test_input.txt\");\n\n println!(\"{:?}\", timetable);\n\n assert_eq!(timetable.timestamp, 939);\n\n assert_eq!(timetable.notes.join(\",\"), \"7,13,x,x,59,x,31,19\");\n\n }\n\n\n\n #[test]\n", "file_path": "day_13/src/main.rs", "rank": 45, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let cypher = XMASCypher::parse_cypher(\"input.txt\", 25);\n\n let invalid_num = cypher.find_invalid();\n\n println!(\"Invalid number in cypher is {}\", invalid_num);\n\n\n\n let weakness_num = cypher.find_weakness();\n\n println!(\"Cypher weakness number is {}\", weakness_num);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_parses_input() {\n\n let cypher = XMASCypher::parse_cypher(\"test_input.txt\", 5);\n\n assert_eq!(cypher.data.len(), 20);\n\n assert_eq!(cypher.data[0], 35);\n\n assert_eq!(cypher.data[19], 576);\n\n assert_eq!(cypher.preamble_length, 5);\n", "file_path": "day_9/src/main.rs", "rank": 46, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let instructions = shared::read_file(\"input.txt\");\n\n let mut tm = TuringMachine::new(&instructions);\n\n\n\n execute_until_loop(&mut tm);\n\n println!(\"The accumulator value is {} before loop\", tm.accumulator);\n\n\n\n let mut tm = TuringMachine::new(&instructions);\n\n find_terminating_sequence(&mut tm);\n\n println!(\n\n \"The accumulator value is {} after successful execution\",\n\n tm.accumulator\n\n );\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n", "file_path": "day_8/src/main.rs", "rank": 47, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let mut seq = SequenceMemory::new(vec![0, 13, 1, 16, 6, 17]);\n\n let spoken_num = seq.play_rounds(2020);\n\n println!(\"2020th spoken num is {}\", spoken_num);\n\n\n\n // TODO: optimized solution\n\n let mut seq = SequenceMemory::new(vec![0, 13, 1, 16, 6, 17]);\n\n let spoken_num = seq.play_rounds(30000000);\n\n println!(\"30000000th spoken num is {}\", spoken_num);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_reads_initial_sequence() {\n\n let seq = SequenceMemory::new(vec![3, 1, 2]);\n\n assert_eq!(seq.turn, 4);\n\n assert_eq!(seq.next_num, 2);\n", "file_path": "day_15/src/main.rs", "rank": 48, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let lines = shared::read_file(\"input.txt\");\n\n let rules = lines.iter().map(|s| &**s).collect::<Vec<&str>>();\n\n let rules_map = parse_rules_to_map(&rules);\n\n\n\n let bags_that_can_fit_count = count_bags_that_can_fit_color(&rules_map, \"shiny gold\");\n\n println!(\n\n \"Num bags that can fit a shiny gold bag {}\",\n\n bags_that_can_fit_count\n\n );\n\n\n\n let bag = rules_map.get(\"shiny gold\").unwrap();\n\n let num_bags_inside = bag.count_total_num_bags(&rules_map);\n\n println!(\"Num bags inside a shiny gold bag {}\", num_bags_inside);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n", "file_path": "day_7/src/main.rs", "rank": 49, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let mut file = File::open(\"input.txt\").unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n let expenses: Vec<i32> = contents\n\n .lines()\n\n .map(|line| line.trim().parse::<i32>().unwrap())\n\n .collect();\n\n\n\n let desired_sum = 2020;\n\n println!(\"Results\");\n\n println!(\n\n \"2 numbers {}\",\n\n find_matching_number_pair(&expenses, desired_sum).unwrap()\n\n );\n\n println!(\n\n \"3 numbers {}\",\n\n find_matching_3_number_sequence(&expenses, desired_sum).unwrap()\n\n );\n", "file_path": "day_1/src/main.rs", "rank": 51, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let adaptors = parse_input(\"input.txt\");\n\n let multiplier = calculate_diff_multiplier(&adaptors);\n\n println!(\"The 1 and 3 jolt diff multiplier is {}\", multiplier);\n\n\n\n let max_configs = calculate_adapter_configurations(&adaptors);\n\n println!(\"Max different configurations {}\", max_configs);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_calculates_the_adaptor_chain() {\n\n let adaptors = parse_input(\"test_input.txt\");\n\n assert_eq!(calculate_diff_multiplier(&adaptors), 220);\n\n }\n\n\n\n #[test]\n\n fn it_calculates_the_different_configurations() {\n\n let adaptors = parse_input(\"test_input.txt\");\n\n assert_eq!(calculate_adapter_configurations(&adaptors), 19208);\n\n }\n\n}\n", "file_path": "day_10/src/main.rs", "rank": 52, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let layout = parse_seating_layout(\"input.txt\");\n\n let mut new_layout = layout.clone();\n\n loop {\n\n let result = update_seating(&new_layout, &check_adjacent_seats, 4);\n\n new_layout = result.0;\n\n let has_changed = result.1;\n\n if has_changed == false {\n\n break;\n\n }\n\n }\n\n let num_occupied_seats = count_occupied(&new_layout);\n\n println!(\"Num occupied seats in stable layout {}\", num_occupied_seats);\n\n\n\n let mut new_layout = layout.clone();\n\n loop {\n\n let result = update_seating(&new_layout, &check_non_empty_adjacent_seats, 5);\n\n new_layout = result.0;\n\n let has_changed = result.1;\n\n if has_changed == false {\n", "file_path": "day_11/src/main.rs", "rank": 53, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let mut file = File::open(\"input.txt\").unwrap();\n\n let mut contents = String::new();\n\n\n\n file.read_to_string(&mut contents).unwrap();\n\n let lines = contents.lines().collect::<Vec<&str>>();\n\n let num_valid_old_rule = lines\n\n .clone()\n\n .into_iter()\n\n .filter(|line| Password::parse_password(line).is_valid_old_rule())\n\n .count();\n\n\n\n let num_valid_new_rule = lines\n\n .clone()\n\n .into_iter()\n\n .filter(|line| Password::parse_password(line).is_valid_new_rule())\n\n .count();\n\n\n\n println!(\"# valid passwords {} with the old rule\", num_valid_old_rule);\n\n println!(\"# valid passwords {} with the new rule\", num_valid_new_rule);\n", "file_path": "day_2/src/main.rs", "rank": 54, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let groups = parse_groups_from_file(\"input.txt\");\n\n\n\n let answer_counts_any_yes = groups\n\n .iter()\n\n .map(|group| count_any_yes_anwer(group))\n\n .collect::<Vec<usize>>();\n\n let answer_sum_any_yes: usize = answer_counts_any_yes.iter().sum();\n\n println!(\"Sum of any yes answers {}\", answer_sum_any_yes);\n\n\n\n let answer_counts_all_yes = groups\n\n .iter()\n\n .map(|group| count_all_yes_anwer(group))\n\n .collect::<Vec<usize>>();\n\n let answer_sum_all_yes: usize = answer_counts_all_yes.iter().sum();\n\n println!(\"Sum of all yes answers {}\", answer_sum_all_yes)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "day_6/src/main.rs", "rank": 55, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let entries = parse_input_file(\"input.txt\");\n\n let num_valid_field_entries = count_valid_entries(&entries, &has_all_required_fields);\n\n println!(\n\n \"Number of entries with all required keys: {}\",\n\n num_valid_field_entries\n\n );\n\n let num_valid_data_entries = count_valid_entries(&entries, &has_valid_field_data);\n\n println!(\n\n \"Number of entries with valid data: {}\",\n\n num_valid_data_entries\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 it_parses_correct_number_of_entries() {\n", "file_path": "day_4/src/main.rs", "rank": 56, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let map = parse_input_file(\"input.txt\");\n\n let num_trees = count_trees(&map, 3, 1);\n\n\n\n println!(\"Num trees {} on single path\", num_trees);\n\n\n\n let paths = vec![(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)];\n\n let multiplied_count = trees_for_paths_multiplied(&map, &paths);\n\n println!(\n\n \"The product of tree counts for multiple paths is {}\",\n\n multiplied_count\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 it_parses_the_input_correctly() {\n", "file_path": "day_3/src/main.rs", "rank": 57, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let boarding_passes = shared::read_file(\"input.txt\");\n\n let mut seat_ids = boarding_passes\n\n .iter()\n\n .map(|pass| {\n\n let seat_details = find_seat_details(pass);\n\n\n\n calculate_seat_id(seat_details)\n\n })\n\n .collect::<Vec<usize>>();\n\n\n\n seat_ids.sort();\n\n\n\n let highest_seat_id = seat_ids[seat_ids.len() - 1];\n\n\n\n println!(\"Highest seat id: {}\", highest_seat_id);\n\n\n\n if let Some(available_seat_id) = find_available_seat_id(&seat_ids) {\n\n println!(\"Available seat id: {}\", available_seat_id)\n\n }\n", "file_path": "day_5/src/main.rs", "rank": 58, "score": 44942.153098541276 }, { "content": "fn main() {\n\n let lines = shared::read_file(\"input.txt\");\n\n let decoded_sum_v1 = decode_program(&lines, Version::V1);\n\n println!(\"Decoded value sum is {} for version v1\", decoded_sum_v1);\n\n\n\n let decoded_sum_v2 = decode_program(&lines, Version::V2);\n\n println!(\"Decoded value sum is {} for version v2\", decoded_sum_v2);\n\n}\n\n\n", "file_path": "day_14/src/main.rs", "rank": 59, "score": 44942.153098541276 }, { "content": "fn update_seating(\n\n layout: &Vec<Vec<String>>,\n\n check_adjacent_seats: &dyn Fn(&Vec<Vec<String>>, usize, usize) -> (usize, usize),\n\n num_taken_limit: usize,\n\n) -> (Vec<Vec<String>>, bool) {\n\n let mut new_layout = vec![];\n\n let mut has_changed = false;\n\n for current_row_num in 0..layout.len() {\n\n let current_row = &layout[current_row_num];\n\n let mut new_row = vec![];\n\n for current_col_num in 0..current_row.len() {\n\n let (_num_vacant, num_taken) =\n\n check_adjacent_seats(layout, current_row_num, current_col_num);\n\n let item = &current_row[current_col_num];\n\n if item == \"L\" && num_taken == 0 {\n\n has_changed = true;\n\n new_row.push(\"#\".to_string());\n\n } else if item == \"#\" && num_taken >= num_taken_limit {\n\n has_changed = true;\n\n new_row.push(\"L\".to_string());\n\n } else {\n\n new_row.push(item.to_string());\n\n }\n\n }\n\n new_layout.push(new_row);\n\n }\n\n\n\n (new_layout, has_changed)\n\n}\n\n\n", "file_path": "day_11/src/main.rs", "rank": 60, "score": 43892.38238066474 }, { "content": "fn check_adjacent_seats(\n\n layout: &Vec<Vec<String>>,\n\n curr_item_row: usize,\n\n curr_item_col: usize,\n\n) -> (usize, usize) {\n\n let mut counts = (0, 0);\n\n\n\n // Row before\n\n if curr_item_row > 0 {\n\n let prev_row = &layout[curr_item_row - 1];\n\n\n\n // Col to the left\n\n if curr_item_col > 0 {\n\n let item = &prev_row[curr_item_col - 1];\n\n counts = check_item(item, counts);\n\n }\n\n\n\n // Same col\n\n let item = &prev_row[curr_item_col];\n\n counts = check_item(item, counts);\n", "file_path": "day_11/src/main.rs", "rank": 61, "score": 42921.43190250093 }, { "content": "fn check_non_empty_adjacent_seats(\n\n layout: &Vec<Vec<String>>,\n\n curr_item_row: usize,\n\n curr_item_col: usize,\n\n) -> (usize, usize) {\n\n let mut to_check = vec![];\n\n\n\n // Row before\n\n if curr_item_row > 0 {\n\n // Col to the left\n\n if curr_item_col > 0 {\n\n to_check.push(find_first_non_empty_seat_in_direction(\n\n layout,\n\n curr_item_row,\n\n curr_item_col,\n\n Direction::Decrease,\n\n Direction::Decrease,\n\n ));\n\n }\n\n\n", "file_path": "day_11/src/main.rs", "rank": 62, "score": 41182.9630636914 }, { "content": "use std::fs::File;\n\nuse std::io::prelude::*;\n\n\n", "file_path": "shared/src/lib.rs", "rank": 63, "score": 30438.260546244317 }, { "content": "#[derive(Copy, Clone)]\n\nenum Direction {\n\n Increase = 1,\n\n Unchanged = 0,\n\n Decrease = -1,\n\n}\n\n\n", "file_path": "day_11/src/main.rs", "rank": 64, "score": 29279.514567218193 }, { "content": " .iter()\n\n .filter(|e| (*e).to_string() != \"x\".to_string())\n\n .map(|e| e.parse::<usize>().unwrap())\n\n .collect::<Vec<usize>>();\n\n\n\n let mut current_timestamp = self.timestamp;\n\n\n\n loop {\n\n for id in valid_bus_ids.iter() {\n\n if current_timestamp % id == 0 {\n\n return (current_timestamp, *id);\n\n }\n\n }\n\n\n\n current_timestamp += 1;\n\n }\n\n }\n\n\n\n pub fn calc_timing_value(&self, timestamp_numeric: usize, bus_number: usize) -> usize {\n\n (timestamp_numeric - self.timestamp) * bus_number\n\n }\n\n}\n\n\n", "file_path": "day_13/src/main.rs", "rank": 77, "score": 9.051909098326853 }, { "content": " let instruction_identifier = data[0];\n\n\n\n let mut instruction_counter = self.instruction_counter;\n\n let mut accumulator = self.accumulator;\n\n\n\n match instruction_identifier {\n\n \"nop\" => instruction_counter += 1,\n\n \"acc\" => {\n\n accumulator += data[1].parse::<isize>().unwrap();\n\n instruction_counter += 1;\n\n }\n\n \"jmp\" => {\n\n let next_instruction =\n\n (instruction_counter as isize) + data[1].parse::<isize>().unwrap();\n\n\n\n if next_instruction <= 0 {\n\n panic!(\"Invalid next instruction counter {}\", next_instruction)\n\n }\n\n\n\n instruction_counter = next_instruction as usize;\n", "file_path": "day_8/src/main.rs", "rank": 78, "score": 8.88939599161347 }, { "content": " assert_eq!(result.1, true);\n\n }\n\n\n\n assert_eq!(count_occupied(&layout), 26);\n\n }\n\n\n\n #[test]\n\n fn it_finds_the_first_non_empty_seat_in_the_direction() {\n\n let mut layout = shared::parse_input_to_character_matrix(\n\n \"\n\n .......#.\n\n ...#.....\n\n .#.......\n\n .........\n\n ..#L....#\n\n ....#....\n\n .........\n\n #........\n\n ...#.....\",\n\n );\n", "file_path": "day_11/src/main.rs", "rank": 79, "score": 7.458116886496157 }, { "content": "\n\n assert_eq!(\n\n find_first_non_empty_seat_in_direction(\n\n &layout,\n\n 4,\n\n 3,\n\n Direction::Decrease,\n\n Direction::Decrease\n\n ),\n\n (2, 1)\n\n );\n\n\n\n layout = shared::parse_input_to_character_matrix(\n\n \"\n\n .##.##.\n\n #.#.#.#\n\n ##...##\n\n ...L...\n\n ##...##\n\n #.#.#.#\n", "file_path": "day_11/src/main.rs", "rank": 80, "score": 7.272071149209684 }, { "content": "\n\n if contains_strs.len() == 1 && contains_strs[0] == \"no other\" {\n\n return Bag {\n\n color: bag_color.to_string(),\n\n contents: vec![],\n\n };\n\n }\n\n\n\n let bag_contents = contains_strs.iter().fold(vec![], |mut vec, content| {\n\n let tokens = content.split(\" \").collect::<Vec<&str>>();\n\n\n\n let amount = tokens[0].parse::<usize>().unwrap();\n\n let color = tokens[1..tokens.len()].join(\" \");\n\n\n\n vec.push(BagContent { color, amount });\n\n\n\n vec\n\n });\n\n\n\n Bag {\n", "file_path": "day_7/src/main.rs", "rank": 81, "score": 6.561311434130886 }, { "content": "use std::collections::HashSet;\n\nuse std::fs::File;\n\nuse std::io::prelude::*;\n\nuse std::iter::FromIterator;\n\n\n", "file_path": "day_1/src/main.rs", "rank": 82, "score": 6.385985370174623 }, { "content": "use shared;\n\n\n", "file_path": "day_9/src/main.rs", "rank": 83, "score": 6.365118143710253 }, { "content": "use shared;\n", "file_path": "day_5/src/main.rs", "rank": 84, "score": 6.365118143710253 }, { "content": "use shared;\n\n\n", "file_path": "day_10/src/main.rs", "rank": 85, "score": 6.365118143710253 }, { "content": "use shared;\n\n\n", "file_path": "day_11/src/main.rs", "rank": 86, "score": 6.365118143710253 }, { "content": " _ => return false,\n\n }\n\n\n\n match fields.get(\"eyr\") {\n\n Some(eyr) => match (*eyr).parse::<usize>() {\n\n Ok(eyr_value) => {\n\n if eyr_value < 2010 || eyr_value > 2030 {\n\n return false;\n\n }\n\n }\n\n _ => return false,\n\n },\n\n _ => return false,\n\n }\n\n\n\n match fields.get(\"hgt\") {\n\n Some(hgt) => {\n\n let hgt_val = *hgt;\n\n if hgt_val.contains(\"cm\") {\n\n let hgt_num = hgt_val.replace(\"cm\", \"\").parse::<usize>().unwrap();\n", "file_path": "day_4/src/main.rs", "rank": 87, "score": 6.144784778288855 }, { "content": "use shared;\n\nuse std::collections::HashMap;\n\n\n", "file_path": "day_14/src/main.rs", "rank": 88, "score": 6.1056740973532415 }, { "content": "use shared;\n\n\n\n#[derive(Debug)]\n", "file_path": "day_13/src/main.rs", "rank": 90, "score": 5.969700968259747 }, { "content": " if hgt_num < 150 || hgt_num > 193 {\n\n return false;\n\n }\n\n } else if hgt_val.contains(\"in\") {\n\n let hgt_num = hgt_val.replace(\"in\", \"\").parse::<usize>().unwrap();\n\n if hgt_num < 59 || hgt_num > 76 {\n\n return false;\n\n }\n\n } else {\n\n return false;\n\n }\n\n }\n\n _ => return false,\n\n }\n\n\n\n match fields.get(\"hcl\") {\n\n Some(hcl) => {\n\n let hcl_re = Regex::new(r\"^#[0-9a-f]{6}$\").unwrap();\n\n if !hcl_re.is_match(*hcl) {\n\n return false;\n", "file_path": "day_4/src/main.rs", "rank": 91, "score": 5.9088469491588125 }, { "content": "}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn it_sums_number_pair() {\n\n let test_numbers = vec![1721, 979, 366, 299, 675, 1456];\n\n assert_eq!(\n\n find_matching_number_pair(&test_numbers, 2020).unwrap(),\n\n 514579\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_sums_3_number_sequence() {\n\n let test_numbers = vec![979, 366, 675];\n\n assert_eq!(\n\n find_matching_3_number_sequence(&test_numbers, 2020).unwrap(),\n\n 241861950\n\n )\n\n }\n\n}\n", "file_path": "day_1/src/main.rs", "rank": 92, "score": 5.897065139799372 }, { "content": "use std::collections::HashMap;\n\n\n\nuse shared;\n\n\n\n#[derive(Debug)]\n", "file_path": "day_7/src/main.rs", "rank": 93, "score": 5.843920770594643 }, { "content": "use std::collections::HashSet;\n\n\n\nuse shared;\n\n\n\n#[derive(Debug)]\n", "file_path": "day_8/src/main.rs", "rank": 94, "score": 5.843920770594643 }, { "content": "use std::collections::HashMap;\n\nuse std::collections::HashSet;\n\n\n\nuse shared;\n\n\n", "file_path": "day_6/src/main.rs", "rank": 95, "score": 5.83469625103034 }, { "content": " let (layout, has_changed) = update_seating(&layout, &check_adjacent_seats, 4);\n\n\n\n let expected_result = vec![\n\n \"#.#L.L#.##\",\n\n \"#LLL#LL.L#\",\n\n \"L.#.L..#..\",\n\n \"#L##.##.L#\",\n\n \"#.#L.LL.LL\",\n\n \"#.#L#L#.##\",\n\n \"..L.L.....\",\n\n \"#L#L##L#L#\",\n\n \"#.LLLLLL.L\",\n\n \"#.#L#L#.##\",\n\n ];\n\n\n\n assert_eq!(has_changed, false);\n\n assert_eq!(\n\n layout.iter().map(|r| r.join(\"\")).collect::<Vec<String>>(),\n\n expected_result\n\n )\n", "file_path": "day_11/src/main.rs", "rank": 96, "score": 5.262578880990414 }, { "content": " Some(byr) => match (*byr).parse::<usize>() {\n\n Ok(byr_value) => {\n\n if byr_value < 1920 || byr_value > 2002 {\n\n return false;\n\n }\n\n }\n\n _ => return false,\n\n },\n\n _ => return false,\n\n }\n\n\n\n match fields.get(\"iyr\") {\n\n Some(iyr) => match (*iyr).parse::<usize>() {\n\n Ok(iyr_value) => {\n\n if iyr_value < 2010 || iyr_value > 2020 {\n\n return false;\n\n }\n\n }\n\n _ => return false,\n\n },\n", "file_path": "day_4/src/main.rs", "rank": 97, "score": 5.138907659965706 }, { "content": " assert_eq!(bag.contents.len(), 0);\n\n }\n\n\n\n #[test]\n\n fn it_counts_bags_that_can_fit_a_color() {\n\n let lines = shared::read_file(\"test_input.txt\");\n\n\n\n let rules = lines.iter().map(|s| &**s).collect::<Vec<&str>>();\n\n let rules_map = parse_rules_to_map(&rules);\n\n assert_eq!(\n\n count_bags_that_can_fit_color(&rules_map, \"shiny gold\"),\n\n 4,\n\n \"counts all bags that can contain a shiny gold bag\"\n\n );\n\n }\n\n\n\n #[test]\n\n fn it_counts_bags_inside_a_bag() {\n\n let lines = shared::read_file(\"test_2_input.txt\");\n\n\n\n let rules = lines.iter().map(|s| &**s).collect::<Vec<&str>>();\n\n let rules_map = parse_rules_to_map(&rules);\n\n\n\n let bag = rules_map.get(\"shiny gold\").unwrap();\n\n assert_eq!(bag.count_total_num_bags(&rules_map), 126);\n\n }\n\n}\n", "file_path": "day_7/src/main.rs", "rank": 98, "score": 5.027687218925854 }, { "content": " }\n\n instruct_id => panic!(\"Invalid instruction {}\", instruct_id),\n\n }\n\n\n\n if persist {\n\n self.instruction_counter = instruction_counter;\n\n self.accumulator = accumulator;\n\n }\n\n\n\n (instruction_counter, accumulator)\n\n }\n\n\n\n pub fn skip(&mut self) {\n\n self.instruction_counter += 1;\n\n }\n\n\n\n pub fn reset(&mut self) {\n\n self.instruction_counter = 0;\n\n self.accumulator = 0;\n\n }\n\n}\n\n\n", "file_path": "day_8/src/main.rs", "rank": 99, "score": 4.979071203810941 } ]
Rust
truck-meshalgo/src/analyzers/topology.rs
roudy16/truck
b92af7761302a5d16b5e52b15f1be7b6c4dfd460
use super::*; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use truck_topology::shell::ShellCondition; pub trait Topology { fn extract_boundaries(&self) -> Vec<Vec<usize>>; fn shell_condition(&self) -> ShellCondition; } #[derive(Clone, Debug)] struct Boundaries { checked: HashSet<[usize; 2]>, boundary: HashMap<[usize; 2], bool>, condition: ShellCondition, } impl Boundaries { #[inline(always)] fn new() -> Self { Boundaries { checked: Default::default(), boundary: Default::default(), condition: ShellCondition::Oriented, } } #[inline(always)] fn insert(&mut self, edge: [Vertex; 2]) { let ori = edge[0].pos < edge[1].pos; let edge = match ori { true => [edge[0].pos, edge[1].pos], false => [edge[1].pos, edge[0].pos], }; self.condition = self.condition & match (self.checked.insert(edge), self.boundary.insert(edge, ori)) { (true, None) => ShellCondition::Oriented, (false, None) => ShellCondition::Irregular, (true, Some(_)) => panic!("unexpected case!"), (false, Some(ori0)) => { self.boundary.remove(&edge); match ori == ori0 { true => ShellCondition::Regular, false => ShellCondition::Oriented, } } }; } #[inline(always)] fn condition(&self) -> ShellCondition { if self.condition == ShellCondition::Oriented && self.boundary.is_empty() { ShellCondition::Closed } else { self.condition } } } impl FromIterator<[Vertex; 2]> for Boundaries { fn from_iter<I: IntoIterator<Item = [Vertex; 2]>>(iter: I) -> Boundaries { let mut boundaries = Boundaries::new(); iter.into_iter().for_each(|edge| boundaries.insert(edge)); boundaries } } impl Topology for Faces { fn extract_boundaries(&self) -> Vec<Vec<usize>> { let mut vemap: HashMap<usize, usize> = self .face_iter() .flat_map(move |face| { let len = face.len(); (0..len).map(move |i| [face[i], face[(i + 1) % len]]) }) .collect::<Boundaries>() .boundary .into_iter() .map(|(edge, ori)| match ori { true => (edge[0], edge[1]), false => (edge[1], edge[0]), }) .collect(); let mut res = Vec::new(); while !vemap.is_empty() { let mut wire = Vec::new(); let front = vemap.iter().next().unwrap(); let front = (*front.0, *front.1); vemap.remove(&front.0); wire.push(front.0); let mut cursor = front.1; while cursor != front.0 { wire.push(cursor); cursor = vemap.remove(&cursor).unwrap_or(front.0); } res.push(wire); } res } fn shell_condition(&self) -> ShellCondition { let boundaries: Boundaries = self .face_iter() .flat_map(move |face| { let len = face.len(); (0..len).map(move |i| [face[i], face[(i + 1) % len]]) }) .collect(); boundaries.condition() } } impl Topology for PolygonMesh { fn extract_boundaries(&self) -> Vec<Vec<usize>> { self.faces().extract_boundaries() } fn shell_condition(&self) -> ShellCondition { self.faces().shell_condition() } }
use super::*; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use truck_topology::shell::ShellCondition; pub trait Topology { fn extract_boundaries(&self) -> Vec<Vec<usize>>; fn shell_condition(&self) -> ShellCondition; } #[derive(Clone, Debug)] struct Boundaries { checked: HashSet<[usize; 2]>, boundary: HashMap<[usize; 2], bool>, condition: ShellCondition, } impl Boundaries { #[inline(always)] fn new() -> Self { Boundaries { checked: Default::default(), boundary: Default::default(), condition: ShellCondition::Oriented, } } #[inline(always)] fn insert(&mut self, edge: [Vertex; 2]) { let ori = edge[0].pos < edge[1].pos; let edge = match ori { true => [edge[0].pos, edge[1].pos], false => [edge[1].pos, edge[0].pos], }; self.condition = self.condition &
; } #[inline(always)] fn condition(&self) -> ShellCondition { if self.condition == ShellCondition::Oriented && self.boundary.is_empty() { ShellCondition::Closed } else { self.condition } } } impl FromIterator<[Vertex; 2]> for Boundaries { fn from_iter<I: IntoIterator<Item = [Vertex; 2]>>(iter: I) -> Boundaries { let mut boundaries = Boundaries::new(); iter.into_iter().for_each(|edge| boundaries.insert(edge)); boundaries } } impl Topology for Faces { fn extract_boundaries(&self) -> Vec<Vec<usize>> { let mut vemap: HashMap<usize, usize> = self .face_iter() .flat_map(move |face| { let len = face.len(); (0..len).map(move |i| [face[i], face[(i + 1) % len]]) }) .collect::<Boundaries>() .boundary .into_iter() .map(|(edge, ori)| match ori { true => (edge[0], edge[1]), false => (edge[1], edge[0]), }) .collect(); let mut res = Vec::new(); while !vemap.is_empty() { let mut wire = Vec::new(); let front = vemap.iter().next().unwrap(); let front = (*front.0, *front.1); vemap.remove(&front.0); wire.push(front.0); let mut cursor = front.1; while cursor != front.0 { wire.push(cursor); cursor = vemap.remove(&cursor).unwrap_or(front.0); } res.push(wire); } res } fn shell_condition(&self) -> ShellCondition { let boundaries: Boundaries = self .face_iter() .flat_map(move |face| { let len = face.len(); (0..len).map(move |i| [face[i], face[(i + 1) % len]]) }) .collect(); boundaries.condition() } } impl Topology for PolygonMesh { fn extract_boundaries(&self) -> Vec<Vec<usize>> { self.faces().extract_boundaries() } fn shell_condition(&self) -> ShellCondition { self.faces().shell_condition() } }
match (self.checked.insert(edge), self.boundary.insert(edge, ori)) { (true, None) => ShellCondition::Oriented, (false, None) => ShellCondition::Irregular, (true, Some(_)) => panic!("unexpected case!"), (false, Some(ori0)) => { self.boundary.remove(&edge); match ori == ori0 { true => ShellCondition::Regular, false => ShellCondition::Oriented, } } }
if_condition
[ { "content": "#[inline(always)]\n\npub fn vertex(pt: Point3) -> Vertex { Vertex::new(pt) }\n\n\n\n/// Returns a line from `vertex0` to `vertex1`.\n\n/// # Examples\n\n/// ```\n\n/// use truck_modeling::*;\n\n///\n\n/// // draw a line\n\n/// let vertex0 = builder::vertex(Point3::new(1.0, 2.0, 3.0));\n\n/// let vertex1 = builder::vertex(Point3::new(6.0, 5.0, 4.0));\n\n/// let line = builder::line(&vertex0, &vertex1);\n\n/// # let curve = line.oriented_curve();\n\n/// # let pt0 = Point3::new(1.0, 2.0, 3.0);\n\n/// # let pt1 = Point3::new(6.0, 5.0, 4.0);\n\n/// # const N: usize = 10;\n\n/// # for i in 0..=N {\n\n/// # let t = i as f64 / N as f64;\n\n/// # assert!(curve.subs(t).near2(&(pt0 + t * (pt1 - pt0))));\n\n/// # }\n\n/// ```\n", "file_path": "truck-modeling/src/builder.rs", "rank": 0, "score": 300220.10784034966 }, { "content": "#[inline(always)]\n\npub fn line(vertex0: &Vertex, vertex1: &Vertex) -> Edge {\n\n let pt0 = vertex0.get_point().to_homogeneous();\n\n let pt1 = vertex1.get_point().to_homogeneous();\n\n let curve = geom_impls::line(pt0, pt1);\n\n Edge::new(vertex0, vertex1, Curve::NURBSCurve(NURBSCurve::new(curve)))\n\n}\n\n\n\n/// Returns a circle arc from `vertex0` to `vertex1` via `transit`.\n\n/// # Examples\n\n/// ```\n\n/// use truck_modeling::*;\n\n///\n\n/// // draw the unit upper semicircle\n\n/// let vertex0 = builder::vertex(Point3::new(1.0, 0.0, 0.0));\n\n/// let vertex1 = builder::vertex(Point3::new(-1.0, 0.0, 0.0));\n\n/// let semi_circle = builder::circle_arc(&vertex0, &vertex1, Point3::new(0.0, 1.0, 0.0));\n\n/// # let curve = match semi_circle.oriented_curve() {\n\n/// # Curve::NURBSCurve(curve) => curve,\n\n/// # _ => unreachable!(),\n\n/// # };\n\n/// # const N: usize = 10;\n\n/// # for i in 0..=N {\n\n/// # let t = curve.knot_vec()[0] + curve.knot_vec().range_length() * i as f64 / N as f64;\n\n/// # assert!(curve.subs(t).to_vec().magnitude().near(&1.0));\n\n/// # }\n\n/// ```\n", "file_path": "truck-modeling/src/builder.rs", "rank": 1, "score": 271429.81351852766 }, { "content": "#[wasm_bindgen]\n\npub fn line(vertex0: &Vertex, vertex1: &Vertex) -> Edge {\n\n builder::line(&*vertex0, &*vertex1).into()\n\n}\n\n/// Returns a circle arc from `vertex0` to `vertex1` via `transit`.\n", "file_path": "truck-js/src/builder.rs", "rank": 2, "score": 271429.81351852766 }, { "content": "/// can be regarded as a vertex slice\n\npub trait AsVertexSlice: AsRef<[Self::V]> {\n\n\t/// items converted to vertex\n\n\ttype V: Copy + Into<Vertex>;\n\n}\n\n\n\nimpl From<&Vertex> for Vertex {\n\n\tfn from(v: &Vertex) -> Vertex { *v }\n\n}\n\n\n\nimpl<'a, T: AsVertexSlice> AsVertexSlice for &'a T {\n\n\ttype V = T::V;\n\n}\n\n\n\nmacro_rules! impl_as_vertex_slice {\n\n\t($vertex: ty) => {\n\n\t\timpl<'a> AsVertexSlice for &'a [$vertex] {\n\n\t\t\ttype V = $vertex;\n\n\t\t}\n\n\t\timpl<const N: usize> AsVertexSlice for [$vertex; N] {\n\n\t\t\ttype V = $vertex;\n", "file_path": "truck-polymesh/src/faces.rs", "rank": 3, "score": 264184.7924621998 }, { "content": "#[wasm_bindgen]\n\npub fn vertex(x: f64, y: f64, z: f64) -> Vertex { builder::vertex(Point3::new(x, y, z)).into() }\n\n/// Returns a line from `vertex0` to `vertex1`.\n", "file_path": "truck-js/src/builder.rs", "rank": 4, "score": 258211.60824301717 }, { "content": "#[inline(always)]\n\npub fn circle_arc(vertex0: &Vertex, vertex1: &Vertex, transit: Point3) -> Edge {\n\n let pt0 = vertex0.get_point().to_homogeneous();\n\n let pt1 = vertex1.get_point().to_homogeneous();\n\n let curve = geom_impls::circle_arc_by_three_points(pt0, pt1, transit);\n\n Edge::new(vertex0, vertex1, Curve::NURBSCurve(NURBSCurve::new(curve)))\n\n}\n\n\n\n/// Returns a Bezier curve from `vertex0` to `vertex1` with inter control points `inter_points`.\n\n/// # Examples\n\n/// ```\n\n/// use truck_modeling::*;\n\n///\n\n/// // draw a Bezier curve\n\n/// let vertex0 = builder::vertex(Point3::origin());\n\n/// let vertex1 = builder::vertex(Point3::new(3.0, 0.0, 0.0));\n\n/// let inter_points = vec![Point3::new(1.0, 1.0, 0.0), Point3::new(2.0, -1.0, 0.0)];\n\n/// let bezier = builder::bezier(&vertex0, &vertex1, inter_points);\n\n/// # let curve = bezier.oriented_curve();\n\n/// # const N: usize = 10;\n\n/// # for i in 0..=N {\n\n/// # let t = i as f64 / N as f64;\n\n/// # let pt = Point3::new(t * 3.0, 6.0 * t * t * t - 9.0 * t * t + 3.0 * t, 0.0);\n\n/// # assert!(curve.subs(t).near(&pt));\n\n/// # }\n\n/// ```\n", "file_path": "truck-modeling/src/builder.rs", "rank": 5, "score": 252249.3034836615 }, { "content": "#[wasm_bindgen]\n\npub fn bezier(vertex0: &Vertex, vertex1: &Vertex, inter_points: &[f64]) -> Edge {\n\n assert!(\n\n inter_points.len() % 3 == 0,\n\n \"inter_points cannot convert to 3-dimentional points!\"\n\n );\n\n let inter_points = inter_points\n\n .chunks(3)\n\n .map(|p| Point3::new(p[0], p[1], p[2]))\n\n .collect();\n\n builder::bezier(&*vertex0, &*vertex1, inter_points).into()\n\n}\n\n/// Returns a homotopic face from `edge0` to `edge1`.\n", "file_path": "truck-js/src/builder.rs", "rank": 6, "score": 252249.3034836615 }, { "content": "#[wasm_bindgen]\n\npub fn circle_arc(vertex0: &Vertex, vertex1: &Vertex, transit: &[f64]) -> Edge {\n\n intopt!(Point3, transit);\n\n builder::circle_arc(&*vertex0, &*vertex1, transit).into()\n\n}\n\n/// Returns a Bezier curve from `vertex0` to `vertex1` with inter control points `inter_points`.\n", "file_path": "truck-js/src/builder.rs", "rank": 7, "score": 252249.3034836615 }, { "content": "#[inline(always)]\n\npub fn bezier(vertex0: &Vertex, vertex1: &Vertex, mut inter_points: Vec<Point3>) -> Edge {\n\n let pt0 = vertex0.get_point();\n\n let pt1 = vertex1.get_point();\n\n let mut pre_ctrl_pts = vec![pt0];\n\n pre_ctrl_pts.append(&mut inter_points);\n\n pre_ctrl_pts.push(pt1);\n\n let ctrl_pts: Vec<_> = pre_ctrl_pts\n\n .into_iter()\n\n .map(|pt| pt.to_homogeneous())\n\n .collect();\n\n let knot_vec = KnotVec::bezier_knot(ctrl_pts.len() - 1);\n\n let curve = BSplineCurve::new(knot_vec, ctrl_pts);\n\n Edge::new(vertex0, vertex1, Curve::NURBSCurve(NURBSCurve::new(curve)))\n\n}\n\n\n\n/// Returns a homotopic face from `edge0` to `edge1`.\n\n/// # Examples\n\n/// ```\n\n/// use truck_modeling::*;\n\n///\n", "file_path": "truck-modeling/src/builder.rs", "rank": 8, "score": 238800.51046420948 }, { "content": "fn check_connectivity<T>(adjacency: &mut HashMap<T, Vec<T>>) -> bool\n\nwhere T: Eq + Clone + Hash {\n\n create_one_component(adjacency);\n\n adjacency.is_empty()\n\n}\n\n\n", "file_path": "truck-topology/src/shell.rs", "rank": 10, "score": 224765.09973500733 }, { "content": "fn degenerate_triangle(tri: [Vertex; 3]) -> bool {\n\n tri[0].pos == tri[1].pos || tri[1].pos == tri[2].pos || tri[2].pos == tri[0].pos\n\n}\n\n\n", "file_path": "truck-meshalgo/src/filters/optimizing.rs", "rank": 11, "score": 218701.80360973364 }, { "content": "/// Concats two curves\n\npub trait Concat<Rhs: BoundedCurve<Point = Self::Point, Vector = Self::Vector>>:\n\n BoundedCurve\n\nwhere Self::Point: Debug {\n\n /// The result of concat two curves\n\n type Output: BoundedCurve<Point = Self::Point, Vector = Self::Vector>;\n\n /// Try concat two curves.\n\n /// # Failure\n\n /// Returns `None` if `self.parameter_range().1 != rhs.parameter_range().0`.\n\n fn try_concat(&self, rhs: &Rhs) -> Result<Self::Output, ConcatError<Self::Point>>;\n\n /// Try concat two curves.\n\n /// # Panic\n\n /// Panic occurs if `self.parameter_range().1 != rhs.parameter_range().0`.\n\n fn concat(&self, rhs: &Rhs) -> Self::Output {\n\n self.try_concat(rhs).unwrap_or_else(|err| panic!(\"{}\", err))\n\n }\n\n}\n\n\n\nimpl<Rhs, C> Concat<Rhs> for Box<C>\n\nwhere\n\n Rhs: BoundedCurve<Point = C::Point, Vector = C::Vector>,\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 12, "score": 217834.81526323344 }, { "content": "/// Defines a tolerance in the whole package\n\npub trait Tolerance: AbsDiffEq<Epsilon = f64> + Debug {\n\n /// The \"distance\" is less than `TOLERANCE`.\n\n fn near(&self, other: &Self) -> bool { self.abs_diff_eq(other, TOLERANCE) }\n\n\n\n /// The \"distance\" is less than `TOLERANCR2`.\n\n fn near2(&self, other: &Self) -> bool { self.abs_diff_eq(other, TOLERANCE2) }\n\n}\n\n\n\nimpl<T: AbsDiffEq<Epsilon = f64> + Debug> Tolerance for T {}\n\n\n\n/// assert near\n\n#[macro_export]\n\nmacro_rules! assert_near {\n\n ($left: expr, $right: expr $(,)?) => {\n\n assert!($left.near(&$right), \"assertion failed: `left` is near `right`\n\nleft: {:?},\n\nright: {:?}\", $left, $right)\n\n };\n\n ($left: expr, $right: expr, $($arg: tt)+) => {\n\n assert!($left.near(&$right), \"assertion failed: `left` is near `right`\n\nleft: {:?},\n\nright: {:?}: {}\", $left, $right, format_args!($($arg)+))\n\n };\n\n}\n\n\n", "file_path": "truck-base/src/tolerance.rs", "rank": 13, "score": 208081.07088670827 }, { "content": "pub fn same_buffer(vec0: &[u8], vec1: &[u8]) -> bool {\n\n vec0.par_iter()\n\n .zip(vec1)\n\n .all(move |(i, j)| std::cmp::max(i, j) - std::cmp::min(i, j) < 3)\n\n}\n\n\n", "file_path": "truck-rendimpl/tests/common.rs", "rank": 14, "score": 203798.29718159186 }, { "content": "pub fn same_buffer(vec0: &[u8], vec1: &[u8]) -> bool {\n\n vec0.par_iter()\n\n .zip(vec1)\n\n .all(move |(i, j)| std::cmp::max(i, j) - std::cmp::min(i, j) < 3)\n\n}\n\n\n", "file_path": "truck-platform/tests/common.rs", "rank": 15, "score": 203798.29718159186 }, { "content": "fn closed_polyline_orientation(pts: &[Point3]) -> bool {\n\n pts.windows(2).fold(0.0, |sum, pt| {\n\n sum + (pt[1][0] + pt[0][0]) * (pt[1][1] - pt[0][1])\n\n }) >= 0.0\n\n}\n\n\n\npub(super) fn attach_plane(mut pts: Vec<Point3>) -> Option<Plane> {\n\n let center = pts.iter().fold(Point3::origin(), |sum, pt| sum + pt.to_vec()) / pts.len() as f64;\n\n let normal = pts.windows(2).fold(Vector3::zero(), |sum, pt| {\n\n sum + (pt[0] - center).cross(pt[1] - center)\n\n });\n\n let n = match normal.so_small() {\n\n true => return None,\n\n false => normal.normalize(),\n\n };\n\n let a = match (n[2].abs() - 1.0).so_small() {\n\n true => Vector3::new(0.0, n[2], -n[1]).normalize(),\n\n false => Vector3::new(n[1], -n[0], 0.0).normalize(),\n\n };\n\n let mat: Matrix4 = Matrix3::from_cols(a, n.cross(a), n).into();\n", "file_path": "truck-modeling/src/geom_impls.rs", "rank": 16, "score": 191187.86999959726 }, { "content": "#[inline(always)]\n\npub fn homotopy(edge0: &Edge, edge1: &Edge) -> Face {\n\n let wire: Wire = vec![\n\n edge0.clone(),\n\n line(edge0.back(), edge1.back()),\n\n edge1.inverse(),\n\n line(edge1.front(), edge0.front()),\n\n ]\n\n .into();\n\n let curve0 = edge0.oriented_curve().lift_up();\n\n let curve1 = edge1.oriented_curve().lift_up();\n\n let surface = BSplineSurface::homotopy(curve0, curve1);\n\n Face::new(\n\n vec![wire],\n\n Surface::NURBSSurface(NURBSSurface::new(surface)),\n\n )\n\n}\n\n\n\n/// Creates a cone by R-sweeping.\n\n/// # Examples\n\n/// ```\n", "file_path": "truck-modeling/src/builder.rs", "rank": 17, "score": 190784.60976218892 }, { "content": "#[derive(Debug, Clone)]\n\nstruct Boundaries<C> {\n\n checked: HashSet<EdgeID<C>>,\n\n boundaries: HashMap<EdgeID<C>, bool>,\n\n condition: ShellCondition,\n\n}\n\n\n\nimpl<C> Boundaries<C> {\n\n #[inline(always)]\n\n fn new() -> Self {\n\n Self {\n\n checked: Default::default(),\n\n boundaries: Default::default(),\n\n condition: ShellCondition::Oriented,\n\n }\n\n }\n\n\n\n #[inline(always)]\n\n fn insert<P>(&mut self, edge: &Edge<P, C>) {\n\n self.condition = self.condition\n\n & match (\n", "file_path": "truck-topology/src/shell.rs", "rank": 19, "score": 183171.26868069204 }, { "content": "fn is_in_the_plane(positions: &[Point3], normals: &[Vector3], face: &[Vertex], tol2: f64) -> bool {\n\n let n = FaceNormal::new(positions, face, 0).normal;\n\n for v in face {\n\n if let Some(nor) = v.nor {\n\n if n.distance2(normals[nor]) < tol2 {\n\n return true;\n\n }\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "truck-meshalgo/src/analyzers/splitting.rs", "rank": 20, "score": 181686.07758512403 }, { "content": "#[test]\n\nfn shell_condition() {\n\n let faces = Faces::from_iter(&[\n\n [0, 1, 4].as_ref(),\n\n &[1, 2, 3, 0],\n\n &[0, 4, 5, 6, 1],\n\n ]);\n\n assert_eq!(faces.shell_condition(), ShellCondition::Irregular); \n\n let faces = Faces::from_iter(&[\n\n [0, 1, 5, 4].as_ref(),\n\n &[1, 2, 6, 5],\n\n &[6, 7, 3, 2],\n\n &[3, 0, 4, 7],\n\n ]);\n\n assert_eq!(faces.shell_condition(), ShellCondition::Regular); \n\n let faces = Faces::from_iter(&[\n\n [0, 1, 5, 4].as_ref(),\n\n &[1, 2, 6, 5],\n\n &[2, 3, 7, 6],\n\n &[3, 0, 4, 7],\n\n ]);\n", "file_path": "truck-meshalgo/tests/analyzers/topology.rs", "rank": 21, "score": 181074.27496093645 }, { "content": "#[derive(Debug, Serialize, Deserialize)]\n\nstruct CompressedEdge<C> {\n\n vertices: (usize, usize),\n\n curve: C,\n\n}\n\n\n\nimpl<C> CompressedEdge<C> {\n\n fn create_edge<P>(self, v: &[Vertex<P>]) -> Result<Edge<P, C>> {\n\n let front = &v[self.vertices.0];\n\n let back = &v[self.vertices.1];\n\n Edge::try_new(front, back, self.curve)\n\n }\n\n}\n\n\n", "file_path": "truck-topology/src/compress.rs", "rank": 22, "score": 179607.80817010533 }, { "content": "/// Search parameter `t` such that `self.subs(t)` is near point.\n\npub trait SearchParameter {\n\n /// point\n\n type Point;\n\n /// curve => `f64`, surface => `(f64, f64)`\n\n type Parameter;\n\n /// Search parameter `t` such that `self.subs(t)` is near point. \n\n /// Returns `None` if could not find such parameter.\n\n fn search_parameter(\n\n &self,\n\n point: Self::Point,\n\n hint: Option<Self::Parameter>,\n\n trial: usize,\n\n ) -> Option<Self::Parameter>;\n\n}\n\n\n\nimpl<'a, T: SearchParameter> SearchParameter for &'a T {\n\n type Point = T::Point;\n\n type Parameter = T::Parameter;\n\n fn search_parameter(\n\n &self,\n", "file_path": "truck-geotrait/src/traits/mod.rs", "rank": 23, "score": 179244.02211956118 }, { "content": "#[test]\n\nfn solid_cut_edge() {\n\n let p = vec![\n\n Point3::new(0.0, 0.0, 0.0),\n\n Point3::new(1.0, 0.0, 0.0),\n\n Point3::new(0.0, 1.0, 0.0),\n\n Point3::new(0.0, 0.0, 1.0),\n\n Point3::new(0.0, 0.5, 0.0),\n\n Point3::new(0.5, 0.5, 0.5),\n\n ];\n\n let v = Vertex::news(&p);\n\n let edge = vec![\n\n Edge::new(&v[0], &v[1], Segment::new(p[0], p[1])),\n\n Edge::new(&v[0], &v[2], Segment::new(p[0], p[2])),\n\n Edge::new(&v[0], &v[3], Segment::new(p[0], p[3])),\n\n Edge::new(&v[1], &v[2], Segment::new(p[1], p[2])),\n\n Edge::new(&v[1], &v[3], Segment::new(p[1], p[3])),\n\n Edge::new(&v[2], &v[3], Segment::new(p[2], p[3])),\n\n ];\n\n let shell: Shell<_, _, _> = vec![\n\n Face::new(\n", "file_path": "truck-topology/tests/euler_operators.rs", "rank": 24, "score": 177684.69152956922 }, { "content": "/// Search parameter `t` such that `self.subs(t)` is nearest point.\n\npub trait SearchNearestParameter {\n\n /// point\n\n type Point;\n\n /// curve => `f64`, surface => `(f64, f64)`\n\n type Parameter;\n\n /// Search nearest parameter `t` such that `self.subs(t)` is nearest point. \n\n /// Returns `None` if could not find such parameter.\n\n fn search_nearest_parameter(\n\n &self,\n\n point: Self::Point,\n\n hint: Option<Self::Parameter>,\n\n trial: usize,\n\n ) -> Option<Self::Parameter>;\n\n}\n\n\n\nimpl<'a, T: SearchNearestParameter> SearchNearestParameter for &'a T {\n\n type Point = T::Point;\n\n type Parameter = T::Parameter;\n\n fn search_nearest_parameter(\n\n &self,\n", "file_path": "truck-geotrait/src/traits/mod.rs", "rank": 25, "score": 177355.20936912895 }, { "content": "/// Dividable surface\n\npub trait ParameterDivision2D {\n\n /// Creates the surface division\n\n ///\n\n /// # Panics\n\n /// \n\n /// `tol` must be more than `TOLERANCE`.\n\n fn parameter_division(&self, range: ((f64, f64), (f64, f64)), tol: f64) -> (Vec<f64>, Vec<f64>);\n\n}\n\n\n\nimpl<'a, S: ParameterDivision2D> ParameterDivision2D for &'a S {\n\n fn parameter_division(&self, range: ((f64, f64), (f64, f64)), tol: f64) -> (Vec<f64>, Vec<f64>) {\n\n (*self).parameter_division(range, tol)\n\n }\n\n}\n\n\n\nimpl<S: ParameterDivision2D> ParameterDivision2D for Box<S> {\n\n fn parameter_division(&self, range: ((f64, f64), (f64, f64)), tol: f64) -> (Vec<f64>, Vec<f64>) {\n\n (**self).parameter_division(range, tol)\n\n }\n\n}\n", "file_path": "truck-geotrait/src/traits/surface.rs", "rank": 26, "score": 177349.67234065407 }, { "content": "/// Dividable curve\n\npub trait ParameterDivision1D {\n\n /// The curve is in the space of `Self::Point`.\n\n type Point;\n\n /// Creates the curve division (prameters, corresponding points).\n\n ///\n\n /// # Panics\n\n ///\n\n /// `tol` must be more than `TOLERANCE`.\n\n fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec<f64>, Vec<Self::Point>);\n\n}\n\n\n\nimpl<'a, C: ParameterDivision1D> ParameterDivision1D for &'a C {\n\n type Point = C::Point;\n\n fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec<f64>, Vec<Self::Point>) {\n\n (*self).parameter_division(range, tol)\n\n }\n\n}\n\n\n\nimpl<C: ParameterDivision1D> ParameterDivision1D for Box<C> {\n\n type Point = C::Point;\n\n fn parameter_division(&self, range: (f64, f64), tol: f64) -> (Vec<f64>, Vec<Self::Point>) {\n\n (**self).parameter_division(range, tol)\n\n }\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 27, "score": 177349.67234065407 }, { "content": "fn line(v0: &Vertex<Point3>, v1: &Vertex<Point3>) -> Edge<Point3, BSplineCurve<Point3>> {\n\n\tlet curve = BSplineCurve::new(\n\n\t\tKnotVec::bezier_knot(1),\n\n\t\tvec![v0.get_point(), v1.get_point()],\n\n\t);\n\n\tEdge::new(v0, v1, curve)\n\n}\n\n\n", "file_path": "truck-shapeops/src/divide_face/tests.rs", "rank": 28, "score": 173825.7816202147 }, { "content": "/// Oriented and reversible\n\npub trait Invertible: Clone {\n\n /// Inverts `self`\n\n fn invert(&mut self);\n\n /// Returns the inverse.\n\n #[inline(always)]\n\n fn inverse(&self) -> Self {\n\n let mut res = self.clone();\n\n res.invert();\n\n res\n\n }\n\n}\n\n\n\n/// Implementation for the test of topological methods.\n\nimpl Invertible for (usize, usize) {\n\n fn invert(&mut self) { *self = (self.1, self.0); }\n\n fn inverse(&self) -> Self { (self.1, self.0) }\n\n}\n\n\n\nimpl<P: Clone> Invertible for Vec<P> {\n\n #[inline(always)]\n", "file_path": "truck-geotrait/src/traits/mod.rs", "rank": 29, "score": 172533.08844579378 }, { "content": "pub trait Empty {\n\n fn empty() -> Self;\n\n}\n\n\n\npub type Ellipse<P, M> = Processor<UnitCircle<P>, M>;\n\npub type Hyperbola<P, M> = Processor<UnitHyperbola<P>, M>;\n\npub type Parabola<P, M> = Processor<UnitParabola<P>, M>;\n\npub type RevolutedLine = Processor<RevolutedCurve<Line<Point3>>, Matrix4>;\n\npub type ToroidalSurface = Processor<RevolutedCurve<Ellipse<Point3, Matrix4>>, Matrix4>;\n\npub type StepExtrudedCurve = ExtrudedCurve<Curve<Point3, Vector4, Matrix4>, Vector3>;\n\npub type StepRevolutedCurve = Processor<RevolutedCurve<Curve<Point3, Vector4, Matrix4>>, Matrix4>;\n\n\n\nmacro_rules! derive_enum {\n\n\t($attr: meta, $typename: ident { $($member: ident ($subtype: ty),)* } $derive_macro_name: ident, $dol: tt) => {\n\n\t\t#[$attr]\n\n\t\tpub enum $typename {\n\n\t\t\t$($member($subtype),)*\n\n\t\t}\n\n\t\tmacro_rules! $derive_macro_name {\n\n\t\t\t(fn $method: ident (&self, $dol ($field: ident : $field_type: ty),*) -> $return_type: ty) => {\n", "file_path": "truck-stepio/src/alias.rs", "rank": 30, "score": 171837.96014944548 }, { "content": "/// Rendered objects in the scene.\n\npub trait Rendered {\n\n /// Returns the render id.\n\n ///\n\n /// [`RenderID`](./struct.RenderID.html) is a key that maps `self` to a drawing element.\n\n /// Each object must have a RenderID to ensure that there are no duplicates.\n\n fn render_id(&self) -> RenderID;\n\n /// Creates the pair (vertex buffer, index buffer).\n\n fn vertex_buffer(\n\n &self,\n\n device_handler: &DeviceHandler,\n\n ) -> (Arc<BufferHandler>, Option<Arc<BufferHandler>>);\n\n /// Creates the bind group layout.\n\n fn bind_group_layout(&self, device_handler: &DeviceHandler) -> Arc<BindGroupLayout>;\n\n /// Creates the bind group in `set = 1`.\n\n fn bind_group(\n\n &self,\n\n device_handler: &DeviceHandler,\n\n layout: &BindGroupLayout,\n\n ) -> Arc<BindGroup>;\n\n /// Creates the render pipeline.\n", "file_path": "truck-platform/src/lib.rs", "rank": 31, "score": 171837.96014944548 }, { "content": "/// Instance for rendering\n\npub trait Instance {\n\n #[doc(hidden)]\n\n type Shaders;\n\n /// Get standard shaders from instance creator.\n\n #[doc(hidden)]\n\n fn standard_shaders(creator: &InstanceCreator) -> Self::Shaders;\n\n}\n\n\n", "file_path": "truck-rendimpl/src/lib.rs", "rank": 32, "score": 171837.96014944548 }, { "content": "/// Parametric surface\n\npub trait ParametricSurface: Clone {\n\n /// The surface is in the space of `Self::Point`.\n\n type Point;\n\n /// The derivation vector of the curve.\n\n type Vector;\n\n /// Substitutes the parameter `(u, v)`.\n\n fn subs(&self, u: f64, v: f64) -> Self::Point;\n\n /// Returns the derivation by `u`.\n\n fn uder(&self, u: f64, v: f64) -> Self::Vector;\n\n /// Returns the derivation by `v`.\n\n fn vder(&self, u: f64, v: f64) -> Self::Vector;\n\n /// Returns the 2nd-order derivation by `u`.\n\n fn uuder(&self, u: f64, v: f64) -> Self::Vector;\n\n /// Returns the 2nd-order derivation by both `u` and `v`.\n\n fn uvder(&self, u: f64, v: f64) -> Self::Vector;\n\n /// Returns the 2nd-order derivation by `v`.\n\n fn vvder(&self, u: f64, v: f64) -> Self::Vector;\n\n}\n\n\n\nimpl<'a, S: ParametricSurface> ParametricSurface for &'a S {\n", "file_path": "truck-geotrait/src/traits/surface.rs", "rank": 33, "score": 170644.27569536155 }, { "content": "/// Cuts one curve into two curves.\n\npub trait Cut: BoundedCurve {\n\n /// Cuts one curve into two curves. Assigns the former curve to `self` and returns the later curve.\n\n fn cut(&mut self, t: f64) -> Self;\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 34, "score": 170644.27569536155 }, { "content": "/// Parametric curves\n\npub trait ParametricCurve: Clone {\n\n /// The curve is in the space of `Self::Point`.\n\n type Point;\n\n /// The derivation vector of the curve.\n\n type Vector;\n\n /// Substitutes the parameter `t`.\n\n fn subs(&self, t: f64) -> Self::Point;\n\n /// Returns the derivation.\n\n fn der(&self, t: f64) -> Self::Vector;\n\n /// Returns the 2nd-order derivation.\n\n fn der2(&self, t: f64) -> Self::Vector;\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 35, "score": 170644.27569536155 }, { "content": "/// positive test implementation for `Cut` by random transformation\n\npub fn cut_random_test<C>(curve: &C, trials: usize)\n\nwhere\n\n C: Cut,\n\n C::Point: Debug + Tolerance,\n\n C::Vector: Debug + Tolerance, {\n\n (0..trials).for_each(move |_| exec_cut_random_test(curve))\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 36, "score": 170243.128146183 }, { "content": "/// The trait for Buffer Objects.\n\npub trait CreateBuffers {\n\n /// Creates buffer handlers of attributes and indices.\n\n fn buffers(\n\n &self,\n\n vertex_usage: BufferUsages,\n\n index_usage: BufferUsages,\n\n device: &Device,\n\n ) -> (BufferHandler, BufferHandler);\n\n}\n\n\n", "file_path": "truck-rendimpl/src/lib.rs", "rank": 37, "score": 169534.47585182983 }, { "content": "/// Find collisions between two polygon meshes and extract interference lines.\n\n///\n\n/// # Details\n\n///\n\n/// The algorithm for mesh extraction is as follows.\n\n/// All the triangles are projected toward the axis to form intervals.\n\n/// By looking at the overlap of these intervals, we can narrow down the interfering triangles.\n\n/// The overlap of the intervals is obtained by sorting the endpoints.\n\n///\n\n/// # Remarks\n\n///\n\n/// We see that the surfaces that are in contact are not interfering with each other.\n\n/// Therefore, polygon meshes included in one plane are not interfering.\n\npub trait Collision {\n\n /// If `self` and `other` collide, then returns only one interference line.\n\n /// Otherewise, returns `None`.\n\n fn collide_with(&self, other: &PolygonMesh) -> Option<(Point3, Point3)>;\n\n /// Extract all interference lines between `self` and `other`.\n\n /// # Remarks\n\n /// The results is not arranged so that included lines make continuous maximal polyline curve.\n\n fn extract_interference(&self, other: &PolygonMesh) -> Vec<(Point3, Point3)>;\n\n}\n\n\n\nimpl Collision for PolygonMesh {\n\n #[inline(always)]\n\n fn collide_with(&self, other: &PolygonMesh) -> Option<(Point3, Point3)> {\n\n are_colliding(self, other)\n\n }\n\n #[inline(always)]\n\n fn extract_interference(&self, other: &PolygonMesh) -> Vec<(Point3, Point3)> {\n\n collision(self, other)\n\n }\n\n}\n\n\n", "file_path": "truck-meshalgo/src/analyzers/collision.rs", "rank": 38, "score": 169528.68377953034 }, { "content": "/// for creating `InstanceCreator`\n\npub trait CreatorCreator {\n\n /// create `InstanceCreator`\n\n fn instance_creator(&self) -> InstanceCreator;\n\n}\n\n\n", "file_path": "truck-rendimpl/src/lib.rs", "rank": 39, "score": 169528.68377953034 }, { "content": "/// By implementing `IntoSTLIterator` for a type, you define how it will be converted to an iterator.\n\n/// This is common for types which describe a collection of some kind.\n\npub trait IntoSTLIterator {\n\n /// Which kind of iterator are we turning this into?\n\n type IntoIter: ExactSizeIterator<Item = STLFace>;\n\n /// Creates an iterator from a value.\n\n fn into_iter(self) -> Self::IntoIter;\n\n}\n\n\n\n/// STL face generate from `PolygonMesh`\n\n#[derive(Debug)]\n\npub struct PolygonMeshSTLFaceIterator<'a> {\n\n positions: &'a Vec<Point3>,\n\n faces: faces::TriangleIterator<'a, Vertex>,\n\n len: usize,\n\n}\n\n\n\nimpl<'a> Iterator for PolygonMeshSTLFaceIterator<'a> {\n\n type Item = STLFace;\n\n fn next(&mut self) -> Option<STLFace> {\n\n self.faces.next().map(|face| {\n\n let p = [\n", "file_path": "truck-polymesh/src/stl.rs", "rank": 40, "score": 169528.68377953034 }, { "content": "/// Splitting the faces into several clusters.\n\npub trait Splitting {\n\n /// Creates a sub mesh by the face indices.\n\n /// # Examples\n\n /// ```\n\n /// use truck_polymesh::*;\n\n /// use truck_meshalgo::analyzers::*;\n\n ///\n\n /// // cube\n\n /// let mesh = PolygonMesh::new(\n\n /// StandardAttributes {\n\n /// positions: vec![\n\n /// Point3::new(0.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 0.0, 1.0),\n\n /// Point3::new(1.0, 0.0, 1.0),\n\n /// Point3::new(1.0, 1.0, 1.0),\n\n /// Point3::new(0.0, 1.0, 1.0),\n\n /// ],\n", "file_path": "truck-meshalgo/src/analyzers/splitting.rs", "rank": 41, "score": 169528.68377953034 }, { "content": " /// trait for abstract control points of polylines and B-splines\n\n pub trait ControlPoint<S>:\n\n Add<Self::Diff, Output = Self>\n\n + Sub<Self::Diff, Output = Self>\n\n + Sub<Self, Output = Self::Diff>\n\n + Mul<S, Output = Self>\n\n + Div<S, Output = Self>\n\n + AddAssign<Self::Diff>\n\n + SubAssign<Self::Diff>\n\n + MulAssign<S>\n\n + DivAssign<S>\n\n + Copy\n\n + Clone\n\n + Debug {\n\n /// differential vector\n\n type Diff: Add<Self::Diff, Output = Self::Diff>\n\n + Sub<Self::Diff, Output = Self::Diff>\n\n + Mul<S, Output = Self::Diff>\n\n + Div<S, Output = Self::Diff>\n\n + AddAssign<Self::Diff>\n\n + SubAssign<Self::Diff>\n", "file_path": "truck-base/src/cgmath_extend_traits.rs", "rank": 42, "score": 168831.65123396396 }, { "content": "/// Bounded surface with parametric range\n\npub trait BoundedSurface: ParametricSurface {\n\n /// The range of the parameter of the surface.\n\n fn parameter_range(&self) -> ((f64, f64), (f64, f64));\n\n}\n\n\n\nimpl<'a, S: BoundedSurface> BoundedSurface for &'a S {\n\n fn parameter_range(&self) -> ((f64, f64), (f64, f64)) {\n\n (*self).parameter_range()\n\n }\n\n}\n\n\n\nimpl<S: BoundedSurface> BoundedSurface for Box<S> {\n\n fn parameter_range(&self) -> ((f64, f64), (f64, f64)) {\n\n (**self).parameter_range()\n\n }\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/surface.rs", "rank": 43, "score": 168826.0720052793 }, { "content": "/// parameter range move by affine transformation\n\npub trait ParameterTransform: BoundedCurve {\n\n /// parameter range move by affine transformation\n\n /// # Panics\n\n /// Panic occurs if `scalar` is not positive.\n\n fn parameter_transform(&mut self, scalar: f64, r#move: f64) -> &mut Self;\n\n /// parameter range move by affine transformation\n\n /// # Examples\n\n /// ```ignore\n\n /// let curve0 = ... // implemented ParameterTransform\n\n /// assert_eq!(curve0.parameter_range(), (0.0, 1.0));\n\n /// let curve1 = curve0.parameter_transformed(1.0, 2.0);\n\n /// assert_eq!(curve1.subs(0.5), curve0.subs(2.5));\n\n /// ```\n\n fn parameter_transformed(&self, scalar: f64, r#move: f64) -> Self {\n\n let mut curve = self.clone();\n\n curve.parameter_transform(scalar, r#move);\n\n curve\n\n }\n\n /// Makes the parameter range `(0.0, 1.0)`.\n\n fn parameter_normalization(&mut self) -> &mut Self {\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 44, "score": 168826.0720052793 }, { "content": "/// bounded parametric curves\n\npub trait BoundedCurve: ParametricCurve {\n\n /// The range of the parameter of the curve.\n\n fn parameter_range(&self) -> (f64, f64);\n\n /// The front end point of the curve.\n\n fn front(&self) -> Self::Point {\n\n let (t, _) = self.parameter_range();\n\n self.subs(t)\n\n }\n\n /// The back end point of the curve.\n\n fn back(&self) -> Self::Point {\n\n let (_, t) = self.parameter_range();\n\n self.subs(t)\n\n }\n\n}\n\n\n\n/// Implementation for the test of topological methods.\n\nimpl ParametricCurve for () {\n\n type Point = ();\n\n type Vector = ();\n\n fn subs(&self, _: f64) -> Self::Point {}\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 45, "score": 168826.0720052793 }, { "content": "#[wasm_bindgen]\n\npub fn homotopy(edge0: &Edge, edge1: &Edge) -> Face { builder::homotopy(&*edge0, &*edge1).into() }\n\n/// Try attatiching a plane whose boundary is `wire`.\n", "file_path": "truck-js/src/builder.rs", "rank": 46, "score": 168758.84150506262 }, { "content": "/// positive test implementation for `ParameterTransform` by random transformation\n\npub fn parameter_transform_random_test<C>(curve: &C, trials: usize)\n\nwhere\n\n C: ParameterTransform,\n\n C::Point: Debug + Tolerance,\n\n C::Vector: Debug + Tolerance + std::ops::Mul<f64, Output = C::Vector>, {\n\n (0..trials).for_each(move |_| exec_parameter_transform_random_test(curve))\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 47, "score": 167819.23309531287 }, { "content": "/// Trait for converting tessellated shape into polygon.\n\npub trait MeshedShape {\n\n /// Converts tessellated shape into polygon.\n\n fn to_polygon(&self) -> PolygonMesh;\n\n}\n\n\n\nimpl MeshedShape for Shell<Point3, PolylineCurve, PolygonMesh> {\n\n fn to_polygon(&self) -> PolygonMesh {\n\n let mut polygon = PolygonMesh::default();\n\n self.face_iter().for_each(|face| {\n\n polygon.merge(face.oriented_surface());\n\n });\n\n polygon\n\n }\n\n}\n\n\n\nimpl MeshedShape for Solid<Point3, PolylineCurve, PolygonMesh> {\n\n fn to_polygon(&self) -> PolygonMesh {\n\n let mut polygon = PolygonMesh::default();\n\n self.boundaries().iter().for_each(|shell| {\n\n polygon.merge(shell.to_polygon());\n\n });\n\n polygon\n\n }\n\n}\n\n\n", "file_path": "truck-meshalgo/src/tessellation/mod.rs", "rank": 48, "score": 167332.66743837006 }, { "content": "/// Trait for tessellating `Shell` and `Solid` in `truck-modeling`.\n\npub trait MeshableShape {\n\n /// Shape whose edges are made polylines and faces polygon surface.\n\n type MeshedShape: MeshedShape;\n\n /// Tessellates shapes. The division of curves and surfaces are by `ParameterDivision1D` and `ParameterDivision2D`,\n\n /// and the constrained Delauney triangulation is based on the crate [`spade`](https://crates.io/crates/spade).\n\n /// \n\n /// # Panics\n\n /// \n\n /// `tol` must be more than `TOLERANCE`.\n\n ///\n\n /// # Remarks\n\n ///\n\n /// The tessellated mesh is not necessarily closed even if `self` is `Solid`.\n\n /// If you want to get closed mesh, use `OptimizationFilter::put_together_same_attrs`.\n\n /// ```\n\n /// use truck_meshalgo::prelude::*;\n\n /// use truck_modeling::builder;\n\n /// use truck_topology::shell::ShellCondition;\n\n ///\n\n /// // modeling a unit cube\n", "file_path": "truck-meshalgo/src/tessellation/mod.rs", "rank": 49, "score": 167332.61473930907 }, { "content": "/// Filters for optimizing data\n\npub trait OptimizingFilter {\n\n /// remove all unused position, texture coordinates, and normal vectors.\n\n /// # Examples\n\n /// ```\n\n /// use truck_polymesh::*;\n\n /// use truck_meshalgo::filters::*;\n\n /// let mut mesh = PolygonMesh::new(\n\n /// StandardAttributes {\n\n /// positions: vec![\n\n /// Point3::new(0.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 0.0, 0.0),\n\n /// Point3::new(0.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 0.0, 1.0),\n\n /// ],\n\n /// ..Default::default()\n\n /// },\n\n /// // 0 is not used!\n\n /// Faces::from_iter(&[&[1, 2, 3]]),\n\n /// );\n\n ///\n", "file_path": "truck-meshalgo/src/filters/optimizing.rs", "rank": 50, "score": 167326.98377984023 }, { "content": "#[doc(hidden)]\n\npub trait ExperimentalSplitters {\n\n fn faces_into_two_clusters<F: Fn(&[Vertex]) -> bool>(\n\n &self,\n\n func: F,\n\n ) -> (Vec<usize>, Vec<usize>);\n\n fn clustering_faces_by_gcurvature(\n\n &self,\n\n threshold: f64,\n\n preferred_upper: bool,\n\n ) -> (Vec<usize>, Vec<usize>);\n\n fn get_gcurve(&self) -> Vec<f64>;\n\n}\n\n\n\n/// splitting the global faces\n\nimpl ExperimentalSplitters for PolygonMesh {\n\n /// separate all faces into two clusters, one with `func` returning true and the other with false.\n\n /// # Returns\n\n /// (the vector of all faces `f` which `func(f) == true`, the one of the other faces)\n\n fn faces_into_two_clusters<F: Fn(&[Vertex]) -> bool>(\n\n &self,\n", "file_path": "truck-meshalgo/src/analyzers/splitting.rs", "rank": 51, "score": 167326.98377984023 }, { "content": "/// triangulation, quadrangulation, give a structure\n\npub trait StructuringFilter {\n\n /// triangulate all n-gons\n\n /// # Examples\n\n /// ```\n\n /// use truck_polymesh::*;\n\n /// use truck_meshalgo::filters::*;\n\n ///\n\n /// // cube consisting quad faces\n\n /// let mut mesh = PolygonMesh::new(\n\n /// StandardAttributes {\n\n /// positions: vec![\n\n /// Point3::new(0.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 0.0, 1.0),\n\n /// Point3::new(1.0, 0.0, 1.0),\n\n /// Point3::new(1.0, 1.0, 1.0),\n\n /// Point3::new(0.0, 1.0, 1.0),\n\n /// ],\n", "file_path": "truck-meshalgo/src/filters/structuring.rs", "rank": 52, "score": 167326.98377984023 }, { "content": "fn exec_polysurface_division() -> bool {\n\n let coef0 = vec![\n\n Vector3::new(0.0, 1.0, 10.0 * rand::random::<f64>() - 5.0),\n\n Vector3::new(1.0, 0.0, 10.0 * rand::random::<f64>() - 5.0),\n\n Vector3::new(0.0, 0.0, 10.0 * rand::random::<f64>() - 5.0),\n\n ];\n\n let coef1 = vec![\n\n Vector3::new(1.0, 0.0, 10.0 * rand::random::<f64>() - 5.0),\n\n Vector3::new(0.0, 1.0, 10.0 * rand::random::<f64>() - 5.0),\n\n Vector3::new(0.0, 0.0, 10.0 * rand::random::<f64>() - 5.0),\n\n ];\n\n let poly = PolySurface(PolyCurve(coef0), PolyCurve(coef1));\n\n let (udiv, vdiv) = algo::surface::parameter_division(&poly, ((-1.0, 1.0), (-1.0, 1.0)), 0.1);\n\n for (i, u) in udiv\n\n .windows(2)\n\n .flat_map(move |u| (1..3).map(move |i| (i, u)))\n\n {\n\n for (j, v) in vdiv\n\n .windows(2)\n\n .flat_map(move |v| (1..3).map(move |j| (j, v)))\n", "file_path": "truck-geotrait/tests/surface.rs", "rank": 53, "score": 166040.27934144353 }, { "content": "fn exec_polycurve_division() -> bool {\n\n let coef: Vec<Vector3> = (0..5)\n\n .map(|_| {\n\n Vector3::new(\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n )\n\n })\n\n .collect();\n\n let poly = PolyCurve::<Point3>(coef);\n\n let (division, pts) = algo::curve::parameter_division(&poly, (-10.0, 10.0), 0.05);\n\n division.windows(2).zip(pts).all(|(a, pt)| {\n\n let pt0 = poly.subs(a[0]);\n\n assert_eq!(pt0, pt);\n\n let pt1 = poly.subs(a[1]);\n\n (1..3).all(|i| {\n\n let t = i as f64 / 3.0;\n\n let res = pt0 + (pt1 - pt0) * t;\n\n let t = a[0] * (1.0 - t) + a[1] * t;\n\n let ans = poly.subs(t);\n\n res.distance(ans) < 0.1\n\n })\n\n })\n\n}\n\n\n", "file_path": "truck-geotrait/tests/curve.rs", "rank": 54, "score": 166040.27934144353 }, { "content": "/// Only solids consisting of faces whose surface is implemented this trait can be used for set operations.\n\npub trait ShapeOpsSurface:\n\n\tParametricSurface3D\n\n\t+ ParameterDivision2D\n\n\t+ SearchParameter<Point = Point3, Parameter = (f64, f64)>\n\n\t+ SearchNearestParameter<Point = Point3, Parameter = (f64, f64)>\n\n\t+ Invertible {\n\n}\n\nimpl<S> ShapeOpsSurface for S where S: ParametricSurface3D\n\n\t\t+ ParameterDivision2D\n\n\t\t+ SearchParameter<Point = Point3, Parameter = (f64, f64)>\n\n\t\t+ SearchNearestParameter<Point = Point3, Parameter = (f64, f64)>\n\n\t\t+ Invertible\n\n{\n\n}\n\n\n", "file_path": "truck-shapeops/src/integrate/mod.rs", "rank": 55, "score": 165236.01331432545 }, { "content": "/// Filters for adding normals\n\npub trait NormalFilters {\n\n /// Normalize all normals and assign `None` to the `nor` index of the vertices\n\n /// that has irregular normals.\n\n /// # Examples\n\n /// ```\n\n /// use truck_polymesh::*;\n\n /// use truck_meshalgo::filters::*;\n\n ///\n\n /// // Morbid data only for testing\n\n /// let mut mesh = PolygonMesh::new(\n\n /// StandardAttributes {\n\n /// positions: vec![Point3::new(0.0, 0.0, 0.0)],\n\n /// normals: vec![\n\n /// Vector3::new(100.0, 20.0, 56.0),\n\n /// Vector3::new(1.0e-12, 3.536e10, std::f64::NAN),\n\n /// Vector3::new(0.0, 1.0, 0.0),\n\n /// ],\n\n /// ..Default::default()\n\n /// },\n\n /// Faces::from_iter(&[&[\n", "file_path": "truck-meshalgo/src/filters/normal_filters.rs", "rank": 56, "score": 165225.51417537453 }, { "content": "/// whether a point is in a domain rounded by a closed polygon.\n\npub trait IncludingPointInDomain {\n\n\t/// Count signed number of faces crossing ray with origin `point` and direction `ray_direction`.\n\n\t/// Counter increase if the dot product of the ray and the normal of a face is positive,\n\n\t/// and decrease if it is negative.\n\n\t///\n\n\t/// # Examples\n\n\t/// ```\n\n\t/// use truck_meshalgo::prelude::*;\n\n\t/// let simplex = PolygonMesh::new(\n\n\t/// StandardAttributes {\n\n\t/// positions: vec![\n\n\t/// Point3::new(0.0, 0.0, 0.0),\n\n\t/// Point3::new(1.0, 0.0, 0.0),\n\n\t/// Point3::new(0.0, 1.0, 0.0),\n\n\t/// Point3::new(0.0, 0.0, 1.0),\n\n\t/// ],\n\n\t/// ..Default::default()\n\n\t/// },\n\n\t/// Faces::from_iter(vec![\n\n\t/// [0, 2, 1],\n", "file_path": "truck-meshalgo/src/analyzers/in_out_judge.rs", "rank": 57, "score": 165225.51417537453 }, { "content": "pub trait FaceAdjacency {\n\n /// create the adjacency list of the faces\n\n fn face_adjacency(&self, use_normal: bool) -> Vec<Vec<usize>>;\n\n}\n\n\n\nimpl FaceAdjacency for Faces {\n\n fn face_adjacency(&self, use_normal: bool) -> Vec<Vec<usize>> {\n\n let len = self.len();\n\n let mut face_adjacency = vec![Vec::<usize>::new(); len];\n\n let mut edge_face_map = HashMap::default();\n\n for (i, face) in self.face_iter().enumerate() {\n\n face.windows(2)\n\n .chain(std::iter::once([face[face.len() - 1], face[0]].as_ref()))\n\n .for_each(|v| {\n\n signup_adjacency(i, v[0], v[1], &mut face_adjacency, &mut edge_face_map, use_normal)\n\n })\n\n }\n\n face_adjacency\n\n }\n\n}\n\n\n", "file_path": "truck-meshalgo/src/common/face_adjacency.rs", "rank": 58, "score": 165225.51417537453 }, { "content": "/// Transform geometry\n\npub trait Transformed<T>: Clone {\n\n /// transform by `trans`.\n\n fn transform_by(&mut self, trans: T);\n\n /// transformed geometry by `trans`.\n\n #[inline(always)]\n\n fn transformed(&self, trans: T) -> Self {\n\n let mut res = self.clone();\n\n res.transform_by(trans);\n\n res\n\n }\n\n}\n\n\n\nimpl<S: Transformed<T>, T> Transformed<T> for Box<S> {\n\n #[inline(always)]\n\n fn transform_by(&mut self, trans: T) { (**self).transform_by(trans) }\n\n #[inline(always)]\n\n fn transformed(&self, trans: T) -> Self { Box::new((**self).transformed(trans)) }\n\n}\n", "file_path": "truck-geotrait/src/traits/mod.rs", "rank": 59, "score": 165039.42750993077 }, { "content": "fn exec_polysurface_snp_on_surface() -> bool {\n\n let coef0 = vec![\n\n Vector3::new(0.0, 1.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(1.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n ];\n\n let coef1 = vec![\n\n Vector3::new(1.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 1.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n ];\n\n let poly = PolySurface(PolyCurve(coef0), PolyCurve(coef1));\n\n let u = 10.0 * rand::random::<f64>() - 5.0;\n\n let v = 10.0 * rand::random::<f64>() - 5.0;\n\n let pt = poly.subs(u, v);\n\n let u0 = u + 0.2 * rand::random::<f64>() - 0.1;\n\n let v0 = v + 0.2 * rand::random::<f64>() - 0.1;\n\n match algo::surface::search_nearest_parameter(&poly, pt, (u0, v0), 100) {\n\n Some(res) => match poly.subs(res.0, res.1).near(&pt) {\n\n true => true,\n", "file_path": "truck-geotrait/tests/surface.rs", "rank": 60, "score": 163945.53636972234 }, { "content": "fn exec_polycurve_snp_on_curve() -> bool {\n\n let coef: Vec<Vector3> = (0..5)\n\n .map(|_| {\n\n Vector3::new(\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n 20.0 * rand::random::<f64>() - 10.0,\n\n )\n\n })\n\n .collect();\n\n let poly = PolyCurve::<Point3>(coef);\n\n let t = 20.0 * rand::random::<f64>() - 10.0;\n\n let pt = poly.subs(t);\n\n let hint = t + 1.0 * rand::random::<f64>() - 0.5;\n\n match algo::curve::search_nearest_parameter(&poly, pt, hint, 100) {\n\n Some(res) => match poly.subs(res).near(&pt) {\n\n true => true,\n\n false => {\n\n eprintln!(\n\n \"wrong answer\\npolynomial: {:?}\\nt: {:?}\\nhint: {:?}\\nresult: {:?}\",\n", "file_path": "truck-geotrait/tests/curve.rs", "rank": 61, "score": 163945.53636972234 }, { "content": "fn exec_polysurface_sp_on_surface() -> bool {\n\n let coef0 = vec![\n\n Vector3::new(0.0, 1.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(1.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n ];\n\n let coef1 = vec![\n\n Vector3::new(1.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 1.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n Vector3::new(0.0, 0.0, 3.0 * rand::random::<f64>() - 1.5),\n\n ];\n\n let poly = PolySurface(PolyCurve(coef0), PolyCurve(coef1));\n\n let u = 10.0 * rand::random::<f64>() - 5.0;\n\n let v = 10.0 * rand::random::<f64>() - 5.0;\n\n let pt = poly.subs(u, v);\n\n let u0 = u + 2.0 * rand::random::<f64>() - 1.0;\n\n let v0 = v + 2.0 * rand::random::<f64>() - 1.0;\n\n match algo::surface::search_parameter3d(&poly, pt, (u0, v0), 100) {\n", "file_path": "truck-geotrait/tests/surface.rs", "rank": 62, "score": 163945.53636972234 }, { "content": "/// Investigates positional relation between polygon mesh and point cloud.\n\npub trait WithPointCloud {\n\n /// Whether all faces of the polygon mesh `self` has intersection with the neighborhood of `point_cloud`.\n\n /// # Arguments\n\n /// - `tol`: the radius of the neighborhoods of points in point cloud.\n\n /// # Panics\n\n /// `tol` must be more than `TOLERANCE`.\n\n /// # Examples\n\n /// ```\n\n /// use truck_meshalgo::prelude::*;\n\n /// let mesh = PolygonMesh::new(\n\n /// StandardAttributes {\n\n /// positions: vec![\n\n /// Point3::new(0.0, 0.0, 0.0),\n\n /// Point3::new(1.0, 0.0, 0.0),\n\n /// Point3::new(0.0, 1.0, 0.0),\n\n /// Point3::new(0.0, 0.0, 2.0),\n\n /// Point3::new(1.0, 0.0, 2.0),\n\n /// Point3::new(0.0, 1.0, 2.0),\n\n /// ],\n\n /// ..Default::default()\n", "file_path": "truck-meshalgo/src/analyzers/point_cloud/mod.rs", "rank": 63, "score": 163217.58294353366 }, { "content": "/// truck struct wrapped by wasm\n\npub trait IntoWasm: Sized {\n\n /// wasm wrapper struct\n\n type WasmWrapper: From<Self>;\n\n /// Into wasm wrapper\n\n fn into_wasm(self) -> Self::WasmWrapper { self.into() }\n\n}\n\n\n\nmod shape;\n\npub use shape::{AbstractShape, Edge, Face, Shell, Solid, Vertex, Wire};\n\n/// the building model utility API\n\npub mod builder;\n\nmod polygon;\n\n/// the boolean operators: `and`, `or`, `not`.\n\npub mod shapeops;\n\npub use polygon::{PolygonBuffer, PolygonMesh, STLType};\n", "file_path": "truck-js/src/lib.rs", "rank": 64, "score": 162829.036178609 }, { "content": "/// attribution container for polygin mesh\n\npub trait Attributes<V> {\n\n /// attribution\n\n type Output;\n\n /// get attribution corresponding to vertex\n\n fn get(&self, vertex: V) -> Option<Self::Output>;\n\n}\n\n\n\n/// standard attributions\n\n#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]\n\npub struct StandardAttributes {\n\n /// positions\n\n pub positions: Vec<Point3>,\n\n /// texture uv coordinates\n\n pub uv_coords: Vec<Vector2>,\n\n /// normals at vertices\n\n pub normals: Vec<Vector3>,\n\n}\n\n\n\n/// standard attribution\n\n#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]\n", "file_path": "truck-polymesh/src/lib.rs", "rank": 65, "score": 162823.28713423782 }, { "content": "/// Whether the surface includes the boundary curve.\n\npub trait IncludeCurve<C: ParametricCurve> {\n\n /// Returns whether the curve `curve` is included in the surface `self`.\n\n fn include(&self, curve: &C) -> bool;\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/surface.rs", "rank": 66, "score": 161475.2184050825 }, { "content": "/// The trait for defining the bounding box\n\npub trait Bounded<S> {\n\n /// the result of subtraction\n\n type Vector;\n\n #[doc(hidden)]\n\n fn infinity() -> Self;\n\n #[doc(hidden)]\n\n fn neg_infinity() -> Self;\n\n #[doc(hidden)]\n\n fn max(&self, other: &Self) -> Self;\n\n #[doc(hidden)]\n\n fn min(&self, other: &Self) -> Self;\n\n #[doc(hidden)]\n\n fn max_component(one: Self::Vector) -> S;\n\n #[doc(hidden)]\n\n fn diagonal(self, other: Self) -> Self::Vector;\n\n #[doc(hidden)]\n\n fn mid(self, other: Self) -> Self;\n\n}\n\n\n\nmacro_rules! pr2 {\n", "file_path": "truck-base/src/bounding_box.rs", "rank": 67, "score": 160627.3244878579 }, { "content": "/// Deterministic hash generator\n\npub trait HashGen<S> {\n\n\t/// deterministic hash, output 1-dim\n\n\tfn hash1(gen: Self) -> S;\n\n\t/// deterministic hash, output 2-dim\n\n\tfn hash2(gen: Self) -> [S; 2];\n\n\t/// deterministic hash, output 3-dim\n\n\tfn hash3(gen: Self) -> [S; 3];\n\n\t/// deterministic hash, output 4-dim\n\n\tfn hash4(gen: Self) -> [S; 4];\n\n}\n\n\n\nimpl<S: Float + FromPrimitive> HashGen<S> for S {\n\n\tfn hash1(s: S) -> S {\n\n\t\tlet a = S::from_f64(61.909685033545934).unwrap();\n\n\t\tlet b = S::from_f64(8.436303256302796).unwrap();\n\n\t\tlet c = S::from_f64(220.6786200836378).unwrap();\n\n\t\tlet x = S::sin(s * a + b) * c;\n\n\t\tx - S::floor(x)\n\n\t}\n\n\n", "file_path": "truck-base/src/hash.rs", "rank": 68, "score": 160621.5871345477 }, { "content": "pub trait SpaceHash {\n\n fn hash(self, space: &HashedPointCloud) -> [usize; 3];\n\n}\n\n\n\nimpl SpaceHash for Point3 {\n\n #[inline(always)]\n\n fn hash(self, space: &HashedPointCloud) -> [usize; 3] {\n\n let x = (self[0] - space.range[0][0]) / (space.range[0][1] - space.range[0][0]);\n\n let ix = f64::clamp(x * space.size[0] as f64, 0.0, space.size[0] as f64 - 1.0) as usize;\n\n let y = (self[1] - space.range[1][0]) / (space.range[1][1] - space.range[1][0]);\n\n let iy = f64::clamp(y * space.size[1] as f64, 0.0, space.size[1] as f64 - 1.0) as usize;\n\n let z = (self[2] - space.range[2][0]) / (space.range[2][1] - space.range[2][0]);\n\n let iz = f64::clamp(z * space.size[2] as f64, 0.0, space.size[2] as f64 - 1.0) as usize;\n\n [ix, iy, iz]\n\n }\n\n}\n\n\n\nimpl SpaceHash for usize {\n\n #[inline(always)]\n\n fn hash(self, space: &HashedPointCloud) -> [usize; 3] {\n\n [\n\n self / (space.size[1] * space.size[2]),\n\n self % (space.size[1] * space.size[2]) / space.size[2],\n\n self % space.size[2],\n\n ]\n\n }\n\n}\n\n\n", "file_path": "truck-meshalgo/src/analyzers/point_cloud/hashed_point_cloud.rs", "rank": 69, "score": 159458.41925506742 }, { "content": "// type definition for test\n\ntype Vertex = truck_topology::Vertex<()>;\n", "file_path": "truck-topology/tests/large-solid-torus.rs", "rank": 70, "score": 158796.76809021365 }, { "content": "/// Divides the domain into equal parts, examines all the values, and returns `(u, v)` such that `surface.subs(u, v)` is closest to `point`.\n\n/// This method is useful to get an efficient hint of `search_nearest_parameter`.\n\npub fn presearch<S>(\n\n surface: &S,\n\n point: S::Point,\n\n (urange, vrange): ((f64, f64), (f64, f64)),\n\n division: usize,\n\n) -> (f64, f64)\n\nwhere\n\n S: ParametricSurface,\n\n S::Point: MetricSpace<Metric = f64> + Copy,\n\n{\n\n let mut res = (0.0, 0.0);\n\n let mut min = std::f64::INFINITY;\n\n let ((u0, u1), (v0, v1)) = (urange, vrange);\n\n for i in 0..=division {\n\n for j in 0..=division {\n\n let p = i as f64 / division as f64;\n\n let q = j as f64 / division as f64;\n\n let u = u0 * (1.0 - p) + u1 * p;\n\n let v = v0 * (1.0 - q) + v1 * q;\n\n let dist = surface.subs(u, v).distance2(point);\n\n if dist < min {\n\n min = dist;\n\n res = (u, v);\n\n }\n\n }\n\n }\n\n res\n\n}\n\n\n", "file_path": "truck-geotrait/src/algo/surface.rs", "rank": 71, "score": 158558.81399854578 }, { "content": "/// The trait for generating `Instance` from `Self`.\n\npub trait ToInstance<I: Instance> {\n\n /// Configuation deacriptor for instance.\n\n type State;\n\n /// Creates `Instance` from `self`.\n\n fn to_instance(&self, handler: &DeviceHandler, shaders: &I::Shaders, desc: &Self::State) -> I;\n\n}\n\n\n", "file_path": "truck-rendimpl/src/lib.rs", "rank": 72, "score": 157229.81794965971 }, { "content": "fn split_into_nondegenerate(poly: Vec<Vertex>) -> Vec<Vec<Vertex>> {\n\n for i in 0..poly.len() {\n\n for j in (i + 1)..poly.len() {\n\n if poly[i].pos == poly[j].pos {\n\n let polygon0: Vec<_> = (0..(j - i)).map(|k| poly[k + i]).collect();\n\n let polygon1: Vec<_> = ((j - i)..poly.len())\n\n .map(|k| poly[(k + i) % poly.len()])\n\n .collect();\n\n let mut result = split_into_nondegenerate(polygon0);\n\n result.extend(split_into_nondegenerate(polygon1));\n\n return result;\n\n }\n\n }\n\n }\n\n vec![poly]\n\n}\n\n\n", "file_path": "truck-meshalgo/src/filters/optimizing.rs", "rank": 73, "score": 156684.10197415616 }, { "content": "#[inline(always)]\n\npub fn parameter_division<S>(\n\n surface: &S,\n\n (urange, vrange): ((f64, f64), (f64, f64)),\n\n tol: f64,\n\n) -> (Vec<f64>, Vec<f64>)\n\nwhere\n\n S: ParametricSurface,\n\n S::Point: EuclideanSpace<Scalar = f64> + MetricSpace<Metric = f64> + HashGen<f64>,\n\n{\n\n nonpositive_tolerance!(tol);\n\n let (mut udiv, mut vdiv) = (vec![urange.0, urange.1], vec![vrange.0, vrange.1]);\n\n sub_parameter_division(surface, (&mut udiv, &mut vdiv), tol);\n\n (udiv, vdiv)\n\n}\n\n\n", "file_path": "truck-geotrait/src/algo/surface.rs", "rank": 74, "score": 156465.74110455957 }, { "content": "pub fn pointcloud_in_polygon_neighborhood(\n\n polygon: &PolygonMesh,\n\n points: &[Point3],\n\n tol: f64,\n\n) -> bool {\n\n nonpositive_tolerance!(tol, 0.0);\n\n let mut current = Vec::new();\n\n let triangles = polygon.faces().triangle_iter().collect::<Vec<_>>();\n\n sorted_endpoints_by_polymesh_points(polygon, points, tol)\n\n .into_iter()\n\n .all(move |EndPoint { r#type, index, .. }| match r#type {\n\n EndPointType::Front => {\n\n current.push(index);\n\n true\n\n }\n\n EndPointType::Back => {\n\n let i = current\n\n .iter()\n\n .enumerate()\n\n .find(|(_, idx)| **idx == index)\n", "file_path": "truck-meshalgo/src/analyzers/point_cloud/sort_end_points.rs", "rank": 75, "score": 155543.14539027627 }, { "content": "/// positive test implementation for `Concat`.\n\npub fn concat_random_test<C0, C1>(curve0: &C0, curve1: &C1, trials: usize)\n\nwhere\n\n C0: Concat<C1>,\n\n C0::Point: Debug + Tolerance,\n\n C0::Vector: Debug + Tolerance,\n\n C0::Output: BoundedCurve<Point = C0::Point, Vector = C0::Vector> + Debug,\n\n C1: BoundedCurve<Point = C0::Point, Vector = C0::Vector>, {\n\n (0..trials).for_each(move |_| exec_concat_random_test(curve0, curve1))\n\n}\n\n\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 76, "score": 155133.28774989056 }, { "content": "/// The structs defined the origin. `f64`, `Vector`, and so on.\n\npub trait Origin: Tolerance + Zero {\n\n /// near origin\n\n #[inline(always)]\n\n fn so_small(&self) -> bool { self.near(&Self::zero()) }\n\n\n\n /// near origin in square order\n\n #[inline(always)]\n\n fn so_small2(&self) -> bool { self.near2(&Self::zero()) }\n\n}\n\n\n\nimpl<T: Tolerance + Zero> Origin for T {}\n", "file_path": "truck-base/src/tolerance.rs", "rank": 77, "score": 155022.43418929333 }, { "content": "/// The framework of applications with `winit`.\n\n/// The main function of this file is the smallest usecase of this trait.\n\npub trait App: Sized + 'static {\n\n /// Initialize application\n\n /// # Arguments\n\n /// - handler: `DeviceHandler` provided by `wgpu`\n\n /// - info: informations of device and backend\n\n fn init(window: Arc<Window>) -> Self;\n\n /// By overriding this function, you can change the display of the title bar.\n\n /// It is not possible to change the window while it is running.\n\n fn app_title<'a>() -> Option<&'a str> { None }\n\n /// Default is `ControlFlow::WaitUntil(1 / 60 seconds)`.\n\n fn default_control_flow() -> ControlFlow {\n\n let next_frame_time = Instant::now() + Duration::from_nanos(16_666_667);\n\n ControlFlow::WaitUntil(next_frame_time)\n\n }\n\n /// By overriding this function, one can set the rendering process for each frame.\n\n fn render(&mut self) {}\n\n /// By overriding this function, one can change the behavior when the window is resized.\n\n fn resized(&mut self, _size: PhysicalSize<u32>) -> ControlFlow { Self::default_control_flow() }\n\n /// By overriding this function, one can change the behavior when the window is moved.\n\n fn moved(&mut self, _position: PhysicalPosition<i32>) -> ControlFlow {\n", "file_path": "truck-rendimpl/examples/app.rs", "rank": 78, "score": 155022.21751624456 }, { "content": "/// Searches the nearest parameter by Newton's method.\n\npub fn search_nearest_parameter<C>(\n\n curve: &C,\n\n point: C::Point,\n\n mut hint: f64,\n\n trials: usize,\n\n) -> Option<f64>\n\nwhere\n\n C: ParametricCurve,\n\n C::Point: EuclideanSpace<Scalar = f64, Diff = C::Vector>,\n\n C::Vector: InnerSpace<Scalar = f64> + Tolerance,\n\n{\n\n #[cfg(all(test, debug_assertions))]\n\n let mut log = Vec::new();\n\n for _ in 0..=trials {\n\n #[cfg(all(test, debug_assertions))]\n\n log.push(hint);\n\n let pt = curve.subs(hint);\n\n let der = curve.der(hint);\n\n let der2 = curve.der2(hint);\n\n let f = der.dot(pt - point);\n", "file_path": "truck-geotrait/src/algo/curve.rs", "rank": 79, "score": 154470.39901576063 }, { "content": "/// Searches the nearest parameter by Newton's method.\n\npub fn search_nearest_parameter<S>(\n\n surface: &S,\n\n point: S::Point,\n\n mut hint: (f64, f64),\n\n trials: usize,\n\n) -> Option<(f64, f64)>\n\nwhere\n\n S: ParametricSurface,\n\n S::Point: EuclideanSpace<Scalar = f64, Diff = S::Vector>,\n\n S::Vector: InnerSpace<Scalar = f64> + Tolerance,\n\n{\n\n #[cfg(all(test, debug_assertions))]\n\n let mut log = Vec::new();\n\n for _ in 0..=trials {\n\n #[cfg(all(test, debug_assertions))]\n\n log.push(hint);\n\n let (u0, v0) = hint;\n\n let s = surface.subs(u0, v0);\n\n let ud = surface.uder(u0, v0);\n\n let vd = surface.vder(u0, v0);\n", "file_path": "truck-geotrait/src/algo/surface.rs", "rank": 80, "score": 154470.39901576063 }, { "content": "#[doc(hidden)]\n\npub fn double_projection<S>(\n\n\tsurface0: &S,\n\n\thint0: Option<(f64, f64)>,\n\n\tsurface1: &S,\n\n\thint1: Option<(f64, f64)>,\n\n\tmut point: Point3,\n\n\tnormal: Vector3,\n\n\ttrials: usize,\n\n) -> Option<(Point3, Point2, Point2)>\n\nwhere\n\n\tS: ParametricSurface3D + SearchNearestParameter<Point = Point3, Parameter = (f64, f64)>,\n\n{\n\n\t#[cfg(all(test, debug_assertions))]\n\n\tlet mut log = Vec::new();\n\n\tlet mut uv0 = surface0.search_nearest_parameter(point, hint0, 10)?;\n\n\tlet mut uv1 = surface1.search_nearest_parameter(point, hint1, 10)?;\n\n\tfor _ in 0..trials {\n\n\t\t#[cfg(all(test, debug_assertions))]\n\n\t\tlog.push((point, uv0, uv1));\n\n\t\tuv0 = surface0.search_nearest_parameter(point, Some(uv0), 10)?;\n", "file_path": "truck-geometry/src/decorators/intersection_curve.rs", "rank": 81, "score": 154470.39901576063 }, { "content": "pub fn intersection_curves<S>(\n\n\tsurface0: S,\n\n\tpolygon0: &PolygonMesh,\n\n\tsurface1: S,\n\n\tpolygon1: &PolygonMesh,\n\n\ttol: f64,\n\n) -> Vec<(\n\n\tPolylineCurve<Point3>,\n\n\tOption<IntersectionCurveWithParameters<S>>,\n\n)>\n\nwhere\n\n\tS: ParametricSurface3D + SearchNearestParameter<Point = Point3, Parameter = (f64, f64)>,\n\n{\n\n\tlet interferences = polygon0.extract_interference(polygon1);\n\n\tlet polylines = crate::polyline_construction::construct_polylines(&interferences);\n\n\tpolylines\n\n\t\t.into_iter()\n\n\t\t.map(|polyline| {\n\n\t\t\tlet curve = IntersectionCurveWithParameters::try_new(\n\n\t\t\t\tsurface0.clone(),\n", "file_path": "truck-shapeops/src/intersection_curve/mod.rs", "rank": 82, "score": 154470.39901576063 }, { "content": "#[inline(always)]\n\npub fn clone<T: Mapped<Point3, Curve, Surface>>(elem: &T) -> T { elem.topological_clone() }\n\n\n\n/// Returns a transformed vertex, edge, wire, face, shell or solid.\n", "file_path": "truck-modeling/src/builder.rs", "rank": 83, "score": 152620.79458814277 }, { "content": "pub trait DistanceWithPointCloud: Sized {\n\n fn distance2(&self, space: &HashedPointCloud) -> f64;\n\n fn distance(&self, space: &HashedPointCloud) -> f64 { f64::sqrt(self.distance2(space)) }\n\n fn is_colliding(&self, space: &HashedPointCloud, tol: f64) -> bool {\n\n nonpositive_tolerance!(tol, 0.0);\n\n self.distance2(space) < tol * tol\n\n }\n\n}\n\n\n\nimpl DistanceWithPointCloud for Point3 {\n\n fn distance2(&self, space: &HashedPointCloud) -> f64 {\n\n let idcs = self.hash(space);\n\n let closure = |dist2: f64, pt: &Point3| f64::min(dist2, MetricSpace::distance2(*self, *pt));\n\n let mut dist2 = space[idcs].iter().fold(std::f64::INFINITY, closure);\n\n if idcs[0] > 0 {\n\n dist2 = space[[idcs[0] - 1, idcs[1], idcs[2]]]\n\n .iter()\n\n .fold(dist2, closure);\n\n }\n\n if idcs[0] + 1 < space.size[0] {\n", "file_path": "truck-meshalgo/src/analyzers/point_cloud/hashed_point_cloud.rs", "rank": 84, "score": 149301.15097496822 }, { "content": "pub fn os_alt_exec_test<F: Fn(Backends, &str)>(test: F) {\n\n let _ = env_logger::try_init();\n\n if cfg!(target_os = \"windows\") {\n\n test(Backends::VULKAN, \"output/vulkan/\");\n\n test(Backends::DX12, \"output/dx12/\");\n\n } else if cfg!(target_os = \"macos\") {\n\n test(Backends::METAL, \"output/\");\n\n } else {\n\n test(Backends::VULKAN, \"output/\");\n\n }\n\n}\n", "file_path": "truck-platform/tests/common.rs", "rank": 85, "score": 149012.01456609 }, { "content": "pub fn os_alt_exec_test<F: Fn(Backends, &str)>(test: F) {\n\n let _ = env_logger::try_init();\n\n if cfg!(target_os = \"windows\") {\n\n test(Backends::VULKAN, \"output/vulkan/\");\n\n test(Backends::DX12, \"output/dx12/\");\n\n } else if cfg!(target_os = \"macos\") {\n\n test(Backends::METAL, \"output/\");\n\n } else {\n\n test(Backends::VULKAN, \"output/\");\n\n }\n\n}\n", "file_path": "truck-rendimpl/tests/common.rs", "rank": 86, "score": 149012.01456609 }, { "content": "#[wasm_bindgen]\n\npub fn not(solid: &Solid) -> Solid {\n\n\tlet mut solid = solid.clone();\n\n\tsolid.not();\n\n\tsolid\n\n}\n", "file_path": "truck-js/src/shapeops.rs", "rank": 87, "score": 148420.29794326026 }, { "content": " /// Abstract sweeping, builds a circle-arc, a prism, a half torus, and so on.\n\n pub trait Sweep<P, C, S> {\n\n /// The struct of sweeped topology.\n\n type Swept;\n\n /// Transform topologies and connect vertices and edges in boundaries.\n\n fn sweep<\n\n FP: Fn(&P) -> P,\n\n FC: Fn(&C) -> C,\n\n FS: Fn(&S) -> S,\n\n CP: Fn(&P, &P) -> C,\n\n CE: Fn(&C, &C) -> S,\n\n >(\n\n &self,\n\n point_mapping: &FP,\n\n curve_mapping: &FC,\n\n surface_mapping: &FS,\n\n connect_points: &CP,\n\n connect_curve: &CE,\n\n ) -> Self::Swept;\n\n }\n\n\n", "file_path": "truck-modeling/src/lib.rs", "rank": 88, "score": 148160.57094472114 }, { "content": "#[allow(dead_code)]\n\nfn same_topology<P, C, S, Q, D, T>(one: &Shell<P, C, S>, other: &Shell<Q, D, T>) -> bool {\n\n let mut vmap = HashMap::<VertexID<P>, VertexID<Q>>::default();\n\n let mut emap = HashMap::<EdgeID<C>, EdgeID<D>>::default();\n\n if one.len() != other.len() {\n\n return false;\n\n }\n\n for (face0, face1) in one.iter().zip(other.iter()) {\n\n let biters0 = face0.boundary_iters();\n\n let biters1 = face1.boundary_iters();\n\n if biters0.len() != biters1.len() {\n\n return false;\n\n }\n\n for (biter0, biter1) in biters0.into_iter().zip(biters1) {\n\n if biter0.len() != biter1.len() {\n\n return false;\n\n }\n\n for (edge0, edge1) in biter0.zip(biter1) {\n\n if !emap_subroutin(&edge0, &edge1, &mut vmap, &mut emap) {\n\n return false;\n\n }\n\n }\n\n }\n\n }\n\n true\n\n}\n", "file_path": "truck-topology/src/compress.rs", "rank": 89, "score": 147770.98119337432 }, { "content": "pub fn divide_faces<C, S>(\n\n\tshell: &Shell<Point3, C, S>,\n\n\tloops_store: &LoopsStore<Point3, C>,\n\n\ttol: f64,\n\n) -> Option<FacesClassification<Point3, C, S>>\n\nwhere\n\n\tC: BoundedCurve<Point = Point3> + ParameterDivision1D<Point = Point3>,\n\n\tS: Clone + SearchParameter<Point = Point3, Parameter = (f64, f64)>,\n\n{\n\n\tlet mut res = FacesClassification::<Point3, C, S>::default();\n\n\tshell\n\n\t\t.iter()\n\n\t\t.zip(loops_store)\n\n\t\t.try_for_each(|(face, loops)| {\n\n\t\t\tif loops\n\n\t\t\t\t.iter()\n\n\t\t\t\t.all(|wire| wire.status() == ShapesOpStatus::Unknown)\n\n\t\t\t{\n\n\t\t\t\tres.push(face.clone(), ShapesOpStatus::Unknown);\n\n\t\t\t} else {\n", "file_path": "truck-shapeops/src/divide_face/mod.rs", "rank": 90, "score": 147079.25986882884 }, { "content": " /// Abstract multi sweeping, builds a circle-arc, a prism, a half torus, and so on.\n\n pub trait MultiSweep<P, C, S> {\n\n /// The struct of sweeped topology.\n\n type Swept;\n\n /// Transform topologies and connect vertices and edges in boundaries.\n\n fn multi_sweep<\n\n FP: Fn(&P) -> P,\n\n FC: Fn(&C) -> C,\n\n FS: Fn(&S) -> S,\n\n CP: Fn(&P, &P) -> C,\n\n CE: Fn(&C, &C) -> S,\n\n >(\n\n &self,\n\n point_mapping: &FP,\n\n curve_mapping: &FC,\n\n surface_mapping: &FS,\n\n connect_points: &CP,\n\n connect_curve: &CE,\n\n division: usize,\n\n ) -> Self::Swept;\n\n }\n\n\n", "file_path": "truck-modeling/src/lib.rs", "rank": 91, "score": 146152.6397128803 }, { "content": "#[test]\n\nfn sliced_hashmap() {\n\n\tlet mut map: SliceHashMap<_, _> = (0..100).map(|i| (i, 100 - i)).collect();\n\n\tassert_eq!(map.len(), 100);\n\n\tassert_eq!(map.vec.len(), map.map.len());\n\n\tfor i in 0..100 {\n\n\t\tassert_eq!(map.insert(i, i + 200).unwrap(), 100 - i);\n\n\t\tassert_eq!(map.vec.len(), map.map.len());\n\n\t}\n\n\tfor i in 0..100 {\n\n\t\tassert_eq!(*map.get(&i).unwrap(), i + 200);\n\n\t\tassert_eq!(map.vec.len(), map.map.len());\n\n\t}\n\n\tassert!(map.insert(100, 300).is_none());\n\n\tassert_eq!(map.len(), 101);\n\n\tfor i in 0..100 {\n\n\t\tassert_eq!(map.remove(&i).unwrap(), i + 200);\n\n\t\tassert_eq!(map.vec.len(), map.map.len());\n\n\t}\n\n\tassert_eq!(map.len(), 1);\n\n\tmap.clear();\n\n\tassert_eq!(map.len(), 0);\n\n}\n", "file_path": "truck-platform/src/slice_hashmap.rs", "rank": 92, "score": 145946.4018891638 }, { "content": "/// Only solids consisting of edges whose curve is implemented this trait can be used for set operations.\n\npub trait ShapeOpsCurve<S: ShapeOpsSurface>:\n\n\tParametricCurve3D\n\n\t+ ParameterDivision1D<Point = Point3>\n\n\t+ Cut\n\n\t+ Invertible\n\n\t+ From<IntersectionCurve<PolylineCurve<Point3>, S>>\n\n\t+ SearchParameter<Point = Point3, Parameter = f64>\n\n\t+ SearchNearestParameter<Point = Point3, Parameter = f64> {\n\n}\n\nimpl<C, S: ShapeOpsSurface> ShapeOpsCurve<S> for C where C: ParametricCurve3D\n\n\t\t+ ParameterDivision1D<Point = Point3>\n\n\t\t+ Cut\n\n\t\t+ Invertible\n\n\t\t+ From<IntersectionCurve<PolylineCurve<Point3>, S>>\n\n\t\t+ SearchParameter<Point = Point3, Parameter = f64>\n\n\t\t+ SearchNearestParameter<Point = Point3, Parameter = f64>\n\n{\n\n}\n\n\n", "file_path": "truck-shapeops/src/integrate/mod.rs", "rank": 93, "score": 145402.03181477534 }, { "content": "pub trait SurfaceFromExpress: ParametricSurface3D + ParameterDivision2D {}\n\nimpl<S: ParametricSurface3D + ParameterDivision2D> SurfaceFromExpress for S {}\n", "file_path": "truck-stepio/src/alias.rs", "rank": 94, "score": 145386.2311860761 }, { "content": "pub fn create_loops_stores<C, S>(\n\n\tgeom_shell0: &Shell<Point3, C, S>,\n\n\tpoly_shell0: &Shell<Point3, PolylineCurve, PolygonMesh>,\n\n\tgeom_shell1: &Shell<Point3, C, S>,\n\n\tpoly_shell1: &Shell<Point3, PolylineCurve, PolygonMesh>,\n\n\ttol: f64,\n\n) -> Option<LoopsStoreQuadruple<C>>\n\nwhere\n\n\tC: SearchNearestParameter<Point = Point3, Parameter = f64>\n\n\t\t+ SearchParameter<Point = Point3, Parameter = f64>\n\n\t\t+ Cut<Point = Point3, Vector = Vector3>\n\n\t\t+ From<IntersectionCurve<PolylineCurve, S>>,\n\n\tS: ParametricSurface3D + SearchNearestParameter<Point = Point3, Parameter = (f64, f64)>,\n\n{\n\n\tlet mut geom_loops_store0: LoopsStore<_, _> = geom_shell0.face_iter().collect();\n\n\tlet mut poly_loops_store0: LoopsStore<_, _> = poly_shell0.face_iter().collect();\n\n\tlet mut geom_loops_store1: LoopsStore<_, _> = geom_shell1.face_iter().collect();\n\n\tlet mut poly_loops_store1: LoopsStore<_, _> = poly_shell1.face_iter().collect();\n\n\tlet store0_len = geom_loops_store0.len();\n\n\tlet store1_len = geom_loops_store1.len();\n", "file_path": "truck-shapeops/src/loops_store/mod.rs", "rank": 95, "score": 145252.1261672465 }, { "content": "#[inline(always)]\n\npub fn search_parameter3d<S: ParametricSurface3D>(\n\n surface: &S,\n\n point: Point3,\n\n (u0, v0): (f64, f64),\n\n trials: usize,\n\n) -> Option<(f64, f64)> {\n\n let proj = ProjectedSurface::new(surface, (u0, v0));\n\n search_parameter2d(&proj, proj.point_proj(point), (u0, v0), trials).and_then(|(u, v)| {\n\n match surface.subs(u, v).near(&point) {\n\n true => Some((u, v)),\n\n false => None,\n\n }\n\n })\n\n}\n\n\n\n/// Creates the surface division\n\n///\n\n/// # Panics\n\n///\n\n/// `tol` must be more than `TOLERANCE`.\n", "file_path": "truck-geotrait/src/algo/surface.rs", "rank": 96, "score": 145252.1261672465 }, { "content": "fn degenerate_quadrangle(quad: [Vertex; 4]) -> QuadrangleType {\n\n if (quad[0].pos == quad[2].pos || quad[1].pos == quad[3].pos)\n\n || (quad[0].pos == quad[1].pos && quad[2].pos == quad[3].pos)\n\n || quad[1].pos == quad[2].pos && quad[3].pos == quad[0].pos\n\n {\n\n QuadrangleType::TotallyDegenerate\n\n } else if quad[0].pos == quad[1].pos || quad[1].pos == quad[2].pos {\n\n QuadrangleType::Triangle([quad[0], quad[2], quad[3]])\n\n } else if quad[2].pos == quad[3].pos || quad[3].pos == quad[0].pos {\n\n QuadrangleType::Triangle([quad[0], quad[1], quad[2]])\n\n } else {\n\n QuadrangleType::NonDegenerate\n\n }\n\n}\n\n\n", "file_path": "truck-meshalgo/src/filters/optimizing.rs", "rank": 97, "score": 143126.63933158928 }, { "content": "/// Homogeneous coordinate of an Euclidean space and a vector space.\n\n/// # Examples\n\n/// ```\n\n/// use truck_base::cgmath64::*;\n\n/// use truck_base::cgmath_extend_traits::*;\n\n/// assert_eq!(Vector4::new(8.0, 6.0, 4.0, 2.0).truncate(), Vector3::new(8.0, 6.0, 4.0));\n\n/// assert_eq!(Vector4::new(8.0, 6.0, 4.0, 2.0).weight(), 2.0);\n\n/// assert_eq!(Vector4::new(8.0, 6.0, 4.0, 2.0).to_point(), Point3::new(4.0, 3.0, 2.0));\n\n/// assert_eq!(Vector4::from_point(Point3::new(4.0, 3.0, 2.0)), Vector4::new(4.0, 3.0, 2.0, 1.0));\n\n/// ```\n\npub trait Homogeneous<S: BaseFloat>: VectorSpace<Scalar = S> {\n\n /// The tangent vector of `Self::Point`\n\n type Vector: VectorSpace<Scalar = S>;\n\n /// The point expressed by homogeneous coordinate\n\n type Point: EuclideanSpace<Scalar = S, Diff = Self::Vector>;\n\n /// Returns the first dim - 1 components.\n\n fn truncate(self) -> Self::Vector;\n\n /// Returns the last component.\n\n fn weight(self) -> S;\n\n /// Returns homogeneous coordinate.\n\n fn from_point(point: Self::Point) -> Self;\n\n /// Returns homogeneous coordinate from point and weight.\n\n fn from_point_weight(point: Self::Point, weight: S) -> Self;\n\n /// Returns the projection to the plane whose the last component is `1.0`.\n\n #[inline(always)]\n\n fn to_point(self) -> Self::Point { Self::Point::from_vec(self.truncate() / self.weight()) }\n\n /// Returns the derivation of the rational curve.\n\n ///\n\n /// For a curve c(t) = (c_0(t), c_1(t), c_2(t), c_3(t)), returns the derivation\n\n /// of the projected curve (c_0 / c_3, c_1 / c_3, c_2 / c_3, 1.0).\n", "file_path": "truck-base/src/cgmath_extend_traits.rs", "rank": 98, "score": 142688.0529863232 }, { "content": "/// 2D parametric curve\n\npub trait ParametricCurve2D: ParametricCurve<Point = Point2, Vector = Vector2> {}\n\nimpl<C: ParametricCurve<Point = Point2, Vector = Vector2>> ParametricCurve2D for C {}\n", "file_path": "truck-geotrait/src/traits/curve.rs", "rank": 99, "score": 142672.30937097588 } ]
Rust
qapro-rs/src/qaruntime/monitor.rs
B34nK0/QUANTAXIS
94162f0f863682e443ef8ae11f5b54da6f93421b
extern crate redis; use actix::prelude::*; use actix::{Actor, Addr, AsyncContext, Context, Handler, Recipient, Supervised}; use chrono::{Local, TimeZone}; use log::{error, info, warn}; use redis::Commands; use serde_json::Value; use std::fmt::Debug; use std::time::Duration; use uuid::Version::Mac; use crate::qaaccount::account::QA_Account; use crate::qaaccount::marketpreset::MarketPreset; use crate::qaaccount::order::QAOrder; use crate::qaconnector::mongo::mongoclient::QAMongoClient; use crate::qadata::resample::{resample_db, QARealtimeResampler}; use crate::qaenv::localenv::CONFIG; use crate::qaprotocol::mifi::qafastkline::QAKlineBase; use crate::qaprotocol::qifi::account::QIFI; use crate::qaruntime::base::{Ack, AddMonitor, Instruct, Order, QAKline, QAOrderRsp, QifiRsp}; use crate::qaruntime::qacontext::{QAContext, StrategyFunc}; use crate::qaruntime::qamanagers::monitor_manager::MonitorManager; use crate::qautil::tradedate::QATradeDate; enum StateCode {} pub struct Monitor<T> { pub qactx: QAContext, pub stg: T, pub mor_manger: Addr<MonitorManager>, pub qarere: QARealtimeResampler, ur: bool, td: QATradeDate, settle_ts: i64, qifi_ts: i64, } impl<T: 'static> Monitor<T> where T: StrategyFunc + Debug, { pub fn new(qactx: QAContext, stg: T, mor_manger: Addr<MonitorManager>) -> Self { let f = qactx.frequence.clone(); let freq = f[0..f.len() - 3].parse::<i64>().unwrap(); let qarere = QARealtimeResampler::new(freq); let u = Self { qactx, stg, mor_manger, qarere, ur: true, td: QATradeDate::new(), settle_ts: 0, qifi_ts: 0, }; u } pub fn backtest(&mut self, mongo_data: &Vec<QAKlineBase>, redis_data: &Vec<QAKlineBase>) { info!("[{}] backtest mongo...", self.qactx.account_cookie); for (realtimebar, is_last) in mongo_data .into_iter() .map(|data| (data.clone().to_bar(), data.is_last)) { println!("{:#?}", realtimebar); if !self .qactx .acc .get_tradingday() .eq(&self.td.get_trade_day(realtimebar.datetime.clone())) { self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); } if is_last { self.ur = true; self.qactx.update(realtimebar.clone(), &mut self.stg); self.qactx.switch(realtimebar); } else { if self.ur { self.qactx.next(realtimebar, &mut self.stg); self.ur = false; } else { self.qactx.update(realtimebar, &mut self.stg); } } } self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); info!("[{}] backtest mongo end", self.qactx.account_cookie); info!("[{}] backtest redis...", self.qactx.account_cookie); for (realtimebar, is_last) in redis_data .into_iter() .map(|data| (data.clone().to_bar(), data.is_last)) { if !self .qactx .acc .get_tradingday() .eq(&self.td.get_trade_day(realtimebar.datetime.clone())) { self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); } if is_last { self.ur = true; self.qactx.update(realtimebar.clone(), &mut self.stg); self.qactx.switch(realtimebar); } else { if self.ur { self.qactx.next(realtimebar, &mut self.stg); self.ur = false; } else { self.qactx.update(realtimebar, &mut self.stg); } } } info!("[{}] backtest redis end", self.qactx.account_cookie); self.qactx .acc .to_csv(format!("{}.csv", self.qactx.account_cookie)); self.qactx.order_que.clear(); } pub fn inner_handle(&mut self, msg: QAKlineBase) { let bar = self.qarere.next(msg.to_bar()); let (is_last, data) = (bar.is_last, bar.to_bar()); if is_last { self.ur = true; self.qactx.update(data.clone(), &mut self.stg); self.qactx.switch(data); } else { if self.ur { self.qactx.next(data, &mut self.stg); self.ur = false; } else { self.qactx.update(data, &mut self.stg); } } match self.mor_manger.try_send(QAOrderRsp { data: self.qactx.order_que.clone(), }) { Err(e) => { let m = format!("pub orders fail {:?}", e.to_string()); } _ => {} } self.qactx.order_que.clear(); match self.mor_manger.try_send(QifiRsp { t: 0, data: self.qactx.acc.get_qifi_slice(), }) { Err(e) => { let m = format!("qifi save fail {:?}", e.to_string()); } _ => { self.qifi_ts = Local::now().timestamp(); } } } pub fn manual_settle(&mut self, instruct: Instruct) { let ts = Local::now().timestamp(); if instruct.body.eq("--force") || ts - self.settle_ts > 60 * 60 * 24 { match self.mor_manger.try_send(QifiRsp { t: 1, data: self.qactx.acc.get_qifi_slice(), }) { Ok(_) => { self.settle_ts = ts; self.qactx.acc.settle(); let m = "settle success".to_owned(); self.ack(instruct, 200, m); } Err(e) => { let m = format!("save qifi_his fail{:?}", e.to_string()); self.ack(instruct, 500, m); } } } else { let m = "last time settle < 24h, or use [--force]".to_owned(); self.ack(instruct, 400, m); } } pub fn manual_send_order(&mut self, instruct: Instruct) { match serde_json::from_str(&instruct.body) { Ok(o) => { let time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string(); let code = self.qactx.code.clone(); let order: Order = o; if order.direction.eq("BUY") && order.offset.eq("OPEN") { self.qactx.buy_open(&code, order.volume, &time, order.price) } else if order.direction.eq("BUY") && order.offset.eq("CLOSE") { self.qactx .buy_close(&code, order.volume, &time, order.price) } else if order.direction.eq("SELL") && order.offset.eq("OPEN") { self.qactx .sell_open(&code, order.volume, &time, order.price) } else if order.direction.eq("SELL") && order.offset.eq("CLOSE") { self.qactx .sell_close(&code, order.volume, &time, order.price) } else { let m = "send_order fail".to_owned(); self.ack(instruct, 400, m); return; } let m = "send_order success".to_owned(); self.ack(instruct, 200, m); } Err(e) => { let m = format!("Instruct order parse fail {}", e.to_string()); self.ack(instruct, 400, m); } } } pub fn get_clock(&mut self, instruct: Instruct) { match instruct.body.as_str() { "stg_status" => println!("{:#?}", &self.stg), _ => {} } self.ack(instruct, 200, self.qactx.clock.clone()); } pub fn ack(&mut self, instruct: Instruct, status: i32, ack: String) { match self.mor_manger.try_send(Ack { id: instruct.id.clone(), status, ack, answerer: self.qactx.account_cookie.clone(), }) { Err(e) => { let s = format!("[{}] ack fail {}", self.qactx.account_cookie, e.to_string()); println!("{:#?}", &s); } _ => {} }; } } impl<T: 'static> Actor for Monitor<T> where T: StrategyFunc + Debug, { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.set_mailbox_capacity(10000); match self.mor_manger.try_send(AddMonitor { account_cookie: self.qactx.account_cookie.clone(), rec: ctx.address().recipient().clone(), }) { Err(e) => error!("monitor register fail {:?}", e.to_string()), _ => {} } ctx.run_interval(Duration::from_secs(30), |mor, ctx| { let t = Local::now().timestamp(); if t - mor.qifi_ts > 30 { match mor.mor_manger.try_send(QifiRsp { t: 0, data: mor.qactx.acc.get_qifi_slice(), }) { Err(e) => error!("heartbeat save qifi fail {:?}", e.to_string()), _ => {} } } }); } } impl<T: 'static> Handler<QAKline> for Monitor<T> where T: StrategyFunc + Debug, { type Result = (); fn handle(&mut self, msg: QAKline, ctx: &mut Context<Self>) -> Self::Result { self.inner_handle(msg.data); } } impl<T: 'static> Handler<Instruct> for Monitor<T> where T: StrategyFunc + Debug, { type Result = (); fn handle(&mut self, msg: Instruct, ctx: &mut Context<Self>) -> Self::Result { match msg.topic.as_str() { "settle" => { self.manual_settle(msg); } "send_order" => { self.manual_send_order(msg); } "clock" => { self.get_clock(msg); } _ => {} } } } impl<T: 'static> Unpin for Monitor<T> where T: StrategyFunc + Debug {} impl<T: 'static> Supervised for Monitor<T> where T: StrategyFunc + Debug, { fn restarting(&mut self, _: &mut actix::Context<Self>) { warn!("[{}] Restarting!!!", self.qactx.account_cookie); } }
extern crate redis; use actix::prelude::*; use actix::{Actor, Addr, AsyncContext, Context, Handler, Recipient, Supervised}; use chrono::{Local, TimeZone}; use log::{error, info, warn}; use redis::Commands; use serde_json::Value; use std::fmt::Debug; use std::time::Duration; use uuid::Version::Mac; use crate::qaaccount::account::QA_Account; use crate::qaaccount::marketpreset::MarketPreset; use crate::qaaccount::order::QAOrder; use crate::qaconnector::mongo::mongoclient::QAMongoClient; use crate::qadata::resample::{resample_db, QARealtimeResampler}; use crate::qaenv::localenv::CONFIG; use crate::qaprotocol::mifi::qafastkline::QAKlineBase; use crate::qaprotocol::qifi::account::QIFI; use crate::qaruntime::base::{Ack, AddMonitor, Instruct, Order, QAKline, QAOrderRsp, QifiRsp}; use crate::qaruntime::qacontext::{QAContext, StrategyFunc}; use crate::qaruntime::qamanagers::monitor_manager::MonitorManager; use crate::qautil::tradedate::QATradeDate; enum StateCode {} pub struct Monitor<T> { pub qactx: QAContext, pub stg: T, pub mor_manger: Addr<MonitorManager>, pub qarere: QARealtimeResampler, ur: bool, td: QATradeDate, settle_ts: i64, qifi_ts: i64, } impl<T: 'static> Monitor<T> where T: StrategyFunc + Debug, { pub fn new(qactx: QAContext, stg: T, mor_manger: Addr<MonitorManager>) -> Self { let f = qactx.frequence.clone(); let freq = f[0..f.len() - 3].parse::<i64>().unwrap(); let qarere = QARealtimeResampler::new(freq); let u = Self { qactx, stg, mor_manger, qarere, ur: true, td: QATradeDate::new(), settle_ts: 0, qifi_ts: 0, }; u } pub fn backtest(&mut self, mongo_data: &Vec<QAKlineBase>, redis_data: &Vec<QAKlineBase>) { info!("[{}] backtest mongo...", self.qactx.account_cookie); for (realtimebar, is_last) in mongo_data .into_iter() .map(|data| (data.clone().to_bar(), data.is_last)) { println!("{:#?}", realtimebar); if !self .qactx .acc .get_tradingday() .eq(&self.td.get_trade_day(realtimebar.datetime.clone())) { self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); } if is_last { self.ur = true; self.qactx.update(realtimebar.clone(), &mut self.stg); self.qactx.switch(realtimebar); } else { if self.ur { self.qactx.next(realtimebar, &mut self.stg); self.ur = false; } else { self.qactx.update(realtimebar, &mut self.stg); } } } self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); info!("[{}] backtest mongo end", self.qactx.account_cookie); info!("[{}] backtest redis...", self.qactx.account_cookie); for (realtimebar, is_last) in redis_data .into_iter() .map(|data| (data.clone().to_bar(), data.is_last)) { if !self .qactx .acc .get_tradingday() .eq(&self.td.get_trade_day(realtimebar.datetime.clone())) { self.qactx.acc.settle(); self.settle_ts = Local::now().timestamp(); } if is_last { self.ur = true; self.qactx.update(realtimebar.clone(), &mut self.stg); self.qactx.switch(realtimebar); } else { if self.ur { self.qactx.next(realtimebar, &mut self.stg); self.ur = false; } else { self.qactx.update(realtimebar, &mut self.stg); } } } info!("[{}] backtest redis end", self.qactx.account_cookie); self.qactx .acc .to_csv(format!("{}.csv", self.qactx.account_cookie)); self.qactx.order_que.clear(); } pub fn inner_handle(&mut self, msg: QAKlineBase) { let bar = self.qarere.next(msg.to_bar()); let (is_last, data) = (bar.is_last, bar.to_bar()); if is_last { self.ur = true; self.qactx.update(data.clone(), &mut self.stg); self.qactx.switch(data); } else { if self.ur { self.qactx.next(data, &mut self.stg); self.ur = false; } else { self.qactx.update(data, &mut self.stg); } } match self.mor_manger.try_send(QAOrderRsp { data: self.qactx.order_que.clone(), }) { Err(e) => { let m = format!("pub orders fail {:?}", e.to_string()); } _ => {} } self.qactx.order_que.clear(); match self.mor_manger.try_send(QifiRsp { t: 0, data: self.qactx.acc.get_qifi_slice(), }) { Err(e) => { let m = format!("qifi save fail {:?}", e.to_string()); } _ => { self.qifi_ts = Local::now().timestamp(); } } } pub fn manual_settle(&mut self, instruct: Instruct) { let ts = Local::now().timestamp(); if instruct.body.eq("--force") || ts - self.settle_ts > 60 * 60 * 24 { match self.mor_manger.try_send(QifiRsp { t: 1, data: self.qactx.acc.get_qifi_slice(), }) { Ok(_) => { self.settle_ts = ts; self.qactx.acc.settle(); let m = "settle success".to_owned(); self.ack(instruct, 200, m); } Err(e) => { let m = format!("save qifi_his fail{:?}", e.to_string()); self.ack(instruct, 500, m); } } } else { let m = "last time settle < 24h, or use [--force]".to_owned(); self.ack(instruct, 400, m); } } pub fn manual_send_order(&mut self, instruct: Instruct) { match serde_json::from_str(&instruct.body) { Ok(o) => { let time = Local::now().format("%Y-%m-%d %H:%M:%S").to_string(); let code = self.qactx.code.clone(); let order: Order = o; if order.direction.eq("BUY") && order.offset.eq("OPEN") { self.qactx.buy_open(&code, order.volume, &time, order.price) } else if order.direction.eq("BUY") && order.offset.eq("CLOSE") { self.qactx .buy_close(&code, order.volume, &time, order.price) } else if order.direction.eq("SELL") && order.offset.eq("OPEN") { self.qactx .sell_open(&code, order.volume, &time, order.price) } else
let m = "send_order success".to_owned(); self.ack(instruct, 200, m); } Err(e) => { let m = format!("Instruct order parse fail {}", e.to_string()); self.ack(instruct, 400, m); } } } pub fn get_clock(&mut self, instruct: Instruct) { match instruct.body.as_str() { "stg_status" => println!("{:#?}", &self.stg), _ => {} } self.ack(instruct, 200, self.qactx.clock.clone()); } pub fn ack(&mut self, instruct: Instruct, status: i32, ack: String) { match self.mor_manger.try_send(Ack { id: instruct.id.clone(), status, ack, answerer: self.qactx.account_cookie.clone(), }) { Err(e) => { let s = format!("[{}] ack fail {}", self.qactx.account_cookie, e.to_string()); println!("{:#?}", &s); } _ => {} }; } } impl<T: 'static> Actor for Monitor<T> where T: StrategyFunc + Debug, { type Context = Context<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.set_mailbox_capacity(10000); match self.mor_manger.try_send(AddMonitor { account_cookie: self.qactx.account_cookie.clone(), rec: ctx.address().recipient().clone(), }) { Err(e) => error!("monitor register fail {:?}", e.to_string()), _ => {} } ctx.run_interval(Duration::from_secs(30), |mor, ctx| { let t = Local::now().timestamp(); if t - mor.qifi_ts > 30 { match mor.mor_manger.try_send(QifiRsp { t: 0, data: mor.qactx.acc.get_qifi_slice(), }) { Err(e) => error!("heartbeat save qifi fail {:?}", e.to_string()), _ => {} } } }); } } impl<T: 'static> Handler<QAKline> for Monitor<T> where T: StrategyFunc + Debug, { type Result = (); fn handle(&mut self, msg: QAKline, ctx: &mut Context<Self>) -> Self::Result { self.inner_handle(msg.data); } } impl<T: 'static> Handler<Instruct> for Monitor<T> where T: StrategyFunc + Debug, { type Result = (); fn handle(&mut self, msg: Instruct, ctx: &mut Context<Self>) -> Self::Result { match msg.topic.as_str() { "settle" => { self.manual_settle(msg); } "send_order" => { self.manual_send_order(msg); } "clock" => { self.get_clock(msg); } _ => {} } } } impl<T: 'static> Unpin for Monitor<T> where T: StrategyFunc + Debug {} impl<T: 'static> Supervised for Monitor<T> where T: StrategyFunc + Debug, { fn restarting(&mut self, _: &mut actix::Context<Self>) { warn!("[{}] Restarting!!!", self.qactx.account_cookie); } }
if order.direction.eq("SELL") && order.offset.eq("CLOSE") { self.qactx .sell_close(&code, order.volume, &time, order.price) } else { let m = "send_order fail".to_owned(); self.ack(instruct, 400, m); return; }
if_condition
[ { "content": "pub fn set_bar(redis: Addr<RedisActor>, key: &str, data: String) {\n\n info!(\"write data to redis\");\n\n let fut1 = redis.do_send(Command(resp_array![\"set\", key, data]));\n\n}\n\n\n\npub async fn set_bar_async(redis: Addr<RedisActor>, key: String, data: String) {\n\n let keys = key.as_str();\n\n // info!(\"async write data to redis\");\n\n redis.send(Command(resp_array![\"set\", keys, data])).await;\n\n}\n\n\n\npub async fn get_bar(redis: Addr<RedisActor>, key: &str) -> Vec<String> {\n\n query(redis, Command(resp_array![\"get\", key])).await\n\n}\n\n\n", "file_path": "qapro-rs/src/qaconnector/redis/redisclient.rs", "rank": 0, "score": 293061.21719323454 }, { "content": "pub fn put_bar(redis: Addr<RedisActor>, key: &str, data: String) {\n\n let fut1 = redis.do_send(Command(resp_array![\"RPUSH\", key, data]));\n\n}\n\n\n\npub async fn query(redis: Addr<RedisActor>, cmd: Command) -> Vec<String> {\n\n let fut1 = redis.send(cmd).await.unwrap();\n\n let mut res = Vec::new();\n\n match fut1 {\n\n Ok(rv) => match rv {\n\n RespValue::Array(bs) => {\n\n let _ = bs\n\n .iter()\n\n .map(|x| {\n\n if let RespValue::BulkString(values) = x {\n\n match from_utf8(values.as_ref()) {\n\n Ok(x) => res.push(x.to_owned()),\n\n _ => {}\n\n }\n\n }\n\n })\n", "file_path": "qapro-rs/src/qaconnector/redis/redisclient.rs", "rank": 1, "score": 293061.21719323454 }, { "content": "pub fn resample(code: String, raw_freq: i64, freq: i64, filepath: String) -> Vec<QAKlineBase> {\n\n //let filepath = \"G:\\\\onedrive\\\\data\\\\TBDATA\\\\\".to_string();\n\n let filepath = format!(\"{}TB_DATA_{}_{}MIN.csv\", &filepath, &code, &raw_freq);\n\n println!(\"{:#?}\", filepath);\n\n let mut rdr = csv::Reader::from_path(&filepath).unwrap();\n\n\n\n let mut bardata: QAKlineBase = QAKlineBase::init();\n\n let frequence: String = format!(\"{}min\", &freq);\n\n let frq: i64 = freq * 60;\n\n let mut ures = vec![];\n\n for result in rdr.deserialize() {\n\n let bar: BAR = result.unwrap();\n\n let cur_datetime: String = bar.datetime.clone();\n\n let curstamp = Utc\n\n .datetime_from_str(cur_datetime.as_ref(), \"%Y-%m-%d %H:%M:%S\")\n\n .unwrap()\n\n .timestamp();\n\n\n\n if bardata.startstamp == 0 {\n\n bardata = QAKlineBase::new_from_bar(\n", "file_path": "qapro-rs/src/qadata/resample.rs", "rank": 2, "score": 262213.41987866955 }, { "content": "pub fn pop_bar(redis: Addr<RedisActor>, key: &str) {\n\n let fut1 = redis.do_send(Command(resp_array![\"RPOP\", key]));\n\n}\n\n\n", "file_path": "qapro-rs/src/qaconnector/redis/redisclient.rs", "rank": 3, "score": 259124.64249064645 }, { "content": "pub fn resample_db(hisdata: Vec<BAR>, freq: i64) -> Vec<QAKlineBase> {\n\n let mut bardata: QAKlineBase = QAKlineBase::init();\n\n let frequence: String = format!(\"{}min\", &freq);\n\n let frq: i64 = freq * 60;\n\n let mut ures = vec![];\n\n for bar in hisdata {\n\n let cur_datetime: String = bar.datetime.clone();\n\n let curstamp = Utc\n\n .datetime_from_str(cur_datetime.as_ref(), \"%Y-%m-%d %H:%M:%S\")\n\n .unwrap()\n\n .timestamp();\n\n\n\n if bardata.startstamp == 0 {\n\n bardata = QAKlineBase::new_from_bar(\n\n bar.clone(),\n\n frequence.parse().unwrap(),\n\n cur_datetime.clone(),\n\n curstamp.clone(),\n\n );\n\n }\n", "file_path": "qapro-rs/src/qadata/resample.rs", "rank": 4, "score": 250178.22013632106 }, { "content": "pub fn flushall(redis: Addr<RedisActor>) {\n\n let fut1 = redis.do_send(Command(resp_array![\"flushall\"]));\n\n}\n\n\n", "file_path": "qapro-rs/src/qaconnector/redis/redisclient.rs", "rank": 5, "score": 242547.86949189001 }, { "content": "pub fn backtest(\n\n data: Vec<BAR>,\n\n name: String,\n\n code: String,\n\n frequence: i32,\n\n context: &mut QAContext,\n\n stg: &mut impl StrategyFunc,\n\n fs: &mut File,\n\n) {\n\n for bar in data {\n\n context.next(bar.clone(), stg);\n\n context.switch(bar);\n\n }\n\n\n\n for o in context.order_que.chunks(2) {\n\n let x = match o[0].order.towards {\n\n 2 => \"多头\",\n\n -2 => \"空头\",\n\n _ => \"\",\n\n };\n", "file_path": "qapro-rs/src/qastrategy/backtest.rs", "rank": 6, "score": 241133.41640154392 }, { "content": "pub fn select_db(redis: Addr<RedisActor>, db: u32) {\n\n let db = db.to_string();\n\n let fut1 = redis.do_send(Command(resp_array![\"select\", db]));\n\n}\n\n\n", "file_path": "qapro-rs/src/qaconnector/redis/redisclient.rs", "rank": 7, "score": 221160.1321850958 }, { "content": "pub fn default_i64() -> i64 {\n\n 0i64\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 8, "score": 218172.85042969056 }, { "content": "pub fn default_bool() -> bool {\n\n false\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 9, "score": 218169.31067003022 }, { "content": "pub fn struct_to_doc<T>(value: T) -> Document\n\nwhere\n\n T: Serialize + std::fmt::Debug,\n\n{\n\n mongodb::bson::to_bson(&value)\n\n .unwrap()\n\n .as_document()\n\n .unwrap()\n\n .to_owned()\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct QAMongoClient {\n\n pub client: Client,\n\n}\n\n\n\nimpl QAMongoClient {\n\n pub async fn new(uri: &str) -> Self {\n\n let client = Client::with_uri_str(uri).unwrap();\n\n\n", "file_path": "qapro-rs/src/qaconnector/mongo/mongoclient.rs", "rank": 10, "score": 194230.21342188318 }, { "content": "pub fn get_n_day_before_date9(n: i64) -> String {\n\n let now = Local::now().timestamp();\n\n let sec = now - 3600 * 24 * n;\n\n let dt = Local.timestamp(sec, 0);\n\n let backtest_start = format!(\"{} 09:00:00\", dt.format(\"%Y-%m-%d\").to_string());\n\n backtest_start\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_to_string() {\n\n let mut u = QATradeDate::new();\n\n let x = u.to_string(20200202);\n\n println!(\"{:#?}\", x);\n\n assert_eq!(x, \"2020-02-02\".to_string());\n\n }\n\n\n", "file_path": "qapro-rs/src/qautil/tradedate.rs", "rank": 11, "score": 184708.71071901493 }, { "content": "pub fn adjust_market(code: &str) -> String {\n\n let re = Regex::new(r\"[a-zA-z]+\").unwrap();\n\n let res = re.captures(code);\n\n if res.is_some() {\n\n \"future_cn\".to_string()\n\n } else {\n\n \"stock_cn\".to_string()\n\n }\n\n}\n\n\n\nimpl QA_Postions {\n\n pub(crate) fn message(&self) {\n\n println!(\"{}\", self.code.clone());\n\n let u = serde_json::to_string(self).unwrap();\n\n println!(\"{:#?}\", u);\n\n }\n\n pub fn new(\n\n code: String,\n\n user_id: String,\n\n username: String,\n", "file_path": "qapro-rs/src/qaaccount/position.rs", "rank": 12, "score": 184653.1392134188 }, { "content": " def time(self):\n\n \"\"\"return the exact time of transaction(to minute level)\n\n\n\n Decorators:\n\n lru_cache\n\n\n\n Returns:\n\n pd.Series -- till minute level\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 13, "score": 182294.94056781754 }, { "content": " def code(self):\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 14, "score": 182285.97981946368 }, { "content": " def order(self):\n\n \"\"\"return the order num of transaction/ for everyday change\n\n\n\n Decorators:\n\n lru_cache\n\n\n\n Returns:\n\n pd.series -- [description]\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 15, "score": 182223.67168935662 }, { "content": "/// 获取a 中 大于等于b 的bool值\n\npub fn vec_gte_bool(a: &[f64], b: f64) -> Vec<bool> {\n\n let mut res = Vec::new();\n\n for i in a {\n\n if i >= &b {\n\n res.push(true);\n\n } else {\n\n res.push(false);\n\n }\n\n }\n\n res\n\n}\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 16, "score": 177326.83362792837 }, { "content": "/// 获取a 中 大于b 的bool值\n\npub fn vec_gt_bool(a: &[f64], b: f64) -> Vec<bool> {\n\n let mut res = Vec::new();\n\n for i in a {\n\n if i > &b {\n\n res.push(true);\n\n } else {\n\n res.push(false);\n\n }\n\n }\n\n res\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 17, "score": 177326.83362792837 }, { "content": "/// 2020-3-27 14:01 @somewheve\n\n/// 将String转换为Value类型的数据 你需要合理的处理这个问题\n\n/// 出于你可能想对自己的数据格式进行修改考虑,我在此仅仅返回了Option<Value>,方便你进行自己的处理\n\n/// 你仍然可以使用我们提供的from_serde_value或者serde_json::from_value来进行转换成struct.\n\n/// ps: 他们是一样,取决于你想不想再导入serde_json\n\n/// Examples\n\n/// ```\n\n/// use qifi_rs::from_string;\n\n/// use serde_json::Value;\n\n/// let qifi_string = r#\"{\"account_cookie\": \"T01B2_IF2004_1min\", \"password\": \"T01B2_IF2004_1min\", \"accounts\": {\"user_id\": \"T01B2_IF2004_1min\", \"currency\": \"CNY\", \"pre_balance\": 1000000, \"deposit\": 0, \"withdraw\": 0, \"WithdrawQuota\": 0, \"close_profit\": 0, \"commission\": 0, \"premium\": 1330, \"static_balance\": 1000000, \"position_profit\": 0, \"float_profit\": 0, \"balance\": 1000000, \"margin\": 0, \"frozen_margin\": 0, \"frozen_commission\": 0.0, \"frozen_premium\": 0.0, \"available\": 1000000, \"risk_ratio\": 0.0}, \"bank_password\": \"\", \"bankid\": \"QASIM\", \"bankname\": \"QASIMBank\", \"banks\": {\"QASIM\": {\"id\": \"QASIM\", \"name\": \"QASIMBank\", \"bank_account\": \"\", \"fetch_amount\": 0.0, \"qry_count\": 0}}, \"broker_name\": \"QAPaperTrading\", \"capital_password\": \"\", \"databaseip\": \"\", \"event\": {}, \"frozen\": {}, \"investor_name\": \"\", \"model\": \"SIM\", \"money\": 1000000, \"orders\": {}, \"ping_gap\": 5, \"portfolio\": \"QAPaperTrade\", \"positions\": {}, \"pub_host\": \"\", \"settlement\": {}, \"sourceid\": \"QIFI_Account\", \"status\": 200, \"taskid\": \"\", \"trade_host\": \"\", \"trades\": {}, \"trading_day\": \"2020-03-26\", \"transfers\": {}, \"updatetime\": \"\", \"wsuri\": \"ws://www.yutiansut.com:7988\"}\"#;\n\n/// let string = String::from(qifi_string);\n\n/// let qifi: Value = from_string(string).unwrap();\n\n/// let _deserialize = serde_json::to_string(&qifi).expect(\"呀 反序列化失败,请检查你的字符串格式\");\n\n///```\n\npub fn from_string(data: String) -> Option<Value> {\n\n let solve = data.replace(\"null\", \"\\\"qifi_default\\\"\");\n\n // println!(\"{:#?}\", solve);\n\n match serde_json::from_str(&solve) {\n\n Ok(_t) => _t,\n\n Err(_e) => None,\n\n }\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/func.rs", "rank": 18, "score": 174876.3078583251 }, { "content": "/// 2020-3-27 14:16 @somewheve\n\n/// 将&str转换为Value类型的数据, 在出现错误的时候返回一个None, 你需要合理的处理这个问题\n\n/// 出于你可能想对自己的数据格式进行修改考虑,我在此仅仅返回了Option<Value>,方便你进行自己的处理\n\n/// 你仍然可以使用我们提供的from_serde_value或者serde_json::from_value来进行转换成struct.\n\n/// ps: 他们是一样,取决于你想不想再导入serde_json户\n\n/// Examples\n\n/// ```\n\n/// use qifi_rs::from_str;\n\n/// use serde_json::Value;\n\n/// let qifi_string = r#\"{\"account_cookie\": \"T01B2_IF2004_1min\", \"password\": \"T01B2_IF2004_1min\", \"accounts\": {\"user_id\": \"T01B2_IF2004_1min\", \"currency\": \"CNY\", \"pre_balance\": 1000000, \"deposit\": 0, \"withdraw\": 0, \"WithdrawQuota\": 0, \"close_profit\": 0, \"commission\": 0, \"premium\": 1330, \"static_balance\": 1000000, \"position_profit\": 0, \"float_profit\": 0, \"balance\": 1000000, \"margin\": 0, \"frozen_margin\": 0, \"frozen_commission\": 0.0, \"frozen_premium\": 0.0, \"available\": 1000000, \"risk_ratio\": 0.0}, \"bank_password\": \"\", \"bankid\": \"QASIM\", \"bankname\": \"QASIMBank\", \"banks\": {\"QASIM\": {\"id\": \"QASIM\", \"name\": \"QASIMBank\", \"bank_account\": \"\", \"fetch_amount\": 0.0, \"qry_count\": 0}}, \"broker_name\": \"QAPaperTrading\", \"capital_password\": \"\", \"databaseip\": \"\", \"event\": {}, \"frozen\": {}, \"investor_name\": \"\", \"model\": \"SIM\", \"money\": 1000000, \"orders\": {}, \"ping_gap\": 5, \"portfolio\": \"QAPaperTrade\", \"positions\": {}, \"pub_host\": \"\", \"settlement\": {}, \"sourceid\": \"QIFI_Account\", \"status\": 200, \"taskid\": \"\", \"trade_host\": \"\", \"trades\": {}, \"trading_day\": \"2020-03-26\", \"transfers\": {}, \"updatetime\": \"\", \"wsuri\": \"ws://www.yutiansut.com:7988\"}\"#;\n\n/// let qifi: Value = from_str(qifi_string).unwrap();\n\n/// let _deserialize = serde_json::to_string(&qifi).expect(\"呀 反序列化失败,请检查你的字符串格式\");\n\n/// ```\n\npub fn from_str(data: &str) -> Option<Value> {\n\n let solve = data.replace(\"null\", \"\\\"qifi_default\\\"\");\n\n match serde_json::from_str(&solve) {\n\n Ok(_t) => _t,\n\n Err(_e) => None,\n\n }\n\n}\n\n\n\n// /// 此API用于快速将读取出来的数据转换为json字符串,注意是单个\n\n// pub fn covert_cursors_to_json(cursor: Cursor) -> String {\n\n// let docs: Vec<_> = cursor.map(|doc| doc.unwrap()).collect();\n\n// serde_json::to_string(&docs).unwrap()\n\n// }\n\n//\n\n// /// 转换单条数据,\n\n// pub fn covert_cursor_to_json(cursor: Cursor) -> String {\n\n// let docs: Vec<_> = cursor.map(|doc| doc.unwrap()).collect()[0];\n\n// serde_json::to_string(&docs).unwrap()\n\n// }\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/func.rs", "rank": 19, "score": 174875.8768241359 }, { "content": "/// 此处为了描述如何从bson数据载入为可用的结构体,传入一个bson以使用它\n\npub fn from_bson_(data: Bson) -> Option<Bson> {\n\n from_bson(data).unwrap()\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/func.rs", "rank": 20, "score": 174866.20801461593 }, { "content": " def code(self):\n\n \"\"\"返回唯一的证券代码\n\n\n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QABlockStruct.py", "rank": 21, "score": 169237.6963643011 }, { "content": " def code(self):\n\n if self.if_multiindex:\n\n return self.index.levels[1].tolist()\n\n else:\n", "file_path": "QUANTAXIS/QAData/QASeriesStruct.py", "rank": 22, "score": 169237.6963643011 }, { "content": "/// Parses CLI arguments, finds location of config file, and parses config file into a struct.\n\npub fn parse_config_from_cli_args(matches: &clap::ArgMatches) -> Config {\n\n let conf = match matches.value_of(\"config\") {\n\n Some(config_path) => match Config::from_file(config_path) {\n\n Ok(config) => config,\n\n Err(msg) => {\n\n eprintln!(\"Failed to parse config file {}: {}\", config_path, msg);\n\n std::process::exit(1);\n\n }\n\n },\n\n None => {\n\n eprintln!(\"No config file specified, append toml file\");\n\n std::process::exit(1);\n\n }\n\n };\n\n conf\n\n}\n\n\n\n#[derive(Clone, Debug, Default, Deserialize)]\n\npub struct Config {\n\n pub clickhouse: ClickhouseConfig,\n", "file_path": "qapro-rs/src/qaenv/localenv.rs", "rank": 23, "score": 163046.8866221442 }, { "content": "pub fn get_direction_or_offset(towards: i32) -> String {\n\n let rt = match towards {\n\n 1 => (String::from(\"BUY_OPEN\"), String::from(\"OPEN\")),\n\n 2 => (String::from(\"BUY\"), String::from(\"OPEN\")),\n\n 3 => (String::from(\"BUY\"), String::from(\"CLOSE\")),\n\n 4 => (String::from(\"BUY\"), String::from(\"CLOSETODAY\")),\n\n -1 => (String::from(\"SELL\"), String::from(\"CLOSE\")),\n\n -2 => (String::from(\"SELL\"), String::from(\"OPEN\")),\n\n -3 => (String::from(\"SELL\"), String::from(\"CLOSE\")),\n\n -4 => (String::from(\"SELL\"), String::from(\"CLOSETODAY\")),\n\n _ => (String::from(\"\"), String::from(\"\")),\n\n };\n\n format!(\"{}_{}\", rt.0, rt.1)\n\n}\n", "file_path": "qapro-rs/src/qastrategy/backtest.rs", "rank": 24, "score": 161664.92559328102 }, { "content": "/// Defines and parses CLI argument for this server.\n\npub fn parse_cli_args<'a>() -> clap::ArgMatches<'a> {\n\n clap::App::new(\"qaruntime-rs\")\n\n .version(VERSION)\n\n .arg(\n\n clap::Arg::with_name(\"config\")\n\n .required(false)\n\n .help(\"Path to configuration file\")\n\n .index(1),\n\n )\n\n .get_matches()\n\n}\n\n\n", "file_path": "qapro-rs/src/qaenv/localenv.rs", "rank": 25, "score": 157714.4294719702 }, { "content": "pub fn evaluate<'a>(sql: Sql, data: PqlValue) -> PqlValue {\n\n let mut env = Env::default();\n\n env.insert(\"\", &Expr::from(data));\n\n let plan = LogicalPlan::from(sql);\n\n let result = plan.execute(&mut env);\n\n result\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::str::FromStr;\n\n\n\n use crate::parsers::planner::LogicalPlan;\n\n use crate::parsers::sql::Env;\n\n use crate::parsers::sql::Sql;\n\n use crate::parsers::value::PqlValue;\n\n\n\n #[test]\n\n fn test_rename() -> anyhow::Result<()> {\n\n let sql = Sql::from_str(\n\n r#\"\n", "file_path": "qapro-rs/src/parsers/planner/eval.rs", "rank": 26, "score": 157591.5022024692 }, { "content": "/// 两数组的差值,可设定abs\n\npub fn diff(a: &[f64], b: &[f64], abs: bool) -> Vec<f64> {\n\n // 以长度较短的为主干,木桶效应,且右对齐\n\n let al = a.len();\n\n let bl = b.len();\n\n let mut res = Vec::new();\n\n let h = min(al, bl);\n\n let a1 = &a[al - h..];\n\n let b1 = &b[bl - h..];\n\n for (index, v) in a1.iter().enumerate() {\n\n let si = if abs {\n\n (v - b1[index]).abs()\n\n } else {\n\n v - b1[index]\n\n };\n\n res.push(si);\n\n }\n\n res\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 27, "score": 157387.72745378007 }, { "content": "pub fn dumps(data: PqlValue, to: &str) -> anyhow::Result<String> {\n\n let to_lang_type = LangType::from_str(&to)?;\n\n let mut lang = Lang::default();\n\n lang.data = data;\n\n lang.to = to_lang_type;\n\n let output = lang.to_string(true)?;\n\n Ok(output)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/engine.rs", "rank": 28, "score": 156792.7974227059 }, { "content": "pub fn evaluate<'a>(sql: &Sql, data: &'a PqlValue) -> PqlValue {\n\n let fields = sql\n\n .from_clause\n\n .iter()\n\n .chain(sql.left_join_clause.iter())\n\n .map(|e| e.to_owned())\n\n .collect::<Vec<_>>();\n\n\n\n let bindings = Bindings::from(fields.as_slice());\n\n\n\n let data = match &sql.where_clause {\n\n None => data.to_owned(),\n\n Some(box WhereCond::Eq { expr, right }) => match expr {\n\n Expr::Path(path) => {\n\n let path = path.expand_fullpath(&bindings);\n\n let cond = WhereCond::Eq {\n\n expr: expr.to_owned(),\n\n right: right.to_owned(),\n\n };\n\n restrict(Some(data.to_owned()), &path, &Some(cond)).expect(\"restricted value\")\n", "file_path": "qapro-rs/src/parsers/sql/eval.rs", "rank": 29, "score": 154149.04581666985 }, { "content": "fn QADataStruct_Factor_schema() -> Schema {\n\n Schema::new(vec![\n\n Field::new(\"date\", DataType::Utf8),\n\n Field::new(\"order_book_id\", DataType::Utf8),\n\n Field::new(\"factor\", DataType::Float32),\n\n ])\n\n}\n\n\n\n// same with python model :: // qafactor Daily struct\n\npub struct QADataStruct_Factor {\n\n pub data: DataFrame,\n\n name: String,\n\n}\n\n\n\nimpl QADataStruct_Factor {\n\n pub fn new_from_vec(\n\n date: Vec<String>,\n\n order_book_id: Vec<String>,\n\n factor: Vec<f32>,\n\n factorname: String,\n", "file_path": "qapro-rs/src/qadatastruct/factorstruct.rs", "rank": 30, "score": 153892.82231960894 }, { "content": "fn QADataStruct_StockAdj_schema() -> Schema {\n\n Schema::new(vec![\n\n Field::new(\"order_book_id\", DataType::Utf8),\n\n Field::new(\"listed_date\", DataType::Utf8),\n\n Field::new(\"de_listed_date\", DataType::Utf8),\n\n Field::new(\"symbol\", DataType::Utf8),\n\n ])\n\n}\n\npub struct QADataStruct_StockList {\n\n pub data: DataFrame,\n\n name: String,\n\n}\n\n\n\nimpl QADataStruct_StockList {\n\n pub fn new_from_vec(\n\n order_book_id: Vec<String>,\n\n listed_date: Vec<String>,\n\n delist_date: Vec<String>,\n\n symbol: Vec<String>,\n\n ) -> Self {\n", "file_path": "qapro-rs/src/qadatastruct/stocklist.rs", "rank": 31, "score": 150843.3346987076 }, { "content": "fn QADataStruct_StockAdj_schema() -> Schema {\n\n Schema::new(vec![\n\n Field::new(\"date\", DataType::Utf8),\n\n Field::new(\"order_book_id\", DataType::Utf8),\n\n Field::new(\"adj\", DataType::Float32),\n\n ])\n\n}\n\npub struct QADataStruct_StockAdj {\n\n pub data: DataFrame,\n\n name: String,\n\n}\n\n\n\nimpl QADataStruct_StockAdj {\n\n pub fn new_from_vec(date: Vec<String>, order_book_id: Vec<String>, adj: Vec<f32>) -> Self {\n\n let dateS = Series::new(\"date\", &date);\n\n\n\n let order_book_idS = Series::new(\"order_book_id\", &order_book_id);\n\n let adjS = Series::new(\"adj\", &adj);\n\n let df = DataFrame::new(vec![dateS, order_book_idS, adjS]).unwrap();\n\n Self {\n", "file_path": "qapro-rs/src/qadatastruct/stockadj.rs", "rank": 32, "score": 150843.3346987076 }, { "content": "fn QADataStruct_StockDay_schema() -> Schema {\n\n Schema::new(vec![\n\n Field::new(\"date\", DataType::Utf8),\n\n Field::new(\"code\", DataType::Utf8),\n\n Field::new(\"order_book_id\", DataType::Utf8),\n\n Field::new(\"num_trades\", DataType::Float32),\n\n Field::new(\"limit_up\", DataType::Float32),\n\n Field::new(\"limit_down\", DataType::Float32),\n\n Field::new(\"open\", DataType::Float32),\n\n Field::new(\"high\", DataType::Float32),\n\n Field::new(\"low\", DataType::Float32),\n\n Field::new(\"close\", DataType::Float32),\n\n Field::new(\"volume\", DataType::Float32),\n\n Field::new(\"total_turnover\", DataType::Float32),\n\n Field::new(\"amount\", DataType::Float32),\n\n ])\n\n}\n\nimpl QADataStruct_StockDay {\n\n pub fn new_from_csv(path: &str) -> Self {\n\n let schema = QADataStruct_StockDay_schema();\n", "file_path": "qapro-rs/src/qadatastruct/stockday.rs", "rank": 33, "score": 150843.3346987076 }, { "content": "pub trait StrategyFunc {\n\n fn on_bar_next(&mut self, data: &BAR, context: &mut QAContext);\n\n fn on_bar_update(&mut self, data: &BAR, context: &mut QAContext);\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct MOrder {\n\n pub model: String,\n\n pub time: String,\n\n pub order: QAOrder,\n\n}\n\n\n\nimpl MOrder {\n\n pub fn to_mt(&self) -> MTrade {\n\n MTrade {\n\n time: self.time.clone(),\n\n model: self.model.clone(),\n\n trade: self.order.to_trade_order(),\n\n }\n\n }\n", "file_path": "qapro-rs/src/qaruntime/qacontext.rs", "rank": 34, "score": 149997.19081711193 }, { "content": "pub trait Handler {\n\n fn to_json(&self) -> String\n\n where\n\n Self: Serialize,\n\n {\n\n serde_json::to_string(&self).unwrap()\n\n }\n\n fn get_datetime(&self) -> String;\n\n fn get_code(&self) -> String;\n\n fn get_date(&self) -> String;\n\n fn get_open(&self) -> f64;\n\n fn get_close(&self) -> f64;\n\n fn get_high(&self) -> f64;\n\n fn get_low(&self) -> f64;\n\n fn get_vol(&self) -> f64;\n\n fn get_amount(&self) -> f64;\n\n\n\n fn set_datetime(&mut self, datetime: String) {}\n\n fn set_code(&mut self, code: String) {}\n\n fn set_date(&mut self, date: String) {}\n\n fn set_open(&mut self, open: f64) {}\n\n fn set_close(&mut self, close: f64) {}\n\n fn set_high(&mut self, high: f64) {}\n\n fn set_low(&mut self, low: f64) {}\n\n fn set_vol(&mut self, vol: f64) {}\n\n fn set_amount(&mut self, amount: f64) {}\n\n}\n", "file_path": "qapro-rs/src/qaprotocol/mifi/mifibase.rs", "rank": 35, "score": 149995.45832977167 }, { "content": "pub fn query_evaluate(data: PqlValue, sql: &str) -> anyhow::Result<PqlValue> {\n\n let sql = Sql::from_str(&sql)?;\n\n let data = PqlValue::from(data);\n\n let value = planner::evaluate(sql, data);\n\n Ok(value)\n\n}\n", "file_path": "qapro-rs/src/parsers/engine.rs", "rank": 36, "score": 149208.62312787762 }, { "content": "pub fn orderby(input: &str) -> IResult<&str, clause::OrderBy> {\n\n let (input, (_, field_name, opt_asc_or_desc)) = tuple((\n\n tag_no_case(\"ORDER BY\"),\n\n preceded(multispace0, string_allowed_in_field),\n\n preceded(\n\n multispace0,\n\n opt(alt((tag_no_case(\"ASC\"), tag_no_case(\"DESC\")))),\n\n ),\n\n ))(input)?;\n\n\n\n let is_asc = opt_asc_or_desc\n\n .map(|asc_or_desc| asc_or_desc.to_lowercase() == \"asc\")\n\n .unwrap_or(true);\n\n Ok((\n\n input,\n\n clause::OrderBy {\n\n label: field_name,\n\n is_asc,\n\n },\n\n ))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/clauses.rs", "rank": 37, "score": 145915.27474828527 }, { "content": "pub fn root<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n\n i: &'a str,\n\n) -> IResult<&'a str, PqlValue, E> {\n\n delimited(multispace0, json_value, opt(multispace0))(i)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/pqlir_parser.rs", "rank": 38, "score": 139053.17607262512 }, { "content": "pub fn new_config() -> Config {\n\n let _args: Vec<String> = env::args().collect();\n\n\n\n let cfg: Config = parse_config_from_cli_args(&parse_cli_args());\n\n cfg\n\n}\n\n\n\nlazy_static! {\n\n pub static ref CONFIG: Config = new_config();\n\n}\n", "file_path": "qapro-rs/src/qaenv/localenv.rs", "rank": 39, "score": 138702.47467275383 }, { "content": "pub fn json_value<'a, E: ParseError<&'a str> + ContextError<&'a str>>(\n\n i: &'a str,\n\n) -> IResult<&'a str, PqlValue, E> {\n\n preceded(\n\n multispace0,\n\n alt((\n\n map(null, |_s| PqlValue::Null),\n\n map(hash, PqlValue::Object),\n\n map(array, PqlValue::Array),\n\n map(bag, PqlValue::Array),\n\n map(string, |s| PqlValue::Str(String::from(s))),\n\n map(double, |f| PqlValue::Float(OrderedFloat(f as f64))),\n\n map(boolean, PqlValue::Boolean),\n\n )),\n\n )(i)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/pqlir_parser.rs", "rank": 40, "score": 136512.76614404222 }, { "content": "pub fn default_i128() -> i128 {\n\n 0i128\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 41, "score": 136437.42945016484 }, { "content": "pub fn default_string() -> String {\n\n \"\".to_string()\n\n}\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 42, "score": 136437.42945016484 }, { "content": "pub fn default_i32() -> i32 {\n\n 0i32\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 43, "score": 136437.42945016484 }, { "content": "pub fn default_f64() -> f64 {\n\n 0f64\n\n}\n\n\n", "file_path": "qapro-rs/src/qaprotocol/qifi/default.rs", "rank": 44, "score": 136437.42945016484 }, { "content": " def last_close(self):\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 45, "score": 134428.10425976772 }, { "content": " def get_time(self, start, end=None):\n\n if end is None:\n\n return self.data.loc[start]\n\n else:\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 46, "score": 134368.57914193106 }, { "content": " def get_big_orders(self, bigamount=1000000):\n\n \"\"\"return big order\n\n\n\n Keyword Arguments:\n\n bigamount {[type]} -- [description] (default: {1000000})\n\n\n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 47, "score": 131503.88016130723 }, { "content": " def get_small_order(self, smallamount=200000):\n\n \"\"\"return small level order\n\n\n\n Keyword Arguments:\n\n smallamount {[type]} -- [description] (default: {200000})\n\n\n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 48, "score": 131503.8048911973 }, { "content": " def get_medium_order(self, lower=200000, higher=1000000):\n\n \"\"\"return medium\n\n\n\n Keyword Arguments:\n\n lower {[type]} -- [description] (default: {200000})\n\n higher {[type]} -- [description] (default: {1000000})\n\n\n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n\n return self.data.query('amount>={}'.format(lower)\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 49, "score": 131499.4351869889 }, { "content": " def info(self):\n\n '''\n\n :return:\n\n '''\n", "file_path": "QUANTAXIS/QAMarket/QAOrder.py", "rank": 50, "score": 130668.74243807077 }, { "content": "pub fn init_log4(path: &str) {\n\n let stdout = ConsoleAppender::builder().build();\n\n\n\n let requests = FileAppender::builder()\n\n .encoder(Box::new(PatternEncoder::new(\n\n \"[{d(%Y-%m-%d %H:%M:%S)}] [{l}] [thread:{I}] [{f}] [{t}]- {m}{n}\",\n\n )))\n\n .build(path)\n\n .unwrap();\n\n\n\n let config = Config::builder()\n\n .appender(Appender::builder().build(\"stdout\", Box::new(stdout)))\n\n .appender(Appender::builder().build(\"requests\", Box::new(requests)))\n\n .logger(Logger::builder().build(\"app::backend::db\", LevelFilter::Info))\n\n .logger(\n\n Logger::builder()\n\n .appender(\"requests\")\n\n .additive(false)\n\n .build(\"app::requests\", LevelFilter::Info),\n\n )\n", "file_path": "qapro-rs/src/qalog/log4.rs", "rank": 51, "score": 130044.60362821314 }, { "content": " def code(self):\n\n '返回结构体中的代码'\n", "file_path": "QUANTAXIS/QAData/base_datastruct.py", "rank": 52, "score": 129924.62866022438 }, { "content": " def get_end_time(self):\n\n\n\n now = datetime.datetime.today()\n\n if now.hour < 15:\n\n \"\"\"\n\n 日内\n\n \"\"\"\n\n end = QA.QA_util_get_last_day(datetime.date.today()) + ' 17:00:00'\n\n else:\n\n end = str(self.today) + ' 17:00:00'\n\n # print(end)\n", "file_path": "config/data_init.py", "rank": 54, "score": 127855.0837982174 }, { "content": "#[derive(Serialize, Deserialize, Debug, Clone)]\n\nstruct Scode {\n\n pub code: String,\n\n pub ip: String,\n\n pub limit: i32,\n\n}\n\n\n\n/// L2行情数据, 注意我为此都添加大量的接口\n\n/// index: 索引\n\n/// time: 时间\n\n/// price: 最新价格\n\n/// isbuy:是否买\n\n/// vol: 成交量\n\n/// buyno:\n\n/// sellno:\n\n/// buyprice:\n\n/// sellprice:\n\n/// buyvol:\n\n/// sellvol:\n\n/// marketname: 市场名称\n\n/// code:\n", "file_path": "qapro-rs/src/qaprotocol/qifi/data.rs", "rank": 55, "score": 127682.33417072828 }, { "content": "struct DailyOrderSchedule {\n\n code: String,\n\n amount: f64,\n\n price: f64,\n\n datetime: String,\n\n}\n\nimpl model {\n\n pub fn default() -> Self {\n\n let w:HashMap<String, HashMap<String, f64>> = serde_json::from_str(r#\"{\"2018-08-22\":{\"000001\":0.1,\n\n \"000002\":0.0,\"000004\":0.0,\"000005\":0.0,\"000006\":0.0,\"000007\":0.0,\"000008\":0.0,\"000009\":0.0,\"000010\":0.0,\n\n \"000011\":0.0,\"000012\":0.0,\"000014\":0.0,\"000016\":0.0,\"000017\":0.0,\"000018\":0.0,\"000019\":0.0,\"000020\":0.0,\n\n \"000021\":0.0,\"000023\":0.0,\"000025\":0.0,\"000026\":0.0,\"000027\":0.0,\"000028\":0.0,\"000029\":0.0,\"000030\":0.0,\n\n \"000031\":0.0,\"000032\":0.0,\"000034\":0.0,\"000035\":0.0,\"000036\":0.0,\"000037\":0.0,\"000038\":0.0,\"000039\":0.0,\n\n \"000040\":0.0,\"000042\":0.0,\"000043\":0.0,\"000045\":0.0,\"000046\":0.0,\"000048\":0.0,\"000049\":0.0,\"000050\":0.0,\n\n \"000055\":0.0,\"000056\":0.0,\"000058\":0.0,\"000059\":0.1,\"000060\":0.0,\"000061\":0.0,\"000062\":0.0,\"000063\":0.0,\n\n \"000065\":0.0},\"2018-08-23\":{\"000001\":0.0,\"000002\":0.0,\"000004\":0.0,\"000005\":0.0,\"000006\":0.0,\"000007\":0.0,\n\n \"000008\":0.0,\"000009\":0.0,\"000010\":0.0,\"000011\":0.0,\"000012\":0.0,\"000014\":0.0,\"000016\":0.0,\"000017\":0.0,\n\n \"000018\":0.0,\"000019\":0.0,\"000020\":0.0,\"000021\":0.0,\"000023\":0.0,\"000025\":0.0,\"000026\":0.0,\"000027\":0.0,\n\n \"000028\":0.0,\"000029\":0.0,\"000030\":0.0,\"000031\":0.0,\"000032\":0.0,\"000034\":0.0,\"000035\":0.0,\"000036\":0.0,\n\n \"000037\":0.0,\"000038\":0.0,\"000039\":0.0,\"000040\":0.0,\"000042\":0.0,\"000043\":0.0,\"000045\":0.0,\"000046\":0.0,\n", "file_path": "qapro-rs/src/qafactor/factorbacktest.rs", "rank": 56, "score": 125913.84639403429 }, { "content": " def get_code(self, code):\n\n \"\"\"getcode 获取某一只股票的板块\n\n\n\n Arguments:\n\n code {str} -- 股票代码\n\n\n\n Returns:\n\n DataStruct -- [description]\n\n \"\"\"\n\n # code= [code] if isinstance(code,str) else\n", "file_path": "QUANTAXIS/QAData/QABlockStruct.py", "rank": 57, "score": 121218.99771317278 }, { "content": " def get_both_code(self, code):\n\n \"\"\"get_both_code 获取几个股票相同的版块\n\n \n\n Arguments:\n\n code {[type]} -- [description]\n\n \n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n", "file_path": "QUANTAXIS/QAData/QABlockStruct.py", "rank": 58, "score": 121210.3873099416 }, { "content": " def view_code(self):\n\n \"\"\"按股票排列的查看blockname的视图\n\n\n\n Returns:\n\n [type] -- [description]\n\n \"\"\"\n\n\n\n return self.data.groupby(level=1).apply(\n\n lambda x:\n\n [item for item in x.index.remove_unused_levels().levels[0]]\n", "file_path": "QUANTAXIS/QAData/QABlockStruct.py", "rank": 59, "score": 121204.7523896272 }, { "content": " def get_code(self, code):\n\n \"\"\"\n\n 获取某一只股票的指标序列\n\n \"\"\"\n\n try:\n\n return self.data.loc[(slice(None), code), :]\n\n except:\n", "file_path": "QUANTAXIS/QAData/QAIndicatorStruct.py", "rank": 60, "score": 121204.7523896272 }, { "content": " def select_code(self, code):\n", "file_path": "QUANTAXIS/QAData/QASeriesStruct.py", "rank": 61, "score": 121204.7523896272 }, { "content": " def select_time(self, start, end=None):\n\n if end is None:\n\n return self.new(self.series.loc[(pd.Timestamp(start), slice(None))])\n\n else:\n", "file_path": "QUANTAXIS/QAData/QASeriesStruct.py", "rank": 62, "score": 121195.32845576714 }, { "content": "pub fn QA_util_date_to_string(date: i32) -> String {\n\n let year = date / 10000;\n\n let month = (date - year * 10000) / 100;\n\n let day = (date - year * 10000 - month * 100);\n\n let month_1 = if month < 10 {\n\n format!(\"0{}\", month)\n\n } else {\n\n format!(\"{}\", month)\n\n };\n\n let day_1 = if day < 10 {\n\n format!(\"0{}\", day)\n\n } else {\n\n format!(\"{}\", day)\n\n };\n\n\n\n let u = format!(\"{}-{}-{}\", year, month_1, day_1);\n\n u\n\n}\n", "file_path": "qapro-rs/src/qautil/tradedate.rs", "rank": 63, "score": 118931.5987124732 }, { "content": "/// 将结构体转换可以直接插入的doc参数\n\n/// Note: 注意你的数据类型中尽量不要使用 **u8等数据类型**,他会导致bson无法解析结构体. 参见 https://github.com/mongodb/bson-rust/issues/89\n\n/// Examples\n\n/// ```\n\n/// use qifi_rs::to_doc;\n\n/// use serde::{Deserialize, Serialize};\n\n/// #[derive(Serialize, Clone, Deserialize, Debug)]\n\n/// struct Name {\n\n/// hello:String\n\n/// }\n\n/// let x = to_doc(Name{ hello:\"somewheve\".to_string()});\n\n/// println!(\"{:?}\", x)\n\n///\n\n/// ```\n\npub fn to_doc<T>(value: T) -> Document\n\nwhere\n\n T: Serialize + std::fmt::Debug,\n\n{\n\n // println!(\"{:?}\", value);\n\n let serialized = bson::to_bson(&value).unwrap(); // Serialize\n\n let x = serialized.as_document().expect(\"期望一个合法的document\");\n\n x.to_owned()\n\n}\n", "file_path": "qapro-rs/src/qaprotocol/qifi/func.rs", "rank": 64, "score": 116919.45070257751 }, { "content": "#[async_trait]\n\npub trait DataConnector {\n\n async fn get_stocklist(&self) -> Result<Vec<String>, io::Error>;\n\n async fn get_stocklist_adv(&self) -> Result<QADataStruct_StockList, io::Error>;\n\n async fn get_stock(\n\n &self,\n\n codelist: Vec<&str>,\n\n start: &str,\n\n end: &str,\n\n freq: &str,\n\n ) -> Result<QAColumnBar, io::Error>;\n\n async fn get_stock_adv(\n\n &self,\n\n codelist: Vec<&str>,\n\n start: &str,\n\n end: &str,\n\n freq: &str,\n\n ) -> Result<QADataStruct_StockDay, io::Error>;\n\n\n\n async fn get_future(\n\n &self,\n", "file_path": "qapro-rs/src/qaconnector/clickhouse/ckclient.rs", "rank": 65, "score": 116802.61382783155 }, { "content": "pub fn re_from_str(pattern: &str) -> regex::Regex {\n\n let regex_pattern = match (pattern.starts_with(\"%\"), pattern.ends_with(\"%\")) {\n\n (true, true) => {\n\n format!(\"{}\", pattern.trim_start_matches(\"%\").trim_end_matches(\"%\"))\n\n }\n\n (true, false) => format!(\"{}$\", pattern.trim_start_matches(\"%\")),\n\n (false, true) => format!(\"^{}\", pattern.trim_end_matches(\"%\")),\n\n (false, false) => format!(\"^{}$\", pattern),\n\n };\n\n let re = regex::Regex::new(&regex_pattern).unwrap();\n\n re\n\n}\n", "file_path": "qapro-rs/src/parsers/sql/where_cond.rs", "rank": 66, "score": 114957.49853984798 }, { "content": "pub fn dma(lst: &[f64], tail: usize) -> f64 {\n\n let l = lst.len();\n\n let mut res = 0.0;\n\n if l <= tail {\n\n for i in lst {\n\n res += *i;\n\n }\n\n return res / l as f64;\n\n } else {\n\n for i in &lst[l - tail..l] {\n\n res += *i;\n\n }\n\n return res / tail as f64;\n\n }\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 67, "score": 113654.19340576512 }, { "content": "/// 取队列中的最大值\n\npub fn dhhv(lst: &[f64], tail: usize) -> f64 {\n\n let mut max = -INFINITY;\n\n let l = lst.len();\n\n let x = if tail > l { lst } else { &lst[l - tail..] };\n\n for i in x {\n\n if i > &max {\n\n max = *i;\n\n }\n\n }\n\n return max;\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 68, "score": 113654.19340576512 }, { "content": "/// 取队列中的最小值\n\npub fn dllv(lst: &[f64], tail: usize) -> f64 {\n\n let mut min = INFINITY;\n\n let l = lst.len();\n\n let x = if tail > l { lst } else { &lst[l - tail..] };\n\n for i in x {\n\n if i < &min {\n\n min = *i;\n\n }\n\n }\n\n return min;\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 69, "score": 113654.19340576512 }, { "content": "/// a 中 大于 b 的个数\n\npub fn vec_gt_count(a: &[f64], b: &[f64]) -> usize {\n\n let al = a.len();\n\n let bl = b.len();\n\n let mut count = 0;\n\n let h = min(al, bl);\n\n let a1 = &a[al - h..];\n\n let b1 = &b[bl - h..];\n\n for (index, i) in a1.iter().enumerate() {\n\n if i > &b1[index] {\n\n count += 1;\n\n }\n\n }\n\n count\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 70, "score": 113654.19340576512 }, { "content": "pub fn function(input: &str) -> IResult<&str, Expr> {\n\n let (input, (funcname, _, expr)) = tuple((\n\n preceded(\n\n whitespace,\n\n alt((\n\n tag_no_case(\"count\"),\n\n tag_no_case(\"upper\"),\n\n tag_no_case(\"lower\"),\n\n tag_no_case(\"ceil\"),\n\n tag_no_case(\"floor\"),\n\n tag_no_case(\"round\"),\n\n )),\n\n ),\n\n char('('),\n\n cut(terminated(\n\n preceded(whitespace, parse_expr),\n\n preceded(whitespace, char(')')),\n\n )),\n\n ))(input)?;\n\n\n", "file_path": "qapro-rs/src/parsers/parser/func.rs", "rank": 71, "score": 111707.02656474478 }, { "content": "pub fn offset(input: &str) -> IResult<&str, u64> {\n\n preceded(\n\n tag_no_case(\"OFFSET\"),\n\n preceded(multispace0, elements::integer),\n\n )(input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::str::FromStr;\n\n\n\n use super::from;\n\n use crate::parsers::sql::Field;\n\n\n\n #[test]\n\n fn parse_from() -> anyhow::Result<()> {\n\n assert_eq!(from(\"FROM [1,2,3]\")?.1, vec![Field::from_str(\"[1,2,3]\")?],);\n\n assert_eq!(\n\n from(\"FROM [1,2,3] AS arr\")?.1,\n\n vec![Field::from_str(\"[1,2,3] AS arr\")?],\n\n );\n\n assert_eq!(\n\n from(\"FROM x.y.z AS xyz\")?.1,\n\n vec![Field::from_str(\"x.y.z AS xyz\")?],\n\n );\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "qapro-rs/src/parsers/parser/clauses.rs", "rank": 72, "score": 111707.02656474478 }, { "content": "/// 数字的最大值\n\npub fn vec_maximum(lst: &[f64], tail: usize) -> f64 {\n\n match tail {\n\n 0 => {\n\n let mut max = -INFINITY;\n\n for i in lst {\n\n if i > &max {\n\n max = *i;\n\n }\n\n }\n\n return max;\n\n }\n\n _ => {\n\n let mut max = -INFINITY;\n\n let l = lst.len();\n\n let x = if tail > l { lst } else { &lst[l - tail..] };\n\n for i in x {\n\n if i > &max {\n\n max = *i;\n\n }\n\n }\n\n return max;\n\n }\n\n }\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 73, "score": 111707.02656474478 }, { "content": "/// 数组中的最小值\n\npub fn vec_minimum(lst: &[f64], tail: usize) -> f64 {\n\n match tail {\n\n 0 => {\n\n let mut min = INFINITY;\n\n for i in lst {\n\n if i < &min {\n\n min = *i;\n\n }\n\n }\n\n min\n\n }\n\n _ => {\n\n let mut min = INFINITY;\n\n let l = lst.len();\n\n let x = if tail > l { lst } else { &lst[l - tail..] };\n\n for i in x {\n\n if i < &min {\n\n min = *i;\n\n }\n\n }\n\n return min;\n\n }\n\n }\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 74, "score": 111707.02656474478 }, { "content": "pub fn comma(input: &str) -> IResult<&str, &str> {\n\n delimited(multispace0, tag(\",\"), multispace0)(input)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/elements.rs", "rank": 75, "score": 111707.02656474478 }, { "content": "pub fn parse(input: &str) -> IResult<&str, Expr> {\n\n parse_math_expr(input)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/math.rs", "rank": 76, "score": 111707.02656474478 }, { "content": "pub fn parse_where(input: &str) -> IResult<&str, WhereCond> {\n\n preceded(\n\n tag_no_case(\"WHERE\"),\n\n alt((parse_where_eq, parse_where_like)),\n\n )(input)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/clauses.rs", "rank": 77, "score": 111707.02656474478 }, { "content": "/// 取两数组每项的较小值\n\npub fn vec_smaller(a: &[f64], b: &[f64]) -> Vec<f64> {\n\n // 以长度较短的为主干,木桶效应,且右对齐\n\n let al = a.len();\n\n let bl = b.len();\n\n let mut res = Vec::new();\n\n let h = min(al, bl);\n\n let a1 = &a[al - h..];\n\n let b1 = &b[bl - h..];\n\n for (index, i) in a1.iter().enumerate() {\n\n let t = &b1[index];\n\n if i < t {\n\n res.push(*i);\n\n } else {\n\n res.push(*t);\n\n }\n\n }\n\n res\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 78, "score": 110946.19829464471 }, { "content": "/// 取两数组每项的较大值\n\npub fn vec_bigger(a: &[f64], b: &[f64]) -> Vec<f64> {\n\n // 以长度较短的为主干,木桶效应,且右对齐\n\n let al = a.len();\n\n let bl = b.len();\n\n let mut res = Vec::new();\n\n let h = min(al, bl);\n\n let a1 = &a[al - h..];\n\n let b1 = &b[bl - h..];\n\n for (index, i) in a1.iter().enumerate() {\n\n let t = &b1[index];\n\n if i > t {\n\n res.push(*i);\n\n } else {\n\n res.push(*t);\n\n }\n\n }\n\n res\n\n}\n\n\n", "file_path": "qapro-rs/src/qadata/datafunc.rs", "rank": 79, "score": 110946.19829464471 }, { "content": "class QA_DataStruct_Min(_quotation_base):\n\n '''这个类是个通用类 一般不使用 特定生成的时候可能会用到 只具备基类方法\n\n '''\n\n\n\n def __init__(self, data, dtype='unknown_min', if_fq='bfq'):\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 80, "score": 110363.46376430379 }, { "content": "class QA_DataStruct_Day(_quotation_base):\n\n \"\"\"这个类是个通用类 一般不使用 特定生成的时候可能会用到 只具备基类方法\n\n\n\n Arguments:\n\n _quotation_base {[type]} -- [description]\n\n \"\"\"\n\n\n\n def __init__(self, data, dtype='unknown_day', if_fq='bfq'):\n\n '''\n\n '''\n", "file_path": "QUANTAXIS/QAData/QADataStruct.py", "rank": 81, "score": 110363.46376430379 }, { "content": "pub fn parse_where_like(input: &str) -> IResult<&str, WhereCond> {\n\n let (input, (expr, _, s)) = preceded(\n\n multispace0,\n\n tuple((\n\n parse_expr,\n\n preceded(multispace0, tag_no_case(\"LIKE\")),\n\n preceded(multispace0, elements::string),\n\n )),\n\n )(input)?;\n\n let res = WhereCond::Like {\n\n expr,\n\n right: s.to_string(),\n\n };\n\n Ok((input, res))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/clauses.rs", "rank": 82, "score": 109851.05619666698 }, { "content": "pub fn parse_where_eq(input: &str) -> IResult<&str, WhereCond> {\n\n let (input, (expr, _, right)) = preceded(\n\n multispace0,\n\n tuple((\n\n parse_expr,\n\n preceded(multispace0, tag(\"=\")),\n\n preceded(multispace0, parse_value),\n\n )),\n\n )(input)?;\n\n let res = WhereCond::Eq { expr, right };\n\n Ok((input, res))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/clauses.rs", "rank": 83, "score": 109851.05619666698 }, { "content": "pub fn from_str(input: &str) -> anyhow::Result<Sql> {\n\n match parse_planner_sql(input) {\n\n Ok((_, sql)) => Ok(sql),\n\n Err(nom::Err::Incomplete(_needed)) => {\n\n anyhow::bail!(\"needed\")\n\n }\n\n Err(nom::Err::Error(err)) => {\n\n dbg!(&err);\n\n eprintln!(\"{}\", err);\n\n anyhow::bail!(\"parser error\")\n\n }\n\n Err(nom::Err::Failure(err)) => {\n\n dbg!(&err);\n\n eprintln!(\"{}\", err);\n\n anyhow::bail!(\"parse failed\")\n\n }\n\n }\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/select_statement.rs", "rank": 84, "score": 109851.05619666698 }, { "content": "pub fn from_str(input: &str) -> anyhow::Result<PqlValue> {\n\n pql_value(input)\n\n}\n", "file_path": "qapro-rs/src/parsers/pqlir_parser.rs", "rank": 85, "score": 109851.05619666698 }, { "content": "pub fn parse_expr(input: &str) -> IResult<&str, Expr> {\n\n // The math::parse must be placed after the parse_path_as_expr to prevent the inf keyword from being parsed.\n\n alt((\n\n parse_star_as_expr,\n\n parser::math::parse,\n\n parser::elements::float_number,\n\n parser::func::function,\n\n ))(input)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 86, "score": 109851.05619666698 }, { "content": "pub fn expr_as_field(input: &str) -> IResult<&str, Field> {\n\n // The math::parse must be placed after the parse_path_as_expr to prevent the inf keyword from being parsed.\n\n let (input, (expr, alias)) = tuple((\n\n parse_expr,\n\n opt(preceded(\n\n opt(preceded(multispace0, tag_no_case(\"AS\"))),\n\n preceded(multispace0, alphanumeric1),\n\n )),\n\n ))(input)?;\n\n\n\n let field = Field {\n\n expr,\n\n alias: alias.map(String::from),\n\n };\n\n Ok((input, field))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 87, "score": 109851.05619666698 }, { "content": "pub fn parse_selector(input: &str) -> IResult<&str, Selector> {\n\n pub fn selecotrnode_with_index<'a>(input: &str) -> IResult<&str, Vec<SelectorNode>> {\n\n let (input, (s, opt_i)) = tuple((\n\n string_allowed_in_field,\n\n opt(delimited(char('['), elements::integer, char(']'))),\n\n ))(input)?;\n\n\n\n let mut nodes = vec![];\n\n nodes.push(SelectorNode::String(s));\n\n if let Some(i) = opt_i {\n\n nodes.push(SelectorNode::Number(i as i64));\n\n };\n\n\n\n Ok((input, nodes))\n\n }\n\n\n\n let (input, (opt_dot, vec_nodes)) = tuple((\n\n opt(char('.')),\n\n separated_list1(char('.'), selecotrnode_with_index),\n\n ))(input)?;\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 88, "score": 109851.05619666698 }, { "content": "pub fn pqlvalue_as_field(input: &str) -> IResult<&str, Field> {\n\n let (input, (value, alias)) = tuple((\n\n pqlir_parser::root,\n\n opt(preceded(\n\n opt(preceded(multispace0, tag_no_case(\"AS\"))),\n\n preceded(multispace0, alphanumeric1),\n\n )),\n\n ))(input)?;\n\n\n\n let field = Field {\n\n expr: Expr::Value(value),\n\n alias: alias.map(String::from),\n\n };\n\n Ok((input, field))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 89, "score": 109851.05619666698 }, { "content": "pub fn parse_field(input: &str) -> IResult<&str, Field> {\n\n alt((expr_as_field, pqlvalue_as_field, selector_as_field))(input)\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 90, "score": 109851.05619666698 }, { "content": "pub fn selector_as_field(input: &str) -> IResult<&str, Field> {\n\n let (input, (selector, alias)) = tuple((\n\n parse_selector,\n\n opt(preceded(\n\n opt(preceded(multispace0, tag_no_case(\"AS\"))),\n\n preceded(multispace0, alphanumeric1),\n\n )),\n\n ))(input)?;\n\n\n\n let field = Field {\n\n expr: Expr::Selector(selector),\n\n alias: alias.map(String::from),\n\n };\n\n Ok((input, field))\n\n}\n\n\n", "file_path": "qapro-rs/src/parsers/parser/expressions.rs", "rank": 91, "score": 109851.05619666698 } ]
Rust
src/integer/conversions.rs
declanvk/rimath
e0dbb421d6da09a8b5e92fc9f0d00e5a454e3118
use crate::{error::Error, integer::Integer}; use core::convert::{TryFrom, TryInto}; impl From<i8> for Integer { fn from(src: i8) -> Self { Self::from_c_long(src) } } impl From<&i8> for Integer { fn from(src: &i8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i8 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i8 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<u8> for Integer { fn from(src: u8) -> Self { Self::from_c_long(src) } } impl From<&u8> for Integer { fn from(src: &u8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u8 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u8 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i16> for Integer { fn from(src: i16) -> Self { Self::from_c_long(src) } } impl From<&i16> for Integer { fn from(src: &i16) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i16 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i16 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<u16> for Integer { fn from(src: u16) -> Self { Self::from_c_long(src) } } impl From<&u16> for Integer { fn from(src: &u16) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u16 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u16 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i32> for Integer { fn from(src: i32) -> Self { Self::from_c_long(src) } } impl From<&i32> for Integer { fn from(src: &i32) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } cfg_if::cfg_if! { if #[cfg(all(target_pointer_width = "64", not(windows)))] { impl From<u32> for Integer { fn from(src: u32) -> Self { Self::from_c_long(src) } } impl From<&u32> for Integer { fn from(src: &u32) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i64> for Integer { fn from(src: i64) -> Self { Self::from_c_long(src) } } impl From<&i64> for Integer { fn from(src: &i64) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } } else { impl From<u32> for Integer { fn from(src: u32) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u32> for Integer { fn from(src: &u32) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl From<i64> for Integer { fn from(src: i64) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&i64> for Integer { fn from(src: &i64) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for i64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for i64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } } } impl From<u64> for Integer { fn from(src: u64) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u64> for Integer { fn from(src: &u64) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl From<i128> for Integer { fn from(src: i128) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&i128> for Integer { fn from(src: &i128) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for i128 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for i128 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl From<u128> for Integer { fn from(src: u128) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u128> for Integer { fn from(src: &u128) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u128 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u128 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } #[cfg(test)] mod test { use super::*; use core::{convert::TryFrom, str::FromStr}; #[test] fn conversion_to_primitive() { let valid_i8 = Integer::from_str("56").unwrap(); let invalid_i8 = Integer::from_str("129").unwrap(); assert_eq!(TryFrom::try_from(valid_i8), Ok(56i8)); assert_eq!( TryFrom::try_from(invalid_i8), Err(Error::ConversionOutsideRange) as Result<i8, _> ); let valid_i32 = Integer::from_str("-2147483648").unwrap(); let invalid_i32 = Integer::from_str("-2147483649").unwrap(); assert_eq!(TryFrom::try_from(valid_i32), Ok(-2_147_483_648i32)); assert_eq!( TryFrom::try_from(invalid_i32), Err(Error::ConversionOutsideRange) as Result<i32, _> ); let valid_i128 = Integer::from_str("170141183460469231731687303715884105727").unwrap(); let invalid_i128 = Integer::from_str("170141183460469231731687303715884105728").unwrap(); assert_eq!( TryFrom::try_from(valid_i128), Ok(170_141_183_460_469_231_731_687_303_715_884_105_727i128) ); assert_eq!( TryFrom::try_from(invalid_i128), Err(Error::ConversionOutsideRange) as Result<i128, _> ); } }
use crate::{error::Error, integer::Integer}; use core::convert::{TryFrom, TryInto}; impl From<i8> for Integer { fn from(src: i8) -> Self { Self::from_c_long(src) } } impl From<&i8> for Integer { fn from(src: &i8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i8 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i8 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<u8> for Integer { fn from(src: u8) -> Self { Self::from_c_long(src) } } impl From<&u8> for Integer { fn from(src: &u8) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u8 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u8 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i16> for Integer { fn from(src: i16) -> Self { Self::from_c_long(src) } } impl From<&i16> for Integer { fn from(src: &i16) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i16 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from))
fn from(src: &i128) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for i128 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for i128 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl From<u128> for Integer { fn from(src: u128) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u128> for Integer { fn from(src: &u128) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u128 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u128 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } #[cfg(test)] mod test { use super::*; use core::{convert::TryFrom, str::FromStr}; #[test] fn conversion_to_primitive() { let valid_i8 = Integer::from_str("56").unwrap(); let invalid_i8 = Integer::from_str("129").unwrap(); assert_eq!(TryFrom::try_from(valid_i8), Ok(56i8)); assert_eq!( TryFrom::try_from(invalid_i8), Err(Error::ConversionOutsideRange) as Result<i8, _> ); let valid_i32 = Integer::from_str("-2147483648").unwrap(); let invalid_i32 = Integer::from_str("-2147483649").unwrap(); assert_eq!(TryFrom::try_from(valid_i32), Ok(-2_147_483_648i32)); assert_eq!( TryFrom::try_from(invalid_i32), Err(Error::ConversionOutsideRange) as Result<i32, _> ); let valid_i128 = Integer::from_str("170141183460469231731687303715884105727").unwrap(); let invalid_i128 = Integer::from_str("170141183460469231731687303715884105728").unwrap(); assert_eq!( TryFrom::try_from(valid_i128), Ok(170_141_183_460_469_231_731_687_303_715_884_105_727i128) ); assert_eq!( TryFrom::try_from(invalid_i128), Err(Error::ConversionOutsideRange) as Result<i128, _> ); } }
} } impl TryFrom<&Integer> for i16 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<u16> for Integer { fn from(src: u16) -> Self { Self::from_c_long(src) } } impl From<&u16> for Integer { fn from(src: &u16) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u16 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u16 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i32> for Integer { fn from(src: i32) -> Self { Self::from_c_long(src) } } impl From<&i32> for Integer { fn from(src: &i32) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } cfg_if::cfg_if! { if #[cfg(all(target_pointer_width = "64", not(windows)))] { impl From<u32> for Integer { fn from(src: u32) -> Self { Self::from_c_long(src) } } impl From<&u32> for Integer { fn from(src: &u32) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for u32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for u32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl From<i64> for Integer { fn from(src: i64) -> Self { Self::from_c_long(src) } } impl From<&i64> for Integer { fn from(src: &i64) -> Self { Self::from_c_long(*src) } } impl TryFrom<Integer> for i64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } impl TryFrom<&Integer> for i64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.try_into_c_long() .and_then(|value| value.try_into().map_err(From::from)) } } } else { impl From<u32> for Integer { fn from(src: u32) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u32> for Integer { fn from(src: &u32) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u32 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u32 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl From<i64> for Integer { fn from(src: i64) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&i64> for Integer { fn from(src: &i64) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for i64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for i64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string().parse().map_err(|_| Error::ConversionOutsideRange) } } } } impl From<u64> for Integer { fn from(src: u64) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&u64> for Integer { fn from(src: &u64) -> Self { Self::from_string_repr(*src, 10).expect("Conversion from string failed") } } impl TryFrom<Integer> for u64 { type Error = Error; fn try_from(src: Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl TryFrom<&Integer> for u64 { type Error = Error; fn try_from(src: &Integer) -> Result<Self, Self::Error> { src.to_string() .parse() .map_err(|_| Error::ConversionOutsideRange) } } impl From<i128> for Integer { fn from(src: i128) -> Self { Self::from_string_repr(src, 10).expect("Conversion from string failed") } } impl From<&i128> for Integer {
random
[ { "content": "fn fib_iter() -> impl Iterator<Item = Integer> {\n\n struct FibIter {\n\n x: Integer,\n\n y: Integer,\n\n }\n\n\n\n impl Iterator for FibIter {\n\n type Item = Integer;\n\n\n\n fn next(&mut self) -> Option<Integer> {\n\n let next_y = &self.x + &self.y;\n\n let next_x = mem::replace(&mut self.y, next_y);\n\n let next = mem::replace(&mut self.x, next_x);\n\n\n\n Some(next)\n\n }\n\n }\n\n\n\n FibIter {\n\n x: 0.into(),\n\n y: 1.into(),\n\n }\n\n}\n", "file_path": "examples/fibonnaci.rs", "rank": 0, "score": 113954.79657679252 }, { "content": "fn fact_iter() -> impl Iterator<Item = Integer> {\n\n struct FactIter {\n\n multiplier: Integer,\n\n next_value: Integer,\n\n }\n\n\n\n impl Iterator for FactIter {\n\n type Item = Integer;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let next = self.next_value.clone();\n\n self.next_value *= &self.multiplier;\n\n self.multiplier += 1;\n\n\n\n Some(next)\n\n }\n\n }\n\n\n\n FactIter {\n\n multiplier: 1.into(),\n\n next_value: 1.into(),\n\n }\n\n}\n", "file_path": "examples/factorial.rs", "rank": 1, "score": 113954.79657679253 }, { "content": "fn catalan_iter() -> impl Iterator<Item = Integer> {\n\n struct CatalanIter {\n\n next: Integer,\n\n counter: Integer,\n\n }\n\n\n\n impl Iterator for CatalanIter {\n\n type Item = Integer;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let next_next = (2 * (2 * &self.counter + 1) * &self.next) / (&self.counter + 2);\n\n let next = mem::replace(&mut self.next, next_next);\n\n self.counter += 1;\n\n\n\n Some(next)\n\n }\n\n }\n\n\n\n CatalanIter {\n\n next: 1.into(),\n\n counter: 0.into(),\n\n }\n\n}\n", "file_path": "examples/catalan.rs", "rank": 2, "score": 113954.79657679253 }, { "content": "fn pell_numbers_iter() -> impl Iterator<Item = Integer> {\n\n PellLucasNumbersIter {\n\n g: generator,\n\n first: 0.into(),\n\n second: 1.into(),\n\n }\n\n}\n\n\n", "file_path": "examples/pell_numbers.rs", "rank": 3, "score": 107539.26585239841 }, { "content": "fn pell_lucas_numbers_iter() -> impl Iterator<Item = Integer> {\n\n PellLucasNumbersIter {\n\n g: generator,\n\n first: 1.into(),\n\n second: 1.into(),\n\n }\n\n}\n\n\n", "file_path": "examples/pell_numbers.rs", "rank": 4, "score": 104649.69079014953 }, { "content": "fn factorial(v: &Integer) -> Integer {\n\n let mut accum = 1.into();\n\n let mut f = v.clone();\n\n\n\n while f > 0 {\n\n accum *= &f;\n\n f -= 1;\n\n }\n\n\n\n accum\n\n}\n\n\n", "file_path": "examples/pi.rs", "rank": 5, "score": 89347.6330203239 }, { "content": "// Product of all odd integer up to the given value.\n\nfn odd_factorial(v: &Integer) -> Integer {\n\n let mut accum = 1.into();\n\n let mut f = if v % 2 == 0 { v - 1 } else { v.clone() };\n\n\n\n while f > 0 {\n\n accum *= &f;\n\n f -= 2;\n\n }\n\n\n\n accum\n\n}\n\n\n", "file_path": "examples/pi.rs", "rank": 6, "score": 86819.6355135926 }, { "content": "fn parse_integer(s: &str) -> Integer {\n\n let (s, radix) = if let Some(s) = s.strip_prefix(\"#\") {\n\n let radix = match s.chars().next() {\n\n Some('x') | Some('X') => 16,\n\n Some('d') | Some('D') => 10,\n\n Some('o') | Some('O') => 8,\n\n Some('b') | Some('B') => 2,\n\n x => panic!(\"unable to parse radix symbol: '{:?}'\", x),\n\n };\n\n\n\n (s.get(1..).expect(\"unable to slice remainder\"), radix)\n\n } else {\n\n (s, 10)\n\n };\n\n\n\n Integer::from_string(s, radix).unwrap_or_else(|err| panic!(\"unable to parse: {:?}. {}\", s, err))\n\n}\n\n\n", "file_path": "tests/creachadair_imath.rs", "rank": 7, "score": 84449.31161508025 }, { "content": "fn generator(first: &Integer, second: &Integer) -> Integer {\n\n 2 * second + first\n\n}\n\n\n", "file_path": "examples/pell_numbers.rs", "rank": 8, "score": 83057.69279538111 }, { "content": "fn sqrt_2_approximations() -> impl Iterator<Item = Rational> {\n\n pell_lucas_numbers_iter()\n\n .zip(pell_numbers_iter())\n\n .skip(1)\n\n .map(Rational::from)\n\n}\n", "file_path": "examples/pell_numbers.rs", "rank": 9, "score": 82810.65273552945 }, { "content": "fn read_file(path: impl AsRef<Path>) -> String {\n\n let mut file = File::open(path.as_ref()).expect(\"unable to open file for read\");\n\n let mut contents = String::new();\n\n file.read_to_string(&mut contents)\n\n .expect(\"unable to read file to string\");\n\n\n\n contents\n\n}\n\n\n", "file_path": "tests/creachadair_imath.rs", "rank": 10, "score": 78591.23452190174 }, { "content": "fn get_creachadair_imath_sys_error_msg(code: creachadair_imath_sys::mp_result) -> String {\n\n // This is safe because the function will always return a cstring with static\n\n // lifetime, even if the error code is not a recognized value.\n\n let err_char_ptr = unsafe { creachadair_imath_sys::mp_error_string(code) };\n\n\n\n // This function is safe bc I checked the static string that `mp_error_string`\n\n // return and they conform to the condition of ending with nul byte. Other\n\n // conditions around lifetimes, and the borrowed cstring being edited are not an\n\n // issue because it is converted to a `String` immediately.\n\n unsafe { CStr::from_ptr(err_char_ptr) }\n\n .to_string_lossy()\n\n .into_owned()\n\n}\n\n\n\nmacro_rules! imath_check_panic {\n\n ($arg:expr) => {\n\n // Accessing this is safe bc the MP_OK value is only ever used as an error\n\n // condition.\n\n if $arg != unsafe { creachadair_imath_sys::MP_OK } {\n\n panic!(\n", "file_path": "src/error.rs", "rank": 11, "score": 72874.66361293537 }, { "content": "fn array_from_iter<T, const N: usize>(mut iter: impl Iterator<Item = T>) -> [T; N] {\n\n // TODO: replace with `MaybeUninit::uninit_array` when stable\n\n // SAFETY: An uninitialized `[MaybeUninit<_>; LEN]` is valid.\n\n let mut arr = unsafe { MaybeUninit::<[MaybeUninit<T>; N]>::uninit().assume_init() };\n\n\n\n for idx in 0..N {\n\n let item = iter.next().expect(\"Unable to extract all N items\");\n\n unsafe { arr[idx].as_mut_ptr().write(item) }\n\n }\n\n\n\n // TODO: replace with `MaybeUninit::array_assume_init` when stable\n\n // SAFETY:\n\n // * Earlier blocks guarantee all N elements are initialized\n\n // * `MaybeUninit<T>` and T are guaranteed to have the same layout\n\n // * MaybeUnint does not drop, so there are no double-frees\n\n // And thus the conversion is safe\n\n unsafe { (&arr as *const _ as *const [T; N]).read() }\n\n}\n\n\n", "file_path": "tests/creachadair_imath.rs", "rank": 12, "score": 59328.84795655254 }, { "content": "fn help() {\n\n eprintln!(\"Usage: ./pi.rs <iterations> <precision>\");\n\n}\n", "file_path": "examples/pi.rs", "rank": 13, "score": 57744.12233228292 }, { "content": "fn main() {\n\n common::sequence_main(\"fibonacci\", fib_iter())\n\n}\n\n\n", "file_path": "examples/fibonnaci.rs", "rank": 14, "score": 57744.12233228292 }, { "content": "fn main() {\n\n common::sequence_main(\"factorial\", fact_iter())\n\n}\n\n\n", "file_path": "examples/factorial.rs", "rank": 15, "score": 57744.12233228292 }, { "content": "fn main() {\n\n common::sequence_main(\"catalan\", catalan_iter());\n\n}\n\n\n", "file_path": "examples/catalan.rs", "rank": 16, "score": 57744.12233228292 }, { "content": "// Compute the value of PI to a selected degree of precision.\n\nfn main() {\n\n let args: Vec<_> = env::args().collect();\n\n\n\n if let Some([iterations, precision]) = args.get(1..=2) {\n\n let iterations = iterations\n\n .parse()\n\n .expect(\"Unable to parse 'iterations' value as a 32-bit unsigned integer.\");\n\n let precision = precision\n\n .parse()\n\n .expect(\"Unable to parse 'precision' value as a 16-bit unsigned integer.\");\n\n\n\n let pi = compute_pi_approx(iterations);\n\n\n\n println!(\"{}\", pi.to_decimal(RoundMode::HalfUp, precision));\n\n } else {\n\n help();\n\n }\n\n}\n\n\n", "file_path": "examples/pi.rs", "rank": 17, "score": 57744.12233228292 }, { "content": "def is_manual_instance_impl(instance_desc):\n", "file_path": "scripts/generate_integer_ops.py", "rank": 18, "score": 57180.53799709042 }, { "content": "def generate_impl_instance(field_pos, instance_desc):\n\n if is_manual_instance_impl(instance_desc):\n\n # body is ready to go\n\n return instance_desc[field_pos['body']]\n\n else:\n\n # got to generate the body\n\n inner_fn = instance_desc[field_pos['inner_fn']]\n\n mut_inplace_return = instance_desc[field_pos['mut_inplace_return']]\n\n\n\n lhs_value = apply_all_effects(\n\n instance_desc[field_pos['lhs_effects']], \"self\")\n\n rhs_value = apply_all_effects(\n\n instance_desc[field_pos['rhs_effects']], \"rhs\")\n\n\n\n format_kwargs = {\n\n 'inner_fn': inner_fn,\n\n 'lhs_value': lhs_value,\n\n 'rhs_value': rhs_value\n\n }\n\n\n\n if mut_inplace_return == \"no\":\n\n body_template = REGULAR_BINOP_FN_BODY_TEMPLATE\n\n else:\n\n if mut_inplace_return == 'lhs':\n\n format_kwargs['ret_value'] = 'self'\n\n elif mut_inplace_return == 'rhs':\n\n format_kwargs['ret_value'] = 'rhs'\n\n\n\n body_template = MUT_INPLACE_RETURN_FN_BODY_TEMPLATE\n\n\n", "file_path": "scripts/generate_integer_ops.py", "rank": 19, "score": 57180.53799709042 }, { "content": "fn main() {\n\n common::sequence_main_custom_display(\"sqrt_2_approximations\", sqrt_2_approximations(), |rat| {\n\n rat.to_decimal(RoundMode::HalfUp, 100)\n\n });\n\n}\n\n\n", "file_path": "examples/pell_numbers.rs", "rank": 20, "score": 56035.341905205954 }, { "content": "fn main() {\n\n let root_dir = canonicalize(PathBuf::from(env::var(\"CARGO_MANIFEST_DIR\").unwrap())).unwrap();\n\n let src = root_dir.join(\"vendor\").join(\"imath\");\n\n\n\n let headers: Vec<_> = HEADER_FILES.iter().map(|head| src.join(head)).collect();\n\n let sources: Vec<_> = SRC_FILES.iter().map(|head| src.join(head)).collect();\n\n\n\n let mut source_builder = Build::new();\n\n for path in &sources {\n\n source_builder.file(path);\n\n }\n\n\n\n source_builder.include(&src).compile(\"imath\");\n\n\n\n // Tell cargo to invalidate the built crate whenever the headers change\n\n for path in &headers {\n\n println!(\"cargo:rerun-if-changed={}\", path.display());\n\n }\n\n\n\n let mut bindings_builder = bindgen::builder();\n", "file_path": "creachadair-imath-sys/build.rs", "rank": 21, "score": 54467.52763888114 }, { "content": "#[test]\n\nfn check_test_data_sub() {\n\n let file_contents = read_file(tc_path!(\"sub.tc\"));\n\n let test_cases = file_contents\n\n .lines()\n\n .filter(filter_comments_and_whitespace)\n\n .map(TestCase::<3, 1>::parse);\n\n\n\n for tc in test_cases {\n\n match tc.operator {\n\n \"sub\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs = parse_integer(tc.arguments[1]);\n\n let result = lhs - rhs;\n\n let expected = parse_integer(tc.outputs[0]);\n\n\n\n assert_eq!(result, expected);\n\n }\n\n \"subv\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs_large = parse_integer(tc.arguments[1]);\n", "file_path": "tests/creachadair_imath.rs", "rank": 22, "score": 51690.34078578444 }, { "content": "#[test]\n\nfn check_test_data_add() {\n\n let file_contents = read_file(tc_path!(\"add.tc\"));\n\n let test_cases = file_contents\n\n .lines()\n\n .filter(filter_comments_and_whitespace)\n\n .map(TestCase::<3, 1>::parse);\n\n\n\n for tc in test_cases {\n\n match tc.operator {\n\n \"add\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs = parse_integer(tc.arguments[1]);\n\n let result = lhs + rhs;\n\n let expected = parse_integer(tc.outputs[0]);\n\n\n\n assert_eq!(result, expected);\n\n }\n\n \"addv\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs_large = parse_integer(tc.arguments[1]);\n", "file_path": "tests/creachadair_imath.rs", "rank": 23, "score": 51690.34078578444 }, { "content": "#[test]\n\nfn check_test_data_neg() {\n\n let file_contents = read_file(tc_path!(\"neg.tc\"));\n\n let test_cases = file_contents\n\n .lines()\n\n .filter(filter_comments_and_whitespace)\n\n .map(TestCase::<2, 1>::parse);\n\n\n\n for tc in test_cases {\n\n match tc.operator {\n\n \"neg\" => {\n\n let input = parse_integer(tc.arguments[0]);\n\n let output = -input;\n\n\n\n let expected = parse_integer(tc.outputs[0]);\n\n\n\n assert_eq!(output, expected);\n\n }\n\n x => panic!(\"unknown operator: {:?}\", x),\n\n }\n\n }\n\n}\n", "file_path": "tests/creachadair_imath.rs", "rank": 24, "score": 51690.34078578444 }, { "content": "#[test]\n\nfn check_test_data_mul() {\n\n let file_contents = read_file(tc_path!(\"mul.tc\"));\n\n let test_cases = file_contents\n\n .lines()\n\n .filter(filter_comments_and_whitespace)\n\n .map(TestCase::<3, 1>::parse);\n\n\n\n for tc in test_cases {\n\n match tc.operator {\n\n \"mul\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs = parse_integer(tc.arguments[1]);\n\n let result = lhs * rhs;\n\n let expected = parse_integer(tc.outputs[0]);\n\n\n\n assert_eq!(result, expected);\n\n }\n\n \"mulv\" => {\n\n let lhs = parse_integer(tc.arguments[0]);\n\n let rhs_large = parse_integer(tc.arguments[1]);\n", "file_path": "tests/creachadair_imath.rs", "rank": 25, "score": 51690.34078578444 }, { "content": "#[test]\n\nfn add_two_numbers() {\n\n let mut a: MaybeUninit<creachadair_imath_sys::mpz_t> = MaybeUninit::uninit();\n\n let mut b: MaybeUninit<creachadair_imath_sys::mpz_t> = MaybeUninit::uninit();\n\n let mut c: MaybeUninit<creachadair_imath_sys::mpz_t> = MaybeUninit::uninit();\n\n\n\n let mut expected: MaybeUninit<creachadair_imath_sys::mpz_t> = MaybeUninit::uninit();\n\n\n\n unsafe {\n\n creachadair_imath_sys::mp_int_init_value(a.as_mut_ptr(), 1024);\n\n creachadair_imath_sys::mp_int_init_value(b.as_mut_ptr(), 4201);\n\n creachadair_imath_sys::mp_int_init_value(c.as_mut_ptr(), 0);\n\n\n\n creachadair_imath_sys::mp_int_init_value(expected.as_mut_ptr(), 5225);\n\n }\n\n\n\n let res = unsafe {\n\n creachadair_imath_sys::mp_int_add(a.as_mut_ptr(), b.as_mut_ptr(), c.as_mut_ptr())\n\n };\n\n\n\n if res != unsafe { creachadair_imath_sys::MP_OK } {\n", "file_path": "creachadair-imath-sys/tests/smoke_test.rs", "rank": 26, "score": 49306.46971232634 }, { "content": "// Compute a rational approximation of PI based on https://en.wikipedia.org/wiki/Approximations_of_%CF%80#Other_classical_formulae\n\n//\n\n// ```\n\n// \\frac{\\pi}{2}\n\n// = \\sum_{k=0}^\\infty\\frac{k!}{(2k+1)!!}\n\n// = \\sum_{k=0}^{\\infty} \\cfrac {2^k k!^2}{(2k + 1)!}\n\n// = 1+\\frac{1}{3}\\left(1+\\frac{2}{5}\\left(1+\\frac{3}{7}\\left(1+\\cdots\\right)\\right)\\right)\n\n// ```\n\nfn compute_pi_approx(iterations: u32) -> Rational {\n\n 2 * (0..iterations)\n\n .map(Integer::from)\n\n .map(|n| {\n\n let numerator = factorial(&n);\n\n let denominator = odd_factorial(&(2 * n + 1));\n\n\n\n (numerator, denominator).into()\n\n })\n\n .sum::<Rational>()\n\n}\n\n\n", "file_path": "examples/pi.rs", "rank": 27, "score": 43433.51816965589 }, { "content": "fn filter_comments_and_whitespace(input: &&str) -> bool {\n\n let trimmed = input.trim_start();\n\n\n\n return !(trimmed.starts_with('#') || trimmed.is_empty());\n\n}\n\n\n\nmacro_rules! tc_path {\n\n ($s:expr) => {\n\n concat!(\"creachadair-imath-sys/vendor/imath/tests/\", $s)\n\n };\n\n}\n\n\n", "file_path": "tests/creachadair_imath.rs", "rank": 28, "score": 42285.33327881541 }, { "content": " get_creachadair_imath_sys_error_msg(*code)\n\n ),\n\n Error::NotCanonicalInteger => write!(\n\n f,\n\n \"The rational value is not a canonical integer, in the form `n/1`.\"\n\n ),\n\n }\n\n }\n\n}\n\n\n\nimpl From<TryFromIntError> for Error {\n\n fn from(_src: TryFromIntError) -> Self {\n\n Error::ConversionOutsideRange\n\n }\n\n}\n\n\n\nimpl From<Infallible> for Error {\n\n fn from(_src: Infallible) -> Self {\n\n Error::NoErrorPossible\n\n }\n\n}\n\n\n\nimpl From<ParseIntError> for Error {\n\n fn from(_src: ParseIntError) -> Self {\n\n Error::IntParseFailed\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 29, "score": 41761.638426606216 }, { "content": "impl std::error::Error for Error {}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Error::StringReprContainedNul => {\n\n write!(f, \"String representation contained a 'nul' character.\")\n\n }\n\n Error::ReadStringTruncated => write!(\n\n f,\n\n \"During conversion, the value representation was truncated.\"\n\n ),\n\n Error::RemainderOutsideBounds => write!(\n\n f,\n\n \"The result of a remainder operation was outside the expected bounds.\"\n\n ),\n\n Error::ConversionOutsideRange => write!(\n\n f,\n\n \"Attempted to convert to a primitive integer while outside its valid range.\"\n\n ),\n", "file_path": "src/error.rs", "rank": 30, "score": 41756.055640604645 }, { "content": "use core::{\n\n convert::Infallible,\n\n fmt,\n\n num::{ParseIntError, TryFromIntError},\n\n};\n\nuse std::ffi::CStr;\n\n\n\npub(crate) type Result<T> = core::result::Result<T, Error>;\n\n\n\n/// Error used in `reckoner`, usually originating from `creachadair-imath-sys`.\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum Error {\n\n /// When converting from a string representation, the given string contained\n\n /// a zero-byte that was not at the end.\n\n StringReprContainedNul,\n\n /// An error occurred when converting a string to a value, and the\n\n /// output was truncated.\n\n ReadStringTruncated,\n\n /// The result of a remainder operation was outside the expected bounds.\n\n RemainderOutsideBounds,\n", "file_path": "src/error.rs", "rank": 31, "score": 41754.9115758831 }, { "content": " /// Could not convert a value to a primitive integer type because it was\n\n /// outside the range.\n\n ConversionOutsideRange,\n\n /// Integer parse failed.\n\n IntParseFailed,\n\n /// It impossible for this error to occur.\n\n NoErrorPossible,\n\n /// Unknown value for an imath rounding mode.\n\n UnknownRoundingMode,\n\n /// Internal error from `creachadair_imath_sys`.\n\n IMath {\n\n /// Internal `creachadair_imath_sys` error code.\n\n code: creachadair_imath_sys::mp_result,\n\n /// Custom message to display.\n\n msg: Option<&'static str>,\n\n },\n\n /// The rational value is not a canonical integer, in the form `n/1`.\n\n NotCanonicalInteger,\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 32, "score": 41754.501777227495 }, { "content": " \"{}\",\n\n Error::IMath {\n\n code: $arg,\n\n msg: None\n\n }\n\n );\n\n }\n\n };\n\n\n\n ($arg:expr, $msg:tt) => {\n\n // Accessing this is safe bc the MP_OK value is only ever used as an error\n\n // condition.\n\n if $arg != unsafe { creachadair_imath_sys::MP_OK } {\n\n panic!(\n\n \"{}\",\n\n Error::IMath {\n\n code: $arg,\n\n msg: Some($msg)\n\n }\n\n );\n\n }\n\n };\n\n}\n", "file_path": "src/error.rs", "rank": 33, "score": 41754.02504775329 }, { "content": " Error::IntParseFailed => write!(f, \"Integer parsing failed.\"),\n\n Error::UnknownRoundingMode => write!(f, \"Unknown value for an imath rounding mode.\"),\n\n Error::NoErrorPossible => write!(\n\n f,\n\n \"This error is not supposed to be possible. Please file an issue.\"\n\n ),\n\n Error::IMath {\n\n code,\n\n msg: Some(msg),\n\n } => write!(\n\n f,\n\n \"imath error ({:?} \\\"{}\\\"): {}\",\n\n code,\n\n get_creachadair_imath_sys_error_msg(*code),\n\n msg\n\n ),\n\n Error::IMath { code, msg: None } => write!(\n\n f,\n\n \"imath error ({:?} \\\"{}\\\")\",\n\n code,\n", "file_path": "src/error.rs", "rank": 34, "score": 41753.95996441132 }, { "content": " /// # Example\n\n /// ```\n\n /// use reckoner::Integer;\n\n ///\n\n /// let a = Integer::from_string(\"8\", 10);\n\n /// let b = Integer::from_string(\"1000\", 2);\n\n ///\n\n /// assert_eq!(a, b);\n\n /// ```\n\n pub fn from_string(s: impl AsRef<str>, radix: u8) -> Result<Self> {\n\n Integer::from_string_repr(s.as_ref(), radix.into())\n\n }\n\n\n\n pub(crate) fn from_string_repr(src: impl ToString, radix: u32) -> Result<Self> {\n\n let string_repr =\n\n CString::new(src.to_string()).map_err(|_| Error::StringReprContainedNul)?;\n\n let char_ptr = string_repr.into_raw();\n\n\n\n let mut init = Integer::uninit();\n\n\n", "file_path": "src/integer.rs", "rank": 35, "score": 37006.39396989235 }, { "content": "}\n\n\n\nimpl Default for Integer {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\nimpl FromStr for Integer {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> core::result::Result<Self, Self::Err> {\n\n Integer::from_string_repr(s, 10)\n\n }\n\n}\n\n\n\nimpl Drop for Integer {\n\n fn drop(&mut self) {\n\n unsafe {\n\n let raw = self.as_raw();\n", "file_path": "src/integer.rs", "rank": 36, "score": 37005.49406931429 }, { "content": " \"Integer {{ single: {:?}, digits: {:p}, alloc: {:?}, used: {:?}, sign: {:?} }}\",\n\n single, digits, alloc, used, sign\n\n )\n\n } else {\n\n fmt::Display::fmt(&self, f)\n\n }\n\n }\n\n}\n\n\n\n// This is safe because the `Integer` has exclusive ownership of its data.\n\nunsafe impl Send for Integer {}\n\n\n\nimpl Clone for Integer {\n\n fn clone(&self) -> Self {\n\n Integer::copy_init(self)\n\n }\n\n\n\n fn clone_from(&mut self, source: &Self) {\n\n source.copy_to(self);\n\n }\n", "file_path": "src/integer.rs", "rank": 37, "score": 37004.91828835114 }, { "content": " let self_raw = self.as_raw();\n\n let mut out: c_long = 0;\n\n let out_raw = (&mut out) as *mut _;\n\n\n\n // This is safe bc `self` has been initialized and `out_raw` points to an actual\n\n // integer.\n\n let res = unsafe { creachadair_imath_sys::mp_int_to_int(self_raw, out_raw) };\n\n\n\n // Accessing this is safe bc the MP_OK value is only ever used as an error\n\n // condition.\n\n if res == unsafe { creachadair_imath_sys::MP_OK } {\n\n Ok(out)\n\n } else {\n\n Err(Error::ConversionOutsideRange)\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Integer {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n", "file_path": "src/integer.rs", "rank": 38, "score": 37000.622684208385 }, { "content": "use crate::error::{Error, Result};\n\nuse core::{\n\n cmp::Ordering,\n\n fmt,\n\n mem::{self, MaybeUninit},\n\n ptr::NonNull,\n\n str::FromStr,\n\n};\n\nuse std::{\n\n alloc,\n\n ffi::CString,\n\n os::raw::{c_long, c_ulong},\n\n};\n\n\n\npub(crate) mod comparison;\n\npub(crate) mod conversions;\n\npub(crate) mod ops;\n\n\n\n/// Multiple precision integer value.\n\n#[repr(transparent)]\n", "file_path": "src/integer.rs", "rank": 39, "score": 37000.56960015432 }, { "content": " /// assert_eq!(c, 500);\n\n /// ```\n\n pub fn into_raw(mut integer: Integer) -> *mut creachadair_imath_sys::mpz_t {\n\n let raw = mem::replace(&mut integer.raw, NonNull::dangling());\n\n\n\n // The destructor does not need to run, as we are intentionally leaking the\n\n // resources here.\n\n mem::forget(integer);\n\n\n\n raw.as_ptr()\n\n }\n\n\n\n // Internal use only\n\n pub(crate) fn as_raw(&self) -> *mut creachadair_imath_sys::mpz_t {\n\n self.raw.as_ptr()\n\n }\n\n\n\n pub(crate) fn from_c_long(src: impl Into<c_long>) -> Self {\n\n let mut init = Integer::uninit();\n\n\n", "file_path": "src/integer.rs", "rank": 40, "score": 37000.35113037243 }, { "content": " /// use reckoner::Integer;\n\n ///\n\n /// let a = Integer::new();\n\n ///\n\n /// assert_eq!(a, 0);\n\n /// ```\n\n pub fn new() -> Self {\n\n Self::from_c_long(0)\n\n }\n\n\n\n pub(crate) fn copy_init(other: &Self) -> Self {\n\n let mut init = Integer::uninit();\n\n let other_raw = other.as_raw();\n\n\n\n {\n\n // This is safe bc init is entirely local. raw_mpz is also scoped to be less\n\n // than the lifetime of the value init\n\n let raw_mpz = init.as_mut_ptr();\n\n\n\n // This is safe bc a valid structure is provided to the unsafe methods. And the\n", "file_path": "src/integer.rs", "rank": 41, "score": 37000.30401428586 }, { "content": " /// assert_eq!(a, 0);\n\n /// ```\n\n pub unsafe fn from_raw(raw: *mut creachadair_imath_sys::mpz_t) -> Self {\n\n assert!(!raw.is_null());\n\n\n\n // This is safe bc the invariants of the function and because it was checked\n\n // that the pointer is not null.\n\n #[allow(unused_unsafe)]\n\n let raw = unsafe { NonNull::new_unchecked(raw) };\n\n\n\n Integer { raw }\n\n }\n\n\n\n /// Consumes the Integer, returning a wrapped raw pointer.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use creachadair_imath_sys::{mp_int_add, MP_OK};\n\n /// use reckoner::Integer;\n\n ///\n", "file_path": "src/integer.rs", "rank": 42, "score": 36999.341964723375 }, { "content": " /// use core::cmp::Ordering;\n\n /// use reckoner::Integer;\n\n ///\n\n /// let a = Integer::from(-234);\n\n /// let b = Integer::from(123);\n\n ///\n\n /// assert_eq!(a.compare_zero(), Ordering::Less);\n\n /// assert_eq!(b.compare_zero(), Ordering::Greater);\n\n /// ```\n\n pub fn compare_zero(&self) -> Ordering {\n\n let self_raw = self.as_raw();\n\n\n\n // This is safe bc both self has been initialized correctly\n\n let raw_cmp = unsafe { creachadair_imath_sys::mp_int_compare_zero(self_raw) };\n\n\n\n raw_cmp.cmp(&0)\n\n }\n\n\n\n pub(crate) fn compare_c_long(&self, value: impl Into<c_long>) -> Ordering {\n\n let self_raw = self.as_raw();\n", "file_path": "src/integer.rs", "rank": 43, "score": 36999.023121221064 }, { "content": " /// assert_eq!(b.compare(&a), Ordering::Greater);\n\n /// assert_eq!(b.compare(&b), Ordering::Equal);\n\n /// ```\n\n pub fn compare(&self, rhs: &Self) -> Ordering {\n\n let self_raw = self.as_raw();\n\n let rhs_raw = rhs.as_raw();\n\n\n\n // This is safe bc both self & rhs have been initialized correctly\n\n let raw_cmp = unsafe { creachadair_imath_sys::mp_int_compare(self_raw, rhs_raw) };\n\n\n\n raw_cmp.cmp(&0)\n\n }\n\n\n\n /// Compare the magnitude of two integers, not taking sign into account.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use core::cmp::Ordering;\n\n /// use reckoner::Integer;\n\n ///\n", "file_path": "src/integer.rs", "rank": 44, "score": 36998.6195761415 }, { "content": " /// assert_eq!(a, 0);\n\n /// ```\n\n pub fn zero(&mut self) {\n\n let self_raw = self.as_raw();\n\n\n\n // This is safe bc `self` has been initialized.\n\n unsafe { creachadair_imath_sys::mp_int_zero(self_raw) };\n\n }\n\n\n\n /// Compare two integers\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use reckoner::Integer;\n\n /// use core::cmp::Ordering;\n\n ///\n\n /// let a = Integer::from(123);\n\n /// let b = Integer::from(456);\n\n ///\n\n /// assert_eq!(a.compare(&b), Ordering::Less);\n", "file_path": "src/integer.rs", "rank": 45, "score": 36998.5775677362 }, { "content": "\n\n #[allow(dead_code)]\n\n pub(crate) fn set_value(&mut self, value: impl Into<c_long>) {\n\n let self_raw = self.as_raw();\n\n\n\n let res = unsafe { creachadair_imath_sys::mp_int_set_value(self_raw, value.into()) };\n\n\n\n imath_check_panic!(res, \"Setting the value directly failed!\");\n\n }\n\n\n\n /// Set value of integer to zero\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use reckoner::Integer;\n\n ///\n\n /// let mut a = Integer::from(21837419283648u128);\n\n ///\n\n /// assert_eq!(a, 21837419283648u128);\n\n /// a.zero();\n", "file_path": "src/integer.rs", "rank": 46, "score": 36998.42905564591 }, { "content": " ///\n\n /// In ths context, initialized means that the\n\n /// `creachadair_imath_sys::mpz_t` has been the argument of a call to\n\n /// `creachadair_imath_sys::mp_int_init`.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use creachadair_imath_sys::{mp_int_zero, MP_OK};\n\n /// use reckoner::Integer;\n\n ///\n\n /// let a = Integer::from(300);\n\n ///\n\n /// assert_eq!(a, 300);\n\n ///\n\n /// let a_raw = Integer::into_raw(a);\n\n ///\n\n /// unsafe { mp_int_zero(a_raw) };\n\n ///\n\n /// let a = unsafe { Integer::from_raw(a_raw) };\n\n ///\n", "file_path": "src/integer.rs", "rank": 47, "score": 36998.161327369315 }, { "content": " let string_repr = self.to_cstring();\n\n\n\n f.write_str(string_repr.to_str().unwrap())\n\n }\n\n}\n\n\n\nimpl fmt::Debug for Integer {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n if f.alternate() {\n\n // This is safe bc self has been initialized\n\n let creachadair_imath_sys::mpz_t {\n\n single,\n\n digits,\n\n alloc,\n\n used,\n\n sign,\n\n } = unsafe { *self.as_raw() };\n\n\n\n write!(\n\n f,\n", "file_path": "src/integer.rs", "rank": 48, "score": 36997.942786086416 }, { "content": " \"98712698346126837461287318238761234897612839471623487619872364981726348176234\"\n\n .parse()\n\n .unwrap();\n\n\n\n let b = a.clone();\n\n\n\n assert_eq!(a, b);\n\n }\n\n\n\n #[test]\n\n fn formatting_integer() {\n\n let a = Integer::from(12345);\n\n\n\n let display_out = format!(\"{}\", a);\n\n let debug_out = format!(\"{:?}\", a);\n\n let debug_alt_out = format!(\"{:#?}\", a);\n\n\n\n assert_eq!(display_out, \"12345\");\n\n assert_eq!(debug_out, \"12345\");\n\n assert!(debug_alt_out.starts_with(\"Integer {\"));\n\n }\n\n\n\n #[test]\n\n fn send_not_sync_integer() {\n\n static_assertions::assert_impl_all!(Integer: Send);\n\n static_assertions::assert_not_impl_any!(Integer: Sync);\n\n }\n\n}\n", "file_path": "src/integer.rs", "rank": 49, "score": 36997.6784691575 }, { "content": "\n\n // This will ensure that the memory holding the integer data (the digits?) is\n\n // not leaked.\n\n creachadair_imath_sys::mp_int_clear(raw);\n\n\n\n // This will ensure that the memory that held the `creachadair_imath_sys::mpz_t`\n\n // is not leaked.\n\n drop(Box::from_raw(raw));\n\n }\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 create_default_integer() {\n\n let int = Integer::new();\n\n\n", "file_path": "src/integer.rs", "rank": 50, "score": 36996.87030330806 }, { "content": "pub struct Integer {\n\n // This value must be constructed from a Box and then when Drop, must be reconstructed so that\n\n // the Box Drop can free the memory used.\n\n raw: NonNull<creachadair_imath_sys::mpz_t>,\n\n}\n\n\n\nimpl Integer {\n\n pub(crate) fn uninit() -> Box<MaybeUninit<creachadair_imath_sys::mpz_t>> {\n\n // Replace with Box::new_uninit when it is stable (1.40 maybe?).\n\n let layout = alloc::Layout::new::<MaybeUninit<creachadair_imath_sys::mpz_t>>();\n\n let ptr = unsafe { alloc::alloc(layout) };\n\n // This cast is safe bc the layout was specified for\n\n // MaybeUninit<creachadair_imath_sys::mpz_t>\n\n unsafe { Box::from_raw(ptr.cast()) }\n\n }\n\n\n\n /// Construct a new integer with a default value of zero.\n\n ///\n\n /// # Example\n\n /// ```\n", "file_path": "src/integer.rs", "rank": 51, "score": 36996.78886364951 }, { "content": " {\n\n // This is safe bc init is entirely local. raw_mpz is also scoped to be less\n\n // than the lifetime of the value init\n\n let raw_mpz = init.as_mut_ptr();\n\n\n\n // This is safe bc a valid structure is provided to the unsafe methods. And the\n\n // src value is of the correct type?\n\n let res_init = unsafe { creachadair_imath_sys::mp_int_init(raw_mpz) };\n\n\n\n imath_check_panic!(res_init, \"Init failed!\");\n\n\n\n // This is safe bc all the data provided to the function is correctly setup\n\n // (integer was allocated/initialized, char_ptr is 0-terminated).\n\n let res_read =\n\n unsafe { creachadair_imath_sys::mp_int_read_string(raw_mpz, radix, char_ptr) };\n\n\n\n // Accessing this is safe bc the MP_OK value is only ever used as an error\n\n // condition.\n\n if res_read != unsafe { creachadair_imath_sys::MP_OK } {\n\n return Err(Error::ReadStringTruncated);\n", "file_path": "src/integer.rs", "rank": 52, "score": 36996.15037653031 }, { "content": " /// let a = Integer::from(-234);\n\n /// let b = Integer::from(123);\n\n ///\n\n /// assert_eq!(a.compare_magnitude(&b), Ordering::Greater);\n\n /// assert_eq!(a.compare(&b), Ordering::Less);\n\n /// ```\n\n pub fn compare_magnitude(&self, rhs: &Self) -> Ordering {\n\n let self_raw = self.as_raw();\n\n let rhs_raw = rhs.as_raw();\n\n\n\n // This is safe bc both self & rhs have been initialized correctly\n\n let raw_cmp = unsafe { creachadair_imath_sys::mp_int_compare_unsigned(self_raw, rhs_raw) };\n\n\n\n raw_cmp.cmp(&0)\n\n }\n\n\n\n /// Compare an integer to zero.\n\n ///\n\n /// # Example\n\n /// ```\n", "file_path": "src/integer.rs", "rank": 53, "score": 36996.02884759515 }, { "content": " /// let a = Integer::from(20);\n\n /// let mut b = Integer::new();\n\n ///\n\n /// assert_eq!(a, 20);\n\n /// assert_eq!(b, 0);\n\n ///\n\n /// a.copy_to(&mut b);\n\n ///\n\n /// assert_eq!(a, 20);\n\n /// assert_eq!(b, 20, \"Failed to copy\");\n\n /// ```\n\n pub fn copy_to(&self, other: &mut Self) {\n\n let self_raw = self.as_raw();\n\n let other_raw = other.as_raw();\n\n\n\n // This is safe bc self has been initialized with a value\n\n let res = unsafe { creachadair_imath_sys::mp_int_copy(self_raw, other_raw) };\n\n\n\n imath_check_panic!(res, \"Copying the value failed!\");\n\n }\n", "file_path": "src/integer.rs", "rank": 54, "score": 36995.72919671318 }, { "content": " // At this point, char_vec is a zero-terminated (possibly with many zeros)\n\n // string containing a string representation of the integer value.\n\n let (non_zero_idx, _) = char_vec\n\n .iter()\n\n .enumerate()\n\n .rfind(|(_, c)| **c != 0)\n\n .unwrap();\n\n let without_nul = &char_vec.as_slice()[..=non_zero_idx];\n\n\n\n CString::new(without_nul).expect(\"Failed to produce a valid CString\")\n\n }\n\n\n\n /// Replaces the value of `other` with a copy of the value of `self`. No new\n\n /// memory is allocated unless `self` has more significant digits than\n\n /// `other` has allocated.\n\n ///\n\n /// # Example\n\n /// ```\n\n /// use reckoner::Integer;\n\n ///\n", "file_path": "src/integer.rs", "rank": 55, "score": 36995.59278253273 }, { "content": " // src value is of the correct type?\n\n let res = unsafe { creachadair_imath_sys::mp_int_init_copy(raw_mpz, other_raw) };\n\n\n\n imath_check_panic!(res, \"Value init failed!\");\n\n }\n\n\n\n // This cast is safe (from MaybeUninit<creachadair_imath_sys::mpz_t> to\n\n // creachadair_imath_sys::mpz_t) because the value is now initialized.\n\n unsafe { Integer::from_raw(Box::into_raw(init).cast()) }\n\n }\n\n\n\n /// Construct an Integer from a raw non-null pointer to\n\n /// `creachadair_imath_sys::mpz_t`.\n\n ///\n\n /// # Safety\n\n ///\n\n /// This function must only every be called once for a given pointer, and\n\n /// the pointer must point to an initialized `creachadair_imath_sys::mpz_t`\n\n /// struct. The recommendation is to only use raw pointers from the\n\n /// `Integer::into_raw` function.\n", "file_path": "src/integer.rs", "rank": 56, "score": 36995.45364202445 }, { "content": " /// let a = Integer::from(200);\n\n /// let b = Integer::from(300);\n\n /// let c = Integer::new();\n\n ///\n\n /// let a_raw = Integer::into_raw(a);\n\n /// let b_raw = Integer::into_raw(b);\n\n /// let c_raw = Integer::into_raw(c);\n\n ///\n\n /// let op_res = unsafe { mp_int_add(a_raw, b_raw, c_raw) };\n\n ///\n\n /// if op_res != unsafe { MP_OK } {\n\n /// panic!(\"Operation failed.\")\n\n /// }\n\n ///\n\n /// let a = unsafe { Integer::from_raw(a_raw) };\n\n /// let b = unsafe { Integer::from_raw(b_raw) };\n\n /// let c = unsafe { Integer::from_raw(c_raw) };\n\n ///\n\n /// assert_eq!(a, 200);\n\n /// assert_eq!(b, 300);\n", "file_path": "src/integer.rs", "rank": 57, "score": 36995.16346264998 }, { "content": " }\n\n\n\n #[test]\n\n fn zero_integer() {\n\n let mut big_int: Integer =\n\n \"98712698346126837461287318238761234897612839471623487619872364981726348176234\"\n\n .parse()\n\n .unwrap();\n\n let mut small_int: Integer = (-4_565_234).into();\n\n\n\n big_int.zero();\n\n assert_eq!(big_int, 0);\n\n\n\n small_int.zero();\n\n assert_eq!(small_int, 0);\n\n }\n\n\n\n #[test]\n\n fn clone_integer() {\n\n let a: Integer =\n", "file_path": "src/integer.rs", "rank": 58, "score": 36994.95191436259 }, { "content": " let string_repr = int.to_string();\n\n assert_eq!(&string_repr, \"0\");\n\n }\n\n\n\n #[test]\n\n fn create_integer_with_value() {\n\n assert_eq!(format!(\"{}\", Integer::from(20000)), \"20000\");\n\n assert_eq!(format!(\"{}\", Integer::from(6)), \"6\");\n\n }\n\n\n\n #[test]\n\n fn parse_big_integer() {\n\n let int: Integer =\n\n \"98712698346126837461287318238761234897612839471623487619872364981726348176234\"\n\n .parse()\n\n .unwrap();\n\n #[allow(clippy::eq_op)]\n\n let zero = &int - &int;\n\n\n\n assert_eq!(zero, 0)\n", "file_path": "src/integer.rs", "rank": 59, "score": 36994.81704647171 }, { "content": " }\n\n }\n\n\n\n // This is safe bc we produced the char_ptr earlier from a CString\n\n let _ = unsafe { CString::from_raw(char_ptr) };\n\n\n\n Ok(\n\n // This `Integer::from_raw` is safe because\n\n //\n\n // This cast is safe (from MaybeUninit<creachadair_imath_sys::mpz_t> to\n\n // creachadair_imath_sys::mpz_t) because the value is now initialized.\n\n unsafe { Integer::from_raw(Box::into_raw(init).cast()) },\n\n )\n\n }\n\n\n\n // Reports the minimum number of characters required to represent `z` as a\n\n // zero-terminated string in base-10.\n\n pub(crate) fn required_display_len(&self) -> usize {\n\n let self_raw = self.as_raw();\n\n\n", "file_path": "src/integer.rs", "rank": 60, "score": 36993.334279210074 }, { "content": " debug_assert_eq!(required_len, cap);\n\n unsafe {\n\n creachadair_imath_sys::mp_int_to_string(\n\n self_raw,\n\n 10,\n\n char_ptr as *mut _,\n\n required_len as i32,\n\n )\n\n }\n\n };\n\n\n\n imath_check_panic!(res, \"Writing the value as a string failed!\");\n\n\n\n // Setting the length is safe bc we now that the `mp_int_to_string`\n\n // should have used the entire capacity to write to\n\n // string.\n\n unsafe {\n\n char_vec.set_len(required_len);\n\n }\n\n\n", "file_path": "src/integer.rs", "rank": 61, "score": 36993.075453202204 }, { "content": " {\n\n // This is safe bc init is entirely local. raw_mpz is also scoped to be less\n\n // than the lifetime of the value init\n\n let raw_mpz = init.as_mut_ptr();\n\n\n\n // This is safe bc a valid structure is provided to the unsafe methods. And the\n\n // src value is of the correct type?\n\n let res = unsafe { creachadair_imath_sys::mp_int_init_value(raw_mpz, src.into()) };\n\n\n\n imath_check_panic!(res, \"Value init failed!\");\n\n }\n\n\n\n // This cast is safe (from MaybeUninit<creachadair_imath_sys::mpz_t> to\n\n // creachadair_imath_sys::mpz_t) because the value is now initialized.\n\n unsafe { Integer::from_raw(Box::into_raw(init).cast()) }\n\n }\n\n\n\n /// Parse an `Integer` from the given string, with the specified\n\n /// radix.\n\n ///\n", "file_path": "src/integer.rs", "rank": 62, "score": 36993.03876409814 }, { "content": " // This is safe bc self has been initialized\n\n let len = unsafe { creachadair_imath_sys::mp_int_string_len(self_raw, 10) };\n\n\n\n // The output of the call is an i32, check that it is gte zero.\n\n assert!(len >= 0);\n\n len as usize\n\n }\n\n\n\n pub(crate) fn to_cstring(&self) -> CString {\n\n let required_len = self.required_display_len();\n\n let self_raw = self.as_raw();\n\n\n\n let mut char_vec: Vec<u8> = Vec::with_capacity(required_len);\n\n // Initialize all to zero\n\n char_vec.resize_with(required_len, Default::default);\n\n\n\n let res = {\n\n let char_ptr = char_vec.as_mut_ptr();\n\n let cap = char_vec.capacity();\n\n\n", "file_path": "src/integer.rs", "rank": 63, "score": 36992.727133627726 }, { "content": " let value = value.into();\n\n\n\n // This is safe bc both self has been initialized correctly\n\n let raw_cmp = unsafe { creachadair_imath_sys::mp_int_compare_value(self_raw, value) };\n\n\n\n raw_cmp.cmp(&0)\n\n }\n\n\n\n #[allow(dead_code)]\n\n pub(crate) fn compare_c_ulong(&self, value: impl Into<c_ulong>) -> Ordering {\n\n let self_raw = self.as_raw();\n\n let value = value.into();\n\n\n\n // This is safe bc both self has been initialized correctly\n\n let raw_cmp = unsafe { creachadair_imath_sys::mp_int_compare_uvalue(self_raw, value) };\n\n\n\n raw_cmp.cmp(&0)\n\n }\n\n\n\n pub(crate) fn try_into_c_long(&self) -> Result<c_long> {\n", "file_path": "src/integer.rs", "rank": 64, "score": 36992.255332297325 }, { "content": "}\n\n\n\npub(crate) mod helpers {\n\n use crate::{error::Error, integer::Integer};\n\n use core::convert::TryInto;\n\n use std::os::raw::c_long;\n\n\n\n #[inline]\n\n pub fn reverse_add_c_long(other: impl Into<c_long>, integer: &Integer) -> Integer {\n\n Integer::add_c_long(integer, other)\n\n }\n\n\n\n #[inline]\n\n pub fn reverse_add_assign(integer: &Integer, other: &mut Integer) {\n\n Integer::add_assign(other, integer);\n\n }\n\n\n\n #[inline]\n\n pub fn reverse_add_c_long_assign(other: impl Into<c_long>, integer: &mut Integer) {\n\n Integer::add_c_long_assign(integer, other);\n", "file_path": "src/integer/ops.rs", "rank": 84, "score": 35341.92442693396 }, { "content": " }\n\n };\n\n}\n\n\n\nimpl_partial_ord!(Integer, Integer::compare);\n\nimpl_partial_ord!(u8, Integer::compare_c_long, deref rhs);\n\nimpl_partial_ord!(i8, Integer::compare_c_long, deref rhs);\n\nimpl_partial_ord!(u16, Integer::compare_c_long, deref rhs);\n\nimpl_partial_ord!(i16, Integer::compare_c_long, deref rhs);\n\nimpl_partial_ord!(i32, Integer::compare_c_long, deref rhs);\n\ncfg_if::cfg_if! {\n\n if #[cfg(all(target_pointer_width = \"64\", not(windows)))] {\n\n impl_partial_ord!(u32, Integer::compare_c_long, deref rhs);\n\n impl_partial_ord!(i64, Integer::compare_c_long, deref rhs);\n\n } else {\n\n impl_partial_ord!(u32, Integer::compare, into rhs);\n\n impl_partial_ord!(i64, Integer::compare, into rhs);\n\n }\n\n}\n\nimpl_partial_ord!(u64, Integer::compare, into rhs);\n", "file_path": "src/integer/comparison.rs", "rank": 85, "score": 35340.62882054609 }, { "content": "\n\nimpl_partial_eq!(Integer, Integer::compare);\n\nimpl_partial_eq!(u8, Integer::compare_c_long, deref rhs);\n\nimpl_partial_eq!(i8, Integer::compare_c_long, deref rhs);\n\nimpl_partial_eq!(u16, Integer::compare_c_long, deref rhs);\n\nimpl_partial_eq!(i16, Integer::compare_c_long, deref rhs);\n\nimpl_partial_eq!(i32, Integer::compare_c_long, deref rhs);\n\ncfg_if::cfg_if! {\n\n if #[cfg(all(target_pointer_width = \"64\", not(windows)))] {\n\n impl_partial_eq!(u32, Integer::compare_c_long, deref rhs);\n\n impl_partial_eq!(i64, Integer::compare_c_long, deref rhs);\n\n } else {\n\n impl_partial_eq!(u32, Integer::compare, into rhs);\n\n impl_partial_eq!(i64, Integer::compare, into rhs);\n\n }\n\n}\n\nimpl_partial_eq!(u64, Integer::compare, into rhs);\n\nimpl_partial_eq!(i128, Integer::compare, into rhs);\n\nimpl_partial_eq!(u128, Integer::compare, into rhs);\n\n\n", "file_path": "src/integer/comparison.rs", "rank": 86, "score": 35340.2588666505 }, { "content": "impl_partial_ord!(i128, Integer::compare, into rhs);\n\nimpl_partial_ord!(u128, Integer::compare, into rhs);\n\n\n\nimpl Ord for Integer {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n Integer::compare(self, other)\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 compare_integers() {\n\n let a = Integer::from_c_long(50505);\n\n let b = Integer::from_c_long(5050);\n\n\n\n assert_eq!(a.cmp(&b), Ordering::Greater);\n\n assert_eq!(a.cmp(&a), Ordering::Equal);\n", "file_path": "src/integer/comparison.rs", "rank": 87, "score": 35339.89415227785 }, { "content": " result\n\n .try_into()\n\n .map_err(|_| Error::RemainderOutsideBounds)\n\n .unwrap()\n\n }\n\n\n\n pub(crate) fn remainder_c_long_assign(&mut self, value: impl Into<c_long>) {\n\n let remainder_raw = self.as_raw();\n\n\n\n Integer::mp_int_div(\n\n self,\n\n &Integer::from(value.into()),\n\n ptr::null_mut(),\n\n remainder_raw,\n\n );\n\n }\n\n}\n\n\n\nimpl Sum for Integer {\n\n fn sum<I: Iterator<Item = Integer>>(iter: I) -> Self {\n", "file_path": "src/integer/ops.rs", "rank": 88, "score": 35339.387963700196 }, { "content": "use crate::integer::Integer;\n\nuse core::cmp::Ordering;\n\n\n\nmacro_rules! impl_partial_eq {\n\n ($rhs:ty, $func:path) => {\n\n impl PartialEq<$rhs> for Integer {\n\n fn eq(&self, other: &$rhs) -> bool {\n\n $func(&self, other) == Ordering::Equal\n\n }\n\n }\n\n };\n\n ($rhs:ty, $func:path, deref rhs) => {\n\n impl PartialEq<$rhs> for Integer {\n\n fn eq(&self, other: &$rhs) -> bool {\n\n $func(&self, *other) == Ordering::Equal\n\n }\n\n }\n\n\n\n impl PartialEq<Integer> for $rhs {\n\n fn eq(&self, other: &Integer) -> bool {\n", "file_path": "src/integer/comparison.rs", "rank": 89, "score": 35338.82465158042 }, { "content": "use crate::{error::Error, integer::Integer};\n\nuse core::{\n\n convert::TryInto,\n\n iter::{Product, Sum},\n\n ptr,\n\n};\n\nuse std::os::raw::c_long;\n\n\n\nmod addition;\n\nmod addition_assign;\n\nmod division;\n\nmod division_assign;\n\nmod multiplication;\n\nmod multiplication_assign;\n\nmod negation;\n\nmod remainder;\n\nmod remainder_assign;\n\nmod subtraction;\n\nmod subtraction_assign;\n\n\n", "file_path": "src/integer/ops.rs", "rank": 90, "score": 35338.52390184686 }, { "content": " let mut s = Integer::from(0);\n\n\n\n for v in iter {\n\n s += v;\n\n }\n\n\n\n s\n\n }\n\n}\n\n\n\nimpl Product for Integer {\n\n fn product<I: Iterator<Item = Integer>>(iter: I) -> Self {\n\n let mut s = Integer::from(1);\n\n\n\n for v in iter {\n\n s *= v;\n\n }\n\n\n\n s\n\n }\n", "file_path": "src/integer/ops.rs", "rank": 91, "score": 35338.19261001077 }, { "content": " {\n\n let mut lhs = Integer::from(*value);\n\n\n\n Integer::remainder_assign(&mut lhs, integer);\n\n\n\n *value = lhs\n\n .try_into()\n\n .map_err(|_| Error::RemainderOutsideBounds)\n\n .unwrap();\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n fn fibonacci(mut n: usize) -> Integer {\n\n let mut f0 = Integer::new();\n\n let mut f1 = Integer::from(1);\n\n\n", "file_path": "src/integer/ops.rs", "rank": 92, "score": 35337.68610260606 }, { "content": " Integer::mp_int_div_value(self, value.into(), quotient_raw, &mut remainder);\n\n\n\n // This should not panic bc the modulo operation will always return within the\n\n // range [0, value].\n\n (\n\n quotient,\n\n remainder\n\n .try_into()\n\n .map_err(|_| Error::RemainderOutsideBounds)\n\n .unwrap(),\n\n )\n\n }\n\n\n\n pub(crate) fn divide_c_long(&self, value: impl Into<c_long>) -> Self {\n\n let quotient = Integer::new();\n\n let quotient_raw = quotient.as_raw();\n\n\n\n Integer::mp_int_div_value(self, value, quotient_raw, ptr::null_mut());\n\n\n\n quotient\n", "file_path": "src/integer/ops.rs", "rank": 93, "score": 35336.8771016645 }, { "content": "\n\n a /= a.clone();\n\n assert_eq!(a, 1);\n\n }\n\n\n\n #[test]\n\n fn remainder_integers() {\n\n let a: Integer = \"52384129912341238437480192384\".parse().unwrap();\n\n\n\n let res_u8: u8 = &a % 122u8;\n\n assert_eq!(res_u8, 62);\n\n\n\n let res_u16: u16 = &a % 60_000u16;\n\n assert_eq!(res_u16, 12384);\n\n\n\n let res_u32: i32 = &a % 127_384i32;\n\n assert_eq!(res_u32, 85248);\n\n }\n\n\n\n #[test]\n", "file_path": "src/integer/ops.rs", "rank": 94, "score": 35335.92449943964 }, { "content": "impl Integer {\n\n /// Add two integers and return the result\n\n pub fn add(&self, other: &Self) -> Self {\n\n let self_raw = self.as_raw();\n\n let other_raw = other.as_raw();\n\n\n\n let result_int = Integer::new();\n\n let result_raw = result_int.as_raw();\n\n\n\n // This operation is safe bc `self`, `other`, and `result` have all been\n\n // initialized. `result` does not necessarily need to be initialized.\n\n let op_res = unsafe { creachadair_imath_sys::mp_int_add(self_raw, other_raw, result_raw) };\n\n\n\n imath_check_panic!(op_res, \"Operation failed!\");\n\n\n\n result_int\n\n }\n\n\n\n /// Add two integers and assign the result to self\n\n pub fn add_assign(&mut self, other: &Self) {\n", "file_path": "src/integer/ops.rs", "rank": 95, "score": 35335.8837111102 }, { "content": " .map_err(|_| Error::RemainderOutsideBounds)\n\n .unwrap()\n\n }\n\n\n\n #[inline]\n\n pub fn remainder_ref<V>(integer: &Integer, rhs: V) -> V\n\n where\n\n Integer: TryInto<V> + From<V>,\n\n {\n\n Integer::remainder(integer, &Integer::from(rhs))\n\n .try_into()\n\n .map_err(|_| Error::RemainderOutsideBounds)\n\n .unwrap()\n\n }\n\n\n\n #[inline]\n\n pub fn c_long_remainder_assign<V>(value: &mut V, integer: &Integer)\n\n where\n\n Integer: TryInto<V> + From<V>,\n\n V: Copy,\n", "file_path": "src/integer/ops.rs", "rank": 96, "score": 35335.68258760725 }, { "content": "impl Eq for Integer {}\n\n\n\nmacro_rules! impl_partial_ord {\n\n ($rhs:ty, $func:path) => {\n\n impl PartialOrd<$rhs> for Integer {\n\n fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {\n\n Some($func(self, other))\n\n }\n\n }\n\n };\n\n ($rhs:ty, $func:path, deref rhs) => {\n\n impl PartialOrd<$rhs> for Integer {\n\n fn partial_cmp(&self, other: &$rhs) -> Option<Ordering> {\n\n Some($func(self, *other))\n\n }\n\n }\n\n\n\n impl PartialOrd<Integer> for $rhs {\n\n fn partial_cmp(&self, other: &Integer) -> Option<Ordering> {\n\n // This implies that:\n", "file_path": "src/integer/comparison.rs", "rank": 97, "score": 35335.39228668628 }, { "content": "\n\n result_int\n\n }\n\n\n\n pub(crate) fn add_c_long_assign(&mut self, other: impl Into<c_long>) {\n\n let self_raw = self.as_raw();\n\n\n\n // This operation is safe because `self` has been initialized and the result\n\n // pointer is allowed to alias with the integer argument.\n\n let op_res =\n\n unsafe { creachadair_imath_sys::mp_int_add_value(self_raw, other.into(), self_raw) };\n\n\n\n imath_check_panic!(op_res, \"Operation failed!\");\n\n }\n\n\n\n /// Subtract two integers and return the result\n\n pub fn subtract(&self, other: &Self) -> Self {\n\n let self_raw = self.as_raw();\n\n let other_raw = other.as_raw();\n\n\n", "file_path": "src/integer/ops.rs", "rank": 98, "score": 35335.15075369742 }, { "content": " }\n\n\n\n #[inline]\n\n pub fn reverse_multiply_c_long(other: impl Into<c_long>, integer: &Integer) -> Integer {\n\n Integer::multiply_c_long(integer, other)\n\n }\n\n\n\n #[inline]\n\n pub fn reverse_multiply_assign(integer: &Integer, other: &mut Integer) {\n\n Integer::multiply_assign(other, integer);\n\n }\n\n\n\n #[inline]\n\n pub fn reverse_multiply_c_long_assign(other: impl Into<c_long>, integer: &mut Integer) {\n\n Integer::multiply_c_long_assign(integer, other);\n\n }\n\n\n\n #[inline]\n\n pub fn reverse_remainder<V>(value: V, integer: &Integer) -> V\n\n where\n", "file_path": "src/integer/ops.rs", "rank": 99, "score": 35335.04985143992 } ]
Rust
examples/pong.rs
legendiguess/example-rs
c401fcc7b08556cd6f5bae71986b727ffced6578
use ggez::{ event::{self, EventHandler, KeyCode, KeyMods}, graphics::{self, DrawMode, DrawParam, FilterMode, Mesh, MeshBuilder, Rect, Text}, nalgebra as na, Context, ContextBuilder, GameResult, }; use mun_examples::marshal_vec2; use mun_runtime::{invoke_fn, RetryResultExt, Runtime, RuntimeBuilder, StructRef}; use rand::Rng; use std::{cell::RefCell, rc::Rc}; extern "C" fn rand_f32() -> f32 { let mut rng = rand::thread_rng(); rng.gen() } fn main() { let (mut ctx, mut event_loop) = ContextBuilder::new("Pong", "Mun Team") .build() .expect("Failed to initialize ggez"); let runtime = RuntimeBuilder::new("pong.munlib") .insert_fn("rand_f32", rand_f32 as extern "C" fn() -> f32) .spawn() .expect("Failed to load munlib"); let state: StructRef = invoke_fn!(runtime, "new_state").wait(); let mut pong = PongGame { runtime, state }; match event::run(&mut ctx, &mut event_loop, &mut pong) { Ok(_) => (), Err(e) => println!("Error occurred: {}", e), } } struct PongGame { runtime: Rc<RefCell<Runtime>>, state: StructRef, } impl EventHandler for PongGame { fn key_down_event( &mut self, ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, ) { match keycode { KeyCode::W => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_up", true).unwrap(); } KeyCode::S => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_down", true).unwrap(); } KeyCode::Up => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_up", true).unwrap(); } KeyCode::Down => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_down", true).unwrap(); } KeyCode::Escape => { event::quit(ctx); } _ => (), } } fn key_up_event(&mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods) { match keycode { KeyCode::W => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_up", false).unwrap(); } KeyCode::S => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_down", false).unwrap(); } KeyCode::Up => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_up", false).unwrap(); } KeyCode::Down => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_down", false).unwrap(); } _ => (), } } fn update(&mut self, _ctx: &mut ggez::Context) -> ggez::GameResult { let _: () = invoke_fn!(self.runtime, "update", self.state.clone()).wait(); self.runtime.borrow_mut().update(); Ok(()) } fn draw(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult { graphics::clear(ctx, graphics::BLACK); let ball = self.state.get::<StructRef>("ball").unwrap(); let paddle_left = self.state.get::<StructRef>("paddle_left").unwrap(); let paddle_right = self.state.get::<StructRef>("paddle_right").unwrap(); let ball_mesh = MeshBuilder::new() .circle( DrawMode::fill(), na::Point2::origin(), invoke_fn!(self.runtime, "ball_radius").unwrap(), invoke_fn!(self.runtime, "ball_tolerance").unwrap(), graphics::WHITE, ) .build(ctx)?; draw_mesh(ctx, &ball_mesh, &ball)?; let paddle_mesh = MeshBuilder::new() .rectangle( DrawMode::fill(), bounds( invoke_fn!(self.runtime, "paddle_width").unwrap(), invoke_fn!(self.runtime, "paddle_height").unwrap(), ), graphics::WHITE, ) .build(ctx)?; draw_mesh(ctx, &paddle_mesh, &paddle_left)?; draw_mesh(ctx, &paddle_mesh, &paddle_right)?; queue_score_text( ctx, &paddle_left, marshal_vec2(&invoke_fn!(self.runtime, "left_score_pos").unwrap()), ); queue_score_text( ctx, &paddle_right, marshal_vec2(&invoke_fn!(self.runtime, "right_score_pos").unwrap()), ); graphics::draw_queued_text(ctx, DrawParam::default(), None, FilterMode::Linear)?; graphics::present(ctx)?; Ok(()) } } fn bounds(width: f32, height: f32) -> Rect { Rect::new(0.0, 0.0, width, height) } fn draw_mesh(ctx: &mut Context, mesh: &Mesh, object: &StructRef) -> GameResult { graphics::draw( ctx, mesh, ( marshal_vec2(&object.get("pos").unwrap()), 0.0, graphics::WHITE, ), ) } fn queue_score_text(ctx: &mut Context, paddle: &StructRef, score_pos: na::Point2<f32>) { let score = paddle.get::<u32>("score").unwrap(); let score_text = Text::new(score.to_string()); graphics::queue_text(ctx, &score_text, score_pos, Some(graphics::WHITE)); }
use ggez::{ event::{self, EventHandler, KeyCode, KeyMods}, graphics::{self, DrawMode, DrawParam, FilterMode, Mesh, MeshBuilder, Rect, Text}, nalgebra as na, Context, ContextBuilder, GameResult, }; use mun_examples::marshal_vec2; use mun_runtime::{invoke_fn, RetryResultExt, Runtime, RuntimeBuilder, StructRef}; use rand::Rng; use std::{cell::RefCell, rc::Rc}; extern "C" fn rand_f32() -> f32 { let mut rng = rand::thread_rng(); rng.gen() } fn main() { let (mut ctx, mut event_loop) = ContextBuilder::new("Pong", "Mun Team") .build() .expect("Failed to initialize ggez"); let runtime = RuntimeBuilder::new("pong.munlib") .insert_fn("rand_f32", rand_f32 as extern "C" fn() -> f32) .spawn() .expect("Failed to load munlib"); let state: StructRef = invoke_fn!(runtime, "new_state").wait(); let mut pong = PongGame { runtime, state }; match event::run(&mut ctx, &mut event_loop, &mut pong) { Ok(_) => (), Err(e) => println!("Error occurred: {}", e), } } struct PongGame { runtime: Rc<RefCell<Runtime>>, state: StructRef, } impl EventHandler for PongGame { fn key_down_event( &mut self, ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, ) { match keycode { KeyCode::W => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_up", true).unwrap(); } KeyCode::S => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_down", true).unwrap(); } KeyCode::Up => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_up", true).unwrap(); } KeyCode::Down => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_down", true).unwrap(); } KeyCode::Escape => { event::quit(ctx); } _ => (), } } fn key_up_event(&mut self, _ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods) { match keycode { KeyCode::W => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_up", false).unwrap(); } KeyCode::S => { let mut paddle = self.state.get::<StructRef>("paddle_left").unwrap(); paddle.set("move_down", false).unwrap(); } KeyCode::Up => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_up", false).unwrap(); } KeyCode::Down => { let mut paddle = self.state.get::<StructRef>("paddle_right").unwrap(); paddle.set("move_down", false).unwrap(); } _ => (), } } fn update(&mut self, _ctx: &mut ggez::Context) -> ggez::GameResult { let _: () = invoke_fn!(self.runtime, "update", self.state.clone()).wait(); self.runtime.borrow_mut().update(); Ok(()) } fn draw(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult { graphics::clear(ctx, graphics::BLACK); let ball = self.state.get::<StructRef>("ball").unwrap(); let paddle_left = self.state.get::<StructRef>("paddle_left").unwrap(); let paddle_right = self.state.get::<StructRef>("paddle_right").unwrap(); let ball_mesh = MeshBuilder::ne
} fn bounds(width: f32, height: f32) -> Rect { Rect::new(0.0, 0.0, width, height) } fn draw_mesh(ctx: &mut Context, mesh: &Mesh, object: &StructRef) -> GameResult { graphics::draw( ctx, mesh, ( marshal_vec2(&object.get("pos").unwrap()), 0.0, graphics::WHITE, ), ) } fn queue_score_text(ctx: &mut Context, paddle: &StructRef, score_pos: na::Point2<f32>) { let score = paddle.get::<u32>("score").unwrap(); let score_text = Text::new(score.to_string()); graphics::queue_text(ctx, &score_text, score_pos, Some(graphics::WHITE)); }
w() .circle( DrawMode::fill(), na::Point2::origin(), invoke_fn!(self.runtime, "ball_radius").unwrap(), invoke_fn!(self.runtime, "ball_tolerance").unwrap(), graphics::WHITE, ) .build(ctx)?; draw_mesh(ctx, &ball_mesh, &ball)?; let paddle_mesh = MeshBuilder::new() .rectangle( DrawMode::fill(), bounds( invoke_fn!(self.runtime, "paddle_width").unwrap(), invoke_fn!(self.runtime, "paddle_height").unwrap(), ), graphics::WHITE, ) .build(ctx)?; draw_mesh(ctx, &paddle_mesh, &paddle_left)?; draw_mesh(ctx, &paddle_mesh, &paddle_right)?; queue_score_text( ctx, &paddle_left, marshal_vec2(&invoke_fn!(self.runtime, "left_score_pos").unwrap()), ); queue_score_text( ctx, &paddle_right, marshal_vec2(&invoke_fn!(self.runtime, "right_score_pos").unwrap()), ); graphics::draw_queued_text(ctx, DrawParam::default(), None, FilterMode::Linear)?; graphics::present(ctx)?; Ok(()) }
function_block-function_prefixed
[ { "content": "fn textures(ctx: &mut Context) -> [(Texture, Vec2<f32>); 5] {\n\n [\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/spaceship.png\").unwrap(),\n\n Vec2::new(6., 7.),\n\n ),\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/rocket.png\").unwrap(),\n\n Vec2::new(3., 3.),\n\n ),\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/asteroid_size_1.png\").unwrap(),\n\n Vec2::new(5.0, 5.0),\n\n ),\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/asteroid_size_2.png\").unwrap(),\n\n Vec2::new(8.0, 8.0),\n\n ),\n\n (\n\n Texture::new(ctx, \"./assets/spaceship/sprites/asteroid_size_3.png\").unwrap(),\n\n Vec2::new(15.0, 15.0),\n\n ),\n\n ]\n\n}\n\n\n", "file_path": "examples/spaceship.rs", "rank": 2, "score": 107003.97611925183 }, { "content": "fn new_asteroids(mun_runtime: &Rc<RefCell<mun_runtime::Runtime>>) -> Vec<StructRef> {\n\n let mut asteroids = Vec::new();\n\n for _ in 0..invoke_fn!(mun_runtime, \"initial_asteroids_amount\").unwrap() {\n\n let position: (f32, f32) = {\n\n if thread_rng().gen_range(0, 1) == 0 {\n\n (0.0, thread_rng().gen_range(0.0, game_area_height()))\n\n } else {\n\n (0.0, thread_rng().gen_range(game_area_width(), 0.0))\n\n }\n\n };\n\n\n\n let asteroid_position: StructRef =\n\n invoke_fn!(mun_runtime, \"new_vec2\", position.0, position.1).unwrap();\n\n\n\n asteroids.push(\n\n invoke_fn!(\n\n mun_runtime,\n\n \"new_asteroid\",\n\n asteroid_position,\n\n thread_rng().gen_range(0.0_f32, 360.0_f32),\n\n 3_u8\n\n )\n\n .unwrap(),\n\n );\n\n }\n\n asteroids\n\n}\n\n\n", "file_path": "examples/spaceship.rs", "rank": 5, "score": 70750.25013838394 }, { "content": "pub fn marshal_vec2(pos: &StructRef) -> Point2<f32> {\n\n Point2::new(pos.get(\"x\").unwrap(), pos.get(\"y\").unwrap())\n\n}\n", "file_path": "src/lib.rs", "rank": 6, "score": 63122.81583835998 }, { "content": "fn main() -> tetra::Result {\n\n let runtime = RuntimeBuilder::new(\"spaceship.munlib\")\n\n .insert_fn(\"sin\", sin as extern \"C\" fn(number: f32) -> f32)\n\n .insert_fn(\"cos\", cos as extern \"C\" fn(number: f32) -> f32)\n\n .insert_fn(\"dbg\", dbg as extern \"C\" fn(number: f32))\n\n .insert_fn(\n\n \"degrees_to_radians\",\n\n degrees_to_radians as extern \"C\" fn(degrees: f32) -> f32,\n\n )\n\n .insert_fn(\"sqrt\", sqrt as extern \"C\" fn(value: f32) -> f32)\n\n .insert_fn(\"game_area_width\", game_area_width as extern \"C\" fn() -> f32)\n\n .insert_fn(\n\n \"game_area_height\",\n\n game_area_height as extern \"C\" fn() -> f32,\n\n )\n\n .spawn()\n\n .expect(\"Failed to spawn Runtime\");\n\n\n\n let game_struct = invoke_fn!(runtime, \"new_game_struct\").unwrap();\n\n\n", "file_path": "examples/spaceship.rs", "rank": 7, "score": 53322.96638190703 }, { "content": "struct SpaceshipGame {\n\n mun_runtime: Rc<RefCell<mun_runtime::Runtime>>,\n\n asteroids: Vec<StructRef>,\n\n rockets: Vec<StructRef>,\n\n textures: [(Texture, Vec2<f32>); 5],\n\n scaler: ScreenScaler,\n\n game_struct: StructRef,\n\n player_input: StructRef,\n\n font: Font,\n\n score: u8,\n\n}\n\n\n\nimpl State for SpaceshipGame {\n\n fn draw(&mut self, ctx: &mut Context) -> tetra::Result {\n\n graphics::set_canvas(ctx, self.scaler.canvas());\n\n\n\n graphics::clear(ctx, Color::BLACK);\n\n\n\n let spaceship_object: StructRef = self\n\n .game_struct\n", "file_path": "examples/spaceship.rs", "rank": 9, "score": 31897.971997761815 }, { "content": "# Mun Example Suite\n\n\n\nA collection of Rust-powered Mun example games to showcase its hot reloading functionality.\n\n\n\n## Pong (est. 1972) since Mun v0.2.1\n\n\n\n![](images/pong.png)\n\n\n\n## Spaceship (Asteroids-like game) since Mun v0.2.1\n\n\n\n![](images/spaceship.png)\n\n\n\n## License\n\n\n\nThe Mun Example Suite is licensed under either of\n\n\n\n * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or\n\n http://www.apache.org/licenses/LICENSE-2.0)\n\n * MIT license ([LICENSE-MIT](LICENSE-MIT) or\n\n http://opensource.org/licenses/MIT)\n\n\n\n at your option.\n", "file_path": "README.md", "rank": 16, "score": 11016.043099728087 }, { "content": "use tetra::graphics::{self, Color, DrawParams, Texture};\n\nuse tetra::math::Vec2;\n\nuse tetra::{Context, ContextBuilder, State};\n\n\n\nuse tetra::graphics::scaling::{ScalingMode, ScreenScaler};\n\n\n\nuse tetra::graphics::text::{Font, Text};\n\n\n\nuse tetra::input::{self, Key};\n\n\n\nuse mun_runtime::{invoke_fn, RetryResultExt, RuntimeBuilder, StructRef};\n\n\n\nuse std::cell::RefCell;\n\nuse std::rc::Rc;\n\n\n\nuse rand::prelude::*;\n\n\n\nextern \"C\" fn sin(number: f32) -> f32 {\n\n number.sin()\n\n}\n", "file_path": "examples/spaceship.rs", "rank": 17, "score": 12.499101093653001 }, { "content": " self.score = 0;\n\n }\n\n }\n\n\n\n if self.asteroids.is_empty() {\n\n self.game_struct.set(\"spawn_new_asteroids\", true).unwrap();\n\n }\n\n\n\n let _: () = invoke_fn!(\n\n self.mun_runtime,\n\n \"update\",\n\n self.game_struct.clone(),\n\n self.player_input.clone()\n\n )\n\n .wait();\n\n\n\n self.mun_runtime.borrow_mut().update();\n\n\n\n self.player_input = invoke_fn!(self.mun_runtime, \"new_player_input\").unwrap();\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "examples/spaceship.rs", "rank": 18, "score": 11.061744671430086 }, { "content": "use ggez::nalgebra::Point2;\n\nuse mun_runtime::StructRef;\n\n\n", "file_path": "src/lib.rs", "rank": 19, "score": 10.76314928098374 }, { "content": " \"new_rocket\",\n\n spaceship_positon,\n\n spaceship_object.get::<f32>(\"angle\").unwrap()\n\n )\n\n .unwrap();\n\n\n\n self.rockets.push(new_bullet);\n\n }\n\n }\n\n\n\n if self.game_struct.get::<bool>(\"spawn_new_asteroids\").unwrap() {\n\n self.game_struct.set(\"spawn_new_asteroids\", false).unwrap();\n\n\n\n self.asteroids = new_asteroids(&self.mun_runtime);\n\n }\n\n\n\n // Rockets update\n\n for index in 0..self.rockets.len() {\n\n let _: () = invoke_fn!(\n\n self.mun_runtime,\n", "file_path": "examples/spaceship.rs", "rank": 20, "score": 9.628838831346192 }, { "content": " // Draw score\n\n graphics::draw(\n\n ctx,\n\n &Text::new(format!(\"Score {}\", self.score), self.font.clone()),\n\n Vec2::new(10., 10.),\n\n );\n\n\n\n Ok(())\n\n }\n\n\n\n fn update(&mut self, ctx: &mut Context) -> tetra::Result {\n\n // Collect input to pass it into mun runtime\n\n if input::is_key_down(ctx, Key::Left) {\n\n self.player_input.set(\"left\", true).unwrap();\n\n }\n\n if input::is_key_down(ctx, Key::Right) {\n\n self.player_input.set(\"right\", true).unwrap();\n\n }\n\n if input::is_key_down(ctx, Key::Up) {\n\n self.player_input.set(\"up\", true).unwrap();\n", "file_path": "examples/spaceship.rs", "rank": 21, "score": 8.683158200579467 }, { "content": " invoke_fn!(\n\n self.mun_runtime,\n\n \"new_asteroid\",\n\n asteroid_object.get::<StructRef>(\"position\").unwrap(),\n\n thread_rng().gen_range(0.0_f32, 360.0_f32),\n\n asteroid.get::<u8>(\"size\").unwrap() - 1\n\n )\n\n .unwrap(),\n\n );\n\n }\n\n false\n\n } else {\n\n true\n\n }\n\n });\n\n\n\n asteroids.append(&mut new_asteroids);\n\n\n\n self.asteroids = asteroids;\n\n\n", "file_path": "examples/spaceship.rs", "rank": 22, "score": 8.184376259319103 }, { "content": " let player_input: StructRef = invoke_fn!(runtime, \"new_player_input\").unwrap();\n\n\n\n ContextBuilder::new(\"Spaceship Game\", 1280, 720)\n\n .build()?\n\n .run(|ctx| {\n\n Ok(SpaceshipGame {\n\n mun_runtime: runtime,\n\n asteroids: Vec::new(),\n\n rockets: Vec::new(),\n\n scaler: ScreenScaler::with_window_size(\n\n ctx,\n\n game_area_width() as i32,\n\n game_area_height() as i32,\n\n ScalingMode::ShowAllPixelPerfect,\n\n )?,\n\n textures: textures(ctx),\n\n game_struct: game_struct,\n\n player_input: player_input,\n\n font: Font::vector(ctx, \"./assets/spaceship/fonts/Minimal3x5.ttf\", 18.0).unwrap(),\n\n score: 0,\n\n })\n\n })\n\n}\n", "file_path": "examples/spaceship.rs", "rank": 23, "score": 8.032900037024188 }, { "content": " }\n\n if input::is_key_down(ctx, Key::Z) {\n\n self.player_input.set(\"shoot\", true).unwrap();\n\n }\n\n\n\n if self.game_struct.get::<bool>(\"spawn_new_rocket\").unwrap() {\n\n self.game_struct.set(\"spawn_new_rocket\", false).unwrap();\n\n\n\n if !(self.rockets.len() >= invoke_fn!(self.mun_runtime, \"max_rockets_amount\").unwrap())\n\n {\n\n let spaceship_object: StructRef = self\n\n .game_struct\n\n .get::<StructRef>(\"spaceship\")\n\n .unwrap()\n\n .get::<StructRef>(\"object\")\n\n .unwrap();\n\n let spaceship_positon = spaceship_object.get::<StructRef>(\"position\").unwrap();\n\n\n\n let new_bullet: StructRef = invoke_fn!(\n\n self.mun_runtime,\n", "file_path": "examples/spaceship.rs", "rank": 24, "score": 7.938694993952105 }, { "content": " \"update_rocket\",\n\n self.rockets[index].clone()\n\n )\n\n .unwrap();\n\n }\n\n // Delete rockets\n\n self.rockets\n\n .retain(|rocket| !rocket.get::<bool>(\"need_to_destroy\").unwrap());\n\n\n\n // Asteroids update\n\n for index in 0..self.asteroids.len() {\n\n let _: () = invoke_fn!(\n\n self.mun_runtime,\n\n \"update_asteroid\",\n\n self.asteroids[index].clone()\n\n )\n\n .unwrap();\n\n }\n\n\n\n let mut new_asteroids: Vec<StructRef> = Vec::new();\n", "file_path": "examples/spaceship.rs", "rank": 25, "score": 7.929001956251581 }, { "content": "\n\n let mut asteroids = self.asteroids.clone();\n\n\n\n asteroids.retain(|asteroid| {\n\n if asteroid.get::<bool>(\"need_to_destroy\").unwrap() {\n\n if asteroid.get::<u8>(\"size\").unwrap() > 1 {\n\n let asteroid_object = asteroid.get::<StructRef>(\"object\").unwrap();\n\n\n\n new_asteroids.push(\n\n invoke_fn!(\n\n self.mun_runtime,\n\n \"new_asteroid\",\n\n asteroid_object.get::<StructRef>(\"position\").unwrap(),\n\n thread_rng().gen_range(0.0_f32, 360.0_f32),\n\n asteroid.get::<u8>(\"size\").unwrap() - 1\n\n )\n\n .unwrap(),\n\n );\n\n\n\n new_asteroids.push(\n", "file_path": "examples/spaceship.rs", "rank": 26, "score": 7.770418582426313 }, { "content": "\n\nextern \"C\" fn cos(number: f32) -> f32 {\n\n number.cos()\n\n}\n\n\n\nextern \"C\" fn dbg(number: f32) {\n\n dbg!(number);\n\n}\n\n\n\nextern \"C\" fn degrees_to_radians(degrees: f32) -> f32 {\n\n degrees.to_radians()\n\n}\n\n\n\nextern \"C\" fn sqrt(value: f32) -> f32 {\n\n value.sqrt()\n\n}\n\n\n\nextern \"C\" fn game_area_width() -> f32 {\n\n 128.0 * 5.0\n\n}\n\n\n\nextern \"C\" fn game_area_height() -> f32 {\n\n 72.0 * 5.0\n\n}\n\n\n", "file_path": "examples/spaceship.rs", "rank": 27, "score": 7.3566395310506385 }, { "content": " for asteroid in self.asteroids.iter() {\n\n let collide: bool = invoke_fn!(\n\n self.mun_runtime,\n\n \"object_collide\",\n\n self.game_struct\n\n .get::<StructRef>(\"spaceship\")\n\n .unwrap()\n\n .get::<StructRef>(\"object\")\n\n .unwrap(),\n\n asteroid.get::<StructRef>(\"object\").clone().unwrap()\n\n )\n\n .unwrap();\n\n\n\n if collide {\n\n self.game_struct\n\n .set(\"token\", rand::thread_rng().gen::<u8>())\n\n .unwrap();\n\n\n\n self.rockets.clear();\n\n\n", "file_path": "examples/spaceship.rs", "rank": 28, "score": 6.776660803740606 }, { "content": " // Asteroids and rocket collision\n\n for rocket in self.rockets.iter_mut() {\n\n for asteroid in self.asteroids.iter_mut() {\n\n let collide: bool = invoke_fn!(\n\n self.mun_runtime,\n\n \"object_collide\",\n\n rocket.get::<StructRef>(\"object\").clone().unwrap(),\n\n asteroid.get::<StructRef>(\"object\").clone().unwrap()\n\n )\n\n .unwrap();\n\n\n\n if collide {\n\n self.score += 1;\n\n rocket.set(\"need_to_destroy\", true).unwrap();\n\n asteroid.set(\"need_to_destroy\", true).unwrap();\n\n }\n\n }\n\n }\n\n\n\n // Asteroids and spaceship collision\n", "file_path": "examples/spaceship.rs", "rank": 29, "score": 6.24110504827606 }, { "content": " let asteroid_position = asteroid_object.get::<StructRef>(\"position\").unwrap();\n\n let asteroid_size: usize = asteroid.get::<u8>(\"size\").unwrap().into();\n\n\n\n graphics::draw(\n\n ctx,\n\n &self.textures[asteroid_size + 1].0,\n\n DrawParams::new()\n\n .position(Vec2::new(\n\n asteroid_position.get(\"x\").unwrap(),\n\n asteroid_position.get(\"y\").unwrap(),\n\n ))\n\n .origin(self.textures[asteroid_size + 1].1)\n\n .rotation(asteroid_object.get::<f32>(\"angle\").unwrap().to_radians()),\n\n );\n\n }\n\n\n\n graphics::reset_canvas(ctx);\n\n\n\n graphics::draw(ctx, &self.scaler, Vec2::new(0., 0.));\n\n\n", "file_path": "examples/spaceship.rs", "rank": 30, "score": 3.170292312332915 }, { "content": " .rotation(rocket_object.get::<f32>(\"angle\").unwrap().to_radians()),\n\n );\n\n }\n\n\n\n // Draw spaceship\n\n graphics::draw(\n\n ctx,\n\n &self.textures[0].0,\n\n DrawParams::new()\n\n .position(Vec2::new(\n\n spaceship_object_position.get(\"x\").unwrap(),\n\n spaceship_object_position.get(\"y\").unwrap(),\n\n ))\n\n .origin(self.textures[0].1)\n\n .rotation(spaceship_object.get::<f32>(\"angle\").unwrap().to_radians()),\n\n );\n\n\n\n // Draw asteroids\n\n for asteroid in self.asteroids.iter() {\n\n let asteroid_object = asteroid.get::<StructRef>(\"object\").unwrap();\n", "file_path": "examples/spaceship.rs", "rank": 31, "score": 3.1196793339556903 }, { "content": " .get::<StructRef>(\"spaceship\")\n\n .unwrap()\n\n .get::<StructRef>(\"object\")\n\n .unwrap();\n\n let spaceship_object_position = spaceship_object.get::<StructRef>(\"position\").unwrap();\n\n\n\n // Draw rockets\n\n for rocket in self.rockets.iter() {\n\n let rocket_object = rocket.get::<StructRef>(\"object\").unwrap();\n\n let rocket_position = rocket_object.get::<StructRef>(\"position\").unwrap();\n\n\n\n graphics::draw(\n\n ctx,\n\n &self.textures[1].0,\n\n DrawParams::new()\n\n .position(Vec2::new(\n\n rocket_position.get(\"x\").unwrap(),\n\n rocket_position.get(\"y\").unwrap(),\n\n ))\n\n .origin(self.textures[1].1)\n", "file_path": "examples/spaceship.rs", "rank": 32, "score": 2.3089522489270715 } ]
Rust
libzmq/src/socket/dish.rs
dmweis/libzmq-rs
8b8384c3f65960d9c842e9c8d54883239ad47d33
use crate::{ addr::Endpoint, auth::*, core::*, error::*, Ctx, CtxHandle, Group, GroupSlice, }; use libzmq_sys as sys; use sys::errno; use serde::{Deserialize, Serialize}; use std::{ ffi::c_void, str, sync::{Arc, Mutex}, }; fn join(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Error> { let rc = unsafe { sys::zmq_join(socket_mut_ptr, group.as_c_str().as_ptr()) }; if rc == -1 { let errno = unsafe { sys::zmq_errno() }; let err = match errno { errno::EINVAL => { Error::new(ErrorKind::InvalidInput("cannot join group twice")) } errno::ETERM => Error::new(ErrorKind::InvalidCtx), errno::EINTR => Error::new(ErrorKind::Interrupted), errno::ENOTSOCK => panic!("invalid socket"), errno::EMTHREAD => panic!("no i/o thread available"), _ => panic!(msg_from_errno(errno)), }; Err(err) } else { Ok(()) } } fn leave(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Error> { let rc = unsafe { sys::zmq_leave(socket_mut_ptr, group.as_c_str().as_ptr()) }; if rc == -1 { let errno = unsafe { sys::zmq_errno() }; let err = match errno { errno::EINVAL => Error::new(ErrorKind::InvalidInput( "cannot leave a group that wasn't joined", )), errno::ETERM => Error::new(ErrorKind::InvalidCtx), errno::EINTR => Error::new(ErrorKind::Interrupted), errno::ENOTSOCK => panic!("invalid socket"), errno::EMTHREAD => panic!("no i/o thread available"), _ => panic!(msg_from_errno(errno)), }; Err(err) } else { Ok(()) } } #[derive(Debug, Clone)] pub struct Dish { inner: Arc<RawSocket>, groups: Arc<Mutex<Vec<Group>>>, } impl Dish { pub fn new() -> Result<Self, Error> { let inner = Arc::new(RawSocket::new(RawSocketType::Dish)?); Ok(Self { inner, groups: Arc::default(), }) } pub fn with_ctx(handle: CtxHandle) -> Result<Self, Error> { let inner = Arc::new(RawSocket::with_ctx(RawSocketType::Dish, handle)?); Ok(Self { inner, groups: Arc::default(), }) } pub fn ctx(&self) -> CtxHandle { self.inner.ctx() } pub fn join<G>(&self, group: G) -> Result<(), Error> where G: Into<Group>, { let mut guard = self.groups.lock().unwrap(); let group = group.into(); join(self.raw_socket().as_mut_ptr(), &group)?; guard.push(group); Ok(()) } pub fn joined(&self) -> Vec<Group> { self.groups.lock().unwrap().to_owned() } pub fn leave<G>(&self, group: G) -> Result<(), Error> where G: AsRef<GroupSlice>, { let mut guard = self.groups.lock().unwrap(); let group = group.as_ref(); leave(self.raw_socket().as_mut_ptr(), group)?; let position = guard.iter().position(|g| g == group).unwrap(); guard.remove(position); Ok(()) } } impl PartialEq for Dish { fn eq(&self, other: &Dish) -> bool { self.inner == other.inner } } impl Eq for Dish {} impl GetRawSocket for Dish { fn raw_socket(&self) -> &RawSocket { &self.inner } } impl Socket for Dish {} impl RecvMsg for Dish {} unsafe impl Send for Dish {} unsafe impl Sync for Dish {} #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(from = "FlatDishConfig")] #[serde(into = "FlatDishConfig")] pub struct DishConfig { socket_config: SocketConfig, recv_config: RecvConfig, groups: Option<Vec<Group>>, } impl DishConfig { pub fn new() -> Self { Self::default() } pub fn build(&self) -> Result<Dish, Error> { self.with_ctx(Ctx::global()) } pub fn with_ctx(&self, handle: CtxHandle) -> Result<Dish, Error> { let dish = Dish::with_ctx(handle)?; self.apply(&dish)?; Ok(dish) } pub fn groups(&self) -> Option<&[Group]> { self.groups.as_deref() } pub fn set_groups<I>(&mut self, maybe_groups: Option<I>) where I: IntoIterator<Item = Group>, { let groups = maybe_groups.map(|g| g.into_iter().collect()); self.groups = groups; } pub fn apply(&self, dish: &Dish) -> Result<(), Error> { if let Some(ref groups) = self.groups { for group in groups { dish.join(group)?; } } self.recv_config.apply(dish)?; self.socket_config.apply(dish)?; Ok(()) } } #[derive(Clone, Serialize, Deserialize)] struct FlatDishConfig { connect: Option<Vec<Endpoint>>, bind: Option<Vec<Endpoint>>, recv_hwm: HighWaterMark, recv_timeout: Period, groups: Option<Vec<Group>>, mechanism: Option<Mechanism>, } impl From<DishConfig> for FlatDishConfig { fn from(config: DishConfig) -> Self { let socket_config = config.socket_config; let recv_config = config.recv_config; Self { connect: socket_config.connect, bind: socket_config.bind, mechanism: socket_config.mechanism, recv_hwm: recv_config.recv_hwm, recv_timeout: recv_config.recv_timeout, groups: config.groups, } } } impl From<FlatDishConfig> for DishConfig { fn from(flat: FlatDishConfig) -> Self { let socket_config = SocketConfig { connect: flat.connect, bind: flat.bind, mechanism: flat.mechanism, }; let recv_config = RecvConfig { recv_hwm: flat.recv_hwm, recv_timeout: flat.recv_timeout, }; Self { socket_config, recv_config, groups: flat.groups, } } } impl GetSocketConfig for DishConfig { fn socket_config(&self) -> &SocketConfig { &self.socket_config } fn socket_config_mut(&mut self) -> &mut SocketConfig { &mut self.socket_config } } impl ConfigureSocket for DishConfig {} impl GetRecvConfig for DishConfig { fn recv_config(&self) -> &RecvConfig { &self.recv_config } fn recv_config_mut(&mut self) -> &mut RecvConfig { &mut self.recv_config } } impl ConfigureRecv for DishConfig {} #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct DishBuilder { inner: DishConfig, } impl DishBuilder { pub fn new() -> Self { Self::default() } pub fn build(&self) -> Result<Dish, Error> { self.inner.build() } pub fn with_ctx(&self, handle: CtxHandle) -> Result<Dish, Error> { self.inner.with_ctx(handle) } pub fn join<I, G>(&mut self, groups: I) -> &mut Self where I: IntoIterator<Item = G>, G: Into<Group>, { let groups: Vec<Group> = groups.into_iter().map(G::into).collect(); self.inner.set_groups(Some(groups)); self } } impl GetSocketConfig for DishBuilder { fn socket_config(&self) -> &SocketConfig { self.inner.socket_config() } fn socket_config_mut(&mut self) -> &mut SocketConfig { self.inner.socket_config_mut() } } impl BuildSocket for DishBuilder {} impl GetRecvConfig for DishBuilder { fn recv_config(&self) -> &RecvConfig { self.inner.recv_config() } fn recv_config_mut(&mut self) -> &mut RecvConfig { self.inner.recv_config_mut() } } impl BuildRecv for DishBuilder {} #[cfg(test)] mod test { use super::*; #[test] fn test_ser_de() { let config = DishConfig::new(); let ron = serde_yaml::to_string(&config).unwrap(); let de: DishConfig = serde_yaml::from_str(&ron).unwrap(); assert_eq!(config, de); } #[test] fn test_dish() { use crate::{prelude::*, TcpAddr, *}; use std::{thread, time::Duration}; let addr: TcpAddr = "127.0.0.1:*".try_into().unwrap(); let radio = RadioBuilder::new().bind(addr).build().unwrap(); let bound = radio.last_endpoint().unwrap(); let a: Group = "group a".try_into().unwrap(); let dish = DishBuilder::new().connect(bound).join(&a).build().unwrap(); thread::spawn(move || { let a: Group = "group a".try_into().unwrap(); let b: Group = "group b".try_into().unwrap(); let mut count = 0; loop { let mut msg = Msg::new(); let group = if count % 2 == 0 { &a } else { &b }; msg.set_group(group); radio.send(msg).unwrap(); std::thread::sleep(Duration::from_millis(1)); count += 1; } }); let msg = dish.recv_msg().unwrap(); assert_eq!(msg.group().unwrap(), &a); let msg = dish.recv_msg().unwrap(); assert_eq!(msg.group().unwrap(), &a); } }
use crate::{ addr::Endpoint, auth::*, core::*, error::*, Ctx, CtxHandle, Group, GroupSlice, }; use libzmq_sys as sys; use sys::errno; use serde::{Deserialize, Serialize}; use std::{ ffi::c_void, str, sync::{Arc, Mutex}, }; fn join(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Error> { let rc = unsafe { sys::zmq_join(socket_mut_ptr, group.as_c_str().as_ptr()) }; if rc == -1 { let errno = unsafe { sys::zmq_errno() }; let err = match errno { errno::EINVAL => { Error::new(ErrorKind::InvalidInput("cannot join group twice")) } errno::ETERM => Error::new(ErrorKind::InvalidCtx), errno::EINTR => Error::new(ErrorKind::Interrupted), errno::ENOTSOCK => panic!("invalid socket"), errno::EMTHREAD => panic!("no i/o thread available"), _ => panic!(msg_from_errno(errno)), }; Err(err) } else { Ok(()) } } fn leave(socket_mut_ptr: *mut c_void, group: &GroupSlice) -> Result<(), Error> { let rc = unsafe { sys::zmq_leave(socket_mut_ptr, group.as_c_str().as_ptr()) }; if rc == -1 { let errno = unsafe { sys::zmq_errno() }; let err = match errno { errno::EINVAL => Error::new(ErrorKind::InvalidInput( "cannot leave a group that wasn't joined", )), errno::ETERM => Error::new(ErrorKind::InvalidCtx), errno::EINTR => Error::new(ErrorKind::Interrupted), errno::ENOTSOCK => panic!("invalid socket"), errno::EMTHREAD => panic!("no i/o thread available"), _ => panic!(msg_from_errno(errno)), }; Err(err) } else { Ok(()) } } #[derive(Debug, Clone)] pub struct Dish { inner: Arc<RawSocket>, groups: Arc<Mutex<Vec<Group>>>, } impl Dish { pub fn new() -> Result<Self, Error> { let inner = Arc::new(RawSocket::new(RawSocketType::Dish)?); Ok(Self { inner, groups: Arc::default(), }) } pub fn with_ctx(handle: CtxHandle) -> Result<Self, Error> { let inner = Arc::new(RawSocket::with_ctx(RawSocketType::Dish, handle)?); Ok(Self { inner, groups: Arc::default(), }) } pub fn ctx(&self) -> CtxHandle { self.inner.ctx() } pub fn join<G>(&self, group: G) -> Result<(), Error> where G: Into<Group>, { let mut guard = self.groups.lock().unwrap(); let group = group.into(); join(self.raw_socket().as_mut_ptr(), &group)?; guard.push(group); Ok(()) } pub fn joined(&self) -> Vec<Group> { self.groups.lock().unwrap().to_owned() } pub fn leave<G>(&self, group: G) -> Result<(), Error> where G: AsRef<GroupSlice>, { let mut guard = self.groups.lock().unwrap(); let group = group.as_ref(); leave(self.raw_socket().as_mut_ptr(), group)?; let position = guard.iter().position(|g| g == group).unwrap(); guard.remove(position); Ok(()) } } impl PartialEq for Dish { fn eq(&self, other: &Dish) -> bool { self.inner == other.inner } } impl Eq for Dish {} impl GetRawSocket for Dish { fn raw_socket(&self) -> &RawSocket { &self.inner } } impl Socket for Dish {} impl RecvMsg for Dish {} unsafe impl Send for Dish {} unsafe impl Sync for Dish {} #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(from = "FlatDishConfig")] #[serde(into = "FlatDishConfig")] pub struct DishConfig { socket_config: SocketConfig, recv_config: RecvConfig, groups: Option<Vec<Group>>, } impl DishConfig { pub fn new() -> Self { Self::default() } pub fn build(&self) -> Result<Dish, Error> { self.with_ctx(Ctx::global()) } pub f
pub fn groups(&self) -> Option<&[Group]> { self.groups.as_deref() } pub fn set_groups<I>(&mut self, maybe_groups: Option<I>) where I: IntoIterator<Item = Group>, { let groups = maybe_groups.map(|g| g.into_iter().collect()); self.groups = groups; } pub fn apply(&self, dish: &Dish) -> Result<(), Error> { if let Some(ref groups) = self.groups { for group in groups { dish.join(group)?; } } self.recv_config.apply(dish)?; self.socket_config.apply(dish)?; Ok(()) } } #[derive(Clone, Serialize, Deserialize)] struct FlatDishConfig { connect: Option<Vec<Endpoint>>, bind: Option<Vec<Endpoint>>, recv_hwm: HighWaterMark, recv_timeout: Period, groups: Option<Vec<Group>>, mechanism: Option<Mechanism>, } impl From<DishConfig> for FlatDishConfig { fn from(config: DishConfig) -> Self { let socket_config = config.socket_config; let recv_config = config.recv_config; Self { connect: socket_config.connect, bind: socket_config.bind, mechanism: socket_config.mechanism, recv_hwm: recv_config.recv_hwm, recv_timeout: recv_config.recv_timeout, groups: config.groups, } } } impl From<FlatDishConfig> for DishConfig { fn from(flat: FlatDishConfig) -> Self { let socket_config = SocketConfig { connect: flat.connect, bind: flat.bind, mechanism: flat.mechanism, }; let recv_config = RecvConfig { recv_hwm: flat.recv_hwm, recv_timeout: flat.recv_timeout, }; Self { socket_config, recv_config, groups: flat.groups, } } } impl GetSocketConfig for DishConfig { fn socket_config(&self) -> &SocketConfig { &self.socket_config } fn socket_config_mut(&mut self) -> &mut SocketConfig { &mut self.socket_config } } impl ConfigureSocket for DishConfig {} impl GetRecvConfig for DishConfig { fn recv_config(&self) -> &RecvConfig { &self.recv_config } fn recv_config_mut(&mut self) -> &mut RecvConfig { &mut self.recv_config } } impl ConfigureRecv for DishConfig {} #[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct DishBuilder { inner: DishConfig, } impl DishBuilder { pub fn new() -> Self { Self::default() } pub fn build(&self) -> Result<Dish, Error> { self.inner.build() } pub fn with_ctx(&self, handle: CtxHandle) -> Result<Dish, Error> { self.inner.with_ctx(handle) } pub fn join<I, G>(&mut self, groups: I) -> &mut Self where I: IntoIterator<Item = G>, G: Into<Group>, { let groups: Vec<Group> = groups.into_iter().map(G::into).collect(); self.inner.set_groups(Some(groups)); self } } impl GetSocketConfig for DishBuilder { fn socket_config(&self) -> &SocketConfig { self.inner.socket_config() } fn socket_config_mut(&mut self) -> &mut SocketConfig { self.inner.socket_config_mut() } } impl BuildSocket for DishBuilder {} impl GetRecvConfig for DishBuilder { fn recv_config(&self) -> &RecvConfig { self.inner.recv_config() } fn recv_config_mut(&mut self) -> &mut RecvConfig { self.inner.recv_config_mut() } } impl BuildRecv for DishBuilder {} #[cfg(test)] mod test { use super::*; #[test] fn test_ser_de() { let config = DishConfig::new(); let ron = serde_yaml::to_string(&config).unwrap(); let de: DishConfig = serde_yaml::from_str(&ron).unwrap(); assert_eq!(config, de); } #[test] fn test_dish() { use crate::{prelude::*, TcpAddr, *}; use std::{thread, time::Duration}; let addr: TcpAddr = "127.0.0.1:*".try_into().unwrap(); let radio = RadioBuilder::new().bind(addr).build().unwrap(); let bound = radio.last_endpoint().unwrap(); let a: Group = "group a".try_into().unwrap(); let dish = DishBuilder::new().connect(bound).join(&a).build().unwrap(); thread::spawn(move || { let a: Group = "group a".try_into().unwrap(); let b: Group = "group b".try_into().unwrap(); let mut count = 0; loop { let mut msg = Msg::new(); let group = if count % 2 == 0 { &a } else { &b }; msg.set_group(group); radio.send(msg).unwrap(); std::thread::sleep(Duration::from_millis(1)); count += 1; } }); let msg = dish.recv_msg().unwrap(); assert_eq!(msg.group().unwrap(), &a); let msg = dish.recv_msg().unwrap(); assert_eq!(msg.group().unwrap(), &a); } }
n with_ctx(&self, handle: CtxHandle) -> Result<Dish, Error> { let dish = Dish::with_ctx(handle)?; self.apply(&dish)?; Ok(dish) }
function_block-function_prefixed
[ { "content": "fn connect(socket_ptr: *mut c_void, c_string: CString) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_connect(socket_ptr, c_string.as_ptr()) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => {\n\n panic!(\"invalid endpoint : {}\", c_string.to_string_lossy())\n\n }\n\n errno::EPROTONOSUPPORT => {\n\n Error::new(ErrorKind::InvalidInput(\"transport not supported\"))\n\n }\n\n errno::ENOCOMPATPROTO => {\n\n Error::new(ErrorKind::InvalidInput(\"transport incompatible\"))\n\n }\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EMTHREAD => panic!(\"no i/o thread available\"),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/raw.rs", "rank": 2, "score": 222536.18060101874 }, { "content": "fn bind(socket_ptr: *mut c_void, c_string: CString) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_bind(socket_ptr, c_string.as_ptr()) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => {\n\n panic!(\"invalid endpoint : {}\", c_string.to_string_lossy())\n\n }\n\n errno::EPROTONOSUPPORT => {\n\n Error::new(ErrorKind::InvalidInput(\"transport not supported\"))\n\n }\n\n errno::ENOCOMPATPROTO => {\n\n Error::new(ErrorKind::InvalidInput(\"transport incompatible\"))\n\n }\n\n errno::EADDRINUSE => Error::new(ErrorKind::AddrInUse),\n\n errno::EADDRNOTAVAIL => Error::new(ErrorKind::AddrNotAvailable),\n\n errno::ENODEV => Error::new(ErrorKind::AddrNotAvailable),\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EMTHREAD => panic!(\"no i/o thread available\"),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/raw.rs", "rank": 3, "score": 222536.18060101877 }, { "content": "fn unbind(socket_ptr: *mut c_void, c_string: CString) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_unbind(socket_ptr, c_string.as_ptr()) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => {\n\n panic!(\"invalid endpoint : {}\", c_string.to_string_lossy())\n\n }\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::ENOENT => {\n\n Error::new(ErrorKind::NotFound(\"endpoint was not bound to\"))\n\n }\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/raw.rs", "rank": 4, "score": 222536.18060101877 }, { "content": "fn disconnect(socket_ptr: *mut c_void, c_string: CString) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_disconnect(socket_ptr, c_string.as_ptr()) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => {\n\n panic!(\"invalid endpoint : {}\", c_string.to_string_lossy())\n\n }\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::ENOENT => {\n\n Error::new(ErrorKind::NotFound(\"endpoint was not in use\"))\n\n }\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/raw.rs", "rank": 5, "score": 222536.18060101874 }, { "content": "/// Start a built-in ØMQ proxy between a frontend and a backend socket.\n\n///\n\n/// The two sockets must be configured before creating the proxy.\n\n///\n\n/// The proxy connects a frontend socket to a backend socket. Conceptually, data\n\n/// flows from frontend to backend. Depending on the socket types, replies may\n\n/// flow in the opposite direction. The direction is conceptual only; the proxy\n\n/// is fully symmetric and there is no technical difference between frontend and\n\n/// backend.\n\n///\n\n/// # Returned Errors\n\n/// * [`InvalidCtx`]\n\n///\n\n/// # Example\n\n/// ```\n\n/// #\n\n/// # use failure::Error;\n\n/// # fn main() -> Result<(), Error> {\n\n/// use libzmq::{prelude::*, *};\n\n/// use std::thread;\n\n///\n\n/// let radio_addr: InprocAddr = \"frontend\".try_into()?;\n\n/// let dish_addr: InprocAddr = \"backend\".try_into()?;\n\n/// let group: Group = \"some group\".try_into()?;\n\n///\n\n/// let radio = RadioBuilder::new()\n\n/// .bind(&radio_addr)\n\n/// .build()?;\n\n///\n\n/// let frontend = DishBuilder::new()\n\n/// .connect(&radio_addr)\n\n/// .join(&group)\n\n/// .build()?;\n\n///\n\n/// let backend = RadioBuilder::new()\n\n/// .bind(&dish_addr)\n\n/// .build()?;\n\n///\n\n/// let dish = DishBuilder::new()\n\n/// .connect(&dish_addr)\n\n/// .join(&group)\n\n/// .build()?;\n\n///\n\n/// let proxy_handle = thread::spawn(move || proxy(frontend, backend));\n\n///\n\n/// let mut msg = Msg::new();\n\n/// msg.set_group(&group);\n\n/// radio.send(msg)?;\n\n///\n\n/// let msg = dish.recv_msg()?;\n\n/// assert!(msg.is_empty());\n\n/// #\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n///\n\n/// [`InvalidCtx`]: ../enum.ErrorKind.html#variant.InvalidCtx\n\npub fn proxy<F, B>(frontend: F, backend: B) -> Result<(), Error>\n\nwhere\n\n F: GetRawSocket,\n\n B: GetRawSocket,\n\n{\n\n let frontend_socket_ptr = frontend.raw_socket().as_mut_ptr();\n\n let backend_socket_ptr = backend.raw_socket().as_mut_ptr();\n\n let rc = unsafe {\n\n sys::zmq_proxy(frontend_socket_ptr, backend_socket_ptr, ptr::null_mut())\n\n };\n\n\n\n assert_eq!(rc, -1);\n\n\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n}\n", "file_path": "libzmq/src/utils.rs", "rank": 6, "score": 211767.25301272827 }, { "content": "fn recv(mut_sock_ptr: *mut c_void, msg: &mut Msg) -> Result<(), Error> {\n\n let rc = unsafe { sys::zmq_msg_recv(msg.as_mut_ptr(), mut_sock_ptr, 0) };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::EINTR => Error::new(ErrorKind::Interrupted),\n\n errno::EAGAIN => Error::new(ErrorKind::WouldBlock),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\n#[allow(dead_code)]\n\npub(crate) enum OldSocketType {\n", "file_path": "libzmq/src/old.rs", "rank": 7, "score": 191478.7063819378 }, { "content": "fn z85_decode(input: &str) -> Result<Vec<u8>, CurveError> {\n\n let input = input.as_bytes();\n\n let len = input.len();\n\n if len % 5 != 0 {\n\n panic!(\"input length must be div by 5\");\n\n }\n\n\n\n let mut out = Vec::with_capacity(len / 5 * 4);\n\n for (i, chunk) in input.chunks(5).enumerate() {\n\n match z85_decode_chunk(chunk) {\n\n Err(pos) => {\n\n return Err(CurveError::InvalidByte {\n\n pos: i * 5 + pos,\n\n byte: chunk[pos],\n\n });\n\n }\n\n Ok(out_chunk) => out.extend_from_slice(&out_chunk),\n\n }\n\n }\n\n\n", "file_path": "libzmq/src/auth/curve.rs", "rank": 8, "score": 177442.26605956917 }, { "content": "/// Send messages in a thread-safe fashion.\n\n///\n\n/// Does not support multipart messages.\n\npub trait SendMsg: GetRawSocket {\n\n /// Push a message into the outgoing socket queue.\n\n ///\n\n /// This operation might block until the mute state end or,\n\n /// if it set, `send_timeout` expires.\n\n ///\n\n /// If the message is a `Msg`, `Vec<u8>`, `[u8]`, or a `String`, it is not copied.\n\n ///\n\n /// # Success\n\n /// The message was queued and now belongs to ØMQ\n\n ///\n\n /// # Error\n\n /// In case of an error, the message is not queued and\n\n /// the ownership is returned.\n\n ///\n\n /// ## Possible Error Variants\n\n /// * [`WouldBlock`] (if `send_timeout` expires)\n\n /// * [`InvalidCtx`]\n\n /// * [`Interrupted`]\n\n /// * [`HostUnreachable`] (only for [`Server`] socket)\n", "file_path": "libzmq/src/core/send.rs", "rank": 9, "score": 169660.87603182634 }, { "content": "fn check_duration(duration: Duration) -> Result<(), Error> {\n\n if duration.as_millis() > i32::max_value() as u128 {\n\n Err(Error::new(ErrorKind::InvalidInput(\n\n \"ms in duration cannot be greater than i32::MAX\",\n\n )))\n\n } else {\n\n Ok(())\n\n }\n\n}\n", "file_path": "libzmq/src/core/sockopt.rs", "rank": 10, "score": 168013.5112459045 }, { "content": "fn send(\n\n socket_ptr: *mut c_void,\n\n mut msg: Msg,\n\n no_block: bool,\n\n) -> Result<(), Error<Msg>> {\n\n let rc = unsafe {\n\n sys::zmq_msg_send(msg.as_mut_ptr(), socket_ptr, no_block as c_int)\n\n };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EAGAIN => Error::with_content(ErrorKind::WouldBlock, msg),\n\n errno::ENOTSUP => panic!(\"send is not supported by socket type\"),\n\n errno::EINVAL => {\n\n panic!(\"multipart messages are not supported by socket type\")\n\n }\n\n errno::EFSM => {\n\n panic!(\"operation cannot be completed in current socket state\")\n\n }\n", "file_path": "libzmq/src/core/send.rs", "rank": 11, "score": 167940.8550264997 }, { "content": "/// Methods shared by all thread-safe sockets.\n\n///\n\n/// Here is the list of socket option that differs from the ØMQ defaults:\n\n/// * All sockets have their linger period set to zero (`ZMQ_BLOCKY`).\n\n/// * All sockets have IPV6 enabled (`ZMQ_IPV6`).\n\n/// * All sockets have `ZMQ_ZAP_ENFORCE_DOMAIN` set to true.\n\n/// * All sockets have `ZMQ_ZAP_DOMAIN` hardcoded to \"global\".\n\npub trait Socket: GetRawSocket {\n\n /// Schedules a connection to a [`Endpoint`].\n\n ///\n\n /// Since ØMQ handles all connections behind the curtain, one cannot know\n\n /// exactly when the connection is truly established a blocking `send`\n\n /// or `recv` call is made on that connection.\n\n ///\n\n /// # Usage Contract\n\n /// * The endpoint's protocol must be supported by the socket.\n\n ///\n\n /// # Returned Errors\n\n /// * [`InvalidInput`] (transport incompatible or not supported)\n\n /// * [`InvalidCtx`]\n\n ///\n\n /// # Example\n\n /// ```\n\n /// # use failure::Error;\n\n /// #\n\n /// # fn main() -> Result<(), Error> {\n\n /// use libzmq::{prelude::*, Client, TcpAddr};\n", "file_path": "libzmq/src/core/mod.rs", "rank": 12, "score": 163047.65169016717 }, { "content": "fn read_file(name: &Path) -> std::io::Result<Vec<u8>> {\n\n let mut file = File::open(name)?;\n\n let mut buf = Vec::new();\n\n file.read_to_end(&mut buf)?;\n\n Ok(buf)\n\n}\n\n\n", "file_path": "libzmq/examples/secure_req_rep.rs", "rank": 14, "score": 158490.60642330514 }, { "content": "/// Receive atomic messages in an immutable, thread-safe fashion.\n\n///\n\n/// Does not support multipart messages.\n\npub trait RecvMsg: GetRawSocket {\n\n /// Retreive a message from the inbound socket queue.\n\n ///\n\n /// This operation might block until the socket receives a message or,\n\n /// if it is set, until `recv_timeout` expires.\n\n ///\n\n /// # Error\n\n /// The `Msg` is returned as the content of the `Error`.\n\n ///\n\n /// ## Possible Error Variants\n\n /// * [`WouldBlock`] (if `recv_timeout` expires)\n\n /// * [`InvalidCtx`]\n\n /// * [`Interrupted`]\n\n ///\n\n /// [`WouldBlock`]: ../enum.ErrorKind.html#variant.WouldBlock\n\n /// [`InvalidCtx`]: ../enum.ErrorKind.html#variant.InvalidCtx\n\n /// [`Interrupted`]: ../enum.ErrorKind.html#variant.Interrupted\n\n fn recv(&self, msg: &mut Msg) -> Result<(), Error> {\n\n recv(self.raw_socket().as_mut_ptr(), msg, false)\n\n }\n", "file_path": "libzmq/src/core/recv.rs", "rank": 15, "score": 149376.06915273154 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let path = PathBuf::from(\"examples\").join(CONFIG_FILE);\n\n\n\n let config: Config =\n\n serde_yaml::from_slice(&read_file(&path).unwrap()).unwrap();\n\n\n\n // Configure the `AuthServer`. We won't need the returned `AuthClient`.\n\n let _ = config.auth.build()?;\n\n\n\n // Configure our two sockets.\n\n let server = config.server.build()?;\n\n let client = config.client.build()?;\n\n\n\n // Once again we used a system assigned port for our server.\n\n let bound = server.last_endpoint()?;\n\n client.connect(bound)?;\n\n\n\n // Spawn the server thread. In a real application, this\n\n // would be on another node.\n\n let handle = thread::spawn(move || -> Result<(), Error> {\n", "file_path": "libzmq/examples/secure_req_rep.rs", "rank": 16, "score": 146617.58103050344 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n let addr: InprocAddr = InprocAddr::new_unique();\n\n\n\n let server = ServerBuilder::new().bind(&addr).build()?;\n\n\n\n // Spawn the server thread.\n\n let handle = thread::spawn(move || -> Result<(), Error> {\n\n loop {\n\n let request = server.recv_msg()?;\n\n assert_eq!(request.to_str(), Ok(\"ping\"));\n\n\n\n // Retrieve the routing_id to route the reply to the client.\n\n let id = request.routing_id().unwrap();\n\n // We cast the Error<Msg> to Error<()>. This drops the Msg.\n\n server.route(\"pong\", id).map_err(Error::cast)?;\n\n }\n\n });\n\n\n\n let client = ClientBuilder::new().connect(addr).build()?;\n\n\n", "file_path": "libzmq/examples/basic_req_rep.rs", "rank": 17, "score": 146617.58103050344 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n // We use a system assigned port here.\n\n let addr: TcpAddr = \"127.0.0.1:*\".try_into()?;\n\n let duration = Duration::from_millis(300);\n\n\n\n let hb = Heartbeat::new(duration)\n\n .add_timeout(3 * duration)\n\n .add_ttl(3 * duration);\n\n\n\n let server = ServerBuilder::new()\n\n .bind(addr)\n\n .send_timeout(duration)\n\n .heartbeat(&hb)\n\n .build()?;\n\n\n\n // Retrieve the assigned port.\n\n let bound = server.last_endpoint()?;\n\n\n\n // Spawn the server thread. In a real application, this\n\n // would be on another node.\n", "file_path": "libzmq/examples/reliable_req_rep.rs", "rank": 18, "score": 146617.58103050344 }, { "content": "fn z85_encode(input: &[u8]) -> Result<String, CurveError> {\n\n let len = input.len();\n\n if len % 4 != 0 {\n\n panic!(\"input lenght must be div by 4\");\n\n }\n\n\n\n let mut out = Vec::with_capacity(len / 4 * 5);\n\n for chunk in input.chunks(4) {\n\n out.extend_from_slice(&z85_encode_chunk(chunk));\n\n }\n\n\n\n unsafe { Ok(String::from_utf8_unchecked(out)) }\n\n}\n\n\n", "file_path": "libzmq/src/auth/curve.rs", "rank": 19, "score": 141161.19816532344 }, { "content": "struct AuthResult {\n\n user_id: String,\n\n metadata: Vec<u8>,\n\n}\n\n\n\n// A configurable ZAP handler.\n\npub(crate) struct AuthServer {\n\n // ZAP handler socket\n\n handler: OldSocket,\n\n request: Server,\n\n whitelist: HashSet<Ipv6Addr>,\n\n blacklist: HashSet<Ipv6Addr>,\n\n plain_registry: HashMap<String, String>,\n\n // Allowed public client keys.\n\n curve_registry: HashSet<CurvePublicKey>,\n\n // Whether curve auth is enabled.\n\n curve_auth: bool,\n\n}\n\n\n\nimpl AuthServer {\n", "file_path": "libzmq/src/auth/server.rs", "rank": 20, "score": 139028.63288295094 }, { "content": "/// A trait that indicates that the socket supports configurable\n\n/// heartbeating.\n\n///\n\n/// The actual heartbeating will be done by the engine in the background.\n\n///\n\n/// Only applies to connection based transports such as `TCP`.\n\n///\n\n/// # Contract\n\n/// * timeout and interval duration in ms cannot exceed i32::MAX\n\n/// * ttl duration in ms cannot exceed 6553599\n\n///\n\n/// # Default value\n\n/// `None` (no heartbeating)\n\n///\n\n/// # Return Errors\n\n/// * [`InvalidInput`]: (if contract is not respected)\n\n///\n\n/// # Example\n\n/// ```\n\n/// # use failure::Error;\n\n/// #\n\n/// # fn main() -> Result<(), Error> {\n\n/// use libzmq::{prelude::*, Client, Heartbeat, auth::*};\n\n/// use std::time::Duration;\n\n///\n\n/// let client = Client::new()?;\n\n/// assert_eq!(client.heartbeat(), None);\n\n///\n\n/// let duration = Duration::from_millis(300);\n\n/// let hb = Heartbeat::new(duration)\n\n/// .add_timeout(2 * duration);\n\n/// let expected = hb.clone();\n\n///\n\n/// client.set_heartbeat(Some(hb))?;\n\n/// assert_eq!(client.heartbeat(), Some(expected));\n\n/// #\n\n/// # Ok(())\n\n/// # }\n\n/// ```\n\n///\n\n/// [`Mechanism`]: ../auth/enum.Mechanism.html\n\npub trait Heartbeating: GetRawSocket {\n\n /// Returns a the socket's heartbeating configuration.\n\n fn heartbeat(&self) -> Option<Heartbeat> {\n\n self.raw_socket().heartbeat().lock().unwrap().to_owned()\n\n }\n\n\n\n /// Sets the socket's heartbeating configuration.\n\n fn set_heartbeat(&self, maybe: Option<Heartbeat>) -> Result<(), Error> {\n\n let raw_socket = self.raw_socket();\n\n let mutex = raw_socket.heartbeat().lock().unwrap();\n\n\n\n set_heartbeat(raw_socket, maybe, mutex)\n\n }\n\n}\n\n\n\n#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]\n\n#[doc(hidden)]\n\npub struct HeartbeatingConfig {\n\n pub(crate) heartbeat: Option<Heartbeat>,\n\n}\n\n\n\nimpl HeartbeatingConfig {\n\n pub(crate) fn apply<S: Heartbeating>(\n\n &self,\n\n socket: &S,\n\n ) -> Result<(), Error> {\n\n socket.set_heartbeat(self.heartbeat.clone())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/heartbeat.rs", "rank": 21, "score": 131691.60009713692 }, { "content": "/// A set of provided methods for the configuration of socket that implements `SendMsg`.\n\npub trait ConfigureSend: GetSendConfig {\n\n fn send_hwm(&self) -> i32 {\n\n self.send_config().send_hwm.into()\n\n }\n\n\n\n fn set_send_hwm(&mut self, hwm: i32) {\n\n self.send_config_mut().send_hwm = HighWaterMark(hwm);\n\n }\n\n\n\n fn send_timeout(&self) -> Period {\n\n self.send_config().send_timeout\n\n }\n\n\n\n fn set_send_timeout(&mut self, period: Period) {\n\n self.send_config_mut().send_timeout = period;\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/send.rs", "rank": 22, "score": 125854.76480885153 }, { "content": "/// A set of provided methods for the builder of a socket that implements `SendMsg`.\n\npub trait BuildSend: GetSendConfig {\n\n fn send_hwm(&mut self, hwm: i32) -> &mut Self {\n\n self.send_config_mut().send_hwm = HighWaterMark(hwm);\n\n self\n\n }\n\n\n\n fn send_timeout(&mut self, timeout: Duration) -> &mut Self {\n\n self.send_config_mut().send_timeout = Finite(timeout);\n\n self\n\n }\n\n}\n", "file_path": "libzmq/src/core/send.rs", "rank": 23, "score": 125854.76480885153 }, { "content": "fn send(\n\n mut_sock_ptr: *mut c_void,\n\n mut msg: Msg,\n\n more: bool,\n\n) -> Result<(), Error> {\n\n let flags = if more { sys::ZMQ_SNDMORE } else { 0 };\n\n let rc = unsafe {\n\n sys::zmq_msg_send(msg.as_mut_ptr(), mut_sock_ptr, flags as c_int)\n\n };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::EINTR => Error::new(ErrorKind::Interrupted),\n\n errno::EAGAIN => Error::new(ErrorKind::WouldBlock),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/old.rs", "rank": 24, "score": 125499.77886203522 }, { "content": "/// A set of provided methods for a socket configuration.\n\npub trait ConfigureSocket: GetSocketConfig {\n\n fn connect(&self) -> Option<&[Endpoint]> {\n\n self.socket_config().connect.as_deref()\n\n }\n\n\n\n fn set_connect<I, E>(&mut self, maybe: Option<I>)\n\n where\n\n I: IntoIterator<Item = E>,\n\n E: Into<Endpoint>,\n\n {\n\n let maybe: Option<Vec<Endpoint>> =\n\n maybe.map(|e| e.into_iter().map(E::into).collect());\n\n self.socket_config_mut().connect = maybe;\n\n }\n\n\n\n fn bind(&self) -> Option<&[Endpoint]> {\n\n self.socket_config().bind.as_deref()\n\n }\n\n\n\n fn set_bind<I, E>(&mut self, maybe: Option<I>)\n", "file_path": "libzmq/src/core/mod.rs", "rank": 25, "score": 118716.61092186405 }, { "content": "#[doc(hidden)]\n\npub trait GetRawSocket: super::private::Sealed {\n\n fn raw_socket(&self) -> &RawSocket;\n\n}\n\n\n\npub(crate) enum RawSocketType {\n\n Client = sys::ZMQ_CLIENT as isize,\n\n Server = sys::ZMQ_SERVER as isize,\n\n Radio = sys::ZMQ_RADIO as isize,\n\n Dish = sys::ZMQ_DISH as isize,\n\n Dealer = sys::ZMQ_DEALER as isize,\n\n Router = sys::ZMQ_ROUTER as isize,\n\n Pair = sys::ZMQ_PAIR as isize,\n\n Sub = sys::ZMQ_SUB as isize,\n\n Scatter = sys::ZMQ_SCATTER as isize,\n\n Gather = sys::ZMQ_GATHER as isize,\n\n}\n\n\n\nimpl From<RawSocketType> for c_int {\n\n fn from(r: RawSocketType) -> c_int {\n\n match r {\n", "file_path": "libzmq/src/core/raw.rs", "rank": 26, "score": 118638.70616676842 }, { "content": "#[doc(hidden)]\n\npub trait GetSendConfig: private::Sealed {\n\n fn send_config(&self) -> &SendConfig;\n\n\n\n fn send_config_mut(&mut self) -> &mut SendConfig;\n\n}\n\n\n", "file_path": "libzmq/src/core/send.rs", "rank": 27, "score": 118171.91599526849 }, { "content": "/// A set of provided methods for a socket builder.\n\npub trait BuildSocket: GetSocketConfig + Sized {\n\n fn connect<I, E>(&mut self, endpoints: I) -> &mut Self\n\n where\n\n I: IntoIterator<Item = E>,\n\n E: Into<Endpoint>,\n\n {\n\n self.socket_config_mut().set_connect(Some(endpoints));\n\n self\n\n }\n\n\n\n fn bind<I, E>(&mut self, endpoints: I) -> &mut Self\n\n where\n\n I: IntoIterator<Item = E>,\n\n E: Into<Endpoint>,\n\n {\n\n self.socket_config_mut().set_bind(Some(endpoints));\n\n self\n\n }\n\n\n\n fn mechanism<M>(&mut self, mechanism: M) -> &mut Self\n", "file_path": "libzmq/src/core/mod.rs", "rank": 28, "score": 113999.27317532417 }, { "content": "fn z85_decode_chunk(input: &[u8]) -> Result<[u8; 4], usize> {\n\n let mut num: u32 = 0;\n\n\n\n for (i, &byte) in input.iter().enumerate().take(5) {\n\n num *= 85;\n\n\n\n if byte < 0x20 || 0x7F < byte {\n\n return Err(i);\n\n }\n\n\n\n let b = OCTETS[byte as usize - 32];\n\n if b == 0xFF {\n\n return Err(i);\n\n }\n\n\n\n num += u32::from(b);\n\n }\n\n\n\n let mut out = [0_u8; 4];\n\n BigEndian::write_u32(&mut out, num);\n\n\n\n Ok(out)\n\n}\n\n\n", "file_path": "libzmq/src/auth/curve.rs", "rank": 29, "score": 110900.58328293635 }, { "content": "#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\nstruct RawCtx {\n\n ctx: *mut c_void,\n\n}\n\n\n\nimpl RawCtx {\n\n fn new() -> Self {\n\n let ctx = unsafe { sys::zmq_ctx_new() };\n\n\n\n if ctx.is_null() {\n\n panic!(msg_from_errno(unsafe { sys::zmq_errno() }));\n\n }\n\n\n\n Self { ctx }\n\n }\n\n\n\n fn get(self, option: CtxOption) -> i32 {\n\n unsafe { sys::zmq_ctx_get(self.ctx, option.into()) }\n\n }\n\n\n\n fn set(self, option: CtxOption, value: i32) -> Result<(), Error> {\n", "file_path": "libzmq/src/ctx.rs", "rank": 30, "score": 108129.50734188186 }, { "content": "#[doc(hidden)]\n\npub trait GetSocketConfig: private::Sealed {\n\n fn socket_config(&self) -> &SocketConfig;\n\n\n\n fn socket_config_mut(&mut self) -> &mut SocketConfig;\n\n}\n\n\n\nimpl GetSocketConfig for SocketConfig {\n\n fn socket_config(&self) -> &SocketConfig {\n\n self\n\n }\n\n\n\n fn socket_config_mut(&mut self) -> &mut SocketConfig {\n\n self\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/mod.rs", "rank": 31, "score": 106103.0138183456 }, { "content": "/// Reports the ØMQ library version.\n\n///\n\n/// Returns a tuple in the format `(Major, Minor, Patch)`.\n\n///\n\n/// See [`zmq_version`].\n\n///\n\n/// [`zmq_version`]: http://api.zeromq.org/4-2:zmq-version\n\n///\n\n/// ```\n\n/// use libzmq::version;\n\n///\n\n/// assert_eq!(version(), (4, 3, 2));\n\n/// ```\n\n// This test acts as a canary when upgrading the *libzmq*\n\n// version.\n\npub fn version() -> (i32, i32, i32) {\n\n let mut major = 0;\n\n let mut minor = 0;\n\n let mut patch = 0;\n\n unsafe {\n\n sys::zmq_version(\n\n &mut major as *mut c_int,\n\n &mut minor as *mut c_int,\n\n &mut patch as *mut c_int,\n\n );\n\n }\n\n (major, minor, patch)\n\n}\n\n\n", "file_path": "libzmq/src/utils.rs", "rank": 32, "score": 96219.83001159903 }, { "content": "fn getsockopt(\n\n mut_sock_ptr: *mut c_void,\n\n option: SocketOption,\n\n mut_value_ptr: *mut c_void,\n\n size: &mut size_t,\n\n) -> Result<(), Error> {\n\n let rc = unsafe {\n\n sys::zmq_getsockopt(mut_sock_ptr, option.into(), mut_value_ptr, size)\n\n };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => panic!(\"invalid option\"),\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EINTR => Error::new(ErrorKind::Interrupted),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n", "file_path": "libzmq/src/core/sockopt.rs", "rank": 33, "score": 95257.98879750814 }, { "content": "fn recv(\n\n socket_ptr: *mut c_void,\n\n msg: &mut Msg,\n\n no_block: bool,\n\n) -> Result<(), Error> {\n\n let rc = unsafe {\n\n sys::zmq_msg_recv(msg.as_mut_ptr(), socket_ptr, no_block as c_int)\n\n };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EAGAIN => Error::new(ErrorKind::WouldBlock),\n\n errno::ENOTSUP => panic!(\"recv not supported by socket type\"),\n\n errno::EFSM => {\n\n panic!(\"operation cannot be completed in current socket state\")\n\n }\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EINTR => Error::new(ErrorKind::Interrupted),\n\n errno::EFAULT => panic!(\"invalid message\"),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/recv.rs", "rank": 34, "score": 95257.98879750814 }, { "content": "fn setsockopt(\n\n mut_sock_ptr: *mut c_void,\n\n option: SocketOption,\n\n value_ptr: *const c_void,\n\n size: size_t,\n\n) -> Result<(), Error> {\n\n let rc = unsafe {\n\n sys::zmq_setsockopt(mut_sock_ptr, option.into(), value_ptr, size)\n\n };\n\n\n\n if rc == -1 {\n\n let errno = unsafe { sys::zmq_errno() };\n\n let err = match errno {\n\n errno::EINVAL => panic!(\"invalid option\"),\n\n errno::ETERM => Error::new(ErrorKind::InvalidCtx),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EINTR => Error::new(ErrorKind::Interrupted),\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n", "file_path": "libzmq/src/core/sockopt.rs", "rank": 35, "score": 95257.98879750814 }, { "content": "#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\nstruct CurveKey {\n\n text: String,\n\n}\n\n\n\nimpl CurveKey {\n\n fn new<S>(text: S) -> Result<Self, CurveError>\n\n where\n\n S: Into<String>,\n\n {\n\n let text = text.into();\n\n if text.len() != CURVE_CURVE_KEY_SIZE {\n\n return Err(CurveError::InvalidSize);\n\n }\n\n\n\n let bytes = text.as_bytes();\n\n\n\n for (pos, &byte) in bytes.iter().enumerate() {\n\n if !LETTERS.contains(&byte) {\n\n return Err(CurveError::InvalidByte { pos, byte });\n\n }\n", "file_path": "libzmq/src/auth/curve.rs", "rank": 36, "score": 94167.6123154285 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ZapRequest {\n\n version: String,\n\n request_id: Msg,\n\n domain: String,\n\n addr: Ipv6Addr,\n\n identity: Msg,\n\n mechanism: String,\n\n credentials: Vec<Msg>,\n\n}\n\n\n\nimpl ZapRequest {\n\n fn new(mut parts: Vec<Msg>) -> Self {\n\n let version = parts.remove(0).to_str().unwrap().to_owned();\n\n assert_eq!(version, ZAP_VERSION);\n\n\n\n let request_id = parts.remove(0);\n\n let domain = parts.remove(0).to_str().unwrap().to_owned();\n\n let addr: Ipv6Addr = parts.remove(0).to_str().unwrap().parse().unwrap();\n\n\n\n let identity = parts.remove(0);\n", "file_path": "libzmq/src/auth/server.rs", "rank": 37, "score": 94158.24684448242 }, { "content": "#[derive(Clone, Debug)]\n\nstruct ZapReply {\n\n version: String,\n\n request_id: Msg,\n\n status_code: StatusCode,\n\n status_text: String,\n\n user_id: String,\n\n metadata: Vec<u8>,\n\n}\n\n\n\nimpl IntoIterator for ZapReply {\n\n type IntoIter = vec::IntoIter<Msg>;\n\n type Item = Msg;\n\n fn into_iter(self) -> Self::IntoIter {\n\n let parts: Vec<Msg> = vec![\n\n self.version.into(),\n\n self.request_id,\n\n self.status_code.to_string().into(),\n\n self.status_text.into(),\n\n self.user_id.into(),\n\n self.metadata.into(),\n\n ];\n\n\n\n parts.into_iter()\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/auth/server.rs", "rank": 38, "score": 94158.24684448242 }, { "content": "fn set_mechanism(\n\n raw_socket: &RawSocket,\n\n mut mechanism: Mechanism,\n\n mut mutex: MutexGuard<Mechanism>,\n\n) -> Result<(), Error> {\n\n if *mutex == mechanism {\n\n return Ok(());\n\n }\n\n\n\n // Undo the previous mechanism.\n\n match &*mutex {\n\n Mechanism::Null => (),\n\n Mechanism::PlainClient(_) => {\n\n raw_socket.set_username(None)?;\n\n raw_socket.set_password(None)?;\n\n }\n\n Mechanism::PlainServer => {\n\n raw_socket.set_plain_server(false)?;\n\n }\n\n Mechanism::CurveClient(_) => {\n", "file_path": "libzmq/src/core/mod.rs", "rank": 39, "score": 92523.74705141141 }, { "content": "fn set_heartbeat(\n\n raw_socket: &RawSocket,\n\n maybe: Option<Heartbeat>,\n\n mut mutex: MutexGuard<Option<Heartbeat>>,\n\n) -> Result<(), Error> {\n\n if *mutex == maybe {\n\n return Ok(());\n\n }\n\n\n\n if let Some(heartbeat) = &maybe {\n\n raw_socket.set_heartbeat_interval(heartbeat.interval)?;\n\n if let Finite(timeout) = heartbeat.timeout {\n\n raw_socket.set_heartbeat_timeout(timeout)?;\n\n }\n\n if let Finite(ttl) = heartbeat.ttl {\n\n raw_socket.set_heartbeat_timeout(ttl)?;\n\n }\n\n } else {\n\n raw_socket.set_heartbeat_interval(Duration::from_millis(0))?;\n\n raw_socket.set_heartbeat_timeout(Duration::from_millis(0))?;\n", "file_path": "libzmq/src/core/heartbeat.rs", "rank": 40, "score": 92523.74705141141 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct FlatServerConfig {\n\n connect: Option<Vec<Endpoint>>,\n\n bind: Option<Vec<Endpoint>>,\n\n heartbeat: Option<Heartbeat>,\n\n send_hwm: HighWaterMark,\n\n send_timeout: Period,\n\n recv_hwm: HighWaterMark,\n\n recv_timeout: Period,\n\n mechanism: Option<Mechanism>,\n\n}\n\n\n\nimpl From<ServerConfig> for FlatServerConfig {\n\n fn from(config: ServerConfig) -> Self {\n\n let socket_config = config.socket_config;\n\n let send_config = config.send_config;\n\n let recv_config = config.recv_config;\n\n let heartbeat_config = config.heartbeat_config;\n\n Self {\n\n connect: socket_config.connect,\n\n bind: socket_config.bind,\n", "file_path": "libzmq/src/socket/server.rs", "rank": 41, "score": 91426.53494937868 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct FlatScatterConfig {\n\n connect: Option<Vec<Endpoint>>,\n\n bind: Option<Vec<Endpoint>>,\n\n heartbeat: Option<Heartbeat>,\n\n send_hwm: HighWaterMark,\n\n send_timeout: Period,\n\n mechanism: Option<Mechanism>,\n\n}\n\n\n\nimpl From<ScatterConfig> for FlatScatterConfig {\n\n fn from(config: ScatterConfig) -> Self {\n\n let socket_config = config.socket_config;\n\n let send_config = config.send_config;\n\n let heartbeat_config = config.heartbeat_config;\n\n Self {\n\n connect: socket_config.connect,\n\n bind: socket_config.bind,\n\n heartbeat: heartbeat_config.heartbeat,\n\n mechanism: socket_config.mechanism,\n\n send_hwm: send_config.send_hwm,\n", "file_path": "libzmq/src/socket/scatter.rs", "rank": 42, "score": 91426.53494937868 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct FlatGatherConfig {\n\n connect: Option<Vec<Endpoint>>,\n\n bind: Option<Vec<Endpoint>>,\n\n heartbeat: Option<Heartbeat>,\n\n recv_hwm: HighWaterMark,\n\n recv_timeout: Period,\n\n mechanism: Option<Mechanism>,\n\n}\n\n\n\nimpl From<GatherConfig> for FlatGatherConfig {\n\n fn from(config: GatherConfig) -> Self {\n\n let socket_config = config.socket_config;\n\n let recv_config = config.recv_config;\n\n let heartbeat_config = config.heartbeat_config;\n\n Self {\n\n connect: socket_config.connect,\n\n bind: socket_config.bind,\n\n heartbeat: heartbeat_config.heartbeat,\n\n mechanism: socket_config.mechanism,\n\n recv_hwm: recv_config.recv_hwm,\n", "file_path": "libzmq/src/socket/gather.rs", "rank": 43, "score": 91426.53494937868 }, { "content": "#[derive(Clone, Serialize, Deserialize)]\n\nstruct FlatClientConfig {\n\n connect: Option<Vec<Endpoint>>,\n\n bind: Option<Vec<Endpoint>>,\n\n heartbeat: Option<Heartbeat>,\n\n send_hwm: HighWaterMark,\n\n send_timeout: Period,\n\n recv_hwm: HighWaterMark,\n\n recv_timeout: Period,\n\n mechanism: Option<Mechanism>,\n\n}\n\n\n\nimpl From<ClientConfig> for FlatClientConfig {\n\n fn from(config: ClientConfig) -> Self {\n\n let socket_config = config.socket_config;\n\n let send_config = config.send_config;\n\n let recv_config = config.recv_config;\n\n let heartbeat_config = config.heartbeat_config;\n\n Self {\n\n connect: socket_config.connect,\n\n bind: socket_config.bind,\n", "file_path": "libzmq/src/socket/client.rs", "rank": 44, "score": 91426.53494937868 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct FlatRadioConfig {\n\n connect: Option<Vec<Endpoint>>,\n\n bind: Option<Vec<Endpoint>>,\n\n send_hwm: HighWaterMark,\n\n send_timeout: Period,\n\n no_drop: Option<bool>,\n\n mechanism: Option<Mechanism>,\n\n}\n\n\n\nimpl From<RadioConfig> for FlatRadioConfig {\n\n fn from(config: RadioConfig) -> Self {\n\n let socket_config = config.socket_config;\n\n let send_config = config.send_config;\n\n Self {\n\n connect: socket_config.connect,\n\n bind: socket_config.bind,\n\n send_hwm: send_config.send_hwm,\n\n send_timeout: send_config.send_timeout,\n\n no_drop: config.no_drop,\n\n mechanism: socket_config.mechanism,\n", "file_path": "libzmq/src/socket/radio.rs", "rank": 45, "score": 91422.05867842326 }, { "content": " pub trait Sealed {}\n\n impl Sealed for SocketConfig {}\n\n impl Sealed for SendConfig {}\n\n impl Sealed for RecvConfig {}\n\n impl Sealed for HeartbeatingConfig {}\n\n impl Sealed for Client {}\n\n impl Sealed for ClientConfig {}\n\n impl Sealed for ClientBuilder {}\n\n impl Sealed for Server {}\n\n impl Sealed for ServerConfig {}\n\n impl Sealed for ServerBuilder {}\n\n impl Sealed for Radio {}\n\n impl Sealed for RadioConfig {}\n\n impl Sealed for RadioBuilder {}\n\n impl Sealed for Dish {}\n\n impl Sealed for DishConfig {}\n\n impl Sealed for DishBuilder {}\n\n impl Sealed for Scatter {}\n\n impl Sealed for ScatterConfig {}\n\n impl Sealed for ScatterBuilder {}\n", "file_path": "libzmq/src/core/mod.rs", "rank": 46, "score": 90551.06569435916 }, { "content": "fn assert_curve_enabled() {\n\n if cfg!(not(feature = \"curve\")) {\n\n panic!(\"CURVE support requires enabling feature flag 'curve'\");\n\n }\n\n}\n\n\n\n/// This socket may or may not be thread safe depending on the `RawSocketType`.\n\n/// We prevent that it is always thread-safe and let the wrapping types decide.\n\n#[derive(Debug)]\n\n#[doc(hidden)]\n\npub struct RawSocket {\n\n socket_mut_ptr: *mut c_void,\n\n ctx: CtxHandle,\n\n mechanism: Mutex<Mechanism>,\n\n heartbeat: Mutex<Option<Heartbeat>>,\n\n}\n\n\n\nimpl RawSocket {\n\n pub(crate) fn new(sock_type: RawSocketType) -> Result<Self, Error> {\n\n let handle = Ctx::global();\n", "file_path": "libzmq/src/core/raw.rs", "rank": 47, "score": 89992.5065193235 }, { "content": "/// A set of provided methods for a socket configuration.\n\npub trait ConfigureHeartbeating: GetHeartbeatingConfig {\n\n fn heartbeat(&self) -> Option<&Heartbeat> {\n\n self.heartbeat_config().heartbeat.as_ref()\n\n }\n\n\n\n fn set_heartbeat(&mut self, maybe: Option<Heartbeat>) {\n\n self.heartbeat_config_mut().heartbeat = maybe;\n\n }\n\n}\n\n\n\nimpl ConfigureHeartbeating for HeartbeatingConfig {}\n\n\n", "file_path": "libzmq/src/core/heartbeat.rs", "rank": 48, "score": 79052.94019070195 }, { "content": "/// A set of provided methods for the builder of a socket that implements `RecvMsg`.\n\npub trait BuildRecv: GetRecvConfig {\n\n fn recv_hwm(&mut self, hwm: i32) -> &mut Self {\n\n self.recv_config_mut().recv_hwm = HighWaterMark(hwm);\n\n self\n\n }\n\n\n\n fn recv_timeout(&mut self, timeout: Duration) -> &mut Self {\n\n self.recv_config_mut().recv_timeout = Finite(timeout);\n\n self\n\n }\n\n}\n", "file_path": "libzmq/src/core/recv.rs", "rank": 49, "score": 79052.77722587358 }, { "content": "/// A set of provided methods for the configuration of a socket that implements `RecvMsg`.\n\npub trait ConfigureRecv: GetRecvConfig {\n\n fn recv_hwm(&self) -> i32 {\n\n self.recv_config().recv_hwm.into()\n\n }\n\n\n\n fn set_recv_hwm(&mut self, hwm: i32) {\n\n self.recv_config_mut().recv_hwm = HighWaterMark(hwm);\n\n }\n\n\n\n fn recv_timeout(&self) -> Period {\n\n self.recv_config().recv_timeout\n\n }\n\n\n\n fn set_recv_timeout(&mut self, period: Period) {\n\n self.recv_config_mut().recv_timeout = period;\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/recv.rs", "rank": 50, "score": 79052.77722587358 }, { "content": "#[doc(hidden)]\n\npub trait GetHeartbeatingConfig: private::Sealed {\n\n fn heartbeat_config(&self) -> &HeartbeatingConfig;\n\n\n\n fn heartbeat_config_mut(&mut self) -> &mut HeartbeatingConfig;\n\n}\n\n\n\nimpl GetHeartbeatingConfig for HeartbeatingConfig {\n\n fn heartbeat_config(&self) -> &HeartbeatingConfig {\n\n self\n\n }\n\n\n\n fn heartbeat_config_mut(&mut self) -> &mut HeartbeatingConfig {\n\n self\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/heartbeat.rs", "rank": 51, "score": 77130.6237839139 }, { "content": "#[doc(hidden)]\n\npub trait GetRecvConfig: private::Sealed {\n\n fn recv_config(&self) -> &RecvConfig;\n\n\n\n fn recv_config_mut(&mut self) -> &mut RecvConfig;\n\n}\n\n\n", "file_path": "libzmq/src/core/recv.rs", "rank": 52, "score": 77130.6237839139 }, { "content": "fn into_ipv6(ip: IpAddr) -> Ipv6Addr {\n\n match ip {\n\n IpAddr::V4(ipv4) => ipv4.to_ipv6_mapped(),\n\n IpAddr::V6(ipv6) => ipv6,\n\n }\n\n}\n\n\n\n/// A client to configure the `AuthServer`.\n\n///\n\n/// There can be multiple `AuthClient` associated with the same `AuthServer`.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// # use failure::Error;\n\n/// #\n\n/// # fn main() -> Result<(), Error> {\n\n/// #[cfg(feature = \"curve\")] {\n\n/// use libzmq::{prelude::*, auth::*, *};\n\n/// use std::{time::Duration};\n", "file_path": "libzmq/src/auth/client.rs", "rank": 53, "score": 76293.3646941036 }, { "content": "/// A set of provided methods for a socket builder.\n\npub trait BuildHeartbeating: GetHeartbeatingConfig + Sized {\n\n fn heartbeat<H>(&mut self, heartbeat: H) -> &mut Self\n\n where\n\n H: Into<Heartbeat>,\n\n {\n\n self.heartbeat_config_mut()\n\n .set_heartbeat(Some(heartbeat.into()));\n\n self\n\n }\n\n}\n", "file_path": "libzmq/src/core/heartbeat.rs", "rank": 54, "score": 75222.20333066066 }, { "content": "fn z85_encode_chunk(input: &[u8]) -> [u8; 5] {\n\n let mut num = BigEndian::read_u32(input) as usize;\n\n let mut out = [0_u8; 5];\n\n\n\n for i in (0..5).rev() {\n\n out[i] = LETTERS[num % 85];\n\n num /= 85;\n\n }\n\n\n\n out\n\n}\n\n\n", "file_path": "libzmq/src/auth/curve.rs", "rank": 55, "score": 74771.5100179226 }, { "content": "\n\n#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]\n\n#[doc(hidden)]\n\npub struct SendConfig {\n\n pub(crate) send_hwm: HighWaterMark,\n\n pub(crate) send_timeout: Period,\n\n}\n\n\n\nimpl SendConfig {\n\n pub(crate) fn apply<S: SendMsg>(&self, socket: &S) -> Result<(), Error> {\n\n socket.set_send_hwm(self.send_hwm.into())?;\n\n socket.set_send_timeout(self.send_timeout)?;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/send.rs", "rank": 56, "score": 74092.59847119449 }, { "content": " /// use std::time::Duration;\n\n ///\n\n /// let client = Client::new()?;\n\n /// client.set_send_timeout(Some(Duration::from_millis(1)))?;\n\n ///\n\n /// // The client is in mute state so the following would block forever\n\n /// // if a timeout wasn't specified. Instead, it will block for 1ms.\n\n /// let err = client.send(\"msg\").unwrap_err();\n\n /// assert_eq!(ErrorKind::WouldBlock, err.kind());\n\n /// #\n\n /// # Ok(())\n\n /// # }\n\n /// ```\n\n fn set_send_timeout<P>(&self, period: P) -> Result<(), Error>\n\n where\n\n P: Into<Period>,\n\n {\n\n self.raw_socket().set_send_timeout(period.into())\n\n }\n\n}\n", "file_path": "libzmq/src/core/send.rs", "rank": 57, "score": 74081.54540274026 }, { "content": " /// #\n\n /// # fn main() -> Result<(), Error> {\n\n /// use libzmq::{prelude::*, *};\n\n ///\n\n /// let client = ClientBuilder::new().build()?;\n\n /// assert_eq!(client.send_hwm()?, 1000);\n\n ///\n\n /// #\n\n /// # Ok(())\n\n /// # }\n\n /// ```\n\n fn send_hwm(&self) -> Result<i32, Error> {\n\n self.raw_socket().send_hwm()\n\n }\n\n\n\n /// Set the high water mark for outbound messages on the specified socket.\n\n ///\n\n /// The high water mark is a hard limit on the maximum number of\n\n /// outstanding messages ØMQ shall queue in memory.\n\n ///\n", "file_path": "libzmq/src/core/send.rs", "rank": 58, "score": 74077.66701990401 }, { "content": "use crate::{\n\n core::*,\n\n error::{msg_from_errno, Error, ErrorKind},\n\n msg::Msg,\n\n};\n\nuse libzmq_sys as sys;\n\nuse sys::errno;\n\n\n\nuse std::{\n\n os::raw::{c_int, c_void},\n\n time::Duration,\n\n};\n\n\n", "file_path": "libzmq/src/core/send.rs", "rank": 59, "score": 74075.6222098176 }, { "content": " /// it will block until the message is sent.\n\n fn send_timeout(&self) -> Result<Period, Error> {\n\n self.raw_socket().send_timeout()\n\n }\n\n\n\n /// Sets the timeout for [`send`] on the socket.\n\n ///\n\n /// If some timeout is specified, the [`send`] will return\n\n /// [`WouldBlock`] after the duration is elapsed. Otherwise,\n\n /// it will block until the message is sent.\n\n ///\n\n /// # Default Value\n\n /// `Infinite`\n\n ///\n\n /// # Example\n\n /// ```\n\n /// # use failure::Error;\n\n /// #\n\n /// # fn main() -> Result<(), Error> {\n\n /// use libzmq::{prelude::*, Client, ErrorKind};\n", "file_path": "libzmq/src/core/send.rs", "rank": 60, "score": 74074.5289733136 }, { "content": " errno::ETERM => Error::with_content(ErrorKind::InvalidCtx, msg),\n\n errno::ENOTSOCK => panic!(\"invalid socket\"),\n\n errno::EINTR => Error::with_content(ErrorKind::Interrupted, msg),\n\n errno::EFAULT => panic!(\"invalid message\"),\n\n errno::EHOSTUNREACH => {\n\n Error::with_content(ErrorKind::HostUnreachable, msg)\n\n }\n\n _ => panic!(msg_from_errno(errno)),\n\n };\n\n\n\n Err(err)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/core/send.rs", "rank": 61, "score": 74073.91247361746 }, { "content": " fn try_send<M>(&self, msg: M) -> Result<(), Error<Msg>>\n\n where\n\n M: Into<Msg>,\n\n {\n\n send(self.raw_socket().as_mut_ptr(), msg.into(), true)\n\n }\n\n\n\n /// The high water mark for outbound messages on the specified socket.\n\n ///\n\n /// The high water mark is a hard limit on the maximum number of\n\n /// outstanding messages ØMQ shall queue in memory.\n\n ///\n\n /// If this limit has been reached the socket shall enter the `mute state`.\n\n ///\n\n /// # Default\n\n /// `1000`\n\n ///\n\n /// # Example\n\n /// ```\n\n /// # use failure::Error;\n", "file_path": "libzmq/src/core/send.rs", "rank": 62, "score": 74073.63179705251 }, { "content": " ///\n\n /// [`zmq_msg_send`]: http://api.zeromq.org/master:zmq-msg-send\n\n /// [`WouldBlock`]: ../enum.ErrorKind.html#variant.WouldBlock\n\n /// [`InvalidCtx`]: ../enum.ErrorKind.html#variant.InvalidCtx\n\n /// [`Interrupted`]: ../enum.ErrorKind.html#variant.Interrupted\n\n /// [`HostUnreachable`]: ../enum.ErrorKind.html#variant.HostUnreachable\n\n /// [`Server`]: struct.Server.html\n\n fn send<M>(&self, msg: M) -> Result<(), Error<Msg>>\n\n where\n\n M: Into<Msg>,\n\n {\n\n send(self.raw_socket().as_mut_ptr(), msg.into(), false)\n\n }\n\n\n\n /// Try to push a message into the outgoing socket queue without blocking.\n\n ///\n\n /// If the action would block, it returns a [`WouldBlock`] error, otherwise\n\n /// the message is pushed into the outgoing queue.\n\n ///\n\n /// If the message is a `Msg`, `Vec<u8>`, `[u8]`, or a `String`, it is not copied.\n", "file_path": "libzmq/src/core/send.rs", "rank": 63, "score": 74070.0165691899 }, { "content": " /// If this limit has been reached the socket shall enter the `mute state`.\n\n ///\n\n /// # Usage Contract\n\n /// * The high water mark cannot be zero.\n\n ///\n\n /// # Returned Error\n\n /// * [`InvalidInput`](on contract violation)\n\n ///\n\n /// # Default value\n\n /// 1000\n\n ///\n\n /// [`InvalidInput`]: ../enum.ErrorKind.html#variant.InvalidInput\n\n fn set_send_hwm(&self, hwm: i32) -> Result<(), Error> {\n\n self.raw_socket().set_send_hwm(hwm)\n\n }\n\n\n\n /// Sets the timeout for [`send`] on the socket.\n\n ///\n\n /// If some timeout is specified, the [`send`] will return\n\n /// [`WouldBlock`] after the duration is elapsed. Otherwise,\n", "file_path": "libzmq/src/core/send.rs", "rank": 64, "score": 74068.86523675971 }, { "content": " ///\n\n /// # Success\n\n /// The message was queued and now belongs to ØMQ\n\n ///\n\n /// # Error\n\n /// In case of an error, the message is not queued and\n\n /// the ownership is returned.\n\n ///\n\n /// ## Possible Error Variants\n\n /// * [`WouldBlock`]\n\n /// * [`InvalidCtx`]\n\n /// * [`Interrupted`]\n\n /// * [`HostUnreachable`] (only for [`Server`] socket)\n\n ///\n\n /// [`zmq_msg_send`]: http://api.zeromq.org/master:zmq-msg-send\n\n /// [`WouldBlock`]: ../enum.ErrorKind.html#variant.WouldBlock\n\n /// [`InvalidCtx`]: ../enum.ErrorKind.html#variant.InvalidCtx\n\n /// [`Interrupted`]: ../enum.ErrorKind.html#variant.Interrupted\n\n /// [`HostUnreachable`]: ../enum.ErrorKind.html#variant.HostUnreachable\n\n /// [`Server`]: struct.Server.html\n", "file_path": "libzmq/src/core/send.rs", "rank": 65, "score": 74065.38356088086 }, { "content": "fn gen_dataset(dataset_size: usize, msg_size: usize) -> Vec<Vec<u8>> {\n\n let mut rng: Isaac64Rng = SeedableRng::seed_from_u64(123_490_814_327);\n\n (0..dataset_size)\n\n .map(|_| Standard.sample_iter(&mut rng).take(msg_size).collect())\n\n .collect()\n\n}\n\n\n\npub(crate) fn bench(c: &mut Criterion) {\n\n c.bench(\n\n &\"50u8 msg on TCP\".to_owned(),\n\n Benchmark::new(\"dataset alloc (control)\", move |b| {\n\n b.iter(|| {\n\n black_box(gen_dataset(MSG_AMOUNT, MSG_SIZE));\n\n });\n\n })\n\n .with_function(\"server-client\", move |b| {\n\n let producer = ServerBuilder::new()\n\n .bind(&*ADDR)\n\n .send_hwm(HWM)\n\n .build()\n", "file_path": "libzmq/benches/socket.rs", "rank": 91, "score": 64360.143036745445 }, { "content": "fn main() {\n\n println!(\"cargo:rerun-if-changed=build.rs\");\n\n println!(\"cargo:rerun-if-env-changed=PROFILE\");\n\n\n\n let wants_debug = env::var_os(\"PROFILE\").unwrap() == \"debug\";\n\n\n\n let maybe_libsodium = if cfg!(feature = \"libsodium\") {\n\n let lib_dir = env::var(\"DEP_SODIUM_LIB\")\n\n .expect(\"build metadata `DEP_SODIUM_LIB` required\");\n\n let include_dir = env::var(\"DEP_SODIUM_INCLUDE\")\n\n .expect(\"build metadata `DEP_SODIUM_INCLUDE` required\");\n\n\n\n Some(zeromq_src::LibLocation::new(lib_dir, include_dir))\n\n } else {\n\n None\n\n };\n\n\n\n let artifacts = zeromq_src::Build::new()\n\n .link_static(true)\n\n .enable_draft(true)\n\n .build_debug(wants_debug)\n\n .with_libsodium(maybe_libsodium)\n\n .build();\n\n\n\n artifacts.print_cargo_metadata();\n\n\n\n #[cfg(feature = \"renew-bindings\")]\n\n gen_bindings(artifacts.include_dir());\n\n}\n", "file_path": "libzmq-sys/build.rs", "rank": 92, "score": 61662.96321843742 }, { "content": "// Used to generate `CURVE` certificates.\n\nfn main() {\n\n let cert = CurveCert::new_unique();\n\n println!(\"public: \\\"{}\\\"\", cert.public().as_str());\n\n println!(\"secret: \\\"{}\\\"\", cert.secret().as_str());\n\n}\n", "file_path": "libzmq/examples/gen_curve_cert.rs", "rank": 93, "score": 58789.34576583511 }, { "content": "/// A trait equivalent to `IntoIter<Item=Into<IpAddr>>` for `std::net::*` types.\n\npub trait IntoIpAddrs {\n\n /// Returned iterator over ip addresses which this type may correspond\n\n /// to.\n\n type IntoIter: Iterator<Item = IpAddr>;\n\n\n\n /// Converts this object to an iterator of resolved `IpAddr`s.\n\n fn into_ip_addrs(self) -> Self::IntoIter;\n\n}\n\n\n\nimpl IntoIpAddrs for IpAddr {\n\n type IntoIter = option::IntoIter<Self>;\n\n fn into_ip_addrs(self) -> Self::IntoIter {\n\n Some(self).into_iter()\n\n }\n\n}\n\n\n\nimpl IntoIpAddrs for Ipv4Addr {\n\n type IntoIter = option::IntoIter<IpAddr>;\n\n fn into_ip_addrs(self) -> Self::IntoIter {\n\n IpAddr::V4(self.to_owned()).into_ip_addrs()\n", "file_path": "libzmq/src/endpoint.rs", "rank": 94, "score": 56816.516757780686 }, { "content": "#[test]\n\nfn bindgen_test_layout_zmq_pollitem_t() {\n\n assert_eq!(\n\n ::std::mem::size_of::<zmq_pollitem_t>(),\n\n 16usize,\n\n concat!(\"Size of: \", stringify!(zmq_pollitem_t))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<zmq_pollitem_t>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(zmq_pollitem_t))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<zmq_pollitem_t>())).socket as *const _\n\n as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(zmq_pollitem_t),\n", "file_path": "libzmq-sys/src/bindings.rs", "rank": 95, "score": 55213.65805024793 }, { "content": "#[test]\n\nfn bindgen_test_layout_zmq_msg_t() {\n\n assert_eq!(\n\n ::std::mem::size_of::<zmq_msg_t>(),\n\n 64usize,\n\n concat!(\"Size of: \", stringify!(zmq_msg_t))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<zmq_msg_t>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(zmq_msg_t))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<zmq_msg_t>())).__ as *const _ as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(zmq_msg_t),\n\n \"::\",\n", "file_path": "libzmq-sys/src/bindings.rs", "rank": 96, "score": 55213.65805024793 }, { "content": "#[test]\n\nfn bindgen_test_layout_zmq_poller_event_t() {\n\n assert_eq!(\n\n ::std::mem::size_of::<zmq_poller_event_t>(),\n\n 32usize,\n\n concat!(\"Size of: \", stringify!(zmq_poller_event_t))\n\n );\n\n assert_eq!(\n\n ::std::mem::align_of::<zmq_poller_event_t>(),\n\n 8usize,\n\n concat!(\"Alignment of \", stringify!(zmq_poller_event_t))\n\n );\n\n assert_eq!(\n\n unsafe {\n\n &(*(::std::ptr::null::<zmq_poller_event_t>())).socket as *const _\n\n as usize\n\n },\n\n 0usize,\n\n concat!(\n\n \"Offset of field: \",\n\n stringify!(zmq_poller_event_t),\n", "file_path": "libzmq-sys/src/bindings.rs", "rank": 97, "score": 54182.30190517512 }, { "content": "#[cfg(feature = \"renew-bindings\")]\n\nfn gen_bindings(include_dir: &Path) {\n\n let args = vec![\"-DZMQ_BUILD_DRAFT_API=1\"];\n\n\n\n let bindings = bindgen::Builder::default()\n\n .header(include_dir.join(\"zmq.h\").to_string_lossy())\n\n .size_t_is_usize(true)\n\n .derive_default(true)\n\n .derive_eq(true)\n\n .derive_partialeq(true)\n\n .derive_debug(true)\n\n .derive_hash(true)\n\n .whitelist_function(\"^zmq_.*\")\n\n .whitelist_type(\"^zmq_.*\")\n\n .whitelist_var(\"^ZMQ_.*\")\n\n .clang_args(args)\n\n .generate()\n\n .expect(\"Unable to generate bindings\");\n\n\n\n let out_path = PathBuf::from(\"./src\").join(\"bindings.rs\");\n\n bindings\n\n .write_to_file(out_path)\n\n .expect(\"Couldn't write bindings!\");\n\n}\n\n\n", "file_path": "libzmq-sys/build.rs", "rank": 98, "score": 51119.44555294581 }, { "content": "#[derive(Copy, Clone, Debug)]\n\n#[allow(dead_code)]\n\nenum CtxOption {\n\n IOThreads,\n\n MaxSockets,\n\n MaxMsgSize,\n\n SocketLimit,\n\n IPV6,\n\n Blocky,\n\n}\n\n\n\nimpl From<CtxOption> for c_int {\n\n fn from(r: CtxOption) -> c_int {\n\n match r {\n\n CtxOption::IOThreads => sys::ZMQ_IO_THREADS as c_int,\n\n CtxOption::MaxSockets => sys::ZMQ_MAX_SOCKETS as c_int,\n\n CtxOption::MaxMsgSize => sys::ZMQ_MAX_MSGSZ as c_int,\n\n CtxOption::SocketLimit => sys::ZMQ_SOCKET_LIMIT as c_int,\n\n CtxOption::IPV6 => sys::ZMQ_IPV6 as c_int,\n\n CtxOption::Blocky => sys::ZMQ_BLOCKY as c_int,\n\n }\n\n }\n\n}\n\n\n", "file_path": "libzmq/src/ctx.rs", "rank": 99, "score": 46235.59806038627 } ]
Rust
rust/subproc/subproc.rs
ChristianVisintin/Brol
e53b663915697aa6543406db2f279e31826bff0c
/* * * Copyright (C) 2020 Christian Visintin - [email protected] * * This file is part of "Pyc" * * Pyc is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pyc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Pyc. If not, see <http://www.gnu.org/licenses/>. * */ extern crate nix; extern crate tempfile; extern crate uuid; use super::pipe::Pipe; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use std::path::PathBuf; use std::time::{Duration, Instant}; #[derive(Copy, Clone, PartialEq, std::fmt::Debug)] pub enum SubProcState { Running, Terminated, Unknown } #[derive(Copy, Clone, PartialEq, std::fmt::Debug)] pub enum SubProcError { CouldNotStartProcess, InvalidData, IoTimeout, SubProcStillRunning, SubProcTerminated, CouldNotKill, PipeError(nix::errno::Errno) } #[derive(std::fmt::Debug)] pub struct ShellProc { pub state: SubProcState, pub pid: i32, rc: u8, stdout_cache: Option<String>, stdin_pipe: Pipe, stdout_pipe: Pipe, stderr_pipe: Pipe } impl ShellProc { pub fn start(argv: Vec<String>) -> Result<ShellProc, SubProcError> { if argv.len() == 0 { return Err(SubProcError::CouldNotStartProcess) } let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let stdin_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stdin.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; let stderr_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stderr.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; let stdout_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stdout.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; match nix::unistd::fork() { Ok(nix::unistd::ForkResult::Parent { child, .. }) => { Ok(ShellProc { state: SubProcState::Running, pid: child.as_raw(), rc: 255, stdout_cache: None, stdin_pipe: stdin_pipe, stderr_pipe: stderr_pipe, stdout_pipe: stdout_pipe }) }, Ok(nix::unistd::ForkResult::Child) => { std::process::exit(ShellProc::run(argv, stdin_pipe.fd, stderr_pipe.fd, stdout_pipe.fd)); }, Err(_) => { return Err(SubProcError::CouldNotStartProcess) } } } pub fn cleanup(&mut self) -> Result<u8, SubProcError> { if self.read_state() != SubProcState::Terminated { return Err(SubProcError::SubProcStillRunning) } let _ = self.stdin_pipe.close(); let _ = self.stdout_pipe.close(); let _ = self.stderr_pipe.close(); Ok(self.rc) } pub fn raise(&self, signal: nix::sys::signal::Signal) -> Result<(), SubProcError> { match nix::sys::signal::kill(nix::unistd::Pid::from_raw(self.pid), signal) { Ok(_) => Ok(()), Err(_) => Err(SubProcError::CouldNotKill) } } pub fn kill(&self) -> Result<(), SubProcError> { self.raise(nix::sys::signal::Signal::SIGKILL) } pub fn read(&mut self) -> Result<(Option<String>, Option<String>), SubProcError> { let stdout: Option<String> = match self.stdout_pipe.read(50, false) { Ok(stdout) => stdout, Err(err) => return Err(err) }; let stderr: Option<String> = match self.stderr_pipe.read(50, false) { Ok(stderr) => match stderr { None => None, Some(stderr) => Some(stderr) }, Err(err) => return Err(err) }; Ok((stdout, stderr)) } pub fn write(&mut self, mut data: String) -> Result<(), SubProcError> { if self.read_state() == SubProcState::Terminated { return Err(SubProcError::SubProcTerminated) } self.stdin_pipe.write(data, 5000) } fn run(argv: Vec<String>, stdin: RawFd, stderr: RawFd, stdout: RawFd) -> i32 { if let Err(_) = nix::unistd::dup2(stdin, 0) { return 255 } if let Err(_) = nix::unistd::dup2(stdout, 1) { return 255 } if let Err(_) = nix::unistd::dup2(stderr, 2) { return 255 } let mut c_argv: Vec<CString> = Vec::with_capacity(argv.len()); for arg in argv.iter() { c_argv.push(CString::new(arg.as_str()).unwrap()); } let mut c_argv_refs: Vec<&CStr> = Vec::with_capacity(c_argv.len()); for arg in c_argv.iter() { c_argv_refs.push(arg); } if let Err(_) = nix::unistd::execvp(c_argv_refs.get(0).unwrap(), c_argv_refs.as_slice()) { return 255 } return 0 } pub fn read_state(&mut self) -> SubProcState { match nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(self.pid), Some(nix::sys::wait::WaitPidFlag::WNOHANG)) { Err(_) => {}, Ok(status) => match status { nix::sys::wait::WaitStatus::Exited(_, rc) => { self.state = SubProcState::Terminated; self.rc = rc as u8; }, nix::sys::wait::WaitStatus::Signaled(_, signal, _) => { self.state = SubProcState::Terminated; self.rc = signal as u8; }, _ => {}, } }; self.state } } impl Drop for ShellProc { fn drop(&mut self) { if let Err(_) = self.cleanup() { let _ = self.kill(); let _ = self.cleanup(); } } } #[cfg(test)] mod tests { use super::*; use nix::NixPath; use std::time::Duration; use std::thread::sleep; #[test] fn test_process_start_stop() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("sh")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); assert_eq!(shell_proc.state, SubProcState::Running); assert_ne!(shell_proc.pid, 0); assert_eq!(shell_proc.rc, 255); assert!(shell_proc.stdout_cache.is_none()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Running); assert!(shell_proc.kill().is_ok()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.state, SubProcState::Terminated); assert_eq!(shell_proc.rc, 9); assert!(shell_proc.cleanup().is_ok()); } #[test] fn test_process_start_error() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("piroporopero")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); sleep(Duration::from_millis(1000)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.rc, 255); } #[test] fn test_process_raise() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("sh")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Running); assert!(shell_proc.raise(nix::sys::signal::Signal::SIGINT).is_ok()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.rc, 2); } }
/* * * Copyright (C) 2020 Christian Visintin - [email protected] * * This file is part of "Pyc" * * Pyc is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pyc is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Pyc. If not, see <http://www.gnu.org/licenses/>. * */ extern crate nix; extern crate tempfile; extern crate uuid; use super::pipe::Pipe; use std::ffi::{CStr, CString}; use std::os::unix::io::RawFd; use std::path::PathBuf; use std::time::{Duration, Instant}; #[derive(Copy, Clone, PartialEq, std::fmt::Debug)] pub enum SubProcState { Running, Terminated, Unknown } #[derive(Copy, Clone, PartialEq, std::fmt::Debug)] pub enum SubProcError { CouldNotStartProcess, InvalidData, IoTimeout, SubProcStillRunning, SubProcTerminated, CouldNotKill, PipeError(nix::errno::Errno) } #[derive(std::fmt::Debug)] pub struct ShellProc { pub state: SubProcState, pub pid: i32, rc: u8, stdout_cache: Option<String>, stdin_pipe: Pipe, stdout_pipe: Pipe, stderr_pipe: Pipe } impl ShellProc { pub fn start(argv: Vec<String>) -> Result<ShellProc, SubProcError> { if argv.len() == 0 { return Err(SubProcError::CouldNotStartProcess) } let tmpdir: tempfile::TempDir = tempfile::TempDir::new().unwrap(); let stdin_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stdin.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; let stderr_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stderr.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; let stdout_pipe: Pipe = match Pipe::open(&tmpdir.path().join("stdout.fifo")) { Ok(p) => p, Err(err) => return Err(err) }; match nix::unistd::fork() { Ok(nix::unistd::ForkResult::Parent { child, .. }) => { Ok(ShellProc { state: SubProcState::Running, pid: child.as_raw(), rc: 255, stdout_cache: None, stdin_pipe: stdin_pipe, stderr_pipe: stderr_pipe, stdout_pipe: stdout_pipe }) }, Ok(nix::unistd::ForkResult::Child) => { std::process::exit(ShellProc::run(argv, stdin_pipe.fd, stderr_pipe.fd, stdout_pipe.fd)); }, Err(_) => { return Err(SubProcError::CouldNotStartProcess) } } } pub fn cleanup(&mut self) -> Result<u8, SubProcError> { if self.read_state() != SubProcState::Terminated { return Err(SubProcError::SubProcStillRunning) } let _ = self.stdin_pipe.close(); let _ = self.stdout_pipe.close(); let _ = self.stderr_pipe.close(); Ok(self.rc) } pub fn raise(&self, signal: nix::sys::signal::Signal) -> Result<(), SubProcError> { match nix::sys::signal::kill(nix::unistd::Pid::from_raw(self.pid), signal) { Ok(_) => Ok(()), Err(_) => Err(SubProcError::CouldNotKill) } } pub fn kill(&self) -> Result<(), SubProcError> { self.raise(nix::sys::signal::Signal::SIGKILL) } pub fn read(&mut self) -> Result<(Option<String>, Option<String>), SubProcError> { let stdout: Option<String> = match self.stdout_pipe.read(50, false) { Ok(stdout) => stdout, Err(err) => return Err(err) }; let stderr: Option<String> = match self.stderr_pipe.read(50, false) { Ok(stderr) => match stderr { None => None, Some(stderr) => Some(stderr) }, Err(err) => return Err(err) }; Ok((stdout, stderr)) } pub fn write(&mut self, mut data: String) -> Result<(), SubProcError> { if self.read_state() == SubProcState::Terminated { return Err(SubProcError::SubProcTerminated) } self.stdin_pipe.write(data, 5000) } fn run(argv: Vec<String>, stdin: RawFd, stderr: RawFd, stdout: RawFd) -> i32 { if let Err(_) = nix::unistd::dup2(stdin, 0) { return 255 } if let Err(_) = nix::unistd::dup2(stdout, 1) { return 255 } if let Err(_) = nix::unistd::dup2(stderr, 2) { return 255 } let mut c_argv: Vec<CString> = Vec::with_capacity(argv.len()); for arg in argv.iter() { c_argv.push(CString::new(arg.as_str()).unwrap()); } let mut c_argv_refs: Vec<&CStr> = Vec::with_capacity(c_argv.len()); for arg in c_argv.iter() { c_argv_refs.push(arg); } if let Err(_) = nix::unistd::execvp(c_argv_refs.get(0).unwrap(), c_argv_refs.as_slice()) { return 255 } return 0 } pub fn read_state(&mut self) -> SubProcState { match nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(self.pid), Some(nix::sys::wait::WaitPidFlag::WNOHANG)) { Err(_) => {}, Ok(status) => match status { nix::sys::wait::WaitStatus::Exited(_, rc) => { self.state = SubProcState::Terminated; self.rc = rc as u8; }, nix::sys::wait::WaitStatus::Signaled(_, signal, _) => { self.state = SubProcState::Terminated; self.rc = signal as u8; }, _ => {}, } }; self.state } } impl Drop for ShellProc { fn drop(&mut self) { if let Err(_) = self.cleanup() { let _ = self.kill(); let _ = self.cleanup(); } } } #[cfg(test)] mod tests { use super::*; use nix::NixPath; use std::time::Duration; use std::thread::sleep; #[test]
#[test] fn test_process_start_error() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("piroporopero")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); sleep(Duration::from_millis(1000)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.rc, 255); } #[test] fn test_process_raise() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("sh")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Running); assert!(shell_proc.raise(nix::sys::signal::Signal::SIGINT).is_ok()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.rc, 2); } }
fn test_process_start_stop() { let mut shell_proc: ShellProc = ShellProc::start(vec![String::from("sh")]).unwrap(); println!("A new subproc started with PID {}", shell_proc.pid); assert_eq!(shell_proc.state, SubProcState::Running); assert_ne!(shell_proc.pid, 0); assert_eq!(shell_proc.rc, 255); assert!(shell_proc.stdout_cache.is_none()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Running); assert!(shell_proc.kill().is_ok()); sleep(Duration::from_millis(500)); assert_eq!(shell_proc.read_state(), SubProcState::Terminated); assert_eq!(shell_proc.state, SubProcState::Terminated); assert_eq!(shell_proc.rc, 9); assert!(shell_proc.cleanup().is_ok()); }
function_block-full_function
[ { "content": "/// ### read_file\n\n/// \n\n/// Read entire file\n\npub fn read_file<P>(filename: P) -> io::Result<String> where P: AsRef<Path>, {\n\n std::fs::read_to_string(filename)\n\n}\n\n\n\n/// ### read_lines\n\n/// \n\n/// Read lines from file\n", "file_path": "rust/file-utils/file.rs", "rank": 0, "score": 230413.53606608542 }, { "content": "#[allow(dead_code)]\n\npub fn read_lines<P>(filename: P) -> io::Result<Vec<String>> where P: AsRef<Path>, {\n\n let file: File = File::open(filename)?;\n\n let reader = io::BufReader::new(file).lines();\n\n let mut lines: Vec<String> = Vec::new();\n\n for line in reader {\n\n if let Ok(line) = line {\n\n lines.push(line);\n\n }\n\n }\n\n Ok(lines)\n\n}\n\n\n\n/// ### write_lines\n\n/// \n\n/// Write lines to file\n", "file_path": "rust/file-utils/file.rs", "rank": 1, "score": 216946.04971366446 }, { "content": "#[allow(dead_code)]\n\npub fn write_lines<P>(filename: P, lines: Vec<String>) -> io::Result<()> where P: AsRef<Path> {\n\n match open_file(filename, true, true, false) {\n\n Ok(mut f) => {\n\n for line in lines.iter() {\n\n writeln!(f, \"{}\", line)?;\n\n }\n\n Ok(())\n\n },\n\n Err(err) => Err(err)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::io::Write;\n\n\n\n #[test]\n\n fn test_utils_file_open() {\n\n let tmpfile: tempfile::NamedTempFile = tempfile::NamedTempFile::new().unwrap();\n", "file_path": "rust/file-utils/file.rs", "rank": 2, "score": 210297.3061360088 }, { "content": "/// ### open_file\n\n/// \n\n/// Open file provided as parameter\n\npub fn open_file<P>(filename: P, create: bool, write: bool, append: bool) -> io::Result<File> where P: AsRef<Path>, {\n\n OpenOptions::new().create(create).write(write).append(append).truncate(!append).open(filename)\n\n}\n\n\n", "file_path": "rust/file-utils/file.rs", "rank": 3, "score": 179541.38086950494 }, { "content": "/// ### to_input_event\n\n/// \n\n/// Get input through callback and convert it to an Input Event\n\nfn to_input_event(ready_fn: &dyn Fn() -> bool, read_fn: &dyn Fn(&mut [u8]) -> io::Result<()>) -> Option<InputEvent> {\n\n //Configure terminal\n\n match ready_fn() {\n\n false => None,\n\n true => {\n\n //Read\n\n let mut buf: Vec<u8> = vec![0u8; 1];\n\n let _ = read_fn(&mut buf);\n\n //Handle input\n\n let key: u8 = *buf.get(0).unwrap_or(&0);\n\n let ev: InputEvent = match key {\n\n 8 | 127 => InputEvent::Backspace,\n\n 10 => InputEvent::Enter,\n\n 13 => InputEvent::CarriageReturn,\n\n 0..=26 => InputEvent::Ctrl(key), //CTRL key (exclude 8, 10, 13)\n\n 27 => { //Is Arrow Key\n\n //Read twice\n\n let _ = read_fn(&mut buf);\n\n let _ = read_fn(&mut buf);\n\n let direction: char = *buf.get(0).unwrap_or(&0) as char;\n", "file_path": "rust/console/console.rs", "rank": 4, "score": 177030.35872871228 }, { "content": "fn run_test_copy(name: &str, mut client: impl RemoteFs, cycles: usize) {\n\n let dest = Path::new(\"/tmp/test.bin\");\n\n println!(\"TEST: {}\", name);\n\n assert!(client.connect().is_ok());\n\n let mut avg = Duration::ZERO;\n\n // Loop over cycles\n\n for n in 0..cycles {\n\n let mut file =\n\n File::open(\"/tmp/data.bin\").expect(\"You need to put a file /tmp/data.bin to run this\");\n\n let file_size: u64 = file.seek(std::io::SeekFrom::End(0)).unwrap_or(0);\n\n // rewind\n\n file.seek(std::io::SeekFrom::Start(0))\n\n .expect(\"Could not rewind\");\n\n let t_start = Instant::now();\n\n client\n\n .create_file(dest, &Metadata::default().size(file_size), Box::new(file))\n\n .expect(\"Failed to create file\");\n\n avg += t_start.elapsed();\n\n println!(\n\n \"Cycle {:02} took {}us ({}ms)\",\n", "file_path": "rust/remotefs-ssh/src/main.rs", "rank": 5, "score": 167214.5695958198 }, { "content": "fn spawn_stdin_channel() -> Receiver<String> {\n\n let (tx, rx) = mpsc::channel::<String>();\n\n thread::spawn(move || loop {\n\n let mut buffer = String::new();\n\n io::stdin().read_line(&mut buffer).unwrap();\n\n tx.send(buffer).unwrap();\n\n });\n\n rx\n\n}\n\n\n", "file_path": "rust/ssh-client/main.rs", "rank": 6, "score": 155967.779904009 }, { "content": "fn run_test(name: &str, mut client: impl RemoteFs, cycles: usize) {\n\n let dest = Path::new(\"/tmp/test.bin\");\n\n println!(\"TEST: {}\", name);\n\n assert!(client.connect().is_ok());\n\n let mut avg = Duration::ZERO;\n\n // Loop over cycles\n\n for n in 0..cycles {\n\n let mut file =\n\n File::open(\"/tmp/data.bin\").expect(\"You need to put a file /tmp/data.bin to run this\");\n\n let file_size: u64 = file.seek(std::io::SeekFrom::End(0)).unwrap_or(0);\n\n // rewind\n\n file.seek(std::io::SeekFrom::Start(0))\n\n .expect(\"Could not rewind\");\n\n let t_start = Instant::now();\n\n let mut writer = client\n\n .create(dest, &Metadata::default().size(file_size))\n\n .ok()\n\n .unwrap();\n\n let mut bytes: usize = 0;\n\n while bytes < (file_size as usize) {\n", "file_path": "rust/remotefs-ssh/src/main.rs", "rank": 7, "score": 148511.82239586837 }, { "content": "/// ### print\n\n/// \n\n/// print on this line without newline\n\npub fn print(row: String) {\n\n print!(\"{}\", row);\n\n let _ = io::stdout().flush();\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 8, "score": 148102.75132195035 }, { "content": "/// ### println\n\n/// \n\n/// Print line and go to new line\n\npub fn println(row: String) {\n\n println!(\"{}\", row);\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 9, "score": 148098.47172393848 }, { "content": "fn trim_newline(s: &mut String) {\n\n if s.ends_with('\\n') {\n\n s.pop();\n\n if s.ends_with('\\r') {\n\n s.pop();\n\n }\n\n }\n\n}\n\n\n\n/// ### read_cmd\n\n///\n\n/// Read user command\n\n\n", "file_path": "rust/sftp-client/main.rs", "rank": 10, "score": 144722.54262183284 }, { "content": "fn trim_newline(s: &mut String) {\n\n if s.ends_with('\\n') {\n\n s.pop();\n\n if s.ends_with('\\r') {\n\n s.pop();\n\n }\n\n }\n\n}\n", "file_path": "rust/ssh-client/main.rs", "rank": 11, "score": 144722.54262183286 }, { "content": "/// ### read\n\n/// \n\n/// Read user input and returns an individual InputEvent (or None)\n\npub fn read() -> Option<InputEvent> {\n\n let stdin_read = |buff: &mut [u8]| -> io::Result<()> {\n\n io::stdin().read_exact(buff)\n\n };\n\n prepare_termios();\n\n let ev: Option<InputEvent> = to_input_event(&input_ready, &stdin_read);\n\n reset_termios();\n\n ev\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 12, "score": 144690.4610858087 }, { "content": "fn input() -> String {\n\n print!(\">> \");\n\n let _ = io::stdout().flush();\n\n let mut input: String = String::new();\n\n io::stdin()\n\n .read_line(&mut input)\n\n .expect(\"Failed to read stdin\");\n\n input\n\n}\n", "file_path": "rust/rabbitmq/src/publisher.rs", "rank": 13, "score": 144443.96401045864 }, { "content": "/// ### carriage_return\n\n/// \n\n/// Return to the beginning of the line\n\npub fn carriage_return() {\n\n print(String::from(\"\\r\"));\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 14, "score": 144321.09074042112 }, { "content": "/// ### input_event_to_string\n\n/// \n\n/// Converts an input event to a string\n\npub fn input_event_to_string(ev: InputEvent) -> String {\n\n match ev {\n\n InputEvent::ArrowDown => String::from(\"\\x1b[B\"),\n\n InputEvent::ArrowLeft => String::from(\"\\x1b[D\"),\n\n InputEvent::ArrowRight => String::from(\"\\x1b[C\"),\n\n InputEvent::ArrowUp => String::from(\"\\x1b[A\"),\n\n InputEvent::Backspace => String::from(\"\\x7F\"),\n\n InputEvent::CarriageReturn => String::from(\"\\x0D\"),\n\n InputEvent::Ctrl(sig) => {\n\n let ch = sig as char;\n\n let mut s = String::new();\n\n s.push(ch);\n\n s\n\n },\n\n InputEvent::Enter => String::from(\"\\x0A\"),\n\n InputEvent::Key(k) => String::from(k)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "rust/console/console.rs", "rank": 15, "score": 140298.29242723403 }, { "content": "/// ### deserialize\n\n///\n\n/// Read data from readable and deserialize its content as TOML\n\npub fn deserialize<R, S>(mut readable: R) -> Result<S, SerializerError>\n\nwhere\n\n R: Read,\n\n S: DeserializeOwned + Sized + std::fmt::Debug,\n\n{\n\n // Read file content\n\n let mut data: String = String::new();\n\n if let Err(err) = readable.read_to_string(&mut data) {\n\n return Err(SerializerError::new(\n\n SerializerErrorKind::Io,\n\n err.to_string(),\n\n ));\n\n }\n\n // Deserialize\n\n match toml::de::from_str(data.as_str()) {\n\n Ok(deserialized) => Ok(deserialized),\n\n Err(err) => Err(SerializerError::new(\n\n SerializerErrorKind::Syntax,\n\n err.to_string(),\n\n )),\n\n }\n\n}\n\n\n", "file_path": "rust/key-event-serde/src/main.rs", "rank": 16, "score": 131770.85389676766 }, { "content": "/// ### rewrite\n\n/// \n\n/// Rewrite current stdout line\n\npub fn rewrite(row: String, len: usize) {\n\n for _ in 0..len {\n\n backspace();\n\n }\n\n print(row);\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 17, "score": 130728.37897303724 }, { "content": " MessageData data;\n", "file_path": "c/union/union.c", "rank": 18, "score": 127435.86501015152 }, { "content": "pub fn serialize<S, W>(serializable: &S, mut writable: W) -> Result<(), SerializerError>\n\nwhere\n\n S: Serialize + Sized,\n\n W: Write,\n\n{\n\n // Serialize content\n\n let data: String = match toml::ser::to_string(serializable) {\n\n Ok(dt) => dt,\n\n Err(err) => {\n\n return Err(SerializerError::new(\n\n SerializerErrorKind::Serialization,\n\n err.to_string(),\n\n ))\n\n }\n\n };\n\n // Write file\n\n match writable.write_all(data.as_bytes()) {\n\n Ok(_) => Ok(()),\n\n Err(err) => Err(SerializerError::new(\n\n SerializerErrorKind::Io,\n", "file_path": "rust/key-event-serde/src/main.rs", "rank": 19, "score": 126479.54848617781 }, { "content": "fn main() -> Result<(), ()> {\n\n \n\n let mut view: UserView = UserView::default();\n\n // Add 2 users\n\n view.add_user(String::from(\"omar\"), 32);\n\n view.add_user(String::from(\"pippo\"), 27);\n\n assert!(view.selected.is_none());\n\n assert_eq!(view.users.len(), 2);\n\n // Select user\n\n view.select_user(\"omar\");\n\n assert!(view.selected.is_some());\n\n println!(\"Selected user: {}, age: {}\", view.selected.as_ref().unwrap().username, view.selected.as_ref().unwrap().age);\n\n // Remove user\n\n view.del_user(\"pippo\");\n\n println!(\"Selected user: {}, age: {}\", view.selected.as_ref().unwrap().username, view.selected.as_ref().unwrap().age);\n\n assert_eq!(view.users.len(), 1);\n\n assert!(view.selected.is_some());\n\n view.del_user(\"omar\");\n\n assert!(view.selected.is_none());\n\n assert_eq!(view.users.len(), 0);\n\n println!(\"Selected user: None\");\n\n\n\n Ok(())\n\n}\n", "file_path": "rust/refcounter/main.rs", "rank": 20, "score": 115112.07716181278 }, { "content": "/// ### backspace\n\n/// \n\n/// Remove last typed character from prompt\n\npub fn backspace() {\n\n //To backspace we have to go back of 1 position, print blank and go back again\n\n print(String::from(\"\\x08 \\x08\"));\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 21, "score": 114828.85187090951 }, { "content": "/// ### clear\n\n/// \n\n/// Clear console\n\npub fn clear() {\n\n print(String::from(\"\\x1b[H\\x1b[2J\"));\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 22, "score": 114828.85187090951 }, { "content": "fn main() -> Result<()> {\n\n // Get opts\n\n let args: Vec<String> = std::env::args().collect();\n\n let queue_name: &String = args.get(1).expect(USAGE);\n\n // Init\n\n let connection: Connection = executor::block_on(Connection::connect(\n\n \"amqp://localhost\",\n\n ConnectionProperties::default(),\n\n ))?;\n\n let channel: Channel = executor::block_on(connection.create_channel())?;\n\n let _ = executor::block_on(channel.queue_declare(\n\n queue_name,\n\n QueueDeclareOptions::default(),\n\n FieldTable::default(),\n\n ))?;\n\n let _ = executor::block_on(channel.queue_bind(\n\n queue_name,\n\n \"random\",\n\n \"this.routing\",\n\n QueueBindOptions::default(),\n", "file_path": "rust/rabbitmq/src/consumer.rs", "rank": 23, "score": 112239.83071251216 }, { "content": "fn read_cmd() -> String {\n\n print!(\">> \");\n\n // Flush\n\n io::stdout().flush().unwrap();\n\n // Read\n\n let mut command = String::new();\n\n let _ = io::stdin().read_line(&mut command);\n\n // Trim\n\n trim_newline(&mut command);\n\n // Return\n\n command\n\n}\n\n\n\n// @! SFTP library\n\n\n\nimpl SftpClient {\n\n pub fn new(session: &Session) -> SftpClient {\n\n // Get wrkdir\n\n let sftp_cli: Sftp = session.sftp().unwrap();\n\n let currdir: PathBuf = sftp_cli.realpath(PathBuf::from(\".\").as_path()).unwrap();\n", "file_path": "rust/sftp-client/main.rs", "rank": 24, "score": 109482.08643573325 }, { "content": "fn gen_key() -> String {\n\n rand::thread_rng()\n\n .sample_iter(Alphanumeric)\n\n .take(256)\n\n .collect::<String>()\n\n}\n\n\n", "file_path": "rust/magic-crypt/main.rs", "rank": 25, "score": 109482.08643573325 }, { "content": "pub fn move_cursor_right() {\n\n print(String::from(\"\\x1b[1C\"));\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 26, "score": 109329.32513374869 }, { "content": "pub fn move_cursor_left() {\n\n print(String::from(\"\\x1b[1D\"));\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 27, "score": 109329.32513374869 }, { "content": "pub fn help() {\n\n println!(\"CD <dir> Change working directory\");\n\n println!(\"GET <file> <dest> Download `file` to `dest`\");\n\n println!(\"HELP Print this help\");\n\n println!(\"LIST [dir] List files in directory\");\n\n println!(\"MKDIR <dir> Make directory\");\n\n println!(\"PUT <file> <dest> Upload local file `file` to `dest`\");\n\n println!(\"PWD Print working directory\");\n\n println!(\"QUIT Quit suppaftp\");\n\n println!(\"RM <file> Remove file\");\n\n println!(\"STAT <file> Stat `file`\");\n\n println!();\n\n}\n", "file_path": "rust/aws-s3-cli/src/main.rs", "rank": 28, "score": 106905.20587294901 }, { "content": "/// ## StoreState\n\n///\n\n/// Store state describes a value in the store\n\nenum StoreState {\n\n Str(String), // String\n\n Signed(isize), // Signed number\n\n Unsigned(usize), // Unsigned number\n\n Float(f64), // Floating point number\n\n Boolean(bool), // Boolean value\n\n Flag, // Empty value; used to work as a Flag (set unset)\n\n}\n\n\n\n// -- store\n\n\n\n/// ## Store\n\n///\n\n/// Store represent the key-value store\n\n/// The store is a key-value hash map. Each key must be unique\n\n/// To each key a `StoreState` is assigned\n\npub(crate) struct Store {\n\n store: HashMap<String, StoreState>,\n\n}\n\n\n", "file_path": "rust/store/store.rs", "rank": 29, "score": 96350.53636908701 }, { "content": "fn main() {\n\n // Get opts\n\n let args: Vec<String> = std::env::args().collect();\n\n let queue_name: &String = args.get(1).expect(USAGE);\n\n // Init\n\n let connection = match executor::block_on(Connection::connect(\n\n \"amqp://localhost\",\n\n ConnectionProperties::default(),\n\n )) {\n\n Err(err) => {\n\n eprintln!(\"Connection error: {}\", err);\n\n exit(1);\n\n }\n\n Ok(c) => c,\n\n };\n\n loop {\n\n let payload = input();\n\n let channel: Channel = executor::block_on(connection.create_channel())\n\n .ok()\n\n .unwrap();\n", "file_path": "rust/rabbitmq/src/publisher.rs", "rank": 30, "score": 94841.19506362268 }, { "content": "fn main() {\n\n assert_eq!(\n\n ErrorCode::try_from(160).ok().unwrap(),\n\n ErrorCode::ItsRainingEggs\n\n );\n\n assert_eq!(\n\n ErrorCode::try_from(31).ok().unwrap(),\n\n ErrorCode::ShopIsClosed\n\n );\n\n assert_eq!(\n\n ErrorCode::try_from(16).ok().unwrap(),\n\n ErrorCode::CartIsEmpty\n\n );\n\n assert_eq!(\n\n ErrorCode::try_from(4).ok().unwrap(),\n\n ErrorCode::BadCreditCard\n\n );\n\n assert!(ErrorCode::try_from(1).is_err());\n\n}\n", "file_path": "rust/c-enums/src/main.rs", "rank": 31, "score": 94832.19431393887 }, { "content": "int main(int argc, char** argv) {\n\n\n\n if (argc < 6) {\n\n printf(\"Usage: %s <device> <red> <green> <blue> <even/odd>\\n\", argv[0]);\n\n return 255;\n\n }\n\n int rc = 0;\n\n const char* device = argv[1];\n\n const uint8_t red = atoi(argv[2]);\n\n const uint8_t green = atoi(argv[3]);\n\n const uint8_t blue = atoi(argv[4]);\n\n const uint8_t is_odd = (strcmp(argv[5], \"odd\") == 0) ? 1 : 0;\n\n FramebufferColor color;\n\n FramebufferColorRGB24 color_ptr24;\n\n color_ptr24.blue = blue;\n\n color_ptr24.green = green;\n\n color_ptr24.red = red;\n\n FramebufferColorRGB32 color_ptr32;\n\n color_ptr32.blue = blue;\n\n color_ptr32.alpha = 255;\n\n color_ptr32.green = green;\n\n color_ptr32.red = red;\n\n FramebufferColorRGB16 color_ptr16;\n\n color_ptr16.blue = blue;\n\n color_ptr16.green = green;\n\n color_ptr16.red = red;\n\n //Instantiate framebuffer\n\n Framebuffer* fb = NULL;\n\n FB_Error error;\n\n if ((error = framebuffer_init(&fb, 0)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not initialize framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Open framebuffer\n\n if ((error = framebuffer_open(fb, device)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not open framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Assign color\n\n if (fb->depth == 24) {\n\n color.color_ptr = (void*) &color_ptr24;\n\n color.syntax = Color_RGB24;\n\n } else if (fb->depth == 32) {\n\n color.color_ptr = (void*) &color_ptr32;\n\n color.syntax = Color_RGB32;\n\n printf(\"Color depth 32\\n\");\n\n } else if (fb->depth == 16) {\n\n color.color_ptr = (void*) &color_ptr16;\n\n color.syntax = Color_RGB16;\n\n } else {\n\n printf(\"Unknown depth %u\\n\", fb->depth);\n\n goto cleanup;\n\n }\n\n framebuffer_clear(fb);\n\n //Write framebuffer\n\n for (size_t y = 0; y < fb->height; y++) {\n\n for (size_t x = 0; x < fb->width; x++) {\n\n uint8_t row_is_odd = (y % 2 == 0 && x % 2 == 1) || (x % 2 == 0 && y % 2 == 1) ? 1 : 0;\n\n if (is_odd && row_is_odd) {\n\n if ((error = framebuffer_write(fb, x, y, &color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not write pixel at (%lu, %lu): %s\\n\", x, y, framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n } else if (is_odd == 0 && row_is_odd == 0) {\n\n if ((error = framebuffer_write(fb, x, y, &color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not write pixel at (%lu, %lu): %s\\n\", x, y, framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n }\n\n }\n\n }\n\n \n\ncleanup:\n\n if (framebuffer_isopen(fb) == FRAMEBUFFER_ERROR_SUCCESS) {\n\n if ((error = framebuffer_close(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not close framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n }\n\n if ((error = framebuffer_cleanup(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not cleanup framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n return rc;\n", "file_path": "c/easyfb/tests/test-chess/chess.c", "rank": 32, "score": 92933.8967461804 }, { "content": "int main(int argc, char** argv) {\n\n\n\n if (argc < 3) {\n\n printf(\"Usage: %s <device> <outfile>\\n\", argv[0]);\n\n return 255;\n\n }\n\n int rc = 0;\n\n const char* device = argv[1];\n\n const char* outfile = argv[2];\n\n //Instantiate framebuffer\n\n Framebuffer* fb = NULL;\n\n FB_Error error;\n\n //RGB\n\n uint8_t* rgb_buffer = NULL;\n\n size_t rgb_buffer_size = 0;\n\n //BMP\n\n size_t bmp_size;\n\n uint8_t* out_bmp = NULL;\n\n //File\n\n FILE* out_file_ptr = NULL;\n\n //Init\n\n if ((error = framebuffer_init(&fb, 0)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not initialize framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Open framebuffer\n\n if ((error = framebuffer_open(fb, device)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not open framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Dump\n\n rgb_buffer_size = fb->width * fb->height * 3;\n\n rgb_buffer = (uint8_t*) malloc(sizeof(uint8_t) * rgb_buffer_size);\n\n if (rgb_buffer == NULL) {\n\n printf(\"Could not allocate RGB buffer\\n\");\n\n rc = 1;\n\n goto cleanup;\n\n }\n\n for (size_t y = 0; y < fb->height; y++) {\n\n for (size_t x = 0; x < fb->width; x++) {\n\n FramebufferColor* color = NULL;\n\n if ((error = framebuffer_read(fb, x, y, &color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n color_cleanup(color);\n\n rc = 1;\n\n printf(\"Could not read from framebuffer at (%lu, %lu): %s\\n\", x, y, framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Push color to rgb buffer\n\n size_t index = ((fb->width * y) + x) * 3;\n\n switch (color->syntax) {\n\n case Color_RGB16: {\n\n FramebufferColorRGB16* color_ptr = (FramebufferColorRGB16*) color->color_ptr;\n\n rgb_buffer[index++] = color_ptr->red;\n\n rgb_buffer[index++] = color_ptr->green;\n\n rgb_buffer[index++] = color_ptr->blue;\n\n break;\n\n }\n\n case Color_RGB24: {\n\n FramebufferColorRGB24* color_ptr = (FramebufferColorRGB24*) color->color_ptr;\n\n rgb_buffer[index++] = color_ptr->red;\n\n rgb_buffer[index++] = color_ptr->green;\n\n rgb_buffer[index++] = color_ptr->blue;\n\n break;\n\n }\n\n case Color_RGB32: {\n\n FramebufferColorRGB32* color_ptr = (FramebufferColorRGB32*) color->color_ptr;\n\n rgb_buffer[index++] = color_ptr->red;\n\n rgb_buffer[index++] = color_ptr->green;\n\n rgb_buffer[index++] = color_ptr->blue;\n\n break;\n\n }\n\n default: {\n\n color_cleanup(color);\n\n rc = 1;\n\n printf(\"Unknown depth %u\\n\", fb->depth);\n\n goto cleanup;\n\n }\n\n }\n\n //Cleanup color\n\n color_cleanup(color);\n\n }\n\n }\n\n //Dump to BMP\n\n out_bmp = buffer_to_bmp(rgb_buffer, rgb_buffer_size, fb->width, fb->height, &bmp_size);\n\n if (out_bmp == NULL) {\n\n printf(\"Failed to encode framebuffer to BMP\\n\");\n\n rc = 2;\n\n goto cleanup;\n\n }\n\n //Dump to file\n\n out_file_ptr = fopen(outfile, \"wb\");\n\n if (out_file_ptr == NULL) {\n\n printf(\"Could not open out file %s\\n\", outfile);\n\n rc = 3;\n\n goto cleanup;\n\n }\n\n for (size_t i = 0; i < bmp_size; i++) {\n\n if (fwrite(&out_bmp[i], sizeof(uint8_t), 1, out_file_ptr) != 1) {\n\n printf(\"Failed to write byte %lu to file %s\\n\", i, outfile);\n\n rc = 3;\n\n goto cleanup;\n\n }\n\n }\n\n fclose(out_file_ptr);\n\n printf(\"Written %lu bytes to %s\\n\", bmp_size, outfile);\n\n \n\ncleanup:\n\n if (rgb_buffer != NULL) {\n\n free(rgb_buffer);\n\n rgb_buffer = NULL;\n\n }\n\n if (out_bmp != NULL) {\n\n free(out_bmp);\n\n out_bmp = NULL;\n\n }\n\n if (framebuffer_isopen(fb) == FRAMEBUFFER_ERROR_SUCCESS) {\n\n if ((error = framebuffer_close(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not close framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n }\n\n if ((error = framebuffer_cleanup(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not cleanup framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n return rc;\n", "file_path": "c/easyfb/tests/test-read/fbread.c", "rank": 33, "score": 92933.8967461804 }, { "content": "int main(int argc, char** argv) {\n\n\n\n if (argc < 5) {\n\n printf(\"Usage: %s <device> <red> <green> <blue>\\n\", argv[0]);\n\n return 255;\n\n }\n\n int rc = 0;\n\n const char* device = argv[1];\n\n const uint8_t red = atoi(argv[2]);\n\n const uint8_t green = atoi(argv[3]);\n\n const uint8_t blue = atoi(argv[4]);\n\n FramebufferColor color;\n\n FramebufferColorRGB24 color_ptr24;\n\n color_ptr24.blue = blue;\n\n color_ptr24.green = green;\n\n color_ptr24.red = red;\n\n FramebufferColorRGB32 color_ptr32;\n\n color_ptr32.blue = blue;\n\n color_ptr32.alpha = 255;\n\n color_ptr32.green = green;\n\n color_ptr32.red = red;\n\n FramebufferColorRGB16 color_ptr16;\n\n color_ptr16.blue = blue;\n\n color_ptr16.green = green;\n\n color_ptr16.red = red;\n\n //Instantiate framebuffer\n\n Framebuffer* fb = NULL;\n\n FB_Error error;\n\n if ((error = framebuffer_init(&fb, 0)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not initialize framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Open framebuffer\n\n if ((error = framebuffer_open(fb, device)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not open framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n //Assign color\n\n if (fb->depth == 24) {\n\n color.color_ptr = (void*) &color_ptr24;\n\n color.syntax = Color_RGB24;\n\n } else if (fb->depth == 32) {\n\n color.color_ptr = (void*) &color_ptr32;\n\n color.syntax = Color_RGB32;\n\n printf(\"Color depth 32\\n\");\n\n } else if (fb->depth == 16) {\n\n color.color_ptr = (void*) &color_ptr16;\n\n color.syntax = Color_RGB16;\n\n } else {\n\n printf(\"Unknown depth %u\\n\", fb->depth);\n\n goto cleanup;\n\n }\n\n //Write framebuffer\n\n for (size_t y = 0; y < fb->height; y++) {\n\n for (size_t x = 0; x < fb->width; x++) {\n\n if ((error = framebuffer_write(fb, x, y, &color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n rc = 1;\n\n printf(\"Could not write pixel at (%lu, %lu): %s\\n\", x, y, framebuffer_get_error_desc(error));\n\n goto cleanup;\n\n }\n\n }\n\n }\n\n \n\ncleanup:\n\n if (framebuffer_isopen(fb) == FRAMEBUFFER_ERROR_SUCCESS) {\n\n if ((error = framebuffer_close(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not close framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n }\n\n if ((error = framebuffer_cleanup(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n printf(\"Could not cleanup framebuffer: %s\\n\", framebuffer_get_error_desc(error));\n\n }\n\n return rc;\n", "file_path": "c/easyfb/tests/test-write/fbwrite.c", "rank": 34, "score": 92933.8967461804 }, { "content": "class FileHandler : public QObject\n\n{\n\n Q_OBJECT\n\n\n\npublic:\n\n FileHandler(QObject *parent = 0) : QObject(parent) {\n\n }\n\n Q_INVOKABLE bool writeFile(QString filePath, QString content, QChar mode);\n\n Q_INVOKABLE QString readFile(QString filePath);\n\n Q_INVOKABLE bool deleteFile(QString filePath);\n\n};\n\n\n\n#endif // FILEHANDLER_H\n", "file_path": "qt/FileHandler/filehandler.h", "rank": 35, "score": 91596.90835406308 }, { "content": "uint8_t* buffer_to_bmp(const uint8_t* buffer, const size_t bufferSize, const size_t width, const size_t height, size_t* bmp_size) {\n\n //Get sizes\n\n const size_t bitsPerPixel = 24;\n\n const size_t nextMultipleOf4 = roundToMultiple(width * (bitsPerPixel / 8), 4);\n\n const size_t paddingSize = nextMultipleOf4 - width * (size_t) (bitsPerPixel / 8);\n\n const size_t totalRowSize = (width * (size_t) (bitsPerPixel / 8)) + paddingSize;\n\n const size_t realRowSize = (width * (size_t) (bitsPerPixel / 8));\n\n const size_t dataSize = totalRowSize * height;\n\n const size_t fileSize = 54 + dataSize;\n\n //Reserve bmo buffer\n\n uint8_t* bmp_buffer = (uint8_t*) malloc(sizeof(uint8_t) * (fileSize));\n\n if (bmp_buffer == NULL) {\n\n *bmp_size = 0;\n\n return NULL;\n\n }\n\n *bmp_size = fileSize * sizeof(uint8_t);\n\n //Set bmp 24\n\n //Write 54 Bytes header\n\n //'BM'\n\n bmp_buffer[0] = 0x42;\n\n bmp_buffer[1] = 0x4D;\n\n //Write filesize; we need to found it first\n\n bmp_buffer[2] = fileSize & 255;\n\n bmp_buffer[3] = (fileSize >> 8) & 255;\n\n bmp_buffer[4] = (fileSize >> 16) & 255;\n\n bmp_buffer[5] = (fileSize >> 24) & 255;\n\n //Reserved\n\n bmp_buffer[6] = 0; \n\n bmp_buffer[7] = 0; \n\n bmp_buffer[8] = 0;\n\n bmp_buffer[9] = 0;\n\n //Data offset\n\n const size_t dataOffset = 54;\n\n bmp_buffer[10] = dataOffset & 255;\n\n bmp_buffer[11] = (dataOffset >> 8) & 255;\n\n bmp_buffer[12] = (dataOffset >> 16) & 255;\n\n bmp_buffer[13] = (dataOffset >> 24) & 255;\n\n //DibSize\n\n bmp_buffer[14] = 40; \n\n bmp_buffer[15] = 0; \n\n bmp_buffer[16] = 0; \n\n bmp_buffer[17] = 0;\n\n //Width\n\n bmp_buffer[18] = width & 255;\n\n bmp_buffer[19] = (width >> 8) & 255; \n\n bmp_buffer[20] = (width >> 16) & 255;\n\n bmp_buffer[21] = (width >> 24) & 255;\n\n //Height\n\n bmp_buffer[22] = height & 255;\n\n bmp_buffer[23] = (height >> 8) & 255; \n\n bmp_buffer[24] = (height >> 16) & 255;\n\n bmp_buffer[25] = (height >> 24) & 255;\n\n //Color planes\n\n bmp_buffer[26] = 1;\n\n bmp_buffer[27] = 0;\n\n //Bits per pixel\n\n bmp_buffer[28] = bitsPerPixel & 255;\n\n bmp_buffer[29] = (bitsPerPixel >> 8 ) & 255;\n\n //biRGB\n\n bmp_buffer[30] = 0; \n\n bmp_buffer[31] = 0; \n\n bmp_buffer[32] = 0; \n\n bmp_buffer[33] = 0;\n\n //Data size\n\n bmp_buffer[34] = (dataSize & 255);\n\n bmp_buffer[35] = (dataSize >> 8) & 255; \n\n bmp_buffer[36] = (dataSize >> 16) & 255;\n\n bmp_buffer[37] = (dataSize >> 24) & 255;\n\n //Print size Width\n\n bmp_buffer[38] = 0;\n\n bmp_buffer[39] = 0; \n\n bmp_buffer[40] = 0;\n\n bmp_buffer[41] = 0;\n\n //Print size Height\n\n bmp_buffer[42] = 0;\n\n bmp_buffer[43] = 0; \n\n bmp_buffer[44] = 0;\n\n bmp_buffer[45] = 0;\n\n //Palette\n\n bmp_buffer[46] = 0; \n\n bmp_buffer[47] = 0; \n\n bmp_buffer[48] = 0; \n\n bmp_buffer[49] = 0;\n\n //Important colors\n\n bmp_buffer[50] = 0; \n\n bmp_buffer[51] = 0; \n\n bmp_buffer[52] = 0; \n\n bmp_buffer[53] = 0;\n\n //Store pixels\n\n int rowPositionCounter = 0;\n\n int px_index = (int) (bufferSize - (width * 3)); //Last row, left\n\n size_t buffRowPositionCounter = 0;\n\n for (size_t dataPtr = dataOffset; dataPtr < fileSize - 1 && px_index >= 0;) {\n\n bmp_buffer[dataPtr++] = buffer[px_index + 2]; //B\n\n bmp_buffer[dataPtr++] = buffer[px_index + 1]; //G\n\n bmp_buffer[dataPtr++] = buffer[px_index]; //R\n\n px_index += 3;\n\n buffRowPositionCounter++;\n\n if (buffRowPositionCounter == width) {\n\n px_index -= (width * 2 * 3);\n\n buffRowPositionCounter = 0;\n\n }\n\n rowPositionCounter += 3;\n\n if (rowPositionCounter >= realRowSize) {\n\n rowPositionCounter = 0;\n\n for (size_t i = 0; i < paddingSize; i++) {\n\n bmp_buffer[dataPtr++] = 0;\n\n }\n\n }\n\n }\n\n return bmp_buffer;\n", "file_path": "c/easyfb/tests/test-read/fbread.c", "rank": 36, "score": 89969.7632854637 }, { "content": "size_t roundToMultiple(const size_t toRound, const size_t multiple) {\n\n if (multiple == 0)\n\n return toRound;\n\n\n\n const size_t remainder = toRound % multiple;\n\n if (remainder == 0)\n\n return toRound;\n\n\n\n return toRound + multiple - remainder;\n", "file_path": "c/easyfb/tests/test-read/fbread.c", "rank": 37, "score": 89969.7632854637 }, { "content": "#define _GNU_SOURCE\n\n\n", "file_path": "c/sigint/sigint.c", "rank": 38, "score": 88811.1746715202 }, { "content": " size_t data_size;\n", "file_path": "c/union/union.c", "rank": 39, "score": 88794.54639774447 }, { "content": "#define MAX_DATA_SIZE 256\n\n\n", "file_path": "c/union/union.c", "rank": 40, "score": 85289.34528748595 }, { "content": "/// ### instant_to_str\n\n///\n\n/// Format a `Instant` into a time string\n\nfn time_to_str(time: SystemTime, fmt: &str) -> String {\n\n let datetime: DateTime<Local> = time.into();\n\n format!(\"{}\", datetime.format(fmt))\n\n}\n\n\n", "file_path": "rust/chrono/main.rs", "rank": 41, "score": 82971.14236820697 }, { "content": "#define _GNU_SOURCE\n\n\n", "file_path": "c/progress_bar/progress_bar.c", "rank": 42, "score": 82070.20911596391 }, { "content": " @Override\n\n public String toString() {\n\n return this.code;\n", "file_path": "java/ISO3166/ISO3166.java", "rank": 43, "score": 81967.89570456094 }, { "content": "def decrypt_file(input_file: str, output_file: str, crypter_key: str, block_size: int = DEFAULT_BLOCK_SIZE) -> bool:\n\n \"\"\"\n\n Decrypt a file using AES/HMAC MD5 using the provided Key\n\n\n\n :param input_file: file to decrypt\n\n :param output_file: where to write the decrypted file content\n\n :param crypter_key: key to use to decrypt data\n\n :type input_file: str\n\n :type output_file: str\n\n :type crypter_key: str\n\n :returns bool\n\n \"\"\"\n\n #Crypter key to bytes\n\n crypter_key = crypter_key.encode()\n\n try:\n\n ihnd = open(input_file, 'rb')\n\n ihnd.seek(0, 2)\n\n filesize = ihnd.tell() - 8 # Remove filesize\n\n if filesize < 32:\n\n print_err(\"File is too short to be decrypted\")\n\n return False\n\n if filesize % 16 != 0: # Remove filesize\n\n print_err(\"File size must be multiple of 16\")\n\n return False\n\n ihnd.seek(0, 0)\n\n #Read first 16 bytes (IV)\n\n iv = ihnd.read(16)\n\n print_info(\"IV is %s\" % hexlify(iv))\n\n #AES key is MD5sum between the crypter key and the IV\n\n digest = hash_md5()\n\n digest.update(iv)\n\n digest.update(crypter_key)\n\n aes_key = digest.digest()\n\n print_info(\"AES key is %s\" % hexlify(aes_key))\n\n #Init AES crypter\n\n crypter = AES.new(aes_key, AES.MODE_CBC, iv)\n\n #Prepare key_ipad and k_opad, I don't know what they are...\n\n key_opad = bytearray()\n\n key_ipad = bytearray()\n\n for i in range(64):\n\n key_ipad.append(0x36)\n\n key_opad.append(0x5C)\n\n for i in range(16):\n\n key_ipad[i] = 0x36 ^ aes_key[i]\n\n key_opad[i] = 0x5C ^ aes_key[i]\n\n datasize = filesize - 32 #filesize - IV - HMAC\n\n #Get HMAC\n\n ihnd.seek(-24, 2) #Last 24 bytes\n\n final_hmac_in = ihnd.read(16)\n\n lastn = ihnd.read(8) # Data size\n\n native_data_size = int.from_bytes(lastn, \"big\")\n\n print_info(\"Decrypted file size will be %d (read from last 8 bytes)\" % native_data_size)\n\n #Verify HMAC before decrypting\n\n digest = hash_md5()\n\n digest.update(key_ipad)\n\n #Return to 16th byte\n\n ihnd.seek(16, 0)\n\n #Digest\n\n while ihnd.tell() <= datasize: # <= cause we're already at 16 (imagine if filesize were 48, datasize would be 16)\n\n digest.update(ihnd.read(16))\n\n final_hmac = digest.digest()\n\n #Opad + md5sum(ipad, file)\n\n digest = hash_md5()\n\n digest.update(key_opad)\n\n digest.update(final_hmac)\n\n final_hmac = digest.digest()\n\n #Compare HMAC\n\n print_info(\"HMAC from file: %s\" % hexlify(final_hmac_in))\n\n print_info(\"HMAC calculated: %s\" % hexlify(final_hmac))\n\n if final_hmac != final_hmac_in:\n\n print_err(\"HMAC doesn't match\")\n\n return False\n\n #Return to 16th byte\n\n ihnd.seek(16, 0)\n\n final_size = 0\n\n #Read and decrypt\n\n try:\n\n #Open output file\n\n ohnd = open(output_file, \"wb\")\n\n offset = 0\n\n progress = 0\n\n while offset < datasize: # <= cause we're already at 16 (imagine if filesize were 48, datasize would be 16)\n\n input_block = bytearray()\n\n input_block.extend(ihnd.read(block_size))\n\n #Encrypt block and append to encrypted data\n\n decrypted_block = crypter.decrypt(bytes(input_block))\n\n #Write decrypted block (only block length)\n\n offset += block_size\n\n if native_data_size > 0 and offset == datasize: #Write remaining bytes\n\n # Remaining bytes\n\n remaining_bytes = native_data_size % block_size\n\n ohnd.write(decrypted_block[0:remaining_bytes])\n\n final_size += remaining_bytes\n\n else:\n\n ohnd.write(decrypted_block) #Write entire block otherwise\n\n final_size += block_size\n\n progress = (offset * 100) / datasize\n\n print_progress_bar(progress, 100)\n\n #Close file\n\n ohnd.close()\n\n except IOError as err:\n\n print_err(\"IOError: %s\" % err)\n\n return False\n\n print_info(\"Data decrypted (%d bytes)\" % final_size)\n\n #Close file\n\n ihnd.close()\n\n except IOError as err:\n\n print_err(\"Could not open input file %s: %s\" % (input_file, err))\n\n return False\n", "file_path": "python/crypter/crypter.py", "rank": 44, "score": 81950.11612757682 }, { "content": "def encrypt_file(input_file: str, output_file: str, crypter_key: str, block_size: int = DEFAULT_BLOCK_SIZE) -> bool:\n\n \"\"\"\n\n Encrypt a file using AES/HMAC MD5 using the provided Key\n\n\n\n :param input_file: file to encrypt\n\n :param output_file: where to write the encrypted file content\n\n :param crypter_key: key to use to encrypt data\n\n :type input_file: str\n\n :type output_file: str\n\n :type crypter_key: str\n\n :returns bool\n\n \"\"\"\n\n #Crypter key to bytes\n\n crypter_key = crypter_key.encode()\n\n try:\n\n ihnd = open(input_file, 'rb')\n\n #Get file size\n\n ihnd.seek(0, 2)\n\n filesize = ihnd.tell()\n\n ihnd.seek(0, 0)\n\n filesize_bytes = bytearray()\n\n filesize_bytes.append(filesize & 0xff)\n\n filesize_bytes.append((filesize << 8) & 0xff)\n\n filesize_bytes.append((filesize << 16) & 0xff)\n\n filesize_bytes.append((filesize << 24) & 0xff)\n\n digest = hash_md5()\n\n digest.update(filesize_bytes)\n\n iv = bytearray(digest.digest())\n\n #Iv[15] must be AND with 0xF0 and then OR with filesize & 0x0F\n\n iv[15] = (iv[15] & 0xF0) | (filesize & 0x0F)\n\n #Write filename at the beginning of file\n\n print_info(\"IV is %s\" % hexlify(iv))\n\n #AES key is MD5SUM between IV and crypter key\n\n digest = hash_md5()\n\n digest.update(iv)\n\n digest.update(crypter_key)\n\n aes_key = digest.digest()\n\n print_info(\"AES key is %s\" % hexlify(aes_key))\n\n #Init AES crypter\n\n crypter = AES.new(aes_key, AES.MODE_CBC, bytearray(iv))\n\n #Prepare key_ipad and k_opad, I don't know what they are...\n\n key_opad = bytearray()\n\n key_ipad = bytearray()\n\n for i in range(64):\n\n key_ipad.append(0x36)\n\n key_opad.append(0x5C)\n\n for i in range(16):\n\n key_ipad[i] = 0x36 ^ aes_key[i]\n\n key_opad[i] = 0x5C ^ aes_key[i]\n\n #Prepare the final digest\n\n digest = hash_md5()\n\n digest.update(key_ipad)\n\n #Open file\n\n try:\n\n ohnd = open(output_file, 'wb')\n\n #Write IV\n\n ohnd.write(iv)\n\n #Read, Encrypt and write\n\n index = 0\n\n input_block = bytearray(block_size)\n\n progress = 0\n\n while index < filesize:\n\n size = block_size\n\n if filesize - index < block_size:\n\n size = filesize - index\n\n for i in range(size):\n\n input_block[i] = ord(ihnd.read(1))\n\n input_block = bytearray(crypter.encrypt(bytes(input_block)))\n\n # index : filesize = progress : 100\n\n progress = (index * 100) / filesize\n\n print_progress_bar(progress, 100)\n\n #Write bytes\n\n ohnd.write(input_block)\n\n #Update digest with encrypted block\n\n digest.update(input_block)\n\n index += size\n\n #Calculate final HMAC\n\n final_hmac = digest.digest()\n\n digest = hash_md5()\n\n digest.update(key_opad)\n\n digest.update(final_hmac)\n\n final_hmac = digest.digest()\n\n print_info(\"HMAC: %s\" % hexlify(final_hmac))\n\n #Write HMAC at the end of the file\n\n ohnd.write(final_hmac)\n\n print_info(\"Wrote %d bytes\" % (index + 32))\n\n # Write original file size at the end of file\n\n data_size_bytes = (filesize).to_bytes(8, byteorder=\"big\")\n\n print_info(\"Wrote 8 bytes at the end %s\" % hexlify(data_size_bytes).decode(\"utf-8\"))\n\n ohnd.write(data_size_bytes)\n\n ohnd.close()\n\n except IOError as err:\n\n print_err(\"IOError: %s\" % err)\n\n return False\n\n ihnd.close()\n\n except IOError as err:\n\n print_err(\"Could not open input file %s: %s\" % (input_file, err))\n\n return False\n\n print_info(\"Encrypted data written to %s\" % output_file)\n", "file_path": "python/crypter/crypter.py", "rank": 45, "score": 81950.11612757682 }, { "content": "fn print_usage(opts: Options) {\n\n let brief = String::from(\"Usage: keyring-client [options]... [service]\");\n\n print!(\"{}\", opts.usage(&brief));\n\n println!(\"\\nPlease, report issues to <https://github.com/veeso/brol>\");\n\n}\n\n\n", "file_path": "rust/keyring-client/src/main.rs", "rank": 46, "score": 77507.5294205557 }, { "content": "def split_file(src: str, dest: str, max_size: int) -> bool:\n\n \"\"\"\n\n Split a file into two;\n\n src will be read for max_size bytes; these bytes will be copied to dest; the last n bytes will be preserved in src\n\n\n\n :param src\n\n :param dest\n\n :param max_size\n\n :type src: str\n\n :type dest: str\n\n :type max_size: int\n\n :returns bool\n\n \"\"\"\n\n try:\n\n dest_stream = open(dest, \"w\", errors=\"replace\")\n\n except IOError as err:\n\n print_err(\"Could not open file %s: %s\" % (dest, err))\n\n return False\n\n try:\n\n src_stream = open(src, \"r+\", errors=\"replace\")\n\n except IOError as err:\n\n print_err(\"Could not open file %s: %s\" % (src, err))\n\n dest_stream.close()\n\n return False\n\n curr_size = 0\n\n #Iterate over src_lines\n\n for line in src_stream.readlines():\n\n line_size = len(line)\n\n #If current size + line_size exceed max_size break\n\n if curr_size + line_size > max_size:\n\n break\n\n #Write row to dest\n\n dest_stream.write(line)\n\n curr_size += line_size\n\n #Close dest stream\n\n dest_stream.close()\n\n struncate(src_stream, curr_size)\n\n src_stream.close()\n", "file_path": "python/logrotate-cli/logrotate-cli.py", "rank": 47, "score": 76160.04602253676 }, { "content": "def calculate_version_downloads(counters: List[int]) -> int:\n\n \"\"\"\n\n Calculate version downloads\n\n \n\n :param counters\n\n \"\"\"\n", "file_path": "python/github-downloads/github-downloads.py", "rank": 48, "score": 73669.85473962637 }, { "content": "def filter_releases_by_version(releases: List[Tuple[str, List[Tuple[str, int]]]], tag: str) -> List[Tuple[str, List[Tuple[str, int]]]]:\n\n \"\"\"\n\n Keep only the release with the provided tag name\n\n\n\n :param releases\n\n :param tag\n\n :returns list\n\n \"\"\"\n", "file_path": "python/github-downloads/github-downloads.py", "rank": 49, "score": 73669.36564483904 }, { "content": "fn main() {\n\n let time: SystemTime = SystemTime::UNIX_EPOCH;\n\n // Set time to 2020-12-16T18:43:40+0100\n\n let time: SystemTime = time.checked_add(Duration::from_secs(1608140620)).unwrap();\n\n // Iso 8601\n\n println!(time_to_str(time, \"%Y-%m-%dT%H:%M:%S%Z\"));\n\n // ls times\n\n assert_eq!(\n\n lstime_to_systime(\"Nov 5 16:32\", \"%b %d %Y\", \"%b %d %H:%M\")\n\n .ok()\n\n .unwrap()\n\n .duration_since(SystemTime::UNIX_EPOCH)\n\n .ok()\n\n .unwrap(),\n\n Duration::from_secs(1604593920)\n\n );\n\n assert_eq!(\n\n lstime_to_systime(\"Dec 2 21:32\", \"%b %d %Y\", \"%b %d %H:%M\")\n\n .ok()\n\n .unwrap()\n", "file_path": "rust/chrono/main.rs", "rank": 50, "score": 62626.10307937948 }, { "content": "struct SftpClient {\n\n client: Sftp,\n\n wrkdir: PathBuf,\n\n}\n\n\n", "file_path": "rust/sftp-client/main.rs", "rank": 51, "score": 61120.88625842068 }, { "content": "/// ### reset_termios\n\n/// \n\n/// Restore previous termios configuration\n\nfn reset_termios() {\n\n let mut term = termios::Termios::from_fd(STDIN_FILENO).unwrap();\n\n let _ = termios::tcgetattr(STDIN_FILENO, &mut term);\n\n term.c_lflag |= termios::ICANON;\n\n term.c_lflag &= termios::ECHO;\n\n let _ = termios::tcsetattr(STDIN_FILENO, termios::TCSADRAIN, &term);\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 52, "score": 61065.77537133091 }, { "content": "/// ### prepare_termios\n\n/// \n\n/// Prepare termios for console\n\nfn prepare_termios() {\n\n let mut term = termios::Termios::from_fd(STDIN_FILENO).unwrap();\n\n let _ = termios::tcgetattr(STDIN_FILENO, &mut term);\n\n term.c_lflag &= !termios::ICANON;\n\n term.c_lflag &= !termios::ECHO;\n\n let _ = termios::tcsetattr(STDIN_FILENO, termios::TCSANOW, &term);\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 53, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n // Check args len\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: {} <address> [port]\", args.get(0).unwrap());\n\n exit(255);\n\n }\n\n let address: String = args.get(1).unwrap().clone();\n\n let port: u16 = match args.get(2) {\n\n Some(p) => p.parse::<u16>().unwrap(),\n\n None => 22,\n\n };\n\n // Create session\n\n println!(\"Connecting to {}:{}\", address, port);\n\n let tcp = TcpStream::connect(format!(\"{}:{}\", address, port)).unwrap();\n\n // Create session\n\n let mut session = Session::new().unwrap();\n\n session.set_tcp_stream(tcp);\n\n session.handshake().unwrap();\n\n println!(\"Connection established\");\n", "file_path": "rust/ssh-client/main.rs", "rank": 54, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if args.len() < 2 {\n\n panic!(\"Usage: {} <file> [open-with]\", args[0]);\n\n }\n\n let file: PathBuf = PathBuf::from(args[1].as_str());\n\n let open_with: Option<String> = match args.get(2) {\n\n Some(s) => Some(s.to_string()),\n\n None => None,\n\n };\n\n /*\n\n println!(\"Open async...\");\n\n let join: JoinHandle<IoResult<ExitStatus>> = open::that_in_background(file.as_path());\n\n println!(\"Opened {}\", file.display());\n\n match join.join() {\n\n Ok(rc) => println!(\"Process exited with {:?}\", rc),\n\n Err(err) => eprintln!(\"Failed to open file: {:?}\", err),\n\n }\n\n */\n\n match open::that(file.as_path()) {\n", "file_path": "rust/open/src/main.rs", "rank": 55, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n // Check args len\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: {} <secret>\", args.get(0).unwrap());\n\n exit(255);\n\n }\n\n let secret: String = args.get(1).unwrap().clone();\n\n let key: String = gen_key();\n\n println!(\"Key is \\\"{}\\\"\", key);\n\n // Prepare crypter, AES-128\n\n let crypter = new_magic_crypt!(key, 256);\n\n // Encrypt and convert to base64\n\n let encrypted: String = crypter.encrypt_str_to_base64(secret.clone());\n\n println!(\"Encrypted secret: \\\"{}\\\"\", encrypted);\n\n // Decrypt\n\n let decrypted: String = crypter.decrypt_base64_to_string(encrypted).ok().unwrap();\n\n println!(\"Decrypted secret: \\\"{}\\\"\", decrypted);\n\n assert_eq!(secret, decrypted);\n\n}\n", "file_path": "rust/magic-crypt/main.rs", "rank": 56, "score": 61065.77537133091 }, { "content": "/// ### lstime_to_systime\n\n///\n\n/// Convert ls syntax time to System Time\n\n/// ls time has two possible syntax:\n\n/// 1. if year is current: %b %d %H:%M (e.g. Nov 5 13:46)\n\n/// 2. else: %b %d %Y (e.g. Nov 5 2019)\n\nfn lstime_to_systime(\n\n tm: &str,\n\n fmt_year: &str,\n\n fmt_hours: &str,\n\n) -> Result<SystemTime, ParseError> {\n\n let datetime: NaiveDateTime = match NaiveDate::parse_from_str(tm, fmt_year) {\n\n Ok(date) => {\n\n // Case 2.\n\n // Return NaiveDateTime from NaiveDate with time 00:00:00\n\n date.and_hms(0, 0, 0)\n\n }\n\n Err(_) => {\n\n // Might be case 1.\n\n // We need to add Current Year at the end of the string\n\n let this_year: i32 = Utc::now().year();\n\n let date_time_str: String = format!(\"{} {}\", tm, this_year);\n\n // Now parse\n\n match NaiveDateTime::parse_from_str(\n\n date_time_str.as_ref(),\n\n format!(\"{} %Y\", fmt_hours).as_ref(),\n", "file_path": "rust/chrono/main.rs", "rank": 57, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let msg: Negotiation = Negotiation {\n\n version: 0xcafe,\n\n name: String::from(\"drome-dario\"),\n\n key: 0xcafebabe,\n\n secure: true,\n\n };\n\n let encoded: Vec<u8> = msg.encode().to_vec();\n\n assert_eq!(\n\n encoded,\n\n vec![\n\n 0xca, 0xfe, 0x00, 0x0b, 0x64, 0x72, 0x6f, 0x6d, 0x65, 0x2d, 0x64, 0x61, 0x72, 0x69,\n\n 0x6f, 0xca, 0xfe, 0xba, 0xbe, 0x01,\n\n ]\n\n );\n\n // Decode\n\n let mut buffer: Bytes = Bytes::from(encoded);\n\n let in_msg: Negotiation = Negotiation::decode(&mut buffer).ok().unwrap();\n\n assert_eq!(msg, in_msg);\n\n}\n", "file_path": "rust/bytes/src/main.rs", "rank": 58, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n // Check args len\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: {} <address> [port]\", args.get(0).unwrap());\n\n exit(255);\n\n }\n\n let address: String = args.get(1).unwrap().clone();\n\n let port: u16 = match args.get(2) {\n\n Some(p) => p.parse::<u16>().unwrap(),\n\n None => 22,\n\n };\n\n // Create session\n\n println!(\"Connecting to {}:{}\", address, port);\n\n let tcp = TcpStream::connect(format!(\"{}:{}\", address, port)).unwrap();\n\n // Create session\n\n let mut session = Session::new().unwrap();\n\n session.set_tcp_stream(tcp);\n\n session.handshake().unwrap();\n\n println!(\"Connection established\");\n", "file_path": "rust/sftp-client/main.rs", "rank": 59, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n // Check args len\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: {} <s>\", args.get(0).unwrap());\n\n exit(255);\n\n }\n\n let target: String = args.get(1).unwrap().clone();\n\n let mut hasher: Sha1 = Sha1::default();\n\n hasher.update(target.as_bytes());\n\n let result = hasher.finalize();\n\n let result: String = hex::encode(result);\n\n println!(\"{}\", result);\n\n}\n", "file_path": "rust/sha1/src/main.rs", "rank": 60, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let mut it: usize = 0;\n\n let max: usize = 4096;\n\n while it < max {\n\n print_progress_bar(it, max, \"Loading...\");\n\n it = it + 1;\n\n sleep(Duration::from_millis(1));\n\n }\n\n}\n", "file_path": "rust/progress_bar/main.rs", "rank": 61, "score": 61065.77537133091 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if args.len() < 3 {\n\n eprintln!(\"Usage: notifications <title> <body>\");\n\n exit(255);\n\n }\n\n let title = args.get(1).to_owned().unwrap();\n\n let body = args.get(2).to_owned().unwrap();\n\n if let Err(err) = Notification::new()\n\n .summary(title.as_str())\n\n .body(body.as_str())\n\n .appname(\"termscp\")\n\n .timeout(5000)\n\n .show()\n\n {\n\n eprintln!(\"Could not display notification: {}\", err);\n\n exit(1);\n\n }\n\n}\n", "file_path": "rust/notifications/src/main.rs", "rank": 62, "score": 61065.77537133091 }, { "content": "int main(int argc, char** argv) {\n\n // @! Union example\n\n Message message;\n\n // Buffer to struct\n\n printf(\"Buffer to struct\\n\");\n\n const uint16_t ev_id = 8134;\n\n const uint32_t duration = 12481297;\n\n uint8_t data[MAX_DATA_SIZE] = {0};\n\n data[0] = 0x02; // Reset\n\n data[2] = ev_id >> 8;\n\n data[1] = ev_id & 0xFF;\n\n data[6] = (duration >> 24) & 0xFF;\n\n data[5] = (duration >> 16) & 0xFF;\n\n data[4] = (duration >> 8) & 0xFF;\n\n data[3] = duration & 0xFF;\n\n \n\n // Set message data\n\n message.msg_type = Event;\n\n message.data_size = 7;\n\n for (size_t i = 0; i < message.data_size; i++) {\n\n message.data.buffer[i] = data[i];\n\n }\n\n print_message(&message);\n\n // Reset message\n\n printf(\"\\n===================================================================\\n\\n\");\n\n memset(message.data.buffer, 0x00, MAX_DATA_SIZE);\n\n message.data_size = 0;\n\n\n\n // Struct to buffer\n\n printf(\"Struct to buffer\\n\");\n\n message.data.event.duration = 12481297;\n\n message.data.event.event_id = 8134;\n\n message.data.event.event_type = EventReset;\n\n message.data_size = 7;\n\n print_message(&message);\n\n\n\n return 0;\n", "file_path": "c/union/union.c", "rank": 63, "score": 60263.67701580964 }, { "content": "int main(int argc, char** argv) {\n\n if (argc < 2) {\n\n printf(\"Usage: %s <UNIX epoch time>\\n\", argv[0]);\n\n return 1;\n\n }\n\n\n\n const time_t epoch = atoi(argv[1]);\n\n struct timeval t_new;\n\n t_new.tv_sec = epoch;\n\n t_new.tv_usec = 0;\n\n\n\n struct timezone tz;\n\n gettimeofday(NULL, &tz);\n\n return settimeofday(&t_new, &tz);\n", "file_path": "c/settimeofday/settime.c", "rank": 64, "score": 60263.67701580964 }, { "content": "int main(int argc, char** argv) {\n\n\n\n //SIGTERM handler\n\n struct sigaction sigterm_hnd;\n\n sigterm_hnd.sa_handler = handle_sigterm;\n\n sigemptyset(&sigterm_hnd.sa_mask);\n\n sigterm_hnd.sa_flags = 0;\n\n // Handle both SIGTERM and SIGINT\n\n sigaction(SIGTERM, &sigterm_hnd, NULL);\n\n sigaction(SIGINT, &sigterm_hnd, NULL);\n\n\n\n printf(\"Press CTRL+C to stop the execution\\n\");\n\n while (!sigterm_raised) {\n\n usleep(1000);\n\n }\n\n\n\n return 0;\n", "file_path": "c/sigint/sigint.c", "rank": 65, "score": 60263.67701580964 }, { "content": "#define USAGE \"jansson <json> <keyToGet>\"\n\n\n", "file_path": "c/jannson/jansson.c", "rank": 66, "score": 60263.67701580964 }, { "content": "int main(int argc, char** argv) {\n\n if (argc < 3) {\n\n printf(\"%s\\n\", USAGE);\n\n return 1;\n\n }\n\n char* jsonText = argv[1];\n\n char* k = argv[2];\n\n\n\n char key[512];\n\n strcpy(key, k);\n\n int rc = 0;\n\n\n\n json_error_t error;\n\n json_t* root = json_loads(jsonText, 0, &error);\n\n json_t* json = root;\n\n if (json == NULL) {\n\n printf(\"error on line %d: %s\\n\", error.line, error.text);\n\n return 1;\n\n }\n\n \n\n\n\n json_t* keyJson;\n\n size_t index;\n\nexplore:\n\n printf(\"Looking for key '%s'\\n\", key);\n\n keyJson = json_object_get(json, key);\n\n if (keyJson == NULL) {\n\n printf(\"Key %s does not exist\\n\", key);\n\n rc = 1;\n\n goto cleanup;\n\n }\n\n if (json_is_string(keyJson)) {\n\n const char* stringValue = json_string_value(keyJson);\n\n printf(\"%s: %s\\n\", key, stringValue);\n\n //free(stringValue);\n\n } else if (json_is_number(keyJson)) {\n\n printf(\"%s: %f\\n\", json_number_value(keyJson));\n\n } else if (json_is_null(keyJson)) {\n\n printf(\"%s: null\\n\", keyJson);\n\n } else if (json_is_boolean(keyJson)) {\n\n printf(\"%s: %d\\n\", key, json_boolean_value(keyJson));\n\n } else if (json_is_object(keyJson)) {\n\n printf(\"%s is an object; type next key to get: \");\n\n scanf(\"%s\", key);\n\n json = keyJson;\n\n goto explore;\n\n } else if (json_is_array(keyJson)) {\n\n printf(\"%s is an array; type index to select: \");\n\n scanf(\"%u\", &index);\n\n json = json_array_get(keyJson, index);\n\n goto explore;\n\n } else {\n\n printf(\"Unknown type\\n\");\n\n rc = 1;\n\n goto cleanup;\n\n }\n\n\n\ncleanup:\n\n //Free resource\n\n json_decref(root);\n\n return rc;\n", "file_path": "c/jannson/jansson.c", "rank": 67, "score": 60263.67701580964 }, { "content": "int main(int argc, char** argv) {\n\n\n\n if (argc < 2) {\n\n printf(\"Usage: %s <filename>\\n\", argv[0]);\n\n return 1;\n\n }\n\n\n\n const char* file_name = argv[1];\n\n FILE* fptr = fopen(file_name, \"r\");\n\n if (fptr == NULL) {\n\n printf(\"Could not open file %s\\n\", file_name);\n\n return 1;\n\n }\n\n // Read lines\n\n char* line = NULL;\n\n size_t line_sz = 0;\n\n ssize_t line_len = 0;\n\n // Iter lines\n\n size_t row = 0;\n\n while ((line_len = getline(&line, &line_sz, fptr)) != -1) {\n\n // Skip empty rows\n\n if (line_len == 0) {\n\n goto getline_continue;\n\n }\n\n // Remove newline\n\n while (line[line_len - 1] == 0x0a || line[line_len - 1] == 0x0d) {\n\n line[line_len - 1] = 0x00;\n\n line_len--;\n\n if (line_len <= 0) {\n\n goto getline_continue;\n\n }\n\n }\n\n // If line is empty continue (double check; now and before)\n\n if (line_len == 0) {\n\n goto getline_continue;\n\n }\n\n printf(\"trimmed line: %s\\n\", line);\n\n\n\ngetline_continue:\n\n // Free line\n\n free(line);\n\n line = NULL;\n\n line_sz = 0;\n\n } // End of iterator\n\n\n\n if (line != NULL) {\n\n free(line);\n\n }\n\n\n\n fclose(fptr);\n\n return 0;\n\n\n", "file_path": "c/getline/getline.c", "rank": 68, "score": 60263.67701580964 }, { "content": "ssize_t getline(char** line, size_t* line_sz, FILE* file) {\n\n\n\n // Get file size\n\n const ssize_t curr_pos = ftell(file);\n\n fseek(file, 0, SEEK_END);\n\n const size_t file_sz = ftell(file);\n\n // Restore pos\n\n fseek(file, curr_pos, SEEK_SET);\n\n if (curr_pos >= file_sz) { // EOF\n\n return -1;\n\n }\n\n const size_t read_sz = 0;\n\n *line_sz = read_sz;\n\n char* line_ptr = NULL;\n\n ssize_t line_len = 0;\n\n while (1) {\n\n // Read 2048\n\n char buffer[2048];\n\n size_t bytes_read = fread(buffer, sizeof(char), 2048, file);\n\n //printf(\"READ: %s\\n\", buffer);\n\n if (bytes_read == 0) {\n\n break;\n\n }\n\n // Look for 0x0A in buffer\n\n for (size_t i = 0; i < bytes_read; i++) {\n\n if (buffer[i] == 0x0A) {\n\n bytes_read = i;\n\n break;\n\n }\n\n }\n\n // Increment line sz\n\n const size_t prev_line_sz = *line_sz;\n\n *line_sz += bytes_read + 1;\n\n // Reallocate line\n\n char* prev_ptr = line_ptr;\n\n line_ptr = (char*) realloc(line_ptr, sizeof(char) * (*line_sz));\n\n if (line_ptr == NULL) {\n\n line_ptr = prev_ptr;\n\n }\n\n // Copy buffer to line\n\n memcpy(line_ptr + prev_line_sz, buffer, bytes_read);\n\n line_ptr[(*line_sz - 1)] = 0x00; // NULL terminate\n\n line_len += bytes_read;\n\n }\n\n // Restore file pointer (or set at the end)\n\n const size_t file_pos = curr_pos + line_len + 1;\n\n if (file_pos < file_sz) {\n\n fseek(file, file_pos, SEEK_SET);\n\n } else {\n\n fseek(file, 0, SEEK_END);\n\n }\n\n // Return\n\n *line = line_ptr;\n\n return line_len;\n", "file_path": "c/getline/getline.c", "rank": 69, "score": 60263.67701580964 }, { "content": "/// ## CliAction\n\n///\n\n/// Defines what to do in client\n\nenum CliAction {\n\n Del,\n\n Get,\n\n Set(String), // Value\n\n}\n\n\n\n/// ### print_usage\n\n///\n\n/// Print usage\n\n\n", "file_path": "rust/keyring-client/src/main.rs", "rank": 70, "score": 59766.4300643719 }, { "content": "fn main() {\n\n let config_path = args()\n\n .collect::<Vec<String>>()\n\n .get(1)\n\n .map(|x| PathBuf::from(x))\n\n .unwrap_or_else(|| {\n\n let mut p = home_dir().unwrap();\n\n p.extend(Path::new(\".ssh/config\"));\n\n p\n\n });\n\n println!(\"Parsing {}...\", config_path.display());\n\n // open file\n\n let mut file = match File::open(config_path.as_path()) {\n\n Ok(f) => f,\n\n Err(err) => panic!(\"Could not open file {}: {}\", config_path.display(), err),\n\n };\n\n // Read\n\n let mut config = String::new();\n\n if let Err(err) = file.read_to_string(&mut config) {\n\n panic!(\"Could not read file: {}\", err);\n\n }\n\n // Parse\n\n let config = match SSHConfig::parse_str(config.as_str()) {\n\n Ok(c) => c,\n\n Err(err) => panic!(\"Could not parse ssh configuration: {:?}\", err),\n\n };\n\n println!(\"{:?}\", config);\n\n}\n", "file_path": "rust/ssh-config/src/main.rs", "rank": 71, "score": 59639.19638608531 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let mut action: Option<CliAction> = None;\n\n // Get options\n\n let mut opts = Options::new();\n\n opts.optflag(\"d\", \"del\", \"delete key from storage\");\n\n opts.optflag(\"g\", \"get\", \"get key from storage\");\n\n opts.optopt(\"s\", \"set\", \"set key into storage\", \"<key_value>\");\n\n opts.optflag(\"h\", \"help\", \"Print this menu\");\n\n let matches = match opts.parse(&args[1..]) {\n\n Ok(m) => m,\n\n Err(f) => {\n\n println!(\"{}\", f.to_string());\n\n std::process::exit(255);\n\n }\n\n };\n\n // Help\n\n if matches.opt_present(\"h\") {\n\n print_usage(opts);\n\n std::process::exit(255);\n", "file_path": "rust/keyring-client/src/main.rs", "rank": 72, "score": 59639.19638608531 }, { "content": "fn main() {\n\n // Prepare view\n\n let mut view = View::<Msg>::default();\n\n view.mount(MY_TEXT, Box::new(Text::default()));\n\n\n\n println!(\"ACTIVE => {:?}\", view.on(MY_TEXT, Event::Active));\n\n}\n\n\n\nimpl Component<Msg> for Text {\n\n fn on(&mut self, ev: Event) -> Msg {\n\n match ev {\n\n Event::Active => Msg::TextActive,\n\n Event::Blur => Msg::TextBlurred,\n\n Event::Click => Msg::TextActive,\n\n Event::Key(ch) => {\n\n self.text.push(ch);\n\n Msg::TextInput(self.text.clone())\n\n }\n\n Event::Submit => Msg::TextSubmit,\n\n }\n\n }\n\n}\n", "file_path": "rust/msg-demo/examples/demo.rs", "rank": 73, "score": 59639.19638608531 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if args.len() < 2 {\n\n eprintln!(\"Usage: fs-notify <path>...\");\n\n exit(255);\n\n };\n\n\n\n let paths = &args.as_slice()[1..];\n\n\n\n let (tx, rx) = channel();\n\n let mut watcher = watcher(tx, Duration::from_secs(5)).unwrap();\n\n\n\n for p in paths.iter() {\n\n watcher.watch(p.as_str(), RecursiveMode::Recursive).unwrap();\n\n }\n\n\n\n loop {\n\n match rx.recv() {\n\n Ok(event) => println!(\"{:?}\", event),\n\n Err(e) => println!(\"watch error: {:?}\", e),\n\n }\n\n }\n\n}\n", "file_path": "rust/fs-notify/src/main.rs", "rank": 74, "score": 59639.19638608531 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if args.len() < 5 {\n\n panic!(\"Usage: <ssh-host> <port> <username> <password> [cycles]\");\n\n }\n\n let hostname = &args[1];\n\n let port = args.get(2).map(|x| x.parse::<u16>().ok().unwrap()).unwrap();\n\n let username = &args[3];\n\n let password = &args[4];\n\n let cycles = args\n\n .get(5)\n\n .map(|x| x.parse::<usize>().ok().unwrap())\n\n .unwrap_or(10);\n\n env_logger::init();\n\n // sftp\n\n let client: SftpFs = SshOpts::new(hostname)\n\n .port(port)\n\n .username(username)\n\n .password(password)\n\n .into();\n", "file_path": "rust/remotefs-ssh/src/main.rs", "rank": 75, "score": 59639.19638608531 }, { "content": "#[derive(Deserialize)]\n\nstruct TagInfo {\n\n tag_name: String,\n\n}\n\n\n\nuse std::env;\n\nuse std::process::exit;\n\n\n", "file_path": "rust/git-latest-release/src/main.rs", "rank": 76, "score": 58567.188306230266 }, { "content": "fn main() {\n\n // Get arguments\n\n let args: Vec<String> = env::args().collect();\n\n // Check args len\n\n if args.len() < 3 {\n\n eprintln!(\"Usage: {} <author> <reponame>\", args.get(0).unwrap());\n\n exit(255);\n\n }\n\n\n\n let author: String = args.get(1).unwrap().to_string();\n\n let repository: String = args.get(2).unwrap().to_string();\n\n // make url\n\n let url: String = format!(\n\n \"https://api.github.com/repos/{}/{}/releases/latest\",\n\n author, repository\n\n );\n\n println!(\"Sending request to \\\"{}\\\"\", url);\n\n // Send request\n\n let body = match ureq::get(url.as_str()).call() {\n\n Ok(response) => response,\n\n Err(err) => panic!(\"Request failed API: {}\", err),\n\n };\n\n let body: TagInfo = match body.into_json() {\n\n Ok(b) => b,\n\n Err(err) => panic!(\"Could not parse response: {}\", err),\n\n };\n\n // get latest tag\n\n println!(\"Latest {} version: {}\", repository, body.tag_name);\n\n}\n", "file_path": "rust/git-latest-release/src/main.rs", "rank": 77, "score": 58329.87580459692 }, { "content": "fn main() {\n\n let keys = KeyBindings::new(\n\n KeyEvent::from(Key::Esc),\n\n KeyEvent::new(Key::Char('o'), KeyModifiers::CONTROL),\n\n );\n\n let mut config = File::create(\"keys.toml\").expect(\"Failed to open file 'keys.toml'\");\n\n serialize(&keys, &mut config).expect(\"Failed to serialize keys\");\n\n}\n", "file_path": "rust/key-event-serde/src/main.rs", "rank": 78, "score": 58329.87580459692 }, { "content": "fn usage() {\n\n println!(\"Usage: aws-s3-cli <bucket> <region> [profile]\");\n\n}\n\n\n", "file_path": "rust/aws-s3-cli/src/main.rs", "rank": 79, "score": 58329.87580459692 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if let Some(\"-h\") = args.get(1).map(|x| x.as_str()) {\n\n usage();\n\n exit(255);\n\n }\n\n if args.len() < 3 {\n\n usage();\n\n exit(255);\n\n }\n\n let bucket_name: &String = args.get(1).unwrap();\n\n let region: &String = args.get(2).unwrap();\n\n let profile: Option<String> = args.get(3).map(|x| x.to_string());\n\n let mut bucket: S3Bucket =\n\n match S3Bucket::connect(bucket_name.as_str(), region.as_str(), profile.as_deref()) {\n\n Ok(b) => b,\n\n Err(e) => panic!(\"{}\", e),\n\n };\n\n loop {\n\n match input() {\n", "file_path": "rust/aws-s3-cli/src/main.rs", "rank": 80, "score": 58329.87580459692 }, { "content": "#!/usr/bin/python3\n\n\n\n\"\"\"\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n Version 2, December 2004\n\n\n\n Copyright (C) 2021 Christian Visintin\n\n\n\n Everyone is permitted to copy and distribute verbatim or modified\n\n copies of this license document, and changing it is allowed as long\n\n as the name is changed.\n\n\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n\n\n 0. You just DO WHAT THE FUCK YOU WANT TO.\n\n\"\"\"\n\n\n\n# Sys\n\nfrom sys import argv, exit\n\n# Typings\n\nfrom typing import List\n\n\n\ndef fibonacci(n: int) -> int:\n\n if n == 0:\n\n return 0\n\n if n == 1:\n\n return 1\n\n return fibonacci(n - 1) + fibonacci(n - 2)\n\n\n\ndef main(argc: int, argv: List[str]) -> int:\n\n # Get options\n\n if argc < 1:\n\n print(\"Usage: fibonaccy.py <n>\")\n\n return 255\n\n x = int(argv[0])\n\n print(\"%d\" % fibonacci(x))\n\n # Return success\n\n return 0\n\n\n\n# Entry point\n\nif __name__ == \"__main__\":\n\n exit(main(len(argv[1:]), argv[1:]))\n", "file_path": "python/fibonacci/fibonaccy.py", "rank": 81, "score": 57817.5000474035 }, { "content": "#!/usr/bin/python3\n\n\n\n\"\"\"\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n Version 2, December 2004\n\n\n\n Copyright (C) 2020 Christian Visintin\n\n\n\n Everyone is permitted to copy and distribute verbatim or modified\n\n copies of this license document, and changing it is allowed as long\n\n as the name is changed.\n\n\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n\n\n 0. You just DO WHAT THE FUCK YOU WANT TO.\n\n\"\"\"\n\n\n\n#Hexlify\n\nfrom binascii import hexlify\n\n#AES\n\nfrom Crypto.Cipher import AES\n\n#Enums\n\nfrom enum import Enum\n\n#Getopt\n\nfrom getopt import getopt, GetoptError\n\n#HMAC\n\nfrom hashlib import md5 as hash_md5\n\nimport hmac\n\n#Argv\n\nfrom sys import argv, exit\n\n\n\nfrom typing import Optional\n\n\n\nPROGRAM_NAME = \"crypter.py\"\n\nUSAGE = \"%s [OPTIONS...] [INPUT_FILE] [OUTPUT_FILE]\\n\\\n\n Where options are:\\n\\\n\n \\t-b\\t<block_size>\\tDefine block size (default: 4096B)\\n\\\n\n \\t-d\\t\\t\\tDecrypt file\\n\\\n\n \\t-e\\t\\t\\tEncrypt file\\n\\\n\n \\t-k\\t\\t\\tKey used to encrypt/decrypt file\\n\\\n\n \\t-f\\t\\t\\tRead key from file\\n\\\n\n \\t-v\\t\\t\\tVerbose\\n\\\n\n \\t-h\\t\\t\\tShow this page\\n\\\n\n \" % PROGRAM_NAME\n\n\n\nKNRM = \"\\x1B[0m\"\n\nKRED = \"\\x1B[31m\"\n\nKGRN = \"\\x1B[32m\"\n\nKYEL = \"\\x1B[33m\"\n\nKBLU = \"\\x1B[34m\"\n\nKMAG = \"\\x1B[35m\"\n\nKCYN = \"\\x1B[36m\"\n\nKWHT = \"\\x1B[37m\"\n\n\n\nDEFAULT_BLOCK_SIZE = 4096\n\n\n\nverbose = False\n\n\n\nclass CrypterMode(Enum):\n\n DECRYPT = 0\n\n ENCRYPT = 1\n\n UNDEFINED = 2\n\n\n\ndef print_err(message: str):\n\n \"\"\"\n\n Print error\n\n\n\n :param message: message to print\n\n :type message: str\n\n \"\"\"\n\n print(\"%s%s%s\" % (KRED, message, KNRM))\n\n\n\ndef print_info(message: str):\n\n \"\"\"\n\n Print information.\n\n The message will be displayed only when set in verbose mode\n\n\n\n :param message: message to print\n\n :type message: str\n\n \"\"\"\n\n global verbose\n\n if verbose:\n\n print(\"%s%s%s\" % (KYEL, message, KNRM))\n\n\n\ndef usage(err: str = None):\n\n \"\"\"\n\n Print usage\n\n \"\"\"\n\n if err:\n\n print_err(err)\n\n print(\"%s\" % USAGE)\n\n\n\ndef print_progress_bar (iteration: int, total: int, prefix: Optional[str] = '', suffix: Optional[str] = '', decimals: Optional[int] = 1, length: Optional[int] = 100, fill: Optional[str] = '█', printEnd: Optional[str] = \"\\r\"):\n\n \"\"\"\n\n Call in a loop to create terminal progress bar\n\n :param iteration - Required : current iteration (Int)\n\n :param total - Required : total iterations (Int)\n\n :param prefix - Optional : prefix string (Str)\n\n :param suffix - Optional : suffix string (Str)\n\n :param decimals - Optional : positive number of decimals in percent complete (Int)\n\n :param length - Optional : character length of bar (Int)\n\n :param fill - Optional : bar fill character (Str)\n\n :param printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n\n \"\"\"\n\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n\n filledLength = int(length * iteration // total)\n\n bar = fill * filledLength + '-' * (length - filledLength)\n\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\n\n # Print New Line on Complete\n\n if iteration >= total: \n\n print()\n\n\n\ndef encrypt_file(input_file: str, output_file: str, crypter_key: str, block_size: int = DEFAULT_BLOCK_SIZE) -> bool:\n\n \"\"\"\n\n Encrypt a file using AES/HMAC MD5 using the provided Key\n\n\n\n :param input_file: file to encrypt\n\n :param output_file: where to write the encrypted file content\n\n :param crypter_key: key to use to encrypt data\n\n :type input_file: str\n\n :type output_file: str\n\n :type crypter_key: str\n\n :returns bool\n\n \"\"\"\n\n #Crypter key to bytes\n\n crypter_key = crypter_key.encode()\n\n try:\n\n ihnd = open(input_file, 'rb')\n\n #Get file size\n\n ihnd.seek(0, 2)\n\n filesize = ihnd.tell()\n\n ihnd.seek(0, 0)\n\n filesize_bytes = bytearray()\n\n filesize_bytes.append(filesize & 0xff)\n\n filesize_bytes.append((filesize << 8) & 0xff)\n\n filesize_bytes.append((filesize << 16) & 0xff)\n\n filesize_bytes.append((filesize << 24) & 0xff)\n\n digest = hash_md5()\n\n digest.update(filesize_bytes)\n\n iv = bytearray(digest.digest())\n\n #Iv[15] must be AND with 0xF0 and then OR with filesize & 0x0F\n\n iv[15] = (iv[15] & 0xF0) | (filesize & 0x0F)\n\n #Write filename at the beginning of file\n\n print_info(\"IV is %s\" % hexlify(iv))\n\n #AES key is MD5SUM between IV and crypter key\n\n digest = hash_md5()\n\n digest.update(iv)\n\n digest.update(crypter_key)\n\n aes_key = digest.digest()\n\n print_info(\"AES key is %s\" % hexlify(aes_key))\n\n #Init AES crypter\n\n crypter = AES.new(aes_key, AES.MODE_CBC, bytearray(iv))\n\n #Prepare key_ipad and k_opad, I don't know what they are...\n\n key_opad = bytearray()\n\n key_ipad = bytearray()\n\n for i in range(64):\n\n key_ipad.append(0x36)\n\n key_opad.append(0x5C)\n\n for i in range(16):\n\n key_ipad[i] = 0x36 ^ aes_key[i]\n\n key_opad[i] = 0x5C ^ aes_key[i]\n\n #Prepare the final digest\n\n digest = hash_md5()\n\n digest.update(key_ipad)\n\n #Open file\n\n try:\n\n ohnd = open(output_file, 'wb')\n\n #Write IV\n\n ohnd.write(iv)\n\n #Read, Encrypt and write\n\n index = 0\n\n input_block = bytearray(block_size)\n\n progress = 0\n\n while index < filesize:\n\n size = block_size\n\n if filesize - index < block_size:\n\n size = filesize - index\n\n for i in range(size):\n\n input_block[i] = ord(ihnd.read(1))\n\n input_block = bytearray(crypter.encrypt(bytes(input_block)))\n\n # index : filesize = progress : 100\n\n progress = (index * 100) / filesize\n\n print_progress_bar(progress, 100)\n\n #Write bytes\n\n ohnd.write(input_block)\n\n #Update digest with encrypted block\n\n digest.update(input_block)\n\n index += size\n\n #Calculate final HMAC\n\n final_hmac = digest.digest()\n\n digest = hash_md5()\n\n digest.update(key_opad)\n\n digest.update(final_hmac)\n\n final_hmac = digest.digest()\n\n print_info(\"HMAC: %s\" % hexlify(final_hmac))\n\n #Write HMAC at the end of the file\n\n ohnd.write(final_hmac)\n\n print_info(\"Wrote %d bytes\" % (index + 32))\n\n # Write original file size at the end of file\n\n data_size_bytes = (filesize).to_bytes(8, byteorder=\"big\")\n\n print_info(\"Wrote 8 bytes at the end %s\" % hexlify(data_size_bytes).decode(\"utf-8\"))\n\n ohnd.write(data_size_bytes)\n\n ohnd.close()\n\n except IOError as err:\n\n print_err(\"IOError: %s\" % err)\n\n return False\n\n ihnd.close()\n\n except IOError as err:\n\n print_err(\"Could not open input file %s: %s\" % (input_file, err))\n\n return False\n\n print_info(\"Encrypted data written to %s\" % output_file)\n\n return True\n\n\n\ndef decrypt_file(input_file: str, output_file: str, crypter_key: str, block_size: int = DEFAULT_BLOCK_SIZE) -> bool:\n\n \"\"\"\n\n Decrypt a file using AES/HMAC MD5 using the provided Key\n\n\n\n :param input_file: file to decrypt\n\n :param output_file: where to write the decrypted file content\n\n :param crypter_key: key to use to decrypt data\n\n :type input_file: str\n\n :type output_file: str\n\n :type crypter_key: str\n\n :returns bool\n\n \"\"\"\n\n #Crypter key to bytes\n\n crypter_key = crypter_key.encode()\n\n try:\n\n ihnd = open(input_file, 'rb')\n\n ihnd.seek(0, 2)\n\n filesize = ihnd.tell() - 8 # Remove filesize\n\n if filesize < 32:\n\n print_err(\"File is too short to be decrypted\")\n\n return False\n\n if filesize % 16 != 0: # Remove filesize\n\n print_err(\"File size must be multiple of 16\")\n\n return False\n\n ihnd.seek(0, 0)\n\n #Read first 16 bytes (IV)\n\n iv = ihnd.read(16)\n\n print_info(\"IV is %s\" % hexlify(iv))\n\n #AES key is MD5sum between the crypter key and the IV\n\n digest = hash_md5()\n\n digest.update(iv)\n\n digest.update(crypter_key)\n\n aes_key = digest.digest()\n\n print_info(\"AES key is %s\" % hexlify(aes_key))\n\n #Init AES crypter\n\n crypter = AES.new(aes_key, AES.MODE_CBC, iv)\n\n #Prepare key_ipad and k_opad, I don't know what they are...\n\n key_opad = bytearray()\n\n key_ipad = bytearray()\n\n for i in range(64):\n\n key_ipad.append(0x36)\n\n key_opad.append(0x5C)\n\n for i in range(16):\n\n key_ipad[i] = 0x36 ^ aes_key[i]\n\n key_opad[i] = 0x5C ^ aes_key[i]\n\n datasize = filesize - 32 #filesize - IV - HMAC\n\n #Get HMAC\n\n ihnd.seek(-24, 2) #Last 24 bytes\n\n final_hmac_in = ihnd.read(16)\n\n lastn = ihnd.read(8) # Data size\n\n native_data_size = int.from_bytes(lastn, \"big\")\n\n print_info(\"Decrypted file size will be %d (read from last 8 bytes)\" % native_data_size)\n\n #Verify HMAC before decrypting\n\n digest = hash_md5()\n\n digest.update(key_ipad)\n\n #Return to 16th byte\n\n ihnd.seek(16, 0)\n\n #Digest\n\n while ihnd.tell() <= datasize: # <= cause we're already at 16 (imagine if filesize were 48, datasize would be 16)\n\n digest.update(ihnd.read(16))\n\n final_hmac = digest.digest()\n\n #Opad + md5sum(ipad, file)\n\n digest = hash_md5()\n\n digest.update(key_opad)\n\n digest.update(final_hmac)\n\n final_hmac = digest.digest()\n\n #Compare HMAC\n\n print_info(\"HMAC from file: %s\" % hexlify(final_hmac_in))\n\n print_info(\"HMAC calculated: %s\" % hexlify(final_hmac))\n\n if final_hmac != final_hmac_in:\n\n print_err(\"HMAC doesn't match\")\n\n return False\n\n #Return to 16th byte\n\n ihnd.seek(16, 0)\n\n final_size = 0\n\n #Read and decrypt\n\n try:\n\n #Open output file\n\n ohnd = open(output_file, \"wb\")\n\n offset = 0\n\n progress = 0\n\n while offset < datasize: # <= cause we're already at 16 (imagine if filesize were 48, datasize would be 16)\n\n input_block = bytearray()\n\n input_block.extend(ihnd.read(block_size))\n\n #Encrypt block and append to encrypted data\n\n decrypted_block = crypter.decrypt(bytes(input_block))\n\n #Write decrypted block (only block length)\n\n offset += block_size\n\n if native_data_size > 0 and offset == datasize: #Write remaining bytes\n\n # Remaining bytes\n\n remaining_bytes = native_data_size % block_size\n\n ohnd.write(decrypted_block[0:remaining_bytes])\n\n final_size += remaining_bytes\n\n else:\n\n ohnd.write(decrypted_block) #Write entire block otherwise\n\n final_size += block_size\n\n progress = (offset * 100) / datasize\n\n print_progress_bar(progress, 100)\n\n #Close file\n\n ohnd.close()\n\n except IOError as err:\n\n print_err(\"IOError: %s\" % err)\n\n return False\n\n print_info(\"Data decrypted (%d bytes)\" % final_size)\n\n #Close file\n\n ihnd.close()\n\n except IOError as err:\n\n print_err(\"Could not open input file %s: %s\" % (input_file, err))\n\n return False\n\n return True\n\n\n\ndef main(argc: int, argv: list) -> int:\n\n #Get option\n\n global verbose\n\n crypter_mode = CrypterMode.UNDEFINED\n\n crypter_key = None\n\n input_file = None\n\n output_file = None\n\n block_size = DEFAULT_BLOCK_SIZE\n\n try:\n\n optlist, args = getopt(argv, \"b::edk::f::vh\")\n\n #Iterate over options\n\n for opt, arg in optlist:\n\n if opt == \"-b\":\n\n block_size = int(arg)\n\n elif opt == \"-d\":\n\n crypter_mode = CrypterMode.DECRYPT\n\n elif opt == \"-e\":\n\n crypter_mode = CrypterMode.ENCRYPT\n\n elif opt == \"-k\":\n\n crypter_key = arg\n\n elif opt == \"-f\":\n\n #Read file\n\n try:\n\n hnd = open(arg, \"r\")\n\n crypter_key = hnd.readline()\n\n crypter_key = crypter_key.rstrip()\n\n hnd.close()\n\n except IOError as err:\n\n print_err(\"Could not read key from file: %s\" % err)\n\n return 255\n\n elif opt == \"-v\":\n\n verbose = True\n\n elif opt == \"-h\":\n\n usage()\n\n return 255\n\n #Look for database path\n\n if args:\n\n if len(args) < 2:\n\n usage(\"Missing I/O files\")\n\n return 255\n\n input_file = args[0]\n\n output_file = args[1]\n\n else:\n\n usage(\"Missing I/O files\")\n\n return 255\n\n except GetoptError as err:\n\n usage(err)\n\n return 255\n\n if not crypter_key:\n\n print_err(\"Please provide secret key\")\n\n return 1\n\n #Encrypt/Decrypt file\n\n if crypter_mode == CrypterMode.ENCRYPT:\n\n if not encrypt_file(input_file, output_file, crypter_key, block_size):\n\n return 1\n\n elif crypter_mode == CrypterMode.DECRYPT:\n\n if not decrypt_file(input_file, output_file, crypter_key, block_size):\n\n return 1\n\n else:\n\n print_err(\"Nothing to do\")\n\n return 255\n\n return 0\n\n\n\nif __name__ == \"__main__\":\n\n exit(main(len(argv) - 1, argv[1:]))\n", "file_path": "python/crypter/crypter.py", "rank": 82, "score": 57817.5000474035 }, { "content": "#!/usr/bin/env python\n\n\n\n\"\"\"\n\nDeveloped by Christian Visintin\n\nGenerate a random time in ISO8601\n\n\"\"\"\n\n\n\nfrom datetime import datetime\n\nfrom random import randint\n\nfrom time import time\n\nfrom sys import argv, exit\n\n\n\ndef main(argc, argv):\n\n if argc == 0:\n\n print(\"Usage: randtime.py <day_offset>\")\n\n return 255\n\n # Get offset\n\n offset = int(argv[0])\n\n # Get time\n\n t_now = int(time())\n\n # Days to second\n\n offset *= 86400\n\n # Generate random\n\n days = randint(0, offset)\n\n # Subtract days from time\n\n t_calc = t_now - days\n\n # Format time\n\n dt = datetime.fromtimestamp(t_calc)\n\n print(dt.strftime(\"%Y-%m-%dT%H:%M:%S%z\"))\n\n return 0\n\n\n\n\n\nif __name__ == \"__main__\":\n\n args = argv[1:]\n\n exit(main(len(args), args))\n", "file_path": "python/randtime/randtime.py", "rank": 83, "score": 57795.07256137574 }, { "content": "#!/usr/bin/python3\n\n\n\n\"\"\"\n\nDeveloped by Christian Visintin\n\n\n\nSubvar is a simple python script which replaces ${VAR} and $VAR with values taken from env\n\n\"\"\"\n\n\n\n#Getopt\n\nfrom getopt import getopt, GetoptError\n\n#Environ\n\nfrom os import environ\n\n#Regex\n\nimport re\n\n#System\n\nfrom sys import argv, exit\n\n\n\nPROGRAM_NAME = \"subvar\"\n\nUSAGE = \"%s [OPTIONS]... [FILE]\\n\\\n\n \\t-a\\t<placeholder>\\t\\t\\tReplace also unresolved variables (with placeholder)\\n\\\n\n \\t-o\\t<output_file>\\t\\t\\tSpecify a file where to output the new file content (Default stdout)\\n\\\n\n \\t-h\\t\\t\\t\\tShow this page\\n\\\n\n \" % PROGRAM_NAME\n\n\n\nKNRM = \"\\x1B[0m\"\n\nKRED = \"\\x1B[31m\"\n\nKGRN = \"\\x1B[32m\"\n\nKYEL = \"\\x1B[33m\"\n\nKBLU = \"\\x1B[34m\"\n\nKMAG = \"\\x1B[35m\"\n\nKCYN = \"\\x1B[36m\"\n\nKWHT = \"\\x1B[37m\"\n\n\n\ndef print_err(message: str):\n\n \"\"\"\n\n Print error\n\n\n\n :param message: message to print\n\n :type message: str\n\n \"\"\"\n\n print(\"%s%s%s\" % (KRED, message, KNRM))\n\n\n\ndef opt_err(message: str):\n\n \"\"\"\n\n Function to call in case of an error while parsing options and terminates with exit code 255\n\n\n\n :param message: message to write\n\n :type message: str\n\n \"\"\"\n\n print_err(\"Configuration Error: %s\" % message)\n\n print(USAGE)\n\n exit(255)\n\n\n\ndef process_input(content: str, replace_all: bool, placeholder: str = '') -> str:\n\n \"\"\"\n\n Process the input and returns the replaced values in the file\n\n\n\n :param content: file content\n\n :param replace_all: should unresolved values be replaced?\n\n :param placeholder: the placeholder in case of unresolved values\n\n :type content: str\n\n :type replace_all: bool\n\n :type placeholder: str\n\n :returns str\n\n \"\"\"\n\n #Search for vars with syntax ${VAR}\n\n output = \"\"\n\n shell_regex = \"\\\\${?(.*?)([\\\\ ,/,\\\\),\\\\\\\",;,\\\\n}])\"\n\n for line in content.splitlines():\n\n #reg_result = re.findall(\"\\\\${(.*?)}\", line)\n\n reg_result = re.findall(shell_regex, line, re.DOTALL)\n\n for i in range(len(reg_result)):\n\n reg_group = reg_result[i]\n\n trailing_char = None\n\n if type(reg_group) == tuple:\n\n var_name = reg_group[0]\n\n trailing_char = reg_group[1]\n\n else:\n\n var_name = reg_group\n\n #@! Okay, there is a variable to replace\n\n #Search for session variable\n\n var_value = environ.get(var_name)\n\n if not var_value: #If value is not found, check for replace all\n\n if replace_all:\n\n var_value = placeholder #If replace all is true, use placeholder\n\n else:\n\n continue #Otherwise keep ${VAR_NAME}\n\n if trailing_char:\n\n #If trailing char is not '}', add trailing char to end of var value\n\n if trailing_char != '}':\n\n var_value += trailing_char\n\n #Replace session variable\n\n line = re.sub(shell_regex, var_value, line, 1)\n\n output += \"%s\\n\" % line\n\n return output\n\n\n\ndef main(argc: int, argv: list) -> int:\n\n #Options\n\n file_name = None\n\n output_file = None\n\n replace_all = False\n\n placeholder = ''\n\n #Get options\n\n try:\n\n optlist, args = getopt(argv, \"a::o::h\")\n\n #Iterate over options\n\n for opt, arg in optlist:\n\n if opt == \"-a\":\n\n replace_all = True\n\n placeholder = arg\n\n if opt == \"-o\":\n\n output_file = arg\n\n elif opt == \"-h\":\n\n print(USAGE)\n\n return 255\n\n #Look for database path\n\n if args:\n\n file_name = args[0]\n\n else:\n\n opt_err(\"File is missing!\")\n\n except GetoptError as err:\n\n opt_err(err)\n\n #Read file\n\n try:\n\n hnd = open(file_name, \"r\")\n\n content = hnd.read()\n\n hnd.close()\n\n except IOError as err:\n\n print_err(\"Could not read file %s: %s\" % (file_name, err))\n\n return 1\n\n content = process_input(content, replace_all, placeholder)\n\n if output_file:\n\n try:\n\n hnd = open(output_file, \"w\")\n\n hnd.write(content)\n\n hnd.close()\n\n except IOError as err:\n\n print_err(\"Could not write out file %s: %s\" % (output_file, err))\n\n return 1\n\n else:\n\n print(content)\n\n return 0\n\n\n\nif __name__ == \"__main__\":\n\n exit(main(len(argv[1:]), argv[1:]))\n", "file_path": "python/subvar/subvar.py", "rank": 84, "score": 57794.286309912626 }, { "content": "\"\"\"\n\nDeveloped by Christian Visintin\n\n\n\nlogrotate-cli is a simple python script which will rotate the log you provide if the size exceeds.\n\nIt will create n rotation with syntax LOGFILE.{ROTATION_NUMBER}.log\n\n\"\"\"\n\n\n\nfrom io import TextIOWrapper\n\n\n\ndef struncate(file: TextIOWrapper, amount: int):\n\n \"\"\"\n\n Truncate the first n bytes from the beginning of file\n\n\n\n :param file\n\n :param amount: amount of bytes to remove from start\n\n :type file: TextIOWrapper\n\n :type amount: int\n\n \"\"\"\n\n #Get file size\n\n file.seek(0, 2)\n\n file_size = file.tell()\n\n #Go to the beginning of file\n\n file_offset = amount\n\n file.seek(0, 0)\n\n bytes_to_write = file_size - amount\n\n bytes_written = 0\n\n while bytes_written < bytes_to_write:\n\n #Move to offset + bytes_written\n\n file.seek(file_offset + bytes_written, 0)\n\n #Get bytes to rewrite\n\n block_size = 1024\n\n if bytes_to_write - bytes_written < block_size:\n\n block_size = bytes_to_write - bytes_written\n\n #Read block\n\n block_data = file.read(block_size)\n\n #Move to the beginning of file + bytes_written\n\n file.seek(bytes_written, 0)\n\n #Write block\n\n bytes_written += file.write(block_data)\n\n #Then truncate\n\n file.flush() #Flush write first\n\n file.seek(bytes_written)\n\n file.truncate()\n", "file_path": "python/struncate/struncate.py", "rank": 85, "score": 57793.356818608554 }, { "content": "int main(int argc, char** argv) {\n\n\n\n struct timeval t0, tdelta, tdiff;\n\n\n\n gettimeofday(&t0, NULL);\n\n usleep(50000); //50ms\n\n gettimeofday(&tdelta, NULL);\n\n timersub(&tdelta, &t0, &tdiff);\n\n\n\n printf(\"Time 0: %ld.%06ld\\n\", t0.tv_sec, t0.tv_usec);\n\n printf(\"Time Delta: %ld.%06ld\\n\", tdelta.tv_sec, tdelta.tv_usec);\n\n printf(\"Time diff: %ld.%06ld\\n\", tdiff.tv_sec, tdiff.tv_usec);\n\n\n\n return 0;\n", "file_path": "c/elapsed-us/main.c", "rank": 86, "score": 57786.97483370167 }, { "content": " MessageType msg_type;\n", "file_path": "c/union/union.c", "rank": 87, "score": 57786.97483370167 }, { "content": "unsigned int sigterm_raised = 0;\n", "file_path": "c/sigint/sigint.c", "rank": 88, "score": 57786.97483370167 }, { "content": "int main(int argc, char** argv) {\n\n\n\n if (argc < 2) {\n\n printf(\"Usage: %s <value>\\n\", argv[0]);\n\n return 255;\n\n }\n\n //Get value\n\n const uint64_t value = (uint64_t) atoll(argv[1]);\n\n const size_t bytes_size = get_bytes_size(value);\n\n printf(\"Bytes size is %lu\\n\", bytes_size);\n\n const size_t ascii_size = bytes_size * 2;\n\n char* ascii = (char*) malloc(sizeof(char) * (ascii_size + 1));\n\n uint_to_ascii(ascii, ascii_size, value);\n\n ascii[ascii_size] = 0x00;\n\n printf(\"Value %llu => Ascii: 0x%s\\n\", value, ascii);\n\n free(ascii);\n\n return 0;\n\n\n", "file_path": "c/uintToAscii/main.c", "rank": 89, "score": 57786.97483370167 }, { "content": "void print_message(const Message* message) {\n\n for (size_t i = 0; i < message->data_size; i++) {\n\n printf(\"%02x \", message->data.buffer[i]);\n\n }\n\n printf(\"\\n\");\n\n switch (message->msg_type) {\n\n case Heartbeat:\n\n printf(\"Heartbeat - error_state: %u\\n\", message->data.heartbeat.error_state);\n\n break;\n\n case Event:\n\n printf(\"Event - event_type %u; event_id %u; duration %lu\\n\", message->data.event.event_type, message->data.event.event_id, message->data.event.duration);\n\n break;\n\n }\n", "file_path": "c/union/union.c", "rank": 90, "score": 57786.97483370167 }, { "content": "void handle_sigterm(int s) {\n\n printf(\"\\nRaised Signal %d\\n\", s);\n\n sigterm_raised = 1;\n", "file_path": "c/sigint/sigint.c", "rank": 91, "score": 57786.97483370167 }, { "content": "/// ### input_ready\n\n/// \n\n/// Returns whether stdin is ready to be read\n\nfn input_ready() -> bool {\n\n prepare_termios();\n\n let mut poll_fds: [nix::poll::PollFd; 1] = [nix::poll::PollFd::new(STDIN_FILENO, nix::poll::PollFlags::POLLIN | nix::poll::PollFlags::POLLRDBAND | nix::poll::PollFlags::POLLHUP)];\n\n let ready: bool = match nix::poll::poll(&mut poll_fds, 100) {\n\n Ok(ret) => {\n\n if ret > 0 && poll_fds[0].revents().is_some() { //Stdin is available to be read\n\n let event: nix::poll::PollFlags = poll_fds[0].revents().unwrap();\n\n if event.intersects(nix::poll::PollFlags::POLLIN) || event.intersects(nix::poll::PollFlags::POLLRDBAND) {\n\n true\n\n } else {\n\n false\n\n }\n\n } else {\n\n false\n\n }\n\n },\n\n Err(_) => false\n\n };\n\n reset_termios();\n\n ready\n\n}\n\n\n", "file_path": "rust/console/console.rs", "rank": 92, "score": 55541.35325147501 }, { "content": "#!/usr/bin/python3\n\n\n\n\"\"\"\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n Version 2, December 2004\n\n\n\n Copyright (C) 2020 Christian Visintin\n\n\n\n Everyone is permitted to copy and distribute verbatim or modified\n\n copies of this license document, and changing it is allowed as long\n\n as the name is changed.\n\n\n\n DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n\n TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n\n\n 0. You just DO WHAT THE FUCK YOU WANT TO.\n\n\"\"\"\n\n\n\n# Base64\n\nfrom base64 import b64encode, b64decode\n\n#Enums\n\nfrom enum import Enum\n\n# Getopt\n\nfrom getopt import getopt, GetoptError\n\n# Argv, exit, stdin, stderr\n\nfrom sys import argv, exit, stdin, stderr, stdout\n\n# Typing\n\nfrom typing import List, Union\n\n\n\nPROGRAM_NAME = \"base64-cli.py\"\n\nUSAGE = \"%s [OPTIONS...]\\n\\\n\n Where options are:\\n\\\n\n \\t-d\\t\\t\\tDecode\\n\\\n\n \\t-e\\t\\t\\tEncode\\n\\\n\n \\t-i\\t<file>\\t\\tIf specified read data from file\\n\\\n\n \\t-o\\t<file>\\t\\tIf specified write data to file\\n\\\n\n \\t-h\\t\\t\\tShow this page\\n\\\n\n \" % PROGRAM_NAME\n\n\n\nKNRM = \"\\x1B[0m\"\n\nKRED = \"\\x1B[31m\"\n\nKGRN = \"\\x1B[32m\"\n\nKYEL = \"\\x1B[33m\"\n\nKBLU = \"\\x1B[34m\"\n\nKMAG = \"\\x1B[35m\"\n\nKCYN = \"\\x1B[36m\"\n\nKWHT = \"\\x1B[37m\"\n\n\n\ndef print_err(message: str):\n\n \"\"\"\n\n Print error\n\n\n\n :param message: message to print\n\n :type message: str\n\n \"\"\"\n\n print(\"%s%s%s\" % (KRED, message, KNRM), file=stderr)\n\n\n\ndef print_info(message: str):\n\n \"\"\"\n\n Print information.\n\n The message will be displayed only when set in verbose mode\n\n\n\n :param message: message to print\n\n :type message: str\n\n \"\"\"\n\n global verbose\n\n if verbose:\n\n print(\"%s%s%s\" % (KYEL, message, KNRM), file=stderr)\n\n\n\ndef usage(err: str = None):\n\n \"\"\"\n\n Print usage\n\n \"\"\"\n\n if err:\n\n print_err(err)\n\n print(\"%s\" % USAGE)\n\n\n\nclass EndecoderAction(Enum):\n\n DECODE = 0\n\n ENCODE = 1\n\n UNDEFINED = 2\n\n\n\ndef read_input(source: Union[str, None]) -> bytes:\n\n \"\"\"\n\n Read input from provided source.\n\n If source is None, input is read from stdin\n\n\n\n :param source: input source\n\n :type source: str\n\n :returns bytes\n\n :raises IOError\n\n \"\"\"\n\n if source:\n\n hnd = open(source, \"rb\")\n\n else:\n\n hnd = stdin\n\n data = hnd.read()\n\n if source:\n\n hnd.close()\n\n # Convert data to bytes\n\n if isinstance(data, str):\n\n data = data.encode(\"utf-8\")\n\n return data\n\n\n\ndef write_output(data: bytes, output_file: Union[str, None]):\n\n \"\"\"\n\n Write output to file or to stdout if output_file is None\n\n\n\n :param data\n\n :type data bytes\n\n :raises IOException\n\n \"\"\"\n\n if output_file:\n\n hnd = open(output_file, \"wb\")\n\n else:\n\n hnd = stdout\n\n # Convert data to string\n\n data = \"%s\\n\" % data.decode(\"utf-8\")\n\n hnd.write(data)\n\n if output_file:\n\n hnd.close()\n\n\n\ndef base64_encode(data: bytes) -> bytes:\n\n \"\"\"\n\n Encode data to base64\n\n\n\n :param data\n\n :type data bytes\n\n :returns bytes\n\n \"\"\"\n\n return b64encode(data)\n\n\n\ndef base64_decode(data: bytes) -> bytes:\n\n \"\"\"\n\n Decode data from base64\n\n\n\n :param data\n\n :type data bytes\n\n :returns bytes\n\n \"\"\"\n\n return b64decode(data)\n\n\n\ndef main(argc: int, argv: List[str]) -> int:\n\n mode = EndecoderAction.UNDEFINED\n\n input_file = None # Stdin\n\n output_file = None # Stdout\n\n try:\n\n optlist, _ = getopt(argv, \"edi::o::h\")\n\n #Iterate over options\n\n for opt, arg in optlist:\n\n if opt == \"-d\":\n\n mode = EndecoderAction.DECODE\n\n elif opt == \"-e\":\n\n mode = EndecoderAction.ENCODE\n\n elif opt == \"-i\":\n\n input_file = arg\n\n elif opt == \"-o\":\n\n output_file = arg\n\n elif opt == \"-h\":\n\n usage()\n\n return 255\n\n except GetoptError as err:\n\n usage(err)\n\n return 255\n\n # Check mode\n\n if mode == EndecoderAction.UNDEFINED:\n\n usage(\"Please define mode (encode, decode)\")\n\n return 255\n\n # Get input\n\n try:\n\n input_data = read_input(input_file)\n\n except Exception as err:\n\n print_err(\"Could not read input: %s\" % err)\n\n return 1\n\n # Encode / decode\n\n if mode == EndecoderAction.ENCODE:\n\n try:\n\n output_data = base64_encode(input_data)\n\n except Exception as err:\n\n print_err(\"Could not encode to base64: %s\" % err)\n\n return 1\n\n elif mode == EndecoderAction.DECODE:\n\n try:\n\n output_data = base64_decode(input_data)\n\n except Exception as err:\n\n print_err(\"Could not decode from base64: %s\" % err)\n\n return 1\n\n # Write output\n\n try:\n\n write_output(output_data, output_file)\n\n except Exception as err:\n\n print_err(\"Could not write output: %s\" % err)\n\n return 1\n\n return 0\n\n\n\nif __name__ == \"__main__\":\n\n exit(main(len(argv) - 1, argv[1:]))\n", "file_path": "python/base64/base64-cli.py", "rank": 93, "score": 55536.33553265671 }, { "content": "FB_Error framebuffer_write(Framebuffer* fb, const size_t x, const size_t y, FramebufferColor* color) {\n\n if (fb == NULL) {\n\n return FRAMEBUFFER_ERROR_UNINITIALIZED;\n\n }\n\n if (framebuffer_isopen(fb) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return FRAMEBUFFER_ERROR_UNINITIALIZED;\n\n }\n\n if (color == NULL) {\n\n return FRAMEBUFFER_ERROR_INVALID_COLOR;\n\n }\n\n return color_write(fb, x, y, color);\n", "file_path": "c/easyfb/src/framebuffer.c", "rank": 94, "score": 55512.15678399155 }, { "content": "def struncate(file: TextIOWrapper, amount: int):\n\n \"\"\"\n\n Truncate the first n bytes from the beginning of file\n\n\n\n :param file\n\n :param amount: amount of bytes to remove from start\n\n :type file: TextIOWrapper\n\n :type amount: int\n\n \"\"\"\n\n #Get file size\n\n file.seek(0, 2)\n\n file_size = file.tell()\n\n #Go to the beginning of file\n\n file_offset = amount\n\n file.seek(0, 0)\n\n bytes_to_write = file_size - amount\n\n bytes_written = 0\n\n while bytes_written < bytes_to_write:\n\n #Move to offset + bytes_written\n\n file.seek(file_offset + bytes_written, 0)\n\n #Get bytes to rewrite\n\n block_size = 1024\n\n if bytes_to_write - bytes_written < block_size:\n\n block_size = bytes_to_write - bytes_written\n\n #Read block\n\n block_data = file.read(block_size)\n\n #Move to the beginning of file + bytes_written\n\n file.seek(bytes_written, 0)\n\n #Write block\n\n bytes_written += file.write(block_data)\n\n #Then truncate\n\n file.flush() #Flush write first\n\n file.seek(bytes_written)\n", "file_path": "python/struncate/struncate.py", "rank": 95, "score": 55510.455785467326 }, { "content": "FB_Error framebuffer_close(Framebuffer* fb) {\n\n if (fb == NULL) {\n\n return FRAMEBUFFER_ERROR_UNINITIALIZED;\n\n }\n\n if (framebuffer_isopen(fb) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return FRAMEBUFFER_ERROR_IS_CLOSED;\n\n }\n\n //Try to close fb\n\n if (close(fb->fd) == -1) {\n\n return FRAMEBUFFER_ERROR_CLOSE;\n\n }\n\n //Unmap area\n\n if (fb->area != NULL) {\n\n munmap(fb->area, fb->size);\n\n }\n\n //Reset parameters\n\n fb->fd = -1;\n\n fb->width = 0;\n\n fb->height = 0;\n\n fb->x_offset = 0;\n\n fb->y_offset = 0;\n\n fb->area = NULL;\n\n return FRAMEBUFFER_ERROR_SUCCESS;\n", "file_path": "c/easyfb/src/framebuffer.c", "rank": 96, "score": 55509.900648785086 }, { "content": "FB_Error framebuffer_open(Framebuffer* fb, const char* dev) {\n\n if (fb == NULL) {\n\n return FRAMEBUFFER_ERROR_UNINITIALIZED;\n\n }\n\n\n\n //Open framebuffer\n\n if ((fb->fd = open(dev, O_RDWR)) > 2) {\n\n if (ioctl(fb->fd, FBIOGET_VSCREENINFO, &fb->vinfo) >= 0) {\n\n fb->size = (size_t) (fb->vinfo.xres_virtual * fb->vinfo.yres_virtual * (fb->vinfo.bits_per_pixel / 8));\n\n fb->depth = fb->vinfo.bits_per_pixel;\n\n fb->area = (uint8_t*) mmap(0, fb->size, PROT_READ | PROT_WRITE, MAP_SHARED, fb->fd, 0);\n\n if (fb->width == 0) {\n\n fb->width = fb->vinfo.xres;\n\n }\n\n if (fb->height == 0) {\n\n fb->height = fb->vinfo.yres;\n\n }\n\n fb->alpha = (fb->vinfo.transp.length > 0) ? 1 : 0;\n\n } else {\n\n framebuffer_close(fb);\n\n return FRAMEBUFFER_ERROR_OPEN;\n\n }\n\n } else {\n\n return FRAMEBUFFER_ERROR_OPEN;\n\n }\n\n return FRAMEBUFFER_ERROR_SUCCESS;\n", "file_path": "c/easyfb/src/framebuffer.c", "rank": 97, "score": 55509.688329360666 }, { "content": "FB_Error framebuffer_clear(Framebuffer* fb) {\n\n FB_Error err;\n\n if ((err = framebuffer_isopen(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return err;\n\n }\n\n FramebufferColor* color = NULL;\n\n if ((err = color_init(&color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return err;\n\n }\n\n switch (fb->depth) {\n\n case 16: {\n\n FramebufferColorRGB16* ptr = (FramebufferColorRGB16*) malloc(sizeof(FramebufferColorRGB16));\n\n ptr->blue = 0x00;\n\n ptr->green = 0x00;\n\n ptr->red = 0x00;\n\n color->color_ptr = (void*) ptr;\n\n color->syntax = Color_RGB16;\n\n break;\n\n }\n\n case 24: {\n\n FramebufferColorRGB24* ptr = (FramebufferColorRGB24*) malloc(sizeof(FramebufferColorRGB24));\n\n ptr->blue = 0x00;\n\n ptr->green = 0x00;\n\n ptr->red = 0x00;\n\n color->color_ptr = (void*) ptr;\n\n color->syntax = Color_RGB24;\n\n break;\n\n }\n\n case 32: {\n\n FramebufferColorRGB32* ptr = (FramebufferColorRGB32*) malloc(sizeof(FramebufferColorRGB32));\n\n ptr->alpha = 0x00;\n\n ptr->blue = 0x00;\n\n ptr->green = 0x00;\n\n ptr->red = 0x00;\n\n color->color_ptr = (void*) ptr;\n\n color->syntax = Color_RGB32;\n\n break;\n\n }\n\n }\n\n\n\n for (size_t y = 0; y < fb->height; y++) {\n\n for (size_t x = 0; x < fb->width; x++) {\n\n if ((err = framebuffer_write(fb, x, y, color)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return err;\n\n }\n\n }\n\n }\n\n color_cleanup(color);\n\n return FRAMEBUFFER_ERROR_SUCCESS;\n", "file_path": "c/easyfb/src/framebuffer.c", "rank": 98, "score": 55509.688329360666 }, { "content": "FB_Error framebuffer_cleanup(Framebuffer* fb) {\n\n if (fb == NULL) {\n\n return FRAMEBUFFER_ERROR_UNINITIALIZED;\n\n }\n\n //If framebuffer is open, close it first\n\n if (framebuffer_isopen(fb) != FRAMEBUFFER_ERROR_IS_CLOSED) {\n\n FB_Error err;\n\n if ((err = framebuffer_close(fb)) != FRAMEBUFFER_ERROR_SUCCESS) {\n\n return err;\n\n }\n\n }\n\n free(fb);\n\n return FRAMEBUFFER_ERROR_SUCCESS;\n", "file_path": "c/easyfb/src/framebuffer.c", "rank": 99, "score": 55509.688329360666 } ]
Rust
core/executor/runtime-test/src/lib.rs
HPIPS/HPIPS_Chain
9c4a5ee923af876c89bb2cc629fd96b11add8196
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature = "strict", deny(warnings))] #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use rstd::{vec::Vec, slice, vec}; use runtime_io::{ set_storage, storage, clear_prefix, print, blake2_128, blake2_256, twox_128, twox_256, ed25519_verify, sr25519_verify, enumerated_trie_root }; macro_rules! impl_stubs { ( $( $new_name:ident => $invoke:expr, )* ) => { $( impl_stubs!(@METHOD $new_name => $invoke); )* }; ( @METHOD $new_name:ident => $invoke:expr ) => { #[no_mangle] pub fn $new_name(input_data: *mut u8, input_len: usize) -> u64 { let input: &[u8] = if input_len == 0 { &[0u8; 0] } else { unsafe { slice::from_raw_parts(input_data, input_len) } }; let output: Vec<u8> = $invoke(input); let res = output.as_ptr() as u64 + ((output.len() as u64) << 32); rstd::mem::forget(output); res } }; } impl_stubs!( test_data_in => |input| { print("set_storage"); set_storage(b"input", input); print("storage"); let foo = storage(b"foo").unwrap(); print("set_storage"); set_storage(b"baz", &foo); print("finished!"); b"all ok!".to_vec() }, test_clear_prefix => |input| { clear_prefix(input); b"all ok!".to_vec() }, test_empty_return => |_| Vec::new(), test_exhaust_heap => |_| Vec::with_capacity(16777216), test_panic => |_| panic!("test panic"), test_conditional_panic => |input: &[u8]| { if input.len() > 0 { panic!("test panic") } input.to_vec() }, test_blake2_256 => |input| blake2_256(input).to_vec(), test_blake2_128 => |input| blake2_128(input).to_vec(), test_twox_256 => |input| twox_256(input).to_vec(), test_twox_128 => |input| twox_128(input).to_vec(), test_ed25519_verify => |input: &[u8]| { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; [ed25519_verify(&sig, &msg[..], &pubkey) as u8].to_vec() }, test_sr25519_verify => |input: &[u8]| { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; [sr25519_verify(&sig, &msg[..], &pubkey) as u8].to_vec() }, test_enumerated_trie_root => |_| { enumerated_trie_root::<primitives::Blake2Hasher>( &[ &b"zero"[..], &b"one"[..], &b"two"[..], ] ).as_ref().to_vec() }, test_sandbox => |code: &[u8]| { let ok = execute_sandboxed(code, &[]).is_ok(); [ok as u8].to_vec() }, test_sandbox_args => |code: &[u8]| { let ok = execute_sandboxed( code, &[ sandbox::TypedValue::I32(0x12345678), sandbox::TypedValue::I64(0x1234567887654321), ] ).is_ok(); [ok as u8].to_vec() }, test_sandbox_return_val => |code: &[u8]| { let ok = match execute_sandboxed( code, &[ sandbox::TypedValue::I32(0x1336), ] ) { Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(0x1337))) => true, _ => false, }; [ok as u8].to_vec() }, test_sandbox_instantiate => |code: &[u8]| { let env_builder = sandbox::EnvironmentDefinitionBuilder::new(); let code = match sandbox::Instance::new(code, &env_builder, &mut ()) { Ok(_) => 0, Err(sandbox::Error::Module) => 1, Err(sandbox::Error::Execution) => 2, Err(sandbox::Error::OutOfBounds) => 3, }; [code].to_vec() }, test_offchain_local_storage => |_| { let kind = primitives::offchain::StorageKind::PERSISTENT; assert_eq!(runtime_io::local_storage_get(kind, b"test"), None); runtime_io::local_storage_set(kind, b"test", b"asd"); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"asd".to_vec())); let res = runtime_io::local_storage_compare_and_set(kind, b"test", Some(b"asd"), b""); assert_eq!(res, true); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"".to_vec())); [0].to_vec() }, test_offchain_local_storage_with_none => |_| { let kind = primitives::offchain::StorageKind::PERSISTENT; assert_eq!(runtime_io::local_storage_get(kind, b"test"), None); let res = runtime_io::local_storage_compare_and_set(kind, b"test", None, b"value"); assert_eq!(res, true); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"value".to_vec())); [0].to_vec() }, test_offchain_http => |_| { use primitives::offchain::HttpRequestStatus; let run = || -> Option<()> { let id = runtime_io::http_request_start("POST", "http://localhost:12345", &[]).ok()?; runtime_io::http_request_add_header(id, "X-Auth", "test").ok()?; runtime_io::http_request_write_body(id, &[1, 2, 3, 4], None).ok()?; runtime_io::http_request_write_body(id, &[], None).ok()?; let status = runtime_io::http_response_wait(&[id], None); assert!(status == vec![HttpRequestStatus::Finished(200)], "Expected Finished(200) status."); let headers = runtime_io::http_response_headers(id); assert_eq!(headers, vec![(b"X-Auth".to_vec(), b"hello".to_vec())]); let mut buffer = vec![0; 64]; let read = runtime_io::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 3); assert_eq!(&buffer[0..read], &[1, 2, 3]); let read = runtime_io::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 0); Some(()) }; [if run().is_some() { 0 } else { 1 }].to_vec() }, ); fn execute_sandboxed(code: &[u8], args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { struct State { counter: u32, } fn env_assert(_e: &mut State, args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { if args.len() != 1 { return Err(sandbox::HostError); } let condition = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; if condition != 0 { Ok(sandbox::ReturnValue::Unit) } else { Err(sandbox::HostError) } } fn env_inc_counter(e: &mut State, args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { if args.len() != 1 { return Err(sandbox::HostError); } let inc_by = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; e.counter += inc_by as u32; Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(e.counter as i32))) } let mut state = State { counter: 0 }; let env_builder = { let mut env_builder = sandbox::EnvironmentDefinitionBuilder::new(); env_builder.add_host_func("env", "assert", env_assert); env_builder.add_host_func("env", "inc_counter", env_inc_counter); let memory = match sandbox::Memory::new(1, Some(16)) { Ok(m) => m, Err(_) => unreachable!(" Memory::new() can return Err only if parameters are borked; \ We passing params here explicitly and they're correct; \ Memory::new() can't return a Error qed" ), }; env_builder.add_memory("env", "memory", memory.clone()); env_builder }; let mut instance = sandbox::Instance::new(code, &env_builder, &mut state)?; let result = instance.invoke(b"call", args, &mut state); result.map_err(|_| sandbox::HostError) }
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature = "strict", deny(warnings))] #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use rstd::{vec::Vec, slice, vec}; use runtime_io::{ set_storage, storage, clear_prefix, print, blake2_128, blake2_256, twox_128, twox_256, ed25519_verify, sr25519_verify, enumerated_trie_root }; macro_rules! impl_stubs { ( $( $new_name:ident => $invoke:expr, )* ) => { $( impl_stubs!(@METHOD $new_name => $invoke); )* }; ( @METHOD $new_name:ident => $invoke:expr ) => { #[no_mangle] pub fn $new_name(input_data: *mut u8, input_len: usize) -> u64 { let input: &[u8] = if input_len == 0 { &[0u8; 0] } else { unsafe { slice::from_raw_parts(input_data, input_len) } }; let output: Vec<u8> = $invoke(input); let res = output.as_ptr() as u64 + ((output.len() as u64) << 32); rstd::mem::forget(output); res } }; } impl_stubs!( test_data_in => |input| { print("set_storage"); set_storage(b"input", input); print("storage"); let foo = storage(b"foo").unwrap(); print("set_storage"); set_storage(b"baz", &foo); print("finished!"); b"all ok!".to_vec() }, test_clear_prefix => |input| { clear_prefix(input); b"all ok!".to_vec() }, test_empty_return => |_| Vec::new(), test_exhaust_heap => |_| Vec::with_capacity(16777216), test_panic => |_| panic!("test panic"), test_conditional_panic => |input: &[u8]| { if input.len() > 0 { panic!("test panic") } input.to_vec() }, test_blake2_256 => |input| blake2_256(input).to_vec(), test_blake2_128 => |input| blake2_128(input).to_vec(), test_twox_256 => |input| twox_256(input).to_vec(), test_twox_128 => |input| twox_128(input).to_vec(), test_ed25519_verify => |input: &[u8]| { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; [ed25519_verify(&sig, &msg[..], &pubkey) as u8].to_vec() }, test_sr25519_verify => |input: &[u8]| { let mut pubkey = [0; 32]; let mut sig = [0; 64]; pubkey.copy_from_slice(&input[0..32]); sig.copy_from_slice(&input[32..96]); let msg = b"all ok!"; [sr25519_verify(&sig, &msg[..], &pubkey) as u8].to_vec() }, test_enumerated_trie_root => |_| { enumerated_trie_root::<primitives::Blake2Hasher>( &[ &b"zero"[..], &b"one"[..], &b"two"[..], ] ).as_ref().to_vec() }, test_sandbox => |code: &[u8]| { let ok = execute_sandboxed(code, &[]).is_ok(); [ok as u8].to_vec() }, test_sandbox_args => |code: &[u8]| { let ok = execute_sandboxed( code, &[ sandbox::TypedValue::I32(0x12345678), sandbox::TypedValue::I64(0x1234567887654321), ] ).is_ok(); [ok as u8].to_vec() }, test_sandbox_return_val => |code: &[u8]| { let ok = match execute_sandboxed( code, &[ sandbox::TypedValue::I32(0x1336), ] ) { Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(0x1337))) => true, _ => false, }; [ok as u8].to_vec() }, test_sandbox_instantiate => |code: &[u8]| { let env_builder = sandbox::EnvironmentDefinitionBuilder::new(); let code = match sandbox::Instance::new(code, &env_builder, &mut ()) { Ok(_) => 0, Err(sandbox::Error::Module) => 1, Err(sandbox::Error::Execution) => 2, Err(sandbox::Error::OutOfBounds) => 3, }; [code].to_vec() }, test_offchain_local_storage => |_| { let kind = primitives::offchain::StorageKind::PERSISTENT; assert_eq!(runtime_io::local_storage_get(kind, b"test"), None); runtime_io::local_storage_set(kind, b"test", b"asd"); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"asd".to_vec())); let res = runtime_io::local_storage_compare_and_set(kind, b"test", Some(b"asd"), b""); assert_eq!(res, true); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"".to_vec())); [0].to_vec() }, test_offchain_local_storage_with_none => |_| { let kind = primitives::offchain::StorageKind::PERSISTENT; assert_eq!(runtime_io::local_storage_get(kind, b"test"), None); let res = runtime_io::local_storage_compare_and_set(kind, b"test", None, b"value"); assert_eq!(res, true); assert_eq!(runtime_io::local_storage_get(kind, b"test"), Some(b"value".to_vec())); [0].to_vec() }, test_offchain_http => |_| { use primitives::offchain::HttpRequestStatus; let run = || -> Option<()> { let id = runtime_io::http_request_start("POST", "http://localhost:12345", &[]).ok()?; runtime_io::http_request_add_header(id, "X-Auth", "test").ok()?; runtime_io::http_request_write_body(id, &[1, 2, 3, 4], None).ok()?; runtime_io::http_request_write_body(id, &[], None).ok()?; let status = runtime_io::http_response_wait(&[id], None); assert!(status == vec![HttpRequestStatus::Finished(200)], "Expected Finished(200) status."); let headers = runtime_io::http_response_headers(id); assert_eq!(headers, vec![(b"X-Auth".to_vec(), b"hello".to_vec())]); let mut buffer = vec![0; 64]; let read = runtime_io::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 3); assert_eq!(&buffer[0..read], &[1, 2, 3]); let read = runtime_io::http_response_read_body(id, &mut buffer, None).ok()?; assert_eq!(read, 0); Some(()) }; [if run().is_some() { 0 } else { 1 }].to_vec() }, ); fn execute_sandboxed(code: &[u8], args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { struct State { counter: u32, } fn env_assert(_e: &mut State, args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { if args.len() !=
fn env_inc_counter(e: &mut State, args: &[sandbox::TypedValue]) -> Result<sandbox::ReturnValue, sandbox::HostError> { if args.len() != 1 { return Err(sandbox::HostError); } let inc_by = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; e.counter += inc_by as u32; Ok(sandbox::ReturnValue::Value(sandbox::TypedValue::I32(e.counter as i32))) } let mut state = State { counter: 0 }; let env_builder = { let mut env_builder = sandbox::EnvironmentDefinitionBuilder::new(); env_builder.add_host_func("env", "assert", env_assert); env_builder.add_host_func("env", "inc_counter", env_inc_counter); let memory = match sandbox::Memory::new(1, Some(16)) { Ok(m) => m, Err(_) => unreachable!(" Memory::new() can return Err only if parameters are borked; \ We passing params here explicitly and they're correct; \ Memory::new() can't return a Error qed" ), }; env_builder.add_memory("env", "memory", memory.clone()); env_builder }; let mut instance = sandbox::Instance::new(code, &env_builder, &mut state)?; let result = instance.invoke(b"call", args, &mut state); result.map_err(|_| sandbox::HostError) }
1 { return Err(sandbox::HostError); } let condition = args[0].as_i32().ok_or_else(|| sandbox::HostError)?; if condition != 0 { Ok(sandbox::ReturnValue::Unit) } else { Err(sandbox::HostError) } }
function_block-function_prefixed
[ { "content": "/// Run whatever tests we have.\n\npub fn run_tests(mut input: &[u8]) -> Vec<u8> {\n\n\tuse runtime_io::print;\n\n\n\n\tprint(\"run_tests...\");\n\n\tlet block = Block::decode(&mut input).unwrap();\n\n\tprint(\"deserialized block.\");\n\n\tlet stxs = block.extrinsics.iter().map(Encode::encode).collect::<Vec<_>>();\n\n\tprint(\"reserialized transactions.\");\n\n\t[stxs.len() as u8].encode()\n\n}\n\n\n", "file_path": "core/test-runtime/src/lib.rs", "rank": 0, "score": 544543.857509528 }, { "content": "/// Determine a child trie root given its ordered contents, closed form. H is the default hasher,\n\n/// but a generic implementation may ignore this type parameter and use other hashers.\n\npub fn child_trie_root<L: TrieConfiguration, I, A, B>(_storage_key: &[u8], input: I) -> Vec<u8>\n\n\twhere\n\n\t\tI: IntoIterator<Item = (A, B)>,\n\n\t\tA: AsRef<[u8]> + Ord,\n\n\t\tB: AsRef<[u8]>,\n\n{\n\n\tL::trie_root(input).as_ref().iter().cloned().collect()\n\n}\n\n\n", "file_path": "core/trie/src/lib.rs", "rank": 1, "score": 472528.90113930474 }, { "content": "fn take<'a>(input: &mut &'a[u8], count: usize) -> Option<&'a[u8]> {\n\n\tif input.len() < count {\n\n\t\treturn None\n\n\t}\n\n\tlet r = &(*input)[..count];\n\n\t*input = &(*input)[count..];\n\n\tSome(r)\n\n}\n\n\n\n/// Concrete implementation of a `NodeCodec` with Parity Codec encoding, generic over the `Hasher`\n\n#[derive(Default, Clone)]\n\npub struct NodeCodec<H>(PhantomData<H>);\n\n\n\nimpl<H: Hasher> NodeCodecT<H> for NodeCodec<H> {\n\n\ttype Error = Error;\n\n\n\n\tfn hashed_null_node() -> <H as Hasher>::Out {\n\n\t\tH::hash(<Self as NodeCodecT<_>>::empty_node())\n\n\t}\n\n\n", "file_path": "core/trie/src/node_codec.rs", "rank": 2, "score": 442112.0630848567 }, { "content": "/// Decode size only from stream input and header byte.\n\nfn decode_size(first: u8, input: &mut impl Input) -> Result<usize, codec::Error> {\n\n\tlet mut result = (first & 255u8 >> 2) as usize;\n\n\tif result < 63 {\n\n\t\treturn Ok(result);\n\n\t}\n\n\tresult -= 1;\n\n\twhile result <= trie_constants::NIBBLE_SIZE_BOUND {\n\n\t\tlet n = input.read_byte()? as usize;\n\n\t\tif n < 255 {\n\n\t\t\treturn Ok(result + n + 1);\n\n\t\t}\n\n\t\tresult += 255;\n\n\t}\n\n\tOk(trie_constants::NIBBLE_SIZE_BOUND)\n\n}\n", "file_path": "core/trie/src/node_header.rs", "rank": 3, "score": 392648.38947289827 }, { "content": "fn to_journal_key(block: u64, index: u64) -> Vec<u8> {\n\n\tto_meta_key(NON_CANONICAL_JOURNAL, &(block, index))\n\n}\n\n\n", "file_path": "core/state-db/src/noncanonical.rs", "rank": 4, "score": 386583.0450476821 }, { "content": "/// Encodes size and prefix to a stream output.\n\nfn encode_size_and_prefix(size: usize, prefix: u8, out: &mut impl Output) {\n\n\tfor b in size_and_prefix_iterator(size, prefix) {\n\n\t\tout.push_byte(b)\n\n\t}\n\n}\n\n\n", "file_path": "core/trie/src/node_header.rs", "rank": 5, "score": 385558.54277536005 }, { "content": "fn to_journal_key(block: u64) -> Vec<u8> {\n\n\tto_meta_key(PRUNING_JOURNAL, &block)\n\n}\n\n\n\nimpl<BlockHash: Hash, Key: Hash> RefWindow<BlockHash, Key> {\n\n\tpub fn new<D: MetaDb>(db: &D) -> Result<RefWindow<BlockHash, Key>, Error<D::Error>> {\n\n\t\tlet last_pruned = db.get_meta(&to_meta_key(LAST_PRUNED, &()))\n\n\t\t\t.map_err(|e| Error::Db(e))?;\n\n\t\tlet pending_number: u64 = match last_pruned {\n\n\t\t\tSome(buffer) => u64::decode(&mut buffer.as_slice())? + 1,\n\n\t\t\tNone => 0,\n\n\t\t};\n\n\t\tlet mut block = pending_number;\n\n\t\tlet mut pruning = RefWindow {\n\n\t\t\tdeath_rows: Default::default(),\n\n\t\t\tdeath_index: Default::default(),\n\n\t\t\tpending_number: pending_number,\n\n\t\t\tpending_canonicalizations: 0,\n\n\t\t\tpending_prunings: 0,\n\n\t\t};\n", "file_path": "core/state-db/src/pruning.rs", "rank": 6, "score": 383806.35924706573 }, { "content": "/// Read meta from the database.\n\npub fn read_meta<Block>(db: &dyn KeyValueDB, col_meta: Option<u32>, col_header: Option<u32>) -> Result<\n\n\tMeta<<<Block as BlockT>::Header as HeaderT>::Number, Block::Hash>,\n\n\tclient::error::Error,\n\n>\n\n\twhere\n\n\t\tBlock: BlockT,\n\n{\n\n\tlet genesis_hash: Block::Hash = match db.get(col_meta, meta_keys::GENESIS_HASH).map_err(db_err)? {\n\n\t\tSome(h) => match Decode::decode(&mut &h[..]) {\n\n\t\t\tOk(h) => h,\n\n\t\t\tErr(err) => return Err(client::error::Error::Backend(\n\n\t\t\t\tformat!(\"Error decoding genesis hash: {}\", err)\n\n\t\t\t)),\n\n\t\t},\n\n\t\tNone => return Ok(Meta {\n\n\t\t\tbest_hash: Default::default(),\n\n\t\t\tbest_number: Zero::zero(),\n\n\t\t\tfinalized_hash: Default::default(),\n\n\t\t\tfinalized_number: Zero::zero(),\n\n\t\t\tgenesis_hash: Default::default(),\n", "file_path": "core/client/db/src/utils.rs", "rank": 7, "score": 383475.2392495442 }, { "content": "/// Do a Blake2 512-bit hash and place result in `dest`.\n\npub fn blake2_512_into(data: &[u8], dest: &mut [u8; 64]) {\n\n\tdest.copy_from_slice(blake2_rfc::blake2b::blake2b(64, &[], data).as_bytes());\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 8, "score": 373226.1552164885 }, { "content": "/// Do a XX 256-bit hash and place result in `dest`.\n\npub fn twox_256_into(data: &[u8], dest: &mut [u8; 32]) {\n\n\tuse ::core::hash::Hasher;\n\n\tuse byteorder::{ByteOrder, LittleEndian};\n\n\tlet mut h0 = twox_hash::XxHash::with_seed(0);\n\n\tlet mut h1 = twox_hash::XxHash::with_seed(1);\n\n\tlet mut h2 = twox_hash::XxHash::with_seed(2);\n\n\tlet mut h3 = twox_hash::XxHash::with_seed(3);\n\n\th0.write(data);\n\n\th1.write(data);\n\n\th2.write(data);\n\n\th3.write(data);\n\n\tlet r0 = h0.finish();\n\n\tlet r1 = h1.finish();\n\n\tlet r2 = h2.finish();\n\n\tlet r3 = h3.finish();\n\n\tLittleEndian::write_u64(&mut dest[0..8], r0);\n\n\tLittleEndian::write_u64(&mut dest[8..16], r1);\n\n\tLittleEndian::write_u64(&mut dest[16..24], r2);\n\n\tLittleEndian::write_u64(&mut dest[24..32], r3);\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 9, "score": 373207.9426683689 }, { "content": "/// Do a Blake2 256-bit hash and place result in `dest`.\n\npub fn blake2_256_into(data: &[u8], dest: &mut [u8; 32]) {\n\n\tdest.copy_from_slice(blake2_rfc::blake2b::blake2b(32, &[], data).as_bytes());\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 10, "score": 373207.942668369 }, { "content": "/// Generate an unique pattern based on the given counter, if the given pattern is a `_`.\n\npub fn generate_unique_pattern(pat: Pat, counter: &mut u32) -> Pat {\n\n\tmatch pat {\n\n\t\tPat::Wild(_) => {\n\n\t\t\tlet generated_name = Ident::new(\n\n\t\t\t\t&format!(\"runtime_api_generated_name_{}\", counter),\n\n\t\t\t\tpat.span()\n\n\t\t\t);\n\n\t\t\t*counter += 1;\n\n\n\n\t\t\tparse_quote!( #generated_name )\n\n\t\t},\n\n\t\t_ => pat,\n\n\t}\n\n}\n\n\n", "file_path": "core/sr-api-macros/src/utils.rs", "rank": 11, "score": 372780.8984451635 }, { "content": "pub fn additional_storage_with_genesis(genesis_block: &crate::Block) -> HashMap<Vec<u8>, Vec<u8>> {\n\n\tmap![\n\n\t\ttwox_128(&b\"latest\"[..]).to_vec() => genesis_block.hash().as_fixed_bytes().to_vec()\n\n\t]\n\n}\n", "file_path": "core/test-runtime/src/genesismap.rs", "rank": 12, "score": 370710.86811919033 }, { "content": "pub fn balance_of_key(who: AccountId) -> Vec<u8> {\n\n\twho.to_keyed_vec(BALANCE_OF)\n\n}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 13, "score": 369447.3744020357 }, { "content": "/// Determine the default child trie root.\n\npub fn default_child_trie_root<L: TrieConfiguration>(_storage_key: &[u8]) -> Vec<u8> {\n\n\tL::trie_root::<_, Vec<u8>, Vec<u8>>(core::iter::empty()).as_ref().iter().cloned().collect()\n\n}\n\n\n", "file_path": "core/trie/src/lib.rs", "rank": 14, "score": 361513.5585172586 }, { "content": "fn bench_twox_128(b: &mut Bencher, key: &Vec<u8>) {\n\n\tb.iter(|| {\n\n\t\tlet _a = twox_128(black_box(key));\n\n\t});\n\n}\n\n\n", "file_path": "core/primitives/benches/benches.rs", "rank": 15, "score": 357018.07247176935 }, { "content": "fn bench_blake2_128(b: &mut Bencher, key: &Vec<u8>) {\n\n\tb.iter(|| {\n\n\t\tlet _a = blake2_128(black_box(key));\n\n\t});\n\n}\n\n\n", "file_path": "core/primitives/benches/benches.rs", "rank": 16, "score": 357018.07247176935 }, { "content": "/// Extract the data segments from the given wasm code.\n\n///\n\n/// Returns `Err` if the given wasm code cannot be deserialized.\n\nfn extract_data_segments(wasm_code: &[u8]) -> Option<Vec<DataSegment>> {\n\n\tlet raw_module: RawModule = deserialize_buffer(wasm_code).ok()?;\n\n\tlet segments = raw_module\n\n\t\t.data_section()\n\n\t\t.map(|ds| ds.entries())\n\n\t\t.unwrap_or(&[])\n\n\t\t.to_vec();\n\n\tSome(segments)\n\n}\n", "file_path": "core/executor/src/wasm_runtimes_cache.rs", "rank": 17, "score": 354201.44244372763 }, { "content": "fn encode_with_vec_prefix<T: Encode, F: Fn(&mut Vec<u8>)>(encoder: F) -> Vec<u8> {\n\n\tlet size = ::rstd::mem::size_of::<T>();\n\n\tlet reserve = match size {\n\n\t\t0..=0b00111111 => 1,\n\n\t\t0..=0b00111111_11111111 => 2,\n\n\t\t_ => 4,\n\n\t};\n\n\tlet mut v = Vec::with_capacity(reserve + size);\n\n\tv.resize(reserve, 0);\n\n\tencoder(&mut v);\n\n\n\n\t// need to prefix with the total length to ensure it's binary compatible with\n\n\t// Vec<u8>.\n\n\tlet mut length: Vec<()> = Vec::new();\n\n\tlength.resize(v.len() - reserve, ());\n\n\tlength.using_encoded(|s| {\n\n\t\tv.splice(0..reserve, s.iter().cloned());\n\n\t});\n\n\n\n\tv\n\n}\n", "file_path": "core/sr-primitives/src/generic/mod.rs", "rank": 18, "score": 353630.49492001906 }, { "content": "/// Generate storage read proof.\n\npub fn prove_read<B, H>(\n\n\tmut backend: B,\n\n\tkey: &[u8]\n\n) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>\n\nwhere\n\n\tB: Backend<H>,\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet trie_backend = backend.as_trie_backend()\n\n\t\t.ok_or_else(\n\n\t\t\t||Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>\n\n\t\t)?;\n\n\tprove_read_on_trie_backend(trie_backend, key)\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 19, "score": 353586.4025948942 }, { "content": "/// Generate child storage read proof.\n\npub fn prove_child_read<B, H>(\n\n\tmut backend: B,\n\n\tstorage_key: &[u8],\n\n\tkey: &[u8],\n\n) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>\n\nwhere\n\n\tB: Backend<H>,\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet trie_backend = backend.as_trie_backend()\n\n\t\t.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>)?;\n\n\tprove_child_read_on_trie_backend(trie_backend, storage_key, key)\n\n}\n\n\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 20, "score": 348339.85419922724 }, { "content": "/// Do a XX 256-bit hash and return result.\n\npub fn twox_256(data: &[u8]) -> [u8; 32] {\n\n\tlet mut r: [u8; 32] = [0; 32];\n\n\ttwox_256_into(data, &mut r);\n\n\tr\n\n}\n", "file_path": "core/primitives/src/hashing.rs", "rank": 21, "score": 346003.08619045094 }, { "content": "/// Do a Blake2 256-bit hash and return result.\n\npub fn blake2_256(data: &[u8]) -> [u8; 32] {\n\n\tlet mut r = [0; 32];\n\n\tblake2_256_into(data, &mut r);\n\n\tr\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 22, "score": 346003.086190451 }, { "content": "fn branch_node_buffered<I>(has_value: bool, has_children: I, output: &mut[u8]) \n\n\twhere\n\n\t\tI: Iterator<Item = bool>,\n\n{\n\n\tlet first = if has_value {\n\n\t\tBRANCH_NODE_WITH_VALUE\n\n\t} else {\n\n\t\tBRANCH_NODE_NO_VALUE\n\n\t};\n\n\toutput[0] = first;\n\n\tBitmap::encode(has_children, &mut output[1..]);\n\n}\n", "file_path": "core/trie/src/trie_stream.rs", "rank": 23, "score": 345930.7740054738 }, { "content": "fn localized_payload<E: Encode>(round: u64, set_id: u64, message: &E) -> Vec<u8> {\n\n\t(message, round, set_id).encode()\n\n}\n\n\n\n/// Type-safe wrapper around u64 when indicating that it's a round number.\n\n#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Encode, Decode)]\n\npub struct Round(pub u64);\n\n\n\n/// Type-safe wrapper around u64 when indicating that it's a set ID.\n\n#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Encode, Decode)]\n\npub struct SetId(pub u64);\n\n\n\n// check a message.\n\npub(crate) fn check_message_sig<Block: BlockT>(\n\n\tmessage: &Message<Block>,\n\n\tid: &AuthorityId,\n\n\tsignature: &AuthoritySignature,\n\n\tround: u64,\n\n\tset_id: u64,\n\n) -> Result<(), ()> {\n\n\tlet as_public = AuthorityId::from_raw(id.0);\n\n\tlet encoded_raw = localized_payload(round, set_id, message);\n\n\tif ed25519::Pair::verify(signature, &encoded_raw, as_public) {\n\n\t\tOk(())\n\n\t} else {\n\n\t\tdebug!(target: \"afg\", \"Bad signature on message from {:?}\", id);\n\n\t\tErr(())\n\n\t}\n\n}\n\n\n", "file_path": "core/finality-grandpa/src/communication/mod.rs", "rank": 24, "score": 342408.52820206166 }, { "content": "/// Do a Blake2 128-bit hash and place result in `dest`.\n\npub fn blake2_128_into(data: &[u8], dest: &mut [u8; 16]) {\n\n\tdest.copy_from_slice(blake2_rfc::blake2b::blake2b(16, &[], data).as_bytes());\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 25, "score": 340349.09919705545 }, { "content": "/// Do a XX 64-bit hash and place result in `dest`.\n\npub fn twox_64_into(data: &[u8], dest: &mut [u8; 8]) {\n\n\tuse ::core::hash::Hasher;\n\n\tlet mut h0 = twox_hash::XxHash::with_seed(0);\n\n\th0.write(data);\n\n\tlet r0 = h0.finish();\n\n\tuse byteorder::{ByteOrder, LittleEndian};\n\n\tLittleEndian::write_u64(&mut dest[0..8], r0);\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 26, "score": 340349.09919705545 }, { "content": "/// Do a XX 128-bit hash and place result in `dest`.\n\npub fn twox_128_into(data: &[u8], dest: &mut [u8; 16]) {\n\n\tuse ::core::hash::Hasher;\n\n\tlet mut h0 = twox_hash::XxHash::with_seed(0);\n\n\tlet mut h1 = twox_hash::XxHash::with_seed(1);\n\n\th0.write(data);\n\n\th1.write(data);\n\n\tlet r0 = h0.finish();\n\n\tlet r1 = h1.finish();\n\n\tuse byteorder::{ByteOrder, LittleEndian};\n\n\tLittleEndian::write_u64(&mut dest[0..8], r0);\n\n\tLittleEndian::write_u64(&mut dest[8..16], r1);\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 27, "score": 340349.09919705545 }, { "content": "fn apply_state_commit(transaction: &mut DBTransaction, commit: state_db::CommitSet<Vec<u8>>) {\n\n\tfor (key, val) in commit.data.inserted.into_iter() {\n\n\t\ttransaction.put(columns::STATE, &key[..], &val);\n\n\t}\n\n\tfor key in commit.data.deleted.into_iter() {\n\n\t\ttransaction.delete(columns::STATE, &key[..]);\n\n\t}\n\n\tfor (key, val) in commit.meta.inserted.into_iter() {\n\n\t\ttransaction.put(columns::STATE_META, &key[..], &val);\n\n\t}\n\n\tfor key in commit.meta.deleted.into_iter() {\n\n\t\ttransaction.delete(columns::STATE_META, &key[..]);\n\n\t}\n\n}\n\n\n\nimpl<Block> client::backend::AuxStore for Backend<Block> where Block: BlockT<Hash=H256> {\n\n\tfn insert_aux<\n\n\t\t'a,\n\n\t\t'b: 'a,\n\n\t\t'c: 'a,\n", "file_path": "core/client/db/src/lib.rs", "rank": 28, "score": 339228.20494765416 }, { "content": "fn get_key(key_size: u32) -> Vec<u8> {\n\n\tuse rand::SeedableRng;\n\n\tuse rand::Rng;\n\n\n\n\tlet rnd: [u8; 32] = rand::rngs::StdRng::seed_from_u64(12).gen();\n\n\tlet mut rnd = rnd.iter().cycle();\n\n\n\n\t(0..key_size)\n\n\t\t.map(|_| rnd.next().unwrap().clone())\n\n\t\t.collect()\n\n}\n\n\n", "file_path": "core/primitives/benches/benches.rs", "rank": 29, "score": 336438.60449929326 }, { "content": "/// Extract the BABE epoch change digest from the given header, if it exists.\n\nfn find_next_epoch_digest<B: BlockT>(header: &B::Header) -> Result<Option<Epoch>, String>\n\n\twhere DigestItemFor<B>: CompatibleDigestItem,\n\n{\n\n\tlet mut epoch_digest: Option<_> = None;\n\n\tfor log in header.digest().logs() {\n\n\t\ttrace!(target: \"babe\", \"Checking log {:?}, looking for epoch change digest.\", log);\n\n\t\tlet log = log.try_to::<ConsensusLog>(OpaqueDigestItemId::Consensus(&BABE_ENGINE_ID));\n\n\t\tmatch (log, epoch_digest.is_some()) {\n\n\t\t\t(Some(ConsensusLog::NextEpochData(_)), true) => Err(babe_err!(\"Multiple BABE epoch change digests, rejecting!\"))?,\n\n\t\t\t(Some(ConsensusLog::NextEpochData(epoch)), false) => epoch_digest = Some(epoch),\n\n\t\t\t_ => trace!(target: \"babe\", \"Ignoring digest not meant for us\"),\n\n\t\t}\n\n\t}\n\n\n\n\tOk(epoch_digest)\n\n}\n\n\n", "file_path": "core/consensus/babe/src/lib.rs", "rank": 30, "score": 332171.86013471277 }, { "content": "/// Execute the given closure with global functions available whose functionality routes into\n\n/// externalities that draw from and populate `storage`. Forwards the value that the closure returns.\n\npub fn with_storage<R, F: FnOnce() -> R>(storage: &mut StorageOverlay, f: F) -> R {\n\n\tlet mut alt_storage = Default::default();\n\n\trstd::mem::swap(&mut alt_storage, storage);\n\n\tlet mut ext = BasicExternalities::new(alt_storage);\n\n\tlet r = ext::using(&mut ext, f);\n\n\t*storage = ext.into_storages().0;\n\n\tr\n\n}\n\n\n", "file_path": "core/sr-io/with_std.rs", "rank": 31, "score": 329124.01663953613 }, { "content": "fn find_pre_digest<B: BlockT, P: Pair>(header: &B::Header) -> Result<u64, String>\n\n\twhere DigestItemFor<B>: CompatibleDigestItem<P>,\n\n\t\tP::Signature: Decode,\n\n\t\tP::Public: Encode + Decode + PartialEq + Clone,\n\n{\n\n\tlet mut pre_digest: Option<u64> = None;\n\n\tfor log in header.digest().logs() {\n\n\t\ttrace!(target: \"aura\", \"Checking log {:?}\", log);\n\n\t\tmatch (log.as_aura_pre_digest(), pre_digest.is_some()) {\n\n\t\t\t(Some(_), true) => Err(aura_err!(\"Multiple AuRa pre-runtime headers, rejecting!\"))?,\n\n\t\t\t(None, _) => trace!(target: \"aura\", \"Ignoring digest not meant for us\"),\n\n\t\t\t(s, false) => pre_digest = s,\n\n\t\t}\n\n\t}\n\n\tpre_digest.ok_or_else(|| aura_err!(\"No AuRa pre-runtime digest found\"))\n\n}\n\n\n\n\n", "file_path": "core/consensus/aura/src/lib.rs", "rank": 32, "score": 327750.50165783573 }, { "content": "/// Reads storage value from overlay or from the backend.\n\nfn try_read_overlay_value<H, B>(overlay: &OverlayedChanges, backend: &B, key: &[u8])\n\n\t-> Result<Option<Vec<u8>>, Box<dyn Error>>\n\nwhere\n\n\tH: Hasher,\n\n\tB: Backend<H>,\n\n{\n\n\tmatch overlay.storage(key).map(|x| x.map(|x| x.to_vec())) {\n\n\t\tSome(value) => Ok(value),\n\n\t\tNone => backend\n\n\t\t\t.storage(key)\n\n\t\t\t.map_err(|err| Box::new(ExecutionError::Backend(format!(\"{}\", err))) as Box<dyn Error>),\n\n\t}\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse std::collections::HashMap;\n\n\tuse codec::Encode;\n\n\tuse overlayed_changes::OverlayedValue;\n\n\tuse super::*;\n", "file_path": "core/state-machine/src/lib.rs", "rank": 33, "score": 322957.7688338342 }, { "content": "/// Convert CHT value into block header hash.\n\npub fn decode_cht_value(value: &[u8]) -> Option<H256> {\n\n\tmatch value.len() {\n\n\t\t32 => Some(H256::from_slice(&value[0..32])),\n\n\t\t_ => None,\n\n\t}\n\n\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse primitives::{Blake2Hasher};\n\n\tuse test_client::runtime::Header;\n\n\tuse super::*;\n\n\n\n\t#[test]\n\n\tfn is_build_required_works() {\n\n\t\tassert_eq!(is_build_required(SIZE, 0u32.into()), None);\n\n\t\tassert_eq!(is_build_required(SIZE, 1u32.into()), None);\n\n\t\tassert_eq!(is_build_required(SIZE, SIZE), None);\n\n\t\tassert_eq!(is_build_required(SIZE, SIZE + 1), None);\n", "file_path": "core/client/src/cht.rs", "rank": 34, "score": 322620.04216915625 }, { "content": "/// Accumulates a list of storage changed in a block.\n\nstruct BlockChanges<B: Header> {\n\n\t/// Block number.\n\n\tnumber: B::Number,\n\n\t/// Block hash.\n\n\thash: B::Hash,\n\n\t/// Parent block hash.\n\n\tparent: B::Hash,\n\n\t/// A set of modified storage keys.\n\n\tstorage: HashSet<StorageKey>,\n\n\t/// A set of modified child storage keys.\n\n\tchild_storage: HashSet<ChildStorageKey>,\n\n\t/// Block is part of the canonical chain.\n\n\tis_canon: bool,\n\n}\n\n\n", "file_path": "core/client/db/src/storage_cache.rs", "rank": 35, "score": 319633.4138874995 }, { "content": "#[cfg(not(feature = \"no_panic_handler\"))]\n\n#[panic_handler]\n\n#[no_mangle]\n\npub fn panic(info: &PanicInfo) -> ! {\n\n\tunsafe {\n\n\t\t#[cfg(feature = \"wasm-nice-panic-message\")]\n\n\t\t{\n\n\t\t\tlet message = rstd::alloc::format!(\"{}\", info);\n\n\t\t\textern_functions_host_impl::ext_print_utf8(message.as_ptr() as *const u8, message.len() as u32);\n\n\t\t}\n\n\t\t#[cfg(not(feature = \"wasm-nice-panic-message\"))]\n\n\t\t{\n\n\t\t\tif let Some(loc) = info.location() {\n\n\t\t\t\textern_functions_host_impl::ext_print_utf8(loc.file().as_ptr() as *const u8, loc.file().len() as u32);\n\n\t\t\t\textern_functions_host_impl::ext_print_num(loc.line() as u64);\n\n\t\t\t\textern_functions_host_impl::ext_print_num(loc.column() as u64);\n\n\t\t\t}\n\n\t\t}\n\n\t\tintrinsics::abort()\n\n\t}\n\n}\n\n\n\n#[cfg(not(feature = \"no_oom\"))]\n", "file_path": "core/sr-io/without_std.rs", "rank": 36, "score": 319336.97068676364 }, { "content": "/// Prepare input pairs for building a changes trie of given block.\n\n///\n\n/// Returns Err if storage error has occurred OR if storage haven't returned\n\n/// required data.\n\npub fn prepare_input<'a, B, S, H, Number>(\n\n\tbackend: &'a B,\n\n\tstorage: &'a S,\n\n\tconfig: &'a Configuration,\n\n\tchanges: &'a OverlayedChanges,\n\n\tparent: &'a AnchorBlockId<H::Out, Number>,\n\n) -> Result<impl Iterator<Item=InputPair<Number>> + 'a, String>\n\n\twhere\n\n\t\tB: Backend<H>,\n\n\t\tS: Storage<H, Number>,\n\n\t\tH: Hasher + 'a,\n\n\t\tNumber: BlockNumber,\n\n{\n\n\tlet number = parent.number.clone() + One::one();\n\n\tlet extrinsics_input = prepare_extrinsics_input(\n\n\t\tbackend,\n\n\t\t&number,\n\n\t\tchanges)?;\n\n\tlet digest_input = prepare_digest_input::<_, H, Number>(\n\n\t\tparent,\n\n\t\tconfig,\n\n\t\tnumber,\n\n\t\tstorage)?;\n\n\tOk(extrinsics_input.chain(digest_input))\n\n}\n\n\n", "file_path": "core/state-machine/src/changes_trie/build.rs", "rank": 37, "score": 318989.48851210764 }, { "content": "type StorageTuple = (HashMap<Vec<u8>, Vec<u8>>, HashMap<Vec<u8>, HashMap<Vec<u8>, Vec<u8>>>);\n\n\n\n/// Simple HashMap-based Externalities impl.\n\npub struct TestExternalities<H: Hasher, N: ChangesTrieBlockNumber> {\n\n\toverlay: OverlayedChanges,\n\n\tbackend: InMemory<H>,\n\n\tchanges_trie_storage: ChangesTrieInMemoryStorage<H, N>,\n\n\toffchain: Option<Box<dyn offchain::Externalities>>,\n\n}\n\n\n\nimpl<H: Hasher, N: ChangesTrieBlockNumber> TestExternalities<H, N> {\n\n\t/// Create a new instance of `TestExternalities` with storage.\n\n\tpub fn new(storage: HashMap<Vec<u8>, Vec<u8>>) -> Self {\n\n\t\tSelf::new_with_children((storage, Default::default()))\n\n\t}\n\n\n\n\t/// Create a new instance of `TestExternalities` with storage and children.\n\n\tpub fn new_with_children(storage: StorageTuple) -> Self {\n\n\t\tSelf::new_with_code_with_children(&[], storage)\n\n\t}\n", "file_path": "core/state-machine/src/testing.rs", "rank": 38, "score": 317303.9966485717 }, { "content": "/// Wraps around an unbounded channel from the `futures` crate. The sender implements `Link` and\n\n/// can be used to buffer commands, and the receiver can be used to poll said commands and transfer\n\n/// them to another link.\n\npub fn buffered_link<B: BlockT>() -> (BufferedLinkSender<B>, BufferedLinkReceiver<B>) {\n\n\tlet (tx, rx) = mpsc::unbounded();\n\n\tlet tx = BufferedLinkSender { tx };\n\n\tlet rx = BufferedLinkReceiver { rx };\n\n\t(tx, rx)\n\n}\n\n\n\n/// See [`buffered_link`].\n\npub struct BufferedLinkSender<B: BlockT> {\n\n\ttx: mpsc::UnboundedSender<BlockImportWorkerMsg<B>>,\n\n}\n\n\n\nimpl<B: BlockT> BufferedLinkSender<B> {\n\n\t/// Returns true if the sender points to nowhere.\n\n\t///\n\n\t/// Once `true` is returned, it is pointless to use the sender anymore.\n\n\tpub fn is_closed(&self) -> bool {\n\n\t\tself.tx.is_closed()\n\n\t}\n\n}\n\n\n\nimpl<B: BlockT> Clone for BufferedLinkSender<B> {\n\n\tfn clone(&self) -> Self {\n\n\t\tBufferedLinkSender {\n\n\t\t\ttx: self.tx.clone(),\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "core/consensus/common/src/import_queue/buffered_link.rs", "rank": 39, "score": 312904.5601941883 }, { "content": "/// Do a Blake2 128-bit hash and return result.\n\npub fn blake2_128(data: &[u8]) -> [u8; 16] {\n\n\tlet mut r = [0; 16];\n\n\tblake2_128_into(data, &mut r);\n\n\tr\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 40, "score": 310050.6706189214 }, { "content": "/// Do a XX 128-bit hash and return result.\n\npub fn twox_128(data: &[u8]) -> [u8; 16] {\n\n\tlet mut r: [u8; 16] = [0; 16];\n\n\ttwox_128_into(data, &mut r);\n\n\tr\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 41, "score": 310050.6706189214 }, { "content": "/// Do a Blake2 512-bit hash and return result.\n\npub fn blake2_512(data: &[u8]) -> [u8; 64] {\n\n\tlet mut r = [0; 64];\n\n\tblake2_512_into(data, &mut r);\n\n\tr\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 42, "score": 310045.2065779074 }, { "content": "fn load_decode<B, T>(backend: &B, key: &[u8]) -> ClientResult<Option<T>>\n\n\twhere\n\n\t\tB: AuxStore,\n\n\t\tT: Decode,\n\n{\n\n\tlet corrupt = |e: codec::Error| {\n\n\t\tClientError::Backend(format!(\"BABE DB is corrupted. Decode error: {}\", e.what())).into()\n\n\t};\n\n\tmatch backend.get_aux(key)? {\n\n\t\tNone => Ok(None),\n\n\t\tSome(t) => T::decode(&mut &t[..]).map(Some).map_err(corrupt)\n\n\t}\n\n}\n\n\n\n/// Load or initialize persistent epoch change data from backend.\n\npub(crate) fn load_epoch_changes<Block: BlockT, B: AuxStore>(\n\n\tbackend: &B,\n\n) -> ClientResult<SharedEpochChanges<Block>> {\n\n\tlet epoch_changes = load_decode::<_, EpochChanges<Block>>(backend, BABE_EPOCH_CHANGES)?\n\n\t\t.map(Into::into)\n", "file_path": "core/consensus/babe/src/aux_schema.rs", "rank": 43, "score": 308361.8465971907 }, { "content": "fn discard_values<Key: Hash>(values: &mut HashMap<Key, (u32, DBValue)>, inserted: Vec<Key>) {\n\n\tfor k in inserted {\n\n\t\tmatch values.entry(k) {\n\n\t\t\tEntry::Occupied(mut e) => {\n\n\t\t\t\tlet (ref mut counter, _) = e.get_mut();\n\n\t\t\t\t*counter -= 1;\n\n\t\t\t\tif *counter == 0 {\n\n\t\t\t\t\te.remove();\n\n\t\t\t\t}\n\n\t\t\t},\n\n\t\t\tEntry::Vacant(_) => {\n\n\t\t\t\tdebug_assert!(false, \"Trying to discard missing value\");\n\n\t\t\t}\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "core/state-db/src/noncanonical.rs", "rank": 44, "score": 307916.61923752766 }, { "content": "/// Returns a `ChildStorageKey` if the given `storage_key` slice is a valid storage\n\n/// key or panics otherwise.\n\n///\n\n/// Panicking here is aligned with what the `without_std` environment would do\n\n/// in the case of an invalid child storage key.\n\nfn child_storage_key_or_panic(storage_key: &[u8]) -> ChildStorageKey<Blake2Hasher> {\n\n\tmatch ChildStorageKey::from_slice(storage_key) {\n\n\t\tSome(storage_key) => storage_key,\n\n\t\tNone => panic!(\"child storage key is invalid\"),\n\n\t}\n\n}\n\n\n\nimpl StorageApi for () {\n\n\tfn storage(key: &[u8]) -> Option<Vec<u8>> {\n\n\t\text::with(|ext| ext.storage(key).map(|s| s.to_vec()))\n\n\t\t\t.expect(\"storage cannot be called outside of an Externalities-provided environment.\")\n\n\t}\n\n\n\n\tfn read_storage(key: &[u8], value_out: &mut [u8], value_offset: usize) -> Option<usize> {\n\n\t\text::with(|ext| ext.storage(key).map(|value| {\n\n\t\t\tlet value = &value[value_offset..];\n\n\t\t\tlet written = std::cmp::min(value.len(), value_out.len());\n\n\t\t\tvalue_out[..written].copy_from_slice(&value[..written]);\n\n\t\t\tvalue.len()\n\n\t\t})).expect(\"read_storage cannot be called outside of an Externalities-provided environment.\")\n", "file_path": "core/sr-io/with_std.rs", "rank": 45, "score": 307192.4837019593 }, { "content": "struct OptionHOut<T: AsRef<[u8]>>(Option<T>);\n\n\n\nimpl<T: AsRef<[u8]>> EstimateSize for OptionHOut<T> {\n\n\tfn estimate_size(&self) -> usize {\n\n\t\t// capacity would be better\n\n\t\tself.0.as_ref().map(|v|v.as_ref().len()).unwrap_or(0)\n\n\t}\n\n}\n\n\n\nimpl<T: EstimateSize> EstimateSize for (T, T) {\n\n\tfn estimate_size(&self) -> usize {\n\n\t\tself.0.estimate_size() + self.1.estimate_size()\n\n\t}\n\n}\n\n\n\nimpl<K: EstimateSize + Eq + StdHash, V: EstimateSize> LRUMap<K, V> {\n\n\tfn remove(&mut self, k: &K) {\n\n\t\tlet map = &mut self.0;\n\n\t\tlet storage_used_size = &mut self.1;\n\n\t\tif let Some(v) = map.remove(k) {\n", "file_path": "core/client/db/src/storage_cache.rs", "rank": 46, "score": 304350.79441048694 }, { "content": "/// Convert header number into CHT key.\n\npub fn encode_cht_key<N: Encode>(number: N) -> Vec<u8> {\n\n\tnumber.encode()\n\n}\n\n\n", "file_path": "core/client/src/cht.rs", "rank": 47, "score": 303313.43056510505 }, { "content": "pub fn nonce_of(who: AccountId) -> u64 {\n\n\tstorage::hashed::get_or(&blake2_256, &who.to_keyed_vec(NONCE_OF), 0)\n\n}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 48, "score": 300180.40369725635 }, { "content": "pub fn balance_of(who: AccountId) -> u64 {\n\n\tstorage::hashed::get_or(&blake2_256, &balance_of_key(who), 0)\n\n}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 49, "score": 300180.40369725635 }, { "content": "/// Remove key mappings.\n\npub fn remove_key_mappings<N: TryInto<u32>, H: AsRef<[u8]>>(\n\n\ttransaction: &mut DBTransaction,\n\n\tkey_lookup_col: Option<u32>,\n\n\tnumber: N,\n\n\thash: H,\n\n) -> client::error::Result<()> {\n\n\tremove_number_to_key_mapping(transaction, key_lookup_col, number)?;\n\n\ttransaction.delete(key_lookup_col, hash.as_ref());\n\n\tOk(())\n\n}\n\n\n", "file_path": "core/client/db/src/utils.rs", "rank": 50, "score": 299850.85177727015 }, { "content": "pub fn sync<F, B, E>(spec: FactoryChainSpec<F>, mut block_factory: B, mut extrinsic_factory: E) where\n\n\tF: ServiceFactory,\n\n\tF::FullService: Future<Item=(), Error=()>,\n\n\tF::LightService: Future<Item=(), Error=()>,\n\n\tB: FnMut(&SyncService<F::FullService>) -> BlockImportParams<F::Block>,\n\n\tE: FnMut(&SyncService<F::FullService>) -> FactoryExtrinsic<F>,\n\n{\n\n\tconst NUM_FULL_NODES: usize = 10;\n\n\t// FIXME: BABE light client support is currently not working.\n\n\tconst NUM_LIGHT_NODES: usize = 0;\n\n\tconst NUM_BLOCKS: usize = 512;\n\n\tlet temp = TempDir::new(\"substrate-sync-test\").expect(\"Error creating test dir\");\n\n\tlet mut network = TestNet::<F>::new(\n\n\t\t&temp,\n\n\t\tspec.clone(),\n\n\t\tNUM_FULL_NODES,\n\n\t\tNUM_LIGHT_NODES,\n\n\t\tvec![],\n\n\t\t30500,\n\n\t);\n", "file_path": "core/service/test/src/lib.rs", "rank": 51, "score": 299679.0313372397 }, { "content": "fn execute_storage_change(key: &[u8], value: Option<&[u8]>) -> ApplyResult {\n\n\tmatch value {\n\n\t\tSome(value) => storage::unhashed::put_raw(key, value),\n\n\t\tNone => storage::unhashed::kill(key),\n\n\t}\n\n\tOk(ApplyOutcome::Success)\n\n}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 52, "score": 299667.91999539477 }, { "content": "fn insert_values<Key: Hash>(values: &mut HashMap<Key, (u32, DBValue)>, inserted: Vec<(Key, DBValue)>) {\n\n\tfor (k, v) in inserted {\n\n\t\tdebug_assert!(values.get(&k).map_or(true, |(_, value)| *value == v));\n\n\t\tlet (ref mut counter, _) = values.entry(k).or_insert_with(|| (0, v));\n\n\t\t*counter += 1;\n\n\t}\n\n}\n\n\n", "file_path": "core/state-db/src/noncanonical.rs", "rank": 53, "score": 297121.49540011585 }, { "content": "/// Prove execution using the given state backend, overlayed changes, and call executor.\n\npub fn prove_execution<B, H, Exec>(\n\n\tmut backend: B,\n\n\toverlay: &mut OverlayedChanges,\n\n\texec: &Exec,\n\n\tmethod: &str,\n\n\tcall_data: &[u8],\n\n) -> Result<(Vec<u8>, Vec<Vec<u8>>), Box<dyn Error>>\n\nwhere\n\n\tB: Backend<H>,\n\n\tH: Hasher,\n\n\tExec: CodeExecutor<H>,\n\n\tH::Out: Ord + 'static,\n\n{\n\n\tlet trie_backend = backend.as_trie_backend()\n\n\t\t.ok_or_else(|| Box::new(ExecutionError::UnableToGenerateProof) as Box<dyn Error>)?;\n\n\tprove_execution_on_trie_backend(trie_backend, overlay, exec, method, call_data)\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 54, "score": 294975.8672878946 }, { "content": "fn deserialize_result(serialized_result: &[u8]) -> std::result::Result<Option<RuntimeValue>, Trap> {\n\n\tuse self::sandbox_primitives::{HostError, ReturnValue};\n\n\tlet result_val = std::result::Result::<ReturnValue, HostError>::decode(&mut &serialized_result[..])\n\n\t\t.map_err(|_| trap(\"Decoding Result<ReturnValue, HostError> failed!\"))?;\n\n\n\n\tmatch result_val {\n\n\t\tOk(return_value) => Ok(match return_value {\n\n\t\t\tReturnValue::Unit => None,\n\n\t\t\tReturnValue::Value(typed_value) => Some(RuntimeValue::from(typed_value)),\n\n\t\t}),\n\n\t\tErr(HostError) => Err(trap(\"Supervisor function returned sandbox::HostError\")),\n\n\t}\n\n}\n\n\n\nimpl<'a, FE: SandboxCapabilities + Externals + 'a> Externals for GuestExternals<'a, FE> {\n\n\tfn invoke_index(\n\n\t\t&mut self,\n\n\t\tindex: usize,\n\n\t\targs: RuntimeArgs,\n\n\t) -> std::result::Result<Option<RuntimeValue>, Trap> {\n", "file_path": "core/executor/src/sandbox.rs", "rank": 55, "score": 293800.5972857774 }, { "content": "/// Serialize the given data structure as a JSON byte vector.\n\npub fn encode<T: serde::Serialize + ?Sized>(value: &T) -> Vec<u8> {\n\n\tserde_json::to_vec(value).expect(PROOF)\n\n}\n\n\n", "file_path": "core/serializer/src/lib.rs", "rank": 56, "score": 293454.9590296689 }, { "content": "fn make_ids(keys: &[Ed25519Keyring]) -> Vec<(AuthorityId, u64)> {\n\n\tkeys.iter()\n\n\t\t.map(|key| AuthorityId(key.to_raw_public()))\n\n\t\t.map(|id| (id, 1))\n\n\t\t.collect()\n\n}\n\n\n", "file_path": "core/finality-grandpa/src/communication/tests.rs", "rank": 57, "score": 293057.34196298063 }, { "content": "pub fn make_commit(inserted: &[u64], deleted: &[u64]) -> CommitSet<H256> {\n\n\tCommitSet {\n\n\t\tdata: make_changeset(inserted, deleted),\n\n\t\tmeta: ChangeSet::default(),\n\n\t}\n\n}\n\n\n", "file_path": "core/state-db/src/test.rs", "rank": 58, "score": 292926.34156719 }, { "content": "pub fn make_changeset(inserted: &[u64], deleted: &[u64]) -> ChangeSet<H256> {\n\n\tChangeSet {\n\n\t\tinserted: inserted\n\n\t\t\t.iter()\n\n\t\t\t.map(|v| {\n\n\t\t\t\t(H256::from_low_u64_be(*v), H256::from_low_u64_be(*v).as_bytes().to_vec())\n\n\t\t\t})\n\n\t\t\t.collect(),\n\n\t\tdeleted: deleted.iter().map(|v| H256::from_low_u64_be(*v)).collect(),\n\n\t}\n\n}\n\n\n", "file_path": "core/state-db/src/test.rs", "rank": 59, "score": 292926.34156719 }, { "content": "pub fn make_db(inserted: &[u64]) -> TestDb {\n\n\tTestDb {\n\n\t\tdata: inserted\n\n\t\t\t.iter()\n\n\t\t\t.map(|v| {\n\n\t\t\t\t(H256::from_low_u64_be(*v), H256::from_low_u64_be(*v).as_bytes().to_vec())\n\n\t\t\t})\n\n\t\t\t.collect(),\n\n\t\tmeta: Default::default(),\n\n\t}\n\n}\n\n\n", "file_path": "core/state-db/src/test.rs", "rank": 60, "score": 291532.18744207727 }, { "content": "fn to_meta_key<S: Codec>(suffix: &[u8], data: &S) -> Vec<u8> {\n\n\tlet mut buffer = data.encode();\n\n\tbuffer.extend(suffix);\n\n\tbuffer\n\n}\n\n\n", "file_path": "core/state-db/src/lib.rs", "rank": 61, "score": 291495.7850604401 }, { "content": "/// Encode and allocate node type header (type and size), and partial value.\n\n/// Same as `partial_from_iterator_encode` but uses non encoded `Partial` as input.\n\nfn partial_encode(partial: Partial, node_kind: NodeKind) -> Vec<u8> {\n\n\tlet number_nibble_encoded = (partial.0).0 as usize;\n\n\tlet nibble_count = partial.1.len() * nibble_ops::NIBBLE_PER_BYTE + number_nibble_encoded;\n\n\n\n\tlet nibble_count = rstd::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count);\n\n\n\n\tlet mut output = Vec::with_capacity(3 + partial.1.len());\n\n\tmatch node_kind {\n\n\t\tNodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output),\n\n\t\tNodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output),\n\n\t\tNodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output),\n\n\t};\n\n\tif number_nibble_encoded > 0 {\n\n\t\toutput.push(nibble_ops::pad_right((partial.0).1));\n\n\t}\n\n\toutput.extend_from_slice(&partial.1[..]);\n\n\toutput\n\n}\n\n\n\nconst BITMAP_LENGTH: usize = 2;\n", "file_path": "core/trie/src/node_codec.rs", "rank": 62, "score": 288280.8998167933 }, { "content": "/// Place a number mapping into the database. This maps number to current perceived\n\n/// block hash at that position.\n\npub fn insert_number_to_key_mapping<N: TryInto<u32> + Clone, H: AsRef<[u8]>>(\n\n\ttransaction: &mut DBTransaction,\n\n\tkey_lookup_col: Option<u32>,\n\n\tnumber: N,\n\n\thash: H,\n\n) -> client::error::Result<()> {\n\n\ttransaction.put_vec(\n\n\t\tkey_lookup_col,\n\n\t\tnumber_index_key(number.clone())?.as_ref(),\n\n\t\tnumber_and_hash_to_lookup_key(number, hash)?,\n\n\t);\n\n\tOk(())\n\n}\n\n\n", "file_path": "core/client/db/src/utils.rs", "rank": 63, "score": 288017.1938241243 }, { "content": "/// Insert a hash to key mapping in the database.\n\npub fn insert_hash_to_key_mapping<N: TryInto<u32>, H: AsRef<[u8]> + Clone>(\n\n\ttransaction: &mut DBTransaction,\n\n\tkey_lookup_col: Option<u32>,\n\n\tnumber: N,\n\n\thash: H,\n\n) -> client::error::Result<()> {\n\n\ttransaction.put_vec(\n\n\t\tkey_lookup_col,\n\n\t\thash.clone().as_ref(),\n\n\t\tnumber_and_hash_to_lookup_key(number, hash)?,\n\n\t);\n\n\tOk(())\n\n}\n\n\n", "file_path": "core/client/db/src/utils.rs", "rank": 64, "score": 288017.1938241243 }, { "content": "fn code_using_trie() -> u64 {\n\n\tlet pairs = [\n\n\t\t(b\"0103000000000000000464\".to_vec(), b\"0400000000\".to_vec()),\n\n\t\t(b\"0103000000000000000469\".to_vec(), b\"0401000000\".to_vec()),\n\n\t].to_vec();\n\n\n\n\tlet mut mdb = PrefixedMemoryDB::default();\n\n\tlet mut root = rstd::default::Default::default();\n\n\tlet _ = {\n\n\t\tlet v = &pairs;\n\n\t\tlet mut t = TrieDBMut::<Blake2Hasher>::new(&mut mdb, &mut root);\n\n\t\tfor i in 0..v.len() {\n\n\t\t\tlet key: &[u8]= &v[i].0;\n\n\t\t\tlet val: &[u8] = &v[i].1;\n\n\t\t\tif !t.insert(key, val).is_ok() {\n\n\t\t\t\treturn 101;\n\n\t\t\t}\n\n\t\t}\n\n\t\tt\n\n\t};\n", "file_path": "core/test-runtime/src/lib.rs", "rank": 65, "score": 282363.23742529785 }, { "content": "pub fn initialize_block(header: &Header) {\n\n\t// populate environment.\n\n\t<Number>::put(&header.number);\n\n\t<ParentHash>::put(&header.parent_hash);\n\n\t<StorageDigest>::put(header.digest());\n\n\tstorage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);\n\n}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 66, "score": 281207.7431333647 }, { "content": "/// Create an instance of fetch data checker.\n\npub fn new_fetch_checker<E, B: BlockT, S: BlockchainStorage<B>, F>(\n\n\tblockchain: Arc<Blockchain<S, F>>,\n\n\texecutor: E,\n\n) -> LightDataChecker<E, Blake2Hasher, B, S, F>\n\n\twhere\n\n\t\tE: CodeExecutor<Blake2Hasher>,\n\n{\n\n\tLightDataChecker::new(blockchain, executor)\n\n}\n", "file_path": "core/client/src/light/mod.rs", "rank": 67, "score": 279211.9841002237 }, { "content": "/// Call `f` for all keys in a child trie.\n\npub fn for_keys_in_child_trie<L: TrieConfiguration, F: FnMut(&[u8]), DB>(\n\n\t_storage_key: &[u8],\n\n\tdb: &DB,\n\n\troot_slice: &[u8],\n\n\tmut f: F\n\n) -> Result<(), Box<TrieError<L>>>\n\n\twhere\n\n\t\tDB: hash_db::HashDBRef<L::Hash, trie_db::DBValue>\n\n\t\t\t+ hash_db::PlainDBRef<TrieHash<L>, trie_db::DBValue>,\n\n{\n\n\tlet mut root = TrieHash::<L>::default();\n\n\t// root is fetched from DB, not writable by runtime, so it's always valid.\n\n\troot.as_mut().copy_from_slice(root_slice);\n\n\n\n\tlet trie = TrieDB::<L>::new(&*db, &root)?;\n\n\tlet iter = trie.iter()?;\n\n\n\n\tfor x in iter {\n\n\t\tlet (key, _) = x?;\n\n\t\tf(&key);\n\n\t}\n\n\n\n\tOk(())\n\n}\n\n\n", "file_path": "core/trie/src/lib.rs", "rank": 68, "score": 277856.74151398626 }, { "content": "type ChildStorageKey = (Vec<u8>, Vec<u8>);\n", "file_path": "core/client/db/src/storage_cache.rs", "rank": 69, "score": 277001.2366695874 }, { "content": "/// Create a new shared cache instance with given max memory usage.\n\npub fn new_shared_cache<B: BlockT, H: Hasher>(\n\n\tshared_cache_size: usize,\n\n\tchild_ratio: (usize, usize),\n\n) -> SharedCache<B, H> {\n\n\tlet top = child_ratio.1.saturating_sub(child_ratio.0);\n\n\tArc::new(Mutex::new(Cache {\n\n\t\tlru_storage: LRUMap(LinkedHashMap::new(), 0,\n\n\t\t\tshared_cache_size * top / child_ratio.1),\n\n\t\tlru_hashes: LRUMap(LinkedHashMap::new(), 0, FIX_LRU_HASH_SIZE),\n\n\t\tlru_child_storage: LRUMap(LinkedHashMap::new(), 0,\n\n\t\t\tshared_cache_size * child_ratio.0 / child_ratio.1),\n\n\t\tmodifications: VecDeque::new(),\n\n\t}))\n\n}\n\n\n\n#[derive(Debug)]\n", "file_path": "core/client/db/src/storage_cache.rs", "rank": 70, "score": 275182.4949434423 }, { "content": "/// Do a XX 64-bit hash and return result.\n\npub fn twox_64(data: &[u8]) -> [u8; 8] {\n\n\tlet mut r: [u8; 8] = [0; 8];\n\n\ttwox_64_into(data, &mut r);\n\n\tr\n\n}\n\n\n", "file_path": "core/primitives/src/hashing.rs", "rank": 71, "score": 274072.86379563523 }, { "content": "/// Hash conversion. Used to convert between unbound associated hash types in traits,\n\n/// implemented by the same hash type.\n\n/// Panics if used to convert between different hash types.\n\npub fn convert_hash<H1: Default + AsMut<[u8]>, H2: AsRef<[u8]>>(src: &H2) -> H1 {\n\n\tlet mut dest = H1::default();\n\n\tassert_eq!(dest.as_mut().len(), src.as_ref().len());\n\n\tdest.as_mut().copy_from_slice(src.as_ref());\n\n\tdest\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse super::*;\n\n\tuse substrate_serializer as ser;\n\n\n\n\t#[test]\n\n\tfn test_h160() {\n\n\t\tlet tests = vec![\n\n\t\t\t(Default::default(), \"0x0000000000000000000000000000000000000000\"),\n\n\t\t\t(H160::from_low_u64_be(2), \"0x0000000000000000000000000000000000000002\"),\n\n\t\t\t(H160::from_low_u64_be(15), \"0x000000000000000000000000000000000000000f\"),\n\n\t\t\t(H160::from_low_u64_be(16), \"0x0000000000000000000000000000000000000010\"),\n\n\t\t\t(H160::from_low_u64_be(1_000), \"0x00000000000000000000000000000000000003e8\"),\n", "file_path": "core/primitives/src/hash.rs", "rank": 72, "score": 273236.37838470394 }, { "content": "fn make_ids(keys: &[Ed25519Keyring]) -> Vec<(primitives::ed25519::Public, u64)> {\n\n\tkeys.iter()\n\n\t\t.map(|key| AuthorityId::from_raw(key.to_raw_public()))\n\n\t\t.map(|id| (id, 1))\n\n\t\t.collect()\n\n}\n\n\n", "file_path": "core/finality-grandpa/src/tests.rs", "rank": 73, "score": 269876.9962568419 }, { "content": "/// Creates new substrate state machine.\n\npub fn new<'a, H, N, B, T, O, Exec>(\n\n\tbackend: &'a B,\n\n\tchanges_trie_storage: Option<&'a T>,\n\n\toffchain_ext: Option<&'a mut O>,\n\n\toverlay: &'a mut OverlayedChanges,\n\n\texec: &'a Exec,\n\n\tmethod: &'a str,\n\n\tcall_data: &'a [u8],\n\n) -> StateMachine<'a, H, N, B, T, O, Exec> {\n\n\tStateMachine {\n\n\t\tbackend,\n\n\t\tchanges_trie_storage,\n\n\t\toffchain_ext,\n\n\t\toverlay,\n\n\t\texec,\n\n\t\tmethod,\n\n\t\tcall_data,\n\n\t\t_hasher: PhantomData,\n\n\t}\n\n}\n", "file_path": "core/state-machine/src/lib.rs", "rank": 74, "score": 269799.1770715298 }, { "content": "/// Check storage read proof, generated by `prove_read` call.\n\npub fn read_proof_check<H>(\n\n\troot: H::Out,\n\n\tproof: Vec<Vec<u8>>,\n\n\tkey: &[u8],\n\n) -> Result<Option<Vec<u8>>, Box<dyn Error>>\n\nwhere\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet proving_backend = create_proof_check_backend::<H>(root, proof)?;\n\n\tread_proof_check_on_proving_backend(&proving_backend, key)\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 75, "score": 269611.6898179862 }, { "content": "#[allow(deprecated)]\n\nfn authorities<A, B, C>(client: &C, at: &BlockId<B>) -> Result<Vec<A>, ConsensusError> where\n\n\tA: Codec,\n\n\tB: BlockT,\n\n\tC: ProvideRuntimeApi + ProvideCache<B>,\n\n\tC::Api: AuraApi<B, A>,\n\n{\n\n\tclient\n\n\t\t.cache()\n\n\t\t.and_then(|cache| cache\n\n\t\t\t.get_at(&well_known_cache_keys::AUTHORITIES, at)\n\n\t\t\t.and_then(|v| Decode::decode(&mut &v[..]).ok())\n\n\t\t)\n\n\t\t.or_else(|| AuraApi::authorities(&*client.runtime_api(), at).ok())\n\n\t\t.ok_or_else(|| consensus_common::Error::InvalidAuthoritiesSet.into())\n\n}\n\n\n\n/// The Aura import queue type.\n\npub type AuraImportQueue<B> = BasicQueue<B>;\n\n\n", "file_path": "core/consensus/aura/src/lib.rs", "rank": 76, "score": 269604.76472153846 }, { "content": "fn invalid_block_range<H: Header>(from: Option<&H>, to: Option<&H>, reason: String) -> error::Error {\n\n\tlet to_string = |x: Option<&H>| match x {\n\n\t\tNone => \"unknown hash\".into(),\n\n\t\tSome(h) => format!(\"{} ({})\", h.number(), h.hash()),\n\n\t};\n\n\n\n\terror::Error::InvalidBlockRange {\n\n\t\tfrom: to_string(from),\n\n\t\tto: to_string(to),\n\n\t\tdetails: reason,\n\n\t}\n\n}\n", "file_path": "core/rpc/src/state/mod.rs", "rank": 77, "score": 269498.82727628376 }, { "content": "/// Execute the given closure with global functions available whose functionality routes into\n\n/// externalities that draw from and populate `storage` and `children_storage`.\n\n/// Forwards the value that the closure returns.\n\npub fn with_storage_and_children<R, F: FnOnce() -> R>(\n\n\tstorage: &mut StorageOverlay,\n\n\tchildren_storage: &mut ChildrenStorageOverlay,\n\n\tf: F\n\n) -> R {\n\n\tlet mut alt_storage = Default::default();\n\n\tlet mut alt_children_storage = Default::default();\n\n\trstd::mem::swap(&mut alt_storage, storage);\n\n\trstd::mem::swap(&mut alt_children_storage, children_storage);\n\n\n\n\tlet mut ext = BasicExternalities::new_with_children(alt_storage, alt_children_storage);\n\n\tlet r = ext::using(&mut ext, f);\n\n\n\n\tlet storage_tuple = ext.into_storages();\n\n\t*storage = storage_tuple.0;\n\n\t*children_storage = storage_tuple.1;\n\n\n\n\tr\n\n}\n\n\n", "file_path": "core/sr-io/with_std.rs", "rank": 78, "score": 268515.8588635971 }, { "content": "/// Determine whether a child trie key is valid.\n\n///\n\n/// For now, the only valid child trie key is `:child_storage:default:`.\n\n///\n\n/// `child_trie_root` and `child_delta_trie_root` can panic if invalid value is provided to them.\n\npub fn is_child_trie_key_valid<L: TrieConfiguration>(storage_key: &[u8]) -> bool {\n\n\tuse primitives::storage::well_known_keys;\n\n\tlet has_right_prefix = storage_key.starts_with(b\":child_storage:default:\");\n\n\tif has_right_prefix {\n\n\t\t// This is an attempt to catch a change of `is_child_storage_key`, which\n\n\t\t// just checks if the key has prefix `:child_storage:` at the moment of writing.\n\n\t\tdebug_assert!(\n\n\t\t\twell_known_keys::is_child_storage_key(&storage_key),\n\n\t\t\t\"`is_child_trie_key_valid` is a subset of `is_child_storage_key`\",\n\n\t\t);\n\n\t}\n\n\thas_right_prefix\n\n}\n\n\n", "file_path": "core/trie/src/lib.rs", "rank": 79, "score": 267600.2529744911 }, { "content": "/// Finalize the block.\n\npub fn finalize_block() -> Header {\n\n\tlet extrinsic_index: u32 = storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap();\n\n\tlet txs: Vec<_> = (0..extrinsic_index).map(ExtrinsicData::take).collect();\n\n\tlet txs = txs.iter().map(Vec::as_slice).collect::<Vec<_>>();\n\n\tlet extrinsics_root = enumerated_trie_root::<Blake2Hasher>(&txs).into();\n\n\t// let mut digest = Digest::default();\n\n\tlet number = <Number>::take().expect(\"Number is set by `initialize_block`\");\n\n\tlet parent_hash = <ParentHash>::take();\n\n\tlet mut digest = <StorageDigest>::take().expect(\"StorageDigest is set by `initialize_block`\");\n\n\n\n\tlet o_new_authorities = <NewAuthorities>::take();\n\n\t// This MUST come after all changes to storage are done. Otherwise we will fail the\n\n\t// “Storage root does not match that calculated” assertion.\n\n\tlet storage_root = BlakeTwo256::storage_root();\n\n\tlet storage_changes_root = BlakeTwo256::storage_changes_root(parent_hash);\n\n\n\n\tif let Some(storage_changes_root) = storage_changes_root {\n\n\t\tdigest.push(generic::DigestItem::ChangesTrieRoot(storage_changes_root));\n\n\t}\n\n\n", "file_path": "core/test-runtime/src/system.rs", "rank": 80, "score": 266134.3360759893 }, { "content": "pub fn bob_account() -> u64 {\n\n 2\n\n}\n\n\n\nimpl discovery::Trait for Test {\n\n type Event = MetaEvent;\n\n type Roles = MockRoles;\n\n}\n\n\n\npub struct MockRoles {}\n\nimpl Roles<Test> for MockRoles {\n\n fn is_role_account(account_id: &u64) -> bool {\n\n *account_id == alice_account()\n\n }\n\n\n\n fn account_has_role(_account_id: &u64, _role: actors::Role) -> bool {\n\n false\n\n }\n\n\n\n fn random_account_for_role(_role: actors::Role) -> Result<u64, &'static str> {\n\n Err(\"not implemented\")\n\n }\n\n}\n\n\n", "file_path": "runtime/src/service_discovery/mock.rs", "rank": 81, "score": 266082.4473207325 }, { "content": "pub fn alice_account() -> u64 {\n\n 1\n\n}\n", "file_path": "runtime/src/service_discovery/mock.rs", "rank": 82, "score": 266082.4473207325 }, { "content": "/// Check child storage read proof, generated by `prove_child_read` call.\n\npub fn read_child_proof_check<H>(\n\n\troot: H::Out,\n\n\tproof: Vec<Vec<u8>>,\n\n\tstorage_key: &[u8],\n\n\tkey: &[u8],\n\n) -> Result<Option<Vec<u8>>, Box<dyn Error>>\n\nwhere\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet proving_backend = create_proof_check_backend::<H>(root, proof)?;\n\n\tread_child_proof_check_on_proving_backend(&proving_backend, storage_key, key)\n\n}\n\n\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 83, "score": 265419.23705267766 }, { "content": "/// Create an instance of light client blockchain backend.\n\npub fn new_light_blockchain<B: BlockT, S: BlockchainStorage<B>, F>(storage: S) -> Arc<Blockchain<S, F>> {\n\n\tArc::new(Blockchain::new(storage))\n\n}\n\n\n", "file_path": "core/client/src/light/mod.rs", "rank": 84, "score": 265031.2428997862 }, { "content": "/// Extract the BABE pre digest from the given header. Pre-runtime digests are\n\n/// mandatory, the function will return `Err` if none is found.\n\nfn find_pre_digest<B: BlockT>(header: &B::Header) -> Result<BabePreDigest, String>\n\n\twhere DigestItemFor<B>: CompatibleDigestItem,\n\n{\n\n\tlet mut pre_digest: Option<_> = None;\n\n\tfor log in header.digest().logs() {\n\n\t\ttrace!(target: \"babe\", \"Checking log {:?}, looking for pre runtime digest\", log);\n\n\t\tmatch (log.as_babe_pre_digest(), pre_digest.is_some()) {\n\n\t\t\t(Some(_), true) => Err(babe_err!(\"Multiple BABE pre-runtime digests, rejecting!\"))?,\n\n\t\t\t(None, _) => trace!(target: \"babe\", \"Ignoring digest not meant for us\"),\n\n\t\t\t(s, false) => pre_digest = s,\n\n\t\t}\n\n\t}\n\n\tpre_digest.ok_or_else(|| babe_err!(\"No BABE pre-runtime digest found\"))\n\n}\n\n\n", "file_path": "core/consensus/babe/src/lib.rs", "rank": 85, "score": 264631.53393281094 }, { "content": "/// Read a header from the database.\n\npub fn read_header<Block: BlockT>(\n\n\tdb: &dyn KeyValueDB,\n\n\tcol_index: Option<u32>,\n\n\tcol: Option<u32>,\n\n\tid: BlockId<Block>,\n\n) -> client::error::Result<Option<Block::Header>> {\n\n\tmatch read_db(db, col_index, col, id)? {\n\n\t\tSome(header) => match Block::Header::decode(&mut &header[..]) {\n\n\t\t\tOk(header) => Ok(Some(header)),\n\n\t\t\tErr(_) => return Err(\n\n\t\t\t\tclient::error::Error::Backend(\"Error decoding header\".into())\n\n\t\t\t),\n\n\t\t}\n\n\t\tNone => Ok(None),\n\n\t}\n\n}\n\n\n", "file_path": "core/client/db/src/utils.rs", "rank": 86, "score": 261935.74311049492 }, { "content": "/// Compute the changes trie root and transaction for given block.\n\n/// Returns Err(()) if unknown `parent_hash` has been passed.\n\n/// Returns Ok(None) if there's no data to perform computation.\n\n/// Panics if background storage returns an error OR if insert to MemoryDB fails.\n\npub fn build_changes_trie<'a, B: Backend<H>, S: Storage<H, Number>, H: Hasher, Number: BlockNumber>(\n\n\tbackend: &B,\n\n\tstorage: Option<&'a S>,\n\n\tchanges: &OverlayedChanges,\n\n\tparent_hash: H::Out,\n\n) -> Result<Option<(MemoryDB<H>, H::Out)>, ()>\n\n\twhere\n\n\t\tH::Out: Ord + 'static,\n\n{\n\n\tlet (storage, config) = match (storage, changes.changes_trie_config.as_ref()) {\n\n\t\t(Some(storage), Some(config)) => (storage, config),\n\n\t\t_ => return Ok(None),\n\n\t};\n\n\n\n\t// build_anchor error should not be considered fatal\n\n\tlet parent = storage.build_anchor(parent_hash).map_err(|_| ())?;\n\n\n\n\t// storage errors are considered fatal (similar to situations when runtime fetches values from storage)\n\n\tlet input_pairs = prepare_input::<B, S, H, Number>(backend, storage, config, changes, &parent)\n\n\t\t.expect(\"changes trie: storage access is not allowed to fail within runtime\");\n", "file_path": "core/state-machine/src/changes_trie/mod.rs", "rank": 87, "score": 261530.6524283428 }, { "content": "/// Check storage read proof on pre-created proving backend.\n\npub fn read_proof_check_on_proving_backend<H>(\n\n\tproving_backend: &TrieBackend<MemoryDB<H>, H>,\n\n\tkey: &[u8],\n\n) -> Result<Option<Vec<u8>>, Box<dyn Error>>\n\nwhere\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tproving_backend.storage(key).map_err(|e| Box::new(e) as Box<dyn Error>)\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 88, "score": 261403.1480443498 }, { "content": "/// Check CHT-based header proof.\n\npub fn check_proof<Header, Hasher>(\n\n\tlocal_root: Header::Hash,\n\n\tlocal_number: Header::Number,\n\n\tremote_hash: Header::Hash,\n\n\tremote_proof: Vec<Vec<u8>>\n\n) -> ClientResult<()>\n\n\twhere\n\n\t\tHeader: HeaderT,\n\n\t\tHasher: hash_db::Hasher,\n\n\t\tHasher::Out: Ord,\n\n{\n\n\tdo_check_proof::<Header, Hasher, _>(local_root, local_number, remote_hash, move |local_root, local_cht_key|\n\n\t\tread_proof_check::<Hasher>(local_root, remote_proof,\n\n\t\t\tlocal_cht_key).map_err(|e| ClientError::from(e)))\n\n}\n\n\n", "file_path": "core/client/src/cht.rs", "rank": 89, "score": 260058.5341487598 }, { "content": "fn with_offchain<R>(f: impl FnOnce(&mut dyn offchain::Externalities) -> R, msg: &'static str) -> R {\n\n\text::with(|ext| ext\n\n\t\t.offchain()\n\n\t\t.map(|ext| f(ext))\n\n\t\t.expect(msg)\n\n\t).expect(\"offchain-worker functions cannot be called outside of an Externalities-provided environment.\")\n\n}\n\n\n\nimpl OffchainApi for () {\n\n\tfn submit_transaction<T: codec::Encode>(data: &T) -> Result<(), ()> {\n\n\t\twith_offchain(|ext| {\n\n\t\t\text.submit_transaction(codec::Encode::encode(data))\n\n\t\t}, \"submit_transaction can be called only in the offchain worker context\")\n\n\t}\n\n\n\n\tfn network_state() -> Result<OpaqueNetworkState, ()> {\n\n\t\twith_offchain(|ext| {\n\n\t\t\text.network_state()\n\n\t\t}, \"network_state can be called only in the offchain worker context\")\n\n\t}\n", "file_path": "core/sr-io/with_std.rs", "rank": 90, "score": 258223.20082969146 }, { "content": "/// Get slot author for given block along with authorities.\n\nfn slot_author<P: Pair>(slot_num: u64, authorities: &[AuthorityId<P>]) -> Option<&AuthorityId<P>> {\n\n\tif authorities.is_empty() { return None }\n\n\n\n\tlet idx = slot_num % (authorities.len() as u64);\n\n\tassert!(idx <= usize::max_value() as u64,\n\n\t\t\"It is impossible to have a vector with length beyond the address space; qed\");\n\n\n\n\tlet current_author = authorities.get(idx as usize)\n\n\t\t.expect(\"authorities not empty; index constrained to list length;\\\n\n\t\t\t\tthis is a valid index; qed\");\n\n\n\n\tSome(current_author)\n\n}\n\n\n", "file_path": "core/consensus/aura/src/lib.rs", "rank": 91, "score": 257976.9728846601 }, { "content": "/// Check child storage read proof on pre-created proving backend.\n\npub fn read_child_proof_check_on_proving_backend<H>(\n\n\tproving_backend: &TrieBackend<MemoryDB<H>, H>,\n\n\tstorage_key: &[u8],\n\n\tkey: &[u8],\n\n) -> Result<Option<Vec<u8>>, Box<dyn Error>>\n\nwhere\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tproving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box<dyn Error>)\n\n}\n\n\n\n/// Sets overlayed changes' changes trie configuration. Returns error if configuration\n\n/// differs from previous OR config decode has failed.\n\npub(crate) fn set_changes_trie_config(\n\n\toverlay: &mut OverlayedChanges,\n\n\tconfig: Option<Vec<u8>>,\n\n\tfinal_check: bool,\n\n) -> Result<(), Box<dyn Error>> {\n\n\tlet config = match config {\n", "file_path": "core/state-machine/src/lib.rs", "rank": 92, "score": 257553.87994328828 }, { "content": "/// Generate storage read proof on pre-created trie backend.\n\npub fn prove_read_on_trie_backend<S, H>(\n\n\ttrie_backend: &TrieBackend<S, H>,\n\n\tkey: &[u8]\n\n) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>\n\nwhere\n\n\tS: trie_backend_essence::TrieBackendStorage<H>,\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet proving_backend = proving_backend::ProvingBackend::<_, H>::new(trie_backend);\n\n\tlet result = proving_backend.storage(key).map_err(|e| Box::new(e) as Box<dyn Error>)?;\n\n\tOk((result, proving_backend.extract_proof()))\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 93, "score": 257492.1877486246 }, { "content": "/// Create in-memory storage of proof check backend.\n\npub fn create_proof_check_backend_storage<H>(\n\n\tproof: Vec<Vec<u8>>\n\n) -> MemoryDB<H>\n\nwhere\n\n\tH: Hasher,\n\n{\n\n\tlet mut db = MemoryDB::default();\n\n\tfor item in proof {\n\n\t\tdb.insert(EMPTY_PREFIX, &item);\n\n\t}\n\n\tdb\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse crate::backend::{InMemory};\n\n\tuse crate::trie_backend::tests::test_trie;\n\n\tuse super::*;\n\n\tuse primitives::{Blake2Hasher};\n\n\tuse crate::ChildStorageKey;\n", "file_path": "core/state-machine/src/proving_backend.rs", "rank": 94, "score": 257374.14707520165 }, { "content": "/// Compute a CHT root from an iterator of block hashes. Fails if shorter than\n\n/// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.\n\n/// Discards the trie's nodes.\n\npub fn compute_root<Header, Hasher, I>(\n\n\tcht_size: Header::Number,\n\n\tcht_num: Header::Number,\n\n\thashes: I,\n\n) -> ClientResult<Hasher::Out>\n\n\twhere\n\n\t\tHeader: HeaderT,\n\n\t\tHasher: hash_db::Hasher,\n\n\t\tHasher::Out: Ord,\n\n\t\tI: IntoIterator<Item=ClientResult<Option<Header::Hash>>>,\n\n{\n\n\tuse trie::TrieConfiguration;\n\n\tOk(trie::trie_types::Layout::<Hasher>::trie_root(\n\n\t\tbuild_pairs::<Header, I>(cht_size, cht_num, hashes)?\n\n\t))\n\n}\n\n\n", "file_path": "core/client/src/cht.rs", "rank": 95, "score": 254571.11662124726 }, { "content": "/// Convert header hash into CHT value.\n\nfn encode_cht_value<Hash: AsRef<[u8]>>(hash: Hash) -> Vec<u8> {\n\n\thash.as_ref().to_vec()\n\n}\n\n\n", "file_path": "core/client/src/cht.rs", "rank": 96, "score": 254158.30844707007 }, { "content": "/// Prune obsolete changes tries. Pruning happens at the same block, where highest\n\n/// level digest is created. Pruning guarantees to save changes tries for last\n\n/// `min_blocks_to_keep` blocks. We only prune changes tries at `max_digest_interval`\n\n/// ranges.\n\n/// Returns MemoryDB that contains all deleted changes tries nodes.\n\npub fn prune<S: Storage<H, Number>, H: Hasher, Number: BlockNumber, F: FnMut(H::Out)>(\n\n\tconfig: &Configuration,\n\n\tstorage: &S,\n\n\tmin_blocks_to_keep: Number,\n\n\tcurrent_block: &AnchorBlockId<H::Out, Number>,\n\n\tmut remove_trie_node: F,\n\n) {\n\n\t// select range for pruning\n\n\tlet (first, last) = match pruning_range(config, min_blocks_to_keep, current_block.number.clone()) {\n\n\t\tSome((first, last)) => (first, last),\n\n\t\tNone => return,\n\n\t};\n\n\n\n\t// delete changes trie for every block in range\n\n\t// FIXME: limit `max_digest_interval` so that this cycle won't involve huge ranges\n\n\tlet mut block = first;\n\n\tloop {\n\n\t\tif block >= last.clone() + One::one() {\n\n\t\t\tbreak;\n\n\t\t}\n", "file_path": "core/state-machine/src/changes_trie/prune.rs", "rank": 97, "score": 253781.6735060252 }, { "content": "/// Generate storage read proof on pre-created trie backend.\n\npub fn prove_child_read_on_trie_backend<S, H>(\n\n\ttrie_backend: &TrieBackend<S, H>,\n\n\tstorage_key: &[u8],\n\n\tkey: &[u8]\n\n) -> Result<(Option<Vec<u8>>, Vec<Vec<u8>>), Box<dyn Error>>\n\nwhere\n\n\tS: trie_backend_essence::TrieBackendStorage<H>,\n\n\tH: Hasher,\n\n\tH::Out: Ord\n\n{\n\n\tlet proving_backend = proving_backend::ProvingBackend::<_, H>::new(trie_backend);\n\n\tlet result = proving_backend.child_storage(storage_key, key).map_err(|e| Box::new(e) as Box<dyn Error>)?;\n\n\tOk((result, proving_backend.extract_proof()))\n\n}\n\n\n", "file_path": "core/state-machine/src/lib.rs", "rank": 98, "score": 253643.0102989367 }, { "content": "/// Check CHT-based header proof on pre-created proving backend.\n\npub fn check_proof_on_proving_backend<Header, Hasher>(\n\n\tlocal_root: Header::Hash,\n\n\tlocal_number: Header::Number,\n\n\tremote_hash: Header::Hash,\n\n\tproving_backend: &TrieBackend<MemoryDB<Hasher>, Hasher>,\n\n) -> ClientResult<()>\n\n\twhere\n\n\t\tHeader: HeaderT,\n\n\t\tHasher: hash_db::Hasher,\n\n\t\tHasher::Out: Ord,\n\n{\n\n\tdo_check_proof::<Header, Hasher, _>(local_root, local_number, remote_hash, |_, local_cht_key|\n\n\t\tread_proof_check_on_proving_backend::<Hasher>(\n\n\t\t\tproving_backend, local_cht_key).map_err(|e| ClientError::from(e)))\n\n}\n\n\n", "file_path": "core/client/src/cht.rs", "rank": 99, "score": 253625.72995185805 } ]
Rust
src/lib.rs
Ekleog/netsim-embed
980e43f530bc760a338b89bbba0b4037e43aed60
use futures::channel::mpsc; use futures::future::Future; use futures::sink::SinkExt; use futures::stream::StreamExt; pub use netsim_embed_core::Ipv4Range; use netsim_embed_core::*; use netsim_embed_machine::*; use netsim_embed_nat::*; use netsim_embed_router::*; pub use pnet_packet::*; use std::net::Ipv4Addr; pub fn run<F>(f: F) where F: Future<Output = ()> + Send + 'static, { env_logger::init(); namespace::unshare_user().unwrap(); smol::run(f); } #[derive(Debug)] pub struct Machine<C, E> { addr: Ipv4Addr, tx: mpsc::Sender<C>, rx: mpsc::Receiver<E>, } impl<C: Send + 'static, E: Send + 'static> Machine<C, E> { pub fn addr(&self) -> Ipv4Addr { self.addr } pub async fn send(&mut self, cmd: C) { self.tx.send(cmd).await.unwrap(); } pub async fn recv(&mut self) -> Option<E> { self.rx.next().await } } #[derive(Debug)] pub struct Network<C, E> { range: Ipv4Range, machines: Vec<Machine<C, E>>, networks: Vec<Network<C, E>>, } impl<C: Send + 'static, E: Send + 'static> Network<C, E> { pub fn range(&self) -> Ipv4Range { self.range } pub fn subnet(&mut self, i: usize) -> &mut Network<C, E> { self.networks.get_mut(i).unwrap() } pub fn machine(&mut self, i: usize) -> &mut Machine<C, E> { self.machines.get_mut(i).unwrap() } } #[derive(Clone, Copy, Debug)] pub struct NatConfig { pub hair_pinning: bool, pub symmetric: bool, pub blacklist_unrecognized_addrs: bool, pub restrict_endpoints: bool, } impl Default for NatConfig { fn default() -> Self { Self { hair_pinning: false, symmetric: false, blacklist_unrecognized_addrs: false, restrict_endpoints: false, } } } #[derive(Debug)] pub struct NetworkBuilder<C, E> { range: Ipv4Range, router: Ipv4Router, machines: Vec<Machine<C, E>>, networks: Vec<Network<C, E>>, } impl<C: Send + 'static, E: Send + 'static> NetworkBuilder<C, E> { pub fn new(range: Ipv4Range) -> Self { let router = Ipv4Router::new(range.gateway_addr()); Self { range, router, machines: Default::default(), networks: Default::default(), } } pub fn spawn_machine<B, F>(&mut self, builder: B) -> Ipv4Addr where B: Fn(mpsc::Receiver<C>, mpsc::Sender<E>) -> F + Send + 'static, F: Future<Output = ()> + Send + 'static, { let (iface_a, iface_b) = wire(); let (cmd_tx, cmd_rx) = mpsc::channel(0); let (event_tx, event_rx) = mpsc::channel(0); let addr = self.range.random_client_addr(); let mask = self.range.netmask_prefix_length(); smol::Task::blocking(async move { let join = machine(addr, mask, iface_b, builder(cmd_rx, event_tx)); join.join().unwrap(); }) .detach(); let machine = Machine { addr, tx: cmd_tx, rx: event_rx, }; self.machines.push(machine); self.router.add_connection(iface_a, vec![addr.into()]); addr } pub fn spawn_network(&mut self, config: Option<NatConfig>, mut builder: NetworkBuilder<C, E>) { let (net_a, net_b) = wire(); if let Some(config) = config { builder .router .add_connection(net_b, vec![Ipv4Range::global().into()]); let (nat_a, nat_b) = wire(); let nat_addr = self.range.random_client_addr(); let mut nat = Ipv4Nat::new(nat_b, net_a, nat_addr, builder.range); nat.set_hair_pinning(config.hair_pinning); nat.set_symmetric(config.symmetric); nat.set_blacklist_unrecognized_addrs(config.blacklist_unrecognized_addrs); nat.set_restrict_endpoints(config.restrict_endpoints); smol::Task::spawn(nat).detach(); self.router.add_connection(nat_a, vec![nat_addr.into()]); } else { builder .router .add_connection(net_b, vec![Ipv4Range::global().into()]); self.router .add_connection(net_a, vec![builder.range.into()]); } let network = builder.spawn(); self.networks.push(network); } pub fn spawn(self) -> Network<C, E> { let Self { range, router, machines, networks, } = self; smol::Task::spawn(router).detach(); Network { range, machines, networks, } } }
use futures::channel::mpsc; use futures::future::Future; use futures::sink::SinkExt; use futures::stream::StreamExt; pub use netsim_embed_core::Ipv4Range; use netsim_embed_core::*; use netsim_embed_machine::*; use netsim_embed_nat::*; use netsim_embed_router::*; pub use pnet_packet::*; use std::net::Ipv4Addr; pub fn run<F>(f: F) where F: Future<Output = ()> + Send + 'static, { env_logger::init(); namespace::unshare_user().unwrap(); smol::run(f); } #[derive(Debug)] pub struct Machine<C, E> { addr: Ipv4Addr, tx: mpsc::Sender<C>, rx: mpsc::Receiver<E>, } impl<C: Send + 'static, E: Send + 'static> Machine<C, E> { pub fn addr(&self) -> Ipv4Addr { self.addr } pub async fn send(&mut self, cmd: C) { self.tx.send(cmd).await.unwrap(); } pub async fn recv(&mut self) -> Option<E> { self.rx.next().await } } #[derive(Debug)] pub struct Network<C, E> { range: Ipv4Range, machines: Vec<Machine<C, E>>, networks: Vec<Network<C, E>>, } impl<C: Send + 'static, E: Send + 'static> Network<C, E> { pub fn range(&self) -> Ipv4Range { self.range } pub fn subnet(&mut self, i: usize) -> &mut Network<C, E> { self.networks.get_mut(i).unwrap() } pub fn machine(&mut self, i: usize) -> &mut Machine<C, E> { self.machines.get_mut(i).unwrap() } } #[derive(Clone, Copy, Debug)] pub struct NatConfig { pub hair_pinning: bool, pub symmetric: bool, pub blacklist_unrecognized_addrs: bool, pub restrict_endpoints: bool, } impl Default for NatConfig { fn default() -> Self { Self { hair_pinning: false, symmetric: false, blacklist_unrecognized_addrs: false, restrict_endpoints: false, } } } #[derive(Debug)] pub struct NetworkBuilder<C, E> { range: Ipv4Range, router: Ipv4Router, machines: Vec<Machine<C, E>>, networks: Vec<Network<C, E>>, } impl<C: Send + 'static, E: Send + 'static> NetworkBuilder<C, E> { pub fn new(range: Ipv4Range) -> Self { let router = Ipv4Router::new(range.gateway_addr()); Self { range, router, machines: Default::default(), networks: Default::default(), } } pub fn spawn_machine<B, F>(&mut self, builder: B) -> Ipv4Addr where B: Fn(mpsc::Receiver<C>, mpsc::Sender<E>) -> F + Send + 'static, F: Future<Output = ()> + Send + 'static, { let (iface_a, iface_b) = wire(); let (cmd_tx, cmd_rx) = mpsc::channel(0); let (event_tx, event_rx) = mpsc::channel(0); let addr = self.range.random_client_addr(); let mask = self.range.netmask_prefix_length(); smol::Task::blocking(async move { let join = machine(addr, mask, iface_b, builder(cmd_rx, event_tx)); join.join().unwrap(); }) .detach(); let machine = Machine { addr, tx: cmd_tx, rx: event_rx, }; self.machines.push(machine); self.router.add_connection(iface_a, vec![addr.into()]); addr } pub fn spawn_network(&mut self, config: Option<NatConfig>, mut builder: NetworkBuilder<C, E>) { let (net_a, net_b) = wire(); if let Some(config) = config { builder .router .add_connection(net_b, vec![Ipv4Range::global().into()]); let (nat_a, nat_b) = wire(); let nat_addr = self.range.random_client_addr(); let mut nat = Ipv4Nat::new(nat_b, net_a, nat_addr, builder.range); nat.set_hair_pinning(config.hair_pinning); nat.set_symmetric(config.symmetric); nat.set_blacklist_unrecognized_addrs(config.blacklist_unrecognized_addrs); nat.set_restrict_endpoints(config.restrict_endpoints); smol::Task::spawn(nat).detach(); self.router.add_connection(nat_a, vec![nat_addr.into()]); } else { builder .router .add_connection(net_b, vec![Ipv4Range::global().into()]); self.router .add_connection(net_a, vec![builder.range.into()]); } let network = builder.spawn(); self.networks.push(network); } pub fn spawn(self) -> Network<C, E> { let Self {
}
range, router, machines, networks, } = self; smol::Task::spawn(router).detach(); Network { range, machines, networks, } }
function_block-function_prefix_line
[ { "content": "/// Spawns a thread in a new network namespace and configures a TUN interface that sends and\n\n/// receives IP packets from the tx/rx channels and runs some UDP/TCP networking code in task.\n\npub fn machine<F>(addr: Ipv4Addr, mask: u8, plug: Plug, task: F) -> thread::JoinHandle<F::Output>\n\nwhere\n\n F: Future + Send + 'static,\n\n F::Output: Send + 'static,\n\n{\n\n thread::spawn(move || {\n\n namespace::unshare_network().unwrap();\n\n\n\n let create_tun_iface = || {\n\n let iface = iface::Iface::new().unwrap();\n\n iface.set_ipv4_addr(addr, mask).unwrap();\n\n iface.put_up().unwrap();\n\n iface.add_ipv4_route(Ipv4Range::global().into()).unwrap();\n\n\n\n #[cfg(not(feature = \"tokio2\"))]\n\n let iface = smol::Async::new(iface).unwrap();\n\n #[cfg(feature = \"tokio2\")]\n\n let iface = tokio::TokioFd::new(iface).unwrap();\n\n\n\n let (mut tx, mut rx) = plug.split();\n", "file_path": "machine/src/lib.rs", "rank": 0, "score": 158833.86977145032 }, { "content": "pub trait PortAllocator: std::fmt::Debug + Send {\n\n fn next_port(&mut self, local_endpoint: SocketAddrV4) -> u16;\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct SequentialPortAllocator {\n\n next_original_port: u16,\n\n next_for_local_endpoint: HashMap<SocketAddrV4, u16>,\n\n}\n\n\n\nimpl Default for SequentialPortAllocator {\n\n fn default() -> Self {\n\n Self {\n\n next_original_port: 49152,\n\n next_for_local_endpoint: HashMap::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl PortAllocator for SequentialPortAllocator {\n", "file_path": "nat/src/port_allocator.rs", "rank": 2, "score": 98199.67936787196 }, { "content": "pub fn unshare_network() -> Result<(), io::Error> {\n\n unsafe {\n\n errno!(libc::unshare(libc::CLONE_NEWNET | libc::CLONE_NEWUTS))?;\n\n let pid = errno!(libc::getpid())?;\n\n let tid = errno!(libc::syscall(libc::SYS_gettid))?;\n\n log::info!(\n\n \"created network namespace: /proc/{}/task/{}/ns/net\",\n\n pid,\n\n tid\n\n );\n\n Ok(())\n\n }\n\n}\n", "file_path": "machine/src/namespace.rs", "rank": 3, "score": 91236.09681281267 }, { "content": "pub fn wire() -> (Plug, Plug) {\n\n let (a_tx, b_rx) = mpsc::unbounded();\n\n let (b_tx, a_rx) = mpsc::unbounded();\n\n let a = Plug { tx: a_tx, rx: a_rx };\n\n let b = Plug { tx: b_tx, rx: b_rx };\n\n (a, b)\n\n}\n", "file_path": "core/src/lib.rs", "rank": 4, "score": 89850.02769471466 }, { "content": "pub fn unshare_user() -> Result<(), io::Error> {\n\n let uid = unsafe { libc::geteuid() };\n\n let gid = unsafe { libc::getegid() };\n\n\n\n unsafe { errno!(libc::unshare(libc::CLONE_NEWUSER))? };\n\n\n\n let mut f = File::create(\"/proc/self/uid_map\")?;\n\n let s = format!(\"0 {} 1\\n\", uid);\n\n f.write(s.as_bytes())?;\n\n\n\n let mut f = File::create(\"/proc/self/setgroups\")?;\n\n f.write(b\"deny\\n\")?;\n\n\n\n let mut f = File::create(\"/proc/self/gid_map\")?;\n\n let s = format!(\"0 {} 1\\n\", gid);\n\n f.write(s.as_bytes())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "machine/src/namespace.rs", "rank": 5, "score": 71247.86475951163 }, { "content": "/// Extension methods for IPv4 addresses\n\npub trait Ipv4AddrExt {\n\n /// Get a random, global IPv4 address.\n\n fn random_global() -> Ipv4Addr;\n\n /// Returns `true` if this is a global IPv4 address\n\n fn is_global(&self) -> bool;\n\n /// Returns `true` if this is a reserved IPv4 address.\n\n fn is_reserved_addr(&self) -> bool;\n\n /// Clasify the address.\n\n fn class(&self) -> Ipv4AddrClass;\n\n /// Create an `Ipv4Addr` representing a netmask\n\n fn from_netmask_bits(bits: u8) -> Ipv4Addr;\n\n}\n\n\n\nimpl Ipv4AddrExt for Ipv4Addr {\n\n fn random_global() -> Ipv4Addr {\n\n loop {\n\n let x: u32 = rand::random();\n\n let ip = Ipv4Addr::from(x);\n\n if Ipv4AddrExt::is_global(&ip) {\n\n return ip;\n", "file_path": "core/src/addr.rs", "rank": 6, "score": 59755.241455482115 }, { "content": "fn main() {\n\n run(async {\n\n let builder = |node_name: &'static str| move |mut cmd: mpsc::Receiver<Command>, mut event: mpsc::Sender<Event>| async move {\n\n let tmp = TempDir::new(\"netsim_embed\").unwrap();\n\n let mut config = Config::from_path(tmp.path()).unwrap();\n\n let bootstrap = if let Command::Bootstrap(bootstrap) = cmd.next().await.unwrap() {\n\n bootstrap\n\n } else {\n\n unreachable!()\n\n };\n\n config.network.node_name = node_name.to_string();\n\n config.network.boot_nodes = bootstrap;\n\n config.network.enable_mdns = false;\n\n let store = Store::new(config).unwrap();\n\n let address = store.address().clone();\n\n let peer_id = store.peer_id().clone();\n\n event.send(Event::Bootstrapped(address, peer_id)).await.unwrap();\n\n\n\n while let Some(cmd) = cmd.next().await {\n\n match cmd {\n", "file_path": "examples/p2p.rs", "rank": 7, "score": 34588.08355436246 }, { "content": "fn main() {\n\n run(async {\n\n let mut net = NetworkBuilder::new(Ipv4Range::global());\n\n let addr = net.spawn_machine(|_: mpsc::Receiver<()>, _: mpsc::Sender<()>| async move {\n\n let socket = smol::Async::<UdpSocket>::bind(\"0.0.0.0:3000\").unwrap();\n\n loop {\n\n let mut buf = [0u8; 11];\n\n let (len, addr) = socket.recv_from(&mut buf).await.unwrap();\n\n if &buf[..len] == b\"ping\" {\n\n println!(\"received ping\");\n\n\n\n socket.send_to(b\"pong\", addr).await.unwrap();\n\n break;\n\n }\n\n }\n\n });\n\n\n\n let mut local = NetworkBuilder::new(Ipv4Range::random_local_subnet());\n\n local.spawn_machine(\n\n move |_: mpsc::Receiver<()>, mut events: mpsc::Sender<()>| async move {\n", "file_path": "examples/ping_pong_udp.rs", "rank": 8, "score": 32045.822578958425 }, { "content": "fn main() {\n\n run(async {\n\n let mut net = NetworkBuilder::new(Ipv4Range::global());\n\n let addr = net.spawn_machine(|_: mpsc::Receiver<()>, _: mpsc::Sender<()>| async move {\n\n let listener = smol::Async::<TcpListener>::bind(\"0.0.0.0:3000\").unwrap();\n\n let mut stream = listener.incoming().next().await.unwrap().unwrap();\n\n\n\n let mut buf = [0u8; 11];\n\n let len = stream.read(&mut buf).await.unwrap();\n\n assert_eq!(&buf[..len], &b\"ping\"[..]);\n\n\n\n println!(\"received ping\");\n\n stream.write_all(b\"pong\").await.unwrap();\n\n });\n\n\n\n let mut local = NetworkBuilder::new(Ipv4Range::random_local_subnet());\n\n local.spawn_machine(\n\n move |_: mpsc::Receiver<()>, mut events: mpsc::Sender<()>| async move {\n\n let mut stream = smol::Async::<TcpStream>::connect(SocketAddrV4::new(addr, 3000))\n\n .await\n", "file_path": "examples/ping_pong_tcp.rs", "rank": 9, "score": 32045.822578958425 }, { "content": " tcp_map: PortMap,\n\n blacklist_unrecognized_addrs: bool,\n\n blacklisted_addrs: HashSet<SocketAddrV4>,\n\n}\n\n\n\nimpl Ipv4Nat {\n\n pub fn new(\n\n public_plug: Plug,\n\n private_plug: Plug,\n\n public_ip: Ipv4Addr,\n\n subnet: Ipv4Range,\n\n ) -> Self {\n\n Self {\n\n private_plug,\n\n public_plug,\n\n public_ip,\n\n subnet,\n\n hair_pinning: false,\n\n udp_map: Default::default(),\n\n tcp_map: Default::default(),\n", "file_path": "nat/src/nat.rs", "rank": 10, "score": 31624.253100964706 }, { "content": "use crate::packet::{Packet, Protocol};\n\nuse crate::port_map::PortMap;\n\nuse futures::future::Future;\n\nuse netsim_embed_core::{Ipv4Range, Plug};\n\nuse std::collections::HashSet;\n\nuse std::net::{Ipv4Addr, SocketAddrV4};\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\n\n\nuse crate::port_allocator::PortAllocator;\n\n\n\n/// An Ipv4 NAT.\n\n#[derive(Debug)]\n\npub struct Ipv4Nat {\n\n private_plug: Plug,\n\n public_plug: Plug,\n\n public_ip: Ipv4Addr,\n\n subnet: Ipv4Range,\n\n hair_pinning: bool,\n\n udp_map: PortMap,\n", "file_path": "nat/src/nat.rs", "rank": 11, "score": 31621.761259639832 }, { "content": " Protocol::Tcp => self.tcp_map.forward_port(port, local_addr),\n\n }\n\n }\n\n\n\n /// Causes the NAT to permanently block all traffic from an address A if it recieves\n\n /// traffic from A directed at an endpoint for which it doesn't have a mapping.\n\n pub fn set_blacklist_unrecognized_addrs(&mut self, blacklist_unrecognized_addrs: bool) {\n\n self.blacklist_unrecognized_addrs = blacklist_unrecognized_addrs;\n\n }\n\n\n\n /// Only allow incoming traffic on a port from remote addresses that we have already\n\n /// sent data to from that port. Makes this a port-restricted NAT.\n\n pub fn set_restrict_endpoints(&mut self, restrict_endpoints: bool) {\n\n self.udp_map.set_restrict_endpoints(restrict_endpoints);\n\n self.tcp_map.set_restrict_endpoints(restrict_endpoints);\n\n }\n\n\n\n /// Makes this NAT a symmetric NAT, meaning packets sent to different remote addresses from\n\n /// the same internal address will appear to originate from different external ports.\n\n pub fn set_symmetric(&mut self, symmetric: bool) {\n", "file_path": "nat/src/nat.rs", "rank": 12, "score": 31621.586941958376 }, { "content": " self.udp_map.set_symmetric(symmetric);\n\n self.tcp_map.set_symmetric(symmetric);\n\n }\n\n}\n\n\n\nimpl Ipv4Nat {\n\n fn process_outgoing(&mut self, cx: &mut Context) -> bool {\n\n loop {\n\n match self.private_plug.poll_incoming(cx) {\n\n Poll::Pending => return false,\n\n Poll::Ready(None) => return true,\n\n Poll::Ready(Some(mut bytes)) => {\n\n let mut packet = if let Some(packet) = Packet::new(&mut bytes) {\n\n packet\n\n } else {\n\n log::info!(\"nat {}: dropping invalid outbound packet\", self.public_ip);\n\n continue;\n\n };\n\n let source_addr = packet.get_source();\n\n let dest_addr = packet.get_destination();\n", "file_path": "nat/src/nat.rs", "rank": 13, "score": 31620.845621615314 }, { "content": " blacklist_unrecognized_addrs: false,\n\n blacklisted_addrs: Default::default(),\n\n }\n\n }\n\n\n\n /// Set the port allocator.\n\n pub fn set_port_allocator<T: Clone + PortAllocator + 'static>(&mut self, port_allocator: T) {\n\n self.udp_map.set_port_allocator(port_allocator.clone());\n\n self.tcp_map.set_port_allocator(port_allocator);\n\n }\n\n\n\n /// Enable/disable hair-pinning.\n\n pub fn set_hair_pinning(&mut self, hair_pinning: bool) {\n\n self.hair_pinning = hair_pinning;\n\n }\n\n\n\n /// Manually forward a port.\n\n pub fn forward_port(&mut self, port: u16, local_addr: SocketAddrV4, protocol: Protocol) {\n\n match protocol {\n\n Protocol::Udp => self.udp_map.forward_port(port, local_addr),\n", "file_path": "nat/src/nat.rs", "rank": 14, "score": 31618.720823306412 }, { "content": " }\n\n }\n\n }\n\n }\n\n}\n\n\n\nimpl Future for Ipv4Nat {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let private_unplugged = self.process_outgoing(cx);\n\n let public_unplugged = self.process_incoming(cx);\n\n\n\n if private_unplugged && public_unplugged {\n\n return Poll::Ready(());\n\n }\n\n\n\n Poll::Pending\n\n }\n\n}\n", "file_path": "nat/src/nat.rs", "rank": 15, "score": 31617.75681302308 }, { "content": " }\n\n\n\n fn process_incoming(&mut self, cx: &mut Context) -> bool {\n\n loop {\n\n match self.public_plug.poll_incoming(cx) {\n\n Poll::Pending => return false,\n\n Poll::Ready(None) => return true,\n\n Poll::Ready(Some(mut bytes)) => {\n\n let mut packet = if let Some(packet) = Packet::new(&mut bytes) {\n\n packet\n\n } else {\n\n log::info!(\"nat {}: dropping invalid inbound packet.\", self.public_ip);\n\n continue;\n\n };\n\n let source_addr = packet.get_source();\n\n let dest_addr = packet.get_destination();\n\n\n\n if dest_addr.ip() != &self.public_ip {\n\n log::info!(\n\n \"nat {} dropping inbound packet not directed at our public ip.\",\n", "file_path": "nat/src/nat.rs", "rank": 16, "score": 31616.61609887229 }, { "content": " );\n\n packet.set_checksum();\n\n let _ = self.private_plug.unbounded_send(bytes);\n\n } else {\n\n if self.blacklist_unrecognized_addrs {\n\n log::info!(\n\n \"nat {}: blacklisting unknown address {}.\",\n\n self.public_ip,\n\n source_addr,\n\n );\n\n self.blacklisted_addrs.insert(source_addr);\n\n } else {\n\n log::info!(\n\n \"nat {}: dropping packet to unknown inbound destination {}.\",\n\n self.public_ip,\n\n dest_addr,\n\n );\n\n log::info!(\"{:?}\", map);\n\n }\n\n }\n", "file_path": "nat/src/nat.rs", "rank": 17, "score": 31615.16666539035 }, { "content": " self.public_ip,\n\n dest_addr,\n\n private_dest_addr,\n\n );\n\n packet.set_checksum();\n\n let _ = self.private_plug.unbounded_send(bytes);\n\n } else {\n\n packet.set_source(external_source_addr);\n\n log::trace!(\n\n \"nat {}: rewrote outbound packet source address: {} => {}\",\n\n self.public_ip,\n\n source_addr,\n\n external_source_addr,\n\n );\n\n packet.set_checksum();\n\n let _ = self.public_plug.unbounded_send(bytes);\n\n }\n\n }\n\n }\n\n }\n", "file_path": "nat/src/nat.rs", "rank": 18, "score": 31615.128660447004 }, { "content": " self.public_ip,\n\n source_addr\n\n );\n\n continue;\n\n }\n\n\n\n let map = match packet.protocol() {\n\n Protocol::Udp => &mut self.udp_map,\n\n Protocol::Tcp => &mut self.tcp_map,\n\n };\n\n\n\n if let Some(private_dest_addr) =\n\n map.get_inbound_addr(source_addr, dest_addr.port())\n\n {\n\n packet.set_destination(private_dest_addr);\n\n log::trace!(\n\n \"nat {}: rewrote inbound packet destination address: {} => {}.\",\n\n self.public_ip,\n\n dest_addr,\n\n private_dest_addr,\n", "file_path": "nat/src/nat.rs", "rank": 19, "score": 31614.710338026158 }, { "content": "\n\n let map = match packet.protocol() {\n\n Protocol::Udp => &mut self.udp_map,\n\n Protocol::Tcp => &mut self.tcp_map,\n\n };\n\n\n\n let external_source_addr =\n\n SocketAddrV4::new(self.public_ip, map.map_port(dest_addr, source_addr));\n\n\n\n if self.hair_pinning && dest_addr.ip() == &self.public_ip {\n\n let private_dest_addr = if let Some(addr) =\n\n map.get_inbound_addr(external_source_addr, dest_addr.port())\n\n {\n\n addr\n\n } else {\n\n continue;\n\n };\n\n packet.set_destination(private_dest_addr);\n\n log::trace!(\n\n \"nat {}: rewrote outbound packet destination address: {} => {}\",\n", "file_path": "nat/src/nat.rs", "rank": 20, "score": 31614.303241833353 }, { "content": " self.public_ip,\n\n );\n\n continue;\n\n }\n\n\n\n let next_ttl = match packet.get_ttl().checked_sub(1) {\n\n Some(ttl) => ttl,\n\n None => {\n\n log::info!(\n\n \"nat {} dropping inbound packet with ttl zero.\",\n\n self.public_ip,\n\n );\n\n continue;\n\n }\n\n };\n\n packet.set_ttl(next_ttl);\n\n\n\n if self.blacklisted_addrs.contains(&source_addr) {\n\n log::info!(\n\n \"nat {} dropped packet from blacklisted addr {}.\",\n", "file_path": "nat/src/nat.rs", "rank": 21, "score": 31612.766348757195 }, { "content": "\n\n if !self.subnet.contains(*source_addr.ip()) {\n\n log::info!(\n\n \"nat {}: dropping outbound packet which does not originate from our subnet.\",\n\n self.public_ip,\n\n );\n\n continue;\n\n }\n\n\n\n let next_ttl = match packet.get_ttl().checked_sub(1) {\n\n Some(ttl) => ttl,\n\n None => {\n\n log::info!(\n\n \"nat {} dropping outbound packet with ttl zero.\",\n\n self.public_ip,\n\n );\n\n continue;\n\n }\n\n };\n\n packet.set_ttl(next_ttl);\n", "file_path": "nat/src/nat.rs", "rank": 22, "score": 31611.771451100776 }, { "content": "use futures::channel::mpsc;\n\nuse futures::future::Future;\n\nuse futures::stream::Stream;\n\nuse netsim_embed_core::{Ipv4Route, Plug};\n\nuse pnet_packet::ipv4::Ipv4Packet;\n\nuse std::net::Ipv4Addr;\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\n\n\n#[derive(Debug)]\n\npub struct Ipv4Router {\n\n addr: Ipv4Addr,\n\n rxs: Vec<mpsc::UnboundedReceiver<Vec<u8>>>,\n\n txs: Vec<(mpsc::UnboundedSender<Vec<u8>>, Vec<Ipv4Route>)>,\n\n}\n\n\n\nimpl Ipv4Router {\n\n pub fn new(addr: Ipv4Addr) -> Self {\n\n Self {\n\n addr,\n", "file_path": "router/src/lib.rs", "rank": 23, "score": 26260.751962851395 }, { "content": " rxs: Default::default(),\n\n txs: Default::default(),\n\n }\n\n }\n\n\n\n pub fn add_connection(&mut self, plug: Plug, routes: Vec<Ipv4Route>) {\n\n let (tx, rx) = plug.split();\n\n self.rxs.push(rx);\n\n self.txs.push((tx, routes));\n\n }\n\n\n\n fn process_packet(&mut self, bytes: Vec<u8>) {\n\n let packet = if let Some(packet) = Ipv4Packet::new(&bytes) {\n\n packet\n\n } else {\n\n log::info!(\"router {}: dropping invalid ipv4 packet\", self.addr);\n\n return;\n\n };\n\n let dest = packet.get_destination();\n\n if dest == self.addr {\n", "file_path": "router/src/lib.rs", "rank": 24, "score": 26260.55233061463 }, { "content": " log::info!(\"router {}: dropping packet addressed to me\", self.addr);\n\n return;\n\n }\n\n for (tx, routes) in &self.txs {\n\n for route in routes {\n\n if route.dest().contains(dest) {\n\n log::debug!(\"router {}: routing packet on route {:?}\", self.addr, route);\n\n let _ = tx.unbounded_send(bytes);\n\n return;\n\n }\n\n }\n\n }\n\n log::info!(\n\n \"router {}: dropping unroutable packet to {}\",\n\n self.addr,\n\n dest\n\n );\n\n }\n\n}\n\n\n", "file_path": "router/src/lib.rs", "rank": 25, "score": 26258.305983434915 }, { "content": "impl Future for Ipv4Router {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let mut i = 0;\n\n while i < self.rxs.len() {\n\n loop {\n\n let packet = match Pin::new(&mut self.rxs[i]).poll_next(cx) {\n\n Poll::Pending => {\n\n i += 1;\n\n break;\n\n }\n\n Poll::Ready(None) => {\n\n self.rxs.remove(i);\n\n self.txs.remove(i);\n\n break;\n\n }\n\n Poll::Ready(Some(packet)) => packet,\n\n };\n\n self.process_packet(packet)\n", "file_path": "router/src/lib.rs", "rank": 26, "score": 26254.818873390774 }, { "content": " }\n\n }\n\n\n\n if self.rxs.is_empty() {\n\n return Poll::Ready(());\n\n }\n\n\n\n Poll::Pending\n\n }\n\n}\n", "file_path": "router/src/lib.rs", "rank": 27, "score": 26245.549329684764 }, { "content": "use std::net::Ipv4Addr;\n\n\n\n#[derive(PartialEq, Eq, Clone, Copy, PartialOrd, Ord, Hash)]\n\npub enum Ipv4AddrClass {\n\n Unspecified,\n\n CurrentNetwork,\n\n Private,\n\n CarrierNat,\n\n Loopback,\n\n LinkLocal,\n\n ProtocolAssignments,\n\n Testnet,\n\n Ipv6Relay,\n\n BenchmarkTests,\n\n Multicast,\n\n Reserved,\n\n Broadcast,\n\n Global,\n\n}\n\n\n\n/// Extension methods for IPv4 addresses\n", "file_path": "core/src/addr.rs", "rank": 28, "score": 26095.66364824089 }, { "content": " }\n\n */\n\n\n\n if ip == 0x00_00_00_00 {\n\n return Ipv4AddrClass::Unspecified;\n\n };\n\n if ip > 0x00_00_00_00 && ip < 0x01_00_00_00 {\n\n return Ipv4AddrClass::CurrentNetwork;\n\n };\n\n if ip >= 0x0a_00_00_00 && ip < 0x0b_00_00_00 {\n\n return Ipv4AddrClass::Private;\n\n };\n\n if ip >= 0x64_40_00_00 && ip < 0x64_80_00_00 {\n\n return Ipv4AddrClass::CarrierNat;\n\n };\n\n if ip >= 0x7f_00_00_00 && ip < 0x80_00_00_00 {\n\n return Ipv4AddrClass::Loopback;\n\n };\n\n if ip >= 0xa9_fe_00_00 && ip < 0xa9_ff_00_00 {\n\n return Ipv4AddrClass::LinkLocal;\n", "file_path": "core/src/addr.rs", "rank": 29, "score": 26090.52861766738 }, { "content": " /*\n\n * needs feature(exclusive_range_patterns)\n\n match ip {\n\n 0x00000000 .. 0x01000000 => Ipv4AddrClass::CurrentNetwork,\n\n 0x0a000000 .. 0x0b000000 => Ipv4AddrClass::Private,\n\n 0x64400000 .. 0x64800000 => Ipv4AddrClass::CarrierNat,\n\n 0x7f000000 .. 0x80000000 => Ipv4AddrClass::Loopback,\n\n 0xa9fe0000 .. 0xa9ff0000 => Ipv4AddrClass::LinkLocal,\n\n 0xac100000 .. 0xac200000 => Ipv4AddrClass::Private,\n\n 0xc0000000 .. 0xc0000100 => Ipv4AddrClass::ProtocolAssignments,\n\n 0xc0000200 .. 0xc0000300 => Ipv4AddrClass::Testnet,\n\n 0xc0586300 .. 0xc0586400 => Ipv4AddrClass::Ipv6Relay,\n\n 0xc0a80000 .. 0xc0a90000 => Ipv4AddrClass::Private,\n\n 0xc6120000 .. 0xc6140000 => Ipv4AddrClass::BenchmarkTests,\n\n 0xc6336400 .. 0xc6336500 => Ipv4AddrClass::Testnet,\n\n 0xcb007100 .. 0xcb007200 => Ipv4AddrClass::Testnet,\n\n 0xe0000000 .. 0xf0000000 => Ipv4AddrClass::Multicast,\n\n 0xf0000000 .. 0xffffffff => Ipv4AddrClass::Reserved,\n\n 0xffffffff => Ipv4AddrClass::Broadcast,\n\n _ => Ipv4AddrClass::Global,\n", "file_path": "core/src/addr.rs", "rank": 30, "score": 26090.529860175793 }, { "content": " }\n\n }\n\n }\n\n\n\n fn is_global(&self) -> bool {\n\n !(self.is_loopback()\n\n || self.is_private()\n\n || self.is_link_local()\n\n || self.is_multicast()\n\n || self.is_broadcast()\n\n || self.is_documentation()\n\n || self.is_reserved_addr())\n\n }\n\n\n\n fn is_reserved_addr(&self) -> bool {\n\n u32::from(*self) & 0xf000_0000 == 0xf000_0000\n\n }\n\n\n\n fn class(&self) -> Ipv4AddrClass {\n\n let ip = u32::from(*self);\n", "file_path": "core/src/addr.rs", "rank": 31, "score": 26090.23174569325 }, { "content": " return Ipv4AddrClass::Testnet;\n\n };\n\n if ip >= 0xcb_00_71_00 && ip < 0xcb_00_72_00 {\n\n return Ipv4AddrClass::Testnet;\n\n };\n\n if ip >= 0xe0_00_00_00 && ip < 0xf0_00_00_00 {\n\n return Ipv4AddrClass::Multicast;\n\n };\n\n if ip >= 0xf0_00_00_00 && ip < 0xff_ff_ff_ff {\n\n return Ipv4AddrClass::Reserved;\n\n };\n\n if ip == 0xff_ff_ff_ff {\n\n return Ipv4AddrClass::Broadcast;\n\n };\n\n Ipv4AddrClass::Global\n\n }\n\n\n\n fn from_netmask_bits(bits: u8) -> Ipv4Addr {\n\n Ipv4Addr::from(!((!0u32) >> bits))\n\n }\n\n}\n", "file_path": "core/src/addr.rs", "rank": 32, "score": 26087.197380008016 }, { "content": " };\n\n if ip >= 0xac_10_00_00 && ip < 0xac_20_00_00 {\n\n return Ipv4AddrClass::Private;\n\n };\n\n if ip >= 0xc0_00_00_00 && ip < 0xc0_00_01_00 {\n\n return Ipv4AddrClass::ProtocolAssignments;\n\n };\n\n if ip >= 0xc0_00_02_00 && ip < 0xc0_00_03_00 {\n\n return Ipv4AddrClass::Testnet;\n\n };\n\n if ip >= 0xc0_58_63_00 && ip < 0xc0_58_64_00 {\n\n return Ipv4AddrClass::Ipv6Relay;\n\n };\n\n if ip >= 0xc0_a8_00_00 && ip < 0xc0_a9_00_00 {\n\n return Ipv4AddrClass::Private;\n\n };\n\n if ip >= 0xc6_12_00_00 && ip < 0xc6_14_00_00 {\n\n return Ipv4AddrClass::BenchmarkTests;\n\n };\n\n if ip >= 0xc6_33_64_00 && ip < 0xc6_33_65_00 {\n", "file_path": "core/src/addr.rs", "rank": 33, "score": 26087.01633365245 }, { "content": "use crate::addr::{Ipv4AddrClass, Ipv4AddrExt};\n\nuse std::net::Ipv4Addr;\n\nuse std::str::FromStr;\n\nuse thiserror::Error;\n\n\n\n/// A range of IPv4 addresses with a common prefix\n\n#[derive(Clone, Copy)]\n\npub struct Ipv4Range {\n\n addr: Ipv4Addr,\n\n bits: u8,\n\n}\n\n\n\nimpl std::fmt::Debug for Ipv4Range {\n\n fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n\n write!(f, \"{}/{}\", self.addr, self.bits)\n\n }\n\n}\n\n\n\nimpl Ipv4Range {\n\n /// Create an IPv4 range with the given base address and netmask prefix length.\n", "file_path": "core/src/range.rs", "rank": 34, "score": 25880.115949220675 }, { "content": " continue;\n\n }\n\n return addr;\n\n }\n\n }\n\n\n\n /// Check whether this range contains the given IP address\n\n pub fn contains(&self, ip: Ipv4Addr) -> bool {\n\n let base_addr = u32::from(self.addr);\n\n let test_addr = u32::from(ip);\n\n (base_addr ^ test_addr).leading_zeros() >= u32::from(self.bits)\n\n }\n\n\n\n /// Split a range into `num` sub-ranges\n\n ///\n\n /// # Panics\n\n ///\n\n /// If the range is too small to be split up that much.\n\n pub fn split(self, num: u32) -> Vec<Self> {\n\n let mut ret = Vec::with_capacity(num as usize);\n", "file_path": "core/src/range.rs", "rank": 35, "score": 25878.037050681025 }, { "content": " ///\n\n /// # Example\n\n ///\n\n /// Create the subnet 192.168.0.0/24 with `Ipv4Range::new(\"192.168.0.0\".parse().unwrap(), 24)`\n\n pub fn new(addr: Ipv4Addr, bits: u8) -> Self {\n\n let mask = !((!0u32).checked_shr(u32::from(bits)).unwrap_or(0));\n\n Ipv4Range {\n\n addr: Ipv4Addr::from(u32::from(addr) & mask),\n\n bits,\n\n }\n\n }\n\n\n\n /// Return the entire IPv4 range, eg. 0.0.0.0/0\n\n pub fn global() -> Self {\n\n Ipv4Range {\n\n addr: Ipv4Addr::new(0, 0, 0, 0),\n\n bits: 0,\n\n }\n\n }\n\n\n", "file_path": "core/src/range.rs", "rank": 36, "score": 25876.72204852255 }, { "content": " /// Returns the local network subnet 10.0.0.0/8\n\n pub fn local_subnet_10() -> Self {\n\n Ipv4Range {\n\n addr: Ipv4Addr::new(10, 0, 0, 0),\n\n bits: 8,\n\n }\n\n }\n\n\n\n /// Returns a local network subnet 172.(16 | x).0.0/16 where x is a 4-bit number given by\n\n /// `block`\n\n ///\n\n /// # Panics\n\n ///\n\n /// If `block & 0xf0 != 0`\n\n pub fn local_subnet_172(block: u8) -> Self {\n\n assert!(block < 16);\n\n Ipv4Range {\n\n addr: Ipv4Addr::new(172, 16 | block, 0, 0),\n\n bits: 16,\n\n }\n", "file_path": "core/src/range.rs", "rank": 37, "score": 25876.020351838444 }, { "content": " ret.push(Ipv4Range { addr: ip, bits: 0 });\n\n if ret.len() == num as usize {\n\n break;\n\n }\n\n n += 1;\n\n }\n\n let extra_bits = (32 - n.leading_zeros()) as u8;\n\n let bits = self.bits + extra_bits;\n\n for range in &mut ret {\n\n range.bits = bits;\n\n }\n\n ret\n\n }\n\n}\n\n\n\n/// Errors returned by `SubnetV*::from_str`\n\n#[derive(Debug, Error)]\n\npub enum IpRangeParseError {\n\n /// Missing '/' delimiter\n\n #[error(\"missing '/' delimiter\")]\n", "file_path": "core/src/range.rs", "rank": 38, "score": 25874.77005769841 }, { "content": " }\n\n\n\n /// Returns the local subnet 192.168.x.0/24 where x is given by `block`.\n\n pub fn local_subnet_192(block: u8) -> Self {\n\n Ipv4Range {\n\n addr: Ipv4Addr::new(192, 168, block, 0),\n\n bits: 24,\n\n }\n\n }\n\n\n\n /// Returns a random local network subnet from one of the ranges 10.0.0.0, 172.16.0.0 or\n\n /// 192.168.0.0\n\n pub fn random_local_subnet() -> Self {\n\n match rand::random::<u8>() % 3 {\n\n 0 => Ipv4Range::local_subnet_10(),\n\n 1 => Ipv4Range::local_subnet_172(rand::random::<u8>() & 0x0f),\n\n 2 => Ipv4Range::local_subnet_192(rand::random()),\n\n _ => unreachable!(),\n\n }\n\n }\n", "file_path": "core/src/range.rs", "rank": 39, "score": 25874.623870927247 }, { "content": " }\n\n\n\n /// Get a random IP address from the range which is not the base address or the default\n\n /// for the gateway address.\n\n pub fn random_client_addr(&self) -> Ipv4Addr {\n\n let mask = !0 >> self.bits;\n\n assert!(mask > 1);\n\n let class = if self.bits == 0 {\n\n Ipv4AddrClass::Global\n\n } else {\n\n self.addr.class()\n\n };\n\n\n\n loop {\n\n let x = rand::random::<u32>() & mask;\n\n if x < 2 {\n\n continue;\n\n }\n\n let addr = Ipv4Addr::from(u32::from(self.addr) | x);\n\n if class != addr.class() {\n", "file_path": "core/src/range.rs", "rank": 40, "score": 25873.162830620673 }, { "content": " Self::new(addr, 32)\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 it_creates_address_range() {\n\n let addrs = Ipv4Range::new(\"1.2.3.0\".parse().unwrap(), 24);\n\n\n\n assert!(addrs.contains(\"1.2.3.5\".parse().unwrap()));\n\n assert!(addrs.contains(\"1.2.3.255\".parse().unwrap()));\n\n assert!(!addrs.contains(\"1.2.4.5\".parse().unwrap()));\n\n }\n\n}\n", "file_path": "core/src/range.rs", "rank": 41, "score": 25872.897904914826 }, { "content": " None => return Err(IpRangeParseError::MissingDelimiter),\n\n };\n\n match split.next() {\n\n Some(..) => return Err(IpRangeParseError::ExtraDelimiter),\n\n None => (),\n\n };\n\n let addr = match Ipv4Addr::from_str(addr) {\n\n Ok(addr) => addr,\n\n Err(e) => return Err(IpRangeParseError::ParseAddr(e)),\n\n };\n\n let bits = match u8::from_str(bits) {\n\n Ok(bits) => bits,\n\n Err(e) => return Err(IpRangeParseError::ParseNetmaskPrefixLength(e)),\n\n };\n\n Ok(Ipv4Range::new(addr, bits))\n\n }\n\n}\n\n\n\nimpl From<Ipv4Addr> for Ipv4Range {\n\n fn from(addr: Ipv4Addr) -> Self {\n", "file_path": "core/src/range.rs", "rank": 42, "score": 25872.23752171751 }, { "content": "\n\n /// Get the netmask as an IP address\n\n pub fn netmask(&self) -> Ipv4Addr {\n\n Ipv4Addr::from(!((!0u32).checked_shr(u32::from(self.bits)).unwrap_or(0)))\n\n }\n\n\n\n /// Get the number of netmask prefix bits\n\n pub fn netmask_prefix_length(&self) -> u8 {\n\n self.bits\n\n }\n\n\n\n /// Get the base address of the range, ie. the lowest IP address which is part of the range.\n\n pub fn base_addr(&self) -> Ipv4Addr {\n\n self.addr\n\n }\n\n\n\n /// Get a default IP address for the range's gateway. This is one higher than the base address\n\n /// of the range. eg. for 10.0.0.0/8, the default address for the gateway will be 10.0.0.1\n\n pub fn gateway_addr(&self) -> Ipv4Addr {\n\n Ipv4Addr::from(u32::from(self.addr) | 1)\n", "file_path": "core/src/range.rs", "rank": 43, "score": 25871.569054549367 }, { "content": " MissingDelimiter,\n\n /// More than one '/' delimiter\n\n #[error(\"more than one '/' delimiter\")]\n\n ExtraDelimiter,\n\n /// error parsing IP address\n\n #[error(\"error parsing IP address: {0}\")]\n\n ParseAddr(std::net::AddrParseError),\n\n /// error parsing netmask prefix length\n\n #[error(\"error parsing netmask prefix length: {0}\")]\n\n ParseNetmaskPrefixLength(std::num::ParseIntError),\n\n}\n\n\n\nimpl FromStr for Ipv4Range {\n\n type Err = IpRangeParseError;\n\n\n\n fn from_str(s: &str) -> Result<Ipv4Range, IpRangeParseError> {\n\n let mut split = s.split('/');\n\n let addr = split.next().unwrap();\n\n let bits = match split.next() {\n\n Some(bits) => bits,\n", "file_path": "core/src/range.rs", "rank": 44, "score": 25870.634197084903 }, { "content": " let mut n = 0u32;\n\n let class = if self.bits == 0 {\n\n Ipv4AddrClass::Global\n\n } else {\n\n self.addr.class()\n\n };\n\n loop {\n\n let mut n_reversed = 0;\n\n for i in 0..32 {\n\n if n & (1 << i) != 0 {\n\n n_reversed |= 0x8000_0000u32 >> i;\n\n }\n\n }\n\n let base_addr = u32::from(self.addr);\n\n let ip = base_addr | (n_reversed >> self.bits);\n\n let ip = Ipv4Addr::from(ip);\n\n if class != ip.class() {\n\n n += 1;\n\n continue;\n\n }\n", "file_path": "core/src/range.rs", "rank": 45, "score": 25868.752117206317 }, { "content": " let (mut reader, mut writer) = iface.split();\n\n\n\n let reader_task = async move {\n\n loop {\n\n let mut buf = [0; libc::ETH_FRAME_LEN as usize];\n\n let n = reader.read(&mut buf).await.unwrap();\n\n if n == 0 {\n\n break;\n\n }\n\n // drop ipv6 packets\n\n if buf[0] >> 4 != 4 {\n\n continue;\n\n }\n\n log::debug!(\"machine {}: sending packet\", addr);\n\n if tx.send(buf[..n].to_vec()).await.is_err() {\n\n break;\n\n }\n\n }\n\n };\n\n\n", "file_path": "machine/src/lib.rs", "rank": 46, "score": 25033.86873236997 }, { "content": "//! Small embeddable network simulator.\n\n\n\nmacro_rules! errno {\n\n ($res:expr) => {{\n\n let res = $res;\n\n if res < 0 {\n\n Err(io::Error::last_os_error())\n\n } else {\n\n Ok(res)\n\n }\n\n }};\n\n}\n\n\n\npub mod iface;\n\npub mod namespace;\n\n#[cfg(feature = \"tokio2\")]\n\npub mod tokio;\n\n\n\nuse futures::future::Future;\n\nuse futures::io::{AsyncReadExt, AsyncWriteExt};\n\nuse futures::sink::SinkExt;\n\nuse futures::stream::StreamExt;\n\nuse netsim_embed_core::{Ipv4Range, Plug};\n\nuse std::net::Ipv4Addr;\n\nuse std::thread;\n\n\n\n/// Spawns a thread in a new network namespace and configures a TUN interface that sends and\n\n/// receives IP packets from the tx/rx channels and runs some UDP/TCP networking code in task.\n", "file_path": "machine/src/lib.rs", "rank": 47, "score": 25031.17281443618 }, { "content": " impl ifreq {\n\n pub fn new(name: &CStr) -> Self {\n\n unsafe {\n\n let mut req: Self = std::mem::zeroed();\n\n std::ptr::copy_nonoverlapping(\n\n name.as_ptr(),\n\n req.ifr_ifrn.ifrn_name.as_mut_ptr() as *mut _,\n\n name.to_bytes().len(),\n\n );\n\n req\n\n }\n\n }\n\n\n\n pub fn set_ifru_addr(&mut self, ipv4_addr: Ipv4Addr) {\n\n unsafe {\n\n let addr = &mut self.ifr_ifru.ifru_addr as *mut libc::sockaddr;\n\n let addr = &mut *(addr as *mut libc::sockaddr_in);\n\n addr.sin_family = libc::AF_INET as libc::sa_family_t;\n\n addr.sin_port = 0;\n\n addr.sin_addr.s_addr = u32::from(ipv4_addr).to_be();\n", "file_path": "machine/src/iface.rs", "rank": 48, "score": 25029.63768613295 }, { "content": "use crate::iface::Iface;\n\nuse futures::io::{AsyncRead, AsyncWrite};\n\nuse std::io;\n\nuse std::os::unix::io::AsRawFd;\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\nuse tokio::io::{AsyncRead as _, AsyncWrite as _, PollEvented};\n\n\n\npub struct TokioFd(PollEvented<Iface>);\n\n\n\nimpl TokioFd {\n\n pub fn new(iface: Iface) -> Result<Self, io::Error> {\n\n let fd = iface.as_raw_fd();\n\n\n\n let flags = unsafe { errno!(libc::fcntl(fd, libc::F_GETFL, 0))? };\n\n\n\n unsafe { errno!(libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK))? };\n\n\n\n Ok(Self(PollEvented::new(iface)?))\n\n }\n", "file_path": "machine/src/tokio.rs", "rank": 49, "score": 25028.41585028771 }, { "content": " let writer_task = async move {\n\n loop {\n\n if let Some(packet) = rx.next().await {\n\n log::debug!(\"machine {}: received packet\", addr);\n\n let n = writer.write(&packet).await.unwrap();\n\n if n == 0 {\n\n break;\n\n }\n\n } else {\n\n break;\n\n }\n\n }\n\n };\n\n\n\n (reader_task, writer_task)\n\n };\n\n\n\n #[cfg(not(feature = \"tokio2\"))]\n\n let result = smol::run(async move {\n\n let (reader_task, writer_task) = create_tun_iface();\n", "file_path": "machine/src/lib.rs", "rank": 50, "score": 25028.086111685516 }, { "content": "use netsim_embed_core::Ipv4Route;\n\nuse std::ffi::{CStr, CString};\n\nuse std::io::{self, Read, Write};\n\nuse std::mem;\n\nuse std::net::Ipv4Addr;\n\nuse std::os::unix::io::{AsRawFd, RawFd};\n\n\n\nmod ioctl {\n\n use ioctl_sys::*;\n\n use libc::*;\n\n use std::ffi::CStr;\n\n use std::net::Ipv4Addr;\n\n\n\n #[repr(C)]\n\n #[derive(Clone, Copy)]\n\n pub struct ifreq {\n\n pub ifr_ifrn: __ifreq_ifr_ifrn,\n\n pub ifr_ifru: __ifreq_ifr_ifru,\n\n }\n\n\n", "file_path": "machine/src/iface.rs", "rank": 51, "score": 25027.55826614123 }, { "content": "\n\n Ok(Self { name, fd })\n\n }\n\n }\n\n\n\n /// Returns the name of the iface.\n\n pub fn name(&self) -> &CStr {\n\n &self.name\n\n }\n\n\n\n /// Receives a packet.\n\n pub fn recv(&self, buf: &mut [u8]) -> Result<usize, io::Error> {\n\n Ok(unsafe {\n\n errno!(libc::read(\n\n self.as_raw_fd(),\n\n buf.as_mut_ptr() as *mut _,\n\n buf.len()\n\n ))? as _\n\n })\n\n }\n", "file_path": "machine/src/iface.rs", "rank": 52, "score": 25026.64224865301 }, { "content": " }\n\n}\n\n\n\nimpl Read for Iface {\n\n fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n\n self.recv(buf)\n\n }\n\n}\n\n\n\nimpl Write for Iface {\n\n fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n\n self.send(buf)\n\n }\n\n\n\n fn flush(&mut self) -> io::Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Iface {\n", "file_path": "machine/src/iface.rs", "rank": 53, "score": 25026.556878927746 }, { "content": " pub ifru_mtu: c_int,\n\n pub ifru: ifmap,\n\n pub ifru_slave: [c_char; IFNAMSIZ],\n\n pub ifru_newname: [c_char; IFNAMSIZ],\n\n pub ifru_data: *mut c_void,\n\n }\n\n\n\n #[repr(C)]\n\n #[derive(Debug, Clone, Copy)]\n\n pub struct ifmap {\n\n pub mem_start: c_ulong,\n\n pub mem_end: c_ulong,\n\n pub base_addr: c_ushort,\n\n pub irq: c_uchar,\n\n pub dma: c_uchar,\n\n pub port: c_uchar,\n\n }\n\n\n\n ioctl!(bad read siocgifflags with 0x8913; ifreq);\n\n ioctl!(bad write siocsifflags with 0x8914; ifreq);\n", "file_path": "machine/src/iface.rs", "rank": 54, "score": 25025.978729443214 }, { "content": " Pin::new(&mut self.0).poll_read(cx, buf)\n\n }\n\n}\n\n\n\nimpl AsyncWrite for TokioFd {\n\n fn poll_write(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context,\n\n buf: &[u8],\n\n ) -> Poll<Result<usize, io::Error>> {\n\n Pin::new(&mut self.0).poll_write(cx, buf)\n\n }\n\n\n\n fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {\n\n Poll::Ready(Ok(()))\n\n }\n\n\n\n fn poll_close(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<Result<(), io::Error>> {\n\n Poll::Ready(Ok(()))\n\n }\n\n}\n", "file_path": "machine/src/tokio.rs", "rank": 55, "score": 25025.75930877242 }, { "content": "\n\n /// Sends a packet.\n\n pub fn send(&self, buf: &[u8]) -> Result<usize, io::Error> {\n\n Ok(unsafe {\n\n errno!(libc::write(\n\n self.as_raw_fd(),\n\n buf.as_ptr() as *mut _,\n\n buf.len()\n\n ))? as _\n\n })\n\n }\n\n\n\n /// Set an interface IPv4 address and netmask\n\n pub fn set_ipv4_addr(&self, ipv4_addr: Ipv4Addr, netmask_bits: u8) -> Result<(), io::Error> {\n\n unsafe {\n\n let fd = errno!(libc::socket(\n\n libc::AF_INET as i32,\n\n libc::SOCK_DGRAM as i32,\n\n 0\n\n ))?;\n", "file_path": "machine/src/iface.rs", "rank": 56, "score": 25025.414834905027 }, { "content": " }\n\n }\n\n }\n\n\n\n #[repr(C)]\n\n #[derive(Clone, Copy)]\n\n pub union __ifreq_ifr_ifrn {\n\n pub ifrn_name: [c_char; IFNAMSIZ],\n\n }\n\n\n\n #[repr(C)]\n\n #[derive(Clone, Copy)]\n\n pub union __ifreq_ifr_ifru {\n\n pub ifru_addr: sockaddr,\n\n pub ifru_dstaddr: sockaddr,\n\n pub ifru_broadaddr: sockaddr,\n\n pub ifru_netmask: sockaddr,\n\n pub ifru_hwaddr: sockaddr,\n\n pub ifru_flags: c_short,\n\n pub ifru_ivalue: c_int,\n", "file_path": "machine/src/iface.rs", "rank": 57, "score": 25024.95323001603 }, { "content": " smol::Task::spawn(reader_task).detach();\n\n smol::Task::spawn(writer_task).detach();\n\n task.await\n\n });\n\n #[cfg(feature = \"tokio2\")]\n\n let result = {\n\n let mut rt = ::tokio::runtime::Builder::new()\n\n .threaded_scheduler()\n\n .enable_all()\n\n .build()\n\n .unwrap();\n\n rt.block_on(async move {\n\n let (reader_task, writer_task) = create_tun_iface();\n\n ::tokio::task::spawn(reader_task);\n\n ::tokio::task::spawn(writer_task);\n\n task.await\n\n })\n\n };\n\n\n\n result\n\n })\n\n}\n", "file_path": "machine/src/lib.rs", "rank": 58, "score": 25024.535588007566 }, { "content": " opts: mio::PollOpt,\n\n ) -> io::Result<()> {\n\n let fd = self.as_raw_fd();\n\n let evented_fd = mio::unix::EventedFd(&fd);\n\n evented_fd.reregister(poll, token, interest, opts)\n\n }\n\n\n\n fn deregister(&self, poll: &mio::Poll) -> io::Result<()> {\n\n let fd = self.as_raw_fd();\n\n let evented_fd = mio::unix::EventedFd(&fd);\n\n evented_fd.deregister(poll)\n\n }\n\n}\n\n\n\nimpl AsyncRead for TokioFd {\n\n fn poll_read(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context,\n\n buf: &mut [u8],\n\n ) -> Poll<Result<usize, io::Error>> {\n", "file_path": "machine/src/tokio.rs", "rank": 59, "score": 25024.015434777397 }, { "content": " ioctl!(bad write siocsifaddr with 0x8916; ifreq);\n\n ioctl!(bad write siocsifnetmask with 0x891c; ifreq);\n\n ioctl!(write tunsetiff with b'T', 202; libc::c_int);\n\n}\n\n\n\n/// See: https://www.kernel.org/doc/Documentation/networking/tuntap.txt\n\npub struct Iface {\n\n name: CString,\n\n fd: RawFd,\n\n}\n\n\n\nimpl AsRawFd for Iface {\n\n fn as_raw_fd(&self) -> RawFd {\n\n self.fd\n\n }\n\n}\n\n\n\nimpl Drop for Iface {\n\n fn drop(&mut self) {\n\n let _ = unsafe { libc::close(self.as_raw_fd()) };\n", "file_path": "machine/src/iface.rs", "rank": 60, "score": 25023.990935779784 }, { "content": " /// Creates a new virtual network interface.\n\n pub fn new() -> Result<Self, io::Error> {\n\n unsafe {\n\n let fd = loop {\n\n match errno!(libc::open(\n\n b\"/dev/net/tun\\0\".as_ptr() as *const _,\n\n libc::O_RDWR\n\n )) {\n\n Ok(fd) => break fd,\n\n Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,\n\n Err(err) => return Err(err),\n\n }\n\n };\n\n\n\n let mut req: ioctl::ifreq = mem::zeroed();\n\n req.ifr_ifru.ifru_flags = libc::IFF_TUN as i16 | libc::IFF_NO_PI as i16;\n\n\n\n errno!(ioctl::tunsetiff(fd, &mut req as *mut _ as *mut _))?;\n\n\n\n let name = CStr::from_ptr(&req.ifr_ifrn.ifrn_name as *const _).to_owned();\n", "file_path": "machine/src/iface.rs", "rank": 61, "score": 25023.185684331194 }, { "content": " let rt_dst = &mut *(&mut rtentry.rt_dst as *mut _ as *mut libc::sockaddr_in);\n\n rt_dst.sin_family = libc::AF_INET as u16;\n\n rt_dst.sin_addr = libc::in_addr {\n\n s_addr: u32::from(route.dest().base_addr()).to_be(),\n\n };\n\n\n\n let rt_genmask = &mut *(&mut rtentry.rt_genmask as *mut _ as *mut libc::sockaddr_in);\n\n rt_genmask.sin_family = libc::AF_INET as u16;\n\n rt_genmask.sin_addr = libc::in_addr {\n\n s_addr: u32::from(route.dest().netmask()).to_be(),\n\n };\n\n\n\n rtentry.rt_flags = libc::RTF_UP as u16;\n\n\n\n if let Some(gateway_addr) = route.gateway() {\n\n let rt_gateway =\n\n &mut *(&mut rtentry.rt_gateway as *mut _ as *mut libc::sockaddr_in);\n\n rt_gateway.sin_family = libc::AF_INET as u16;\n\n rt_gateway.sin_addr = libc::in_addr {\n\n s_addr: u32::from(gateway_addr).to_be(),\n", "file_path": "machine/src/iface.rs", "rank": 62, "score": 25021.220444864764 }, { "content": " let mut req = ioctl::ifreq::new(self.name());\n\n req.set_ifru_addr(ipv4_addr);\n\n\n\n if let Err(err) = errno!(ioctl::siocsifaddr(fd, &req)) {\n\n let _ = libc::close(fd);\n\n return Err(err);\n\n }\n\n\n\n let netmask = Ipv4Addr::from(!((!0u32) >> netmask_bits));\n\n req.set_ifru_addr(netmask);\n\n\n\n if let Err(err) = errno!(ioctl::siocsifnetmask(fd, &req)) {\n\n let _ = libc::close(fd);\n\n return Err(err);\n\n }\n\n\n\n let _ = libc::close(fd);\n\n Ok(())\n\n }\n\n }\n", "file_path": "machine/src/iface.rs", "rank": 63, "score": 25019.225553461278 }, { "content": "\n\n /// Put an interface up.\n\n pub fn put_up(&self) -> Result<(), io::Error> {\n\n unsafe {\n\n let fd = errno!(libc::socket(\n\n libc::AF_INET as i32,\n\n libc::SOCK_DGRAM as i32,\n\n 0\n\n ))?;\n\n let mut req = ioctl::ifreq::new(self.name());\n\n\n\n if let Err(err) = errno!(ioctl::siocgifflags(fd, &mut req)) {\n\n let _ = libc::close(fd);\n\n return Err(err);\n\n }\n\n\n\n req.ifr_ifru.ifru_flags |= libc::IFF_UP as i16 | libc::IFF_RUNNING as i16;\n\n\n\n if let Err(err) = errno!(ioctl::siocsifflags(fd, &req)) {\n\n let _ = libc::close(fd);\n", "file_path": "machine/src/iface.rs", "rank": 64, "score": 25018.68949251296 }, { "content": "use std::fs::File;\n\nuse std::io::{self, Write};\n\n\n", "file_path": "machine/src/namespace.rs", "rank": 65, "score": 25018.679058388552 }, { "content": " return Err(err);\n\n }\n\n\n\n let _ = libc::close(fd);\n\n Ok(())\n\n }\n\n }\n\n\n\n /// Adds an ipv4 route.\n\n pub fn add_ipv4_route(&self, route: Ipv4Route) -> Result<(), io::Error> {\n\n unsafe {\n\n let fd = errno!(libc::socket(\n\n libc::PF_INET as i32,\n\n libc::SOCK_DGRAM as i32,\n\n libc::IPPROTO_IP as i32,\n\n ))\n\n .unwrap();\n\n\n\n let mut rtentry: libc::rtentry = mem::zeroed();\n\n\n", "file_path": "machine/src/iface.rs", "rank": 66, "score": 25018.49503616091 }, { "content": " };\n\n\n\n rtentry.rt_flags |= libc::RTF_GATEWAY as u16;\n\n }\n\n\n\n rtentry.rt_dev = self.name.as_ptr() as *mut _;\n\n\n\n if let Err(err) = errno!(libc::ioctl(fd, u64::from(libc::SIOCADDRT), &rtentry)) {\n\n let _ = libc::close(fd);\n\n return Err(err).unwrap();\n\n }\n\n\n\n Ok(())\n\n }\n\n }\n\n}\n", "file_path": "machine/src/iface.rs", "rank": 67, "score": 25017.067429527382 }, { "content": "}\n\n\n\nimpl mio::Evented for Iface {\n\n fn register(\n\n &self,\n\n poll: &mio::Poll,\n\n token: mio::Token,\n\n interest: mio::Ready,\n\n opts: mio::PollOpt,\n\n ) -> io::Result<()> {\n\n let fd = self.as_raw_fd();\n\n let evented_fd = mio::unix::EventedFd(&fd);\n\n evented_fd.register(poll, token, interest, opts)\n\n }\n\n\n\n fn reregister(\n\n &self,\n\n poll: &mio::Poll,\n\n token: mio::Token,\n\n interest: mio::Ready,\n", "file_path": "machine/src/tokio.rs", "rank": 68, "score": 25016.89567131716 }, { "content": "use pnet_packet::ip::IpNextHeaderProtocols;\n\nuse pnet_packet::ipv4::{self, Ipv4Packet, MutableIpv4Packet};\n\nuse pnet_packet::tcp::{self, MutableTcpPacket, TcpPacket};\n\nuse pnet_packet::udp::{self, MutableUdpPacket, UdpPacket};\n\nuse pnet_packet::{MutablePacket, Packet as _};\n\nuse std::net::SocketAddrV4;\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub enum Protocol {\n\n Udp,\n\n Tcp,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Packet<'a> {\n\n protocol: Protocol,\n\n bytes: &'a mut [u8],\n\n}\n\n\n\nimpl<'a> Packet<'a> {\n", "file_path": "nat/src/packet.rs", "rank": 69, "score": 24691.972285056756 }, { "content": "mod nat;\n\nmod packet;\n\nmod port_allocator;\n\nmod port_map;\n\n\n\npub use nat::Ipv4Nat;\n\npub use port_allocator::{PortAllocator, RandomPortAllocator, SequentialPortAllocator};\n", "file_path": "nat/src/lib.rs", "rank": 70, "score": 24687.614132068014 }, { "content": " };\n\n SocketAddrV4::new(ip, port.into())\n\n }\n\n\n\n pub fn get_ttl(&self) -> u8 {\n\n Ipv4Packet::new(self.bytes).unwrap().get_ttl()\n\n }\n\n\n\n pub fn protocol(&self) -> Protocol {\n\n self.protocol\n\n }\n\n\n\n pub fn set_source(&mut self, addr: SocketAddrV4) {\n\n let mut packet = MutableIpv4Packet::new(self.bytes).unwrap();\n\n packet.set_source(*addr.ip());\n\n match self.protocol {\n\n Protocol::Udp => {\n\n let mut udp = MutableUdpPacket::new(packet.payload_mut()).unwrap();\n\n udp.set_source(addr.port().into());\n\n }\n", "file_path": "nat/src/packet.rs", "rank": 71, "score": 24686.449889966876 }, { "content": " Protocol::Tcp => {\n\n let mut tcp = MutableTcpPacket::new(packet.payload_mut()).unwrap();\n\n tcp.set_source(addr.port().into());\n\n }\n\n }\n\n }\n\n\n\n pub fn set_destination(&mut self, addr: SocketAddrV4) {\n\n let mut packet = MutableIpv4Packet::new(self.bytes).unwrap();\n\n packet.set_destination(*addr.ip());\n\n match self.protocol {\n\n Protocol::Udp => {\n\n let mut udp = MutableUdpPacket::new(packet.payload_mut()).unwrap();\n\n udp.set_destination(addr.port().into());\n\n }\n\n Protocol::Tcp => {\n\n let mut tcp = MutableTcpPacket::new(packet.payload_mut()).unwrap();\n\n tcp.set_destination(addr.port().into());\n\n }\n\n }\n", "file_path": "nat/src/packet.rs", "rank": 72, "score": 24685.657165393677 }, { "content": " pub fn new(bytes: &'a mut [u8]) -> Option<Self> {\n\n let packet = if let Some(packet) = Ipv4Packet::new(bytes) {\n\n packet\n\n } else {\n\n return None;\n\n };\n\n let protocol = match packet.get_next_level_protocol() {\n\n IpNextHeaderProtocols::Udp => {\n\n if UdpPacket::new(packet.payload()).is_none() {\n\n return None;\n\n }\n\n Protocol::Udp\n\n }\n\n IpNextHeaderProtocols::Tcp => {\n\n if TcpPacket::new(packet.payload()).is_none() {\n\n return None;\n\n }\n\n Protocol::Tcp\n\n }\n\n _ => return None,\n", "file_path": "nat/src/packet.rs", "rank": 73, "score": 24685.26192833242 }, { "content": " };\n\n Some(Self { protocol, bytes })\n\n }\n\n\n\n pub fn get_source(&self) -> SocketAddrV4 {\n\n let packet = Ipv4Packet::new(self.bytes).unwrap();\n\n let ip = packet.get_source();\n\n let port = match self.protocol {\n\n Protocol::Udp => UdpPacket::new(packet.payload()).unwrap().get_source(),\n\n Protocol::Tcp => TcpPacket::new(packet.payload()).unwrap().get_source(),\n\n };\n\n SocketAddrV4::new(ip, port.into())\n\n }\n\n\n\n pub fn get_destination(&self) -> SocketAddrV4 {\n\n let packet = Ipv4Packet::new(self.bytes).unwrap();\n\n let ip = packet.get_destination();\n\n let port = match self.protocol {\n\n Protocol::Udp => UdpPacket::new(packet.payload()).unwrap().get_destination(),\n\n Protocol::Tcp => TcpPacket::new(packet.payload()).unwrap().get_destination(),\n", "file_path": "nat/src/packet.rs", "rank": 74, "score": 24683.644315705435 }, { "content": " }\n\n\n\n pub fn set_ttl(&mut self, ttl: u8) {\n\n MutableIpv4Packet::new(self.bytes).unwrap().set_ttl(ttl)\n\n }\n\n\n\n pub fn set_checksum(&mut self) {\n\n let mut packet = MutableIpv4Packet::new(self.bytes).unwrap();\n\n let source = packet.get_source();\n\n let dest = packet.get_destination();\n\n packet.set_checksum(ipv4::checksum(&packet.to_immutable()));\n\n match self.protocol {\n\n Protocol::Udp => {\n\n let mut udp = MutableUdpPacket::new(packet.payload_mut()).unwrap();\n\n udp.set_checksum(udp::ipv4_checksum(&udp.to_immutable(), &source, &dest));\n\n }\n\n Protocol::Tcp => {\n\n let mut tcp = MutableTcpPacket::new(packet.payload_mut()).unwrap();\n\n tcp.set_checksum(tcp::ipv4_checksum(&tcp.to_immutable(), &source, &dest));\n\n }\n\n }\n\n }\n\n}\n", "file_path": "nat/src/packet.rs", "rank": 75, "score": 24683.345991974333 }, { "content": "use crate::port_allocator::{PortAllocator, SequentialPortAllocator};\n\nuse std::collections::hash_map::{Entry, HashMap};\n\nuse std::net::SocketAddrV4;\n\n\n\n#[derive(Debug)]\n\npub struct PortMap {\n\n map_out: HashMap<SocketAddrV4, u16>,\n\n map_in: HashMap<u16, SocketAddrV4>,\n\n allowed_endpoints: Option<HashMap<u16, SocketAddrV4>>,\n\n symmetric_map: Option<SymmetricMap>,\n\n port_allocator: Box<dyn PortAllocator>,\n\n}\n\n\n\nimpl Default for PortMap {\n\n fn default() -> Self {\n\n Self {\n\n map_out: Default::default(),\n\n map_in: Default::default(),\n\n allowed_endpoints: Default::default(),\n\n symmetric_map: Default::default(),\n", "file_path": "nat/src/port_map.rs", "rank": 76, "score": 23432.80402889213 }, { "content": "\n\n pub fn set_restrict_endpoints(&mut self, restrict_endpoints: bool) {\n\n if restrict_endpoints {\n\n self.allowed_endpoints = Some(Default::default());\n\n } else {\n\n self.allowed_endpoints = None;\n\n }\n\n }\n\n\n\n pub fn set_symmetric(&mut self, symmetric: bool) {\n\n if symmetric {\n\n self.symmetric_map = Some(Default::default());\n\n } else {\n\n self.symmetric_map = None;\n\n }\n\n }\n\n\n\n pub fn get_inbound_addr(&self, remote_addr: SocketAddrV4, port: u16) -> Option<SocketAddrV4> {\n\n if let Some(ref allowed_endpoints) = self.allowed_endpoints {\n\n if !allowed_endpoints\n", "file_path": "nat/src/port_map.rs", "rank": 77, "score": 23432.00076561589 }, { "content": " port_allocator: Box::new(SequentialPortAllocator::default()),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct SymmetricMap {\n\n map_out: HashMap<(SocketAddrV4, SocketAddrV4), u16>,\n\n map_in: HashMap<u16, (SocketAddrV4, SocketAddrV4)>,\n\n}\n\n\n\nimpl PortMap {\n\n pub fn forward_port(&mut self, port: u16, local_addr: SocketAddrV4) {\n\n self.map_out.insert(local_addr, port);\n\n self.map_in.insert(port, local_addr);\n\n }\n\n\n\n pub fn set_port_allocator<T: PortAllocator + 'static>(&mut self, port_allocator: T) {\n\n self.port_allocator = Box::new(port_allocator);\n\n }\n", "file_path": "nat/src/port_map.rs", "rank": 78, "score": 23428.55084907328 }, { "content": "#[derive(Clone, Debug, Default)]\n\npub struct RandomPortAllocator;\n\n\n\nimpl PortAllocator for RandomPortAllocator {\n\n fn next_port(&mut self, _local_endpoint: SocketAddrV4) -> u16 {\n\n loop {\n\n let port = rand::random();\n\n if port >= 1000 {\n\n return port;\n\n }\n\n }\n\n }\n\n}\n", "file_path": "nat/src/port_allocator.rs", "rank": 79, "score": 23426.763331033282 }, { "content": " }\n\n }\n\n None\n\n }\n\n\n\n pub fn map_port(&mut self, remote_addr: SocketAddrV4, source_addr: SocketAddrV4) -> u16 {\n\n let port = match self.map_out.entry(source_addr) {\n\n Entry::Occupied(oe) => *oe.get(),\n\n Entry::Vacant(ve) => {\n\n if let Some(ref mut symmetric_map) = self.symmetric_map {\n\n match symmetric_map.map_out.entry((source_addr, remote_addr)) {\n\n Entry::Occupied(oe) => *oe.get(),\n\n Entry::Vacant(ve) => {\n\n let port = loop {\n\n let port = self.port_allocator.next_port(source_addr);\n\n if self.map_in.contains_key(&port) {\n\n continue;\n\n }\n\n if symmetric_map.map_in.contains_key(&port) {\n\n continue;\n", "file_path": "nat/src/port_map.rs", "rank": 80, "score": 23423.365523868102 }, { "content": " .get(&port)\n\n .map(|allowed| *allowed == remote_addr)\n\n .unwrap_or(false)\n\n {\n\n log::trace!(\n\n \"NAT dropping packet from restricted address {}. allowed endpoints: {:?}\",\n\n remote_addr,\n\n allowed_endpoints\n\n );\n\n return None;\n\n }\n\n }\n\n if let Some(addr) = self.map_in.get(&port) {\n\n return Some(*addr);\n\n }\n\n if let Some(ref symmetric_map) = self.symmetric_map {\n\n if let Some(&(addr, allowed_remote_addr)) = symmetric_map.map_in.get(&port) {\n\n if allowed_remote_addr == remote_addr {\n\n return Some(addr);\n\n }\n", "file_path": "nat/src/port_map.rs", "rank": 81, "score": 23422.22127776209 }, { "content": "use std::collections::hash_map::{Entry, HashMap};\n\nuse std::net::SocketAddrV4;\n\n\n", "file_path": "nat/src/port_allocator.rs", "rank": 82, "score": 23419.90108275209 }, { "content": " }\n\n break port;\n\n };\n\n\n\n ve.insert(port);\n\n symmetric_map\n\n .map_in\n\n .insert(port, (source_addr, remote_addr));\n\n port\n\n }\n\n }\n\n } else {\n\n let port = loop {\n\n let port = self.port_allocator.next_port(source_addr);\n\n if self.map_in.contains_key(&port) {\n\n continue;\n\n }\n\n break port;\n\n };\n\n\n", "file_path": "nat/src/port_map.rs", "rank": 83, "score": 23419.192218162727 }, { "content": " ve.insert(port);\n\n self.map_in.insert(port, source_addr);\n\n port\n\n }\n\n }\n\n };\n\n if let Some(ref mut allowed_endpoints) = self.allowed_endpoints {\n\n allowed_endpoints.insert(port, remote_addr);\n\n }\n\n port\n\n }\n\n}\n", "file_path": "nat/src/port_map.rs", "rank": 84, "score": 23419.030629975667 }, { "content": " fn next_port(&mut self, local_endpoint: SocketAddrV4) -> u16 {\n\n match self.next_for_local_endpoint.entry(local_endpoint) {\n\n Entry::Occupied(mut entry) => {\n\n let port = *entry.get();\n\n *entry.get_mut() = entry.get().checked_add(1).unwrap_or(49152);\n\n port\n\n }\n\n Entry::Vacant(entry) => {\n\n let port = self.next_original_port;\n\n self.next_original_port = self.next_original_port.wrapping_add(16);\n\n if self.next_original_port < 49152 {\n\n self.next_original_port += 49153\n\n };\n\n entry.insert(port);\n\n port\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "nat/src/port_allocator.rs", "rank": 85, "score": 23418.236488336886 }, { "content": " let natconfig = NatConfig::default();\n\n //natconfig.hair_pinning = true;\n\n //natconfig.symmetric = true;\n\n let mut net = NetworkBuilder::new(Ipv4Range::global());\n\n net.spawn_machine(builder(\"boot\"));\n\n net.spawn_network(Some(natconfig), local1);\n\n net.spawn_network(Some(natconfig), local2);\n\n //net.spawn_machine(builder(\"local2\"));\n\n\n\n let mut net = net.spawn();\n\n let mut bootstrap = vec![];\n\n\n\n let m = net.machine(0);\n\n m.send(Command::Bootstrap(vec![])).await;\n\n if let Event::Bootstrapped(addr, peer_id) = m.recv().await.unwrap() {\n\n bootstrap.push((addr, peer_id));\n\n } else {\n\n unreachable!()\n\n }\n\n\n", "file_path": "examples/p2p.rs", "rank": 93, "score": 23.413164366592813 }, { "content": "impl From<Ipv4Addr> for Ipv4Route {\n\n fn from(addr: Ipv4Addr) -> Self {\n\n Self::new(addr.into(), None)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Plug {\n\n tx: mpsc::UnboundedSender<Vec<u8>>,\n\n rx: mpsc::UnboundedReceiver<Vec<u8>>,\n\n}\n\n\n\nimpl Plug {\n\n pub fn poll_incoming(&mut self, cx: &mut Context) -> Poll<Option<Vec<u8>>> {\n\n Pin::new(&mut self.rx).poll_next(cx)\n\n }\n\n\n\n pub fn unbounded_send(&mut self, packet: Vec<u8>) {\n\n let _ = self.tx.unbounded_send(packet);\n\n }\n", "file_path": "core/src/lib.rs", "rank": 94, "score": 22.858175226605965 }, { "content": "use futures::channel::mpsc;\n\nuse futures::stream::Stream;\n\nuse std::net::Ipv4Addr;\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\n\n\nmod addr;\n\nmod range;\n\n\n\npub use range::Ipv4Range;\n\n\n\n#[derive(Clone, Copy, Debug)]\n\npub struct Ipv4Route {\n\n dest: Ipv4Range,\n\n gateway: Option<Ipv4Addr>,\n\n}\n\n\n\nimpl Ipv4Route {\n\n /// Create a new route with the given destination and gateway.\n\n pub fn new(dest: Ipv4Range, gateway: Option<Ipv4Addr>) -> Self {\n", "file_path": "core/src/lib.rs", "rank": 95, "score": 20.03466344997078 }, { "content": "use futures::channel::mpsc;\n\nuse futures::sink::SinkExt;\n\nuse futures::stream::StreamExt;\n\nuse ipfs_embed::{Config, Store, Multiaddr, PeerId};\n\nuse libipld::cid::{Cid, Codec};\n\nuse libipld::multihash::Sha2_256;\n\nuse libipld::store::{ReadonlyStore, Store as _, Visibility};\n\nuse netsim_embed::{run, Ipv4Range, NatConfig, NetworkBuilder};\n\nuse tempdir::TempDir;\n\nuse std::time::Duration;\n\n\n\n#[derive(Debug, Eq, PartialEq)]\n\npub enum Command {\n\n Bootstrap(Vec<(Multiaddr, PeerId)>),\n\n Insert(Cid, Vec<u8>),\n\n Get(Cid),\n\n}\n\n\n\nimpl Command {\n\n pub fn insert(bytes: &[u8]) -> Self {\n", "file_path": "examples/p2p.rs", "rank": 96, "score": 17.1061590407096 }, { "content": " let socket = smol::Async::<UdpSocket>::bind(\"0.0.0.0:0\").unwrap();\n\n socket\n\n .send_to(b\"ping\", SocketAddrV4::new(addr, 3000))\n\n .await\n\n .unwrap();\n\n\n\n let mut buf = [0u8; 11];\n\n let (len, _addr) = socket.recv_from(&mut buf).await.unwrap();\n\n if &buf[..len] == b\"pong\" {\n\n println!(\"received pong\");\n\n events.send(()).await.unwrap();\n\n }\n\n },\n\n );\n\n\n\n net.spawn_network(Some(NatConfig::default()), local);\n\n net.spawn().subnet(0).machine(0).recv().await;\n\n });\n\n}\n", "file_path": "examples/ping_pong_udp.rs", "rank": 97, "score": 15.936523018546405 }, { "content": " Self { dest, gateway }\n\n }\n\n\n\n /// Returns the destination IP range of the route.\n\n pub fn dest(&self) -> Ipv4Range {\n\n self.dest\n\n }\n\n\n\n /// Returns the route's gateway (if ayn).\n\n pub fn gateway(&self) -> Option<Ipv4Addr> {\n\n self.gateway\n\n }\n\n}\n\n\n\nimpl From<Ipv4Range> for Ipv4Route {\n\n fn from(range: Ipv4Range) -> Self {\n\n Self::new(range, None)\n\n }\n\n}\n\n\n", "file_path": "core/src/lib.rs", "rank": 98, "score": 14.998669244881887 } ]
Rust
src/libstd/ffi/c_str.rs
jauhien/rust
f3092b1d58fd7fba154e40f6b2279d67663298a5
use fmt; use iter::IteratorExt; use libc; use mem; use ops::Deref; use slice::{self, SliceExt}; use string::String; use vec::Vec; #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CString { inner: Vec<libc::c_char>, } impl CString { pub fn from_slice(v: &[u8]) -> CString { CString::from_vec(v.to_vec()) } pub fn from_vec(v: Vec<u8>) -> CString { assert!(!v.iter().any(|&x| x == 0)); unsafe { CString::from_vec_unchecked(v) } } pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.push(0); CString { inner: mem::transmute(v) } } pub fn as_slice_with_nul(&self) -> &[libc::c_char] { &self.inner } pub fn as_bytes(&self) -> &[u8] { unsafe { mem::transmute(&**self) } } pub fn as_bytes_with_nul(&self) -> &[u8] { unsafe { mem::transmute(self.as_slice_with_nul()) } } } impl Deref for CString { type Target = [libc::c_char]; fn deref(&self) -> &[libc::c_char] { &self.inner[..(self.inner.len() - 1)] } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f) } } pub unsafe fn c_str_to_bytes<'a>(raw: &'a *const libc::c_char) -> &'a [u8] { let len = libc::strlen(*raw); slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint) } pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: &'a *const libc::c_char) -> &'a [u8] { let len = libc::strlen(*raw) + 1; slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint) } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use libc; use mem; #[test] fn c_to_rust() { let data = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(c_str_to_bytes(&ptr), b"123"); assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0"); } } #[test] fn simple() { let s = CString::from_slice(b"1234"); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); unsafe { assert_eq!(&*s, mem::transmute::<_, &[libc::c_char]>(b"1234")); assert_eq!(s.as_slice_with_nul(), mem::transmute::<_, &[libc::c_char]>(b"1234\0")); } } #[should_fail] #[test] fn build_with_zero1() { CString::from_slice(b"\0"); } #[should_fail] #[test] fn build_with_zero2() { CString::from_vec(vec![0]); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::from_slice(b"12"); assert_eq!(format!("{:?}", s), "\"12\""); } }
use fmt; use iter::IteratorExt; use libc; use mem; use ops::Deref; use slice::{self, SliceExt}; use string::String; use vec::Vec; #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash)] pub struct CString { inner: Vec<libc::c_char>, } impl CString { pub fn from_slice(v: &[u8]) -> CString { CString::from_vec(v.to_vec()) } pub fn from_vec(v: Vec<u8>) -> CString { assert!(!v.iter().any(|&x| x == 0)); unsafe { CString::from_vec_unchecked(v) } } pub unsafe fn from_vec_unchecked(mut v: Vec<u8>) -> CString { v.push(0); CString { inner: mem::transmute(v) } } pub fn as_slice_with_nul(&self) -> &[libc::c_char] { &self.inner } pub fn as_bytes(&self) -> &[u8] { unsafe { mem::transmute(&**self) } } pub fn as_bytes_with_nul(&self) -> &[u8] { unsafe { mem::transmute(self.as_slice_with_nul()) } } } impl Deref for CString { type Target = [libc::c_char]; fn deref(&self) -> &[libc::c_char] { &self.inner[..(self.inner.len() - 1)] } } #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for CString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f) } } pub unsafe fn c_str_to_bytes<'a>(raw: &'a *const libc::c_char) -> &'a [u8] { let len = libc::strlen(*raw); slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint) } pub unsafe fn c_str_to_bytes_with_nul<'a>(raw: &'a *const libc::c_char) -> &'a [u8] { let len = libc::strlen(*raw) + 1; slice::from_raw_buf(&*(raw as *const _ as *const *const u8), len as uint) } #[cfg(test)] mod tests { use prelude::v1::*; use super::*; use libc; use mem; #[test] fn c_to_rust() { let da
#[test] fn simple() { let s = CString::from_slice(b"1234"); assert_eq!(s.as_bytes(), b"1234"); assert_eq!(s.as_bytes_with_nul(), b"1234\0"); unsafe { assert_eq!(&*s, mem::transmute::<_, &[libc::c_char]>(b"1234")); assert_eq!(s.as_slice_with_nul(), mem::transmute::<_, &[libc::c_char]>(b"1234\0")); } } #[should_fail] #[test] fn build_with_zero1() { CString::from_slice(b"\0"); } #[should_fail] #[test] fn build_with_zero2() { CString::from_vec(vec![0]); } #[test] fn build_with_zero3() { unsafe { let s = CString::from_vec_unchecked(vec![0]); assert_eq!(s.as_bytes(), b"\0"); } } #[test] fn formatted() { let s = CString::from_slice(b"12"); assert_eq!(format!("{:?}", s), "\"12\""); } }
ta = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(c_str_to_bytes(&ptr), b"123"); assert_eq!(c_str_to_bytes_with_nul(&ptr), b"123\0"); } }
function_block-function_prefixed
[ { "content": "// same as cci_iter_lib, more-or-less, but not marked inline\n\npub fn iter<F>(v: Vec<uint> , mut f: F) where F: FnMut(uint) {\n\n let mut i = 0u;\n\n let n = v.len();\n\n while i < n {\n\n f(v[i]);\n\n i += 1u;\n\n }\n\n}\n", "file_path": "src/test/auxiliary/cci_no_inline_lib.rs", "rank": 0, "score": 608125.7763290815 }, { "content": "#[start]\n\npub fn start(_: int, _: *const *const u8) -> int { 0 }\n", "file_path": "src/test/run-pass/use.rs", "rank": 1, "score": 590767.5854912736 }, { "content": "fn f(p: *const u8) -> u8 {\n\n return *p; //~ ERROR dereference of unsafe pointer requires unsafe function or block\n\n}\n\n\n", "file_path": "src/test/compile-fail/unsafe-fn-deref-ptr.rs", "rank": 2, "score": 564707.2921712617 }, { "content": "fn range_<F>(lo: uint, hi: uint, mut it: F) where F: FnMut(uint) {\n\n let mut lo_ = lo;\n\n while lo_ < hi { it(lo_); lo_ += 1u; }\n\n}\n\n\n", "file_path": "src/test/run-pass/type-params-in-for-each.rs", "rank": 3, "score": 549057.8221023073 }, { "content": "fn f(p: *const u8) {\n\n *p = 0u8; //~ ERROR dereference of unsafe pointer requires unsafe function or block\n\n return;\n\n}\n\n\n", "file_path": "src/test/compile-fail/unsafe-fn-assign-deref-ptr.rs", "rank": 4, "score": 542970.1868122069 }, { "content": "pub fn keep_going<F>(data: &[u8], mut f: F) -> i64 where\n\n F: FnMut(*const u8, uint) -> i64,\n\n{\n\n let origamt = data.len();\n\n let mut data = data.as_ptr();\n\n let mut amt = origamt;\n\n while amt > 0 {\n\n let ret = retry(|| f(data, amt));\n\n if ret == 0 {\n\n break\n\n } else if ret != -1 {\n\n amt -= ret as uint;\n\n data = unsafe { data.offset(ret as int) };\n\n } else {\n\n return ret;\n\n }\n\n }\n\n return (origamt - amt) as i64;\n\n}\n\n\n", "file_path": "src/libstd/sys/common/mod.rs", "rank": 5, "score": 533081.6597553046 }, { "content": "// given a Vec<u8>, for each window call a function\n\n// i.e., for \"hello\" and windows of size four,\n\n// run it(\"hell\") and it(\"ello\"), then return \"llo\"\n\nfn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where\n\n F: FnMut(&[u8]),\n\n{\n\n let mut ii = 0u;\n\n\n\n let len = bb.len();\n\n while ii < len - (nn - 1u) {\n\n it(&bb[ii..ii+nn]);\n\n ii += 1u;\n\n }\n\n\n\n return bb[len - (nn - 1u)..len].to_vec();\n\n}\n\n\n", "file_path": "src/test/bench/shootout-k-nucleotide-pipes.rs", "rank": 6, "score": 522882.59988375474 }, { "content": "pub fn inner<F>(f: F) -> F {\n\n (move || f)()\n\n}\n", "file_path": "src/test/auxiliary/issue-18711.rs", "rank": 7, "score": 515519.00224926136 }, { "content": "pub fn escape_default<F>(c: u8, mut f: F) where\n\n F: FnMut(u8),\n\n{\n\n match c {\n\n b'\\t' => { f(b'\\\\'); f(b't'); }\n\n b'\\r' => { f(b'\\\\'); f(b'r'); }\n\n b'\\n' => { f(b'\\\\'); f(b'n'); }\n\n b'\\\\' => { f(b'\\\\'); f(b'\\\\'); }\n\n b'\\'' => { f(b'\\\\'); f(b'\\''); }\n\n b'\"' => { f(b'\\\\'); f(b'\"'); }\n\n b'\\x20' ... b'\\x7e' => { f(c); }\n\n _ => {\n\n f(b'\\\\');\n\n f(b'x');\n\n for &offset in &[4u, 0u] {\n\n match ((c as i32) >> offset) & 0xf {\n\n i @ 0 ... 9 => f(b'0' + (i as u8)),\n\n i => f(b'a' + (i as u8 - 10)),\n\n }\n\n }\n", "file_path": "src/libstd/ascii.rs", "rank": 8, "score": 515224.0470546638 }, { "content": "pub fn main() { let _a = [0; 1 as uint]; }\n", "file_path": "src/test/run-pass/vec-repeat-with-cast.rs", "rank": 9, "score": 514726.82568635396 }, { "content": "struct X { pub x: uint }\n\nimpl Default for X {\n\n fn default() -> X {\n\n X { x: 42u }\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/issue-8783.rs", "rank": 10, "score": 512975.58375527523 }, { "content": "pub fn FnvHashSet<V: Hash<FnvHasher> + Eq>() -> FnvHashSet<V> {\n\n Default::default()\n\n}\n\n\n", "file_path": "src/librustc/util/nodemap.rs", "rank": 11, "score": 502688.7406960722 }, { "content": "pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod) {\n\n for item in &module.items {\n\n visitor.visit_item(&**item)\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 12, "score": 500927.7586262004 }, { "content": "#[start]\n\npub fn main(_: int, _: *const *const u8) -> int {\n\n println!(\"hello\");\n\n 0\n\n}\n", "file_path": "src/test/run-pass/native-print-no-runtime.rs", "rank": 13, "score": 495648.1456209253 }, { "content": "pub fn parse_type_param_def_data<'tcx, F>(data: &[u8], start: uint,\n\n crate_num: ast::CrateNum, tcx: &ty::ctxt<'tcx>,\n\n conv: F) -> ty::TypeParameterDef<'tcx> where\n\n F: FnMut(DefIdSource, ast::DefId) -> ast::DefId,\n\n{\n\n let mut st = parse_state_from_data(data, crate_num, start, tcx);\n\n parse_type_param_def(&mut st, conv)\n\n}\n\n\n", "file_path": "src/librustc/metadata/tydecode.rs", "rank": 14, "score": 494834.63350115425 }, { "content": "pub fn main() { let mut v = vec!(1, 2, 3); v.push(1); }\n", "file_path": "src/test/run-pass/vec-push.rs", "rank": 15, "score": 493423.70130409155 }, { "content": "#[inline]\n\npub fn iter<T, F>(v: &[T], mut f: F) where F: FnMut(&T) {\n\n let mut i = 0u;\n\n let n = v.len();\n\n while i < n {\n\n f(&v[i]);\n\n i += 1u;\n\n }\n\n}\n", "file_path": "src/test/auxiliary/cci_iter_lib.rs", "rank": 16, "score": 492293.35203988897 }, { "content": "fn test<F>(f: F) -> uint where F: FnOnce(uint) -> uint {\n\n return f(22u);\n\n}\n\n\n", "file_path": "src/test/run-pass/sendfn-is-a-block.rs", "rank": 17, "score": 492032.735812536 }, { "content": "pub fn increment(x: uint) -> uint {\n\n x + 1\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! increment {\n\n ($x:expr) => ({\n\n use $crate::increment;\n\n increment($x)\n\n })\n\n}\n\n\n", "file_path": "src/test/run-pass/macro-crate-use.rs", "rank": 18, "score": 490684.02981082094 }, { "content": "// Acquires a slice of the vector `v` from its length to its capacity\n\n// (uninitialized data), reads into it, and then updates the length.\n\n//\n\n// This function is leveraged to efficiently read some bytes into a destination\n\n// vector without extra copying and taking advantage of the space that's already\n\n// in `v`.\n\n//\n\n// The buffer we're passing down, however, is pointing at uninitialized data\n\n// (the end of a `Vec`), and many operations will be *much* faster if we don't\n\n// have to zero it out. In order to prevent LLVM from generating an `undef`\n\n// value when reads happen from this uninitialized memory, we force LLVM to\n\n// think it's initialized by sending it through a black box. This should prevent\n\n// actual undefined behavior after optimizations.\n\nfn with_end_to_cap<F>(v: &mut Vec<u8>, f: F) -> Result<usize>\n\n where F: FnOnce(&mut [u8]) -> Result<usize>\n\n{\n\n unsafe {\n\n let n = try!(f({\n\n let base = v.as_mut_ptr().offset(v.len() as isize);\n\n black_box(slice::from_raw_mut_buf(mem::copy_lifetime(v, &base),\n\n v.capacity() - v.len()))\n\n }));\n\n\n\n // If the closure (typically a `read` implementation) reported that it\n\n // read a larger number of bytes than the vector actually has, we need\n\n // to be sure to clamp the vector to at most its capacity.\n\n let new_len = cmp::min(v.capacity(), v.len() + n);\n\n v.set_len(new_len);\n\n return Ok(n);\n\n }\n\n\n\n // Semi-hack used to prevent LLVM from retaining any assumptions about\n\n // `dummy` over this function call\n\n unsafe fn black_box<T>(mut dummy: T) -> T {\n\n asm!(\"\" :: \"r\"(&mut dummy) : \"memory\");\n\n dummy\n\n }\n\n}\n\n\n", "file_path": "src/libstd/io/mod.rs", "rank": 19, "score": 489526.69373988546 }, { "content": "fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 }\n", "file_path": "src/test/compile-fail/unboxed-closures-unsafe-extern-fn.rs", "rank": 20, "score": 488326.9354192572 }, { "content": "fn use_slice_mut(_: &mut [u8]) {}\n\n\n", "file_path": "src/test/run-pass/coerce-overloaded-autoderef.rs", "rank": 21, "score": 482005.41986816446 }, { "content": "fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 }\n", "file_path": "src/test/compile-fail/unboxed-closures-wrong-arg-type-extern-fn.rs", "rank": 22, "score": 480038.7330930172 }, { "content": "pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId) {\n\n let stuff = [\"foo\", \"bar\"];\n\n\n\n for l in &stuff {\n\n f(&CrateId::new(*l));\n\n }\n\n}\n\n\n", "file_path": "src/test/compile-fail/issue-7573.rs", "rank": 23, "score": 479847.0186035832 }, { "content": "struct X { x: uint, nxt: *const foo }\n\n\n", "file_path": "src/test/run-pass/instantiable.rs", "rank": 24, "score": 479396.63573773776 }, { "content": "pub fn main() { let _x: uint = 10 as uint; }\n", "file_path": "src/test/run-pass/uint.rs", "rank": 25, "score": 478885.33766691084 }, { "content": "pub fn main() { let x: A = A {a: 1}; assert!((a(x) == 1)); }\n", "file_path": "src/test/run-pass/type-namespace.rs", "rank": 26, "score": 478850.0392861536 }, { "content": "pub fn FnvHashMap<K: Hash<FnvHasher> + Eq, V>() -> FnvHashMap<K, V> {\n\n Default::default()\n\n}\n", "file_path": "src/librustc/util/nodemap.rs", "rank": 27, "score": 475509.9467727644 }, { "content": "// given a map, increment the counter for a key\n\nfn update_freq(mm: &mut HashMap<Vec<u8> , uint>, key: &[u8]) {\n\n let key = key.to_vec();\n\n let newval = match mm.remove(&key) {\n\n Some(v) => v + 1,\n\n None => 1\n\n };\n\n mm.insert(key, newval);\n\n}\n\n\n", "file_path": "src/test/bench/shootout-k-nucleotide-pipes.rs", "rank": 28, "score": 472658.1668374428 }, { "content": "fn mult<F>(v: &[f64], out: &mut [f64], start: uint, a: F)\n\n where F: Fn(uint, uint) -> f64 {\n\n for (i, slot) in out.iter_mut().enumerate().map(|(i, s)| (i + start, s)) {\n\n let mut sum = f64x2(0.0, 0.0);\n\n for (j, chunk) in v.chunks(2).enumerate().map(|(j, s)| (2 * j, s)) {\n\n let top = f64x2(chunk[0], chunk[1]);\n\n let bot = f64x2(a(i, j), a(i, j + 1));\n\n sum += top / bot;\n\n }\n\n let f64x2(a, b) = sum;\n\n *slot = a + b;\n\n }\n\n}\n\n\n", "file_path": "src/test/bench/shootout-spectralnorm.rs", "rank": 29, "score": 469486.20858114504 }, { "content": "pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where\n\n F: FnMut(ast::Name, Vec<ast::Attribute>, String) -> bool,\n\n{\n\n let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);\n\n reader::tagged_docs(macros, tag_macro_def, |macro_doc| {\n\n let name = item_name(intr, macro_doc);\n\n let attrs = get_attributes(macro_doc);\n\n let body = reader::get_doc(macro_doc, tag_macro_def_body);\n\n f(name, attrs, body.as_str().to_string())\n\n });\n\n}\n\n\n", "file_path": "src/librustc/metadata/decoder.rs", "rank": 30, "score": 468862.930138865 }, { "content": "pub fn walk_struct_def<'v, V: Visitor<'v>>(visitor: &mut V,\n\n struct_definition: &'v StructDef) {\n\n for field in &struct_definition.fields {\n\n visitor.visit_struct_field(field)\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 31, "score": 467823.1259988281 }, { "content": "pub fn walk_struct_field<'v, V: Visitor<'v>>(visitor: &mut V,\n\n struct_field: &'v StructField) {\n\n if let NamedField(name, _) = struct_field.node.kind {\n\n visitor.visit_ident(struct_field.span, name);\n\n }\n\n\n\n visitor.visit_ty(&*struct_field.node.ty);\n\n\n\n for attr in &struct_field.node.attrs {\n\n visitor.visit_attribute(attr);\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 32, "score": 467823.1259988281 }, { "content": "pub fn noop_fold_mod<T: Folder>(Mod {inner, items}: Mod, folder: &mut T) -> Mod {\n\n Mod {\n\n inner: folder.new_span(inner),\n\n items: items.into_iter().flat_map(|x| folder.fold_item(x).into_iter()).collect(),\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/fold.rs", "rank": 33, "score": 466337.7280108612 }, { "content": "pub fn main() { let x = 10; test(x); }\n", "file_path": "src/test/run-pass/move-arg.rs", "rank": 34, "score": 465467.59279603907 }, { "content": "pub fn main() { let mut x: int; if 1 > 2 { x = 12; } else { x = 10; } foo(x); }\n", "file_path": "src/test/run-pass/lazy-init.rs", "rank": 35, "score": 465378.52340396267 }, { "content": "pub fn main() { let x = box 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": 36, "score": 464530.4068102657 }, { "content": "pub fn addr() -> uint { unsafe { mem::transmute(&both::foo) } }\n", "file_path": "src/test/run-make/mixing-deps/dylib.rs", "rank": 37, "score": 463491.23044638627 }, { "content": "pub fn main() { let mut n; n = 1; println!(\"{}\", n); }\n", "file_path": "src/test/run-pass/simple-infer.rs", "rank": 38, "score": 462993.05297481373 }, { "content": "pub fn spawn<F>(_: F) -> () where F: FnOnce(), F: Send + 'static {}\n\n\n", "file_path": "src/test/run-pass/traits-negative-impls.rs", "rank": 39, "score": 462105.0608223014 }, { "content": "pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>(visitor: &mut V,\n\n type_binding: &'v TypeBinding) {\n\n visitor.visit_ident(type_binding.span, type_binding.ident);\n\n visitor.visit_ty(&*type_binding.ty);\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 40, "score": 461923.43802568037 }, { "content": "#[inline]\n\npub fn retry<T, F> (mut f: F) -> T where\n\n T: SignedInt,\n\n F: FnMut() -> T,\n\n{\n\n let one: T = Int::one();\n\n loop {\n\n let n = f();\n\n if n == -one && os::errno() == libc::EINTR as i32 { }\n\n else { return n }\n\n }\n\n}\n\n\n", "file_path": "src/libstd/sys/unix/mod.rs", "rank": 41, "score": 461913.48691327893 }, { "content": "struct Bar<F> where F: FnMut() -> int { f: F }\n\n\n\nstatic mut b : Bar<fn() -> int> = Bar { f: foo as fn() -> int};\n\n\n", "file_path": "src/test/run-pass/const-fn-val.rs", "rank": 42, "score": 459381.497398703 }, { "content": "pub fn f<T, F>((b1, b2): (T, T), mut f: F) -> Partial<T> where F: FnMut(T) -> T {\n\n let p = Partial { x: b1, y: b2 };\n\n\n\n // Move of `p` is legal even though we are also moving `p.y`; the\n\n // `..p` moves all fields *except* `p.y` in this context.\n\n Partial { y: f(p.y), ..p }\n\n}\n\n\n", "file_path": "src/test/run-pass/struct-partial-move-1.rs", "rank": 43, "score": 458657.7325110356 }, { "content": "pub fn walk_mac<'v, V: Visitor<'v>>(_: &mut V, _: &'v Mac) {\n\n // Empty!\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 44, "score": 457555.62237710145 }, { "content": "pub fn skip_ty<'v, V: Visitor<'v>>(_: &mut V, _: &'v Ty) {\n\n // Empty!\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 45, "score": 457555.62237710145 }, { "content": "#[lang=\"start\"]\n\nfn start(_main: *const u8, _argc: int, _argv: *const *const u8) -> int { 0 }\n\n\n\nextern {\n\n fn _foo() -> [u8; 16];\n\n}\n\n\n", "file_path": "src/test/run-make/target-specs/foo.rs", "rank": 46, "score": 454521.3442770684 }, { "content": "pub fn main() { let _x = m::f(); }\n", "file_path": "src/test/run-pass/mod-view-items.rs", "rank": 47, "score": 454143.4815872138 }, { "content": "fn use_vec(mut v: Vec<u8>) {\n\n use_slice_mut(&mut v[..]); // what you have to write today\n\n use_slice_mut(&mut v); // what you'd be able to write\n\n use_slice_mut(&mut &mut &mut v);\n\n\n\n use_slice(&v[..]); // what you have to write today\n\n use_slice(&v); // what you'd be able to write\n\n use_slice(&&&&&&v);\n\n use_slice(&mut &&&&&v);\n\n use_slice(&&&mut &&&v);\n\n}\n\n\n", "file_path": "src/test/run-pass/coerce-overloaded-autoderef.rs", "rank": 48, "score": 453367.6635048501 }, { "content": "pub fn each_impl<F>(cdata: Cmd, mut callback: F) where\n\n F: FnMut(ast::DefId),\n\n{\n\n let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);\n\n let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {\n\n callback(item_def_id(impl_doc, cdata));\n\n true\n\n });\n\n}\n\n\n", "file_path": "src/librustc/metadata/decoder.rs", "rank": 49, "score": 453169.19860489335 }, { "content": "fn two<F>(mut it: F) where F: FnMut(int) { it(0); it(1); }\n\n\n", "file_path": "src/test/run-pass/foreach-nested.rs", "rank": 50, "score": 451463.4731229634 }, { "content": "pub fn expand_deriving_hash<F>(cx: &mut ExtCtxt,\n\n span: Span,\n\n mitem: &MetaItem,\n\n item: &Item,\n\n push: F) where\n\n F: FnOnce(P<Item>),\n\n{\n\n\n\n let path = Path::new_(vec!(\"std\", \"hash\", \"Hash\"), None,\n\n vec!(box Literal(Path::new_local(\"__S\"))), true);\n\n let generics = LifetimeBounds {\n\n lifetimes: Vec::new(),\n\n bounds: vec!((\"__S\",\n\n vec!(Path::new(vec!(\"std\", \"hash\", \"Writer\")),\n\n Path::new(vec!(\"std\", \"hash\", \"Hasher\"))))),\n\n };\n\n let args = Path::new_local(\"__S\");\n\n let inline = cx.meta_word(span, InternedString::new(\"inline\"));\n\n let attrs = vec!(cx.attribute(span, inline));\n\n let hash_trait_def = TraitDef {\n", "file_path": "src/libsyntax/ext/deriving/hash.rs", "rank": 51, "score": 449486.26762402244 }, { "content": "fn inc<T: Deref<Target=int> + DerefMut>(mut t: T) {\n\n *t += 1;\n\n}\n\n\n", "file_path": "src/test/run-pass/deref-mut-on-ref.rs", "rank": 52, "score": 449435.71223279374 }, { "content": "pub fn walk_ty_method<'v, V: Visitor<'v>>(visitor: &mut V, method_type: &'v TypeMethod) {\n\n visitor.visit_ident(method_type.span, method_type.ident);\n\n visitor.visit_explicit_self(&method_type.explicit_self);\n\n for argument_type in &method_type.decl.inputs {\n\n visitor.visit_ty(&*argument_type.ty)\n\n }\n\n visitor.visit_generics(&method_type.generics);\n\n walk_fn_ret_ty(visitor, &method_type.decl.output);\n\n for attr in &method_type.attrs {\n\n visitor.visit_attribute(attr);\n\n }\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 53, "score": 449402.58574168687 }, { "content": "fn call_it<F:FnMut(i32)->i32>(mut f: F, x: i32) -> i32 {\n\n f(x) + 3\n\n}\n\n\n", "file_path": "src/test/run-pass/unboxed-closures-manual-impl.rs", "rank": 54, "score": 447695.9339310693 }, { "content": "#[inline]\n\n#[unstable(feature = \"core\")]\n\npub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<uint> {\n\n // Marked #[inline] to allow llvm optimizing it away\n\n if code < MAX_ONE_B && dst.len() >= 1 {\n\n dst[0] = code as u8;\n\n Some(1)\n\n } else if code < MAX_TWO_B && dst.len() >= 2 {\n\n dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;\n\n dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;\n\n Some(2)\n\n } else if code < MAX_THREE_B && dst.len() >= 3 {\n\n dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;\n\n dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;\n\n dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;\n\n Some(3)\n\n } else if dst.len() >= 4 {\n\n dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;\n\n dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;\n\n dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;\n\n dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;\n\n Some(4)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n/// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer,\n\n/// and then returns the number of `u16`s written.\n\n///\n\n/// If the buffer is not large enough, nothing will be written into it\n\n/// and a `None` will be returned.\n", "file_path": "src/libcore/char.rs", "rank": 55, "score": 447586.8270301686 }, { "content": "fn conspirator<F>(mut f: F) where F: FnMut(&mut R, bool) {\n\n let mut r = R {c: box f};\n\n f(&mut r, false) //~ ERROR use of moved value\n\n}\n\n\n", "file_path": "src/test/compile-fail/moves-based-on-type-no-recursive-stack-closure.rs", "rank": 56, "score": 446596.147712848 }, { "content": "fn iter_vec<T, F>(v: Vec<T> , mut f: F) where F: FnMut(&T) { for x in &v { f(x); } }\n\n\n", "file_path": "src/test/run-pass/block-iter-1.rs", "rank": 57, "score": 446277.13153173856 }, { "content": "fn iter_vec<T, F>(v: Vec<T>, mut f: F) where F: FnMut(&T) { for x in &v { f(x); } }\n\n\n", "file_path": "src/test/run-pass/block-iter-2.rs", "rank": 58, "score": 446277.13153173856 }, { "content": "fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] }\n\n\n", "file_path": "src/test/run-pass/issue-4464.rs", "rank": 59, "score": 445656.4882746885 }, { "content": "pub fn expand_deriving_ord<F>(cx: &mut ExtCtxt,\n\n span: Span,\n\n mitem: &MetaItem,\n\n item: &Item,\n\n push: F) where\n\n F: FnOnce(P<Item>),\n\n{\n\n macro_rules! md {\n\n ($name:expr, $op:expr, $equal:expr) => { {\n\n let inline = cx.meta_word(span, InternedString::new(\"inline\"));\n\n let attrs = vec!(cx.attribute(span, inline));\n\n MethodDef {\n\n name: $name,\n\n generics: LifetimeBounds::empty(),\n\n explicit_self: borrowed_explicit_self(),\n\n args: vec!(borrowed_self()),\n\n ret_ty: Literal(Path::new(vec!(\"bool\"))),\n\n attributes: attrs,\n\n combine_substructure: combine_substructure(box |cx, span, substr| {\n\n cs_op($op, $equal, cx, span, substr)\n", "file_path": "src/libsyntax/ext/deriving/cmp/ord.rs", "rank": 60, "score": 444009.6614769383 }, { "content": "pub fn expand_deriving_eq<F>(cx: &mut ExtCtxt,\n\n span: Span,\n\n mitem: &MetaItem,\n\n item: &Item,\n\n push: F) where\n\n F: FnOnce(P<Item>),\n\n{\n\n // structures are equal if all fields are equal, and non equal, if\n\n // any fields are not equal or if the enum variants are different\n\n fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {\n\n cs_fold(\n\n true, // use foldl\n\n |cx, span, subexpr, self_f, other_fs| {\n\n let other_f = match other_fs {\n\n [ref o_f] => o_f,\n\n _ => cx.span_bug(span, \"not exactly 2 arguments in `derive(PartialEq)`\")\n\n };\n\n\n\n let eq = cx.expr_binary(span, ast::BiEq, self_f, other_f.clone());\n\n\n", "file_path": "src/libsyntax/ext/deriving/cmp/eq.rs", "rank": 61, "score": 443986.63509314996 }, { "content": "pub fn replace_map<'a, T, F>(src: &mut T, prod: F) where F: FnOnce(T) -> T {\n\n unsafe { *src = prod(ptr::read(src as *mut T as *const T)); }\n\n}\n\n\n", "file_path": "src/test/run-pass/unboxed-closures-unique-type-id.rs", "rank": 62, "score": 441515.3693935012 }, { "content": "pub fn increment(x: uint) -> uint {\n\n x + 1\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! increment {\n\n ($x:expr) => ($crate::increment($x))\n\n}\n\n\n", "file_path": "src/test/auxiliary/macro_crate_nonterminal.rs", "rank": 63, "score": 440876.656544726 }, { "content": "pub fn foo(x: &uint) -> uint {\n\n *x\n\n}\n", "file_path": "src/test/auxiliary/cci_borrow_lib.rs", "rank": 64, "score": 440876.656544726 }, { "content": "pub fn main() { let mut x: i32 = -400_i32; x = 0_i32 - x; assert!((x == 400_i32)); }\n", "file_path": "src/test/run-pass/i32-sub.rs", "rank": 65, "score": 440710.36393023224 }, { "content": "fn search_entry_hashed<'a, K: Eq, V>(table: &'a mut RawTable<K,V>, hash: SafeHash, k: K)\n\n -> Entry<'a, K, V>\n\n{\n\n // Worst case, we'll find one empty bucket among `size + 1` buckets.\n\n let size = table.size();\n\n let mut probe = Bucket::new(table, hash);\n\n let ib = probe.index();\n\n\n\n loop {\n\n let bucket = match probe.peek() {\n\n Empty(bucket) => {\n\n // Found a hole!\n\n return Vacant(VacantEntry {\n\n hash: hash,\n\n key: k,\n\n elem: NoElem(bucket),\n\n });\n\n },\n\n Full(bucket) => bucket\n\n };\n", "file_path": "src/libstd/collections/hash/map.rs", "rank": 66, "score": 440237.125642295 }, { "content": "fn call_it_mut<F:FnMut(&isize)->isize>(_: &mut F, _: isize) -> isize { 0 }\n", "file_path": "src/test/compile-fail/unboxed-closures-wrong-abi.rs", "rank": 67, "score": 437344.52650672337 }, { "content": "pub fn main() { let mut r: R<int> = R {v: Vec::new()}; r.v = f(); }\n", "file_path": "src/test/run-pass/alloca-from-derived-tydesc.rs", "rank": 68, "score": 437261.88939360355 }, { "content": "pub fn main() { let x = { box 100 }; assert!((*x == 100)); }\n", "file_path": "src/test/run-pass/expr-block-unique.rs", "rank": 69, "score": 436175.90786333475 }, { "content": "pub fn main() { let x = f(box 3); println!(\"{}\", *x); }\n", "file_path": "src/test/run-pass/generic-fn-unique.rs", "rank": 70, "score": 436072.3485660032 }, { "content": "pub fn walk_fn<'v, V: Visitor<'v>>(visitor: &mut V,\n\n function_kind: FnKind<'v>,\n\n function_declaration: &'v FnDecl,\n\n function_body: &'v Block,\n\n _span: Span) {\n\n walk_fn_decl(visitor, function_declaration);\n\n\n\n match function_kind {\n\n FkItemFn(_, generics, _, _) => {\n\n visitor.visit_generics(generics);\n\n }\n\n FkMethod(_, generics, method) => {\n\n visitor.visit_generics(generics);\n\n match method.node {\n\n MethDecl(_, _, _, ref explicit_self, _, _, _, _) =>\n\n visitor.visit_explicit_self(explicit_self),\n\n MethMac(ref mac) =>\n\n visitor.visit_mac(mac)\n\n }\n\n }\n\n FkFnBlock(..) => {}\n\n }\n\n\n\n visitor.visit_block(function_body)\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 71, "score": 436049.0690468108 }, { "content": "#[no_mangle]\n\npub fn test(a: &Struct,\n\n b: &Struct,\n\n c: &Struct,\n\n d: &Struct,\n\n e: &Struct) -> int {\n\n a.method(b.method(c.method(d.method(e.method(1)))))\n\n}\n", "file_path": "src/test/codegen/static-method-call-multi.rs", "rank": 72, "score": 434469.1154087599 }, { "content": "struct X<F> where F: FnOnce(&str, &str) {\n\n err: F,\n\n}\n\n\n\nimpl<F> X<F> where F: FnOnce(&str, &str) {\n\n pub fn boom(self) {\n\n exit(self.err, \"prog\", \"arg\");\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/issue-3904.rs", "rank": 73, "score": 434266.51171479945 }, { "content": "#[bench]\n\nfn bench_explicit_return_type(_: &mut ::test::Bencher) -> () {}\n\n\n", "file_path": "src/test/run-pass/test-fn-signature-verification-for-explicit-return-type.rs", "rank": 74, "score": 434077.33592034894 }, { "content": "fn g(a: *const int) -> *const int { let b = f(a); return b; }\n\n\n", "file_path": "src/test/run-pass/type-ptr.rs", "rank": 75, "score": 433285.22280543117 }, { "content": "fn takes_hrtb_closure<F: for<'a>FnMut(LifetimeStruct<'a>)>(mut f: F) {\n\n f(LifetimeStruct);\n\n}\n", "file_path": "src/test/run-pass/issue-19135.rs", "rank": 76, "score": 433124.89164614066 }, { "content": "// given a map, print a sorted version of it\n\nfn sort_and_fmt(mm: &HashMap<Vec<u8> , uint>, total: uint) -> String {\n\n fn pct(xx: uint, yy: uint) -> f64 {\n\n return (xx as f64) * 100.0 / (yy as f64);\n\n }\n\n\n\n // sort by key, then by value\n\n fn sortKV(mut orig: Vec<(Vec<u8> ,f64)> ) -> Vec<(Vec<u8> ,f64)> {\n\n orig.sort_by(|&(ref a, _), &(ref b, _)| a.cmp(b));\n\n orig.sort_by(|&(_, a), &(_, b)| f64_cmp(b, a));\n\n orig\n\n }\n\n\n\n let mut pairs = Vec::new();\n\n\n\n // map -> [(k,%)]\n\n for (key, &val) in mm {\n\n pairs.push(((*key).clone(), pct(val, total)));\n\n }\n\n\n\n let pairs_sorted = sortKV(pairs);\n", "file_path": "src/test/bench/shootout-k-nucleotide-pipes.rs", "rank": 77, "score": 432889.09502746625 }, { "content": "/// Like with walk_method_helper this doesn't correspond to a method\n\n/// in Visitor, and so it gets a _helper suffix.\n\npub fn walk_trait_ref<'v,V>(visitor: &mut V,\n\n trait_ref: &'v TraitRef)\n\n where V: Visitor<'v>\n\n{\n\n visitor.visit_path(&trait_ref.path, trait_ref.ref_id)\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 78, "score": 428833.84664242086 }, { "content": "fn bar(v: &mut [uint]) {\n\n v.reverse();\n\n v.reverse();\n\n v.reverse();\n\n}\n\n\n", "file_path": "src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs", "rank": 79, "score": 428219.29914249 }, { "content": "fn bar(v: &mut [uint]) {\n\n reverse(v);\n\n reverse(v);\n\n reverse(v);\n\n}\n\n\n", "file_path": "src/test/run-pass/coerce-reborrow-mut-vec-arg.rs", "rank": 80, "score": 428219.29914249 }, { "content": "fn reverse(v: &mut [uint]) {\n\n v.reverse();\n\n}\n\n\n", "file_path": "src/test/run-pass/coerce-reborrow-mut-vec-arg.rs", "rank": 81, "score": 428219.29914249 }, { "content": "pub fn f<T, F>((b1, b2): (T, T), (b3, b4): (T, T), mut f: F) -> Two<T> where F: FnMut(T) -> T {\n\n let p = Partial { x: b1, y: b2 };\n\n let q = Partial { x: b3, y: b4 };\n\n\n\n // Move of `q` is legal even though we have already moved `q.y`;\n\n // the `..q` moves all fields *except* `q.y` in this context.\n\n // Likewise, the move of `p.x` is legal for similar reasons.\n\n (Partial { x: f(q.y), ..p }, Partial { y: f(p.x), ..q })\n\n}\n\n\n", "file_path": "src/test/run-pass/struct-partial-move-2.rs", "rank": 82, "score": 428137.9505969594 }, { "content": "fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {\n\n let mut frequencies = Table::new();\n\n if input.len() < frame { return frequencies; }\n\n let mut code = Code(0);\n\n\n\n // Pull first frame.\n\n for _ in 0..frame {\n\n code = code.push_char(input[0]);\n\n input = &input[1..];\n\n }\n\n frequencies.lookup(code, BumpCallback);\n\n\n\n while input.len() != 0 && input[0] != ('>' as u8) {\n\n code = code.rotate(input[0], frame);\n\n frequencies.lookup(code, BumpCallback);\n\n input = &input[1..];\n\n }\n\n frequencies\n\n}\n\n\n", "file_path": "src/test/bench/shootout-k-nucleotide.rs", "rank": 83, "score": 427949.76251000614 }, { "content": "#[start]\n\nfn main(_: int, _: *const *const u8) -> int {\n\n 0\n\n}\n", "file_path": "src/test/compile-fail/issue-19660.rs", "rank": 84, "score": 427933.238243734 }, { "content": "fn call_f<F:FnMut()>(mut f: F) {\n\n f();\n\n}\n\n\n", "file_path": "src/test/run-pass/bare-fn-implements-fn-mut.rs", "rank": 85, "score": 427646.95379357616 }, { "content": "fn f(x: *const int) {\n\n unsafe {\n\n assert_eq!(*x, 3);\n\n }\n\n}\n\n\n", "file_path": "src/test/run-pass/unsafe-pointer-assignability.rs", "rank": 86, "score": 427256.82099139434 }, { "content": "fn foo<F: Fn()>(mut f: F, mut g: F) {\n\n Fn::call(&g, ()); //~ ERROR explicit use of unboxed closure method `call`\n\n FnMut::call_mut(&mut g, ()); //~ ERROR explicit use of unboxed closure method `call_mut`\n\n FnOnce::call_once(g, ()); //~ ERROR explicit use of unboxed closure method `call_once`\n\n}\n\n\n", "file_path": "src/test/compile-fail/feature-gate-unboxed-closures-ufcs-calls.rs", "rank": 87, "score": 426399.20975735865 }, { "content": "fn asBlock<F>(f: F) -> uint where F: FnOnce() -> uint {\n\n return f();\n\n}\n\n\n", "file_path": "src/test/run-pass/block-arg-call-as.rs", "rank": 88, "score": 423838.04755439865 }, { "content": "/// Like with walk_method_helper this doesn't correspond to a method\n\n/// in Visitor, and so it gets a _helper suffix.\n\npub fn walk_poly_trait_ref<'v, V>(visitor: &mut V,\n\n trait_ref: &'v PolyTraitRef,\n\n _modifier: &'v TraitBoundModifier)\n\n where V: Visitor<'v>\n\n{\n\n walk_lifetime_decls_helper(visitor, &trait_ref.bound_lifetimes);\n\n visitor.visit_trait_ref(&trait_ref.trait_ref);\n\n}\n\n\n", "file_path": "src/libsyntax/visit.rs", "rank": 89, "score": 423831.2278022701 }, { "content": "fn call_fn_mut<F: FnMut()>(mut f: F) {\n\n f()\n\n}\n\n\n", "file_path": "src/test/run-pass/unboxed-closures-by-ref.rs", "rank": 90, "score": 423351.64448023273 }, { "content": "struct X<F> where F: FnOnce() + 'static + Send {\n\n field: F,\n\n}\n\n\n", "file_path": "src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs", "rank": 91, "score": 423242.62031934696 }, { "content": "#[no_mangle]\n\npub fn test(s: &Struct) -> int {\n\n s.method()\n\n}\n", "file_path": "src/test/codegen/static-method-call.rs", "rank": 92, "score": 423229.4659892185 }, { "content": "#[start]\n\npub fn main(_: int, _: **u8, _: *u8) -> int {\n\n no_std_crate::foo();\n\n 0\n\n}\n", "file_path": "src/test/run-pass/no-std-xcrate2.rs", "rank": 93, "score": 422570.727871842 }, { "content": "fn call<F>(mut f: F) where F: FnMut(Fn) {\n\n f(box || {\n\n //~^ ERROR: cannot borrow `f` as mutable more than once\n\n f(box || {})\n\n });\n\n}\n\n\n", "file_path": "src/test/compile-fail/borrowck-call-is-borrow-issue-12224.rs", "rank": 94, "score": 422525.27009436657 }, { "content": "fn is_fn<F>(_: F) where F: Fn() {}\n\n\n", "file_path": "src/test/compile-fail/extern-wrong-value-type.rs", "rank": 95, "score": 422094.3656765636 }, { "content": "#[inline]\n\n#[unstable(feature = \"core\")]\n\npub fn char_range_at_raw(bytes: &[u8], i: uint) -> (u32, usize) {\n\n if bytes[i] < 128u8 {\n\n return (bytes[i] as u32, i + 1);\n\n }\n\n\n\n // Multibyte case is a fn to allow char_range_at to inline cleanly\n\n fn multibyte_char_range_at(bytes: &[u8], i: uint) -> (u32, usize) {\n\n let mut val = bytes[i] as u32;\n\n let w = UTF8_CHAR_WIDTH[val as uint] as uint;\n\n assert!((w != 0));\n\n\n\n val = utf8_first_byte!(val, w);\n\n val = utf8_acc_cont_byte!(val, bytes[i + 1]);\n\n if w > 2 { val = utf8_acc_cont_byte!(val, bytes[i + 2]); }\n\n if w > 3 { val = utf8_acc_cont_byte!(val, bytes[i + 3]); }\n\n\n\n return (val, i + w);\n\n }\n\n\n\n multibyte_char_range_at(bytes, i)\n", "file_path": "src/libcore/str/mod.rs", "rank": 96, "score": 420912.843837515 }, { "content": "fn bar<F: Fn(&u8, &u8) -> &u8>(f: &F) {} //~ ERROR missing lifetime specifier\n\n//~^ HELP the signature does not say whether it is borrowed from argument 1 or argument 2\n\n\n", "file_path": "src/test/compile-fail/issue-19707.rs", "rank": 97, "score": 420426.85212799755 }, { "content": "pub fn now() -> DateTime<X> { from_utc(Y) }\n\n\n\npub struct DateTime<Off: Offset> { pub offset: Off::State }\n", "file_path": "src/test/run-pass/associated-types-normalize-unifield-struct.rs", "rank": 98, "score": 420322.33402298065 }, { "content": "fn call_fn_mut<F: FnMut()>(mut f: F) {\n\n f()\n\n}\n\n\n", "file_path": "src/test/run-pass/unboxed-closures-infer-kind.rs", "rank": 99, "score": 419629.19845816476 } ]
Rust
rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/complaints.rs
pipe-blockchain/ic
69d3263702ac3b52fd18c35dd1cc46de08d92073
use rand::Rng; use std::collections::BTreeMap; use tecdsa::*; fn corrupt_ciphertext_single( ctext: &[EccScalar], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<EccScalar>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].curve_type(); let randomizer = EccScalar::one(curve_type); ctext[corruption_target] = ctext[corruption_target].add(&randomizer)?; Ok(ctext) } fn corrupt_ciphertext_pairs( ctext: &[(EccScalar, EccScalar)], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<(EccScalar, EccScalar)>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].0.curve_type(); let randomizer = EccScalar::one(curve_type); ctext[corruption_target].0 = ctext[corruption_target].0.add(&randomizer)?; Ok(ctext) } fn corrupt_dealing( dealing: &IDkgDealingInternal, corruption_target: usize, ) -> ThresholdEcdsaResult<IDkgDealingInternal> { let ciphertext = match &dealing.ciphertext { MEGaCiphertext::Single(c) => MEGaCiphertext::Single(MEGaCiphertextSingle { ephemeral_key: c.ephemeral_key, ctexts: corrupt_ciphertext_single(&c.ctexts, corruption_target)?, }), MEGaCiphertext::Pairs(c) => MEGaCiphertext::Pairs(MEGaCiphertextPair { ephemeral_key: c.ephemeral_key, ctexts: corrupt_ciphertext_pairs(&c.ctexts, corruption_target)?, }), }; Ok(IDkgDealingInternal { ciphertext, commitment: dealing.commitment.clone(), proof: dealing.proof.clone(), }) } #[test] fn should_complaint_system_work() -> ThresholdEcdsaResult<()> { let curve = EccCurveType::K256; let associated_data = b"assoc_data_test"; let mut rng = rand::thread_rng(); let sk0 = MEGaPrivateKey::generate(curve, &mut rng)?; let pk0 = sk0.public_key()?; let sk1 = MEGaPrivateKey::generate(curve, &mut rng)?; let pk1 = sk1.public_key()?; let dealer_index = 0; let threshold = 1; let dealing = IDkgDealingInternal::new( &SecretShares::Random, curve, Seed::from_rng(&mut rng), threshold, &[pk0, pk1], dealer_index, associated_data, )?; let mut dealings = BTreeMap::new(); let corruption_target = 0; dealings.insert( dealer_index, corrupt_dealing(&dealing, corruption_target as usize)?, ); let complaints = generate_complaints( &dealings, associated_data, corruption_target, &sk0, &pk0, Seed::from_rng(&mut rng), ) .expect("failed to generate complaints"); assert_eq!(complaints.len(), 1); for complaint in complaints.values() { complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk0, associated_data, ) .unwrap(); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk0, &rng.gen::<[u8; 32]>(), ) .is_err()); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk1, associated_data, ) .is_err()); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index + 1, corruption_target, &pk0, associated_data, ) .is_err()); } let modified_ephemeral_key = MEGaCiphertextPair { ephemeral_key: EccPoint::hash_to_point(curve, &rng.gen::<[u8; 32]>(), "ad".as_bytes())?, ctexts: vec![ ( EccScalar::random(curve, &mut rng)?, EccScalar::random(curve, &mut rng)?, ), ( EccScalar::random(curve, &mut rng)?, EccScalar::random(curve, &mut rng)?, ), ], }; let bad_key_dealing = IDkgDealingInternal { ciphertext: modified_ephemeral_key.into(), commitment: dealing.commitment.clone(), proof: dealing.proof, }; assert_eq!( complaints .get(&0) .unwrap() .verify( &bad_key_dealing, dealer_index, corruption_target, &pk0, associated_data, ) .unwrap_err(), ThresholdEcdsaError::InvalidProof ); Ok(()) } #[test] fn should_complaint_verification_reject_spurious_complaints() -> ThresholdEcdsaResult<()> { let curve = EccCurveType::K256; let associated_data = b"assoc_data_test"; let mut rng = rand::thread_rng(); let sk = MEGaPrivateKey::generate(curve, &mut rng)?; let pk = sk.public_key()?; let dealer_index = 0; let receiver_index = 0; let threshold = 1; let dealing = IDkgDealingInternal::new( &SecretShares::Random, curve, Seed::from_rng(&mut rng), threshold, &[pk], dealer_index, associated_data, )?; let complaint = IDkgComplaintInternal::new( Seed::from_rng(&mut rng), &dealing, dealer_index, receiver_index, &sk, &pk, associated_data, )?; assert!(complaint .verify(&dealing, dealer_index, 0, &pk, associated_data) .is_err()); Ok(()) }
use rand::Rng; use std::collections::BTreeMap; use tecdsa::*; fn corrupt_ciphertext_single( ctext: &[EccScalar], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<EccScalar>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].curve_type(); let randomizer = EccScalar::one(curve_type); ctext[corruption_target] = ctext[corruption_target].add(&randomizer)?; Ok(ctext) } fn corrupt_ciphertext_pairs( ctext: &[(EccScalar, EccScalar)], corruption_target: usize, ) -> ThresholdEcdsaResult<Vec<(EccScalar, EccScalar)>> { let mut ctext = ctext.to_vec(); let curve_type = ctext[corruption_target].0.curve_type(); let randomizer = EccScalar::one(curve_type); ctext[corruption_target].0 = ctext[corruption_target].0.add(&randomizer)?; Ok(ctext) } fn corrupt_dealing( dealing: &IDkgDealingInternal, corruption_target: usize, ) -> ThresholdEcdsaResult<IDkgDealingInternal> { let ciphertext = match &dealing.ciphertext { MEGaCiphertext::Single(c) => MEGaCiphertext::Single(MEGaCiphertextSingle { ephemeral_key: c.ephemeral_key, ctexts: corrupt_ciphertext_single(&c.ctexts, corruption_target)?, }), MEGaCiphertext::Pairs(c) => MEGaCiphertext::Pairs(MEGaCiphertextPair { ephemeral_key: c.ephemeral_key, ctexts: corrupt_ciphertext_pairs(&c.ctexts, corruption_target)?, }), };
} #[test] fn should_complaint_system_work() -> ThresholdEcdsaResult<()> { let curve = EccCurveType::K256; let associated_data = b"assoc_data_test"; let mut rng = rand::thread_rng(); let sk0 = MEGaPrivateKey::generate(curve, &mut rng)?; let pk0 = sk0.public_key()?; let sk1 = MEGaPrivateKey::generate(curve, &mut rng)?; let pk1 = sk1.public_key()?; let dealer_index = 0; let threshold = 1; let dealing = IDkgDealingInternal::new( &SecretShares::Random, curve, Seed::from_rng(&mut rng), threshold, &[pk0, pk1], dealer_index, associated_data, )?; let mut dealings = BTreeMap::new(); let corruption_target = 0; dealings.insert( dealer_index, corrupt_dealing(&dealing, corruption_target as usize)?, ); let complaints = generate_complaints( &dealings, associated_data, corruption_target, &sk0, &pk0, Seed::from_rng(&mut rng), ) .expect("failed to generate complaints"); assert_eq!(complaints.len(), 1); for complaint in complaints.values() { complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk0, associated_data, ) .unwrap(); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk0, &rng.gen::<[u8; 32]>(), ) .is_err()); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index, corruption_target, &pk1, associated_data, ) .is_err()); assert!(complaint .verify( dealings.get(&dealer_index).unwrap(), dealer_index + 1, corruption_target, &pk0, associated_data, ) .is_err()); } let modified_ephemeral_key = MEGaCiphertextPair { ephemeral_key: EccPoint::hash_to_point(curve, &rng.gen::<[u8; 32]>(), "ad".as_bytes())?, ctexts: vec![ ( EccScalar::random(curve, &mut rng)?, EccScalar::random(curve, &mut rng)?, ), ( EccScalar::random(curve, &mut rng)?, EccScalar::random(curve, &mut rng)?, ), ], }; let bad_key_dealing = IDkgDealingInternal { ciphertext: modified_ephemeral_key.into(), commitment: dealing.commitment.clone(), proof: dealing.proof, }; assert_eq!( complaints .get(&0) .unwrap() .verify( &bad_key_dealing, dealer_index, corruption_target, &pk0, associated_data, ) .unwrap_err(), ThresholdEcdsaError::InvalidProof ); Ok(()) } #[test] fn should_complaint_verification_reject_spurious_complaints() -> ThresholdEcdsaResult<()> { let curve = EccCurveType::K256; let associated_data = b"assoc_data_test"; let mut rng = rand::thread_rng(); let sk = MEGaPrivateKey::generate(curve, &mut rng)?; let pk = sk.public_key()?; let dealer_index = 0; let receiver_index = 0; let threshold = 1; let dealing = IDkgDealingInternal::new( &SecretShares::Random, curve, Seed::from_rng(&mut rng), threshold, &[pk], dealer_index, associated_data, )?; let complaint = IDkgComplaintInternal::new( Seed::from_rng(&mut rng), &dealing, dealer_index, receiver_index, &sk, &pk, associated_data, )?; assert!(complaint .verify(&dealing, dealer_index, 0, &pk, associated_data) .is_err()); Ok(()) }
Ok(IDkgDealingInternal { ciphertext, commitment: dealing.commitment.clone(), proof: dealing.proof.clone(), })
call_expression
[ { "content": "fn dealings(c: &mut Criterion) {\n\n c.bench_function(\"create_dealing(Random, 3/5)\", |b| {\n\n b.iter(|| create_random_dealing(3, 5))\n\n });\n\n\n\n c.bench_function(\"create_dealing(Random, 5/9)\", |b| {\n\n b.iter(|| create_random_dealing(5, 9))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, dealings);\n\ncriterion_main!(benches);\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/dealings.rs", "rank": 0, "score": 314711.5549940218 }, { "content": "fn create_random_dealing(\n\n threshold: u32,\n\n recipients: usize,\n\n) -> Result<IDkgDealingInternal, IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let dealer_index = 0;\n\n\n\n let mut private_keys = Vec::with_capacity(recipients);\n\n\n\n for _i in 0..recipients {\n\n private_keys.push(MEGaPrivateKey::generate(curve, &mut rng)?);\n\n }\n\n\n\n let public_keys = private_keys\n\n .iter()\n\n .map(|k| k.public_key())\n\n .collect::<Result<Vec<_>, _>>()?;\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/dealings.rs", "rank": 1, "score": 279970.38636313315 }, { "content": "#[allow(clippy::needless_range_loop)]\n\nfn random_graph<T: Rng>(num_nodes: usize, degree: usize, rng: &mut T) -> Vec<Vec<usize>> {\n\n let mut distances = vec![vec![num_nodes; num_nodes]; num_nodes];\n\n for i in 0..num_nodes {\n\n distances[i][i] = 0;\n\n let mut indices: Vec<_> = (0..num_nodes).collect();\n\n indices.remove(i);\n\n indices.shuffle(rng);\n\n for j in 0..degree {\n\n distances[i][indices[j]] = 1;\n\n }\n\n }\n\n distances\n\n}\n\n\n", "file_path": "rs/consensus/tests/framework/delivery.rs", "rank": 2, "score": 264455.3079323662 }, { "content": "fn corrupt_signed_dealing(signed_dealing: &mut IDkgMultiSignedDealing) {\n\n let invalidated_internal_dealing_raw = {\n\n let mut internal_dealing = IDkgDealingInternal::deserialize(\n\n &signed_dealing.dealing.idkg_dealing.internal_dealing_raw,\n\n )\n\n .expect(\"failed to deserialize internal dealing\");\n\n match internal_dealing.ciphertext {\n\n MEGaCiphertext::Single(ref mut ctext) => {\n\n ctext.ephemeral_key = EccPoint::generator_g(ctext.ephemeral_key.curve_type())\n\n .expect(\"failed to create generator\");\n\n }\n\n MEGaCiphertext::Pairs(ref mut ctext) => {\n\n ctext.ephemeral_key = EccPoint::generator_g(ctext.ephemeral_key.curve_type())\n\n .expect(\"failed to create generator\");\n\n }\n\n };\n\n internal_dealing\n\n .serialize()\n\n .expect(\"failed to serialize internal dealing\")\n\n };\n\n signed_dealing.dealing.idkg_dealing.internal_dealing_raw = invalidated_internal_dealing_raw;\n\n}\n", "file_path": "rs/crypto/tests/canister_threshold_sigs.rs", "rank": 3, "score": 260638.79930960783 }, { "content": "#[test]\n\nfn create_random_dealing() -> Result<(), IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let (private_keys, public_keys) = gen_private_keys(curve, 5)?;\n\n let threshold = 2;\n\n let dealer_index = 0;\n\n let randomness = Randomness::from(rng.gen::<[u8; 32]>());\n\n\n\n let shares = SecretShares::Random;\n\n\n\n let dealing = create_dealing(\n\n AlgorithmId::ThresholdEcdsaSecp256k1,\n\n &associated_data,\n\n dealer_index,\n\n NumberOfNodes::from(threshold as u32),\n\n &public_keys,\n\n &shares,\n\n randomness,\n\n )?;\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 4, "score": 258145.92464422958 }, { "content": "fn flip_curve(s: &EccScalar) -> EccScalar {\n\n let wrong_curve = match s.curve_type() {\n\n EccCurveType::K256 => EccCurveType::P256,\n\n EccCurveType::P256 => EccCurveType::K256,\n\n };\n\n\n\n let s_bytes = s.serialize();\n\n\n\n // Since ord(k256) > ord(p256) we might have to reduce in that case\n\n EccScalar::from_bytes_wide(wrong_curve, &s_bytes).expect(\"Deserialization failed\")\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 5, "score": 250239.4175201325 }, { "content": "fn leb128(v: &mut Vec<u8>, mut n: usize) {\n\n loop {\n\n let mut b = n & 127;\n\n if n > 127 {\n\n b |= 128\n\n };\n\n v.push(b as u8);\n\n n >>= 7;\n\n if n == 0 {\n\n break;\n\n }\n\n }\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/fs_ni_dkg/src/forward_secure.rs", "rank": 6, "score": 246254.8198990026 }, { "content": "fn hash2curve(c: &mut Criterion) {\n\n let input = \"greetings humans\".as_bytes();\n\n let dst = \"domain sep\".as_bytes();\n\n\n\n c.bench_function(\"hash to curve P256\", |b| {\n\n b.iter(|| {\n\n let _pt =\n\n EccPoint::hash_to_point(EccCurveType::P256, input, dst).expect(\"hash2curve failed\");\n\n })\n\n });\n\n\n\n c.bench_function(\"hash to curve K256\", |b| {\n\n b.iter(|| {\n\n let _pt =\n\n EccPoint::hash_to_point(EccCurveType::K256, input, dst).expect(\"hash2curve failed\");\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, hash2curve);\n\ncriterion_main!(benches);\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/hash2curve.rs", "rank": 7, "score": 244508.64061697404 }, { "content": "fn zk_proofs(c: &mut Criterion) {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let ad = rng.gen::<[u8; 32]>();\n\n\n\n let seed = Seed::from_bytes(&rng.gen::<[u8; 32]>());\n\n\n\n let secret = EccScalar::random(curve, &mut rng).unwrap();\n\n let masking = EccScalar::random(curve, &mut rng).unwrap();\n\n\n\n let pedersen = EccPoint::pedersen(&secret, &masking).unwrap();\n\n let simple = EccPoint::mul_by_g(&secret).unwrap();\n\n\n\n c.bench_function(\"ProofOfEqualOpenings::create\", |b| {\n\n b.iter(|| zk::ProofOfEqualOpenings::create(seed.clone(), &secret, &masking, &ad).unwrap())\n\n });\n\n\n\n let proof = zk::ProofOfEqualOpenings::create(seed.clone(), &secret, &masking, &ad).unwrap();\n\n\n\n c.bench_function(\"ProofOfEqualOpenings::verify\", |b| {\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/zk.rs", "rank": 8, "score": 241227.3904133541 }, { "content": "fn poly_bench(c: &mut Criterion) {\n\n let curve = EccCurveType::K256;\n\n\n\n let mut rng = rand::thread_rng();\n\n\n\n for degree in [8, 16, 32] {\n\n let poly = Polynomial::random(curve, degree, &mut rng).unwrap();\n\n\n\n let x = EccScalar::random(curve, &mut rng).unwrap();\n\n\n\n c.bench_function(\n\n &format!(\"poly evaluate_at({}, degree {})\", curve, degree),\n\n |b| {\n\n b.iter(|| {\n\n let _ = poly.evaluate_at(&x);\n\n })\n\n },\n\n );\n\n\n\n let mut samples = Vec::with_capacity(degree + 1);\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/poly.rs", "rank": 9, "score": 241227.3904133541 }, { "content": "/// Floyd–Warshall algorithm that computes the distance between all pairs of\n\n/// nodes. Return max distance (or diameter) if successful, or None otherwise.\n\nfn distance_vector(distances: &mut Vec<Vec<usize>>) -> Option<usize> {\n\n let n = distances.len();\n\n for k in 0..n {\n\n for i in 0..n {\n\n for j in 0..n {\n\n let distance = distances[i][k] + distances[k][j];\n\n if distance < distances[i][j] {\n\n distances[i][j] = distance;\n\n }\n\n }\n\n }\n\n }\n\n let max_distance = distances\n\n .iter()\n\n .fold(0, |max, v| std::cmp::max(max, *v.iter().max().unwrap()));\n\n let connected = distances.iter().all(|v| v.iter().all(|x| *x < n));\n\n if connected {\n\n Some(max_distance)\n\n } else {\n\n None\n", "file_path": "rs/consensus/tests/framework/delivery.rs", "rank": 10, "score": 239540.56188166648 }, { "content": "/// Auxiliary function to pop a random element from a vector.\n\nfn pop_random<A>(v: &mut Vec<A>, rng: &mut ChaCha8Rng) -> Option<A> {\n\n let v_len = v.len();\n\n if v_len <= 1 {\n\n v.pop()\n\n } else {\n\n let ix = rng.gen_range(0..v.len());\n\n let el = v.remove(ix);\n\n Some(el)\n\n }\n\n}\n", "file_path": "rs/ic_fondue/src/pot/inner.rs", "rank": 11, "score": 239342.60881845135 }, { "content": "fn field_ops(c: &mut Criterion) {\n\n let curve_type = EccCurveType::K256;\n\n\n\n let input = [0xba; 32];\n\n let input_wide = [0xba; 64];\n\n\n\n let fe1 = EccFieldElement::from_bytes(curve_type, &input).expect(\"from_bytes failed\");\n\n let fe2 =\n\n EccFieldElement::from_bytes_wide(curve_type, &input_wide).expect(\"from_bytes_wide failed\");\n\n\n\n c.bench_function(\"field addition\", |b| {\n\n b.iter(|| {\n\n let _ = fe1.add(&fe2).expect(\"Add failed\");\n\n })\n\n });\n\n\n\n c.bench_function(\"field subtraction\", |b| {\n\n b.iter(|| {\n\n let _ = fe1.sub(&fe2).expect(\"Sub failed\");\n\n })\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/benches/field_ops.rs", "rank": 12, "score": 238078.41620185482 }, { "content": "fn unleb128(v: &[u8], cur: &mut usize) -> usize {\n\n let mut n = 0;\n\n let mut m = 1;\n\n loop {\n\n let b = v[*cur] as usize;\n\n *cur += 1;\n\n n += m * (b & 127);\n\n if b < 128 {\n\n break;\n\n }\n\n m *= 128;\n\n }\n\n n\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/fs_ni_dkg/src/forward_secure.rs", "rank": 13, "score": 234630.07562106877 }, { "content": "fn prepare(pool: &mut ConsensusPoolImpl, num: usize) {\n\n let cup = pool\n\n .validated()\n\n .catch_up_package()\n\n .get_by_height(Height::from(0))\n\n .next()\n\n .unwrap();\n\n let parent = cup.content.block.as_ref();\n\n let mut changeset = ChangeSet::new();\n\n for i in 0..num {\n\n let mut block = Block::from_parent(parent);\n\n block.rank = Rank(i as u64);\n\n let ingress = IngressPayload::from(vec![SignedIngressBuilder::new()\n\n .method_payload(vec![0; 128 * 1024])\n\n .build()]);\n\n let xnet = XNetPayload::default();\n\n let self_validating = SelfValidatingPayload::default();\n\n block.payload = Payload::new(\n\n ic_crypto::crypto_hash,\n\n (\n", "file_path": "rs/artifact_pool/benches/load_blocks.rs", "rank": 14, "score": 230906.53086017468 }, { "content": "fn bench_multi_sig_n_signers(criterion: &mut Criterion, num_of_signers: usize) {\n\n let group_name = format!(\"crypto_multi_sig_{}_signers\", num_of_signers);\n\n let group = &mut criterion.benchmark_group(group_name);\n\n\n\n // Nb. We ensure there's always enough nodes for separate verifier and combiner,\n\n // just to eliminate any potential cross-talk.\n\n let env = MultiSigTestEnvironment::new(num_of_signers + 2);\n\n\n\n bench_multi_sig_sign(group, &env);\n\n bench_multi_sig_verify_individual(group, &env);\n\n bench_multi_sig_combine(group, &env, num_of_signers);\n\n bench_multi_sig_verify_combined(group, &env, num_of_signers);\n\n}\n\n\n", "file_path": "rs/crypto/benches/multi_sig.rs", "rank": 15, "score": 227755.92456017356 }, { "content": "/// Extract longest prefix from `blocks` which fits in `max_size`\n\nfn take_prefix(blocks: &mut VecDeque<EncodedBlock>, mut max_size: usize) -> Vec<EncodedBlock> {\n\n let mut result = vec![];\n\n while let Some(next) = blocks.front() {\n\n if next.size_bytes() > max_size {\n\n break;\n\n }\n\n max_size -= next.size_bytes();\n\n result.push(blocks.pop_front().unwrap());\n\n }\n\n result\n\n}\n\n\n", "file_path": "rs/rosetta-api/ledger_canister/src/archive.rs", "rank": 16, "score": 226797.0657953004 }, { "content": "pub fn criterion_benchmark(c: &mut Criterion, ingress_payload_size: usize) {\n\n // we want some diversity wrt. to the numbers that we use in order to force different lengths\n\n // of varint encodings.\n\n let source: u64 = 42;\n\n let receiver: u64 = 1025;\n\n let method_name = \"query test\".to_string();\n\n let method_payload: Vec<u8> = repeat(0x32).take(ingress_payload_size).collect::<Vec<u8>>();\n\n let message_id: u64 = i64::max_value() as u64;\n\n let message_time = SystemTime::now();\n\n\n\n // the buffer that we are going to serialize to/deserialize from\n\n let mut buf = Vec::new();\n\n\n\n // Setup vanilla struct for all encodings that are supported by serde.\n\n let ingress_msg = vanilla::Ingress {\n\n source,\n\n receiver,\n\n method_name: method_name.clone(),\n\n method_payload: method_payload.clone(),\n\n message_id,\n", "file_path": "experimental/encoding_bench/benches/encoding_benchmark.rs", "rank": 17, "score": 223454.65229636937 }, { "content": "fn keygen(num_signers: usize, mut rng: &mut StdRng) -> Vec<(SecretKeyBytes, PublicKeyBytes)> {\n\n (0..num_signers)\n\n .map(|_| multi::keypair_from_rng(&mut rng))\n\n .collect()\n\n}\n", "file_path": "rs/crypto/src/cli/clib/multi_sig/bench.rs", "rank": 18, "score": 222262.50925533782 }, { "content": "fn buf_apply_write(heap: &mut Vec<u8>, write: &Write) {\n\n // match the behavior of write_bytes: copy the i32 `addr` to heap[0;4]\n\n heap[0..4].copy_from_slice(&write.dst.to_le_bytes());\n\n heap[write.dst as usize..(write.dst as usize + write.bytes.len() as usize)]\n\n .copy_from_slice(&write.bytes)\n\n}\n\n\n\nconst TEST_HEAP_SIZE_BYTES: usize = WASM_PAGE_SIZE_BYTES * TEST_NUM_PAGES;\n\nconst TEST_NUM_PAGES: usize = 800;\n\nconst TEST_NUM_WRITES: usize = 2000;\n\nconst WASM_PAGE_SIZE_BYTES: usize = 65536;\n\nconst BYTES_PER_INSTRUCTION: usize = 1;\n\n\n", "file_path": "rs/embedders/tests/wasmtime_random_memory_writes.rs", "rank": 19, "score": 220413.27742647636 }, { "content": "/// Call ingress manager on_state_change, and apply changeset to the ingress\n\n/// pool. Return number of change actions.\n\nfn on_state_change(pool: &mut IngressPoolImpl, manager: &IngressManager) -> usize {\n\n let changeset = manager.on_state_change(pool);\n\n let n = changeset.len();\n\n pool.apply_changeset(changeset);\n\n n\n\n}\n\n\n", "file_path": "rs/ingress_manager/benches/handle_ingress.rs", "rank": 20, "score": 217519.70280690136 }, { "content": "#[test]\n\nfn should_run_idkg_successfully_for_random_dealing() {\n\n let subnet_size = thread_rng().gen_range(1, 10);\n\n let env = CanisterThresholdSigTestEnvironment::new(subnet_size);\n\n\n\n let params = env.params_for_random_sharing(AlgorithmId::ThresholdEcdsaSecp256k1);\n\n run_idkg_and_create_transcript(&params, &env.crypto_components);\n\n}\n\n\n", "file_path": "rs/crypto/tests/canister_threshold_sigs.rs", "rank": 21, "score": 216812.2280725156 }, { "content": "fn read_bytes<'a>(ops: &mut Ops<'a>, len: usize) -> &'a [u8] {\n\n if len < ops.len() {\n\n let (bytes, rest) = ops.split_at(len as usize);\n\n *ops = rest;\n\n bytes\n\n } else {\n\n panic!(\"cannot read {} bytes of a {} byte string\", len, ops.len());\n\n }\n\n}\n\n\n", "file_path": "rs/universal_canister/impl/src/main.rs", "rank": 22, "score": 216238.6589359427 }, { "content": "fn random_bytes<R: Rng>(n: u128, rng: &mut R) -> Vec<u8> {\n\n (0..n).map(|_| rng.gen::<u8>()).collect()\n\n}\n\n\n", "file_path": "rs/crypto/benches/hash.rs", "rank": 23, "score": 216222.76226713718 }, { "content": "fn unecp2(buf: &[u8], cur: &mut usize) -> ECP2 {\n\n let a = ECP2::frombytes(&buf[*cur..]);\n\n *cur = *cur + 1 + 96;\n\n a\n\n}\n\n\n\n/// A forward secure ciphertext\n\n///\n\n/// This is the (C,R,S,Z) tuple of Dec in section 5.2 of\n\n/// <https://eprint.iacr.org/2021/339.pdf>\n\npub struct SingleCiphertext {\n\n pub cc: ECP,\n\n pub rr: ECP,\n\n pub ss: ECP,\n\n pub zz: ECP2,\n\n}\n\n\n\n/// Forward secure ciphertexts\n\n///\n\n/// This is (C,R,S,Z) tuple of section 5.2, with multiple C values,\n\n/// one for each recipent.\n\npub struct Crsz {\n\n pub cc: Vec<Vec<ECP>>,\n\n pub rr: Vec<ECP>,\n\n pub ss: Vec<ECP>,\n\n pub zz: Vec<ECP2>,\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/fs_ni_dkg/src/forward_secure.rs", "rank": 24, "score": 214721.43648759997 }, { "content": "fn unecp(buf: &[u8], cur: &mut usize) -> ECP {\n\n let a = ECP::frombytes(&buf[*cur..]);\n\n *cur = *cur + 1 + 48;\n\n a\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/fs_ni_dkg/src/forward_secure.rs", "rank": 25, "score": 214721.43648759997 }, { "content": "/// Returns a mutable reference to the global state.\n\n///\n\n/// This should only be called once the global state has been initialized, which\n\n/// happens in `canister_init` or `canister_post_upgrade`.\n\nfn governance_mut() -> &'static mut Governance {\n\n unsafe { GOVERNANCE.as_mut().expect(\"Canister not initialized!\") }\n\n}\n\n\n", "file_path": "rs/nns/governance/canister/canister.rs", "rank": 26, "score": 214115.30199894065 }, { "content": "fn registry_mut() -> &'static mut Registry {\n\n unsafe {\n\n if let Some(g) = &mut REGISTRY {\n\n g\n\n } else {\n\n REGISTRY = Some(Registry::new());\n\n registry_mut()\n\n }\n\n }\n\n}\n\n\n", "file_path": "rs/registry/canister/canister/canister.rs", "rank": 27, "score": 214115.30199894065 }, { "content": "/// Returns a mutable reference to the global state.\n\n///\n\n/// This should only be called once the global state has been initialized, which\n\n/// happens in `canister_init` or `canister_post_upgrade`.\n\nfn governance_mut() -> &'static mut Governance {\n\n unsafe { GOVERNANCE.as_mut().expect(\"Canister not initialized!\") }\n\n}\n\n\n", "file_path": "rs/sns/governance/canister/canister.rs", "rank": 28, "score": 214115.30199894065 }, { "content": "fn gtc_mut() -> &'static mut Gtc {\n\n unsafe {\n\n if let Some(gtc) = &mut GTC {\n\n gtc\n\n } else {\n\n GTC = Some(Gtc::default());\n\n gtc_mut()\n\n }\n\n }\n\n}\n\n\n", "file_path": "rs/nns/gtc/canister/canister.rs", "rank": 29, "score": 214115.30199894065 }, { "content": "/// Generate a random `IDkgId`.\n\n///\n\n/// Note: There is a proptest strategy for `IDkgId` which is useful in many\n\n/// circumstances but cumbersome in others. Please use the appropriate method\n\n/// for each circumstance.\n\npub fn random_dkg_id<R: Rng>(rng: &mut R) -> IDkgId {\n\n let instance_id = Height::from(rng.gen::<u64>());\n\n let subnet_id = SubnetId::from(PrincipalId::new_subnet_test_id(rng.gen::<u64>()));\n\n IDkgId {\n\n instance_id,\n\n subnet_id,\n\n }\n\n}\n", "file_path": "rs/crypto/test_utils/src/dkg.rs", "rank": 30, "score": 213686.75026370253 }, { "content": "#[test]\n\nfn should_use_unique_separator_byte_per_randomness_purpose() {\n\n let mut set = BTreeSet::new();\n\n\n\n // ensure separator bytes are unique\n\n assert!(set.insert(COMMITTEE_SAMPLING_SEPARATOR_BYTE));\n\n assert!(set.insert(BLOCKMAKER_RANKING_SEPARATOR_BYTE));\n\n assert!(set.insert(DKG_COMMITTEE_SAMPLING_SEPARATOR_BYTE));\n\n assert!(set.insert(EXECUTION_THREAD_SEPARATOR_BYTE));\n\n\n\n // ensure there is a separator for each purpose\n\n assert_eq!(set.len(), RandomnessPurpose::COUNT);\n\n}\n\n\n", "file_path": "rs/crypto/src/prng/tests.rs", "rank": 31, "score": 213290.56529639193 }, { "content": "#[test]\n\nfn should_run_idkg_successfully_for_reshare_of_random_dealing() {\n\n let subnet_size = thread_rng().gen_range(1, 10);\n\n let env = CanisterThresholdSigTestEnvironment::new(subnet_size);\n\n\n\n let initial_params = env.params_for_random_sharing(AlgorithmId::ThresholdEcdsaSecp256k1);\n\n let initial_transcript =\n\n run_idkg_and_create_transcript(&initial_params, &env.crypto_components);\n\n\n\n let reshare_params = build_params_from_previous(\n\n initial_params,\n\n IDkgTranscriptOperation::ReshareOfMasked(initial_transcript),\n\n );\n\n run_idkg_and_create_transcript(&reshare_params, &env.crypto_components);\n\n}\n\n\n", "file_path": "rs/crypto/tests/canister_threshold_sigs.rs", "rank": 32, "score": 213238.9754380003 }, { "content": "fn random_subset(\n\n shares: &BTreeMap<NodeIndex, ThresholdEcdsaSigShareInternal>,\n\n include: usize,\n\n) -> BTreeMap<NodeIndex, ThresholdEcdsaSigShareInternal> {\n\n assert!(include <= shares.len());\n\n\n\n let mut rng = rand::thread_rng();\n\n let mut result = BTreeMap::new();\n\n\n\n let keys = shares.keys().collect::<Vec<_>>();\n\n\n\n while result.len() != include {\n\n let key_to_add = keys[rng.gen::<usize>() % keys.len()];\n\n\n\n if !result.contains_key(key_to_add) {\n\n result.insert(*key_to_add, shares[key_to_add].clone());\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/protocol.rs", "rank": 33, "score": 213189.58910196478 }, { "content": "// Looks for the data section and if it is present, converts it to a vector of\n\n// tuples (heap offset, bytes) and then deletes the section.\n\nfn get_data(sections: &mut Vec<Section>) -> Vec<(usize, Vec<u8>)> {\n\n let mut res = Vec::new();\n\n let mut data_section_idx = sections.len();\n\n for (i, section) in sections.iter_mut().enumerate() {\n\n if let Section::Data(section) = section {\n\n data_section_idx = i;\n\n res = section\n\n .entries_mut()\n\n .iter_mut()\n\n .map(|segment| {\n\n let offset = match segment.offset() {\n\n None => panic!(\"no offset found for the data segment\"),\n\n Some(exp) => {\n\n match exp.code() {\n\n [\n\n Instruction::I32Const(val),\n\n Instruction::End\n\n ] => ((*val) as u32) as usize, // Convert via `u32` to avoid 64-bit sign-extension.\n\n _ => panic!(\n\n \"complex initialization expressions for data segments are not supported!\"\n", "file_path": "rs/embedders/src/wasm_utils/instrumentation.rs", "rank": 35, "score": 213160.19396878715 }, { "content": "#[cfg(feature = \"profiler\")]\n\nfn frames_post_processor() -> impl Fn(&mut pprof::Frames) {\n\n let thread_rename = [\n\n (Regex::new(r\"^rocksdb:bg\\d*$\").unwrap(), \"rocksdb:bg\"),\n\n (Regex::new(r\"^rocksdb:low\\d*$\").unwrap(), \"rocksdb:low\"),\n\n (Regex::new(r\"^rocksdb:high\\d*$\").unwrap(), \"rocksdb:high\"),\n\n (Regex::new(r\"^snap sender\\d*$\").unwrap(), \"snap-sender\"),\n\n (Regex::new(r\"^apply-\\d*$\").unwrap(), \"apply\"),\n\n (Regex::new(r\"^future-poller-\\d*$\").unwrap(), \"future-poller\"),\n\n ];\n\n\n\n move |frames| {\n\n for (regex, name) in thread_rename.iter() {\n\n if regex.is_match(&frames.thread_name) {\n\n frames.thread_name = name.to_string();\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "rs/replica/src/main.rs", "rank": 36, "score": 212459.3082378002 }, { "content": "// Generate random data structures:\n\n// Alternatively we could implement Distribution for all of these types.\n\n// Deriving Rand may be enough for many. See: https://stackoverflow.com/questions/48490049/how-do-i-choose-a-random-value-from-an-enum\n\npub fn random_height(rng: &mut ChaCha20Rng) -> Height {\n\n Height::from(rng.gen::<u64>())\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/threshold/ni_dkg/tests/fixtures.rs", "rank": 37, "score": 211225.61625886746 }, { "content": "#[test]\n\nfn create_mult_dealing() -> Result<(), IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let (private_keys, public_keys) = gen_private_keys(curve, 5)?;\n\n let threshold = 2;\n\n let dealer_index = 0;\n\n let randomness = Randomness::from(rng.gen::<[u8; 32]>());\n\n\n\n let lhs = EccScalar::random(curve, &mut rng)?;\n\n let rhs = EccScalar::random(curve, &mut rng)?;\n\n let mask = EccScalar::random(curve, &mut rng)?;\n\n let shares = SecretShares::UnmaskedTimesMasked(lhs, (rhs, mask));\n\n\n\n let dealing = create_dealing(\n\n AlgorithmId::ThresholdEcdsaSecp256k1,\n\n &associated_data,\n\n dealer_index,\n\n NumberOfNodes::from(threshold as u32),\n\n &public_keys,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 38, "score": 210532.04763151077 }, { "content": "fn reset_mem_protection(base: *mut u8, len: usize, new_permissions: libc::c_int) {\n\n unsafe {\n\n let page_size = PAGE_SIZE as u64;\n\n\n\n // find the aligned base address to reset the permissions from\n\n let aligned_base = (base as u64).prev_multiple_of(&page_size);\n\n let total_len = (base as u64 + len as u64) - aligned_base;\n\n\n\n let result = mprotect(\n\n aligned_base as *mut c_void,\n\n total_len as usize,\n\n new_permissions,\n\n );\n\n\n\n assert_eq!(\n\n result,\n\n 0,\n\n \"mprotect failed: {}\",\n\n std::io::Error::last_os_error()\n\n );\n", "file_path": "rs/cow_state/src/lib.rs", "rank": 39, "score": 210251.3508560207 }, { "content": "fn gen_private_keys(\n\n curve: EccCurveType,\n\n cnt: usize,\n\n) -> Result<(Vec<MEGaPrivateKey>, Vec<MEGaPublicKey>), ThresholdEcdsaError> {\n\n let mut rng = rand::thread_rng();\n\n let mut private_keys = Vec::with_capacity(cnt);\n\n\n\n for _i in 0..cnt {\n\n private_keys.push(MEGaPrivateKey::generate(curve, &mut rng)?);\n\n }\n\n\n\n let public_keys = private_keys\n\n .iter()\n\n .map(|k| k.public_key())\n\n .collect::<Result<Vec<_>, _>>()?;\n\n\n\n Ok((private_keys, public_keys))\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 42, "score": 209749.3794909046 }, { "content": "// Generate random data structures:\n\n// Alternatively we could implement Distribution for all of these types.\n\n// Deriving Rand may be enough for many. See: https://stackoverflow.com/questions/48490049/how-do-i-choose-a-random-value-from-an-enum\n\npub fn random_height(rng: &mut ChaCha20Rng) -> Height {\n\n Height::from(rng.gen::<u64>())\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/vault/test_utils/ni_dkg/fixtures.rs", "rank": 43, "score": 208812.35924266177 }, { "content": "#[test]\n\nfn create_reshare_unmasked_dealing() -> Result<(), IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let (private_keys, public_keys) = gen_private_keys(curve, 5)?;\n\n let threshold = 2;\n\n let dealer_index = 0;\n\n let randomness = Randomness::from(rng.gen::<[u8; 32]>());\n\n\n\n let secret = EccScalar::random(curve, &mut rng)?;\n\n let shares = SecretShares::ReshareOfUnmasked(secret);\n\n\n\n let dealing = create_dealing(\n\n AlgorithmId::ThresholdEcdsaSecp256k1,\n\n &associated_data,\n\n dealer_index,\n\n NumberOfNodes::from(threshold as u32),\n\n &public_keys,\n\n &shares,\n\n randomness,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 44, "score": 208106.01852365077 }, { "content": "#[test]\n\nfn invalid_create_dealing_requests() -> Result<(), IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let (private_keys, public_keys) = gen_private_keys(curve, 5)?;\n\n let threshold = 2;\n\n let dealer_index = 0;\n\n let randomness = Randomness::from(rng.gen::<[u8; 32]>());\n\n\n\n let shares = SecretShares::Random;\n\n\n\n // invalid threshold\n\n assert!(create_dealing(\n\n AlgorithmId::ThresholdEcdsaSecp256k1,\n\n &associated_data,\n\n dealer_index,\n\n NumberOfNodes::from(private_keys.len() as u32 + 1),\n\n &public_keys,\n\n &shares,\n\n randomness,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 45, "score": 208106.01852365077 }, { "content": "#[test]\n\nfn create_reshare_masked_dealings() -> Result<(), IdkgCreateDealingInternalError> {\n\n let curve = EccCurveType::K256;\n\n let mut rng = rand::thread_rng();\n\n let associated_data = vec![1, 2, 3];\n\n let (private_keys, public_keys) = gen_private_keys(curve, 5)?;\n\n let threshold = 2;\n\n let dealer_index = 0;\n\n let randomness = Randomness::from(rng.gen::<[u8; 32]>());\n\n\n\n let secret = EccScalar::random(curve, &mut rng)?;\n\n let mask = EccScalar::random(curve, &mut rng)?;\n\n let shares = SecretShares::ReshareOfMasked(secret, mask);\n\n\n\n let dealing = create_dealing(\n\n AlgorithmId::ThresholdEcdsaSecp256k1,\n\n &associated_data,\n\n dealer_index,\n\n NumberOfNodes::from(threshold as u32),\n\n &public_keys,\n\n &shares,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/dealings.rs", "rank": 46, "score": 208106.01852365077 }, { "content": "// Helper function to perform a memory read `base_address[count]` and print additional information.\n\npub fn memory_read<T>(base_address: *mut T, count: usize) -> T\n\nwhere\n\n T: std::fmt::Display + std::cmp::PartialEq,\n\n{\n\n let page_num = page_num(base_address, count);\n\n let address = unsafe { base_address.offset(count as isize) };\n\n let value = unsafe { std::ptr::read(address) };\n\n info!(\n\n \"READ 0x{:x} page({}) memory[{}] = {}\",\n\n address as u64, page_num, count, value\n\n );\n\n value\n\n}\n\n\n", "file_path": "experimental/rs/memory_area/tests/test_utils.rs", "rank": 47, "score": 207453.0845367193 }, { "content": "fn reset_mem_protection(base: *mut u8, len: usize, new_permissions: libc::c_int) {\n\n unsafe {\n\n let result = mprotect(base as *mut c_void, len, new_permissions);\n\n\n\n assert_eq!(\n\n result,\n\n 0,\n\n \"mprotect failed: {}\",\n\n std::io::Error::last_os_error()\n\n );\n\n }\n\n}\n\n\n", "file_path": "rs/cow_state/tests/cow_state.rs", "rank": 48, "score": 207453.0845367193 }, { "content": "// Return the page number of the page that `base_address[count]` falls on\n\npub fn page_num<T>(base_address: *mut T, count: usize) -> u64 {\n\n let address = unsafe { base_address.offset(count as isize) };\n\n let address_page_boundary = address as u64 & !(*memory_area::PAGE_SIZE as u64 - 1);\n\n (address_page_boundary - base_address as u64) / *memory_area::PAGE_SIZE as u64\n\n}\n\n\n", "file_path": "experimental/rs/memory_area/tests/test_utils.rs", "rank": 49, "score": 207453.0845367193 }, { "content": "fn no_op(_: *mut ()) {}\n", "file_path": "rs/rust_canisters/dfn_core/src/api.rs", "rank": 50, "score": 207049.72711434859 }, { "content": "pub fn random_algorithm_id(rng: &mut ChaCha20Rng) -> AlgorithmId {\n\n AlgorithmId::iter()\n\n .choose(rng)\n\n .expect(\"Could not choose an AlgorithmId\")\n\n}\n\n\n\n/// A single node with its CSP\n\npub struct MockNode {\n\n pub node_id: NodeId,\n\n pub csp: Csp<ChaCha20Rng, VolatileSecretKeyStore, VolatileSecretKeyStore>,\n\n}\n\nimpl MockNode {\n\n pub fn random(rng: &mut ChaCha20Rng) -> Self {\n\n let node_id = node_test_id(rng.gen::<u64>());\n\n Self::from_node_id(rng, node_id)\n\n }\n\n pub fn from_node_id(rng: &mut ChaCha20Rng, node_id: NodeId) -> Self {\n\n let csprng = ChaCha20Rng::from_seed(rng.gen::<[u8; 32]>());\n\n let csp = Csp::of(csprng, VolatileSecretKeyStore::new());\n\n Self { node_id, csp }\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/threshold/ni_dkg/tests/fixtures.rs", "rank": 51, "score": 206475.08605481742 }, { "content": "pub fn random_subnet_id(rng: &mut ChaCha20Rng) -> SubnetId {\n\n subnet_test_id(rng.gen::<u64>())\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/threshold/ni_dkg/tests/fixtures.rs", "rank": 52, "score": 206475.08605481742 }, { "content": "fn encrypt_and_commit_single_polynomial(\n\n poly: &Polynomial,\n\n num_coefficients: usize,\n\n recipients: &[MEGaPublicKey],\n\n dealer_index: NodeIndex,\n\n associated_data: &[u8],\n\n seed: Seed,\n\n) -> ThresholdEcdsaResult<(MEGaCiphertext, PolynomialCommitment)> {\n\n let curve = poly.curve_type();\n\n\n\n let mut plaintexts = Vec::with_capacity(recipients.len());\n\n\n\n for (idx, _recipient) in recipients.iter().enumerate() {\n\n let scalar = EccScalar::from_node_index(curve, idx as NodeIndex);\n\n let v_s = poly.evaluate_at(&scalar)?;\n\n plaintexts.push(v_s)\n\n }\n\n\n\n let ciphertext = MEGaCiphertextSingle::encrypt(\n\n seed,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/src/dealings.rs", "rank": 53, "score": 206468.42713343204 }, { "content": "fn encrypt_and_commit_pair_of_polynomials(\n\n values: &Polynomial,\n\n mask: &Polynomial,\n\n num_coefficients: usize,\n\n recipients: &[MEGaPublicKey],\n\n dealer_index: NodeIndex,\n\n associated_data: &[u8],\n\n seed: Seed,\n\n) -> ThresholdEcdsaResult<(MEGaCiphertext, PolynomialCommitment)> {\n\n let curve = values.curve_type();\n\n\n\n let mut plaintexts = Vec::with_capacity(recipients.len());\n\n\n\n for (idx, _recipient) in recipients.iter().enumerate() {\n\n let scalar = EccScalar::from_node_index(curve, idx as NodeIndex);\n\n let v_s = values.evaluate_at(&scalar)?;\n\n let m_s = mask.evaluate_at(&scalar)?;\n\n plaintexts.push((v_s, m_s))\n\n }\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/src/dealings.rs", "rank": 54, "score": 206468.42713343204 }, { "content": "/// Create a dealing for threshold ECDSA\n\npub fn create_dealing(\n\n algorithm_id: ic_types::crypto::AlgorithmId,\n\n associated_data: &[u8],\n\n dealer_index: NodeIndex,\n\n threshold: NumberOfNodes,\n\n recipients: &[MEGaPublicKey],\n\n shares: &SecretShares,\n\n randomness: Randomness,\n\n) -> Result<IDkgDealingInternal, IdkgCreateDealingInternalError> {\n\n let curve = match algorithm_id {\n\n AlgorithmId::ThresholdEcdsaSecp256k1 => Ok(EccCurveType::K256),\n\n _ => Err(IdkgCreateDealingInternalError::UnsupportedAlgorithm),\n\n }?;\n\n\n\n let seed = Seed::from_randomness(&randomness);\n\n\n\n IDkgDealingInternal::new(\n\n shares,\n\n curve,\n\n seed,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/src/lib.rs", "rank": 55, "score": 205685.3403094534 }, { "content": "/// Makes `count` input queue reservations for responses from `remote`.\n\nfn make_input_queue_reservations(canister: &mut CanisterState, count: usize, remote: CanisterId) {\n\n for _ in 0..count {\n\n canister\n\n .push_output_request(test_request(*LOCAL_CANISTER, remote))\n\n .unwrap();\n\n }\n\n canister.output_into_iter().count();\n\n}\n\n\n", "file_path": "rs/messaging/src/routing/stream_handler/tests.rs", "rank": 56, "score": 205600.04057256615 }, { "content": "pub fn random_bls12_381_scalar<R: RngCore>(rng: &mut R) -> Scalar {\n\n loop {\n\n let mut repr = [0u64; 4];\n\n for r in repr.iter_mut() {\n\n *r = rng.next_u64();\n\n }\n\n\n\n /*\n\n Since the modulus is 255 bits, we clear out the most significant bit to\n\n reduce number of repetitions for the rejection sampling.\n\n\n\n (This also matches the logic used in the old version of zcrypto/pairing,\n\n which we are attempting to maintain bit-for-bit compatability with)\n\n */\n\n repr[3] &= 0xffffffffffffffff >> 1;\n\n\n\n let mut repr8 = [0u8; 32];\n\n repr8[..8].copy_from_slice(&repr[0].to_le_bytes());\n\n repr8[8..16].copy_from_slice(&repr[1].to_le_bytes());\n\n repr8[16..24].copy_from_slice(&repr[2].to_le_bytes());\n", "file_path": "rs/crypto/internal/crypto_lib/bls12_381/common/src/hash.rs", "rank": 57, "score": 205585.89040082094 }, { "content": "/// Callback for handling reject responses from \"handle_request\".\n\nfn on_reject(_env: *mut ()) {\n\n METRICS.with(|m| m.borrow_mut().reject_responses += 1);\n\n}\n\n\n", "file_path": "rs/rust_canisters/xnet_test/src/main.rs", "rank": 58, "score": 204456.7231081201 }, { "content": "/// Callback for handling replies from \"handle_request\".\n\nfn on_reply(_env: *mut ()) {\n\n let (reply, _) =\n\n candid::Decode!(&api::arg_data()[..], Reply, Vec<u8>).expect(\"failed to decode response\");\n\n let elapsed = Duration::from_nanos((time_nanos() - reply.time_nanos) as u64);\n\n METRICS.with(|m| m.borrow_mut().latency_distribution.observe(elapsed));\n\n}\n\n\n", "file_path": "rs/rust_canisters/xnet_test/src/main.rs", "rank": 59, "score": 204456.7231081201 }, { "content": "pub fn random_subnet_id(rng: &mut ChaCha20Rng) -> SubnetId {\n\n subnet_test_id(rng.gen::<u64>())\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/vault/test_utils/ni_dkg/fixtures.rs", "rank": 60, "score": 204225.0929206239 }, { "content": "pub fn random_algorithm_id(rng: &mut ChaCha20Rng) -> AlgorithmId {\n\n AlgorithmId::iter()\n\n .choose(rng)\n\n .expect(\"Could not choose an AlgorithmId\")\n\n}\n\n\n\n/// A single node with its CSP\n\npub struct MockNode {\n\n pub node_id: NodeId,\n\n pub fs_key_id: KeyId,\n\n pub csp_vault: Arc<dyn CspVault>,\n\n}\n\nimpl MockNode {\n\n pub fn random(rng: &mut ChaCha20Rng, csp_vault_factory: fn() -> Arc<dyn CspVault>) -> Self {\n\n let node_id = node_test_id(rng.gen::<u64>());\n\n Self::from_node_id(node_id, csp_vault_factory)\n\n }\n\n pub fn from_node_id(node_id: NodeId, csp_vault_factory: fn() -> Arc<dyn CspVault>) -> Self {\n\n let csp_vault = csp_vault_factory();\n\n Self {\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/vault/test_utils/ni_dkg/fixtures.rs", "rank": 61, "score": 204225.0929206239 }, { "content": "fn linear_20k(c: &mut Criterion) {\n\n let secs = 1;\n\n let mut gov = Governance::new(\n\n fixture_for_scale(20_000, true),\n\n Box::new(MockEnvironment { secs }),\n\n Box::new(MockLedger {}),\n\n );\n\n c.bench_function(\"linear 20k\", |b| {\n\n b.iter(|| make_and_process_proposal(&mut gov))\n\n });\n\n}\n\n\n", "file_path": "rs/nns/governance/benches/scale.rs", "rank": 62, "score": 203394.18264748965 }, { "content": "fn tree_20k(c: &mut Criterion) {\n\n let secs = 1;\n\n let mut gov = Governance::new(\n\n fixture_for_scale(20_000, false),\n\n Box::new(MockEnvironment { secs }),\n\n Box::new(MockLedger {}),\n\n );\n\n c.bench_function(\"tree 20k\", |b| {\n\n b.iter(|| make_and_process_proposal(&mut gov))\n\n });\n\n}\n\n\n", "file_path": "rs/nns/governance/benches/scale.rs", "rank": 63, "score": 203394.18264748965 }, { "content": "fn tree_200k(c: &mut Criterion) {\n\n let secs = 1;\n\n let mut gov = Governance::new(\n\n fixture_for_scale(200_000, false),\n\n Box::new(MockEnvironment { secs }),\n\n Box::new(MockLedger {}),\n\n );\n\n c.bench_function(\"tree 200k\", |b| {\n\n b.iter(|| make_and_process_proposal(&mut gov))\n\n });\n\n}\n\n\n", "file_path": "rs/nns/governance/benches/scale.rs", "rank": 64, "score": 203394.18264748965 }, { "content": "fn linear_200k(c: &mut Criterion) {\n\n let secs = 1;\n\n let mut gov = Governance::new(\n\n fixture_for_scale(200_000, true),\n\n Box::new(MockEnvironment { secs }),\n\n Box::new(MockLedger {}),\n\n );\n\n c.bench_function(\"linear 200k\", |b| {\n\n b.iter(|| make_and_process_proposal(&mut gov))\n\n });\n\n}\n\n\n", "file_path": "rs/nns/governance/benches/scale.rs", "rank": 65, "score": 203394.18264748965 }, { "content": "fn mangle_json_value<F>(value: &mut Value, f: &mut F)\n\nwhere\n\n F: FnMut(&Value) -> Option<Value>,\n\n{\n\n if let Some(v) = f(value) {\n\n *value = v;\n\n } else if let Some(a) = value.as_array_mut() {\n\n a.iter_mut().for_each(|mut v| mangle_json_value(&mut v, f));\n\n } else if let Some(o) = value.as_object_mut() {\n\n o.iter_mut()\n\n .for_each(|(_, mut v)| mangle_json_value(&mut v, f));\n\n }\n\n}\n\n\n", "file_path": "rs/registry/regedit/src/normalization.rs", "rank": 66, "score": 202470.6361883576 }, { "content": "/// Verify a dealing using public information\n\n///\n\n/// Verify that the dealing has the expected type of ciphertext\n\n/// and commitment (depending on the type of dealing)\n\n///\n\n/// When CRP-1158 is completed this will also verify the zero\n\n/// knowledge proofs\n\npub fn publicly_verify_dealing(\n\n algorithm_id: AlgorithmId,\n\n dealing: &IDkgDealingInternal,\n\n transcript_type: &IDkgTranscriptOperationInternal,\n\n reconstruction_threshold: NumberOfNodes,\n\n dealer_index: NodeIndex,\n\n number_of_receivers: NumberOfNodes,\n\n associated_data: &[u8],\n\n) -> Result<(), IDkgVerifyDealingInternalError> {\n\n let curve = match algorithm_id {\n\n AlgorithmId::ThresholdEcdsaSecp256k1 => Ok(EccCurveType::K256),\n\n _ => Err(IDkgVerifyDealingInternalError::UnsupportedAlgorithm),\n\n }?;\n\n\n\n dealing\n\n .publicly_verify(\n\n curve,\n\n transcript_type,\n\n reconstruction_threshold,\n\n dealer_index,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/src/lib.rs", "rank": 67, "score": 202418.06060312584 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn privately_verify_dealing(\n\n algorithm_id: AlgorithmId,\n\n dealing: &IDkgDealingInternal,\n\n private_key: &MEGaPrivateKey,\n\n public_key: &MEGaPublicKey,\n\n associated_data: &[u8],\n\n dealer_index: NodeIndex,\n\n recipient_index: NodeIndex,\n\n) -> Result<(), IDkgVerifyDealingInternalError> {\n\n let curve = match algorithm_id {\n\n AlgorithmId::ThresholdEcdsaSecp256k1 => Ok(EccCurveType::K256),\n\n _ => Err(IDkgVerifyDealingInternalError::UnsupportedAlgorithm),\n\n }?;\n\n\n\n dealing\n\n .privately_verify(\n\n curve,\n\n private_key,\n\n public_key,\n\n associated_data,\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/src/lib.rs", "rank": 68, "score": 202396.96367934466 }, { "content": "pub fn random_ni_dkg_tag(rng: &mut ChaCha20Rng) -> NiDkgTag {\n\n NiDkgTag::iter()\n\n .choose(rng)\n\n .expect(\"Could not choose a NiDkgTag\")\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/threshold/ni_dkg/tests/fixtures.rs", "rank": 69, "score": 202050.58748415834 }, { "content": "pub fn random_ni_dkg_id(rng: &mut ChaCha20Rng) -> NiDkgId {\n\n NiDkgId {\n\n start_block_height: random_height(rng),\n\n dealer_subnet: random_subnet_id(rng),\n\n target_subnet: NiDkgTargetSubnet::Local,\n\n dkg_tag: random_ni_dkg_tag(rng),\n\n }\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/threshold/ni_dkg/tests/fixtures.rs", "rank": 70, "score": 202050.58748415834 }, { "content": "fn random_writes(heap_size: usize, num_writes: usize) -> impl Strategy<Value = Vec<Write>> {\n\n // Start generating writes at address 4096 (or higher) to avoid generating\n\n // writes to the first OS page. This is because we must first copy the\n\n // offset from the payload to Wasm memory. We store the 4-byte offset at\n\n // addr=0, hence dirtying the first OS page.\n\n let write_strategy = (4096..heap_size).prop_flat_map(move |dst| {\n\n let dst = dst as u32;\n\n // up to 128 bytes\n\n let remain = (heap_size - dst as usize) % 128;\n\n prop::collection::vec(any::<u8>(), 0..=remain).prop_map(move |bytes| Write { dst, bytes })\n\n });\n\n prop::collection::vec(write_strategy, 1..num_writes)\n\n}\n\n\n", "file_path": "rs/embedders/tests/wasmtime_random_memory_writes.rs", "rank": 71, "score": 201798.85787527214 }, { "content": "fn test_resharing_dealing(seed: Randomness) {\n\n let mut rng = ChaChaRng::from_seed(seed.get());\n\n\n\n let state = StateWithThresholdKey::random(&mut rng);\n\n let state = StateWithEphemeralKeys::random(&mut rng, state);\n\n let state = StateWithResharedDealings::random(&mut rng, state);\n\n state\n\n .verify_dealings()\n\n .expect(\"Resharing dealings do not verify\");\n\n // Verify that if the public coefficients are altered, verification fails:\n\n {\n\n let mut state = state;\n\n let current_first_term = state.initial_state.public_coefficients.coefficients[0];\n\n state.initial_state.public_coefficients.coefficients[0] = PublicKeyBytes::from(\n\n if current_first_term == PublicKeyBytes::from(PublicKey(G2Projective::identity())) {\n\n PublicKey(G2Projective::generator())\n\n } else {\n\n PublicKey(G2Projective::identity())\n\n },\n\n );\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/bls12_381/src/dkg/secp256k1/dealing/test_resharing.rs", "rank": 72, "score": 201678.75562943684 }, { "content": "// Helper function to perform a memory write `base_address[count] = val` followed by memory read\n\n// `base_address[count]` and print additional information.\n\npub fn memory_write_read<T>(memory: *mut T, count: usize, val: T)\n\nwhere\n\n T: std::fmt::Display + std::fmt::Debug + PartialEq + Copy,\n\n{\n\n let page_num = page_num(memory, count);\n\n let address = unsafe { memory.offset(count as isize) };\n\n info!(\n\n \"WRITE 0x{:x} page({}) memory[{}] <- {}\",\n\n address as u64, page_num, count, val\n\n );\n\n unsafe {\n\n std::ptr::write(address as *mut T, val);\n\n }\n\n let read_val = memory_read(memory, count);\n\n assert_eq!(val, read_val);\n\n}\n\n\n", "file_path": "experimental/rs/memory_area/tests/test_utils.rs", "rank": 73, "score": 201660.9597078296 }, { "content": "fn bench_hash(criterion: &mut Criterion) {\n\n let group = &mut criterion.benchmark_group(\"crypto_hash\");\n\n\n\n group.sample_size(20);\n\n bench_sha256(group, \"sha256_32_B\", 32);\n\n bench_sha256(group, \"sha256_1_KiB\", KIBIBYTE);\n\n bench_sha256(group, \"sha256_1_MiB\", MEBIBYTE);\n\n bench_sha256_chunked(group, \"sha256_1_MiB_in_1_KiB_chunks\", MEBIBYTE, KIBIBYTE);\n\n bench_sha256_chunked(\n\n group,\n\n \"sha256_1_MiB_in_16_KiB_chunks\",\n\n MEBIBYTE,\n\n 16 * KIBIBYTE,\n\n );\n\n\n\n group.sample_size(10);\n\n group.measurement_time(Duration::from_secs(7));\n\n bench_sha256(group, \"sha256_10_MiB\", 10 * MEBIBYTE);\n\n bench_sha256_chunked(\n\n group,\n", "file_path": "rs/crypto/benches/hash.rs", "rank": 74, "score": 200679.47616224937 }, { "content": "pub fn random_ni_dkg_id(rng: &mut ChaCha20Rng) -> NiDkgId {\n\n NiDkgId {\n\n start_block_height: random_height(rng),\n\n dealer_subnet: random_subnet_id(rng),\n\n target_subnet: NiDkgTargetSubnet::Local,\n\n dkg_tag: random_ni_dkg_tag(rng),\n\n }\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/vault/test_utils/ni_dkg/fixtures.rs", "rank": 75, "score": 199947.83348166937 }, { "content": "pub fn random_ni_dkg_tag(rng: &mut ChaCha20Rng) -> NiDkgTag {\n\n NiDkgTag::iter()\n\n .choose(rng)\n\n .expect(\"Could not choose a NiDkgTag\")\n\n}\n", "file_path": "rs/crypto/internal/crypto_service_provider/src/vault/test_utils/ni_dkg/fixtures.rs", "rank": 76, "score": 199947.83348166937 }, { "content": "pub fn get_random_node_endpoint<'a>(handle: &'a IcHandle, rng: &mut ChaCha8Rng) -> &'a IcEndpoint {\n\n handle.as_permutation(rng).next().unwrap()\n\n}\n\n\n", "file_path": "rs/tests/src/util.rs", "rank": 77, "score": 198838.62352465128 }, { "content": "fn criterion_calls(criterion: &mut Criterion) {\n\n let bench_replica = BenchReplica::new();\n\n let mut id: u64 = 0;\n\n\n\n let registry = Arc::new(MockRegistryClient::new());\n\n\n\n let subnet_type = SubnetType::Application;\n\n let subnet_config = SubnetConfigs::default().own_subnet_config(subnet_type);\n\n let cycles_account_manager = Arc::new(CyclesAccountManager::new(\n\n subnet_config.scheduler_config.max_instructions_per_message,\n\n subnet_type,\n\n bench_replica.replica_config.subnet_id,\n\n SubnetConfigs::default()\n\n .own_subnet_config(subnet_type)\n\n .cycles_account_manager_config,\n\n ));\n\n let tmpdir = tempfile::Builder::new()\n\n .prefix(\"ic_config\")\n\n .tempdir()\n\n .unwrap();\n", "file_path": "rs/replica/benches/execution_only_update.rs", "rank": 78, "score": 198086.47215602087 }, { "content": "fn criterion_make_checkpoint(c: &mut Criterion) {\n\n #[derive(Clone)]\n\n struct BenchData {\n\n state: ReplicatedState,\n\n height: Height,\n\n layout: StateLayout,\n\n metrics: CheckpointMetrics,\n\n thread_pool: Rc<scoped_threadpool::Pool>, // Rc is needed for `Clone`\n\n }\n\n\n\n let mut group = c.benchmark_group(\"state manager\");\n\n\n\n group.bench_function(\"empty state\", |b| {\n\n b.iter_with_setup(\n\n // Setup input data for measurement\n\n || {\n\n with_test_replica_logger(|log| {\n\n let tmp = Builder::new().prefix(\"test\").tempdir().unwrap();\n\n let root = tmp.path().to_path_buf();\n\n let layout = StateLayout::new(log, root);\n", "file_path": "rs/state_manager/benches/checkpoint.rs", "rank": 79, "score": 198086.47215602087 }, { "content": "fn make_module_wat(heap_size: usize) -> String {\n\n format!(\n\n r#\"\n\n (module\n\n (import \"ic0\" \"msg_reply\" (func $msg_reply))\n\n (import \"ic0\" \"msg_reply_data_append\"\n\n (func $msg_reply_data_append (param i32) (param i32)))\n\n (import \"ic0\" \"msg_arg_data_copy\"\n\n (func $ic0_msg_arg_data_copy (param i32) (param i32) (param i32)))\n\n (import \"ic0\" \"msg_arg_data_size\"\n\n (func $ic0_msg_arg_data_size (result i32)))\n\n (import \"ic0\" \"stable_grow\"\n\n (func $ic0_stable_grow (param $pages i32) (result i32)))\n\n (import \"ic0\" \"stable_read\"\n\n (func $ic0_stable_read (param $dst i32) (param $offset i32) (param $size i32)))\n\n\n\n (func $dump_heap\n\n (call $msg_reply_data_append (i32.const 0) (i32.mul (memory.size) (i32.const 0x10000)))\n\n (call $msg_reply)\n\n )\n", "file_path": "rs/embedders/tests/wasmtime_random_memory_writes.rs", "rank": 80, "score": 196055.88258966943 }, { "content": "fn bench_multi_sig(criterion: &mut Criterion) {\n\n let signer_counts = vec![1, 10, 50, 100];\n\n\n\n for num_of_signers in signer_counts {\n\n bench_multi_sig_n_signers(criterion, num_of_signers);\n\n }\n\n}\n\n\n", "file_path": "rs/crypto/benches/multi_sig.rs", "rank": 81, "score": 195607.16602493718 }, { "content": "/// This is a hack to work around a moc/Motoko limitation. Service definition\n\n/// for the governance canister takes an argument (for initialization), but moc\n\n/// can't handle services with function types.\n\n///\n\n/// We don't want to initialize the service in lifeline canister anyway, so we\n\n/// remove the argument here to make this build.\n\nfn remove_governance_service_args(did: &mut String) {\n\n *did = did.replace(\"service : (Governance) ->\", \"service :\");\n\n}\n\n\n\nconst GOVERNANCE_DID: &str = \"../../governance/canister/governance.did\";\n\nconst ROOT_DID: &str = \"../root/canister/root.did\";\n\n\n", "file_path": "rs/nns/handlers/lifeline/build.rs", "rank": 82, "score": 195607.16602493718 }, { "content": "fn crypto_basicsig_ed25519(criterion: &mut Criterion) {\n\n let algorithm_id = AlgorithmId::Ed25519;\n\n\n\n let group = &mut criterion.benchmark_group(format!(\"crypto_basicsig/{:?}\", algorithm_id));\n\n\n\n crypto_basicsig_verifybypubkey(group, algorithm_id);\n\n\n\n crypto_ed25519_basicsig_verify(group);\n\n\n\n crypto_ed25519_basicsig_sign(group);\n\n}\n\n\n", "file_path": "rs/crypto/benches/basic_sig.rs", "rank": 83, "score": 195607.16602493718 }, { "content": "fn validate_payload_benchmark(criterion: &mut Criterion) {\n\n let mut group = criterion.benchmark_group(\"validate_payload\");\n\n group.sample_size(30);\n\n group.measurement_time(std::time::Duration::from_secs(40));\n\n\n\n for message_count in (50..=850).step_by(50) {\n\n run_test(\n\n \"validate_payload_benchmark\",\n\n |now: Time,\n\n consensus_pool: &mut ConsensusPoolImpl,\n\n payload_builder: &dyn PayloadBuilder| {\n\n let tip = add_past_blocks(consensus_pool, now, message_count);\n\n let pool_reader = PoolReader::new(consensus_pool);\n\n\n\n let seed = CERTIFIED_HEIGHT + PAST_PAYLOAD_HEIGHT + 10;\n\n let ingress = prepare_ingress_payload(now, message_count, seed as u8);\n\n let xnet = XNetPayload::default();\n\n let self_validating = SelfValidatingPayload::default();\n\n let payload = Payload::new(\n\n ic_crypto::crypto_hash,\n", "file_path": "rs/consensus/benches/validate_payload.rs", "rank": 84, "score": 195607.16602493718 }, { "content": "fn crypto_basicsig_secp256k1(criterion: &mut Criterion) {\n\n let algorithm_id = AlgorithmId::EcdsaSecp256k1;\n\n\n\n let group = &mut criterion.benchmark_group(format!(\"crypto_basicsig/{:?}\", algorithm_id));\n\n\n\n crypto_basicsig_verifybypubkey(group, algorithm_id);\n\n}\n\n\n", "file_path": "rs/crypto/benches/basic_sig.rs", "rank": 85, "score": 195607.16602493718 }, { "content": "/// Speed test for building ingress payloads.\n\nfn build_payload(criterion: &mut Criterion) {\n\n let mut group = criterion.benchmark_group(\"build_payload\");\n\n group.sample_size(30);\n\n group.measurement_time(std::time::Duration::from_secs(10));\n\n for i in 1..=10 {\n\n let size = 5000 + 10000 * i;\n\n run_test(\n\n \"get_ingress_payload\",\n\n |time_source: Arc<FastForwardTimeSource>,\n\n pool: &mut IngressPoolImpl,\n\n manager: &mut IngressManager,\n\n registry| {\n\n let now = time_source.get_relative_time();\n\n let then = prepare(time_source.as_ref(), pool, now, size);\n\n time_source.set_time(then).unwrap();\n\n let name = format!(\"get_ingress_payload({})\", size);\n\n let byte_limit = registry\n\n .get_subnet_record(subnet_test_id(0), RegistryVersion::new(1))\n\n .unwrap()\n\n .unwrap()\n", "file_path": "rs/ingress_manager/benches/build_payload.rs", "rank": 86, "score": 195607.16602493718 }, { "content": "/// Speed test for ingress handling.\n\nfn handle_ingress(criterion: &mut Criterion) {\n\n let mut group = criterion.benchmark_group(\"handle_ingress\");\n\n group.sample_size(10);\n\n group.measurement_time(Duration::from_secs(10));\n\n for i in 1..=10 {\n\n // num messages per second\n\n let ingress_rate = i * 100;\n\n // We don't have to run the benchmark for the full TTL interval. Ending in 30\n\n // simulated seconds is good enough.\n\n let time_span = Duration::from_secs(30);\n\n // range of ingress expiry\n\n let expiry_range = MAX_INGRESS_TTL + time_span;\n\n let total_messages = ingress_rate * expiry_range.as_secs();\n\n run_test(\n\n \"get_ingress_payload\",\n\n |time_source: Arc<FastForwardTimeSource>,\n\n pool_config: ArtifactPoolConfig,\n\n log: ReplicaLogger,\n\n history: &SimulatedIngressHistory,\n\n manager: &mut IngressManager| {\n", "file_path": "rs/ingress_manager/benches/handle_ingress.rs", "rank": 87, "score": 195607.16602493718 }, { "content": "// Make a proposal for neuron 0 and call proccess proposals. The\n\n// following graph is set up to cascade following, so the proposal\n\n// will be accepted when submitted and executed in the call to process\n\n// proposals.\n\nfn make_and_process_proposal(gov: &mut Governance) {\n\n gov.make_proposal(\n\n &NeuronId { id: 0 },\n\n // Must match neuron 1's serialized_id.\n\n &PrincipalId::try_from(b\"SID0\".to_vec()).unwrap(),\n\n &Proposal {\n\n title: Some(\"Celebrate Good Times\".to_string()),\n\n summary: \"test\".to_string(),\n\n action: Some(proposal::Action::Motion(Motion {\n\n motion_text: \"dummy text\".to_string(),\n\n })),\n\n ..Default::default()\n\n },\n\n )\n\n .unwrap();\n\n gov.run_periodic_tasks().now_or_never();\n\n}\n\n\n", "file_path": "rs/nns/governance/benches/scale.rs", "rank": 88, "score": 195607.16602493718 }, { "content": "fn crypto_basicsig_p256(criterion: &mut Criterion) {\n\n let algorithm_id = AlgorithmId::EcdsaP256;\n\n\n\n let group = &mut criterion.benchmark_group(format!(\"crypto_basicsig/{:?}\", algorithm_id));\n\n\n\n crypto_basicsig_verifybypubkey(group, algorithm_id);\n\n}\n\n\n", "file_path": "rs/crypto/benches/basic_sig.rs", "rank": 89, "score": 195607.16602493718 }, { "content": "fn apply_deletion_mutation(registry: &mut Registry) {\n\n // Hard-coded keys that should be deleted\n\n let keys_to_delete = vec![make_node_record_key(NodeId::new(\n\n PrincipalId::from_str(\"hwywo-g5rog-wwern-wtt6d-ds6fb-jvh6j-mwlha-pj2ul-2m4dj-6mdqq-gqe\")\n\n .unwrap(),\n\n ))];\n\n let mutations = keys_to_delete\n\n .into_iter()\n\n .filter_map(|key| {\n\n registry\n\n .get(key.as_bytes(), registry.latest_version())\n\n .map(|_| delete(key))\n\n })\n\n .collect();\n\n\n\n // Delete specified records and check global invariants are not violated\n\n registry.maybe_apply_mutation_internal(mutations);\n\n}\n\n\n", "file_path": "rs/registry/canister/canister/canister.rs", "rank": 90, "score": 195607.16602493718 }, { "content": "fn crypto_basicsig_rsasha256(criterion: &mut Criterion) {\n\n let algorithm_id = AlgorithmId::RsaSha256;\n\n\n\n let group = &mut criterion.benchmark_group(format!(\"crypto_basicsig/{:?}\", algorithm_id));\n\n\n\n crypto_basicsig_verifybypubkey(group, algorithm_id);\n\n}\n\n\n", "file_path": "rs/crypto/benches/basic_sig.rs", "rank": 91, "score": 195607.16602493718 }, { "content": "fn crypto_nidkg_benchmarks(criterion: &mut Criterion) {\n\n let test_cases = vec![\n\n TestCase {\n\n sample_size: 50,\n\n sampling_mode: SamplingMode::Flat,\n\n num_of_nodes: 2,\n\n num_of_dealers: 1,\n\n dkg_tag: NiDkgTag::LowThreshold,\n\n },\n\n TestCase {\n\n sample_size: 30,\n\n sampling_mode: SamplingMode::Flat,\n\n num_of_nodes: 4,\n\n num_of_dealers: 3,\n\n dkg_tag: NiDkgTag::HighThreshold,\n\n },\n\n TestCase {\n\n sample_size: 10,\n\n sampling_mode: SamplingMode::Flat,\n\n num_of_nodes: 10,\n", "file_path": "rs/crypto/benches/ni_dkg.rs", "rank": 92, "score": 195607.16602493718 }, { "content": "/// Speed test for loading and copying block proposals.\n\nfn load_blocks(criterion: &mut Criterion) {\n\n let mut group = criterion.benchmark_group(\"block_loading\");\n\n run_test(\"load_blocks\", |pool: &mut ConsensusPoolImpl| {\n\n prepare(pool, 20);\n\n group.bench_function(\"Load blocks and sum their heights\", |bench| {\n\n bench.iter(|| {\n\n sum_block_heights(pool);\n\n })\n\n });\n\n group.bench_function(\"Load blocks and sum their ingress counts\", |bench| {\n\n bench.iter(|| {\n\n sum_ingress_counts(pool);\n\n })\n\n });\n\n })\n\n}\n\n\n\ncriterion_group!(benches, load_blocks);\n\n\n\ncriterion_main!(benches);\n", "file_path": "rs/artifact_pool/benches/load_blocks.rs", "rank": 93, "score": 195607.16602493718 }, { "content": "fn random_bytes_chunked<R: Rng>(n: u128, chunk_size: u128, rng: &mut R) -> Vec<Vec<u8>> {\n\n assert_eq!(n % chunk_size, 0, \"partial chunks currently not supported\");\n\n let mut chunks: Vec<Vec<u8>> = vec![];\n\n for _ in 0..(n / chunk_size) {\n\n let chunk: Vec<u8> = random_bytes(chunk_size, rng);\n\n chunks.push(chunk);\n\n }\n\n chunks\n\n}\n\n\n", "file_path": "rs/crypto/benches/hash.rs", "rank": 94, "score": 193944.5094412833 }, { "content": "#[test]\n\nfn test_random_oracle_stability() -> ThresholdEcdsaResult<()> {\n\n let curve_type = EccCurveType::K256;\n\n let seed = Seed::from_bytes(&[0x42; 32]);\n\n\n\n let mut rng = seed.into_rng();\n\n\n\n let mut ro = ro::RandomOracle::new(\"ic-test-domain-sep\");\n\n\n\n let s1 = EccScalar::random(curve_type, &mut rng)?;\n\n let pt1 = EccPoint::generator_g(curve_type)?.scalar_mul(&s1)?;\n\n ro.add_point(\"pt1\", &pt1)?;\n\n assert!(ro.add_point(\"pt1\", &pt1).is_err()); // duplicate name\n\n\n\n ro.add_u64(\"i1\", 42)?;\n\n ro.add_bytestring(\"v1\", &[42; 42])?;\n\n ro.add_scalar(\"s1\", &s1)?;\n\n ro.add_u64(\"round\", 1)?;\n\n\n\n let c1 = ro.output_scalars(curve_type, 2)?;\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/threshold_sig/tecdsa/tests/ro.rs", "rank": 95, "score": 193333.6290178513 }, { "content": "fn cmp_fp2(left: &mut FP2, right: &mut FP2) -> Ordering {\n\n let cmpa = BIG::comp(&left.geta(), &right.geta());\n\n let cmpb = BIG::comp(&left.getb(), &right.getb());\n\n if cmpb == 0 {\n\n isize_to_ordering(cmpa)\n\n } else {\n\n isize_to_ordering(cmpb)\n\n }\n\n}\n\n\n", "file_path": "rs/crypto/internal/crypto_lib/bls12_381/serde/miracl/src/lib.rs", "rank": 96, "score": 193287.81400616592 }, { "content": "/// Speed tests for the log analyzer.\n\npub fn criterion_benchmark(c: &mut Criterion) {\n\n // Test `gr_it`: As a baseline, we want to see how quickly the analyzer\n\n // can apply a basic boolean predicate to series of integers. It should be\n\n // roughly the same.\n\n fn gr_it(n: i64) -> bool {\n\n for i in 1..n {\n\n if i <= 0 {\n\n return false;\n\n }\n\n }\n\n true\n\n }\n\n\n\n c.bench_function(\"< 1_000_000_000\", |b| {\n\n b.iter(|| (1..1_000_000_000).all(|x| x >= 0))\n\n });\n\n c.bench_function(\"gr_it 1_000_000_000\", |b| b.iter(|| gr_it(1_000_000_000)));\n\n\n\n fn odd(x: &u64) -> bool {\n\n x % 2 == 1\n", "file_path": "rs/log_analyzer/benches/speed.rs", "rank": 97, "score": 192546.58594405284 }, { "content": "fn set_common_db_options(options: &mut Options) {\n\n options.create_if_missing(true);\n\n options.create_missing_column_families(true);\n\n options.set_use_fsync(true);\n\n options.set_compression_type(DBCompressionType::None);\n\n}\n\n\n", "file_path": "rs/artifact_pool/src/rocksdb_pool.rs", "rank": 98, "score": 190960.99139124784 }, { "content": "fn bench_threshold_sig_1_node_threshold_1(criterion: &mut Criterion) {\n\n let group = &mut criterion.benchmark_group(\"crypto_threshold_sig_1_node_threshold_1\");\n\n group.sample_size(25);\n\n bench_threshold_sig_n_nodes(group, 1, 1);\n\n}\n\n\n", "file_path": "rs/crypto/benches/threshold_sig.rs", "rank": 99, "score": 190960.99139124784 } ]
Rust
src/ir/item.rs
dbdr/cargo-call-stack
681d8edad0d27f7cd25aac064c173968a08f304a
use nom::{types::CompleteStr, *}; use crate::ir::{define::Define, FnSig}; #[derive(Clone, Debug, PartialEq)] pub enum Item<'a> { Alias(&'a str, &'a str), Comment, SourceFilename, Target, Global, Type, Define(Define<'a>), Declare(Declare<'a>), Attributes, Metadata, } #[derive(Clone, Debug, PartialEq)] pub struct Declare<'a> { pub name: &'a str, pub sig: Option<FnSig<'a>>, } named!(comment<CompleteStr, Item>, map!(super::comment, |_| Item::Comment)); named!(source_filename<CompleteStr, Item>, do_parse!( tag!("source_filename") >> space >> char!('=') >> not_line_ending >> (Item::SourceFilename) )); named!(target<CompleteStr, Item>, do_parse!( tag!("target") >> space >> alt!(tag!("datalayout") | tag!("triple")) >> space >> char!('=') >> not_line_ending >> (Item::Target) )); named!(alias<CompleteStr, Item>, do_parse!( name: call!(super::function) >> space >> char!('=') >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> tag!("alias") >> space >> call!(super::type_) >> space0 >> char!(',') >> space >> call!(super::type_) >> space >> alias: call!(super::function) >> (Item::Alias(name.0, alias.0)) )); named!(global<CompleteStr, Item>, do_parse!( call!(super::global) >> space >> char!('=') >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> alt!(tag!("global") | tag!("constant")) >> space >> not_line_ending >> (Item::Global) )); named!(type_<CompleteStr, Item>, do_parse!( call!(super::alias) >> space >> char!('=') >> not_line_ending >> (Item::Type) )); fn declare(input: CompleteStr) -> IResult<CompleteStr, Item> { let (rest, (output, name)) = do_parse!( input, tag!("declare") >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> output: alt!(map!(call!(super::type_), Some) | map!(tag!("void"), |_| None)) >> space >> name: call!(super::function) >> char!('(') >> ((output, name.0)) )?; if name.starts_with("llvm.") { do_parse!( rest, not_line_ending >> (Item::Declare(Declare { name, sig: None })) ) } else { do_parse!( rest, inputs: separated_list!( do_parse!(char!(',') >> space >> (())), do_parse!( ty: call!(super::type_) >> many0!(do_parse!(space >> call!(super::attribute) >> (()))) >> (ty) ) ) >> char!(')') >> not_line_ending >> (Item::Declare(Declare { name, sig: Some(FnSig { output: output.map(Box::new), inputs }) })) ) } } named!(attributes<CompleteStr, Item>, do_parse!( tag!("attributes") >> space >> char!('#') >> not_line_ending >> (Item::Attributes) )); named!(metadata<CompleteStr, Item>, do_parse!( tag!("!") >> not_line_ending >> (Item::Metadata) )); named!(pub item<CompleteStr, Item>, alt!( comment | source_filename | target | type_ | global | alias | map!(call!(super::define::parse), Item::Define) | declare | attributes | metadata )); #[cfg(test)] mod tests { use nom::types::CompleteStr as S; use crate::ir::{Declare, FnSig, Item, Type}; #[test] fn alias() { assert_eq!( super::alias(S( r#"@__pre_init = unnamed_addr alias void (), void ()* @DefaultPreInit"# )), Ok((S(""), Item::Alias("__pre_init", "DefaultPreInit"))) ); } #[test] fn declare() { assert_eq!( super::declare(S(r#"declare noalias i8* @malloc(i64) unnamed_addr #3"#)), Ok(( S(""), Item::Declare(Declare { name: "malloc", sig: Some(FnSig { inputs: vec![Type::Integer(64)], output: Some(Box::new(Type::Pointer(Box::new(Type::Integer(8))))) }) }) )) ); } #[test] fn global() { assert_eq!( super::global(S( "@0 = private constant <{ [0 x i8] }> zeroinitializer, align 4, !dbg !0" )), Ok((S(""), Item::Global)) ); assert_eq!( super::global(S( "@DEVICE_PERIPHERALS = local_unnamed_addr global <{ [1 x i8] }> zeroinitializer, align 1, !dbg !175" )), Ok((S(""), Item::Global)) ); } #[test] fn type_() { assert_eq!( super::type_(S("%\"blue_pill::ItmLogger\" = type {}")), Ok((S(""), Item::Type)) ); } }
use nom::{types::CompleteStr, *}; use crate::ir::{define::Define, FnSig}; #[derive(Clone, Debug, PartialEq)] pub enum Item<'a> { Alias(&'a str, &'a str), Comment, SourceFilename, Target, Global, Type, Define(Define<'a>), Declare(Declare<'a>), Attributes, Metadata, } #[derive(Clone, Debug, PartialEq)] pub struct Declare<'a> { pub name: &'a str, pub sig: Option<FnSig<'a>>, } named!(comment<CompleteStr, Item>, map!(super::comment, |_| Item::Comment)); named!(source_filename<CompleteStr, Item>, do_parse!( tag!("source_filename") >> space >> char!('=') >> not_line_ending >> (Item::SourceFilename) )); named!(target<CompleteStr, Item>, do_parse!( tag!("target") >> space >> alt!(tag!("datalayout") | tag!("triple")) >> space >> char!('=') >> not_line_ending >> (Item::Target) )); named!(alias<CompleteStr, Item>, do_parse!( name: call!(super::function) >> space >> char!('=') >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> tag!("alias") >> space >> call!(super::type_) >> space0 >> char!(',') >> space >> call!(super::type_) >> space >> alias: call!(super::function) >> (Item::Alias(name.0, alias.0)) )); named!(global<CompleteStr, Item>, do_parse!( call!(super::global) >> space >> char!('=') >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> alt!(tag!("global") | tag!("constant")) >> space >> not_line_ending >> (Item::Global) )); named!(type_<CompleteStr, Item>, do_parse!( call!(super::alias) >> space >> char!('=') >> not_line_ending >> (Item::Type) )); fn declare(input: CompleteStr) -> IResult<CompleteStr, Item> {
if name.starts_with("llvm.") { do_parse!( rest, not_line_ending >> (Item::Declare(Declare { name, sig: None })) ) } else { do_parse!( rest, inputs: separated_list!( do_parse!(char!(',') >> space >> (())), do_parse!( ty: call!(super::type_) >> many0!(do_parse!(space >> call!(super::attribute) >> (()))) >> (ty) ) ) >> char!(')') >> not_line_ending >> (Item::Declare(Declare { name, sig: Some(FnSig { output: output.map(Box::new), inputs }) })) ) } } named!(attributes<CompleteStr, Item>, do_parse!( tag!("attributes") >> space >> char!('#') >> not_line_ending >> (Item::Attributes) )); named!(metadata<CompleteStr, Item>, do_parse!( tag!("!") >> not_line_ending >> (Item::Metadata) )); named!(pub item<CompleteStr, Item>, alt!( comment | source_filename | target | type_ | global | alias | map!(call!(super::define::parse), Item::Define) | declare | attributes | metadata )); #[cfg(test)] mod tests { use nom::types::CompleteStr as S; use crate::ir::{Declare, FnSig, Item, Type}; #[test] fn alias() { assert_eq!( super::alias(S( r#"@__pre_init = unnamed_addr alias void (), void ()* @DefaultPreInit"# )), Ok((S(""), Item::Alias("__pre_init", "DefaultPreInit"))) ); } #[test] fn declare() { assert_eq!( super::declare(S(r#"declare noalias i8* @malloc(i64) unnamed_addr #3"#)), Ok(( S(""), Item::Declare(Declare { name: "malloc", sig: Some(FnSig { inputs: vec![Type::Integer(64)], output: Some(Box::new(Type::Pointer(Box::new(Type::Integer(8))))) }) }) )) ); } #[test] fn global() { assert_eq!( super::global(S( "@0 = private constant <{ [0 x i8] }> zeroinitializer, align 4, !dbg !0" )), Ok((S(""), Item::Global)) ); assert_eq!( super::global(S( "@DEVICE_PERIPHERALS = local_unnamed_addr global <{ [1 x i8] }> zeroinitializer, align 1, !dbg !175" )), Ok((S(""), Item::Global)) ); } #[test] fn type_() { assert_eq!( super::type_(S("%\"blue_pill::ItmLogger\" = type {}")), Ok((S(""), Item::Type)) ); } }
let (rest, (output, name)) = do_parse!( input, tag!("declare") >> space >> many0!(do_parse!(call!(super::attribute) >> space >> (()))) >> output: alt!(map!(call!(super::type_), Some) | map!(tag!("void"), |_| None)) >> space >> name: call!(super::function) >> char!('(') >> ((output, name.0)) )?;
assignment_statement
[ { "content": "pub fn type_(input: CompleteStr) -> IResult<CompleteStr, Type> {\n\n let (rest, void) = opt!(input, tag!(\"void\"))?;\n\n\n\n if void.is_some() {\n\n // this must be a function\n\n let (mut rest, inputs) = do_parse!(rest, space >> inputs: fn_inputs >> (inputs))?;\n\n let mut ty = Type::Fn(FnSig {\n\n inputs,\n\n output: None,\n\n });\n\n\n\n // is this a function pointer?\n\n loop {\n\n let (rest_, start) = opt!(rest, char!('*'))?;\n\n\n\n if start.is_none() {\n\n break;\n\n } else {\n\n rest = rest_;\n\n ty = Type::Pointer(Box::new(ty));\n", "file_path": "src/ir/ty.rs", "rank": 0, "score": 132530.12806570352 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Global<'a>(Option<&'a str>);\n\n\n\nnamed!(global<CompleteStr, Global>, do_parse!(\n\n char!('@') >>\n\n s: alt!(map!(string, |s| Some(s.0)) | map!(digit, |_| None) | map!(ident, |i| Some(i.0))) >>\n\n (Global(s)))\n\n);\n\n\n", "file_path": "src/ir.rs", "rank": 2, "score": 109262.0071517956 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Alias<'a>(&'a str);\n\n\n\nnamed!(alias<CompleteStr, Alias>, do_parse!(\n\n char!('%') >>\n\n name: name >>\n\n (Alias(name)))\n\n);\n\n\n", "file_path": "src/ir.rs", "rank": 3, "score": 105769.2890159122 }, { "content": "#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\nenum Target {\n\n Other,\n\n Thumbv6m,\n\n Thumbv7m,\n\n}\n\n\n\nimpl Target {\n\n fn is_thumb(&self) -> bool {\n\n match *self {\n\n Target::Thumbv6m | Target::Thumbv7m => true,\n\n Target::Other => false,\n\n }\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 4, "score": 100604.96956931085 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Comment;\n\n\n\nnamed!(comment<CompleteStr, Comment>, do_parse!(\n\n char!(';') >>\n\n not_line_ending >>\n\n (Comment))\n\n);\n\n\n", "file_path": "src/ir.rs", "rank": 5, "score": 99905.6656338471 }, { "content": "pub fn parse<'a>(ll: &'a str) -> Result<Vec<Item<'a>>, failure::Error> {\n\n items(CompleteStr(ll)).map(|t| t.1).map_err(|e| {\n\n format_err!(\n\n \"BUG: failed to parse .ll file; please submit a bug report. Details:\\n{}\",\n\n e\n\n )\n\n })\n\n}\n\n\n\nnamed!(items<CompleteStr, Vec<Item>>, do_parse!(\n\n items: separated_list_complete!(many1!(line_ending), crate::ir::item::item) >>\n\n many0!(line_ending) >>\n\n eof!() >>\n\n (items)\n\n));\n\n\n", "file_path": "src/ir.rs", "rank": 6, "score": 99296.3155249771 }, { "content": "/// Analyzes a subroutine and returns all the `BL` and `B` instructions in it, plus whether this\n\n/// function performs an indirect function call or not\n\n// NOTE we assume that `bytes` is always valid input so all errors are bugs\n\n// Reference: ARMv7-M Architecture Reference Manual (ARM DDI 0403E.b)\n\n// Reference: ARMv6-M Architecture Reference Manual (ARM DDI 0419D)\n\npub fn analyze(\n\n bytes: &[u8],\n\n address: u32,\n\n v7: bool,\n\n tags: &[(u32, Tag)],\n\n) -> (Vec<i32>, Vec<i32>, bool, bool, Option<u64>) {\n\n macro_rules! bug {\n\n ($first:expr) => {\n\n panic!(\n\n \"BUG: unknown instruction {:02x}{:02x}\",\n\n $first[1], $first[0]\n\n );\n\n };\n\n\n\n ($first:expr, $second:expr) => {\n\n panic!(\n\n \"BUG: unknown instruction {:02x}{:02x} {:02x}{:02x}\",\n\n $first[1], $first[0], $second[1], $second[0]\n\n );\n\n };\n", "file_path": "src/thumb.rs", "rank": 7, "score": 87504.2783076469 }, { "content": "// removes hashes like `::hfc5adc5d79855638`, if present\n\nfn dehash(demangled: &str) -> Option<&str> {\n\n const HASH_LENGTH: usize = 19;\n\n\n\n let len = demangled.as_bytes().len();\n\n if len > HASH_LENGTH {\n\n if demangled\n\n .get(len - HASH_LENGTH..)\n\n .map(|hash| hash.starts_with(\"::h\"))\n\n .unwrap_or(false)\n\n {\n\n Some(&demangled[..len - HASH_LENGTH])\n\n } else {\n\n None\n\n }\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 8, "score": 83323.05127866655 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct String<'a>(&'a str);\n\n\n\n// NOTE this will accept things that are not valid in LLVM-IR but we are only dealing with\n\n// well-formed LLVM-IR so this is good enough\n\nnamed!(string<CompleteStr, String>, do_parse!(\n\n char!('\"') >>\n\n x: take_until!(\"\\\"\") >>\n\n char!('\"') >>\n\n (String(&x)))\n\n);\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use nom::types::CompleteStr as S;\n\n\n\n use super::{Alias, Comment, FnSig, GetElementPtr, Ident, Local, String, Type};\n\n\n\n #[test]\n\n fn alias() {\n\n assert_eq!(\n", "file_path": "src/ir.rs", "rank": 9, "score": 78595.05052168187 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Ident<'a>(&'a str);\n\n\n", "file_path": "src/ir.rs", "rank": 10, "score": 78595.05052168187 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Attribute;\n\n\n\nnamed!(attribute<CompleteStr, Attribute>, do_parse!(\n\n switch!(\n\n take_while1!(|c: char| c.is_alphabetic() || c == '_'),\n\n CompleteStr(\"dereferenceable\") | CompleteStr(\"dereferenceable_or_null\")\n\n => do_parse!(char!('(') >> digit >> char!(')') >> (())) |\n\n CompleteStr(\"align\") => do_parse!(space >> digit >> (())) |\n\n // have this branch always error because this is not an attribute but part of a type\n\n CompleteStr(\"double\") |CompleteStr(\"float\") | CompleteStr(\"void\") =>\n\n do_parse!(none_of!(\" \") >> (())) |\n\n // have this branch always error because there are not attributes but operations\n\n CompleteStr(\"bitcast\") | CompleteStr(\"getelementptr\") => do_parse!(none_of!(\" \") >> (())) |\n\n // have this branch always error because there are not attributes but keywords\n\n CompleteStr(\"alias\") | CompleteStr(\"global\") | CompleteStr(\"constant\") =>\n\n do_parse!(none_of!(\" \") >> (())) |\n\n _ => do_parse!((()))) >>\n\n (Attribute)\n\n));\n\n\n\n// NOTE constant operation\n", "file_path": "src/ir.rs", "rank": 11, "score": 78463.80673771942 }, { "content": "#[derive(Clone, Debug, PartialEq)]\n\nstruct Argument<'a>(Type<'a>);\n\n\n\nnamed!(argument<CompleteStr, Argument>, do_parse!(\n\n ty: call!(super::type_) >> space >>\n\n many0!(do_parse!(call!(super::attribute) >> space >> (()))) >>\n\n alt!(\n\n map!(call!(super::bitcast), drop) |\n\n map!(call!(super::getelementptr), drop) |\n\n map!(super::local, drop) |\n\n map!(digit, drop)) >>\n\n (Argument(ty))\n\n));\n\n\n\nnamed!(bitcast_call<CompleteStr, Stmt>, do_parse!(\n\n opt!(do_parse!(tag!(\"tail\") >> space >> (()))) >>\n\n // XXX can this be `invoke`?\n\n tag!(\"call\") >> space >>\n\n // not seen in practice (yet?)\n\n // many0!(do_parse!(call!(super::attribute) >> space >> (()))) >>\n\n alt!(map!(call!(super::type_), drop) | map!(tag!(\"void\"), drop)) >> space >>\n", "file_path": "src/ir/define.rs", "rank": 12, "score": 75779.58728985504 }, { "content": "#[derive(Clone, Debug, PartialEq)]\n\nstruct Parameter<'a>(Type<'a>);\n\n\n\nnamed!(parameter<CompleteStr, Parameter>, do_parse!(\n\n ty: call!(super::type_) >>\n\n many0!(do_parse!(space >> call!(super::attribute) >> (()))) >>\n\n opt!(do_parse!(space >> call!(super::alias) >> (()))) >>\n\n (Parameter(ty))\n\n));\n\n\n\nnamed!(pub parse<CompleteStr, Define>, do_parse!(\n\n tag!(\"define\") >> space >>\n\n many0!(do_parse!(call!(super::attribute) >> space >> (()))) >>\n\n output: alt!(map!(call!(super::type_), Some) | map!(tag!(\"void\"), |_| None)) >> space >>\n\n name: call!(super::function) >>\n\n // parameter list\n\n char!('(') >>\n\n inputs: separated_list!(\n\n do_parse!(char!(',') >> space >> (())),\n\n map!(parameter, |p| p.0)\n\n ) >> char!(')') >>\n", "file_path": "src/ir/define.rs", "rank": 13, "score": 75779.58728985504 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Bitcast<'a>(Option<&'a str>);\n\n\n\nnamed!(bitcast<CompleteStr, Bitcast>, do_parse!(\n\n tag!(\"bitcast\") >> space >>\n\n name: delimited!(\n\n char!('('),\n\n do_parse!(\n\n call!(type_) >> space >>\n\n name: global >> space >>\n\n tag!(\"to\") >> space >>\n\n call!(type_) >> (name.0)\n\n ),\n\n char!(')')\n\n ) >> (Bitcast(name))\n\n));\n\n\n\n// NOTE constant operation\n", "file_path": "src/ir.rs", "rank": 14, "score": 72552.8475319087 }, { "content": "fn call_stack(ex: &str) -> String {\n\n String::from_utf8(\n\n Command::new(\"cargo\")\n\n .args(&[\"call-stack\", \"--example\", ex])\n\n .current_dir(env::current_dir().unwrap().join(\"cortex-m-examples\"))\n\n .output()\n\n .unwrap()\n\n .stdout,\n\n )\n\n .unwrap()\n\n}\n", "file_path": "tests/examples.rs", "rank": 15, "score": 69762.9424168225 }, { "content": "fn fmt_struct(f: &mut fmt::Formatter, fields: &[Type]) -> fmt::Result {\n\n f.write_str(\"{\")?;\n\n let mut is_first = true;\n\n for field in fields {\n\n if is_first {\n\n is_first = false;\n\n } else {\n\n f.write_str(\", \")?;\n\n }\n\n\n\n write!(f, \"{}\", field)?;\n\n }\n\n if !is_first {\n\n // not empty\n\n f.write_str(\" \")?;\n\n }\n\n f.write_str(\"}\")?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/ir/ty.rs", "rank": 16, "score": 68866.40578415625 }, { "content": "// LLVM LangRef: `[-a-zA-Z$._][-a-zA-Z$._0-9]*`\n\n// not using `named!` because lifetime inference doesn't work correctly\n\nfn ident<'a>(input: CompleteStr<'a>) -> IResult<CompleteStr<'a>, Ident<'a>> {\n\n map_res!(\n\n input,\n\n take_while1!(|c: char| c.is_alphanumeric() || \"-$._\".contains(c)),\n\n |s: CompleteStr<'a>| if s.chars().next().unwrap_or('\\0').is_digit(10) {\n\n Err(())\n\n } else {\n\n Ok(Ident(s.0))\n\n }\n\n )\n\n}\n\n\n", "file_path": "src/ir.rs", "rank": 17, "score": 67287.6716808531 }, { "content": "fn matches(bytes: &[u8], pattern: &str) -> bool {\n\n assert!(pattern.starts_with(\"0b\"));\n\n\n\n let pattern = pattern[2..].replace(\"_\", \"\");\n\n assert_eq!(pattern.len(), 16);\n\n\n\n let mask1 =\n\n u8::from_str_radix(&pattern[..8].replace(\"0\", \"1\").replace(\"x\", \"0\"), 2).expect(\"BUG\");\n\n let value1 = u8::from_str_radix(&pattern[..8].replace(\"x\", \"0\"), 2).expect(\"BUG\");\n\n\n\n let mask2 =\n\n u8::from_str_radix(&pattern[8..].replace(\"0\", \"1\").replace(\"x\", \"0\"), 2).expect(\"BUG\");\n\n let value2 = u8::from_str_radix(&pattern[8..].replace(\"x\", \"0\"), 2).expect(\"BUG\");\n\n\n\n let first = bytes[1];\n\n let second = bytes[0];\n\n (first & mask1 == value1) && (second & mask2 == value2)\n\n}\n\n\n", "file_path": "src/thumb.rs", "rank": 18, "score": 62278.26443306544 }, { "content": "#[inline(never)]\n\n#[entry]\n\nfn main() -> ! {\n\n if let Some(f) = unsafe { F.load(Ordering::Relaxed).as_ref() } {\n\n // call via function pointer\n\n f();\n\n }\n\n\n\n loop {}\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/fn.rs", "rank": 19, "score": 54540.79012292181 }, { "content": "#[exception]\n\nfn SysTick() {\n\n F.store(bar as *mut _, Ordering::Relaxed);\n\n}\n", "file_path": "cortex-m-examples/examples/fn.rs", "rank": 20, "score": 53278.877644254484 }, { "content": "fn max_of(mut iter: impl Iterator<Item = Max>) -> Option<Max> {\n\n iter.next().map(|first| iter.fold(first, max))\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 21, "score": 52139.017232043414 }, { "content": "#[test]\n\nfn to() {\n\n if channel_is_nightly() {\n\n let dot = call_stack(\"to\");\n\n\n\n let mut bar = None;\n\n let mut baz = None;\n\n let mut quux = None;\n\n let mut to = None;\n\n\n\n for line in dot.lines() {\n\n if line.contains(\"label=\\\"to::Foo::foo\\\\n\") {\n\n bar = Some(\n\n line.split_whitespace()\n\n .next()\n\n .unwrap()\n\n .parse::<u32>()\n\n .unwrap(),\n\n );\n\n } else if line.contains(\"label=\\\"<to::Baz as to::Foo>::foo\\\\n\") {\n\n baz = Some(\n", "file_path": "tests/examples.rs", "rank": 22, "score": 50532.270910760504 }, { "content": "#[derive(Clone, Copy, Eq, PartialEq)]\n\nenum Max {\n\n Exact(u64),\n\n LowerBound(u64),\n\n}\n\n\n\nimpl ops::Add<Local> for Max {\n\n type Output = Max;\n\n\n\n fn add(self, rhs: Local) -> Max {\n\n match (self, rhs) {\n\n (Max::Exact(lhs), Local::Exact(rhs)) => Max::Exact(lhs + rhs),\n\n (Max::Exact(lhs), Local::Unknown) => Max::LowerBound(lhs),\n\n (Max::LowerBound(lhs), Local::Exact(rhs)) => Max::LowerBound(lhs + rhs),\n\n (Max::LowerBound(lhs), Local::Unknown) => Max::LowerBound(lhs),\n\n }\n\n }\n\n}\n\n\n\nimpl ops::Add<Max> for Max {\n\n type Output = Max;\n", "file_path": "src/main.rs", "rank": 23, "score": 50253.62742112692 }, { "content": "#[derive(Clone, Copy, PartialEq)]\n\nenum Local {\n\n Exact(u64),\n\n Unknown,\n\n}\n\n\n\nimpl fmt::Display for Local {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n Local::Exact(n) => write!(f, \"{}\", n),\n\n Local::Unknown => f.write_str(\"?\"),\n\n }\n\n }\n\n}\n\n\n\nimpl Into<Max> for Local {\n\n fn into(self) -> Max {\n\n match self {\n\n Local::Exact(n) => Max::Exact(n),\n\n Local::Unknown => Max::LowerBound(0),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 24, "score": 50253.62742112692 }, { "content": "#[derive(Debug, Default)]\n\nstruct Dynamic {\n\n called: bool,\n\n callers: HashSet<NodeIndex>,\n\n callees: HashSet<NodeIndex>,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 25, "score": 49558.19041067516 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct Local;\n\n\n\nnamed!(local<CompleteStr, Local>, do_parse!(\n\n char!('%') >>\n\n alt!(map!(digit, drop) | map!(ident, drop)) >>\n\n (Local))\n\n);\n\n\n\n// `internal`, `fastcc`, `dereferenceable(4)`, etc.\n", "file_path": "src/ir.rs", "rank": 26, "score": 49558.013478183566 }, { "content": "#[derive(Default)]\n\nstruct Indirect {\n\n called: bool,\n\n callers: HashSet<NodeIndex>,\n\n callees: HashSet<NodeIndex>,\n\n}\n\n\n\n// used to track dynamic dispatch (trait objects)\n", "file_path": "src/main.rs", "rank": 27, "score": 49554.26800277384 }, { "content": "fn bar() -> bool {\n\n unsafe { asm!(\"\" : : \"r\"(0) \"r\"(1) \"r\"(2) \"r\"(3) \"r\"(4) \"r\"(5) \"r\"(6) \"r\"(7)) }\n\n\n\n true\n\n}\n\n\n\n// this handler can change the function pointer at any time\n", "file_path": "cortex-m-examples/examples/fn.rs", "rank": 28, "score": 49375.35962901452 }, { "content": "fn foo() -> bool {\n\n // spill variables onto the stack\n\n unsafe { asm!(\"\" : : \"r\"(0) \"r\"(1) \"r\"(2) \"r\"(3) \"r\"(4) \"r\"(5)) }\n\n\n\n false\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/fn.rs", "rank": 29, "score": 49375.35962901452 }, { "content": "#[test]\n\nfn fmul() {\n\n if channel_is_nightly() {\n\n let dot = call_stack(\"fmul\");\n\n\n\n let mut main = None;\n\n let mut fmul = None;\n\n\n\n for line in dot.lines() {\n\n if line.contains(\"label=\\\"main\\\\n\") {\n\n main = Some(\n\n line.split_whitespace()\n\n .next()\n\n .unwrap()\n\n .parse::<u32>()\n\n .unwrap(),\n\n );\n\n } else if line.contains(\"label=\\\"__aeabi_fmul\\\\n\") {\n\n fmul = Some(\n\n line.split_whitespace()\n\n .next()\n", "file_path": "tests/examples.rs", "rank": 30, "score": 48623.12010321501 }, { "content": "#[test]\n\nfn fun() {\n\n if channel_is_nightly() {\n\n let dot = call_stack(\"fn\");\n\n\n\n let mut foo = None;\n\n let mut bar = None;\n\n let mut fun = None;\n\n\n\n for line in dot.lines() {\n\n if line.contains(\"label=\\\"fn::foo\\\\n\") {\n\n foo = Some(\n\n line.split_whitespace()\n\n .next()\n\n .unwrap()\n\n .parse::<u32>()\n\n .unwrap(),\n\n );\n\n } else if line.contains(\"label=\\\"fn::bar\\\\n\") {\n\n bar = Some(\n\n line.split_whitespace()\n", "file_path": "tests/examples.rs", "rank": 31, "score": 48623.12010321501 }, { "content": "#[test]\n\nfn cycle() {\n\n if channel_is_nightly() {\n\n let dot = call_stack(\"cycle\");\n\n\n\n let mut found = false;\n\n for line in dot.lines() {\n\n if line.contains(\"label=\\\"main\\\\n\") {\n\n found = true;\n\n // worst-case stack usage must be exact\n\n assert!(line.contains(\"max = \"));\n\n }\n\n }\n\n\n\n assert!(found);\n\n }\n\n}\n\n\n", "file_path": "tests/examples.rs", "rank": 32, "score": 48623.12010321501 }, { "content": "#[allow(non_snake_case)]\n\nfn Node<'a, S>(name: S, stack: Option<u64>, dashed: bool) -> Node<'a>\n\nwhere\n\n S: Into<Cow<'a, str>>,\n\n{\n\n Node {\n\n name: name.into(),\n\n local: stack.map(Local::Exact).unwrap_or(Local::Unknown),\n\n max: None,\n\n dashed,\n\n }\n\n}\n\n\n\n/// Local stack usage\n", "file_path": "src/main.rs", "rank": 33, "score": 47946.50227110888 }, { "content": "struct Baz;\n\n\n\nimpl Foo for Baz {\n\n // overrides the default method\n\n fn foo(&self) -> bool {\n\n unsafe { asm!(\"\" : : \"r\"(0) \"r\"(1) \"r\"(2) \"r\"(3) \"r\"(4) \"r\"(5) \"r\"(6) \"r\"(7)) }\n\n\n\n true\n\n }\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/to.rs", "rank": 34, "score": 47846.758555570996 }, { "content": "struct Quux;\n\n\n\nimpl Quux {\n\n // not a trait method!\n\n #[inline(never)]\n\n fn foo(&self) -> bool {\n\n // NOTE(asm!) side effect to preserve function calls to this method\n\n unsafe { asm!(\"NOP\" : : : : \"volatile\") }\n\n\n\n false\n\n }\n\n}\n\n\n\n// this handler can change the trait object at any time\n", "file_path": "cortex-m-examples/examples/to.rs", "rank": 35, "score": 47846.758555570996 }, { "content": "struct Bar;\n\n\n\n// uses the default method implementation\n\nimpl Foo for Bar {}\n\n\n", "file_path": "cortex-m-examples/examples/to.rs", "rank": 36, "score": 47846.758555570996 }, { "content": "fn main() {\n\n // Put the linker script somewhere the linker can find it\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 // Only re-run the build script when memory.x is changed,\n\n // instead of when any part of the source code changes.\n\n println!(\"cargo:rerun-if-changed=memory.x\");\n\n}\n", "file_path": "cortex-m-examples/build.rs", "rank": 37, "score": 46942.69847454454 }, { "content": "#[entry]\n\n#[inline(never)]\n\nfn main() -> ! {\n\n // trait object dispatch\n\n (*TO.lock()).foo();\n\n\n\n Quux.foo();\n\n\n\n loop {}\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/to.rs", "rank": 38, "score": 46942.69847454454 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq)]\n\nstruct GetElementPtr;\n\n\n\nnamed!(getelementptr<CompleteStr, GetElementPtr>, do_parse!(\n\n tag!(\"getelementptr\") >> space >>\n\n opt!(do_parse!(tag!(\"inbounds\") >> space >> ())) >>\n\n delimited!(char!('('), do_parse!(\n\n type_ >> char!(',') >> space >>\n\n type_ >> space >>\n\n global >>\n\n many1!(do_parse!(char!(',') >> space >> type_ >> space >> digit >> (()))) >>\n\n (())\n\n ), char!(')')) >>\n\n (GetElementPtr)\n\n));\n\n\n\nnamed!(name<CompleteStr, &str>,\n\n alt!(\n\n map!(string, |s| s.0) |\n\n map!(ident, |i| i.0)\n\n )\n", "file_path": "src/ir.rs", "rank": 39, "score": 46336.00385584093 }, { "content": "#[derive(Clone)]\n\nstruct Node<'a> {\n\n name: Cow<'a, str>,\n\n local: Local,\n\n max: Option<Max>,\n\n dashed: bool,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 40, "score": 45559.86374150423 }, { "content": "#[inline(never)]\n\n#[entry]\n\nfn main() -> ! {\n\n foo();\n\n\n\n quux();\n\n\n\n loop {}\n\n}\n\n\n\n// these three functions form a cycle that breaks when `SysTick` runs\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 41, "score": 45452.22423143026 }, { "content": "#[inline(never)]\n\nfn foo() {\n\n if X.load(Ordering::Relaxed) {\n\n bar()\n\n }\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 42, "score": 45452.22423143026 }, { "content": "#[inline(never)]\n\nfn bar() {\n\n if X.load(Ordering::Relaxed) {\n\n baz()\n\n }\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 43, "score": 45452.22423143026 }, { "content": "#[entry]\n\nfn main() -> ! {\n\n let x = f32::from_bits(X.load(Ordering::Relaxed));\n\n let y = x * 1.1;\n\n X.store(y.to_bits(), Ordering::Relaxed);\n\n\n\n loop {}\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/fmul.rs", "rank": 44, "score": 45452.22423143026 }, { "content": "#[inline(never)]\n\nfn baz() {\n\n if X.load(Ordering::Relaxed) {\n\n foo()\n\n }\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 45, "score": 45452.22423143026 }, { "content": "#[exception]\n\nfn SysTick() {\n\n *TO.lock() = &Baz;\n\n}\n", "file_path": "cortex-m-examples/examples/to.rs", "rank": 46, "score": 45452.22423143026 }, { "content": "#[inline(never)]\n\nfn quux() {\n\n // spill variables onto the stack\n\n unsafe { asm!(\"\" : : \"r\"(0) \"r\"(1) \"r\"(2) \"r\"(3) \"r\"(4) \"r\"(5)) }\n\n}\n\n\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 47, "score": 45452.22423143026 }, { "content": "#[exception]\n\nfn SysTick() {\n\n X.fetch_add(1, Ordering::Relaxed);\n\n}\n", "file_path": "cortex-m-examples/examples/fmul.rs", "rank": 48, "score": 44121.21401432646 }, { "content": "#[exception]\n\nfn SysTick() {\n\n X.store(false, Ordering::Relaxed);\n\n}\n", "file_path": "cortex-m-examples/examples/cycle.rs", "rank": 49, "score": 44121.21401432646 }, { "content": "struct Escaper<W>\n\nwhere\n\n W: io::Write,\n\n{\n\n writer: W,\n\n error: io::Result<()>,\n\n}\n\n\n\nimpl<W> Escaper<W>\n\nwhere\n\n W: io::Write,\n\n{\n\n fn new(writer: W) -> Self {\n\n Escaper {\n\n writer,\n\n error: Ok(()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 50, "score": 43852.35429430139 }, { "content": "fn channel_is_nightly() -> bool {\n\n rustc_version::version_meta().map(|m| m.channel).ok() == Some(Channel::Nightly)\n\n}\n\n\n", "file_path": "tests/examples.rs", "rank": 51, "score": 41548.70621619029 }, { "content": "fn main() -> Result<(), failure::Error> {\n\n match run() {\n\n Ok(ec) => process::exit(ec),\n\n Err(e) => {\n\n eprintln!(\"error: {}\", e);\n\n process::exit(1)\n\n }\n\n }\n\n}\n\n\n\n// Font used in the dot graphs\n\nconst FONT: &str = \"monospace\";\n\n\n\n// Version we analyzed to extract some ad-hoc information\n\nconst VERS: &str = \"1.33.0\"; // compiler-builtins = \"0.1.4\"\n\n\n", "file_path": "src/main.rs", "rank": 52, "score": 35632.34077594436 }, { "content": "fn thumb_expand_imm(imm12: u16) -> u32 {\n\n if imm12 >> 10 == 0b00 {\n\n match (imm12 >> 8) & 0b0011 {\n\n 0b00 => u32::from(imm12 & 0b0000_1111_1111),\n\n\n\n 0b01 => u32::from(imm12 & 0b0000_1111_1111) << 8,\n\n\n\n 0b10 => {\n\n let imm8 = u32::from(imm12 & 0b0000_1111_1111);\n\n (imm8 << 24) | (imm8 << 8)\n\n }\n\n\n\n 0b11 => {\n\n let imm8 = u32::from(imm12 & 0b0000_1111_1111);\n\n (imm8 << 24) | (imm8 << 16) | (imm8 << 8) | imm8\n\n }\n\n\n\n _ => unreachable!(),\n\n }\n\n } else {\n", "file_path": "src/thumb.rs", "rank": 53, "score": 33356.2406852774 }, { "content": "fn run() -> Result<i32, failure::Error> {\n\n Builder::from_env(Env::default().default_filter_or(\"warn\")).init();\n\n\n\n let matches = App::new(\"cargo-call-stack\")\n\n .version(crate_version!())\n\n .author(crate_authors!(\", \"))\n\n .about(\"Generate a call graph and perform whole program stack usage analysis\")\n\n // as this is used as a Cargo subcommand the first argument will be the name of the binary\n\n // we ignore this argument\n\n .arg(Arg::with_name(\"binary-name\").hidden(true))\n\n .arg(\n\n Arg::with_name(\"target\")\n\n .long(\"target\")\n\n .takes_value(true)\n\n .value_name(\"TRIPLE\")\n\n .help(\"Target triple for which the code is compiled\"),\n\n )\n\n .arg(\n\n Arg::with_name(\"verbose\")\n\n .long(\"verbose\")\n", "file_path": "src/main.rs", "rank": 54, "score": 32975.525863510426 }, { "content": "fn sign_extend(x: i32, nbits: u32) -> i32 {\n\n let shift = 32 - nbits;\n\n x.wrapping_shl(shift).wrapping_shr(shift)\n\n}\n\n\n", "file_path": "src/thumb.rs", "rank": 55, "score": 30749.497647463715 }, { "content": "fn max(lhs: Max, rhs: Max) -> Max {\n\n match (lhs, rhs) {\n\n (Max::Exact(lhs), Max::Exact(rhs)) => Max::Exact(cmp::max(lhs, rhs)),\n\n (Max::Exact(lhs), Max::LowerBound(rhs)) => Max::LowerBound(cmp::max(lhs, rhs)),\n\n (Max::LowerBound(lhs), Max::Exact(rhs)) => Max::LowerBound(cmp::max(lhs, rhs)),\n\n (Max::LowerBound(lhs), Max::LowerBound(rhs)) => Max::LowerBound(cmp::max(lhs, rhs)),\n\n }\n\n}\n\n\n\nimpl fmt::Display for Max {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n Max::Exact(n) => write!(f, \"= {}\", n),\n\n Max::LowerBound(n) => write!(f, \">= {}\", n),\n\n }\n\n }\n\n}\n\n\n\n// used to track indirect function calls (`fn` pointers)\n", "file_path": "src/main.rs", "rank": 56, "score": 30749.497647463715 }, { "content": "#![feature(asm)]\n\n#![no_main]\n\n#![no_std]\n\n\n\nextern crate panic_halt;\n\n\n\nuse core::sync::atomic::{AtomicPtr, Ordering};\n\n\n\nuse cortex_m_rt::{entry, exception};\n\n\n\nstatic F: AtomicPtr<fn() -> bool> = AtomicPtr::new(foo as *mut _);\n\n\n\n#[inline(never)]\n\n#[entry]\n", "file_path": "cortex-m-examples/examples/fn.rs", "rank": 68, "score": 26375.272680264985 }, { "content": "fn dot(g: Graph<Node, ()>, cycles: &[Vec<NodeIndex>]) -> io::Result<()> {\n\n let stdout = io::stdout();\n\n let mut stdout = stdout.lock();\n\n\n\n writeln!(stdout, \"digraph {{\")?;\n\n writeln!(stdout, \" node [fontname={} shape=box]\", FONT)?;\n\n\n\n for (i, node) in g.raw_nodes().iter().enumerate() {\n\n let node = &node.weight;\n\n\n\n write!(stdout, \" {} [label=\\\"\", i,)?;\n\n\n\n let mut escaper = Escaper::new(&mut stdout);\n\n write!(escaper, \"{}\", rustc_demangle::demangle(&node.name)).ok();\n\n escaper.error?;\n\n\n\n if let Some(max) = node.max {\n\n write!(stdout, \"\\\\nmax {}\", max)?;\n\n }\n\n\n", "file_path": "src/main.rs", "rank": 69, "score": 25739.098250628194 }, { "content": "use nom::{types::CompleteStr, *};\n\n\n\nuse crate::ir::{FnSig, Type};\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct Define<'a> {\n\n pub name: &'a str,\n\n pub sig: FnSig<'a>,\n\n pub stmts: Vec<Stmt<'a>>,\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum Stmt<'a> {\n\n // ` call void asm sideeffect \"cpsid i\"`\n\n Asm(&'a str),\n\n\n\n BitcastCall(Option<&'a str>),\n\n\n\n DirectCall(&'a str),\n\n\n", "file_path": "src/ir/define.rs", "rank": 70, "score": 25.948205075625125 }, { "content": " fields: separated_list!(do_parse!(char!(',') >> space >> (())), type_) >> space0 >>\n\n char!('}') >>\n\n (fields)\n\n));\n\n\n\nnamed!(packed_struct<CompleteStr, Type>, do_parse!(\n\n char!('<') >>\n\n fields: _struct >>\n\n char!('>') >>\n\n (Type::PackedStruct(fields))\n\n));\n\n\n\nnamed!(struct_<CompleteStr, Type>, map!(_struct, Type::Struct));\n\n\n", "file_path": "src/ir/ty.rs", "rank": 71, "score": 25.465463416510012 }, { "content": "use core::{fmt, str::FromStr};\n\n\n\nuse nom::{types::CompleteStr, *};\n\n\n\nuse crate::ir::FnSig;\n\n\n\n// NOTE we don't keep track of pointers; `i8` and `i8*` are both considered `Type::Integer`\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub enum Type<'a> {\n\n // `%\"crate::module::Struct::<ConcreteType>\"`\n\n Alias(&'a str),\n\n\n\n // `[0 x i8]`\n\n Array(usize, Box<Type<'a>>),\n\n\n\n // `double`\n\n Double,\n\n\n\n // `float`\n\n Float,\n", "file_path": "src/ir/ty.rs", "rank": 72, "score": 25.455774811087952 }, { "content": "use core::fmt;\n\n\n\nuse failure::format_err;\n\nuse nom::{types::CompleteStr, *};\n\n\n\nmod define;\n\nmod item;\n\nmod ty;\n\n\n\npub use crate::ir::{\n\n define::{Define, Stmt},\n\n item::{Declare, Item},\n\n ty::{type_, Type},\n\n};\n\n\n\n#[derive(Clone, Debug, Eq, Hash, PartialEq)]\n\npub struct FnSig<'a> {\n\n pub inputs: Vec<Type<'a>>,\n\n pub output: Option<Box<Type<'a>>>,\n\n}\n", "file_path": "src/ir.rs", "rank": 73, "score": 24.427943482596877 }, { "content": "\n\n Type::Fn(sig) => {\n\n write!(f, \"{}\", sig)?;\n\n }\n\n\n\n Type::Pointer(ty) => {\n\n write!(f, \"{}\", ty)?;\n\n f.write_str(\"*\")?;\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nnamed!(array<CompleteStr, Type>, delimited!(\n\n char!('['),\n\n do_parse!(\n\n count: map_res!(digit, |cs: CompleteStr| usize::from_str(cs.0)) >> space >>\n\n char!('x') >> space >>\n", "file_path": "src/ir/ty.rs", "rank": 74, "score": 23.813660659459952 }, { "content": " ty: type_ >>\n\n (Type::Array(count, Box::new(ty)))\n\n ),\n\n char!(']')\n\n));\n\n\n\nnamed!(double<CompleteStr, Type>, map!(tag!(\"double\"), |_| Type::Double));\n\n\n\nnamed!(float<CompleteStr, Type>, map!(tag!(\"float\"), |_| Type::Float));\n\n\n\nnamed!(integer<CompleteStr, Type>, do_parse!(\n\n char!('i') >>\n\n count: map_res!(digit, |cs: CompleteStr| usize::from_str(cs.0)) >>\n\n (Type::Integer(count)))\n\n);\n\n\n\nnamed!(alias<CompleteStr, Type>, map!(super::alias, |a| Type::Alias(a.0)));\n\n\n\nnamed!(_struct<CompleteStr, Vec<Type>>, do_parse!(\n\n char!('{') >> space0 >>\n", "file_path": "src/ir/ty.rs", "rank": 75, "score": 23.30811645798356 }, { "content": " // TODO we likely want to parse the metadata (`!dbg !0`) that comes after the parameter list\n\n not_line_ending >> line_ending >>\n\n stmts: separated_nonempty_list!(many1!(line_ending), call!(super::define::stmt)) >>\n\n opt!(line_ending) >> tag!(\"}\") >>\n\n (Define { name: name.0, stmts, sig: FnSig { inputs, output: output.map(Box::new) } })\n\n));\n\n\n\nnamed!(label<CompleteStr, Stmt>, do_parse!(\n\n alt!(map!(super::ident, drop) | map!(super::string, drop)) >>\n\n char!(':') >>\n\n opt!(do_parse!(space >> call!(super::comment) >> ())) >>\n\n (Stmt::Label)\n\n));\n\n\n\nnamed!(comment<CompleteStr, Stmt>, do_parse!(\n\n call!(super::comment) >>\n\n (Stmt::Comment)\n\n));\n\n\n\nnamed!(asm<CompleteStr, Stmt>, do_parse!(\n", "file_path": "src/ir/define.rs", "rank": 76, "score": 20.00339543127449 }, { "content": " alt!(tag!(\"call\") | tag!(\"invoke\")) >> space >>\n\n many0!(do_parse!(call!(super::attribute) >> space >> (()))) >>\n\n output: alt!(map!(call!(super::type_), Some) | map!(tag!(\"void\"), |_| None)) >> space >>\n\n char!('%') >> digit >>\n\n inputs: delimited!(\n\n char!('('),\n\n separated_list!(\n\n do_parse!(char!(',') >> space >> (())),\n\n map!(argument, |arg| arg.0)\n\n ),\n\n char!(')')\n\n ) >>\n\n // TODO we likely want to parse the metadata (`!dbg !0`) that comes after the argument list\n\n // NOTE shortcut\n\n not_line_ending >>\n\n (Stmt::IndirectCall(FnSig { inputs, output: output.map(Box::new) }))\n\n));\n\n\n\nnamed!(other<CompleteStr, Stmt>, do_parse!(\n\n separated_nonempty_list!(\n", "file_path": "src/ir/define.rs", "rank": 77, "score": 18.904083831226778 }, { "content": " rest = rest_;\n\n ty = Type::Pointer(Box::new(ty));\n\n }\n\n }\n\n } else {\n\n break;\n\n }\n\n }\n\n\n\n Ok((rest, ty))\n\n }\n\n}\n\n\n\nnamed!(fn_inputs<CompleteStr, Vec<Type>>, do_parse!(\n\n char!('(') >> space0 >>\n\n inputs: separated_list!(do_parse!(char!(',') >> space >> (())), type_) >>\n\n char!(')') >>\n\n (inputs)\n\n));\n\n\n", "file_path": "src/ir/ty.rs", "rank": 78, "score": 18.764838166643184 }, { "content": ");\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub struct Function<'a>(pub &'a str);\n\n\n\nnamed!(function<CompleteStr, Function>, do_parse!(\n\n char!('@') >>\n\n name: name >>\n\n (Function(name))\n\n));\n\n\n", "file_path": "src/ir.rs", "rank": 79, "score": 18.308284138819044 }, { "content": " )\n\n));\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use nom::types::CompleteStr as S;\n\n\n\n use super::{Argument, Define, Parameter};\n\n use crate::ir::{FnSig, Stmt, Type};\n\n\n\n #[test]\n\n fn argument() {\n\n assert_eq!(\n\n super::argument(S(r#\"{}* nonnull align 1 %3\"#)),\n\n Ok((\n\n S(\"\"),\n\n Argument(Type::Pointer(Box::new(Type::Struct(vec![]))))\n\n ))\n\n );\n\n\n", "file_path": "src/ir/define.rs", "rank": 80, "score": 17.361917384170077 }, { "content": "\n\n // `i8`\n\n Integer(usize),\n\n\n\n // `<{ i8, i16 }>`\n\n PackedStruct(Vec<Type<'a>>),\n\n\n\n // `{ i8, [0 x i16] }`\n\n Struct(Vec<Type<'a>>),\n\n\n\n // `i32 (i32)`\n\n Fn(FnSig<'a>),\n\n\n\n // `i8*`\n\n Pointer(Box<Type<'a>>),\n\n}\n\n\n\nimpl<'a> Type<'a> {\n\n pub fn erased() -> Self {\n\n Type::Pointer(Box::new(Type::Struct(vec![])))\n", "file_path": "src/ir/ty.rs", "rank": 81, "score": 17.04462950155563 }, { "content": " space,\n\n map_res!(is_not!(\" \\t\\r\\n\"), |t: CompleteStr| if t.0 == \"call\" { Err(()) } else { Ok(()) })\n\n ) >>\n\n (Stmt::Other)\n\n));\n\n\n\n// NOTE we discard the LHS of assignments\n\nnamed!(assign<CompleteStr, Stmt>, do_parse!(\n\n call!(super::local) >> space >> char!('=') >> space >>\n\n rhs: alt!(asm | bitcast_call | direct_call | indirect_call | other) >>\n\n (rhs)\n\n));\n\n\n\nnamed!(pub stmt<CompleteStr, Stmt>, alt!(\n\n label |\n\n comment |\n\n do_parse!(\n\n space >>\n\n stmt: alt!(assign | asm | bitcast_call | direct_call | indirect_call | other) >>\n\n (stmt)\n", "file_path": "src/ir/define.rs", "rank": 82, "score": 16.79850733538888 }, { "content": " name: call!(super::bitcast) >>\n\n // NOTE shortcut\n\n not_line_ending >>\n\n (Stmt::BitcastCall(name.0))\n\n));\n\n\n\nnamed!(direct_call<CompleteStr, Stmt>, do_parse!(\n\n opt!(do_parse!(tag!(\"tail\") >> space >> (()))) >>\n\n alt!(tag!(\"call\") | tag!(\"invoke\")) >> space >>\n\n many0!(do_parse!(call!(super::attribute) >> space >> (()))) >>\n\n alt!(map!(call!(super::type_), drop) | map!(tag!(\"void\"), drop)) >> space >>\n\n name: call!(super::function) >>\n\n // TODO we likely want to parse the metadata (`!dbg !0`) that comes after the argument list\n\n // NOTE shortcut\n\n char!('(') >> not_line_ending >>\n\n (Stmt::DirectCall(name.0))\n\n));\n\n\n\nnamed!(indirect_call<CompleteStr, Stmt>, do_parse!(\n\n opt!(do_parse!(tag!(\"tail\") >> space >> (()))) >>\n", "file_path": "src/ir/define.rs", "rank": 83, "score": 15.742036522842312 }, { "content": "\n\nimpl<'a> fmt::Display for Type<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Type::Alias(name) => {\n\n f.write_str(\"%\\\"\")?;\n\n f.write_str(name)?;\n\n f.write_str(\"\\\"\")?;\n\n }\n\n\n\n Type::Array(count, ty) => {\n\n f.write_str(\"[\")?;\n\n write!(f, \"{}\", count)?;\n\n f.write_str(\" x \")?;\n\n write!(f, \"{}\", ty)?;\n\n f.write_str(\"]\")?;\n\n }\n\n\n\n Type::Double => {\n\n f.write_str(\"double\")?;\n", "file_path": "src/ir/ty.rs", "rank": 84, "score": 14.367757448868307 }, { "content": " IndirectCall(FnSig<'a>),\n\n\n\n Comment,\n\n\n\n // `start:`\n\n Label,\n\n\n\n Other,\n\n}\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n", "file_path": "src/ir/define.rs", "rank": 85, "score": 13.66793721382347 }, { "content": " }\n\n\n\n // is this a function?\n\n loop {\n\n let (rest_, inputs) = opt!(rest, do_parse!(space >> inputs: fn_inputs >> (inputs)))?;\n\n\n\n if let Some(inputs) = inputs {\n\n rest = rest_;\n\n ty = Type::Fn(FnSig {\n\n inputs,\n\n output: Some(Box::new(ty)),\n\n });\n\n\n\n // is this a function pointer?\n\n loop {\n\n let (rest_, start) = opt!(rest, char!('*'))?;\n\n\n\n if start.is_none() {\n\n break;\n\n } else {\n", "file_path": "src/ir/ty.rs", "rank": 86, "score": 13.650691034564527 }, { "content": " }\n\n\n\n Type::Float => {\n\n f.write_str(\"float\")?;\n\n }\n\n\n\n Type::Integer(n) => {\n\n f.write_str(\"i\")?;\n\n write!(f, \"{}\", n)?;\n\n }\n\n\n\n Type::PackedStruct(fields) => {\n\n f.write_str(\"<\")?;\n\n fmt_struct(f, fields)?;\n\n f.write_str(\">\")?;\n\n }\n\n\n\n Type::Struct(fields) => {\n\n fmt_struct(f, fields)?;\n\n }\n", "file_path": "src/ir/ty.rs", "rank": 87, "score": 13.031692753949425 }, { "content": " assert_eq!(\n\n super::parse(S(\n\n r#\"define noalias void ()** @foo() unnamed_addr #0 !dbg !1272 {\n\nstart:\n\n ret void ()** null, !dbg !1278\n\n}\"#\n\n )),\n\n Ok((\n\n S(\"\"),\n\n Define {\n\n name: \"foo\",\n\n stmts: vec![Stmt::Label, Stmt::Other],\n\n sig: FnSig {\n\n inputs: vec![],\n\n output: Some(Box::new(Type::Pointer(Box::new(Type::Pointer(Box::new(\n\n Type::Fn(FnSig {\n\n inputs: vec![],\n\n output: None,\n\n })\n\n )))))),\n", "file_path": "src/ir/define.rs", "rank": 88, "score": 12.878074461047396 }, { "content": " }\n\n\n\n // Rust uses the \"erased\" type `{}*` for dynamic dispatch\n\n pub fn has_been_erased(&self) -> bool {\n\n match self {\n\n Type::Pointer(ty) => match **ty {\n\n Type::Struct(ref fields) => fields.is_empty(),\n\n _ => false,\n\n },\n\n _ => false,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/ir/ty.rs", "rank": 89, "score": 12.796747032787911 }, { "content": " match canonical_name {\n\n \"__aeabi_memcpy\" | \"__aeabi_memcpy4\" | \"__aeabi_memcpy8\" => {\n\n // `fn(*mut u8, *const u8, usize)`\n\n let sig = FnSig {\n\n inputs: vec![\n\n Type::Pointer(Box::new(Type::Integer(8))),\n\n Type::Pointer(Box::new(Type::Integer(8))),\n\n Type::Integer(32), // ARM has 32-bit pointers\n\n ],\n\n output: None,\n\n };\n\n indirects.entry(sig).or_default().callees.insert(idx);\n\n }\n\n\n\n \"__aeabi_memclr\" | \"__aeabi_memclr4\" | \"__aeabi_memclr8\" => {\n\n // `fn(*mut u8, usize)`\n\n let sig = FnSig {\n\n inputs: vec![\n\n Type::Pointer(Box::new(Type::Integer(8))),\n\n Type::Integer(32), // ARM has 32-bit pointers\n", "file_path": "src/main.rs", "rank": 90, "score": 12.756653115920804 }, { "content": " Ok((\n\n S(\"\"),\n\n Stmt::IndirectCall(FnSig {\n\n inputs: vec![\n\n Type::Pointer(Box::new(Type::Struct(vec![]))),\n\n Type::Pointer(Box::new(Type::Array(0, Box::new(Type::Integer(8))))),\n\n Type::Integer(64),\n\n ],\n\n output: Some(Box::new(Type::Integer(1)))\n\n })\n\n ))\n\n );\n\n\n\n assert_eq!(\n\n super::indirect_call(S(r#\"call zeroext i1 %98({}* nonnull align 1 %93, [0 x i8]* noalias nonnull readonly align 1 bitcast (<{ [10 x i8] }>* @1 to [0 x i8]*), i32 10) #10, !dbg !5301\"#)),\n\n Ok((\n\n S(\"\"),\n\n Stmt::IndirectCall(FnSig {\n\n inputs: vec![\n\n Type::Pointer(Box::new(Type::Struct(vec![]))),\n", "file_path": "src/ir/define.rs", "rank": 91, "score": 12.678566688238515 }, { "content": "#[cfg(test)]\n\nmod tests {\n\n use nom::types::CompleteStr as S;\n\n\n\n use crate::ir::{FnSig, Type};\n\n\n\n #[test]\n\n fn fn_inputs() {\n\n assert_eq!(super::fn_inputs(S(r#\"()\"#)), Ok((S(\"\"), vec![])));\n\n }\n\n\n\n #[test]\n\n fn sanity() {\n\n assert_eq!(super::integer(S(\"i8\")), Ok((S(\"\"), Type::Integer(8))));\n\n assert_eq!(super::integer(S(\"i16\")), Ok((S(\"\"), Type::Integer(16))));\n\n assert_eq!(super::integer(S(\"i32\")), Ok((S(\"\"), Type::Integer(32))));\n\n\n\n assert_eq!(\n\n super::array(S(\"[0 x i32]\")),\n\n Ok((S(\"\"), Type::Array(0, Box::new(Type::Integer(32)))))\n", "file_path": "src/ir/ty.rs", "rank": 92, "score": 12.329056326633953 }, { "content": "use clap::{crate_authors, crate_version, App, Arg};\n\nuse env_logger::{Builder, Env};\n\nuse filetime::FileTime;\n\nuse log::{error, warn};\n\nuse petgraph::{\n\n algo,\n\n graph::{DiGraph, NodeIndex},\n\n visit::{Dfs, Reversed, Topo},\n\n Direction, Graph,\n\n};\n\nuse walkdir::WalkDir;\n\nuse xmas_elf::{sections::SectionData, symbol_table::Entry, ElfFile};\n\n\n\nuse crate::{\n\n ir::{FnSig, Item, Stmt, Type},\n\n thumb::Tag,\n\n};\n\n\n\nmod ir;\n\nmod thumb;\n\n\n", "file_path": "src/main.rs", "rank": 93, "score": 12.234913919482398 }, { "content": " fn parse() {\n\n assert_eq!(\n\n super::parse(S(\n\n r#\"define internal void @_ZN4core3ptr18real_drop_in_place17h10d0d6d6b26fb8afE(%\"blue_pill::ItmLogger\"* nocapture nonnull align 1) unnamed_addr #0 !dbg !2105 {\n\nstart:\n\n ret void\n\n}\"#\n\n )),\n\n Ok(\n\n (S(\"\"),\n\n Define {\n\n name: \"_ZN4core3ptr18real_drop_in_place17h10d0d6d6b26fb8afE\",\n\n stmts: vec![Stmt::Label, Stmt::Other],\n\n sig: FnSig {\n\n inputs: vec![Type::Pointer(Box::new(Type::Alias(\"blue_pill::ItmLogger\")))],\n\n output: None,\n\n },\n\n }))\n\n );\n\n\n", "file_path": "src/ir/define.rs", "rank": 94, "score": 12.105741847957168 }, { "content": " for item in items {\n\n match item {\n\n Item::Define(def) => {\n\n defines.insert(def.name, def);\n\n }\n\n\n\n Item::Declare(decl) => {\n\n declares.insert(decl.name, decl);\n\n }\n\n\n\n _ => {}\n\n }\n\n }\n\n\n\n let target = project.target().or(target_flag).unwrap_or(&host);\n\n\n\n // we know how to analyze the machine code in the ELF file for these targets thus we have more\n\n // information and need less LLVM-IR hacks\n\n let target_ = match target {\n\n \"thumbv6m-none-eabi\" => Target::Thumbv6m,\n", "file_path": "src/main.rs", "rank": 95, "score": 11.986926600503367 }, { "content": " let sig = FnSig {\n\n inputs: vec![Type::Float],\n\n output: Some(Box::new(Type::Integer(32))),\n\n };\n\n indirects.entry(sig).or_default().callees.insert(idx);\n\n }\n\n\n\n \"__aeabi_ui2f\" | \"__aeabi_i2f\" => {\n\n // `fn({i,u}32) -> f32`\n\n let sig = FnSig {\n\n inputs: vec![Type::Integer(32)],\n\n output: Some(Box::new(Type::Float)),\n\n };\n\n indirects.entry(sig).or_default().callees.insert(idx);\n\n }\n\n\n\n \"__divmoddi4\" | \"__udivmoddi4\" => {\n\n // `fn({i,u}64, {i,u}64, *{i,u}64) -> {i,u}64`\n\n let sig = FnSig {\n\n inputs: vec![\n", "file_path": "src/main.rs", "rank": 96, "score": 11.948476965874006 }, { "content": " Ok((\n\n S(\"\"),\n\n Type::Pointer(Box::new(Type::Fn(FnSig {\n\n inputs: vec![Type::Integer(8)],\n\n output: Some(Box::new(Type::Integer(8))),\n\n })))\n\n ))\n\n );\n\n\n\n assert_eq!(\n\n super::type_(S(\"void ()**\")),\n\n Ok((\n\n S(\"\"),\n\n Type::Pointer(Box::new(Type::Pointer(Box::new(Type::Fn(FnSig {\n\n inputs: vec![],\n\n output: None,\n\n })))))\n\n ))\n\n );\n\n }\n\n}\n", "file_path": "src/ir/ty.rs", "rank": 97, "score": 11.748922227141186 }, { "content": " indices.insert(canonical_name.into(), idx);\n\n\n\n // trait methods look like `<crate::module::Type as crate::module::Trait>::method::h$hash`\n\n // default trait methods look like `crate::module::Trait::method::h$hash`\n\n let is_trait_method = demangled.starts_with(\"<\") && demangled.contains(\" as \") || {\n\n dehash(&demangled)\n\n .map(|path| default_methods.contains(path))\n\n .unwrap_or(false)\n\n };\n\n\n\n if let Some(def) = names.iter().filter_map(|name| defines.get(name)).next() {\n\n // if the signature is `fn(&_, &mut fmt::Formatter) -> fmt::Result`\n\n match (&def.sig.inputs[..], def.sig.output.as_ref()) {\n\n ([Type::Pointer(..), Type::Pointer(fmt)], Some(output))\n\n if **fmt == Type::Alias(\"core::fmt::Formatter\")\n\n && **output == Type::Integer(1) =>\n\n {\n\n fmts.insert(idx);\n\n }\n\n\n", "file_path": "src/main.rs", "rank": 98, "score": 11.588474329724836 }, { "content": " assert_eq!(\n\n super::parse(S(\n\n r#\"define internal fastcc void @_ZN3std10sys_common12thread_local22register_dtor_fallback17h254497a6d25774eeE(i8*, void (i8*)* nonnull) unnamed_addr #0 personality i32 (i32, i32, i64, %\"unwind::libunwind::_Unwind_Exception\"*, %\"unwind::libunwind::_Unwind_Context\"*)* @rust_eh_personality !dbg !5158 {\n\nstart:\n\n ret void\n\n}\"#\n\n )),\n\n Ok(\n\n (S(\"\"),\n\n Define {\n\n name: \"_ZN3std10sys_common12thread_local22register_dtor_fallback17h254497a6d25774eeE\",\n\n stmts: vec![Stmt::Label, Stmt::Other],\n\n sig: FnSig {\n\n inputs: vec![\n\n Type::Pointer(Box::new(Type::Integer(8))),\n\n Type::Pointer(Box::new(Type::Fn(FnSig {\n\n inputs: vec![Type::Pointer(Box::new(Type::Integer(8)))],\n\n output: None,\n\n }))),\n\n ],\n", "file_path": "src/ir/define.rs", "rank": 99, "score": 11.545224639680491 } ]
Rust
sqlx-core/src/query.rs
rage311/sqlx
249efbd36b07ce609b6d946c3fcd50653a6eccd0
use std::marker::PhantomData; use async_stream::try_stream; use either::Either; use futures_core::stream::BoxStream; use futures_util::{future, StreamExt, TryFutureExt, TryStreamExt}; use crate::arguments::{Arguments, IntoArguments}; use crate::database::{Database, HasArguments}; use crate::encode::Encode; use crate::error::Error; use crate::executor::{Execute, Executor}; #[must_use = "query must be executed to affect database"] pub struct Query<'q, DB: Database, A> { pub(crate) query: &'q str, pub(crate) arguments: Option<A>, pub(crate) database: PhantomData<DB>, } #[must_use = "query must be executed to affect database"] pub struct Map<'q, DB: Database, F, A> { inner: Query<'q, DB, A>, mapper: F, } impl<'q, DB, A> Execute<'q, DB> for Query<'q, DB, A> where DB: Database, A: Send + IntoArguments<'q, DB>, { #[inline] fn query(&self) -> &'q str { self.query } #[inline] fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments> { self.arguments.take().map(IntoArguments::into_arguments) } } impl<'q, DB: Database> Query<'q, DB, <DB as HasArguments<'q>>::Arguments> { pub fn bind<T: 'q + Encode<'q, DB>>(mut self, value: T) -> Self { if let Some(arguments) = &mut self.arguments { arguments.add(value); } self } } impl<'q, DB, A: Send> Query<'q, DB, A> where DB: Database, A: 'q + IntoArguments<'q, DB>, { #[inline] pub fn map<F, O>(self, f: F) -> Map<'q, DB, impl Fn(DB::Row) -> Result<O, Error>, A> where F: Fn(DB::Row) -> O, { self.try_map(move |row| Ok(f(row))) } #[inline] pub fn try_map<F, O>(self, f: F) -> Map<'q, DB, F, A> where F: Fn(DB::Row) -> Result<O, Error>, { Map { inner: self, mapper: f, } } #[inline] pub async fn execute<'e, 'c: 'e, E>(self, executor: E) -> Result<u64, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.execute(self).await } #[inline] pub async fn execute_many<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<u64, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.execute_many(self) } #[inline] pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<DB::Row, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch(self) } #[inline] pub fn fetch_many<'e, 'c: 'e, E>( self, executor: E, ) -> BoxStream<'e, Result<Either<u64, DB::Row>, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_many(self) } #[inline] pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result<Vec<DB::Row>, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_all(self).await } #[inline] pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<DB::Row, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_one(self).await } #[inline] pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result<Option<DB::Row>, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_optional(self).await } } impl<'q, DB, F: Send, A: Send> Execute<'q, DB> for Map<'q, DB, F, A> where DB: Database, A: IntoArguments<'q, DB>, { #[inline] fn query(&self) -> &'q str { self.inner.query() } #[inline] fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments> { self.inner.take_arguments() } } impl<'q, DB, F, O, A> Map<'q, DB, F, A> where DB: Database, F: Send + Sync + Fn(DB::Row) -> Result<O, Error>, O: Send + Unpin, A: 'q + Send + IntoArguments<'q, DB>, { pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<O, Error>> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch_many(executor) .try_filter_map(|step| async move { Ok(match step { Either::Left(_) => None, Either::Right(o) => Some(o), }) }) .boxed() } pub fn fetch_many<'e, 'c: 'e, E>( self, executor: E, ) -> BoxStream<'e, Result<Either<u64, O>, Error>> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { Box::pin(try_stream! { let mut s = executor.fetch_many(self.inner); while let Some(v) = s.try_next().await? { match v { Either::Left(v) => yield Either::Left(v), Either::Right(row) => { let mapped = (self.mapper)(row)?; yield Either::Right(mapped); } } } }) } pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result<Vec<O>, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch(executor).try_collect().await } pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch_optional(executor) .and_then(|row| match row { Some(row) => future::ok(row), None => future::err(Error::RowNotFound), }) .await } pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result<Option<O>, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { let row = executor.fetch_optional(self.inner).await?; if let Some(row) = row { (self.mapper)(row).map(Some) } else { Ok(None) } } } #[inline] pub fn query<DB>(sql: &str) -> Query<'_, DB, <DB as HasArguments<'_>>::Arguments> where DB: Database, { Query { database: PhantomData, arguments: Some(Default::default()), query: sql, } } #[inline] pub fn query_with<'q, DB, A>(sql: &'q str, arguments: A) -> Query<'q, DB, A> where DB: Database, A: IntoArguments<'q, DB>, { Query { database: PhantomData, arguments: Some(arguments), query: sql, } }
use std::marker::PhantomData; use async_stream::try_stream; use either::Either; use futures_core::stream::BoxStream; use futures_util::{future, StreamExt, TryFutureExt, TryStreamExt}; use crate::arguments::{Arguments, IntoArguments}; use crate::database::{Database, HasArguments}; use crate::encode::Encode; use crate::error::Error; use crate::executor::{Execute, Executor}; #[must_use = "query must be executed to affect database"] pub struct Query<'q, DB: Database, A> { pub(crate) query: &'q str, pub(crate) arguments: Option<A>, pub(crate) database: PhantomData<DB>, } #[must_use = "query must be executed to affect database"] pub struct Map<'q, DB: Database, F, A> { inner: Query<'q, DB, A>, mapper: F, } impl<'q, DB, A> Execute<'q, DB> for Query<'q, DB, A> where DB: Database, A: Send + IntoArguments<'q, DB>, { #[inline] fn query(&self) -> &'q str { self.query } #[inline] fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments> { self.arguments.take().map(IntoArguments::into_arguments) } } impl<'q, DB: Database> Query<'q, DB, <DB as HasArguments<'q>>::Arguments> { pub fn bind<T: 'q + Encode<'q, DB>>(mut self, value: T) -> Self { if let Some(arguments) = &mut self.arguments { arguments.add(value); } self } } impl<'q, DB, A: Send> Query<'q, DB, A> where DB: Database, A: 'q + IntoArguments<'q, DB>, { #[inline] pub fn map<F, O>(self, f: F) -> Map<'q, DB, impl Fn(DB::Row) -> Result<O, Error>, A> where F: Fn(DB::Row) -> O, { self.try_map(move |row| Ok(f(row))) } #[inline] pub fn try_map<F, O>(self, f: F) -> Map<'q, DB, F, A> where F: Fn(DB::Row) -> Result<O, Error>, { Map { inner: self, mapper: f, } } #[inline] pub async fn execute<'e, 'c: 'e, E>(self, executor: E) -> Result<u64, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.execute(self).await } #[inline] pub async fn execute_many<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<u64, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.execute_many(self) } #[inline] pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<DB::Row, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch(self) } #[inline] pub fn fetch_many<'e, 'c: 'e, E>( self, executor: E, ) -> BoxStream<'e, Result<Either<u64, DB::Row>, Error>> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_many(self) } #[inline] pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result<Vec<DB::Row>, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_all(self).await } #[inline] pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<DB::Row, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_one(self).await } #[inline] pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result<Option<DB::Row>, Error> where 'q: 'e, A: 'e, E: Executor<'c, Database = DB>, { executor.fetch_optional(self).await } } impl<'q, DB, F: Send, A: Send> Execute<'q, DB> for Map<'q, DB, F, A> where DB: Database, A: IntoArguments<'q, DB>, { #[inline] fn query(&self) -> &'q str { self.inner.query() } #[inline] fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments> { self.inner.take_arguments() } } impl<'q, DB, F, O, A> Map<'q, DB, F, A> where DB: Database, F: Send + Sync + Fn(DB::Row) -> Result<O, Error>, O: Send + Unpin, A: 'q + Send + IntoArguments<'q, DB>, { pub fn fetch<'e, 'c: 'e, E>(self, executor: E) -> BoxStream<'e, Result<O, Error>> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch_many(executor) .try_fi
ither::Right(mapped); } } } }) } pub async fn fetch_all<'e, 'c: 'e, E>(self, executor: E) -> Result<Vec<O>, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch(executor).try_collect().await } pub async fn fetch_one<'e, 'c: 'e, E>(self, executor: E) -> Result<O, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { self.fetch_optional(executor) .and_then(|row| match row { Some(row) => future::ok(row), None => future::err(Error::RowNotFound), }) .await } pub async fn fetch_optional<'e, 'c: 'e, E>(self, executor: E) -> Result<Option<O>, Error> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { let row = executor.fetch_optional(self.inner).await?; if let Some(row) = row { (self.mapper)(row).map(Some) } else { Ok(None) } } } #[inline] pub fn query<DB>(sql: &str) -> Query<'_, DB, <DB as HasArguments<'_>>::Arguments> where DB: Database, { Query { database: PhantomData, arguments: Some(Default::default()), query: sql, } } #[inline] pub fn query_with<'q, DB, A>(sql: &'q str, arguments: A) -> Query<'q, DB, A> where DB: Database, A: IntoArguments<'q, DB>, { Query { database: PhantomData, arguments: Some(arguments), query: sql, } }
lter_map(|step| async move { Ok(match step { Either::Left(_) => None, Either::Right(o) => Some(o), }) }) .boxed() } pub fn fetch_many<'e, 'c: 'e, E>( self, executor: E, ) -> BoxStream<'e, Result<Either<u64, O>, Error>> where 'q: 'e, E: 'e + Executor<'c, Database = DB>, DB: 'e, F: 'e, O: 'e, { Box::pin(try_stream! { let mut s = executor.fetch_many(self.inner); while let Some(v) = s.try_next().await? { match v { Either::Left(v) => yield Either::Left(v), Either::Right(row) => { let mapped = (self.mapper)(row)?; yield E
random
[ { "content": "#[inline]\n\npub fn query_as<'q, DB, O>(sql: &'q str) -> QueryAs<'q, DB, O, <DB as HasArguments<'q>>::Arguments>\n\nwhere\n\n DB: Database,\n\n O: for<'r> FromRow<'r, DB::Row>,\n\n{\n\n QueryAs {\n\n inner: query(sql),\n\n output: PhantomData,\n\n }\n\n}\n\n\n\n/// Make a SQL query, with the given arguments, that is mapped to a concrete type\n\n/// using [`FromRow`](crate::row::FromRow).\n", "file_path": "sqlx-core/src/query_as.rs", "rank": 0, "score": 393892.0144496772 }, { "content": "/// A type that may be executed against a database connection.\n\n///\n\n/// Implemented for the following:\n\n///\n\n/// * [`&str`]\n\n/// * [`Query`]\n\n///\n\npub trait Execute<'q, DB: Database>: Send + Sized {\n\n /// Returns the query string that will be executed.\n\n fn query(&self) -> &'q str;\n\n\n\n /// Returns the arguments to be bound against the query string.\n\n ///\n\n /// Returning `None` for `Arguments` indicates to use a \"simple\" query protocol and to not\n\n /// prepare the query. Returning `Some(Default::default())` is an empty arguments object that\n\n /// will be prepared (and cached) before execution.\n\n fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments>;\n\n}\n\n\n\n// NOTE: `Execute` is explicitly not implemented for String and &String to make it slightly more\n\n// involved to write `conn.execute(format!(\"SELECT {}\", val))`\n\nimpl<'q, DB: Database> Execute<'q, DB> for &'q str {\n\n #[inline]\n\n fn query(&self) -> &'q str {\n\n self\n\n }\n\n\n\n #[inline]\n\n fn take_arguments(&mut self) -> Option<<DB as HasArguments<'q>>::Arguments> {\n\n None\n\n }\n\n}\n", "file_path": "sqlx-core/src/executor.rs", "rank": 2, "score": 386228.412980257 }, { "content": "#[inline]\n\npub fn query_as_with<'q, DB, O, A>(sql: &'q str, arguments: A) -> QueryAs<'q, DB, O, A>\n\nwhere\n\n DB: Database,\n\n A: IntoArguments<'q, DB>,\n\n O: for<'r> FromRow<'r, DB::Row>,\n\n{\n\n QueryAs {\n\n inner: query_with(sql, arguments),\n\n output: PhantomData,\n\n }\n\n}\n", "file_path": "sqlx-core/src/query_as.rs", "rank": 4, "score": 376820.35812735895 }, { "content": "#[inline]\n\npub fn query_scalar_with<'q, DB, O, A>(sql: &'q str, arguments: A) -> QueryScalar<'q, DB, O, A>\n\nwhere\n\n DB: Database,\n\n A: IntoArguments<'q, DB>,\n\n (O,): for<'r> FromRow<'r, DB::Row>,\n\n{\n\n QueryScalar {\n\n inner: query_as_with(sql, arguments),\n\n }\n\n}\n", "file_path": "sqlx-core/src/query_scalar.rs", "rank": 5, "score": 365843.76414981607 }, { "content": "/// Represents a single row from the database.\n\n///\n\n/// This trait is sealed and cannot be implemented for types outside of SQLx.\n\n///\n\n/// [`FromRow`]: crate::row::FromRow\n\n/// [`Cursor`]: crate::cursor::Cursor\n\n/// [`Query::fetch`]: crate::query::Query::fetch\n\npub trait Row: private_row::Sealed + Unpin + Send + Sync + 'static {\n\n type Database: Database;\n\n\n\n /// Returns `true` if this row has no columns.\n\n #[inline]\n\n fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n\n\n /// Returns the number of columns in this row.\n\n fn len(&self) -> usize;\n\n\n\n /// Index into the database row and decode a single value.\n\n ///\n\n /// A string index can be used to access a column by name and a `usize` index\n\n /// can be used to access a column by position.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the column does not exist or its value cannot be decoded into the requested type.\n", "file_path": "sqlx-core/src/row.rs", "rank": 6, "score": 341046.2169666618 }, { "content": "pub trait IntoArguments<'q, DB: HasArguments<'q>>: Sized + Send {\n\n fn into_arguments(self) -> <DB as HasArguments<'q>>::Arguments;\n\n}\n\n\n\n// NOTE: required due to lack of lazy normalization\n\n#[allow(unused_macros)]\n\nmacro_rules! impl_into_arguments_for_arguments {\n\n ($Arguments:path) => {\n\n impl<'q>\n\n crate::arguments::IntoArguments<\n\n 'q,\n\n <$Arguments as crate::arguments::Arguments<'q>>::Database,\n\n > for $Arguments\n\n {\n\n fn into_arguments(self) -> $Arguments {\n\n self\n\n }\n\n }\n\n };\n\n}\n\n\n\n// TODO: Impl `IntoArguments` for &[&dyn Encode]\n\n// TODO: Impl `IntoArguments` for (impl Encode, ...) x16\n", "file_path": "sqlx-core/src/arguments.rs", "rank": 7, "score": 293847.2888450593 }, { "content": "#[inline]\n\npub fn query_scalar<'q, DB, O>(\n\n sql: &'q str,\n\n) -> QueryScalar<'q, DB, O, <DB as HasArguments<'q>>::Arguments>\n\nwhere\n\n DB: Database,\n\n (O,): for<'r> FromRow<'r, DB::Row>,\n\n{\n\n QueryScalar {\n\n inner: query_as(sql),\n\n }\n\n}\n\n\n\n/// Make a SQL query, with the given arguments, that is mapped to a single concrete type\n\n/// using [`FromRow`](crate::row::FromRow).\n", "file_path": "sqlx-core/src/query_scalar.rs", "rank": 8, "score": 292685.08426849986 }, { "content": "pub fn quote_query_as<DB: DatabaseExt>(\n\n input: &QueryMacroInput,\n\n out_ty: &Type,\n\n bind_args: &Ident,\n\n columns: &[RustColumn],\n\n) -> TokenStream {\n\n let instantiations = columns.iter().enumerate().map(\n\n |(\n\n i,\n\n &RustColumn {\n\n ref ident,\n\n ref type_,\n\n ..\n\n },\n\n )| {\n\n // For \"checked\" queries, the macro checks these at compile time and using \"try_get\"\n\n // would also perform pointless runtime checks\n\n\n\n if input.checked {\n\n quote!( #ident: row.try_get_unchecked::<#type_, _>(#i).try_unwrap_optional()? )\n", "file_path": "sqlx-macros/src/query/output.rs", "rank": 9, "score": 267975.2512652048 }, { "content": "/// An error that was returned from the database.\n\npub trait DatabaseError: 'static + Send + Sync + StdError {\n\n /// The primary, human-readable error message.\n\n fn message(&self) -> &str;\n\n\n\n /// The (SQLSTATE) code for the error.\n\n fn code(&self) -> Option<Cow<'_, str>> {\n\n None\n\n }\n\n\n\n #[doc(hidden)]\n\n fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static);\n\n\n\n #[doc(hidden)]\n\n fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);\n\n\n\n #[doc(hidden)]\n\n fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;\n\n}\n\n\n\nimpl dyn DatabaseError {\n", "file_path": "sqlx-core/src/error.rs", "rank": 10, "score": 264285.2471983814 }, { "content": "/// Returns a tokenstream which typechecks the arguments passed to the macro\n\n/// and binds them to `DB::Arguments` with the ident `query_args`.\n\npub fn quote_args<DB: DatabaseExt>(\n\n input: &QueryMacroInput,\n\n describe: &Describe<DB>,\n\n) -> crate::Result<TokenStream> {\n\n let db_path = DB::db_path();\n\n\n\n if input.arg_names.is_empty() {\n\n return Ok(quote! {\n\n let query_args = <#db_path as sqlx::database::HasArguments>::Arguments::default();\n\n });\n\n }\n\n\n\n let arg_name = &input.arg_names;\n\n\n\n let args_check = if input.checked && DB::PARAM_CHECKING == ParamChecking::Strong {\n\n describe\n\n .params\n\n .iter()\n\n .zip(input.arg_names.iter().zip(&input.arg_exprs))\n\n .enumerate()\n", "file_path": "sqlx-macros/src/query/args.rs", "rank": 11, "score": 256831.7737364165 }, { "content": "/// A type that contains or can provide a database\n\n/// connection to use for executing queries against the database.\n\n///\n\n/// No guarantees are provided that successive queries run on the same\n\n/// physical database connection.\n\n///\n\n/// A [`Connection`](crate::connection::Connection) is an `Executor` that guarantees that\n\n/// successive queries are ran on the same physical database connection.\n\n///\n\n/// Implemented for the following:\n\n///\n\n/// * [`&Pool`]\n\n/// * [`&mut PoolConnection`]\n\n/// * [`&mut Connection`]\n\n///\n\npub trait Executor<'c>: Send + Debug + Sized {\n\n type Database: Database;\n\n\n\n /// Execute the query and return the total number of rows affected.\n\n fn execute<'e, 'q: 'e, E: 'q>(self, query: E) -> BoxFuture<'e, Result<u64, Error>>\n\n where\n\n 'c: 'e,\n\n E: Execute<'q, Self::Database>,\n\n {\n\n self.execute_many(query)\n\n .try_fold(0, |acc, x| async move { Ok(acc + x) })\n\n .boxed()\n\n }\n\n\n\n /// Execute multiple queries and return the rows affected from each query, in a stream.\n\n fn execute_many<'e, 'q: 'e, E: 'q>(self, query: E) -> BoxStream<'e, Result<u64, Error>>\n\n where\n\n 'c: 'e,\n\n E: Execute<'q, Self::Database>,\n\n {\n", "file_path": "sqlx-core/src/executor.rs", "rank": 12, "score": 248241.43461900225 }, { "content": "fn build_listen_all_query(channels: impl IntoIterator<Item = impl AsRef<str>>) -> String {\n\n channels.into_iter().fold(String::new(), |mut acc, chan| {\n\n acc.push_str(r#\"LISTEN \"\"#);\n\n acc.push_str(&ident(chan.as_ref()));\n\n acc.push_str(r#\"\";\"#);\n\n acc\n\n })\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/listener.rs", "rank": 13, "score": 244094.05839890975 }, { "content": "#[inline]\n\nfn encode_startup_param(buf: &mut Vec<u8>, name: &str, value: &str) {\n\n buf.put_str_nul(name);\n\n buf.put_str_nul(value);\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/startup.rs", "rank": 14, "score": 241273.1146880663 }, { "content": "pub fn columns_to_rust<DB: DatabaseExt>(describe: &Describe<DB>) -> crate::Result<Vec<RustColumn>> {\n\n describe\n\n .columns\n\n .iter()\n\n .enumerate()\n\n .map(|(i, column)| -> crate::Result<_> {\n\n let name = &*column.name;\n\n let ident = parse_ident(name)?;\n\n\n\n let mut type_ = if let Some(type_info) = &column.type_info {\n\n <DB as DatabaseExt>::return_type_for_id(&type_info).map_or_else(\n\n || {\n\n let message = if let Some(feature_gate) =\n\n <DB as DatabaseExt>::get_feature_gate(&type_info)\n\n {\n\n format!(\n\n \"optional feature `{feat}` required for type {ty} of {col}\",\n\n ty = &type_info,\n\n feat = feature_gate,\n\n col = DisplayColumn {\n", "file_path": "sqlx-macros/src/query/output.rs", "rank": 15, "score": 229355.44681289064 }, { "content": "/// A tuple of arguments to be sent to the database.\n\npub trait Arguments<'q>: Send + Sized + Default {\n\n type Database: Database;\n\n\n\n /// Reserves the capacity for at least `additional` more values (of `size` total bytes) to\n\n /// be added to the arguments without a reallocation.\n\n fn reserve(&mut self, additional: usize, size: usize);\n\n\n\n /// Add the value to the end of the arguments.\n\n fn add<T>(&mut self, value: T)\n\n where\n\n T: 'q + Encode<'q, Self::Database>;\n\n}\n\n\n", "file_path": "sqlx-core/src/arguments.rs", "rank": 16, "score": 222592.6958606341 }, { "content": "#[allow(unused_variables)]\n\nfn expand_from_db(input: QueryMacroInput, db_url: &str) -> crate::Result<TokenStream> {\n\n // FIXME: Introduce [sqlx::any::AnyConnection] and [sqlx::any::AnyDatabase] to support\n\n // runtime determinism here\n\n\n\n let db_url = Url::parse(db_url)?;\n\n match db_url.scheme() {\n\n #[cfg(feature = \"postgres\")]\n\n \"postgres\" | \"postgresql\" => {\n\n let data = block_on(async {\n\n let mut conn = sqlx_core::postgres::PgConnection::connect(db_url.as_str()).await?;\n\n QueryData::from_db(&mut conn, &input.src).await\n\n })?;\n\n\n\n expand_with_data(input, data)\n\n },\n\n #[cfg(not(feature = \"postgres\"))]\n\n \"postgres\" | \"postgresql\" => Err(format!(\"database URL has the scheme of a PostgreSQL database but the `postgres` feature is not enabled\").into()),\n\n #[cfg(feature = \"mysql\")]\n\n \"mysql\" | \"mariadb\" => {\n\n let data = block_on(async {\n", "file_path": "sqlx-macros/src/query/mod.rs", "rank": 17, "score": 221348.66141255497 }, { "content": "#[cfg(any(feature = \"runtime-tokio\", feature = \"runtime-actix\"))]\n\npub fn block_on<F: std::future::Future>(future: F) -> F::Output {\n\n use once_cell::sync::Lazy;\n\n use tokio::runtime::{self, Runtime};\n\n\n\n // lazily initialize a global runtime once for multiple invocations of the macros\n\n static RUNTIME: Lazy<Runtime> = Lazy::new(|| {\n\n runtime::Builder::new()\n\n // `.basic_scheduler()` requires calling `Runtime::block_on()` which needs mutability\n\n .threaded_scheduler()\n\n .enable_io()\n\n .enable_time()\n\n .build()\n\n .expect(\"failed to initialize Tokio runtime\")\n\n });\n\n\n\n RUNTIME.enter(|| futures::executor::block_on(future))\n\n}\n", "file_path": "sqlx-macros/src/runtime.rs", "rank": 18, "score": 215400.45228281769 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_command_complete_rows_affected(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"INSERT 0 1214\\0\";\n\n\n\n let data = CommandComplete::decode(Bytes::from_static(DATA)).unwrap();\n\n\n\n b.iter(|| {\n\n let _rows = test::black_box(&data).rows_affected();\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/command_complete.rs", "rank": 19, "score": 211295.69030123184 }, { "content": "fn ident(mut name: &str) -> String {\n\n // If the input string contains a NUL byte, we should truncate the\n\n // identifier.\n\n if let Some(index) = name.find('\\0') {\n\n name = &name[..index];\n\n }\n\n\n\n // Any double quotes must be escaped\n\n name.replace('\"', \"\\\"\\\"\")\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/listener.rs", "rank": 20, "score": 211256.86440579797 }, { "content": "pub fn add_file(name: &str) -> anyhow::Result<()> {\n\n use chrono::prelude::*;\n\n use std::path::PathBuf;\n\n\n\n fs::create_dir_all(MIGRATION_FOLDER).context(\"Unable to create migrations directory\")?;\n\n\n\n let dt = Utc::now();\n\n let mut file_name = dt.format(\"%Y-%m-%d_%H-%M-%S\").to_string();\n\n file_name.push_str(\"_\");\n\n file_name.push_str(name);\n\n file_name.push_str(\".sql\");\n\n\n\n let mut path = PathBuf::new();\n\n path.push(MIGRATION_FOLDER);\n\n path.push(&file_name);\n\n\n\n let mut file = File::create(path).context(\"Failed to create file\")?;\n\n file.write_all(b\"-- Add migration script here\")\n\n .context(\"Could not write to file\")?;\n\n\n", "file_path": "sqlx-cli/src/migration.rs", "rank": 21, "score": 203180.30026085855 }, { "content": "#[cfg(feature = \"offline\")]\n\npub fn expand_from_file(\n\n input: QueryMacroInput,\n\n file: std::path::PathBuf,\n\n) -> crate::Result<TokenStream> {\n\n use data::offline::DynQueryData;\n\n\n\n let query_data = DynQueryData::from_data_file(file, &input.src)?;\n\n assert!(!query_data.db_name.is_empty());\n\n\n\n match &*query_data.db_name {\n\n #[cfg(feature = \"postgres\")]\n\n sqlx_core::postgres::Postgres::NAME => expand_with_data(\n\n input,\n\n QueryData::<sqlx_core::postgres::Postgres>::from_dyn_data(query_data)?,\n\n ),\n\n #[cfg(feature = \"mysql\")]\n\n sqlx_core::mysql::MySql::NAME => expand_with_data(\n\n input,\n\n QueryData::<sqlx_core::mysql::MySql>::from_dyn_data(query_data)?,\n\n ),\n", "file_path": "sqlx-macros/src/query/mod.rs", "rank": 22, "score": 200641.80819407967 }, { "content": "fn parse(key: &str) -> Result<PublicKey, Error> {\n\n // This takes advantage of the knowledge that we know\n\n // we are receiving a PKCS#8 RSA Public Key at all\n\n // times from MySQL\n\n\n\n if !key.starts_with(\"-----BEGIN PUBLIC KEY-----\\n\") {\n\n return Err(err_protocol!(\n\n \"unexpected format for RSA Public Key from MySQL (expected PKCS#8); first line: {:?}\",\n\n key.splitn(1, '\\n').next()\n\n )\n\n .into());\n\n }\n\n\n\n let key_with_trailer = key.trim_start_matches(\"-----BEGIN PUBLIC KEY-----\\n\");\n\n let trailer_pos = key_with_trailer.find('-').unwrap_or(0);\n\n let inner_key = key_with_trailer[..trailer_pos].replace('\\n', \"\");\n\n\n\n let inner = base64::decode(&inner_key).map_err(|_err| {\n\n // TODO(@abonander): err_protocol doesn't like referring to [err]\n\n err_protocol!(\"unexpected error decoding what should be base64-encoded data\")\n", "file_path": "sqlx-core/src/mysql/protocol/rsa.rs", "rank": 23, "score": 199784.5004954397 }, { "content": "#[test]\n\nfn test_decode_ready_for_query() -> Result<(), Error> {\n\n const DATA: &[u8] = b\"E\";\n\n\n\n let m = ReadyForQuery::decode(Bytes::from_static(DATA))?;\n\n\n\n assert!(matches!(m.transaction_status, TransactionStatus::Error));\n\n\n\n Ok(())\n\n}\n", "file_path": "sqlx-core/src/postgres/message/ready_for_query.rs", "rank": 24, "score": 196757.12238691052 }, { "content": "// function that will be called on new Application to configure routes for this module\n\npub fn init(cfg: &mut web::ServiceConfig) {\n\n cfg.service(find_all);\n\n cfg.service(find);\n\n cfg.service(create);\n\n cfg.service(update);\n\n cfg.service(delete);\n\n}", "file_path": "examples/postgres/todo-api/src/todo/routes.rs", "rank": 25, "score": 196495.8448733002 }, { "content": "pub fn check_struct_attributes<'a>(\n\n input: &'a DeriveInput,\n\n fields: &Punctuated<Field, Comma>,\n\n) -> syn::Result<SqlxContainerAttributes> {\n\n let attributes = parse_container_attributes(&input.attrs)?;\n\n\n\n assert_attribute!(\n\n !attributes.transparent,\n\n \"unexpected #[sqlx(transparent)]\",\n\n input\n\n );\n\n\n\n assert_attribute!(\n\n attributes.rename_all.is_none(),\n\n \"unexpected #[sqlx(rename_all = ..)]\",\n\n input\n\n );\n\n\n\n assert_attribute!(attributes.repr.is_none(), \"unexpected #[repr(..)]\", input);\n\n\n", "file_path": "sqlx-macros/src/derives/attributes.rs", "rank": 26, "score": 193511.83754522313 }, { "content": "pub fn conjure_value<T>() -> T {\n\n panic!()\n\n}\n\n\n", "file_path": "src/ty_match.rs", "rank": 27, "score": 191871.1175206732 }, { "content": "fn expand_with_data<DB: DatabaseExt>(\n\n input: QueryMacroInput,\n\n data: QueryData<DB>,\n\n) -> crate::Result<TokenStream>\n\nwhere\n\n Describe<DB>: DescribeExt,\n\n{\n\n // validate at the minimum that our args match the query's input parameters\n\n if input.arg_names.len() != data.describe.params.len() {\n\n return Err(syn::Error::new(\n\n Span::call_site(),\n\n format!(\n\n \"expected {} parameters, got {}\",\n\n data.describe.params.len(),\n\n input.arg_names.len()\n\n ),\n\n )\n\n .into());\n\n }\n\n\n", "file_path": "sqlx-macros/src/query/mod.rs", "rank": 28, "score": 191695.8533418083 }, { "content": "/// if `max_lifetime` or `idle_timeout` is set, spawn a task that reaps senescent connections\n\nfn spawn_reaper<DB: Database>(pool: &Arc<SharedPool<DB>>) {\n\n let period = match (pool.options.max_lifetime, pool.options.idle_timeout) {\n\n (Some(it), None) | (None, Some(it)) => it,\n\n\n\n (Some(a), Some(b)) => cmp::min(a, b),\n\n\n\n (None, None) => return,\n\n };\n\n\n\n let pool = Arc::clone(&pool);\n\n\n\n spawn(async move {\n\n while !pool.is_closed.load(Ordering::Acquire) {\n\n // reap at most the current size minus the minimum idle\n\n let max_reaped = pool.size().saturating_sub(pool.options.min_size);\n\n\n\n // collect connections to reap\n\n let (reap, keep) = (0..max_reaped)\n\n // only connections waiting in the queue\n\n .filter_map(|_| pool.pop_idle())\n", "file_path": "sqlx-core/src/pool/inner.rs", "rank": 29, "score": 190735.35964326863 }, { "content": "#[test]\n\nfn test_encode_execute() {\n\n const EXPECTED: &[u8] = b\"E\\0\\0\\0\\x11sqlx_p_5\\0\\0\\0\\0\\x02\";\n\n\n\n let mut buf = Vec::new();\n\n let m = Execute {\n\n portal: Some(5),\n\n limit: 2,\n\n };\n\n\n\n m.encode(&mut buf);\n\n\n\n assert_eq!(buf, EXPECTED);\n\n}\n", "file_path": "sqlx-core/src/postgres/message/execute.rs", "rank": 30, "score": 190389.903021973 }, { "content": "/// get the time between the deadline and now and use that as our timeout\n\n///\n\n/// returns `Error::PoolTimedOut` if the deadline is in the past\n\nfn deadline_as_timeout<DB: Database>(deadline: Instant) -> Result<Duration, Error> {\n\n deadline\n\n .checked_duration_since(Instant::now())\n\n .ok_or(Error::PoolTimedOut)\n\n}\n\n\n", "file_path": "sqlx-core/src/pool/mod.rs", "rank": 31, "score": 189272.64401242527 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_data_row(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"\\x00\\x08\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\n\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x14\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00(\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00P\";\n\n\n\n b.iter(|| {\n\n let _ = DataRow::decode(test::black_box(Bytes::from_static(DATA)));\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/data_row.rs", "rank": 32, "score": 186712.15831758754 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_data_row_get(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"\\x00\\x08\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\n\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x14\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00(\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00P\";\n\n\n\n let row = DataRow::decode(test::black_box(Bytes::from_static(DATA))).unwrap();\n\n\n\n b.iter(|| {\n\n let _value = test::black_box(&row).get(3);\n\n });\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/data_row.rs", "rank": 33, "score": 186712.15831758754 }, { "content": "fn is_beyond_lifetime<DB: Database>(live: &Live<DB>, options: &Options) -> bool {\n\n // check if connection was within max lifetime (or not set)\n\n options\n\n .max_lifetime\n\n .map_or(false, |max| live.created.elapsed() > max)\n\n}\n\n\n", "file_path": "sqlx-core/src/pool/inner.rs", "rank": 34, "score": 183933.9580880964 }, { "content": "fn is_beyond_idle<DB: Database>(idle: &Idle<DB>, options: &Options) -> bool {\n\n // if connection wasn't idle too long (or not set)\n\n options\n\n .idle_timeout\n\n .map_or(false, |timeout| idle.since.elapsed() > timeout)\n\n}\n\n\n\nasync fn check_conn<'s: 'p, 'p, DB: Database>(\n\n mut conn: Floating<'s, Idle<DB>>,\n\n options: &'p Options,\n\n) -> Option<Floating<'s, Live<DB>>> {\n\n // If the connection we pulled has expired, close the connection and\n\n // immediately create a new connection\n\n if is_beyond_lifetime(&conn, options) {\n\n // we're closing the connection either way\n\n // close the connection but don't really care about the result\n\n let _ = conn.close().await;\n\n return None;\n\n } else if options.test_on_acquire {\n\n // Check that the connection is still live\n", "file_path": "sqlx-core/src/pool/inner.rs", "rank": 35, "score": 183933.9580880964 }, { "content": "pub fn dupe_value<T>(_t: &T) -> T {\n\n panic!()\n\n}\n\n\n", "file_path": "src/ty_match.rs", "rank": 36, "score": 182579.07706265897 }, { "content": "fn get_db_kind() -> anyhow::Result<&'static str> {\n\n let db_url = dotenv::var(\"DATABASE_URL\")\n\n .map_err(|_| anyhow!(\"`DATABASE_URL` must be set to use the `prepare` subcommand\"))?;\n\n\n\n let db_url = Url::parse(&db_url)?;\n\n\n\n // these should match the values of `DatabaseExt::NAME` in `sqlx-macros`\n\n match db_url.scheme() {\n\n \"postgres\" | \"postgresql\" => Ok(\"PostgreSQL\"),\n\n \"mysql\" | \"mariadb\" => Ok(\"MySQL/MariaDB\"),\n\n \"sqlite\" => Ok(\"SQLite\"),\n\n _ => bail!(\"unexpected scheme in database URL: {}\", db_url.scheme()),\n\n }\n\n}\n", "file_path": "sqlx-cli/src/prepare.rs", "rank": 37, "score": 181627.0398868553 }, { "content": "/// Encode a single value to be sent to the database.\n\npub trait Encode<'q, DB: Database>: Type<DB> {\n\n fn produces(&self) -> DB::TypeInfo {\n\n Self::type_info()\n\n }\n\n\n\n /// Writes the value of `self` into `buf` in the expected format for the database.\n\n #[must_use]\n\n fn encode(self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull\n\n where\n\n Self: Sized,\n\n {\n\n self.encode_by_ref(buf)\n\n }\n\n\n\n /// Writes the value of `self` into `buf` without moving `self`.\n\n ///\n\n /// Where possible, make use of `encode` instead as it can take advantage of re-using\n\n /// memory.\n\n #[must_use]\n\n fn encode_by_ref(&self, buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer) -> IsNull;\n", "file_path": "sqlx-core/src/encode.rs", "rank": 38, "score": 180812.72343433247 }, { "content": "fn get_base_url<'a>(db_url: &'a str) -> Result<DbUrl> {\n\n let split: Vec<&str> = db_url.rsplitn(2, '/').collect();\n\n\n\n if split.len() != 2 {\n\n return Err(anyhow!(\"Failed to find database name in connection string\"));\n\n }\n\n\n\n let db_name = split[0];\n\n let base_url = split[1];\n\n\n\n Ok(DbUrl { base_url, db_name })\n\n}\n\n\n\n#[async_trait]\n\nimpl DatabaseMigrator for MySql {\n\n fn database_type(&self) -> String {\n\n \"MySql\".to_string()\n\n }\n\n\n\n fn can_migrate_database(&self) -> bool {\n", "file_path": "sqlx-cli/src/migrator/mysql.rs", "rank": 39, "score": 180579.86937342834 }, { "content": "fn get_base_url<'a>(db_url: &'a str) -> Result<DbUrl> {\n\n let split: Vec<&str> = db_url.rsplitn(2, '/').collect();\n\n\n\n if split.len() != 2 {\n\n return Err(anyhow!(\"Failed to find database name in connection string\"));\n\n }\n\n\n\n let db_name = split[0];\n\n let base_url = split[1];\n\n\n\n Ok(DbUrl { base_url, db_name })\n\n}\n\n\n\n#[async_trait]\n\nimpl DatabaseMigrator for Postgres {\n\n fn database_type(&self) -> String {\n\n \"Postgres\".to_string()\n\n }\n\n\n\n fn can_migrate_database(&self) -> bool {\n", "file_path": "sqlx-cli/src/migrator/postgres.rs", "rank": 40, "score": 180579.86937342834 }, { "content": "fn expand_derive_from_row_struct(\n\n input: &DeriveInput,\n\n fields: &Punctuated<Field, Comma>,\n\n) -> syn::Result<proc_macro2::TokenStream> {\n\n let ident = &input.ident;\n\n\n\n let generics = &input.generics;\n\n\n\n let (lifetime, provided) = generics\n\n .lifetimes()\n\n .next()\n\n .map(|def| (def.lifetime.clone(), false))\n\n .unwrap_or_else(|| (Lifetime::new(\"'a\", Span::call_site()), true));\n\n\n\n let (_, ty_generics, _) = generics.split_for_impl();\n\n\n\n let mut generics = generics.clone();\n\n generics\n\n .params\n\n .insert(0, parse_quote!(R: sqlx::Row<#lifetime>));\n", "file_path": "sqlx-macros/src/derives/row.rs", "rank": 41, "score": 179149.22728000104 }, { "content": "#[proc_macro_derive(FromRow, attributes(sqlx))]\n\npub fn derive_from_row(input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input as syn::DeriveInput);\n\n\n\n match derives::expand_derive_from_row(&input) {\n\n Ok(ts) => ts.into(),\n\n Err(e) => e.to_compile_error().into(),\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/lib.rs", "rank": 42, "score": 178549.84582011425 }, { "content": "#[proc_macro]\n\npub fn expand_query(input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input as query::QueryMacroInput);\n\n\n\n match query::expand_input(input) {\n\n Ok(ts) => ts.into(),\n\n Err(e) => {\n\n if let Some(parse_err) = e.downcast_ref::<syn::Error>() {\n\n macro_result(parse_err.to_compile_error())\n\n } else {\n\n let msg = e.to_string();\n\n macro_result(quote!(compile_error!(#msg)))\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/lib.rs", "rank": 43, "score": 178441.06386785524 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_error_response(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"SNOTICE\\0VNOTICE\\0C42710\\0Mextension \\\"uuid-ossp\\\" already exists, skipping\\0Fextension.c\\0L1656\\0RCreateExtension\\0\\0\";\n\n\n\n b.iter(|| {\n\n let _ = Notice::decode(test::black_box(Bytes::from_static(DATA)));\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/response.rs", "rank": 44, "score": 177290.37971533212 }, { "content": "fn parse_ident(name: &str) -> crate::Result<Ident> {\n\n // workaround for the following issue (it's semi-fixed but still spits out extra diagnostics)\n\n // https://github.com/dtolnay/syn/issues/749#issuecomment-575451318\n\n\n\n let is_valid_ident = name.chars().all(|c| c.is_alphanumeric() || c == '_');\n\n\n\n if is_valid_ident {\n\n let ident = String::from(\"r#\") + name;\n\n if let Ok(ident) = syn::parse_str(&ident) {\n\n return Ok(ident);\n\n }\n\n }\n\n\n\n Err(format!(\"{:?} is not a valid Rust identifier\", name).into())\n\n}\n", "file_path": "sqlx-macros/src/query/output.rs", "rank": 45, "score": 176202.47611575123 }, { "content": "pub fn expand_input(input: QueryMacroInput) -> crate::Result<TokenStream> {\n\n let manifest_dir =\n\n env::var(\"CARGO_MANIFEST_DIR\").map_err(|_| \"`CARGO_MANIFEST_DIR` must be set\")?;\n\n\n\n // If a .env file exists at CARGO_MANIFEST_DIR, load environment variables from this,\n\n // otherwise fallback to default dotenv behaviour.\n\n let env_path = std::path::Path::new(&manifest_dir).join(\".env\");\n\n if env_path.exists() {\n\n dotenv::from_path(&env_path)\n\n .map_err(|e| format!(\"failed to load environment from {:?}, {}\", env_path, e))?\n\n }\n\n\n\n // if `dotenv` wasn't initialized by the above we make sure to do it here\n\n match dotenv::var(\"DATABASE_URL\").ok() {\n\n Some(db_url) => expand_from_db(input, &db_url),\n\n\n\n #[cfg(feature = \"offline\")]\n\n None => {\n\n let data_file_path = std::path::Path::new(&manifest_dir).join(\"sqlx-data.json\");\n\n\n", "file_path": "sqlx-macros/src/query/mod.rs", "rank": 46, "score": 175976.91714893238 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_error_response_get_message(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"SNOTICE\\0VNOTICE\\0C42710\\0Mextension \\\"uuid-ossp\\\" already exists, skipping\\0Fextension.c\\0L1656\\0RCreateExtension\\0\\0\";\n\n\n\n let res = Notice::decode(test::black_box(Bytes::from_static(DATA))).unwrap();\n\n\n\n b.iter(|| {\n\n let _ = test::black_box(&res).message();\n\n });\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/response.rs", "rank": 47, "score": 175165.54930731628 }, { "content": "/// Authorize a JWT returning the user_id\n\nfn authorize_token(token: &str) -> jsonwebtoken::errors::Result<i32> {\n\n let data = jsonwebtoken::decode::<TokenClaims>(\n\n token,\n\n SECRET_KEY.as_ref(),\n\n &jsonwebtoken::Validation::default(),\n\n )?;\n\n\n\n Ok(data.claims.sub)\n\n}\n\n\n", "file_path": "examples/realworld/src/api/util.rs", "rank": 48, "score": 171351.92889392647 }, { "content": "#[async_trait]\n\npub trait Db {\n\n /// A connection to the database\n\n type Conn;\n\n\n\n /// Establish a connection with the database\n\n async fn conn(&self) -> sqlx::Result<Self::Conn>;\n\n}\n\n\n", "file_path": "examples/realworld/src/db/mod.rs", "rank": 49, "score": 170736.4540384948 }, { "content": "pub fn expand_derive_from_row(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {\n\n match &input.data {\n\n Data::Struct(DataStruct {\n\n fields: Fields::Named(FieldsNamed { named, .. }),\n\n ..\n\n }) => expand_derive_from_row_struct(input, named),\n\n\n\n Data::Struct(DataStruct {\n\n fields: Fields::Unnamed(_),\n\n ..\n\n }) => Err(syn::Error::new_spanned(\n\n input,\n\n \"tuple structs are not supported\",\n\n )),\n\n\n\n Data::Struct(DataStruct {\n\n fields: Fields::Unit,\n\n ..\n\n }) => Err(syn::Error::new_spanned(\n\n input,\n\n \"unit structs are not supported\",\n\n )),\n\n\n\n Data::Enum(_) => Err(syn::Error::new_spanned(input, \"enums are not supported\")),\n\n\n\n Data::Union(_) => Err(syn::Error::new_spanned(input, \"unions are not supported\")),\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/derives/row.rs", "rank": 50, "score": 170038.23241258218 }, { "content": "// Hi(str, salt, i):\n\nfn hi<'a>(s: &'a str, salt: &'a [u8], iter_count: u32) -> Result<[u8; 32], Error> {\n\n let mut mac = Hmac::<Sha256>::new_varkey(s.as_bytes()).map_err(Error::protocol)?;\n\n\n\n mac.input(&salt);\n\n mac.input(&1u32.to_be_bytes());\n\n\n\n let mut u = mac.result().code();\n\n let mut hi = u;\n\n\n\n for _ in 1..iter_count {\n\n let mut mac = Hmac::<Sha256>::new_varkey(s.as_bytes()).map_err(Error::protocol)?;\n\n mac.input(u.as_slice());\n\n u = mac.result().code();\n\n hi = hi.iter().zip(u.iter()).map(|(&a, &b)| a ^ b).collect();\n\n }\n\n\n\n Ok(hi.into())\n\n}\n", "file_path": "sqlx-core/src/postgres/connection/sasl.rs", "rank": 51, "score": 169068.2044196629 }, { "content": "pub fn encrypt<D: Digest>(key: &[u8], message: &[u8]) -> Result<Vec<u8>, Error> {\n\n let key = std::str::from_utf8(key).map_err(|_err| {\n\n // TODO(@abonander): err_protocol doesn't like referring to [err]\n\n err_protocol!(\"unexpected error decoding what should be UTF-8\")\n\n })?;\n\n\n\n let key = parse(key)?;\n\n\n\n Ok(oaep_encrypt::<_, D>(&mut thread_rng(), &key, message)?)\n\n}\n\n\n", "file_path": "sqlx-core/src/mysql/protocol/rsa.rs", "rank": 52, "score": 169048.91742741282 }, { "content": "fn emplace_row_metadata(\n\n statement: &StatementHandle,\n\n column_names: &mut HashMap<UStr, usize>,\n\n) -> Result<(), Error> {\n\n column_names.clear();\n\n\n\n let num = statement.column_count();\n\n\n\n column_names.reserve(num);\n\n\n\n for i in 0..num {\n\n let name: UStr = statement.column_name(i).to_owned().into();\n\n\n\n column_names.insert(name, i);\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\nimpl<'c> Executor<'c> for &'c mut SqliteConnection {\n", "file_path": "sqlx-core/src/sqlite/connection/executor.rs", "rank": 53, "score": 168207.29466421393 }, { "content": "fn read_file_src(source: &str, source_span: Span) -> syn::Result<String> {\n\n use std::path::Path;\n\n\n\n let path = Path::new(source);\n\n\n\n if path.is_absolute() {\n\n return Err(syn::Error::new(\n\n source_span,\n\n \"absolute paths will only work on the current machine\",\n\n ));\n\n }\n\n\n\n // requires `proc_macro::SourceFile::path()` to be stable\n\n // https://github.com/rust-lang/rust/issues/54725\n\n if path.is_relative()\n\n && !path\n\n .parent()\n\n .map_or(false, |parent| !parent.as_os_str().is_empty())\n\n {\n\n return Err(syn::Error::new(\n", "file_path": "sqlx-macros/src/query/input.rs", "rank": 54, "score": 162504.67773466802 }, { "content": "/// Associate [`Database`] with an [`Arguments`](crate::arguments::Arguments) of a generic lifetime.\n\n///\n\n/// ---\n\n///\n\n/// The upcoming Rust feature, [Generic Associated Types], should obviate\n\n/// the need for this trait.\n\n///\n\n/// [Generic Associated Types]: https://github.com/rust-lang/rust/issues/44265\n\npub trait HasArguments<'q> {\n\n type Database: Database;\n\n\n\n /// The concrete `Arguments` implementation for this database.\n\n type Arguments: Arguments<'q, Database = Self::Database>;\n\n\n\n /// The concrete type used as a buffer for arguments while encoding.\n\n type ArgumentBuffer: Default;\n\n}\n", "file_path": "sqlx-core/src/database.rs", "rank": 55, "score": 157560.0687153925 }, { "content": "fn decode_time(len: u8, mut buf: &[u8]) -> Result<Time, BoxDynError> {\n\n let hour = buf.get_u8();\n\n let minute = buf.get_u8();\n\n let seconds = buf.get_u8();\n\n\n\n let micros = if len > 3 {\n\n // microseconds : int<EOF>\n\n buf.get_uint_le(buf.len())\n\n } else {\n\n 0\n\n };\n\n\n\n Time::try_from_hms_micro(hour, minute, seconds, micros as u32)\n\n .map_err(|e| format!(\"Time out of range for MySQL: {}\", e).into())\n\n}\n", "file_path": "sqlx-core/src/mysql/types/time.rs", "rank": 56, "score": 156554.55414981366 }, { "content": "/// A record that can be built from a row returned by the database.\n\n///\n\n/// In order to use [`query_as`] the output type must implement `FromRow`.\n\n///\n\n/// # Deriving\n\n///\n\n/// This trait can be automatically derived by SQLx for any struct. The generated implementation\n\n/// will consist of a sequence of calls to [`Row::try_get`] using the name from each\n\n/// struct field.\n\n///\n\n/// ```rust,ignore\n\n/// #[derive(sqlx::FromRow)]\n\n/// struct User {\n\n/// id: i32,\n\n/// name: String,\n\n/// }\n\n/// ```\n\n///\n\n/// [`query_as`]: crate::query_as\n\n/// [`Row::try_get`]: crate::row::Row::try_get\n\npub trait FromRow<'r, R: Row>: Sized {\n\n fn from_row(row: &'r R) -> Result<Self, Error>;\n\n}\n\n\n\n// implement FromRow for tuples of types that implement Decode\n\n// up to tuples of 9 values\n\n\n\nmacro_rules! impl_from_row_for_tuple {\n\n ($( ($idx:tt) -> $T:ident );+;) => {\n\n impl<'r, R, $($T,)+> FromRow<'r, R> for ($($T,)+)\n\n where\n\n R: Row,\n\n $($T: crate::decode::Decode<'r, R::Database>,)+\n\n {\n\n #[inline]\n\n fn from_row(row: &'r R) -> Result<Self, Error> {\n\n Ok(($(row.try_get($idx as usize)?,)+))\n\n }\n\n }\n\n };\n", "file_path": "sqlx-core/src/from_row.rs", "rank": 57, "score": 156355.20439751502 }, { "content": "fn crop_letters(s: &str, pos: usize) -> &str {\n\n match s.char_indices().skip(pos).next() {\n\n Some((pos, _)) => &s[pos..],\n\n None => \"\",\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl DatabaseMigrator for Sqlite {\n\n fn database_type(&self) -> String {\n\n \"Sqlite\".to_string()\n\n }\n\n\n\n fn can_migrate_database(&self) -> bool {\n\n true\n\n }\n\n\n\n fn can_create_database(&self) -> bool {\n\n true\n\n }\n", "file_path": "sqlx-cli/src/migrator/sqlite.rs", "rank": 58, "score": 156248.97396508337 }, { "content": "/// Represents a single database connection.\n\npub trait Connection: Send {\n\n type Database: Database;\n\n\n\n /// Explicitly close this database connection.\n\n ///\n\n /// This method is **not required** for safe and consistent operation. However, it is\n\n /// recommended to call it instead of letting a connection `drop` as the database backend\n\n /// will be faster at cleaning up resources.\n\n fn close(self) -> BoxFuture<'static, Result<(), Error>>;\n\n\n\n /// Checks if a connection to the database is still valid.\n\n fn ping(&mut self) -> BoxFuture<'_, Result<(), Error>>;\n\n\n\n /// Begin a new transaction or establish a savepoint within the active transaction.\n\n ///\n\n /// Returns a [`Transaction`] for controlling and tracking the new transaction.\n\n fn begin(&mut self) -> BoxFuture<'_, Result<Transaction<'_, Self::Database, Self>, Error>>\n\n where\n\n Self: Sized,\n\n {\n", "file_path": "sqlx-core/src/connection.rs", "rank": 59, "score": 155824.78714183124 }, { "content": "/// A type that can be decoded from the database.\n\npub trait Decode<'r, DB: Database>: Sized + Type<DB> {\n\n /// Determines if a value of this type can be created from a value with the\n\n /// given type information.\n\n fn accepts(ty: &DB::TypeInfo) -> bool {\n\n *ty == Self::type_info()\n\n }\n\n\n\n /// Decode a new value of this type using a raw value from the database.\n\n fn decode(value: <DB as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError>;\n\n}\n\n\n\n// implement `Decode` for Option<T> for all SQL types\n\nimpl<'r, DB, T> Decode<'r, DB> for Option<T>\n\nwhere\n\n DB: Database,\n\n T: Decode<'r, DB>,\n\n{\n\n fn accepts(ty: &DB::TypeInfo) -> bool {\n\n T::accepts(ty)\n\n }\n\n\n\n fn decode(value: <DB as HasValueRef<'r>>::ValueRef) -> Result<Self, BoxDynError> {\n\n if value.is_null() {\n\n Ok(None)\n\n } else {\n\n Ok(Some(T::decode(value)?))\n\n }\n\n }\n\n}\n", "file_path": "sqlx-core/src/decode.rs", "rank": 60, "score": 152687.3616555923 }, { "content": "#[test]\n\nfn test_data_type_from_str() -> Result<(), BoxDynError> {\n\n assert_eq!(DataType::Int, \"INT\".parse()?);\n\n assert_eq!(DataType::Int, \"INTEGER\".parse()?);\n\n assert_eq!(DataType::Int, \"INTBIG\".parse()?);\n\n assert_eq!(DataType::Int, \"MEDIUMINT\".parse()?);\n\n\n\n assert_eq!(DataType::Int64, \"BIGINT\".parse()?);\n\n assert_eq!(DataType::Int64, \"UNSIGNED BIG INT\".parse()?);\n\n assert_eq!(DataType::Int64, \"INT8\".parse()?);\n\n\n\n assert_eq!(DataType::Text, \"CHARACTER(20)\".parse()?);\n\n assert_eq!(DataType::Text, \"NCHAR(55)\".parse()?);\n\n assert_eq!(DataType::Text, \"TEXT\".parse()?);\n\n assert_eq!(DataType::Text, \"CLOB\".parse()?);\n\n\n\n assert_eq!(DataType::Blob, \"BLOB\".parse()?);\n\n\n\n assert_eq!(DataType::Float, \"REAL\".parse()?);\n\n assert_eq!(DataType::Float, \"FLOAT\".parse()?);\n\n assert_eq!(DataType::Float, \"DOUBLE PRECISION\".parse()?);\n\n\n\n assert_eq!(DataType::Bool, \"BOOLEAN\".parse()?);\n\n assert_eq!(DataType::Bool, \"BOOL\".parse()?);\n\n\n\n Ok(())\n\n}\n", "file_path": "sqlx-core/src/sqlite/type_info.rs", "rank": 61, "score": 151880.5624402508 }, { "content": "pub fn check_weak_enum_attributes(\n\n input: &DeriveInput,\n\n variants: &Punctuated<Variant, Comma>,\n\n) -> syn::Result<SqlxContainerAttributes> {\n\n let attributes = check_enum_attributes(input)?;\n\n\n\n assert_attribute!(attributes.repr.is_some(), \"expected #[repr(..)]\", input);\n\n\n\n assert_attribute!(\n\n attributes.rename_all.is_none(),\n\n \"unexpected #[sqlx(c = ..)]\",\n\n input\n\n );\n\n\n\n for variant in variants {\n\n let attributes = parse_child_attributes(&variant.attrs)?;\n\n\n\n assert_attribute!(\n\n attributes.rename.is_none(),\n\n \"unexpected #[sqlx(rename = ..)]\",\n\n variant\n\n );\n\n }\n\n\n\n Ok(attributes)\n\n}\n\n\n", "file_path": "sqlx-macros/src/derives/attributes.rs", "rank": 62, "score": 151400.54668823042 }, { "content": "pub fn check_strong_enum_attributes(\n\n input: &DeriveInput,\n\n _variants: &Punctuated<Variant, Comma>,\n\n) -> syn::Result<SqlxContainerAttributes> {\n\n let attributes = check_enum_attributes(input)?;\n\n\n\n assert_attribute!(attributes.repr.is_none(), \"unexpected #[repr(..)]\", input);\n\n\n\n Ok(attributes)\n\n}\n\n\n", "file_path": "sqlx-macros/src/derives/attributes.rs", "rank": 63, "score": 151400.54668823042 }, { "content": "/// Create a batch insert statement\n\n///\n\n/// This incantation borrowed from @mehcode\n\n/// https://discordapp.com/channels/665528275556106240/665528275556106243/694835667401703444\n\nfn build_batch_insert(rows: usize, columns: usize) -> String {\n\n use itertools::Itertools;\n\n\n\n (0..rows)\n\n .format_with(\",\", |i, f| {\n\n f(&format_args!(\n\n \"({})\",\n\n (1..=columns).format_with(\",\", |j, f| f(&format_args!(\"${}\", j + (i * columns))))\n\n ))\n\n })\n\n .to_string()\n\n}\n", "file_path": "examples/realworld/src/db/mod.rs", "rank": 64, "score": 148442.70459717346 }, { "content": "/// Indicates that a SQL type is supported for a database.\n\npub trait Type<DB: Database> {\n\n /// Returns the canonical type information on the database for the type `T`.\n\n fn type_info() -> DB::TypeInfo;\n\n}\n\n\n\n// for references, the underlying SQL type is identical\n\nimpl<T: ?Sized + Type<DB>, DB: Database> Type<DB> for &'_ T {\n\n #[inline]\n\n fn type_info() -> DB::TypeInfo {\n\n <T as Type<DB>>::type_info()\n\n }\n\n}\n\n\n\n// for optionals, the underlying SQL type is identical\n\nimpl<T: Type<DB>, DB: Database> Type<DB> for Option<T> {\n\n #[inline]\n\n fn type_info() -> DB::TypeInfo {\n\n <T as Type<DB>>::type_info()\n\n }\n\n}\n", "file_path": "sqlx-core/src/types/mod.rs", "rank": 65, "score": 147401.29432482587 }, { "content": "/// Extract the JWT token from a header string\n\nfn parse_token(header: &str) -> String {\n\n header.splitn(2, ' ').nth(1).unwrap_or_default().to_owned()\n\n}\n\n\n", "file_path": "examples/realworld/src/api/util.rs", "rank": 66, "score": 143429.01704332145 }, { "content": "// https://github.com/RustCrypto/RSA/blob/9f1464c43831d422d9903574aad6ab072db9f2b0/src/oaep.rs#L13\n\nfn internals_inc_counter(counter: &mut [u8]) {\n\n if counter[3] == u8::max_value() {\n\n counter[3] = 0;\n\n } else {\n\n counter[3] += 1;\n\n return;\n\n }\n\n\n\n if counter[2] == u8::max_value() {\n\n counter[2] = 0;\n\n } else {\n\n counter[2] += 1;\n\n return;\n\n }\n\n\n\n if counter[1] == u8::max_value() {\n\n counter[1] = 0;\n\n } else {\n\n counter[1] += 1;\n\n return;\n", "file_path": "sqlx-core/src/mysql/protocol/rsa.rs", "rank": 67, "score": 140246.35341039737 }, { "content": "fn to_asciz(s: &str) -> Vec<u8> {\n\n let mut z = String::with_capacity(s.len() + 1);\n\n z.push_str(s);\n\n z.push('\\0');\n\n\n\n z.into_bytes()\n\n}\n", "file_path": "sqlx-core/src/mysql/connection/auth.rs", "rank": 68, "score": 139769.53481757973 }, { "content": "/// An owned value from the database.\n\npub trait Value {\n\n type Database: Database;\n\n\n\n /// Get this value as a reference.\n\n fn as_ref(&self) -> <Self::Database as HasValueRef<'_>>::ValueRef;\n\n\n\n /// Get the type information, if available, for this value.\n\n ///\n\n /// Some database implementations do not implement type deduction for\n\n /// expressions (`SELECT 2 + 5`); and, this will return `None` in those cases.\n\n fn type_info(&self) -> Option<Cow<'_, <Self::Database as Database>::TypeInfo>>;\n\n\n\n /// Returns `true` if the SQL value is `NULL`.\n\n fn is_null(&self) -> bool;\n\n\n\n /// Decode this single value into the requested type.\n\n ///\n\n /// # Panics\n\n ///\n\n /// Panics if the value cannot be decoded into the requested type.\n", "file_path": "sqlx-core/src/value.rs", "rank": 69, "score": 138783.39117211202 }, { "content": "/// A type that can be used to index into a [`Row`].\n\n///\n\n/// The [`get`] and [`try_get`] methods of [`Row`] accept any type that implements `ColumnIndex`.\n\n/// This trait is implemented for strings which are used to look up a column by name, and for\n\n/// `usize` which is used as a positional index into the row.\n\n///\n\n/// This trait is sealed and cannot be implemented for types outside of SQLx.\n\n///\n\n/// [`Row`]: trait.Row.html\n\n/// [`get`]: trait.Row.html#method.get\n\n/// [`try_get`]: trait.Row.html#method.try_get\n\npub trait ColumnIndex<R: Row + ?Sized>: private_column_index::Sealed + Debug {\n\n /// Returns a valid positional index into the row, [`ColumnIndexOutOfBounds`], or,\n\n /// [`ColumnNotFound`].\n\n ///\n\n /// [`ColumnNotFound`]: ../enum.Error.html#variant.ColumnNotFound\n\n /// [`ColumnIndexOutOfBounds`]: ../enum.Error.html#variant.ColumnIndexOutOfBounds\n\n fn index(&self, row: &R) -> Result<usize, Error>;\n\n}\n\n\n\nimpl<R, I> ColumnIndex<R> for &'_ I\n\nwhere\n\n R: Row + ?Sized,\n\n I: ColumnIndex<R> + ?Sized,\n\n{\n\n #[inline]\n\n fn index(&self, row: &R) -> Result<usize, Error> {\n\n (**self).index(row)\n\n }\n\n}\n\n\n", "file_path": "sqlx-core/src/row.rs", "rank": 70, "score": 137815.42592001506 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_encode_startup(b: &mut test::Bencher) {\n\n use test::black_box;\n\n\n\n let mut buf = Vec::with_capacity(128);\n\n\n\n b.iter(|| {\n\n buf.clear();\n\n\n\n black_box(Startup {\n\n username: Some(\"postgres\"),\n\n database: Some(\"postgres\"),\n\n params: &[],\n\n })\n\n .encode(&mut buf);\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/startup.rs", "rank": 71, "score": 136590.6480693533 }, { "content": "pub fn same_type<T>(_1: &T, _2: &T) {}\n\n\n\npub struct WrapSame<T, U>(PhantomData<T>, PhantomData<U>);\n\n\n\nimpl<T, U> WrapSame<T, U> {\n\n pub fn new(_arg: &U) -> Self {\n\n WrapSame(PhantomData, PhantomData)\n\n }\n\n}\n\n\n", "file_path": "src/ty_match.rs", "rank": 72, "score": 136174.3127444973 }, { "content": "#[proc_macro_derive(Decode, attributes(sqlx))]\n\npub fn derive_decode(tokenstream: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(tokenstream as syn::DeriveInput);\n\n match derives::expand_derive_decode(&input) {\n\n Ok(ts) => ts.into(),\n\n Err(e) => e.to_compile_error().into(),\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/lib.rs", "rank": 73, "score": 135718.80281080713 }, { "content": "#[proc_macro_derive(Type, attributes(sqlx))]\n\npub fn derive_type(tokenstream: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(tokenstream as syn::DeriveInput);\n\n match derives::expand_derive_type_encode_decode(&input) {\n\n Ok(ts) => ts.into(),\n\n Err(e) => e.to_compile_error().into(),\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/lib.rs", "rank": 74, "score": 135718.80281080713 }, { "content": "#[proc_macro_derive(Encode, attributes(sqlx))]\n\npub fn derive_encode(tokenstream: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(tokenstream as syn::DeriveInput);\n\n match derives::expand_derive_encode(&input) {\n\n Ok(ts) => ts.into(),\n\n Err(e) => e.to_compile_error().into(),\n\n }\n\n}\n\n\n", "file_path": "sqlx-macros/src/lib.rs", "rank": 75, "score": 135718.80281080713 }, { "content": "// https://github.com/RustCrypto/RSA/blob/9f1464c43831d422d9903574aad6ab072db9f2b0/src/oaep.rs#L46\n\nfn oeap_mgf1_xor<D: Digest>(out: &mut [u8], digest: &mut D, seed: &[u8]) {\n\n let mut counter = vec![0u8; 4];\n\n let mut i = 0;\n\n\n\n while i < out.len() {\n\n let mut digest_input = vec![0u8; seed.len() + 4];\n\n digest_input[0..seed.len()].copy_from_slice(seed);\n\n digest_input[seed.len()..].copy_from_slice(&counter);\n\n\n\n digest.input(digest_input.as_slice());\n\n let digest_output = &*digest.result_reset();\n\n let mut j = 0;\n\n loop {\n\n if j >= digest_output.len() || i >= out.len() {\n\n break;\n\n }\n\n\n\n out[i] ^= digest_output[j];\n\n j += 1;\n\n i += 1;\n\n }\n\n internals_inc_counter(counter.as_mut_slice());\n\n }\n\n}\n\n\n", "file_path": "sqlx-core/src/mysql/protocol/rsa.rs", "rank": 76, "score": 135652.48725005597 }, { "content": "fn decode_date(mut buf: &[u8]) -> NaiveDate {\n\n let year = buf.get_u16_le();\n\n NaiveDate::from_ymd(year as i32, buf[0] as u32, buf[1] as u32)\n\n}\n\n\n", "file_path": "sqlx-core/src/mysql/types/chrono.rs", "rank": 77, "score": 135127.72862919592 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_encode_md5_password(b: &mut test::Bencher) {\n\n use test::black_box;\n\n\n\n let mut buf = Vec::with_capacity(128);\n\n\n\n b.iter(|| {\n\n buf.clear();\n\n\n\n black_box(Password::Md5 {\n\n password: \"password\",\n\n username: \"root\",\n\n salt: [147, 24, 57, 152],\n\n })\n\n .encode(&mut buf);\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/password.rs", "rank": 78, "score": 135127.72862919592 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_encode_clear_password(b: &mut test::Bencher) {\n\n use test::black_box;\n\n\n\n let mut buf = Vec::with_capacity(128);\n\n\n\n b.iter(|| {\n\n buf.clear();\n\n\n\n black_box(Password::Cleartext(\"password\")).encode(&mut buf);\n\n });\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/password.rs", "rank": 79, "score": 135127.72862919592 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_encode_describe_portal(b: &mut test::Bencher) {\n\n use test::black_box;\n\n\n\n let mut buf = Vec::with_capacity(128);\n\n\n\n b.iter(|| {\n\n buf.clear();\n\n\n\n black_box(Describe::Portal(5)).encode(&mut buf);\n\n });\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/describe.rs", "rank": 80, "score": 135127.72862919592 }, { "content": "// XOR(x, y)\n\n// If len(y) < len(x), wrap around inside y\n\nfn xor_eq(x: &mut [u8], y: &[u8]) {\n\n let y_len = y.len();\n\n\n\n for i in 0..x.len() {\n\n x[i] ^= y[i % y_len];\n\n }\n\n}\n\n\n", "file_path": "sqlx-core/src/mysql/connection/auth.rs", "rank": 81, "score": 134905.60939379732 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_command_complete(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"INSERT 0 1214\\0\";\n\n\n\n b.iter(|| {\n\n let _ = CommandComplete::decode(test::black_box(Bytes::from_static(DATA)));\n\n });\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/command_complete.rs", "rank": 82, "score": 133714.16704295663 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_encode_describe_unnamed_statement(b: &mut test::Bencher) {\n\n use test::black_box;\n\n\n\n let mut buf = Vec::with_capacity(128);\n\n\n\n b.iter(|| {\n\n buf.clear();\n\n\n\n black_box(Describe::UnnamedStatement).encode(&mut buf);\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/describe.rs", "rank": 83, "score": 133714.16704295663 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_parameter_description(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x05\\x00\";\n\n\n\n b.iter(|| {\n\n ParameterDescription::decode(test::black_box(Bytes::from_static(DATA))).unwrap();\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/parameter_description.rs", "rank": 84, "score": 133714.16704295663 }, { "content": "#[test]\n\nfn test_encode_query() {\n\n const EXPECTED: &[u8] = b\"Q\\0\\0\\0\\rSELECT 1\\0\";\n\n\n\n let mut buf = Vec::new();\n\n let m = Query(\"SELECT 1\");\n\n\n\n m.encode(&mut buf);\n\n\n\n assert_eq!(buf, EXPECTED);\n\n}\n", "file_path": "sqlx-core/src/postgres/message/query.rs", "rank": 85, "score": 133683.02334744713 }, { "content": "/// Hashes and salts a password for storage in a DB\n\nfn hash_password(password: &str) -> argon2::Result<String> {\n\n let salt = generate_random_salt();\n\n let hash = argon2::hash_encoded(password.as_bytes(), &salt, &argon2::Config::default())?;\n\n\n\n Ok(hash)\n\n}\n\n\n", "file_path": "examples/realworld/src/api/users.rs", "rank": 86, "score": 133485.46243652457 }, { "content": "pub trait BufMutExt: BufMut {\n\n fn put_str_nul(&mut self, s: &str);\n\n}\n\n\n\nimpl BufMutExt for Vec<u8> {\n\n fn put_str_nul(&mut self, s: &str) {\n\n self.extend(s.as_bytes());\n\n self.push(0);\n\n }\n\n}\n", "file_path": "sqlx-core/src/io/buf_mut.rs", "rank": 87, "score": 132595.93165480456 }, { "content": "pub fn get() -> Result<Box<dyn DatabaseMigrator>> {\n\n let db_url_raw = env::var(\"DATABASE_URL\").context(\"Failed to find 'DATABASE_URL'\")?;\n\n\n\n let db_url = Url::parse(&db_url_raw)?;\n\n\n\n // This code is taken from: https://github.com/launchbadge/sqlx/blob/master/sqlx-macros/src/lib.rs#L63\n\n match db_url.scheme() {\n\n #[cfg(feature = \"sqlite\")]\n\n \"sqlite\" => Ok(Box::new(self::sqlite::Sqlite::new(db_url_raw ))),\n\n #[cfg(not(feature = \"sqlite\"))]\n\n \"sqlite\" => bail!(\"Not implemented. DATABASE_URL {} has the scheme of a SQLite database but the `sqlite` feature of sqlx was not enabled\",\n\n db_url),\n\n\n\n #[cfg(feature = \"postgres\")]\n\n \"postgresql\" | \"postgres\" => Ok(Box::new(self::postgres::Postgres::new(db_url_raw))),\n\n #[cfg(not(feature = \"postgres\"))]\n\n \"postgresql\" | \"postgres\" => bail!(\"DATABASE_URL {} has the scheme of a Postgres database but the `postgres` feature of sqlx was not enabled\",\n\n db_url),\n\n\n\n #[cfg(feature = \"mysql\")]\n", "file_path": "sqlx-cli/src/migrator/mod.rs", "rank": 88, "score": 132565.66033781774 }, { "content": "#[cfg(all(test, not(debug_assertions)))]\n\n#[bench]\n\nfn bench_decode_backend_key_data(b: &mut test::Bencher) {\n\n const DATA: &[u8] = b\"\\0\\0'\\xc6\\x89R\\xc5+\";\n\n\n\n b.iter(|| {\n\n BackendKeyData::decode(test::black_box(Bytes::from_static(DATA))).unwrap();\n\n });\n\n}\n", "file_path": "sqlx-core/src/postgres/message/backend_key_data.rs", "rank": 89, "score": 131025.45175351221 }, { "content": "#[test]\n\nfn test_decode_data_row() {\n\n const DATA: &[u8] = b\"\\x00\\x08\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\n\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00\\x14\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00(\\xff\\xff\\xff\\xff\\x00\\x00\\x00\\x04\\x00\\x00\\x00P\";\n\n\n\n let row = DataRow::decode(DATA.into()).unwrap();\n\n\n\n assert_eq!(row.len(), 8);\n\n\n\n assert!(row.get(0).is_none());\n\n assert_eq!(row.get(1).unwrap(), &[0_u8, 0, 0, 10][..]);\n\n assert!(row.get(2).is_none());\n\n assert_eq!(row.get(3).unwrap(), &[0_u8, 0, 0, 20][..]);\n\n assert!(row.get(4).is_none());\n\n assert_eq!(row.get(5).unwrap(), &[0_u8, 0, 0, 40][..]);\n\n assert!(row.get(6).is_none());\n\n assert_eq!(row.get(7).unwrap(), &[0_u8, 0, 0, 80][..]);\n\n}\n\n\n", "file_path": "sqlx-core/src/postgres/message/data_row.rs", "rank": 90, "score": 130978.6861777823 }, { "content": "/// A reference to a single value from the database.\n\npub trait ValueRef<'r>: Sized {\n\n type Database: Database;\n\n\n\n /// Creates an owned value from this value reference.\n\n ///\n\n /// This is just a reference increment in PostgreSQL and MySQL and thus is `O(1)`. In SQLite,\n\n /// this is a copy.\n\n fn to_owned(&self) -> <Self::Database as Database>::Value;\n\n\n\n /// Get the type information, if available, for this value.\n\n ///\n\n /// Some database implementations do not implement type deduction for\n\n /// expressions (`SELECT 2 + 5`); and, this will return `None` in those cases.\n\n fn type_info(&self) -> Option<Cow<'_, <Self::Database as Database>::TypeInfo>>;\n\n\n\n /// Returns `true` if the SQL value is `NULL`.\n\n fn is_null(&self) -> bool;\n\n}\n", "file_path": "sqlx-core/src/value.rs", "rank": 91, "score": 130967.98856057637 }, { "content": "pub trait TypeInfo: Debug + Display + Clone + PartialEq<Self> {}\n", "file_path": "sqlx-core/src/type_info.rs", "rank": 92, "score": 130304.19969278318 }, { "content": "pub trait MySqlBufMutExt: BufMut {\n\n fn put_uint_lenenc(&mut self, v: u64);\n\n\n\n fn put_str_lenenc(&mut self, v: &str);\n\n\n\n fn put_bytes_lenenc(&mut self, v: &[u8]);\n\n}\n\n\n\nimpl MySqlBufMutExt for Vec<u8> {\n\n fn put_uint_lenenc(&mut self, v: u64) {\n\n // https://dev.mysql.com/doc/internals/en/integer.html\n\n // https://mariadb.com/kb/en/library/protocol-data-types/#length-encoded-integers\n\n\n\n if v < 251 {\n\n self.push(v as u8);\n\n } else if v < 0x1_00_00 {\n\n self.push(0xfc);\n\n self.extend(&(v as u16).to_le_bytes());\n\n } else if v < 0x1_00_00_00 {\n\n self.push(0xfd);\n", "file_path": "sqlx-core/src/mysql/io/buf_mut.rs", "rank": 93, "score": 130207.5168403697 }, { "content": "pub trait PgBufMutExt {\n\n fn put_length_prefixed<F>(&mut self, f: F)\n\n where\n\n F: FnOnce(&mut Vec<u8>);\n\n\n\n fn put_statement_name(&mut self, id: u32);\n\n\n\n fn put_portal_name(&mut self, id: Option<u32>);\n\n}\n\n\n\nimpl PgBufMutExt for Vec<u8> {\n\n // writes a length-prefixed message, this is used when encoding nearly all messages as postgres\n\n // wants us to send the length of the often-variable-sized messages up front\n\n fn put_length_prefixed<F>(&mut self, f: F)\n\n where\n\n F: FnOnce(&mut Vec<u8>),\n\n {\n\n // reserve space to write the prefixed length\n\n let offset = self.len();\n\n self.extend(&[0; 4]);\n", "file_path": "sqlx-core/src/postgres/io/buf_mut.rs", "rank": 94, "score": 129861.66712043333 }, { "content": "pub fn run(cargo_args: Vec<String>) -> anyhow::Result<()> {\n\n #[derive(serde::Serialize)]\n\n struct DataFile {\n\n db: &'static str,\n\n #[serde(flatten)]\n\n data: QueryData,\n\n }\n\n\n\n let db_kind = get_db_kind()?;\n\n let data = run_prepare_step(cargo_args)?;\n\n\n\n serde_json::to_writer_pretty(\n\n File::create(\"sqlx-data.json\").context(\"failed to create/open `sqlx-data.json`\")?,\n\n &DataFile { db: db_kind, data },\n\n )\n\n .context(\"failed to write to `sqlx-data.json`\")?;\n\n\n\n println!(\n\n \"query data written to `sqlx-data.json` in the current directory; \\\n\n please check this into version control\"\n\n );\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "sqlx-cli/src/prepare.rs", "rank": 95, "score": 129782.55507032468 }, { "content": "pub fn check(cargo_args: Vec<String>) -> anyhow::Result<()> {\n\n let db_kind = get_db_kind()?;\n\n let data = run_prepare_step(cargo_args)?;\n\n\n\n let data_file = fs::read(\"sqlx-data.json\").context(\n\n \"failed to open `sqlx-data.json`; you may need to run `cargo sqlx prepare` first\",\n\n )?;\n\n\n\n let mut saved_data: QueryData = serde_json::from_slice(&data_file)?;\n\n\n\n let expected_db = saved_data\n\n .remove(\"db\")\n\n .context(\"expected key `db` in data file\")?;\n\n\n\n let expected_db = expected_db\n\n .as_str()\n\n .context(\"expected key `db` to be a string\")?;\n\n\n\n if db_kind != expected_db {\n\n bail!(\n", "file_path": "sqlx-cli/src/prepare.rs", "rank": 96, "score": 129782.55507032468 }, { "content": "// https://github.com/RustCrypto/RSA/blob/9f1464c43831d422d9903574aad6ab072db9f2b0/src/internals.rs#L184\n\nfn internals_copy_with_left_pad(dest: &mut [u8], src: &[u8]) {\n\n // left pad with zeros\n\n let padding_bytes = dest.len() - src.len();\n\n for el in dest.iter_mut().take(padding_bytes) {\n\n *el = 0;\n\n }\n\n dest[padding_bytes..].copy_from_slice(src);\n\n}\n\n\n", "file_path": "sqlx-core/src/mysql/protocol/rsa.rs", "rank": 97, "score": 129147.55972809323 }, { "content": "#[derive(sqlx::FromRow)]\n\nstruct SqliteArticleEntity {\n\n article_id: EntityId,\n\n title: String,\n\n slug: String,\n\n description: String,\n\n body: String,\n\n author_id: EntityId,\n\n created_at: i32,\n\n updated_at: i32,\n\n}\n\n\n\nimpl From<SqliteArticleEntity> for ArticleEntity {\n\n fn from(entity: SqliteArticleEntity) -> Self {\n\n let SqliteArticleEntity {\n\n article_id,\n\n title,\n\n slug,\n\n description,\n\n body,\n\n author_id,\n", "file_path": "examples/realworld/src/db/sqlite.rs", "rank": 98, "score": 128995.9200763093 }, { "content": "#[derive(sqlx::FromRow)]\n\nstruct SqliteCommentEntity {\n\n comment_id: EntityId,\n\n body: String,\n\n article_id: EntityId,\n\n author_id: EntityId,\n\n created_at: EntityId,\n\n updated_at: EntityId,\n\n}\n\n\n\nimpl From<SqliteCommentEntity> for CommentEntity {\n\n fn from(entity: SqliteCommentEntity) -> Self {\n\n let SqliteCommentEntity {\n\n comment_id,\n\n body,\n\n article_id,\n\n author_id,\n\n created_at,\n\n updated_at,\n\n } = entity;\n\n CommentEntity {\n", "file_path": "examples/realworld/src/db/sqlite.rs", "rank": 99, "score": 128995.9200763093 } ]
Rust
src/base.rs
KeenS/kappaLisp
9f6726d49e278f40270994939d126285cd9b8d3b
use std::ops::Deref; use env::Env; use eval::funcall; use expr::{Error as E, Expr, Kfloat, Kint, Result, Type}; use util::*; macro_rules! expr { ($e:expr) => { $e }; } macro_rules! def_arith_op { ($name: ident, $op: tt, $init: expr) => { pub fn $name(env: &mut Env, args: &Expr) -> Result<Expr> { let (init, args) = match args { Expr::Cons(hd, tl) => match tl.deref() { tl @ &Expr::Cons(_, _) => (hd.deref().clone(), tl), _ => ($init, args), }, args => ($init, args), }; f_foldl( env, &|_, x, y| match (x, y) { (&Expr::Int(x), &Expr::Int(y)) => Ok(kint(expr!(x $op y))), (&Expr::Float(x), &Expr::Int(y)) => Ok(kfloat(expr!(x $op (y as Kfloat)))), (&Expr::Int(x), &Expr::Float(y)) => Ok(kfloat(expr!((x as Kfloat) $op y))), (&Expr::Float(x), &Expr::Float(y)) => Ok(kfloat(expr!(x $op y))), (&Expr::Int(_), y) => Err(E::Type(Type::Int, y.clone())), (x, _) => Err(E::Type(Type::Int, x.clone())), }, &init, args, ) } }; } def_arith_op!(k_add, +, kint(0)); def_arith_op!(k_sub, -, kint(0)); def_arith_op!(k_mul, *, kint(1)); def_arith_op!(k_div, /, kint(1)); macro_rules! def_arith_cmp { ($name: ident, $op: tt) => { pub fn $name(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (x, Int)(y, Int)); Ok(kbool(expr!(x $op y))) } }; } def_arith_cmp!(k_gt, >); def_arith_cmp!(k_ge, >=); def_arith_cmp!(k_lt, <); def_arith_cmp!(k_le, <=); def_arith_cmp!(k_eq, ==); def_arith_cmp!(k_neq, !=); pub fn k_concat(env: &mut Env, args: &Expr) -> Result<Expr> { let res = f_foldl( env, &|_, acc, x| match (acc, x) { (&Expr::Str(ref acc), &Expr::Str(ref x)) => Ok(kstr(format!("{}{}", acc, x))), (_, y) => Err(E::Type(Type::Str, y.clone())), }, &kstr(""), &args, ); Ok(res?.clone()) } pub fn k_funcall(env: &mut Env, args: &Expr) -> Result<Expr> { match args { &Expr::Cons(ref f, ref args) => match f.deref() { &Expr::Proc(ref f) => funcall(env, f, args.deref()), f => Err(E::NotFunction(f.clone())), }, args => Err(E::Form(args.clone())), } } pub fn k_cons(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (car, Any)(cdr, Any)); Ok(kcons(car.clone(), cdr.clone())) } pub fn k_car(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, ((car, _), Cons)); Ok(car.clone()) } pub fn k_cdr(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, ((_, cdr), Cons)); Ok(cdr.clone()) } pub fn k_equal_p(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (x, Any)(y, Any)); if x == y { Ok(ksym("t")) } else { Ok(knil()) } } pub fn k_string_to_number(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (s, Str)); match s.parse() { Ok(i) => Ok(Expr::Int(i)), Err(_) => Err(E::InvalidArgument(args.clone())), } } pub fn k_substring(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (s, Str) & optional(start, Int)(end, Int)); let len = s.len(); let ilen = len as Kint; let start = start.unwrap_or(0); let end = end.unwrap_or(ilen); if 0 <= start && start <= end && end < ilen { let start = start as usize; let end = end as usize; Ok(kstr((&s[start..end]).to_owned())) } else { Err(E::InvalidArgument(args.clone())) } } pub fn init(env: &mut Env) -> Result<()> { env.fregister("+", kprim("k_add", k_add)); env.fregister("-", kprim("k_sub", k_sub)); env.fregister("/", kprim("k_div", k_div)); env.fregister("*", kprim("k_mul", k_mul)); env.fregister(">", kprim("k_gt", k_gt)); env.fregister(">=", kprim("k_ge", k_ge)); env.fregister("<", kprim("k_lt", k_lt)); env.fregister("<=", kprim("k_le", k_le)); env.fregister("=", kprim("k_eq", k_eq)); env.fregister("/=", kprim("k_neq", k_neq)); env.fregister("concat", kprim("k_concat", k_concat)); env.fregister("funcall", kprim("k_funcall", k_funcall)); env.fregister("cons", kprim("k_cons", k_cons)); env.fregister("car", kprim("k_car", k_car)); env.fregister("cdr", kprim("k_cdr", k_cdr)); env.fregister("equalp", kprim("k_equal_p", k_equal_p)); env.fregister( "string-to-number", kprim("k_string_to_number", k_string_to_number), ); env.fregister("substring", kprim("k_substring", k_substring)); env.register("t", ksym("t")); Ok(()) }
use std::ops::Deref; use env::Env; use eval::funcall; use expr::{Error as E, Expr, Kfloat, Kint, Result, Type}; use util::*; macro_rules! expr { ($e:expr) => { $e }; } macro_rules! def_arith_op { ($name: ident, $op: tt, $init: expr) => { pub fn $name(env: &mut Env, args: &Expr) -> Result<Expr> { let (init, args) = match args { Expr::Cons(hd, tl) => match tl.deref() { tl @ &Expr::Cons(_, _) => (hd.deref().clone(), tl), _ => ($init, args), }, args => ($init, args), }; f_foldl( env, &|_, x, y| match (x, y) { (&Expr::Int(x), &Expr::Int(y)) => Ok(kint(expr!(x $op y))), (&Expr::Float(x), &Expr::Int(y)) => Ok(kfloat(expr!(x $op (y as Kfloat)))), (&Expr::Int(x), &Expr::Float(y)) => Ok(kfloat(expr!((x as Kfloat) $op y))), (&Expr::Float(x), &Expr::Float(y)) => Ok(kfloat(expr!(x $op y))), (&Expr::Int(_), y) => Err(E::Type(Type::Int, y.clone())), (x, _) => Err(E::Type(Type::Int, x.clone())), }, &init, args, ) } }; } def_arith_op!(k_add, +, kint(0)); def_arith_op!(k_sub, -, kint(0)); def_arith_op!(k_mul, *, kint(1)); def_arith_op!(k_div, /, kint(1)); macro_rules! def_arith_cmp { ($name: ident, $op: tt) => { pub fn $name(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (x, Int)(y, Int)); Ok(kbool(expr!(x $op y))) } }; } def_arith_cmp!(k_gt, >); def_arith_cmp!(k_ge, >=); def_arith_cmp!(k_lt, <); def_arith_cmp!(k_le, <=); def_arith_cmp!(k_eq, ==); def_arith_cmp!(k_neq, !=); pub fn k_concat(env: &mut Env, args: &Expr) -> Result<Expr> { let res = f_foldl( env, &|_, acc, x| match (acc, x) { (&Expr::Str(ref acc), &Expr::Str(ref x)) => Ok(kstr(format!("{}{}", acc, x))), (_, y) => Err(E::Type(Type::Str, y.clone())), }, &kstr(""), &args, ); Ok(res?.clone()) } pub fn k_funcall(env: &mut Env, args: &Expr) -> Result<Expr> { match args { &Expr::Cons(ref f, ref args) => match f.deref() { &Expr::Proc(ref f) => funcall(env, f, args.deref()), f => Err(E::NotFunction(f.clone())), }, args => Err(E::Form(args.clone())), } } pub fn k_cons(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (car, Any)(cdr, Any)); Ok(kcons(car.clone(), cdr.clone())) } pub fn k_car(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, ((car, _), Cons)); Ok(car.clone()) } pub fn k_cdr(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, ((_, cdr), Cons)); Ok(cdr.clone()) } pub fn k_equal_p(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (x, Any)(y, Any)); if x == y { Ok(ksym("t")) } else { Ok(knil()) } } pub fn k_string_to_number(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (s, Str)); match s.parse() { Ok(i) => Ok(Expr::Int(i)), Err(_) => Err(E::InvalidArgument(args.clone())), } } pub fn k_substring(_: &mut Env, args: &Expr) -> Result<Expr> { get_args!(args, (s, Str) & optional(start, Int)(end, Int)); let len = s.len(); let ilen = len as Kint; let start = start.unwrap_or(0); let end = end.unwrap_or(ilen); if 0 <= start && start <= end && end < ilen { let start = start as usize; let end = end as usize; Ok(kstr((&s[start..end]).to_owned())) } else { Err(E::InvalidArgument(args.clone())) } } pub fn init(env: &mut Env) -> Result<()> { env.fregister("+", kprim("k_add", k_add)); env.fregister("-", kprim("k_sub", k_sub)); env.fregister("/", kprim("k_div", k_div)); env.fregister("*", kprim("k_mul", k_mul)); env.fregister(">", kprim("k_gt", k_gt)); env.fregister(">=", kprim("k_ge", k_ge)); env.fregister("<", kprim("k_lt", k_lt)); env.fregister("<=", kprim("k_le", k_le)); env.fregister("=", kprim("k_eq", k_eq)); env.fregister("/=", kprim("k_neq", k_neq)); env.fregister("concat", kprim("k_concat", k_concat)); en
v.fregister("funcall", kprim("k_funcall", k_funcall)); env.fregister("cons", kprim("k_cons", k_cons)); env.fregister("car", kprim("k_car", k_car)); env.fregister("cdr", kprim("k_cdr", k_cdr)); env.fregister("equalp", kprim("k_equal_p", k_equal_p)); env.fregister( "string-to-number", kprim("k_string_to_number", k_string_to_number), ); env.fregister("substring", kprim("k_substring", k_substring)); env.register("t", ksym("t")); Ok(()) }
function_block-function_prefixed
[ { "content": "pub fn f_foldl<F>(env: &mut Env, f: &F, init: &Expr, args: &Expr) -> Result<Expr>\n\nwhere\n\n F: Fn(&mut Env, &Expr, &Expr) -> Result<Expr>,\n\n{\n\n let mut res = init.clone();\n\n let mut head = args;\n\n let nil = &Expr::Nil;\n\n while head != nil {\n\n match head {\n\n Expr::Cons(car, cdr) => {\n\n res = f(env, &res, car)?;\n\n head = cdr;\n\n }\n\n _ => return Err(E::InvalidArgument(args.clone())),\n\n }\n\n }\n\n Ok(res)\n\n}\n\n\n\n// fn f_reverse(mut env: &mut Env, args: &Expr) -> Result<Expr> {\n\n// f_foldl(env, &|_, acc, x| Ok(Expr::Cons(Rc::new(x.clone()), Rc::new(acc))), Expr::Nil, args)\n\n// }\n\n\n", "file_path": "src/util.rs", "rank": 0, "score": 362280.70125861006 }, { "content": "pub fn f_foldr<F>(env: &mut Env, f: &F, init: &Expr, args: &Expr) -> Result<Expr>\n\nwhere\n\n F: Fn(&mut Env, &Expr, &Expr) -> Result<Expr>,\n\n{\n\n match args {\n\n Expr::Nil => Ok(init.clone()),\n\n Expr::Cons(car, cdr) => {\n\n let v = f_foldr(env, f, init, cdr)?;\n\n f(env, &v, car)\n\n }\n\n args => Err(E::InvalidArgument(args.clone())),\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 1, "score": 345708.9976785162 }, { "content": "pub fn f_map<F>(env: &mut Env, f: &F, list: &Expr) -> Result<Expr>\n\nwhere\n\n F: Fn(&mut Env, &Expr) -> Result<Expr>,\n\n{\n\n f_foldr(\n\n env,\n\n &|env, acc, x| Ok(kcons(f(env, x)?, acc.clone())),\n\n &knil(),\n\n list,\n\n )\n\n}\n\n\n\n// fn f_iter<F>(mut env: &mut Env, f: &F, list: &Expr) -> Result<Expr>\n\n// where F: Fn(&mut Env, Expr) -> Result<()>{\n\n// f_foldr(env, &|env, _, x| {try!(f(env,x.clone())); Ok(Expr::Nil)}\n\n// , Expr::Nil, list)\n\n// }\n", "file_path": "src/util.rs", "rank": 2, "score": 300566.3099178815 }, { "content": "pub fn funcall(env: &mut Env, f: &Proc, args: &Expr) -> Result<Expr> {\n\n match f {\n\n Proc::Prim(_, f) => f(env, args),\n\n Proc::Lambda(params, body) => {\n\n env.new_local();\n\n bind_names(env, params.deref(), args)?;\n\n let ret = eval(env, body.deref());\n\n env.end_local();\n\n ret\n\n }\n\n f => Err(E::NotFunction(kproc(f.clone()))),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 9, "score": 267685.4709909895 }, { "content": "pub fn k_current_time(_: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args);\n\n let time::Timespec { sec, nsec } = time::get_time();\n\n let hi = sec >> LOWER_BITS;\n\n let lo = sec & ((1 << LOWER_BITS) - 1);\n\n Ok(klist!(hi as Kint, lo as Kint, nsec as Kint, 0))\n\n}\n\n\n", "file_path": "src/datetime.rs", "rank": 10, "score": 265522.2030200672 }, { "content": "pub fn init(mut env: &mut Env) -> Result<()> {\n\n env.fregister(\"skk-calc\", kprim(\"k_skk_calc\", k_skk_calc));\n\n env.fregister(\n\n \"skk-current-date-1\",\n\n kprim(\"k_skk_current_date_1\", k_skk_current_date_1),\n\n );\n\n env.fregister(\n\n \"skk-current-date\",\n\n kprim(\"k_skk_current_date\", k_skk_current_date),\n\n );\n\n let lisp = include_str!(\"skk.lisp\");\n\n let mut input = lisp.chars().peekable();\n\n while let Some(e) = read_in(&mut input) {\n\n let _ = eval(&mut env, &e)?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/skk.rs", "rank": 12, "score": 264343.1049772796 }, { "content": "pub fn run(env: &mut Env, sexp: &str) -> Result<Expr> {\n\n let expr = read(sexp)?;\n\n eval(env, &expr)\n\n}\n\n\n", "file_path": "src/kappa_lisp.rs", "rank": 13, "score": 263259.43580092315 }, { "content": "pub fn k_current_time_string(_: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, &optional (specified_time, Any) (_, Any));\n\n let now = match specified_time {\n\n None => time::now(),\n\n Some(st) => time::at(datetime_info_to_timespec(st)?),\n\n };\n\n Ok(kstr(format!(\"{}\", now.ctime())))\n\n}\n\n\n", "file_path": "src/datetime.rs", "rank": 15, "score": 260973.43425168138 }, { "content": "pub fn k_skk_current_date_1(_: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, &optional(specified_time, Any));\n\n // TODO: don't allocate month/wday table every time\n\n let mvec = vec![\n\n \"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\",\n\n ];\n\n let wvec = vec![\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n let now = specified_time.map_or(Ok(time::now()), |st| {\n\n datetime_info_to_timespec(st).map(|tm| time::at(tm))\n\n });\n\n let now = now?;\n\n let year = (now.tm_year + 1900).to_string();\n\n let month = mvec[now.tm_mon as usize];\n\n let mday = now.tm_mday.to_string();\n\n let wday = wvec[now.tm_wday as usize];\n\n let hour = now.tm_hour.to_string();\n\n let min = now.tm_min.to_string();\n\n let sec = now.tm_sec.to_string();\n\n Ok(klist!(year, month, mday, wday, hour, min, sec))\n\n}\n\n\n", "file_path": "src/skk.rs", "rank": 16, "score": 260973.4342516814 }, { "content": "pub fn cdr(cons: &Expr) -> Result<Expr> {\n\n match cons {\n\n Expr::Cons(_, cdr) => Ok(cdr.deref().clone()),\n\n arg => Err(E::Type(Type::Cons, arg.clone())),\n\n }\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! klist {\n\n ($car: expr, $($cdr: expr), *) => (\n\n kcons($crate::expr::Expr::from($car), klist!($($cdr),*))\n\n );\n\n ($car: expr) => (\n\n kcons($crate::expr::Expr::from($car), knil())\n\n );\n\n () => (\n\n knil()\n\n );\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 17, "score": 260724.09967563662 }, { "content": "pub fn car(cons: &Expr) -> Result<Expr> {\n\n match cons {\n\n Expr::Cons(car, _) => Ok(car.deref().clone()),\n\n arg => Err(E::Type(Type::Cons, arg.clone())),\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 18, "score": 260724.09967563662 }, { "content": "pub fn init(env: &mut Env) -> Result<()> {\n\n env.fregister(\n\n \"current-time-string\",\n\n kprim(\"k_current_time_string\", k_current_time_string),\n\n );\n\n env.fregister(\"current-time\", kprim(\"k_current_time\", k_current_time));\n\n Ok(())\n\n}\n", "file_path": "src/datetime.rs", "rank": 19, "score": 259622.5743023807 }, { "content": "pub fn init(env: &mut Env) -> Result<()> {\n\n let lisp = include_str!(\"stdlib.lisp\");\n\n let mut input = lisp.chars().peekable();\n\n while let Some(e) = read_in(&mut input) {\n\n let _ = eval(env, &e)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "src/stdlib.rs", "rank": 21, "score": 259622.57430238073 }, { "content": "pub fn k_skk_calc(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, (op, Sym));\n\n let skk_num_list = env.find(&\"skk-num-list\".to_owned())?.clone();\n\n get_args!(&skk_num_list, (x, Int)(y, Int));\n\n let res = match &op[..] {\n\n \"+\" => x + y,\n\n \"-\" => x - y,\n\n \"*\" => x * y,\n\n \"/\" => x / y,\n\n op => return Err(E::User(format!(\"unknown operator {}\", op))),\n\n };\n\n Ok(kint(res))\n\n}\n\n\n", "file_path": "src/skk.rs", "rank": 22, "score": 257018.35518959785 }, { "content": "pub fn k_skk_default_current_date(_: &mut Env, args: &Expr) -> Result<Expr> {\n\n // get_args!(args,\n\n // (date_information, Any)\n\n // (format, Nullable Str)\n\n // (num_type, Int)\n\n // (gengo, Bool)\n\n // (gengo_index, Nullable Int)\n\n // (month_alist_index, Nullable Int)\n\n // (dayofweek_alist_index, Nullable Int)\n\n // &optional (and_time, Bool)\n\n // );\n\n // get_args!(date_information,\n\n // (year, Str)(month, Str)(day, Str)(day_of_week, Str)(hour, Str)(minute, Str)(second,\n\n // Str));\n\n // let res = match and_time {\n\n // None | Some(false) => {\n\n // let format = format.map_or(\"%s年%s月%s日(%s)\", |s| &s);\n\n // kstr(format)\n\n // }\n\n // _ => {\n\n // let format = format.map_or(\"%s年%s月%s日(%s)%s時%s分%s秒\", |s| &s);\n\n // kstr(format)\n\n // }\n\n // };\n\n Ok(knil())\n\n}\n\n\n", "file_path": "src/skk.rs", "rank": 23, "score": 256706.20282152953 }, { "content": "#[inline]\n\npub fn kprim<S: Into<String>, F: 'static + Fn(&mut Env, &Expr) -> Result<Expr> + Sized>(\n\n name: S,\n\n f: F,\n\n) -> Proc {\n\n Proc::Prim(name.into(), Rc::new(f))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 24, "score": 255669.0942210848 }, { "content": "pub fn init(env: &mut Env) -> Result<()> {\n\n base::init(env)?;\n\n datetime::init(env)?;\n\n stdlib::init(env)?;\n\n skk::init(env)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/kappa_lisp.rs", "rank": 25, "score": 254803.710756746 }, { "content": "pub fn k_skk_current_date(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, &optional(f, Proc)(format, Any)(and_time, Any));\n\n let date_information = k_skk_current_date_1(env, &knil())?;\n\n let nil = knil();\n\n let format = format.unwrap_or(&nil);\n\n let gengo = knil(); //or t\n\n let and_time = and_time.unwrap_or(&nil);\n\n match f {\n\n Some(f) => funcall(env, f, &klist!(date_information, format, gengo, and_time)),\n\n None => Ok(knil()),\n\n }\n\n}\n\n\n", "file_path": "src/skk.rs", "rank": 26, "score": 252741.9361886959 }, { "content": "fn bind_name(env: &mut Env, name: &Expr, value: Expr) -> Result<()> {\n\n match name {\n\n &Expr::Sym(ref name) => Ok(env.register(name.deref().clone(), value)),\n\n name => return Err(E::Form(name.clone())),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 27, "score": 249001.5567990526 }, { "content": "pub fn eval(env: &mut Env, expr: &Expr) -> Result<Expr> {\n\n match expr {\n\n Expr::Nil\n\n | Expr::Str(_)\n\n | Expr::Int(_)\n\n | Expr::Float(_)\n\n | Expr::Keyword(_)\n\n | Expr::Proc(_) => Ok(expr.clone()),\n\n Expr::Sym(name) => match env.find(&name.to_owned()) {\n\n Ok(v) => Ok(v.clone()),\n\n Err(m) => {\n\n if name.deref() == \"t\" {\n\n Ok(ksym(\"t\"))\n\n } else {\n\n Err(m)\n\n }\n\n }\n\n },\n\n Expr::Cons(car, cdr) => {\n\n let car = car.deref();\n", "file_path": "src/eval.rs", "rank": 28, "score": 248684.6896582007 }, { "content": "fn k_quote(_: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, (sexp, Any));\n\n Ok(sexp.clone())\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 29, "score": 240194.0253152196 }, { "content": "fn bind_names(env: &mut Env, params: &Expr, args: &Expr) -> Result<()> {\n\n let mut phead = params;\n\n let mut ahead = args;\n\n let mut in_optional = false;\n\n let optional = ksym(\"&optional\");\n\n let rest = ksym(\"&rest\");\n\n let nil = &knil();\n\n while phead != nil || ahead != nil {\n\n match phead {\n\n Expr::Cons(pcar, pcdr) => {\n\n let pcar = pcar.deref();\n\n if pcar == &optional {\n\n in_optional = true;\n\n phead = pcdr.deref();\n\n continue;\n\n }\n\n if pcar == &rest {\n\n match pcdr.deref() {\n\n Expr::Cons(name, tail) => {\n\n if tail.deref() != nil {\n", "file_path": "src/eval.rs", "rank": 30, "score": 240136.46617437014 }, { "content": "#[inline]\n\npub fn kcons(car: Expr, cdr: Expr) -> Expr {\n\n Expr::Cons(Rc::new(car), Rc::new(cdr))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 31, "score": 238572.02363730886 }, { "content": "fn k_if(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n // TODO: optional else clasue. Need optional argments.\n\n get_args!(args, (cnd, Any)(thn, Any) & optional(els, Any));\n\n let res = eval(env, cnd)?;\n\n if res != knil() {\n\n eval(env, thn)\n\n } else {\n\n match els {\n\n Some(els) => eval(env, els),\n\n None => Ok(knil()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 32, "score": 235240.84987684275 }, { "content": "#[inline]\n\npub fn kfloat(f: Kfloat) -> Expr {\n\n Expr::Float(f)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 33, "score": 232341.0372672898 }, { "content": "fn k_feval(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n match args {\n\n Expr::Cons(car, _) => Ok(kproc(feval(env, car.deref())?)),\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 34, "score": 230845.3801983993 }, { "content": "fn k_progn(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n let mut head = args;\n\n let nil = &knil();\n\n let mut res = knil();\n\n while head != nil {\n\n match head {\n\n Expr::Cons(car, cdr) => {\n\n res = eval(env, car.deref())?;\n\n head = cdr.deref();\n\n }\n\n _ => return Err(E::Form(args.clone())),\n\n }\n\n }\n\n Ok(res)\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 35, "score": 230845.3801983993 }, { "content": "fn k_fset(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, (s, Any)(f, Any));\n\n let s = eval(env, s)?;\n\n let f = feval(env, f)?;\n\n let tmp = klist!(s);\n\n get_args!(&tmp, (s, Sym));\n\n env.fregister(s.deref().clone(), f.clone());\n\n return Ok(knil());\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 36, "score": 230845.3801983993 }, { "content": "fn k_lambda(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n Ok(kproc(f_lambda(env, args)?))\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 37, "score": 230845.3801983993 }, { "content": "fn k_set(env: &mut Env, args: &Expr) -> Result<Expr> {\n\n get_args!(args, (s, Any)(e, Any));\n\n let s = eval(env, s)?;\n\n let e = eval(env, e)?;\n\n let tmp = klist!(s);\n\n get_args!(&tmp, (s, Sym));\n\n env.register(s.deref().clone(), e.clone());\n\n return Ok(knil());\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 38, "score": 230845.3801983993 }, { "content": "fn f_lambda(_: &mut Env, args: &Expr) -> Result<Proc> {\n\n match args {\n\n Expr::Cons(params, body) => Ok(klambda(\n\n params.deref().clone(),\n\n kcons(ksym(\"progn\"), body.deref().clone()),\n\n )),\n\n _ => unreachable!(),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 39, "score": 225650.5764401518 }, { "content": "fn feval(env: &mut Env, expr: &Expr) -> Result<Proc> {\n\n match expr {\n\n Expr::Sym(sym) => match env.ffind(sym) {\n\n Ok(f) => Ok(f.clone()),\n\n Err(e) => Err(e),\n\n },\n\n Expr::Cons(op, rest) => {\n\n let op = op.deref();\n\n match op {\n\n Expr::Sym(sym) => match &sym[..] {\n\n \"lambda\" => f_lambda(env, rest.deref()),\n\n _ => Ok(Proc::Expr(Rc::new(eval(env, expr)?))),\n\n },\n\n _ => Err(E::NotFunction(expr.clone())),\n\n }\n\n }\n\n Expr::Proc(f) => Ok(f.clone()),\n\n _ => Err(E::NotFunction(expr.clone())),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 40, "score": 209329.04677403765 }, { "content": "#[inline]\n\npub fn kint(i: Kint) -> Expr {\n\n Expr::Int(i)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 41, "score": 207707.1446598022 }, { "content": "pub fn read(s: &str) -> Result<Expr> {\n\n let mut input = s.chars().peekable();\n\n match read_aux(&mut input, ' ') {\n\n Some(e) => Ok(e),\n\n None => Err(Error::ReadError),\n\n }\n\n}\n", "file_path": "src/read.rs", "rank": 42, "score": 203559.9865250722 }, { "content": "pub fn run_new(sexp: &str) -> Result<Expr> {\n\n let mut env = Env::new();\n\n init(&mut env)?;\n\n let expr = read(sexp)?;\n\n eval(&mut env, &expr)\n\n}\n", "file_path": "src/kappa_lisp.rs", "rank": 43, "score": 191478.64757401342 }, { "content": "pub fn macro_fn(env: &mut Env, p: &Proc) -> Result<Option<Proc>> {\n\n match p {\n\n Proc::Expr(exp) => match exp.deref() {\n\n Expr::Cons(sym, f) => if sym.deref() == &ksym(\"macro\") {\n\n Ok(Some(feval(env, f.deref())?))\n\n } else {\n\n Ok(None)\n\n },\n\n _ => Ok(None),\n\n },\n\n _ => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/eval.rs", "rank": 44, "score": 189964.6140920312 }, { "content": "#[inline]\n\npub fn kstr<S: Into<String>>(s: S) -> Expr {\n\n Expr::Str(Rc::new(s.into()))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 45, "score": 172405.15313544078 }, { "content": "pub fn datetime_info_to_timespec(args: &Expr) -> Result<Timespec> {\n\n get_args!(args, (hi, Int) (lo, Int) (nsec, Int) (_, Int));\n\n let hi = hi as i64;\n\n let lo = lo as i64;\n\n let sec = (hi << LOWER_BITS) + lo;\n\n Ok(Timespec {\n\n sec: sec,\n\n nsec: nsec as i32,\n\n })\n\n}\n\n\n", "file_path": "src/datetime.rs", "rank": 46, "score": 167455.4470713874 }, { "content": "#[inline]\n\npub fn knil() -> Expr {\n\n Expr::Nil\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 47, "score": 151015.35730859943 }, { "content": "#[inline]\n\npub fn kbool(b: bool) -> Expr {\n\n match b {\n\n true => ksym(\"t\"),\n\n false => Expr::Nil,\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 48, "score": 141083.6865462302 }, { "content": "#[inline]\n\npub fn kmacro(p: Proc) -> Expr {\n\n kcons(ksym(\"macro\"), Expr::Proc(p))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 49, "score": 141083.6865462302 }, { "content": "#[inline]\n\npub fn kproc(p: Proc) -> Expr {\n\n Expr::Proc(p)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 50, "score": 141083.6865462302 }, { "content": "#[inline]\n\npub fn klambda(param: Expr, body: Expr) -> Proc {\n\n Proc::Lambda(Rc::new(param), Rc::new(body))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 51, "score": 140563.9332668624 }, { "content": "pub fn read_in(input: &mut Peekable<Chars>) -> Option<Expr> {\n\n read_aux(input, ' ')\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 52, "score": 138496.2047019321 }, { "content": "#[inline]\n\npub fn kkw<S: Into<String>>(s: S) -> Expr {\n\n Expr::Keyword(Rc::new(s.into()))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 53, "score": 127175.68803019653 }, { "content": "#[inline]\n\npub fn ksym<S: Into<String>>(s: S) -> Expr {\n\n Expr::Sym(Rc::new(s.into()))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 54, "score": 127175.68803019653 }, { "content": "fn read_string(input: &mut Peekable<Chars>, _: char) -> Option<Expr> {\n\n let mut string = String::new();\n\n // :TODO: treat escapes\n\n loop {\n\n let c = input.next()?;\n\n match c == '\"' {\n\n true => return Some(kstr(string)),\n\n false => string.push(c),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 55, "score": 114379.40884781204 }, { "content": "fn read_list(input: &mut Peekable<Chars>, _: char) -> Option<Expr> {\n\n let c = next_nonwhitespaces(input, ' ')?;\n\n let car = match c {\n\n ')' => return Some(knil()),\n\n _ => read_aux(input, c),\n\n };\n\n\n\n let c = peek_nonwhitespaces(input, ' ')?;\n\n let cdr = if c == '.' {\n\n let _ = next_nonwhitespaces(input, ' ')?; // == 'c'\n\n match read_list(input, '(')? {\n\n Expr::Cons(ref e, ref nil) => {\n\n if nil.deref() == &knil() {\n\n Some(e.deref().clone())\n\n } else {\n\n None\n\n }\n\n }\n\n _ => None,\n\n }\n\n } else {\n\n read_list(input, '(')\n\n };\n\n match (car, cdr) {\n\n (Some(car), Some(cdr)) => Some(kcons(car, cdr)),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 56, "score": 114379.40884781204 }, { "content": "fn read_function(input: &mut Peekable<Chars>, _: char) -> Option<Expr> {\n\n let v = read_aux(input, ' ')?;\n\n Some(klist!(ksym(\"function\"), v))\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 57, "score": 114379.40884781204 }, { "content": "fn read_dispatch(input: &mut Peekable<Chars>, _: char) -> Option<Expr> {\n\n let v = input.next()?;\n\n match v {\n\n '\\'' => read_function(input, '\\''),\n\n v => panic!(\"unknown reader macro #{:?}\", v),\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 58, "score": 114379.40884781204 }, { "content": "fn read_quote(input: &mut Peekable<Chars>, _: char) -> Option<Expr> {\n\n let v = read_aux(input, ' ')?;\n\n Some(klist!(ksym(\"quote\"), v))\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 59, "score": 114379.40884781207 }, { "content": "fn read_int(input: &mut Peekable<Chars>, first: char, radix: u32) -> Option<Kint> {\n\n match first {\n\n '0'...'9' => read_uint(input, first, radix),\n\n _ => {\n\n let c = input.next()?;\n\n match first {\n\n '+' => read_uint(input, c, radix),\n\n '-' => Some(-1 * read_uint(input, c, radix)?),\n\n _ => None,\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 60, "score": 110761.19552739742 }, { "content": "pub fn is_macro(exp: &Proc) -> bool {\n\n match exp {\n\n Proc::Expr(exp) => match exp.deref() {\n\n Expr::Cons(sym, _) => sym.deref() == &kstr(\"macro\"),\n\n _ => false,\n\n },\n\n _ => false,\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 61, "score": 94324.12829871882 }, { "content": "fn read_symbol(input: &mut Peekable<Chars>, first: char) -> Option<Expr> {\n\n let mut sym = first.to_string();\n\n while input.peek().map(|c| !is_delimiter(*c)).unwrap_or(false) {\n\n sym.push(input.next().unwrap());\n\n }\n\n if sym == \"nil\" {\n\n Some(knil())\n\n } else {\n\n Some(ksym(sym))\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 62, "score": 92928.28368873123 }, { "content": "fn read_plus(input: &mut Peekable<Chars>, first: char) -> Option<Expr> {\n\n let c = input.peek()?.clone();\n\n match c.is_digit(10) {\n\n true => read_number(input, first, 10),\n\n false => read_symbol(input, first),\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 63, "score": 92928.28368873123 }, { "content": "fn read_aux(input: &mut Peekable<Chars>, first: char) -> Option<Expr> {\n\n let first = next_nonwhitespaces(input, first)?;\n\n match first {\n\n '0'...'9' => read_number(input, first, 10),\n\n '-' => read_hyphen(input, first),\n\n '+' => read_plus(input, first),\n\n '(' => read_list(input, first),\n\n '\"' => read_string(input, first),\n\n '\\'' => read_quote(input, first),\n\n '#' => read_dispatch(input, first),\n\n ':' => read_keyword(input, first),\n\n _ => read_symbol(input, first),\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 64, "score": 92928.28368873123 }, { "content": "fn read_hyphen(input: &mut Peekable<Chars>, first: char) -> Option<Expr> {\n\n let c = input.peek()?.clone();\n\n match c.is_digit(10) {\n\n true => read_number(input, first, 10),\n\n false => read_symbol(input, first),\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 65, "score": 92928.28368873123 }, { "content": "fn read_keyword(input: &mut Peekable<Chars>, first: char) -> Option<Expr> {\n\n debug_assert_eq!(first, ':');\n\n let mut kw = String::new();\n\n while input.peek().map(|c| !is_delimiter(*c)).unwrap_or(false) {\n\n kw.push(input.next().unwrap());\n\n }\n\n Some(kkw(kw))\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 66, "score": 92928.28368873123 }, { "content": "fn read_uint(input: &mut Peekable<Chars>, first: char, radix: u32) -> Option<Kint> {\n\n let mut acc = String::new();\n\n acc.push(first);\n\n while input.peek().unwrap_or(&' ').is_digit(radix) {\n\n let c = match input.next() {\n\n Some(x) => x,\n\n None => break,\n\n };\n\n acc.push(c);\n\n }\n\n Some(Kint::from_str_radix(&acc[..], radix).unwrap())\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 67, "score": 91263.99215560421 }, { "content": "fn read_number(input: &mut Peekable<Chars>, first: char, radix: u32) -> Option<Expr> {\n\n let i = read_int(input, first, radix)?;\n\n match input.peek() {\n\n Some(&'.') => {\n\n let mut acc = String::new();\n\n match first {\n\n '-' => {\n\n acc.push('-');\n\n acc.push('0')\n\n }\n\n _ => acc.push('0'),\n\n }\n\n acc.push(input.next()?);\n\n while input.peek().unwrap_or(&' ').is_digit(radix) {\n\n let c = match input.next() {\n\n Some(x) => x,\n\n None => break,\n\n };\n\n acc.push(c);\n\n }\n\n // FIXME: ignoring radix\n\n let f = Kfloat::from_str(&acc[..]).unwrap();\n\n Some(Expr::Float((i as Kfloat) + f))\n\n }\n\n _ => Some(Expr::Int(i)),\n\n }\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 68, "score": 86363.08679269152 }, { "content": "fn peek_nonwhitespaces(input: &mut Peekable<Chars>, first: char) -> Option<char> {\n\n match first.is_whitespace() {\n\n false => return Some(first),\n\n true => (),\n\n }\n\n while input.peek().map(|c| c.is_whitespace()).unwrap_or(false) {\n\n input.next();\n\n }\n\n input.peek().map(|c| c.clone())\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 69, "score": 57270.36744518838 }, { "content": "fn next_nonwhitespaces(input: &mut Peekable<Chars>, first: char) -> Option<char> {\n\n match first.is_whitespace() {\n\n false => return Some(first),\n\n true => (),\n\n }\n\n while input.peek().map(|c| c.is_whitespace()).unwrap_or(false) {\n\n input.next();\n\n }\n\n input.next()\n\n}\n\n\n", "file_path": "src/read.rs", "rank": 70, "score": 57270.36744518838 }, { "content": "#[test]\n\nfn test_car() {\n\n assert_eq!(run_new(\"(car (cons 1 2))\"), Ok(kint(1)));\n\n assert_eq!(run_new(\"(car (list 1 2))\"), Ok(kint(1)));\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 71, "score": 57115.47714635778 }, { "content": "#[test]\n\nfn test_cdr() {\n\n assert_eq!(run_new(\"(cdr (cons 1 2))\"), Ok(kint(2)));\n\n assert_eq!(run_new(\"(cdr (list 1 2))\"), Ok(klist!(kint(2))));\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 72, "score": 57115.47714635778 }, { "content": "#[test]\n\nfn test_cons() {\n\n assert_eq!(run_new(\"(cons 1 2)\"), Ok(kcons(kint(1), kint(2))));\n\n assert_eq!(run_new(\"(cons () 2)\"), Ok(kcons(knil(), kint(2))));\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 73, "score": 57115.47714635778 }, { "content": "#[test]\n\nfn test_read_int() {\n\n assert_eq!(read(\"0\"), Ok(kint(0)));\n\n assert_eq!(read(\"10\"), Ok(kint(10)));\n\n assert_eq!(read(\"-10\"), Ok(kint(-10)));\n\n assert_eq!(read(\"+10\"), Ok(kint(10)));\n\n}\n\n\n", "file_path": "tests/read.rs", "rank": 74, "score": 55023.621442993935 }, { "content": "use std::ops::Deref;\n\nuse std::rc::Rc;\n\n\n\nuse env::Env;\n\nuse expr::{Error as E, Expr, Kfloat, Kint, Proc, Result, Type};\n\n\n\n#[inline]\n", "file_path": "src/util.rs", "rank": 75, "score": 30170.2382949172 }, { "content": " match $v {\n\n &Expr::Nil => Ok(false),\n\n _ => Ok(true)\n\n }\n\n );\n\n ($v:expr, Cons) => (\n\n match $v {\n\n &Expr::Cons(ref car, ref cdr) => Ok((car.deref(), cdr.deref())),\n\n hd => Err(E::Type(Type::Cons, hd.clone()))\n\n }\n\n );\n\n ($v:expr, Proc) => (\n\n match $v {\n\n &Expr::Proc(ref p) => Ok(p),\n\n hd => Err(E::Type(Type::Proc, hd.clone()))\n\n }\n\n );\n\n ($v:expr, Any) => (\n\n match $v {\n\n hd => if true {\n", "file_path": "src/util.rs", "rank": 76, "score": 30169.394038817907 }, { "content": " (\n\n match $args {\n\n Expr::Cons(hd, tl) => {\n\n let v = get_args_one!(hd.deref(), $($ident)+)?;\n\n (v, gen_match!(tl.deref(), $($other)*))\n\n },\n\n Expr::Nil => return Err(E::ArityShort),\n\n args => return Err(E::InvalidArgument(args.clone()))\n\n };\n\n );\n\n ($args: expr, &optional ($var: pat, $($ident: tt)+) $($other:tt) *) =>\n\n (\n\n match $args {\n\n Expr::Cons(hd, tl) => {\n\n let v = get_args_one!(hd.deref(), $($ident)+)?;\n\n (Some(v), gen_match!(tl.deref(), &optional $($other)*))\n\n },\n\n Expr::Nil => {\n\n (None, gen_match!($args, &optional $($other)*))\n\n },\n", "file_path": "src/util.rs", "rank": 77, "score": 30168.81840298612 }, { "content": "macro_rules! get_args_one {\n\n ($v:expr, Nullable $($ident: tt)+) => (\n\n match $v {\n\n &Expr::Nil => Ok(None),\n\n v => Ok(Some(get_args_one!(v, $($ident)+)?))\n\n }\n\n );\n\n ($v:expr, Int) => (\n\n match $v {\n\n &Expr::Int(x) => Ok(x),\n\n hd => Err(E::Type(Type::Int, hd.clone()))\n\n }\n\n );\n\n\n\n ($v:expr, Float) => {\n\n match $v {\n\n &Expr::Float(x) => Ok(x),\n\n hd => Err(E::Type(Type::Float, hd.clone()))\n\n }\n\n };\n", "file_path": "src/util.rs", "rank": 78, "score": 30168.18212025397 }, { "content": " ($v:expr, Str) => (\n\n match $v {\n\n &Expr::Str(ref x) => Ok(x),\n\n hd => Err(E::Type(Type::Str, hd.clone()))\n\n\n\n }\n\n );\n\n ($v:expr, Sym) => (\n\n match $v {\n\n &Expr::Sym(ref x) => Ok(x),\n\n hd => Err(E::Type(Type::Sym, hd.clone()))\n\n }\n\n );\n\n ($v:expr, Nil) => (\n\n match $v {\n\n &Expr::Nil => Ok(()),\n\n hd => Err(E::Type(Type::Nil, hd.clone()))\n\n }\n\n );\n\n ($v:expr, Bool) => (\n", "file_path": "src/util.rs", "rank": 79, "score": 30166.95015876358 }, { "content": " args => return Err(E::InvalidArgument(args.clone()))\n\n };\n\n );\n\n ($args: expr, &optional) => (\n\n match $args {\n\n Expr::Nil => (),\n\n _ => return Err(E::ArityExceed)\n\n }\n\n );\n\n ($args: expr, ) => (\n\n match $args {\n\n Expr::Nil => (),\n\n _ => return Err(E::ArityExceed)\n\n }\n\n );\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! get_args {\n\n ($args: expr, $($other:tt) *) =>\n", "file_path": "src/util.rs", "rank": 80, "score": 30164.897234447068 }, { "content": " Ok(hd)\n\n } else {\n\n unreachable!()\n\n }\n\n };\n\n )\n\n}\n\n\n\nmacro_rules! gen_pattern {\n\n (($var: pat, $($ident: tt)*) $($other:tt) *) => (\n\n ($var, gen_pattern!($($other)*))\n\n );\n\n (&optional ($var: pat, $($ident: tt)*) $($other:tt) *) => (\n\n ($var, gen_pattern!($($other)*))\n\n );\n\n () => (())\n\n}\n\n\n\nmacro_rules! gen_match {\n\n ($args: expr, ($var: pat, $($ident: tt)+) $($other:tt) *) =>\n", "file_path": "src/util.rs", "rank": 81, "score": 30163.376125438725 }, { "content": " (\n\n let gen_pattern!($($other)*) = gen_match!($args, $($other)*);\n\n ) ;\n\n ($args: expr, ) => (\n\n let () = gen_match!($args,);\n\n );\n\n ($args: expr) => (\n\n let () = gen_match!($args,);\n\n );\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 82, "score": 30163.088669722696 }, { "content": "#[test]\n\nfn test_t() {\n\n assert_eq!(run_new(\"t\"), Ok(ksym(\"t\")))\n\n}\n", "file_path": "tests/base.rs", "rank": 83, "score": 29868.7177409188 }, { "content": "fn main() {\n\n let mut env = Env::new();\n\n init(&mut env).unwrap();\n\n run(\n\n &mut env,\n\n r\"\n", "file_path": "src/main.rs", "rank": 84, "score": 29868.7177409188 }, { "content": "#[test]\n\nfn test_if() {\n\n assert_eq!(run_new(\"(if () 1 2)\"), Ok(kint(2)));\n\n assert_eq!(run_new(\"(if 1 1 2)\"), Ok(kint(1)));\n\n assert_eq!(run_new(\"(if 1 1)\"), Ok(kint(1)));\n\n assert_eq!(run_new(\"(if nil 1)\"), Ok(knil()));\n\n}\n", "file_path": "tests/eval.rs", "rank": 85, "score": 29868.7177409188 }, { "content": " match self.flocal.front_mut() {\n\n Some(l) => l.insert(name.into(), value),\n\n None => self.fglobal.insert(name.into(), value),\n\n };\n\n }\n\n\n\n pub fn find(&self, name: &String) -> Result<&Expr> {\n\n for m in self.local.iter() {\n\n match m.get(name) {\n\n Some(v) => return Ok(v),\n\n None => (),\n\n }\n\n }\n\n match self.global.get(name) {\n\n Some(v) => Ok(v),\n\n None => Err(E::Unbound(name.clone())),\n\n }\n\n }\n\n\n\n pub fn ffind(&self, name: &String) -> Result<&Proc> {\n", "file_path": "src/env.rs", "rank": 86, "score": 29382.148307855347 }, { "content": " }\n\n\n\n pub fn new_local(&mut self) {\n\n self.local.push_front(HashMap::new());\n\n self.flocal.push_front(HashMap::new());\n\n }\n\n\n\n pub fn end_local(&mut self) {\n\n self.local.pop_front();\n\n self.flocal.pop_front();\n\n }\n\n\n\n pub fn register<S: Into<String>>(&mut self, name: S, value: Expr) {\n\n match self.local.front_mut() {\n\n Some(l) => l.insert(name.into(), value),\n\n None => self.global.insert(name.into(), value),\n\n };\n\n }\n\n\n\n pub fn fregister<S: Into<String>>(&mut self, name: S, value: Proc) {\n", "file_path": "src/env.rs", "rank": 87, "score": 29379.21078386484 }, { "content": "use std::collections::HashMap;\n\nuse std::collections::LinkedList;\n\n\n\nuse expr::{Error as E, Expr, Proc, Result};\n\n\n\npub struct Env {\n\n global: HashMap<String, Expr>,\n\n local: LinkedList<HashMap<String, Expr>>,\n\n fglobal: HashMap<String, Proc>,\n\n flocal: LinkedList<HashMap<String, Proc>>,\n\n}\n\n\n\nimpl Env {\n\n pub fn new() -> Env {\n\n Env {\n\n global: HashMap::new(),\n\n local: LinkedList::new(),\n\n fglobal: HashMap::new(),\n\n flocal: LinkedList::new(),\n\n }\n", "file_path": "src/env.rs", "rank": 88, "score": 29378.97709202842 }, { "content": " for m in self.flocal.iter() {\n\n match m.get(name) {\n\n Some(v) => return Ok(v),\n\n None => (),\n\n }\n\n }\n\n match self.fglobal.get(name) {\n\n Some(v) => Ok(v),\n\n None => Err(E::Unbound(name.clone())),\n\n }\n\n }\n\n}\n", "file_path": "src/env.rs", "rank": 89, "score": 29378.03428309714 }, { "content": "#[test]\n\nfn test_funcall() {\n\n assert_eq!(run_new(\"(funcall #'+ 1 2)\"), Ok(kint(3)));\n\n assert_eq!(\n\n run_new(\"(funcall #'(lambda (x y) (* x y)) 1 2)\"),\n\n Ok(kint(2))\n\n );\n\n assert_eq!(run_new(\"(funcall (lambda (x y) (* x y)) 1 2)\"), Ok(kint(2)))\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 90, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_progn() {\n\n assert_eq!(run_new(\"(progn 1 2)\"), Ok(kint(2)));\n\n assert_eq!(run_new(\"(progn (+ 1 2) (+ 2 3))\"), Ok(kint(5)));\n\n}\n\n\n", "file_path": "tests/eval.rs", "rank": 91, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_fset() {\n\n let mut env = Env::new();\n\n init(&mut env).unwrap();\n\n assert_eq!(\n\n run(&mut env, \"(fset 'add2 (lambda (x) (+ x 2)))\"),\n\n Ok(knil())\n\n );\n\n assert_eq!(run(&mut env, \"(add2 2)\"), Ok(kint(4)));\n\n}\n\n\n", "file_path": "tests/eval.rs", "rank": 92, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_sub() {\n\n assert_eq!(run_new(\"(-)\"), Ok(kint(0)));\n\n assert_eq!(run_new(\"(- 1)\"), Ok(kint(-1)));\n\n assert_eq!(run_new(\"(- 1 2)\"), Ok(kint(-1)));\n\n assert_eq!(run_new(\"(- 1.0 2 3)\"), Ok(kfloat(-4.0)));\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 93, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_lambda() {\n\n assert_eq!(\n\n run_new(\"(lambda (x) x)\"),\n\n Ok(kproc(klambda(\n\n klist!(ksym(\"x\")),\n\n klist!(ksym(\"progn\"), ksym(\"x\"))\n\n )))\n\n );\n\n assert_eq!(\n\n run_new(\"(lambda (x y z) x)\"),\n\n Ok(kproc(klambda(\n\n klist!(ksym(\"x\"), ksym(\"y\"), ksym(\"z\")),\n\n klist!(ksym(\"progn\"), ksym(\"x\"))\n\n )))\n\n );\n\n assert_eq!(\n\n run_new(\"(lambda (x y &optional z) z)\"),\n\n Ok(kproc(klambda(\n\n klist!(ksym(\"x\"), ksym(\"y\"), ksym(\"&optional\"), ksym(\"z\")),\n\n klist!(ksym(\"progn\"), ksym(\"z\"))\n", "file_path": "tests/eval.rs", "rank": 94, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_atom() {\n\n assert_eq!(run_new(\"1\"), Ok(kint(1)));\n\n assert_eq!(run_new(\"()\"), Ok(knil()));\n\n assert_eq!(run_new(\"t\"), Ok(ksym(\"t\")));\n\n assert_eq!(run_new(\":t\"), Ok(kkw(\"t\")));\n\n assert_eq!(run_new(\"\\\"string\\\"\"), Ok(kstr(\"string\".to_string())));\n\n}\n\n// TODO: test `function`\n\n\n", "file_path": "tests/eval.rs", "rank": 95, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_add() {\n\n assert_eq!(run_new(\"(+)\"), Ok(kint(0)));\n\n assert_eq!(run_new(\"(+ 1)\"), Ok(kint(1)));\n\n assert_eq!(run_new(\"(+ 1 2)\"), Ok(kint(3)));\n\n assert_eq!(run_new(\"(+ 1 2 3)\"), Ok(kint(6)));\n\n assert_eq!(run_new(\"(+ 1 2 3.0)\"), Ok(kfloat(6.0)));\n\n}\n\n\n", "file_path": "tests/base.rs", "rank": 96, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_set() {\n\n let mut env = Env::new();\n\n init(&mut env).unwrap();\n\n assert_eq!(run(&mut env, \"(set 'foo (+ 1 2 3))\"), Ok(knil()));\n\n assert_eq!(run(&mut env, \"foo\"), Ok(kint(6)));\n\n}\n\n\n", "file_path": "tests/eval.rs", "rank": 97, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_assoc() {\n\n assert_eq!(\n\n run_new(\"(cdr (assoc 'two '((one . 1) (two . 2))))\"),\n\n Ok(kint(2))\n\n );\n\n}\n", "file_path": "tests/stdlib.rs", "rank": 98, "score": 28844.08541180505 }, { "content": "#[test]\n\nfn test_list() {\n\n assert_eq!(run_new(\"(list)\"), Ok(knil()));\n\n assert_eq!(run_new(\"(list 1)\"), Ok(klist!(kint(1))));\n\n assert_eq!(run_new(\"(list 1 2)\"), Ok(klist!(kint(1), kint(2))));\n\n}\n\n\n", "file_path": "tests/stdlib.rs", "rank": 99, "score": 28844.08541180505 } ]
Rust
sleighcraft/build.rs
ioo0s/sleighcraft
ad8024574d83ee109c1172b021f4a7438b95b1a1
use filetime::FileTime; use std::env; use std::fs; use std::path::{Path, PathBuf}; const DECOMPILER_SOURCE_BASE_CXX: &[&str] = &[ "space.cc", "float.cc", "address.cc", "pcoderaw.cc", "translate.cc", "opcodes.cc", "globalcontext.cc", "capability.cc", "architecture.cc", "options.cc", "graph.cc", "cover.cc", "block.cc", "cast.cc", "typeop.cc", "database.cc", "cpool.cc", "comment.cc", "fspec.cc", "action.cc", "loadimage.cc", "varnode.cc", "op.cc", "type.cc", "variable.cc", "varmap.cc", "jumptable.cc", "emulate.cc", "emulateutil.cc", "flow.cc", "userop.cc", "funcdata.cc", "funcdata_block.cc", "funcdata_varnode.cc", "funcdata_op.cc", "pcodeinject.cc", "heritage.cc", "prefersplit.cc", "rangeutil.cc", "ruleaction.cc", "subflow.cc", "blockaction.cc", "merge.cc", "double.cc", "coreaction.cc", "condexe.cc", "override.cc", "dynamic.cc", "crc32.cc", "prettyprint.cc", "printlanguage.cc", "printc.cc", "printjava.cc", "memstate.cc", "opbehavior.cc", "paramid.cc", "transform.cc", "stringmanage.cc", "string_ghidra.cc", "ghidra_arch.cc", "typegrp_ghidra.cc", "cpool_ghidra.cc", "loadimage_ghidra.cc", "inject_ghidra.cc", "database_ghidra.cc", "inject_sleigh.cc", "ghidra_translate.cc", "ghidra_context.cc", "comment_ghidra.cc", "sleigh_arch.cc", "sleigh.cc", "filemanage.cc", "semantics.cc", "slghsymbol.cc", "context.cc", "sleighbase.cc", "slghpatexpress.cc", "slghpattern.cc", "pcodecompile.cc", ]; /* const DECOMPILER_SOURCE_BASE_YACC: [&'static str; 1] = [ "xml.y" ]; const SLEIGH_COMPILER_SOURCE_CXX: [&'static str; 1] = [ "slghparse.y" ]; const SLEIGH_COMPILER_SOURCE_FLEX: [&'static str; 1] = [ "slghscan.l" ]; */ const DECOMPILER_SOURCE_SLEIGH_YACC: &[&str] = &["pcodeparse.y", "grammar.y", "xml.y"]; const PROXIES: &[&str] = &[ "address_proxy.cc", "addrspace_proxy.cc", "cover_proxy.cc", "funcdata_proxy.cc", "loadimage_proxy.cc", "opbehavior_proxy.cc", "opcode_proxy.cc", "opcodes_proxy.cc", "typeop_proxy.cc", "block_proxy.cc", "varnode_proxy.cc", "varnodedata_proxy.cc", "variable_proxy.cc", ]; struct CompileOptions { sources: Vec<PathBuf>, objects: Vec<PathBuf>, } fn need_recompile(source: &Path) -> bool { let outdir = env::var("OUT_DIR").unwrap(); let path = Path::new(&outdir).join(source); let mut path = path; path.set_extension("o"); let metadata = match fs::metadata(path) { Ok(m) => m, Err(_) => return true, }; let object_mtime = FileTime::from_last_modification_time(&metadata); let metadata = fs::metadata(source).unwrap_or_else(|_| panic!("source code {:?} not found", source)); let source_mtime = FileTime::from_last_modification_time(&metadata); source_mtime > object_mtime } fn obj_path_from_src_path(src_path: &Path) -> PathBuf { let outdir = env::var("OUT_DIR").unwrap(); let mut path = Path::new(&outdir).join(src_path); path.set_extension("o"); path } fn prepare() -> CompileOptions { let mut objects = vec![]; let mut sources = vec![]; for src in DECOMPILER_SOURCE_BASE_CXX.iter() { let path = Path::new("src").join("cpp").join(src); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } for src in DECOMPILER_SOURCE_SLEIGH_YACC.iter() { let name = src.split('.').next().unwrap(); let path = Path::new("src") .join("cpp") .join("gen") .join("bison") .join(&format!("{}.cpp", name)); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } for src in PROXIES.iter() { let path = Path::new("src") .join("cpp") .join("bridge") .join("proxies") .join(src); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } CompileOptions { sources, objects } } fn main() { let compile_opts = prepare(); let sleigh_src_file = Path::new("src").join("sleigh.rs"); let mut target = cxx_build::bridge(sleigh_src_file); for obj in &compile_opts.objects { target.object(obj); } let disasm_src_path= Path::new("src").join("cpp").join("bridge").join("disasm.cpp"); let src_cpp = Path::new("src").join("cpp"); let src_cpp_gen_bison = Path::new("src").join("cpp").join("gen").join("bison"); let src_cpp_gen_flex = Path::new("src").join("cpp").join("gen").join("flex"); #[cfg(target_os = "windows")] { target.define("_WINDOWS", "1"); } target .cpp(true) .warnings(false) .file(disasm_src_path) .files(compile_opts.sources) .flag_if_supported("-std=c++14") .include(src_cpp) .include(src_cpp_gen_bison) .include(src_cpp_gen_flex) .compile("sleigh"); }
use filetime::FileTime; use std::env; use std::fs; use std::path::{Path, PathBuf}; const DECOMPILER_SOURCE_BASE_CXX: &[&str] = &[ "space.cc", "float.cc", "address.cc", "pcoderaw.cc", "translate.cc", "opcodes.cc", "globalcontext.cc", "capability.cc", "architecture.cc", "options.cc", "graph.cc", "cover.cc", "block.cc", "cast.cc", "typeop.cc", "database.cc", "cpool.cc", "comment.cc", "fspec.cc", "action.cc", "loadimage.cc", "varnode.cc", "op.cc", "type.cc", "variable.cc", "varmap.cc", "jumptable.cc", "emulate.cc", "emulateutil.cc", "flow.cc", "userop.cc", "funcdata.cc", "funcdata_block.cc", "funcdata_varnode.cc", "funcdata_op.cc", "pcodeinject.cc", "heritage.cc", "prefersplit.cc", "rangeutil.cc", "ruleaction.cc", "subflow.cc", "blockaction.cc", "merge.cc", "double.cc", "coreaction.cc", "condexe.cc", "override.cc", "dynamic.cc", "crc32.cc", "prettyprint.cc", "printlanguage.cc", "printc.cc", "printjava.cc", "memstate.cc", "opbehavior.cc", "paramid.cc", "transform.cc", "stringmanage.cc", "string_ghidra.cc", "ghidra_arch.cc", "typegrp_ghidra.cc", "cpool_ghidra.cc", "loadimage_ghidra.cc", "inject_ghidra.cc", "database_ghidra.cc", "inject_sleigh.cc", "ghidra_translate.cc", "ghidra_context.cc", "comment_ghidra.cc", "sleigh_arch.cc", "sleigh.cc", "filemanage.cc", "semantics.cc", "slghsymbol.cc", "context.cc", "sleighbase.cc", "slghpatexpress.cc", "slghpattern.cc", "pcodecompile.cc", ]; /* const DECOMPILER_SOURCE_BASE_YACC: [&'static str; 1] = [ "xml.y" ]; const SLEIGH_COMPILER_SOURCE_CXX: [&'static str; 1] = [ "slghparse.y" ]; const SLEIGH_COMPILER_SOURCE_FLEX: [&'static str; 1] = [ "slghscan.l" ]; */ const DECOMPILER_SOURCE_SLEIGH_YACC: &[&str] = &["pcodeparse.y", "grammar.y", "xml.y"]; const PROXIES: &[&str] = &[ "address_proxy.cc", "addrspace_proxy.cc", "cover_proxy.cc", "funcdata_proxy.cc", "loadimage_proxy.cc", "opbehavior_proxy.cc", "opcode_proxy.cc", "opcodes_proxy.cc", "typeop_proxy.cc", "block_proxy.cc", "varnode_proxy.cc", "varnodedata_proxy.cc", "variable_proxy.cc", ]; struct CompileOptions { sources: Vec<PathBuf>, objects: Vec<PathBuf>, } fn need_recompile(source: &Path) -> bool { let outdir = env::var("OUT_DIR").unwrap(); let path = Path::new(&outdir).join(source); let mut path = path; path.set_extension("o"); let metadata = match fs::metadata(path) { Ok(m) => m, Err(_) => return true, }; let object_mtime = FileTime::from_last_modification_time(&metadata); let metadata = fs::metadata(source).unwrap_or_else(|_| panic!("source code {:?} not found", source)); let source_mtime = FileTime::from_last_modification_time(&metadata); source_mtime > object_mtime } fn obj_path_from_src_path(src_path: &Path) -> PathBuf { let outdir = env::var("OUT_DIR").unwrap(); let mut p
.warnings(false) .file(disasm_src_path) .files(compile_opts.sources) .flag_if_supported("-std=c++14") .include(src_cpp) .include(src_cpp_gen_bison) .include(src_cpp_gen_flex) .compile("sleigh"); }
ath = Path::new(&outdir).join(src_path); path.set_extension("o"); path } fn prepare() -> CompileOptions { let mut objects = vec![]; let mut sources = vec![]; for src in DECOMPILER_SOURCE_BASE_CXX.iter() { let path = Path::new("src").join("cpp").join(src); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } for src in DECOMPILER_SOURCE_SLEIGH_YACC.iter() { let name = src.split('.').next().unwrap(); let path = Path::new("src") .join("cpp") .join("gen") .join("bison") .join(&format!("{}.cpp", name)); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } for src in PROXIES.iter() { let path = Path::new("src") .join("cpp") .join("bridge") .join("proxies") .join(src); if need_recompile(&path) { sources.push(path); } else { objects.push(obj_path_from_src_path(&path)); } } CompileOptions { sources, objects } } fn main() { let compile_opts = prepare(); let sleigh_src_file = Path::new("src").join("sleigh.rs"); let mut target = cxx_build::bridge(sleigh_src_file); for obj in &compile_opts.objects { target.object(obj); } let disasm_src_path= Path::new("src").join("cpp").join("bridge").join("disasm.cpp"); let src_cpp = Path::new("src").join("cpp"); let src_cpp_gen_bison = Path::new("src").join("cpp").join("gen").join("bison"); let src_cpp_gen_flex = Path::new("src").join("cpp").join("gen").join("flex"); #[cfg(target_os = "windows")] { target.define("_WINDOWS", "1"); } target .cpp(true)
random
[ { "content": "fn load_preset() -> HashMap<&'static str, &'static str> {\n\n let mut map = HashMap::new();\n\n macro_rules! def_arch {\n\n ($name: expr) => {\n\n // presets are used across the whole lifetime, it's safe to ignore\n\n // the lifetime by leaking its names' memory\n\n let name: &'static str = Box::leak($name.to_lowercase().into_boxed_str());\n\n map.insert(name, include_str!(concat!(\"sla/\", $name, \".sla\")));\n\n };\n\n }\n\n def_arch!(\"6502\");\n\n def_arch!(\"6805\");\n\n def_arch!(\"6809\");\n\n def_arch!(\"8048\");\n\n def_arch!(\"8051\");\n\n def_arch!(\"8085\");\n\n def_arch!(\"68020\");\n\n def_arch!(\"68030\");\n\n def_arch!(\"68040\");\n\n def_arch!(\"80251\");\n", "file_path": "sleighcraft/src/sleigh.rs", "rank": 1, "score": 297186.5008966583 }, { "content": "pub fn arch(name: &str) -> Result<&str> {\n\n let content = *PRESET\n\n .get(&name.to_lowercase().as_str())\n\n .ok_or(Error::ArchNotFound(name.to_string()))?;\n\n Ok(content)\n\n}\n", "file_path": "sleighcraft/src/sleigh.rs", "rank": 3, "score": 193269.87689214537 }, { "content": " -# Each p-code \\b RETURN instruction for the current\n\n function is adjusted to hide the use of the return\n\n address and to add an input location for the return\n\n value. The return value is considered an input to\n\n the \\b RETURN instruction.\n\n\n\n \\subsection step5 The Main Simplification Loop\n\n\n\n \\subsubsection step5a Generate SSA Form\n\n\n\n This is very similar to forward engineering\n\n algorithms. It uses a fairly standard phi-node\n\n placement algorithm based on the control flow dominator\n\n tree and the so-called dominance frontier. A standard\n\n renaming algorithm is used for the final linking of\n\n variable defs and uses. The decompiler has to take\n\n into account partially overlapping variables and guard\n\n against various aliasing situations, which are\n\n generally more explicit to a compiler. The decompiler\n\n SSA algorithm also works incrementally. Many of the\n\n stack references in a function cannot be fully resolved\n", "file_path": "sleighcraft/src/cpp/docmain.hh", "rank": 4, "score": 158919.62040341712 }, { "content": "struct InstructionProxy {\n\n string space;\n\n uint64_t offset;\n\n string mnemonic;\n\n string body;\n\n// Instruction& instruction;\n\n// InstructionProxy(Instruction& instruction): instruction(instruction) {}\n\n\n\n const string& get_space() const {\n\n return space;\n\n }\n\n\n\n uint64_t get_offset() const {\n\n return offset;\n\n }\n\n\n\n const string& get_mnemonic() const {\n\n return mnemonic;\n\n }\n\n\n\n const string& get_body() const {\n\n return body;\n\n }\n\n};\n\n\n\n\n", "file_path": "sleighcraft/src/cpp/bridge/disasm.h", "rank": 5, "score": 157723.22887963665 }, { "content": "#include \"op.hh\"\n\n#include \"varnode_proxy.hh\"\n\n#include \"address_proxy.hh\"\n\n#include \"typeop_proxy.hh\"\n\nclass OpCodeProxy {\n\npublic:\n\n PcodeOp& opcode;\n\n OpCodeProxy(PcodeOp& opcode): opcode(opcode) {};\n\n OpCodeProxy(PcodeOp* opcode): opcode(*opcode) {};\n\n\n\n int4 count(void) const;\n\n unique_ptr<VarnodeProxy> get_out(void) const;\n\n unique_ptr<VarnodeProxy> get_in(int4 slot) const;\n\n // const unique_ptr<AddressProxy> get_addr(void) const;\n\n uintm get_time(void) const ;\n\n uint4 get_eval_type(void) const;\n\n uint4 get_halt_type(void) const;\n\n\n\n bool is_dead(void) const;\n\n bool is_assignment(void) const;\n\n bool is_call(void) const;\n\n bool is_call_without_spec(void) const;\n\n bool is_marker(void) const;\n\n bool is_indirect_creation(void) const;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies/opcode_proxy.hh", "rank": 6, "score": 123291.33282915328 }, { "content": "class OpCodesProxy {\n\npublic:\n\n const char* getOpname(OpCodes opc);\n\n OpCodes getOpcode(const string &nm);\n\n OpCodes getBooleanflip(OpCodes opc,bool &reorder);\n\n\n\n // TODO: implemented the methods\n\n};\n\n\n\n*/\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/opcodes_proxy.hh", "rank": 7, "score": 123283.45527215517 }, { "content": "class OpCodeProxy;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies.h", "rank": 8, "score": 123213.20514754055 }, { "content": "class OpCodeProxy;\n", "file_path": "sleighcraft/src/cpp/bridge/disasm.h", "rank": 9, "score": 109531.64117148935 }, { "content": "class SectionSymbol : public SleighSymbol { // Named p-code sections\n\n int4 templateid;\t\t// Index into the ConstructTpl array\n\n int4 define_count;\t\t// Number of definitions of this named section\n\n int4 ref_count;\t\t// Number of references to this named section\n\npublic:\n\n SectionSymbol(const string &nm,int4 id) : SleighSymbol(nm) { templateid=id; define_count=0; ref_count=0; }\n\n int4 getTemplateId(void) const { return templateid; }\n\n void incrementDefineCount(void) { define_count += 1; }\n\n void incrementRefCount(void) { ref_count += 1; }\n\n int4 getDefineCount(void) const { return define_count; }\n\n int4 getRefCount(void) const { return ref_count; }\n\n virtual symbol_type getType(void) const { return section_symbol; }\n\n // Not saved or restored\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slghsymbol.hh", "rank": 10, "score": 107038.84138509407 }, { "content": "fn main() {\n\n neon_build::setup();\n\n}\n", "file_path": "bindings/nodejs/native/build.rs", "rank": 13, "score": 103339.15913772941 }, { "content": "#[test]\n\nfn test_x86() {\n\n let mut sleigh_builder = SleighBuilder::default();\n\n let spec = arch(\"x86\").unwrap();\n\n let buf = [0x90, 0x32, 0x31];\n\n let mut loader = PlainLoadImage::from_buf(&buf, 0);\n\n sleigh_builder.loader(&mut loader);\n\n sleigh_builder.spec(spec);\n\n let mut asm_emit = CollectingAssemblyEmit::default();\n\n let mut pcode_emit = CollectingPcodeEmit::default();\n\n sleigh_builder.asm_emit(&mut asm_emit);\n\n sleigh_builder.pcode_emit(&mut pcode_emit);\n\n let mut sleigh = sleigh_builder.try_build().unwrap();\n\n\n\n sleigh.decode(0).unwrap();\n\n\n\n println!(\"{:?}\", asm_emit.asms);\n\n println!(\"{:?}\", pcode_emit.pcode_asms);\n\n}\n\n\n", "file_path": "sleighcraft/tests/mod.rs", "rank": 14, "score": 103339.15913772941 }, { "content": "struct Enumerator {\n\n string enumconstant;\t\t// Identifier associated with constant\n\n bool constantassigned;\t// True if user specified explicit constant\n\n uintb value;\t\t\t// The actual constant\n\n Enumerator(const string &nm) { constantassigned = false; enumconstant = nm; }\n\n Enumerator(const string &nm,uintb val) { constantassigned = true; enumconstant=nm; value=val; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/grammar.hh", "rank": 15, "score": 103053.40374750584 }, { "content": "enum class PcodeOpCode: std::uint8_t;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies.h", "rank": 16, "score": 102051.58895644046 }, { "content": "/// \\brief Simple unit test class\n\n///\n\n/// The macro TEST instantiates this object with a name and function pointer.\n\n/// The static run() method calls all the function pointers of all instantiated\n\n/// objects.\n\nstruct UnitTest {\n\n static std::vector<UnitTest *> tests;\t\t///< The collection of test objects\n\n std::string name;\t\t\t\t///< Name of the test\n\n testfunc_t func;\t\t\t\t///< Call-back function executing the test\n\n\n\n /// \\brief Constructor\n\n ///\n\n /// \\param name is the identifier for the test\n\n /// \\param func is a call-back function that executes the test\n\n UnitTest(const std::string &name,testfunc_t func) :\n\n name(name), func(func)\n\n {\n\n tests.push_back(this);\n\n }\n\n\n\n static void run(std::set<std::string> &testNames);\t///< Run all the instantiated tests\n\n};\n\n\n\n\n\n/// \\brief Main unit test macro\n", "file_path": "sleighcraft/src/cpp/test.hh", "rank": 17, "score": 101624.93164107145 }, { "content": "/// \\brief Raw components of a function prototype (obtained from parsing source code)\n\nstruct PrototypePieces {\n\n ProtoModel *model;\t\t///< (Optional) model on which prototype is based\n\n string name;\t\t\t///< Identifier (function name) associated with prototype\n\n Datatype *outtype;\t\t///< Return data-type\n\n vector<Datatype *> intypes;\t///< Input data-types\n\n vector<string> innames;\t///< Identifiers for input types\n\n bool dotdotdot;\t\t///< True if prototype takes variable arguments\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/fspec.hh", "rank": 18, "score": 101624.50482545633 }, { "content": "/// \\brief Class for describing a relative p-code branch destination\n\n///\n\n/// An intra-instruction p-code branch takes a \\e relative operand.\n\n/// The actual value produced during p-code generation is calculated at\n\n/// the last second using \\b this. It stores the index of the BRANCH\n\n/// instruction and a reference to its destination operand. This initially\n\n/// holds a reference to a destination \\e label symbol, but is later updated\n\n/// with the final relative value.\n\nstruct RelativeRecord {\n\n VarnodeData *dataptr;\t\t///< Varnode indicating relative offset\n\n uintb calling_index;\t\t///< Index of instruction containing relative offset\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/sleigh.hh", "rank": 19, "score": 101624.09467166048 }, { "content": "/// \\brief Data for building one p-code instruction\n\n///\n\n/// Raw data used by the emitter to produce a single PcodeOp\n\nstruct PcodeData {\n\n OpCode opc;\t\t\t///< The op code\n\n VarnodeData *outvar;\t \t///< Output Varnode data (or null)\n\n VarnodeData *invar;\t\t///< Array of input Varnode data\n\n int4 isize;\t\t\t///< Number of input Varnodes\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/sleigh.hh", "rank": 20, "score": 101623.99756852756 }, { "content": "/// \\brief A tracked register (Varnode) and the value it contains\n\n///\n\n/// This is the object returned when querying for tracked registers,\n\n/// via ContextDatabase::getTrackedSet(). It holds the storage details of the register and\n\n/// the actual value it holds at the point of the query.\n\nstruct TrackedContext {\n\n VarnodeData loc;\t///< Storage details of the register being tracked\n\n uintb val;\t\t///< The value of the register\n\n void restoreXml(const Element *el,const AddrSpaceManager *manage);\t///< Restore \\b this from an XML stream\n\n void saveXml(ostream &s) const;\t\t\t\t\t///< Save \\b this to an XML stream\n\n};\n\ntypedef vector<TrackedContext> TrackedSet;\t\t///< A set of tracked registers and their values (at one code point)\n\n\n", "file_path": "sleighcraft/src/cpp/globalcontext.hh", "rank": 21, "score": 101623.30285443724 }, { "content": "/// \\brief A simple node used to dynamically define a sequence of operations\n\n///\n\n/// This should be deprecated in favor of ExecutablePcode objects. This\n\n/// class holds a single operation (within a sequence). It acts on the output\n\n/// of the previous operation with an optional constant value as the second input.\n\nstruct OpFollow {\n\n OpCode opc;\t\t\t///< The particular p-code operation\n\n uintb val;\t\t\t///< A possible constant second input\n\n int4 slot;\t\t\t///< Slot to follow\n\n OpFollow(void) {}\t\t///< Construct an empty object\n\n void restoreXml(const Element *el);\t///< Restore \\b this node from an XML stream\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/userop.hh", "rank": 22, "score": 101623.10315359732 }, { "content": "/// \\brief A control-flow edge between blocks (FlowBlock)\n\n///\n\n/// The edge is owned by the source block and can have FlowBlock::edge_flags\n\n/// labels applied to it. The \\b point indicates the FlowBlock at the other end\n\n/// from the source block. NOTE: The control-flow direction of the edge can\n\n/// only be determined from context, whether the edge is in the incoming or outgoing edge list.\n\nstruct BlockEdge {\n\n uint4 label;\t\t\t///< Label of the edge\n\n FlowBlock *point;\t\t///< Other end of the edge\n\n int4 reverse_index;\t\t///< Index for edge coming other way\n\n BlockEdge(void) {}\t\t///< Constructor for use with restoreXml\n\n BlockEdge(FlowBlock *pt,uint4 lab,int4 rev) { label=lab; point=pt; reverse_index = rev; }\t///< Constructor\n\n void saveXml(ostream &s) const;\t///< Save the edge to an XML stream\n\n void restoreXml(const Element *el,BlockMap &resolver);\t///< Restore \\b this edge from an XML stream\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/block.hh", "rank": 23, "score": 101618.39055125276 }, { "content": "/// \\brief An exception thrown by the XML parser\n\n///\n\n/// This object holds the error message as passed to the SAX interface callback\n\n/// and is thrown as a formal exception.\n\nstruct XmlError {\n\n string explain;\t\t///< Explanatory string\n\n XmlError(const string &s) { explain = s; }\t///< Constructor\n\n};\n\n\n\n/// \\brief Start-up the XML parser given a stream and a handler\n\n///\n\n/// This runs the low-level XML parser.\n\n/// \\param i is the given stream to get character data from\n\n/// \\param hand is the ContentHandler that stores or processes the XML content events\n\n/// \\param dbg is non-zero if the parser should output debug information during its parse\n\n/// \\return 0 if there is no error during parsing or a (non-zero) error condition\n\nextern int4 xml_parse(istream &i,ContentHandler *hand,int4 dbg=0);\n\n\n\n/// \\brief Parse the given XML stream into an in-memory document\n\n///\n\n/// The stream is parsed using the standard ContentHandler for producing an in-memory\n\n/// DOM representation of the XML document.\n\n/// \\param i is the given stream\n\n/// \\return the in-memory XML document\n", "file_path": "sleighcraft/src/cpp/xml.hh", "rank": 24, "score": 101617.84103847158 }, { "content": "/// \\brief Label for describing extent of address range that has been heritaged\n\nstruct SizePass {\n\n int4 size;\t\t\t///< Size of the range (in bytes)\n\n int4 pass;\t\t\t///< Pass when the range was heritaged\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/heritage.hh", "rank": 25, "score": 101611.60766396255 }, { "content": "/// \\brief A parsed name/value pair\n\nstruct NameValue {\n\n string *name;\t\t///< The name\n\n string *value;\t///< The value\n\n};\n\n\n\nextern int yylex(void);\t\t\t\t\t\t\t///< Interface to the scanner\n\nextern int yyerror(const char *str);\t\t\t///< Interface for registering an error in parsing\n\nextern void print_content(const string &str);\t///< Send character data to the ContentHandler\n\nextern int4 convertEntityRef(const string &ref);\t///< Convert an XML entity to its equivalent character\n\nextern int4 convertCharRef(const string &ref);\t///< Convert an XML character reference to its equivalent character\n\nstatic XmlScan *global_scan;\t\t\t\t\t///< Global reference to the scanner\n\nstatic ContentHandler *handler;\t\t\t\t\t///< Global reference to the content handler\n\nextern int yydebug;\t\t\t\t\t\t\t\t///< Debug mode\n\n\n\n#line 177 \"src/decompile/cpp/xml.cc\" /* yacc.c:339 */\n\n\n\n# ifndef YY_NULLPTR\n\n# if defined __cplusplus && 201103L <= __cplusplus\n\n# define YY_NULLPTR nullptr\n\n# else\n", "file_path": "sleighcraft/src/cpp/xml.cc", "rank": 26, "score": 101611.60766396255 }, { "content": "/// \\brief The lowest level error generated by the decompiler\n\n///\n\n/// This is the base error for all exceptions thrown by the\n\n/// decompiler. This underived form is thrown for very low\n\n/// level errors that immediately abort decompilation (usually\n\n/// for just a single function).\n\nstruct LowlevelError {\n\n string explain;\t\t///< Explanatory string\n\n /// Initialize the error with an explanatory string\n\n LowlevelError(const string &s) { explain = s; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/error.hh", "rank": 27, "score": 101611.60766396255 }, { "content": "struct DatatypeCompare;\n\n\n", "file_path": "sleighcraft/src/cpp/type.hh", "rank": 28, "score": 101611.60766396255 }, { "content": "struct OperandResolve {\n\n vector<OperandSymbol *> &operands;\n\n OperandResolve(vector<OperandSymbol *> &ops) : operands(ops) {\n\n base=-1; offset=0; cur_rightmost = -1; size = 0; }\n\n int4 base;\t\t// Current base operand (as we traverse the pattern equation from left to right)\n\n int4 offset;\t\t// Bytes we have traversed from the LEFT edge of the current base\n\n int4 cur_rightmost;\t// (resulting) rightmost operand in our pattern\n\n int4 size;\t\t// (resulting) bytes traversed from the LEFT edge of the rightmost\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slghpatexpress.hh", "rank": 29, "score": 101611.60766396255 }, { "content": "struct DisassemblyResult {\n\n bool success;\n\n int4 length;\n\n uint4 flags;\n\n Address jumpaddress;\n\n uintb targethit;\n\n};\n\n\n\n\n", "file_path": "sleighcraft/src/cpp/codedata.hh", "rank": 30, "score": 101611.60766396255 }, { "content": "struct TargetFeature {\n\n string name;\t\t\t// Name of the target function\n\n uint4 featuremask;\t\t// id of this target for ORing into a mask\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/codedata.hh", "rank": 31, "score": 101611.60766396255 }, { "content": "/// \\brief Compare two Comment pointers\n\n///\n\n/// Comments are ordered first by function, then address,\n\n/// then the sub-sort index.\n\nstruct CommentOrder {\n\n bool operator()(const Comment *a,const Comment *b) const;\t///< Comparison operator\n\n};\n\n\n\ntypedef set<Comment *,CommentOrder> CommentSet;\t\t///< A set of comments sorted by function and address\n\n\n", "file_path": "sleighcraft/src/cpp/comment.hh", "rank": 32, "score": 101611.60766396255 }, { "content": "struct IdentRec {\n\n const char *nm;\n\n int4 id;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/pcodeparse.hh", "rank": 33, "score": 101611.60766396255 }, { "content": "struct VarnodeData;\n", "file_path": "sleighcraft/src/cpp/space.hh", "rank": 34, "score": 101611.60766396255 }, { "content": "struct SymbolCompare {\n\n bool operator()(const SleighSymbol *a,const SleighSymbol *b) const {\n\n return (a->getName() < b->getName()); }\n\n};\n\n\n\ntypedef set<SleighSymbol *,SymbolCompare> SymbolTree;\n", "file_path": "sleighcraft/src/cpp/slghsymbol.hh", "rank": 35, "score": 101611.60766396255 }, { "content": "struct LeafIterator {\n\n CallGraphNode *node;\n\n int4 outslot;\n\n LeafIterator(CallGraphNode *n) { node=n; outslot = 0; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/callgraph.hh", "rank": 36, "score": 101611.60766396255 }, { "content": "struct AddrLink {\n\n Address a;\n\n Address b;\n\n AddrLink(Address i) { a = i; b=Address(); }\n\n AddrLink(Address i,Address j) { a=i; b=j; }\n\n bool operator<(const AddrLink &op2) const {\n\n if (a != op2.a) return (a < op2.a);\n\n return (b < op2.b);\n\n }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/codedata.hh", "rank": 37, "score": 101611.60766396255 }, { "content": "/// Compare two Datatype pointers for equivalence of their description\n\nstruct DatatypeCompare {\n\n /// Comparison operator\n\n bool operator()(const Datatype *a,const Datatype *b) const {\n\n int4 res = a->compareDependency(*b);\n\n if (res != 0) return (res<0);\n\n return a->getId() < b->getId(); }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/type.hh", "rank": 38, "score": 101611.60766396255 }, { "content": "/// \\brief Basic elements of a parameter: address, data-type, properties\n\nstruct ParameterPieces {\n\n enum {\n\n isthis = 1,\t\t///< Parameter is \"this\" pointer\n\n hiddenretparm = 2,\t///< Parameter is hidden pointer to return value, mirrors Varnode::hiddenretparm\n\n indirectstorage = 4,\t///< Parameter is indirect pointer to true parameter, mirrors Varnode::indirectstorage\n\n namelock = 8,\t///< Parameter's name is locked, mirrors Varnode::namelock\n\n typelock = 16,\t///< Parameter's data-type is locked, mirrors Varnode::typelock\n\n sizelock = 32\t///< Size of the parameter is locked (but not the data-type)\n\n };\n\n Address addr;\t\t\t///< Storage address of the parameter\n\n Datatype *type;\t\t///< The datatype of the parameter\n\n uint4 flags;\t\t\t///< additional attributes of the parameter\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/fspec.hh", "rank": 39, "score": 101611.60766396255 }, { "content": "/// \\brief Data defining a specific memory location\n\n///\n\n/// Within the decompiler's model of a processor, any register,\n\n/// memory location, or other variable can always be represented\n\n/// as an address space, an offset within the space, and the\n\n/// size of the sequence of bytes. This is more commonly referred\n\n/// to as a Varnode, but this is a bare-bones container\n\n/// for the data that doesn't have the cached attributes and\n\n/// the dataflow links of the Varnode within its syntax tree.\n\nstruct VarnodeData {\n\n AddrSpace *space;\t\t///< The address space\n\n uintb offset;\t\t\t///< The offset within the space\n\n uint4 size; ///< The number of bytes in the location\n\n bool operator<(const VarnodeData &op2) const; ///< An ordering for VarnodeData\n\n bool operator==(const VarnodeData &op2) const; ///< Compare for equality\n\n bool operator!=(const VarnodeData &op2) const; ///< Compare for inequality\n\n\n\n /// Get the location of the varnode as an address\n\n Address getAddr(void) const;\n\n\n\n /// Recover this object from an XML tag\n\n void restoreXml(const Element *el,const AddrSpaceManager *manage);\n\n\n\n /// Does \\b this container another given VarnodeData\n\n bool contains(const VarnodeData &op2) const;\n\n};\n\n\n\n/// VarnodeData can be sorted in terms of the space its in\n\n/// (the space's \\e index), the offset within the space,\n", "file_path": "sleighcraft/src/cpp/pcoderaw.hh", "rank": 40, "score": 101611.60766396255 }, { "content": "/// \\brief Specifies subfields of a structure or what a pointer points to\n\nstruct TypeField {\n\n int4 offset;\t\t\t///< Offset (into containing struct) of subfield\n\n string name;\t\t\t///< Name of subfield\n\n Datatype *type;\t\t///< type of subfield\n\n bool operator<(const TypeField &op2) const { return (offset < op2.offset); }\t///< Compare based on offset\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/type.hh", "rank": 41, "score": 101611.60766396255 }, { "content": "/// \\brief An exception specific to the command line interface\n\nstruct IfaceError {\n\n string explain;\t\t///< Explanatory string\n\n IfaceError(const string &s) { explain = s; }\t///< Constructor\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/interface.hh", "rank": 42, "score": 101611.60766396255 }, { "content": "/// \\brief A stack equation\n\nstruct StackEqn {\n\n int4 var1;\t\t\t///< Variable with 1 coefficient\n\n int4 var2;\t\t\t///< Variable with -1 coefficient\n\n int4 rhs;\t\t\t///< Right hand side of the equation\n\n static bool compare(const StackEqn &a,const StackEqn &b);\t///< Order two equations\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/coreaction.cc", "rank": 43, "score": 101611.60766396255 }, { "content": "struct ConstructState {\n\n Constructor *ct;\n\n FixedHandle hand;\n\n vector<ConstructState *> resolve;\n\n ConstructState *parent;\n\n int4 length;\t\t\t// Length of this instantiation of the constructor\n\n uint4 offset;\t\t\t// Absolute offset (from start of instruction)\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/context.hh", "rank": 44, "score": 101611.60766396255 }, { "content": "struct StarQuality {\n\n ConstTpl id;\n\n uint4 size;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/pcodecompile.hh", "rank": 45, "score": 101611.60766396255 }, { "content": "struct TypeSpecifiers {\n\n Datatype *type_specifier;\n\n string function_specifier;\n\n uint4 flags;\n\n TypeSpecifiers(void) { type_specifier = (Datatype *)0; flags = 0; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/grammar.hh", "rank": 46, "score": 101611.60766396255 }, { "content": "#[test]\n\nfn test_x86_case_ignoring() {\n\n let mut sleigh_builder = SleighBuilder::default();\n\n let spec = arch(\"x86\").unwrap();\n\n let buf = [0x90, 0x32, 0x31];\n\n let mut loader = PlainLoadImage::from_buf(&buf, 0);\n\n sleigh_builder.loader(&mut loader);\n\n sleigh_builder.spec(spec);\n\n let mut asm_emit = CollectingAssemblyEmit::default();\n\n let mut pcode_emit = CollectingPcodeEmit::default();\n\n sleigh_builder.asm_emit(&mut asm_emit);\n\n sleigh_builder.pcode_emit(&mut pcode_emit);\n\n let mut sleigh = sleigh_builder.try_build().unwrap();\n\n\n\n sleigh.decode(0).unwrap();\n\n\n\n println!(\"{:?}\", asm_emit.asms);\n\n println!(\"{:?}\", pcode_emit.pcode_asms);\n\n}\n", "file_path": "sleighcraft/tests/mod.rs", "rank": 47, "score": 100523.87664680381 }, { "content": "#ifndef YY_STRUCT_YY_BUFFER_STATE\n\n#define YY_STRUCT_YY_BUFFER_STATE\n\nstruct yy_buffer_state\n\n\t{\n\n\tFILE *yy_input_file;\n\n\n\n\tchar *yy_ch_buf;\t\t/* input buffer */\n\n\tchar *yy_buf_pos;\t\t/* current position in input buffer */\n\n\n\n\t/* Size of input buffer in bytes, not including room for EOB\n\n\t * characters.\n\n\t */\n\n\tyy_size_t yy_buf_size;\n\n\n\n\t/* Number of characters read into yy_ch_buf, not including EOB\n\n\t * characters.\n\n\t */\n\n\tyy_size_t yy_n_chars;\n\n\n\n\t/* Whether we \"own\" the buffer - i.e., we know we created it,\n\n\t * and can realloc() it to grow it, and should free() it to\n\n\t * delete it.\n", "file_path": "sleighcraft/src/cpp/slghscan.cc", "rank": 48, "score": 100247.75497841736 }, { "content": "/// \\brief Comparator for JoinRecord objects\n\nstruct JoinRecordCompare {\n\n bool operator()(const JoinRecord *a,const JoinRecord *b) const {\n\n return *a < *b; }\t\t///< Compare to JoinRecords using their built-in comparison\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/translate.hh", "rank": 49, "score": 100246.96815474884 }, { "content": "/// \\brief A record indicating a function symbol\n\n///\n\n/// This is a lightweight object holding the Address and name of a function\n\nstruct LoadImageFunc {\n\n Address address;\t///< Start of function\n\n string name;\t\t///< Name of function\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/loadimage.hh", "rank": 50, "score": 100246.70304271331 }, { "content": "/// \\brief An edge in a data-flow path or graph\n\n///\n\n/// A minimal node for traversing expressions in the data-flow\n\nstruct PcodeOpNode {\n\n PcodeOp *op;\t\t///< The p-code end-point of the edge\n\n int4 slot;\t\t///< Slot indicating the input Varnode end-point of the edge\n\n PcodeOpNode(void) { op = (PcodeOp *)0; slot = 0; }\t///< Unused constructor\n\n PcodeOpNode(PcodeOp *o,int4 s) { op = o; slot = s; }\t///< Constructor\n\n};\n\n\n\n/// A map from sequence number (SeqNum) to PcodeOp\n\ntypedef map<SeqNum,PcodeOp *> PcodeOpTree;\n\n\n", "file_path": "sleighcraft/src/cpp/op.hh", "rank": 51, "score": 100246.65453942094 }, { "content": "/// \\brief A record describing a section bytes in the executable\n\n///\n\n/// A lightweight object specifying the location and size of the section and basic properties\n\nstruct LoadImageSection {\n\n /// Boolean properties a section might have\n\n enum {\n\n unalloc = 1,\t\t///< Not allocated in memory (debug info)\n\n noload = 2,\t\t\t///< uninitialized section\n\n code = 4,\t\t\t///< code only\n\n data = 8,\t\t\t///< data only\n\n readonly = 16\t\t///< read only section\n\n };\n\n Address address;\t\t///< Starting address of section\n\n uintb size;\t\t\t///< Number of bytes in section\n\n uint4 flags;\t\t\t///< Properties of the section\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/loadimage.hh", "rank": 52, "score": 100246.57819730471 }, { "content": "/// \\brief A structure for pushing nested fields to the RPN stack\n\n///\n\n/// A helper class for unraveling a nested reference to a field. It links the\n\n/// data-type, field name, field object, and token together\n\nstruct PartialSymbolEntry {\n\n const OpToken *token;\t\t///< Operator used to drill-down to the field\n\n const TypeField *field;\t///< The component object describing the field\n\n const Datatype *parent;\t///< The parent data-type owning the field\n\n string fieldname;\t\t///< The name of the field\n\n EmitXml::syntax_highlight hilite;\t///< Highlight information for the field token\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/printc.hh", "rank": 53, "score": 100246.26778160705 }, { "content": "struct FieldQuality {\n\n string name;\n\n uint4 low,high;\n\n bool signext;\n\n bool flow;\n\n bool hex;\n\n FieldQuality(string *nm,uintb *l,uintb *h);\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slgh_compile.hh", "rank": 54, "score": 100240.2642478635 }, { "content": "struct FieldContext {\n\n VarnodeSymbol *sym;\n\n FieldQuality *qual;\n\n bool operator<(const FieldContext &op2) const;\n\n FieldContext(VarnodeSymbol *s,FieldQuality *q) { sym=s; qual=q; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slgh_compile.hh", "rank": 55, "score": 100240.2642478635 }, { "content": "struct RtlPair {\n\n ConstructTpl *section;\t// A p-code section\n\n SymbolScope *scope;\t\t// and its associated symbol scope\n\n RtlPair(void) { section = (ConstructTpl *)0; scope = (SymbolScope *)0; }\n\n RtlPair(ConstructTpl *sec,SymbolScope *sc) { section = sec; scope = sc; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slgh_compile.hh", "rank": 56, "score": 100240.2642478635 }, { "content": "struct ImportRecord {\n\n string dllname;\n\n string funcname;\n\n int ordinal;\n\n Address address;\n\n Address thunkaddress;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/loadimage_bfd.hh", "rank": 57, "score": 100240.2642478635 }, { "content": "struct PreferSplitRecord {\n\n VarnodeData storage;\n\n int4 splitoffset;\t\t// Number of initial bytes (in address order) to split into first piece\n\n bool operator<(const PreferSplitRecord &op2) const;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/prefersplit.hh", "rank": 58, "score": 100240.2642478635 }, { "content": "/// Compare two Datatype pointers: first by name, then by id\n\nstruct DatatypeNameCompare {\n\n /// Comparison operator\n\n bool operator()(const Datatype *a,const Datatype *b) const {\n\n int4 res = a->getName().compare( b->getName() );\n\n if (res != 0) return (res < 0);\n\n return a->getId() < b->getId(); }\n\n};\n\n\n\n/// A set of data-types sorted by function\n\ntypedef set<Datatype *,DatatypeCompare> DatatypeSet;\n\n\n\n/// A set of data-types sorted by name\n\ntypedef set<Datatype *,DatatypeNameCompare> DatatypeNameSet;\n\n\n", "file_path": "sleighcraft/src/cpp/type.hh", "rank": 59, "score": 100240.2642478635 }, { "content": "struct FileStreamState {\n\n YY_BUFFER_STATE lastbuffer;\t// Last lex buffer corresponding to the stream\n\n FILE *file; // The NEW file stream\n\n};\n\n\n\nextern SleighCompile *slgh;\n\nint4 last_preproc; // lex state before last preprocessing erasure\n\nint4 actionon; // whether '&' '|' and '^' are treated as actionon in pattern section\n\nint4 withsection = 0; // whether we are between the 'with' keyword and its open brace '{'\n\nvector<FileStreamState> filebuffers;\n\nvector<int4> ifstack;\n\nint4 negative_if = -1;\n\n\n\nvoid preproc_error(const string &err)\n\n\n\n{\n\n slgh->reportError((const Location *)0, err);\n\n cerr << \"Terminating due to error in preprocessing\" << endl;\n\n exit(1);\n\n}\n", "file_path": "sleighcraft/src/cpp/slghscan.cc", "rank": 60, "score": 100240.2642478635 }, { "content": "struct yy_trans_info\n\n\t{\n\n\tflex_int32_t yy_verify;\n\n\tflex_int32_t yy_nxt;\n\n\t};\n\nstatic yyconst flex_int16_t yy_accept[527] =\n\n { 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 165, 14, 7, 8, 6, 14,\n\n 3, 13, 4, 13, 13, 13, 13, 5, 1, 58,\n\n 56, 57, 58, 50, 58, 25, 51, 52, 52, 26,\n\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 51,\n\n 51, 51, 51, 51, 51, 23, 22, 20, 21, 22,\n\n 17, 19, 18, 15, 68, 66, 67, 61, 68, 61,\n\n 64, 62, 64, 59, 96, 94, 95, 96, 89, 96,\n\n 85, 88, 90, 91, 91, 88, 88, 90, 83, 84,\n\n 87, 90, 90, 71, 86, 69, 161, 159, 160, 153,\n\n\n\n 154, 161, 153, 153, 155, 156, 156, 153, 153, 153,\n\n 153, 155, 155, 155, 155, 155, 155, 155, 155, 155,\n", "file_path": "sleighcraft/src/cpp/slghscan.cc", "rank": 61, "score": 100240.2642478635 }, { "content": "/// \\brief A parsed name/value pair\n\nstruct NameValue {\n\n string *name;\t\t///< The name\n\n string *value;\t///< The value\n\n};\n\n\n\nextern int yylex(void);\t\t\t\t\t\t\t///< Interface to the scanner\n\nextern int yyerror(const char *str);\t\t\t///< Interface for registering an error in parsing\n\nextern void print_content(const string &str);\t///< Send character data to the ContentHandler\n\nextern int4 convertEntityRef(const string &ref);\t///< Convert an XML entity to its equivalent character\n\nextern int4 convertCharRef(const string &ref);\t///< Convert an XML character reference to its equivalent character\n\nstatic std::mutex global_scan_mutex;\n\nstatic std::mutex handler_mutex;\n\nstatic XmlScan *global_scan;\t\t\t\t\t///< Global reference to the scanner\n\nstatic ContentHandler *handler;\t\t\t\t\t///< Global reference to the content handler\n\nextern int yydebug;\t\t\t\t\t\t\t\t///< Debug mode\n\n\n\n#line 186 \"/home/anciety/Desktop/Code/bincraft/sleighcraft/src/cpp/build/bison/xml.cpp\" /* yacc.c:337 */\n\n# ifndef YY_NULLPTR\n\n# if defined __cplusplus\n\n# if 201103L <= __cplusplus\n", "file_path": "sleighcraft/src/cpp/gen/bison/xml.cpp", "rank": 63, "score": 98934.33270399935 }, { "content": "/// \\brief Compare two Varnode pointers by location then definition\n\nstruct VarnodeCompareLocDef {\n\n bool operator()(const Varnode *a,const Varnode *b) const;\t///< Functional comparison operator\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/varnode.hh", "rank": 64, "score": 98934.33270399935 }, { "content": "/// \\brief Compare two Varnode pointers by definition then location\n\nstruct VarnodeCompareDefLoc {\n\n bool operator()(const Varnode *a,const Varnode *b) const;\t///< Functional comparison operator\n\n};\n\n\n\n/// A set of Varnodes sorted by location (then by definition)\n\ntypedef set<Varnode *,VarnodeCompareLocDef> VarnodeLocSet;\n\n\n\n/// A set of Varnodes sorted by definition (then location)\n\ntypedef set<Varnode *,VarnodeCompareDefLoc> VarnodeDefSet;\n\n\n", "file_path": "sleighcraft/src/cpp/varnode.hh", "rank": 65, "score": 98934.33270399935 }, { "content": "#ifndef YY_STRUCT_YY_BUFFER_STATE\n\n#define YY_STRUCT_YY_BUFFER_STATE\n\nstruct yy_buffer_state\n\n\t{\n\n\tFILE *yy_input_file;\n\n\n\n\tchar *yy_ch_buf;\t\t/* input buffer */\n\n\tchar *yy_buf_pos;\t\t/* current position in input buffer */\n\n\n\n\t/* Size of input buffer in bytes, not including room for EOB\n\n\t * characters.\n\n\t */\n\n\tint yy_buf_size;\n\n\n\n\t/* Number of characters read into yy_ch_buf, not including EOB\n\n\t * characters.\n\n\t */\n\n\tint yy_n_chars;\n\n\n\n\t/* Whether we \"own\" the buffer - i.e., we know we created it,\n\n\t * and can realloc() it to grow it, and should free() it to\n\n\t * delete it.\n", "file_path": "sleighcraft/src/cpp/gen/flex/slghscan.cpp", "rank": 66, "score": 97696.73264899998 }, { "content": "struct yy_trans_info\n\n\t{\n\n\tflex_int32_t yy_verify;\n\n\tflex_int32_t yy_nxt;\n\n\t};\n\nstatic const flex_int16_t yy_accept[527] =\n\n { 0,\n\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n\n 0, 0, 0, 0, 165, 14, 7, 8, 6, 14,\n\n 3, 13, 4, 13, 13, 13, 13, 5, 1, 58,\n\n 56, 57, 58, 50, 58, 25, 51, 52, 52, 26,\n\n 51, 51, 51, 51, 51, 51, 51, 51, 51, 51,\n\n 51, 51, 51, 51, 51, 23, 22, 20, 21, 22,\n\n 17, 19, 18, 15, 68, 66, 67, 61, 68, 61,\n\n 64, 62, 64, 59, 96, 94, 95, 96, 89, 96,\n\n 85, 88, 90, 91, 91, 88, 88, 90, 83, 84,\n\n 87, 90, 90, 71, 86, 69, 161, 159, 160, 153,\n\n\n\n 154, 161, 153, 153, 155, 156, 156, 153, 153, 153,\n\n 153, 155, 155, 155, 155, 155, 155, 155, 155, 155,\n", "file_path": "sleighcraft/src/cpp/gen/flex/slghscan.cpp", "rank": 67, "score": 97689.24191844612 }, { "content": "struct FileStreamState {\n\n YY_BUFFER_STATE lastbuffer;\t// Last lex buffer corresponding to the stream\n\n FILE *file; // The NEW file stream\n\n};\n\n\n\nextern SleighCompile *slgh;\n\nint4 last_preproc; // lex state before last preprocessing erasure\n\nint4 actionon; // whether '&' '|' and '^' are treated as actionon in pattern section\n\nint4 withsection = 0; // whether we are between the 'with' keyword and its open brace '{'\n\nvector<FileStreamState> filebuffers;\n\nvector<int4> ifstack;\n\nint4 negative_if = -1;\n\n\n\nvoid preproc_error(const string &err)\n\n\n\n{\n\n slgh->reportError((const Location *)0, err);\n\n cerr << \"Terminating due to error in preprocessing\" << endl;\n\n exit(1);\n\n}\n", "file_path": "sleighcraft/src/cpp/gen/flex/slghscan.cpp", "rank": 68, "score": 97689.24191844612 }, { "content": "/// \\brief Exception for encountering unimplemented pcode\n\n///\n\n/// This error is thrown when a particular machine instruction\n\n/// cannot be translated into pcode. This particular error\n\n/// means that the particular instruction being decoded was valid,\n\n/// but the system doesn't know how to represent it in pcode.\n\nstruct UnimplError : public LowlevelError {\n\n int4 instruction_length;\t///< Number of bytes in the unimplemented instruction\n\n /// \\brief Constructor\n\n ///\n\n /// \\param s is a more verbose description of the error\n\n /// \\param l is the length (in bytes) of the unimplemented instruction\n\n UnimplError(const string &s,int4 l) : LowlevelError(s) { instruction_length = l; }\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/translate.hh", "rank": 69, "score": 90403.15670648465 }, { "content": "/// \\brief A generic recoverable error\n\n///\n\n/// This error is the most basic form of recoverable error,\n\n/// meaning there is some problem that the user did not take\n\n/// into account.\n\nstruct RecovError : public LowlevelError {\n\n /// Initialize the error with an explanatory string\n\n RecovError(const string &s) : LowlevelError(s) {}\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/error.hh", "rank": 70, "score": 90403.15670648465 }, { "content": "struct SleighError : public LowlevelError {\n\n SleighError(const string &s) : LowlevelError(s) {}\n\n};\n\n\n\ninline void ParserContext::deallocateState(ParserWalkerChange &walker) {\n\n alloc = 1;\n\n walker.context=this;\n\n walker.baseState();\n\n}\n\n\n\ninline void ParserContext::allocateOperand(int4 i,ParserWalkerChange &walker) {\n\n ConstructState *opstate = &state[alloc++];\n\n opstate->parent = walker.point;\n\n opstate->ct = (Constructor *)0;\n\n walker.point->resolve[i] = opstate;\n\n walker.breadcrumb[walker.depth++] += 1;\n\n walker.point = opstate;\n\n walker.breadcrumb[walker.depth] = 0;\n\n}\n\n\n\n#endif\n", "file_path": "sleighcraft/src/cpp/context.hh", "rank": 71, "score": 90403.15670648465 }, { "content": "/// This exception is thrown when emulation evaluation of an operator fails for some reason.\n\n/// This can be thrown for either forward or reverse emulation\n\nstruct EvaluationError : public LowlevelError {\n\n EvaluationError(const string &s) : LowlevelError(s) {} ///< Initialize the error with an explanatory string\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/opbehavior.hh", "rank": 72, "score": 90403.15670648465 }, { "content": "/// \\brief Exception that mirrors exceptions thrown by the Ghidra client\n\n///\n\n/// If the Ghidra client throws an exception while trying to answer a query,\n\n/// the exception is caught and sent back to the ArchitectureGhidra object\n\n/// in a specially formatted interrupt message. The message is decoded\n\n/// into this object, which is than thrown.\n\n///\n\n/// This class also doubles as an exception generated by the decompiler\n\n/// because of message protocol \\e alignment, which should get sent back to the Ghidra client\n\nstruct JavaError : public LowlevelError {\n\n string type;\t\t\t\t///< The name of the Java exception class\n\n JavaError(const string &tp,const string &message) : LowlevelError(message) {\n\n type = tp; }\t\t\t///< Construct given a class and message\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/ghidra_arch.hh", "rank": 73, "score": 89221.44362684192 }, { "content": "/// \\brief Exception thrown for a thunk mechanism that looks like a jump-table\n\nstruct JumptableThunkError : public LowlevelError {\n\n JumptableThunkError(const string &s) : LowlevelError(s) {}\t///< Construct with an explanatory string\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/jumptable.hh", "rank": 74, "score": 89214.75178807025 }, { "content": "/// \\brief An exception describing a parsing error in a command line\n\n///\n\n/// Thrown when attempting to parse a command line. Options are missing or are in\n\n/// the wrong form etc.\n\nstruct IfaceParseError : public IfaceError {\n\n IfaceParseError(const string &s) : IfaceError(s) {}\t///< Constructor\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/interface.hh", "rank": 75, "score": 89214.75178807025 }, { "content": "/// \\brief Exception for bad instruction data\n\n///\n\n/// This error is thrown when the system cannot decode data\n\n/// for a particular instruction. This usually means that the\n\n/// data is not really a machine instruction, but may indicate\n\n/// that the system is unaware of the particular instruction.\n\nstruct BadDataError : public LowlevelError {\n\n /// \\brief Constructor\n\n ///\n\n /// \\param s is a more verbose description of the error\n\n BadDataError(const string &s) : LowlevelError(s) {}\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/translate.hh", "rank": 76, "score": 89214.75178807025 }, { "content": "/// \\brief Exception indicating data was not available\n\n///\n\n/// This exception is thrown when a request for load image\n\n/// data cannot be met, usually because the requested address\n\n/// range is not in the image.\n\nstruct DataUnavailError : public LowlevelError {\n\n DataUnavailError(const string &s) : LowlevelError(s) {} ///< Instantiate with an explanatory string\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/loadimage.hh", "rank": 77, "score": 89214.75178807025 }, { "content": "/// \\brief An exception throw during the execution of a command\n\n///\n\n/// Processing of a specific command has started but has reached an error state\n\nstruct IfaceExecutionError : public IfaceError {\n\n IfaceExecutionError(const string &s) : IfaceError(s) {}\t///< Constructor\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/interface.hh", "rank": 78, "score": 89214.75178807025 }, { "content": "/// \\brief Exception thrown is there are no legal flows to a switch\n\nstruct JumptableNotReachableError : public LowlevelError {\n\n JumptableNotReachableError(const string &s) : LowlevelError(s) {}\t///< Constructor\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/jumptable.hh", "rank": 79, "score": 89214.75178807025 }, { "content": "/// \\brief Exception thrown when a prototype can't be modeled properly\n\nstruct ParamUnassignedError : public LowlevelError {\n\n ParamUnassignedError(const string &s) : LowlevelError(s) {}\t///< Constructor\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/fspec.hh", "rank": 80, "score": 89214.75178807025 }, { "content": "/// \\brief An error generated while parsing a command or language\n\n///\n\n/// This error is generated when parsing character data of some\n\n/// form, as in a user command from the console or when parsing\n\n/// C syntax.\n\nstruct ParseError : public LowlevelError { // Parsing error\n\n /// Initialize the error with an explanatory string\n\n ParseError(const string &s) : LowlevelError(s) {}\n\n};\n\n\n\n#endif\n", "file_path": "sleighcraft/src/cpp/error.hh", "rank": 81, "score": 82805.20513178657 }, { "content": "struct SpaceQuality {\t// Qualities of an address space\n\n enum {\t\t\t// Class of space\n\n ramtype,\n\n registertype\n\n };\n\n string name;\n\n uint4 type;\n\n uint4 size;\n\n uint4 wordsize; // number of bytes in unit of the space\n\n bool isdefault;\n\n SpaceQuality(const string &nm);\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/slgh_compile.hh", "rank": 82, "score": 81814.57506539783 }, { "content": "struct FixedHandle {\t\t// A handle that is fully resolved\n\n AddrSpace *space;\n\n uint4 size;\n\n AddrSpace *offset_space;\t// Either null or where dynamic offset is stored\n\n uintb offset_offset;\t\t// Either static offset or ptr offset\n\n uint4 offset_size;\t\t// Size of pointer\n\n AddrSpace *temp_space;\t// Consistent temporary location for value\n\n uintb temp_offset;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/context.hh", "rank": 83, "score": 81134.79434870645 }, { "content": "#[pymodule]\n\nfn bincraft(_py: Python<'_>, m: &PyModule) -> PyResult<()> {\n\n m.add_class::<Sleigh>()\n\n}\n", "file_path": "bindings/python/src/lib.rs", "rank": 84, "score": 79002.74037785555 }, { "content": "struct ContextSet {\t\t// Instructions for setting a global context value\n\n TripleSymbol *sym;\t\t// Resolves to address where setting takes effect\n\n ConstructState *point;\t// Point at which context set was made\n\n int4 num;\t\t\t// Number of context word affected\n\n uintm mask;\t\t\t// Bits within word affected\n\n uintm value;\t\t\t// New setting for bits\n\n bool flow;\t\t\t// Does the new context flow from its set point\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/context.hh", "rank": 85, "score": 77156.39043257177 }, { "content": "class ConstantIsConstant : public RHSConstant { // TRUE if the varnode is constant\n\n int4 varindex;\n\npublic:\n\n ConstantIsConstant(int4 ind) { varindex = ind; }\n\n virtual RHSConstant *clone(void) { return new ConstantIsConstant(varindex); }\n\n virtual uintb getConstant(UnifyState &state) const;\n\n virtual void writeExpression(ostream &s,UnifyCPrinter &printstate) const;\n\n};\n\n\n", "file_path": "sleighcraft/src/cpp/unify.hh", "rank": 86, "score": 74792.47531804294 }, { "content": "#include \"varnode.hh\"\n\n#include \"addrspace_proxy.hh\"\n\n#include \"cover_proxy.hh\"\n\n#include \"address_proxy.hh\"\n\n#include \"variable_proxy.hh\"\n\nclass VarnodeProxy {\n\npublic:\n\n Varnode& varnode;\n\n VarnodeProxy(Varnode& varnode): varnode(varnode) {};\n\n VarnodeProxy(Varnode* varnode): varnode(*varnode) {};\n\n\n\n void set_high(const VariableProxy &tv,int2 mg) const;\n\n unique_ptr <AddressProxy> get_addr(void) const;\n\n unique_ptr<AddrSpaceProxy> get_space(void) const;\n\n uintb get_offset(void) const;\n\n int4 get_size(void) const;\n\n int2 get_merge_group(void) const;\n\n unique_ptr<CoverProxy> get_def (void) const;\n\n unique_ptr<VariableProxy> get_high (void) const;\n\n bool equals(const VarnodeProxy& op2) const;\n\n bool not_equal(const VarnodeProxy& op2) const;\n\n bool less_than(const VarnodeProxy& op2) const;\n\n // TODO: complete the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/varnode_proxy.hh", "rank": 87, "score": 73027.02704017195 }, { "content": "#include \"variable.hh\"\n\n#include \"varnode_proxy.hh\"\n\nclass VariableProxy {\n\npublic:\n\n HighVariable* highvn;\n\n\n\n VariableProxy(HighVariable* highvn): highvn(highvn) {};\n\n VariableProxy(HighVariable& highvn): highvn(&highvn) {};\n\n unique_ptr <VarnodeProxy> get_instance(int4 i) const;\n\n bool has_name(void) const;\n\n unique_ptr <VarnodeProxy> get_tied_varnode(void) const;\n\n unique_ptr <VarnodeProxy> get_input_varnode(void) const;\n\n unique_ptr <VarnodeProxy> get_type_representative(void) const;\n\n unique_ptr <VarnodeProxy> get_name_representative(void) const;\n\n\n\n // TODO: complete the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/variable_proxy.hh", "rank": 88, "score": 73025.57360913244 }, { "content": "class AddressProxy {\n\npublic:\n\n Address& addr;\n\n\n\n AddressProxy(Address &addr): addr(addr) {}\n\n AddressProxy(Address *addr): addr(*addr) {}\n\n bool is_invalid() const;\n\n int4 get_addr_size() const;\n\n bool is_big_endian() const;\n\n unique_ptr<AddrSpaceProxy> get_space() const;\n\n uintb get_offset() const;\n\n void to_physical();\n\n int8_t get_shortcut() const;\n\n bool equals(const AddressProxy& op2) const;\n\n bool not_equal(const AddressProxy& op2) const;\n\n bool less_than(const AddressProxy& op2) const;\n\n bool less_equal(const AddressProxy& op2) const;\n\n unique_ptr<AddressProxy> add(int4 off) const;\n\n unique_ptr<AddressProxy> sub(int4 off) const;\n\n bool contained_by(int4 size, const AddressProxy& op2, int4 size2) const;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies/address_proxy.hh", "rank": 89, "score": 73018.95720867308 }, { "content": "class CoverProxy {\n\npublic:\n\n PcodeOp pcodeop;\n\n\n\n CoverProxy(PcodeOp* pcodeop): pcodeop(*pcodeop) {};\n\n CoverProxy(PcodeOp& pcodeop): pcodeop(pcodeop) {};\n\n\n\n // TODO: implemented the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/cover_proxy.hh", "rank": 90, "score": 73018.95720867308 }, { "content": "#include \"printlanguage.hh\"\n\nclass BlockProxy {\n\npublic:\n\n BlockBasic& blockbasic;\n\n\n\n BlockProxy (BlockBasic& blockbasic): blockbasic(blockbasic) {};\n\n BlockProxy (BlockBasic* blockbasic): blockbasic(*blockbasic) {};\n\n\n\n // TODO: implemented the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/block_proxy.hh", "rank": 91, "score": 73018.95720867308 }, { "content": "#include \"address.hh\"\n\n#include \"addrspace_proxy.hh\"\n\nclass AddrSpaceProxy;\n\n\n", "file_path": "sleighcraft/src/cpp/bridge/proxies/address_proxy.hh", "rank": 92, "score": 72240.86058657405 }, { "content": "class OpBehaviorProxy {\n\npublic:\n\n OpBehavior& opbehavior;\n\n\n\n OpBehaviorProxy(OpBehavior& opbehavior): opbehavior(opbehavior) {};\n\n OpBehaviorProxy(OpBehavior* opbehavior): opbehavior(*opbehavior) {};\n\n\n\n PcodeOpCode get_opcode(void) const;\n\n bool is_special(void) const;\n\n bool is_unary(void) const;\n\n virtual uintb evaluate_unary(int4 sizeout,int4 sizein,uintb in1) const;\n\n virtual uintb evaluate_binary(int4 sizeout,int4 sizein,uintb in1,uintb in2) const;\n\n virtual uintb recover_input_binary(int4 slot,int4 sizeout,uintb out,int4 sizein,uintb in) const;\n\n virtual uintb recover_input_unary(int4 sizeout,uintb out,int4 sizein) const;\n\n\n\n // TODO: complete the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/opbehavior_proxy.hh", "rank": 93, "score": 72234.2441861147 }, { "content": "#include \"funcdata.hh\"\n\nclass FuncDataProxy {\n\npublic:\n\n Funcdata& funcdata;\n\n\n\n FuncDataProxy(Funcdata& funcdata): funcdata(funcdata) {};\n\n FuncDataProxy(Funcdata* funcdata): funcdata(*funcdata) {};\n\n\n\n // TODO: implemented the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/funcdata_proxy.hh", "rank": 94, "score": 72234.2441861147 }, { "content": "class VarnodeDataProxy {\n\npublic:\n\n VarnodeData& vardata;\n\n\n\n VarnodeDataProxy(VarnodeData& vardata): vardata(vardata) {};\n\n VarnodeDataProxy(VarnodeData* vardata): vardata(*vardata) {};\n\n uintb get_offset(void) const;\n\n uint4 get_size(void) const;\n\n\n\n bool not_null() const;\n\n unique_ptr <AddressProxy> get_addr(void) const;\n\n unique_ptr <AddrSpaceProxy>get_space(void) const;\n\n bool is_contains(const VarnodeDataProxy &op2) const;\n\n\n\n //TODO: implemented void restoreXml\n\n};\n\n\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/varnodedata_proxy.hh", "rank": 95, "score": 72234.2441861147 }, { "content": "class TypeOpProxy {\n\npublic:\n\n TypeOp& typeop;\n\n\n\n TypeOpProxy(TypeOp& typeop): typeop(typeop) {};\n\n TypeOpProxy(TypeOp* typeop): typeop(*typeop) {};\n\n\n\n const string& get_name(void) const;\n\n PcodeOpCode get_opcode(void) const;\n\n uint4 get_flags(void) const;\n\n unique_ptr<OpBehaviorProxy> get_behavior(void) const;\n\n bool mark_explicit_unsigned(PcodeOp *op,int4 slot) const; //PcodeOp_proxy -> cover_proxy\n\n uintb evaluate_unary(int4 sizeout,int4 sizein,uintb in1) const;\n\n uintb evaluate_binary(int4 sizeout,int4 sizein,uintb in1,uintb in2) const;\n\n uintb recover_input_binary(int4 slot,int4 sizeout,uintb out,int4 sizein,uintb in) const;\n\n uintb recover_input_unary(int4 sizeout,uintb out,int4 sizein) const;\n\n bool is_commutative(void) const;\n\n bool inherits_sign(void) const;\n\n // virtual string get_operator_name(const PcodeOp *op) const;\n\n\n\n // TODO: complete the methods\n\n};\n\n\n\n#endif", "file_path": "sleighcraft/src/cpp/bridge/proxies/typeop_proxy.hh", "rank": 96, "score": 72234.2441861147 }, { "content": "class AddrSpaceProxy {\n\npublic:\n\n AddrSpace& space;\n\n\n\n AddrSpaceProxy(AddrSpace* space): space(*space) {}\n\n AddrSpaceProxy(AddrSpace& space): space(space) {}\n\n\n\n const string& get_name(void) const;\n\n SpaceType get_type(void) const;\n\n int4 get_delay(void) const;\n\n int4 get_deadcode_delay(void) const;\n\n int4 get_index(void) const;\n\n uint4 get_wordsize(void) const;\n\n uint4 get_addrsize(void) const;\n\n uintb get_highest(void) const;\n\n uintb get_pointer_lower_bound(void) const;\n\n uintb get_pointer_upper_bound(void) const;\n\n int4 get_minimum_ptr_size(void) const;\n\n uintb wrap_offset(uintb off) const;\n\n int8_t get_shortcut(void) const;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies/addrspace_proxy.hh", "rank": 97, "score": 72234.2441861147 }, { "content": "class CoverProxy;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies.h", "rank": 98, "score": 69483.21554751847 }, { "content": "class AddressProxy;\n", "file_path": "sleighcraft/src/cpp/bridge/proxies.h", "rank": 99, "score": 69483.21554751847 } ]
Rust
tests/integration_test.rs
danieldulaney/rusync
992bb083699da5cec2e547044e49675677058ab9
extern crate filetime; extern crate tempdir; extern crate rusync; use std::fs; use std::fs::File; use std::io; use std::os::unix; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::path::PathBuf; use std::process::Command; use filetime::FileTime; use tempdir::TempDir; use rusync::progress::ProgressInfo; fn assert_same_contents(a: &Path, b: &Path) { assert!(a.exists(), "{:?} does not exist", a); assert!(b.exists(), "{:?} does not exist", b); let status = Command::new("diff") .args(&[a, b]) .status() .expect("Failed to execute process"); assert!(status.success(), "{:?} and {:?} differ", a, b) } fn is_executable(path: &Path) -> bool { let metadata = std::fs::metadata(&path).expect(&format!("Could not get metadata of {:?}", path)); let permissions = metadata.permissions(); let mode = permissions.mode(); mode & 0o111 != 0 } fn assert_executable(path: &Path) { assert!( is_executable(&path), "{:?} does not appear to be executable", path ); } fn assert_not_executable(path: &Path) { assert!(!is_executable(&path), "{:?} appears to be executable", path); } fn setup_test(tmp_path: &Path) -> (PathBuf, PathBuf) { let src_path = tmp_path.join("src"); let dest_path = tmp_path.join("dest"); let status = Command::new("cp") .args(&["-R", "tests/data", &src_path.to_string_lossy()]) .status() .expect("Failed to execute process"); assert!(status.success()); (src_path, dest_path) } fn make_recent(path: &Path) -> io::Result<()> { let metadata = fs::metadata(&path)?; let atime = FileTime::from_last_access_time(&metadata); let mtime = FileTime::from_last_modification_time(&metadata); let mut epoch = mtime.seconds_relative_to_1970(); epoch += 1; let mtime = FileTime::from_seconds_since_1970(epoch, 0); filetime::set_file_times(&path, atime, mtime)?; Ok(()) } struct DummyProgressInfo {} impl ProgressInfo for DummyProgressInfo {} fn new_test_syncer(src: &Path, dest: &Path) -> rusync::Syncer { let dummy_progress_info = DummyProgressInfo {}; let options = rusync::SyncOptions::new(); rusync::Syncer::new(&src, &dest, options, Box::new(dummy_progress_info)) } #[test] fn fresh_copy() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); let outcome = syncer.sync(); assert!( outcome.is_ok(), "sync::sync failed with: {}", outcome.err().expect("") ); let src_top = src_path.join("top.txt"); let dest_top = dest_path.join("top.txt"); assert_same_contents(&src_top, &dest_top); let link_dest = dest_path.join("a_dir/link_to_one"); let target = fs::read_link(link_dest).expect("failed to read metada"); assert_eq!(target.to_string_lossy(), "one.txt"); } #[test] fn skip_up_to_date_files() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); let stats = syncer.sync().unwrap(); assert_eq!(stats.up_to_date, 0); let src_top_txt = src_path.join("top.txt"); make_recent(&src_top_txt).expect("could not make top.txt recent"); let syncer = new_test_syncer(&src_path, &dest_path); let stats = syncer.sync().expect(""); assert_eq!(stats.copied, 1); } #[test] fn preserve_permissions() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().unwrap(); let dest_exe = &dest_path.join("a_dir/foo.exe"); assert_executable(&dest_exe); } #[test] fn do_not_preserve_permissions() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let mut options = rusync::SyncOptions::new(); options.preserve_permissions = false; let syncer = rusync::Syncer::new( &src_path, &dest_path, options, Box::new(DummyProgressInfo {}), ); syncer.sync().expect(""); let dest_exe = &dest_path.join("a_dir/foo.exe"); assert_not_executable(&dest_exe); } #[test] fn rewrite_partially_written_files() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let src_top = src_path.join("top.txt"); let expected = fs::read_to_string(&src_top).expect(""); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().expect(""); let dest_top = dest_path.join("top.txt"); fs::write(&dest_top, "this is").expect(""); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().expect(""); let actual = fs::read_to_string(&dest_top).expect(""); assert_eq!(actual, expected); } #[test] fn dest_read_only() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); fs::create_dir_all(&dest_path).expect(""); let dest_top = dest_path.join("top.txt"); fs::write(&dest_top, "this is read only").expect(""); let top_file = File::open(dest_top).expect(""); let metadata = top_file.metadata().unwrap(); let mut permissions = metadata.permissions(); permissions.set_readonly(true); top_file.set_permissions(permissions).unwrap(); let src_top = src_path.join("top.txt"); make_recent(&src_top).expect("could not make top.txt recent"); let syncer = new_test_syncer(&src_path, &dest_path); let result = syncer.sync(); assert!(result.is_err()); } #[test] fn broken_link_in_src() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let src_broken_link = &src_path.join("broken"); unix::fs::symlink("no-such", &src_broken_link).expect(""); let syncer = new_test_syncer(&src_path, &dest_path); let result = syncer.sync(); let dest_broken_link = &dest_path.join("broken"); assert!(!dest_broken_link.exists()); assert_eq!( dest_broken_link.read_link().unwrap().to_string_lossy(), "no-such" ); assert!(result.is_ok()); }
extern crate filetime; extern crate tempdir; extern crate rusync; use std::fs; use std::fs::File; use std::io; use std::os::unix; use std::os::unix::fs::PermissionsExt; use std::path::Path; use std::path::PathBuf; use std::process::Command; use filetime::FileTime; use tempdir::TempDir; use rusync::progress::ProgressInfo; fn assert_same_contents(a: &Path, b: &Path) { assert!(a.exists(), "{:?} does not exist", a); assert!(b.exists(), "{:?} does not exist", b); let status = Command::new("diff") .args(&[a, b]) .status() .expect("Failed to execute process"); assert!(status.success(), "{:?} and {:?} differ", a, b) } fn is_executable(path: &Path) -> bool { let metadata = std::fs::metadata(&path).expect(&format!("Could not get metadata of {:?}", path)); let permissions = metadata.permissions(); let mode = permissions.mode(); mode & 0o111 != 0 } fn assert_executable(path: &Path) { assert!( is_executable(&path), "{:?} does not appear to be executable", path ); } fn assert_not_executable(path: &Path) { assert!(!is_executable(&path), "{:?} appears to be executable", path); } fn setup_test(tmp_path: &Path) -> (PathBuf, PathBuf) { let src_path = tmp_path.join("src"); let dest_path = tmp_path.join("dest"); let status = Command::new("cp") .args(&["-R", "tests/data", &src_path.to_string_lossy()]) .statu
create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); let outcome = syncer.sync(); assert!( outcome.is_ok(), "sync::sync failed with: {}", outcome.err().expect("") ); let src_top = src_path.join("top.txt"); let dest_top = dest_path.join("top.txt"); assert_same_contents(&src_top, &dest_top); let link_dest = dest_path.join("a_dir/link_to_one"); let target = fs::read_link(link_dest).expect("failed to read metada"); assert_eq!(target.to_string_lossy(), "one.txt"); } #[test] fn skip_up_to_date_files() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); let stats = syncer.sync().unwrap(); assert_eq!(stats.up_to_date, 0); let src_top_txt = src_path.join("top.txt"); make_recent(&src_top_txt).expect("could not make top.txt recent"); let syncer = new_test_syncer(&src_path, &dest_path); let stats = syncer.sync().expect(""); assert_eq!(stats.copied, 1); } #[test] fn preserve_permissions() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().unwrap(); let dest_exe = &dest_path.join("a_dir/foo.exe"); assert_executable(&dest_exe); } #[test] fn do_not_preserve_permissions() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let mut options = rusync::SyncOptions::new(); options.preserve_permissions = false; let syncer = rusync::Syncer::new( &src_path, &dest_path, options, Box::new(DummyProgressInfo {}), ); syncer.sync().expect(""); let dest_exe = &dest_path.join("a_dir/foo.exe"); assert_not_executable(&dest_exe); } #[test] fn rewrite_partially_written_files() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let src_top = src_path.join("top.txt"); let expected = fs::read_to_string(&src_top).expect(""); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().expect(""); let dest_top = dest_path.join("top.txt"); fs::write(&dest_top, "this is").expect(""); let syncer = new_test_syncer(&src_path, &dest_path); syncer.sync().expect(""); let actual = fs::read_to_string(&dest_top).expect(""); assert_eq!(actual, expected); } #[test] fn dest_read_only() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); fs::create_dir_all(&dest_path).expect(""); let dest_top = dest_path.join("top.txt"); fs::write(&dest_top, "this is read only").expect(""); let top_file = File::open(dest_top).expect(""); let metadata = top_file.metadata().unwrap(); let mut permissions = metadata.permissions(); permissions.set_readonly(true); top_file.set_permissions(permissions).unwrap(); let src_top = src_path.join("top.txt"); make_recent(&src_top).expect("could not make top.txt recent"); let syncer = new_test_syncer(&src_path, &dest_path); let result = syncer.sync(); assert!(result.is_err()); } #[test] fn broken_link_in_src() { let tmp_dir = TempDir::new("test-rusync").expect("failed to create temp dir"); let (src_path, dest_path) = setup_test(&tmp_dir.path()); let src_broken_link = &src_path.join("broken"); unix::fs::symlink("no-such", &src_broken_link).expect(""); let syncer = new_test_syncer(&src_path, &dest_path); let result = syncer.sync(); let dest_broken_link = &dest_path.join("broken"); assert!(!dest_broken_link.exists()); assert_eq!( dest_broken_link.read_link().unwrap().to_string_lossy(), "no-such" ); assert!(result.is_ok()); }
s() .expect("Failed to execute process"); assert!(status.success()); (src_path, dest_path) } fn make_recent(path: &Path) -> io::Result<()> { let metadata = fs::metadata(&path)?; let atime = FileTime::from_last_access_time(&metadata); let mtime = FileTime::from_last_modification_time(&metadata); let mut epoch = mtime.seconds_relative_to_1970(); epoch += 1; let mtime = FileTime::from_seconds_since_1970(epoch, 0); filetime::set_file_times(&path, atime, mtime)?; Ok(()) } struct DummyProgressInfo {} impl ProgressInfo for DummyProgressInfo {} fn new_test_syncer(src: &Path, dest: &Path) -> rusync::Syncer { let dummy_progress_info = DummyProgressInfo {}; let options = rusync::SyncOptions::new(); rusync::Syncer::new(&src, &dest, options, Box::new(dummy_progress_info)) } #[test] fn fresh_copy() { let tmp_dir = TempDir::new("test-rusync").expect("failed to
random
[ { "content": "pub fn get_rel_path(a: &Path, b: &Path) -> FSResult<PathBuf> {\n\n let rel_path = pathdiff::diff_paths(&a, &b);\n\n if rel_path.is_none() {\n\n let desc = format!(\n\n \"Could not get relative path from {} to {}\",\n\n &a.to_string_lossy(),\n\n &b.to_string_lossy()\n\n );\n\n Err(FSError::from_description(&desc))\n\n } else {\n\n Ok(rel_path.unwrap())\n\n }\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 3, "score": 106250.26618524629 }, { "content": "fn has_different_size(src: &Entry, dest: &Entry) -> bool {\n\n let src_meta = src.metadata().expect(\"src_meta should not be None\");\n\n let src_size = src_meta.len();\n\n\n\n let dest_meta = dest.metadata();\n\n if dest_meta.is_none() {\n\n return true;\n\n }\n\n let dest_size = dest_meta.unwrap().len();\n\n dest_size != src_size\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 7, "score": 73129.50065977924 }, { "content": "fn is_more_recent_than(src: &Entry, dest: &Entry) -> bool {\n\n if !dest.exists() {\n\n return true;\n\n }\n\n\n\n let src_meta = &src.metadata();\n\n let dest_meta = &dest.metadata();\n\n\n\n let src_meta = &src_meta.expect(\"src_meta was None\");\n\n let dest_meta = &dest_meta.expect(\"dest_meta was None\");\n\n\n\n let src_mtime = FileTime::from_last_modification_time(&src_meta);\n\n let dest_mtime = FileTime::from_last_modification_time(&dest_meta);\n\n\n\n let src_precise = src_mtime.seconds() * 1000 * 1000 * 1000 + u64::from(src_mtime.nanoseconds());\n\n let dest_precise =\n\n dest_mtime.seconds() * 1000 * 1000 * 1000 + u64::from(dest_mtime.nanoseconds());\n\n\n\n src_precise > dest_precise\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 9, "score": 56837.655400822296 }, { "content": "fn get_terminal_width() -> usize {\n\n if let Some((w, _)) = term_size::dimensions() {\n\n return w;\n\n }\n\n // We're likely not a tty here, so this is a good enough\n\n // default:\n\n 80\n\n}\n\n\n", "file_path": "src/console_info.rs", "rank": 12, "score": 49130.43982615883 }, { "content": "pub fn copy_permissions(src: &Entry, dest: &Entry) -> FSResult<()> {\n\n let src_meta = &src.metadata();\n\n // is_link should not be none because we should have been able to\n\n // read its metadata way back in WalkWorker\n\n let is_link = src\n\n .is_link()\n\n .unwrap_or_else(|| panic!(\"is_link was None for {:#?}\", src));\n\n if is_link {\n\n return Ok(());\n\n }\n\n // The only way for src_meta to be None is if src is a broken symlink\n\n // and we checked that right above:\n\n let src_meta = &src_meta.expect(&format!(\"src_meta was None for {:#?}\", src));\n\n let permissions = src_meta.permissions();\n\n let dest_file = File::open(dest.path());\n\n if let Err(e) = dest_file {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\n\n \"Could not open {} while copying permissions\",\n", "file_path": "src/fsops.rs", "rank": 13, "score": 39077.43040332608 }, { "content": "import sys\n\nimport subprocess\n\n\n\ndef main():\n\n failed = []\n\n n = int(sys.argv[1])\n\n test_args = sys.argv[2:]\n\n for i in range(n):\n\n print(i +1, \"on\", n, end=\" \")\n\n process = subprocess.run(\n\n [\"cargo\", \"test\", *test_args],\n\n stdout=subprocess.PIPE,\n\n stderr=subprocess.STDOUT,\n\n )\n\n if process.returncode == 0:\n\n print(\"ok\")\n\n else:\n\n print(\"!!! FAILED\")\n\n failed.append(process.stdout.decode())\n\n\n\n if not failed:\n\n return\n\n\n\n for fail in failed:\n\n print(fail)\n\n print(\"-\" * 80)\n\n print()\n\n\n\n\n\nif __name__ == \"__main__\":\n\n main()\n", "file_path": "tools/test_n.py", "rank": 14, "score": 36324.18937786662 }, { "content": "fn main() {\n\n let opt = Opt::from_args();\n\n let source = &opt.source;\n\n if !source.is_dir() {\n\n eprintln!(\"{} is not a directory\", source.to_string_lossy());\n\n process::exit(1);\n\n }\n\n let destination = &opt.destination;\n\n\n\n let console_info = ConsoleProgressInfo::new();\n\n let mut options = SyncOptions::new();\n\n options.preserve_permissions = opt.preserve_permissions();\n\n let syncer = Syncer::new(&source, &destination, options, Box::new(console_info));\n\n let stats = syncer.sync();\n\n match stats {\n\n Err(err) => {\n\n eprintln!(\"{}\", err);\n\n process::exit(1);\n\n }\n\n Ok(_) => {\n\n process::exit(0);\n\n }\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 15, "score": 35248.21314022949 }, { "content": "import sys\n\n\n\n\n\ndef main():\n\n new_version = sys.argv[1]\n\n with open(\"Changelog.md\") as stream:\n\n contents = stream.read()\n\n if not new_version in contents:\n\n sys.exit(\"new_version: %s not found in Changelog\" % new_version)\n\n\n\n\n\nif __name__ == \"__main__\":\n\n main()\n", "file_path": "tools/check-changelog.py", "rank": 16, "score": 34055.075396383174 }, { "content": "fn erase_line() {\n\n let line_width = get_terminal_width();\n\n let line = vec![32 as u8; line_width as usize];\n\n print!(\"{}\\r\", String::from_utf8(line).unwrap());\n\n}\n\n\n", "file_path": "src/console_info.rs", "rank": 17, "score": 32894.56399175104 }, { "content": "pub fn copy_entry(\n\n progress_sender: &mpsc::Sender<ProgressMessage>,\n\n src: &Entry,\n\n dest: &Entry,\n\n) -> FSResult<SyncOutcome> {\n\n let src_path = src.path();\n\n let src_file = File::open(src_path);\n\n if let Err(e) = src_file {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\"Could not open {} for reading\", src_path.to_string_lossy()),\n\n ));\n\n }\n\n let mut src_file = src_file.unwrap();\n\n let src_meta = src.metadata().expect(\"src_meta should not be None\");\n\n let src_size = src_meta.len();\n\n let dest_path = dest.path();\n\n let dest_file = File::create(dest_path);\n\n if let Err(e) = dest_file {\n\n return Err(FSError::from_io_error(\n", "file_path": "src/fsops.rs", "rank": 22, "score": 31536.744924456696 }, { "content": "pub fn sync_entries(\n\n progress_sender: &mpsc::Sender<ProgressMessage>,\n\n src: &Entry,\n\n dest: &Entry,\n\n) -> FSResult<SyncOutcome> {\n\n let _ = progress_sender.send(ProgressMessage::StartSync(src.description().to_string()));\n\n src.is_link().expect(\"src.is_link should not be None\");\n\n if src.is_link().unwrap() {\n\n return copy_link(&src, &dest);\n\n }\n\n let different_size = has_different_size(&src, &dest);\n\n let more_recent = is_more_recent_than(&src, &dest);\n\n // TODO: check if files really are different ?\n\n if more_recent || different_size {\n\n return copy_entry(&progress_sender, &src, &dest);\n\n }\n\n Ok(SyncOutcome::UpToDate)\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/fsops.rs", "rank": 23, "score": 31536.744924456696 }, { "content": "fn human_seconds(s: usize) -> String {\n\n let hours = s / 3600;\n\n let minutes = (s / 60) % 60;\n\n let seconds = s % 60;\n\n return format!(\"{:02}:{:02}:{:02}\", hours, minutes, seconds);\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n\n\n use super::human_seconds;\n\n\n\n #[test]\n\n fn test_human_seconds() {\n\n assert_eq!(\"00:00:05\", human_seconds(5));\n\n assert_eq!(\"00:00:42\", human_seconds(42));\n\n assert_eq!(\"00:03:05\", human_seconds(185));\n\n assert_eq!(\"02:04:05\", human_seconds(7445));\n\n assert_eq!(\"200:00:02\", human_seconds(720002));\n\n }\n\n\n\n}\n", "file_path": "src/console_info.rs", "rank": 25, "score": 27622.836268023362 }, { "content": "pub fn to_io_error(message: &str) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, message)\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 26, "score": 24634.54654037314 }, { "content": "fn copy_link(src: &Entry, dest: &Entry) -> FSResult<SyncOutcome> {\n\n let src_target = std::fs::read_link(src.path());\n\n if let Err(e) = src_target {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\"Could not read link {}\", src.path().to_string_lossy()),\n\n ));\n\n }\n\n let src_target = src_target.unwrap();\n\n let is_link = dest.is_link();\n\n let outcome;\n\n match is_link {\n\n Some(true) => {\n\n let dest_target = std::fs::read_link(dest.path());\n\n if let Err(e) = dest_target {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\"Could not read link {}\", dest.path().to_string_lossy()),\n\n ));\n\n }\n", "file_path": "src/fsops.rs", "rank": 27, "score": 22168.87869146395 }, { "content": "def main():\n\n failed = []\n\n n = int(sys.argv[1])\n\n test_args = sys.argv[2:]\n\n for i in range(n):\n\n print(i +1, \"on\", n, end=\" \")\n\n process = subprocess.run(\n\n [\"cargo\", \"test\", *test_args],\n\n stdout=subprocess.PIPE,\n\n stderr=subprocess.STDOUT,\n\n )\n\n if process.returncode == 0:\n\n print(\"ok\")\n\n else:\n\n print(\"!!! FAILED\")\n\n failed.append(process.stdout.decode())\n\n\n\n if not failed:\n\n return\n\n\n\n for fail in failed:\n\n print(fail)\n\n print(\"-\" * 80)\n", "file_path": "tools/test_n.py", "rank": 28, "score": 20130.91440146492 }, { "content": "def main():\n\n new_version = sys.argv[1]\n\n with open(\"Changelog.md\") as stream:\n\n contents = stream.read()\n\n if not new_version in contents:\n", "file_path": "tools/check-changelog.py", "rank": 29, "score": 19169.63808912401 }, { "content": "# rusync\n\n\n\n<a href=\"https://crates.io/crates/rusync\"><img src=\"https://img.shields.io/crates/v/rusync.svg\"/></a>\n\n<a href=\"https://travis-ci.org/dmerejkowsky/rusync\"><img src=\"https://api.travis-ci.org/dmerejkowsky/rusync.svg?branch=master\"/></a>\n\n\n\n`rsync` implemented in rust.\n\n\n\n# Caveat\n\n\n\nWe do everything we can to make sure data loss is impossible, but despite our best efforts, it may still happen.\n\n\n\nPlease make sure your files files are backed up if necessary before using `rusync` on sensitive data.\n\n\n\nThank you for your understanding!\n\n\n\n# Usage\n\n\n\n```\n\n$ cargo install rusync\n\n$ rusync test/src test/dest\n\n:: Syncing from test/src to test/dest …\n\n 50% 24/50 Downloads/archlinux.iso 00:01:30\n\n```\n\n\n\n# Features\n\n\n\n* Easy to remember command line syntax\n\n\n\n* Print progress on one line, and erase it when done, thus avoiding flooding your terminal\n\n with useless noise.\n\n\n\n* Un-surprising behavior: missing directories are created\n\n on the fly, files are only copied if:\n\n\n\n * Destination is missing\n\n * Older than the source\n\n * Or size is different\n\n\n\n* Minimalistic implementation\n\n\n\n# Missing\n\n\n\nThere are *tons* of stuff in `rsync` we don't implement.\n\n\n\nBut for me, the goal was to learn more about Rust and I've learned plenty of things already.\n\n\n\nThe big missing feature is an option to delete extraneous files. Maybe I'll start working on it one day.\n\n\n\nSome people have asked for transfer over `ssh`. Not sure if that can be easily done. Maybe try using `rusync` normally on top of `sshfs`?\n\n\n\nFor the rest, well, patches are welcome!\n", "file_path": "README.md", "rank": 30, "score": 15480.503691557675 }, { "content": "# v0.5.0\n\n\n\n* rusync is now usable as a library! Thanks @mmstick for the suggestion. See [documentation](https://docs.rs/rusync) for details.\n\n\n\n# v0.4.3\n\n\n\n* Using term_size instead of terminal_size. This fixes compilation on Android.\n\n\n\n# v0.4.2\n\n\n\n* Bug fix: broken symlink in source directory were not re-created in the destination directory\n\n\n\n# v0.4.1\n\n\n\n* Improve error handling: display more details about the file operation that failed\n\n instead of just the raw io::Error\n\n\n\n# v0.4.0\n\n\n\n* Display an ETA at the right of the progress bar.\n\n\n\n# v0.3.1\n\n\n\n* Exit early if the source given on the command line is not an argument. We used to display a weird\n\n \"0 files copied\" in this case.\n\n\n\n# v0.3.0\n\n\n\n* Change output to be like a Ninja. Print all progress on one line, and erase it when done.\n\n\n\nThe line looks like:\n\n\n\n```\n\n 50% 24/50 Downloads/archlinux.iso\n\n```\n\n\n\nIt contains the percentage of the current file that has been transfered, the index of the current transfered,\n\nthe total number of files to copy, and the name of the current file.\n\n\n\nNote that the number of files to copy may increase while rusync is running: this is because the contents\n\nof the source folder are read *while the copy is done*.\n\n\n\n\n\n# v0.2.3\n\n\n\n* Add a `--no-perms` flag to disable preservation of permissions. Useful when\n\n you *know* this will fail and don't want to be flooded with warning messages.\n\n\n\n# v0.2.1\n\n\n\nThis contains several bug fixes regarding symlinks.\n\n\n\nHere the algorithm when now use:\n\n\n\n* If the destination does not exists:\n\n * Create a new symlink with the same target as the previous one.\n\n\n\n* If the destination exists:\n\n\n\n * If it's not a symlink:\n\n * Abort!\n\n\n\n * Otherwise:\n\n\n\n * If the destination symlink already has the correct target, consider it up to date.\n\n * If the destination symlink is broken, remove it and re-create it.\n\n * If the destination symlink does not point to the correct location, remove it and re-create it.\n\n\n\n# v0.2.0\n\n\n\n* Try and preserve permissions after files are copied\n\n\n\n# v0.1.2\n\n\n\n* Add missing call to `stdout().flush()`\n\n\n", "file_path": "Changelog.md", "rank": 31, "score": 15479.683497873 }, { "content": "# v0.1.1\n\n\n\n* Display a progress bar for each file\n\n\n\n# v0.1.0\n\n\n\nInitial release\n", "file_path": "Changelog.md", "rank": 32, "score": 15474.907305473931 }, { "content": "extern crate colored;\n\nextern crate rusync;\n\nextern crate structopt;\n\n\n\nuse rusync::console_info::ConsoleProgressInfo;\n\nuse rusync::sync::SyncOptions;\n\nuse rusync::Syncer;\n\nuse std::path::PathBuf;\n\nuse std::process;\n\nuse structopt::StructOpt;\n\n\n\n#[derive(Debug, StructOpt)]\n\n#[structopt(name = \"rusync\")]\n", "file_path": "src/main.rs", "rank": 34, "score": 14.694507899654294 }, { "content": " &self.path\n\n }\n\n pub fn metadata(&self) -> Option<&fs::Metadata> {\n\n self.metadata.as_ref()\n\n }\n\n pub fn exists(&self) -> bool {\n\n self.exists\n\n }\n\n\n\n pub fn is_link(&self) -> Option<bool> {\n\n self.is_link\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\n\n use super::Entry;\n\n use super::Path;\n\n\n", "file_path": "src/entry.rs", "rank": 35, "score": 12.78704778264183 }, { "content": "use std::fs;\n\nuse std::option::Option;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Entry {\n\n description: String,\n\n path: PathBuf,\n\n metadata: Option<fs::Metadata>,\n\n exists: bool,\n\n is_link: Option<bool>,\n\n}\n\n\n\nimpl Entry {\n\n pub fn new(description: &str, entry_path: &Path) -> Entry {\n\n let mut metadata = fs::metadata(&entry_path).ok();\n\n let is_link;\n\n let symlink_metadata = fs::symlink_metadata(&entry_path);\n\n if let Ok(data) = symlink_metadata {\n", "file_path": "src/entry.rs", "rank": 36, "score": 11.491229495644788 }, { "content": " #[test]\n\n fn new_entry_with_non_existing_path() {\n\n let path = Path::new(\"/path/to/nosuch.txt\");\n\n let entry = Entry::new(\"nosuch\", &path);\n\n\n\n assert!(!entry.exists());\n\n assert!(entry.metadata.is_none());\n\n }\n\n\n\n #[test]\n\n fn new_entry_with_existing_path() {\n\n let path = Path::new(file!());\n\n let entry = Entry::new(\"entry.rs\", &path);\n\n\n\n assert!(entry.exists());\n\n assert!(entry.metadata.is_some());\n\n let is_link = entry.is_link();\n\n assert!(is_link.is_some());\n\n assert!(!is_link.unwrap());\n\n }\n\n\n\n}\n", "file_path": "src/entry.rs", "rank": 37, "score": 10.724270164843563 }, { "content": "mod tests {\n\n\n\n extern crate tempdir;\n\n use self::tempdir::TempDir;\n\n\n\n use std;\n\n use std::error::Error;\n\n use std::fs::File;\n\n use std::io::prelude::*;\n\n use std::os::unix;\n\n use std::path::Path;\n\n use std::path::PathBuf;\n\n\n\n use super::copy_link;\n\n use super::Entry;\n\n use super::FSResult;\n\n use super::SyncOutcome;\n\n\n\n fn create_file(path: &Path) {\n\n let mut out = File::create(path).expect(&format!(\"could not open {:?} for writing\", path));\n", "file_path": "src/fsops.rs", "rank": 38, "score": 10.338998268153576 }, { "content": " let existing_link = tmp_path.join(\"existing_link\");\n\n create_link(\"old\", &existing_link);\n\n let outcome = sync_src_link(&tmp_path, &src_link, \"existing_link\");\n\n assert_eq!(outcome.expect(\"\"), SyncOutcome::SymlinkUpdated);\n\n assert_links_to(&tmp_path, \"existing_link\", \"src\");\n\n }\n\n\n\n #[test]\n\n fn copy_link_dest_is_a_regular_file() {\n\n let tmp_dir = TempDir::new(\"test-rusync-fsops\").expect(\"failed to create temp dir\");\n\n let tmp_path = tmp_dir.path();\n\n let src_link = setup_copy_test(tmp_path);\n\n\n\n let existing_file = tmp_path.join(\"existing\");\n\n create_file(&existing_file);\n\n let outcome = sync_src_link(&tmp_path, &src_link, \"existing\");\n\n assert!(outcome.is_err());\n\n let err = outcome.err().unwrap();\n\n let desc = err.description();\n\n assert!(desc.contains(\"existing\"));\n\n }\n\n\n\n}\n", "file_path": "src/fsops.rs", "rank": 39, "score": 8.531839258698499 }, { "content": "extern crate pathdiff;\n\n\n\nuse std;\n\nuse std::error::Error;\n\nuse std::fs;\n\nuse std::fs::File;\n\nuse std::io;\n\nuse std::io::Read;\n\nuse std::io::Write;\n\nuse std::os::unix;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::sync::mpsc;\n\n\n\nuse filetime::FileTime;\n\n\n\nuse entry::Entry;\n\nuse progress::ProgressMessage;\n\n\n\nconst BUFFER_SIZE: usize = 100 * 1024;\n", "file_path": "src/fsops.rs", "rank": 40, "score": 8.250677141418592 }, { "content": "extern crate colored;\n\n\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::sync::mpsc::channel;\n\nuse std::thread;\n\n\n\nuse entry::Entry;\n\nuse fsops;\n\nuse fsops::SyncOutcome::*;\n\nuse progress::{ProgressInfo, ProgressMessage};\n\nuse workers::ProgressWorker;\n\nuse workers::SyncWorker;\n\nuse workers::WalkWorker;\n\n\n\n#[derive(Default)]\n\npub struct Stats {\n\n /// Number of files in the source\n\n pub num_files: u64,\n\n /// Sum of the sizes of all the files in the source\n", "file_path": "src/sync.rs", "rank": 41, "score": 7.958851681128909 }, { "content": " is_link = Some(data.file_type().is_symlink());\n\n metadata = Some(data);\n\n } else {\n\n is_link = None;\n\n }\n\n\n\n Entry {\n\n description: String::from(description),\n\n metadata,\n\n path: entry_path.to_path_buf(),\n\n exists: entry_path.exists(),\n\n is_link,\n\n }\n\n }\n\n\n\n pub fn description(&self) -> &String {\n\n &self.description\n\n }\n\n\n\n pub fn path(&self) -> &PathBuf {\n", "file_path": "src/entry.rs", "rank": 42, "score": 7.805625291634221 }, { "content": " Ok(())\n\n }\n\n\n\n fn process_file(&self, entry: &DirEntry) -> Option<fs::Metadata> {\n\n let rel_path = fsops::get_rel_path(&entry.path(), &self.source);\n\n if rel_path.is_err() {\n\n return None;\n\n }\n\n let rel_path = rel_path.unwrap();\n\n let parent_rel_path = rel_path.parent();\n\n if parent_rel_path.is_none() {\n\n eprintln!(\n\n \"Could not get parent path of {}\",\n\n rel_path.to_string_lossy()\n\n );\n\n return None;\n\n }\n\n\n\n let desc = rel_path.to_string_lossy();\n\n let src_entry = Entry::new(&desc, &entry.path());\n", "file_path": "src/workers/walk_worker.rs", "rank": 43, "score": 7.656477792983919 }, { "content": "//! let stats = syncer.sync();\n\n//! match stats {\n\n//! Err(err) => {\n\n//! eprintln!(\"Error when syncing: {}\", err);\n\n//! }\n\n//! Ok(stats) => {\n\n//! println!(\"Transfered {} files\", stats.copied);\n\n//! }\n\n//! }\n\n//! ```\n\n//!\n\nextern crate colored;\n\nextern crate filetime;\n\nextern crate term_size;\n\n\n\npub mod console_info;\n\nmod entry;\n\nmod fsops;\n\npub mod progress;\n\npub mod sync;\n\nmod workers;\n\npub use sync::Syncer;\n\npub use sync::SyncOptions;\n\npub use sync::Stats;\n\npub use console_info::ConsoleProgressInfo;\n", "file_path": "src/lib.rs", "rank": 44, "score": 7.003086684516254 }, { "content": " }\n\n}\n\n\n\n#[derive(Copy, Clone)]\n\npub struct SyncOptions {\n\n /// Wether to preserve permissions of the source file after the destination is written.\n\n pub preserve_permissions: bool,\n\n}\n\n\n\nimpl SyncOptions {\n\n pub fn new() -> SyncOptions {\n\n SyncOptions {\n\n preserve_permissions: true,\n\n }\n\n }\n\n}\n\n\n\npub struct Syncer {\n\n source: PathBuf,\n\n destination: PathBuf,\n", "file_path": "src/sync.rs", "rank": 45, "score": 6.463035259167984 }, { "content": "\n\n fn sync_src_link(tmp_path: &Path, src_link: &Path, dest: &str) -> FSResult<SyncOutcome> {\n\n let src_entry = Entry::new(\"src\", &src_link);\n\n let dest_path = &tmp_path.join(&dest);\n\n let dest_entry = Entry::new(&dest, dest_path);\n\n copy_link(&src_entry, &dest_entry)\n\n }\n\n\n\n #[test]\n\n fn copy_link_dest_does_not_exist() {\n\n let tmp_dir = TempDir::new(\"test-rusync-fsops\").expect(\"failed to create temp dir\");\n\n let tmp_path = tmp_dir.path();\n\n let src_link = setup_copy_test(tmp_path);\n\n\n\n let outcome = sync_src_link(&tmp_path, &src_link, \"new\");\n\n assert_eq!(outcome.expect(\"\"), SyncOutcome::SymlinkCreated);\n\n assert_links_to(&tmp_path, \"new\", \"src\");\n\n }\n\n\n\n #[test]\n", "file_path": "src/fsops.rs", "rank": 46, "score": 6.15168694701315 }, { "content": "//! rusync\n\n//!\n\n//! Implements copy from one directory to an other\n\n//!\n\n//! To use rusync as a library, start with the [Syncer](sync/struct.Syncer.html) struct.\n\n//!\n\n//! To customize its output, implement the [ProgressInfo](progress/trait.ProgressInfo.html) trait.\n\n\n\n//! # Example\n\n//!\n\n//! ```\n\n//! let console_info = rusync::ConsoleProgressInfo::new();\n\n//! // or any struct that implements the ProgressInfo trait\n\n//!\n\n//! let options = rusync::SyncOptions::new();\n\n//! // can set any public field of SyncOptions here\n\n//!\n\n//! let source = std::path::Path::new(\"src\");\n\n//! let destination = std::path::Path::new(\"dest\");\n\n//! let syncer = rusync::Syncer::new(&source, &destination, options, Box::new(console_info));\n", "file_path": "src/lib.rs", "rank": 47, "score": 5.96409183317509 }, { "content": " }\n\n\n\n fn sync(&self, src_entry: &Entry, opts: SyncOptions) -> fsops::FSResult<SyncOutcome> {\n\n let rel_path = fsops::get_rel_path(&src_entry.path(), &self.source)?;\n\n self.create_missing_dest_dirs(&rel_path)?;\n\n let desc = rel_path.to_string_lossy();\n\n\n\n let dest_path = self.destination.join(&rel_path);\n\n let dest_entry = Entry::new(&desc, &dest_path);\n\n let outcome = fsops::sync_entries(&self.output, &src_entry, &dest_entry)?;\n\n if opts.preserve_permissions {\n\n fsops::copy_permissions(&src_entry, &dest_entry)?;\n\n }\n\n Ok(outcome)\n\n }\n\n}\n", "file_path": "src/workers/sync_worker.rs", "rank": 48, "score": 5.790866262191217 }, { "content": "use std::fs;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::sync::mpsc::{Receiver, Sender};\n\n\n\nuse entry::Entry;\n\nuse fsops;\n\nuse fsops::SyncOutcome;\n\nuse progress::ProgressMessage;\n\nuse sync::SyncOptions;\n\n\n\npub struct SyncWorker {\n\n input: Receiver<Entry>,\n\n output: Sender<ProgressMessage>,\n\n source: PathBuf,\n\n destination: PathBuf,\n\n}\n\n\n\nimpl SyncWorker {\n\n pub fn new(\n", "file_path": "src/workers/sync_worker.rs", "rank": 49, "score": 5.770615300402339 }, { "content": "use std::fs;\n\nuse std::fs::DirEntry;\n\nuse std::io;\n\nuse std::option::Option;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::sync::mpsc::Sender;\n\n\n\nuse entry::Entry;\n\nuse fsops;\n\nuse progress::ProgressMessage;\n\n\n\npub struct WalkWorker {\n\n entry_output: Sender<Entry>,\n\n progress_output: Sender<ProgressMessage>,\n\n source: PathBuf,\n\n}\n\n\n\nimpl WalkWorker {\n\n pub fn new(\n", "file_path": "src/workers/walk_worker.rs", "rank": 50, "score": 5.6626223779969465 }, { "content": " fn copy_link_dest_is_a_broken_link() {\n\n let tmp_dir = TempDir::new(\"test-rusync-fsops\").expect(\"failed to create temp dir\");\n\n let tmp_path = tmp_dir.path();\n\n let src_link = setup_copy_test(tmp_path);\n\n\n\n let broken_link = &tmp_path.join(\"broken\");\n\n create_link(\"no-such-file\", &broken_link);\n\n let outcome = sync_src_link(&tmp_path, &src_link, \"broken\");\n\n assert_eq!(outcome.expect(\"\"), SyncOutcome::SymlinkUpdated);\n\n assert_links_to(&tmp_path, \"broken\", \"src\");\n\n }\n\n\n\n #[test]\n\n fn copy_link_dest_doest_not_point_to_correct_location() {\n\n let tmp_dir = TempDir::new(\"test-rusync-fsops\").expect(\"failed to create temp dir\");\n\n let tmp_path = tmp_dir.path();\n\n let src_link = setup_copy_test(tmp_path);\n\n\n\n let old_dest = &tmp_path.join(\"old\");\n\n create_file(&old_dest);\n", "file_path": "src/fsops.rs", "rank": 51, "score": 5.449316118579312 }, { "content": " let metadata = src_entry.metadata();\n\n if metadata.is_none() {\n\n eprintln!(\n\n \"Could not read metadata from {}\",\n\n &entry.path().to_string_lossy(),\n\n );\n\n return None;\n\n }\n\n\n\n let metadata = metadata.unwrap();\n\n let sent = self.entry_output.send(src_entry.clone());\n\n if sent.is_err() {\n\n // entry output chan is closed\n\n return None;\n\n }\n\n Some(metadata.clone())\n\n }\n\n\n\n pub fn start(&self) {\n\n let outcome = &self.walk();\n\n if outcome.is_err() {\n\n // Send err to output\n\n }\n\n }\n\n}\n", "file_path": "src/workers/walk_worker.rs", "rank": 52, "score": 4.64985714784874 }, { "content": " \"Refusing to replace existing path {:?} by symlink\",\n\n dest.path()\n\n )));\n\n }\n\n None => {\n\n // OK, dest does not exist\n\n outcome = SyncOutcome::SymlinkCreated;\n\n }\n\n }\n\n let symlink_result = unix::fs::symlink(&src_target, &dest.path());\n\n match symlink_result {\n\n Err(e) => Err(FSError::from_io_error(\n\n e,\n\n &format!(\n\n \"Could not create link from {} to {}\",\n\n dest.path().to_string_lossy(),\n\n &src_target.to_string_lossy()\n\n ),\n\n )),\n\n Ok(_) => Ok(outcome),\n\n }\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 53, "score": 4.5336283895989835 }, { "content": " out.write_all(b\"\").expect(\"could not write old test\");\n\n }\n\n\n\n fn create_link(src: &str, dest: &Path) {\n\n unix::fs::symlink(&src, &dest).expect(&format!(\"could not link {:?} -> {:?}\", src, dest));\n\n }\n\n\n\n fn assert_links_to(tmp_path: &Path, src: &str, dest: &str) {\n\n let src_path = tmp_path.join(src);\n\n let link = std::fs::read_link(src_path).expect(&format!(\"could not read link {:?}\", src));\n\n assert_eq!(link.to_string_lossy(), dest);\n\n }\n\n\n\n fn setup_copy_test(tmp_path: &Path) -> PathBuf {\n\n let src = &tmp_path.join(\"src\");\n\n create_file(&src);\n\n let src_link = &tmp_path.join(\"src_link\");\n\n create_link(\"src\", &src_link);\n\n src_link.to_path_buf()\n\n }\n", "file_path": "src/fsops.rs", "rank": 54, "score": 4.477792180255651 }, { "content": " }\n\n\n\n fn create_missing_dest_dirs(&self, rel_path: &Path) -> fsops::FSResult<()> {\n\n let parent_rel_path = rel_path.parent();\n\n if parent_rel_path.is_none() {\n\n return Err(fsops::FSError::from_description(&format!(\n\n \"Could not get parent path of {}\",\n\n rel_path.to_string_lossy()\n\n )));\n\n }\n\n let parent_rel_path = parent_rel_path.unwrap();\n\n let to_create = self.destination.join(parent_rel_path);\n\n let create_result = fs::create_dir_all(&to_create);\n\n if let Err(e) = create_result {\n\n return Err(fsops::FSError::from_io_error(\n\n e,\n\n &format!(\"Could not create {}\", &to_create.to_string_lossy()),\n\n ));\n\n }\n\n Ok(())\n", "file_path": "src/workers/sync_worker.rs", "rank": 55, "score": 4.072752120490746 }, { "content": " if path.is_dir() {\n\n subdirs.push(path);\n\n } else {\n\n let meta = self.process_file(&entry);\n\n if let Some(meta) = meta {\n\n num_files += 1;\n\n total_size += meta.len();\n\n let sent = self.progress_output.send(ProgressMessage::Todo {\n\n num_files,\n\n total_size: total_size as usize,\n\n });\n\n if sent.is_err() {\n\n return Err(fsops::to_io_error(\n\n &\"stats output chan is closed\".to_string(),\n\n ));\n\n }\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/workers/walk_worker.rs", "rank": 56, "score": 3.532150536193794 }, { "content": " dest.description()\n\n ),\n\n ));\n\n }\n\n let dest_file = dest_file.unwrap();\n\n\n\n if let Err(e) = dest_file.set_permissions(permissions) {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\"Could set permissions for {}\", dest.description()),\n\n ));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/fsops.rs", "rank": 57, "score": 3.009643799379888 }, { "content": "//! console_info\n\n//!\n\n//! Display transfer progress to the command line\n\n\n\nuse colored::Colorize;\n\nuse progress::{Progress, ProgressInfo};\n\nuse std::io;\n\nuse std::io::Write;\n\nuse sync;\n\nuse term_size;\n\n\n\npub struct ConsoleProgressInfo {}\n\n\n\nimpl ConsoleProgressInfo {\n\n pub fn new() -> ConsoleProgressInfo {\n\n ConsoleProgressInfo {}\n\n }\n\n}\n\n\n\nimpl ProgressInfo for ConsoleProgressInfo {\n", "file_path": "src/console_info.rs", "rank": 58, "score": 2.934602473609086 }, { "content": "mod progress_worker;\n\nmod sync_worker;\n\nmod walk_worker;\n\n\n\npub use self::progress_worker::ProgressWorker;\n\npub use self::sync_worker::SyncWorker;\n\npub use self::walk_worker::WalkWorker;\n", "file_path": "src/workers/mod.rs", "rank": 59, "score": 2.7730745367263503 }, { "content": "/// Trait for implementing rusync progress details\n\npub trait ProgressInfo {\n\n /// A new transfer has begun from the `source` directory to the `destination`\n\n /// directory\n\n #[allow(unused_variables)]\n\n fn start(&self, source: &str, destination: &str) {}\n\n\n\n /// A new file named `name` is being transfered\n\n #[allow(unused_variables)]\n\n fn new_file(&self, name: &str) {}\n\n\n\n /// The file transfer is done\n\n #[allow(unused_variables)]\n\n fn done_syncing(&self) {}\n\n\n\n /// Callback for the detailed progress\n\n #[allow(unused_variables)]\n\n fn progress(&self, progress: &Progress) {}\n\n\n\n /// The transfer between `source` and `destination` is done. Details\n\n /// of the transfer in the Stats struct\n\n #[allow(unused_variables)]\n\n fn end(&self, stats: &Stats) {}\n\n}\n", "file_path": "src/progress.rs", "rank": 60, "score": 2.714265240630075 }, { "content": " source: &Path,\n\n entry_output: Sender<Entry>,\n\n progress_output: Sender<ProgressMessage>,\n\n ) -> WalkWorker {\n\n WalkWorker {\n\n entry_output,\n\n progress_output,\n\n source: source.to_path_buf(),\n\n }\n\n }\n\n\n\n fn walk(&self) -> io::Result<()> {\n\n let mut num_files = 0;\n\n let mut total_size = 0;\n\n let mut subdirs: Vec<PathBuf> = vec![self.source.to_path_buf()];\n\n while !subdirs.is_empty() {\n\n let subdir = subdirs.pop().unwrap();\n\n for entry in fs::read_dir(subdir)? {\n\n let entry = entry?;\n\n let path = entry.path();\n", "file_path": "src/workers/walk_worker.rs", "rank": 61, "score": 2.64085497403859 }, { "content": "#[derive(Debug, StructOpt)]\n\n#[structopt(name = \"rusync\")]\n\nstruct Opt {\n\n #[structopt(long = \"no-perms\")]\n\n no_preserve_permissions: bool,\n\n\n\n #[structopt(parse(from_os_str))]\n\n source: PathBuf,\n\n\n\n #[structopt(parse(from_os_str))]\n\n destination: PathBuf,\n\n}\n\n\n\nimpl Opt {\n\n fn preserve_permissions(&self) -> bool {\n\n !self.no_preserve_permissions\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 62, "score": 2.6026954428936784 }, { "content": "use std::sync::mpsc::Receiver;\n\nuse std::time::Instant;\n\n\n\nuse progress::{Progress, ProgressInfo, ProgressMessage};\n\nuse sync::Stats;\n\n\n\npub struct ProgressWorker {\n\n input: Receiver<ProgressMessage>,\n\n progress_info: Box<ProgressInfo + Send>,\n\n}\n\n\n\nimpl ProgressWorker {\n\n pub fn new(\n\n input: Receiver<ProgressMessage>,\n\n progress_info: Box<ProgressInfo + Send>,\n\n ) -> ProgressWorker {\n\n ProgressWorker {\n\n input,\n\n progress_info,\n\n }\n", "file_path": "src/workers/progress_worker.rs", "rank": 63, "score": 2.5591392057925395 }, { "content": " options: SyncOptions,\n\n progress_info: Box<ProgressInfo + Send>,\n\n}\n\n\n\nimpl Syncer {\n\n pub fn new(\n\n source: &Path,\n\n destination: &Path,\n\n options: SyncOptions,\n\n progress_info: Box<ProgressInfo + Send>,\n\n ) -> Syncer {\n\n Syncer {\n\n source: source.to_path_buf(),\n\n destination: destination.to_path_buf(),\n\n progress_info,\n\n options,\n\n }\n\n }\n\n\n\n pub fn sync(self) -> Result<Stats, String> {\n", "file_path": "src/sync.rs", "rank": 64, "score": 2.5071407981379012 }, { "content": " source: &Path,\n\n destination: &Path,\n\n input: Receiver<Entry>,\n\n output: Sender<ProgressMessage>,\n\n ) -> SyncWorker {\n\n SyncWorker {\n\n source: source.to_path_buf(),\n\n destination: destination.to_path_buf(),\n\n input,\n\n output,\n\n }\n\n }\n\n\n\n pub fn start(self, opts: SyncOptions) -> fsops::FSResult<()> {\n\n for entry in self.input.iter() {\n\n let sync_outcome = self.sync(&entry, opts)?;\n\n let progress = ProgressMessage::DoneSyncing(sync_outcome);\n\n self.output.send(progress).unwrap();\n\n }\n\n Ok(())\n", "file_path": "src/workers/sync_worker.rs", "rank": 65, "score": 2.3888701083987693 }, { "content": "use fsops::SyncOutcome;\n\nuse sync::Stats;\n\n\n\n#[doc(hidden)]\n\npub enum ProgressMessage {\n\n DoneSyncing(SyncOutcome),\n\n StartSync(String),\n\n Todo {\n\n num_files: u64,\n\n total_size: usize,\n\n },\n\n Syncing {\n\n description: String,\n\n size: usize,\n\n done: usize,\n\n },\n\n}\n\n\n\npub struct Progress {\n\n /// Name of the file being transferred\n", "file_path": "src/progress.rs", "rank": 66, "score": 2.216843461608341 }, { "content": " let dest_target = dest_target.unwrap();\n\n if dest_target != src_target {\n\n let rm_result = fs::remove_file(dest.path());\n\n if let Err(e) = rm_result {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\n\n \"Could not remove {} while updating link\",\n\n dest.description()\n\n ),\n\n ));\n\n }\n\n outcome = SyncOutcome::SymlinkUpdated;\n\n } else {\n\n return Ok(SyncOutcome::UpToDate);\n\n }\n\n }\n\n Some(false) => {\n\n // Never safe to delete\n\n return Err(FSError::from_description(&format!(\n", "file_path": "src/fsops.rs", "rank": 67, "score": 1.2708599884060736 }, { "content": " e,\n\n &format!(\"Could not open {} for writing\", dest_path.to_string_lossy()),\n\n ));\n\n }\n\n let mut dest_file = dest_file.unwrap();\n\n let mut buffer = vec![0; BUFFER_SIZE];\n\n loop {\n\n let num_read = src_file.read(&mut buffer);\n\n if let Err(e) = num_read {\n\n return Err(FSError::from_io_error(\n\n e,\n\n &format!(\"Could not read from {}\", src.description()),\n\n ));\n\n }\n\n\n\n let num_read = num_read.unwrap();\n\n if num_read == 0 {\n\n break;\n\n }\n\n let write_result = dest_file.write_all(&buffer[0..num_read]);\n", "file_path": "src/fsops.rs", "rank": 68, "score": 1.1911455242052433 }, { "content": " pub current_file: String,\n\n /// Number of bytes transfered for the current file\n\n pub file_done: usize,\n\n /// Size of the current file (in bytes)\n\n pub file_size: usize,\n\n /// Number of bytes transfered since the start\n\n pub total_done: usize,\n\n /// Estimated total size of the transfer (this may change during transfer)\n\n pub total_size: usize,\n\n /// Index of the current file in the list of all files to transfer\n\n pub index: usize,\n\n /// Total number of files to transfer\n\n pub num_files: usize,\n\n /// Estimated time remaining for the transfer, in seconds\n\n pub eta: usize,\n\n}\n\n\n\n/// Trait for implementing rusync progress details\n", "file_path": "src/progress.rs", "rank": 69, "score": 1.1241001125411758 }, { "content": " let index_width = index.to_string().len();\n\n let num_files = progress.num_files;\n\n let num_files_width = num_files.to_string().len();\n\n let widgets_width = percent_width + index_width + num_files_width + eta_width;\n\n let num_separators = 5;\n\n let line_width = get_terminal_width();\n\n let file_width = line_width - widgets_width - num_separators - 1;\n\n let mut current_file = progress.current_file.clone();\n\n current_file.truncate(file_width as usize);\n\n let current_file = format!(\n\n \"{filename:<pad$}\",\n\n pad = file_width as usize,\n\n filename = current_file\n\n );\n\n let file_percent = ((progress.file_done * 100) as usize) / progress.file_size;\n\n print!(\n\n \"{:>3}% {}/{} {} {:<}\\r\",\n\n file_percent, index, num_files, current_file, eta_str\n\n );\n\n let _ = io::stdout().flush();\n", "file_path": "src/console_info.rs", "rank": 70, "score": 0.9928673928271947 } ]
Rust
src/caret/movement.rs
jamessral/sodium
f98a942348861398e74457ded693e57b86d31fd5
use edit::buffer::TextBuffer; use state::editor::Editor; impl Editor { #[inline] pub fn goto(&mut self, (x, y): (usize, usize)) { self.cursor_mut().y = y; self.cursor_mut().x = x; } #[inline] pub fn previous(&self, n: usize) -> Option<(usize, usize)> { self.before(n, self.pos()) } #[inline] pub fn next(&self, n: usize) -> Option<(usize, usize)> { self.after(n, self.pos()) } #[inline] pub fn after(&self, n: usize, (x, y): (usize, usize)) -> Option<(usize, usize)> { if x + n < self.buffers.current_buffer()[y].len() { Some((x + n, y)) } else { if y + 1 >= self.buffers.current_buffer().len() { None } else { let mut mv = n + x - self.buffers.current_buffer()[y].len(); let mut ry = y + 1; loop { if mv < self.buffers.current_buffer()[ry].len() { return Some((mv, ry)); } else { if ry + 1 < self.buffers.current_buffer().len() { mv -= self.buffers.current_buffer()[ry].len(); ry += 1; } else { return None; } } } } } } #[inline] pub fn before(&self, n: usize, (x, y): (usize, usize)) -> Option<(usize, usize)> { if x >= n { Some((x - n, y)) } else { if y == 0 { None } else { let mut mv = n - x - 1; let mut ry = y - 1; loop { if mv <= self.buffers.current_buffer()[ry].len() { return Some((self.buffers.current_buffer()[ry].len() - mv, ry)); } else { if ry > 0 && mv >= self.buffers.current_buffer()[ry].len() { mv -= self.buffers.current_buffer()[ry].len(); ry -= 1; } else if ry == 0 { return None; } } } } } } #[inline] pub fn right(&self, n: usize, tight: bool) -> (usize, usize) { self.bound_hor((self.x() + n, self.y()), tight) } #[inline] pub fn right_unbounded(&self, n: usize) -> (isize, isize) { ((self.x() + n) as isize, self.y() as isize) } #[inline] pub fn left(&self, n: usize) -> (usize, usize) { if n <= self.x() { (self.x() - n, self.y()) } else { (0, self.y()) } } #[inline] pub fn left_unbounded(&self, n: usize) -> (isize, isize) { (self.x() as isize - n as isize, self.y() as isize) } #[inline] pub fn up(&self, n: usize) -> (usize, usize) { if n <= self.y() { (self.cursor().x, self.y() - n) } else { (self.cursor().x, 0) } } #[inline] pub fn up_unbounded(&self, n: usize) -> (isize, isize) { (self.cursor().x as isize, self.y() as isize - n as isize) } #[inline] pub fn down(&self, n: usize) -> (usize, usize) { self.bound_ver((self.cursor().x, self.y() + n)) } #[inline] pub fn down_unbounded(&self, n: usize) -> (isize, isize) { (self.cursor().x as isize, self.y() as isize + n as isize) } pub fn next_ocur(&self, c: char, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); for (i, ch) in self.buffers.current_buffer()[self.y()] .chars() .skip(x) .enumerate() { if ch == c { if i > 0 { dn += 1; if dn == n { x += i; return Some(x); } } } } None } pub fn previous_ocur(&self, c: char, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); let y = self.y(); for (i, ch) in self.buffers.current_buffer()[y] .chars() .rev() .skip(self.buffers.current_buffer()[y].len() - x) .enumerate() { if ch == c { dn += 1; if dn == n { x -= i + 1; return Some(x); } } } None } pub fn _next_word_forward(&self, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); for (i, ch) in self.buffers.current_buffer()[self.y()] .chars() .skip(x) .enumerate() { if ch.is_whitespace() { dn += 1; if dn == n { x += i + 1; return Some(x); } } } None } }
use edit::buffer::TextBuffer; use state::editor::Editor; impl Editor { #[inline] pub fn goto(&mut self, (x, y): (usize, usize)) { self.cursor_mut().y = y; self.cursor_mut().x = x; } #[inline] pub fn previous(&self, n: usize) -> Option<(usize, usize)> { self.before(n, self.pos()) } #[inline] pub fn next(&self, n: usize) -> Option<(usize, usize)> { self.after(n, self.pos()) } #[inline] pub fn after(&self, n: usize, (x, y): (usize, usize)) -> Option<(usize, usize)> { if x + n < self.buffers.current_buffer()[y].len() { Some((x + n, y)) } else { if y + 1 >= self.buffers.current_buffer().len() { None } else { let mut mv = n + x - self.buffers.current_buffer()[y].len(); let mut ry = y + 1; loop { if mv < self.buffers.current_buffer()[ry].len() { return Some((mv, ry)); } else { if ry + 1 < self.buffers.current_buffer().len() {
#[inline] pub fn before(&self, n: usize, (x, y): (usize, usize)) -> Option<(usize, usize)> { if x >= n { Some((x - n, y)) } else { if y == 0 { None } else { let mut mv = n - x - 1; let mut ry = y - 1; loop { if mv <= self.buffers.current_buffer()[ry].len() { return Some((self.buffers.current_buffer()[ry].len() - mv, ry)); } else { if ry > 0 && mv >= self.buffers.current_buffer()[ry].len() { mv -= self.buffers.current_buffer()[ry].len(); ry -= 1; } else if ry == 0 { return None; } } } } } } #[inline] pub fn right(&self, n: usize, tight: bool) -> (usize, usize) { self.bound_hor((self.x() + n, self.y()), tight) } #[inline] pub fn right_unbounded(&self, n: usize) -> (isize, isize) { ((self.x() + n) as isize, self.y() as isize) } #[inline] pub fn left(&self, n: usize) -> (usize, usize) { if n <= self.x() { (self.x() - n, self.y()) } else { (0, self.y()) } } #[inline] pub fn left_unbounded(&self, n: usize) -> (isize, isize) { (self.x() as isize - n as isize, self.y() as isize) } #[inline] pub fn up(&self, n: usize) -> (usize, usize) { if n <= self.y() { (self.cursor().x, self.y() - n) } else { (self.cursor().x, 0) } } #[inline] pub fn up_unbounded(&self, n: usize) -> (isize, isize) { (self.cursor().x as isize, self.y() as isize - n as isize) } #[inline] pub fn down(&self, n: usize) -> (usize, usize) { self.bound_ver((self.cursor().x, self.y() + n)) } #[inline] pub fn down_unbounded(&self, n: usize) -> (isize, isize) { (self.cursor().x as isize, self.y() as isize + n as isize) } pub fn next_ocur(&self, c: char, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); for (i, ch) in self.buffers.current_buffer()[self.y()] .chars() .skip(x) .enumerate() { if ch == c { if i > 0 { dn += 1; if dn == n { x += i; return Some(x); } } } } None } pub fn previous_ocur(&self, c: char, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); let y = self.y(); for (i, ch) in self.buffers.current_buffer()[y] .chars() .rev() .skip(self.buffers.current_buffer()[y].len() - x) .enumerate() { if ch == c { dn += 1; if dn == n { x -= i + 1; return Some(x); } } } None } pub fn _next_word_forward(&self, n: usize) -> Option<usize> { let mut dn = 0; let mut x = self.x(); for (i, ch) in self.buffers.current_buffer()[self.y()] .chars() .skip(x) .enumerate() { if ch.is_whitespace() { dn += 1; if dn == n { x += i + 1; return Some(x); } } } None } }
mv -= self.buffers.current_buffer()[ry].len(); ry += 1; } else { return None; } } } } } }
function_block-function_prefix_line
[ { "content": "/// Convert a usize tuple to isize\n\npub fn to_signed_pos((x, y): (usize, usize)) -> (isize, isize) {\n\n (x as isize, y as isize)\n\n}\n\n\n\nimpl Editor {\n\n /// Get the position of the current cursor, bounded\n\n #[inline]\n\n pub fn pos(&self) -> (usize, usize) {\n\n let cursor = self.cursor();\n\n self.bound((cursor.x, cursor.y), false)\n\n }\n\n\n\n #[inline]\n\n /// Get the X coordinate of the current cursor (bounded)\n\n pub fn x(&self) -> usize {\n\n self.pos().0\n\n }\n\n\n\n #[inline]\n\n /// Get the Y coordinate of the current cursor (bounded)\n", "file_path": "src/caret/position.rs", "rank": 0, "score": 77822.81053422717 }, { "content": "/// \"Invert\" a character, meaning that it gets swapped with it's counterpart, if no counterpart\n\n/// exists, swap the case of the character.\n\npub fn invert(c: char) -> char {\n\n match c {\n\n '<' => '>',\n\n '>' => '<',\n\n '&' => '|',\n\n '*' => '/',\n\n '(' => ')',\n\n ')' => '(',\n\n '+' => '-',\n\n '-' => '+',\n\n ';' => ':',\n\n ':' => ';',\n\n '\\\\' => '/',\n\n '/' => '\\\\',\n\n ',' => '.',\n\n '.' => ',',\n\n '\\'' => '\"',\n\n '\"' => '\\'',\n\n '[' => ']',\n\n ']' => '[',\n", "file_path": "src/edit/invert.rs", "rank": 1, "score": 52665.02791005266 }, { "content": "fn main() {\n\n self::state::editor::Editor::init();\n\n}\n", "file_path": "src/main.rs", "rank": 2, "score": 34359.754975726326 }, { "content": "/// A line in a buffer.\n\npub trait Line<'a> {\n\n /// The underlying iterator.\n\n type Iter: Iterator<Item = char> + 'a;\n\n\n\n /// Iterator over characters.\n\n fn chars_iter(&'a self) -> Self::Iter;\n\n}\n\n\n\nimpl<'a, T: AsRef<str>> Line<'a> for T {\n\n type Iter = Chars<'a>;\n\n\n\n fn chars_iter(&self) -> Chars {\n\n self.as_ref().chars()\n\n }\n\n}\n\n\n", "file_path": "src/edit/buffer.rs", "rank": 3, "score": 29770.30531803389 }, { "content": "/// A buffer structure\n\npub trait TextBuffer<'a> {\n\n /// The line type of the buffer.\n\n type Line: 'a + Line<'a>;\n\n /// The line iterator.\n\n type LineIter: Iterator<Item = &'a Self::Line>;\n\n\n\n /// Create a new empty split buffer\n\n fn new() -> Self;\n\n\n\n /// Convert a string to a split buffer\n\n fn from_str(s: &str) -> Self;\n\n\n\n /// Get the nth line in the buffer by option reference\n\n fn get_line(&self, n: usize) -> Option<&Self::Line>;\n\n\n\n /// Get the nth line in the buffer by optional mutable reference\n\n fn get_line_mut(&mut self, n: usize) -> Option<&mut Self::Line>;\n\n\n\n /// Remove the nth line and return it. Panics on out of bound.\n\n fn remove_line(&mut self, n: usize) -> Self::Line;\n", "file_path": "src/edit/buffer.rs", "rank": 4, "score": 28534.911633546853 }, { "content": " pub redraw_task: RedrawTask,\n\n /// The previous instruction\n\n pub previous_instruction: Option<Inst>,\n\n /// The character width in pixels\n\n pub char_width: usize,\n\n /// The character height in pixels\n\n pub char_height: usize,\n\n /// The files currently open\n\n pub files: Vec<String>,\n\n}\n\n\n\nimpl Editor {\n\n /// Create new default state editor\n\n pub fn init() {\n\n #[cfg(feature = \"orbital\")]\n\n let window =\n\n Window::new_flags(-1, -1, 700, 500, &\"Sodium\", &[WindowFlag::Resizable]).unwrap();\n\n\n\n #[cfg(feature = \"orbital\")]\n\n let mut editor = Editor {\n", "file_path": "src/state/editor.rs", "rank": 5, "score": 25798.219803796073 }, { "content": " editor.exec(inp);\n\n editor.status_bar.mode = editor.cursor().mode.to_string();\n\n editor.redraw();\n\n }\n\n }\n\n\n\n /// Hint the buffer about the cursor position.\n\n pub fn hint(&mut self) {\n\n let x = self.cursor().x;\n\n let y = self.cursor().y;\n\n\n\n self.buffers.current_buffer_mut().focus_hint_y(y);\n\n self.buffers.current_buffer_mut().focus_hint_x(x);\n\n }\n\n}\n", "file_path": "src/state/editor.rs", "rank": 6, "score": 25795.21031348979 }, { "content": "}\n\n\n\n/// Provides access to buffer manipulation functions.\n\npub struct BufferManager {\n\n buffers: Vec<Buffer>,\n\n current_buffer_index: usize,\n\n}\n\n\n\nimpl BufferManager {\n\n /// Create a new BufferManager with default values.\n\n pub fn new() -> BufferManager {\n\n BufferManager {\n\n buffers: vec![Buffer::new()],\n\n current_buffer_index: 0,\n\n }\n\n }\n\n\n\n /// Adds the specified buffer to the set of buffers and returns\n\n /// its index.\n\n pub fn new_buffer(&mut self, buffer: Buffer) -> usize {\n", "file_path": "src/state/editor.rs", "rank": 7, "score": 25795.11762696144 }, { "content": " self.buffers.push(buffer);\n\n\n\n self.buffers.len() - 1\n\n }\n\n\n\n /// Returns an iterator over the buffers.\n\n pub fn iter(&self) -> Iter<Buffer> {\n\n self.buffers.iter()\n\n }\n\n\n\n /// Gets the number of buffers.\n\n pub fn len(&self) -> usize {\n\n self.buffers.len()\n\n }\n\n\n\n /// Gets the index of the current buffer.\n\n pub fn current_buffer_index(&self) -> usize {\n\n self.current_buffer_index\n\n }\n\n\n", "file_path": "src/state/editor.rs", "rank": 8, "score": 25794.72903599625 }, { "content": " pub fn new() -> Buffer {\n\n Buffer {\n\n raw_buffer: SplitBuffer::new(),\n\n current_cursor: 0,\n\n cursors: vec![Cursor::new()],\n\n scroll_x: 0,\n\n scroll_y: 0,\n\n title: None,\n\n is_transient: false,\n\n }\n\n }\n\n}\n\n\n\nimpl From<SplitBuffer> for Buffer {\n\n fn from(b: SplitBuffer) -> Buffer {\n\n let mut info = Buffer::new();\n\n info.raw_buffer = b;\n\n\n\n info\n\n }\n", "file_path": "src/state/editor.rs", "rank": 9, "score": 25794.40271442588 }, { "content": "pub struct Buffer {\n\n /// The document\n\n pub raw_buffer: SplitBuffer,\n\n /// The current cursor\n\n pub current_cursor: u8,\n\n /// The cursors\n\n pub cursors: Vec<Cursor>,\n\n /// The x coordinate of the scroll\n\n pub scroll_x: usize,\n\n /// The y coordinate of the scroll\n\n pub scroll_y: usize,\n\n /// The title of the document\n\n pub title: Option<String>,\n\n /// True if the buffer is transient and should be deleted when\n\n /// it is no longer the current buffer.\n\n pub is_transient: bool,\n\n}\n\n\n\nimpl Buffer {\n\n /// Create a new Buffer with default values.\n", "file_path": "src/state/editor.rs", "rank": 10, "score": 25794.377477316953 }, { "content": "}\n\n\n\n/// The current state of the editor, including the file, the cursor, the scrolling info, etc.\n\npub struct Editor {\n\n /// The buffers and related state\n\n pub buffers: BufferManager,\n\n /// The window\n\n #[cfg(feature = \"orbital\")]\n\n pub window: Window,\n\n /// The status bar\n\n pub status_bar: StatusBar,\n\n /// The prompt\n\n pub prompt: Vec<String>,\n\n /// The prompt index, usually 0\n\n pub prompt_index: usize,\n\n /// The settings\n\n pub options: Options,\n\n /// The key state\n\n pub key_state: KeyState,\n\n /// Redraw\n", "file_path": "src/state/editor.rs", "rank": 11, "score": 25794.220008589356 }, { "content": " options: Options::new(),\n\n key_state: KeyState::new(),\n\n redraw_task: RedrawTask::None,\n\n previous_instruction: None,\n\n char_width: 8,\n\n char_height: 16,\n\n files: Vec::new(),\n\n };\n\n\n\n let mut files: Vec<String> = Vec::new();\n\n\n\n let mut args_iter = args().skip(1).peekable();\n\n loop {\n\n let arg = match args_iter.next() {\n\n Some(x) => x,\n\n None => break,\n\n };\n\n\n\n match arg.as_str() {\n\n \"--version\" => {\n", "file_path": "src/state/editor.rs", "rank": 12, "score": 25793.965882507822 }, { "content": " /// Delete the specified buffer\n\n pub fn delete_buffer(&mut self, n: usize) {\n\n assert!(n < self.buffers.len(), \"Buffer index out of bounds\");\n\n\n\n self.buffers.remove(n);\n\n\n\n if self.buffers.len() == 0 {\n\n self.buffers.push(Buffer::new());\n\n self.current_buffer_index = 0;\n\n } else if n == 0 {\n\n self.current_buffer_index = 0;\n\n } else if self.current_buffer_index >= n {\n\n self.current_buffer_index -= 1;\n\n }\n\n }\n\n\n\n /// Validates that the specifed buffer index is valid\n\n pub fn is_buffer_index_valid(&self, n: usize) -> bool {\n\n n < self.buffers.iter().filter(|b| !b.is_transient).count()\n\n }\n", "file_path": "src/state/editor.rs", "rank": 13, "score": 25793.016001347387 }, { "content": " /// Get a reference to the currently open buffer.\n\n pub fn current_buffer(&self) -> &SplitBuffer {\n\n &self.current_buffer_info().raw_buffer\n\n }\n\n\n\n /// Get a mutable reference to the currently open buffer.\n\n pub fn current_buffer_mut(&mut self) -> &mut SplitBuffer {\n\n &mut self.current_buffer_info_mut().raw_buffer\n\n }\n\n\n\n /// Get a reference to the currently open buffer information.\n\n pub fn current_buffer_info(&self) -> &Buffer {\n\n &self.buffers[self.current_buffer_index]\n\n }\n\n\n\n /// Get a mutable reference to the currently open buffer information.\n\n pub fn current_buffer_info_mut(&mut self) -> &mut Buffer {\n\n &mut self.buffers[self.current_buffer_index]\n\n }\n\n\n", "file_path": "src/state/editor.rs", "rank": 14, "score": 25792.888449511996 }, { "content": " buffers: BufferManager::new(),\n\n window: window,\n\n status_bar: StatusBar::new(),\n\n prompt: vec![String::new()],\n\n prompt_index: 0,\n\n options: Options::new(),\n\n key_state: KeyState::new(),\n\n redraw_task: RedrawTask::None,\n\n previous_instruction: None,\n\n char_width: 8,\n\n char_height: 16,\n\n files: Vec::new(),\n\n };\n\n\n\n #[cfg(not(feature = \"orbital\"))]\n\n let mut editor = Editor {\n\n buffers: BufferManager::new(),\n\n status_bar: StatusBar::new(),\n\n prompt: vec![String::new()],\n\n prompt_index: 0,\n", "file_path": "src/state/editor.rs", "rank": 15, "score": 25792.774712599916 }, { "content": " }\n\n }\n\n\n\n if files.len() > 0 {\n\n // TODO: open multiple files into separate buffers\n\n editor.open(&files[0]);\n\n }\n\n\n\n debugln!(editor, \"Starting Sodium\");\n\n\n\n editor.redraw();\n\n\n\n debugln!(editor, \"First redraw of the screen\");\n\n\n\n loop {\n\n let inp = editor.get_inst();\n\n if let Inst(_, Cmd { key: Key::Quit }) = inp {\n\n debugln!(editor, \"C'ya\");\n\n break;\n\n }\n", "file_path": "src/state/editor.rs", "rank": 16, "score": 25792.706782346322 }, { "content": " /// Switch the current buffer to the specified buffer\n\n pub fn switch_to(&mut self, n: usize) {\n\n debug_assert!(n < self.buffers.len(), \"Buffer index out of bounds\");\n\n\n\n // if the current view is transient, delete it\n\n let mut n = n;\n\n if self.current_buffer_info().is_transient {\n\n let index = self.current_buffer_index;\n\n self.delete_buffer(index);\n\n\n\n // if the current view is less than the view to switch to\n\n // then we need to account for the view we just removed\n\n if index <= n {\n\n n -= 1;\n\n }\n\n }\n\n\n\n self.current_buffer_index = n;\n\n }\n\n\n", "file_path": "src/state/editor.rs", "rank": 17, "score": 25792.443281039363 }, { "content": " }\n\n }\n\n args_iter.next();\n\n */\n\n }\n\n \"--\" => {\n\n // everything from here on out is a file\n\n for file in args_iter {\n\n files.push(file);\n\n }\n\n editor.files = files.clone();\n\n break;\n\n }\n\n _ => {\n\n {\n\n let mut arg_chars = arg.chars();\n\n if arg_chars.next() == Some('-') {\n\n for ch in arg_chars {\n\n match ch {\n\n 'R' => match editor.options.set(\"readonly\") {\n", "file_path": "src/state/editor.rs", "rank": 18, "score": 25791.481240644596 }, { "content": " println!(\n\n \"Sodium {}\",\n\n option_env!(\"CARGO_PKG_VERSION\").unwrap_or(\"unknown\")\n\n );\n\n return;\n\n }\n\n \"--help\" => {\n\n println!(\"{}\", HELP);\n\n return;\n\n }\n\n \"-u\" => {\n\n unimplemented!();\n\n /*\n\n match args_iter.peek() {\n\n Some(config) => {\n\n // this is the config file to use for this session\n\n println!(\"{}\", config);\n\n },\n\n None => {\n\n panic!(\"No config file specified.\");\n", "file_path": "src/state/editor.rs", "rank": 19, "score": 25791.217437766296 }, { "content": "use std::slice::Iter;\n\nuse edit::buffer::{SplitBuffer, TextBuffer};\n\nuse state::cursor::Cursor;\n\nuse io::graphics::StatusBar;\n\nuse io::key::{Cmd, Key};\n\nuse io::key_state::KeyState;\n\nuse state::options::Options;\n\nuse io::parse::Inst;\n\nuse io::redraw::RedrawTask;\n\n\n\n#[cfg(feature = \"orbital\")]\n\nuse orbclient::Window;\n\n#[cfg(feature = \"orbital\")]\n\nuse orbclient::WindowFlag;\n\n\n\nuse std::env::args;\n\n\n\nconst HELP: &'static str = include_str!(\"../../help.txt\");\n\n\n\n/// A SplitBuffer and related state\n", "file_path": "src/state/editor.rs", "rank": 20, "score": 25790.791035317154 }, { "content": " Ok(_) => debugln!(editor, \"Set readonly mode\"),\n\n Err(_) => println!(\"Could not set readonly mode\"),\n\n },\n\n 'h' => {\n\n println!(\"{}\", HELP);\n\n return;\n\n }\n\n _ => {\n\n unimplemented!();\n\n }\n\n }\n\n }\n\n\n\n continue;\n\n }\n\n }\n\n\n\n files.push(arg);\n\n editor.files = files.clone()\n\n }\n", "file_path": "src/state/editor.rs", "rank": 21, "score": 25790.08448553656 }, { "content": "fn get_buffers_description(buffers: &BufferManager) -> String {\n\n fn print_buffer(i: usize, b: &Buffer) -> String {\n\n let title = b.title.as_ref().map(|s| s.as_str()).unwrap_or(\"<No Title>\");\n\n\n\n format!(\"b{}\\t\\t\\t{}\", i, title)\n\n }\n\n\n\n let descriptions = buffers\n\n .iter()\n\n // don't include transient buffers like the one\n\n // this is going to be shown in\n\n .filter(|b| !b.is_transient)\n\n .enumerate()\n\n .map(|(i, b)| print_buffer(i, b))\n\n .collect::<Vec<_>>()\n\n .join(\"\\n\");\n\n\n\n format!(\n\n \"Buffers\\n=====================================\\n\\n{}\",\n\n descriptions\n\n )\n\n}\n", "file_path": "src/core/prompt.rs", "rank": 22, "score": 24076.239973720374 }, { "content": "\n\n if let Ok(number) = rest.parse::<usize>() {\n\n SwitchToBuffer {\n\n buffer_index: number,\n\n }\n\n } else {\n\n return None;\n\n }\n\n }\n\n _ => return None,\n\n })\n\n }\n\n}\n\n\n\nimpl Editor {\n\n /// Invoke a command in the prompt\n\n pub fn invoke<'a>(&mut self, cmd: PromptCommand<'a>) {\n\n use self::PromptCommand::*;\n\n\n\n match cmd {\n", "file_path": "src/core/prompt.rs", "rank": 26, "score": 15.638737971031054 }, { "content": "use caret::position::to_signed_pos;\n\nuse edit::buffer::TextBuffer;\n\nuse io::parse::Inst;\n\nuse state::editor::Editor;\n\n\n\nimpl Editor {\n\n /// Convert an instruction to a motion (new coordinate). Returns None if the instructions given\n\n /// either is invalid or has no movement.\n\n ///\n\n /// A motion is a namespace (i.e. non mode-specific set of commands), which represents\n\n /// movements. These are useful for commands which takes a motion as post-parameter, such as d.\n\n /// d deletes the text given by the motion following. Other commands can make use of motions,\n\n /// using this method.\n\n pub fn to_motion(&mut self, Inst(n, cmd): Inst) -> Option<(usize, usize)> {\n\n use io::key::Key::*;\n\n\n\n let y = self.y();\n\n\n\n match cmd.key {\n\n Char('h') => Some(self.left(n.d())),\n", "file_path": "src/caret/motion.rs", "rank": 28, "score": 14.331157662064959 }, { "content": "#[cfg(feature = \"orbital\")]\n\nuse edit::buffer::TextBuffer;\n\n#[cfg(feature = \"orbital\")]\n\nuse io::redraw::RedrawTask;\n\nuse state::editor::Editor;\n\n#[cfg(feature = \"orbital\")]\n\nuse state::mode::{Mode, PrimitiveMode};\n\n\n\n#[cfg(feature = \"orbital\")]\n\nuse orbclient::{Color, Renderer};\n\n\n\nuse std::iter;\n\n\n\n#[cfg(feature = \"orbital\")]\n\nimpl Editor {\n\n /// Redraw the window\n\n pub fn redraw(&mut self) {\n\n let w = self.window.width() as usize;\n\n let h = self.window.height() as usize;\n\n\n", "file_path": "src/io/graphics.rs", "rank": 29, "score": 13.094594899045275 }, { "content": "use edit::buffer::TextBuffer;\n\nuse state::editor::Editor;\n\n\n\nimpl Editor {\n\n /// Remove from a given motion (row based), i.e. if the motion given is to another line, all\n\n /// the lines from the current one to the one defined by the motion are removed. If the motion\n\n /// defines a position on the same line, only the characters from the current position to the\n\n /// motion's position are removed.\n\n pub fn remove_rb<'a>(&mut self, (x, y): (isize, isize)) {\n\n if y == (self.y() as isize) {\n\n let (x, y) = self.bound((x as usize, y as usize), false);\n\n // Single line mode\n\n let (a, b) = if self.x() > x {\n\n (x, self.x())\n\n } else {\n\n (self.x(), x)\n\n };\n\n for _ in self.buffers.current_buffer_mut()[y].drain(a..b) {}\n\n } else {\n\n let (_, y) = self.bound((x as usize, y as usize), true);\n", "file_path": "src/edit/selection.rs", "rank": 30, "score": 12.906005417274987 }, { "content": " y: 0,\n\n mode: Mode::Command(CommandMode::Normal),\n\n }\n\n }\n\n}\n\n\n\nimpl Editor {\n\n /// Get the character under the cursor\n\n #[inline]\n\n pub fn current(&self) -> Option<char> {\n\n let (x, y) = self.pos();\n\n match self.buffers.current_buffer()[y].chars().nth(x) {\n\n Some(c) => Some(c),\n\n None => None,\n\n }\n\n }\n\n\n\n /// Get the current cursor\n\n #[inline]\n\n pub fn cursor(&self) -> &Cursor {\n", "file_path": "src/state/cursor.rs", "rank": 31, "score": 12.663236437184397 }, { "content": "use edit::buffer::TextBuffer;\n\nuse state::cursor::Cursor;\n\nuse state::editor::Editor;\n\nuse io::redraw::RedrawTask;\n\n\n\nimpl Editor {\n\n /// Delete a character.\n\n #[inline]\n\n pub fn delete(&mut self) {\n\n let &Cursor { x, y, .. } = self.cursor();\n\n if x == self.buffers.current_buffer()[y].len() {\n\n if y + 1 < self.buffers.current_buffer().len() {\n\n let s = self.buffers.current_buffer_mut().remove_line(y + 1);\n\n self.buffers.current_buffer_mut()[y].push_str(&s);\n\n self.redraw_task = RedrawTask::Lines(y..y + 1);\n\n }\n\n } else if x < self.buffers.current_buffer()[y].len() {\n\n self.buffers.current_buffer_mut()[y].remove(x);\n\n self.redraw_task = RedrawTask::LinesAfter(y);\n\n }\n", "file_path": "src/edit/delete.rs", "rank": 32, "score": 12.403885767869024 }, { "content": "use state::editor::Editor;\n\n\n\nimpl Editor {\n\n /// Invert n characters next to the cursor in the buffer.\n\n pub fn invert_chars(&mut self, n: usize) {\n\n for _ in 0..n {\n\n let (x, y) = self.pos();\n\n let current = self.current();\n\n\n\n if let Some(cur) = current {\n\n self.buffers.current_buffer_mut()[y].remove(x);\n\n self.buffers.current_buffer_mut()[y].insert(x, invert(cur));\n\n }\n\n if let Some(m) = self.next(1) {\n\n self.goto(m);\n\n }\n\n }\n\n\n\n self.hint();\n\n }\n\n}\n\n\n\n/// \"Invert\" a character, meaning that it gets swapped with it's counterpart, if no counterpart\n\n/// exists, swap the case of the character.\n", "file_path": "src/edit/invert.rs", "rank": 33, "score": 12.331150388095118 }, { "content": "use state::editor::Editor;\n\nuse state::mode::{CommandMode, Mode};\n\n\n\n#[derive(Clone)]\n\n/// A cursor, i.e. a state defining a mode, and a position. The cursor does not define the content\n\n/// of the current file.\n\npub struct Cursor {\n\n /// The x coordinate of the cursor\n\n pub x: usize,\n\n /// The y coordinate of the cursor\n\n pub y: usize,\n\n /// The mode of the cursor\n\n pub mode: Mode,\n\n}\n\n\n\nimpl Cursor {\n\n /// Create a new default cursor\n\n pub fn new() -> Cursor {\n\n Cursor {\n\n x: 0,\n", "file_path": "src/state/cursor.rs", "rank": 34, "score": 12.311096060736155 }, { "content": "use edit::buffer::{SplitBuffer, TextBuffer};\n\nuse state::editor::{Buffer, Editor};\n\nuse std::fs::File;\n\nuse std::io::{Read, Write};\n\n\n\n/// The status of a file IO operation.\n\npub enum FileStatus {\n\n /// Oll fino.\n\n Ok,\n\n /// File not found.\n\n NotFound,\n\n /// Other error.\n\n Other,\n\n}\n\n\n\nimpl Editor {\n\n /// Open a file.\n\n pub fn open(&mut self, path: &str) -> FileStatus {\n\n if let Some(mut file) = File::open(path).ok() {\n\n let mut con = String::new();\n", "file_path": "src/io/file.rs", "rank": 35, "score": 12.274749207569664 }, { "content": " /// Not given (the user have not defined any numeral parameter to this command)\n\n Null,\n\n}\n\nimpl Parameter {\n\n /// Either unwrap the Int(n) to n or fallback to a given value\n\n #[inline]\n\n pub fn or(self, fallback: usize) -> usize {\n\n if let Parameter::Int(n) = self {\n\n n\n\n } else {\n\n fallback\n\n }\n\n }\n\n /// Fallback to one (default)\n\n #[inline]\n\n pub fn d(self) -> usize {\n\n self.or(1)\n\n }\n\n}\n\n\n", "file_path": "src/io/parse.rs", "rank": 36, "score": 11.201116102910978 }, { "content": "use state::editor::Editor;\n\nuse io::parse::{Inst, Parameter};\n\nuse state::mode::{CommandMode, Mode, PrimitiveMode};\n\nuse edit::insert::{InsertMode, InsertOptions};\n\nuse io::redraw::RedrawTask;\n\nuse edit::buffer::TextBuffer;\n\nuse core::prompt::PromptCommand;\n\n\n\n// TODO: Move the command definitions outta here\n\nimpl Editor {\n\n /// Execute an instruction\n\n pub fn exec(&mut self, Inst(para, cmd): Inst) {\n\n use io::key::Key::*;\n\n use state::mode::Mode::*;\n\n use state::mode::PrimitiveMode::*;\n\n use state::mode::CommandMode::*;\n\n\n\n let n = para.d();\n\n let bef = self.pos();\n\n let mut mov = false;\n", "file_path": "src/core/exec.rs", "rank": 37, "score": 10.457569027079971 }, { "content": " c,\n\n Color::rgb(255, 255, 255),\n\n );\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[cfg(not(feature = \"orbital\"))]\n\nimpl Editor {\n\n /// Redraw the window\n\n pub fn redraw(&mut self) {}\n\n /// Redraw the status bar\n\n pub fn redraw_status_bar(&mut self) {}\n\n}\n\n\n\n/// The statubar (showing various info about the current state of the editor)\n\npub struct StatusBar {\n\n /// The current mode\n\n pub mode: &'static str,\n", "file_path": "src/io/graphics.rs", "rank": 39, "score": 10.437534365933466 }, { "content": " } else {\n\n (x, y)\n\n }\n\n }\n\n\n\n /// Bound horizontally, i.e. don't change the vertical axis only make sure that the horizontal\n\n /// axis is bounded.\n\n #[inline]\n\n pub fn bound_hor(&self, (x, y): (usize, usize), tight: bool) -> (usize, usize) {\n\n (self.bound((x, y), tight).0, y)\n\n }\n\n /// Bound vertically, i.e. don't change the horizontal axis only make sure that the vertical\n\n /// axis is bounded.\n\n #[inline]\n\n pub fn bound_ver(&self, (x, mut y): (usize, usize)) -> (usize, usize) {\n\n // Is this premature optimization? Yes, yes it is!\n\n y = if y > self.buffers.current_buffer().len() - 1 {\n\n self.buffers.current_buffer().len() - 1\n\n } else {\n\n y\n\n };\n\n\n\n (x, y)\n\n }\n\n}\n", "file_path": "src/caret/position.rs", "rank": 40, "score": 9.925077493453426 }, { "content": " pub fn y(&self) -> usize {\n\n self.pos().1\n\n }\n\n\n\n /// Convert a position value to a bounded position value\n\n #[inline]\n\n pub fn bound(&self, (x, mut y): (usize, usize), tight: bool) -> (usize, usize) {\n\n y = if y >= self.buffers.current_buffer().len() {\n\n self.buffers.current_buffer().len() - 1\n\n } else {\n\n y\n\n };\n\n\n\n let ln = self.buffers.current_buffer()[y].len() + if tight { 0 } else { 1 };\n\n if x >= ln {\n\n if ln == 0 {\n\n (0, y)\n\n } else {\n\n (ln - 1, y)\n\n }\n", "file_path": "src/caret/position.rs", "rank": 41, "score": 9.878145183615988 }, { "content": "impl Editor {\n\n /// Get the next character input. Useful for commands taking a character as post-parameter,\n\n /// such as r (replace).\n\n pub fn get_char(&mut self) -> char {\n\n #[cfg(feature = \"orbital\")]\n\n loop {\n\n for event in self.window.events() {\n\n match event.to_option() {\n\n EventOption::Key(k) => if let Some(Key::Char(c)) = self.key_state.feed(k) {\n\n self.status_bar.cmd.push(c);\n\n self.redraw_task = RedrawTask::StatusBar;\n\n return c;\n\n },\n\n _ => {}\n\n }\n\n }\n\n }\n\n #[cfg(not(feature = \"orbital\"))]\n\n '\\0'\n\n }\n", "file_path": "src/io/parse.rs", "rank": 42, "score": 9.84355640187682 }, { "content": "use io::key::{Cmd, Key};\n\n#[cfg(feature = \"orbital\")]\n\nuse io::redraw::RedrawTask;\n\nuse state::editor::Editor;\n\n#[cfg(feature = \"orbital\")]\n\nuse state::mode::Mode;\n\n\n\n#[cfg(feature = \"orbital\")]\n\nuse orbclient::EventOption;\n\n\n\n#[derive(Copy, Clone)]\n\n/// An instruction, i.e. a command and a numeral parameter\n\npub struct Inst(pub Parameter, pub Cmd);\n\n\n\n/// A numeral parameter, i.e. a number (or nothing) given before a command (toghether making an\n\n/// instruction)\n\n#[derive(Copy, Clone)]\n\npub enum Parameter {\n\n /// An integer as parameter\n\n Int(usize),\n", "file_path": "src/io/parse.rs", "rank": 43, "score": 9.718762376339477 }, { "content": "use edit::buffer::TextBuffer;\n\nuse state::editor::Editor;\n\n\n\n/// Convert a usize tuple to isize\n", "file_path": "src/caret/position.rs", "rank": 44, "score": 9.676473713064171 }, { "content": "\n\n /// Insert line at n. Panics on out of bound.\n\n fn insert_line(&mut self, n: usize, line: Self::Line);\n\n\n\n /// Convert a vector of lines to a split buffer\n\n fn from_lines(vec: &[Self::Line]) -> SplitBuffer;\n\n\n\n /// Give a hint on where the operations are most frequent (i.e. where the cursor is). X value.\n\n fn focus_hint_x(&mut self, x: usize);\n\n\n\n /// Give a hint on where the operations are most frequent (i.e. where the cursor is). Y value.\n\n fn focus_hint_y(&mut self, y: usize);\n\n\n\n /// Get the number of lines in the buffer.\n\n fn len(&self) -> usize;\n\n\n\n /// Get an iterator over the lines in the buffer.\n\n fn lines(&'a self) -> Self::LineIter;\n\n\n\n /// Get an iterator over the line starting from a certain line\n", "file_path": "src/edit/buffer.rs", "rank": 45, "score": 9.64048088044221 }, { "content": "use std::ops::Range;\n\n\n\n#[derive(Clone)]\n\n/// A task for the renderer for redrawing\n\npub enum RedrawTask {\n\n /// None redraw task.\n\n None,\n\n /// Redraw a range of lines.\n\n Lines(Range<usize>),\n\n /// Redraw the lines after a given line.\n\n LinesAfter(usize),\n\n /// Full screen redraw.\n\n Full,\n\n /// Status bar redraw.\n\n StatusBar,\n\n /// Move cursor.\n\n Cursor((usize, usize), (usize, usize)),\n\n}\n", "file_path": "src/io/redraw.rs", "rank": 47, "score": 9.581691895434606 }, { "content": " let buffer = self.buffers.current_buffer_info();\n\n buffer.cursors.get(buffer.current_cursor as usize).unwrap()\n\n }\n\n\n\n /// Get the current cursor mutably\n\n #[inline]\n\n pub fn cursor_mut(&mut self) -> &mut Cursor {\n\n let buffer = self.buffers.current_buffer_info_mut();\n\n buffer\n\n .cursors\n\n .get_mut(buffer.current_cursor as usize)\n\n .unwrap()\n\n }\n\n\n\n /// Go to next cursor\n\n #[inline]\n\n pub fn next_cursor(&mut self) {\n\n let buffer = self.buffers.current_buffer_info_mut();\n\n buffer.current_cursor =\n\n (buffer.current_cursor.wrapping_add(1)) % (buffer.cursors.len() as u8);\n", "file_path": "src/state/cursor.rs", "rank": 48, "score": 9.578825531240795 }, { "content": " }\n\n &ln[..len]\n\n } else {\n\n \"\"\n\n }\n\n }\n\n}\n\n\n\n\n\nimpl Index<usize> for SplitBuffer {\n\n type Output = String;\n\n\n\n fn index<'a>(&'a self, index: usize) -> &'a String {\n\n self.get_line(index).expect(\"Out of bound\")\n\n }\n\n}\n\nimpl IndexMut<usize> for SplitBuffer {\n\n fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut String {\n\n #[cfg(debug)]\n\n fn debug_check(b: &mut SplitBuffer) {\n", "file_path": "src/edit/buffer.rs", "rank": 50, "score": 9.340285884868216 }, { "content": " }\n\n }\n\n\n\n fn get_line(&self, n: usize) -> Option<&String> {\n\n if n < self.before.len() {\n\n Some(&self.before[n])\n\n } else if n < self.len() {\n\n let n = self.len() - 1 - n;\n\n Some(&self.after[n])\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n fn get_line_mut(&mut self, n: usize) -> Option<&mut String> {\n\n if n < self.before.len() {\n\n Some(&mut self.before[n])\n\n } else if n < self.len() {\n\n let n = self.len() - 1 - n;\n\n Some(&mut self.after[n])\n", "file_path": "src/edit/buffer.rs", "rank": 51, "score": 9.012376479071564 }, { "content": " Ok(())\n\n }\n\n None => Err(()),\n\n }\n\n }\n\n /// Unset a given option (mark it as inactive)\n\n pub fn unset(&mut self, name: &str) -> Result<(), ()> {\n\n match self.get_mut(name) {\n\n Some(x) => {\n\n *x = false;\n\n Ok(())\n\n }\n\n None => Err(()),\n\n }\n\n }\n\n /// Toggle a given option\n\n pub fn toggle(&mut self, name: &str) -> Result<(), ()> {\n\n match self.get_mut(name) {\n\n Some(x) => {\n\n *x = !*x;\n\n Ok(())\n\n }\n\n None => Err(()),\n\n }\n\n }\n\n}\n", "file_path": "src/state/options.rs", "rank": 52, "score": 8.792263082210072 }, { "content": "/// Editor options.\n\npub struct Options {\n\n /// Autoindent on line breaks?\n\n pub autoindent: bool,\n\n /// Debug mode.\n\n pub debug: bool,\n\n /// Highlight.\n\n pub highlight: bool,\n\n /// Line marker (dimmed background of the current line).\n\n pub line_marker: bool,\n\n /// enables read-only mode\n\n pub readonly: bool,\n\n /// Enable linenumbers\n\n pub line_numbers: bool,\n\n}\n\n\n\nimpl Options {\n\n /// Create new default options\n\n pub fn new() -> Self {\n\n Options {\n", "file_path": "src/state/options.rs", "rank": 54, "score": 8.538405673212543 }, { "content": "use edit::buffer::TextBuffer;\n\nuse io::key::Key;\n\nuse io::redraw::RedrawTask;\n\nuse state::editor::Editor;\n\n\n\n#[derive(Clone, PartialEq, Copy)]\n\n/// The type of the insert mode\n\npub enum InsertMode {\n\n /// Insert text (before the cursor)\n\n Insert,\n\n /// Replace text (on the cursor)\n\n Replace,\n\n}\n\n\n\n\n\n#[derive(Clone, PartialEq, Copy)]\n\n/// The insert options\n\npub struct InsertOptions {\n\n /// The mode type\n\n pub mode: InsertMode,\n", "file_path": "src/edit/insert.rs", "rank": 55, "score": 8.319291411720062 }, { "content": " Some((o, y))\n\n } else {\n\n None\n\n }\n\n }\n\n Char(c) => {\n\n self.status_bar.msg = format!(\"Motion not defined: '{}'\", c);\n\n self.redraw_status_bar();\n\n None\n\n }\n\n _ => {\n\n self.status_bar.msg = format!(\"Motion not defined\");\n\n None\n\n }\n\n }\n\n }\n\n /// Like to_motion() but does not bound to the text. Therefore it returns an isize, and in some\n\n /// cases it's a position which is out of bounds. This is useful when commands want to mesure\n\n /// the relative movement over the movement.\n\n pub fn to_motion_unbounded(&mut self, Inst(n, cmd): Inst) -> Option<(isize, isize)> {\n", "file_path": "src/caret/motion.rs", "rank": 56, "score": 7.909320073769678 }, { "content": "\n\nimpl SplitBuffer {\n\n fn up(&mut self) {\n\n self.after\n\n .push(self.before.pop().expect(\"Popped last element\"));\n\n }\n\n\n\n fn down(&mut self) {\n\n self.before\n\n .push(self.after.pop().expect(\"Popped last element\"));\n\n }\n\n\n\n fn y(&self) -> usize {\n\n self.before.len()\n\n }\n\n}\n\n\n\n// TODO remove\n\nimpl SplitBuffer {\n\n /// Convert the buffer to a string.\n", "file_path": "src/edit/buffer.rs", "rank": 57, "score": 7.785720164050533 }, { "content": "}\n\n\n\nimpl<'a> Iterator for SplitBufIter<'a> {\n\n type Item = &'a String;\n\n\n\n fn next(&mut self) -> Option<&'a String> {\n\n self.nth(1)\n\n }\n\n\n\n fn nth(&mut self, n: usize) -> Option<&'a String> {\n\n let res = self.buffer.get_line(self.line);\n\n self.line += n;\n\n\n\n res\n\n }\n\n\n\n fn count(self) -> usize {\n\n self.buffer.len()\n\n }\n\n}\n", "file_path": "src/edit/buffer.rs", "rank": 58, "score": 7.752072287621962 }, { "content": " } else {\n\n None\n\n }\n\n }\n\n\n\n fn remove_line(&mut self, n: usize) -> String {\n\n if n < self.before.len() {\n\n self.before.remove(n)\n\n } else if n < self.len() {\n\n let n = n - self.before.len();\n\n let ret = self.after.remove(n);\n\n if n == 0 {\n\n self.up();\n\n }\n\n ret\n\n } else {\n\n panic!(\"Out of bound\");\n\n }\n\n }\n\n\n", "file_path": "src/edit/buffer.rs", "rank": 59, "score": 7.693488804981907 }, { "content": " autoindent: true,\n\n debug: true, // TODO: Let this be `true` only in debug compilation cfg\n\n highlight: true,\n\n line_marker: true,\n\n readonly: false,\n\n line_numbers: false,\n\n }\n\n }\n\n\n\n /// Get the given option as a mutable reference\n\n pub fn get_mut(&mut self, name: &str) -> Option<&mut bool> {\n\n match name {\n\n \"autoindent\" | \"ai\" => Some(&mut self.autoindent),\n\n \"debug\" | \"debug_mode\" => Some(&mut self.debug),\n\n \"highlight\" | \"hl\" => Some(&mut self.highlight),\n\n \"line_marker\" | \"linemarker\" | \"linemark\" | \"lm\" => Some(&mut self.line_marker),\n\n \"readonly\" | \"ro\" => Some(&mut self.readonly),\n\n \"line_numbers\" | \"ln\" => Some(&mut self.line_numbers),\n\n _ => None,\n\n }\n", "file_path": "src/state/options.rs", "rank": 61, "score": 7.481392750765254 }, { "content": "//! Sodium is a next generation Vi-like editor.\n\n\n\n#![feature(stmt_expr_attributes)]\n\n#![deny(warnings)]\n\n#![deny(missing_docs)]\n\n\n\n#[cfg(feature = \"orbital\")]\n\nextern crate orbclient;\n\n\n\n/// Core functionality.\n\n#[macro_use]\n\npub mod core;\n\n/// Carret primitives.\n\npub mod caret;\n\n/// Editing.\n\npub mod edit;\n\n/// Input/Output\n\npub mod io;\n\n/// State of the editor.\n\npub mod state;\n\n\n\n\n", "file_path": "src/main.rs", "rank": 62, "score": 7.449391983983249 }, { "content": "use io::file::FileStatus;\n\nuse io::redraw::RedrawTask;\n\nuse state::editor::{Buffer, BufferManager, Editor};\n\nuse edit::buffer::{SplitBuffer, TextBuffer};\n\n\n\nuse std::process::exit;\n\n\n\n/// Prompt mode commands.\n\npub enum PromptCommand<'a> {\n\n /// Set an option.\n\n Set {\n\n /// The option to set.\n\n option: &'a str,\n\n },\n\n /// Unset an option.\n\n Unset {\n\n /// The option to unset.\n\n option: &'a str,\n\n },\n\n /// Toggle an option.\n", "file_path": "src/core/prompt.rs", "rank": 63, "score": 7.427638316716003 }, { "content": " fn lines_from(&'a self, from: usize) -> Self::LineIter;\n\n\n\n /// Get the leading whitespaces of the nth line. Used for autoindenting.\n\n fn get_indent(&self, n: usize) -> &str;\n\n}\n\n\n\n\n\n/// The buffer data structure, that Sodium is using.\n\n///\n\n/// This structure consists of two \"subbuffers\", which are just vectors over lines (defined by\n\n/// Strings). The split is called a center.\n\n///\n\n/// The nearer a given operation is to the center, the better it performs.\n\n///\n\n/// The second buffer is in reverse order to get the particular efficiency we want.\n\npub struct SplitBuffer {\n\n before: Vec<String>,\n\n after: Vec<String>,\n\n #[cfg(debug)] _hinted_since_edit: bool,\n\n}\n", "file_path": "src/edit/buffer.rs", "rank": 64, "score": 7.40299073063662 }, { "content": "use edit::insert::InsertOptions;\n\n\n\n#[derive(Clone, PartialEq, Copy)]\n\n/// A mode. Modes determine which set of commands that will be used. Modes comes in two flavors:\n\npub enum Mode {\n\n /// A primitive mode. In this mode type, absolutely none preprocessing of the commands are\n\n /// done. Therefore the instruction will just be a command, without any form of numeral\n\n /// parameter. This is useful for modes such as insert, where commands don't take numeral\n\n /// parameters.\n\n Primitive(PrimitiveMode),\n\n /// Command mode. In this mode type input is collected into instructions, which are commands\n\n /// having a numeral parameter. This numeral parameter is useful for a number of things, such\n\n /// as repeation, line number, etc.\n\n Command(CommandMode),\n\n}\n\n\n\nimpl Mode {\n\n /// Convert the mode to string\n\n pub fn to_string(self) -> &'static str {\n\n use self::Mode::*;\n", "file_path": "src/state/mode.rs", "rank": 65, "score": 7.325355929747547 }, { "content": "}\n\n\n\nimpl Editor {\n\n /// Insert text under the current cursor.\n\n pub fn insert(&mut self, k: Key, InsertOptions { mode }: InsertOptions) {\n\n let (mut x, mut y) = self.pos();\n\n match (mode, k) {\n\n (InsertMode::Insert, Key::Char('\\n')) => {\n\n let first_part = self.buffers.current_buffer()[y][..x].to_owned();\n\n let second_part = self.buffers.current_buffer()[y][x..].to_owned();\n\n\n\n self.buffers.current_buffer_mut()[y] = first_part;\n\n\n\n let nl = if self.options.autoindent {\n\n self.buffers.current_buffer().get_indent(y).to_owned()\n\n } else {\n\n String::new()\n\n };\n\n let begin = nl.len();\n\n\n", "file_path": "src/edit/insert.rs", "rank": 66, "score": 7.308895486329041 }, { "content": "\n\nimpl<'a> DoubleEndedIterator for SplitBufIter<'a> {\n\n fn next_back(&mut self) -> Option<&'a String> {\n\n if self.line == 0 {\n\n None\n\n } else {\n\n self.line -= 1;\n\n self.buffer.get_line(self.line)\n\n }\n\n }\n\n}\n", "file_path": "src/edit/buffer.rs", "rank": 67, "score": 7.2933250685545685 }, { "content": " /// The current command\n\n pub cmd: String,\n\n /// A message (such as an error or other info to the user)\n\n pub msg: String,\n\n}\n\n\n\nimpl StatusBar {\n\n /// Create new status bar\n\n pub fn new() -> Self {\n\n StatusBar {\n\n mode: \"Normal\",\n\n cmd: String::new(),\n\n msg: \"Welcome to Sodium!\".to_string(),\n\n }\n\n }\n\n}\n", "file_path": "src/io/graphics.rs", "rank": 68, "score": 7.198999767849819 }, { "content": "\n\n self.hint();\n\n }\n\n\n\n /// Backspace.\n\n #[inline]\n\n pub fn backspace(&mut self) {\n\n let previous = self.previous(1);\n\n if let Some(p) = previous {\n\n self.goto(p);\n\n self.delete();\n\n } else {\n\n self.status_bar.msg = \"Can't delete file start\".to_owned();\n\n }\n\n }\n\n}\n", "file_path": "src/edit/delete.rs", "rank": 69, "score": 7.13074793613971 }, { "content": "/// The global editor state.\n\npub mod editor;\n\n/// Cursors.\n\n///\n\n/// A cursor contains various non-global information about the editor state. You can switch between\n\n/// cursor, for reusing older editor states.\n\npub mod cursor;\n\n/// Options and configuration of the editor.\n\npub mod options;\n\n/// Editor modes.\n\npub mod mode;\n", "file_path": "src/state/mod.rs", "rank": 70, "score": 7.0476231941083025 }, { "content": " }\n\n\n\n /// Go to previous cursor\n\n #[inline]\n\n pub fn prev_cursor(&mut self) {\n\n let buffer = self.buffers.current_buffer_info_mut();\n\n if buffer.current_cursor != 0 {\n\n buffer.current_cursor -= 1;\n\n } else {\n\n buffer.current_cursor = (buffer.cursors.len() - 1) as u8;\n\n }\n\n }\n\n}\n", "file_path": "src/state/cursor.rs", "rank": 71, "score": 7.021502908182285 }, { "content": "impl KeyState {\n\n /// Create a new default key state.\n\n pub fn new() -> KeyState {\n\n KeyState {\n\n ctrl: false,\n\n alt: false,\n\n shift: false,\n\n }\n\n }\n\n\n\n /// Feed the keystate with a new key input.\n\n #[cfg(feature = \"orbital\")]\n\n pub fn feed(&mut self, k: KeyEvent) -> Option<Key> {\n\n use orbclient::{K_ALT, K_CTRL, K_LEFT_SHIFT, K_RIGHT_SHIFT};\n\n\n\n let c = k.character;\n\n match c {\n\n '\\0' => {\n\n // \"I once lived here\" - bug\n\n match k.scancode {\n", "file_path": "src/io/key_state.rs", "rank": 72, "score": 6.861626378784354 }, { "content": " }\n\n scr_lines += 1;\n\n scr_chars = 0;\n\n if scr_lines > max_vert_chars {\n\n break;\n\n }\n\n }\n\n self.redraw_status_bar();\n\n self.redraw_task = RedrawTask::None;\n\n self.window.sync();\n\n }\n\n\n\n fn coords_to_window_coords(&mut self, point: (usize, usize), max_horz_chars: usize) -> (usize, usize) {\n\n let (_, scroll_y) = {\n\n let current_buffer = self.buffers.current_buffer_info();\n\n\n\n (current_buffer.scroll_x, current_buffer.scroll_y)\n\n };\n\n\n\n let to_y = point.1 - scroll_y;\n", "file_path": "src/io/graphics.rs", "rank": 73, "score": 6.59584726006071 }, { "content": " ListBuffers,\n\n /// Create a new empty buffer.\n\n CreateBuffer,\n\n /// Delete the current buffer.\n\n DeleteBuffer,\n\n /// Switch to the nth buffer.\n\n SwitchToBuffer {\n\n /// The index of the buffer to switch to.\n\n buffer_index: usize,\n\n },\n\n /// Display help in a new buffer.\n\n Help,\n\n /// Exit Sodium.\n\n Quit,\n\n}\n\n\n\nimpl<'a> PromptCommand<'a> {\n\n /// Parse a string to get a PromptCommand. If the parse fails,\n\n /// None is returned.\n\n pub fn parse(s: &'a str) -> Option<PromptCommand<'a>> {\n", "file_path": "src/core/prompt.rs", "rank": 74, "score": 6.474731898758504 }, { "content": " pub fn to_string(&self) -> String {\n\n self.lines().map(|x| x.to_owned() + \"\\n\").collect()\n\n }\n\n}\n\n\n\nimpl<'a> TextBuffer<'a> for SplitBuffer {\n\n type Line = String;\n\n type LineIter = SplitBufIter<'a>;\n\n\n\n fn new() -> Self {\n\n SplitBuffer {\n\n before: vec![String::new()],\n\n after: Vec::new(),\n\n }\n\n }\n\n\n\n fn from_str(s: &str) -> Self {\n\n SplitBuffer {\n\n before: s.lines().map(ToOwned::to_owned).collect(),\n\n after: Vec::new(),\n", "file_path": "src/edit/buffer.rs", "rank": 75, "score": 6.3862177806121 }, { "content": "#[cfg(feature = \"orbital\")]\n\nuse io::key::Key;\n\n#[cfg(feature = \"orbital\")]\n\nuse orbclient::KeyEvent;\n\n\n\n#[cfg(feature = \"ansi\")]\n\nuse std::io::Stdin;\n\n#[cfg(feature = \"ansi\")]\n\nuse std::io::prelude::*;\n\n\n\n/// Key state\n\npub struct KeyState {\n\n /// Ctrl modifier.\n\n pub ctrl: bool,\n\n /// Alt modifier.\n\n pub alt: bool,\n\n /// Shift modifier.\n\n pub shift: bool,\n\n}\n\n\n", "file_path": "src/io/key_state.rs", "rank": 76, "score": 6.257262956640411 }, { "content": " if b._hinted_since_edit {\n\n b._hinted_since_edit = false;\n\n } else {\n\n panic!(\"No focus hint given since last edit!\");\n\n }\n\n }\n\n\n\n #[cfg(not(debug))]\n\n fn debug_check(_: &mut SplitBuffer) {}\n\n\n\n debug_check(&mut *self);\n\n\n\n self.get_line_mut(index).expect(\"Out of bound\")\n\n }\n\n}\n\n\n\n/// A iterator over the lines of a split buffer\n\npub struct SplitBufIter<'a> {\n\n buffer: &'a SplitBuffer,\n\n line: usize,\n", "file_path": "src/edit/buffer.rs", "rank": 77, "score": 6.1258710504123535 }, { "content": "use std::cmp::min;\n\nuse std::ops::{Index, IndexMut};\n\nuse std::str::Chars;\n\n\n\n/// A line in a buffer.\n", "file_path": "src/edit/buffer.rs", "rank": 78, "score": 6.07998343369526 }, { "content": "/// Primitives for debugging.\n\n#[macro_use]\n\npub mod debug;\n\n\n\n/// Executing commands.\n\npub mod exec;\n\n\n\n/// The command prompt.\n\npub mod prompt;\n", "file_path": "src/core/mod.rs", "rank": 79, "score": 5.98337408409754 }, { "content": " }\n\n\n\n /// Get a given option\n\n pub fn get(&self, name: &str) -> Option<bool> {\n\n match name {\n\n \"autoindent\" | \"ai\" => Some(self.autoindent),\n\n \"debug\" | \"debug_mode\" => Some(self.debug),\n\n \"highlight\" | \"hl\" => Some(self.highlight),\n\n \"line_marker\" | \"linemarker\" | \"linemark\" | \"lm\" => Some(self.line_marker),\n\n \"readonly\" | \"ro\" => Some(self.readonly),\n\n \"line_numbers\" | \"ln\" => Some(self.line_numbers),\n\n _ => None,\n\n }\n\n }\n\n\n\n /// Set a given option (mark it as active)\n\n pub fn set(&mut self, name: &str) -> Result<(), ()> {\n\n match self.get_mut(name) {\n\n Some(x) => {\n\n *x = true;\n", "file_path": "src/state/options.rs", "rank": 80, "score": 5.975823662468733 }, { "content": "\n\n /// Get the next instruction, i.e. the next input of a command together with a numeral\n\n /// parameter.\n\n pub fn get_inst(&mut self) -> Inst {\n\n #[cfg(feature = \"orbital\")]\n\n {\n\n let mut n = 0;\n\n let mut unset = true;\n\n\n\n let mut key = Key::Null;\n\n self.status_bar.cmd = String::new();\n\n\n\n // self.status_bar.cmd = String::new();\n\n loop {\n\n for event in self.window.events() {\n\n match event.to_option() {\n\n EventOption::Key(key_event) => {\n\n if let Some(k) = self.key_state.feed(key_event) {\n\n let c = k.to_char();\n\n self.status_bar.cmd.push(c);\n", "file_path": "src/io/parse.rs", "rank": 81, "score": 5.822467723467332 }, { "content": "/// A primitive mode\n\npub enum PrimitiveMode {\n\n /// Insert mode. In this text is inserted\n\n Insert(InsertOptions),\n\n /// Prompt. In the prompt the user can give the editor commands, which often are more\n\n /// \"sentence-like\", i.e. they're not like commands in normal mode for example. These commands\n\n /// can be used for a number of things, such as configurating Sodium, or enabling/disabling\n\n /// options.\n\n Prompt,\n\n}\n", "file_path": "src/state/mode.rs", "rank": 82, "score": 5.500454675065342 }, { "content": " let vert_offset: usize = 0;\n\n\n\n let horz_offset: usize = if self.options.line_numbers {\n\n let len = self.buffers.current_buffer_info().raw_buffer.len();\n\n let mut ret: usize = 3;\n\n while len >= 10usize.pow((ret - 1) as u32) {\n\n ret += 1;\n\n }\n\n ret\n\n } else {\n\n 0\n\n };\n\n\n\n let max_vert_chars = h/self.char_height - 2 - vert_offset;\n\n let max_horz_chars = w/self.char_width - horz_offset;\n\n\n\n // Redraw window\n\n self.window.set(Color::rgb(25, 25, 25));\n\n\n\n let mut scr_lines: usize = 0;\n", "file_path": "src/io/graphics.rs", "rank": 83, "score": 5.499221724384197 }, { "content": " fn insert_line(&mut self, n: usize, line: String) {\n\n if n < self.before.len() {\n\n self.before.insert(n, line);\n\n } else if n <= self.len() {\n\n let n = self.len() - n;\n\n self.after.insert(n, line);\n\n } else {\n\n panic!(\"Out of bound\");\n\n }\n\n }\n\n\n\n fn from_lines(ln: &[String]) -> SplitBuffer {\n\n SplitBuffer {\n\n before: ln.to_owned(),\n\n after: Vec::new(),\n\n }\n\n }\n\n\n\n fn focus_hint_y(&mut self, y: usize) {\n\n if y < self.y() {\n", "file_path": "src/edit/buffer.rs", "rank": 85, "score": 5.448556750521095 }, { "content": "/// Motions.\n\n///\n\n/// A motion is a command defining some movement from point A to point B, these can be used in\n\n/// mulitple context, for example as argument for other commands.\n\npub mod motion;\n\n/// Movement.\n\npub mod movement;\n\n/// Calculations and bounding of positions.\n\npub mod position;\n", "file_path": "src/caret/mod.rs", "rank": 86, "score": 5.299418029507176 }, { "content": "/// Partial redraws.\n\npub mod redraw;\n\n/// Parsing of input commands.\n\npub mod parse;\n\n/// The \"key state\" of the editor.\n\n///\n\n/// The key state contains information about the current state of modifiers.\n\npub mod key_state;\n\n/// Key input and parsing.\n\npub mod key;\n\n/// Graphics and rendering.\n\npub mod graphics;\n\n/// Loading and writing files.\n\npub mod file;\n", "file_path": "src/io/mod.rs", "rank": 87, "score": 5.2525695529424565 }, { "content": " for _ in 0..min(self.y() - y, self.before.len()) {\n\n self.up();\n\n }\n\n } else if y > self.y() {\n\n for _ in 0..min(y - self.y(), self.after.len()) {\n\n self.down();\n\n }\n\n } else if y >= self.len() {\n\n panic!(\"Out of bound\");\n\n }\n\n }\n\n\n\n fn focus_hint_x(&mut self, _: usize) {}\n\n\n\n fn len(&self) -> usize {\n\n self.before.len() + self.after.len()\n\n }\n\n\n\n fn lines(&'a self) -> SplitBufIter<'a> {\n\n SplitBufIter {\n", "file_path": "src/edit/buffer.rs", "rank": 88, "score": 5.133709010536517 }, { "content": " buffer: self,\n\n line: 0,\n\n }\n\n }\n\n\n\n fn lines_from(&'a self, from: usize) -> SplitBufIter<'a> {\n\n SplitBufIter {\n\n buffer: self,\n\n line: from,\n\n }\n\n }\n\n\n\n fn get_indent(&self, n: usize) -> &str {\n\n if let Some(ln) = self.get_line(n) {\n\n let mut len = 0;\n\n for c in ln.chars() {\n\n match c {\n\n '\\t' | ' ' => len += 1,\n\n _ => break,\n\n }\n", "file_path": "src/edit/buffer.rs", "rank": 89, "score": 4.950124458662517 }, { "content": " self.buffers.current_buffer_mut()[y].remove(x);\n\n self.buffers.current_buffer_mut()[y].insert(x, c);\n\n }\n\n }\n\n let next = self.next(1);\n\n if let Some(p) = next {\n\n self.goto(p);\n\n }\n\n self.redraw_task = RedrawTask::Lines(y..y + 1);\n\n }\n\n _ => {}\n\n }\n\n\n\n self.hint();\n\n }\n\n\n\n /// Insert a string\n\n pub fn insert_str(&mut self, txt: String, opt: InsertOptions) {\n\n for c in txt.chars() {\n\n self.insert(Key::Char(c), opt);\n\n }\n\n }\n\n}\n", "file_path": "src/edit/insert.rs", "rank": 90, "score": 4.632112335567376 }, { "content": " use self::PrimitiveMode::*;\n\n use self::CommandMode::*;\n\n match self {\n\n Command(Normal) => \"Normal\",\n\n Primitive(Insert(_)) => \"Insert\",\n\n Primitive(Prompt) => \"Prompt\",\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, PartialEq, Copy)]\n\n/// A command mode\n\npub enum CommandMode {\n\n // Visual(VisualOptions),\n\n /// Normal mode. The default mode, which can be used for most common commands and switching to\n\n /// other modes.\n\n Normal,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Copy)]\n", "file_path": "src/state/mode.rs", "rank": 91, "score": 4.6217252205664945 }, { "content": " break;\n\n }\n\n }\n\n self.buffers.current_buffer_info_mut().scroll_y = result_y;\n\n }\n\n\n\n /// Redraw the status bar\n\n pub fn redraw_status_bar(&mut self) {\n\n let h = self.window.height();\n\n let w = self.window.width();\n\n let mode = self.cursor().mode;\n\n self.window.rect(\n\n 0,\n\n h as i32 - 18 - {\n\n if mode == Mode::Primitive(PrimitiveMode::Prompt) {\n\n 18\n\n } else {\n\n 0\n\n }\n\n },\n", "file_path": "src/io/graphics.rs", "rank": 92, "score": 4.468146090378231 }, { "content": " let _ = file.read_to_string(&mut con);\n\n\n\n if con.is_empty() {\n\n con.push('\\n');\n\n }\n\n\n\n let mut new_buffer: Buffer = SplitBuffer::from_str(&con).into();\n\n new_buffer.title = Some(path.into());\n\n\n\n let new_buffer_index = self.buffers.new_buffer(new_buffer);\n\n self.buffers.switch_to(new_buffer_index);\n\n self.hint();\n\n FileStatus::Ok\n\n } else {\n\n FileStatus::NotFound\n\n }\n\n }\n\n\n\n /// Write the file.\n\n pub fn write<'a> (&'a mut self, mut path: &'a str) -> FileStatus {\n", "file_path": "src/io/file.rs", "rank": 93, "score": 4.388179263135834 }, { "content": "\n\n let mut ret_y = 0;\n\n\n\n let ret_x = point.0 % max_horz_chars;\n\n for (y, row) in self.buffers.current_buffer().lines_from(scroll_y).enumerate() {\n\n if to_y > y {\n\n ret_y += row.len() / max_horz_chars + 1;\n\n } else {\n\n ret_y += point.0 / max_horz_chars;\n\n break;\n\n }\n\n }\n\n (ret_x, ret_y)\n\n }\n\n\n\n // Ensure that the cursor is visible\n\n fn cursor_in_window(&mut self, max_horz_chars: usize, max_vert_chars: usize) {\n\n let (_pos_x, pos_y) = self.pos();\n\n if self.buffers.current_buffer_info().scroll_y > 0\n\n && pos_y <= self.buffers.current_buffer_info().scroll_y\n", "file_path": "src/io/graphics.rs", "rank": 94, "score": 4.360654113383432 }, { "content": " // The amount of digits for this line number\n\n let mut digit_nr: usize = 0;\n\n while line_number >= 10usize.pow(digit_nr as u32) {\n\n digit_nr += 1;\n\n }\n\n // Print the digits for this line number\n\n for i in 1..digit_nr + 1 {\n\n let digit = ((line_number % 10) as u8 + ('0' as u32) as u8) as char;\n\n line_number = (line_number - line_number % 10)/10 as usize;\n\n self.window.char(\n\n (self.char_width * (horz_offset - 1 - i)) as i32,\n\n (self.char_height * (scr_lines + vert_offset)) as i32,\n\n digit,\n\n Color::rgb(255, 255, 0),\n\n );\n\n }\n\n }\n\n for (x, c) in row.chars().flat_map(|c| if c == '\\t' {\n\n iter::repeat(' ').take(4)\n\n } else {\n", "file_path": "src/io/graphics.rs", "rank": 95, "score": 3.9653526445772047 }, { "content": " (Command(Normal), Char('X')) => {\n\n self.backspace();\n\n let bounded = self.bound(self.pos(), true);\n\n self.goto(bounded);\n\n }\n\n (Command(Normal), Char('L')) => {\n\n if self.buffers.current_buffer()[self.y()].len() != 0 {\n\n let ln_end = (self.buffers.current_buffer()[self.y()].len() - 1, self.y());\n\n self.goto(ln_end);\n\n mov = true;\n\n }\n\n }\n\n (Command(Normal), Char('H')) => {\n\n self.cursor_mut().x = 0;\n\n mov = true;\n\n }\n\n (Command(Normal), Char('r')) => {\n\n let (x, y) = self.pos();\n\n let c = self.get_char();\n\n let current_buffer = self.buffers.current_buffer_info_mut();\n", "file_path": "src/core/exec.rs", "rank": 96, "score": 3.910484662109101 }, { "content": "- [x] Make editor.pos method and use that instead of\n\n- [ ] Add word navigation\n\n- [ ] `.` command\n\n- [ ] More partial redrawing (register \"is_modified\")\n\n\n\n\n\nKnown bugs:\n\n\n\n- [x] When using `t` with a char that isn't in the document, Sodium will crash.\n\n- [x] `dG` on the last line of the file deletes from the cursor to the end of the line, instead of the entire line.\n\n Not sure if intended.\n\n\n\nThe bug causing these two bugs, is localised to be in position.rs. It resolves by returning a value one over bound x\n\n\n\n- [x] The x value is wrongly bounded. Reproduction:\n\n 1) Make two lines:\n\n - abc\n\n - abcdef\n\n 2) Go to the end of the first line.\n\n 3) Go one down. As you'll see you'll end up at d. That's right.\n\n 4) Now go two the end of the first line again.\n\n 5) Type 2l.\n\n 6) Now go one down\n\n 7) You'll end up on e, even though it should be d\n\n\n\n- [x] Crashes when:\n\n 1) Write abc on line 1\n\n 2) Press o to go to the next line\n\n 3) Go to normal mode\n\n 4) Press a and go to append mode\n\n 5) Type text\n\n 6) Out of bound (index) error\n\n\n\n- [x] When typing the first char in a line in normal insert mode, it wont go to the next char.\n\n\n\n- [x] The modifier keys are only working for one command\n\n Solutions:\n\n - Make a struct KeyState storing info on the modifiers active. Add a method `feed` which feeds the keystate with a key, updating it. This should Option<Key>, where a key should be returned iff the key entered was not a modifier\n\n\n\n- [ ] Crashes when ~ command is used on an empty line\n\n- [ ] `z` command is buggy.\n\n- [ ] `x` is buggy (when line length differ)\n\n\n\nRefactoring:\n\n- Organize into modules\n", "file_path": "TODO.md", "rank": 97, "score": 3.903863647476384 }, { "content": " Some((to_signed_pos((o, y))))\n\n } else {\n\n None\n\n }\n\n }\n\n Char('f') => {\n\n let ch = self.get_char();\n\n\n\n if let Some(o) = self.previous_ocur(ch, n.d()) {\n\n Some((to_signed_pos((o, y))))\n\n } else {\n\n None\n\n }\n\n }\n\n _ => None,\n\n }\n\n }\n\n}\n", "file_path": "src/caret/motion.rs", "rank": 98, "score": 3.8399356963658153 }, { "content": " w as u32,\n\n 16,\n\n Color::rgb(45, 45, 45),\n\n );\n\n }\n\n\n\n self.window.rect(\n\n ((window_pos_x + horz_offset) * self.char_width) as i32,\n\n ((window_pos_y + vert_offset) * self.char_height) as i32,\n\n self.char_width as u32,\n\n self.char_height as u32,\n\n Color::rgb(255, 255, 255),\n\n );\n\n\n\n let mut string = false;\n\n\n\n 'outer: for (y, row) in self.buffers.current_buffer().lines_from(scroll_y).enumerate() {\n\n // Print line numbers\n\n if self.options.line_numbers {\n\n let mut line_number = scroll_y + y as usize + 1;\n", "file_path": "src/io/graphics.rs", "rank": 99, "score": 3.8371457182688293 } ]
Rust
serde-generate/tests/ocaml_runtime.rs
zefchain/serde-reflection
3bc9fa7422a2e725960ae8a1166f6929961f6128
use serde_generate::{ ocaml, test_utils, test_utils::{Choice, Runtime, Test}, CodeGeneratorConfig, SourceInstaller, }; use std::{fs::File, io::Write, process::Command}; use tempfile::tempdir; fn quote_bytes(bytes: &[u8]) -> String { format!( "\"{}\"", bytes .iter() .map(|x| format!("\\{:03}", x)) .collect::<Vec<_>>() .join("") ) } #[test] fn test_ocaml_bcs_runtime_on_simple_data() { test_ocaml_runtime_on_simple_data(Runtime::Bcs); } #[test] fn test_ocaml_bincode_runtime_on_simple_data() { test_ocaml_runtime_on_simple_data(Runtime::Bincode); } fn test_ocaml_runtime_on_simple_data(runtime: Runtime) { let registry = test_utils::get_simple_registry().unwrap(); let dir0 = tempdir().unwrap(); let dir = dir0.path(); let installer = ocaml::Installer::new(dir.to_path_buf()); let runtime_str = match runtime { Runtime::Bcs => { installer.install_bcs_runtime().unwrap(); "bcs" } Runtime::Bincode => { installer.install_bincode_runtime().unwrap(); "bincode" } }; let config = CodeGeneratorConfig::new("testing".to_string()).with_encodings(vec![runtime.into()]); let dir_path = dir.join(&config.module_name()); std::fs::create_dir_all(&dir_path).unwrap(); let dune_project_source_path = dir.join("dune-project"); let mut dune_project_file = std::fs::File::create(dune_project_source_path).unwrap(); writeln!(dune_project_file, "(lang dune 3.0)").unwrap(); let dune_source_path = dir_path.join("dune"); let mut dune_file = std::fs::File::create(dune_source_path).unwrap(); writeln!( dune_file, r#" (env (_ (flags (:standard -w -30-42)))) (library (name testing) (modules testing) (preprocess (pps ppx)) (libraries {}_runtime)) (executable (name main) (modules main) (libraries serde testing)) "#, runtime_str ) .unwrap(); let lib_path = dir_path.join("testing.ml"); let mut lib = File::create(&lib_path).unwrap(); let generator = ocaml::CodeGenerator::new(&config); generator.output(&mut lib, &registry).unwrap(); let exe_path = dir_path.join("main.ml"); let mut exe = File::create(&exe_path).unwrap(); let reference = runtime.serialize(&Test { a: vec![4, 6], b: (-3, 5), c: Choice::C { x: 7 }, }); let reference_bytes = quote_bytes(&reference); writeln!( exe, r#" open Serde open Stdint exception Unexpected_success let () = let input = Bytes.of_string {0} in let value = Deserialize.apply Testing.test_de input in let a = List.map Uint32.of_int [4; 6] in let b = -3L, Uint64.of_int 5 in let c = Testing.Choice_C {{ x = Uint8.of_int 7 }} in let value2 = {{Testing.a; b; c}} in assert (value = value2); let output = Serialize.apply Testing.test_ser value2 in assert (input = output); let input2 = Bytes.of_string ({0} ^ "\001") in try let _ = Deserialize.apply Testing.test_de input2 in raise Unexpected_success with | Unexpected_success -> assert false | _ -> () "#, reference_bytes ) .unwrap(); let status = Command::new("dune") .arg("exec") .arg("testing/main.exe") .arg("--root") .arg(dir) .status() .unwrap(); assert!(status.success()); } #[test] fn test_ocaml_bcs_runtime_on_supported_types() { test_ocaml_runtime_on_supported_types(Runtime::Bcs); } #[test] fn test_ocaml_bincode_runtime_on_supported_types() { test_ocaml_runtime_on_supported_types(Runtime::Bincode); } fn test_ocaml_runtime_on_supported_types(runtime: Runtime) { let registry = test_utils::get_registry().unwrap(); let dir0 = tempdir().unwrap(); let dir = dir0.path(); let installer = ocaml::Installer::new(dir.to_path_buf()); let runtime_str = match runtime { Runtime::Bcs => { installer.install_bcs_runtime().unwrap(); "bcs" } Runtime::Bincode => { installer.install_bincode_runtime().unwrap(); "bincode" } }; let config = CodeGeneratorConfig::new("testing".to_string()).with_encodings(vec![runtime.into()]); let dir_path = dir.join(&config.module_name()); std::fs::create_dir_all(&dir_path).unwrap(); let dune_project_source_path = dir.join("dune-project"); let mut dune_project_file = std::fs::File::create(dune_project_source_path).unwrap(); writeln!(dune_project_file, "(lang dune 3.0)").unwrap(); let dune_source_path = dir_path.join("dune"); let mut dune_file = std::fs::File::create(dune_source_path).unwrap(); writeln!( dune_file, r#" (env (_ (flags (:standard -w -30-42)))) (executable (name test) (modules test) (preprocess (pps ppx)) (libraries {}_runtime)) "#, runtime_str ) .unwrap(); let source_path = dir_path.join("test.ml"); println!("{:?}", source_path); let mut source = File::create(&source_path).unwrap(); let generator = ocaml::CodeGenerator::new(&config); generator.output(&mut source, &registry).unwrap(); let positive_encodings: Vec<_> = runtime .get_positive_samples_quick() .iter() .map(|bytes| quote_bytes(bytes)) .collect(); let negative_encodings: Vec<_> = runtime .get_negative_samples() .iter() .map(|bytes| quote_bytes(bytes)) .collect(); writeln!( source, r#" open Serde exception Unexpected_success let () = List.iter (fun s -> let b = Bytes.of_string s in let sd = Deserialize.apply serde_data_de b in let b2 = Serialize.apply serde_data_ser sd in assert (b = b2)) [{}]; List.iter (fun s -> let b = Bytes.of_string s in try let _ = Deserialize.apply serde_data_de b in raise Unexpected_success with | Unexpected_success -> assert false | _ -> ()) [{}] "#, positive_encodings.join("; "), negative_encodings.join("; ") ) .unwrap(); let status = Command::new("dune") .arg("exec") .arg("testing/test.exe") .arg("--root") .arg(dir) .status() .unwrap(); assert!(status.success()); }
use serde_generate::{ ocaml, test_utils, test_utils::{Choice, Runtime, Test}, CodeGeneratorConfig, SourceInstaller, }; use std::{fs::File, io::Write, process::Command}; use tempfile::tempdir; fn quote_bytes(bytes: &[u8]) -> String { format!( "\"{}\"", bytes .iter() .map(|x| format!("\\{:03}", x)) .collect::<Vec<_>>() .join("") ) } #[test] fn test_ocaml_bcs_runtime_on_simple_data() { test_ocaml_runtime_on_simple_data(Runtime::Bcs); } #[test] fn test_ocaml_bincode_runtime_on_simple_data() { test_ocaml_runtime_on_simple_data(Runtime::Bincode); } fn test_ocaml_runtime_on_simple_data(runtime: Runtime) { let registry = test_utils::get_simple_registry().unwrap(); let dir0 = tempdir().unwrap(); let dir = dir0.path(); let installer = ocaml::Installer::new(dir.to_path_buf()); let runtime_str =
; let config = CodeGeneratorConfig::new("testing".to_string()).with_encodings(vec![runtime.into()]); let dir_path = dir.join(&config.module_name()); std::fs::create_dir_all(&dir_path).unwrap(); let dune_project_source_path = dir.join("dune-project"); let mut dune_project_file = std::fs::File::create(dune_project_source_path).unwrap(); writeln!(dune_project_file, "(lang dune 3.0)").unwrap(); let dune_source_path = dir_path.join("dune"); let mut dune_file = std::fs::File::create(dune_source_path).unwrap(); writeln!( dune_file, r#" (env (_ (flags (:standard -w -30-42)))) (library (name testing) (modules testing) (preprocess (pps ppx)) (libraries {}_runtime)) (executable (name main) (modules main) (libraries serde testing)) "#, runtime_str ) .unwrap(); let lib_path = dir_path.join("testing.ml"); let mut lib = File::create(&lib_path).unwrap(); let generator = ocaml::CodeGenerator::new(&config); generator.output(&mut lib, &registry).unwrap(); let exe_path = dir_path.join("main.ml"); let mut exe = File::create(&exe_path).unwrap(); let reference = runtime.serialize(&Test { a: vec![4, 6], b: (-3, 5), c: Choice::C { x: 7 }, }); let reference_bytes = quote_bytes(&reference); writeln!( exe, r#" open Serde open Stdint exception Unexpected_success let () = let input = Bytes.of_string {0} in let value = Deserialize.apply Testing.test_de input in let a = List.map Uint32.of_int [4; 6] in let b = -3L, Uint64.of_int 5 in let c = Testing.Choice_C {{ x = Uint8.of_int 7 }} in let value2 = {{Testing.a; b; c}} in assert (value = value2); let output = Serialize.apply Testing.test_ser value2 in assert (input = output); let input2 = Bytes.of_string ({0} ^ "\001") in try let _ = Deserialize.apply Testing.test_de input2 in raise Unexpected_success with | Unexpected_success -> assert false | _ -> () "#, reference_bytes ) .unwrap(); let status = Command::new("dune") .arg("exec") .arg("testing/main.exe") .arg("--root") .arg(dir) .status() .unwrap(); assert!(status.success()); } #[test] fn test_ocaml_bcs_runtime_on_supported_types() { test_ocaml_runtime_on_supported_types(Runtime::Bcs); } #[test] fn test_ocaml_bincode_runtime_on_supported_types() { test_ocaml_runtime_on_supported_types(Runtime::Bincode); } fn test_ocaml_runtime_on_supported_types(runtime: Runtime) { let registry = test_utils::get_registry().unwrap(); let dir0 = tempdir().unwrap(); let dir = dir0.path(); let installer = ocaml::Installer::new(dir.to_path_buf()); let runtime_str = match runtime { Runtime::Bcs => { installer.install_bcs_runtime().unwrap(); "bcs" } Runtime::Bincode => { installer.install_bincode_runtime().unwrap(); "bincode" } }; let config = CodeGeneratorConfig::new("testing".to_string()).with_encodings(vec![runtime.into()]); let dir_path = dir.join(&config.module_name()); std::fs::create_dir_all(&dir_path).unwrap(); let dune_project_source_path = dir.join("dune-project"); let mut dune_project_file = std::fs::File::create(dune_project_source_path).unwrap(); writeln!(dune_project_file, "(lang dune 3.0)").unwrap(); let dune_source_path = dir_path.join("dune"); let mut dune_file = std::fs::File::create(dune_source_path).unwrap(); writeln!( dune_file, r#" (env (_ (flags (:standard -w -30-42)))) (executable (name test) (modules test) (preprocess (pps ppx)) (libraries {}_runtime)) "#, runtime_str ) .unwrap(); let source_path = dir_path.join("test.ml"); println!("{:?}", source_path); let mut source = File::create(&source_path).unwrap(); let generator = ocaml::CodeGenerator::new(&config); generator.output(&mut source, &registry).unwrap(); let positive_encodings: Vec<_> = runtime .get_positive_samples_quick() .iter() .map(|bytes| quote_bytes(bytes)) .collect(); let negative_encodings: Vec<_> = runtime .get_negative_samples() .iter() .map(|bytes| quote_bytes(bytes)) .collect(); writeln!( source, r#" open Serde exception Unexpected_success let () = List.iter (fun s -> let b = Bytes.of_string s in let sd = Deserialize.apply serde_data_de b in let b2 = Serialize.apply serde_data_ser sd in assert (b = b2)) [{}]; List.iter (fun s -> let b = Bytes.of_string s in try let _ = Deserialize.apply serde_data_de b in raise Unexpected_success with | Unexpected_success -> assert false | _ -> ()) [{}] "#, positive_encodings.join("; "), negative_encodings.join("; ") ) .unwrap(); let status = Command::new("dune") .arg("exec") .arg("testing/test.exe") .arg("--root") .arg(dir) .status() .unwrap(); assert!(status.success()); }
match runtime { Runtime::Bcs => { installer.install_bcs_runtime().unwrap(); "bcs" } Runtime::Bincode => { installer.install_bincode_runtime().unwrap(); "bincode" } }
if_condition
[ { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"{{{}}}\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"{}\", *x as i8))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 1, "score": 298972.9093064957 }, { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"std::vector<uint8_t>{{{}}}\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"0x{:02x}\", x))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 2, "score": 298972.9093064957 }, { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"yield return new TestCaseData(new byte[] {{ {} }});\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"{}\", *x as u8))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 3, "score": 298972.9093064957 }, { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"{{{}}}\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"{}\", x))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 4, "score": 298972.9093064957 }, { "content": "fn quote_bytes(bytes: &[u8]) -> String {\n\n format!(\n\n \"[{}]\",\n\n bytes\n\n .iter()\n\n .map(|x| format!(\"{}\", x))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 5, "score": 298972.9093064957 }, { "content": "fn test_csharp_runtime_on_simple_data(dir: PathBuf, runtime: Runtime) {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let test_dir = make_test_project(&dir, runtime, \"Testing\", \"SimpleData\").unwrap();\n\n let config =\n\n CodeGeneratorConfig::new(\"SimpleData\".to_string()).with_encodings(vec![runtime.into()]);\n\n\n\n let installer = csharp::Installer::new(dir);\n\n installer.install_serde_runtime().unwrap();\n\n match runtime {\n\n Runtime::Bincode => installer.install_bincode_runtime().unwrap(),\n\n Runtime::Bcs => installer.install_bcs_runtime().unwrap(),\n\n }\n\n installer.install_module(&config, &registry).unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (-3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 12, "score": 200032.99891690322 }, { "content": "fn test_csharp_runtime_on_supported_types(dir: PathBuf, runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let test_dir = make_test_project(&dir, runtime, \"Testing\", \"Data\").unwrap();\n\n let config = CodeGeneratorConfig::new(\"Data\".to_string()).with_encodings(vec![runtime.into()]);\n\n\n\n let installer = csharp::Installer::new(dir);\n\n installer.install_serde_runtime().unwrap();\n\n match runtime {\n\n Runtime::Bincode => installer.install_bincode_runtime().unwrap(),\n\n Runtime::Bcs => installer.install_bcs_runtime().unwrap(),\n\n }\n\n installer.install_module(&config, &registry).unwrap();\n\n\n\n let positive_encodings = runtime\n\n .get_positive_samples_quick()\n\n .iter()\n\n .map(|bytes| quote_bytes(bytes))\n\n .collect::<Vec<_>>()\n\n .join(\"\\n\\t\\t\\t\\t\");\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 13, "score": 200032.99891690322 }, { "content": "#[test]\n\nfn test_that_installed_ocaml_code_compiles() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"ocaml\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path())\n\n .arg(\"--with-runtimes\")\n\n .arg(\"serde\")\n\n .arg(\"--\")\n\n .arg(yaml_path)\n\n .status()\n", "file_path": "serde-generate/tests/cli.rs", "rank": 14, "score": 199606.55705605145 }, { "content": "// Note: this does not test pointer equality, only referenced content.\n\nfn assert_variable_contains_value(format: &Format, value: &Format) {\n\n match format {\n\n Format::Variable(variable) => {\n\n assert_eq!(\n\n variable\n\n .borrow()\n\n .deref()\n\n .as_ref()\n\n .expect(\"must contain a value\"),\n\n value\n\n );\n\n }\n\n _ => panic!(),\n\n }\n\n}\n\n\n", "file_path": "serde-reflection/tests/format.rs", "rank": 15, "score": 184459.19017081024 }, { "content": "#[test]\n\nfn test_format_visiting() {\n\n use Format::*;\n\n\n\n let format = ContainerFormat::Enum(\n\n vec![(\n\n 0,\n\n Named {\n\n name: \"foo\".into(),\n\n value: VariantFormat::Tuple(vec![\n\n TypeName(\"foo\".into()),\n\n TypeName(\"bar\".into()),\n\n Seq(Box::new(TypeName(\"foo\".into()))),\n\n ]),\n\n },\n\n )]\n\n .into_iter()\n\n .collect(),\n\n );\n\n let mut names = HashSet::new();\n\n format\n", "file_path": "serde-reflection/tests/format.rs", "rank": 16, "score": 179087.76654011448 }, { "content": "#[test]\n\nfn test_format_unification() {\n\n use Format::*;\n\n\n\n let mut x = Format::unknown();\n\n assert!(x.unify(U8).is_ok());\n\n x.reduce();\n\n assert_eq!(x, U8);\n\n assert_eq!(\n\n x.unify(U16).unwrap_err(),\n\n Error::Incompatible(\"U8\".into(), \"U16\".into())\n\n );\n\n\n\n let mut x = Tuple(vec![Format::unknown(), U32]);\n\n x.unify(Tuple(vec![U16, Format::unknown()])).unwrap();\n\n x.reduce();\n\n assert_eq!(x, Tuple(vec![U16, U32]));\n\n\n\n for x in vec![\n\n Unit,\n\n Bool,\n", "file_path": "serde-reflection/tests/format.rs", "rank": 17, "score": 179087.76654011448 }, { "content": "fn install_test_dependency(path: &Path) -> Result<()> {\n\n Command::new(\"dart\")\n\n .current_dir(path)\n\n .env(\"PUB_CACHE\", \"../.pub-cache\")\n\n .args([\"pub\", \"add\", \"-d\", \"test\"])\n\n .status()?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "serde-generate/tests/dart_runtime.rs", "rank": 18, "score": 176180.87507836142 }, { "content": "#[test]\n\nfn test_container_format_unification() {\n\n use ContainerFormat::*;\n\n use Format::*;\n\n\n\n let mut x = TupleStruct(vec![Format::unknown(), U32]);\n\n x.unify(TupleStruct(vec![U16, Format::unknown()])).unwrap();\n\n x.reduce();\n\n assert_eq!(x, TupleStruct(vec![U16, U32]));\n\n\n\n let mut x = Enum(\n\n vec![(\n\n 0,\n\n Named {\n\n name: \"foo\".into(),\n\n value: VariantFormat::Tuple(vec![Format::unknown()]),\n\n },\n\n )]\n\n .into_iter()\n\n .collect(),\n\n );\n", "file_path": "serde-reflection/tests/format.rs", "rank": 19, "score": 175770.05750707386 }, { "content": "#[test]\n\nfn test_that_ocaml_code_compiles() {\n\n let config = CodeGeneratorConfig::new(\"testing\".to_string()).with_serialization(false);\n\n test_that_ocaml_code_compiles_with_config(&config, false, None, None);\n\n}\n\n\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 20, "score": 172255.51182203056 }, { "content": "fn run_nunit(proj_dir: &Path) {\n\n let _lock = MUTEX.lock();\n\n let status = Command::new(\"dotnet\")\n\n .arg(\"test\")\n\n .current_dir(proj_dir)\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 21, "score": 170858.77552633398 }, { "content": "fn dotnet_build(proj_dir: &Path) {\n\n let _lock = MUTEX.lock();\n\n let status = Command::new(\"dotnet\")\n\n .arg(\"build\")\n\n .current_dir(proj_dir)\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 22, "score": 170858.77552633398 }, { "content": "#[test]\n\nfn test_csharp_bcs_runtime_tests() {\n\n let test_dir = Path::new(\"runtime/csharp/Serde.Tests\");\n\n dotnet_build(test_dir);\n\n run_nunit(test_dir);\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 23, "score": 170417.99022848977 }, { "content": "#[test]\n\nfn test_that_ocaml_code_compiles_with_comments() {\n\n let comments = vec![(\n\n vec![\"testing\".to_string(), \"SerdeData\".to_string()],\n\n \"Some\\ncomments\".to_string(),\n\n )]\n\n .into_iter()\n\n .collect();\n\n let config = CodeGeneratorConfig::new(\"testing\".to_string())\n\n .with_serialization(false)\n\n .with_comments(comments);\n\n let (_dir, source_path) = test_that_ocaml_code_compiles_with_config(&config, false, None, None);\n\n let content = std::fs::read_to_string(&source_path).unwrap();\n\n assert!(content.contains(\"(*\\n Some\\n comments\\n*)\\n\"));\n\n}\n\n\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 24, "score": 169237.83364298329 }, { "content": "#[test]\n\nfn test_that_ocaml_code_compiles_with_bcs() {\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![Encoding::Bcs]);\n\n test_that_ocaml_code_compiles_with_config(&config, false, None, Some(Encoding::Bcs));\n\n}\n\n\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 25, "score": 169237.83364298329 }, { "content": "#[test]\n\nfn test_that_ocaml_code_compiles_with_bincode() {\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![Encoding::Bincode]);\n\n test_that_ocaml_code_compiles_with_config(&config, false, None, Some(Encoding::Bincode));\n\n}\n\n\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 26, "score": 169237.83364298329 }, { "content": "#[test]\n\nfn test_ocaml_code_with_external_definitions() {\n\n let definitions = vec![\n\n (\"foo\".to_string(), vec![\"Map\".to_string()]),\n\n (String::new(), vec![\"Bytes\".into()]),\n\n ]\n\n .into_iter()\n\n .collect();\n\n\n\n let config = CodeGeneratorConfig::new(\"testing\".to_string())\n\n .with_external_definitions(definitions)\n\n .with_serialization(false);\n\n test_that_ocaml_code_compiles_with_config(&config, true, None, None);\n\n\n\n let more = r#\"\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 27, "score": 169237.83364298329 }, { "content": "fn test_that_ocaml_code_compiles_with_config(\n\n config: &CodeGeneratorConfig,\n\n must_fail: bool,\n\n more: Option<&str>,\n\n encoding: Option<Encoding>,\n\n) -> (TempDir, std::path::PathBuf) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir0 = tempdir().unwrap();\n\n let dir = dir0.path();\n\n std::fs::create_dir_all(&dir).unwrap();\n\n\n\n let source_path = dir.join(\"test.ml\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n if let Some(s) = more {\n\n writeln!(source, \"{}\", s).unwrap()\n\n };\n\n\n\n let generator = ocaml::CodeGenerator::new(config);\n\n generator.output(&mut source, &registry).unwrap();\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 28, "score": 169232.63625401846 }, { "content": "#[test]\n\nfn test_dart_runtime_autotest() {\n\n // Not setting PUB_CACHE here because this is the only test run with the default\n\n // config anyway.\n\n let dart_test = Command::new(\"dart\")\n\n .current_dir(&\"runtime/dart\")\n\n .args([\"test\", \"-r\", \"expanded\"])\n\n .status()\n\n .unwrap();\n\n\n\n assert!(dart_test.success());\n\n}\n\n\n", "file_path": "serde-generate/tests/dart_runtime.rs", "rank": 29, "score": 167351.11233371554 }, { "content": "#[test]\n\nfn test_rust_bcs_runtime() {\n\n test_rust_runtime(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/rust_runtime.rs", "rank": 30, "score": 167351.11233371554 }, { "content": "#[test]\n\nfn test_swift_runtime_autotests() {\n\n let runtime_path = std::env::current_exe()\n\n .unwrap()\n\n .parent()\n\n .unwrap()\n\n .join(\"../../../serde-generate/runtime/swift\");\n\n\n\n let status = Command::new(\"swift\")\n\n .current_dir(runtime_path.to_str().unwrap())\n\n .arg(\"test\")\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 31, "score": 167351.11233371554 }, { "content": "#[test]\n\nfn test_golang_runtime_autotests() {\n\n let runtime_mod_path = std::env::current_exe()\n\n .unwrap()\n\n .parent()\n\n .unwrap()\n\n .join(\"../../../serde-generate/runtime/golang\");\n\n\n\n let status = Command::new(\"go\")\n\n .current_dir(runtime_mod_path.to_str().unwrap())\n\n .arg(\"test\")\n\n .arg(\"./...\")\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 32, "score": 167351.11233371554 }, { "content": "#[test]\n\nfn test_rust_bincode_runtime() {\n\n test_rust_runtime(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/rust_runtime.rs", "rank": 33, "score": 167351.11233371554 }, { "content": "#[test]\n\nfn test_on_larger_registry() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let map = analyzer::get_dependency_map(&registry).unwrap();\n\n assert_eq!(\n\n map.get(\"SerdeData\").unwrap(),\n\n &btreeset!(\n\n \"CStyleEnum\",\n\n \"List\",\n\n \"NewTypeStruct\",\n\n \"OtherTypes\",\n\n \"PrimitiveTypes\",\n\n \"Struct\",\n\n \"Tree\",\n\n \"TupleStruct\",\n\n \"UnitStruct\",\n\n \"SimpleList\",\n\n )\n\n );\n\n\n\n let vector = analyzer::best_effort_topological_sort(&map);\n", "file_path": "serde-generate/tests/analyzer.rs", "rank": 34, "score": 167194.55996400575 }, { "content": "#[test]\n\nfn test_borrowed_bytes() {\n\n #[derive(Serialize, Deserialize, PartialEq, Eq, Debug, Clone)]\n\n struct Borrowed<'a>(#[serde(with = \"serde_bytes\")] &'a [u8]);\n\n\n\n let bytes = [1u8; 4];\n\n let mut samples = Samples::new();\n\n let mut tracer = Tracer::new(TracerConfig::default());\n\n\n\n let (format, value) = tracer.trace_value(&mut samples, &Borrowed(&bytes)).unwrap();\n\n assert_eq!(format, Format::TypeName(\"Borrowed\".into()));\n\n // Value was traced and serialized as a bytes.\n\n assert_eq!(value, Value::Bytes(bytes.to_vec()));\n\n\n\n let (format, samples) = tracer.trace_type::<Borrowed>(&samples).unwrap();\n\n assert_eq!(format, Format::TypeName(\"Borrowed\".into()));\n\n assert_eq!(samples, vec![Borrowed(&bytes),]);\n\n\n\n let registry = tracer.registry().unwrap();\n\n assert_eq!(\n\n registry.get(\"Borrowed\").unwrap(),\n\n &ContainerFormat::NewTypeStruct(Box::new(Format::Bytes))\n\n );\n\n}\n\n\n", "file_path": "serde-reflection/tests/serde.rs", "rank": 35, "score": 167089.96469483493 }, { "content": "/// Returns:\n\n/// 1. A `PathBuf` to the directory to write test data into\n\n/// 2. Optionally, a `tempfile::TempDir` which deletes the directory when it goes out of scope\n\nfn create_test_dir(test_name: &'static str) -> (PathBuf, Option<tempfile::TempDir>) {\n\n // Set env var to generate into subdirectories for inspection\n\n if std::env::var(\"TEST_USE_SUBDIR\").is_ok() {\n\n let mut tries = 0;\n\n while tries < 20 {\n\n let test_dir_name = if tries == 0 {\n\n test_name.into()\n\n } else {\n\n format!(\"{}_{}\", test_name, tries)\n\n };\n\n let dir = Path::new(\"tests\").join(test_dir_name).to_path_buf();\n\n match std::fs::create_dir(&dir) {\n\n Ok(()) => return (dir, None),\n\n Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => tries += 1,\n\n Err(e) => panic!(\"Error creating test directory: {:?}\", e),\n\n }\n\n }\n\n panic!(\"Error creating test directory: Too many existing test directories\");\n\n } else {\n\n let tempdir = tempfile::Builder::new()\n\n .suffix(&format!(\"_{}\", test_name))\n\n .tempdir()\n\n .unwrap();\n\n (tempdir.path().to_path_buf(), Some(tempdir))\n\n }\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 36, "score": 166534.6156971628 }, { "content": "#[test]\n\nfn test_that_ocaml_code_compiles_with_custom_code() {\n\n let custom_code = vec![(\n\n vec![\"testing\".to_string(), \"SerdeData\".to_string()],\n\n r#\"let serde_data_to_string = function\n\n | SerdeData_PrimitiveTypes _ -> \"primitive types\"\n\n | SerdeData_OtherTypes _ -> \"other types\"\n\n | SerdeData_UnitVariant -> \"unit variant\"\n\n | SerdeData_NewTypeVariant _ -> \"new type variant\"\n\n | _ -> \"etc\"\"#\n\n .to_string(),\n\n )]\n\n .into_iter()\n\n .collect();\n\n let config = CodeGeneratorConfig::new(\"testing\".to_string())\n\n .with_serialization(false)\n\n .with_custom_code(custom_code);\n\n let (_dir, source_path) = test_that_ocaml_code_compiles_with_config(&config, false, None, None);\n\n let content = std::fs::read_to_string(&source_path).unwrap();\n\n assert!(content.contains(\"serde_data_to_string\"));\n\n}\n", "file_path": "serde-generate/tests/ocaml_generation.rs", "rank": 37, "score": 166351.67728047294 }, { "content": "// Full test using cargo. This may take a while.\n\nfn test_rust_runtime(runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let mut file = std::fs::File::create(dir.path().join(\"Cargo.toml\")).unwrap();\n\n write!(\n\n &mut file,\n\n r#\"[package]\n\nname = \"testing2\"\n\nversion = \"0.1.0\"\n\nedition = \"2018\"\n\n\n\n[dependencies]\n\nserde = {{ version = \"1.0\", features = [\"derive\"] }}\n\nserde_bytes = \"0.11\"\n\n{}\n\n\n\n[workspace]\n\n\"#,\n\n runtime.rust_package()\n\n )\n", "file_path": "serde-generate/tests/rust_runtime.rs", "rank": 38, "score": 164607.28814484592 }, { "content": "#[test]\n\nfn test_typescript_runtime_bcs_serialization() {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let dir_path = dir.path();\n\n std::fs::create_dir_all(dir_path.join(\"tests\")).unwrap();\n\n\n\n let installer = typescript::Installer::new(dir_path.to_path_buf());\n\n installer.install_serde_runtime().unwrap();\n\n installer.install_bcs_runtime().unwrap();\n\n\n\n let source_path = dir_path.join(\"tests/test.ts\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let runtime = Runtime::Bcs;\n\n let config = CodeGeneratorConfig::new(\"main\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = typescript::CodeGenerator::new(&config);\n\n generator.output(&mut source, &registry).unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n", "file_path": "serde-generate/tests/typescript_runtime.rs", "rank": 39, "score": 164425.60795442827 }, { "content": "#[test]\n\nfn test_java_bcs_runtime_autotest() {\n\n let dir = tempdir().unwrap();\n\n let paths = std::iter::empty()\n\n .chain(std::fs::read_dir(\"runtime/java/com/novi/serde\").unwrap())\n\n .chain(std::fs::read_dir(\"runtime/java/com/novi/bcs\").unwrap())\n\n .map(|e| e.unwrap().path());\n\n let status = Command::new(\"javac\")\n\n .arg(\"-Xlint\")\n\n .arg(\"-d\")\n\n .arg(dir.path())\n\n .args(paths)\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n\n\n let status = Command::new(\"java\")\n\n .arg(\"-enableassertions\")\n\n .arg(\"-cp\")\n\n .arg(dir.path())\n\n .arg(\"com.novi.bcs.BcsTest\")\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 40, "score": 164425.60795442827 }, { "content": "#[test]\n\nfn test_get_registry() {\n\n let registry = get_registry().unwrap();\n\n let expected = r#\"---\n\nCStyleEnum:\n\n ENUM:\n\n 0:\n\n A: UNIT\n\n 1:\n\n B: UNIT\n\n 2:\n\n C: UNIT\n\n 3:\n\n D: UNIT\n\n 4:\n\n E: UNIT\n\nList:\n\n ENUM:\n\n 0:\n\n Empty: UNIT\n\n 1:\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 41, "score": 163666.38567280024 }, { "content": "#[test]\n\nfn test_pattern_variable_unification() {\n\n let mut x = Format::unknown();\n\n let mut y = Format::unknown();\n\n let mut z = Format::unknown();\n\n x.unify(y.clone()).unwrap();\n\n // x is untouched when unifying with y.\n\n // We chose to assign y to (a clone of the RC pointer to the refcell of) x.\n\n assert_eq!(x, Format::unknown());\n\n assert_variable_contains_value(&y, &x);\n\n\n\n x.unify(Format::U8).unwrap();\n\n // y is untouched when assigning x alone.\n\n assert_variable_contains_value(&y, &x);\n\n\n\n y.unify(z.clone()).unwrap();\n\n // We chose to assign z.\n\n assert_variable_contains_value(&y, &x);\n\n assert_variable_contains_value(&z, &y);\n\n\n\n z.unify(Format::U8).unwrap();\n", "file_path": "serde-reflection/tests/format.rs", "rank": 42, "score": 163539.98034499868 }, { "content": "#[test]\n\nfn test_general_variable_unification() {\n\n let mut x = Format::unknown();\n\n let mut y = Format::unknown();\n\n y.unify(Format::U8).unwrap();\n\n x.unify(y.clone()).unwrap();\n\n assert!(x.unify(Format::U16).is_err());\n\n x.unify(Format::U8).unwrap();\n\n\n\n let mut x = VariantFormat::unknown();\n\n let mut y = VariantFormat::unknown();\n\n y.unify(VariantFormat::Unit).unwrap();\n\n x.unify(y.clone()).unwrap();\n\n assert!(x\n\n .unify(VariantFormat::NewType(Box::new(Format::U16)))\n\n .is_err());\n\n x.unify(VariantFormat::Unit).unwrap();\n\n}\n\n\n", "file_path": "serde-reflection/tests/format.rs", "rank": 43, "score": 163539.98034499868 }, { "content": "#[test]\n\nfn test_python_bcs_runtime_on_supported_types() {\n\n test_python_runtime_on_supported_types(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 44, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_csharp_bincode_runtime_on_simple_data() {\n\n let (dir, _tmp) = create_test_dir(\"test_csharp_bincode_runtime_on_simple_data\");\n\n test_csharp_runtime_on_simple_data(dir, Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 45, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_dart_bcs_runtime_on_simple_data() {\n\n test_dart_runtime_on_simple_data(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/dart_runtime.rs", "rank": 46, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_swift_bincode_runtime_on_simple_data() {\n\n test_swift_runtime_on_simple_data(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 47, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_cpp_bincode_runtime_on_supported_types() {\n\n test_cpp_runtime_on_supported_types(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 48, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_python_bcs_runtime_on_simple_data() {\n\n test_python_runtime_on_simple_data(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 49, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_swift_bcs_runtime_on_simple_data() {\n\n test_swift_runtime_on_simple_data(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 50, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_csharp_bincode_runtime_on_supported_types() {\n\n let (dir, _tmp) = create_test_dir(\"test_csharp_bincode_runtime_on_supported_types\");\n\n test_csharp_runtime_on_supported_types(dir, Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 51, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_cpp_bcs_runtime_on_supported_types() {\n\n test_cpp_runtime_on_supported_types(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 52, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_golang_bincode_runtime_on_simple_data() {\n\n test_golang_runtime_on_simple_data(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 53, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_cpp_bincode_runtime_on_simple_date() {\n\n test_cpp_runtime_on_simple_date(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 54, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_python_bincode_runtime_on_supported_types() {\n\n test_python_runtime_on_supported_types(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 55, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_cpp_bcs_runtime_on_simple_date() {\n\n test_cpp_runtime_on_simple_date(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 56, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_golang_bincode_runtime_on_supported_types() {\n\n test_golang_runtime_on_supported_types(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 57, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_golang_bcs_runtime_on_simple_data() {\n\n test_golang_runtime_on_simple_data(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 58, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_swift_bcs_runtime_on_supported_types() {\n\n test_swift_runtime_on_supported_types(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 59, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_csharp_bcs_runtime_on_supported_types() {\n\n let (dir, _tmp) = create_test_dir(\"test_csharp_bcs_runtime_on_supported_types\");\n\n test_csharp_runtime_on_supported_types(dir, Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 60, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_java_bincode_runtime_on_simple_data() {\n\n test_java_runtime_on_simple_data(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 61, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_java_bcs_runtime_on_simple_data() {\n\n test_java_runtime_on_simple_data(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 62, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_csharp_bcs_runtime_on_simple_data() {\n\n let (dir, _tmp) = create_test_dir(\"test_csharp_runtime_on_simple_data\");\n\n test_csharp_runtime_on_simple_data(dir, Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 63, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_python_bincode_runtime_on_simple_data() {\n\n test_python_runtime_on_simple_data(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 64, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_golang_bcs_runtime_on_supported_types() {\n\n test_golang_runtime_on_supported_types(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 65, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_java_bcs_runtime_on_supported_types() {\n\n test_java_runtime_on_supported_types(Runtime::Bcs);\n\n}\n\n\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 66, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_java_bincode_runtime_on_supported_types() {\n\n test_java_runtime_on_supported_types(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 67, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_dart_bincode_runtime_on_simple_data() {\n\n test_dart_runtime_on_simple_data(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/dart_runtime.rs", "rank": 68, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_swift_bincode_runtime_on_supported_types() {\n\n test_swift_runtime_on_supported_types(Runtime::Bincode);\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 69, "score": 161628.22465726556 }, { "content": "#[test]\n\nfn test_that_installed_rust_code_compiles() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"rust\")\n\n .arg(\"--module-name\")\n\n .arg(\"testing:0.2.0\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path())\n\n .arg(yaml_path)\n\n .status()\n\n .unwrap();\n", "file_path": "serde-generate/tests/cli.rs", "rank": 70, "score": 160326.3100908914 }, { "content": "#[test]\n\nfn test_that_installed_python_code_parses() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"python3\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path())\n\n .arg(\"--module-name\")\n\n .arg(\"test_types\")\n\n .arg(\"--with-runtimes\")\n\n .arg(\"serde\")\n\n .arg(\"bincode\")\n", "file_path": "serde-generate/tests/cli.rs", "rank": 71, "score": 160326.3100908914 }, { "content": "#[test]\n\nfn test_that_installed_cpp_code_compiles() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"cpp\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path())\n\n .arg(yaml_path)\n\n .arg(\"--with-runtimes\")\n\n .arg(\"serde\")\n\n .arg(\"bincode\")\n\n .arg(\"bcs\")\n", "file_path": "serde-generate/tests/cli.rs", "rank": 72, "score": 160326.3100908914 }, { "content": "#[test]\n\nfn test_that_installed_java_code_compiles() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"java\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path())\n\n .arg(\"--module-name\")\n\n .arg(\"test.types\")\n\n .arg(\"--with-runtimes\")\n\n .arg(\"serde\")\n\n .arg(\"--\")\n", "file_path": "serde-generate/tests/cli.rs", "rank": 73, "score": 160326.3100908914 }, { "content": "#[test]\n\nfn test_get_simple_registry() {\n\n let registry = get_simple_registry().unwrap();\n\n assert_eq!(\n\n serde_yaml::to_string(&registry).unwrap(),\n\n r#\"---\n\nChoice:\n\n ENUM:\n\n 0:\n\n A: UNIT\n\n 1:\n\n B:\n\n NEWTYPE: U64\n\n 2:\n\n C:\n\n STRUCT:\n\n - x: U8\n\nTest:\n\n STRUCT:\n\n - a:\n\n SEQ: U32\n\n - b:\n\n TUPLE:\n\n - I64\n\n - U64\n\n - c:\n\n TYPENAME: Choice\n\n\"#\n\n );\n\n}\n\n\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 74, "score": 160323.6651223081 }, { "content": "fn make_output_file(dir: &Path) {\n\n std::fs::create_dir_all(dir.join(\"testing\")).unwrap_or(());\n\n}\n\n\n", "file_path": "serde-generate/tests/typescript_generation.rs", "rank": 75, "score": 159904.13720007284 }, { "content": "fn test_golang_runtime_on_simple_data(runtime: Runtime) {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let source_path = dir.path().join(\"test.go\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let config = CodeGeneratorConfig::new(\"main\".to_string())\n\n .with_encodings(vec![runtime.into()])\n\n .with_external_definitions(\n\n vec![(\"github.com/google/go-cmp/cmp\".to_string(), vec![])]\n\n .into_iter()\n\n .collect(),\n\n );\n\n let generator = golang::CodeGenerator::new(&config);\n\n generator.output(&mut source, &registry).unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (-3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n\n\n writeln!(\n\n source,\n\n r#\"\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 76, "score": 159579.30930002534 }, { "content": "fn test_python_runtime_on_simple_data(runtime: Runtime) {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let source_path = dir.path().join(\"test.py\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = python3::CodeGenerator::new(&config);\n\n generator.output(&mut source, &registry).unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n writeln!(\n\n source,\n\n r#\"\n\ninput = bytes({1:?})\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 77, "score": 159579.30930002534 }, { "content": "fn test_swift_runtime_on_simple_data(runtime: Runtime) {\n\n // To see the source, uncomment this and replace `dir.path()` by `my_path` below.\n\n // let my_path = std::path::Path::new(\"../test\");\n\n // std::fs::remove_dir_all(my_path).unwrap_or(());\n\n // std::fs::create_dir_all(my_path).unwrap();\n\n let dir = tempfile::tempdir().unwrap();\n\n let config =\n\n CodeGeneratorConfig::new(\"Testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let installer = swift::Installer::new(dir.path().to_path_buf());\n\n installer.install_module(&config, &registry).unwrap();\n\n installer.install_serde_runtime().unwrap(); // also installs bcs and bincode\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (-3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n\n\n std::fs::create_dir_all(dir.path().join(\"Sources/main\")).unwrap();\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 78, "score": 159579.30930002534 }, { "content": "fn test_cpp_runtime_on_supported_types(runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let header_path = dir.path().join(\"test.hpp\");\n\n let mut header = File::create(&header_path).unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = cpp::CodeGenerator::new(&config);\n\n generator.output(&mut header, &registry).unwrap();\n\n\n\n let positive_encodings: Vec<_> = runtime\n\n .get_positive_samples()\n\n .iter()\n\n .map(|bytes| quote_bytes(bytes))\n\n .collect();\n\n\n\n let negative_encodings: Vec<_> = runtime\n\n .get_negative_samples()\n\n .iter()\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 79, "score": 159579.30930002534 }, { "content": "fn test_cpp_runtime_on_simple_date(runtime: Runtime) {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let header_path = dir.path().join(\"test.hpp\");\n\n let mut header = File::create(&header_path).unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = cpp::CodeGenerator::new(&config);\n\n generator.output(&mut header, &registry).unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (-3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n\n\n let source_path = dir.path().join(\"test.cpp\");\n\n let mut source = File::create(&source_path).unwrap();\n\n writeln!(\n", "file_path": "serde-generate/tests/cpp_runtime.rs", "rank": 80, "score": 159579.30930002534 }, { "content": "fn test_swift_runtime_on_supported_types(runtime: Runtime) {\n\n // To see the source, uncomment this and replace `dir.path()` by `my_path` below.\n\n // let my_path = std::path::Path::new(\"../test\");\n\n // std::fs::remove_dir_all(my_path).unwrap_or(());\n\n // std::fs::create_dir_all(my_path).unwrap();\n\n let dir = tempfile::tempdir().unwrap();\n\n let config =\n\n CodeGeneratorConfig::new(\"Testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let registry = test_utils::get_registry().unwrap();\n\n let installer = swift::Installer::new(dir.path().to_path_buf());\n\n installer.install_module(&config, &registry).unwrap();\n\n installer.install_serde_runtime().unwrap(); // also installs bcs and bincode\n\n\n\n std::fs::create_dir_all(dir.path().join(\"Sources/main\")).unwrap();\n\n let main_path = dir.path().join(\"Sources/main/main.swift\");\n\n let mut main = File::create(main_path).unwrap();\n\n\n\n let positive_encodings = runtime\n\n .get_positive_samples_quick()\n\n .iter()\n", "file_path": "serde-generate/tests/swift_runtime.rs", "rank": 81, "score": 159579.30930002534 }, { "content": "fn test_golang_runtime_on_supported_types(runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let source_path = dir.path().join(\"test.go\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let config = CodeGeneratorConfig::new(\"main\".to_string())\n\n .with_encodings(vec![runtime.into()])\n\n .with_external_definitions(\n\n vec![(\"github.com/google/go-cmp/cmp\".to_string(), vec![])]\n\n .into_iter()\n\n .collect(),\n\n );\n\n let generator = golang::CodeGenerator::new(&config);\n\n generator.output(&mut source, &registry).unwrap();\n\n\n\n let positive_encodings = runtime\n\n .get_positive_samples_quick()\n\n .iter()\n\n .map(|bytes| quote_bytes(bytes))\n", "file_path": "serde-generate/tests/golang_runtime.rs", "rank": 82, "score": 159579.30930002534 }, { "content": "fn test_dart_runtime_on_simple_data(runtime: Runtime) {\n\n let tempdir = tempdir().unwrap();\n\n let source_path = tempdir\n\n .path()\n\n .join(format!(\"dart_project_{}\", runtime.name().to_lowercase()));\n\n\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n\n\n let config = CodeGeneratorConfig::new(\"example\".to_string())\n\n .with_encodings(vec![runtime.into()])\n\n .with_c_style_enums(false);\n\n\n\n let installer = dart::Installer::new(source_path.clone());\n\n installer.install_module(&config, &registry).unwrap();\n\n installer.install_serde_runtime().unwrap();\n\n installer.install_bincode_runtime().unwrap();\n\n installer.install_bcs_runtime().unwrap();\n\n\n\n create_dir_all(source_path.join(\"test\")).unwrap();\n\n\n", "file_path": "serde-generate/tests/dart_runtime.rs", "rank": 83, "score": 159579.30930002534 }, { "content": "fn test_java_runtime_on_supported_types(runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = java::CodeGenerator::new(&config);\n\n generator\n\n .write_source_files(dir.path().to_path_buf(), &registry)\n\n .unwrap();\n\n\n\n let positive_encodings: Vec<_> = runtime\n\n .get_positive_samples_quick()\n\n .iter()\n\n .map(|bytes| quote_bytes(bytes))\n\n .collect();\n\n\n\n let negative_encodings: Vec<_> = runtime\n\n .get_negative_samples()\n\n .iter()\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 84, "score": 159579.30930002534 }, { "content": "fn test_java_runtime_on_simple_data(runtime: Runtime) {\n\n let registry = test_utils::get_simple_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = java::CodeGenerator::new(&config);\n\n generator\n\n .write_source_files(dir.path().to_path_buf(), &registry)\n\n .unwrap();\n\n\n\n let reference = runtime.serialize(&Test {\n\n a: vec![4, 6],\n\n b: (-3, 5),\n\n c: Choice::C { x: 7 },\n\n });\n\n\n\n let mut source = File::create(&dir.path().join(\"Main.java\")).unwrap();\n\n writeln!(\n\n source,\n", "file_path": "serde-generate/tests/java_runtime.rs", "rank": 85, "score": 159579.30930002534 }, { "content": "fn test_python_runtime_on_supported_types(runtime: Runtime) {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let source_path = dir.path().join(\"test.py\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![runtime.into()]);\n\n let generator = python3::CodeGenerator::new(&config);\n\n generator.output(&mut source, &registry).unwrap();\n\n\n\n let positive_encodings: Vec<_> = runtime.get_positive_samples_quick();\n\n let negative_encodings: Vec<_> = runtime.get_negative_samples();\n\n\n\n writeln!(\n\n source,\n\n r#\"\n\nfrom copy import copy\n\nimport serde_types as st\n\nimport sys\n", "file_path": "serde-generate/tests/python_runtime.rs", "rank": 86, "score": 159579.30930002534 }, { "content": "fn make_test_project(\n\n tmp_dir: &Path,\n\n runtime: Runtime,\n\n test_name: &str,\n\n library_name: &str,\n\n) -> std::io::Result<PathBuf> {\n\n let test_dir = tmp_dir.join(test_name.replace('.', \"/\"));\n\n std::fs::create_dir(&test_dir)?;\n\n let mut proj = std::fs::File::create(test_dir.join(format!(\"{}.csproj\", test_name)))?;\n\n write!(\n\n proj,\n\n r#\"\n\n<Project Sdk=\"Microsoft.NET.Sdk\">\n\n\n\n <PropertyGroup>\n\n <TargetFrameworks>netcoreapp2.1;netcoreapp3.1</TargetFrameworks>\n\n <IsPackable>false</IsPackable>\n\n <LangVersion>7.2</LangVersion>\n\n </PropertyGroup>\n\n\n", "file_path": "serde-generate/tests/csharp_runtime.rs", "rank": 87, "score": 159415.64400587272 }, { "content": "#[test]\n\nfn test_that_installed_python_code_with_package_parses() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n let yaml_path = dir.path().join(\"test.yaml\");\n\n std::fs::write(yaml_path.clone(), serde_yaml::to_string(&registry).unwrap()).unwrap();\n\n\n\n let status = Command::new(\"cargo\")\n\n .arg(\"run\")\n\n .arg(\"-p\")\n\n .arg(\"serde-generate\")\n\n .arg(\"--\")\n\n .arg(\"--language\")\n\n .arg(\"python3\")\n\n .arg(\"--target-source-dir\")\n\n .arg(dir.path().join(\"my_package\"))\n\n .arg(\"--module-name\")\n\n .arg(\"test_types\")\n\n .arg(\"--serde-package-name\")\n\n .arg(\"my_package\")\n\n .arg(\"--with-runtimes\")\n", "file_path": "serde-generate/tests/cli.rs", "rank": 88, "score": 157154.3169250932 }, { "content": "fn main() {{\n\n for encoding in vec![{}] {{\n\n let value = {}::<SerdeData>(&encoding).unwrap();\n\n let s = {}(&value).unwrap();\n\n assert_eq!(s, encoding);\n\n }}\n\n}}\n\n\"#,\n\n encodings.join(\", \"),\n\n runtime.quote_deserialize(),\n\n runtime.quote_serialize(),\n\n )\n\n .unwrap();\n\n\n\n // Use a stable `target` dir to avoid downloading and recompiling crates everytime.\n\n let target_dir = std::env::current_dir().unwrap().join(\"../target\");\n\n let status = Command::new(\"cargo\")\n\n .current_dir(dir.path())\n\n .arg(\"run\")\n\n .arg(\"--target-dir\")\n\n .arg(target_dir)\n\n .status()\n\n .unwrap();\n\n assert!(status.success());\n\n}\n", "file_path": "serde-generate/tests/rust_runtime.rs", "rank": 89, "score": 155065.39131405277 }, { "content": "fn test_that_swift_code_compiles_with_config_and_registry(\n\n config: &CodeGeneratorConfig,\n\n registry: &Registry,\n\n) -> (TempDir, std::path::PathBuf) {\n\n let dir = tempdir().unwrap();\n\n std::fs::create_dir_all(dir.path().join(\"Sources/Testing\")).unwrap_or(());\n\n let serde_package_path = std::env::current_dir()\n\n .unwrap()\n\n .join(\"../serde-generate/runtime/swift\");\n\n let mut file = File::create(dir.path().join(\"Package.swift\")).unwrap();\n\n write!(\n\n file,\n\n r#\"// swift-tools-version:5.3\n\n\n\nimport PackageDescription\n\n\n\nlet package = Package(\n\n name: \"Testing\",\n\n products: [\n\n .library(\n", "file_path": "serde-generate/tests/swift_generation.rs", "rank": 90, "score": 154132.31718440243 }, { "content": "fn test_that_golang_code_compiles_with_config_and_registry(\n\n config: &CodeGeneratorConfig,\n\n registry: &Registry,\n\n) -> (TempDir, std::path::PathBuf) {\n\n let dir = tempdir().unwrap();\n\n let source_path = dir.path().join(\"test.go\");\n\n let mut source = File::create(&source_path).unwrap();\n\n\n\n let generator = golang::CodeGenerator::new(config);\n\n generator.output(&mut source, registry).unwrap();\n\n\n\n writeln!(&mut source, \"func main() {{}}\").unwrap();\n\n\n\n let status = Command::new(\"go\")\n\n .current_dir(dir.path())\n\n .arg(\"mod\")\n\n .arg(\"init\")\n\n .arg(\"example.com/test\")\n\n .status()\n\n .unwrap();\n", "file_path": "serde-generate/tests/golang_generation.rs", "rank": 91, "score": 154132.31718440243 }, { "content": "#[test]\n\nfn test_that_installed_python_code_passes_pyre_check() {\n\n let registry = test_utils::get_registry().unwrap();\n\n let dir = tempdir().unwrap();\n\n\n\n let config =\n\n CodeGeneratorConfig::new(\"testing\".to_string()).with_encodings(vec![Encoding::Bcs]);\n\n let installer = python3::Installer::new(dir.path().join(\"src\"), /* serde package */ None);\n\n installer.install_module(&config, &registry).unwrap();\n\n installer.install_serde_runtime().unwrap();\n\n installer.install_bincode_runtime().unwrap();\n\n installer.install_bcs_runtime().unwrap();\n\n\n\n // Copy test files manually to type-check them as well.\n\n // This should go away when python runtimes are properly packaged.\n\n let status = Command::new(\"cp\")\n\n .arg(\"-r\")\n\n .arg(\"runtime/python/bcs/test_bcs.py\")\n\n .arg(dir.path().join(\"src/bcs\"))\n\n .status()\n\n .unwrap();\n", "file_path": "serde-generate/tests/python_generation.rs", "rank": 92, "score": 151271.62008607906 }, { "content": "#[cfg(test)]\n\nfn test_get_sample_with_long_sequence(runtime: Runtime) {\n\n let value = get_sample_value_with_long_sequence(0);\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_long_sequence(0)\n\n );\n\n\n\n let value = get_sample_value_with_long_sequence(20);\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_long_sequence(20)\n\n );\n\n\n\n let value = get_sample_value_with_long_sequence(200);\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_long_sequence(200)\n\n );\n\n}\n\n\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 93, "score": 150186.81469935353 }, { "content": "#[cfg(test)]\n\nfn test_get_sample_with_container_depth(runtime: Runtime) {\n\n let value = get_sample_value_with_container_depth(2).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_container_depth(2).unwrap()\n\n );\n\n\n\n let value = get_sample_value_with_container_depth(20).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_container_depth(20).unwrap()\n\n );\n\n\n\n let value = get_sample_value_with_container_depth(200).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime.get_sample_with_container_depth(200).unwrap()\n\n );\n\n}\n\n\n\n// Make sure the direct computation of the serialization of these test values\n\n// agrees with the usual serialization.\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 94, "score": 150186.81469935353 }, { "content": "fn get_small_registry() -> Result<Registry> {\n\n let mut tracer = Tracer::new(TracerConfig::default());\n\n let samples = Samples::new();\n\n tracer.trace_type::<Test>(&samples)?;\n\n tracer.registry()\n\n}\n\n\n", "file_path": "serde-generate/tests/swift_generation.rs", "rank": 95, "score": 148892.92292990116 }, { "content": "fn get_small_registry() -> Result<Registry> {\n\n let mut tracer = Tracer::new(TracerConfig::default());\n\n let samples = Samples::new();\n\n tracer.trace_type::<Test>(&samples)?;\n\n tracer.registry()\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_generation.rs", "rank": 96, "score": 148892.92292990116 }, { "content": "fn get_empty_registry() -> Result<Registry> {\n\n let tracer = Tracer::new(TracerConfig::default());\n\n tracer.registry()\n\n}\n\n\n", "file_path": "serde-generate/tests/golang_generation.rs", "rank": 97, "score": 148892.92292990116 }, { "content": "#[cfg(test)]\n\nfn test_get_alternate_sample_with_container_depth(runtime: Runtime) {\n\n let value = get_alternate_sample_value_with_container_depth(2).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime\n\n .get_alternate_sample_with_container_depth(2)\n\n .unwrap()\n\n );\n\n\n\n let value = get_alternate_sample_value_with_container_depth(20).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime\n\n .get_alternate_sample_with_container_depth(20)\n\n .unwrap()\n\n );\n\n\n\n let value = get_alternate_sample_value_with_container_depth(200).unwrap();\n\n assert_eq!(\n\n runtime.serialize(&value),\n\n runtime\n\n .get_alternate_sample_with_container_depth(200)\n\n .unwrap()\n\n );\n\n}\n\n\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 98, "score": 147620.77658308725 }, { "content": "#[cfg(test)]\n\nfn test_get_positive_samples(runtime: Runtime) -> usize {\n\n let samples = runtime.get_positive_samples();\n\n let length = samples.len();\n\n for sample in samples {\n\n assert!(runtime.deserialize::<SerdeData>(&sample).is_some());\n\n }\n\n length\n\n}\n\n\n", "file_path": "serde-generate/src/test_utils.rs", "rank": 99, "score": 147408.5125476221 } ]
Rust
generate-assets/src/lib.rs
BlackPhlox/bevy-website
3a84400990d4d85e40303ba4bc3e1e85f63c991d
use cratesio_dbdump_csvtab::rusqlite::Connection; use cratesio_dbdump_lookup::{get_versions, CrateDependency, CrateLookup}; use rand::{thread_rng, Rng}; use serde::Deserialize; use std::{fs, io, path::PathBuf, str::FromStr}; #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct Asset { pub name: String, pub link: String, pub description: String, pub order: Option<usize>, pub image: Option<String>, pub color: Option<String>, pub emoji: Option<String>, #[serde(skip)] pub original_path: Option<PathBuf>, #[serde(skip)] pub tags: Vec<String>, #[serde(skip)] pub dependencies: Vec<CrateDependency>, #[serde(skip)] pub downloads: u32, #[serde(skip)] pub repo_url: Option<String>, #[serde(skip)] pub homepage_url: Option<String>, #[serde(skip)] pub last_update: i64, #[serde(skip)] pub latest_version: String, #[serde(skip)] pub license: String, } #[derive(Debug, Clone)] pub struct Section { pub name: String, pub content: Vec<AssetNode>, pub template: Option<String>, pub header: Option<String>, pub order: Option<usize>, pub sort_order_reversed: bool, } #[derive(Debug, Clone)] pub enum AssetNode { Section(Section), Asset(Asset), } impl AssetNode { pub fn name(&self) -> String { match self { AssetNode::Section(content) => content.name.clone(), AssetNode::Asset(content) => content.name.clone(), } } pub fn order(&self) -> usize { match self { AssetNode::Section(content) => content.order.unwrap_or(99999), AssetNode::Asset(content) => content.order.unwrap_or(99999), } } } fn visit_dirs(dir: PathBuf, section: &mut Section, db: &Connection) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.file_name().unwrap() == ".git" || path.file_name().unwrap() == ".github" { continue; } if path.is_dir() { let folder = path.file_name().unwrap(); let (order, sort_order_reversed) = if path.join("_category.toml").exists() { let from_file: toml::Value = toml::de::from_str( &fs::read_to_string(path.join("_category.toml")).unwrap(), ) .unwrap(); ( from_file .get("order") .and_then(|v| v.as_integer()) .map(|v| v as usize), from_file .get("sort_order_reversed") .and_then(|v| v.as_bool()) .unwrap_or(false), ) } else { (None, false) }; let mut new_section = Section { name: folder.to_str().unwrap().to_string(), content: vec![], template: None, header: None, order, sort_order_reversed, }; visit_dirs(path.clone(), &mut new_section, db)?; section.content.push(AssetNode::Section(new_section)); } else { if path.file_name().unwrap() == "_category.toml" || path.extension().unwrap() != "toml" { continue; } let mut asset: Asset = toml::de::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); asset.original_path = Some(path); populate_with_crate_io_data(db, &mut asset); section.content.push(AssetNode::Asset(asset)); } } } Ok(()) } fn populate_with_crate_io_data(db: &Connection, asset: &mut Asset) { if asset.image.is_none() && asset.emoji.is_none() { let emoji_code: u32 = thread_rng().gen_range(0x1F600..0x1F64F); let emoji = char::from_u32(emoji_code).unwrap_or('💔'); asset.emoji = Some(emoji.to_string()); } let co = db.get_crate(&asset.name); if let Ok(Some(c)) = co { let latest_version = &get_versions(db, asset.name.to_string(), true).unwrap()[0]; asset.latest_version = latest_version.1.clone(); let license = &latest_version.2; asset.license = license.to_string(); if asset.description.is_empty() { asset.description = c.description; } asset.homepage_url = c.homepage_url; let dt = chrono::NaiveDateTime::parse_from_str(c.last_update.as_str(), "%Y-%m-%d %H:%M:%S%.6f"); if let Ok(n_date_time) = dt { asset.last_update = n_date_time.format("%s").to_string().parse().unwrap(); } else { println!("{:?}", dt.unwrap_err()); } asset.downloads = c.downloads; asset.tags = c .keywords .into_iter() .filter(|s| !(s.eq("bevy") || s.eq("bevyengine") || s.eq("gamedev") || s.eq("game"))) .collect(); asset.repo_url = c.repo_url; let mut crate_dependencies = c.dependencies; crate_dependencies.dedup_by_key(|cd| format!("{}{}", cd.crate_id, cd.version)); asset.dependencies = crate_dependencies .into_iter() .map(|f| { let is_bevy = (f.crate_id.eq("bevy") || f.crate_id.eq("bevy_app")) && f.version.ends_with(".0"); let v = if is_bevy { f.version[..f.version.len() - 2].to_string() } else { f.version } .replace("^", ""); CrateDependency { crate_id: f.crate_id, version: v, kind: f.kind, } }) .collect() } } pub fn parse_assets(asset_dir: &str, db: &Connection) -> io::Result<Section> { let mut asset_root_section = Section { name: "Assets".to_string(), content: vec![], template: Some("assets.html".to_string()), header: Some("Assets".to_string()), order: None, sort_order_reversed: false, }; visit_dirs( PathBuf::from_str(asset_dir).unwrap(), &mut asset_root_section, db, )?; Ok(asset_root_section) }
use cratesio_dbdump_csvtab::rusqlite::Connection; use cratesio_dbdump_lookup::{get_versions, CrateDependency, CrateLookup}; use rand::{thread_rng, Rng}; use serde::Deserialize; use std::{fs, io, path::PathBuf, str::FromStr}; #[derive(Deserialize, Debug, Clone)] #[serde(deny_unknown_fields)] pub struct Asset { pub name: String, pub link: String, pub description: String, pub order: Option<usize>, pub image: Option<String>, pub color: Option<String>, pub emoji: Option<String>, #[serde(skip)] pub original_path: Option<PathBuf>, #[serde(skip)] pub tags: Vec<String>, #[serde(skip)] pub dependencies: Vec<CrateDependency>, #[serde(skip)] pub downloads: u32, #[serde(skip)] pub repo_url: Option<String>, #[serde(skip)] pub homepage_url: Option<String>, #[serde(skip)] pub last_update: i64, #[serde(skip)] pub latest_version: String, #[serde(skip)] pub license: String, } #[derive(Debug, Clone)] pub struct Section { pub name: String, pub content: Vec<AssetNode>, pub template: Option<String>, pub header: Option<String>, pub order: Option<usize>, pub sort_order_reversed: bool, } #[derive(Debug, Clone)] pub enum AssetNode { Section(Section), Asset(Asset), } impl AssetNode { pub fn name(&self) -> String { match self { AssetNode::Section(content) => content.name.clone(), AssetNode::Asset(content) => content.name.clone(), } } pub fn order(&self) -> usize { match self { AssetNode::Section(content) => content.order.unwrap_or(99999), AssetNode::Asset(content) => content.order.unwrap_or(99999), } } } fn visit_dirs(dir: PathBuf, section: &mut Section, db: &Connection) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.file_name().unwrap() == ".git" || path.file_name().unwrap() == ".github" { continue; } if path.is_dir() { let folder = path.file_name().unwrap(); let (order, sort_order_reversed) = if path.join("_category.toml").exists() { let from_file: toml::Value = toml::de::from_str( &fs::read_to_string(path.join("_category.toml")).unwrap(), ) .unwrap(); ( from_file .get("order") .and_then(|v| v.as_integer()) .map(|v| v as usize), from_file .get("sort_order_reversed") .and_then(|v| v.as_bool()) .unwrap_or(false), ) } else { (None, false) }; let mut new_section = Section { name: folder.to_str().unwrap().to_string(), content: vec![], template: None, header: None, order, sort_order_reversed, }; visit_dirs(path.clone(), &mut new_section, db)?; section.content.push(AssetNode::Section(new_section)); } else { if path.file_name().unwrap() == "_category.toml" || path.extension().unwrap() != "toml" {
fn populate_with_crate_io_data(db: &Connection, asset: &mut Asset) { if asset.image.is_none() && asset.emoji.is_none() { let emoji_code: u32 = thread_rng().gen_range(0x1F600..0x1F64F); let emoji = char::from_u32(emoji_code).unwrap_or('💔'); asset.emoji = Some(emoji.to_string()); } let co = db.get_crate(&asset.name); if let Ok(Some(c)) = co { let latest_version = &get_versions(db, asset.name.to_string(), true).unwrap()[0]; asset.latest_version = latest_version.1.clone(); let license = &latest_version.2; asset.license = license.to_string(); if asset.description.is_empty() { asset.description = c.description; } asset.homepage_url = c.homepage_url; let dt = chrono::NaiveDateTime::parse_from_str(c.last_update.as_str(), "%Y-%m-%d %H:%M:%S%.6f"); if let Ok(n_date_time) = dt { asset.last_update = n_date_time.format("%s").to_string().parse().unwrap(); } else { println!("{:?}", dt.unwrap_err()); } asset.downloads = c.downloads; asset.tags = c .keywords .into_iter() .filter(|s| !(s.eq("bevy") || s.eq("bevyengine") || s.eq("gamedev") || s.eq("game"))) .collect(); asset.repo_url = c.repo_url; let mut crate_dependencies = c.dependencies; crate_dependencies.dedup_by_key(|cd| format!("{}{}", cd.crate_id, cd.version)); asset.dependencies = crate_dependencies .into_iter() .map(|f| { let is_bevy = (f.crate_id.eq("bevy") || f.crate_id.eq("bevy_app")) && f.version.ends_with(".0"); let v = if is_bevy { f.version[..f.version.len() - 2].to_string() } else { f.version } .replace("^", ""); CrateDependency { crate_id: f.crate_id, version: v, kind: f.kind, } }) .collect() } } pub fn parse_assets(asset_dir: &str, db: &Connection) -> io::Result<Section> { let mut asset_root_section = Section { name: "Assets".to_string(), content: vec![], template: Some("assets.html".to_string()), header: Some("Assets".to_string()), order: None, sort_order_reversed: false, }; visit_dirs( PathBuf::from_str(asset_dir).unwrap(), &mut asset_root_section, db, )?; Ok(asset_root_section) }
continue; } let mut asset: Asset = toml::de::from_str(&fs::read_to_string(&path).unwrap()).unwrap(); asset.original_path = Some(path); populate_with_crate_io_data(db, &mut asset); section.content.push(AssetNode::Asset(asset)); } } } Ok(()) }
function_block-function_prefix_line
[ { "content": "fn visit_dirs(dir: PathBuf, section: &mut Section) -> io::Result<()> {\n\n if !dir.is_dir() {\n\n // Todo: after the 0.6 release, remove this if statement\n\n // For now we will allow this to be able to point to the `latest` branch (0.5)\n\n // which does not yet include error codes\n\n return Ok(());\n\n }\n\n assert!(dir.is_dir(), \"The path to the errors is not a directory\");\n\n for entry in fs::read_dir(dir)? {\n\n let entry = entry?;\n\n let path = entry.path();\n\n if path.file_name().unwrap() == \".git\" || path.file_name().unwrap() == \".github\" {\n\n continue;\n\n }\n\n if !path.is_dir() {\n\n if path.extension().unwrap() != \"md\" {\n\n continue;\n\n }\n\n\n\n let error_code = read_to_string(path.clone())?;\n", "file_path": "generate-errors/src/lib.rs", "rank": 3, "score": 188629.4206471068 }, { "content": "pub fn parse_errors(errors_dir: &str) -> io::Result<Section> {\n\n let mut errors_root_section = Section {\n\n name: \"Errors\".to_string(),\n\n content: vec![],\n\n template: Some(\"errors.html\".to_string()),\n\n header: Some(\"Errors\".to_string()),\n\n order: None,\n\n sort_order_reversed: false,\n\n };\n\n visit_dirs(\n\n PathBuf::from_str(&errors_dir).unwrap(),\n\n &mut errors_root_section,\n\n )?;\n\n Ok(errors_root_section)\n\n}\n", "file_path": "generate-errors/src/lib.rs", "rank": 4, "score": 145146.51829922237 }, { "content": "import re\n\nimport os\n\nimport sys\n\n\n\nname_fix = {\n\n 'bevy_nbody': 'thallada-bevy_nbody',\n\n 'bevy-nbody': 'WhoisDavid-bevy-nbody',\n\n}\n\n\n\nf = open(sys.argv[1] + \"/README.md\")\n\nlines = f.readlines()\n\n\n\nroot_folder = sys.argv[2] + \"/\"\n\nos.mkdir(root_folder)\n\n\n\ncategory = None\n\nsubcategory = None\n\ncurrent_path = root_folder\n\nfor line in lines:\n\n if line[0:3] == \"## \":\n\n category = line.split(\"# \")[1][0:-1]\n\n current_path = root_folder + category\n\n os.mkdir(current_path)\n\n elif line[0:3] == \"###\":\n\n subcategory = line.split(\"# \")[1][0:-1]\n\n current_path = root_folder + category + \"/\" + subcategory\n\n os.mkdir(current_path)\n\n elif line[0:2] == \"* \":\n\n line = line[0:-1]\n\n m = re.search('\\* \\[([^]]*)\\]\\(([^)]*)\\)(: (.*))?', line)\n\n name = m.group(1)\n\n link = m.group(2)\n\n desc = m.group(4)\n\n if name in name_fix:\n\n name = name_fix[name]\n\n f = open(current_path + '/' + name.replace(' ', '-').replace('/', '-') + \".toml\", \"w\")\n\n f.write(\"name = \\\"\" + name + \"\\\"\\n\")\n\n if desc is not None:\n\n f.write(\"description = \\\"\" + desc.replace('\"', '\\'') + \"\\\"\\n\")\n\n f.write(\"link = \\\"\" + link + \"\\\"\\n\")\n\n f.close()\n\n\n", "file_path": "generate-assets/parse_old_readme.py", "rank": 5, "score": 49679.26098738263 }, { "content": "+++\n\ntitle = \"Posts\"\n\nsort_by = \"date\"\n\ntemplate = \"news.html\"\n\npage_template = \"news-page.html\"\n\ninsert_anchor_links = \"right\"\n\n+++\n", "file_path": "content/news/_index.md", "rank": 13, "score": 33116.67832645362 }, { "content": "+++\n\ntitle = \"Learn\"\n\ntemplate = \"learn.html\"\n\n[extra]\n\nheader_message = \"Learn\"\n", "file_path": "content/learn/index.md", "rank": 14, "score": 33116.35648836087 }, { "content": "+++\n\ntitle = \"Community\"\n\ntemplate = \"community.html\"\n\n[extra]\n\nheader_message = \"Community\"\n", "file_path": "content/community/_index.md", "rank": 15, "score": 33116.35648836087 }, { "content": "### Interact with Fields Using Their Names\n\n\n\n```rust\n\nassert_eq!(*foo.get_field::<u32>(\"a\").unwrap(), 1);\n\n\n\n*foo.get_field_mut::<u32>(\"a\").unwrap() = 2;\n\n\n\nassert_eq!(foo.a, 2);\n\n```\n\n\n\n### Patch Your Types With New Values\n\n\n\n```rust\n\nlet mut dynamic_struct = DynamicStruct::default();\n\ndynamic_struct.insert(\"a\", 42u32);\n\ndynamic_struct.insert(\"c\", vec![3, 4, 5]);\n\n\n\nfoo.apply(&dynamic_struct);\n\n\n\nassert_eq!(foo.a, 42);\n\nassert_eq!(foo.c, vec![3, 4, 5]);\n\n```\n\n\n\n### Look Up Nested Fields Using \"Path Strings\"\n\n\n\n```rust\n\nlet value = *foo.get_path::<String>(\"b[0].value\").unwrap();\n\nassert_eq!(value.as_str(), \"hello world\");\n\n```\n\n\n\n### Iterate Over Struct Fields\n\n\n\n```rust\n\nfor (i, value: &Reflect) in foo.iter_fields().enumerate() {\n\n let field_name = foo.name_at(i).unwrap();\n\n if let Ok(value) = value.downcast_ref::<u32>() {\n\n println!(\"{} is a u32 with the value: {}\", field_name, *value);\n\n } \n\n}\n\n```\n\n\n\n### Automatically Serialize And Deserialize With Serde\n\n\n\nThis doesn't require manual Serde impls!\n\n\n\n```rust\n\nlet mut registry = TypeRegistry::default();\n\nregistry.register::<u32>();\n\nregistry.register::<String>();\n\nregistry.register::<Bar>();\n\n\n\nlet serializer = ReflectSerializer::new(&foo, &registry);\n\nlet serialized = ron::ser::to_string_pretty(&serializer, ron::ser::PrettyConfig::default()).unwrap();\n\n\n\nlet mut deserializer = ron::de::Deserializer::from_str(&serialized).unwrap();\n\nlet reflect_deserializer = ReflectDeserializer::new(&registry);\n\nlet value = reflect_deserializer.deserialize(&mut deserializer).unwrap();\n\nlet dynamic_struct = value.take::<DynamicStruct>().unwrap();\n\n\n\n/// reflect has its own partal_eq impl\n\nassert!(foo.reflect_partial_eq(&dynamic_struct).unwrap());\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 16, "score": 32622.10162841106 }, { "content": "### Trait Reflection\n\n\n\nYou can now call a trait on a given `&dyn Reflect` reference without knowing the underlying type! This is a form of magic that should probably be avoided in most situations. But in the few cases where it is completely necessary, it is very useful:\n\n\n\n```rust\n\n#[derive(Reflect)]\n\n#[reflect(DoThing)]\n\nstruct MyType {\n\n value: String,\n\n}\n\n\n\nimpl DoThing for MyType {\n\n fn do_thing(&self) -> String {\n\n format!(\"{} World!\", self.value)\n\n }\n\n}\n\n\n\n#[reflect_trait]\n\npub trait DoThing {\n\n fn do_thing(&self) -> String;\n\n}\n\n\n\n// First, lets box our type as a Box<dyn Reflect>\n\nlet reflect_value: Box<dyn Reflect> = Box::new(MyType {\n\n value: \"Hello\".to_string(),\n\n});\n\n\n\n/* \n\nThis means we no longer have direct access to MyType or it methods. We can only call Reflect methods on reflect_value. What if we want to call `do_thing` on our type? We could downcast using reflect_value.get::<MyType>(), but what if we don't know the type at compile time?\n\n*/\n\n\n\n// Normally in rust we would be out of luck at this point. Lets use our new reflection powers to do something cool!\n\nlet mut type_registry = TypeRegistry::default()\n\ntype_registry.register::<MyType>();\n\n\n\n/*\n\nThe #[reflect] attribute we put on our DoThing trait generated a new `ReflectDoThing` struct, which implements TypeData. This was added to MyType's TypeRegistration.\n\n*/\n\n\n\nlet reflect_do_thing = type_registry\n\n .get_type_data::<ReflectDoThing>(reflect_value.type_id())\n\n .unwrap();\n\n\n\n// We can use this generated type to convert our `&dyn Reflect` reference to an `&dyn DoThing` reference\n\nlet my_trait: &dyn DoThing = reflect_do_thing.get(&*reflect_value).unwrap();\n\n\n\n// Which means we can now call do_thing(). Magic!\n\nprintln!(\"{}\", my_trait.do_thing());\n\n```\n\n\n\n\n\n## 3D Texture Assets\n\n\n\n<div class=\"release-feature-authors\">authors: @bonsairobo</div>\n\n\n\nThe Texture asset now has support for 3D textures. The new `array_texture.rs` example illustrates how to load a 3d texture and sample from each \"layer\".\n\n\n\n![array_texture](array_texture.png)\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 17, "score": 32612.797464470095 }, { "content": "### Changed\n\n\n\n- [Bevy ECS V2][1525]\n\n- [Fix Reflect serialization of tuple structs][1366]\n\n- [color spaces and representation][1572]\n\n- [Make vertex buffers optional][1485]\n\n- [add to lower case to make asset loading case insensitive][1427]\n\n- [Replace right/up/forward and counter parts with local_x/local_y and local_z][1476]\n\n- [Use valid keys to initialize AHasher in FixedState][1268]\n\n- [Change Name to take Into<String> instead of String][1283]\n\n- [Update to wgpu-rs 0.7][542]\n\n- [Update glam to 0.13.0.][1550]\n\n- [use std clamp instead of Bevy's][1644]\n\n- [Make Reflect impls unsafe (Reflect::any must return `self`)][1679]\n\n\n\n### Fixed\n\n\n\n- [convert grayscale images to rgb][1524]\n\n- [Glb textures should use bevy_render to load images][1454]\n\n- [Don't panic on error when loading assets][1286]\n\n- [Prevent ImageBundles from causing constant layout recalculations][1299]\n\n- [do not check for focus until cursor position has been set][1070]\n\n- [Fix lock order to remove the chance of deadlock][1121]\n\n- [Prevent double panic in the Drop of TaksPoolInner][1064]\n\n- [Ignore events when receiving unknown WindowId][1072]\n\n- [Fix potential bug when using multiple lights.][1055]\n\n- [remove panics when mixing UI and non UI entities in hierarchy][1180]\n\n- [fix label to load gltf scene][1204]\n\n- [fix repeated gamepad events][1221]\n\n- [Fix iOS touch location][1224]\n\n- [Don't panic if there's no index buffer and call draw][1229]\n\n- [Fix Bug in Asset Server Error Message Formatter][1340]\n\n- [add_stage now checks Stage existence][1346]\n\n- [Fix Un-Renamed add_resource Compile Error][1357]\n\n- [Fix Interaction not resetting to None sometimes][1315]\n\n- [Fix regression causing \"flipped\" sprites to be invisible][1399]\n\n- [revert default vsync mode to Fifo][1416]\n\n- [Fix missing paths in ECS SystemParam derive macro][1434]\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 18, "score": 32610.875988489024 }, { "content": "## Event Ergonomics\n\n\n\n<div class=\"release-feature-authors\">authors: @TheRawMeatball</div>\n\n\n\nEvents now have a first-class shorthand syntax for easier consumption:\n\n\n\n```rust\n\n// Old Bevy 0.4 syntax\n\nfn system(mut reader: Local<EventReader<SomeEvent>>, events: Res<Events<SomeEvent>>) {\n\n for event in reader.iter(&events) {\n\n }\n\n}\n\n\n\n// New Bevy 0.5 syntax\n\nfn system(mut reader: EventReader<SomeEvent>) {\n\n for event in reader.iter() {\n\n }\n\n}\n\n```\n\n\n\nThere is also now a symmetrical `EventWriter` api:\n\n\n\n```rust\n\nfn system(mut writer: EventWriter<SomeEvent>) {\n\n writer.send(SomeEvent { ... })\n\n}\n\n```\n\n\n\nThe old \"manual\" approach is still possible via `ManualEventReader`:\n\n\n\n```rust\n\nfn system(mut reader: Local<ManualEventReader<SomeEvent>>, events: Res<Events<SomeEvent>>) {\n\n for event in reader.iter(&events) {\n\n }\n\n}\n\n```\n\n\n\n## Rich Text\n\n\n\n<div class=\"release-feature-authors\">authors: @tigregalis</div>\n\n\n\nText can now have \"sections\", each with their own style / formatting. This makes text much more flexible, while still respecting the text layout rules:\n\n\n\n![rich_text](rich_text.png)\n\n\n\nThis is accomplished using the new \"text section\" api:\n\n\n\n```rust\n\ncommands\n\n .spawn_bundle(TextBundle {\n\n text: Text {\n\n sections: vec![\n\n TextSection {\n\n value: \"FPS: \".to_string(),\n\n style: TextStyle {\n\n font: asset_server.load(\"FiraSans-Bold.ttf\"),\n\n font_size: 90.0,\n\n color: Color::WHITE,\n\n },\n\n },\n\n TextSection {\n\n value: \"60.03\".to_string(),\n\n style: TextStyle {\n\n font: asset_server.load(\"FiraMono-Medium.ttf\"),\n\n font_size: 90.0,\n\n color: Color::GOLD,\n\n },\n\n },\n\n ],\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n })\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 19, "score": 32606.72750918065 }, { "content": "When I was first building Bevy, I decided that the engine would benefit from such features. Reflection is a good foundation for scene systems, Godot-like (or Unity-like) property animation systems, and editor inspection tools. I built the `bevy_property` and `bevy_type_registry` crates to fill these needs.\n\n\n\nThey got the job done, but they were custom-tailored to Bevy's needs, were full of custom jargon (rather than reflecting Rust language constructs directly), didn't handle traits, and had a number of fundamental restrictions on how data could be accessed. \n\n\n\nIn this release we replaced the old `bevy_property` and `bevy_type_registry` crates with a new {{rust_mod(crate=\"bevy_reflect\" version=\"0.4.0\")}} crate. Bevy Reflect is intended to be a \"generic\" Rust reflection crate. I'm hoping it will be as useful for non-Bevy projects as it is for Bevy. We now use it for our Scene system, but in the future we will use it for animating Component fields and auto-generating Bevy Editor inspector widgets.\n\n\n\nBevy Reflect enables you to dynamically interact with Rust types by deriving the {{rust_type(type=\"trait\" crate=\"bevy_reflect\" version=\"0.4.0\" name=\"Reflect\" no_mod=true)}} trait:\n\n\n\n```rust\n\n#[derive(Reflect)]\n\nstruct Foo {\n\n a: u32,\n\n b: Vec<Bar>,\n\n c: Vec<u32>,\n\n}\n\n\n\n#[derive(Reflect)]\n\nstruct Bar {\n\n value: String\n\n}\n\n\n\n// I'll use this value to illustrate `bevy_reflect` features\n\nlet mut foo = Foo {\n\n a: 1,\n\n b: vec![Bar { value: \"hello world\" }]\n\n c: vec![1, 2]\n\n};\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 20, "score": 32605.96096180967 }, { "content": "### Top-Level GLTF Asset\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n\nPreviously it was hard to interact with GLTF assets because scenes / meshes / textures / and materials were only loaded as \"sub assets\". Thanks to the new top level {{rust_type(type=\"struct\" crate=\"bevy_gltf\" version=\"0.5.0\" name=\"Gltf\" no_mod=true)}} asset type, it is now possible to navigate the contents of the GLTF asset:\n\n\n\n```rust\n\n// load GLTF asset on startup\n\nfn setup(mut commands: Commands, assets: Res<AssetServer>) {\n\n let handle = assets.load(\"flight_helmet.gltf\");\n\n commands.insert_resource(handle);\n\n}\n\n\n\n// access GLTF asset at some later point in time\n\nfn system(handle: Res<Handle<Gltf>>, gltfs: Res<Assets<Gltf>>, materials: Res<Assets<StandardMaterial>>) {\n\n let gltf = gltfs.get(&handle).unwrap();\n\n let material_handle = gltf.named_materials.get(\"MetalPartsMat\").unwrap();\n\n let material = materials.get(material_handle).unwrap();\n\n}\n\n```\n\n\n\n## Bevy ECS V2\n\n\n\nThis release marks a huge step forward for Bevy's ECS. It has significant implications for how Bevy Apps are composed and how well they perform:\n\n\n\n* **[A full rewrite of the ECS core:](#ecs-core-rewrite)**\n\n * Massively improved performance across the board\n\n * \"Hybrid\" component storage\n\n * An \"Archetype Graph\" for faster archetype changes \n\n * Stateful queries that cache results across runs\n\n* **[A brand new parallel System executor:](#new-parallel-system-executor)**\n\n * Support for explicit system ordering\n\n * System Labels\n\n * System Sets\n\n * Improved system \"run criteria\"\n\n * Increased system parallelism\n\n* **[\"Reliable\" change detection:](#reliable-change-detection)**\n\n * Systems will now always detect component changes, even across frames\n\n* **[A rewrite of the State system:](#states-v2)** \n\n * A much more natural \"stack-based state machine\" model\n\n * Direct integration with the new scheduler \n\n * Improved \"state lifecycle\" events\n\n\n\nRead on for the details!\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 21, "score": 32605.929431560846 }, { "content": "#### Stage Trait\n\n\n\nStages are now a trait. You can now implement your own {{rust_type(type=\"trait\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"Stage\" no_mod=true)}} types!\n\n\n\n```rust\n\nstruct MyStage;\n\n\n\nimpl Stage for MyStage {\n\n fn run(&mut self, world: &mut World, resources: &mut Resources) {\n\n // Do stage stuff here.\n\n // You have unique access to the World and Resources, so you are free to do anything\n\n }\n\n}\n\n```\n\n\n\n#### Stage Type: {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"SystemStage\" no_mod=true)}}\n\n\n\nThis is basically a \"normal\" stage. You can add systems to it and you can decide how those systems will be executed (parallel, serial, or custom logic)\n\n\n\n```rust\n\n// runs systems in parallel (using the default parallel executor)\n\nlet parallel_stage =\n\n SystemStage::parallel()\n\n .with_system(a.system())\n\n .with_system(b.system());\n\n\n\n// runs systems serially (in registration order)\n\nlet serial_stage =\n\n SystemStage::serial()\n\n .with_system(a.system())\n\n .with_system(b.system());\n\n\n\n// you can also write your own custom SystemStageExecutor\n\nlet custom_executor_stage =\n\n SystemStage::new(MyCustomExecutor::new())\n\n .with_system(a.system())\n\n .with_system(b.system());\n\n```\n\n\n\n#### Stage Type: {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"Schedule\" no_mod=true)}}\n\n\n\nYou read that right! {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"Schedule\" no_mod=true)}} now implements the {{rust_type(type=\"trait\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"Stage\" no_mod=true)}} trait, which means you can nest Schedules within other schedules:\n\n\n\n```rust\n\nlet schedule = Schedule::default()\n\n .with_stage(\"update\", SystemStage::parallel()\n\n .with_system(a.system())\n\n .with_system(b.system())\n\n )\n\n .with_stage(\"nested\", Schedule::default()\n\n .with_stage(\"nested_stage\", SystemStage::serial()\n\n .with_system(b.system())\n\n )\n\n );\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 22, "score": 32605.807219333652 }, { "content": "#### Fragmented Iterator Benchmark (in milliseconds, less is better)\n\n\n\nThis is the [ecs_bench_suite](https://github.com/rust-gamedev/ecs_bench_suite) `frag_iter` benchmark. It runs a query on 27 archetypes with 20 entities each. However unlike the \"Sparse Fragmented Iterator Benchmark\", there are no \"unmatched\" archetypes. This test uses \"table storage\" across the board.\n\n\n\n![frag_iter](frag_iter.svg)\n\n\n\nThe gains here compared to the last benchmark are smaller because there aren't any unmatched archetypes. However **Bevy 0.5** still gets a nice boost due to better iterator/query impls, amortizing the cost of matched archetypes to zero, and for_each iterators. \n\n\n\n### Uber Fast \"for_each\" Query Iterators\n\n\n\nDevelopers now have the choice to use a fast {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"system\" version=\"0.5.0\" name=\"Query\" no_mod=true method=\"for_each\")}} iterator, which yields ~1.5-3x iteration speed improvements for \"fragmented iteration\", and minor ~1.2x iteration speed improvements for unfragmented iteration. \n\n\n\n```rust\n\nfn system(query: Query<(&A, &mut B)>) {\n\n // you now have the option to do this for a speed boost\n\n query.for_each_mut(|(a, mut b)| {\n\n });\n\n\n\n // however normal iterators are still available\n\n for (a, mut b) in query.iter_mut() {\n\n }\n\n}\n\n```\n\n\n\nWe will continue to encourage \"normal\" iterators as they are more flexible and more \"rust idiomatic\". But when that extra \"oomf\" is needed, `for_each` will be there ... waiting for you :)\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 23, "score": 32604.91294601906 }, { "content": "+++\n\ntitle = \"Bevy 0.2\"\n\ndate = 2020-09-19\n\n[extra]\n\nauthor = \"Carter Anderson\"\n\ntwitter = \"cart_cart\"\n\ngithub = \"cart\"\n\nyoutube = \"cartdev\"\n\nimage = \"matching_squares.png\"\n\nshow_image = true\n\nimage_subtitle = \"Matching Squares by @TheNeikos\"\n\nimage_subtitle_link = \"https://github.com/TheNeikos/bevy_squares\"\n\n+++\n\n\n\nA month after the initial Bevy release, and thanks to **87** contributors, **174** pull requests, and our [**generous sponsors**](https://github.com/sponsors/cart), I'm happy to announce the **Bevy 0.2** release on [crates.io](https://crates.io/crates/bevy)!\n\n\n\nFor those who don't know, Bevy is a refreshingly simple data-driven game engine built in Rust. You can check out [Quick Start Guide](/learn/book/getting-started/) to get started. Bevy is also free and open source forever! You can grab the full [source code](https://github.com/bevyengine/bevy) on GitHub.\n\n\n\nHere are some of the highlights from this release:\n\n\n\n<!-- more -->\n\n\n\n## Async Task System\n\n\n\n<div class=\"release-feature-authors\">authors: @lachlansneff and @aclysma</div>\n\n\n\nBevy uses multi-threading throughout the engine: ECS scheduling, asset loading, rendering, etc. Before this release it used [Rayon](https://github.com/rayon-rs/rayon) for almost all of these tasks. Rayon is nice because it is generally as simple as calling `some_list.par_iter().for_each(|x| do_something(x))`. Rayon then automatically breaks the `for_each` into tasks and runs them on as many cores as it can. Rayon is a great choice if you want to easily parallelize code, but it has the downside of being pretty cpu-hungry.\n\n\n\nBevy (and a number of other rust game engines and ecs frameworks using rayon) have received feedback that they were overly cpu hungry / usage was not proportional to \"real\" work done.\n\n\n\nWe decided to resolve this problem by building a custom async-friendly task system, which enables the creation of context-specific task pools. For example, you might have separate pools for compute, IO, networking, etc. This also gives us the flexibility to load balance work appropriately according to work type and/or priority. The cpu usage wins have been huge:\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 24, "score": 32603.798798301894 }, { "content": "## Wireframes\n\n\n\n<div class=\"release-feature-authors\">authors: @Neo-Zhixing</div>\n\n\n\nBevy can now draw wireframes using the opt-in `WireframePlugin`\n\n\n\n![wireframe](wireframe.png)\n\n\n\nThese can either be enabled globally or per-entity by adding the new `Wireframe` component.\n\n\n\n## Simple 3D Game Example: Alien Cake Addict\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n\nThis example serves as a quick introduction to building 3D games in Bevy. It shows how to spawn scenes, respond to input, implement game logic, and handle state transitions. Pick up as many cakes as you can!\n\n\n\n![alien_cake_addict](alien_cake_addict.png)\n\n\n\n## Timer Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @kokounet</div>\n\n\n\nThe {{rust_type(type=\"struct\" crate=\"bevy_core\" version=\"0.5.0\" name=\"Timer\" no_mod=true)}} struct now internally uses {{rust_type(type=\"struct\" crate=\"std\" mod=\"time\" name=\"Duration\" no_mod=true plural=true)}} instead of using `f32` representations of seconds. This both increases precision and makes the api a bit nicer to look at.\n\n\n\n```rust\n\nfn system(mut timer: ResMut<Timer>, time: Res<Time>) {\n\n if timer.tick(time.delta()).just_finished() {\n\n println!(\"timer just finished\");\n\n }\n\n}\n\n```\n\n\n\n## Assets Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @willcrichton, @zicklag, @mockersf, @Archina</div>\n\n\n\nBevy's asset system had a few minor improvements this release:\n\n\n\n* Bevy no longer panics on errors when loading assets\n\n* Asset paths with multiple dots are now properly handled\n\n* Improved type safety for \"labeled assets\" produced by asset loaders \n\n* Made asset path loading case-insensitive \n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 25, "score": 32602.85372483055 }, { "content": "Bevy's scheduler pre-checks `Queries` once ahead of time, which allows systems to access their results without any additional checks.\n\n\n\nThe test was to lookup (and modify) a specific entity's component 100,000 times on each system iteration. Here is a quick rundown of how these tests were performed in each case:\n\n\n\n* bevy (world): Direct `World` access using `world.get_mut::<A>(entity)`\n\n* bevy (system): A system containing a `Query<&mut A>` that accesses the component using `query.get_mut(entity)`\n\n* legion (world): Direct `World` access using `let entry = world.entry(entity); entry.get_component_mut::<A>()`\n\n* legion (system): A system with `SubWorld` access using `let entry = world.entry(entity); entry.get_component_mut::<A>()` \n\n\n\nIt's worth noting that using `query.get_component::<T>(entity)` instead of `query.get(entity)` does require safety checks, for the same reason the legion entry api does. We cannot know ahead of time what component type a caller will pass into the method, which means we _must_ check it to make sure it matches the `Query`. \n\n\n\nAdditionally, here are some relevant [ecs_bench_suite](https://github.com/rust-gamedev/ecs_bench_suite) results (omitted benchmarks had no significant change):\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 26, "score": 32602.763992579985 }, { "content": "### Changed\n\n \n\n- [Transform rewrite][374]\n\n- [Use generational entity ids and other optimizations][504]\n\n- [Optimize transform systems to only run on changes.][417]\n\n- [Send an AssetEvent when modifying using `get_id_mut`][323]\n\n- [Rename `Assets::get_id_mut` -> `Assets::get_with_id_mut`][332]\n\n- [Support multiline text in `DrawableText`][183]\n\n- [iOS: use shaderc-rs for glsl to spirv compilation][324]\n\n- [Changed the default node size to Auto instead of Undefined to match the Stretch implementation.][304]\n\n- [Load assets from root path when loading directly][478]\n\n- [Add `render` feature][485], which makes the entire render pipeline optional.\n\n\n\n### Fixed\n\n\n\n- [Properly track added and removed RenderResources in RenderResourcesNode.][361]\n\n - Fixes issues where entities vanished or changed color when new entities were spawned/despawned.\n\n- [Fixed sprite clipping at same depth][385]\n\n - Transparent sprites should no longer clip.\n\n- [Check asset path existence][345]\n\n- [Fixed deadlock in hot asset reloading][376]\n\n- [Fixed hot asset reloading on Windows][394]\n\n- [Allow glTFs to be loaded that don't have uvs and normals][406]\n\n- [Fixed archetypes_generation being incorrectly updated for systems][383]\n\n- [Remove child from parent when it is despawned][386]\n\n- [Initialize App.schedule systems when running the app][444]\n\n- [Fix missing asset info path for synchronous loading][486]\n\n- [fix font atlas overflow][495]\n\n- [do not assume font handle is present in assets][490]\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 27, "score": 32601.544429510595 }, { "content": "### Added\n\n\n\n- [PBR Rendering][1554]\n\n- [PBR Textures][1632]\n\n- [HIDPI Text][1132]\n\n- [Rich text][1245]\n\n- [Wireframe Rendering Pipeline][562]\n\n- [Render Layers][1209]\n\n- [Add Sprite Flipping][1407]\n\n- [OrthographicProjection scaling mode + camera bundle refactoring][400]\n\n- [3D OrthographicProjection improvements + new example][1361]\n\n- [Flexible camera bindings][1689]\n\n- [Render text in 2D scenes][1122]\n\n- [Text2d render quality][1171]\n\n- [System sets and run criteria v2][1675]\n\n- [System sets and parallel executor v2][1144]\n\n- [Many-to-many system labels][1576]\n\n- [Non-string labels (#1423 continued)][1473]\n\n- [Make EventReader a SystemParam][1244]\n\n- [Add EventWriter][1575]\n\n- [Reliable change detection][1471]\n\n- [Redo State architecture][1424]\n\n- [Query::get_unique][1263]\n\n- [gltf: load normal and occlusion as linear textures][1762]\n\n- [Add separate brightness field to AmbientLight][1605]\n\n- [world coords to screen space][1258]\n\n- [Experimental Frustum Culling (for Sprites)][1492]\n\n- [Enable wgpu device limits][1544]\n\n- [bevy_render: add torus and capsule shape][1223]\n\n- [New mesh attribute: color][1194]\n\n- [Minimal change to support instanced rendering][1262]\n\n- [Add support for reading from mapped buffers][1274]\n\n- [Texture atlas format and conversion][1365]\n\n- [enable wgpu device features][547]\n\n- [Subpixel text positioning][1196]\n\n- [make more information available from loaded GLTF model][1020]\n\n- [use Name on node when loading a gltf file][1183]\n\n- [GLTF loader: support mipmap filters][1639]\n\n- [Add support for gltf::Material::unlit][1341]\n\n- [Implement Reflect for tuples up to length 12][1218]\n\n- [Process Asset File Extensions With Multiple Dots][1277]\n\n- [Update Scene Example to Use scn.ron File][1339]\n\n- [3d game example][1252]\n\n- [Add keyboard modifier example (#1656)][1657]\n\n- [Count number of times a repeating Timer wraps around in a tick][1112]\n\n- [recycle `Timer` refactor to duration.sparkles Add `Stopwatch` struct.][1151]\n\n- [add scene instance entity iteration][1058]\n\n- [Make Commands and World apis consistent][1703]\n\n- [Add `insert_children` and `push_children` to EntityMut][1728]\n\n- [Extend AppBuilder api with `add_system_set` and similar methods][1453]\n\n- [add labels and ordering for transform and parent systems in POST_UPDATE stage][1456]\n\n- [Explicit execution order ambiguities API][1469]\n\n- [Resolve (most) internal system ambiguities][1606]\n\n- [Change 'components' to 'bundles' where it makes sense semantically][1257]\n\n- [add `Flags<T>` as a query to get flags of component][1172]\n\n- [Rename add_resource to insert_resource][1356]\n\n- [Update init_resource to not overwrite][1349]\n\n- [Enable dynamic mutable access to component data][1284]\n\n- [Get rid of ChangedRes][1313]\n\n- [impl SystemParam for Option<Res<T>> / Option<ResMut<T>>][1494]\n\n- [Add Window Resize Constraints][1409]\n\n- [Add basic file drag and drop support][1096]\n\n- [Modify Derive to allow unit structs for RenderResources.][1089]\n\n- [bevy_render: load .spv assets][1104]\n\n- [Expose wgpu backend in WgpuOptions and allow it to be configured from the environment][1042]\n\n- [updates on diagnostics (log + new diagnostics)][1085]\n\n- [enable change detection for labels][1155]\n\n- [Name component with fast comparisons][1109]\n\n- [Support for !Send tasks][1216]\n\n- [Add missing spawn_local method to Scope in the single threaded executor case][1266]\n\n- [Add bmp as a supported texture format][1081]\n\n- [Add an alternative winit runner that can be started when not on the main thread][1063]\n\n- [Added use_dpi setting to WindowDescriptor][1131]\n\n- [Implement Copy for ElementState][1154]\n\n- [Mutable mesh accessors: indices_mut and attribute_mut][1164]\n\n- [Add support for OTF fonts][1200]\n\n- [Add `from_xyz` to `Transform`][1212]\n\n- [Adding copy_texture_to_buffer and copy_texture_to_texture][1236]\n\n- [Added `set_minimized` and `set_position` to `Window`][1292]\n\n- [Example for 2D Frustum Culling][1503]\n\n- [Add remove resource to commands][1478]\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 28, "score": 32600.91234828213 }, { "content": "## Gamepad Settings\n\n\n\n<div class=\"release-feature-authors\">authors: @simpuid</div>\n\n\n\nThe newly added `GamepadSettings` resource gives developers the ability to customize gamepad settings on a per-controller, per-axis/button basis:\n\n\n\n```rust\n\nfn system(mut gamepad_settings: ResMut<GamepadSettings>) {\n\n gamepad_settings.axis_settings.insert(\n\n GamepadAxis(Gamepad(0), GamepadAxisType::LeftStickX),\n\n AxisSettings {\n\n positive_high: 0.8,\n\n positive_low: 0.01,\n\n ..Default::default()\n\n },\n\n );\n\n}\n\n```\n\n\n\n## Plugin Groups\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nIf you've used Bevy, you're probably familiar with this part of `App` initialization:\n\n\n\n```rust\n\napp.add_default_plugins();\n\n```\n\n\n\nThis adds the plugins for all of the \"core\" engine functionality (rendering, input, audio, windowing, etc). It was straightforward, but also very static. What if you don't want to add _all_ of the default plugins? What if you want to create your own custom set of plugins?\n\n\n\nTo resolve this, we added `PluginGroups`, which are ordered collections of plugins that can be individually enabled or disabled:\n\n\n\n```rust\n\n// This:\n\napp.add_default_plugins()\n\n\n\n// Has been replaced by this:\n\napp.add_plugins(DefaultPlugins)\n\n\n\n// You can disable specific plugins in a PluginGroup:\n\napp.add_plugins_with(DefaultPlugins, |group| {\n\n group.disable::<RenderPlugin>()\n\n .disable::<AudioPlugin>()\n\n});\n\n\n\n// And you can create your own PluginGroups:\n\npub struct HelloWorldPlugins;\n\n\n\nimpl PluginGroup for HelloWorldPlugins {\n\n fn build(&mut self, group: &mut PluginGroupBuilder) {\n\n group.add(PrintHelloPlugin)\n\n .add(PrintWorldPlugin);\n\n }\n\n}\n\n\n\napp.add_plugins(HelloWorldPlugins);\n\n```\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 29, "score": 32600.649242111635 }, { "content": "### Explicit System Dependencies and System Labels\n\n\n\n<div class=\"release-feature-authors\">authors: @Ratysz, @TheRawMeatball</div>\n\n\n\nSystems can now be assigned one or more {{rust_type(type=\"trait\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"SystemLabel\" no_mod=true plural=true)}}. These labels can then be referenced by other systems (within a stage) to run before or after systems with that label:\n\n\n\n```rust\n\napp\n\n .add_system(update_velocity.system().label(\"velocity\"))\n\n // The \"movement\" system will run after \"update_velocity\" \n\n .add_system(movement.system().after(\"velocity\"))\n\n```\n\n\n\nThis produces an equivalent ordering, but it uses `before()` instead.\n\n\n\n```rust\n\napp\n\n // The \"update_velocity\" system will run before \"movement\" \n\n .add_system(update_velocity.system().before(\"movement\"))\n\n .add_system(movement.system().label(\"movement\"));\n\n```\n\n\n\nAny type that implements the {{rust_type(type=\"trait\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"SystemLabel\" no_mod=true)}} trait can be used. In most cases we recommend defining custom types and deriving {{rust_type(type=\"trait\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"SystemLabel\" no_mod=true)}} for them. This prevents typos, allows for encapsulation (when needed), and allows IDEs to autocomplete labels:\n\n\n\n```rust\n\n#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)]\n\npub enum PhysicsSystem {\n\n UpdateVelocity,\n\n Movement,\n\n}\n\n\n\napp\n\n .add_system(update_velocity.system().label(PhysicsSystem::UpdateVelocity))\n\n .add_system(movement.system()\n\n .label(PhysicsSystem::Movement)\n\n .after(PhysicsSystem::UpdateVelocity)\n\n );\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 30, "score": 32600.54107484476 }, { "content": "### Query::single\n\n\n\n<div class=\"release-feature-authors\">authors: @TheRawMeatball</div>\n\n\n\nQueries now have {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"system\" version=\"0.5.0\" name=\"Query\" no_mod=true method=\"single\")}} and {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"system\" version=\"0.5.0\" name=\"Query\" no_mod=true method=\"single_mut\")}} methods, which return a single query result if there is _exactly_ one matching entity:\n\n\n\n```rust\n\nfn system(query: Query<&Player>) {\n\n // only returns Ok if there is exactly one Player\n\n if let Ok(player) = query.single() {\n\n }\n\n}\n\n```\n\n\n\n### Removed ChangedRes\n\n\n\n<div class=\"release-feature-authors\">authors: @TheRawMeatball</div>\n\n\n\nWe have removed `ChangedRes<A>` in favor of the following:\n\n\n\n\n\n```rust\n\nfn system(a: Res<A>) {\n\n if a.is_changed() {\n\n // do something\n\n }\n\n}\n\n```\n\n\n\n### Optional Resource Queries\n\n\n\n<div class=\"release-feature-authors\">authors: @jamadazi</div>\n\n\n\nIt is now possible for a system to check for Resource existence via `Option` queries:\n\n\n\n```rust\n\nfn system(a: Option<Res<A>>) {\n\n if let Some(a) = a {\n\n // do something\n\n }\n\n}\n\n```\n\n\n\n### New Bundle Naming Convention\n\n\n\nComponent Bundles previously used the `XComponents` naming convention (ex: `SpriteComponents`, `TextComponents`, etc). We decided to move to a `XBundle` naming convention (ex: `SpriteBundle`, `TextBundle`, etc) to be more explicit about what these types are and to help prevent new users from conflating Bundles and Components. \n\n\n\n### World Metadata Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\n`World` now has queryable `Components`, `Archetypes`, `Bundles`, and `Entities` collections:\n\n\n\n```rust\n\n// you can access these new collections from normal systems, just like any other SystemParam\n\nfn system(archetypes: &Archetypes, components: &Components, bundles: &Bundles, entities: &Entities) {\n\n}\n\n```\n\n\n\nThis enables developers to access internal ECS metadata from their Systems.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 31, "score": 32600.46044248304 }, { "content": "### Many-to-Many System Labels\n\n\n\nMany-to-many labels is a powerful concept that makes it easy to take a dependency on many systems that produce a given behavior/outcome. For example, if you have a system that needs to run after all \"physics\" has finished updating (see the example above), you could label all \"physics systems\" with the same `Physics` label:\n\n\n\n```rust\n\n#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)]\n\npub struct Physics;\n\n\n\n#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)]\n\npub enum PhysicsSystem {\n\n UpdateVelocity,\n\n Movement,\n\n}\n\n\n\napp\n\n .add_system(update_velocity.system()\n\n .label(PhysicsSystem::UpdateVelocity)\n\n .label(Physics)\n\n )\n\n .add_system(movement.system()\n\n .label(PhysicsSystem::Movement)\n\n .label(Physics)\n\n .after(PhysicsSystem::UpdateVelocity)\n\n )\n\n .add_system(runs_after_physics.system().after(Physics));\n\n```\n\n\n\nBevy plugin authors should export labels like this in their public APIs to enable their users to insert systems before/after logic provided by the plugin.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 32, "score": 32600.244928801727 }, { "content": "### Flexible ECS Parameters\n\n\n\nPrior versions of Bevy forced you to provide system parameters in a specific order:\n\n\n\n```rust\n\n/// This system followed the [Commands][Resources][Queries] order and compiled as expected\n\nfn valid_system(mut commands: Commands, time: Res<Time>, query: Query<&Transform>) {\n\n}\n\n\n\n/// This system did not follow the required ordering, which caused compilation to fail\n\nfn invalid_system(query: Query<&Transform>, mut commands: Commands, time: Res<Time>) {\n\n}\n\n```\n\n\n\nNewbies would fall prey to this constantly. These completely arbitrary constraints were a quirk of the internal implementation. The `IntoSystem` trait was only implemented for specific orders. Supporting every order would have exponentially affected compile times. The internal implementation was also constructed with a [famously complicated macro](https://github.com/bevyengine/bevy/blob/9afe196f1690a6a6e47bf67ac740b4edeffd97bd/crates/bevy_ecs/src/system/into_system.rs#L158).\n\n\n\nTo resolve this, I completely rewrote how we generate systems. We now use a `SystemParam` trait, which we implement for each parameter type. This has a number of benefits:\n\n\n\n* **Significantly Faster Compile Times**: We're seeing a <b style=\"color: rgb(50, 210, 50)\">~25%</b> decrease in clean compile times\n\n* **Use Any Parameter Order You Want**: No more arbitrary order restrictions!\n\n* **Easily Add New Parameters**: It is now easy for us (and for users) to create new parameters. Just implement the `SystemParam` trait!\n\n* **Simpler Implementation**: The new implementation is much smaller and also way easier to maintain and understand.\n\n\n\n```rust\n\n// In Bevy 0.4 this system is now perfectly valid. Cool!\n\nfn system(query: Query<&Transform>, commands: &mut Commands, time: Res<Time>) {\n\n}\n\n```\n\n\n\nNotice that in **Bevy 0.4**, commands now look like `commands: &mut Commands` instead of `mut commands: Commands`. \n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 33, "score": 32600.06997813481 }, { "content": "+++\n\ntitle = \"Bevy 0.3\"\n\ndate = 2020-11-03\n\n[extra]\n\nauthor = \"Carter Anderson\"\n\ntwitter = \"cart_cart\"\n\ngithub = \"cart\"\n\nyoutube = \"cartdev\"\n\nimage = \"sheep_game.png\"\n\nshow_image = true\n\nimage_subtitle = \"Sheep Game by @schneckerstein\"\n\nimage_subtitle_link = \"https://twitter.com/schneckerstein/status/1309491121555410945\"\n\n+++\n\n\n\nA little over a month after releasing Bevy 0.2, and thanks to **59** contributors, **122** pull requests, and our [**generous sponsors**](https://github.com/sponsors/cart), I'm happy to announce the **Bevy 0.3** release on [crates.io](https://crates.io/crates/bevy)!\n\n\n\nFor those who don't know, Bevy is a refreshingly simple data-driven game engine built in Rust. You can check out [Quick Start Guide](/learn/book/getting-started/) to get started. Bevy is also free and open source forever! You can grab the full [source code](https://github.com/bevyengine/bevy) on GitHub.\n\n\n\nHere are some of the highlights from this release:\n\n\n\n<!-- more -->\n\n\n\n## Initial Android Support\n\n\n\n<div class=\"release-feature-authors\">authors: @enfipy, @PrototypeNM1, @endragor, @naithar</div>\n\n\n\nYou can try out the [Bevy Android example](https://github.com/bevyengine/bevy/tree/v0.3.0/examples/android) by following the [instructions here](https://github.com/bevyengine/bevy/blob/v0.3.0/examples/README.md#android). While many things work, please note that this is _very hot_ off the presses. Some features will work and others probably won't. Now is a great time to dive in and help us close the gaps!\n\n\n\n![android](android.png)\n\n\n\n\n\nThis was a massive group effort that spanned multiple projects:\n\n\n\n* Bevy: rewrote bevy-glsl-to-spirv to support android / static libraries (@PrototypeNM1, @enfipy)\n\n* Bevy: `bevy_asset` backend using Android Asset Manager (@enfipy)\n\n* Bevy: Touch support (@naithar)\n\n* Bevy: Texture format fix (@enfipy)\n\n* Bevy: UI touch fixes, touch force, and android example (@enfipy)\n\n* Cpal: android audio support (@endragor) \n\n* android-ndk-rs / cargo-apk: fix to support Bevy project structure (@PrototypeNM1)\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 34, "score": 32599.972572267125 }, { "content": "### Stateful Queries and System Parameters\n\n\n\n{{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"world\" version=\"0.5.0\" name=\"World\" no_mod=true)}} queries (and other system parameters) are now stateful. This allows us to:\n\n\n\n1. Cache archetype (and table) matches\n\n * This resolves another issue with (naive) archetypal ECS: query performance getting worse as the number of archetypes goes up (and fragmentation occurs).\n\n2. Cache Query Fetch and Filter state\n\n * The expensive parts of fetch/filter operations (such as hashing the TypeId to find the ComponentId) now only happen once when the Query is first constructed\n\n3. Incrementally build up state\n\n * When new archetypes are added, we only process the new archetypes (no need to rebuild state for old archetypes)\n\n\n\nAs a result, the direct {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"world\" version=\"0.5.0\" name=\"World\" no_mod=true)}} query api now looks like this:\n\n\n\n```rust\n\nlet mut query = world.query::<(&A, &mut B)>();\n\nfor (a, mut b) in query.iter_mut(&mut world) {\n\n}\n\n```\n\n\n\nHowever for {{rust_type(type=\"trait\" crate=\"bevy_ecs\" mod=\"system\" version=\"0.5.0\" name=\"System\" no_mod=true plural=true)}} this is a non-breaking change. Query state management is done internally by the relevant SystemParam.\n\n\n\nWe have achieved some pretty significant performance wins as a result of the new Query system.\n\n\n\n#### \"Sparse\" Fragmented Iterator Benchmark (in nanoseconds, less is better)\n\n\n\nThis benchmark runs a query that matches 5 entities within a single archetype and _doesn't_ match 100 other archetypes. This is a reasonable test of \"real world\" queries in games, which generally have many different entity \"types\", most of which _don't_ match a given query. This test uses \"table storage\" across the board.\n\n\n\n![sparse_frag_iter](sparse_frag_iter.svg)\n\n\n\n\n\n**Bevy 0.5** marks a huge improvement for cases like this, thanks to the new \"stateful queries\". **Bevy 0.4** needs to check every archetype each time the iterator is run, whereas **Bevy 0.5** amortizes that cost to zero.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 35, "score": 32598.857920640494 }, { "content": "### Sub-Asset Loading\n\n\n\nSometimes you only want to load a specific asset from an asset source. You can now load sub assets like this:\n\n\n\n```rust\n\n// Mesh0/Primitive0 references the first mesh primitive in \"my_scene.gltf\"\n\nlet mesh = asset_server.load(\"my_scene.gltf#Mesh0/Primitive0\");\n\n```\n\n\n\n### AssetIo Trait\n\n\n\nThe `AssetServer` is now backed by the `AssetIo` trait. This allows us to load assets from whatever storage we want. This means on desktop we now load from the filesystem, on Android we use the Android Asset Manager, and on the web we make HTTP requests using the `fetch()` api.\n\n\n\n### Asset Dependencies\n\n\n\nAssets can now depend on other assets, which will automatically be loaded when the original asset is loaded. This is useful when loading something like a \"scene\" which might reference other asset sources. We utilize this in our new GLTF loader.\n\n\n\n### Removed AssetServer::load_sync()\n\n\n\nThis might rustle some feathers, but `AssetServer::load_sync()` had to go! This api wasn't WASM friendly, encouraged users to block game execution for the sake of convenience (which causes \"hitching\"), and was incompatible with the new AssetLoader api. Asset loading is now always asynchronous. Users of `load_sync()` should instead `load()` their assets, check load status in their systems, and change game state accordingly. \n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 36, "score": 32598.77834533777 }, { "content": "## States\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nBy popular demand, Bevy now supports States. These are logical \"app states\" that allow you to enable/disable systems according to the state your app is in.\n\n\n\nStates are defined as normal Rust enums:\n\n\n\n```rust\n\n#[derive(Clone)]\n\nenum AppState {\n\n Loading,\n\n Menu,\n\n InGame\n\n}\n\n```\n\n\n\nYou then add them to your app as a resource like this:\n\n\n\n```rust\n\n// add a new AppState resource that defaults to the Loading state\n\napp.add_resource(State::new(AppState::Loading))\n\n```\n\n\n\nTo run systems according to the current state, add a {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"StateStage\" no_mod=true)}}:\n\n\n\n```rust\n\napp.add_stage_after(stage::UPDATE, STAGE, StateStage::<AppState>::default())\n\n```\n\n\n\nYou can then add systems for each state value / lifecycle-event like this:\n\n\n\n```rust\n\napp\n\n .on_state_enter(STAGE, AppState::Menu, setup_menu.system())\n\n .on_state_update(STAGE, AppState::Menu, menu.system())\n\n .on_state_exit(STAGE, AppState::Menu, cleanup_menu.system())\n\n .on_state_enter(STAGE, AppState::InGame, setup_game.system())\n\n .on_state_update(STAGE, AppState::InGame, movement.system())\n\n```\n\n\n\nNotice that there are different \"lifecycle events\":\n\n\n\n* **on_enter**: Runs once when first entering a state\n\n* **on_exit**: Runs once when exiting a state\n\n* **on_update**: Runs exactly once on every run of the stage (after any on_enter or on_exit events have been run)\n\n\n\nYou can queue a state change from a system like this:\n\n\n\n```rust\n\nfn system(mut state: ResMut<State<AppState>>) {\n\n state.set_next(AppState::InGame).unwrap();\n\n}\n\n```\n\n\n\nQueued state changes get applied at the end of the StateStage. If you change state within a StateStage, the lifecycle events will occur in the same update/frame. You can do this any number of times (aka it will continue running state lifecycle systems until no more changes are queued). This ensures that multiple state changes can be applied within the same frame.\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 37, "score": 32598.40274654355 }, { "content": "### Changed\n\n\n\n- [delegate layout reflection to RenderResourceContext][691] \n\n- [Fall back to remove components one by one when failing to remove a bundle][719]\n\n- [Port hecs derive macro improvements][761] \n\n- [Use glyph_brush_layout and add text alignment support][765]\n\n- [upgrade glam and hexasphere][791]\n\n- [Flexible ECS Params][798]\n\n- [Make Timer.tick return &Self][820]\n\n- [FileAssetIo includes full path on error][821]\n\n- [Removed ECS query APIs that could easily violate safety from the public interface][829]\n\n- [Changed Query filter API to be easier to understand][834]\n\n- [bevy_render: delegate buffer aligning to render_resource_context][842]\n\n- [wasm32: non-spirv shader specialization][843]\n\n- [Renamed XComponents to XBundle][863]\n\n- [Check for conflicting system resource parameters][864]\n\n- [Tweaks to TextureAtlasBuilder.finish()][887]\n\n- [do not spend time drawing text with is_visible = false][893]\n\n- [Extend the Texture asset type to support 3D data][903]\n\n- [Breaking changes to timer API][914]\n\n - Created getters and setters rather than exposing struct members.\n\n- [Removed timer auto-ticking system][931]\n\n - Added an example of how to tick timers manually.\n\n- [When a task scope produces <= 1 task to run, run it on the calling thread immediately][932]\n\n- [Breaking changes to Time API][934]\n\n - Created getters to get `Time` state and made members private.\n\n - Modifying `Time`'s values directly is no longer possible outside of bevy.\n\n- [Use `mailbox` instead of `fifo` for vsync on supported systems][920]\n\n- [switch winit size to logical to be dpi independent][947]\n\n- [Change bevy_input::Touch API to match similar APIs][952]\n\n- [Run parent-update and transform-propagation during the \"post-startup\" stage (instead of \"startup\")][955]\n\n- [Renderer Optimization Round 1][958]\n\n- [Change`TextureAtlasBuilder` into expected Builder conventions][969]\n\n- [Optimize Text rendering / SharedBuffers][972]\n\n- [hidpi swap chains][973]\n\n- [optimize asset gpu data transfer][987]\n\n- [naming coherence for cameras][995]\n\n- [Schedule v2][1021]\n\n- [Use shaderc for aarch64-apple-darwin][1027]\n\n- [update `Window`'s `width` & `height` methods to return `f32`][1033]\n\n- [Break out Visible component from Draw][1034]\n\n - Users setting `Draw::is_visible` or `Draw::is_transparent` should now set `Visible::is_visible` and `Visible::is_transparent`\n\n- [`winit` upgraded from version 0.23 to version 0.24][1043]\n\n- [set is_transparent to true by default for UI bundles][1071]\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 38, "score": 32598.34382752126 }, { "content": "+++\n\ntitle = \"Bevy 0.5\"\n\ndate = 2021-04-06\n\n[extra]\n\nauthor = \"Carter Anderson\"\n\ntwitter = \"cart_cart\"\n\ngithub = \"cart\"\n\nyoutube = \"cartdev\"\n\nimage = \"ante.png\"\n\nshow_image = true\n\nimage_subtitle = \"Screenshot of Ante: a voxel builder game being developed in Bevy by @TheNeikos\"\n\nimage_subtitle_link = \"\"\n\n+++\n\n\n\nThanks to **88** contributors, **283** pull requests, and our [**generous sponsors**](https://github.com/sponsors/cart), I'm happy to announce the **Bevy 0.5** release on [crates.io](https://crates.io/crates/bevy)!\n\n\n\nFor those who don't know, Bevy is a refreshingly simple data-driven game engine built in Rust. You can check out [Quick Start Guide](/learn/book/getting-started/) to get started. Bevy is also free and open source forever! You can grab the full [source code](https://github.com/bevyengine/bevy) on GitHub. Check out [Awesome Bevy](https://github.com/bevyengine/awesome-bevy) for a list of community-developed plugins, games, and learning resources.\n\n\n\n**Bevy 0.5** is quite a bit bigger than our past few releases (and took a bit longer) as we have made a number of foundational changes. If you plan on updating your App or Plugin to **Bevy 0.5**, check out our [0.4 to 0.5 Migration Guide](/learn/book/migration-guides/0.4-0.5/).\n\n\n\nHere are some of the highlights from this release:\n\n\n\n\n\n<!-- more -->\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 39, "score": 32597.959829328644 }, { "content": "## WGPU Configuration Options\n\n\n\n<div class=\"release-feature-authors\">authors: @Neo-Zhixing</div>\n\n\n\nIt is now possible to enable/disable wgpu features (such as `WgpuFeature::PushConstants` and `WgpuFeature::NonFillPolygonMode`) by setting them in the `WgpuOptions` resource:\n\n\n\n\n\n```rust\n\napp\n\n .insert_resource(WgpuOptions {\n\n features: WgpuFeatures {\n\n features: vec![WgpuFeature::NonFillPolygonMode],\n\n },\n\n ..Default::default()\n\n })\n\n\n\n```\n\n\n\nWgpu limits (such as `WgpuLimits::max_bind_groups`) can also now be configured in the `WgpuOptions` resource.\n\n\n\n## Scene Instance Entity Iteration\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n\nIt is now possible to iterate all entities in a spawned scene instance. This makes it possible to perform post-processing on scenes after they have been loaded.\n\n\n\n\n\n```rust\n\nstruct MySceneInstance(InstanceId);\n\n\n\nfn setup(\n\n mut commands: Commands,\n\n asset_server: Res<AssetServer>,\n\n mut scene_spawner: ResMut<SceneSpawner>,\n\n) {\n\n // Spawn a scene and keep its `instance_id`\n\n let instance_id = scene_spawner.spawn(asset_server.load(\"model.gltf#Scene0\"));\n\n commands.insert_resource(MySceneInstance(instance_id));\n\n}\n\n\n\nfn print_scene_entities(\n\n scene_spawner: Res<SceneSpawner>,\n\n scene_instance: Res<MySceneInstance>,\n\n) {\n\n if let Some(entity_iter) = scene_spawner.iter_instance_entities(scene_instance.0) {\n\n for entity in entity_iter {\n\n println!(\"Found scene entity {:?}\", entity);\n\n }\n\n }\n\n}\n\n```\n\n\n\n## Window Resize Constraints\n\n\n\n<div class=\"release-feature-authors\">authors: @digital7-code</div>\n\n\n\nWindows can now have \"resize constraints\". Windows cannot be resized past these constraints\n\n\n\n```rust\n\napp\n\n .insert_resource(WindowDescriptor {\n\n resize_constraints: WindowResizeConstraints {\n\n min_height: 200.0,\n\n max_height: 800.0,\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n })\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 40, "score": 32597.87417596806 }, { "content": "### Changed\n\n\n\n- [ecs: ergonomic query.iter(), remove locks, add QuerySets][741]\n\n - `query.iter()` is now a real iterator!\n\n - `QuerySet` allows working with conflicting queries and is checked at compile-time.\n\n- [Rename `query.entity()` and `query.get()`][752]\n\n - `query.get::<Component>(entity)` is now `query.get_component::<Component>(entity)`\n\n - `query.entity(entity)` is now `query.get(entity)`\n\n- [Asset system rework and GLTF scene loading][693]\n\n- [Introduces WASM implementation of `AssetIo`][703]\n\n- [Move transform data out of Mat4][596]\n\n- [Separate gamepad state code from gamepad event code and other customizations][700]\n\n- [gamepad: expose raw and filtered gamepad events][711]\n\n- [Do not depend on `spirv-reflect` on `wasm32` target][689]\n\n- [Move dynamic plugin loading to its own optional crate][544]\n\n- [Add field to `WindowDescriptor` on wasm32 targets to optionally provide an existing canvas element as winit window][515]\n\n- [Adjust how `ArchetypeAccess` tracks mutable & immutable deps][660]\n\n- [Use `FnOnce` in `Commands` and `ChildBuilder` where possible][535]\n\n- [Runners explicitly call `App.initialize()`][690]\n\n- [sRGB awareness for `Color`][616]\n\n - Color is now assumed to be provided in the non-linear sRGB colorspace.\n\n Constructors such as `Color::rgb` and `Color::rgba` will be converted to linear sRGB.\n\n - New methods `Color::rgb_linear` and `Color::rgba_linear` will accept colors already in linear sRGB (the old behavior)\n\n - Individual color-components must now be accessed through setters and getters.\n\n- [`Mesh` overhaul with custom vertex attributes][599]\n\n - Any vertex attribute can now be added over `mesh.attributes.insert()`.\n\n - See `example/shader/mesh_custom_attribute.rs`\n\n - Removed `VertexAttribute`, `Vertex`, `AsVertexBufferDescriptor`.\n\n - For missing attributes (requested by shader, but not defined by mesh), Bevy will provide a zero-filled fallback buffer.\n\n- Despawning an entity multiple times causes a debug-level log message to be emitted instead of a panic: [#649][649], [#651][651]\n\n- [Migrated to Rodio 0.12][692]\n\n - New method of playing audio can be found in the examples.\n\n- Added support for inserting custom initial values for `Local<T>` system resources [#745][745] \n\n \n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 41, "score": 32597.845329286207 }, { "content": "## Touch Input\n\n\n\n<div class=\"release-feature-authors\">authors: @naithar</div>\n\n\n\nBevy now has support for touches:\n\n\n\n```rust\n\nfn touch_system(touches: Res<Touches>) {\n\n // you can iterate all current touches and retrieve their state like this:\n\n for touch in touches.iter() {\n\n println!(\"active touch: {:?}\", touch);\n\n }\n\n\n\n for touch in touches.iter_just_pressed() {\n\n println!(\"just pressed {:?}\", touch);\n\n }\n\n\n\n for touch in touches.iter_just_released() {\n\n println!(\"just released {:?}\", touch);\n\n }\n\n\n\n for touch in touches.iter_just_cancelled() {\n\n println!(\"just cancelled {:?}\", touch);\n\n }\n\n}\n\n```\n\n\n\nYou can also consume raw touch events using the `Events<TouchInput>` resource.\n\n\n\n## Asset System Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\n### Asset Handle Reference Counting\n\n\n\nAssets are now automatically freed when their \"handle reference count\" reaches zero. This means you no longer need to think about freeing assets manually:\n\n\n\n```rust\n\n// Calling load() now returns a strong handle:\n\nlet handle = asset_server.load(\"sprite.png\");\n\n\n\n// Note that you no longer need to unwrap() loaded handles. Ergonomics for the win!\n\n\n\n// Cloning a handle increases the reference count by one\n\nlet second_handle = handle.clone();\n\n\n\n// Spawn a sprite and give it our handle\n\ncommands.spawn(SpriteComponents {\n\n material: materials.add(handle.into()),\n\n ..Default::default()\n\n});\n\n\n\n// Later in some other system:\n\ncommands.despawn(sprite_entity);\n\n\n\n// There are no more active handles to \"sprite.png\", so it will be freed before the next update\n\n```\n\n\n\n### Asset Loaders can now load multiple assets \n\n\n\nIn past releases, `AssetLoaders` could only produce a single asset of a single type. In **Bevy 0.3**, they can now produce any number of assets for any type. The old behavior was extremely limiting when loading assets like GLTF files, which might produce many meshes, textures, and scenes. \n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 42, "score": 32597.75376812796 }, { "content": "### Ambiguity Detection and Resolution\n\n\n\nWhile the new executor is now much easier to reason about, it does introduce a new class of error: \"system order ambiguities\". When two systems interact with the same data, but have no explicit ordering defined, the output they produce is non-deterministic (and often not what the author intended).\n\n\n\nConsider the following app:\n\n\n\n```rust\n\nfn increment_counter(mut counter: ResMut<usize>) {\n\n *counter += 1;\n\n}\n\n\n\nfn print_every_other_time(counter: Res<usize>) {\n\n if *counter % 2 == 0 {\n\n println!(\"ran\");\n\n }\n\n}\n\n\n\napp\n\n .add_system(increment_counter.system())\n\n .add_system(print_every_other_time.system())\n\n```\n\n\n\nThe author clearly intended `print_every_other_time` to run every other update. However, due to the fact that these systems have no order defined, they could run in a different order each update and create a situation where nothing is printed over the course of two updates:\n\n\n\n```\n\nUPDATE\n\n- increment_counter (counter now equals 1)\n\n- print_every_other_time (nothing printed)\n\nUPDATE\n\n- print_every_other_time (nothing printed)\n\n- increment_counter (counter now equals 2)\n\n```\n\n\n\nThe old executor would have implicitly forced `increment_counter` to run first because it conflicts with `print_every_other_time` and it was inserted first. But the new executor requires you to be explicit here (which we believe is a good thing).\n\n\n\nTo help detect this class of error, we built an opt-in tool that detects these ambiguities and logs them:\n\n\n\n```rust\n\n// add this resource to your App to enable ambiguity detection\n\napp.insert_resource(ReportExecutionOrderAmbiguities)\n\n```\n\n\n\nThen when we run our App, we will see the following message printed to our terminal: \n\n\n\n```\n\nExecution order ambiguities detected, you might want to add an explicit dependency relation between some of these systems:\n\n * Parallel systems:\n\n -- \"&app::increment_counter\" and \"&app::print_every_other_time\"\n\n conflicts: [\"usize\"]\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 43, "score": 32597.51554322771 }, { "content": "### Merged Resources into World\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nResources are now just a special kind of Component. This allows us to keep the code size small by reusing existing Bevy ECS internals. It also enabled us to optimize the parallel executor access controls and it should make scripting language integration easier down the line.\n\n\n\n```rust\n\nworld.insert_resource(1);\n\nworld.insert_resource(2.0);\n\nlet a = world.get_resource::<i32>().unwrap();\n\nlet mut b = world.get_resource_mut::<f64>().unwrap();\n\n*b = 3.0;\n\n\n\n// Resources are still accessed the same way in Systems\n\nfn system(foo: Res<f64>, bar: ResMut<i32>) {\n\n}\n\n```\n\n\n\n_But_ this merge did create problems for people directly interacting with `World`. What if you need mutable access to multiple resources at the same time? `world.get_resource_mut()` borrows World mutably, which prevents multiple mutable accesses! We solved this with `WorldCell`. \n\n\n\n### WorldCell\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nWorldCell applies the \"access control\" concept used by Systems to direct world access:\n\n\n\n```rust\n\nlet world_cell = world.cell();\n\nlet a = world_cell.get_resource_mut::<i32>().unwrap();\n\nlet b = world_cell.get_resource_mut::<f64>().unwrap();\n\n```\n\n\n\nThis adds cheap runtime checks to ensure that world accesses do not conflict with each other. \n\n\n\nWe made this a separate api to enable users to decide what tradeoffs they want. Direct World access has stricter lifetimes, but it is more efficient and does compile time access control. `WorldCell` has looser lifetimes, but incurs a _small_ runtime penalty as a result. \n\n\n\nThe api is currently limited to resource access, but it will be extended to queries / entity component access in the future.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 44, "score": 32597.47794255424 }, { "content": "+++\n\ntitle = \"Bevy 0.4\"\n\ndate = 2020-12-19\n\n[extra]\n\nauthor = \"Carter Anderson\"\n\ntwitter = \"cart_cart\"\n\ngithub = \"cart\"\n\nyoutube = \"cartdev\"\n\nimage = \"colonize.png\"\n\nshow_image = true\n\nimage_subtitle = \"Screenshot of Colonize: a Dwarf-Fortress/Rimworld-like game being developed in Bevy by @indiv0\"\n\nimage_subtitle_link = \"https://github.com/indiv0/colonize/\"\n\n+++\n\n\n\nA little over a month after releasing Bevy 0.3, and thanks to **66** contributors, **178** pull requests, and our [**generous sponsors**](https://github.com/sponsors/cart), I'm happy to announce the **Bevy 0.4** release on [crates.io](https://crates.io/crates/bevy)!\n\n\n\nFor those who don't know, Bevy is a refreshingly simple data-driven game engine built in Rust. You can check out [Quick Start Guide](/learn/book/getting-started/) to get started. Bevy is also free and open source forever! You can grab the full [source code](https://github.com/bevyengine/bevy) on GitHub.\n\n\n\nHere are some of the highlights from this release:\n\n\n\n\n\n<!-- more -->\n\n\n\n## WASM + WebGL2\n\n\n\n<div class=\"release-feature-authors\">authors: @mrk-its</div>\n\n\n\nBevy now has a WebGL2 render backend! @mrk-its has been hard at work building the [Bevy WebGL2 Plugin](https://github.com/mrk-its/bevy_webgl2) and expanding `bevy_render` to meet the needs of the web. He also put together a nice website showcasing various Bevy examples and games running on the web. \n\n\n\nI think the results speak for themselves:\n\n\n\n### [Bevy WebGL2 Showcase](https://mrk.sed.pl/bevy-showcase/)\n\n[![webgl2 showcase](webgl_showcase.png)](https://mrk.sed.pl/bevy-showcase/)\n\n\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 45, "score": 32596.942698203424 }, { "content": "## Dynamic Window Settings\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n\nBevy provides a backend-agnostic windowing api. Up until this point, window settings could only be set once at app startup. If you wanted to set window settings dynamically, you had to directly interact with window backends (ex: winit).\n\n\n\nIn this release we added the ability to dynamically set window properties at runtime using the Bevy window abstraction:\n\n\n\n```rust\n\n// This system dynamically sets the window title to the number of seconds since startup. Because why not?\n\nfn change_title(time: Res<Time>, mut windows: ResMut<Windows>) {\n\n let window = windows.get_primary_mut().unwrap();\n\n window.set_title(format!(\n\n \"Seconds since startup: {}\", time.seconds_since_startup\n\n ));\n\n}\n\n```\n\n\n\n\n\n## Documentation Search-ability\n\n\n\n<div class=\"release-feature-authors\">authors: @memoryruins</div>\n\n\n\nThe `bevy` crate documentation search function now returns results for all sub-crates (like bevy_sprite). Due to how documentation is generated for re-exported crates, by default the `bevy` search index only covered the \"prelude\". @memoryruins found a way to fix this problem by creating new modules and exporting the contents of each crate within those modules (as opposed to aliasing the crates). \n\n\n\n![docs](docs.png)\n\n\n\n\n\n## Change Log\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 46, "score": 32596.925684782647 }, { "content": "### Contributors\n\n\n\n<div class=\"release-feature-authors\">author: @karroffel</div>\n\n\n\n@karroffel added a fun example that represents each Bevy contributor as a \"Bevy Bird\". It scrapes the latest contributor list from git.\n\n\n\n![contributors](contributors.png)\n\n\n\n### BevyMark\n\n\n\n<div class=\"release-feature-authors\">author: @robdavenport</div>\n\n\n\nA \"bunnymark-style\" benchmark illustrating Bevy's sprite rendering performance. This was useful when implementing the renderer optimizations mentioned above.\n\n\n\n![bevymark](bevymark.png)\n\n\n\n## Change Log\n\n\n\n### Added\n\n- [add bevymark benchmark example][273]\n\n- [gltf: support camera and fix hierarchy][772] \n\n- [Add tracing spans to schedules, stages, systems][789]\n\n- [add example that represents contributors as bevy icons][801]\n\n- [Add received character][805]\n\n- [Add bevy_dylib to force dynamic linking of bevy][808] \n\n- [Added RenderPass::set_scissor_rect][815]\n\n- [`bevy_log`][836]\n\n - Adds logging functionality as a Plugin.\n\n - Changes internal logging to work with the new implementation.\n\n- [cross-platform main function][847]\n\n- [Controllable ambient light color][852]\n\n - Added a resource to change the current ambient light color for PBR.\n\n- [Added more basic color constants][859]\n\n- [Add box shape][883]\n\n- [Expose an EventId for events][894]\n\n- [System Inputs, Outputs, and Chaining][876]\n\n- [Expose an `EventId` for events][894]\n\n- [Added `set_cursor_position` to `Window`][917]\n\n- [Added new Bevy reflection system][926]\n\n - Replaces the properties system\n\n- [Add support for Apple Silicon][928]\n\n- [Live reloading of shaders][937]\n\n- [ Store mouse cursor position in Window][940]\n\n- [Add removal_detection example][945]\n\n- [Additional vertex attribute value types][946]\n\n- [Added WindowFocused event][956]\n\n- [Tracing chrome span names][979]\n\n- [Allow windows to be maximized][1004]\n\n- [GLTF: load default material][1016]\n\n- [can spawn a scene from a ChildBuilder, or directly set its parent when spawning it][1026]\n\n- [add ability to load `.dds`, `.tga`, and `.jpeg` texture formats][1038]\n\n- [add ability to provide custom a `AssetIo` implementation][1037]\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 47, "score": 32596.600766549178 }, { "content": "### System Inputs, Outputs, and Chaining\n\n\n\nSystems can now have inputs and outputs. This opens up a variety of interesting behaviors, such as system error handling:\n\n\n\n```rust\n\nfn main() {\n\n App::build()\n\n .add_system(result_system.system().chain(error_handler.system()))\n\n .run();\n\n}\n\n\n\nfn result_system(query: Query<&Transform>) -> Result<()> {\n\n let transform = query.get(SOME_ENTITY)?;\n\n println!(\"found entity transform: {:?}\", transform);\n\n Ok(())\n\n}\n\n\n\nfn error_handler_system(In(result): In<Result<()>>, error_handler: Res<MyErrorHandler>) {\n\n if let Err(err) = result {\n\n error_handler.handle_error(err);\n\n }\n\n}\n\n```\n\n\n\nThe {{rust_type(type=\"trait\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"System\" no_mod=true)}} trait now looks like this:\n\n```rust\n\n// Has no inputs and no outputs\n\nSystem<In = (), Out = ()>\n\n\n\n// Takes a usize as input and return a f32\n\nSystem<In = usize, Out = f32>\n\n```\n\n\n\nWe use this feature in our new Schedule implementation.\n\n\n\n### Schedule V2\n\n\n\nBevy's old Schedule was nice. System registrations were easy to read and easy to compose. But it also had significant limitations:\n\n\n\n* Only one Schedule allowed\n\n* Very static: you were limited to using the tools we gave you:\n\n * stages are just lists of systems\n\n * stages are added to schedules\n\n * stages use hard-coded system runners\n\n* Couldn't switch between schedules at runtime\n\n* Couldn't easily support \"fixed timestep\" scenarios\n\n\n\nTo solve these problems, I wrote a new Schedule system from scratch. Before you get worried, these are largely _non-breaking_ changes. The high level \"app builder\" syntax you know and love is still available:\n\n\n\n```rust\n\napp.add_system(my_system.system())\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 48, "score": 32596.591832021524 }, { "content": "## States V2\n\n\n\n<div class=\"release-feature-authors\">authors: @TheRawMeatball</div>\n\n\n\nThe [last Bevy release](https://bevyengine.org/news/bevy-0-4) added States, which enabled developers to run groups of ECS systems according to the value of a `State<T>` resource. Systems could be run according to \"state lifecycle events\", such as on_enter, on_update, and on_exit. States make things like separate \"loading screen\" and \"in game\" logic easier to encode in Bevy ECS.\n\n\n\nThe old implementation largely worked, but it had a number of quirks and limitations. First and foremost, it required adding a new `StateStage`, which cut down on parallelism, increased boilerplate, and forced ordering where it wasn't required. Additionally, some of the lifecycle events didn't always behave as expected.\n\n\n\nThe new {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"State\" no_mod=true)}} implementation is built on top of the new parallel executor's SystemSet and RunCriteria features, for a much more natural, flexible, and parallel api that builds on existing concepts instead of creating new ones:\n\n\n\n```rust\n\n#[derive(Debug, Clone, Eq, PartialEq, Hash)]\n\nenum AppState {\n\n Menu,\n\n InGame,\n\n}\n\n\n\nfn main() {\n\n App::build()\n\n .add_state(AppState::Menu)\n\n .add_system_set(SystemSet::on_enter(AppState::Menu).with_system(setup_menu.system()))\n\n .add_system_set(SystemSet::on_update(AppState::Menu).with_system(menu_logic.system()))\n\n .add_system_set(SystemSet::on_exit(AppState::Menu).with_system(cleanup_menu.system()))\n\n .add_system_set(SystemSet::on_enter(AppState::InGame).with_system(setup_game.system()))\n\n .add_system_set(\n\n SystemSet::on_update(AppState::InGame)\n\n .with_system(game_logic.system())\n\n .with_system(more_game_logic.system())\n\n )\n\n .run();\n\n}\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 49, "score": 32596.57736800344 }, { "content": "## Timer Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @amberkowalski, @marcusbuffett, @CleanCut</div>\n\n\n\nBevy's Timer component/resource got a number of quality-of-life improvements: pausing, field accessor methods, ergonomics improvements, and internal refactoring / code quality improvements. Timer Components also no longer tick by default. Timer resources and newtyped Timer components couldn't tick by default, so it was a bit inconsistent to have the (relatively uncommon) \"unwrapped component Timer\" auto-tick.\n\n\n\nThe timer api now looks like this:\n\n\n\n```rust\n\n\n\nstruct MyTimer {\n\n timer: Timer,\n\n}\n\n\n\nfn main() {\n\n App::build()\n\n .add_resource(MyTimer {\n\n // a five second non-repeating timer\n\n timer: Timer::from_seconds(5.0, false),\n\n })\n\n .add_system(timer_system.system())\n\n .run();\n\n}\n\n\n\n\n\nfn timer_system(time: Res<Time>, my_timer: ResMut<MyTimer>) {\n\n if my_timer.timer.tick(time.delta_seconds()).just_finished() {\n\n println!(\"five seconds have passed\");\n\n }\n\n}\n\n```\n\n\n\n## Task System Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @aclysma</div>\n\n\n\n@aclysma changed how Bevy Tasks schedules work, which increased performance in the `breakout.rs` example game by <b style=\"color: rgb(50, 210, 50)\">~20%</b> and resolved a [deadlock](https://github.com/bevyengine/bevy/pull/892) when a Task Pool is configured to only have one thread. Tasks are now executed on the calling thread immediately when there is only one task to run, which cuts down on the overhead of moving work to other threads / blocking on them to finish.\n\n\n\n## Apple Silicon Support\n\n\n\n<div class=\"release-feature-authors\">authors: @frewsxcv, @wyhaya, @scoopr</div>\n\n\n\nBevy now runs on Apple silicon thanks to upstream work on winit (@scoopr) and coreaudio-sys (@wyhaya). @frewsxcv and @wyhaya updated Bevy's dependencies and verified that it builds/runs on Apple's new chips.\n\n\n\n## New Examples\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 50, "score": 32596.358975764993 }, { "content": "### Added\n\n\n\n- [Touch Input][696]\n\n- [iOS XCode Project][539]\n\n- [Android Example and use bevy-glsl-to-spirv 0.2.0][740]\n\n- [Introduce Mouse capture API][679]\n\n- [`bevy_input::touch`: implement touch input][696]\n\n- [D-pad support on MacOS][653]\n\n- [Support for Android file system][723]\n\n- [app: PluginGroups and DefaultPlugins][744]\n\n - `PluginGroup` is a collection of plugins where each plugin can be enabled or disabled.\n\n- [Support to get gamepad button/trigger values using `Axis<GamepadButton>`][683]\n\n- [Expose Winit decorations][627]\n\n- [Enable changing window settings at runtime][644]\n\n- [Expose a pointer of EventLoopProxy to process custom messages][674]\n\n- [Add a way to specify padding/ margins between sprites in a TextureAtlas][460]\n\n- [Add `bevy_ecs::Commands::remove` for bundles][579]\n\n- [impl `Default` for `TextureFormat`][675]\n\n- [Expose current_entity in ChildBuilder][595]\n\n- [`AppBuilder::add_thread_local_resource`][671]\n\n- [`Commands::write_world_boxed` takes a pre-boxed world writer to the ECS's command queue][661]\n\n- [`FrameTimeDiagnosticsPlugin` now shows \"frame count\" in addition to \"frame time\" and \"fps\"][678]\n\n- [Add hierarchy example][565]\n\n- [`WgpuPowerOptions` for choosing between low power, high performance, and adaptive power][397]\n\n- Derive `Debug` for more types: [#597][597], [#632][632] \n\n- Index buffer specialization\n\n - [Allows the use of U32 indices in Mesh index buffers in addition to the usual U16 indices][568]\n\n - [Switch to u32 indices by default][572]\n\n- More instructions for system dependencies\n\n - [Add `systemd-devel` for Fedora Linux dependencies][528]\n\n - [Add `libudev-dev` to Ubuntu dependencies][538]\n\n - [Add Void Linux to linux dependencies file][645]\n\n - [WSL2 instructions][727]\n\n- [Suggest `-Zrun-dsymutil-no` for faster compilation on MacOS][552]\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 51, "score": 32596.069117682833 }, { "content": "#### Run Criteria\n\n\n\nYou can add \"run criteria\" to any {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"SystemStage\" no_mod=true)}} or {{rust_type(type=\"struct\" crate=\"bevy_ecs\" version=\"0.4.0\" name=\"Schedule\" no_mod=true)}}.\n\n\n\n```rust\n\n// A \"run criteria\" is just a system that returns a `ShouldRun` result\n\nfn only_on_10_criteria(value: Res<usize>) -> ShouldRun {\n\n if *value == 10 { \n\n ShouldRun::Yes \n\n } else { \n\n ShouldRun::No\n\n }\n\n}\n\n\n\napp\n\n // this stage only runs when Res<usize> has a value of 10\n\n .add_stage_after(stage::UPDATE, \"only_on_10_stage\", SystemStage::parallel()\n\n .with_run_criteria(only_on_10_criteria.system())\n\n .with_system(my_system.system())\n\n )\n\n // this stage only runs once\n\n .add_stage_after(stage::RUN_ONCE, \"one_and_done\", Schedule::default()\n\n .with_run_criteria(RunOnce::default())\n\n .with_system(my_system.system())\n\n )\n\n```\n\n\n\n#### Fixed Timestep\n\n\n\nYou can now run stages on a \"fixed timestep\".\n\n\n\n```rust\n\n// this stage will run once every 0.4 seconds\n\napp.add_stage_after(stage::UPDATE, \"fixed_update\", SystemStage::parallel()\n\n .with_run_criteria(FixedTimestep::step(0.4))\n\n .with_system(my_system.system())\n\n)\n\n```\n\n\n\nThis builds on top of `ShouldRun::YesAndLoop`, which ensures that the schedule continues to loop until it has consumed all accumulated time.\n\n\n\nCheck out the excellent [\"Fix Your Timestep!\"](https://gafferongames.com/post/fix_your_timestep/) article if you want to learn more about fixed timesteps.\n\n\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 52, "score": 32596.039149681146 }, { "content": "## !Send Tasks\n\n\n\n<div class=\"release-feature-authors\">authors: @alec-deason</div>\n\n\n\nBevy's async task system now supports `!Send` tasks. Some tasks cannot be sent / run on other threads (such as tasks created by the upcoming Distill asset plugin). \"Thread local\" tasks can now be spawned in Bevy `TaskPools` like this:\n\n\n\n```rust\n\nlet pool = TaskPool::default();\n\npool.scope(|scope| {\n\n scope.spawn_local(async move {\n\n println!(\"I am a local task\");\n\n });\n\n});\n\n```\n\n\n\n## More ECS V2 Changes\n\n\n\n### EntityRef / EntityMut\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nWorld entity operations in **Bevy 0.4** require that the user passes in an `entity` id to each operation:\n\n\n\n```rust\n\nlet entity = world.spawn((A, )); // create a new entity with A\n\nworld.get::<A>(entity);\n\nworld.insert(entity, (B, C));\n\nworld.insert_one(entity, D);\n\n```\n\n\n\nThis means that each operation needs to look up the entity location / verify its validity. The initial spawn operation also requires a Bundle as input. This can be awkward when no components are required (or one component is required).\n\n\n\nThese operations have been replaced by `EntityRef` and `EntityMut`, which are \"builder-style\" wrappers around world that provide read and read/write operations on a single, pre-validated entity:\n\n\n\n```rust\n\n// spawn now takes no inputs and returns an EntityMut\n\nlet entity = world.spawn()\n\n .insert(A) // insert a single component into the entity\n\n .insert_bundle((B, C)) // insert a bundle of components into the entity\n\n .id() // id returns the Entity id\n\n\n\n// Returns EntityMut (or panics if the entity does not exist)\n\nworld.entity_mut(entity)\n\n .insert(D)\n\n .insert_bundle(SomeBundle::default());\n\n\n\n// The `get_X` variants return Options, in case you want to check existence instead of panicking \n\nworld.get_entity_mut(entity)\n\n .unwrap()\n\n .insert(E);\n\n\n\nif let Some(entity_ref) = world.get_entity(entity) {\n\n let d = entity_ref.get::<D>().unwrap();\n\n}\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 53, "score": 32595.930991809004 }, { "content": "### Direct component lookup (in nanoseconds, smaller is better) \n\n\n\nAs a result of these optimizations, direct component lookup is _much_ faster than it used to be:\n\n\n\n![get_component graph](get_component.svg)\n\n\n\nNote that this benchmark used `world.get::<T>(entity)`. `query.get::<T>(entity)` should have results similar to the `hecs` results because it still uses a lock. Eventually I'm hoping that we can remove locks from system queries too.\n\n\n\n## Change Log\n\n\n\n### Added\n\n\n\n- [Task System for Bevy][384]\n\n - Replaces rayon with a custom designed task system that consists of several \"TaskPools\".\n\n - Exports `IOTaskPool`, `ComputePool`, and `AsyncComputePool` in `bevy_tasks` crate.\n\n- [Parallel queries for distributing work over with the `ParallelIterator` trait.][292]\n\n - e.g. `query.iter().par_iter(batch_size).for_each(/* ... */)`\n\n- [Added gamepad support using Gilrs][280]\n\n- [Implement WASM support for bevy_winit][503]\n\n- [Create winit canvas under WebAssembly][506] \n\n- [Implement single threaded task scheduler for WebAssembly][496]\n\n- [Support for binary glTF (.glb).][271]\n\n- [Support for `Or` in ECS queries.][358]\n\n- [Added methods `unload()` and `unload_sync()` on `SceneSpawner` for unloading scenes.][339].\n\n- [Custom rodio source for audio.][145]\n\n - `AudioOuput` is now able to play anything `Decodable`.\n\n- [`Color::hex`][362] for creating `Color` from string hex values.\n\n - Accepts the forms RGB, RGBA, RRGGBB, and RRGGBBAA.\n\n- [`Color::rgb_u8` and `Color::rgba_u8`.][381]\n\n- [Added `bevy_render::pass::ClearColor` to prelude.][396]\n\n- [`SpriteResizeMode` may choose how `Sprite` resizing should be handled. `Automatic` by default.][430]\n\n- [Added methods on `Input<T>`][428] for iterator access to keys.\n\n - `get_pressed()`, `get_just_pressed()`, `get_just_released()`\n\n- [Derived `Copy` for `MouseScrollUnit`.][270]\n\n- [Derived `Clone` for UI component bundles.][390]\n\n- [Some examples of documentation][338]\n\n- [Update docs for Updated, Changed and Mutated][451]\n\n- Tips for faster builds on macOS: [#312][312], [#314][314], [#433][433]\n\n- Added and documented cargo features\n\n - [Created document `docs/cargo_features.md`.][249]\n\n - [Added features for x11 and wayland display servers.][249]\n\n - [and added a feature to disable libloading.][363] (helpful for WASM support)\n\n- Added more instructions for Linux dependencies\n\n - [Arch / Manjaro][275], [NixOS][290], [Ubuntu][463] and [Solus][331]\n\n- [Provide shell.nix for easier compiling with nix-shell][491]\n\n- [Add `AppBuilder::add_startup_stage_|before/after`][505]\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 54, "score": 32595.866394135395 }, { "content": "### 100% Lockless Parallel ECS\n\n\n\nBevy ECS is now completely lock free. In Bevy 0.2, we made direct `World` access and \"for-each\" systems lock free. This is possible because the Bevy ECS scheduler ensures that systems only run in parallel in ways that respect Rust's mutability rules. \n\n\n\nWe couldn't remove locks from `Query` systems because of systems like this:\n\n\n\n```rust\n\nfn conflicting_query_system(mut q0: Query<&mut A>, mut q1: Query<(&mut A, &B)>) {\n\n let a = q0.get_mut(some_entity).unwrap();\n\n let (another_a, b) = q1.get_mut(some_entity).unwrap();\n\n // Aaah!!! We have two mutable references to some_entity's A component!\n\n // Very unsafe!\n\n}\n\n```\n\n\n\nThe locks ensured that the second `q1.get_mut(some_entity)` access panicked, keeping us nice and safe. In **Bevy 0.3**, a system like `conflicting_query_system` will fail when the schedule is constructed. By default, _systems cannot have conflicting queries_.\n\n\n\nHowever there are some cases where a system _needs_ conflicting queries to do what it needs to do. For these cases, we added `QuerySets`: \n\n\n\n```rust\n\nfn system(mut queries: QuerySet<(Query<&mut A>, Query<(&mut A, &B)>)>) {\n\n for a in queries.q0_mut().iter_mut() {\n\n }\n\n\n\n for (a, b) in queries.q1_mut().iter_mut() {\n\n }\n\n}\n\n```\n\n\n\nBy putting our conflicting `Queries` in a `QuerySet`, the Rust borrow checker protects us from unsafe query accesses.\n\n\n\nBecause of this, we were able to remove _all_ safety checks from `query.iter()` and `query.get(entity)`, which means these methods are now _exactly_ as fast as their `World` counterparts (which we made lock-free in Bevy 0.2). \n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 55, "score": 32595.847055194234 }, { "content": "States now use a \"stack-based state machine\" model. This opens up a number of options for state transitions:\n\n\n\n```rust\n\nfn system(mut state: ResMut<State<AppState>>) {\n\n // Queues up a state change that pushes a new state on to the\n\n // stack (preserving previous states)\n\n state.push(AppState::InGame).unwrap();\n\n\n\n // Queues up a state change that removes the current state on\n\n // the stack and reverts to the previous state\n\n state.pop().unwrap();\n\n\n\n // Queues up a state change that overwrites the current state at\n\n // the \"top\" of the stack\n\n state.set(AppState::InGame).unwrap();\n\n\n\n // Queues up a state change that replaces the entire stack of states\n\n state.replace(AppState::InGame).unwrap();\n\n}\n\n```\n\n\n\nJust like the old implementation, state changes are applied in the same frame. This means it is possible to transition from states `A->B->C` and run the relevant state lifecycle events without skipping frames. This builds on top of \"looping run criteria\", which we also use for our \"fixed timestep\" implementation (and which you can use for your own run criteria logic).\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 56, "score": 32595.33313490982 }, { "content": "#### Component Insertion (in microseconds, smaller is better)\n\n\n\n![component insertion](ecs_simple_insert.svg)\n\n\n\n#### Component Add/Remove (in milliseconds, smaller is better)\n\n\n\n![component add/remove](ecs_add_remove.svg)\n\n\n\n#### Fragmented Iteration (in nanoseconds, smaller is better)\n\n\n\n![fragmented iteration](ecs_frag_iter.svg)\n\n\n\n\n\n### Thread Local Resources\n\n\n\nSome resource types cannot (or should not) be passed between threads. This is often true for low level apis like windowing, input, and audio. It is now possible to add \"thread local resources\" to the `Resources` collection, which can only be accessed from the main thread using \"thread local systems\":\n\n\n\n```rust\n\n// in your app setup\n\napp.add_thread_local_resource(MyResource);\n\n\n\n// a thread local system\n\nfn system(world: &mut World, resources: &mut Resources) {\n\n let my_resource = resources.get_thread_local::<MyResource>().unwrap();\n\n}\n\n```\n\n\n\n### Query Api Changes\n\n\n\nFirst, to improve clarity we renamed `query.get::<Component>(entity)` to `query.get_component::<Component>(entity)`. We now return the \"full\" query result for a specific entity using `query.get(entity)`.\n\n\n\nTo allow multiple concurrent reads of Queries (where it is safe), we added separate `query.iter()` and `query.iter_mut()` apis, as well as `query.get(entity)` and `query.get_mut(entity)`. Queries that are \"read only\" can now retrieve their results via an immutable borrow.\n\n\n\n## Mesh Improvements\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 57, "score": 32595.265213142375 }, { "content": "## GLTF Scene Loader\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nUp until this point, the GLTF loader was painfully limited. It could only load the first mesh with a single texture in a GLTF file. For **Bevy 0.3**, we took advantage of the asset system improvements to write a new `GltfLoader` that loads GLTF files as Bevy `Scenes`, along with all meshes and textures in the files.\n\n\n\nHere's Bevy loading the Khronos Flight Helmet example, which consists of multiple meshes and textures!\n\n\n\n![flight helmet](flight_helmet.png)\n\n\n\nHere is the complete code for a system that loads a GLTF file and spawns it as a scene:\n\n\n\n```rust\n\nfn load_gltf_system(mut commands: Commands, asset_server: Res<AssetServer>) {\n\n let scene_handle = asset_server.load(\"models/FlightHelmet/FlightHelmet.gltf\");\n\n commands.spawn_scene(scene_handle);\n\n}\n\n```\n\n\n\n## Bevy ECS Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\n### Query Ergonomics\n\n\n\nIn this release I finally was able to remove the one thing I _truly despised_ in Bevy ECS. In previous versions of Bevy, iterating over the components in a `Query` looked like this:\n\n\n\n```rust\n\nfor (a, b) in &mut query.iter() {\n\n // The `&mut` here just felt so unnatural\n\n}\n\n\n\n// Or if you preferred you could do this\n\nfor (a, b) in query.iter().iter() {\n\n // query.iter().iter()? Really???\n\n}\n\n```\n\n\n\nSimilarly, retrieving a specific entity's component's looked like this:\n\n\n\n```rust\n\nif let Ok(mut result) = query.entity(entity) {\n\n if let Some((a, b)) = result.get() {\n\n // access components here\n\n }\n\n}\n\n```\n\n\n\nIn **Bevy 0.3** you can just do this:\n\n\n\n```rust\n\n// iteration\n\nfor (a, b) in query.iter() {\n\n // sweet ergonomic bliss\n\n}\n\n\n\n// entity lookup\n\nif let Ok((a,b)) = query.get(entity) {\n\n // boilerplate be gone!\n\n}\n\n```\n\n\n\nYou might naturally be thinking something like:\n\n\n\n*Why did this take so long? Why would removing a single `&mut` be hard?*\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 58, "score": 32595.19788957033 }, { "content": "## Sprite Flipping\n\n\n\n<div class=\"release-feature-authors\">authors: @zicklag</div>\n\n\n\nSprites can now be easily (and efficiently) flipped along the x or y axis:\n\n\n\n![sprite_flipping](sprite_flipping.png)\n\n\n\n```rust\n\ncommands.spawn_bundle(SpriteBundle {\n\n material: material.clone(),\n\n transform: Transform::from_xyz(150.0, 0.0, 0.0),\n\n ..Default::default()\n\n});\n\ncommands.spawn_bundle(SpriteBundle {\n\n material,\n\n transform: Transform::from_xyz(-150.0, 0.0, 0.0),\n\n sprite: Sprite {\n\n // Flip the logo to the left\n\n flip_x: true,\n\n // And don't flip it upside-down ( the default )\n\n flip_y: false,\n\n ..Default::default()\n\n },\n\n ..Default::default()\n\n});\n\n```\n\n\n\n## Color Spaces\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 59, "score": 32594.93999744213 }, { "content": "## Initial iOS Support\n\n\n\n<div class=\"release-feature-authors\">authors: @simlay, @MichaelHills, @Dash-L, @naithar</div>\n\n\n\nBevy can now run on iOS!\n\n\n\n<img src=\"ios.png\" style=\"margin-left: -4rem; margin-bottom: -5rem; margin-top: -3rem\" />\n\n\n\nYou can try out the [Bevy iOS example](https://github.com/bevyengine/bevy/tree/v0.3.0/examples/ios) by following the [instructions here](https://github.com/bevyengine/bevy/tree/v0.3.0/examples#ios). This one is also hot off the presses: some features will work and others probably won't.\n\n\n\nThis was another large group effort that spanned multiple projects:\n\n\n\n* Bevy: XCode Project / Example (@simlay with help from @MichaelHills)\n\n* Bevy: Runtime shader compilation using shaderc (@MichaelHills)\n\n* Bevy: Rodio upgrade (@Dash-L)\n\n* Bevy: Touch support (@naithar)\n\n* Winit: Fix iOS portrait view (@MichaelHills) \n\n* RustAudio: iOS support (@simlay and @MichaelHills)\n\n\n\nKnown issues:\n\n* [Audio doesn't quite work yet](https://github.com/RustAudio/cpal/pull/485)\n\n\n\n## WASM Asset Loading\n\n\n\n<div class=\"release-feature-authors\">authors: @mrk-its (and ported to the new AssetIo by @cart)</div>\n\n\n\n@mrk-its has been hard at work on expanding Bevy's WASM support. In this release we landed WASM asset loading. You can now load assets when you publish to WASM just like you would on any other platform:\n\n\n\n```rust\n\nasset_server.load(\"sprite.png\");\n\n```\n\n\n\nIf the asset hasn't already been loaded, this will make a `fetch()` request to retrieve the asset over HTTP.\n\n\n\n@mrk-its has also been building a custom WebGL2 `bevy_render` backend. It is already pretty usable, but its not _quite_ ready yet. Expect more news on this soon!\n\n\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 60, "score": 32594.807150680044 }, { "content": "#### Frame Time to Draw 10,000 Static Sprites (in milliseconds, less is better)\n\n\n\n![bevy_round1_static](bevy_round1_static.svg)\n\n\n\n#### Frame Time to Draw 10,000 Moving Sprites (in milliseconds, less is better)\n\n\n\n![bevy_round1_dynamic](bevy_round1_dynamic.svg)\n\n\n\n### Optimize Text Rendering (and other immediate rendering)\n\n\n\nText Rendering (and anything else that used the `SharedBuffers` immediate-rendering abstraction) was _extremely_ slow in prior Bevy releases. This was because the `SharedBuffers` abstraction was a placeholder implementation that didn't actually share buffers. By implementing the \"real\" `SharedBuffers` abstraction, we got a pretty significant text rendering speed boost.\n\n\n\n#### Frame Time to Draw \"text_debug\" Example (in milliseconds, less is better)\n\n\n\n![text_rendering](text_rendering.svg)\n\n\n\n### Mailbox Vsync\n\n\n\nBevy now uses wgpu's \"mailbox vsync\" by default. This reduces input latency on platforms that support it.\n\n\n\n## Reflection\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nRust has a pretty big \"reflection\" gap. For those who aren't aware, \"reflection\" is a class of language feature that enables you to interact with language constructs at runtime. They add a form of \"dynamic-ness\" to what are traditionally static language concepts. \n\n\n\nWe have bits and pieces of reflection in Rust, such as {{rust_type(type=\"struct\" crate=\"std\", mod=\"any\", name=\"TypeId\")}} and {{rust_type(type=\"fn\" crate=\"std\", mod=\"any\", name=\"type_name\")}}. But when it comes to interacting with datatypes ... we don't have anything yet. This is unfortunate because some problems are inherently dynamic in nature.\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 61, "score": 32593.75910219849 }, { "content": "### Flexible Mesh Vertex Attributes\n\n\n\n<div class=\"release-feature-authors\">authors: @julhe</div>\n\n\n\nBevy meshes used to require exactly three \"vertex attributes\": `position`, `normal`, and `uv`. This worked for most things, but there are a number of cases that require other attributes, such as \"vertex colors\" or \"bone weights for animation\". **Bevy 0.3** adds support for custom vertex attributes. Meshes can define whatever attributes they want and shaders can consume whatever attributes they want!\n\n\n\n[Here is an example](https://github.com/bevyengine/bevy/blob/v0.3.0/examples/shader/mesh_custom_attribute.rs) that illustrates how to define a custom shader that consumes a mesh with an added \"vertex color\" attribute.\n\n\n\n![custom_vertex_attribute](custom_vertex_attribute.png)\n\n\n\n### Index Buffer Specialization\n\n\n\n<div class=\"release-feature-authors\">authors: @termhn</div>\n\n\n\nRendering meshes often involves using vertex \"indices\" to cut down on duplicate vertex information. Bevy used to hard code the precision of these indices to `u16`, which was too small for some cases. Now render pipelines can \"specialize\" based on a configured index buffer, which now defaults to `u32` to cover most use cases.\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 62, "score": 32593.742949778767 }, { "content": "## Physically Based Rendering (PBR)\n\n\n\n<div class=\"release-feature-authors\">authors: @StarArawn, @mtsr, @mockersf, @IngmarBitter, @Josh015, @norgate, @cart</div>\n\n\n\nBevy now uses PBR shaders when rendering. PBR is a semi-standard approach to rendering that attempts to use approximations of real-world \"physically based\" lighting and material properties. We largely use techniques from the [Filament](https://github.com/google/filament/) PBR implementation, but we also incorporate some ideas from [Unreal](https://www.unrealengine.com/en-US/blog/physically-based-shading-on-mobile) and [Disney](https://google.github.io/filament/Filament.html#citation-burley12).\n\n\n\nBevy's `StandardMaterial` now has `base_color`, `roughness`, `metallic`, `reflection`, and `emissive` properties. It also now supports textures for `base_color`, `normal_map`, `metallic_roughness`, `emissive`, and `occlusion` properties. \n\n\n\nThe new PBR example helps visualize these new material properties:\n\n\n\n![pbr](pbr.png)\n\n\n\n## GLTF Improvements\n\n\n\n### PBR Textures\n\n\n\n<div class=\"release-feature-authors\">authors: @mtsr, @mockersf</div>\n\n\n\nThe GLTF loader now supports normal maps, metallic/roughness, occlusion, and emissive textures. Our \"flight helmet\" gltf example utilizes the new PBR texture support and looks much nicer as a result:\n\n\n\n<video controls loop><source src=\"flighthelmet.mp4\" type=\"video/mp4\"/></video>\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 63, "score": 32593.519225016447 }, { "content": "### Improved Run Criteria\n\n\n\nRun Criteria are now decoupled from systems and will be re-used when possible. For example, the FixedTimestep criteria in the example above will only be run once per stage run. The executor will re-use the criteria's result for both the `foo` and `bar` system.\n\n\n\nRun Criteria can now also be labeled and referenced by other systems:\n\n\n\n\n\n```rust\n\nfn every_other_time(mut has_ran: Local<bool>) -> ShouldRun {\n\n *has_ran = !*has_ran;\n\n if *has_ran {\n\n ShouldRun::Yes\n\n } else {\n\n ShouldRun::No\n\n }\n\n}\n\n\n\napp.add_stage(SystemStage::parallel()\n\n .with_system_run_criteria(every_other_time.system().label(\"every_other_time\")))\n\n .add_system(foo.system().with_run_criteria(\"every_other_time\"))\n\n```\n\n\n\nResults from Run Criteria can also be \"piped\" into other criteria, which enables interesting composed behaviors:\n\n\n\n```rust\n\nfn once_in_a_blue_moon(In(input): In<ShouldRun>, moon: Res<Moon>) -> ShouldRun {\n\n if moon.is_blue() {\n\n input\n\n } else {\n\n ShouldRun::No\n\n }\n\n}\n\n\n\napp\n\n .add_system(foo.with_run_criteria(\n\n \"every_other_time\".pipe(once_in_a_blue_moon.system())\n\n )\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 64, "score": 32593.409585448502 }, { "content": "## Logging and Profiling\n\n\n\n<div class=\"release-feature-authors\">authors: @superdump, @cart</div>\n\n\n\nBevy finally has built in logging, which is now enabled by default via the new {{rust_type(type=\"struct\" crate=\"bevy_log\" version=\"0.4.0\" name=\"LogPlugin\" no_mod=true)}}. We evaluated various logging libraries and eventually landed on the new `tracing` crate. `tracing` is a structured logger that handles async / parallel logging well (perfect for an engine like Bevy), and enables profiling in addition to \"normal\" logging.\n\n\n\nThe {{rust_type(type=\"struct\" crate=\"bevy_log\" version=\"0.4.0\" name=\"LogPlugin\" no_mod=true)}} configures each platform to log to the appropriate backend by default: the terminal on desktop, the console on web, and Android Logs / logcat on Android. We built a new Android `tracing` backend because one didn't exist yet.\n\n\n\n\n\n### Logging\n\n\n\nBevy's internal plugins now generate `tracing` logs. And you can easily add logs to your own app logic like this:\n\n\n\n```rust\n\n// these are imported by default in bevy::prelude::*\n\ntrace!(\"very noisy\");\n\ndebug!(\"helpful for debugging\");\n\ninfo!(\"helpful information that is worth printing by default\");\n\nwarn!(\"something bad happened that isn't a failure, but thats worth calling out\");\n\nerror!(\"something failed\");\n\n```\n\n\n\nThese lines result in pretty-printed terminal logs:\n\n\n\n![logs](logs.png)\n\n\n\n`tracing` has a ton of useful features like structured logging and filtering. [Check out their documentation for more info.](https://docs.rs/tracing/*/tracing/)\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 65, "score": 32593.13737788408 }, { "content": "## Reliable change detection\n\n\n\n<div class=\"release-feature-authors\">authors: @Davier, @bjorn3, @alice-i-cecile, @cart</div>\n\n\n\nGlobal change detection, the ability to run queries on the Changed/Added status of any ECS component or resource, just got a major usability boost: changes are now detected across frames/updates:\n\n\n\n```rust\n\n// This is still the same change detection api we all know and love,\n\n// the only difference is that it \"just works\" in every situation.\n\nfn system(query: Query<Entity, Changed<A>>) {\n\n // iterates all entities whose A component has changed since\n\n // the last run of this system \n\n for e in query.iter() {\n\n }\n\n}\n\n```\n\n\n\nGlobal change detection was already a feature that set Bevy apart from other ECS frameworks, but now it is completely \"fool proof\". It works as expected regardless of system ordering, stage membership, or system run criteria.\n\n\n\nThe old behavior was \"systems detect changes that ocurred in systems that ran before them this frame\". This was because we used a `bool` to track when each component/resource is added/modified. This flag was cleared for each component at the end of the frame. As a result, users had to be very careful about order of operations, and using features like \"system run criteria\" could result in dropped changes if systems didn't run on a given update.\n\n\n\nWe now use a clever \"world tick\" design that allows systems to detect changes that happened at _any_ point in time since their last run.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 66, "score": 32593.089305394686 }, { "content": "## New Parallel System Executor\n\n\n\n<div class=\"release-feature-authors\">authors: @Ratysz</div>\n\n\n\nBevy's old parallel executor had a number of fundamental limitations:\n\n\n\n1. The only way to explicitly define system order was to create new stages. This was both boilerplate-ey and prevented parallelism (because stages run \"one by one\" in order). We've noticed that system ordering is a common requirement and stages just weren't cutting it.\n\n2. Systems had \"implicit\" orderings when they accessed conflicting resources. These orderings were hard to reason about.\n\n3. The \"implicit orderings\" produced execution strategies that often left a lot of parallelism potential on the table.\n\n\n\nFortunately @Ratysz has been [doing](https://ratysz.github.io/article/scheduling-1/) a lot of [research](https://github.com/Ratysz/yaks/) in this area and volunteered to contribute a new executor. The new executor solves all of the issues above and also adds a bunch of new usability improvements. The \"ordering\" rules are now dead-simple:\n\n\n\n1. Systems run in parallel by default\n\n2. Systems with explicit orderings defined will respect those orderings\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 67, "score": 32592.66957920431 }, { "content": "{{rust_type(type=\"enum\" crate=\"bevy_render\" mod=\"color\" version=\"0.5.0\" name=\"Color\" no_mod=true)}} is now internally represented as an enum, which enables lossless (and correct) color representation. This is a significant improvement over the previous implementation, which internally converted all colors to linear sRGB (which could cause precision issues). Colors are now only converted to linear sRGB when they are sent to the GPU. We also took this opportunity to fix some incorrect color constants defined in the wrong color space.\n\n\n\n```rust\n\npub enum Color {\n\n /// sRGBA color\n\n Rgba {\n\n /// Red component. [0.0, 1.0]\n\n red: f32,\n\n /// Green component. [0.0, 1.0]\n\n green: f32,\n\n /// Blue component. [0.0, 1.0]\n\n blue: f32,\n\n /// Alpha component. [0.0, 1.0]\n\n alpha: f32,\n\n },\n\n /// RGBA color in the Linear sRGB colorspace (often colloquially referred to as \"linear\", \"RGB\", or \"linear RGB\").\n\n RgbaLinear {\n\n /// Red component. [0.0, 1.0]\n\n red: f32,\n\n /// Green component. [0.0, 1.0]\n\n green: f32,\n\n /// Blue component. [0.0, 1.0]\n\n blue: f32,\n\n /// Alpha component. [0.0, 1.0]\n\n alpha: f32,\n\n },\n\n /// HSL (hue, saturation, lightness) color with an alpha channel\n\n Hsla {\n\n /// Hue component. [0.0, 360.0]\n\n hue: f32,\n\n /// Saturation component. [0.0, 1.0]\n\n saturation: f32,\n\n /// Lightness component. [0.0, 1.0]\n\n lightness: f32,\n\n /// Alpha component. [0.0, 1.0]\n\n alpha: f32,\n\n },\n\n}\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 68, "score": 32592.409668003416 }, { "content": "This is what the new `Transform` api looks like in a Bevy ECS system:\n\n\n\n```rust\n\nfn system(mut transform: Mut<Transform>) {\n\n // move along the positive x-axis\n\n transform.translation += Vec3::new(1.0, 0.0, 0.0);\n\n\n\n // rotate 180 degrees (pi) around the y-axis\n\n transform.rotation *= Quat::from_rotation_y(PI);\n\n\n\n // scale 2x\n\n transform.scale *= 2.0;\n\n}\n\n```\n\n\n\nCompared to the last version this is easier to use, more correct, and should also be slightly faster.\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 69, "score": 32592.38552710104 }, { "content": "### Resource Scopes\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nWorldCell does not yet support component queries, and even when it does there will sometimes be legitimate reasons to want a mutable world ref _and_ a mutable resource ref (ex: bevy_render and bevy_scene both need this). In these cases we could always drop down to the unsafe `world.get_resource_unchecked_mut()`, but that is not ideal!\n\n\n\nInstead developers can use a \"resource scope\"\n\n\n\n```rust\n\nworld.resource_scope(|world: &mut World, mut a: Mut<A>| {\n\n})\n\n```\n\n\n\nThis temporarily removes the `A` resource from `World`, provides mutable pointers to both, and re-adds A to World when finished. Thanks to the move to ComponentIds/sparse sets, this is a cheap operation.\n\n\n\nIf multiple resources are required, scopes can be nested. We could also consider adding a \"resource tuple\" to the api if this pattern becomes common and the boilerplate gets nasty.\n\n\n\n### Query Conflicts Use ComponentId Instead of ArchetypeComponentId\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nFor safety reasons, systems cannot contain queries that conflict with each other without wrapping them in a `QuerySet`. In **Bevy 0.4**, we used `ArchetypeComponentIds` to determine conflicts. This was nice because it could take into account filters:\n\n\n\n```rust\n\n// these queries will never conflict due to their filters\n\nfn filter_system(a: Query<&mut A, With<B>>, b: Query<&mut B, Without<B>>) {\n\n}\n\n```\n\n\n\nBut it also had a significant downside:\n\n```rust\n\n// these queries will not conflict _until_ an entity with A, B, and C is spawned\n\nfn maybe_conflicts_system(a: Query<(&mut A, &C)>, b: Query<(&mut A, &B)>) {\n\n}\n\n```\n\n\n\nThe system above will panic at runtime if an entity with A, B, and C is spawned. This makes it hard to trust that your game logic will run without crashing.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 70, "score": 32592.279142285366 }, { "content": "## What's Next For Bevy?\n\n\n\nWe still have a long road ahead of us, but the Bevy developer community is growing at a rapid pace and we already have big plans for the future. Expect to see progress in the following areas soon:\n\n\n\n* \"Pipelined\" rendering and other renderer optimizations\n\n* Bevy UI redesign\n\n* Animation: component animation and 3d skeletal animation\n\n* ECS: relationships/indexing, async systems, archetype invariants, \"stageless\" system schedules \n\n* 3D Lighting Features: shadows, more light types\n\n* More Bevy Scene features and usability improvements\n\n\n\nWe also plan on breaking ground on the Bevy Editor as soon as we converge on a final Bevy UI design.\n\n\n\n## Support Bevy\n\n\n\n[Sponsorships](https://github.com/sponsors/cart) help make full time work on Bevy sustainable. If you believe in Bevy's mission, consider [sponsoring @cart](https://github.com/sponsors/cart) ... every bit helps!\n\n\n\n<a class=\"header-item header-button header-button-donate\" style=\"margin-left: 0px;\" href=\"https://github.com/sponsors/cart\">Donate <img src=\"/assets/heart.svg\" class=\"header-button-donate-heart\" alt=\"heart icon\"/></a>\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 71, "score": 32592.1797922664 }, { "content": "#### Typed Stage Builders\n\n\n\nNow that stages can be any type, we need a way for {{rust_type(type=\"trait\" crate=\"bevy_app\" version=\"0.4.0\" name=\"Plugin\" no_mod=true plural=true)}} to interact with arbitrary stage types:\n\n\n\n```rust\n\napp\n\n // this \"high level\" builder pattern still works (and assumes that the stage is a SystemStage)\n\n .add_system(some_system.system())\n\n // this \"low level\" builder is equivalent to add_system()\n\n .stage(stage::UPDATE, |stage: &mut SystemStage|\n\n stage.add_system(some_system.system())\n\n )\n\n // this works for custom stage types too\n\n .stage(MY_CUSTOM_STAGE, |stage: &mut MyCustomStage|\n\n stage.do_custom_thing()\n\n )\n\n```\n\n\n\n### Deprecated For-Each Systems\n\n\n\nPrior versions of Bevy supported \"for-each\" systems, which looked like this:\n\n\n\n```rust\n\n// on each update this system runs once for each entity with a Transform component\n\nfn system(time: Res<Time>, entity: Entity, transform: Mut<Transform>) {\n\n // do per-entity logic here\n\n}\n\n```\n\n\n\nFrom now on, the system above should be written like this:\n\n\n\n```rust\n\n// on each update this system runs once and internally iterates over each entity\n\nfn system(time: Res<Time>, query: Query<(Entity, &mut Transform)>) {\n\n for (entity, mut transform) in query.iter_mut() {\n\n // do per-entity logic here\n\n }\n\n}\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 72, "score": 32591.717736533177 }, { "content": "### System Sets\n\n\n\n{{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"SystemSet\" no_mod=true plural=true)}} are a new way to apply the same configuration to a group of systems, which significantly cuts down on boilerplate. The \"physics\" example above could be rephrased like this:\n\n\n\n```rust\n\napp\n\n .add_system_set(SystemSet::new()\n\n // this label is added to all systems in the set\n\n .label(Physics)\n\n .with_system(update_velocity.system().label(PhysicsSystem::UpdateVelocity))\n\n .with_system(movement.system()\n\n .label(PhysicsSystem::Movement)\n\n .after(PhysicsSystem::UpdateVelocity)\n\n )\n\n )\n\n```\n\n\n\nSystemSets can also use `before(Label)` and `after(Label)` to run all systems in the set before/after the given label.\n\n\n\nThis is also very useful for groups of systems that need to run with the same {{rust_type(type=\"struct\" crate=\"bevy_ecs\" mod=\"schedule\" version=\"0.5.0\" name=\"RunCriteria\" no_mod=true)}}.\n\n\n\n```rust\n\napp\n\n // all systems in this set will run once every two seconds\n\n .add_system_set(SystemSet::new()\n\n .with_run_criteria(FixedTimestep::step(2.0))\n\n .with_system(foo.system())\n\n .with_system(bar.system())\n\n )\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 73, "score": 32591.52227868681 }, { "content": "## Flexible Camera Bindings\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nBevy used to \"hack in\" camera bindings for each RenderGraph PassNode. This worked when there was only one binding type (the combined `ViewProj` matrix), but many shaders require other camera properties, such as the world space position.\n\n\n\nIn Bevy 0.5 we removed the \"hack\" in favor of the `RenderResourceBindings` system used elsewhere. This enables shaders to bind arbitrary camera data (with any set or binding index) and only pull in the data they need.\n\n\n\nThe new PBR shaders take advantage of this feature, but custom shaders can also use it.\n\n\n\n```glsl\n\nlayout(set = 0, binding = 0) uniform CameraViewProj {\n\n mat4 ViewProj;\n\n};\n\nlayout(set = 0, binding = 1) uniform CameraPosition {\n\n vec3 CameraPos;\n\n};\n\n```\n\n\n\n## Render Layers\n\n\n\n<div class=\"release-feature-authors\">authors: @schell</div>\n\n\n\nSometimes you don't want a camera to draw everything in a scene, or you want to temporarily hide a set of things in the scene. **Bevy 0.5** adds a `RenderLayer` system, which gives developers the ability to add entities to layers by adding the `RenderLayers` component.\n\n\n\nCameras can also have a {{rust_type(type=\"struct\" crate=\"bevy_render\" mod=\"camera\" version=\"0.5.0\" name=\"RenderLayers\" no_mod=true)}} component, which determines what layers they can see.\n\n\n\n```rust\n\n// spawn a sprite on layer 0\n\ncommands\n\n .spawn_bundle(SpriteBundle {\n\n material: materials.add(Color::rgb(1.0, 0.5, 0.5).into()),\n\n transform: Transform::from_xyz(0.0, -50.0, 1.0),\n\n sprite: Sprite::new(Vec2::new(30.0, 30.0)),\n\n })\n\n .insert(RenderLayers::layer(0));\n\n// spawn a sprite on layer 1\n\ncommands\n\n .spawn_bundle(SpriteBundle {\n\n material: materials.add(Color::rgb(1.0, 0.5, 0.5).into()),\n\n transform: Transform::from_xyz(0.0, -50.0, 1.0),\n\n sprite: Sprite::new(Vec2::new(30.0, 30.0)),\n\n })\n\n .insert(RenderLayers::layer(1));\n\n// spawn a camera that only draws the sprite on layer 1\n\ncommands\n\n .spawn_bundle(OrthographicCameraBundle::new_2d());\n\n .insert(RenderLayers::layer(1));\n\n```\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 74, "score": 32591.495616618125 }, { "content": "## Parallel Queries\n\n\n\n<div class=\"release-feature-authors\">authors: @GrantMoyer</div>\n\n\n\nBevy ECS Queries are a flexible way to retrieve data from the Entity Component System. Systems that _use_ queries already run in parallel, but before this change the queries themselves could not be _iterated_ in parallel. **Bevy 0.2** adds the ability to easily iterate queries in parallel:\n\n\n\n```rs\n\nfn system(pool: Res<ComputeTaskPool>, mut query: Query<&mut Transform>) {\n\n query.iter().par_iter(32).for_each(&pool, |mut transform| {\n\n transform.translate(Vec3::new(1.0, 0.0, 0.0));\n\n });\n\n}\n\n```\n\n\n\nThis provides a nice functional api (similar to Rayon) that runs on top of the new `bevy_tasks` system. It breaks the query up into 32 \"batches\" and runs each batch as a different task in the bevy task system. \n\n\n\n## Transform System Rewrite\n\n\n\n<div class=\"release-feature-authors\">authors: @MarekLg</div>\n\n\n\n```rs\n\n// old\n\nfn system(translation: &Translation, rotation: &Rotation, scale: &Scale) {\n\n println!(\"{} {} {}\", translation.0, rotation.0, scale.0);\n\n}\n\n\n\n// new\n\nfn system(transform: &Transform) {\n\n println!(\"{} {} {}\", transform.translation(), transform.rotation(), transform.scale());\n\n}\n\n```\n\n\n\nBevy's old transform system used separate `Translation`, `Rotation`, and `Scale` components as the \"source of truth\". Users modified with these components in their systems, after which they were synced to a `LocalTransform` component, which was in turn synced to a global `Transform` component, taking hierarchy into account. This was nice for a couple of reasons:\n\n\n\n* Slightly more cache efficient to retrieve individual components like `Translation` (because less data needs to be accessed)\n\n* Theoretically more parallel-friendly. Systems that only access `Translation` won't block systems accessing `Rotation`.\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 75, "score": 32591.4821676462 }, { "content": "+++\n\ntitle = \"Book\"\n\nsort_by = \"weight\"\n\ntemplate = \"book-section.html\"\n\npage_template = \"book-section.html\"\n\nredirect_to = \"learn/book/introduction\"\n", "file_path": "content/learn/book/_index.md", "rank": 76, "score": 32590.9273584469 }, { "content": "For-each systems were nice to look at and sometimes saved some typing. Why remove them?\n\n\n\n1. For-each systems were fundamentally limited in a number of ways. They couldn't iterate removed components, filter, control iteration, or use multiple queries at the same time. This meant they needed to be converted to \"query systems\" as soon as those features were needed.\n\n2. Bevy should generally have \"one way to do things\". For-each systems were a slightly more ergonomic way to define a small subset of system types. This forced people to make a \"design decision\" when they shouldn't need to. It also made examples and tutorials inconsistent according to people's preferences for one or the other.\n\n3. There were a number of \"gotchas\" for newcomers that constantly come up in our support forums and confused newbies:\n\n * users expect `&mut T` queries to work in foreach systems (ex: `fn system(a: &mut A) {}`). These can't work because we require `Mut<T>` tracking pointers to ensure change tracking always works as expected. The equivalent `Query<&mut A>` works because we can return the tracking pointer when iterating the Query.\n\n * A \"run this for-each system on some criteria\" bug that was common enough that we had to cover it in the Bevy Book.\n\n4. They increased compile times. Removing for-each systems saved me about ~5 seconds on clean Bevy compiles)\n\n5. Their internal implementation required a complicated macro. This affected maintainability.\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 77, "score": 32590.651025249783 }, { "content": "## Transform Re-Rewrite\n\n\n\n<div class=\"release-feature-authors\">authors: @MarekLg (with some design help from @AThilenius, @bitshifter, @termhn, and @cart)</div>\n\n\n\nTransforms are important to get right. They are used in many slices of the engine, user code touches them constantly, and they are relatively expensive to compute: especially transform hierarchies.\n\n\n\nIn the last release, we vastly simplified Bevy's transform system to use a consolidated `Transform` and `GlobalTransform` instead of multiple separate `Translation`, `Rotation`, and `Scale` components (which were synced to `Transform` and `GlobalTransform`). This made the user-facing api/dataflow simpler, as well as the underlying implementation. The `Transform` component was backed by a 4x4 matrix. I pressed the big green \"merge\" button ... happy that we had solved the Transform problem once and for all!\n\n\n\nIt turns out there was still more work to be done! [@AThilenius pointed out](https://github.com/bevyengine/bevy/issues/229#issuecomment-698953161) that using a 4x4 matrix as the source of truth for an affine transform accumulates error over time. Additionally, the Transform api was still a little cumbersome to use. [At the suggestion of @termhn](https://github.com/bevyengine/bevy/issues/229#issuecomment-699172675) we decided to investigate using a \"similarity\" as the source of truth. This had the following benefits:\n\n\n\n1. no more error accumulation\n\n2. we could directly expose translation/rotation/scale fields, which simplified the api significantly\n\n3. cheaper to store and cheaper to compute hierarchies in some cases\n\n\n\nWe collectively decided this was a good path forward and now we have a re-rewrite that is even better. Yes this is _another_ breaking change, but thats why we label Bevy as being in the \"experimentation phase\". Now is the time to break things as often as possible to ensure that we find good apis that will stand the test of time.\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 78, "score": 32590.499914861884 }, { "content": "```\n\n\n\nThe ambiguity detector found a conflict and mentions that adding an explicit dependency would resolve the conflict:\n\n\n\n```rust\n\napp\n\n .add_system(increment_counter.system().label(\"increment\"))\n\n .add_system(print_every_other_time.system().after(\"increment\"))\n\n```\n\n\n\nThere _are_ some cases where ambiguities are _not_ a bug, such as operations on unordered collection like `Assets`. This is why we don't enable the detector by default. You are free to just ignore these ambiguities, but if you want to suppress the messages in the detector (without defining a dependency), you can add your systems to an \"ambiguity set\":\n\n\n\n```rust\n\napp\n\n .add_system(a.system().in_ambiguity_set(\"foo\"))\n\n .add_system(b.system().in_ambiguity_set(\"foo\"))\n\n```\n\n\n\nI want to stress that this is totally optional. Bevy code should be ergonomic and \"fun\" to write. If sprinkling ambiguity sets everywhere isn't your cup of tea, just don't worry about it!\n\n\n\nWe are also actively seeking feedback on the new executor. We believe that the new implementation is easier to understand and encourages self-documenting code. The improved parallelism is also nice! But we want to hear from users (both new users starting fresh and old users porting their codebases to the new executor). This space is all about design tradeoffs and feedback will help us ensure we made the right calls.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 79, "score": 32590.252125268322 }, { "content": "## GLTF Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @iwikal, @FuriouZz, @rod-salazar</div>\n\n\n\nBevy's GLTF loader now imports Cameras. Here is a simple scene setup in Blender:\n\n\n\n![gltf_camera_blender](gltf_camera_blender.png)\n\n\n\nAnd here is how it looks in Bevy (the lighting is different because we don't import lights yet):\n\n\n\n![gltf_camera_bevy](gltf_camera_bevy.png)\n\n\n\n\n\nThere were also a number of other improvements:\n\n* Pixel format conversion while importing images from a GLTF\n\n* Default material loading\n\n* Hierarchy fixes\n\n\n\n## Spawn Scenes as Children\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf</div>\n\n\n\nScenes can now be spawned as children like this:\n\n\n\n```rust\n\ncommands\n\n .spawn((\n\n Transform::from_translation(Vec3::new(0.5, 0.0, 0.0)),\n\n GlobalTransform::default(),\n\n ))\n\n .with_children(|parent| {\n\n parent.spawn_scene(asset_server.load(\"scene.gltf\"));\n\n });\n\n```\n\n\n\nBy spawning beneath a parent, this enables you to do things like translate/rotate/scale multiple instances of the same scene:\n\n\n\n![scene_children](scene_children.png)\n\n\n\n## Dynamic Linking\n\n\n\n<div class=\"release-feature-authors\">authors: @bjorn3, @cart</div>\n\n\n\n@bjorn3 discovered that you can force Bevy to dynamically link.\n\n\n\nThis _significantly_ reduces iterative compile times. Check out how long it takes to compile a change made to the `3d_scene.rs` example with the [Fast Compiles Config](https://bevyengine.org/learn/book/getting-started/setup/) _and_ dynamic linking:\n\n\n\n![fast dynamic](dynamic_fast.png)\n\n\n\n### Time To Compile Change To 3d_scene Example (in seconds, less is better)\n\n\n\n![fast_compiles](fast_compiles.svg)\n\n\n\n\n\nWe added a cargo feature to easily enable dynamic linking during development\n\n\n\n```sh\n\n# for a bevy app\n\ncargo run --features bevy/dynamic\n\n\n\n# for bevy examples\n\ncargo run --features dynamic --example breakout\n\n```\n\n\n\nJust keep in mind that you should disable the feature when publishing your game.\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 80, "score": 32589.737768258216 }, { "content": "### Fixed\n\n\n\n- [Fixed typos in KeyCode identifiers][857]\n\n- [Remove redundant texture copies in TextureCopyNode][871]\n\n- [Fix a deadlock that can occur when using scope() on ComputeTaskPool from within a system][892]\n\n- [Don't draw text that isn't visible][893]\n\n- [Use `instant::Instant` for WASM compatibility][895]\n\n- [Fix pixel format conversion in bevy_gltf][897]\n\n- [Fixed duplicated children when spawning a Scene][904]\n\n- [Corrected behaviour of the UI depth system][905]\n\n- [Allow despawning of hierarchies in threadlocal systems][908]\n\n- [Fix `RenderResources` index slicing][948]\n\n- [Run parent-update and transform-propagation during the \"post-startup\" stage][955]\n\n- [Fix collision detection by comparing abs() penetration depth][966]\n\n- [deal with rounding issue when creating the swap chain][997]\n\n- [only update components for entities in map][1023]\n\n- [Don't panic when attempting to set shader defs from an asset that hasn't loaded yet][1035]\n\n\n\n[273]: https://github.com/bevyengine/bevy/pull/273\n\n[691]: https://github.com/bevyengine/bevy/pull/691\n\n[719]: https://github.com/bevyengine/bevy/pull/719\n\n[761]: https://github.com/bevyengine/bevy/pull/761\n\n[761]: https://github.com/bevyengine/bevy/pull/761\n\n[765]: https://github.com/bevyengine/bevy/pull/765\n\n[772]: https://github.com/bevyengine/bevy/pull/772\n\n[772]: https://github.com/bevyengine/bevy/pull/772\n\n[789]: https://github.com/bevyengine/bevy/pull/789\n\n[791]: https://github.com/bevyengine/bevy/pull/791\n\n[798]: https://github.com/bevyengine/bevy/pull/798\n\n[801]: https://github.com/bevyengine/bevy/pull/801\n\n[801]: https://github.com/bevyengine/bevy/pull/801\n\n[805]: https://github.com/bevyengine/bevy/pull/805\n\n[808]: https://github.com/bevyengine/bevy/pull/808\n\n[815]: https://github.com/bevyengine/bevy/pull/815\n\n[820]: https://github.com/bevyengine/bevy/pull/820\n\n[821]: https://github.com/bevyengine/bevy/pull/821\n\n[821]: https://github.com/bevyengine/bevy/pull/821\n\n[829]: https://github.com/bevyengine/bevy/pull/829\n\n[829]: https://github.com/bevyengine/bevy/pull/829\n\n[834]: https://github.com/bevyengine/bevy/pull/834\n\n[834]: https://github.com/bevyengine/bevy/pull/834\n\n[836]: https://github.com/bevyengine/bevy/pull/836\n\n[836]: https://github.com/bevyengine/bevy/pull/836\n\n[842]: https://github.com/bevyengine/bevy/pull/842\n\n[843]: https://github.com/bevyengine/bevy/pull/843\n\n[847]: https://github.com/bevyengine/bevy/pull/847\n\n[852]: https://github.com/bevyengine/bevy/pull/852\n\n[852]: https://github.com/bevyengine/bevy/pull/852\n\n[857]: https://github.com/bevyengine/bevy/pull/857\n\n[857]: https://github.com/bevyengine/bevy/pull/857\n\n[859]: https://github.com/bevyengine/bevy/pull/859\n\n[859]: https://github.com/bevyengine/bevy/pull/859\n\n[863]: https://github.com/bevyengine/bevy/pull/863\n\n[864]: https://github.com/bevyengine/bevy/pull/864\n\n[871]: https://github.com/bevyengine/bevy/pull/871\n\n[876]: https://github.com/bevyengine/bevy/pull/876\n\n[876]: https://github.com/bevyengine/bevy/pull/876\n\n[883]: https://github.com/bevyengine/bevy/pull/883\n\n[887]: https://github.com/bevyengine/bevy/pull/887\n\n[892]: https://github.com/bevyengine/bevy/pull/892\n\n[893]: https://github.com/bevyengine/bevy/pull/893\n\n[893]: https://github.com/bevyengine/bevy/pull/893\n\n[893]: https://github.com/bevyengine/bevy/pull/893\n\n[894]: https://github.com/bevyengine/bevy/pull/894\n\n[894]: https://github.com/bevyengine/bevy/pull/894\n\n[894]: https://github.com/bevyengine/bevy/pull/894\n\n[895]: https://github.com/bevyengine/bevy/pull/895\n\n[895]: https://github.com/bevyengine/bevy/pull/895\n\n[897]: https://github.com/bevyengine/bevy/pull/897\n\n[903]: https://github.com/bevyengine/bevy/pull/903\n\n[904]: https://github.com/bevyengine/bevy/pull/904\n\n[904]: https://github.com/bevyengine/bevy/pull/904\n\n[905]: https://github.com/bevyengine/bevy/pull/905\n\n[905]: https://github.com/bevyengine/bevy/pull/905\n\n[908]: https://github.com/bevyengine/bevy/pull/908\n\n[914]: https://github.com/bevyengine/bevy/pull/914\n\n[914]: https://github.com/bevyengine/bevy/pull/914\n\n[917]: https://github.com/bevyengine/bevy/pull/917\n\n[917]: https://github.com/bevyengine/bevy/pull/917\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 81, "score": 32589.683171179244 }, { "content": "### Profiling\n\n\n\nWe have added the option to add \"tracing spans\" to all ECS systems by enabling the `trace` feature. We also have built in support for the `tracing-chrome` extension, which causes Bevy to output traces in the \"chrome tracing\" format.\n\n\n\nIf you run your app with `cargo run --features bevy/trace,bevy/trace_chrome` you will get a json file which can be opened in Chrome browsers by visiting the `chrome://tracing` url:\n\n\n\n![profiling](profiling.png)\n\n\n\n@superdump added support for those nice \"span names\" to upstream `tracing_chrome`.\n\n\n\n\n\n## HIDPI\n\n\n\n<div class=\"release-feature-authors\">authors: @mockersf, @blunted2night, @cart</div>\n\n\n\nBevy now handles HIDPI / Retina / high pixel density displays properly:\n\n\n\n* OS-reported pixel density is now taken into account when creating windows. If a Bevy App asks for a 1280x720 window on a 2x pixel density display, it will create a window that is 2560x1440\n\n* Window width/height is now reported in \"logical units\" (1280x720 in the example above). Physical units are still available using the `window.physical_width()` and `window.physical_height()` methods.\n\n* Window \"swap chains\" are created using the physical resolution to ensure we still have crisp rendering (2560x1440 in the example above) \n\n* Bevy UI has been adapted to handle HIDPI scaling correctly\n\n\n\nThere is still a bit more work to be done here. While Bevy UI renders images and boxes at crisp HIDPI resolutions, text is still rendered using the logical resolution, which means it won't be as crisp as it could be on HIDPI displays.\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 82, "score": 32589.60154796946 }, { "content": "## Joystick/Gamepad Input\n\n\n\n<div class=\"release-feature-authors\">authors: @simpuid</div>\n\n\n\nThe Bevy Input plugin now has cross-platform support for most controllers thanks to the [gilrs](https://gitlab.com/gilrs-project/gilrs) library!\n\n\n\n```rs\n\nfn button_system(gamepads: Res<Vec<Gamepad>>, button_input: Res<Input<GamepadButton>>) {\n\n for gamepad in gamepads.iter() {\n\n if button_input.just_pressed(GamepadButton(*gamepad, GamepadButtonType::RightTrigger)) {\n\n println!(\"Pressed right trigger!\");\n\n }\n\n }\n\n}\n\n```\n\n\n\n\n\n## Bevy ECS Performance Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\n### Generational Entity IDs\n\n\n\nWe changed Entity IDs from being random UUIDs to incrementing generational indices. Random UUIDs were nice because they could be created anywhere, were unique across game runs, and could be safely persisted to files or reused across networks. I was really hoping we could make them work, but they ended up being too slow relative to the alternatives. The randomness had a measurable cost and entity locations had to be looked up using a hash map.\n\n\n\nBy moving to generational indices (we use the hecs implementation), we can directly use entity ids as array indices, which makes entity location lookups lightning fast.\n\n\n\n\n\n### Read Only Queries\n\n\n\nI implemented \"read only\" traits for queries that don't mutate anything. This allows us to guarantee that a query won't mutate anything.\n\n\n\n### Removed locking from World apis\n\n\n\nThis gives us a really nice speed boost. We can do this safely due to a combination of the new \"read only queries\" and changing World mutation apis to be a mutable World borrow.\n\n\n\nThis is not yet enabled for `Queries` in systems because a system could have multiple `Queries`, which could be simultaneously accessed in a way that doesn't make mutable access unique. I think thats a solve-able problem, but it will take a bit more work. Fortunately \"for-each\" systems don't have any collision risk, so we now use lock-less queries there.\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 83, "score": 32589.19815362357 }, { "content": "## Text Layout Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @AlisCode, @tigregalis</div>\n\n\n\nPrior Bevy releases used a custom, naive text layout system. It had a number of bugs and limitations, such as the infamous \"wavy text\" bug:\n\n\n\n![wavy_text](wavy_text.png)\n\n\n\nThe new text layout system uses glyph_brush_layout, which fixes the layout bugs and adds a number of new layout options. Note that the \"Fira Sans\" font used in the example has some stylistic \"waviness\" ... this isn't a bug:\n\n\n\n![text_layout](text_layout.png)\n\n\n\n\n\n## Renderer Optimization\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nBevy's render api was built to be easy to use and extend. I wanted to nail down a good api first, but that resulted in a number of performance TODOs that caused some pretty serious overhead.\n\n\n\nFor **Bevy 0.4** I decided to resolve as many of those TODOs as I could. There is still plenty more to do (like instancing and batching), but Bevy already performs _much_ better than it did before.\n\n\n\n### Incrementalize Everything\n\n\n\nMost of Bevy's high level render abstractions were designed to be incrementally updated, but when I was first building the engine, ECS change detection wasn't implemented. Now that we have all of these nice optimization tools, it makes sense to use them!\n\n\n\nFor the first optimization round, I incrementalized as much as I could:\n\n* Added change detection to RenderResourceNode, Sprites, and Transforms, which improved performance when those values don't change\n\n* Only sync asset gpu data when the asset changes\n\n* Share asset RenderResourceBindings across all entities that reference an asset\n\n* Mesh provider system now only updates mesh specialization when it needs to\n\n* Stop clearing bind groups every frame and remove stale bind groups every other frame\n\n* Cache unmatched render resource binding results (which prevents redundant computations per-entity per-frame)\n\n* Don't send render pass state change commands when the state has not actually changed\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 84, "score": 32589.120877563968 }, { "content": "### Total Combined Percent CPU Usage - 8 Core Machine (smaller is better)\n\n\n\n![threading cpu usage 8 core](bevy_tasks_1.svg)\n\n\n\n### Total Combined Percent CPU Usage - 32 Core Machine (smaller is better)\n\n\n\n![threading cpu usage 32 core](bevy_tasks_2.svg)\n\n\n\n## Initial Web Platform Support\n\n\n\n<div class=\"release-feature-authors\">authors: @smokku</div>\n\n\n\n(A subset of) Bevy now runs on the web using WebAssembly/WASM! Specifically, Bevy apps can run Bevy ECS schedules, react to input events, create an empty canvas (using winit), and a few other things. This is a huge first step, but it is important to call out that there are still a number of missing pieces, such as 2D/3D rendering, multi-threading, and sound. \n\n\n\nThose limitations haven't stopped @mrk-its from building the first WASM Bevy game!\n\n\n\n### [bevy-robbo](https://github.com/mrk-its/bevy-robbo) ([playable here](https://mrk.sed.pl/bevy-robbo/ascii/))\n\n\n\n![bevy-robbo](bevy-robbo.png)\n\n\n\nThey use Bevy for game logic and cleverly work around the render limitations by passing ASCII art game state from [this Bevy system](https://github.com/mrk-its/bevy-robbo/blob/ascii/src/systems/js_render.rs) to [this JavaScript function](https://github.com/mrk-its/bevy-robbo/blob/ascii/wasm/render.js). \n\n\n\nYou can play around with some Bevy WASM examples by [following the instructions here](https://github.com/bevyengine/bevy/tree/v0.2.0/examples#wasm).\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 85, "score": 32588.855841847908 }, { "content": "### Configurable SystemParams\n\n\n\n<div class=\"release-feature-authors\">authors: @cart, @DJMcNab</div>\n\n\n\nUsers can now provide some initial configuration / values for system parameters (when possible). Most SystemParams have no config (the config type is `()`), but the `Local<T>` param now supports user-provided parameters:\n\n\n\n```rust\n\nfn foo(value: Local<usize>) { \n\n}\n\n\n\napp.add_system(foo.system().config(|c| c.0 = Some(10)));\n\n```\n\n\n\n### Preparation for Scripting Support\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nBevy ECS Components are now decoupled from Rust types. The new `Components` collection stores metadata such as memory layout and destructors. Components also no longer require Rust TypeIds.\n\n\n\nNew component metadata can be added at any time using `world.register_component()`.\n\n\n\nAll component storage types (currently Table and Sparse Set) are \"blob storage\". They can store any value with a given memory layout. This enables data from other sources (ex: a Python data type) to be stored and accessed in the same way as Rust data types.\n\n\n\nWe haven't completely enabled scripting yet ([and will likely never officially support non-Rust scripting](https://discord.com/channels/691052431525675048/692648082499829760/817178225791729716)), but this is a major step toward enabling community-supported scripting languages.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 86, "score": 32588.76044968479 }, { "content": "## Cross Platform Main Function\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nOn most supported Bevy platforms you can just use normal main functions (ex: Windows, MacOS, Linux, and Web). Here is the smallest possible Bevy app that runs on those platforms:\n\n\n\n```rust\n\nuse bevy::prelude::*;\n\n\n\nfn main() {\n\n App::build().run();\n\n}\n\n```\n\n\n\nHowever some platforms (currently Android and iOS) require additional boilerplate. This arcane magic is error prone, takes up space, and isn't particularly nice to look at. Up until this point, Bevy users had to supply their own boilerplate ... but no more! **Bevy 0.4** adds a new `#[bevy_main]` proc-macro, which inserts the relevant boilerplate for you. This is a big step toward our \"write once run anywhere\" goal.\n\n\n\nThis Bevy App has all the code required to run on Windows, MacOS, Linux, Android, iOS, and Web:\n\n\n\n```rust\n\nuse bevy::prelude::*;\n\n\n\n#[bevy_main]\n\nfn main() {\n\n App::build().run();\n\n}\n\n```\n\n\n\n## Live Shader Reloading\n\n\n\n<div class=\"release-feature-authors\">authors: @yrns</div>\n\n\n\nBevy can now update changes to shaders at runtime, giving you instant feedback without restarting your app. This video isn't sped up!\n\n\n\n<video controls loop><source src=\"hot_shader_reloading.mp4\" type=\"video/mp4\"/></video>\n\n\n\n## ECS Improvements\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nIt wouldn't be a Bevy update without another round of ECS improvements!\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 87, "score": 32588.29540862772 }, { "content": "### Performance Improvements\n\n\n\nBevy had a number of nice performance improvements this release:\n\n\n\n* Removed atomic locks from Query access, making Bevy ECS 100% lock free\n\n* Removed archetype \"safety checks\" from Query access. At this point we have already verified that the given Query access is safe, so we don't need to check again on every call.\n\n* Rewrote `QueryIter` to be simpler (and therefore easier to control optimizations for), which allowed us to remove the iterator wrapper without tanking performance. This also resolved some performance inconsistencies where some system permutations performed optimally and others didn't. Now everything is on the \"fast path\"! \n\n* Ported some performance improvements from upstream hecs, which improved iteration over heavily fragmented archetypes and improved component insertion times\n\n\n\n#### Getting an Entity's Component (per 100k, in milliseconds, smaller is better)\n\n\n\nNote: these numbers are for getting a component 100,000 times, not for an individual component lookup\n\n\n\n![getting an entity's component](ecs_get_component.svg)\n\n\n\nThis is where the big wins were. By removing locks and safety checks from Query systems, we were able to _significantly_ reduce the cost of retrieving a specific entity's component from within a system.\n\n\n\nI included a comparison to [Legion ECS](https://github.com/amethyst/legion) (another great archetypal ECS with a parallel scheduler) to illustrate why Bevy's new approach is so cool. Legion exposes a direct \"world like\" api (called a SubWorld) in its systems. The SubWorld's entry api _cannot_ know ahead of time what types will be passed into it, which means it _must_ do (relatively) expensive safety checks to ensure the user doesn't request access to something they shouldn't.\n\n\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 88, "score": 32588.279259847226 }, { "content": "### Fixed\n\n\n\n- [Properly update bind group ids when setting dynamic bindings][560]\n\n- [Properly exit the app on AppExit event][610]\n\n- [Fix FloatOrd hash being different for different NaN values][618]\n\n- [Fix Added behavior for QueryOne get][543]\n\n- [Update camera_system to fix issue with late camera addition][488]\n\n- [Register `IndexFormat` as a property][664]\n\n- [Fix breakout example bug][685]\n\n- [Fix PreviousParent lag by merging parent update systems][713]\n\n- [Fix bug of connection event of gamepad at startup][730]\n\n- [Fix wavy text][725]\n\n\n\n[397]: https://github.com/bevyengine/bevy/pull/397\n\n[460]: https://github.com/bevyengine/bevy/pull/460\n\n[488]: https://github.com/bevyengine/bevy/pull/488\n\n[515]: https://github.com/bevyengine/bevy/pull/515\n\n[528]: https://github.com/bevyengine/bevy/pull/528\n\n[535]: https://github.com/bevyengine/bevy/pull/535\n\n[538]: https://github.com/bevyengine/bevy/pull/538\n\n[539]: https://github.com/bevyengine/bevy/pull/539\n\n[543]: https://github.com/bevyengine/bevy/pull/543\n\n[544]: https://github.com/bevyengine/bevy/pull/544\n\n[552]: https://github.com/bevyengine/bevy/pull/552\n\n[560]: https://github.com/bevyengine/bevy/pull/560\n\n[565]: https://github.com/bevyengine/bevy/pull/565\n\n[568]: https://github.com/bevyengine/bevy/pull/568\n\n[572]: https://github.com/bevyengine/bevy/pull/572\n\n[579]: https://github.com/bevyengine/bevy/pull/579\n\n[595]: https://github.com/bevyengine/bevy/pull/595\n\n[596]: https://github.com/bevyengine/bevy/pull/596\n\n[597]: https://github.com/bevyengine/bevy/pull/597\n\n[599]: https://github.com/bevyengine/bevy/pull/599\n\n[610]: https://github.com/bevyengine/bevy/pull/610\n\n[616]: https://github.com/bevyengine/bevy/pull/616\n\n[618]: https://github.com/bevyengine/bevy/pull/618\n\n[627]: https://github.com/bevyengine/bevy/pull/627\n\n[632]: https://github.com/bevyengine/bevy/pull/632\n\n[644]: https://github.com/bevyengine/bevy/pull/644\n\n[645]: https://github.com/bevyengine/bevy/pull/645\n\n[649]: https://github.com/bevyengine/bevy/pull/649\n\n[651]: https://github.com/bevyengine/bevy/pull/651\n\n[653]: https://github.com/bevyengine/bevy/pull/653\n\n[660]: https://github.com/bevyengine/bevy/pull/660\n\n[661]: https://github.com/bevyengine/bevy/pull/661\n\n[664]: https://github.com/bevyengine/bevy/pull/664\n\n[671]: https://github.com/bevyengine/bevy/pull/671\n\n[674]: https://github.com/bevyengine/bevy/pull/674\n\n[675]: https://github.com/bevyengine/bevy/pull/675\n\n[678]: https://github.com/bevyengine/bevy/pull/678\n\n[679]: https://github.com/bevyengine/bevy/pull/679\n\n[683]: https://github.com/bevyengine/bevy/pull/683\n\n[685]: https://github.com/bevyengine/bevy/pull/685\n\n[689]: https://github.com/bevyengine/bevy/pull/689\n\n[690]: https://github.com/bevyengine/bevy/pull/690\n\n[692]: https://github.com/bevyengine/bevy/pull/692\n\n[693]: https://github.com/bevyengine/bevy/pull/693\n\n[696]: https://github.com/bevyengine/bevy/pull/696\n\n[700]: https://github.com/bevyengine/bevy/pull/700\n\n[703]: https://github.com/bevyengine/bevy/pull/703\n\n[711]: https://github.com/bevyengine/bevy/pull/711\n\n[713]: https://github.com/bevyengine/bevy/pull/713\n\n[723]: https://github.com/bevyengine/bevy/pull/723\n\n[725]: https://github.com/bevyengine/bevy/pull/725\n\n[727]: https://github.com/bevyengine/bevy/pull/727\n\n[730]: https://github.com/bevyengine/bevy/pull/730\n\n[740]: https://github.com/bevyengine/bevy/pull/740\n\n[741]: https://github.com/bevyengine/bevy/pull/741\n\n[744]: https://github.com/bevyengine/bevy/pull/744\n\n[745]: https://github.com/bevyengine/bevy/pull/745\n", "file_path": "content/news/2020-11-03-bevy-0.3/index.md", "rank": 89, "score": 32588.202494095218 }, { "content": "### Simplified Query Filters\n\n\n\nUp until now, Bevy's Query filters were intermingled with components:\n\n\n\n```rust\n\nfn system(query: Query<With<A, Without<B, (&Transform, Changed<Velocity>)>>>) {\n\n}\n\n```\n\n\n\nConfused? You wouldn't be the first! You can interpret the query above as \"give me immutable references to the `Transform` and `Velocity` components of all entities that have the `A` component, _do not_ have the `B` component, and have a changed Velocity component\".\n\n\n\nFirst, the nesting of types via With / Without makes it very unclear whats going on. Additionally, it's hard to tell what the `Changed<Velocity>` parameter does. Is it just a filter? Does it also return a Velocity component? If so, is it immutable or mutable?\n\n\n\nIt made sense to break up these concepts. In **Bevy 0.4**, Query filters are separate from Query components. The query above looks like this:\n\n\n\n```rust\n\n// Query with filters\n\nfn system(query: Query<(&Transform, &Velocity), (With<A>, Without<B>, Changed<Velocity>)>) {\n\n}\n\n\n\n// Query without filters\n\nfn system(query: Query<(&Transform, &Velocity)>) {\n\n}\n\n```\n\n\n\nThis makes it much easier to tell what a Query is doing at a glance. It also makes for more composable behaviors. For example, you can now filter on `Changed<Velocity>` without actually retrieving the `Velocity` component.\n\n\n\nAnd now that filters are a separate type, you can create type aliases for filters that you want to re-use:\n\n\n\n```rust\n\ntype ChangedVelocity = (With<A>, Without<B>, Changed<Velocity>);\n\n\n\nfn system(query: Query<(&Transform, &Velocity), ChangedVelocity>) {\n\n}\n\n```\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 90, "score": 32588.042240103667 }, { "content": "## ECS Core Rewrite\n\n\n\n<div class=\"release-feature-authors\">authors: @cart</div>\n\n\n\nUp until this point, Bevy used a heavily forked version of [hecs](https://github.com/Ralith/hecs) for our ECS core. Since Bevy's first release, we've learned a lot about Bevy's ECS needs. We've also collaborated with other ECS project leaders, such as [Sander Mertens](https://github.com/SanderMertens) (lead [flecs](https://github.com/SanderMertens/flecs) developer) and [Gijs-Jan Roelofs](https://github.com/gjroelofs) (Xenonauts ECS framework developer). As an \"ECS community\", we've started to zero in on what the future of ECS could be.\n\n\n\nBevy ECS v2 is our first step into that future. It also means that Bevy ECS is no longer a \"hecs fork\". We are going out on our own!\n\n\n\n### Component Storage (The Problem) \n\n\n\nTwo ECS storage paradigms have gained a lot of traction over the years:\n\n\n\n* **Archetypal ECS**:\n\n * Stores components in \"tables\" with static schemas. Each \"column\" stores components of a given type. Each \"row\" is an entity.\n\n * Each \"archetype\" has its own table. Adding/removing an entity's component changes the archetype.\n\n * Enables super-fast Query iteration due to its cache-friendly data layout\n\n * Comes at the cost of more expensive add/remove operations for an Entity's components, because all components need to be copied to the new archetype's \"table\"\n\n * Parallelism-friendly: entities only exist in one archetype at a time so systems that access the same components but in different archetypes can run in parallel \n\n * Frameworks: Old Bevy ECS, hecs, legion, flecs, Unity DOTS\n\n* **Sparse Set ECS**:\n\n * Stores components of the same type in densely packed arrays, which are sparsely indexed by densely packed unsigned integers (entity ids)\n\n * Query iteration is slower than Archetypal ECS (by default) because each entity's component could be at any position in the sparse set. This \"random access\" pattern isn't cache friendly. Additionally, there is an extra layer of indirection because you must first map the entity id to an index in the component array.\n\n * Adding/removing components is a cheap, constant time operation\n\n * \"Component Packs\" are used to optimize iteration performance on a case by case basis (but packs conflict with each other)\n\n * Less parallelism friendly: systems need to either lock a whole component storage (not granular) or individual entities (expensive)\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 91, "score": 32587.773279905072 }, { "content": "## HIDPI Text\n\n\n\n<div class=\"release-feature-authors\">authors: @blunted2night</div>\n\n\n\nText is now rendered according to the current monitor's scale factor. This gives nice, crisp text at any resolution.\n\n\n\n![hidpi_text](hidpi_text.png)\n\n\n\n## Render Text in 2D World Space\n\n\n\n<div class=\"release-feature-authors\">authors: @CleanCut, @blunted2night</div>\n\n\n\nText can now be spawned into 2D scenes using the new `Text2dBundle`. This makes it easier to do things like \"draw names above players\".\n\n\n\n<video controls loop><source src=\"2d_text.mp4\" type=\"video/mp4\"/></video>\n\n\n\n## World To Screen Coordinate Conversions\n\n\n\n<div class=\"release-feature-authors\">authors: @aevyrie</div>\n\n\n\nIt is now possible to convert world coordinates to a given camera's screen coordinates using the new `Camera::world_to_screen()` function. Here is an example of this feature being used to position a UI element on top of a moving 3d object. \n\n\n\n<video controls loop><source src=\"world_to_screen.mp4\" type=\"video/mp4\"/></video>\n\n\n\n## 3D Orthographic Camera\n\n\n\n<div class=\"release-feature-authors\">authors: @jamadazi</div>\n\n\n\nOrthographic cameras can now be used in 3D! This is useful for things like CAD applications and isometric games.\n\n\n\n![ortho_3d](ortho_3d.png)\n\n\n\n## Orthographic Camera Scaling Modes\n\n\n\n<div class=\"release-feature-authors\">authors: @jamadazi</div>\n\n\n\nPrior to **Bevy 0.5**, Bevy's orthographic camera had only one mode: \"window scaling\". It would adapt the projection according to the vertical and horizontal size of the window. This works for some styles of games, but other games need arbitrary window-independent scale factors or scale factors defined by either horizontal or vertical window sizes.\n\n\n\n**Bevy 0.5** adds a new `ScalingMode` option to `OrthographicCamera`, which enables developers to customize how the projection is calculated.\n\n\n\nIt also adds the ability to \"zoom\" the camera using `OrthographicProjection::scale`.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 92, "score": 32587.589307859012 }, { "content": "`Commands` have also been updated to use this new pattern\n\n\n\n```rust\n\nlet entity = commands.spawn()\n\n .insert(A)\n\n .insert_bundle((B, C))\n\n .insert_bundle(SomeBundle::default())\n\n .id();\n\n```\n\n\n\n`Commands` also still support spawning with a Bundle, which should make migration from **Bevy 0.4** easier. It also cuts down on boilerplate in some situations:\n\n\n\n```rust\n\ncommands.spawn_bundle(SomeBundle::default());\n\n```\n\n\n\nNote that these Command methods use the \"type state\" pattern, which means this style of chaining is no longer possible:\n\n\n\n```rust\n\n// Spawns two entities, each with the components in SomeBundle and the A component\n\n// Valid in Bevy 0.4, but invalid in Bevy 0.5\n\ncommands\n\n .spawn(SomeBundle::default())\n\n .insert(A)\n\n .spawn(SomeBundle::default())\n\n .insert(A);\n\n```\n\n\n\nInstead, you should do this:\n\n\n\n```rust\n\ncommands\n\n .spawn_bundle(SomeBundle::default())\n\n .insert(A);\n\ncommands\n\n .spawn_bundle(SomeBundle::default())\n\n .insert(A);\n\n```\n\n\n\nThis allows us to make things like \"entity id retrieval\" infallible and opens the doors to future api improvements.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 93, "score": 32587.24463161589 }, { "content": "## Contributors\n\n\n\nA huge thanks to the **88 contributors** that made this release (and associated docs) possible!\n\n\n\n* mockersf\n\n* CAD97\n\n* willcrichton\n\n* Toniman20\n\n* ElArtista\n\n* lassade\n\n* Divoolej\n\n* msklywenn\n\n* cart\n\n* maxwellodri\n\n* schell\n\n* payload\n\n* guimcaballero\n\n* themilkybit\n\n* Davier\n\n* TheRawMeatball\n\n* alexschrod\n\n* Ixentus\n\n* undinococo\n\n* zicklag\n\n* lambdagolem\n\n* reidbhuntley\n\n* enfipy\n\n* CleanCut\n\n* LukeDowell\n\n* IngmarBitter\n\n* MinerSebas\n\n* ColonisationCaptain\n\n* tigregalis\n\n* siler\n\n* Lythenas\n\n* Restioson\n\n* kokounet\n\n* ryanleecode\n\n* adam-bates\n\n* Neo-Zhixing\n\n* bgourlie\n\n* Telzhaak\n\n* rkr35\n\n* jamadazi\n\n* bjorn3\n\n* VasanthakumarV\n\n* turboMaCk\n\n* YohDeadfall\n\n* rmsc\n\n* szunami\n\n* mnmaita\n\n* WilliamTCarroll\n\n* Ratysz\n\n* OptimisticPeach\n\n* mtsr\n\n* AngelicosPhosphoros\n\n* Adamaq01\n\n* Moxinilian\n\n* tomekr\n\n* jakobhellermann\n\n* sdfgeoff\n\n* Byteron\n\n* aevyrie\n\n* verzuz\n\n* ndarilek\n\n* huhlig\n\n* zaszi\n\n* Puciek\n\n* DJMcNab\n\n* sburris0\n\n* rparrett\n\n* smokku\n\n* TehPers\n\n* alec-deason\n\n* Fishrock123\n\n* woubuc\n\n* Newbytee\n\n* Archina\n\n* StarArawn\n\n* JCapucho\n\n* M2WZ\n\n* TotalKrill\n\n* refnil\n\n* bitshifter\n\n* NiklasEi\n\n* alice-i-cecile\n\n* joshuajbouw\n\n* DivineGod\n\n* ShadowMitia\n\n* memoryruins\n\n* blunted2night\n\n* RedlineTriad\n\n\n\n## Change Log\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 94, "score": 32587.17693325364 }, { "content": "### Hybrid Component Storage (The Solution)\n\n\n\nIn Bevy ECS V2, we get to have our cake and eat it too. It now has _both_ of the component storage types above (and more can be added later if needed):\n\n\n\n* **Tables** (aka \"archetypal\" storage in other frameworks)\n\n * The default storage. If you don't configure anything, this is what you get\n\n * Fast iteration by default\n\n * Slower add/remove operations\n\n* **Sparse Sets**\n\n * Opt-in\n\n * Slower iteration\n\n * Faster add/remove operations\n\n\n\nThese storage types complement each other perfectly. By default Query iteration is fast. If developers know that they want to add/remove a component at high frequencies, they can set the storage to \"sparse set\":\n\n\n\n```rust\n\napp.register_component(\n\n ComponentDescriptor::new::<MyComponent>(StorageType::SparseSet)\n\n);\n\n```\n\n\n\n#### Component Add/Remove Benchmark (in milliseconds, less is better)\n\n\n\nThis benchmark illustrates adding and removing a single 4x4 matrix component 10,000 times from an entity that has 5 other 4x4 matrix components. The \"other\" components are included to help illustrate the cost of \"table storage\" (used by Bevy 0.4, Bevy 0.5 (Table), and Legion), which requires moving the \"other\" components to a new table.\n\n\n\n![component add/remove](add_remove_big.svg)\n\n\n\nYou may have noticed that **Bevy 0.5 (Table)** is also _way_ faster than **Bevy 0.4**, even though they both use \"table storage\". This is largely a result of the new [Archetype Graph](https://github.com/bevyengine/bevy/pull/1525), which significantly cuts the cost of archetype changes.\n\n\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 95, "score": 32587.0937414247 }, { "content": "However this approach also has some pretty serious downsides:\n\n\n\n* The \"individual components\" are the source of truth, so `LocalTransform` is out of date when user systems are running. If an up to date \"full transform\" is needed, it must be manually constructed by accessing all three components.\n\n* Very hard to reason about. There are 5 components users need to think about and they all interact with each other differently.\n\n* Setting a Transform to a specific matrix value (ex: `Mat4::look_at()`) was extremely cumbersome, and the value would be immediately overwritten unless the user explicitly disabled component syncing.\n\n\n\nGiven these issues, we decided to move to a single unified local-to-parent `Transform` component as the source of truth, and a computed `GlobalTransform` component for world-space transforms. We think this api will be much easier to use and to reason about. [Unity is also considering a similar Transform rework for their ECS](https://gist.github.com/joeante/79d25ec3a0e86436e53eb74f3ac82c0c) and a lot of discussion on this topic happened in this [Amethyst Forum Thread](https://community.amethyst.rs/t/legion-transform-design-discussion).\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 96, "score": 32587.008366693422 }, { "content": "- [Fix staging buffer required size calculation (fixes #1056)][1509]\n\n\n\n\n\n[400]: https://github.com/bevyengine/bevy/pull/400\n\n[542]: https://github.com/bevyengine/bevy/pull/542\n\n[547]: https://github.com/bevyengine/bevy/pull/547\n\n[562]: https://github.com/bevyengine/bevy/pull/562\n\n[1020]: https://github.com/bevyengine/bevy/pull/1020\n\n[1042]: https://github.com/bevyengine/bevy/pull/1042\n\n[1055]: https://github.com/bevyengine/bevy/pull/1055\n\n[1058]: https://github.com/bevyengine/bevy/pull/1058\n\n[1063]: https://github.com/bevyengine/bevy/pull/1063\n\n[1064]: https://github.com/bevyengine/bevy/pull/1064\n\n[1070]: https://github.com/bevyengine/bevy/pull/1070\n\n[1072]: https://github.com/bevyengine/bevy/pull/1072\n\n[1081]: https://github.com/bevyengine/bevy/pull/1081\n\n[1085]: https://github.com/bevyengine/bevy/pull/1085\n\n[1089]: https://github.com/bevyengine/bevy/pull/1089\n\n[1096]: https://github.com/bevyengine/bevy/pull/1096\n\n[1104]: https://github.com/bevyengine/bevy/pull/1104\n\n[1109]: https://github.com/bevyengine/bevy/pull/1109\n\n[1112]: https://github.com/bevyengine/bevy/pull/1112\n\n[1121]: https://github.com/bevyengine/bevy/pull/1121\n\n[1122]: https://github.com/bevyengine/bevy/pull/1122\n\n[1131]: https://github.com/bevyengine/bevy/pull/1131\n\n[1132]: https://github.com/bevyengine/bevy/pull/1132\n\n[1144]: https://github.com/bevyengine/bevy/pull/1144\n\n[1151]: https://github.com/bevyengine/bevy/pull/1151\n\n[1154]: https://github.com/bevyengine/bevy/pull/1154\n\n[1155]: https://github.com/bevyengine/bevy/pull/1155\n\n[1164]: https://github.com/bevyengine/bevy/pull/1164\n\n[1171]: https://github.com/bevyengine/bevy/pull/1171\n\n[1172]: https://github.com/bevyengine/bevy/pull/1172\n\n[1180]: https://github.com/bevyengine/bevy/pull/1180\n\n[1183]: https://github.com/bevyengine/bevy/pull/1183\n\n[1194]: https://github.com/bevyengine/bevy/pull/1194\n\n[1196]: https://github.com/bevyengine/bevy/pull/1196\n\n[1200]: https://github.com/bevyengine/bevy/pull/1200\n\n[1204]: https://github.com/bevyengine/bevy/pull/1204\n\n[1209]: https://github.com/bevyengine/bevy/pull/1209\n\n[1212]: https://github.com/bevyengine/bevy/pull/1212\n\n[1216]: https://github.com/bevyengine/bevy/pull/1216\n\n[1218]: https://github.com/bevyengine/bevy/pull/1218\n\n[1221]: https://github.com/bevyengine/bevy/pull/1221\n\n[1223]: https://github.com/bevyengine/bevy/pull/1223\n\n[1224]: https://github.com/bevyengine/bevy/pull/1224\n\n[1229]: https://github.com/bevyengine/bevy/pull/1229\n\n[1236]: https://github.com/bevyengine/bevy/pull/1236\n\n[1244]: https://github.com/bevyengine/bevy/pull/1244\n\n[1245]: https://github.com/bevyengine/bevy/pull/1245\n\n[1252]: https://github.com/bevyengine/bevy/pull/1252\n\n[1257]: https://github.com/bevyengine/bevy/pull/1257\n\n[1258]: https://github.com/bevyengine/bevy/pull/1258\n\n[1262]: https://github.com/bevyengine/bevy/pull/1262\n\n[1263]: https://github.com/bevyengine/bevy/pull/1263\n\n[1266]: https://github.com/bevyengine/bevy/pull/1266\n\n[1268]: https://github.com/bevyengine/bevy/pull/1268\n\n[1274]: https://github.com/bevyengine/bevy/pull/1274\n\n[1277]: https://github.com/bevyengine/bevy/pull/1277\n\n[1283]: https://github.com/bevyengine/bevy/pull/1283\n\n[1284]: https://github.com/bevyengine/bevy/pull/1284\n\n[1286]: https://github.com/bevyengine/bevy/pull/1286\n\n[1292]: https://github.com/bevyengine/bevy/pull/1292\n\n[1299]: https://github.com/bevyengine/bevy/pull/1299\n\n[1313]: https://github.com/bevyengine/bevy/pull/1313\n\n[1315]: https://github.com/bevyengine/bevy/pull/1315\n\n[1339]: https://github.com/bevyengine/bevy/pull/1339\n\n[1340]: https://github.com/bevyengine/bevy/pull/1340\n\n[1341]: https://github.com/bevyengine/bevy/pull/1341\n\n[1346]: https://github.com/bevyengine/bevy/pull/1346\n\n[1349]: https://github.com/bevyengine/bevy/pull/1349\n\n[1356]: https://github.com/bevyengine/bevy/pull/1356\n\n[1357]: https://github.com/bevyengine/bevy/pull/1357\n\n[1361]: https://github.com/bevyengine/bevy/pull/1361\n\n[1365]: https://github.com/bevyengine/bevy/pull/1365\n\n[1366]: https://github.com/bevyengine/bevy/pull/1366\n\n[1399]: https://github.com/bevyengine/bevy/pull/1399\n\n[1407]: https://github.com/bevyengine/bevy/pull/1407\n\n[1409]: https://github.com/bevyengine/bevy/pull/1409\n\n[1416]: https://github.com/bevyengine/bevy/pull/1416\n", "file_path": "content/news/2021-04-06-bevy-0.5/index.md", "rank": 97, "score": 32586.941920373934 }, { "content": "### Internal Improvements\n\n- Many improvements to Bevy's CI [#325][325], [#349][349], [#357][357], [#373][373], [#423][423]\n\n\n\n[145]: https://github.com/bevyengine/bevy/pull/145\n\n[183]: https://github.com/bevyengine/bevy/pull/183\n\n[249]: https://github.com/bevyengine/bevy/pull/249\n\n[270]: https://github.com/bevyengine/bevy/pull/270\n\n[271]: https://github.com/bevyengine/bevy/pull/271\n\n[275]: https://github.com/bevyengine/bevy/pull/275\n\n[280]: https://github.com/bevyengine/bevy/pull/280\n\n[290]: https://github.com/bevyengine/bevy/pull/290\n\n[292]: https://github.com/bevyengine/bevy/pull/292\n\n[304]: https://github.com/bevyengine/bevy/pull/304\n\n[312]: https://github.com/bevyengine/bevy/pull/312\n\n[314]: https://github.com/bevyengine/bevy/pull/314\n\n[323]: https://github.com/bevyengine/bevy/pull/323\n\n[324]: https://github.com/bevyengine/bevy/pull/324\n\n[325]: https://github.com/bevyengine/bevy/pull/325\n\n[331]: https://github.com/bevyengine/bevy/pull/331\n\n[332]: https://github.com/bevyengine/bevy/pull/332\n\n[338]: https://github.com/bevyengine/bevy/pull/332\n\n[345]: https://github.com/bevyengine/bevy/pull/345\n\n[349]: https://github.com/bevyengine/bevy/pull/349\n\n[357]: https://github.com/bevyengine/bevy/pull/357\n\n[358]: https://github.com/bevyengine/bevy/pull/358\n\n[361]: https://github.com/bevyengine/bevy/pull/361\n\n[362]: https://github.com/bevyengine/bevy/pull/362\n\n[363]: https://github.com/bevyengine/bevy/pull/363\n\n[373]: https://github.com/bevyengine/bevy/pull/373\n\n[374]: https://github.com/bevyengine/bevy/pull/374\n\n[376]: https://github.com/bevyengine/bevy/pull/376\n\n[381]: https://github.com/bevyengine/bevy/pull/381\n\n[383]: https://github.com/bevyengine/bevy/pull/383\n\n[384]: https://github.com/bevyengine/bevy/pull/384\n\n[385]: https://github.com/bevyengine/bevy/pull/385\n\n[386]: https://github.com/bevyengine/bevy/pull/386\n\n[390]: https://github.com/bevyengine/bevy/pull/390\n\n[394]: https://github.com/bevyengine/bevy/pull/394\n\n[396]: https://github.com/bevyengine/bevy/pull/396\n\n[339]: https://github.com/bevyengine/bevy/pull/339\n\n[406]: https://github.com/bevyengine/bevy/pull/406\n\n[417]: https://github.com/bevyengine/bevy/pull/417\n\n[423]: https://github.com/bevyengine/bevy/pull/423\n\n[428]: https://github.com/bevyengine/bevy/pull/428\n\n[430]: https://github.com/bevyengine/bevy/pull/430\n\n[433]: https://github.com/bevyengine/bevy/pull/433\n\n[444]: https://github.com/bevyengine/bevy/pull/444\n\n[451]: https://github.com/bevyengine/bevy/pull/451\n\n[463]: https://github.com/bevyengine/bevy/pull/463\n\n[478]: https://github.com/bevyengine/bevy/pull/478\n\n[485]: https://github.com/bevyengine/bevy/pull/485\n\n[486]: https://github.com/bevyengine/bevy/pull/486\n\n[490]: https://github.com/bevyengine/bevy/pull/490\n\n[491]: https://github.com/bevyengine/bevy/pull/491\n\n[495]: https://github.com/bevyengine/bevy/pull/495\n\n[496]: https://github.com/bevyengine/bevy/pull/496\n\n[503]: https://github.com/bevyengine/bevy/pull/503\n\n[504]: https://github.com/bevyengine/bevy/pull/504\n\n[505]: https://github.com/bevyengine/bevy/pull/505\n\n[506]: https://github.com/bevyengine/bevy/pull/506\n\n\n", "file_path": "content/news/2020-09-19-bevy-0.2/index.md", "rank": 98, "score": 32586.93262217541 }, { "content": "[920]: https://github.com/bevyengine/bevy/pull/920\n\n[920]: https://github.com/bevyengine/bevy/pull/920\n\n[926]: https://github.com/bevyengine/bevy/pull/926\n\n[926]: https://github.com/bevyengine/bevy/pull/926\n\n[928]: https://github.com/bevyengine/bevy/pull/928\n\n[928]: https://github.com/bevyengine/bevy/pull/928\n\n[931]: https://github.com/bevyengine/bevy/pull/931\n\n[931]: https://github.com/bevyengine/bevy/pull/931\n\n[932]: https://github.com/bevyengine/bevy/pull/932\n\n[934]: https://github.com/bevyengine/bevy/pull/934\n\n[934]: https://github.com/bevyengine/bevy/pull/934\n\n[937]: https://github.com/bevyengine/bevy/pull/937\n\n[940]: https://github.com/bevyengine/bevy/pull/940\n\n[945]: https://github.com/bevyengine/bevy/pull/945\n\n[945]: https://github.com/bevyengine/bevy/pull/945\n\n[946]: https://github.com/bevyengine/bevy/pull/946\n\n[947]: https://github.com/bevyengine/bevy/pull/947\n\n[948]: https://github.com/bevyengine/bevy/pull/948\n\n[952]: https://github.com/bevyengine/bevy/pull/952\n\n[955]: https://github.com/bevyengine/bevy/pull/955\n\n[955]: https://github.com/bevyengine/bevy/pull/955\n\n[955]: https://github.com/bevyengine/bevy/pull/955\n\n[956]: https://github.com/bevyengine/bevy/pull/956\n\n[958]: https://github.com/bevyengine/bevy/pull/958\n\n[966]: https://github.com/bevyengine/bevy/pull/966\n\n[969]: https://github.com/bevyengine/bevy/pull/969\n\n[972]: https://github.com/bevyengine/bevy/pull/972\n\n[973]: https://github.com/bevyengine/bevy/pull/973\n\n[979]: https://github.com/bevyengine/bevy/pull/979\n\n[987]: https://github.com/bevyengine/bevy/pull/987\n\n[995]: https://github.com/bevyengine/bevy/pull/995\n\n[997]: https://github.com/bevyengine/bevy/pull/997\n\n[1004]: https://github.com/bevyengine/bevy/pull/1004\n\n[1016]: https://github.com/bevyengine/bevy/pull/1016\n\n[1021]: https://github.com/bevyengine/bevy/pull/1021\n\n[1023]: https://github.com/bevyengine/bevy/pull/1023\n\n[1026]: https://github.com/bevyengine/bevy/pull/1026\n\n[1027]: https://github.com/bevyengine/bevy/pull/1027\n\n[1033]: https://github.com/bevyengine/bevy/pull/1033\n\n[1034]: https://github.com/bevyengine/bevy/pull/1034\n\n[1034]: https://github.com/bevyengine/bevy/pull/1034\n\n[1035]: https://github.com/bevyengine/bevy/pull/1035\n\n[1037]: https://github.com/bevyengine/bevy/pull/1037\n\n[1038]: https://github.com/bevyengine/bevy/pull/1038\n\n[1043]: https://github.com/bevyengine/bevy/pull/1043\n\n[1043]: https://github.com/bevyengine/bevy/pull/1043\n\n[1071]: https://github.com/bevyengine/bevy/pull/1071\n\n\n", "file_path": "content/news/2020-12-19-bevy-0.4/index.md", "rank": 99, "score": 32586.930842314785 } ]
Rust
tensorflow-sys/build.rs
andrewcsmith/rust-1
18db708a1893ae96dad207392bd721dcd7bc83f3
extern crate curl; extern crate flate2; extern crate pkg_config; extern crate semver; extern crate tar; use std::error::Error; use std::fs::File; use std::io::BufWriter; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use std::process::Command; use std::{env, fs}; use curl::easy::Easy; use flate2::read::GzDecoder; use semver::Version; use tar::Archive; const FRAMEWORK_LIBRARY: &'static str = "tensorflow_framework"; const LIBRARY: &'static str = "tensorflow"; const REPOSITORY: &'static str = "https://github.com/tensorflow/tensorflow.git"; const FRAMEWORK_TARGET: &'static str = "tensorflow:libtensorflow_framework.so"; const TARGET: &'static str = "tensorflow:libtensorflow.so"; const VERSION: &'static str = "1.12.0"; const TAG: &'static str = "v1.12.0"; const MIN_BAZEL: &'static str = "0.5.4"; macro_rules! get(($name:expr) => (ok!(env::var($name)))); macro_rules! ok(($expression:expr) => ($expression.unwrap())); macro_rules! log { ($fmt:expr) => (println!(concat!("libtensorflow-sys/build.rs:{}: ", $fmt), line!())); ($fmt:expr, $($arg:tt)*) => (println!(concat!("libtensorflow-sys/build.rs:{}: ", $fmt), line!(), $($arg)*)); } macro_rules! log_var(($var:ident) => (log!(concat!(stringify!($var), " = {:?}"), $var))); fn main() { if check_windows_lib() { log!("Returning early because {} was already found", LIBRARY); return; } if pkg_config::find_library(LIBRARY).is_ok() { log!("Returning early because {} was already found", LIBRARY); return; } let force_src = match env::var("TF_RUST_BUILD_FROM_SRC") { Ok(s) => s == "true", Err(_) => false, }; if !force_src && env::consts::ARCH == "x86_64" && (env::consts::OS == "linux" || env::consts::OS == "macos") { install_prebuilt(); } else { build_from_src(); } } #[cfg(not(target_env = "msvc"))] fn check_windows_lib() -> bool { false } #[cfg(target_env = "msvc")] fn check_windows_lib() -> bool { let windows_lib: &str = &format!("{}.lib", LIBRARY); if let Ok(path) = env::var("PATH") { for p in path.split(";") { let path = Path::new(p).join(windows_lib); if path.exists() { println!("cargo:rustc-link-lib=dylib={}", LIBRARY); println!("cargo:rustc-link-search=native={}", p); return true } } } false } fn remove_suffix(value: &mut String, suffix: &str) { if value.ends_with(suffix) { let n = value.len(); value.truncate(n - suffix.len()); } } fn extract<P: AsRef<Path>, P2: AsRef<Path>>(archive_path: P, extract_to: P2) { let file = File::open(archive_path).unwrap(); let unzipped = GzDecoder::new(file); let mut a = Archive::new(unzipped); a.unpack(extract_to).unwrap(); } fn install_prebuilt() { let os = match env::consts::OS { "macos" => "darwin", x => x, }; let proc_type = if cfg!(feature = "tensorflow_gpu") {"gpu"} else {"cpu"}; let binary_url = format!( "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-{}-{}-{}-{}.tar.gz", proc_type, os, env::consts::ARCH, VERSION); log_var!(binary_url); let short_file_name = binary_url.split("/").last().unwrap(); let mut base_name = short_file_name.to_string(); remove_suffix(&mut base_name, ".tar.gz"); log_var!(base_name); let download_dir = match env::var("TF_RUST_DOWNLOAD_DIR") { Ok(s) => PathBuf::from(s), Err(_) => PathBuf::from(&get!("CARGO_MANIFEST_DIR")).join("target"), }; if !download_dir.exists() { fs::create_dir(&download_dir).unwrap(); } let file_name = download_dir.join(short_file_name); log_var!(file_name); if !file_name.exists() { let f = File::create(&file_name).unwrap(); let mut writer = BufWriter::new(f); let mut easy = Easy::new(); easy.url(&binary_url).unwrap(); easy.write_function(move |data| { Ok(writer.write(data).unwrap()) }).unwrap(); easy.perform().unwrap(); let response_code = easy.response_code().unwrap(); if response_code != 200 { panic!("Unexpected response code {} for {}", response_code, binary_url); } } let unpacked_dir = download_dir.join(base_name); let lib_dir = unpacked_dir.join("lib"); let framework_library_file = format!("lib{}.so", FRAMEWORK_LIBRARY); let library_file = format!("lib{}.so", LIBRARY); let framework_library_full_path = lib_dir.join(&framework_library_file); let library_full_path = lib_dir.join(&library_file); if !framework_library_full_path.exists() || !library_full_path.exists() { extract(file_name, &unpacked_dir); } println!("cargo:rustc-link-lib=dylib={}", FRAMEWORK_LIBRARY); println!("cargo:rustc-link-lib=dylib={}", LIBRARY); let output = PathBuf::from(&get!("OUT_DIR")); let new_framework_library_full_path = output.join(&framework_library_file); if new_framework_library_full_path.exists() { log!("File {} already exists, deleting.", new_framework_library_full_path.display()); std::fs::remove_file(&new_framework_library_full_path).unwrap(); } let new_library_full_path = output.join(&library_file); if new_library_full_path.exists() { log!("File {} already exists, deleting.", new_library_full_path.display()); std::fs::remove_file(&new_library_full_path).unwrap(); } log!("Copying {} to {}...", library_full_path.display(), new_library_full_path.display()); std::fs::copy(&library_full_path, &new_library_full_path).unwrap(); log!("Copying {} to {}...", framework_library_full_path.display(), new_framework_library_full_path.display()); std::fs::copy(&framework_library_full_path, &new_framework_library_full_path).unwrap(); println!("cargo:rustc-link-search={}", output.display()); } fn build_from_src() { let output = PathBuf::from(&get!("OUT_DIR")); log_var!(output); let source = PathBuf::from(&get!("CARGO_MANIFEST_DIR")).join(format!("target/source-{}", TAG)); log_var!(source); let lib_dir = output.join(format!("lib-{}", TAG)); log_var!(lib_dir); if lib_dir.exists() { log!("Directory {:?} already exists", lib_dir); } else { log!("Creating directory {:?}", lib_dir); fs::create_dir(lib_dir.clone()).unwrap(); } let framework_library_path = lib_dir.join(format!("lib{}.so", FRAMEWORK_LIBRARY)); log_var!(framework_library_path); let library_path = lib_dir.join(format!("lib{}.so", LIBRARY)); log_var!(library_path); if library_path.exists() && framework_library_path.exists() { log!("{:?} and {:?} already exist, not building", library_path, framework_library_path); } else { if let Err(e) = check_bazel() { println!("cargo:error=Bazel must be installed at version {} or greater. (Error: {})", MIN_BAZEL, e); process::exit(1); } let framework_target_path = &FRAMEWORK_TARGET.replace(":", "/"); log_var!(framework_target_path); let target_path = &TARGET.replace(":", "/"); log_var!(target_path); if !Path::new(&source.join(".git")).exists() { run("git", |command| { command.arg("clone") .arg(format!("--branch={}", TAG)) .arg("--recursive") .arg(REPOSITORY) .arg(&source) }); } let configure_hint_file_pb = source.join(".rust-configured"); let configure_hint_file = Path::new(&configure_hint_file_pb); if !configure_hint_file.exists() { run("bash", |command| command.current_dir(&source) .env("TF_NEED_CUDA", if cfg!(feature = "tensorflow_gpu") {"1"} else {"0"}) .arg("-c") .arg("yes ''|./configure")); File::create(configure_hint_file).unwrap(); } let bazel_args_string = if let Ok(args) = env::var("TF_RUST_BAZEL_OPTS") { args } else { "".to_string() }; run("bazel", |command| { command.current_dir(&source) .arg("build") .arg(format!("--jobs={}", get!("NUM_JOBS"))) .arg("--compilation_mode=opt") .arg("--copt=-march=native") .args(bazel_args_string.split_whitespace()) .arg(TARGET) }); let framework_target_bazel_bin = source.join("bazel-bin").join(framework_target_path); log!("Copying {:?} to {:?}", framework_target_bazel_bin, framework_library_path); fs::copy(framework_target_bazel_bin, framework_library_path).unwrap(); let target_bazel_bin = source.join("bazel-bin").join(target_path); log!("Copying {:?} to {:?}", target_bazel_bin, library_path); fs::copy(target_bazel_bin, library_path).unwrap(); } println!("cargo:rustc-link-lib=dylib={}", FRAMEWORK_LIBRARY); println!("cargo:rustc-link-lib=dylib={}", LIBRARY); println!("cargo:rustc-link-search={}", lib_dir.display()); } fn run<F>(name: &str, mut configure: F) where F: FnMut(&mut Command) -> &mut Command { let mut command = Command::new(name); let configured = configure(&mut command); log!("Executing {:?}", configured); if !ok!(configured.status()).success() { panic!("failed to execute {:?}", configured); } log!("Command {:?} finished successfully", configured); } fn check_bazel() -> Result<(), Box<Error>> { let mut command = Command::new("bazel"); command.arg("version"); log!("Executing {:?}", command); let out = command.output()?; log!("Command {:?} finished successfully", command); let stdout = String::from_utf8(out.stdout)?; let mut found_version = false; for line in stdout.lines() { if line.starts_with("Build label:") { found_version = true; let mut version_str = line.split(":") .nth(1) .unwrap() .split(" ") .nth(1) .unwrap() .trim(); if version_str.ends_with('-') { version_str = &version_str[..version_str.len() - 1]; } let version = Version::parse(version_str)?; let want = Version::parse(MIN_BAZEL)?; if version < want { return Err(format!("Installed version {} is less than required version {}", version_str, MIN_BAZEL) .into()); } } } if !found_version { return Err("Did not find version number in `bazel version` output.".into()); } Ok(()) }
extern crate curl; extern crate flate2; extern crate pkg_config; extern crate semver; extern crate tar; use std::error::Error; use std::fs::File; use std::io::BufWriter; use std::io::Write; use std::path::{Path, PathBuf}; use std::process; use std::process::Command; use std::{env, fs}; use curl::easy::Easy; use flate2::read::GzDecoder; use semver::Version; use tar::Archive; const FRAMEWORK_LIBRARY: &'static str = "tensorflow_framework"; const LIBRARY: &'static str = "tensorflow"; const REPOSITORY: &'static str = "https://github.com/tensorflow/tensorflow.git"; const FRAMEWORK_TARGET: &'static str = "tensorflow:libtensorflow_framework.so"; const TARGET: &'static str = "tensorflow:libtensorflow.so"; const VERSION: &'static str = "1.12.0"; const TAG: &'static str = "v1.12.0"; const MIN_BAZEL: &'static str = "0.5.4"; macro_rules! get(($name:expr) => (ok!(env::var($name)))); macro_rules! ok(($expression:expr) => ($expression.unwrap())); macro_rules! log { ($fmt:expr) => (println!(concat!("libtensorflow-sys/build.rs:{}: ", $fmt), line!())); ($fmt:expr, $($arg:tt)*) => (println!(concat!("libtensorflow-sys/build.rs:{}: ", $fmt), line!(), $($arg)*)); } macro_rules! log_var(($var:ident) => (log!(concat!(stringify!($var), " = {:?}"), $var))); fn main() { if check_windows_lib() { log!("Returning early because {} was already found", LIBRARY); return; } if pkg_config::find_library(LIBRARY).is_ok() { log!("Returning early because {} was already found", LIBRARY); return; } let force_src = match env::var("TF_RUST_BUILD_FROM_SRC") { Ok(s) => s == "true", Err(_) => false, }; if !force_src && env::consts::ARCH == "x86_64" && (env::consts::OS == "linux" || env::consts::OS == "macos") { install_prebuilt(); } else { build_from_src(); } } #[cfg(not(target_env = "msvc"))] fn check_windows_lib() -> bool { false } #[cfg(target_env = "msvc")] fn check_windows_lib() -> bool { let windows_lib: &str = &format!("{}.lib", LIBRARY); if let Ok(path) = env::var("PATH") { for p in path.split(";") { let path = Path::new(p).join(windows_lib); if path.exists() { println!("cargo:rustc-link-lib=dylib={}", LIBRARY); println!("cargo:rustc-link-search=native={}", p); return true } } } false } fn remove_suffix(value: &mut String, suffix: &str) { if value.ends_with(suffix) { let n = value.len(); value.truncate(n - suffix.len()); } } fn extract<P: AsRef<Path>, P2: AsRef<Path>>(archive_path: P, extract_to: P2) { let file = File::open(archive_path).unwrap(); let unzipped = GzDecoder::new(file); let mut a = Archive::new(unzipped); a.unpack(extract_to).unwrap(); } fn install_prebuilt() { let os = match env::consts::OS { "macos" => "darwin", x => x, }; let proc_type = if cfg!(feature = "tensorflow_gpu") {"gpu"} else {"cpu"}; let binary_url = format!( "https://storage.googleapis.com/tensorflow/libtensorflow/libtensorflow-{}-{}-{}-{}.tar.gz", proc_type, os, env::consts::ARCH, VERSION); log_var!(binary_url); let short_file_name = binary_url.split("/").last().unwrap(); let mut base_name = short_file_name.to_string(); remove_suffix(&mut base_name, ".tar.gz"); log_var!(base_name); let download_dir = match env::var("TF_RUST_DOWNLOAD_DIR") { Ok(s) => PathBuf::from(s), Err(_) => PathBuf::from(&get!("CARGO_MANIFEST_DIR")).join("target"), }; if !download_dir.exists() { fs::create_dir(&download_dir).unwrap(); } let file_name = download_dir.join(short_file_name); log_var!(file_name); if !file_name.exists() { let f = File::create(&file_name).unwrap(); let mut writer = BufWriter::new(f); let mut easy = Easy::new(); easy.url(&binary_url).unwrap(); easy.write_function(move |data| { Ok(writer.write(data).unwrap()) }).unwrap(); easy.perform().unwrap(); let response_code = easy.response_code().unwrap(); if response_code != 200 { panic!("Unexpected response code {} for {}", response_code, binary_url); } } let unpacked_dir = download_dir.join(base_name); let lib_dir = unpacked_dir.join("lib"); let framework_library_file = format!("lib{}.so", FRAMEWORK_LIBRARY); let library_file = format!("lib{}.so", LIBRARY); let framework_library_full_path = lib_dir.join(&framework_library_file); let library_full_path = lib_dir.join(&library_file); if !framework_library_full_path.exists() || !library_full_path.exists() { extract(file_name, &unpacked_dir); } println!("cargo:rustc-link-lib=dylib={}", FRAMEWORK_LIBRARY); println!("cargo:rustc-link-lib=dylib={}", LIBRARY); let output = PathBuf::from(&get!("OUT_DIR")); let new_framework_library_full_path = output.join(&framework_library_file); if new_framework_library_full_path.exists() { log!("File {} already exists, deleting.", new_framework_library_full_path.display()); std::fs::remove_file(&new_framework_library_full_path).unwrap(); } let new_library_full_path = output.join(&library_file); if new_library_full_path.exists() { log!("File {} already exists, deleting.", new_library_full_path.display()); std::fs::remove_file(&new_library_full_path).unwrap(); } log!("Copying {} to {}...", library_full_path.display(), new_library_full_path.display()); std::fs::copy(&library_full_path, &new_library_full_path).unwrap(); log!("Copying {} to {}...", framework_library_full_path.display(), new_framework_library_full_path.display()); std::fs::copy(&framework_library_full_path, &new_framework_library_full_path).unwrap(); println!("cargo:rustc-link-search={}", output.display()); } fn build_from_src() { let output = PathBuf::from(&get!("OUT_DIR")); log_var!(output); let source = PathBuf::from(&get!("CARGO_MANIFEST_DIR")).join(format!("target/source-{}", TAG)); log_var!(source); let lib_dir = output.join(format!("lib-{}", TAG)); log_var!(lib_dir); if lib_dir.exists() { log!("Directory {:?} already exists", lib_dir); } else { log!("Creating directory {:?}", lib_dir); fs::create_dir(lib_dir.clone()).unwrap(); } let framework_library_path = lib_dir.join(format!("lib{}.so", FRAMEWORK_LIBRARY)); log_var!(framework_library_path); let library_path = lib_dir.join(format!("lib{}.so", LIBRARY)); log_var!(library_path); if library_path.exists() && framework_library_path.exists() { log!("{:?} and {:?} already exist, not building", library_path, framework_library_path); } else { if let Err(e) = check_bazel() { println!("cargo:error=Bazel must be installed at version {} or greater. (Error: {})", MIN_BAZEL, e); process::exit(1); } let framework_target_path = &FRAMEWORK_TARGET.replace(":", "/"); log_var!(framework_target_path); let target_path = &TARGET.replace(":", "/"); log_var!(target_path); if !Path::new(&source.join(".git")).exists() { run("git", |command| { command.arg("clone") .arg(format!("--branch={}", TAG)) .arg("--recursive") .arg(REPOSITORY) .arg(&source) }); } let configure_hint_file_pb = source.join(".rust-configured"); let configure_hint_file = Path::new(&configure_hint_file_pb); if !configure_hint_file.exists() { run("bash", |command| command.current_dir(&source) .env("TF_NEED_CUDA", if cfg!(feature = "tensorflow_gpu") {"1"} else {"0"}) .arg("-c") .arg("yes ''|./configure")); File::create(configure_hint_file).unwrap(); } let bazel_args_string = if let Ok(args) = env::var("TF_RUST_BAZEL_OPTS") { args } else { "".to_string() }; run("bazel", |command| { command.current_dir(&source) .arg("build") .arg(format!("--jobs={}", get!("NUM_JOBS"))) .arg("--compilation_mode=opt") .arg("--copt=-march=native") .args(bazel_args_string.split_whitespace()) .arg(TARGET) }); let framework_target_bazel_bin = source.join("bazel-bin").join(framework_target_path); log!("Copying {:?} to {:?}", framework_target_bazel_bin, framework_library_path); fs::copy(framework_target_bazel_bin, framework_library_path).unwrap(); let target_bazel_bin = source.join("bazel-bin").join(target_path); log!("Copying {:?} to {:?}", target_bazel_bin, library_path); fs::copy(target_bazel_bin, library_path).unwrap(); } println!("cargo:rustc-link-lib=dylib={}", FRAMEWORK_LIBRARY); println!("cargo:rustc-link-lib=dylib={}", LIBRARY); println!("cargo:rustc-link-search={}", lib_dir.display()); } fn run<F>(name: &str, mut configure: F) where F: FnMut(&mut Command) -> &mut Command { let mut command = Command::new(name); let configured = configure(&mut command); log!("Executing {:?}", configured); if !ok!(configured.status()).success() { panic!("failed to execute {:?}", configured); } log!("Command {:?} finished successfully", configured); } fn check_bazel() -> Result<(), Box<Error>> { let mut command = Command::new("bazel"); command.arg("version"); log!("Executing {:?}", command); let out = command.output()?; log!("Command {:?} finished successfully", command); let stdout = String::from_utf8(out.stdout)?; let mut found_version = false; for line in stdout.lines() { if line.starts_with("Build label:") { found_version = true; let mut version_str = line.split(":") .nth(1) .unwrap() .split(" ") .nth(1) .unwrap() .trim(); if version_str.ends_with('-') { version_str = &version_str[..version_str.len() - 1]; } let version = Version::parse(version_str)?; let want = Version::parse(MIN_BAZEL)?; if vers
ion < want { return Err(format!("Installed version {} is less than required version {}", version_str, MIN_BAZEL) .into()); } } } if !found_version { return Err("Did not find version number in `bazel version` output.".into()); } Ok(()) }
function_block-function_prefixed
[ { "content": "fn log_env_var(log: &mut Write, var: &str) -> Result<(), io::Error> {\n\n match env::var(var) {\n\n Ok(s) => writeln!(log, \"{}={}\", var, s),\n\n Err(env::VarError::NotPresent) => writeln!(log, \"{} is not present\", var),\n\n Err(env::VarError::NotUnicode(_)) => writeln!(log, \"{} is not unicode\", var),\n\n }\n\n}\n\n\n", "file_path": "libtensorflow-sys/build.rs", "rank": 0, "score": 250596.84133942678 }, { "content": "/// Returns a string describing version information of the\n\n/// `TensorFlow` library. `TensorFlow` is using semantic versioning.\n\npub fn version() -> std::result::Result<String, Utf8Error> {\n\n unsafe { CStr::from_ptr(tf::TF_Version()).to_str().map(|s| s.to_string()) }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 5, "score": 177744.22487721726 }, { "content": "fn find_header(name: &str) -> Option<PathBuf> {\n\n let cpath_str = match env::var(\"CPATH\") {\n\n Ok(s) => s,\n\n Err(_) => \"\".to_string(),\n\n } + \":/usr/include:/usr/local/include\";\n\n for s in cpath_str.split(\":\") {\n\n if s != \"\" {\n\n let full = Path::new(s).join(name);\n\n let exists = match fs::metadata(&full) {\n\n Ok(m) => m.is_file(),\n\n Err(_) => false,\n\n };\n\n if exists {\n\n return Some(full);\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "libtensorflow-sys/build.rs", "rank": 10, "score": 131164.80360767432 }, { "content": "fn main() {\n\n let out_dir_str = env::var(\"OUT_DIR\").unwrap();\n\n let out_dir = Path::new(&out_dir_str);\n\n let dest_path = out_dir.join(\"ffi.rs\");\n\n let log_path = out_dir.join(\"build.log\");\n\n\n\n let mut log = match File::create(&log_path) {\n\n Ok(f) => f,\n\n Err(_) => panic!(format!(\"Unable to open file {}\", log_path.to_str().unwrap())),\n\n };\n\n\n\n let mut bindings = bindgen::builder();\n\n bindings.forbid_unknown_types();\n\n\n\n log_env_var(&mut log, \"CPATH\").unwrap();\n\n let tf_header = match find_header(\"tensor_c_api.h\") {\n\n Some(p) => p,\n\n None => panic!(\"Unable to find tensor_c_api.h\"),\n\n };\n\n\n", "file_path": "libtensorflow-sys/build.rs", "rank": 11, "score": 128785.28405893306 }, { "content": "fn run() -> Result<(), Box<Error>> {\n\n let filename = \"examples/addition/model.pb\"; // z = x + y\n\n if !Path::new(filename).exists() {\n\n return Err(Box::new(Status::new_set(Code::NotFound,\n\n &format!(\"Run 'python addition.py' to generate {} \\\n\n and try again.\",\n\n filename))\n\n .unwrap()));\n\n }\n\n\n\n // Create input variables for our addition\n\n let mut x = Tensor::new(&[1]);\n\n x[0] = 2i32;\n\n let mut y = Tensor::new(&[1]);\n\n y[0] = 40i32;\n\n\n\n // Load the computation graph defined by regression.py.\n\n let mut graph = Graph::new();\n\n let mut proto = Vec::new();\n\n File::open(filename)?.read_to_end(&mut proto)?;\n", "file_path": "examples/addition.rs", "rank": 12, "score": 127501.64525018992 }, { "content": "fn run() -> Result<(), Box<Error>> {\n\n let filename = \"examples/regression/model.pb\"; // y = w * x + b\n\n if !Path::new(filename).exists() {\n\n return Err(Box::new(Status::new_set(Code::NotFound,\n\n &format!(\"Run 'python regression.py' to generate \\\n\n {} and try again.\",\n\n filename))\n\n .unwrap()));\n\n }\n\n\n\n // Generate some test data.\n\n let w = 0.1;\n\n let b = 0.3;\n\n let num_points = 100;\n\n let steps = 201;\n\n let mut rand = random::default();\n\n let mut x = Tensor::new(&[num_points as u64]);\n\n let mut y = Tensor::new(&[num_points as u64]);\n\n for i in 0..num_points {\n\n x[i] = (2.0 * rand.read::<f64>() - 1.0) as f32;\n", "file_path": "examples/regression.rs", "rank": 13, "score": 127501.64525018992 }, { "content": "fn run() -> Result<(), Box<Error>> {\n\n // Build the graph\n\n let mut g = Graph::new();\n\n let y_node = {\n\n let mut compiler = Compiler::new(&mut g);\n\n let x_expr = <Placeholder<f32>>::new_expr(&vec![2], \"x\");\n\n compiler.compile(x_expr * 2.0f32 + 1.0f32)?\n\n };\n\n let x_node = g.operation_by_name_required(\"x\")?;\n\n // This is another valid way to get x_node and y_node:\n\n // let (x_node, y_node) = {\n\n // let mut compiler = Compiler::new(&mut g);\n\n // let x_expr = <Placeholder<f32>>::new_expr(&vec![2], \"x\");\n\n // let x_node = compiler.compile(x_expr.clone())?;\n\n // let y_node = compiler.compile(x_expr * 2.0f32 + 1.0f32)?;\n\n // (x_node, y_node)\n\n // };\n\n let options = SessionOptions::new();\n\n let mut session = Session::new(&options, &g)?;\n\n\n", "file_path": "examples/expressions.rs", "rank": 14, "score": 127501.64525018992 }, { "content": "fn run() -> Result<(), Box<Error>> {\n\n let export_dir = \"examples/regression_savedmodel\"; // y = w * x + b\n\n if !Path::new(export_dir).exists() {\n\n return Err(Box::new(Status::new_set(Code::NotFound,\n\n &format!(\"Run 'python regression_savedmodel.py' to generate \\\n\n {} and try again.\",\n\n export_dir))\n\n .unwrap()));\n\n }\n\n\n\n // Generate some test data.\n\n let w = 0.1;\n\n let b = 0.3;\n\n let num_points = 100;\n\n let steps = 201;\n\n let mut rand = random::default();\n\n let mut x = Tensor::new(&[num_points as u64]);\n\n let mut y = Tensor::new(&[num_points as u64]);\n\n for i in 0..num_points {\n\n x[i] = (2.0 * rand.read::<f64>() - 1.0) as f32;\n", "file_path": "examples/regression_savedmodel.rs", "rank": 15, "score": 123350.9306505516 }, { "content": "fn run() -> Result<(), Box<Error>> {\n\n let filename = \"examples/regression_checkpoint/model.pb\"; // y = w * x + b\n\n if !Path::new(filename).exists() {\n\n return Err(Box::new(Status::new_set(Code::NotFound,\n\n &format!(\"Run 'python regression_checkpoint.py' to generate \\\n\n {} and try again.\",\n\n filename))\n\n .unwrap()));\n\n }\n\n\n\n // Generate some test data.\n\n let w = 0.1;\n\n let b = 0.3;\n\n let num_points = 100;\n\n let steps = 201;\n\n let mut rand = random::default();\n\n let mut x = Tensor::new(&[num_points as u64]);\n\n let mut y = Tensor::new(&[num_points as u64]);\n\n for i in 0..num_points {\n\n x[i] = (2.0 * rand.read::<f64>() - 1.0) as f32;\n", "file_path": "examples/regression_checkpoint.rs", "rank": 16, "score": 123350.9306505516 }, { "content": "fn main() {\n\n use std::mem::size_of;\n\n use std::ptr::{null, null_mut};\n\n use std::slice::from_raw_parts;\n\n\n\n unsafe {\n\n let options = nonnull!(ffi::TF_NewSessionOptions());\n\n let status = nonnull!(ffi::TF_NewStatus());\n\n let graph = nonnull!(ffi::TF_NewGraph());\n\n\n\n let graph_def = read(\"examples/assets/multiplication.pb\"); // c = a * b\n\n let opts = nonnull!(ffi::TF_NewImportGraphDefOptions());\n\n let graph_def_buf = ffi::TF_Buffer{\n\n data: graph_def.as_ptr() as *const c_void,\n\n length: graph_def.len(),\n\n data_deallocator: None,\n\n };\n\n ffi::TF_GraphImportGraphDef(graph,\n\n &graph_def_buf,\n\n opts,\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 17, "score": 122641.0831336884 }, { "content": "fn write_tensor_recursive<T: Display>(f: &mut Formatter, shape: &[u64], values: &[T]) -> ::std::fmt::Result {\n\n if shape.len() == 0 {\n\n // Handle special case of a scalar tensor.\n\n write!(f, \"{}\", values[0])\n\n } else {\n\n // Recur with values split into chunks of the next dims size,\n\n // Surround with brackets and separate with comma.\n\n write!(f, \"[\")?;\n\n\n\n if shape[0] > 0 {\n\n let chunk_size = values.len() / shape[0] as usize;\n\n\n\n for i in 0..shape[0] as usize {\n\n if i != 0 {\n\n write!(f, \", \")?;\n\n }\n\n\n\n write_tensor_recursive(f, &shape[1..], &values[i*chunk_size..(i+1)*chunk_size])?;\n\n }\n\n }\n", "file_path": "src/lib.rs", "rank": 18, "score": 117697.38969647906 }, { "content": "fn main() {\n\n // Putting the main code in another function serves two purposes:\n\n // 1. We can use the `?` operator.\n\n // 2. We can call exit safely, which does not run any destructors.\n\n exit(match run() {\n\n Ok(_) => 0,\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/regression.rs", "rank": 19, "score": 104273.39760469421 }, { "content": "fn main() {\n\n // Putting the main code in another function serves two purposes:\n\n // 1. We can use the `?` operator.\n\n // 2. We can call exit safely, which does not run any destructors.\n\n exit(match run() {\n\n Ok(_) => 0,\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/addition.rs", "rank": 20, "score": 104273.39760469421 }, { "content": "fn main() {\n\n // Putting the main code in another function serves two purposes:\n\n // 1. We can use the `?` operator.\n\n // 2. We can call exit safely, which does not run any destructors.\n\n exit(match run() {\n\n Ok(_) => 0,\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/expressions.rs", "rank": 21, "score": 104273.39760469421 }, { "content": "fn main() {\n\n // Putting the main code in another function serves two purposes:\n\n // 1. We can use the `?` operator.\n\n // 2. We can call exit safely, which does not run any destructors.\n\n exit(match run() {\n\n Ok(_) => 0,\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/regression_checkpoint.rs", "rank": 22, "score": 100270.09210347646 }, { "content": "fn main() {\n\n // Putting the main code in another function serves two purposes:\n\n // 1. We can use the `?` operator.\n\n // 2. We can call exit safely, which does not run any destructors.\n\n exit(match run() {\n\n Ok(_) => 0,\n\n Err(e) => {\n\n println!(\"{}\", e);\n\n 1\n\n }\n\n })\n\n}\n\n\n", "file_path": "examples/regression_savedmodel.rs", "rank": 23, "score": 100270.09210347646 }, { "content": "/// Returns a serialized KernelList protocol buffer containing KernelDefs for\n\n/// all kernels registered for the operation named `name`.\n\npub fn get_registered_kernels_for_op(name: &str) -> Result<Vec<u8>> {\n\n let c_name = CString::new(name)?;\n\n let mut status = Status::new();\n\n let buf = unsafe {\n\n let buf = tf::TF_GetRegisteredKernelsForOp(c_name.as_ptr(), status.inner());\n\n if !status.is_ok() {\n\n return Err(status);\n\n }\n\n Buffer::<u8>::from_c(buf, true)\n\n };\n\n Ok(Vec::from(buf.as_ref()))\n\n}\n\n\n\n////////////////////////\n\n\n\n/// A Shape is the shape of a tensor. A Shape may be an unknown rank, or it may\n\n/// have a known rank with each dimension being known or unknown.\n\n#[derive(Debug,Eq,Ord,PartialEq,PartialOrd,Hash,Clone)]\n\npub struct Shape(Option<Vec<Option<i64>>>);\n\n\n", "file_path": "src/lib.rs", "rank": 24, "score": 98489.39346331952 }, { "content": "fn read<T: AsRef<Path>>(path: T) -> Vec<u8> {\n\n use std::fs::File;\n\n use std::io::Read;\n\n\n\n let mut buffer = vec![];\n\n let mut file = File::open(path).unwrap();\n\n file.read_to_end(&mut buffer).unwrap();\n\n buffer\n\n}\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 25, "score": 98350.02707447088 }, { "content": "#[test]\n\nfn bindgen_test_layout_TF_Output() {\n\n assert_eq!(::std::mem::size_of::<TF_Output>() , 16usize , concat ! (\n\n \"Size of: \" , stringify ! ( TF_Output ) ));\n\n assert_eq! (::std::mem::align_of::<TF_Output>() , 8usize , concat ! (\n\n \"Alignment of \" , stringify ! ( TF_Output ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Output ) ) . oper as * const _ as\n\n usize } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Output ) , \"::\" ,\n\n stringify ! ( oper ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Output ) ) . index as * const _ as\n\n usize } , 8usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Output ) , \"::\" ,\n\n stringify ! ( index ) ));\n\n}\n\nimpl Clone for TF_Output {\n\n fn clone(&self) -> Self { *self }\n\n}\n\n#[repr(C)]\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 26, "score": 82861.74798002884 }, { "content": "/// Returns a serialized KernelList protocol buffer containing KernelDefs for\n\n/// all registered kernels.\n\npub fn get_all_registered_kernels() -> Result<Vec<u8>> {\n\n let mut status = Status::new();\n\n let buf = unsafe {\n\n let buf = tf::TF_GetAllRegisteredKernels(status.inner());\n\n if !status.is_ok() {\n\n return Err(status);\n\n }\n\n Buffer::<u8>::from_c(buf, true)\n\n };\n\n Ok(Vec::from(buf.as_ref()))\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 27, "score": 73636.68060288746 }, { "content": "#[test]\n\nfn linkage() {\n\n unsafe {\n\n let buffer = ffi::TF_NewBuffer();\n\n assert!(!buffer.is_null());\n\n ffi::TF_DeleteBuffer(buffer);\n\n }\n\n}\n", "file_path": "tensorflow-sys/tests/lib.rs", "rank": 28, "score": 71590.83691628964 }, { "content": "#[test]\n\nfn bindgen_test_layout___fsid_t() {\n\n assert_eq!(::std::mem::size_of::<__fsid_t>() , 8usize , concat ! (\n\n \"Size of: \" , stringify ! ( __fsid_t ) ));\n\n assert_eq! (::std::mem::align_of::<__fsid_t>() , 4usize , concat ! (\n\n \"Alignment of \" , stringify ! ( __fsid_t ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const __fsid_t ) ) . __val as * const _ as\n\n usize } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( __fsid_t ) , \"::\" ,\n\n stringify ! ( __val ) ));\n\n}\n\nimpl Clone for __fsid_t {\n\n fn clone(&self) -> Self { *self }\n\n}\n\npub type __clock_t = ::std::os::raw::c_long;\n\npub type __rlim_t = ::std::os::raw::c_ulong;\n\npub type __rlim64_t = ::std::os::raw::c_ulong;\n\npub type __id_t = ::std::os::raw::c_uint;\n\npub type __time_t = ::std::os::raw::c_long;\n\npub type __useconds_t = ::std::os::raw::c_uint;\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 29, "score": 63406.83602999263 }, { "content": "#[test]\n\nfn bindgen_test_layout_TF_WhileParams() {\n\n assert_eq!(::std::mem::size_of::<TF_WhileParams>() , 72usize , concat ! (\n\n \"Size of: \" , stringify ! ( TF_WhileParams ) ));\n\n assert_eq! (::std::mem::align_of::<TF_WhileParams>() , 8usize , concat ! (\n\n \"Alignment of \" , stringify ! ( TF_WhileParams ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_WhileParams ) ) . ninputs as * const _\n\n as usize } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_WhileParams ) , \"::\"\n\n , stringify ! ( ninputs ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_WhileParams ) ) . cond_graph as *\n\n const _ as usize } , 8usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_WhileParams ) , \"::\"\n\n , stringify ! ( cond_graph ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_WhileParams ) ) . cond_inputs as *\n\n const _ as usize } , 16usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_WhileParams ) , \"::\"\n\n , stringify ! ( cond_inputs ) ));\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 30, "score": 61217.70155320702 }, { "content": "#[test]\n\nfn bindgen_test_layout_TF_Input() {\n\n assert_eq!(::std::mem::size_of::<TF_Input>() , 16usize , concat ! (\n\n \"Size of: \" , stringify ! ( TF_Input ) ));\n\n assert_eq! (::std::mem::align_of::<TF_Input>() , 8usize , concat ! (\n\n \"Alignment of \" , stringify ! ( TF_Input ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Input ) ) . oper as * const _ as usize\n\n } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Input ) , \"::\" ,\n\n stringify ! ( oper ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Input ) ) . index as * const _ as\n\n usize } , 8usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Input ) , \"::\" ,\n\n stringify ! ( index ) ));\n\n}\n\nimpl Clone for TF_Input {\n\n fn clone(&self) -> Self { *self }\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy)]\n\npub struct TF_Output {\n\n pub oper: *mut TF_Operation,\n\n pub index: ::std::os::raw::c_int,\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 31, "score": 61217.70155320702 }, { "content": "#[test]\n\nfn bindgen_test_layout_TF_Buffer() {\n\n assert_eq!(::std::mem::size_of::<TF_Buffer>() , 24usize , concat ! (\n\n \"Size of: \" , stringify ! ( TF_Buffer ) ));\n\n assert_eq! (::std::mem::align_of::<TF_Buffer>() , 8usize , concat ! (\n\n \"Alignment of \" , stringify ! ( TF_Buffer ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Buffer ) ) . data as * const _ as\n\n usize } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Buffer ) , \"::\" ,\n\n stringify ! ( data ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Buffer ) ) . length as * const _ as\n\n usize } , 8usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Buffer ) , \"::\" ,\n\n stringify ! ( length ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_Buffer ) ) . data_deallocator as *\n\n const _ as usize } , 16usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_Buffer ) , \"::\" ,\n\n stringify ! ( data_deallocator ) ));\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 32, "score": 61217.70155320702 }, { "content": "#[test]\n\nfn bindgen_test_layout_TF_AttrMetadata() {\n\n assert_eq!(::std::mem::size_of::<TF_AttrMetadata>() , 32usize , concat ! (\n\n \"Size of: \" , stringify ! ( TF_AttrMetadata ) ));\n\n assert_eq! (::std::mem::align_of::<TF_AttrMetadata>() , 8usize , concat !\n\n ( \"Alignment of \" , stringify ! ( TF_AttrMetadata ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_AttrMetadata ) ) . is_list as * const\n\n _ as usize } , 0usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_AttrMetadata ) ,\n\n \"::\" , stringify ! ( is_list ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_AttrMetadata ) ) . list_size as *\n\n const _ as usize } , 8usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_AttrMetadata ) ,\n\n \"::\" , stringify ! ( list_size ) ));\n\n assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_AttrMetadata ) ) . type_ as * const _\n\n as usize } , 16usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_AttrMetadata ) ,\n\n \"::\" , stringify ! ( type_ ) ));\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 42, "score": 59234.60383187793 }, { "content": "import os\n\nimport tensorflow as tf\n\n\n\na = tf.placeholder(tf.float32, name='a')\n\nb = tf.placeholder(tf.float32, name='b')\n\nc = tf.mul(a, b, name='c')\n\n\n\ndefinition = tf.Session().graph_def\n\ndirectory = os.path.dirname(os.path.realpath(__file__))\n\ntf.train.write_graph(definition, directory, 'multiplication.pb', as_text=False)\n", "file_path": "tensorflow-sys/examples/assets/multiplication.py", "rank": 43, "score": 51021.0646817088 }, { "content": "#[inline]\n\nfn product(values: &[u64]) -> u64 {\n\n values.iter().product()\n\n}\n\n\n\nimpl<T: TensorType> Tensor<T> {\n\n /// Creates a new tensor.\n\n ///\n\n /// The data is initialized to zeros.\n\n pub fn new(dims: &[u64]) -> Self {\n\n Tensor {\n\n inner: T::InnerType::new_inner(dims),\n\n dims: Vec::from(dims),\n\n }\n\n }\n\n\n\n /// Sets (copies) the tensor values to the provided ones.\n\n ///\n\n /// ```\n\n /// # use tensorflow::Tensor;\n\n /// let a = Tensor::new(&[2, 2]).with_values(&[0_i32, 1, 2, 3]).unwrap();\n", "file_path": "src/lib.rs", "rank": 44, "score": 39799.62860434973 }, { "content": "import tensorflow as tf\n\n\n\nactual = \"test_resources/io/expected.tfrecord\"\n\nwriter = tf.python_io.TFRecordWriter(golden)\n\n\n\nwriter.write(\"The Quick Brown Fox\".encode(\"utf-8\"))\n", "file_path": "test_resources/io/python_writer.py", "rank": 45, "score": 39087.22654819919 }, { "content": "/// A Rust type that maps to a `DataType`.\n\n///\n\n/// Currently, all implementors must *not* implement Drop (or transitively contain\n\n/// anything that does) and must be bit-for-bit compatible with the corresponding C\n\n/// type. Clients must not implement this trait.\n\n///\n\n/// This trait doesn't require `num::Zero` or `num::One` because some tensor\n\n/// types (such as `bool` and `String`) don't implement them and we need to\n\n/// supply custom implementations.\n\npub trait TensorType: Default + Clone + Display + Debug + 'static {\n\n /// Tensor representation for this type. Normally `TensorDataCRepr` for types\n\n /// that have the same representation in Rust; or `TensorDataNoCRepr` for\n\n /// types where the Rust and C representations differ.\n\n #[doc(hidden)]\n\n type InnerType: TensorInner<Self>;\n\n \n\n /// Returns the DataType that corresponds to this type.\n\n fn data_type() -> DataType;\n\n\n\n /// Returns the zero value.\n\n fn zero() -> Self;\n\n\n\n /// Returns the one value.\n\n fn one() -> Self;\n\n\n\n /// Return true if the data has the same representation in C and Rust and\n\n /// can be written/read directly.\n\n fn is_repr_c() -> bool;\n\n\n", "file_path": "src/lib.rs", "rank": 46, "score": 36314.91849902697 }, { "content": "extern crate bindgen;\n\n\n\nuse std::env;\n\nuse std::fs;\n\nuse std::fs::File;\n\nuse std::io;\n\nuse std::io::Write;\n\nuse std::path::Path;\n\nuse std::path::PathBuf;\n\nuse std::result::Result;\n\n\n", "file_path": "libtensorflow-sys/build.rs", "rank": 47, "score": 30541.360699927394 }, { "content": " bindings.link(\"tensorflow\");\n\n bindings.match_pat(\"tensor_c_api.h\");\n\n bindings.header(tf_header.to_str().unwrap());\n\n\n\n let bindings = bindings.generate();\n\n let bindings = bindings.unwrap();\n\n bindings.write_to_file(&dest_path).unwrap();\n\n\n\n println!(\"cargo:include={}\", dest_path.to_str().unwrap());\n\n}\n", "file_path": "libtensorflow-sys/build.rs", "rank": 48, "score": 30536.303843517802 }, { "content": "extern crate libc;\n\nextern crate tensorflow_sys as ffi;\n\n\n\nuse libc::{c_int, int64_t, size_t};\n\nuse std::alloc::System;\n\nuse std::ffi::{CStr, CString};\n\nuse std::mem;\n\nuse std::path::Path;\n\nuse std::os::raw::c_void;\n\n\n\nmacro_rules! nonnull(\n\n ($pointer:expr) => ({\n\n let pointer = $pointer;\n\n assert!(!pointer.is_null());\n\n pointer\n\n });\n\n);\n\n\n\nmacro_rules! ok(\n\n ($status:expr) => ({\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 49, "score": 27603.50306585248 }, { "content": " *const ::std::os::raw::c_char);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefOptionsNumReturnOperations(opts:\n\n *const TF_ImportGraphDefOptions)\n\n -> ::std::os::raw::c_int;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_ImportGraphDefResults {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefResultsReturnOutputs(results:\n\n *mut TF_ImportGraphDefResults,\n\n num_outputs:\n\n *mut ::std::os::raw::c_int,\n\n outputs:\n\n *mut *mut TF_Output);\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 50, "score": 27598.352926997413 }, { "content": "extern \"C\" {\n\n pub fn TF_NewStatus() -> *mut TF_Status;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteStatus(arg1: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetStatus(s: *mut TF_Status, code: TF_Code,\n\n msg: *const ::std::os::raw::c_char);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GetCode(s: *const TF_Status) -> TF_Code;\n\n}\n\nextern \"C\" {\n\n pub fn TF_Message(s: *const TF_Status) -> *const ::std::os::raw::c_char;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy)]\n\npub struct TF_Buffer {\n\n pub data: *const ::std::os::raw::c_void,\n\n pub length: usize,\n\n pub data_deallocator: ::std::option::Option<unsafe extern \"C\" fn(data:\n\n *mut ::std::os::raw::c_void,\n\n length:\n\n usize)>,\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 51, "score": 27597.169805131925 }, { "content": " noutputs: ::std::os::raw::c_int,\n\n target_opers: *const *const TF_Operation,\n\n ntargets: ::std::os::raw::c_int,\n\n handle: *mut *const ::std::os::raw::c_char,\n\n arg2: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SessionPRun(arg1: *mut TF_Session,\n\n handle: *const ::std::os::raw::c_char,\n\n inputs: *const TF_Output,\n\n input_values: *const *const TF_Tensor,\n\n ninputs: ::std::os::raw::c_int,\n\n outputs: *const TF_Output,\n\n output_values: *mut *mut TF_Tensor,\n\n noutputs: ::std::os::raw::c_int,\n\n target_opers: *const *const TF_Operation,\n\n ntargets: ::std::os::raw::c_int,\n\n arg2: *mut TF_Status);\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 52, "score": 27596.992865451546 }, { "content": " pub fn TF_DeleteSession(arg1: *mut TF_Session, status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SessionRun(session: *mut TF_Session,\n\n run_options: *const TF_Buffer,\n\n inputs: *const TF_Output,\n\n input_values: *const *const TF_Tensor,\n\n ninputs: ::std::os::raw::c_int,\n\n outputs: *const TF_Output,\n\n output_values: *mut *mut TF_Tensor,\n\n noutputs: ::std::os::raw::c_int,\n\n target_opers: *const *const TF_Operation,\n\n ntargets: ::std::os::raw::c_int,\n\n run_metadata: *mut TF_Buffer, arg1: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SessionPRunSetup(arg1: *mut TF_Session,\n\n inputs: *const TF_Output,\n\n ninputs: ::std::os::raw::c_int,\n\n outputs: *const TF_Output,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 53, "score": 27596.939706070803 }, { "content": "extern \"C\" {\n\n pub fn TF_ImportGraphDefResultsReturnOperations(results:\n\n *mut TF_ImportGraphDefResults,\n\n num_opers:\n\n *mut ::std::os::raw::c_int,\n\n opers:\n\n *mut *mut *mut TF_Operation);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefResultsMissingUnusedInputMappings(results:\n\n *mut TF_ImportGraphDefResults,\n\n num_missing_unused_input_mappings:\n\n *mut ::std::os::raw::c_int,\n\n src_names:\n\n *mut *mut *const ::std::os::raw::c_char,\n\n src_indexes:\n\n *mut *mut ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteImportGraphDefResults(results:\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 54, "score": 27596.899848239154 }, { "content": " pub fn TF_OperationNumOutputs(oper: *mut TF_Operation)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationOutputType(oper_out: TF_Output) -> TF_DataType;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationOutputListLength(oper: *mut TF_Operation,\n\n arg_name:\n\n *const ::std::os::raw::c_char,\n\n status: *mut TF_Status)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationNumInputs(oper: *mut TF_Operation)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationInputType(oper_in: TF_Input) -> TF_DataType;\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 55, "score": 27596.789694365918 }, { "content": " *mut TF_ImportGraphDefResults);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphImportGraphDefWithResults(graph: *mut TF_Graph,\n\n graph_def: *const TF_Buffer,\n\n options:\n\n *const TF_ImportGraphDefOptions,\n\n status: *mut TF_Status)\n\n -> *mut TF_ImportGraphDefResults;\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphImportGraphDefWithReturnOutputs(graph: *mut TF_Graph,\n\n graph_def:\n\n *const TF_Buffer,\n\n options:\n\n *const TF_ImportGraphDefOptions,\n\n return_outputs:\n\n *mut TF_Output,\n\n num_return_outputs:\n\n ::std::os::raw::c_int,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 56, "score": 27596.256119602505 }, { "content": " _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewTensor(arg1: TF_DataType, dims: *const i64,\n\n num_dims: ::std::os::raw::c_int,\n\n data: *mut ::std::os::raw::c_void, len: usize,\n\n deallocator:\n\n ::std::option::Option<unsafe extern \"C\" fn(data:\n\n *mut ::std::os::raw::c_void,\n\n len:\n\n usize,\n\n arg:\n\n *mut ::std::os::raw::c_void)>,\n\n deallocator_arg: *mut ::std::os::raw::c_void)\n\n -> *mut TF_Tensor;\n\n}\n\nextern \"C\" {\n\n pub fn TF_AllocateTensor(arg1: TF_DataType, dims: *const i64,\n\n num_dims: ::std::os::raw::c_int, len: usize)\n\n -> *mut TF_Tensor;\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 57, "score": 27595.65385727104 }, { "content": " *const ::std::os::raw::c_char,\n\n output_attr_value: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteFunction(func: *mut TF_Function);\n\n}\n\nextern \"C\" {\n\n pub fn TF_TryEvaluateConstant(graph: *mut TF_Graph, output: TF_Output,\n\n result: *mut *mut TF_Tensor,\n\n status: *mut TF_Status)\n\n -> ::std::os::raw::c_uchar;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_Session {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewSession(graph: *mut TF_Graph, opts: *const TF_SessionOptions,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 58, "score": 27595.177400985074 }, { "content": " inputs.as_mut_ptr(),\n\n input_tensors.as_ptr(),\n\n inputs.len() as c_int,\n\n outputs.as_mut_ptr(),\n\n output_tensors.as_mut_ptr(),\n\n outputs.len() as c_int,\n\n target_names.as_mut_ptr(),\n\n target_names.len() as c_int,\n\n null_mut(),\n\n status);\n\n ok!(status);\n\n\n\n let tensor = nonnull!(output_tensors[0]);\n\n let data = nonnull!(ffi::TF_TensorData(tensor)) as *const f32;\n\n let data = from_raw_parts(data, ffi::TF_TensorByteSize(tensor) / size_of::<f32>());\n\n\n\n assert_eq!(data, &[1.0 * 4.0, 2.0 * 5.0, 3.0 * 6.0]);\n\n\n\n ffi::TF_CloseSession(session, status);\n\n\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 59, "score": 27594.876235999716 }, { "content": "extern \"C\" {\n\n pub fn TF_OperationInputListLength(oper: *mut TF_Operation,\n\n arg_name:\n\n *const ::std::os::raw::c_char,\n\n status: *mut TF_Status)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationInput(oper_in: TF_Input) -> TF_Output;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationOutputNumConsumers(oper_out: TF_Output)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationOutputConsumers(oper_out: TF_Output,\n\n consumers: *mut TF_Input,\n\n max_consumers: ::std::os::raw::c_int)\n\n -> ::std::os::raw::c_int;\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 60, "score": 27594.774294670697 }, { "content": " ntargets: ::std::os::raw::c_int,\n\n run_metadata: *mut TF_Buffer, arg2: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_PRunSetup(arg1: *mut TF_DeprecatedSession,\n\n input_names: *mut *const ::std::os::raw::c_char,\n\n ninputs: ::std::os::raw::c_int,\n\n output_names: *mut *const ::std::os::raw::c_char,\n\n noutputs: ::std::os::raw::c_int,\n\n target_oper_names: *mut *const ::std::os::raw::c_char,\n\n ntargets: ::std::os::raw::c_int,\n\n handle: *mut *const ::std::os::raw::c_char,\n\n arg2: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_PRun(arg1: *mut TF_DeprecatedSession,\n\n handle: *const ::std::os::raw::c_char,\n\n input_names: *mut *const ::std::os::raw::c_char,\n\n inputs: *mut *mut TF_Tensor,\n\n ninputs: ::std::os::raw::c_int,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 61, "score": 27594.536606689297 }, { "content": "extern \"C\" {\n\n pub fn TF_TensorData(arg1: *const TF_Tensor)\n\n -> *mut ::std::os::raw::c_void;\n\n}\n\nextern \"C\" {\n\n pub fn TF_StringEncode(src: *const ::std::os::raw::c_char, src_len: usize,\n\n dst: *mut ::std::os::raw::c_char, dst_len: usize,\n\n status: *mut TF_Status) -> usize;\n\n}\n\nextern \"C\" {\n\n pub fn TF_StringDecode(src: *const ::std::os::raw::c_char, src_len: usize,\n\n dst: *mut *const ::std::os::raw::c_char,\n\n dst_len: *mut usize, status: *mut TF_Status)\n\n -> usize;\n\n}\n\nextern \"C\" {\n\n pub fn TF_StringEncodedSize(len: usize) -> usize;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 62, "score": 27594.082912507038 }, { "content": " oper:\n\n *mut TF_Operation);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefOptionsAddReturnOutput(opts:\n\n *mut TF_ImportGraphDefOptions,\n\n oper_name:\n\n *const ::std::os::raw::c_char,\n\n index:\n\n ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefOptionsNumReturnOutputs(opts:\n\n *const TF_ImportGraphDefOptions)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_ImportGraphDefOptionsAddReturnOperation(opts:\n\n *mut TF_ImportGraphDefOptions,\n\n oper_name:\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 63, "score": 27594.079304226085 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_AddGradients(g: *mut TF_Graph, y: *mut TF_Output,\n\n ny: ::std::os::raw::c_int, x: *mut TF_Output,\n\n nx: ::std::os::raw::c_int, dx: *mut TF_Output,\n\n status: *mut TF_Status, dy: *mut TF_Output);\n\n}\n\nextern \"C\" {\n\n pub fn TF_AddGradientsWithPrefix(g: *mut TF_Graph,\n\n prefix: *const ::std::os::raw::c_char,\n\n y: *mut TF_Output,\n\n ny: ::std::os::raw::c_int,\n\n x: *mut TF_Output,\n\n nx: ::std::os::raw::c_int,\n\n dx: *mut TF_Output,\n\n status: *mut TF_Status,\n\n dy: *mut TF_Output);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphToFunction(fn_body: *const TF_Graph,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 64, "score": 27593.931626328464 }, { "content": " fn_name: *const ::std::os::raw::c_char,\n\n append_hash_to_fn_name: ::std::os::raw::c_uchar,\n\n num_opers: ::std::os::raw::c_int,\n\n opers: *const *const TF_Operation,\n\n ninputs: ::std::os::raw::c_int,\n\n inputs: *const TF_Output,\n\n noutputs: ::std::os::raw::c_int,\n\n outputs: *const TF_Output,\n\n output_names:\n\n *const *const ::std::os::raw::c_char,\n\n opts: *const TF_FunctionOptions,\n\n description: *const ::std::os::raw::c_char,\n\n status: *mut TF_Status) -> *mut TF_Function;\n\n}\n\nextern \"C\" {\n\n pub fn TF_FunctionName(func: *mut TF_Function)\n\n -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn TF_FunctionToFunctionDef(func: *mut TF_Function,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 65, "score": 27593.91157142994 }, { "content": " pub fn TF_GraphGetOpDef(graph: *mut TF_Graph,\n\n op_name: *const ::std::os::raw::c_char,\n\n output_op_def: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphVersions(graph: *mut TF_Graph,\n\n output_version_def: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_ImportGraphDefOptions {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewImportGraphDefOptions() -> *mut TF_ImportGraphDefOptions;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteImportGraphDefOptions(opts:\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 66, "score": 27593.755783659723 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrBool(oper: *mut TF_Operation,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *mut ::std::os::raw::c_uchar,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrBoolList(oper: *mut TF_Operation,\n\n attr_name:\n\n *const ::std::os::raw::c_char,\n\n values: *mut ::std::os::raw::c_uchar,\n\n max_values: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrType(oper: *mut TF_Operation,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *mut TF_DataType,\n\n status: *mut TF_Status);\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 67, "score": 27593.64181446824 }, { "content": "extern \"C\" {\n\n pub fn TF_Reset(opt: *const TF_SessionOptions,\n\n containers: *mut *const ::std::os::raw::c_char,\n\n ncontainers: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ExtendGraph(arg1: *mut TF_DeprecatedSession,\n\n proto: *const ::std::os::raw::c_void,\n\n proto_len: usize, arg2: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_Run(arg1: *mut TF_DeprecatedSession,\n\n run_options: *const TF_Buffer,\n\n input_names: *mut *const ::std::os::raw::c_char,\n\n inputs: *mut *mut TF_Tensor, ninputs: ::std::os::raw::c_int,\n\n output_names: *mut *const ::std::os::raw::c_char,\n\n outputs: *mut *mut TF_Tensor,\n\n noutputs: ::std::os::raw::c_int,\n\n target_oper_names: *mut *const ::std::os::raw::c_char,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 68, "score": 27593.45087206523 }, { "content": " index: 0,\n\n });\n\n input_tensors.push(tensor);\n\n\n\n let mut outputs = vec![];\n\n let mut output_tensors = vec![];\n\n\n\n let name = CString::new(\"c\").unwrap();\n\n\n\n let output_op = nonnull!(ffi::TF_GraphOperationByName(graph, name.as_ptr()));\n\n outputs.push(ffi::TF_Output{\n\n oper: output_op,\n\n index: 0,\n\n });\n\n output_tensors.push(null_mut());\n\n\n\n let mut target_names = vec![];\n\n\n\n ffi::TF_SessionRun(session,\n\n null(),\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 69, "score": 27593.251639703714 }, { "content": "pub struct TF_SessionOptions {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewSessionOptions() -> *mut TF_SessionOptions;\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetTarget(options: *mut TF_SessionOptions,\n\n target: *const ::std::os::raw::c_char);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetConfig(options: *mut TF_SessionOptions,\n\n proto: *const ::std::os::raw::c_void,\n\n proto_len: usize, status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteSessionOptions(arg1: *mut TF_SessionOptions);\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 70, "score": 27593.080174948616 }, { "content": "extern \"C\" {\n\n pub fn TF_OperationNumControlInputs(oper: *mut TF_Operation)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetControlInputs(oper: *mut TF_Operation,\n\n control_inputs:\n\n *mut *mut TF_Operation,\n\n max_control_inputs:\n\n ::std::os::raw::c_int)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationNumControlOutputs(oper: *mut TF_Operation)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetControlOutputs(oper: *mut TF_Operation,\n\n control_outputs:\n\n *mut *mut TF_Operation,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 71, "score": 27592.94870032125 }, { "content": " pub fn TF_AddInputList(desc: *mut TF_OperationDescription,\n\n inputs: *const TF_Output,\n\n num_inputs: ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_AddControlInput(desc: *mut TF_OperationDescription,\n\n input: *mut TF_Operation);\n\n}\n\nextern \"C\" {\n\n pub fn TF_ColocateWith(desc: *mut TF_OperationDescription,\n\n op: *mut TF_Operation);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrString(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *const ::std::os::raw::c_void,\n\n length: usize);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrStringList(desc: *mut TF_OperationDescription,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 72, "score": 27592.91499436709 }, { "content": " output_names: *mut *const ::std::os::raw::c_char,\n\n outputs: *mut *mut TF_Tensor,\n\n noutputs: ::std::os::raw::c_int,\n\n target_oper_names: *mut *const ::std::os::raw::c_char,\n\n ntargets: ::std::os::raw::c_int, arg2: *mut TF_Status);\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_DeviceList {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_SessionListDevices(session: *mut TF_Session,\n\n status: *mut TF_Status)\n\n -> *mut TF_DeviceList;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeprecatedSessionListDevices(session: *mut TF_DeprecatedSession,\n\n status: *mut TF_Status)\n\n -> *mut TF_DeviceList;\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 73, "score": 27592.858728508483 }, { "content": "extern \"C\" {\n\n pub fn TF_GraphGetTensorShape(graph: *mut TF_Graph, output: TF_Output,\n\n dims: *mut i64,\n\n num_dims: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewOperation(graph: *mut TF_Graph,\n\n op_type: *const ::std::os::raw::c_char,\n\n oper_name: *const ::std::os::raw::c_char)\n\n -> *mut TF_OperationDescription;\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetDevice(desc: *mut TF_OperationDescription,\n\n device: *const ::std::os::raw::c_char);\n\n}\n\nextern \"C\" {\n\n pub fn TF_AddInput(desc: *mut TF_OperationDescription, input: TF_Output);\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 74, "score": 27592.736369511404 }, { "content": "extern \"C\" {\n\n pub fn TF_DeviceListMemoryBytes(list: *const TF_DeviceList,\n\n index: ::std::os::raw::c_int,\n\n status: *mut TF_Status) -> i64;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeviceListIncarnation(list: *const TF_DeviceList,\n\n index: ::std::os::raw::c_int,\n\n status: *mut TF_Status) -> u64;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_Library {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_LoadLibrary(library_filename: *const ::std::os::raw::c_char,\n\n status: *mut TF_Status) -> *mut TF_Library;\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 75, "score": 27592.63304361141 }, { "content": " assert_eq! (unsafe {\n\n & ( * ( 0 as * const TF_WhileParams ) ) . name as * const _ as\n\n usize } , 64usize , concat ! (\n\n \"Alignment of field: \" , stringify ! ( TF_WhileParams ) , \"::\"\n\n , stringify ! ( name ) ));\n\n}\n\nimpl Clone for TF_WhileParams {\n\n fn clone(&self) -> Self { *self }\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewWhile(g: *mut TF_Graph, inputs: *mut TF_Output,\n\n ninputs: ::std::os::raw::c_int, status: *mut TF_Status)\n\n -> TF_WhileParams;\n\n}\n\nextern \"C\" {\n\n pub fn TF_FinishWhile(params: *const TF_WhileParams,\n\n status: *mut TF_Status, outputs: *mut TF_Output);\n\n}\n\nextern \"C\" {\n\n pub fn TF_AbortWhile(params: *const TF_WhileParams);\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 76, "score": 27592.5921140737 }, { "content": "extern \"C\" {\n\n pub fn TF_Version() -> *const ::std::os::raw::c_char;\n\n}\n\npub const TF_DataType_TF_COMPLEX: TF_DataType = TF_DataType::TF_COMPLEX64;\n\n#[repr(u32)]\n\n#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]\n\npub enum TF_DataType {\n\n TF_FLOAT = 1,\n\n TF_DOUBLE = 2,\n\n TF_INT32 = 3,\n\n TF_UINT8 = 4,\n\n TF_INT16 = 5,\n\n TF_INT8 = 6,\n\n TF_STRING = 7,\n\n TF_COMPLEX64 = 8,\n\n TF_INT64 = 9,\n\n TF_BOOL = 10,\n\n TF_QINT8 = 11,\n\n TF_QUINT8 = 12,\n\n TF_QINT32 = 13,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 77, "score": 27592.2328289122 }, { "content": " status);\n\n ffi::TF_DeleteImportGraphDefOptions(opts);\n\n ok!(status);\n\n\n\n let session = nonnull!(ffi::TF_NewSession(graph, options, status));\n\n let mut inputs = vec![];\n\n let mut input_tensors: Vec<*const ffi::TF_Tensor> = vec![];\n\n\n\n let name = CString::new(\"a\").unwrap();\n\n let mut data = vec![1f32, 2.0, 3.0];\n\n let dims = vec![data.len() as int64_t];\n\n let tensor = nonnull!(ffi::TF_NewTensor(ffi::TF_FLOAT,\n\n dims.as_ptr(),\n\n dims.len() as c_int,\n\n data.as_mut_ptr() as *mut _,\n\n data.len() as size_t * mem::size_of::<f32>(),\n\n Some(noop),\n\n null_mut()));\n\n\n\n let input_op = nonnull!(ffi::TF_GraphOperationByName(graph, name.as_ptr()));\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 78, "score": 27592.211312068102 }, { "content": " ffi::TF_DeleteSession(session, status);\n\n ffi::TF_DeleteGraph(graph);\n\n ffi::TF_DeleteTensor(tensor);\n\n ffi::TF_DeleteStatus(status);\n\n ffi::TF_DeleteSessionOptions(options);\n\n }\n\n\n\n unsafe extern \"C\" fn noop(_: *mut std::os::raw::c_void, _: size_t, _: *mut std::os::raw::c_void) {}\n\n}\n\n\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 79, "score": 27592.053483950476 }, { "content": " status: *mut TF_Status) -> *mut TF_Session;\n\n}\n\nextern \"C\" {\n\n pub fn TF_LoadSessionFromSavedModel(session_options:\n\n *const TF_SessionOptions,\n\n run_options: *const TF_Buffer,\n\n export_dir:\n\n *const ::std::os::raw::c_char,\n\n tags:\n\n *const *const ::std::os::raw::c_char,\n\n tags_len: ::std::os::raw::c_int,\n\n graph: *mut TF_Graph,\n\n meta_graph_def: *mut TF_Buffer,\n\n status: *mut TF_Status)\n\n -> *mut TF_Session;\n\n}\n\nextern \"C\" {\n\n pub fn TF_CloseSession(arg1: *mut TF_Session, status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 80, "score": 27592.045135953624 }, { "content": " proto: *const ::std::os::raw::c_void,\n\n proto_len: usize, status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_FinishOperation(desc: *mut TF_OperationDescription,\n\n status: *mut TF_Status) -> *mut TF_Operation;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationName(oper: *mut TF_Operation)\n\n -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationOpType(oper: *mut TF_Operation)\n\n -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationDevice(oper: *mut TF_Operation)\n\n -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 81, "score": 27591.94843023769 }, { "content": " pub fn TF_DeletePRunHandle(handle: *const ::std::os::raw::c_char);\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_DeprecatedSession {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewDeprecatedSession(arg1: *const TF_SessionOptions,\n\n status: *mut TF_Status)\n\n -> *mut TF_DeprecatedSession;\n\n}\n\nextern \"C\" {\n\n pub fn TF_CloseDeprecatedSession(arg1: *mut TF_DeprecatedSession,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteDeprecatedSession(arg1: *mut TF_DeprecatedSession,\n\n status: *mut TF_Status);\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 82, "score": 27591.927712266508 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_TensorMaybeMove(tensor: *mut TF_Tensor) -> *mut TF_Tensor;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteTensor(arg1: *mut TF_Tensor);\n\n}\n\nextern \"C\" {\n\n pub fn TF_TensorType(arg1: *const TF_Tensor) -> TF_DataType;\n\n}\n\nextern \"C\" {\n\n pub fn TF_NumDims(arg1: *const TF_Tensor) -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_Dim(tensor: *const TF_Tensor, dim_index: ::std::os::raw::c_int)\n\n -> i64;\n\n}\n\nextern \"C\" {\n\n pub fn TF_TensorByteSize(arg1: *const TF_Tensor) -> usize;\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 83, "score": 27591.900679875234 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_SetAttrFloatList(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n values: *const f32,\n\n num_values: ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrBool(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: ::std::os::raw::c_uchar);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrBoolList(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n values: *const ::std::os::raw::c_uchar,\n\n num_values: ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrType(desc: *mut TF_OperationDescription,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 84, "score": 27591.750387505046 }, { "content": " pub fn TF_GetOpList(lib_handle: *mut TF_Library) -> TF_Buffer;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteLibraryHandle(lib_handle: *mut TF_Library);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GetAllOpList() -> *mut TF_Buffer;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_ApiDefMap {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewApiDefMap(op_list_buffer: *mut TF_Buffer,\n\n status: *mut TF_Status) -> *mut TF_ApiDefMap;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteApiDefMap(apimap: *mut TF_ApiDefMap);\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 85, "score": 27591.724830110314 }, { "content": " attr_name:\n\n *const ::std::os::raw::c_char,\n\n output_attr_value: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphOperationByName(graph: *mut TF_Graph,\n\n oper_name: *const ::std::os::raw::c_char)\n\n -> *mut TF_Operation;\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphNextOperation(graph: *mut TF_Graph, pos: *mut usize)\n\n -> *mut TF_Operation;\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphToGraphDef(graph: *mut TF_Graph,\n\n output_graph_def: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 86, "score": 27591.720249643036 }, { "content": " inputs.push(ffi::TF_Output{\n\n oper: input_op,\n\n index: 0,\n\n });\n\n input_tensors.push(tensor);\n\n\n\n let name = CString::new(\"b\").unwrap();\n\n let mut data = vec![4f32, 5.0, 6.0];\n\n let dims = vec![data.len() as int64_t];\n\n let tensor = nonnull!(ffi::TF_NewTensor(ffi::TF_FLOAT,\n\n dims.as_ptr(),\n\n dims.len() as c_int,\n\n data.as_mut_ptr() as *mut _,\n\n data.len() as size_t as size_t * mem::size_of::<f32>(),\n\n Some(noop),\n\n null_mut()));\n\n\n\n let input_op = nonnull!(ffi::TF_GraphOperationByName(graph, name.as_ptr()));\n\n inputs.push(ffi::TF_Output{\n\n oper: input_op,\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 87, "score": 27591.630713767678 }, { "content": "}\n\nimpl Clone for TF_Buffer {\n\n fn clone(&self) -> Self { *self }\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewBufferFromString(proto: *const ::std::os::raw::c_void,\n\n proto_len: usize) -> *mut TF_Buffer;\n\n}\n\nextern \"C\" {\n\n pub fn TF_NewBuffer() -> *mut TF_Buffer;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeleteBuffer(arg1: *mut TF_Buffer);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GetBuffer(buffer: *mut TF_Buffer) -> TF_Buffer;\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_Tensor {\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 88, "score": 27591.62608522882 }, { "content": " if ffi::TF_GetCode($status) != ffi::TF_OK {\n\n panic!(CStr::from_ptr(ffi::TF_Message($status)).to_string_lossy().into_owned());\n\n }\n\n });\n\n);\n\n\n\n#[cfg_attr(feature=\"examples_system_alloc\", global_allocator)]\n\n#[cfg(feature=\"examples_system_alloc\")]\n\nstatic ALLOCATOR: System = System;\n\n\n", "file_path": "tensorflow-sys/examples/multiplication.rs", "rank": 89, "score": 27591.495455108754 }, { "content": "/* automatically generated by rust-bindgen */\n\n\n\npub const _STDINT_H: ::std::os::raw::c_uint = 1;\n\npub const _FEATURES_H: ::std::os::raw::c_uint = 1;\n\npub const _DEFAULT_SOURCE: ::std::os::raw::c_uint = 1;\n\npub const __USE_ISOC11: ::std::os::raw::c_uint = 1;\n\npub const __USE_ISOC99: ::std::os::raw::c_uint = 1;\n\npub const __USE_ISOC95: ::std::os::raw::c_uint = 1;\n\npub const __USE_POSIX_IMPLICITLY: ::std::os::raw::c_uint = 1;\n\npub const _POSIX_SOURCE: ::std::os::raw::c_uint = 1;\n\npub const _POSIX_C_SOURCE: ::std::os::raw::c_uint = 200809;\n\npub const __USE_POSIX: ::std::os::raw::c_uint = 1;\n\npub const __USE_POSIX2: ::std::os::raw::c_uint = 1;\n\npub const __USE_POSIX199309: ::std::os::raw::c_uint = 1;\n\npub const __USE_POSIX199506: ::std::os::raw::c_uint = 1;\n\npub const __USE_XOPEN2K: ::std::os::raw::c_uint = 1;\n\npub const __USE_XOPEN2K8: ::std::os::raw::c_uint = 1;\n\npub const _ATFILE_SOURCE: ::std::os::raw::c_uint = 1;\n\npub const __USE_MISC: ::std::os::raw::c_uint = 1;\n\npub const __USE_ATFILE: ::std::os::raw::c_uint = 1;\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 90, "score": 27591.041627253897 }, { "content": "#[derive(Debug, Copy, Clone)]\n\npub struct TF_Function {\n\n _unused: [u8; 0],\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy, Clone)]\n\npub struct TF_FunctionOptions {\n\n _unused: [u8; 0],\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphSetTensorShape(graph: *mut TF_Graph, output: TF_Output,\n\n dims: *const i64,\n\n num_dims: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_GraphGetTensorNumDims(graph: *mut TF_Graph, output: TF_Output,\n\n status: *mut TF_Status)\n\n -> ::std::os::raw::c_int;\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 91, "score": 27591.03020006399 }, { "content": "extern crate tensorflow_sys as ffi;\n\n\n\n#[test]\n", "file_path": "tensorflow-sys/tests/lib.rs", "rank": 92, "score": 27590.98854718827 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_DeleteDeviceList(list: *mut TF_DeviceList);\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeviceListCount(list: *const TF_DeviceList)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeviceListName(list: *const TF_DeviceList,\n\n index: ::std::os::raw::c_int,\n\n status: *mut TF_Status)\n\n -> *const ::std::os::raw::c_char;\n\n}\n\nextern \"C\" {\n\n pub fn TF_DeviceListType(list: *const TF_DeviceList,\n\n index: ::std::os::raw::c_int,\n\n status: *mut TF_Status)\n\n -> *const ::std::os::raw::c_char;\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 93, "score": 27590.975946134615 }, { "content": "}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrTypeList(oper: *mut TF_Operation,\n\n attr_name:\n\n *const ::std::os::raw::c_char,\n\n values: *mut TF_DataType,\n\n max_values: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrShape(oper: *mut TF_Operation,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *mut i64,\n\n num_dims: ::std::os::raw::c_int,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrShapeList(oper: *mut TF_Operation,\n\n attr_name:\n\n *const ::std::os::raw::c_char,\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 94, "score": 27590.96626263353 }, { "content": " status: *mut TF_Status)\n\n -> ::std::os::raw::c_int;\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationToNodeDef(oper: *mut TF_Operation,\n\n output_node_def: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\n#[repr(C)]\n\n#[derive(Debug, Copy)]\n\npub struct TF_WhileParams {\n\n pub ninputs: ::std::os::raw::c_int,\n\n pub cond_graph: *const TF_Graph,\n\n pub cond_inputs: *const TF_Output,\n\n pub cond_output: TF_Output,\n\n pub body_graph: *const TF_Graph,\n\n pub body_inputs: *const TF_Output,\n\n pub body_outputs: *const TF_Output,\n\n pub name: *const ::std::os::raw::c_char,\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 95, "score": 27590.94909777661 }, { "content": " attr_name: *const ::std::os::raw::c_char,\n\n value: TF_DataType);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrTypeList(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n values: *const TF_DataType,\n\n num_values: ::std::os::raw::c_int);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrFuncName(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *const ::std::os::raw::c_char,\n\n length: usize);\n\n}\n\nextern \"C\" {\n\n pub fn TF_SetAttrShape(desc: *mut TF_OperationDescription,\n\n attr_name: *const ::std::os::raw::c_char,\n\n dims: *const i64, num_dims: ::std::os::raw::c_int);\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 96, "score": 27590.93684675736 }, { "content": " max_length: usize,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrStringList(oper: *mut TF_Operation,\n\n attr_name:\n\n *const ::std::os::raw::c_char,\n\n values:\n\n *mut *mut ::std::os::raw::c_void,\n\n lengths: *mut usize,\n\n max_values: ::std::os::raw::c_int,\n\n storage: *mut ::std::os::raw::c_void,\n\n storage_size: usize,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_OperationGetAttrInt(oper: *mut TF_Operation,\n\n attr_name: *const ::std::os::raw::c_char,\n\n value: *mut i64, status: *mut TF_Status);\n\n}\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 97, "score": 27590.893169620926 }, { "content": " output_func_def: *mut TF_Buffer,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_FunctionImportFunctionDef(proto: *const ::std::os::raw::c_void,\n\n proto_len: usize,\n\n status: *mut TF_Status)\n\n -> *mut TF_Function;\n\n}\n\nextern \"C\" {\n\n pub fn TF_FunctionSetAttrValueProto(func: *mut TF_Function,\n\n attr_name:\n\n *const ::std::os::raw::c_char,\n\n proto: *const ::std::os::raw::c_void,\n\n proto_len: usize,\n\n status: *mut TF_Status);\n\n}\n\nextern \"C\" {\n\n pub fn TF_FunctionGetAttrValueProto(func: *mut TF_Function,\n\n attr_name:\n", "file_path": "tensorflow-sys/src/bindgen.rs", "rank": 98, "score": 27590.613186709772 }, { "content": "extern crate random;\n\nextern crate tensorflow;\n\n\n\nuse random::Source;\n\nuse std::alloc::System;\n\nuse std::error::Error;\n\nuse std::fs::File;\n\nuse std::io::Read;\n\nuse std::result::Result;\n\nuse std::path::Path;\n\nuse std::process::exit;\n\nuse tensorflow::Code;\n\nuse tensorflow::Graph;\n\nuse tensorflow::ImportGraphDefOptions;\n\nuse tensorflow::Session;\n\nuse tensorflow::SessionOptions;\n\nuse tensorflow::SessionRunArgs;\n\nuse tensorflow::Status;\n\nuse tensorflow::Tensor;\n\n\n\n#[cfg_attr(feature=\"examples_system_alloc\", global_allocator)]\n\n#[cfg(feature=\"examples_system_alloc\")]\n\nstatic ALLOCATOR: System = System;\n\n\n", "file_path": "examples/regression.rs", "rank": 99, "score": 32.283542048024366 } ]
Rust
src/mock_server.rs
pactflow/pact-protobuf-plugin
1d57edee9e5fe34b76d32ab4f72ea8935eab4bc2
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Mutex; use std::task::{Context, Poll}; use std::thread; use anyhow::anyhow; use bytes::Bytes; use http::Method; use hyper::{http, Request, Response}; use hyper::server::accept; use lazy_static::lazy_static; use maplit::hashmap; use pact_matching::BodyMatchResult; use pact_models::content_types::ContentType; use pact_models::json_utils::json_to_string; use pact_models::plugins::PluginData; use pact_models::prelude::v4::V4Pact; use pact_models::v4::sync_message::SynchronousMessage; use prost::Message; use prost_types::{FileDescriptorSet, MethodDescriptorProto}; use serde_json::Value; use tokio::net::TcpListener; use tokio::runtime::Handle; use tokio::sync::oneshot::{channel, Sender}; use tonic::body::{BoxBody, empty_body}; use tonic::metadata::MetadataMap; use tower::make::Shared; use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; use tower_http::ServiceBuilderExt; use tower_service::Service; use tracing::{debug, error, Instrument, instrument, trace, trace_span}; use uuid::Uuid; use crate::dynamic_message::PactCodec; use crate::mock_service::MockService; use crate::tcp::TcpIncoming; use crate::utils::{find_message_type_by_name, last_name}; lazy_static! { pub static ref MOCK_SERVER_STATE: Mutex<HashMap<String, (Sender<()>, Vec<(String, BodyMatchResult)>)>> = Mutex::new(hashmap!{}); } #[derive(Debug, Clone)] pub struct GrpcMockServer { pact: V4Pact, plugin_config: PluginData, descriptors: HashMap<String, FileDescriptorSet>, routes: HashMap<String, (FileDescriptorSet, MethodDescriptorProto, SynchronousMessage)>, pub server_key: String } impl GrpcMockServer { pub fn new(pact: V4Pact, plugin_config: &PluginData) -> Self { GrpcMockServer { pact, plugin_config: plugin_config.clone(), descriptors: Default::default(), routes: Default::default(), server_key: Uuid::new_v4().to_string() } } #[instrument] pub async fn start_server(mut self, host_interface: &str, port: u32, tls: bool) -> anyhow::Result<SocketAddr> { for (key, value) in &self.plugin_config.configuration { if let Value::Object(map) = value { if let Some(descriptor) = map.get("protoDescriptors") { let bytes = base64::decode(json_to_string(descriptor))?; let buffer = Bytes::from(bytes); let fds = FileDescriptorSet::decode(buffer)?; self.descriptors.insert(key.clone(), fds); } } } if self.descriptors.is_empty() { return Err(anyhow!("Pact file does not contain any Protobuf descriptors")); } self.routes = self.pact.interactions.iter() .filter_map(|i| i.as_v4_sync_message()) .filter_map(|i| i.plugin_config.get("protobuf").map(|p| (p.clone(), i.clone()))) .filter_map(|(c, i)| { if let Some(key) = c.get("descriptorKey") { if let Some(descriptors) = self.descriptors.get(json_to_string(key).as_str()) { if let Some(service) = c.get("service") { if let Some((service_name, method_name)) = json_to_string(service).split_once('/') { descriptors.file.iter().filter_map(|d| { d.service.iter().find(|s| s.name.clone().unwrap_or_default() == service_name) }).next() .and_then(|d| { d.method.iter() .find(|m| m.name.clone().unwrap_or_default() == method_name) .map(|m| (format!("{service_name}/{method_name}"), (descriptors.clone(), m.clone(), i.clone()))) }) } else { None } } else { None } } else { None } } else { None } }).collect(); let interface = if host_interface.is_empty() { "[::1]" } else { host_interface }; let addr: SocketAddr = format!("{interface}:{port}").parse()?; trace!("setting up mock server {addr}"); let (snd, rcr) = channel::<()>(); { let mut guard = MOCK_SERVER_STATE.lock().unwrap(); guard.insert(self.server_key.clone(), (snd, vec![])); } let listener = TcpListener::bind(addr).await?; let address = listener.local_addr()?; let handle = Handle::current(); let key = self.server_key.clone(); let key2 = self.server_key.clone(); let result = thread::spawn(move || { let incoming_stream = TcpIncoming { inner: listener }; let incoming = accept::from_stream(incoming_stream); trace!("setting up middleware"); let service = ServiceBuilder::new() .trace_for_grpc() .layer(CompressionLayer::new()) .service(self); trace!("setting up HTTP server"); let server = hyper::Server::builder(incoming) .http2_only(true) .serve(Shared::new(service)) .with_graceful_shutdown(async move { let _ = rcr.await; trace!("Received shutdown signal for server {}", key); }) .instrument(tracing::trace_span!("mock server", key = key2.as_str(), port = address.port())); trace!("spawning server onto runtime"); handle.spawn(server); trace!("spawning server onto runtime - done"); }).join(); if result.is_err() { Err(anyhow!("Failed to start mock server thread")) } else { trace!("Mock server setup OK"); Ok(address) } } } impl Service<hyper::Request<hyper::Body>> for GrpcMockServer { type Response = hyper::Response<BoxBody>; type Error = anyhow::Error; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } #[instrument] fn call(&mut self, req: Request<hyper::Body>) -> Self::Future { let routes = self.routes.clone(); let server_key = self.server_key.clone(); Box::pin(async move { trace!("Got request {req:?}"); let headers = req.headers(); let metadata = MetadataMap::from_headers(headers.clone()); let content_type = if let Some(content_type) = metadata.get("content-type") { ContentType::parse(content_type.to_str().unwrap_or_default()) .map_err(|err| anyhow!(err)) } else { Err(anyhow!("no content type was provided")) }; match content_type { Ok(content_type) => if content_type.base_type().to_string().starts_with("application/grpc") { let method = req.method(); if method == Method::POST { let request_path = req.uri().path(); debug!("gRPC request received {}", request_path); if let Some((service, method)) = request_path[1..].split_once('/') { let service_name = last_name(service); let lookup = format!("{service_name}/{method}"); if let Some((file, method_descriptor, message)) = routes.get(lookup.as_str()) { trace!(message = message.description.as_str(), "Found route for service call"); let input_message_name = method_descriptor.input_type.clone().unwrap_or_default(); let input_message = find_message_type_by_name(last_name(input_message_name.as_str()), file); let output_message_name = method_descriptor.output_type.clone().unwrap_or_default(); let output_message = find_message_type_by_name(last_name(output_message_name.as_str()), file); if let Ok(input_message) = input_message { if let Ok(output_message) = output_message { let codec = PactCodec::new(file, &input_message, &output_message, message); let mock_service = MockService::new(file, service_name, method_descriptor, &input_message, &output_message, message, server_key.as_str()); let mut grpc = tonic::server::Grpc::new(codec); Ok(grpc.unary(mock_service, req).await) } else { error!("Did not find the descriptor for the output message {}", output_message_name); Ok(failed_precondition()) } } else { error!("Did not find the descriptor for the input message {}", input_message_name); Ok(failed_precondition()) } } else { Ok(invalid_path()) } } else { Ok(invalid_path()) } } else { Ok(invalid_method()) } } else { Ok(invalid_media()) } Err(err) => { error!("Failed to parse the content type - {err}"); Ok(invalid_media()) } } }.instrument(trace_span!("mock_server_handler", key = self.server_key.as_str()))) } } fn invalid_media() -> Response<BoxBody> { http::Response::builder() .status(415) .body(empty_body()) .unwrap() } fn invalid_method() -> Response<BoxBody> { http::Response::builder() .status(405) .body(empty_body()) .unwrap() } fn invalid_path() -> Response<BoxBody> { http::Response::builder() .status(200) .header("grpc-status", "12") .header("content-type", "application/grpc") .body(empty_body()) .unwrap() } fn failed_precondition() -> Response<BoxBody> { http::Response::builder() .status(200) .header("grpc-status", "9") .header("content-type", "application/grpc") .body(empty_body()) .unwrap() }
use std::collections::HashMap; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use std::sync::Mutex; use std::task::{Context, Poll}; use std::thread; use anyhow::anyhow; use bytes::Bytes; use http::Method; use hyper::{http, Request, Response}; use hyper::server::accept; use lazy_static::lazy_static; use maplit::hashmap; use pact_matching::BodyMatchResult; use pact_models::content_types::ContentType; use pact_models::json_utils::json_to_string; use pact_models::plugins::PluginData; use pact_models::prelude::v4::V4Pact; use pact_models::v4::sync_message::SynchronousMessage; use prost::Message; use prost_types::{FileDescriptorSet, MethodDescriptorProto}; use serde_json::Value; use tokio::net::TcpListener; use tokio::runtime::Handle; use tokio::sync::oneshot::{channel, Sender}; use tonic::body::{BoxBody, empty_body}; use tonic::metadata::MetadataMap; use tower::make::Shared; use tower::ServiceBuilder; use tower_http::compression::CompressionLayer; use tower_http::ServiceBuilderExt; use tower_service::Service; use tracing::{debug, error, Instrument, instrument, trace, trace_span}; use uuid::Uuid; use crate::dynamic_message::PactCodec; use crate::mock_service::MockService; use crate::tcp::TcpIncoming; use crate::utils::{find_message_type_by_name, last_name}; lazy_static! { pub static ref MOCK_SERVER_STATE: Mutex<HashMap<String, (Sender<()>, Vec<(String, BodyMatchResult)>)>> = Mutex::new(hashmap!{}); } #[derive(Debug, Clone)] pub struct GrpcMockServer { pact: V4Pact, plugin_config: PluginData, descriptors: HashMap<String, FileDescriptorSet>, routes: HashMap<String, (FileDescriptorSet, MethodDescriptorProto, SynchronousMessage)>, pub server_key: String } impl GrpcMockServer { pub f
} #[instrument] pub async fn start_server(mut self, host_interface: &str, port: u32, tls: bool) -> anyhow::Result<SocketAddr> { for (key, value) in &self.plugin_config.configuration { if let Value::Object(map) = value { if let Some(descriptor) = map.get("protoDescriptors") { let bytes = base64::decode(json_to_string(descriptor))?; let buffer = Bytes::from(bytes); let fds = FileDescriptorSet::decode(buffer)?; self.descriptors.insert(key.clone(), fds); } } } if self.descriptors.is_empty() { return Err(anyhow!("Pact file does not contain any Protobuf descriptors")); } self.routes = self.pact.interactions.iter() .filter_map(|i| i.as_v4_sync_message()) .filter_map(|i| i.plugin_config.get("protobuf").map(|p| (p.clone(), i.clone()))) .filter_map(|(c, i)| { if let Some(key) = c.get("descriptorKey") { if let Some(descriptors) = self.descriptors.get(json_to_string(key).as_str()) { if let Some(service) = c.get("service") { if let Some((service_name, method_name)) = json_to_string(service).split_once('/') { descriptors.file.iter().filter_map(|d| { d.service.iter().find(|s| s.name.clone().unwrap_or_default() == service_name) }).next() .and_then(|d| { d.method.iter() .find(|m| m.name.clone().unwrap_or_default() == method_name) .map(|m| (format!("{service_name}/{method_name}"), (descriptors.clone(), m.clone(), i.clone()))) }) } else { None } } else { None } } else { None } } else { None } }).collect(); let interface = if host_interface.is_empty() { "[::1]" } else { host_interface }; let addr: SocketAddr = format!("{interface}:{port}").parse()?; trace!("setting up mock server {addr}"); let (snd, rcr) = channel::<()>(); { let mut guard = MOCK_SERVER_STATE.lock().unwrap(); guard.insert(self.server_key.clone(), (snd, vec![])); } let listener = TcpListener::bind(addr).await?; let address = listener.local_addr()?; let handle = Handle::current(); let key = self.server_key.clone(); let key2 = self.server_key.clone(); let result = thread::spawn(move || { let incoming_stream = TcpIncoming { inner: listener }; let incoming = accept::from_stream(incoming_stream); trace!("setting up middleware"); let service = ServiceBuilder::new() .trace_for_grpc() .layer(CompressionLayer::new()) .service(self); trace!("setting up HTTP server"); let server = hyper::Server::builder(incoming) .http2_only(true) .serve(Shared::new(service)) .with_graceful_shutdown(async move { let _ = rcr.await; trace!("Received shutdown signal for server {}", key); }) .instrument(tracing::trace_span!("mock server", key = key2.as_str(), port = address.port())); trace!("spawning server onto runtime"); handle.spawn(server); trace!("spawning server onto runtime - done"); }).join(); if result.is_err() { Err(anyhow!("Failed to start mock server thread")) } else { trace!("Mock server setup OK"); Ok(address) } } } impl Service<hyper::Request<hyper::Body>> for GrpcMockServer { type Response = hyper::Response<BoxBody>; type Error = anyhow::Error; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } #[instrument] fn call(&mut self, req: Request<hyper::Body>) -> Self::Future { let routes = self.routes.clone(); let server_key = self.server_key.clone(); Box::pin(async move { trace!("Got request {req:?}"); let headers = req.headers(); let metadata = MetadataMap::from_headers(headers.clone()); let content_type = if let Some(content_type) = metadata.get("content-type") { ContentType::parse(content_type.to_str().unwrap_or_default()) .map_err(|err| anyhow!(err)) } else { Err(anyhow!("no content type was provided")) }; match content_type { Ok(content_type) => if content_type.base_type().to_string().starts_with("application/grpc") { let method = req.method(); if method == Method::POST { let request_path = req.uri().path(); debug!("gRPC request received {}", request_path); if let Some((service, method)) = request_path[1..].split_once('/') { let service_name = last_name(service); let lookup = format!("{service_name}/{method}"); if let Some((file, method_descriptor, message)) = routes.get(lookup.as_str()) { trace!(message = message.description.as_str(), "Found route for service call"); let input_message_name = method_descriptor.input_type.clone().unwrap_or_default(); let input_message = find_message_type_by_name(last_name(input_message_name.as_str()), file); let output_message_name = method_descriptor.output_type.clone().unwrap_or_default(); let output_message = find_message_type_by_name(last_name(output_message_name.as_str()), file); if let Ok(input_message) = input_message { if let Ok(output_message) = output_message { let codec = PactCodec::new(file, &input_message, &output_message, message); let mock_service = MockService::new(file, service_name, method_descriptor, &input_message, &output_message, message, server_key.as_str()); let mut grpc = tonic::server::Grpc::new(codec); Ok(grpc.unary(mock_service, req).await) } else { error!("Did not find the descriptor for the output message {}", output_message_name); Ok(failed_precondition()) } } else { error!("Did not find the descriptor for the input message {}", input_message_name); Ok(failed_precondition()) } } else { Ok(invalid_path()) } } else { Ok(invalid_path()) } } else { Ok(invalid_method()) } } else { Ok(invalid_media()) } Err(err) => { error!("Failed to parse the content type - {err}"); Ok(invalid_media()) } } }.instrument(trace_span!("mock_server_handler", key = self.server_key.as_str()))) } } fn invalid_media() -> Response<BoxBody> { http::Response::builder() .status(415) .body(empty_body()) .unwrap() } fn invalid_method() -> Response<BoxBody> { http::Response::builder() .status(405) .body(empty_body()) .unwrap() } fn invalid_path() -> Response<BoxBody> { http::Response::builder() .status(200) .header("grpc-status", "12") .header("content-type", "application/grpc") .body(empty_body()) .unwrap() } fn failed_precondition() -> Response<BoxBody> { http::Response::builder() .status(200) .header("grpc-status", "9") .header("content-type", "application/grpc") .body(empty_body()) .unwrap() }
n new(pact: V4Pact, plugin_config: &PluginData) -> Self { GrpcMockServer { pact, plugin_config: plugin_config.clone(), descriptors: Default::default(), routes: Default::default(), server_key: Uuid::new_v4().to_string() }
function_block-random_span
[ { "content": "/// Get the name of the enum value\n\npub fn enum_name(enum_value: i32, descriptor: &EnumDescriptorProto) -> String {\n\n descriptor.value.iter().find(|v| v.number.unwrap_or(-1) == enum_value)\n\n .map(|v| v.name.clone().unwrap_or_else(|| format!(\"enum {}\", enum_value)))\n\n .unwrap_or_else(|| format!(\"Unknown enum {}\", enum_value))\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 121801.39864395706 }, { "content": "/// Convert a Protobuf Struct to a BTree Map\n\npub fn proto_struct_to_btreemap(val: &prost_types::Struct) -> BTreeMap<String, Value> {\n\n val.fields.iter().map(|(k, v)| (k.clone(), v.clone())).collect()\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 1, "score": 114533.97593185502 }, { "content": "#[derive(Debug)]\n\nstruct MessageRequest {\n\n pub contents: MessageContents\n\n}\n\n\n\n// We can't use the default Rocket serialisation because we want to use the Pact models and they\n\n// don't implement the serde serialisation traits. Not too hard to do it ourselves using the\n\n// FromData trait\n\n#[rocket::async_trait]\n\nimpl <'r> FromData<'r> for MessageRequest {\n\n type Error = anyhow::Error;\n\n\n\n async fn from_data(req: &'r Request<'_>, data: Data<'r>) -> Outcome<'r, Self> {\n\n if let Some(content_type) = req.content_type() {\n\n if content_type.is_json() {\n\n match data.open(ByteUnit::max_value()).into_bytes().await {\n\n Ok(data) => match serde_json::from_slice::<Value>(data.value.as_slice()) {\n\n Ok(json) => {\n\n if let Some(contents) = json.get(\"request\") {\n\n debug!(\"contents = {:?}\", contents);\n\n match MessageContents::from_json(contents) {\n", "file_path": "tests/pact_verify.rs", "rank": 2, "score": 114115.36687335299 }, { "content": "/// If the field is a repeated field\n\npub fn is_repeated_field(descriptor: &FieldDescriptorProto) -> bool {\n\n descriptor.label() == Label::Repeated\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 3, "score": 94268.19821704089 }, { "content": "#[derive(Debug)]\n\nstruct GrpcError {\n\n pub status: Status\n\n}\n\n\n\nimpl Display for GrpcError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"gRPC request failed {}\", self.status)\n\n }\n\n}\n\n\n\nimpl std::error::Error for GrpcError {}\n\n\n\n/// Verify a gRPC interaction\n\npub async fn verify_interaction(\n\n pact: &V4Pact,\n\n interaction: &SynchronousMessage,\n\n request_body: &OptionalBody,\n\n metadata: &HashMap<String, proto::MetadataValue>,\n\n config: &HashMap<String, Value>\n\n) -> anyhow::Result<(Vec<MismatchResult>, Vec<String>)> {\n", "file_path": "src/verification.rs", "rank": 4, "score": 88324.3285779275 }, { "content": "/// Return the type name of a Prootbuf value\n\npub fn proto_type_name(value: &Value) -> String {\n\n match &value.kind {\n\n Some(kind) => match kind {\n\n Kind::NullValue(_) => \"Null\".to_string(),\n\n Kind::NumberValue(_) => \"Number\".to_string(),\n\n Kind::StringValue(_) => \"String\".to_string(),\n\n Kind::BoolValue(_) => \"Boolean\".to_string(),\n\n Kind::StructValue(_) => \"Struct\".to_string(),\n\n Kind::ListValue(_) => \"List\".to_string(),\n\n }\n\n None => \"Unknown\".to_string()\n\n }\n\n}\n\n\n\n/// Parse the JSON string into a V4 Pact model\n\npub(crate) fn parse_pact_from_request_json(pact_json: &str, source: &str) -> anyhow::Result<V4Pact> {\n\n // Parse the Pact JSON string into a JSON struct\n\n let json: serde_json::Value = match serde_json::from_str(pact_json) {\n\n Ok(json) => json,\n\n Err(err) => {\n", "file_path": "src/utils.rs", "rank": 5, "score": 85804.61452092623 }, { "content": "/// Search for a message by type name in the file descriptor\n\npub fn find_message_type_in_file_descriptor(message_name: &str, descriptor: &FileDescriptorProto) -> anyhow::Result<DescriptorProto> {\n\n descriptor.message_type.iter()\n\n .find(|message| message.name.clone().unwrap_or_default() == message_name)\n\n .cloned()\n\n .ok_or_else(|| anyhow!(\"Did not find a message type '{}' in the file descriptor '{:?}'\",\n\n message_name, descriptor.name))\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 6, "score": 83097.90336686368 }, { "content": "/// Search for a message by type name in all the descriptors\n\npub fn find_message_type_by_name(message_name: &str, descriptors: &FileDescriptorSet) -> anyhow::Result<DescriptorProto> {\n\n descriptors.file.iter()\n\n .map(|descriptor| find_message_type_in_file_descriptor(message_name, descriptor).ok())\n\n .find(|result| result.is_some())\n\n .flatten()\n\n .ok_or_else(|| anyhow!(\"Did not find a message type '{}' in the descriptors\", message_name))\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 7, "score": 80302.26440664406 }, { "content": "// We are not using provider states, so we define a executor that does nothing\n\nstruct NoopProviderStateExecutor { }\n\n\n\n#[async_trait]\n\nimpl ProviderStateExecutor for NoopProviderStateExecutor {\n\n async fn call(\n\n self: Arc<Self>,\n\n _interaction_id: Option<String>,\n\n _provider_state: &ProviderState,\n\n _setup: bool,\n\n _client: Option<&Client>\n\n ) -> anyhow::Result<HashMap<String, Value>> {\n\n Ok(hashmap!{})\n\n }\n\n\n\n fn teardown(self: &Self) -> bool {\n\n false\n\n }\n\n}\n\n\n\n// Structure to hold the data we receive from the Pact verifier\n", "file_path": "tests/pact_verify.rs", "rank": 8, "score": 79148.4077316342 }, { "content": "/// If the field is a map field. A field will be a map field if it is a repeated field, the field\n\n/// type is a message and the nested type has the map flag set on the message options.\n\npub fn is_map_field(message_descriptor: &DescriptorProto, field: &FieldDescriptorProto) -> bool {\n\n if field.label() == Label::Repeated && field.r#type() == field_descriptor_proto::Type::Message {\n\n match find_nested_type(message_descriptor, field) {\n\n Some(nested) => match nested.options {\n\n None => false,\n\n Some(options) => options.map_entry.unwrap_or(false)\n\n },\n\n None => false\n\n }\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 9, "score": 71995.58440896764 }, { "content": "/// Returns the nested descriptor for this field.\n\npub fn find_nested_type(message_descriptor: &DescriptorProto, field: &FieldDescriptorProto) -> Option<DescriptorProto> {\n\n trace!(\">> find_nested_type({:?}, {:?}, {:?}, {:?})\", message_descriptor.name, field.name, field.r#type(), field.type_name);\n\n if field.r#type() == field_descriptor_proto::Type::Message {\n\n let type_name = field.type_name.clone().unwrap_or_default();\n\n let message_type = last_name(type_name.as_str());\n\n trace!(\"find_nested_type: Looking for nested type '{}'\", message_type);\n\n message_descriptor.nested_type.iter().find(|nested| {\n\n trace!(\"find_nested_type: type = '{:?}'\", nested.name);\n\n nested.name.clone().unwrap_or_default() == message_type\n\n }).cloned()\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n/// Return the hexadecimal representation for the bytes\n\npub(crate) fn as_hex(data: &[u8]) -> String {\n\n let mut buffer = String::with_capacity(data.len() * 2);\n\n\n\n for b in data {\n", "file_path": "src/utils.rs", "rank": 10, "score": 71156.42664641813 }, { "content": "/// Look for the message field data with the given name\n\npub fn find_message_field_by_name(descriptor: &DescriptorProto, field_data: Vec<ProtobufField>, field_name: &str) -> Option<ProtobufField> {\n\n let field_num = match descriptor.field.iter()\n\n .find(|f| f.name.clone().unwrap_or_default() == field_name)\n\n .map(|f| f.number.unwrap_or(-1)) {\n\n Some(n) => n,\n\n None => return None\n\n };\n\n\n\n field_data.iter().find(|d| d.field_num == field_num as u32).cloned()\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 11, "score": 67773.31066615524 }, { "content": "fn find_message_descriptor(message_name: &str, all_descriptors: &HashMap<String, &FileDescriptorProto>) -> anyhow::Result<DescriptorProto> {\n\n all_descriptors.values().map(|descriptor| {\n\n descriptor.message_type.iter()\n\n .find(|p| p.name.clone().unwrap_or_default() == message_name)\n\n }).find(|d| d.is_some())\n\n .flatten()\n\n .cloned()\n\n .ok_or_else(|| anyhow!(\"Did not find the descriptor for message {}\", message_name))\n\n}\n\n\n", "file_path": "src/protobuf.rs", "rank": 12, "score": 67768.99687244248 }, { "content": "fn integer_value(v: String) -> Result<(), String> {\n\n v.parse::<u64>().map(|_| ()).map_err(|e| format!(\"'{}' is not a valid integer value: {}\", v, e) )\n\n}\n\n\n\n/// Main method of the plugin process. This will start a gRPC server using the plugin proto file\n\n/// (`https://github.com/pact-foundation/pact-plugins/blob/main/proto/plugin.proto`) and then\n\n/// output the port the server is running on as well as a server key required to access the\n\n/// gRPC server.\n\n///\n\n/// Log level will be passed in using the `LOG_LEVEL` environment variable.\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n // Setup the logging system based on the LOG_LEVEL environment variable\n\n let log_level = env::var(\"LOG_LEVEL\").unwrap_or_else(|_| \"INFO\".to_string());\n\n let file_appender = tracing_appender::rolling::daily(\"./log\", \"plugin.log\");\n\n let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);\n\n let json_appender = tracing_appender::rolling::daily(\"./log\", \"plugin.log.json\");\n\n let (json_non_blocking, _json_guard) = tracing_appender::non_blocking(json_appender);\n\n\n\n // Setup tracing\n", "file_path": "src/main.rs", "rank": 13, "score": 62980.02424606674 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n built::write_built_file()?;\n\n Ok(())\n\n}\n", "file_path": "build.rs", "rank": 14, "score": 60353.58357777668 }, { "content": "#[derive(Clone, Debug)]\n\nstruct MapEntry {\n\n pub field_descriptor: FieldDescriptorProto,\n\n pub value: ProtobufField\n\n}\n\n\n\nimpl Display for MapEntry {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"{}\", self.value)\n\n }\n\n}\n\n\n", "file_path": "src/matching.rs", "rank": 15, "score": 57277.13458805581 }, { "content": "#[derive(Debug, Clone)]\n\nstruct AuthInterceptor {\n\n pub server_key: String\n\n}\n\n\n\nimpl Interceptor for AuthInterceptor {\n\n fn call(&mut self, request: Request<()>) -> Result<Request<()>, Status> {\n\n update_access_time();\n\n if let Some(auth) = request.metadata().get(\"authorization\") {\n\n if let Ok(auth) = auth.to_str() {\n\n if self.server_key == auth {\n\n Ok(request)\n\n } else {\n\n Err(Status::unauthenticated(\"invalid credentials supplied\"))\n\n }\n\n } else {\n\n Err(Status::unauthenticated(\"could not read credentials supplied\"))\n\n }\n\n } else {\n\n Err(Status::unauthenticated(\"no credentials supplied\"))\n\n }\n\n }\n\n}\n\n\n\nlazy_static! {\n\n pub static ref SHUTDOWN_TIMER: Mutex<Option<Instant>> = Mutex::new(None);\n\n}\n\n\n\n/// Maximum time to wait when there is no activity to shut the plugin down (10 minutes)\n\nconst MAX_TIME: u64 = 600;\n\n\n", "file_path": "src/main.rs", "rank": 16, "score": 57277.13458805581 }, { "content": "/// Find the integer value of the given enum type and name.\n\npub fn find_enum_value_by_name(message_descriptor: &DescriptorProto, enum_name: &str, enum_value: &str) -> Option<i32> {\n\n trace!(\">> find_enum_value_by_name({:?}, {}, {})\", message_descriptor.name, enum_name, enum_value);\n\n message_descriptor.enum_type.iter()\n\n .find_map(|enum_descriptor| {\n\n trace!(\"find_enum_value_by_name: enum type = {:?}\", enum_descriptor.name);\n\n if let Some(name) = &enum_descriptor.name {\n\n if name == last_name(enum_name) {\n\n enum_descriptor.value.iter().find_map(|val| {\n\n if let Some(name) = &val.name {\n\n if name == enum_value {\n\n val.number\n\n } else {\n\n None\n\n }\n\n } else {\n\n None\n\n }\n\n })\n\n } else {\n\n None\n\n }\n\n } else {\n\n None\n\n }\n\n })\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 17, "score": 56956.373703846984 }, { "content": "/// Find the field descriptor in the message descriptor for the given field value\n\nfn find_field_descriptor(field: &ProtobufField, descriptor: &DescriptorProto) -> Option<FieldDescriptorProto> {\n\n descriptor.field.iter()\n\n .find(|field_desc| field_desc.number.unwrap_or_default() == field.field_num as i32)\n\n .cloned()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use expectest::prelude::*;\n\n use prost::Message;\n\n use prost::encoding::WireType;\n\n use prost_types::{DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto, FileDescriptorSet, MessageOptions};\n\n use prost_types::field_descriptor_proto::Label::{Optional, Repeated};\n\n use prost_types::field_descriptor_proto::Type::{Enum, String};\n\n use pact_models::matchingrules_list;\n\n\n\n use crate::message_decoder::ProtobufField;\n\n use crate::utils::tests::DESCRIPTORS;\n\n\n\n use super::*;\n", "file_path": "src/matching.rs", "rank": 18, "score": 56177.7898710912 }, { "content": "#[derive(Clone, Debug, PartialEq)]\n\nstruct FieldValueInner {\n\n /// Values for the field, only repeated and map fields will have more than one value.\n\n values: Vec<MessageFieldValue>,\n\n /// Descriptor for the field.\n\n descriptor: FieldDescriptorProto,\n\n /// Type of field (singular, map or repeated)\n\n field_type: MessageFieldValueType,\n\n /// Field data type\n\n proto_type: Type\n\n}\n\n\n\n/// Builder struct for a Protobuf message\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct MessageBuilder {\n\n /// Protobuf descriptor for the file the message belongs to\n\n pub file_descriptor: FileDescriptorProto,\n\n /// Protobuf descriptor for the message\n\n pub descriptor: DescriptorProto,\n\n /// Message name\n\n pub message_name: String,\n", "file_path": "src/message_builder.rs", "rank": 19, "score": 54186.012194738316 }, { "content": "fn find_field_descriptor(field_num: i32, descriptor: &DescriptorProto) -> anyhow::Result<FieldDescriptorProto> {\n\n descriptor.field.iter().find(|field| {\n\n if let Some(num) = field.number {\n\n num == field_num\n\n } else {\n\n false\n\n }\n\n })\n\n .cloned()\n\n .ok_or_else(|| anyhow!(\"Did not find a field with number {} in the descriptor\", field_num))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use bytes::{BufMut, Bytes, BytesMut};\n\n use expectest::prelude::*;\n\n use pact_plugin_driver::proto::InitPluginRequest;\n\n use prost::encoding::WireType;\n\n use prost::Message;\n\n use prost_types::{DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FileDescriptorSet};\n", "file_path": "src/message_decoder.rs", "rank": 20, "score": 53882.858963093546 }, { "content": "/// Match a single Protobuf message\n\npub fn match_message(\n\n message_name: &str,\n\n descriptors: &FileDescriptorSet,\n\n expected_request: &mut Bytes,\n\n actual_request: &mut Bytes,\n\n matching_rules: &MatchingRuleCategory,\n\n allow_unexpected_keys: bool\n\n) -> anyhow::Result<BodyMatchResult> {\n\n debug!(\"Looking for message '{}'\", message_name);\n\n let message_descriptor = find_message_type_by_name(message_name, descriptors)?;\n\n\n\n let expected_message = decode_message(expected_request, &message_descriptor, descriptors)?;\n\n debug!(\"expected message = {:?}\", expected_message);\n\n\n\n let actual_message = decode_message(actual_request, &message_descriptor, descriptors)?;\n\n debug!(\"actual message = {:?}\", actual_message);\n\n\n\n let plugin_config = hashmap!{};\n\n let diff_config = if allow_unexpected_keys {\n\n DiffConfig::AllowUnexpectedKeys\n\n } else {\n\n DiffConfig::NoUnexpectedKeys\n\n };\n\n let context = CoreMatchingContext::new(diff_config, matching_rules, &plugin_config);\n\n\n\n compare(&message_descriptor, &expected_message, &actual_message, &context,\n\n expected_request, descriptors)\n\n}\n\n\n", "file_path": "src/matching.rs", "rank": 21, "score": 52362.64698372159 }, { "content": "/// Match a Protobuf service call, which has an input and output message\n\npub fn match_service(\n\n service_name: &str,\n\n method_name: &str,\n\n descriptors: &FileDescriptorSet,\n\n expected_request: &mut Bytes,\n\n actual_request: &mut Bytes,\n\n rules: &MatchingRuleCategory,\n\n allow_unexpected_keys: bool,\n\n content_type: &ContentType\n\n) -> anyhow::Result<BodyMatchResult> {\n\n debug!(\"Looking for service '{}'\", service_name);\n\n let (_, service_descriptor) = find_service_descriptor(descriptors, service_name)?;\n\n trace!(\"Found service descriptor with name {:?}\", service_descriptor.name);\n\n\n\n let (method_name, service_part) = if method_name.contains(':') {\n\n method_name.split_once(':').unwrap_or((method_name, \"\"))\n\n } else {\n\n (method_name, \"\")\n\n };\n\n let method_descriptor = service_descriptor.method.iter().find(|method_desc| {\n", "file_path": "src/matching.rs", "rank": 22, "score": 52362.64698372159 }, { "content": "pub fn update_access_time() {\n\n let mut guard = SHUTDOWN_TIMER.lock().unwrap();\n\n *guard = Some(Instant::now());\n\n}\n", "file_path": "src/main.rs", "rank": 23, "score": 50903.60856215316 }, { "content": "/// Convert the message field data into a JSON value\n\npub fn field_data_to_json(\n\n field_data: Vec<ProtobufField>,\n\n descriptor: &DescriptorProto,\n\n descriptors: &FileDescriptorSet\n\n) -> anyhow::Result<serde_json::Value> {\n\n let mut object = hashmap!{};\n\n\n\n for field in field_data {\n\n if let Some(value) = descriptor.field.iter().find(|f| f.number.unwrap_or(-1) as u32 == field.field_num) {\n\n match &value.name {\n\n Some(name) => {\n\n object.insert(name.clone(), match &field.data {\n\n ProtobufFieldData::String(s) => serde_json::Value::String(s.clone()),\n\n ProtobufFieldData::Boolean(b) => serde_json::Value::Bool(*b),\n\n ProtobufFieldData::UInteger32(n) => json!(n),\n\n ProtobufFieldData::Integer32(n) => json!(n),\n\n ProtobufFieldData::UInteger64(n) => json!(n),\n\n ProtobufFieldData::Integer64(n) => json!(n),\n\n ProtobufFieldData::Float(n) => json!(n),\n\n ProtobufFieldData::Double(n) => json!(n),\n", "file_path": "src/utils.rs", "rank": 24, "score": 50903.60856215316 }, { "content": "/// If the message fields include the field with the given descriptor\n\npub fn find_message_field<'a>(message: &'a [ProtobufField], field_descriptor: &ProtobufField) -> Option<&'a ProtobufField> {\n\n message.iter().find(|v| v.field_num == field_descriptor.field_num)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 25, "score": 50174.113056221875 }, { "content": "#[tracing::instrument(ret, skip_all)]\n\npub fn decode_message<B>(\n\n buffer: &mut B,\n\n descriptor: &DescriptorProto,\n\n descriptors: &FileDescriptorSet\n\n) -> anyhow::Result<Vec<ProtobufField>>\n\n where B: Buf {\n\n let mut fields = vec![];\n\n\n\n while buffer.has_remaining() {\n\n let (field_num, wire_type) = decode_key(buffer)?;\n\n trace!(field_num, ?wire_type, \"read field header, bytes remaining = {}\", buffer.remaining());\n\n\n\n match find_field_descriptor(field_num as i32, descriptor) {\n\n Ok(field_descriptor) => {\n\n let data = match wire_type {\n\n WireType::Varint => {\n\n let varint = decode_varint(buffer)?;\n\n let t: Type = field_descriptor.r#type();\n\n match t {\n\n Type::Int64 => ProtobufFieldData::Integer64(varint as i64),\n", "file_path": "src/message_decoder.rs", "rank": 26, "score": 47769.4446906067 }, { "content": "def executeOnShell(String command, Closure closure = null) {\n\n executeOnShell(command, new File(System.properties.'user.dir'), closure)\n\n}\n\n\n", "file_path": "release.groovy", "rank": 27, "score": 43129.863262192506 }, { "content": "/// Return the last name in a dot separated string\n\npub fn last_name(entry_type_name: &str) -> &str {\n\n entry_type_name.split('.').last().unwrap_or(entry_type_name)\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 28, "score": 41562.21236209285 }, { "content": "fn field_type_name(field: &FieldValueInner) -> anyhow::Result<String> {\n\n Ok(match field.proto_type {\n\n Type::Double => \"double\".to_string(),\n\n Type::Float => \"float\".to_string(),\n\n Type::Int64 => \"int64\".to_string(),\n\n Type::Uint64 => \"uint64\".to_string(),\n\n Type::Int32 => \"int32\".to_string(),\n\n Type::Fixed64 => \"fixed64\".to_string(),\n\n Type::Fixed32 => \"fixed32\".to_string(),\n\n Type::Bool => \"bool\".to_string(),\n\n Type::String => \"string\".to_string(),\n\n Type::Group => \"group\".to_string(),\n\n Type::Message => {\n\n let message = field.descriptor.type_name.as_ref()\n\n .ok_or_else(|| anyhow!(\"Type name is missing from the descriptor for message field\"))?;\n\n format!(\"message {}\", message)\n\n },\n\n Type::Bytes => \"bytes\".to_string(),\n\n Type::Uint32 => \"uint32\".to_string(),\n\n Type::Enum => {\n", "file_path": "src/message_builder.rs", "rank": 29, "score": 38443.764281174255 }, { "content": "def executeOnShell(String command, File workingDir, Closure closure = null) {\n\n println command\n", "file_path": "release.groovy", "rank": 30, "score": 38082.52288195557 }, { "content": "fn os_type(os_info: Bitness, arch: &str, os: &str) -> String {\n\n match os {\n\n \"linux\" => match arch {\n\n \"x86\" => \"linux-x86_32\",\n\n \"x86_64\" => \"linux-x86_64\",\n\n \"aarch64\" => \"linux-aarch_64\",\n\n \"s390x\" => \"linux-s390_64\",\n\n _ => \"unknown\"\n\n }.to_string(),\n\n \"macos\" => format!(\"osx-{}\", arch),\n\n \"windows\" => format!(\"win{}\", match os_info {\n\n Bitness::X32 => \"32\",\n\n Bitness::X64 => \"64\",\n\n _ => \"64\"\n\n }),\n\n _ => \"unknown\".to_string()\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "src/protoc.rs", "rank": 31, "score": 37225.90100686937 }, { "content": " VerificationOptions,\n\n verify_provider_async\n\n};\n\nuse pact_verifier::callback_executors::ProviderStateExecutor;\n\nuse prost::bytes::BytesMut;\n\nuse prost::Message;\n\nuse reqwest::Client;\n\nuse rocket::{Data, Request};\n\nuse rocket::data::{ByteUnit, FromData, Outcome};\n\nuse rocket::http::{ContentType, Status};\n\nuse rocket::outcome::Outcome::{Failure, Success};\n\nuse serde_json::Value;\n\nuse test_log::test;\n\nuse tracing::{debug, error};\n\n\n\nuse pact_protobuf_plugin::built_info;\n\nuse pact_protobuf_plugin::server::ProtobufPactPlugin;\n\n\n\n// We are not using provider states, so we define a executor that does nothing\n", "file_path": "tests/pact_verify.rs", "rank": 32, "score": 32473.01276195833 }, { "content": "use std::collections::HashMap;\n\nuse std::env;\n\nuse std::sync::Arc;\n\n\n\nuse anyhow::anyhow;\n\nuse async_trait::async_trait;\n\nuse expectest::prelude::*;\n\nuse maplit::hashmap;\n\nuse pact_models::http_utils::HttpAuth;\n\nuse pact_models::prelude::ProviderState;\n\nuse pact_models::v4::message_parts::MessageContents;\n\nuse pact_plugin_driver::plugin_manager::shutdown_plugins;\n\nuse pact_plugin_driver::proto::InitPluginRequest;\n\nuse pact_plugin_driver::proto::pact_plugin_server::PactPlugin;\n\nuse pact_verifier::{\n\n FilterInfo,\n\n NullRequestFilterExecutor,\n\n PactSource,\n\n ProviderInfo,\n\n PublishOptions,\n", "file_path": "tests/pact_verify.rs", "rank": 33, "score": 32470.22805957995 }, { "content": " }\n\n } else {\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Request did not contain any data\")))\n\n }\n\n}\n\n\n\n// Pact verification test. This first starts up a Rocket server that can provide the Protobuf\n\n// messages required by the Pact verifier.\n\n#[test(tokio::test(flavor = \"multi_thread\", worker_threads = 1))]\n\nasync fn verify_plugin() {\n\n // Test Setup\n\n let provider_info = ProviderInfo {\n\n name: \"plugin\".to_string(),\n\n port: Some(8000),\n\n .. ProviderInfo::default()\n\n };\n\n // Set the source to fetch from the Pact broker\n\n let source = PactSource::BrokerWithDynamicConfiguration {\n\n provider_name: \"plugin\".to_string(),\n\n broker_url: \"https://pact-foundation.pactflow.io\".to_string(),\n", "file_path": "tests/pact_verify.rs", "rank": 34, "score": 32468.323047537113 }, { "content": " (Status::BadRequest, (ContentType::Text, Vec::from(\"No content type for the provided message\")))\n\n }\n\n}\n\n\n\n// Handle the init plugin request message and return the response. We do this by calling the actual\n\n// plugin server init_plugin method, but pass in the Protobuf message we get from the verifier.\n\nasync fn init_plugin_request(request_message: &MessageRequest) -> (Status, (ContentType, Vec<u8>)) {\n\n if let Some(data) = request_message.contents.contents.value() {\n\n match InitPluginRequest::decode(data) {\n\n Ok(request) => {\n\n debug!(\"Got init plugin request {:?}\", request);\n\n\n\n // This is were we call our actual service method, passing in the input message\n\n // and getting the output message as the response, which we then return in encoded form\n\n let plugin = ProtobufPactPlugin::new();\n\n match plugin.init_plugin(tonic::Request::new(request)).await {\n\n Ok(response) => {\n\n debug!(\"Got init plugin response {:?}\", response);\n\n let mut buffer = BytesMut::new();\n\n match response.get_ref().encode(&mut buffer) {\n", "file_path": "tests/pact_verify.rs", "rank": 35, "score": 32465.81990002826 }, { "content": " Ok(_) => {\n\n (Status::Ok, (ContentType::new(\"application\", \"protobuf\").with_params((\"message\", \"InitPluginResponse\")),\n\n buffer.to_vec()))\n\n }\n\n Err(err) => {\n\n error!(\"Failed to write response to buffer - {}\", err);\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Failed to write response to buffer\")))\n\n }\n\n }\n\n }\n\n Err(err) => {\n\n error!(\"Failed to generate response for InitPluginRequest - {}\", err);\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Failed to generate response message\")))\n\n }\n\n }\n\n }\n\n Err(err) => {\n\n error!(\"Failed to parse request message - {}\", err);\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Failed to parse request message\")))\n\n }\n", "file_path": "tests/pact_verify.rs", "rank": 36, "score": 32465.58089741542 }, { "content": " provider_tags: vec![\"pact-protobuf-plugin\".to_string()],\n\n provider_branch: None\n\n })\n\n } else {\n\n None\n\n };\n\n let ps_executor = NoopProviderStateExecutor {};\n\n\n\n // Start the rocket server\n\n let server = rocket::build()\n\n .mount(\"/\", rocket::routes![messages])\n\n .ignite()\n\n .await.expect(\"Could not start the Rocket server\");\n\n let shutdown = server.shutdown();\n\n tokio::spawn(server.launch());\n\n\n\n // Execute the verification\n\n let result = verify_provider_async(\n\n provider_info,\n\n vec![source],\n", "file_path": "tests/pact_verify.rs", "rank": 37, "score": 32465.084068422177 }, { "content": " enable_pending: false,\n\n include_wip_pacts_since: None,\n\n provider_tags: vec![],\n\n provider_branch: None,\n\n selectors: vec![],\n\n auth: Some(HttpAuth::Token(env::var(\"PACTFLOW_TOKEN\")\n\n .expect(\"The PACTFLOW_TOKEN environment variable must be set\").to_string())),\n\n links: vec![]\n\n };\n\n // Set the version to be the plugin name + version + git SHA\n\n let mut version = \"pact-protobuf-plugin:\".to_string();\n\n version.push_str(env!(\"CARGO_PKG_VERSION\"));\n\n version.push_str(\"+\");\n\n version.push_str(built_info::GIT_COMMIT_HASH.unwrap_or(\"0\"));\n\n\n\n let options: VerificationOptions<NullRequestFilterExecutor> = VerificationOptions::default();\n\n let publish_options = if env::var(\"CI\").map(|v| v == \"true\").unwrap_or(false) {\n\n Some(PublishOptions {\n\n provider_version: Some(version),\n\n build_url: None,\n", "file_path": "tests/pact_verify.rs", "rank": 38, "score": 32464.917976940895 }, { "content": "// Rocket server used to pass the Protobuf messages from/to the verifier. Each request should\n\n// contain the content type which will have a message attribute telling us which message it is\n\n// for.\n\n#[rocket::post(\"/\", data = \"<request>\")]\n\nasync fn messages(request: MessageRequest) -> (Status, (ContentType, Vec<u8>)) {\n\n debug!(\"Got request = {:?}\", request);\n\n if let Some(content_type) = request.contents.message_content_type() {\n\n if content_type.sub_type == \"protobuf\" {\n\n if let Some(message_type) = content_type.attributes.get(\"message\") {\n\n match message_type.as_str() {\n\n \"InitPluginRequest\" => init_plugin_request(&request).await,\n\n _ => (Status::BadRequest, (ContentType::Text, Vec::from(\"Unknown protobuf message type provided\")))\n\n }\n\n } else {\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Not a protobuf message type provided\")))\n\n }\n\n } else {\n\n (Status::BadRequest, (ContentType::Text, Vec::from(\"Not a protobuf message\")))\n\n }\n\n } else {\n", "file_path": "tests/pact_verify.rs", "rank": 39, "score": 32464.202771706125 }, { "content": " Ok(contents) => Success(MessageRequest { contents }),\n\n Err(err) => Failure((Status::UnprocessableEntity, anyhow!(err)))\n\n }\n\n } else {\n\n Failure((Status::UnprocessableEntity, anyhow!(\"Missing request\")))\n\n }\n\n }\n\n Err(err) => Failure((Status::UnprocessableEntity, anyhow!(\"Failed to parse JSON: {}\", err)))\n\n }\n\n Err(err) => Failure((Status::UnprocessableEntity, anyhow!(err)))\n\n }\n\n } else {\n\n Failure((Status::UnprocessableEntity, anyhow!(\"Expected JSON, got {}\", content_type)))\n\n }\n\n } else {\n\n Failure((Status::UnprocessableEntity, anyhow!(\"No content type\")))\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/pact_verify.rs", "rank": 40, "score": 32460.736372989577 }, { "content": " FilterInfo::None,\n\n vec![],\n\n &options,\n\n publish_options.as_ref(),\n\n &Arc::new(ps_executor), None\n\n ).await;\n\n\n\n // Need to shutdown all the things, otherwise we could leave hanging plugin processes.\n\n shutdown.notify();\n\n shutdown_plugins();\n\n\n\n // Confirm that the verification was successful\n\n expect!(result.unwrap().result).to(be_true());\n\n}\n", "file_path": "tests/pact_verify.rs", "rank": 41, "score": 32460.354028837573 }, { "content": "fn build_grpc_request(\n\n body: &OptionalBody,\n\n metadata: &HashMap<String, proto::MetadataValue>,\n\n file_desc: &FileDescriptorSet,\n\n input_desc: &DescriptorProto\n\n) -> anyhow::Result<tonic::Request<DynamicMessage>> {\n\n let mut bytes = body.value().unwrap_or_default();\n\n let message_fields = decode_message(&mut bytes, input_desc, file_desc)?;\n\n let mut request = tonic::Request::new(DynamicMessage::new(input_desc, &message_fields));\n\n let request_metadata = request.metadata_mut();\n\n for (key, md) in metadata {\n\n if key != \"request-path\" {\n\n if let Some(value) = &md.value {\n\n match value {\n\n proto::metadata_value::Value::NonBinaryValue(value) => {\n\n let str_value = proto_value_to_string(value).unwrap_or_default();\n\n match str_value.parse::<MetadataValue<Ascii>>() {\n\n Ok(value) => match key.parse::<MetadataKey<Ascii>>() {\n\n Ok(key) => {\n\n request_metadata.insert(key, value.clone());\n", "file_path": "src/verification.rs", "rank": 42, "score": 29420.688418021047 }, { "content": "/// Create a field value of type google.protobuf.Struct\n\nfn build_struct_field(\n\n path: &DocPath,\n\n message_builder: &mut MessageBuilder,\n\n field_type: MessageFieldValueType,\n\n field_descriptor: &FieldDescriptorProto,\n\n field_name: &str,\n\n field_value: &Value,\n\n matching_rules: &mut MatchingRuleCategory,\n\n generators: &mut HashMap<String, Generator>\n\n) -> anyhow::Result<Option<MessageFieldValue>> {\n\n trace!(\">> build_struct_field('{}', {}, {:?}, {:?}, {:?}, {:?})\", path, field_name, field_value,\n\n message_builder, matching_rules, generators);\n\n\n\n match field_value {\n\n Value::Object(map) => if let Some(matching_def) = map.get(\"pact:match\") {\n\n // if (fieldsMap.containsKey(\"pact:match\")) {\n\n // val expression = fieldsMap[\"pact:match\"]!!.stringValue\n\n // when (val ruleDefinition = MatchingRuleDefinition.parseMatchingRuleDefinition(expression)) {\n\n // is Ok -> TODO()\n\n // is Err -> {\n", "file_path": "src/protobuf.rs", "rank": 43, "score": 29353.73772753172 }, { "content": "##### Service method provider\n\n\n\nThe Pact framework (using this plugin) can test gRPC service method calls to a running gRPC server. The server can be\n\ntested by either using a unit test, or by using the Rust Verifier CLI. It will need the Pact file created from the\n\nconsumer test with the compiled protobuf descriptors in it (these will have been added by this plugin during the consumer test).\n\n\n\nFor an example Java unit test: See the [example gRPC verification test](https://github.com/pact-foundation/pact-plugins/blob/main/examples/gRPC/area_calculator/provider-jvm/server/src/test/java/io/pact/example/grpc/provider/PactVerificationTest.java).\n\n\n\nBy starting the gRPC server, we can then also use the [Pact Verifier](https://github.com/pact-foundation/pact-reference/tree/master/rust/pact_verifier_cli) to check it.\n\n\n\n###### For example (using the [example gRPC project](https://github.com/pact-foundation/pact-plugins/blob/main/examples/gRPC/area_calculator/provider-jvm)):\n\n\n\n_Running the gRPC server:_\n\n\n\n```console\n\ngRPC/area_calculator/provider-jvm: \n", "file_path": "README.md", "rank": 44, "score": 19735.661558095042 }, { "content": "##### Service method provider\n\n\n\nThe Protocol Buffer service providers normally extend an interface generated by the protoc compiler. To test them, we\n\nneed a mechanism to get the Pact verifier to pass in the input message from the Pact file and then get the output message\n\nfrom the service and compare that to the output message from the Pact file.\n\n\n\nWe can use the same mechanism as for message pact (see [Non-HTTP testing (Message Pact)](https://docs.pact.io/getting_started/how_pact_works/#non-http-testing-message-pact)),\n\nwere we create an HTTP proxy server to receive the input message from the verifier and invoke the service method implementation\n\nto get the output message.\n\n\n\nThere are two main ways to run the verification:\n\n\n\n1. Execute the Pact verifier, providing the source of the Pact file, and configure it to use the HTTP mock server.\n\n2. Write a test in the provider's code base. For an example of doing this in Rust, see [a test that verifies this plugin](tests/pact_verify.rs).\n\n\n\n### The Protobuf test configuration\n\n\n\nThe consumer tests need to get the plugin loaded and configure the expected messages to use in the test. This is done\n\nusing the `usingPlugin` (or `using_plugin`, depending on the language implementation) followed by the content for the test\n\nin some type of map form.\n\n\n\nFor each field of the message that we want in the contract, we define an entry with the field name as the key and\n\na matching definition as the value. For documentation on the matching definition format, see [Matching Rule definition expressions](https://github.com/pact-foundation/pact-plugins/blob/main/docs/matching-rule-definition-expressions.md).\n\n\n\nFor example, for a JVM test (taken from [Protocol Buffer Java examples](https://developers.google.com/protocol-buffers/docs/javatutorial)) we would use the PactBuilder class:\n\n\n\n```protobuf\n\n// this example taken from https://developers.google.com/protocol-buffers/docs/javatutorial#defining-your-protocol-format\n\nmessage Person {\n\n string name = 1;\n\n int32 id = 2;\n", "file_path": "README.md", "rank": 45, "score": 19735.58617832766 }, { "content": " string email = 3;\n\n\n\n enum PhoneType {\n\n MOBILE = 0;\n\n HOME = 1;\n\n WORK = 2;\n\n }\n\n\n\n message PhoneNumber {\n\n string number = 1;\n\n PhoneType type = 2 [default = HOME];\n\n }\n\n\n\n repeated PhoneNumber phones = 4;\n\n}\n\n```\n\n\n\n```java\n\nbuilder\n\n // Tell the Pact framework to load the protobuf plugin \n\n .usingPlugin(\"protobuf\")\n\n \n\n // Define the expected message (description) and the type of interaction. Here is is an asynchronous message.\n\n .expectsToReceive(\"Person Message\", \"core/interaction/message\")\n\n \n\n // Provide the data for the test\n\n .with(Map.of(\n\n // For a single asynchronous message, we just provide the contents for the message. For RPC service calls, there\n\n // will be a request and response message\n\n \"message.contents\", Map.of(\n\n // set the content type, so the Pact framework will know to send it to the Protobuf plugin\n\n \"pact:content-type\", \"application/protobuf\",\n\n // pact:proto contains the source proto file, which is required to be able to test the interaction\n\n \"pact:proto\", filePath(\"addressbook.proto\"),\n\n // provide the name of the message type we are going to test (defined in the proto file)\n\n \"pact:message-type\", \"Person\",\n\n \n\n // We can then setup the expected fields of the message\n\n \"name\", \"notEmpty('Fred')\", // The name field must not be empty, and we use Fred in our tests\n\n \"id\", \"matching(regex, '100\\\\d+', '1000001')\", // The id field must match the regular expression, and we use 1000001 in the tests \n\n \"email\", \"matching(regex, '\\\\w+@[a-z0-9\\\\.]+', '[email protected]')\" // Emails must match a regular expression\n\n\n\n // phones is a repeated field, so we define an example that all values must match against\n\n \"phones\", Map.of(\n\n \"number\", \"matching(regex, '(\\\\+\\\\d+)?(\\\\d+\\\\-)?\\\\d+\\\\-\\\\d+', '+61-03-1234-5678')\" // Phone numbers must match a regular expression\n\n // We don't include type, as it is an emum and has a default value, so it is optional\n\n // but we could have done something like matching(equalTo, 'WORK')\n\n )\n\n )\n\n ))\n\n```\n\n\n", "file_path": "README.md", "rank": 46, "score": 19734.523293315313 }, { "content": "## Requirements to use it\n\n\n\nThis plugin provides matching and verification of Protobuf proto3 encoded messages to the Pact contract testing framework. It requires a version\n\nof the Pact framework that supports the [V4 Pact specification](https://github.com/pact-foundation/pact-specification/tree/version-4) \n\nas well as the [Pact plugin framework](https://github.com/pact-foundation/pact-plugins).\n\n\n\nSupported Pact versions:\n\n- [Pact-JVM v4.4.x](https://github.com/pact-foundation/pact-jvm)\n\n- [Pact-Rust Consumer v0.9.x](https://github.com/pact-foundation/pact-reference/tree/master/rust/pact_consumer)\n\n- [Pact-Rust Verifier v0.9.x](https://github.com/pact-foundation/pact-reference/tree/master/rust/pact_verifier_cli)\n\n\n\nTo support compiling Protocol Buffer proto files requires a version of the [Protocol Buffer compiler](https://github.com/protocolbuffers/protobuf).\n\n\n\n## Installation\n\n\n\nThe executable binaries and plugin manifest file for the plugin can be downloaded from the project [releases page](../releases). There will be an executable for each\n\noperating system and architecture. If your particular operating system or architecture is not supported, please send\n\na request to [[email protected]]([email protected]) with the details.\n\n\n", "file_path": "README.md", "rank": 47, "score": 19733.838593449458 }, { "content": "## Using the plugin\n\n\n\nThis plugin will register itself with the Pact framework for the `application/protobuf` and `application/gRPC` content types.\n\n\n\nUsing this plugin, you can write Pact tests that verify either a single Protobuf message (i.e. a message provider sends\n\na single, or one-shot, message to a consumer), or you can verify a service method call where there is an input message \n\nand an output message.\n\n\n\nSingle message tests are supported by using the V4 asynchronous message Pact format, and the service method calls use the\n\nV4 synchronous message Pact format.\n\n\n\n### Testing an interaction with a single Protobuf message\n\n\n\nFor an overview how asynchronous messages work with Pact, see [Non-HTTP testing (Message Pact)](https://docs.pact.io/getting_started/how_pact_works/#non-http-testing-message-pact).\n\n\n\nIn this scenario, a message provider writes a Protocol Buffer message to some one-way transport mechanism, like a message queue, and a consumer\n\nthen reads it. With this style of testing, the transport mechanism is abstracted away.\n\n\n\n#### Protocol Buffer message consumer\n\n\n\nThe message consumer test is written using the Pact Message test DSL. The test DSL defines the expected message format,\n\nand then the consumer is tested with an example message generated by the test framework.\n\n\n\nFor an example of a message consumer test:\n\n* [Java example consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/examples/protobuf/protobuf-consumer-jvm/src/test/java/io/pact/example/protobuf/provider/PactConsumerTest.java)\n\n* [Rust example consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/examples/protobuf/protobuf-consumer-rust/src/lib.rs)\n\n\n", "file_path": "README.md", "rank": 48, "score": 19733.669873569295 }, { "content": "<a href=\"https://pactflow.io\"><img src=\"docs/pactflow-logo-s.png\" alt=\"pactflow logo\" height=\"60px\" align=\"right\"></a>\n\n\n\n# Pact Protobuf/gRPC Plugin [![Pact-Protobuf-Plugin Build](https://github.com/pactflow/pact-protobuf-plugin/actions/workflows/build.yml/badge.svg)](https://github.com/pactflow/pact-protobuf-plugin/actions/workflows/build.yml)\n\n\n\n> Pact plugin for testing messages and gRPC service calls encoded with as [Protocol buffers](https://developers.google.com/protocol-buffers)\n\n> using the [Pact](https://docs.pact.io) contract testing framework.\n\n\n\n## About this plugin\n\n\n\nThis plugin provides support for matching and verifying Protobuf messages and gRPC service calls. It fits into the\n\n[Pact contract testing framework](https://docs.pact.io) and extends Pact testing for [Protocol buffer](https://developers.google.com/protocol-buffers) \n\npayloads and gRPC. \n\n\n\n## Table of Content\n\n\n\n- [Requirements to use it](#requirements-to-use-it)\n\n- [Installation](#installation)\n\n - [Installing the plugin](#installing-the-plugin)\n\n - [Installing the Protocol buffer protoc compiler](#installing-the-protocol-buffer-protoc-compiler) \n\n- [Supported features](#supported-features)\n\n- [Unsupported features](#unsupported-features)\n\n- [Using the plugin](#using-the-plugin)\n\n - [Testing an interaction with a single Protobuf message](#testing-an-interaction-with-a-single-protobuf-message)\n\n - [Testing a gRPC service interaction](#testing-a-grpc-service-interaction)\n\n- [Support](#support)\n\n- [Contributing to the plugin](#contributing)\n\n- [Development Roadmap](#development-roadmap)\n\n\n", "file_path": "README.md", "rank": 49, "score": 19733.5130301164 }, { "content": "### Running the tests\n\n\n\nYou can run all the unit tests by executing `cargo test --lib`.\n\n\n\nThere is a Pact test that verifies the plugin aqainst the Pact file published to [pact-foundation.pactflow.io](https://pact-foundation.pactflow.io).\n\nRunning this test requires a Pactflow API token and the plugin to be built and installed. See the installation instructions above.\n\nThe test is run using `cargo test --test pact_verify`.\n\n\n\n## Development Roadmap\n\n\n\nPact plugin development board: https://github.com/pact-foundation/pact-plugins/projects/1\n\n\n\n## License and Copyright\n\n\n\nThis plugin is released under the **MIT License** and is copyright © 2021-22 [Pactflow](https://pactflow.io).\n\n\n\nThe Pactflow logos are copyright © [Pactflow](https://pactflow.io) and may not be used without permission.\n", "file_path": "README.md", "rank": 50, "score": 19733.439441036735 }, { "content": "#### Testing a gRPC service method interaction without a gRPC server\n\n\n\nIf you can mock out the gRPC channel or stub, it is fairly easy to test the service method call without requiring a\n\ngRPC server.\n\n\n\n##### Service method consumer\n\n\n\nTo test the service message consumer, we write a Pact test that defines the expected input (or request) message and the \n\nexpected output (or response message). The Pact test framework will generate an example input and output message.\n\n\n\nTo execute the test, we need to intercept the service method call and verify that the message the consumer generated was\n\ncorrect, then we return the output message and verify that the consumer processed it correctly. This can be achieved using\n\na test mocking library.\n\n\n\nFor an example:\n\n* [JVM example service consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/drivers/jvm/core/src/test/groovy/io/pact/plugins/jvm/core/DriverPactTest.groovy#L116)\n\n* [Rust example service consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/drivers/rust/driver/tests/pact.rs#L43)\n\n\n", "file_path": "README.md", "rank": 51, "score": 19733.418506701088 }, { "content": "port number to the verifier.\n\n\n\n```console\n\ngRPC/area_calculator/provider-jvm: \n\n❯ pact_verifier_cli -f ../consumer-jvm/build/pacts/protobuf-consumer-area-calculator-provider.json -p 37621\n\n\n\nVerifying a pact between protobuf-consumer and area-calculator-provider\n\n\n\n calculate rectangle area request\n\n\n\n Test Name: io.pact.example.grpc.consumer.PactConsumerTest.calculateRectangleArea(MockServer, SynchronousMessages)\n\n\n\n Given a Calculator/calculate request\n\n with an input .area_calculator.ShapeMessage message\n\n will return an output .area_calculator.AreaResponse message [OK]\n\n```\n\n\n", "file_path": "README.md", "rank": 52, "score": 19733.38841486069 }, { "content": "## Support\n\n\n\nJoin us on slack [![slack](https://slack.pact.io/badge.svg)](https://slack.pact.io) in the **#protobufs** channel\n\n\n\nor\n\n\n\n Twitter: @pact_up\n\n Stack Overflow: stackoverflow.com/questions/tagged/pact\n\n\n\n## Contributing\n\n\n\nPRs are always welcome!\n\n\n\nFor details on the V4 Pact specification, refer to https://github.com/pact-foundation/pact-specification/tree/version-4\n\n\n\nFor details on the Pact plugin framework, refer to https://github.com/pact-foundation/pact-plugins\n\n\n\n### Raising defects\n\n\n\nBefore raising an issue, make sure you have checked the open and closed issues to see if an answer is provided there.\n\nThere may also be an answer to your question on [stackoverflow](https://stackoverflow.com/questions/tagged/pact).\n\n\n\nPlease provide the following information with your issue to enable us to respond as quickly as possible.\n\n\n\n1. The relevant versions of the packages you are using (plugin and Pact versions).\n\n1. The steps to recreate your issue.\n\n1. An executable code example where possible.\n\n\n\n### New features / changes\n\n\n\n1. Fork it\n\n1. Create your feature branch (git checkout -b my-new-feature)\n\n1. Commit your changes (git commit -am 'feat: Add some feature')\n\n1. Push to the branch (git push origin my-new-feature)\n\n1. Create new Pull Request\n\n\n\n#### Commit messages\n\n\n\nWe follow the [Conventional Changelog](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md)\n\nmessage conventions. Please ensure you follow the guidelines.\n\n\n\n### Building the plugin\n\n\n\nTo build the plugin, you need a working Rust environment (version 1.58+). Refer to the [Rust Guide](https://www.rust-lang.org/learn/get-started).\n\n\n\nThe build tool used is `cargo` and you can build the plugin by running `cargo build`. This will compile the plugin and \n\nput the generated files in `target/debug`. The main plugin executable is `pact-protobuf-plugin`\n\nand this will need to be copied into the Pact plugin directory. See the installation instructions above.\n\n\n", "file_path": "README.md", "rank": 53, "score": 19733.2666750323 }, { "content": "# 0.1.1 - Support verifying gRPC requests\n\n\n\n* d42a5c7 - chore: use the published version of pact-plugin-driver (Ronald Holshausen, Mon Apr 11 17:40:04 2022 +1000)\n\n* 0f2d989 - Revert \"update changelog for release 0.1.1\" (Ronald Holshausen, Mon Apr 11 17:25:10 2022 +1000)\n\n* b4f59eb - update changelog for release 0.1.1 (Ronald Holshausen, Mon Apr 11 17:22:23 2022 +1000)\n\n* d88641e - fix: add the wire type into the failure message (Ronald Holshausen, Mon Apr 11 14:41:13 2022 +1000)\n\n* f0cd56e - fix: handle case where actual field does not match expected discriptor (Ronald Holshausen, Mon Apr 11 14:36:41 2022 +1000)\n\n* 8065bff - fix: handle additional fields from the provider (Ronald Holshausen, Mon Apr 11 13:57:16 2022 +1000)\n\n* 453a215 - chore: fix clippy violations (Ronald Holshausen, Mon Apr 11 11:36:27 2022 +1000)\n\n* f33a8ae - chore: cleanup compiler messages (Ronald Holshausen, Mon Apr 11 11:13:56 2022 +1000)\n\n* 5a4915e - feat: initial attempt at verifcation (Ronald Holshausen, Fri Apr 8 14:30:27 2022 +1000)\n\n* 377f010 - feat: Initial gRPC request implementation for verifying (Ronald Holshausen, Thu Apr 7 12:57:45 2022 +1000)\n\n* 1a907fa - feat: implemented the plubming for verifing requests (Ronald Holshausen, Wed Apr 6 09:17:15 2022 +1000)\n\n* 66e0f38 - bump version to 0.1.1 (Ronald Holshausen, Thu Mar 24 17:02:48 2022 +1100)\n\n\n", "file_path": "CHANGELOG.md", "rank": 54, "score": 19732.24257246421 }, { "content": "### Installing the plugin\n\nTo install the plugin requires the plugin executable binary as well as the plugin manifest file to be unpacked/copied into\n\na Pact plugin directory. By default, this will be `.pact/plugins/protobuf-<version>` in the home directory (i.e. `$HOME/.pact/plugins/protobuf-0.1.5`).\n\n\n\nExample installation of Linux version 0.1.5 (replace with the actual version you are using): \n\n1. Create the plugin directory if needed: `mkdir -p ~/.pact/plugins/protobuf-0.1.5`\n\n2. Download the plugin manifest into the directory: `wget https://github.com/pactflow/pact-protobuf-plugin/releases/download/v-0.1.5/pact-plugin.json -O ~/.pact/plugins/protobuf-0.1.3/pact-plugin.json`\n\n3. Download the plugin executable into the directory: `wget https://github.com/pactflow/pact-protobuf-plugin/releases/download/v-0.1.5/pact-protobuf-plugin-linux-x86_64.gz -O ~/.pact/plugins/protobuf-0.1.5/pact-protobuf-plugin.gz`\n\n4. Unpack the plugin executable: `gunzip -N ~/.pact/plugins/protobuf-0.1.5/pact-protobuf-plugin.gz`\n\n5. Make the plugin executable: `chmod +x ~/.pact/plugins/protobuf-0.1.5/pact-protobuf-plugin`\n\n\n\n**Note:** The unpacked executable name must match the `entryPoint` value in the manifest file. By default, this is\n\n`pact-protobuf-plugin` on unix* and `pact-protobuf-plugin.exe` on Windows.\n\n\n\n#### Overriding the default Pact plugin directory\n\n\n\nThe default plugin directory (`$HOME/.pact/plugins`) can be changed by setting the `PACT_PLUGIN_DIR` environment variable.\n\n\n", "file_path": "README.md", "rank": 55, "score": 19732.04623609676 }, { "content": "#### Verifying the message provider\n\n\n\nThe message provider is verified by getting it to generate a message, and then this is verified against the Pact file\n\nfrom the consumer. There are two main ways of verifying the provider:\n\n\n\n1. Write a test in the provider code base that can call the provider to generate the message. \n\n2. Use an HTTP proxy server that can call the provider and return the generated message, and then use a Pact framework verifier to verify it.\n\n\n\nFor an example of the latter form, see [Simple Example Protobuf provider](https://github.com/pact-foundation/pact-plugins/tree/main/examples/protobuf/protobuf-provider).\n\n\n\n### Testing a gRPC service method interaction\n\n\n\nWith a service method call, the consumer creates an input message, then invokes a service method and gets an output message\n\nas the response. The most common service call is via the gRPC framework.\n\n\n\n#### Testing a gRPC service method interaction with a gRPC server\n\n\n\nThis plugin supports testing service method calls via gRPC on both the consumer and provider side.\n\n\n\n##### Service method consumer\n\n\n\nThe service method consumer is tested by configuring a test that starts a gRPC mock server based on the proto file for\n\nthe service. Each test first configures a Pact from the proto file. The Pact framework (via this plugin)\n\nwill then create a gRPC mock server for the test. The gRPC consumer can then be pointed at the mock server during the\n\ntest and send the input message and then verify the output message that is received back.\n\n\n\nFor an example:\n\n* [JVM example gRPC consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/examples/gRPC/area_calculator/consumer-jvm/src/test/java/io/pact/example/grpc/consumer/PactConsumerTest.java)\n\n* [Rust example gRPC consumer test](https://github.com/pact-foundation/pact-plugins/blob/main/examples/gRPC/area_calculator/consumer-rust/src/lib.rs)\n\n\n", "file_path": "README.md", "rank": 56, "score": 19731.899902635432 }, { "content": "❯ ./gradlew run\n\n\n\n> Task :server:run\n\n14:56:17,785 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]\n\n14:56:17,786 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]\n\n14:56:17,787 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/home/ronald/Development/Projects/Pact/pact-plugins/examples/gRPC/area_calculator/provider-jvm/server/build/resources/main/logback.xml]\n\n14:56:17,862 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - debug attribute not set\n\n14:56:17,863 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - About to instantiate appender of type [ch.qos.logback.core.ConsoleAppender]\n\n14:56:17,869 |-INFO in ch.qos.logback.core.joran.action.AppenderAction - Naming appender as [STDOUT]\n\n14:56:17,874 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property\n\n14:56:17,928 |-INFO in ch.qos.logback.classic.joran.action.RootLoggerAction - Setting level of ROOT logger to ERROR\n\n14:56:17,928 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]\n\n14:56:17,930 |-ERROR in ch.qos.logback.core.joran.spi.Interpreter@13:36 - no applicable action for [io.grpc.netty], current ElementPath is [[configuration][io.grpc.netty]]\n\n14:56:17,930 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.\n\n14:56:17,932 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@2b662a77 - Registering current configuration as safe fallback point\n\n\n\nStarted calculator service on 37621\n\n<===========--> 87% EXECUTING [18s]\n\n> :server:run\n\n```\n\n\n\nWe can see that the gRPC server was started on a random port (37621 above). So we can then provide the Pact file and\n", "file_path": "README.md", "rank": 57, "score": 19731.113963836782 }, { "content": "# 0.1.7 - Bugfix Release\n\n\n\n* 9697164 - fix: need to consider the default values when comparing with a missing field value (Ronald Holshausen, Fri May 27 16:02:49 2022 +1000)\n\n* ad9c37b - chore: update the tracing events for matching payloads (Ronald Holshausen, Fri May 27 10:35:07 2022 +1000)\n\n* 8dc4c17 - fix: disable ansi mode so the log file is more readable (Ronald Holshausen, Thu May 26 14:19:17 2022 +1000)\n\n* 820613d - chore: Upgrade to pact-plugin-driver 0.1.8 (Ronald Holshausen, Thu May 26 14:18:43 2022 +1000)\n\n* 6a12675 - chore: no point logging that you can not install logging (Ronald Holshausen, Wed May 25 14:19:39 2022 +1000)\n\n* 11ddc11 - bump version to 0.1.7 (Ronald Holshausen, Wed May 25 13:37:30 2022 +1000)\n\n\n\n# 0.1.6 - Bugfix Release\n\n\n\n* 580baba - fix: do not shutdown server for a get_mock_server_results request (Ronald Holshausen, Tue May 24 17:04:02 2022 +1000)\n\n* 0a3cb5f - feat: implement method for mock server results for FFI functions (Ronald Holshausen, Tue May 24 16:44:15 2022 +1000)\n\n* 009efa0 - chore: add the install script to the release build (Ronald Holshausen, Tue May 24 16:29:14 2022 +1000)\n\n* 2f4556b - chore: correct the install plugin script (Ronald Holshausen, Tue May 24 11:51:17 2022 +1000)\n\n* 593dc63 - core: add bash script to install plugin (Ronald Holshausen, Tue May 24 10:25:22 2022 +1000)\n\n* b998318 - fix: correct the installation docs to make the plugin executable (Ronald Holshausen, Mon May 16 14:50:55 2022 +1000)\n\n* 8f7956c - fix: correct the installation docs to make the plugin executable (Ronald Holshausen, Mon May 16 14:49:50 2022 +1000)\n\n* eb38ca2 - chore: fix pact test after upgrading deps (Ronald Holshausen, Tue May 10 13:56:08 2022 +1000)\n\n* 4a82af7 - bump version to 0.1.6 (Ronald Holshausen, Tue May 10 13:26:53 2022 +1000)\n\n\n", "file_path": "CHANGELOG.md", "rank": 58, "score": 19730.641826877687 }, { "content": "# 0.0.2 - Fix for interactions over HTTP\n\n\n\n* 7040854 - chore: add Rust version to readme (Ronald Holshausen, Tue Jan 25 16:04:09 2022 +1100)\n\n* 29803ec - fix: for interactions over HTTP, need to specify if the message is for the request or response (Ronald Holshausen, Tue Jan 25 15:29:11 2022 +1100)\n\n* 9283375 - chore: Update crates (Ronald Holshausen, Tue Jan 25 11:54:50 2022 +1100)\n\n* 5627fac - fix: print correct message in debug log (tienvo, Sat Jan 22 00:10:01 2022 +0700)\n\n* 49cdead - chore: Upgrade pavy-models, pact-matching and plugin driver crates (Ronald Holshausen, Mon Jan 17 11:35:35 2022 +1100)\n\n* 05c4df9 - chore: update readme (Ronald Holshausen, Fri Jan 14 14:12:44 2022 +1100)\n\n* 8b08746 - chore: update readme (Ronald Holshausen, Fri Jan 14 14:10:42 2022 +1100)\n\n* faa350c - chore: update release script (Ronald Holshausen, Fri Jan 14 10:47:45 2022 +1100)\n\n* 2dd98a9 - bump version to 0.0.2 (Ronald Holshausen, Fri Jan 14 10:45:27 2022 +1100)\n\n\n\n# 0.0.1 - configurable logging\n\n\n\n* c5a09ce - feat: add configurable logging, default logging to also write to a file (Ronald Holshausen, Thu Jan 13 17:44:09 2022 +1100)\n\n* 9ed4b00 - chore: update readme (Ronald Holshausen, Wed Jan 5 11:47:22 2022 +1100)\n\n* e966520 - chore: update readme (Ronald Holshausen, Wed Jan 5 11:37:03 2022 +1100)\n\n* f54b575 - chore: update readme (Ronald Holshausen, Wed Jan 5 10:12:21 2022 +1100)\n\n* b8598ec - chore: update readme (Ronald Holshausen, Tue Jan 4 16:54:55 2022 +1100)\n\n* a02903f - chore: update readme (Ronald Holshausen, Tue Jan 4 16:23:59 2022 +1100)\n\n* 32ebe6a - chore: update readme (Ronald Holshausen, Tue Jan 4 15:56:02 2022 +1100)\n\n* 8780e10 - chore: update readme (Ronald Holshausen, Tue Jan 4 14:39:18 2022 +1100)\n\n* 5ae876c - chore: update readme (Ronald Holshausen, Tue Jan 4 14:27:12 2022 +1100)\n\n* fa5288e - chore: add readme (Ronald Holshausen, Tue Jan 4 13:48:57 2022 +1100)\n\n* 1a9ffd7 - chore: fix pact_matching to the githib version (Ronald Holshausen, Tue Jan 4 13:22:38 2022 +1100)\n\n* 5720d98 - chore: update plugin driver to 0.0.16 and pact verifier to 0.12.2 (Ronald Holshausen, Tue Jan 4 12:15:43 2022 +1100)\n\n* 8c3a54f - chore: Upgrade pact_verifier to 0.12.2 (Ronald Holshausen, Fri Dec 31 15:37:27 2021 +1100)\n\n* 3f97ae8 - fix: update pact-plugin-driver to 0.0.15 (fixes issue with version) (Ronald Holshausen, Fri Dec 31 15:17:25 2021 +1100)\n\n* 6bbf654 - chore: Update manifest file for release (Ronald Holshausen, Fri Dec 31 12:42:15 2021 +1100)\n\n* 1176114 - bump version to 0.0.1 (Ronald Holshausen, Fri Dec 31 12:22:39 2021 +1100)\n\n\n", "file_path": "CHANGELOG.md", "rank": 59, "score": 19729.75823268793 }, { "content": "## Logging\n\n\n\n_NOTE: Since 0.1.3, the logging was switched to the Rust tracing crate and a log configuration file is no longer supported._ \n\n\n\nThe plugin will log to both standard output and two files (log/plugin.log.* and log/plugin.log.json.*) in the plugin \n\ninstallation directory. Each file will be rolled per day and be suffixed with the current date. The JSON log file will\n\nbe formatted in the [bunyan format](https://github.com/trentm/node-bunyan).The log level will be set by the `LOG_LEVEL`\n\nenvironment variable that is passed into the plugin process (this should be set by the framework calling it).\n\n\n\n## Supported features\n\n\n\nThe plugin currently supports proto3 formatted messages and service calls.\n\n\n\nIt supports the following:\n\n* Scalar fields (Double, Float, Int64, Uint64, Int32, Uint32, Fixed64, Fixed32, Bool, Sfixed32, Sfixed64, Sint32, Sint64).\n\n* Variable length fields (String, Bytes).\n\n* Enum fields.\n\n* Embedded messages.\n\n* Map fields (with a string key).\n\n* Repeated fields.\n\n* oneOf fields.\n\n* gRPC Service method calls. \n\n\n\n## Unsupported features\n\n\n\nThe following features are currently unsupported, but may be supported in a later release:\n\n* Map fields with scalar keys.\n\n* Map fields with enum keys.\n\n* default values for fields.\n\n* packed fields.\n\n* required fields (note that this is deprecated in Proto 3).\n\n* Testing/verifying Protobuf options.\n\n* Testing/verifying gRPC service call metadata.\n\n\n\nThe following features will **not** be supported by this plugin:\n\n* proto2\n\n* Groups\n\n\n\nThe following features may be supported in a future release, but are not currently planned to be supported:\n\n* Map fields where the key is not a string or scalar value.\n\n* gRPC streaming (either oneway or bidirectional).\n\n\n", "file_path": "README.md", "rank": 60, "score": 19729.410534991814 }, { "content": "# 0.1.5 - Updated logging\n\n\n\n* 6b3c0ca - chore: update readme (Ronald Holshausen, Tue May 10 12:10:00 2022 +1000)\n\n* 4ec5788 - chore: cleanup unused imports (Ronald Holshausen, Tue May 10 11:58:22 2022 +1000)\n\n* 55c9fa5 - feat: add bunyan formatted JSON logs (Ronald Holshausen, Tue May 10 11:44:46 2022 +1000)\n\n* 3dae582 - chore: fix failing CI build (Ronald Holshausen, Tue May 10 11:14:40 2022 +1000)\n\n* 905b19e - feat: use tracing appender for a rolling log file instead of log4rs (Ronald Holshausen, Tue May 10 10:46:45 2022 +1000)\n\n* 5e547cf - bump version to 0.1.5 (Ronald Holshausen, Thu May 5 13:26:06 2022 +1000)\n\n\n\n# 0.1.4 - Bugfix Release\n\n\n\n* 45a9937 - fix(windows): Protoc does not support Windows paths that start with \\\\?\\ (Ronald Holshausen, Thu May 5 11:41:13 2022 +1000)\n\n* f1e14fc - fix(windows): Use native OS paths when execting protoc binary (Ronald Holshausen, Wed May 4 17:25:43 2022 +1000)\n\n* 997be06 - chore: update readme with gRPC support (Ronald Holshausen, Fri Apr 29 15:05:22 2022 +1000)\n\n* 071e150 - bump version to 0.1.4 (Ronald Holshausen, Fri Apr 29 09:58:27 2022 +1000)\n\n\n\n# 0.1.3 - Updated verification output\n\n\n\n* 57f7cbd - chore: fix the CI build (Ronald Holshausen, Fri Apr 29 09:22:44 2022 +1000)\n\n* 6f22d4e - chore: update dependencies (Ronald Holshausen, Fri Apr 29 09:14:53 2022 +1000)\n\n* 070ebbc - feat: add verification output for the verification call (Ronald Holshausen, Tue Apr 26 16:50:57 2022 +1000)\n\n* ab7d0d8 - bump version to 0.1.3 (Ronald Holshausen, Tue Apr 12 15:59:17 2022 +1000)\n\n\n\n# 0.1.2 - Bugfix Release\n\n\n\n* accda0d - feat: add a shutdown time of 10 minutes to avoid hanging processes (Ronald Holshausen, Tue Apr 12 15:22:38 2022 +1000)\n\n* fda0844 - fix(regression): gRPC implementaton broke verifying Protobuf messages (Ronald Holshausen, Tue Apr 12 12:45:52 2022 +1000)\n\n* 9993693 - chore: debugging CI build (Ronald Holshausen, Tue Apr 12 11:08:04 2022 +1000)\n\n* b319205 - bump version to 0.1.2 (Ronald Holshausen, Mon Apr 11 18:06:20 2022 +1000)\n\n\n", "file_path": "CHANGELOG.md", "rank": 61, "score": 19729.03973413941 }, { "content": "### Installing the Protocol buffer protoc compiler\n\n\n\nThe plugin can automatically download the correct version of the Protocol buffer compiler for the current operating system\n\nand architecture. By default, it will download the compiler from https://github.com/protocolbuffers/protobuf/releases\n\nand then unpack it into the plugin's installation directory.\n\n\n\nThe plugin executes the following steps:\n\n\n\n1. Look for a valid `protoc/bin/protoc` in the plugin installation directory\n\n2. If not found, look for a `protoc-{version}-{OS}.zip` in the plugin installation directory and unpack that (i.e. for Linux it will look for `protoc-3.19.1-linux-x86_64.zip`).\n\n3. If not found, try download protoc using the `downloadUrl` entry in the plugin manifest file\n\n4. Otherwise, fallback to using the system installed protoc\n\n\n\n#### Dealing with network and firewall issues\n\n\n\nIf the plugin is going to run in an environment that does not allow automatic downloading of files, then you can do any of the following:\n\n\n\n1. Download the protoc archive and place it in the plugin installation directory. It will need to be the correct version and operating system/architecture.\n\n2. Download the protoc archive and unpack it into the plugin installation directory. It will need to be in a `protoc` directory. _Do this if the current version is not supported for your operating system/architecture._\n\n3. Change the `downloadUrl` entry in the plugin manifest to point to a location that the file can be downloaded from.\n\n4. Install the correct version of the protoc compiler as an operating system package. It must then be on the executable path when the plugin runs. For instance, for Alpine Linux this will need to be done as the downloaded versions will not work.\n\n\n", "file_path": "README.md", "rank": 62, "score": 19727.94502058624 }, { "content": "# 0.1.0 - gRPC mock servers\n\n\n\n* f49c15a - chore: clean in prep for release (Ronald Holshausen, Thu Mar 24 16:09:09 2022 +1100)\n\n* 8df497c - chore: add the gRPC service name into any error messages from the mock server (Ronald Holshausen, Thu Mar 17 16:29:03 2022 +1100)\n\n* f77b773 - chore: bind to IP6 loopback address (Ronald Holshausen, Thu Mar 17 10:50:54 2022 +1100)\n\n* 2bfcd37 - fix: matching rule paths were incorrect for gRPC interactions (Ronald Holshausen, Tue Mar 15 14:00:48 2022 +1100)\n\n* 6c2f38b - feat: return the results back from the mock server (Ronald Holshausen, Fri Mar 11 16:36:53 2022 +1100)\n\n* fef6b67 - chore: cleanup unused imports (Ronald Holshausen, Wed Mar 9 15:04:31 2022 +1100)\n\n* cfe24a8 - feat: first working version of a gRPC mock server (Ronald Holshausen, Wed Mar 9 14:34:42 2022 +1100)\n\n* d66ace5 - feat: Initial setup of basic mock gRPC server (Ronald Holshausen, Mon Mar 7 15:19:33 2022 +1100)\n\n* d782063 - Merge branch 'main' into feat/mock-server (Ronald Holshausen, Mon Mar 7 10:39:31 2022 +1100)\n\n* e7eebc7 - bump version to 0.0.4 (Ronald Holshausen, Mon Feb 28 10:35:41 2022 +1100)\n\n* 897eae2 - chore: bump minor version (Ronald Holshausen, Wed Feb 2 15:04:49 2022 +1100)\n\n\n\n# 0.0.3 - Bugfix Release\n\n\n\n* 34d0248 - fix: check not empty value for unexpected keys (tienvx, Tue Feb 1 10:41:33 2022 +0700)\n\n* aa49c13 - fix: extract message type from input type to compare (tienvx, Sat Jan 29 15:44:11 2022 +0700)\n\n* 59c0c44 - bump version to 0.0.3 (Ronald Holshausen, Tue Jan 25 16:43:22 2022 +1100)\n\n\n", "file_path": "CHANGELOG.md", "rank": 63, "score": 19727.1143374686 }, { "content": "# 0.0.0 - First Release\n", "file_path": "CHANGELOG.md", "rank": 64, "score": 19725.58446886744 }, { "content": "//! Module provides the service implementation based on a Pact interaction\n\n\n\nuse std::future::Future;\n\nuse std::pin::Pin;\n\nuse std::task::{Context, Poll};\n\nuse maplit::hashmap;\n\nuse pact_matching::{CoreMatchingContext, DiffConfig};\n\n\n\nuse pact_models::v4::sync_message::SynchronousMessage;\n\nuse prost_types::{DescriptorProto, FileDescriptorSet, MethodDescriptorProto};\n\nuse tonic::{Request, Response, Status};\n\nuse tower_service::Service;\n\nuse tracing::{error, instrument, trace};\n\n\n\nuse crate::dynamic_message::DynamicMessage;\n\nuse crate::matching::compare;\n\nuse crate::message_decoder::decode_message;\n\nuse crate::mock_server::MOCK_SERVER_STATE;\n\n\n\n#[derive(Debug, Clone)]\n", "file_path": "src/mock_service.rs", "rank": 66, "score": 25.35586914358348 }, { "content": "//! gRPC codec that used a Pact interaction\n\n\n\nuse anyhow::anyhow;\n\nuse bytes::BufMut;\n\nuse itertools::Itertools;\n\nuse pact_models::v4::sync_message::SynchronousMessage;\n\nuse prost::encoding::{encode_key, encode_varint, WireType};\n\nuse prost_types::{DescriptorProto, FileDescriptorSet};\n\nuse tonic::codec::{Codec, DecodeBuf, Decoder, EncodeBuf, Encoder};\n\nuse tonic::Status;\n\nuse tracing::{debug, error, instrument, trace};\n\n\n\nuse crate::message_decoder::{decode_message, ProtobufField, ProtobufFieldData};\n\n\n\n#[derive(Debug, Clone)]\n\npub(crate) struct PactCodec {\n\n message: SynchronousMessage,\n\n input_message: DescriptorProto,\n\n output_message: DescriptorProto,\n\n file_descriptor_set: FileDescriptorSet,\n", "file_path": "src/dynamic_message.rs", "rank": 67, "score": 23.523338797823047 }, { "content": " \"service\".to_string() => Value::String(\n\n service_name.split_once(':').map(|(s, _)| s).unwrap_or(service_name).to_string()\n\n ),\n\n \"descriptorKey\".to_string() => Value::String(descriptor_hash.to_string())\n\n })),\n\n pact_configuration: None\n\n });\n\n trace!(\"request = {request:?}\");\n\n trace!(\"response = {response:?}\");\n\n (\n\n request.map(|r| InteractionResponse { plugin_configuration: plugin_configuration.clone(), .. r }),\n\n response.iter().map(|r| InteractionResponse { plugin_configuration: plugin_configuration.clone(), .. r.clone() }).collect()\n\n )\n\n })\n\n}\n\n\n", "file_path": "src/protobuf.rs", "rank": 68, "score": 22.21158061067701 }, { "content": "}\n\n\n\nimpl Service<tonic::Request<DynamicMessage>> for MockService {\n\n type Response = tonic::Response<DynamicMessage>;\n\n type Error = Status;\n\n type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;\n\n\n\n fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {\n\n Poll::Ready(Ok(()))\n\n }\n\n\n\n fn call(&mut self, req: Request<DynamicMessage>) -> Self::Future {\n\n let request = req.into_inner();\n\n let message_descriptor = self.input_message.clone();\n\n let response_descriptor = self.output_message.clone();\n\n let service = self.clone();\n\n Box::pin(async move {\n\n service.handle_message(request, message_descriptor, response_descriptor).await\n\n })\n\n }\n\n}\n", "file_path": "src/mock_service.rs", "rank": 70, "score": 21.524181164872918 }, { "content": " let pact_configuration = plugin_configuration.pact_configuration.unwrap_or_default();\n\n debug!(\"Pact level configuration keys: {:?}\", pact_configuration.fields.keys());\n\n\n\n let config_for_interaction = pact_configuration.fields.iter()\n\n .map(|(key, config)| (key.clone(), proto_value_to_json(config)))\n\n .collect();\n\n let descriptors = match get_descriptors_for_interaction(message_key.as_str(), &config_for_interaction) {\n\n Ok(descriptors) => descriptors,\n\n Err(err) => return Self::error_response(err.to_string())\n\n };\n\n\n\n let mut expected_body = request.expected.as_ref()\n\n .and_then(|body| body.content.clone().map(Bytes::from))\n\n .unwrap_or_default();\n\n let mut actual_body = request.actual.as_ref()\n\n .map(|body| body.content.clone().map(Bytes::from))\n\n .flatten()\n\n .unwrap_or_default();\n\n let mut matching_rules = MatchingRuleCategory::empty(\"body\");\n\n for (key, rules) in &request.rules {\n", "file_path": "src/server.rs", "rank": 71, "score": 21.427447155230716 }, { "content": "//! Shared utilities\n\n\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::fmt::Write;\n\n\n\nuse anyhow::anyhow;\n\nuse bytes::{Bytes, BytesMut};\n\nuse maplit::hashmap;\n\nuse pact_models::json_utils::json_to_string;\n\nuse pact_models::pact::load_pact_from_json;\n\nuse pact_models::prelude::v4::V4Pact;\n\nuse pact_models::v4::interaction::V4Interaction;\n\nuse prost::Message;\n\nuse prost_types::{DescriptorProto, EnumDescriptorProto, field_descriptor_proto, FieldDescriptorProto, FileDescriptorProto, FileDescriptorSet, MethodDescriptorProto, ServiceDescriptorProto, Value};\n\nuse prost_types::field_descriptor_proto::Label;\n\nuse prost_types::value::Kind;\n\nuse serde_json::json;\n\nuse tracing::{debug, error, trace, warn};\n\n\n\nuse crate::message_decoder::{decode_message, ProtobufField, ProtobufFieldData};\n\n\n\n/// Return the last name in a dot separated string\n", "file_path": "src/utils.rs", "rank": 73, "score": 20.33022020491979 }, { "content": " type Error = Status;\n\n\n\n #[instrument]\n\n fn encode(&mut self, item: Self::Item, dst: &mut EncodeBuf<'_>) -> Result<(), Self::Error> {\n\n item.write_to(dst).map_err(|err| {\n\n error!(\"Failed to encode the message - {err}\");\n\n Status::invalid_argument(format!(\"Failed to encode the message - {err}\"))\n\n })\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub(crate) struct DynamicMessageDecoder {\n\n descriptor: DescriptorProto,\n\n message: SynchronousMessage,\n\n file_descriptor_set: FileDescriptorSet,\n\n}\n\n\n\nimpl DynamicMessageDecoder {\n\n fn new(codec: &PactCodec) -> Self {\n", "file_path": "src/dynamic_message.rs", "rank": 74, "score": 20.21563754498926 }, { "content": "use pact_verifier::verification_result::MismatchResult;\n\nuse tonic::{Response, Status};\n\nuse tonic::metadata::KeyAndValueRef;\n\nuse tracing::{debug, error, info, trace};\n\n\n\nuse crate::dynamic_message::DynamicMessage;\n\nuse crate::matching::{match_message, match_service};\n\nuse crate::message_decoder::decode_message;\n\nuse crate::mock_server::{GrpcMockServer, MOCK_SERVER_STATE};\n\nuse crate::protobuf::process_proto;\n\nuse crate::protoc::setup_protoc;\n\nuse crate::utils::{\n\n find_message_type_by_name,\n\n get_descriptors_for_interaction,\n\n last_name,\n\n lookup_interaction_by_id,\n\n lookup_service_descriptors_for_interaction,\n\n parse_pact_from_request_json\n\n};\n\nuse crate::verification::verify_interaction;\n", "file_path": "src/server.rs", "rank": 76, "score": 20.05177118474706 }, { "content": "pub(crate) struct MockService {\n\n file_descriptor_set: FileDescriptorSet,\n\n service_name: String,\n\n message: SynchronousMessage,\n\n method_descriptor: MethodDescriptorProto,\n\n input_message: DescriptorProto,\n\n output_message: DescriptorProto,\n\n server_key: String\n\n}\n\n\n\nimpl MockService {\n\n #[instrument]\n\n pub(crate) async fn handle_message(\n\n &self,\n\n request: DynamicMessage,\n\n message_descriptor: DescriptorProto,\n\n response_descriptor: DescriptorProto\n\n ) -> Result<Response<DynamicMessage>, Status> {\n\n // 1. Compare the incoming message to the request message from the interaction\n\n let mut expected_message_bytes = self.message.request.contents.value().unwrap_or_default();\n", "file_path": "src/mock_service.rs", "rank": 77, "score": 19.294867520128964 }, { "content": "}\n\n\n\nimpl PactCodec {\n\n pub(crate) fn new(\n\n file: &FileDescriptorSet,\n\n input_message: &DescriptorProto,\n\n output_message: &DescriptorProto,\n\n message: &SynchronousMessage\n\n ) -> Self {\n\n PactCodec {\n\n file_descriptor_set: file.clone(),\n\n input_message: input_message.clone(),\n\n output_message: output_message.clone(),\n\n message: message.clone()\n\n }\n\n }\n\n}\n\n\n\nimpl Default for PactCodec {\n\n fn default() -> Self {\n", "file_path": "src/dynamic_message.rs", "rank": 78, "score": 19.218633340255806 }, { "content": " ProtobufFieldData::Message(_, descriptor) => {\n\n write!(f, \"{}\", descriptor.name.clone().unwrap_or_else(|| \"unknown\".to_string()))\n\n }\n\n ProtobufFieldData::Unknown(b) => if b.len() <= 16 {\n\n write!(f, \"{}\", as_hex(b.as_slice()))\n\n } else {\n\n write!(f, \"{}... ({} bytes)\", as_hex(&b[0..16]), b.len())\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Decodes the Protobuf message using the descriptors\n\n#[tracing::instrument(ret, skip_all)]\n", "file_path": "src/message_decoder.rs", "rank": 79, "score": 19.186954131367813 }, { "content": "//! Decoder for encoded Protobuf messages using the descriptors\n\n\n\nuse std::fmt::{Display, Formatter};\n\nuse std::str::from_utf8;\n\n\n\nuse anyhow::anyhow;\n\nuse bytes::{Buf, BytesMut};\n\nuse itertools::Itertools;\n\nuse prost::encoding::{decode_key, decode_varint, encode_varint, WireType};\n\nuse prost_types::{DescriptorProto, EnumDescriptorProto, FieldDescriptorProto, FileDescriptorSet};\n\nuse prost_types::field_descriptor_proto::Type;\n\nuse tracing::{error, trace, warn};\n\n\n\nuse crate::utils::{as_hex, find_message_type_by_name, last_name};\n\n\n\n/// Decoded Protobuf field\n\n#[derive(Clone, Debug, PartialEq)]\n\npub struct ProtobufField {\n\n /// Field number\n\n pub field_num: u32,\n", "file_path": "src/message_decoder.rs", "rank": 80, "score": 19.186210573553804 }, { "content": "\n\n let response = plugin.configure_interaction(Request::new(request)).await.unwrap();\n\n let response_message = response.get_ref();\n\n expect!(&response_message.error).to(\n\n be_equal_to(\"Config item with key 'pact:proto' and path to the proto file is required\"));\n\n }\n\n\n\n #[tokio::test]\n\n async fn configure_interaction_test__with_missing_message_or_service_name() {\n\n let plugin = ProtobufPactPlugin { manifest: Default::default() };\n\n let request = proto::ConfigureInteractionRequest {\n\n content_type: \"text/test\".to_string(),\n\n contents_config: Some(prost_types::Struct {\n\n fields: btreemap!{\n\n \"pact:proto\".to_string() => prost_types::Value { kind: Some(prost_types::value::Kind::StringValue(\"test.proto\".to_string())) }\n\n }\n\n })\n\n };\n\n\n\n let response = plugin.configure_interaction(Request::new(request)).await.unwrap();\n\n let response_message = response.get_ref();\n\n expect!(&response_message.error).to(\n\n be_equal_to(\"Config item with key 'pact:message-type' and the protobuf message name or 'pact:proto-service' and the service name is required\"));\n\n }\n\n}\n", "file_path": "src/server.rs", "rank": 81, "score": 19.023592406286664 }, { "content": " PluginConfiguration\n\n};\n\nuse pact_plugin_driver::proto::body::ContentTypeHint;\n\nuse pact_plugin_driver::proto::interaction_response::MarkupType;\n\nuse pact_plugin_driver::utils::{proto_value_to_json, proto_value_to_string, to_proto_struct};\n\nuse prost_types::{DescriptorProto, field_descriptor_proto, FieldDescriptorProto, FileDescriptorProto, ServiceDescriptorProto};\n\nuse prost_types::field_descriptor_proto::Type;\n\nuse prost_types::value::Kind;\n\nuse serde_json::{json, Value};\n\nuse tokio::fs::File;\n\nuse tokio::io::AsyncReadExt;\n\nuse tracing::{debug, trace, warn};\n\nuse tracing_core::LevelFilter;\n\n\n\nuse crate::message_builder::{MessageBuilder, MessageFieldValue, MessageFieldValueType, RType};\n\nuse crate::protoc::Protoc;\n\nuse crate::utils::{\n\n find_enum_value_by_name,\n\n find_message_type_in_file_descriptor,\n\n find_nested_type,\n", "file_path": "src/protobuf.rs", "rank": 82, "score": 18.727848041944284 }, { "content": " &self,\n\n request: tonic::Request<proto::ConfigureInteractionRequest>,\n\n ) -> Result<tonic::Response<proto::ConfigureInteractionResponse>, tonic::Status> {\n\n let message = request.get_ref();\n\n debug!(\"Configure interaction request for content type '{}'\", message.content_type);\n\n\n\n // Check for the \"pact:proto\" key\n\n let fields = message.contents_config.as_ref().map(|config| config.fields.clone()).unwrap_or_default();\n\n let proto_file = match fields.get(\"pact:proto\").and_then(proto_value_to_string) {\n\n Some(pf) => pf,\n\n None => {\n\n error!(\"Config item with key 'pact:proto' and path to the proto file is required\");\n\n return Ok(tonic::Response::new(proto::ConfigureInteractionResponse {\n\n error: \"Config item with key 'pact:proto' and path to the proto file is required\".to_string(),\n\n .. proto::ConfigureInteractionResponse::default()\n\n }))\n\n }\n\n };\n\n\n\n // Check for either the message type or proto service\n", "file_path": "src/server.rs", "rank": 84, "score": 18.529107099987026 }, { "content": "use tonic::{Request, Response, Status};\n\nuse tonic::metadata::{Ascii, Binary, MetadataKey, MetadataMap, MetadataValue};\n\nuse tower::ServiceExt;\n\nuse tracing::{debug, error, trace, warn};\n\n\n\nuse crate::dynamic_message::{DynamicMessage, PactCodec};\n\nuse crate::matching::match_service;\n\nuse crate::message_decoder::decode_message;\n\nuse crate::utils::{find_message_type_by_name, last_name, lookup_service_descriptors_for_interaction};\n\n\n\n#[derive(Debug)]\n", "file_path": "src/verification.rs", "rank": 86, "score": 18.253760344699007 }, { "content": "//! Builder for creating protobuf messages based on a descriptor\n\n\n\nuse std::collections::btree_map::Entry;\n\nuse std::collections::BTreeMap;\n\n\n\nuse anyhow::anyhow;\n\nuse bytes::{BufMut, Bytes, BytesMut};\n\nuse itertools::Itertools;\n\nuse maplit::btreemap;\n\nuse prost::encoding::{encode_key, encode_varint, string, WireType};\n\nuse prost::Message;\n\nuse prost_types::{DescriptorProto, FieldDescriptorProto, FileDescriptorProto};\n\nuse prost_types::field_descriptor_proto::Type;\n\nuse tracing::trace;\n\n\n\nuse crate::utils::last_name;\n\n\n\n/// Enum to set what type of field the value is for\n\n#[derive(Clone, Copy, Debug, PartialEq)]\n\npub enum MessageFieldValueType {\n", "file_path": "src/message_builder.rs", "rank": 87, "score": 17.983022527971205 }, { "content": " let enum_type_name = field.descriptor.type_name.as_ref()\n\n .ok_or_else(|| anyhow!(\"Type name is missing from the descriptor for enum field\"))?;\n\n format!(\"enum {}\", enum_type_name)\n\n }\n\n Type::Sfixed32 => \"sfixed32\".to_string(),\n\n Type::Sfixed64 => \"sfixed64\".to_string(),\n\n Type::Sint32 => \"sint32\".to_string(),\n\n Type::Sint64 => \"sint64\".to_string()\n\n })\n\n}\n\n\n\n/// Rust type to use for a protobuf type\n\n#[derive(Clone, Debug, PartialEq)]\n\npub enum RType {\n\n /// String value\n\n String(String),\n\n /// Boolean value\n\n Boolean(bool),\n\n /// Unsigned 32 bit integer\n\n UInteger32(u32),\n", "file_path": "src/message_builder.rs", "rank": 88, "score": 17.74364683022604 }, { "content": " }\n\n\n\n fn error_response<E>(err: E) -> Result<Response<CompareContentsResponse>, Status>\n\n where E: Into<String> {\n\n Ok(tonic::Response::new(proto::CompareContentsResponse {\n\n error: err.into(),\n\n ..proto::CompareContentsResponse::default()\n\n }))\n\n }\n\n}\n\n\n\n#[tonic::async_trait]\n\nimpl PactPlugin for ProtobufPactPlugin {\n\n // Init plugin request. This will be called shortly after the plugin is started.\n\n // This will return the catalogue entries for the plugin\n\n async fn init_plugin(\n\n &self,\n\n request: tonic::Request<proto::InitPluginRequest>,\n\n ) -> Result<tonic::Response<proto::InitPluginResponse>, tonic::Status> {\n\n let message = request.get_ref();\n", "file_path": "src/server.rs", "rank": 89, "score": 17.725330958631027 }, { "content": "pub(crate) struct DynamicMessage {\n\n descriptor: DescriptorProto,\n\n fields: Vec<ProtobufField>,\n\n}\n\n\n\nimpl DynamicMessage {\n\n pub(crate) fn new(descriptor: &DescriptorProto, fields: &[ProtobufField]) -> DynamicMessage {\n\n DynamicMessage {\n\n descriptor: descriptor.clone(),\n\n fields: fields.to_vec()\n\n }\n\n }\n\n\n\n pub(crate) fn proto_fields(&self) -> &[ProtobufField] {\n\n self.fields.as_slice()\n\n }\n\n\n\n pub(crate) fn write_to<B>(&self, buffer: &mut B) -> anyhow::Result<()> where B: BufMut {\n\n for field in self.fields.iter().sorted_by(|a, b| Ord::cmp(&a.field_num, &b.field_num)) {\n\n trace!(field = field.to_string().as_str(), \"Writing\");\n", "file_path": "src/dynamic_message.rs", "rank": 90, "score": 17.649721417734696 }, { "content": "use tokio::process::Command;\n\nuse tracing::{debug, trace};\n\nuse zip::ZipArchive;\n\n\n\npub(crate) struct Protoc {\n\n protoc_path: String,\n\n local_install: bool\n\n}\n\n\n\nimpl Protoc {\n\n fn new(path: String, local_install: bool) -> Self {\n\n Protoc {\n\n protoc_path: path,\n\n local_install\n\n }\n\n }\n\n\n\n // Try to invoke the protoc binary\n\n async fn invoke(&self) -> anyhow::Result<String> {\n\n trace!(\"Invoking protoc: '{} --version'\", self.protoc_path);\n", "file_path": "src/protoc.rs", "rank": 91, "score": 17.576595112779238 }, { "content": "\n\n#[derive(Debug, Clone)]\n\npub(crate) struct DynamicMessageEncoder {\n\n descriptor: DescriptorProto,\n\n message: SynchronousMessage,\n\n file_descriptor_set: FileDescriptorSet\n\n}\n\n\n\nimpl DynamicMessageEncoder {\n\n fn new(codec: &PactCodec) -> Self {\n\n DynamicMessageEncoder {\n\n descriptor: codec.output_message.clone(),\n\n message: codec.message.clone(),\n\n file_descriptor_set: codec.file_descriptor_set.clone()\n\n }\n\n }\n\n}\n\n\n\nimpl Encoder for DynamicMessageEncoder {\n\n type Item = DynamicMessage;\n", "file_path": "src/dynamic_message.rs", "rank": 92, "score": 17.43347693305979 }, { "content": " fields: BTreeMap<String, FieldValueInner>,\n\n}\n\n\n\nimpl MessageBuilder {\n\n /// Create a new message builder for the message\n\n pub fn new(descriptor: &DescriptorProto, message_name: &str, file_descriptor: &FileDescriptorProto) -> Self {\n\n MessageBuilder {\n\n file_descriptor: file_descriptor.clone(),\n\n descriptor: descriptor.clone(),\n\n message_name: message_name.to_string(),\n\n fields: btreemap!{}\n\n }\n\n }\n\n\n\n /// Find the field descriptor for the given name\n\n pub fn field_by_name(&self, name: &str) -> Option<FieldDescriptorProto> {\n\n self.descriptor.field.iter()\n\n .find(|f| f.name.clone().unwrap_or_default() == name)\n\n .cloned()\n\n }\n", "file_path": "src/message_builder.rs", "rank": 93, "score": 17.352625826096055 }, { "content": "use tonic::transport::Server;\n\nuse tower::ServiceBuilder;\n\nuse tower_http::compression::CompressionLayer;\n\nuse tower_http::sensitive_headers::SetSensitiveHeadersLayer;\n\nuse tower_http::trace::{DefaultMakeSpan, TraceLayer};\n\nuse tracing::info;\n\nuse tracing_bunyan_formatter::{BunyanFormattingLayer, JsonStorageLayer};\n\nuse tracing_subscriber::fmt::writer::MakeWriterExt;\n\nuse tracing_subscriber::FmtSubscriber;\n\nuse tracing_subscriber::layer::SubscriberExt;\n\nuse uuid::Uuid;\n\n\n\nuse pact_protobuf_plugin::server::ProtobufPactPlugin;\n\nuse pact_protobuf_plugin::tcp::TcpIncoming;\n\n\n\n/// Interceptor to check the server key for the request\n\n#[derive(Debug, Clone)]\n", "file_path": "src/main.rs", "rank": 94, "score": 17.284388969449783 }, { "content": " let output_name = method_descriptor.output_type.as_ref().ok_or_else(|| anyhow!(\"Input message name is empty for service {}/{}\", service_name, method_name))?;\n\n let input_message_name = last_name(input_name.as_str());\n\n let request_descriptor = find_message_descriptor(input_message_name, all_descriptors)?;\n\n let output_message_name = last_name(output_name.as_str());\n\n let response_descriptor = find_message_descriptor(output_message_name, all_descriptors)?;\n\n\n\n let request_part_config = if service_part == \"request\" {\n\n config.clone()\n\n } else {\n\n config.get(\"request\").and_then(|request_config| {\n\n request_config.kind.as_ref().and_then(|kind| {\n\n match kind {\n\n Kind::StructValue(s) => Some(proto_struct_to_btreemap(s)),\n\n _ => None\n\n }\n\n })\n\n })\n\n .unwrap_or_default()\n\n };\n\n let request_part = if request_part_config.is_empty() {\n", "file_path": "src/protobuf.rs", "rank": 95, "score": 17.105226444196518 }, { "content": " None\n\n } else {\n\n construct_protobuf_interaction_for_message(&request_descriptor,\n\n &request_part_config, input_message_name, \"\", file_descriptor)\n\n .ok()\n\n .map(|i| InteractionResponse { part_name: \"request\".into(), .. i } )\n\n };\n\n\n\n let response_part_config = if service_part == \"response\" {\n\n vec![ config.clone() ]\n\n } else {\n\n config.get(\"response\").and_then(|response_config| {\n\n response_config.kind.as_ref().map(|kind| {\n\n match kind {\n\n Kind::StructValue(s) => vec![ proto_struct_to_btreemap(s) ],\n\n Kind::ListValue(l) => l.values.iter().map(|v| {\n\n v.kind.as_ref().and_then(|k| match k {\n\n Kind::StructValue(s) => Some(proto_struct_to_btreemap(s)),\n\n _ => None\n\n })\n", "file_path": "src/protobuf.rs", "rank": 96, "score": 17.023672757552184 }, { "content": " Ok(pact) => pact,\n\n Err(err) => return Ok(tonic::Response::new(proto::StartMockServerResponse {\n\n response: Some(proto::start_mock_server_response::Response::Error(format!(\"Failed to parse Pact JSON: {}\", err))),\n\n ..proto::StartMockServerResponse::default()\n\n }))\n\n };\n\n\n\n trace!(\"Got pact {pact:?}\");\n\n // Check for the plugin specific configuration for the Protobuf descriptors\n\n let plugin_config = match pact.plugin_data.iter().find(|pd| pd.name == \"protobuf\") {\n\n None => {\n\n error!(\"Provided Pact file does not have any Protobuf descriptors\");\n\n return Ok(tonic::Response::new(proto::StartMockServerResponse {\n\n response: Some(proto::start_mock_server_response::Response::Error(\"Provided Pact file does not have any Protobuf descriptors\".to_string())),\n\n .. proto::StartMockServerResponse::default()\n\n }))\n\n }\n\n Some(config) => config.clone()\n\n };\n\n\n", "file_path": "src/server.rs", "rank": 97, "score": 16.976425252095908 }, { "content": "//! Pact plugin for Protobuf and gRPC.\n\n//!\n\n//! Implements the version 1 of the Pact plugin interface described at `https://github.com/pact-foundation/pact-plugins/blob/main/docs/content-matcher-design.md`.\n\n\n\nuse std::env;\n\nuse std::iter::once;\n\nuse std::net::SocketAddr;\n\nuse std::str::FromStr;\n\nuse std::sync::Mutex;\n\nuse std::time::{Duration, Instant};\n\n\n\nuse clap::{App, Arg, ErrorKind};\n\nuse hyper::header;\n\nuse lazy_static::lazy_static;\n\nuse pact_plugin_driver::proto::pact_plugin_server::PactPluginServer;\n\nuse tokio::net::TcpListener;\n\nuse tokio::sync::oneshot::channel;\n\nuse tokio::time;\n\nuse tonic::{Request, Status};\n\nuse tonic::service::{interceptor, Interceptor};\n", "file_path": "src/main.rs", "rank": 98, "score": 16.738733806493194 }, { "content": " name: Some(\"rules\".to_string()),\n\n number: Some(4),\n\n label: Some(Repeated as i32),\n\n r#type: Some(field_descriptor_proto::Type::Message as i32),\n\n type_name: Some(\".io.pact.plugin.CompareContentsRequest.RulesEntry\".to_string()),\n\n extendee: None,\n\n default_value: None,\n\n oneof_index: None,\n\n json_name: None,\n\n options: None,\n\n proto3_optional: None\n\n };\n\n let descriptor = DescriptorProto {\n\n name: Some(\"CompareContentsRequest\".to_string()),\n\n field: vec![\n\n field1.clone(),\n\n field2.clone()\n\n ],\n\n extension: vec![],\n\n nested_type: vec![\n", "file_path": "src/message_builder.rs", "rank": 99, "score": 16.705743812228796 } ]
Rust
src/infrastructure/arranging/sequencing.rs
SpeedyNinja/laminar
bf65f8ad2a8d168a265d0bc302b232912ce0bca4
use super::{Arranging, ArrangingSystem}; use crate::packet::SequenceNumber; use std::{collections::HashMap, marker::PhantomData}; pub struct SequencingSystem<T> { streams: HashMap<u8, SequencingStream<T>>, } impl<T> SequencingSystem<T> { pub fn new() -> SequencingSystem<T> { SequencingSystem { streams: HashMap::with_capacity(32), } } } impl<T> ArrangingSystem for SequencingSystem<T> { type Stream = SequencingStream<T>; fn stream_count(&self) -> usize { self.streams.len() } fn get_or_create_stream(&mut self, stream_id: u8) -> &mut Self::Stream { self.streams .entry(stream_id) .or_insert_with(|| SequencingStream::new(stream_id)) } } pub struct SequencingStream<T> { _stream_id: u8, top_index: usize, phantom: PhantomData<T>, unique_item_identifier: u16, } impl<T> SequencingStream<T> { pub fn new(stream_id: u8) -> SequencingStream<T> { SequencingStream { _stream_id: stream_id, top_index: 0, phantom: PhantomData, unique_item_identifier: 0, } } #[cfg(test)] pub fn stream_id(&self) -> u8 { self._stream_id } pub fn new_item_identifier(&mut self) -> SequenceNumber { self.unique_item_identifier = self.unique_item_identifier.wrapping_add(1); self.unique_item_identifier } } impl<T> Arranging for SequencingStream<T> { type ArrangingItem = T; fn arrange( &mut self, incoming_index: usize, item: Self::ArrangingItem, ) -> Option<Self::ArrangingItem> { if incoming_index > self.top_index { self.top_index = incoming_index; return Some(item); } None } } #[cfg(test)] mod tests { use super::{Arranging, ArrangingSystem, SequencingSystem}; #[derive(Debug, PartialEq, Clone)] struct Packet { pub sequence: usize, pub ordering_stream: u8, } impl Packet { fn new(sequence: usize, ordering_stream: u8) -> Packet { Packet { sequence, ordering_stream, } } } #[test] fn create_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); } #[test] fn create_existing_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); system.get_or_create_stream(1); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); } macro_rules! assert_sequence { ( [$( $x:expr ),*], [$( $y:expr),*], $stream_id:expr) => { { let mut before: Vec<usize> = Vec::new(); $( before.push($x); )* let mut after: Vec<usize> = Vec::new(); $( after.push($y); )* let mut packets = Vec::new(); for (_, v) in before.iter().enumerate() { packets.push(Packet::new(*v, $stream_id)); } let mut sequence_system = SequencingSystem::<Packet>::new(); let stream = sequence_system.get_or_create_stream(1); let mut sequenced_packets = Vec::new(); for packet in packets.into_iter() { match stream.arrange(packet.sequence, packet.clone()) { Some(packet) => { sequenced_packets.push(packet.sequence);}, None => {} }; } assert_eq!(after, sequenced_packets); } }; } #[test] fn can_sequence() { assert_sequence!([1, 3, 5, 4, 2], [1, 3, 5], 1); assert_sequence!([1, 5, 4, 3, 2], [1, 5], 1); assert_sequence!([5, 3, 4, 2, 1], [5], 1); assert_sequence!([4, 3, 2, 1, 5], [4, 5], 1); assert_sequence!([2, 1, 4, 3, 5], [2, 4, 5], 1); assert_sequence!([5, 2, 1, 4, 3], [5], 1); assert_sequence!([3, 2, 4, 1, 5], [3, 4, 5], 1); } #[test] fn sequence_on_multiple_streams() { assert_sequence!([1, 3, 5, 4, 2], [1, 3, 5], 1); assert_sequence!([1, 5, 4, 3, 2], [1, 5], 2); assert_sequence!([5, 3, 4, 2, 1], [5], 3); assert_sequence!([4, 3, 2, 1, 5], [4, 5], 4); assert_sequence!([2, 1, 4, 3, 5], [2, 4, 5], 5); assert_sequence!([5, 2, 1, 4, 3], [5], 6); assert_sequence!([3, 2, 4, 1, 5], [3, 4, 5], 7); } }
use super::{Arranging, ArrangingSystem}; use crate::packet::SequenceNumber; use std::{collections::HashMap, marker::PhantomData}; pub struct SequencingSystem<T> { streams: HashMap<u8, SequencingStream<T>>, } impl<T> SequencingSystem<T> { pub fn new() -> SequencingSystem<T> { SequencingSystem { streams: HashMap::with_capacity(32), } } } impl<T> ArrangingSystem for SequencingSystem<T> { type Stream = SequencingStream<T>; fn stream_count(&self) -> usize { self.streams.len() } fn get_or_create_stream(&mut self, stream_id: u8) -> &mut Self::Stream { self.streams .entry(stream_id) .or_insert_with(|| SequencingStream::new(stream_id)) } } pub struct SequencingStream<T> { _stream_id: u8, top_index: usize, phantom: PhantomData<T>, unique_item_identifier: u16, } impl<T> SequencingStream<T> { pub fn new(stream_id: u8) -> SequencingStream<T> { SequencingStream { _stream_id: stream_id, top_index: 0, phantom: PhantomData, unique_item_identifier: 0, } } #[cfg(test)] pub fn stream_id(&self) -> u8 { self._stream_id } pub fn new_item_identifier(&mut self) -> SequenceNumber { self.unique_item_identifier = self.unique_item_identifier.wrapping_add(1); self.unique_item_identifier } } impl<T> Arranging for SequencingStream<T> { type ArrangingItem = T; fn arrange( &mut self, incoming_index: usize, item: Self::ArrangingItem, ) -> Option<Self::ArrangingItem> { if incoming_index > self.top_index { self.top_index = incoming_index; return Some(item); } None } } #[cfg(test)] mod tests { use super::{Arranging, ArrangingSystem, SequencingSystem}; #[derive(Debug, PartialEq, Clone)] struct Packet { pub sequence: usize, pub ordering_stream: u8, } impl Packet { fn new(sequence: usize, ordering_stream: u8) -> Packet { Packet { sequence, ordering_stream, } } } #[test]
#[test] fn create_existing_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); system.get_or_create_stream(1); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); } macro_rules! assert_sequence { ( [$( $x:expr ),*], [$( $y:expr),*], $stream_id:expr) => { { let mut before: Vec<usize> = Vec::new(); $( before.push($x); )* let mut after: Vec<usize> = Vec::new(); $( after.push($y); )* let mut packets = Vec::new(); for (_, v) in before.iter().enumerate() { packets.push(Packet::new(*v, $stream_id)); } let mut sequence_system = SequencingSystem::<Packet>::new(); let stream = sequence_system.get_or_create_stream(1); let mut sequenced_packets = Vec::new(); for packet in packets.into_iter() { match stream.arrange(packet.sequence, packet.clone()) { Some(packet) => { sequenced_packets.push(packet.sequence);}, None => {} }; } assert_eq!(after, sequenced_packets); } }; } #[test] fn can_sequence() { assert_sequence!([1, 3, 5, 4, 2], [1, 3, 5], 1); assert_sequence!([1, 5, 4, 3, 2], [1, 5], 1); assert_sequence!([5, 3, 4, 2, 1], [5], 1); assert_sequence!([4, 3, 2, 1, 5], [4, 5], 1); assert_sequence!([2, 1, 4, 3, 5], [2, 4, 5], 1); assert_sequence!([5, 2, 1, 4, 3], [5], 1); assert_sequence!([3, 2, 4, 1, 5], [3, 4, 5], 1); } #[test] fn sequence_on_multiple_streams() { assert_sequence!([1, 3, 5, 4, 2], [1, 3, 5], 1); assert_sequence!([1, 5, 4, 3, 2], [1, 5], 2); assert_sequence!([5, 3, 4, 2, 1], [5], 3); assert_sequence!([4, 3, 2, 1, 5], [4, 5], 4); assert_sequence!([2, 1, 4, 3, 5], [2, 4, 5], 5); assert_sequence!([5, 2, 1, 4, 3], [5], 6); assert_sequence!([3, 2, 4, 1, 5], [3, 4, 5], 7); } }
fn create_stream() { let mut system: SequencingSystem<Packet> = SequencingSystem::new(); let stream = system.get_or_create_stream(1); assert_eq!(stream.stream_id(), 1); }
function_block-function_prefix_line
[ { "content": "pub fn payload() -> Vec<u8> {\n\n vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n}\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 0, "score": 186202.72506258375 }, { "content": "pub fn payload() -> Vec<u8> {\n\n vec![0; 4000]\n\n}\n", "file_path": "tests/fragmentation_packets_test.rs", "rank": 1, "score": 186202.72506258375 }, { "content": "pub fn sequence_greater_than(s1: u16, s2: u16) -> bool {\n\n ((s1 > s2) && (s1 - s2 <= 32768)) || ((s1 < s2) && (s2 - s1 > 32768))\n\n}\n\n\n", "file_path": "src/sequence_buffer.rs", "rank": 2, "score": 156038.72631281 }, { "content": "pub fn sequence_less_than(s1: u16, s2: u16) -> bool {\n\n sequence_greater_than(s2, s1)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::SequenceBuffer;\n\n use crate::packet::SequenceNumber;\n\n use crate::sequence_buffer::sequence_greater_than;\n\n use crate::sequence_buffer::sequence_less_than;\n\n\n\n #[derive(Clone, Default)]\n\n struct DataStub;\n\n\n\n #[test]\n\n fn test_sequence_comparisons_than() {\n\n assert!(sequence_greater_than(1, 0));\n\n assert!(sequence_less_than(0, 1));\n\n\n\n // Right around the halfway point is where we cut over.\n", "file_path": "src/sequence_buffer.rs", "rank": 3, "score": 156038.72631281 }, { "content": "/// This is an example of how to construct a packet.\n\npub fn construct_packet() -> Packet {\n\n // this is the destination address of the packet.\n\n let destination: SocketAddr = server_address();\n\n\n\n // lets construct some payload (raw data) for or packet.\n\n let raw_data = \"example data\".as_bytes();\n\n\n\n // lets construct or packet by passing in the destination for this packet and the bytes needed to be send..\n\n let packet: Packet = Packet::reliable_unordered(destination, raw_data.to_owned());\n\n\n\n packet\n\n}\n\n\n", "file_path": "examples/udp.rs", "rank": 4, "score": 139762.48969049274 }, { "content": "fn process_packet_when_received(connection: &mut VirtualConnection, data: &[u8]) {\n\n connection.process_incoming(&data).unwrap().unwrap();\n\n}\n\n\n", "file_path": "benches/packet_processing.rs", "rank": 5, "score": 138992.35897476514 }, { "content": "pub fn client_addr() -> SocketAddr {\n\n \"127.0.0.1:0\".parse().unwrap()\n\n}\n", "file_path": "tests/common/mod.rs", "rank": 6, "score": 137505.94572956496 }, { "content": "#[test]\n\n#[cfg(feature = \"tester\")]\n\nfn send_receive_unreliable_packets() {\n\n let client_addr = client_addr();\n\n let listen_addr: SocketAddr = \"127.0.0.1:12346\".parse().unwrap();\n\n let server = Server::new(listen_addr);\n\n\n\n let client = Client::new(Duration::from_millis(1), 5000);\n\n\n\n let assert_function = move |packet: Packet| {\n\n assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Unreliable);\n\n assert_eq!(packet.payload(), payload().as_slice());\n\n };\n\n\n\n let packet_factory = move || -> Packet { Packet::unreliable(listen_addr, payload()) };\n\n\n\n let server_handle = server.start_receiving(assert_function);\n\n\n\n client\n\n .run_instance(packet_factory, client_addr)\n\n .wait_until_finished();\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 7, "score": 115887.67440644708 }, { "content": "#[test]\n\n#[cfg(feature = \"tester\")]\n\nfn send_receive_fragment_packets() {\n\n let listen_addr: SocketAddr = \"127.0.0.1:12346\".parse().unwrap();\n\n let client_addr = client_addr();\n\n\n\n let server = Server::new(listen_addr);\n\n\n\n let client = Client::new(Duration::from_millis(1), 5000);\n\n\n\n let assert_function = move |packet: Packet| {\n\n assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Reliable);\n\n assert_eq!(packet.payload(), payload().as_slice());\n\n };\n\n\n\n let packet_factory = move || -> Packet { Packet::reliable_unordered(listen_addr, payload()) };\n\n\n\n let server_handle = server.start_receiving(assert_function);\n\n\n\n client\n\n .run_instance(packet_factory, client_addr)\n", "file_path": "tests/fragmentation_packets_test.rs", "rank": 8, "score": 115887.67440644708 }, { "content": "#[test]\n\n#[cfg(feature = \"tester\")]\n\nfn send_receive_unreliable_packets_muliple_clients() {\n\n let listen_addr: SocketAddr = \"127.0.0.1:12345\".parse().unwrap();\n\n let server = Server::new(listen_addr);\n\n let client = Client::new(Duration::from_millis(16), 500);\n\n\n\n let assert_function = move |packet: Packet| {\n\n assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Unreliable);\n\n assert_eq!(packet.payload(), payload().as_slice());\n\n };\n\n\n\n let packet_factory = move || -> Packet { Packet::unreliable(listen_addr, payload()) };\n\n\n\n let server_handle = server.start_receiving(assert_function);\n\n\n\n let received = server_handle.event_receiver();\n\n\n\n let handle = thread::spawn(move || loop {\n\n match received.recv() {\n\n Ok(event) => {\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 9, "score": 110352.44666791469 }, { "content": "fn receive_reliable_benchmark(c: &mut Criterion) {\n\n let mut connection =\n\n VirtualConnection::new(SERVER_ADDR.parse().unwrap(), &Arc::new(Config::default()));\n\n\n\n // setup fake received bytes.\n\n let mut buffer = acked_header_bytes(DeliveryMethod::ReliableUnordered, 0, 1, 2);\n\n buffer.append(&mut vec![1; 500]);\n\n\n\n c.bench_function(\"process reliable packet on receive\", move |b| {\n\n b.iter(|| process_packet_when_received(&mut connection, &buffer))\n\n });\n\n}\n\n\n\ncriterion_group!(\n\n benches,\n\n receive_unreliable_benchmark,\n\n receive_reliable_benchmark\n\n);\n\ncriterion_main!(benches);\n", "file_path": "benches/packet_processing.rs", "rank": 10, "score": 107352.16904550437 }, { "content": "fn receive_unreliable_benchmark(c: &mut Criterion) {\n\n let mut connection =\n\n VirtualConnection::new(SERVER_ADDR.parse().unwrap(), &Arc::new(Config::default()));\n\n\n\n // setup fake received bytes.\n\n let mut buffer = standard_header_bytes(DeliveryMethod::UnreliableUnordered);\n\n buffer.append(&mut vec![1; 500]);\n\n\n\n c.bench_function(\"process unreliable packet on receive\", move |b| {\n\n b.iter(|| process_packet_when_received(&mut connection, &buffer))\n\n });\n\n}\n\n\n", "file_path": "benches/packet_processing.rs", "rank": 11, "score": 107352.16904550437 }, { "content": "/// An arranging system that has multiple streams on which you can arrange items.\n\npub trait ArrangingSystem {\n\n /// The type of stream that is used for arranging items.\n\n type Stream;\n\n\n\n /// Returns the number of streams currently created.\n\n fn stream_count(&self) -> usize;\n\n /// Try to get a `Stream` by `stream_id`. When the stream does not exist, it will be inserted by the given `stream_id` and returned.\n\n fn get_or_create_stream(&mut self, stream_id: u8) -> &mut Self::Stream;\n\n}\n", "file_path": "src/infrastructure/arranging.rs", "rank": 12, "score": 103675.96069278542 }, { "content": "/// This is mimicking the `HeaderParser for StandardHeader` implementation which is no longer\n\n/// visible externally\n\nfn standard_header_bytes(delivery_method: DeliveryMethod) -> Vec<u8> {\n\n let mut buffer = Vec::new();\n\n buffer.write_u16::<BigEndian>(ProtocolVersion::get_crc16());\n\n // Represents a standard `Packet`\n\n buffer.write_u8(0);\n\n buffer.write_u8(delivery_method as u8);\n\n buffer\n\n}\n\n\n", "file_path": "benches/packet_processing.rs", "rank": 13, "score": 94305.94708906191 }, { "content": "#[allow(unused_must_use)]\n\npub fn main() {\n\n let mut server = Socket::bind(server_address()).unwrap();\n\n\n\n /* setup or `Client` and send some test data. */\n\n let mut client = Socket::bind(client_address()).unwrap();\n\n\n\n client.send(Packet::unreliable(\n\n server_address(),\n\n serialize(&DataType::Coords {\n\n latitude: 10.55454,\n\n longitude: 10.555,\n\n altitude: 1.3,\n\n })\n\n .unwrap(),\n\n ));\n\n\n\n client.send(Packet::unreliable(\n\n server_address(),\n\n serialize(&DataType::Coords {\n\n latitude: 3.344,\n", "file_path": "examples/simple_udp.rs", "rank": 14, "score": 90702.81710839437 }, { "content": "/// This is an example of how to receive data over udp.\n\npub fn receive_data() {\n\n // setup an udp socket and bind it to the client address.\n\n let mut socket = Socket::bind(server_address()).unwrap();\n\n\n\n // Next start receiving.\n\n loop {\n\n if let Some(result) = socket.recv() {\n\n match result {\n\n SocketEvent::Packet(packet) => {\n\n let endpoint: SocketAddr = packet.addr();\n\n let received_data: &[u8] = packet.payload();\n\n\n\n // you can here deserialize your bytes into the data you have passed it when sending.\n\n\n\n println!(\n\n \"Received packet from: {:?} with length {}\",\n\n endpoint,\n\n received_data.len()\n\n );\n\n }\n\n _ => {}\n\n }\n\n break;\n\n }\n\n }\n\n}\n\n\n", "file_path": "examples/udp.rs", "rank": 15, "score": 90698.75371720953 }, { "content": "/// This is an example of how to send data to an specific address.\n\npub fn send_data() {\n\n // Setup a udp socket and bind it to the client address.\n\n let mut socket = Socket::bind(client_address()).unwrap();\n\n\n\n let packet = construct_packet();\n\n\n\n // next send or packet to the endpoint we earlier putted into the packet.\n\n socket.send(packet);\n\n}\n\n\n", "file_path": "examples/udp.rs", "rank": 16, "score": 90698.75371720953 }, { "content": "/// A trait which can be implemented for arranging operations.\n\npub trait Arranging {\n\n type ArrangingItem;\n\n\n\n /// Arrange the given item based on the given index.\n\n /// If the `incoming_offset` somehow does not satisfies the arranging algorithm it returns `None`.\n\n /// If the `incoming_offset` satisfies the arranging algorithm it returns `Some` with the passed item.\n\n fn arrange(\n\n &mut self,\n\n incoming_index: usize,\n\n item: Self::ArrangingItem,\n\n ) -> Option<Self::ArrangingItem>;\n\n}\n\n\n", "file_path": "src/infrastructure/arranging.rs", "rank": 17, "score": 88212.31411449896 }, { "content": "fn process_packet_before_send(\n\n connection: &mut VirtualConnection,\n\n _config: &Config,\n\n delivery_method: DeliveryMethod,\n\n) {\n\n let payload = vec![1, 2, 3, 4, 5];\n\n\n\n let _packet_data = connection\n\n .process_outgoing(&payload, delivery_method)\n\n .unwrap();\n\n}\n\n\n", "file_path": "benches/packet_processing.rs", "rank": 18, "score": 82014.14844488459 }, { "content": "pub trait EnumConverter {\n\n type Enum;\n\n\n\n fn to_u8(&self) -> u8;\n\n}\n", "file_path": "src/packet.rs", "rank": 19, "score": 77913.35703760563 }, { "content": "#[cfg(feature = \"tester\")]\n\nmod common;\n\n#[cfg(feature = \"tester\")]\n\nuse common::{client_addr, Client, Server, ServerEvent};\n\n\n\nuse laminar::{DeliveryGuarantee, OrderingGuarantee, Packet};\n\nuse log::debug;\n\nuse std::net::SocketAddr;\n\nuse std::{thread, time::Duration};\n\n\n\n#[test]\n\n#[cfg(feature = \"tester\")]\n", "file_path": "tests/fragmentation_packets_test.rs", "rank": 20, "score": 74195.8282263578 }, { "content": "#[cfg(feature = \"tester\")]\n\nmod common;\n\n\n\n#[cfg(feature = \"tester\")]\n\nuse common::{client_addr, Client, Server, ServerEvent};\n\n\n\nuse laminar::{DeliveryGuarantee, OrderingGuarantee, Packet};\n\nuse log::{debug, error, info};\n\nuse std::net::SocketAddr;\n\nuse std::{thread, time::Duration};\n\n\n\n#[test]\n\n#[cfg(feature = \"tester\")]\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 21, "score": 74195.67193881553 }, { "content": " });\n\n\n\n let mut clients = Vec::new();\n\n\n\n for _ in 0..10 {\n\n clients.push(client.run_instance(packet_factory, client_addr()));\n\n info!(\"Client started.\");\n\n }\n\n\n\n for client in clients {\n\n client.wait_until_finished();\n\n info!(\"Client finished.\");\n\n }\n\n\n\n info!(\"Waiting 2 seconds\");\n\n // give the server time to process all packets.\n\n thread::sleep(Duration::from_millis(2000));\n\n info!(\"Shutting down server!\");\n\n server_handle.shutdown();\n\n server_handle.wait_until_finished();\n\n info!(\"Server is stopped\");\n\n handle.join().unwrap();\n\n}\n\n\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 22, "score": 74190.91879339662 }, { "content": " .wait_until_finished();\n\n\n\n // give the server time to process all packets.\n\n thread::sleep(Duration::from_millis(500));\n\n\n\n server_handle.shutdown();\n\n\n\n for event in server_handle.iter_events().collect::<Vec<ServerEvent>>() {\n\n match event {\n\n ServerEvent::Throughput(throughput) => {\n\n debug!(\"Throughput: {}\", throughput);\n\n }\n\n ServerEvent::AverageThroughput(avg_throughput) => {\n\n debug!(\"Avg. Throughput: {}\", avg_throughput);\n\n }\n\n ServerEvent::TotalSent(total) => {\n\n debug!(\"Total Packets Received {}\", total);\n\n }\n\n _ => debug!(\"Not handled!\"),\n\n }\n\n }\n\n\n\n server_handle.wait_until_finished();\n\n}\n\n\n", "file_path": "tests/fragmentation_packets_test.rs", "rank": 23, "score": 74185.73452566435 }, { "content": "\n\n // give the server time to process all packets.\n\n thread::sleep(Duration::from_millis(200));\n\n\n\n server_handle.shutdown();\n\n\n\n for event in server_handle.iter_events().collect::<Vec<ServerEvent>>() {\n\n match event {\n\n ServerEvent::Throughput(throughput) => {\n\n debug!(\"Throughput: {}\", throughput);\n\n }\n\n ServerEvent::AverageThroughput(avg_throughput) => {\n\n debug!(\"Avg. Throughput: {}\", avg_throughput);\n\n }\n\n ServerEvent::TotalSent(total) => {\n\n debug!(\"Total Packets Received {}\", total);\n\n }\n\n ServerEvent::SocketEvent(event) => {\n\n info!(\"Socket Event: {:?}\", event);\n\n }\n\n }\n\n }\n\n\n\n server_handle.wait_until_finished();\n\n}\n\n\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 24, "score": 74185.6661858824 }, { "content": " match event {\n\n ServerEvent::Throughput(throughput) => {\n\n info!(\"Throughput: {}\", throughput);\n\n }\n\n ServerEvent::AverageThroughput(avg_throughput) => {\n\n info!(\"Avg. Throughput: {}\", avg_throughput);\n\n }\n\n ServerEvent::TotalSent(total) => {\n\n info!(\"Total Received: {}\", total);\n\n }\n\n ServerEvent::SocketEvent(event) => {\n\n info!(\"Socket Event: {:?}\", event);\n\n }\n\n };\n\n }\n\n Err(_) => {\n\n error!(\"Stopped receiving events; closing event handler.\");\n\n return;\n\n }\n\n }\n", "file_path": "tests/unreliable_packets_test.rs", "rank": 25, "score": 74182.82411324466 }, { "content": "/// This is mimicking the `HeaderParser for AckedPacketHeader` implementation which is no longer\n\n/// visible externally\n\nfn acked_header_bytes(\n\n delivery_method: DeliveryMethod,\n\n seq: u16,\n\n ack_seq: u16,\n\n ack_field: u32,\n\n) -> Vec<u8> {\n\n let mut buffer = standard_header_bytes(delivery_method);\n\n buffer.write_u16::<BigEndian>(seq);\n\n buffer.write_u16::<BigEndian>(ack_seq);\n\n buffer.write_u32::<BigEndian>(ack_field);\n\n buffer\n\n}\n\n\n", "file_path": "benches/packet_processing.rs", "rank": 26, "score": 72802.67920431912 }, { "content": "/// Trait that supports reading a Header from a packet\n\npub trait HeaderReader {\n\n /// Associated type for the HeaderReader, since it reads it from a Header\n\n type Header;\n\n\n\n /// Read the specified header from the given Cursor.\n\n fn read(rdr: &mut Cursor<&[u8]>) -> Self::Header;\n\n\n\n /// This will get the size of the header.\n\n fn size() -> u8;\n\n}\n", "file_path": "src/packet/header/header_reader.rs", "rank": 27, "score": 70927.41419879124 }, { "content": "/// Trait for writing a header\n\npub trait HeaderWriter {\n\n /// Associated type since we parse the header into an Output\n\n type Output;\n\n\n\n /// Write the header to the given buffer.\n\n fn parse(&self, buffer: &mut Vec<u8>) -> Self::Output;\n\n}\n", "file_path": "src/packet/header/header_writer.rs", "rank": 28, "score": 70924.0212272028 }, { "content": "mod client;\n\nmod server;\n\n\n\npub use self::client::Client;\n\npub use self::server::{Server, ServerEvent};\n\n\n\nuse std::net::SocketAddr;\n\n\n", "file_path": "tests/common/mod.rs", "rank": 29, "score": 69785.12798247446 }, { "content": "use super::{HeaderReader, HeaderWriter};\n\nuse crate::error::Result;\n\nuse crate::net::constants::ARRANGING_PACKET_HEADER;\n\nuse crate::packet::SequenceNumber;\n\nuse byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};\n\nuse std::io::Cursor;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\n/// This header represents a fragmented packet header.\n\npub struct ArrangingHeader {\n\n arranging_id: SequenceNumber,\n\n stream_id: u8,\n\n}\n\n\n\nimpl ArrangingHeader {\n\n /// Create new fragment with the given packet header\n\n pub fn new(arranging_id: SequenceNumber, stream_id: u8) -> Self {\n\n ArrangingHeader {\n\n arranging_id,\n\n stream_id,\n", "file_path": "src/packet/header/arranging_header.rs", "rank": 42, "score": 62011.98137469009 }, { "content": " }\n\n }\n\n\n\n /// Get the sequence number from this packet.\n\n pub fn arranging_id(&self) -> SequenceNumber {\n\n self.arranging_id\n\n }\n\n\n\n /// Get the sequence number from this packet.\n\n pub fn stream_id(&self) -> u8 {\n\n self.stream_id\n\n }\n\n}\n\n\n\nimpl HeaderWriter for ArrangingHeader {\n\n type Output = Result<()>;\n\n\n\n fn parse(&self, buffer: &mut Vec<u8>) -> Self::Output {\n\n buffer.write_u16::<BigEndian>(self.arranging_id)?;\n\n buffer.write_u8(self.stream_id)?;\n", "file_path": "src/packet/header/arranging_header.rs", "rank": 43, "score": 62010.81194714549 }, { "content": " /// Get the size of this header.\n\n fn size() -> u8 {\n\n ARRANGING_PACKET_HEADER\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::net::constants::ARRANGING_PACKET_HEADER;\n\n use crate::packet::header::{ArrangingHeader, HeaderReader, HeaderWriter};\n\n use std::io::Cursor;\n\n\n\n #[test]\n\n fn serialize() {\n\n let mut buffer = Vec::new();\n\n let header = ArrangingHeader::new(1, 2);\n\n header.parse(&mut buffer).is_ok();\n\n\n\n assert_eq!(buffer[1], 1);\n\n assert_eq!(buffer[2], 2);\n", "file_path": "src/packet/header/arranging_header.rs", "rank": 44, "score": 62004.16121670571 }, { "content": "\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl HeaderReader for ArrangingHeader {\n\n type Header = Result<ArrangingHeader>;\n\n\n\n fn read(rdr: &mut Cursor<&[u8]>) -> Self::Header {\n\n let arranging_id = rdr.read_u16::<BigEndian>()?;\n\n let stream_id = rdr.read_u8()?;\n\n\n\n let header = ArrangingHeader {\n\n arranging_id,\n\n stream_id,\n\n };\n\n\n\n Ok(header)\n\n }\n\n\n", "file_path": "src/packet/header/arranging_header.rs", "rank": 45, "score": 62000.640542721936 }, { "content": " }\n\n\n\n #[test]\n\n fn deserialize() {\n\n let buffer = vec![0, 1, 2];\n\n let mut cursor = Cursor::new(buffer.as_slice());\n\n\n\n let header = ArrangingHeader::read(&mut cursor).unwrap();\n\n\n\n assert_eq!(header.arranging_id(), 1);\n\n assert_eq!(header.stream_id(), 2);\n\n }\n\n\n\n #[test]\n\n fn size() {\n\n assert_eq!(ArrangingHeader::size(), ARRANGING_PACKET_HEADER);\n\n }\n\n}\n", "file_path": "src/packet/header/arranging_header.rs", "rank": 46, "score": 61996.755033570094 }, { "content": "#[derive(Debug)]\n\nstruct ThroughputEntry {\n\n measured_throughput: u32,\n\n _start: Instant,\n\n}\n\n\n\nimpl ThroughputEntry {\n\n /// Construct a new throughput entry.\n\n pub fn new(measured_throughput: u32, time: Instant) -> ThroughputEntry {\n\n ThroughputEntry {\n\n measured_throughput,\n\n _start: time,\n\n }\n\n }\n\n}\n\n\n\n/// Helper to monitor throughput.\n\n///\n\n/// Throughput is calculated at some duration.\n\n/// For each duration an entry is created to keep track of the history of throughput.\n\n///\n", "file_path": "src/throughput.rs", "rank": 47, "score": 53734.49005306146 }, { "content": "// TODO: Use functions in example\n\nfn main() {}\n", "file_path": "examples/udp.rs", "rank": 48, "score": 47725.94047706402 }, { "content": "fn server_address() -> SocketAddr {\n\n SERVER_ADDR.parse().unwrap()\n\n}\n\n\n", "file_path": "examples/udp.rs", "rank": 49, "score": 42006.062336098395 }, { "content": "fn client_address() -> SocketAddr {\n\n CLIENT_ADDR.parse().unwrap()\n\n}\n\n\n", "file_path": "examples/udp.rs", "rank": 50, "score": 42006.062336098395 }, { "content": "fn server_address() -> SocketAddr {\n\n SERVER_ADDR.parse().unwrap()\n\n}\n\n\n\n/// This will run an simple example with client and server communicating.\n", "file_path": "examples/simple_udp.rs", "rank": 51, "score": 40824.7638141931 }, { "content": "fn client_address() -> SocketAddr {\n\n CLIENT_ADDR.parse().unwrap()\n\n}\n\n\n", "file_path": "examples/simple_udp.rs", "rank": 52, "score": 40824.7638141931 }, { "content": " ///\n\n /// # Remark\n\n /// - When `stream_id` is specified as `None` the default stream will be used; if you are not sure what this is you can leave it at `None`.\n\n pub fn reliable_sequenced(addr: SocketAddr, payload: Vec<u8>, stream_id: Option<u8>) -> Packet {\n\n Packet {\n\n addr,\n\n payload: payload.into_boxed_slice(),\n\n delivery: DeliveryGuarantee::Reliable,\n\n ordering: OrderingGuarantee::Sequenced(stream_id),\n\n }\n\n }\n\n\n\n /// Returns the payload of this packet.\n\n pub fn payload(&self) -> &[u8] {\n\n &self.payload\n\n }\n\n\n\n /// Returns the address of this packet.\n\n ///\n\n /// # Remark\n", "file_path": "src/packet/packet_structure.rs", "rank": 53, "score": 40669.34326937576 }, { "content": " /// when calling this function afterward it will read all the bytes from there on.\n\n pub fn read_payload(&self) -> Box<[u8]> {\n\n self.buffer[self.cursor.position() as usize..self.buffer.len()]\n\n .to_vec()\n\n .into_boxed_slice()\n\n }\n\n\n\n // checks if a given length of bytes could be read with the buffer.\n\n fn can_read(&self, length: u8) -> bool {\n\n (self.buffer.len() - self.cursor.position() as usize) >= length as usize\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::packet::header::{AckedPacketHeader, HeaderReader, StandardHeader};\n\n use crate::packet::{DeliveryGuarantee, OrderingGuarantee, PacketReader, PacketType};\n\n\n\n #[test]\n\n fn can_read_bytes() {\n", "file_path": "src/packet/packet_reader.rs", "rank": 54, "score": 40665.73076880295 }, { "content": " delivery: DeliveryGuarantee::Reliable,\n\n ordering: OrderingGuarantee::None,\n\n }\n\n }\n\n\n\n /// Create a new packet by passing the receiver, data and a optional stream on which the ordering will be done.\n\n ///\n\n /// Reliable; All packets will be sent and received, with order.\n\n ///\n\n /// *Details*\n\n ///\n\n /// | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation | Packet Delivery |\n\n /// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: |\n\n /// | No | No | Ordered | Yes | Yes |\n\n ///\n\n /// Basically this is almost TCP-like with ordering of packets.\n\n ///\n\n /// # Remark\n\n /// - When `stream_id` is specified as `None` the default stream will be used; if you are not sure what this is you can leave it at `None`.\n\n pub fn reliable_ordered(addr: SocketAddr, payload: Vec<u8>, stream_id: Option<u8>) -> Packet {\n", "file_path": "src/packet/packet_structure.rs", "rank": 55, "score": 40662.59152693129 }, { "content": " // standard header, arranging header\n\n let reliable_ordered_payload: Vec<u8> = vec![vec![0, 1, 0, 1, 2], vec![0, 1, 2]].concat();\n\n\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let arranging_header = reader\n\n .read_arranging_header(StandardHeader::size() as u16)\n\n .unwrap();\n\n\n\n assert_eq!(arranging_header.arranging_id(), 1);\n\n assert_eq!(arranging_header.stream_id(), 2);\n\n }\n\n\n\n #[test]\n\n fn assure_read_reliable_ordered_header() {\n\n // standard header, acked header, arranging header\n\n let reliable_ordered_payload: Vec<u8> = vec![\n\n vec![0, 1, 0, 1, 2],\n\n vec![0, 1, 0, 2, 0, 0, 0, 3],\n\n vec![0, 1, 2],\n", "file_path": "src/packet/packet_reader.rs", "rank": 56, "score": 40662.510793269845 }, { "content": "use crate::net::constants::STANDARD_HEADER_SIZE;\n\nuse crate::packet::header::{\n\n AckedPacketHeader, ArrangingHeader, FragmentHeader, HeaderReader, StandardHeader,\n\n};\n\nuse crate::{ErrorKind, Result};\n\n\n\nuse std::io::Cursor;\n\n\n\n/// Can be used to read the packet contents of laminar.\n\n///\n\n/// # Remarks\n\n/// - `PacketReader` is using an underlying `Cursor` to manage the reading of the bytes.\n\n/// - `PacketReader` can interpret where some data is located in the buffer, that's why you don't have to worry about the position of the `Cursor`.\n\npub struct PacketReader<'s> {\n\n buffer: &'s [u8],\n\n cursor: Cursor<&'s [u8]>,\n\n}\n\n\n\nimpl<'s> PacketReader<'s> {\n\n /// Construct a new instance of `PacketReader`, the given `buffer` will be used to read information from.\n", "file_path": "src/packet/packet_reader.rs", "rank": 57, "score": 40660.99737731199 }, { "content": " /// Could be both the receiving endpoint or the one to send this packet to.\n\n /// This depends whether it is a packet that has been received or one that needs to be send.\n\n pub fn addr(&self) -> SocketAddr {\n\n self.addr\n\n }\n\n\n\n /// Returns the [`DeliveryGuarantee`](./enum.DeliveryGuarantee.html) of this packet.\n\n pub fn delivery_guarantee(&self) -> DeliveryGuarantee {\n\n self.delivery\n\n }\n\n\n\n /// Returns the [`OrderingGuarantee`](./enum.OrderingGuarantee.html) of this packet.\n\n pub fn order_guarantee(&self) -> OrderingGuarantee {\n\n self.ordering\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::packet::{DeliveryGuarantee, OrderingGuarantee, Packet};\n", "file_path": "src/packet/packet_structure.rs", "rank": 58, "score": 40660.719647038866 }, { "content": " assert_eq!(standard_header.packet_type(), PacketType::Packet);\n\n assert_eq!(\n\n standard_header.delivery_guarantee(),\n\n DeliveryGuarantee::Reliable\n\n );\n\n assert_eq!(\n\n standard_header.ordering_guarantee(),\n\n OrderingGuarantee::Ordered(None)\n\n );\n\n\n\n assert_eq!(acked_header.sequence(), 1);\n\n assert_eq!(acked_header.ack_seq(), 2);\n\n assert_eq!(acked_header.ack_field(), 3);\n\n }\n\n\n\n #[test]\n\n fn expect_read_error() {\n\n // standard header (with one corrupt byte)\n\n let reliable_ordered_payload: Vec<u8> = vec![vec![0, 1, 0, 1]].concat();\n\n\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n assert!(reader.read_standard_header().is_err());\n\n }\n\n}\n", "file_path": "src/packet/packet_reader.rs", "rank": 59, "score": 40660.34648562646 }, { "content": " }\n\n\n\n /// Create a new unreliable sequenced packet by passing the receiver, data.\n\n ///\n\n /// Unreliable Sequenced; Packets can be dropped, but could not be duplicated and arrive in sequence.\n\n ///\n\n /// *Details*\n\n ///\n\n /// | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation | Packet Delivery |\n\n /// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: |\n\n /// | Yes | Yes | Sequenced | No | No |\n\n ///\n\n /// Basically just bare UDP, free to be dropped, but has some sequencing to it so that only the newest packets are kept.\n\n pub fn unreliable_sequenced(\n\n addr: SocketAddr,\n\n payload: Vec<u8>,\n\n stream_id: Option<u8>,\n\n ) -> Packet {\n\n Packet {\n\n addr,\n", "file_path": "src/packet/packet_structure.rs", "rank": 60, "score": 40660.29541427742 }, { "content": " ]\n\n .concat();\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let standard_header = reader.read_standard_header().unwrap();\n\n let acked_header = reader.read_acknowledge_header().unwrap();\n\n let arranging_header = reader\n\n .read_arranging_header((StandardHeader::size() + AckedPacketHeader::size()) as u16)\n\n .unwrap();\n\n\n\n assert_eq!(standard_header.protocol_version(), 1);\n\n assert_eq!(standard_header.packet_type(), PacketType::Packet);\n\n assert_eq!(\n\n standard_header.delivery_guarantee(),\n\n DeliveryGuarantee::Reliable\n\n );\n\n assert_eq!(\n\n standard_header.ordering_guarantee(),\n\n OrderingGuarantee::Ordered(None)\n\n );\n", "file_path": "src/packet/packet_reader.rs", "rank": 61, "score": 40659.85216327136 }, { "content": "use crate::packet::{DeliveryGuarantee, OrderingGuarantee};\n\nuse std::net::SocketAddr;\n\n\n\n#[derive(Clone, PartialEq, Eq, Debug)]\n\n/// This is a user friendly packet containing the payload, endpoint, and reliability guarantees.\n\n/// A packet could have reliability guarantees to specify how it should be delivered and processed.\n\n///\n\n/// | Reliability Type | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation |Packet Delivery|\n\n/// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: | :-------------:\n\n/// | **Unreliable Unordered** | Yes | Yes | No | No | No\n\n/// | **Reliable Unordered** | No | No | No | Yes | Yes\n\n/// | **Reliable Ordered** | No | No | Ordered | Yes | Yes\n\n/// | **Sequenced** | Yes | No | Sequenced | No | No\n\n///\n\n/// You are able to send packets with any the above guarantees.\n\npub struct Packet {\n\n /// the endpoint from where it came\n\n addr: SocketAddr,\n\n /// the raw payload of the packet\n\n payload: Box<[u8]>,\n", "file_path": "src/packet/packet_structure.rs", "rank": 62, "score": 40659.84164852355 }, { "content": "\n\n assert_eq!(acked_header.sequence(), 1);\n\n assert_eq!(acked_header.ack_seq(), 2);\n\n assert_eq!(acked_header.ack_field(), 3);\n\n\n\n assert_eq!(arranging_header.arranging_id(), 1);\n\n assert_eq!(arranging_header.stream_id(), 2);\n\n }\n\n\n\n #[test]\n\n fn assure_read_reliable_unordered_header() {\n\n // standard header, acked header, arranging header\n\n let reliable_ordered_payload: Vec<u8> =\n\n vec![vec![0, 1, 0, 1, 2], vec![0, 1, 0, 2, 0, 0, 0, 3]].concat();\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let standard_header = reader.read_standard_header().unwrap();\n\n let acked_header = reader.read_acknowledge_header().unwrap();\n\n\n\n assert_eq!(standard_header.protocol_version(), 1);\n", "file_path": "src/packet/packet_reader.rs", "rank": 63, "score": 40659.45025042396 }, { "content": " assert_eq!(acked_header.ack_field(), 3);\n\n }\n\n\n\n #[test]\n\n fn assure_read_fragment_header() {\n\n // standard header, acked header, arranging header\n\n let reliable_ordered_payload: Vec<u8> = vec![\n\n vec![0, 1, 0, 1, 2],\n\n vec![0, 1, 0, 3],\n\n vec![0, 1, 0, 2, 0, 0, 0, 3],\n\n ]\n\n .concat();\n\n\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let standard_header = reader.read_standard_header().unwrap();\n\n let (fragment_header, acked_header) = reader.read_fragment().unwrap();\n\n\n\n assert_eq!(standard_header.protocol_version(), 1);\n\n assert_eq!(standard_header.packet_type(), PacketType::Packet);\n", "file_path": "src/packet/packet_reader.rs", "rank": 64, "score": 40659.27695376581 }, { "content": " let buffer = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n\n\n let reader = PacketReader::new(buffer.as_slice());\n\n assert_eq!(reader.can_read(buffer.len() as u8), true);\n\n assert_eq!(reader.can_read((buffer.len() + 1) as u8), false);\n\n }\n\n\n\n #[test]\n\n fn assure_read_standard_header() {\n\n // standard header\n\n let reliable_ordered_payload: Vec<u8> = vec![vec![0, 1, 0, 1, 2]].concat();\n\n\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let standard_header = reader.read_standard_header().unwrap();\n\n\n\n assert_eq!(standard_header.protocol_version(), 1);\n\n assert_eq!(standard_header.packet_type(), PacketType::Packet);\n\n assert_eq!(\n\n standard_header.delivery_guarantee(),\n", "file_path": "src/packet/packet_reader.rs", "rank": 65, "score": 40658.45441762063 }, { "content": " DeliveryGuarantee::Reliable\n\n );\n\n assert_eq!(\n\n standard_header.ordering_guarantee(),\n\n OrderingGuarantee::Ordered(None)\n\n );\n\n }\n\n\n\n #[test]\n\n fn assure_read_acknowledgment_header() {\n\n // standard header, acked header\n\n let reliable_ordered_payload: Vec<u8> =\n\n vec![vec![0, 1, 0, 1, 2], vec![0, 1, 0, 2, 0, 0, 0, 3]].concat();\n\n\n\n let mut reader = PacketReader::new(reliable_ordered_payload.as_slice());\n\n\n\n let acked_header = reader.read_acknowledge_header().unwrap();\n\n\n\n assert_eq!(acked_header.sequence(), 1);\n\n assert_eq!(acked_header.ack_seq(), 2);\n", "file_path": "src/packet/packet_reader.rs", "rank": 66, "score": 40657.54724183402 }, { "content": "\n\n /// Read the `StandardHeader` from the underlying buffer.\n\n ///\n\n /// # Remark\n\n /// - Will change the position to the location of `StandardHeader`\n\n pub fn read_arranging_header(&mut self, start_offset: u16) -> Result<ArrangingHeader> {\n\n self.cursor.set_position(u64::from(start_offset));\n\n\n\n if self.can_read(ArrangingHeader::size()) {\n\n ArrangingHeader::read(&mut self.cursor)\n\n } else {\n\n Err(ErrorKind::CouldNotReadHeader(String::from(\"arranging\")))\n\n }\n\n }\n\n\n\n /// Read the `AckedPacketHeader` from the underlying buffer.\n\n ///\n\n /// # Remark\n\n /// - Will change the position to the location of `AckedPacketHeader`\n\n pub fn read_acknowledge_header(&mut self) -> Result<AckedPacketHeader> {\n", "file_path": "src/packet/packet_reader.rs", "rank": 67, "score": 40657.398072068616 }, { "content": " payload: payload.into_boxed_slice(),\n\n delivery: DeliveryGuarantee::Unreliable,\n\n ordering: OrderingGuarantee::Sequenced(stream_id),\n\n }\n\n }\n\n\n\n /// Create a new packet by passing the receiver, data.\n\n /// Reliable; All packets will be sent and received, but without order.\n\n ///\n\n /// *Details*\n\n ///\n\n /// | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation | Packet Delivery |\n\n /// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: |\n\n /// | No | No | No | Yes | Yes |\n\n ///\n\n /// Basically this is almost TCP without ordering of packets.\n\n pub fn reliable_unordered(addr: SocketAddr, payload: Vec<u8>) -> Packet {\n\n Packet {\n\n addr,\n\n payload: payload.into_boxed_slice(),\n", "file_path": "src/packet/packet_structure.rs", "rank": 68, "score": 40656.76644768761 }, { "content": " Packet {\n\n addr,\n\n payload: payload.into_boxed_slice(),\n\n delivery: DeliveryGuarantee::Reliable,\n\n ordering: OrderingGuarantee::Ordered(stream_id),\n\n }\n\n }\n\n\n\n /// Create a new packet by passing the receiver, data and a optional stream on which the sequencing will be done.\n\n ///\n\n /// Reliable; All packets will be sent and received, but arranged in sequence.\n\n /// Which means that only the newest packets will be let through, older packets will be received but they won't get to the user.\n\n ///\n\n /// *Details*\n\n ///\n\n /// | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation | Packet Delivery |\n\n /// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: |\n\n /// | Yes | No | Sequenced | Yes | Yes |\n\n ///\n\n /// Basically this is almost TCP-like but then sequencing instead of ordering.\n", "file_path": "src/packet/packet_structure.rs", "rank": 69, "score": 40656.73277073191 }, { "content": " use std::net::SocketAddr;\n\n\n\n #[test]\n\n fn assure_creation_unreliable_packet() {\n\n let packet = Packet::unreliable(test_addr(), test_payload());\n\n\n\n assert_eq!(packet.addr(), test_addr());\n\n assert_eq!(packet.payload(), test_payload().as_slice());\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Unreliable);\n\n assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);\n\n }\n\n\n\n #[test]\n\n fn assure_creation_unreliable_sequenced() {\n\n let packet = Packet::unreliable_sequenced(test_addr(), test_payload(), Some(1));\n\n\n\n assert_eq!(packet.addr(), test_addr());\n\n assert_eq!(packet.payload(), test_payload().as_slice());\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Unreliable);\n\n assert_eq!(\n", "file_path": "src/packet/packet_structure.rs", "rank": 70, "score": 40656.68786890738 }, { "content": " pub fn new(buffer: &'s [u8]) -> PacketReader<'s> {\n\n PacketReader {\n\n buffer,\n\n cursor: Cursor::new(buffer),\n\n }\n\n }\n\n\n\n /// Read the `StandardHeader` from the underlying buffer.\n\n ///\n\n /// # Remark\n\n /// - Will change the position to the location of `StandardHeader`\n\n pub fn read_standard_header(&mut self) -> Result<StandardHeader> {\n\n self.cursor.set_position(0);\n\n\n\n if self.can_read(StandardHeader::size()) {\n\n StandardHeader::read(&mut self.cursor)\n\n } else {\n\n Err(ErrorKind::CouldNotReadHeader(String::from(\"standard\")))\n\n }\n\n }\n", "file_path": "src/packet/packet_reader.rs", "rank": 71, "score": 40656.47037765114 }, { "content": " /// defines on how the packet will be delivered.\n\n delivery: DeliveryGuarantee,\n\n /// defines on how the packet will be ordered.\n\n ordering: OrderingGuarantee,\n\n}\n\n\n\nimpl Packet {\n\n /// Create a new packet by passing the receiver, data, and guarantees on how this packet should be delivered.\n\n pub(crate) fn new(\n\n addr: SocketAddr,\n\n payload: Box<[u8]>,\n\n delivery: DeliveryGuarantee,\n\n ordering: OrderingGuarantee,\n\n ) -> Packet {\n\n Packet {\n\n addr,\n\n payload,\n\n delivery,\n\n ordering,\n\n }\n", "file_path": "src/packet/packet_structure.rs", "rank": 72, "score": 40656.460031687624 }, { "content": " }\n\n\n\n /// Create a new unreliable packet by passing the receiver, data.\n\n ///\n\n /// Unreliable: Packets can be dropped, duplicated or arrive without order.\n\n ///\n\n /// **Details**\n\n ///\n\n /// | Packet Drop | Packet Duplication | Packet Order | Packet Fragmentation | Packet Delivery |\n\n /// | :-------------: | :-------------: | :-------------: | :-------------: | :-------------: |\n\n /// | Yes | Yes | No | No | No |\n\n ///\n\n /// Basically just bare UDP. The packet may or may not be delivered.\n\n pub fn unreliable(addr: SocketAddr, payload: Vec<u8>) -> Packet {\n\n Packet {\n\n addr,\n\n payload: payload.into_boxed_slice(),\n\n delivery: DeliveryGuarantee::Unreliable,\n\n ordering: OrderingGuarantee::None,\n\n }\n", "file_path": "src/packet/packet_structure.rs", "rank": 73, "score": 40654.61728405203 }, { "content": " packet.order_guarantee(),\n\n OrderingGuarantee::Sequenced(Some(1))\n\n );\n\n }\n\n\n\n #[test]\n\n fn assure_creation_reliable() {\n\n let packet = Packet::reliable_unordered(test_addr(), test_payload());\n\n\n\n assert_eq!(packet.addr(), test_addr());\n\n assert_eq!(packet.payload(), test_payload().as_slice());\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Reliable);\n\n assert_eq!(packet.order_guarantee(), OrderingGuarantee::None);\n\n }\n\n\n\n #[test]\n\n fn assure_creation_reliable_ordered() {\n\n let packet = Packet::reliable_ordered(test_addr(), test_payload(), Some(1));\n\n\n\n assert_eq!(packet.addr(), test_addr());\n", "file_path": "src/packet/packet_structure.rs", "rank": 74, "score": 40654.10663990043 }, { "content": " assert_eq!(packet.payload(), test_payload().as_slice());\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Reliable);\n\n assert_eq!(\n\n packet.order_guarantee(),\n\n OrderingGuarantee::Ordered(Some(1))\n\n );\n\n }\n\n\n\n #[test]\n\n fn assure_creation_reliable_sequence() {\n\n let packet = Packet::reliable_sequenced(test_addr(), test_payload(), Some(1));\n\n\n\n assert_eq!(packet.addr(), test_addr());\n\n assert_eq!(packet.payload(), test_payload().as_slice());\n\n assert_eq!(packet.delivery_guarantee(), DeliveryGuarantee::Reliable);\n\n assert_eq!(\n\n packet.order_guarantee(),\n\n OrderingGuarantee::Sequenced(Some(1))\n\n );\n\n }\n", "file_path": "src/packet/packet_structure.rs", "rank": 75, "score": 40652.76354953383 }, { "content": " // acknowledge header comes after standard header.\n\n self.cursor.set_position(u64::from(STANDARD_HEADER_SIZE));\n\n\n\n if self.can_read(AckedPacketHeader::size()) {\n\n AckedPacketHeader::read(&mut self.cursor)\n\n } else {\n\n Err(ErrorKind::CouldNotReadHeader(String::from(\n\n \"acknowledgment\",\n\n )))\n\n }\n\n }\n\n\n\n /// Read the `FragmentHeader` and optionally the `AckedPacketHeader` from the underlying buffer.\n\n ///\n\n /// # Remark\n\n /// - Notice that this will continue on the position of last read header;\n\n /// e.g. when reading `StandardHeader` the position of the underlying `Cursor` will be at the end where it left of,\n\n /// when calling this function afterward it will read the `FragmentHeader` from there on.\n\n /// - Note that only the first fragment of a sequence contains acknowledgment information that's why `AckedPacketHeader` is optional.\n\n pub fn read_fragment(&mut self) -> Result<(FragmentHeader, Option<AckedPacketHeader>)> {\n", "file_path": "src/packet/packet_reader.rs", "rank": 76, "score": 40651.033323097334 }, { "content": " assert_eq!(\n\n standard_header.delivery_guarantee(),\n\n DeliveryGuarantee::Reliable\n\n );\n\n assert_eq!(\n\n standard_header.ordering_guarantee(),\n\n OrderingGuarantee::Ordered(None)\n\n );\n\n\n\n assert_eq!(acked_header.unwrap().sequence(), 1);\n\n assert_eq!(acked_header.unwrap().ack_seq(), 2);\n\n assert_eq!(acked_header.unwrap().ack_field(), 3);\n\n\n\n assert_eq!(fragment_header.sequence(), 1);\n\n assert_eq!(fragment_header.id(), 0);\n\n assert_eq!(fragment_header.fragment_count(), 3);\n\n }\n\n\n\n #[test]\n\n fn assure_read_unreliable_sequenced_header() {\n", "file_path": "src/packet/packet_reader.rs", "rank": 77, "score": 40649.20000742191 }, { "content": "\n\n fn test_payload() -> Vec<u8> {\n\n return \"test\".as_bytes().to_vec();\n\n }\n\n\n\n fn test_addr() -> SocketAddr {\n\n \"127.0.0.1:12345\".parse().unwrap()\n\n }\n\n}\n", "file_path": "src/packet/packet_structure.rs", "rank": 78, "score": 40648.85765425286 }, { "content": " if self.can_read(FragmentHeader::size()) {\n\n let fragment_header = FragmentHeader::read(&mut self.cursor)?;\n\n\n\n let acked_header = if fragment_header.id() == 0 {\n\n Some(AckedPacketHeader::read(&mut self.cursor)?)\n\n } else {\n\n None\n\n };\n\n\n\n Ok((fragment_header, acked_header))\n\n } else {\n\n Err(ErrorKind::CouldNotReadHeader(String::from(\"fragment\")))\n\n }\n\n }\n\n\n\n /// Read the payload` from the underlying buffer.\n\n ///\n\n /// # Remark\n\n /// - Notice that this will continue on the position of last read header;\n\n /// e.g. when reading `StandardHeader` the position of the underlying `Cursor` will be at the end where it left of,\n", "file_path": "src/packet/packet_reader.rs", "rank": 79, "score": 40648.55068890203 }, { "content": "fn server() -> Result<(), ErrorKind> {\n\n let mut socket = Socket::bind(SERVER)?;\n\n let (mut sender, mut receiver) = (socket.get_packet_sender(), socket.get_event_receiver());\n\n let _thread = thread::spawn(move || socket.start_polling());\n\n\n\n loop {\n\n if let Ok(event) = receiver.recv() {\n\n match event {\n\n SocketEvent::Packet(packet) => {\n\n let msg = packet.payload();\n\n\n\n if msg == b\"Bye!\" {\n\n break;\n\n }\n\n\n\n let msg = String::from_utf8_lossy(msg);\n\n let ip = packet.addr().ip();\n\n\n\n println!(\"Received {:?} from {:?}\", msg, ip);\n\n\n", "file_path": "examples/server_client.rs", "rank": 80, "score": 39620.93614599693 }, { "content": "fn main() -> Result<(), ErrorKind> {\n\n let stdin = stdin();\n\n\n\n println!(\"Please type in `server` or `client`.\");\n\n\n\n let mut s = String::new();\n\n stdin.read_line(&mut s)?;\n\n\n\n if s.starts_with(\"s\") {\n\n println!(\"Starting server..\");\n\n server()\n\n } else {\n\n println!(\"Starting client..\");\n\n client()\n\n }\n\n}\n", "file_path": "examples/server_client.rs", "rank": 81, "score": 39620.93614599693 }, { "content": "fn client() -> Result<(), ErrorKind> {\n\n let addr = \"127.0.0.1:12352\";\n\n let mut socket = Socket::bind(addr)?;\n\n println!(\"Connected on {}\", addr);\n\n\n\n let server = SERVER.parse().unwrap();\n\n\n\n println!(\"Type a message and press Enter to send. Send `Bye!` to quit.\");\n\n\n\n let stdin = stdin();\n\n let mut s_buffer = String::new();\n\n\n\n loop {\n\n s_buffer.clear();\n\n stdin.read_line(&mut s_buffer)?;\n\n let line = s_buffer.replace(|x| x == '\\n' || x == '\\r', \"\");\n\n\n\n socket.send(Packet::reliable_unordered(\n\n server,\n\n line.clone().into_bytes(),\n", "file_path": "examples/server_client.rs", "rank": 82, "score": 39620.93614599693 }, { "content": " fn read(rdr: &mut Cursor<&[u8]>) -> Self::Header {\n\n let seq = rdr.read_u16::<BigEndian>()?;\n\n let ack_seq = rdr.read_u16::<BigEndian>()?;\n\n let ack_field = rdr.read_u32::<BigEndian>()?;\n\n\n\n Ok(AckedPacketHeader {\n\n seq,\n\n ack_seq,\n\n ack_field,\n\n })\n\n }\n\n\n\n fn size() -> u8 {\n\n ACKED_PACKET_HEADER\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::net::constants::ACKED_PACKET_HEADER;\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 83, "score": 38511.17794231002 }, { "content": " /// Get last acknowledged sequence number.\n\n pub fn ack_seq(&self) -> u16 {\n\n self.ack_seq\n\n }\n\n}\n\n\n\nimpl HeaderWriter for AckedPacketHeader {\n\n type Output = Result<()>;\n\n\n\n fn parse(&self, buffer: &mut Vec<u8>) -> Self::Output {\n\n buffer.write_u16::<BigEndian>(self.seq)?;\n\n buffer.write_u16::<BigEndian>(self.ack_seq)?;\n\n buffer.write_u32::<BigEndian>(self.ack_field)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl HeaderReader for AckedPacketHeader {\n\n type Header = Result<AckedPacketHeader>;\n\n\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 84, "score": 38509.78957923764 }, { "content": "use super::{HeaderReader, HeaderWriter};\n\nuse crate::error::Result;\n\nuse crate::net::constants::ACKED_PACKET_HEADER;\n\nuse byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};\n\nuse std::io::Cursor;\n\n\n\n#[derive(Copy, Clone, Debug)]\n\n/// This header providing reliability information.\n\npub struct AckedPacketHeader {\n\n /// this is the sequence number so that we can know where in the sequence of packages this packet belongs.\n\n pub seq: u16,\n\n // this is the last acknowledged sequence number.\n\n ack_seq: u16,\n\n // this is an bitfield of all last 32 acknowledged packages\n\n ack_field: u32,\n\n}\n\n\n\nimpl AckedPacketHeader {\n\n /// When we compose packet headers, the local sequence becomes the sequence number of the packet, and the remote sequence becomes the ack.\n\n /// The ack bitfield is calculated by looking into a queue of up to 33 packets, containing sequence numbers in the range [remote sequence - 32, remote sequence].\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 85, "score": 38508.51823620005 }, { "content": " use crate::packet::header::{AckedPacketHeader, HeaderReader, HeaderWriter};\n\n use std::io::Cursor;\n\n\n\n #[test]\n\n fn serialize() {\n\n let mut buffer = Vec::new();\n\n let header = AckedPacketHeader::new(1, 2, 3);\n\n header.parse(&mut buffer).is_ok();\n\n\n\n assert_eq!(buffer[1], 1);\n\n assert_eq!(buffer[3], 2);\n\n assert_eq!(buffer[7], 3);\n\n assert_eq!(buffer.len() as u8, AckedPacketHeader::size());\n\n }\n\n\n\n #[test]\n\n fn deserialize() {\n\n let buffer = vec![0, 1, 0, 2, 0, 0, 0, 3];\n\n\n\n let mut cursor = Cursor::new(buffer.as_slice());\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 86, "score": 38506.956403794975 }, { "content": " /// We set bit n (in [1,32]) in ack bits to 1 if the sequence number remote sequence - n is in the received queue.\n\n pub fn new(seq_num: u16, last_seq: u16, bit_field: u32) -> AckedPacketHeader {\n\n AckedPacketHeader {\n\n seq: seq_num,\n\n ack_seq: last_seq,\n\n ack_field: bit_field,\n\n }\n\n }\n\n\n\n /// Get the sequence number from this packet.\n\n #[allow(dead_code)]\n\n pub fn sequence(&self) -> u16 {\n\n self.seq\n\n }\n\n\n\n /// Get bit field of all last 32 acknowledged packages\n\n pub fn ack_field(&self) -> u32 {\n\n self.ack_field\n\n }\n\n\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 87, "score": 38504.090085489 }, { "content": "\n\n let header = AckedPacketHeader::read(&mut cursor).unwrap();\n\n\n\n assert_eq!(header.sequence(), 1);\n\n assert_eq!(header.ack_seq(), 2);\n\n assert_eq!(header.ack_field(), 3);\n\n }\n\n\n\n #[test]\n\n fn size() {\n\n assert_eq!(AckedPacketHeader::size(), ACKED_PACKET_HEADER);\n\n }\n\n}\n", "file_path": "src/packet/header/acked_packet_header.rs", "rank": 88, "score": 38498.90502854121 }, { "content": "//! This module provides all the logic around the packet, such as reading, parsing, and constructing headers.\n\n\n\npub mod header;\n\n\n\nmod enums;\n\nmod outgoing;\n\nmod packet_reader;\n\nmod packet_structure;\n\n\n\npub use self::enums::{DeliveryGuarantee, OrderingGuarantee, PacketType};\n\npub use self::outgoing::{Outgoing, OutgoingPacket, OutgoingPacketBuilder};\n\npub use self::packet_reader::PacketReader;\n\npub use self::packet_structure::Packet;\n\n\n\npub type SequenceNumber = u16;\n\n\n", "file_path": "src/packet.rs", "rank": 89, "score": 34925.2178672912 }, { "content": "use laminar::{Config, Packet, Socket};\n\nuse log::{error, info};\n\nuse std::net::SocketAddr;\n\nuse std::thread::{self, JoinHandle};\n\nuse std::time::Duration;\n\nuse std::time::Instant;\n\n\n\n/// Represents a client to some endpoint.\n\npub struct Client {\n\n /// The sending timeout\n\n pub sending_timeout: Duration,\n\n /// The number of packets to send\n\n pub packets_to_send: u32,\n\n}\n\n\n\nimpl Client {\n\n /// Constructs a new `Client`.\n\n pub fn new(timeout_sending: Duration, packets_to_send: u32) -> Client {\n\n Client {\n\n sending_timeout: timeout_sending,\n", "file_path": "tests/common/client.rs", "rank": 90, "score": 34712.815160028396 }, { "content": " SocketEvent(SocketEvent),\n\n}\n\n\n\n/// Represents a server which receives packets from some endpoint.\n\npub struct Server {\n\n throughput_monitor: ThroughputMonitoring,\n\n listening_host: SocketAddr,\n\n}\n\n\n\nimpl Server {\n\n /// Constructs a new `Server` instance.\n\n pub fn new(listening_host: SocketAddr) -> Server {\n\n Server {\n\n throughput_monitor: ThroughputMonitoring::new(Duration::from_millis(1000)),\n\n listening_host,\n\n }\n\n }\n\n\n\n /// Start to receive packets from some endpoint.\n\n /// This function takes in a closure with which a packet contents will be asserted.\n", "file_path": "tests/common/server.rs", "rank": 91, "score": 34708.35965574569 }, { "content": "\n\n/// This is a handle to a running client which is sending data to some endpoint.\n\npub struct ClientHandle {\n\n thread_handle: JoinHandle<()>,\n\n}\n\n\n\nimpl ClientHandle {\n\n /// Constructs a new `ClientHandle` by the given thread handle.\n\n pub fn new(handle: JoinHandle<()>) -> ClientHandle {\n\n ClientHandle {\n\n thread_handle: handle,\n\n }\n\n }\n\n\n\n /// Wait until the client has sent all of its packets.\n\n pub fn wait_until_finished(self) {\n\n self.thread_handle.join().unwrap();\n\n }\n\n}\n", "file_path": "tests/common/client.rs", "rank": 92, "score": 34707.65620533371 }, { "content": " packets_to_send,\n\n }\n\n }\n\n\n\n /// This will run a specific instance of the client running at the given socket address.\n\n /// This function takes in a closure who constructs a packet which will be sent out to the client.\n\n pub fn run_instance<F>(&self, create_packet: F, endpoint: SocketAddr) -> ClientHandle\n\n where\n\n F: Fn() -> Packet + Send + 'static,\n\n {\n\n let timeout = self.sending_timeout;\n\n let packets_to_send = self.packets_to_send;\n\n\n\n let handle = thread::spawn(move || {\n\n let mut socket = Socket::bind(endpoint).unwrap();\n\n\n\n info!(\"Client {:?} starts to send packets.\", endpoint);\n\n\n\n for _ in 0..packets_to_send {\n\n let packet = create_packet();\n", "file_path": "tests/common/client.rs", "rank": 93, "score": 34706.19216875255 }, { "content": " pub fn start_receiving<F>(self, packet_assert: F) -> ServerHandle\n\n where\n\n F: Fn(Packet) + Send + Sized + 'static,\n\n {\n\n let mut socket = Socket::bind(self.listening_host).unwrap();\n\n\n\n let (notify_tx, notify_rx) = crossbeam_channel::unbounded();\n\n let (events_tx, events_rx) = crossbeam_channel::unbounded();\n\n let mut throughput_monitor = self.throughput_monitor;\n\n\n\n let serve_handle = thread::spawn(move || {\n\n loop {\n\n socket.manual_poll(Instant::now());\n\n match socket.recv() {\n\n Some(result) => match result {\n\n SocketEvent::Packet(p) => {\n\n packet_assert(p);\n\n if throughput_monitor.tick() {\n\n if let Err(e) = events_tx.send(ServerEvent::Throughput(\n\n throughput_monitor.last_throughput(),\n", "file_path": "tests/common/server.rs", "rank": 94, "score": 34705.78383680372 }, { "content": " }\n\n }\n\n }\n\n }\n\n });\n\n\n\n ServerHandle::new(serve_handle, notify_tx, events_rx, self.listening_host)\n\n }\n\n}\n\n\n\n/// Handle to the running server.\n\npub struct ServerHandle {\n\n server_handle: JoinHandle<()>,\n\n notify_tx: Sender<ServerCommand>,\n\n events_rx: Receiver<ServerEvent>,\n\n pub listening_host: SocketAddr,\n\n}\n\n\n\nimpl ServerHandle {\n\n /// Construct a new `ServerHandle`\n", "file_path": "tests/common/server.rs", "rank": 95, "score": 34705.0556357726 }, { "content": "use crossbeam_channel::{Receiver, Sender, TryIter};\n\nuse laminar::{Config, Packet, Socket, SocketEvent, ThroughputMonitoring};\n\n\n\nuse log::error;\n\nuse std::net::SocketAddr;\n\nuse std::thread::{self, JoinHandle};\n\nuse std::time::{Duration, Instant};\n\n\n\n/// Enum with commands you can send to the server.\n\n#[derive(Debug)]\n\npub enum ServerCommand {\n\n Shutdown,\n\n}\n\n\n\n/// Enums which events you can receive from the server.\n\n#[derive(Debug)]\n\npub enum ServerEvent {\n\n Throughput(u32),\n\n AverageThroughput(u32),\n\n TotalSent(u32),\n", "file_path": "tests/common/server.rs", "rank": 96, "score": 34704.73312546227 }, { "content": " socket.send(packet);\n\n socket.manual_poll(Instant::now());\n\n\n\n let beginning_park = Instant::now();\n\n let mut timeout_remaining = timeout;\n\n loop {\n\n thread::park_timeout(timeout_remaining);\n\n let elapsed = beginning_park.elapsed();\n\n if elapsed >= timeout {\n\n break;\n\n }\n\n timeout_remaining = timeout - elapsed;\n\n }\n\n }\n\n info!(\"Client {:?} sent all messages.\", endpoint);\n\n });\n\n\n\n ClientHandle::new(handle)\n\n }\n\n}\n", "file_path": "tests/common/client.rs", "rank": 97, "score": 34702.718875464954 }, { "content": " pub fn wait_until_finished(self) {\n\n self.server_handle.join().unwrap();\n\n }\n\n\n\n /// Iterate over the events that have happened on the server.\n\n pub fn iter_events(&self) -> TryIter<ServerEvent> {\n\n self.events_rx.try_iter()\n\n }\n\n\n\n #[allow(unused)]\n\n pub fn event_receiver(&self) -> Receiver<ServerEvent> {\n\n self.events_rx.clone()\n\n }\n\n}\n", "file_path": "tests/common/server.rs", "rank": 98, "score": 34702.30540292556 }, { "content": " pub fn new(\n\n server_handle: JoinHandle<()>,\n\n notify_tx: Sender<ServerCommand>,\n\n events_rx: Receiver<ServerEvent>,\n\n listening_host: SocketAddr,\n\n ) -> ServerHandle {\n\n ServerHandle {\n\n server_handle,\n\n notify_tx,\n\n events_rx,\n\n listening_host,\n\n }\n\n }\n\n\n\n /// Send the shutdown signal to the server.\n\n pub fn shutdown(&self) {\n\n self.notify_tx.send(ServerCommand::Shutdown).unwrap();\n\n }\n\n\n\n /// Wait until this server is finished, if no shutdown signal is send or no error has been thrown then this will be a blocking call.\n", "file_path": "tests/common/server.rs", "rank": 99, "score": 34700.79100677603 } ]
Rust
lib/src/kvstore.rs
crashlabs-io/moiradb
a94642077d4deea192558b7112f291db82b8f8d6
use super::*; use rocksdb::{WriteBatch, DB}; use std::fmt::Debug; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; type DBValue<V> = Arc<Option<V>>; #[derive(Debug)] pub enum KVCommand<K, V> where K: Send, V: Send, { Read(K, oneshot::Sender<DBValue<V>>), Write(Vec<(K, DBValue<V>)>), } #[derive(Clone)] pub struct KVAdapter<K, V> where K: Send, V: Send, { pub sender: mpsc::UnboundedSender<KVCommand<K, V>>, } impl<K, V> KVAdapter<K, V> where K: Debug + Send, V: Debug + Send, { pub async fn read(&mut self, key: K) -> DBValue<V> { let (send, response) = oneshot::channel(); if let Err(e) = self.sender.send(KVCommand::Read(key, send)) { panic!(format!("SendError: {:?}", e)); } response.await.unwrap() } pub fn read_to_fut(&mut self, key: K, fut: oneshot::Sender<DBValue<V>>) { if let Err(e) = self.sender.send(KVCommand::Read(key, fut)) { panic!(format!("SendError: {:?}", e)); } } pub fn write(&mut self, write_set: Vec<(K, DBValue<V>)>) { if let Err(e) = self.sender.send(KVCommand::Write(write_set)) { panic!(format!("SendError: {:?}", e)); } } } /* pub struct KVBackend<K,V> { pub kvstore : DB, pub cache : HashMap<K,V>, pub receiver : mpsc::Receiver<KVCommand<K,V>>, } */ pub fn init<K, V>(db: DB) -> (KVAdapter<K, V>, JoinHandle<()>) where K: 'static + Send + Serialize + Debug, V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug, { let (tx, mut rx) = mpsc::unbounded_channel(); let handle = tokio::spawn(async move { while let Some(command) = rx.recv().await { match command { KVCommand::Read(key, response) => { let key_bytes = bincode::serialize(&key).unwrap(); let value = db.get_pinned(key_bytes).unwrap(); if let Some(value_bytes) = value { let parsed_value: V = bincode::deserialize(&value_bytes[..]).unwrap(); match response.send(Arc::new(Some(parsed_value))) { Err(e) => println!( "Error {:?} sending parsed response value for key: {:?}", e, key ), _ => (), }; } else { match response.send(Arc::new(None)) { Err(e) => { println!("Error {:?} sending empty response for key: {:?}", e, key) } _ => (), }; } } KVCommand::Write(mut write_set) => { let mut batch = WriteBatch::default(); while let Some((key, value)) = write_set.pop() { let key_bytes = bincode::serialize(&key).unwrap(); match &*value { None => batch.delete(key_bytes), Some(value) => { let value_bytes = bincode::serialize(&value).unwrap(); batch.put(key_bytes, value_bytes); } } } match db.write(batch) { Ok(_) => {} Err(e) => println!("Error writing to db: {:?}", e), }; } } } match db.flush() { Ok(_) => {} Err(e) => println!("Error flushing database: {:?}", e), }; }); let adapter: KVAdapter<K, V> = KVAdapter { sender: tx }; (adapter, handle) } #[cfg(test)] mod tests { use rocksdb::Options; use super::*; #[tokio::test(flavor = "multi_thread")] async fn kvstore_read_and_write() { let path = "/tmp/test_kvstore_read_and_write.rocksdb"; let _ = DB::destroy(&Options::default(), path); let store = DB::open_default(path).expect("database barfed on open"); let (mut kv_adapter, _) = init::<String, String>(store); let v = kv_adapter.read("A".to_string()).await; assert_eq!(None, *v); kv_adapter.write(vec![("A".to_string(), Arc::new(Some("VA".to_string())))]); let v = kv_adapter.read("A".to_string()).await; assert_eq!(Some("VA".to_string()), *v); kv_adapter.write(vec![("A".to_string(), Arc::new(None))]); let v = kv_adapter.read("A".to_string()).await; assert_eq!(None, *v); } }
use super::*; use rocksdb::{WriteBatch, DB}; use std::fmt::Debug; use tokio::sync::mpsc; use tokio::sync::oneshot; use tokio::task::JoinHandle; type DBValue<V> = Arc<Option<V>>; #[derive(Debug)] pub enum KVCommand<K, V> where K: Send, V: Send, { Read(K, oneshot::Sender<DBValue<V>>), Write(Vec<(K, DBValue<V>)>), } #[derive(Clone)] pub struct KVAdapter<K, V> where K: Send, V: Send, { pub sender: mpsc::UnboundedSender<KVCommand<K, V>>, } impl<K, V> KVAdapter<K, V> where K: Debug + Send, V: Debug + Send, { pub async fn read(&mut self, key: K) -> DBValue<V> { let (send, response) = oneshot::channel(); if let Err(e) = self.sender.send(KVCommand::Read(key, send)) { panic!(format!("SendError: {:?}", e)); } response.await.unwrap() } pub fn read_to_fut(&mut self, key: K, fut: oneshot::Sender<DBValue<V>>) { if let Err(e) = self.sender.send(KVCommand::Read(key, fut)) { panic!(format!("SendError: {:?}", e)); } } pub fn write(&mut self, write_set: Vec<(K, DBValue<V>)>) { if let Err(e) = self.sender.send(KVCommand::Write(write_set)) { panic!(format!("SendError: {:?}", e)); } } } /* pub struct KVBackend<K,V> { pub kvstore : DB, pub cache : HashMap<K,V>, pub receiver : mpsc::Receiver<KVCommand<K,V>>, } */ pub fn init<K, V>(db: DB) -> (KVAdapter<K, V>, JoinHandle<()>) where K: 'static + Send + Serialize + Debug, V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug, { let (tx, mut rx) = mpsc::unbounded_channel(); let handle = tokio::spawn(async move { while let Some(command) = rx.recv().await { match command { KVCommand::Read(key, response) => { let key_bytes = bincode::serialize(&key).unwrap(); let value = db.get_pinned(key_bytes).unwrap(); if let Some(value_bytes) = value { let parsed_value: V = bincode::deserialize(&value_bytes[..]).unwrap(); match response.send(Arc::new(Some(parsed_value))) { Err(e) => println!( "Error {:?} sending parsed response value for key: {:?}", e, key ), _ => (), }; } else { match response.send(Arc::new(None)) { Err(e) => { println!("Error {:?} sending empty response for key: {:?}", e, key) } _ => (), }; } } KVCommand::Write(mut write_set) => { let mut batch = WriteBatch::default(); while let Some((key, value)) = write_set.pop() { let key_bytes = bincode::serialize(&key).unwrap(); match &*value { None => batch.delete(key_bytes), Some(value) => { let value_bytes = bincode::serialize(&value).unwrap(); batch.put(key_bytes, value_bytes); } } } match db.write(batch) { Ok(_) => {} Err(e) => println!("Error writing to db: {:?}", e), }; } } } match db.flush() { Ok(_) => {} Err(e) => println!("Error flushing database: {:?}", e), }; }); let adapter: KVAdapter<K, V> = KVAdapter { sender: tx }; (adapter, handle) } #[cfg(test)] mod tests { use rocksdb::Options; use super::*; #[tokio::test(flavor = "multi_thread")] async fn kvstore_read_and_write() { let path = "/tmp/test_kvstore_read_and_write.rocksdb"; let _ = DB::destroy(&Options::default(), path); let store = DB::open_default(path).expect("database barfed on open"); let (mut kv_adapter, _) = init::<String, String>(store); let v = kv_adapter.read("A".to_string()).await; assert_eq!(None, *v);
}
kv_adapter.write(vec![("A".to_string(), Arc::new(Some("VA".to_string())))]); let v = kv_adapter.read("A".to_string()).await; assert_eq!(Some("VA".to_string()), *v); kv_adapter.write(vec![("A".to_string(), Arc::new(None))]); let v = kv_adapter.read("A".to_string()).await; assert_eq!(None, *v); }
function_block-function_prefix_line
[ { "content": "pub trait MergeCommand<K, V>: Command<K, V>\n\nwhere\n\n K: Debug,\n\n V: Debug,\n\n Self: Debug,\n\n{\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy)]\n\npub enum ExecState {\n\n Abort,\n\n Commit,\n\n Merge,\n\n NoWrite,\n\n Pending,\n\n Reschedule,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Entry<K, V, C> {\n", "file_path": "lib/src/types.rs", "rank": 1, "score": 144103.3174811268 }, { "content": "#[async_trait]\n\npub trait Command<K, V>\n\nwhere\n\n K: Debug,\n\n V: Debug,\n\n Self: Debug,\n\n{\n\n async fn execute(&self, db: &mut MoiraDb<K, V, Self>) -> TransactionResult;\n\n\n\n fn merge_operator(_key: &K, _prev_value: DBValue<V>, _updates: Vec<DBValue<V>>) -> DBValue<V> {\n\n unimplemented!();\n\n }\n\n}\n\n\n", "file_path": "lib/src/types.rs", "rank": 2, "score": 138585.1601489251 }, { "content": "pub fn execute(command: &PaymentCommand, db: &mut NotMoiraDb) -> TransactionResult {\n\n let sender_record: Option<Account> = db.read(&command.sender);\n\n let receiver_record: Option<Account> = db.read(&command.receiver);\n\n\n\n if sender_record.is_none() {\n\n return TransactionResult::Abort(\n\n format!(\"account does not exist: {:?}\", command.sender).to_string(),\n\n );\n\n };\n\n\n\n if receiver_record.is_none() {\n\n return TransactionResult::Abort(\n\n format!(\"account does not exist: {:?}\", command.receiver).to_string(),\n\n );\n\n };\n\n\n\n let mut sender_account: Account = sender_record.unwrap().clone();\n\n let mut receiver_account: Account = receiver_record.unwrap().clone();\n\n\n\n let amount = command.amount;\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 4, "score": 118290.86160811594 }, { "content": "fn setup_data_store(test_name: &str) -> KVAdapter<AccountKey, Account> {\n\n let path = format!(\"/tmp/bench_{}.rocksdb\", test_name);\n\n let _ = DB::destroy(&Options::default(), path.clone());\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let (kv_adapter, _) = init::<AccountKey, Account>(store);\n\n kv_adapter\n\n}\n\n\n\n#[tokio::main]\n\nasync fn multithreaded_payment_all_cpus_ten_accounts(c: &mut Criterion) {\n\n let num_accounts = 10;\n\n let cores = num_cpus::get(); // use all cores\n\n let test_name = \"multithreaded-all-cpus-10-accounts\";\n\n bench_it(c, test_name, num_accounts, cores).await;\n\n}\n\n\n\n#[tokio::main]\n\nasync fn multithreaded_payment_one_cpu_ten_accounts(c: &mut Criterion) {\n\n let num_accounts = 10;\n\n let cores = 1;\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 5, "score": 93574.89205058834 }, { "content": "/// This benchmarks the speed of completely sequential operations.\n\nfn bench_single_threaded_payment(c: &mut Criterion) {\n\n let path = \"/tmp/bench_insert_singlethread.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let mut db = NotMoiraDb { seq: 0, store };\n\n\n\n for account in 0u8..255 {\n\n let key: AccountKey = [account; 32];\n\n let value = Account {\n\n balance: 10000000000000000, // big enough that we can subtract lots of 10 without running out of money\n\n };\n\n db.write(key, Some(value));\n\n }\n\n\n\n let payment = PaymentCommand {\n\n sender: [0; 32],\n\n receiver: [1; 32],\n\n amount: 10,\n\n };\n\n\n\n c.bench_function(\"execute-single-threaded\", |b| {\n\n b.iter(|| execute(&payment, &mut db))\n\n });\n\n}\n\n\n\ncriterion_group!(benches, bench_single_threaded_payment);\n\ncriterion_main!(benches);\n", "file_path": "moiradb-command-examples/benches/singlethread.rs", "rank": 6, "score": 69154.38775345573 }, { "content": "// Make a block of transactions\n\nfn make_block(size: u128, account_keys: &Vec<AccountKey>) -> Block<AccountKey, PaymentCommand> {\n\n let mut rng = rand::thread_rng();\n\n let mut block: Block<AccountKey, PaymentCommand> = Vec::with_capacity(size as usize);\n\n for seq in 0u128..size {\n\n let payment = PaymentCommand {\n\n sender: account_keys.choose(&mut rng).unwrap().clone(),\n\n receiver: account_keys.choose(&mut rng).unwrap().clone(),\n\n amount: 1,\n\n };\n\n\n\n let t = Transaction {\n\n seq: seq as u64,\n\n write_set: vec![payment.sender.clone(), payment.receiver.clone()]\n\n .into_iter()\n\n .collect(),\n\n command: payment,\n\n };\n\n block.push(Arc::new(t));\n\n }\n\n block\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 7, "score": 62586.215424025504 }, { "content": "use async_trait::async_trait;\n\nuse std::collections::HashSet;\n\nuse std::fmt::Debug;\n\nuse std::sync::Arc;\n\n\n\nuse tokio::sync::oneshot;\n\n\n\nuse crate::moiradb::MoiraDb;\n\npub type DBValue<V> = Arc<Option<V>>;\n\n\n\npub type Block<K, C> = Vec<Arc<Transaction<K, C>>>;\n\n\n\n#[async_trait]\n", "file_path": "lib/src/types.rs", "rank": 8, "score": 25349.92993729285 }, { "content": " pub transaction: Arc<Transaction<K, C>>,\n\n pub state: ExecState,\n\n pub value: Option<DBValue<V>>,\n\n pub futures: Vec<oneshot::Sender<(Vec<DBValue<V>>, DBValue<V>)>>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum MoiraCommand<K, V, C>\n\nwhere\n\n C: ?Sized + Debug,\n\n K: Debug,\n\n V: Debug,\n\n{\n\n Read(K, u64, oneshot::Sender<(Vec<DBValue<V>>, DBValue<V>)>),\n\n Outcome(MoiraDb<K, V, C>),\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Transaction<K, C: ?Sized> {\n\n pub seq: u64,\n", "file_path": "lib/src/types.rs", "rank": 9, "score": 25349.836089398617 }, { "content": " pub write_set: HashSet<K>,\n\n pub command: C,\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum TransactionResult {\n\n Commit,\n\n Abort(String),\n\n Reschedule,\n\n}\n", "file_path": "lib/src/types.rs", "rank": 10, "score": 25339.345362569093 }, { "content": "use async_trait::async_trait;\n\nuse moiradb::{Command, MoiraDb, TransactionResult};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::sync::Arc;\n\n// use std::{thread, time::Duration};\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]\n\npub struct Account {\n\n pub balance: u64,\n\n}\n\n\n\npub type AccountKey = [u8; 32];\n\n\n\n#[derive(Debug)]\n\npub struct PaymentCommand {\n\n pub sender: AccountKey,\n\n pub receiver: AccountKey,\n\n pub amount: u64,\n\n}\n\n\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 18, "score": 20235.306780178234 }, { "content": "extern crate moiradb;\n\n\n\nuse moiradb::{execute_block, kvstore::init, Block, Transaction};\n\nuse moiradb_command_examples::replay_beacon::{BeaconCommand, BeaconKey, BeaconState};\n\n\n\nuse rand::Rng;\n\nuse rocksdb::{Options, DB};\n\nuse std::sync::Arc;\n\nuse tokio;\n\n\n\nuse std::time;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n println!(\"Running moiradb beacon example...\");\n\n\n\n // Create the database\n\n let path = \"/tmp/full_beacon_test.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n", "file_path": "moiradb-command-examples/examples/beacon.rs", "rank": 19, "score": 20235.070346467288 }, { "content": "extern crate moiradb;\n\n\n\nuse moiradb::{execute_block, kvstore::init, Block, Transaction};\n\nuse moiradb_command_examples::payment::{Account, AccountKey, PaymentCommand};\n\nuse rand::seq::SliceRandom;\n\nuse rand::Rng;\n\nuse rocksdb::{Options, DB};\n\nuse std::sync::Arc;\n\nuse tokio;\n\n\n\nuse std::time;\n\n\n\n#[tokio::main]\n\nasync fn main() {\n\n println!(\"Running moiradb payment example...\");\n\n\n\n // Create the database\n\n let path = \"/tmp/full_payment_test.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n", "file_path": "moiradb-command-examples/examples/payment.rs", "rank": 20, "score": 20234.71781589169 }, { "content": " .as_ref()\n\n .as_ref()\n\n .unwrap()\n\n .balance\n\n );\n\n }\n\n\n\n #[tokio::test(flavor = \"multi_thread\")]\n\n async fn full_payment_test() {\n\n // Create the database\n\n let path = \"/tmp/full_payment_test.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let (mut kv_adapter, _) = moiradb::kvstore::init::<AccountKey, Account>(store);\n\n\n\n // Random numbers\n\n let mut rng = rand::thread_rng();\n\n\n\n // Populate with initial accounts\n\n let mut account_keys: Vec<AccountKey> = Vec::with_capacity(2000);\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 21, "score": 20233.686557986613 }, { "content": " ) -> Transaction<AccountKey, PaymentCommand> {\n\n let payment = PaymentCommand {\n\n sender,\n\n receiver,\n\n amount,\n\n };\n\n\n\n Transaction {\n\n seq,\n\n write_set: vec![payment.sender.clone(), payment.receiver.clone()]\n\n .into_iter()\n\n .collect(),\n\n command: payment,\n\n }\n\n }\n\n\n\n #[tokio::test(flavor = \"multi_thread\")]\n\n async fn payment_test_correct() {\n\n let path = \"/tmp/payment_test_correct.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 22, "score": 20230.16682267117 }, { "content": "\n\n // thread::sleep(Duration::from_millis(1));\n\n return TransactionResult::Commit;\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use moiradb::{Block, Transaction};\n\n use rand::seq::SliceRandom;\n\n use rand::Rng;\n\n use rocksdb::{Options, DB};\n\n use std::time;\n\n\n\n fn make_tx(\n\n sender: AccountKey,\n\n receiver: AccountKey,\n\n amount: u64,\n\n seq: u64,\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 23, "score": 20229.72687740536 }, { "content": "#[async_trait]\n\nimpl Command<AccountKey, Account> for PaymentCommand {\n\n async fn execute(\n\n &self,\n\n db: &mut MoiraDb<AccountKey, Account, PaymentCommand>,\n\n ) -> TransactionResult {\n\n if self.sender == self.receiver {\n\n return TransactionResult::Abort(\"Same sender and receiver.\".to_string());\n\n }\n\n\n\n let sender_record: Arc<Option<Account>> = db.read(self.sender.clone()).await;\n\n let receiver_record: Arc<Option<Account>> = db.read(self.receiver.clone()).await;\n\n\n\n if sender_record.is_none() {\n\n return TransactionResult::Abort(\n\n format!(\"account does not exist: {:?}\", self.sender).to_string(),\n\n );\n\n };\n\n\n\n if receiver_record.is_none() {\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 24, "score": 20229.454702702966 }, { "content": " for _ in 0..100 {\n\n let key = rng.gen::<AccountKey>();\n\n\n\n let account = Account { balance: 1000 };\n\n\n\n kv_adapter.write(vec![(key, Arc::new(Some(account)))]);\n\n account_keys.push(key);\n\n }\n\n\n\n // Make a block of transactions\n\n let tx_number = 100u128; // <- CHANGE NO OF TX TO TEST SCALING\n\n let mut block: Block<AccountKey, PaymentCommand> = Vec::with_capacity(tx_number as usize);\n\n for seq in 0u128..tx_number {\n\n let payment = PaymentCommand {\n\n sender: account_keys.choose(&mut rng).unwrap().clone(),\n\n receiver: account_keys.choose(&mut rng).unwrap().clone(),\n\n amount: 1,\n\n };\n\n\n\n if payment.sender == payment.receiver {\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 25, "score": 20229.292705689997 }, { "content": " let (mut kv_adapter, handle) = init::<AccountKey, Account>(store);\n\n println!(\"* database created\");\n\n\n\n // Populate with initial accounts\n\n let mut rng = rand::thread_rng();\n\n const NUM_OF_ACCOUNTS: usize = 10000;\n\n let mut account_keys: Vec<AccountKey> = Vec::with_capacity(NUM_OF_ACCOUNTS);\n\n for _ in 0..NUM_OF_ACCOUNTS {\n\n let key = rng.gen::<AccountKey>();\n\n\n\n let account = Account { balance: 1000 };\n\n\n\n kv_adapter.write(vec![(key, Arc::new(Some(account)))]);\n\n account_keys.push(key);\n\n }\n\n println!(\"* saved 10,000 accounts with random identifiers\");\n\n\n\n // Make a block of transactions\n\n let tx_number = 50_000u128; // <- CHANGE NO OF TX TO TEST SCALING\n\n let mut block: Block<AccountKey, PaymentCommand> = Vec::with_capacity(tx_number as usize);\n", "file_path": "moiradb-command-examples/examples/payment.rs", "rank": 26, "score": 20228.941216123134 }, { "content": " let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let (mut kv_adapter, _) = moiradb::kvstore::init::<AccountKey, Account>(store);\n\n\n\n // Random numbers\n\n let mut rng = rand::thread_rng();\n\n\n\n let alice_key = rng.gen::<AccountKey>();\n\n let alice_account = Account { balance: 100 };\n\n\n\n let bob_key = rng.gen::<AccountKey>();\n\n let bob_account = Account { balance: 200 };\n\n\n\n let charlie_key = rng.gen::<AccountKey>();\n\n let charlie_account = Account { balance: 400 };\n\n\n\n kv_adapter.write(vec![\n\n (alice_key, Arc::new(Some(alice_account))),\n\n (bob_key, Arc::new(Some(bob_account))),\n\n (charlie_key, Arc::new(Some(charlie_account))),\n\n ]);\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 27, "score": 20228.25214024327 }, { "content": " for seq in 0u128..tx_number {\n\n let payment = PaymentCommand {\n\n sender: account_keys.choose(&mut rng).unwrap().clone(),\n\n receiver: account_keys.choose(&mut rng).unwrap().clone(),\n\n amount: 1,\n\n };\n\n\n\n let t = Transaction {\n\n seq: seq as u64,\n\n write_set: vec![payment.sender.clone(), payment.receiver.clone()]\n\n .into_iter()\n\n .collect(),\n\n command: payment,\n\n };\n\n\n\n block.push(Arc::new(t));\n\n }\n\n println!(\"* constructed a block with 50,000 transactions using saved accounts\");\n\n\n\n let now = time::Instant::now();\n", "file_path": "moiradb-command-examples/examples/payment.rs", "rank": 28, "score": 20228.03378017472 }, { "content": " let (kv_adapter, handle) = init::<BeaconKey, BeaconState>(store);\n\n println!(\"* database created\");\n\n\n\n // Populate with initial accounts\n\n let mut rng = rand::thread_rng();\n\n const NUM_OF_BEACONS: usize = 10000;\n\n\n\n let mut block: Block<BeaconKey, BeaconCommand> = Vec::with_capacity(NUM_OF_BEACONS);\n\n block.push(Arc::new(Transaction {\n\n seq: 0,\n\n write_set: vec![BeaconKey::CurrentEpoch, BeaconKey::Epoch { epoch: 0 }]\n\n .into_iter()\n\n .collect(),\n\n command: BeaconCommand::SetEpoch { epoch: 0 },\n\n }));\n\n\n\n for seq in 1usize..NUM_OF_BEACONS {\n\n let my_beacon = rng.gen::<[u8; 32]>();\n\n block.push(Arc::new(Transaction {\n\n seq: seq as u64,\n", "file_path": "moiradb-command-examples/examples/beacon.rs", "rank": 29, "score": 20223.622796961263 }, { "content": "extern crate moiradb;\n\n\n\nuse criterion::{criterion_group, criterion_main, Criterion};\n\nuse futures::executor::block_on;\n\nuse moiradb::{\n\n execute_block,\n\n kvstore::{init, KVAdapter},\n\n Block, Transaction,\n\n};\n\nuse moiradb_command_examples::payment::{Account, AccountKey, PaymentCommand};\n\nuse rand::{prelude::SliceRandom, Rng};\n\nuse rocksdb::{Options, DB};\n\nuse std::sync::Arc;\n\nuse std::time::Instant;\n\nuse tokio::task;\n\n\n\n// Make a block of transactions\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 30, "score": 20223.247941843078 }, { "content": " let cores = num_cpus::get(); // <- Change number of cores.\n\n println!(\n\n \"* running money transfers using PaymentCommand using {} cores\",\n\n cores\n\n );\n\n execute_block(block, kv_adapter, cores).await;\n\n handle.await.unwrap();\n\n let spent = now.elapsed();\n\n println!(\"* block execution finished in {:?}\", spent.clone());\n\n println!(\"\");\n\n println!(\"Time per transaction {}us\", spent.as_micros() / tx_number);\n\n}\n", "file_path": "moiradb-command-examples/examples/payment.rs", "rank": 31, "score": 20222.630295393614 }, { "content": "async fn bench_it(c: &mut Criterion, test_name: &str, num_accounts: usize, cores: usize) {\n\n let local = task::LocalSet::new();\n\n let mut kv_adapter = setup_data_store(test_name);\n\n let account_keys = make_accounts(num_accounts, &mut kv_adapter).await;\n\n c.bench_function(test_name, |b| {\n\n b.iter_custom(|iters| {\n\n let block_size = iters;\n\n let block = make_block(block_size as u128, &account_keys);\n\n let kv_adapter = kv_adapter.clone();\n\n let t = local.run_until(async move {\n\n let start = Instant::now();\n\n execute_block(block.clone(), kv_adapter.clone(), cores).await;\n\n start.elapsed()\n\n });\n\n\n\n block_on(t)\n\n });\n\n });\n\n}\n\n\n\ncriterion_group!(\n\n benches,\n\n multithreaded_payment_all_cpus_ten_accounts,\n\n multithreaded_payment_one_cpu_ten_accounts,\n\n multithreaded_payment_one_cpu_ten_thousand_accounts,\n\n multithreaded_payment_all_cpus_ten_thousand_accounts,\n\n);\n\ncriterion_main!(benches);\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 32, "score": 20222.508640828393 }, { "content": " return TransactionResult::Abort(\n\n format!(\"account does not exist: {:?}\", self.receiver).to_string(),\n\n );\n\n };\n\n\n\n let mut sender_account: Account = (*sender_record).clone().unwrap();\n\n let mut receiver_account: Account = (*receiver_record).clone().unwrap();\n\n\n\n let amount = self.amount;\n\n if !(sender_account.balance >= amount) {\n\n return TransactionResult::Abort(\"not enough money\".to_string());\n\n }\n\n\n\n sender_account.balance -= amount;\n\n receiver_account.balance += amount;\n\n\n\n db.write(self.sender.clone(), Arc::new(Some(sender_account)))\n\n .await;\n\n db.write(self.receiver.clone(), Arc::new(Some(receiver_account)))\n\n .await;\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 33, "score": 20222.369945957842 }, { "content": " continue;\n\n }\n\n\n\n let t = Transaction {\n\n seq: seq as u64,\n\n write_set: vec![payment.sender.clone(), payment.receiver.clone()]\n\n .into_iter()\n\n .collect(),\n\n command: payment,\n\n };\n\n\n\n block.push(Arc::new(t));\n\n }\n\n\n\n let now = time::Instant::now();\n\n let cores = 4; // <- Change number of cores.\n\n moiradb::execute_block(block, kv_adapter, cores).await;\n\n\n\n let spent = now.elapsed();\n\n println!(\"Time per transaction {}us\", spent.as_micros() / tx_number);\n\n }\n\n}\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 34, "score": 20221.838975736155 }, { "content": "}\n\n\n\nasync fn make_accounts(\n\n number_of_accounts: usize,\n\n kv_adapter: &mut KVAdapter<AccountKey, Account>,\n\n) -> Vec<AccountKey> {\n\n let mut rng = rand::thread_rng();\n\n let mut account_keys: Vec<AccountKey> = Vec::with_capacity(number_of_accounts);\n\n for _ in 0..number_of_accounts {\n\n let key = rng.gen::<AccountKey>();\n\n let account = Account { balance: 1000 };\n\n kv_adapter.write(vec![(key, Arc::new(Some(account)))]);\n\n account_keys.push(key);\n\n }\n\n account_keys\n\n}\n\n\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 35, "score": 20221.04543219108 }, { "content": " write_set: vec![\n\n BeaconKey::Epoch { epoch: 0 },\n\n BeaconKey::Beacon {\n\n key: my_beacon,\n\n epoch: 0,\n\n },\n\n ]\n\n .into_iter()\n\n .collect(),\n\n command: BeaconCommand::SetBeacon {\n\n key: my_beacon,\n\n epoch: 0,\n\n },\n\n }));\n\n }\n\n println!(\"* database populated with {} beacons\", NUM_OF_BEACONS);\n\n\n\n let now = time::Instant::now();\n\n let cores = num_cpus::get(); // <- Change number of cores.\n\n println!(\"* running beacons using BeaconCommand on {} cores\", cores);\n", "file_path": "moiradb-command-examples/examples/beacon.rs", "rank": 36, "score": 20220.776472116326 }, { "content": "\n\n let mut block: Block<AccountKey, PaymentCommand> = Vec::with_capacity(10);\n\n let t1 = make_tx(alice_key, bob_key, 10, 10);\n\n let t2 = make_tx(alice_key, bob_key, 10000, 20);\n\n let t3 = make_tx(bob_key, charlie_key, 210, 30);\n\n let t4 = make_tx(charlie_key, alice_key, 5, 40);\n\n\n\n block.push(Arc::new(t1));\n\n block.push(Arc::new(t2));\n\n block.push(Arc::new(t3));\n\n block.push(Arc::new(t4));\n\n\n\n let cores = 4; // <- Change number of cores.\n\n moiradb::execute_block(block, kv_adapter.clone(), cores).await;\n\n\n\n assert_eq!(\n\n 95u64,\n\n kv_adapter\n\n .read(alice_key)\n\n .await\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 37, "score": 20220.155885992277 }, { "content": "extern crate moiradb;\n\n\n\nuse criterion::{criterion_group, criterion_main, Criterion};\n\nuse moiradb_command_examples::{\n\n benchmark_singlethread::{execute, NotMoiraDb},\n\n payment::{Account, AccountKey, PaymentCommand},\n\n};\n\nuse rocksdb::{Options, DB};\n\n\n\n/// This benchmarks the speed of completely sequential operations.\n", "file_path": "moiradb-command-examples/benches/singlethread.rs", "rank": 38, "score": 20219.072479761824 }, { "content": " let test_name = \"multithreaded-one-cpu-10-accounts\";\n\n bench_it(c, test_name, num_accounts, cores).await;\n\n}\n\n\n\n#[tokio::main]\n\nasync fn multithreaded_payment_one_cpu_ten_thousand_accounts(c: &mut Criterion) {\n\n let num_accounts = 10000;\n\n let cores = 1;\n\n let test_name = \"multithreaded-one-cpu-10K-accounts\";\n\n bench_it(c, test_name, num_accounts, cores).await;\n\n}\n\n\n\n#[tokio::main]\n\nasync fn multithreaded_payment_all_cpus_ten_thousand_accounts(c: &mut Criterion) {\n\n let num_accounts = 10000;\n\n let cores = num_cpus::get();\n\n let test_name = \"multithreaded-all-cpus-10K-accounts\";\n\n bench_it(c, test_name, num_accounts, cores).await;\n\n}\n\n\n", "file_path": "moiradb-command-examples/benches/multithread.rs", "rank": 39, "score": 20218.824162310655 }, { "content": " execute_block(block, kv_adapter, cores).await;\n\n handle.await.unwrap();\n\n let spent = now.elapsed();\n\n println!(\"* block execution finished in {:?}\", spent.clone());\n\n println!(\"\");\n\n println!(\n\n \"Time per transaction {}us\",\n\n spent.as_micros() / (NUM_OF_BEACONS as u128)\n\n );\n\n}\n", "file_path": "moiradb-command-examples/examples/beacon.rs", "rank": 40, "score": 20216.73899207737 }, { "content": "pub mod benchmark_singlethread;\n\npub mod payment;\n\npub mod replay_beacon;\n", "file_path": "moiradb-command-examples/src/lib.rs", "rank": 41, "score": 20216.13769963452 }, { "content": " .as_ref()\n\n .as_ref()\n\n .unwrap()\n\n .balance\n\n );\n\n assert_eq!(\n\n 0u64,\n\n kv_adapter\n\n .read(bob_key)\n\n .await\n\n .as_ref()\n\n .as_ref()\n\n .unwrap()\n\n .balance\n\n );\n\n assert_eq!(\n\n 605u64,\n\n kv_adapter\n\n .read(charlie_key)\n\n .await\n", "file_path": "moiradb-command-examples/src/payment.rs", "rank": 42, "score": 20214.35276309701 }, { "content": "\n\nimpl NotMoiraDb {\n\n pub fn read<K, V>(&self, key: &K) -> Option<V>\n\n where\n\n K: Eq + Hash + Serialize,\n\n V: Serialize + DeserializeOwned,\n\n {\n\n let encoded = bincode::serialize(&key).unwrap();\n\n match self.store.get(&encoded) {\n\n Ok(Some(result)) => {\n\n let thing: V = bincode::deserialize(&result[..]).unwrap();\n\n return Some(thing);\n\n }\n\n Ok(None) => return None,\n\n Err(err) => panic!(\"failed on rocksdb retrieval: {}\", err),\n\n }\n\n }\n\n\n\n pub fn write<K, V>(&mut self, key: K, value: Option<V>)\n\n where\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 43, "score": 19255.285252850943 }, { "content": " let path = \"/tmp/test_delete.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let mut db = NotMoiraDb { seq: 0, store };\n\n\n\n let key = [0; 32];\n\n let value = Account {\n\n balance: 10000000000000000, // big enough that we can subtract lots of 10 without running out of money\n\n };\n\n db.write(key.clone(), Some(value.clone()));\n\n let none: Option<Account> = None;\n\n db.write(key.clone(), none);\n\n let result: Option<Account> = db.read(&key);\n\n assert_eq!(None, result);\n\n }\n\n}\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 44, "score": 19251.191284268152 }, { "content": "\n\n #[test]\n\n fn insert_and_retrieve() {\n\n let path = \"/tmp/test_insert.rocksdb\";\n\n let _ = DB::destroy(&Options::default(), path);\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let mut db = NotMoiraDb { seq: 0, store };\n\n\n\n let key = [0; 32];\n\n let value = Account {\n\n balance: 10000000000000000, // big enough that we can subtract lots of 10 without running out of money\n\n };\n\n db.write(key.clone(), Some(value.clone()));\n\n\n\n let result: Account = db.read(&key).unwrap();\n\n assert_eq!(value, result);\n\n }\n\n\n\n #[test]\n\n fn delete_on_no_value() {\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 45, "score": 19249.138186381762 }, { "content": "use async_trait::async_trait;\n\nuse moiradb::types::DBValue;\n\nuse moiradb::{Command, MergeCommand, MoiraDb, TransactionResult};\n\n\n\nuse serde::{Deserialize, Serialize};\n\nuse std::sync::Arc;\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum BeaconKey {\n\n Beacon { key: [u8; 32], epoch: u64 },\n\n Epoch { epoch: u64 },\n\n CurrentEpoch,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]\n\npub enum BeaconState {\n\n Beacon,\n\n EpochSet { keys: Vec<BeaconKey> },\n\n CurrentEpoch { epoch: u64 },\n\n BeaconUpdate(BeaconKey),\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 46, "score": 19247.463696742394 }, { "content": " if !(sender_account.balance >= amount) {\n\n return TransactionResult::Abort(\"not enough money\".to_string());\n\n }\n\n\n\n sender_account.balance -= amount;\n\n receiver_account.balance += amount;\n\n\n\n db.write(command.sender.clone(), Some(sender_account));\n\n db.write(command.receiver.clone(), Some(receiver_account));\n\n thread::sleep(Duration::from_millis(1));\n\n\n\n return TransactionResult::Commit;\n\n}\n\n\n\n/// These tests do basic verification of single-threaded operations. No benching.\n\n#[cfg(test)]\n\nmod tests {\n\n use rocksdb::Options;\n\n\n\n use super::*;\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 47, "score": 19247.05328826094 }, { "content": " K: Eq + Hash + Serialize,\n\n V: Serialize,\n\n {\n\n let encoded_key = bincode::serialize(&key).unwrap();\n\n\n\n match value {\n\n None => self.store.delete(&encoded_key).unwrap(),\n\n Some(v) => {\n\n let encoded_value = bincode::serialize(&v).unwrap();\n\n self.store.put(&encoded_key, encoded_value).unwrap();\n\n }\n\n };\n\n return;\n\n }\n\n}\n\n\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 48, "score": 19246.220300200886 }, { "content": "}\n\n\n\n#[derive(Debug)]\n\npub enum BeaconCommand {\n\n SetEpoch { epoch: u64 },\n\n SetBeacon { key: [u8; 32], epoch: u64 },\n\n}\n\n\n\nimpl MergeCommand<BeaconKey, BeaconState> for BeaconCommand {}\n\n\n\n#[async_trait]\n\nimpl Command<BeaconKey, BeaconState> for BeaconCommand {\n\n fn merge_operator(\n\n _key: &BeaconKey,\n\n prev_value: DBValue<BeaconState>,\n\n updates: Vec<DBValue<BeaconState>>,\n\n ) -> DBValue<BeaconState> {\n\n let mut keys = if let BeaconState::EpochSet { keys } = prev_value.as_ref().clone().unwrap()\n\n {\n\n keys\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 49, "score": 19242.61300070055 }, { "content": " let stored_beacon = db.read(beacon_key.clone()).await;\n\n if stored_beacon.is_some() {\n\n return TransactionResult::Abort(\"Beacon already used.\".to_string());\n\n }\n\n\n\n // Write the beacon\n\n db.write(beacon_key, Arc::new(Some(BeaconState::Beacon)))\n\n .await;\n\n\n\n // Write the index to the beacon\n\n // THIS IS THE INEFFICIENT BIT\n\n let use_merge = true;\n\n\n\n if !use_merge {\n\n let epoch_index_key = BeaconKey::Epoch { epoch: current };\n\n let mut index = (*db.read(epoch_index_key).await).clone().unwrap();\n\n\n\n if let BeaconState::EpochSet { keys: idx_keys } = &mut index {\n\n idx_keys.push(beacon_key);\n\n }\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 50, "score": 19239.659144623787 }, { "content": " } else {\n\n panic!(\"Wrong value type.\");\n\n };\n\n\n\n keys.reserve(updates.len());\n\n println!(\"Added {} keys\", updates.len());\n\n keys.extend(updates.iter().map(|item| {\n\n if let BeaconState::BeaconUpdate(k) = item.as_ref().as_ref().unwrap() {\n\n k\n\n } else {\n\n panic!(\"wrong type of update!\");\n\n }\n\n }));\n\n\n\n Arc::new(Some(BeaconState::EpochSet { keys }))\n\n }\n\n\n\n async fn execute(\n\n &self,\n\n db: &mut MoiraDb<BeaconKey, BeaconState, BeaconCommand>,\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 51, "score": 19239.093130405006 }, { "content": "use crate::payment::{Account, PaymentCommand};\n\nuse moiradb::TransactionResult;\n\nuse rocksdb::DB;\n\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse std::hash::Hash;\n\nuse std::{thread, time::Duration};\n\n\n\n/// A struct with similar methods to MoiraDb that we can use to measure similar\n\n/// operations in a completely single-threaded way.\n\n///\n\n/// This is strictly for benchmarking purposes so we can answer the question\n\n/// \"has this thing sped up?\"\n\n///\n\n/// You don't ever need to instantiate this, or attempt to emulate it in your\n\n/// own applications - in fact it's a demonstration of what we *don't* want to\n\n/// do.\n\npub struct NotMoiraDb {\n\n pub seq: u64,\n\n pub store: DB, // mock to make things type check\n\n}\n", "file_path": "moiradb-command-examples/src/benchmark_singlethread.rs", "rank": 52, "score": 19238.015876495578 }, { "content": " match *current_epoch {\n\n None => {\n\n if *my_epoch != 0 {\n\n return TransactionResult::Abort(\"New epoch must be zero\".to_string());\n\n }\n\n // Set the current epoch to zero\n\n db.write(\n\n BeaconKey::CurrentEpoch,\n\n Arc::new(Some(BeaconState::CurrentEpoch { epoch: 0 })),\n\n )\n\n .await;\n\n // Write an empty index for epoch zero\n\n db.write(\n\n BeaconKey::Epoch { epoch: 0 },\n\n Arc::new(Some(BeaconState::EpochSet { keys: Vec::new() })),\n\n )\n\n .await;\n\n\n\n return TransactionResult::Commit;\n\n }\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 53, "score": 19237.62760967222 }, { "content": " ) -> TransactionResult {\n\n match self {\n\n /* The logic to register a beacon as used */\n\n BeaconCommand::SetBeacon {\n\n key: cmd_key,\n\n epoch: cmd_epoch,\n\n } => {\n\n let current_epoch = db.read(BeaconKey::CurrentEpoch).await;\n\n match *current_epoch {\n\n Some(BeaconState::CurrentEpoch { epoch: current }) => {\n\n // Only valid within the epoch\n\n if *cmd_epoch != current {\n\n return TransactionResult::Abort(\"Wrong epoch.\".to_string());\n\n }\n\n\n\n // Check if the beacon already exists\n\n let beacon_key = BeaconKey::Beacon {\n\n key: *cmd_key,\n\n epoch: *cmd_epoch,\n\n };\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 54, "score": 19234.86652686949 }, { "content": " Some(BeaconState::CurrentEpoch { epoch: current }) => {\n\n if *my_epoch != current + 1 {\n\n return TransactionResult::Abort(\"New epoch must follow\".to_string());\n\n }\n\n // Set the current epoch to my_epoch\n\n db.write(\n\n BeaconKey::CurrentEpoch,\n\n Arc::new(Some(BeaconState::CurrentEpoch { epoch: *my_epoch })),\n\n )\n\n .await;\n\n\n\n // Write an empty index for epoch my_epoch\n\n db.write(\n\n BeaconKey::Epoch { epoch: *my_epoch },\n\n Arc::new(Some(BeaconState::EpochSet { keys: Vec::new() })),\n\n )\n\n .await;\n\n\n\n // Clean up keys from past epoch\n\n let v = db.read(BeaconKey::Epoch { epoch: current }).await;\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 55, "score": 19233.968241721912 }, { "content": "\n\n db.write(epoch_index_key, Arc::new(Some(index))).await;\n\n } else {\n\n let epoch_index_key = BeaconKey::Epoch { epoch: current };\n\n let update = BeaconState::BeaconUpdate(beacon_key);\n\n db.merge(epoch_index_key, Arc::new(Some(update))).await;\n\n }\n\n\n\n return TransactionResult::Commit;\n\n }\n\n _ => {\n\n return TransactionResult::Abort(\"Wrong structure.\".to_string());\n\n }\n\n }\n\n }\n\n\n\n /* The Logic that advances the epoch */\n\n BeaconCommand::SetEpoch { epoch: my_epoch } => {\n\n // Read the current epoch\n\n let current_epoch = db.read(BeaconKey::CurrentEpoch).await;\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 56, "score": 19233.06455396626 }, { "content": " if let Some(BeaconState::EpochSet { keys: prev_keys }) = Option::as_ref(&v)\n\n {\n\n for key in prev_keys {\n\n db.delete(*key).await;\n\n }\n\n } else {\n\n return TransactionResult::Abort(\"Wrong state type.\".to_string());\n\n }\n\n\n\n return TransactionResult::Commit;\n\n }\n\n Some(_) => {\n\n return TransactionResult::Abort(\"Wrong state type.\".to_string());\n\n }\n\n }\n\n }\n\n };\n\n }\n\n}\n", "file_path": "moiradb-command-examples/src/replay_beacon.rs", "rank": 57, "score": 19229.603168455218 }, { "content": "# Moiradb\n\n\n\nA deterministic database. \n\n\n\n## Dependencies\n\n\n\nOn Debian / Ubuntu the following packages are needed:\n\n\n\n```\n\nsudo apt install gnuplot build-essential pkg-config clang\n\n```\n\n\n\n`gnuplot` is only necessary for graph generation for benchmarks, it's optional. \n\n\n\n## Benchmarks\n\n\n\nYou can run benchmarks using `cargo bench`. We're using Criterion for this, so benchmarks work in Rust stable. \n\n\n\nBenchmarks generate HTML report pages, output is in `target/criterion/<reportname>/report`.\n\n\n\n## Running perf\n\n\n\nIn order to do perf stats collection, run \n\n\n\n```\n\ncargo build --release\n\nperf record --call-graph=dwarf ./target/release/moiradb\n\n```\n\n\n\nYou may need to run the following commands to enable stats collection by non-root users:\n\n\n\n```\n\nsudo sh -c 'echo 1 >/proc/sys/kernel/perf_event_paranoid'\n\nsudo sysctl -w kernel.perf_event_paranoid=1\n\n```\n\n\n\n## What's with the name? \n\n\n\nIn Greek mythology, *Moira* (or the *Moirai*) are the entities that control our fates - perfect for a deterministic database.\n", "file_path": "README.md", "rank": 58, "score": 16309.781233675569 }, { "content": "\n\nimpl<K, V, C> MoiraDb<K, V, C>\n\nwhere\n\n K: 'static + Send + Serialize + Eq + Hash + Clone + Debug,\n\n V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug,\n\n C: Debug + MergeCommand<K, V>,\n\n{\n\n pub async fn merge(&mut self, key: K, value: DBValue<V>) {\n\n // We cache writes here until we know the outcome of the execution.\n\n self.kv_store.insert(key, WriteType::Merge(value));\n\n }\n\n\n\n pub async fn collect(&mut self, key: K) -> DBValue<V> {\n\n // First read touches the database.\n\n let (tx, rx) = oneshot::channel();\n\n match self\n\n .read_commands\n\n .send(MoiraCommand::Read(key.clone(), self.seq, tx))\n\n {\n\n Err(_) => println!(\"Error sending command response\"),\n", "file_path": "lib/src/moiradb.rs", "rank": 59, "score": 50.626466328582744 }, { "content": " }\n\n\n\n // First read touches the database.\n\n let (tx, rx) = oneshot::channel();\n\n match self\n\n .read_commands\n\n .send(MoiraCommand::Read(key, self.seq, tx))\n\n {\n\n Err(_) => println!(\"Error sending command response\"),\n\n Ok(_) => (),\n\n };\n\n\n\n let (_vec, val) = rx.await.unwrap();\n\n return val;\n\n }\n\n\n\n /// Inserts the key and the value into the local key-value cache\n\n pub async fn write(&mut self, key: K, value: DBValue<V>) {\n\n // We cache writes here until we know the outcome of the execution.\n\n self.kv_store.insert(key, WriteType::Write(value));\n", "file_path": "lib/src/moiradb.rs", "rank": 60, "score": 42.73416242503205 }, { "content": "/* List of generic types we will use (exhaustive):\n\n\n\n - K - Key of the DB (copy, clone, serialize, deserialize)\n\n - V - Value of the DB (clone, serialize, deserialize)\n\n - C - Command to the transaction system (serialize, deserialize)\n\n\n\n*/\n\n\n\n/// Loop through all transactions in a block and execute each of them asynchronously.\n\npub async fn execute_block<K, V, C>(\n\n transactions: Block<K, C>,\n\n kv_adapter: KVAdapter<K, V>,\n\n cores: usize,\n\n) where\n\n K: 'static + Send + Sync + Serialize + Eq + Hash + Clone + Debug,\n\n V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug,\n\n C: 'static + Send + Sync + Debug + Command<K, V>,\n\n{\n\n const CONCURRENT_FUTURES: usize = 200;\n\n\n", "file_path": "lib/src/lib.rs", "rank": 61, "score": 34.9358336377558 }, { "content": "use std::{\n\n collections::{HashMap, HashSet},\n\n hash::Hash,\n\n sync::Arc,\n\n};\n\n\n\nuse crate::types::{Command, DBValue, MergeCommand, MoiraCommand, Transaction, TransactionResult};\n\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse std::fmt::Debug;\n\nuse tokio::sync::{mpsc::UnboundedSender, oneshot};\n\n\n\n#[derive(Debug, Clone)]\n\npub enum WriteType<V> {\n\n Write(DBValue<V>),\n\n Merge(DBValue<V>),\n\n}\n\n\n\n#[derive(Debug)]\n\n/// There is 1 MoiraDb per transaction.\n\npub struct MoiraDb<K, V, C: ?Sized>\n", "file_path": "lib/src/moiradb.rs", "rank": 62, "score": 31.124800076689628 }, { "content": " V: 'static + Send + Sync + Serialize + DeserializeOwned,\n\n{\n\n kv_adapter: KVAdapter<K, V>,\n\n pub multi_db: HashMap<K, Vec<Entry<K, V, C>>>,\n\n\n\n // Maintain some stats\n\n pub read_hit: u64,\n\n pub read_miss: u64,\n\n pub futures_stored: u64,\n\n pub read_len: u64,\n\n pub read_num: u64,\n\n}\n\n\n\nimpl<K, V, C> MultiVersionedStore<K, V, C>\n\nwhere\n\n K: 'static + Send + Serialize + Eq + Hash + Clone + Debug,\n\n V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug,\n\n C: Debug + Command<K, V>,\n\n{\n\n pub fn new(kv_adapter: KVAdapter<K, V>) -> MultiVersionedStore<K, V, C> {\n", "file_path": "lib/src/multistore.rs", "rank": 63, "score": 30.91755792414114 }, { "content": " self.read_miss += 1;\n\n }\n\n\n\n pub async fn read(\n\n &mut self,\n\n key: &K,\n\n seq: u64,\n\n call_back: oneshot::Sender<(Vec<DBValue<V>>, DBValue<V>)>,\n\n ) {\n\n match self.multi_db.get_mut(key) {\n\n None => {\n\n // No entry -- read from database\n\n let v = self.kv_adapter.read(key.clone()).await;\n\n let _ = call_back.send((Vec::new(), v));\n\n\n\n // self.kv_adapter.read_to_fut(key.clone(), call_back);\n\n self.read_miss += 1;\n\n }\n\n Some(entry_list) => {\n\n self.read_num += 1;\n", "file_path": "lib/src/multistore.rs", "rank": 64, "score": 29.960950136835066 }, { "content": " read_commands,\n\n kv_store: HashMap::with_capacity(transaction.write_set.len()),\n\n outcome: TransactionResult::Reschedule,\n\n transaction,\n\n }\n\n }\n\n\n\n /// Read data from the local cache or, in a case where the data is not cached\n\n /// locally, from the MultiVersionedStore.\n\n pub async fn read(&mut self, key: K) -> DBValue<V> {\n\n // Ensure we return written values on write-read.\n\n if let Some(type_of_val) = self.kv_store.get(&key) {\n\n match type_of_val {\n\n WriteType::Write(value) => {\n\n return value.clone();\n\n }\n\n WriteType::Merge(_) => {\n\n panic!(\"Cannot read merged values.\");\n\n }\n\n }\n", "file_path": "lib/src/moiradb.rs", "rank": 65, "score": 29.741858764463057 }, { "content": " pub outcome: TransactionResult,\n\n\n\n /// A reference to the transaction to execute\n\n pub transaction: Arc<Transaction<K, C>>,\n\n}\n\n\n\nimpl<K, V, C> MoiraDb<K, V, C>\n\nwhere\n\n K: 'static + Send + Serialize + Eq + Hash + Clone + Debug,\n\n V: 'static + Send + Sync + Serialize + DeserializeOwned + Debug,\n\n C: Command<K, V> + Debug,\n\n{\n\n /// Construct a new instance of MoiraDb.\n\n pub fn new(\n\n transaction: Arc<Transaction<K, C>>,\n\n read_commands: UnboundedSender<MoiraCommand<K, V, C>>,\n\n ) -> MoiraDb<K, V, C> {\n\n MoiraDb {\n\n seq: transaction.seq,\n\n write_set: transaction.write_set.iter().cloned().collect(),\n", "file_path": "lib/src/moiradb.rs", "rank": 66, "score": 29.186831435873795 }, { "content": " }\n\n\n\n /// Inserts a None value for a given key, effectively deleting any stored data.\n\n pub async fn delete(&mut self, key: K) {\n\n // We cache writes here until we know the outcome of the execution.\n\n // TODO: do not re-allocate for each None, use a single one and clone the Arc.\n\n self.kv_store.insert(key, WriteType::Write(Arc::new(None)));\n\n }\n\n\n\n /// Sends back results to MoiraDb to commit, or abort or reschedule db writes\n\n /// to the backing store. Consumes this instance of MoiraDb.\n\n ///\n\n /// When a command executes, it returns Abort, Commit, or Reschedule.\n\n ///\n\n /// Abort stops execution.\n\n ///\n\n /// Commit, and this transaction has only written to the originally\n\n /// expected values in the write set, we can commit.\n\n ///\n\n /// But if it has written to more keys than what was originally expected, we\n", "file_path": "lib/src/moiradb.rs", "rank": 67, "score": 29.166595977396234 }, { "content": " }\n\n\n\n pub async fn commit_all_changes(&mut self) {\n\n let mut write_set: Vec<(K, DBValue<V>)> = Vec::with_capacity(self.multi_db.len());\n\n let mut all_keys: Vec<K> = self.multi_db.iter().map(|(k, _)| k).cloned().collect();\n\n\n\n while let Some(key) = all_keys.pop() {\n\n let (tx, rx) = oneshot::channel();\n\n self.read(&key, u64::MAX, tx).await;\n\n let (_vec, value): (Vec<DBValue<V>>, DBValue<V>) = rx.await.unwrap();\n\n let value = if _vec.len() > 0 {\n\n C::merge_operator(&key, value, _vec)\n\n } else {\n\n value\n\n };\n\n write_set.push((key.clone(), value.clone()));\n\n }\n\n self.kv_adapter.write(write_set);\n\n }\n\n}\n", "file_path": "lib/src/multistore.rs", "rank": 68, "score": 28.88388325056642 }, { "content": "where\n\n C: Debug,\n\n K: Debug,\n\n V: Debug,\n\n{\n\n // Keep private, external code will have access to this object,\n\n // so we should help devs keep things correct by only exposing\n\n // the safe interface.\n\n pub seq: u64,\n\n\n\n /// A channel to the multi version store allowing reads and final write\n\n read_commands: UnboundedSender<MoiraCommand<K, V, C>>,\n\n\n\n /// A local cache of key/values, read/write\n\n pub kv_store: HashMap<K, WriteType<V>>,\n\n\n\n /// The keys we expect the transaction to write to\n\n pub write_set: HashSet<K>,\n\n\n\n /// The outcome of executing the command\n", "file_path": "lib/src/moiradb.rs", "rank": 69, "score": 28.4636771213906 }, { "content": "pub use crate::moiradb::{MoiraDb, WriteType};\n\npub use crate::types::{\n\n Block, Command, ExecState, MergeCommand, MoiraCommand, Transaction, TransactionResult,\n\n};\n\nuse futures::stream::futures_unordered::FuturesUnordered;\n\nuse futures::StreamExt;\n\nuse kvstore::KVAdapter;\n\nuse multistore::MultiVersionedStore;\n\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse std::collections::VecDeque;\n\nuse std::fmt::Debug;\n\nuse std::hash::Hash;\n\nuse std::sync::Arc;\n\nuse tokio::sync::mpsc;\n\n\n\npub mod kvstore;\n\npub mod moiradb;\n\npub mod multistore;\n\npub mod types;\n\n\n", "file_path": "lib/src/lib.rs", "rank": 70, "score": 27.514168321540836 }, { "content": " assert_eq!(Some(\"EXPECTED_VALUE\".to_string()), *val);\n\n }\n\n }\n\n }\n\n\n\n mod writes {\n\n use super::*;\n\n\n\n mod on_read_and_write {\n\n use super::*;\n\n\n\n #[tokio::test]\n\n async fn it_return_the_written_value() {\n\n let kv_adapter = setup_database(\"returns_what_I_write\");\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let (send, read_response) = oneshot::channel();\n\n\n\n let block = make_block_one();\n\n mv_store.prepare(&block);\n", "file_path": "lib/src/multistore.rs", "rank": 71, "score": 26.308305372989363 }, { "content": " mod reads {\n\n use super::*;\n\n\n\n mod when_there_is_no_value_in_the_backing_store {\n\n use super::*;\n\n\n\n #[tokio::test]\n\n async fn returns_none() {\n\n let kv_adapter = setup_database(\"returns_none\");\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let (send, read_response) = oneshot::channel();\n\n\n\n let block = make_block_one();\n\n mv_store.prepare(&block);\n\n mv_store.read(&\"FOO\".to_string(), 0, send).await;\n\n let (_vec, val) = read_response.await.unwrap();\n\n assert_eq!(None, *val);\n\n }\n\n }\n", "file_path": "lib/src/multistore.rs", "rank": 72, "score": 25.57149879568594 }, { "content": "\n\n mod when_there_is_a_value_in_the_backing_store {\n\n use super::*;\n\n\n\n #[tokio::test]\n\n async fn it_returns_the_value() {\n\n let mut kv_adapter = setup_database(\"value_in_backing_store\");\n\n kv_adapter.write(vec![(\n\n \"EXPECTED_KEY\".to_string(),\n\n Arc::new(Some(\"EXPECTED_VALUE\".to_string())),\n\n )]);\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n\n\n let (send, read_response) = oneshot::channel();\n\n\n\n let block = make_block_one();\n\n mv_store.prepare(&block);\n\n mv_store.read(&\"EXPECTED_KEY\".to_string(), 0, send).await;\n\n let (_vec, val) = read_response.await.unwrap();\n", "file_path": "lib/src/multistore.rs", "rank": 73, "score": 25.315831008388795 }, { "content": " // Sequence number of read\n\n seq: u64,\n\n // The response channel for this read.\n\n response: oneshot::Sender<(Vec<DBValue<V>>, DBValue<V>)>,\n\n // Merged collected values on the way.\n\n merged_values: Vec<DBValue<V>>,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Entry<K, V, C> {\n\n pub seq: u64, // we copy this here, since comparing seems to be hot (from profiling).\n\n pub transaction: Arc<Transaction<K, C>>,\n\n pub state: ExecState,\n\n pub value: Option<DBValue<V>>,\n\n pub futures: Vec<Read<V>>,\n\n}\n\n\n\npub struct MultiVersionedStore<K, V, C>\n\nwhere\n\n K: 'static + Send + Serialize + Eq + Hash + Clone,\n", "file_path": "lib/src/multistore.rs", "rank": 74, "score": 25.001588973562768 }, { "content": " use super::*;\n\n\n\n mod on_abort {\n\n use super::*;\n\n\n\n #[tokio::test]\n\n async fn reads_give_me_old_value() {\n\n let kv_adapter = setup_database(\"reads_give_me_old_value\");\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let (send, read_response) = oneshot::channel();\n\n\n\n let block = make_block_many();\n\n mv_store.prepare(&block);\n\n\n\n mv_store\n\n .write(\n\n &\"A\".to_string(),\n\n Some(Arc::new(Some(\"MY_VALUE\".to_string()))),\n\n 1,\n", "file_path": "lib/src/multistore.rs", "rank": 75, "score": 24.63245680424545 }, { "content": "\n\n#[cfg(test)]\n\nmod test_prepare {\n\n use rocksdb::{Options, DB};\n\n\n\n use crate::kvstore::init;\n\n use crate::moiradb::MoiraDb;\n\n use crate::types::TransactionResult;\n\n use async_trait::async_trait;\n\n\n\n use super::*;\n\n\n\n #[async_trait]\n\n impl Command<String, String> for String {\n\n async fn execute(&self, _db: &mut MoiraDb<String, String, Self>) -> TransactionResult {\n\n TransactionResult::Commit\n\n }\n\n }\n\n\n\n #[tokio::test]\n", "file_path": "lib/src/multistore.rs", "rank": 76, "score": 23.901190889640745 }, { "content": "use std::{\n\n cmp::Ordering,\n\n collections::{HashMap, VecDeque},\n\n fmt::Debug,\n\n hash::Hash,\n\n sync::Arc,\n\n};\n\n\n\nuse serde::{de::DeserializeOwned, Serialize};\n\nuse tokio::sync::oneshot;\n\n\n\nuse crate::{\n\n kvstore::KVAdapter,\n\n types::{Block, Command, DBValue, ExecState, Transaction},\n\n};\n\n\n\n#[derive(Debug)]\n\npub struct Read<V> {\n\n // The index of the start entry for this read.\n\n start_entry: usize,\n", "file_path": "lib/src/multistore.rs", "rank": 77, "score": 23.771328446662658 }, { "content": " pub async fn write(\n\n &mut self,\n\n key: &K,\n\n optional_value: Option<DBValue<V>>,\n\n seq: u64,\n\n commit_type: ExecState,\n\n ) {\n\n // let entry = self.bisect_entry_simple(key, seq);\n\n\n\n let entry_list = self.multi_db.get_mut(key).unwrap();\n\n // The format! is always executed, and this is in the critical path. Simplify\n\n // to unwrap above.\n\n // .expect(format!(\"Attempt to write to key {:?} not expected\", key).as_str());\n\n let pos = entry_list\n\n .binary_search_by(|entry| match entry.seq.cmp(&seq) {\n\n Ordering::Equal => Ordering::Equal,\n\n Ordering::Greater => Ordering::Less,\n\n Ordering::Less => Ordering::Greater,\n\n })\n\n .unwrap();\n", "file_path": "lib/src/multistore.rs", "rank": 78, "score": 22.888899130358574 }, { "content": " }\n\n }\n\n\n\n pub fn setup_database(test_name: &str) -> KVAdapter<String, String> {\n\n let path = format!(\"/tmp/test_{}.rocksdb\", test_name);\n\n let _ = DB::destroy(&Options::default(), path.clone());\n\n let store = DB::open_default(path).expect(\"database barfed on open\");\n\n let (kv_adapter, _) = init::<String, String>(store);\n\n kv_adapter\n\n }\n\n\n\n fn make_block_one() -> Block<String, String> {\n\n let t1 = Transaction {\n\n seq: 1,\n\n write_set: vec![\"A\".to_string(), \"B\".to_string()].into_iter().collect(),\n\n command: \"T1\".to_string(),\n\n };\n\n let block = vec![Arc::new(t1)];\n\n block\n\n }\n", "file_path": "lib/src/multistore.rs", "rank": 79, "score": 22.115298410613512 }, { "content": " self.update_future_at(key, read_fut, pos).await;\n\n }\n\n }\n\n\n\n async fn update_future_at(&mut self, key: &K, mut read_fut: Read<V>, current_pos: usize) {\n\n let entry_list = self.multi_db.get_mut(key).unwrap();\n\n\n\n for entry in entry_list.iter_mut().skip(current_pos) {\n\n self.read_len += 1;\n\n if entry.seq < read_fut.seq {\n\n self.read_hit += 1;\n\n // This is the value we are looking for!\n\n match entry.state {\n\n // A write for this sequence number did not happen,\n\n // so we continue looking for a previous value.\n\n ExecState::Abort | ExecState::Reschedule | ExecState::NoWrite => continue,\n\n ExecState::Commit => {\n\n let _ = read_fut\n\n .response\n\n .send((read_fut.merged_values, entry.value.clone().unwrap()));\n", "file_path": "lib/src/multistore.rs", "rank": 80, "score": 21.767585779851487 }, { "content": " let mut multi_versioned_store = MultiVersionedStore::<K, V, C>::new(kv_adapter);\n\n multi_versioned_store.prepare(&transactions);\n\n\n\n let (command_sender, mut command_receiver) = mpsc::unbounded_channel::<MoiraCommand<K, V, C>>();\n\n\n\n // Run all transactions in separate tasks\n\n let mut inner_blocks = Vec::<VecDeque<Arc<Transaction<K, C>>>>::with_capacity(cores);\n\n for _ in 0..cores {\n\n inner_blocks.push(VecDeque::with_capacity(1 + transactions.len() / cores));\n\n }\n\n\n\n for i in 0..transactions.len() {\n\n inner_blocks[i % cores].push_back(transactions[i].clone());\n\n }\n\n\n\n while let Some(mut inner_block) = inner_blocks.pop() {\n\n let inner_command_sender = command_sender.clone();\n\n\n\n // We're making on tokio task per inner block\n\n tokio::spawn(async move {\n", "file_path": "lib/src/lib.rs", "rank": 81, "score": 21.10066957186177 }, { "content": " multi_versioned_store.read(&key, seq, response).await;\n\n }\n\n MoiraCommand::Outcome(db) => {\n\n let final_outcome = db.outcome;\n\n\n\n match final_outcome {\n\n TransactionResult::Commit => {\n\n // println!(\"Commit {}\", db.seq);\n\n for key in &db.write_set {\n\n if db.kv_store.contains_key(&key) {\n\n match &db.kv_store[&key] {\n\n WriteType::Write(val) => {\n\n multi_versioned_store\n\n .write(\n\n &key,\n\n Some(val.clone()),\n\n db.seq,\n\n ExecState::Commit,\n\n )\n\n .await;\n", "file_path": "lib/src/lib.rs", "rank": 82, "score": 19.986918504604805 }, { "content": " Ok(_) => (),\n\n };\n\n\n\n let (mut _vec, val) = rx.await.unwrap();\n\n\n\n // Ensure we return written values on write-read.\n\n if let Some(type_of_val) = self.kv_store.get(&key) {\n\n match type_of_val {\n\n WriteType::Write(value) => {\n\n return value.clone();\n\n }\n\n WriteType::Merge(val) => {\n\n _vec.push(val.clone());\n\n }\n\n }\n\n }\n\n\n\n let new_val = C::merge_operator(&key, val, _vec);\n\n return new_val;\n\n }\n\n}\n", "file_path": "lib/src/moiradb.rs", "rank": 83, "score": 19.327474509260536 }, { "content": " ExecState::Commit,\n\n )\n\n .await;\n\n mv_store\n\n .write(&\"A\".to_string(), None, 4, ExecState::Abort)\n\n .await;\n\n mv_store.read(&\"A\".to_string(), 5, send).await;\n\n\n\n let (_vec, val) = read_response.await.unwrap();\n\n assert_eq!(Some(\"MY_VALUE\".to_string()), *val);\n\n }\n\n\n\n // This one tests the futures, basically\n\n #[tokio::test]\n\n async fn early_reads_give_me_old_value() {\n\n let kv_adapter = setup_database(\"early_reads_give_me_old_value\");\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let (send, read_response) = oneshot::channel();\n\n\n", "file_path": "lib/src/multistore.rs", "rank": 84, "score": 19.066443690221977 }, { "content": "\n\n let return_sender = self.read_commands.clone();\n\n\n\n // consume self by sending it back to the MultiVersionedStore\n\n return_sender\n\n .send(MoiraCommand::Outcome(self))\n\n .expect(\"channel to MultiVersionStore failed\");\n\n }\n\n\n\n /// Run the command, then consume this MoiraDb in set_outcome()\n\n pub async fn run_command(mut self) -> u64 {\n\n // Run the command with MoiraDb\n\n let transaction = self.transaction.clone();\n\n let result = transaction.command.execute(&mut self).await;\n\n // Send back the result to the Moira server task.\n\n let seq = self.seq;\n\n self.set_outcome(result).await;\n\n seq\n\n }\n\n}\n", "file_path": "lib/src/moiradb.rs", "rank": 85, "score": 18.976199435489548 }, { "content": " }\n\n WriteType::Merge(val) => {\n\n // println!(\"Merge to key {:?}\", key);\n\n multi_versioned_store\n\n .write(\n\n &key,\n\n Some(val.clone()),\n\n db.seq,\n\n ExecState::Merge,\n\n )\n\n .await;\n\n }\n\n };\n\n } else {\n\n multi_versioned_store\n\n .write(key, None, db.seq, ExecState::NoWrite)\n\n .await;\n\n }\n\n }\n\n }\n", "file_path": "lib/src/lib.rs", "rank": 86, "score": 18.461511393317252 }, { "content": "\n\n mv_store\n\n .write(\n\n &\"A\".to_string(),\n\n Some(Arc::new(Some(\"MY_VALUE\".to_string()))),\n\n 1,\n\n ExecState::Commit,\n\n )\n\n .await;\n\n mv_store.read(&\"A\".to_string(), 2, send).await;\n\n let (_vec, val) = read_response.await.unwrap();\n\n assert_eq!(Some(\"MY_VALUE\".to_string()), *val);\n\n }\n\n\n\n #[tokio::test]\n\n async fn it_return_what_was_written_even_on_later_read() {\n\n let kv_adapter = setup_database(\"returns_what_I_write_even_later\");\n\n let mut mv_store =\n\n MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let (send, read_response) = oneshot::channel();\n", "file_path": "lib/src/multistore.rs", "rank": 87, "score": 17.575953703099547 }, { "content": " async fn test_prepare_one() {\n\n let kv_adapter = setup_database(\"prepare_one\");\n\n let mut mv_store = MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let block = make_block_one();\n\n mv_store.prepare(&block);\n\n assert_eq!(true, mv_store.multi_db.contains_key(\"A\"));\n\n assert_eq!(true, mv_store.multi_db.contains_key(\"B\"));\n\n assert_eq!(false, mv_store.multi_db.contains_key(\"C\"));\n\n assert_eq!(1, mv_store.multi_db.get(\"A\").unwrap().len());\n\n }\n\n\n\n #[tokio::test]\n\n async fn test_prepare_many() {\n\n let kv_adapter = setup_database(\"prepare_many\");\n\n\n\n let mut mv_store = MultiVersionedStore::<String, String, String>::new(kv_adapter);\n\n let block = make_block_many();\n\n mv_store.prepare(&block);\n\n assert_eq!(false, mv_store.multi_db.contains_key(\"H\"));\n\n assert_eq!(2, mv_store.multi_db.get(\"A\").unwrap().len());\n", "file_path": "lib/src/multistore.rs", "rank": 88, "score": 16.815405462609462 }, { "content": " let fut = mdb.run_command(); // no wait here!\n\n transaction_bag.push(fut);\n\n }\n\n }\n\n\n\n // We signal to the server task that no more work is to be done.\n\n drop(inner_command_sender);\n\n });\n\n } // At this point, we're running all the transactions in their own tasks.\n\n // The next bit will then serve the reads for transactions and receive the results.\n\n\n\n // Drop so that when the tasks also drop it, the server exits.\n\n drop(command_sender);\n\n\n\n // Run the loop to serve reads and seal outcomes of transactions\n\n let mut reschedule = VecDeque::new();\n\n while let Some(cmd) = command_receiver.recv().await {\n\n match cmd {\n\n MoiraCommand::Read(key, seq, response) => {\n\n // Just do the read in the multi-versioned store\n", "file_path": "lib/src/lib.rs", "rank": 89, "score": 16.47419219752276 }, { "content": " TransactionResult::Abort(_) => {\n\n // println!(\"Abort {}\", db.seq);\n\n for key in &db.write_set {\n\n multi_versioned_store\n\n .write(key, None, db.seq, ExecState::Abort)\n\n .await;\n\n }\n\n }\n\n TransactionResult::Reschedule => {\n\n // println!(\"Reschedule {}\", db.seq);\n\n for key in &db.write_set {\n\n multi_versioned_store\n\n .write(key, None, db.seq, ExecState::Reschedule)\n\n .await;\n\n }\n\n reschedule.push_back(db.transaction.clone());\n\n }\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Persist all committed changes.\n\n multi_versioned_store.commit_all_changes().await;\n\n\n\n // TODO: deal with rescheduled transactions\n\n}\n", "file_path": "lib/src/lib.rs", "rank": 90, "score": 16.28772909229651 }, { "content": " let mut entry = entry_list.get_mut(pos).unwrap();\n\n let mut futures = Vec::with_capacity(entry.futures.len());\n\n\n\n if entry.seq == seq {\n\n // We found the entry to write!\n\n // 1. Update the state\n\n entry.state = commit_type;\n\n // 2. Update the value\n\n entry.value = optional_value;\n\n // 3. Notify waiting reads\n\n while let Some(read_fut) = entry.futures.pop() {\n\n self.futures_stored -= 1;\n\n futures.push(read_fut);\n\n }\n\n } else {\n\n // No entry -- panic\n\n panic!(format!(\"Could not find key {:?} at seq {:?}\", key, seq));\n\n }\n\n\n\n while let Some(read_fut) = futures.pop() {\n", "file_path": "lib/src/multistore.rs", "rank": 91, "score": 15.7726191703935 }, { "content": " return;\n\n }\n\n ExecState::Pending => {\n\n entry.futures.push(read_fut);\n\n self.futures_stored += 1;\n\n return;\n\n }\n\n ExecState::Merge => {\n\n read_fut.merged_values.push(entry.value.clone().unwrap());\n\n continue;\n\n }\n\n }\n\n }\n\n }\n\n\n\n // Hit the end of the list\n\n let v = self.kv_adapter.read(key.clone()).await;\n\n let _ = read_fut.response.send((read_fut.merged_values, v));\n\n\n\n // self.kv_adapter.read_to_fut(key.clone(), read_fut.response);\n", "file_path": "lib/src/multistore.rs", "rank": 92, "score": 15.444993036359156 }, { "content": " let mut temp: HashMap<K, VecDeque<Entry<K, V, C>>> = HashMap::new();\n\n for transaction in transaction_block {\n\n for key in &transaction.write_set {\n\n let new_entry: Entry<K, V, C> = Entry {\n\n seq: transaction.seq,\n\n transaction: transaction.clone(),\n\n state: ExecState::Pending,\n\n value: None,\n\n futures: Vec::new(),\n\n };\n\n let entry_list = temp.entry(key.clone()).or_insert(VecDeque::new());\n\n entry_list.push_front(new_entry);\n\n }\n\n }\n\n\n\n for (k, v) in temp {\n\n self.multi_db.insert(k, v.into_iter().collect());\n\n }\n\n }\n\n\n", "file_path": "lib/src/multistore.rs", "rank": 93, "score": 15.357035876959415 }, { "content": " MultiVersionedStore {\n\n kv_adapter,\n\n multi_db: HashMap::new(),\n\n\n\n read_hit: 0,\n\n read_miss: 0,\n\n futures_stored: 0,\n\n read_len: 0,\n\n read_num: 0,\n\n }\n\n }\n\n\n\n pub fn print_stats(&self) {\n\n println!(\n\n \"HIT: {} MISS: {} FUTURES: {} LEN: {} NUM: {}\",\n\n self.read_hit, self.read_miss, self.futures_stored, self.read_len, self.read_num\n\n );\n\n }\n\n\n\n pub fn prepare(&mut self, transaction_block: &Block<K, C>) {\n", "file_path": "lib/src/multistore.rs", "rank": 94, "score": 14.960604019157625 }, { "content": " assert_eq!(1, mv_store.multi_db.get(\"B\").unwrap().len());\n\n assert_eq!(2, mv_store.multi_db.get(\"C\").unwrap().len());\n\n assert_eq!(1, mv_store.multi_db.get(\"D\").unwrap().len());\n\n assert_eq!(1, mv_store.multi_db.get(\"X\").unwrap().len());\n\n assert_eq!(1, mv_store.multi_db.get(\"Y\").unwrap().len());\n\n }\n\n\n\n #[cfg(test)]\n\n mod the_multi_versioned_store {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_binary_search() {\n\n let v = vec![10, 7, 3, 1];\n\n // 5 -> 3 [idx=2]\n\n let x = v.binary_search_by(|i| match i.cmp(&5) {\n\n Ordering::Equal => Ordering::Greater,\n\n Ordering::Greater => Ordering::Less,\n\n Ordering::Less => Ordering::Greater,\n\n });\n", "file_path": "lib/src/multistore.rs", "rank": 95, "score": 14.784371125154806 }, { "content": " /// need to reschedule it for a later commit version. Later, we will re-run the\n\n /// deferred future(s) and include the proper set of keys, so that the future\n\n /// result will be consistent.\n\n pub async fn set_outcome(mut self, state: TransactionResult) {\n\n self.outcome = match state {\n\n TransactionResult::Abort(a) => TransactionResult::Abort(a),\n\n TransactionResult::Reschedule => TransactionResult::Reschedule,\n\n TransactionResult::Commit => {\n\n // Check we did not use any write we did not expect.\n\n let mut outcome = TransactionResult::Commit;\n\n for (k, _) in &self.kv_store {\n\n if !self.write_set.contains(k) {\n\n // An unexpected key was written to, reschedule.\n\n outcome = TransactionResult::Reschedule;\n\n break;\n\n }\n\n }\n\n outcome\n\n }\n\n };\n", "file_path": "lib/src/moiradb.rs", "rank": 96, "score": 14.481352703064115 }, { "content": " let block = make_block_many();\n\n mv_store.prepare(&block);\n\n\n\n mv_store.read(&\"A\".to_string(), 5, send).await;\n\n mv_store\n\n .write(\n\n &\"A\".to_string(),\n\n Some(Arc::new(Some(\"MY_VALUE\".to_string()))),\n\n 1,\n\n ExecState::Commit,\n\n )\n\n .await;\n\n mv_store\n\n .write(&\"A\".to_string(), None, 4, ExecState::Abort)\n\n .await;\n\n\n\n let (_vec, val) = read_response.await.unwrap();\n\n assert_eq!(Some(\"MY_VALUE\".to_string()), *val);\n\n }\n\n }\n", "file_path": "lib/src/multistore.rs", "rank": 97, "score": 12.269997929620127 }, { "content": "\n\n let block = make_block_one();\n\n mv_store.prepare(&block);\n\n\n\n mv_store.read(&\"A\".to_string(), 2, send).await;\n\n mv_store\n\n .write(\n\n &\"A\".to_string(),\n\n Some(Arc::new(Some(\"MY_VALUE\".to_string()))),\n\n 1,\n\n ExecState::Commit,\n\n )\n\n .await;\n\n let (_vec, val) = read_response.await.unwrap();\n\n assert_eq!(Some(\"MY_VALUE\".to_string()), *val);\n\n }\n\n }\n\n }\n\n\n\n mod aborts {\n", "file_path": "lib/src/multistore.rs", "rank": 98, "score": 12.014397118482625 }, { "content": " // We will make one future per transaction and put them in this bag\n\n let mut transaction_bag = FuturesUnordered::new();\n\n\n\n // Make and put all transactions as futures in a bag\n\n let mut idx = 0;\n\n while let Some(trans) = inner_block.pop_front() {\n\n let moiradb = MoiraDb::new(trans.clone(), inner_command_sender.clone());\n\n let fut = moiradb.run_command(); // no .await here! We set up the future but don't run it.\n\n transaction_bag.push(fut);\n\n idx += 1;\n\n if idx == CONCURRENT_FUTURES {\n\n break;\n\n }\n\n }\n\n\n\n // Now execute them one by one in any order.\n\n while let Some(_) = transaction_bag.next().await {\n\n // Add one more\n\n if let Some(trans) = inner_block.pop_front() {\n\n let mdb = MoiraDb::new(trans.clone(), inner_command_sender.clone());\n", "file_path": "lib/src/lib.rs", "rank": 99, "score": 11.26533717291283 } ]
Rust
common/functions/src/scalars/udfs/in_basic.rs
pymongo/databend
c349ea00478df90c6b9c6438bec9b3643b4072e4
use std::collections::HashSet; use std::fmt; use common_datavalues::columns::DataColumn; use common_datavalues::prelude::DataColumnsWithField; use common_datavalues::prelude::MutableArrayBuilder; use common_datavalues::prelude::MutableBooleanArrayBuilder; use common_datavalues::types::merge_types; use common_datavalues::DataType; use common_datavalues::DataTypeAndNullable; use common_datavalues::DataValue; use common_exception::ErrorCode; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function; #[derive(Clone)] pub struct InFunction<const NEGATED: bool>; impl<const NEGATED: bool> InFunction<NEGATED> { pub fn try_create(_display_name: &str) -> Result<Box<dyn Function>> { Ok(Box::new(InFunction::<NEGATED> {})) } pub fn desc() -> FunctionDescription { FunctionDescription::creator(Box::new(Self::try_create)).features( FunctionFeatures::default() .bool_function() .variadic_arguments(2, usize::MAX), ) } } macro_rules! basic_contains { ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, bool) => { let mut vals_set = HashSet::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.insert(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.bool()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(&val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, $PRIMITIVE_TYPE: ident) => { let mut vals_set = HashSet::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.insert(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.$PRIMITIVE_TYPE()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; } macro_rules! float_contains { ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, $PRIMITIVE_TYPE: ident) => { let mut vals_set = Vec::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.push(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.$PRIMITIVE_TYPE()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; } impl<const NEGATED: bool> Function for InFunction<NEGATED> { fn name(&self) -> &str { "InFunction" } fn return_type(&self, args: &[DataTypeAndNullable]) -> Result<DataTypeAndNullable> { let input_dt = args[0].data_type(); if input_dt == &DataType::Null { return Ok(DataTypeAndNullable::create(input_dt, false)); } let dt = DataType::Boolean; Ok(DataTypeAndNullable::create(&dt, false)) } fn eval(&self, columns: &DataColumnsWithField, _input_rows: usize) -> Result<DataColumn> { let input_column = columns[0].column(); let input_array = match input_column { DataColumn::Array(array) => array.to_owned(), DataColumn::Constant(scalar, _) => scalar.to_array()?, }; let input_dt = input_array.data_type(); if input_dt == &DataType::Null { let mut array = MutableBooleanArrayBuilder::<false>::with_capacity(input_array.len()); for _ in 0..input_array.len() { array.push_null(); } return Ok(DataColumn::Array(array.as_series())); } let mut builder = MutableBooleanArrayBuilder::<false>::with_capacity(input_column.len()); let check_arrays = &columns[1..]; let mut least_super_dt = input_dt.clone(); for array in check_arrays { least_super_dt = merge_types(&least_super_dt, array.data_type())?; } let input_array = input_array.cast_with_type(&least_super_dt)?; match least_super_dt { DataType::Boolean => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Boolean, bool ); } DataType::UInt8 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt8, u8 ); } DataType::UInt16 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt16, u16 ); } DataType::UInt32 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt32, u32 ); } DataType::UInt64 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt64, u64 ); } DataType::Int8 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int8, i8 ); } DataType::Int16 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int16, i16 ); } DataType::Int32 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int32, i32 ); } DataType::Int64 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int64, i64 ); } DataType::Float32 => { float_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Float32, f32 ); } DataType::Float64 => { float_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Float64, f64 ); } DataType::String => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, String, string ); } DataType::Struct(_) => {} _ => { unimplemented!() } } Ok(DataColumn::Array(builder.as_series())) } } impl<const NEGATED: bool> fmt::Display for InFunction<NEGATED> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if NEGATED { write!(f, "NOT IN") } else { write!(f, "IN") } } }
use std::collections::HashSet; use std::fmt; use common_datavalues::columns::DataColumn; use common_datavalues::prelude::DataColumnsWithField; use common_datavalues::prelude::MutableArrayBuilder; use common_datavalues::prelude::MutableBooleanArrayBuilder; use common_datavalues::types::merge_types; use common_datavalues::DataType; use common_datavalues::DataTypeAndNullable; use common_datavalues::DataValue; use common_exception::ErrorCode; use common_exception::Result; use crate::scalars::function_factory::FunctionDescription; use crate::scalars::function_factory::FunctionFeatures; use crate::scalars::Function; #[derive(Clone)] pub struct InFunction<const NEGATED: bool>; impl<const NEGATED: bool> InFunction<NEGATED> { pub fn try_create(_display_name: &str) -> Result<Box<dyn Function>> { Ok(Box::new(InFunction::<NEGATED> {})) } pub fn desc() -> FunctionDescription { FunctionDescription::creator(Box::new(Self::try_create)).features( FunctionFeatures::default() .bool_function() .variadic_arguments(2, usize::MAX), ) } } macro_rules! basic_contains { ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, bool) => { let mut vals_set = HashSet::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.insert(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.bool()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(&val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, $PRIMITIVE_TYPE: ident) => { let mut vals_set = HashSet::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.insert(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.$PRIMITIVE_TYPE()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; } macro_rules! float_contains { ($INPUT_DT: expr, $INPUT_ARRAY: expr, $CHECK_ARRAY: expr, $NEGATED: expr, $BUILDER: expr, $CAST_TYPE: ident, $PRIMITIVE_TYPE: ident) => { let mut vals_set = Vec::new(); for array in $CHECK_ARRAY { let array = array.column().cast_with_type($INPUT_DT)?; match array { DataColumn::Constant(DataValue::$CAST_TYPE(Some(val)), _) => { vals_set.push(val); } DataColumn::Constant(DataValue::$CAST_TYPE(None), _) => { continue; } _ => { return Err(ErrorCode::LogicalError("it's a bug")); } } } let arr = $INPUT_ARRAY.$PRIMITIVE_TYPE()?; for val in arr.into_no_null_iter() { let contains = vals_set.contains(val); $BUILDER.push((contains && !NEGATED) || (!contains && NEGATED)); } }; } impl<const NEGATED: bool> Function for InFunction<NEGATED> { fn name(&self) -> &str { "InFunction" } fn return_type(&self, args: &[DataTypeAndNullable]) -> Result<DataTypeAndNullable> { let input_dt = args[0].data_type(); if input_dt == &DataType::Null { return Ok(DataTypeAndNullable::create(input_dt, false)); } let dt = DataType::Boolean; Ok(DataTypeAndNullable::create(&dt, false)) }
} impl<const NEGATED: bool> fmt::Display for InFunction<NEGATED> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if NEGATED { write!(f, "NOT IN") } else { write!(f, "IN") } } }
fn eval(&self, columns: &DataColumnsWithField, _input_rows: usize) -> Result<DataColumn> { let input_column = columns[0].column(); let input_array = match input_column { DataColumn::Array(array) => array.to_owned(), DataColumn::Constant(scalar, _) => scalar.to_array()?, }; let input_dt = input_array.data_type(); if input_dt == &DataType::Null { let mut array = MutableBooleanArrayBuilder::<false>::with_capacity(input_array.len()); for _ in 0..input_array.len() { array.push_null(); } return Ok(DataColumn::Array(array.as_series())); } let mut builder = MutableBooleanArrayBuilder::<false>::with_capacity(input_column.len()); let check_arrays = &columns[1..]; let mut least_super_dt = input_dt.clone(); for array in check_arrays { least_super_dt = merge_types(&least_super_dt, array.data_type())?; } let input_array = input_array.cast_with_type(&least_super_dt)?; match least_super_dt { DataType::Boolean => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Boolean, bool ); } DataType::UInt8 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt8, u8 ); } DataType::UInt16 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt16, u16 ); } DataType::UInt32 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt32, u32 ); } DataType::UInt64 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, UInt64, u64 ); } DataType::Int8 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int8, i8 ); } DataType::Int16 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int16, i16 ); } DataType::Int32 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int32, i32 ); } DataType::Int64 => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Int64, i64 ); } DataType::Float32 => { float_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Float32, f32 ); } DataType::Float64 => { float_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, Float64, f64 ); } DataType::String => { basic_contains!( &least_super_dt, input_array, check_arrays, NEGATED, builder, String, string ); } DataType::Struct(_) => {} _ => { unimplemented!() } } Ok(DataColumn::Array(builder.as_series())) }
function_block-full_function
[ { "content": "pub fn string_literal(val: &str) -> Expression {\n\n Expression::create_literal(DataValue::String(Some(val.as_bytes().to_vec())))\n\n}\n\n\n", "file_path": "query/src/storages/fuse/table_functions/table_arg_util.rs", "rank": 0, "score": 452972.13957462483 }, { "content": "pub fn is_builtin_function(name: &str) -> bool {\n\n FunctionFactory::instance().check(name) || AggregateFunctionFactory::instance().check(name)\n\n}\n", "file_path": "common/functions/src/lib.rs", "rank": 1, "score": 443319.6646049219 }, { "content": "pub fn try_create_aggregate_arg_minmax_function<const IS_MIN: bool>(\n\n display_name: &str,\n\n _params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<Arc<dyn AggregateFunction>> {\n\n assert_binary_arguments(display_name, arguments.len())?;\n\n let data_type = arguments[1].data_type();\n\n\n\n with_match_primitive_type!(data_type, |$T| {\n\n type AggState = NumericState<$T>;\n\n if IS_MIN {\n\n AggregateArgMinMaxFunction::<AggState>::try_create_arg_min(\n\n display_name,\n\n arguments,\n\n )\n\n } else {\n\n AggregateArgMinMaxFunction::<AggState>::try_create_arg_max(\n\n display_name,\n\n arguments,\n\n )\n", "file_path": "common/functions/src/aggregates/aggregate_arg_min_max.rs", "rank": 2, "score": 380616.9514272418 }, { "content": "#[inline]\n\npub fn label_counter_with_val(name: &'static str, val: u64, tenant_id: &str, cluster_id: &str) {\n\n let labels = [\n\n (LABEL_KEY_TENANT, tenant_id.to_string()),\n\n (LABEL_KEY_CLUSTER, cluster_id.to_string()),\n\n ];\n\n counter!(name, val, &labels);\n\n}\n\n\n", "file_path": "common/metrics/src/recorder.rs", "rank": 3, "score": 365004.2861137875 }, { "content": "pub fn aggregate_arg_max_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(\n\n try_create_aggregate_arg_minmax_function::<false>,\n\n ))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_arg_min_max.rs", "rank": 4, "score": 359563.21704828786 }, { "content": "pub fn aggregate_arg_min_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(\n\n try_create_aggregate_arg_minmax_function::<true>,\n\n ))\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_arg_min_max.rs", "rank": 5, "score": 359563.21704828786 }, { "content": "pub fn sort(name: &str, asc: bool, nulls_first: bool) -> Expression {\n\n Expression::Sort {\n\n expr: Box::new(col(name)),\n\n asc,\n\n nulls_first,\n\n origin_expr: Box::new(col(name)),\n\n }\n\n}\n", "file_path": "common/planners/src/plan_expression_sort.rs", "rank": 6, "score": 354367.3217265337 }, { "content": "pub fn criterion_benchmark_suite(c: &mut Criterion, sql: &str) {\n\n c.bench_function(sql, |b| {\n\n b.iter(|| {\n\n tokio::runtime::Runtime::new()\n\n .unwrap()\n\n .block_on(select_executor(sql))\n\n })\n\n });\n\n}\n", "file_path": "query/benches/suites/mod.rs", "rank": 7, "score": 353410.8429454578 }, { "content": "pub fn string_value(expr: &Expression) -> Result<String> {\n\n if let Expression::Literal { value, .. } = expr {\n\n String::from_utf8(value.as_string()?)\n\n .map_err(|e| ErrorCode::BadArguments(format!(\"invalid string. {}\", e)))\n\n } else {\n\n Err(ErrorCode::BadArguments(format!(\n\n \"expecting string literal, but got {:?}\",\n\n expr\n\n )))\n\n }\n\n}\n\n\n", "file_path": "query/src/storages/fuse/table_functions/table_arg_util.rs", "rank": 8, "score": 352475.4454847942 }, { "content": "pub fn parse_array_type(source: &str) -> Option<&str> {\n\n if !source.starts_with(\"Array\") {\n\n return None;\n\n }\n\n\n\n let inner_type = &source[6..source.len() - 1];\n\n Some(inner_type)\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 9, "score": 337303.3336188044 }, { "content": "fn function_arg_as_expr(arg_expr: &FunctionArgExpr) -> Result<Expr> {\n\n match arg_expr {\n\n FunctionArgExpr::Expr(expr) => Ok(expr.clone()),\n\n FunctionArgExpr::Wildcard | FunctionArgExpr::QualifiedWildcard(_) => Err(\n\n ErrorCode::SyntaxException(std::format!(\"Unsupported arg statement: {}\", arg_expr)),\n\n ),\n\n }\n\n}\n", "file_path": "common/ast/src/udfs/udf_transformer.rs", "rank": 10, "score": 335510.67338599544 }, { "content": "#[allow(clippy::result_unit_err)]\n\npub fn parse_compression(source: &str) -> std::result::Result<bool, ()> {\n\n match source {\n\n \"none\" => Ok(false),\n\n \"lz4\" => Ok(true),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 11, "score": 335275.7421355877 }, { "content": "// Check if all plans in an expression are physical plans\n\npub fn check_physical(expression: &SExpr) -> bool {\n\n if !expression.plan().is_physical() {\n\n return false;\n\n }\n\n\n\n for child in expression.children() {\n\n if !child.plan().is_physical() {\n\n return false;\n\n }\n\n }\n\n\n\n true\n\n}\n", "file_path": "query/src/sql/exec/util.rs", "rank": 12, "score": 327014.0246363181 }, { "content": "pub fn try_create_aggregate_minmax_function<const IS_MIN: bool>(\n\n display_name: &str,\n\n _params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<Arc<dyn AggregateFunction>> {\n\n assert_unary_arguments(display_name, arguments.len())?;\n\n let data_type = arguments[0].data_type();\n\n\n\n with_match_primitive_type!(data_type, |$T| {\n\n type AggState = NumericState<$T>;\n\n if IS_MIN {\n\n AggregateMinMaxFunction::<AggState>::try_create_min(\n\n display_name,\n\n arguments,\n\n )\n\n } else {\n\n AggregateMinMaxFunction::<AggState>::try_create_max(\n\n display_name,\n\n arguments,\n\n )\n", "file_path": "common/functions/src/aggregates/aggregate_min_max.rs", "rank": 13, "score": 325569.87331522035 }, { "content": "/// Transform the like pattern to regex pattern.\n\n/// e.g. 'Hello\\._World%\\%' tranform to '^Hello\\\\\\..World.*%$'.\n\npub fn like_pattern_to_regex(pattern: &str) -> String {\n\n let mut regex = String::with_capacity(pattern.len() * 2);\n\n regex.push('^');\n\n\n\n let mut chars = pattern.chars().peekable();\n\n while let Some(c) = chars.next() {\n\n match c {\n\n // Use double backslash to escape special character.\n\n '^' | '$' | '(' | ')' | '*' | '+' | '.' | '[' | '?' | '{' | '|' => {\n\n regex.push('\\\\');\n\n regex.push(c);\n\n }\n\n '%' => regex.push_str(\".*\"),\n\n '_' => regex.push('.'),\n\n '\\\\' => match chars.peek().cloned() {\n\n Some('%') => {\n\n regex.push('%');\n\n chars.next();\n\n }\n\n Some('_') => {\n", "file_path": "common/datavalues/src/arrays/ops/like.rs", "rank": 14, "score": 322677.04601992585 }, { "content": "pub fn get_list_builder(\n\n dt: &DataType,\n\n value_capacity: usize,\n\n list_capacity: usize,\n\n) -> Box<dyn ListBuilderTrait> {\n\n macro_rules! get_primitive_builder {\n\n ($type:ty) => {{\n\n let builder =\n\n ListPrimitiveArrayBuilder::<$type>::with_capacity(value_capacity, list_capacity);\n\n Box::new(builder)\n\n }};\n\n }\n\n macro_rules! get_bool_builder {\n\n () => {{\n\n let builder = ListBooleanArrayBuilder::with_capacity(value_capacity, list_capacity);\n\n Box::new(builder)\n\n }};\n\n }\n\n macro_rules! get_string_builder {\n\n () => {{\n", "file_path": "common/datavalues/src/arrays/list/builder.rs", "rank": 15, "score": 322519.2158493126 }, { "content": "pub fn aggregate_sum_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_sum_function))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_sum.rs", "rank": 16, "score": 307183.4030442325 }, { "content": "pub fn aggregate_avg_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_avg_function))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_avg.rs", "rank": 17, "score": 307183.4030442325 }, { "content": "fn get_maybe_monotonic(op: &str, args: Expressions) -> Result<bool> {\n\n let factory = FunctionFactory::instance();\n\n let function_features = factory.get_features(op)?;\n\n if !function_features.maybe_monotonic {\n\n return Ok(false);\n\n }\n\n\n\n for arg in args {\n\n if !check_maybe_monotonic(&arg)? {\n\n return Ok(false);\n\n }\n\n }\n\n Ok(true)\n\n}\n\n\n", "file_path": "query/src/storages/index/range_filter.rs", "rank": 18, "score": 305204.6980773995 }, { "content": "fn parse_sql_to_expr(query_expr: &str) -> Expr {\n\n let dialect = GenericDialect {};\n\n let mut tokenizer = Tokenizer::new(&dialect, query_expr);\n\n let tokens = tokenizer.tokenize().unwrap();\n\n let mut parser = Parser::new(tokens, &dialect);\n\n parser.parse_expr().unwrap()\n\n}\n\n\n", "file_path": "query/tests/it/sql/sql_parser.rs", "rank": 19, "score": 304887.4361075785 }, { "content": "pub fn aggregate_min_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_minmax_function::<true>))\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_min_max.rs", "rank": 20, "score": 303753.8650463228 }, { "content": "pub fn aggregate_max_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_minmax_function::<false>))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_min_max.rs", "rank": 21, "score": 303753.8650463228 }, { "content": "/// Check the like pattern type.\n\n///\n\n/// is_pruning: indicate whether to be called on range_filter for pruning.\n\n///\n\n/// For example:\n\n///\n\n/// 'a\\\\%row'\n\n/// '\\\\%' will be escaped to a percent. Need transform to `a%row`.\n\n///\n\n/// If is_pruning is true, will be called on range_filter:L379.\n\n/// OrdinalStr is returned, because the pattern can be transformed by range_filter:L382.\n\n///\n\n/// If is_pruning is false, will be called on like.rs:L74.\n\n/// PatternStr is returned, because the pattern cannot be used directly on like.rs:L76.\n\npub fn check_pattern_type(pattern: &[u8], is_pruning: bool) -> PatternType {\n\n let len = pattern.len();\n\n if len == 0 {\n\n return PatternType::OrdinalStr;\n\n }\n\n\n\n let mut index = 0;\n\n let start_percent = pattern[0] == b'%';\n\n if start_percent {\n\n if is_pruning {\n\n return PatternType::PatternStr;\n\n }\n\n index += 1;\n\n }\n\n\n\n while index < len {\n\n match pattern[index] {\n\n b'_' => return PatternType::PatternStr,\n\n b'%' => {\n\n if index == len - 1 && !start_percent {\n", "file_path": "common/datavalues/src/arrays/ops/like.rs", "rank": 22, "score": 300458.05055822496 }, { "content": "pub fn aggregate_stddev_pop_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_stddev_pop_function))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_stddev_pop.rs", "rank": 23, "score": 300438.8572616576 }, { "content": "pub fn aggregate_window_funnel_function_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(try_create_aggregate_window_funnel_function))\n\n}\n", "file_path": "common/functions/src/aggregates/aggregate_window_funnel.rs", "rank": 24, "score": 300438.8572616576 }, { "content": "pub fn aggregate_covariance_sample_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(\n\n try_create_aggregate_covariance::<AggregateCovarianceSampleImpl>,\n\n ))\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_covariance.rs", "rank": 25, "score": 300071.7029706512 }, { "content": "pub fn aggregate_covariance_population_desc() -> AggregateFunctionDescription {\n\n AggregateFunctionDescription::creator(Box::new(\n\n try_create_aggregate_covariance::<AggregateCovariancePopulationImpl>,\n\n ))\n\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n\n// TODO: correlation function\n\n//struct AggregateCorrelationImpl;\n\n///////////////////////////////////////////////////////////////////////////////\n", "file_path": "common/functions/src/aggregates/aggregate_covariance.rs", "rank": 26, "score": 300071.7029706512 }, { "content": "fn to_primitive_str(dt: &DataType) -> &str {\n\n use DataType::*;\n\n match dt {\n\n UInt8 => \"u8\",\n\n UInt16 => \"u16\",\n\n UInt32 => \"u32\",\n\n UInt64 => \"u64\",\n\n Int8 => \"i8\",\n\n Int16 => \"i16\",\n\n Int32 => \"i32\",\n\n Int64 => \"i64\",\n\n Float32 => \"f32\",\n\n Float64 => \"f64\",\n\n _ => panic!(\"unsupported data type\"),\n\n }\n\n}\n", "file_path": "common/codegen/src/writes/arithmetics_type.rs", "rank": 27, "score": 297937.957325228 }, { "content": "pub fn get_expr_display_string(_expr: &Expr) -> String {\n\n // TODO: this is Postgres style name for anonymous select item\n\n \"?column?\".to_string()\n\n}\n\n\n\npub struct BindResult {\n\n pub bind_context: BindContext,\n\n pub metadata: Metadata,\n\n}\n\n\n\nimpl BindResult {\n\n pub fn create(bind_context: BindContext, metadata: Metadata) -> Self {\n\n BindResult {\n\n bind_context,\n\n metadata,\n\n }\n\n }\n\n\n\n pub fn s_expr(&self) -> &SExpr {\n\n self.bind_context.expression.as_ref().unwrap()\n\n }\n\n}\n", "file_path": "query/src/sql/planner/binder.rs", "rank": 28, "score": 294535.57243435684 }, { "content": "/// tranform from DFStringArray to DFStringArray\n\n/// # Safety\n\n/// The caller must uphold the following invariants:\n\n/// * ensure the total len of transformed DFStringArray values <= estimate_bytes\n\npub fn transform<F>(from: &DFStringArray, estimate_bytes: usize, mut f: F) -> DFStringArray\n\nwhere F: FnMut(&[u8], &mut [u8]) -> Option<usize> {\n\n let mut values: Vec<u8> = Vec::with_capacity(estimate_bytes);\n\n let mut offsets: Vec<i64> = Vec::with_capacity(from.len() + 1);\n\n let mut validity = MutableBitmap::with_capacity(from.len());\n\n offsets.push(0);\n\n\n\n let mut offset: usize = 0;\n\n\n\n unsafe {\n\n for x in from.into_no_null_iter() {\n\n let bytes = std::slice::from_raw_parts_mut(\n\n values.as_mut_ptr().add(offset),\n\n values.capacity() - offset,\n\n );\n\n if let Some(len) = f(x, bytes) {\n\n offset += len;\n\n offsets.push(offset as i64);\n\n validity.push(true);\n\n } else {\n", "file_path": "common/datavalues/src/arrays/string/transform.rs", "rank": 29, "score": 293788.1835841205 }, { "content": "pub fn download(url: &str, target_file: &str) -> Result<()> {\n\n let res = ureq::get(url).call()?;\n\n let total_size: u64 = res\n\n .header(\"content-length\")\n\n .expect(\"cannot fetch content length from header\")\n\n .parse()\n\n .expect(\"cannot parse content header\");\n\n let pb = ProgressBar::new(total_size);\n\n pb.set_style(ProgressStyle::default_bar()\n\n .template(\"{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})\")\n\n .progress_chars(\"#>-\"));\n\n\n\n let mut out = File::create(target_file).unwrap_or_else(|_| {\n\n panic!(\n\n \"{}\",\n\n format!(\"cannot create target file {}\", target_file).as_str()\n\n )\n\n });\n\n io::copy(&mut pb.wrap_read(res.into_reader()), &mut out)\n\n .expect(\"cannot download to target file\");\n\n Ok(())\n\n}\n\n\n", "file_path": "cli/src/cmds/packages/fetch.rs", "rank": 30, "score": 289094.5459179588 }, { "content": "pub fn parse_nullable_type(source: &str) -> Option<&str> {\n\n if !source.starts_with(\"Nullable\") {\n\n return None;\n\n }\n\n\n\n let inner_type = &source[9..source.len() - 1];\n\n\n\n if inner_type.starts_with(\"Nullable\") {\n\n return None;\n\n }\n\n\n\n Some(inner_type)\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 31, "score": 288842.91150487494 }, { "content": "pub fn sort_to_inner_expr(expr: &Expression) -> Expression {\n\n match expr {\n\n Expression::Sort {\n\n expr: nest_exprs, ..\n\n } => *nest_exprs.clone(),\n\n _ => expr.clone(),\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 32, "score": 287383.2617672208 }, { "content": "#[inline]\n\npub fn label_counter(name: &'static str, tenant_id: &str, cluster_id: &str) {\n\n label_counter_with_val(name, 1, tenant_id, cluster_id)\n\n}\n\n\n", "file_path": "common/metrics/src/recorder.rs", "rank": 33, "score": 286626.44712270185 }, { "content": "pub fn unpack(tar_file: &str, target_dir: &str) -> Result<()> {\n\n let tar_gz = File::open(tar_file)?;\n\n let tar = GzDecoder::new(tar_gz);\n\n let mut archive = Archive::new(tar);\n\n let res = archive.unpack(target_dir);\n\n return match res {\n\n Ok(_) => {\n\n if Path::new(format!(\"{}/GNUSparseFile.0\", target_dir).as_str()).exists()\n\n && Path::new(format!(\"{}/GNUSparseFile.0\", target_dir).as_str()).is_dir()\n\n {\n\n let options = dir::CopyOptions::new(); //Initialize default values for CopyOptions\n\n\n\n let mut from_paths = Vec::new();\n\n from_paths.push(format!(\"{}/GNUSparseFile.0/databend-query\", target_dir));\n\n from_paths.push(format!(\"{}/GNUSparseFile.0/databend-meta\", target_dir));\n\n move_items(&from_paths, target_dir, &options)\n\n .expect(\"cannot move executable files\");\n\n if let Ok(()) = std::fs::remove_dir_all(format!(\"{}/GNUSparseFile.0\", target_dir)) {\n\n }\n\n }\n\n Ok(())\n\n }\n\n Err(e) => Err(CliError::Unknown(format!(\n\n \"cannot unpack file {} to {}, error: {}\",\n\n tar_file, target_dir, e\n\n ))),\n\n };\n\n}\n\n\n", "file_path": "cli/src/cmds/packages/fetch.rs", "rank": 34, "score": 286351.02484191424 }, { "content": "/// Convert any `Expression` to an `Expression::Column`.\n\npub fn expr_as_column_expr(expr: &Expression) -> Result<Expression> {\n\n match expr {\n\n Expression::Column(_) => Ok(expr.clone()),\n\n _ => Ok(Expression::Column(expr.column_name())),\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 35, "score": 286048.95642841875 }, { "content": "pub fn expand_aggregate_arg_exprs(exprs: &[Expression]) -> Vec<Expression> {\n\n let mut res = vec![];\n\n for expr in exprs {\n\n match expr {\n\n Expression::AggregateFunction { args, .. } => {\n\n for arg in args {\n\n if !res.contains(arg) {\n\n res.push(arg.clone());\n\n }\n\n }\n\n }\n\n _ => {\n\n if !res.contains(expr) {\n\n res.push(expr.clone());\n\n }\n\n }\n\n }\n\n }\n\n res\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 36, "score": 285182.4415046497 }, { "content": "pub fn find_aggregate_exprs_in_expr(expr: &Expression) -> Vec<Expression> {\n\n find_exprs_in_expr(expr, &|nest_exprs| {\n\n matches!(nest_exprs, Expression::AggregateFunction { .. })\n\n })\n\n}\n\n\n\n/// Collect all arguments from aggregation function and append to this exprs\n\n/// [ColumnExpr(b), Aggr(sum(a, b))] ---> [ColumnExpr(b), ColumnExpr(a)]\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 37, "score": 283535.0740595318 }, { "content": "pub trait ArrayBuilder<N, Array> {\n\n fn append_value(&mut self, val: N);\n\n fn append_null(&mut self);\n\n fn append_option(&mut self, opt_val: Option<N>) {\n\n match opt_val {\n\n Some(v) => self.append_value(v),\n\n None => self.append_null(),\n\n }\n\n }\n\n fn finish(&mut self) -> Array;\n\n}\n\n\n", "file_path": "common/datavalues/src/arrays/builder.rs", "rank": 38, "score": 282517.8877427079 }, { "content": "pub fn create_mutable_array(datatype: DataType) -> Box<dyn MutableArrayBuilder> {\n\n match datatype {\n\n DataType::Boolean => Box::new(MutableBooleanArrayBuilder::<true>::default()),\n\n DataType::UInt8 => Box::new(MutablePrimitiveArrayBuilder::<u8, true>::default()),\n\n DataType::UInt16 => Box::new(MutablePrimitiveArrayBuilder::<u16, true>::default()),\n\n DataType::UInt32 => Box::new(MutablePrimitiveArrayBuilder::<u32, true>::default()),\n\n DataType::UInt64 => Box::new(MutablePrimitiveArrayBuilder::<u64, true>::default()),\n\n DataType::Int8 => Box::new(MutablePrimitiveArrayBuilder::<i8, true>::default()),\n\n DataType::Int16 => Box::new(MutablePrimitiveArrayBuilder::<i16, true>::default()),\n\n DataType::Int32 => Box::new(MutablePrimitiveArrayBuilder::<i32, true>::default()),\n\n DataType::Int64 => Box::new(MutablePrimitiveArrayBuilder::<i64, true>::default()),\n\n DataType::Float32 => Box::new(MutablePrimitiveArrayBuilder::<f32, true>::default()),\n\n DataType::Float64 => Box::new(MutablePrimitiveArrayBuilder::<f64, true>::default()),\n\n DataType::String => Box::new(MutableStringArrayBuilder::<true>::default()),\n\n _ => {\n\n todo!()\n\n }\n\n }\n\n}\n", "file_path": "common/datavalues/src/arrays/mutable.rs", "rank": 39, "score": 282274.10097283823 }, { "content": "pub fn from_url(url_str: &str) -> Result<Options> {\n\n let url = Url::parse(url_str)?;\n\n\n\n if url.scheme() != \"tcp\" {\n\n return Err(UrlError::UnsupportedScheme {\n\n scheme: url.scheme().to_string(),\n\n }\n\n .into());\n\n }\n\n\n\n if url.cannot_be_a_base() || !url.has_host() {\n\n return Err(UrlError::Invalid.into());\n\n }\n\n\n\n let mut options = Options::default();\n\n\n\n if let Some(username) = get_username_from_url(&url) {\n\n options.username = username.into();\n\n }\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 40, "score": 281374.3801605295 }, { "content": "pub fn parse_tuple_type(source: &str) -> Option<Vec<&str>> {\n\n if !source.starts_with(\"Tuple\") {\n\n return None;\n\n }\n\n\n\n let types = &source[6..source.len() - 1];\n\n\n\n let mut inner_types = Vec::new();\n\n let chars = types.char_indices();\n\n let mut diff = 0;\n\n let mut last = 0;\n\n for (i, c) in chars {\n\n match c {\n\n '(' => diff += 1,\n\n ')' => diff -= 1,\n\n ',' => {\n\n if diff == 0 {\n\n inner_types.push(types[last..i].trim());\n\n last = i + 1;\n\n }\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 41, "score": 281137.0128737493 }, { "content": "fn parse_knobs(mut input: syn::ItemFn, is_test: bool, has_tracker: bool) -> TokenStream {\n\n let mut inner_impl = input.clone();\n\n inner_impl.sig.ident = Ident::new(\"main_impl\", inner_impl.sig.ident.span());\n\n\n\n input.sig.asyncness = None;\n\n input.sig.inputs.clear();\n\n let (last_stmt_start_span, last_stmt_end_span) = {\n\n let mut last_stmt = input\n\n .block\n\n .stmts\n\n .last()\n\n .map(quote::ToTokens::into_token_stream)\n\n .unwrap_or_default()\n\n .into_iter();\n\n\n\n let start = last_stmt\n\n .next()\n\n .map_or_else(proc_macro2::Span::call_site, |t| t.span());\n\n let end = last_stmt.last().map_or(start, |t| t.span());\n\n (start, end)\n", "file_path": "common/macros/src/async_entrypoint.rs", "rank": 42, "score": 279682.1360985237 }, { "content": "/// Rebuilds an `expr` using the inner expr for expression\n\n/// `(a + b) as c` ---> `(a + b)`\n\npub fn unwrap_alias_exprs(expr: &Expression) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_exprs| match nest_exprs {\n\n Expression::Alias(_, nested_expr) => Ok(Some(*nested_expr.clone())),\n\n _ => Ok(None),\n\n })\n\n}\n\n\n\npub struct ExpressionDataTypeVisitor {\n\n stack: Vec<DataTypeAndNullable>,\n\n input_schema: DataSchemaRef,\n\n}\n\n\n\nimpl ExpressionDataTypeVisitor {\n\n pub fn create(input_schema: DataSchemaRef) -> ExpressionDataTypeVisitor {\n\n ExpressionDataTypeVisitor {\n\n input_schema,\n\n stack: vec![],\n\n }\n\n }\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 43, "score": 278766.07659993146 }, { "content": "pub fn col(name: &str) -> Expression {\n\n Expression::Column(name.to_string())\n\n}\n", "file_path": "common/planners/src/plan_expression_column.rs", "rank": 44, "score": 278463.7430461905 }, { "content": "/// Init logging and tracing.\n\n///\n\n/// A local tracing collection(maybe for testing) can be done with a local jaeger server.\n\n/// To report tracing data and view it:\n\n/// docker run -d -p6831:6831/udp -p6832:6832/udp -p16686:16686 jaegertracing/all-in-one:latest\n\n/// RUST_LOG=trace cargo test\n\n/// open http://localhost:16686/\n\n///\n\n/// To adjust batch sending delay, use `OTEL_BSP_SCHEDULE_DELAY`:\n\n/// RUST_LOG=trace OTEL_BSP_SCHEDULE_DELAY=1 cargo test\n\n///\n\n// TODO(xp): use DATABEND_JAEGER to assign jaeger server address.\n\npub fn init_global_tracing(app_name: &str, dir: &str, level: &str) -> Vec<WorkerGuard> {\n\n let mut guards = vec![];\n\n\n\n // Stdout layer.\n\n let (stdout_writer, stdout_guard) = tracing_appender::non_blocking(std::io::stdout());\n\n let stdout_logging_layer = Layer::new().with_writer(stdout_writer);\n\n guards.push(stdout_guard);\n\n\n\n // JSON log layer.\n\n let rolling_appender = RollingFileAppender::new(Rotation::HOURLY, dir, app_name);\n\n let (rolling_writer, rolling_writer_guard) = tracing_appender::non_blocking(rolling_appender);\n\n let file_logging_layer = BunyanFormattingLayer::new(app_name.to_string(), rolling_writer);\n\n guards.push(rolling_writer_guard);\n\n\n\n // Jaeger layer.\n\n global::set_text_map_propagator(TraceContextPropagator::new());\n\n let tracer = opentelemetry_jaeger::new_pipeline()\n\n .with_service_name(app_name)\n\n .install_batch(opentelemetry::runtime::Tokio)\n\n .expect(\"install\");\n", "file_path": "common/tracing/src/logging.rs", "rank": 45, "score": 278096.6413844451 }, { "content": "pub fn do_init_meta_ut_tracing(app_name: &str, dir: &str, level: &str) -> Vec<WorkerGuard> {\n\n let mut guards = vec![];\n\n\n\n let span_rolling_appender = RollingFileAppender::new(Rotation::HOURLY, dir, app_name);\n\n let (writer, writer_guard) = tracing_appender::non_blocking(span_rolling_appender);\n\n\n\n let f_layer = fmt::Layer::new()\n\n .with_span_events(fmt::format::FmtSpan::FULL)\n\n .with_writer(writer)\n\n .with_ansi(false)\n\n .event_format(EventFormatter {});\n\n\n\n guards.push(writer_guard);\n\n\n\n // Use env RUST_LOG to initialize log if present.\n\n // Otherwise use the specified level.\n\n let directives = env::var(EnvFilter::DEFAULT_ENV).unwrap_or_else(|_x| level.to_string());\n\n let env_filter = EnvFilter::new(directives);\n\n let subscriber = Registry::default().with(env_filter).with(f_layer);\n\n\n\n tracing::subscriber::set_global_default(subscriber)\n\n .expect(\"error setting global tracing subscriber\");\n\n\n\n guards\n\n}\n", "file_path": "common/tracing/src/logging.rs", "rank": 46, "score": 275874.9226960803 }, { "content": "// Can works before expression,filter,having in PlanBuilder\n\npub fn validate_expression(expr: &Expression) -> Result<()> {\n\n let validator = ExpressionValidator::new(&|expr: &Expression| match expr {\n\n Expression::ScalarFunction { op, args } => {\n\n let features = FunctionFactory::instance().get_features(op)?;\n\n validate_function_arg(\n\n op,\n\n args.len(),\n\n features.variadic_arguments,\n\n features.num_arguments,\n\n )\n\n }\n\n\n\n // Currently no need to check UnaryExpression and BinaryExpression\n\n // todo: AggregateFunction validation after generic AggregateFunctions\n\n _ => Ok(()),\n\n });\n\n\n\n let validator = expr.accept(validator)?;\n\n match validator.error {\n\n Some(err) => Err(err),\n\n None => Ok(()),\n\n }\n\n}\n", "file_path": "common/planners/src/plan_expression_validator.rs", "rank": 47, "score": 275467.5043380449 }, { "content": "pub fn parse_func_history_args(table_args: &TableArgs) -> Result<(String, String)> {\n\n match table_args {\n\n Some(args) if args.len() == 2 => {\n\n let db = string_value(&args[0])?;\n\n let tbl = string_value(&args[1])?;\n\n Ok((db, tbl))\n\n }\n\n _ => Err(ErrorCode::BadArguments(format!(\n\n \"expecting database and table name (as two string literals), but got {:?}\",\n\n table_args\n\n ))),\n\n }\n\n}\n", "file_path": "query/src/storages/fuse/table_functions/table_arg_util.rs", "rank": 48, "score": 274491.3983801723 }, { "content": "#[allow(dead_code)]\n\npub fn eval_function(\n\n columns: &DataColumnsWithField,\n\n rows: usize,\n\n func: Box<dyn Function>,\n\n) -> Result<DataColumn> {\n\n if func.passthrough_null() {\n\n let arg_column_validities = columns\n\n .iter()\n\n .map(|column_with_field| {\n\n let col = column_with_field.column();\n\n col.get_validity()\n\n })\n\n .collect::<Vec<_>>();\n\n\n\n let v = func.eval(columns, rows)?;\n\n let v = v.apply_validities(arg_column_validities.as_ref())?;\n\n Ok(v)\n\n } else {\n\n func.eval(columns, rows)\n\n }\n\n}\n", "file_path": "common/functions/tests/it/scalars/helpers.rs", "rank": 49, "score": 273733.56037030177 }, { "content": "fn check_maybe_monotonic(expr: &Expression) -> Result<bool> {\n\n match expr {\n\n Expression::Literal { .. } => Ok(true),\n\n Expression::Column { .. } => Ok(true),\n\n Expression::BinaryExpression { op, left, right } => {\n\n get_maybe_monotonic(op, vec![left.as_ref().clone(), right.as_ref().clone()])\n\n }\n\n Expression::UnaryExpression { op, expr } => {\n\n get_maybe_monotonic(op, vec![expr.as_ref().clone()])\n\n }\n\n Expression::ScalarFunction { op, args } => get_maybe_monotonic(op, args.clone()),\n\n Expression::Cast { expr, .. } => check_maybe_monotonic(expr),\n\n _ => Ok(false),\n\n }\n\n}\n\n\n", "file_path": "query/src/storages/index/range_filter.rs", "rank": 50, "score": 273685.1072969133 }, { "content": "pub fn test_scalar_functions(\n\n test_function: Box<dyn Function>,\n\n tests: &[ScalarFunctionTest],\n\n) -> Result<()> {\n\n let mut tests_with_type = Vec::with_capacity(tests.len());\n\n for test in tests {\n\n let mut arguments = Vec::with_capacity(test.columns.len());\n\n\n\n for (index, arg_column) in test.columns.iter().enumerate() {\n\n match arg_column {\n\n DataColumn::Constant(v, _n) => {\n\n arguments.push(DataColumnWithField::new(\n\n arg_column.clone(),\n\n DataField::new(\n\n &format!(\"dummy_{}\", index),\n\n arg_column.data_type(),\n\n v.is_null(),\n\n ),\n\n ));\n\n }\n", "file_path": "common/functions/tests/it/scalars/scalar_function_test.rs", "rank": 51, "score": 270952.6096543725 }, { "content": "/// Rebuilds an `expr` as a projection on top of a collection of `Expression`'s.\n\n///\n\n/// For example, the Expression `a + b < 1` would require, as input, the 2\n\n/// individual columns, `a` and `b`. But, if the base exprs already\n\n/// contain the `a + b` result, then that may be used in lieu of the `a` and\n\n/// `b` columns.\n\n///\n\n/// This is useful in the context of a query like:\n\n///\n\n/// SELECT a + b < 1 ... GROUP BY a + b\n\n///\n\n/// where post-aggregation, `a + b` need not be a projection against the\n\n/// individual columns `a` and `b`, but rather it is a projection against the\n\n/// `a + b` found in the GROUP BY.\n\npub fn rebase_expr(expr: &Expression, base_exprs: &[Expression]) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_exprs| {\n\n if base_exprs.contains(nest_exprs) {\n\n Ok(Some(expr_as_column_expr(nest_exprs)?))\n\n } else {\n\n Ok(None)\n\n }\n\n })\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 52, "score": 270906.7025897851 }, { "content": "/// return a new expression l <op> r.\n\nfn binary_expr(l: Expression, op: &str, r: Expression) -> Expression {\n\n Expression::BinaryExpression {\n\n op: op.to_string(),\n\n left: Box::new(l),\n\n right: Box::new(r),\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 53, "score": 270506.0468863104 }, { "content": "pub fn is_fuse_table(table: &dyn Table) -> bool {\n\n let tid = table.as_any().type_id();\n\n tid == TypeId::of::<FuseTable>()\n\n}\n", "file_path": "query/src/storages/fuse/table.rs", "rank": 54, "score": 269587.9830813028 }, { "content": "pub fn test_scalar_functions_with_type(\n\n test_function: Box<dyn Function>,\n\n tests: &[ScalarFunctionTestWithType],\n\n) -> Result<()> {\n\n for test in tests {\n\n let mut rows_size = 0;\n\n let mut arguments_type = Vec::with_capacity(test.columns.len());\n\n\n\n for (_index, arg_column) in test.columns.iter().enumerate() {\n\n match arg_column.column() {\n\n DataColumn::Constant(v, n) => {\n\n rows_size = *n;\n\n arguments_type.push(DataTypeAndNullable::create(\n\n arg_column.data_type(),\n\n v.is_null(),\n\n ));\n\n }\n\n DataColumn::Array(series) if series.null_count() == 0 => {\n\n rows_size = series.len();\n\n arguments_type.push(DataTypeAndNullable::create(arg_column.data_type(), false));\n", "file_path": "common/functions/tests/it/scalars/scalar_function_test.rs", "rank": 55, "score": 268187.7875128611 }, { "content": "pub fn from_arrow_type(dt: &ArrowType) -> DataTypePtr {\n\n match dt {\n\n ArrowType::Null => Arc::new(NullableType::create(Arc::new(NullType {}))),\n\n ArrowType::UInt8 => Arc::new(UInt8Type::default()),\n\n ArrowType::UInt16 => Arc::new(UInt16Type::default()),\n\n ArrowType::UInt32 => Arc::new(UInt32Type::default()),\n\n ArrowType::UInt64 => Arc::new(UInt64Type::default()),\n\n ArrowType::Int8 => Arc::new(Int8Type::default()),\n\n ArrowType::Int16 => Arc::new(Int16Type::default()),\n\n ArrowType::Int32 => Arc::new(Int32Type::default()),\n\n ArrowType::Int64 => Arc::new(Int64Type::default()),\n\n ArrowType::Boolean => Arc::new(BooleanType::default()),\n\n ArrowType::Float32 => Arc::new(Float32Type::default()),\n\n ArrowType::Float64 => Arc::new(Float64Type::default()),\n\n\n\n // TODO support other list\n\n ArrowType::LargeList(f) => {\n\n let inner = from_arrow_field(f);\n\n Arc::new(ArrayType::create(inner))\n\n }\n", "file_path": "common/datavalues2/src/types/data_type.rs", "rank": 56, "score": 266819.1181032426 }, { "content": "#[inline]\n\npub fn set_bit(data: &mut [u8], i: usize) {\n\n data[i >> 3] |= BIT_MASK[i & 7];\n\n}\n\n\n\n/// Sets bit at position `i` for `data`\n\n///\n\n/// # Safety\n\n///\n\n/// Note this doesn't do any bound checking, for performance reason. The caller is\n\n/// responsible to guarantee that `i` is within bounds.\n\n#[inline]\n\npub unsafe fn set_bit_raw(data: *mut u8, i: usize) {\n\n *data.add(i >> 3) |= BIT_MASK[i & 7];\n\n}\n\n\n\n/// Sets bit at position `i` for `data` to 0\n", "file_path": "common/datavalues/src/bit_util.rs", "rank": 57, "score": 264250.9480838774 }, { "content": "#[inline]\n\npub fn unset_bit(data: &mut [u8], i: usize) {\n\n data[i >> 3] ^= BIT_MASK[i & 7];\n\n}\n\n\n\n/// Sets bit at position `i` for `data` to 0\n\n///\n\n/// # Safety\n\n///\n\n/// Note this doesn't do any bound checking, for performance reason. The caller is\n\n/// responsible to guarantee that `i` is within bounds.\n\n#[inline]\n\npub unsafe fn unset_bit_raw(data: *mut u8, i: usize) {\n\n *data.add(i >> 3) ^= BIT_MASK[i & 7];\n\n}\n\n\n\n/// Returns the ceil of `value`/`divisor`\n", "file_path": "common/datavalues/src/bit_util.rs", "rank": 58, "score": 264250.9480838774 }, { "content": "#[inline]\n\npub fn get_bit(data: &[u8], i: usize) -> bool {\n\n (data[i >> 3] & BIT_MASK[i & 7]) != 0\n\n}\n\n\n\n/// Returns whether bit at position `i` in `data` is set or not.\n\n///\n\n/// # Safety\n\n///\n\n/// Note this doesn't do any bound checking, for performance reason. The caller is\n\n/// responsible to guarantee that `i` is within bounds.\n\n#[inline]\n\npub unsafe fn get_bit_raw(data: *const u8, i: usize) -> bool {\n\n (*data.add(i >> 3) & BIT_MASK[i & 7]) != 0\n\n}\n\n\n\n/// Sets bit at position `i` for `data`\n", "file_path": "common/datavalues/src/bit_util.rs", "rank": 59, "score": 264245.3813648416 }, { "content": "pub fn make_state_uri(query_id: &str) -> String {\n\n format!(\"/v1/query/{}\", query_id)\n\n}\n\n\n", "file_path": "query/src/servers/http/v1/http_query_handlers.rs", "rank": 60, "score": 263962.3600736629 }, { "content": "pub fn make_final_uri(query_id: &str) -> String {\n\n format!(\"/v1/query/{}/kill?delete=true\", query_id)\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct QueryError {\n\n pub code: u16,\n\n pub message: String,\n\n pub backtrace: Option<String>,\n\n // TODO(youngsofun): add other info more friendly to client\n\n}\n\n\n\nimpl QueryError {\n\n fn from_error_code(e: &ErrorCode) -> Self {\n\n QueryError {\n\n code: e.code(),\n\n message: e.message(),\n\n backtrace: e.backtrace().map(|b| b.to_string()),\n\n }\n\n }\n", "file_path": "query/src/servers/http/v1/http_query_handlers.rs", "rank": 61, "score": 263962.3600736629 }, { "content": "pub fn get_username_from_url(url: &Url) -> Option<&str> {\n\n let user = url.username();\n\n if user.is_empty() {\n\n return None;\n\n }\n\n Some(user)\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 62, "score": 263547.9396474407 }, { "content": "pub fn get_password_from_url(url: &Url) -> Option<&str> {\n\n url.password()\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 63, "score": 263547.9396474407 }, { "content": "/// Assert with order sensitive.\n\n/// ['a', 'b'] not equals ['b', 'a']\n\npub fn assert_blocks_eq_with_name(test_name: &str, expect: Vec<&str>, blocks: &[DataBlock]) {\n\n let expected_lines: Vec<String> = expect.iter().map(|&s| s.into()).collect();\n\n let formatted = pretty_format_blocks(blocks).unwrap();\n\n let actual_lines: Vec<&str> = formatted.trim().lines().collect();\n\n\n\n assert_eq!(\n\n expected_lines, actual_lines,\n\n \"{:#?}\\n\\nexpected:\\n\\n{:#?}\\nactual:\\n\\n{:#?}\\n\\n\",\n\n test_name, expected_lines, actual_lines\n\n );\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 64, "score": 262572.4395387668 }, { "content": "pub fn try_create_aggregate_sum_function(\n\n display_name: &str,\n\n _params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<AggregateFunctionRef> {\n\n assert_unary_arguments(display_name, arguments.len())?;\n\n\n\n let data_type = arguments[0].data_type();\n\n with_match_primitive_type!(data_type, |$T| {\n\n AggregateSumFunction::<$T, <$T as DFPrimitiveType>::LargestType>::try_create(\n\n display_name,\n\n arguments,\n\n )\n\n },\n\n\n\n // no matching branch\n\n {\n\n Err(ErrorCode::BadDataValueType(format!(\n\n \"AggregateSumFunction does not support type '{:?}'\",\n\n data_type\n\n )))\n\n })\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_sum.rs", "rank": 65, "score": 261366.38112135843 }, { "content": "pub fn try_create_aggregate_avg_function(\n\n display_name: &str,\n\n _params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<Arc<dyn AggregateFunction>> {\n\n assert_unary_arguments(display_name, arguments.len())?;\n\n\n\n let data_type = arguments[0].data_type();\n\n with_match_primitive_type!(data_type, |$T| {\n\n AggregateAvgFunction::<$T, <$T as DFPrimitiveType>::LargestType>::try_create(\n\n display_name,\n\n arguments,\n\n )\n\n },\n\n\n\n {\n\n Err(ErrorCode::BadDataValueType(format!(\n\n \"AggregateAvgFunction does not support type '{:?}'\",\n\n data_type\n\n )))\n\n })\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_avg.rs", "rank": 66, "score": 261366.38112135843 }, { "content": "pub fn parse_fixed_string(source: &str) -> Option<usize> {\n\n if !source.starts_with(\"FixedString\") {\n\n return None;\n\n }\n\n\n\n let inner_size = &source[12..source.len() - 1];\n\n match inner_size.parse::<usize>() {\n\n Err(_) => None,\n\n Ok(value) => Some(value),\n\n }\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 67, "score": 260762.98677379574 }, { "content": "/// Assert with order insensitive.\n\n/// ['a', 'b'] equals ['b', 'a']\n\npub fn assert_blocks_sorted_eq_with_name(test_name: &str, expect: Vec<&str>, blocks: &[DataBlock]) {\n\n let mut expected_lines: Vec<String> = expect.iter().map(|&s| s.into()).collect();\n\n\n\n // sort except for header + footer\n\n let num_lines = expected_lines.len();\n\n if num_lines > 3 {\n\n expected_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()\n\n }\n\n\n\n let formatted = pretty_format_blocks(blocks).unwrap();\n\n let mut actual_lines: Vec<&str> = formatted.trim().lines().collect();\n\n\n\n // sort except for header + footer\n\n let num_lines = actual_lines.len();\n\n if num_lines > 3 {\n\n actual_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()\n\n }\n\n\n\n assert_eq!(\n\n expected_lines, actual_lines,\n\n \"{:#?}\\n\\nexpected:\\n\\n{:#?}\\nactual:\\n\\n{:#?}\\n\\n\",\n\n test_name, expected_lines, actual_lines\n\n );\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 68, "score": 260387.87631737522 }, { "content": "fn date_array_to_string_array<T>(array: &DFPrimitiveArray<T>, fmt: &str) -> Vec<JsonValue>\n\nwhere T: DFPrimitiveType + Serialize + Into<i64> {\n\n array\n\n .into_iter()\n\n .map(|o| o.map(|x| date_number_to_string(Into::<i64>::into(*x), fmt)))\n\n .map(to_json_value)\n\n .collect()\n\n}\n\n\n", "file_path": "query/src/servers/http/v1/block_to_json.rs", "rank": 69, "score": 259003.1788889719 }, { "content": "// Rebuilds an `expr` to ColumnExpr when some expressions already processed in upstream\n\n// Skip Sort, Alias because we can go into the inner nest_exprs\n\npub fn rebase_expr_from_input(expr: &Expression, schema: &DataSchemaRef) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_exprs| match nest_exprs {\n\n Expression::Sort { .. }\n\n | Expression::Column(_)\n\n | Expression::Literal {\n\n column_name: None, ..\n\n }\n\n | Expression::Alias(_, _) => Ok(None),\n\n _ => {\n\n if schema.field_with_name(&nest_exprs.column_name()).is_ok() {\n\n Ok(Some(expr_as_column_expr(nest_exprs)?))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 70, "score": 258451.59032346285 }, { "content": "// put_uvarint encodes a uint64 into buf and returns the number of bytes written.\n\n// If the buffer is too small, put_uvarint will panic.\n\npub fn put_uvarint(mut buffer: impl AsMut<[u8]>, x: u64) -> usize {\n\n let mut i = 0;\n\n let mut mx = x;\n\n let buf = buffer.as_mut();\n\n while mx >= 0x80 {\n\n buf[i] = mx as u8 | 0x80;\n\n mx >>= 7;\n\n i += 1;\n\n }\n\n buf[i] = mx as u8;\n\n i + 1\n\n}\n", "file_path": "common/io/src/binary_write.rs", "rank": 71, "score": 257368.91185878133 }, { "content": "pub fn try_create_aggregate_window_funnel_function(\n\n display_name: &str,\n\n params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<AggregateFunctionRef> {\n\n assert_unary_params(display_name, params.len())?;\n\n assert_variadic_arguments(display_name, arguments.len(), (1, 32))?;\n\n\n\n for (idx, arg) in arguments[1..].iter().enumerate() {\n\n if arg.data_type() != &DataType::Boolean {\n\n return Err(ErrorCode::BadDataValueType(format!(\n\n \"Illegal type of the argument {} in AggregateWindowFunnelFunction, must be boolean, got: {}\",\n\n idx + 1, arg.data_type()\n\n )));\n\n }\n\n }\n\n\n\n let data_type = arguments[0].data_type();\n\n with_match_date_date_time_types! {creator, data_type.clone(), display_name, params, arguments}\n\n with_match_unsigned_numeric_types! {creator, data_type.clone(), display_name, params, arguments}\n\n\n\n Err(ErrorCode::BadDataValueType(format!(\n\n \"AggregateWindowFunnelFunction does not support type '{:?}'\",\n\n data_type\n\n )))\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_window_funnel.rs", "rank": 72, "score": 255823.877960734 }, { "content": "pub fn try_create_aggregate_stddev_pop_function(\n\n display_name: &str,\n\n _params: Vec<DataValue>,\n\n arguments: Vec<DataField>,\n\n) -> Result<Arc<dyn AggregateFunction>> {\n\n assert_unary_arguments(display_name, arguments.len())?;\n\n\n\n let data_type = arguments[0].data_type();\n\n\n\n with_match_primitive_type!(data_type, |$T| {\n\n AggregateStddevPopFunction::<$T>::try_create(display_name, arguments)\n\n },\n\n\n\n {\n\n Err(ErrorCode::BadDataValueType(format!(\n\n \"AggregateStddevPopFunction does not support type '{:?}'\",\n\n data_type\n\n )))\n\n })\n\n}\n\n\n", "file_path": "common/functions/src/aggregates/aggregate_stddev_pop.rs", "rank": 73, "score": 255823.877960734 }, { "content": "pub fn create_github_client(token: &str) -> Result<Arc<Octocrab>> {\n\n if token.is_empty() {\n\n return Ok(octocrab::instance());\n\n }\n\n Ok(Arc::new(\n\n octocrab::OctocrabBuilder::new()\n\n .add_header(AUTHORIZATION, format!(\"token {}\", token))\n\n .build()\n\n .map_err(|err| {\n\n ErrorCode::UnexpectedError(format!(\n\n \"Error Occured when creating octorab client, err: {}\",\n\n err\n\n ))\n\n })?,\n\n ))\n\n}\n", "file_path": "query/src/storages/github/github_client.rs", "rank": 74, "score": 255425.43388086488 }, { "content": "pub fn get_database_from_url(url: &Url) -> Result<Option<&str>> {\n\n match url.path_segments() {\n\n None => Ok(None),\n\n Some(mut segments) => {\n\n let head = segments.next();\n\n\n\n if segments.next().is_some() {\n\n return Err(Error::Url(UrlError::Invalid));\n\n }\n\n\n\n match head {\n\n Some(database) if !database.is_empty() => Ok(Some(database)),\n\n _ => Ok(None),\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 75, "score": 255425.43388086488 }, { "content": "// put_uvarint encodes a uint64 into buf and returns the number of bytes written.\n\n// If the buffer is too small, put_uvarint will panic.\n\npub fn put_uvarint(mut buffer: impl AsMut<[u8]>, x: u64) -> usize {\n\n let mut i = 0;\n\n let mut mx = x;\n\n let buf = buffer.as_mut();\n\n while mx >= 0x80 {\n\n buf[i] = mx as u8 | 0x80;\n\n mx >>= 7;\n\n i += 1;\n\n }\n\n buf[i] = mx as u8;\n\n i + 1\n\n}\n", "file_path": "common/clickhouse-srv/src/binary/uvarint.rs", "rank": 76, "score": 254805.38233265985 }, { "content": "/// Rebuilds an `expr` with columns that refer to aliases replaced by the\n\n/// alias' underlying `expr`.\n\npub fn resolve_aliases_to_exprs(\n\n expr: &Expression,\n\n aliases: &HashMap<String, Expression>,\n\n) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_exprs| match nest_exprs {\n\n Expression::Column(name) => {\n\n if let Some(aliased_expr) = aliases.get(name) {\n\n Ok(Some(aliased_expr.clone()))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n _ => Ok(None),\n\n })\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 77, "score": 254687.74340686412 }, { "content": "/// convert expr to Verifiable Expression\n\n/// Rules: (section 5.2 of http://vldb.org/pvldb/vol14/p3083-edara.pdf)\n\npub fn build_verifiable_expr(\n\n expr: &Expression,\n\n schema: &DataSchemaRef,\n\n stat_columns: &mut StatColumns,\n\n) -> Expression {\n\n let unhandled = lit(true);\n\n\n\n let (exprs, op) = match expr {\n\n Expression::Literal { .. } => return expr.clone(),\n\n Expression::ScalarFunction { op, args } => (args.clone(), op.clone()),\n\n Expression::BinaryExpression { left, op, right } => match op.to_lowercase().as_str() {\n\n \"and\" => {\n\n let left = build_verifiable_expr(left, schema, stat_columns);\n\n let right = build_verifiable_expr(right, schema, stat_columns);\n\n return left.and(right);\n\n }\n\n \"or\" => {\n\n let left = build_verifiable_expr(left, schema, stat_columns);\n\n let right = build_verifiable_expr(right, schema, stat_columns);\n\n return left.or(right);\n", "file_path": "query/src/storages/index/range_filter.rs", "rank": 78, "score": 254686.5242768303 }, { "content": "// test cases fro Cmd::IncrSeq:\n\n// case_name, txid, key, want\n\npub fn cases_incr_seq() -> Vec<(&'static str, Option<RaftTxId>, &'static str, u64)> {\n\n vec![\n\n (\"incr on none\", Some(RaftTxId::new(\"foo\", 1)), \"k1\", 1),\n\n (\"incr on existent\", Some(RaftTxId::new(\"foo\", 2)), \"k1\", 2),\n\n (\n\n \"dup: same serial, even with diff key, got the previous result\",\n\n Some(RaftTxId::new(\"foo\", 2)),\n\n \"k2\",\n\n 2,\n\n ),\n\n (\n\n \"diff client, same serial, not a dup request\",\n\n Some(RaftTxId::new(\"bar\", 2)),\n\n \"k2\",\n\n 1,\n\n ),\n\n (\"no txid, no de-dup\", None, \"k2\", 2),\n\n ]\n\n}\n\n\n\npub type AddFileCase = (\n\n &'static str,\n\n Option<RaftTxId>,\n\n &'static str,\n\n &'static str,\n\n Option<String>,\n\n Option<String>,\n\n);\n\n\n", "file_path": "common/meta/raft-store/src/state_machine/testing.rs", "rank": 79, "score": 254216.03515344212 }, { "content": "pub fn create_query_context_with_cluster(desc: ClusterDescriptor) -> Result<Arc<QueryContext>> {\n\n let sessions = SessionManagerBuilder::create().build()?;\n\n let dummy_session = sessions.create_session(\"TestSession\")?;\n\n\n\n let local_id = desc.local_node_id;\n\n let nodes = desc.cluster_nodes_list;\n\n\n\n let context = QueryContext::create_from_shared(QueryContextShared::try_create(\n\n sessions.get_conf().clone(),\n\n Arc::new(dummy_session.as_ref().clone()),\n\n Cluster::create(nodes, local_id),\n\n )?);\n\n\n\n context.get_settings().set_max_threads(8)?;\n\n Ok(context)\n\n}\n", "file_path": "query/tests/it/tests/context.rs", "rank": 80, "score": 252898.98242767697 }, { "content": "pub fn assert_blocks_eq(expect: Vec<&str>, blocks: &[DataBlock]) {\n\n assert_blocks_eq_with_name(\"\", expect, blocks)\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 81, "score": 252743.26710826074 }, { "content": "pub fn generate_local_log_dir(conf: &Config, dir_name: &str) -> String {\n\n let log_base = format!(\"{}/logs\", conf.clone().databend_dir);\n\n if !Path::new(log_base.as_str()).exists() {\n\n fs::create_dir(Path::new(log_base.as_str()))\n\n .unwrap_or_else(|_| panic!(\"cannot create directory {}\", log_base));\n\n }\n\n let query_log_dir = format!(\"{}/{}\", log_base, dir_name);\n\n if !Path::new(query_log_dir.as_str()).exists() {\n\n fs::create_dir(Path::new(query_log_dir.as_str())).unwrap_or_else(|_| {\n\n panic!(\"cannot create meta serivce log directory {}\", query_log_dir)\n\n });\n\n }\n\n query_log_dir\n\n}\n\n\n", "file_path": "cli/src/cmds/clusters/create.rs", "rank": 82, "score": 252743.26710826074 }, { "content": "/// Determines if the set of `Expression`'s are a valid projection on the input\n\n/// `Expression::Column`'s.\n\npub fn find_columns_not_satisfy_exprs(\n\n columns: &[Expression],\n\n exprs: &[Expression],\n\n) -> Result<Option<Expression>> {\n\n columns.iter().try_for_each(|c| match c {\n\n Expression::Column(_) => Ok(()),\n\n\n\n _ => Err(ErrorCode::SyntaxException(\n\n \"Expression::Column are required\".to_string(),\n\n )),\n\n })?;\n\n\n\n let exprs = find_column_exprs(exprs);\n\n for expr in &exprs {\n\n if !columns.contains(expr) {\n\n return Ok(Some(expr.clone()));\n\n }\n\n }\n\n Ok(None)\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 83, "score": 251418.79931611737 }, { "content": "pub fn validate_input<'a>(\n\n col0: &'a DataColumnWithField,\n\n col1: &'a DataColumnWithField,\n\n) -> (&'a DataColumnWithField, &'a DataColumnWithField) {\n\n if col0.data_type().is_integer() || col0.data_type().is_interval() {\n\n (col0, col1)\n\n } else {\n\n (col1, col0)\n\n }\n\n}\n\n\n", "file_path": "common/functions/src/scalars/arithmetics/utils.rs", "rank": 84, "score": 251338.39210256768 }, { "content": "#[inline]\n\npub fn unary<I, O, F>(array: &DFPrimitiveArray<I>, op: F) -> DFPrimitiveArray<O>\n\nwhere\n\n I: DFPrimitiveType,\n\n O: DFPrimitiveType,\n\n F: Fn(I) -> O,\n\n{\n\n let values = array.into_no_null_iter().map(|v| op(*v));\n\n let av = values.collect();\n\n to_primitive::<O>(av, array.inner().validity().cloned())\n\n}\n\n\n", "file_path": "common/datavalues/src/arrays/ops/arity.rs", "rank": 85, "score": 250675.43182747823 }, { "content": "#[allow(clippy::result_unit_err)]\n\npub fn parse_duration(source: &str) -> std::result::Result<Duration, ()> {\n\n let digits_count = source.chars().take_while(|c| c.is_digit(10)).count();\n\n\n\n let left: String = source.chars().take(digits_count).collect();\n\n let right: String = source.chars().skip(digits_count).collect();\n\n\n\n let num = match u64::from_str(&left) {\n\n Ok(value) => value,\n\n Err(_) => return Err(()),\n\n };\n\n\n\n match right.as_str() {\n\n \"s\" => Ok(Duration::from_secs(num)),\n\n \"ms\" => Ok(Duration::from_millis(num)),\n\n _ => Err(()),\n\n }\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/options.rs", "rank": 86, "score": 250559.73350443033 }, { "content": "/// Sorted assert.\n\npub fn assert_blocks_sorted_eq(expect: Vec<&str>, blocks: &[DataBlock]) {\n\n assert_blocks_sorted_eq_with_name(\"\", expect, blocks)\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 87, "score": 250158.2991514106 }, { "content": "/// tranform from DFStringArray to DFStringArray\n\n/// # Safety\n\n/// The caller must uphold the following invariants:\n\n/// * ensure the len of transformed DFStringArray values <= estimate_bytes\n\npub fn transform_with_no_null<F>(\n\n from: &DFStringArray,\n\n estimate_bytes: usize,\n\n mut f: F,\n\n) -> DFStringArray\n\nwhere\n\n F: FnMut(&[u8], &mut [u8]) -> usize,\n\n{\n\n let mut values: Vec<u8> = Vec::with_capacity(estimate_bytes);\n\n let mut offsets: Vec<i64> = Vec::with_capacity(from.len() + 1);\n\n offsets.push(0);\n\n\n\n let mut offset: usize = 0;\n\n\n\n unsafe {\n\n for x in from.into_no_null_iter() {\n\n let bytes = std::slice::from_raw_parts_mut(\n\n values.as_mut_ptr().add(offset),\n\n values.capacity() - offset,\n\n );\n", "file_path": "common/datavalues/src/arrays/string/transform.rs", "rank": 88, "score": 249150.10022610248 }, { "content": "pub fn equal(lhs: &dyn Column, rhs: &dyn Column) -> bool {\n\n if lhs.data_type() != rhs.data_type() || lhs.len() != lhs.len() {\n\n return false;\n\n }\n\n\n\n use crate::PhysicalTypeID::*;\n\n\n\n match lhs.data_type_id().to_physical_type() {\n\n Null => true,\n\n Nullable => {\n\n let lhs: &NullableColumn = lhs.as_any().downcast_ref().unwrap();\n\n let rhs: &NullableColumn = rhs.as_any().downcast_ref().unwrap();\n\n\n\n lhs.validity() == rhs.validity() && lhs.inner() == rhs.inner()\n\n }\n\n Boolean => {\n\n let lhs: &BooleanColumn = lhs.as_any().downcast_ref().unwrap();\n\n let rhs: &BooleanColumn = rhs.as_any().downcast_ref().unwrap();\n\n\n\n lhs.values() == rhs.values()\n", "file_path": "common/datavalues2/src/columns/eq.rs", "rank": 89, "score": 249013.18320860236 }, { "content": "pub fn parse_enum16(input: &str) -> Option<Vec<(String, i16)>> {\n\n parse_enum(EnumSize::Enum16, input)\n\n}\n\n\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 90, "score": 247877.5667318262 }, { "content": "pub fn parse_decimal(source: &str) -> Option<(u8, u8, NoBits)> {\n\n if source.len() < 12 {\n\n return None;\n\n }\n\n\n\n if !source.starts_with(\"Decimal\") {\n\n return None;\n\n }\n\n\n\n let mut nobits = None;\n\n let mut precision = None;\n\n let mut scale = None;\n\n\n\n let mut params_indexes = (None, None);\n\n\n\n for (idx, byte) in source.as_bytes().iter().enumerate() {\n\n if *byte == b'(' {\n\n match &source.as_bytes()[..idx] {\n\n b\"Decimal\" => {}\n\n b\"Decimal32\" => {\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 91, "score": 247877.5667318262 }, { "content": "pub fn parse_enum8(input: &str) -> Option<Vec<(String, i8)>> {\n\n parse_enum(EnumSize::Enum8, input).map(|result| {\n\n result\n\n .iter()\n\n .map(|(key, val)| (key.clone(), *val as i8))\n\n .collect::<Vec<(String, i8)>>()\n\n })\n\n}\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 92, "score": 247877.5667318262 }, { "content": "pub fn assert_blocks_sorted_eq_with_regex(patterns: Vec<&str>, blocks: &[DataBlock]) {\n\n let mut re_patterns: Vec<String> = patterns\n\n .iter()\n\n .map(|&s| {\n\n let mut re_pattern: String = \"^\".into();\n\n re_pattern += s;\n\n re_pattern += \"$\";\n\n re_pattern\n\n })\n\n .collect();\n\n\n\n // sort except for header + footer\n\n let num_lines = re_patterns.len();\n\n if num_lines > 3 {\n\n re_patterns.as_mut_slice()[2..num_lines - 1].sort_unstable()\n\n }\n\n\n\n let formatted = pretty_format_blocks(blocks).unwrap();\n\n let mut actual_lines: Vec<&str> = formatted.trim().lines().collect();\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 93, "score": 247665.34047238278 }, { "content": "pub fn make_page_uri(query_id: &str, page_no: usize) -> String {\n\n format!(\"/v1/query/{}/page/{}\", query_id, page_no)\n\n}\n\n\n", "file_path": "query/src/servers/http/v1/http_query_handlers.rs", "rank": 94, "score": 247665.34047238278 }, { "content": "pub fn arithmetic_mul_div_monotonicity(\n\n args: &[Monotonicity],\n\n op: DataValueBinaryOperator,\n\n) -> Result<Monotonicity> {\n\n if !matches!(\n\n op,\n\n DataValueBinaryOperator::Mul | DataValueBinaryOperator::Div\n\n ) {\n\n return Err(ErrorCode::BadArguments(format!(\n\n \"Invalid operator '{}' for get_monotonicity\",\n\n op\n\n )));\n\n }\n\n\n\n let f_x = &args[0];\n\n let g_x = &args[1];\n\n\n\n match (f_x.is_constant, g_x.is_constant) {\n\n // both f(x) and g(x) are constant\n\n (true, true) => Ok(Monotonicity::create_constant()),\n", "file_path": "common/functions/src/scalars/arithmetics/arithmetic_mul.rs", "rank": 95, "score": 246977.87295777036 }, { "content": "pub fn decompress_buffer<R>(reader: &mut R, mut buffer: Vec<u8>) -> Result<Vec<u8>>\n\nwhere R: ReadEx {\n\n let h = U128 {\n\n lo: reader.read_scalar()?,\n\n hi: reader.read_scalar()?,\n\n };\n\n\n\n let method: u8 = reader.read_scalar()?;\n\n if method != 0x82 {\n\n let message: String = format!(\"unsupported compression method {}\", method);\n\n return Err(raise_error(message));\n\n }\n\n\n\n let compressed: u32 = reader.read_scalar()?;\n\n let original: u32 = reader.read_scalar()?;\n\n\n\n if compressed > DBMS_MAX_COMPRESSED_SIZE {\n\n return Err(raise_error(\"compressed data too big\".to_string()));\n\n }\n\n\n", "file_path": "common/clickhouse-srv/src/types/block/compressed.rs", "rank": 96, "score": 245932.43524942984 }, { "content": "/// Resolves an `Expression::Wildcard` to a collection of `Expression::Column`'s.\n\npub fn expand_wildcard(expr: &Expression, schema: &DataSchemaRef) -> Vec<Expression> {\n\n match expr {\n\n Expression::Wildcard => schema\n\n .fields()\n\n .iter()\n\n .map(|f| Expression::Column(f.name().to_string()))\n\n .collect::<Vec<Expression>>(),\n\n _ => vec![expr.clone()],\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_common.rs", "rank": 97, "score": 245403.8406767277 }, { "content": "pub fn parse_date_time64(source: &str) -> Option<(u32, Option<String>)> {\n\n let integer = many1::<String, _, _>(digit()).and_then(|digits| {\n\n digits\n\n .parse::<u32>()\n\n .map_err(|_| StringStreamError::UnexpectedParse)\n\n });\n\n\n\n let word_syms = token('\\\\').with(any()).or(none_of(\"'\".chars()));\n\n let word = token('\\'')\n\n .with(many::<String, _, _>(word_syms))\n\n .skip(token('\\''));\n\n\n\n let timezone = optional(spaces().skip(token(',')).skip(spaces()).with(word));\n\n\n\n let pair = spaces()\n\n .with(integer)\n\n .skip(spaces())\n\n .and(timezone)\n\n .skip(spaces());\n\n\n", "file_path": "common/clickhouse-srv/src/types/column/factory.rs", "rank": 98, "score": 245292.59877497607 }, { "content": "pub fn equal(lhs: &dyn DataType, rhs: &dyn DataType) -> bool {\n\n if lhs.data_type_id() != rhs.data_type_id() {\n\n return false;\n\n }\n\n\n\n use crate::prelude::TypeID::*;\n\n match lhs.data_type_id() {\n\n Boolean | UInt8 | UInt16 | UInt32 | UInt64 | Int8 | Int16 | Int32 | Int64 | Float32\n\n | Float64 | String | Date16 | Date32 | Interval | DateTime32 | DateTime64 => true,\n\n\n\n Null | Nullable => {\n\n let lhs: &NullableType = lhs.as_any().downcast_ref().unwrap();\n\n let rhs: &NullableType = rhs.as_any().downcast_ref().unwrap();\n\n\n\n *lhs.inner_type() == *rhs.inner_type()\n\n }\n\n\n\n Array => {\n\n let lhs: &ArrayType = lhs.as_any().downcast_ref().unwrap();\n\n let rhs: &ArrayType = rhs.as_any().downcast_ref().unwrap();\n", "file_path": "common/datavalues2/src/types/eq.rs", "rank": 99, "score": 243545.06872415356 } ]
Rust
research/query_service/ir/integrated/tests/expand_test.rs
wuyueandrew/GraphScope
9e2d77d83378f85f001b555d06e4dcbf9a6a4260
mod common; #[cfg(test)] mod test { use std::sync::Arc; use graph_proxy::{create_demo_graph, SimplePartition}; use graph_store::ldbc::LDBCVertexParser; use graph_store::prelude::DefaultId; use ir_common::expr_parse::str_to_expr_pb; use ir_common::generated::algebra as pb; use ir_common::generated::common as common_pb; use pegasus::api::{Map, Sink}; use pegasus::result::ResultStream; use pegasus::JobConf; use runtime::graph::element::{Element, GraphElement}; use runtime::graph::property::Details; use runtime::process::operator::flatmap::FlatMapFuncGen; use runtime::process::operator::map::MapFuncGen; use runtime::process::operator::source::SourceOperator; use runtime::process::record::Record; use crate::common::test::*; fn source_gen(alias: Option<common_pb::NameOrId>) -> Box<dyn Iterator<Item = Record> + Send> { create_demo_graph(); let scan_opr_pb = pb::Scan { scan_opt: 0, alias, params: None, idx_predicate: None }; let mut source_opr_pb = pb::logical_plan::Operator { opr: Some(pb::logical_plan::operator::Opr::Scan(scan_opr_pb)) }; let source = SourceOperator::new(&mut source_opr_pb, 1, 1, Arc::new(SimplePartition { num_servers: 1 })) .unwrap(); source.gen_source(0).unwrap() } fn expand_test(expand: pb::EdgeExpand) -> ResultStream<Record> { let conf = JobConf::new("expand_test"); let result = pegasus::run(conf, || { let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); result } fn expand_test_with_source_tag( source_tag: common_pb::NameOrId, expand: pb::EdgeExpand, ) -> ResultStream<Record> { let conf = JobConf::new("expand_test"); let result = pegasus::run(conf, || { let source_tag = source_tag.clone(); let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(Some(source_tag)))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); result } #[test] fn expand_outv_test() { let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: None, is_edge: false, alias: None }; let mut result = expand_test(expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v3: DefaultId = LDBCVertexParser::to_global_id(3, 1); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let v5: DefaultId = LDBCVertexParser::to_global_id(5, 1); let mut expected_ids = vec![v2, v3, v3, v3, v4, v5]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_oute_with_label_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_edges = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let expected_edges = vec![(v1, v4), (v1, v2)]; while let Some(Ok(record)) = result.next() { if let Some(e) = record.get(None).unwrap().as_graph_edge() { result_edges.push((e.src_id as usize, e.dst_id as usize)); } } assert_eq!(result_edges, expected_edges) } #[test] fn expand_oute_with_many_labels_test() { let query_param = query_params(vec!["knows".into(), "created".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_edges = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v3: DefaultId = LDBCVertexParser::to_global_id(3, 1); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let v5: DefaultId = LDBCVertexParser::to_global_id(5, 1); let v6: DefaultId = LDBCVertexParser::to_global_id(6, 0); let mut expected_edges = vec![(v1, v2), (v1, v3), (v1, v4), (v4, v3), (v4, v5), (v6, v3)]; expected_edges.sort(); while let Some(Ok(record)) = result.next() { if let Some(e) = record.get(None).unwrap().as_graph_edge() { result_edges.push((e.src_id as usize, e.dst_id as usize)); } } result_edges.sort(); assert_eq!(result_edges, expected_edges) } #[test] fn expand_inv_with_label_property_test() { let query_param = query_params(vec!["knows".into()], vec!["name".into()], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 1, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_ids_with_prop = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let expected_ids_with_prop = vec![(v1, "marko".to_string().into()), (v1, "marko".to_string().into())]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids_with_prop.push(( element.id() as usize, element .details() .unwrap() .get_property(&"name".into()) .unwrap() .try_to_owned() .unwrap(), )) } } assert_eq!(result_ids_with_prop, expected_ids_with_prop) } #[test] fn expand_bothv_test() { let query_param = query_params(vec![], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 2, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut cnt = 0; let expected_result_num = 12; while let Some(_) = result.next() { cnt += 1; } assert_eq!(cnt, expected_result_num) } #[test] fn expand_outv_from_tag_as_tag_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: Some("a".into()), direction: 0, params: Some(query_param), is_edge: false, alias: Some("b".into()), }; let mut result = expand_test_with_source_tag("a".into(), expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let mut expected_ids = vec![v2, v4]; while let Some(Ok(record)) = result.next() { if let Some(element) = record .get(Some(&"b".into())) .unwrap() .as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_outv_from_select_tag_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let project = pb::Project { mappings: vec![pb::project::ExprAlias { expr: str_to_expr_pb("@a".to_string()).ok(), alias: None, }], is_append: false, }; let expand = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: false, alias: None, }; let conf = JobConf::new("expand_test"); let mut result = pegasus::run(conf, || { let project = project.clone(); let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(Some("a".into())))?; let map_func = project.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let mut expected_ids = vec![v2, v4]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_outv_filter_test() { let query_param = query_params(vec!["knows".into()], vec![], str_to_expr_pb("@.id == 2".to_string()).ok()); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let expected_ids = vec![v2]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } assert_eq!(result_ids, expected_ids) } #[test] fn expand_oute_inv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_params(vec!["knows".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 1, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_oute_inv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![2, 4]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_ine_outv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 1, params: Some(query_params(vec!["created".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 0, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_ine_outv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![1, 4, 4, 6]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_bothe_otherv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 2, params: Some(query_params(vec!["knows".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 2, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_bothe_otherv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![1, 1, 2, 4]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } }
mod common; #[cfg(test)] mod test { use std::sync::Arc; use graph_proxy::{create_demo_graph, SimplePartition}; use graph_store::ldbc::LDBCVertexParser; use graph_store::prelude::DefaultId; use ir_common::expr_parse::str_to_expr_pb; use ir_common::generated::algebra as pb; use ir_common::generated::common as common_pb; use pegasus::api::{Map, Sink}; use pegasus::result::ResultStream; use pegasus::JobConf; use runtime::graph::element::{Element, GraphElement}; use runtime::graph::property::Details; use runtime::process::operator::flatmap::FlatMapFuncGen; use runtime::process::operator::map::MapFuncGen; use runtime::process::operator::source::SourceOperator; use runtime::process::record::Record; use crate::common::test::*; fn source_gen(alias: Option<common_pb::NameOrId>) -> Box<dyn Iterator<Item = Record> + Send> { create_demo_graph(); let scan_opr_pb = pb::Scan { scan_opt: 0, alias, params: None, idx_predicate: None }; let mut source_opr_pb = pb::logical_plan::Operator { opr: Some(pb::logical_plan::operator::Opr::Scan(scan_opr_pb)) }; let source = SourceOperator::new(&mut source_opr_pb, 1, 1, Arc::new(SimplePartition { num_servers: 1 })) .unwrap(); source.gen_source(0).unwrap() } fn expand_test(expand: pb::EdgeExpand) -> ResultStream<Record> { let conf = JobConf::new("expand_test"); let result = pegasus::run(conf, || { let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); result } fn expand_test_with_source_tag( source_tag: common_pb::NameOrId, expand: pb::EdgeExpand, ) -> ResultStream<Record> { let conf = JobConf::new("expand_test"); let result = pegasus::run(conf, || { let source_tag = source_tag.clone(); let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(Some(source_tag)))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); result } #[test] fn expand_outv_test() { let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: None, is_edge: false, alias: None }; let mut result = expand_test(expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v3: DefaultId = LDBCVertexParser::to_global_id(3, 1); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let v5: DefaultId = LDBCVertexParser::to_global_id(5, 1); let mut expected_ids = vec![v2, v3, v3, v3, v4, v5]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test]
#[test] fn expand_oute_with_many_labels_test() { let query_param = query_params(vec!["knows".into(), "created".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_edges = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v3: DefaultId = LDBCVertexParser::to_global_id(3, 1); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let v5: DefaultId = LDBCVertexParser::to_global_id(5, 1); let v6: DefaultId = LDBCVertexParser::to_global_id(6, 0); let mut expected_edges = vec![(v1, v2), (v1, v3), (v1, v4), (v4, v3), (v4, v5), (v6, v3)]; expected_edges.sort(); while let Some(Ok(record)) = result.next() { if let Some(e) = record.get(None).unwrap().as_graph_edge() { result_edges.push((e.src_id as usize, e.dst_id as usize)); } } result_edges.sort(); assert_eq!(result_edges, expected_edges) } #[test] fn expand_inv_with_label_property_test() { let query_param = query_params(vec!["knows".into()], vec!["name".into()], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 1, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_ids_with_prop = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let expected_ids_with_prop = vec![(v1, "marko".to_string().into()), (v1, "marko".to_string().into())]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids_with_prop.push(( element.id() as usize, element .details() .unwrap() .get_property(&"name".into()) .unwrap() .try_to_owned() .unwrap(), )) } } assert_eq!(result_ids_with_prop, expected_ids_with_prop) } #[test] fn expand_bothv_test() { let query_param = query_params(vec![], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 2, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut cnt = 0; let expected_result_num = 12; while let Some(_) = result.next() { cnt += 1; } assert_eq!(cnt, expected_result_num) } #[test] fn expand_outv_from_tag_as_tag_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: Some("a".into()), direction: 0, params: Some(query_param), is_edge: false, alias: Some("b".into()), }; let mut result = expand_test_with_source_tag("a".into(), expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let mut expected_ids = vec![v2, v4]; while let Some(Ok(record)) = result.next() { if let Some(element) = record .get(Some(&"b".into())) .unwrap() .as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_outv_from_select_tag_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let project = pb::Project { mappings: vec![pb::project::ExprAlias { expr: str_to_expr_pb("@a".to_string()).ok(), alias: None, }], is_append: false, }; let expand = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: false, alias: None, }; let conf = JobConf::new("expand_test"); let mut result = pegasus::run(conf, || { let project = project.clone(); let expand = expand.clone(); |input, output| { let mut stream = input.input_from(source_gen(Some("a".into())))?; let map_func = project.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let mut expected_ids = vec![v2, v4]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } result_ids.sort(); expected_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_outv_filter_test() { let query_param = query_params(vec!["knows".into()], vec![], str_to_expr_pb("@.id == 2".to_string()).ok()); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: false, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_ids = vec![]; let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let expected_ids = vec![v2]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize) } } assert_eq!(result_ids, expected_ids) } #[test] fn expand_oute_inv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_params(vec!["knows".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 1, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_oute_inv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![2, 4]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_ine_outv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 1, params: Some(query_params(vec!["created".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 0, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_ine_outv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![1, 4, 4, 6]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } #[test] fn expand_bothe_otherv_test() { let expand_opr = pb::EdgeExpand { v_tag: None, direction: 2, params: Some(query_params(vec!["knows".into()], vec![], None)), is_edge: true, alias: None, }; let getv_opr = pb::GetV { tag: None, opt: 2, params: Some(query_params(vec![], vec![], None)), alias: None, }; let conf = JobConf::new("expand_bothe_otherv_test"); let mut result = pegasus::run(conf, || { let expand = expand_opr.clone(); let getv = getv_opr.clone(); |input, output| { let mut stream = input.input_from(source_gen(None))?; let flatmap_func = expand.gen_flat_map().unwrap(); stream = stream.flat_map(move |input| flatmap_func.exec(input))?; let map_func = getv.gen_map().unwrap(); stream = stream.map(move |input| map_func.exec(input))?; stream.sink_into(output) } }) .expect("build job failure"); let expected_ids = vec![1, 1, 2, 4]; let mut result_ids = vec![]; while let Some(Ok(record)) = result.next() { if let Some(element) = record.get(None).unwrap().as_graph_vertex() { result_ids.push(element.id() as usize); assert!(element .details() .unwrap() .get_property(&"name".into()) .is_none()) } } result_ids.sort(); assert_eq!(result_ids, expected_ids) } }
fn expand_oute_with_label_test() { let query_param = query_params(vec!["knows".into()], vec![], None); let expand_opr_pb = pb::EdgeExpand { v_tag: None, direction: 0, params: Some(query_param), is_edge: true, alias: None, }; let mut result = expand_test(expand_opr_pb); let mut result_edges = vec![]; let v1: DefaultId = LDBCVertexParser::to_global_id(1, 0); let v2: DefaultId = LDBCVertexParser::to_global_id(2, 0); let v4: DefaultId = LDBCVertexParser::to_global_id(4, 0); let expected_edges = vec![(v1, v4), (v1, v2)]; while let Some(Ok(record)) = result.next() { if let Some(e) = record.get(None).unwrap().as_graph_edge() { result_edges.push((e.src_id as usize, e.dst_id as usize)); } } assert_eq!(result_edges, expected_edges) }
function_block-full_function
[ { "content": "fn create_src(id: u32, source: &mut Source<i32>) -> Result<(Stream<i32>, Stream<i32>), BuildJobError> {\n\n let src1 = if id == 0 { source.input_from(1..5)? } else { source.input_from(8..10)? };\n\n let (src1, src2) = src1.copied()?;\n\n let src2 = src2.map(|x| Ok(x + 1))?;\n\n Ok((src1, src2))\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/tests/join_test.rs", "rank": 0, "score": 485664.3595615772 }, { "content": "pub fn run_opt<DI, DO, F>(conf: JobConf, sink: ResultSink<DO>, mut logic: F) -> Result<(), JobSubmitError>\n\nwhere\n\n DI: Data,\n\n DO: Debug + Send + 'static,\n\n F: FnMut(&mut Worker<DI, DO>) -> Result<(), BuildJobError>,\n\n{\n\n init_env();\n\n let peer_guard = Arc::new(AtomicUsize::new(0));\n\n let conf = Arc::new(conf);\n\n let workers = allocate_local_worker(&conf)?;\n\n if workers.is_none() {\n\n return Ok(());\n\n }\n\n let worker_ids = workers.unwrap();\n\n let mut workers = Vec::new();\n\n for id in worker_ids {\n\n let mut worker = Worker::new(&conf, id, &peer_guard, sink.clone());\n\n let _g = crate::worker_id::guard(worker.id);\n\n logic(&mut worker)?;\n\n workers.push(worker);\n", "file_path": "research/engine/pegasus/pegasus/src/lib.rs", "rank": 1, "score": 443198.6727531151 }, { "content": "fn idents_to_vars(idents: Vec<String>) -> ExprResult<pb::VariableKeys> {\n\n let mut vars = Vec::with_capacity(idents.len());\n\n for ident in idents {\n\n if !ident.starts_with(VAR_PREFIX) {\n\n return Err(format!(\"invalid variable token: {:?}, a variable must start with \\\"@\\\"\", ident)\n\n .as_str()\n\n .into());\n\n } else {\n\n let var: pb::Variable = ident.into();\n\n vars.push(var)\n\n }\n\n }\n\n\n\n Ok(pb::VariableKeys { keys: vars })\n\n}\n\n\n\nimpl TryFrom<Token> for pb::ExprOpr {\n\n type Error = ExprError;\n\n\n\n fn try_from(token: Token) -> ExprResult<Self> {\n", "file_path": "research/query_service/ir/common/src/expr_parse/mod.rs", "rank": 2, "score": 398139.4323448905 }, { "content": "fn parse_conf_req(mut req: pb::JobConfig) -> JobConf {\n\n let mut conf = JobConf::new(req.job_name);\n\n if req.job_id != 0 {\n\n conf.job_id = req.job_id;\n\n }\n\n\n\n if req.workers != 0 {\n\n conf.workers = req.workers;\n\n }\n\n\n\n if req.time_limit != 0 {\n\n conf.time_limit = req.time_limit;\n\n }\n\n\n\n if req.batch_size != 0 {\n\n conf.batch_size = req.batch_size;\n\n }\n\n\n\n if req.batch_capacity != 0 {\n\n conf.batch_capacity = req.batch_capacity;\n", "file_path": "research/engine/pegasus/server/src/rpc.rs", "rank": 3, "score": 393946.78933383914 }, { "content": "pub fn start_connection(self_index: usize, remote_addresses: Vec<(usize, String)>, mut retry_times: u64) -> ::std::io::Result<Vec<(usize, String, TcpStream)>> {\n\n let mut result = Vec::with_capacity(remote_addresses.len());\n\n\n\n for (remote_index, remote_address) in remote_addresses {\n\n if remote_address.is_empty() {\n\n continue;\n\n }\n\n assert!(self_index > remote_index);\n\n loop {\n\n match TcpStream::connect(remote_address.as_str()) {\n\n Ok(mut tcp_stream) => {\n\n tcp_stream.set_nodelay(true).map_err(|e| Error::new(e.kind(), format!(\"set_nodelay call failed, caused: {:?}\", e)))?;\n\n unsafe { abomonation::encode(&HANDSHAKE_MAGIC, &mut tcp_stream) }.map_err(|e| Error::new(e.kind(), format!(\"failed to encode/send handshake magic, caused: {:?}\", e)))?;\n\n unsafe { abomonation::encode(&(self_index as u64), &mut tcp_stream) }.map_err(|e| Error::new(e.kind(), format!(\"failed to encode/send worker index, caused: {:?}\", e)))?;\n\n println!(\"worker {} connect to worker {} success!!\", self_index, remote_index);\n\n result.push((remote_index, remote_address, tcp_stream));\n\n break;\n\n },\n\n Err(error) => {\n\n sleep(Duration::from_millis(CONNECTION_INTERVAL_TIME));\n", "file_path": "interactive_engine/executor/Pegasus/src/network.rs", "rank": 4, "score": 388924.1745378382 }, { "content": "#[inline]\n\nfn pass<D: Data>(input: &mut InputHandle<D>, output: &mut OutputHandle<D>) -> IOResult<()> {\n\n input.for_each_batch(|dataset| {\n\n output.session(&dataset).give_batch(dataset.data())?;\n\n Ok(true)\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "interactive_engine/executor/Pegasus/src/operator/advanced/scope.rs", "rank": 5, "score": 384787.6634192115 }, { "content": "pub fn run<DI, DO, F, FN>(conf: JobConf, func: F) -> Result<ResultStream<DO>, JobSubmitError>\n\nwhere\n\n DI: Data,\n\n DO: Debug + Send + 'static,\n\n F: Fn() -> FN,\n\n FN: FnOnce(&mut Source<DI>, ResultSink<DO>) -> Result<(), BuildJobError> + 'static,\n\n{\n\n let (tx, rx) = crossbeam_channel::unbounded();\n\n let sink = ResultSink::new(tx);\n\n let cancel_hook = sink.get_cancel_hook().clone();\n\n let results = ResultStream::new(conf.job_id, cancel_hook, rx);\n\n run_opt(conf, sink, |worker| worker.dataflow(func()))?;\n\n Ok(results)\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/src/lib.rs", "rank": 6, "score": 384467.97237980005 }, { "content": "pub fn await_connection(self_index: usize, tcp_listener: TcpListener, await_address: Vec<(usize, String)>, mut retry_times: u64) -> ::std::io::Result<Vec<(usize, String, TcpStream)>> {\n\n\n\n if cfg!(target_os = \"linux\") {\n\n tcp_listener.set_nonblocking(true).map_err(|e| Error::new(e.kind(), format!(\"Tcp listener cannot set non-blocking: {:?}\", e)))?;\n\n }\n\n\n\n let mut result = Vec::with_capacity(await_address.len());\n\n\n\n for _ in 0..await_address.len() {\n\n loop {\n\n match tcp_listener.accept() {\n\n Ok((mut tcp_stream, _socket_addr)) => {\n\n tcp_stream.set_nodelay(true).map_err(|e| Error::new(e.kind(), format!(\"Stream set_nodelay call failed, caused: {:?}\", e)))?;\n\n let mut buffer = [0u8; 16];\n\n tcp_stream.read_exact(&mut buffer).map_err(|e| Error::new(e.kind(), format!(\"failed to read worker index, caused: {:?}\", e)))?;\n\n let (magic, mut buffer) = unsafe { abomonation::decode::<u64>(&mut buffer) }.expect(\"failed to decode magic\");\n\n if magic != &HANDSHAKE_MAGIC {\n\n let error = ::std::io::Error::new(::std::io::ErrorKind::InvalidData, \"received incorrect timely handshake\");\n\n eprintln!(\"Worker {}: connected from other workers failed, caused by {}.\", self_index, error);\n\n continue;\n", "file_path": "interactive_engine/executor/Pegasus/src/network.rs", "rank": 7, "score": 371650.94511529163 }, { "content": "#[inline]\n\nfn execute_local(mut task: GenericTask, fired: &mut Vec<Operator>) -> Result<(), ExecError> {\n\n task.execute()?;\n\n if let Some(task) = check_task_finish(task) {\n\n fired.push(task);\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "interactive_engine/executor/Pegasus/src/schedule/mod.rs", "rank": 8, "score": 370798.82389308605 }, { "content": "fn has_any<T: Data>(mut stream: Stream<T>) -> Result<SingleItem<bool>, BuildJobError> {\n\n stream\n\n .set_upstream_batch_capacity(1)\n\n .set_upstream_batch_size(1);\n\n let x = stream.unary(\"any_global\", |info| {\n\n let mut any_map = TidyTagMap::<()>::new(info.scope_level);\n\n move |input, output| {\n\n input.for_each_batch(|batch| {\n\n if !batch.is_empty() {\n\n if !any_map.contains_key(batch.tag()) {\n\n any_map.insert(batch.tag().clone(), ());\n\n output\n\n .new_session(batch.tag())?\n\n .give(Single(true))?;\n\n }\n\n batch.clear();\n\n\n\n if batch.is_last() {\n\n any_map.remove(batch.tag());\n\n }\n", "file_path": "research/engine/pegasus/pegasus/src/operator/concise/any.rs", "rank": 9, "score": 365949.59686068876 }, { "content": "#[inline]\n\npub fn retain<T, F: Fn(&T) -> bool>(origin: &mut Vec<T>, predicate: F) -> Vec<T> {\n\n let mut target = Vec::new();\n\n let mut index = origin.len();\n\n while index > 0 {\n\n if !predicate(&origin[index - 1]) {\n\n let item = if index == origin.len() {\n\n origin.remove(index - 1)\n\n } else {\n\n origin.swap_remove(index - 1)\n\n };\n\n target.push(item);\n\n }\n\n index -= 1;\n\n }\n\n target\n\n}\n\n\n\n#[derive(Copy, Clone, Hash, Eq, PartialEq)]\n\npub struct Port {\n\n pub index: usize,\n", "file_path": "interactive_engine/executor/Pegasus/src/common/mod.rs", "rank": 10, "score": 357285.76656940277 }, { "content": "fn parse_conf_req(conf: pb::JobConfig) -> JobConf {\n\n let mut job_conf = JobConf::with_id(conf.job_id, conf.job_name, conf.workers);\n\n if conf.time_limit != 0 {\n\n job_conf.time_limit = conf.time_limit;\n\n }\n\n if conf.batch_size != 0 {\n\n job_conf.batch_size = conf.batch_size;\n\n }\n\n if conf.output_capacity != 0 {\n\n job_conf.batch_capacity = conf.output_capacity;\n\n }\n\n if conf.memory_limit != 0 {\n\n job_conf.memory_limit = conf.memory_limit;\n\n }\n\n job_conf.plan_print = conf.plan_print;\n\n if !conf.servers.is_empty() {\n\n job_conf.reset_servers(ServerConf::Partial(conf.servers.clone()));\n\n }\n\n job_conf\n\n}\n", "file_path": "research/engine/pegasus/server-v0/src/rpc.rs", "rank": 11, "score": 350907.8457756598 }, { "content": "fn mock_process_2(servers: Vec<Server>, conf: ConnectionParams) -> std::thread::JoinHandle<()> {\n\n std::thread::Builder::new()\n\n .name(\"process-2\".to_owned())\n\n .spawn(move || {\n\n let detector = MockServerDetect { servers };\n\n let addr = pegasus_network::start_up(2, conf, \"127.0.0.1:1236\", detector).unwrap();\n\n info!(\"server 2 start at {:?}\", addr);\n\n let remotes = vec![0, 1];\n\n while !pegasus_network::check_connect(2, &remotes) {\n\n std::thread::sleep(Duration::from_secs(1));\n\n }\n\n let ipc_ch = pegasus_network::ipc_channel::<Entry>(1, 2, &remotes).unwrap();\n\n let (mut sends, recv) = ipc_ch.take();\n\n let entry = Entry::new(2);\n\n sends[0].send(&entry).unwrap();\n\n sends[1].send(&entry).unwrap();\n\n sends[0].close().unwrap();\n\n sends[1].close().unwrap();\n\n let mut receives = vec![];\n\n loop {\n", "file_path": "research/engine/pegasus/network/tests/ipc_test.rs", "rank": 12, "score": 348748.83034835244 }, { "content": "fn mock_process_0(servers: Vec<Server>, conf: ConnectionParams) -> std::thread::JoinHandle<()> {\n\n std::thread::Builder::new()\n\n .name(\"process-0\".to_owned())\n\n .spawn(move || {\n\n let detector = MockServerDetect { servers };\n\n let addr = pegasus_network::start_up(0, conf, \"127.0.0.1:1234\", detector).unwrap();\n\n info!(\"server 0 start at {:?}\", addr);\n\n let remotes = vec![1, 2];\n\n while !pegasus_network::check_connect(0, &remotes) {\n\n std::thread::sleep(Duration::from_secs(1));\n\n }\n\n\n\n let ipc_ch = pegasus_network::ipc_channel::<Entry>(1, 0, &remotes).unwrap();\n\n let (mut sends, recv) = ipc_ch.take();\n\n let entry = Entry::new(0);\n\n sends[0].send(&entry).unwrap();\n\n sends[1].send(&entry).unwrap();\n\n sends[0].close().unwrap();\n\n sends[1].close().unwrap();\n\n let mut receives = vec![];\n", "file_path": "research/engine/pegasus/network/tests/ipc_test.rs", "rank": 13, "score": 348748.83034835244 }, { "content": "fn mock_process_1(servers: Vec<Server>, conf: ConnectionParams) -> std::thread::JoinHandle<()> {\n\n std::thread::Builder::new()\n\n .name(\"process-1\".to_owned())\n\n .spawn(move || {\n\n let detector = MockServerDetect { servers };\n\n let addr = pegasus_network::start_up(1, conf, \"127.0.0.1:1235\", detector).unwrap();\n\n info!(\"server 1 start at {:?}\", addr);\n\n let remotes = vec![0, 2];\n\n\n\n while !pegasus_network::check_connect(1, &remotes) {\n\n std::thread::sleep(Duration::from_secs(1));\n\n }\n\n\n\n let ipc_ch = pegasus_network::ipc_channel::<Entry>(1, 1, &remotes).unwrap();\n\n let (mut sends, recv) = ipc_ch.take();\n\n let entry = Entry::new(1);\n\n sends[0].send(&entry).unwrap();\n\n sends[1].send(&entry).unwrap();\n\n sends[0].close().unwrap();\n\n sends[1].close().unwrap();\n", "file_path": "research/engine/pegasus/network/tests/ipc_test.rs", "rank": 14, "score": 348748.83034835244 }, { "content": "fn ipc_with_conf(conf: ConnectionParams) {\n\n pegasus_common::logs::init_log();\n\n let mut servers = vec![];\n\n servers.push(Server { id: 0, addr: \"127.0.0.1:1234\".parse().unwrap() });\n\n servers.push(Server { id: 1, addr: \"127.0.0.1:1235\".parse().unwrap() });\n\n servers.push(Server { id: 2, addr: \"127.0.0.1:1236\".parse().unwrap() });\n\n let g1 = mock_process_0(servers.clone(), conf);\n\n let g2 = mock_process_1(servers.clone(), conf);\n\n let g3 = mock_process_2(servers, conf);\n\n g1.join().unwrap();\n\n g2.join().unwrap();\n\n g3.join().unwrap();\n\n}\n\n\n", "file_path": "research/engine/pegasus/network/tests/ipc_test.rs", "rank": 15, "score": 343749.87768244895 }, { "content": "/// Resolves all partial tokens by converting them to complex tokens.\n\nfn partial_tokens_to_tokens(mut tokens: &[PartialToken]) -> ExprResult<Vec<Token>> {\n\n let mut result = Vec::new();\n\n let mut recent_token: Option<Token> = None;\n\n while !tokens.is_empty() {\n\n let first = tokens[0].clone();\n\n let second = tokens.get(1).cloned();\n\n let third = tokens.get(2).cloned();\n\n let mut cutoff = 2;\n\n\n\n let curr_token = match first {\n\n PartialToken::Token(token) => {\n\n cutoff = 1;\n\n Some(token)\n\n }\n\n PartialToken::Literal(literal) => {\n\n cutoff = 1;\n\n if let Ok(number) = literal.parse::<i64>() {\n\n Some(Token::Int(number))\n\n } else if let Ok(number) = literal.parse::<f64>() {\n\n Some(Token::Float(number))\n", "file_path": "research/query_service/ir/common/src/expr_parse/token.rs", "rank": 16, "score": 338522.2320793204 }, { "content": "pub fn str_to_expr_pb(expr_str: String) -> ExprResult<pb::Expression> {\n\n let mut operators = vec![];\n\n for token in tokenize(&expr_str)? {\n\n operators.push(token.try_into()?);\n\n }\n\n\n\n Ok(pb::Expression { operators })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::expr_parse::token::tokenize;\n\n\n\n #[test]\n\n fn test_to_suffix_expr() {\n\n // 1 + 2\n\n let case1 = tokenize(\"1 + 2\").unwrap();\n\n let expected_case1 = vec![Token::Int(1), Token::Int(2), Token::Plus];\n\n assert_eq!(to_suffix_expr(case1).unwrap(), expected_case1);\n", "file_path": "research/query_service/ir/common/src/expr_parse/mod.rs", "rank": 17, "score": 333783.3741482586 }, { "content": "pub fn reconnect(self_index: usize, listener: TcpListener, start_addresses: Vec<(usize, String)>, await_address: Vec<(usize, String)>, retry_times: u64) -> ::std::io::Result<Vec<(usize, String, TcpStream)>> {\n\n let start_task = thread::spawn(move || start_connection(self_index, start_addresses, retry_times));\n\n let await_task = thread::spawn(move || await_connection(self_index, listener, await_address, retry_times));\n\n\n\n let mut result = vec![];\n\n match start_task.join() {\n\n Ok(Ok(sub_result)) => result.extend(sub_result.into_iter()),\n\n Ok(Err(e)) => return Err(e),\n\n Err(_e) => return Err(Error::new(ErrorKind::Other, \"Join start connection failed. \")),\n\n };\n\n\n\n match await_task.join() {\n\n Ok(Ok(sub_result)) => result.extend(sub_result.into_iter()),\n\n Ok(Err(e)) => return Err(e),\n\n Err(_e) => return Err(Error::new(ErrorKind::Other, \"Join await connection failed. \")),\n\n };\n\n\n\n return Ok(result);\n\n}\n\n\n\n\n", "file_path": "interactive_engine/executor/Pegasus/src/network.rs", "rank": 18, "score": 327334.1165059243 }, { "content": "fn iterate<D, F>(stream: Stream<D>, until: IterCondition<D>, emit_kind: Option<EmitKind>, func: F) -> Result<Stream<D>, BuildJobError>\n\n where\n\n D: Data,\n\n F: FnOnce(Stream<D>) -> Result<Stream<D>, BuildJobError>,\n\n{\n\n let max_iters = until.max_iters;\n\n let (leave, enter) = stream\n\n .enter()?\n\n .binary_branch_notify(\"switch\", |info| SwitchOperator::<D>::new(info.scope_level, emit_kind, until))?;\n\n let index = enter.get_upstream_port().index;\n\n let after_body = func(enter)?;\n\n let feedback: Stream<D> = after_body\n\n .sync_state()\n\n .transform_notify(\"feedback\", move |info| {\n\n FeedbackOperator::<D>::new(info.scope_level, max_iters)\n\n })?;\n\n feedback.feedback_to(index)?;\n\n leave.leave()\n\n}\n\n\n\nimpl<D: 'static + Send> IterCondition<D> {\n\n pub fn until<F>(&mut self, func: F)\n\n where\n\n F: Fn(&D) -> FnResult<bool> + Send + 'static,\n\n {\n\n self.set_until(Box::new(filter!(func)));\n\n }\n\n}\n", "file_path": "research/engine/pegasus/pegasus/src/operator/iteration/mod.rs", "rank": 19, "score": 315964.948896315 }, { "content": "/// Turn a sequence of tokens with bracket, into a suffix order\n\npub fn to_suffix_expr<E: ExprToken + std::fmt::Debug>(expr: Vec<E>) -> ExprResult<Vec<E>> {\n\n let mut stack: Vec<E> = Vec::with_capacity(expr.len());\n\n let mut results: Vec<E> = Vec::with_capacity(expr.len());\n\n\n\n for token in expr {\n\n if token.is_operand() {\n\n results.push(token);\n\n } else if token.is_left_brace() {\n\n stack.push(token);\n\n } else if token.is_right_brace() {\n\n let mut is_left_brace = false;\n\n while !stack.is_empty() {\n\n let recent = stack.pop().unwrap();\n\n if recent.is_left_brace() {\n\n is_left_brace = true;\n\n break;\n\n } else {\n\n results.push(recent);\n\n }\n\n }\n", "file_path": "research/query_service/ir/common/src/expr_parse/mod.rs", "rank": 20, "score": 312002.37961996836 }, { "content": "#[inline]\n\nfn allocate_local_worker(conf: &Arc<JobConf>) -> Result<Option<WorkerIdIter>, BuildJobError> {\n\n let server_conf = conf.servers();\n\n let servers = match server_conf {\n\n ServerConf::Local => {\n\n return Ok(Some(WorkerIdIter::new(conf.job_id, conf.workers, 0, 0, 1)));\n\n }\n\n ServerConf::Partial(ids) => ids.clone(),\n\n ServerConf::All => get_servers(),\n\n };\n\n\n\n if servers.is_empty() || (servers.len() == 1) {\n\n Ok(Some(WorkerIdIter::new(conf.job_id, conf.workers, 0, 0, 1)))\n\n } else {\n\n if let Some(my_id) = server_id() {\n\n let mut my_index = -1;\n\n for (index, id) in servers.iter().enumerate() {\n\n if *id == my_id {\n\n my_index = index as i64;\n\n }\n\n }\n", "file_path": "research/engine/pegasus/pegasus/src/lib.rs", "rank": 21, "score": 309341.1229826325 }, { "content": "#[bench]\n\nfn read_vec_deque(b: &mut Bencher) {\n\n let mut queue = VecDeque::new();\n\n //let item = \"bench\".to_owned();\n\n for _ in 0..572726701 {\n\n queue.push_back(FlatPtr(!0, 65536));\n\n }\n\n\n\n b.iter(|| queue.pop_front());\n\n println!(\"after read queue.size {}\", queue.len());\n\n}\n\n\n", "file_path": "research/engine/pegasus/common/benches/queue.rs", "rank": 22, "score": 309122.0848773413 }, { "content": "#[bench]\n\nfn write_vec_deque(b: &mut Bencher) {\n\n let mut queue = VecDeque::new();\n\n b.iter(|| queue.push_back(FlatPtr(!0, 65536)));\n\n println!(\"after write queue.size {}\", queue.len());\n\n}\n\n\n", "file_path": "research/engine/pegasus/common/benches/queue.rs", "rank": 23, "score": 309122.0848773413 }, { "content": "#[test]\n\nfn test_vertex_direct_result_iterator() {\n\n\n\n}\n", "file_path": "interactive_engine/executor/runtime/src/dataflow/test/iterator_test.rs", "rank": 24, "score": 308112.81164794473 }, { "content": "fn common_parse_key<'a>(k: &'a [u8], prefix: &str, size: usize) -> GraphResult<Vec<&'a str>> {\n\n if transform::bytes_to_i64(&k[0..8])?.to_be() != META_TABLE_ID {\n\n let msg = format!(\"invalid meta key\");\n\n let err = gen_graph_err!(GraphErrorCode::InvalidData, msg, common_parse_key, k, prefix, size);\n\n return Err(err);\n\n }\n\n let key = res_unwrap!(transform::bytes_to_str(&k[8..]), common_parse_key, k, prefix, size)?;\n\n let items: Vec<&str> = key.split(\"#\").collect();\n\n if key.starts_with(prefix) && items.len() == size {\n\n return Ok(items);\n\n }\n\n let msg = format!(\"invalid key {}\", key);\n\n let err = gen_graph_err!(GraphErrorCode::InvalidData, msg, common_parse_key, k, prefix, size);\n\n Err(err)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/graph/meta.rs", "rank": 25, "score": 302282.09294253483 }, { "content": "pub fn assign_empty_partition(partition_id_list: &Vec<u32>, partition_vertex_list: &mut Vec<(u32, Vec<i64>)>) {\n\n partition_vertex_list.clear();\n\n for partition_id in partition_id_list.iter() {\n\n partition_vertex_list.push((*partition_id, vec![]));\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/src/util/partition.rs", "rank": 26, "score": 300667.89932047715 }, { "content": "/// Each serving consists of a tuple, where tuple.0 indicates the player id,\n\n/// and tuple.1 indicates the ball that it is serving. The game continues\n\n/// until any player hits a LOSS ball, or it exceeds a random `max_iters`.\n\nfn single_play(serving: Stream<(u32, u32)>) -> Result<Stream<(u32, u32)>, BuildJobError> {\n\n let max_iters = 30;\n\n let mut until = IterCondition::<(u32, u32)>::max_iters(max_iters);\n\n until.until(move |(_player, ball)| Ok(*ball == LOSS));\n\n\n\n serving.iterate_until(until, |start| {\n\n start\n\n // Hit the ball to the opponent side, aka, 0 -> 1, 1 -> 0\n\n .repartition(|(player, _ball)| Ok((*player ^ 1) as u64))\n\n .map(|(player, ball)| {\n\n // The larger ball is, the easier it is to hit the ball back, which means\n\n // the less possible for the other player to loss (hit a zero number)\n\n let new_ball = thread_rng().gen_range(LOSS..ball);\n\n println!(\"Player {:?} hits a new ball {:?}\", player ^ 1, new_ball);\n\n Ok((player ^ 1, new_ball))\n\n })\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/examples/ping_pong.rs", "rank": 27, "score": 299044.22528488154 }, { "content": "pub fn assign_all_partition(vid: i64, partition_vertex_list: &mut Vec<(u32, Vec<i64>)>) {\n\n for (_, vidlist) in partition_vertex_list.iter_mut() {\n\n if !vidlist.contains(&vid) {\n\n vidlist.push(vid);\n\n }\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/src/util/partition.rs", "rank": 28, "score": 298496.33855409734 }, { "content": "fn exec_projector(input: &Record, projector: &Projector) -> FnResult<Arc<Entry>> {\n\n let entry = match projector {\n\n Projector::ExprProjector(evaluator) => {\n\n let projected_result = evaluator\n\n .eval::<RecordElement, Record>(Some(&input))\n\n .map_err(|e| FnExecError::from(e))?;\n\n Arc::new(\n\n match projected_result {\n\n Object::None => CommonObject::None,\n\n _ => CommonObject::Prop(projected_result),\n\n }\n\n .into(),\n\n )\n\n }\n\n Projector::GraphElementProjector(tag_key) => tag_key.get_arc_entry(input)?,\n\n };\n\n Ok(entry)\n\n}\n\n\n\nimpl MapFunction<Record, Record> for ProjectOperator {\n", "file_path": "research/query_service/ir/runtime/src/process/operator/map/project.rs", "rank": 29, "score": 295358.1626498811 }, { "content": "fn detect_filters(params_opt: Option<&pb::QueryParams>) -> usize {\n\n if let Some(params) = params_opt {\n\n let mut count = 0;\n\n // Simply count whether there is any predicate, without actually looking into\n\n // the number of filter clauses\n\n if params.predicate.is_some() {\n\n count += 1;\n\n }\n\n // Simply count whether there is any column (for filtering)\n\n if !params.columns.is_empty() {\n\n count += 1;\n\n }\n\n count\n\n } else {\n\n 0\n\n }\n\n}\n\n\n\nimpl MatchingStrategy for JoinSentence {\n\n fn build_logical_plan(&self) -> IrResult<pb::LogicalPlan> {\n", "file_path": "research/query_service/ir/core/src/plan/patmat.rs", "rank": 30, "score": 292885.4092166168 }, { "content": "// g.V(5).in().out().hasId(5).in()\n\nfn modern_graph_filter_flatmap_test() -> ResultStream<u32> {\n\n let mut conf = JobConf::default();\n\n let num_workers = 2;\n\n conf.set_workers(num_workers);\n\n let result_stream = pegasus::run(conf, || {\n\n let src = if pegasus::get_current_worker().index == 0 { vec![] } else { vec![5] };\n\n move |input, output| {\n\n input\n\n .input_from(src)?\n\n .repartition(|x| Ok(*x as u64))\n\n .flat_map(move |x| Ok(MAP.get(&x).unwrap().1.iter().cloned()))?\n\n .repartition(|x| Ok(*x as u64))\n\n .flat_map(move |x| Ok(MAP.get(&x).unwrap().0.iter().cloned()))?\n\n .repartition(|x| Ok(*x as u64))\n\n .filter(|x| Ok(*x == 5))?\n\n .repartition(|x| Ok(*x as u64))\n\n .flat_map(|x| Ok(MAP.get(&x).unwrap().1.iter().cloned()))?\n\n .sink_into(output)\n\n }\n\n })\n\n .expect(\"submit job failure\");\n\n result_stream\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/tests/filter_test.rs", "rank": 31, "score": 291780.9296679882 }, { "content": "#[inline]\n\nfn try_read<R: io::Read>(reader: &mut R, bytes: &mut [u8]) -> io::Result<usize> {\n\n loop {\n\n match reader.read(bytes) {\n\n Ok(size) => return Ok(size),\n\n Err(err) => match err.kind() {\n\n io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => return Ok(0),\n\n io::ErrorKind::Interrupted => (),\n\n _ => return Err(err),\n\n },\n\n }\n\n }\n\n}\n\n\n\n#[enum_dispatch(MessageDecoder)]\n\npub enum GeneralDecoder {\n\n Simple(SimpleBlockDecoder),\n\n Reentrant(ReentrantDecoder),\n\n ReentrantSlab(ReentrantSlabDecoder),\n\n}\n\n\n", "file_path": "research/engine/pegasus/network/src/receive/decode.rs", "rank": 32, "score": 285878.8529960851 }, { "content": "fn parse_path_list_proto(path_list_proto: &mut RepeatedField<PathEntityListProto>) -> Option<Vec<Vec<ExtraPathEntity>>> {\n\n let path_list = vec![];\n\n for path_proto_list in path_list_proto.iter_mut() {\n\n let mut path_value_list = vec![];\n\n for path_proto in path_proto_list.mut_path_val_list().iter_mut() {\n\n let message = RawMessage::from_proto(path_proto.mut_message());\n\n let label_list = {\n\n let curr_label_list = path_proto.take_label_list();\n\n if curr_label_list.is_empty() {\n\n None\n\n } else {\n\n Some(curr_label_list)\n\n }\n\n };\n\n path_value_list.push(ExtraPathEntity {\n\n label_list,\n\n message,\n\n });\n\n }\n\n }\n\n if path_list.is_empty() {\n\n return None;\n\n }\n\n\n\n return Some(path_list);\n\n}\n\n\n", "file_path": "interactive_engine/executor/runtime/src/dataflow/message/mod.rs", "rank": 33, "score": 282190.0895702027 }, { "content": "fn add_path_list_bulk(path_list: &mut Vec<Vec<ExtraPathEntity>>, path_entity: ExtraPathEntity, bulk: i64) {\n\n if bulk > 0 {\n\n let to_build_count = bulk - path_list.len() as i64;\n\n for _ in 0..to_build_count {\n\n path_list.push(vec![]);\n\n }\n\n for i in 0..bulk - 1 {\n\n path_list.get_mut(i as usize).unwrap().push(path_entity.clone());\n\n }\n\n path_list.get_mut((bulk - 1) as usize).unwrap().push(path_entity);\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/executor/runtime/src/dataflow/message/mod.rs", "rank": 34, "score": 280211.2311859154 }, { "content": "pub fn assign_single_partition(vid: i64, partition_id: u32, partition_vertex_list: &mut Vec<(u32, Vec<i64>)>) {\n\n for (curr_partition_id, vid_list) in partition_vertex_list.iter_mut() {\n\n if *curr_partition_id == partition_id {\n\n if !vid_list.contains(&vid) {\n\n vid_list.push(vid);\n\n }\n\n return;\n\n }\n\n }\n\n\n\n partition_vertex_list.push((partition_id, vec![vid]));\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/src/util/partition.rs", "rank": 35, "score": 280124.4421857857 }, { "content": "#[inline]\n\npub fn file_size(path: &str) -> Result<usize, String> {\n\n fs::metadata(path).map(|meta| {\n\n meta.len() as usize\n\n }).map_err(|e| format!(\"get metadata of {} failed, {:?}\", path, e))\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/src/util/fs.rs", "rank": 36, "score": 278404.87857223896 }, { "content": "#[inline]\n\nfn input_batch_level_to_num(level: &InputBatchLevel) -> usize {\n\n match level {\n\n InputBatchLevel::VerySmall => 4,\n\n InputBatchLevel::Small => 16,\n\n InputBatchLevel::Medium => 64,\n\n InputBatchLevel::Large => 256,\n\n InputBatchLevel::VeryLarge => 1024,\n\n }\n\n}\n\n\n\n\n", "file_path": "interactive_engine/executor/runtime/src/rpc/mod.rs", "rank": 37, "score": 278219.64666461496 }, { "content": "#[inline]\n\nfn read_dump<T: Copy, R: Read>(reader: &mut R) -> std::io::Result<Vec<T>> {\n\n let size = reader.read_u64::<LittleEndian>()? as usize;\n\n if size > 0 {\n\n let mut buf = vec![0u8; size];\n\n reader.read_exact(&mut buf)?;\n\n let list = unsafe {\n\n let ptr = buf.as_ptr() as *mut T;\n\n let length = size / std::mem::size_of::<T>();\n\n Vec::from_raw_parts(ptr, length, length)\n\n };\n\n std::mem::forget(buf);\n\n Ok(list)\n\n } else {\n\n Ok(vec![])\n\n }\n\n}\n\n\n\npub struct NeighborsBackend {\n\n mmap: Mmap,\n\n len: usize,\n", "file_path": "research/engine/pegasus/graph/src/lib.rs", "rank": 38, "score": 275453.72922577197 }, { "content": "pub fn ls<P: AsRef<Path>>(path: P) -> Result<Vec<String>, String> {\n\n let mut ret = Vec::new();\n\n let paths = fs::read_dir(path).map_err(|e| format!(\"{:?}\", e))?;\n\n for path in paths {\n\n let path_buf = path.map_err(|e| format!(\"{:?}\", e))?.path();\n\n let filename = path_buf.to_str().ok_or_else(|| format!(\"error\"))?.to_owned();\n\n ret.push(filename);\n\n }\n\n Ok(ret)\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/src/util/fs.rs", "rank": 39, "score": 272718.42363924184 }, { "content": "#[inline]\n\nfn dump<T: Copy, W: Write>(writer: &mut W, list: &Vec<T>) -> std::io::Result<()> {\n\n let len = list.len();\n\n let buf = unsafe {\n\n let ptr = list.as_ptr() as *const u8;\n\n let size = len * std::mem::size_of::<T>();\n\n std::slice::from_raw_parts(ptr, size)\n\n };\n\n writer.write_u64::<LittleEndian>(buf.len() as u64)?;\n\n writer.write_all(buf)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "research/engine/pegasus/graph/src/lib.rs", "rank": 40, "score": 272398.0609232101 }, { "content": "pub fn tokenize(string: &str) -> ExprResult<Vec<Token>> {\n\n partial_tokens_to_tokens(&str_to_partial_tokens(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_tokenize() {\n\n // ((1 + 2) * 2) ^ 3 == 6 ^ 3\n\n let case1 = tokenize(\"((1 + 1e-3) * 2) ^ 3 == 6 ^ 3\").unwrap();\n\n let expected_case1 = vec![\n\n Token::LBrace,\n\n Token::LBrace,\n\n Token::Int(1),\n\n Token::Plus,\n\n Token::Float(0.001),\n\n Token::RBrace,\n\n Token::Star,\n", "file_path": "research/query_service/ir/common/src/expr_parse/token.rs", "rank": 41, "score": 271584.83497623965 }, { "content": "pub fn read_id<R: ReadExt>(reader: &mut R) -> io::Result<ID> {\n\n reader.read_u64()\n\n}\n\n\n", "file_path": "research/query_service/ir/runtime/src/graph/mod.rs", "rank": 42, "score": 270330.95939086966 }, { "content": "#[inline]\n\nfn read_string<R: Read>(reader: &mut R) -> std::io::Result<String> {\n\n let len = read_var_uint(reader)?;\n\n if len as usize > MAX_STRING_SIZE {\n\n panic!(\"string too large\");\n\n }\n\n let mut buf = Vec::with_capacity(len as usize);\n\n unsafe { buf.set_len(len as usize) };\n\n\n\n reader.read_exact(&mut buf[..])?;\n\n\n\n Ok(String::from_utf8(buf).unwrap())\n\n}\n", "file_path": "research/engine/pegasus/benchmark/src/graph/storage/clickhouse/mod.rs", "rank": 43, "score": 270330.95939086966 }, { "content": "/// Converts a string to a vector of partial tokens.\n\nfn str_to_partial_tokens(string: &str) -> ExprResult<Vec<PartialToken>> {\n\n let mut result = Vec::new();\n\n let mut iter = string.chars().peekable();\n\n while let Some(c) = iter.next() {\n\n if c == '\"' {\n\n result.push(parse_string_literal(&mut iter, false)?);\n\n } else if c == '[' {\n\n result.push(PartialToken::LBracket);\n\n result.push(parse_string_literal(&mut iter, true)?);\n\n // must have right bracket to escape from `parse_string_literal()`\n\n result.push(PartialToken::RBracket);\n\n } else if c == '{' {\n\n result.push(PartialToken::LCBracket);\n\n result.push(parse_string_literal(&mut iter, true)?);\n\n // must have right bracket to escape from `parse_string_literal()`\n\n result.push(PartialToken::RCBracket);\n\n } else {\n\n let partial_token = char_to_partial_token(c);\n\n\n\n let if_let_successful =\n", "file_path": "research/query_service/ir/common/src/expr_parse/token.rs", "rank": 44, "score": 269392.35434648977 }, { "content": "fn token_array_to_token(token_array: Vec<Token>) -> ExprResult<Token> {\n\n if token_array.is_empty() {\n\n Ok(Token::IdentArray(vec![]))\n\n } else {\n\n // use pivot to regulate the type of all elements\n\n let pivot = token_array.first().unwrap();\n\n match pivot {\n\n Token::Int(_) => {\n\n let mut vec = Vec::with_capacity(token_array.len());\n\n for t in token_array {\n\n match t {\n\n Token::Int(i) => vec.push(i),\n\n _ => {\n\n return Err(ExprError::unsupported(\n\n \"array of various type unsupported\".to_string(),\n\n ))\n\n }\n\n }\n\n }\n\n Ok(Token::IntArray(vec))\n", "file_path": "research/query_service/ir/common/src/expr_parse/token.rs", "rank": 45, "score": 269392.35434648977 }, { "content": "#[inline]\n\npub fn check_has_network_error(ch_id: u128) -> Option<Vec<SocketAddr>> {\n\n if let Ok(ref mut lock) = NETWORK_SEND_ERRORS.try_lock() {\n\n lock.remove(&ch_id)\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "research/engine/pegasus/network/src/send/mod.rs", "rank": 46, "score": 268917.74657656497 }, { "content": "#[inline]\n\nfn read_var_uint<R: Read>(reader: &mut R) -> std::io::Result<u64> {\n\n let mut out = 0u64;\n\n for i in 0..9u64 {\n\n let mut octet = [0u8];\n\n reader.read_exact(&mut octet[..])?;\n\n out |= ((octet[0] & 0x7F) as u64) << (7 * i);\n\n if (octet[0] & 0x80) == 0 {\n\n break;\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n\npub const MAX_STRING_SIZE: usize = 1 << 30;\n\n\n", "file_path": "research/engine/pegasus/benchmark/src/graph/storage/clickhouse/mod.rs", "rank": 47, "score": 267335.0544254579 }, { "content": "#[inline]\n\nfn send_request<W: Write>(req: Bytes, writes: &mut [W]) -> Result<(), io::Error> {\n\n // TODO : If some send success, some send failure, send cancel to successes as rollback;\n\n for write in writes {\n\n loop {\n\n match write.write_all(&req) {\n\n Ok(_) => break,\n\n Err(ref e) if e.kind() == io::ErrorKind::Interrupted\n\n || e.kind() == io::ErrorKind::WouldBlock => continue,\n\n Err(e) => return Err(e)\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n\npub type ClientResponseReader<R> = BinaryReader<TaskResponseHeader, R>;\n\n\n", "file_path": "interactive_engine/executor/Pegasus/src/server/clients/client.rs", "rank": 48, "score": 267106.9386852843 }, { "content": "#[derive(Copy,Clone)]\n\nstruct Slice(pub *mut u8, pub usize);\n\n\n\nimpl Slice {\n\n pub fn as_slice(&self) -> &[u8] {\n\n unsafe {\n\n ::std::slice::from_raw_parts(self.0, self.1)\n\n }\n\n }\n\n\n\n pub fn as_mut_slice(&mut self) -> &mut [u8] {\n\n unsafe {\n\n ::std::slice::from_raw_parts_mut(self.0, self.1)\n\n }\n\n }\n\n}\n\n\n\npub struct Bytes {\n\n slice: Slice,\n\n backend: Arc<Box<dyn Any>>\n\n}\n", "file_path": "interactive_engine/executor/Pegasus/src/common/mod.rs", "rank": 49, "score": 266601.23688896175 }, { "content": "#[bench]\n\nfn bench_and(b: &mut test::Bencher) {\n\n let p = 3u32;\n\n let mut x = 0;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n x += i & p;\n\n }\n\n });\n\n println!(\"{}\", x);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 50, "score": 265538.7502456837 }, { "content": "pub fn write_id<W: WriteExt>(writer: &mut W, id: ID) -> io::Result<()> {\n\n writer.write_u64(id)\n\n}\n\n\n\n/// The number of bits in an `ID`\n\npub const ID_BITS: usize = std::mem::size_of::<ID>() * 8;\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug)]\n\npub enum Direction {\n\n Out = 0,\n\n In = 1,\n\n Both = 2,\n\n}\n\n\n\nimpl From<algebra_pb::edge_expand::Direction> for Direction {\n\n fn from(direction: algebra_pb::edge_expand::Direction) -> Self\n\n where\n\n Self: Sized,\n\n {\n\n match direction {\n", "file_path": "research/query_service/ir/runtime/src/graph/mod.rs", "rank": 51, "score": 264003.5503292709 }, { "content": "/// Notes: check active may produce new flow control events(High/LowWaterMark);\n\n/// Make sure to flush these events timely;\n\nfn check_active(task: &mut Dataflow, event_manager: &mut EventManager, strategy: &Box<dyn Strategy>) -> IOResult<bool> {\n\n let mut has_active = false;\n\n for op_opt in task.operators() {\n\n if let Some(ref mut op) = op_opt {\n\n event_manager.extract_inbound_events(op, strategy)?;\n\n if op.is_active() {\n\n has_active = true;\n\n }\n\n }\n\n }\n\n Ok(has_active)\n\n}\n\n\n\nimpl Scheduler {\n\n\n\n pub fn check_active(&mut self, task: &mut Dataflow) -> IOResult<bool> {\n\n update(&mut self.event_manager, &self.strategy)?;\n\n let active = check_active(task, &mut self.event_manager, &self.strategy)?;\n\n self.event_manager.push()?;\n\n Ok(active)\n", "file_path": "interactive_engine/executor/Pegasus/src/schedule/mod.rs", "rank": 52, "score": 263670.7115687585 }, { "content": "#[bench]\n\nfn bench_add(b: &mut test::Bencher) {\n\n let mut rng = rand::thread_rng();\n\n let mut d: u32 = rng.gen();\n\n let mut x = 0u32;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n if d > 1000 {\n\n x += i;\n\n }\n\n }\n\n //d = d.wrapping_add(1);\n\n });\n\n println!(\"{}\", x);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 53, "score": 262628.03239701025 }, { "content": "#[bench]\n\nfn bench_hash(b: &mut test::Bencher) {\n\n let mut x = 0;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n let mut h = DefaultHasher::new();\n\n h.write_u32(i);\n\n x += h.finish();\n\n }\n\n });\n\n println!(\"{}\", x);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 54, "score": 262628.03239701025 }, { "content": "#[bench]\n\nfn bench_mix_and(b: &mut test::Bencher) {\n\n let p = Mix::And(3);\n\n let mut x = 0;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n match p {\n\n Mix::Div(d) => x += i % d,\n\n Mix::And(a) => x += i & a,\n\n }\n\n }\n\n });\n\n println!(\"{}\", x);\n\n}\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 55, "score": 262628.03239701025 }, { "content": "#[bench]\n\nfn bench_div(b: &mut test::Bencher) {\n\n let p = 4u32;\n\n let mut x = 0;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n x += i % p;\n\n }\n\n });\n\n println!(\"{}\", x);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 56, "score": 262628.03239701025 }, { "content": "fn parse_label_list_proto(label_list_proto: &mut RepeatedField<LabelEntityProto>) -> Option<Vec<ExtraLabelEntity>> {\n\n let mut label_list = vec![];\n\n for label_proto in label_list_proto.iter_mut() {\n\n label_list.push(ExtraLabelEntity {\n\n label_id: label_proto.get_label_id(),\n\n message: RawMessage::from_proto(label_proto.mut_message()),\n\n });\n\n }\n\n\n\n if label_list.is_empty() {\n\n return None;\n\n }\n\n return Some(label_list);\n\n}\n\n\n", "file_path": "interactive_engine/executor/runtime/src/dataflow/message/mod.rs", "rank": 57, "score": 261885.2416126696 }, { "content": "#[inline]\n\nfn check_connection<R: ReadExt>(conn: &mut R) -> std::io::Result<Option<(u64, u32)>> {\n\n let handshake = conn.read_u128()?;\n\n Ok(check_handshake(handshake))\n\n}\n\n\n", "file_path": "research/engine/pegasus/network/src/transport/mod.rs", "rank": 58, "score": 261086.22603226392 }, { "content": "#[bench]\n\nfn bench_mix_div(b: &mut test::Bencher) {\n\n let p = Mix::Div(4);\n\n let mut x = 0;\n\n b.iter(|| {\n\n for i in 1..1001 {\n\n match p {\n\n Mix::Div(d) => x += i % d,\n\n Mix::And(a) => x += i & a,\n\n }\n\n }\n\n });\n\n println!(\"{}\", x);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_div.rs", "rank": 59, "score": 259806.2509118567 }, { "content": "fn update(event_manager: &mut EventManager, strategy: &Box<dyn Strategy>) -> IOResult<()> {\n\n let (deltas, has_updates) = event_manager.pull()?;\n\n if has_updates {\n\n for (ch, delta) in deltas.iter_mut().enumerate() {\n\n if *delta != 0 {\n\n strategy.messages(ch, *delta);\n\n *delta = 0;\n\n }\n\n }\n\n\n\n if ::log::log_enabled!(::log::Level::Debug) {\n\n event_manager.log();\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "interactive_engine/executor/Pegasus/src/schedule/mod.rs", "rank": 60, "score": 259192.3840290616 }, { "content": "fn get_items<I: ItemCommon>(store: &dyn ExternalStorage) -> GraphResult<Vec<I>> {\n\n let mut ret = Vec::new();\n\n let mut prefix = Vec::new();\n\n let table_prefix = transform::i64_to_arr(META_TABLE_ID.to_be());\n\n prefix.extend_from_slice(&table_prefix);\n\n prefix.extend_from_slice(I::prefix().as_bytes());\n\n let mut iter = res_unwrap!(store.scan_prefix(&prefix), get_items)?;\n\n while let Some((k, v)) = iter.next() {\n\n let item = res_unwrap!(I::from_kv(k, v), get_items)?;\n\n ret.push(item);\n\n }\n\n Ok(ret)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::collections::{HashSet, HashMap};\n\n use crate::db::storage::rocksdb::RocksDB;\n\n use crate::db::graph::tests::types;\n", "file_path": "interactive_engine/executor/store/src/db/graph/meta.rs", "rank": 61, "score": 258672.00238777633 }, { "content": "#[bench]\n\nfn tag_one_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = HashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::One(77), ());\n\n map.remove(&Tag::One(77));\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 62, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_root_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = HashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::Root, ());\n\n map.remove(&Tag::Root);\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 63, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_three_a_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = AHashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::Three(3, 6, 9), ());\n\n map.remove(&Tag::Three(3, 6, 9));\n\n })\n\n}\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 64, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_one_a_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = AHashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::One(77), ());\n\n map.remove(&Tag::One(77));\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 65, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_three_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = HashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::Three(3, 6, 9), ());\n\n map.remove(&Tag::Three(3, 6, 9));\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 66, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_two_a_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = AHashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::Two(3, 6), ());\n\n map.remove(&Tag::Two(3, 6));\n\n })\n\n}\n\n\n\n// #[bench]\n\n// fn tag_two_hash_w_r_hit_1000(b: &mut test::Bencher) {\n\n// let mut map = HashMap::new();\n\n// for i in 0..1000 {\n\n// map.insert(Tag::Two(3, i), ());\n\n// }\n\n// b.iter(|| {\n\n// map.insert(Tag::Two(3, 2000), ());\n\n// map.remove(&Tag::Two(3, 2000));\n\n// })\n\n// }\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 67, "score": 257069.39097863017 }, { "content": "#[bench]\n\nfn tag_two_hash_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = HashMap::with_capacity(1024);\n\n b.iter(|| {\n\n map.insert(Tag::Two(3, 6), ());\n\n map.remove(&Tag::Two(3, 6));\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 68, "score": 257069.39097863017 }, { "content": "#[test]\n\nfn join_test_empty_stream() {\n\n let mut conf = JobConf::new(\"inner_join\");\n\n conf.set_workers(2);\n\n let mut result = pegasus::run(conf, || {\n\n let id = pegasus::get_current_worker().index;\n\n move |input, output| {\n\n let (src1, src2) = create_src(id, input)?;\n\n let src2 = src2.filter_map(|_| Ok(None))?;\n\n src1.key_by(|x| Ok((x, x)))?\n\n .partition_by_key()\n\n .inner_join(src2.key_by(|x| Ok((x, x)))?.partition_by_key())?\n\n .map(|(d1, d2)| Ok(((d1.key, d1.value), (d2.key, d2.value))))?\n\n .collect::<Vec<((i32, i32), (i32, i32))>>()?\n\n .sink_into(output)\n\n }\n\n })\n\n .expect(\"run job failure;\");\n\n\n\n let mut result = result.next().unwrap().unwrap();\n\n result.sort_by_key(|x| x.0 .0);\n\n assert_eq!(result, []);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/tests/join_test.rs", "rank": 69, "score": 255503.81243947407 }, { "content": "#[bench]\n\nfn tag_one_int_map_w_r_hit(b: &mut test::Bencher) {\n\n let mut map = IntMap::default();\n\n b.iter(|| {\n\n map.insert(77, ());\n\n map.remove(&77);\n\n })\n\n}\n\n\n\n// #[bench]\n\n// fn tag_one_hash_w_r_hit_1000(b: &mut test::Bencher) {\n\n// let mut map = HashMap::new();\n\n// for i in 0..1024u32 {\n\n// map.insert(Tag::One(i), ());\n\n// }\n\n// b.iter(|| {\n\n// map.insert(Tag::One(2000), ());\n\n// map.remove(&Tag::One(2000));\n\n// })\n\n// }\n\n//\n", "file_path": "research/engine/pegasus/pegasus/benches/bench_tag.rs", "rank": 70, "score": 254413.67585500702 }, { "content": "fn check_list_equal<T: PartialEq>(list1: &Vec<T>, list2: &Vec<T>) -> bool {\n\n if list1.len() == list2.len() {\n\n for val1 in list1.iter() {\n\n if !list2.contains(val1) {\n\n return false;\n\n }\n\n }\n\n return true;\n\n } else {\n\n return false;\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/test/global_graph_test_fn.rs", "rank": 71, "score": 253780.3929509875 }, { "content": "pub fn startup(conf: Configuration) -> Result<(), StartupError> {\n\n if let Some(pool_size) = conf.max_pool_size {\n\n pegasus_executor::set_core_pool_size(pool_size as usize);\n\n }\n\n pegasus_executor::try_start_executor_async();\n\n\n\n let mut servers = HashSet::new();\n\n let server_id = conf.server_id();\n\n servers.insert(server_id);\n\n if let Some(id) = set_server_id(server_id) {\n\n return Err(StartupError::AlreadyStarted(id));\n\n }\n\n if let Some(net_conf) = conf.network_config() {\n\n if let Some(peers) = net_conf.get_servers()? {\n\n let addr = net_conf.local_addr()?;\n\n let conn_conf = net_conf.get_connection_param();\n\n for p in peers.iter() {\n\n servers.insert(p.id);\n\n }\n\n let addr = pegasus_network::start_up(server_id, conn_conf, addr, peers)?;\n", "file_path": "research/engine/pegasus/pegasus/src/lib.rs", "rank": 72, "score": 252944.5098107895 }, { "content": "fn check_edge_iter<E: RocksEdge>(mut iter: Records<E>, mut ans: HashMap<EdgeId, EdgeDataRef>, mut ids: HashSet<EdgeId>) {\n\n while let Some(edge) = iter.next() {\n\n let e = edge.unwrap();\n\n assert!(ids.remove(e.get_edge_id()), \"find an edge not in user's answer, this edge is {:?}\", e);\n\n let ans_e = ans.remove(e.get_edge_id()).unwrap();\n\n check_edge(&e, &ans_e);\n\n }\n\n assert!(ids.is_empty(), \"some edge in user's answer is not found in data\");\n\n assert!(ans.is_empty(), \"some edge in helper is not found in data\");\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/graph/tests/helper.rs", "rank": 73, "score": 250952.48589314753 }, { "content": "pub fn partition<P: AsRef<Path>>(_path: P, _partitions: usize) -> std::io::Result<Vec<MemIdTopoGraph>> {\n\n todo!()\n\n}\n\n\n", "file_path": "research/engine/pegasus/graph/src/lib.rs", "rank": 74, "score": 250592.03902012666 }, { "content": "fn do_reduce<D, B, F>(src: Stream<D>, builder: B) -> Result<SingleItem<D>, BuildJobError>\n\nwhere\n\n D: Data,\n\n F: FnMut(D, D) -> FnResult<D> + Send + 'static,\n\n B: Fn() -> F + Send + 'static,\n\n{\n\n let single = src.unary(\"reduce\", |info| {\n\n let mut table = TidyTagMap::<(D, F)>::new(info.scope_level);\n\n move |input, output| {\n\n input.for_each_batch(|dataset| {\n\n let r = if let Some((mut pre, mut f)) = table.remove(&dataset.tag) {\n\n for item in dataset.drain() {\n\n pre = f(pre, item)?;\n\n }\n\n Some((pre, f))\n\n } else {\n\n let mut f = (builder)();\n\n let mut iter = dataset.drain();\n\n if let Some(mut pre) = iter.next() {\n\n for item in iter {\n", "file_path": "research/engine/pegasus/pegasus/src/operator/concise/reduce.rs", "rank": 75, "score": 250104.34204447648 }, { "content": "#[inline]\n\nfn setup_connection<W: WriteExt>(server_id: u64, hb_sec: u32, conn: &mut W) -> std::io::Result<()> {\n\n let handshake = get_handshake(server_id, hb_sec);\n\n conn.write_u128(handshake)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n\n\n fn handshake(server_id: u64) {\n\n let value = get_handshake(server_id, 5);\n\n assert_eq!(Some((server_id, 5)), check_handshake(value), \"error handshake on {}\", server_id);\n\n }\n\n\n\n #[test]\n\n fn hand_shake_rw_test() {\n\n for i in 0u64..65536 {\n\n handshake(i);\n\n }\n\n handshake(!0);\n\n }\n\n}\n", "file_path": "research/engine/pegasus/network/src/transport/mod.rs", "rank": 76, "score": 249992.86438361937 }, { "content": " @Test\n\n public void aliasTest() throws IOException {\n\n ExpandOp op = new ExpandOp();\n\n op.setEdgeOpt(new OpArg<>(Boolean.valueOf(true), Function.identity()));\n\n op.setDirection(new OpArg<>(FfiDirection.Out, Function.identity()));\n\n op.setAlias(new OpArg(ArgUtils.asFfiAlias(\"a\", true), Function.identity()));\n\n irPlan.appendInterOp(-1, op);\n\n String actual = irPlan.getPlanAsJson();\n\n Assert.assertEquals(FileUtils.readJsonFromResource(\"expand_alias.json\"), actual);\n", "file_path": "research/query_service/ir/compiler/src/test/java/com/alibaba/graphscope/common/intermediate/operator/ExpandOpTest.java", "rank": 77, "score": 249973.21821198598 }, { "content": "#[test]\n\nfn apply_collect_empty_stream() {\n\n let mut conf = JobConf::new(\"apply_x_flatmap_any_x_test\");\n\n conf.set_workers(2);\n\n let mut result = pegasus::run(conf, || {\n\n |input, output| {\n\n input\n\n .input_from(0..1000u32)?\n\n .apply(|sub| {\n\n sub.repartition(|x| Ok(*x as u64))\n\n .flat_map(|i| Ok(vec![i, i + 2].into_iter()))?\n\n .filter(|i| Ok(*i % 2 == 0))?\n\n .map(|x| Ok(x))?\n\n .collect::<Vec<_>>()\n\n })?\n\n .filter_map(\n\n |(x, vec)| if vec.is_empty() { Ok(None) } else { Ok(Some((x, vec.len() as u64))) },\n\n )?\n\n .sink_into(output)\n\n }\n\n })\n", "file_path": "research/engine/pegasus/pegasus/tests/subtask_test.rs", "rank": 78, "score": 248791.16944254428 }, { "content": "#[test]\n\nfn apply_count_empty_stream() {\n\n let mut conf = JobConf::new(\"apply_x_flatmap_any_x_test\");\n\n conf.set_workers(2);\n\n let mut result = pegasus::run(conf, || {\n\n |input, output| {\n\n input\n\n .input_from(0..1000u32)?\n\n .apply(|sub| {\n\n sub.repartition(|x| Ok(*x as u64))\n\n .flat_map(|i| Ok(vec![i, i + 2].into_iter()))?\n\n .filter(|i| Ok(*i % 2 == 0))?\n\n .map(|x| Ok(x))?\n\n .count()\n\n })?\n\n .filter_map(|(x, cnt)| if cnt == 0 { Ok(None) } else { Ok(Some((x, cnt))) })?\n\n .sink_into(output)\n\n }\n\n })\n\n .expect(\"build job failure\");\n\n\n\n let mut count = 0;\n\n while let Some(Ok(d)) = result.next() {\n\n assert_eq!(d.0 % 2, 0);\n\n assert_eq!(d.1, 2);\n\n count += 1;\n\n }\n\n\n\n assert_eq!(count, 1000);\n\n}\n\n\n", "file_path": "research/engine/pegasus/pegasus/tests/subtask_test.rs", "rank": 79, "score": 248791.16944254428 }, { "content": "#[inline]\n\nfn encode_storage_label(labels: &Vec<Label>) -> FnExecResult<Vec<LabelId>> {\n\n labels\n\n .iter()\n\n .map(|label| match label {\n\n Label::Str(_) => {\n\n Err(FnExecError::query_store_error(\"encode storage label error, should provide label_id\"))\n\n }\n\n Label::Id(id) => Ok(*id as LabelId),\n\n })\n\n .collect::<Result<Vec<LabelId>, _>>()\n\n}\n\n\n", "file_path": "research/query_service/ir/graph_proxy/src/gs_store/graph_query.rs", "rank": 80, "score": 248747.17687510775 }, { "content": "fn busy_send<W: Write>(net_tx: &mut NetSender<W>, block: bool, timeout: u64, local: u64, remote: u64) {\n\n let heart_beat_tick = crossbeam_channel::tick(Duration::from_secs(5));\n\n while !crate::is_shutdown(local) {\n\n let result = if block { net_tx.send(timeout) } else { net_tx.try_send(timeout) };\n\n match result {\n\n Ok(true) => {\n\n info!(\"finish sending all data to {:?}\", remote);\n\n break;\n\n }\n\n Err(e) => {\n\n error!(\"fail to send data to {:?}, caused by {};\", remote, e);\n\n break;\n\n }\n\n _ => {\n\n if let Ok(_) = heart_beat_tick.try_recv() {\n\n net_tx.send_heart_beat();\n\n }\n\n }\n\n }\n\n }\n\n info!(\"IPC sender to {:?} exit;\", remote);\n\n remove_remote_sender(local, remote);\n\n}\n", "file_path": "research/engine/pegasus/network/src/send/mod.rs", "rank": 81, "score": 247763.83722763474 }, { "content": "/// Parses an escape sequence within a string literal.\n\nfn parse_escape_sequence<Iter: Iterator<Item = char>>(iter: &mut Iter) -> ExprResult<char> {\n\n match iter.next() {\n\n Some('\"') => Ok('\"'),\n\n Some('\\\\') => Ok('\\\\'),\n\n Some(c) => Err(ExprError::IllegalEscapeSequence(format!(\"\\\\{}\", c))),\n\n None => Err(ExprError::IllegalEscapeSequence(\"\\\\\".to_string())),\n\n }\n\n}\n\n\n", "file_path": "research/query_service/ir/common/src/expr_parse/token.rs", "rank": 82, "score": 247153.76451939554 }, { "content": "#[bench]\n\nfn write_linked_list(b: &mut Bencher) {\n\n let mut queue = LinkedList::new();\n\n b.iter(|| queue.push_back(FlatPtr(!0, 65536)));\n\n println!(\"after write linked size {}\", queue.len());\n\n}\n\n\n", "file_path": "research/engine/pegasus/common/benches/queue.rs", "rank": 83, "score": 246212.4263792669 }, { "content": "#[bench]\n\nfn read_array_queue(b: &mut Bencher) {\n\n let queue = ArrayQueue::new(100_000_000);\n\n //let item = \"bench\".to_owned();\n\n for _ in 0..100_000_000 {\n\n queue.push(FlatPtr(!0, 65536)).ok();\n\n }\n\n\n\n b.iter(|| queue.pop());\n\n println!(\"after read array queue.size {}\", queue.len());\n\n}\n", "file_path": "research/engine/pegasus/common/benches/queue.rs", "rank": 84, "score": 246212.4263792669 }, { "content": "#[bench]\n\nfn write_array_queue(b: &mut Bencher) {\n\n let queue = ArrayQueue::new(100_000_000);\n\n b.iter(|| {\n\n for i in 0..100_000_000 {\n\n queue.push(FlatPtr(i, i)).ok();\n\n }\n\n\n\n while let Ok(_) = queue.pop() {}\n\n })\n\n}\n\n\n", "file_path": "research/engine/pegasus/common/benches/queue.rs", "rank": 85, "score": 246212.4263792669 }, { "content": "/// Visit proto directory recursively. The callback function is invoked if a file is encountered,\n\n/// otherwise add the sub-directory to watching list to trigger regeneration of .rs proto files (by\n\n/// print the cargo directive).\n\nfn visit_dirs(dir: &Path, cb: &mut dyn FnMut(&DirEntry)) {\n\n if dir.is_dir() {\n\n println!(\"cargo:rerun-if-changed={}\", dir.to_str().unwrap());\n\n for entry in fs::read_dir(dir).unwrap() {\n\n let entry = entry.unwrap();\n\n let path = entry.path();\n\n if path.is_dir() {\n\n visit_dirs(&path, cb);\n\n } else {\n\n cb(&entry);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/rust-common/build.rs", "rank": 86, "score": 245387.4543473003 }, { "content": "pub fn parse_pb<M: Message>(buf: &[u8]) -> GraphResult<M> {\n\n protobuf::parse_from_bytes::<M>(buf)\n\n .map_err(|e| GraphError::new(InvalidData, format!(\"{:?}\", e)))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n macro_rules! test_unsafe_rw {\n\n ($r_func:ident, $w_func:ident, $ty:ty) => {\n\n let mut buf = Vec::with_capacity(100);\n\n let mut writer = UnsafeBytesWriter::new(&mut buf);\n\n writer.$w_func(20, 1.0 as $ty);\n\n let reader = UnsafeBytesReader::new(&buf);\n\n assert_eq!(reader.$r_func(20), 1.0 as $ty);\n\n };\n\n }\n\n\n\n #[test]\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/util.rs", "rank": 87, "score": 242130.8680703185 }, { "content": "fn check_edge_equals<E>(v1: &E, v2: &E) -> bool\n\n where E: Edge {\n\n if v1.get_edge_id() == v2.get_edge_id() &&\n\n v1.get_label_id() == v2.get_label_id() &&\n\n v1.get_src_label_id() == v2.get_src_label_id() &&\n\n v1.get_src_id() == v2.get_src_id() &&\n\n v1.get_dst_label_id() == v2.get_dst_label_id() &&\n\n v1.get_dst_id() == v2.get_dst_id() {\n\n let mut list1 = vec![];\n\n let mut pi1 = v1.get_properties();\n\n while let Some(prop) = pi1.next() {\n\n list1.push(prop);\n\n }\n\n\n\n let mut pi2 = v2.get_properties();\n\n let mut list2 = vec![];\n\n while let Some(prop) = pi2.next() {\n\n list2.push(prop);\n\n }\n\n\n\n if !check_list_equal(&list1, &list2) {\n\n panic!(\"Expect vertex {:?}:{:?} property list {:?} while find property list {:?}\", v1.get_label_id(), v1.get_edge_id(), &list1, &list2);\n\n }\n\n return true;\n\n } else {\n\n panic!(\"Expect vertex {:?}:{:?} != result vertex {:?}:{:?}\", v1.get_label_id(), v1.get_edge_id(), v2.get_label_id(), v2.get_edge_id());\n\n }\n\n}\n", "file_path": "interactive_engine/executor/store/src/test/global_graph_test_fn.rs", "rank": 88, "score": 241968.199006872 }, { "content": "fn check_vertex_equals<V>(v1: &V, v2: &V) -> bool\n\n where V: Vertex {\n\n if v1.get_id() == v2.get_id() && v1.get_label_id() == v2.get_label_id() {\n\n let mut list1 = vec![];\n\n let mut pi1 = v1.get_properties();\n\n while let Some(prop) = pi1.next() {\n\n list1.push(prop);\n\n }\n\n\n\n let mut pi2 = v2.get_properties();\n\n let mut list2 = vec![];\n\n while let Some(prop) = pi2.next() {\n\n list2.push(prop);\n\n }\n\n\n\n if !check_list_equal(&list1, &list2) {\n\n panic!(\"Expect vertex {:?}:{:?} property list {:?} while find property list {:?}\", v1.get_label_id(), v1.get_id(), &list1, &list2);\n\n }\n\n return true;\n\n } else {\n\n panic!(\"Expect vertex {:?}:{:?} != result vertex {:?}:{:?}\", v1.get_label_id(), v1.get_id(), v2.get_label_id(), v2.get_id());\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/test/global_graph_test_fn.rs", "rank": 89, "score": 241968.199006872 }, { "content": "pub fn order_message_list(val_list: &mut Vec<RawMessage>,\n\n message: RawMessage,\n\n order_list: &[OrderComparator],\n\n range_limit: usize,\n\n has_limit: bool) {\n\n val_list.push(message);\n\n val_list.sort_by(|a, b|\n\n cmp_vertex_edge(a, b, order_list));\n\n if has_limit && val_list.len() > range_limit {\n\n val_list.pop();\n\n }\n\n}\n\n\n", "file_path": "interactive_engine/executor/runtime/src/dataflow/manager/order.rs", "rank": 90, "score": 240045.4603287495 }, { "content": "#[inline]\n\nfn encode_result<T>(_result: T) -> Vec<u8> {\n\n unimplemented!()\n\n}\n", "file_path": "research/engine/pegasus/benchmark/src/queries/ldbc/ic1.rs", "rank": 91, "score": 240009.40810074267 }, { "content": "#[test]\n\nfn test_route() {\n\n let store_config = StoreConfig {\n\n worker_id: 1,\n\n alive_id: 0,\n\n worker_num: 2,\n\n zk_url: \"\".to_string(),\n\n graph_name: \"\".to_string(),\n\n partition_num: 4,\n\n zk_timeout_ms: 0,\n\n zk_auth_enable: false,\n\n zk_auth_user: \"test\".to_string(),\n\n zk_auth_password: \"test\".to_string(),\n\n hb_interval_ms: 0,\n\n insert_thread_count: 0,\n\n download_thread_count: 0,\n\n hadoop_home: \"\".to_string(),\n\n local_data_root: \"\".to_string(),\n\n load_thread_count: 0,\n\n rpc_thread_count: 0,\n\n rpc_port: 0,\n", "file_path": "interactive_engine/executor/runtime/src/execution/mod.rs", "rank": 92, "score": 239851.82409722448 }, { "content": "pub fn i64_to_vec(x: i64) -> Vec<u8> {\n\n int_to_vec!(x, i64)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/transform.rs", "rank": 93, "score": 239446.2075648312 }, { "content": "pub fn u32_to_vec(x: u32) -> Vec<u8> {\n\n int_to_vec!(x, u32)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/transform.rs", "rank": 94, "score": 239446.2075648312 }, { "content": "pub fn u64_to_vec(x: u64) -> Vec<u8> {\n\n int_to_vec!(x, u64)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/transform.rs", "rank": 95, "score": 239446.2075648312 }, { "content": "pub fn i16_to_vec(x: i16) -> Vec<u8> {\n\n int_to_vec!(x, i16)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/transform.rs", "rank": 96, "score": 239446.2075648312 }, { "content": "pub fn i32_to_vec(x: i32) -> Vec<u8> {\n\n int_to_vec!(x, i32)\n\n}\n\n\n", "file_path": "interactive_engine/executor/store/src/db/common/bytes/transform.rs", "rank": 97, "score": 239446.2075648312 }, { "content": "#[inline]\n\nfn enter_loop<D: Data, A: DataflowBuilder>(input: &Stream<D, A>) -> Stream<D, A> {\n\n if input.is_local() {\n\n let target = input.worker_id().1 as u64;\n\n input.enter(Exchange::new(move |_| target))\n\n } else {\n\n input.enter(Pipeline)\n\n }\n\n}\n\n\n\nimpl<D: Data, A: DataflowBuilder> Iteration<D, A> for Stream<D, A> {\n\n fn iterate<F>(&self, max_times: u32, func: F) -> Stream<D, A> where F: Fn(&Stream<D, A>) -> Stream<D, A> {\n\n if max_times <= 8 {\n\n let mut stream = func(self);\n\n for _i in 1..max_times {\n\n stream = func(&stream);\n\n }\n\n stream\n\n } else {\n\n let enter = enter_loop(self);\n\n let iterate = enter.add_loop_control(func, |info, ch1, ch2, events| {\n", "file_path": "interactive_engine/executor/Pegasus/src/operator/advanced/iterate.rs", "rank": 98, "score": 238903.2213302594 }, { "content": "fn update(worker_id: &WorkerId, manager: &mut Vec<ChannelEvents>,\n\n updates: &mut VecDeque<Event>, deltas: &mut Vec<i64>) {\n\n while let Some(event) = updates.pop_front() {\n\n let ch_id = match &event {\n\n Event::Pushed(_, count, channel) => {\n\n deltas[channel.0] += *count as i64;\n\n *channel\n\n },\n\n Event::Pulled(_, count, channel) => {\n\n deltas[channel.0] -= *count as i64;\n\n *channel\n\n }\n\n Event::END(_, _, channel) => *channel,\n\n Event::EOS(_, channel) => *channel,\n\n Event::Iterations(_, _, channel) => *channel,\n\n Event::HighWaterMark(_, channel, _) => *channel,\n\n Event::LowWaterMark(_, channel, _) => *channel,\n\n };\n\n if let Some(ch_m) = get_ch_mgr(manager, &ch_id) {\n\n trace!(\"### Worker[{}]: accept event {:?}\", worker_id.1, event);\n", "file_path": "interactive_engine/executor/Pegasus/src/event.rs", "rank": 99, "score": 238676.9475370289 } ]
Rust
src/config/request.rs
initprism/isahc
9ddf6b4de16f3b90608dcce0abf2ddd8c51ef2e6
use super::{proxy::Proxy, *}; use curl::easy::Easy2; #[doc(hidden)] pub trait WithRequestConfig: Sized { fn with_config(self, f: impl FnOnce(&mut RequestConfig)) -> Self; } pub(crate) trait SetOpt { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error>; } macro_rules! define_request_config { ($($field:ident: $t:ty,)*) => { #[derive(Clone, Debug, Default)] pub struct RequestConfig { $( pub(crate) $field: $t, )* } impl RequestConfig { pub(crate) fn client_defaults() -> Self { Self { version_negotiation: Some(VersionNegotiation::default()), automatic_decompression: Some(true), authentication: Some(Authentication::default()), ..Default::default() } } pub(crate) fn merge(&mut self, defaults: &Self) { $( if self.$field.is_none() { if let Some(value) = defaults.$field.as_ref() { self.$field = Some(value.clone()); } } )* } } }; } define_request_config! { timeout: Option<Duration>, connect_timeout: Option<Duration>, low_speed_timeout: Option<(u32, Duration)>, version_negotiation: Option<VersionNegotiation>, automatic_decompression: Option<bool>, expect_continue: Option<ExpectContinue>, authentication: Option<Authentication>, credentials: Option<Credentials>, tcp_keepalive: Option<Duration>, tcp_nodelay: Option<bool>, interface: Option<NetworkInterface>, ip_version: Option<IpVersion>, dial: Option<Dialer>, proxy: Option<Option<http::Uri>>, proxy_blacklist: Option<proxy::Blacklist>, proxy_authentication: Option<Proxy<Authentication>>, proxy_credentials: Option<Proxy<Credentials>>, max_upload_speed: Option<u64>, max_download_speed: Option<u64>, ssl_client_certificate: Option<ClientCertificate>, ssl_ca_certificate: Option<CaCertificate>, ssl_ciphers: Option<ssl::Ciphers>, ssl_options: Option<SslOption>, enable_metrics: Option<bool>, redirect_policy: Option<RedirectPolicy>, auto_referer: Option<bool>, title_case_headers: Option<bool>, } impl SetOpt for RequestConfig { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error> { if let Some(timeout) = self.timeout { easy.timeout(timeout)?; } if let Some((low_speed, timeout)) = self.low_speed_timeout { easy.low_speed_limit(low_speed)?; easy.low_speed_time(timeout)?; } if let Some(timeout) = self.connect_timeout { easy.connect_timeout(timeout)?; } if let Some(negotiation) = self.version_negotiation.as_ref() { negotiation.set_opt(easy)?; } #[allow(unsafe_code)] { if let Some(enable) = self.automatic_decompression { if enable { easy.accept_encoding("")?; } else { unsafe { match curl_sys::curl_easy_setopt( easy.raw(), curl_sys::CURLOPT_ACCEPT_ENCODING, 0, ) { curl_sys::CURLE_OK => {} code => return Err(curl::Error::new(code)), } } } } } if let Some(expect_continue) = self.expect_continue.as_ref() { expect_continue.set_opt(easy)?; } if let Some(auth) = self.authentication.as_ref() { auth.set_opt(easy)?; } if let Some(credentials) = self.credentials.as_ref() { credentials.set_opt(easy)?; } if let Some(interval) = self.tcp_keepalive { easy.tcp_keepalive(true)?; easy.tcp_keepintvl(interval)?; } if let Some(enable) = self.tcp_nodelay { easy.tcp_nodelay(enable)?; } if let Some(interface) = self.interface.as_ref() { interface.set_opt(easy)?; } if let Some(version) = self.ip_version.as_ref() { version.set_opt(easy)?; } if let Some(dialer) = self.dial.as_ref() { dialer.set_opt(easy)?; } if let Some(proxy) = self.proxy.as_ref() { match proxy { Some(uri) => easy.proxy(&format!("{}", uri))?, None => easy.proxy("")?, } } if let Some(blacklist) = self.proxy_blacklist.as_ref() { blacklist.set_opt(easy)?; } if let Some(auth) = self.proxy_authentication.as_ref() { auth.set_opt(easy)?; } if let Some(credentials) = self.proxy_credentials.as_ref() { credentials.set_opt(easy)?; } if let Some(max) = self.max_upload_speed { easy.max_send_speed(max)?; } if let Some(max) = self.max_download_speed { easy.max_recv_speed(max)?; } if let Some(cert) = self.ssl_client_certificate.as_ref() { cert.set_opt(easy)?; } if let Some(cert) = self.ssl_ca_certificate.as_ref() { cert.set_opt(easy)?; } if let Some(ciphers) = self.ssl_ciphers.as_ref() { ciphers.set_opt(easy)?; } if let Some(options) = self.ssl_options.as_ref() { options.set_opt(easy)?; } if let Some(enable) = self.enable_metrics { easy.progress(enable)?; } Ok(()) } }
use super::{proxy::Proxy, *}; use curl::easy::Easy2; #[doc(hidden)] pub trait WithRequestConfig: Sized { fn with_config(self, f: impl FnOnce(&mut RequestConfig)) -> Self; } pub(crate) trait SetOpt { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error>; } macro_rules! define_request_config { ($($field:ident: $t:ty,)*) => { #[derive(Clone, Debug, Default)] pub struct RequestConfig { $( pub(crate) $field: $t, )* } impl RequestConfig { pub(crate) fn client_defaults() -> Self { Self { version_negotiation: Some(VersionNegotiation::default()), automatic_decompression: Some(true), authentication: Some(Authentication::default()), ..Default::default() } } pub(crate) fn merge(&mut self, defaults: &Self) { $( if self.$field.is_none() { if let Some(value) = defaults.$field.as_ref() { self.$field = Some(value.clone()); } } )* } } }; } define_request_config! { timeout: Option<Duration>, connect_timeout: Option<Duration>, low_speed_timeout: Option<(u32, Duration)>, version_negotiation: Option<VersionNegotiation>, automatic_decompression: Option<bool>, expect_continue: Option<ExpectContinue>, authent
peed, timeout)) = self.low_speed_timeout { easy.low_speed_limit(low_speed)?; easy.low_speed_time(timeout)?; } if let Some(timeout) = self.connect_timeout { easy.connect_timeout(timeout)?; } if let Some(negotiation) = self.version_negotiation.as_ref() { negotiation.set_opt(easy)?; } #[allow(unsafe_code)] { if let Some(enable) = self.automatic_decompression { if enable { easy.accept_encoding("")?; } else { unsafe { match curl_sys::curl_easy_setopt( easy.raw(), curl_sys::CURLOPT_ACCEPT_ENCODING, 0, ) { curl_sys::CURLE_OK => {} code => return Err(curl::Error::new(code)), } } } } } if let Some(expect_continue) = self.expect_continue.as_ref() { expect_continue.set_opt(easy)?; } if let Some(auth) = self.authentication.as_ref() { auth.set_opt(easy)?; } if let Some(credentials) = self.credentials.as_ref() { credentials.set_opt(easy)?; } if let Some(interval) = self.tcp_keepalive { easy.tcp_keepalive(true)?; easy.tcp_keepintvl(interval)?; } if let Some(enable) = self.tcp_nodelay { easy.tcp_nodelay(enable)?; } if let Some(interface) = self.interface.as_ref() { interface.set_opt(easy)?; } if let Some(version) = self.ip_version.as_ref() { version.set_opt(easy)?; } if let Some(dialer) = self.dial.as_ref() { dialer.set_opt(easy)?; } if let Some(proxy) = self.proxy.as_ref() { match proxy { Some(uri) => easy.proxy(&format!("{}", uri))?, None => easy.proxy("")?, } } if let Some(blacklist) = self.proxy_blacklist.as_ref() { blacklist.set_opt(easy)?; } if let Some(auth) = self.proxy_authentication.as_ref() { auth.set_opt(easy)?; } if let Some(credentials) = self.proxy_credentials.as_ref() { credentials.set_opt(easy)?; } if let Some(max) = self.max_upload_speed { easy.max_send_speed(max)?; } if let Some(max) = self.max_download_speed { easy.max_recv_speed(max)?; } if let Some(cert) = self.ssl_client_certificate.as_ref() { cert.set_opt(easy)?; } if let Some(cert) = self.ssl_ca_certificate.as_ref() { cert.set_opt(easy)?; } if let Some(ciphers) = self.ssl_ciphers.as_ref() { ciphers.set_opt(easy)?; } if let Some(options) = self.ssl_options.as_ref() { options.set_opt(easy)?; } if let Some(enable) = self.enable_metrics { easy.progress(enable)?; } Ok(()) } }
ication: Option<Authentication>, credentials: Option<Credentials>, tcp_keepalive: Option<Duration>, tcp_nodelay: Option<bool>, interface: Option<NetworkInterface>, ip_version: Option<IpVersion>, dial: Option<Dialer>, proxy: Option<Option<http::Uri>>, proxy_blacklist: Option<proxy::Blacklist>, proxy_authentication: Option<Proxy<Authentication>>, proxy_credentials: Option<Proxy<Credentials>>, max_upload_speed: Option<u64>, max_download_speed: Option<u64>, ssl_client_certificate: Option<ClientCertificate>, ssl_ca_certificate: Option<CaCertificate>, ssl_ciphers: Option<ssl::Ciphers>, ssl_options: Option<SslOption>, enable_metrics: Option<bool>, redirect_policy: Option<RedirectPolicy>, auto_referer: Option<bool>, title_case_headers: Option<bool>, } impl SetOpt for RequestConfig { fn set_opt<H>(&self, easy: &mut Easy2<H>) -> Result<(), curl::Error> { if let Some(timeout) = self.timeout { easy.timeout(timeout)?; } if let Some((low_s
random
[ { "content": "/// Creates an interceptor from an arbitrary closure or function.\n\npub fn from_fn<F, E>(f: F) -> InterceptorFn<F>\n\nwhere\n\n F: for<'a> private::AsyncFn2<Request<AsyncBody>, Context<'a>, Output = InterceptorResult<E>>\n\n + Send\n\n + Sync\n\n + 'static,\n\n E: Error + Send + Sync + 'static,\n\n{\n\n InterceptorFn(f)\n\n}\n\n\n\n/// An interceptor created from an arbitrary closure or function. See\n\n/// [`from_fn`] for details.\n\npub struct InterceptorFn<F>(F);\n\n\n\nimpl<E, F> Interceptor for InterceptorFn<F>\n\nwhere\n\n E: Error + Send + Sync + 'static,\n\n F: for<'a> private::AsyncFn2<Request<AsyncBody>, Context<'a>, Output = InterceptorResult<E>>\n\n + Send\n", "file_path": "src/interceptor/mod.rs", "rank": 0, "score": 206378.1334083178 }, { "content": "#[allow(unsafe_code)]\n\nfn parse_cookie_value(mut bytes: &[u8]) -> Result<&str, ParseError> {\n\n // Strip quotes, but only if in a legal pair.\n\n if bytes.starts_with(b\"\\\"\") && bytes.ends_with(b\"\\\"\") {\n\n bytes = &bytes[1..bytes.len() - 1];\n\n }\n\n\n\n // Validate the bytes are all legal cookie octets.\n\n if !is_valid_cookie_value(bytes) {\n\n return Err(ParseError(()));\n\n }\n\n\n\n // Safety: We know that the given bytes are valid US-ASCII at this point, so\n\n // therefore it is also valid UTF-8.\n\n Ok(unsafe { str::from_utf8_unchecked(bytes) })\n\n}\n\n\n", "file_path": "src/cookies/cookie.rs", "rank": 2, "score": 155171.54467919044 }, { "content": "/// Send a HEAD request to the given URI.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::head`] for details.\n\npub fn head<U>(uri: U) -> Result<Response<Body>, Error>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().head(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 3, "score": 153758.69071874727 }, { "content": "/// Send a GET request to the given URI.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::get`] for details.\n\npub fn get<U>(uri: U) -> Result<Response<Body>, Error>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().get(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 4, "score": 153758.69071874727 }, { "content": "/// Send a DELETE request to the given URI.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::delete`] for details.\n\npub fn delete<U>(uri: U) -> Result<Response<Body>, Error>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().delete(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 5, "score": 153758.69071874727 }, { "content": "/// Provides additional methods when building a request for configuring various\n\n/// execution-related options on how the request should be sent.\n\n///\n\n/// This trait can be used to either configure requests individually by invoking\n\n/// them on an [`http::request::Builder`], or to configure the default settings\n\n/// for an [`HttpClient`](crate::HttpClient) by invoking them on an\n\n/// [`HttpClientBuilder`](crate::HttpClientBuilder).\n\n///\n\n/// This trait is sealed and cannot be implemented for types outside of Isahc.\n\npub trait Configurable: request::WithRequestConfig {\n\n /// Specify a maximum amount of time that a complete request/response cycle\n\n /// is allowed to take before being aborted. This includes DNS resolution,\n\n /// connecting to the server, writing the request, and reading the response.\n\n ///\n\n /// Since response bodies are streamed, you will likely receive a\n\n /// [`Response`](crate::http::Response) before the response body stream has\n\n /// been fully consumed. This means that the configured timeout will still\n\n /// be active for that request, and if it expires, further attempts to read\n\n /// from the stream will return a [`TimedOut`](std::io::ErrorKind::TimedOut)\n\n /// I/O error.\n\n ///\n\n /// This also means that if you receive a response with a body but do not\n\n /// immediately start reading from it, then the timeout timer will still be\n\n /// active and may expire before you even attempt to read the body. Keep\n\n /// this in mind when consuming responses and consider handling the response\n\n /// body right after you receive it if you are using this option.\n\n ///\n\n /// If not set, no timeout will be enforced.\n\n ///\n", "file_path": "src/config/mod.rs", "rank": 6, "score": 153571.32050460085 }, { "content": "pub fn read_url(url: &str) -> Result<Vec<u8>, String> {\n\n let client = match Request::get(url)\n\n .timeout(Duration::from_secs(5))\n\n .header(\"User-Agent\", \"el_monitorro/0.1.0\")\n\n .redirect_policy(RedirectPolicy::Limit(10))\n\n .body(())\n\n {\n\n Ok(cl) => cl,\n\n Err(er) => {\n\n let msg = format!(\"{:?}\", er);\n\n\n\n return Err(msg);\n\n }\n\n };\n\n\n\n match client.send() {\n\n Ok(mut response) => {\n\n let mut writer: Vec<u8> = vec![];\n\n\n\n if let Err(err) = io::copy(response.body_mut(), &mut writer) {\n", "file_path": "examples/spurious_abort_logs.rs", "rank": 7, "score": 151434.4633265213 }, { "content": "/// Send an HTTP request and return the HTTP response.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::send`] for details.\n\npub fn send<B: Into<Body>>(request: Request<B>) -> Result<Response<Body>, Error> {\n\n HttpClient::shared().send(request)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 8, "score": 141911.8174628916 }, { "content": "/// Send a POST request to the given URI with a given request body.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::post`] for details.\n\npub fn post<U, B>(uri: U, body: B) -> Result<Response<Body>, Error>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n B: Into<Body>,\n\n{\n\n HttpClient::shared().post(uri, body)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 9, "score": 139589.92822729444 }, { "content": "/// Send a PUT request to the given URI with a given request body.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::put`] for details.\n\npub fn put<U, B>(uri: U, body: B) -> Result<Response<Body>, Error>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n B: Into<Body>,\n\n{\n\n HttpClient::shared().put(uri, body)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 10, "score": 139589.92822729444 }, { "content": "/// Execute a given closure with a reference to the list cache. If the list is\n\n/// out of date, attempt to refresh it first before continuing.\n\nfn with_cache<T>(f: impl FnOnce(&ListCache) -> T) -> T {\n\n let cache = CACHE.upgradable_read();\n\n\n\n // First check if the list needs to be refreshed.\n\n if cache.needs_refreshed() {\n\n // Upgrade our lock to gain write access.\n\n let mut cache = RwLockUpgradableReadGuard::upgrade(cache);\n\n\n\n // If there was contention then the cache might not need refreshed any\n\n // more.\n\n if cache.needs_refreshed() {\n\n if let Err(e) = cache.refresh() {\n\n tracing::warn!(\"could not refresh public suffix list: {}\", e);\n\n }\n\n }\n\n\n\n f(&*cache)\n\n } else {\n\n f(&*cache)\n\n }\n\n}\n", "file_path": "src/cookies/psl/mod.rs", "rank": 11, "score": 134597.28427070554 }, { "content": "/// Provides extension methods for working with HTTP responses.\n\npub trait ResponseExt<T> {\n\n /// Get the trailer of the response containing headers that were received\n\n /// after the response body.\n\n ///\n\n /// See the documentation for [`Trailer`] for more details on how to handle\n\n /// trailing headers.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use isahc::prelude::*;\n\n ///\n\n /// let mut response = isahc::get(\"https://my-site-with-trailers.com\")?;\n\n ///\n\n /// println!(\"Status: {}\", response.status());\n\n /// println!(\"Headers: {:#?}\", response.headers());\n\n ///\n\n /// // Read and discard the response body until the end.\n\n /// response.consume()?;\n\n ///\n", "file_path": "src/response.rs", "rank": 12, "score": 133581.40424552964 }, { "content": "/// Extension methods on an HTTP request.\n\npub trait RequestExt<T> {\n\n /// Create a new request builder with the method, URI, and headers cloned\n\n /// from this request.\n\n ///\n\n /// Note that third-party extensions are not cloned.\n\n fn to_builder(&self) -> http::request::Builder;\n\n\n\n /// Send the HTTP request synchronously using the default client.\n\n ///\n\n /// This is a convenience method that is equivalent to\n\n /// [`send`](crate::send).\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// use isahc::{prelude::*, Request};\n\n ///\n\n /// let response = Request::post(\"https://httpbin.org/post\")\n\n /// .header(\"Content-Type\", \"application/json\")\n\n /// .body(r#\"{\n", "file_path": "src/request.rs", "rank": 13, "score": 133581.40424552964 }, { "content": "/// Base trait for interceptors.\n\n///\n\n/// Since clients may be used to send requests concurrently, all interceptors\n\n/// must be synchronized and must be able to account for multiple requests being\n\n/// made in parallel.\n\npub trait Interceptor: Send + Sync {\n\n /// The type of error returned by this interceptor.\n\n type Err: Error + Send + Sync + 'static;\n\n\n\n /// Intercept a request, returning a response.\n\n ///\n\n /// The returned future is allowed to borrow the interceptor for the\n\n /// duration of its execution.\n\n fn intercept<'a>(\n\n &'a self,\n\n request: Request<AsyncBody>,\n\n ctx: Context<'a>,\n\n ) -> InterceptorFuture<'a, Self::Err>;\n\n}\n\n\n\n/// The type of future returned by an interceptor.\n\npub type InterceptorFuture<'a, E> = Pin<Box<dyn Future<Output = InterceptorResult<E>> + Send + 'a>>;\n\n\n", "file_path": "src/interceptor/mod.rs", "rank": 14, "score": 127865.71799938372 }, { "content": "/// Helper trait for defining key-value pair types that can be dereferenced into\n\n/// a tuple from a reference.\n\n///\n\n/// This trait is sealed and cannot be implemented for types outside of Isahc.\n\npub trait HeaderPair<K, V> {\n\n fn pair(self) -> (K, V);\n\n}\n\n\n\nimpl<K, V> HeaderPair<K, V> for (K, V) {\n\n fn pair(self) -> (K, V) {\n\n self\n\n }\n\n}\n\n\n\nimpl<'a, K: Copy, V: Copy> HeaderPair<K, V> for &'a (K, V) {\n\n fn pair(self) -> (K, V) {\n\n (self.0, self.1)\n\n }\n\n}\n\n\n\n/// An HTTP client for making requests.\n\n///\n\n/// An [`HttpClient`] instance acts as a session for executing one or more HTTP\n\n/// requests, and also allows you to set common protocol settings that should be\n", "file_path": "src/client.rs", "rank": 15, "score": 127862.8393325463 }, { "content": "/// Provides extension methods for consuming HTTP response streams.\n\npub trait ReadResponseExt<R: Read> {\n\n /// Read any remaining bytes from the response body stream and discard them\n\n /// until the end of the stream is reached. It is usually a good idea to\n\n /// call this method before dropping a response if you know you haven't read\n\n /// the entire response body.\n\n ///\n\n /// # Background\n\n ///\n\n /// By default, if a response stream is dropped before it has been\n\n /// completely read from, then that HTTP connection will be terminated.\n\n /// Depending on which version of HTTP is being used, this may require\n\n /// closing the network connection to the server entirely. This can result\n\n /// in sub-optimal performance for making multiple requests, as it prevents\n\n /// Isahc from keeping the connection alive to be reused for subsequent\n\n /// requests.\n\n ///\n\n /// If you are downloading a file on behalf of a user and have been\n\n /// requested to cancel the operation, then this is probably what you want.\n\n /// But if you are making many small API calls to a known server, then you\n\n /// may want to call `consume()` before dropping the response, as reading a\n", "file_path": "src/response.rs", "rank": 16, "score": 125673.21024712214 }, { "content": "/// A responder is a request-response handler responsible for producing the\n\n/// responses returned by a mock endpoint.\n\n///\n\n/// Responders are not responsible for doing any assertions.\n\npub trait Responder: Send + Sync + 'static {\n\n fn respond(&self, request: Request) -> Option<Response>;\n\n}\n\n\n\n/// Simple responder that returns a general response.\n\npub struct DefaultResponder;\n\n\n\nimpl Responder for DefaultResponder {\n\n fn respond(&self, _: Request) -> Option<Response> {\n\n Some(Response::default())\n\n }\n\n}\n", "file_path": "testserver/src/responder.rs", "rank": 17, "score": 122648.69442324071 }, { "content": "fn benchmark(c: &mut Criterion) {\n\n c.bench_function(\"download 64K: curl\", move |b| {\n\n let server = TestServer::static_response(&DATA);\n\n let endpoint = server.endpoint();\n\n\n\n b.iter_batched(\n\n || {\n\n let mut easy = curl::easy::Easy::new();\n\n easy.url(&endpoint).unwrap();\n\n easy\n\n },\n\n |mut easy| {\n\n let mut sink = sink();\n\n let mut transfer = easy.transfer();\n\n\n\n transfer\n\n .write_function(|bytes| {\n\n sink.write_all(bytes).unwrap();\n\n Ok(bytes.len())\n\n })\n", "file_path": "benchmarks/benches/download.rs", "rank": 18, "score": 122092.01122366053 }, { "content": "/// Gets a human-readable string with the version number of Isahc and its\n\n/// dependencies.\n\n///\n\n/// This function can be helpful when troubleshooting issues in Isahc or one of\n\n/// its dependencies.\n\npub fn version() -> &'static str {\n\n static FEATURES_STRING: &str = include_str!(concat!(env!(\"OUT_DIR\"), \"/features.txt\"));\n\n static VERSION_STRING: Lazy<String> = Lazy::new(|| {\n\n format!(\n\n \"isahc/{} (features:{}) {}\",\n\n env!(\"CARGO_PKG_VERSION\"),\n\n FEATURES_STRING,\n\n curl::Version::num(),\n\n )\n\n });\n\n\n\n &VERSION_STRING\n\n}\n", "file_path": "src/lib.rs", "rank": 19, "score": 121189.14606898002 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n tracing_subscriber::fmt::init();\n\n\n\n let mut response = isahc::get(\"https://example.org\")?;\n\n\n\n // Consume the response stream quietly.\n\n std::io::copy(response.body_mut(), &mut std::io::sink())?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/tracing.rs", "rank": 20, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n futures_lite::future::block_on(async {\n\n let mut response = isahc::get_async(\"http://example.org\").await?;\n\n\n\n println!(\"Status: {}\", response.status());\n\n println!(\"Headers:\\n{:?}\", response.headers());\n\n println!(\"Body: {}\", response.text().await?);\n\n\n\n Ok(())\n\n })\n\n}\n", "file_path": "examples/async.rs", "rank": 21, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n let response = Request::get(\"https://nghttp2.org\")\n\n .version_negotiation(VersionNegotiation::http2())\n\n .body(())\n\n .map_err(Into::into)\n\n .and_then(isahc::send)?;\n\n\n\n println!(\"{:#?}\", response.headers());\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/http2.rs", "rank": 22, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n // Create a custom client instance and customize a couple things different\n\n // than the default settings. Check the documentation of `HttpClient` and\n\n // `Configurable` for everything that can be customized.\n\n let client = HttpClient::builder()\n\n .timeout(Duration::from_secs(5))\n\n .redirect_policy(RedirectPolicy::Follow)\n\n .build()?;\n\n\n\n let mut response = client.get(\"https://rust-lang.org\")?;\n\n\n\n // Copy the response body directly to stdout.\n\n copy(response.body_mut(), &mut stdout())?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/client.rs", "rank": 23, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n // Send a GET request and wait for the response headers.\n\n // Must be `mut` so we can read the response body.\n\n let mut response = isahc::get(\"http://example.org\")?;\n\n\n\n // Print some basic info about the response to standard output.\n\n println!(\"Status: {}\", response.status());\n\n println!(\"Headers: {:#?}\", response.headers());\n\n\n\n // Read the response body as text into a string and print it.\n\n print!(\"{}\", response.text()?);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/simple.rs", "rank": 24, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n env_logger::init();\n\n\n\n let mut response = isahc::get(\"https://example.org\")?;\n\n\n\n // Consume the response stream quietly.\n\n std::io::copy(response.body_mut(), &mut std::io::sink())?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/logging.rs", "rank": 25, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n let options = Options::from_args();\n\n\n\n let bar = ProgressBar::new(0).with_style(\n\n ProgressStyle::default_bar()\n\n .template(\"{bar:40.cyan/blue} {bytes:>7}/{total_bytes:7} {msg}\"),\n\n );\n\n\n\n let mut response = Request::get(options.url).metrics(true).body(())?.send()?;\n\n let metrics = response.metrics().unwrap().clone();\n\n let body = response.body_mut();\n\n let mut buf = [0; 16384 * 4];\n\n\n\n loop {\n\n match body.read(&mut buf) {\n\n Ok(0) => {\n\n bar.finish();\n\n break;\n\n }\n\n Ok(_) => {\n", "file_path": "examples/progress.rs", "rank": 26, "score": 120997.4393012844 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n let count = env::args()\n\n .nth(1)\n\n .and_then(|s| s.parse::<u32>().ok())\n\n .unwrap_or(100);\n\n\n\n let urls: Vec<String> = (0..count)\n\n .map(|i| format!(\"https://httpbin.org/anything/{:03}\", i))\n\n .collect();\n\n let client = HttpClient::new()?;\n\n\n\n let start = Instant::now();\n\n\n\n // Iterate over each URL and send a request in parallel.\n\n urls.par_iter()\n\n .try_for_each(|url| {\n\n let start = Instant::now();\n\n let response = client.get(url)?;\n\n let end = Instant::now();\n\n println!(\n", "file_path": "examples/parallel_requests.rs", "rank": 27, "score": 118708.05550439394 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n // We're opening the source code file you are looking at right now for\n\n // reading.\n\n let file = File::open(file!())?;\n\n\n\n // Perform the upload.\n\n let mut response = isahc::put(\"https://httpbin.org/put\", file)?;\n\n\n\n // Print interesting info from the response.\n\n println!(\"Status: {}\", response.status());\n\n println!(\"Headers: {:#?}\", response.headers());\n\n print!(\"{}\", response.text()?);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/upload_file.rs", "rank": 28, "score": 118708.05550439394 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n let weird_request = Request::head(\"http://download.opensuse.org/update/tumbleweed/repodata/repomd.xml\")\n\n .body(Body::from_reader(Cursor::new(b\"\")))?;\n\n\n\n let error = isahc::send(weird_request).unwrap_err();\n\n eprintln!(\"{}\", error);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/head_length.rs", "rank": 29, "score": 118708.05550439394 }, { "content": "fn main() -> Result<(), isahc::Error> {\n\n block_on(async {\n\n // Open a response stream.\n\n let response = isahc::get_async(\"https://www.rust-lang.org\").await?;\n\n\n\n let mut buf = [0; 8192];\n\n let mut offset = 0;\n\n let mut reader = response.into_body();\n\n\n\n // Set up a loop where we continuously read from the stream.\n\n loop {\n\n match reader.read(&mut buf).await? {\n\n // Zero bytes read, we hit EOF with no question marks.\n\n 0 => {\n\n println!(\"Download complete! No '?' byte of all {} bytes.\", offset);\n\n return Ok(());\n\n }\n\n // At least one byte was read.\n\n len => {\n\n // Check to dee if there's any question marks this time\n", "file_path": "examples/stream_cancellation.rs", "rank": 30, "score": 118708.05550439394 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n let out_dir = PathBuf::from(env::var(\"OUT_DIR\")?);\n\n fs::write(out_dir.join(\"features.txt\"), get_feature_string())?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "build.rs", "rank": 31, "score": 118419.9866621138 }, { "content": "/// Provides extension methods for consuming asynchronous HTTP response streams.\n\npub trait AsyncReadResponseExt<R: AsyncRead + Unpin> {\n\n /// Read any remaining bytes from the response body stream and discard them\n\n /// until the end of the stream is reached. It is usually a good idea to\n\n /// call this method before dropping a response if you know you haven't read\n\n /// the entire response body.\n\n ///\n\n /// # Background\n\n ///\n\n /// By default, if a response stream is dropped before it has been\n\n /// completely read from, then that HTTP connection will be terminated.\n\n /// Depending on which version of HTTP is being used, this may require\n\n /// closing the network connection to the server entirely. This can result\n\n /// in sub-optimal performance for making multiple requests, as it prevents\n\n /// Isahc from keeping the connection alive to be reused for subsequent\n\n /// requests.\n\n ///\n\n /// If you are downloading a file on behalf of a user and have been\n\n /// requested to cancel the operation, then this is probably what you want.\n\n /// But if you are making many small API calls to a known server, then you\n\n /// may want to call `consume()` before dropping the response, as reading a\n", "file_path": "src/response.rs", "rank": 32, "score": 116813.72808016074 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n // Create a new cookie jar.\n\n let cookie_jar = CookieJar::new();\n\n\n\n // Send a request to a server that sets a cookie.\n\n let uri = \"http://httpbin.org/cookies/set?foo=bar&baz=123\".parse()?;\n\n let _response = Request::get(&uri)\n\n // Set the cookie jar to use for this request.\n\n .cookie_jar(cookie_jar.clone())\n\n .body(())?\n\n .send()?;\n\n\n\n // Print all cookies relevant to the URL.\n\n for cookie in cookie_jar.get_for_uri(&uri) {\n\n println!(\"Cookie set: {} = {}\", cookie.name(), cookie.value());\n\n }\n\n\n\n // Replace a cookie\n\n let cookie = Cookie::builder(\"foo\", \"rab\").path(\"/\").build()?;\n\n cookie_jar.set(cookie, &uri)?;\n", "file_path": "examples/cookies.rs", "rank": 33, "score": 116130.60286522334 }, { "content": "#[test_case(\"GET\")]\n\n#[test_case(\"HEAD\")]\n\n#[test_case(\"POST\")]\n\n#[test_case(\"PUT\")]\n\n#[test_case(\"DELETE\")]\n\n#[test_case(\"PATCH\")]\n\n#[test_case(\"FOOBAR\")]\n\nfn request_with_body_of_unknown_size_uses_chunked_encoding(method: &str) {\n\n let body = \"foo\";\n\n\n\n let m = mock!();\n\n\n\n Request::builder()\n\n .method(method)\n\n .uri(m.url())\n\n // This header should be ignored\n\n .header(\"transfer-encoding\", \"identity\")\n\n .body(Body::from_reader(body.as_bytes()))\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(m.request().method, method);\n\n m.request().expect_header(\"transfer-encoding\", \"chunked\");\n\n m.request().expect_body(body);\n\n}\n\n\n", "file_path": "tests/request_body.rs", "rank": 34, "score": 115314.41085038196 }, { "content": "fn main() -> Result<(), Box<dyn Error>> {\n\n env_logger::init();\n\n\n\n read_url(\"https://tynan.com/feed/\")?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/spurious_abort_logs.rs", "rank": 35, "score": 111950.09978970021 }, { "content": "fn trim_left_ascii(mut ascii: &[u8]) -> &[u8] {\n\n while ascii.first() == Some(&b' ') {\n\n ascii = &ascii[1..];\n\n }\n\n\n\n ascii\n\n}\n\n\n", "file_path": "src/cookies/cookie.rs", "rank": 36, "score": 111058.63252937212 }, { "content": "fn main() -> Result<(), Box<dyn std::error::Error>> {\n\n let request = ShoutCloudRequest {\n\n input: \"hello world\".into(),\n\n };\n\n\n\n let response = Request::post(\"HTTP://API.SHOUTCLOUD.IO/V1/SHOUT\")\n\n .header(\"content-type\", \"application/json\")\n\n .body(serde_json::to_vec(&request)?)?\n\n .send()?\n\n .json::<ShoutCloudResponse>()?;\n\n\n\n println!(\"Response: {:?}\", response);\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/json.rs", "rank": 37, "score": 107565.13993803889 }, { "content": "#[test]\n\nfn timeout_during_response_body_produces_error() {\n\n struct SlowReader;\n\n\n\n impl Read for SlowReader {\n\n fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {\n\n thread::sleep(Duration::from_secs(2));\n\n Ok(0)\n\n }\n\n }\n\n\n\n let m = mock! {\n\n body_reader: Cursor::new(vec![0; 100_000]).chain(SlowReader),\n\n };\n\n\n\n let mut response = Request::get(m.url())\n\n .timeout(Duration::from_millis(500))\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n // Because of the short timeout, the response body should abort while being\n\n // read from.\n\n assert_eq!(\n\n response.copy_to(std::io::sink()).unwrap_err().kind(),\n\n std::io::ErrorKind::TimedOut\n\n );\n\n}\n", "file_path": "tests/timeouts.rs", "rank": 38, "score": 106583.49986241494 }, { "content": "#[test]\n\nfn request_errors_if_read_timeout_is_reached() {\n\n // Spawn a slow server.\n\n let m = mock! {\n\n delay: 1s,\n\n };\n\n\n\n // Send a request with a timeout.\n\n let result = Request::post(m.url())\n\n .timeout(Duration::from_millis(500))\n\n .body(\"hello world\")\n\n .unwrap()\n\n .send();\n\n\n\n // Client should time-out.\n\n assert_matches!(result, Err(e) if e == isahc::error::ErrorKind::Timeout);\n\n\n\n assert_eq!(m.requests().len(), 1);\n\n}\n\n\n\n/// Issue #154\n", "file_path": "tests/timeouts.rs", "rank": 39, "score": 106583.49986241494 }, { "content": "#[allow(unsafe_code)]\n\nfn parse_token(bytes: &[u8]) -> Result<&str, ParseError> {\n\n if is_valid_token(bytes) {\n\n // Safety: We know that the given bytes are valid US-ASCII at this\n\n // point, so therefore it is also valid UTF-8.\n\n Ok(unsafe { str::from_utf8_unchecked(bytes) })\n\n } else {\n\n Err(ParseError(()))\n\n }\n\n}\n\n\n", "file_path": "src/cookies/cookie.rs", "rank": 40, "score": 105920.49771713305 }, { "content": "/// Send a DELETE request to the given URI asynchronously.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::delete_async`] for details.\n\npub fn delete_async<U>(uri: U) -> ResponseFuture<'static>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().delete_async(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 41, "score": 104010.36627856034 }, { "content": "/// Send a HEAD request to the given URI asynchronously.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::head_async`] for details.\n\npub fn head_async<U>(uri: U) -> ResponseFuture<'static>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().head_async(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 42, "score": 104010.36627856034 }, { "content": "/// Send a GET request to the given URI asynchronously.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::get_async`] for details.\n\npub fn get_async<U>(uri: U) -> ResponseFuture<'static>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n{\n\n HttpClient::shared().get_async(uri)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 43, "score": 104010.36627856034 }, { "content": "#[test]\n\nfn trailer_headers_timeout() {\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").unwrap();\n\n let url = format!(\"http://{}\", listener.local_addr().unwrap());\n\n\n\n thread::spawn(move || {\n\n let mut stream = listener.accept().unwrap().0;\n\n stream.set_nodelay(true).unwrap();\n\n\n\n consume_request_in_background(&stream);\n\n\n\n stream\n\n .write_all(\n\n b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n transfer-encoding: chunked\\r\\n\\\n\n trailer: foo\\r\\n\\\n\n \\r\\n\",\n\n )\n\n .unwrap();\n\n\n", "file_path": "tests/headers.rs", "rank": 44, "score": 100862.24283226635 }, { "content": "#[test]\n\nfn metrics_are_disabled_by_default() {\n\n let m = mock!();\n\n\n\n let response = isahc::get(m.url()).unwrap();\n\n\n\n assert!(!m.requests().is_empty());\n\n assert!(response.metrics().is_none());\n\n}\n\n\n", "file_path": "tests/metrics.rs", "rank": 45, "score": 100837.54723356369 }, { "content": "/// Parse the given `Location` header value into a string.\n\nfn parse_location(location: &HeaderValue) -> Result<Cow<'_, str>, ToStrError> {\n\n match location.to_str() {\n\n // This will return a `str` if the header value contained only legal\n\n // US-ASCII characters.\n\n Ok(s) => Ok(Cow::Borrowed(s)),\n\n\n\n // Try to parse the location as UTF-8 bytes instead of US-ASCII. This is\n\n // technically against the URI spec which requires all literal\n\n // characters in the URI to be US-ASCII (see [RFC 3986, Section\n\n // 4.1](https://tools.ietf.org/html/rfc3986#section-4.1)).\n\n //\n\n // This is also more or less against the HTTP spec, which historically\n\n // allowed for ISO-8859-1 text in header values but since was restricted\n\n // to US-ASCII plus opaque bytes. Never has UTF-8 been encouraged or\n\n // allowed as-such. See [RFC 7230, Section\n\n // 3.2.4](https://tools.ietf.org/html/rfc7230#section-3.2.4) for more\n\n // info.\n\n //\n\n // However, some bad or misconfigured web servers will do this anyway,\n\n // and most web browsers recover from this by allowing and interpreting\n", "file_path": "src/redirect.rs", "rank": 46, "score": 100250.16191063053 }, { "content": "#[test]\n\nfn accept_headers_populated_by_default() {\n\n let m = mock!();\n\n\n\n isahc::get(m.url()).unwrap();\n\n\n\n m.request().expect_header(\"accept\", \"*/*\");\n\n m.request()\n\n .expect_header(\"accept-encoding\", \"deflate, gzip\");\n\n}\n\n\n", "file_path": "tests/headers.rs", "rank": 47, "score": 98392.21310630094 }, { "content": "#[test]\n\nfn expect_header_is_sent_by_default() {\n\n let m = mock!();\n\n\n\n let body = Body::from_reader(\"hello world\".as_bytes());\n\n\n\n isahc::post(m.url(), body).unwrap();\n\n\n\n m.request().expect_header(\"expect\", \"100-continue\");\n\n}\n\n\n", "file_path": "tests/expect.rs", "rank": 48, "score": 98392.21310630094 }, { "content": "#[test]\n\nfn any_ip_version_uses_ipv4_or_ipv6() {\n\n // Create an IPv4 listener.\n\n let server_v4 = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();\n\n let port = server_v4.local_addr().unwrap().port();\n\n\n\n // Create an IPv6 listener on the same port.\n\n let server_v6 = TcpListener::bind((Ipv6Addr::LOCALHOST, port)).unwrap();\n\n\n\n fn respond(client: &mut TcpStream, response: &[u8]) -> io::Result<()> {\n\n client.read(&mut [0; 8192])?;\n\n client.write_all(response)?;\n\n client.flush()?;\n\n client.shutdown(Shutdown::Both)\n\n }\n\n\n\n // Each server response with a string indicating which address family used.\n\n thread::spawn(move || {\n\n let (mut client, _) = server_v4.accept().unwrap();\n\n respond(\n\n &mut client,\n", "file_path": "tests/net.rs", "rank": 49, "score": 96136.42666303997 }, { "content": "#[test]\n\nfn override_client_default_user_agent() {\n\n let m = mock!();\n\n\n\n let client = HttpClient::builder()\n\n .default_header(\"user-agent\", \"foo\")\n\n .build()\n\n .unwrap();\n\n\n\n client.get(m.url()).unwrap();\n\n\n\n m.request().expect_header(\"user-agent\", \"foo\");\n\n}\n\n\n\n// Issue [#205](https://github.com/sagebind/isahc/issues/205)\n", "file_path": "tests/headers.rs", "rank": 50, "score": 96097.40553960697 }, { "content": "/// Send a POST request to the given URI asynchronously with a given request\n\n/// body.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::post_async`] for details.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {\n\n/// use isahc::prelude::*;\n\n///\n\n/// let mut response = isahc::post_async(\"https://httpbin.org/post\", r#\"{\n\n/// \"speed\": \"fast\",\n\n/// \"cool_name\": true\n\n/// }\"#).await?;\n\n///\n\n/// let mut body: Vec<u8> = vec![];\n\n/// response.copy_to(&mut body).await?;\n\n///\n\n/// let msg: serde_json::Value = serde_json::from_slice(&body)?;\n\n/// println!(\"{}\", msg);\n\n/// # Ok(()) }\n\n/// ```\n\npub fn post_async<U, B>(uri: U, body: B) -> ResponseFuture<'static>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n B: Into<AsyncBody>,\n\n{\n\n HttpClient::shared().post_async(uri, body)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 51, "score": 93976.21646307777 }, { "content": "/// Send an HTTP request and return the HTTP response asynchronously.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::send_async`] for details.\n\npub fn send_async<B: Into<AsyncBody>>(request: Request<B>) -> ResponseFuture<'static> {\n\n HttpClient::shared().send_async(request)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 52, "score": 93961.66688667404 }, { "content": "/// Send a PUT request to the given URI asynchronously with a given request\n\n/// body.\n\n///\n\n/// The request is executed using a shared [`HttpClient`] instance. See\n\n/// [`HttpClient::put_async`] for details.\n\npub fn put_async<U, B>(uri: U, body: B) -> ResponseFuture<'static>\n\nwhere\n\n http::Uri: TryFrom<U>,\n\n <http::Uri as TryFrom<U>>::Error: Into<http::Error>,\n\n B: Into<AsyncBody>,\n\n{\n\n HttpClient::shared().put_async(uri, body)\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 53, "score": 93961.60461085953 }, { "content": "#[test]\n\nfn response_body_with_chunked_encoding_has_unknown_size() {\n\n let m = mock! {\n\n body: \"hello world\",\n\n transfer_encoding: true,\n\n };\n\n\n\n let response = isahc::get(m.url()).unwrap();\n\n\n\n assert_eq!(response.body().len(), None);\n\n}\n\n\n\n// See issue #341.\n", "file_path": "tests/response_body.rs", "rank": 54, "score": 91921.52431294534 }, { "content": "#[test]\n\nfn response_body_with_content_length_knows_its_size() {\n\n let m = mock! {\n\n body: \"hello world\",\n\n };\n\n\n\n let response = isahc::get(m.url()).unwrap();\n\n\n\n assert_eq!(response.body().len(), Some(11));\n\n}\n\n\n", "file_path": "tests/response_body.rs", "rank": 55, "score": 91921.52431294534 }, { "content": "#[derive(Default)]\n\nstruct IntHasher([u8; 8], #[cfg(debug_assertions)] bool);\n\n\n\nimpl Hasher for IntHasher {\n\n fn write(&mut self, bytes: &[u8]) {\n\n #[cfg(debug_assertions)]\n\n {\n\n if self.1 {\n\n panic!(\"socket hash function can only be written to once\");\n\n } else {\n\n self.1 = true;\n\n }\n\n\n\n if bytes.len() > 8 {\n\n panic!(\"only a maximum of 8 bytes can be hashed\");\n\n }\n\n }\n\n\n\n (&mut self.0[..bytes.len()]).copy_from_slice(bytes);\n\n }\n\n\n\n #[inline]\n\n fn finish(&self) -> u64 {\n\n u64::from_ne_bytes(self.0)\n\n }\n\n}\n", "file_path": "src/agent/selector.rs", "rank": 56, "score": 91720.46330627924 }, { "content": "/// Resolve one URI in terms of another.\n\nfn resolve(base: &Uri, target: &str) -> Result<Uri, Box<dyn std::error::Error>> {\n\n // Optimistically check if this is an absolute URI.\n\n match Url::parse(target) {\n\n Ok(url) => Ok(Uri::try_from(url.as_str())?),\n\n\n\n // Relative URI, resolve against the base.\n\n Err(url::ParseError::RelativeUrlWithoutBase) => {\n\n let base = Url::parse(base.to_string().as_str())?;\n\n\n\n Ok(Uri::try_from(base.join(target)?.as_str())?)\n\n }\n\n\n\n Err(e) => Err(Box::new(e)),\n\n }\n\n}\n", "file_path": "src/redirect.rs", "rank": 57, "score": 91063.06818232802 }, { "content": "fn poller_add(poller: &Poller, socket: Socket, readable: bool, writable: bool) -> io::Result<()> {\n\n // If this errors, we retry the operation as a modification instead. This is\n\n // because this new socket might re-use a file descriptor that was\n\n // previously closed, but is still registered with the poller. Retrying the\n\n // operation as a modification is sufficient to handle this.\n\n //\n\n // This is especially common with the epoll backend.\n\n if let Err(e) = poller.add(socket, Event {\n\n key: socket as usize,\n\n readable,\n\n writable,\n\n }) {\n\n tracing::debug!(\n\n \"failed to add interest for socket {}, retrying as a modify: {}\",\n\n socket,\n\n e\n\n );\n\n poller.modify(socket, Event {\n\n key: socket as usize,\n\n readable,\n\n writable,\n\n })?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/agent/selector.rs", "rank": 58, "score": 90916.33314281702 }, { "content": "// http://tools.ietf.org/html/rfc6265#section-5.1.4\n\nfn default_path(uri: &Uri) -> &str {\n\n // Step 2\n\n if !uri.path().starts_with('/') {\n\n return \"/\";\n\n }\n\n\n\n // Step 3\n\n let rightmost_slash_idx = uri.path().rfind('/').unwrap();\n\n if rightmost_slash_idx == 0 {\n\n // There's only one slash; it's the first character.\n\n return \"/\";\n\n }\n\n\n\n // Step 4\n\n &uri.path()[..rightmost_slash_idx]\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n", "file_path": "src/cookies/jar.rs", "rank": 59, "score": 89754.85749772296 }, { "content": "#[test_case(\"GET\")]\n\n#[test_case(\"HEAD\")]\n\n#[test_case(\"POST\")]\n\n#[test_case(\"PUT\")]\n\n#[test_case(\"DELETE\")]\n\n#[test_case(\"PATCH\")]\n\n#[test_case(\"FOOBAR\")]\n\nfn request_with_body_of_known_size(method: &str) {\n\n let body = \"MyVariableOne=ValueOne&MyVariableTwo=ValueTwo\";\n\n\n\n let m = mock!();\n\n\n\n Request::builder()\n\n .method(method)\n\n .uri(m.url())\n\n .header(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n .body(body)\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(m.request().method, method);\n\n m.request()\n\n .expect_header(\"content-length\", body.len().to_string());\n\n m.request()\n\n .expect_header(\"content-type\", \"application/x-www-form-urlencoded\");\n\n m.request().expect_body(body);\n\n}\n\n\n", "file_path": "tests/request_body.rs", "rank": 60, "score": 88958.2293856461 }, { "content": "#[derive(Debug, Default)]\n\nstruct Shared {\n\n /// Set to the final result of the transfer received from curl. This is used\n\n /// to communicate an error while reading the response body if the handler\n\n /// suddenly aborts.\n\n result: OnceCell<Result<(), Error>>,\n\n}\n\n\n\nimpl RequestHandler {\n\n /// Create a new request handler and an associated response future.\n\n pub(crate) fn new(\n\n request_body: AsyncBody,\n\n ) -> (\n\n Self,\n\n impl Future<Output = Result<Response<ResponseBodyReader>, Error>>,\n\n ) {\n\n let (sender, receiver) = async_channel::bounded(1);\n\n let shared = Arc::new(Shared::default());\n\n let (response_body_reader, response_body_writer) = pipe::pipe();\n\n\n\n let handler = Self {\n", "file_path": "src/handler.rs", "rank": 61, "score": 75086.19009710944 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct Options {\n\n url: http::Uri,\n\n}\n\n\n", "file_path": "examples/progress.rs", "rank": 62, "score": 75086.14214382404 }, { "content": "#[derive(Debug)]\n\nstruct Shared {\n\n headers: OnceCell<HeaderMap>,\n\n ready: Event,\n\n}\n\n\n\nimpl Trailer {\n\n /// Get a populated trailer handle containing no headers.\n\n pub(crate) fn empty() -> &'static Self {\n\n static EMPTY: OnceCell<Trailer> = OnceCell::new();\n\n\n\n EMPTY.get_or_init(|| Self {\n\n shared: Arc::new(Shared {\n\n headers: OnceCell::from(HeaderMap::new()),\n\n ready: Event::new(),\n\n }),\n\n })\n\n }\n\n\n\n /// Returns true if the trailer has been received (if any).\n\n ///\n", "file_path": "src/trailer.rs", "rank": 63, "score": 75081.39263654356 }, { "content": "struct Inner {\n\n /// This is how we talk to our background agent thread.\n\n agent: agent::Handle,\n\n\n\n /// Client-wide request configuration.\n\n client_config: ClientConfig,\n\n\n\n /// Default request configuration to use if not specified in a request.\n\n request_config: RequestConfig,\n\n\n\n /// Registered interceptors that requests should pass through.\n\n interceptors: Vec<InterceptorObj>,\n\n\n\n /// Configured cookie jar, if any.\n\n #[cfg(feature = \"cookies\")]\n\n cookie_jar: Option<crate::cookies::CookieJar>,\n\n}\n\n\n\nimpl HttpClient {\n\n /// Create a new HTTP client using the default configuration.\n", "file_path": "src/client.rs", "rank": 64, "score": 75076.53315442704 }, { "content": "struct Inner {\n\n kind: ErrorKind,\n\n context: Option<String>,\n\n source: Option<Box<dyn SourceError>>,\n\n local_addr: OnceCell<SocketAddr>,\n\n remote_addr: OnceCell<SocketAddr>,\n\n}\n\n\n\nimpl Error {\n\n /// Create a new error from a given error kind and source error.\n\n pub(crate) fn new<E>(kind: ErrorKind, source: E) -> Self\n\n where\n\n E: StdError + Send + Sync + 'static,\n\n {\n\n Self::with_context(kind, None, source)\n\n }\n\n\n\n /// Create a new error from a given error kind, source error, and context\n\n /// string.\n\n pub(crate) fn with_context<E>(kind: ErrorKind, context: Option<String>, source: E) -> Self\n", "file_path": "src/error.rs", "rank": 65, "score": 75076.53315442704 }, { "content": "/// Information stored about each registered socket.\n\nstruct Registration {\n\n readable: bool,\n\n writable: bool,\n\n tick: usize,\n\n}\n\n\n\nimpl Selector {\n\n /// Create a new socket selector.\n\n pub(crate) fn new() -> io::Result<Self> {\n\n Ok(Self {\n\n poller: Arc::new(Poller::new()?),\n\n sockets: HashMap::with_hasher(Default::default()),\n\n bad_sockets: HashSet::with_hasher(Default::default()),\n\n events: Vec::new(),\n\n tick: 0,\n\n })\n\n }\n\n\n\n /// Get a task waker that will interrupt this selector whenever it is\n\n /// waiting for activity.\n", "file_path": "src/agent/selector.rs", "rank": 66, "score": 73660.96582495703 }, { "content": "/// Response body stream. Holds a reference to the agent to ensure it is kept\n\n/// alive until at least this transfer is complete.\n\nstruct ResponseBody {\n\n inner: ResponseBodyReader,\n\n _client: HttpClient,\n\n}\n\n\n\nimpl AsyncRead for ResponseBody {\n\n fn poll_read(\n\n mut self: Pin<&mut Self>,\n\n cx: &mut Context<'_>,\n\n buf: &mut [u8],\n\n ) -> Poll<io::Result<usize>> {\n\n let inner = Pin::new(&mut self.inner);\n\n inner.poll_read(cx, buf)\n\n }\n\n}\n\n\n", "file_path": "src/client.rs", "rank": 67, "score": 73660.96582495703 }, { "content": "#[derive(Debug)]\n\nstruct CookieWithContext {\n\n /// The domain-value of the cookie, as defined in RFC 6265. Will be derived\n\n /// from the request URI if the cookie did not specify one.\n\n domain_value: String,\n\n\n\n /// The path-value of the cookie, as defined in RFC 6265. Will be derived\n\n /// from the request URI if the cookie did not specify one.\n\n path_value: String,\n\n\n\n // The original cookie.\n\n cookie: Cookie,\n\n}\n\n\n\nimpl CookieWithContext {\n\n /// True if the cookie is a host-only cookie (i.e. the request's host must\n\n /// exactly match the domain of the cookie).\n\n fn is_host_only(&self) -> bool {\n\n self.cookie.domain().is_none()\n\n }\n\n\n", "file_path": "src/cookies/jar.rs", "rank": 68, "score": 72343.11128890133 }, { "content": "#[derive(Debug, serde::Serialize)]\n\n#[serde(rename_all = \"UPPERCASE\")]\n\nstruct ShoutCloudRequest {\n\n input: String,\n\n}\n\n\n", "file_path": "examples/json.rs", "rank": 69, "score": 72342.88877906953 }, { "content": "#[derive(Debug, serde::Deserialize)]\n\n#[serde(rename_all = \"UPPERCASE\")]\n\nstruct ShoutCloudResponse {\n\n input: String,\n\n output: String,\n\n}\n\n\n", "file_path": "examples/json.rs", "rank": 70, "score": 72342.88877906953 }, { "content": "/// Internal state of an agent thread.\n\n///\n\n/// The agent thread runs the primary client event loop, which is essentially a\n\n/// traditional curl multi event loop with some extra bookkeeping and async\n\n/// features like wakers.\n\nstruct AgentContext {\n\n /// A curl multi handle, of course.\n\n multi: curl::multi::Multi,\n\n\n\n /// Used to send messages to the agent thread.\n\n message_tx: Sender<Message>,\n\n\n\n /// Incoming messages from the agent handle.\n\n message_rx: Receiver<Message>,\n\n\n\n /// Contains all of the active requests.\n\n requests: Slab<curl::multi::Easy2Handle<RequestHandler>>,\n\n\n\n /// Indicates if the thread has been requested to stop.\n\n close_requested: bool,\n\n\n\n /// A waker that can wake up the agent thread while it is polling.\n\n waker: Waker,\n\n\n\n /// This is the poller we use to poll for socket activity!\n\n selector: Selector,\n\n\n\n /// A timer we use to keep track of curl's timeouts.\n\n timer: Arc<Timer>,\n\n\n\n /// Queue of socket registration updates from the multi handle.\n\n socket_updates: Receiver<(Socket, SocketEvents, usize)>,\n\n}\n\n\n\n/// A message sent from the main thread to the agent thread.\n", "file_path": "src/agent/mod.rs", "rank": 71, "score": 72338.25180678481 }, { "content": "struct ListCache {\n\n list: List,\n\n last_refreshed: Option<SystemTime>,\n\n last_updated: Option<SystemTime>,\n\n}\n\n\n\nimpl Default for ListCache {\n\n fn default() -> Self {\n\n Self {\n\n // Use a bundled version of the list. We bundle using a Git\n\n // submodule instead of downloading it from the Internet during the\n\n // build, because that would force you to have an active Internet\n\n // connection in order to compile. And that would be really\n\n // annoying, especially if you are on a slow connection.\n\n list: include_str!(\"list/public_suffix_list.dat\")\n\n .parse()\n\n .expect(\"could not parse bundled public suffix list\"),\n\n\n\n // Refresh the list right away.\n\n last_refreshed: None,\n", "file_path": "src/cookies/psl/mod.rs", "rank": 72, "score": 71099.54523169194 }, { "content": "type InterceptorResult<E> = Result<Response<AsyncBody>, E>;\n\n\n\n/// Defines an inline interceptor using a closure-like syntax.\n\n///\n\n/// Closures are not supported due to a limitation in Rust's type inference.\n\n#[cfg(feature = \"unstable-interceptors\")]\n\n#[macro_export]\n\nmacro_rules! interceptor {\n\n ($request:ident, $ctx:ident, $body:expr) => {{\n\n async fn interceptor(\n\n mut $request: $crate::http::Request<$crate::AsyncBody>,\n\n $ctx: $crate::interceptor::Context<'_>,\n\n ) -> Result<$crate::http::Response<$crate::AsyncBody>, $crate::Error> {\n\n (move || async move { $body })().await.map_err(Into::into)\n\n }\n\n\n\n $crate::interceptor::from_fn(interceptor)\n\n }};\n\n}\n\n\n", "file_path": "src/interceptor/mod.rs", "rank": 73, "score": 67599.10214117929 }, { "content": "/// Object-safe version of the interceptor used for type erasure. Implementation\n\n/// detail of [`InterceptorObj`].\n\ntrait DynInterceptor: Send + Sync {\n\n fn dyn_intercept<'a>(\n\n &'a self,\n\n request: Request<AsyncBody>,\n\n cx: Context<'a>,\n\n ) -> InterceptorFuture<'a, Error>;\n\n}\n\n\n\nimpl<I: Interceptor> DynInterceptor for I {\n\n fn dyn_intercept<'a>(\n\n &'a self,\n\n request: Request<AsyncBody>,\n\n cx: Context<'a>,\n\n ) -> InterceptorFuture<'a, Error> {\n\n Box::pin(async move { self.intercept(request, cx).await.map_err(Error::from_any) })\n\n }\n\n}\n", "file_path": "src/interceptor/obj.rs", "rank": 74, "score": 65930.56085805074 }, { "content": "struct GrowableBufReader<R: Read> {\n\n inner: R,\n\n buffer: Vec<u8>,\n\n low: usize,\n\n high: usize,\n\n}\n\n\n\nimpl<R: Read> GrowableBufReader<R> {\n\n fn new(inner: R) -> Self {\n\n Self {\n\n inner,\n\n buffer: Vec::with_capacity(8192),\n\n low: 0,\n\n high: 0,\n\n }\n\n }\n\n\n\n #[inline]\n\n fn available(&self) -> usize {\n\n self.high - self.low\n", "file_path": "testserver/src/server.rs", "rank": 75, "score": 64699.83081830964 }, { "content": "#[test]\n\nfn no_proxy() {\n\n let m = mock!();\n\n\n\n Request::get(m.url())\n\n .proxy(None)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(m.requests().len(), 1);\n\n}\n\n\n", "file_path": "tests/proxy.rs", "rank": 76, "score": 64436.076910336866 }, { "content": "fn main() {\n\n // accept expired cert\n\n Request::get(\"https://expired.badssl.com\")\n\n .ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .expect(\"cert should have been accepted\");\n\n\n\n // accepting invalid certs alone does not allow invalid hosts\n\n Request::get(\"https://wrong.host.badssl.com\")\n\n .ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .expect_err(\"cert should have been rejected\");\n\n\n\n // accept cert with wrong host\n\n Request::get(\"https://wrong.host.badssl.com\")\n\n .ssl_options(SslOption::DANGER_ACCEPT_INVALID_HOSTS)\n", "file_path": "examples/badssl.rs", "rank": 77, "score": 64436.076910336866 }, { "content": "fn main() {\n\n println!(\"version: {}\", isahc::version());\n\n}\n", "file_path": "examples/version.rs", "rank": 78, "score": 64436.076910336866 }, { "content": "#[test]\n\nfn head_request() {\n\n let m = mock!();\n\n\n\n isahc::head(m.url()).unwrap();\n\n\n\n assert_eq!(m.request().method, \"HEAD\");\n\n}\n\n\n", "file_path": "tests/methods.rs", "rank": 79, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn response_301_no_follow() {\n\n let m = mock! {\n\n status: 301,\n\n headers {\n\n \"Location\": \"/2\",\n\n }\n\n };\n\n\n\n let response = isahc::get(m.url()).unwrap();\n\n\n\n assert_eq!(response.status(), 301);\n\n assert_eq!(response.headers()[\"Location\"], \"/2\");\n\n assert_eq!(response.effective_uri().unwrap().path(), \"/\");\n\n\n\n assert!(!m.requests().is_empty());\n\n}\n\n\n", "file_path": "tests/redirects.rs", "rank": 80, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn http_proxy() {\n\n // URI of our test server, which we will treat as a proxy.\n\n let m = mock!();\n\n let proxy = m.url().parse::<http::Uri>().unwrap();\n\n\n\n // Fake upstream URI to connect to.\n\n let upstream = \"http://127.0.0.2:1234/\".parse::<http::Uri>().unwrap();\n\n\n\n Request::get(upstream.clone())\n\n .proxy(proxy)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n // We should receive the request instead, following the HTTP proxy\n\n // protocol. The request-target should be the absolute URI of our\n\n // upstream request target (see [RFC\n\n // 7230](https://tools.ietf.org/html/rfc7230), sections 5.3 and 5.7).\n\n assert_eq!(m.request().url, upstream.to_string());\n\n // Host should be the upstream authority, not the proxy host.\n\n m.request()\n\n .expect_header(\"host\", upstream.authority().unwrap().as_str());\n\n m.request().expect_header(\"proxy-connection\", \"Keep-Alive\");\n\n}\n\n\n", "file_path": "tests/proxy.rs", "rank": 81, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn deserialize_json() {\n\n let m = mock! {\n\n body: r#\"{\n\n \"foo\": \"bar\"\n\n }\"#,\n\n };\n\n\n\n let mut response = isahc::get(m.url()).unwrap();\n\n let data = response.json::<Value>().unwrap();\n\n\n\n assert_eq!(data[\"foo\"], \"bar\");\n\n}\n\n\n", "file_path": "tests/json.rs", "rank": 82, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn put_request() {\n\n let m = mock!();\n\n\n\n isahc::put(m.url(), ()).unwrap();\n\n\n\n assert_eq!(m.request().method, \"PUT\");\n\n}\n\n\n", "file_path": "tests/methods.rs", "rank": 83, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn get_request() {\n\n let m = mock!();\n\n\n\n isahc::get(m.url()).unwrap();\n\n\n\n assert_eq!(m.request().method, \"GET\");\n\n}\n\n\n", "file_path": "tests/methods.rs", "rank": 84, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn post_request() {\n\n let m = mock!();\n\n\n\n isahc::post(m.url(), ()).unwrap();\n\n\n\n assert_eq!(m.request().method, \"POST\");\n\n}\n\n\n", "file_path": "tests/methods.rs", "rank": 85, "score": 63059.2532618261 }, { "content": "#[test]\n\n#[cfg_attr(tarpaulin, ignore)]\n\nfn socks4_proxy() {\n\n // Set up a simple SOCKS4 proxy.\n\n let proxy_server = Socks4Server::new(\"127.0.0.1:0\").unwrap();\n\n\n\n // Create the proxy URI for our listener.\n\n let proxy_uri = http::Uri::builder()\n\n .scheme(\"socks4\")\n\n .authority(proxy_server.addr().to_string().as_str())\n\n .path_and_query(\"/\")\n\n .build()\n\n .unwrap();\n\n\n\n // Run the proxy server in the background.\n\n proxy_server.spawn();\n\n\n\n // Set up our upstream HTTP test server.\n\n let m = mock!();\n\n\n\n // Send a request...\n\n Request::get(m.url())\n", "file_path": "tests/proxy.rs", "rank": 86, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn cookie_lifecycle() {\n\n let jar = CookieJar::default();\n\n let client = HttpClient::builder()\n\n .cookie_jar(jar.clone())\n\n .build()\n\n .unwrap();\n\n\n\n let m1 = mock! {\n\n headers {\n\n \"set-cookie\": \"foo=bar\",\n\n \"set-cookie\": \"baz=123\",\n\n }\n\n };\n\n let m2 = mock!();\n\n\n\n let response1 = client.get(m1.url()).unwrap();\n\n\n\n assert!(response1.cookie_jar().is_some());\n\n\n\n let response2 = client.get(m2.url()).unwrap();\n\n\n\n assert!(response2.cookie_jar().is_some());\n\n\n\n dbg!(m2.request()).expect_header(\"cookie\", \"baz=123; foo=bar\");\n\n}\n", "file_path": "tests/cookies.rs", "rank": 87, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn delete_request() {\n\n let m = mock!();\n\n\n\n isahc::delete(m.url()).unwrap();\n\n\n\n assert_eq!(m.request().method, \"DELETE\");\n\n}\n\n\n", "file_path": "tests/methods.rs", "rank": 88, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn trailer_headers() {\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").unwrap();\n\n let url = format!(\"http://{}\", listener.local_addr().unwrap());\n\n\n\n thread::spawn(move || {\n\n let mut stream = listener.accept().unwrap().0;\n\n\n\n consume_request_in_background(&stream);\n\n\n\n stream\n\n .write_all(\n\n b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n transfer-encoding: chunked\\r\\n\\\n\n trailer: foo\\r\\n\\\n\n \\r\\n\\\n\n 2\\r\\n\\\n\n OK\\r\\n\\\n\n 0\\r\\n\\\n\n foo: bar\\r\\n\\\n", "file_path": "tests/headers.rs", "rank": 89, "score": 63059.2532618261 }, { "content": "#[test]\n\nfn redirect_limit_is_respected() {\n\n let m = mock! {\n\n status: 301,\n\n headers {\n\n \"Location\": \"/next\",\n\n }\n\n };\n\n\n\n let error = Request::get(m.url())\n\n .redirect_policy(RedirectPolicy::Limit(5))\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap_err();\n\n\n\n // Request should error with too many redirects.\n\n assert_eq!(error, isahc::error::ErrorKind::TooManyRedirects);\n\n assert_eq!(error.remote_addr(), Some(m.addr()));\n\n\n\n // After request (limit + 1) that returns a redirect should error.\n\n assert_eq!(m.requests().len(), 6);\n\n}\n\n\n", "file_path": "tests/redirects.rs", "rank": 90, "score": 61772.7415555139 }, { "content": "#[cfg(feature = \"spnego\")]\n\n#[test]\n\nfn negotiate_auth_exists() {\n\n let m = mock! {\n\n status: 401,\n\n headers {\n\n \"WWW-Authenticate\": \"Negotiate\",\n\n }\n\n };\n\n\n\n Request::get(m.url())\n\n .authentication(Authentication::negotiate())\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert!(!m.requests().is_empty());\n\n}\n\n\n", "file_path": "tests/auth.rs", "rank": 91, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn redirect_with_response_body() {\n\n let m2 = mock! {\n\n body: \"OK\",\n\n };\n\n let location = m2.url();\n\n\n\n let m1 = mock! {\n\n status: 302,\n\n headers {\n\n \"Location\": location,\n\n }\n\n body: \"REDIRECT\",\n\n };\n\n\n\n let response = Request::post(m1.url())\n\n .redirect_policy(RedirectPolicy::Follow)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(response.status(), 200);\n\n assert_eq!(response.effective_uri().unwrap().to_string(), m2.url());\n\n\n\n assert_eq!(m1.request().method, \"POST\");\n\n assert_eq!(m2.request().method, \"GET\");\n\n}\n\n\n\n// Issue #250\n", "file_path": "tests/redirects.rs", "rank": 92, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn proxy_blacklist_works() {\n\n // This time, the proxy is the fake one.\n\n let proxy = \"http://127.0.0.2:1234/\".parse::<http::Uri>().unwrap();\n\n\n\n // Our test server is upstream (we don't expect the proxy to be used).\n\n let m = mock!();\n\n let upstream = m.url().parse::<http::Uri>().unwrap();\n\n\n\n Request::get(&upstream)\n\n .proxy(proxy)\n\n // Exclude our upstream from the proxy we set.\n\n .proxy_blacklist(Some(upstream.host().unwrap().to_string()))\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(m.requests().len(), 1);\n\n}\n", "file_path": "tests/proxy.rs", "rank": 93, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn arbitrary_foobar_request() {\n\n let m = mock!();\n\n\n\n Request::builder()\n\n .method(\"FOOBAR\")\n\n .uri(m.url())\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(m.request().method, \"FOOBAR\");\n\n}\n", "file_path": "tests/methods.rs", "rank": 94, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn trailer_headers_async() {\n\n let listener = TcpListener::bind(\"127.0.0.1:0\").unwrap();\n\n let url = format!(\"http://{}\", listener.local_addr().unwrap());\n\n\n\n thread::spawn(move || {\n\n let mut stream = listener.accept().unwrap().0;\n\n\n\n consume_request_in_background(&stream);\n\n\n\n stream\n\n .write_all(\n\n b\"\\\n\n HTTP/1.1 200 OK\\r\\n\\\n\n transfer-encoding: chunked\\r\\n\\\n\n trailer: foo\\r\\n\\\n\n \\r\\n\\\n\n 2\\r\\n\\\n\n OK\\r\\n\\\n\n 0\\r\\n\\\n\n foo: bar\\r\\n\\\n", "file_path": "tests/headers.rs", "rank": 95, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn response_301_auto_follow() {\n\n let m2 = mock! {\n\n status: 200,\n\n body: \"ok\",\n\n };\n\n let location = m2.url();\n\n\n\n let m1 = mock! {\n\n status: 301,\n\n headers {\n\n \"Location\": location,\n\n }\n\n };\n\n\n\n let mut response = Request::get(m1.url())\n\n .redirect_policy(RedirectPolicy::Follow)\n\n .body(())\n\n .unwrap()\n\n .send()\n\n .unwrap();\n\n\n\n assert_eq!(response.status(), 200);\n\n assert_eq!(response.text().unwrap(), \"ok\");\n\n assert_eq!(response.effective_uri().unwrap().to_string(), m2.url());\n\n\n\n assert!(!m1.requests().is_empty());\n\n assert!(!m2.requests().is_empty());\n\n}\n\n\n", "file_path": "tests/redirects.rs", "rank": 96, "score": 61772.7415555139 }, { "content": "fn poller_modify(\n\n poller: &Poller,\n\n socket: Socket,\n\n readable: bool,\n\n writable: bool,\n\n) -> io::Result<()> {\n\n // If this errors, we retry the operation as an add instead. This is done\n\n // because epoll is weird.\n\n if let Err(e) = poller.modify(socket, Event {\n\n key: socket as usize,\n\n readable,\n\n writable,\n\n }) {\n\n tracing::debug!(\n\n \"failed to modify interest for socket {}, retrying as an add: {}\",\n\n socket,\n\n e\n\n );\n\n poller.add(socket, Event {\n\n key: socket as usize,\n\n readable,\n\n writable,\n\n })?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/agent/selector.rs", "rank": 97, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn deserialize_json_async() {\n\n let m = mock! {\n\n body: r#\"{\n\n \"foo\": \"bar\"\n\n }\"#,\n\n };\n\n\n\n block_on(async move {\n\n let mut response = isahc::get_async(m.url()).await.unwrap();\n\n let data = response.json::<Value>().await.unwrap();\n\n\n\n assert_eq!(data[\"foo\"], \"bar\");\n\n });\n\n}\n\n\n", "file_path": "tests/json.rs", "rank": 98, "score": 61772.7415555139 }, { "content": "#[test]\n\nfn redirect_policy_from_client() {\n\n let m2 = mock!();\n\n let location = m2.url();\n\n\n\n let m1 = mock! {\n\n status: 302,\n\n headers {\n\n \"Location\": location,\n\n }\n\n };\n\n\n\n let client = HttpClient::builder()\n\n .redirect_policy(RedirectPolicy::Limit(8))\n\n .build()\n\n .unwrap();\n\n\n\n let response = client.post(m1.url(), ()).unwrap();\n\n\n\n assert_eq!(response.status(), 200);\n\n assert_eq!(response.effective_uri().unwrap().to_string(), m2.url());\n\n\n\n assert_eq!(m1.request().method, \"POST\");\n\n assert_eq!(m2.request().method, \"GET\");\n\n}\n\n\n", "file_path": "tests/redirects.rs", "rank": 99, "score": 61772.7415555139 } ]
Rust
src/barcodeservice.rs
kalkspace/getraenkekassengeraete
39248dc3a0c6a3ae1b285e8a3f964cfe81775460
use async_stream::stream; use futures_core::stream::Stream; use libc::ioctl; use log::{error, warn}; use std::convert::TryFrom; use std::error::Error; use std::fs::File; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use tokio::io::AsyncReadExt; use tokio::time::{sleep, Duration}; use tokio_fd::AsyncFd; fn u8_8(u: &[u8]) -> [u8; 8] { [u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7]] } fn u8_4(u: &[u8]) -> [u8; 4] { [u[0], u[1], u[2], u[3]] } fn u8_2(u: &[u8]) -> [u8; 2] { [u[0], u[1]] } const EVIOCGRAB: u64 = 1074021776; fn create_input_event(buf: &[u8]) -> libc::input_event { libc::input_event { time: libc::timeval { tv_sec: i64::from_le_bytes(u8_8(&buf[0..8])), tv_usec: i64::from_le_bytes(u8_8(&buf[8..16])), }, type_: u16::from_le_bytes(u8_2(&buf[16..18])), code: u16::from_le_bytes(u8_2(&buf[18..20])), value: i32::from_le_bytes(u8_4(&buf[20..24])), } } struct KeyboardFile { _file: File, fd: AsyncFd, } impl KeyboardFile { pub fn new(dev: &Path) -> Result<KeyboardFile, Box<dyn Error>> { let file = File::open(dev)?; let fd = file.as_raw_fd(); unsafe { ioctl(fd, EVIOCGRAB, 1); } Ok(KeyboardFile { _file: file, fd: AsyncFd::try_from(fd)?, }) } pub fn fd_mut(&mut self) -> &mut AsyncFd { &mut self.fd } } struct BarcodeScanner { dev: PathBuf, keyboard_file: Option<KeyboardFile>, first_sleep_secs: Option<u64>, } impl BarcodeScanner { pub fn new(dev: impl Into<PathBuf>) -> BarcodeScanner { BarcodeScanner { dev: dev.into(), keyboard_file: None, first_sleep_secs: Some(0), } } pub async fn acquire_keyboard_fd(&mut self) -> &mut AsyncFd { if self.keyboard_file.is_none() { let mut sleep_secs = self.first_sleep_secs.take().unwrap_or(1); while self.keyboard_file.is_none() { sleep(Duration::from_secs(sleep_secs)).await; self.keyboard_file = match KeyboardFile::new(&self.dev) { Ok(fd) => Some(fd), Err(e) => { error!("Error accessing keyboard {}", e); if sleep_secs == 0 { sleep_secs = 1; } else { sleep_secs = sleep_secs * 2; if sleep_secs > 4 { sleep_secs = 4; } } None } } } } self.keyboard_file.as_mut().unwrap().fd_mut() } pub async fn try_read_barcode(&mut self) -> Result<String, Box<dyn Error>> { let input_event_size = std::mem::size_of::<libc::input_event>(); let mut buf = [0u8; 2048]; let mut s = String::new(); let fd = self.acquire_keyboard_fd().await; loop { let r = fd.read(&mut buf).await?; if r == 0 { continue; } for event_buf in buf.chunks_exact(input_event_size) { let event = create_input_event(&event_buf); if event.type_ != 1 { continue; } if event.value != 0 { continue; } match event.code { 2 => s += "1", 3 => s += "2", 4 => s += "3", 5 => s += "4", 6 => s += "5", 7 => s += "6", 8 => s += "7", 9 => s += "8", 10 => s += "9", 11 => s += "0", 28 => { if s.len() > 0 { return Ok(s); } warn!("Tried submitting empty barcode. Skipping."); s.clear(); } _ => { warn!("Invalid scancode {}", event.code); s.clear(); } } } } } pub async fn read_barcode(&mut self) -> String { loop { match self.try_read_barcode().await { Ok(s) => return s, Err(e) => { error!("Error reading barcode {}", e); self.keyboard_file = None } } } } } pub fn run(dev: impl Into<PathBuf>) -> impl Stream<Item = String> { stream! { let mut scanner = BarcodeScanner::new(dev); loop { yield scanner.read_barcode().await; } } }
use async_stream::stream; use futures_core::stream::Stream; use libc::ioctl; use log::{error, warn}; use std::convert::TryFrom; use std::error::Error; use std::fs::File; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use tokio::io::AsyncReadExt; use tokio::time::{sleep, Duration}; use tokio_fd::AsyncFd; fn u8_8(u: &[u8]) -> [u8; 8] { [u[0], u[1], u[2], u[3], u[4], u[5], u[6], u[7]] } fn u8_4(u: &[u8]) -> [u8; 4] { [u[0], u[1], u[2], u[3]] } fn u8_2(u: &[u8]) -> [u8; 2] { [u[0], u[1]] } const EVIOCGRAB: u64 = 1074021776; fn create_input_event(buf: &[u8]) -> libc::input_event { libc::input_event { time: libc::timeval { tv_sec: i64::from_le_bytes(u8_8(&buf[0..8])), tv_usec: i64::from_le_bytes(u8_8(&buf[8..16])), }, type_: u16::from_le_bytes(u8_2(&buf[16..18])), code: u16::from_le_bytes(u8_2(&buf[18..20])), value: i32::from_le_bytes(u8_4(&buf[20..24])), } } struct KeyboardFile { _file: File, fd: AsyncFd, } impl KeyboardFile { pub fn new(dev: &Path) -> Result<KeyboardFile, Box<dyn Error>> { let file = File::open(dev)?; let fd = file.as_raw_fd(); unsafe { ioctl(fd, EVIOCGRAB, 1); } Ok(KeyboardFile { _file: file, fd: AsyncFd::try_from(fd)?, }) } pub fn fd_mut(&mut self) -> &mut AsyncFd { &mut self.fd } } struct BarcodeScanner { dev: PathBuf, keyboard_file: Option<KeyboardFile>, first_sleep_secs: Option<u64>, } impl BarcodeScanner { pub fn new(dev: impl Into<PathBuf>) -> BarcodeScanner { BarcodeScanner { dev: dev.into(), keyboard_file: None, first_sleep_secs: Some(0), } } pub async fn acquire_keyboard_fd(&mut self) -> &mut AsyncFd { if self.keyboard_file.is_none() { let mut sleep_secs = self.first_sleep_secs.take().unwrap_or(1); while self.keyboard_file.is_none() { sleep(Duration::from_secs(sleep_secs)).await; self.keyboard_file = match KeyboardFile::new(&self.dev) { Ok(fd) => Some(fd), Err(e) => { error!("Error accessing keyboard {}", e); if sleep_secs == 0 { sleep_secs = 1; } else { sleep_secs = sleep_secs * 2; if sleep_secs > 4 { sleep_secs = 4; } } None } } } } self.keyboard_file.as_mut().unwrap().fd_mut() } pub async fn try_read_barcode(&mut self) -> Result<String, Box<dyn Error>> { let input_event_size = std::mem::size_of::<libc::input_event>(); let mut buf = [0u8; 2048]; let mut s = String::new(); let fd = self.acquire_keyboard_fd().await; loop { let r = fd.read(&mut buf).await?; if r == 0 { continue; } for event_buf in buf.chunks_exact(input_event_size) { let event = create_input_event(&event_buf); if event.type_ != 1 { continue; } if event.value != 0 { continue; } match event.code { 2 => s += "1", 3 => s += "2", 4 => s += "3", 5 => s += "4", 6 => s += "5", 7 => s += "6", 8 => s += "7", 9 => s += "8", 10 => s += "9", 11 => s += "0", 28 => { if s.len() > 0 { return Ok(s); } warn!("Tried submitting empty barcode. Skipping."); s.clear(); } _ => { warn!("Invalid scancode {}", event.code); s.clear(); } } } } } pub async fn read_barcode(&mut self) -> String { loop {
} } } pub fn run(dev: impl Into<PathBuf>) -> impl Stream<Item = String> { stream! { let mut scanner = BarcodeScanner::new(dev); loop { yield scanner.read_barcode().await; } } }
match self.try_read_barcode().await { Ok(s) => return s, Err(e) => { error!("Error reading barcode {}", e); self.keyboard_file = None } }
if_condition
[ { "content": "pub fn run(dev: impl Into<PathBuf>) -> impl Stream<Item = ()> {\n\n stream! {\n\n let mut reader = StornoReader::new(dev);\n\n loop {\n\n yield reader.read_storno().await;\n\n }\n\n }\n\n}\n", "file_path": "src/stornoservice.rs", "rank": 1, "score": 146362.85813021462 }, { "content": "pub fn run() -> Result<impl Stream<Item = Option<CardDetail>>, Box<dyn StdError>> {\n\n let (tx, mut rx) = mpsc::channel(16);\n\n // hmmmm ... creating a new one seems wrong?\n\n let rt = tokio::runtime::Runtime::new()?;\n\n thread::spawn(move || {\n\n let mut service = Service::new();\n\n loop {\n\n match service.fetch_next_uuid() {\n\n Ok(result) => rt.block_on(async {\n\n tx.send(result).await.unwrap();\n\n }),\n\n Err(e) => error!(\"Nfc Error: {:?}\", e),\n\n }\n\n }\n\n });\n\n\n\n Ok(stream! {\n\n while let Some(uuid) = rx.recv().await {\n\n yield uuid;\n\n }\n\n })\n\n}\n", "file_path": "src/nfcservice.rs", "rank": 7, "score": 74510.05662309236 }, { "content": "struct StornoFile {\n\n // we need to keep file in scope to read from fd\n\n _file: File,\n\n fd: AsyncFd,\n\n}\n\n\n\nimpl StornoFile {\n\n pub fn new(dev: &Path) -> Result<StornoFile, Box<dyn Error>> {\n\n let file = File::open(dev)?;\n\n let fd = file.as_raw_fd();\n\n let mut t = termios::tcgetattr(fd)?;\n\n termios::cfsetispeed(&mut t, termios::BaudRate::B9600)?;\n\n Ok(StornoFile {\n\n _file: file,\n\n fd: AsyncFd::try_from(fd)?,\n\n })\n\n }\n\n\n\n pub fn fd_mut(&mut self) -> &mut AsyncFd {\n\n &mut self.fd\n\n }\n\n}\n\n\n", "file_path": "src/stornoservice.rs", "rank": 9, "score": 57048.37833230723 }, { "content": "fn get_uid(card: &Card) -> Result<Option<Vec<u8>>, Box<dyn StdError>> {\n\n let apdu = &[0xFF, 0xCA, 0x00, 0x00, 0x00];\n\n debug!(\"Sending APDU: {:?}\", apdu);\n\n let mut rapdu_buf = [0; MAX_BUFFER_SIZE];\n\n let rapdu = card.transmit(apdu, &mut rapdu_buf)?;\n\n debug!(\"APDU response: {:x?}\", rapdu);\n\n let l = rapdu.len();\n\n // min length 3: at least one u8 as id + successful response\n\n if l < 3 || rapdu[l - 2] != 0x90 || rapdu[l - 1] != 0x00 {\n\n Ok(None)\n\n } else {\n\n Ok(Some(rapdu[0..l - 2].to_vec()))\n\n }\n\n}\n\n\n", "file_path": "src/nfcservice.rs", "rank": 10, "score": 54721.4929060608 }, { "content": "fn cashier_event_stream<'a>(\n\n clients: Clients<'a>,\n\n) -> impl Stream<Item = Result<Event, warp::Error>> + Send + 'a {\n\n // Use a counter to assign a new unique ID for this client.\n\n let my_id = NEXT_CLIENT_ID.fetch_add(1, Ordering::Relaxed);\n\n\n\n // Use an unbounded channel to handle buffering and flushing of messages\n\n // to the event source...\n\n let (tx, rx) = mpsc::unbounded_channel();\n\n let rx = UnboundedReceiverStream::new(rx);\n\n\n\n // Save the sender in our list of connected users.\n\n clients.lock().unwrap().insert(my_id, tx);\n\n\n\n // Convert messages into Server-Sent Events and return resulting stream.\n\n rx.map(|msg| {\n\n Ok(Event::default()\n\n .event((msg.r#type).clone())\n\n .data(serde_json::to_string(&msg.id).unwrap()))\n\n })\n\n}\n", "file_path": "src/main.rs", "rank": 11, "score": 50618.78906801376 }, { "content": "#[derive(Default)]\n\nstruct Service {\n\n ctx: Option<Context>,\n\n reader_states: Vec<ReaderState>,\n\n readers_buf: Vec<u8>,\n\n reconnect_timeout: Duration,\n\n}\n\n\n\nimpl Service {\n\n pub fn new() -> Service {\n\n Service {\n\n reader_states: vec![\n\n // Listen for reader insertions/removals, if supported.\n\n ReaderState::new(PNP_NOTIFICATION(), State::UNAWARE),\n\n ],\n\n readers_buf: vec![0; 2048],\n\n ..Default::default()\n\n }\n\n }\n\n\n\n fn get_context(&mut self) -> Result<Context, Box<dyn StdError>> {\n", "file_path": "src/nfcservice.rs", "rank": 12, "score": 38595.629499648654 }, { "content": "struct StornoReader {\n\n dev: PathBuf,\n\n first_sleep_secs: Option<u64>,\n\n storno_file: Option<StornoFile>,\n\n}\n\n\n\nimpl StornoReader {\n\n pub fn new(dev: impl Into<PathBuf>) -> StornoReader {\n\n StornoReader {\n\n dev: dev.into(),\n\n storno_file: None,\n\n first_sleep_secs: Some(0),\n\n }\n\n }\n\n\n\n pub async fn acquire_storno_fd(&mut self) -> &mut AsyncFd {\n\n if self.storno_file.is_none() {\n\n // special case for the very first call (try to acquire immediately)\n\n // if the fd somehow became None after the first call we had an error\n\n // and should wait before trying again\n", "file_path": "src/stornoservice.rs", "rank": 13, "score": 37504.99139954295 }, { "content": "#[derive(Debug, Clone, Serialize)]\n\nstruct Message<'a> {\n\n r#type: &'a str,\n\n id: String,\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 14, "score": 36826.06005168226 }, { "content": "fn parse_card(card: Card) -> Result<Option<CardDetail>, Box<dyn StdError>> {\n\n let result = match get_mete_card_state(&card)? {\n\n // YES! KalkGetränke app <3\n\n MeteCardState::Uuid(uuid) => Some(CardDetail::MeteUuid(uuid)),\n\n MeteCardState::ApplicationUnknown => None,\n\n MeteCardState::InvalidAnswer => None,\n\n MeteCardState::UnsupportedApplicationSelect => {\n\n get_uid(&card)?.map(|uid| CardDetail::Plain(uid))\n\n }\n\n };\n\n Ok(result)\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum CardDetail {\n\n MeteUuid(String),\n\n Plain(Vec<u8>),\n\n}\n\n\n", "file_path": "src/nfcservice.rs", "rank": 15, "score": 33173.57533829348 }, { "content": "fn get_mete_card_state(card: &Card) -> Result<MeteCardState, Box<dyn StdError>> {\n\n // Send KalkGetränk APDU\n\n let apdu = b\"\\x00\\xA4\\x04\\x00\\x0d\\xff\\x4b\\x61\\x6c\\x6b\\x47\\x65\\x74\\x72\\xc3\\xa4\\x6e\\x6b\\x00\";\n\n debug!(\"Sending APDU: {:?}\", apdu);\n\n let mut rapdu_buf = [0; MAX_BUFFER_SIZE];\n\n let rapdu = card.transmit(apdu, &mut rapdu_buf)?;\n\n debug!(\"APDU response: {:x?}\", rapdu);\n\n let l = rapdu.len();\n\n if l == 0 {\n\n return Ok(MeteCardState::UnsupportedApplicationSelect);\n\n }\n\n if l < 2 || rapdu[l - 2] != 0x90 || rapdu[l - 1] != 0x00 {\n\n return Ok(MeteCardState::ApplicationUnknown);\n\n }\n\n\n\n let apdu = b\"\\xd0\\x00\\x00\\x00\\x24\";\n\n debug!(\"Sending APDU: {:?}\", apdu);\n\n let rapdu = card.transmit(apdu, &mut rapdu_buf)?;\n\n debug!(\"APDU response: {:x?}\", rapdu);\n\n let l = rapdu.len();\n", "file_path": "src/nfcservice.rs", "rank": 16, "score": 32119.851399882155 }, { "content": "fn is_dead(rs: &ReaderState) -> bool {\n\n rs.event_state().intersects(State::UNKNOWN | State::IGNORE)\n\n}\n\n\n", "file_path": "src/nfcservice.rs", "rank": 17, "score": 28085.99163083153 }, { "content": "\n\n self.storno_file.as_mut().unwrap().fd_mut()\n\n }\n\n\n\n pub async fn try_read_storno(&mut self) -> Result<(), Box<dyn Error>> {\n\n let fd = self.acquire_storno_fd().await;\n\n let mut buf = [0u8; 512];\n\n // sometimes the key is triggering storno and stornoend at the same time\n\n // check that there is some time difference between both!\n\n // it seems that releasing the key doesn't trigger storno\n\n // so the code might be stupid but works for me :S\n\n let mut storno = Instant::now();\n\n let min_storno_time = Duration::from_millis(50);\n\n loop {\n\n // this currently blocks forever even if you pull out the device. unclear how to solve that\n\n let r = fd.read(&mut buf).await?;\n\n if r == 0 {\n\n continue;\n\n }\n\n let st = std::str::from_utf8(&buf[0..r])?;\n", "file_path": "src/stornoservice.rs", "rank": 21, "score": 15.966166473746863 }, { "content": " if st.contains(STORNO) {\n\n storno = Instant::now();\n\n }\n\n if st.contains(STORNOEND) && storno.elapsed() >= min_storno_time {\n\n return Ok(());\n\n }\n\n }\n\n }\n\n\n\n pub async fn read_storno(&mut self) -> () {\n\n loop {\n\n match self.try_read_storno().await {\n\n Ok(()) => return (),\n\n Err(e) => {\n\n error!(\"Error reading storno {}\", e);\n\n self.storno_file = None\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/stornoservice.rs", "rank": 22, "score": 15.852028275874629 }, { "content": " let mut sleep_secs = self.first_sleep_secs.take().unwrap_or(1);\n\n while self.storno_file.is_none() {\n\n sleep(Duration::from_secs(sleep_secs)).await;\n\n self.storno_file = match StornoFile::new(&self.dev) {\n\n Ok(fd) => Some(fd),\n\n Err(e) => {\n\n error!(\"Error accessing storno file {}\", e);\n\n if sleep_secs == 0 {\n\n sleep_secs = 1;\n\n } else {\n\n sleep_secs = sleep_secs * 2;\n\n if sleep_secs > 4 {\n\n sleep_secs = 4;\n\n }\n\n }\n\n None\n\n }\n\n }\n\n }\n\n }\n", "file_path": "src/stornoservice.rs", "rank": 23, "score": 15.314282228908718 }, { "content": "use async_stream::stream;\n\nuse futures_core::stream::Stream;\n\nuse log::error;\n\nuse nix::sys::termios;\n\nuse std::convert::TryFrom;\n\nuse std::error::Error;\n\nuse std::fs::File;\n\nuse std::os::unix::io::AsRawFd;\n\nuse std::path::{Path, PathBuf};\n\nuse std::time::{Duration, Instant};\n\nuse tokio::io::AsyncReadExt;\n\nuse tokio::time::sleep;\n\nuse tokio_fd::AsyncFd;\n\n\n\nconst STORNO: &str = \"storno\\n\";\n\nconst STORNOEND: &str = \"stornoend\\n\";\n\n\n", "file_path": "src/stornoservice.rs", "rank": 25, "score": 14.286801935340248 }, { "content": " }\n\n Err(Error::NoSmartcard) => {\n\n debug!(\"A smartcard is not present in the reader.\");\n\n continue;\n\n }\n\n Err(err) => return Err(err.into()),\n\n };\n\n }\n\n if found_card {\n\n return Ok(None);\n\n }\n\n }\n\n }\n\n\n\n pub fn fetch_next_uuid(&mut self) -> Result<Option<CardDetail>, Box<dyn StdError>> {\n\n let ctx = self.get_context()?;\n\n\n\n self.fetch_next_uuid_with_context(ctx)\n\n }\n\n}\n\n\n", "file_path": "src/nfcservice.rs", "rank": 28, "score": 10.700482696345455 }, { "content": " let ctx = match self.ctx.take() {\n\n Some(ctx) => ctx,\n\n None => {\n\n thread::sleep(self.reconnect_timeout);\n\n match Context::establish(Scope::User) {\n\n Ok(ctx) => {\n\n self.reconnect_timeout = Duration::from_secs(0);\n\n ctx\n\n }\n\n Err(e) => {\n\n self.reconnect_timeout = match self.reconnect_timeout.as_secs() {\n\n 0 => Duration::from_secs(1),\n\n d => {\n\n let mut d = d * d;\n\n if d > 64 {\n\n d = 64;\n\n }\n\n Duration::from_secs(d)\n\n }\n\n };\n", "file_path": "src/nfcservice.rs", "rank": 29, "score": 9.622661497692725 }, { "content": "use async_stream::stream;\n\nuse futures_core::stream::Stream;\n\nuse log::{debug, error};\n\nuse pcsc::*;\n\nuse std::error::Error as StdError;\n\nuse std::thread;\n\nuse std::time::Duration;\n\nuse tokio::sync::mpsc;\n\n\n", "file_path": "src/nfcservice.rs", "rank": 30, "score": 9.343622880508633 }, { "content": " },\n\n barcode = barcode_stream.next() => {\n\n if barcode.is_none() {\n\n continue;\n\n }\n\n let barcode = barcode.unwrap();\n\n Message {\n\n r#type: \"barcode\",\n\n id: barcode,\n\n }\n\n },\n\n storno = storno_stream.next() => {\n\n if storno.is_none() {\n\n continue;\n\n }\n\n Message {\n\n r#type: \"storno\",\n\n id: String::from(\"\"),\n\n }\n\n }\n", "file_path": "src/main.rs", "rank": 31, "score": 8.585875089945635 }, { "content": " };\n\n clients.lock().unwrap().retain(move |_, tx| {\n\n // If not `is_ok`, the SSE stream is gone, and so don't retain\n\n tx.send(message.clone()).is_ok()\n\n });\n\n }\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<(), Box<dyn Error>> {\n\n pretty_env_logger::init();\n\n let nfc_stream = nfcservice::run()?;\n\n // hardcoded for now\n\n let barcode_stream =\n\n barcodeservice::run(\"/dev/input/by-id/usb-Newtologic_NT4010S_XXXXXX-event-kbd\");\n\n let storno_stream = stornoservice::run(\"/dev/stornoschluessel\");\n\n\n\n // Keep track of all connected clients, key is usize, value\n\n // is an event stream sender.\n\n\n", "file_path": "src/main.rs", "rank": 32, "score": 8.435551740112786 }, { "content": " .push(ReaderState::new(reader, State::UNAWARE));\n\n }\n\n }\n\n\n\n // Update the view of the state to wait on.\n\n for rs in self.reader_states.iter_mut() {\n\n rs.sync_current_state();\n\n }\n\n ctx.get_status_change(None, &mut self.reader_states)?;\n\n\n\n let readers = ctx.list_readers(&mut self.readers_buf)?;\n\n let mut found_card = false;\n\n for reader in readers {\n\n match ctx.connect(reader, ShareMode::Shared, Protocols::ANY) {\n\n Ok(card) => {\n\n found_card = true;\n\n match parse_card(card)? {\n\n Some(carddetail) => return Ok(Some(carddetail)),\n\n _ => continue,\n\n }\n", "file_path": "src/nfcservice.rs", "rank": 33, "score": 7.925077982941183 }, { "content": " return Err(Box::new(e));\n\n }\n\n }\n\n }\n\n };\n\n Ok(ctx)\n\n }\n\n\n\n fn fetch_next_uuid_with_context(\n\n &mut self,\n\n ctx: Context,\n\n ) -> Result<Option<CardDetail>, Box<dyn StdError>> {\n\n loop {\n\n self.reader_states.retain(|rs| !is_dead(rs));\n\n\n\n let readers = ctx.list_readers(&mut self.readers_buf)?;\n\n\n\n for reader in readers {\n\n if !self.reader_states.iter().any(|rs| rs.name() == reader) {\n\n self.reader_states\n", "file_path": "src/nfcservice.rs", "rank": 34, "score": 7.516373506146131 }, { "content": " warp::cors()\n\n .allow_origin(allow_origin.as_str())\n\n .allow_methods(vec![\"GET\", \"POST\", \"DELETE\"]),\n\n );\n\n\n\n let addr = match std::env::var(\"BIND\") {\n\n Ok(var) => var,\n\n Err(_) => String::from(\"0.0.0.0:3030\"),\n\n };\n\n\n\n warp::serve(route).run(addr.parse::<SocketAddr>()?).await;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 35, "score": 6.132491733635284 }, { "content": " let clients: Clients = Arc::new(Mutex::new(HashMap::new()));\n\n let cloned_clients = clients.clone();\n\n tokio::spawn(async move {\n\n consume_device_events(cloned_clients, nfc_stream, barcode_stream, storno_stream).await;\n\n });\n\n\n\n // failing to make this optional\n\n let allow_origin = std::env::var(\"ALLOW_ORIGIN\").unwrap_or(String::from(\"https://example.com\"));\n\n\n\n // Turn our \"state\" into a new Filter...\n\n let clients = warp::any().map(move || clients.clone());\n\n let route = warp::path::end()\n\n .and(warp::get())\n\n .and(clients)\n\n .map(|clients| {\n\n let stream = cashier_event_stream(clients);\n\n // reply using server-sent events\n\n warp::sse::reply(warp::sse::keep_alive().stream(stream))\n\n })\n\n .with(\n", "file_path": "src/main.rs", "rank": 36, "score": 6.015456148750074 }, { "content": " match nfc {\n\n None => Message{\n\n r#type: \"nfc-invalid\",\n\n id: String::new(),\n\n },\n\n Some(card_detail) => {\n\n match card_detail {\n\n nfcservice::CardDetail::MeteUuid(uuid) => {\n\n Message{\n\n r#type: \"nfc-uuid\",\n\n id: uuid,\n\n }},\n\n nfcservice::CardDetail::Plain(uid) => {\n\n Message{\n\n r#type: \"nfc-plain\",\n\n id: uid.iter().map(|x| format!(\"{:02x}\", x)).collect::<String>(),\n\n }},\n\n }\n\n }\n\n }\n", "file_path": "src/main.rs", "rank": 37, "score": 4.869014515689674 }, { "content": "use futures::{Stream, StreamExt};\n\nuse serde::Serialize;\n\nuse std::collections::HashMap;\n\nuse std::error::Error;\n\nuse std::net::SocketAddr;\n\nuse std::sync::{\n\n atomic::{AtomicUsize, Ordering},\n\n Arc, Mutex,\n\n};\n\nuse tokio::sync::mpsc;\n\nuse tokio_stream::wrappers::UnboundedReceiverStream;\n\nuse warp::{sse::Event, Filter};\n\n\n\nmod barcodeservice;\n\nmod nfcservice;\n\nmod stornoservice;\n\n\n\n/// Our global unique client id counter.\n\nstatic NEXT_CLIENT_ID: AtomicUsize = AtomicUsize::new(1);\n\n\n\n// this is a generic type right now and I don't like it but I fail\n\n// to send two different messages because of rust n00bness\n\n#[derive(Debug, Clone, Serialize)]\n", "file_path": "src/main.rs", "rank": 38, "score": 4.581579690347693 }, { "content": "# getraenkekassengeraete\n\n\n\nAggregating nfc and barcodes to a browser consumable event stream\n", "file_path": "README.md", "rank": 39, "score": 4.197160308854416 }, { "content": " if l == 0 {\n\n return Ok(MeteCardState::UnsupportedApplicationSelect);\n\n }\n\n if l != 38 || rapdu[l - 2] != 0x90 || rapdu[l - 1] != 0x00 {\n\n return Ok(MeteCardState::InvalidAnswer);\n\n }\n\n let s = std::str::from_utf8(&rapdu[0..l - 2])?.to_owned();\n\n\n\n Ok(MeteCardState::Uuid(s))\n\n}\n\n\n", "file_path": "src/nfcservice.rs", "rank": 40, "score": 2.2324795255939 }, { "content": "/// Our state of currently connected users.\n\n///\n\n/// - Key is their id\n\n/// - Value is a sender of `Message`\n\ntype Clients<'a> = Arc<Mutex<HashMap<usize, mpsc::UnboundedSender<Message<'a>>>>>;\n\n\n\nasync fn consume_device_events<'a>(\n\n clients: Clients<'a>,\n\n nfc_stream: impl Stream<Item = Option<nfcservice::CardDetail>>,\n\n barcode_stream: impl Stream<Item = String>,\n\n storno_stream: impl Stream<Item = ()>,\n\n) {\n\n tokio::pin!(nfc_stream);\n\n tokio::pin!(barcode_stream);\n\n tokio::pin!(storno_stream);\n\n loop {\n\n let message = tokio::select! {\n\n nfc = nfc_stream.next() => {\n\n // too much nesting :S\n\n // unsure why there is another option\n\n if nfc.is_none() {\n\n continue;\n\n }\n\n let nfc = nfc.unwrap();\n", "file_path": "src/main.rs", "rank": 41, "score": 2.148236155775246 } ]
Rust
crates/holochain_sqlite/src/db/p2p_agent_store.rs
the-a-man-006/holochain
ace36de1c9021dd4f49e4bba226db81f671b818e
use crate::prelude::*; use crate::sql::*; use kitsune_p2p::agent_store::{AgentInfo, AgentInfoSigned}; use kitsune_p2p::dht_arc::DhtArc; use kitsune_p2p::KitsuneAgent; use rusqlite::*; pub trait AsP2pStateConExt { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; fn p2p_list(&mut self) -> DatabaseResult<Vec<AgentInfoSigned>>; fn p2p_gossip_query( &mut self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>>; } pub trait AsP2pStateTxExt { fn p2p_get(&self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; fn p2p_list(&self) -> DatabaseResult<Vec<AgentInfoSigned>>; fn p2p_gossip_query( &self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>>; } impl AsP2pStateConExt for crate::db::PConn { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>> { self.with_reader(move |reader| reader.p2p_get(agent)) } fn p2p_list(&mut self) -> DatabaseResult<Vec<AgentInfoSigned>> { self.with_reader(move |reader| reader.p2p_list()) } fn p2p_gossip_query( &mut self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>> { self.with_reader(move |reader| reader.p2p_gossip_query(since_ms, until_ms, within_arc)) } } pub async fn p2p_put(db: &DbWrite, signed: &AgentInfoSigned) -> DatabaseResult<()> { let record = P2pRecord::from_signed(signed)?; db.async_commit(move |txn| tx_p2p_put(txn, record)).await } pub async fn p2p_put_all( db: &DbWrite, signed: impl Iterator<Item = &AgentInfoSigned>, ) -> DatabaseResult<()> { let mut records = Vec::new(); for s in signed { records.push(P2pRecord::from_signed(s)?); } db.async_commit(move |txn| { for record in records { tx_p2p_put(txn, record)?; } Ok(()) }) .await } fn tx_p2p_put(txn: &mut Transaction, record: P2pRecord) -> DatabaseResult<()> { txn.execute( sql_p2p_agent_store::INSERT, named_params! { ":agent": &record.agent.0, ":encoded": &record.encoded, ":signed_at_ms": &record.signed_at_ms, ":expires_at_ms": &record.expires_at_ms, ":storage_center_loc": &record.storage_center_loc, ":storage_start_1": &record.storage_start_1, ":storage_end_1": &record.storage_end_1, ":storage_start_2": &record.storage_start_2, ":storage_end_2": &record.storage_end_2, }, )?; Ok(()) } pub async fn p2p_prune(db: &DbWrite) -> DatabaseResult<()> { db.async_commit(move |txn| { let now = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap() .as_millis() as u64; txn.execute(sql_p2p_agent_store::PRUNE, named_params! { ":now": now })?; DatabaseResult::Ok(()) }) .await?; Ok(()) } impl AsP2pStateTxExt for Transaction<'_> { fn p2p_get(&self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(stmt .query_row(named_params! { ":agent": &agent.0 }, |r| { let r = r.get_ref(0)?; let r = r.as_blob()?; let signed = AgentInfoSigned::try_from(r) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(signed) }) .optional()?) } fn p2p_list(&self) -> DatabaseResult<Vec<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT_ALL) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; let mut out = Vec::new(); for r in stmt.query_map([], |r| { let r = r.get_ref(0)?; let r = r.as_blob()?; let signed = AgentInfoSigned::try_from(r) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(signed) })? { out.push(r?); } Ok(out) } fn p2p_gossip_query( &self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>> { let mut stmt = self .prepare(sql_p2p_agent_store::GOSSIP_QUERY) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; let (storage_1, storage_2) = split_arc(&within_arc); let mut out = Vec::new(); for r in stmt.query_map( named_params! { ":since_ms": clamp64(since_ms), ":until_ms": clamp64(until_ms), ":storage_start_1": storage_1.map(|s| s.0), ":storage_end_1": storage_1.map(|s| s.1), ":storage_start_2": storage_2.map(|s| s.0), ":storage_end_2": storage_2.map(|s| s.1), }, |r| { let agent: Vec<u8> = r.get(0)?; Ok(KitsuneAgent(agent)) }, )? { out.push(r?); } Ok(out) } } #[derive(Debug)] struct P2pRecord { agent: KitsuneAgent, encoded: Vec<u8>, signed_at_ms: i64, expires_at_ms: i64, storage_center_loc: u32, storage_start_1: Option<u32>, storage_end_1: Option<u32>, storage_start_2: Option<u32>, storage_end_2: Option<u32>, } pub type SplitRange = (u32, u32); pub fn split_arc(arc: &DhtArc) -> (Option<SplitRange>, Option<SplitRange>) { let mut storage_1 = None; let mut storage_2 = None; use std::ops::{Bound, RangeBounds}; let r = arc.range(); let s = r.start_bound(); let e = r.end_bound(); match (s, e) { (Bound::Excluded(_), Bound::Excluded(_)) => (), (Bound::Included(s), Bound::Included(e)) => { if s > e { storage_1 = Some((u32::MIN, *e)); storage_2 = Some((*s, u32::MAX)); } else { storage_1 = Some((*s, *e)); } } _ => unreachable!(), } (storage_1, storage_2) } fn clamp64(u: u64) -> i64 { if u > i64::MAX as u64 { i64::MAX } else { u as i64 } } impl P2pRecord { pub fn from_signed(signed: &AgentInfoSigned) -> DatabaseResult<Self> { use std::convert::TryFrom; let info = AgentInfo::try_from(signed).map_err(|e| anyhow::anyhow!(e))?; let agent = info.as_agent_ref().clone(); let encoded = <Vec<u8>>::try_from(signed).map_err(|e| anyhow::anyhow!(e))?; let signed_at_ms = info.signed_at_ms(); let expires_at_ms = signed_at_ms + info.expires_after_ms(); let arc = info.dht_arc().map_err(|e| anyhow::anyhow!(e))?; let storage_center_loc = arc.center_loc.into(); let (storage_1, storage_2) = split_arc(&arc); Ok(Self { agent, encoded, signed_at_ms: clamp64(signed_at_ms), expires_at_ms: clamp64(expires_at_ms), storage_center_loc, storage_start_1: storage_1.map(|s| s.0), storage_end_1: storage_1.map(|s| s.1), storage_start_2: storage_2.map(|s| s.0), storage_end_2: storage_2.map(|s| s.1), }) } } #[cfg(test)] mod p2p_test;
use crate::prelude::*; use crate::sql::*; use kitsune_p2p::agent_store::{AgentInfo, AgentInfoSigned}; use kitsune_p2p::dht_arc::DhtArc; use kitsune_p2p::KitsuneAgent; use rusqlite::*; pub trait AsP2pStateConExt { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; fn p2p_list(&mut self) -> DatabaseResult<Vec<AgentInfoSigned>>; fn p2p_gossip_query( &mut self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>>; } pub trait AsP2pStateTxExt { fn p2p_get(&self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>>; fn p2p_list(&self) -> DatabaseResult<Vec<AgentInfoSigned>>; fn p2p_gossip_query( &self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>>; } impl AsP2pStateConExt for crate::db::PConn { fn p2p_get(&mut self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>> { self.with_reader(move |reader| reader.p2p_get(agent)) } fn p2p_list(&mut self) -> DatabaseResult<Vec<AgentInfoSigned>> { self.with_reader(move |reader| reader.p2p_list()) } fn p2p_gossip_query( &mut self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>> { self.with_reader(move |reader| reader.p2p_gossip_query(since_ms, until_ms, within_arc)) } } pub async fn p2p_put(db: &DbWrite, signed: &AgentInfoSigned) -> DatabaseResult<()> { let record = P2pRecord::from_signed(signed)?; db.async_commit(move |txn| tx_p2p_put(txn, record)).await } pub async fn p2p_put_all( db: &DbWrite, signed: impl Iterator<Item = &AgentInfoSigned>, ) -> DatabaseResult<()> { let mut records = Vec::new(); for s in signed { records.push(P2pRecord::from_signed(s)?); } db.async_commit(move |txn| { for record in records { tx_p2p_put(txn, record)?; } Ok(()) }) .await } fn tx_p2p_put(txn: &mut Transaction, record: P2pRecord) -> DatabaseResult<()> { txn.execute( sql_p2p_agent_store::INSERT, named_params! { ":agent": &record.agent.0, ":encoded": &record.encoded, ":signed_at_ms": &record.signed_at_ms, ":expires_at_ms": &record.expires_at_ms, ":storage_center_loc": &record.storage_center_loc, ":storage_start_1": &record.storage_start_1, ":storage_end_1": &record.storage_end_1, ":storage_start_2": &record.storage_start_2, ":storage_end_2": &record.storage_end_2, }, )?; Ok(()) } pub async fn p2p_prune(db: &DbWrite) -> DatabaseResult<()> { db.async_commit(move |txn| { let now = std::time::SystemTime::now() .duration_since(std::time::SystemTime::UNIX_EPOCH) .unwrap() .as_millis() as u64; txn.execute(sql_p2p_agent_store::PRUNE, named_params! { ":now": now })?; DatabaseResult::Ok(()) }) .await?; Ok(()) } impl AsP2pStateTxExt for Transaction<'_> {
fn p2p_list(&self) -> DatabaseResult<Vec<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT_ALL) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; let mut out = Vec::new(); for r in stmt.query_map([], |r| { let r = r.get_ref(0)?; let r = r.as_blob()?; let signed = AgentInfoSigned::try_from(r) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(signed) })? { out.push(r?); } Ok(out) } fn p2p_gossip_query( &self, since_ms: u64, until_ms: u64, within_arc: DhtArc, ) -> DatabaseResult<Vec<KitsuneAgent>> { let mut stmt = self .prepare(sql_p2p_agent_store::GOSSIP_QUERY) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; let (storage_1, storage_2) = split_arc(&within_arc); let mut out = Vec::new(); for r in stmt.query_map( named_params! { ":since_ms": clamp64(since_ms), ":until_ms": clamp64(until_ms), ":storage_start_1": storage_1.map(|s| s.0), ":storage_end_1": storage_1.map(|s| s.1), ":storage_start_2": storage_2.map(|s| s.0), ":storage_end_2": storage_2.map(|s| s.1), }, |r| { let agent: Vec<u8> = r.get(0)?; Ok(KitsuneAgent(agent)) }, )? { out.push(r?); } Ok(out) } } #[derive(Debug)] struct P2pRecord { agent: KitsuneAgent, encoded: Vec<u8>, signed_at_ms: i64, expires_at_ms: i64, storage_center_loc: u32, storage_start_1: Option<u32>, storage_end_1: Option<u32>, storage_start_2: Option<u32>, storage_end_2: Option<u32>, } pub type SplitRange = (u32, u32); pub fn split_arc(arc: &DhtArc) -> (Option<SplitRange>, Option<SplitRange>) { let mut storage_1 = None; let mut storage_2 = None; use std::ops::{Bound, RangeBounds}; let r = arc.range(); let s = r.start_bound(); let e = r.end_bound(); match (s, e) { (Bound::Excluded(_), Bound::Excluded(_)) => (), (Bound::Included(s), Bound::Included(e)) => { if s > e { storage_1 = Some((u32::MIN, *e)); storage_2 = Some((*s, u32::MAX)); } else { storage_1 = Some((*s, *e)); } } _ => unreachable!(), } (storage_1, storage_2) } fn clamp64(u: u64) -> i64 { if u > i64::MAX as u64 { i64::MAX } else { u as i64 } } impl P2pRecord { pub fn from_signed(signed: &AgentInfoSigned) -> DatabaseResult<Self> { use std::convert::TryFrom; let info = AgentInfo::try_from(signed).map_err(|e| anyhow::anyhow!(e))?; let agent = info.as_agent_ref().clone(); let encoded = <Vec<u8>>::try_from(signed).map_err(|e| anyhow::anyhow!(e))?; let signed_at_ms = info.signed_at_ms(); let expires_at_ms = signed_at_ms + info.expires_after_ms(); let arc = info.dht_arc().map_err(|e| anyhow::anyhow!(e))?; let storage_center_loc = arc.center_loc.into(); let (storage_1, storage_2) = split_arc(&arc); Ok(Self { agent, encoded, signed_at_ms: clamp64(signed_at_ms), expires_at_ms: clamp64(expires_at_ms), storage_center_loc, storage_start_1: storage_1.map(|s| s.0), storage_end_1: storage_1.map(|s| s.1), storage_start_2: storage_2.map(|s| s.0), storage_end_2: storage_2.map(|s| s.1), }) } } #[cfg(test)] mod p2p_test;
fn p2p_get(&self, agent: &KitsuneAgent) -> DatabaseResult<Option<AgentInfoSigned>> { use std::convert::TryFrom; let mut stmt = self .prepare(sql_p2p_agent_store::SELECT) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(stmt .query_row(named_params! { ":agent": &agent.0 }, |r| { let r = r.get_ref(0)?; let r = r.as_blob()?; let signed = AgentInfoSigned::try_from(r) .map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.into()))?; Ok(signed) }) .optional()?) }
function_block-full_function
[ { "content": "/// Insert a [`Header`] into the database.\n\npub fn insert_header(txn: &mut Transaction, header: SignedHeaderHashed) -> StateMutationResult<()> {\n\n let (header, signature) = header.into_header_and_signature();\n\n let (header, hash) = header.into_inner();\n\n let header_type = header.header_type();\n\n let header_seq = header.header_seq();\n\n let author = header.author().clone();\n\n let prev_hash = header.prev_header().cloned();\n\n let private = match header.entry_type().map(|et| et.visibility()) {\n\n Some(EntryVisibility::Private) => true,\n\n Some(EntryVisibility::Public) => false,\n\n None => false,\n\n };\n\n match header {\n\n Header::CreateLink(create_link) => {\n\n sql_insert!(txn, Header, {\n\n \"hash\": hash,\n\n \"type\": header_type ,\n\n \"seq\": header_seq,\n\n \"author\": author,\n\n \"prev_hash\": prev_hash,\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 1, "score": 393607.76597262773 }, { "content": "#[tracing::instrument(skip(txn))]\n\npub fn dump_db(txn: &Transaction) {\n\n let dump = |mut stmt: Statement| {\n\n let mut rows = stmt.query([]).unwrap();\n\n while let Some(row) = rows.next().unwrap() {\n\n for column in row.column_names() {\n\n let row = row.get_ref_unwrap(column);\n\n match row {\n\n holochain_sqlite::rusqlite::types::ValueRef::Null\n\n | holochain_sqlite::rusqlite::types::ValueRef::Integer(_)\n\n | holochain_sqlite::rusqlite::types::ValueRef::Real(_) => {\n\n tracing::debug!(?column, ?row);\n\n }\n\n holochain_sqlite::rusqlite::types::ValueRef::Text(text) => {\n\n tracing::debug!(?column, row = ?String::from_utf8_lossy(text));\n\n }\n\n holochain_sqlite::rusqlite::types::ValueRef::Blob(blob) => {\n\n let blob = base64::encode_config(blob, base64::URL_SAFE_NO_PAD);\n\n tracing::debug!(\"column: {:?} row:{}\", column, blob);\n\n }\n\n }\n", "file_path": "crates/holochain_state/src/test_utils.rs", "rank": 2, "score": 364184.15359973215 }, { "content": "pub fn put(txn: &mut Transaction, wasm: DnaWasmHashed) -> StateMutationResult<()> {\n\n mutations::insert_wasm(txn, wasm)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use holo_hash::HasHash;\n\n use holochain_sqlite::prelude::DatabaseResult;\n\n use holochain_types::dna::wasm::DnaWasm;\n\n\n\n #[tokio::test(flavor = \"multi_thread\")]\n\n async fn wasm_store_round_trip() -> DatabaseResult<()> {\n\n use holochain_sqlite::prelude::*;\n\n observability::test_run().ok();\n\n\n\n // all the stuff needed to have a WasmBuf\n\n let env = crate::test_utils::test_wasm_env();\n\n\n\n // a wasm\n", "file_path": "crates/holochain_state/src/wasm.rs", "rank": 3, "score": 350525.3215306319 }, { "content": "/// Insert an [`Entry`] into the database.\n\npub fn insert_entry(txn: &mut Transaction, entry: EntryHashed) -> StateMutationResult<()> {\n\n let (entry, hash) = entry.into_inner();\n\n let mut cap_secret = None;\n\n let mut cap_access = None;\n\n let mut cap_grantor = None;\n\n let cap_tag = match &entry {\n\n Entry::CapGrant(ZomeCallCapGrant {\n\n tag,\n\n access,\n\n functions: _,\n\n }) => {\n\n cap_access = match access {\n\n CapAccess::Unrestricted => Some(\"unrestricted\"),\n\n CapAccess::Transferable { secret } => {\n\n cap_secret = Some(to_blob(secret)?);\n\n Some(\"transferable\")\n\n }\n\n CapAccess::Assigned {\n\n secret,\n\n assignees: _,\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 4, "score": 350525.3215306319 }, { "content": "pub fn put(txn: &mut Transaction, dna_def: DnaDef) -> StateMutationResult<()> {\n\n mutations::insert_dna_def(txn, DnaDefHashed::from_content_sync(dna_def))\n\n}\n", "file_path": "crates/holochain_state/src/dna_def.rs", "rank": 5, "score": 346973.954679862 }, { "content": "/// Insert a [`DnaWasm`] into the database.\n\npub fn insert_wasm(txn: &mut Transaction, wasm: DnaWasmHashed) -> StateMutationResult<()> {\n\n let (wasm, hash) = wasm.into_inner();\n\n sql_insert!(txn, Wasm, {\n\n \"hash\": hash,\n\n \"blob\": to_blob(wasm)?,\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 6, "score": 346973.95467986196 }, { "content": "/// Insert a [`DnaDef`] into the database.\n\npub fn insert_dna_def(txn: &mut Transaction, dna_def: DnaDefHashed) -> StateMutationResult<()> {\n\n let (dna_def, hash) = dna_def.into_inner();\n\n sql_insert!(txn, DnaDef, {\n\n \"hash\": hash,\n\n \"blob\": to_blob(dna_def)?,\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 7, "score": 340182.98422655696 }, { "content": "/// Add one to the receipt count for a [`DhtOp`].\n\npub fn add_one_receipt_count(txn: &mut Transaction, hash: &DhtOpHash) -> StateMutationResult<()> {\n\n txn.execute(\n\n \"UPDATE DhtOp SET receipt_count = IFNULL(receipt_count, 0) + 1 WHERE hash = :hash;\",\n\n named_params! { \":hash\": hash },\n\n )?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 8, "score": 340182.98422655696 }, { "content": "pub fn insert_valid_authored_op(txn: &mut Transaction, op: DhtOpHashed) -> StateMutationResult<()> {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, true)?;\n\n set_validation_status(txn, hash, holochain_zome_types::ValidationStatus::Valid)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_state/src/test_utils/mutations_helpers.rs", "rank": 9, "score": 330710.39188133716 }, { "content": "fn rand_signed_at_ms() -> u64 {\n\n let mut rng = rand::thread_rng();\n\n\n\n let now = std::time::SystemTime::now()\n\n .duration_since(std::time::SystemTime::UNIX_EPOCH)\n\n .unwrap()\n\n .as_millis() as u64;\n\n\n\n now - rng.gen_range(1000, 2000)\n\n}\n\n\n\nasync fn rand_insert(db: &DbWrite, space: &KitsuneSpace, agent: &KitsuneAgent) {\n\n use std::convert::TryInto;\n\n\n\n let mut rng = rand::thread_rng();\n\n\n\n let signed_at_ms = rand_signed_at_ms();\n\n let expires_after_ms = rng.gen_range(100, 200);\n\n\n\n let info = AgentInfo::new(\n", "file_path": "crates/holochain_sqlite/src/db/p2p_agent_store/p2p_test.rs", "rank": 10, "score": 326194.70506452373 }, { "content": "pub fn sign(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: Sign,\n\n) -> Result<Signature, WasmError> {\n\n tokio_helper::block_forever_on(async move {\n\n call_context.host_access.keystore().sign(input).await\n\n })\n\n .map_err(|keystore_error| WasmError::Host(keystore_error.to_string()))\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod wasm_test {\n\n use crate::fixt::ZomeCallHostAccessFixturator;\n\n use ::fixt::prelude::*;\n\n use hdk::prelude::test_utils::fake_agent_pubkey_1;\n\n use hdk::prelude::test_utils::fake_agent_pubkey_2;\n\n use hdk::prelude::*;\n\n use holochain_state::host_fn_workspace::HostFnWorkspace;\n", "file_path": "crates/holochain/src/core/ribosome/host_fn/sign.rs", "rank": 13, "score": 302165.8666507182 }, { "content": "pub fn count_valid(txn: &Transaction, op_hash: &DhtOpHash) -> DatabaseResult<usize> {\n\n let count: usize = txn\n\n .query_row(\n\n \"SELECT COUNT(hash) FROM ValidationReceipt WHERE op_hash = :op_hash\",\n\n named_params! {\n\n \":op_hash\": op_hash\n\n },\n\n |row| row.get(0),\n\n )\n\n .optional()?\n\n .unwrap_or(0);\n\n Ok(count)\n\n}\n\n\n", "file_path": "crates/holochain_state/src/validation_receipts.rs", "rank": 14, "score": 297718.3985367676 }, { "content": "/// Get agent info for a single agent\n\npub fn get_agent_info_signed(\n\n environ: EnvWrite,\n\n _kitsune_space: Arc<kitsune_p2p::KitsuneSpace>,\n\n kitsune_agent: Arc<kitsune_p2p::KitsuneAgent>,\n\n) -> ConductorResult<Option<AgentInfoSigned>> {\n\n Ok(environ.conn()?.p2p_get(&kitsune_agent)?)\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 15, "score": 293260.4885647826 }, { "content": "/// Get agent info for a single space\n\npub fn query_agent_info_signed(\n\n environ: EnvWrite,\n\n _kitsune_space: Arc<kitsune_p2p::KitsuneSpace>,\n\n) -> ConductorResult<Vec<AgentInfoSigned>> {\n\n Ok(environ.conn()?.p2p_list()?)\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 16, "score": 293259.57712759776 }, { "content": "pub fn get_all(txn: &Transaction<'_>) -> StateQueryResult<Vec<DnaDefHashed>> {\n\n let mut stmt = txn.prepare(\n\n \"\n\n SELECT hash, blob FROM DnaDef\n\n \",\n\n )?;\n\n let items = stmt\n\n .query_and_then([], |row| {\n\n let hash: DnaHash = row.get(\"hash\")?;\n\n let wasm = row.get(\"blob\")?;\n\n StateQueryResult::Ok(DnaDefHashed::with_pre_hashed(from_blob(wasm)?, hash))\n\n })?\n\n .collect();\n\n items\n\n}\n\n\n", "file_path": "crates/holochain_state/src/dna_def.rs", "rank": 18, "score": 272992.30034514185 }, { "content": "pub fn contains(txn: &Transaction<'_>, hash: &WasmHash) -> StateQueryResult<bool> {\n\n Ok(txn.query_row(\n\n \"SELECT EXISTS(SELECT 1 FROM Wasm WHERE hash = :hash)\",\n\n named_params! {\n\n \":hash\": hash\n\n },\n\n |row| row.get(0),\n\n )?)\n\n}\n\n\n", "file_path": "crates/holochain_state/src/wasm.rs", "rank": 19, "score": 272049.4355218486 }, { "content": "pub fn contains(txn: &Transaction<'_>, hash: &DnaHash) -> StateQueryResult<bool> {\n\n Ok(txn.query_row(\n\n \"SELECT EXISTS(SELECT 1 FROM DnaDef WHERE hash = :hash)\",\n\n named_params! {\n\n \":hash\": hash\n\n },\n\n |row| row.get(0),\n\n )?)\n\n}\n\n\n", "file_path": "crates/holochain_state/src/dna_def.rs", "rank": 20, "score": 269123.4975102271 }, { "content": "pub fn contains(txn: &Transaction<'_>, key: EntryDefBufferKey) -> StateQueryResult<bool> {\n\n let key: EntryDefStoreKey = key.into();\n\n Ok(txn.query_row(\n\n \"SELECT EXISTS(SELECT 1 FROM EntryDef WHERE key = :key)\",\n\n named_params! {\n\n \":key\": key\n\n },\n\n |row| row.get(0),\n\n )?)\n\n}\n\n\n", "file_path": "crates/holochain_state/src/entry_def.rs", "rank": 22, "score": 263532.2942577299 }, { "content": "/// Extend holo_hash::AgentPubKey with additional signature functionality\n\n/// from Keystore.\n\npub trait AgentPubKeyExt {\n\n /// create a new agent keypair in given keystore, returning the AgentPubKey\n\n fn new_from_pure_entropy(\n\n keystore: &KeystoreSender,\n\n ) -> KeystoreApiFuture<holo_hash::AgentPubKey>\n\n where\n\n Self: Sized;\n\n\n\n /// sign some arbitrary data\n\n fn sign<S>(&self, keystore: &KeystoreSender, data: S) -> KeystoreApiFuture<Signature>\n\n where\n\n S: Serialize + std::fmt::Debug;\n\n\n\n /// sign some arbitrary raw bytes\n\n fn sign_raw(&self, keystore: &KeystoreSender, data: &[u8]) -> KeystoreApiFuture<Signature>;\n\n\n\n /// verify a signature for given data with this agent public_key is valid\n\n fn verify_signature<D>(&self, signature: &Signature, data: D) -> KeystoreApiFuture<bool>\n\n where\n\n D: TryInto<SerializedBytes, Error = SerializedBytesError>;\n", "file_path": "crates/holochain_keystore/src/agent_pubkey_ext.rs", "rank": 23, "score": 261461.68224804397 }, { "content": "pub fn get_all(txn: &Transaction<'_>) -> StateQueryResult<Vec<(EntryDefBufferKey, EntryDef)>> {\n\n let mut stmt = txn.prepare(\n\n \"\n\n SELECT key, blob FROM EntryDef\n\n \",\n\n )?;\n\n let items = stmt\n\n .query_and_then([], |row| {\n\n let key: Vec<u8> = row.get(\"key\")?;\n\n let key: EntryDefStoreKey = key.into();\n\n let item = row.get(\"blob\")?;\n\n StateQueryResult::Ok((key.into(), from_blob(item)?))\n\n })?\n\n .collect::<StateQueryResult<Vec<_>>>();\n\n\n\n items\n\n}\n\n\n", "file_path": "crates/holochain_state/src/entry_def.rs", "rank": 24, "score": 260859.40113786675 }, { "content": "pub fn get(txn: &Transaction<'_>, hash: &WasmHash) -> StateQueryResult<Option<DnaWasmHashed>> {\n\n let item = txn\n\n .query_row(\n\n \"SELECT hash, blob FROM Wasm WHERE hash = :hash\",\n\n named_params! {\n\n \":hash\": hash\n\n },\n\n |row| {\n\n let hash: WasmHash = row.get(\"hash\")?;\n\n let wasm = row.get(\"blob\")?;\n\n Ok((hash, wasm))\n\n },\n\n )\n\n .optional()?;\n\n match item {\n\n Some((hash, wasm)) => Ok(Some(DnaWasmHashed::with_pre_hashed(from_blob(wasm)?, hash))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "crates/holochain_state/src/wasm.rs", "rank": 25, "score": 260001.41980796683 }, { "content": "pub fn wasm_call_n(c: &mut Criterion) {\n\n let mut group = c.benchmark_group(\"wasm_call_n\");\n\n\n\n for n in vec![\n\n 1, // 1 byte\n\n 1_000, // 1 kb\n\n 1_000_000, // 1 mb\n\n ] {\n\n group.throughput(Throughput::Bytes(n as _));\n\n\n\n group.bench_function(BenchmarkId::from_parameter(n), |b| {\n\n // bytes\n\n let bytes = vec![0; n];\n\n let _g = TOKIO_RUNTIME.lock().unwrap().enter();\n\n let ha = HOST_ACCESS_FIXTURATOR.lock().unwrap().next().unwrap();\n\n\n\n b.iter(|| {\n\n let zome: Zome = TestWasm::Bench.into();\n\n let i = ZomeCallInvocation {\n\n cell_id: CELL_ID.lock().unwrap().clone(),\n", "file_path": "crates/holochain/benches/bench.rs", "rank": 26, "score": 259424.8923830785 }, { "content": "/// Helper function to get all the peer data from this conductor\n\npub fn all_agent_infos(env: EnvRead) -> StateQueryResult<Vec<AgentInfoSigned>> {\n\n fresh_reader!(env, |r| Ok(r.p2p_list()?))\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 27, "score": 258188.85904559324 }, { "content": "pub fn get(txn: &Transaction<'_>, hash: &DnaHash) -> StateQueryResult<Option<DnaDefHashed>> {\n\n let item = txn\n\n .query_row(\n\n \"SELECT hash, blob FROM DnaDef WHERE hash = :hash\",\n\n named_params! {\n\n \":hash\": hash\n\n },\n\n |row| {\n\n let hash: DnaHash = row.get(\"hash\")?;\n\n let wasm = row.get(\"blob\")?;\n\n Ok((hash, wasm))\n\n },\n\n )\n\n .optional()?;\n\n match item {\n\n Some((hash, wasm)) => Ok(Some(DnaDefHashed::with_pre_hashed(from_blob(wasm)?, hash))),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "crates/holochain_state/src/dna_def.rs", "rank": 28, "score": 257328.52668810368 }, { "content": "pub fn spawn_output(holochain: &mut Child) {\n\n let stdout = holochain.stdout.take();\n\n let stderr = holochain.stderr.take();\n\n tokio::task::spawn(async move {\n\n if let Some(stdout) = stdout {\n\n let mut reader = BufReader::new(stdout).lines();\n\n while let Ok(Some(line)) = reader.next_line().await {\n\n trace!(\"holochain bin stdout: {}\", line);\n\n }\n\n }\n\n });\n\n tokio::task::spawn(async move {\n\n if let Some(stderr) = stderr {\n\n let mut reader = BufReader::new(stderr).lines();\n\n while let Ok(Some(line)) = reader.next_line().await {\n\n trace!(\"holochain bin stderr: {}\", line);\n\n }\n\n }\n\n });\n\n}\n\n\n\npub async fn check_started(holochain: &mut Child) {\n\n let started = tokio::time::timeout(std::time::Duration::from_secs(1), holochain.wait()).await;\n\n if let Ok(status) = started {\n\n panic!(\"Holochain failed to start. status: {:?}\", status);\n\n }\n\n}\n\n\n", "file_path": "crates/holochain/tests/websocket.rs", "rank": 29, "score": 256673.00483639498 }, { "content": "pub fn sign_ephemeral(\n\n _ribosome: Arc<impl RibosomeT>,\n\n _call_context: Arc<CallContext>,\n\n input: SignEphemeral,\n\n) -> Result<EphemeralSignatures, WasmError> {\n\n let rng = SystemRandom::new();\n\n let mut seed = [0; 32];\n\n rng.fill(&mut seed)\n\n .map_err(|e| WasmError::Guest(e.to_string()))?;\n\n let ephemeral_keypair =\n\n Ed25519KeyPair::from_seed_unchecked(&seed).map_err(|e| WasmError::Host(e.to_string()))?;\n\n\n\n let signatures: Result<Vec<Signature>, _> = input\n\n .into_inner()\n\n .into_iter()\n\n .map(|data| ephemeral_keypair.sign(&data).as_ref().try_into())\n\n .collect();\n\n\n\n Ok(EphemeralSignatures {\n\n signatures: signatures.map_err(|e| WasmError::Host(e.to_string()))?,\n", "file_path": "crates/holochain/src/core/ribosome/host_fn/sign_ephemeral.rs", "rank": 30, "score": 255160.61306347046 }, { "content": "pub fn get(txn: &Transaction<'_>, key: EntryDefBufferKey) -> StateQueryResult<Option<EntryDef>> {\n\n let key: EntryDefStoreKey = key.into();\n\n let item = txn\n\n .query_row(\n\n \"SELECT blob FROM EntryDef WHERE key = :key\",\n\n named_params! {\n\n \":key\": key\n\n },\n\n |row| {\n\n let item = row.get(\"blob\")?;\n\n Ok(item)\n\n },\n\n )\n\n .optional()?;\n\n match item {\n\n Some(item) => Ok(Some(from_blob(item)?)),\n\n None => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "crates/holochain_state/src/entry_def.rs", "rank": 31, "score": 254732.7206371766 }, { "content": "pub fn get_agent_activity(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n input: GetAgentActivityInput,\n\n) -> Result<AgentActivity, WasmError> {\n\n let GetAgentActivityInput {\n\n agent_pubkey,\n\n chain_query_filter,\n\n activity_request,\n\n } = input;\n\n let options = match activity_request {\n\n ActivityRequest::Status => GetActivityOptions {\n\n include_valid_activity: false,\n\n include_rejected_activity: false,\n\n ..Default::default()\n\n },\n\n ActivityRequest::Full => GetActivityOptions {\n\n include_valid_activity: true,\n\n include_rejected_activity: true,\n\n ..Default::default()\n", "file_path": "crates/holochain/src/core/ribosome/host_fn/get_agent_activity.rs", "rank": 32, "score": 250708.83827274188 }, { "content": "#[allow(clippy::extra_unused_lifetimes)]\n\npub fn agent_info<'a>(\n\n _ribosome: Arc<impl RibosomeT>,\n\n call_context: Arc<CallContext>,\n\n _input: (),\n\n) -> Result<AgentInfo, WasmError> {\n\n let agent_pubkey = call_context\n\n .host_access\n\n .workspace()\n\n .source_chain()\n\n .agent_pubkey()\n\n .clone();\n\n Ok(AgentInfo {\n\n agent_initial_pubkey: agent_pubkey.clone(),\n\n agent_latest_pubkey: agent_pubkey,\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(feature = \"slow_tests\")]\n\npub mod test {\n", "file_path": "crates/holochain/src/core/ribosome/host_fn/agent_info.rs", "rank": 33, "score": 250138.9709317935 }, { "content": "/// Encode a serde::Serialize item as message-pack data to given writer.\n\n/// You may wish to first wrap your writer in a BufWriter.\n\npub fn rmp_encode<W, S>(write: &mut W, item: S) -> Result<(), std::io::Error>\n\nwhere\n\n W: std::io::Write,\n\n S: serde::Serialize,\n\n{\n\n let mut se = rmp_serde::encode::Serializer::new(write)\n\n .with_struct_map()\n\n .with_string_variants();\n\n item.serialize(&mut se)\n\n .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/kitsune_p2p/types/src/codec.rs", "rank": 34, "score": 248336.9330218091 }, { "content": "/// A fixture AgentPubKey for unit testing.\n\n/// NB: This must match up with AgentPubKeyFixturator's Predictable curve\n\npub fn fake_agent_pubkey_1() -> AgentPubKey {\n\n AgentPubKey::try_from(\"uhCAkmrkoAHPVf_eufG7eC5fm6QKrW5pPMoktvG5LOC0SnJ4vV1Uv\").unwrap()\n\n}\n\n\n", "file_path": "crates/holochain_zome_types/src/test_utils.rs", "rank": 35, "score": 246054.15895219828 }, { "content": "/// Another fixture AgentPubKey for unit testing.\n\n/// NB: This must match up with AgentPubKeyFixturator's Predictable curve\n\npub fn fake_agent_pubkey_2() -> AgentPubKey {\n\n AgentPubKey::try_from(\"uhCAke1j8Z2a-_min0h0pGuEMcYlo_V1l1mt9OtBuywKmHlg4L_R-\").unwrap()\n\n}\n\n\n", "file_path": "crates/holochain_zome_types/src/test_utils.rs", "rank": 36, "score": 246054.11053232156 }, { "content": "/// Helpers for constructing AgentActivity\n\npub trait AgentActivityExt {\n\n /// Create an empty chain status\n\n fn empty<T>(agent: &AgentPubKey) -> AgentActivityResponse<T> {\n\n AgentActivityResponse {\n\n agent: agent.clone(),\n\n valid_activity: ChainItems::NotRequested,\n\n rejected_activity: ChainItems::NotRequested,\n\n status: ChainStatus::Empty,\n\n // TODO: Add the actual highest observed in a follow up PR\n\n highest_observed: None,\n\n }\n\n }\n\n}\n\n\n\nimpl AgentActivityExt for AgentActivityResponse {}\n", "file_path": "crates/holochain_types/src/chain.rs", "rank": 37, "score": 243228.6821407312 }, { "content": "/// Helper function to get a single agent info\n\npub fn get_single_agent_info(\n\n env: EnvRead,\n\n _space: DnaHash,\n\n agent: AgentPubKey,\n\n) -> StateQueryResult<Option<AgentInfoSigned>> {\n\n let agent = agent.to_kitsune();\n\n fresh_reader!(env, |r| Ok(r.p2p_get(&agent)?))\n\n}\n\n\n\n/// Interconnect every provided pair of conductors via their peer store databases\n\n#[cfg(any(test, feature = \"test_utils\"))]\n\npub async fn exchange_peer_info(envs: Vec<EnvWrite>) {\n\n for (i, a) in envs.iter().enumerate() {\n\n for (j, b) in envs.iter().enumerate() {\n\n if i == j {\n\n continue;\n\n }\n\n inject_agent_infos(a.clone(), all_agent_infos(b.clone().into()).unwrap().iter())\n\n .await\n\n .unwrap();\n\n inject_agent_infos(b.clone(), all_agent_infos(a.clone().into()).unwrap().iter())\n\n .await\n\n .unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 38, "score": 241989.18891033647 }, { "content": "/// Fill a buffer with data that is readable as latency information.\n\n/// Note, the minimum message size to get the timing data across is 16 bytes.\n\npub fn fill_with_latency_info(buf: &mut [u8]) {\n\n if buf.is_empty() {\n\n return;\n\n }\n\n\n\n // make sure we call this first, so we don't go back in time\n\n let epoch = *LOC_EPOCH;\n\n\n\n let now = std::time::Instant::now();\n\n let now = now.duration_since(epoch).as_secs_f64();\n\n\n\n // create a pattern of tag/marker\n\n let mut pat = [0_u8; 16];\n\n pat[0..8].copy_from_slice(LAT_TAG);\n\n pat[8..16].copy_from_slice(&now.to_le_bytes());\n\n\n\n // copy the tag/marker pattern repeatedly into the buffer\n\n let mut offset = 0;\n\n while offset < buf.len() {\n\n let len = std::cmp::min(pat.len(), buf.len() - offset);\n\n buf[offset..offset + len].copy_from_slice(&pat[..len]);\n\n offset += len;\n\n }\n\n}\n\n\n\n/// Return the duration since the time encoded in a latency info buffer.\n\n/// Returns a unit error if we could not parse the buffer into time data.\n", "file_path": "crates/kitsune_p2p/types/src/tx2/tx2_utils/latency.rs", "rank": 39, "score": 241957.85645570583 }, { "content": "/// Implementors are able to create a new read-only DB transaction\n\npub trait ReadManager<'e> {\n\n /// Run a closure, passing in a new read-only transaction\n\n fn with_reader<E, R, F>(&'e mut self, f: F) -> Result<R, E>\n\n where\n\n E: From<DatabaseError>,\n\n F: 'e + FnOnce(Transaction) -> Result<R, E>;\n\n\n\n #[cfg(feature = \"test_utils\")]\n\n /// Same as with_reader, but with no Results: everything gets unwrapped\n\n fn with_reader_test<R, F>(&'e mut self, f: F) -> R\n\n where\n\n F: 'e + FnOnce(Transaction) -> R;\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/db.rs", "rank": 40, "score": 241084.57742242113 }, { "content": "/// Implementors are able to create a new read-write DB transaction\n\npub trait WriteManager<'e> {\n\n /// Run a closure, passing in a mutable reference to a read-write\n\n /// transaction, and commit the transaction after the closure has run.\n\n /// If there is a SQLite error, recover from it and re-run the closure.\n\n // FIXME: B-01566: implement write failure detection\n\n #[cfg(feature = \"test_utils\")]\n\n fn with_commit_sync<E, R, F>(&'e mut self, f: F) -> Result<R, E>\n\n where\n\n E: From<DatabaseError>,\n\n F: 'e + FnOnce(&mut Transaction) -> Result<R, E>;\n\n\n\n // /// Get a raw read-write transaction for this environment.\n\n // /// It is preferable to use WriterManager::with_commit for database writes,\n\n // /// which can properly recover from and manage write failures\n\n // fn writer_unmanaged(&'e mut self) -> DatabaseResult<Writer<'e>>;\n\n\n\n #[cfg(feature = \"test_utils\")]\n\n fn with_commit_test<R, F>(&'e mut self, f: F) -> Result<R, DatabaseError>\n\n where\n\n F: 'e + FnOnce(&mut Transaction) -> R,\n", "file_path": "crates/holochain_sqlite/src/db.rs", "rank": 41, "score": 241084.49763715157 }, { "content": "#[async_trait::async_trait]\n\npub trait SignedHeaderHashedExt {\n\n /// Create a hash from data\n\n fn from_content_sync(signed_header: SignedHeader) -> SignedHeaderHashed;\n\n /// Sign some content\n\n #[allow(clippy::new_ret_no_self)]\n\n async fn new(\n\n keystore: &KeystoreSender,\n\n header: HeaderHashed,\n\n ) -> Result<SignedHeaderHashed, KeystoreError>;\n\n /// Validate the data\n\n async fn validate(&self) -> Result<(), KeystoreError>;\n\n}\n\n\n\n#[allow(missing_docs)]\n\n#[async_trait::async_trait]\n\nimpl SignedHeaderHashedExt for SignedHeaderHashed {\n\n fn from_content_sync(signed_header: SignedHeader) -> Self\n\n where\n\n Self: Sized,\n\n {\n", "file_path": "crates/holochain_types/src/element.rs", "rank": 42, "score": 240649.18782349076 }, { "content": "/// Keeping with convention if Alice is pubkey 1\n\n/// and bob is pubkey 2 the this helps make test\n\n/// logging easier to read.\n\npub fn which_agent(key: &AgentPubKey) -> String {\n\n let key = key.to_string();\n\n let alice = fake_agent_pubkey_1().to_string();\n\n let bob = fake_agent_pubkey_2().to_string();\n\n if key == alice {\n\n return \"alice\".to_string();\n\n }\n\n if key == bob {\n\n return \"bob\".to_string();\n\n }\n\n key\n\n}\n\n\n", "file_path": "crates/holochain_types/src/test_utils.rs", "rank": 43, "score": 240127.73093783576 }, { "content": "fn now() -> u64 {\n\n std::time::SystemTime::now()\n\n .duration_since(std::time::UNIX_EPOCH)\n\n .unwrap()\n\n .as_millis() as u64\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 44, "score": 239873.5236693594 }, { "content": "/// Query the _headers_ of a remote agent's chain.\n\n///\n\n/// The agent activity is only the headers of their source chain.\n\n/// The agent activity is held by the neighbourhood centered on the agent's public key, rather than a content hash like the rest of the DHT.\n\n///\n\n/// The agent activity can be filtered with [ `ChainQueryFilter` ] like a local chain query.\n\npub fn get_agent_activity(\n\n agent: AgentPubKey,\n\n query: ChainQueryFilter,\n\n request: ActivityRequest,\n\n) -> ExternResult<AgentActivity> {\n\n HDK.with(|h| {\n\n h.borrow()\n\n .get_agent_activity(GetAgentActivityInput::new(agent, query, request))\n\n })\n\n}\n\n\n", "file_path": "crates/hdk/src/chain.rs", "rank": 45, "score": 239664.6561200419 }, { "content": "pub fn time_to_micros(t: SystemTime) -> DatabaseResult<i64> {\n\n t.duration_since(std::time::UNIX_EPOCH)\n\n .map_err(|e| DatabaseError::Other(e.into()))?\n\n .as_micros()\n\n .try_into()\n\n .map_err(|e: TryFromIntError| DatabaseError::Other(e.into()))\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/db/p2p_metrics.rs", "rank": 46, "score": 239095.46100770967 }, { "content": "/// A fixture AgentPubKey for unit testing.\n\npub fn fake_agent_pub_key(name: u8) -> AgentPubKey {\n\n fake_holo_hash(name, hash_type::Agent::new())\n\n}\n\n\n", "file_path": "crates/holochain_zome_types/src/test_utils.rs", "rank": 47, "score": 238689.86962349914 }, { "content": "/// Create a [TestDb] of [DbKind::Cell], backed by a temp directory.\n\npub fn test_cell_db() -> TestDb {\n\n let cell_id = fake_cell_id(1);\n\n test_db(DbKind::Cell(cell_id))\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/test_utils.rs", "rank": 48, "score": 237350.06187546038 }, { "content": "/// Fetch an Entry from a DB by its hash. Requires no joins.\n\npub fn get_entry_from_db(\n\n txn: &Transaction,\n\n entry_hash: &EntryHash,\n\n) -> StateQueryResult<Option<Entry>> {\n\n let entry = txn.query_row_named(\n\n \"\n\n SELECT Entry.blob AS entry_blob FROM Entry\n\n WHERE hash = :entry_hash\n\n \",\n\n named_params! {\n\n \":entry_hash\": entry_hash,\n\n },\n\n |row| {\n\n Ok(from_blob::<Entry>(\n\n row.get(row.column_index(\"entry_blob\")?)?,\n\n ))\n\n },\n\n );\n\n if let Err(holochain_sqlite::rusqlite::Error::QueryReturnedNoRows) = &entry {\n\n Ok(None)\n\n } else {\n\n Ok(Some(entry??))\n\n }\n\n}\n", "file_path": "crates/holochain_state/src/query.rs", "rank": 49, "score": 236957.17202491738 }, { "content": "pub fn time_from_micros(micros: i64) -> DatabaseResult<SystemTime> {\n\n std::time::UNIX_EPOCH\n\n .checked_add(Duration::from_micros(micros as u64))\n\n .ok_or_else(|| {\n\n DatabaseError::Other(anyhow::anyhow!(\n\n \"Got invalid i64 microsecond timestamp: {}\",\n\n micros\n\n ))\n\n })\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/db/p2p_metrics.rs", "rank": 50, "score": 236837.0663948891 }, { "content": "pub fn insert_element_scratch(scratch: &mut Scratch, element: Element) {\n\n let (header, entry) = element.into_inner();\n\n scratch.add_header(header);\n\n if let Some(entry) = entry.into_option() {\n\n scratch.add_entry(EntryHashed::from_content_sync(entry))\n\n }\n\n}\n\n\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 51, "score": 236611.17947482137 }, { "content": "/// Trivial wrapper for `__agent_info` host function.\n\n/// Agent info input struct is `()` so the function call simply looks like this:\n\n///\n\n/// ```ignore\n\n/// let agent_info = agent_info()?;\n\n/// ```\n\n///\n\n/// the [ `AgentInfo` ] is the current agent's original pubkey/address that they joined the network with\n\n/// and their most recent pubkey/address.\n\npub fn agent_info() -> ExternResult<AgentInfo> {\n\n HDK.with(|h| h.borrow().agent_info(()))\n\n}\n\n\n", "file_path": "crates/hdk/src/info.rs", "rank": 52, "score": 235333.5975440197 }, { "content": " pub trait HostFnApiT {\n\n $(\n\n fn $f(&self, _: $in_arg) -> Result<$out_arg, HostFnApiError>;\n\n )*\n\n }\n\n }\n\n}\n\n\n\n// Every externed function that the zome developer exposes to holochain returns `ExternIO`.\n\n// The zome developer can expose callbacks in a \"sparse\" way based on names and the functions\n\n// can take different input (e.g. validation vs. hooks like init, etc.).\n\n// All we can say is that some SerializedBytes are being received and returned.\n\n// In the case of ZomeExtern functions exposed to a client, the data input/output is entirely\n\n// arbitrary so we can't say anything at all. In this case the happ developer must BYO\n\n// deserialization context to match the client, either directly or via. the HDK.\n\n// Note though, that _unlike_ zome externs, the host _does_ know exactly the guest should be\n\n// returning for callbacks, it's just that the unpacking of the return happens in two steps:\n\n// - first the sparse callback is triggered with SB input/output\n\n// - then the guest inflates the expected input or the host the expected output based on the\n\n// callback flavour\n", "file_path": "crates/holochain_zome_types/src/zome_io.rs", "rank": 53, "score": 234498.03115264408 }, { "content": "/// Query the p2p_metrics database in a variety of ways\n\npub fn query_metrics(\n\n txn: &mut Transaction,\n\n query: MetricQuery,\n\n) -> DatabaseResult<MetricQueryAnswer> {\n\n Ok(match query {\n\n MetricQuery::LastSync { agent } => {\n\n let agent_bytes: &[u8] = agent.as_ref();\n\n let timestamp: Option<i64> = txn.query_row(\n\n sql_p2p_metrics::QUERY_LAST_SYNC,\n\n named_params! {\n\n \":agent\": agent_bytes,\n\n \":kind\": MetricKind::QuickGossip.to_string(),\n\n },\n\n |row| row.get(0),\n\n )?;\n\n let time = match timestamp {\n\n Some(t) => Some(time_from_micros(t)?),\n\n None => None,\n\n };\n\n MetricQueryAnswer::LastSync(time)\n", "file_path": "crates/holochain_sqlite/src/db/p2p_metrics.rs", "rank": 54, "score": 234199.6055032065 }, { "content": "/// Record a p2p metric datum\n\npub fn put_metric_datum(\n\n txn: &mut Transaction,\n\n agent: Arc<KitsuneAgent>,\n\n metric: MetricKind,\n\n timestamp: std::time::SystemTime,\n\n) -> DatabaseResult<()> {\n\n let agent_bytes: &[u8] = agent.as_ref();\n\n txn.execute(\n\n sql_p2p_metrics::INSERT,\n\n named_params! {\n\n \":agent\": agent_bytes,\n\n \":kind\": metric.to_string(),\n\n \":moment\": time_to_micros(timestamp)?\n\n },\n\n )?;\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/db/p2p_metrics.rs", "rank": 55, "score": 231547.56406979478 }, { "content": "/// Get the peer density an agent is currently seeing within\n\n/// a given [`DhtArc`]\n\npub fn query_peer_density(\n\n env: EnvWrite,\n\n kitsune_space: Arc<kitsune_p2p::KitsuneSpace>,\n\n dht_arc: DhtArc,\n\n) -> ConductorResult<PeerDensity> {\n\n let now = now();\n\n let arcs = env.conn()?.p2p_list()?;\n\n let arcs = fallible_iterator::convert(arcs.into_iter().map(ConductorResult::Ok))\n\n .filter_map(|v| {\n\n if dht_arc.contains(v.as_agent_ref().get_loc()) {\n\n let info = kitsune_p2p::agent_store::AgentInfo::try_from(&v)?;\n\n if info.as_space_ref() == kitsune_space.as_ref() && !is_expired(now, &info) {\n\n Ok(Some(info.dht_arc()?))\n\n } else {\n\n Ok(None)\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n })\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 56, "score": 231411.84903942334 }, { "content": "/// Turn an [AgentKey] into a [KitsuneAgent]\n\npub fn agent_holo_to_kit(a: holo_hash::AgentPubKey) -> kitsune_p2p::KitsuneAgent {\n\n a.into_kitsune_raw()\n\n}\n\n\n", "file_path": "crates/holochain_p2p/src/types.rs", "rank": 57, "score": 230523.96859037527 }, { "content": "/// HashTypes whose content are only hashable asynchronously, i.e. the content is unbounded in size\n\npub trait HashTypeAsync: HashType {}\n", "file_path": "crates/holo_hash/src/hash_type.rs", "rank": 58, "score": 230250.74182557833 }, { "content": "/// internal REPR for holo hash\n\npub fn holo_hash_encode(data: &[u8]) -> String {\n\n format!(\"u{}\", base64::encode_config(data, base64::URL_SAFE_NO_PAD),)\n\n}\n\n\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 59, "score": 229411.84974004055 }, { "content": "pub fn write_config(mut path: PathBuf, config: &ConductorConfig) -> PathBuf {\n\n path.push(\"conductor_config.yml\");\n\n std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap()).unwrap();\n\n path\n\n}\n\n\n\n#[instrument(skip(holochain, response))]\n\nasync fn check_timeout<T>(\n\n holochain: &mut Child,\n\n response: impl Future<Output = Result<T, WebsocketError>>,\n\n timeout_millis: u64,\n\n) -> T {\n\n match tokio::time::timeout(std::time::Duration::from_millis(timeout_millis), response).await {\n\n Ok(response) => response.unwrap(),\n\n Err(_) => {\n\n holochain.kill().await.unwrap();\n\n error!(\"Timeout\");\n\n panic!(\"Timed out on request after {}\", timeout_millis);\n\n }\n\n }\n", "file_path": "crates/holochain/tests/websocket.rs", "rank": 60, "score": 227765.5849217854 }, { "content": "/// Extension trait to augment the direct_api version of KdEntrySigned\n\npub trait KdEntrySignedExt: Sized {\n\n /// Build out a full, checked entry from wire encoding\n\n fn from_wire(wire: Box<[u8]>) -> BoxFuture<'static, KdResult<Self>>;\n\n\n\n /// Build out a full, checked entry from db encoding\n\n fn from_str(s: &str) -> BoxFuture<'static, KdResult<Self>>;\n\n\n\n /// Sign entry data into a full KdEntry instance\n\n fn from_content(\n\n persist: &KdPersist,\n\n content: KdEntryContent,\n\n ) -> BoxFuture<'static, KdResult<Self>>;\n\n\n\n /// Sign entry data into a full KdEntry instance with additional binary data\n\n fn from_content_with_binary(\n\n persist: &KdPersist,\n\n content: KdEntryContent,\n\n binary: &[u8],\n\n ) -> BoxFuture<'static, KdResult<Self>>;\n\n}\n", "file_path": "crates/kitsune_p2p/direct/src/types/kdentry.rs", "rank": 61, "score": 227732.10203919525 }, { "content": "/// Extension trait to augment the direct_api version of KdAgentInfo\n\npub trait KdAgentInfoExt: Sized {\n\n /// convert KdAgentInfo into a kitsune AgentInfoSigned\n\n fn to_kitsune(&self) -> AgentInfoSigned;\n\n\n\n /// convert a kitsune AgentInfoSigned into KdAgentInfo\n\n fn from_kitsune(kitsune: &AgentInfoSigned) -> KdResult<Self>;\n\n}\n\n\n", "file_path": "crates/kitsune_p2p/direct/src/types/kdagent.rs", "rank": 62, "score": 227564.37391823402 }, { "content": "/// Write [`ConductorConfig`] to [`CONDUCTOR_CONFIG`]\n\npub fn write_config(mut path: PathBuf, config: &ConductorConfig) -> PathBuf {\n\n path.push(CONDUCTOR_CONFIG);\n\n std::fs::write(path.clone(), serde_yaml::to_string(&config).unwrap()).unwrap();\n\n path\n\n}\n\n\n", "file_path": "crates/hc_sandbox/src/config.rs", "rank": 63, "score": 225575.7742161465 }, { "content": "/// ## Remote Signal\n\n/// Send a signal to a list of other agents.\n\n/// This will send the data as an [ `AppSignal` ] to\n\n/// this zome for all the agents supplied.\n\n///\n\n/// ### Non-blocking\n\n/// This is a non-blocking call and will not return an\n\n/// error if the calls fail. This is designed to be used\n\n/// as a send and forget operation.\n\n/// A log will be produced at `[remote_signal]=info` if the calls\n\n/// fail though (this may be removed in the future).\n\n///\n\n/// ### Usage\n\n/// Currently this requires the function `recv_remote_signal` be\n\n/// exposed by this zome with a signature like:\n\n/// ```ignore\n\n/// #[hdk_extern]\n\n/// fn recv_remote_signal(signal: SerializedBytes) -> ExternResult<()> {\n\n/// emit_signal(&signal)?;\n\n/// Ok(())\n\n/// }\n\n/// ```\n\n/// This function will also need to be added to your init as a\n\n/// unrestricted cap grant so it can be called remotely.\n\n///\n\n/// This requirements will likely be removed in the future as\n\n/// we design a better way to grant the capability to remote signal.\n\npub fn remote_signal<I>(input: I, agents: Vec<AgentPubKey>) -> ExternResult<()>\n\nwhere\n\n I: serde::Serialize + std::fmt::Debug,\n\n{\n\n HDK.with(|h| {\n\n h.borrow().remote_signal(RemoteSignal {\n\n signal: ExternIO::encode(input)?,\n\n agents,\n\n })\n\n })\n\n}\n", "file_path": "crates/hdk/src/p2p.rs", "rank": 64, "score": 224395.10087866307 }, { "content": "/// Sign something that is serializable using the private key for the passed public key.\n\n///\n\n/// Serde convenience for [ `sign_raw `].\n\npub fn sign<K, D>(key: K, data: D) -> ExternResult<Signature>\n\nwhere\n\n K: Into<AgentPubKey>,\n\n D: serde::Serialize + std::fmt::Debug,\n\n{\n\n HDK.with(|h| h.borrow().sign(Sign::new(key.into(), data)?))\n\n}\n\n\n", "file_path": "crates/hdk/src/ed25519.rs", "rank": 65, "score": 222770.38338542558 }, { "content": "/// Construct a bound async read/write memory channel\n\npub fn bound_async_mem_channel(\n\n max_bytes: usize,\n\n maybe_active: Option<&Active>,\n\n) -> (\n\n Box<dyn futures::io::AsyncWrite + 'static + Send + Unpin>,\n\n Box<dyn futures::io::AsyncRead + 'static + Send + Unpin>,\n\n) {\n\n let buf = Vec::with_capacity(max_bytes);\n\n\n\n let inner = Arc::new(Share::new(MemInner {\n\n buf,\n\n max_bytes,\n\n closed: false,\n\n want_read_waker: None,\n\n want_write_waker: None,\n\n }));\n\n\n\n if let Some(active) = maybe_active {\n\n let k_inner = inner.clone();\n\n active.register_kill_cb(move || {\n", "file_path": "crates/kitsune_p2p/types/src/tx2/tx2_utils/mem_chan.rs", "rank": 66, "score": 221816.90208936186 }, { "content": "/// Load sandbox paths from the `.hc` file.\n\npub fn load(mut hc_dir: PathBuf) -> anyhow::Result<Vec<PathBuf>> {\n\n let mut paths = Vec::new();\n\n hc_dir.push(\".hc\");\n\n if hc_dir.exists() {\n\n let existing = std::fs::read_to_string(hc_dir)?;\n\n for sandbox in existing.lines() {\n\n let path = PathBuf::from(sandbox);\n\n let mut config_path = path.clone();\n\n config_path.push(CONDUCTOR_CONFIG);\n\n if config_path.exists() {\n\n paths.push(path);\n\n } else {\n\n tracing::error!(\"Failed to load path {} from existing .hc\", path.display());\n\n }\n\n }\n\n }\n\n Ok(paths)\n\n}\n\n\n", "file_path": "crates/hc_sandbox/src/save.rs", "rank": 67, "score": 221709.19371626014 }, { "content": "/// Read the [`ConductorConfig`] from the file [`CONDUCTOR_CONFIG`] in the provided path.\n\npub fn read_config(mut path: PathBuf) -> anyhow::Result<Option<ConductorConfig>> {\n\n path.push(CONDUCTOR_CONFIG);\n\n\n\n match std::fs::read_to_string(path) {\n\n Ok(yaml) => Ok(Some(serde_yaml::from_str(&yaml)?)),\n\n Err(_) => Ok(None),\n\n }\n\n}\n", "file_path": "crates/hc_sandbox/src/config.rs", "rank": 68, "score": 221709.19371626014 }, { "content": "/// Insert a [`DhtOp`] into the [`Scratch`].\n\npub fn insert_op_scratch(scratch: &mut Scratch, op: DhtOpHashed) -> StateMutationResult<()> {\n\n let (op, _) = op.into_inner();\n\n let op_light = op.to_light();\n\n let header = op.header();\n\n let signature = op.signature().clone();\n\n if let Some(entry) = op.entry() {\n\n let entry_hashed = EntryHashed::with_pre_hashed(\n\n entry.clone(),\n\n header\n\n .entry_hash()\n\n .ok_or_else(|| DhtOpError::HeaderWithoutEntry(header.clone()))?\n\n .clone(),\n\n );\n\n scratch.add_entry(entry_hashed);\n\n }\n\n let header_hashed = HeaderHashed::with_pre_hashed(header, op_light.header_hash().to_owned());\n\n let header_hashed = SignedHeaderHashed::with_presigned(header_hashed, signature);\n\n scratch.add_header(header_hashed);\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/holochain_state/src/mutations.rs", "rank": 69, "score": 221391.24375408917 }, { "content": "#[hdk_extern]\n\nfn send_assigned_cap_claim(agent: AgentPubKey) -> ExternResult<()> {\n\n let tag = String::from(\"has_cap_claim\");\n\n\n\n // make a new secret\n\n let secret = CapSecret::try_from_random()?;\n\n\n\n // grant the secret as assigned (can only be used by the intended agent)\n\n let mut functions: GrantedFunctions = BTreeSet::new();\n\n let this_zome = zome_info()?.zome_name;\n\n functions.insert((this_zome.clone(), \"needs_cap_claim\".into()));\n\n create_cap_grant(CapGrantEntry {\n\n access: (secret, agent.clone()).into(),\n\n functions,\n\n tag: tag.clone(),\n\n })?;\n\n\n\n // send the assigned cap token\n\n call_remote(\n\n agent,\n\n this_zome,\n\n \"accept_cap_claim\".into(),\n\n None,\n\n &CapClaim::new(tag, agent_info()?.agent_latest_pubkey, secret),\n\n )?;\n\n Ok(())\n\n}\n", "file_path": "crates/test_utils/wasm/wasm_workspace/capability/src/lib.rs", "rank": 70, "score": 220424.2976034134 }, { "content": "/// Efficiently read framed data.\n\npub trait AsFramedReader: 'static + Send + Unpin {\n\n /// Read a frame of data from this AsFramedReader instance.\n\n /// This returns a Vec in case the first read contains multiple small items.\n\n fn read(&mut self, timeout: KitsuneTimeout) -> BoxFuture<'_, KitsuneResult<RR>>;\n\n}\n\n\n", "file_path": "crates/kitsune_p2p/types/src/tx2/framed.rs", "rank": 71, "score": 219169.44969683472 }, { "content": "/// Create a [TestEnv] of [DbKind::P2pAgentStore], backed by a temp directory.\n\npub fn test_p2p_agent_store_env() -> TestEnv {\n\n test_env(DbKind::P2pAgentStore(Arc::new(KitsuneSpace(vec![0; 36]))))\n\n}\n\n\n", "file_path": "crates/holochain_state/src/test_utils.rs", "rank": 72, "score": 219153.22482852946 }, { "content": "/// Remove sandboxes by their index in the file.\n\n/// You can get the index by calling [`load`].\n\n/// If no sandboxes are passed in then all are deleted.\n\n/// If all sandboxes are deleted the `.hc` file will be removed.\n\npub fn clean(mut hc_dir: PathBuf, sandboxes: Vec<usize>) -> anyhow::Result<()> {\n\n let existing = load(hc_dir.clone())?;\n\n let sandboxes_len = sandboxes.len();\n\n let to_remove: Vec<_> = if sandboxes.is_empty() {\n\n existing.iter().collect()\n\n } else {\n\n sandboxes\n\n .into_iter()\n\n .filter_map(|i| existing.get(i))\n\n .collect()\n\n };\n\n let to_remove_len = to_remove.len();\n\n for p in to_remove {\n\n if p.exists() && p.is_dir() {\n\n if let Err(e) = std::fs::remove_dir_all(p) {\n\n tracing::error!(\"Failed to remove {} because {:?}\", p.display(), e);\n\n }\n\n }\n\n }\n\n if sandboxes_len == 0 || sandboxes_len == to_remove_len {\n", "file_path": "crates/hc_sandbox/src/save.rs", "rank": 73, "score": 218180.34748719103 }, { "content": "fn num_valid(txn: &Transaction) -> usize {\n\n txn\n\n .query_row(\"SELECT COUNT(hash) FROM DhtOP WHERE when_integrated IS NOT NULL AND validation_status = :status\", \n\n named_params!{\n\n \":status\": ValidationStatus::Valid,\n\n },\n\n |row| row.get(0))\n\n .unwrap()\n\n}\n\n\n\nasync fn run_test(\n\n alice_cell_id: CellId,\n\n bob_cell_id: CellId,\n\n handle: ConductorHandle,\n\n dna_file: &DnaFile,\n\n) -> usize {\n\n // Check if the correct number of ops are integrated\n\n // every 100 ms for a maximum of 10 seconds but early exit\n\n // if they are there.\n\n let num_attempts = 100;\n", "file_path": "crates/holochain/src/core/workflow/app_validation_workflow/tests.rs", "rank": 74, "score": 217697.86735229113 }, { "content": "fn limbo_is_empty(txn: &Transaction) -> bool {\n\n let not_empty: bool = txn\n\n .query_row(\n\n \"SELECT EXISTS(SELECT 1 FROM DhtOP WHERE when_integrated IS NULL)\",\n\n [],\n\n |row| row.get(0),\n\n )\n\n .unwrap();\n\n !not_empty\n\n}\n\n\n", "file_path": "crates/holochain/src/core/workflow/app_validation_workflow/tests.rs", "rank": 75, "score": 217697.86735229113 }, { "content": "fn is_expired(now: u64, info: &kitsune_p2p::agent_store::AgentInfo) -> bool {\n\n info.signed_at_ms()\n\n .checked_add(info.expires_after_ms())\n\n .map(|expires| expires <= now)\n\n .unwrap_or(true)\n\n}\n\n\n", "file_path": "crates/holochain/src/conductor/p2p_agent_store.rs", "rank": 76, "score": 216083.8679237831 }, { "content": "/// Parse a list of dnas.\n\n/// If paths are directories then each directory\n\n/// will be searched for the first file that matches\n\n/// `*.dna`.\n\npub fn parse_dnas(mut dnas: Vec<PathBuf>) -> anyhow::Result<Vec<PathBuf>> {\n\n if dnas.is_empty() {\n\n dnas.push(std::env::current_dir()?);\n\n }\n\n for dna in dnas.iter_mut() {\n\n if dna.is_dir() {\n\n let file_path = search_for_dna(&dna)?;\n\n *dna = file_path;\n\n }\n\n ensure!(\n\n dna.file_name()\n\n .map(|f| f.to_string_lossy().ends_with(\".dna\"))\n\n .unwrap_or(false),\n\n \"File {} is not a valid dna file name: (e.g. my-dna.dna)\",\n\n dna.display()\n\n );\n\n }\n\n Ok(dnas)\n\n}\n\n\n", "file_path": "crates/hc_sandbox/src/bundles.rs", "rank": 77, "score": 216056.5472469369 }, { "content": "/// Save all sandboxes to the `.hc` file in the `hc_dir` directory.\n\npub fn save(mut hc_dir: PathBuf, paths: Vec<PathBuf>) -> anyhow::Result<()> {\n\n use std::io::Write;\n\n std::fs::create_dir_all(&hc_dir)?;\n\n hc_dir.push(\".hc\");\n\n let mut file = std::fs::OpenOptions::new()\n\n .append(true)\n\n .create(true)\n\n .open(hc_dir)?;\n\n\n\n for path in paths {\n\n writeln!(file, \"{}\", path.display())?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "crates/hc_sandbox/src/save.rs", "rank": 78, "score": 216056.5472469369 }, { "content": "/// internal compute a 32 byte blake2b hash\n\npub fn blake2b_256(data: &[u8]) -> Vec<u8> {\n\n let hash = blake2b_simd::Params::new().hash_length(32).hash(data);\n\n hash.as_bytes().to_vec()\n\n}\n\n\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 79, "score": 215422.54935617986 }, { "content": "/// internal compute a 16 byte blake2b hash\n\npub fn blake2b_128(data: &[u8]) -> Vec<u8> {\n\n let hash = blake2b_simd::Params::new().hash_length(16).hash(data);\n\n hash.as_bytes().to_vec()\n\n}\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 80, "score": 215422.54935617986 }, { "content": "#[deprecated = \"Raising visibility into a change that needs to happen after `use_existing` is implemented\"]\n\npub fn we_must_remember_to_rework_cell_panic_handling_after_implementing_use_existing_cell_resolution(\n\n) {\n\n}\n\n\n\n/// The result of running Cell resolution\n\n// TODO: rework, make fields private\n\n#[allow(missing_docs)]\n\n#[derive(PartialEq, Eq, Debug)]\n\npub struct CellSlotResolution {\n\n pub agent: AgentPubKey,\n\n pub dnas_to_register: Vec<(DnaFile, Option<MembraneProof>)>,\n\n pub slots: Vec<(SlotId, AppSlot)>,\n\n}\n\n\n\n#[allow(missing_docs)]\n\nimpl CellSlotResolution {\n\n pub fn new(agent: AgentPubKey) -> Self {\n\n Self {\n\n agent,\n\n dnas_to_register: Default::default(),\n", "file_path": "crates/holochain_types/src/app/app_bundle.rs", "rank": 81, "score": 213185.62242977094 }, { "content": "fn register_agent_activity(a: TestData) -> (Vec<Db>, Vec<Db>, &'static str) {\n\n let op = DhtOp::RegisterAgentActivity(a.signature.clone(), a.dna_header.clone());\n\n let pre_state = vec![Db::IntQueue(op.clone())];\n\n let expect = vec![\n\n Db::Integrated(op.clone()),\n\n Db::MetaActivity(a.dna_header.clone()),\n\n ];\n\n (pre_state, expect, \"register agent activity\")\n\n}\n\n\n", "file_path": "crates/holochain/src/core/workflow/integrate_dht_ops_workflow/tests.rs", "rank": 82, "score": 212878.45522116104 }, { "content": "#[allow(clippy::let_and_return)]\n\npub fn mdns_listen(service_type: String) -> impl Stream<Item = Result<MdnsResponse, MdnsError>> {\n\n //let service_name = format!(\"{}.local\", HC_SERVICE_TYPE);\n\n let svc_type = format!(\"_{}{}.local\", service_type, HC_SERVICE_PROTOCOL);\n\n //println!(\"MDNS query for service type '{}'\", svc_type);\n\n let query = mdns::discover::all(svc_type, Duration::from_secs(QUERY_INTERVAL_SEC))\n\n .expect(\"mdns Discover failed\");\n\n // Get Mdns Response stream\n\n let response_stream = query.listen();\n\n // Change it into a MdnsResponse stream\n\n let mdns_stream = response_stream\n\n // Filtering out Empty responses\n\n .filter(move |res| {\n\n match res {\n\n Ok(response) => !response.is_empty() && response.ip_addr().is_some(),\n\n Err(_) => true, // Keep errors\n\n }\n\n })\n\n .map(|maybe_response| {\n\n if let Err(e) = maybe_response {\n\n return Err(MdnsError::Mdns(e));\n", "file_path": "crates/kitsune_p2p/mdns/src/lib.rs", "rank": 83, "score": 212163.66728066286 }, { "content": "#[hdk_extern]\n\nfn call_create_entry_remotely(agent: AgentPubKey) -> ExternResult<HeaderHash> {\n\n let zome_call_response: ZomeCallResponse = call_remote(\n\n agent.clone(),\n\n \"create_entry\".to_string().into(),\n\n \"create_entry\".to_string().into(),\n\n None,\n\n &(),\n\n )?;\n\n\n\n match zome_call_response {\n\n ZomeCallResponse::Ok(v) => Ok(v.decode()?),\n\n ZomeCallResponse::Unauthorized(cell_id, zome_name, function_name, agent_pubkey) => Err(WasmError::Guest(format!(\"Unauthorized: {} {} {} {}\", cell_id, zome_name, function_name, agent_pubkey))),\n\n // Unbounded recursion.\n\n ZomeCallResponse::NetworkError(_) => call_create_entry_remotely(agent),\n\n }\n\n}\n", "file_path": "crates/test_utils/wasm/wasm_workspace/create_entry/src/lib.rs", "rank": 84, "score": 210960.15693386667 }, { "content": "/// Decode message-pack data from given reader into an owned item.\n\n/// You may wish to first wrap your reader in a BufReader.\n\npub fn rmp_decode<R, D>(r: &mut R) -> Result<D, std::io::Error>\n\nwhere\n\n R: std::io::Read,\n\n for<'de> D: Sized + serde::Deserialize<'de>,\n\n{\n\n let mut de = rmp_serde::decode::Deserializer::new(r);\n\n D::deserialize(&mut de).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))\n\n}\n\n\n", "file_path": "crates/kitsune_p2p/types/src/codec.rs", "rank": 85, "score": 209856.79935825677 }, { "content": "/// internal compute the holo dht location u32\n\npub fn holo_dht_location_bytes(data: &[u8]) -> Vec<u8> {\n\n // Assert the data size is relatively small so we are\n\n // comfortable executing this synchronously / blocking tokio thread.\n\n assert_eq!(32, data.len(), \"only 32 byte hashes supported\");\n\n\n\n let hash = blake2b_128(data);\n\n let mut out = vec![hash[0], hash[1], hash[2], hash[3]];\n\n for i in (4..16).step_by(4) {\n\n out[0] ^= hash[i];\n\n out[1] ^= hash[i + 1];\n\n out[2] ^= hash[i + 2];\n\n out[3] ^= hash[i + 3];\n\n }\n\n out\n\n}\n\n\n", "file_path": "crates/holo_hash/src/encode.rs", "rank": 86, "score": 207955.92482275903 }, { "content": "fn show_limbo(txn: &Transaction) -> Vec<DhtOpLight> {\n\n txn.prepare(\"SELECT blob FROM DhtOp WHERE when_integrated IS NULL\")\n\n .unwrap()\n\n .query_and_then([], |row| from_blob(row.get(\"blob\")?))\n\n .unwrap()\n\n .collect::<StateQueryResult<Vec<DhtOpLight>>>()\n\n .unwrap()\n\n}\n\n\n", "file_path": "crates/holochain/src/core/workflow/app_validation_workflow/tests.rs", "rank": 87, "score": 207009.5480047373 }, { "content": "fn rand_agent() -> KitsuneAgent {\n\n let mut rng = rand::thread_rng();\n\n\n\n let mut data = vec![0_u8; 36];\n\n rng.fill(&mut data[..]);\n\n KitsuneAgent(data)\n\n}\n\n\n", "file_path": "crates/holochain_sqlite/src/db/p2p_agent_store/p2p_test.rs", "rank": 89, "score": 204173.27327110973 }, { "content": "#[cfg(feature = \"packing\")]\n\npub fn prune_path<P: AsRef<Path>>(mut path: PathBuf, subpath: P) -> UnpackingResult<PathBuf> {\n\n if path.ends_with(&subpath) {\n\n for _ in subpath.as_ref().components() {\n\n let _ = path.pop();\n\n }\n\n Ok(path)\n\n } else {\n\n Err(UnpackingError::ManifestPathSuffixMismatch(\n\n path,\n\n subpath.as_ref().to_owned(),\n\n ))\n\n }\n\n}\n", "file_path": "crates/mr_bundle/src/util.rs", "rank": 90, "score": 203845.38127101242 }, { "content": "pub fn fill_db(env: &EnvWrite, op: DhtOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash.clone(), ValidationStatus::Valid).unwrap();\n\n set_when_integrated(txn, hash, timestamp::now()).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/holochain_cascade/src/test_utils.rs", "rank": 91, "score": 203311.10545202918 }, { "content": "pub fn wire_to_shh<T: TryInto<SignedHeader> + Clone>(op: &T) -> SignedHeaderHashed {\n\n let r = op.clone().try_into();\n\n match r {\n\n Ok(SignedHeader(header, signature)) => {\n\n SignedHeaderHashed::with_presigned(HeaderHashed::from_content_sync(header), signature)\n\n }\n\n Err(_) => unreachable!(),\n\n }\n\n}\n", "file_path": "crates/holochain_cascade/src/test_utils.rs", "rank": 92, "score": 202854.95923965255 }, { "content": "pub fn fill_db_pending(env: &EnvWrite, op: DhtOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash, ValidationStatus::Valid).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/holochain_cascade/src/test_utils.rs", "rank": 93, "score": 201121.8305077577 }, { "content": "pub fn fill_db_rejected(env: &EnvWrite, op: DhtOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n let hash = op.as_hash().clone();\n\n insert_op(txn, op, false).unwrap();\n\n set_validation_status(txn, hash.clone(), ValidationStatus::Rejected).unwrap();\n\n set_when_integrated(txn, hash, timestamp::now()).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n", "file_path": "crates/holochain_cascade/src/test_utils.rs", "rank": 94, "score": 201121.8305077577 }, { "content": "pub fn fill_db_as_author(env: &EnvWrite, op: DhtOpHashed) {\n\n env.conn()\n\n .unwrap()\n\n .with_commit_sync(|txn| {\n\n insert_op(txn, op, true).unwrap();\n\n DatabaseResult::Ok(())\n\n })\n\n .unwrap();\n\n}\n\n\n\n#[async_trait::async_trait]\n\nimpl HolochainP2pCellT for MockNetwork {\n\n async fn get_validation_package(\n\n &mut self,\n\n request_from: AgentPubKey,\n\n header_hash: HeaderHash,\n\n ) -> actor::HolochainP2pResult<ValidationPackageResponse> {\n\n self.0\n\n .lock()\n\n .await\n", "file_path": "crates/holochain_cascade/src/test_utils.rs", "rank": 95, "score": 201121.8305077577 }, { "content": "/// Get compressed bytes from some serializable data\n\npub fn encode<T: serde::ser::Serialize>(data: &T) -> MrBundleResult<Vec<u8>> {\n\n let bytes = rmp_serde::to_vec_named(data)?;\n\n let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());\n\n enc.write_all(&bytes)?;\n\n Ok(enc.finish()?)\n\n}\n\n\n", "file_path": "crates/mr_bundle/src/encoding.rs", "rank": 96, "score": 200484.60460676684 }, { "content": "/// Sign N serializable things using an ephemeral private key.\n\n///\n\n/// Serde convenience for [ `sign_ephemeral_raw` ].\n\npub fn sign_ephemeral<D>(datas: Vec<D>) -> ExternResult<EphemeralSignatures>\n\nwhere\n\n D: serde::Serialize + std::fmt::Debug,\n\n{\n\n HDK.with(|h| h.borrow().sign_ephemeral(SignEphemeral::new(datas)?))\n\n}\n\n\n", "file_path": "crates/hdk/src/ed25519.rs", "rank": 97, "score": 199851.94284015434 }, { "content": "/// Sign N data using an ephemeral private key.\n\n///\n\n/// This is a complement to [ `sign_raw` ] in case we don't have a meaningful key for the input.\n\n/// __The generated private half of the key is discarded immediately upon signing__.\n\n///\n\n/// The signatures output are pairwise ordered the same as the input data.\n\n/// It is up to the caller to construct meaning for ephemeral signatures in some cryptographic system.\n\npub fn sign_ephemeral_raw(datas: Vec<Vec<u8>>) -> ExternResult<EphemeralSignatures> {\n\n HDK.with(|h| h.borrow().sign_ephemeral(SignEphemeral::new_raw(datas)))\n\n}\n\n\n", "file_path": "crates/hdk/src/ed25519.rs", "rank": 98, "score": 197592.2805641576 }, { "content": "// Now we expect an invalid link\n\nfn expected_invalid_link(txn: &Transaction, invalid_link_hash: &HeaderHash) -> bool {\n\n let sql = format!(\n\n \"\n\n {}\n\n (\n\n (type = :create_link AND header_hash = :invalid_link_hash \n\n AND validation_status = :rejected)\n\n OR\n\n (type = :store_element AND header_hash = :invalid_link_hash \n\n AND validation_status = :rejected)\n\n )\n\n \",\n\n SELECT\n\n );\n\n\n\n let count: usize = txn\n\n .query_row(\n\n &sql,\n\n named_params! {\n\n \":invalid_link_hash\": invalid_link_hash,\n\n \":create_link\": DhtOpType::RegisterAddLink,\n\n \":store_element\": DhtOpType::StoreElement,\n\n \":rejected\": ValidationStatus::Rejected,\n\n },\n\n |row| row.get(0),\n\n )\n\n .unwrap();\n\n count == 2\n\n}\n\n\n", "file_path": "crates/holochain/src/core/workflow/app_validation_workflow/tests.rs", "rank": 99, "score": 197329.7624174636 } ]
Rust
src/resources/automata.rs
Luminoth/remix-exploration
491e4b3bc1447eae35baa9a2599e182b743cdb41
use bevy::prelude::*; use crate::game::dna::*; use crate::game::stats::*; use crate::resources::*; pub trait AutomataStats { fn stats(&self) -> &StatSet; fn modify(&mut self, statid: StatId, amount: isize) -> bool; } macro_rules! impl_modify_stats { () => { fn modify(&mut self, statid: StatId, amount: isize) -> bool { if self.points - amount < 0 { return false; } match statid { StatId::Constitution => { if self.stats.constitution() + amount < 0 { return false; } self.stats .set_constitution(self.stats.constitution() + amount); } StatId::Dexterity => { if self.stats.dexterity() + amount < 0 { return false; } self.stats.set_dexterity(self.stats.dexterity() + amount); } StatId::Strength => { if self.stats.strength() + amount < 0 { return false; } self.stats.set_strength(self.stats.strength() + amount); } StatId::Fortitude => { if self.stats.fortitude() + amount < 0 { return false; } self.stats.set_fortitude(self.stats.fortitude() + amount); } StatId::Aggression => { if self.stats.aggression() + amount < 0 { return false; } self.stats.set_aggression(self.stats.aggression() + amount); } StatId::Intellect => { if self.stats.intellect() + amount < 0 { return false; } self.stats.set_intellect(self.stats.intellect() + amount); } } self.points -= amount; true } }; } #[derive(Debug, Default, Clone, Copy)] pub struct PlayerAutomataStats { points: isize, pub stats: StatSet, } impl AutomataStats for PlayerAutomataStats { fn stats(&self) -> &StatSet { &self.stats } impl_modify_stats!(); } impl PlayerAutomataStats { pub fn new(points: isize) -> Self { Self { points, ..Default::default() } } pub fn points(&self) -> isize { self.points } pub fn value(&self, statid: StatId) -> isize { match statid { StatId::Constitution => self.stats.constitution(), StatId::Dexterity => self.stats.dexterity(), StatId::Strength => self.stats.strength(), StatId::Fortitude => self.stats.fortitude(), StatId::Aggression => self.stats.aggression(), StatId::Intellect => self.stats.intellect(), } } } #[derive(Debug, Default, Clone, Copy)] pub struct AIAutomataStats { points: isize, pub stats: StatSet, } impl AutomataStats for AIAutomataStats { fn stats(&self) -> &StatSet { &self.stats } impl_modify_stats!(); } impl AIAutomataStats { pub fn new(points: isize, random: &mut Random) -> Self { Self { points, stats: StatSet::random(points, random), } } } #[derive(Debug)] pub struct AIAutomataPopulation { mutation_rate: f64, population: Vec<AIAutomataStats>, mating_pool: Vec<Dna>, } impl AIAutomataPopulation { pub fn new(mutation_rate: f64, rounds: usize, points: isize, random: &mut Random) -> Self { let mut population = Vec::with_capacity(rounds); for _ in 0..population.capacity() { population.push(AIAutomataStats::new(points, random)); } Self { mutation_rate, population, mating_pool: vec![], } } pub fn round_stats(&self, round: usize) -> &AIAutomataStats { self.population.get(round).unwrap() } } pub struct AutomataColors { pub cell: Color, pub player_automata: Color, pub ai_automata: Color, }
use bevy::prelude::*; use crate::game::dna::*; use crate::game::stats::*; use crate::resources::*; pub trait AutomataStats { fn stats(&self) -> &StatSet; fn modify(&mut self, statid: StatId, amount: isize) -> bool; } macro_rules! impl_modify_stats { () => { fn modify(&mut self, statid: StatId, amount: isize) -> bool { if self.points - amount < 0 { return false; } match statid { StatId::Constitution => { if self.stats.constitution() + amount < 0 { return false; } self.stats .set_constitution(self.stats.constitution() + amount); } StatId::Dexterity => { if self.stats.dexterity() + amount < 0 { return false; } self.stats.set_dexterity(self.stats.dexterity() + amount); } StatId::Strength => { if self.stats.strength() + amount < 0 { return false; } self.stats.set_strength(self.stats.strength() + amount); } StatId::Fortitude => { if self.stats.fortitude() + amount < 0 { return false; } self.stats.set_fortitude(self.stats.fortitude() + amount); } StatId::Aggression => { if self.stats.aggression() + amount < 0 { return false; } self.stats.set_aggression(self.stats.aggression() + amount); } StatId::Intellect => { if self.stats.intellect() + amount < 0 { return false; } self.stats.set_intellect(self.stats.intellect() + amount); } } self.points -= amount; true } }; } #[derive(Debug, Default, Clone, Copy)] pub struct PlayerAutomataStats { points: isize, pub stats: StatSet, } impl AutomataStats for PlayerAutomataStats { fn stats(&self) -> &StatSet { &self.stats } impl_modify_stats!(); } impl PlayerAutomataStats { pub fn new(points: isize) -> Self { Self { points, ..Default::default() } } pub fn points(&self) -> isize { self.points } pub fn value(&self, statid: StatId) -> isize { match statid { StatId::Constitution => self.stats.constitution(), StatId::Dexterity => self.stats.dexterity(), StatId::Strength => self.stats.strength(), StatId::Fortitude => self.stats.fortitude(), StatId::Aggression => self.stats.aggression(), StatId::Intellect => self.stats.intellect(), } } } #[derive(Debug, Default, Clone, Copy)] pub struct AIAutomataStats { points: isize, pub stats: StatSet, } impl AutomataStats for AIAutomataStats { fn stats(&self) -> &StatSet { &self.stats } impl_modify_stats!(); } impl AIAutomataStats { pub fn new(points: isize, random: &mut Random) -> Self { Self { points, stats: StatSet::random(points, random), } } } #[derive(Debug)] pub struct AIAutomataPopulation { mutation_rate: f64, population: Vec<AIAutomataStats>, mating_pool: Vec<Dna>, } impl AIAutomataPopulation { pub fn new(mutation_rate: f64, rounds: usize, points: isize, random: &mut Random) -> Self { let mut populat
, } } pub fn round_stats(&self, round: usize) -> &AIAutomataStats { self.population.get(round).unwrap() } } pub struct AutomataColors { pub cell: Color, pub player_automata: Color, pub ai_automata: Color, }
ion = Vec::with_capacity(rounds); for _ in 0..population.capacity() { population.push(AIAutomataStats::new(points, random)); } Self { mutation_rate, population, mating_pool: vec![]
function_block-random_span
[ { "content": "/// Stat modified event handler\n\npub fn stat_modified_event_handler(\n\n stats: ResMut<PlayerAutomataStats>,\n\n button_colors: Res<ButtonColors>,\n\n mut events: EventReader<StatModifiedEvent>,\n\n mut text_query: Query<(&mut Text, &StatModifierText), Without<PointsText>>,\n\n mut points_text_query: Query<&mut Text, With<PointsText>>,\n\n mut modifier_query: Query<\n\n (&mut ButtonHelper, &mut UiColor, &StatModifierButton),\n\n Without<ActionButton>,\n\n >,\n\n mut action_query: Query<(&mut ButtonHelper, &mut UiColor), With<ActionButton>>,\n\n) {\n\n for event in events.iter() {\n\n for (mut text, modifier) in text_query.iter_mut() {\n\n if modifier.statid == event.0 {\n\n text.sections[0].value = format!(\"{}\", stats.value(modifier.statid));\n\n }\n\n }\n\n\n\n if let Ok(mut text) = points_text_query.get_single_mut() {\n", "file_path": "src/states/remix.rs", "rank": 1, "score": 97089.51725712765 }, { "content": "/// Game teardown\n\npub fn teardown(mut commands: Commands, entities: Query<Entity>) {\n\n for entity in entities.iter() {\n\n commands.entity(entity).despawn_recursive();\n\n }\n\n\n\n commands.remove_resource::<ClearColor>();\n\n}\n", "file_path": "src/states/game.rs", "rank": 2, "score": 86618.9018600684 }, { "content": "/// Remix teardown\n\npub fn teardown(mut commands: Commands, entities: Query<Entity>) {\n\n for entity in entities.iter() {\n\n commands.entity(entity).despawn_recursive();\n\n }\n\n\n\n commands.remove_resource::<ClearColor>();\n\n}\n", "file_path": "src/states/remix.rs", "rank": 3, "score": 86618.9018600684 }, { "content": "/// Game over teardown\n\npub fn teardown(mut commands: Commands, entities: Query<Entity>) {\n\n for entity in entities.iter() {\n\n commands.entity(entity).despawn_recursive();\n\n }\n\n\n\n commands.remove_resource::<PlayerAutomataStats>();\n\n commands.remove_resource::<AIAutomataPopulation>();\n\n commands.remove_resource::<GameRound>();\n\n\n\n commands.remove_resource::<ClearColor>();\n\n}\n", "file_path": "src/states/gameover.rs", "rank": 4, "score": 86618.9018600684 }, { "content": "/// Intro teardown\n\npub fn teardown(mut commands: Commands, entities: Query<Entity>) {\n\n for entity in entities.iter() {\n\n commands.entity(entity).despawn_recursive();\n\n }\n\n\n\n commands.remove_resource::<ClearColor>();\n\n}\n", "file_path": "src/states/intro.rs", "rank": 5, "score": 86618.9018600684 }, { "content": "fn fps(diagnostics: &Diagnostics, dt: f64) -> (f64, f64) {\n\n let mut fps = 0.0;\n\n if let Some(fps_diagnostic) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) {\n\n if let Some(fps_avg) = fps_diagnostic.average() {\n\n fps = fps_avg;\n\n }\n\n }\n\n\n\n let mut frame_time = dt;\n\n if let Some(frame_time_diagnostic) = diagnostics.get(FrameTimeDiagnosticsPlugin::FRAME_TIME) {\n\n if let Some(frame_time_avg) = frame_time_diagnostic.average() {\n\n frame_time = frame_time_avg;\n\n }\n\n }\n\n\n\n (fps, frame_time)\n\n}\n\n\n", "file_path": "src/systems/debug.rs", "rank": 6, "score": 85733.61751543381 }, { "content": "/// Game setup\n\npub fn setup(\n\n mut commands: Commands,\n\n gridworld: Res<GridWorld>,\n\n mut round: ResMut<GameRound>,\n\n colors: Res<AutomataColors>,\n\n button_colors: Res<ButtonColors>,\n\n fonts: Res<Fonts>,\n\n) {\n\n // cameras\n\n let mut camera = OrthographicCameraBundle::new_2d();\n\n camera.orthographic_projection.scaling_mode = bevy::render::camera::ScalingMode::FixedVertical;\n\n camera.orthographic_projection.scale = GRID_HEIGHT as f32 / 2.0;\n\n\n\n commands.insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0)));\n\n commands\n\n .spawn_bundle(camera)\n\n .insert(MainCamera)\n\n .insert(Name::new(\"Main Camera\"));\n\n commands\n\n .spawn_bundle(UiCameraBundle::default())\n", "file_path": "src/states/game.rs", "rank": 7, "score": 81496.09629325845 }, { "content": "/// Intro setup\n\npub fn setup(\n\n mut commands: Commands,\n\n mut random: ResMut<Random>,\n\n button_colors: Res<ButtonColors>,\n\n fonts: Res<Fonts>,\n\n) {\n\n // cameras\n\n commands.insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0)));\n\n commands\n\n .spawn_bundle(UiCameraBundle::default())\n\n .insert(UiCamera)\n\n .insert(Name::new(\"UI Camera\"));\n\n\n\n // world\n\n let gridworld = GridWorld::new(crate::GRID_WIDTH, crate::GRID_HEIGHT);\n\n commands.insert_resource(gridworld);\n\n\n\n // player automata stats\n\n let player_stats = PlayerAutomataStats::new(crate::STAT_POINTS);\n\n commands.insert_resource(player_stats);\n", "file_path": "src/states/intro.rs", "rank": 8, "score": 81496.09629325845 }, { "content": "/// Remix setup\n\npub fn setup(\n\n mut commands: Commands,\n\n player_stats: Res<PlayerAutomataStats>,\n\n button_colors: Res<ButtonColors>,\n\n fonts: Res<Fonts>,\n\n) {\n\n // cameras\n\n commands.insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0)));\n\n commands\n\n .spawn_bundle(UiCameraBundle::default())\n\n .insert(UiCamera)\n\n .insert(Name::new(\"UI Camera\"));\n\n\n\n // UI\n\n let root = spawn_ui_root(&mut commands);\n\n commands.entity(root).with_children(|parent| {\n\n spawn_header(parent, &fonts, \"Remix Your Automaton\");\n\n\n\n // remaining points\n\n parent\n", "file_path": "src/states/remix.rs", "rank": 9, "score": 81496.09629325845 }, { "content": "#[allow(clippy::needless_return)]\n\npub fn automata_action(\n\n mut round: ResMut<GameRound>,\n\n mut player_automata_query: Query<&mut Automata, (With<PlayerAutomata>, Without<AIAutomata>)>,\n\n mut ai_automata_query: Query<&mut Automata, (With<AIAutomata>, Without<PlayerAutomata>)>,\n\n) {\n\n if round.stage != GameStage::Running {\n\n return;\n\n }\n\n\n\n // TODO: we need a cooldown on taking actions\n\n // so things don't progress too fast\n\n\n\n if let Ok(mut player) = player_automata_query.get_single_mut() {\n\n if let Ok(mut ai) = ai_automata_query.get_single_mut() {\n\n match round.action {\n\n GameAction::PlayerMove => {\n\n player.move_action();\n\n\n\n round.action = GameAction::PlayerAttack;\n\n }\n", "file_path": "src/states/game.rs", "rank": 10, "score": 79199.15735685188 }, { "content": "/// Recursively set the visibility of an entity and its children\n\n// https://github.com/bevyengine/bevy/issues/838\n\npub fn set_visible_recursive(\n\n entity: Entity,\n\n is_visible: bool,\n\n visibility_query: &mut Query<&mut Visibility>,\n\n children_query: &Query<&Children>,\n\n) {\n\n if let Ok(mut visible) = visibility_query.get_mut(entity) {\n\n visible.is_visible = is_visible;\n\n }\n\n\n\n if let Ok(children) = children_query.get(entity) {\n\n for child in children.iter() {\n\n set_visible_recursive(*child, is_visible, visibility_query, children_query);\n\n }\n\n }\n\n}\n", "file_path": "src/util.rs", "rank": 11, "score": 79195.6254291684 }, { "content": "/// Generic button update\n\npub fn update_buttons(\n\n colors: Res<ButtonColors>,\n\n mut query: Query<(&Interaction, &mut UiColor, &ButtonHelper), Changed<Interaction>>,\n\n) {\n\n for (interaction, mut color, helper) in query.iter_mut() {\n\n if helper.interactable() {\n\n match *interaction {\n\n Interaction::Clicked => {\n\n *color = colors.pressed;\n\n }\n\n Interaction::Hovered => {\n\n *color = colors.hovered;\n\n }\n\n Interaction::None => {\n\n *color = colors.normal;\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/systems/ui.rs", "rank": 12, "score": 79195.6254291684 }, { "content": "/// Handles the debug UI\n\npub fn debug_ui(\n\n debug_state: ResMut<DebugState>,\n\n context: ResMut<EguiContext>,\n\n mut inspector: ResMut<WorldInspectorParams>,\n\n time: Res<Time>,\n\n diagnostics: Res<Diagnostics>,\n\n) {\n\n if !debug_state.enabled {\n\n return;\n\n }\n\n\n\n let (fps, frame_time) = fps(&diagnostics, time.delta_seconds_f64());\n\n\n\n egui::Window::new(\"Debug\").show(context.ctx(), |ui| {\n\n ui.vertical(|ui| {\n\n ui.label(format!(\n\n \"{:.1} fps, {:.3} ms/frame\",\n\n fps,\n\n frame_time * 1000.0\n\n ));\n\n\n\n if ui.button(\"Inspector\").clicked() {\n\n inspector.enabled = !inspector.enabled;\n\n }\n\n });\n\n });\n\n}\n", "file_path": "src/systems/debug.rs", "rank": 13, "score": 79195.6254291684 }, { "content": "/// Toggles debug on input\n\n///\n\n/// Sends the ToggleDebugEvent\n\npub fn debug_system(\n\n mut inspector: ResMut<WorldInspectorParams>,\n\n mut debug_state: ResMut<DebugState>,\n\n keyboard_input: Res<Input<KeyCode>>,\n\n mut debug_events: EventWriter<ToggleDebugEvent>,\n\n) {\n\n if keyboard_input.just_pressed(KeyCode::Grave) {\n\n debug!(\"toggling debug ...\");\n\n\n\n debug_state.enabled = !debug_state.enabled;\n\n\n\n if !debug_state.enabled {\n\n inspector.enabled = false;\n\n }\n\n\n\n debug_events.send(ToggleDebugEvent);\n\n }\n\n}\n\n\n", "file_path": "src/systems/debug.rs", "rank": 14, "score": 79195.6254291684 }, { "content": "/// Spawn a UI header\n\nfn spawn_header(parent: &mut ChildBuilder, fonts: &Fonts, text: impl Into<String>) {\n\n parent.spawn_bundle(TextBundle {\n\n style: Style {\n\n margin: Rect::all(Val::Px(5.0)),\n\n ..Default::default()\n\n },\n\n text: Text::with_section(\n\n text,\n\n TextStyle {\n\n font: fonts.normal.clone(),\n\n font_size: 30.0,\n\n color: Color::WHITE,\n\n },\n\n Default::default(),\n\n ),\n\n ..Default::default()\n\n });\n\n}\n\n\n", "file_path": "src/states/mod.rs", "rank": 15, "score": 79003.72652091763 }, { "content": "/// Modifier button handler\n\npub fn modifier_button_handler(\n\n mut stats: ResMut<PlayerAutomataStats>,\n\n mut modifier_query: Query<\n\n (&Interaction, &ButtonHelper, &StatModifierButton),\n\n (Changed<Interaction>, Without<ActionButton>),\n\n >,\n\n mut state_modified_events: EventWriter<StatModifiedEvent>,\n\n) {\n\n if let Ok((interaction, helper, modifier)) = modifier_query.get_single_mut() {\n\n #[allow(clippy::collapsible_if)]\n\n if helper.interactable() && *interaction == Interaction::Clicked {\n\n if stats.modify(modifier.statid, modifier.modifier) {\n\n state_modified_events.send(StatModifiedEvent(modifier.statid));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/remix.rs", "rank": 16, "score": 77099.59038612807 }, { "content": "/// Action button handler\n\npub fn action_button_handler(\n\n mut action_query: Query<\n\n (&Interaction, &ButtonHelper),\n\n (Changed<Interaction>, With<ActionButton>),\n\n >,\n\n mut state: ResMut<State<GameState>>,\n\n) {\n\n if let Ok((interaction, helper)) = action_query.get_single_mut() {\n\n if helper.interactable() && *interaction == Interaction::Clicked {\n\n state.set(GameState::Intro).unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/gameover.rs", "rank": 17, "score": 77099.59038612807 }, { "content": "/// Action button handler\n\npub fn action_button_handler(\n\n mut action_query: Query<\n\n (&Interaction, &ButtonHelper),\n\n (Changed<Interaction>, With<ActionButton>),\n\n >,\n\n mut state: ResMut<State<GameState>>,\n\n) {\n\n if let Ok((interaction, helper)) = action_query.get_single_mut() {\n\n if helper.interactable() && *interaction == Interaction::Clicked {\n\n state.set(GameState::Remix).unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/intro.rs", "rank": 18, "score": 77099.59038612807 }, { "content": "/// Action button handler\n\npub fn action_button_handler(\n\n mut action_query: Query<\n\n (&Interaction, &ButtonHelper),\n\n (Changed<Interaction>, With<ActionButton>),\n\n >,\n\n mut state: ResMut<State<GameState>>,\n\n) {\n\n if let Ok((interaction, helper)) = action_query.get_single_mut() {\n\n if helper.interactable() && *interaction == Interaction::Clicked {\n\n state.set(GameState::Game).unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/remix.rs", "rank": 19, "score": 77099.59038612807 }, { "content": "/// Cell selection button handler\n\npub fn cell_selection_button_handler(\n\n mut commands: Commands,\n\n mut random: ResMut<Random>,\n\n mut round: ResMut<GameRound>,\n\n colors: Res<AutomataColors>,\n\n query: Query<(&Interaction, &ButtonHelper, &CellSelectionButton), Changed<Interaction>>,\n\n cell_selection_ui_query: Query<Entity, With<CellSelection>>,\n\n hud_query: Query<Entity, With<Hud>>,\n\n mut visibility_query: Query<&mut Visibility>,\n\n children_query: Query<&Children>,\n\n\n\n mut game_start_events: EventWriter<GameStartEvent>,\n\n) {\n\n if round.stage != GameStage::CellSelection {\n\n return;\n\n }\n\n\n\n if let Ok((interaction, helper, selection)) = query.get_single() {\n\n if helper.interactable() && *interaction == Interaction::Clicked {\n\n // hide cell selection UI\n", "file_path": "src/states/game.rs", "rank": 20, "score": 75181.89914254282 }, { "content": "/// Automata health changed event handler\n\npub fn health_changed_event_handler(\n\n mut events: EventReader<HealthChangedEvent>,\n\n mut text_query: Query<(&mut Text, &AutomataHealthText)>,\n\n) {\n\n for event in events.iter() {\n\n for (mut text, health) in text_query.iter_mut() {\n\n if health.player == event.player {\n\n text.sections[0].value = format!(\"{}\", event.value);\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// Automata action handler\n", "file_path": "src/states/game.rs", "rank": 21, "score": 75181.89914254282 }, { "content": "/// Game start event handler\n\npub fn game_start_event_handler(\n\n mut events: EventReader<GameStartEvent>,\n\n round: Res<GameRound>,\n\n player_stats: Res<PlayerAutomataStats>,\n\n ai_population: Res<AIAutomataPopulation>,\n\n mut player_automata_query: Query<&mut Automata, (With<PlayerAutomata>, Without<AIAutomata>)>,\n\n mut ai_automata_query: Query<&mut Automata, (With<AIAutomata>, Without<PlayerAutomata>)>,\n\n mut health_text_query: Query<(&mut Text, &AutomataHealthText)>,\n\n) {\n\n for _ in events.iter() {\n\n if let Ok(mut automata) = player_automata_query.get_single_mut() {\n\n automata.reset(&*player_stats);\n\n\n\n for (mut text, health) in health_text_query.iter_mut() {\n\n if !health.player {\n\n continue;\n\n }\n\n\n\n text.sections[0].value = format!(\"{}\", automata.health);\n\n }\n", "file_path": "src/states/game.rs", "rank": 22, "score": 75181.89914254282 }, { "content": "/// Game over setup\n\npub fn setup(mut commands: Commands, button_colors: Res<ButtonColors>, fonts: Res<Fonts>) {\n\n // cameras\n\n commands.insert_resource(ClearColor(Color::rgb(0.0, 0.0, 0.0)));\n\n commands\n\n .spawn_bundle(UiCameraBundle::default())\n\n .insert(UiCamera)\n\n .insert(Name::new(\"UI Camera\"));\n\n\n\n // UI\n\n let root = spawn_ui_root(&mut commands);\n\n commands.entity(root).with_children(|parent| {\n\n spawn_header(parent, &fonts, \"Game Over\");\n\n\n\n spawn_spacer(parent);\n\n\n\n spawn_ok_action(parent, &button_colors, &fonts, \"Continue\", true);\n\n });\n\n}\n\n\n", "file_path": "src/states/gameover.rs", "rank": 23, "score": 72330.01453268745 }, { "content": "#[derive(Debug, Inspectable, Default)]\n\nstruct StatSetFitness {\n\n constitution: f32,\n\n dexterity: f32,\n\n strength: f32,\n\n fortitude: f32,\n\n aggression: f32,\n\n intellect: f32,\n\n}\n\n\n\n/// Genetic algorithm DNA\n\n#[derive(Debug, Inspectable)]\n\npub struct Dna {\n\n genes: StatSet,\n\n\n\n fitness: StatSetFitness,\n\n rounds: usize,\n\n points: isize,\n\n}\n\n\n\nimpl Dna {\n", "file_path": "src/game/dna.rs", "rank": 24, "score": 70028.3137315435 }, { "content": "/// Spawn a UI spacer\n\nfn spawn_spacer(parent: &mut ChildBuilder) {\n\n parent.spawn_bundle(NodeBundle {\n\n style: Style {\n\n size: Size::new(Val::Auto, Val::Auto),\n\n flex_grow: 1.0,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n });\n\n}\n\n\n", "file_path": "src/states/mod.rs", "rank": 25, "score": 68816.40273865081 }, { "content": "/// Spawn a cell selection row\n\nfn spawn_cell_selection_row(parent: &mut ChildBuilder, button_colors: &ButtonColors, row: usize) {\n\n parent\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n\n size: Size::new(Val::Auto, Val::Auto),\n\n align_items: AlignItems::Center,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n })\n\n .insert(Name::new(\"Cell Selection Row\"))\n\n .with_children(|parent| {\n\n for column in 0..crate::GRID_WIDTH {\n\n parent.spawn_bundle(CellSelectionButtonBundle {\n\n button: ButtonBundle {\n\n style: Style {\n\n size: Size::new(\n\n Val::Px(GRID_BUTTON_WIDTH),\n\n Val::Px(GRID_BUTTON_HEIGHT),\n", "file_path": "src/states/game.rs", "rank": 26, "score": 66978.13154239228 }, { "content": "/// Spawn a stat input\n\nfn spawn_stat_input(\n\n parent: &mut ChildBuilder,\n\n button_colors: &ButtonColors,\n\n fonts: &Fonts,\n\n statid: StatId,\n\n player_stats: &PlayerAutomataStats,\n\n description: impl Into<String>,\n\n) {\n\n parent\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n\n size: Size::new(Val::Auto, Val::Auto),\n\n align_items: AlignItems::Center,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n })\n\n .insert(Name::new(statid.name()))\n\n .with_children(|parent| {\n", "file_path": "src/states/remix.rs", "rank": 27, "score": 64961.82071582133 }, { "content": "/// Spawn a UI root node\n\nfn spawn_ui_root(commands: &mut Commands) -> Entity {\n\n commands\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n\n position_type: PositionType::Absolute,\n\n size: Size::new(Val::Percent(100.0), Val::Percent(100.0)),\n\n flex_direction: FlexDirection::ColumnReverse,\n\n align_items: AlignItems::Center,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n })\n\n .insert(Name::new(\"UI Root\"))\n\n .id()\n\n}\n\n\n", "file_path": "src/states/mod.rs", "rank": 28, "score": 64699.08915443742 }, { "content": "/// Initial setup\n\nfn setup(mut commands: Commands, asset_server: Res<AssetServer>) {\n\n #[cfg(debug_assertions)]\n\n asset_server.watch_for_changes().unwrap();\n\n\n\n let random = Random::default();\n\n\n\n // assets\n\n let fonts = Fonts {\n\n normal: asset_server.load(\"fonts/FiraSans-Bold.ttf\"),\n\n };\n\n commands.insert_resource(fonts);\n\n\n\n // materials\n\n let automata_materials = resources::automata::AutomataColors {\n\n cell: Color::BISQUE,\n\n player_automata: Color::TEAL,\n\n ai_automata: Color::ORANGE_RED,\n\n };\n\n commands.insert_resource(automata_materials);\n\n\n", "file_path": "src/main.rs", "rank": 29, "score": 59381.57087843155 }, { "content": "/// Gets the position for a grid cell\n\npub fn cell_position(cell: UVec2, z: f32) -> Vec3 {\n\n // (0, 0) is in the center\n\n let mut cell = IVec2::new(cell.x as i32, cell.y as i32)\n\n - IVec2::new(\n\n crate::GRID_WIDTH as i32 / 2 - 1, // not exactly sure why this needs to be offset\n\n crate::GRID_HEIGHT as i32 / 2,\n\n );\n\n\n\n // y is bottom up\n\n cell.y = -cell.y;\n\n\n\n // convert to pixels\n\n let mut position =\n\n Vec2::new(cell.x as f32, cell.y as f32) * Vec2::new(crate::CELL_WIDTH, crate::CELL_HEIGHT);\n\n\n\n // account for sprites rendering from their center\n\n position -= Vec2::new(crate::CELL_WIDTH / 2.0, crate::CELL_HEIGHT / 2.0);\n\n\n\n // margins (TODO: this feels wrong)\n\n position.y -= crate::TOP_MARGIN / crate::GRID_HEIGHT as f32;\n\n\n\n // sorting\n\n position.extend(z)\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 30, "score": 59376.72825653347 }, { "content": "/// Clamps a float between a min and a max\n\npub fn clampf<F: Float>(v: F, min: F, max: F) -> F {\n\n Float::min(max, Float::max(min, v))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 31, "score": 51842.515782482384 }, { "content": "/// Clamps an ord between a min and a max\n\npub fn clamp<T: Ord>(v: T, min: T, max: T) -> T {\n\n std::cmp::min(max, std::cmp::max(min, v))\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 32, "score": 51842.515782482384 }, { "content": "/// Game state plugin\n\nstruct GameStatePlugin;\n\n\n\nimpl Plugin for GameStatePlugin {\n\n fn build(&self, app: &mut App) {\n\n // events\n\n app.add_event::<GameStartEvent>()\n\n .add_event::<HealthChangedEvent>();\n\n\n\n // systems\n\n app.add_system_set(SystemSet::on_enter(GameState::Game).with_system(states::game::setup))\n\n .add_system_set(\n\n SystemSet::on_update(GameState::Game)\n\n .with_system(states::game::cell_selection_button_handler)\n\n .with_system(states::game::game_start_event_handler)\n\n .with_system(states::game::health_changed_event_handler)\n\n .with_system(states::game::automata_action),\n\n )\n\n .add_system_set(\n\n SystemSet::on_exit(GameState::Game).with_system(states::game::teardown),\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/plugins/states.rs", "rank": 33, "score": 46083.53895777004 }, { "content": "/// Intro state plugin\n\nstruct IntroStatePlugin;\n\n\n\nimpl Plugin for IntroStatePlugin {\n\n fn build(&self, app: &mut App) {\n\n // systems\n\n app.add_system_set(SystemSet::on_enter(GameState::Intro).with_system(states::intro::setup))\n\n .add_system_set(\n\n SystemSet::on_update(GameState::Intro)\n\n .with_system(states::intro::action_button_handler),\n\n )\n\n .add_system_set(\n\n SystemSet::on_exit(GameState::Intro).with_system(states::intro::teardown),\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/plugins/states.rs", "rank": 34, "score": 46083.53895777004 }, { "content": "/// Remix state plugin\n\nstruct RemixStatePlugin;\n\n\n\nimpl Plugin for RemixStatePlugin {\n\n fn build(&self, app: &mut App) {\n\n // events\n\n app.add_event::<StatModifiedEvent>();\n\n\n\n // systems\n\n app.add_system_set(SystemSet::on_enter(GameState::Remix).with_system(states::remix::setup))\n\n .add_system_set(\n\n SystemSet::on_update(GameState::Remix)\n\n .with_system(states::remix::modifier_button_handler)\n\n .with_system(states::remix::action_button_handler)\n\n .with_system(states::remix::stat_modified_event_handler),\n\n )\n\n .add_system_set(\n\n SystemSet::on_exit(GameState::Remix).with_system(states::remix::teardown),\n\n );\n\n }\n\n}\n\n\n", "file_path": "src/plugins/states.rs", "rank": 35, "score": 46083.53895777004 }, { "content": "/// Game over state plugin\n\nstruct GameOverStatePlugin;\n\n\n\nimpl Plugin for GameOverStatePlugin {\n\n fn build(&self, app: &mut App) {\n\n // systems\n\n app.add_system_set(\n\n SystemSet::on_enter(GameState::GameOver).with_system(states::gameover::setup),\n\n )\n\n .add_system_set(\n\n SystemSet::on_update(GameState::GameOver)\n\n .with_system(states::gameover::action_button_handler),\n\n )\n\n .add_system_set(\n\n SystemSet::on_exit(GameState::GameOver).with_system(states::gameover::teardown),\n\n );\n\n }\n\n}\n", "file_path": "src/plugins/states.rs", "rank": 36, "score": 46083.53895777004 }, { "content": "#[bevy_main]\n\nfn main() {\n\n std::panic::set_hook(Box::new(|data| {\n\n error!(%data, \"Unexpected panic!\");\n\n }));\n\n\n\n let mut app = App::new();\n\n\n\n // basic bevy\n\n app.insert_resource(WindowDescriptor {\n\n title: \"Remix - Exploration\".to_owned(),\n\n width: WINDOW_WIDTH,\n\n height: WINDOW_HEIGHT,\n\n vsync: false,\n\n resizable: false,\n\n ..Default::default()\n\n })\n\n .insert_resource(bevy::log::LogSettings {\n\n level: bevy::log::Level::DEBUG,\n\n ..Default::default()\n\n })\n", "file_path": "src/main.rs", "rank": 37, "score": 44816.93053821889 }, { "content": "/// Spawn a UI OK action row\n\nfn spawn_ok_action(\n\n parent: &mut ChildBuilder,\n\n button_colors: &ButtonColors,\n\n fonts: &Fonts,\n\n text: impl Into<String>,\n\n interactable: bool,\n\n) {\n\n parent\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n\n size: Size::new(Val::Auto, Val::Auto),\n\n align_items: AlignItems::Center,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n })\n\n .insert(Name::new(\"Actions\"))\n\n .with_children(|parent| {\n\n parent\n", "file_path": "src/states/mod.rs", "rank": 38, "score": 41017.03638277523 }, { "content": " ];\n\n random.shuffle(&mut buckets);\n\n\n\n // random points for each stat\n\n for stat in buckets.drain(1..) {\n\n let p = random.random_range(0..=points);\n\n stats.modify(stat, p);\n\n\n\n points -= p;\n\n }\n\n stats.modify(buckets[0], points);\n\n\n\n stats\n\n }\n\n\n\n /// Returns the value of the given stat\n\n pub fn value(&self, statid: StatId) -> isize {\n\n match statid {\n\n StatId::Constitution => self.constitution(),\n\n StatId::Dexterity => self.dexterity(),\n", "file_path": "src/game/stats.rs", "rank": 39, "score": 27845.13492202423 }, { "content": "\n\n/// A single automata stat\n\n#[derive(Debug, Clone, Copy, Inspectable, Default)]\n\npub struct Stat {\n\n value: isize,\n\n}\n\n\n\nimpl From<isize> for Stat {\n\n #[inline]\n\n fn from(value: isize) -> Self {\n\n Self { value }\n\n }\n\n}\n\n\n\n/// A set of automata stats\n\n#[derive(Debug, Clone, Copy, Inspectable, Default)]\n\npub struct StatSet {\n\n constitution: Stat,\n\n dexterity: Stat,\n\n strength: Stat,\n", "file_path": "src/game/stats.rs", "rank": 40, "score": 27845.01503100154 }, { "content": " }\n\n\n\n impl_stat!(fortitude);\n\n\n\n /// Gets the amount of damage absorbed, based on Fortitude stat\n\n #[inline]\n\n pub fn absorbed_damage(&self) -> usize {\n\n (BASE_ATTACK_ABSORB + (self.fortitude() as f32 * FORTITUDE_MOD) as isize).max(1) as usize\n\n }\n\n\n\n impl_stat!(aggression);\n\n\n\n /// Gets the chance to move towards the enemy automata\n\n #[inline]\n\n pub fn move_towards_enemy(&self, random: &mut Random) -> (bool, f64) {\n\n let target =\n\n (BASE_MOVE_TOWARDS_ENEMY + self.aggression() as f64 * AGGRESSION_MOD).clamp(0.0, 0.75);\n\n let roll = random.random();\n\n (roll < target, roll)\n\n }\n", "file_path": "src/game/stats.rs", "rank": 41, "score": 27843.532034700947 }, { "content": " dexterity,\n\n strength,\n\n fortitude,\n\n aggression,\n\n intellect,\n\n }\n\n }\n\n\n\n /// Crates a new, randomized stat set\n\n pub fn random(mut points: isize, random: &mut Random) -> Self {\n\n let mut stats = Self::default();\n\n\n\n // shuffle the stat types\n\n let mut buckets = vec![\n\n StatId::Constitution,\n\n StatId::Dexterity,\n\n StatId::Strength,\n\n StatId::Fortitude,\n\n StatId::Aggression,\n\n StatId::Intellect,\n", "file_path": "src/game/stats.rs", "rank": 42, "score": 27840.949903733374 }, { "content": " fortitude: Stat,\n\n aggression: Stat,\n\n intellect: Stat,\n\n}\n\n\n\nmacro_rules! impl_stat {\n\n ($statid:tt) => {\n\n /// Gets the value of the stat\n\n #[inline]\n\n pub fn $statid(&self) -> isize {\n\n self.$statid.value\n\n }\n\n\n\n paste! {\n\n /// Sets the value of the stat\n\n #[inline]\n\n pub fn [<set_ $statid>](&mut self, value: isize) {\n\n self.$statid.value = value;\n\n }\n\n }\n", "file_path": "src/game/stats.rs", "rank": 43, "score": 27839.757023899823 }, { "content": " }\n\n StatId::Fortitude => {\n\n // TODO:\n\n }\n\n StatId::Aggression => {\n\n // TODO:\n\n }\n\n StatId::Intellect => {\n\n // TODO:\n\n }\n\n }\n\n }\n\n\n\n /// Modifies a stat by amount\n\n #[inline]\n\n fn modify(&mut self, statid: StatId, amount: isize) {\n\n match statid {\n\n StatId::Constitution => {\n\n self.constitution.value += amount;\n\n }\n", "file_path": "src/game/stats.rs", "rank": 44, "score": 27839.319376562216 }, { "content": "\n\n impl_stat!(intellect);\n\n\n\n /// Gets the chance to move towards food\n\n #[inline]\n\n pub fn move_towards_food(&self, random: &mut Random) -> (bool, f64) {\n\n let target =\n\n (BASE_MOVE_TOWARDS_FOOD + self.intellect() as f64 * INTELLECT_MOD).clamp(0.0, 0.75);\n\n let roll = random.random();\n\n (roll < target, roll)\n\n }\n\n}\n", "file_path": "src/game/stats.rs", "rank": 45, "score": 27839.093084885153 }, { "content": " };\n\n}\n\n\n\nimpl StatSet {\n\n pub fn size() -> usize {\n\n 1\n\n }\n\n\n\n /// Creates a new stat set\n\n #[allow(dead_code)]\n\n pub fn new(\n\n constitution: Stat,\n\n dexterity: Stat,\n\n strength: Stat,\n\n fortitude: Stat,\n\n aggression: Stat,\n\n intellect: Stat,\n\n ) -> Self {\n\n Self {\n\n constitution,\n", "file_path": "src/game/stats.rs", "rank": 46, "score": 27836.83713458861 }, { "content": " /// Gets the automata initial health, based on Constitution stat\n\n #[inline]\n\n pub fn initial_health(&self) -> usize {\n\n (BASE_HEALTH + (self.constitution() as f32 * CONSTITUTION_MOD) as isize).max(1) as usize\n\n }\n\n\n\n impl_stat!(dexterity);\n\n\n\n /// Gets the automata movement, based on Dexterity stat\n\n #[inline]\n\n pub fn movement(&self) -> usize {\n\n (BASE_MOVEMENT + (self.dexterity() as f32 * DEXTERITY_MOD) as isize).max(1) as usize\n\n }\n\n\n\n impl_stat!(strength);\n\n\n\n /// Gets the automata attack damage, based on Strength stat\n\n #[inline]\n\n pub fn attack_damage(&self) -> usize {\n\n (BASE_ATTACK + (self.strength() as f32 * STRENGTH_MOD) as isize).max(1) as usize\n", "file_path": "src/game/stats.rs", "rank": 47, "score": 27836.649747822255 }, { "content": " StatId::Strength => self.strength(),\n\n StatId::Fortitude => self.fortitude(),\n\n StatId::Aggression => self.aggression(),\n\n StatId::Intellect => self.intellect(),\n\n }\n\n }\n\n\n\n /// Randomizes a single stat\n\n pub fn randomize_stat(&mut self, statid: StatId) {\n\n // TODO: not sure how to handle this,\n\n // if the stat value changes we need to shuffle other stats around\n\n match statid {\n\n StatId::Constitution => {\n\n // TODO:\n\n }\n\n StatId::Dexterity => {\n\n // TODO:\n\n }\n\n StatId::Strength => {\n\n // TODO:\n", "file_path": "src/game/stats.rs", "rank": 48, "score": 27836.5475424889 }, { "content": "const BASE_MOVE_TOWARDS_FOOD: f64 = 0.1;\n\n\n\n/// Intellect modifier for calculating chance to move towards food\n\nconst INTELLECT_MOD: f64 = 0.05 / 5.0; // 5% chance every 5 points\n\n\n\n/// Stat identifier enum for things that need it\n\n#[derive(Debug, Eq, PartialEq, Copy, Clone, Inspectable)]\n\npub enum StatId {\n\n /// Constitution - HP\n\n Constitution,\n\n\n\n /// Dexterity - Movement\n\n Dexterity,\n\n\n\n /// Strength - Attack\n\n Strength,\n\n\n\n /// Fortitude - Defense\n\n Fortitude,\n\n\n", "file_path": "src/game/stats.rs", "rank": 49, "score": 27834.72110121875 }, { "content": " StatId::Dexterity => {\n\n self.dexterity.value += amount;\n\n }\n\n StatId::Strength => {\n\n self.strength.value += amount;\n\n }\n\n StatId::Fortitude => {\n\n self.fortitude.value += amount;\n\n }\n\n StatId::Aggression => {\n\n self.aggression.value += amount;\n\n }\n\n StatId::Intellect => {\n\n self.intellect.value += amount;\n\n }\n\n }\n\n }\n\n\n\n impl_stat!(constitution);\n\n\n", "file_path": "src/game/stats.rs", "rank": 50, "score": 27832.457538767158 }, { "content": " /// Aggression - Move towards enemy automata\n\n Aggression,\n\n\n\n /// Intellect - Move towards food\n\n Intellect,\n\n}\n\n\n\nimpl StatId {\n\n // TODO: replace this with a From<> impl\n\n pub fn name(&self) -> Cow<'static, str> {\n\n match self {\n\n StatId::Constitution => \"Constitution\".into(),\n\n StatId::Dexterity => \"Dexterity\".into(),\n\n StatId::Strength => \"Strength\".into(),\n\n StatId::Fortitude => \"Fortitude\".into(),\n\n StatId::Aggression => \"Aggression\".into(),\n\n StatId::Intellect => \"Intellect\".into(),\n\n }\n\n }\n\n}\n", "file_path": "src/game/stats.rs", "rank": 51, "score": 27832.272040308522 }, { "content": "//! Automata stats\n\n\n\nuse std::borrow::Cow;\n\n\n\nuse bevy_inspector_egui::prelude::*;\n\nuse paste::paste;\n\n\n\nuse crate::resources::*;\n\n\n\n/// Base automata health\n\nconst BASE_HEALTH: isize = 10;\n\n\n\n/// Constitution modifier for calculating initial health\n\nconst CONSTITUTION_MOD: f32 = 1.0;\n\n\n\n/// Base automata movement\n\nconst BASE_MOVEMENT: isize = 1;\n\n\n\n/// Dexterity modifier for calculating movement\n\nconst DEXTERITY_MOD: f32 = 0.2;\n", "file_path": "src/game/stats.rs", "rank": 52, "score": 27830.377665761916 }, { "content": "\n\n/// Base automata attack damage\n\nconst BASE_ATTACK: isize = 1;\n\n\n\n/// Strength modifier for calculating attack damage\n\nconst STRENGTH_MOD: f32 = 0.25;\n\n\n\n/// Base automata attack damage absorb\n\nconst BASE_ATTACK_ABSORB: isize = 0;\n\n\n\n/// Fortitude modifier for calculating damage absorb\n\nconst FORTITUDE_MOD: f32 = 0.25;\n\n\n\n/// Base chance to move towards the enemy automata\n\nconst BASE_MOVE_TOWARDS_ENEMY: f64 = 0.1; // 10% starting chance\n\n\n\n/// Aggression modifier for calculating chance to move towards enemy automata\n\nconst AGGRESSION_MOD: f64 = 0.05 / 5.0; // 5% chance every 5 points\n\n\n\n/// Base chance to move towards food\n", "file_path": "src/game/stats.rs", "rank": 53, "score": 27828.603865950252 }, { "content": " /// Creates a new, randomized DNA\n\n pub fn new(rounds: usize, points: isize, random: &mut Random) -> Self {\n\n Self {\n\n genes: StatSet::random(points, random),\n\n fitness: StatSetFitness::default(),\n\n rounds,\n\n points,\n\n }\n\n }\n\n\n\n /// Adjust genetic fitness based on round results\n\n pub fn fitness(&mut self, stats: &StatSet, health: usize) {\n\n self.fitness.constitution = health.pow(2) as f32 / stats.initial_health().pow(2) as f32;\n\n\n\n // TODO:\n\n //self.fitness.dexterity = ???\n\n //self.fitness.strength = ???\n\n //self.fitenss.fortitude = ???\n\n //self.fitness.aggression = ???\n\n //self.fitness.intellect = ???\n", "file_path": "src/game/dna.rs", "rank": 56, "score": 22.247340254358274 }, { "content": "//! UI components\n\n\n\nuse bevy::prelude::*;\n\nuse bevy_inspector_egui::prelude::*;\n\n\n\nuse crate::game::stats::*;\n\nuse crate::resources::ui::*;\n\n\n\n/// Button helper\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct ButtonHelper {\n\n interactable: bool,\n\n}\n\n\n\nimpl ButtonHelper {\n\n pub fn new(interactable: bool) -> Self {\n\n Self { interactable }\n\n }\n\n\n\n #[inline]\n", "file_path": "src/components/ui.rs", "rank": 60, "score": 16.8061975600349 }, { "content": " #[allow(dead_code)]\n\n pub fn shuffle<T>(&mut self, v: &mut Vec<T>) {\n\n v.shuffle(&mut self.random);\n\n }\n\n\n\n /// Coin returns a random boolean\n\n #[allow(dead_code)]\n\n pub fn coin(&mut self) -> bool {\n\n self.random_range(0..=1) == 1\n\n }\n\n\n\n /// Dice returns a random in the range [1..faces]\n\n #[allow(dead_code)]\n\n pub fn dice(&mut self, faces: usize) -> usize {\n\n self.random_range(1..=faces)\n\n }\n\n\n\n /// Generates a uniform random value in the range [0..1)\n\n #[allow(dead_code)]\n\n pub fn random(&mut self) -> f64 {\n", "file_path": "src/resources/mod.rs", "rank": 61, "score": 16.146706220333456 }, { "content": "//! AI dna\n\n\n\nuse bevy::prelude::*;\n\nuse bevy_inspector_egui::prelude::*;\n\n\n\nuse crate::resources::*;\n\n\n\nuse super::stats::*;\n\n\n\npub const MUTATION_RATE: f64 = 0.01; // 1% chance to mutate\n\n\n\n#[derive(Debug, Copy, Clone)]\n", "file_path": "src/game/dna.rs", "rank": 62, "score": 14.957207624250044 }, { "content": " } else {\n\n partner.genes.intellect()\n\n });\n\n }\n\n }\n\n\n\n child\n\n }\n\n\n\n /// Randomly mutate a specific stat at the given mutation rate\n\n fn mutate_stat(&mut self, mutation_rate: f64, random: &mut Random, statid: StatId) {\n\n if random.random() < mutation_rate {\n\n debug!(\"{} mutation!\", statid.name());\n\n self.genes.randomize_stat(statid);\n\n }\n\n }\n\n\n\n /// Mutate random genes at the given mutation rate\n\n fn mutate(&mut self, mutation_rate: f64, random: &mut Random) {\n\n self.mutate_stat(mutation_rate, random, StatId::Constitution);\n\n self.mutate_stat(mutation_rate, random, StatId::Dexterity);\n\n self.mutate_stat(mutation_rate, random, StatId::Strength);\n\n self.mutate_stat(mutation_rate, random, StatId::Fortitude);\n\n self.mutate_stat(mutation_rate, random, StatId::Aggression);\n\n self.mutate_stat(mutation_rate, random, StatId::Intellect);\n\n }\n\n}\n", "file_path": "src/game/dna.rs", "rank": 63, "score": 14.458823308403606 }, { "content": "//! Gridworld resources\n\n\n\nuse bevy::prelude::*;\n\n\n\n/// A GridWorld cell\n\n#[derive(Debug)]\n\npub struct Cell(pub UVec2);\n\n\n\n/// The grid... world\n\n#[derive(Debug, Default)]\n\npub struct GridWorld {\n\n pub cells: Vec<Cell>,\n\n}\n\n\n\nimpl GridWorld {\n\n /// Creates a new grid world\n\n pub fn new(width: usize, height: usize) -> Self {\n\n let size = width * height;\n\n let mut cells = Vec::with_capacity(size);\n\n\n", "file_path": "src/resources/gridworld.rs", "rank": 64, "score": 14.178507339435518 }, { "content": "\n\n // AI automata population\n\n let ai_population = AIAutomataPopulation::new(\n\n MUTATION_RATE,\n\n crate::ROUNDS,\n\n crate::STAT_POINTS,\n\n &mut random,\n\n );\n\n commands.insert_resource(ai_population);\n\n\n\n // round\n\n commands.insert_resource(GameRound::default());\n\n\n\n // UI\n\n let root = spawn_ui_root(&mut commands);\n\n commands.entity(root).with_children(|parent| {\n\n spawn_header(parent, &fonts, \"Remix Exploration\");\n\n\n\n spawn_spacer(parent);\n\n\n\n spawn_ok_action(parent, &button_colors, &fonts, \"Play\", true);\n\n });\n\n}\n\n\n", "file_path": "src/states/intro.rs", "rank": 65, "score": 14.163618465709519 }, { "content": "}\n\n\n\nimpl Default for Random {\n\n /// Constructs a default random from system entropy\n\n fn default() -> Self {\n\n Self {\n\n random: StdRng::from_entropy(),\n\n }\n\n }\n\n}\n\n\n\nimpl Random {\n\n /// Constructs a new random from a seed\n\n #[allow(dead_code)]\n\n pub fn new(seed: u64) -> Self {\n\n Self {\n\n random: StdRng::seed_from_u64(seed),\n\n }\n\n }\n\n\n", "file_path": "src/resources/mod.rs", "rank": 66, "score": 14.131161469745113 }, { "content": "#[derive(Debug, Default, Component, Inspectable)]\n\npub struct ActionButton;\n\n\n\n/// Cell selection button\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct CellSelectionButton {\n\n // TODO: this should be UVec2, but those aren't Inspectable\n\n pub cell: Vec2,\n\n}\n\n\n\n/// Stat modifier button\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct StatModifierButton {\n\n pub statid: StatId,\n\n pub modifier: isize,\n\n}\n\n\n\n/// Points text tag\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct PointsText;\n", "file_path": "src/components/ui.rs", "rank": 67, "score": 14.016750296049267 }, { "content": " #[derivative(Default)]\n\n PlayerMove,\n\n\n\n /// The player's attack action\n\n PlayerAttack,\n\n\n\n /// The AI's move action\n\n AIMove,\n\n\n\n /// The AI's attack action\n\n AIAttack,\n\n}\n\n\n\n#[derive(Debug, Default)]\n\npub struct GameRound {\n\n pub round: usize,\n\n pub stage: GameStage,\n\n pub action: GameAction,\n\n}\n\n\n\nimpl GameRound {\n\n pub fn reset(&mut self) {\n\n self.stage = GameStage::default();\n\n self.action = GameAction::default();\n\n }\n\n}\n", "file_path": "src/resources/game.rs", "rank": 68, "score": 13.680548538103123 }, { "content": "//! Game resources\n\n\n\nuse derivative::*;\n\n\n\n/// The game stages\n\n#[derive(Debug, Clone, Copy, Eq, PartialEq, Derivative)]\n\n#[derivative(Default)]\n\npub enum GameStage {\n\n /// The player is selecting their spawn cell\n\n #[derivative(Default)]\n\n CellSelection,\n\n\n\n /// The simulation is running\n\n Running,\n\n}\n\n\n\n#[derive(Debug, Clone, Copy, Eq, PartialEq, Derivative)]\n\n#[derivative(Default)]\n\npub enum GameAction {\n\n /// The player's move action\n", "file_path": "src/resources/game.rs", "rank": 70, "score": 12.265985372579074 }, { "content": "\n\n/// Stat modifier text\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct StatModifierText {\n\n pub statid: StatId,\n\n}\n\n\n\n/// Round text\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct RoundText;\n\n\n\n/// Automata health text\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct AutomataHealthText {\n\n pub player: bool,\n\n}\n\n\n\n/// Cell selection tag\n\n#[derive(Component)]\n\npub struct CellSelection;\n\n\n\n/// HUD tag\n\n#[derive(Component)]\n\npub struct Hud;\n", "file_path": "src/components/ui.rs", "rank": 71, "score": 12.113719376573226 }, { "content": " text.sections[0].value = format!(\"{}\", stats.points());\n\n }\n\n\n\n for (mut helper, mut color, modifier) in modifier_query.iter_mut() {\n\n match modifier.modifier.cmp(&0) {\n\n // down\n\n std::cmp::Ordering::Less => helper.set_interactable(\n\n stats.value(modifier.statid) > 0,\n\n &mut color,\n\n &button_colors,\n\n ),\n\n // up\n\n std::cmp::Ordering::Greater => {\n\n helper.set_interactable(stats.points() > 0, &mut color, &button_colors)\n\n }\n\n _ => (),\n\n }\n\n }\n\n\n\n if let Ok((mut action_helper, mut color)) = action_query.get_single_mut() {\n\n action_helper.set_interactable(stats.points() == 0, &mut color, &button_colors);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/remix.rs", "rank": 72, "score": 11.985954662883522 }, { "content": " }\n\n\n\n if let Ok(mut automata) = ai_automata_query.get_single_mut() {\n\n let ai_stats = ai_population.round_stats(round.round);\n\n automata.reset(ai_stats);\n\n\n\n for (mut text, health) in health_text_query.iter_mut() {\n\n if health.player {\n\n continue;\n\n }\n\n\n\n text.sections[0].value = format!(\"{}\", automata.health);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/states/game.rs", "rank": 73, "score": 11.758835147250654 }, { "content": "//! Game states\n\n\n\npub mod game;\n\npub mod gameover;\n\npub mod intro;\n\npub mod remix;\n\n\n\nuse bevy::prelude::*;\n\n\n\nuse crate::bundles::ui::*;\n\nuse crate::components::ui::*;\n\nuse crate::resources::ui::*;\n\n\n\n/// The game state\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]\n\npub enum GameState {\n\n /// Intro state - Explain how to play the game\n\n Intro,\n\n\n\n /// Remix state - Assign attribute points\n", "file_path": "src/states/mod.rs", "rank": 74, "score": 11.32070402136124 }, { "content": "//! ECS resources\n\n\n\npub mod automata;\n\npub mod debug;\n\npub mod game;\n\npub mod gridworld;\n\npub mod ui;\n\n\n\nuse bevy::prelude::*;\n\nuse num_traits::Float;\n\nuse rand::distributions::uniform::{SampleRange, SampleUniform};\n\nuse rand::prelude::*;\n\nuse rand_distr::{Normal, StandardNormal};\n\n\n\nuse crate::util::clampf;\n\n\n\n/// Random wrapper\n\npub struct Random {\n\n // TODO: would SmallRng be better here? we don't need a secure rng\n\n random: StdRng,\n", "file_path": "src/resources/mod.rs", "rank": 75, "score": 11.227365281806222 }, { "content": " margin: Rect::all(Val::Px(5.0)),\n\n ..Default::default()\n\n },\n\n text: Text::with_section(\n\n format!(\"{}\", player_stats.stats().value(statid)),\n\n TextStyle {\n\n font: fonts.normal.clone(),\n\n font_size: 14.0,\n\n color: Color::WHITE,\n\n },\n\n Default::default(),\n\n ),\n\n ..Default::default()\n\n },\n\n modifier_text: StatModifierText { statid },\n\n });\n\n\n\n parent\n\n .spawn_bundle(NodeBundle {\n\n style: Style {\n", "file_path": "src/states/remix.rs", "rank": 76, "score": 10.447597972078562 }, { "content": " color: Color::NONE.into(),\n\n ..Default::default()\n\n },\n\n helper: ButtonHelper::new(true),\n\n modifier_button: StatModifierButton {\n\n statid,\n\n modifier: 1,\n\n },\n\n })\n\n .with_children(|parent| {\n\n parent.spawn_bundle(TextBundle {\n\n text: Text::with_section(\n\n \"^\",\n\n TextStyle {\n\n font: fonts.normal.clone(),\n\n font_size: 12.0,\n\n color: Color::rgb(0.9, 0.9, 0.9),\n\n },\n\n Default::default(),\n\n ),\n", "file_path": "src/states/remix.rs", "rank": 77, "score": 10.060344443549894 }, { "content": "\n\n #[bundle]\n\n pub text: TextBundle,\n\n}\n\n\n\n/// Stat Modifier text component bundle\n\n#[derive(Bundle)]\n\npub struct StatModifierTextBundle {\n\n pub modifier_text: StatModifierText,\n\n\n\n #[bundle]\n\n pub text: TextBundle,\n\n}\n\n\n\n/// Round text component bundle\n\n#[derive(Bundle)]\n\npub struct RoundTextBundle {\n\n pub round_text: RoundText,\n\n\n\n #[bundle]\n", "file_path": "src/bundles/ui.rs", "rank": 78, "score": 9.946353890554175 }, { "content": " },\n\n Default::default(),\n\n ),\n\n ..Default::default()\n\n },\n\n points_text: PointsText,\n\n });\n\n });\n\n\n\n spawn_stat_input(\n\n parent,\n\n &button_colors,\n\n &fonts,\n\n StatId::Constitution,\n\n &player_stats,\n\n \"Initial health\",\n\n );\n\n\n\n spawn_stat_input(\n\n parent,\n", "file_path": "src/states/remix.rs", "rank": 79, "score": 9.735990064319328 }, { "content": "//! Remix state events\n\n\n\nuse crate::game::stats::*;\n\n\n\n/// Notifies about a stat being modified in the UI\n\npub struct StatModifiedEvent(pub StatId);\n", "file_path": "src/events/remix.rs", "rank": 81, "score": 9.561610397425149 }, { "content": "//! GridWorld components\n\n\n\nuse bevy::prelude::*;\n\nuse bevy_inspector_egui::prelude::*;\n\n\n\nuse crate::bundles::gridworld::*;\n\nuse crate::util::*;\n\n\n\nconst PADDING: f32 = 0.1;\n\n\n\n/// GridWorld Cell tag\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct GridWorldCell;\n\n\n\nimpl GridWorldCell {\n\n pub fn spawn(commands: &mut Commands, parent: Entity, cell: UVec2, color: Color) {\n\n let position = cell_position(cell, 0.0);\n\n //debug!(\"Cell position: {}\", position);\n\n\n\n commands.entity(parent).with_children(|parent| {\n", "file_path": "src/components/gridworld.rs", "rank": 82, "score": 9.484541655804481 }, { "content": "//! UI plugin\n\n\n\nuse bevy::prelude::*;\n\n\n\nuse crate::systems::ui::*;\n\n\n\n/// UI plugin\n\npub struct UIPlugin;\n\n\n\nimpl Plugin for UIPlugin {\n\n fn build(&self, app: &mut App) {\n\n // systems\n\n app.add_system(update_buttons);\n\n }\n\n}\n", "file_path": "src/plugins/ui.rs", "rank": 83, "score": 9.447596366606012 }, { "content": "//! Automata components\n\n\n\nuse std::cmp::Ordering;\n\n\n\nuse bevy::prelude::*;\n\nuse bevy_inspector_egui::prelude::*;\n\n\n\nuse crate::bundles::automata::*;\n\nuse crate::resources::automata::*;\n\nuse crate::resources::*;\n\nuse crate::util::*;\n\n\n\n/// Automata state\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct Automata {\n\n /// Current HP (health)\n\n pub health: usize,\n\n // TODO:\n\n // # of moves made towards enemy\n\n // # of moves made towards food\n", "file_path": "src/components/automata.rs", "rank": 84, "score": 9.284118783372318 }, { "content": "\n\npub const TOP_MARGIN: f32 = 1.0;\n\npub const LEFT_MARGIN: f32 = 0.0;\n\n\n\nconst BASE_CELL_WIDTH: f32 = 1.0;\n\nconst BASE_CELL_HEIGHT: f32 = 1.0;\n\n\n\n// TODO: this is a mess...\n\npub const CELL_X_SCALE: f32 =\n\n ((GRID_WIDTH as f32 * BASE_CELL_WIDTH) - LEFT_MARGIN) / (GRID_WIDTH as f32 * BASE_CELL_WIDTH);\n\npub const CELL_Y_SCALE: f32 = ((GRID_HEIGHT as f32 * BASE_CELL_HEIGHT) - TOP_MARGIN)\n\n / (GRID_HEIGHT as f32 * BASE_CELL_HEIGHT);\n\n\n\npub const CELL_WIDTH: f32 = BASE_CELL_WIDTH * CELL_X_SCALE * ASPECT_RATIO;\n\npub const CELL_HEIGHT: f32 = BASE_CELL_HEIGHT * CELL_Y_SCALE;\n\n\n\npub const ROUNDS: usize = 10;\n\npub const STAT_POINTS: isize = 50;\n\n\n\n/// Initial setup\n", "file_path": "src/main.rs", "rank": 85, "score": 9.122381359810003 }, { "content": " font_size: 24.0,\n\n color: Color::WHITE,\n\n },\n\n Default::default(),\n\n ),\n\n ..Default::default()\n\n });\n\n\n\n parent.spawn_bundle(PointsTextBundle {\n\n text: TextBundle {\n\n style: Style {\n\n margin: Rect::all(Val::Px(5.0)),\n\n ..Default::default()\n\n },\n\n text: Text::with_section(\n\n format!(\"{}\", player_stats.points()),\n\n TextStyle {\n\n font: fonts.normal.clone(),\n\n font_size: 24.0,\n\n color: Color::WHITE,\n", "file_path": "src/states/remix.rs", "rank": 86, "score": 9.074817938609222 }, { "content": " pub fn interactable(&self) -> bool {\n\n self.interactable\n\n }\n\n\n\n pub fn set_interactable(\n\n &mut self,\n\n interactable: bool,\n\n color: &mut UiColor,\n\n colors: &ButtonColors,\n\n ) {\n\n self.interactable = interactable;\n\n *color = if self.interactable {\n\n colors.normal\n\n } else {\n\n colors.disabled\n\n };\n\n }\n\n}\n\n\n\n/// Action button\n", "file_path": "src/components/ui.rs", "rank": 87, "score": 9.034717943588735 }, { "content": " }\n\n\n\n /// Create a child through gentics crossover\n\n fn crossover(&self, partner: &Dna, method: CrossoverMethod, random: &mut Random) -> Dna {\n\n let mut child = Dna::new(self.rounds, self.points, random);\n\n\n\n match method {\n\n CrossoverMethod::Midpoint => {\n\n child.genes.set_constitution(self.genes.constitution());\n\n child.genes.set_dexterity(self.genes.dexterity());\n\n child.genes.set_strength(self.genes.strength());\n\n child.genes.set_fortitude(partner.genes.fortitude());\n\n child.genes.set_aggression(partner.genes.aggression());\n\n child.genes.set_intellect(partner.genes.intellect());\n\n }\n\n CrossoverMethod::Coin => {\n\n child\n\n .genes\n\n .set_constitution(if random.random_range(0..=1) == 0 {\n\n self.genes.constitution()\n", "file_path": "src/game/dna.rs", "rank": 88, "score": 8.951862263605907 }, { "content": " .spawn_bundle(NodeBundle {\n\n style: Style {\n\n size: Size::new(Val::Auto, Val::Auto),\n\n align_items: AlignItems::Center,\n\n ..Default::default()\n\n },\n\n color: Color::NONE.into(),\n\n ..Default::default()\n\n })\n\n .insert(Name::new(\"Stat Points\"))\n\n .with_children(|parent| {\n\n parent.spawn_bundle(TextBundle {\n\n style: Style {\n\n margin: Rect::all(Val::Px(5.0)),\n\n ..Default::default()\n\n },\n\n text: Text::with_section(\n\n \"Remaining Stat Points: \",\n\n TextStyle {\n\n font: fonts.normal.clone(),\n", "file_path": "src/states/remix.rs", "rank": 89, "score": 8.84941216152744 }, { "content": "//! ECS components\n\n\n\npub mod automata;\n\npub mod gridworld;\n\npub mod ui;\n\n\n\nuse bevy::prelude::*;\n\nuse bevy_inspector_egui::prelude::*;\n\n\n\n/// Main camera tag\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct MainCamera;\n\n\n\n/// UI camera tag\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct UiCamera;\n", "file_path": "src/components/mod.rs", "rank": 90, "score": 8.718959224801031 }, { "content": " if random.coin() {\n\n 0\n\n } else {\n\n crate::GRID_HEIGHT as u32 - 1\n\n }\n\n }\n\n },\n\n );\n\n\n\n info!(\"Spawning AI at {}\", ai_cell);\n\n\n\n let entity = Automata::spawn(commands, parent, ai_cell, color, \"AI automata\");\n\n\n\n commands.entity(entity).insert(AIAutomata);\n\n }\n\n\n\n /// Resets an automata to its initial state\n\n pub fn reset(&mut self, stats: &dyn AutomataStats) {\n\n self.health = stats.stats().initial_health();\n\n }\n", "file_path": "src/components/automata.rs", "rank": 91, "score": 8.501702132902288 }, { "content": "\n\n ret.unwrap()\n\n }\n\n\n\n /// Spawn a new player automata\n\n pub fn spawn_player(commands: &mut Commands, parent: Entity, color: Color, player_cell: UVec2) {\n\n info!(\"Spawning player at {}\", player_cell);\n\n\n\n let entity = Automata::spawn(commands, parent, player_cell, color, \"Player automata\");\n\n\n\n commands.entity(entity).insert(PlayerAutomata);\n\n }\n\n\n\n /// Spawn a new AI automata population\n\n pub fn spawn_ai(\n\n commands: &mut Commands,\n\n parent: Entity,\n\n color: Color,\n\n player_cell: UVec2,\n\n random: &mut Random,\n", "file_path": "src/components/automata.rs", "rank": 92, "score": 8.48469291836295 }, { "content": " self.random_range(0.0..1.0)\n\n }\n\n\n\n /// Generates a uniform random value in the given range\n\n #[allow(dead_code)]\n\n pub fn random_range<T, R>(&mut self, range: R) -> T\n\n where\n\n T: SampleUniform,\n\n R: SampleRange<T>,\n\n {\n\n self.random.gen_range(range)\n\n }\n\n\n\n /// Generates a uniform random vector in the range ([0..1], [0..1])\n\n #[allow(dead_code)]\n\n pub fn vec2(&mut self) -> Vec2 {\n\n self.vec2_range(0.0..=1.0, 0.0..=1.0)\n\n }\n\n\n\n /// Generates a uniform random vector in the given range\n", "file_path": "src/resources/mod.rs", "rank": 93, "score": 8.397954615357037 }, { "content": " pub modifier_button: StatModifierButton,\n\n\n\n #[bundle]\n\n pub button: ButtonBundle,\n\n}\n\n\n\n/// Cell selection button component bundle\n\n#[derive(Bundle)]\n\npub struct CellSelectionButtonBundle {\n\n pub helper: ButtonHelper,\n\n pub cell_selection_button: CellSelectionButton,\n\n\n\n #[bundle]\n\n pub button: ButtonBundle,\n\n}\n\n\n\n/// Points text component bundle\n\n#[derive(Bundle)]\n\npub struct PointsTextBundle {\n\n pub points_text: PointsText,\n", "file_path": "src/bundles/ui.rs", "rank": 94, "score": 8.386565878844372 }, { "content": "//! Game states plugin\n\n\n\nuse bevy::app::PluginGroupBuilder;\n\nuse bevy::prelude::*;\n\n\n\nuse crate::events::game::*;\n\nuse crate::events::remix::*;\n\nuse crate::states;\n\nuse crate::states::*;\n\n\n\n/// Game states plugin group\n\npub struct StatesPlugins;\n\n\n\nimpl PluginGroup for StatesPlugins {\n\n fn build(&mut self, group: &mut PluginGroupBuilder) {\n\n group\n\n .add(IntroStatePlugin)\n\n .add(RemixStatePlugin)\n\n .add(GameStatePlugin)\n\n .add(GameOverStatePlugin);\n\n }\n\n}\n\n\n\n/// Intro state plugin\n", "file_path": "src/plugins/states.rs", "rank": 95, "score": 8.366004546745097 }, { "content": "//! UI bundles\n\n\n\nuse bevy::prelude::*;\n\n\n\nuse crate::components::ui::*;\n\n\n\n/// Action button component bundle\n\n#[derive(Bundle)]\n\npub struct ActionButtonBundle {\n\n pub helper: ButtonHelper,\n\n pub action_button: ActionButton,\n\n\n\n #[bundle]\n\n pub button: ButtonBundle,\n\n}\n\n\n\n/// Stat modifier button component bundle\n\n#[derive(Bundle)]\n\npub struct StatModifierButtonBundle {\n\n pub helper: ButtonHelper,\n", "file_path": "src/bundles/ui.rs", "rank": 96, "score": 8.341095346431006 }, { "content": "//! Debug resources\n\n\n\n/// Holds whatever debug state we need to keep around\n\n#[derive(Debug, Default)]\n\npub struct DebugState {\n\n pub enabled: bool,\n\n}\n", "file_path": "src/resources/debug.rs", "rank": 97, "score": 8.331250480926219 }, { "content": "\n\n pub fn move_action(&mut self) {\n\n debug!(\"move\");\n\n }\n\n\n\n pub fn attack_action(&mut self) {\n\n debug!(\"attack\");\n\n }\n\n}\n\n\n\n/// Player automata tag\n\n#[derive(Debug, Default, Component, Inspectable)]\n\npub struct PlayerAutomata;\n\n\n\n/// AI automata state\n\n#[derive(Debug, Component, Inspectable)]\n\npub struct AIAutomata;\n", "file_path": "src/components/automata.rs", "rank": 98, "score": 8.239081334266668 }, { "content": " #[allow(dead_code)]\n\n pub fn vec2_range<R>(&mut self, xrange: R, yrange: R) -> Vec2\n\n where\n\n R: SampleRange<f32>,\n\n {\n\n Vec2::new(self.random_range(xrange), self.random_range(yrange))\n\n }\n\n\n\n /// Generates a uniform random direction vector\n\n #[allow(dead_code)]\n\n pub fn direction(&mut self) -> Vec2 {\n\n let theta = self.random() as f32 * std::f32::consts::PI * 2.0;\n\n Vec2::new(theta.cos(), theta.sin())\n\n }\n\n\n\n /// Generates a random value with the given normal distribution\n\n #[allow(dead_code)]\n\n pub fn normal<F>(&mut self, mean: F, std_dev: F) -> F\n\n where\n\n F: Float,\n", "file_path": "src/resources/mod.rs", "rank": 99, "score": 8.237842469686061 } ]
Rust
fusestore/store/src/api/rpc/flight_service_test.rs
tisonkun/datafuse
c0371078750cad9fbf4b3770c1c581dbe10c4b20
use common_arrow::arrow::array::ArrayRef; use common_datablocks::DataBlock; use common_datavalues::DataColumnarValue; use common_flights::GetTableActionResult; use common_flights::StoreClient; use common_planners::ScanPlan; use log::info; use pretty_assertions::assert_eq; use test_env_log::test; #[test(tokio::test)] async fn test_flight_create_database() -> anyhow::Result<()> { use common_planners::CreateDatabasePlan; use common_planners::DatabaseEngineType; let addr = crate::tests::start_store_server().await?; let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: "db1".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(0, res.database_id, "first database id is 0"); } { let plan = CreateDatabasePlan { if_not_exists: false, db: "db2".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(1, res.database_id, "second database id is 1"); } Ok(()) } #[test(tokio::test)] async fn test_flight_create_get_table() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; info!("init logging"); let addr = crate::tests::start_store_server().await?; let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: "db1".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(0, res.database_id, "first database id is 0"); } { let schema = Arc::new(DataSchema::new(vec![DataField::new( "number", DataType::UInt64, false, )])); let mut plan = CreateTablePlan { if_not_exists: false, db: "db1".to_string(), table: "tb2".to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::JsonEachRaw, }; { let res = client.create_table(plan.clone()).await.unwrap(); assert_eq!(1, res.table_id, "table id is 1"); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get created table"); } { plan.if_not_exists = true; let res = client.create_table(plan.clone()).await.unwrap(); assert_eq!(1, res.table_id, "new table id"); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get created table"); } { plan.if_not_exists = false; let res = client.create_table(plan.clone()).await; info!("create table res: {:?}", res); let status = res.err().unwrap(); assert_eq!( "status: Some entity that we attempted to create already exists: table exists", status.to_string() ); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get old table"); } } Ok(()) } #[test(tokio::test)] async fn test_do_append() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_datavalues::Int64Array; use common_datavalues::StringArray; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; let addr = crate::tests::start_store_server().await?; let schema = Arc::new(DataSchema::new(vec![ DataField::new("col_i", DataType::Int64, false), DataField::new("col_s", DataType::Utf8, false), ])); let db_name = "test_db"; let tbl_name = "test_tbl"; let col0: ArrayRef = Arc::new(Int64Array::from(vec![0, 1, 2])); let col1: ArrayRef = Arc::new(StringArray::from(vec!["str1", "str2", "str3"])); let expected_rows = col0.data().len() * 2; let expected_cols = 2; let block = DataBlock::create_by_array(schema.clone(), vec![col0, col1]); let batches = vec![block.clone(), block]; let num_batch = batches.len(); let stream = futures::stream::iter(batches); let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: db_name.to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; client.create_database(plan.clone()).await?; let plan = CreateTablePlan { if_not_exists: false, db: db_name.to_string(), table: tbl_name.to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::Parquet, }; client.create_table(plan.clone()).await?; } let res = client .append_data( db_name.to_string(), tbl_name.to_string(), schema, Box::pin(stream), ) .await?; log::info!("append res is {:?}", res); let summary = res.summary; assert_eq!(summary.rows, expected_rows); assert_eq!(res.parts.len(), num_batch); res.parts.iter().for_each(|p| { assert_eq!(p.rows, expected_rows / num_batch); assert_eq!(p.cols, expected_cols); }); Ok(()) } #[test(tokio::test)] async fn test_scan_partition() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_datavalues::Int64Array; use common_datavalues::StringArray; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; let addr = crate::tests::start_store_server().await?; let schema = Arc::new(DataSchema::new(vec![ DataField::new("col_i", DataType::Int64, false), DataField::new("col_s", DataType::Utf8, false), ])); let db_name = "test_db"; let tbl_name = "test_tbl"; let col0: ArrayRef = Arc::new(Int64Array::from(vec![0, 1, 2])); let col1: ArrayRef = Arc::new(StringArray::from(vec!["str1", "str2", "str3"])); let expected_rows = col0.data().len() * 2; let expected_cols = 2; let block = DataBlock::create(schema.clone(), vec![ DataColumnarValue::Array(col0), DataColumnarValue::Array(col1), ]); let batches = vec![block.clone(), block]; let num_batch = batches.len(); let stream = futures::stream::iter(batches); let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: db_name.to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; client.create_database(plan.clone()).await?; let plan = CreateTablePlan { if_not_exists: false, db: db_name.to_string(), table: tbl_name.to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::Parquet, }; client.create_table(plan.clone()).await?; } let res = client .append_data( db_name.to_string(), tbl_name.to_string(), schema, Box::pin(stream), ) .await?; log::info!("append res is {:?}", res); let summary = res.summary; assert_eq!(summary.rows, expected_rows); assert_eq!(res.parts.len(), num_batch); res.parts.iter().for_each(|p| { assert_eq!(p.rows, expected_rows / num_batch); assert_eq!(p.cols, expected_cols); }); let plan = ScanPlan { schema_name: tbl_name.to_string(), ..ScanPlan::empty() }; let res = client .scan_partition(db_name.to_string(), tbl_name.to_string(), &plan) .await; println!("scan res is {:?}", res); Ok(()) }
use common_arrow::arrow::array::ArrayRef; use common_datablocks::DataBlock; use common_datavalues::DataColumnarValue; use common_flights::GetTableActionResult; use common_flights::StoreClient; use common_planners::ScanPlan; use log::info; use pretty_assertions::assert_eq; use test_env_log::test; #[test(tokio::test)] async fn test_flight_create_database() -> anyhow::Result<()> { use common_planners::CreateDatabasePlan; use common_planners::DatabaseEngineType; let addr = crate::tests::start_store_server().await?; let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: "db1".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(0, res.database_id, "first database id is 0"); } { let plan = CreateDatabasePlan { if_not_exists: false, db: "db2".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(1, res.database_id, "second database id is 1"); } Ok(()) } #[test(tokio::test)] async fn test_flight_create_get_table() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; info!("init logging"); let addr = crate::tests::start_store_server().await?; let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: "db1".to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; let res = client.create_database(plan.clone()).await; info!("create database res: {:?}", res); let res = res.unwrap(); assert_eq!(0, res.database_id, "first database id is 0"); } { let schema = Arc::new(DataSchema::new(vec![DataField::new( "number", DataType::UInt64, false, )])); let mut plan = CreateTablePlan { if_not_exists: false, db: "db1".to_string(), table: "tb2".to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::JsonEachRaw, }; { let res = client.create_table(plan.clone()).await.unwrap(); assert_eq!(1, res.table_id, "table id is 1"); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get created table"); } { plan.if_not_exists = true; let res = client.create_table(plan.clone()).await.unwrap(); assert_eq!(1, res.table_id, "new table id"); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get created table"); } { plan.if_not_exists = false; let res = client.create_table(plan.clone()).await; info!("create table res: {:?}", res); let status = res.err().unwrap(); assert_eq!( "status: Some entity that we attempted to create already exists: table exists", status.to_string() ); let got = client.get_table("db1".into(), "tb2".into()).await.unwrap(); let want = GetTableActionResult { table_id: 1, db: "db1".into(), name: "tb2".into(), schema: schema.clone(), }; assert_eq!(want, got, "get old table"); } } Ok(()) } #[test(tokio::test)] async fn test_do_append() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_datavalues::Int64Array; use common_datavalues::StringArray; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; let addr = crate::tests::start_store_server().await?; let schema = Arc::new(DataSchema::new(vec![ DataField::new("col_i", DataType::Int64, false), DataField::new("col_s", DataType::Utf8, false), ]));
#[test(tokio::test)] async fn test_scan_partition() -> anyhow::Result<()> { use std::sync::Arc; use common_arrow::arrow::datatypes::DataType; use common_datavalues::DataField; use common_datavalues::DataSchema; use common_datavalues::Int64Array; use common_datavalues::StringArray; use common_flights::StoreClient; use common_planners::CreateDatabasePlan; use common_planners::CreateTablePlan; use common_planners::DatabaseEngineType; use common_planners::TableEngineType; let addr = crate::tests::start_store_server().await?; let schema = Arc::new(DataSchema::new(vec![ DataField::new("col_i", DataType::Int64, false), DataField::new("col_s", DataType::Utf8, false), ])); let db_name = "test_db"; let tbl_name = "test_tbl"; let col0: ArrayRef = Arc::new(Int64Array::from(vec![0, 1, 2])); let col1: ArrayRef = Arc::new(StringArray::from(vec!["str1", "str2", "str3"])); let expected_rows = col0.data().len() * 2; let expected_cols = 2; let block = DataBlock::create(schema.clone(), vec![ DataColumnarValue::Array(col0), DataColumnarValue::Array(col1), ]); let batches = vec![block.clone(), block]; let num_batch = batches.len(); let stream = futures::stream::iter(batches); let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: db_name.to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; client.create_database(plan.clone()).await?; let plan = CreateTablePlan { if_not_exists: false, db: db_name.to_string(), table: tbl_name.to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::Parquet, }; client.create_table(plan.clone()).await?; } let res = client .append_data( db_name.to_string(), tbl_name.to_string(), schema, Box::pin(stream), ) .await?; log::info!("append res is {:?}", res); let summary = res.summary; assert_eq!(summary.rows, expected_rows); assert_eq!(res.parts.len(), num_batch); res.parts.iter().for_each(|p| { assert_eq!(p.rows, expected_rows / num_batch); assert_eq!(p.cols, expected_cols); }); let plan = ScanPlan { schema_name: tbl_name.to_string(), ..ScanPlan::empty() }; let res = client .scan_partition(db_name.to_string(), tbl_name.to_string(), &plan) .await; println!("scan res is {:?}", res); Ok(()) }
let db_name = "test_db"; let tbl_name = "test_tbl"; let col0: ArrayRef = Arc::new(Int64Array::from(vec![0, 1, 2])); let col1: ArrayRef = Arc::new(StringArray::from(vec!["str1", "str2", "str3"])); let expected_rows = col0.data().len() * 2; let expected_cols = 2; let block = DataBlock::create_by_array(schema.clone(), vec![col0, col1]); let batches = vec![block.clone(), block]; let num_batch = batches.len(); let stream = futures::stream::iter(batches); let mut client = StoreClient::try_create(addr.as_str(), "root", "xxx").await?; { let plan = CreateDatabasePlan { if_not_exists: false, db: db_name.to_string(), engine: DatabaseEngineType::Local, options: Default::default(), }; client.create_database(plan.clone()).await?; let plan = CreateTablePlan { if_not_exists: false, db: db_name.to_string(), table: tbl_name.to_string(), schema: schema.clone(), options: maplit::hashmap! {"opt‐1".into() => "val-1".into()}, engine: TableEngineType::Parquet, }; client.create_table(plan.clone()).await?; } let res = client .append_data( db_name.to_string(), tbl_name.to_string(), schema, Box::pin(stream), ) .await?; log::info!("append res is {:?}", res); let summary = res.summary; assert_eq!(summary.rows, expected_rows); assert_eq!(res.parts.len(), num_batch); res.parts.iter().for_each(|p| { assert_eq!(p.rows, expected_rows / num_batch); assert_eq!(p.cols, expected_cols); }); Ok(()) }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn test_mem_engine_create_get_table() -> anyhow::Result<()> {\n\n // TODO check generated ver\n\n let eng = MemEngine::create();\n\n\n\n let mut eng = eng.lock().unwrap();\n\n\n\n let cmdfoo = CmdCreateDatabase {\n\n db_name: \"foo\".into(),\n\n db: Some(Db {\n\n db_id: -1,\n\n ver: -1,\n\n table_name_to_id: HashMap::new(),\n\n tables: HashMap::new(),\n\n }),\n\n };\n\n\n\n let cmd_table = CmdCreateTable {\n\n db_name: \"foo\".into(),\n\n table_name: \"t1\".into(),\n\n table: Some(Table {\n", "file_path": "fusestore/store/src/engine/mem_engine_test.rs", "rank": 0, "score": 273590.02057403466 }, { "content": "SELECT COUNT(1) from system.tables where name = 't' and database = 'db';\n\n\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_create_database.sql", "rank": 1, "score": 255699.58258542445 }, { "content": "create table default.test_csv (id int,name varchar(255),rank int) Engine = CSV location = 'tests/data/sample.csv';\n", "file_path": "tests/suites/0_stateless/05_0002_ddl_create_local_csv_table.sql", "rank": 2, "score": 255308.88245970104 }, { "content": "select avg(rank), max(id), name from default.test_csv group by name order by name desc;\n", "file_path": "tests/suites/0_stateless/05_0002_ddl_create_local_csv_table.sql", "rank": 3, "score": 237474.31505243963 }, { "content": "CREATE DATABASE IF NOT EXISTS db ENGINE = Local;\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_create_database.sql", "rank": 4, "score": 228637.5756980029 }, { "content": "pub fn set_do_put_meta(meta: &mut MetadataMap, db_name: &str, tbl_name: &str) {\n\n meta.insert_bin(\n\n META_KEY_DB_NAME,\n\n MetadataValue::from_bytes(db_name.as_bytes()),\n\n );\n\n meta.insert_bin(\n\n META_KEY_TBL_NAME,\n\n MetadataValue::from_bytes(tbl_name.as_bytes()),\n\n );\n\n}\n\n\n", "file_path": "common/flights/src/store_do_put.rs", "rank": 5, "score": 227595.16500081655 }, { "content": "pub fn sort(name: &str, asc: bool, nulls_first: bool) -> Expression {\n\n Expression::Sort {\n\n expr: Box::new(col(name)),\n\n asc,\n\n nulls_first,\n\n }\n\n}\n", "file_path": "common/planners/src/plan_expression_sort.rs", "rank": 6, "score": 221820.361816193 }, { "content": "CREATE TABLE IF NOT EXISTS t(c1 int) ENGINE = Null;\n", "file_path": "tests/suites/0_stateless/05_0000_ddl_create_tables.sql", "rank": 7, "score": 210028.90040255775 }, { "content": "select toTypeName(number + 1), toTypeName(number - 1),\n\n toTypeName(number / 1), toTypeName(number * 1) from numbers(100) limit 1;\n", "file_path": "tests/suites/0_stateless/02_0001_function_to_type_name.sql", "rank": 8, "score": 202398.01725590427 }, { "content": "pub fn col(name: &str) -> Expression {\n\n Expression::Column(name.to_string())\n\n}\n", "file_path": "common/planners/src/plan_expression_column.rs", "rank": 9, "score": 201418.5876255663 }, { "content": "CREATE TABLE db.t(c1 int) ENGINE = Null;\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_create_database.sql", "rank": 10, "score": 198135.24757368918 }, { "content": "SELECT COUNT(1) from system.tables where name = 't' and database = 'default';\n\n\n", "file_path": "tests/suites/0_stateless/05_0000_ddl_create_tables.sql", "rank": 11, "score": 197750.32392563508 }, { "content": "CREATE DATABASE db ENGINE = Local;\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_create_database.sql", "rank": 12, "score": 189118.76616577414 }, { "content": "#[test]\n\nfn test_mem_engine_create_database() -> anyhow::Result<()> {\n\n // TODO check generated ver\n\n let eng = MemEngine::create();\n\n\n\n let mut eng = eng.lock().unwrap();\n\n\n\n let cmdfoo = CmdCreateDatabase {\n\n db_name: \"foo\".into(),\n\n db: Some(Db {\n\n db_id: -1,\n\n ver: -1,\n\n table_name_to_id: HashMap::new(),\n\n tables: HashMap::new(),\n\n }),\n\n };\n\n let cmdbar = CmdCreateDatabase {\n\n db_name: \"bar\".into(),\n\n db: Some(Db {\n\n db_id: -1,\n\n ver: -1,\n", "file_path": "fusestore/store/src/engine/mem_engine_test.rs", "rank": 13, "score": 186931.83090461313 }, { "content": "#[test]\n\nfn test_mem_engine_drop_table() -> anyhow::Result<()> {\n\n let eng = MemEngine::create();\n\n let test_db = \"test_db\";\n\n let test_tbl = \"test_tbl\";\n\n let mut eng = eng.lock().unwrap();\n\n\n\n let cmd_db = CmdCreateDatabase {\n\n db_name: test_db.to_string(),\n\n db: Some(Db {\n\n db_id: -1,\n\n ver: -1,\n\n table_name_to_id: HashMap::new(),\n\n tables: HashMap::new(),\n\n }),\n\n };\n\n\n\n let cmd_table = CmdCreateTable {\n\n db_name: test_db.to_string(),\n\n table_name: test_tbl.to_string(),\n\n table: Some(Table {\n", "file_path": "fusestore/store/src/engine/mem_engine_test.rs", "rank": 14, "score": 186667.69357051916 }, { "content": "fn new_addr() -> String {\n\n let addr = format!(\"127.0.0.1:{}\", 19000 + *Seq::default());\n\n tracing::info!(\"new_addr: {}\", addr);\n\n addr\n\n}\n", "file_path": "fusestore/store/src/meta_service/raftmeta_test.rs", "rank": 15, "score": 181021.3308530466 }, { "content": "///! Convert a series of record batches into a table\n\nfn create_table(results: &[DataBlock]) -> Result<Table> {\n\n let mut table = Table::new();\n\n table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);\n\n\n\n if results.is_empty() {\n\n return Ok(table);\n\n }\n\n\n\n let schema = results[0].schema();\n\n\n\n let mut header = Vec::new();\n\n for field in schema.fields() {\n\n header.push(Cell::new(&field.name()));\n\n }\n\n table.set_titles(Row::new(header));\n\n\n\n for batch in results {\n\n for row in 0..batch.num_rows() {\n\n let mut cells = Vec::new();\n\n for col in 0..batch.num_columns() {\n\n let array = batch.column(col).to_array()?;\n\n cells.push(Cell::new(&array_value_to_string(&array, row)?));\n\n }\n\n table.add_row(Row::new(cells));\n\n }\n\n }\n\n\n\n Ok(table)\n\n}\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 16, "score": 178484.78234317742 }, { "content": "CREATE DATABASE db ENGINE = Local;\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_drop_database.sql", "rank": 17, "score": 177505.40351308635 }, { "content": "select toTypeName(number) from numbers(100) limit 1;\n", "file_path": "tests/suites/0_stateless/02_0001_function_to_type_name.sql", "rank": 18, "score": 172479.64739220054 }, { "content": "fn generate_uuids(size: usize) -> (Option<String>, Option<String>, Option<String>) {\n\n match size {\n\n 1 => (Some(uuid::Uuid::new_v4().to_string()), None, None),\n\n 2 => (\n\n Some(uuid::Uuid::new_v4().to_string()),\n\n Some(uuid::Uuid::new_v4().to_string()),\n\n None,\n\n ),\n\n 3 => (\n\n Some(uuid::Uuid::new_v4().to_string()),\n\n Some(uuid::Uuid::new_v4().to_string()),\n\n Some(uuid::Uuid::new_v4().to_string()),\n\n ),\n\n _ => panic!(\"Logic error for generate_uuids.\"),\n\n }\n\n}\n", "file_path": "fusequery/query/src/api/rpc/flight_dispatcher_test.rs", "rank": 19, "score": 168784.64062779656 }, { "content": "CREATE TABLE IF NOT EXISTS t1(a int, b varchar);\n\nSELECT * FROM system.tables WHERE database='db1';\n\n\n", "file_path": "tests/suites/0_stateless/09_0000_remote_create_table.sql", "rank": 20, "score": 165431.32762673145 }, { "content": "CREATE TABLE t(c1 int) ENGINE = Null;\n", "file_path": "tests/suites/0_stateless/05_0000_ddl_create_tables.sql", "rank": 21, "score": 165370.25422829436 }, { "content": "CREATE DATABASE IF NOT EXISTS db1;\n\nUSE db1;\n\n\n", "file_path": "tests/suites/0_stateless/09_0000_remote_create_table.sql", "rank": 22, "score": 158259.19201247205 }, { "content": "DROP TABLE IF EXISTS t1;\n", "file_path": "tests/suites/0_stateless/09_0000_remote_create_table.sql", "rank": 23, "score": 158192.32239526138 }, { "content": "fn criterion_benchmark_aggregate_query(c: &mut Criterion) {\n\n let queries = vec![\n\n \"SELECT MIN(number) FROM numbers_mt(10000000)\",\n\n \"SELECT MAX(number) FROM numbers_mt(10000000)\",\n\n \"SELECT COUNT(number) FROM numbers_mt(10000000)\",\n\n \"SELECT SUM(number) FROM numbers_mt(10000000)\",\n\n \"SELECT AVG(number) FROM numbers_mt(10000000)\",\n\n \"SELECT COUNT(number) FROM numbers_mt(10000000) WHERE number>10 and number<20\",\n\n \"SELECT MIN(number), MAX(number), AVG(number), COUNT(number) FROM numbers_mt(10000000)\",\n\n \"SELECT COUNT(number) FROM numbers_mt(1000000) GROUP BY number%3\",\n\n \"SELECT COUNT(number) FROM numbers_mt(1000000) GROUP BY number%3, number%4\",\n\n ];\n\n\n\n for query in queries {\n\n criterion_benchmark_suite(c, query);\n\n }\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark_aggregate_query);\n\ncriterion_main!(benches);\n", "file_path": "fusequery/query/benches/suites/bench_aggregate_query_sql.rs", "rank": 24, "score": 154433.74636987876 }, { "content": "fn criterion_benchmark_filter_query(c: &mut Criterion) {\n\n let queries = vec![\"SELECT number FROM numbers_mt(10000000) WHERE number>100 AND number<200\"];\n\n\n\n for query in queries {\n\n criterion_benchmark_suite(c, query);\n\n }\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark_filter_query);\n\ncriterion_main!(benches);\n", "file_path": "fusequery/query/benches/suites/bench_filter_query_sql.rs", "rank": 25, "score": 154433.74636987876 }, { "content": "fn criterion_benchmark_limit_query(c: &mut Criterion) {\n\n let queries = vec![\"SELECT number FROM numbers_mt(10000000) LIMIT 1\"];\n\n\n\n for query in queries {\n\n criterion_benchmark_suite(c, query);\n\n }\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark_limit_query);\n\ncriterion_main!(benches);\n", "file_path": "fusequery/query/benches/suites/bench_limit_query_sql.rs", "rank": 26, "score": 154433.74636987876 }, { "content": "fn criterion_benchmark_sort_query(c: &mut Criterion) {\n\n let queries = vec![\n\n \"SELECT number FROM numbers_mt(10000000) ORDER BY number DESC LIMIT 10\",\n\n \"SELECT number FROM numbers_mt(10000000) ORDER BY number ASC LIMIT 10\",\n\n ];\n\n\n\n for query in queries {\n\n criterion_benchmark_suite(c, query);\n\n }\n\n}\n\n\n\ncriterion_group!(benches, criterion_benchmark_sort_query);\n\ncriterion_main!(benches);\n", "file_path": "fusequery/query/benches/suites/bench_sort_query_sql.rs", "rank": 27, "score": 154433.74636987876 }, { "content": "\n\nimpl ToString for TableEngineType {\n\n fn to_string(&self) -> String {\n\n match self {\n\n TableEngineType::JsonEachRaw => \"JSON\".into(),\n\n TableEngineType::Parquet => \"Parquet\".into(),\n\n TableEngineType::Csv => \"CSV\".into(),\n\n TableEngineType::Null => \"Null\".into(),\n\n }\n\n }\n\n}\n\n\n\npub type TableOptions = HashMap<String, String>;\n\n\n\n#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]\n\npub struct CreateTablePlan {\n\n pub if_not_exists: bool,\n\n pub db: String,\n\n /// The table name\n\n pub table: String,\n", "file_path": "common/planners/src/plan_table_create.rs", "rank": 28, "score": 154123.19474417545 }, { "content": " /// The table schema\n\n pub schema: DataSchemaRef,\n\n /// The file type of physical file\n\n pub engine: TableEngineType,\n\n pub options: TableOptions,\n\n}\n\n\n\nimpl CreateTablePlan {\n\n pub fn schema(&self) -> DataSchemaRef {\n\n self.schema.clone()\n\n }\n\n}\n", "file_path": "common/planners/src/plan_table_create.rs", "rank": 29, "score": 154119.58650887146 }, { "content": "// Copyright 2020-2021 The Datafuse Authors.\n\n//\n\n// SPDX-License-Identifier: Apache-2.0.\n\n\n\nuse std::collections::HashMap;\n\n\n\nuse common_datavalues::DataSchemaRef;\n\n\n\n/// Types of files to parse as DataFrames\n\n#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]\n\npub enum TableEngineType {\n\n /// Newline-delimited JSON\n\n JsonEachRaw,\n\n /// Apache Parquet columnar store\n\n Parquet,\n\n /// Comma separated values\n\n Csv,\n\n /// Null ENGINE\n\n Null,\n\n}\n", "file_path": "common/planners/src/plan_table_create.rs", "rank": 30, "score": 154103.77742376344 }, { "content": "CREATE TABLE t(c1 int) ENGINE = Null;\n\n\n", "file_path": "tests/suites/0_stateless/05_0000_ddl_drop_tables.sql", "rank": 31, "score": 153574.8523255647 }, { "content": "fn constant_folding(schema: &DataSchemaRef, expr: Expression) -> Result<Expression> {\n\n let new_expr = match expr {\n\n Expression::BinaryExpression { left, op, right } => match op.as_str() {\n\n \"=\" => match (left.as_ref(), right.as_ref()) {\n\n (\n\n Expression::Literal(DataValue::Boolean(l)),\n\n Expression::Literal(DataValue::Boolean(r)),\n\n ) => match (l, r) {\n\n (Some(l), Some(r)) => Expression::Literal(DataValue::Boolean(Some(l == r))),\n\n _ => Expression::Literal(DataValue::Boolean(None)),\n\n },\n\n (Expression::Literal(DataValue::Boolean(b)), _)\n\n if is_boolean_type(schema, &right)? =>\n\n {\n\n match b {\n\n Some(true) => *right,\n\n // Fix this after we implement NOT\n\n Some(false) => Expression::BinaryExpression { left, op, right },\n\n None => Expression::Literal(DataValue::Boolean(None)),\n\n }\n", "file_path": "fusequery/query/src/optimizers/optimizer_constant_folding.rs", "rank": 32, "score": 151839.27662356492 }, { "content": "fn is_boolean_type(schema: &DataSchemaRef, expr: &Expression) -> Result<bool> {\n\n if let DataType::Boolean = expr.to_data_field(schema)?.data_type() {\n\n return Ok(true);\n\n }\n\n Ok(false)\n\n}\n\n\n", "file_path": "fusequery/query/src/optimizers/optimizer_constant_folding.rs", "rank": 33, "score": 151839.27662356492 }, { "content": "select number * number + 1 as number, number + 1 as b from numbers(1);\n", "file_path": "tests/suites/0_stateless/03_0000_select_aliases.sql", "rank": 34, "score": 150948.56005310564 }, { "content": "/// Resolves an `Expression::Wildcard` to a collection of `Expression::Column`'s.\n\npub fn expand_wildcard(expr: &Expression, schema: &DataSchemaRef) -> Vec<Expression> {\n\n match expr {\n\n Expression::Wildcard => schema\n\n .fields()\n\n .iter()\n\n .map(|f| Expression::Column(f.name().to_string()))\n\n .collect::<Vec<Expression>>(),\n\n _ => vec![expr.clone()],\n\n }\n\n}\n\n\n", "file_path": "fusequery/query/src/sql/expr_common.rs", "rank": 35, "score": 148934.22887765313 }, { "content": "// Rebuilds an `expr` to ColumnExpr when some expressions already processed in upstream\n\n// Skip Sort, Alias because we can go into the inner nest_exprs\n\npub fn rebase_expr_from_input(expr: &Expression, schema: &DataSchemaRef) -> Result<Expression> {\n\n clone_with_replacement(expr, &|nest_exprs| match nest_exprs {\n\n Expression::Sort { .. } | Expression::Column(_) | Expression::Alias(_, _) => Ok(None),\n\n _ => {\n\n if schema.field_with_name(&nest_exprs.column_name()).is_ok() {\n\n Ok(Some(expr_as_column_expr(nest_exprs)?))\n\n } else {\n\n Ok(None)\n\n }\n\n }\n\n })\n\n}\n\n\n", "file_path": "fusequery/query/src/sql/expr_common.rs", "rank": 36, "score": 147751.91634538787 }, { "content": "DROP DATABASE IF EXISTS db1;\n\n\n", "file_path": "tests/suites/0_stateless/09_0000_remote_create_table.sql", "rank": 37, "score": 146842.5583707059 }, { "content": "pub fn criterion_benchmark_suite(c: &mut Criterion, sql: &str) {\n\n c.bench_function(sql, |b| {\n\n b.iter(|| {\n\n tokio::runtime::Runtime::new()\n\n .unwrap()\n\n .block_on(select_executor(sql))\n\n })\n\n });\n\n}\n", "file_path": "fusequery/query/benches/suites/mod.rs", "rank": 38, "score": 144754.082200167 }, { "content": "-- https://github.com/datafuselabs/datafuse/issues/492\n\nSELECT number ,number-1 , number*100 , 1> 100 ,1 < 10 FROM numbers_mt (10) order by number;\n\n\n", "file_path": "tests/suites/0_stateless/02_0005_function_compare.sql", "rank": 39, "score": 144632.23308526343 }, { "content": "CREATE TABLE IF NOT EXISTS t1(a varchar, b varchar);\n\nINSERT INTO t1(a,b) VALUES('1', 'v1'),('2','v2');\n\nSELECT * FROM t1;\n\n\n", "file_path": "tests/suites/0_stateless/09_0001_remote_insert.sql", "rank": 40, "score": 144333.9487561544 }, { "content": "CREATE TABLE t(c1 int) ENGINE = Null;\n\nSHOW TABLES;\n", "file_path": "tests/suites/0_stateless/06_0000_show_queries.sql", "rank": 41, "score": 144271.83200001356 }, { "content": "#[test]\n\nfn test_having_plan() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .having(col(\"number\").eq(lit(1i64)))?\n\n .project(&[col(\"number\")])?\n\n .build()?;\n\n\n\n let expect = \"\\\n\n Projection: number:UInt64\\\n\n \\n Having: (number = 1)\\\n\n \\n ReadDataSource: scan partitions: [8], scan schema: [number:UInt64], statistics: [read_rows: 10000, read_bytes: 80000]\";\n\n let actual = format!(\"{:?}\", plan);\n\n\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_having_test.rs", "rank": 42, "score": 142185.39003367623 }, { "content": "#[test]\n\nfn test_mem_engine_drop_database() -> anyhow::Result<()> {\n\n let eng = MemEngine::create();\n\n let mut eng = eng.lock().unwrap();\n\n let test_db_name = \"foo\";\n\n let cmd = CmdCreateDatabase {\n\n db_name: test_db_name.to_string(),\n\n db: Some(Db {\n\n db_id: -1,\n\n ver: -1,\n\n table_name_to_id: HashMap::new(),\n\n tables: HashMap::new(),\n\n }),\n\n };\n\n let _ = eng.create_database(cmd.clone(), false).unwrap();\n\n let r = eng.drop_database(test_db_name, false);\n\n assert!(r.is_ok());\n\n\n\n // with flag \"IF EXISTS\"\n\n let r = eng.drop_database(test_db_name, true);\n\n assert!(r.is_ok());\n\n\n\n let r = eng.drop_database(test_db_name, false);\n\n assert!(r.is_err());\n\n assert_eq!(r.unwrap_err().code(), Code::NotFound);\n\n Ok(())\n\n}\n\n\n", "file_path": "fusestore/store/src/engine/mem_engine_test.rs", "rank": 43, "score": 141835.7274685452 }, { "content": "#[test]\n\nfn test_to_type_name_function() -> Result<()> {\n\n #[allow(dead_code)]\n\n struct Test {\n\n name: &'static str,\n\n display: &'static str,\n\n nullable: bool,\n\n arg_names: Vec<&'static str>,\n\n columns: Vec<DataColumnarValue>,\n\n expect: DataArrayRef,\n\n error: &'static str,\n\n func: Box<dyn IFunction>,\n\n }\n\n\n\n let schema = DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Boolean, false)]);\n\n\n\n let tests = vec![Test {\n\n name: \"to_type_name-example-passed\",\n\n display: \"toTypeName\",\n\n nullable: false,\n\n arg_names: vec![\"a\"],\n", "file_path": "common/functions/src/udfs/to_type_name_test.rs", "rank": 44, "score": 141576.46431595684 }, { "content": "SELECT number as c1, (number+1) as c2 FROM numbers_mt (3) where number+1>1;\n\nEXPLAIN SELECT number as c1, (number+1) as c2 FROM numbers_mt (3) where number >1;\n", "file_path": "tests/suites/0_stateless/03_0005_select_filter.sql", "rank": 45, "score": 139862.68322907877 }, { "content": "#[test]\n\nfn test_limit_plan() -> anyhow::Result<()> {\n\n use std::sync::Arc;\n\n\n\n use pretty_assertions::assert_eq;\n\n\n\n use crate::*;\n\n\n\n let limit = PlanNode::Limit(LimitPlan {\n\n n: 33,\n\n input: Arc::from(PlanBuilder::empty().build()?),\n\n });\n\n let expect = \"Limit: 33\";\n\n let actual = format!(\"{:?}\", limit);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_limit_test.rs", "rank": 46, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_expression_plan() -> anyhow::Result<()> {\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .filter(\n\n add(col(\"number\"), lit(1))\n\n .eq(lit(4))\n\n .and(col(\"number\").not_eq(lit(4)))\n\n .and(col(\"number\").lt(lit(4)))\n\n .and(col(\"number\").lt_eq(lit(4)))\n\n .and(col(\"number\").gt(lit(4)))\n\n .and(not(col(\"number\").gt_eq(lit(4)))),\n\n )?\n\n .build()?;\n\n let explain = PlanNode::Explain(ExplainPlan {\n\n typ: ExplainType::Syntax,\n\n input: Arc::new(plan),\n\n });\n\n let expect =\"Filter: (((((((number + 1) = 4) and (number != 4)) and (number < 4)) and (number <= 4)) and (number > 4)) and (not (number >= 4)))\\\n\n \\n ReadDataSource: scan partitions: [8], scan schema: [number:UInt64], statistics: [read_rows: 10000, read_bytes: 80000]\";\n\n let actual = format!(\"{:?}\", explain);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_test.rs", "rank": 47, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_projection_plan() -> anyhow::Result<()> {\n\n use std::sync::Arc;\n\n\n\n use common_datavalues::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n use crate::*;\n\n\n\n let schema = DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Utf8, false)]);\n\n\n\n let projection = PlanNode::Projection(ProjectionPlan {\n\n expr: vec![col(\"a\")],\n\n schema: DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Utf8, false)]),\n\n input: Arc::from(PlanBuilder::from(&PlanNode::Empty(EmptyPlan { schema })).build()?),\n\n });\n\n let _ = projection.schema();\n\n let expect = \"Projection: a:Utf8\";\n\n let actual = format!(\"{:?}\", projection);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_projection_test.rs", "rank": 48, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_scan_plan() -> anyhow::Result<()> {\n\n use common_datavalues::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n use crate::*;\n\n\n\n let scan = PlanNode::Scan(ScanPlan {\n\n schema_name: \"scan_test\".to_string(),\n\n table_schema: DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Utf8, false)]),\n\n table_args: None,\n\n projection: None,\n\n projected_schema: DataSchemaRefExt::create(vec![DataField::new(\n\n \"a\",\n\n DataType::Utf8,\n\n false,\n\n )]),\n\n filters: vec![],\n\n limit: None,\n\n });\n\n let _ = scan.schema();\n\n let expect = \"\";\n\n let actual = format!(\"{:?}\", scan);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_scan_test.rs", "rank": 49, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_explain_plan() -> anyhow::Result<()> {\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .project(&[col(\"number\").alias(\"c1\"), col(\"number\").alias(\"c2\")])?\n\n .filter(add(col(\"number\"), lit(1)).eq(lit(4)))?\n\n .having(add(col(\"number\"), lit(1)).eq(lit(4)))?\n\n .build()?;\n\n let explain = PlanNode::Explain(ExplainPlan {\n\n typ: ExplainType::Syntax,\n\n input: Arc::new(plan),\n\n });\n\n let expect =\"\\\n\n Having: ((number + 1) = 4)\\\n\n \\n Filter: ((number + 1) = 4)\\\n\n \\n Projection: number as c1:UInt64, number as c2:UInt64\\\n\n \\n ReadDataSource: scan partitions: [8], scan schema: [number:UInt64], statistics: [read_rows: 10000, read_bytes: 80000]\";\n\n let actual = format!(\"{:?}\", explain);\n\n assert_eq!(expect, actual);\n\n assert_eq!(explain.schema().fields().clone(), vec![DataField::new(\n\n \"explain\",\n\n DataType::Utf8,\n\n false\n\n )]);\n\n\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_explain_test.rs", "rank": 50, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_filter_plan() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .filter(col(\"number\").eq(lit(1i64)))?\n\n .project(&[col(\"number\")])?\n\n .build()?;\n\n\n\n let expect =\"\\\n\n Projection: number:UInt64\\\n\n \\n Filter: (number = 1)\\\n\n \\n ReadDataSource: scan partitions: [8], scan schema: [number:UInt64], statistics: [read_rows: 10000, read_bytes: 80000]\";\n\n let actual = format!(\"{:?}\", plan);\n\n\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_filter_test.rs", "rank": 51, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_aggregator_plan() -> anyhow::Result<()> {\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .aggregate_partial(&[sum(col(\"number\")).alias(\"sumx\")], &[])?\n\n .aggregate_final(source.schema(), &[sum(col(\"number\")).alias(\"sumx\")], &[])?\n\n .project(&[col(\"sumx\")])?\n\n .build()?;\n\n let explain = PlanNode::Explain(ExplainPlan {\n\n typ: ExplainType::Syntax,\n\n input: Arc::new(plan),\n\n });\n\n let expect = \"\\\n\n Projection: sumx:UInt64\\\n\n \\n AggregatorFinal: groupBy=[[]], aggr=[[sum(number) as sumx]]\\\n\n \\n AggregatorPartial: groupBy=[[]], aggr=[[sum(number) as sumx]]\\\n\n \\n ReadDataSource: scan partitions: [8], scan schema: [number:UInt64], statistics: [read_rows: 10000, read_bytes: 80000]\";\n\n let actual = format!(\"{:?}\", explain);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_aggregator_test.rs", "rank": 52, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_plan_builds() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n struct TestCase {\n\n name: &'static str,\n\n plan: Result<PlanNode>,\n\n expect: &'static str,\n\n err: &'static str,\n\n }\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let tests = vec![\n\n TestCase {\n\n name: \"field(*)-pass\",\n\n plan: (PlanBuilder::from(&source)\n\n .expression(&[Expression::Wildcard], \"\")?\n\n .project(&[col(\"number\")])?\n\n .build()),\n\n expect: \"\\\n\n Projection: number:UInt64\\\n", "file_path": "common/planners/src/plan_builder_test.rs", "rank": 53, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_plan_rewriter_1() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n use crate::*;\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .filter(col(\"number\").eq(lit(1i64)))?\n\n .aggregate_partial(&[col(\"number\")], &[col(\"number\")])?\n\n .aggregate_final(source.schema(), &[col(\"number\")], &[col(\"number\")])?\n\n .project(&[col(\"number\").alias(\"x\"), col(\"number\").alias(\"y\")])?\n\n .build()?;\n\n struct DefaultRewriter;\n\n impl<'plan> PlanRewriter<'plan> for DefaultRewriter {}\n\n\n\n // DefaultRewriter::rewrite_plan_node() should return a totally same plan as input\n\n let mut rewriter = DefaultRewriter {};\n\n let before_rewrite = format!(\"{:?}\", &plan);\n\n let after_rewrite = format!(\"{:?}\", rewriter.rewrite_plan_node(&plan)?);\n\n assert_eq!(before_rewrite, after_rewrite);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_rewriter_test.rs", "rank": 54, "score": 139299.4539491397 }, { "content": "#[test]\n\nfn test_expression_plan_format() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n let schema = DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Utf8, false)]);\n\n\n\n let expression = PlanNode::Expression(ExpressionPlan {\n\n exprs: vec![col(\"a\")],\n\n schema: schema.clone(),\n\n input: Arc::from(PlanBuilder::from(&PlanNode::Empty(EmptyPlan { schema })).build()?),\n\n desc: \"\".to_string(),\n\n });\n\n let _ = expression.schema();\n\n let expect = \"Expression: a:Utf8 ()\";\n\n let actual = format!(\"{:?}\", expression);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_test.rs", "rank": 55, "score": 137916.49117946494 }, { "content": "#[test]\n\nfn test_plan_parser() -> anyhow::Result<()> {\n\n struct Test {\n\n name: &'static str,\n\n sql: &'static str,\n\n expect: &'static str,\n\n error: &'static str,\n\n }\n\n\n\n let tests = vec![\n\n Test {\n\n name: \"create-database-passed\",\n\n sql: \"CREATE DATABASE db1\",\n\n expect: \"Create database db1, engine: Remote, if_not_exists:false, option: {}\",\n\n error: \"\",\n\n },\n\n Test {\n\n name: \"create-database-if-not-exists-passed\",\n\n sql: \"CREATE DATABASE IF NOT EXISTS db1\",\n\n expect: \"Create database db1, engine: Remote, if_not_exists:true, option: {}\",\n\n error: \"\",\n", "file_path": "fusequery/query/src/sql/plan_parser_test.rs", "rank": 56, "score": 137916.49117946494 }, { "content": "#[test]\n\nfn test_rewrite_expressions_plan() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .project(&[col(\"number\").alias(\"x\"), col(\"number\").alias(\"y\")])?\n\n .filter(col(\"x\").eq(lit(1i64)))?\n\n .build()?;\n\n\n\n let actual = RewriteHelper::projection_to_map(&plan)?;\n\n let mut expect = HashMap::new();\n\n expect.insert(\"x\".to_string(), col(\"number\"));\n\n expect.insert(\"y\".to_string(), col(\"number\"));\n\n assert_eq!(expect, actual);\n\n\n\n let exprs = vec![Expression::ScalarFunction {\n\n op: \"multiply\".to_string(),\n\n args: vec![col(\"x\"), col(\"y\")],\n\n }];\n\n\n\n let expect_plan = Expression::ScalarFunction {\n\n op: \"multiply\".to_string(),\n\n args: vec![col(\"number\"), col(\"number\")],\n\n };\n\n let actual_plan = RewriteHelper::rewrite_alias_exprs(&actual, &exprs)?;\n\n assert_eq!(expect_plan, actual_plan[0]);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "common/planners/src/plan_rewriter_test.rs", "rank": 57, "score": 137916.49117946494 }, { "content": "#[test]\n\nfn test_plan_display_indent() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n // TODO test other plan type\n\n let schema = DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Int64, false)]);\n\n\n\n let mut options = HashMap::new();\n\n options.insert(\"opt_foo\".to_string(), \"opt_bar\".to_string());\n\n\n\n let plan_create = PlanNode::CreateTable(CreateTablePlan {\n\n if_not_exists: true,\n\n db: \"foo\".into(),\n\n table: \"bar\".into(),\n\n schema,\n\n engine: TableEngineType::JsonEachRaw,\n\n options,\n\n });\n\n\n\n assert_eq!(\n\n \"Create table foo.bar Field { name: \\\"a\\\", data_type: Int64, nullable: false, dict_id: 0, dict_is_ordered: false, metadata: None }, engine: JSON, if_not_exists:true, option: {\\\"opt_foo\\\": \\\"opt_bar\\\"}\",\n\n format!(\"{}\", plan_create.display_indent())\n\n );\n\n\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_display_test.rs", "rank": 58, "score": 137916.49117946494 }, { "content": "#[test]\n\nfn test_select_wildcard_plan() -> anyhow::Result<()> {\n\n use std::sync::Arc;\n\n\n\n use common_datavalues::*;\n\n use pretty_assertions::assert_eq;\n\n\n\n use crate::*;\n\n\n\n let schema = DataSchemaRefExt::create(vec![DataField::new(\"a\", DataType::Utf8, false)]);\n\n let plan = PlanBuilder::create(schema).project(&[col(\"a\")])?.build()?;\n\n let select = PlanNode::Select(SelectPlan {\n\n input: Arc::new(plan),\n\n });\n\n let expect = \"Projection: a:Utf8\";\n\n\n\n let actual = format!(\"{:?}\", select);\n\n assert_eq!(expect, actual);\n\n Ok(())\n\n}\n", "file_path": "common/planners/src/plan_select_test.rs", "rank": 59, "score": 137916.49117946494 }, { "content": "fn build_boolean_column(values: &DataArrayRef) -> Result<Vec<Option<u8>>> {\n\n let values = as_boolean_array(values);\n\n\n\n Ok(match values.null_count() {\n\n //faster path\n\n 0 => (0..values.len())\n\n .map(|i| Some(values.value(i) as u8))\n\n .collect::<Vec<Option<u8>>>(),\n\n _ => (0..values.len())\n\n .map(|i| {\n\n if values.is_null(i) {\n\n None\n\n } else {\n\n Some(values.value(i) as u8)\n\n }\n\n })\n\n .collect::<Vec<Option<u8>>>(),\n\n })\n\n}\n\n\n", "file_path": "fusequery/query/src/servers/clickhouse/clickhouse_stream.rs", "rank": 60, "score": 137834.03357719415 }, { "content": "fn build_string_column(values: &DataArrayRef) -> Result<Vec<Option<&str>>> {\n\n let values = as_string_array(values);\n\n Ok(match values.null_count() {\n\n //faster path\n\n 0 => (0..values.len())\n\n .map(|i| Some(values.value(i)))\n\n .collect::<Vec<Option<&str>>>(),\n\n _ => (0..values.len())\n\n .map(|i| {\n\n if values.is_null(i) {\n\n None\n\n } else {\n\n Some(values.value(i))\n\n }\n\n })\n\n .collect::<Vec<Option<&str>>>(),\n\n })\n\n}\n", "file_path": "fusequery/query/src/servers/clickhouse/clickhouse_stream.rs", "rank": 61, "score": 137834.03357719415 }, { "content": "SELECT avg(number), max(number+1)+1 FROM numbers_mt(10000) where number > 2 GROUP BY 1;\n", "file_path": "tests/suites/0_stateless/03_0003_select_group_by.sql", "rank": 62, "score": 137634.37894923222 }, { "content": "fn read_file(\n\n file: &str,\n\n tx: Sender<Option<Result<DataBlock>>>,\n\n projection: &[usize],\n\n) -> Result<()> {\n\n let file_reader = File::open(file).map_err(|e| ErrorCodes::CannotReadFile(e.to_string()))?;\n\n let file_reader = SerializedFileReader::new(file_reader)\n\n .map_err(|e| ErrorCodes::ParquetError(e.to_string()))?;\n\n let mut arrow_reader = ParquetFileArrowReader::new(Arc::new(file_reader));\n\n\n\n // TODO projection, row filters, batch size configurable, schema judgement\n\n let batch_size = 2048;\n\n let mut batch_reader = arrow_reader\n\n .get_record_reader_by_columns(projection.to_owned(), batch_size)\n\n .map_err(|exception| ErrorCodes::ParquetError(exception.to_string()))?;\n\n\n\n loop {\n\n match batch_reader.next() {\n\n Some(Ok(batch)) => {\n\n tx.send(Some(Ok(batch.try_into()?)))\n", "file_path": "fusequery/query/src/datasources/local/parquet_table.rs", "rank": 63, "score": 137331.99096004464 }, { "content": "#[test]\n\nfn test_rewrite_projection_alias_plan() -> anyhow::Result<()> {\n\n use pretty_assertions::assert_eq;\n\n\n\n #[allow(dead_code)]\n\n struct RewriteTest {\n\n name: &'static str,\n\n exprs: Vec<Expression>,\n\n expect_str: &'static str,\n\n error_msg: &'static str,\n\n }\n\n\n\n let tests = vec![\n\n RewriteTest {\n\n name: \"Cyclic\",\n\n exprs: vec![\n\n Box::new(Expression::ScalarFunction {\n\n op: \"plus\".to_string(),\n\n args: vec![lit(1i32), col(\"z\")],\n\n })\n\n .alias(\"x\"),\n", "file_path": "common/planners/src/plan_rewriter_test.rs", "rank": 64, "score": 136571.24165552843 }, { "content": "pub fn init_tracing() {\n\n static START: Once = Once::new();\n\n\n\n START.call_once(|| {\n\n // init without span:\n\n // fmt::init();\n\n\n\n let fmt_layer = fmt::Layer::default()\n\n .with_span_events(fmt::format::FmtSpan::FULL)\n\n .with_ansi(false);\n\n\n\n let subscriber = Registry::default()\n\n .with(EnvFilter::from_default_env())\n\n .with(fmt_layer);\n\n\n\n tracing::subscriber::set_global_default(subscriber)\n\n .expect(\"error setting global tracing subscriber\");\n\n });\n\n}\n", "file_path": "fusestore/store/src/tests/logging.rs", "rank": 65, "score": 136222.3785143361 }, { "content": "SELECT number as c1, (number+1) as c2 FROM numbers_mt (3) where number >1;\n", "file_path": "tests/suites/0_stateless/03_0005_select_filter.sql", "rank": 66, "score": 135190.71992958538 }, { "content": "select 1 - number as number from numbers(3) order by number;\n", "file_path": "tests/suites/0_stateless/03_0000_select_aliases.sql", "rank": 67, "score": 131523.9440407948 }, { "content": "DROP DATABASE IF EXISTS db;\n\n\n", "file_path": "tests/suites/0_stateless/05_0001_ddl_drop_database.sql", "rank": 68, "score": 131067.3875312547 }, { "content": "SELECT toTypeName(CAST(number AS float)) FROM numbers_mt(10);\n\n\n", "file_path": "tests/suites/0_stateless/02_0002_function_cast.sql", "rank": 69, "score": 130670.75919660652 }, { "content": "pub fn rand_local_addr() -> String {\n\n let mut rng = rand::thread_rng();\n\n let port: u32 = rng.gen_range(10000..11000);\n\n let addr = format!(\"127.0.0.1:{}\", port);\n\n return addr;\n\n}\n\n\n\nmacro_rules! serve_grpc {\n\n ($addr:expr, $srv:expr) => {\n\n let addr = $addr.parse::<std::net::SocketAddr>()?;\n\n\n\n let srv = tonic::transport::Server::builder().add_service($srv);\n\n\n\n tokio::spawn(async move {\n\n srv.serve(addr)\n\n .await\n\n .map_err(|e| anyhow::anyhow!(\"Flight service error: {:?}\", e))?;\n\n Ok::<(), anyhow::Error>(())\n\n });\n\n\n\n tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;\n\n };\n\n}\n", "file_path": "fusestore/store/src/tests/service.rs", "rank": 70, "score": 130069.40558786815 }, { "content": "fn build_primitive_column<T>(values: &DataArrayRef) -> Result<Vec<Option<T::Native>>>\n\nwhere T: ArrowPrimitiveType {\n\n let values = as_primitive_array::<T>(values);\n\n\n\n Ok(match values.null_count() {\n\n //faster path\n\n 0 => (0..values.len())\n\n .map(|i| Some(values.value(i)))\n\n .collect::<Vec<Option<T::Native>>>(),\n\n _ => (0..values.len())\n\n .map(|i| {\n\n if values.is_null(i) {\n\n None\n\n } else {\n\n Some(values.value(i))\n\n }\n\n })\n\n .collect::<Vec<Option<T::Native>>>(),\n\n })\n\n}\n\n\n", "file_path": "fusequery/query/src/servers/clickhouse/clickhouse_stream.rs", "rank": 71, "score": 129857.43643276246 }, { "content": "pub fn get_sort_descriptions(\n\n schema: &DataSchemaRef,\n\n exprs: &[Expression],\n\n) -> Result<Vec<SortColumnDescription>> {\n\n let mut sort_columns_descriptions = vec![];\n\n for x in exprs {\n\n match *x {\n\n Expression::Sort {\n\n ref expr,\n\n asc,\n\n nulls_first,\n\n } => {\n\n let column_name = expr.to_data_field(schema)?.name().clone();\n\n sort_columns_descriptions.push(SortColumnDescription {\n\n column_name,\n\n asc,\n\n nulls_first,\n\n });\n\n }\n\n _ => {\n\n return Result::Err(ErrorCodes::BadTransformType(format!(\n\n \"Sort expression must be ExpressionPlan::Sort, but got: {:?}\",\n\n x\n\n )));\n\n }\n\n }\n\n }\n\n Ok(sort_columns_descriptions)\n\n}\n", "file_path": "fusequery/query/src/pipelines/transforms/transform_sort_partial.rs", "rank": 72, "score": 129574.49008507517 }, { "content": "#[test]\n\nfn test_expression_validate() -> anyhow::Result<()> {\n\n struct Test {\n\n desc: &'static str,\n\n expression: Expression,\n\n error: Option<ErrorCodes>,\n\n }\n\n\n\n let cases = vec![\n\n Test {\n\n desc: \"toTypeName-not-pass\",\n\n expression: Expression::ScalarFunction {\n\n op: \"toTypeName\".to_string(),\n\n args: vec![],\n\n },\n\n error: Some(ErrorCodes::NumberArgumentsNotMatch(\n\n \"ToTypeNameFunction expect to have 1 arguments, but got 0\",\n\n )),\n\n },\n\n Test {\n\n desc: \"example-not-pass\",\n", "file_path": "common/planners/src/plan_expression_test.rs", "rank": 73, "score": 127674.5305771827 }, { "content": "/// Not.\n\npub fn not(other: Expression) -> Expression {\n\n Expression::UnaryExpression {\n\n op: \"not\".to_string(),\n\n expr: Box::new(other),\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 74, "score": 126514.52359878714 }, { "content": "/// sum() aggregate function.\n\npub fn sum(other: Expression) -> Expression {\n\n Expression::AggregateFunction {\n\n op: \"sum\".to_string(),\n\n args: vec![other],\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 75, "score": 124857.06878533766 }, { "content": "/// avg() aggregate function.\n\npub fn avg(other: Expression) -> Expression {\n\n Expression::AggregateFunction {\n\n op: \"avg\".to_string(),\n\n args: vec![other],\n\n }\n\n}\n\n\n\nimpl Expression {\n\n /// And.\n\n pub fn and(&self, other: Expression) -> Expression {\n\n binary_expr(self.clone(), \"and\", other)\n\n }\n\n\n\n /// Equal.\n\n pub fn eq(&self, other: Expression) -> Expression {\n\n binary_expr(self.clone(), \"=\", other)\n\n }\n\n\n\n /// Not equal.\n\n pub fn not_eq(&self, other: Expression) -> Expression {\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 76, "score": 124857.06878533766 }, { "content": "SELECT max(number) FROM numbers_mt(0) GROUP BY number % 4;\n", "file_path": "tests/suites/0_stateless/03_0003_select_group_by.sql", "rank": 77, "score": 124180.17432616705 }, { "content": "fn is_local_impl(address: &IpAddr) -> Result<bool> {\n\n for network_interface in &pnet::datalink::interfaces() {\n\n for interface_ip in &network_interface.ips {\n\n if address == &interface_ip.ip() {\n\n return Ok(true);\n\n }\n\n }\n\n }\n\n\n\n Ok(false)\n\n}\n", "file_path": "fusequery/query/src/clusters/cluster.rs", "rank": 78, "score": 122473.33559529715 }, { "content": "// Can works before expression,filter,having in PlanBuilder\n\npub fn validate_expression(expr: &Expression) -> Result<()> {\n\n let validator = ExpressionValidator::new(&|expr: &Expression| match expr {\n\n Expression::ScalarFunction { op, args } => {\n\n let func = FunctionFactory::get(op)?;\n\n validate_function_arg(func, args)\n\n }\n\n\n\n // Currently no need to check UnaryExpression and BinaryExpression\n\n // todo: AggregateFunction validation after generic AggregateFunctions\n\n _ => Ok(()),\n\n });\n\n\n\n let validator = expr.accept(validator)?;\n\n match validator.error {\n\n Some(err) => Err(err),\n\n None => Ok(()),\n\n }\n\n}\n", "file_path": "common/planners/src/plan_expression_validator.rs", "rank": 79, "score": 121712.07279553302 }, { "content": "pub fn try_create_context() -> Result<FuseQueryContextRef> {\n\n let ctx = FuseQueryContext::try_create()?;\n\n\n\n ctx.set_max_threads(8)?;\n\n Ok(ctx)\n\n}\n", "file_path": "fusequery/query/src/tests/context.rs", "rank": 80, "score": 121464.72695734692 }, { "content": "#[test]\n\nfn test_plan_walker() -> std::result::Result<(), Box<dyn std::error::Error>> {\n\n use pretty_assertions::assert_eq;\n\n\n\n let source = Test::create().generate_source_plan_for_test(10000)?;\n\n let plan = PlanBuilder::from(&source)\n\n .aggregate_partial(&[sum(col(\"number\"))], &[])?\n\n .aggregate_final(source.schema(), &[sum(col(\"number\"))], &[])?\n\n .project(&[col(\"sum(number)\").alias(\"sumx\")])?\n\n .build()?;\n\n\n\n // PreOrder.\n\n {\n\n let mut actual: Vec<String> = vec![];\n\n for child in plan.inputs() {\n\n child.walk_preorder(|plan| -> Result<bool, Box<dyn std::error::Error>> {\n\n actual.push(plan.name().to_string());\n\n return Ok(true);\n\n })?;\n\n }\n\n\n", "file_path": "common/planners/src/plan_walker_test.rs", "rank": 81, "score": 121020.01064503458 }, { "content": "struct DefaultGetNodePlan(PlanNode, Arc<Box<dyn GetNodePlan>>);\n\n\n", "file_path": "fusequery/query/src/interpreters/plan_scheduler.rs", "rank": 82, "score": 119071.78714295044 }, { "content": "/// Assert with order sensitive.\n\n/// ['a', 'b'] not equals ['b', 'a']\n\npub fn assert_blocks_eq_with_name(test_name: &str, expect: Vec<&str>, blocks: &[DataBlock]) {\n\n let expected_lines: Vec<String> = expect.iter().map(|&s| s.into()).collect();\n\n let formatted = pretty_format_blocks(&blocks).unwrap();\n\n let actual_lines: Vec<&str> = formatted.trim().lines().collect();\n\n\n\n assert_eq!(\n\n expected_lines, actual_lines,\n\n \"{:#?}\\n\\nexpected:\\n\\n{:#?}\\nactual:\\n\\n{:#?}\\n\\n\",\n\n test_name, expected_lines, actual_lines\n\n );\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 83, "score": 118414.11142593034 }, { "content": "pub fn lit<T: ILiteral>(n: T) -> Expression {\n\n n.to_literal()\n\n}\n", "file_path": "common/planners/src/plan_expression_literal.rs", "rank": 84, "score": 118306.14486643075 }, { "content": "fn create_dispatcher() -> Result<(FlightDispatcher, Sender<Request>)> {\n\n let conf = Config::default();\n\n let sessions = SessionManager::create();\n\n let cluster = Cluster::create_global(conf.clone())?;\n\n let dispatcher = FlightDispatcher::new(conf, cluster, sessions);\n\n let sender = dispatcher.run();\n\n Ok((dispatcher, sender))\n\n}\n\n\n", "file_path": "fusequery/query/src/api/rpc/flight_dispatcher_test.rs", "rank": 85, "score": 117993.921493916 }, { "content": "select 1, sum(number) from numbers_mt(1000000);\n\n-- SELECT min(sum(number)) FROM numbers(10);", "file_path": "tests/suites/0_stateless/03_0001_select_aggregator.sql", "rank": 86, "score": 117825.80124146643 }, { "content": "/// Assert with order insensitive.\n\n/// ['a', 'b'] equals ['b', 'a']\n\npub fn assert_blocks_sorted_eq_with_name(test_name: &str, expect: Vec<&str>, blocks: &[DataBlock]) {\n\n let mut expected_lines: Vec<String> = expect.iter().map(|&s| s.into()).collect();\n\n\n\n // sort except for header + footer\n\n let num_lines = expected_lines.len();\n\n if num_lines > 3 {\n\n expected_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()\n\n }\n\n\n\n let formatted = pretty_format_blocks(&blocks).unwrap();\n\n let mut actual_lines: Vec<&str> = formatted.trim().lines().collect();\n\n\n\n // sort except for header + footer\n\n let num_lines = actual_lines.len();\n\n if num_lines > 3 {\n\n actual_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()\n\n }\n\n\n\n assert_eq!(\n\n expected_lines, actual_lines,\n\n \"{:#?}\\n\\nexpected:\\n\\n{:#?}\\nactual:\\n\\n{:#?}\\n\\n\",\n\n test_name, expected_lines, actual_lines\n\n );\n\n}\n\n\n", "file_path": "common/datablocks/src/data_block_debug.rs", "rank": 87, "score": 117312.17188484588 }, { "content": "/// Mod binary function.\n\npub fn modular(left: Expression, right: Expression) -> Expression {\n\n binary_expr(left, \"%\", right)\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 88, "score": 116807.63016948075 }, { "content": "/// Add binary function.\n\npub fn add(left: Expression, right: Expression) -> Expression {\n\n binary_expr(left, \"+\", right)\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 89, "score": 116807.63016948075 }, { "content": "struct ReadSourceGetNodePlan(Arc<Box<dyn GetNodePlan>>);\n\n\n\nimpl GetNodePlan for DefaultGetNodePlan {\n\n fn get_plan(&self, node_name: &str, cluster_nodes: &[Arc<Node>]) -> Result<PlanNode> {\n\n let mut clone_node = self.0.clone();\n\n clone_node.set_inputs(vec![&self.1.get_plan(node_name, cluster_nodes)?])?;\n\n Ok(clone_node)\n\n }\n\n}\n\n\n\nimpl GetNodePlan for EmptyGetNodePlan {\n\n fn get_plan(&self, _node_name: &str, _cluster_nodes: &[Arc<Node>]) -> Result<PlanNode> {\n\n Ok(PlanNode::Empty(EmptyPlan {\n\n schema: Arc::new(DataSchema::empty()),\n\n }))\n\n }\n\n}\n\n\n\nimpl RemoteGetNodePlan {\n\n pub fn create(\n", "file_path": "fusequery/query/src/interpreters/plan_scheduler.rs", "rank": 90, "score": 116500.04867822258 }, { "content": "struct LocalReadSourceGetNodePlan(ReadDataSourcePlan, Arc<Box<dyn GetNodePlan>>);\n\n\n", "file_path": "fusequery/query/src/interpreters/plan_scheduler.rs", "rank": 91, "score": 115560.08248791027 }, { "content": "/// return a new expression l <op> r.\n\nfn binary_expr(l: Expression, op: &str, r: Expression) -> Expression {\n\n Expression::BinaryExpression {\n\n op: op.to_string(),\n\n left: Box::new(l),\n\n right: Box::new(r),\n\n }\n\n}\n\n\n", "file_path": "common/planners/src/plan_expression_function.rs", "rank": 92, "score": 115391.12450747009 }, { "content": "pub fn get_do_put_meta(meta: &MetadataMap) -> anyhow::Result<(String, String)> {\n\n fn fetch_string(\n\n meta: &MetadataMap,\n\n key: &str,\n\n error_msg: &'static str,\n\n ) -> anyhow::Result<String> {\n\n meta.get_bin(key)\n\n .and_then(|v| v.to_bytes().ok())\n\n .and_then(|b| String::from_utf8(b.to_vec()).ok())\n\n .ok_or_else(|| anyhow::anyhow!(error_msg))\n\n }\n\n let db_name = fetch_string(meta, META_KEY_DB_NAME, \"invalid db_name meta data\")?;\n\n let tbl_name = fetch_string(meta, META_KEY_TBL_NAME, \"invalid tbl_name meta data\")?;\n\n Ok((db_name, tbl_name))\n\n}\n", "file_path": "common/flights/src/store_do_put.rs", "rank": 93, "score": 111827.39740644471 }, { "content": "fn validate_function_arg(func: Box<dyn IFunction>, args: &[Expression]) -> Result<()> {\n\n match func.variadic_arguments() {\n\n Some((start, end)) => {\n\n return if args.len() < start || args.len() > end {\n\n Err(ErrorCodes::NumberArgumentsNotMatch(format!(\n\n \"{} expect to have [{}, {}) arguments, but got {}\",\n\n func.name(),\n\n start,\n\n end,\n\n args.len()\n\n )))\n\n } else {\n\n Ok(())\n\n };\n\n }\n\n None => {\n\n let num = func.num_arguments();\n\n return if num != args.len() {\n\n Err(ErrorCodes::NumberArgumentsNotMatch(format!(\n\n \"{} expect to have {} arguments, but got {}\",\n", "file_path": "common/planners/src/plan_expression_validator.rs", "rank": 94, "score": 111168.55824812193 }, { "content": "DROP TABLE IF EXISTS t;\n", "file_path": "tests/suites/0_stateless/05_0000_ddl_drop_tables.sql", "rank": 95, "score": 110696.37797932912 }, { "content": "DROP TABLE t1;\n\n\n", "file_path": "tests/suites/0_stateless/09_0000_remote_create_table.sql", "rank": 96, "score": 110610.50094432318 } ]
Rust
vrp-scientific/src/solomon/reader.rs
andrewgy8/vrp
c94574ad555c6ca06480f678f52850caf9aa71cb
#[cfg(test)] #[path = "../../tests/unit/solomon/reader_test.rs"] mod reader_test; use crate::common::*; use crate::utils::MatrixFactory; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::models::common::{TimeSpan, TimeWindow}; use vrp_core::models::problem::*; use vrp_core::models::Problem; use vrp_core::utils::TryCollect; pub fn read_solomon_format<R: Read>(reader: BufReader<R>) -> Result<Problem, String> { SolomonReader { buffer: String::new(), reader, matrix: MatrixFactory::default() }.read_problem() } pub trait SolomonProblem { fn read_solomon(self) -> Result<Problem, String>; } impl<R: Read> SolomonProblem for BufReader<R> { fn read_solomon(self) -> Result<Problem, String> { read_solomon_format(self) } } impl SolomonProblem for String { fn read_solomon(self) -> Result<Problem, String> { read_solomon_format(BufReader::new(self.as_bytes())) } } struct VehicleLine { number: usize, capacity: usize, } struct JobLine { id: usize, location: (i32, i32), demand: usize, tw: TimeWindow, service: usize, } struct SolomonReader<R: Read> { buffer: String, reader: BufReader<R>, matrix: MatrixFactory, } impl<R: Read> TextReader for SolomonReader<R> { fn read_fleet(&mut self) -> Result<Fleet, String> { self.skip_lines(4)?; let vehicle = self.read_vehicle()?; self.skip_lines(4)?; let depot = self.read_customer()?; Ok(create_fleet_with_distance_costs( vehicle.number, vehicle.capacity, self.matrix.collect(depot.location), depot.tw.clone(), )) } fn read_jobs(&mut self) -> Result<Vec<Job>, String> { let mut jobs: Vec<Job> = Default::default(); loop { match self.read_customer() { Ok(customer) => { let mut dimens = create_dimens_with_id("", customer.id); dimens.set_demand(Demand::<i32> { pickup: (0, 0), delivery: (customer.demand as i32, 0) }); jobs.push(Job::Single(Arc::new(Single { places: vec![Place { location: Some(self.matrix.collect(customer.location)), duration: customer.service as f64, times: vec![TimeSpan::Window(customer.tw.clone())], }], dimens, }))); } Err(error) => { if self.buffer.is_empty() { break; } else { return Err(error); } } } } Ok(jobs) } fn create_transport(&self) -> Result<Arc<dyn TransportCost + Send + Sync>, String> { self.matrix.create_transport() } } impl<R: Read> SolomonReader<R> { fn read_vehicle(&mut self) -> Result<VehicleLine, String> { read_line(&mut self.reader, &mut self.buffer)?; let (number, capacity) = self .buffer .split_whitespace() .map(|line| line.parse::<usize>().unwrap()) .try_collect() .ok_or_else(|| "Cannot parse vehicle number or/and capacity".to_string())?; Ok(VehicleLine { number, capacity }) } fn read_customer(&mut self) -> Result<JobLine, String> { read_line(&mut self.reader, &mut self.buffer)?; let (id, x, y, demand, start, end, service) = self .buffer .split_whitespace() .map(|line| line.parse::<i32>().unwrap()) .try_collect() .ok_or_else(|| "Cannot read customer line".to_string())?; Ok(JobLine { id: id as usize, location: (x, y), demand: demand as usize, tw: TimeWindow::new(start as f64, end as f64), service: service as usize, }) } fn skip_lines(&mut self, count: usize) -> Result<(), String> { for _ in 0..count { read_line(&mut self.reader, &mut self.buffer).map_err(|_| "Cannot skip lines")?; } Ok(()) } }
#[cfg(test)] #[path = "../../tests/unit/solomon/reader_test.rs"] mod reader_test; use crate::common::*; use crate::utils::MatrixFactory; use std::io::{BufReader, Read}; use std::sync::Arc; use vrp_core::construction::constraints::*; use vrp_core::models::common::{TimeSpan, TimeWindow}; use vrp_core::models::problem::*; use vrp_core::models::Problem; use vrp_core::utils::TryCollect; pub fn read_solomon_format<R: Read>(reader: BufReader<R>) -> Result<Problem, String> { SolomonReader { buffer: String::new(), reader, matrix: MatrixFactory::default() }.read_problem() } pub trait SolomonProblem { fn read_solomon(self) -> Result<Problem, String>; } impl<R: Read> SolomonProblem for BufReader<R> { fn read_solomon(self) -> Result<Problem, String> { read_solomon_format(self) } } impl SolomonProblem for String { fn read_solomon(self) -> Result<Problem, String> { read_solomon_format(BufReader::new(self.as_bytes())) } } struct VehicleLine { number: usize, capacity: usize, } struct JobLine { id: usize, location: (i32, i32), demand: usize, tw: TimeWindow, service: usize, } struct SolomonReader<R: Read> { buffer: String, reader: BufReader<R>, matrix: MatrixFactory, } impl<R: Read> TextReader for SolomonReader<R> { fn read_fleet(&mut self) -> Result<Fleet, String> { self.skip_lines(4)?; let vehicle = self.read_vehicle()?; self.skip_lines(4)?; let depot = self.read_customer()?; Ok(create_fleet_with_distance_costs( vehicle.number, vehicle.capacity, self.matrix.collect(depot.location), depot.tw.clone(), )) } fn read_jobs(&mut self) -> Result<Vec<Job>, String> { let mut jobs: Vec<Job> = Default::default(); loop { match self.read_customer() { Ok(customer) => { let mut dimens = create_dimens_with_id("", customer.id); dimens.set_demand(Demand::<i32> { pickup: (0, 0), delivery: (customer.demand as i32, 0) }); jobs.push(Job::Single(Arc::new(Single { places: vec![Place { location: Some(self.matrix.collect(customer.location)), duration: customer.service as f64, times: vec![TimeSpan::Window(customer.tw.clone())], }], dimens, }))); } Err(error) => { if self.buffer.is_empty() { break; } else { return Err(error); } } } } Ok(jobs) } fn create_transport(&self) -> Result<Arc<dyn TransportCost + Send + Sync>, String> { self.matrix.create_transport() } } impl<R: Read> SolomonReader<R> { fn read_vehicle(&mut self) -> Result<VehicleLine, String> { read_line(&mut self.reader, &mut self.buffer)?; let (number, capacity) = self .buffer .split_whitespace() .map(|line| line.parse::<usize>().unwrap()) .try_collect() .ok_or_else(|| "Cannot parse vehicle number or/and capacity".to_string())?; Ok(VehicleLine { number, capacity }) } fn read_customer(&mut self) -> Result<JobLine, String> { read_line(&mut self.reader, &mut self.buffer)?; let (id, x, y, demand, start, end, service) = self .buffer .split_whitespace() .map(|line| line.parse::<i32>().unwrap()) .try_collect() .ok_or_else(|| "Cannot read customer line".to_string())?; Ok(JobLine { id: id as usize, location: (x, y), demand: demand as usize, tw: TimeWindow::new(start as f64, end as f64), service: service as usize, }) } fn skip_lines(&mut self, count: usize) -> Result<(), String> {
}
for _ in 0..count { read_line(&mut self.reader, &mut self.buffer).map_err(|_| "Cannot skip lines")?; } Ok(()) }
function_block-function_prefix_line
[ { "content": "pub fn read_line<R: Read>(reader: &mut BufReader<R>, mut buffer: &mut String) -> Result<usize, String> {\n\n buffer.clear();\n\n reader.read_line(&mut buffer).map_err(|err| err.to_string())\n\n}\n", "file_path": "vrp-scientific/src/common/text_reader.rs", "rank": 0, "score": 646762.6952845149 }, { "content": "pub fn create_delivery_job_with_times(id: &str, location: Vec<f64>, times: Vec<(i32, i32)>, duration: f64) -> Job {\n\n Job {\n\n deliveries: Some(vec![JobTask {\n\n places: vec![JobPlace { duration, times: convert_times(&times), ..create_job_place(location) }],\n\n demand: Some(vec![1]),\n\n tag: None,\n\n }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 1, "score": 623139.1858293874 }, { "content": "pub fn create_pickup_job_with_demand(id: &str, location: Vec<f64>, demand: Vec<i32>) -> Job {\n\n Job { pickups: Some(vec![JobTask { demand: Some(demand), ..create_task(location) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 2, "score": 596286.1550923266 }, { "content": "pub fn create_delivery_job_with_demand(id: &str, location: Vec<f64>, demand: Vec<i32>) -> Job {\n\n Job { deliveries: Some(vec![JobTask { demand: Some(demand), ..create_task(location) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 3, "score": 596274.4227853883 }, { "content": "pub fn create_pickup_delivery_job(id: &str, pickup_location: Vec<f64>, delivery_location: Vec<f64>) -> Job {\n\n Job {\n\n pickups: Some(vec![create_task(pickup_location.clone())]),\n\n deliveries: Some(vec![create_task(delivery_location.clone())]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 4, "score": 533562.8180133296 }, { "content": "pub fn create_delivery_job_with_duration(id: &str, location: Vec<f64>, duration: f64) -> Job {\n\n Job {\n\n deliveries: Some(vec![JobTask {\n\n places: vec![JobPlace { duration, ..create_job_place(location) }],\n\n demand: Some(vec![1]),\n\n tag: None,\n\n }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 5, "score": 526381.0653070749 }, { "content": "pub fn create_delivery_job_with_priority(id: &str, location: Vec<f64>, priority: i32) -> Job {\n\n Job { priority: Some(priority), ..create_delivery_job(id, location) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 6, "score": 522670.2621228337 }, { "content": "pub fn create_delivery_job_with_skills(id: &str, location: Vec<f64>, skills: Vec<String>) -> Job {\n\n Job { skills: Some(skills), ..create_delivery_job(id, location) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 7, "score": 511813.5305890597 }, { "content": "pub fn create_fleet_with_distance_costs(number: usize, capacity: usize, location: Location, time: TimeWindow) -> Fleet {\n\n Fleet::new(\n\n vec![Arc::new(Driver {\n\n costs: Costs {\n\n fixed: 0.0,\n\n per_distance: 0.0,\n\n per_driving_time: 0.0,\n\n per_waiting_time: 0.0,\n\n per_service_time: 0.0,\n\n },\n\n dimens: create_dimens_with_id(\"driver\", 0),\n\n details: Default::default(),\n\n })],\n\n (0..number)\n\n .map(|i| {\n\n let mut dimens = create_dimens_with_id(\"v\", i);\n\n dimens.set_capacity(capacity as i32);\n\n Arc::new(Vehicle {\n\n profile: 0,\n\n costs: Costs {\n", "file_path": "vrp-scientific/src/common/text_reader.rs", "rank": 8, "score": 499148.48357160465 }, { "content": "pub fn create_default_vehicle_shift_with_locations(start: (f64, f64), end: (f64, f64)) -> VehicleShift {\n\n VehicleShift {\n\n start: VehiclePlace { time: format_time(0.), location: vec![start.0, start.1].to_loc() },\n\n end: Some(VehiclePlace { time: format_time(1000.).to_string(), location: vec![end.0, end.1].to_loc() }),\n\n breaks: None,\n\n reloads: None,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 9, "score": 493077.2054294586 }, { "content": "pub fn single_demand_as_multi(pickup: (i32, i32), delivery: (i32, i32)) -> Demand<MultiDimensionalCapacity> {\n\n let make = |value| {\n\n if value == 0 {\n\n MultiDimensionalCapacity::default()\n\n } else {\n\n MultiDimensionalCapacity::new(vec![value])\n\n }\n\n };\n\n\n\n Demand { pickup: (make(pickup.0), make(pickup.1)), delivery: (make(delivery.0), make(delivery.1)) }\n\n}\n", "file_path": "vrp-pragmatic/tests/helpers/core.rs", "rank": 10, "score": 488600.92056102736 }, { "content": "pub fn read_init_solution<R: Read>(mut reader: BufReader<R>, problem: Arc<Problem>) -> Result<Solution, String> {\n\n let mut buffer = String::new();\n\n\n\n let mut solution = Solution {\n\n registry: Registry::new(&problem.fleet),\n\n routes: vec![],\n\n unassigned: Default::default(),\n\n extras: problem.extras.clone(),\n\n };\n\n\n\n loop {\n\n match read_line(&mut reader, &mut buffer) {\n\n Ok(read) if read > 0 => {\n\n let route: Vec<_> = buffer.split(':').collect();\n\n assert_eq!(route.len(), 2);\n\n let id_map = problem.jobs.all().fold(HashMap::<String, Arc<Single>>::new(), |mut acc, job| {\n\n let single = job.to_single().clone();\n\n acc.insert(single.dimens.get_id().unwrap().to_string(), single);\n\n acc\n\n });\n", "file_path": "vrp-scientific/src/common/text_reader.rs", "rank": 11, "score": 486986.86215816555 }, { "content": "fn create_condition(vehicle_id: String, shift_index: usize) -> Arc<dyn Fn(&Actor) -> bool + Sync + Send> {\n\n Arc::new(move |actor: &Actor| {\n\n *actor.vehicle.dimens.get_id().unwrap() == vehicle_id\n\n && *actor.vehicle.dimens.get_value::<usize>(\"shift_index\").unwrap() == shift_index\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 12, "score": 485403.1035355856 }, { "content": "pub fn get_time_window(start: &String, end: &String) -> Option<TimeWindow> {\n\n let start = parse_time_safe(start);\n\n let end = parse_time_safe(end);\n\n\n\n if let (Some(start), Some(end)) = (start.ok(), end.ok()) {\n\n Some(TimeWindow::new(start, end))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/validation/common.rs", "rank": 13, "score": 482316.55071054905 }, { "content": "/// Creates time agnostic or time aware routing costs based on matrix data passed.\n\npub fn create_matrix_transport_cost(costs: Vec<MatrixData>) -> Result<Arc<dyn TransportCost + Send + Sync>, String> {\n\n if costs.is_empty() {\n\n return Err(\"No matrix data found\".to_string());\n\n }\n\n\n\n let size = (costs.first().unwrap().durations.len() as f64).sqrt() as usize;\n\n\n\n if costs.iter().any(|matrix| matrix.distances.len() != matrix.durations.len()) {\n\n return Err(\"Distance and duration collections have different length\".to_string());\n\n }\n\n\n\n if costs.iter().any(|matrix| (matrix.distances.len() as f64).sqrt() as usize != size) {\n\n return Err(\"Distance lengths don't match\".to_string());\n\n }\n\n\n\n if costs.iter().any(|matrix| (matrix.durations.len() as f64).sqrt() as usize != size) {\n\n return Err(\"Duration lengths don't match\".to_string());\n\n }\n\n\n\n Ok(if costs.iter().any(|costs| costs.timestamp.is_some()) {\n\n Arc::new(TimeAwareMatrixTransportCost::new(costs, size)?)\n\n } else {\n\n Arc::new(TimeAgnosticMatrixTransportCost::new(costs, size)?)\n\n })\n\n}\n\n\n", "file_path": "vrp-core/src/models/problem/costs.rs", "rank": 14, "score": 480798.61508981884 }, { "content": "pub fn create_service_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { services: Some(vec![JobTask { demand: None, ..create_task(location.clone()) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 15, "score": 472349.7247224296 }, { "content": "pub fn create_pickup_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { pickups: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 16, "score": 472321.84984758415 }, { "content": "pub fn create_delivery_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { deliveries: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 17, "score": 472309.4498765387 }, { "content": "/// Deserializes routing matrix in json format from [`BufReader`].\n\npub fn deserialize_matrix<R: Read>(reader: BufReader<R>) -> Result<Matrix, Vec<FormatError>> {\n\n serde_json::from_reader(reader).map_err(|err| {\n\n vec![FormatError::new(\n\n \"E0001\".to_string(),\n\n \"cannot deserialize matrix\".to_string(),\n\n format!(\"check input json: '{}'\", err),\n\n )]\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/model.rs", "rank": 19, "score": 439022.3410878606 }, { "content": "pub fn get_customer_id(job: &Job) -> String {\n\n get_job_id(job).to_owned()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 20, "score": 431445.09358641226 }, { "content": "fn can_check_breaks_impl(break_times: VehicleBreakTime, expected_result: Result<(), String>) {\n\n let problem = Problem {\n\n plan: Plan {\n\n jobs: vec![create_delivery_job(\"job1\", vec![1., 0.]), create_delivery_job(\"job2\", vec![2., 0.])],\n\n relations: None,\n\n },\n\n fleet: Fleet {\n\n vehicles: vec![VehicleType {\n\n shifts: vec![VehicleShift {\n\n start: VehiclePlace { time: format_time(0.), location: vec![0., 0.].to_loc() },\n\n end: Some(VehiclePlace { time: format_time(1000.).to_string(), location: vec![0., 0.].to_loc() }),\n\n breaks: Some(vec![VehicleBreak { time: break_times, duration: 0.0, locations: None }]),\n\n reloads: None,\n\n }],\n\n capacity: vec![5],\n\n ..create_default_vehicle_type()\n\n }],\n\n profiles: create_default_profiles(),\n\n },\n\n ..create_empty_problem()\n", "file_path": "vrp-pragmatic/tests/unit/checker/breaks_test.rs", "rank": 21, "score": 428422.69512528466 }, { "content": "pub fn create_replacement_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { replacements: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 22, "score": 428336.7112461964 }, { "content": "pub fn get_job_simple_demand(job: &Job) -> &Demand<i32> {\n\n match job {\n\n Job::Single(single) => &single.dimens,\n\n Job::Multi(multi) => &multi.dimens,\n\n }\n\n .get_demand()\n\n .unwrap()\n\n}\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 23, "score": 427639.0029470508 }, { "content": "pub fn get_customer_id(job: &Job) -> String {\n\n job.dimens().get_id().unwrap().clone()\n\n}\n", "file_path": "vrp-core/tests/helpers/models/domain.rs", "rank": 24, "score": 427622.24371013884 }, { "content": "fn get_break_time_window(tour: &Tour, vehicle_break: &VehicleBreak) -> Result<TimeWindow, String> {\n\n match &vehicle_break.time {\n\n VehicleBreakTime::TimeWindow(tw) => Ok(parse_time_window(tw)),\n\n VehicleBreakTime::TimeOffset(offset) => {\n\n if offset.len() != 2 {\n\n return Err(format!(\"Invalid offset break for tour: '{}'\", tour.vehicle_id));\n\n }\n\n\n\n let departure = tour\n\n .stops\n\n .first()\n\n .map(|stop| parse_time(&stop.time.departure))\n\n .ok_or_else(|| format!(\"Cannot get departure time for tour: '{}'\", tour.vehicle_id))?;\n\n Ok(TimeWindow::new(departure + *offset.first().unwrap(), departure + *offset.last().unwrap()))\n\n }\n\n }\n\n}\n", "file_path": "vrp-pragmatic/src/checker/breaks.rs", "rank": 25, "score": 416674.1418541932 }, { "content": "pub fn import_problem<R: Read>(input_format: &str, readers: Option<Vec<BufReader<R>>>) -> Result<Problem, String> {\n\n match (input_format, readers) {\n\n (\"csv\", Some(mut readers)) if readers.len() == 2 => {\n\n let jobs = readers.swap_remove(0);\n\n let vehicles = readers.swap_remove(0);\n\n read_csv_problem(jobs, vehicles).map_err(|err| format!(\"cannot read csv: {}\", err))\n\n }\n\n (\"csv\", _) => Err(\"csv format expects two files with jobs and vehicles as an input\".to_string()),\n\n (\"hre\", Some(mut readers)) if readers.len() == 1 => {\n\n let problem = readers.swap_remove(0);\n\n read_hre_problem(problem).map_err(|err| format!(\"cannot read problem from hre json: '{}'\", err))\n\n }\n\n (\"hre\", _) => Err(\"hre format expects one input file\".to_string()),\n\n _ => Err(format!(\"unknown format: '{}'\", input_format)),\n\n }\n\n}\n", "file_path": "vrp-cli/src/extensions/import/mod.rs", "rank": 26, "score": 413182.17217953654 }, { "content": "fn get_single_job(id: &String, single: Single, priority: &Option<i32>, skills: &Option<Vec<String>>) -> Job {\n\n let mut single = single;\n\n single.dimens.set_id(id.as_str());\n\n\n\n add_priority(&mut single.dimens, priority);\n\n add_skills(&mut single.dimens, skills);\n\n\n\n Job::Single(Arc::new(single))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 27, "score": 411622.8340641039 }, { "content": "fn parse_time_safe(time: &String) -> Result<f64, ParseError> {\n\n DateTime::parse_from_rfc3339(time).map(|time| time.timestamp() as f64)\n\n}\n", "file_path": "vrp-pragmatic/src/lib.rs", "rank": 28, "score": 406357.68621499557 }, { "content": "pub fn get_sorted_customer_ids_from_jobs(jobs: &[Job]) -> Vec<String> {\n\n let mut ids = jobs.iter().map(|job| get_customer_id(&job)).collect::<Vec<String>>();\n\n ids.sort();\n\n ids\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/domain.rs", "rank": 29, "score": 406259.6735399297 }, { "content": "pub fn create_vehicle_with_capacity(id: &str, capacity: Vec<i32>) -> VehicleType {\n\n VehicleType {\n\n type_id: id.to_string(),\n\n vehicle_ids: vec![format!(\"{}_1\", id)],\n\n profile: \"car\".to_string(),\n\n costs: create_default_vehicle_costs(),\n\n shifts: vec![create_default_vehicle_shift()],\n\n capacity,\n\n skills: None,\n\n limits: None,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 30, "score": 403952.3253138823 }, { "content": "pub fn create_dimens_with_id(prefix: &str, id: usize) -> Dimensions {\n\n let mut dimens = Dimensions::new();\n\n dimens.set_id([prefix.to_string(), id.to_string()].concat().as_str());\n\n dimens\n\n}\n\n\n", "file_path": "vrp-scientific/src/common/text_reader.rs", "rank": 31, "score": 401030.00067152234 }, { "content": "pub fn default_pickup_delivery_prototype() -> impl Strategy<Value = Job> {\n\n pickup_delivery_prototype(\n\n default_job_place_prototype(),\n\n default_job_place_prototype(),\n\n generate_simple_demand(1..4),\n\n generate_no_priority(),\n\n generate_no_skills(),\n\n )\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 32, "score": 397467.6707514212 }, { "content": "/// Checks that vehicle load is assigned correctly. The following rules are checked:\n\n/// * max vehicle's capacity is not violated\n\n/// * load change is correct\n\npub fn check_vehicle_load(context: &CheckerContext) -> Result<(), String> {\n\n context.solution.tours.iter().try_for_each(|tour| {\n\n let capacity = Capacity::new(context.get_vehicle(tour.vehicle_id.as_str())?.capacity.clone());\n\n\n\n let legs = (0_usize..)\n\n .zip(tour.stops.windows(2))\n\n .map(|(idx, leg)| {\n\n (\n\n idx,\n\n match leg {\n\n [from, to] => (from, to),\n\n _ => panic!(\"Unexpected leg configuration\"),\n\n },\n\n )\n\n })\n\n .collect::<Vec<_>>();\n\n let intervals: Vec<Vec<(usize, (&Stop, &Stop))>> = legs\n\n .iter()\n\n .fold(Vec::<(usize, usize)>::default(), |mut acc, (idx, (_, to))| {\n\n let last_idx = legs.len() - 1;\n", "file_path": "vrp-pragmatic/src/checker/capacity.rs", "rank": 33, "score": 397099.2709594095 }, { "content": "pub fn get_job_id(job: &Job) -> &String {\n\n job.dimens().get_id().unwrap()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 34, "score": 390387.3238179713 }, { "content": "fn add_conditional_job(job_index: &mut JobIndex, jobs: &mut Vec<Job>, job_id: String, single: Single) {\n\n let job = Job::Single(Arc::new(single));\n\n job_index.insert(job_id, job.clone());\n\n jobs.push(job);\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 35, "score": 390287.4404488721 }, { "content": "/// Get time windows.\n\npub fn get_time_window_from_vec(tw: &Vec<String>) -> Option<TimeWindow> {\n\n if tw.len() != 2 {\n\n None\n\n } else {\n\n get_time_window(tw.first().unwrap(), tw.last().unwrap())\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/validation/common.rs", "rank": 36, "score": 388864.981554862 }, { "content": "fn can_check_load_impl(stop_loads: Vec<i32>, expected_result: Result<(), String>) {\n\n let problem = Problem {\n\n plan: Plan {\n\n jobs: vec![\n\n create_delivery_job(\"job1\", vec![1., 0.]),\n\n create_delivery_job(\"job2\", vec![2., 0.]),\n\n create_delivery_job(\"job3\", vec![3., 0.]),\n\n create_pickup_job(\"job4\", vec![4., 0.]),\n\n create_pickup_delivery_job(\"job5\", vec![1., 0.], vec![5., 0.]),\n\n ],\n\n relations: None,\n\n },\n\n fleet: Fleet {\n\n vehicles: vec![VehicleType {\n\n shifts: vec![VehicleShift {\n\n start: VehiclePlace { time: format_time(0.), location: vec![0., 0.].to_loc() },\n\n end: Some(VehiclePlace { time: format_time(1000.).to_string(), location: vec![0., 0.].to_loc() }),\n\n breaks: None,\n\n reloads: Some(vec![VehicleReload {\n\n times: None,\n", "file_path": "vrp-pragmatic/tests/unit/checker/capacity_test.rs", "rank": 37, "score": 388845.98427278234 }, { "content": "pub fn get_job_id(job: &Job) -> &String {\n\n job.dimens().get_id().unwrap()\n\n}\n\n\n\npub struct SingleBuilder {\n\n single: Single,\n\n}\n\n\n\nimpl Default for SingleBuilder {\n\n fn default() -> Self {\n\n Self { single: test_single() }\n\n }\n\n}\n\n\n\nimpl SingleBuilder {\n\n pub fn id(&mut self, id: &str) -> &mut Self {\n\n self.single.dimens.set_value(\"id\", id.to_string());\n\n self\n\n }\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 38, "score": 387323.6062846766 }, { "content": "struct ProblemReader(pub Box<dyn Fn(File, Option<Vec<File>>) -> Result<Problem, String>>);\n\n\n", "file_path": "vrp-cli/src/commands/solve.rs", "rank": 39, "score": 385724.11597086274 }, { "content": "pub fn create_job_place(location: Vec<f64>) -> JobPlace {\n\n JobPlace { times: None, location: location.to_loc(), duration: 1. }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 40, "score": 383600.16692548676 }, { "content": "/// A trait to get or set demand.\n\npub trait DemandDimension<Capacity: Add + Sub + Ord + Copy + Default + Send + Sync + 'static> {\n\n fn set_demand(&mut self, demand: Demand<Capacity>) -> &mut Self;\n\n fn get_demand(&self) -> Option<&Demand<Capacity>>;\n\n}\n\n\n", "file_path": "vrp-core/src/construction/constraints/capacity.rs", "rank": 41, "score": 383210.1400227277 }, { "content": "struct LocationWriter(pub Box<dyn Fn(File, BufWriter<Box<dyn Write>>) -> Result<(), String>>);\n\n\n", "file_path": "vrp-cli/src/commands/solve.rs", "rank": 42, "score": 382558.3139091993 }, { "content": "fn assert_time_window(tw: &TimeWindow, expected: &(f64, f64)) {\n\n assert_eq!(tw.start, expected.0);\n\n assert_eq!(tw.end, expected.1);\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/format/problem/reader_test.rs", "rank": 43, "score": 381358.64839487127 }, { "content": "pub fn get_break_time_windows() -> impl Strategy<Value = VehicleBreakTime> {\n\n generate_multiple_time_windows_fixed(\n\n START_DAY,\n\n vec![from_hours(11), from_hours(13)],\n\n vec![from_hours(2), from_hours(4)],\n\n 1..2,\n\n )\n\n .prop_map(|tws| VehicleBreakTime::TimeWindow(tws.first().unwrap().clone()))\n\n}\n\n\n\nprop_compose! {\n\n fn get_vehicle_type_with_breaks()\n\n (\n\n vehicle in default_vehicle_type_prototype(),\n\n breaks in get_breaks()\n\n ) -> VehicleType {\n\n assert_eq!(vehicle.shifts.len(), 1);\n\n\n\n let mut vehicle = vehicle;\n\n vehicle.shifts.first_mut().unwrap().breaks = breaks;\n", "file_path": "vrp-pragmatic/tests/slow/property/generated_with_breaks.rs", "rank": 44, "score": 376419.77707673126 }, { "content": "fn read_jobs<R: Read>(reader: BufReader<R>) -> Result<Vec<Job>, Box<dyn Error>> {\n\n let get_task = |job: &CsvJob| JobTask {\n\n places: vec![JobPlace {\n\n location: Location { lat: job.lat, lng: job.lng },\n\n duration: job.duration as f64 * 60.,\n\n times: parse_tw(job.tw_start.clone(), job.tw_end.clone()).map(|tw| vec![tw]),\n\n }],\n\n demand: if job.demand != 0 { Some(vec![job.demand.abs()]) } else { None },\n\n tag: None,\n\n };\n\n\n\n let get_tasks = |jobs: &Vec<&CsvJob>, filter: Box<dyn Fn(&CsvJob) -> bool>| {\n\n let tasks = jobs.iter().filter(|j| filter.deref()(j)).map(|job| get_task(job)).collect::<Vec<_>>();\n\n if tasks.is_empty() {\n\n None\n\n } else {\n\n Some(tasks)\n\n }\n\n };\n\n\n", "file_path": "vrp-cli/src/extensions/import/csv.rs", "rank": 45, "score": 376279.48689264525 }, { "content": "fn parse_time_window(tw: &Vec<String>) -> TimeWindow {\n\n TimeWindow::new(parse_time(tw.first().unwrap()), parse_time(tw.last().unwrap()))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/mod.rs", "rank": 46, "score": 376266.965818572 }, { "content": "fn get_vehicle_id_from_job(job: &Arc<Single>) -> Option<&String> {\n\n job.dimens.get_value::<String>(\"vehicle_id\")\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/mod.rs", "rank": 47, "score": 373823.7429090705 }, { "content": "fn parse_time_window(tw: &Vec<String>) -> TimeWindow {\n\n assert_eq!(tw.len(), 2);\n\n TimeWindow::new(parse_time(tw.first().unwrap()), parse_time(tw.last().unwrap()))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/reader.rs", "rank": 48, "score": 373219.32143185 }, { "content": "pub fn get_locations_serialized(problem: &Problem) -> Result<String, String> {\n\n // TODO validate the problem?\n\n\n\n let locations = get_unique_locations(&problem);\n\n let mut buffer = String::new();\n\n let writer = unsafe { BufWriter::new(buffer.as_mut_vec()) };\n\n serde_json::to_writer_pretty(writer, &locations).map_err(|err| err.to_string())?;\n\n\n\n Ok(buffer)\n\n}\n\n\n", "file_path": "vrp-cli/src/lib.rs", "rank": 49, "score": 372728.7462237071 }, { "content": "pub fn read_hre_problem<R: Read>(reader: BufReader<R>) -> Result<Problem, FormatError> {\n\n let job_place_mapper = |job: &hre::Job, place: &hre::JobPlace| JobTask {\n\n places: vec![JobPlace {\n\n location: to_loc(&place.location),\n\n duration: place.duration,\n\n times: place.times.clone(),\n\n }],\n\n demand: Some(job.demand.clone()),\n\n tag: place.tag.clone(),\n\n };\n\n\n\n let multi_job_place_mapper = |places: &Vec<hre::MultiJobPlace>| {\n\n if places.is_empty() {\n\n None\n\n } else {\n\n Some(\n\n places\n\n .iter()\n\n .map(|place| JobTask {\n\n places: vec![JobPlace {\n", "file_path": "vrp-cli/src/extensions/import/hre.rs", "rank": 50, "score": 372709.11376576696 }, { "content": "/// Generates meaningful problem from the prototype.\n\n/// There is another problem generation implementation in `vrp-pragmatic` crate, used by tests.\n\n/// Its main goal is to discover problem space by generating many, potentially unrealistic, problems\n\n/// using property based approach. This implementation, in contrast, focuses on generating realistic\n\n/// problems.\n\npub fn generate_from_prototype(problem: &Problem, job_size: usize) -> Result<Problem, String> {\n\n if problem.plan.jobs.len() < 3 {\n\n return Err(\"at least three jobs should be defined\".to_string());\n\n }\n\n\n\n Ok(Problem {\n\n plan: generate_plan(&problem, job_size),\n\n fleet: problem.fleet.clone(),\n\n objectives: problem.objectives.clone(),\n\n config: problem.config.clone(),\n\n })\n\n}\n", "file_path": "vrp-cli/src/extensions/generate/prototype.rs", "rank": 51, "score": 371139.34203646827 }, { "content": "fn can_ruin_solution_with_matrix_routes_impl(matrix: (usize, usize), ints: Vec<i32>, expected_ids: Vec<&str>) {\n\n let reals = vec![];\n\n\n\n let (problem, solution) = generate_matrix_routes(matrix.0, matrix.1);\n\n let insertion_ctx: InsertionContext = InsertionContext::new_from_solution(\n\n Arc::new(problem),\n\n (Arc::new(solution), None),\n\n Arc::new(FakeRandom::new(ints, reals)),\n\n );\n\n\n\n let insertion_ctx = WorstJobRemoval::default()\n\n .run(&mut create_default_refinement_ctx(insertion_ctx.problem.clone()), insertion_ctx);\n\n\n\n assert_eq!(get_sorted_customer_ids_from_jobs(&insertion_ctx.solution.required), expected_ids);\n\n}\n", "file_path": "vrp-core/tests/unit/solver/mutation/ruin/worst_jobs_removal_test.rs", "rank": 52, "score": 370813.77900277416 }, { "content": "/// Checks that breaks are properly assigned.\n\npub fn check_breaks(context: &CheckerContext) -> Result<(), String> {\n\n context.solution.tours.iter().try_for_each(|tour| {\n\n let vehicle_shift = context.get_vehicle_shift(tour)?;\n\n let actual_break_count = tour.stops.iter().try_fold(0, |acc, stop| {\n\n stop.activities.windows(2).flat_map(|leg| as_leg_with_break(context, tour, stop, leg)).try_fold(\n\n acc,\n\n |acc, (from, to, vehicle_break)| {\n\n // check time\n\n let visit_time = get_time_window(stop, to);\n\n let break_time_window = get_break_time_window(tour, &vehicle_break)?;\n\n if !visit_time.intersects(&break_time_window) {\n\n return Err(format!(\n\n \"Break visit time '{:?}' is invalid: expected is in '{:?}'\",\n\n visit_time, break_time_window\n\n ));\n\n }\n\n\n\n // check location\n\n let actual_location = get_location(stop, to);\n\n match &vehicle_break.locations {\n", "file_path": "vrp-pragmatic/src/checker/breaks.rs", "rank": 53, "score": 367163.06195692794 }, { "content": "pub fn test_single_with_simple_demand(demand: Demand<i32>) -> Arc<Single> {\n\n let mut single = test_single();\n\n single.dimens.set_demand(demand);\n\n Arc::new(single)\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 54, "score": 367045.8194016722 }, { "content": "pub fn test_activity_with_location_and_tw(location: Location, tw: TimeWindow) -> Activity {\n\n Activity {\n\n place: Place { location, duration: DEFAULT_JOB_DURATION, time: tw },\n\n schedule: Schedule::new(location as f64, location as f64 + DEFAULT_JOB_DURATION),\n\n job: Some(test_single_with_location(Some(location))),\n\n }\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/solution/route.rs", "rank": 55, "score": 366300.4339970635 }, { "content": "/// Deserializes solution from json format.\n\npub fn deserialize_solution<R: Read>(reader: BufReader<R>) -> Result<Solution, Error> {\n\n serde_json::from_reader(reader)\n\n}\n", "file_path": "vrp-pragmatic/src/format/solution/model.rs", "rank": 56, "score": 365930.0957016767 }, { "content": "pub fn default_job_single_day_time_windows() -> impl Strategy<Value = Option<Vec<Vec<String>>>> {\n\n generate_multiple_time_windows_fixed(\n\n START_DAY,\n\n vec![from_hours(9), from_hours(14)],\n\n vec![from_hours(2), from_hours(4)],\n\n 1..3,\n\n )\n\n .prop_map(|tw| Some(tw))\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 57, "score": 364618.40233606164 }, { "content": "fn parse_tw(start: Option<String>, end: Option<String>) -> Option<Vec<String>> {\n\n match (start, end) {\n\n (Some(start), Some(end)) => Some(vec![start, end]),\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "vrp-cli/src/extensions/import/csv.rs", "rank": 58, "score": 362568.8812605785 }, { "content": "pub fn default_time_plus_offset(offset: i32) -> String {\n\n format_time(parse_time(&START_DAY.to_string()) + from_hours(offset).as_secs_f64())\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 59, "score": 362100.46944266313 }, { "content": "pub fn test_tour_activity_with_location_and_tw(location: Location, tw: TimeWindow) -> TourActivity {\n\n Box::new(test_activity_with_location_and_tw(location, tw))\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/solution/tour.rs", "rank": 60, "score": 361334.545236386 }, { "content": "fn add_priority(dimens: &mut Dimensions, priority: &Option<i32>) {\n\n if let Some(priority) = priority {\n\n dimens.set_value(\"priority\", *priority);\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 61, "score": 356254.4152715538 }, { "content": "pub fn default_pickup_prototype() -> impl Strategy<Value = Job> {\n\n pickup_job_prototype(\n\n job_task_prototype(default_job_place_prototype(), generate_simple_demand(1..5), generate_no_tags()),\n\n generate_no_priority(),\n\n generate_no_skills(),\n\n )\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 62, "score": 356064.888238532 }, { "content": "pub fn default_delivery_prototype() -> impl Strategy<Value = Job> {\n\n delivery_job_prototype(\n\n job_task_prototype(default_job_place_prototype(), generate_simple_demand(1..5), generate_no_tags()),\n\n generate_no_priority(),\n\n generate_no_skills(),\n\n )\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 63, "score": 356052.12510418275 }, { "content": "fn add_tag(dimens: &mut Dimensions, tag: &Option<String>) {\n\n if let Some(tag) = tag {\n\n dimens.set_value(\"tag\", tag.clone());\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 64, "score": 355716.55459605495 }, { "content": "/// Deserializes problem in json format from [`BufReader`].\n\npub fn deserialize_problem<R: Read>(reader: BufReader<R>) -> Result<Problem, Vec<FormatError>> {\n\n serde_json::from_reader(reader).map_err(|err| {\n\n vec![FormatError::new(\n\n \"E0000\".to_string(),\n\n \"cannot deserialize problem\".to_string(),\n\n format!(\"check input json: '{}'\", err),\n\n )]\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/model.rs", "rank": 65, "score": 355675.6157170663 }, { "content": "/// Generates jobs.\n\npub fn generate_jobs(job_proto: impl Strategy<Value = Job>, range: Range<usize>) -> impl Strategy<Value = Vec<Job>> {\n\n prop::collection::vec(job_proto, range)\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/jobs.rs", "rank": 66, "score": 352679.50176478585 }, { "content": "/// Selects seed job from existing solution\n\nfn select_seed_job<'a>(routes: &'a [RouteContext], random: &Arc<dyn Random + Send + Sync>) -> Option<(usize, Job)> {\n\n if routes.is_empty() {\n\n return None;\n\n }\n\n\n\n let route_index = random.uniform_int(0, (routes.len() - 1) as i32) as usize;\n\n let mut ri = route_index;\n\n\n\n loop {\n\n let rc = routes.get(ri).unwrap();\n\n\n\n if rc.route.tour.has_jobs() {\n\n let job = select_random_job(rc, random);\n\n if let Some(job) = job {\n\n return Some((ri, job));\n\n }\n\n }\n\n\n\n ri = (ri + 1) % routes.len();\n\n if ri == route_index {\n\n break;\n\n }\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "vrp-core/src/solver/mutation/ruin/mod.rs", "rank": 67, "score": 351366.3776613658 }, { "content": "fn parse_time(time: &String) -> f64 {\n\n parse_time_safe(time).unwrap()\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/lib.rs", "rank": 68, "score": 347661.8701846694 }, { "content": "fn format_time(time: f64) -> String {\n\n Utc.timestamp(time as i64, 0).to_rfc3339_opts(SecondsFormat::Secs, true)\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/lib.rs", "rank": 69, "score": 347661.8701846694 }, { "content": "fn get_tour_by_vehicle_id(vehicle_id: &str, shift_index: Option<usize>, solution: &Solution) -> Result<Tour, String> {\n\n solution\n\n .tours\n\n .iter()\n\n .find(|tour| tour.vehicle_id == vehicle_id && tour.shift_index == shift_index.unwrap_or(0))\n\n .cloned()\n\n .ok_or_else(|| format!(\"Cannot find tour for '{}'\", vehicle_id))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/relations.rs", "rank": 70, "score": 346888.643955172 }, { "content": "/// A trait to get or set capacity.\n\npub trait CapacityDimension<Capacity: Add + Sub + Ord + Copy + Default + Send + Sync + 'static> {\n\n fn set_capacity(&mut self, demand: Capacity) -> &mut Self;\n\n fn get_capacity(&self) -> Option<&Capacity>;\n\n}\n\n\n", "file_path": "vrp-core/src/construction/constraints/capacity.rs", "rank": 71, "score": 346648.00066185097 }, { "content": "fn read_vehicles<R: Read>(reader: BufReader<R>) -> Result<Vec<VehicleType>, Box<dyn Error>> {\n\n let vehicles = read_csv_entries::<CsvVehicle, _>(reader)?\n\n .into_iter()\n\n .map(|vehicle| {\n\n let depot_location = Location { lat: vehicle.lat, lng: vehicle.lng };\n\n\n\n VehicleType {\n\n type_id: vehicle.id.clone(),\n\n vehicle_ids: (1..vehicle.amount).map(|seq| format!(\"{}_{}\", vehicle.profile, seq)).collect(),\n\n profile: vehicle.profile,\n\n costs: VehicleCosts { fixed: Some(25.), distance: 0.0002, time: 0.005 },\n\n shifts: vec![VehicleShift {\n\n start: VehiclePlace { time: vehicle.tw_start, location: depot_location.clone() },\n\n end: Some(VehiclePlace { time: vehicle.tw_end, location: depot_location }),\n\n breaks: None,\n\n reloads: None,\n\n }],\n\n capacity: vec![vehicle.capacity],\n\n skills: None,\n\n limits: None,\n\n }\n\n })\n\n .collect();\n\n\n\n Ok(vehicles)\n\n}\n\n\n", "file_path": "vrp-cli/src/extensions/import/csv.rs", "rank": 72, "score": 345635.15544969187 }, { "content": "pub fn create_simple_demand(size: i32) -> Demand<i32> {\n\n if size > 0 {\n\n Demand::<i32> { pickup: (size, 0), delivery: (0, 0) }\n\n } else {\n\n Demand::<i32> { pickup: (0, 0), delivery: (-size, 0) }\n\n }\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/construction/constraints.rs", "rank": 73, "score": 342998.4203043204 }, { "content": "pub fn test_place_with_location(location: Option<Location>) -> Place {\n\n Place { location, duration: DEFAULT_JOB_DURATION, times: vec![DEFAULT_JOB_TIME_SPAN] }\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 74, "score": 342087.30725520756 }, { "content": "/// This trait defines multi-trip strategy.\n\npub trait MultiTrip<Capacity: Add + Sub + Ord + Copy + Default + Send + Sync + 'static> {\n\n /// Returns true if job is reload.\n\n fn is_reload_job(&self, job: &Job) -> bool;\n\n\n\n /// Returns true if single job is reload.\n\n fn is_reload_single(&self, single: &Single) -> bool;\n\n\n\n /// Returns true if given job is reload and can be used with given route.\n\n fn is_assignable(&self, route: &Route, job: &Job) -> bool;\n\n\n\n /// Returns true when `current` capacity is close `max_capacity`.\n\n fn is_reload_needed(&self, current: &Capacity, max_capacity: &Capacity) -> bool;\n\n\n\n /// Returns true if route context has reloads.\n\n fn has_reloads(&self, route_ctx: &RouteContext) -> bool;\n\n\n\n /// Returns reload job from activity or None.\n\n fn get_reload<'a>(&self, activity: &'a Activity) -> Option<&'a Arc<Single>>;\n\n\n\n /// Gets all reloads for specific route from jobs collection.\n", "file_path": "vrp-core/src/construction/constraints/capacity.rs", "rank": 75, "score": 341046.8664905423 }, { "content": "struct DemandJobSelector<Capacity: Add + Sub + Ord + Copy + Default + Send + Sync + 'static> {\n\n asc_order: bool,\n\n phantom: PhantomData<Capacity>,\n\n}\n\n\n\nimpl<Capacity: Add<Output = Capacity> + Sub<Output = Capacity> + Ord + Copy + Default + Send + Sync + 'static>\n\n DemandJobSelector<Capacity>\n\n{\n\n pub fn new(asc_order: bool) -> Self {\n\n Self { asc_order, phantom: PhantomData }\n\n }\n\n\n\n fn get_capacity(demand: &Demand<Capacity>) -> Capacity {\n\n demand.pickup.0 + demand.delivery.0 + demand.pickup.1 + demand.delivery.1\n\n }\n\n\n\n fn get_job_demand(job: &Job) -> Option<Capacity> {\n\n match job {\n\n Job::Single(job) => job.dimens.get_demand(),\n\n Job::Multi(job) => job.jobs.first().and_then(|s| s.dimens.get_demand()),\n", "file_path": "vrp-core/src/solver/mutation/recreate/recreate_with_blinks.rs", "rank": 76, "score": 338842.8126253896 }, { "content": "pub fn get_vehicle_id(vehicle: &Vehicle) -> &String {\n\n vehicle.dimens.get_id().unwrap()\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/fleet.rs", "rank": 77, "score": 337483.3610595963 }, { "content": "pub fn default_job_place_prototype() -> impl Strategy<Value = JobPlace> {\n\n job_place_prototype(\n\n generate_location(&DEFAULT_BOUNDING_BOX),\n\n generate_durations(1..10),\n\n default_job_single_day_time_windows(),\n\n )\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 78, "score": 336404.4100858512 }, { "content": "pub fn default_vehicle_places_prototype() -> impl Strategy<Value = (VehiclePlace, Option<VehiclePlace>)> {\n\n generate_location(&DEFAULT_BOUNDING_BOX).prop_flat_map(|location| {\n\n Just((\n\n VehiclePlace { time: default_time_plus_offset(9), location: location.clone() },\n\n Some(VehiclePlace { time: default_time_plus_offset(18), location }),\n\n ))\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 79, "score": 333023.0884632488 }, { "content": "pub fn create_job(id: &str) -> Job {\n\n Job {\n\n id: id.to_string(),\n\n pickups: None,\n\n deliveries: None,\n\n replacements: None,\n\n services: None,\n\n priority: None,\n\n skills: None,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 80, "score": 332596.04022455745 }, { "content": "pub fn get_job_time_windows(problem: &Problem) -> Vec<(f64, f64)> {\n\n problem\n\n .jobs\n\n .all()\n\n .map(|j| match j {\n\n Job::Single(j) => j\n\n .places\n\n .first()\n\n .unwrap()\n\n .times\n\n .first()\n\n .map(|span| span.as_time_window().unwrap())\n\n .map(|tw| (tw.start, tw.end))\n\n .unwrap(),\n\n _ => panic!(),\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 81, "score": 331668.3009818531 }, { "content": "fn can_use_break_between_two_jobs_in_relation_impl(relation_type: RelationType, jobs: Vec<String>) {\n\n let solution = get_solution(relation_type, jobs);\n\n\n\n assert_eq!(\n\n solution,\n\n Solution {\n\n statistic: Statistic {\n\n cost: 26.,\n\n distance: 6,\n\n duration: 10,\n\n times: Timing { driving: 6, serving: 2, waiting: 0, break_time: 2 },\n\n },\n\n tours: vec![Tour {\n\n vehicle_id: \"my_vehicle_1\".to_string(),\n\n type_id: \"my_vehicle\".to_string(),\n\n shift_index: 0,\n\n stops: vec![\n\n create_stop_with_activity(\n\n \"departure\",\n\n \"departure\",\n", "file_path": "vrp-pragmatic/tests/features/breaks/relation_break_test.rs", "rank": 82, "score": 329584.5163730516 }, { "content": "pub fn test_tour_activity_with_simple_demand(demand: Demand<i32>) -> TourActivity {\n\n Box::new(test_activity_with_job(test_single_with_simple_demand(demand)))\n\n}\n", "file_path": "vrp-core/tests/helpers/models/solution/tour.rs", "rank": 83, "score": 328140.80493553635 }, { "content": "pub fn get_vehicle_capacity(problem: &Problem) -> i32 {\n\n *problem.fleet.vehicles.iter().next().unwrap().dimens.get_capacity().unwrap()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 84, "score": 327855.7275349079 }, { "content": "/// Promotes break jobs from required and ignored.\n\nfn create_job_transition() -> Box<dyn JobContextTransition + Send + Sync> {\n\n Box::new(ConcreteJobContextTransition {\n\n remove_required: |ctx, job| !is_required_job(ctx, job, true),\n\n promote_required: |ctx, job| is_required_job(ctx, job, false),\n\n remove_locked: |_, _| false,\n\n promote_locked: |_, _| false,\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/breaks.rs", "rank": 85, "score": 327593.9083272492 }, { "content": "fn select_random_job(rc: &RouteContext, random: &Arc<dyn Random + Send + Sync>) -> Option<Job> {\n\n let size = rc.route.tour.activity_count();\n\n if size == 0 {\n\n return None;\n\n }\n\n\n\n let activity_index = random.uniform_int(1, size as i32) as usize;\n\n let mut ai = activity_index;\n\n\n\n loop {\n\n let job = rc.route.tour.get(ai).and_then(|a| a.retrieve_job());\n\n\n\n if job.is_some() {\n\n return job;\n\n }\n\n\n\n ai = (ai + 1) % (size + 1);\n\n if ai == activity_index {\n\n break;\n\n }\n\n }\n\n\n\n None\n\n}\n", "file_path": "vrp-core/src/solver/mutation/ruin/mod.rs", "rank": 86, "score": 324340.7881260681 }, { "content": "fn returns_proper_job_neighbours_impl(index: usize, expected: Vec<String>) {\n\n let fleet = FleetBuilder::default()\n\n .add_driver(test_driver())\n\n .add_vehicles(vec![\n\n VehicleBuilder::default().id(\"v1\").profile(1).details(vec![test_vehicle_detail()]).build(),\n\n VehicleBuilder::default().id(\"v2\").profile(1).details(vec![test_vehicle_detail()]).build(),\n\n ])\n\n .build();\n\n let species = vec![\n\n SingleBuilder::default().id(\"s0\").location(Some(0)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s1\").location(Some(1)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s2\").location(Some(2)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s3\").location(Some(3)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s4\").location(Some(4)).build_as_job_ref(),\n\n ];\n\n let jobs = Jobs::new(&fleet, species.clone(), &create_profile_aware_transport_cost());\n\n\n\n let result: Vec<String> = jobs\n\n .neighbors(1, species.get(index).unwrap(), 0.0, u32::max_value() as f64)\n\n .map(|j| get_job_id(&j).clone())\n", "file_path": "vrp-core/tests/unit/models/problem/jobs_test.rs", "rank": 87, "score": 324265.4072142165 }, { "content": "fn can_detect_relation_errors_impl(job_ids: Vec<String>, vehicle_id: String, expected: Option<(&str, &str)>) {\n\n let problem = Problem {\n\n plan: Plan {\n\n jobs: vec![create_delivery_job(\"job2\", vec![1., 0.])],\n\n relations: Some(vec![Relation {\n\n type_field: RelationType::Strict,\n\n jobs: job_ids,\n\n vehicle_id,\n\n shift_index: None,\n\n }]),\n\n },\n\n fleet: Fleet { vehicles: vec![create_default_vehicle(\"vehicle\")], profiles: vec![] },\n\n ..create_empty_problem()\n\n };\n\n\n\n let result = validate_result(&ValidationContext::new(&problem, None));\n\n\n\n if let Some((code, action)) = expected {\n\n assert_eq!(result.clone().map(|err| err.code), Some(code.to_string()));\n\n assert!(result.map_or(\"\".to_string(), |err| err.action).contains(action));\n", "file_path": "vrp-pragmatic/tests/unit/validation/relations_test.rs", "rank": 88, "score": 323233.4646483711 }, { "content": "/// Creates default population.\n\npub fn create_default_population(problem: Arc<Problem>) -> Box<dyn Population + Sync + Send> {\n\n Box::new(DominancePopulation::new(problem, Arc::new(DefaultRandom::default()), 4, 2, 2))\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/solver/mod.rs", "rank": 89, "score": 323132.709077816 }, { "content": "pub fn default_job_prototype() -> impl Strategy<Value = Job> {\n\n prop_oneof![default_delivery_prototype(), default_pickup_prototype(), default_pickup_delivery_prototype()]\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 90, "score": 321847.3270476905 }, { "content": "pub fn test_single_with_id_and_location(id: &str, location: Option<Location>) -> Arc<Single> {\n\n let mut single = Single { places: vec![test_place_with_location(location)], dimens: Default::default() };\n\n single.dimens.set_id(id);\n\n Arc::new(single)\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 91, "score": 320920.1505236069 }, { "content": "fn can_use_break_last_in_relation_impl(relation_type: RelationType, jobs: Vec<String>) {\n\n let solution = get_solution(relation_type, jobs);\n\n\n\n assert_eq!(\n\n solution,\n\n Solution {\n\n statistic: Statistic {\n\n cost: 26.,\n\n distance: 6,\n\n duration: 10,\n\n times: Timing { driving: 6, serving: 2, waiting: 0, break_time: 2 },\n\n },\n\n tours: vec![Tour {\n\n vehicle_id: \"my_vehicle_1\".to_string(),\n\n type_id: \"my_vehicle\".to_string(),\n\n shift_index: 0,\n\n stops: vec![\n\n create_stop_with_activity(\n\n \"departure\",\n\n \"departure\",\n", "file_path": "vrp-pragmatic/tests/features/breaks/relation_break_test.rs", "rank": 92, "score": 320527.00482253433 }, { "content": "pub fn get_job_demands(problem: &Problem) -> Vec<i32> {\n\n problem.jobs.all().map(|j| get_job_simple_demand(&j).delivery.0).collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 93, "score": 319906.57694444124 }, { "content": "pub fn get_job_durations(problem: &Problem) -> Vec<f64> {\n\n problem\n\n .jobs\n\n .all()\n\n .map(|j| match j {\n\n Job::Single(j) => j.places.first().unwrap().duration,\n\n _ => panic!(),\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 94, "score": 319777.623246571 }, { "content": "pub fn create_task(location: Vec<f64>) -> JobTask {\n\n JobTask { places: vec![create_job_place(location)], demand: Some(vec![1]), tag: None }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 95, "score": 319600.3326662912 }, { "content": "pub fn create_details_actor_groups(actors: &[Arc<Actor>]) -> Box<dyn Fn(&Arc<Actor>) -> usize + Send + Sync> {\n\n let unique_type_keys: HashSet<_> = actors.iter().map(|a| a.detail.clone()).collect();\n\n\n\n let type_key_map: HashMap<_, _> = unique_type_keys.into_iter().zip(0_usize..).collect();\n\n\n\n let groups: HashMap<_, _> = actors.iter().map(|a| (a.clone(), *type_key_map.get(&a.detail).unwrap())).collect();\n\n\n\n Box::new(move |a| *groups.get(a).unwrap())\n\n}\n", "file_path": "vrp-core/tests/helpers/models/problem/fleet.rs", "rank": 96, "score": 319323.7264372979 }, { "content": "pub fn get_job_ids(problem: &Problem) -> Vec<String> {\n\n problem.jobs.all().map(|j| get_job_id(&j).to_owned()).collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 97, "score": 319252.3610614281 }, { "content": "/// Checks that sum of pickup/delivery demand should be equal.\n\nfn check_e1102_multiple_pickups_deliveries_demand(ctx: &ValidationContext) -> Result<(), FormatError> {\n\n let has_tasks = |tasks: &Option<Vec<JobTask>>| tasks.as_ref().map_or(false, |tasks| tasks.len() > 0);\n\n let get_demand = |tasks: &Option<Vec<JobTask>>| {\n\n if let Some(tasks) = tasks {\n\n tasks\n\n .iter()\n\n .map(|task| {\n\n task.demand.clone().map_or_else(\n\n || MultiDimensionalCapacity::default(),\n\n |demand| MultiDimensionalCapacity::new(demand),\n\n )\n\n })\n\n .sum()\n\n } else {\n\n MultiDimensionalCapacity::default()\n\n }\n\n };\n\n\n\n let ids = ctx\n\n .jobs()\n", "file_path": "vrp-pragmatic/src/validation/jobs.rs", "rank": 98, "score": 318975.4901190382 }, { "content": "/// A actor group key implementation which creates groups using \"type\" dimension.\n\npub fn create_typed_actor_groups(actors: &[Arc<Actor>]) -> Box<dyn Fn(&Arc<Actor>) -> usize + Send + Sync> {\n\n let unique_type_keys: HashSet<_> = actors\n\n .iter()\n\n .map(|a| (a.vehicle.dimens.get_value::<String>(\"type_id\").cloned().unwrap(), a.detail.clone()))\n\n .collect();\n\n\n\n let type_key_map: HashMap<_, _> = unique_type_keys.into_iter().zip(0_usize..).collect();\n\n\n\n let groups: HashMap<_, _> = actors\n\n .iter()\n\n .map(|a| {\n\n (\n\n a.clone(),\n\n *type_key_map\n\n .get(&(a.vehicle.dimens.get_value::<String>(\"type_id\").cloned().unwrap(), a.detail.clone()))\n\n .unwrap(),\n\n )\n\n })\n\n .collect();\n\n\n\n Box::new(move |a| *groups.get(a).unwrap())\n\n}\n", "file_path": "vrp-pragmatic/src/extensions/typed_actor_group_key.rs", "rank": 99, "score": 316938.4332188922 } ]
Rust
src/boxed/api.rs
sharksforarms/bitvec
293e670d5b6fe89da595edccb3f93cafb75d8835
use crate::{ boxed::BitBox, order::BitOrder, pointer::BitPtr, slice::BitSlice, store::BitStore, vec::BitVec, }; use core::{ marker::Unpin, mem::ManuallyDrop, pin::Pin, }; use wyz::pipe::Pipe; impl<O, T> BitBox<O, T> where O: BitOrder, T: BitStore, { #[cfg_attr(not(tarpaulin), inline(always))] #[deprecated(since = "0.18.0", note = "Prefer `::from_bitslice`")] pub fn new(x: &BitSlice<O, T>) -> Self { Self::from_bitslice(x) } #[inline] pub fn pin(x: &BitSlice<O, T>) -> Pin<Self> where O: Unpin, T: Unpin, { x.pipe(Self::from_bitslice).pipe(Pin::new) } #[inline] pub unsafe fn from_raw(raw: *mut BitSlice<O, T>) -> Self { raw.pipe(BitPtr::from_bitslice_ptr_mut) .to_nonnull() .pipe(|pointer| Self { pointer }) } #[cfg_attr(not(tarpaulin), inline(always))] pub fn into_raw(b: Self) -> *mut BitSlice<O, T> { Self::leak(b) } #[inline] pub fn leak<'a>(b: Self) -> &'a mut BitSlice<O, T> where T: 'a { b.pipe(ManuallyDrop::new).bitptr().to_bitslice_mut() } #[inline] pub fn into_bitvec(self) -> BitVec<O, T> { let bitptr = self.bitptr(); let raw = self .pipe(ManuallyDrop::new) .with_box(|b| unsafe { ManuallyDrop::take(b) }) .into_vec() .pipe(ManuallyDrop::new); /* The distribution claims that `[T]::into_vec(Box<[T]>) -> Vec<T>` does not alter the address of the heap allocation, and only modifies the buffer handle. Since the address does not change, the `BitPtr` does not need to be updated; the only change is that buffer capacity is now carried locally, rather than frozen in the allocator’s state. Inspection of the distribution’s implementation shows that the conversion from `(buf, len)` to `(buf, cap, len)` is done by using the slice length as the buffer capacity. However, this is *not* a behavior guaranteed by the distribution, and so the pipeline above must remain in place in the event that this behavior ever changes. It should compile away to nothing, as it is almost entirely typesystem manipulation. */ unsafe { BitVec::from_raw_parts(bitptr.to_bitslice_ptr_mut(), raw.capacity()) } } }
use crate::{ boxed::BitBox, order::BitOrder, pointer::BitPtr, slice::BitSlice, store::BitStore, vec::BitVec, }; use core::{ marker::Unpin, mem::ManuallyDrop, pin::Pin, }; use wyz::pipe::Pipe; impl<O, T> BitBox<O, T> where O: BitOrder, T: BitStore, { #[cfg_attr(not(tarpaulin), inline(always))] #[deprecated(since = "0.18.0", note = "Prefer `::from_bitslice`")] pub fn new(x: &BitSlice<O, T>) -> Self { Self::from_bitslice(x) } #[inline] pub fn pin(x: &BitSlice<O, T>) -> Pin<Self> where O: Unpin, T: Unpin, { x.pipe(Self::from_bitslice).pipe(Pin::new) } #[inline] pub unsafe fn from_raw(raw: *mut BitSlice<O, T>) -> Self { raw.pipe(BitPtr::from_bitslice_ptr_mut) .to_nonnull() .pipe(|pointer| Self { pointer }) } #[cfg_attr(not(tarpaulin), inline(always))] pub fn into_raw(b: Self) -> *mut BitSlice<O, T> { Self::leak(b) } #[inline] pub fn leak<'a>(b: Self) -> &'a mut BitSlice<O, T> where T: 'a { b.pipe(ManuallyDrop::new).bitptr().to_bitslice_mut() } #[inline] pub fn into_bitvec(self) -> BitVec<O, T> { let bitptr = self.bitptr();
/* The distribution claims that `[T]::into_vec(Box<[T]>) -> Vec<T>` does not alter the address of the heap allocation, and only modifies the buffer handle. Since the address does not change, the `BitPtr` does not need to be updated; the only change is that buffer capacity is now carried locally, rather than frozen in the allocator’s state. Inspection of the distribution’s implementation shows that the conversion from `(buf, len)` to `(buf, cap, len)` is done by using the slice length as the buffer capacity. However, this is *not* a behavior guaranteed by the distribution, and so the pipeline above must remain in place in the event that this behavior ever changes. It should compile away to nothing, as it is almost entirely typesystem manipulation. */ unsafe { BitVec::from_raw_parts(bitptr.to_bitslice_ptr_mut(), raw.capacity()) } } }
let raw = self .pipe(ManuallyDrop::new) .with_box(|b| unsafe { ManuallyDrop::take(b) }) .into_vec() .pipe(ManuallyDrop::new);
assignment_statement
[ { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn mem_mut<T>(x: &mut T) -> &mut T::Mem\n\nwhere T: BitStore {\n\n\tunsafe { &mut *(x as *mut _ as *mut _) }\n\n}\n\n\n\n/// Removes the `::Alias` marker from a register value’s type.\n", "file_path": "src/devel.rs", "rank": 0, "score": 153952.61623005528 }, { "content": "#[inline(always)]\n\npub fn from_mut<O, T>(elem: &mut T) -> &mut BitSlice<O, T>\n\nwhere\n\n\tO: BitOrder,\n\n\tT: BitStore + BitMemory,\n\n{\n\n\tBitSlice::from_element_mut(elem)\n\n}\n\n\n\n/* NOTE: Crate style is to use block doc comments at the left margin. A bug in\n\n`rustfmt` replaces four spaces at left margin with hard tab, which is incorrect\n\nin comments. Once `rustfmt` is fixed, revert these to block comments.\n\n*/\n\n\n\n/// Forms a bitslice from a pointer and a length.\n\n///\n\n/// The `len` argument is the number of **elements**, not the number of bits.\n\n///\n\n/// # Original\n\n///\n\n/// [`slice::from_raw_parts`](https://doc.rust-lang.org/core/slice/fn.from_raw_parts.html)\n", "file_path": "src/slice/api.rs", "rank": 1, "score": 137867.34355964756 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn remove_bitptr_alias<T>(x: BitPtr<T::Alias>) -> BitPtr<T>\n\nwhere T: BitStore {\n\n\tunsafe { *(&x as *const _ as *const _) }\n\n}\n\n\n\n/// Removes the `::Mem` marker from a memory value.\n", "file_path": "src/devel.rs", "rank": 2, "score": 126869.46770206268 }, { "content": "#[bench]\n\nfn get_mut(b: &mut Bencher) {\n\n\tlet mut src = [0u8; 16];\n\n\tlet bsb08 = src.view_bits_mut::<Msb0>();\n\n\tb.iter(|| *bsb08.get_mut(69).unwrap() = true);\n\n\tlet mut src = [0u8; 16];\n\n\tlet bsl08 = src.view_bits_mut::<Lsb0>();\n\n\tb.iter(|| *bsl08.get_mut(69).unwrap() = true);\n\n\n\n\tlet mut src = [0u16; 8];\n\n\tlet bsb16 = src.view_bits_mut::<Msb0>();\n\n\tb.iter(|| *bsb16.get_mut(69).unwrap() = true);\n\n\tlet mut src = [0u16; 8];\n\n\tlet bsl16 = src.view_bits_mut::<Lsb0>();\n\n\tb.iter(|| *bsl16.get_mut(69).unwrap() = true);\n\n\n\n\tlet mut src = [0u32; 4];\n\n\tlet bsb32 = src.view_bits_mut::<Msb0>();\n\n\tb.iter(|| *bsb32.get_mut(69).unwrap() = true);\n\n\tlet mut src = [0u32; 4];\n\n\tlet bsl32 = src.view_bits_mut::<Lsb0>();\n", "file_path": "benches/slice.rs", "rank": 3, "score": 121467.98917013915 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn nonnull_slice_to_base<T>(mut nn_slice: NonNull<[T]>) -> NonNull<T> {\n\n\tunsafe { nn_slice.as_mut() }\n\n\t\t.pipe(<[T]>::as_mut_ptr)\n\n\t\t.pipe(|p| unsafe { NonNull::new_unchecked(p) })\n\n}\n\n\n\n/** Normalizes any range into a basic `Range`.\n\n\n\nThis unpacks any range type into an ordinary `Range`, returning the start and\n\nexclusive end markers. If the start marker is not provided, it is assumed to be\n\nzero; if the end marker is not provided, then it is assumed to be `end`.\n\n\n\nThe end marker, if provided, may be greater than `end`. This is not checked in\n\nthe function, and must be inspected by the caller.\n\n\n\n# Type Parameters\n\n\n\n- `R`: A range of some kind\n\n\n\n# Parameters\n\n\n\n- `bounds`: A range of some kind\n\n- `end`: The value to use as the exclusive end, if the range does not have an\n\n end.\n\n\n\n# Returns\n\n\n\n`bounds` normalized to an ordinary `Range`, optionally clamped to `end`.\n\n**/\n", "file_path": "src/devel.rs", "rank": 4, "score": 113434.2951916889 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn alias_mask<T>(\n\n\tx: BitMask<T::Mem>,\n\n) -> BitMask<<T::Alias as BitStore>::Mem>\n\nwhere T: BitStore {\n\n\tunsafe { *(&x as *const _ as *const _) }\n\n}\n\n\n\n/// Inserts an `::Alias` marker into a `T::Mem` value’s type.\n", "file_path": "src/devel.rs", "rank": 5, "score": 113143.78748495958 }, { "content": "#[bench]\n\nfn element(b: &mut Bencher) {\n\n\tb.iter(|| BitSlice::<Msb0, u8>::from_element(&!0));\n\n\tb.iter(|| BitSlice::<Lsb0, u8>::from_element(&!0));\n\n\tb.iter(|| BitSlice::<Msb0, u16>::from_element(&!0));\n\n\tb.iter(|| BitSlice::<Lsb0, u16>::from_element(&!0));\n\n\tb.iter(|| BitSlice::<Msb0, u32>::from_element(&!0));\n\n\tb.iter(|| BitSlice::<Lsb0, u32>::from_element(&!0));\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\t{\n\n\t\tb.iter(|| BitSlice::<Msb0, u64>::from_element(&!0));\n\n\t\tb.iter(|| BitSlice::<Lsb0, u64>::from_element(&!0));\n\n\t}\n\n}\n\n\n", "file_path": "benches/slice.rs", "rank": 6, "score": 112796.22090109228 }, { "content": "#[bench]\n\nfn slice(b: &mut Bencher) {\n\n\tb.iter(|| BitSlice::<Msb0, u8>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\tb.iter(|| BitSlice::<Lsb0, u8>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\tb.iter(|| BitSlice::<Msb0, u16>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\tb.iter(|| BitSlice::<Lsb0, u16>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\tb.iter(|| BitSlice::<Msb0, u32>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\tb.iter(|| BitSlice::<Lsb0, u32>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\t{\n\n\t\tb.iter(|| BitSlice::<Msb0, u64>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\t\tb.iter(|| BitSlice::<Lsb0, u64>::from_slice(&[0, 1, !0 - 1, !0][..]));\n\n\t}\n\n}\n\n\n", "file_path": "benches/slice.rs", "rank": 7, "score": 112796.22090109228 }, { "content": "#[bench]\n\nfn index(b: &mut Bencher) {\n\n\tlet bsb08 = [0u8; 16].view_bits::<Msb0>();\n\n\tlet bsl08 = [0u8; 16].view_bits::<Lsb0>();\n\n\tb.iter(|| assert!(!black_box(bsb08)[black_box(69)]));\n\n\tb.iter(|| assert!(!black_box(bsl08)[black_box(69)]));\n\n\n\n\tlet bsb16 = [0u16; 8].view_bits::<Msb0>();\n\n\tlet bsl16 = [0u16; 8].view_bits::<Lsb0>();\n\n\tb.iter(|| assert!(!black_box(bsb16)[black_box(69)]));\n\n\tb.iter(|| assert!(!black_box(bsl16)[black_box(69)]));\n\n\n\n\tlet bsb32 = [0u32; 4].view_bits::<Msb0>();\n\n\tlet bsl32 = [0u32; 4].view_bits::<Lsb0>();\n\n\tb.iter(|| assert!(!black_box(bsb32)[black_box(69)]));\n\n\tb.iter(|| assert!(!black_box(bsl32)[black_box(69)]));\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\t{\n\n\t\tlet bsb64 = [0u64; 2].view_bits::<Msb0>();\n\n\t\tlet bsl64 = [0u64; 2].view_bits::<Lsb0>();\n\n\t\tb.iter(|| assert!(!black_box(bsb64)[black_box(69)]));\n\n\t\tb.iter(|| assert!(!black_box(bsl64)[black_box(69)]));\n\n\t}\n\n}\n\n\n\n/* This routine has more work to do: index, create a reference struct, and drop\n\nit. The compiler *should* be able to properly arrange immediate drops, though.\n\n*/\n", "file_path": "benches/slice.rs", "rank": 8, "score": 112796.22090109228 }, { "content": "#[bench]\n\nfn len(b: &mut Bencher) {\n\n\tlet bsb08 = [0u8; 16].view_bits::<Msb0>();\n\n\tlet bsl08 = [0u8; 16].view_bits::<Lsb0>();\n\n\tb.iter(|| bsb08.len());\n\n\tb.iter(|| bsl08.len());\n\n\n\n\tlet bsb16 = [0u16; 8].view_bits::<Msb0>();\n\n\tlet bsl16 = [0u16; 8].view_bits::<Lsb0>();\n\n\tb.iter(|| bsb16.len());\n\n\tb.iter(|| bsl16.len());\n\n\n\n\tlet bsb32 = [0u32; 4].view_bits::<Msb0>();\n\n\tlet bsl32 = [0u32; 4].view_bits::<Lsb0>();\n\n\tb.iter(|| bsb32.len());\n\n\tb.iter(|| bsl32.len());\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\t{\n\n\t\tlet bsb64 = [0u64; 2].view_bits::<Msb0>();\n\n\t\tlet bsl64 = [0u64; 2].view_bits::<Lsb0>();\n\n\t\tb.iter(|| bsb64.len());\n\n\t\tb.iter(|| bsl64.len());\n\n\t}\n\n}\n\n\n\n// This index value is not only \"nice\", it also ensures that the hard path is\n\n// hit in `BitIdx::offset`.\n", "file_path": "benches/slice.rs", "rank": 9, "score": 112796.22090109228 }, { "content": "#[bench]\n\nfn vec_rep(b: &mut Bencher) {\n\n\tb.iter(|| vec![0u8; 16 * 16 * 9 / 8]);\n\n\tb.iter(|| vec![-1i8; 16 * 16 * 9 / 8]);\n\n}\n", "file_path": "benches/macros.rs", "rank": 10, "score": 109430.49940456022 }, { "content": "#[bench]\n\nfn bitvec_rep(b: &mut Bencher) {\n\n\tb.iter(|| bitvec![0; 16 * 16 * 9]);\n\n\tb.iter(|| bitvec![1; 16 * 16 * 9]);\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 11, "score": 109430.49940456022 }, { "content": "#[bench]\n\n#[cfg(target_pointer_width = \"64\")]\n\nfn bits_seq_u64(b: &mut Bencher) {\n\n\tb.iter(|| {\n\n\t\tbits![Local, u64;\n\n\t\t\t0, 1, 0, 1, 0, 0, 1, 1,\n\n\t\t\t0, 1, 1, 0, 0, 0, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 1,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 0, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 1, 1, 0, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 1,\n\n\t\t]\n\n\t});\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 12, "score": 106371.92281757745 }, { "content": "#[bench]\n\n#[cfg(target_pointer_width = \"64\")]\n\nfn bits_rep_u64(b: &mut Bencher) {\n\n\tb.iter(|| bits![Local, u64; 0; 120]);\n\n\tb.iter(|| bits![Local, u64; 1; 120]);\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 13, "score": 106371.92281757745 }, { "content": "#[bench]\n\nfn bits_seq_u8(b: &mut Bencher) {\n\n\tb.iter(|| {\n\n\t\tbits![Local, u8;\n\n\t\t\t0, 1, 0, 1, 0, 0, 1, 1,\n\n\t\t\t0, 1, 1, 0, 0, 0, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 1,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 0, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 1, 1, 0, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 1,\n\n\t\t]\n\n\t});\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 14, "score": 106366.82360392791 }, { "content": "#[bench]\n\nfn bits_rep_u32(b: &mut Bencher) {\n\n\tb.iter(|| bits![Local, u32; 0; 120]);\n\n\tb.iter(|| bits![Local, u32; 1; 120]);\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 15, "score": 106366.82360392791 }, { "content": "#[bench]\n\nfn bits_rep_u16(b: &mut Bencher) {\n\n\tb.iter(|| bits![Local, u16; 0; 120]);\n\n\tb.iter(|| bits![Local, u16; 1; 120]);\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 16, "score": 106366.82360392791 }, { "content": "#[bench]\n\nfn bits_rep_u8(b: &mut Bencher) {\n\n\tb.iter(|| bits![Local, u8; 0; 120]);\n\n\tb.iter(|| bits![Local, u8; 1; 120]);\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 17, "score": 106366.82360392791 }, { "content": "#[bench]\n\nfn bits_seq_u16(b: &mut Bencher) {\n\n\tb.iter(|| {\n\n\t\tbits![Local, u16;\n\n\t\t\t0, 1, 0, 1, 0, 0, 1, 1,\n\n\t\t\t0, 1, 1, 0, 0, 0, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 1,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 0, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 1, 1, 0, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 1,\n\n\t\t]\n\n\t});\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 18, "score": 106366.82360392791 }, { "content": "#[bench]\n\nfn bits_seq_u32(b: &mut Bencher) {\n\n\tb.iter(|| {\n\n\t\tbits![Local, u32;\n\n\t\t\t0, 1, 0, 1, 0, 0, 1, 1,\n\n\t\t\t0, 1, 1, 0, 0, 0, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 1,\n\n\t\t\t0, 1, 1, 1, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 0, 1, 0, 1, 1, 0, 0,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 0, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 0,\n\n\t\t\t0, 1, 1, 0, 0, 1, 0, 0,\n\n\t\t\t0, 1, 1, 0, 1, 1, 1, 1,\n\n\t\t\t0, 0, 1, 0, 0, 0, 0, 1,\n\n\t\t]\n\n\t});\n\n}\n\n\n", "file_path": "benches/macros.rs", "rank": 19, "score": 106366.82360392791 }, { "content": "pub fn verify<O>(verbose: bool)\n\nwhere O: BitOrder {\n\n\tverify_for_type::<O, u8>(verbose);\n\n\tverify_for_type::<O, u16>(verbose);\n\n\tverify_for_type::<O, u32>(verbose);\n\n\tverify_for_type::<O, usize>(verbose);\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\tverify_for_type::<O, u64>(verbose);\n\n}\n\n\n\n/** Verifies a `BitOrder` implementation’s adherence to the stated rules, for\n\none register type.\n\n\n\nThis function checks some `BitOrder` implementation against only one of the\n\n`BitMemory` types that it will encounter. This is useful if you are implementing\n\nan ordering that only needs to be concerned with a subset of the types, and you\n\nknow that you will never use it with the types it does not support.\n\n\n\n# Type Parameters\n", "file_path": "src/order.rs", "rank": 20, "score": 102848.91771630195 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn accessor<T>(x: &T) -> &T::Access\n\nwhere T: BitStore {\n\n\tunsafe { &*(x as *const T as *const T::Access) }\n\n}\n\n\n\n/// Inserts an `::Alias` marker into a `BitMask`’s type parameter.\n", "file_path": "src/devel.rs", "rank": 21, "score": 94831.57305246766 }, { "content": "pub fn verify_for_type<O, M>(verbose: bool)\n\nwhere\n\n\tO: BitOrder,\n\n\tM: BitMemory,\n\n{\n\n\tuse core::any::type_name;\n\n\tlet mut accum = BitMask::<M>::ZERO;\n\n\n\n\tlet oname = type_name::<O>();\n\n\tlet mname = type_name::<M>();\n\n\n\n\tfor n in 0 .. M::BITS {\n\n\t\t// Wrap the counter as an index.\n\n\t\tlet idx = unsafe { BitIdx::<M>::new_unchecked(n) };\n\n\n\n\t\t// Compute the bit position for the index.\n\n\t\tlet pos = O::at::<M>(idx);\n\n\t\tif verbose {\n\n\t\t\t#[cfg(feature = \"std\")]\n\n\t\t\tprintln!(\n", "file_path": "src/order.rs", "rank": 22, "score": 94674.3790862338 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn remove_mem<T>(x: T::Mem) -> T\n\nwhere T: BitStore {\n\n\tunsafe { ptr::read(&x as *const T::Mem as *const T) }\n\n}\n\n\n\n/// Gets a `NonNull<T>` base pointer from a `NonNull<[T]>` slice pointer.\n", "file_path": "src/devel.rs", "rank": 23, "score": 92262.52260803804 }, { "content": "pub trait AsBitsMut<T>\n\nwhere T: BitStore\n\n{\n\n\t/// Views memory as a slice of mutable bits.\n\n\t///\n\n\t/// # Type Parameters\n\n\t///\n\n\t/// - `O`: The bit ordering used for the region.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&mut self`: The value that is providing a bit-slice view.\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// A mutable view into some bits.\n\n\tfn as_bits_mut<O>(&mut self) -> &mut BitSlice<O, T>\n\n\twhere O: BitOrder;\n\n}\n\n\n", "file_path": "src/view.rs", "rank": 24, "score": 92238.64265938409 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn load_aliased_local<T>(x: &T::Alias) -> T::Mem\n\nwhere T: BitStore {\n\n\tx.pipe(accessor::<T::Alias>)\n\n\t\t.pipe(BitAccess::load_value)\n\n\t\t.pipe(remove_alias::<T>)\n\n}\n\n\n\n/// Converts a mutable reference into its memory register type.\n", "file_path": "src/devel.rs", "rank": 25, "score": 85607.527357502 }, { "content": "#[inline]\n\npub fn normalize_range<R>(bounds: R, end: usize) -> Range<usize>\n\nwhere R: RangeBounds<usize> {\n\n\tlet min = match bounds.start_bound() {\n\n\t\tBound::Included(&n) => n,\n\n\t\tBound::Excluded(&n) => n + 1,\n\n\t\tBound::Unbounded => 0,\n\n\t};\n\n\tlet max = match bounds.end_bound() {\n\n\t\tBound::Included(&n) => n + 1,\n\n\t\tBound::Excluded(&n) => n,\n\n\t\tBound::Unbounded => end,\n\n\t};\n\n\tmin .. max\n\n}\n\n\n\n/** Asserts that a range satisfies bounds constraints.\n\n\n\nThis requires that the range start be not greater than the range end, and the\n\nrange end be not greater than the ending marker (if provided).\n\n\n\n# Parameters\n\n\n\n- `range`: The range to validate\n\n- `end`: An optional maximal value that the range cannot exceed\n\n\n\n# Panics\n\n\n\nThis panics if the range fails a requirement.\n\n**/\n", "file_path": "src/devel.rs", "rank": 26, "score": 81734.98809877416 }, { "content": "#[inline]\n\npub fn assert_range(range: Range<usize>, end: impl Into<Option<usize>>) {\n\n\tif range.start > range.end {\n\n\t\tpanic!(\n\n\t\t\t\"Malformed range: `{} .. {}` must run from lower to higher\",\n\n\t\t\trange.start, range.end\n\n\t\t);\n\n\t}\n\n\tif let Some(end) = end.into() {\n\n\t\tif range.end > end {\n\n\t\t\tpanic!(\n\n\t\t\t\t\"Range out of bounds: `{} .. {}` must not exceed `{}`\",\n\n\t\t\t\trange.start, range.end, end\n\n\t\t\t);\n\n\t\t}\n\n\t}\n\n}\n\n\n\n#[cfg(all(test, feature = \"std\"))]\n\nmod tests {\n\n\tuse super::*;\n\n\tuse std::panic::catch_unwind;\n\n\n\n\t#[test]\n\n\tfn check_range_asserts() {\n\n\t\tassert!(catch_unwind(|| assert_range(7 .. 2, None)).is_err());\n\n\t\tassert!(catch_unwind(|| assert_range(0 .. 8, 4)).is_err());\n\n\t}\n\n}\n", "file_path": "src/devel.rs", "rank": 27, "score": 80099.92771973688 }, { "content": "#[inline(always)]\n\npub fn from_ref<O, T>(elem: &T) -> &BitSlice<O, T>\n\nwhere\n\n\tO: BitOrder,\n\n\tT: BitStore + BitMemory,\n\n{\n\n\tBitSlice::from_element(elem)\n\n}\n\n\n\n/** Converts a reference to `T` into a bitslice over one element.\n\n\n\n# Original\n\n\n\n[`slice::from_mut`](https://doc.rust-lang.org/core/slice/fn.from_mut.html)\n\n**/\n", "file_path": "src/slice/api.rs", "rank": 28, "score": 79852.52897116836 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn alias_mem<T>(x: T::Mem) -> <T::Alias as BitStore>::Mem\n\nwhere T: BitStore {\n\n\tunsafe { *(&x as *const _ as *const _) }\n\n}\n\n\n\n/// Loads through an aliased reference into an unmarked local.\n", "file_path": "src/devel.rs", "rank": 29, "score": 76759.77638173106 }, { "content": "#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\npub fn remove_alias<T>(x: <<T as BitStore>::Alias as BitStore>::Mem) -> T::Mem\n\nwhere T: BitStore {\n\n\tunsafe { *(&x as *const _ as *const _) }\n\n}\n\n\n\n/// Removes the `::Alias` marker from a `BitPtr`’s referent type.\n", "file_path": "src/devel.rs", "rank": 30, "score": 70881.0713678061 }, { "content": "struct BitPtr {\n\n uintptr_t ptr_head : __builtin_ctzll(alignof(T));\n\n uintptr_t ptr_addr : sizeof(uintptr_T) * 8 - __builtin_ctzll(alignof(T));\n\n\n\n size_t len_head : 3;\n\n size_t len_bits : sizeof(size_t) * 8 - 3;\n\n};\n\n```\n\n\n\nThis means that the `BitPtr<T>` has three *logical* fields, stored in four\n\nsegments across the two *structural* fields of the type. The widths and\n\nplacements of each segment are functions of the size of `*const T` and `usize`,\n\nand of the alignment of the `T` referent buffer element type.\n\n\n\n# Fields\n\n\n\nThis section describes the purpose, semantic meaning, and layout of the three\n\nlogical fields.\n\n\n\n## Base Address\n", "file_path": "src/pointer.rs", "rank": 31, "score": 67870.83374803641 }, { "content": "#[cfg(feature = \"alloc\")]\n\n#[test]\n\nfn issue_33() {\n\n\tlet mut swdio = BitVec::<Lsb0, u8>::new();\n\n\n\n\tswdio.resize(64, true);\n\n\n\n\tlet mut seq = 0xE79E; // LSb first\n\n\tfor _ in 0 .. 16 {\n\n\t\tswdio.push(seq & 0b1 != 0);\n\n\t\tseq >>= 1;\n\n\t}\n\n\n\n\tswdio.reserve(64);\n\n\tswdio.resize(swdio.len() + 64, true);\n\n\n\n\tswdio.resize(swdio.len() + 10, false);\n\n}\n", "file_path": "tests/issue_33.rs", "rank": 32, "score": 65778.65056081582 }, { "content": "#[cfg(feature = \"alloc\")]\n\n#[test]\n\nfn issue_10() {\n\n\tlet bv = bitvec![Local, u8;\n\n\t\t0, 0, 0, 0,\n\n\t\t0, 0, 0, 1,\n\n\t\t1, 0, 0, 0,\n\n\t\t0, 0, 0, 1,\n\n\t];\n\n\n\n\tlet slice = &bv[4 .. 12];\n\n\tassert_eq!(slice.len(), 8);\n\n\tassert!(!slice[0]);\n\n\tassert!(slice[3]);\n\n\tassert!(slice[4]);\n\n\tassert!(!slice[7]);\n\n\n\n\tlet mut bv2 = slice.to_owned();\n\n\tassert_eq!(bv2, slice);\n\n\tassert!(!bv2[0]);\n\n\tassert!(bv2[3]);\n\n\tassert!(bv2[4]);\n\n\tassert!(!bv2[7]);\n\n\n\n\tbv2.force_align();\n\n\t// These may be removed in the future.\n\n\tassert_eq!(bv2.as_slice().len(), 1);\n\n\tassert_eq!(bv2.as_slice()[0], 0x18);\n\n}\n", "file_path": "tests/issue_10.rs", "rank": 33, "score": 65778.65056081582 }, { "content": "#[test]\n\n#[cfg(feature = \"alloc\")]\n\nfn issue_65() {\n\n\tlet mut v = BitVec::<Msb0, u8>::default();\n\n\n\n\tv.extend_from_bitslice(&bits![Msb0, u8; 0, 1]);\n\n\n\n\tassert_eq!(v.into_vec(), [0b0100_0000]);\n\n}\n", "file_path": "tests/issue_65.rs", "rank": 34, "score": 65778.65056081582 }, { "content": "#[cfg(not(feature = \"std\"))]\n\nfn main() {\n\n\t// This example requires the standard library.\n\n}\n", "file_path": "examples/tour.rs", "rank": 35, "score": 65778.65056081582 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\n#[cfg(feature = \"alloc\")]\n\nfn with_alloc() {\n\n\tlet a = bits![Msb0, u8; 0, 1];\n\n\tlet b = bitbox![Lsb0, u16; 0, 1];\n\n\tlet c = bitvec![0, 1];\n\n\n\n\tassert_eq!(a, a); assert_eq!(a, b); assert_eq!(a, c);\n\n\tassert_eq!(b, a); assert_eq!(b, b); assert_eq!(b, c);\n\n\tassert_eq!(c, a); assert_eq!(c, b); assert_eq!(c, c);\n\n}\n", "file_path": "tests/equality.rs", "rank": 36, "score": 65778.65056081582 }, { "content": "#[cfg(not(feature = \"std\"))]\n\nfn main() {\n\n\t// This example requires the standard library.\n\n}\n", "file_path": "examples/sieve.rs", "rank": 37, "score": 65778.65056081582 }, { "content": "fn main() {\n\n\teprintln!(\"Press <Enter> to move through the steps of the example\");\n\n\tparse(build());\n\n}\n\n\n", "file_path": "examples/ipv4.rs", "rank": 38, "score": 65778.65056081582 }, { "content": "#[test]\n\nfn no_alloc() {\n\n\tlet a = bits![mut Msb0, u8; 0, 1];\n\n\tlet b = bits![mut Lsb0, u16; 0, 1];\n\n\tlet c = bits![mut 1, 0];\n\n\n\n\t// BitSlice as PartialEq<BitSlice>\n\n\tassert_eq!(*a, *b);\n\n\t// BitSlice as PartialEq<&mut BitSlice>\n\n\tassert_eq!(*a, b);\n\n\t// &mut BitSlice as PartialEq<BitSlice>\n\n\tassert_eq!(a, *b);\n\n\t// &mut BitSlice as PartialEq<&mut BitSlice>\n\n\tassert_eq!(a, b);\n\n\n\n\t// &BitSlice as PartialEq<&BitSlice>\n\n\tassert_eq!(&*a, &*b);\n\n\t// &BitSlice as PartialEq<BitSlice>\n\n\tassert_eq!(&*a, *b);\n\n\t// BitSlice as PartialEq<&BitSlice>\n\n\tassert_eq!(*a, &*b);\n", "file_path": "tests/equality.rs", "rank": 39, "score": 65778.65056081582 }, { "content": "#[cfg(feature = \"std\")]\n\nfn snooze() {\n\n\tthread::sleep(Duration::from_millis(10));\n\n}\n\n\n", "file_path": "examples/aliasing.rs", "rank": 40, "score": 65778.65056081582 }, { "content": "#[cfg(not(feature = \"std\"))]\n\nfn main() {\n\n\t// This example requires the presence of a standard library.\n\n}\n", "file_path": "examples/aliasing.rs", "rank": 41, "score": 65778.65056081582 }, { "content": "\t#[doc(hidden)]\n\n\tpub trait Sealed {}\n\n}\n\n\n\n#[cfg(test)]\n\n#[cfg(not(tarpaulin_include))]\n\nmod tests {\n\n\tuse crate::prelude::*;\n\n\tuse core::cell::Cell;\n\n\tuse static_assertions::*;\n\n\n\n\t#[test]\n\n\tfn traits() {\n\n\t\t// The integers are threadsafe, as they are known to be unaliased.\n\n\t\tassert_impl_all!(BitSlice<Local, u8>: Send, Sync);\n\n\t\tassert_impl_all!(BitSlice<Local, u16>: Send, Sync);\n\n\t\tassert_impl_all!(BitSlice<Local, u32>: Send, Sync);\n\n\t\tassert_impl_all!(BitSlice<Local, usize>: Send, Sync);\n\n\n\n\t\t#[cfg(target_pointer_width = \"64\")]\n\n\t\tassert_impl_all!(BitSlice<Local, u64>: Send, Sync);\n", "file_path": "src/store.rs", "rank": 42, "score": 64035.76697512494 }, { "content": "\t#[doc(hidden)]\n\n\tpub trait Sealed {}\n\n}\n", "file_path": "src/mem.rs", "rank": 43, "score": 64035.76697512494 }, { "content": "#[test]\n\nfn inspect() {\n\n\tlet bv = bitvec![Local, u16; 0; 40];\n\n\tassert_eq!(bv.elements(), 3);\n\n}\n\n\n", "file_path": "src/vec/tests.rs", "rank": 44, "score": 63726.177300065705 }, { "content": "#[test]\n\n#[allow(deprecated)]\n\nfn api() {\n\n\tlet boxed: Box<[u8]> = Box::new([0; 4]);\n\n\tlet bb = BitBox::<Local, _>::from_boxed_slice(boxed);\n\n\tassert_eq!(bb, bits![0; 32]);\n\n\tlet boxed = bb.into_boxed_slice();\n\n\tassert_eq!(boxed[..], [0u8; 4][..]);\n\n\n\n\tlet pinned = BitBox::pin(bits![0, 1, 0, 1]);\n\n\tlet unpinned = BitBox::new(bits![0, 1, 0, 1]);\n\n\tassert_eq!(pinned.as_ref().get_ref(), unpinned[..]);\n\n\n\n\tlet boxed = bitbox![0; 10];\n\n\tlet bitptr = boxed.bitptr();\n\n\tlet reboxed = unsafe { BitBox::from_raw(BitBox::into_raw(boxed)) };\n\n\tlet bv = reboxed.into_bitvec();\n\n\tlet bb = bv.into_boxed_bitslice();\n\n\tassert_eq!(bb.bitptr(), bitptr);\n\n}\n", "file_path": "src/boxed/tests.rs", "rank": 45, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn test_bitvec1() {\n\n\tlet data = 0x03ABu32;\n\n\tlet data_bits = data.write(true, Some(10));\n\n\n\n\tassert_eq!(bitvec![Msb0, u8; 1,0,1,0,1,0,1,1, 1,1], data_bits);\n\n\tlet data_vec = data_bits.into_vec();\n\n\n\n\tassert_eq!(vec![0xAB, 0b11_000000], data_vec);\n\n}\n\n\n", "file_path": "tests/issue_62.rs", "rank": 46, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn iterators() {\n\n\t0b0100_1000u8\n\n\t\t.view_bits::<Msb0>()\n\n\t\t.split(|_, bit| *bit)\n\n\t\t.zip([1usize, 2, 3].iter())\n\n\t\t.for_each(|(bits, len)| assert_eq!(bits.len(), *len));\n\n\n\n\tlet mut data = 0b0100_1000u8;\n\n\tdata.view_bits_mut::<Msb0>()\n\n\t\t.split_mut(|_, bit| *bit)\n\n\t\t.zip([1usize, 2, 3].iter())\n\n\t\t.for_each(|(bits, len)| {\n\n\t\t\tassert_eq!(bits.len(), *len);\n\n\t\t\tbits.set_all(true)\n\n\t\t});\n\n\tassert_eq!(data, !0);\n\n\n\n\t0b0100_1000u8\n\n\t\t.view_bits::<Msb0>()\n\n\t\t.rsplit(|_, bit| *bit)\n", "file_path": "src/slice/tests.rs", "rank": 47, "score": 63726.177300065705 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn prove_custom() {\n\n verify::<Custom>();\n\n}\n\n```\n\n\n\n[`verify`]: fn.verify.html\n\n**/\n\npub unsafe trait BitOrder {\n\n\t/// Converts a semantic bit index into an electrical bit position.\n\n\t///\n\n\t/// This function is the basis of the trait, and must adhere to a number of\n\n\t/// requirements in order for an implementation to be considered correct.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `index`: The semantic index of a bit within an element `M`.\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// The electrical position of the indexed bit within an element `M`. See\n", "file_path": "src/order.rs", "rank": 48, "score": 63726.177300065705 }, { "content": "#[test]\n\n#[should_panic(expected = \"Vector capacity exceeded\")]\n\nfn overcommit() {\n\n\tBitVec::<Local, usize>::with_capacity(\n\n\t\tBitSlice::<Local, usize>::MAX_BITS + 1,\n\n\t);\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n\texpected = \"Attempted to reconstruct a `BitVec` from a null pointer\"\n\n)]\n", "file_path": "src/vec/tests.rs", "rank": 49, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn test_bitvec3() {\n\n\tlet data = 0xDDCCBBAA;\n\n\tlet data_bits = data.write(true, None).into_vec();\n\n\n\n\tassert_eq!(vec![0xAA, 0xBB, 0xCC, 0xDD], data_bits);\n\n}\n\n\n", "file_path": "tests/issue_62.rs", "rank": 50, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn misc() {\n\n\tlet mut bv = bitvec![1; 10];\n\n\tbv.truncate(20);\n\n\tassert_eq!(bv, bits![1; 10]);\n\n\tbv.truncate(5);\n\n\tassert_eq!(bv, bits![1; 5]);\n\n\n\n\tlet mut bv = bitvec![0, 0, 1, 0, 0];\n\n\tassert!(bv.swap_remove(2));\n\n\tassert!(bv.not_any());\n\n\n\n\tbv.insert(2, true);\n\n\tassert_eq!(bv, bits![0, 0, 1, 0, 0]);\n\n\n\n\tbv.remove(2);\n\n\tassert!(bv.not_any());\n\n\n\n\tlet mut bv = bitvec![0, 0, 1, 1, 0, 1, 0, 1, 0, 0];\n\n\tbv.retain(|idx, bit| !(idx & 1 == 0 && *bit));\n\n\t// ^^^ even ^^^ prime\n", "file_path": "src/vec/tests.rs", "rank": 51, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn push() {\n\n\tlet mut bvm08 = BitVec::<Msb0, u8>::new();\n\n\tassert!(bvm08.is_empty());\n\n\n\n\tbvm08.push(false);\n\n\tassert_eq!(bvm08.len(), 1);\n\n\tassert!(!bvm08[0]);\n\n\n\n\tbvm08.push(true);\n\n\tassert_eq!(bvm08.len(), 2);\n\n\tassert!(bvm08[1]);\n\n\n\n\tbvm08.extend(&[true; 3]);\n\n\tbvm08.extend(&[false; 3]);\n\n\tassert_eq!(bvm08, bits![0, 1, 1, 1, 1, 0, 0, 0]);\n\n}\n\n\n", "file_path": "src/vec/tests.rs", "rank": 52, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn alignment() {\n\n\tlet mut data = [0u16; 5];\n\n\tlet addr = &data as *const [u16; 5] as *const u16 as usize;\n\n\tlet bits = data.view_bits_mut::<Local>();\n\n\n\n\tlet (head, body, tail) = unsafe { bits[5 .. 75].align_to_mut::<u32>() };\n\n\n\n\t// `data` is aligned to the back half of a `u32`\n\n\tif addr % 4 == 2 {\n\n\t\tassert_eq!(head.len(), 11);\n\n\t\tassert_eq!(body.len(), 59);\n\n\t\tassert!(tail.is_empty());\n\n\t}\n\n\t// `data` is aligned to the front half of a `u32`\n\n\telse {\n\n\t\tassert!(head.is_empty());\n\n\t\tassert_eq!(body.len(), 64);\n\n\t\tassert_eq!(tail.len(), 6);\n\n\t}\n\n}\n", "file_path": "src/slice/tests.rs", "rank": 53, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn cloning() {\n\n\tlet mut a = bitvec![0];\n\n\tlet b = bitvec![1; 20];\n\n\n\n\tassert_ne!(a, b);\n\n\ta.clone_from(&b);\n\n\tassert_eq!(a, b);\n\n}\n", "file_path": "src/vec/tests.rs", "rank": 54, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn modify() {\n\n\tlet mut data = 0b0000_1111u8;\n\n\n\n\tlet bits = data.view_bits_mut::<Local>();\n\n\tbits.swap(3, 4);\n\n\tassert_eq!(data, 0b0001_0111);\n\n\n\n\tlet bits = data.view_bits_mut::<Lsb0>();\n\n\tbits[1 .. 7].reverse();\n\n\tassert_eq!(data, 0b0110_1001);\n\n\tdata.view_bits_mut::<Msb0>()[1 .. 7].reverse();\n\n\n\n\tlet bits = data.view_bits_mut::<Msb0>();\n\n\tbits.copy_within(2 .. 4, 0);\n\n\tassert_eq!(data, 0b0101_0111);\n\n\n\n\tlet bits = data.view_bits_mut::<Msb0>();\n\n\tbits.copy_within(5 .., 2);\n\n\tassert_eq!(data, 0b0111_1111);\n\n}\n\n\n", "file_path": "src/slice/tests.rs", "rank": 55, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn reservations() {\n\n\tlet mut bv = bitvec![1; 40];\n\n\tassert!(bv.capacity() >= 40);\n\n\tbv.reserve(100);\n\n\tassert!(bv.capacity() >= 140, \"{}\", bv.capacity());\n\n\tbv.shrink_to_fit();\n\n\tassert!(bv.capacity() >= 40);\n\n\n\n\t// Trip the first assertion by wrapping around the `usize` boundary.\n\n\tassert!(\n\n\t\tcatch_unwind(|| {\n\n\t\t\tlet mut bv = bitvec![1; 100];\n\n\t\t\tbv.reserve(!0 - 50);\n\n\t\t})\n\n\t\t.is_err()\n\n\t);\n\n\n\n\t// Trip the second assertion by exceeding `MAX_BITS` without wrapping.\n\n\tassert!(\n\n\t\tcatch_unwind(|| {\n", "file_path": "src/vec/tests.rs", "rank": 56, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn construction() {\n\n\tuse core::slice;\n\n\tlet data = 0u8;\n\n\tlet bits = data.view_bits::<Local>();\n\n\tassert_eq!(bits.len(), 8);\n\n\n\n\tassert!(\n\n\t\tBitSlice::<Local, u8>::from_slice(unsafe {\n\n\t\t\tslice::from_raw_parts(\n\n\t\t\t\t1usize as *const _,\n\n\t\t\t\tBitSlice::<Local, u8>::MAX_ELTS,\n\n\t\t\t)\n\n\t\t})\n\n\t\t.is_none()\n\n\t);\n\n\n\n\tassert!(\n\n\t\tBitSlice::<Local, u8>::from_slice_mut(unsafe {\n\n\t\t\tslice::from_raw_parts_mut(\n\n\t\t\t\t1usize as *mut _,\n", "file_path": "src/slice/tests.rs", "rank": 57, "score": 63726.177300065705 }, { "content": "#[test]\n\n#[cfg(all(feature = \"alloc\", feature = \"serde\"))]\n\nfn serdes_vector() {\n\n\tlet bv = bitvec![Msb0, u8; 1, 0, 1, 1, 0, 0, 1, 0];\n\n\tlet json = serde_json::to_string(&bv).expect(\"cannot fail to serialize\");\n\n\tassert_eq!(json.trim(), r#\"{\"head\":0,\"bits\":8,\"data\":[178]}\"#);\n\n\n\n\tlet bb: BitBox<Msb0, u8> =\n\n\t\tserde_json::from_str(&json).expect(\"cannot fail to deserialize\");\n\n\n\n\tassert!(bb[0]);\n\n\tassert_eq!(bb.as_slice()[0], 178);\n\n}\n", "file_path": "tests/serdes.rs", "rank": 58, "score": 63726.177300065705 }, { "content": "fn from_null() {\n\n\tunsafe {\n\n\t\tBitVec::from_raw_parts(\n\n\t\t\tptr::slice_from_raw_parts_mut(ptr::null_mut::<u8>(), 64)\n\n\t\t\t\tas *mut BitSlice<Local, usize>,\n\n\t\t\t0,\n\n\t\t);\n\n\t}\n\n}\n\n\n", "file_path": "src/vec/tests.rs", "rank": 59, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn query() {\n\n\tlet data = [0x0Fu8, !0, 0xF0, 0, 0x0E];\n\n\tlet bits = data.view_bits::<Msb0>();\n\n\n\n\tassert!(bits[36 .. 39].all());\n\n\tassert!(bits[4 .. 20].all());\n\n\tassert!(bits[.. 8].any());\n\n\tassert!(bits[4 .. 20].any());\n\n\tassert!(bits[32 ..].not_all());\n\n\tassert!(bits[.. 4].not_any());\n\n\tassert!(bits[.. 8].some());\n\n\n\n\tassert_eq!(bits[1 .. 7].count_ones(), 3);\n\n\tassert_eq!(bits[1 .. 7].count_zeros(), 3);\n\n\tassert_eq!(bits[.. 24].count_ones(), 16);\n\n\tassert_eq!(bits[16 ..].count_zeros(), 17);\n\n\n\n\tassert!(!bits![0].contains(bits![0, 1]));\n\n\tassert!(bits![0, 1, 0].contains(bits![1, 0]));\n\n\tassert!(bits![0, 1, 0].starts_with(bits![0, 1]));\n\n\tassert!(bits![0, 1, 0].ends_with(bits![1, 0]));\n\n}\n\n\n", "file_path": "src/slice/tests.rs", "rank": 60, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn split() {\n\n\tassert!(BitSlice::<Local, usize>::empty().split_first().is_none());\n\n\tassert_eq!(\n\n\t\t1u8.view_bits::<Lsb0>().split_first(),\n\n\t\tSome((&true, bits![Lsb0, u8; 0; 7]))\n\n\t);\n\n\n\n\tassert!(\n\n\t\tBitSlice::<Local, usize>::empty_mut()\n\n\t\t\t.split_first_mut()\n\n\t\t\t.is_none()\n\n\t);\n\n\tlet mut data = 0u8;\n\n\tlet (head, _) = data.view_bits_mut::<Lsb0>().split_first_mut().unwrap();\n\n\thead.set(true);\n\n\tassert_eq!(data, 1);\n\n\n\n\tassert!(BitSlice::<Local, usize>::empty().split_last().is_none());\n\n\tassert_eq!(\n\n\t\t1u8.view_bits::<Msb0>().split_last(),\n", "file_path": "src/slice/tests.rs", "rank": 61, "score": 63726.177300065705 }, { "content": "#[test]\n\n#[cfg(all(feature = \"alloc\", feature = \"serde\"))]\n\nfn serdes_array() {\n\n\tlet ba = bitarr![Msb0, u8; 1, 0, 1, 1, 0, 0, 1, 0];\n\n\tlet json = serde_json::to_string(&ba).expect(\"cannot fail to serialize\");\n\n\tassert_eq!(json.trim(), r#\"[178]\"#);\n\n\n\n\tlet ba: BitArray<Msb0, [u8; 1]> =\n\n\t\tserde_json::from_str(&json).expect(\"cannot fail to deserialize\");\n\n\tassert!(ba[0]);\n\n\tassert_eq!(ba.as_slice()[0], 178);\n\n\n\n\t// Note: Scalar arrays do not (yet) serialize as a sequence of one element.\n\n\tlet ba_bare: BitArray<Msb0, u8> =\n\n\t\tserde_json::from_str(&\"178\").expect(\"cannot fail to deserialize\");\n\n\tassert_eq!(ba.as_bitslice(), ba_bare.as_bitslice());\n\n}\n\n\n", "file_path": "tests/serdes.rs", "rank": 62, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn test_bitvec4() {\n\n\tlet data = 0xDDCCBBAA;\n\n\tlet data_bits = data.write(false, None).into_vec();\n\n\n\n\tassert_eq!(vec![0xDD, 0xCC, 0xBB, 0xAA], data_bits);\n\n}\n", "file_path": "tests/issue_62.rs", "rank": 63, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn from_vec() {\n\n\tlet bv = BitVec::<Msb0, u8>::from_vec(vec![0, 1, 2, 3]);\n\n\tassert_eq!(bv.len(), 32);\n\n\tassert_eq!(bv.count_ones(), 4);\n\n}\n\n\n", "file_path": "src/vec/tests.rs", "rank": 64, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn iterators() {\n\n\tlet data = 0x35u8.view_bits::<Msb0>();\n\n\tlet bv: BitVec<Msb0, u8> = data.iter().collect();\n\n\tassert_eq!(bv.count_ones(), 4);\n\n\n\n\tfor (l, r) in (&bv).into_iter().zip(bits![0, 0, 1, 1, 0, 1, 0, 1]) {\n\n\t\t/* Unimportant but interesting implementation detail: all accessors in\n\n\t\tthe crate that return an `&bool` use the same two addresses, because\n\n\t\tthe compiler unifies `&literal` references into secret statics. You\n\n\t\tcould argue that, much like YAML accepting yes/no as boolean literals,\n\n\t\tthere are now four valid boolean values in the crate: `true`, `false`,\n\n\t\tand the addresses of their secret statics.\n\n\n\n\t\tSwitch to a by-value comparison instead of by-ref if this test fails.\n\n\t\t*/\n\n\t\tassert_eq!(l as *const _, r as *const _);\n\n\t}\n\n\n\n\tlet mut iter = bv.clone().into_iter();\n\n\tassert!(!iter.next().unwrap());\n", "file_path": "src/vec/tests.rs", "rank": 65, "score": 63726.177300065705 }, { "content": "#[test]\n\nfn test_bitvec2() {\n\n\tlet data = 0x03ABu32;\n\n\tlet data_bits = data.write(false, Some(10)).into_vec();\n\n\n\n\tassert_eq!(vec![0b11, 0xAB], data_bits);\n\n}\n\n\n", "file_path": "tests/issue_62.rs", "rank": 66, "score": 63726.177300065705 }, { "content": "pub trait BitField {\n\n\t/// Loads the bits in the `self` region into a local value.\n\n\t///\n\n\t/// This can load into any of the unsigned integers which implement\n\n\t/// `BitMemory`. Any further transformation must be done by the user.\n\n\t///\n\n\t/// The default implementation of this function calls [`load_le`] on\n\n\t/// little-endian byte-ordered CPUs, and [`load_be`] on big-endian\n\n\t/// byte-ordered CPUs.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&self`: A read reference to some bits in memory. This slice must be\n\n\t/// trimmed to have a width no more than the `M::BITS` width of the type\n\n\t/// being loaded. This can be accomplished with range indexing on a larger\n\n\t/// slice.\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// A value `M` whose least `self.len()` significant bits are filled with\n", "file_path": "src/field.rs", "rank": 67, "score": 62172.386458982546 }, { "content": "pub trait BitView {\n\n\t/// The access-control type of the storage region.\n\n\ttype Store: BitStore;\n\n\n\n\t/// The underlying register type of the storage region.\n\n\ttype Mem: BitMemory;\n\n\n\n\t/// Views a memory region as a `BitSlice`.\n\n\t///\n\n\t/// # Type Parameters\n\n\t///\n\n\t/// - `O`: The bit ordering used for the region.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&self`: The region to view as individual bits.\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// A `&BitSlice` view over the region at `*self`.\n", "file_path": "src/view.rs", "rank": 68, "score": 62172.386458982546 }, { "content": "#[test]\n\n#[should_panic]\n\nfn check_panic() {\n\n\tcheck(\"fail\", 10, 8);\n\n}\n", "file_path": "src/field/tests.rs", "rank": 69, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn byte_fields() {\n\n\tlet mut data = [0u8; 3];\n\n\n\n\tdata.view_bits_mut::<Msb0>()[4 .. 20].store_be(0xABCDu16);\n\n\tassert_eq!(data, [0x0A, 0xBC, 0xD0]);\n\n\tassert_eq!(data.view_bits::<Msb0>()[4 .. 20].load_be::<u16>(), 0xABCD);\n\n\n\n\tdata.view_bits_mut::<Msb0>()[2 .. 6].store_be(9u8);\n\n\tassert_eq!(data, [0x26, 0xBC, 0xD0]);\n\n\tassert_eq!(data.view_bits::<Msb0>()[2 .. 6].load_be::<u8>(), 9);\n\n\n\n\tdata = [0; 3];\n\n\tdata.view_bits_mut::<Lsb0>()[4 .. 20].store_be(0xABCDu16);\n\n\tassert_eq!(data, [0xA0, 0xBC, 0x0D]);\n\n\tassert_eq!(data.view_bits::<Lsb0>()[4 .. 20].load_be::<u16>(), 0xABCD);\n\n\n\n\tdata.view_bits_mut::<Lsb0>()[2 .. 6].store_be(9u8);\n\n\t// 0b1010_0000 | 0b00_1001_00\n\n\tassert_eq!(data, [0xA4, 0xBC, 0x0D]);\n\n\tassert_eq!(data.view_bits::<Lsb0>()[2 .. 6].load_be::<u8>(), 9);\n", "file_path": "src/field/tests.rs", "rank": 70, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn l08() {\n\n\tlet bits = bits![mut Lsb0, u8; 0; 32];\n\n\n\n\tfor i in 0 .. 8 {\n\n\t\tfor n in 0u8 ..= !0 {\n\n\t\t\tbits[i ..][.. 8].store_le::<u8>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 8].load_le::<u8>(), n);\n\n\t\t}\n\n\t}\n\n\n\n\tfor i in 0 .. 16 {\n\n\t\tfor n in 0u16 ..= !0 {\n\n\t\t\tbits[i ..][.. 16].store_le::<u16>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 16].load_le::<u16>(), n);\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/field/permutation_tests.rs", "rank": 71, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn get_value() {\n\n\tlet data = [5u32 << 3, 0x01234567, !5];\n\n\tlet bits = data.view_bits::<Lsb0>();\n\n\n\n\tif let Domain::Enclave { head, elem, tail } = bits[3 .. 6].domain() {\n\n\t\tlet byte = get::<u32, u8>(elem, Lsb0::mask(head, tail), 3);\n\n\t\tassert_eq!(byte, 5u8);\n\n\t}\n\n\telse {\n\n\t\tunreachable!(\"it does\");\n\n\t}\n\n\n\n\tif let Domain::Region {\n\n\t\thead: None,\n\n\t\tbody: &[],\n\n\t\ttail: Some((elem, tail)),\n\n\t} = bits[32 .. 48].domain()\n\n\t{\n\n\t\tlet short = get::<u32, u16>(elem, Lsb0::mask(None, tail), 0);\n\n\t\tassert_eq!(short, 0x4567u16);\n", "file_path": "src/field/tests.rs", "rank": 72, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn l16() {\n\n\tlet bits = bits![mut Lsb0, u16; 0; 32];\n\n\n\n\tfor i in 0 .. 8 {\n\n\t\tfor n in 0u8 ..= !0 {\n\n\t\t\tbits[i ..][.. 8].store_le::<u8>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 8].load_le::<u8>(), n);\n\n\t\t}\n\n\t}\n\n\n\n\tfor i in 0 .. 16 {\n\n\t\tfor n in 0u16 ..= !0 {\n\n\t\t\tbits[i ..][.. 16].store_le::<u16>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 16].load_le::<u16>(), n);\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/field/permutation_tests.rs", "rank": 73, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn m08() {\n\n\tlet bits = bits![mut Msb0, u8; 0; 32];\n\n\n\n\tfor i in 0 .. 8 {\n\n\t\tfor n in 0u8 ..= !0 {\n\n\t\t\tbits[i ..][.. 8].store_le::<u8>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 8].load_le::<u8>(), n);\n\n\t\t}\n\n\t}\n\n\n\n\tfor i in 0 .. 16 {\n\n\t\tfor n in 0u16 ..= !0 {\n\n\t\t\tbits[i ..][.. 16].store_le::<u16>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 16].load_le::<u16>(), n);\n\n\t\t}\n\n\t}\n\n}\n\n\n", "file_path": "src/field/permutation_tests.rs", "rank": 74, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn force_align() {\n\n\tlet data = 0xA5u8;\n\n\tlet bits = data.view_bits::<Msb0>();\n\n\n\n\tlet mut bv = bits[2 ..].to_bitvec();\n\n\tassert_eq!(bv.as_slice(), &[0xA5u8]);\n\n\tbv.force_align();\n\n\tassert_eq!(bv.as_slice(), &[0b1001_0101]);\n\n\tbv.force_align();\n\n\tassert_eq!(bv.as_slice(), &[0b1001_0101]);\n\n}\n\n\n", "file_path": "src/vec/tests.rs", "rank": 75, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn m16() {\n\n\tlet bits = bits![mut Msb0, u16; 0; 32];\n\n\n\n\tfor i in 0 .. 8 {\n\n\t\tfor n in 0u8 ..= !0 {\n\n\t\t\tbits[i ..][.. 8].store_le::<u8>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 8].load_le::<u8>(), n);\n\n\t\t}\n\n\t}\n\n\n\n\tfor i in 0 .. 16 {\n\n\t\tfor n in 0u16 ..= !0 {\n\n\t\t\tbits[i ..][.. 16].store_le::<u16>(n);\n\n\t\t\tassert_eq!(bits[i ..][.. 16].load_le::<u16>(), n);\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "src/field/permutation_tests.rs", "rank": 76, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn get_set() {\n\n\tlet mut data = 0u8;\n\n\tlet bits = data.view_bits_mut::<Local>();\n\n\n\n\tfor n in 0 .. 8 {\n\n\t\tassert!(!bits.get(n).unwrap());\n\n\t\tbits.set(n, true);\n\n\t\tassert!(bits.get(n).unwrap());\n\n\t}\n\n\n\n\tassert_eq!(bits.first(), Some(&true));\n\n\t*bits.first_mut().unwrap() = false;\n\n\tassert_eq!(bits.last(), Some(&true));\n\n\t*bits.last_mut().unwrap() = false;\n\n\n\n\tlet (a, b) = (bits![mut Msb0, u8; 0, 1], bits![mut Lsb0, u16; 1, 0]);\n\n\tassert_eq!(a, bits![0, 1]);\n\n\tassert_eq!(b, bits![1, 0]);\n\n\ta.swap_with_bitslice(b);\n\n\tassert_eq!(a, bits![1, 0]);\n\n\tassert_eq!(b, bits![0, 1]);\n\n}\n\n\n", "file_path": "src/slice/tests.rs", "rank": 77, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn set_value() {\n\n\tlet mut data = [0u32; 3];\n\n\tlet bits = data.view_bits_mut::<Lsb0>();\n\n\n\n\tif let DomainMut::Enclave { head, elem, tail } = bits[3 .. 6].domain_mut() {\n\n\t\tset::<u32, u16>(elem, 13u16, Lsb0::mask(head, tail), 3);\n\n\t}\n\n\telse {\n\n\t\tunreachable!(\"it does\");\n\n\t}\n\n\n\n\tif let DomainMut::Region {\n\n\t\thead: None,\n\n\t\tbody: &mut [],\n\n\t\ttail: Some((elem, tail)),\n\n\t} = bits[32 .. 48].domain_mut()\n\n\t{\n\n\t\tset::<u32, u16>(elem, 0x4567u16, Lsb0::mask(None, tail), 0);\n\n\t}\n\n\telse {\n", "file_path": "src/field/tests.rs", "rank": 78, "score": 61876.05597036227 }, { "content": "#[test]\n\nfn check_resize() {\n\n\tassert_eq!(resize::<u8, u8>(0xA5u8), 0xA5u8);\n\n\tassert_eq!(resize::<u8, u16>(0xA5u8), 0xA5u16);\n\n\tassert_eq!(resize::<u8, u32>(0xA5u8), 0xA5u32);\n\n\n\n\tassert_eq!(resize::<u16, u8>(0x1234u16), 0x34u8);\n\n\tassert_eq!(resize::<u16, u16>(0x1234u16), 0x1234u16);\n\n\tassert_eq!(resize::<u16, u32>(0x1234u16), 0x1234u32);\n\n\n\n\tassert_eq!(resize::<u32, u8>(0x1234_5678u32), 0x78u8);\n\n\tassert_eq!(resize::<u32, u16>(0x1234_5678u32), 0x5678u16);\n\n\tassert_eq!(resize::<u32, u32>(0x1234_5678u32), 0x1234_5678u32);\n\n\n\n\t#[cfg(target_pointer_width = \"64\")]\n\n\t{\n\n\t\tassert_eq!(resize::<u8, u64>(0xA5u8), 0xA5u64);\n\n\t\tassert_eq!(resize::<u16, u64>(0x1234u16), 0x1234u64);\n\n\t\tassert_eq!(resize::<u32, u64>(0x1234_5678u32), 0x1234_5678u64);\n\n\n\n\t\tassert_eq!(resize::<u64, u8>(0x0123_4567_89AB_CDEFu64), 0xEFu8);\n\n\t\tassert_eq!(resize::<u64, u16>(0x0123_4567_89AB_CDEFu64), 0xCDEFu16);\n\n\t\tassert_eq!(resize::<u64, u32>(0x0123_4567_89AB_CDEFu64), 0x89AB_CDEFu32);\n\n\t\tassert_eq!(\n\n\t\t\tresize::<u64, u64>(0x0123_4567_89AB_CDEFu64),\n\n\t\t\t0x0123_4567_89AB_CDEFu64\n\n\t\t);\n\n\t}\n\n}\n\n\n", "file_path": "src/field/permutation_tests.rs", "rank": 79, "score": 60199.76778821552 }, { "content": "pub trait AsBits<T>\n\nwhere T: BitStore\n\n{\n\n\t/// Views memory as a slice of immutable bits.\n\n\t///\n\n\t/// # Type Parameters\n\n\t///\n\n\t/// - `O`: The bit ordering used for the region.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&self`: The value that is providing a bit-slice view.\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// An immutable view into some bits.\n\n\tfn as_bits<O>(&self) -> &BitSlice<O, T>\n\n\twhere O: BitOrder;\n\n}\n\n\n", "file_path": "src/view.rs", "rank": 80, "score": 59654.80572223288 }, { "content": "/// Build up an IPv4 packet\n\nfn build() -> Ipv4Header {\n\n\tlet mut pkt: Ipv4Header = BitArray::zeroed();\n\n\trender(\"Starting with a blank packet\", &pkt, 0 .. 0);\n\n\n\n\t// Set IPv4\n\n\tpkt[.. 4].store(4u8);\n\n\trender(\"Set IP version to 4\", &pkt, 0 .. 4);\n\n\t// Set an IHL of 5 words\n\n\tpkt[4 .. 8].store(5u8);\n\n\trender(\"Set header length to 5 words (20 bytes)\", &pkt, 4 .. 8);\n\n\t// Set the DSCP to \"low drop, class 3\" per Wikipedia\n\n\tpkt[8 .. 14].store(0b011010u8);\n\n\trender(\"Set DSCP number\", &pkt, 8 .. 14);\n\n\t// Set the ECN flag to \"ECT(0)\", per RFC 3168\n\n\tpkt[14 .. 16].store(0b10u8);\n\n\trender(\"Set ECN flag\", &pkt, 14 .. 16);\n\n\n\n\t// Set a total size of 20 bytes. The storage API will convert to\n\n\t// big-endian.\n\n\tpkt[16 .. 32].store_be(20u16);\n", "file_path": "examples/ipv4.rs", "rank": 81, "score": 59095.54633484405 }, { "content": "fn zero() -> ContainsBitfield {\n\n ContainsBitfield { data: bitarr![Msb0, u8; 0; 10] }\n\n}\n\n```\n\n\n\nThe order/store type parameters must be repeated in the macros to construct both\n\nthe typename and the value. Mismatches will result in a compiler error.\n\n**/\n\n#[macro_export]\n\nmacro_rules! bitarr {\n\n\t// Produces a typename instead of a value expression\n\n\n\n\t(for $len:literal, in $order:path, $store:ident) => {\n\n\t\t$crate::array::BitArray::<\n\n\t\t\t$order,\n\n\t\t\t[$store; $crate::mem::elts::<$store>($len)],\n\n\t\t>\n\n\t};\n\n\n\n\t(for $len:literal, in $store:ident) => {\n", "file_path": "src/macros.rs", "rank": 82, "score": 59095.54633484405 }, { "content": "pub trait BitSliceIndex<'a, O, T>\n\nwhere\n\n\tO: 'a + BitOrder,\n\n\tT: 'a + BitStore,\n\n{\n\n\t/// The output type for immutable functions.\n\n\ttype Immut;\n\n\n\n\t/// The output type for mutable functions.\n\n\ttype Mut;\n\n\n\n\t/// Returns a shared reference to the output at this location, if in bounds.\n\n\t///\n\n\t/// # Original\n\n\t///\n\n\t/// [`SliceIndex::get`](https://doc.rust-lang.org/core/slice/trait.SliceIndex.html#method.get)\n\n\tfn get(self, slice: &'a BitSlice<O, T>) -> Option<Self::Immut>;\n\n\n\n\t/// Returns a mutable reference to the output at this location, if in\n\n\t/// bounds.\n", "file_path": "src/slice/api.rs", "rank": 83, "score": 49916.797699899886 }, { "content": "pub trait BitStore: seal::Sealed + Sized + Debug {\n\n\t/// The register type that the implementor describes.\n\n\ttype Mem: BitMemory + Into<Self> + BitStore;\n\n\n\n\t/// The modifier type over `Self::Mem` used to perform memory access.\n\n\ttype Access: BitAccess<Self::Mem>;\n\n\n\n\t/// A sibling `BitStore` implementor that performs alias-aware memory\n\n\t/// access.\n\n\t///\n\n\t/// While the associated type always has the same `Mem` concrete type as\n\n\t/// `Self`, attempting to encode this requirement as `<Mem = Self::Mem>\n\n\t/// causes Rust to enter an infinite recursion in the trait solver.\n\n\t///\n\n\t/// Instead, the two `Radium` bounds inform the compiler that the `Alias` is\n\n\t/// irradiant over both the current memory and the destination memory types,\n\n\t/// allowing generic type algebra to resolve correctly even though the fact\n\n\t/// that `Radium` is only implemented once is not guaranteed.\n\n\ttype Alias: BitStore\n\n\t\t+ Radium<Self::Mem>\n", "file_path": "src/store.rs", "rank": 84, "score": 48434.1367795197 }, { "content": "fn trim<O: BitOrder, T: BitStore>(\n\n bits: &BitSlice<O, T>,\n\n to_trim: bool,\n\n) -> &BitSlice<O, T> {\n\n let stop = |b: &bool| *b != to_trim;\n\n let front = bits.iter().position(stop).unwrap_or(0);\n\n let back = bits.iter().rposition(stop).unwrap_or(0);\n\n &bits[front ..= back]\n\n}\n\n# assert_eq!(trim(bits![0, 0, 1, 1, 0, 1, 0], false), bits![1, 1, 0, 1]);\n\n```\n\n\n\nto get behavior something like\n\n`trim(&BitSlice[0, 0, 1, 1, 0, 1, 0], false) == &BitSlice[1, 1, 0, 1]`.\n\n\n\n# Documentation\n\n\n\nAll APIs that mirror something in the standard library will have an `Original`\n\nsection linking to the corresponding item. All APIs that have a different\n\nsignature or behavior than the original will have an `API Differences` section\n", "file_path": "src/slice.rs", "rank": 85, "score": 47563.46807627818 }, { "content": "#[inline]\n\nfn resize<T, U>(value: T) -> U\n\nwhere\n\n\tT: BitMemory,\n\n\tU: BitMemory,\n\n{\n\n\tlet mut out = U::ZERO;\n\n\tlet size_t = mem::size_of::<T>();\n\n\tlet size_u = mem::size_of::<U>();\n\n\n\n\tunsafe {\n\n\t\tresize_inner::<T, U>(&value, &mut out, size_t, size_u);\n\n\t}\n\n\n\n\tout\n\n}\n\n\n\n/// Performs little-endian byte-order register resizing.\n\n#[inline(always)]\n\n#[cfg(not(tarpaulin_include))]\n\n#[cfg(target_endian = \"little\")]\n", "file_path": "src/field.rs", "rank": 86, "score": 47525.274282722225 }, { "content": "fn parse(header: BitArray<Msb0, [u8; 20]>) {\n\n\tassert_eq!(ipv4_csum(&header[..]), 0);\n\n\n\n\t// Check that the version field is `4`, by `load`ing it and by direct\n\n\t// inspection\n\n\tassert_eq!(header[.. 4].load::<u8>(), 4);\n\n\tassert_eq!(header[.. 8].load::<u8>() & 0xF0, 0x40);\n\n\n\n\tlet ihl = header[4 .. 8].load::<u8>() as usize;\n\n\tassert!((5 .. 16).contains(&ihl));\n\n\tassert!(!header[49], \"Unexpected fragmentation\");\n\n\tassert!(header[50], \"Unexpected fragmentation\");\n\n\n\n\teprintln!(\"Final packet: [\");\n\n\tfor byte in &header.unwrap() {\n\n\t\teprintln!(\" {:08b}\", *byte);\n\n\t}\n\n\teprintln!(\"]\");\n\n}\n\n\n", "file_path": "examples/ipv4.rs", "rank": 87, "score": 47520.18108731293 }, { "content": "pub trait BitMemory: IsUnsigned + BitOps + seal::Sealed {\n\n\t/// The bit width of the register element.\n\n\t///\n\n\t/// `mem::size_of` returns the size in bytes, and bytes are always eight\n\n\t/// bits on architectures Rust targets.\n\n\tconst BITS: u8 = mem::size_of::<Self>() as u8 * 8;\n\n\t/// The number of bits required to store an index in the range `0 .. BITS`.\n\n\tconst INDX: u8 = Self::BITS.trailing_zeros() as u8;\n\n\t/// A mask over all bits that can be used as an index within the element.\n\n\tconst MASK: u8 = Self::BITS - 1;\n\n\n\n\t/// The value with only its least significant bit set to `1`.\n\n\tconst ONE: Self;\n\n\t/// The value with all of its bits set to `1`.\n\n\tconst ALL: Self;\n\n}\n\n\n\nmacro_rules! memory {\n\n\t($($t:ty),+ $(,)?) => { $(\n\n\t\timpl BitMemory for $t {\n", "file_path": "src/mem.rs", "rank": 88, "score": 47246.98689559217 }, { "content": "pub trait BitAccess<M>: Debug + Radium<M> + Sized\n\nwhere M: BitMemory\n\n{\n\n\t/// Sets one bit in a memory element to `0`.\n\n\t///\n\n\t/// # Type Parameters\n\n\t///\n\n\t/// - `O`: A bit ordering.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&self`\n\n\t/// - `index`: The semantic index of the bit in `*self` to be erased.\n\n\t///\n\n\t/// # Effects\n\n\t///\n\n\t/// The memory element at `*self` has the bit corresponding to `index` set\n\n\t/// to `0`, and all other bits are unchanged.\n\n\t#[inline]\n\n\tfn clear_bit<O>(&self, index: BitIdx<M>)\n", "file_path": "src/access.rs", "rank": 89, "score": 45969.95578441628 }, { "content": "fn ipv4_csum(header: &BitSlice<Msb0, u8>) -> u16 {\n\n\tif !(160 .. 288).contains(&header.len()) {\n\n\t\tpanic!(\"IPv4 headers must be between 160 and 288 bits\");\n\n\t}\n\n\tlet mut accum = 0u32;\n\n\tfor pair in header.chunks(16) {\n\n\t\taccum += pair.load_be::<u16>() as u32;\n\n\t}\n\n\twhile accum > 0xFFFFu32 {\n\n\t\tlet high = accum & !0xFFFFu32;\n\n\t\taccum += high >> 16;\n\n\t\taccum -= high;\n\n\t}\n\n\t!(accum as u16)\n\n}\n\n\n", "file_path": "examples/ipv4.rs", "rank": 90, "score": 45061.53978042804 }, { "content": "#[inline]\n\nfn check(action: &'static str, len: usize, width: u8) {\n\n\tif !(1 ..= width as usize).contains(&len) {\n\n\t\tpanic!(\"Cannot {} {} bits from a {}-bit region\", action, width, len);\n\n\t}\n\n}\n\n\n\n/** Reads a value out of a section of a memory element.\n\n\n\nThis function is used to extract a portion of an `M` value from a portion of a\n\n`T` value. The `BitField` implementations call it as they assemble a complete\n\n`M`. It performs the following steps:\n\n\n\n1. the referent value of the `elem` pointer is copied into local memory,\n\n2. `mask`ed to discard the portions of `*elem` that are not live,\n\n3. shifted to the LSedge of the `T::Mem` temporary,\n\n4. then `resize`d into an `M` value.\n\n\n\nThis is the exact inverse of `set`.\n\n\n\n# Type Parameters\n", "file_path": "src/field.rs", "rank": 91, "score": 42935.03254621635 }, { "content": "\t/// Views the memory address as an alias pointer.\n\n\t#[inline(always)]\n\n\tpub(crate) fn to_alias(self) -> *const T::Alias {\n\n\t\tself.addr as *const T::Alias\n\n\t}\n\n\n\n\t/// Views the memory address as an immutable pointer.\n\n\t#[inline(always)]\n\n\tpub(crate) fn to_const(self) -> *const T {\n\n\t\tself.addr as *const T\n\n\t}\n\n\n\n\t/// Views the memory address as a mutable pointer.\n\n\t#[inline(always)]\n\n\t#[allow(clippy::wrong_self_convention)]\n\n\tpub(crate) fn to_mut(self) -> *mut T {\n\n\t\tself.addr as *mut T\n\n\t}\n\n\n\n\t/// Gets the numeric value of the address.\n", "file_path": "src/pointer.rs", "rank": 92, "score": 42059.69160734397 }, { "content": "\t\t\tSome(r) => r,\n\n\t\t\tNone => return Self::EMPTY,\n\n\t\t};\n\n\t\tlet ptr = dvl::nonnull_slice_to_base(slice_nn).cast::<u8>();\n\n\t\tlet len = unsafe { slice_nn.as_ref() }.len();\n\n\t\tSelf {\n\n\t\t\tptr,\n\n\t\t\tlen,\n\n\t\t\t_ty: PhantomData,\n\n\t\t}\n\n\t}\n\n\n\n\t/// Typecasts a raw region pointer into a pointer structure.\n\n\t#[inline(always)]\n\n\t#[cfg(feature = \"alloc\")]\n\n\tpub(crate) fn from_bitslice_ptr_mut<O>(raw: *mut BitSlice<O, T>) -> Self\n\n\twhere O: BitOrder {\n\n\t\tSelf::from_bitslice_ptr(raw as *const BitSlice<O, T>)\n\n\t}\n\n\n", "file_path": "src/pointer.rs", "rank": 93, "score": 42057.83456114549 }, { "content": "\t/// # Safety\n\n\t///\n\n\t/// None. The invariants of `::new` must be checked at the caller.\n\n\t#[inline]\n\n\t#[cfg(feature = \"alloc\")]\n\n\tpub(crate) unsafe fn set_pointer(&mut self, addr: impl Into<Address<T>>) {\n\n\t\tlet mut addr = addr.into();\n\n\t\tif addr.to_const().is_null() {\n\n\t\t\t*self = Self::EMPTY;\n\n\t\t\treturn;\n\n\t\t}\n\n\t\taddr.addr &= Self::PTR_ADDR_MASK;\n\n\t\taddr.addr |= self.ptr.as_ptr() as usize & Self::PTR_HEAD_MASK;\n\n\t\tself.ptr = NonNull::new_unchecked(addr.to_mut() as *mut u8);\n\n\t}\n\n\n\n\t/// Gets the starting bit index of the referent region.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n", "file_path": "src/pointer.rs", "rank": 94, "score": 42057.05704227218 }, { "content": "\t/// according to the `O` ordering.\n\n\t/// - `value`: The bit value to insert at `index`.\n\n\t///\n\n\t/// # Effects\n\n\t///\n\n\t/// `value` is written to the bit specified by `index`, relative to\n\n\t/// `self.head()` and `self.pointer()`.\n\n\t#[inline]\n\n\tpub(crate) unsafe fn write<O>(&self, index: usize, value: bool)\n\n\twhere O: BitOrder {\n\n\t\tlet (elt, bit) = self.head().offset(index as isize);\n\n\t\tlet base = self.pointer().to_access();\n\n\t\t(&*base.offset(elt)).write_bit::<O>(bit, value);\n\n\t}\n\n\n\n\t/// Typecasts a raw region pointer into a pointer structure.\n\n\t#[inline]\n\n\tpub(crate) fn from_bitslice_ptr<O>(raw: *const BitSlice<O, T>) -> Self\n\n\twhere O: BitOrder {\n\n\t\tlet slice_nn = match NonNull::new(raw as *const [()] as *mut [()]) {\n", "file_path": "src/pointer.rs", "rank": 95, "score": 42056.931768865375 }, { "content": "\t/// - `&self`\n\n\t///\n\n\t/// # Returns\n\n\t///\n\n\t/// The address of the starting element of the memory region. This address\n\n\t/// is weakly typed so that it can be cast by call sites to the most useful\n\n\t/// access type.\n\n\t#[inline]\n\n\tpub(crate) fn pointer(&self) -> Address<T> {\n\n\t\tAddress::new(self.ptr.as_ptr() as usize & Self::PTR_ADDR_MASK)\n\n\t}\n\n\n\n\t/// Overwrites the data pointer with a new address. This method does not\n\n\t/// perform safety checks on the new pointer.\n\n\t///\n\n\t/// # Parameters\n\n\t///\n\n\t/// - `&mut self`\n\n\t/// - `ptr`: The new address of the `BitPtr<T>`’s domain.\n\n\t///\n", "file_path": "src/pointer.rs", "rank": 96, "score": 42056.4904086787 }, { "content": "\t/// # Examples\n\n\t///\n\n\t/// ```rust\n\n\t/// use bitvec::prelude::*;\n\n\t///\n\n\t/// let bv = bitvec![0; 20];\n\n\t/// let ptr = bv.as_bitptr();\n\n\t///\n\n\t/// let bits = unsafe { &*ptr };\n\n\t/// assert_eq!(bv, bits);\n\n\t/// ```\n\n\t///\n\n\t/// [`as_mut_bitptr`]: #method.as_mut_bitptr\n\n\t#[inline]\n\n\t#[cfg(not(tarpaulin_include))]\n\n\tpub fn as_bitptr(&self) -> *const BitSlice<O, T> {\n\n\t\tself.pointer.as_ptr() as *const BitSlice<O, T>\n\n\t}\n\n\n\n\t/// Returns an unsafe mutable pointer to the vector’s region.\n", "file_path": "src/vec.rs", "rank": 97, "score": 30.181423136789338 }, { "content": "\t#[inline]\n\n\tpub fn as_mut_slice(&mut self) -> &mut [T] {\n\n\t\tlet bitptr = self.bitptr();\n\n\t\tlet (base, elts) = (bitptr.pointer().to_mut(), bitptr.elements());\n\n\t\tunsafe { slice::from_raw_parts_mut(base, elts) }\n\n\t}\n\n\n\n\t#[inline]\n\n\tpub(crate) fn bitptr(&self) -> BitPtr<T> {\n\n\t\tself.pointer.as_ptr().pipe(BitPtr::from_bitslice_ptr_mut)\n\n\t}\n\n\n\n\t/// Permits a function to modify the `Box<[T]>` backing storage of a\n\n\t/// `BitBox<_, T>`.\n\n\t///\n\n\t/// This produces a temporary `Box<[T::Mem]>` structure governing the\n\n\t/// `BitBox`’s buffer and allows a function to view it mutably. After the\n\n\t/// callback returns, the `Box` is written back into `self` and forgotten.\n\n\t///\n\n\t/// # Type Parameters\n", "file_path": "src/boxed.rs", "rank": 98, "score": 29.572921194161477 }, { "content": "\t/// that the vector start at the leading edge of the first element, use\n\n\t/// [`force_align`] to guarantee this.\n\n\t///\n\n\t/// # Examples\n\n\t///\n\n\t/// ```rust\n\n\t/// use bitvec::prelude::*;\n\n\t///\n\n\t/// let bits = bits![0, 1, 0, 1, 1, 0, 1, 1];\n\n\t/// let bv = BitVec::from_bitslice(&bits[2 ..]);\n\n\t/// assert_eq!(bv, bits[2 ..]);\n\n\t/// ```\n\n\t///\n\n\t/// [`force_align`]: #method.force_align\n\n\t#[inline]\n\n\tpub fn from_bitslice(slice: &BitSlice<O, T>) -> Self {\n\n\t\tlet mut bitptr = slice.bitptr();\n\n\t\tlet (base, elts) = (bitptr.pointer().to_access(), bitptr.elements());\n\n\t\tlet source = unsafe { slice::from_raw_parts(base, elts) };\n\n\n", "file_path": "src/vec.rs", "rank": 99, "score": 29.016036410450727 } ]
Rust
src/display.rs
adi-g15/Ludo-The_Game-rs
d4c9f776982b0a2dd0f1ab53b192ccd2d41cd0f8
use crossterm::{ self, cursor, style::{self, Color, Stylize}, terminal, ExecutableCommand, QueueableCommand, }; use std::{io::{stdout, Write, stdin}, thread, time::Duration}; mod parts; pub struct Display { player_name: String, } impl Display { pub fn new() -> Self { let display = Display { player_name: String::new(), }; stdout().execute(terminal::SetTitle("Ludo-The_Game")).unwrap(); Display::splash_screen("Namaste from Ludo-The_Game 🙏", None); thread::sleep(Duration::from_millis(1200)); display } pub fn get_player_names(&self) -> [String; 4] { let hor_char = "─"; let vert_char = "│"; let message = "Enter names of the Players (Leave empty if not playing)"; let mut names = [String::new(), String::new(), String::new(), String::new()]; let colors = ["🔴","🟢","🟡","🔵"]; let (columns, rows) = terminal::size().unwrap(); let original_position = cursor::position().unwrap(); let mut stdout = stdout(); self.header(); stdout .queue(cursor::MoveTo(1,3)).unwrap() .queue(style::Print(format!("┌{}┐", hor_char.repeat(columns as usize -3)))).unwrap(); for i in 4..rows { stdout .queue(cursor::MoveTo(1,i)).unwrap() .queue(style::Print(vert_char)).unwrap() .queue(cursor::MoveToColumn(columns)).unwrap() .queue(style::Print(vert_char)).unwrap() .queue(cursor::MoveToNextLine(1)).unwrap() ; } stdout .queue(cursor::MoveTo(1,rows-1)).unwrap() .queue(style::Print(format!("└{}┘", hor_char.repeat(columns as usize -3)))).unwrap() ; stdout .queue(cursor::MoveTo(((columns as usize - message.len()) as u16)/2, (rows - 5)/2)).unwrap(); stdout.queue(style::PrintStyledContent(message.bold())).unwrap(); for (i,name) in names.iter_mut().enumerate() { stdout .queue(cursor::MoveToNextLine(1)).unwrap() /* reason for -4-1 = 2 emoji ka, 1 space, 1 ':', baaki 1 aise hi*/ .queue(cursor::MoveToColumn((columns/2) - "Player".len() as u16 -4 -1 )).unwrap() .queue(style::Print(format!("{} Player{} : ", colors[i], i+1))).unwrap() ; stdout.flush().unwrap(); if stdin().read_line(name).is_err() { panic!("Failed to read name"); } name.clone_from(&name.trim().to_string()); stdout.queue(cursor::MoveToPreviousLine(1)).unwrap(); } stdout.queue(cursor::MoveTo(original_position.0, original_position.1)).unwrap(); stdout.flush().unwrap(); names } pub fn ensure_terminal_size() { let (mut curr_cols, mut curr_rows) = terminal::size().unwrap(); while curr_cols < 100 || curr_rows < 44 { Display::splash_screen("Please Zoom Out or Stretch to make the terminal window larger.", Some(Color::Red)); thread::sleep(Duration::from_millis(50)); (curr_cols, curr_rows) = terminal::size().unwrap(); } } pub fn set_player(&mut self, name: &str) { self.player_name = name.to_string(); } pub fn update_display(&self, board_contents: Vec<((u8,u8), String)> ) { Display::ensure_terminal_size(); let player_name = &self.player_name; let mut stdout = stdout(); stdout .queue(terminal::Clear(terminal::ClearType::All)) .unwrap() .queue(cursor::Hide) .unwrap(); let (columns, _rows) = match terminal::size() { Ok(size) => (size.0 as usize, size.1 as usize), Err(e) => panic!("{:?}", e), }; let h_scale: u16 = 3; let v_scale: u16 = 1; self.header(); let ((board_start_col, board_start_row),(board_end_col, board_end_row)) = self.board_design(h_scale, v_scale); self.update_according_to_ludo_board(board_start_col, board_start_row, h_scale, v_scale, board_contents); stdout .queue(cursor::MoveTo(board_end_col, board_end_row)).unwrap() ; if !player_name.is_empty() { stdout .queue(cursor::MoveToNextLine(1)) .unwrap() .queue(style::Print(format!( "{}{}", " ".repeat((columns - player_name.len()) / 2), player_name ))) .unwrap() .queue(cursor::MoveToNextLine(1)) .unwrap() .queue(style::Print("±".repeat(columns))) .unwrap(); } stdout.queue(cursor::MoveToNextLine(1)).unwrap(); if stdout.flush().is_err() { terminal::disable_raw_mode().unwrap(); panic!("Couldn't print board"); } stdout.execute(cursor::Show).unwrap(); } pub fn end_display(&mut self) { if terminal::disable_raw_mode().is_err() { /* Ignore */ }; } }
use crossterm::{ self, cursor, style::{self, Color, Stylize}, terminal, ExecutableCommand, QueueableCommand, }; use std::{io::{stdout, Write, stdin}, thread, time::Duration}; mod parts; pub struct Display { player_name: String, } impl Display { pub fn new() -> Self { let display = Display { player_name: String::new(), }; stdout().execute(terminal::SetTitle("Ludo-The_Game")).unwrap(); Display::splash_screen("Namaste from Ludo-The_Game 🙏", None); thread::sleep(Duration::from_millis(1200)); display } pub fn get_player_names(&self) -> [String; 4] { let hor_char = "─"; let vert_char = "│"; let message = "Enter names of the Players (Leave empty if not playing)"; let mut names = [String::new(), String::new(), String::new(), String::new()]; let colors = ["🔴","🟢","🟡","🔵"]; let (columns, rows) = terminal::size().unwrap(); let original_position = cursor::position().unwrap(); let mut stdout = stdout(); self.header(); stdout .queue(cursor::MoveTo(1,3)).unwrap() .queue(style::Print(format!("┌{}┐", hor_char.repeat(columns as usize -3)))).unwrap(); for i in 4..rows { stdout .queue(cursor::MoveTo(1,i)).unwrap() .queue(style::Print(vert_char)).unwrap() .queue(cursor::MoveToColumn(columns)).unwrap() .queue(style::Print(vert_char)).unwrap() .queue(cursor::MoveToNextLine(1)).unwrap() ; } stdout .queue(cursor::MoveTo(1,rows-1)).unwrap() .queue(style::Print(format!("└{}┘", hor_char.repeat(columns as usize -3)))).unwrap() ; stdout .queue(cursor::MoveTo(((columns as usize - message.len()) as u16)/2, (rows - 5)/2)).unwrap(); stdout.queue(style::PrintStyledContent(message.bold())).unwrap(); for (i,name) in names.iter_mut().enumerate() { stdout .queue(cursor::MoveToNextLine(1)).unwrap() /* reason for -4-1 = 2 emoji ka, 1 space, 1 ':', baaki 1 aise hi*/ .queue(cursor::MoveToColumn((columns/2) - "Player".len() as u16 -4 -1 )).unwrap() .queue(style::Print(format!("{} Player{} : ", colors[i], i+1))).unwrap() ; stdout.flush().unwrap(); if stdin().read_line(name).is_err() { panic!("Failed to read name"); } name.clone_from(&name.trim().to_string()); stdout.queue(cursor::MoveToPreviousLine(1)).unwrap(); } stdout.queue(cursor::MoveTo(original_position.0, original_position.1)).unwrap(); stdout.flush().unwrap(); names } pub fn ensure_terminal_size() { let (mut curr_cols, mut curr_rows) = terminal::size().unwrap(); while curr_cols < 100 || curr_rows < 44 { Display::splash_screen("Please Zoom Out or Stretch to make the terminal window larger.", Some(Color::Red)); thread::sleep(Duration::from_millis(50)); (curr_cols, curr_rows) = terminal::size().unwrap(); } } pub fn set_player(&mut self, name: &str) { self.player_name = name.to_string(); } pub fn update_display(&self, board_contents: Vec<((u8,u8), String)> ) { Display::ensure_terminal_size(); let player_name = &self.player_name; let mut stdout = stdout(); stdout .queue(terminal::Clear(terminal::ClearType:
ap() .queue(style::Print("±".repeat(columns))) .unwrap(); } stdout.queue(cursor::MoveToNextLine(1)).unwrap(); if stdout.flush().is_err() { terminal::disable_raw_mode().unwrap(); panic!("Couldn't print board"); } stdout.execute(cursor::Show).unwrap(); } pub fn end_display(&mut self) { if terminal::disable_raw_mode().is_err() { /* Ignore */ }; } }
:All)) .unwrap() .queue(cursor::Hide) .unwrap(); let (columns, _rows) = match terminal::size() { Ok(size) => (size.0 as usize, size.1 as usize), Err(e) => panic!("{:?}", e), }; let h_scale: u16 = 3; let v_scale: u16 = 1; self.header(); let ((board_start_col, board_start_row),(board_end_col, board_end_row)) = self.board_design(h_scale, v_scale); self.update_according_to_ludo_board(board_start_col, board_start_row, h_scale, v_scale, board_contents); stdout .queue(cursor::MoveTo(board_end_col, board_end_row)).unwrap() ; if !player_name.is_empty() { stdout .queue(cursor::MoveToNextLine(1)) .unwrap() .queue(style::Print(format!( "{}{}", " ".repeat((columns - player_name.len()) / 2), player_name ))) .unwrap() .queue(cursor::MoveToNextLine(1)) .unwr
random
[ { "content": "pub fn roll() -> u8 {\n\n rand::thread_rng().gen_range(1..7)\n\n}\n", "file_path": "src/engine/dice.rs", "rank": 0, "score": 47329.51763547484 }, { "content": "use std::io::{stdout, Write};\n\n\n\nuse crate::display::Display;\n\nuse crossterm::{\n\n cursor,\n\n style::{self, Color, Stylize},\n\n terminal::{self, ClearType}, QueueableCommand, ExecutableCommand\n\n};\n\n\n\nimpl Display {\n\n pub fn header(&self) {\n\n let mut stdout = stdout();\n\n\n\n let hor_char = \"─\";\n\n let vert_char = \"│\";\n\n\n\n let msg = \" Namaste from Ludo-The_Game 🙏 \";\n\n let (columns, _rows) = match terminal::size() {\n\n Ok(size) => (size.0 as usize, size.1 as usize),\n\n Err(e) => panic!(\"{:?}\", e),\n", "file_path": "src/display/parts.rs", "rank": 1, "score": 42154.33653876256 }, { "content": " .queue(cursor::MoveToColumn(columns as u16)).unwrap()\n\n .queue(style::Print(vert_char)).unwrap()\n\n .queue(cursor::MoveTo(1,2)).unwrap()\n\n .queue(style::Print(format!(\"└{}┘\", hor_char.repeat(columns-3)))).unwrap()\n\n .queue(cursor::MoveToNextLine(1)).unwrap();\n\n // END: Header\n\n }\n\n\n\n pub fn board_design(&self, h_scale: u16, v_scale: u16) -> ((u16,u16),(u16,u16)) {\n\n // START: Board Design\n\n let mut stdout = stdout();\n\n let hor_char = \"─\";\n\n let vert_char = \"│\";\n\n\n\n let (columns, _rows) = match terminal::size() {\n\n Ok(size) => (size.0 as usize, size.1 as usize),\n\n Err(e) => panic!(\"{:?}\", e),\n\n };\n\n\n\n let left_spacing: u16 = (columns as u16 - (15 * (h_scale + 1) + 1) - 3/*due to numbers*/) / 2;\n", "file_path": "src/display/parts.rs", "rank": 2, "score": 42146.98620378127 }, { "content": "\n\n // Left Margin\n\n stdout\n\n .queue(cursor::MoveToColumn(left_spacing as u16 + 1 + (h_scale / 2))).unwrap();\n\n\n\n for i in 0..15 {\n\n stdout\n\n .queue(style::Print((i as u8).to_string()))\n\n .unwrap()\n\n .queue(style::Print(\n\n \" \".repeat(h_scale as usize - (if i > 9 { 1 } else { 0 })),\n\n ))\n\n .unwrap();\n\n }\n\n\n\n stdout.queue(cursor::MoveToNextLine(1)).unwrap();\n\n\n\n let board_start_row = cursor::position().unwrap().1;\n\n let board_start_col = left_spacing as u16;\n\n\n", "file_path": "src/display/parts.rs", "rank": 3, "score": 42145.73955571281 }, { "content": " if !(((r,c) == (10,10)) || ((r,c) == (10,13)) || ((r,c) == (13,10)) || ((r,c) == (13,13))) {\n\n continue;\n\n } else {\n\n // cell = \"📘\".to_string();\n\n cell = \"##\".to_string();\n\n // color = Some(Color::Blue);\n\n }\n\n }\n\n\n\n stdout\n\n .queue(cursor::MoveTo(\n\n (board_start_col + (c as u16) * (h_scale + 1) + (h_scale / 2)).into(),\n\n (board_start_row + (r as u16) * (v_scale + 1) + 1) as u16,\n\n )).unwrap();\n\n\n\n match color {\n\n Some(color) => stdout.queue(\n\n style::PrintStyledContent((if cell.is_empty() { \" \" } else { &cell }).with(color))\n\n ),\n\n None => stdout.queue(\n", "file_path": "src/display/parts.rs", "rank": 4, "score": 42145.715964704694 }, { "content": " stdout\n\n .queue(cursor::MoveToColumn(left_spacing)).unwrap()\n\n .queue(style::Print(\n\n hor_char.repeat(15 * (h_scale + 1) as usize + 1)\n\n )).unwrap()\n\n .queue(cursor::MoveToNextLine(1)).unwrap();\n\n\n\n for i in 0..15 {\n\n // Left spacing of each row\n\n stdout\n\n .queue(cursor::MoveToColumn(left_spacing - 3)).unwrap()\n\n .queue(style::Print(format!(\n\n \"{} {}\",\n\n (i as u8).to_string() + if i < 10 { \" \" } else { \"\" },\n\n vert_char\n\n ))).unwrap();\n\n\n\n // printing vertical line after each cell (empty)\n\n for _j in 0..15 {\n\n stdout\n", "file_path": "src/display/parts.rs", "rank": 5, "score": 42145.5303718009 }, { "content": " .unwrap();\n\n\n\n stdout\n\n .queue(cursor::MoveTo(\n\n ((columns as usize - message.len()) as u16) / 2,\n\n rows / 2,\n\n ))\n\n .unwrap();\n\n // Print Message\n\n match colour {\n\n Some(colour) => stdout.queue(style::PrintStyledContent(message.bold().with(colour))),\n\n None => stdout.queue(style::PrintStyledContent(message.bold())),\n\n }\n\n .unwrap();\n\n\n\n // Restore Cursor Position\n\n stdout\n\n .queue(cursor::MoveTo(original_position.0, original_position.1)).unwrap()\n\n .flush().unwrap();\n\n }\n", "file_path": "src/display/parts.rs", "rank": 6, "score": 42145.27265171493 }, { "content": " let hor_char = \"─\";\n\n let vert_char = \"│\";\n\n\n\n let (columns, rows) = terminal::size().unwrap();\n\n let original_position = cursor::position().unwrap();\n\n\n\n let mut stdout = stdout();\n\n\n\n stdout.execute(terminal::Clear(ClearType::All)).unwrap();\n\n\n\n stdout\n\n .queue(cursor::MoveTo(1, 0))\n\n .unwrap()\n\n .queue(style::Print(format!(\n\n \"┌{}┐\",\n\n hor_char.repeat(columns as usize - 3)\n\n )))\n\n .unwrap();\n\n\n\n for i in 1..rows {\n", "file_path": "src/display/parts.rs", "rank": 7, "score": 42145.038849079254 }, { "content": " };\n\n\n\n stdout.queue(terminal::Clear(ClearType::All)).unwrap();\n\n\n\n // START: Header\n\n let left_spacing = (columns - msg.len()) / 2;\n\n stdout\n\n .queue(cursor::MoveTo(1, 0)).unwrap()\n\n .queue(style::Print(format!(\"┌{}┐\", hor_char.repeat(columns - 3)))).unwrap()\n\n .queue(cursor::MoveTo(1,1)).unwrap()\n\n .queue(style::Print(vert_char)).unwrap()\n\n .queue(cursor::MoveToColumn(left_spacing as u16)).unwrap()\n\n .queue(style::PrintStyledContent(\n\n msg.with(Color::Rgb {\n\n r: 214,\n\n g: 214,\n\n b: 214,\n\n })\n\n .bold(),\n\n )).unwrap()\n", "file_path": "src/display/parts.rs", "rank": 8, "score": 42143.06995715747 }, { "content": "\n\n pub fn update_according_to_ludo_board(\n\n &self,\n\n board_start_col: u16,\n\n board_start_row: u16,\n\n h_scale: u16,\n\n v_scale: u16,\n\n board_contents: Vec<((u8,u8), String)>\n\n ) {\n\n // START: Board Content\n\n let mut stdout = stdout();\n\n\n\n for ((r, c), mut cell) in board_contents {\n\n // If this has value, then means print it with that color's background\n\n let mut color = Option::None;\n\n\n\n // Inner Square\n\n if r >= 6 && r <= 8 && c >= 6 && c <= 8 {\n\n continue;\n\n }\n", "file_path": "src/display/parts.rs", "rank": 9, "score": 42142.7833818485 }, { "content": " style::Print(if cell.is_empty() { \" \" } else { &cell })\n\n )\n\n }.unwrap();\n\n }\n\n // END: Board Content\n\n }\n\n\n\n fn color_boxes(\n\n &self,\n\n board_start_col: u16,\n\n board_start_row: u16,\n\n h_scale: u16,\n\n v_scale: u16,\n\n row_start: u16,\n\n row_end: u16, /* exclusive */\n\n col_start: u16,\n\n col_end: u16, /* exclusive */\n\n colour: Color,\n\n ) {\n\n let mut stdout = stdout();\n", "file_path": "src/display/parts.rs", "rank": 10, "score": 42141.900134365205 }, { "content": " .queue(style::Print(format!(\n\n \"{}{}\",\n\n \" \".repeat(h_scale.into()),\n\n vert_char\n\n ))).unwrap();\n\n }\n\n\n\n // Bottom Line of each row\n\n stdout\n\n .queue(cursor::MoveToNextLine(1)).unwrap()\n\n .queue(cursor::MoveToColumn(left_spacing)).unwrap()\n\n .queue(style::Print(hor_char.repeat(15 * (h_scale + 1) as usize + 1))).unwrap()\n\n .queue(cursor::MoveToNextLine(1)).unwrap();\n\n }\n\n\n\n let (board_end_col, board_end_row) = cursor::position().unwrap();\n\n\n\n // START: Colour Boxes\n\n self.color_boxes(\n\n board_start_col,\n", "file_path": "src/display/parts.rs", "rank": 11, "score": 42141.023313797494 }, { "content": " stdout\n\n .queue(cursor::MoveTo(1, i))\n\n .unwrap()\n\n .queue(style::Print(vert_char))\n\n .unwrap()\n\n .queue(cursor::MoveToColumn(columns))\n\n .unwrap()\n\n .queue(style::Print(vert_char))\n\n .unwrap()\n\n .queue(cursor::MoveToNextLine(1))\n\n .unwrap();\n\n }\n\n\n\n stdout\n\n .queue(cursor::MoveTo(1, rows - 1))\n\n .unwrap()\n\n .queue(style::Print(format!(\n\n \"└{}┘\",\n\n hor_char.repeat(columns as usize - 3)\n\n )))\n", "file_path": "src/display/parts.rs", "rank": 12, "score": 42140.35048253026 }, { "content": " Color::Blue,\n\n );\n\n self.color_boxes(\n\n board_start_col,\n\n board_start_row,\n\n h_scale,\n\n v_scale,\n\n 6,\n\n 9,\n\n 6,\n\n 9,\n\n Color::White,\n\n );\n\n // END: Colour Boxes \n\n // END: Board Design\n\n\n\n ((board_start_col, board_start_row), (board_end_col, board_end_row))\n\n }\n\n\n\n pub fn splash_screen(message: &str, colour: Option<Color>) {\n", "file_path": "src/display/parts.rs", "rank": 13, "score": 42137.15072358903 }, { "content": " let width = col_end - col_start;\n\n let blocks = \"▒\".repeat((((h_scale + 1) * width) - 1).into());\n\n let styled_blocks = match colour {\n\n Color::White => blocks.white(),\n\n Color::Red => blocks.red(),\n\n Color::Green => blocks.green(),\n\n Color::Yellow => blocks.yellow(),\n\n Color::Blue => blocks.blue(),\n\n _ => unimplemented!(), // not required\n\n };\n\n\n\n for r in row_start..row_end {\n\n stdout\n\n .queue(cursor::MoveTo(\n\n board_start_col + col_start * (h_scale + 1),\n\n board_start_row + r * (v_scale + 1) + 1,\n\n ))\n\n .unwrap()\n\n .queue(style::PrintStyledContent(styled_blocks.clone()))\n\n .unwrap();\n", "file_path": "src/display/parts.rs", "rank": 14, "score": 42135.95290138499 }, { "content": "\n\n // For the v_scale*3 - 1 lines in between\n\n if r != (row_end - 1) {\n\n for i in 0..v_scale {\n\n stdout\n\n .queue(cursor::MoveTo(\n\n (board_start_col + col_start * (h_scale + 1)).into(),\n\n (board_start_row + r * (v_scale + 1) + i + 2).into(),\n\n ))\n\n .unwrap()\n\n .queue(style::PrintStyledContent(styled_blocks.clone()))\n\n .unwrap();\n\n }\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/display/parts.rs", "rank": 15, "score": 42134.98103075205 }, { "content": " board_start_row,\n\n h_scale,\n\n v_scale,\n\n 9,\n\n 15,\n\n 0,\n\n 6,\n\n Color::Red,\n\n );\n\n self.color_boxes(\n\n board_start_col,\n\n board_start_row,\n\n h_scale,\n\n v_scale,\n\n 0,\n\n 6,\n\n 0,\n\n 6,\n\n Color::Green,\n\n );\n", "file_path": "src/display/parts.rs", "rank": 16, "score": 42132.028073381254 }, { "content": " self.color_boxes(\n\n board_start_col,\n\n board_start_row,\n\n h_scale,\n\n v_scale,\n\n 0,\n\n 6,\n\n 9,\n\n 15,\n\n Color::Yellow,\n\n );\n\n self.color_boxes(\n\n board_start_col,\n\n board_start_row,\n\n h_scale,\n\n v_scale,\n\n 9,\n\n 15,\n\n 9,\n\n 15,\n", "file_path": "src/display/parts.rs", "rank": 17, "score": 42131.8875145857 }, { "content": "\n\n // Safe Spots\n\n if [(1, 8), (2, 6), (6, 1), (6, 12), (8, 2), (8, 13), (12, 8), (13, 6)].contains(&(r,c)) {\n\n // Safe spots will have a grey background\n\n color = Some(Color::Grey);\n\n }\n\n\n\n // Red Square\n\n if r >= 9 && c <= 5 {\n\n if !(((r,c) == (10,1)) || ((r,c) == (10,4)) || ((r,c) == (13,1)) || ((r,c) == (13,4))) {\n\n continue;\n\n } else {\n\n // cell = \"🍎\".to_string();\n\n cell = \"##\".to_string();\n\n }\n\n }\n\n\n\n // Green Square\n\n if r <= 5 && c <= 5 {\n\n if !(((r,c) == (1,1)) || ((r,c) == (1,4)) || ((r,c) == (4,1)) || ((r,c) == (4,4))) {\n", "file_path": "src/display/parts.rs", "rank": 18, "score": 42131.7521996714 }, { "content": " continue;\n\n } else {\n\n // cell = \"🥗\".to_string();\n\n cell = \"##\".to_string();\n\n }\n\n }\n\n\n\n // Yellow Square\n\n if r <= 5 && c >= 9 {\n\n if !(((r,c) == (1,10)) || ((r,c) == (4,10)) || ((r,c) == (1,13)) || ((r,c) == (4,13))) {\n\n continue;\n\n } else {\n\n // cell = \"💛\".to_string();\n\n cell = \"##\".to_string();\n\n }\n\n\n\n }\n\n\n\n // Blue Square\n\n if r >= 9 && c >= 9 {\n", "file_path": "src/display/parts.rs", "rank": 19, "score": 42129.526064793725 }, { "content": "fn main() {\n\n let mut ludo = Ludo::new();\n\n ludo.play();\n\n\n\n std::thread::sleep(std::time::Duration::from_secs(5));\n\n}\n", "file_path": "src/main.rs", "rank": 20, "score": 28314.640179631657 }, { "content": "use crate::engine::Rang;\n\n\n\npub struct Player {\n\n pub name: String,\n\n pub colour: Rang,\n\n}\n", "file_path": "src/game/player.rs", "rank": 21, "score": 22864.573668634643 }, { "content": "}\n\n\n\npub struct LudoEngine {\n\n board: [[Box; 15]; 15],\n\n\n\n // Note1: Whenever needs to share goti, .clone() the Rc, else RefCell will be in shared state and .borrow_mut() may panic\n\n // Note2: ONLY use .borrow_mut(), at the moment you are making a change, else a non-mutable function call that tries to .borrow() may panic\n\n // Why Rc<RefCell<>> ? Because, RefCell can't be cloned (I dont want to derive Clone on LudoGoti)\n\n moving_gotis: Map<Rang, Vec<Rc<RefCell<LudoGoti>>>>,\n\n locked_gotis: Map<Rang, Vec<Rc<RefCell<LudoGoti>>>>,\n\n num_finished: Map<Rang, u8>,\n\n active_colours: Vec<Rang>,\n\n curr_colour: Rang,\n\n}\n\n\n\nimpl LudoEngine {\n\n pub fn new(active_colours: Vec<Rang>) -> Self {\n\n if active_colours.is_empty() {\n\n panic!(\"No active colours to play 🥲\");\n\n }\n", "file_path": "src/engine/mod.rs", "rank": 31, "score": 20656.68054406847 }, { "content": "use array_init::array_init;\n\nuse std::{cell::RefCell, collections::BTreeMap as Map, rc::Rc};\n\n\n\nmod cell;\n\npub mod dice;\n\nmod goti;\n\nmod rang;\n\n\n\nuse self::{\n\n cell::{LudoCell as Box, LudoCellType},\n\n goti::LudoGoti,\n\n};\n\npub use rang::Rang; // 'Colour' use krne se confusion hota h kyunki crossterm::Color me bhi h\n\n\n\n#[derive(Debug, PartialEq, Eq)]\n\npub enum MoveResult {\n\n NormalMove((u8, u8)), // normal move\n\n Attacked((u8, u8)), // attacked a goti already present there\n\n Unlocked, // goti was unlocked\n\n Finished, // goti finished move\n", "file_path": "src/engine/mod.rs", "rank": 32, "score": 20655.990976590445 }, { "content": " pub(crate) fn set_current_colour(&mut self, colour: Rang) {\n\n self.curr_colour = colour;\n\n }\n\n\n\n // Returns Err(()), if no locked goti present\n\n pub fn unlock_goti(&mut self, colour: Rang) -> Result<(), ()> {\n\n let locked_positions = Rang::GetLockedPositions(colour);\n\n\n\n // SAFETY: If the attacked_goti was moving, that means atleast 1 locked_positions must be empty, so unwrap() wont panic\n\n let i = locked_positions\n\n .iter()\n\n .position(|coord| {\n\n self.board[coord.0 as usize][coord.1 as usize]\n\n .gotis\n\n .is_empty()\n\n == false\n\n })\n\n .unwrap();\n\n let locked_coord = locked_positions[i];\n\n\n", "file_path": "src/engine/mod.rs", "rank": 33, "score": 20655.86208484479 }, { "content": " }\n\n\n\n panic!(\"Invalid coordinate: {:?}\", coord);\n\n }\n\n\n\n // If any player isn't finished return false, else true\n\n // It is upto the game to exit if for eg. you want it to exit even if one player isn't finished\n\n pub(crate) fn is_game_finished(&self) -> bool {\n\n for colour in self.active_colours.iter() {\n\n if self.is_finished(*colour) == false {\n\n return false;\n\n }\n\n }\n\n\n\n true\n\n }\n\n\n\n // Note: returns None for non-playing colors\n\n pub(crate) fn get_num_locked(&self, colour: Rang) -> Option<u8> {\n\n match self.locked_gotis.get(&colour) {\n\n Some(v) => Some(v.len() as u8),\n\n None => None\n\n }\n\n }\n\n}\n", "file_path": "src/engine/mod.rs", "rank": 34, "score": 20655.659345806464 }, { "content": " .position(|coord| {\n\n self.board[coord.0 as usize][coord.1 as usize]\n\n .gotis\n\n .is_empty()\n\n })\n\n .unwrap();\n\n let empty_locked_cell = &mut self.board[locked_positions[i].0 as usize]\n\n [locked_positions[i].1 as usize];\n\n\n\n attacked_goti.borrow_mut().coords = locked_positions[i];\n\n empty_locked_cell.gotis.push(attacked_goti);\n\n }\n\n } else {\n\n // Normal move\n\n // Remove goti from start_cell, and put in dest_cell\n\n {\n\n let start_cell =\n\n &mut self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n start_cell.gotis.remove(start_cell_goti_index);\n\n }\n", "file_path": "src/engine/mod.rs", "rank": 35, "score": 20654.89156452519 }, { "content": " locked_gotis,\n\n moving_gotis,\n\n num_finished,\n\n }\n\n }\n\n\n\n pub fn get_board(&self) -> &[[Box; 15]; 15] {\n\n &self.board\n\n }\n\n\n\n /** @note Will always return `true` for a colour that is not playing */\n\n pub(crate) fn is_finished(&self, colour: Rang) -> bool {\n\n if self.active_colours.contains(&colour) == false {\n\n true\n\n } else {\n\n self.moving_gotis.get(&colour).unwrap().is_empty()\n\n && self.locked_gotis.get(&colour).unwrap().is_empty()\n\n }\n\n }\n\n\n", "file_path": "src/engine/mod.rs", "rank": 36, "score": 20654.648813722582 }, { "content": "\n\n let mut locked_gotis = Map::new();\n\n // Locked Locations:\n\n for colour in active_colours.iter() {\n\n let colour = *colour;\n\n locked_gotis.insert(colour, Vec::new());\n\n\n\n for (r, c) in Rang::GetLockedPositions(colour) {\n\n board[r as usize][c as usize].cell_type = LudoCellType::LockedPosition(colour);\n\n\n\n let goti_ref = Rc::new(RefCell::new(LudoGoti {\n\n colour,\n\n coords: (r, c),\n\n }));\n\n\n\n locked_gotis\n\n .get_mut(&colour)\n\n .unwrap()\n\n .push(goti_ref.clone());\n\n\n", "file_path": "src/engine/mod.rs", "rank": 37, "score": 20654.139692563607 }, { "content": " * Invariant: start_coord is a valid coordinate for a goti to exist on the board\n\n * Note: This does NOT check if goti of such `colour` exists on `start_coord`, for easier debugging or other use by the programmer\n\n * @returns Some(final_coords), if move possible\n\n * None, otherwise if not possible\n\n */\n\n pub fn is_move_possible(\n\n &self,\n\n colour: Rang,\n\n start_coord: (u8, u8),\n\n mut dist: u8,\n\n ) -> Option<(u8, u8)> {\n\n if self.board[start_coord.0 as usize][start_coord.1 as usize].cell_type\n\n == LudoCellType::NoUse\n\n {\n\n panic!(\"Invalid start coord: {:?}\", start_coord)\n\n }\n\n\n\n let goti_is_locked = Rang::GetLockedPositions(colour).contains(&start_coord);\n\n\n\n if goti_is_locked {\n", "file_path": "src/engine/mod.rs", "rank": 38, "score": 20653.35597154021 }, { "content": " };\n\n\n\n let was_attack = {\n\n let cell = &self.board[final_coords.0 as usize][final_coords.1 as usize];\n\n\n\n // If it is a SafeSpot, attack can not happen\n\n // If it is any other cell where two colors can meet,\n\n // then presence of any other colour = presence of enemy... yuddh hoga ab to, jai mahismati\n\n (cell.cell_type != LudoCellType::SafeSpot) && (\n\n cell.gotis.iter().position(|g| g.borrow().colour != colour).is_some()\n\n )\n\n };\n\n let finished = final_coords == Rang::GetEndCoord(colour);\n\n let unlocked = final_coords == Rang::GetStartCoord(colour);\n\n\n\n // Mutable changes here; This MUST be an atomic change, either all or none\n\n {\n\n // SAFETY: goti_index == None, already handled, so .unwrap() won't panic\n\n // Cloned `goti`, ab atleast ek reference h goti ka always\n\n let start_cell = &self.board[start_coords.0 as usize][start_coords.1 as usize];\n", "file_path": "src/engine/mod.rs", "rank": 39, "score": 20653.15945421821 }, { "content": " .locked_gotis\n\n .get(&colour)\n\n .unwrap()\n\n .iter()\n\n .position(|g| g == &goti)\n\n .unwrap();\n\n self.locked_gotis\n\n .get_mut(&colour)\n\n .unwrap()\n\n .remove(goti_index);\n\n\n\n self.moving_gotis\n\n .get_mut(&colour)\n\n .unwrap()\n\n .push(goti.clone());\n\n } else if finished {\n\n // Remove goti from everywhere, moving gotis (& start_cell)\n\n let start_cell = &mut self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n start_cell.gotis.remove(start_cell_goti_index);\n\n\n", "file_path": "src/engine/mod.rs", "rank": 40, "score": 20652.972457484608 }, { "content": " // SAFETY: all these .unwrap() here assume presence of goti in self.moving_gotis also, which must be the case, else it's critical internal bug\n\n let goti_index = self\n\n .moving_gotis\n\n .get(&colour)\n\n .unwrap()\n\n .iter()\n\n .position(|g| g == &goti)\n\n .unwrap();\n\n self.moving_gotis\n\n .get_mut(&colour)\n\n .unwrap()\n\n .remove(goti_index);\n\n\n\n *self.num_finished.get_mut(&goti.borrow().colour).unwrap() += 1;\n\n } else if was_attack {\n\n // Remove goti from start_cell, and put in dest_cell\n\n {\n\n let start_cell =\n\n &mut self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n start_cell.gotis.remove(start_cell_goti_index);\n", "file_path": "src/engine/mod.rs", "rank": 41, "score": 20652.627322282347 }, { "content": " return if dist == 6 {\n\n Some(Rang::GetStartCoord(colour))\n\n } else {\n\n None\n\n };\n\n }\n\n\n\n let mut final_coord = start_coord;\n\n\n\n while dist != 0 {\n\n // Kabhi seedha aage jana hota h, ya kabhi direction change krna hota h, wo ludo engine handle karega\n\n final_coord = LudoEngine::get_next_coord(colour, final_coord);\n\n\n\n if final_coord.0 > 14\n\n || final_coord.1 > 14\n\n || ((self.board[final_coord.0 as usize][final_coord.1 as usize].cell_type\n\n == LudoCellType::NoUse)\n\n && (final_coord != Rang::GetEndCoord(colour)))\n\n {\n\n return None;\n", "file_path": "src/engine/mod.rs", "rank": 42, "score": 20652.539871582172 }, { "content": " match self.move_goti(colour, locked_coord, 6) {\n\n Ok(res) => {\n\n debug_assert!(res == MoveResult::Unlocked);\n\n Ok(())\n\n }\n\n Err(_) => Err(()),\n\n }\n\n }\n\n\n\n // Invariant: Expects that atleast 1 goti of `colour` is present at `start_coord`\n\n pub fn move_goti(\n\n &mut self,\n\n colour: Rang,\n\n start_coords: (u8, u8),\n\n dist: u8,\n\n ) -> Result<MoveResult, String> {\n\n let final_coords = match self.is_move_possible(colour, start_coords, dist) {\n\n Some(coord) => coord,\n\n None => {\n\n return Err(\"Move not possible\".to_string());\n", "file_path": "src/engine/mod.rs", "rank": 43, "score": 20652.23025387525 }, { "content": " }\n\n {\n\n let dest_cell =\n\n &mut self.board[final_coords.0 as usize][final_coords.1 as usize];\n\n dest_cell.gotis.push(goti.clone());\n\n }\n\n\n\n // TIP1: Hide this loop, dimaag kharab hone ki sambhavna hai : )\n\n // TIP2: Can add more logic inside the lambda for special rules, for eg. here all gotis of different colors are enemies\n\n // AND, Remove all attacked_gotis from dest_cell, and put in locked_gotis\n\n loop {\n\n let attacked_goti = {\n\n // SAFETY: `goti_to_remove_idx` is a valid index in `dest_cells.gotis`, so unwraps won't panic\n\n let dest_cell =\n\n &mut self.board[final_coords.0 as usize][final_coords.1 as usize];\n\n let goti_to_remove_idx = dest_cell\n\n .gotis\n\n .iter()\n\n .position(|g| g.borrow().colour != colour);\n\n\n", "file_path": "src/engine/mod.rs", "rank": 44, "score": 20652.194094667168 }, { "content": " }\n\n\n\n // Blue\n\n for c in 9..14 {\n\n board[7][c].cell_type = LudoCellType::HomeLane(Rang::Blue);\n\n }\n\n }\n\n\n\n let mut moving_gotis = Map::new();\n\n let mut num_finished = Map::new();\n\n for colour in active_colours.iter() {\n\n let colour = *colour;\n\n moving_gotis.insert(colour, Vec::new());\n\n num_finished.insert(colour, 0);\n\n }\n\n\n\n LudoEngine {\n\n curr_colour: *active_colours.first().unwrap(),\n\n active_colours,\n\n board,\n", "file_path": "src/engine/mod.rs", "rank": 45, "score": 20652.111375534845 }, { "content": " }\n\n\n\n dist -= 1;\n\n }\n\n\n\n Some(final_coord)\n\n }\n\n\n\n // Returns coords of movable gotis\n\n // Prevent from leaking internal ds\n\n // Note: This does NOT handle the case of UNLOCK, handle it yourself then call engine.unlock_goti()\n\n pub fn get_movable_gotis(&self, colour: Rang, dist: u8) -> Vec<(u8, u8)> {\n\n let mut start_coords = Vec::new();\n\n {\n\n let gotis = match self.moving_gotis.get(&colour) {\n\n Some(gotis) => gotis,\n\n None => return vec![],\n\n };\n\n\n\n for goti in gotis {\n", "file_path": "src/engine/mod.rs", "rank": 46, "score": 20652.025285232998 }, { "content": "\n\n let goti = start_cell.gotis.get(start_cell_goti_index).unwrap().clone();\n\n {\n\n goti.borrow_mut().coords = final_coords;\n\n }\n\n\n\n if unlocked {\n\n // Remove goti from locked_gotis (& start_cell), and put in moving gotis (& dest_cell)\n\n {\n\n let start_cell =\n\n &mut self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n start_cell.gotis.remove(start_cell_goti_index);\n\n }\n\n {\n\n let dest_cell =\n\n &mut self.board[final_coords.0 as usize][final_coords.1 as usize];\n\n dest_cell.gotis.push(goti.clone());\n\n }\n\n\n\n let goti_index = self\n", "file_path": "src/engine/mod.rs", "rank": 47, "score": 20651.929804767326 }, { "content": " if goti_to_remove_idx.is_none() {\n\n break;\n\n }\n\n\n\n let goti_ref = dest_cell\n\n .gotis\n\n .get(goti_to_remove_idx.unwrap())\n\n .unwrap()\n\n .clone();\n\n\n\n dest_cell.gotis.remove(goti_to_remove_idx.unwrap());\n\n\n\n goti_ref\n\n };\n\n\n\n let locked_positions = Rang::GetLockedPositions(attacked_goti.borrow().colour);\n\n\n\n // SAFETY: If the attacked_goti was moving, that means atleast 1 locked_positions must be empty, so unwrap() wont panic\n\n let i = locked_positions\n\n .iter()\n", "file_path": "src/engine/mod.rs", "rank": 48, "score": 20651.527485005758 }, { "content": "\n\n // Bas is array ko initialise krne ke liye itna krna pda :')\n\n let mut board: [[Box; 15]; 15] = array_init(|_| {\n\n array_init(|_| Box {\n\n cell_type: LudoCellType::NoUse,\n\n gotis: Vec::new(),\n\n })\n\n });\n\n\n\n // Order Matters: For eg. Default also marks some as SafeSpots\n\n // Defaults (ie. usual Path box)\n\n {\n\n for r in 6..9 {\n\n for c in 0..15 {\n\n board[r][c].cell_type = LudoCellType::Default;\n\n board[c][r].cell_type = LudoCellType::Default;\n\n }\n\n }\n\n\n\n // Mark middle square as NoUse again\n", "file_path": "src/engine/mod.rs", "rank": 49, "score": 20650.766239632736 }, { "content": " }\n\n };\n\n\n\n // Invariant: cell.gotis has a goti of `colour`\n\n let start_cell_goti_index = {\n\n let start_cell = &self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n\n\n match start_cell\n\n .gotis\n\n .iter()\n\n .position(|g| g.borrow().colour == colour)\n\n {\n\n Some(i) => i,\n\n None => {\n\n return Err(format!(\n\n \"Goti of colour: {:?} doesn't exist at {:?}\",\n\n colour, start_coords\n\n ))\n\n }\n\n }\n", "file_path": "src/engine/mod.rs", "rank": 50, "score": 20650.051059456513 }, { "content": " {\n\n let dest_cell =\n\n &mut self.board[final_coords.0 as usize][final_coords.1 as usize];\n\n dest_cell.gotis.push(goti.clone());\n\n }\n\n }\n\n }\n\n\n\n let start_cell = &self.board[start_coords.0 as usize][start_coords.1 as usize];\n\n\n\n if was_attack {\n\n Ok(MoveResult::Attacked(final_coords))\n\n } else if finished {\n\n Ok(MoveResult::Finished)\n\n } else if unlocked {\n\n Ok(MoveResult::Unlocked)\n\n } else {\n\n match start_cell.cell_type {\n\n LudoCellType::Default | LudoCellType::SafeSpot => {\n\n Ok(MoveResult::NormalMove(final_coords))\n", "file_path": "src/engine/mod.rs", "rank": 51, "score": 20649.723309445897 }, { "content": " for r in 6..9 {\n\n for c in 6..9 {\n\n board[r][c].cell_type = LudoCellType::NoUse;\n\n }\n\n }\n\n }\n\n\n\n // Safe Spots\n\n for (r, c) in [\n\n (1, 8),\n\n (2, 6),\n\n (6, 1),\n\n (6, 12),\n\n (8, 2),\n\n (8, 13),\n\n (12, 8),\n\n (13, 6),\n\n ] {\n\n board[r][c].cell_type = LudoCellType::SafeSpot;\n\n }\n", "file_path": "src/engine/mod.rs", "rank": 52, "score": 20648.144359661517 }, { "content": " // board should know also\n\n board[r as usize][c as usize].gotis.push(goti_ref);\n\n }\n\n }\n\n\n\n // Home Lane (the ending path to finish)\n\n {\n\n // Red\n\n for r in 9..14 {\n\n board[r][7].cell_type = LudoCellType::HomeLane(Rang::Red);\n\n }\n\n\n\n // Green\n\n for c in 1..6 {\n\n board[7][c].cell_type = LudoCellType::HomeLane(Rang::Green);\n\n }\n\n\n\n // Yellow\n\n for r in 1..6 {\n\n board[r][7].cell_type = LudoCellType::HomeLane(Rang::Yellow);\n", "file_path": "src/engine/mod.rs", "rank": 53, "score": 20648.012803156544 }, { "content": " if self\n\n .is_move_possible(colour, goti.borrow().coords, dist)\n\n .is_some()\n\n {\n\n start_coords.push(goti.borrow().coords);\n\n }\n\n }\n\n }\n\n\n\n start_coords\n\n }\n\n\n\n // This may return NoUse coord\n\n fn get_next_coord(colour: Rang, coord: (u8, u8)) -> (u8, u8) {\n\n // arranged as: (start_coord, next_coord)\n\n let turns = [\n\n // Outer turns\n\n ((0, 6), (0, 7)),\n\n ((0, 8), (1, 8)),\n\n ((6, 0), (6, 1)),\n", "file_path": "src/engine/mod.rs", "rank": 54, "score": 20647.623921655497 }, { "content": " {\n\n let (current, next) = Rang::GetHomeTurn(colour);\n\n if coord == current {\n\n return next;\n\n }\n\n }\n\n\n\n // Handling rest cases (can return invalid locations, as in function description)\n\n if coord.0 == 6 {\n\n return (coord.0, coord.1 + 1);\n\n } else if coord.0 == 7 {\n\n // ie. (7,0)\n\n if coord.1 == 0 {\n\n return (coord.0 - 1, coord.1);\n\n } else if coord.1 < 6 {\n\n return (coord.0, coord.1 + 1);\n\n } else if coord.1 == 14 {\n\n return (coord.0 + 1, coord.1);\n\n } else if coord.1 > 8 {\n\n return (coord.0, coord.1 - 1);\n", "file_path": "src/engine/mod.rs", "rank": 55, "score": 20645.780763786523 }, { "content": " ((6, 14), (7, 14)),\n\n ((8, 0), (7, 0)),\n\n ((8, 14), (8, 13)),\n\n ((14, 6), (13, 6)),\n\n ((14, 8), (14, 7)),\n\n // Inner turns\n\n ((9, 6), (8, 5)),\n\n ((6, 5), (5, 6)),\n\n ((8, 9), (9, 8)),\n\n ((5, 8), (6, 9)),\n\n ];\n\n\n\n // Check if on outer or inner corners\n\n for (current, next) in turns {\n\n if coord == current {\n\n return next;\n\n }\n\n }\n\n\n\n // Check Home turns\n", "file_path": "src/engine/mod.rs", "rank": 56, "score": 20645.780763786523 }, { "content": " }\n\n } else if coord.0 == 8 {\n\n return (coord.0, coord.1 - 1);\n\n }\n\n\n\n if coord.1 == 6 {\n\n return (coord.0 - 1, coord.1);\n\n } else if coord.1 == 7 {\n\n // ie. (0,7)\n\n if coord.0 == 0 {\n\n return (coord.0, coord.1 + 1);\n\n } else if coord.0 < 6 {\n\n return (coord.0 + 1, coord.1);\n\n } else if coord.0 == 14 {\n\n return (coord.0, coord.1 - 1);\n\n } else if coord.0 > 8 {\n\n return (coord.0 - 1, coord.1);\n\n }\n\n } else if coord.1 == 8 {\n\n return (coord.0 + 1, coord.1);\n", "file_path": "src/engine/mod.rs", "rank": 57, "score": 20645.780763786523 }, { "content": " }\n\n LudoCellType::HomeLane(c) => {\n\n if c == colour {\n\n Ok(MoveResult::NormalMove(final_coords))\n\n } else {\n\n panic!(\n\n \".is_move_possible() galat coordinate diya: {:?}, rang: {:?} 🥺!!\",\n\n final_coords, colour\n\n )\n\n }\n\n }\n\n _ => panic!(\n\n \".is_move_possible() galat coordinate diya: {:?}, rang: {:?} 🥺!!\",\n\n final_coords, colour\n\n ),\n\n }\n\n }\n\n }\n\n\n\n /**\n", "file_path": "src/engine/mod.rs", "rank": 58, "score": 20645.780763786523 }, { "content": "mod player;\n\n\n\nuse std::io::{stdin, stdout, Write};\n\n\n\nuse crate::display::Display;\n\nuse crate::engine::MoveResult;\n\nuse crate::engine::{dice::roll, LudoEngine, Rang};\n\n\n\nuse crossterm::style::Color;\n\nuse player::Player;\n\n\n\npub struct LudoGame {\n\n engine: LudoEngine, // actual logic\n\n display: Display,\n\n active_players: Vec<Player>, // order matters !\n\n}\n\n\n\nimpl LudoGame {\n\n pub fn new() -> Self {\n\n let display = Display::new();\n", "file_path": "src/game.rs", "rank": 59, "score": 25.82615082278573 }, { "content": " // for player in self.active_players.iter() {\n\n same_player_next_chance = false; // may later be modified, if for eg. '6', or finishes etc.\n\n\n\n let player = &self.active_players[player_index];\n\n\n\n if self.engine.is_game_finished() {\n\n break;\n\n } else if self.engine.is_finished(player.colour) {\n\n continue;\n\n }\n\n\n\n self.engine.set_current_colour(player.colour);\n\n self.display.set_player(&player.name);\n\n self.update_display();\n\n\n\n print!(\"Press Enter to Roll: \");\n\n stdout().flush().unwrap();\n\n // ignore input till Enter\n\n let mut ignore_buf = String::new();\n\n stdin().read_line(&mut ignore_buf).unwrap();\n", "file_path": "src/game.rs", "rank": 60, "score": 19.943946273526308 }, { "content": " }\n\n }\n\n\n\n if active_players.is_empty() {\n\n Display::splash_screen(\"No players entered\", Some(Color::Red));\n\n std::thread::sleep(std::time::Duration::from_secs(10));\n\n panic!(\"No players entered\");\n\n }\n\n\n\n LudoGame {\n\n active_players,\n\n display,\n\n engine,\n\n }\n\n }\n\n\n\n fn update_display(&self) {\n\n // `display` component requires this\n\n let mut display_content = Vec::new();\n\n let board = &self.engine.get_board();\n", "file_path": "src/game.rs", "rank": 61, "score": 17.611139553934766 }, { "content": " let mut active_players = Vec::new();\n\n let mut active_colours = Vec::new();\n\n\n\n let player_names = display.get_player_names();\n\n let colors = [Rang::Red, Rang::Green, Rang::Yellow, Rang::Blue];\n\n\n\n for (i, name) in player_names.iter().enumerate() {\n\n if !name.is_empty() {\n\n active_colours.push(colors[i]);\n\n }\n\n }\n\n\n\n let engine = LudoEngine::new(active_colours);\n\n\n\n for (i, name) in player_names.iter().enumerate() {\n\n if !name.is_empty() {\n\n active_players.push(Player {\n\n name: name.clone(),\n\n colour: colors[i],\n\n })\n", "file_path": "src/game.rs", "rank": 62, "score": 17.56464326023081 }, { "content": " }\n\n }\n\n }\n\n\n\n for player in self.active_players.iter() {\n\n if self.engine.is_finished(player.colour) {\n\n display_content.push((Rang::GetEndCoord(player.colour), \"👑\".to_string()));\n\n }\n\n }\n\n\n\n self.display.update_display(display_content.clone());\n\n }\n\n\n\n pub fn play(&mut self) {\n\n self.update_display();\n\n\n\n // Will be updated at end of each iteration\n\n let mut player_index = 0;\n\n let mut same_player_next_chance;\n\n loop {\n", "file_path": "src/game.rs", "rank": 63, "score": 14.497802258527907 }, { "content": " }\n\n } else {\n\n println!(\"No possible moves...\");\n\n }\n\n\n\n if same_player_next_chance == false {\n\n // Next player\n\n player_index = (player_index + 1) % self.active_players.len();\n\n }\n\n\n\n std::thread::sleep(std::time::Duration::from_secs(1));\n\n }\n\n\n\n // !TODO\n\n }\n\n}\n\n\n\nimpl Drop for LudoGame {\n\n fn drop(&mut self) {\n\n self.display.end_display();\n\n }\n\n}\n", "file_path": "src/game.rs", "rank": 64, "score": 11.75412656499553 }, { "content": "\n\n for (i, row) in board.iter().enumerate() {\n\n for (j, cell) in row.iter().enumerate() {\n\n if !cell.gotis.is_empty() {\n\n // Invariant: Assuming all gotis in one cell, even if multiple, are of same color\n\n let mut content = match cell.gotis[0].borrow().colour {\n\n Rang::Red => '🔴',\n\n Rang::Green => '🟢',\n\n Rang::Yellow => '🟡',\n\n Rang::Blue => '🔵',\n\n }\n\n .to_string();\n\n\n\n if cell.gotis.len() > 1 {\n\n content.push_str(&cell.gotis.len().to_string())\n\n }\n\n\n\n display_content.push(((i as u8, j as u8), content));\n\n\n\n // Note: Not handling case of multiple gotis of different colors, in same cell, eg. \"RG\", \"RGRB\" which should be shown as \"R2GB\"\n", "file_path": "src/game.rs", "rank": 65, "score": 11.541153929283755 }, { "content": " i += 1;\n\n }\n\n\n\n for c in movable_gotis.iter() {\n\n println!(\"{}. [{}][{}]\", i, c.0, c.1);\n\n i += 1;\n\n }\n\n\n\n let mut input = String::new();\n\n stdin().read_line(&mut input).expect(\"Failed to read input\");\n\n\n\n let trimmed = input.trim();\n\n let mut chosen_option = match trimmed.parse::<u8>() {\n\n Ok(i) => i,\n\n Err(_) => {\n\n println!(\"Not a option: {:?}\", trimmed);\n\n println!(\"Repeating...\");\n\n // Probable bug: Dice output wont be same next time\n\n\n\n std::thread::sleep(std::time::Duration::from_secs(1));\n", "file_path": "src/game.rs", "rank": 66, "score": 11.512270434199541 }, { "content": " ignore_buf.clear();\n\n\n\n let roll = roll();\n\n\n\n println!(\"Roll Output - {:?}\", roll);\n\n\n\n if roll == 6 {\n\n same_player_next_chance = true;\n\n }\n\n\n\n let movable_gotis = self.engine.get_movable_gotis(player.colour, roll);\n\n\n\n if (roll == 6 && self.engine.get_num_locked(player.colour).unwrap() > 0)\n\n || !movable_gotis.is_empty()\n\n {\n\n println!(\"Chose from these options: \");\n\n\n\n let mut i = 0;\n\n if roll == 6 && self.engine.get_num_locked(player.colour).unwrap() > 0 {\n\n println!(\"0. Unlock New Goti (just type 0)\");\n", "file_path": "src/game.rs", "rank": 67, "score": 9.591944505663538 }, { "content": "mod display;\n\nmod engine;\n\nmod game;\n\n\n\nuse game::LudoGame as Ludo;\n\n\n", "file_path": "src/main.rs", "rank": 68, "score": 8.792506304940826 }, { "content": "use super::Rang;\n\nuse debug_print::debug_println;\n\n\n\n#[derive(PartialEq, Eq)]\n\npub struct LudoGoti {\n\n pub colour: Rang,\n\n pub coords: (u8,u8)\n\n}\n\n\n\nimpl Drop for LudoGoti {\n\n fn drop(&mut self) {\n\n debug_println!(\"(Ignore this, if another panic happened before this) Dropping {:?}, was at {:?}\", self.colour, self.coords);\n\n debug_assert!(self.coords == Rang::GetEndCoord(self.colour), \"Goti was not at finish location when dropped\");\n\n }\n\n}\n", "file_path": "src/engine/goti.rs", "rank": 69, "score": 8.025909599637956 }, { "content": "#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]\n\npub enum Rang {\n\n Red, // लाल\n\n Green, // हरा\n\n Yellow, // पीला\n\n Blue // नीला\n\n}\n\n\n\n#[allow(non_snake_case)]\n\nimpl Rang {\n\n pub(crate) fn GetStartCoord(colour: Rang) -> (u8, u8) {\n\n match colour {\n\n Self::Red => (13,6),\n\n Self::Green => (6,1),\n\n Self::Yellow => (1,8),\n\n Self::Blue => (8,13),\n\n }\n\n }\n\n\n\n pub(crate) fn GetEndCoord(colour: Rang) -> (u8, u8) {\n", "file_path": "src/engine/rang.rs", "rank": 70, "score": 7.29266298594757 }, { "content": "# Ludo-The Game (in Rust)\n\n\n\nDid it as a refresher on rust, it is totally inspired from [Ludo-The Game](https://github.com/adi-g15/Ludo-The_Game). Why duplicate my project ? ... :)\n\n\n\n![Screenshot](./ss.png)\n\n\n\n### Running\n\n\n\nInstall [rust](https://doc.rust-lang.org/stable/book/ch01-01-installation.html) and cargo, simple way is [rustup](rustup.rs/#install)\n\n\n\n```sh\n\ncargo run --release\n\n```\n\n\n\n### Features:\n\n* Built in separate components:\n\n - engine - Game Engine (say an API that internally does all the state keeping and internal logic of Ludo)\n\n - display- Display component using `crossterm` library, and COMPLETELY separate from this, you can very well use it in other 'Ludo' games, just provide array of strings and coords to box to print at.\n\n - game - The Ludo Game, using the engine and display component... consider it a 'reference implementation' of using the 'LudoEngine'\n\n\n\n* Ludo Engine: Complex term for a simple thing, does all internal logic of Ludo, say you are building an \"All in one\" game, you can just take this engine (inside the 'src/engine' directory), and built a perfectly working ludo component\n\n* Bas itna hi : )\n", "file_path": "README.md", "rank": 71, "score": 6.975006360354329 }, { "content": " match colour {\n\n Self::Red => (8,7),\n\n Self::Green => (7,6),\n\n Self::Yellow => (6,7),\n\n Self::Blue => (7,8),\n\n }\n\n }\n\n\n\n pub fn GetHomeTurn(colour: Rang) -> ((u8,u8),(u8,u8)) {\n\n match colour {\n\n Self::Red => ((14,7), (13,7)),\n\n Self::Green => ((7,0), (7,1)),\n\n Self::Yellow => ((0,7), (1,7)),\n\n Self::Blue => ((7,14), (7,13))\n\n }\n\n }\n\n\n\n pub fn GetLockedPositions(colour: Rang) -> [(u8,u8); 4] {\n\n match colour {\n\n Self::Red => [(10, 1), (10, 4), (13, 1), (13, 4)],\n\n Self::Green => [(1, 1), (1, 4), (4, 1), (4, 4)],\n\n Self::Yellow => [(1, 10), (1, 13), (4, 10), (4, 13)],\n\n Self::Blue => [(10, 10), (10, 13), (13, 10), (13, 13)]\n\n }\n\n }\n\n}\n", "file_path": "src/engine/rang.rs", "rank": 72, "score": 6.033943457612775 }, { "content": " continue;\n\n }\n\n };\n\n\n\n let mut skip_rest = true;\n\n\n\n if roll == 6 && self.engine.get_num_locked(player.colour).unwrap() > 0 {\n\n same_player_next_chance = true;\n\n\n\n if chosen_option == 0 {\n\n self.engine.unlock_goti(player.colour)\n\n .expect(\"No Goti to unlock... this is a bug, please report at https://github.com/ludo-game-self.engine/issues\");\n\n } else {\n\n chosen_option -= 1;\n\n skip_rest = false;\n\n }\n\n } else {\n\n skip_rest = false;\n\n }\n\n\n", "file_path": "src/game.rs", "rank": 73, "score": 5.798472476850469 }, { "content": "use std::{cell::RefCell, rc::Rc};\n\n\n\nuse super::goti::LudoGoti;\n\nuse super::rang::Rang;\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\n\npub enum LudoCellType {\n\n Default,\n\n SafeSpot,\n\n LockedPosition(Rang),\n\n HomeLane(Rang),\n\n\n\n NoUse // MUST not be mutated, such a cell will panic on invalid (eg. movedHere etc.)\n\n}\n\n\n\npub struct LudoCell {\n\n pub cell_type: LudoCellType,\n\n pub gotis: Vec<Rc<RefCell<LudoGoti>>>\n\n}\n", "file_path": "src/engine/cell.rs", "rank": 74, "score": 5.452947650749265 }, { "content": " if !skip_rest {\n\n // Choice is one of `movable_gotis`\n\n match movable_gotis.get(chosen_option as usize) {\n\n Some(start_coord) => {\n\n let result = self.engine.move_goti(player.colour, *start_coord, roll)\n\n .expect(\"Could not move, although .get_movable_gotis() said i can :(... this is a bug, please report at https://github.com/ludo-game-self.engine/issues\");\n\n\n\n match result {\n\n MoveResult::Attacked(_)\n\n | MoveResult::Finished\n\n | MoveResult::Unlocked => {\n\n same_player_next_chance = true;\n\n }\n\n MoveResult::NormalMove(_) => {}\n\n };\n\n }\n\n None => {\n\n println!(\"Invalid choice: {:?}\", chosen_option);\n\n }\n\n }\n", "file_path": "src/game.rs", "rank": 75, "score": 4.714567148893618 }, { "content": "use rand::Rng;\n\n\n", "file_path": "src/engine/dice.rs", "rank": 76, "score": 2.984550445611694 } ]
Rust
pallets/kitties/src/lib.rs
pillarBoy/advance-lesson-2
f5dd1e736ec1c2e073c7e3093e252f004ffda68e
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use frame_support::{ Parameter, RuntimeDebug, StorageDoubleMap, StorageValue, decl_error, decl_event, decl_module, decl_storage, dispatch::{ DispatchError, DispatchResult }, ensure, traits::Get, traits::{ Currency, ExistenceRequirement::AllowDeath, ReservableCurrency, Randomness }, }; use sp_io::hashing::{blake2_128}; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, One, CheckedAdd}; use sp_std::prelude::*; #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub struct Kitty(pub [u8; 16]); #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub struct KittyNode<T: Trait> { _self: T::KittyIndex, companion: Option<(T::KittyIndex, T::KittyIndex)>, children: Vec<T::KittyIndex>, } type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance; pub trait Trait: frame_system::Trait { type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; type Randomness: Randomness<Self::Hash>; type KittyIndex: Parameter + AtLeast32BitUnsigned + Bounded + Default + Copy; type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>; type KittyReserveFunds: Get<BalanceOf<Self>>; } decl_storage! { trait Store for Module<T: Trait> as Kitties { pub Kitties get(fn kitties): double_map hasher(blake2_128_concat) T::AccountId, hasher(blake2_128_concat) T::KittyIndex => Option<Kitty>; pub KittiesCount get(fn kitties_count): T::KittyIndex; pub KittyOwners get(fn kitty_owner): map hasher(blake2_128_concat) T::KittyIndex => Option<T::AccountId>; pub AccountKitties get(fn account_kitties): map hasher(blake2_128_concat) T::AccountId => Vec<(T::KittyIndex, Kitty)>; pub KittyLockAmount get(fn lock_amount): map hasher(blake2_128_concat) T::KittyIndex => Option<BalanceOf<T>>; pub KittyNodeStorage get(fn get_kitty_from_node): Vec<KittyNode<T>>; } } decl_event! { pub enum Event<T> where <T as frame_system::Trait>::AccountId, <T as Trait>::KittyIndex, Balance = BalanceOf<T>, BlockNumber = <T as system::Trait>::BlockNumber, { Created(AccountId, KittyIndex), Transfered(AccountId, AccountId, KittyIndex), LockFunds(AccountId, Balance, BlockNumber), UnlockFunds(AccountId, Balance, BlockNumber), TransferFunds(AccountId, AccountId, Balance, BlockNumber), } } decl_error! { pub enum Error for Module<T: Trait> { KittiesCountOverflow, InvalidaKittyId, RequireDifferentParent, AccountNotExist, BalanceNotEnough, } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 0] pub fn reserve_funds(origin, locker: T::AccountId, amount: BalanceOf<T>) -> DispatchResult { let _sender = ensure_signed(origin)?; T::Currency::reserve(&locker, amount) .map_err(|_| Error::<T>::BalanceNotEnough)?; let now = <system::Module<T>>::block_number(); Self::deposit_event(RawEvent::LockFunds(locker, amount, now)); Ok(()) } #[weight = 10_000] pub fn unreserve_and_transfer( origin, to_punish: T::AccountId, dest: T::AccountId, collateral: BalanceOf<T> ) -> DispatchResult { let _ = ensure_signed(origin)?; let overdraft = T::Currency::unreserve(&to_punish, collateral); T::Currency::transfer(&to_punish, &dest, collateral - overdraft, AllowDeath)?; let now = <system::Module<T>>::block_number(); Self::deposit_event(RawEvent::TransferFunds(to_punish, dest, collateral - overdraft, now)); Ok(()) } #[weight = 1000] pub fn create(origin) -> DispatchResult { let sender = ensure_signed(origin.clone())?; let kitty_id = Self::next_kitty_id()?; let dna = Self::random_value(&sender); let kitty = Kitty(dna); Self::insert_kitty(&sender, kitty_id, kitty)?; let amount = T::KittyReserveFunds::get(); KittyLockAmount::<T>::insert(kitty_id, amount); Self::reserve_funds(origin, sender.clone(), amount)?; Self::deposit_event(RawEvent::Created(sender.clone(), kitty_id)); let mut node_vec = KittyNodeStorage::<T>::take(); let node = KittyNode { _self: kitty_id, children: Vec::new(), companion: None, }; node_vec.push(node); KittyNodeStorage::<T>::put(node_vec); Ok(()) } #[weight = 0] pub fn transfer(origin, to: T::AccountId, kitty_id: T::KittyIndex) -> DispatchResult { let sender = ensure_signed(origin.clone())?; let kitty = Kitties::<T>::take(&sender, kitty_id).ok_or(Error::<T>::InvalidaKittyId)?; let sender_kitty_vec = AccountKitties::<T>::take(&sender); let mut to_kitty_vec = AccountKitties::<T>::take(&to); let mut new_sender_k_vec = Vec::new(); for (kid, kt) in sender_kitty_vec.iter() { if kid != &kitty_id { new_sender_k_vec.push((*kid, kt)); } else { to_kitty_vec.push((*kid, kitty.clone())); } } AccountKitties::<T>::insert(&sender, new_sender_k_vec); AccountKitties::<T>::insert(&to, to_kitty_vec); KittyOwners::<T>::insert(&kitty_id, to.clone()); let amount = Self::lock_amount(kitty_id).ok_or(Error::<T>::InvalidaKittyId)?; Self::unreserve_and_transfer(origin.clone(), sender.clone(), to.clone(), amount)?; Self::reserve_funds(origin, to.clone(), amount)?; Self::deposit_event(RawEvent::Transfered(sender, to, kitty_id)); Ok(()) } #[weight = 0] pub fn breed(origin, kitty_id_1: T::KittyIndex, kitty_id_2: T::KittyIndex) { let sender = ensure_signed(origin.clone())?; let amount = T::KittyReserveFunds::get(); let new_kitty_id = Self::do_breed(&sender, kitty_id_1, kitty_id_2)?; KittyLockAmount::<T>::insert(&new_kitty_id, amount.clone()); Self::reserve_funds(origin, sender.clone(), amount)?; let mut node_vec = KittyNodeStorage::<T>::take(); for k in &mut node_vec.iter_mut() { if k._self == kitty_id_1 { k.children.push(new_kitty_id); } else if k._self == kitty_id_2 { k.children.push(new_kitty_id); } } let node = KittyNode { _self: new_kitty_id, children: Vec::new(), companion: Some((kitty_id_1, kitty_id_2)), }; node_vec.push(node); KittyNodeStorage::<T>::put(node_vec); Self::deposit_event(RawEvent::Created(sender, new_kitty_id)); } } } fn combine_dna(dna1: u8, dna2: u8, selector: u8) -> u8 { (selector & dna1) | (!selector & dna2) } impl<T: Trait> Module<T> { fn next_kitty_id() -> sp_std::result::Result<T::KittyIndex, DispatchError> { let kitty_id = Self::kitties_count().checked_add(&One::one()).ok_or(Error::<T>::KittiesCountOverflow)?; Ok(kitty_id) } fn random_value(sender: &T::AccountId) -> [u8;16] { let payload = ( T::Randomness::random_seed(), &sender, <frame_system::Module<T>>::extrinsic_index(), ); payload.using_encoded(blake2_128) } fn insert_kitty(owner: &T::AccountId, kitty_id: T::KittyIndex, kitty: Kitty) -> DispatchResult { Kitties::<T>::insert(&owner, kitty_id, kitty.clone()); KittyOwners::<T>::insert(kitty_id, &owner); let mut kitty_vec = AccountKitties::<T>::take(&owner); kitty_vec.push((kitty_id, kitty)); AccountKitties::<T>::insert(&owner, kitty_vec); KittiesCount::<T>::put(kitty_id); Ok(()) } fn do_breed(sender: &T::AccountId, kitty_id_1: T::KittyIndex, kitty_id_2: T::KittyIndex) -> sp_std::result::Result<T::KittyIndex, DispatchError> { let kitty1 = Self::kitties(&sender, kitty_id_1).ok_or(Error::<T>::InvalidaKittyId)?; let kitty2 = Self::kitties(&sender, kitty_id_2).ok_or(Error::<T>::InvalidaKittyId)?; ensure!(kitty_id_1 != kitty_id_2, Error::<T>::RequireDifferentParent); let kitty_id = Self::next_kitty_id()?; let kitty1_dna = kitty1.0; let kitty2_dna = kitty2.0; let selector = Self::random_value(&sender); let mut new_dna = [0u8; 16]; for i in 0..kitty1_dna.len() { new_dna[i] = combine_dna(kitty1_dna[i], kitty2_dna[i], selector[i]); } Self::insert_kitty(sender, kitty_id, Kitty(new_dna))?; Ok(kitty_id) } }
#![cfg_attr(not(feature = "std"), no_std)] use codec::{Encode, Decode}; use frame_support::{ Parameter, RuntimeDebug, StorageDoubleMap, StorageValue, decl_error, decl_event, decl_module, decl_storage, dispatch::{ DispatchError, DispatchResult }, ensure, traits::Get, traits::{ Currency, ExistenceRequirement::AllowDeath, ReservableCurrency, Randomness }, }; use sp_io::hashing::{blake2_128}; use frame_system::{self as system, ensure_signed}; use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, One, CheckedAdd}; use sp_std::prelude::*; #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub struct Kitty(pub [u8; 16]); #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] pub struct KittyNode<T: Trait> { _self: T::KittyIndex, companion: Option<(T::KittyIndex, T::KittyIndex)>, children: Vec<T::KittyIndex>, } type BalanceOf<T> = <<T as Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance; pub trait Trait: frame_system::Trait { type Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>; type Randomness: Randomness<Self::Hash>; type KittyIndex: Parameter + AtLeast32BitUnsigned + Bounded + Default + Copy; type Currency: Currency<Self::AccountId> + ReservableCurrency<Self::AccountId>; type KittyReserveFunds: Get<BalanceOf<Self>>; } decl_storage! { trait Store for Module<T: Trait> as Kitties { pub Kitties get(fn kitties): double_map hasher(blake2_128_concat) T::AccountId, hasher(blake2_128_concat) T::KittyIndex => Option<Kitty>; pub KittiesCount get(fn kitties_count): T::KittyIndex; pub KittyOwners get(fn kitty_owner): map hasher(blake2_128_concat) T::KittyIndex => Option<T::AccountId>; pub AccountKitties get(fn account_kitties): map hasher(blake2_128_concat) T::AccountId => Vec<(T::KittyIndex, Kitty)>; pub KittyLockAmount get(fn lock_amount): map hasher(blake2_128_concat) T::KittyIndex => Option<BalanceOf<T>>; pub KittyNodeStorage get(fn get_kitty_from_node): Vec<KittyNode<T>>; } } decl_event! { pub enum Event<T> where <T as frame_system::Trait>::AccountId, <T as Trait>::KittyIndex, Balance = BalanceOf<T>, BlockNumber = <T as system::Trait>::BlockNumber, { Created(AccountId, KittyIndex), Transfered(AccountId, AccountId, KittyIndex), LockFunds(AccountId, Balance, BlockNumber), UnlockFunds(AccountId, Balance, BlockNumber), TransferFunds(AccountId, AccountId, Balance, BlockNumber), } } decl_error! { pub enum Error for Module<T: Trait> { KittiesCountOverflow, InvalidaKittyId, RequireDifferentParent, AccountNotExist, BalanceNotEnough, } } decl_module! { pub struct Module<T: Trait> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; #[weight = 0] pub fn reserve_funds(origin, locker: T::AccountId, amount: BalanceOf<T>) -> DispatchResult { let _sender = ensure_signed(origin)?; T::Currency::reserve(&locker, amount) .map_err(|_| Error::<T>::BalanceNotEnough)?; let now = <system::Module<T>>::block_number(); Self::deposit_event(RawEvent::LockFunds(locker, amount, now)); Ok(()) } #[weight = 10_000] pub fn unreserve_and_transfer( origin, to_punish: T::AccountId, dest: T::AccountId, collateral: BalanceOf<T> ) -> DispatchResult { let _ = ensure_signed(origin)?; let overdraft = T::Currency::unreserve(&to_punish, collateral); T::Currency::transfer(&to_punish, &dest, collateral - overdraft, AllowDeath)?; let now = <system::Module<T>>::block_number(); Self::deposit_event(RawEvent::TransferFunds(to_punish, dest, collateral - overdraft, now)); Ok(()) } #[weight = 1000] pub fn create(origin) -> DispatchResult { let sender = ensure_signed(origin.clone())?; let kitty_id = Self::next_kitty_id()?; let dna = Self::random_value(&sender); let kitty = Kitty(dna); Self::insert_kitty(&sender, kitty_id, kitty)?; let amount = T::KittyReserveFunds::get(); KittyLockAmount::<T>::insert(kitty_id, amount); Self::reserve_funds(origin, sender.clone(), amount)?; Self::deposit_event(RawEvent::Created(sender.clone(), kitty_id)); let mut node_vec = KittyNodeStorage::<T>::take(); let node = KittyNode { _self: kitty_id, children: Vec::new(), companion: None, }; node_vec.push(node); KittyNodeStorage::<T>::put(node_vec); Ok(()) } #[weight = 0] pub fn transfer(origin, to: T::AccountId, kitty_id: T::KittyIndex) -> DispatchResult { let sender = ensure_signed(origin.clone())?; let kitty = Kitties::<T>::take(&sender, kitty_id).ok_or(Error::<T>::InvalidaKittyId)?; let sender_kitty_vec = AccountKitties::<T>::take(&sender); let mut to_kitty_vec = AccountKitties::<T>::take(&to); let mut new_sender_k_vec = Vec::new(); for (kid, kt) in sender_kitty_vec.iter() { if kid != &kitty_id { new_sender_k_vec.push((*kid, kt)); } else { to_kitty_vec.push((*kid, kitty.clone())); } } AccountKitties::<T>::insert(&sender, new_sender_k_vec); AccountKitties::<T>::insert(&to, to_kitty_vec); KittyOwners::<T>::insert(&kitty_id, to.clone()); let amount = Self::lock_amount(kitty_id).ok_or(Error::<T>::InvalidaKittyId)?; Self::unreserve_and_transfer(origin.clone(), sender.clone(), to.clone(), amount)?; Self::reserve_funds(origin, to.clone(), amount)?; Self::deposit_event(RawEvent::Transfered(sender, to, kitty_id)); Ok(()) } #[weight = 0] pub fn breed(origin, kitty_id_1: T::KittyIndex, kitty_id_2: T::KittyIndex) { let sender = ensure_signed(origin.clone())?; let amount = T::KittyReserveFunds::get(); let new_kitty_id = Self::do_breed(&sender, kitty_id_1, kitty_id_2)?; KittyLockAmount::<T>::insert(&new_kitty_id, amount.clone()); Self::reserve_funds(origin, sender.clone(), amount)?; let mut node_vec = KittyNodeStorage::<T>::take(); for k in &mut node_vec.iter_mut() { if k._self == kitty_id_1 { k.children.push(new_kitty_id); } else if k._self == kitty_id_2 { k.children.push(new_kitty_id); } } let node = KittyNode { _self: new_kitty_id, children: Vec::new(), companion: Some((kitty_id_1, kitty_id_2)), }; node_vec.push(node); KittyNodeStorage::<T>::put(node_vec); Self::deposit_event(RawEvent::Created(sender, new_kitty_id)); } } } fn combine_dna(dna1: u8, dna2: u8, selector: u8) -> u8 { (selector & dna1) | (!selector & dna2) } impl<T: Trait> Module<T> { fn next_kitty_id() -> sp_std::result::Result<T::KittyIndex, DispatchError> { let kitty_id = Self::kitties_count().checked_add(&One::one()).ok_or(Error::<T>::KittiesCountOverflow)?; Ok(kitty_id) } fn random_value(sender: &T::AccountId) -> [u8;16] { let payload = ( T::Randomness::random_see
fn insert_kitty(owner: &T::AccountId, kitty_id: T::KittyIndex, kitty: Kitty) -> DispatchResult { Kitties::<T>::insert(&owner, kitty_id, kitty.clone()); KittyOwners::<T>::insert(kitty_id, &owner); let mut kitty_vec = AccountKitties::<T>::take(&owner); kitty_vec.push((kitty_id, kitty)); AccountKitties::<T>::insert(&owner, kitty_vec); KittiesCount::<T>::put(kitty_id); Ok(()) } fn do_breed(sender: &T::AccountId, kitty_id_1: T::KittyIndex, kitty_id_2: T::KittyIndex) -> sp_std::result::Result<T::KittyIndex, DispatchError> { let kitty1 = Self::kitties(&sender, kitty_id_1).ok_or(Error::<T>::InvalidaKittyId)?; let kitty2 = Self::kitties(&sender, kitty_id_2).ok_or(Error::<T>::InvalidaKittyId)?; ensure!(kitty_id_1 != kitty_id_2, Error::<T>::RequireDifferentParent); let kitty_id = Self::next_kitty_id()?; let kitty1_dna = kitty1.0; let kitty2_dna = kitty2.0; let selector = Self::random_value(&sender); let mut new_dna = [0u8; 16]; for i in 0..kitty1_dna.len() { new_dna[i] = combine_dna(kitty1_dna[i], kitty2_dna[i], selector[i]); } Self::insert_kitty(sender, kitty_id, Kitty(new_dna))?; Ok(kitty_id) } }
d(), &sender, <frame_system::Module<T>>::extrinsic_index(), ); payload.using_encoded(blake2_128) }
function_block-function_prefixed
[ { "content": "pub fn last_event() -> Event {\n\n System::events().last().unwrap().event.clone()\n\n}", "file_path": "pallets/kitties/src/mock.rs", "rank": 2, "score": 148286.20940153103 }, { "content": "/// Configure the pallet by specifying the parameters and types on which it depends.\n\npub trait Trait: frame_system::Trait {\n\n\t/// Because this pallet emits events, it depends on the runtime's definition of an event.\n\n\ttype Event: From<Event<Self>> + Into<<Self as frame_system::Trait>::Event>;\n\n}\n\n\n\n// The pallet's runtime storage items.\n\n// https://substrate.dev/docs/en/knowledgebase/runtime/storage\n\ndecl_storage! {\n", "file_path": "pallets/template/src/lib.rs", "rank": 4, "score": 120451.16229257958 }, { "content": "/// Builds a new service for a light client.\n\npub fn new_light(config: Configuration) -> Result<TaskManager, ServiceError> {\n\n\tlet (client, backend, keystore, mut task_manager, on_demand) =\n\n\t\tsc_service::new_light_parts::<Block, RuntimeApi, Executor>(&config)?;\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::light_block_import(\n\n\t\tclient.clone(), backend.clone(), &(client.clone() as Arc<_>),\n\n\t\tArc::new(on_demand.checker().clone()) as Arc<_>,\n\n\t)?;\n\n\tlet finality_proof_import = grandpa_block_import.clone();\n\n\tlet finality_proof_request_builder =\n\n\t\tfinality_proof_import.create_finality_proof_request_builder();\n\n\n", "file_path": "node/src/service.rs", "rank": 6, "score": 96530.00270438458 }, { "content": "/// Builds a new service for a full client.\n\npub fn new_full(config: Configuration) -> Result<TaskManager, ServiceError> {\n\n\tlet sc_service::PartialComponents {\n\n\t\tclient, backend, mut task_manager, import_queue, keystore, select_chain, transaction_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\tlet finality_proof_provider =\n\n\t\tGrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone());\n\n\n\n\tlet (network, network_status_sinks, system_rpc_tx, network_starter) =\n\n\t\tsc_service::build_network(sc_service::BuildNetworkParams {\n\n\t\t\tconfig: &config,\n\n\t\t\tclient: client.clone(),\n\n\t\t\ttransaction_pool: transaction_pool.clone(),\n\n\t\t\tspawn_handle: task_manager.spawn_handle(),\n\n\t\t\timport_queue,\n\n\t\t\ton_demand: None,\n\n\t\t\tblock_announce_validator_builder: None,\n\n\t\t\tfinality_proof_request_builder: None,\n", "file_path": "node/src/service.rs", "rank": 7, "score": 96530.00270438456 }, { "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::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\n\t\t\t\tlet PartialComponents { client, task_manager, ..}\n", "file_path": "node/src/command.rs", "rank": 8, "score": 94800.98877796408 }, { "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": 9, "score": 94800.98877796408 }, { "content": "#[test]\n\nfn correct_error_for_none_value() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\t// Ensure the expected error is thrown when no value is present.\n\n\t\tassert_noop!(\n\n\t\t\tTemplateModule::cause_error(Origin::signed(1)),\n\n\t\t\tError::<Test>::NoneValue\n\n\t\t);\n\n\t});\n\n}\n", "file_path": "pallets/template/src/tests.rs", "rank": 10, "score": 87327.32571701195 }, { "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()\n\n\t\t.build_storage::<Test>()\n\n\t\t.unwrap();\n\n\n\n\tbalances::GenesisConfig::<Test> {\n\n\t\t// Provide some initial balances\n\n\t\tbalances: vec![(1, 10000), (2, 11000), (3, 12000), (4, 13000), (5, 14000)],\n\n\t}\n\n\t.assimilate_storage(&mut t)\n\n\t.unwrap();\n\n\tlet mut ext: sp_io::TestExternalities = t.into();\n\n\text.execute_with(|| System::set_block_number(1));\n\n\text\n\n}\n\n\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 11, "score": 86811.42233058502 }, { "content": "pub fn development_config() -> Result<ChainSpec, String> {\n\n\tlet wasm_binary = WASM_BINARY.ok_or(\"Development wasm binary 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": 12, "score": 85470.00432625247 }, { "content": "#[test]\n\nfn reserve_funds_failed_not_enough_balance() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\tassert_noop!(KModule::reserve_funds(Origin::signed(1), 1, 12000), Error::<Test>::BalanceNotEnough);\n\n\t});\n\n}\n\n\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 13, "score": 83600.52794508013 }, { "content": "pub fn local_testnet_config() -> Result<ChainSpec, String> {\n\n\tlet wasm_binary = WASM_BINARY.ok_or(\"Development wasm binary 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": 14, "score": 83534.67829321919 }, { "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": 15, "score": 83522.08736755366 }, { "content": "\t// A unique name is used to ensure that the pallet's storage items are isolated.\n\n\t// This name may be updated, but each pallet in the runtime must use a unique name.\n\n\t// ---------------------------------vvvvvvvvvvvvvv\n\n\ttrait Store for Module<T: Trait> as TemplateModule {\n\n\t\t// Learn more about declaring storage items:\n\n\t\t// https://substrate.dev/docs/en/knowledgebase/runtime/storage#declaring-storage-items\n\n\t\tSomething get(fn something): Option<u32>;\n\n\t}\n\n}\n\n\n\n// Pallets use events to inform users when important changes are made.\n\n// https://substrate.dev/docs/en/knowledgebase/runtime/events\n\ndecl_event!(\n\n\tpub enum Event<T> where AccountId = <T as frame_system::Trait>::AccountId {\n\n\t\t/// Event documentation should end with an array that provides descriptive names for event\n\n\t\t/// parameters. [something, who]\n\n\t\tSomethingStored(u32, AccountId),\n\n\t}\n\n);\n\n\n\n// Errors inform users that something went wrong.\n\ndecl_error! {\n\n\tpub enum Error for Module<T: Trait> {\n", "file_path": "pallets/template/src/lib.rs", "rank": 16, "score": 83017.36163280156 }, { "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": 17, "score": 79517.6530587407 }, { "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\tlet inherent_data_providers = sp_inherents::InherentDataProviders::new();\n\n\n\n\tlet (client, backend, keystore, task_manager) =\n\n\t\tsc_service::new_full_parts::<Block, RuntimeApi, Executor>(&config)?;\n\n\tlet client = Arc::new(client);\n\n\n", "file_path": "node/src/service.rs", "rank": 18, "score": 77632.47355813974 }, { "content": "#[cfg(feature = \"std\")]\n\npub fn native_version() -> NativeVersion {\n\n\tNativeVersion {\n\n\t\truntime_version: VERSION,\n\n\t\tcan_author_with: Default::default(),\n\n\t}\n\n}\n\n\n\nparameter_types! {\n\n\tpub const BlockHashCount: BlockNumber = 2400;\n\n\t/// We allow for 2 seconds of compute with a 6 second average block time.\n\n\tpub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;\n\n\tpub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);\n\n\t/// Assume 10% of weight for average on_initialize calls.\n\n\tpub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()\n\n\t\t.saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();\n\n\tpub const MaximumBlockLength: u32 = 5 * 1024 * 1024;\n\n\tpub const Version: RuntimeVersion = VERSION;\n\n}\n\n\n\n// Configure FRAME pallets to include in runtime.\n", "file_path": "runtime/src/lib.rs", "rank": 19, "score": 77378.64089592198 }, { "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": 20, "score": 72861.70769225608 }, { "content": "#[test]\n\nfn can_create_kitty() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\tassert_ok!(KModule::create(Origin::signed(1), 100));\n\n\n\n let kt = Kitty([39, 140, 77, 194, 163, 1, 154, 220, 108, 18, 30, 32, 100, 223, 46, 1]);\n\n assert_eq!(KModule::kitties(1, 1), Some(kt.clone()));\n\n\t\tassert_eq!(KModule::kitties_count(), 1);\n\n\n\n\t\t// 创建kitty 检查质押token\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 100);\n\n\t\t\n\n assert_eq!(last_event(), Event::kitties(RawEvent::Created(1, 1)));\n\n\t});\n\n}\n\n\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 21, "score": 72801.16066806077 }, { "content": "// Build genesis storage according to the mock runtime.\n\npub fn new_test_ext() -> sp_io::TestExternalities {\n\n\tsystem::GenesisConfig::default().build_storage::<Test>().unwrap().into()\n\n}\n", "file_path": "pallets/template/src/mock.rs", "rank": 22, "score": 68341.38910452291 }, { "content": "#[test]\n\nfn can_transfer() {\n\n new_test_ext().execute_with(|| {\n\n assert_ok!(KModule::create(Origin::signed(1), 100));\n\n\n\n assert_eq!(KModule::kitties_count(), 1);\n\n\n\n\t\t// kitty id 不正确 不可以转移\n\n assert_noop!(KModule::transfer(Origin::signed(1), 2, 0), Error::<Test>::InvalidaKittyId);\n\n\t\tassert_ok!(KModule::transfer(Origin::signed(1), 2, 1));\n\n\t\t\n\n\t\t// transfer kitty 检查账户1质押token\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 0);\n\n\t\t// transfer kitty 检查账户2质押token\n\n\t\tassert_eq!(Balances::free_balance(2), 11000);\n\n\t\tassert_eq!(Balances::reserved_balance(2), 100);\n\n\t\t// 检查 event\n\n assert_eq!(last_event(), Event::kitties(RawEvent::Transfered(1, 2, 1)));\n\n });\n\n}\n\n\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 23, "score": 67059.37442447359 }, { "content": "#[test]\n\nfn can_breed() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\tassert_ok!(KModule::create(Origin::signed(1), 100));\n\n\t\t// transfer kitty 检查账户1质押token\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 100);\n\n\t\t// 再生一个\n\n\t\tassert_ok!(KModule::create(Origin::signed(1), 100));\n\n\t\t// transfer kitty 检查账户1质押token\n\n\t\tassert_eq!(Balances::free_balance(&1), 9800);\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 200);\n\n\n\n\t\t// 边界检查\n\n\t\tassert_noop!(KModule::breed(Origin::signed(1), 0, 3, 100), Error::<Test>::InvalidaKittyId);\n\n\t\tassert_noop!(KModule::breed(Origin::signed(1), 1, 1, 100), Error::<Test>::RequireDifferentParent);\n\n\t\t// do breed\n\n\t\tassert_ok!(KModule::breed(Origin::signed(1), 1, 2, 100));\n\n\t\tlet kt = Kitty([39, 140, 77, 194, 163, 1, 154, 220, 108, 18, 30, 32, 100, 223, 46, 1]);\n\n\t\tassert_eq!(KModule::kitties(1, 3), Some(kt.clone()));\n\n\t\tassert_eq!(KModule::kitties_count(), 3);\n\n\n\n\t\t// transfer kitty 检查账户1质押token\n\n\t\tassert_eq!(Balances::free_balance(&1), 9700);\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 300);\n\n\n\n\t\tassert_eq!(last_event(), Event::kitties(RawEvent::Created(1, 3)));\n\n\t})\n\n}", "file_path": "pallets/kitties/src/tests.rs", "rank": 24, "score": 67059.37442447359 }, { "content": "#[test]\n\nfn it_works_for_default_value() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\t// Dispatch a signed extrinsic.\n\n\t\tassert_ok!(TemplateModule::do_something(Origin::signed(1), 42));\n\n\t\t// Read pallet storage and assert an expected result.\n\n\t\tassert_eq!(TemplateModule::something(), Some(42));\n\n\t});\n\n}\n\n\n", "file_path": "pallets/template/src/tests.rs", "rank": 25, "score": 66542.08441571286 }, { "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": 26, "score": 66237.59365445885 }, { "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": 27, "score": 66029.79181158401 }, { "content": "#[test]\n\nfn can_reserve_funds() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\tassert_ok!(KModule::reserve_funds(Origin::signed(1), 1, 100));\n\n\n\n\t\tassert_eq!(last_event(), Event::kitties(RawEvent::LockFunds(1, 100, 1)));\n\n\n\n\t\t// Test and see if (1, 5000) holds 账户可转账余额\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\t// 账户锁仓余额\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 100);\n\n\t});\n\n}\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 28, "score": 65175.762989588395 }, { "content": "#[test]\n\nfn can_unreserve_and_transfer() {\n\n\tnew_test_ext().execute_with(|| {\n\n\t\tassert_ok!(KModule::reserve_funds(Origin::signed(1), 1, 100));\n\n\t\t// Test and see if (1, 5000) holds 账户可转账余额\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\t// 账户锁仓余额\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 100);\n\n\t\tassert_eq!(last_event(), Event::kitties(RawEvent::LockFunds(1, 100, 1)));\n\n\n\n\t\t// 转移质押token\n\n\t\tassert_ok!(KModule::unreserve_and_transfer(Origin::signed(1), 1, 2, 100));\n\n\t\t// 转移质押event\n\n\t\tassert_eq!(last_event(), Event::kitties(RawEvent::TransferFunds(1, 2, 100, 1)));\n\n\n\n\t\tassert_eq!(Balances::reserved_balance(&1), 0);\n\n\t\tassert_eq!(Balances::reserved_balance(&2), 0);\n\n\t\tassert_eq!(Balances::free_balance(&1), 9900);\n\n\t\tassert_eq!(Balances::free_balance(&2), 11100);\n\n\n\n\t});\n\n}\n\n\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 29, "score": 65175.762989588395 }, { "content": "fn main() -> sc_cli::Result<()> {\n\n\tcommand::run()\n\n}\n", "file_path": "node/src/main.rs", "rank": 30, "score": 60143.770155701124 }, { "content": "type AccountPublic = <Signature as Verify>::Signer;\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 31, "score": 56736.885825222314 }, { "content": "type FullBackend = sc_service::TFullBackend<Block>;\n", "file_path": "node/src/service.rs", "rank": 32, "score": 55274.80903595456 }, { "content": "type FullSelectChain = sc_consensus::LongestChain<FullBackend, Block>;\n\n\n", "file_path": "node/src/service.rs", "rank": 33, "score": 51332.07302479367 }, { "content": "type FullClient = sc_service::TFullClient<Block, RuntimeApi, Executor>;\n", "file_path": "node/src/service.rs", "rank": 34, "score": 48990.5851221359 }, { "content": "fn main() {\n\n\tWasmBuilder::new()\n\n\t\t.with_current_project()\n\n\t\t.with_wasm_builder_from_crates(\"2.0.0\")\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": 35, "score": 47298.60998461467 }, { "content": "use substrate_build_script_utils::{generate_cargo_keys, rerun_if_git_head_changed};\n\n\n", "file_path": "node/build.rs", "rank": 36, "score": 26864.167712584847 }, { "content": "//! A collection of node-specific RPC methods.\n\n//! Substrate provides the `sc-rpc` crate, which defines the core RPC layer\n\n//! used by Substrate nodes. This file extends those RPC definitions with\n\n//! capabilities that are specific to this project's runtime configuration.\n\n\n\n#![warn(missing_docs)]\n\n\n\nuse std::sync::Arc;\n\n\n\nuse node_template_runtime::{opaque::Block, AccountId, Balance, Index};\n\nuse sp_api::ProvideRuntimeApi;\n\nuse sp_blockchain::{Error as BlockChainError, HeaderMetadata, HeaderBackend};\n\nuse sp_block_builder::BlockBuilder;\n\npub use sc_rpc_api::DenyUnsafe;\n\nuse sp_transaction_pool::TransactionPool;\n\n\n\n\n\n/// Full client dependencies.\n\npub struct FullDeps<C, P> {\n\n\t/// The client instance to use.\n\n\tpub client: Arc<C>,\n\n\t/// Transaction pool instance.\n\n\tpub pool: Arc<P>,\n\n\t/// Whether to deny unsafe calls\n\n\tpub deny_unsafe: DenyUnsafe,\n\n}\n\n\n\n/// Instantiate all full RPC extensions.\n", "file_path": "node/src/rpc.rs", "rank": 37, "score": 25577.908066285458 }, { "content": "\n\n\tio.extend_with(\n\n\t\tSystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))\n\n\t);\n\n\n\n\tio.extend_with(\n\n\t\tTransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))\n\n\t);\n\n\n\n\t// Extend this RPC with a custom API by using the following syntax.\n\n\t// `YourRpcStruct` should have a reference to a client, which is needed\n\n\t// to call into the runtime.\n\n\t// `io.extend_with(YourRpcTrait::to_delegate(YourRpcStruct::new(ReferenceToClient, ...)));`\n\n\n\n\tio\n\n}\n", "file_path": "node/src/rpc.rs", "rank": 38, "score": 25577.537250493402 }, { "content": "//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.\n\n\n\nuse std::sync::Arc;\n\nuse std::time::Duration;\n\nuse sc_client_api::{ExecutorProvider, RemoteBackend};\n\nuse node_template_runtime::{self, opaque::Block, RuntimeApi};\n\nuse sc_service::{error::Error as ServiceError, Configuration, TaskManager};\n\nuse sp_inherents::InherentDataProviders;\n\nuse sc_executor::native_executor_instance;\n\npub use sc_executor::NativeExecutor;\n\nuse sp_consensus_aura::sr25519::{AuthorityPair as AuraPair};\n\nuse sc_finality_grandpa::{FinalityProofProvider as GrandpaFinalityProofProvider, SharedVoterState};\n\n\n\n// Our native executor instance.\n\nnative_executor_instance!(\n\n\tpub Executor,\n\n\tnode_template_runtime::api::dispatch,\n\n\tnode_template_runtime::native_version,\n\n\tframe_benchmarking::benchmarking::HostFunctions,\n\n);\n\n\n", "file_path": "node/src/service.rs", "rank": 39, "score": 25577.29778645747 }, { "content": "\t\t\tnetwork.clone(),\n\n\t\t\tinherent_data_providers.clone(),\n\n\t\t\tforce_authoring,\n\n\t\t\tkeystore.clone(),\n\n\t\t\tcan_author_with,\n\n\t\t)?;\n\n\n\n\t\t// the AURA authoring task is considered essential, i.e. if it\n\n\t\t// fails we take down the service with it.\n\n\t\ttask_manager.spawn_essential_handle().spawn_blocking(\"aura\", aura);\n\n\t}\n\n\n\n\t// if the node isn't actively participating in consensus then it doesn't\n\n\t// need a keystore, regardless of which protocol we use below.\n\n\tlet keystore = if role.is_authority() {\n\n\t\tSome(keystore as sp_core::traits::BareCryptoStorePtr)\n\n\t} else {\n\n\t\tNone\n\n\t};\n\n\n", "file_path": "node/src/service.rs", "rank": 40, "score": 25576.04061136238 }, { "content": "use structopt::StructOpt;\n\nuse sc_cli::RunCmd;\n\n\n\n#[derive(Debug, StructOpt)]\n\npub struct Cli {\n\n\t#[structopt(subcommand)]\n\n\tpub subcommand: Option<Subcommand>,\n\n\n\n\t#[structopt(flatten)]\n\n\tpub run: RunCmd,\n\n}\n\n\n\n#[derive(Debug, StructOpt)]\n\npub enum Subcommand {\n\n\t/// Build a chain specification.\n\n\tBuildSpec(sc_cli::BuildSpecCmd),\n\n\n\n\t/// Validate blocks.\n\n\tCheckBlock(sc_cli::CheckBlockCmd),\n\n\n", "file_path": "node/src/cli.rs", "rank": 41, "score": 25572.294532432556 }, { "content": "\t\tBox::new(move |deny_unsafe, _| {\n\n\t\t\tlet deps = crate::rpc::FullDeps {\n\n\t\t\t\tclient: client.clone(),\n\n\t\t\t\tpool: pool.clone(),\n\n\t\t\t\tdeny_unsafe,\n\n\t\t\t};\n\n\n\n\t\t\tcrate::rpc::create_full(deps)\n\n\t\t})\n\n\t};\n\n\n\n\tsc_service::spawn_tasks(sc_service::SpawnTasksParams {\n\n\t\tnetwork: network.clone(),\n\n\t\tclient: client.clone(),\n\n\t\tkeystore: keystore.clone(),\n\n\t\ttask_manager: &mut task_manager,\n\n\t\ttransaction_pool: transaction_pool.clone(),\n\n\t\ttelemetry_connection_sinks: telemetry_connection_sinks.clone(),\n\n\t\trpc_extensions_builder: rpc_extensions_builder,\n\n\t\ton_demand: None,\n", "file_path": "node/src/service.rs", "rank": 42, "score": 25570.42305954889 }, { "content": "\t\tSome(Box::new(grandpa_block_import.clone())),\n\n\t\tNone,\n\n\t\tclient.clone(),\n\n\t\tinherent_data_providers.clone(),\n\n\t\t&task_manager.spawn_handle(),\n\n\t\tconfig.prometheus_registry(),\n\n\t\tsp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()),\n\n\t)?;\n\n\n\n\tOk(sc_service::PartialComponents {\n\n\t\tclient, backend, task_manager, import_queue, keystore, select_chain, transaction_pool,\n\n\t\tinherent_data_providers,\n\n\t\tother: (aura_block_import, grandpa_link),\n\n\t})\n\n}\n\n\n", "file_path": "node/src/service.rs", "rank": 43, "score": 25570.4179413011 }, { "content": "\t\tremote_blockchain: None,\n\n\t\tbackend, network_status_sinks, system_rpc_tx, config,\n\n\t})?;\n\n\n\n\tif role.is_authority() {\n\n\t\tlet proposer = sc_basic_authorship::ProposerFactory::new(\n\n\t\t\tclient.clone(),\n\n\t\t\ttransaction_pool,\n\n\t\t\tprometheus_registry.as_ref(),\n\n\t\t);\n\n\n\n\t\tlet can_author_with =\n\n\t\t\tsp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone());\n\n\n\n\t\tlet aura = sc_consensus_aura::start_aura::<_, _, _, _, _, AuraPair, _, _, _>(\n\n\t\t\tsc_consensus_aura::slot_duration(&*client)?,\n\n\t\t\tclient.clone(),\n\n\t\t\tselect_chain,\n\n\t\t\tblock_import,\n\n\t\t\tproposer,\n", "file_path": "node/src/service.rs", "rank": 44, "score": 25569.85884556275 }, { "content": "\t\t\tspawn_handle: task_manager.spawn_handle(),\n\n\t\t\timport_queue,\n\n\t\t\ton_demand: Some(on_demand.clone()),\n\n\t\t\tblock_announce_validator_builder: None,\n\n\t\t\tfinality_proof_request_builder: Some(finality_proof_request_builder),\n\n\t\t\tfinality_proof_provider: Some(finality_proof_provider),\n\n\t\t})?;\n\n\n\n\tif config.offchain_worker.enabled {\n\n\t\tsc_service::build_offchain_workers(\n\n\t\t\t&config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),\n\n\t\t);\n\n\t}\n\n\n\n\tsc_service::spawn_tasks(sc_service::SpawnTasksParams {\n\n\t\tremote_blockchain: Some(backend.remote_blockchain()),\n\n\t\ttransaction_pool,\n\n\t\ttask_manager: &mut task_manager,\n\n\t\ton_demand: Some(on_demand),\n\n\t\trpc_extensions_builder: Box::new(|_, _| ()),\n", "file_path": "node/src/service.rs", "rank": 45, "score": 25569.559672298208 }, { "content": "\tlet import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(\n\n\t\tsc_consensus_aura::slot_duration(&*client)?,\n\n\t\tgrandpa_block_import,\n\n\t\tNone,\n\n\t\tSome(Box::new(finality_proof_import)),\n\n\t\tclient.clone(),\n\n\t\tInherentDataProviders::new(),\n\n\t\t&task_manager.spawn_handle(),\n\n\t\tconfig.prometheus_registry(),\n\n\t\tsp_consensus::NeverCanAuthor,\n\n\t)?;\n\n\n\n\tlet finality_proof_provider =\n\n\t\tGrandpaFinalityProofProvider::new_for_service(backend.clone(), client.clone());\n\n\n\n\tlet (network, network_status_sinks, system_rpc_tx, network_starter) =\n\n\t\tsc_service::build_network(sc_service::BuildNetworkParams {\n\n\t\t\tconfig: &config,\n\n\t\t\tclient: client.clone(),\n\n\t\t\ttransaction_pool: transaction_pool.clone(),\n", "file_path": "node/src/service.rs", "rank": 46, "score": 25569.53287150177 }, { "content": "use sc_service::PartialComponents;\n\nuse node_template_runtime::Block;\n\n\n\nimpl SubstrateCli for Cli {\n\n\tfn impl_name() -> String {\n\n\t\t\"Substrate Node\".into()\n\n\t}\n\n\n\n\tfn impl_version() -> String {\n\n\t\tenv!(\"SUBSTRATE_CLI_IMPL_VERSION\").into()\n\n\t}\n\n\n\n\tfn description() -> String {\n\n\t\tenv!(\"CARGO_PKG_DESCRIPTION\").into()\n\n\t}\n\n\n\n\tfn author() -> String {\n\n\t\tenv!(\"CARGO_PKG_AUTHORS\").into()\n\n\t}\n\n\n", "file_path": "node/src/command.rs", "rank": 47, "score": 25568.93297683756 }, { "content": "\t\t\tfinality_proof_provider: Some(finality_proof_provider.clone()),\n\n\t\t})?;\n\n\n\n\tif config.offchain_worker.enabled {\n\n\t\tsc_service::build_offchain_workers(\n\n\t\t\t&config, backend.clone(), task_manager.spawn_handle(), client.clone(), network.clone(),\n\n\t\t);\n\n\t}\n\n\n\n\tlet role = config.role.clone();\n\n\tlet force_authoring = config.force_authoring;\n\n\tlet name = config.network.node_name.clone();\n\n\tlet enable_grandpa = !config.disable_grandpa;\n\n\tlet prometheus_registry = config.prometheus_registry().cloned();\n\n\tlet telemetry_connection_sinks = sc_service::TelemetryConnectionSinks::default();\n\n\n\n\tlet rpc_extensions_builder = {\n\n\t\tlet client = client.clone();\n\n\t\tlet pool = transaction_pool.clone();\n\n\n", "file_path": "node/src/service.rs", "rank": 48, "score": 25568.61732928278 }, { "content": "//! Substrate Node Template CLI library.\n\n#![warn(missing_docs)]\n\n\n\nmod chain_spec;\n\n#[macro_use]\n\nmod service;\n\nmod cli;\n\nmod command;\n\nmod rpc;\n\n\n", "file_path": "node/src/main.rs", "rank": 49, "score": 25568.319304615823 }, { "content": "\tfn support_url() -> String {\n\n\t\t\"support.anonymous.an\".into()\n\n\t}\n\n\n\n\tfn copyright_start_year() -> i32 {\n\n\t\t2017\n\n\t}\n\n\n\n\tfn load_spec(&self, id: &str) -> Result<Box<dyn sc_service::ChainSpec>, String> {\n\n\t\tOk(match id {\n\n\t\t\t\"dev\" => Box::new(chain_spec::development_config()?),\n\n\t\t\t\"\" | \"local\" => Box::new(chain_spec::local_testnet_config()?),\n\n\t\t\tpath => Box::new(chain_spec::ChainSpec::from_json_file(\n\n\t\t\t\tstd::path::PathBuf::from(path),\n\n\t\t\t)?),\n\n\t\t})\n\n\t}\n\n\n\n\tfn native_runtime_version(_: &Box<dyn ChainSpec>) -> &'static RuntimeVersion {\n\n\t\t&node_template_runtime::VERSION\n\n\t}\n\n}\n\n\n\n/// Parse and run command line arguments\n", "file_path": "node/src/command.rs", "rank": 50, "score": 25568.22816809452 }, { "content": "\t\t\t}\n\n\t\t},\n\n\t\tNone => {\n\n\t\t\tlet runner = cli.create_runner(&cli.run)?;\n\n\t\t\trunner.run_node_until_exit(|config| match config.role {\n\n\t\t\t\tRole::Light => service::new_light(config),\n\n\t\t\t\t_ => service::new_full(config),\n\n\t\t\t})\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "node/src/command.rs", "rank": 51, "score": 25568.216744830876 }, { "content": "\t\ttelemetry_connection_sinks: sc_service::TelemetryConnectionSinks::default(),\n\n\t\tconfig,\n\n\t\tclient,\n\n\t\tkeystore,\n\n\t\tbackend,\n\n\t\tnetwork,\n\n\t\tnetwork_status_sinks,\n\n\t\tsystem_rpc_tx,\n\n\t })?;\n\n\n\n\t network_starter.start_network();\n\n\n\n\t Ok(task_manager)\n\n}\n", "file_path": "node/src/service.rs", "rank": 52, "score": 25568.02892635987 }, { "content": "// This file is part of Substrate.\n\n\n\n// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.\n\n// SPDX-License-Identifier: Apache-2.0\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// \thttp://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::{chain_spec, service};\n\nuse crate::cli::{Cli, Subcommand};\n\nuse sc_cli::{SubstrateCli, RuntimeVersion, Role, ChainSpec};\n", "file_path": "node/src/command.rs", "rank": 53, "score": 25567.770141085508 }, { "content": "\tlet select_chain = sc_consensus::LongestChain::new(backend.clone());\n\n\n\n\tlet transaction_pool = sc_transaction_pool::BasicPool::new_full(\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);\n\n\n\n\tlet (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import(\n\n\t\tclient.clone(), &(client.clone() as Arc<_>), select_chain.clone(),\n\n\t)?;\n\n\n\n\tlet aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(\n\n\t\tgrandpa_block_import.clone(), client.clone(),\n\n\t);\n\n\n\n\tlet import_queue = sc_consensus_aura::import_queue::<_, _, _, AuraPair, _, _>(\n\n\t\tsc_consensus_aura::slot_duration(&*client)?,\n\n\t\taura_block_import.clone(),\n", "file_path": "node/src/service.rs", "rank": 54, "score": 25566.827260058682 }, { "content": "pub mod chain_spec;\n\npub mod service;\n\npub mod rpc;\n", "file_path": "node/src/lib.rs", "rank": 55, "score": 25566.800288452334 }, { "content": "\t\tSome(Subcommand::PurgeChain(cmd)) => {\n\n\t\t\tlet runner = cli.create_runner(cmd)?;\n\n\t\t\trunner.sync_run(|config| cmd.run(config.database))\n\n\t\t},\n\n\t\tSome(Subcommand::Revert(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, backend, ..}\n\n\t\t\t\t\t= service::new_partial(&config)?;\n\n\t\t\t\tOk((cmd.run(client, backend), task_manager))\n\n\t\t\t})\n\n\t\t},\n\n\t\tSome(Subcommand::Benchmark(cmd)) => {\n\n\t\t\tif cfg!(feature = \"runtime-benchmarks\") {\n\n\t\t\t\tlet runner = cli.create_runner(cmd)?;\n\n\n\n\t\t\t\trunner.sync_run(|config| cmd.run::<Block, service::Executor>(config))\n\n\t\t\t} else {\n\n\t\t\t\tErr(\"Benchmarking wasn't enabled when building the node. \\\n\n\t\t\t\tYou can enable it with `--features runtime-benchmarks`.\".into())\n", "file_path": "node/src/command.rs", "rank": 56, "score": 25566.333720683266 }, { "content": "\t\t\t\t\t= service::new_partial(&config)?;\n\n\t\t\t\tOk((cmd.run(client, config.database), task_manager))\n\n\t\t\t})\n\n\t\t},\n\n\t\tSome(Subcommand::ExportState(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, ..}\n\n\t\t\t\t\t= service::new_partial(&config)?;\n\n\t\t\t\tOk((cmd.run(client, config.chain_spec), task_manager))\n\n\t\t\t})\n\n\t\t},\n\n\t\tSome(Subcommand::ImportBlocks(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", "file_path": "node/src/command.rs", "rank": 57, "score": 25565.96628493947 }, { "content": "\tlet grandpa_config = sc_finality_grandpa::Config {\n\n\t\t// FIXME #1578 make this available through chainspec\n\n\t\tgossip_duration: Duration::from_millis(333),\n\n\t\tjustification_period: 512,\n\n\t\tname: Some(name),\n\n\t\tobserver_enabled: false,\n\n\t\tkeystore,\n\n\t\tis_authority: role.is_network_authority(),\n\n\t};\n\n\n\n\tif enable_grandpa {\n\n\t\t// start the full GRANDPA voter\n\n\t\t// NOTE: non-authorities could run the GRANDPA observer protocol, but at\n\n\t\t// this point the full voter should provide better guarantees of block\n\n\t\t// and vote data availability than the observer. The observer has not\n\n\t\t// been tested extensively yet and having most nodes in a network run it\n\n\t\t// could lead to finality stalls.\n\n\t\tlet grandpa_config = sc_finality_grandpa::GrandpaParams {\n\n\t\t\tconfig: grandpa_config,\n\n\t\t\tlink: grandpa_link,\n", "file_path": "node/src/service.rs", "rank": 58, "score": 25564.795851277762 }, { "content": "\t\t\tnetwork,\n\n\t\t\tinherent_data_providers,\n\n\t\t\ttelemetry_on_connect: Some(telemetry_connection_sinks.on_connect_stream()),\n\n\t\t\tvoting_rule: sc_finality_grandpa::VotingRulesBuilder::default().build(),\n\n\t\t\tprometheus_registry,\n\n\t\t\tshared_voter_state: SharedVoterState::empty(),\n\n\t\t};\n\n\n\n\t\t// the GRANDPA voter task is considered infallible, i.e.\n\n\t\t// if it fails we take down the service with it.\n\n\t\ttask_manager.spawn_essential_handle().spawn_blocking(\n\n\t\t\t\"grandpa-voter\",\n\n\t\t\tsc_finality_grandpa::run_grandpa_voter(grandpa_config)?\n\n\t\t);\n\n\t} else {\n\n\t\tsc_finality_grandpa::setup_disabled_grandpa(\n\n\t\t\tclient,\n\n\t\t\t&inherent_data_providers,\n\n\t\t\tnetwork,\n\n\t\t)?;\n\n\t}\n\n\n\n\tnetwork_starter.start_network();\n\n\tOk(task_manager)\n\n}\n\n\n", "file_path": "node/src/service.rs", "rank": 59, "score": 25564.772156250277 }, { "content": "\t/// Export blocks.\n\n\tExportBlocks(sc_cli::ExportBlocksCmd),\n\n\n\n\t/// Export the state of a given block into a chain spec.\n\n\tExportState(sc_cli::ExportStateCmd),\n\n\n\n\t/// Import blocks.\n\n\tImportBlocks(sc_cli::ImportBlocksCmd),\n\n\n\n\t/// Remove the whole chain.\n\n\tPurgeChain(sc_cli::PurgeChainCmd),\n\n\n\n\t/// Revert the chain to a previous state.\n\n\tRevert(sc_cli::RevertCmd),\n\n\n\n\t/// The custom benchmark subcommmand benchmarking runtime pallets.\n\n\t#[structopt(name = \"benchmark\", about = \"Benchmark runtime pallets.\")]\n\n\tBenchmark(frame_benchmarking_cli::BenchmarkCmd),\n\n}\n", "file_path": "node/src/cli.rs", "rank": 60, "score": 25563.097707641413 }, { "content": "pub use super::*;\n\n\n\npub use std::cell::RefCell;\n\nuse sp_core::H256;\n\npub use frame_support::{\n\n impl_outer_origin, impl_outer_event, parameter_types, weights::Weight,\n\n\tassert_ok, assert_noop,\n\n\ttraits::{Currency, Get,},\n\n};\n\nuse sp_runtime::{\n\n\ttraits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill,\n\n};\n\n\n\nuse pallet_balances as balances;\n\n\n\nuse frame_system as system;\n\n\n\nimpl_outer_origin! {\n\n\tpub enum Origin for Test {}\n\n}\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 66, "score": 25313.808336262915 }, { "content": "\ttype WeightInfo = ();\n\n}\n\n\n\nthread_local! {\n\n\tstatic RANDOM_PAYLOAD: RefCell<H256> = RefCell::new(Default::default());\n\n\tstatic EXISTENTIAL_DEPOSIT: RefCell<Balance> = RefCell::new(0);\n\n}\n\n\n\npub struct MockRandom;\n\n\n\nimpl Randomness<H256> for MockRandom {\n\n fn random(_subject: &[u8]) -> H256 {\n\n RANDOM_PAYLOAD.with(|v| *v.borrow())\n\n }\n\n}\n\n\n\nimpl Trait for Test {\n\n\ttype Event = Event;\n\n\ttype Randomness = MockRandom;\n\n\ttype KittyIndex = u32;\n\n\ttype Currency = Balances;\n\n\ttype KittyReserveFunds = u8;\n\n}\n\n\n\n\n\n// Build genesis storage according to the mock runtime.\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 69, "score": 25308.351718831207 }, { "content": "\t\tbalances<T>,\n\n\t}\n\n}\n\n// Configure a mock runtime to test the pallet.\n\n\n\npub type KModule = Module<Test>;\n\npub type System = frame_system::Module<Test>;\n\npub type Balances = pallet_balances::Module<Test>;\n\n\n\n#[derive(Clone, Eq, PartialEq)]\n\npub struct Test;\n\nparameter_types! {\n\n\tpub const BlockHashCount: u64 = 250;\n\n\tpub const MaximumBlockWeight: Weight = 1024;\n\n\tpub const MaximumBlockLength: u32 = 2 * 1024;\n\n\t// pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);\n\n\tpub const AvailableBlockRatio: Perbill = Perbill::one();\n\n\n\n\t// pub const ExistentialDeposit: u64 = 1;\n\n\tpub const TransferFee: u64 = 0;\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 72, "score": 25305.115551515628 }, { "content": "\tpub const CreationFee: u64 = 0;\n\n\n\n\tpub const KittyReserveFundsConst: u64 = 10_000_000_000_000;\n\n}\n\n\n\nimpl system::Trait for Test {\n\n\ttype BaseCallFilter = ();\n\n\ttype Origin = Origin;\n\n\ttype Call = ();\n\n\ttype Index = u64;\n\n\ttype BlockNumber = u64;\n\n\ttype Hash = H256;\n\n\ttype Hashing = BlakeTwo256;\n\n\ttype AccountId = u64;\n\n\ttype Lookup = IdentityLookup<Self::AccountId>;\n\n\ttype Header = Header;\n\n\ttype Event = Event;\n\n\ttype BlockHashCount = BlockHashCount;\n\n\ttype MaximumBlockWeight = MaximumBlockWeight;\n\n\ttype DbWeight = ();\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 75, "score": 25301.39737165685 }, { "content": "\n\npub(crate) type Balance = u128;\n\n\n\n\n\npub mod kitties {\n\n\t// Re-export needed for `impl_outer_event!`.\n\n\tpub use super::super::*;\n\n}\n\n\n\npub struct ExistentialDeposit;\n\nimpl Get<Balance> for ExistentialDeposit {\n\n\tfn get() -> Balance {\n\n\t\tEXISTENTIAL_DEPOSIT.with(|v| *v.borrow())\n\n\t}\n\n}\n\n\n\nimpl_outer_event! {\n\n\tpub enum Event for Test {\n\n\t\tframe_system<T>,\n\n\t\tkitties<T>,\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 77, "score": 25299.530308877354 }, { "content": "\ttype BlockExecutionWeight = ();\n\n\ttype ExtrinsicBaseWeight = ();\n\n\ttype MaximumExtrinsicWeight = MaximumBlockWeight;\n\n\ttype MaximumBlockLength = MaximumBlockLength;\n\n\ttype AvailableBlockRatio = AvailableBlockRatio;\n\n\ttype Version = ();\n\n\ttype PalletInfo = ();\n\n\ttype AccountData = pallet_balances::AccountData<Balance>;\n\n\ttype OnNewAccount = ();\n\n\ttype OnKilledAccount = ();\n\n\ttype SystemWeightInfo = ();\n\n}\n\n\n\nimpl pallet_balances::Trait for Test {\n\n\ttype MaxLocks = ();\n\n\ttype Balance = Balance;\n\n\ttype Event = Event;\n\n\ttype DustRemoval = ();\n\n\ttype ExistentialDeposit = ExistentialDeposit;\n\n\ttype AccountStore = System;\n", "file_path": "pallets/kitties/src/mock.rs", "rank": 78, "score": 25297.92311435022 }, { "content": "use crate::{Error, mock::*};\n\nuse frame_support::{assert_ok, assert_noop};\n\n\n\n\n\n#[test]\n", "file_path": "pallets/kitties/src/tests.rs", "rank": 79, "score": 25291.50232585631 }, { "content": "use sp_core::{Pair, Public, sr25519};\n\nuse node_template_runtime::{\n\n\tAccountId, AuraConfig, BalancesConfig, GenesisConfig, GrandpaConfig,\n\n\tSudoConfig, SystemConfig, WASM_BINARY, Signature\n\n};\n\nuse sp_consensus_aura::sr25519::AuthorityId as AuraId;\n\nuse sp_finality_grandpa::AuthorityId as GrandpaId;\n\nuse sp_runtime::traits::{Verify, IdentifyAccount};\n\nuse sc_service::ChainType;\n\n\n\n// The URL for the telemetry server.\n\n// const STAGING_TELEMETRY_URL: &str = \"wss://telemetry.polkadot.io/submit/\";\n\n\n\n/// Specialized `ChainSpec`. This is a specialization of the general Substrate ChainSpec type.\n\npub type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;\n\n\n\n/// Generate a crypto pair from seed.\n", "file_path": "node/src/chain_spec.rs", "rank": 80, "score": 24396.77322516823 }, { "content": "\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Bob\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Bob//stash\"),\n\n\t\t\t],\n\n\t\t\ttrue,\n\n\t\t),\n\n\t\t// Bootnodes\n\n\t\tvec![],\n\n\t\t// Telemetry\n\n\t\tNone,\n\n\t\t// Protocol ID\n\n\t\tNone,\n\n\t\t// Properties\n\n\t\tNone,\n\n\t\t// Extensions\n\n\t\tNone,\n\n\t))\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 81, "score": 24388.253927358943 }, { "content": "\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Bob\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Charlie\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Dave\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Eve\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Ferdie\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Alice//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Bob//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Charlie//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Dave//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Eve//stash\"),\n\n\t\t\t\tget_account_id_from_seed::<sr25519::Public>(\"Ferdie//stash\"),\n\n\t\t\t],\n\n\t\t\ttrue,\n\n\t\t),\n\n\t\t// Bootnodes\n\n\t\tvec![],\n\n\t\t// Telemetry\n\n\t\tNone,\n\n\t\t// Protocol ID\n\n\t\tNone,\n\n\t\t// Properties\n\n\t\tNone,\n\n\t\t// Extensions\n\n\t\tNone,\n\n\t))\n\n}\n\n\n", "file_path": "node/src/chain_spec.rs", "rank": 82, "score": 24387.510685566784 }, { "content": "## runtime 里面定义一个 pallet 可以使用的常量\n\n\n\n- 先在runtime lib里面 用`parameter_types`宏定义,然后添加到 pallet对应的Trait for Runtime 里面。 \n\n\n\nexp:`pallet_kitties` 的 `kitty_reserve_funds` 常量\n\n\n\n`runtime -> src -> lib.rs`\n\n```rust\n\nparameter_types! {\n\n\tpub const KittyReserveFundsConst: u64 = 1_000_000_000_u64;\n\n}\n\n\n\npallet_kitties::Trait for Runtime {\n\n // ...\n\n type KittyReserveFunds = KittyReserveFundsConst;\n\n}\n\n```\n\n\n\n`pallet_kitties -> src -> lib.rs`\n\n\n\n```rust\n\nuse frame_support::{ traits::{Get} };\n\n\n\npub trait Trait {\n\n // 名字 必须跟 runtime 的 trait 的 type 相同!相同!相同!且首字母大写!首字母大写!首字母大写!\n\n pub KittyReserveFunds: Get<u64>;\n\n}\n\n\n\ndecl_module! {\n\n\tpub struct Module<T: Trait> for enum Call where origin: T::Origin {\n\n // ...\n\n #[weight = 0]\n\n\t\tpub fn use_runtime_const(origin) {\n\n let sender = ensure_signed(origin)?;\n\n \n\n // 使用 KittyReserveFunds \n\n let kitty_reserve_funds = T::KittyReserveFunds::get();\n\n // ...\n\n\t\t}\n\n }\n\n}\n", "file_path": "作业笔记.md", "rank": 83, "score": 31.94413589816805 }, { "content": "## 视频中的一个bug\n\n- transfer 没有做边界和kitties拥有者的判断,然后直接就执行了transfer了\n\n\n\n我的修改是添加了这个kittyid和拥有者的判断\n\n```rust\n\n// 修改前\n\npub fn transfer(origin, to: T::AccountId, kitty_id: T::KittyIndex) -> DispatchResult {\n\n let sender = ensure_signed(origin.clone())?;\n\n <KittyOwner<T>>::insert(kitty_id, to.clone());\n\n // ...\n\n}\n\n// 修改后代码\n\n\n\npub fn transfer(origin, to: T::AccountId, kitty_id: T::KittyIndex) -> DispatchResult {\n\n let sender = ensure_signed(origin.clone())?;\n\n let kitty = Kitties::<T>::take(&sender, kitty_id).ok_or(Error::<T>::InvalidaKittyId)?;\n\n // ...\n\n}\n\n```\n\n\n\n### pallet_kitties -> lib 的 Trait 与 runtime -> lib的 impl pallet_kitties::Trait for Tuntime 的关系\n\n\n\n- pallet_kitties -> lib 里面的Trait 主要是定义trait type的类型,或者说某个type条件需要实现那些Trait 每一个`+`表示需要多一个Trait实现。\n\n- runtime 里面每`impl`一个`pallet`的`Trait`其实都是对`Trait` 每个 `Type`的实现,并且必须把 pallet_kitties -> lib -> Trait 里面每个 Type 所有的条件 Trait 都实现,不然就会报错\n\n\n\n- `pallet_kitties`和`runtime`两边的`Trait`里面的`Type`的名字 必须一样!必须一样!必须一样!不然它会报错, 而且 少一个都不行!少一个都不行!少一个都不行!\n\n\n\n- 每个`type`的名字用大驼峰命名(首字母大写)\n\n\n\n\n", "file_path": "作业笔记.md", "rank": 84, "score": 29.804341489866186 }, { "content": "use crate::{Module, Trait};\n\nuse sp_core::H256;\n\nuse frame_support::{impl_outer_origin, parameter_types, weights::Weight};\n\nuse sp_runtime::{\n\n\ttraits::{BlakeTwo256, IdentityLookup}, testing::Header, Perbill,\n\n};\n\nuse frame_system as system;\n\n\n\nimpl_outer_origin! {\n\n\tpub enum Origin for Test {}\n\n}\n\n\n\n// Configure a mock runtime to test the pallet.\n\n\n\n#[derive(Clone, Eq, PartialEq)]\n\npub struct Test;\n\nparameter_types! {\n\n\tpub const BlockHashCount: u64 = 250;\n\n\tpub const MaximumBlockWeight: Weight = 1024;\n\n\tpub const MaximumBlockLength: u32 = 2 * 1024;\n", "file_path": "pallets/template/src/mock.rs", "rank": 85, "score": 27.164927315358817 }, { "content": "use pallet_grandpa::fg_primitives;\n\nuse sp_version::RuntimeVersion;\n\n#[cfg(feature = \"std\")]\n\nuse sp_version::NativeVersion;\n\n\n\n// A few exports that help ease life for downstream crates.\n\n#[cfg(any(feature = \"std\", test))]\n\npub use sp_runtime::BuildStorage;\n\npub use pallet_timestamp::Call as TimestampCall;\n\npub use pallet_balances::Call as BalancesCall;\n\npub use sp_runtime::{Permill, Perbill};\n\npub use frame_support::{\n\n\tconstruct_runtime, parameter_types, StorageValue,\n\n\ttraits::{KeyOwnerProofSystem, Randomness},\n\n\tweights::{\n\n\t\tWeight, IdentityFee,\n\n\t\tconstants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},\n\n\t},\n\n};\n\n\n", "file_path": "runtime/src/lib.rs", "rank": 86, "score": 25.472880147057 }, { "content": "\t\t/// Error names should be descriptive.\n\n\t\tNoneValue,\n\n\t\t/// Errors should have helpful documentation associated with them.\n\n\t\tStorageOverflow,\n\n\t}\n\n}\n\n\n\n// Dispatchable functions allows users to interact with the pallet and invoke state changes.\n\n// These functions materialize as \"extrinsics\", which are often compared to transactions.\n\n// Dispatchable functions must be annotated with a weight and must return a DispatchResult.\n\ndecl_module! {\n\n\tpub struct Module<T: Trait> for enum Call where origin: T::Origin {\n\n\t\t// Errors must be initialized if they are used by the pallet.\n\n\t\ttype Error = Error<T>;\n\n\n\n\t\t// Events must be initialized if they are used by the pallet.\n\n\t\tfn deposit_event() = default;\n\n\n\n\t\t/// An example dispatchable that takes a singles value as a parameter, writes the value to\n\n\t\t/// storage and emits an event. This function must be dispatched by a signed extrinsic.\n", "file_path": "pallets/template/src/lib.rs", "rank": 87, "score": 24.18134132001415 }, { "content": "\t\t#[weight = 10_000 + T::DbWeight::get().writes(1)]\n\n\t\tpub fn do_something(origin, something: u32) -> dispatch::DispatchResult {\n\n\t\t\t// Check that the extrinsic was signed and get the signer.\n\n\t\t\t// This function will return an error if the extrinsic is not signed.\n\n\t\t\t// https://substrate.dev/docs/en/knowledgebase/runtime/origin\n\n\t\t\tlet who = ensure_signed(origin)?;\n\n\n\n\t\t\t// Update storage.\n\n\t\t\tSomething::put(something);\n\n\n\n\t\t\t// Emit an event.\n\n\t\t\tSelf::deposit_event(RawEvent::SomethingStored(something, who));\n\n\t\t\t// Return a successful DispatchResult\n\n\t\t\tOk(())\n\n\t\t}\n\n\n\n\t\t/// An example dispatchable that may throw a custom error.\n\n\t\t#[weight = 10_000 + T::DbWeight::get().reads_writes(1,1)]\n\n\t\tpub fn cause_error(origin) -> dispatch::DispatchResult {\n\n\t\t\tlet _who = ensure_signed(origin)?;\n", "file_path": "pallets/template/src/lib.rs", "rank": 88, "score": 23.75406397725093 }, { "content": "\ttype WeightToFee = IdentityFee<Balance>;\n\n\ttype FeeMultiplierUpdate = ();\n\n}\n\n\n\nimpl pallet_sudo::Trait for Runtime {\n\n\ttype Event = Event;\n\n\ttype Call = Call;\n\n}\n\n\n\n/// Configure the template pallet in pallets/template.\n\nimpl pallet_template::Trait for Runtime {\n\n\ttype Event = Event;\n\n}\n\n\n\nparameter_types! {\n\n\tpub const KittyReserveFunds: u64 = 5_000_000_000_000_000;\n\n}\n\n\n\nimpl pallet_kitties::Trait for Runtime {\n\n\ttype Event = Event;\n", "file_path": "runtime/src/lib.rs", "rank": 89, "score": 23.404194866615942 }, { "content": "impl pallet_balances::Trait for Runtime {\n\n\ttype MaxLocks = MaxLocks;\n\n\t/// The type for recording an account's balance.\n\n\ttype Balance = Balance;\n\n\t/// The ubiquitous event type.\n\n\ttype Event = Event;\n\n\ttype DustRemoval = ();\n\n\ttype ExistentialDeposit = ExistentialDeposit;\n\n\ttype AccountStore = System;\n\n\ttype WeightInfo = ();\n\n}\n\n\n\nparameter_types! {\n\n\tpub const TransactionByteFee: Balance = 1;\n\n}\n\n\n\nimpl pallet_transaction_payment::Trait for Runtime {\n\n\ttype Currency = Balances;\n\n\ttype OnTransactionPayment = ();\n\n\ttype TransactionByteFee = TransactionByteFee;\n", "file_path": "runtime/src/lib.rs", "rank": 90, "score": 23.383878418366873 }, { "content": "\ttype Randomness = RandomnessCollectiveFlip;\n\n\ttype KittyIndex = u32;\n\n\ttype Currency = Balances;\n\n\ttype KittyReserveFunds = KittyReserveFunds;\n\n}\n\n\n\n\n\n// Create the runtime by composing the FRAME pallets that were previously configured.\n\nconstruct_runtime!(\n\n\tpub enum Runtime where\n\n\t\tBlock = Block,\n\n\t\tNodeBlock = opaque::Block,\n\n\t\tUncheckedExtrinsic = UncheckedExtrinsic\n\n\t{\n\n\t\tSystem: frame_system::{Module, Call, Config, Storage, Event<T>},\n\n\t\tRandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},\n\n\t\tTimestamp: pallet_timestamp::{Module, Call, Storage, Inherent},\n\n\t\tAura: pallet_aura::{Module, Config<T>, Inherent},\n\n\t\tGrandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},\n\n\t\tBalances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},\n", "file_path": "runtime/src/lib.rs", "rank": 91, "score": 21.400193810696077 }, { "content": "#![cfg_attr(not(feature = \"std\"), no_std)]\n\n\n\n/// Edit this file to define custom logic or remove it if it is not needed.\n\n/// Learn more about FRAME and the core library of Substrate FRAME pallets:\n\n/// https://substrate.dev/docs/en/knowledgebase/runtime/frame\n\n\n\nuse frame_support::{decl_module, decl_storage, decl_event, decl_error, dispatch, traits::Get};\n\nuse frame_system::ensure_signed;\n\n\n\n#[cfg(test)]\n\nmod mock;\n\n\n\n#[cfg(test)]\n\nmod tests;\n\n\n\n/// Configure the pallet by specifying the parameters and types on which it depends.\n", "file_path": "pallets/template/src/lib.rs", "rank": 92, "score": 18.32309759749767 }, { "content": "use crate::{Error, mock::*};\n\nuse frame_support::{assert_ok, assert_noop};\n\n\n\nmod kitties {\n\n\t// Re-export needed for `impl_outer_event!`.\n\n\tpub use super::super::*;\n\n}\n\n\n\n#[test]\n", "file_path": "pallets/template/src/tests.rs", "rank": 93, "score": 16.3609075049074 }, { "content": "\tpub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);\n\n}\n\n\n\nimpl system::Trait for Test {\n\n\ttype BaseCallFilter = ();\n\n\ttype Origin = Origin;\n\n\ttype Call = ();\n\n\ttype Index = u64;\n\n\ttype BlockNumber = u64;\n\n\ttype Hash = H256;\n\n\ttype Hashing = BlakeTwo256;\n\n\ttype AccountId = u64;\n\n\ttype Lookup = IdentityLookup<Self::AccountId>;\n\n\ttype Header = Header;\n\n\ttype Event = ();\n\n\ttype BlockHashCount = BlockHashCount;\n\n\ttype MaximumBlockWeight = MaximumBlockWeight;\n\n\ttype DbWeight = ();\n\n\ttype BlockExecutionWeight = ();\n\n\ttype ExtrinsicBaseWeight = ();\n", "file_path": "pallets/template/src/mock.rs", "rank": 94, "score": 16.1095132835674 }, { "content": "### Pallets\n\n\n\nThe runtime in this project is constructed using many FRAME pallets that ship with the\n\n[core Substrate repository](https://github.com/paritytech/substrate/tree/master/frame) and a\n\ntemplate pallet that is [defined in the `pallets`](./pallets/template/src/lib.rs) directory.\n\n\n\nA FRAME pallet is compromised of a number of blockchain primitives:\n\n\n\n- Storage: FRAME defines a rich set of powerful\n\n [storage abstractions](https://substrate.dev/docs/en/knowledgebase/runtime/storage) that makes\n\n it easy to use Substrate's efficient key-value database to manage the evolving state of a\n\n blockchain.\n\n- Dispatchables: FRAME pallets define special types of functions that can be invoked (dispatched)\n\n from outside of the runtime in order to update its state.\n\n- Events: Substrate uses [events](https://substrate.dev/docs/en/knowledgebase/runtime/events) to\n\n notify users of important changes in the runtime.\n\n- Errors: When a dispatchable fails, it returns an error.\n\n- Trait: The `Trait` configuration interface is used to define the types and parameters upon which\n\n a FRAME pallet depends.\n\n\n\n### Run in Docker\n\n\n\nFirst, install [Docker](https://docs.docker.com/get-docker/) and\n\n[Docker Compose](https://docs.docker.com/compose/install/).\n\n\n\nThen run the following command to start a single node development chain.\n\n\n\n```bash\n\n./scripts/docker_run.sh\n\n```\n\n\n\nThis command will firstly compile your code, and then start a local development network. You can\n\nalso replace the default command (`cargo build --release && ./target/release/node-template --dev --ws-external`)\n\nby appending your own. A few useful ones are as follow.\n\n\n\n```bash\n\n# Run Substrate node without re-compiling\n\n./scripts/docker_run.sh ./target/release/node-template --dev --ws-external\n\n\n\n# Purge the local dev chain\n\n./scripts/docker_run.sh ./target/release/node-template purge-chain --dev\n\n\n\n# Check whether the code is compilable\n\n./scripts/docker_run.sh cargo check\n\n```\n", "file_path": "README.md", "rank": 95, "score": 15.236151333133582 }, { "content": "\ttype WeightInfo = ();\n\n}\n\n\n\nparameter_types! {\n\n\tpub const MinimumPeriod: u64 = SLOT_DURATION / 2;\n\n}\n\n\n\nimpl pallet_timestamp::Trait for Runtime {\n\n\t/// A timestamp: milliseconds since the unix epoch.\n\n\ttype Moment = u64;\n\n\ttype OnTimestampSet = Aura;\n\n\ttype MinimumPeriod = MinimumPeriod;\n\n\ttype WeightInfo = ();\n\n}\n\n\n\nparameter_types! {\n\n\tpub const ExistentialDeposit: u128 = 500;\n\n\tpub const MaxLocks: u32 = 50;\n\n}\n\n\n", "file_path": "runtime/src/lib.rs", "rank": 96, "score": 14.15086061828903 }, { "content": "\n\nimpl frame_system::Trait for Runtime {\n\n\t/// The basic call filter to use in dispatchable.\n\n\ttype BaseCallFilter = ();\n\n\t/// The identifier used to distinguish between accounts.\n\n\ttype AccountId = AccountId;\n\n\t/// The aggregated dispatch type that is available for extrinsics.\n\n\ttype Call = Call;\n\n\t/// The lookup mechanism to get account ID from whatever is passed in dispatchers.\n\n\ttype Lookup = IdentityLookup<AccountId>;\n\n\t/// The index type for storing how many extrinsics an account has signed.\n\n\ttype Index = Index;\n\n\t/// The index type for blocks.\n\n\ttype BlockNumber = BlockNumber;\n\n\t/// The type for hashing blocks and tries.\n\n\ttype Hash = Hash;\n\n\t/// The hashing algorithm used.\n\n\ttype Hashing = BlakeTwo256;\n\n\t/// The header type.\n\n\ttype Header = generic::Header<BlockNumber, BlakeTwo256>;\n", "file_path": "runtime/src/lib.rs", "rank": 97, "score": 13.948969785803206 }, { "content": "impl pallet_aura::Trait for Runtime {\n\n\ttype AuthorityId = AuraId;\n\n}\n\n\n\nimpl pallet_grandpa::Trait for Runtime {\n\n\ttype Event = Event;\n\n\ttype Call = Call;\n\n\n\n\ttype KeyOwnerProofSystem = ();\n\n\n\n\ttype KeyOwnerProof =\n\n\t\t<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;\n\n\n\n\ttype KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(\n\n\t\tKeyTypeId,\n\n\t\tGrandpaId,\n\n\t)>>::IdentificationTuple;\n\n\n\n\ttype HandleEquivocation = ();\n\n\n", "file_path": "runtime/src/lib.rs", "rank": 98, "score": 13.82280226265671 }, { "content": "\t\t\t\t// Execution Phase\n\n\t\t\t\thex_literal::hex!(\"26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a\").to_vec().into(),\n\n\t\t\t\t// Event Count\n\n\t\t\t\thex_literal::hex!(\"26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850\").to_vec().into(),\n\n\t\t\t\t// System Events\n\n\t\t\t\thex_literal::hex!(\"26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7\").to_vec().into(),\n\n\t\t\t];\n\n\n\n\t\t\tlet mut batches = Vec::<BenchmarkBatch>::new();\n\n\t\t\tlet params = (&config, &whitelist);\n\n\n\n\t\t\tadd_benchmark!(params, batches, frame_system, SystemBench::<Runtime>);\n\n\t\t\tadd_benchmark!(params, batches, pallet_balances, Balances);\n\n\t\t\tadd_benchmark!(params, batches, pallet_timestamp, Timestamp);\n\n\n\n\t\t\tif batches.is_empty() { return Err(\"Benchmark not found for this pallet.\".into()) }\n\n\t\t\tOk(batches)\n\n\t\t}\n\n\t}\n\n}\n", "file_path": "runtime/src/lib.rs", "rank": 99, "score": 11.895741457267542 } ]
Rust
core/src/storage/collections/stash/impls.rs
jsulmont/ink
d1474ae4b7cb3b4119ec39d702358d4e51b0b5bf
#[cfg(feature = "ink-generate-abi")] use ink_abi::{ HasLayout, LayoutField, LayoutStruct, StorageLayout, }; use scale::{ Decode, Encode, }; #[cfg(feature = "ink-generate-abi")] use type_metadata::Metadata; use crate::storage::{ self, alloc::{ Allocate, AllocateUsing, Initialize, }, chunk::SyncChunk, Flush, Key, }; #[derive(Debug)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] pub struct Stash<T> { header: storage::Value<StashHeader>, entries: SyncChunk<Entry<T>>, } #[derive(Debug, Encode, Decode)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] struct StashHeader { next_vacant: u32, len: u32, max_len: u32, } impl Flush for StashHeader { #[inline] fn flush(&mut self) { self.next_vacant.flush(); self.len.flush(); self.max_len.flush(); } } #[derive(Debug)] pub struct Values<'a, T> { iter: Iter<'a, T>, } impl<'a, T> Values<'a, T> { pub(crate) fn new(stash: &'a Stash<T>) -> Self { Self { iter: stash.iter() } } } impl<T> Flush for Stash<T> where T: Encode + Flush, { #[inline] fn flush(&mut self) { self.header.flush(); self.entries.flush(); } } #[cfg(feature = "ink-generate-abi")] impl<T> HasLayout for Stash<T> where T: Metadata + 'static, { fn layout(&self) -> StorageLayout { LayoutStruct::new( Self::meta_type(), vec![ LayoutField::of("header", &self.header), LayoutField::of("entries", &self.entries), ], ) .into() } } impl<'a, T> Iterator for Values<'a, T> where T: scale::Codec, { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|(_index, value)| value) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, T> ExactSizeIterator for Values<'a, T> where T: scale::Codec {} impl<'a, T> DoubleEndedIterator for Values<'a, T> where T: scale::Codec, { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back().map(|(_index, value)| value) } } #[derive(Debug)] pub struct Iter<'a, T> { stash: &'a Stash<T>, begin: u32, end: u32, yielded: u32, } impl<'a, T> Iter<'a, T> { pub(crate) fn new(stash: &'a Stash<T>) -> Self { Self { stash, begin: 0, end: stash.max_len(), yielded: 0, } } } impl<'a, T> Iterator for Iter<'a, T> where T: scale::Codec, { type Item = (u32, &'a T); fn next(&mut self) -> Option<Self::Item> { debug_assert!(self.begin <= self.end); if self.yielded == self.stash.len() { return None } while self.begin < self.end { let cur = self.begin; self.begin += 1; if let Some(elem) = self.stash.get(cur) { self.yielded += 1; return Some((cur, elem)) } } None } fn size_hint(&self) -> (usize, Option<usize>) { let remaining = (self.stash.len() - self.yielded) as usize; (remaining, Some(remaining)) } } impl<'a, T> ExactSizeIterator for Iter<'a, T> where T: scale::Codec {} impl<'a, T> DoubleEndedIterator for Iter<'a, T> where T: scale::Codec, { fn next_back(&mut self) -> Option<Self::Item> { debug_assert!(self.begin <= self.end); if self.yielded == self.stash.len() { return None } while self.begin < self.end { self.end -= 1; if let Some(elem) = self.stash.get(self.end) { self.yielded += 1; return Some((self.end, elem)) } } None } } #[derive(Debug, Encode, Decode)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] enum Entry<T> { Vacant(u32), Occupied(T), } impl<T> Flush for Entry<T> where T: Flush, { #[inline] fn flush(&mut self) { match self { Entry::Vacant(_) => (), Entry::Occupied(occupied) => occupied.flush(), } } } impl<T> Encode for Stash<T> { fn encode_to<W: scale::Output>(&self, dest: &mut W) { self.header.encode_to(dest); self.entries.encode_to(dest); } } impl<T> Decode for Stash<T> { fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> { let header = storage::Value::decode(input)?; let entries = SyncChunk::decode(input)?; Ok(Self { header, entries }) } } impl<T> AllocateUsing for Stash<T> { #[inline] unsafe fn allocate_using<A>(alloc: &mut A) -> Self where A: Allocate, { Self { header: storage::Value::allocate_using(alloc), entries: SyncChunk::allocate_using(alloc), } } } impl<T> Initialize for Stash<T> { type Args = (); #[inline(always)] fn default_value() -> Option<Self::Args> { Some(()) } #[inline] fn initialize(&mut self, _args: Self::Args) { self.header.set(StashHeader { next_vacant: 0, len: 0, max_len: 0, }); } } impl<T> Stash<T> { pub fn iter(&self) -> Iter<T> { Iter::new(self) } pub fn values(&self) -> Values<T> { Values::new(self) } pub fn entries_key(&self) -> Key { self.entries.cells_key() } pub fn len(&self) -> u32 { self.header.len } pub fn max_len(&self) -> u32 { self.header.max_len } pub fn is_empty(&self) -> bool { self.len() == 0 } fn next_vacant(&self) -> u32 { self.header.next_vacant } } impl<T> Stash<T> where T: scale::Codec, { pub fn get(&self, n: u32) -> Option<&T> { self.entries.get(n).and_then(|entry| { match entry { Entry::Occupied(val) => Some(val), Entry::Vacant(_) => None, } }) } pub fn put(&mut self, val: T) -> u32 { let current_vacant = self.header.next_vacant; debug_assert!(current_vacant <= self.len()); if current_vacant == self.len() { self.entries.set(current_vacant, Entry::Occupied(val)); self.header.next_vacant = current_vacant + 1; self.header.max_len += 1; } else { let next_vacant = match self .entries .put(current_vacant, Entry::Occupied(val)) .expect( "[ink_core::Stash::put] Error: \ expected a vacant entry here, but no entry was found", ) { Entry::Vacant(next_vacant) => next_vacant, Entry::Occupied(_) => { unreachable!( "[ink_core::Stash::put] Error: \ a next_vacant index can never point to an occupied entry" ) } }; self.header.next_vacant = next_vacant; } self.header.len += 1; current_vacant } pub fn take(&mut self, n: u32) -> Option<T> { match self.entries.get(n) { None | Some(Entry::Vacant(_)) => None, Some(Entry::Occupied(_)) => { match self .entries .put(n, Entry::Vacant(self.next_vacant())) .expect( "[ink_core::Stash::take] Error: \ we already asserted that the entry at `n` exists", ) { Entry::Occupied(val) => { self.header.next_vacant = n; debug_assert!(!self.is_empty()); self.header.len -= 1; Some(val) } Entry::Vacant(_) => { unreachable!( "[ink_core::Stash::take] Error: \ we already asserted that the entry is occupied" ) } } } } } }
#[cfg(feature = "ink-generate-abi")] use ink_abi::{ HasLayout, LayoutField, LayoutStruct, StorageLayout, }; use scale::{ Decode, Encode, }; #[cfg(feature = "ink-generate-abi")] use type_metadata::Metadata; use crate::storage::{ self, alloc::{ Allocate, AllocateUsing, Initialize, }, chunk::SyncChunk, Flush, Key, }; #[derive(Debug)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] pub struct Stash<T> { header: storage::Value<StashHeader>, entries: SyncChunk<Entry<T>>, } #[derive(Debug, Encode, Decode)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] struct StashHeader { next_vacant: u32, len: u32, max_len: u32, } impl Flush for StashHeader { #[inline] fn flush(&mut self) { self.next_vacant.flush(); self.len.flush(); self.max_len.flush(); } } #[derive(Debug)] pub struct Values<'a, T> { iter: Iter<'a, T>, } impl<'a, T> Values<'a, T> { pub(crate) fn new(stash: &'a Stash<T>) -> Self { Self { iter: stash.iter() } } } impl<T> Flush for Stash<T> where T: Encode + Flush, { #[inline] fn flush(&mut self) { self.header.flush(); self.entries.flush(); } } #[cfg(feature = "ink-generate-abi")] impl<T> HasLayout for Stash<T> where T: Metadata + 'static, { fn layout(&self) -> StorageLayout { LayoutStruct::new( Self::meta_type(), vec![ LayoutField::of("header", &self.header), LayoutField::of("entries", &self.entries), ], ) .into() } } impl<'a, T> Iterator for Values<'a, T> where T: scale::Codec, { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.iter.next().map(|(_index, value)| value) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, T> ExactSizeIterator for Values<'a, T> where T: scale::Codec {} impl<'a, T> DoubleEndedIterator for Values<'a, T> where T: scale::Codec, { fn next_back(&mut self) -> Option<Self::Item> { self.iter.next_back().map(|(_index, value)| value) } } #[derive(Debug)] pub struct Iter<'a, T> { stash: &'a Stash<T>, begin: u32, end: u32, yielded: u32, } impl<'a, T> Iter<'a, T> { pub(crate) fn new(stash: &'a Stash<T>) -> Self { Self { stash, begin: 0, end: stash.max_len(), yielded: 0, } } } impl<'a, T> Iterator for Iter<'a, T> where T: scale::Codec, { type Item = (u32, &'a T); fn next(&mut self) -> Option<Self::Item> { debug_assert!(self.begin <= self.end); if self.yielded == self.stash.len() { return None
self.header.len } pub fn max_len(&self) -> u32 { self.header.max_len } pub fn is_empty(&self) -> bool { self.len() == 0 } fn next_vacant(&self) -> u32 { self.header.next_vacant } } impl<T> Stash<T> where T: scale::Codec, { pub fn get(&self, n: u32) -> Option<&T> { self.entries.get(n).and_then(|entry| { match entry { Entry::Occupied(val) => Some(val), Entry::Vacant(_) => None, } }) } pub fn put(&mut self, val: T) -> u32 { let current_vacant = self.header.next_vacant; debug_assert!(current_vacant <= self.len()); if current_vacant == self.len() { self.entries.set(current_vacant, Entry::Occupied(val)); self.header.next_vacant = current_vacant + 1; self.header.max_len += 1; } else { let next_vacant = match self .entries .put(current_vacant, Entry::Occupied(val)) .expect( "[ink_core::Stash::put] Error: \ expected a vacant entry here, but no entry was found", ) { Entry::Vacant(next_vacant) => next_vacant, Entry::Occupied(_) => { unreachable!( "[ink_core::Stash::put] Error: \ a next_vacant index can never point to an occupied entry" ) } }; self.header.next_vacant = next_vacant; } self.header.len += 1; current_vacant } pub fn take(&mut self, n: u32) -> Option<T> { match self.entries.get(n) { None | Some(Entry::Vacant(_)) => None, Some(Entry::Occupied(_)) => { match self .entries .put(n, Entry::Vacant(self.next_vacant())) .expect( "[ink_core::Stash::take] Error: \ we already asserted that the entry at `n` exists", ) { Entry::Occupied(val) => { self.header.next_vacant = n; debug_assert!(!self.is_empty()); self.header.len -= 1; Some(val) } Entry::Vacant(_) => { unreachable!( "[ink_core::Stash::take] Error: \ we already asserted that the entry is occupied" ) } } } } } }
} while self.begin < self.end { let cur = self.begin; self.begin += 1; if let Some(elem) = self.stash.get(cur) { self.yielded += 1; return Some((cur, elem)) } } None } fn size_hint(&self) -> (usize, Option<usize>) { let remaining = (self.stash.len() - self.yielded) as usize; (remaining, Some(remaining)) } } impl<'a, T> ExactSizeIterator for Iter<'a, T> where T: scale::Codec {} impl<'a, T> DoubleEndedIterator for Iter<'a, T> where T: scale::Codec, { fn next_back(&mut self) -> Option<Self::Item> { debug_assert!(self.begin <= self.end); if self.yielded == self.stash.len() { return None } while self.begin < self.end { self.end -= 1; if let Some(elem) = self.stash.get(self.end) { self.yielded += 1; return Some((self.end, elem)) } } None } } #[derive(Debug, Encode, Decode)] #[cfg_attr(feature = "ink-generate-abi", derive(Metadata))] enum Entry<T> { Vacant(u32), Occupied(T), } impl<T> Flush for Entry<T> where T: Flush, { #[inline] fn flush(&mut self) { match self { Entry::Vacant(_) => (), Entry::Occupied(occupied) => occupied.flush(), } } } impl<T> Encode for Stash<T> { fn encode_to<W: scale::Output>(&self, dest: &mut W) { self.header.encode_to(dest); self.entries.encode_to(dest); } } impl<T> Decode for Stash<T> { fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> { let header = storage::Value::decode(input)?; let entries = SyncChunk::decode(input)?; Ok(Self { header, entries }) } } impl<T> AllocateUsing for Stash<T> { #[inline] unsafe fn allocate_using<A>(alloc: &mut A) -> Self where A: Allocate, { Self { header: storage::Value::allocate_using(alloc), entries: SyncChunk::allocate_using(alloc), } } } impl<T> Initialize for Stash<T> { type Args = (); #[inline(always)] fn default_value() -> Option<Self::Args> { Some(()) } #[inline] fn initialize(&mut self, _args: Self::Args) { self.header.set(StashHeader { next_vacant: 0, len: 0, max_len: 0, }); } } impl<T> Stash<T> { pub fn iter(&self) -> Iter<T> { Iter::new(self) } pub fn values(&self) -> Values<T> { Values::new(self) } pub fn entries_key(&self) -> Key { self.entries.cells_key() } pub fn len(&self) -> u32 {
random
[ { "content": "/// Returns an iterator over the uninterpreted bytes of all past emitted events.\n\npub fn emitted_events<T: EnvTypes>() -> impl Iterator<Item = Vec<u8>> {\n\n ContractEnv::<T>::emitted_events()\n\n}\n", "file_path": "core/src/env/test.rs", "rank": 0, "score": 403824.9360293277 }, { "content": "/// Iterator over the bits that are contained in the filled test bit vector.\n\nfn filled_bits() -> impl Iterator<Item = bool> + DoubleEndedIterator {\n\n vec![true, false, false, true, true, false].into_iter()\n\n}\n\n\n", "file_path": "core/src/storage/collections/bitvec/tests.rs", "rank": 1, "score": 294949.15535413637 }, { "content": "/// Yields back the filtered `#[ink(..)]` markers converted into their ink! form if any.\n\npub fn filter_map_ink_attributes<'a, I>(attrs: I) -> impl Iterator<Item = ir::Marker>\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute> + 'a,\n\n{\n\n use core::convert::TryFrom as _;\n\n attrs\n\n .into_iter()\n\n .cloned()\n\n .filter_map(|attr| ir::Marker::try_from(attr).ok())\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 2, "score": 286403.402976539 }, { "content": "/// Types implementing this trait are storage structs.\n\npub trait Storage: AllocateUsing + Initialize + Flush {}\n", "file_path": "lang2/src/traits.rs", "rank": 3, "score": 286237.0135275312 }, { "content": "/// Types implementing this type can be used as contract state.\n\npub trait ContractState: AllocateUsing + Initialize + Flush {\n\n /// The name of the contract state.\n\n ///\n\n /// # Note\n\n ///\n\n /// - This must be a valid Rust identifier.\n\n /// - Normally this reflects the name of the contract.\n\n // const NAME: &'static str;\n\n const NAME: &'static str;\n\n}\n\n\n\n/// Define contract state with less boilerplate code.\n\n#[macro_export]\n\nmacro_rules! state {\n\n\t(\n\n\t\t$( #[$state_meta:meta] )*\n\n\t\t$vis:vis struct $state_name:ident {\n\n\t\t\t$(\n\n\t\t\t\t$( #[$field_meta:meta] )*\n\n\t\t\t\t$field_name:ident : $field_ty:ty ,\n", "file_path": "model/src/state.rs", "rank": 4, "score": 281694.6694136751 }, { "content": "pub fn set_storage(key: &[u8], value: Option<&[u8]>) {\n\n match value {\n\n Some(value) => unsafe {\n\n sys::ext_set_storage(\n\n key.as_ptr() as u32,\n\n 1,\n\n value.as_ptr() as u32,\n\n value.len() as u32,\n\n )\n\n },\n\n None => unsafe { sys::ext_set_storage(key.as_ptr() as u32, 0, 0, 0) },\n\n }\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 5, "score": 243367.59517835078 }, { "content": "fn zero_bitvec_with_len(len: usize) -> storage::BitVec {\n\n let mut bv = new_empty_bitvec();\n\n for _ in 0..len {\n\n bv.push(false);\n\n }\n\n bv\n\n}\n\n\n", "file_path": "core/src/storage/collections/bitvec/tests.rs", "rank": 7, "score": 230011.3761833219 }, { "content": "/// A single cache entry for a copy chunk cell.\n\ntype CacheEntry<'a, T> = Entry<'a, u32, CacheValue<T>>;\n\n\n\nimpl<T> Cache<T> {\n\n /// Returns an immutable reference to the cached value at position `n` if any.\n\n fn get(&self, n: u32) -> Option<&CacheValue<T>> {\n\n self.entries.get(&n)\n\n }\n\n\n\n /// Returns a mutable reference to the cached value at position `n` if any.\n\n fn get_mut(&mut self, n: u32) -> Option<&mut CacheValue<T>> {\n\n self.entries.get_mut(&n)\n\n }\n\n\n\n /// Returns the cache entry at position `n`.\n\n fn entry_at(&mut self, n: u32) -> CacheEntry<T> {\n\n self.entries.entry(n)\n\n }\n\n\n\n /// Updates the cell value of the cached cell at position `n`.\n\n pub fn update(&mut self, n: u32, new_val: Option<T>) -> Option<&T> {\n", "file_path": "core/src/storage/chunk/sync_chunk/cache.rs", "rank": 8, "score": 227782.7845907726 }, { "content": "#[rustfmt::skip]\n\nfn instantiate() -> impl TestableContract<DeployArgs = u32> {\n\n\tContractDecl::using::<Adder, ContractEnv<DefaultSrmlTypes>>()\n\n\t\t.on_deploy(|env, init_val| {\n\n\t\t\tenv.state.val.set(init_val)\n\n\t\t})\n\n\t\t.on_msg_mut::<Inc>(|env, by| {\n\n\t\t\tenv.state.val += by\n\n\t\t})\n\n\t\t.on_msg::<Get>(|env, _| {\n\n\t\t\t*env.state.val\n\n\t\t})\n\n\t\t.instantiate()\n\n}\n\n\n", "file_path": "model/tests/incrementer.rs", "rank": 9, "score": 219108.22770462278 }, { "content": "pub fn get_storage(key: &[u8]) -> RetCode {\n\n unsafe { sys::ext_get_storage(key.as_ptr() as u32) }.into()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 10, "score": 212180.22439486458 }, { "content": "pub fn get_runtime_storage(key: &[u8]) -> RetCode {\n\n unsafe { sys::ext_get_runtime_storage(key.as_ptr() as u32, key.len() as u32) }.into()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 11, "score": 209782.19412135996 }, { "content": "#[test]\n\nfn iter() {\n\n run_test(|| {\n\n let stash = filled_stash();\n\n let mut iter = stash.iter();\n\n assert_eq!(iter.next(), Some((0, &5)));\n\n assert_eq!(iter.next(), Some((1, &42)));\n\n assert_eq!(iter.next(), Some((2, &1337)));\n\n assert_eq!(iter.next(), Some((3, &77)));\n\n assert_eq!(iter.next(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 12, "score": 209162.98130717242 }, { "content": "#[test]\n\nfn iter() {\n\n run_test(|| {\n\n let vec = new_filled_vec();\n\n let mut iter = vec.iter();\n\n assert_eq!(iter.next(), Some(&5));\n\n assert_eq!(iter.next(), Some(&42));\n\n assert_eq!(iter.next(), Some(&1337));\n\n assert_eq!(iter.next(), Some(&77));\n\n assert_eq!(iter.next(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/vec/tests.rs", "rank": 13, "score": 209027.664327905 }, { "content": "pub fn wrap(\n\n ident: &Ident,\n\n trait_name: &'static str,\n\n impl_quote: TokenStream2,\n\n) -> TokenStream2 {\n\n let mut renamed = format!(\"_IMPL_{}_FOR_\", trait_name);\n\n renamed.push_str(ident.to_string().trim_start_matches(\"r#\"));\n\n let dummy_const = Ident::new(&renamed, Span::call_site());\n\n\n\n quote! {\n\n #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)]\n\n const #dummy_const: () = {\n\n #[allow(unknown_lints)]\n\n #[cfg_attr(feature = \"cargo-clippy\", allow(useless_attribute))]\n\n #[allow(rust_2018_idioms)]\n\n use type_metadata as _type_metadata;\n\n use ink_abi as _ink_abi;\n\n\n\n #[cfg(not(feature = \"std\"))]\n\n extern crate alloc;\n", "file_path": "abi/derive/src/impl_wrapper.rs", "rank": 14, "score": 202235.4835417701 }, { "content": "pub fn assert_failure(input: TokenStream2, err_str: &'static str) {\n\n assert_eq!(\n\n generate_or_err(input)\n\n .map(|result| result.to_string())\n\n .map_err(|err| err.to_string()),\n\n Err(err_str.to_string())\n\n )\n\n}\n", "file_path": "lang/src/tests/utils.rs", "rank": 15, "score": 199897.43627374226 }, { "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\n#[cfg(test)]\n\npub use contract::generate_or_err;\n", "file_path": "lang2/macro/src/lib.rs", "rank": 16, "score": 199837.28111023857 }, { "content": "pub fn scratch_read(dest: &mut [u8], offset: u32) -> RetCode {\n\n unsafe { sys::ext_scratch_read(dest.as_mut_ptr() as u32, offset, dest.len() as u32) };\n\n RetCode::success()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 17, "score": 194219.58537347673 }, { "content": "pub fn scratch_size() -> usize {\n\n (unsafe { sys::ext_scratch_size() }) as usize\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 18, "score": 193523.10698716252 }, { "content": "/// Load the contents of the scratch buffer\n\nfn read_scratch_buffer() -> Vec<u8> {\n\n let size = unsafe { sys::ext_scratch_size() };\n\n let mut value = Vec::new();\n\n if size > 0 {\n\n value.resize(size as usize, 0);\n\n unsafe {\n\n sys::ext_scratch_read(value.as_mut_ptr() as u32, 0, size);\n\n }\n\n }\n\n value\n\n}\n\n\n", "file_path": "core/src/env/srml/srml_only/impls.rs", "rank": 19, "score": 190027.26449134015 }, { "content": "/// Types implementing this trait can be allocated on the storage by storage allocators.\n\npub trait AllocateUsing\n\nwhere\n\n Self: Sized,\n\n{\n\n /// Allocates an uninitialized instance of `Self` using\n\n /// the given storage allocator.\n\n ///\n\n /// # Safety\n\n ///\n\n /// Unsafe because the storage contents of the resulting instance\n\n /// are uninitialized. Operating on uninitialized storage may result\n\n /// in panics or even in undefined behaviour.\n\n unsafe fn allocate_using<A>(alloc: &mut A) -> Self\n\n where\n\n A: Allocate;\n\n}\n\n\n", "file_path": "core/src/storage/alloc/traits.rs", "rank": 20, "score": 183497.5705096972 }, { "content": "#[panic_handler]\n\npub fn panic(_info: &core::panic::PanicInfo) -> ! {\n\n unsafe { core::intrinsics::abort() }\n\n}\n\n\n\n// `extern` fn uses type `core::alloc::Layout`, which is not FFI-safe\n\n#[allow(improper_ctypes)]\n\n#[alloc_error_handler]\n\npub extern \"C\" fn oom(_: core::alloc::Layout) -> ! {\n\n unsafe { core::intrinsics::abort() }\n\n}\n", "file_path": "alloc/src/handlers.rs", "rank": 21, "score": 182316.12053254206 }, { "content": "/// Returns the in-group index of the `n`-th cell.\n\n/// This refers to the index which the cell has within a group.\n\n///\n\n/// For example, for `COUNT = 2` the cell `3` is found at in-group\n\n/// index `0` (within the group at index `2`).\n\nfn get_ingroup_index(n: u32) -> usize {\n\n let group = get_group_index(n);\n\n match (group, n) {\n\n (0, 0) => 0,\n\n (0, _) => panic!(\"first group contains only root node\"),\n\n (_, _) => ((n - 1) % COUNT) as usize,\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 should_get_group_index() {\n\n assert_eq!(get_group_index(0), 0);\n\n\n\n assert_eq!(get_group_index(1), 1);\n\n assert_eq!(get_group_index(2), 1);\n\n\n", "file_path": "core/src/storage/collections/binary_heap/duplex_sync_chunk.rs", "rank": 22, "score": 180265.6842266601 }, { "content": "/// Returns the given data back to the caller.\n\n///\n\n/// # Note\n\n///\n\n/// This operation must be the last operation performed by a called\n\n/// smart contract before it returns the execution back to its caller.\n\npub fn return_data<T, E>(data: T)\n\nwhere\n\n T: Encode,\n\n E: Env,\n\n{\n\n E::return_data(&data.encode()[..])\n\n}\n\n\n", "file_path": "core/src/env/api.rs", "rank": 23, "score": 179837.82242282334 }, { "content": "/// Types that are able to flush their state into the contract storage.\n\n///\n\n/// # Note\n\n///\n\n/// Many types support caching of their state into memory to avoid costly\n\n/// contract storage reads or writes. When execution of a contract is finished\n\n/// or interrupted (e.g. due to calling a remote contract) we have to flush\n\n/// all cached state into the contract storage.\n\n///\n\n/// # Implementation Hints\n\n///\n\n/// Caching types provided by ink! are `SyncCell` for caching of a single data\n\n/// and `SyncChunk` for caching an array of data.\n\n///\n\n/// All abstractions built upon them that do not have their own caching mechanism\n\n/// shall simply forward flushing to their interiors. Examples for this are\n\n/// `storage::Vec` or `storage::Value`.\n\npub trait Flush {\n\n /// Flushes the cached state back to the contract storage, if any.\n\n ///\n\n /// # Note\n\n ///\n\n /// Needs to take `self` by `&mut` since `SyncChunk` and `SyncCell`\n\n /// and potentially other abstraction facilities are required to\n\n /// write back their cached values which is a mutable operation.\n\n fn flush(&mut self);\n\n}\n\n\n\nmacro_rules! impl_empty_flush_for {\n\n\t( $($ty:ty),* ) => {\n\n\t\t$(\n\n\t\t\timpl Flush for $ty {\n\n\t\t\t\tfn flush(&mut self) {}\n\n\t\t\t}\n\n\t\t)*\n\n\t};\n\n}\n", "file_path": "core/src/storage/flush.rs", "rank": 24, "score": 179341.79110807192 }, { "content": "/// Parses the contract manifest and returns relevant metadata.\n\npub fn collect_crate_metadata(working_dir: Option<&PathBuf>) -> Result<CrateMetadata> {\n\n let mut cmd = MetadataCommand::new();\n\n if let Some(dir) = working_dir {\n\n cmd.current_dir(dir);\n\n }\n\n let metadata = cmd.exec()?;\n\n\n\n let root_package_id = metadata\n\n .resolve\n\n .and_then(|resolve| resolve.root)\n\n .ok_or_else(|| Error::Other(\"Cannot infer the root project id\".to_string()))?;\n\n\n\n // Find the root package by id in the list of packages. It is logical error if the root\n\n // package is not found in the list.\n\n let root_package = metadata\n\n .packages\n\n .iter()\n\n .find(|package| package.id == root_package_id)\n\n .expect(\"The package is not found in the `cargo metadata` output\");\n\n\n", "file_path": "cli/src/cmd/build.rs", "rank": 25, "score": 178370.19347094657 }, { "content": "pub fn set_rent_allowance(value: &[u8]) -> RetCode {\n\n unsafe { sys::ext_set_rent_allowance(value.as_ptr() as u32, value.len() as u32) };\n\n RetCode::success()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 26, "score": 177381.060820198 }, { "content": "/// Types implementing this trait require initialization of their storage contents\n\n/// after allocation before they can be used.\n\n///\n\n/// # Example\n\n///\n\n/// For example types like [`Value`](struct.Value.html) have uninitialized\n\n/// associated storage. Accessing a newly allocated instance of [`Value`](struct.Value.html)\n\n/// would result in a panic or even undefined behaviour.\n\n/// To circumvent this it is required to initialize its associated contract storage\n\n/// via [`initialize`](trait.Initialize.html#method.initialize).\n\npub trait Initialize\n\nwhere\n\n Self: Sized,\n\n{\n\n /// Arguments used for deployment.\n\n ///\n\n /// # Note\n\n ///\n\n /// - This will probably most often be `()`.\n\n /// - For multiple arguments use tuples.\n\n type Args: Sized;\n\n\n\n /// The default value for default initialization purposes.\n\n ///\n\n /// Returns `None` by default which means that the type does not\n\n /// support default initialization.\n\n ///\n\n /// # Note\n\n ///\n\n /// Should be manually implemented only by those storage types\n", "file_path": "core/src/storage/alloc/traits.rs", "rank": 27, "score": 175313.47137246918 }, { "content": "/// Iterator over the bit blocks of a bit vector.\n\n///\n\n/// # Note\n\n///\n\n/// This is an internal iterator that should not be exposed\n\n/// to the outside.\n\nstruct BlockIter<'a> {\n\n bitvec: &'a BitVec,\n\n begin: u32,\n\n end: u32,\n\n}\n\n\n\nimpl<'a> BlockIter<'a> {\n\n fn new(bitvec: &'a BitVec) -> Self {\n\n Self {\n\n bitvec,\n\n begin: 0,\n\n end: BitBlock::required_blocks(bitvec.len()),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for BlockIter<'a> {\n\n type Item = &'a BitBlock;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n", "file_path": "core/src/storage/collections/bitvec/vec.rs", "rank": 28, "score": 174668.6830918176 }, { "content": "pub fn generate_impl(input: TokenStream2) -> Result<TokenStream2> {\n\n let mut ast: DeriveInput = syn::parse2(input)?;\n\n\n\n ast.generics.type_params_mut().for_each(|p| {\n\n p.bounds.push(parse_quote!(_ink_abi::HasLayout));\n\n });\n\n\n\n let ident = &ast.ident;\n\n let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();\n\n\n\n let layout = match &ast.data {\n\n Data::Struct(ref s) => generate_struct_layout(s),\n\n Data::Enum(ref _e) => bail!(&ast, \"enums are not supported\"),\n\n Data::Union(ref _u) => bail!(&ast, \"unions are not supported\"),\n\n };\n\n\n\n let has_layout_impl = quote! {\n\n impl #impl_generics _ink_abi::HasLayout for #ident #ty_generics #where_clause {\n\n fn layout(&self) -> _ink_abi::StorageLayout {\n\n #layout.into()\n\n }\n\n }\n\n };\n\n\n\n Ok(wrap(ident, \"HAS_LAYOUT\", has_layout_impl))\n\n}\n\n\n", "file_path": "abi/derive/src/has_layout.rs", "rank": 29, "score": 174519.19555005943 }, { "content": "/// Sets the contract balance for the next contract invocation.\n\npub fn set_balance<T: EnvTypes>(balance: T::Balance) {\n\n ContractEnv::<T>::set_balance(balance)\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 30, "score": 172422.6977781889 }, { "content": "/// Sets the timestamp for the next contract invocation.\n\npub fn set_now<T: EnvTypes>(timestamp: T::Moment) {\n\n ContractEnv::<T>::set_now(timestamp)\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 31, "score": 172422.6977781889 }, { "content": "/// Sets the caller for the next calls to the given address.\n\npub fn set_caller<T: EnvTypes>(address: T::AccountId) {\n\n ContractEnv::<T>::set_caller(address)\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 32, "score": 170117.7620722319 }, { "content": "fn empty_stash() -> Stash<i32> {\n\n unsafe {\n\n let mut alloc = BumpAlloc::from_raw_parts(Key([0x0; 32]));\n\n Stash::allocate_using(&mut alloc).initialize_into(())\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 33, "score": 166273.55687046805 }, { "content": "fn filled_stash() -> Stash<i32> {\n\n let mut stash = empty_stash();\n\n stash.put(5);\n\n stash.put(42);\n\n stash.put(1337);\n\n stash.put(77);\n\n assert_eq!(stash.len(), 4);\n\n stash\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 34, "score": 166273.55687046805 }, { "content": "fn holey_stash() -> Stash<i32> {\n\n let mut stash = filled_stash();\n\n stash.put(123);\n\n stash.take(1);\n\n stash.take(3);\n\n stash\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 35, "score": 166273.55687046805 }, { "content": "#[test]\n\nfn using_self_val_in_deploy() {\n\n assert_failure(\n\n quote! {\n\n #![env = ink_core::env::DefaultSrmlTypes]\n\n struct TestContract {}\n\n impl Deploy for TestContract {\n\n fn deploy(self) {}\n\n }\n\n impl TestContract {}\n\n },\n\n \"the deploy implementation must operate on `&mut self`\",\n\n )\n\n}\n\n\n", "file_path": "lang/src/tests/mod.rs", "rank": 36, "score": 166203.13213615486 }, { "content": "#[test]\n\nfn using_self_ref_in_deploy() {\n\n assert_failure(\n\n quote! {\n\n #![env = ink_core::env::DefaultSrmlTypes]\n\n struct TestContract {}\n\n impl Deploy for TestContract {\n\n fn deploy(&self) {}\n\n }\n\n impl TestContract {}\n\n },\n\n \"the deploy implementation must operate on `&mut self`\",\n\n )\n\n}\n\n\n", "file_path": "lang/src/tests/mod.rs", "rank": 37, "score": 166203.13213615486 }, { "content": "#[test]\n\nfn using_self_val_in_message() {\n\n assert_failure(\n\n quote! {\n\n #![env = ink_core::env::DefaultSrmlTypes]\n\n struct TestContract {}\n\n impl Deploy for TestContract {\n\n fn deploy(&mut self) {}\n\n }\n\n impl TestContract {\n\n pub(external) fn with_self_value(self) {}\n\n }\n\n },\n\n \"contract messages must operate on `&self` or `&mut self`\",\n\n )\n\n}\n\n\n", "file_path": "lang/src/tests/mod.rs", "rank": 38, "score": 166203.13213615486 }, { "content": "#[test]\n\nfn using_non_self_in_message() {\n\n assert_failure(\n\n quote! {\n\n #![env = ink_core::env::DefaultSrmlTypes]\n\n struct TestContract {}\n\n impl Deploy for TestContract {\n\n fn deploy(&mut self) {}\n\n }\n\n impl TestContract {\n\n pub(external) fn with_self_value(not_self: u32) {}\n\n }\n\n },\n\n \"contract messages must operate on `&self` or `&mut self`\",\n\n )\n\n}\n\n\n", "file_path": "lang/src/tests/mod.rs", "rank": 39, "score": 166203.13213615486 }, { "content": "#[test]\n\nfn iter_back() {\n\n run_test(|| {\n\n let stash = filled_stash();\n\n let mut iter = stash.iter();\n\n assert_eq!(iter.next_back(), Some((3, &77)));\n\n assert_eq!(iter.next_back(), Some((2, &1337)));\n\n assert_eq!(iter.next_back(), Some((1, &42)));\n\n assert_eq!(iter.next_back(), Some((0, &5)));\n\n assert_eq!(iter.next_back(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 40, "score": 166063.5977981456 }, { "content": "#[test]\n\nfn iter_holey() {\n\n run_test(|| {\n\n let stash = holey_stash();\n\n let mut iter = stash.iter();\n\n assert_eq!(iter.next(), Some((0, &5)));\n\n assert_eq!(iter.next(), Some((2, &1337)));\n\n assert_eq!(iter.next(), Some((4, &123)));\n\n assert_eq!(iter.next(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 41, "score": 166063.5977981456 }, { "content": "#[test]\n\nfn deploy_handler_with_return_type() {\n\n assert_failure(\n\n quote! {\n\n #![env = ink_core::env::DefaultSrmlTypes]\n\n struct TestContract {}\n\n impl Deploy for TestContract {\n\n fn deploy(&mut self) -> u32 {}\n\n }\n\n },\n\n \"the deploy implementation must not have a return type\",\n\n )\n\n}\n\n\n", "file_path": "lang/src/tests/mod.rs", "rank": 42, "score": 166006.41914379472 }, { "content": "#[test]\n\nfn iter_back() {\n\n run_test(|| {\n\n let vec = new_filled_vec();\n\n let mut iter = vec.iter();\n\n assert_eq!(iter.next_back(), Some(&77));\n\n assert_eq!(iter.next_back(), Some(&1337));\n\n assert_eq!(iter.next_back(), Some(&42));\n\n assert_eq!(iter.next_back(), Some(&5));\n\n assert_eq!(iter.next_back(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/vec/tests.rs", "rank": 43, "score": 165931.14903801924 }, { "content": "/// Sets the current block number for the next contract invocation.\n\npub fn set_block_number<T: EnvTypes>(block_number: T::BlockNumber) {\n\n ContractEnv::<T>::set_block_number(block_number)\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 44, "score": 165758.52682503 }, { "content": "#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Encode, Decode)]\n\nstruct V(u32);\n\n\n", "file_path": "core/src/storage/collections/binary_heap/tests.rs", "rank": 45, "score": 165168.78390225465 }, { "content": "#[test]\n\nfn iter_size_hint() {\n\n run_test(|| {\n\n let stash = filled_stash();\n\n let mut iter = stash.iter();\n\n assert_eq!(iter.size_hint(), (4, Some(4)));\n\n iter.next();\n\n assert_eq!(iter.size_hint(), (3, Some(3)));\n\n })\n\n}\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 46, "score": 163240.87295299704 }, { "content": "#[test]\n\nfn iter_back_holey() {\n\n run_test(|| {\n\n let stash = holey_stash();\n\n let mut iter = stash.iter();\n\n assert_eq!(iter.next_back(), Some((4, &123)));\n\n assert_eq!(iter.next_back(), Some((2, &1337)));\n\n assert_eq!(iter.next_back(), Some((0, &5)));\n\n assert_eq!(iter.next_back(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/stash/tests.rs", "rank": 47, "score": 163240.87295299704 }, { "content": "#[test]\n\nfn iter_size_hint() {\n\n run_test(|| {\n\n let vec = new_filled_vec();\n\n let mut iter = vec.iter();\n\n assert_eq!(iter.size_hint(), (4, Some(4)));\n\n let _ = iter.next();\n\n assert_eq!(iter.size_hint(), (3, Some(3)));\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/vec/tests.rs", "rank": 48, "score": 163111.17334454093 }, { "content": "#[test]\n\nfn len() {\n\n const N: u32 = 5;\n\n let mut bv = new_empty_bitvec();\n\n for n in 1..=N {\n\n bv.push(false);\n\n assert_eq!(bv.len(), n);\n\n }\n\n for n in 1..=N {\n\n bv.pop();\n\n assert_eq!(bv.len(), N - n);\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/collections/bitvec/tests.rs", "rank": 49, "score": 162663.14423623076 }, { "content": "#[test]\n\nfn iter() {\n\n let filled = new_filled_bitvec();\n\n for (actual, expected) in filled.iter().zip(filled_bits()) {\n\n assert_eq!(actual, expected)\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/collections/bitvec/tests.rs", "rank": 50, "score": 162569.3180300733 }, { "content": "/// Returns the group index of the `n`-th cell.\n\nfn get_group_index(n: u32) -> u32 {\n\n match n {\n\n 0 => 0,\n\n _ => {\n\n // the first group only ever contains a single element:\n\n // the root node (e.g. for `COUNT = 2`, `[Some(root), None]`).\n\n // so when calculating indices we need to account for the\n\n // items which have been left empty in the first group.\n\n let padding = COUNT - 1;\n\n (n + padding) / COUNT\n\n }\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/collections/binary_heap/duplex_sync_chunk.rs", "rank": 51, "score": 161089.85628986277 }, { "content": "#[test]\n\nfn iter() {\n\n run_test(|| {\n\n // given\n\n let heap = filled_heap();\n\n\n\n // when\n\n let mut iter = heap.iter();\n\n\n\n // then\n\n // order can be arbitrary\n\n assert_eq!(iter.next(), Some((0, &1337)));\n\n assert_eq!(iter.next(), Some((1, &77)));\n\n assert_eq!(iter.next(), Some((2, &42)));\n\n assert_eq!(iter.next(), Some((3, &5)));\n\n assert_eq!(iter.next(), None);\n\n })\n\n}\n\n\n", "file_path": "core/src/storage/collections/binary_heap/tests.rs", "rank": 52, "score": 160611.9524285097 }, { "content": "/// Returns a filled storage vector at address `0x42`.\n\n///\n\n/// Elements are `[5, 42, 1337, 77]` in that order.\n\nfn new_filled_vec() -> storage::Vec<i32> {\n\n let mut vec = new_empty_vec();\n\n vec.push(5);\n\n vec.push(42);\n\n vec.push(1337);\n\n vec.push(77);\n\n assert_eq!(vec.len(), 4);\n\n vec\n\n}\n\n\n", "file_path": "core/src/storage/collections/vec/tests.rs", "rank": 53, "score": 160088.18354612813 }, { "content": "#[rustfmt::skip]\n\nfn instantiate() -> impl Contract {\n\n\tContractDecl::using::<Noop, ContractEnv<DefaultSrmlTypes>>()\n\n\t\t.on_deploy(|env, ()| {\n\n let (handler, state) = env.split_mut();\n\n state.deploy(handler)\n\n })\n\n .on_msg::<DoNothing>(|env, ()| {\n\n let (handler, state) = env.split();\n\n state.do_nothing(handler)\n\n })\n\n\t\t.instantiate()\n\n}\n", "file_path": "model/tests/noop.rs", "rank": 54, "score": 156618.32026533285 }, { "content": "/// Returns an iterator over all doc attributes.\n\npub fn filter_doc_attributes(\n\n attrs: &[syn::Attribute],\n\n) -> impl Iterator<Item = &syn::Attribute> {\n\n attrs\n\n .iter()\n\n .filter(|attr| attr.style == syn::AttrStyle::Outer && attr.path.is_ident(\"doc\"))\n\n}\n\n\n\nimpl Event {\n\n /// Returns all doc attributes of the message.\n\n pub fn docs(&self) -> impl Iterator<Item = &syn::Attribute> {\n\n filter_doc_attributes(&self.attrs)\n\n }\n\n}\n\n\n\nimpl Contract {\n\n /// Extracts the type for environment types from the contract items\n\n /// and performs some integrity checks on it.\n\n ///\n\n /// # Errors\n", "file_path": "lang/src/hir.rs", "rank": 55, "score": 155993.22812723287 }, { "content": "pub fn restore_to(\n\n dest: &[u8],\n\n code_hash: &[u8],\n\n rent_allowance: &[u8],\n\n filtered_keys: &[Key],\n\n) {\n\n unsafe {\n\n sys::ext_restore_to(\n\n dest.as_ptr() as u32,\n\n dest.len() as u32,\n\n code_hash.as_ptr() as u32,\n\n code_hash.len() as u32,\n\n rent_allowance.as_ptr() as u32,\n\n rent_allowance.len() as u32,\n\n filtered_keys.as_ptr() as u32,\n\n filtered_keys.len() as u32,\n\n )\n\n }\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 56, "score": 155982.26777725955 }, { "content": "pub fn create(\n\n code_hash: &[u8],\n\n gas_limit: u64,\n\n value: &[u8],\n\n create_data: &[u8],\n\n) -> RetCode {\n\n unsafe {\n\n sys::ext_instantiate(\n\n code_hash.as_ptr() as u32,\n\n code_hash.len() as u32,\n\n gas_limit,\n\n value.as_ptr() as u32,\n\n value.len() as u32,\n\n create_data.as_ptr() as u32,\n\n create_data.len() as u32,\n\n )\n\n }\n\n .into()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 57, "score": 155982.26777725955 }, { "content": "/// Returns an empty storage vector at address `0x42`.\n\nfn new_empty_vec<T>() -> storage::Vec<T> {\n\n unsafe {\n\n let mut alloc = BumpAlloc::from_raw_parts(Key([0x0; 32]));\n\n Vec::<T>::allocate_using(&mut alloc).initialize_into(())\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/collections/vec/tests.rs", "rank": 58, "score": 155875.2020334936 }, { "content": "#[rustfmt::skip]\n\nfn instantiate() -> impl Contract {\n\n\tContractDecl::using::<Erc20Token, ContractEnv<DefaultSrmlTypes>>()\n\n\t\t.on_deploy(|env, init_supply| {\n\n\t\t\tlet caller = env.caller();\n\n\t\t\tenv.state.balances[&caller] = init_supply;\n\n\t\t\tenv.state.total.set(init_supply);\n\n\t\t})\n\n\t\t.on_msg::<TotalSupply>(|env, _| {\n\n\t\t\t*env.state.total.get()\n\n\t\t})\n\n\t\t.on_msg::<BalanceOf>(|env, owner| {\n\n\t\t\tenv.state.balances[&owner]\n\n\t\t})\n\n\t\t.on_msg_mut::<Transfer>(|env, (to, amount)| {\n\n\t\t\tlet from = env.caller();\n\n\t\t\tlet balance_from = env.state.balances[&from];\n\n\t\t\tlet balance_to = env.state.balances[&to];\n\n\n\n\t\t\tif balance_from >= amount {\n\n\t\t\t\tenv.state.balances[&from] = balance_from - amount;\n\n\t\t\t\tenv.state.balances[&to] = balance_to + amount;\n\n\t\t\t\treturn true\n\n\t\t\t}\n\n\n\n\t\t\tfalse\n\n\t\t})\n\n\t\t.instantiate()\n\n}\n\n\n", "file_path": "examples/model/erc20/src/lib.rs", "rank": 59, "score": 152635.29200063547 }, { "content": "/// Instantiates a new smart contract.\n\n///\n\n/// Upon success returns the account ID of the newly created smart contract.\n\npub fn create<T>(\n\n code_hash: T::Hash,\n\n gas_limit: u64,\n\n value: T::Balance,\n\n input_data: &[u8],\n\n) -> Result<T::AccountId, CreateError>\n\nwhere\n\n T: Env,\n\n{\n\n T::create(code_hash, gas_limit, value, input_data)\n\n}\n", "file_path": "core/src/env/api.rs", "rank": 60, "score": 152557.99411707642 }, { "content": "pub fn call(callee: &[u8], gas_limit: u64, value: &[u8], call_data: &[u8]) -> RetCode {\n\n unsafe {\n\n sys::ext_call(\n\n callee.as_ptr() as u32,\n\n callee.len() as u32,\n\n gas_limit,\n\n value.as_ptr() as u32,\n\n value.len() as u32,\n\n call_data.as_ptr() as u32,\n\n call_data.len() as u32,\n\n )\n\n }\n\n .into()\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 61, "score": 152417.85773275825 }, { "content": "/// Returns the total number of reads to all storage entries.\n\npub fn total_reads() -> u64 {\n\n ContractEnvStorage::total_reads()\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 62, "score": 150613.39701694093 }, { "content": "/// Returns the total number of writes to all storage entries.\n\npub fn total_writes() -> u64 {\n\n ContractEnvStorage::total_writes()\n\n}\n\n\n", "file_path": "core/src/env/test.rs", "rank": 63, "score": 150613.39701694093 }, { "content": "/// Invokes a remote smart contract.\n\n///\n\n/// Does not expect to receive return data back.\n\n/// Use this whenever you call a remote smart contract that returns nothing back.\n\npub fn call_invoke<T>(\n\n callee: T::AccountId,\n\n gas: u64,\n\n value: T::Balance,\n\n input_data: &[u8],\n\n) -> Result<(), CallError>\n\nwhere\n\n T: Env,\n\n{\n\n T::call_invoke(callee, gas, value, input_data)\n\n}\n\n\n", "file_path": "core/src/env/api.rs", "rank": 64, "score": 150613.2267184798 }, { "content": "fn generate_type_spec_code(ty: &syn::Type) -> TokenStream2 {\n\n fn without_display_name(ty: &syn::Type) -> TokenStream2 {\n\n quote! { ink_abi::TypeSpec::new::<#ty>() }\n\n }\n\n if let syn::Type::Path(type_path) = ty {\n\n if type_path.qself.is_some() {\n\n return without_display_name(ty)\n\n }\n\n let path = &type_path.path;\n\n if path.segments.is_empty() {\n\n return without_display_name(ty)\n\n }\n\n let segs = path\n\n .segments\n\n .iter()\n\n .map(|seg| seg.ident.to_string())\n\n .collect::<Vec<_>>();\n\n return quote! {\n\n ink_abi::TypeSpec::with_name_segs::<#ty, _>(vec![#(#segs),*].into_iter().map(AsRef::as_ref))\n\n }\n\n }\n\n without_display_name(ty)\n\n}\n\n\n", "file_path": "lang/src/gen/abi.rs", "rank": 65, "score": 150131.1412371613 }, { "content": "fn dummy_chunk() -> SyncChunk<u32> {\n\n unsafe {\n\n let mut alloc = BumpAlloc::from_raw_parts(Key([0x0; 32]));\n\n SyncChunk::allocate_using(&mut alloc)\n\n }\n\n}\n\n\n", "file_path": "core/src/storage/chunk/sync_chunk/tests.rs", "rank": 66, "score": 146004.80863628356 }, { "content": "/// Evaluates a remote smart contract.\n\n///\n\n/// Expects to receive return data back.\n\n/// Use this whenever calling a remote smart contract that returns a value.\n\npub fn call_evaluate<T, R>(\n\n callee: T::AccountId,\n\n gas: u64,\n\n value: T::Balance,\n\n input_data: &[u8],\n\n) -> Result<R, CallError>\n\nwhere\n\n T: Env,\n\n R: Decode,\n\n{\n\n T::call_evaluate(callee, gas, value, input_data)\n\n}\n\n\n", "file_path": "core/src/env/api.rs", "rank": 67, "score": 145668.47866897532 }, { "content": "/// Yields back the filtered `#[ink(..)]` markers if any.\n\npub fn filter_ink_attributes<'a, I>(\n\n attrs: I,\n\n) -> impl Iterator<Item = &'a syn::Attribute> + 'a\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute> + 'a,\n\n{\n\n attrs.into_iter().filter(|attr| is_ink_attribute(attr))\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 68, "score": 145658.3618587863 }, { "content": "pub fn println(content: &str) {\n\n let bytes = content.as_bytes();\n\n unsafe { sys::ext_println(bytes.as_ptr() as u32, bytes.len() as u32) }\n\n}\n\n\n\nmod sys {\n\n extern \"C\" {\n\n pub fn ext_instantiate(\n\n init_code_ptr: u32,\n\n init_code_len: u32,\n\n gas: u64,\n\n value_ptr: u32,\n\n value_len: u32,\n\n input_data_ptr: u32,\n\n input_data_len: u32,\n\n ) -> u32;\n\n\n\n pub fn ext_call(\n\n callee_ptr: u32,\n\n callee_len: u32,\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 69, "score": 145652.81708266103 }, { "content": "/// Returns `Ok` if all identifiers within the `TokenStream` match `pred`\n\n/// and otherwise return an error pointing to the faulty `Ident`.\n\npub fn idents_respect_pred<P, E>(\n\n input: TokenStream2,\n\n pred: P,\n\n or_err: E,\n\n) -> Result<(), syn::Error>\n\nwhere\n\n P: Copy + Fn(&Ident) -> bool,\n\n E: Copy + Fn(&Ident) -> syn::Error,\n\n{\n\n for tt in input.into_iter() {\n\n match tt {\n\n TokenTree2::Ident(ident) => {\n\n if !pred(&ident) {\n\n return Err(or_err(&ident))\n\n }\n\n }\n\n TokenTree2::Group(group) => {\n\n // We ignore upon success and return back upon error.\n\n idents_respect_pred(group.stream(), pred, or_err)?;\n\n }\n\n TokenTree2::Punct(_) | TokenTree2::Literal(_) => (),\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "lang2/macro/src/lint.rs", "rank": 70, "score": 143865.46002660418 }, { "content": "/// Yields back all non-`#[ink(..)]` attributes if any.\n\npub fn filter_non_ink_attributes<'a, I>(\n\n attrs: I,\n\n) -> impl Iterator<Item = &'a syn::Attribute> + 'a\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute> + 'a,\n\n{\n\n attrs.into_iter().filter(|attr| !is_ink_attribute(attr))\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 71, "score": 143865.02791019244 }, { "content": "pub fn dispatch_call(call: &[u8]) {\n\n unsafe { sys::ext_dispatch_call(call.as_ptr() as u32, call.len() as u32) }\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 72, "score": 143859.4831340672 }, { "content": "pub fn random_seed(subject: &[u8]) {\n\n unsafe { sys::ext_random_seed(subject.as_ptr() as u32, subject.len() as u32) }\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 73, "score": 143859.4831340672 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nstruct StorageMarker<S>(PhantomData<fn() -> S>);\n\n\n\nimpl<S> Default for StorageMarker<S> {\n\n fn default() -> Self {\n\n Self(Default::default())\n\n }\n\n}\n\n\n\n/// Simplifies declaration of a smart contract.\n\npub struct ContractBuilder<Storage, Constrs, Msgs> {\n\n storage: StorageMarker<Storage>,\n\n constructors: Constrs,\n\n messages: Msgs,\n\n}\n\n\n\nimpl<Storage, Constrs> ContractBuilder<Storage, Constrs, EmptyDispatchList>\n\nwhere\n\n Constrs: PushDispatcher,\n\n{\n\n /// Pushes a new constructor to the contract definition.\n", "file_path": "lang2/src/contract.rs", "rank": 74, "score": 143279.64817595723 }, { "content": "/// Filters the given attributes for `#[doc(..)]` attributes\n\n/// and trims them to human-readable documentation strings.\n\n///\n\n/// # Note\n\n///\n\n/// This is mainly used in the ABI generation routines.\n\npub fn filter_map_trimmed_doc_strings<'a, I>(\n\n attrs: I,\n\n) -> impl Iterator<Item = String> + 'a\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute>,\n\n <I as IntoIterator>::IntoIter: 'a,\n\n{\n\n attrs\n\n .into_iter()\n\n .filter(move |attr| {\n\n attr.style == syn::AttrStyle::Outer && attr.path.is_ident(\"doc\")\n\n })\n\n .map(to_trimmed_doc_string)\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 75, "score": 142142.46644914412 }, { "content": "#[proc_macro]\n\npub fn contract(input: TokenStream) -> TokenStream {\n\n contract::generate(input.into()).into()\n\n}\n\n\n\n#[cfg(test)]\n\npub use contract::generate_or_err;\n", "file_path": "lang/src/lib.rs", "rank": 76, "score": 141077.381779459 }, { "content": "/// Negate the given bytes inplace.\n\n///\n\n/// Interprets the bytes as big endian twos-complement number.\n\npub fn negate_bytes(bytes: &mut [u8]) {\n\n invert_bytes(bytes);\n\n bytes_add_bytes(bytes, &[0x01]);\n\n}\n\n\n\nmacro_rules! impl_slice_as_array {\n\n ( $name:ident, $n:expr ) => {\n\n /// Interprets the slice as exact size array if possible.\n\n ///\n\n /// Otherwise returns `None`.\n\n pub fn $name<T>(slice: &[T]) -> Option<&[T; $n]> {\n\n if slice.len() != $n {\n\n return None\n\n }\n\n Some(unsafe { &*(slice.as_ptr() as *const [T; $n]) })\n\n }\n\n };\n\n}\n\n\n\nimpl_slice_as_array!(slice4_as_array4, 4);\n\nimpl_slice_as_array!(slice8_as_array8, 8);\n\nimpl_slice_as_array!(slice16_as_array16, 16);\n\n\n", "file_path": "core/src/byte_utils.rs", "rank": 77, "score": 141077.381779459 }, { "content": "pub fn generate(input: TokenStream2) -> TokenStream2 {\n\n match generate_or_err(input) {\n\n Ok(tokens) => tokens,\n\n Err(err) => err.to_compile_error(),\n\n }\n\n}\n\n\n", "file_path": "lang/src/contract.rs", "rank": 78, "score": 141077.381779459 }, { "content": "/// Types implementing this trait are storage allocators.\n\npub trait Allocator: Allocate {\n\n /// Deallocates a storage area.\n\n ///\n\n /// The given storage region must have been allocated by this\n\n /// allocator before.\n\n fn dealloc(&mut self, key: Key);\n\n}\n\n\n", "file_path": "core/src/storage/alloc/traits.rs", "rank": 79, "score": 140927.60325066108 }, { "content": "fn serialize_key<S>(key: &LayoutKey, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let bytes = key.0;\n\n let mut hex = String::with_capacity(bytes.len() * 2 + 2);\n\n write!(hex, \"0x\").expect(\"failed writing to string\");\n\n for byte in &bytes {\n\n write!(hex, \"{:02x}\", byte).expect(\"failed writing to string\");\n\n }\n\n\n\n serializer.serialize_str(&hex)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use type_metadata::{\n\n form::{\n\n Form,\n", "file_path": "abi/src/layout.rs", "rank": 80, "score": 139618.47607258093 }, { "content": "/// Types implementing this trait can allocate storage.\n\n///\n\n/// # Note\n\n///\n\n/// Since the current Wasm implementation is 32-bit we are\n\n/// fine to only support allocation sizes of max 32-bit in\n\n/// contract storage. However, for static allocator like\n\n/// `BumpAllocator` that is meant to allocate also other\n\n/// allocators we might need relaxed allocation sizes.\n\npub trait Allocate {\n\n /// Allocates a storage area.\n\n ///\n\n /// The returned key denotes a storage region that fits for at\n\n /// least the given number of cells.\n\n fn alloc(&mut self, size: u64) -> Key;\n\n}\n\n\n", "file_path": "core/src/storage/alloc/traits.rs", "rank": 81, "score": 139527.32047697206 }, { "content": "pub fn generate(input: TokenStream2) -> TokenStream2 {\n\n match generate_impl(input) {\n\n Ok(output) => output,\n\n Err(err) => err.to_compile_error(),\n\n }\n\n}\n\n\n", "file_path": "abi/derive/src/has_layout.rs", "rank": 82, "score": 139355.52665609206 }, { "content": "#[proc_macro_derive(HasLayout)]\n\npub fn has_layout(input: TokenStream) -> TokenStream {\n\n has_layout::generate(input.into()).into()\n\n}\n", "file_path": "abi/derive/src/lib.rs", "rank": 83, "score": 139355.52665609206 }, { "content": "/// Returns the keccak-256 hash for the given byte slice.\n\npub fn keccak256<T>(val: &T) -> [u8; 32]\n\nwhere\n\n T: ?Sized + Hash,\n\n{\n\n let mut hasher = Keccak256Hasher::default();\n\n val.hash(&mut hasher);\n\n hasher.finish256()\n\n}\n", "file_path": "utils/src/hash.rs", "rank": 84, "score": 138048.73897688463 }, { "content": "pub fn scratch_write(src: &[u8]) -> RetCode {\n\n unsafe { sys::ext_scratch_write(src.as_ptr() as u32, src.len() as u32) };\n\n RetCode::success()\n\n}\n\n\n\nmacro_rules! impl_ext_wrapper_for {\n\n ( $( ($name:ident => $ext_name:ident), )* ) => {\n\n $(\n\n pub fn $name() {\n\n unsafe {\n\n sys::$ext_name()\n\n }\n\n }\n\n )*\n\n }\n\n}\n\nimpl_ext_wrapper_for! {\n\n (caller => ext_caller),\n\n (block_number => ext_block_number),\n\n (address => ext_address),\n\n (balance => ext_balance),\n\n (gas_price => ext_gas_price),\n\n (gas_left => ext_gas_left),\n\n (value_transferred => ext_value_transferred),\n\n (now => ext_now),\n\n (rent_allowance => ext_rent_allowance),\n\n (minimum_balance => ext_minimum_balance),\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 85, "score": 137700.96034904025 }, { "content": "/// Dispatches a Call into the runtime, for invoking other substrate\n\n/// modules. Dispatched only after successful contract execution.\n\n///\n\n/// The encoded Call MUST be decodable by the target substrate runtime.\n\n/// If decoding fails, then the smart contract execution will fail.\n\npub fn dispatch_call<T, C>(call: C)\n\nwhere\n\n T: Env,\n\n C: Into<<T as EnvTypes>::Call>,\n\n{\n\n T::dispatch_raw_call(&call.into().encode()[..])\n\n}\n\n\n", "file_path": "core/src/env/api.rs", "rank": 86, "score": 136841.04705299102 }, { "content": "/// Returns `true` if the attributes contain any `#[ink(..)]` markers.\n\npub fn has_ink_attributes<'a, I>(attrs: I) -> bool\n\nwhere\n\n I: IntoIterator<Item = &'a syn::Attribute> + 'a,\n\n{\n\n filter_ink_attributes(attrs).count() > 0\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 88, "score": 136255.4050282908 }, { "content": "/// Returns `true` if the given attribute is any of `#[ink(..)]`.\n\npub fn is_ink_attribute(attr: &syn::Attribute) -> bool {\n\n attr.path.is_ident(\"ink\")\n\n}\n\n\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 89, "score": 135181.2226403288 }, { "content": "pub fn generate_or_err(input: TokenStream2) -> Result<TokenStream2> {\n\n let ast_contract = parser::parse_contract(input)?;\n\n let hir_contract = hir::Contract::from_ast(&ast_contract)?;\n\n #[cfg(feature = \"ink-generate-abi\")]\n\n old_abi::generate_old_abi(&hir_contract)?;\n\n let tokens = gen::generate_code(&hir_contract);\n\n Ok(tokens)\n\n}\n", "file_path": "lang/src/contract.rs", "rank": 90, "score": 135175.82440210902 }, { "content": "pub fn deposit_event(topics: &[u8], data: &[u8]) {\n\n unsafe {\n\n sys::ext_deposit_event(\n\n topics.as_ptr() as u32,\n\n topics.len() as u32,\n\n data.as_ptr() as u32,\n\n data.len() as u32,\n\n )\n\n }\n\n}\n\n\n", "file_path": "core/src/env2/srml/ext.rs", "rank": 91, "score": 135175.82440210902 }, { "content": "/// Writes a JSON API description into the `target/` folder.\n\npub fn generate_old_abi(contract: &hir::Contract) -> Result<()> {\n\n let description = ContractDescription::try_from(contract)?;\n\n let contents = serde_json::to_string_pretty(&description)\n\n .expect(\"Failed at generating JSON API description as JSON\");\n\n let path_buf = String::from(\"target/old_abi.json\");\n\n std::fs::create_dir(\"target\").unwrap_or(());\n\n std::fs::write(path_buf, contents)\n\n .expect(\"Failed at writing JSON API descrition to file\");\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::{\n\n PrimitiveTypeDescription::*,\n\n TypeDescription::*,\n\n *,\n\n };\n\n use syn::parse_quote;\n\n\n", "file_path": "lang/src/old_abi.rs", "rank": 92, "score": 135175.82440210902 }, { "content": "/// Generates code for the given contract.\n\n///\n\n/// # Note\n\n///\n\n/// This generates code for normal Wasm smart contract builds as\n\n/// well as code for specialized `test` and `doc` targets.\n\npub fn generate_code(contract: &hir::Contract) -> TokenStream2 {\n\n let mut tokens = quote! {};\n\n build::generate_code(&mut tokens, contract);\n\n doc::generate_code(&mut tokens, contract);\n\n test::generate_code(&mut tokens, contract);\n\n abi::generate_code(&mut tokens, contract);\n\n as_dependency::generate_code(&mut tokens, contract);\n\n tokens\n\n}\n\n\n", "file_path": "lang/src/gen/mod.rs", "rank": 93, "score": 135175.82440210902 }, { "content": "/// Trims a doc string obtained from an attribute token stream into the actual doc string.\n\n///\n\n/// Practically speaking this method removes the trailing start `\" = \\\"\"` and end `\\\"`\n\n/// of documentation strings coming from Syn attribute token streams.\n\npub fn to_trimmed_doc_string(attr: &syn::Attribute) -> String {\n\n attr.tokens\n\n .to_string()\n\n .trim_start_matches('=')\n\n .trim_start()\n\n .trim_start_matches('r')\n\n .trim_start_matches('\"')\n\n .trim_end_matches('\"')\n\n .trim()\n\n .into()\n\n}\n", "file_path": "lang2/macro/src/ir/utils.rs", "rank": 94, "score": 133589.55292735697 }, { "content": "pub fn assert_eq_tokenstreams(input: TokenStream2, expected: TokenStream2) {\n\n let result = generate_or_err(input)\n\n .map(|result| result.to_string())\n\n .map_err(|err| err.to_string());\n\n let expected = Ok(expected.to_string());\n\n assert_eq!(result, expected,)\n\n}\n\n\n", "file_path": "lang/src/tests/utils.rs", "rank": 95, "score": 132053.37404287682 }, { "content": "/// Types implementing this are messages that may only read from storage.\n\npub trait Message: FnInput + FnOutput + FnSelector {\n\n const IS_MUT: bool;\n\n}\n\n\n", "file_path": "lang2/src/traits.rs", "rank": 96, "score": 132007.1743336398 }, { "content": "/// Load the wasm blob from the specified path.\n\n///\n\n/// Defaults to the target contract wasm in the current project, inferred via the crate metadata.\n\nfn load_contract_code(path: Option<&PathBuf>) -> Result<Vec<u8>> {\n\n let default_wasm_path =\n\n build::collect_crate_metadata(path).map(CrateMetadata::dest_wasm)?;\n\n let contract_wasm_path = path.unwrap_or(&default_wasm_path);\n\n\n\n let mut data = Vec::new();\n\n let mut file = fs::File::open(&contract_wasm_path)\n\n .map_err(|e| format!(\"Failed to open {}: {}\", contract_wasm_path.display(), e))?;\n\n file.read_to_end(&mut data)?;\n\n\n\n Ok(data)\n\n}\n\n\n", "file_path": "cli/src/cmd/deploy.rs", "rank": 97, "score": 131615.97257345653 }, { "content": "pub fn parse_contract(token_stream: TokenStream2) -> Result<ast::Contract> {\n\n syn::parse2(token_stream).map_err(Into::into)\n\n}\n\n\n\nimpl Parse for ast::Contract {\n\n fn parse(input: ParseStream<'_>) -> Result<Self> {\n\n Ok(ast::Contract {\n\n items: ast::Item::parse_outer(input)?,\n\n })\n\n }\n\n}\n\n\n\nimpl ast::Item {\n\n fn parse_outer(input: ParseStream<'_>) -> Result<Vec<Self>> {\n\n let mut res = Vec::new();\n\n while !input.is_empty() {\n\n res.push(input.parse()?);\n\n }\n\n Ok(res)\n\n }\n", "file_path": "lang/src/parser.rs", "rank": 98, "score": 131282.4776900934 }, { "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": "lang2/macro/src/contract.rs", "rank": 99, "score": 129751.17362194766 } ]
Rust
day-8/src/main.rs
jharmer95/advent2020
113fa84933ddf9d3d70fb0620aa27b585a9f3a74
use inputs::get_input; mod cpu_sim { use std::{cmp::Ordering, str::FromStr}; pub struct CPU { accumulator: isize, pc: usize, } pub enum ExecutionErr { Ok, Finished, OutOfBounds, } impl CPU { pub const fn new() -> Self { Self { accumulator: 0, pc: 0, } } pub fn reset(&mut self) { self.accumulator = 0; self.pc = 0; } pub fn run_one(&mut self, opcodes: &[Instruction]) -> ExecutionErr { let num_ins = opcodes.len(); match self.pc.cmp(&num_ins) { Ordering::Equal => return ExecutionErr::Finished, Ordering::Greater => { eprintln!("Invalid address loaded into PC!"); return ExecutionErr::OutOfBounds; } Ordering::Less => (), } match opcodes[self.pc] { Instruction::NOP(_) => self.pc += 1, Instruction::ACC(op) => { self.accumulator += op; self.pc += 1; } Instruction::JMP(op) => { if op < 0 { self.pc -= -op as usize; } else { self.pc += op as usize; } } } ExecutionErr::Ok } pub const fn accumulator(&self) -> isize { self.accumulator } pub const fn pc(&self) -> usize { self.pc } } #[derive(Debug)] pub enum Instruction { NOP(isize), ACC(isize), JMP(isize), } impl FromStr for Instruction { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let x: Vec<&str> = s.split(' ').collect(); match x.get(0) { Some(&"nop") => Ok(Self::NOP(x[1].parse().unwrap())), Some(&"acc") => Ok(Self::ACC(x[1].parse().unwrap())), Some(&"jmp") => Ok(Self::JMP(x[1].parse().unwrap())), _ => Err(String::from("Invalid opcode passed")), } } } impl Clone for Instruction { fn clone(&self) -> Self { match self { Self::ACC(op) => Self::ACC(*op), Self::JMP(op) => Self::JMP(*op), Self::NOP(op) => Self::NOP(*op), } } } } fn part1(opcodes: &[cpu_sim::Instruction]) -> isize { let mut cpu = cpu_sim::CPU::new(); let mut pc_vals = vec![]; while !pc_vals.contains(&cpu.pc()) { pc_vals.push(cpu.pc()); cpu.run_one(opcodes); } cpu.accumulator() } fn test_sequence(cpu: &mut cpu_sim::CPU, opcodes: &[cpu_sim::Instruction]) -> bool { let mut pc_vals = vec![]; loop { if pc_vals.contains(&cpu.pc()) { return false; } pc_vals.push(cpu.pc()); match cpu.run_one(opcodes) { cpu_sim::ExecutionErr::Ok => (), cpu_sim::ExecutionErr::Finished => { return true; } cpu_sim::ExecutionErr::OutOfBounds => { eprintln!("Out of bounds error occurred!"); return false; } } } } fn part2(opcodes: &[cpu_sim::Instruction]) -> isize { let mut cpu = cpu_sim::CPU::new(); let mut opcodes2 = opcodes.to_vec(); for i in 0..opcodes2.len() { match opcodes2[i] { cpu_sim::Instruction::NOP(op) => { opcodes2[i] = cpu_sim::Instruction::JMP(op); if test_sequence(&mut cpu, &opcodes2) { return cpu.accumulator(); } opcodes2[i] = cpu_sim::Instruction::NOP(op); } cpu_sim::Instruction::ACC(_) => continue, cpu_sim::Instruction::JMP(op) => { opcodes2[i] = cpu_sim::Instruction::NOP(op); if test_sequence(&mut cpu, &opcodes2) { return cpu.accumulator(); } opcodes2[i] = cpu_sim::Instruction::JMP(op); } } cpu.reset(); } panic!("All possibilities exhausted!"); } fn main() { let inputs = get_input::<cpu_sim::Instruction>("inputs/day-8.txt").expect("Could not parse path!"); println!("Part 1 solution: {}", part1(&inputs)); println!("Part 2 solution: {}", part2(&inputs)); } #[test] fn check() { let inputs = get_input::<cpu_sim::Instruction>("../inputs/day-8.txt").expect("Could not parse path!"); assert_eq!(part1(&inputs), 1723); assert_eq!(part2(&inputs), 846); }
use inputs::get_input; mod cpu_sim { use std::{cmp::Ordering, str::FromStr}; pub struct CPU { accumulator: isize, pc: usize, } pub enum ExecutionErr { Ok, Finished, OutOfBounds, } impl CPU { pub const fn new() -> Self { Self { accumulator: 0, pc: 0, } } pub fn reset(&mut self) { self.accumulator = 0; self.pc = 0; } pub fn run_one(&mut self, opcodes: &[Instruction]) -> ExecutionErr { let num_ins = opcodes.len(); match self.pc.cmp(&num_ins) { Ordering::Equal => return ExecutionErr::Finished, Ordering::Greater => { eprintln!("Invalid address loaded into PC!"); return ExecutionErr::OutOfBounds; } Ordering::Less => (), } match opcodes[self.pc] { Instruction::NOP(_) => self.pc += 1, Instruction::ACC(op) => { self.accumulator += op; self.pc += 1; } Instruction::JMP(op) => { if op < 0 { self.pc -= -op as usize; } else { self.pc += op as usize; } } } ExecutionErr::Ok } pub const fn accumulator(&self) -> isize { self.accumulator } pub const fn pc(&self) -> usize { self.pc } } #[derive(Debug)] pub enum Instruction { NOP(isize), ACC(isize), JMP(isize), } impl FromStr for Instruction { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let x: Vec<&str> = s.split(' ').collect(); match x.get(0) { Some(&"nop") => Ok(Self::NOP(x[1].parse().unwrap())), Some(&"acc") => Ok(Self::ACC(x[1].parse().unwrap())), Some(&"jmp") => Ok(Self::JMP(x[1].parse().unwrap())), _ => Err(String::from("Invalid opcode passed")), } } } impl Clone for Instruction {
} } fn part1(opcodes: &[cpu_sim::Instruction]) -> isize { let mut cpu = cpu_sim::CPU::new(); let mut pc_vals = vec![]; while !pc_vals.contains(&cpu.pc()) { pc_vals.push(cpu.pc()); cpu.run_one(opcodes); } cpu.accumulator() } fn test_sequence(cpu: &mut cpu_sim::CPU, opcodes: &[cpu_sim::Instruction]) -> bool { let mut pc_vals = vec![]; loop { if pc_vals.contains(&cpu.pc()) { return false; } pc_vals.push(cpu.pc()); match cpu.run_one(opcodes) { cpu_sim::ExecutionErr::Ok => (), cpu_sim::ExecutionErr::Finished => { return true; } cpu_sim::ExecutionErr::OutOfBounds => { eprintln!("Out of bounds error occurred!"); return false; } } } } fn part2(opcodes: &[cpu_sim::Instruction]) -> isize { let mut cpu = cpu_sim::CPU::new(); let mut opcodes2 = opcodes.to_vec(); for i in 0..opcodes2.len() { match opcodes2[i] { cpu_sim::Instruction::NOP(op) => { opcodes2[i] = cpu_sim::Instruction::JMP(op); if test_sequence(&mut cpu, &opcodes2) { return cpu.accumulator(); } opcodes2[i] = cpu_sim::Instruction::NOP(op); } cpu_sim::Instruction::ACC(_) => continue, cpu_sim::Instruction::JMP(op) => { opcodes2[i] = cpu_sim::Instruction::NOP(op); if test_sequence(&mut cpu, &opcodes2) { return cpu.accumulator(); } opcodes2[i] = cpu_sim::Instruction::JMP(op); } } cpu.reset(); } panic!("All possibilities exhausted!"); } fn main() { let inputs = get_input::<cpu_sim::Instruction>("inputs/day-8.txt").expect("Could not parse path!"); println!("Part 1 solution: {}", part1(&inputs)); println!("Part 2 solution: {}", part2(&inputs)); } #[test] fn check() { let inputs = get_input::<cpu_sim::Instruction>("../inputs/day-8.txt").expect("Could not parse path!"); assert_eq!(part1(&inputs), 1723); assert_eq!(part2(&inputs), 846); }
fn clone(&self) -> Self { match self { Self::ACC(op) => Self::ACC(*op), Self::JMP(op) => Self::JMP(*op), Self::NOP(op) => Self::NOP(*op), } }
function_block-full_function
[ { "content": "fn tokenize(inputs: &[String]) -> HashMap<&str, Vec<(String, usize)>> {\n\n let mut ret = HashMap::new();\n\n\n\n for line in inputs {\n\n let split: Vec<&str> = line.split(\" bags contain \").collect();\n\n let container = split[0];\n\n let contents = split[1];\n\n\n\n let mut str1 = contents.replace(\" bags\", \"\");\n\n str1 = str1.replace(\" bag\", \"\");\n\n str1 = str1.replace(\".\", \"\");\n\n let mut split2: Vec<&str> = str1.split(\", \").collect();\n\n split2.retain(|&x| x != \"no other\");\n\n\n\n let mut vec = Vec::new();\n\n\n\n for part in split2 {\n\n let (num, color) = part.split_at(1);\n\n let num = num.parse::<usize>().unwrap();\n\n vec.push((color.trim().to_string(), num));\n\n }\n\n\n\n ret.insert(container, vec);\n\n }\n\n\n\n ret\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 3, "score": 128171.89419457242 }, { "content": "fn count_bags2(map: &HashMap<&str, Vec<(String, usize)>>, color: &str) -> usize {\n\n let mut count = 0;\n\n\n\n for (&k, v) in map {\n\n if k == color {\n\n for entry in v {\n\n count += entry.1 + entry.1 * count_bags2(map, entry.0.as_str());\n\n }\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 4, "score": 125633.02380636302 }, { "content": "fn part1(inputs: &[String], bag_name: &str) -> usize {\n\n let map = tokenize(inputs);\n\n\n\n let mut bag_list = vec![];\n\n count_bags1(&map, bag_name, &mut bag_list);\n\n\n\n bag_list.sort_unstable();\n\n bag_list.dedup();\n\n bag_list.len()\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 5, "score": 123695.47853612757 }, { "content": "fn part2(inputs: &[String], bag_name: &str) -> usize {\n\n let map = tokenize(inputs);\n\n\n\n count_bags2(&map, bag_name)\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 6, "score": 123695.47853612757 }, { "content": "fn count_bags1(map: &HashMap<&str, Vec<(String, usize)>>, color: &str, bag_list: &mut Vec<String>) {\n\n for (&k, v) in map {\n\n for entry in v {\n\n if entry.0 == color {\n\n bag_list.push(k.to_string());\n\n count_bags1(map, k, bag_list);\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 7, "score": 119436.3918650273 }, { "content": "fn validate_passport_string1(pass_str: &str) -> bool {\n\n pass_str.contains(\"byr:\")\n\n && pass_str.contains(\"iyr:\")\n\n && pass_str.contains(\"eyr:\")\n\n && pass_str.contains(\"hgt:\")\n\n && pass_str.contains(\"hcl:\")\n\n && pass_str.contains(\"ecl:\")\n\n && pass_str.contains(\"pid:\")\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 8, "score": 98378.63989599617 }, { "content": "fn validate_passport_string2(pass_str: &str) -> bool {\n\n let keys: Vec<&str> = pass_str.split(' ').collect();\n\n\n\n validate_key(&keys, \"byr:\", &|s| match s[4..].parse::<i32>() {\n\n Ok(num) => (1920..=2002).contains(&num),\n\n _ => false,\n\n }) && validate_key(&keys, \"iyr:\", &|s| match s[4..].parse::<i32>() {\n\n Ok(num) => (2010..=2020).contains(&num),\n\n _ => false,\n\n }) && validate_key(&keys, \"eyr:\", &|s| match s[4..].parse::<i32>() {\n\n Ok(num) => (2020..=2030).contains(&num),\n\n _ => false,\n\n }) && validate_key(&keys, \"hgt:\", &|s| {\n\n let hgt_str = &s[4..];\n\n\n\n match hgt_str.find(\"cm\") {\n\n Some(idx2) => match hgt_str[..idx2].parse::<i32>() {\n\n Ok(hgt) => (150..=193).contains(&hgt),\n\n _ => false,\n\n },\n", "file_path": "day-4/src/main.rs", "rank": 9, "score": 98378.63989599617 }, { "content": "fn part2(inputs: &[String]) -> usize {\n\n let mut str_buf = String::new();\n\n let mut count = 0;\n\n let mut group_sz = 0;\n\n\n\n for line in inputs {\n\n if line.is_empty() {\n\n for c in 'a'..='z' {\n\n if str_buf.matches(c).count() == group_sz {\n\n count += 1;\n\n }\n\n }\n\n\n\n str_buf.clear();\n\n group_sz = 0;\n\n continue;\n\n }\n\n\n\n str_buf.push_str(line);\n\n group_sz += 1;\n", "file_path": "day-6/src/main.rs", "rank": 10, "score": 96092.35416751365 }, { "content": "fn part1(inputs: &[String]) -> usize {\n\n let mut str_buf = String::new();\n\n let mut count = 0;\n\n let mut char_vec: Vec<char> = vec![];\n\n char_vec.reserve(26);\n\n\n\n for line in inputs {\n\n if line.is_empty() {\n\n char_vec = str_buf.chars().collect();\n\n char_vec.sort_unstable();\n\n char_vec.dedup();\n\n\n\n count += char_vec.len();\n\n str_buf.clear();\n\n continue;\n\n }\n\n\n\n str_buf.push_str(line);\n\n }\n\n\n\n char_vec = str_buf.chars().collect();\n\n char_vec.sort_unstable();\n\n char_vec.dedup();\n\n\n\n count + char_vec.len()\n\n}\n\n\n", "file_path": "day-6/src/main.rs", "rank": 11, "score": 96092.35416751365 }, { "content": "/// Opens a file and returns a vector containing the representation of each line of the file,\n\n/// also separating based on a delimiter string\n\n///\n\n/// # Errors\n\n///\n\n/// This function will return an error if:\n\n///\n\n/// * The path provided does not exist or is inaccessible\n\n/// * The data can not be parsed into type `T`\n\npub fn get_input_delim<T>(path: &str, delim: &str) -> Result<Vec<T>, io::Error>\n\nwhere\n\n T: std::str::FromStr,\n\n <T as std::str::FromStr>::Err: std::fmt::Debug,\n\n{\n\n let f = File::open(path)?;\n\n let file_reader = BufReader::new(f);\n\n let mut vals: Vec<T> = vec![];\n\n\n\n for line in file_reader.lines() {\n\n for val_str in line?.split(delim) {\n\n let val = match val_str.trim().parse() {\n\n Ok(itm) => itm,\n\n Err(_) => {\n\n return Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"Could parse data for type specified!\",\n\n ))\n\n }\n\n };\n\n\n\n vals.push(val);\n\n }\n\n }\n\n\n\n Ok(vals)\n\n}\n", "file_path": "inputs/src/lib.rs", "rank": 12, "score": 95582.6846426667 }, { "content": "fn validate2(rule: &PassWordRule, in_str: &str) -> bool {\n\n (in_str.chars().nth(rule.n1 - 1).unwrap() == rule.character)\n\n ^ (in_str.chars().nth(rule.n2 - 1).unwrap() == rule.character)\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 13, "score": 92372.53782778286 }, { "content": "fn validate1(rule: &PassWordRule, in_str: &str) -> bool {\n\n let mut count = 0;\n\n\n\n for c in in_str.chars() {\n\n if c == rule.character {\n\n count += 1;\n\n }\n\n }\n\n\n\n count <= rule.n2 && count >= rule.n1\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 14, "score": 92372.53782778286 }, { "content": "/// Opens a file and returns a vector containing the representation of each line of the file\n\n///\n\n/// # Errors\n\n///\n\n/// This function will return an error if:\n\n///\n\n/// * The path provided does not exist or is inaccessible\n\n/// * The data can not be parsed into type `T`\n\npub fn get_input<T>(path: &str) -> Result<Vec<T>, io::Error>\n\nwhere\n\n T: std::str::FromStr,\n\n <T as std::str::FromStr>::Err: std::fmt::Debug,\n\n{\n\n let f = File::open(path)?;\n\n\n\n let file_reader = BufReader::new(f);\n\n let mut vals: Vec<T> = vec![];\n\n\n\n for line in file_reader.lines() {\n\n let val = match line?.trim().parse() {\n\n Ok(itm) => itm,\n\n Err(_) => {\n\n return Err(io::Error::new(\n\n io::ErrorKind::InvalidData,\n\n \"Could parse data for type specified!\",\n\n ))\n\n }\n\n };\n\n\n\n vals.push(val);\n\n }\n\n\n\n Ok(vals)\n\n}\n\n\n", "file_path": "inputs/src/lib.rs", "rank": 15, "score": 88693.56226917871 }, { "content": "fn validate_key(list: &[&str], key: &str, f: &dyn Fn(&&str) -> bool) -> bool {\n\n match list.iter().find(|&&s| s.starts_with(key)) {\n\n Some(s) => f(s),\n\n None => false,\n\n }\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 16, "score": 88311.87106926666 }, { "content": "fn check_slope(inputs: &[String], right: usize, down: usize) -> u64 {\n\n let num_col = inputs[0].len();\n\n let mut cur_col = 0;\n\n let mut cur_row = 0;\n\n let mut tree_count = 0;\n\n\n\n for row in inputs {\n\n if cur_row % down != 0 {\n\n cur_row += 1;\n\n continue;\n\n }\n\n\n\n if row.chars().nth(cur_col % num_col).unwrap() == '#' {\n\n tree_count += 1;\n\n }\n\n\n\n cur_row += 1;\n\n cur_col += right;\n\n }\n\n\n\n tree_count\n\n}\n\n\n", "file_path": "day-3/src/main.rs", "rank": 17, "score": 88197.4175778952 }, { "content": "struct PassWordRule {\n\n character: char,\n\n n1: usize,\n\n n2: usize,\n\n}\n\n\n\nimpl PassWordRule {\n\n fn parse(in_str: &str) -> (Self, &str) {\n\n let chunks: Vec<&str> = in_str.split(' ').collect();\n\n let reps: Vec<&str> = chunks[0].split('-').collect();\n\n\n\n (\n\n Self {\n\n character: chunks[1].chars().next().unwrap(),\n\n n1: reps[0].parse::<usize>().unwrap(),\n\n n2: reps[1].parse::<usize>().unwrap(),\n\n },\n\n chunks[2],\n\n )\n\n }\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 18, "score": 75891.75628338815 }, { "content": "fn part2(inputs: &[String]) -> i64 {\n\n // TODO: Find a more algorithmic way to solve this\n\n part2_naive(inputs)\n\n}\n\n\n", "file_path": "day-13/src/main.rs", "rank": 19, "score": 73091.57797458935 }, { "content": "fn part1(list: &[String]) -> u64 {\n\n let mut count = 0;\n\n\n\n for line in list {\n\n let (rule, passwd) = PassWordRule::parse(line);\n\n if validate1(&rule, passwd) {\n\n count += 1;\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 20, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> u64 {\n\n check_slope(inputs, 3, 1)\n\n}\n\n\n", "file_path": "day-3/src/main.rs", "rank": 21, "score": 73091.57797458935 }, { "content": "fn part2(list: &[String]) -> u64 {\n\n let mut count = 0;\n\n\n\n for line in list {\n\n let (rule, passwd) = PassWordRule::parse(line);\n\n if validate2(&rule, passwd) {\n\n count += 1;\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 22, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> u64 {\n\n let mut str_buf = String::new();\n\n let mut valid_count = 0;\n\n\n\n for line in inputs {\n\n if line.is_empty() {\n\n if validate_passport_string1(&str_buf) {\n\n valid_count += 1;\n\n }\n\n\n\n str_buf.clear();\n\n continue;\n\n }\n\n\n\n str_buf.push_str(line);\n\n str_buf.push(' ');\n\n }\n\n\n\n // One more time assuming there is no final empty line\n\n if validate_passport_string1(&str_buf) {\n\n valid_count += 1;\n\n }\n\n\n\n valid_count\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 23, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> i32 {\n\n let timestamp: i32 = inputs[0].parse().expect(\"Error parsing timestamp!\");\n\n let mut min_diff: i32 = std::i32::MAX;\n\n let mut next_bus = 0;\n\n\n\n for input in &inputs[1..] {\n\n if input == \"x\" {\n\n continue;\n\n }\n\n\n\n let bus_num: i32 = input.parse().expect(\"Error parsing bus number!\");\n\n\n\n let diff = if (timestamp % bus_num) == 0 {\n\n 0\n\n } else {\n\n bus_num - (timestamp % bus_num)\n\n };\n\n\n\n if diff < min_diff {\n\n min_diff = diff;\n\n next_bus = bus_num;\n\n }\n\n }\n\n\n\n min_diff * next_bus\n\n}\n\n\n", "file_path": "day-13/src/main.rs", "rank": 24, "score": 73091.57797458935 }, { "content": "fn part2(inputs: &[String]) -> i32 {\n\n let mut ship = Ship::new(Direction::East);\n\n let mut waypoint = Position { x: 10, y: 1 };\n\n\n\n for input in inputs {\n\n let amount: i32 = input[1..]\n\n .parse()\n\n .expect(\"Error parsing instruction as i32!\");\n\n\n\n match input.chars().next().unwrap() {\n\n 'F' => {\n\n ship.translate(Direction::North, waypoint.y * amount);\n\n ship.translate(Direction::East, waypoint.x * amount);\n\n }\n\n 'L' => rotate_waypoint(&mut waypoint, Rotation::Left, amount),\n\n 'R' => rotate_waypoint(&mut waypoint, Rotation::Right, amount),\n\n 'N' => waypoint.y += amount,\n\n 'E' => waypoint.x += amount,\n\n 'S' => waypoint.y -= amount,\n\n 'W' => waypoint.x -= amount,\n\n _ => panic!(\"Invalid instruction character!\"),\n\n }\n\n }\n\n\n\n ship.position.manhattan_distance()\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 25, "score": 73091.57797458935 }, { "content": "fn part2(inputs: &[String]) -> u64 {\n\n check_slope(inputs, 1, 1)\n\n * check_slope(inputs, 3, 1)\n\n * check_slope(inputs, 5, 1)\n\n * check_slope(inputs, 7, 1)\n\n * check_slope(inputs, 1, 2)\n\n}\n\n\n", "file_path": "day-3/src/main.rs", "rank": 26, "score": 73091.57797458935 }, { "content": "fn part2(inputs: &[String]) -> i32 {\n\n let mut seats = Seat::parse_grid(inputs);\n\n let mut changes: Vec<(usize, usize)> = vec![];\n\n\n\n loop {\n\n changes.clear();\n\n\n\n for i in 0..seats.len() {\n\n for j in 0..seats[i].len() {\n\n match seats[i][j] {\n\n Seat::None => continue,\n\n Seat::Empty => {\n\n if check_los((i, j), &seats) == 0 {\n\n changes.push((i, j));\n\n }\n\n }\n\n\n\n Seat::Occupied => {\n\n if check_los((i, j), &seats) >= 5 {\n\n changes.push((i, j));\n", "file_path": "day-11/src/main.rs", "rank": 27, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> i32 {\n\n let mut ship = Ship::new(Direction::East);\n\n\n\n for input in inputs {\n\n let amount: i32 = input[1..]\n\n .parse()\n\n .expect(\"Error parsing instruction as i32!\");\n\n\n\n match input.chars().next().unwrap() {\n\n 'F' => ship.go_forward(amount),\n\n 'L' => ship.rotate(Rotation::Left, amount),\n\n 'R' => ship.rotate(Rotation::Right, amount),\n\n 'N' => ship.translate(Direction::North, amount),\n\n 'E' => ship.translate(Direction::East, amount),\n\n 'S' => ship.translate(Direction::South, amount),\n\n 'W' => ship.translate(Direction::West, amount),\n\n _ => panic!(\"Invalid instruction character!\"),\n\n }\n\n }\n\n\n\n ship.position.manhattan_distance()\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 28, "score": 73091.57797458935 }, { "content": "fn part2(inputs: &[String]) -> u64 {\n\n let mut str_buf = String::new();\n\n let mut valid_count = 0;\n\n\n\n for line in inputs {\n\n if line.is_empty() {\n\n if validate_passport_string2(&str_buf) {\n\n valid_count += 1;\n\n }\n\n\n\n str_buf.clear();\n\n continue;\n\n }\n\n\n\n str_buf.push_str(line);\n\n str_buf.push(' ');\n\n }\n\n\n\n // One more time assuming there is no final empty line\n\n if validate_passport_string2(&str_buf) {\n\n valid_count += 1;\n\n }\n\n\n\n valid_count\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 29, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> i32 {\n\n let mut seats = Seat::parse_grid(inputs);\n\n let mut changes: Vec<(usize, usize)> = vec![];\n\n\n\n loop {\n\n changes.clear();\n\n\n\n for i in 0..seats.len() {\n\n for j in 0..seats[i].len() {\n\n match seats[i][j] {\n\n Seat::None => continue,\n\n Seat::Empty => {\n\n if check_neighbors((i, j), &seats) == 0 {\n\n changes.push((i, j));\n\n }\n\n }\n\n\n\n Seat::Occupied => {\n\n if check_neighbors((i, j), &seats) >= 4 {\n\n changes.push((i, j));\n", "file_path": "day-11/src/main.rs", "rank": 30, "score": 73091.57797458935 }, { "content": "fn part2(inputs: &[String]) -> i32 {\n\n let mut id_list: Vec<i32> = vec![];\n\n id_list.reserve_exact(inputs.len());\n\n\n\n for input in inputs {\n\n id_list.push(calc_seat_id(input));\n\n }\n\n\n\n let min_id = *id_list.iter().min().unwrap();\n\n let max_id = *id_list.iter().max().unwrap();\n\n\n\n for x in min_id..max_id {\n\n if !id_list.contains(&x) {\n\n return x;\n\n }\n\n }\n\n\n\n panic!(\"Could not find a missing seat!\");\n\n}\n\n\n", "file_path": "day-5/src/main.rs", "rank": 31, "score": 73091.57797458935 }, { "content": "fn part1(inputs: &[String]) -> i32 {\n\n let mut max_id = i32::MIN;\n\n\n\n for input in inputs {\n\n let result = calc_seat_id(input);\n\n\n\n if result > max_id {\n\n max_id = result;\n\n }\n\n }\n\n\n\n max_id\n\n}\n\n\n", "file_path": "day-5/src/main.rs", "rank": 32, "score": 73091.57797458935 }, { "content": "fn part2_naive(inputs: &[String]) -> i64 {\n\n let mut offset: i64 = 0;\n\n let mut vec = Vec::new();\n\n\n\n for input in &inputs[1..] {\n\n if input == \"x\" {\n\n offset += 1;\n\n continue;\n\n }\n\n\n\n let bus_num: i64 = input.parse().expect(\"Error parsing bus number!\");\n\n vec.push(SieveInput {\n\n modulo: bus_num,\n\n offset,\n\n });\n\n\n\n offset += 1;\n\n }\n\n\n\n // TODO: Try using a bezout identity to calculate (https://www.wikiwand.com/en/Chinese_remainder_theorem#/Using_the_existence_construction)\n\n\n\n 0\n\n}\n\n\n", "file_path": "day-13/src/main.rs", "rank": 33, "score": 71482.01990781547 }, { "content": "fn calc_seat_id(input: &str) -> i32 {\n\n struct MinMax {\n\n min: i32,\n\n max: i32,\n\n }\n\n\n\n impl MinMax {\n\n const fn range(&self) -> i32 {\n\n self.max - self.min\n\n }\n\n\n\n fn bisect_low(&mut self) {\n\n self.max -= (self.range() + 1) / 2;\n\n }\n\n\n\n fn bisect_high(&mut self) {\n\n self.min += (self.range() + 1) / 2;\n\n }\n\n }\n\n\n", "file_path": "day-5/src/main.rs", "rank": 34, "score": 71003.29760530691 }, { "content": "fn check_los((y, x): (usize, usize), seats: &[Vec<Seat>]) -> i32 {\n\n let mut count = 0;\n\n\n\n let mut current_y = y;\n\n\n\n // Look North\n\n loop {\n\n if current_y == 0 {\n\n break;\n\n }\n\n\n\n current_y -= 1;\n\n\n\n match seats[current_y][x] {\n\n Seat::Occupied => {\n\n count += 1;\n\n break;\n\n }\n\n Seat::Empty => {\n\n break;\n", "file_path": "day-11/src/main.rs", "rank": 35, "score": 68754.74969494168 }, { "content": "fn part2(inputs: &[u64]) -> Result<u64, &str> {\n\n let calculated: Vec<u64> = inputs.iter().map(|i| 2020 - i).collect();\n\n\n\n for num in inputs {\n\n for num2 in inputs {\n\n if num == num2 {\n\n continue;\n\n }\n\n\n\n if calculated.iter().any(|&i| i == num + num2) {\n\n return Ok(num * num2 * (2020 - num - num2));\n\n }\n\n }\n\n }\n\n\n\n Err(\"Could not find match in inputs!\")\n\n}\n\n\n", "file_path": "day-1/src/main.rs", "rank": 36, "score": 67000.2158505497 }, { "content": "fn part1(inputs: &[u64]) -> Result<u64, &str> {\n\n let calculated: Vec<u64> = inputs.iter().map(|i| 2020 - i).collect();\n\n\n\n for num in inputs {\n\n if calculated.iter().any(|i| i == num) {\n\n return Ok(num * (2020 - num));\n\n }\n\n }\n\n\n\n Err(\"Could not find match in inputs!\")\n\n}\n\n\n", "file_path": "day-1/src/main.rs", "rank": 37, "score": 67000.2158505497 }, { "content": "#[derive(Clone, Copy)]\n\nenum Rotation {\n\n Left,\n\n Right,\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 38, "score": 53963.81893127762 }, { "content": "#[derive(Clone, Copy)]\n\nenum Direction {\n\n North,\n\n East,\n\n South,\n\n West,\n\n}\n\n\n\nimpl Direction {\n\n fn rotate(&mut self, rotation: Rotation, degrees: i32) {\n\n let conv_rotation = match rotation {\n\n Rotation::Left => 4 - ((degrees / 90) % 4),\n\n Rotation::Right => (degrees / 90) % 4,\n\n };\n\n\n\n let direction_discriminant = (*self as i32 + conv_rotation) % 4;\n\n\n\n *self = match direction_discriminant {\n\n 0 => Self::North,\n\n 1 => Self::East,\n\n 2 => Self::South,\n\n 3 => Self::West,\n\n _ => panic!(\"Impossible number given!\"),\n\n };\n\n }\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 39, "score": 53963.81893127762 }, { "content": "enum Seat {\n\n None,\n\n Empty,\n\n Occupied,\n\n}\n\n\n\nimpl Clone for Seat {\n\n fn clone(&self) -> Self {\n\n match self {\n\n Self::None => Self::None,\n\n Self::Empty => Self::Empty,\n\n Self::Occupied => Self::Occupied,\n\n }\n\n }\n\n}\n\n\n\nimpl Seat {\n\n fn parse(c: char) -> Self {\n\n match c {\n\n '.' => Self::None,\n", "file_path": "day-11/src/main.rs", "rank": 40, "score": 53961.26174227205 }, { "content": "#[derive(Clone, Copy)]\n\nstruct Position {\n\n x: i32,\n\n y: i32,\n\n}\n\n\n\nimpl Position {\n\n const fn manhattan_distance(self) -> i32 {\n\n self.x.abs() + self.y.abs()\n\n }\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 41, "score": 53829.64420992364 }, { "content": "struct Ship {\n\n position: Position,\n\n direction: Direction,\n\n}\n\n\n\nimpl Ship {\n\n const fn new(dir: Direction) -> Self {\n\n Self {\n\n position: Position { x: 0, y: 0 },\n\n direction: dir,\n\n }\n\n }\n\n\n\n fn translate(&mut self, dir: Direction, distance: i32) {\n\n match dir {\n\n Direction::North => self.position.y += distance,\n\n Direction::South => self.position.y -= distance,\n\n Direction::East => self.position.x += distance,\n\n Direction::West => self.position.x -= distance,\n\n };\n", "file_path": "day-12/src/main.rs", "rank": 42, "score": 53827.087020918065 }, { "content": "fn part2(inputs: &[i32]) -> usize {\n\n let mut vec = inputs.to_vec();\n\n let max_val = inputs.iter().max().unwrap() + 3;\n\n vec.push(max_val);\n\n vec.sort_unstable();\n\n\n\n let mut map = BTreeMap::new();\n\n map.insert(0, 1);\n\n\n\n for num in vec {\n\n map.insert(num, 0);\n\n\n\n if map.contains_key(&(num - 1)) {\n\n map.insert(num, map[&num] + map[&(num - 1)]);\n\n }\n\n\n\n if map.contains_key(&(num - 2)) {\n\n map.insert(num, map[&num] + map[&(num - 2)]);\n\n }\n\n\n\n if map.contains_key(&(num - 3)) {\n\n map.insert(num, map[&num] + map[&(num - 3)]);\n\n }\n\n }\n\n\n\n map[&max_val]\n\n}\n\n\n", "file_path": "day-10/src/main.rs", "rank": 43, "score": 53613.87077539408 }, { "content": "struct SieveInput {\n\n modulo: i64,\n\n offset: i64,\n\n}\n\n\n", "file_path": "day-13/src/main.rs", "rank": 44, "score": 52667.58481035533 }, { "content": "fn check_neighbors(current: (usize, usize), seats: &[Vec<Seat>]) -> i32 {\n\n let mut count = 0;\n\n\n\n if current.0 != 0 && matches!(seats[current.0 - 1][current.1], Seat::Occupied) {\n\n count += 1;\n\n }\n\n\n\n if current.1 != 0 && matches!(seats[current.0][current.1 - 1], Seat::Occupied) {\n\n count += 1;\n\n }\n\n\n\n if current.0 != seats.len() - 1 && matches!(seats[current.0 + 1][current.1], Seat::Occupied) {\n\n count += 1;\n\n }\n\n\n\n if current.1 != seats[current.0].len() - 1\n\n && matches!(seats[current.0][current.1 + 1], Seat::Occupied)\n\n {\n\n count += 1;\n\n }\n", "file_path": "day-11/src/main.rs", "rank": 45, "score": 52056.80957505091 }, { "content": "fn check_index(index: usize, inputs: &[u64]) -> bool {\n\n for &num in &inputs[(index - PREAMBLE_SZ)..index] {\n\n for &num2 in &inputs[(index - PREAMBLE_SZ)..index] {\n\n if num == num2 {\n\n continue;\n\n }\n\n\n\n if num + num2 == inputs[index] {\n\n return true;\n\n }\n\n }\n\n }\n\n\n\n false\n\n}\n\n\n", "file_path": "day-9/src/main.rs", "rank": 46, "score": 47651.228358964196 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-6.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&inputs), 6947);\n\n assert_eq!(part2(&inputs), 3398);\n\n}\n", "file_path": "day-6/src/main.rs", "rank": 47, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-5.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&inputs), 871);\n\n assert_eq!(part2(&inputs), 640);\n\n}\n", "file_path": "day-5/src/main.rs", "rank": 49, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-12.txt\").expect(\"Could not parse path!\");\n\n assert_eq!(part1(&inputs), 1_457);\n\n assert_eq!(part2(&inputs), 106_860);\n\n}\n", "file_path": "day-12/src/main.rs", "rank": 50, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-4.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&inputs), 250);\n\n assert_eq!(part2(&inputs), 158);\n\n}\n", "file_path": "day-4/src/main.rs", "rank": 51, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let input_lines = get_input::<String>(\"../inputs/day-2.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&input_lines), 582);\n\n assert_eq!(part2(&input_lines), 729);\n\n}\n", "file_path": "day-2/src/main.rs", "rank": 52, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<u64>(\"inputs/day-9.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {:?}\", part1(&inputs));\n\n println!(\"Part 2 solution: {:?}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-9/src/main.rs", "rank": 53, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<u64>(\"../inputs/day-9.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&inputs), Some(41_682_220));\n\n assert_eq!(part2(&inputs), Some(5_388_976));\n\n}\n", "file_path": "day-9/src/main.rs", "rank": 54, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-4.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 55, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-7.txt\").expect(\"Could not parse path!\");\n\n assert_eq!(part1(&inputs, \"shiny gold\"), 300);\n\n assert_eq!(part2(&inputs, \"shiny gold\"), 8030);\n\n}\n", "file_path": "day-7/src/main.rs", "rank": 56, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-11.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-11/src/main.rs", "rank": 57, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<i32>(\"inputs/day-10.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-10/src/main.rs", "rank": 58, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-6.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-6/src/main.rs", "rank": 59, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let numbers = get_input::<u64>(\"../inputs/day-1.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&numbers).unwrap(), 290_784);\n\n assert_eq!(part2(&numbers).unwrap(), 177_337_980);\n\n}\n", "file_path": "day-1/src/main.rs", "rank": 60, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-11.txt\").expect(\"Could not parse path!\");\n\n assert_eq!(part1(&inputs), 2494);\n\n assert_eq!(part2(&inputs), 2306);\n\n}\n", "file_path": "day-11/src/main.rs", "rank": 61, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-5.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-5/src/main.rs", "rank": 62, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-12.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 64, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<i32>(\"../inputs/day-10.txt\").expect(\"Could not parse path!\");\n\n assert_eq!(part1(&inputs), 2_482);\n\n assert_eq!(part2(&inputs), 96_717_311_574_016);\n\n}\n", "file_path": "day-10/src/main.rs", "rank": 65, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs =\n\n get_input_delim::<String>(\"../inputs/day-13.txt\", \",\").expect(\"Could not parse path!\");\n\n\n\n // TODO: Re-enable tests once complete!\n\n //assert_eq!(part1(&inputs), 2_045);\n\n //assert_eq!(part2(&inputs), 1_068_788);\n\n}\n", "file_path": "day-13/src/main.rs", "rank": 66, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let input_lines = get_input::<String>(\"inputs/day-2.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&input_lines));\n\n println!(\"Part 2 solution: {}\", part2(&input_lines));\n\n}\n\n\n", "file_path": "day-2/src/main.rs", "rank": 67, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs =\n\n get_input_delim::<String>(\"inputs/day-13.txt\", \",\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-13/src/main.rs", "rank": 68, "score": 36349.51705136788 }, { "content": "#[test]\n\nfn check() {\n\n let inputs = get_input::<String>(\"../inputs/day-3.txt\").expect(\"Could not parse path!\");\n\n\n\n assert_eq!(part1(&inputs), 289);\n\n assert_eq!(part2(&inputs), 5_522_401_584);\n\n}\n", "file_path": "day-3/src/main.rs", "rank": 69, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-3.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs));\n\n println!(\"Part 2 solution: {}\", part2(&inputs));\n\n}\n\n\n", "file_path": "day-3/src/main.rs", "rank": 70, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let numbers = get_input::<u64>(\"inputs/day-1.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {:?}\", part1(&numbers));\n\n println!(\"Part 1 solution: {:?}\", part2(&numbers));\n\n}\n\n\n", "file_path": "day-1/src/main.rs", "rank": 71, "score": 36349.51705136788 }, { "content": "fn main() {\n\n let inputs = get_input::<String>(\"inputs/day-7.txt\").expect(\"Could not parse path!\");\n\n\n\n println!(\"Part 1 solution: {}\", part1(&inputs, \"shiny gold\"));\n\n println!(\"Part 2 solution: {}\", part2(&inputs, \"shiny gold\"));\n\n}\n\n\n", "file_path": "day-7/src/main.rs", "rank": 72, "score": 36349.51705136788 }, { "content": "fn part1(inputs: &[i32]) -> i32 {\n\n let mut vec: Vec<i32> = inputs.to_vec();\n\n vec.sort_unstable();\n\n\n\n let mut diffs = (0, 0, 1);\n\n let mut last = 0;\n\n\n\n for num in vec {\n\n match num - last {\n\n 1 => diffs.0 += 1,\n\n 2 => diffs.1 += 1,\n\n 3 => diffs.2 += 1,\n\n _ => panic!(\"Gap exceeded 3 jolts!\"),\n\n }\n\n\n\n last = num;\n\n }\n\n\n\n diffs.0 * diffs.2\n\n}\n\n\n", "file_path": "day-10/src/main.rs", "rank": 73, "score": 30613.094582469777 }, { "content": "fn part1(inputs: &[u64]) -> Option<u64> {\n\n for index in PREAMBLE_SZ..=inputs.len() - PREAMBLE_SZ {\n\n if !check_index(index, inputs) {\n\n return Some(inputs[index]);\n\n }\n\n }\n\n\n\n eprintln!(\"Value not found!\");\n\n None\n\n}\n\n\n", "file_path": "day-9/src/main.rs", "rank": 74, "score": 29112.122146714908 }, { "content": "fn part2(inputs: &[u64]) -> Option<u64> {\n\n for index in PREAMBLE_SZ..=inputs.len() - PREAMBLE_SZ {\n\n if !check_index(index, inputs) {\n\n let val = inputs[index];\n\n\n\n for idx in 0..inputs.len() {\n\n let mut idx2 = idx;\n\n let mut sum = 0;\n\n\n\n while sum < val {\n\n sum += inputs[idx2];\n\n idx2 += 1;\n\n }\n\n\n\n if sum == val {\n\n return Some(\n\n inputs[idx..idx2].iter().max().unwrap()\n\n + inputs[idx..idx2].iter().min().unwrap(),\n\n );\n\n }\n\n }\n\n }\n\n }\n\n\n\n eprintln!(\"Value not found!\");\n\n None\n\n}\n\n\n", "file_path": "day-9/src/main.rs", "rank": 75, "score": 29112.122146714908 }, { "content": "fn rotate_waypoint(waypoint: &mut Position, rotation: Rotation, degrees: i32) {\n\n let conv_rotation = match rotation {\n\n Rotation::Left => 4 - ((degrees / 90) % 4),\n\n Rotation::Right => (degrees / 90) % 4,\n\n };\n\n\n\n match conv_rotation {\n\n 0 => (),\n\n 1 => {\n\n swap(&mut waypoint.x, &mut waypoint.y);\n\n waypoint.y *= -1;\n\n }\n\n 2 => {\n\n waypoint.x *= -1;\n\n waypoint.y *= -1;\n\n }\n\n 3 => {\n\n swap(&mut waypoint.x, &mut waypoint.y);\n\n waypoint.x *= -1;\n\n }\n\n _ => panic!(\"Invalid computation of rotation!\"),\n\n }\n\n}\n\n\n", "file_path": "day-12/src/main.rs", "rank": 76, "score": 24869.162190550494 }, { "content": "use inputs::get_input;\n\nuse std::collections::HashMap;\n\n\n", "file_path": "day-7/src/main.rs", "rank": 83, "score": 4.382898640696 }, { "content": "use std::collections::BTreeMap;\n\n\n\nuse inputs::get_input;\n\n\n", "file_path": "day-10/src/main.rs", "rank": 84, "score": 4.235960362490806 }, { "content": "use std::collections::BTreeMap;\n\n\n\nuse inputs::get_input_delim;\n\n\n", "file_path": "day-13/src/main.rs", "rank": 85, "score": 4.098871911252216 }, { "content": "use core::mem::swap;\n\nuse inputs::get_input;\n\n\n\n#[derive(Clone, Copy)]\n", "file_path": "day-12/src/main.rs", "rank": 86, "score": 4.0908299714263645 }, { "content": "use inputs::get_input;\n\n\n\nconst PREAMBLE_SZ: usize = 25;\n\n\n", "file_path": "day-9/src/main.rs", "rank": 87, "score": 4.082039061044599 }, { "content": " }\n\n\n\n for c in 'a'..='z' {\n\n if str_buf.matches(c).count() == group_sz {\n\n count += 1;\n\n }\n\n }\n\n\n\n count\n\n}\n\n\n", "file_path": "day-6/src/main.rs", "rank": 88, "score": 3.822575209802014 }, { "content": " 'L' => Self::Empty,\n\n '#' => Self::Occupied,\n\n _ => panic!(\"Invalid character parsed!\"),\n\n }\n\n }\n\n\n\n fn parse_row(s: &str) -> Vec<Self> {\n\n let mut vec = vec![];\n\n vec.reserve(s.len());\n\n\n\n for c in s.chars() {\n\n vec.push(Self::parse(c));\n\n }\n\n\n\n vec\n\n }\n\n\n\n fn parse_grid(grid: &[String]) -> Vec<Vec<Self>> {\n\n let mut vec = vec![];\n\n vec.reserve(grid.len());\n\n\n\n for s in grid {\n\n vec.push(Self::parse_row(s));\n\n }\n\n\n\n vec\n\n }\n\n}\n\n\n", "file_path": "day-11/src/main.rs", "rank": 89, "score": 3.7651736072388107 }, { "content": " None => match hgt_str.find(\"in\") {\n\n Some(idx2) => match hgt_str[..idx2].parse::<i32>() {\n\n Ok(hgt) => (59..=76).contains(&hgt),\n\n _ => false,\n\n },\n\n None => false,\n\n },\n\n }\n\n }) && validate_key(&keys, \"hcl:\", &|s| {\n\n let mut iter = s.chars().skip(4);\n\n\n\n iter.next().unwrap() == '#' && iter.all(|c| c.is_digit(16))\n\n }) && validate_key(&keys, \"ecl:\", &|s| {\n\n [\"amb\", \"blu\", \"brn\", \"gry\", \"grn\", \"hzl\", \"oth\"].contains(&&s[4..])\n\n }) && validate_key(&keys, \"pid:\", &|s| {\n\n s.len() == 13 && matches!(&s[4..].parse::<u64>(), Ok(_))\n\n })\n\n}\n\n\n", "file_path": "day-4/src/main.rs", "rank": 90, "score": 3.664723800116191 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-6/src/main.rs", "rank": 91, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-5/src/main.rs", "rank": 92, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-3/src/main.rs", "rank": 93, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-11/src/main.rs", "rank": 94, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-1/src/main.rs", "rank": 95, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-4/src/main.rs", "rank": 96, "score": 2.3110736289730056 }, { "content": "use inputs::get_input;\n\n\n", "file_path": "day-2/src/main.rs", "rank": 97, "score": 2.3110736289730056 }, { "content": "\n\n if current.0 != 0\n\n && current.1 != 0\n\n && matches!(seats[current.0 - 1][current.1 - 1], Seat::Occupied)\n\n {\n\n count += 1;\n\n }\n\n\n\n if current.0 != 0\n\n && current.1 != seats[current.0].len() - 1\n\n && matches!(seats[current.0 - 1][current.1 + 1], Seat::Occupied)\n\n {\n\n count += 1;\n\n }\n\n\n\n if current.0 != seats.len() - 1\n\n && current.1 != 0\n\n && matches!(seats[current.0 + 1][current.1 - 1], Seat::Occupied)\n\n {\n\n count += 1;\n", "file_path": "day-11/src/main.rs", "rank": 98, "score": 1.7980555078299132 }, { "content": "use std::fs::File;\n\nuse std::io::{self, BufRead, BufReader};\n\n\n\n/// Opens a file and returns a vector containing the representation of each line of the file\n\n///\n\n/// # Errors\n\n///\n\n/// This function will return an error if:\n\n///\n\n/// * The path provided does not exist or is inaccessible\n\n/// * The data can not be parsed into type `T`\n", "file_path": "inputs/src/lib.rs", "rank": 99, "score": 1.5116350366910942 } ]
Rust
src/game.rs
unixzii/game-of-life
21059c29140883e080ab4c5076a8d0f0a488d42e
use std::rc::Rc; use std::cell::{RefCell, RefMut}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::closure::Closure; use web_sys::{console, window}; use crate::ui; use crate::engine; struct UiResponder { state: State, } impl ui::Responder for UiResponder { fn on_mouse_down(&self, point: ui::Point) { js_log!("on_mouse_down: {:?}", point); let mut state_inner = self.state.get_inner(); state_inner.is_mouse_down = true; drop(state_inner); self.state.put_cell(point.x, point.y); } fn on_mouse_move(&self, point: ui::Point) { if !self.state.get_inner().is_mouse_down { return; } js_log!("on_mouse_move: {:?}", point); self.state.put_cell(point.x, point.y); } fn on_mouse_up(&self) { js_log!("on_mouse_up"); self.state.get_inner().is_mouse_down = false; } } pub struct Config { pub update_interval: i32, } pub struct State { inner: Rc<RefCell<StateInner>>, } struct StateInner { canvas: ui::Canvas, world: engine::World, config: Config, is_mouse_down: bool, timer_closure: Option<Box<dyn Drop>>, timer_id: i32, } impl State { pub fn new(canvas: ui::Canvas, world: engine::World, config: Config) -> State { let state = State { inner: Rc::new(RefCell::new(StateInner { canvas: canvas, world: world, config: config, is_mouse_down: false, timer_closure: None, timer_id: -1, })), }; let responder = Box::new(UiResponder { state: state.clone() }); state.get_inner().canvas.install_responder(responder); return state; } pub fn clone(&self) -> State { return State { inner: self.inner.clone(), }; } pub fn resume(&self) { let mut inner = self.get_inner(); if inner.timer_closure.is_some() { return; } let state_clone = self.clone(); let closure = Box::new(Closure::wrap(Box::new(move || { state_clone.tick(); }) as Box<dyn FnMut()>)); let timer_id = window().unwrap().set_interval_with_callback_and_timeout_and_arguments_0( closure.as_ref().as_ref().unchecked_ref(), inner.config.update_interval ).unwrap(); inner.timer_closure = Some(closure); inner.timer_id = timer_id; } pub fn pause(&self) { let mut inner = self.get_inner(); if inner.timer_closure.is_none() { return; } window().unwrap().clear_interval_with_handle(inner.timer_id); inner.timer_closure = None; inner.timer_id = -1; } fn put_cell(&self, x: i32, y: i32) { self.get_inner().world.set_cell(x, y, engine::Cell::Alive); self.update_canvas(); } fn tick(&self) { self.get_inner().world.next_gen(); self.update_canvas(); } fn update_canvas(&self) { let inner = self.get_inner(); inner.canvas.clear(); for col in 0..(inner.world.height()) { for row in 0..(inner.world.width()) { if inner.world.cell_at(row, col) == engine::Cell::Alive { inner.canvas.draw_cell(row, col); } } } } fn get_inner<'a>(&'a self) -> RefMut<'a, StateInner> { return self.inner.borrow_mut(); } } impl Drop for State { fn drop(&mut self) { self.pause(); } }
use std::rc::Rc; use std::cell::{RefCell, RefMut}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::closure::Closure; use web_sys::{console, window}; use crate::ui; use crate::engine; struct UiResponder { state: State, } impl ui::Responder for UiResponder { fn on_mouse_down(&self, point: ui::Point) { js_log!("on_mouse_down: {:?}", point); let mut state_inner = self.state.get_inner(); state_inner.is_mouse_down = true; drop(state_inner); self.state.put_cell(point.x, point.y); } fn on_mouse_move(&self, point: ui::Point) { if !self.state.get_inner().is_mouse_down { return; } js_log!("on_mouse_move: {:?}", point); self.state.put_cell(point.x, point.y); } fn on_mouse_up(&self) { js_log!("on_mouse_up"); self.state.get_inner().is_mouse_down = false; } } pub struct Config { pub update_interval: i32, } pub struct State { inner: Rc<RefCell<StateInner>>, } struct StateInner { canvas: ui::Canvas, world: engine::World, config: Config, is_mouse_down: bool, timer_closure: Option<Box<dyn Drop>>, timer_id: i32, } impl State { pub fn new(canvas: ui::Canvas, world: engine::World, config: Config) -> State { let state = State { inner: Rc::new(RefCell::new(StateInner { canvas: canvas, world: world, config: config, is_mouse_down: false, timer_closure: None, timer_id: -1, })), }; let responder = Box::new(UiResponder { state: state.clone() }); state.get_inner().canvas.install_responder(responder); return state; } pub fn clone(&self) -> State { return State { inner: self.inner.clone(), }; } pub fn resume(&self) { let mut inner = self.get_inner();
let timer_id = window().unwrap().set_interval_with_callback_and_timeout_and_arguments_0( closure.as_ref().as_ref().unchecked_ref(), inner.config.update_interval ).unwrap(); inner.timer_closure = Some(closure); inner.timer_id = timer_id; } pub fn pause(&self) { let mut inner = self.get_inner(); if inner.timer_closure.is_none() { return; } window().unwrap().clear_interval_with_handle(inner.timer_id); inner.timer_closure = None; inner.timer_id = -1; } fn put_cell(&self, x: i32, y: i32) { self.get_inner().world.set_cell(x, y, engine::Cell::Alive); self.update_canvas(); } fn tick(&self) { self.get_inner().world.next_gen(); self.update_canvas(); } fn update_canvas(&self) { let inner = self.get_inner(); inner.canvas.clear(); for col in 0..(inner.world.height()) { for row in 0..(inner.world.width()) { if inner.world.cell_at(row, col) == engine::Cell::Alive { inner.canvas.draw_cell(row, col); } } } } fn get_inner<'a>(&'a self) -> RefMut<'a, StateInner> { return self.inner.borrow_mut(); } } impl Drop for State { fn drop(&mut self) { self.pause(); } }
if inner.timer_closure.is_some() { return; } let state_clone = self.clone(); let closure = Box::new(Closure::wrap(Box::new(move || { state_clone.tick(); }) as Box<dyn FnMut()>));
random
[ { "content": "fn generate_initial_world(world: &mut engine::World) {\n\n for col in 0..(world.height()) {\n\n for row in 0..(world.width()) {\n\n if Math::random() < 0.3 {\n\n world.set_cell(row, col, engine::Cell::Alive);\n\n }\n\n }\n\n }\n\n}", "file_path": "src/lib.rs", "rank": 0, "score": 62270.6349009884 }, { "content": "#[wasm_bindgen]\n\npub fn start() {\n\n utils::set_panic_hook();\n\n\n\n let config = game::Config {\n\n update_interval: 60,\n\n };\n\n\n\n let rows = 100;\n\n let cols = 100;\n\n\n\n let window = web_sys::window().expect(\"There must be a window instance\");\n\n let document = window.document().expect(\"There must be a document instance\");\n\n let canvas = ui::Canvas::new(&document, rows, cols);\n\n\n\n let mut world = engine::World::new(rows, cols);\n\n generate_initial_world(&mut world);\n\n\n\n let state = game::State::new(canvas, world, config);\n\n state.resume();\n\n\n\n // TODO: We really should manage the memory correctly!\n\n mem::forget(state);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 46884.75884128888 }, { "content": "pub fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details see\n\n // https://github.com/rustwasm/console_error_panic_hook#readme\n\n #[cfg(feature = \"console_error_panic_hook\")]\n\n console_error_panic_hook::set_once();\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! js_log {\n\n ($($arg:tt)*) => {{\n\n let format_str = format!($($arg)*);\n\n console::log_1(&JsValue::from_str(format_str.as_str()));\n\n }}\n\n}\n", "file_path": "src/utils.rs", "rank": 3, "score": 43013.91447844838 }, { "content": "/// A wrapper of the [`Responder`] object.\n\nstruct ResponderHolder {\n\n responder: Option<Box<dyn Responder>>,\n\n}\n\n\n\nimpl ResponderHolder {\n\n fn on_mouse_down(&self, point: Point) {\n\n if let Some(responder) = self.responder.as_ref() {\n\n responder.on_mouse_down(point);\n\n }\n\n }\n\n\n\n fn on_mouse_move(&self, point: Point) {\n\n if let Some(responder) = self.responder.as_ref() {\n\n responder.on_mouse_move(point);\n\n }\n\n }\n\n\n\n fn on_mouse_up(&self) {\n\n if let Some(responder) = self.responder.as_ref() {\n\n responder.on_mouse_up();\n", "file_path": "src/ui.rs", "rank": 4, "score": 40957.37015022075 }, { "content": "/// Used to respond the events sent from the DOM element.\n\npub trait Responder {\n\n fn on_mouse_down(&self, point: Point);\n\n fn on_mouse_move(&self, point: Point);\n\n fn on_mouse_up(&self);\n\n}\n\n\n", "file_path": "src/ui.rs", "rank": 6, "score": 38868.95555304047 }, { "content": "#[wasm_bindgen_test]\n\nfn pass() {\n\n assert_eq!(1 + 1, 2);\n\n}\n", "file_path": "tests/web.rs", "rank": 7, "score": 26843.379241569088 }, { "content": "/// A storage with two buffers for arbitary type.\n\n/// \n\n/// This is useful for generating next generation world while referring to the\n\n/// current generation world, and make this process done without allocating\n\n/// new memory.\n\nstruct DoubleBuffer<T> {\n\n back: Option<T>,\n\n front: Option<T>,\n\n}\n\n\n\nimpl<T> DoubleBuffer<T> {\n\n /// Create a new instance with the given buffer factory.\n\n fn new<F>(mut f: F) -> DoubleBuffer<T>\n\n where F: FnMut() -> T {\n\n return DoubleBuffer {\n\n back: Some(f()),\n\n front: Some(f()),\n\n };\n\n }\n\n\n\n /// Swap the buffer.\n\n fn swap(&mut self) {\n\n let tmp = self.back.take().unwrap();\n\n self.back = self.front.take();\n\n self.front = Some(tmp);\n", "file_path": "src/engine.rs", "rank": 8, "score": 22297.50031476599 }, { "content": "use std::collections::LinkedList;\n\nuse std::rc::Rc;\n\nuse std::cell::RefCell;\n\n\n\nuse wasm_bindgen::{JsCast, JsValue};\n\nuse wasm_bindgen::closure::Closure;\n\nuse web_sys::{\n\n Document,\n\n HtmlCanvasElement,\n\n CanvasRenderingContext2d\n\n};\n\n\n\n/// A struct that represents a point of the world.\n\n#[derive(Debug)]\n\npub struct Point {\n\n pub x: i32,\n\n pub y: i32,\n\n}\n\n\n\n/// Used to respond the events sent from the DOM element.\n", "file_path": "src/ui.rs", "rank": 13, "score": 12.593652937105698 }, { "content": "\n\n // Install the event listeners.\n\n let responder_holder = Rc::new(RefCell::new(ResponderHolder {\n\n responder: None,\n\n }));\n\n let mut event_handlers: LinkedList<Box<dyn Drop>> = LinkedList::new();\n\n {\n\n let event_target: &web_sys::EventTarget = &canvas_el;\n\n // The mouse down event:\n\n {\n\n let responder_holder_clone = responder_holder.clone();\n\n let mouse_down_cb = \n\n Box::new(Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {\n\n let point = Point {\n\n x: (event.offset_x() as f64 / cell_width) as i32,\n\n y: (event.offset_y() as f64 / cell_height) as i32,\n\n };\n\n\n\n responder_holder_clone.borrow().on_mouse_down(point);\n\n }) as Box<dyn FnMut(_)>));\n", "file_path": "src/ui.rs", "rank": 14, "score": 11.447751235420322 }, { "content": " });\n\n\n\n return World {\n\n stride: width,\n\n cells: cells,\n\n };\n\n }\n\n\n\n pub fn width(&self) -> i32 {\n\n return self.stride;\n\n }\n\n\n\n pub fn height(&self) -> i32 {\n\n return (self.cells.front_ref().len() / (self.stride as usize)) as i32;\n\n }\n\n\n\n /// Modifies the cell at the given point.\n\n pub fn set_cell(&mut self, x: i32, y: i32, cell: Cell) {\n\n let index = self.index(x, y);\n\n self.cells.front_mut()[index] = cell;\n", "file_path": "src/engine.rs", "rank": 16, "score": 9.59067749223056 }, { "content": " }\n\n\n\n /// Returns a copy of the cell at the given point. \n\n pub fn cell_at(&self, x: i32, y: i32) -> Cell {\n\n let index = self.index(x, y);\n\n return self.cells.front_ref()[index];\n\n }\n\n\n\n /// Returns the count of neighbours of the cell at the given point.\n\n pub fn neighbour_count(&self, x: i32, y: i32) -> i32 {\n\n let dir = [-1, 0, 1];\n\n let mut count = 0;\n\n for x_dir in dir.iter() {\n\n for y_dir in dir.iter() {\n\n let dest_x = x + x_dir;\n\n let dest_y = y + y_dir;\n\n if dest_x < 0 || dest_y < 0 || (dest_x == x && dest_y == y) {\n\n continue;\n\n }\n\n\n", "file_path": "src/engine.rs", "rank": 17, "score": 9.501661107005411 }, { "content": " Alive,\n\n Dead,\n\n}\n\n\n\n/// The Game of Life world.\n\npub struct World {\n\n stride: i32,\n\n cells: DoubleBuffer<Vec<Cell>>,\n\n}\n\n\n\nimpl World {\n\n /// Create a new world with given size.\n\n pub fn new(width: i32, height: i32) -> World {\n\n let cells: DoubleBuffer<Vec<Cell>> = DoubleBuffer::new(|| {\n\n let length = (width * height) as usize; \n\n let mut vec = Vec::with_capacity(length);\n\n for _ in 0..length {\n\n vec.push(Cell::Dead);\n\n }\n\n return vec;\n", "file_path": "src/engine.rs", "rank": 18, "score": 8.927649772596514 }, { "content": " }\n\n }\n\n}\n\n\n\nconst DEFAULT_WIDTH: i32 = 500;\n\nconst DEFAULT_HEIGHT: i32 = 500;\n\n\n\n/// An object that acts as the controller of the canvas DOM elememnt.\n\n#[allow(dead_code)]\n\npub struct Canvas {\n\n el: HtmlCanvasElement,\n\n ctx: CanvasRenderingContext2d,\n\n responder_holder: Rc<RefCell<ResponderHolder>>,\n\n event_handlers: LinkedList<Box<dyn Drop>>,\n\n width: f64,\n\n height: f64,\n\n cell_width: f64,\n\n cell_height: f64,\n\n}\n\n\n", "file_path": "src/ui.rs", "rank": 19, "score": 8.71979737554783 }, { "content": " .unwrap() // Option<_>\n\n .dyn_into::<web_sys::CanvasRenderingContext2d>()\n\n .unwrap();\n\n return Canvas {\n\n el: canvas_el,\n\n ctx: context,\n\n responder_holder: responder_holder,\n\n event_handlers: event_handlers,\n\n width: width,\n\n height: height,\n\n cell_width: cell_width,\n\n cell_height: cell_height,\n\n };\n\n }\n\n\n\n pub fn install_responder(&mut self, responder: Box<dyn Responder>) {\n\n self.responder_holder.borrow_mut().responder = Some(responder);\n\n }\n\n\n\n pub fn clear(&self) {\n", "file_path": "src/ui.rs", "rank": 20, "score": 8.292476368801337 }, { "content": " event_target.add_event_listener_with_callback(\n\n \"mousedown\",\n\n mouse_down_cb.as_ref().as_ref().unchecked_ref()\n\n ).unwrap();\n\n event_handlers.push_back(mouse_down_cb);\n\n }\n\n\n\n // The mouse move event:\n\n {\n\n let responder_holder_clone = responder_holder.clone();\n\n let mouse_move_cb = \n\n Box::new(Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {\n\n let point = Point {\n\n x: (event.offset_x() as f64 / cell_width) as i32,\n\n y: (event.offset_y() as f64 / cell_height) as i32,\n\n };\n\n\n\n responder_holder_clone.borrow().on_mouse_move(point);\n\n }) as Box<dyn FnMut(_)>));\n\n event_target.add_event_listener_with_callback(\n", "file_path": "src/ui.rs", "rank": 21, "score": 7.475170600622351 }, { "content": "impl Canvas {\n\n /// Creates a new instance with the given [`web_sys::Document`] and world size.\n\n /// \n\n /// Calling this method has a side-effect that manipulate the DOM to initialize\n\n /// the canvas and related elements.\n\n pub fn new(document: &Document, rows: i32, cols: i32) -> Canvas {\n\n let width = DEFAULT_WIDTH as f64;\n\n let height = DEFAULT_HEIGHT as f64;\n\n let cell_width = width / (rows as f64);\n\n let cell_height = height / (cols as f64);\n\n\n\n let body = document.body().unwrap();\n\n \n\n let canvas_el = document.create_element(\"canvas\")\n\n .unwrap()\n\n .dyn_into::<web_sys::HtmlCanvasElement>()\n\n .unwrap();\n\n canvas_el.set_width(DEFAULT_WIDTH as u32);\n\n canvas_el.set_height(DEFAULT_HEIGHT as u32);\n\n body.prepend_with_node_1(&canvas_el).unwrap();\n", "file_path": "src/ui.rs", "rank": 23, "score": 6.933524917407249 }, { "content": " }\n\n\n\n /// Returns the mutable reference to the back buffer.\n\n fn back_mut(&mut self) -> &mut T {\n\n return self.back.as_mut().unwrap();\n\n }\n\n\n\n /// Returns the mutable reference to the front buffer.\n\n fn front_mut(&mut self) -> &mut T {\n\n return self.front.as_mut().unwrap();\n\n }\n\n\n\n /// Returns the reference to the front buffer.\n\n fn front_ref(&self) -> &T {\n\n return self.front.as_ref().unwrap();\n\n }\n\n}\n\n\n\n#[derive(PartialEq, Copy, Clone)]\n\npub enum Cell {\n", "file_path": "src/engine.rs", "rank": 24, "score": 6.3171416752734295 }, { "content": " }\n\n\n\n // Swap the buffer, make next generation cells current.\n\n self.cells.swap();\n\n }\n\n\n\n /// Returns the index of cell vector for the cell at the given point.\n\n fn index(&self, x: i32, y: i32) -> usize {\n\n return (self.stride * y + x) as usize;\n\n }\n\n}\n", "file_path": "src/engine.rs", "rank": 25, "score": 5.990454579417879 }, { "content": "use std::cmp::PartialEq;\n\n\n\n/// A storage with two buffers for arbitary type.\n\n/// \n\n/// This is useful for generating next generation world while referring to the\n\n/// current generation world, and make this process done without allocating\n\n/// new memory.\n", "file_path": "src/engine.rs", "rank": 26, "score": 4.518790958161989 }, { "content": " \"mousemove\",\n\n mouse_move_cb.as_ref().as_ref().unchecked_ref()\n\n ).unwrap();\n\n event_handlers.push_back(mouse_move_cb);\n\n }\n\n\n\n // The mouse up event:\n\n {\n\n let responder_holder_clone = responder_holder.clone();\n\n let mouse_up_cb = \n\n Box::new(Closure::wrap(Box::new(move || {\n\n responder_holder_clone.borrow().on_mouse_up();\n\n }) as Box<dyn FnMut()>));\n\n event_target.add_event_listener_with_callback(\n\n \"mouseup\",\n\n mouse_up_cb.as_ref().as_ref().unchecked_ref()\n\n ).unwrap();\n\n event_handlers.push_back(mouse_up_cb);\n\n }\n\n }\n", "file_path": "src/ui.rs", "rank": 27, "score": 4.342607635737172 }, { "content": "#![feature(exclusive_range_pattern)]\n\n\n\n#[macro_use]\n\nmod utils;\n\nmod ui;\n\nmod game;\n\nmod engine;\n\n\n\nuse std::mem;\n\n\n\nuse wasm_bindgen::prelude::*;\n\nuse web_sys;\n\nuse js_sys::Math;\n\n\n\n/// Entry point: starts the game.\n\n#[wasm_bindgen]\n", "file_path": "src/lib.rs", "rank": 28, "score": 4.204262999477421 }, { "content": " self.ctx.clear_rect(0.0, 0.0, self.width, self.height);\n\n }\n\n\n\n pub fn draw_cell(&self, x: i32, y: i32) {\n\n self.ctx.set_fill_style(&JsValue::from_str(\"#000\"));\n\n self.ctx.fill_rect(\n\n self.cell_width * (x as f64),\n\n self.cell_height * (y as f64),\n\n self.cell_width,\n\n self.cell_height\n\n );\n\n }\n\n}\n", "file_path": "src/ui.rs", "rank": 29, "score": 3.599282310395993 }, { "content": " let dest_index = self.index(dest_x, dest_y);\n\n if dest_index >= self.cells.front_ref().len() {\n\n continue;\n\n }\n\n if self.cells.front_ref()[dest_index] == Cell::Alive {\n\n count += 1;\n\n }\n\n }\n\n }\n\n return count;\n\n }\n\n\n\n /// Generate the next generation.\n\n pub fn next_gen(&mut self) {\n\n for col in 0..(self.height()) {\n\n for row in 0..(self.width()) {\n\n let index = self.index(row, col);\n\n let neighbour_count = self.neighbour_count(row, col);\n\n\n\n // The rules of \"Conway's Game of Life\":\n", "file_path": "src/engine.rs", "rank": 30, "score": 2.549651956671224 }, { "content": "//! Test suite for the Web and headless browsers.\n\n\n\n#![cfg(target_arch = \"wasm32\")]\n\n\n\nextern crate wasm_bindgen_test;\n\nuse wasm_bindgen_test::*;\n\n\n\nwasm_bindgen_test_configure!(run_in_browser);\n\n\n\n#[wasm_bindgen_test]\n", "file_path": "tests/web.rs", "rank": 31, "score": 1.6606457727346389 }, { "content": "\n\n // Then, let's just add some style.\n\n {\n\n let style = body.style();\n\n style.set_property(\"display\", \"flex\").unwrap();\n\n style.set_property(\"align-items\", \"center\").unwrap();\n\n style.set_property(\"justify-content\", \"center\").unwrap();\n\n style.set_property(\"height\", \"100vh\").unwrap();\n\n style.set_property(\"margin\", \"0\").unwrap();\n\n style.set_property(\"background-color\", \"#f5f5f5\").unwrap();\n\n }\n\n {\n\n let style = canvas_el.style();\n\n style.set_property(\"margin\", \"30px\").unwrap();\n\n style.set_property(\"box-shadow\", \"0 10px 30px #00000026\").unwrap();\n\n style.set_property(\"background-color\", \"#fff\").unwrap();\n\n }\n\n\n\n let context = canvas_el.get_context(\"2d\")\n\n .unwrap() // Result<_, _>\n", "file_path": "src/ui.rs", "rank": 32, "score": 1.5711115975679446 }, { "content": " // https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\n\n let next_gen_cell =\n\n if self.cells.front_ref()[index] == Cell::Alive {\n\n match neighbour_count {\n\n 0..2 => Cell::Dead,\n\n 2..=3 => Cell::Alive,\n\n _ => Cell::Dead,\n\n }\n\n } else {\n\n if neighbour_count == 3 {\n\n Cell::Alive\n\n } else {\n\n Cell::Dead\n\n }\n\n };\n\n\n\n // We fill the next generation cells to the back store.\n\n let back = self.cells.back_mut();\n\n back[index] = next_gen_cell;\n\n }\n", "file_path": "src/engine.rs", "rank": 33, "score": 1.2623140548841172 }, { "content": "<div align=\"center\">\n\n\n\n <h1><code>game-of-life</code></h1>\n\n\n\n <strong>A Conway's Game of Life implementation with Rust and WebAssembly.</strong>\n\n\n\n <sub>Built with 🦀🕸 by <a href=\"https://rustwasm.github.io/\">The Rust and WebAssembly Working Group</a></sub>\n\n</div>\n\n\n\n## About\n\n\n\n<img src=\"artworks/screenshot.png\" alt=\"Screen Shot\" width=\"350\" />\n\n\n\nThis is a simple project that demonstrates how to write a web app without a single line of JavaScript code.\n\n\n\n### Features\n\n\n\n* DOM operations via [`web-sys`](https://crates.io/crates/web-sys)\n\n* Use 2D canvas to render the graphics\n\n* Event handling (including timer, mouse events)\n\n* Heap memory accessing\n\n* `Math.random` via [`js-sys`](https://crates.io/crates/js-sys)\n\n* Less than 500 sloc, no boilerplate interop code (thanks to [`wasm-bindgen`](https://github.com/rustwasm/wasm-bindgen))\n\n\n\nJust try the [online demo](https://unixzii.github.io/game-of-life) here.\n\n\n\n## Build\n\n\n\nBefore build the project, make sure you have installed these dependencies:\n\n\n\n* Node\n\n* Rust (rustup is recommended)\n\n* [wasm-pack](https://rustwasm.github.io/)\n\n\n\nNote that Webpack is not required by this project, feel free to not install that :)\n\n\n\nIf you're all set, then:\n\n\n\n```shell\n\ngit clone https://github.com/unixzii/game-of-life.git\n\ncd game-of-life\n\nmake\n\n```\n\n\n\nFinally, start a web server and open `index.html` in your favorite browser.\n\n\n\n## License\n\n\n", "file_path": "README.md", "rank": 34, "score": 1.2202352288189715 } ]
Rust
src/codec_impl.rs
Stebalien/libipld
92586bc1708fb69463ef865f81f9986b3cf31524
#[cfg(feature = "dag-cbor")] use crate::cbor::DagCborCodec; use crate::cid::Cid; use crate::codec::{Codec, Decode, Encode, References}; use crate::error::{Result, UnsupportedCodec}; use crate::ipld::Ipld; #[cfg(feature = "dag-json")] use crate::json::DagJsonCodec; #[cfg(feature = "dag-pb")] use crate::pb::DagPbCodec; use crate::raw::RawCodec; use core::convert::TryFrom; use std::io::{Read, Seek, Write}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IpldCodec { Raw, #[cfg(feature = "dag-cbor")] DagCbor, #[cfg(feature = "dag-json")] DagJson, #[cfg(feature = "dag-pb")] DagPb, } impl TryFrom<u64> for IpldCodec { type Error = UnsupportedCodec; fn try_from(ccode: u64) -> core::result::Result<Self, Self::Error> { Ok(match ccode { 0x55 => Self::Raw, #[cfg(feature = "dag-cbor")] 0x71 => Self::DagCbor, #[cfg(feature = "dag-json")] 0x0129 => Self::DagJson, #[cfg(feature = "dag-pb")] 0x70 => Self::DagPb, _ => return Err(UnsupportedCodec(ccode)), }) } } impl From<IpldCodec> for u64 { fn from(mc: IpldCodec) -> Self { match mc { IpldCodec::Raw => 0x55, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => 0x71, #[cfg(feature = "dag-json")] IpldCodec::DagJson => 0x0129, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => 0x70, } } } impl From<RawCodec> for IpldCodec { fn from(_: RawCodec) -> Self { Self::Raw } } #[cfg(feature = "dag-cbor")] impl From<DagCborCodec> for IpldCodec { fn from(_: DagCborCodec) -> Self { Self::DagCbor } } #[cfg(feature = "dag-cbor")] impl From<IpldCodec> for DagCborCodec { fn from(_: IpldCodec) -> Self { Self } } #[cfg(feature = "dag-json")] impl From<DagJsonCodec> for IpldCodec { fn from(_: DagJsonCodec) -> Self { Self::DagJson } } #[cfg(feature = "dag-json")] impl From<IpldCodec> for DagJsonCodec { fn from(_: IpldCodec) -> Self { Self } } #[cfg(feature = "dag-pb")] impl From<DagPbCodec> for IpldCodec { fn from(_: DagPbCodec) -> Self { Self::DagPb } } #[cfg(feature = "dag-pb")] impl From<IpldCodec> for DagPbCodec { fn from(_: IpldCodec) -> Self { Self } } impl Codec for IpldCodec {} impl Encode<IpldCodec> for Ipld { fn encode<W: Write>(&self, c: IpldCodec, w: &mut W) -> Result<()> { match c { IpldCodec::Raw => self.encode(RawCodec, w)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => self.encode(DagCborCodec, w)?, #[cfg(feature = "dag-json")] IpldCodec::DagJson => self.encode(DagJsonCodec, w)?, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => self.encode(DagPbCodec, w)?, }; Ok(()) } } impl Decode<IpldCodec> for Ipld { fn decode<R: Read + Seek>(c: IpldCodec, r: &mut R) -> Result<Self> { Ok(match c { IpldCodec::Raw => Self::decode(RawCodec, r)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => Self::decode(DagCborCodec, r)?, #[cfg(feature = "dag-json")] IpldCodec::DagJson => Self::decode(DagJsonCodec, r)?, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => Self::decode(DagPbCodec, r)?, }) } } impl References<IpldCodec> for Ipld { fn references<R: Read + Seek, E: Extend<Cid>>( c: IpldCodec, r: &mut R, set: &mut E, ) -> Result<()> { match c { IpldCodec::Raw => <Self as References<RawCodec>>::references(RawCodec, r, set)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => { <Self as References<DagCborCodec>>::references(DagCborCodec, r, set)? } #[cfg(feature = "dag-json")] IpldCodec::DagJson => { <Self as References<DagJsonCodec>>::references(DagJsonCodec, r, set)? } #[cfg(feature = "dag-pb")] IpldCodec::DagPb => <Self as References<DagPbCodec>>::references(DagPbCodec, r, set)?, }; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn raw_encode() { let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec()); let result = IpldCodec::Raw.encode(&data).unwrap(); assert_eq!(result, vec![0x22, 0x33, 0x44]); } #[test] fn raw_decode() { let data = [0x22, 0x33, 0x44]; let result: Ipld = IpldCodec::Raw.decode(&data).unwrap(); assert_eq!(result, Ipld::Bytes(data.to_vec())); } #[cfg(feature = "dag-cbor")] #[test] fn dag_cbor_encode() { let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec()); let result = IpldCodec::DagCbor.encode(&data).unwrap(); assert_eq!(result, vec![0x43, 0x22, 0x33, 0x44]); } #[cfg(feature = "dag-cbor")] #[test] fn dag_cbor_decode() { let data = [0x43, 0x22, 0x33, 0x44]; let result: Ipld = IpldCodec::DagCbor.decode(&data).unwrap(); assert_eq!(result, Ipld::Bytes(vec![0x22, 0x33, 0x44])); } #[cfg(feature = "dag-json")] #[test] fn dag_json_encode() { let data = Ipld::Bool(true); let result = String::from_utf8(IpldCodec::DagJson.encode(&data).unwrap().to_vec()).unwrap(); assert_eq!(result, "true"); } #[cfg(feature = "dag-json")] #[test] fn dag_json_decode() { let data = b"true"; let result: Ipld = IpldCodec::DagJson.decode(data).unwrap(); assert_eq!(result, Ipld::Bool(true)); } #[cfg(feature = "dag-pb")] #[test] fn dag_pb_encode() { let mut data_map = std::collections::BTreeMap::<String, Ipld>::new(); data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec())); data_map.insert("Links".to_string(), Ipld::List(vec![])); let data = Ipld::Map(data_map); let result = IpldCodec::DagPb.encode(&data).unwrap(); assert_eq!(result, vec![0x0a, 0x04, 0x64, 0x61, 0x74, 0x61]); } #[cfg(feature = "dag-pb")] #[test] fn dag_pb_decode() { let mut data_map = std::collections::BTreeMap::<String, Ipld>::new(); data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec())); data_map.insert("Links".to_string(), Ipld::List(vec![])); let expected = Ipld::Map(data_map); let data = [0x0a, 0x04, 0x64, 0x61, 0x74, 0x61]; let result: Ipld = IpldCodec::DagPb.decode(&data).unwrap(); assert_eq!(result, expected); } }
#[cfg(feature = "dag-cbor")] use crate::cbor::DagCborCodec; use crate::cid::Cid; use crate::codec::{Codec, Decode, Encode, Refere
es<RawCodec>>::references(RawCodec, r, set)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => { <Self as References<DagCborCodec>>::references(DagCborCodec, r, set)? } #[cfg(feature = "dag-json")] IpldCodec::DagJson => { <Self as References<DagJsonCodec>>::references(DagJsonCodec, r, set)? } #[cfg(feature = "dag-pb")] IpldCodec::DagPb => <Self as References<DagPbCodec>>::references(DagPbCodec, r, set)?, }; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn raw_encode() { let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec()); let result = IpldCodec::Raw.encode(&data).unwrap(); assert_eq!(result, vec![0x22, 0x33, 0x44]); } #[test] fn raw_decode() { let data = [0x22, 0x33, 0x44]; let result: Ipld = IpldCodec::Raw.decode(&data).unwrap(); assert_eq!(result, Ipld::Bytes(data.to_vec())); } #[cfg(feature = "dag-cbor")] #[test] fn dag_cbor_encode() { let data = Ipld::Bytes([0x22, 0x33, 0x44].to_vec()); let result = IpldCodec::DagCbor.encode(&data).unwrap(); assert_eq!(result, vec![0x43, 0x22, 0x33, 0x44]); } #[cfg(feature = "dag-cbor")] #[test] fn dag_cbor_decode() { let data = [0x43, 0x22, 0x33, 0x44]; let result: Ipld = IpldCodec::DagCbor.decode(&data).unwrap(); assert_eq!(result, Ipld::Bytes(vec![0x22, 0x33, 0x44])); } #[cfg(feature = "dag-json")] #[test] fn dag_json_encode() { let data = Ipld::Bool(true); let result = String::from_utf8(IpldCodec::DagJson.encode(&data).unwrap().to_vec()).unwrap(); assert_eq!(result, "true"); } #[cfg(feature = "dag-json")] #[test] fn dag_json_decode() { let data = b"true"; let result: Ipld = IpldCodec::DagJson.decode(data).unwrap(); assert_eq!(result, Ipld::Bool(true)); } #[cfg(feature = "dag-pb")] #[test] fn dag_pb_encode() { let mut data_map = std::collections::BTreeMap::<String, Ipld>::new(); data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec())); data_map.insert("Links".to_string(), Ipld::List(vec![])); let data = Ipld::Map(data_map); let result = IpldCodec::DagPb.encode(&data).unwrap(); assert_eq!(result, vec![0x0a, 0x04, 0x64, 0x61, 0x74, 0x61]); } #[cfg(feature = "dag-pb")] #[test] fn dag_pb_decode() { let mut data_map = std::collections::BTreeMap::<String, Ipld>::new(); data_map.insert("Data".to_string(), Ipld::Bytes(b"data".to_vec())); data_map.insert("Links".to_string(), Ipld::List(vec![])); let expected = Ipld::Map(data_map); let data = [0x0a, 0x04, 0x64, 0x61, 0x74, 0x61]; let result: Ipld = IpldCodec::DagPb.decode(&data).unwrap(); assert_eq!(result, expected); } }
nces}; use crate::error::{Result, UnsupportedCodec}; use crate::ipld::Ipld; #[cfg(feature = "dag-json")] use crate::json::DagJsonCodec; #[cfg(feature = "dag-pb")] use crate::pb::DagPbCodec; use crate::raw::RawCodec; use core::convert::TryFrom; use std::io::{Read, Seek, Write}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IpldCodec { Raw, #[cfg(feature = "dag-cbor")] DagCbor, #[cfg(feature = "dag-json")] DagJson, #[cfg(feature = "dag-pb")] DagPb, } impl TryFrom<u64> for IpldCodec { type Error = UnsupportedCodec; fn try_from(ccode: u64) -> core::result::Result<Self, Self::Error> { Ok(match ccode { 0x55 => Self::Raw, #[cfg(feature = "dag-cbor")] 0x71 => Self::DagCbor, #[cfg(feature = "dag-json")] 0x0129 => Self::DagJson, #[cfg(feature = "dag-pb")] 0x70 => Self::DagPb, _ => return Err(UnsupportedCodec(ccode)), }) } } impl From<IpldCodec> for u64 { fn from(mc: IpldCodec) -> Self { match mc { IpldCodec::Raw => 0x55, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => 0x71, #[cfg(feature = "dag-json")] IpldCodec::DagJson => 0x0129, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => 0x70, } } } impl From<RawCodec> for IpldCodec { fn from(_: RawCodec) -> Self { Self::Raw } } #[cfg(feature = "dag-cbor")] impl From<DagCborCodec> for IpldCodec { fn from(_: DagCborCodec) -> Self { Self::DagCbor } } #[cfg(feature = "dag-cbor")] impl From<IpldCodec> for DagCborCodec { fn from(_: IpldCodec) -> Self { Self } } #[cfg(feature = "dag-json")] impl From<DagJsonCodec> for IpldCodec { fn from(_: DagJsonCodec) -> Self { Self::DagJson } } #[cfg(feature = "dag-json")] impl From<IpldCodec> for DagJsonCodec { fn from(_: IpldCodec) -> Self { Self } } #[cfg(feature = "dag-pb")] impl From<DagPbCodec> for IpldCodec { fn from(_: DagPbCodec) -> Self { Self::DagPb } } #[cfg(feature = "dag-pb")] impl From<IpldCodec> for DagPbCodec { fn from(_: IpldCodec) -> Self { Self } } impl Codec for IpldCodec {} impl Encode<IpldCodec> for Ipld { fn encode<W: Write>(&self, c: IpldCodec, w: &mut W) -> Result<()> { match c { IpldCodec::Raw => self.encode(RawCodec, w)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => self.encode(DagCborCodec, w)?, #[cfg(feature = "dag-json")] IpldCodec::DagJson => self.encode(DagJsonCodec, w)?, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => self.encode(DagPbCodec, w)?, }; Ok(()) } } impl Decode<IpldCodec> for Ipld { fn decode<R: Read + Seek>(c: IpldCodec, r: &mut R) -> Result<Self> { Ok(match c { IpldCodec::Raw => Self::decode(RawCodec, r)?, #[cfg(feature = "dag-cbor")] IpldCodec::DagCbor => Self::decode(DagCborCodec, r)?, #[cfg(feature = "dag-json")] IpldCodec::DagJson => Self::decode(DagJsonCodec, r)?, #[cfg(feature = "dag-pb")] IpldCodec::DagPb => Self::decode(DagPbCodec, r)?, }) } } impl References<IpldCodec> for Ipld { fn references<R: Read + Seek, E: Extend<Cid>>( c: IpldCodec, r: &mut R, set: &mut E, ) -> Result<()> { match c { IpldCodec::Raw => <Self as Referenc
random
[ { "content": "/// Marker trait for types supporting the `DagCborCodec`.\n\npub trait DagCbor: Encode<DagCborCodec> + Decode<DagCborCodec> {}\n\n\n\nimpl<T: Encode<DagCborCodec> + Decode<DagCborCodec>> DagCbor for T {}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use libipld_core::cid::Cid;\n\n use libipld_core::codec::assert_roundtrip;\n\n use libipld_core::ipld::Ipld;\n\n use libipld_core::multihash::{Code, MultihashDigest};\n\n use libipld_macro::ipld;\n\n use std::collections::HashSet;\n\n\n\n #[test]\n\n fn test_encode_decode_cbor() {\n\n let cid = Cid::new_v1(0, Code::Blake3_256.digest(&b\"cid\"[..]));\n\n let ipld = ipld!({\n\n \"number\": 1,\n\n \"list\": [true, null, false],\n", "file_path": "dag-cbor/src/lib.rs", "rank": 0, "score": 83351.25083845468 }, { "content": "/// Reads a map of any type that implements `TryReadCbor` from a stream of cbor encoded bytes.\n\npub fn read_map<R: Read + Seek, K: Decode<DagCbor> + Ord, T: Decode<DagCbor>>(\n\n r: &mut R,\n\n len: u64,\n\n) -> Result<BTreeMap<K, T>> {\n\n let len = usize::try_from(len).map_err(|_| LengthOutOfRange::new::<usize>())?;\n\n let mut map: BTreeMap<K, T> = BTreeMap::new();\n\n for _ in 0..len {\n\n let key = K::decode(DagCbor, r)?;\n\n let value = T::decode(DagCbor, r)?;\n\n map.insert(key, value);\n\n }\n\n Ok(map)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 1, "score": 70809.78063970925 }, { "content": "/// Reads a list of any type that implements `TryReadCbor` from a stream of cbor encoded bytes.\n\npub fn read_list<R: Read + Seek, T: Decode<DagCbor>>(r: &mut R, len: u64) -> Result<Vec<T>> {\n\n let len = usize::try_from(len).map_err(|_| LengthOutOfRange::new::<usize>())?;\n\n // Limit up-front allocations to 16KiB as the length is user controlled.\n\n //\n\n // Can't make this \"const\" because the generic, but it _should_ be known at compile time.\n\n let max_alloc = (16 * 1024) / std::mem::size_of::<T>();\n\n\n\n let mut list: Vec<T> = Vec::with_capacity(len.min(max_alloc));\n\n for _ in 0..len {\n\n list.push(T::decode(DagCbor, r)?);\n\n }\n\n Ok(list)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 2, "score": 52241.074893454905 }, { "content": "//! CBOR encoder.\n\n\n\nuse std::cmp::Ordering;\n\nuse std::collections::BTreeMap;\n\nuse std::io::Write;\n\nuse std::iter::FromIterator;\n\nuse std::ops::Deref;\n\nuse std::sync::Arc;\n\n\n\nuse byteorder::{BigEndian, ByteOrder};\n\nuse libipld_core::cid::Cid;\n\nuse libipld_core::codec::Encode;\n\nuse libipld_core::error::Result;\n\nuse libipld_core::ipld::Ipld;\n\n\n\nuse crate::cbor::{MajorKind, FALSE, TRUE};\n\nuse crate::error::NumberOutOfRange;\n\nuse crate::DagCborCodec as DagCbor;\n\n\n\n/// Writes a null byte to a cbor encoded byte stream.\n", "file_path": "dag-cbor/src/encode.rs", "rank": 3, "score": 39218.97938793086 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\nimpl<A: Encode<DagCbor>, B: Encode<DagCbor>, C: Encode<DagCbor>> Encode<DagCbor> for (A, B, C) {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::Array, 3)?;\n\n self.0.encode(c, w)?;\n\n self.1.encode(c, w)?;\n\n self.2.encode(c, w)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<A: Encode<DagCbor>, B: Encode<DagCbor>, C: Encode<DagCbor>, D: Encode<DagCbor>> Encode<DagCbor>\n\n for (A, B, C, D)\n\n{\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::Array, 4)?;\n\n self.0.encode(c, w)?;\n\n self.1.encode(c, w)?;\n\n self.2.encode(c, w)?;\n\n self.3.encode(c, w)?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "dag-cbor/src/encode.rs", "rank": 4, "score": 39215.6753407879 }, { "content": " match self {\n\n Self::Null => write_null(w),\n\n Self::Bool(b) => b.encode(c, w),\n\n Self::Integer(i) => i.encode(c, w),\n\n Self::Float(f) => f.encode(c, w),\n\n Self::Bytes(b) => b.as_slice().encode(c, w),\n\n Self::String(s) => s.encode(c, w),\n\n Self::List(l) => l.encode(c, w),\n\n Self::Map(m) => m.encode(c, w),\n\n Self::Link(cid) => cid.encode(c, w),\n\n }\n\n }\n\n}\n\n\n\nimpl<T: Encode<DagCbor>> Encode<DagCbor> for Arc<T> {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n self.deref().encode(c, w)\n\n }\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 5, "score": 39215.6162521762 }, { "content": "impl Encode<DagCbor> for () {\n\n fn encode<W: Write>(&self, _c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::Array, 0)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<A: Encode<DagCbor>> Encode<DagCbor> for (A,) {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::Array, 1)?;\n\n self.0.encode(c, w)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<A: Encode<DagCbor>, B: Encode<DagCbor>> Encode<DagCbor> for (A, B) {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::Array, 2)?;\n\n self.0.encode(c, w)?;\n\n self.1.encode(c, w)?;\n", "file_path": "dag-cbor/src/encode.rs", "rank": 6, "score": 39215.479520384135 }, { "content": " } else {\n\n (*self as u32).encode(c, w)\n\n }\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for i64 {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n if self.is_negative() {\n\n write_u64(w, MajorKind::NegativeInt, -(*self + 1) as u64)\n\n } else {\n\n (*self as u64).encode(c, w)\n\n }\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for f32 {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n // IPLD maximally encodes floats.\n\n f64::from(*self).encode(c, w)\n", "file_path": "dag-cbor/src/encode.rs", "rank": 7, "score": 39215.432220733484 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for Box<[u8]> {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n self[..].encode(c, w)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for str {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_u64(w, MajorKind::TextString, self.len() as u64)?;\n\n w.write_all(self.as_bytes())?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for String {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n", "file_path": "dag-cbor/src/encode.rs", "rank": 8, "score": 39215.2022104344 }, { "content": " } else {\n\n (*self as u8).encode(c, w)\n\n }\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for i16 {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n if self.is_negative() {\n\n write_u16(w, MajorKind::NegativeInt, -(*self + 1) as u16)\n\n } else {\n\n (*self as u16).encode(c, w)\n\n }\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for i32 {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n if self.is_negative() {\n\n write_u32(w, MajorKind::NegativeInt, -(*self + 1) as u32)\n", "file_path": "dag-cbor/src/encode.rs", "rank": 9, "score": 39215.16437924667 }, { "content": " write_null(w)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<T: Encode<DagCbor>> Encode<DagCbor> for Vec<T> {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u64(w, MajorKind::Array, self.len() as u64)?;\n\n for value in self {\n\n value.encode(c, w)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<T: Encode<DagCbor> + 'static> Encode<DagCbor> for BTreeMap<String, T> {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n write_u64(w, MajorKind::Map, self.len() as u64)?;\n\n // CBOR RFC-7049 specifies a canonical sort order, where keys are sorted by length first.\n", "file_path": "dag-cbor/src/encode.rs", "rank": 10, "score": 39214.967959678535 }, { "content": " write_u16(w, MajorKind::UnsignedInt, *self)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for u32 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_u32(w, MajorKind::UnsignedInt, *self)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for u64 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_u64(w, MajorKind::UnsignedInt, *self)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for i8 {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n if self.is_negative() {\n\n write_u8(w, MajorKind::NegativeInt, -(*self + 1) as u8)\n", "file_path": "dag-cbor/src/encode.rs", "rank": 11, "score": 39214.88323603391 }, { "content": "\n\nimpl Encode<DagCbor> for Cid {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_tag(w, 42)?;\n\n // insert zero byte per https://github.com/ipld/specs/blob/master/block-layer/codecs/dag-cbor.md#links\n\n // TODO: don't allocate\n\n let buf = self.to_bytes();\n\n let len = buf.len();\n\n write_u64(w, MajorKind::ByteString, len as u64 + 1)?;\n\n w.write_all(&[0])?;\n\n w.write_all(&buf[..len])?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<T: Encode<DagCbor>> Encode<DagCbor> for Option<T> {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n\n if let Some(value) = self {\n\n value.encode(c, w)?;\n\n } else {\n", "file_path": "dag-cbor/src/encode.rs", "rank": 12, "score": 39214.76097673656 }, { "content": " }\n\n}\n\n\n\nimpl Encode<DagCbor> for f64 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n // IPLD forbids nan, infinities, etc.\n\n if !self.is_finite() {\n\n return Err(NumberOutOfRange::new::<f64>().into());\n\n }\n\n let mut buf = [0xfb, 0, 0, 0, 0, 0, 0, 0, 0];\n\n BigEndian::write_f64(&mut buf[1..], *self);\n\n w.write_all(&buf)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for [u8] {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_u64(w, MajorKind::ByteString, self.len() as u64)?;\n\n w.write_all(self)?;\n", "file_path": "dag-cbor/src/encode.rs", "rank": 13, "score": 39214.518489456226 }, { "content": " // This was later revised with RFC-8949, but we need to stick to the original order to stay\n\n // compatible with existing data.\n\n let mut cbor_order = Vec::from_iter(self);\n\n cbor_order.sort_unstable_by(|&(key_a, _), &(key_b, _)| {\n\n match key_a.len().cmp(&key_b.len()) {\n\n Ordering::Greater => Ordering::Greater,\n\n Ordering::Less => Ordering::Less,\n\n Ordering::Equal => key_a.cmp(key_b),\n\n }\n\n });\n\n for (k, v) in cbor_order {\n\n k.encode(c, w)?;\n\n v.encode(c, w)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for Ipld {\n\n fn encode<W: Write>(&self, c: DagCbor, w: &mut W) -> Result<()> {\n", "file_path": "dag-cbor/src/encode.rs", "rank": 14, "score": 39214.50079522648 }, { "content": " self.as_str().encode(c, w)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for i128 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n if *self < 0 {\n\n if -(*self + 1) > u64::max_value() as i128 {\n\n return Err(NumberOutOfRange::new::<i128>().into());\n\n }\n\n write_u64(w, MajorKind::NegativeInt, -(*self + 1) as u64)?;\n\n } else {\n\n if *self > u64::max_value() as i128 {\n\n return Err(NumberOutOfRange::new::<i128>().into());\n\n }\n\n write_u64(w, MajorKind::UnsignedInt, *self as u64)?;\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "dag-cbor/src/encode.rs", "rank": 15, "score": 39214.34383145563 }, { "content": "//! CBOR decoder\n\nuse crate::cbor::{Major, MajorKind, F32, F64, FALSE, NULL, TRUE};\n\nuse crate::error::{\n\n InvalidCidPrefix, LengthOutOfRange, NumberNotMinimal, NumberOutOfRange, UnexpectedCode,\n\n UnexpectedEof, UnknownTag,\n\n};\n\nuse crate::DagCborCodec as DagCbor;\n\nuse byteorder::{BigEndian, ByteOrder};\n\nuse core::convert::TryFrom;\n\nuse libipld_core::codec::{Decode, References};\n\nuse libipld_core::error::Result;\n\nuse libipld_core::ipld::Ipld;\n\nuse libipld_core::{cid::Cid, raw_value::SkipOne};\n\nuse std::collections::BTreeMap;\n\nuse std::io::{Read, Seek, SeekFrom};\n\nuse std::sync::Arc;\n\n\n\n/// Reads a u8 from a byte stream.\n", "file_path": "dag-cbor/src/decode.rs", "rank": 16, "score": 39025.4615989417 }, { "content": " let _data2: () = DagCborCodec.decode(&bytes)?;\n\n\n\n let data = (\"hello\".to_string(),);\n\n let bytes = DagCborCodec.encode(&data)?;\n\n let data2: (String,) = DagCborCodec.decode(&bytes)?;\n\n assert_eq!(data, data2);\n\n\n\n let data = (\"hello\".to_string(), \"world\".to_string());\n\n let bytes = DagCborCodec.encode(&data)?;\n\n let data2: (String, String) = DagCborCodec.decode(&bytes)?;\n\n assert_eq!(data, data2);\n\n\n\n let data = (\"hello\".to_string(), \"world\".to_string(), 42);\n\n let bytes = DagCborCodec.encode(&data)?;\n\n let data2: (String, String, u32) = DagCborCodec.decode(&bytes)?;\n\n assert_eq!(data, data2);\n\n\n\n let data = (\"hello\".to_string(), \"world\".to_string(), 42, 64);\n\n let bytes = DagCborCodec.encode(&data)?;\n\n let data2: (String, String, u32, u8) = DagCborCodec.decode(&bytes)?;\n\n assert_eq!(data, data2);\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "dag-cbor/src/decode.rs", "rank": 17, "score": 39023.61420726104 }, { "content": "mod tests {\n\n use super::*;\n\n use crate::{error::UnexpectedEof, DagCborCodec};\n\n use libipld_core::codec::Codec;\n\n\n\n #[test]\n\n fn il_map() {\n\n let bytes = [\n\n 0xBF, // Start indefinite-length map\n\n 0x63, // First key, UTF-8 string length 3\n\n 0x46, 0x75, 0x6e, // \"Fun\"\n\n 0xF5, // First value, true\n\n 0x63, // Second key, UTF-8 string length 3\n\n 0x41, 0x6d, 0x74, // \"Amt\"\n\n 0x21, // Second value, -2\n\n 0xFF, // \"break\"\n\n ];\n\n DagCborCodec\n\n .decode::<Ipld>(&bytes)\n\n .expect_err(\"should have failed to decode indefinit length map\");\n", "file_path": "dag-cbor/src/decode.rs", "rank": 18, "score": 39022.79589397827 }, { "content": " }\n\n\n\n #[test]\n\n fn bad_list() {\n\n let bytes = [\n\n 0x5b, // Byte string with an 8 byte length\n\n 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // very long\n\n 0x01, // but only one byte.\n\n ];\n\n DagCborCodec\n\n .decode::<Ipld>(&bytes)\n\n .expect_err(\"decoding large truncated buffer should have failed\")\n\n .downcast::<UnexpectedEof>()\n\n .expect(\"expected an unexpected eof\");\n\n }\n\n\n\n #[test]\n\n fn tuples() -> Result<()> {\n\n let data = ();\n\n let bytes = DagCborCodec.encode(&data)?;\n", "file_path": "dag-cbor/src/decode.rs", "rank": 19, "score": 39021.87237519084 }, { "content": " }\n\n Ok(num)\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for f64 {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n // TODO: We don't accept f16\n\n // TODO: By IPLD spec, we shouldn't accept f32 either...\n\n let num = match read_major(r)? {\n\n F32 => read_f32(r)?.into(),\n\n F64 => read_f64(r)?,\n\n m => return Err(UnexpectedCode::new::<Self>(m.into()).into()),\n\n };\n\n // This is by IPLD spec, but is it widely used?\n\n if !num.is_finite() {\n\n return Err(NumberOutOfRange::new::<Self>().into());\n\n }\n\n Ok(num)\n\n }\n", "file_path": "dag-cbor/src/decode.rs", "rank": 20, "score": 39021.68989432944 }, { "content": " 0x83 => (A::decode(c, r)?, B::decode(c, r)?, C::decode(c, r)?),\n\n _ => {\n\n return Err(UnexpectedCode::new::<Self>(major).into());\n\n }\n\n };\n\n Ok(result)\n\n }\n\n}\n\n\n\nimpl<A: Decode<DagCbor>, B: Decode<DagCbor>, C: Decode<DagCbor>, D: Decode<DagCbor>> Decode<DagCbor>\n\n for (A, B, C, D)\n\n{\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_u8(r)?;\n\n let result = match major {\n\n 0x84 => (\n\n A::decode(c, r)?,\n\n B::decode(c, r)?,\n\n C::decode(c, r)?,\n\n D::decode(c, r)?,\n", "file_path": "dag-cbor/src/decode.rs", "rank": 21, "score": 39021.34780478575 }, { "content": " }\n\n}\n\n\n\nimpl<A: Decode<DagCbor>, B: Decode<DagCbor>> Decode<DagCbor> for (A, B) {\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_u8(r)?;\n\n let result = match major {\n\n 0x82 => (A::decode(c, r)?, B::decode(c, r)?),\n\n _ => {\n\n return Err(UnexpectedCode::new::<Self>(major).into());\n\n }\n\n };\n\n Ok(result)\n\n }\n\n}\n\n\n\nimpl<A: Decode<DagCbor>, B: Decode<DagCbor>, C: Decode<DagCbor>> Decode<DagCbor> for (A, B, C) {\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_u8(r)?;\n\n let result = match major {\n", "file_path": "dag-cbor/src/decode.rs", "rank": 22, "score": 39021.1129129806 }, { "content": " remaining = remaining\n\n .checked_add(1)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n },\n\n };\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<T: Decode<DagCbor>> Decode<DagCbor> for Arc<T> {\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n\n Ok(Arc::new(T::decode(c, r)?))\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for () {\n\n fn decode<R: Read + Seek>(_c: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_u8(r)?;\n", "file_path": "dag-cbor/src/decode.rs", "rank": 23, "score": 39020.80902083481 }, { "content": " match major {\n\n 0x80 => {}\n\n _ => {\n\n return Err(UnexpectedCode::new::<Self>(major).into());\n\n }\n\n };\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<A: Decode<DagCbor>> Decode<DagCbor> for (A,) {\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_u8(r)?;\n\n let result = match major {\n\n 0x81 => (A::decode(c, r)?,),\n\n _ => {\n\n return Err(UnexpectedCode::new::<Self>(major).into());\n\n }\n\n };\n\n Ok(result)\n", "file_path": "dag-cbor/src/decode.rs", "rank": 24, "score": 39020.55394033036 }, { "content": " }\n\n } else {\n\n Err(UnexpectedCode::new::<Self>(major.into()).into())\n\n }\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for Box<[u8]> {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::ByteString {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n }\n\n let len = read_uint(r, major)?;\n\n Ok(read_bytes(r, len)?.into_boxed_slice())\n\n }\n\n}\n\n\n\nimpl<T: Decode<DagCbor>> Decode<DagCbor> for Option<T> {\n\n fn decode<R: Read + Seek>(c: DagCbor, r: &mut R) -> Result<Self> {\n", "file_path": "dag-cbor/src/decode.rs", "rank": 25, "score": 39020.39631177821 }, { "content": " let result = match read_major(r)? {\n\n NULL => None,\n\n _ => {\n\n r.seek(SeekFrom::Current(-1))?;\n\n Some(T::decode(c, r)?)\n\n }\n\n };\n\n Ok(result)\n\n }\n\n}\n\n\n\nimpl<T: Decode<DagCbor>> Decode<DagCbor> for Vec<T> {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::Array {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n }\n\n let len = read_uint(r, major)?;\n\n read_list(r, len)\n\n }\n", "file_path": "dag-cbor/src/decode.rs", "rank": 26, "score": 39020.3412528806 }, { "content": "}\n\n\n\nimpl<K: Decode<DagCbor> + Ord, T: Decode<DagCbor>> Decode<DagCbor> for BTreeMap<K, T> {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::Map {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n }\n\n\n\n let len = read_uint(r, major)?;\n\n read_map(r, len)\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for Ipld {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n let ipld = match major.kind() {\n\n MajorKind::UnsignedInt => Self::Integer(read_uint(r, major)? as i128),\n\n MajorKind::NegativeInt => Self::Integer(-1 - read_uint(r, major)? as i128),\n", "file_path": "dag-cbor/src/decode.rs", "rank": 27, "score": 39020.297123156604 }, { "content": "macro_rules! impl_num {\n\n (unsigned $($t:ty),*) => {\n\n $(\n\n impl Decode<DagCbor> for $t {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::UnsignedInt {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n }\n\n let value = read_uint(r, major)?;\n\n Self::try_from(value).map_err(|_| NumberOutOfRange::new::<Self>().into())\n\n }\n\n }\n\n )*\n\n };\n\n (signed $($t:ty),*) => {\n\n $(\n\n impl Decode<DagCbor> for $t {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n", "file_path": "dag-cbor/src/decode.rs", "rank": 28, "score": 39020.130688661695 }, { "content": "}\n\n\n\nimpl Decode<DagCbor> for String {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::TextString {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n }\n\n let len = read_uint(r, major)?;\n\n read_str(r, len)\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for Cid {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n let major = read_major(r)?;\n\n if major.kind() == MajorKind::Tag {\n\n match read_uint(r, major)? {\n\n 42 => read_link(r),\n\n tag => Err(UnknownTag(tag).into()),\n", "file_path": "dag-cbor/src/decode.rs", "rank": 29, "score": 39020.04883275942 }, { "content": " } else {\n\n return Err(UnknownTag(value).into());\n\n }\n\n }\n\n MajorKind::Other => match major {\n\n FALSE => Self::Bool(false),\n\n TRUE => Self::Bool(true),\n\n NULL => Self::Null,\n\n F32 => Self::Float(read_f32(r)? as f64),\n\n F64 => Self::Float(read_f64(r)?),\n\n m => return Err(UnexpectedCode::new::<Self>(m.into()).into()),\n\n },\n\n };\n\n Ok(ipld)\n\n }\n\n}\n\n\n\nimpl References<DagCbor> for Ipld {\n\n fn references<R: Read + Seek, E: Extend<Cid>>(\n\n _: DagCbor,\n", "file_path": "dag-cbor/src/decode.rs", "rank": 30, "score": 39019.5013940512 }, { "content": " value => Ok(value),\n\n },\n\n 27 => match read_u64(r)? as u64 {\n\n 0..=MAX_4BYTE => Err(NumberNotMinimal.into()),\n\n value => Ok(value),\n\n },\n\n _ => Err(UnexpectedCode::new::<u64>(major.into()).into()),\n\n }\n\n}\n\n\n\nimpl Decode<DagCbor> for bool {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n Ok(match read_major(r)? {\n\n FALSE => false,\n\n TRUE => true,\n\n m => return Err(UnexpectedCode::new::<Self>(m.into()).into()),\n\n })\n\n }\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 31, "score": 39019.4973684644 }, { "content": "impl_num!(signed i8, i16, i32, i64, i128);\n\n\n\nimpl Decode<DagCbor> for f32 {\n\n fn decode<R: Read + Seek>(_: DagCbor, r: &mut R) -> Result<Self> {\n\n // TODO: We don't accept f16\n\n // TODO: By IPLD spec, we shouldn't accept f32 either...\n\n let num = match read_major(r)? {\n\n F32 => read_f32(r)?,\n\n F64 => {\n\n let num = read_f64(r)?;\n\n let converted = num as Self;\n\n if f64::from(converted) != num {\n\n return Err(NumberOutOfRange::new::<Self>().into());\n\n }\n\n converted\n\n }\n\n m => return Err(UnexpectedCode::new::<Self>(m.into()).into()),\n\n };\n\n if !num.is_finite() {\n\n return Err(NumberOutOfRange::new::<Self>().into());\n", "file_path": "dag-cbor/src/decode.rs", "rank": 32, "score": 39019.09380381153 }, { "content": " }\n\n r.seek(SeekFrom::Current(offset as i64))?;\n\n }\n\n MajorKind::Array => {\n\n remaining = remaining\n\n .checked_add(read_uint(r, major)?)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n MajorKind::Map => {\n\n // TODO: consider using a checked \"monad\" type to simplify.\n\n let items = read_uint(r, major)?\n\n .checked_mul(2)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n remaining = remaining\n\n .checked_add(items)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n MajorKind::Tag => match read_uint(r, major)? {\n\n 42 => set.extend(std::iter::once(read_link(r)?)),\n\n _ => {\n", "file_path": "dag-cbor/src/decode.rs", "rank": 33, "score": 39018.096798704624 }, { "content": " }\n\n MajorKind::ByteString | MajorKind::TextString => {\n\n // We could just reject this case, but we can't just play it fast and loose and\n\n // wrap. We might as well just try to seek (and likely fail).\n\n let mut offset = read_uint(r, major)?;\n\n while offset > i64::MAX as u64 {\n\n r.seek(SeekFrom::Current(i64::MAX))?;\n\n offset -= i64::MAX as u64;\n\n }\n\n // TODO: validate utf8?\n\n r.seek(SeekFrom::Current(offset as i64))?;\n\n }\n\n MajorKind::Array => {\n\n remaining = remaining\n\n .checked_add(read_uint(r, major)?)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n MajorKind::Map => {\n\n // TODO: consider using a checked \"monad\" type to simplify.\n\n let items = read_uint(r, major)?\n", "file_path": "dag-cbor/src/decode.rs", "rank": 34, "score": 39017.90591419515 }, { "content": " r: &mut R,\n\n set: &mut E,\n\n ) -> Result<()> {\n\n let mut remaining: u64 = 1;\n\n while remaining > 0 {\n\n remaining -= 1;\n\n let major = read_major(r)?;\n\n match major.kind() {\n\n MajorKind::UnsignedInt | MajorKind::NegativeInt | MajorKind::Other => {\n\n // TODO: validate ints & floats?\n\n r.seek(SeekFrom::Current(major.len() as i64))?;\n\n }\n\n MajorKind::ByteString | MajorKind::TextString => {\n\n // TODO: validate utf8?\n\n // We could just reject this case, but we can't just play it fast and loose and\n\n // wrap. We might as well just try to seek (and likely fail).\n\n let mut offset = read_uint(r, major)?;\n\n while offset > i64::MAX as u64 {\n\n r.seek(SeekFrom::Current(i64::MAX))?;\n\n offset -= i64::MAX as u64;\n", "file_path": "dag-cbor/src/decode.rs", "rank": 35, "score": 39015.97746966416 }, { "content": " .checked_mul(2)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n remaining = remaining\n\n .checked_add(items)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n MajorKind::Tag => {\n\n // TODO: validate tag?\n\n r.seek(SeekFrom::Current(major.len() as i64))?;\n\n remaining = remaining\n\n .checked_add(1)\n\n .ok_or_else(LengthOutOfRange::new::<Self>)?;\n\n }\n\n };\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "dag-cbor/src/decode.rs", "rank": 36, "score": 39015.97746966416 }, { "content": " ),\n\n _ => {\n\n return Err(UnexpectedCode::new::<Self>(major).into());\n\n }\n\n };\n\n Ok(result)\n\n }\n\n}\n\n\n\nimpl SkipOne for DagCbor {\n\n fn skip<R: Read + Seek>(&self, r: &mut R) -> Result<()> {\n\n let mut remaining: u64 = 1;\n\n while remaining > 0 {\n\n remaining -= 1;\n\n let major = read_major(r)?;\n\n match major.kind() {\n\n MajorKind::UnsignedInt | MajorKind::NegativeInt | MajorKind::Other => {\n\n // TODO: validate?\n\n // minimal integer, valid float, etc?\n\n r.seek(SeekFrom::Current(major.len() as i64))?;\n", "file_path": "dag-cbor/src/decode.rs", "rank": 37, "score": 39015.97746966416 }, { "content": " let value = read_uint(r, major)?;\n\n match major.kind() {\n\n MajorKind::UnsignedInt | MajorKind::NegativeInt => (),\n\n _ => return Err(UnexpectedCode::new::<Self>(major.into()).into()),\n\n };\n\n\n\n let mut value = Self::try_from(value)\n\n .map_err(|_| NumberOutOfRange::new::<Self>())?;\n\n if major.kind() == MajorKind::NegativeInt {\n\n // This is guaranteed to not overflow.\n\n value = -1 - value;\n\n }\n\n Ok(value)\n\n }\n\n }\n\n )*\n\n };\n\n}\n\n\n\nimpl_num!(unsigned u8, u16, u32, u64, u128);\n", "file_path": "dag-cbor/src/decode.rs", "rank": 38, "score": 39015.97746966416 }, { "content": " MajorKind::ByteString => {\n\n let len = read_uint(r, major)?;\n\n Self::Bytes(read_bytes(r, len)?)\n\n }\n\n MajorKind::TextString => {\n\n let len = read_uint(r, major)?;\n\n Self::String(read_str(r, len)?)\n\n }\n\n MajorKind::Array => {\n\n let len = read_uint(r, major)?;\n\n Self::List(read_list(r, len)?)\n\n }\n\n MajorKind::Map => {\n\n let len = read_uint(r, major)?;\n\n Self::Map(read_map(r, len)?)\n\n }\n\n MajorKind::Tag => {\n\n let value = read_uint(r, major)?;\n\n if value == 42 {\n\n Self::Link(read_link(r)?)\n", "file_path": "dag-cbor/src/decode.rs", "rank": 39, "score": 39015.97746966416 }, { "content": "/// Encode trait.\n\n///\n\n/// This trait is generic over a codec, so that different codecs can be implemented for the same\n\n/// type.\n\npub trait Encode<C: Codec> {\n\n /// Encodes into a `impl Write`.\n\n ///\n\n /// It takes a specific codec as parameter, so that the [`Encode`] can be generic over an enum\n\n /// that contains multiple codecs.\n\n fn encode<W: Write>(&self, c: C, w: &mut W) -> Result<()>;\n\n}\n\n\n\nimpl<C: Codec, T: Encode<C>> Encode<C> for &T {\n\n fn encode<W: Write>(&self, c: C, w: &mut W) -> Result<()> {\n\n self.deref().encode(c, w)\n\n }\n\n}\n\n\n", "file_path": "core/src/codec.rs", "rank": 40, "score": 35879.08497337412 }, { "content": "/// References trait.\n\n///\n\n/// This trait is generic over a codec, so that different codecs can be implemented for the same\n\n/// type.\n\npub trait References<C: Codec>: Sized {\n\n /// Scrape the references from an `impl Read`.\n\n ///\n\n /// It takes a specific codec as parameter, so that the [`References`] can be generic over an\n\n /// enum that contains multiple codecs.\n\n fn references<R: Read + Seek, E: Extend<Cid>>(c: C, r: &mut R, set: &mut E) -> Result<()>;\n\n}\n\n\n", "file_path": "core/src/codec.rs", "rank": 41, "score": 35163.048235259914 }, { "content": "/// Decode trait.\n\n///\n\n/// This trait is generic over a codec, so that different codecs can be implemented for the same\n\n/// type.\n\npub trait Decode<C: Codec>: Sized {\n\n /// Decode from an `impl Read`.\n\n ///\n\n /// It takes a specific codec as parameter, so that the [`Decode`] can be generic over an enum\n\n /// that contains multiple codecs.\n\n fn decode<R: Read + Seek>(c: C, r: &mut R) -> Result<Self>;\n\n}\n\n\n", "file_path": "core/src/codec.rs", "rank": 42, "score": 34717.1584887546 }, { "content": "#[allow(clippy::needless_collect)]\n\nfn gen_encode_union(u: &Union) -> TokenStream {\n\n let arms = u\n\n .variants\n\n .iter()\n\n .enumerate()\n\n .map(|(i, s)| {\n\n let pat = &*s.pat;\n\n let key = rename(&syn::Member::Named(s.name.clone()), s.rename.as_ref());\n\n let value = gen_encode_struct_body(s);\n\n match u.repr {\n\n UnionRepr::Keyed => {\n\n quote! {\n\n #pat => {\n\n write_u8(w, MajorKind::Map, 1)?;\n\n Encode::encode(#key, c, w)?;\n\n #value\n\n }\n\n }\n\n }\n\n UnionRepr::Kinded => {\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 43, "score": 32220.98390217518 }, { "content": "fn gen_encode_struct(s: &Struct) -> TokenStream {\n\n let pat = &*s.pat;\n\n let body = gen_encode_struct_body(s);\n\n gen_encode_match(std::iter::once(quote!(#pat => { #body })))\n\n}\n\n\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 44, "score": 32220.98390217518 }, { "content": "fn gen_decode_struct(s: &Struct) -> TokenStream {\n\n let len = s.fields.len() as u64;\n\n let construct = &*s.construct;\n\n match s.repr {\n\n StructRepr::Map => {\n\n let binding: Vec<_> = s.fields.iter().map(|field| &field.binding).collect();\n\n let key: Vec<_> = s\n\n .fields\n\n .iter()\n\n .map(|field| rename(&field.name, field.rename.as_ref()))\n\n .collect();\n\n let fields: Vec<_> = s\n\n .fields\n\n .iter()\n\n .map(|field| {\n\n let binding = &field.binding;\n\n let key = rename(&field.name, field.rename.as_ref());\n\n if let Some(default) = field.default.as_ref() {\n\n quote!(let #binding = #binding.unwrap_or(#default);)\n\n } else {\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 45, "score": 32061.347221430657 }, { "content": "fn gen_decode_union(u: &Union) -> TokenStream {\n\n match u.repr {\n\n UnionRepr::Keyed => {\n\n let variants = u.variants.iter().map(|s| {\n\n let key = rename(&syn::Member::Named(s.name.clone()), s.rename.as_ref());\n\n let parse = gen_decode_struct(s);\n\n quote! {\n\n if key.as_str() == #key {\n\n #parse\n\n }\n\n }\n\n });\n\n quote! {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::Map {\n\n return Err(UnexpectedCode::new::<Self>(major.into()).into());\n\n } else if read_uint(r, major)? != 1 {\n\n return Err(LengthOutOfRange::new::<Self>().into());\n\n }\n\n let key: String = Decode::decode(c, r)?;\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 46, "score": 32061.347221430657 }, { "content": "/// Writes a null byte to a cbor encoded byte stream.\n\npub fn write_null<W: Write>(w: &mut W) -> Result<()> {\n\n w.write_all(&[0xf6])?;\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 47, "score": 31425.0051880281 }, { "content": "fn gen_encode_struct_body(s: &Struct) -> TokenStream {\n\n match s.repr {\n\n StructRepr::Map => {\n\n let len = s.fields.len() as u64;\n\n let dfields = s.fields.iter().filter_map(|field| {\n\n if let Some(default) = field.default.as_ref() {\n\n let binding = &field.binding;\n\n let default = &*default;\n\n Some(quote! {\n\n if #binding == &#default {\n\n len -= 1;\n\n }\n\n })\n\n } else {\n\n None\n\n }\n\n });\n\n let mut cbor_order = s\n\n .fields\n\n .iter()\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 48, "score": 31420.870174727123 }, { "content": "/// Read a and validate major \"byte\". This includes both the major type and the additional info.\n\npub fn read_major<R: Read>(r: &mut R) -> Result<Major> {\n\n Ok(Major::try_from(read_u8(r)?)?)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 49, "score": 30507.62999978796 }, { "content": "/// Reads a u64 from a byte stream.\n\npub fn read_u64<R: Read>(r: &mut R) -> Result<u64> {\n\n let mut buf = [0; 8];\n\n r.read_exact(&mut buf)?;\n\n Ok(BigEndian::read_u64(&buf))\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 50, "score": 30507.62999978796 }, { "content": "pub fn decode<R: Read>(r: &mut R) -> Result<Ipld, Error> {\n\n let mut de = serde_json::Deserializer::from_reader(r);\n\n deserialize(&mut de)\n\n}\n\n\n", "file_path": "dag-json/src/codec.rs", "rank": 51, "score": 30507.62999978796 }, { "content": "/// Reads a u16 from a byte stream.\n\npub fn read_u16<R: Read>(r: &mut R) -> Result<u16> {\n\n let mut buf = [0; 2];\n\n r.read_exact(&mut buf)?;\n\n Ok(BigEndian::read_u16(&buf))\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 52, "score": 30507.62999978796 }, { "content": "/// Reads a u32 from a byte stream.\n\npub fn read_u32<R: Read>(r: &mut R) -> Result<u32> {\n\n let mut buf = [0; 4];\n\n r.read_exact(&mut buf)?;\n\n Ok(BigEndian::read_u32(&buf))\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 53, "score": 30507.62999978796 }, { "content": "/// Reads a f32 from a byte stream.\n\npub fn read_f32<R: Read>(r: &mut R) -> Result<f32> {\n\n let mut buf = [0; 4];\n\n r.read_exact(&mut buf)?;\n\n Ok(BigEndian::read_f32(&buf))\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 54, "score": 30507.62999978796 }, { "content": "/// Reads a u8 from a byte stream.\n\npub fn read_u8<R: Read>(r: &mut R) -> Result<u8> {\n\n let mut buf = [0; 1];\n\n r.read_exact(&mut buf)?;\n\n Ok(buf[0])\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 55, "score": 30507.62999978796 }, { "content": "/// Reads a f64 from a byte stream.\n\npub fn read_f64<R: Read>(r: &mut R) -> Result<f64> {\n\n let mut buf = [0; 8];\n\n r.read_exact(&mut buf)?;\n\n Ok(BigEndian::read_f64(&buf))\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 56, "score": 30507.62999978796 }, { "content": "/// Get the name of a crate based on its original name.\n\n///\n\n/// This works even if the crate was renamed in the `Cargo.toml` file. If the crate is not a\n\n/// dependency, it will lead to a compile-time error.\n\nfn use_crate(name: &str) -> Result<syn::Ident, TokenStream> {\n\n match crate_name(name) {\n\n Ok(FoundCrate::Name(n)) => Ok(syn::Ident::new(&n, Span::call_site())),\n\n Ok(FoundCrate::Itself) => Ok(syn::Ident::new(\"crate\", Span::call_site())),\n\n Err(err) => Err(syn::Error::new(Span::call_site(), err).to_compile_error()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn test() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"examples/basic.rs\");\n\n t.pass(\"examples/name_attr.rs\");\n\n t.pass(\"examples/repr_attr.rs\");\n\n }\n\n}\n", "file_path": "dag-cbor-derive/src/lib.rs", "rank": 57, "score": 30168.45479331575 }, { "content": "/// Writes a tag to a cbor encoded byte stream.\n\npub fn write_tag<W: Write>(w: &mut W, tag: u64) -> Result<()> {\n\n write_u64(w, MajorKind::Tag, tag)\n\n}\n\n\n\nimpl Encode<DagCbor> for bool {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n let buf = if *self { [TRUE.into()] } else { [FALSE.into()] };\n\n w.write_all(&buf)?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for u8 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n\n write_u8(w, MajorKind::UnsignedInt, *self)\n\n }\n\n}\n\n\n\nimpl Encode<DagCbor> for u16 {\n\n fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {\n", "file_path": "dag-cbor/src/encode.rs", "rank": 58, "score": 29938.41576257338 }, { "content": "/// Reads a cid from a stream of cbor encoded bytes.\n\npub fn read_link<R: Read + Seek>(r: &mut R) -> Result<Cid> {\n\n let major = read_major(r)?;\n\n if major.kind() != MajorKind::ByteString {\n\n return Err(UnexpectedCode::new::<Cid>(major.into()).into());\n\n }\n\n let len = read_uint(r, major)?;\n\n if len < 1 {\n\n return Err(LengthOutOfRange::new::<Cid>().into());\n\n }\n\n\n\n let mut r = r.take(len);\n\n\n\n // skip the first byte per\n\n // https://github.com/ipld/specs/blob/master/block-layer/codecs/dag-cbor.md#links\n\n let prefix = read_u8(&mut r)?;\n\n if prefix != 0 {\n\n return Err(InvalidCidPrefix(prefix).into());\n\n }\n\n\n\n // Read the CID. No need to limit the size, the CID will do this for us.\n\n let cid = Cid::read_bytes(&mut r)?;\n\n\n\n // Make sure we've read the entire CID.\n\n if r.read(&mut [0u8][..])? != 0 {\n\n return Err(LengthOutOfRange::new::<Cid>().into());\n\n }\n\n\n\n Ok(cid)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 59, "score": 29790.108732176333 }, { "content": "pub fn encode<W: Write>(ipld: &Ipld, writer: &mut W) -> Result<(), Error> {\n\n let mut ser = Serializer::new(writer);\n\n serialize(ipld, &mut ser)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-json/src/codec.rs", "rank": 60, "score": 29242.4206647397 }, { "content": "/// Read the uint argument to the given major type. This function errors if:\n\n/// 1. The major type doesn't expect an integer argument.\n\n/// 2. The integer argument is not \"minimally\" encoded per the IPLD spec.\n\npub fn read_uint<R: Read>(r: &mut R, major: Major) -> Result<u64> {\n\n const MAX_SHORT: u64 = 23;\n\n const MAX_1BYTE: u64 = u8::MAX as u64;\n\n const MAX_2BYTE: u64 = u16::MAX as u64;\n\n const MAX_4BYTE: u64 = u32::MAX as u64;\n\n if major.kind() == MajorKind::Other {\n\n return Err(UnexpectedCode::new::<u64>(major.into()).into());\n\n }\n\n match major.info() {\n\n value @ 0..=23 => Ok(value as u64),\n\n 24 => match read_u8(r)? as u64 {\n\n 0..=MAX_SHORT => Err(NumberNotMinimal.into()),\n\n value => Ok(value),\n\n },\n\n 25 => match read_u16(r)? as u64 {\n\n 0..=MAX_1BYTE => Err(NumberNotMinimal.into()),\n\n value => Ok(value),\n\n },\n\n 26 => match read_u32(r)? as u64 {\n\n 0..=MAX_2BYTE => Err(NumberNotMinimal.into()),\n", "file_path": "dag-cbor/src/decode.rs", "rank": 61, "score": 29100.916693366933 }, { "content": "/// Reads `len` number of bytes from a byte stream and converts them to a string.\n\npub fn read_str<R: Read>(r: &mut R, len: u64) -> Result<String> {\n\n let bytes = read_bytes(r, len)?;\n\n Ok(String::from_utf8(bytes)?)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 62, "score": 29097.54107366244 }, { "content": "pub fn gen_encode(ast: &SchemaType, libipld: &syn::Ident) -> TokenStream {\n\n let (ident, generics, body) = match ast {\n\n SchemaType::Struct(s) => (&s.name, s.generics.as_ref().unwrap(), gen_encode_struct(s)),\n\n SchemaType::Union(u) => (&u.name, &u.generics, gen_encode_union(u)),\n\n };\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n let trait_name = quote!(#libipld::codec::Encode<#libipld::cbor::DagCborCodec>);\n\n\n\n quote! {\n\n impl#impl_generics #trait_name for #ident #ty_generics #where_clause {\n\n fn encode<W: std::io::Write>(\n\n &self,\n\n c: #libipld::cbor::DagCborCodec,\n\n w: &mut W,\n\n ) -> #libipld::Result<()> {\n\n use #libipld::codec::Encode;\n\n use #libipld::cbor::cbor::MajorKind;\n\n use #libipld::cbor::encode::{write_null, write_u8, write_u64};\n\n #body\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 63, "score": 28581.881088076203 }, { "content": "fn gen_encode_match(arms: impl Iterator<Item = TokenStream>) -> TokenStream {\n\n quote! {\n\n match *self {\n\n #(#arms,)*\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 64, "score": 28581.881088076203 }, { "content": "pub fn gen_decode(ast: &SchemaType, libipld: &syn::Ident) -> TokenStream {\n\n let (ident, generics, body) = match ast {\n\n SchemaType::Struct(s) => (&s.name, s.generics.as_ref().unwrap(), gen_decode_struct(s)),\n\n SchemaType::Union(u) => (&u.name, &u.generics, gen_decode_union(u)),\n\n };\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n let trait_name = quote!(#libipld::codec::Decode<#libipld::cbor::DagCborCodec>);\n\n\n\n quote! {\n\n impl#impl_generics #trait_name for #ident #ty_generics #where_clause {\n\n fn decode<R: std::io::Read + std::io::Seek>(\n\n c: #libipld::cbor::DagCborCodec,\n\n r: &mut R,\n\n ) -> #libipld::Result<Self> {\n\n use #libipld::cbor::cbor::{MajorKind, NULL};\n\n use #libipld::cbor::decode::{read_uint, read_major};\n\n use #libipld::cbor::error::{LengthOutOfRange, MissingKey, UnexpectedCode, UnexpectedKey};\n\n use #libipld::codec::Decode;\n\n use #libipld::error::Result;\n\n use std::io::SeekFrom;\n\n #body\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "dag-cbor-derive/src/gen.rs", "rank": 65, "score": 28440.274095558907 }, { "content": "/// Reads `len` number of bytes from a byte stream.\n\npub fn read_bytes<R: Read>(r: &mut R, len: u64) -> Result<Vec<u8>> {\n\n let len = usize::try_from(len).map_err(|_| LengthOutOfRange::new::<usize>())?;\n\n // Limit up-front allocations to 16KiB as the length is user controlled.\n\n let mut buf = Vec::with_capacity(len.min(16 * 1024));\n\n r.take(len as u64).read_to_end(&mut buf)?;\n\n if buf.len() != len {\n\n return Err(UnexpectedEof.into());\n\n }\n\n Ok(buf)\n\n}\n\n\n", "file_path": "dag-cbor/src/decode.rs", "rank": 66, "score": 28440.274095558907 }, { "content": "/// Writes a u64 to a cbor encoded byte stream.\n\npub fn write_u64<W: Write>(w: &mut W, major: MajorKind, value: u64) -> Result<()> {\n\n if value <= u64::from(u32::max_value()) {\n\n write_u32(w, major, value as u32)?;\n\n } else {\n\n let mut buf = [(major as u8) << 5 | 27, 0, 0, 0, 0, 0, 0, 0, 0];\n\n BigEndian::write_u64(&mut buf[1..], value);\n\n w.write_all(&buf)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 67, "score": 27954.725950470824 }, { "content": "/// Writes a u32 to a cbor encoded byte stream.\n\npub fn write_u32<W: Write>(w: &mut W, major: MajorKind, value: u32) -> Result<()> {\n\n if value <= u32::from(u16::max_value()) {\n\n write_u16(w, major, value as u16)?;\n\n } else {\n\n let mut buf = [(major as u8) << 5 | 26, 0, 0, 0, 0];\n\n BigEndian::write_u32(&mut buf[1..], value);\n\n w.write_all(&buf)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 68, "score": 27954.725950470824 }, { "content": "/// Writes a u8 to a cbor encoded byte stream.\n\npub fn write_u8<W: Write>(w: &mut W, major: MajorKind, value: u8) -> Result<()> {\n\n let major = major as u8;\n\n if value <= 0x17 {\n\n let buf = [major << 5 | value];\n\n w.write_all(&buf)?;\n\n } else {\n\n let buf = [major << 5 | 24, value];\n\n w.write_all(&buf)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 69, "score": 27954.725950470824 }, { "content": "/// Writes a u16 to a cbor encoded byte stream.\n\npub fn write_u16<W: Write>(w: &mut W, major: MajorKind, value: u16) -> Result<()> {\n\n if value <= u16::from(u8::max_value()) {\n\n write_u8(w, major, value as u8)?;\n\n } else {\n\n let mut buf = [(major as u8) << 5 | 25, 0, 0];\n\n BigEndian::write_u16(&mut buf[1..], value);\n\n w.write_all(&buf)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "dag-cbor/src/encode.rs", "rank": 70, "score": 27954.725950470824 }, { "content": "//! Prelude\n\npub use crate::cache::Cache;\n\npub use crate::codec::{Codec, Decode, Encode, References};\n\npub use crate::store::{Store, StoreParams};\n", "file_path": "src/prelude.rs", "rank": 71, "score": 14.981663431458292 }, { "content": " pub fn ipld(&self) -> Result<Ipld>\n\n where\n\n Ipld: Decode<S::Codecs>,\n\n {\n\n self.decode::<S::Codecs, Ipld>()\n\n }\n\n\n\n /// Returns the references.\n\n pub fn references<E: Extend<Cid>>(&self, set: &mut E) -> Result<()>\n\n where\n\n Ipld: References<S::Codecs>,\n\n {\n\n S::Codecs::try_from(self.cid.codec())?.references::<Ipld, E>(&self.data, set)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::cbor::DagCborCodec;\n", "file_path": "src/block.rs", "rank": 72, "score": 11.613958757355608 }, { "content": "//! Block validation\n\nuse crate::cid::Cid;\n\nuse crate::codec::{Codec, Decode, Encode, References};\n\nuse crate::error::{BlockTooLarge, InvalidMultihash, Result, UnsupportedMultihash};\n\nuse crate::ipld::Ipld;\n\nuse crate::multihash::MultihashDigest;\n\nuse crate::store::StoreParams;\n\nuse core::borrow::Borrow;\n\nuse core::convert::TryFrom;\n\nuse core::marker::PhantomData;\n\nuse core::ops::Deref;\n\n\n\n/// Block\n\n#[derive(Clone)]\n\npub struct Block<S> {\n\n _marker: PhantomData<S>,\n\n /// Content identifier.\n\n cid: Cid,\n\n /// Binary data.\n\n data: Vec<u8>,\n", "file_path": "src/block.rs", "rank": 73, "score": 11.09573187690329 }, { "content": "use libipld::cbor::DagCborCodec;\n\nuse libipld::codec::{Decode, Encode};\n\nuse libipld::ipld::Ipld;\n\nuse libipld::{ipld, DagCbor};\n\nuse std::io::Cursor;\n\n\n\n#[derive(Clone, Debug, Default, PartialEq, DagCbor)]\n", "file_path": "dag-cbor-derive/examples/name_attr.rs", "rank": 74, "score": 10.905275903869509 }, { "content": "//! Implements the raw codec.\n\nuse alloc::{boxed::Box, vec, vec::Vec};\n\nuse core::{convert::TryFrom, iter::Extend};\n\n\n\nuse crate::cid::Cid;\n\nuse crate::codec::{Codec, Decode, Encode, References};\n\nuse crate::error::{Result, UnsupportedCodec};\n\nuse crate::io::{Read, Seek, Write};\n\nuse crate::ipld::Ipld;\n\n\n\n/// Raw codec.\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct RawCodec;\n\n\n\nimpl Codec for RawCodec {}\n\n\n\nimpl From<RawCodec> for u64 {\n\n fn from(_: RawCodec) -> Self {\n\n 0x55\n\n }\n", "file_path": "core/src/raw.rs", "rank": 75, "score": 10.878610848263554 }, { "content": "//! Cache\n\nuse crate::block::Block;\n\nuse crate::cid::Cid;\n\nuse crate::codec::{Codec, Decode, Encode, References};\n\nuse crate::error::Result;\n\nuse crate::ipld::Ipld;\n\nuse crate::store::{Store, StoreParams};\n\nuse async_trait::async_trait;\n\nuse cached::stores::SizedCache;\n\nuse cached::Cached;\n\nuse parking_lot::Mutex;\n\nuse std::ops::Deref;\n\n\n\n/// Cache for ipld blocks.\n\n#[derive(Debug)]\n\npub struct IpldCache<S: Store, C, T> {\n\n store: S,\n\n codec: C,\n\n hash: <S::Params as StoreParams>::Hashes,\n\n cache: Mutex<SizedCache<Cid, T>>,\n", "file_path": "src/cache.rs", "rank": 76, "score": 10.847855865137769 }, { "content": "//! Protobuf codec.\n\n#![deny(missing_docs)]\n\n#![deny(warnings)]\n\n\n\npub use crate::codec::{PbLink, PbNode};\n\nuse core::convert::{TryFrom, TryInto};\n\nuse libipld_core::cid::Cid;\n\nuse libipld_core::codec::{Codec, Decode, Encode, References};\n\nuse libipld_core::error::{Result, UnsupportedCodec};\n\nuse libipld_core::ipld::Ipld;\n\nuse std::io::{Read, Seek, Write};\n\n\n\nmod codec;\n\n\n\n/// Protobuf codec.\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct DagPbCodec;\n\n\n\nimpl Codec for DagPbCodec {}\n\n\n", "file_path": "dag-pb/src/lib.rs", "rank": 77, "score": 10.698763308785598 }, { "content": " }\n\n}\n\n\n\nimpl<T> References<RawCodec> for T {\n\n fn references<R: Read, E: Extend<Cid>>(_c: RawCodec, _r: &mut R, _set: &mut E) -> Result<()> {\n\n Ok(())\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_raw_codec() {\n\n let data: &[u8] = &[0, 1, 2, 3];\n\n let bytes = RawCodec.encode(data).unwrap();\n\n assert_eq!(data, &*bytes);\n\n let data2: Vec<u8> = RawCodec.decode(&bytes).unwrap();\n\n assert_eq!(data, &*data2);\n\n\n\n let ipld = Ipld::Bytes(data2);\n\n let bytes = RawCodec.encode(&ipld).unwrap();\n\n assert_eq!(data, &*bytes);\n\n let ipld2: Ipld = RawCodec.decode(&bytes).unwrap();\n\n assert_eq!(ipld, ipld2);\n\n }\n\n}\n", "file_path": "core/src/raw.rs", "rank": 78, "score": 10.650664964567449 }, { "content": "use libipld_cbor::DagCborCodec;\n\nuse libipld_core::{\n\n codec::{assert_roundtrip, Codec, Decode, Encode},\n\n ipld::Ipld,\n\n raw_value::{IgnoredAny, RawValue, SkipOne},\n\n};\n\nuse std::{io::Cursor, result};\n\n\n\n#[test]\n", "file_path": "dag-cbor/tests/roundtrip.rs", "rank": 79, "score": 10.57736856286161 }, { "content": "//! Json codec.\n\n#![deny(missing_docs)]\n\n#![deny(warnings)]\n\n\n\nuse core::convert::TryFrom;\n\nuse libipld_core::cid::Cid;\n\nuse libipld_core::codec::{Codec, Decode, Encode, References};\n\nuse libipld_core::error::{Result, UnsupportedCodec};\n\nuse libipld_core::ipld::Ipld;\n\n// TODO vmx 2020-05-28: Don't expose the `serde_json` error directly, but wrap it in a custom one\n\npub use serde_json::Error;\n\nuse std::io::{Read, Seek, Write};\n\n\n\nmod codec;\n\n\n\n/// Json codec.\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct DagJsonCodec;\n\n\n\nimpl Codec for DagJsonCodec {}\n", "file_path": "dag-json/src/lib.rs", "rank": 81, "score": 10.305809340772303 }, { "content": "\n\n use crate::ipld::Ipld;\n\n use crate::serde::{from_ipld, to_ipld};\n\n\n\n /// Utility for testing (de)serialization of [`Ipld`].\n\n ///\n\n /// Checks if `data` and `ipld` match if they are encoded into each other.\n\n fn assert_roundtrip<T>(data: &T, ipld: &Ipld)\n\n where\n\n T: Serialize + DeserializeOwned + PartialEq + fmt::Debug,\n\n {\n\n let encoded: Ipld = to_ipld(&data).unwrap();\n\n assert_eq!(&encoded, ipld);\n\n let decoded: T = from_ipld(ipld.clone()).unwrap();\n\n assert_eq!(&decoded, data);\n\n }\n\n\n\n #[derive(Debug, Deserialize, PartialEq, Serialize)]\n\n struct Person {\n\n name: String,\n", "file_path": "core/src/serde/mod.rs", "rank": 82, "score": 10.268575272522298 }, { "content": "//! CBOR codec.\n\n#![deny(missing_docs)]\n\n#![deny(warnings)]\n\n\n\nuse core::convert::TryFrom;\n\nuse libipld_core::codec::{Codec, Decode, Encode};\n\npub use libipld_core::error::{Result, UnsupportedCodec};\n\n\n\npub mod cbor;\n\npub mod decode;\n\npub mod encode;\n\npub mod error;\n\n\n\n/// CBOR codec.\n\n#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct DagCborCodec;\n\n\n\nimpl Codec for DagCborCodec {}\n\n\n\nimpl From<DagCborCodec> for u64 {\n", "file_path": "dag-cbor/src/lib.rs", "rank": 83, "score": 10.092898499928328 }, { "content": " use crate::codec_impl::IpldCodec;\n\n use crate::ipld;\n\n use crate::ipld::Ipld;\n\n use crate::multihash::Code;\n\n use crate::store::DefaultParams;\n\n use fnv::FnvHashSet;\n\n\n\n type IpldBlock = Block<DefaultParams>;\n\n\n\n #[test]\n\n fn test_references() {\n\n let b1 = IpldBlock::encode(IpldCodec::Raw, Code::Blake3_256, &ipld!(&b\"cid1\"[..])).unwrap();\n\n let b2 = IpldBlock::encode(IpldCodec::DagJson, Code::Blake3_256, &ipld!(\"cid2\")).unwrap();\n\n let b3 = IpldBlock::encode(\n\n IpldCodec::DagPb,\n\n Code::Blake3_256,\n\n &ipld!({\n\n \"Data\": &b\"data\"[..],\n\n \"Links\": Ipld::List(vec![]),\n\n }),\n", "file_path": "src/block.rs", "rank": 84, "score": 10.053132360489798 }, { "content": "//! Typed cid.\n\nuse core::{\n\n cmp::Ordering,\n\n fmt,\n\n hash::{Hash, Hasher},\n\n marker::PhantomData,\n\n ops::Deref,\n\n};\n\n\n\nuse crate::cid::Cid;\n\nuse crate::codec::{Codec, Decode, Encode};\n\nuse crate::error::Result;\n\nuse crate::io::{Read, Seek, Write};\n\n\n\n/// Typed cid.\n\n#[derive(Debug)]\n\npub struct Link<T> {\n\n cid: Cid,\n\n _marker: PhantomData<T>,\n\n}\n", "file_path": "core/src/link.rs", "rank": 85, "score": 9.696702028649629 }, { "content": " \"encoded string {}\",\n\n std::str::from_utf8(&contact_encoded).unwrap()\n\n );\n\n\n\n assert_eq!(\n\n std::str::from_utf8(&contact_encoded).unwrap(),\n\n format!(r#\"{{\"details\":{{\"/\":\"{}\"}},\"name\":\"Hello World!\"}}\"#, cid)\n\n );\n\n\n\n let contact_decoded: Ipld = DagJsonCodec.decode(&contact_encoded).unwrap();\n\n assert_eq!(contact_decoded, contact);\n\n }\n\n}\n", "file_path": "dag-json/src/lib.rs", "rank": 87, "score": 9.056826896541882 }, { "content": "where\n\n Cid: Encode<C>,\n\n{\n\n fn encode<W: Write>(&self, c: C, w: &mut W) -> Result<()> {\n\n self.cid().encode(c, w)\n\n }\n\n}\n\n\n\nimpl<C: Codec, T> Decode<C> for Link<T>\n\nwhere\n\n Cid: Decode<C>,\n\n{\n\n fn decode<R: Read + Seek>(c: C, r: &mut R) -> Result<Self> {\n\n Ok(Self::new(Cid::decode(c, r)?))\n\n }\n\n}\n\n\n\nimpl<T> Deref for Link<T> {\n\n type Target = Cid;\n\n\n", "file_path": "core/src/link.rs", "rank": 88, "score": 8.74723043390557 }, { "content": " \"bytes\": vec![0, 1, 2, 3],\n\n \"map\": { \"float\": 0.0, \"string\": \"hello\" },\n\n \"link\": cid,\n\n });\n\n let bytes = DagCborCodec.encode(&ipld).unwrap();\n\n let ipld2 = DagCborCodec.decode(&bytes).unwrap();\n\n assert_eq!(ipld, ipld2);\n\n }\n\n\n\n #[test]\n\n fn test_references() {\n\n let cid = Cid::new_v1(0, Code::Blake3_256.digest(&b\"0\"[..]));\n\n let ipld = ipld!({\n\n \"list\": [true, cid],\n\n });\n\n let bytes = DagCborCodec.encode(&ipld).unwrap();\n\n let mut set = HashSet::new();\n\n DagCborCodec\n\n .references::<Ipld, _>(&bytes, &mut set)\n\n .unwrap();\n", "file_path": "dag-cbor/src/lib.rs", "rank": 89, "score": 8.706144683914474 }, { "content": " /// use libipld::store::DefaultParams;\n\n ///\n\n /// let block =\n\n /// Block::<DefaultParams>::encode(DagCborCodec, Code::Blake3_256, \"Hello World!\").unwrap();\n\n /// let ipld = block.decode::<DagCborCodec, Ipld>().unwrap();\n\n ///\n\n /// assert_eq!(ipld, Ipld::String(\"Hello World!\".to_string()));\n\n /// ```\n\n pub fn decode<CD: Codec, T: Decode<CD>>(&self) -> Result<T>\n\n where\n\n S::Codecs: Into<CD>,\n\n {\n\n debug_assert_eq!(\n\n Into::<u64>::into(CD::try_from(self.cid.codec()).unwrap()),\n\n Into::<u64>::into(S::Codecs::try_from(self.cid.codec()).unwrap()),\n\n );\n\n CD::try_from(self.cid.codec())?.decode(&self.data)\n\n }\n\n\n\n /// Returns the decoded ipld.\n", "file_path": "src/block.rs", "rank": 90, "score": 8.57688156413682 }, { "content": "\n\nimpl Decode<DagJsonCodec> for Ipld {\n\n fn decode<R: Read + Seek>(_: DagJsonCodec, r: &mut R) -> Result<Self> {\n\n Ok(codec::decode(r)?)\n\n }\n\n}\n\n\n\nimpl References<DagJsonCodec> for Ipld {\n\n fn references<R: Read + Seek, E: Extend<Cid>>(\n\n c: DagJsonCodec,\n\n r: &mut R,\n\n set: &mut E,\n\n ) -> Result<()> {\n\n Ipld::decode(c, r)?.references(set);\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "dag-json/src/lib.rs", "rank": 91, "score": 8.531149655524445 }, { "content": " let mh = hcode.digest(&data);\n\n let cid = Cid::new_v1(codec.into(), mh);\n\n Ok(Self {\n\n _marker: PhantomData,\n\n cid,\n\n data,\n\n })\n\n }\n\n\n\n /// Decodes a block.\n\n ///\n\n /// # Example\n\n ///\n\n /// Decoding to [`Ipld`]:\n\n ///\n\n /// ```\n\n /// use libipld::block::Block;\n\n /// use libipld::cbor::DagCborCodec;\n\n /// use libipld::ipld::Ipld;\n\n /// use libipld::multihash::Code;\n", "file_path": "src/block.rs", "rank": 92, "score": 8.364947855612797 }, { "content": " );\n\n }\n\n let ipld2: Ipld = Decode::decode(c, &mut Cursor::new(bytes.as_slice())).unwrap();\n\n assert_eq!(&ipld2, ipld);\n\n let data2: T = Decode::decode(c, &mut Cursor::new(bytes.as_slice())).unwrap();\n\n assert_eq!(&data2, data);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::ipld::Ipld;\n\n use anyhow::anyhow;\n\n\n\n #[derive(Clone, Copy, Debug)]\n\n struct CodecImpl;\n\n\n\n impl Codec for CodecImpl {}\n\n\n\n impl From<CodecImpl> for u64 {\n", "file_path": "core/src/codec.rs", "rank": 93, "score": 8.294061613774643 }, { "content": "//! Reference store implementation.\n\nuse crate::block::Block;\n\nuse crate::cid::Cid;\n\nuse crate::codec::References;\n\nuse crate::error::{BlockNotFound, Result};\n\nuse crate::ipld::Ipld;\n\nuse crate::store::{Store, StoreParams};\n\nuse async_trait::async_trait;\n\nuse fnv::{FnvHashMap, FnvHashSet};\n\nuse std::collections::BTreeMap;\n\nuse std::marker::PhantomData;\n\nuse std::sync::{Arc, Mutex};\n\n\n\n/// Temp pin.\n\n#[derive(Clone)]\n\npub struct TempPin(Arc<InnerTempPin>);\n\n\n", "file_path": "src/mem.rs", "rank": 94, "score": 8.262447512448135 }, { "content": "// serde deserializer visitor that is used by Deseraliazer to decode\n\n// json into IPLD.\n\nstruct JsonVisitor;\n\nimpl<'de> de::Visitor<'de> for JsonVisitor {\n\n type Value = Ipld;\n\n\n\n fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n fmt.write_str(\"any valid JSON value\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n self.visit_string(String::from(value))\n\n }\n\n\n\n fn visit_string<E>(self, value: String) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n Ok(Ipld::String(value))\n", "file_path": "dag-json/src/codec.rs", "rank": 95, "score": 8.146929814965139 }, { "content": "//! misc stuff\n\nuse alloc::{boxed::Box, vec, vec::Vec};\n\nuse core::{convert::TryFrom, marker::PhantomData};\n\n\n\nuse crate::codec::{Codec, Decode, Encode};\n\nuse crate::io::{Read, Seek, SeekFrom, Write};\n\n\n\n/// A raw value for a certain codec.\n\n///\n\n/// Contains the raw, unprocessed data for a single item for that particular codec\n\n#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]\n\npub struct RawValue<C> {\n\n data: Box<[u8]>,\n\n _p: PhantomData<C>,\n\n}\n\n\n\nimpl<C> RawValue<C> {\n\n fn new(data: Box<[u8]>) -> Self {\n\n Self {\n\n data,\n", "file_path": "core/src/raw_value.rs", "rank": 96, "score": 8.087201793573426 }, { "content": " use super::*;\n\n use libipld_core::cid::Cid;\n\n use libipld_core::multihash::{Code, MultihashDigest};\n\n use std::collections::BTreeMap;\n\n\n\n #[test]\n\n fn encode_struct() {\n\n let digest = Code::Blake3_256.digest(&b\"block\"[..]);\n\n let cid = Cid::new_v1(0x55, digest);\n\n\n\n // Create a contact object that looks like:\n\n // Contact { name: \"Hello World\", details: CID }\n\n let mut map = BTreeMap::new();\n\n map.insert(\"name\".to_string(), Ipld::String(\"Hello World!\".to_string()));\n\n map.insert(\"details\".to_string(), Ipld::Link(cid));\n\n let contact = Ipld::Map(map);\n\n\n\n let contact_encoded = DagJsonCodec.encode(&contact).unwrap();\n\n println!(\"encoded: {:02x?}\", contact_encoded);\n\n println!(\n", "file_path": "dag-json/src/lib.rs", "rank": 97, "score": 8.04316060128635 }, { "content": " }\n\n}\n\n\n\nimpl Decode<DagPbCodec> for Ipld {\n\n fn decode<R: Read + Seek>(_: DagPbCodec, r: &mut R) -> Result<Self> {\n\n let mut bytes = Vec::new();\n\n r.read_to_end(&mut bytes)?;\n\n Ok(PbNode::from_bytes(&bytes)?.into())\n\n }\n\n}\n\n\n\nimpl References<DagPbCodec> for Ipld {\n\n fn references<R: Read + Seek, E: Extend<Cid>>(\n\n c: DagPbCodec,\n\n r: &mut R,\n\n set: &mut E,\n\n ) -> Result<()> {\n\n Ipld::decode(c, r)?.references(set);\n\n Ok(())\n\n }\n", "file_path": "dag-pb/src/lib.rs", "rank": 98, "score": 7.914414854094224 }, { "content": "/// Utility for testing codecs.\n\n///\n\n/// Encodes the `data` using the codec `c` and checks that it matches the `ipld`.\n\npub fn assert_roundtrip<C, T>(c: C, data: &T, ipld: &Ipld)\n\nwhere\n\n C: Codec,\n\n T: Decode<C> + Encode<C> + core::fmt::Debug + PartialEq,\n\n Ipld: Decode<C> + Encode<C>,\n\n{\n\n fn hex(bytes: &[u8]) -> String {\n\n bytes.iter().map(|byte| format!(\"{:02x}\", byte)).collect()\n\n }\n\n let mut bytes = Vec::new();\n\n data.encode(c, &mut bytes).unwrap();\n\n let mut bytes2 = Vec::new();\n\n ipld.encode(c, &mut bytes2).unwrap();\n\n if bytes != bytes2 {\n\n panic!(\n\n r#\"assertion failed: `(left == right)`\n\n left: `{}`,\n\n right: `{}`\"#,\n\n hex(&bytes),\n\n hex(&bytes2)\n", "file_path": "core/src/codec.rs", "rank": 99, "score": 7.883560909367537 } ]
Rust
crates/sui-config/src/node.rs
MystenLabs/sui
b180b663c0b755c97ea37ad57ff636fb04f2e158
use crate::genesis; use crate::Config; use anyhow::Result; use debug_ignore::DebugIgnore; use multiaddr::Multiaddr; use narwhal_config::Committee as ConsensusCommittee; use narwhal_config::Parameters as ConsensusParameters; use narwhal_crypto::ed25519::Ed25519PublicKey; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use sui_types::base_types::SuiAddress; use sui_types::committee::StakeUnit; use sui_types::crypto::{KeyPair, PublicKeyBytes}; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct NodeConfig { #[serde(default = "default_key_pair")] pub key_pair: KeyPair, pub db_path: PathBuf, #[serde(default = "default_grpc_address")] pub network_address: Multiaddr, #[serde(default = "default_metrics_address")] pub metrics_address: SocketAddr, #[serde(default = "default_json_rpc_address")] pub json_rpc_address: SocketAddr, #[serde(skip_serializing_if = "Option::is_none")] pub consensus_config: Option<ConsensusConfig>, pub genesis: Genesis, } fn default_key_pair() -> KeyPair { sui_types::crypto::get_key_pair().1 } fn default_grpc_address() -> Multiaddr { use multiaddr::multiaddr; multiaddr!(Ip4([0, 0, 0, 0]), Tcp(8080u16)) } fn default_metrics_address() -> SocketAddr { use std::net::{IpAddr, Ipv4Addr}; SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184) } pub fn default_json_rpc_address() -> SocketAddr { use std::net::{IpAddr, Ipv4Addr}; SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000) } impl Config for NodeConfig {} impl NodeConfig { pub fn key_pair(&self) -> &KeyPair { &self.key_pair } pub fn public_key(&self) -> PublicKeyBytes { *self.key_pair.public_key_bytes() } pub fn sui_address(&self) -> SuiAddress { SuiAddress::from(self.public_key()) } pub fn db_path(&self) -> &Path { &self.db_path } pub fn network_address(&self) -> &Multiaddr { &self.network_address } pub fn consensus_config(&self) -> Option<&ConsensusConfig> { self.consensus_config.as_ref() } pub fn genesis(&self) -> Result<&genesis::Genesis> { self.genesis.genesis() } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct ConsensusConfig { pub consensus_address: Multiaddr, pub consensus_db_path: PathBuf, #[serde(skip_serializing)] #[serde(default)] pub narwhal_config: DebugIgnore<ConsensusParameters>, pub narwhal_committee: DebugIgnore<ConsensusCommittee<Ed25519PublicKey>>, } impl ConsensusConfig { pub fn address(&self) -> &Multiaddr { &self.consensus_address } pub fn db_path(&self) -> &Path { &self.consensus_db_path } pub fn narwhal_config(&self) -> &ConsensusParameters { &self.narwhal_config } pub fn narwhal_committee(&self) -> &ConsensusCommittee<Ed25519PublicKey> { &self.narwhal_committee } } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub struct ValidatorInfo { pub public_key: PublicKeyBytes, pub stake: StakeUnit, pub network_address: Multiaddr, } impl ValidatorInfo { pub fn sui_address(&self) -> SuiAddress { SuiAddress::from(self.public_key()) } pub fn public_key(&self) -> PublicKeyBytes { self.public_key } pub fn stake(&self) -> StakeUnit { self.stake } pub fn network_address(&self) -> &Multiaddr { &self.network_address } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Genesis { #[serde(flatten)] location: GenesisLocation, #[serde(skip)] genesis: once_cell::sync::OnceCell<genesis::Genesis>, } impl Genesis { pub fn new(genesis: genesis::Genesis) -> Self { Self { location: GenesisLocation::InPlace { genesis }, genesis: Default::default(), } } pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self { Self { location: GenesisLocation::File { genesis_file_location: path.into(), }, genesis: Default::default(), } } fn genesis(&self) -> Result<&genesis::Genesis> { match &self.location { GenesisLocation::InPlace { genesis } => Ok(genesis), GenesisLocation::File { genesis_file_location, } => self .genesis .get_or_try_init(|| genesis::Genesis::load(&genesis_file_location)), } } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(untagged)] enum GenesisLocation { InPlace { genesis: genesis::Genesis, }, File { #[serde(rename = "genesis-file-location")] genesis_file_location: PathBuf, }, } #[cfg(test)] mod tests { use super::Genesis; use crate::genesis; #[test] fn serialize_genesis_config_from_file() { let g = Genesis::new_from_file("path/to/file"); let s = serde_yaml::to_string(&g).unwrap(); assert_eq!("---\ngenesis-file-location: path/to/file\n", s); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); } #[test] fn serialize_genesis_config_in_place() { let g = Genesis::new(genesis::Genesis::get_default_genesis()); let mut s = serde_yaml::to_string(&g).unwrap(); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); s.push_str("\ngenesis-file-location: path/to/file"); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); } #[test] fn load_genesis_config_from_file() { let file = tempfile::NamedTempFile::new().unwrap(); let genesis_config = Genesis::new_from_file(file.path()); let genesis = genesis::Genesis::get_default_genesis(); genesis.save(file.path()).unwrap(); let loaded_genesis = genesis_config.genesis().unwrap(); assert_eq!(&genesis, loaded_genesis); } }
use crate::genesis; use crate::Config; use anyhow::Result; use debug_ignore::DebugIgnore; use multiaddr::Multiaddr; use narwhal_config::Committee as ConsensusCommittee; use narwhal_config::Parameters as ConsensusParameters; use narwhal_crypto::ed25519::Ed25519PublicKey; use serde::{Deserialize, Serialize}; use std::net::SocketAddr; use std::path::{Path, PathBuf}; use sui_types::base_types::SuiAddress; use sui_types::committee::StakeUnit; use sui_types::crypto::{KeyPair, PublicKeyBytes}; #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct NodeConfig { #[serde(default = "default_key_pair")] pub key_pair: KeyPair, pub db_path: PathBuf, #[serde(default = "default_grpc_address")] pub network_ad
#[serde(skip)] genesis: once_cell::sync::OnceCell<genesis::Genesis>, } impl Genesis { pub fn new(genesis: genesis::Genesis) -> Self { Self { location: GenesisLocation::InPlace { genesis }, genesis: Default::default(), } } pub fn new_from_file<P: Into<PathBuf>>(path: P) -> Self { Self { location: GenesisLocation::File { genesis_file_location: path.into(), }, genesis: Default::default(), } } fn genesis(&self) -> Result<&genesis::Genesis> { match &self.location { GenesisLocation::InPlace { genesis } => Ok(genesis), GenesisLocation::File { genesis_file_location, } => self .genesis .get_or_try_init(|| genesis::Genesis::load(&genesis_file_location)), } } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] #[serde(untagged)] enum GenesisLocation { InPlace { genesis: genesis::Genesis, }, File { #[serde(rename = "genesis-file-location")] genesis_file_location: PathBuf, }, } #[cfg(test)] mod tests { use super::Genesis; use crate::genesis; #[test] fn serialize_genesis_config_from_file() { let g = Genesis::new_from_file("path/to/file"); let s = serde_yaml::to_string(&g).unwrap(); assert_eq!("---\ngenesis-file-location: path/to/file\n", s); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); } #[test] fn serialize_genesis_config_in_place() { let g = Genesis::new(genesis::Genesis::get_default_genesis()); let mut s = serde_yaml::to_string(&g).unwrap(); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); s.push_str("\ngenesis-file-location: path/to/file"); let loaded_genesis: Genesis = serde_yaml::from_str(&s).unwrap(); assert_eq!(g, loaded_genesis); } #[test] fn load_genesis_config_from_file() { let file = tempfile::NamedTempFile::new().unwrap(); let genesis_config = Genesis::new_from_file(file.path()); let genesis = genesis::Genesis::get_default_genesis(); genesis.save(file.path()).unwrap(); let loaded_genesis = genesis_config.genesis().unwrap(); assert_eq!(&genesis, loaded_genesis); } }
dress: Multiaddr, #[serde(default = "default_metrics_address")] pub metrics_address: SocketAddr, #[serde(default = "default_json_rpc_address")] pub json_rpc_address: SocketAddr, #[serde(skip_serializing_if = "Option::is_none")] pub consensus_config: Option<ConsensusConfig>, pub genesis: Genesis, } fn default_key_pair() -> KeyPair { sui_types::crypto::get_key_pair().1 } fn default_grpc_address() -> Multiaddr { use multiaddr::multiaddr; multiaddr!(Ip4([0, 0, 0, 0]), Tcp(8080u16)) } fn default_metrics_address() -> SocketAddr { use std::net::{IpAddr, Ipv4Addr}; SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9184) } pub fn default_json_rpc_address() -> SocketAddr { use std::net::{IpAddr, Ipv4Addr}; SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 9000) } impl Config for NodeConfig {} impl NodeConfig { pub fn key_pair(&self) -> &KeyPair { &self.key_pair } pub fn public_key(&self) -> PublicKeyBytes { *self.key_pair.public_key_bytes() } pub fn sui_address(&self) -> SuiAddress { SuiAddress::from(self.public_key()) } pub fn db_path(&self) -> &Path { &self.db_path } pub fn network_address(&self) -> &Multiaddr { &self.network_address } pub fn consensus_config(&self) -> Option<&ConsensusConfig> { self.consensus_config.as_ref() } pub fn genesis(&self) -> Result<&genesis::Genesis> { self.genesis.genesis() } } #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "kebab-case")] pub struct ConsensusConfig { pub consensus_address: Multiaddr, pub consensus_db_path: PathBuf, #[serde(skip_serializing)] #[serde(default)] pub narwhal_config: DebugIgnore<ConsensusParameters>, pub narwhal_committee: DebugIgnore<ConsensusCommittee<Ed25519PublicKey>>, } impl ConsensusConfig { pub fn address(&self) -> &Multiaddr { &self.consensus_address } pub fn db_path(&self) -> &Path { &self.consensus_db_path } pub fn narwhal_config(&self) -> &ConsensusParameters { &self.narwhal_config } pub fn narwhal_committee(&self) -> &ConsensusCommittee<Ed25519PublicKey> { &self.narwhal_committee } } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] pub struct ValidatorInfo { pub public_key: PublicKeyBytes, pub stake: StakeUnit, pub network_address: Multiaddr, } impl ValidatorInfo { pub fn sui_address(&self) -> SuiAddress { SuiAddress::from(self.public_key()) } pub fn public_key(&self) -> PublicKeyBytes { self.public_key } pub fn stake(&self) -> StakeUnit { self.stake } pub fn network_address(&self) -> &Multiaddr { &self.network_address } } #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] pub struct Genesis { #[serde(flatten)] location: GenesisLocation,
random
[ { "content": "#[serde_as]\n\n#[derive(Eq, PartialEq, Clone, Copy, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n\nstruct ObjectKey(pub ObjectID, pub VersionNumber);\n\n\n\nimpl ObjectKey {\n\n pub const ZERO: ObjectKey = ObjectKey(ObjectID::ZERO, VersionNumber::MIN);\n\n\n\n pub fn max_for_id(id: &ObjectID) -> Self {\n\n Self(*id, VersionNumber::MAX)\n\n }\n\n}\n\n\n\nimpl From<ObjectRef> for ObjectKey {\n\n fn from(object_ref: ObjectRef) -> Self {\n\n (&object_ref).into()\n\n }\n\n}\n\n\n\nimpl From<&ObjectRef> for ObjectKey {\n\n fn from(object_ref: &ObjectRef) -> Self {\n\n Self(object_ref.0, object_ref.1)\n\n }\n", "file_path": "crates/sui-core/src/authority/authority_store.rs", "rank": 0, "score": 176178.3304984197 }, { "content": "/// Activate the blanket implementation of `Signable` based on serde and BCS.\n\n/// * We use `serde_name` to extract a seed from the name of structs and enums.\n\n/// * We use `BCS` to generate canonical bytes suitable for hashing and signing.\n\npub trait BcsSignable: Serialize + serde::de::DeserializeOwned {}\n\n\n\nimpl<T, W> Signable<W> for T\n\nwhere\n\n T: BcsSignable,\n\n W: std::io::Write,\n\n{\n\n fn write(&self, writer: &mut W) {\n\n let name = serde_name::trace_name::<Self>().expect(\"Self must be a struct or an enum\");\n\n // Note: This assumes that names never contain the separator `::`.\n\n write!(writer, \"{}::\", name).expect(\"Hasher should not fail\");\n\n bcs::serialize_into(writer, &self).expect(\"Message serialization should not fail\");\n\n }\n\n}\n\n\n\nimpl<T> SignableBytes for T\n\nwhere\n\n T: BcsSignable,\n\n{\n\n fn from_signable_bytes(bytes: &[u8]) -> Result<Self, Error> {\n\n // Remove name tag before deserialization using BCS\n\n let name = serde_name::trace_name::<Self>().expect(\"Self must be a struct or an enum\");\n\n let name_byte_len = format!(\"{}::\", name).bytes().len();\n\n Ok(bcs::from_bytes(&bytes[name_byte_len..])?)\n\n }\n\n}\n\n\n\npub type PubKeyLookup = HashMap<PublicKeyBytes, dalek::PublicKey>;\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 1, "score": 174773.66863618518 }, { "content": "pub fn format_signature_token_struct(\n\n view: &BinaryIndexedView,\n\n sidx: StructHandleIndex,\n\n ty_args: &[SignatureToken],\n\n) -> String {\n\n let (address, module_name, struct_name) = resolve_struct(view, sidx);\n\n let s;\n\n let ty_args_string = if ty_args.is_empty() {\n\n \"\"\n\n } else {\n\n s = format!(\n\n \"<{}>\",\n\n ty_args\n\n .iter()\n\n .map(|t| format_signature_token(view, t))\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n );\n\n &s\n\n };\n\n format!(\n\n \"0x{}::{}::{}{}\",\n\n address.short_str_lossless(),\n\n module_name,\n\n struct_name,\n\n ty_args_string\n\n )\n\n}\n", "file_path": "crates/sui-verifier/src/lib.rs", "rank": 2, "score": 139005.8346494493 }, { "content": "// TODO move these to move bytecode utils\n\npub fn resolve_struct<'a>(\n\n view: &'a BinaryIndexedView,\n\n sidx: StructHandleIndex,\n\n) -> (&'a AccountAddress, &'a IdentStr, &'a IdentStr) {\n\n let shandle = view.struct_handle_at(sidx);\n\n let mhandle = view.module_handle_at(shandle.module);\n\n let address = view.address_identifier_at(mhandle.address);\n\n let module_name = view.identifier_at(mhandle.name);\n\n let struct_name = view.identifier_at(shandle.name);\n\n (address, module_name, struct_name)\n\n}\n\n\n", "file_path": "crates/sui-verifier/src/lib.rs", "rank": 3, "score": 138724.89525067518 }, { "content": "pub fn verify_module(module: &CompiledModule) -> SuiResult {\n\n verify_key_structs(module)\n\n}\n\n\n", "file_path": "crates/sui-verifier/src/struct_with_key_verifier.rs", "rank": 4, "score": 124452.51689506948 }, { "content": "pub fn get_nth_struct_field(v: Value, n: usize) -> Result<Value, PartialVMError> {\n\n let mut itr = v.value_as::<Struct>()?.unpack()?;\n\n Ok(itr.nth(n).unwrap())\n\n}\n", "file_path": "crates/sui-framework/src/natives/mod.rs", "rank": 5, "score": 114503.33706572477 }, { "content": "pub fn bytes_from_hex<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: for<'a> TryFrom<&'a [u8]>,\n\n D: serde::de::Deserializer<'de>,\n\n{\n\n let s = String::deserialize(deserializer)?;\n\n let value = decode_bytes_hex(&s).map_err(serde::de::Error::custom)?;\n\n Ok(value)\n\n}\n\n\n", "file_path": "crates/sui-types/src/base_types.rs", "rank": 6, "score": 112404.97817062406 }, { "content": "// Extract a field valye that's nested inside value `v`. The offset of each nesting\n\n// is determined by `offsets`.\n\npub fn get_nested_struct_field(mut v: Value, offsets: &[usize]) -> Result<Value, PartialVMError> {\n\n for offset in offsets {\n\n v = get_nth_struct_field(v, *offset)?;\n\n }\n\n Ok(v)\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/mod.rs", "rank": 7, "score": 111119.31038958224 }, { "content": "// TODO: get_key_pair() and get_key_pair_from_bytes() should return KeyPair only.\n\n// TODO: rename to random_key_pair\n\npub fn get_key_pair() -> (SuiAddress, KeyPair) {\n\n get_key_pair_from_rng(&mut OsRng)\n\n}\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 8, "score": 110700.9812094951 }, { "content": "export interface Keypair {\n\n /**\n\n * The public key for this keypair\n\n */\n\n getPublicKey(): PublicKey;\n\n\n\n /**\n\n * Return the signature for the data\n\n */\n\n signData(data: Base64DataBuffer): Base64DataBuffer;\n", "file_path": "sdk/typescript/src/cryptography/keypair.ts", "rank": 9, "score": 108497.99399911522 }, { "content": "pub fn bytes_as_hex<B, S>(bytes: &B, serializer: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n B: AsRef<[u8]>,\n\n S: serde::ser::Serializer,\n\n{\n\n serializer.serialize_str(&encode_bytes_hex(bytes))\n\n}\n\n\n", "file_path": "crates/sui-types/src/base_types.rs", "rank": 10, "score": 108328.9534359215 }, { "content": "/// Generate `COMMITTEE_SIZE` test cryptographic key pairs.\n\npub fn test_keys() -> Vec<(SuiAddress, KeyPair)> {\n\n let mut rng = StdRng::from_seed([0; 32]);\n\n (0..TEST_COMMITTEE_SIZE)\n\n .map(|_| get_key_pair_from_rng(&mut rng))\n\n .collect()\n\n}\n\n\n", "file_path": "crates/test-utils/src/lib.rs", "rank": 11, "score": 106149.85906243577 }, { "content": "pub fn sui_config_dir() -> Result<PathBuf, anyhow::Error> {\n\n match std::env::var_os(\"SUI_CONFIG_DIR\") {\n\n Some(config_env) => Ok(config_env.into()),\n\n None => match dirs::home_dir() {\n\n Some(v) => Ok(v.join(SUI_DIR).join(SUI_CONFIG_DIR)),\n\n None => anyhow::bail!(\"Cannot obtain home directory path\"),\n\n },\n\n }\n\n .and_then(|dir| {\n\n if !dir.exists() {\n\n std::fs::create_dir_all(dir.clone())?;\n\n }\n\n Ok(dir)\n\n })\n\n}\n\n\n", "file_path": "crates/sui-config/src/lib.rs", "rank": 12, "score": 101631.93443732658 }, { "content": "pub fn random_key_pairs(num: usize) -> Vec<KeyPair> {\n\n let mut items = num;\n\n let mut rng = OsRng;\n\n\n\n std::iter::from_fn(|| {\n\n if items == 0 {\n\n None\n\n } else {\n\n items -= 1;\n\n Some(get_key_pair_from_rng(&mut rng).1)\n\n }\n\n })\n\n .collect::<Vec<_>>()\n\n}\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 13, "score": 101593.82519146922 }, { "content": "// TODO: C-GETTER\n\npub fn get_key_pair_from_bytes(bytes: &[u8]) -> (SuiAddress, KeyPair) {\n\n let keypair = KeyPair {\n\n key_pair: DalekKeypair::from_bytes(bytes).unwrap(),\n\n public_key_cell: OnceCell::new(),\n\n };\n\n (SuiAddress::from(keypair.public_key_bytes()), keypair)\n\n}\n\n\n\n// TODO: replace this with a byte interpretation based on multicodec\n\npub const SUI_SIGNATURE_LENGTH: usize =\n\n ed25519_dalek::PUBLIC_KEY_LENGTH + ed25519_dalek::SIGNATURE_LENGTH;\n\n\n\n#[serde_as]\n\n#[derive(Eq, PartialEq, Copy, Clone, Serialize, Deserialize, JsonSchema)]\n\npub struct Signature(\n\n #[schemars(with = \"Base64\")]\n\n #[serde_as(as = \"Readable<Base64, Bytes>\")]\n\n [u8; SUI_SIGNATURE_LENGTH],\n\n);\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 14, "score": 100373.68305934792 }, { "content": "#[derive(Parser, Debug)]\n\n#[clap(author, version, about, long_about = None)]\n\nstruct Args {\n\n #[clap(subcommand)]\n\n cmd: Command,\n\n}\n\n\n", "file_path": "crates/x/src/main.rs", "rank": 15, "score": 96702.70315796757 }, { "content": "struct Genesis {\n\n pub objects: Vec<Object>,\n\n pub modules: Vec<Vec<CompiledModule>>,\n\n}\n\n\n", "file_path": "crates/sui-adapter/src/genesis.rs", "rank": 16, "score": 95097.85767512984 }, { "content": "#[derive(Helper)]\n\nstruct ShellHelper {\n\n pub command: CommandStructure,\n\n pub completion_cache: CompletionCache,\n\n}\n\n\n\nimpl Hinter for ShellHelper {\n\n type Hint = String;\n\n}\n\n\n\nimpl Highlighter for ShellHelper {}\n\n\n\nimpl Validator for ShellHelper {}\n\n\n\nimpl Completer for ShellHelper {\n\n type Candidate = Pair;\n\n fn complete(\n\n &self,\n\n line: &str,\n\n _pos: usize,\n\n _ctx: &Context<'_>,\n", "file_path": "crates/sui/src/shell.rs", "rank": 17, "score": 95097.85767512984 }, { "content": "#[derive(Parser)]\n\n#[clap(rename_all = \"kebab-case\")]\n\nstruct Args {\n\n #[clap(long)]\n\n pub config_path: PathBuf,\n\n\n\n #[clap(long, help = \"Specify address to listen on\")]\n\n listen_address: Option<Multiaddr>,\n\n}\n\n\n\n#[tokio::main]\n\nasync fn main() -> Result<()> {\n\n // Initialize logging\n\n let config = telemetry_subscribers::TelemetryConfig {\n\n service_name: \"sui-node\".into(),\n\n enable_tracing: std::env::var(\"SUI_TRACING_ENABLE\").is_ok(),\n\n json_log_output: std::env::var(\"SUI_JSON_SPAN_LOGS\").is_ok(),\n\n ..Default::default()\n\n };\n\n\n\n let _guard = telemetry_subscribers::init(config);\n\n\n", "file_path": "crates/sui-node/src/main.rs", "rank": 18, "score": 95097.85767512984 }, { "content": "#[derive(Serialize, Deserialize, Default, Clone)]\n\nstruct Method {\n\n name: String,\n\n #[serde(skip_serializing_if = \"Vec::is_empty\")]\n\n tags: Vec<Tag>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<String>,\n\n params: Vec<ContentDescriptor>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n result: Option<ContentDescriptor>,\n\n}\n\n\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 19, "score": 94341.06821392149 }, { "content": "#[derive(Serialize, Deserialize, Default, Clone)]\n\nstruct License {\n\n name: String,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n url: Option<String>,\n\n}\n\n\n\nimpl Default for RpcModuleDocBuilder {\n\n fn default() -> Self {\n\n Self::new()\n\n }\n\n}\n\n\n\nimpl RpcModuleDocBuilder {\n\n pub fn new() -> Self {\n\n let schema_generator = SchemaSettings::default()\n\n .with(|s| {\n\n s.definitions_path = \"#/components/schemas/\".to_string();\n\n })\n\n .into_generator();\n\n\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 20, "score": 94341.06821392149 }, { "content": "#[derive(Serialize, Deserialize, Default, Clone)]\n\nstruct Tag {\n\n name: String,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n summery: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<String>,\n\n}\n\n\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 21, "score": 94341.06821392149 }, { "content": "#[derive(Serialize, Deserialize, Default, Clone)]\n\nstruct Contact {\n\n name: String,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n url: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n email: Option<String>,\n\n}\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 22, "score": 94341.06821392149 }, { "content": "#[derive(Serialize, Deserialize, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Components {\n\n #[serde(skip_serializing_if = \"BTreeMap::is_empty\")]\n\n content_descriptors: BTreeMap<String, ContentDescriptor>,\n\n #[serde(skip_serializing_if = \"BTreeMap::is_empty\")]\n\n schemas: BTreeMap<String, SchemaObject>,\n\n}\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 23, "score": 94340.9015134325 }, { "content": "#[derive(Serialize, Deserialize, Default, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\nstruct Info {\n\n title: String,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n description: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n terms_of_service: Option<String>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n contact: Option<Contact>,\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n license: Option<License>,\n\n version: String,\n\n}\n\n\n", "file_path": "crates/sui-open-rpc/src/lib.rs", "rank": 24, "score": 94340.84699831848 }, { "content": "struct Options {\n\n #[clap(arg_enum, default_value = \"Print\", ignore_case = true)]\n\n action: Action,\n\n}\n\n\n\nconst FILE_PATH: &str = \"sui-core/tests/staged/sui.yaml\";\n\n\n", "file_path": "crates/sui-core/src/generate_format.rs", "rank": 25, "score": 94329.38040679741 }, { "content": "struct FaucetConfig {\n\n #[clap(long, default_value_t = 5003)]\n\n port: u16,\n\n\n\n #[clap(long, default_value = \"127.0.0.1\")]\n\n host_ip: Ipv4Addr,\n\n\n\n #[clap(long, default_value_t = 50000)]\n\n amount: u64,\n\n\n\n #[clap(long, default_value_t = 5)]\n\n num_coins: usize,\n\n\n\n #[clap(long, default_value_t = 10)]\n\n request_buffer_size: usize,\n\n\n\n #[clap(long, default_value_t = 120)]\n\n timeout_in_seconds: u64,\n\n}\n\n\n", "file_path": "crates/sui-faucet/src/main.rs", "rank": 26, "score": 94329.38040679741 }, { "content": "struct Options {\n\n #[clap(arg_enum, default_value = \"Record\", ignore_case = true)]\n\n action: Action,\n\n}\n\n\n\nconst FILE_PATH: &str = concat!(\n\n env!(\"CARGO_MANIFEST_DIR\"),\n\n \"/../sui-open-rpc/spec/openrpc.json\",\n\n);\n\n\n\nconst OBJECT_SAMPLE_FILE_PATH: &str = concat!(\n\n env!(\"CARGO_MANIFEST_DIR\"),\n\n \"/../sui-open-rpc/samples/objects.json\",\n\n);\n\n\n\nconst TRANSACTION_SAMPLE_FILE_PATH: &str = concat!(\n\n env!(\"CARGO_MANIFEST_DIR\"),\n\n \"/../sui-open-rpc/samples/transactions.json\",\n\n);\n\n\n", "file_path": "crates/generate-json-rpc-spec/src/main.rs", "rank": 27, "score": 93582.27474100687 }, { "content": "// A structure that stores a set of spanning trees, and that supports addition\n\n// of links to merge them, and construct ever growing components.\n\nstruct SpanGraph {\n\n nodes: HashMap<AuthorityName, (AuthorityName, StakeUnit)>,\n\n}\n\n\n\nimpl SpanGraph {\n\n /// Initialize the graph with each authority just pointing to itself.\n\n pub fn new(committee: &Committee) -> SpanGraph {\n\n let nodes: HashMap<AuthorityName, (AuthorityName, StakeUnit)> = committee\n\n .voting_rights\n\n .iter()\n\n .map(|(n, w)| (*n, (*n, *w)))\n\n .collect();\n\n\n\n SpanGraph { nodes }\n\n }\n\n\n\n /// Follow pointer until you get to a node that only point to itself\n\n /// and return the node name, and the weight of the tree that points\n\n /// indirectly to it.\n\n pub fn top_node(&self, name: &AuthorityName) -> (AuthorityName, StakeUnit) {\n", "file_path": "crates/sui-core/src/checkpoints/reconstruction.rs", "rank": 28, "score": 93582.27474100687 }, { "content": "struct Method {\n\n name: String,\n\n params: Vec<(String, Type)>,\n\n returns: Option<Type>,\n\n doc: String,\n\n}\n\n\n", "file_path": "crates/sui-open-rpc-macros/src/lib.rs", "rank": 29, "score": 93582.27474100687 }, { "content": "/// A list of constant costs of various operations in Sui.\n\nstruct SuiCostTable {\n\n /// A flat fee charged for every transaction. This is also the mimmum amount of\n\n /// gas charged for a transaction.\n\n pub min_transaction_cost: ComputationCost,\n\n /// Computation cost per byte charged for package publish. This cost is primarily\n\n /// determined by the cost to verify and link a package. Note that this does not\n\n /// include the cost of writing the package to the store.\n\n pub package_publish_per_byte_cost: ComputationCost,\n\n /// Per byte cost to read objects from the store. This is computation cost instead of\n\n /// storage cost because it does not change the amount of data stored on the db.\n\n pub object_read_per_byte_cost: ComputationCost,\n\n /// Per byte cost to write objects to the store. This is computation cost instead of\n\n /// storage cost because it does not change the amount of data stored on the db.\n\n pub object_mutation_per_byte_cost: ComputationCost,\n\n /// Cost to use shared objects in a transaction, which requires full consensus.\n\n pub consensus_cost: ComputationCost,\n\n\n\n /// Unit cost of a byte in the storage. This will be used both for charging for\n\n /// new storage as well as rebating for deleting storage. That is, we expect users to\n\n /// get full refund on the object storage when it's deleted.\n", "file_path": "crates/sui-types/src/gas.rs", "rank": 30, "score": 93582.27474100687 }, { "content": "#[derive(Clone)]\n\nstruct JsonRpcMetrics {\n\n /// Counter of requests, route is a label (ie separate timeseries per route)\n\n requests_by_route: IntCounterVec,\n\n /// Request latency, route is a label\n\n req_latency_by_route: HistogramVec,\n\n /// Failed requests by route\n\n errors_by_route: IntCounterVec,\n\n}\n\n\n\nimpl JsonRpcMetrics {\n\n pub fn new() -> Self {\n\n static METRICS: Lazy<JsonRpcMetrics> = Lazy::new(|| JsonRpcMetrics {\n\n requests_by_route: register_int_counter_vec!(\n\n \"rpc_requests_by_route\",\n\n \"Number of requests by route\",\n\n &[\"route\"]\n\n )\n\n .unwrap(),\n\n req_latency_by_route: register_histogram_vec!(\n\n \"req_latency_by_route\",\n", "file_path": "crates/sui-gateway/src/json_rpc.rs", "rank": 31, "score": 92855.66137775089 }, { "content": "#[derive(Clone)]\n\nstruct LockServiceImpl {\n\n /// This is a map between object references of currently active objects that can be mutated,\n\n /// and the transaction that they are lock on for use by this specific authority. Where an object\n\n /// lock exists for an object version, but no transaction has been seen using it the lock is set\n\n /// to None. The safety of consistent broadcast depend on each honest authority never changing\n\n /// the lock once it is set. After a certificate for this object is processed it can be\n\n /// forgotten.\n\n transaction_lock: DBMap<ObjectRef, Option<TransactionDigest>>,\n\n}\n\n\n\n// TODO: Create method needs to make sure only one instance or thread of this is running per authority\n\n// If not for multiple authorities per process, it should really be one per process.\n\nimpl LockServiceImpl {\n\n /// Open or create a new LockService database\n\n fn try_open_db<P: AsRef<Path>>(path: P, db_options: Option<Options>) -> Result<Self, SuiError> {\n\n let (options, point_lookup) = default_db_options(db_options);\n\n\n\n let db = {\n\n let path = &path;\n\n let db_options = Some(options);\n", "file_path": "crates/sui-storage/src/lock_service.rs", "rank": 32, "score": 92855.66137775089 }, { "content": "#[derive(Parse, Debug)]\n\nstruct NamedAttribute {\n\n #[paren]\n\n _paren_token: Paren,\n\n #[inside(_paren_token)]\n\n _ident: Ident,\n\n #[inside(_paren_token)]\n\n _eq_token: Token![=],\n\n #[inside(_paren_token)]\n\n value: syn::LitStr,\n\n}\n", "file_path": "crates/sui-open-rpc-macros/src/lib.rs", "rank": 33, "score": 92855.66137775089 }, { "content": "struct LockServiceInner {\n\n sender: Option<Sender<LockServiceCommands>>,\n\n query_sender: Option<Sender<LockServiceQueries>>,\n\n run_command_loop: Option<JoinHandle<()>>,\n\n run_queries_loop: Option<JoinHandle<()>>,\n\n}\n\n\n\nimpl LockServiceInner {\n\n #[inline]\n\n fn sender(&self) -> &Sender<LockServiceCommands> {\n\n self.sender\n\n .as_ref()\n\n .expect(\"LockServiceInner should not have been dropped yet\")\n\n }\n\n\n\n #[inline]\n\n fn query_sender(&self) -> &Sender<LockServiceQueries> {\n\n self.query_sender\n\n .as_ref()\n\n .expect(\"LockServiceInner should not have been dropped yet\")\n", "file_path": "crates/sui-storage/src/lock_service.rs", "rank": 34, "score": 92855.66137775089 }, { "content": "struct RpcDefinition {\n\n name: Ident,\n\n methods: Vec<Method>,\n\n}\n", "file_path": "crates/sui-open-rpc-macros/src/lib.rs", "rank": 35, "score": 92855.66137775089 }, { "content": "#[derive(Debug)]\n\nstruct OwnedObj {\n\n value: Value,\n\n type_: Type,\n\n /// Owner is the direct owner of the object.\n\n owner: Owner,\n\n /// Signer is the ultimate owner of the object potentially through\n\n /// chains of object ownership.\n\n /// e.g. If account A ownd object O1, O1 owns O2. Then\n\n /// O2's owner is O1, and signer is A.\n\n /// signer will always be set eventually, but it needs to be optional first\n\n /// since we may not know its signer initially.\n\n signer: Option<Owner>,\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 36, "score": 92855.66137775089 }, { "content": "struct LockedNotifier {\n\n high_watermark: u64,\n\n live_tickets: BTreeSet<TxSequenceNumber>,\n\n}\n\n\n\nimpl TransactionNotifier {\n\n /// Create a new transaction notifier for the authority store\n\n pub fn new(state: Arc<AuthorityStore>) -> SuiResult<TransactionNotifier> {\n\n let seq = state.next_sequence_number()?;\n\n Ok(TransactionNotifier {\n\n state,\n\n low_watermark: AtomicU64::new(seq),\n\n notify: Notify::new(),\n\n has_stream: AtomicBool::new(false),\n\n is_closed: AtomicBool::new(false),\n\n\n\n // Keep a set of the tickets that are still being processed\n\n // This is the size of the number of concurrent processes.\n\n inner: Mutex::new(LockedNotifier {\n\n high_watermark: seq,\n", "file_path": "crates/sui-core/src/authority/authority_notifier.rs", "rank": 37, "score": 92855.66137775089 }, { "content": "/// Generate a keypair from the specified RNG (useful for testing with seedable rngs).\n\npub fn get_key_pair_from_rng<R>(csprng: &mut R) -> (SuiAddress, KeyPair)\n\nwhere\n\n R: rand::CryptoRng + rand::RngCore,\n\n{\n\n let kp = DalekKeypair::generate(csprng);\n\n let keypair = KeyPair {\n\n key_pair: kp,\n\n public_key_cell: OnceCell::new(),\n\n };\n\n (SuiAddress::from(keypair.public_key_bytes()), keypair)\n\n}\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 38, "score": 92808.9296859239 }, { "content": "#[derive(Serialize)]\n\nstruct TransactionResponseSample {\n\n pub move_call: TransactionResponse,\n\n pub transfer: TransactionResponse,\n\n pub coin_split: TransactionResponse,\n\n}\n", "file_path": "crates/generate-json-rpc-spec/src/main.rs", "rank": 39, "score": 92154.6284792625 }, { "content": "#[derive(Serialize)]\n\nstruct ObjectResponseSample {\n\n pub example_nft: GetObjectDataResponse,\n\n pub coin: GetObjectDataResponse,\n\n pub move_package: GetObjectDataResponse,\n\n pub hero: GetObjectDataResponse,\n\n}\n\n\n", "file_path": "crates/generate-json-rpc-spec/src/main.rs", "rank": 40, "score": 92154.6284792625 }, { "content": "#[derive(Parse, Debug)]\n\nstruct OpenRpcAttribute {\n\n label: syn::Ident,\n\n _eq_token: Token![=],\n\n value: syn::LitStr,\n\n}\n\n\n", "file_path": "crates/sui-open-rpc-macros/src/lib.rs", "rank": 41, "score": 92148.70860093589 }, { "content": "#[derive(Clone)]\n\nstruct TestConsensus {\n\n sender: Arc<std::sync::Mutex<std::sync::mpsc::Sender<CheckpointFragment>>>,\n\n}\n\n\n\nimpl ConsensusSender for TestConsensus {\n\n fn send_to_consensus(&self, fragment: CheckpointFragment) -> Result<(), SuiError> {\n\n self.sender\n\n .lock()\n\n .expect(\"Locking failed\")\n\n .send(fragment)\n\n .expect(\"Failed to send\");\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl TestConsensus {\n\n pub fn new() -> (TestConsensus, std::sync::mpsc::Receiver<CheckpointFragment>) {\n\n let (tx, rx) = std::sync::mpsc::channel();\n\n (\n\n TestConsensus {\n\n sender: Arc::new(std::sync::Mutex::new(tx)),\n\n },\n\n rx,\n\n )\n\n }\n\n}\n\n\n", "file_path": "crates/sui-core/src/checkpoints/tests/checkpoint_tests.rs", "rank": 42, "score": 92148.70860093589 }, { "content": "#[derive(Parse, Debug)]\n\nstruct OpenRpcAttributes {\n\n #[parse_terminated(OpenRpcAttribute::parse)]\n\n fields: Punctuated<OpenRpcAttribute, Token![,]>,\n\n}\n\n\n\nimpl OpenRpcAttributes {\n\n fn find_attr(&self, name: &str) -> Option<LitStr> {\n\n self.fields\n\n .iter()\n\n .find(|attr| attr.label == name)\n\n .map(|attr| attr.value.clone())\n\n }\n\n}\n\n\n", "file_path": "crates/sui-open-rpc-macros/src/lib.rs", "rank": 43, "score": 92148.70860093589 }, { "content": "struct TxnSummary {\n\n created: Vec<ObjectID>,\n\n written: Vec<ObjectID>,\n\n deleted: Vec<ObjectID>,\n\n events: Vec<Event>,\n\n}\n\n\n\nimpl<'a> MoveTestAdapter<'a> for SuiTestAdapter<'a> {\n\n type ExtraPublishArgs = SuiPublishArgs;\n\n type ExtraRunArgs = SuiRunArgs;\n\n type Subcommand = SuiSubcommand;\n\n type ExtraInitArgs = SuiInitArgs;\n\n type ExtraValueArgs = SuiExtraValueArgs;\n\n\n\n fn compiled_state(&mut self) -> &mut CompiledState<'a> {\n\n &mut self.compiled_state\n\n }\n\n\n\n fn default_syntax(&self) -> SyntaxChoice {\n\n self.default_syntax\n", "file_path": "crates/sui-transactional-test-runner/src/test_adapter.rs", "rank": 44, "score": 92148.70860093589 }, { "content": "struct TestNetwork {\n\n _network: SuiNetwork,\n\n _rpc_server: HttpServerHandle,\n\n accounts: Vec<SuiAddress>,\n\n http_client: HttpClient,\n\n working_dir: PathBuf,\n\n}\n\n\n\nasync fn start_rpc_gateway(\n\n config_path: &Path,\n\n) -> Result<(SocketAddr, HttpServerHandle), anyhow::Error> {\n\n let server = HttpServerBuilder::default().build(\"127.0.0.1:0\").await?;\n\n let addr = server.local_addr()?;\n\n let client = create_client(config_path)?;\n\n let mut module = RpcModule::new(());\n\n module.merge(RpcGatewayImpl::new(client.clone()).into_rpc())?;\n\n module.merge(GatewayReadApiImpl::new(client.clone()).into_rpc())?;\n\n module.merge(TransactionBuilderImpl::new(client.clone()).into_rpc())?;\n\n\n\n let handle = server.start(module)?;\n\n Ok((addr, handle))\n\n}\n", "file_path": "crates/sui/src/unit_tests/rpc_server_tests.rs", "rank": 45, "score": 92148.70860093589 }, { "content": "struct TransferResult {\n\n pub authority_state: AuthorityState,\n\n pub object_id: ObjectID,\n\n pub gas_object_id: ObjectID,\n\n pub response: SuiResult<TransactionInfoResponse>,\n\n}\n\n\n\nasync fn execute_transfer(gas_balance: u64, gas_budget: u64, run_confirm: bool) -> TransferResult {\n\n let (sender, sender_key) = get_key_pair();\n\n let object_id: ObjectID = ObjectID::random();\n\n let recipient = dbg_addr(2);\n\n let authority_state = init_state_with_ids(vec![(sender, object_id)]).await;\n\n let gas_object_id = ObjectID::random();\n\n let gas_object = Object::with_id_owner_gas_coin_object_for_testing(\n\n gas_object_id,\n\n SequenceNumber::new(),\n\n sender,\n\n gas_balance,\n\n );\n\n let gas_object_ref = gas_object.compute_object_reference();\n", "file_path": "crates/sui-core/src/unit_tests/gas_tests.rs", "rank": 46, "score": 92148.70860093589 }, { "content": "#[derive(Clone)]\n\nstruct AsyncTestConsensus {\n\n sender: Arc<std::sync::Mutex<tokio::sync::mpsc::UnboundedSender<CheckpointFragment>>>,\n\n}\n\n\n\nimpl ConsensusSender for AsyncTestConsensus {\n\n fn send_to_consensus(&self, fragment: CheckpointFragment) -> Result<(), SuiError> {\n\n self.sender\n\n .lock()\n\n .expect(\"Locking failed\")\n\n .send(fragment)\n\n .expect(\"Failed to send\");\n\n Ok(())\n\n }\n\n}\n\n\n\n#[allow(clippy::disallowed_methods)]\n\nimpl AsyncTestConsensus {\n\n pub fn new() -> (\n\n AsyncTestConsensus,\n\n tokio::sync::mpsc::UnboundedReceiver<CheckpointFragment>,\n", "file_path": "crates/sui-core/src/checkpoints/tests/checkpoint_tests.rs", "rank": 47, "score": 91460.62910255301 }, { "content": "struct LocalConfirmationTransactionHandler {\n\n state: Arc<AuthorityState>,\n\n}\n\n\n\n#[async_trait]\n\nimpl ConfirmationTransactionHandler for LocalConfirmationTransactionHandler {\n\n async fn handle(&self, cert: ConfirmationTransaction) -> SuiResult<TransactionInfoResponse> {\n\n self.state.handle_confirmation_transaction(cert).await\n\n }\n\n\n\n fn destination_name(&self) -> String {\n\n format!(\"{:?}\", self.state.name)\n\n }\n\n}\n\n\n\npub async fn select_gossip_peer<A>(\n\n my_name: AuthorityName,\n\n peer_names: HashSet<AuthorityName>,\n\n active_authority: &ActiveAuthority<A>,\n\n) -> Result<AuthorityName, SuiError>\n", "file_path": "crates/sui-core/src/authority_active/gossip/mod.rs", "rank": 48, "score": 90790.67705785081 }, { "content": "/// An abstraction of the (possibly distributed) store for objects, and (soon) events and transactions\n\npub trait Storage {\n\n fn reset(&mut self);\n\n\n\n fn read_object(&self, id: &ObjectID) -> Option<&Object>;\n\n\n\n // Specify the list of object IDs created during the transaction.\n\n // This is needed to determine unwrapped objects at the end.\n\n fn set_create_object_ids(&mut self, ids: HashSet<ObjectID>);\n\n\n\n fn write_object(&mut self, object: Object);\n\n\n\n /// Record an event that happened during execution\n\n fn log_event(&mut self, event: Event);\n\n\n\n fn delete_object(&mut self, id: &ObjectID, version: SequenceNumber, kind: DeleteKind);\n\n}\n\n\n", "file_path": "crates/sui-types/src/storage.rs", "rank": 49, "score": 89631.95290379494 }, { "content": "pub trait Config\n\nwhere\n\n Self: DeserializeOwned + Serialize,\n\n{\n\n fn persisted(self, path: &Path) -> PersistedConfig<Self> {\n\n PersistedConfig {\n\n inner: self,\n\n path: path.to_path_buf(),\n\n }\n\n }\n\n\n\n fn load<P: AsRef<Path>>(path: P) -> Result<Self, anyhow::Error> {\n\n let path = path.as_ref();\n\n trace!(\"Reading config from {}\", path.display());\n\n let reader = fs::File::open(path)\n\n .with_context(|| format!(\"Unable to load config from {}\", path.display()))?;\n\n Ok(serde_yaml::from_reader(reader)?)\n\n }\n\n\n\n fn save<P: AsRef<Path>>(&self, path: P) -> Result<(), anyhow::Error> {\n", "file_path": "crates/sui-config/src/lib.rs", "rank": 50, "score": 89631.95290379494 }, { "content": "pub fn make_committee_key<R>(rand: &mut R) -> (Vec<KeyPair>, Committee)\n\nwhere\n\n R: rand::CryptoRng + rand::RngCore,\n\n{\n\n make_committee_key_num(4, rand)\n\n}\n\n\n", "file_path": "crates/sui-types/src/unit_tests/utils.rs", "rank": 51, "score": 89581.12493573953 }, { "content": "pub trait SignableBytes\n\nwhere\n\n Self: Sized,\n\n{\n\n fn from_signable_bytes(bytes: &[u8]) -> Result<Self, anyhow::Error>;\n\n}\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 52, "score": 88887.09854343755 }, { "content": "#[async_trait]\n\npub trait Faucet {\n\n /// Send `Coin<SUI>` of the specified amount to the recipient\n\n async fn send(\n\n &self,\n\n recipient: SuiAddress,\n\n amounts: &[u64],\n\n ) -> Result<FaucetReceipt, FaucetError>;\n\n}\n\n\n\nimpl<'a> FromIterator<&'a SuiObject> for FaucetReceipt {\n\n fn from_iter<T: IntoIterator<Item = &'a SuiObject>>(iter: T) -> Self {\n\n FaucetReceipt {\n\n sent: iter.into_iter().map(|o| o.into()).collect(),\n\n }\n\n }\n\n}\n\n\n\nimpl From<&SuiObject> for CoinInfo {\n\n fn from(v: &SuiObject) -> Self {\n\n let gas_coin = GasCoin::try_from(v).unwrap();\n", "file_path": "crates/sui-faucet/src/faucet/mod.rs", "rank": 53, "score": 88887.09854343755 }, { "content": "pub fn all_natives(\n\n move_stdlib_addr: AccountAddress,\n\n sui_framework_addr: AccountAddress,\n\n) -> NativeFunctionTable {\n\n const SUI_NATIVES: &[(&str, &str, NativeFunction)] = &[\n\n (\"Event\", \"emit\", event::emit),\n\n (\"ID\", \"bytes_to_address\", id::bytes_to_address),\n\n (\"ID\", \"delete_id\", id::delete_id),\n\n (\"ID\", \"get_versioned_id\", id::get_versioned_id),\n\n (\n\n \"TestScenario\",\n\n \"delete_object_for_testing\",\n\n test_scenario::delete_object_for_testing,\n\n ),\n\n (\n\n \"TestScenario\",\n\n \"emit_wrapped_object_events\",\n\n test_scenario::emit_wrapped_object_events,\n\n ),\n\n (\n", "file_path": "crates/sui-framework/src/natives/mod.rs", "rank": 54, "score": 88887.09854343755 }, { "content": "/// Given a list of `modules`, links each module against its\n\n/// dependencies and runs each module with both the Move VM verifier\n\n/// and the Sui verifier.\n\npub fn verify_and_link<\n\n E: Debug,\n\n S: ResourceResolver<Error = E> + ModuleResolver<Error = E> + Storage,\n\n>(\n\n state_view: &S,\n\n modules: &[CompiledModule],\n\n package_id: ObjectID,\n\n natives: NativeFunctionTable,\n\n gas_status: &mut SuiGasStatus,\n\n) -> Result<MoveVM, SuiError> {\n\n // Run the Move bytecode verifier and linker.\n\n // It is important to do this before running the Sui verifier, since the sui\n\n // verifier may assume well-formedness conditions enforced by the Move verifier hold\n\n let vm = MoveVM::new(natives)\n\n .expect(\"VM creation only fails if natives are invalid, and we created the natives\");\n\n let mut session = vm.new_session(state_view);\n\n // TODO(https://github.com/MystenLabs/sui/issues/69): avoid this redundant serialization by exposing VM API that allows us to run the linker directly on `Vec<CompiledModule>`\n\n let new_module_bytes: Vec<_> = modules\n\n .iter()\n\n .map(|m| {\n", "file_path": "crates/sui-adapter/src/adapter.rs", "rank": 55, "score": 88887.09854343755 }, { "content": "pub trait Encoding {\n\n fn decode(s: &str) -> Result<Vec<u8>, anyhow::Error>;\n\n fn encode<T: AsRef<[u8]>>(data: T) -> String;\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, JsonSchema)]\n\npub struct Hex(String);\n\n#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, JsonSchema)]\n\n#[serde(try_from = \"String\")]\n\npub struct Base64(String);\n\n\n\nimpl TryFrom<String> for Base64 {\n\n type Error = anyhow::Error;\n\n fn try_from(value: String) -> Result<Self, Self::Error> {\n\n // Make sure the value is valid base64 string.\n\n Base64::decode(&value)?;\n\n Ok(Self(value))\n\n }\n\n}\n\n\n", "file_path": "crates/sui-types/src/sui_serde.rs", "rank": 56, "score": 88887.09854343755 }, { "content": "/// Implementation of Move native function `Event::emit<T: copy + drop>(event: T)`\n\n/// Adds an event to the transaction's event log\n\npub fn emit(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 1);\n\n\n\n let ty = ty_args.pop().unwrap();\n\n let event = args.pop_back().unwrap();\n\n\n\n // gas cost is proportional to size of event\n\n let event_size = event.size();\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 1).add(event_size);\n\n match ty {\n\n Type::Struct(..) | Type::StructInstantiation(..) => (),\n\n ty => {\n\n // TODO: // TODO(https://github.com/MystenLabs/sui/issues/19): enforce this in the ability system\n\n panic!(\"Unsupported event type {:?}--struct expected\", ty)\n\n }\n\n }\n\n\n\n if !context.save_event(Vec::new(), EventType::User as u64, ty, event)? {\n\n return Ok(NativeResult::err(cost, 0));\n\n }\n\n\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n}\n", "file_path": "crates/sui-framework/src/natives/event.rs", "rank": 57, "score": 88887.09854343755 }, { "content": "/// Make a transaction calling a specific move module & function.\n\npub fn move_transaction(\n\n gas_object: Object,\n\n module: &'static str,\n\n function: &'static str,\n\n package_ref: ObjectRef,\n\n arguments: Vec<CallArg>,\n\n) -> Transaction {\n\n // The key pair of the sender of the transaction.\n\n let (sender, keypair) = test_keys().pop().unwrap();\n\n\n\n // Make the transaction.\n\n let data = TransactionData::new_move_call(\n\n sender,\n\n package_ref,\n\n ident_str!(module).to_owned(),\n\n ident_str!(function).to_owned(),\n\n /* type_args */ vec![],\n\n gas_object.compute_object_reference(),\n\n arguments,\n\n MAX_GAS,\n\n );\n\n let signature = Signature::new(&data, &keypair);\n\n Transaction::new(data, signature)\n\n}\n\n\n", "file_path": "crates/test-utils/src/messages.rs", "rank": 58, "score": 88887.09854343755 }, { "content": "struct PeerGossip<A> {\n\n peer_name: AuthorityName,\n\n client: SafeClient<A>,\n\n state: Arc<AuthorityState>,\n\n max_seq: Option<TxSequenceNumber>,\n\n aggregator: Arc<AuthorityAggregator<A>>,\n\n}\n\n\n\nconst EACH_ITEM_DELAY_MS: u64 = 1_000;\n\nconst REQUEST_FOLLOW_NUM_DIGESTS: u64 = 100_000;\n\nconst REFRESH_FOLLOWER_PERIOD_SECS: u64 = 60;\n\n\n\nuse super::ActiveAuthority;\n\n\n\npub async fn gossip_process<A>(active_authority: &ActiveAuthority<A>, degree: usize)\n\nwhere\n\n A: AuthorityAPI + Send + Sync + 'static + Clone,\n\n{\n\n gossip_process_with_start_seq(active_authority, degree, None).await\n\n}\n", "file_path": "crates/sui-core/src/authority_active/gossip/mod.rs", "rank": 59, "score": 88271.6435839218 }, { "content": "// Syncs a ConfirmationTransaction to a (possibly) remote authority.\n\nstruct RemoteConfirmationTransactionHandler<A> {\n\n destination_authority: AuthorityName,\n\n destination_client: SafeClient<A>,\n\n}\n\n\n\n#[async_trait]\n\nimpl<A> ConfirmationTransactionHandler for RemoteConfirmationTransactionHandler<A>\n\nwhere\n\n A: AuthorityAPI + Send + Sync + 'static + Clone,\n\n{\n\n async fn handle(&self, cert: ConfirmationTransaction) -> SuiResult<TransactionInfoResponse> {\n\n self.destination_client\n\n .handle_confirmation_transaction(cert)\n\n .await\n\n }\n\n\n\n fn destination_name(&self) -> String {\n\n format!(\"{:?}\", self.destination_authority)\n\n }\n\n}\n", "file_path": "crates/sui-core/src/authority_aggregator.rs", "rank": 60, "score": 88271.6435839218 }, { "content": "struct IDLeakAnalysis<'a> {\n\n binary_view: &'a BinaryIndexedView<'a>,\n\n function_view: &'a FunctionView<'a>,\n\n stack: Vec<AbstractValue>,\n\n}\n\n\n\nimpl<'a> IDLeakAnalysis<'a> {\n\n fn new(binary_view: &'a BinaryIndexedView<'a>, function_view: &'a FunctionView<'a>) -> Self {\n\n Self {\n\n binary_view,\n\n function_view,\n\n stack: vec![],\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> TransferFunctions for IDLeakAnalysis<'a> {\n\n type State = AbstractState;\n\n type AnalysisError = SuiError;\n\n\n", "file_path": "crates/sui-verifier/src/id_leak_verifier.rs", "rank": 61, "score": 88271.6435839218 }, { "content": "/// Given a list of `modules`, use `ctx` to generate a fresh ID for the new packages.\n\n/// If `is_framework` is true, then the modules can have arbitrary user-defined address,\n\n/// otherwise their addresses must be 0.\n\n/// Mutate each module's self ID to the appropriate fresh ID and update its module handle tables\n\n/// to reflect the new ID's of its dependencies.\n\n/// Returns the newly created package ID.\n\npub fn generate_package_id(\n\n modules: &mut [CompiledModule],\n\n ctx: &mut TxContext,\n\n) -> Result<ObjectID, SuiError> {\n\n let mut sub_map = BTreeMap::new();\n\n let package_id = ctx.fresh_id();\n\n for module in modules.iter() {\n\n let old_module_id = module.self_id();\n\n let old_address = *old_module_id.address();\n\n if old_address != AccountAddress::ZERO {\n\n let handle = module.module_handle_at(module.self_module_handle_idx);\n\n let name = module.identifier_at(handle.name);\n\n return Err(SuiError::ModulePublishFailure {\n\n error: format!(\"Publishing module {name} with non-zero address is not allowed\"),\n\n });\n\n }\n\n let new_module_id = ModuleId::new(\n\n AccountAddress::from(package_id),\n\n old_module_id.name().to_owned(),\n\n );\n", "file_path": "crates/sui-adapter/src/adapter.rs", "rank": 62, "score": 88167.5679592992 }, { "content": "#[async_trait]\n\npub trait AuthorityAPI {\n\n /// Initiate a new transaction to a Sui or Primary account.\n\n async fn handle_transaction(\n\n &self,\n\n transaction: Transaction,\n\n ) -> Result<TransactionInfoResponse, SuiError>;\n\n\n\n /// Confirm a transaction to a Sui or Primary account.\n\n async fn handle_confirmation_transaction(\n\n &self,\n\n transaction: ConfirmationTransaction,\n\n ) -> Result<TransactionInfoResponse, SuiError>;\n\n\n\n /// Processes consensus request.\n\n async fn handle_consensus_transaction(\n\n &self,\n\n transaction: ConsensusTransaction,\n\n ) -> Result<TransactionInfoResponse, SuiError>;\n\n\n\n /// Handle Account information requests for this account.\n", "file_path": "crates/sui-core/src/authority_client.rs", "rank": 63, "score": 88162.6747347351 }, { "content": "/// - Check that `package_object`, `module` and `function` are valid\n\n/// - Check that the the signature of `function` is well-typed w.r.t `type_args`, `object_args`, and `pure_args`\n\n/// - Return the ID of the resolved module, a vector of BCS encoded arguments to pass to the VM, and a partitioning\n\n/// of the input objects into objects passed by value vs by mutable reference\n\npub fn resolve_and_type_check(\n\n objects: &BTreeMap<ObjectID, impl Borrow<Object>>,\n\n module: &CompiledModule,\n\n function: &Identifier,\n\n type_args: &[TypeTag],\n\n args: Vec<CallArg>,\n\n is_genesis: bool,\n\n) -> Result<TypeCheckSuccess, SuiError> {\n\n // Resolve the function we are calling\n\n let function_str = function.as_ident_str();\n\n let module_id = module.self_id();\n\n let fdef_opt = module.function_defs.iter().find(|fdef| {\n\n module.identifier_at(module.function_handle_at(fdef.function).name) == function_str\n\n });\n\n let fdef = match fdef_opt {\n\n Some(fdef) => fdef,\n\n None => {\n\n return Err(SuiError::FunctionNotFound {\n\n error: format!(\n\n \"Could not resolve function '{}' in module {}\",\n", "file_path": "crates/sui-adapter/src/adapter.rs", "rank": 64, "score": 88162.6747347351 }, { "content": "pub fn create_authority_aggregator(\n\n authority_configs: &[ValidatorInfo],\n\n) -> AuthorityAggregator<SafeClient<NetworkAuthorityClient>> {\n\n let voting_rights: BTreeMap<_, _> = authority_configs\n\n .iter()\n\n .map(|config| (config.public_key(), config.stake()))\n\n .collect();\n\n let committee = Committee::new(0, voting_rights);\n\n let clients: BTreeMap<_, _> = authority_configs\n\n .iter()\n\n .map(|config| {\n\n (\n\n config.public_key(),\n\n SafeClient::new(\n\n NetworkAuthorityClient::connect_lazy(config.network_address()).unwrap(),\n\n committee.clone(),\n\n config.public_key(),\n\n ),\n\n )\n\n })\n\n .collect();\n\n AuthorityAggregator::new(committee, clients)\n\n}\n", "file_path": "crates/test-utils/src/authority.rs", "rank": 65, "score": 88162.6747347351 }, { "content": "/// Implementation of Move native function\n\n/// `freeze_object<T: key>(obj: T)`\n\npub fn freeze_object(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 1);\n\n\n\n let ty = ty_args.pop().unwrap();\n\n let obj = args.pop_back().unwrap();\n\n let event_type = EventType::FreezeObject;\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 1);\n\n if context.save_event(vec![], event_type as u64, ty, obj)? {\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n } else {\n\n Ok(NativeResult::err(cost, 0))\n\n }\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/transfer.rs", "rank": 66, "score": 88162.6747347351 }, { "content": "pub fn is_object(\n\n view: &BinaryIndexedView,\n\n function_type_args: &[AbilitySet],\n\n t: &SignatureToken,\n\n) -> Result<bool, String> {\n\n use SignatureToken as S;\n\n match t {\n\n S::Reference(inner) | S::MutableReference(inner) | S::Vector(inner) => {\n\n is_object(view, function_type_args, inner)\n\n }\n\n _ => is_object_struct(view, function_type_args, t),\n\n }\n\n}\n\n\n", "file_path": "crates/sui-verifier/src/entry_points_verifier.rs", "rank": 67, "score": 88162.6747347351 }, { "content": "pub trait SuiRpcModule\n\nwhere\n\n Self: Sized,\n\n{\n\n fn rpc(self) -> RpcModule<Self>;\n\n fn rpc_doc_module() -> Module;\n\n}\n", "file_path": "crates/sui-gateway/src/api.rs", "rank": 68, "score": 88162.6747347351 }, { "content": "/// Implementation of Move native function\n\n/// `transfer_internal<T: key>(obj: T, recipient: vector<u8>, to_object: bool)`\n\n/// Here, we simply emit this event. The sui adapter\n\n/// treats this as a special event that is handled\n\n/// differently from user events:\n\n/// the adapter will change the owner of the object\n\n/// in question to `recipient`.\n\npub fn transfer_internal(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 3);\n\n\n\n let ty = ty_args.pop().unwrap();\n\n let to_object = pop_arg!(args, bool);\n\n let recipient = pop_arg!(args, AccountAddress);\n\n let transferred_obj = args.pop_back().unwrap();\n\n let event_type = if to_object {\n\n EventType::TransferToObject\n\n } else {\n\n EventType::TransferToAddress\n\n };\n\n // Charge a constant native gas cost here, since\n\n // we will charge it properly when processing\n\n // all the events in adapter.\n\n // TODO: adjust native_gas cost size base.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 1);\n\n if context.save_event(recipient.to_vec(), event_type as u64, ty, transferred_obj)? {\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n } else {\n\n Ok(NativeResult::err(cost, 0))\n\n }\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/transfer.rs", "rank": 69, "score": 88162.6747347351 }, { "content": "#[open_rpc(namespace = \"sui\", tag = \"Gateway API\")]\n\n#[rpc(server, client, namespace = \"sui\")]\n\npub trait RpcGatewayApi {\n\n /// Execute the transaction using the transaction data, signature and public key.\n\n #[method(name = \"executeTransaction\")]\n\n async fn execute_transaction(\n\n &self,\n\n tx_bytes: Base64,\n\n signature: Base64,\n\n pub_key: Base64,\n\n ) -> RpcResult<TransactionResponse>;\n\n\n\n /// Synchronize client state with validators.\n\n #[method(name = \"syncAccountState\")]\n\n async fn sync_account_state(&self, address: SuiAddress) -> RpcResult<()>;\n\n}\n\n\n", "file_path": "crates/sui-gateway/src/api.rs", "rank": 70, "score": 88162.6747347351 }, { "content": "#[open_rpc(namespace = \"sui\", tag = \"Transaction Builder API\")]\n\n#[rpc(server, client, namespace = \"sui\")]\n\npub trait RpcTransactionBuilder {\n\n /// Create a transaction to transfer a Sui coin from one address to another.\n\n #[method(name = \"transferCoin\")]\n\n async fn transfer_coin(\n\n &self,\n\n signer: SuiAddress,\n\n object_id: ObjectID,\n\n gas: Option<ObjectID>,\n\n gas_budget: u64,\n\n recipient: SuiAddress,\n\n ) -> RpcResult<TransactionBytes>;\n\n\n\n /// Execute a Move call transaction by calling the specified function in the module of a given package.\n\n #[method(name = \"moveCall\")]\n\n async fn move_call(\n\n &self,\n\n signer: SuiAddress,\n\n package_object_id: ObjectID,\n\n module: String,\n\n function: String,\n", "file_path": "crates/sui-gateway/src/api.rs", "rank": 71, "score": 88162.6747347351 }, { "content": "/// Implementation of Move native function\n\n/// `share_object<T: key>(obj: T)`\n\npub fn share_object(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 1);\n\n\n\n let ty = ty_args.pop().unwrap();\n\n let obj = args.pop_back().unwrap();\n\n let event_type = EventType::ShareObject;\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 1);\n\n if context.save_event(vec![], event_type as u64, ty, obj)? {\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n } else {\n\n Ok(NativeResult::err(cost, 0))\n\n }\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/transfer.rs", "rank": 72, "score": 88162.6747347351 }, { "content": "#[async_trait]\n\npub trait GatewayAPI {\n\n async fn execute_transaction(\n\n &self,\n\n tx: Transaction,\n\n ) -> Result<TransactionResponse, anyhow::Error>;\n\n\n\n /// Send coin object to a Sui address.\n\n async fn transfer_coin(\n\n &self,\n\n signer: SuiAddress,\n\n object_id: ObjectID,\n\n gas: Option<ObjectID>,\n\n gas_budget: u64,\n\n recipient: SuiAddress,\n\n ) -> Result<TransactionData, anyhow::Error>;\n\n\n\n /// Synchronise account state with a random authorities, updates all object_ids\n\n /// from account_addr, request only goes out to one authority.\n\n /// this method doesn't guarantee data correctness, caller will have to handle potential byzantine authority\n\n async fn sync_account_state(&self, account_addr: SuiAddress) -> Result<(), anyhow::Error>;\n", "file_path": "crates/sui-core/src/gateway_state.rs", "rank": 73, "score": 88162.6747347351 }, { "content": "pub fn delete_id(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 1);\n\n\n\n // unwrap safe because the interface of native function guarantees it.\n\n let ty = ty_args.pop().unwrap();\n\n let versioned_id = args.pop_back().unwrap();\n\n\n\n // TODO: what should the cost of this be?\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n\n\n if !context.save_event(vec![], EventType::DeleteObjectID as u64, ty, versioned_id)? {\n\n return Ok(NativeResult::err(cost, 0));\n\n }\n\n\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n}\n", "file_path": "crates/sui-framework/src/natives/id.rs", "rank": 74, "score": 88162.6747347351 }, { "content": "pub trait BackingPackageStore {\n\n fn get_package(&self, package_id: &ObjectID) -> SuiResult<Option<Object>>;\n\n}\n", "file_path": "crates/sui-types/src/storage.rs", "rank": 75, "score": 88162.6747347351 }, { "content": "pub fn bytes_to_address(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.is_empty());\n\n debug_assert!(args.len() == 1);\n\n\n\n let addr_bytes = pop_arg!(args, Vec<u8>);\n\n // unwrap safe because this native function is only called from new_from_bytes,\n\n // which already asserts the size of bytes to be equal of account address.\n\n let addr = AccountAddress::from_bytes(addr_bytes).unwrap();\n\n\n\n // TODO: what should the cost of this be?\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::CREATE_SIGNER, 0);\n\n\n\n Ok(NativeResult::ok(cost, smallvec![Value::address(addr)]))\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/id.rs", "rank": 76, "score": 88162.6747347351 }, { "content": "#[open_rpc(namespace = \"sui\", tag = \"Read API\")]\n\n#[rpc(server, client, namespace = \"sui\")]\n\npub trait RpcReadApi {\n\n /// Return the list of objects owned by an address.\n\n #[method(name = \"getObjectsOwnedByAddress\")]\n\n async fn get_objects_owned_by_address(\n\n &self,\n\n address: SuiAddress,\n\n ) -> RpcResult<Vec<SuiObjectInfo>>;\n\n\n\n #[method(name = \"getObjectsOwnedByObject\")]\n\n async fn get_objects_owned_by_object(\n\n &self,\n\n object_id: ObjectID,\n\n ) -> RpcResult<Vec<SuiObjectInfo>>;\n\n\n\n #[method(name = \"getTotalTransactionNumber\")]\n\n async fn get_total_transaction_number(&self) -> RpcResult<u64>;\n\n\n\n #[method(name = \"getTransactionsInRange\")]\n\n async fn get_transactions_in_range(\n\n &self,\n", "file_path": "crates/sui-gateway/src/api.rs", "rank": 77, "score": 88162.6747347351 }, { "content": "/// Create a new gas status with the given `gas_budget`, and charge the transaction flat fee.\n\npub fn start_gas_metering(\n\n gas_budget: u64,\n\n computation_gas_unit_price: u64,\n\n storage_gas_unit_price: u64,\n\n) -> SuiResult<SuiGasStatus<'static>> {\n\n let mut gas_status = SuiGasStatus::new_with_budget(\n\n gas_budget,\n\n computation_gas_unit_price,\n\n storage_gas_unit_price,\n\n );\n\n // Charge the flat transaction fee.\n\n gas_status.charge_min_tx_gas()?;\n\n Ok(gas_status)\n\n}\n\n\n", "file_path": "crates/sui-types/src/gas.rs", "rank": 78, "score": 88162.6747347351 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct Foo(String);\n\n\n\nimpl BcsSignable for Foo {}\n\n\n", "file_path": "crates/sui-types/src/unit_tests/base_types_tests.rs", "rank": 79, "score": 87595.36573243966 }, { "content": "#[derive(Serialize, Deserialize)]\n\nstruct Bar(String);\n\n\n\nimpl BcsSignable for Bar {}\n\n\n", "file_path": "crates/sui-types/src/unit_tests/base_types_tests.rs", "rank": 80, "score": 87595.36573243966 }, { "content": "#[cfg(test)]\n\n#[derive(Serialize, Deserialize)]\n\nstruct Foo(String);\n\n\n\nimpl BcsSignable for Foo {}\n\n\n", "file_path": "crates/sui-types/src/unit_tests/signature_seed_tests.rs", "rank": 81, "score": 87595.251892663 }, { "content": "/// Given a `path` and a `build_config`, build the package in that path and return the compiled modules as Vec<Vec<u8>>.\n\n/// This is useful for when publishing\n\n/// If we are building the Sui framework, `is_framework` will be true;\n\n/// Otherwise `is_framework` should be false (e.g. calling from client).\n\npub fn build_move_package_to_bytes(\n\n path: &Path,\n\n is_framework: bool,\n\n) -> Result<Vec<Vec<u8>>, SuiError> {\n\n build_move_package(\n\n path,\n\n BuildConfig {\n\n ..Default::default()\n\n },\n\n is_framework,\n\n )\n\n .map(|mods| {\n\n mods.iter()\n\n .map(|m| {\n\n let mut bytes = Vec::new();\n\n m.serialize(&mut bytes).unwrap();\n\n bytes\n\n })\n\n .collect::<Vec<_>>()\n\n })\n\n}\n\n\n", "file_path": "crates/sui-framework/src/lib.rs", "rank": 82, "score": 87463.06693878517 }, { "content": "/// Given a `path` and a `build_config`, build the package in that path and return the compiled modules as base64.\n\n/// This is useful for when publishing via JSON\n\n/// If we are building the Sui framework, `is_framework` will be true;\n\n/// Otherwise `is_framework` should be false (e.g. calling from client).\n\npub fn build_move_package_to_base64(\n\n path: &Path,\n\n is_framework: bool,\n\n) -> Result<Vec<String>, SuiError> {\n\n build_move_package_to_bytes(path, is_framework)\n\n .map(|mods| mods.iter().map(base64::encode).collect::<Vec<_>>())\n\n}\n\n\n", "file_path": "crates/sui-framework/src/lib.rs", "rank": 83, "score": 87463.06693878517 }, { "content": "#[async_trait]\n\npub trait ConfirmationTransactionHandler {\n\n async fn handle(&self, cert: ConfirmationTransaction) -> SuiResult<TransactionInfoResponse>;\n\n\n\n fn destination_name(&self) -> String;\n\n}\n\n\n", "file_path": "crates/sui-core/src/authority_aggregator.rs", "rank": 84, "score": 87457.85226786195 }, { "content": "pub fn get_versioned_id(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.len() == 1);\n\n debug_assert!(args.len() == 1);\n\n\n\n let obj = pop_arg!(args, StructRef);\n\n let id_field = obj.borrow_field(0)?;\n\n\n\n // TODO: what should the cost of this be?\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::SIGNER_BORROW, 0);\n\n\n\n Ok(NativeResult::ok(cost, smallvec![id_field]))\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/id.rs", "rank": 85, "score": 87457.85226786195 }, { "content": "/// Store package in state_view and call module initializers\n\npub fn store_package_and_init_modules<\n\n E: Debug,\n\n S: ResourceResolver<Error = E> + ModuleResolver<Error = E> + Storage,\n\n>(\n\n state_view: &mut S,\n\n vm: &MoveVM,\n\n modules: Vec<CompiledModule>,\n\n ctx: &mut TxContext,\n\n gas_status: &mut SuiGasStatus,\n\n) -> SuiResult {\n\n let modules_to_init = modules\n\n .iter()\n\n .filter_map(|module| {\n\n let init_fdef = module.function_defs.iter().find(|fdef| {\n\n let fhandle = module.function_handle_at(fdef.function).name;\n\n let fname = module.identifier_at(fhandle);\n\n fname == INIT_FN_NAME\n\n })?;\n\n\n\n let fhandle = module.function_handle_at(init_fdef.function);\n", "file_path": "crates/sui-adapter/src/adapter.rs", "rank": 86, "score": 87457.85226786195 }, { "content": "pub fn update_object(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert_eq!(ty_args.len(), 1);\n\n debug_assert_eq!(args.len(), 1);\n\n\n\n let ty = ty_args.pop().unwrap();\n\n let obj = args.pop_back().unwrap();\n\n\n\n // Gas amount doesn't matter as this is test only.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n context.save_event(vec![], UPDATE_OBJECT_EVENT, ty, obj)?;\n\n // Run through the events to make sure the object we returned didn't violate any rules.\n\n match get_global_inventory(context.events()) {\n\n Ok(_) => Ok(NativeResult::ok(cost, smallvec![])),\n\n Err(abort_code) => Ok(NativeResult::err(cost, abort_code)),\n\n }\n\n}\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 87, "score": 87457.85226786195 }, { "content": "/// Resolve a the JSON args of a function into the expected formats to make them usable by Move call\n\n/// This is because we have special types which we need to specify in other formats\n\npub fn resolve_move_function_args(\n\n package: &MovePackage,\n\n module_ident: Identifier,\n\n function: Identifier,\n\n combined_args_json: Vec<SuiJsonValue>,\n\n) -> Result<Vec<SuiJsonCallArg>, anyhow::Error> {\n\n // Extract the expected function signature\n\n let module = package.deserialize_module(&module_ident)?;\n\n let function_str = function.as_ident_str();\n\n let fdef = module\n\n .function_defs\n\n .iter()\n\n .find(|fdef| {\n\n module.identifier_at(module.function_handle_at(fdef.function).name) == function_str\n\n })\n\n .ok_or_else(|| {\n\n anyhow!(\n\n \"Could not resolve function {} in module {}\",\n\n function,\n\n module_ident\n", "file_path": "crates/sui-json/src/lib.rs", "rank": 88, "score": 87457.85226786195 }, { "content": "pub fn derive_id(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.is_empty());\n\n debug_assert!(args.len() == 2);\n\n\n\n let ids_created = pop_arg!(args, u64);\n\n let tx_hash = pop_arg!(args, Vec<u8>);\n\n\n\n // TODO(https://github.com/MystenLabs/sui/issues/58): finalize digest format\n\n // unwrap safe because all digests in Move are serialized from the Rust `TransactionDigest`\n\n let digest = TransactionDigest::try_from(tx_hash.as_slice()).unwrap();\n\n let id = Value::address(AccountAddress::from(digest.derive_id(ids_created)));\n\n\n\n // TODO: choose cost\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::CREATE_SIGNER, 0);\n\n\n\n Ok(NativeResult::ok(cost, smallvec![id]))\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/tx_context.rs", "rank": 89, "score": 87457.85226786195 }, { "content": "/// Given a `path` and a `build_config`, build the package in that path.\n\n/// If we are building the Sui framework, `is_framework` will be true;\n\n/// Otherwise `is_framework` should be false (e.g. calling from client).\n\npub fn build_move_package(\n\n path: &Path,\n\n build_config: BuildConfig,\n\n is_framework: bool,\n\n) -> SuiResult<Vec<CompiledModule>> {\n\n match build_config.compile_package(path, &mut Vec::new()) {\n\n Err(error) => Err(SuiError::ModuleBuildFailure {\n\n error: error.to_string(),\n\n }),\n\n Ok(package) => {\n\n let compiled_modules = package.root_modules_map();\n\n if !is_framework {\n\n if let Some(m) = compiled_modules\n\n .iter_modules()\n\n .iter()\n\n .find(|m| m.self_id().address() != &AccountAddress::ZERO)\n\n {\n\n return Err(SuiError::ModulePublishFailure {\n\n error: format!(\n\n \"Modules must all have 0x0 as their addresses. Violated by module {:?}\",\n", "file_path": "crates/sui-framework-build/src/lib.rs", "rank": 90, "score": 87457.85226786195 }, { "content": "/// Return the number of events emitted, including both user-defined events and system events\n\npub fn num_events(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.is_empty());\n\n debug_assert!(args.is_empty());\n\n\n\n // Gas amount doesn't matter as this is test only.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n\n\n let num_events = context.events().len();\n\n Ok(NativeResult::ok(\n\n cost,\n\n smallvec![Value::u64(num_events as u64)],\n\n ))\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 91, "score": 87457.85226786195 }, { "content": "/// Delete the given object\n\npub fn delete_object_for_testing(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert_eq!(ty_args.len(), 1);\n\n debug_assert_eq!(args.len(), 1);\n\n\n\n // Gas amount doesn't matter as this is test only.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 92, "score": 86771.84620725915 }, { "content": "/// Implementation of Move native function\n\n/// `delete_child_object_internal<T: key>(child: T)`\n\npub fn delete_child_object_internal(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.is_empty());\n\n // first args is an object ID that we will emit in a DeleteChildObject event\n\n // second arg is VersionedID that we want to ignore\n\n debug_assert!(args.len() == 2);\n\n\n\n let obj_id = args.pop_front().unwrap();\n\n let event_type = EventType::DeleteChildObject;\n\n // TODO: Decide the cost.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 1);\n\n if context.save_event(vec![], event_type as u64, Type::Address, obj_id)? {\n\n Ok(NativeResult::ok(cost, smallvec![]))\n\n } else {\n\n Ok(NativeResult::err(cost, 0))\n\n }\n\n}\n", "file_path": "crates/sui-framework/src/natives/transfer.rs", "rank": 93, "score": 86771.84620725915 }, { "content": "#[open_rpc(namespace = \"sui\", tag = \"Full Node API\")]\n\n#[rpc(server, client, namespace = \"sui\")]\n\npub trait RpcFullNodeReadApi {\n\n #[method(name = \"getTransactionsByInputObject\")]\n\n async fn get_transactions_by_input_object(\n\n &self,\n\n object: ObjectID,\n\n ) -> RpcResult<Vec<(GatewayTxSeqNumber, TransactionDigest)>>;\n\n\n\n #[method(name = \"getTransactionsByMutatedObject\")]\n\n async fn get_transactions_by_mutated_object(\n\n &self,\n\n object: ObjectID,\n\n ) -> RpcResult<Vec<(GatewayTxSeqNumber, TransactionDigest)>>;\n\n\n\n #[method(name = \"getTransactionsFromAddress\")]\n\n async fn get_transactions_from_addr(\n\n &self,\n\n addr: SuiAddress,\n\n ) -> RpcResult<Vec<(GatewayTxSeqNumber, TransactionDigest)>>;\n\n\n\n #[method(name = \"getTransactionsToAddress\")]\n\n async fn get_transactions_to_addr(\n\n &self,\n\n addr: SuiAddress,\n\n ) -> RpcResult<Vec<(GatewayTxSeqNumber, TransactionDigest)>>;\n\n}\n\n\n", "file_path": "crates/sui-gateway/src/api.rs", "rank": 94, "score": 86771.84620725915 }, { "content": "pub fn get_unowned_inventory(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert_eq!(ty_args.len(), 1);\n\n debug_assert_eq!(args.len(), 2);\n\n\n\n let tx_end_index = pop_arg!(args, u64) as usize;\n\n let immutable = pop_arg!(args, bool);\n\n let owner = if immutable {\n\n Owner::Immutable\n\n } else {\n\n Owner::Shared\n\n };\n\n\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n match get_inventory_for(owner, None, &ty_args[0], tx_end_index, context.events()) {\n\n Ok(inventory) => Ok(NativeResult::ok(\n\n cost,\n\n smallvec![Value::vector_for_testing_only(inventory)],\n\n )),\n\n Err(abort_code) => Ok(NativeResult::err(cost, abort_code)),\n\n }\n\n}\n\n\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 95, "score": 86771.84620725915 }, { "content": "/// Create a new signer (for test only) from an address.\n\npub fn new_signer_from_address(\n\n context: &mut NativeContext,\n\n ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert!(ty_args.is_empty());\n\n debug_assert_eq!(args.len(), 1);\n\n\n\n let address = pop_arg!(args, AccountAddress);\n\n let signer = Value::signer(address);\n\n\n\n // Gas amount doesn't matter as this is test only.\n\n let cost = native_gas(context.cost_table(), NativeCostIndex::EMIT_EVENT, 0);\n\n Ok(NativeResult::ok(cost, smallvec![signer]))\n\n}\n", "file_path": "crates/sui-framework/src/natives/tx_context.rs", "rank": 96, "score": 86771.84620725915 }, { "content": " pub trait SealedAuthoritySignInfoTrait {}\n\n impl SealedAuthoritySignInfoTrait for super::EmptySignInfo {}\n\n impl SealedAuthoritySignInfoTrait for super::AuthoritySignInfo {}\n\n impl SealedAuthoritySignInfoTrait for super::AuthorityQuorumSignInfo {}\n\n}\n\n\n", "file_path": "crates/sui-types/src/crypto.rs", "rank": 97, "score": 86771.84620725915 }, { "content": "pub fn emit_wrapped_object_events(\n\n context: &mut NativeContext,\n\n mut ty_args: Vec<Type>,\n\n mut args: VecDeque<Value>,\n\n) -> PartialVMResult<NativeResult> {\n\n debug_assert_eq!(ty_args.len(), 1);\n\n debug_assert_eq!(args.len(), 2);\n\n\n\n let id_type = ty_args.pop().unwrap();\n\n let removed = pop_arg!(args, VectorRef);\n\n let tx_begin_idx = pop_arg!(args, u64) as usize;\n\n\n\n let mut removed_ids: BTreeSet<ObjectID> = BTreeSet::new();\n\n for i in 0..removed.len(&id_type)?.value_as::<u64>()? {\n\n let id = removed.borrow_elem(i as usize, &id_type)?;\n\n let id_bytes = get_nested_struct_field(id.value_as::<StructRef>()?.read_ref()?, &[0])?;\n\n removed_ids.insert(id_bytes.value_as::<AccountAddress>()?.into());\n\n }\n\n\n\n let processed_ids: BTreeSet<_> = context.events()[tx_begin_idx..]\n", "file_path": "crates/sui-framework/src/natives/test_scenario.rs", "rank": 98, "score": 86103.91297562083 }, { "content": "#[cfg(test)]\n\npub fn init_transfer_transaction(\n\n sender: SuiAddress,\n\n secret: &KeyPair,\n\n recipient: SuiAddress,\n\n object_ref: ObjectRef,\n\n gas_object_ref: ObjectRef,\n\n) -> Transaction {\n\n let data = TransactionData::new_transfer(recipient, object_ref, sender, gas_object_ref, 10000);\n\n let signature = Signature::new(&data, secret);\n\n Transaction::new(data, signature)\n\n}\n\n\n", "file_path": "crates/sui-core/src/unit_tests/authority_tests.rs", "rank": 99, "score": 86103.91297562083 } ]
Rust
examples/responders/src/main.rs
rotoclone/Rocket
3a7559edcec7c443e68e22e038aaa2d90ef27c23
#[macro_use] extern crate rocket; #[cfg(test)] mod tests; /****************** `Result`, `Option` `NameFile` Responder *******************/ use std::{io, env}; use rocket::tokio::fs; use rocket::data::{Capped, TempFile}; use rocket::response::NamedFile; const FILENAME: &str = "big_file.dat"; #[post("/file", data = "<file>")] async fn upload(mut file: Capped<TempFile<'_>>) -> io::Result<String> { file.persist_to(env::temp_dir().join(FILENAME)).await?; Ok(format!("{} bytes at {}", file.n.written, file.path().unwrap().display())) } #[get("/file")] async fn file() -> Option<NamedFile> { NamedFile::open(env::temp_dir().join(FILENAME)).await.ok() } #[delete("/file")] async fn delete() -> Option<()> { fs::remove_file(env::temp_dir().join(FILENAME)).await.ok() } /***************************** `Stream` Responder *****************************/ use rocket::tokio::select; use rocket::tokio::time::{self, Duration}; use rocket::futures::stream::{repeat, StreamExt}; use rocket::Shutdown; use rocket::response::stream::TextStream; #[get("/stream/hi")] fn many_his() -> TextStream![&'static str] { TextStream(repeat("hi").take(100)) } #[get("/stream/hi/<n>")] fn one_hi_per_ms(mut shutdown: Shutdown, n: u8) -> TextStream![&'static str] { TextStream! { let mut interval = time::interval(Duration::from_millis(n as u64)); loop { select! { _ = interval.tick() => yield "hi", _ = &mut shutdown => { yield "goodbye"; break; } }; } } } /***************************** `Redirect` Responder ***************************/ use rocket::response::Redirect; #[get("/redir")] fn redir_root() -> Redirect { Redirect::to(uri!(redir_login)) } #[get("/redir/login")] fn redir_login() -> &'static str { "Hi! Please log in before continuing." } #[get("/redir/<name>")] fn maybe_redir(name: &str) -> Result<&'static str, Redirect> { match name { "Sergio" => Ok("Hello, Sergio!"), _ => Err(Redirect::to(uri!(redir_login))), } } /***************************** `content` Responders ***************************/ use rocket::Request; use rocket::response::content; #[get("/content", format = "xml", rank = 1)] fn xml() -> content::Xml<&'static str> { content::Xml("<payload>I'm here</payload>") } #[get("/content", format = "json", rank = 2)] fn json() -> content::Json<&'static str> { content::Json(r#"{ "payload": "I'm here" }"#) } #[catch(404)] fn not_found(request: &Request<'_>) -> content::Html<String> { let html = match request.format() { Some(ref mt) if !(mt.is_xml() || mt.is_html()) => { format!("<p>'{}' requests are not supported.</p>", mt) } _ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::Html(html) } /******************************* `Either` Responder ***************************/ use rocket::Either; use rocket::response::content::{Json, MsgPack}; use rocket::http::uncased::AsUncased; #[get("/content/<kind>")] fn json_or_msgpack(kind: &str) -> Either<Json<&'static str>, MsgPack<&'static [u8]>> { if kind.as_uncased() == "msgpack" { Either::Right(MsgPack(&[162, 104, 105])) } else { Either::Left(Json("\"hi\"")) } } /******************************* Custom Responder *****************************/ use std::borrow::Cow; use rocket::response::content::Html; #[derive(Responder)] enum StoredData { File(Option<NamedFile>), String(Cow<'static, str>), Bytes(Vec<u8>), #[response(status = 401)] NotAuthorized(Html<&'static str>), } #[derive(FromFormField, UriDisplayQuery)] enum Kind { File, String, Bytes } #[get("/custom?<kind>")] async fn custom(kind: Option<Kind>) -> StoredData { match kind { Some(Kind::File) => { let path = env::temp_dir().join(FILENAME); StoredData::File(NamedFile::open(path).await.ok()) }, Some(Kind::String) => StoredData::String("Hey, I'm some data.".into()), Some(Kind::Bytes) => StoredData::Bytes(vec![72, 105]), None => StoredData::NotAuthorized(Html("No no no!")) } } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![many_his, one_hi_per_ms, file, upload, delete]) .mount("/", routes![redir_root, redir_login, maybe_redir]) .mount("/", routes![xml, json, json_or_msgpack]) .mount("/", routes![custom]) .register("/", catchers![not_found]) }
#[macro_use] extern crate rocket; #[cfg(test)] mod tests; /****************** `Result`, `Option` `NameFile` Responder *******************/ use std::{io, env}; use rocket::tokio::fs; use rocket::data::{Capped, TempFile}; use rocket::response::NamedFile; const FILENAME: &str = "big_file.dat"; #[post("/file", data = "<file>")] async fn upload(mut file: Capped<TempFile<'_>>) -> io::Result<String> { file.persist_to(env::temp_dir().join(FILENAME)).await?; Ok(format!("{} bytes at {}", file.n.written, file.path().unwrap().display())) } #[get("/file")] async fn file() -> Option<NamedFile> { NamedFile::open(env::temp_dir().join(FILENAME)).await.ok() } #[delete("/file")] async fn delete() -> Option<()> { fs::remove_file(env::temp_dir().join(FILENAME)).await.ok() } /***************************** `Stream` Responder *****************************/ use rocket::tokio::select; use rocket::tokio::time::{self, Duration}; use rocket::futures::stream::{repeat, StreamExt}; use rocket::Shutdown; use rocket::response::stream::TextStream; #[get("/stream/hi")] fn many_his() -> TextStream![&'static str] { TextStream(repeat("hi").take(100)) } #[get("/stream/hi/<n>")] fn one_hi_per_ms(mut shutdown: Shutdown, n: u8) -> TextStream![&'static str] { TextStream! { let mut interval = time::interval(Duration::from_millis(n as u64)); loop { select! { _ = interval.tick() => yield "hi", _ = &mut shutdown => { yield "goodbye"; break; } }; } } } /***************************** `Redirect` Responder ***************************/ use rocket::response::Redirect; #[get("/redir")] fn redir_root() -> Redirect { Redirect::to(uri!(redir_login)) } #[get("/redir/login")] fn redir_login() -> &'static str { "Hi! Please log in before continuing." } #[get("/redir/<name>")] fn maybe_redir(name: &str) -> Result<&'static str, Redirect> { match name { "Sergio" => Ok("Hello, Sergio!"), _ => Err(Redirect::to(uri!(redir_login))), } } /***************************** `content` Responders ***************************/ use rocket::Request; use rocket::response::content; #[get("/content", format = "xml", rank = 1)] fn xml() -> content::Xml<&'static str> { content::Xml("<payload>I'm here</payload>") } #[get("/content", format = "json", rank = 2)] fn json() -> content::Json<&'static str> { content::Json(r#"{ "payload": "I'm here" }"#) } #[catch(404)] fn not_found(request: &Request<'_>) -> content::Html<String> { let html = match request.format() { Some(ref mt) if !(mt.is_xml() || mt.is_html()) => { format!("<p>'{}' requests are not supported.</p>", mt) } _ => format!("<p>Sorry, '{}' is an invalid path! Try \ /hello/&lt;name&gt;/&lt;age&gt; instead.</p>", request.uri()) }; content::Html(html) } /******************************* `Either` Responder ***************************/ use rocket::Either; use rocket::response::content::{Json, MsgPack}; use rocket::http::uncased::AsUncased; #[get("/content/<kind>")] fn json_or_msgpack(kind: &str) -> Either<Json<&'static str>, MsgPack<&'static [u8]>> { if kind.as_uncased() == "msgpack" { Either::Right(MsgPack(&[162, 104, 105])) } else { Either::Left(Json("\"hi\"")) } } /******************************* Custom Responder *****************************/ use std::borrow::Cow; use rocket::response::content::Html; #[derive(Responder)] enum StoredData { File(Option<NamedFile>), String(Cow<'static, str>), Bytes(Vec<u8>), #[response(status = 401)] NotAuthorized(Html<&'static str>), } #[derive(FromFormField, UriDisplayQuery)] enum Kind { File, String, Bytes } #[get("/custom?<kind>")] async fn custom(kind: Option<Kind>) -> StoredData { match kind { Some(Kind::File) => { let path = env::temp_dir().join(FILENAME); StoredData::File(NamedFile::open(path).await.ok()) }, Some(Kind::String) => StoredData::String("Hey, I'm some data.".into()), Some(Kind::Bytes) => StoredData::Bytes(vec![72, 105]), None => StoredData::NotAuthorized(Html("No no no!")) } } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![many_his, one_hi_per_ms, file, upload, delete]) .mount("/", routes![redir_root, redir_login, maybe_redir]) .
mount("/", routes![xml, json, json_or_msgpack]) .mount("/", routes![custom]) .register("/", catchers![not_found]) }
function_block-function_prefix_line
[ { "content": "#[rocket::post(\"/\", data = \"<_data>\", format = \"json\")]\n\nfn index(_data: rocket::Data) -> &'static str { \"json\" }\n\n\n", "file_path": "core/lib/tests/replace-content-type-518.rs", "rank": 3, "score": 552084.1880964399 }, { "content": "fn read_file_content(path: &str) -> Vec<u8> {\n\n let mut fp = File::open(&path).expect(&format!(\"Can't open {}\", path));\n\n let mut file_content = vec![];\n\n\n\n fp.read_to_end(&mut file_content).expect(&format!(\"Reading {} failed.\", path));\n\n file_content\n\n}\n\n\n", "file_path": "examples/static-files/src/tests.rs", "rank": 4, "score": 512684.00375040073 }, { "content": "#[rocket::post(\"/\", data = \"<_data>\", rank = 2)]\n\nfn other_index(_data: rocket::Data) -> &'static str { \"other\" }\n\n\n", "file_path": "core/lib/tests/replace-content-type-518.rs", "rank": 8, "score": 481764.87933238735 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail/typed-uris-bad-params.rs", "rank": 9, "score": 475593.02135465853 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n\nuse rocket::form::{FromFormField, Errors, ValueField, DataField};\n\n\n\n#[rocket::async_trait]\n\nimpl<'v> FromFormField<'v> for S {\n\n fn default() -> Option<Self> { None }\n\n\n\n fn from_value(_: ValueField<'v>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n\n\n async fn from_data(_: DataField<'v, '_>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n}\n\n\n", "file_path": "core/codegen/tests/ui-fail/typed-uri-bad-type.rs", "rank": 10, "score": 475593.02135465853 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n\nuse rocket::form::{FromFormField, Errors, ValueField, DataField};\n\n\n\n#[rocket::async_trait]\n\nimpl<'v> FromFormField<'v> for S {\n\n fn default() -> Option<Self> { None }\n\n\n\n fn from_value(_: ValueField<'v>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n\n\n async fn from_data(_: DataField<'v, '_>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n}\n\n\n", "file_path": "core/codegen/tests/ui-fail-stable/typed-uri-bad-type.rs", "rank": 11, "score": 470615.6083674575 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail-stable/typed-uris-bad-params.rs", "rank": 12, "score": 470615.60836745746 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n\nuse rocket::form::{FromFormField, Errors, ValueField, DataField};\n\n\n\n#[rocket::async_trait]\n\nimpl<'v> FromFormField<'v> for S {\n\n fn default() -> Option<Self> { None }\n\n\n\n fn from_value(_: ValueField<'v>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n\n\n async fn from_data(_: DataField<'v, '_>) -> Result<Self, Errors<'v>> { Ok(S) }\n\n}\n\n\n", "file_path": "core/codegen/tests/ui-fail-nightly/typed-uri-bad-type.rs", "rank": 13, "score": 470615.60836745746 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn optionals(id: Option<i32>, name: Result<String, &str>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail-nightly/typed-uris-bad-params.rs", "rank": 14, "score": 470615.60836745746 }, { "content": "#[head(\"/other\")]\n\nfn other() -> content::Json<&'static str> {\n\n content::Json(\"{ 'hi': 'hello' }\")\n\n}\n\n\n\nmod head_handling_tests {\n\n use super::*;\n\n\n\n use rocket::Route;\n\n use rocket::local::blocking::Client;\n\n use rocket::http::{Status, ContentType};\n\n\n\n fn routes() -> Vec<Route> {\n\n routes![index, empty, other]\n\n }\n\n\n\n #[test]\n\n fn auto_head() {\n\n let client = Client::debug_with(routes()).unwrap();\n\n let response = client.head(\"/\").dispatch();\n\n\n", "file_path": "core/lib/tests/head_handling.rs", "rank": 15, "score": 458583.19095340464 }, { "content": "#[post(\"/\", format = \"xml\")]\n\nfn xml() -> &'static str { \"xml\" }\n\n\n\n// Unreachable. Written for codegen.\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 16, "score": 457266.02708011324 }, { "content": "#[post(\"/\", format = \"msgpack\", rank = 2)]\n\nfn msgpack() -> &'static str { \"msgpack\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 17, "score": 457226.52682005323 }, { "content": "#[post(\"/\", format = \"json\")]\n\nfn json() -> &'static str { \"json\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 18, "score": 457178.6864156693 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn simple(id: i32, name: String) -> &'static str { \"\" }\n\n\n", "file_path": "core/codegen/tests/ui-fail/typed-uris-invalid-syntax.rs", "rank": 19, "score": 445855.1653133329 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn simple(id: i32, name: String) -> &'static str { \"\" }\n\n\n", "file_path": "core/codegen/tests/ui-fail-nightly/typed-uris-invalid-syntax.rs", "rank": 20, "score": 440608.5058477223 }, { "content": "#[post(\"/<id>/<name>\")]\n\nfn simple(id: i32, name: String) -> &'static str { \"\" }\n\n\n", "file_path": "core/codegen/tests/ui-fail-stable/typed-uris-invalid-syntax.rs", "rank": 21, "score": 440608.50584772223 }, { "content": "#[post(\"/\", format = \"text/html\")]\n\nfn specified_html() -> &'static str {\n\n \"specified_html\"\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n\n\n use rocket::{Rocket, Build};\n\n use rocket::local::blocking::Client;\n\n use rocket::http::{Status, ContentType};\n\n\n\n fn rocket() -> Rocket<Build> {\n\n rocket::build()\n\n .mount(\"/first\", routes![specified, unspecified])\n\n .mount(\"/second\", routes![specified_json, specified_html])\n\n }\n\n\n\n macro_rules! check_dispatch {\n\n ($mount:expr, $ct:expr, $body:expr) => (\n\n let client = Client::debug(rocket()).unwrap();\n", "file_path": "core/lib/tests/precise-content-type-matching.rs", "rank": 22, "score": 439071.39966792875 }, { "content": "#[post(\"/\", format = \"application/json\")]\n\nfn specified_json() -> &'static str {\n\n \"specified_json\"\n\n}\n\n\n", "file_path": "core/lib/tests/precise-content-type-matching.rs", "rank": 23, "score": 439025.564116553 }, { "content": "#[post(\"/\")]\n\nfn rg_ct(ct: Option<HasContentType>) -> &'static str {\n\n ct.map_or(\"Absent\", |_| \"Present\")\n\n}\n\n\n", "file_path": "core/lib/tests/local-request-content-type-issue-505.rs", "rank": 24, "score": 435687.2651321425 }, { "content": "#[post(\"/data\", rank = 2)]\n\nfn data_no_ct() -> &'static str {\n\n \"Data Absent\"\n\n}\n\n\n\nmod local_request_content_type_tests {\n\n use super::*;\n\n\n\n use rocket::{Rocket, Build};\n\n use rocket::local::blocking::Client;\n\n use rocket::http::ContentType;\n\n\n\n fn rocket() -> Rocket<Build> {\n\n rocket::build().mount(\"/\", routes![rg_ct, data_has_ct, data_no_ct])\n\n }\n\n\n\n #[test]\n\n fn has_no_ct() {\n\n let client = Client::debug(rocket()).unwrap();\n\n\n\n let req = client.post(\"/\");\n", "file_path": "core/lib/tests/local-request-content-type-issue-505.rs", "rank": 25, "score": 432237.772142661 }, { "content": "fn strict_encoded<T: 'static>(string: &'static str) -> Result<T, Errors<'static>>\n\n where for<'a> T: FromForm<'a>\n\n{\n\n Form::<Strict<T>>::parse_encoded(string.into()).map(|s| s.into_inner())\n\n}\n\n\n", "file_path": "core/codegen/tests/from_form.rs", "rank": 26, "score": 425371.97989811434 }, { "content": "#[post(\"/?<id>&<name>\")]\n\nfn optionals_q(id: Option<i32>, name: Result<String, Errors<'_>>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail/typed-uri-bad-type.rs", "rank": 27, "score": 425199.55446292576 }, { "content": "#[post(\"/?<id>&<name>\")]\n\nfn optionals_q(id: Option<i32>, name: Result<String, Errors<'_>>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail-stable/typed-uri-bad-type.rs", "rank": 28, "score": 420951.20410922164 }, { "content": "#[post(\"/?<id>&<name>\")]\n\nfn optionals_q(id: Option<i32>, name: Result<String, Errors<'_>>) { }\n\n\n", "file_path": "core/codegen/tests/ui-fail-nightly/typed-uri-bad-type.rs", "rank": 29, "score": 420951.2041092217 }, { "content": "#[post(\"/data\", data = \"<_ct>\", rank = 1)]\n\nfn data_has_ct(_ct: HasContentType) -> &'static str {\n\n \"Data Present\"\n\n}\n\n\n", "file_path": "core/lib/tests/local-request-content-type-issue-505.rs", "rank": 30, "score": 414104.14878626284 }, { "content": "#[get(\"/<_number>\", rank = 3)]\n\nfn get3(_number: u64) -> &'static str { \"3\" }\n\n\n", "file_path": "core/codegen/tests/route-ranking.rs", "rank": 31, "score": 410402.56520815706 }, { "content": "#[get(\"/<_number>\")]\n\nfn get0(_number: u8) -> &'static str { \"0\" }\n\n\n", "file_path": "core/codegen/tests/route-ranking.rs", "rank": 32, "score": 410351.0196030369 }, { "content": "#[catch(404)]\n\nfn hello_not_found(req: &Request<'_>) -> content::Html<String> {\n\n content::Html(format!(\"\\\n\n <p>Sorry, but '{}' is not a valid path!</p>\\\n\n <p>Try visiting /hello/&lt;name&gt;/&lt;age&gt; instead.</p>\",\n\n req.uri()))\n\n}\n\n\n", "file_path": "examples/error-handling/src/main.rs", "rank": 33, "score": 409676.43060612446 }, { "content": "#[get(\"/<path..>\", rank = 2)]\n\nfn none(path: Segments<'_>) -> String {\n\n path.collect::<Vec<_>>().join(\"/\")\n\n}\n\n\n", "file_path": "core/lib/tests/segments-issues-41-86.rs", "rank": 34, "score": 409664.87749059394 }, { "content": "#[track_caller]\n\nfn test_query_file<T> (path: &str, file: T, status: Status)\n\n where T: Into<Option<&'static str>>\n\n{\n\n let client = Client::tracked(rocket()).unwrap();\n\n let response = client.get(path).dispatch();\n\n assert_eq!(response.status(), status);\n\n\n\n let body_data = response.into_bytes();\n\n if let Some(filename) = file.into() {\n\n let expected_data = read_file_content(filename);\n\n assert!(body_data.map_or(false, |s| s == expected_data));\n\n }\n\n}\n\n\n", "file_path": "examples/static-files/src/tests.rs", "rank": 35, "score": 403834.6946031867 }, { "content": "#[catch(404)]\n\nfn general_not_found() -> content::Html<&'static str> {\n\n content::Html(r#\"\n\n <p>Hmm... What are you looking for?</p>\n\n Say <a href=\"/hello/Sergio/100\">hello!</a>\n\n \"#)\n\n}\n\n\n", "file_path": "examples/error-handling/src/main.rs", "rank": 36, "score": 402140.67823853437 }, { "content": "#[post(\"/\", format = \"application/json\")]\n\nfn specified() -> &'static str {\n\n \"specified\"\n\n}\n\n\n", "file_path": "core/lib/tests/precise-content-type-matching.rs", "rank": 37, "score": 397452.76520051435 }, { "content": "#[post(\"/\", rank = 2)]\n\nfn unspecified() -> &'static str {\n\n \"unspecified\"\n\n}\n\n\n", "file_path": "core/lib/tests/precise-content-type-matching.rs", "rank": 38, "score": 397446.8696958845 }, { "content": "#[post(\"/\", format = \"application/msgpack\")]\n\nfn msgpack_long() -> &'static str { \"msgpack_long\" }\n\n\n\n// Unreachable. Written for codegen.\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 39, "score": 397261.68951065285 }, { "content": "#[post(\"/\", format = \"application/json\", rank = 2)]\n\nfn json_long() -> &'static str { \"json_long\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 40, "score": 397231.7326341974 }, { "content": "#[get(\"/<name>/<age>\")]\n\nfn wave(name: &str, age: u8) -> String {\n\n format!(\"👋 Hello, {} year old named {}!\", age, name)\n\n}\n\n\n", "file_path": "examples/hello/src/main.rs", "rank": 41, "score": 396738.93464846467 }, { "content": "#[catch(404)]\n\nfn not_found(request: &Request) -> &'static str {\n\n request.cookies().add(Cookie::new(\"not_found\", \"404\"));\n\n \"404 - Not Found\"\n\n}\n\n\n", "file_path": "core/lib/tests/catcher-cookies-1213.rs", "rank": 42, "score": 394143.11017243634 }, { "content": "fn extract_id(from: &str) -> Option<String> {\n\n from.rfind('/').map(|i| &from[(i + 1)..]).map(|s| s.trim_end().to_string())\n\n}\n\n\n", "file_path": "examples/pastebin/src/tests.rs", "rank": 44, "score": 374652.3250465809 }, { "content": "#[get(\"/test/<path..>\")]\n\nfn test(path: Segments<'_>) -> String {\n\n path.collect::<Vec<_>>().join(\"/\")\n\n}\n\n\n", "file_path": "core/lib/tests/segments-issues-41-86.rs", "rank": 45, "score": 372335.2910283035 }, { "content": "fn starts_with<'v, S: AsRef<str>>(string: S, prefix: &str) -> Result<(), Errors<'v>> {\n\n if !string.as_ref().starts_with(prefix) {\n\n Err(Error::validation(format!(\"must start with {:?}\", prefix)))?\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "core/lib/tests/form-validation-names.rs", "rank": 46, "score": 371886.14064607583 }, { "content": "#[get(\"/use\")]\n\nfn used(flash: Option<FlashMessage<'_>>) -> Option<String> {\n\n flash.map(|f| f.message().into())\n\n}\n\n\n\nmod flash_lazy_remove_tests {\n\n use rocket::local::blocking::Client;\n\n use rocket::http::Status;\n\n\n\n #[test]\n\n fn test() {\n\n use super::*;\n\n\n\n // Ensure the cookie's not there at first.\n\n let client = Client::debug_with(routes![set, unused, used]).unwrap();\n\n let response = client.get(\"/unused\").dispatch();\n\n assert_eq!(response.status(), Status::NotFound);\n\n\n\n // Set the flash cookie.\n\n client.post(\"/\").dispatch();\n\n\n", "file_path": "core/lib/tests/flash-lazy-removes-issue-466.rs", "rank": 47, "score": 363388.8937741492 }, { "content": "#[allow(dead_code)]\n\n#[get(\"/unmanaged\")]\n\nfn unmanaged(_u8: rocket::State<'_, u8>, _string: rocket::State<'_, String>) { }\n\n\n", "file_path": "examples/error-handling/src/main.rs", "rank": 48, "score": 362612.51676267677 }, { "content": "#[get(\"/<_number>\", rank = 1)]\n\nfn get1(_number: u16) -> &'static str { \"1\" }\n\n\n", "file_path": "core/codegen/tests/route-ranking.rs", "rank": 49, "score": 362188.5610330369 }, { "content": "#[get(\"/<_number>\", rank = 2)]\n\nfn get2(_number: u32) -> &'static str { \"2\" }\n\n\n", "file_path": "core/codegen/tests/route-ranking.rs", "rank": 50, "score": 362188.5610330369 }, { "content": "#[catch(400)]\n\nfn catch(r#raw: &rocket::Request) -> String {\n\n format!(\"{}\", raw.method())\n\n}\n\n\n", "file_path": "core/codegen/tests/route-raw.rs", "rank": 51, "score": 361788.09242089366 }, { "content": "/// Splits a path into a name that may be used to identify the template, and the\n\n/// template's data type, if any.\n\nfn split_path(root: &Path, path: &Path) -> (String, Option<String>) {\n\n let rel_path = path.strip_prefix(root).unwrap().to_path_buf();\n\n let path_no_ext = remove_extension(&rel_path);\n\n let data_type = path_no_ext.extension();\n\n let mut name = remove_extension(&path_no_ext).to_string_lossy().into_owned();\n\n\n\n // Ensure template name consistency on Windows systems\n\n if cfg!(windows) {\n\n name = name.replace(\"\\\\\", \"/\");\n\n }\n\n\n\n (name, data_type.map(|d| d.to_string_lossy().into_owned()))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn template_path_index_html() {\n", "file_path": "contrib/lib/src/templates/context.rs", "rank": 52, "score": 357282.39389640355 }, { "content": "#[get(\"/\", rank = 3)]\n\nfn other() -> &'static str { \"other\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 53, "score": 357074.58867182716 }, { "content": "#[test]\n\nfn test_invalid_path() {\n\n test_query_file(\"/thou_shalt_not_exist\", None, Status::NotFound);\n\n test_query_file(\"/thou/shalt/not/exist\", None, Status::NotFound);\n\n test_query_file(\"/thou/shalt/not/exist?a=b&c=d\", None, Status::NotFound);\n\n}\n", "file_path": "examples/static-files/src/tests.rs", "rank": 55, "score": 348414.27919050417 }, { "content": "#[get(\"/\", format = \"binary\", rank = 2)]\n\nfn binary() -> &'static str { \"binary\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 56, "score": 346709.4399578802 }, { "content": "#[get(\"/\", format = \"plain\")]\n\nfn plain() -> &'static str { \"plain\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 57, "score": 346703.4613806297 }, { "content": "fn login(client: &Client, user: &str, pass: &str) -> Option<Cookie<'static>> {\n\n let response = client.post(session::uri!(login))\n\n .header(ContentType::Form)\n\n .body(format!(\"username={}&password={}\", user, pass))\n\n .dispatch();\n\n\n\n user_id_cookie(&response)\n\n}\n\n\n", "file_path": "examples/cookies/src/tests.rs", "rank": 58, "score": 345921.6228747482 }, { "content": "fn download_paste(client: &Client, id: &str) -> Option<String> {\n\n let response = client.get(uri!(super::retrieve: id)).dispatch();\n\n if response.status().class().is_success() {\n\n Some(response.into_string().unwrap())\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "examples/pastebin/src/tests.rs", "rank": 59, "score": 345875.3605972276 }, { "content": "fn test(uri: &str, content_type: ContentType, status: Status, body: String) {\n\n let client = Client::tracked(rocket()).unwrap();\n\n let response = client.get(uri).header(content_type).dispatch();\n\n assert_eq!(response.status(), status);\n\n assert_eq!(response.into_string(), Some(body));\n\n}\n\n\n", "file_path": "examples/manual-routing/src/tests.rs", "rank": 60, "score": 344224.2997848866 }, { "content": "fn uri_origin<'a>(path: &'a str, query: Option<&'a str>) -> Uri<'a> {\n\n Uri::Origin(Origin::new(path, query))\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/tests.rs", "rank": 61, "score": 341327.75601957034 }, { "content": "#[get(\"/\")]\n\nfn index() -> Html<&'static str> {\n\n Html(r#\"<a href=\"message\">Set a Message</a> or <a href=\"session\">Use Sessions</a>.\"#)\n\n}\n\n\n", "file_path": "examples/cookies/src/main.rs", "rank": 62, "score": 340931.40920153126 }, { "content": "#[get(\"/\")]\n\nfn index() -> Html<&'static str> {\n\n Html(r#\"See <a href=\"tera\">Tera</a> or <a href=\"hbs\">Handlebars</a>.\"#)\n\n}\n\n\n", "file_path": "examples/templating/src/main.rs", "rank": 63, "score": 340931.4092015313 }, { "content": "#[get(\"/\", format = \"application/foo\")]\n\nfn get_foo() -> &'static str { \"get_foo\" }\n\n\n\n// TODO: #[rocket(allow(unknown_format))]\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 64, "score": 337151.9088429648 }, { "content": "#[post(\"/\", format = \"application/foo\")]\n\nfn post_foo() -> &'static str { \"post_foo\" }\n\n\n\n// TODO: #[rocket(allow(unknown_format))]\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 65, "score": 337151.9088429648 }, { "content": "#[rocket::get(\"/\")]\n\nfn return_private_cookie(cookies: &CookieJar<'_>) -> Option<String> {\n\n match cookies.get_private(\"cookie_name\") {\n\n Some(cookie) => Some(cookie.value().into()),\n\n None => None,\n\n }\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n use rocket::routes;\n\n use rocket::local::blocking::Client;\n\n use rocket::http::{Cookie, Status};\n\n\n\n #[test]\n\n fn private_cookie_is_returned() {\n\n let rocket = rocket::build().mount(\"/\", routes![return_private_cookie]);\n\n\n\n let client = Client::debug(rocket).unwrap();\n\n let req = client.get(\"/\").private_cookie(Cookie::new(\"cookie_name\", \"cookie_value\"));\n\n let response = req.dispatch();\n", "file_path": "core/lib/tests/local_request_private_cookie-issue-368.rs", "rank": 66, "score": 336487.81960196386 }, { "content": "#[get(\"/<path..>\")]\n\nfn files(route: &Route, path: PathBuf) -> String {\n\n Path::new(route.uri.base()).join(path).normalized_str().to_string()\n\n}\n\n\n\nmod route_guard_tests {\n\n use super::*;\n\n use rocket::local::blocking::Client;\n\n\n\n fn assert_path(client: &Client, path: &str) {\n\n let res = client.get(path).dispatch();\n\n assert_eq!(res.into_string(), Some(path.into()));\n\n }\n\n\n\n #[test]\n\n fn check_mount_path() {\n\n let rocket = rocket::build()\n\n .mount(\"/first\", routes![files])\n\n .mount(\"/second\", routes![files]);\n\n\n\n let client = Client::debug(rocket).unwrap();\n\n assert_path(&client, \"/first/some/path\");\n\n assert_path(&client, \"/second/some/path\");\n\n assert_path(&client, \"/first/second/b/c\");\n\n assert_path(&client, \"/second/a/b/c\");\n\n }\n\n}\n", "file_path": "core/lib/tests/route_guard.rs", "rank": 67, "score": 333701.10122254374 }, { "content": "#[rocket::get(\"/<name>\")]\n\nfn hello_name(name: String) -> String {\n\n format!(\"Hello, {}! This is {}.\", name, rocket::uri!(hello_name: &name))\n\n}\n\n\n", "file_path": "core/lib/tests/scoped-uri.rs", "rank": 68, "score": 331110.7115792236 }, { "content": "#[rocket::launch]\n\nfn rocket() -> _ {\n\n rocket::build()\n\n .mount(\"/\", rocket::routes![manual::second])\n\n .mount(\"/\", StaticFiles::from(crate_relative!(\"static\")))\n\n}\n", "file_path": "examples/static-files/src/main.rs", "rank": 69, "score": 328822.51353934855 }, { "content": "#[get(\"/static/<user>/is/<path..>\")]\n\nfn dual(user: String, path: Segments<'_>) -> String {\n\n user + \"/is/\" + &path.collect::<Vec<_>>().join(\"/\")\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n use rocket::local::blocking::Client;\n\n\n\n #[test]\n\n fn segments_works() {\n\n let rocket = rocket::build()\n\n .mount(\"/\", routes![test, two, one_two, none, dual])\n\n .mount(\"/point\", routes![test, two, one_two, dual]);\n\n let client = Client::debug(rocket).unwrap();\n\n\n\n // We construct a path that matches each of the routes above. We ensure the\n\n // prefix is stripped, confirming that dynamic segments are working.\n\n for prefix in &[\"\", \"/test\", \"/two\", \"/one/two\",\n\n \"/point/test\", \"/point/two\", \"/point/one/two\",\n\n \"/static\", \"/point/static\"]\n\n {\n\n let path = \"this/is/the/path/we/want\";\n\n let response = client.get(format!(\"{}/{}\", prefix, path)).dispatch();\n\n assert_eq!(response.into_string(), Some(path.into()));\n\n }\n\n }\n\n}\n", "file_path": "core/lib/tests/segments-issues-41-86.rs", "rank": 70, "score": 328486.02514669986 }, { "content": "#[get(\"/\", format = \"bar/baz\", rank = 2)]\n\nfn get_bar_baz() -> &'static str { \"get_bar_baz\" }\n\n\n\n// TODO: #[rocket(allow(unknown_format))]\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 71, "score": 328332.4499299205 }, { "content": "#[put(\"/\", format = \"bar/baz\")]\n\nfn put_bar_baz() -> &'static str { \"put_bar_baz\" }\n\n\n", "file_path": "core/codegen/tests/route-format.rs", "rank": 72, "score": 328326.529347823 }, { "content": "#[get(\"/two/<path..>\")]\n\nfn two(path: Segments<'_>) -> String {\n\n path.collect::<Vec<_>>().join(\"/\")\n\n}\n\n\n", "file_path": "core/lib/tests/segments-issues-41-86.rs", "rank": 73, "score": 325767.38188163796 }, { "content": "#[patch(\"/\", data = \"<form_data>\")]\n\nfn bug(form_data: Form<FormData>) -> &'static str {\n\n assert_eq!(\"Form data\", form_data.into_inner().form_data);\n\n \"OK\"\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n use rocket::local::blocking::Client;\n\n use rocket::http::{Status, ContentType};\n\n\n\n #[test]\n\n fn method_eval() {\n\n let client = Client::debug_with(routes![bug]).unwrap();\n\n let response = client.post(\"/\")\n\n .header(ContentType::Form)\n\n .body(\"_method=patch&form_data=Form+data\")\n\n .dispatch();\n\n\n\n assert_eq!(response.into_string(), Some(\"OK\".into()));\n\n }\n", "file_path": "core/lib/tests/form_method-issue-45.rs", "rank": 74, "score": 324976.45362664806 }, { "content": "fn upload_paste(client: &Client, body: &str) -> String {\n\n let response = client.post(uri!(super::upload)).body(body).dispatch();\n\n assert_eq!(response.status(), Status::Ok);\n\n assert_eq!(response.content_type(), Some(ContentType::Plain));\n\n extract_id(&response.into_string().unwrap()).unwrap()\n\n}\n\n\n", "file_path": "examples/pastebin/src/tests.rs", "rank": 75, "score": 324790.2460548675 }, { "content": "#[get(\"/<_>/b/<path..>\", rank = 1)]\n\nfn segments(path: PathString) -> String {\n\n format!(\"nonempty+{}\", path.0)\n\n}\n\n\n", "file_path": "core/codegen/tests/route.rs", "rank": 76, "score": 322901.66931875853 }, { "content": "#[get(\"/one/two/<path..>\")]\n\nfn one_two(path: Segments<'_>) -> String {\n\n path.collect::<Vec<_>>().join(\"/\")\n\n}\n\n\n", "file_path": "core/lib/tests/segments-issues-41-86.rs", "rank": 77, "score": 321884.3525314779 }, { "content": "fn test_root(kind: &str) {\n\n // Check that the redirect works.\n\n let client = Client::tracked(rocket()).unwrap();\n\n for method in &[Get, Head] {\n\n let response = client.req(*method, format!(\"/{}\", kind)).dispatch();\n\n assert_eq!(response.status(), Status::SeeOther);\n\n assert!(response.body().is_none());\n\n\n\n let location = response.headers().get_one(\"Location\").unwrap();\n\n assert_eq!(location, format!(\"/{}/hello/Your%20Name\", kind));\n\n }\n\n\n\n // Check that other request methods are not accepted (and instead caught).\n\n for method in &[Post, Put, Delete, Options, Trace, Connect, Patch] {\n\n let mut map = std::collections::HashMap::new();\n\n map.insert(\"path\", format!(\"/{}\", kind));\n\n let expected = Template::show(client.rocket(), format!(\"{}/error/404\", kind), &map);\n\n\n\n let response = client.req(*method, format!(\"/{}\", kind)).dispatch();\n\n assert_eq!(response.status(), Status::NotFound);\n\n assert_eq!(response.into_string(), expected);\n\n }\n\n}\n\n\n", "file_path": "examples/templating/src/tests.rs", "rank": 78, "score": 321106.8731243509 }, { "content": "fn strict<'f, T: FromForm<'f>>(string: &'f str) -> Result<T, Errors<'f>> {\n\n Form::<Strict<T>>::parse(string).map(|s| s.into_inner())\n\n}\n\n\n", "file_path": "core/codegen/tests/from_form.rs", "rank": 79, "score": 320068.3023779142 }, { "content": "fn lenient<'f, T: FromForm<'f>>(string: &'f str) -> Result<T, Errors<'f>> {\n\n Form::<T>::parse(string)\n\n}\n\n\n", "file_path": "core/codegen/tests/from_form.rs", "rank": 80, "score": 320068.3023779142 }, { "content": "#[get(\"/<path..>\", rank = 2)]\n\nfn segments_empty(path: PathString) -> String {\n\n format!(\"empty+{}\", path.0)\n\n}\n\n\n", "file_path": "core/codegen/tests/route.rs", "rank": 81, "score": 319430.04511937633 }, { "content": "#[parser]\n\nfn quoted_string<'a>(input: &mut Input<'a>) -> Result<'a, Extent<&'a str>> {\n\n eat('\"')?;\n\n\n\n let mut is_escaped = false;\n\n let inner = take_while(|&c| {\n\n if is_escaped { is_escaped = false; return true; }\n\n if c == '\\\\' { is_escaped = true; return true; }\n\n c != '\"'\n\n })?;\n\n\n\n eat('\"')?;\n\n inner\n\n}\n\n\n", "file_path": "core/http/src/parse/media_type.rs", "rank": 82, "score": 318065.13177627686 }, { "content": "#[get(\"/\")]\n\nfn index(hit_count: State<'_, HitCount>) -> content::Html<String> {\n\n let count = hit_count.0.fetch_add(1, Ordering::Relaxed) + 1;\n\n content::Html(format!(\"Your visit is recorded!<br /><br />Visits: {}\", count))\n\n}\n\n\n", "file_path": "examples/state/src/managed_hit_count.rs", "rank": 83, "score": 315057.4507033984 }, { "content": "#[get(\"/hello/<name>\")]\n\nfn hello(name: String) -> String {\n\n format!(\"Hello, {}!\", name)\n\n}\n\n\n", "file_path": "core/lib/tests/uri-percent-encoding-issue-808.rs", "rank": 84, "score": 314919.3113749431 }, { "content": "#[inline]\n\npub fn from_str(s: &str) -> Result<Uri<'_>, Error<'_>> {\n\n Ok(parse!(uri: RawInput::new(s.as_bytes()))?)\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/mod.rs", "rank": 85, "score": 314735.5033268648 }, { "content": "#[parser]\n\nfn port_from<'a>(input: &mut RawInput<'a>, bytes: &[u8]) -> Result<'a, u16> {\n\n let mut port_num: u32 = 0;\n\n for (b, i) in bytes.iter().rev().zip(&[1, 10, 100, 1000, 10000]) {\n\n if !b.is_ascii_digit() {\n\n parse_error!(\"port byte is out of range\")?;\n\n }\n\n\n\n port_num += (b - b'0') as u32 * i;\n\n }\n\n\n\n if port_num > u16::max_value() as u32 {\n\n parse_error!(\"port out of range: {}\", port_num)?;\n\n }\n\n\n\n Ok(port_num as u16)\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/parser.rs", "rank": 86, "score": 314702.945256299 }, { "content": "#[get(\"/\")]\n\nfn hello() -> &'static str {\n\n \"Hello, world!\"\n\n}\n\n\n", "file_path": "examples/testing/src/main.rs", "rank": 87, "score": 313250.59991698177 }, { "content": "#[get(\"/hello/<name>/<age>\")]\n\nfn hello(name: &str, age: i8) -> String {\n\n format!(\"Hello, {} year old named {}!\", age, name)\n\n}\n\n\n", "file_path": "examples/error-handling/src/main.rs", "rank": 88, "score": 312149.31307608134 }, { "content": "fn hi<'r>(req: &'r Request, _: Data) -> route::BoxFuture<'r> {\n\n route::Outcome::from(req, \"Hello!\").pin()\n\n}\n\n\n", "file_path": "examples/manual-routing/src/main.rs", "rank": 89, "score": 311504.65173769696 }, { "content": "pub fn prefix_last_segment(path: &mut syn::Path, prefix: &str) {\n\n let mut last_seg = path.segments.last_mut().expect(\"syn::Path has segments\");\n\n last_seg.ident = last_seg.ident.prepend(prefix);\n\n}\n\n\n", "file_path": "core/codegen/src/bang/uri.rs", "rank": 90, "score": 311429.255403228 }, { "content": "#[inline]\n\npub fn absolute_from_str(s: &str) -> Result<Absolute<'_>, Error<'_>> {\n\n Ok(parse!(absolute_only: RawInput::new(s.as_bytes()))?)\n\n}\n", "file_path": "core/http/src/parse/uri/mod.rs", "rank": 91, "score": 311403.2409780779 }, { "content": "#[inline]\n\npub fn origin_from_str(s: &str) -> Result<Origin<'_>, Error<'_>> {\n\n Ok(parse!(origin: RawInput::new(s.as_bytes()))?)\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/mod.rs", "rank": 92, "score": 311403.2409780779 }, { "content": "#[inline]\n\npub fn authority_from_str(s: &str) -> Result<Authority<'_>, Error<'_>> {\n\n Ok(parse!(authority_only: RawInput::new(s.as_bytes()))?)\n\n}\n\n\n", "file_path": "core/http/src/parse/uri/mod.rs", "rank": 93, "score": 311403.2409780779 }, { "content": "fn name<'a>(req: &'a Request, _: Data) -> route::BoxFuture<'a> {\n\n let param = req.param::<&'a str>(0)\n\n .and_then(|res| res.ok())\n\n .unwrap_or(\"unnamed\".into());\n\n\n\n route::Outcome::from(req, param).pin()\n\n}\n\n\n", "file_path": "examples/manual-routing/src/main.rs", "rank": 94, "score": 311223.33105657285 }, { "content": "#[catch(default)]\n\nfn default_catcher(status: Status, req: &Request<'_>) -> status::Custom<String> {\n\n let msg = format!(\"{} ({})\", status, req.uri());\n\n status::Custom(status, msg)\n\n}\n\n\n", "file_path": "examples/error-handling/src/main.rs", "rank": 95, "score": 310882.70033174375 }, { "content": "#[get(\"/\")]\n\nfn index(cookies: &CookieJar<'_>) -> &'static str {\n\n cookies.add(Cookie::new(\"index\", \"hi\"));\n\n \"Hello, world!\"\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n use rocket::local::blocking::Client;\n\n use rocket::fairing::AdHoc;\n\n\n\n #[test]\n\n fn error_catcher_sets_cookies() {\n\n let rocket = rocket::build()\n\n .mount(\"/\", routes![index])\n\n .register(\"/\", catchers![not_found])\n\n .attach(AdHoc::on_request(\"Add Cookie\", |req, _| Box::pin(async move {\n\n req.cookies().add(Cookie::new(\"fairing\", \"woo\"));\n\n })));\n\n\n\n let client = Client::debug(rocket).unwrap();\n", "file_path": "core/lib/tests/catcher-cookies-1213.rs", "rank": 96, "score": 309913.65391395654 }, { "content": "#[get(\"/\")]\n\nfn index() -> &'static str {\n\n \"Hello, world!\"\n\n}\n\n\n", "file_path": "core/lib/tests/head_handling.rs", "rank": 97, "score": 309033.2498913109 }, { "content": "#[catch(500)]\n\nfn ise() -> &'static str {\n\n \"Hey, sorry! :(\"\n\n}\n\n\n", "file_path": "core/lib/tests/panic-handling.rs", "rank": 98, "score": 309033.2498913109 }, { "content": "#[allow(dead_code)]\n\n#[post(\"/<_unused_param>?<_unused_query>\", data=\"<_unused_data>\")]\n\nfn test_unused_params(_unused_param: String, _unused_query: String, _unused_data: Data) {\n\n}\n\n\n", "file_path": "core/codegen/tests/route.rs", "rank": 99, "score": 308426.8878058316 } ]
Rust
crates/shell/src/minifb/window.rs
Dmitry-Borodin/orbtk
235e0d84f7914605e28b8c313e4f21d00e6208b0
use std::{cell::RefCell, rc::Rc, sync::mpsc}; use derive_more::Constructor; use super::{KeyState, MouseState, WindowState, CONSOLE}; use crate::{ event::{ButtonState, KeyEvent, MouseButton, MouseEvent}, render::RenderContext2D, window_adapter::WindowAdapter, WindowRequest, }; #[derive(Constructor)] pub struct Window<A> where A: WindowAdapter, { window: minifb::Window, adapter: A, render_context: RenderContext2D, request_receiver: Option<mpsc::Receiver<WindowRequest>>, window_state: WindowState, mouse: MouseState, update: bool, redraw: bool, close: bool, key_states: Vec<KeyState>, key_events: Rc<RefCell<Vec<KeyEvent>>>, } impl<A> Window<A> where A: WindowAdapter, { fn push_mouse_event(&mut self, pressed: bool, button: MouseButton) { let state = if pressed { ButtonState::Down } else { ButtonState::Up }; self.adapter.mouse_event(MouseEvent { x: self.mouse.mouse_pos.0 as f64, y: self.mouse.mouse_pos.1 as f64, button, state, }); } fn push_key_down_event(&mut self, index: usize) { let key_repeat = match self.key_states.get(index).unwrap().minifb_key { minifb::Key::Left | minifb::Key::Right | minifb::Key::Up | minifb::Key::Down | minifb::Key::Backspace | minifb::Key::Delete => minifb::KeyRepeat::Yes, _ => minifb::KeyRepeat::No, }; if self .window .is_key_pressed(self.key_states.get(index).unwrap().minifb_key, key_repeat) { self.adapter.key_event(KeyEvent { key: self.key_states.get(index).unwrap().key, state: ButtonState::Down, text: String::default(), }); self.update = true; } } fn push_key_up_event(&mut self, index: usize) { if self .window .is_key_released(self.key_states.get(index).unwrap().minifb_key) { self.adapter.key_event(KeyEvent { key: self.key_states.get(index).unwrap().key, state: ButtonState::Up, text: String::default(), }); self.update = true; } } pub fn is_open(&self) -> bool { self.window.is_open() && !self.close } pub fn drain_events(&mut self) { self.window.update(); if let Some(pos) = self.window.get_mouse_pos(minifb::MouseMode::Discard) { if (pos.0.floor(), pos.1.floor()) != self.mouse.mouse_pos { self.adapter.mouse(pos.0 as f64, pos.1 as f64); self.mouse.mouse_pos = (pos.0.floor(), pos.1.floor()); self.update = true; } } let left_button_down = self.window.get_mouse_down(minifb::MouseButton::Left); let middle_button_down = self.window.get_mouse_down(minifb::MouseButton::Middle); let right_button_down = self.window.get_mouse_down(minifb::MouseButton::Right); if left_button_down != self.mouse.button_left { if left_button_down { self.push_mouse_event(true, MouseButton::Left); } else { self.push_mouse_event(false, MouseButton::Left); } self.mouse.button_left = left_button_down; self.update = true; } if middle_button_down != self.mouse.button_middle { if middle_button_down { self.push_mouse_event(true, MouseButton::Middle); } else { self.push_mouse_event(false, MouseButton::Middle); } self.mouse.button_middle = middle_button_down; self.update = true; } if right_button_down != self.mouse.button_right { if right_button_down { self.push_mouse_event(true, MouseButton::Right); } else { self.push_mouse_event(false, MouseButton::Right); } self.mouse.button_right = right_button_down; self.update = true; } if let Some(delta) = self.window.get_scroll_wheel() { self.adapter.scroll(delta.0 as f64, delta.1 as f64); self.update = true; } if self.window_state.size != self.window.get_size() { self.window_state.size = self.window.get_size(); self.render_context.resize( self.window_state.size.0 as f64, self.window_state.size.1 as f64, ); self.adapter.resize( self.window_state.size.0 as f64, self.window_state.size.1 as f64, ); self.update = true; } if self.window_state.active != self.window.is_active() { self.adapter.active(self.window.is_active()); self.window_state.active = self.window.is_active(); } while let Some(event) = self.key_events.borrow_mut().pop() { self.adapter.key_event(event); self.update = true; } for i in 0..self.key_states.len() { self.push_key_down_event(i); self.push_key_up_event(i); } } pub fn receive_requests(&mut self) { if let Some(request_receiver) = &self.request_receiver { for request in request_receiver.try_iter() { match request { WindowRequest::Redraw => { self.update = true; self.redraw = true; } WindowRequest::ChangeTitle(title) => { self.window.set_title(&title); self.update = true; self.redraw = true; } WindowRequest::Close => { self.close = true; } } } } } pub fn update(&mut self) { if !self.update { return; } self.adapter.run(&mut self.render_context); self.update = false; self.redraw = true; } pub fn render(&mut self) { if self.redraw { if let Some(data) = self.render_context.data() { let _ = self.window.update_with_buffer( data, self.window_state.size.0 as usize, self.window_state.size.1 as usize, ); self.redraw = false; } } } }
use std::{cell::RefCell, rc::Rc, sync::mpsc}; use derive_more::Constructor; use super::{KeyState, MouseState, WindowState, CONSOLE}; use crate::{ event::{ButtonState, KeyEvent, MouseButton, MouseEvent}, render::RenderContext2D, window_adapter::WindowAdapter, WindowRequest, }; #[derive(Constructor)] pub struct Window<A> where A: WindowAdapter, { window: minifb::Window, adapter: A, render_context: RenderContext2D, request_receiver: Option<mpsc::Receiver<WindowRequest>>, window_state: WindowState, mouse: MouseState, update: bool, redraw: bool, close: bool, key_states: Vec<KeyState>, key_events: Rc<RefCell<Vec<KeyEvent>>>, } impl<A> Window<A> where A: WindowAdapter, { fn push_mouse_event(&mut self, pressed: bool, button: MouseButton) { let state = if pressed { ButtonState::Down } else { ButtonState::Up }; self.adapter.mouse_event(MouseEvent { x: self.mouse.mouse_pos.0 as f64, y: self.mouse.mouse_pos.1 as f64, button, state, }); } fn push_key_down_event(&mut self, index: usize) { let key_repeat = match self.key_states.get(index).unwrap().minifb_key { minifb::Key::Left | minifb::Key::Right |
fn push_key_up_event(&mut self, index: usize) { if self .window .is_key_released(self.key_states.get(index).unwrap().minifb_key) { self.adapter.key_event(KeyEvent { key: self.key_states.get(index).unwrap().key, state: ButtonState::Up, text: String::default(), }); self.update = true; } } pub fn is_open(&self) -> bool { self.window.is_open() && !self.close } pub fn drain_events(&mut self) { self.window.update(); if let Some(pos) = self.window.get_mouse_pos(minifb::MouseMode::Discard) { if (pos.0.floor(), pos.1.floor()) != self.mouse.mouse_pos { self.adapter.mouse(pos.0 as f64, pos.1 as f64); self.mouse.mouse_pos = (pos.0.floor(), pos.1.floor()); self.update = true; } } let left_button_down = self.window.get_mouse_down(minifb::MouseButton::Left); let middle_button_down = self.window.get_mouse_down(minifb::MouseButton::Middle); let right_button_down = self.window.get_mouse_down(minifb::MouseButton::Right); if left_button_down != self.mouse.button_left { if left_button_down { self.push_mouse_event(true, MouseButton::Left); } else { self.push_mouse_event(false, MouseButton::Left); } self.mouse.button_left = left_button_down; self.update = true; } if middle_button_down != self.mouse.button_middle { if middle_button_down { self.push_mouse_event(true, MouseButton::Middle); } else { self.push_mouse_event(false, MouseButton::Middle); } self.mouse.button_middle = middle_button_down; self.update = true; } if right_button_down != self.mouse.button_right { if right_button_down { self.push_mouse_event(true, MouseButton::Right); } else { self.push_mouse_event(false, MouseButton::Right); } self.mouse.button_right = right_button_down; self.update = true; } if let Some(delta) = self.window.get_scroll_wheel() { self.adapter.scroll(delta.0 as f64, delta.1 as f64); self.update = true; } if self.window_state.size != self.window.get_size() { self.window_state.size = self.window.get_size(); self.render_context.resize( self.window_state.size.0 as f64, self.window_state.size.1 as f64, ); self.adapter.resize( self.window_state.size.0 as f64, self.window_state.size.1 as f64, ); self.update = true; } if self.window_state.active != self.window.is_active() { self.adapter.active(self.window.is_active()); self.window_state.active = self.window.is_active(); } while let Some(event) = self.key_events.borrow_mut().pop() { self.adapter.key_event(event); self.update = true; } for i in 0..self.key_states.len() { self.push_key_down_event(i); self.push_key_up_event(i); } } pub fn receive_requests(&mut self) { if let Some(request_receiver) = &self.request_receiver { for request in request_receiver.try_iter() { match request { WindowRequest::Redraw => { self.update = true; self.redraw = true; } WindowRequest::ChangeTitle(title) => { self.window.set_title(&title); self.update = true; self.redraw = true; } WindowRequest::Close => { self.close = true; } } } } } pub fn update(&mut self) { if !self.update { return; } self.adapter.run(&mut self.render_context); self.update = false; self.redraw = true; } pub fn render(&mut self) { if self.redraw { if let Some(data) = self.render_context.data() { let _ = self.window.update_with_buffer( data, self.window_state.size.0 as usize, self.window_state.size.1 as usize, ); self.redraw = false; } } } }
minifb::Key::Up | minifb::Key::Down | minifb::Key::Backspace | minifb::Key::Delete => minifb::KeyRepeat::Yes, _ => minifb::KeyRepeat::No, }; if self .window .is_key_pressed(self.key_states.get(index).unwrap().minifb_key, key_repeat) { self.adapter.key_event(KeyEvent { key: self.key_states.get(index).unwrap().key, state: ButtonState::Down, text: String::default(), }); self.update = true; } }
function_block-function_prefix_line
[ { "content": "fn get_mouse_button(button: event::MouseButton) -> MouseButton {\n\n match button {\n\n event::MouseButton::Wheel => MouseButton::Middle,\n\n event::MouseButton::Right => MouseButton::Right,\n\n _ => MouseButton::Left,\n\n }\n\n}\n\n\n", "file_path": "crates/shell/src/web/window.rs", "rank": 0, "score": 277267.9075084544 }, { "content": "/// Checks if the given point is inside of a widget.\n\npub fn check_mouse_condition(mouse_position: Point, widget: &WidgetContainer<'_>) -> bool {\n\n let enabled = widget.get::<bool>(\"enabled\");\n\n\n\n if !enabled {\n\n return false;\n\n }\n\n\n\n let bounds = widget.get::<Rectangle>(\"bounds\");\n\n let position = widget.get::<Point>(\"position\");\n\n\n\n let mut rect = Rectangle::new(0.0, 0.0, bounds.width(), bounds.height());\n\n\n\n rect.set_x(position.x);\n\n rect.set_y(position.y);\n\n\n\n rect.contains((mouse_position.x, mouse_position.y))\n\n}\n\n\n\n/// `MouseMoveEvent` indicates if the mouse position is changed on the window.\n\n#[derive(Event)]\n", "file_path": "crates/api/src/event/mouse.rs", "rank": 1, "score": 231121.3571990885 }, { "content": "/// Creates a `WindowAdapter` and a `WindowSettings` object from a window builder closure.\n\npub fn create_window<F: Fn(&mut BuildContext) -> Entity + 'static>(\n\n app_name: impl Into<String>,\n\n request_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,\n\n create_fn: F,\n\n) -> (WindowAdapter, WindowSettings, mpsc::Receiver<WindowRequest>) {\n\n let app_name = app_name.into();\n\n let mut world: World<Tree, StringComponentStore, render::RenderContext2D> =\n\n World::from_stores(Tree::default(), StringComponentStore::default());\n\n\n\n let (sender, receiver) = mpsc::channel();\n\n\n\n let registry = Rc::new(RefCell::new(Registry::new()));\n\n\n\n if app_name.is_empty() {\n\n registry\n\n .borrow_mut()\n\n .register(\"settings\", Settings::default());\n\n } else {\n\n registry\n\n .borrow_mut()\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 2, "score": 225843.94238588677 }, { "content": "#[derive(Default, AsAny)]\n\nstruct WindowState {\n\n actions: VecDeque<Action>,\n\n background: Brush,\n\n title: String\n\n}\n\n\n\nimpl WindowState {\n\n fn push_action(&mut self, action: Action) {\n\n self.actions.push_front(action);\n\n }\n\n\n\n fn resize(&self, width: f64, height: f64, ctx: &mut Context) {\n\n ctx.window()\n\n .get_mut::<Rectangle>(\"bounds\")\n\n .set_size(width, height);\n\n ctx.window()\n\n .get_mut::<Constraint>(\"constraint\")\n\n .set_size(width, height);\n\n }\n\n\n", "file_path": "crates/widgets/src/window.rs", "rank": 3, "score": 200251.6292827576 }, { "content": "/// The `WindowAdapter` represents the bridge to the `Shell` backend.\n\n/// It receives events from the `Window` and runs it's own logic. \n\npub trait WindowAdapter {\n\n /// Is called after the window is resized.\n\n fn resize(&mut self, _width: f64, _height: f64) {}\n\n\n\n /// Is called after the mouse was moved.\n\n fn mouse(&mut self, _x: f64, _y: f64) {}\n\n\n\n /// Is called after the state of a mouse button is changed.\n\n fn mouse_event(&mut self, _event: MouseEvent) {}\n\n\n\n /// Is called if mouse wheel or trackpad detect scroll event.\n\n fn scroll(&mut self, _delta_x: f64, _delta_y: f64) {}\n\n\n\n /// Is called after the state of a keyboard key is changed.\n\n fn key_event(&mut self, _event: KeyEvent) {}\n\n\n\n /// Is called after the quit event of the window is called.\n\n fn quit_event(&mut self) {}\n\n\n\n /// Gets the current mouse position.\n\n fn mouse_position(&self) -> Point;\n\n\n\n /// Is called if active state of the window is changed.\n\n fn active(&mut self, active: bool);\n\n\n\n /// Runs the inner logic of the shell adapter.\n\n fn run(&mut self, render_context: &mut RenderContext2D);\n\n}\n", "file_path": "crates/shell/src/window_adapter.rs", "rank": 4, "score": 200185.49960281645 }, { "content": "fn calculate_thumb_x(mouse_x: f64, thumb_width: f64, slider_x: f64, track_width: f64) -> f64 {\n\n (mouse_x - slider_x - thumb_width)\n\n .max(0.0)\n\n .min(track_width - thumb_width)\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 5, "score": 197910.85037622933 }, { "content": "/// Used to define a state of a widget.\n\n///\n\n/// A state is used to operate on the properties (components) of the widget, its parent or children.\n\npub trait State: AsAny {\n\n /// Init is used for initial setup.\n\n fn init(&mut self, _: &mut Registry, _: &mut Context) {}\n\n\n\n /// Used to cleanup the state and is called after window close is requested.\n\n fn cleanup(&mut self, _: &mut Registry, _: &mut Context) {}\n\n\n\n /// Updates the state for the given `ctx`.\n\n ///\n\n /// This update method is called before layout is calculated.\n\n fn update(&mut self, _: &mut Registry, _: &mut Context) {}\n\n\n\n /// Updates the state for the given `ctx`.\n\n ///\n\n /// This update method is called after layout is calculated and before rendering.\n\n fn update_post_layout(&mut self, _: &mut Registry, _: &mut Context) {}\n\n}\n", "file_path": "crates/api/src/widget/state.rs", "rank": 6, "score": 172299.2305854421 }, { "content": "fn adjust_minimum(minimum: f64, maximum: f64) -> f64 {\n\n if minimum > maximum {\n\n return maximum;\n\n }\n\n\n\n minimum\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 7, "score": 169436.28355020395 }, { "content": "fn adjust_maximum(minimum: f64, maximum: f64) -> f64 {\n\n if maximum < minimum {\n\n return minimum;\n\n }\n\n\n\n maximum\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 8, "score": 169436.28355020395 }, { "content": "fn adjust_value(value: f64, minimum: f64, maximum: f64) -> f64 {\n\n if value < minimum {\n\n return minimum;\n\n }\n\n\n\n if value > maximum {\n\n return maximum;\n\n }\n\n\n\n value\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 9, "score": 167921.72021883278 }, { "content": "// Check constraint for the given\n\nfn constrain(val: f64, min: f64, max: f64, size: f64) -> f64 {\n\n if min == 0.0 && max == 0.0 && size > 0.0 {\n\n size\n\n } else if val < min && min > 0.0 {\n\n min\n\n } else if val > max && max > 0.0 {\n\n max\n\n } else {\n\n val\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_width() {\n\n let width = 12.0;\n\n\n", "file_path": "crates/api/src/properties/layout/constraint.rs", "rank": 10, "score": 164376.00617987837 }, { "content": "fn calculate_width(curren_progress: f64, max_width: f64) -> f64 {\n\n if curren_progress == RANGE_MIN {\n\n return 0.01;\n\n } else {\n\n if curren_progress == RANGE_MAX {\n\n return max_width * 0.99;\n\n } else if curren_progress > RANGE_MIN && curren_progress < RANGE_MAX {\n\n return max_width * curren_progress;\n\n } else {\n\n return max_width * 0.99;\n\n }\n\n }\n\n}\n\n\n\nwidget!(\n\n /// The `ProgressBar` widget is used to indicating a finite progress\n\n /// (e.g. copying a file, downloading a video from the internet).\n\n /// A progress is visually represented as a horizontal bar which grows when the progress advances.\n\n /// The ProgressBar expects values between 0.0 and 1.0, whereas 0.0 means 0%, and 1.0 means 100%.\n\n /// Any value outside of this range cosidered as 100%.\n", "file_path": "crates/widgets/src/progress_bar.rs", "rank": 11, "score": 163903.75539001328 }, { "content": "#[derive(AsAny, Default)]\n\nstruct MainState {\n\n show_window: bool,\n\n}\n\n\n\nimpl MainState {\n\n fn show_window(&mut self) {\n\n self.show_window = true;\n\n }\n\n}\n\n\n\nimpl State for MainState {\n\n fn update(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n if self.show_window {\n\n ctx.child(\"button\").set(\"enabled\", false);\n\n ctx.show_window(|ctx| {\n\n Window::create()\n\n .title(\"Dialog\")\n\n .position((120.0, 120.0))\n\n .size(100.0, 75.0)\n\n .child(\n", "file_path": "examples/multi_window.rs", "rank": 12, "score": 163278.8262844921 }, { "content": "/// Does nothing. self function is only use by the web backend.\n\npub fn initialize() {}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n event_loop: Vec<EventLoop<()>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n\n Shell {\n\n window_shells: vec![],\n", "file_path": "crates/shell/src/glutin/mod.rs", "rank": 13, "score": 161141.5187694807 }, { "content": "/// Does nothing. This function is only use by the web backend.\n\npub fn initialize() {}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n\n Shell {\n\n window_shells: vec![],\n\n requests,\n", "file_path": "crates/shell/src/minifb/mod.rs", "rank": 14, "score": 161136.67284118664 }, { "content": "/// Initializes web stuff.\n\npub fn initialize() {\n\n set_panic_hook();\n\n stdweb::initialize();\n\n}\n\n\n\n/// Represents an application shell that could handle multiple windows.\n\npub struct Shell<A: 'static>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n window_shells: Vec<Window<A>>,\n\n requests: mpsc::Receiver<ShellRequest<A>>,\n\n}\n\n\n\nimpl<A> Shell<A>\n\nwhere\n\n A: WindowAdapter,\n\n{\n\n /// Creates a new application shell.\n\n pub fn new(requests: mpsc::Receiver<ShellRequest<A>>) -> Self {\n", "file_path": "crates/shell/src/web/mod.rs", "rank": 15, "score": 161131.77000361268 }, { "content": "pub fn print_tree(\n\n entity: Entity,\n\n depth: usize,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n) {\n\n let name = ecm.component_store().get::<String>(\"name\", entity).unwrap();\n\n\n\n let selector = if let Ok(selector) = ecm.component_store().get::<Selector>(\"selector\", entity) {\n\n selector.clone()\n\n } else {\n\n Selector::default()\n\n };\n\n\n\n crate::shell::CONSOLE.log(format!(\n\n \"{}{} (entity: {}{})\",\n\n \"| \".repeat(depth),\n\n name,\n\n entity.0,\n\n selector\n\n ));\n\n\n\n for child in ecm.entity_store().clone().children.get(&entity).unwrap() {\n\n print_tree(*child, depth + 1, ecm);\n\n }\n\n}\n", "file_path": "crates/api/src/systems/init_system.rs", "rank": 16, "score": 156084.71612477142 }, { "content": "pub fn default_theme() -> Theme {\n\n Theme::create_from_css(DEFAULT_THEME_CSS).build()\n\n}\n\n\n", "file_path": "crates/theme/src/lib.rs", "rank": 17, "score": 154676.3883542904 }, { "content": "pub fn light_theme() -> Theme {\n\n Theme::create_from_css(&LIGHT_THEME_CSS[..]).build()\n\n}\n", "file_path": "crates/theme/src/lib.rs", "rank": 18, "score": 154676.38835429033 }, { "content": "/// Returns the value of a property of a widget if it exists otherwise the given value.\n\npub fn get_property_or_value<T>(\n\n key: &str,\n\n entity: Entity,\n\n store: &StringComponentStore,\n\n value: T,\n\n) -> T\n\nwhere\n\n T: Clone + Component,\n\n{\n\n if let Ok(property) = store.get::<T>(key, entity).map(|r| r.clone()) {\n\n return property;\n\n }\n\n value\n\n}\n\n\n\n/// Use to build a property or to share it.\n\n#[derive(PartialEq, Debug)]\n\npub enum PropertySource<P: Component + Debug> {\n\n Source(Entity),\n\n KeySource(String, Entity),\n\n Value(P),\n\n}\n\n\n\nimpl<P: Component + Debug> From<Entity> for PropertySource<P> {\n\n fn from(entity: Entity) -> Self {\n\n PropertySource::Source(entity)\n\n }\n\n}\n\n\n", "file_path": "crates/api/src/properties/mod.rs", "rank": 19, "score": 149848.22125590223 }, { "content": "fn is_single_tasks(task: &RenderTask) -> bool {\n\n match task {\n\n RenderTask::Start() => true,\n\n RenderTask::SetBackground(_) => true,\n\n RenderTask::Resize { .. } => true,\n\n RenderTask::RegisterFont { .. } => true,\n\n RenderTask::DrawRenderTarget { .. } => true,\n\n RenderTask::DrawImage { .. } => true,\n\n RenderTask::DrawImageWithClip { .. } => true,\n\n RenderTask::DrawPipeline { .. } => true,\n\n RenderTask::SetTransform { .. } => true,\n\n RenderTask::Terminate { .. } => true,\n\n _ => false,\n\n }\n\n}\n\n\n\nimpl RenderWorker {\n\n fn new(\n\n width: f64,\n\n height: f64,\n", "file_path": "crates/render/src/concurrent/mod.rs", "rank": 20, "score": 146116.94795155275 }, { "content": "#[derive(Clone)]\n\nstruct PipelineWrapper(pub Box<dyn Pipeline>);\n\n\n\nimpl PartialEq for PipelineWrapper {\n\n fn eq(&self, _: &Self) -> bool {\n\n true\n\n }\n\n}\n\n\n\n// Used to sent render tasks to render thread.\n", "file_path": "crates/render/src/concurrent/mod.rs", "rank": 21, "score": 145260.19036709322 }, { "content": "#[derive(Default, AsAny)]\n\nstruct BarState {\n\n indicator: Entity,\n\n}\n\n\n\nimpl State for BarState {\n\n fn init(&mut self, _: &mut Registry, ctx: &mut Context) {\n\n self.indicator = ctx\n\n .entity_of_child(ID_INDICATOR)\n\n .expect(\"BarState.init(): Child could not be found!\");\n\n\n\n ctx.get_widget(self.indicator)\n\n .get_mut::<Constraint>(\"constraint\")\n\n .set_width(0.1);\n\n }\n\n\n\n fn update(&mut self, _: &mut Registry, ctx: &mut Context<'_>) {\n\n let val = ctx.widget().clone_or_default::<f64>(\"val\");\n\n let max_width = ctx.widget().get::<Rectangle>(\"bounds\").width();\n\n let new_width = calculate_width(val, max_width);\n\n\n\n ctx.get_widget(self.indicator)\n\n .get_mut::<Constraint>(\"constraint\")\n\n .set_width(new_width);\n\n }\n\n}\n\n\n", "file_path": "crates/widgets/src/progress_bar.rs", "rank": 22, "score": 143886.6097673346 }, { "content": "pub fn parse(s: &str) -> Vec<Rule> {\n\n let mut input = ParserInput::new(s);\n\n let mut parser = Parser::new(&mut input);\n\n let rule_parser = RuleParser::new();\n\n\n\n let rules = {\n\n let rule_list_parser =\n\n cssparser::RuleListParser::new_for_stylesheet(&mut parser, rule_parser);\n\n rule_list_parser.collect::<Vec<_>>()\n\n };\n\n\n\n for rule in &rules {\n\n match *rule {\n\n Ok(_) => {}\n\n Err(ref e) => {\n\n match e.error {\n\n ParseError::Basic(ref e) => eprintln!(\"{:?}\", e),\n\n ParseError::Custom(ref e) => eprintln!(\"{:?}\", e),\n\n }\n\n println!(\"Error occurred in `{}`\", parser.slice(e.span.clone()));\n\n }\n\n }\n\n }\n\n\n\n rules.into_iter().filter_map(|rule| rule.ok()).collect()\n\n}\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 23, "score": 141350.85434284448 }, { "content": "#[derive(Default, AsAny)]\n\nstruct NumericBoxState {\n\n action: Option<InputAction>,\n\n pub input: Entity,\n\n min: Decimal,\n\n max: Decimal,\n\n step: Decimal,\n\n current_value: Decimal,\n\n}\n\n\n\nimpl NumericBoxState {\n\n fn action(&mut self, action: InputAction) {\n\n self.action = Some(action);\n\n }\n\n\n\n fn change_val(&mut self, new_value: Decimal, ctx: &mut Context<'_>) {\n\n if new_value >= self.min && new_value <= self.max {\n\n self.current_value = new_value;\n\n ctx.get_widget(self.input)\n\n .set::<String16>(\"text\", String16::from(self.current_value.to_string()));\n\n }\n\n }\n\n\n\n fn request_focus(&self, ctx: &mut Context<'_>) {\n\n if !ctx.widget().get::<bool>(\"focused\") {\n\n ctx.widget().set::<bool>(\"focused\", true);\n\n ctx.push_event_by_window(FocusEvent::RequestFocus(ctx.entity));\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/widgets/src/numeric_box.rs", "rank": 24, "score": 141300.9903023596 }, { "content": "pub trait AsAny: Any {\n\n fn as_any(&self) -> &dyn Any;\n\n\n\n fn as_any_mut(&mut self) -> &mut dyn Any;\n\n}\n\n\n", "file_path": "crates/api/src/widget/state.rs", "rank": 25, "score": 140459.62397525468 }, { "content": "pub trait MouseHandler: Sized + Widget {\n\n /// Inserts a click handler.\n\n fn on_click<H: Fn(&mut StatesContext, Point) -> bool + 'static>(self, handler: H) -> Self {\n\n self.insert_handler(ClickEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n\n\n /// Insert a mouse down handler.\n\n fn on_mouse_down<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self {\n\n self.insert_handler(MouseDownEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n\n\n /// Insert a mouse up handler.\n\n fn on_mouse_up<H: Fn(&mut StatesContext, Mouse) -> bool + 'static>(self, handler: H) -> Self {\n\n self.insert_handler(MouseUpEventHandler {\n\n handler: Rc::new(handler),\n\n })\n", "file_path": "crates/api/src/event/mouse.rs", "rank": 26, "score": 139696.406127947 }, { "content": "#[proc_macro_derive(AsAny)]\n\npub fn derive_as_any(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl AsAny for #ident {\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n\n\n fn as_any_mut(&mut self) -> &mut dyn Any {\n\n self\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 27, "score": 139343.65915451152 }, { "content": "#[proc_macro_derive(Pipeline)]\n\npub fn derive_pipeline(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl render::Pipeline for #ident {\n\n fn box_eq(&self, other: &dyn Any) -> bool {\n\n other.downcast_ref::<Self>().map_or(false, |a| self == a)\n\n }\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n fn clone_box(&self) -> Box<dyn render::Pipeline> {\n\n Box::new(self.clone())\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 28, "score": 137262.0501597513 }, { "content": "#[proc_macro_derive(Event)]\n\npub fn derive_event(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl Event for #ident {}\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n\n\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 29, "score": 137262.0501597513 }, { "content": "#[proc_macro_derive(IntoHandler)]\n\npub fn derive_into_handler(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let ident = &input.ident;\n\n\n\n let gen = quote! {\n\n impl Into<Rc<dyn EventHandler>> for #ident {\n\n fn into(self) -> Rc<dyn EventHandler> {\n\n Rc::new(self)\n\n }\n\n }\n\n };\n\n\n\n TokenStream::from(gen)\n\n}\n", "file_path": "crates/proc-macros/src/lib.rs", "rank": 30, "score": 137262.0501597513 }, { "content": "// minifb key input helper\n\nstruct KeyInputCallBack {\n\n key_events: Rc<RefCell<Vec<KeyEvent>>>,\n\n}\n\n\n\nimpl KeyInputCallBack {\n\n fn uni_char_to_key_event(&mut self, uni_char: u32) {\n\n let mut text = String::new();\n\n\n\n let key = if let Some(character) = char::from_u32(uni_char) {\n\n text = character.to_string();\n\n Key::from(character)\n\n } else {\n\n Key::Unknown\n\n };\n\n if key == Key::Up\n\n || key == Key::Down\n\n || key == Key::Left\n\n || key == Key::Right\n\n || key == Key::Backspace\n\n || key == Key::Control\n", "file_path": "crates/shell/src/minifb/window_builder.rs", "rank": 31, "score": 136156.0557242932 }, { "content": "/// Adds the given `pseudo_class` to the css selector of the given `widget`.\n\npub fn add_selector_to_widget(pseudo_class: &str, widget: &mut WidgetContainer<'_>) {\n\n if let Some(selector) = widget.try_get_mut::<Selector>(\"selector\") {\n\n selector.pseudo_classes.insert(String::from(pseudo_class));\n\n selector.set_dirty(true);\n\n }\n\n}\n\n\n", "file_path": "crates/api/src/widget/mod.rs", "rank": 32, "score": 125082.62424590852 }, { "content": "/// Removes the given `pseudo_class` from the css selector of the given `widget`.\n\npub fn remove_selector_from_widget(pseudo_class: &str, widget: &mut WidgetContainer<'_>) {\n\n if let Some(selector) = widget.try_get_mut::<Selector>(\"selector\") {\n\n selector.pseudo_classes.remove(pseudo_class);\n\n selector.set_dirty(true);\n\n }\n\n}\n\n\n\n/// Used to define the `parent_type`of a widget.\n\npub enum ParentType {\n\n /// No children could be added to the widget.\n\n None,\n\n\n\n /// Only one child could be added to the widget.\n\n Single,\n\n\n\n /// Multiple children could be added to the widget.\n\n Multi,\n\n}\n\n\n", "file_path": "crates/api/src/widget/mod.rs", "rank": 33, "score": 125082.62424590852 }, { "content": "fn default_or(key: &str, default_value: f64, ctx: &mut Context<'_>) -> Decimal {\n\n let property = ctx.widget().clone_or_default(key);\n\n\n\n match Decimal::from_f64(property) {\n\n Some(val) => val,\n\n None => Decimal::from_f64(default_value).unwrap(),\n\n }\n\n}\n\n\n\nimpl State for NumericBoxState {\n\n fn init(&mut self, _: &mut Registry, ctx: &mut Context<'_>) {\n\n self.input = ctx.entity_of_child(ID_INPUT).expect(\n\n \"NumericBoxState\n\n .init(): the child input could not be found!\",\n\n );\n\n self.min = default_or(\"min\", 0.0, ctx);\n\n self.max = default_or(\"max\", MAX, ctx);\n\n self.step = default_or(\"step\", 1.0, ctx);\n\n self.current_value = default_or(\"val\", 0.0, ctx);\n\n\n", "file_path": "crates/widgets/src/numeric_box.rs", "rank": 34, "score": 124893.42199288167 }, { "content": "pub fn get_all_children(children: &mut Vec<Entity>, parent: Entity, tree: &Tree) {\n\n for child in &tree.children[&parent] {\n\n children.push(*child);\n\n get_all_children(children, *child, tree);\n\n }\n\n}\n\n\n\n// -- Helpers --\n", "file_path": "crates/api/src/widget/context.rs", "rank": 35, "score": 121942.34019643223 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/widgets.rs", "rank": 36, "score": 121598.79730465396 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/calculator.rs", "rank": 37, "score": 121598.79730465396 }, { "content": "// helper to request MainViewState\n\nfn state<'a>(id: Entity, states: &'a mut StatesContext) -> &'a mut MainViewState {\n\n states.get_mut(id)\n\n}\n", "file_path": "examples/settings.rs", "rank": 38, "score": 121598.79730465396 }, { "content": "//! This module contains traits to inject custom logic into the window shell.\n\n\n\nuse crate::render::RenderContext2D;\n\nuse crate::{event::*, utils::Point};\n\n\n\n/// The `WindowAdapter` represents the bridge to the `Shell` backend.\n\n/// It receives events from the `Window` and runs it's own logic. \n", "file_path": "crates/shell/src/window_adapter.rs", "rank": 39, "score": 120600.03956461945 }, { "content": "/// Finds th parent of the `target_child`. The parent of the `target_child` must be the given `parent` or\n\n/// a child of the given parent.\n\npub fn find_parent(tree: &Tree, target_child: Entity, parent: Entity) -> Option<Entity> {\n\n if tree.children[&parent].contains(&target_child) {\n\n return Some(parent);\n\n }\n\n\n\n for child in &tree.children[&parent] {\n\n let parent = find_parent(tree, target_child, *child);\n\n if parent.is_some() {\n\n return parent;\n\n }\n\n }\n\n\n\n return None;\n\n}\n\n\n", "file_path": "crates/api/src/widget/context.rs", "rank": 40, "score": 120162.3829840206 }, { "content": "/// Get the property of a widget.\n\npub fn get_property<T>(key: &str, entity: Entity, store: &StringComponentStore) -> T\n\nwhere\n\n T: Clone + Component,\n\n{\n\n store.get::<T>(key, entity).map(|r| r.clone()).unwrap()\n\n}\n\n\n", "file_path": "crates/api/src/properties/mod.rs", "rank": 41, "score": 118447.5871513283 }, { "content": " pub fn new(\n\n world: World<Tree, StringComponentStore, render::RenderContext2D>,\n\n ctx: ContextProvider,\n\n ) -> Self {\n\n WindowAdapter { world, ctx }\n\n }\n\n}\n\n\n\nimpl WindowAdapter {\n\n fn root(&mut self) -> Entity {\n\n self.world\n\n .entity_component_manager()\n\n .entity_store()\n\n .root\n\n .unwrap()\n\n }\n\n}\n\n\n\nimpl shell::WindowAdapter for WindowAdapter {\n\n fn resize(&mut self, width: f64, height: f64) {\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 42, "score": 117774.36578957785 }, { "content": " fn scroll(&mut self, delta_x: f64, delta_y: f64) {\n\n let root = self.root();\n\n self.ctx.event_queue.borrow_mut().register_event(\n\n ScrollEvent {\n\n delta: Point::new(delta_x, delta_y),\n\n },\n\n root,\n\n )\n\n }\n\n\n\n fn mouse_event(&mut self, event: shell::MouseEvent) {\n\n let root = self.root();\n\n match event.state {\n\n shell::ButtonState::Up => {\n\n self.ctx.event_queue.borrow_mut().register_event(\n\n MouseUpEvent {\n\n x: event.x,\n\n y: event.y,\n\n button: event.button,\n\n },\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 43, "score": 117774.32907200383 }, { "content": "use dces::prelude::{Entity, World};\n\nuse std::{cell::RefCell, collections::HashMap, sync::mpsc};\n\n\n\nuse crate::{\n\n prelude::*,\n\n properties::Constraint,\n\n render, shell,\n\n shell::{ShellRequest, WindowRequest, WindowSettings},\n\n tree::Tree,\n\n utils::{Point, Rectangle},\n\n};\n\n\n\n/// Represents a window. Each window has its own tree, event pipeline and shell.\n\npub struct WindowAdapter {\n\n world: World<Tree, StringComponentStore, render::RenderContext2D>,\n\n ctx: ContextProvider,\n\n}\n\n\n\nimpl WindowAdapter {\n\n /// Creates a new WindowAdapter.\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 44, "score": 117773.43457223779 }, { "content": " }\n\n\n\n fn mouse_position(&self) -> Point {\n\n self.ctx.mouse_position.get()\n\n }\n\n\n\n fn key_event(&mut self, event: shell::KeyEvent) {\n\n let root = self.root();\n\n match event.state {\n\n shell::ButtonState::Up => self\n\n .ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event(KeyUpEvent { event }, root),\n\n shell::ButtonState::Down => self\n\n .ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event(KeyDownEvent { event }, root),\n\n }\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 45, "score": 117769.8364387036 }, { "content": " root,\n\n );\n\n self.ctx.event_queue.borrow_mut().register_event(\n\n GlobalMouseUpEvent {\n\n x: event.x,\n\n y: event.y,\n\n button: event.button,\n\n },\n\n root,\n\n );\n\n }\n\n shell::ButtonState::Down => self.ctx.event_queue.borrow_mut().register_event(\n\n MouseDownEvent {\n\n x: event.x,\n\n y: event.y,\n\n button: event.button,\n\n },\n\n root,\n\n ),\n\n }\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 46, "score": 117766.743151405 }, { "content": " let root = self.root();\n\n self.ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event_with_strategy(\n\n WindowEvent::Resize { width, height },\n\n EventStrategy::Direct,\n\n root,\n\n );\n\n }\n\n\n\n fn mouse(&mut self, x: f64, y: f64) {\n\n let root = self.root();\n\n self.ctx.mouse_position.set(Point::new(x, y));\n\n self.ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event(MouseMoveEvent { x, y }, root)\n\n }\n\n\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 47, "score": 117765.6040832981 }, { "content": " }\n\n\n\n let window = create_fn(&mut BuildContext::new(\n\n world.entity_component_manager(),\n\n &context_provider.render_objects,\n\n &context_provider.layouts,\n\n &context_provider.handler_map,\n\n &mut *context_provider.states.borrow_mut(),\n\n &theme,\n\n ));\n\n\n\n {\n\n let tree: &mut Tree = world.entity_component_manager().entity_store_mut();\n\n tree.set_root(window);\n\n }\n\n\n\n window\n\n };\n\n\n\n let constraint = *world\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 48, "score": 117764.22022958512 }, { "content": " fonts.insert(\n\n \"Material Icons\".to_string(),\n\n crate::theme::fonts::MATERIAL_ICONS_REGULAR_FONT,\n\n );\n\n\n\n let settings = WindowSettings {\n\n title: world\n\n .entity_component_manager()\n\n .component_store()\n\n .get::<String>(\"title\", window)\n\n .unwrap()\n\n .clone(),\n\n borderless: *world\n\n .entity_component_manager()\n\n .component_store()\n\n .get::<bool>(\"borderless\", window)\n\n .unwrap(),\n\n resizeable: *world\n\n .entity_component_manager()\n\n .component_store()\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 49, "score": 117764.14779247082 }, { "content": " ))\n\n .with_priority(0)\n\n .build();\n\n\n\n world\n\n .create_system(LayoutSystem::new(context_provider.clone()))\n\n .with_priority(1)\n\n .build();\n\n\n\n world\n\n .create_system(PostLayoutStateSystem::new(\n\n context_provider.clone(),\n\n registry.clone(),\n\n ))\n\n .with_priority(2)\n\n .build();\n\n\n\n world\n\n .create_system(RenderSystem::new(context_provider.clone()))\n\n .with_priority(3)\n\n .build();\n\n\n\n (\n\n WindowAdapter::new(world, context_provider),\n\n settings,\n\n receiver,\n\n )\n\n}\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 50, "score": 117762.38521039642 }, { "content": " root,\n\n );\n\n }\n\n\n\n fn run(&mut self, render_context: &mut render::RenderContext2D) {\n\n self.world.run_with_context(render_context);\n\n }\n\n}\n\n\n\n/// Creates a `WindowAdapter` and a `WindowSettings` object from a window builder closure.\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 51, "score": 117762.12251557045 }, { "content": " .get::<bool>(\"resizeable\", window)\n\n .unwrap(),\n\n always_on_top: *world\n\n .entity_component_manager()\n\n .component_store()\n\n .get::<bool>(\"always_on_top\", window)\n\n .unwrap(),\n\n position: (position.x, position.y),\n\n size: (constraint.width(), constraint.height()),\n\n fonts,\n\n };\n\n\n\n world\n\n .entity_component_manager()\n\n .component_store_mut()\n\n .register(\"global\", window, Global::default());\n\n world\n\n .entity_component_manager()\n\n .component_store_mut()\n\n .register(\"global\", window, Global::default());\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 52, "score": 117762.08908267821 }, { "content": " .entity_component_manager()\n\n .component_store()\n\n .get::<Constraint>(\"constraint\", window)\n\n .unwrap();\n\n\n\n let position = *world\n\n .entity_component_manager()\n\n .component_store()\n\n .get::<Point>(\"position\", window)\n\n .unwrap();\n\n\n\n let mut fonts = HashMap::new();\n\n fonts.insert(\n\n \"Roboto Regular\".to_string(),\n\n crate::theme::fonts::ROBOTO_REGULAR_FONT,\n\n );\n\n fonts.insert(\n\n \"Roboto Medium\".to_string(),\n\n crate::theme::fonts::ROBOTO_MEDIUM_FONT,\n\n );\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 53, "score": 117761.26131909015 }, { "content": " .register(\"settings\", Settings::new(app_name.clone()));\n\n };\n\n\n\n let context_provider = ContextProvider::new(sender, request_sender.clone(), app_name);\n\n\n\n let theme = crate::theme::default_theme();\n\n\n\n let window = {\n\n let overlay = Overlay::create().build(&mut BuildContext::new(\n\n world.entity_component_manager(),\n\n &context_provider.render_objects,\n\n &context_provider.layouts,\n\n &context_provider.handler_map,\n\n &mut *context_provider.states.borrow_mut(),\n\n &theme,\n\n ));\n\n\n\n {\n\n let tree: &mut Tree = world.entity_component_manager().entity_store_mut();\n\n tree.set_overlay(overlay);\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 54, "score": 117760.94550536646 }, { "content": " }\n\n\n\n fn quit_event(&mut self) {\n\n let root = self.root();\n\n\n\n self.ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event(SystemEvent::Quit, root);\n\n }\n\n\n\n fn active(&mut self, active: bool) {\n\n let root = self.root();\n\n\n\n self.ctx\n\n .event_queue\n\n .borrow_mut()\n\n .register_event_with_strategy(\n\n WindowEvent::ActiveChanged(active),\n\n EventStrategy::Direct,\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 55, "score": 117759.54200575537 }, { "content": " world\n\n .entity_component_manager()\n\n .component_store_mut()\n\n .register(\n\n \"bounds\",\n\n window,\n\n Rectangle::from((0.0, 0.0, constraint.width(), constraint.height())),\n\n );\n\n\n\n world.register_init_system(InitSystem::new(context_provider.clone(), registry.clone()));\n\n\n\n world.register_cleanup_system(CleanupSystem::new(\n\n context_provider.clone(),\n\n registry.clone(),\n\n ));\n\n\n\n world\n\n .create_system(EventStateSystem::new(\n\n context_provider.clone(),\n\n registry.clone(),\n", "file_path": "crates/api/src/application/window_adapter.rs", "rank": 56, "score": 117758.78443572445 }, { "content": "#[derive(Default, AsAny)]\n\nstruct MainViewState {\n\n action: Option<ProgressEvent>,\n\n}\n\n\n\nwidget!(MainView<MainViewState>);\n\n\n\nimpl MainViewState {\n\n fn action(&mut self, action: impl Into<Option<ProgressEvent>>) {\n\n self.action = action.into();\n\n }\n\n}\n\n\n\nimpl State for MainViewState {\n\n fn update(&mut self, _: &mut Registry, ctx: &mut Context<'_>) {\n\n if let Some(action) = self.action {\n\n match action {\n\n ProgressEvent::Advance(amount) => {\n\n let old_width = ctx.child(\"pgbar\").clone_or_default::<f64>(\"val\");\n\n let new_width = old_width + amount;\n\n // Set the ProgressBar's val property to the calculated percentage\n", "file_path": "examples/progress_bar.rs", "rank": 57, "score": 116522.95064324318 }, { "content": "fn get_key(code: &str, key: String) -> (Key, String) {\n\n let mut text = String::from(\"\");\n\n\n\n let code = match code {\n\n \"Backspace\" => Key::Backspace,\n\n \"Delete\" => Key::Delete,\n\n \"ControlLeft\" | \"ControlRight\" => Key::Control,\n\n \"ShiftLeft\" => Key::ShiftL,\n\n \"ShiftRight\" => Key::ShiftR,\n\n \"AltLeft\" => Key::Alt,\n\n \"AltRight\" => Key::Alt,\n\n \"ArrowUp\" => Key::Up,\n\n \"ArrowLeft\" => Key::Left,\n\n \"ArrowRight\" => Key::Right,\n\n \"ArrowDown\" => Key::Down,\n\n \"Escape\" => Key::Escape,\n\n \"Enter\" => Key::Enter,\n\n \"OSLeft\" | \"OSRight\" => Key::Home,\n\n \"CapsLock\" => Key::CapsLock,\n\n _ => {\n\n text = key.clone();\n\n Key::from(key.chars().next().unwrap())\n\n }\n\n };\n\n\n\n (code, text)\n\n}\n\n\n\n// -- Helpers --", "file_path": "crates/shell/src/web/window.rs", "rank": 58, "score": 115575.5746667359 }, { "content": "fn main() {\n\n // use this only if you want to run it as web application.\n\n orbtk::initialize();\n\n\n\n Application::new()\n\n .window(|ctx| {\n\n Window::create()\n\n .title(\"OrbTk - multi window example window 1\")\n\n .position((100.0, 100.0))\n\n .size(420.0, 730.0)\n\n .child(MainView::create().build(ctx))\n\n .build(ctx)\n\n })\n\n .window(|ctx| {\n\n Window::create()\n\n .title(\"OrbTk - multi window example window 2\")\n\n .position((600.0, 100.0))\n\n .size(420.0, 730.0)\n\n .child(\n\n Stack::create()\n\n .child(TextBlock::create().text(\"Window 2\").margin(4.0).build(ctx))\n\n .child(Button::create().margin(4.0).text(\"Click me\").build(ctx))\n\n .build(ctx),\n\n )\n\n .build(ctx)\n\n })\n\n .run();\n\n}\n", "file_path": "examples/multi_window.rs", "rank": 59, "score": 115303.17292010892 }, { "content": "fn generate_digit_button(\n\n ctx: &mut BuildContext,\n\n id: Entity,\n\n sight: char,\n\n primary: bool,\n\n column: usize,\n\n column_span: usize,\n\n row: usize,\n\n) -> Entity {\n\n let mut button = Button::create()\n\n .class(\"single_content\")\n\n .min_size(48.0, 48.0)\n\n .text(sight.to_string())\n\n .on_click(move |states, _| -> bool {\n\n state(id, states).action(Action::Digit(sight));\n\n true\n\n })\n\n .attach(Grid::column(column))\n\n .attach(Grid::row(row))\n\n .attach(Grid::column_span(column_span));\n\n\n\n if primary {\n\n button = button.class(\"primary\");\n\n }\n\n\n\n button.build(ctx)\n\n}\n\n\n", "file_path": "examples/calculator.rs", "rank": 60, "score": 113617.24272513422 }, { "content": "fn generate_operation_button(\n\n ctx: &mut BuildContext,\n\n id: Entity,\n\n sight: char,\n\n primary: bool,\n\n column: usize,\n\n column_span: usize,\n\n row: usize,\n\n) -> Entity {\n\n let mut button = Button::create()\n\n .class(\"single_content\")\n\n .min_size(48.0, 48.0)\n\n .text(sight.to_string())\n\n .class(\"square\")\n\n .on_click(move |states, _| -> bool {\n\n state(id, states).action(Action::Operator(sight));\n\n true\n\n })\n\n .attach(Grid::column(column))\n\n .attach(Grid::column_span(column_span))\n", "file_path": "examples/calculator.rs", "rank": 61, "score": 113617.24272513422 }, { "content": "// Wrapper for the render thread.\n\nstruct RenderWorker {\n\n render_thread: Option<thread::JoinHandle<()>>,\n\n}\n\n\n", "file_path": "crates/render/src/concurrent/mod.rs", "rank": 62, "score": 100964.20570151505 }, { "content": "struct RuleParser;\n\n\n\nimpl RuleParser {\n\n fn new() -> Self {\n\n RuleParser {}\n\n }\n\n}\n\n\n\nimpl<'i> cssparser::QualifiedRuleParser<'i> for RuleParser {\n\n type Prelude = Vec<Selector>;\n\n type QualifiedRule = Rule;\n\n type Error = CustomParseError;\n\n\n\n fn parse_prelude<'t>(\n\n &mut self,\n\n input: &mut Parser<'i, 't>,\n\n ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {\n\n let res = parse_selectors(input)?;\n\n Ok(res)\n\n }\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 63, "score": 100964.20570151505 }, { "content": "struct DeclarationParser;\n\n\n\nimpl<'i> cssparser::DeclarationParser<'i> for DeclarationParser {\n\n type Declaration = Declaration;\n\n type Error = CustomParseError;\n\n\n\n fn parse_value<'t>(\n\n &mut self,\n\n name: CompactCowStr<'i>,\n\n input: &mut Parser<'i, 't>,\n\n ) -> Result<Self::Declaration, ParseError<'i, Self::Error>> {\n\n let value = match &*name {\n\n \"color\" | \"border-color\" | \"icon-color\" => Value::Brush(parse_basic_color(input)?),\n\n\n\n \"background\" | \"foreground\" => Value::Brush(parse_basic_color(input)?),\n\n\n\n \"font-family\" | \"icon-family\" => Value::Str(parse_string(input)?),\n\n\n\n \"border-radius\" | \"border-width\" | \"font-size\" | \"icon-size\" | \"icon-margin\"\n\n | \"padding\" | \"padding-left\" | \"padding-top\" | \"padding-right\" | \"padding-bottom\"\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 64, "score": 100964.20570151505 }, { "content": "/// Contains a set of getters and setters to read and write to a border.\n\npub trait Bordered {\n\n /// Gets the thickness.\n\n fn border_thickness(&self) -> Thickness;\n\n\n\n /// Sets the border thickness.\n\n fn set_border_thickness(&mut self, thickness: Thickness);\n\n\n\n /// Gets the border brush.\n\n fn border_brush(&self) -> &Brush;\n\n\n\n /// Sets the border brush.\n\n fn set_border_brush(&mut self, brush: Brush);\n\n\n\n /// Gets the border radius.\n\n fn border_radius(&self) -> f64;\n\n\n\n /// Sets the border radius.\n\n fn set_border_radius(&mut self, radius: f64);\n\n\n\n /// Gets the complete border.\n", "file_path": "crates/utils/src/border.rs", "rank": 65, "score": 98598.6828654593 }, { "content": "// todo: documentation\n\npub trait Spacer {\n\n /// Gets left.\n\n fn left(&self) -> f64;\n\n\n\n /// Sets left.\n\n fn set_left(&mut self, left: f64);\n\n\n\n /// Gets top.\n\n fn top(&self) -> f64;\n\n\n\n /// Sets top.\n\n fn set_top(&mut self, top: f64);\n\n\n\n /// Gets right.\n\n fn right(&self) -> f64;\n\n\n\n /// Sets right.\n\n fn set_right(&mut self, right: f64);\n\n\n\n /// Gets bottom.\n", "file_path": "crates/utils/src/spacer.rs", "rank": 66, "score": 98598.6828654593 }, { "content": "#[test]\n\nfn test_sub() {\n\n const EXPECTED_RESULT: Point = Point { x: -3., y: 5. };\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let left_side = Point::new(5., 7.);\n\n let right_side = Point::new(8., 2.);\n\n\n\n let result = left_side - right_side;\n\n\n\n assert!((result.x - EXPECTED_RESULT.x).abs() < ERROR_MARGIN);\n\n assert!((result.y - EXPECTED_RESULT.y).abs() < ERROR_MARGIN);\n\n}\n\n\n", "file_path": "crates/utils/src/point.rs", "rank": 67, "score": 97478.20073249517 }, { "content": "#[test]\n\nfn test_distance() {\n\n const EXPECTED_RESULT: f64 = 9.48683;\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let point_positive = Point::new(1., 5.);\n\n let point_negative = Point::new(-2., -4.);\n\n\n\n assert!(((point_positive.distance(point_negative) - EXPECTED_RESULT).abs() < ERROR_MARGIN));\n\n assert!(((point_negative.distance(point_positive) - EXPECTED_RESULT).abs() < ERROR_MARGIN));\n\n}\n\n\n", "file_path": "crates/utils/src/point.rs", "rank": 68, "score": 97478.20073249517 }, { "content": "#[test]\n\nfn test_add() {\n\n const EXPECTED_RESULT: Point = Point { x: 13., y: 9. };\n\n const ERROR_MARGIN: f64 = 0.00001;\n\n\n\n let left_side = Point::new(5., 7.);\n\n let right_side = Point::new(8., 2.);\n\n\n\n let result = left_side + right_side;\n\n\n\n assert!((result.x - EXPECTED_RESULT.x).abs() < ERROR_MARGIN);\n\n assert!((result.y - EXPECTED_RESULT.y).abs() < ERROR_MARGIN);\n\n}\n", "file_path": "crates/utils/src/point.rs", "rank": 69, "score": 97478.20073249517 }, { "content": "fn calculate_value(\n\n thumb_x: f64,\n\n minimum: f64,\n\n maximum: f64,\n\n thumb_width: f64,\n\n track_width: f64,\n\n) -> f64 {\n\n thumb_x / (track_width - thumb_width) * (maximum - minimum)\n\n}\n\n\n", "file_path": "crates/widgets/src/slider.rs", "rank": 70, "score": 97478.20073249517 }, { "content": "pub trait RenderPipeline {\n\n /// Draws the ctx of the pipeline.\n\n fn draw(&self, image: &mut RenderTarget);\n\n}\n\n\n", "file_path": "crates/render/src/lib.rs", "rank": 71, "score": 96901.30773369255 }, { "content": "#[derive(Clone, PartialEq)]\n\nstruct EmptyRenderPipeline;\n\n\n\nimpl render::Pipeline for EmptyRenderPipeline {\n\n fn box_eq(&self, other: &dyn Any) -> bool {\n\n other.downcast_ref::<Self>().map_or(false, |a| self == a)\n\n }\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n\n\n fn clone_box(&self) -> Box<dyn render::Pipeline> {\n\n Box::new(self.clone())\n\n }\n\n}\n\n\n\nimpl render::RenderPipeline for EmptyRenderPipeline {\n\n fn draw(&self, _: &mut render::RenderTarget) {}\n\n}\n\n\n\n/// RenderPipeline object.\n\n#[derive(Clone, Debug)]\n\npub struct RenderPipeline(pub Box<dyn render::Pipeline>);\n\n\n\nimpl Default for RenderPipeline {\n\n fn default() -> Self {\n\n RenderPipeline(Box::new(EmptyRenderPipeline))\n\n }\n\n}\n", "file_path": "crates/api/src/properties/widget/render_pipeline.rs", "rank": 72, "score": 96301.36166848967 }, { "content": "fn apply_arrangement(\n\n bounds: &mut Rectangle,\n\n size_counter: &mut f64,\n\n margin: Thickness,\n\n alignment: (Alignment, Alignment),\n\n orientation: Orientation,\n\n available_size: (f64, f64),\n\n) {\n\n let (xpos, ypos, size);\n\n\n\n match orientation {\n\n Orientation::Horizontal => {\n\n xpos = *size_counter\n\n + alignment.0.align_position(\n\n available_size.0,\n\n bounds.width(),\n\n margin.left(),\n\n margin.right(),\n\n );\n\n\n", "file_path": "crates/api/src/layout/stack.rs", "rank": 73, "score": 95785.28833068117 }, { "content": "fn calculate_thumb_x_from_value(\n\n value: f64,\n\n minimum: f64,\n\n maximum: f64,\n\n track_width: f64,\n\n thumb_width: f64,\n\n) -> f64 {\n\n (value / (maximum - minimum)) * (track_width - thumb_width)\n\n}\n\n\n\n// --- Helpers --\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_calculate_thumb_x() {\n\n assert_eq!(0.0, calculate_thumb_x(-1000.0, 32.0, 0.0, 100.0));\n\n assert_eq!(0.0, calculate_thumb_x(0.0, 32.0, 0.0, 100.0));\n", "file_path": "crates/widgets/src/slider.rs", "rank": 74, "score": 95785.28833068117 }, { "content": "/// Applies spacing to widgets in a stack, depending upon their position, and the orientation.\n\nfn apply_spacing(\n\n margins: &mut Thickness,\n\n spacing: f64,\n\n orientation: Orientation,\n\n index: usize,\n\n nchildren: usize,\n\n) {\n\n let start = if index == 0 { 0.0 } else { spacing / 2.0 };\n\n let end = if index == nchildren - 1 {\n\n 0.0\n\n } else {\n\n spacing / 2.0\n\n };\n\n\n\n match orientation {\n\n Orientation::Vertical => {\n\n margins.top += start;\n\n margins.bottom += end;\n\n }\n\n Orientation::Horizontal => {\n\n margins.left += start;\n\n margins.right += end;\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/api/src/layout/stack.rs", "rank": 75, "score": 95785.28833068117 }, { "content": "/// Used to define an event.\n\npub trait Event: Any {\n\n fn strategy(&self) -> EventStrategy {\n\n EventStrategy::BottomUp\n\n }\n\n}\n\n\n\npub type EventHandlerMap = BTreeMap<Entity, Vec<Rc<dyn EventHandler>>>;\n\n\n\npub type TriggerHandler = dyn Fn(&mut StatesContext, Entity) + 'static;\n\n\n\n#[macro_export]\n\nmacro_rules! trigger_event {\n\n ($event:ident, $event_handler:ident, $trait:ident, $method:tt) => {\n\n pub struct $event(pub Entity);\n\n\n\n impl Event for $event {}\n\n\n\n pub struct $event_handler(Rc<TriggerHandler>);\n\n\n\n impl EventHandler for $event_handler {\n", "file_path": "crates/api/src/event/mod.rs", "rank": 76, "score": 94838.05804005664 }, { "content": "/// A layout is used to dynamic order the children of a widget.\n\npub trait Layout: Any {\n\n // Measure all children before the arrangement.\n\n fn measure(\n\n &self,\n\n render_context_2_d: &mut RenderContext2D,\n\n entity: Entity,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n layouts: &BTreeMap<Entity, Box<dyn Layout>>,\n\n theme: &ThemeValue,\n\n ) -> DirtySize;\n\n\n\n /// Arranges and sizes the children.\n\n fn arrange(\n\n &self,\n\n render_context_2_d: &mut RenderContext2D,\n\n parent_size: (f64, f64),\n\n entity: Entity,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n layouts: &BTreeMap<Entity, Box<dyn Layout>>,\n\n theme: &ThemeValue,\n\n ) -> (f64, f64);\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 77, "score": 94837.88631064299 }, { "content": "fn accumulate_desired_size(\n\n desired_size: &mut (f64, f64),\n\n desired: DirtySize,\n\n margin: Thickness,\n\n orientation: Orientation,\n\n) {\n\n let width = desired.width() + margin.left() + margin.right();\n\n let height = desired.height() + margin.top() + margin.bottom();\n\n\n\n match orientation {\n\n Orientation::Horizontal => {\n\n desired_size.0 += width;\n\n desired_size.1 = desired_size.1.max(height);\n\n }\n\n Orientation::Vertical => {\n\n desired_size.0 = desired_size.0.max(width);\n\n desired_size.1 += height;\n\n }\n\n }\n\n}\n", "file_path": "crates/api/src/layout/stack.rs", "rank": 78, "score": 94168.23638620648 }, { "content": "fn set_panic_hook() {\n\n // When the `console_error_panic_hook` feature is enabled, we can call the\n\n // `set_panic_hook` function at least once during initialization, and then\n\n // we will get better error messages if our code ever panics.\n\n //\n\n // For more details see\n\n // https://github.com/rustwasm/console_error_panic_hook#readme\n\n #[cfg(feature = \"console_error_panic_hook\")]\n\n console_error_panic_hook::set_once();\n\n}\n\n\n", "file_path": "crates/shell/src/web/mod.rs", "rank": 79, "score": 94168.23638620648 }, { "content": "/// This trait is used to define an event handler.\n\npub trait EventHandler {\n\n /// Handles an `event` by the given `widget`. If it returns `true` the event will not be forwarded.\n\n fn handle_event(&self, state_context: &mut StatesContext, event: &EventBox) -> bool;\n\n\n\n /// Check if the handler could handle the given event box.\n\n fn handles_event(&self, event: &EventBox) -> bool;\n\n}\n", "file_path": "crates/api/src/event/event_handler.rs", "rank": 80, "score": 93734.6411761223 }, { "content": "/// The `Widget` trait is used to define a new widget.\n\npub trait Widget: Template {\n\n /// Creates a new widget.\n\n fn create() -> Self;\n\n\n\n /// Builds the widget and returns the template of the widget.\n\n fn build(self, ctx: &mut BuildContext) -> Entity;\n\n\n\n /// Inerts a new event handler.\n\n fn insert_handler(self, handler: impl Into<Rc<dyn EventHandler>>) -> Self;\n\n\n\n /// Appends a child to the widget.\n\n fn child(self, child: Entity) -> Self;\n\n}\n", "file_path": "crates/api/src/widget/mod.rs", "rank": 81, "score": 93216.57161391957 }, { "content": "/// The `Template` trait provides the method for the widget template creation.\n\npub trait Template: Sized {\n\n /// Creates the template of the widget and returns it.\n\n fn template(self, _id: Entity, _context: &mut BuildContext) -> Self {\n\n self\n\n }\n\n\n\n fn render_object(&self) -> Box<dyn RenderObject> {\n\n Box::new(DefaultRenderObject)\n\n }\n\n\n\n fn layout(&self) -> Box<dyn Layout> {\n\n Box::new(GridLayout::new())\n\n }\n\n}\n", "file_path": "crates/api/src/widget/template.rs", "rank": 82, "score": 93211.72469857577 }, { "content": "fn parse_selectors<'i, 't>(\n\n input: &mut Parser<'i, 't>,\n\n) -> Result<Vec<Selector>, ParseError<'i, CustomParseError>> {\n\n let mut selectors = Vec::new();\n\n\n\n let mut selector = Selector::default();\n\n\n\n let mut first_token_in_selector = true;\n\n while let Ok(t) = input.next() {\n\n match t {\n\n // Element\n\n Token::Ident(ref element_name) => {\n\n if first_token_in_selector {\n\n selector.element = Some(element_name.to_string())\n\n } else {\n\n let mut old_selector = Selector::new().with(element_name.to_string());\n\n mem::swap(&mut old_selector, &mut selector);\n\n selector.relation = Some(Box::new(SelectorRelation::Ancestor(old_selector)));\n\n }\n\n }\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 83, "score": 91804.81160981083 }, { "content": "fn parse_string<'i, 't>(\n\n input: &mut Parser<'i, 't>,\n\n) -> Result<String, ParseError<'i, CustomParseError>> {\n\n Ok(match input.next()? {\n\n Token::QuotedString(s) => match css_string(&s) {\n\n Some(string) => string,\n\n None => return Err(CustomParseError::InvalidStringName(s.into_owned()).into()),\n\n },\n\n\n\n t => {\n\n let basic_error = BasicParseError::UnexpectedToken(t);\n\n return Err(basic_error.into());\n\n }\n\n })\n\n}\n\n\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 84, "score": 91804.81160981083 }, { "content": "pub trait RenderObject: Any {\n\n fn render(\n\n &self,\n\n render_context: &mut RenderContext2D,\n\n entity: Entity,\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n context_provider: &ContextProvider,\n\n theme: &ThemeValue,\n\n offsets: &mut BTreeMap<Entity, (f64, f64)>,\n\n debug: bool,\n\n ) {\n\n let mut global_position = Point::default();\n\n\n\n if let Some(parent) = ecm.entity_store().parent[&entity] {\n\n if let Some(offset) = offsets.get(&parent) {\n\n global_position = Point::new(offset.0, offset.1);\n\n }\n\n }\n\n\n\n if let Ok(visibility) = ecm\n", "file_path": "crates/api/src/render_object/mod.rs", "rank": 85, "score": 91661.47000015501 }, { "content": "fn parse_basic_color<'i, 't>(\n\n input: &mut Parser<'i, 't>,\n\n) -> Result<Brush, ParseError<'i, CustomParseError>> {\n\n Ok(match input.next()? {\n\n Token::Ident(s) => match css_color(&s) {\n\n Some(color) => color,\n\n None => return Err(CustomParseError::InvalidColorName(s.into_owned()).into()),\n\n },\n\n\n\n Token::IDHash(hash) | Token::Hash(hash) => Brush::from(hash.into_owned()),\n\n\n\n t => {\n\n let basic_error = BasicParseError::UnexpectedToken(t);\n\n return Err(basic_error.into());\n\n }\n\n })\n\n}\n\n\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 86, "score": 90187.75966533614 }, { "content": "pub trait KeyDownHandler: Sized + Widget {\n\n /// Inserts a handler.\n\n fn on_key_down<H: Fn(&mut StatesContext, KeyEvent) -> bool + 'static>(\n\n self,\n\n handler: H,\n\n ) -> Self {\n\n self.insert_handler(KeyDownEventHandler {\n\n handler: Rc::new(handler),\n\n })\n\n }\n\n\n\n /// Handles events triggered by a specific key.\n\n fn on_key_down_key<H: Fn() -> bool + 'static>(self, key: Key, handler: H) -> Self {\n\n self.on_key_down(\n\n move |_, event| {\n\n if event.key == key {\n\n handler()\n\n } else {\n\n false\n\n }\n\n },\n\n )\n\n }\n\n}\n", "file_path": "crates/api/src/event/key.rs", "rank": 87, "score": 88430.98964451226 }, { "content": "/// Used to implement a custom render pipeline.\n\npub trait Pipeline: RenderPipeline + Any + Send {\n\n /// Equality for two Pipeline objects.\n\n fn box_eq(&self, other: &dyn Any) -> bool;\n\n\n\n /// Converts self to an any reference.\n\n fn as_any(&self) -> &dyn Any;\n\n\n\n /// Clones self as box.\n\n fn clone_box(&self) -> Box<dyn Pipeline>;\n\n\n\n /// Draws the ctx of the pipeline.\n\n fn draw_pipeline(&self, image: &mut RenderTarget) {\n\n self.draw(image);\n\n }\n\n}\n\n\n\nimpl PartialEq for Box<dyn Pipeline> {\n\n fn eq(&self, other: &Box<dyn Pipeline>) -> bool {\n\n self.box_eq(other.as_any())\n\n }\n", "file_path": "crates/render/src/lib.rs", "rank": 88, "score": 88424.91934211698 }, { "content": "fn component<C: Component + Clone>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> C {\n\n ecm.component_store()\n\n .get::<C>(component, entity)\n\n .unwrap()\n\n .clone()\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 89, "score": 87115.47680989963 }, { "content": "fn try_component<C: Component + Clone>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> Option<C> {\n\n if let Ok(c) = ecm.component_store().get::<C>(component, entity) {\n\n return Some(c.clone());\n\n }\n\n\n\n None\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 90, "score": 85635.61170848655 }, { "content": "fn component_try_mut<'a, C: Component>(\n\n ecm: &'a mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> Option<&'a mut C> {\n\n ecm.component_store_mut()\n\n .get_mut::<C>(component, entity)\n\n .ok()\n\n}\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 91, "score": 85635.61170848655 }, { "content": "/// Used to convert components / properties into a PropertySource object.\n\npub trait IntoPropertySource<P: Component + Debug> {\n\n fn into_source(self) -> PropertySource<P>;\n\n}\n\n\n\n/// Used ot generate attached properties.\n\npub struct AttachedProperty<P>\n\nwhere\n\n P: Component + Debug,\n\n{\n\n pub key: String,\n\n pub property_source: PropertySource<P>,\n\n}\n\n\n\nimpl<P> AttachedProperty<P>\n\nwhere\n\n P: Component + Debug,\n\n{\n\n /// Create a new attached property.\n\n pub fn new(key: impl Into<String>, property_source: impl IntoPropertySource<P>) -> Self {\n\n AttachedProperty {\n", "file_path": "crates/api/src/properties/mod.rs", "rank": 92, "score": 85519.57721029119 }, { "content": "fn css_string(name: &str) -> Option<String> {\n\n Some(String::from(name))\n\n}\n\n\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 93, "score": 82911.92996810985 }, { "content": "fn css_color(name: &str) -> Option<Brush> {\n\n Some(match name {\n\n \"transparent\" => Brush::from(name),\n\n\n\n \"black\" => Brush::from(\"#000000\"),\n\n \"silver\" => Brush::from(\"#C0C0C0\"),\n\n \"gray\" | \"grey\" => Brush::from(\"#808080\"),\n\n \"white\" => Brush::from(\"#FFFFFF\"),\n\n \"maroon\" => Brush::from(\"#800000\"),\n\n \"red\" => Brush::from(\"#FF0000\"),\n\n \"purple\" => Brush::from(\"#800080\"),\n\n \"fuchsia\" => Brush::from(\"#FF00FF\"),\n\n \"green\" => Brush::from(\"#008000\"),\n\n \"lime\" => Brush::from(\"#00FF00\"),\n\n \"olive\" => Brush::from(\"#808000\"),\n\n \"yellow\" => Brush::from(\"#FFFF00\"),\n\n \"navy\" => Brush::from(\"#000080\"),\n\n \"blue\" => Brush::from(\"#0000FF\"),\n\n \"teal\" => Brush::from(\"#008080\"),\n\n \"aqua\" => Brush::from(\"#00FFFF\"),\n\n _ => return None,\n\n })\n\n}\n\n\n", "file_path": "crates/css-engine/src/theme.rs", "rank": 94, "score": 82911.92996810985 }, { "content": "fn component_or_default<C: Component + Clone + Default>(\n\n ecm: &mut EntityComponentManager<Tree, StringComponentStore>,\n\n entity: Entity,\n\n component: &str,\n\n) -> C {\n\n ecm.component_store()\n\n .get::<C>(component, entity)\n\n .map(Clone::clone)\n\n .unwrap_or_default()\n\n}\n\n\n", "file_path": "crates/api/src/layout/mod.rs", "rank": 95, "score": 82911.92996810985 }, { "content": "fn brush_to_source<'a>(brush: &Brush) -> raqote::Source<'a> {\n\n match brush {\n\n Brush::SolidColor(color) => raqote::Source::Solid(raqote::SolidSource {\n\n r: color.r(),\n\n g: color.g(),\n\n b: color.b(),\n\n a: color.a(),\n\n }),\n\n Brush::LinearGradient { start, end, stops } => {\n\n let g_stops = stops\n\n .iter()\n\n .map(|stop| raqote::GradientStop {\n\n position: stop.position as f32,\n\n color: raqote::Color::new(\n\n stop.color.a(),\n\n stop.color.r(),\n\n stop.color.g(),\n\n stop.color.b(),\n\n ),\n\n })\n", "file_path": "crates/render/src/raqote/mod.rs", "rank": 96, "score": 80793.94744847175 }, { "content": "\n\n /// Sets or share the icon font size property.\n\n icon_size: f64,\n\n\n\n /// Sets or shares the icon font property.\n\n icon_font: String,\n\n\n\n /// Sets or shares the pressed property.\n\n pressed: bool,\n\n\n\n /// Sets or shares the spacing between icon and text.\n\n spacing: f64\n\n }\n\n);\n\n\n\nimpl Template for Button {\n\n fn template(self, id: Entity, ctx: &mut BuildContext) -> Self {\n\n self.name(\"Button\")\n\n .element(\"button\")\n\n .height(36.0)\n", "file_path": "crates/widgets/src/button.rs", "rank": 97, "score": 77840.76206591715 }, { "content": "use super::behaviors::MouseBehavior;\n\nuse crate::prelude::*;\n\n\n\nwidget!(\n\n /// The `Button` widget can be clicked by user. It's used to perform an action.\n\n ///\n\n /// **CSS element:** `button`\n\n Button: MouseHandler {\n\n /// Sets or shares the background property.\n\n background: Brush,\n\n\n\n /// Sets or shares the border radius property.\n\n border_radius: f64,\n\n\n\n /// Sets or shares the border thickness property.\n\n border_width: Thickness,\n\n\n\n /// Sets or shares the border brush property.\n\n border_brush: Brush,\n\n\n", "file_path": "crates/widgets/src/button.rs", "rank": 98, "score": 77840.46731879181 }, { "content": " .min_width(64.0)\n\n .background(colors::LYNCH_COLOR)\n\n .border_radius(4.0)\n\n .border_width(0.0)\n\n .border_brush(\"transparent\")\n\n .padding((16.0, 0.0, 16.0, 0.0))\n\n .foreground(colors::LINK_WATER_COLOR)\n\n .text(\"\")\n\n .font_size(fonts::FONT_SIZE_12)\n\n .font(\"Roboto Regular\")\n\n .icon(\"\")\n\n .icon_font(\"Material Icons\")\n\n .icon_size(fonts::ICON_FONT_SIZE_12)\n\n .icon_brush(colors::LINK_WATER_COLOR)\n\n .pressed(false)\n\n .spacing(8.0)\n\n .child(\n\n MouseBehavior::create()\n\n .pressed(id)\n\n .enabled(id)\n", "file_path": "crates/widgets/src/button.rs", "rank": 99, "score": 77827.29914379206 } ]
Rust
crates/ra_syntax/src/ast/edit.rs
ztlpn/rust-analyzer
6b9bd7bdd2712a7e85d6bfc70c231dbe36c2e585
use std::{iter, ops::RangeInclusive}; use arrayvec::ArrayVec; use rustc_hash::FxHashMap; use crate::{ algo, ast::{ self, make::{self, tokens}, AstNode, TypeBoundsOwner, }, AstToken, Direction, InsertPosition, SmolStr, SyntaxElement, SyntaxKind::{ATTR, COMMENT, WHITESPACE}, SyntaxNode, SyntaxToken, T, }; impl ast::FnDef { #[must_use] pub fn with_body(&self, body: ast::Block) -> ast::FnDef { let mut to_insert: ArrayVec<[SyntaxElement; 2]> = ArrayVec::new(); let old_body_or_semi: SyntaxElement = if let Some(old_body) = self.body() { old_body.syntax().clone().into() } else if let Some(semi) = self.semicolon_token() { to_insert.push(make::tokens::single_space().into()); semi.into() } else { to_insert.push(make::tokens::single_space().into()); to_insert.push(body.syntax().clone().into()); return insert_children(self, InsertPosition::Last, to_insert.into_iter()); }; to_insert.push(body.syntax().clone().into()); let replace_range = RangeInclusive::new(old_body_or_semi.clone(), old_body_or_semi); replace_children(self, replace_range, to_insert.into_iter()) } } impl ast::ItemList { #[must_use] pub fn append_items(&self, items: impl Iterator<Item = ast::ImplItem>) -> ast::ItemList { let mut res = self.clone(); if !self.syntax().text().contains_char('\n') { res = res.make_multiline(); } items.for_each(|it| res = res.append_item(it)); res } #[must_use] pub fn append_item(&self, item: ast::ImplItem) -> ast::ItemList { let (indent, position) = match self.impl_items().last() { Some(it) => ( leading_indent(it.syntax()).unwrap_or_default().to_string(), InsertPosition::After(it.syntax().clone().into()), ), None => match self.l_curly() { Some(it) => ( " ".to_string() + &leading_indent(self.syntax()).unwrap_or_default(), InsertPosition::After(it), ), None => return self.clone(), }, }; let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); let to_insert: ArrayVec<[SyntaxElement; 2]> = [ws.ws().into(), item.syntax().clone().into()].into(); insert_children(self, position, to_insert.into_iter()) } fn l_curly(&self) -> Option<SyntaxElement> { self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) } fn make_multiline(&self) -> ast::ItemList { let l_curly = match self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) { Some(it) => it, None => return self.clone(), }; let sibling = match l_curly.next_sibling_or_token() { Some(it) => it, None => return self.clone(), }; let existing_ws = match sibling.as_token() { None => None, Some(tok) if tok.kind() != WHITESPACE => None, Some(ws) => { if ws.text().contains('\n') { return self.clone(); } Some(ws.clone()) } }; let indent = leading_indent(self.syntax()).unwrap_or("".into()); let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); let to_insert = iter::once(ws.ws().into()); match existing_ws { None => insert_children(self, InsertPosition::After(l_curly), to_insert), Some(ws) => { replace_children(self, RangeInclusive::new(ws.clone().into(), ws.into()), to_insert) } } } } impl ast::RecordFieldList { #[must_use] pub fn append_field(&self, field: &ast::RecordField) -> ast::RecordFieldList { self.insert_field(InsertPosition::Last, field) } #[must_use] pub fn insert_field( &self, position: InsertPosition<&'_ ast::RecordField>, field: &ast::RecordField, ) -> ast::RecordFieldList { let is_multiline = self.syntax().text().contains_char('\n'); let ws; let space = if is_multiline { ws = tokens::WsBuilder::new(&format!( "\n{} ", leading_indent(self.syntax()).unwrap_or("".into()) )); ws.ws() } else { tokens::single_space() }; let mut to_insert: ArrayVec<[SyntaxElement; 4]> = ArrayVec::new(); to_insert.push(space.into()); to_insert.push(field.syntax().clone().into()); to_insert.push(tokens::comma().into()); macro_rules! after_l_curly { () => {{ let anchor = match self.l_curly() { Some(it) => it, None => return self.clone(), }; InsertPosition::After(anchor) }}; } macro_rules! after_field { ($anchor:expr) => { if let Some(comma) = $anchor .syntax() .siblings_with_tokens(Direction::Next) .find(|it| it.kind() == T![,]) { InsertPosition::After(comma) } else { to_insert.insert(0, tokens::comma().into()); InsertPosition::After($anchor.syntax().clone().into()) } }; }; let position = match position { InsertPosition::First => after_l_curly!(), InsertPosition::Last => { if !is_multiline { to_insert.pop(); } match self.fields().last() { Some(it) => after_field!(it), None => after_l_curly!(), } } InsertPosition::Before(anchor) => { InsertPosition::Before(anchor.syntax().clone().into()) } InsertPosition::After(anchor) => after_field!(anchor), }; insert_children(self, position, to_insert.iter().cloned()) } fn l_curly(&self) -> Option<SyntaxElement> { self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) } } impl ast::TypeParam { #[must_use] pub fn remove_bounds(&self) -> ast::TypeParam { let colon = match self.colon_token() { Some(it) => it, None => return self.clone(), }; let end = match self.type_bound_list() { Some(it) => it.syntax().clone().into(), None => colon.clone().into(), }; replace_children(self, RangeInclusive::new(colon.into(), end), iter::empty()) } } #[must_use] pub fn strip_attrs_and_docs<N: ast::AttrsOwner>(node: &N) -> N { N::cast(strip_attrs_and_docs_inner(node.syntax().clone())).unwrap() } fn strip_attrs_and_docs_inner(mut node: SyntaxNode) -> SyntaxNode { while let Some(start) = node.children_with_tokens().find(|it| it.kind() == ATTR || it.kind() == COMMENT) { let end = match &start.next_sibling_or_token() { Some(el) if el.kind() == WHITESPACE => el.clone(), Some(_) | None => start.clone(), }; node = algo::replace_children(&node, RangeInclusive::new(start, end), &mut iter::empty()); } node } #[must_use] pub fn replace_descendants<N: AstNode, D: AstNode>( parent: &N, replacement_map: impl Iterator<Item = (D, D)>, ) -> N { let map = replacement_map .map(|(from, to)| (from.syntax().clone().into(), to.syntax().clone().into())) .collect::<FxHashMap<_, _>>(); let new_syntax = algo::replace_descendants(parent.syntax(), &map); N::cast(new_syntax).unwrap() } #[derive(Debug, Clone, Copy)] pub struct IndentLevel(pub u8); impl From<u8> for IndentLevel { fn from(level: u8) -> IndentLevel { IndentLevel(level) } } impl IndentLevel { pub fn from_node(node: &SyntaxNode) -> IndentLevel { let first_token = match node.first_token() { Some(it) => it, None => return IndentLevel(0), }; for ws in prev_tokens(first_token).filter_map(ast::Whitespace::cast) { let text = ws.syntax().text(); if let Some(pos) = text.rfind('\n') { let level = text[pos + 1..].chars().count() / 4; return IndentLevel(level as u8); } } IndentLevel(0) } pub fn increase_indent<N: AstNode>(self, node: N) -> N { N::cast(self._increase_indent(node.syntax().clone())).unwrap() } fn _increase_indent(self, node: SyntaxNode) -> SyntaxNode { let replacements: FxHashMap<SyntaxElement, SyntaxElement> = node .descendants_with_tokens() .filter_map(|el| el.into_token()) .filter_map(ast::Whitespace::cast) .filter(|ws| { let text = ws.syntax().text(); text.contains('\n') }) .map(|ws| { ( ws.syntax().clone().into(), make::tokens::whitespace(&format!( "{}{:width$}", ws.syntax().text(), "", width = self.0 as usize * 4 )) .into(), ) }) .collect(); algo::replace_descendants(&node, &replacements) } } fn leading_indent(node: &SyntaxNode) -> Option<SmolStr> { for token in prev_tokens(node.first_token()?) { if let Some(ws) = ast::Whitespace::cast(token.clone()) { let ws_text = ws.text(); if let Some(pos) = ws_text.rfind('\n') { return Some(ws_text[pos + 1..].into()); } } if token.text().contains('\n') { break; } } None } fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> { iter::successors(Some(token), |token| token.prev_token()) } #[must_use] fn insert_children<N: AstNode>( parent: &N, position: InsertPosition<SyntaxElement>, mut to_insert: impl Iterator<Item = SyntaxElement>, ) -> N { let new_syntax = algo::insert_children(parent.syntax(), position, &mut to_insert); N::cast(new_syntax).unwrap() } #[must_use] fn replace_children<N: AstNode>( parent: &N, to_replace: RangeInclusive<SyntaxElement>, mut to_insert: impl Iterator<Item = SyntaxElement>, ) -> N { let new_syntax = algo::replace_children(parent.syntax(), to_replace, &mut to_insert); N::cast(new_syntax).unwrap() } #[test] fn test_increase_indent() { let arm_list = { let arm = make::match_arm(iter::once(make::placeholder_pat().into()), make::expr_unit()); make::match_arm_list(vec![arm.clone(), arm].into_iter()) }; assert_eq!( arm_list.syntax().to_string(), "{ _ => (), _ => (), }" ); let indented = IndentLevel(2).increase_indent(arm_list); assert_eq!( indented.syntax().to_string(), "{ _ => (), _ => (), }" ); }
use std::{iter, ops::RangeInclusive}; use arrayvec::ArrayVec; use rustc_hash::FxHashMap; use crate::{ algo, ast::{ self, make::{self, tokens}, AstNode, TypeBoundsOwner, }, AstToken, Direction, InsertPosition, SmolStr, SyntaxElement, SyntaxKind::{ATTR, COMMENT, WHITESPACE}, SyntaxNode, SyntaxToken, T, }; impl ast::FnDef { #[must_use] pub fn with_body(&self, body: ast::Block) -> ast::FnDef { let mut to_insert: ArrayVec<[SyntaxElement; 2]> = ArrayVec::new(); let old_body_or_semi: SyntaxElement = if let Some(old_body) = self.body() { old_body.syntax().clone().into() } else if let Some(semi) = self.semicolon_token() { to_insert.push(make::tokens::single_space().into()); semi.into() } else { to_insert.push(make::tokens::single_space().into()); to_insert.push(body.syntax().clone().into()); return insert_children(self, InsertPosition::Last, to_insert.int
} impl ast::ItemList { #[must_use] pub fn append_items(&self, items: impl Iterator<Item = ast::ImplItem>) -> ast::ItemList { let mut res = self.clone(); if !self.syntax().text().contains_char('\n') { res = res.make_multiline(); } items.for_each(|it| res = res.append_item(it)); res } #[must_use] pub fn append_item(&self, item: ast::ImplItem) -> ast::ItemList { let (indent, position) = match self.impl_items().last() { Some(it) => ( leading_indent(it.syntax()).unwrap_or_default().to_string(), InsertPosition::After(it.syntax().clone().into()), ), None => match self.l_curly() { Some(it) => ( " ".to_string() + &leading_indent(self.syntax()).unwrap_or_default(), InsertPosition::After(it), ), None => return self.clone(), }, }; let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); let to_insert: ArrayVec<[SyntaxElement; 2]> = [ws.ws().into(), item.syntax().clone().into()].into(); insert_children(self, position, to_insert.into_iter()) } fn l_curly(&self) -> Option<SyntaxElement> { self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) } fn make_multiline(&self) -> ast::ItemList { let l_curly = match self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) { Some(it) => it, None => return self.clone(), }; let sibling = match l_curly.next_sibling_or_token() { Some(it) => it, None => return self.clone(), }; let existing_ws = match sibling.as_token() { None => None, Some(tok) if tok.kind() != WHITESPACE => None, Some(ws) => { if ws.text().contains('\n') { return self.clone(); } Some(ws.clone()) } }; let indent = leading_indent(self.syntax()).unwrap_or("".into()); let ws = tokens::WsBuilder::new(&format!("\n{}", indent)); let to_insert = iter::once(ws.ws().into()); match existing_ws { None => insert_children(self, InsertPosition::After(l_curly), to_insert), Some(ws) => { replace_children(self, RangeInclusive::new(ws.clone().into(), ws.into()), to_insert) } } } } impl ast::RecordFieldList { #[must_use] pub fn append_field(&self, field: &ast::RecordField) -> ast::RecordFieldList { self.insert_field(InsertPosition::Last, field) } #[must_use] pub fn insert_field( &self, position: InsertPosition<&'_ ast::RecordField>, field: &ast::RecordField, ) -> ast::RecordFieldList { let is_multiline = self.syntax().text().contains_char('\n'); let ws; let space = if is_multiline { ws = tokens::WsBuilder::new(&format!( "\n{} ", leading_indent(self.syntax()).unwrap_or("".into()) )); ws.ws() } else { tokens::single_space() }; let mut to_insert: ArrayVec<[SyntaxElement; 4]> = ArrayVec::new(); to_insert.push(space.into()); to_insert.push(field.syntax().clone().into()); to_insert.push(tokens::comma().into()); macro_rules! after_l_curly { () => {{ let anchor = match self.l_curly() { Some(it) => it, None => return self.clone(), }; InsertPosition::After(anchor) }}; } macro_rules! after_field { ($anchor:expr) => { if let Some(comma) = $anchor .syntax() .siblings_with_tokens(Direction::Next) .find(|it| it.kind() == T![,]) { InsertPosition::After(comma) } else { to_insert.insert(0, tokens::comma().into()); InsertPosition::After($anchor.syntax().clone().into()) } }; }; let position = match position { InsertPosition::First => after_l_curly!(), InsertPosition::Last => { if !is_multiline { to_insert.pop(); } match self.fields().last() { Some(it) => after_field!(it), None => after_l_curly!(), } } InsertPosition::Before(anchor) => { InsertPosition::Before(anchor.syntax().clone().into()) } InsertPosition::After(anchor) => after_field!(anchor), }; insert_children(self, position, to_insert.iter().cloned()) } fn l_curly(&self) -> Option<SyntaxElement> { self.syntax().children_with_tokens().find(|it| it.kind() == T!['{']) } } impl ast::TypeParam { #[must_use] pub fn remove_bounds(&self) -> ast::TypeParam { let colon = match self.colon_token() { Some(it) => it, None => return self.clone(), }; let end = match self.type_bound_list() { Some(it) => it.syntax().clone().into(), None => colon.clone().into(), }; replace_children(self, RangeInclusive::new(colon.into(), end), iter::empty()) } } #[must_use] pub fn strip_attrs_and_docs<N: ast::AttrsOwner>(node: &N) -> N { N::cast(strip_attrs_and_docs_inner(node.syntax().clone())).unwrap() } fn strip_attrs_and_docs_inner(mut node: SyntaxNode) -> SyntaxNode { while let Some(start) = node.children_with_tokens().find(|it| it.kind() == ATTR || it.kind() == COMMENT) { let end = match &start.next_sibling_or_token() { Some(el) if el.kind() == WHITESPACE => el.clone(), Some(_) | None => start.clone(), }; node = algo::replace_children(&node, RangeInclusive::new(start, end), &mut iter::empty()); } node } #[must_use] pub fn replace_descendants<N: AstNode, D: AstNode>( parent: &N, replacement_map: impl Iterator<Item = (D, D)>, ) -> N { let map = replacement_map .map(|(from, to)| (from.syntax().clone().into(), to.syntax().clone().into())) .collect::<FxHashMap<_, _>>(); let new_syntax = algo::replace_descendants(parent.syntax(), &map); N::cast(new_syntax).unwrap() } #[derive(Debug, Clone, Copy)] pub struct IndentLevel(pub u8); impl From<u8> for IndentLevel { fn from(level: u8) -> IndentLevel { IndentLevel(level) } } impl IndentLevel { pub fn from_node(node: &SyntaxNode) -> IndentLevel { let first_token = match node.first_token() { Some(it) => it, None => return IndentLevel(0), }; for ws in prev_tokens(first_token).filter_map(ast::Whitespace::cast) { let text = ws.syntax().text(); if let Some(pos) = text.rfind('\n') { let level = text[pos + 1..].chars().count() / 4; return IndentLevel(level as u8); } } IndentLevel(0) } pub fn increase_indent<N: AstNode>(self, node: N) -> N { N::cast(self._increase_indent(node.syntax().clone())).unwrap() } fn _increase_indent(self, node: SyntaxNode) -> SyntaxNode { let replacements: FxHashMap<SyntaxElement, SyntaxElement> = node .descendants_with_tokens() .filter_map(|el| el.into_token()) .filter_map(ast::Whitespace::cast) .filter(|ws| { let text = ws.syntax().text(); text.contains('\n') }) .map(|ws| { ( ws.syntax().clone().into(), make::tokens::whitespace(&format!( "{}{:width$}", ws.syntax().text(), "", width = self.0 as usize * 4 )) .into(), ) }) .collect(); algo::replace_descendants(&node, &replacements) } } fn leading_indent(node: &SyntaxNode) -> Option<SmolStr> { for token in prev_tokens(node.first_token()?) { if let Some(ws) = ast::Whitespace::cast(token.clone()) { let ws_text = ws.text(); if let Some(pos) = ws_text.rfind('\n') { return Some(ws_text[pos + 1..].into()); } } if token.text().contains('\n') { break; } } None } fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> { iter::successors(Some(token), |token| token.prev_token()) } #[must_use] fn insert_children<N: AstNode>( parent: &N, position: InsertPosition<SyntaxElement>, mut to_insert: impl Iterator<Item = SyntaxElement>, ) -> N { let new_syntax = algo::insert_children(parent.syntax(), position, &mut to_insert); N::cast(new_syntax).unwrap() } #[must_use] fn replace_children<N: AstNode>( parent: &N, to_replace: RangeInclusive<SyntaxElement>, mut to_insert: impl Iterator<Item = SyntaxElement>, ) -> N { let new_syntax = algo::replace_children(parent.syntax(), to_replace, &mut to_insert); N::cast(new_syntax).unwrap() } #[test] fn test_increase_indent() { let arm_list = { let arm = make::match_arm(iter::once(make::placeholder_pat().into()), make::expr_unit()); make::match_arm_list(vec![arm.clone(), arm].into_iter()) }; assert_eq!( arm_list.syntax().to_string(), "{ _ => (), _ => (), }" ); let indented = IndentLevel(2).increase_indent(arm_list); assert_eq!( indented.syntax().to_string(), "{ _ => (), _ => (), }" ); }
o_iter()); }; to_insert.push(body.syntax().clone().into()); let replace_range = RangeInclusive::new(old_body_or_semi.clone(), old_body_or_semi); replace_children(self, replace_range, to_insert.into_iter()) }
function_block-function_prefixed
[ { "content": "fn adj_comments(comment: &ast::Comment, dir: Direction) -> ast::Comment {\n\n let mut res = comment.clone();\n\n for element in comment.syntax().siblings_with_tokens(dir) {\n\n let token = match element.as_token() {\n\n None => break,\n\n Some(token) => token,\n\n };\n\n if let Some(c) = ast::Comment::cast(token.clone()) {\n\n res = c\n\n } else if token.kind() != WHITESPACE || token.text().contains(\"\\n\\n\") {\n\n break;\n\n }\n\n }\n\n res\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use ra_syntax::{AstNode, SourceFile};\n\n use test_utils::extract_offset;\n", "file_path": "crates/ra_ide_api/src/extend_selection.rs", "rank": 1, "score": 350528.92509612354 }, { "content": "pub fn where_clause(preds: impl Iterator<Item = ast::WherePred>) -> ast::WhereClause {\n\n let preds = preds.map(|p| p.syntax().to_string()).join(\", \");\n\n return from_text(preds.as_str());\n\n\n\n fn from_text(text: &str) -> ast::WhereClause {\n\n ast_from_text(&format!(\"fn f() where {} {{ }}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 2, "score": 328258.5587771117 }, { "content": "/// Returns the textual content of a doc comment block as a quoted string\n\n/// That is, strips leading `///` (or `/**`, etc)\n\n/// and strips the ending `*/`\n\n/// And then quote the string, which is needed to convert to `tt::Literal`\n\nfn doc_comment_text(comment: &ast::Comment) -> SmolStr {\n\n let prefix_len = comment.prefix().len();\n\n let mut text = &comment.text()[prefix_len..];\n\n\n\n // Remove ending \"*/\"\n\n if comment.kind().shape == ast::CommentShape::Block {\n\n text = &text[0..text.len() - 2];\n\n }\n\n\n\n // Quote the string\n\n // Note that `tt::Literal` expect an escaped string\n\n let text = format!(\"{:?}\", text.escape_default().to_string());\n\n text.into()\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 3, "score": 326734.1925771579 }, { "content": "/// Convert the syntax tree (what user has written) to a `TokenTree` (what macro\n\n/// will consume).\n\npub fn ast_to_token_tree(ast: &ast::TokenTree) -> Option<(tt::Subtree, TokenMap)> {\n\n let mut token_map = TokenMap::default();\n\n let node = ast.syntax();\n\n let tt = convert_tt(&mut token_map, node.text_range().start(), node)?;\n\n Some((tt, token_map))\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 4, "score": 317986.3413656675 }, { "content": "fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {\n\n let use_tree_list = ast::UseTreeList::cast(token.parent())?;\n\n let (tree,) = use_tree_list.use_trees().collect_tuple()?;\n\n edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());\n\n Some(())\n\n}\n\n\n", "file_path": "crates/ra_ide_api/src/join_lines.rs", "rank": 5, "score": 313525.4281219861 }, { "content": "pub fn where_pred(path: ast::Path, bounds: impl Iterator<Item = ast::TypeBound>) -> ast::WherePred {\n\n let bounds = bounds.map(|b| b.syntax().to_string()).join(\" + \");\n\n return from_text(&format!(\"{}: {}\", path.syntax(), bounds));\n\n\n\n fn from_text(text: &str) -> ast::WherePred {\n\n ast_from_text(&format!(\"fn f() where {} {{ }}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 6, "score": 313453.84891513956 }, { "content": "fn prev_tokens(token: SyntaxToken) -> impl Iterator<Item = SyntaxToken> {\n\n successors(token.prev_token(), |token| token.prev_token())\n\n}\n\n\n", "file_path": "crates/ra_fmt/src/lib.rs", "rank": 7, "score": 312175.34466698114 }, { "content": "pub fn match_arm_list(arms: impl Iterator<Item = ast::MatchArm>) -> ast::MatchArmList {\n\n let arms_str = arms.map(|arm| format!(\"\\n {}\", arm.syntax())).join(\",\");\n\n return from_text(&format!(\"{},\\n\", arms_str));\n\n\n\n fn from_text(text: &str) -> ast::MatchArmList {\n\n ast_from_text(&format!(\"fn f() {{ match () {{{}}} }}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 8, "score": 311839.7220968403 }, { "content": "pub fn record_pat(path: ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::RecordPat {\n\n let pats_str = pats.map(|p| p.syntax().to_string()).join(\", \");\n\n return from_text(&format!(\"{}{{ {} }}\", path.syntax(), pats_str));\n\n\n\n fn from_text(text: &str) -> ast::RecordPat {\n\n ast_from_text(&format!(\"fn f({}: ())\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 9, "score": 310459.8901014079 }, { "content": "pub fn match_arm(pats: impl Iterator<Item = ast::Pat>, expr: ast::Expr) -> ast::MatchArm {\n\n let pats_str = pats.map(|p| p.syntax().to_string()).join(\" | \");\n\n return from_text(&format!(\"{} => {}\", pats_str, expr.syntax()));\n\n\n\n fn from_text(text: &str) -> ast::MatchArm {\n\n ast_from_text(&format!(\"fn f() {{ match () {{{}}} }}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 10, "score": 310459.8901014079 }, { "content": "/// Parse given tokens into the given sink as a rust file.\n\npub fn parse(token_source: &mut dyn TokenSource, tree_sink: &mut dyn TreeSink) {\n\n parse_from_tokens(token_source, tree_sink, grammar::root);\n\n}\n\n\n\npub enum FragmentKind {\n\n Path,\n\n Expr,\n\n Statement,\n\n Type,\n\n Pattern,\n\n Item,\n\n Block,\n\n Visibility,\n\n MetaItem,\n\n\n\n // These kinds are used when parsing the result of expansion\n\n // FIXME: use separate fragment kinds for macro inputs and outputs?\n\n Items,\n\n Statements,\n\n}\n\n\n", "file_path": "crates/ra_parser/src/lib.rs", "rank": 11, "score": 299425.9895475628 }, { "content": "fn add_body(fn_def: ast::FnDef) -> ast::FnDef {\n\n if fn_def.body().is_none() {\n\n fn_def.with_body(make::block_from_expr(make::expr_unimplemented()))\n\n } else {\n\n fn_def\n\n }\n\n}\n\n\n", "file_path": "crates/ra_assists/src/assists/add_missing_impl_members.rs", "rank": 12, "score": 297052.5731133825 }, { "content": "fn b() { foo(1, 2, @, impl, let) }\n", "file_path": "crates/ra_syntax/test_data/parser/err/0022_bad_exprs.rs", "rank": 13, "score": 291491.9827479406 }, { "content": "pub fn expr_unimplemented() -> ast::Expr {\n\n expr_from_text(\"unimplemented!()\")\n\n}\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 14, "score": 288359.5331002339 }, { "content": "pub fn expr_unit() -> ast::Expr {\n\n expr_from_text(\"()\")\n\n}\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 15, "score": 288359.5331002339 }, { "content": "pub fn placeholder_pat() -> ast::PlaceholderPat {\n\n return from_text(\"_\");\n\n\n\n fn from_text(text: &str) -> ast::PlaceholderPat {\n\n ast_from_text(&format!(\"fn f({}: ())\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 16, "score": 284969.8323640842 }, { "content": "fn extend_comments(comment: ast::Comment) -> Option<TextRange> {\n\n let prev = adj_comments(&comment, Direction::Prev);\n\n let next = adj_comments(&comment, Direction::Next);\n\n if prev != next {\n\n Some(TextRange::from_to(\n\n prev.syntax().text_range().start(),\n\n next.syntax().text_range().end(),\n\n ))\n\n } else {\n\n None\n\n }\n\n}\n\n\n", "file_path": "crates/ra_ide_api/src/extend_selection.rs", "rank": 17, "score": 282857.17008776846 }, { "content": "/// Like `AstNode`, but wraps tokens rather than interior nodes.\n\npub trait AstToken {\n\n fn cast(token: SyntaxToken) -> Option<Self>\n\n where\n\n Self: Sized;\n\n fn syntax(&self) -> &SyntaxToken;\n\n fn text(&self) -> &SmolStr {\n\n self.syntax().text()\n\n }\n\n}\n\n\n\n/// An iterator over `SyntaxNode` children of a particular AST type.\n\n#[derive(Debug)]\n\npub struct AstChildren<N> {\n\n inner: SyntaxNodeChildren,\n\n ph: PhantomData<N>,\n\n}\n\n\n\nimpl<N> AstChildren<N> {\n\n fn new(parent: &SyntaxNode) -> Self {\n\n AstChildren { inner: parent.children(), ph: PhantomData }\n\n }\n\n}\n\n\n\nimpl<N: AstNode> Iterator for AstChildren<N> {\n\n type Item = N;\n\n fn next(&mut self) -> Option<N> {\n\n self.inner.by_ref().find_map(N::cast)\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 18, "score": 282808.2927236658 }, { "content": "pub fn block_from_expr(e: ast::Expr) -> ast::Block {\n\n return from_text(&format!(\"{{ {} }}\", e.syntax()));\n\n\n\n fn from_text(text: &str) -> ast::Block {\n\n ast_from_text(&format!(\"fn f() {}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 19, "score": 282365.0372493595 }, { "content": "pub fn bind_pat(name: ast::Name) -> ast::BindPat {\n\n return from_text(name.text());\n\n\n\n fn from_text(text: &str) -> ast::BindPat {\n\n ast_from_text(&format!(\"fn f({}: ())\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 20, "score": 276450.65446880576 }, { "content": "pub fn path_pat(path: ast::Path) -> ast::PathPat {\n\n let path_str = path.syntax().text().to_string();\n\n return from_text(path_str.as_str());\n\n fn from_text(text: &str) -> ast::PathPat {\n\n ast_from_text(&format!(\"fn f({}: ())\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 21, "score": 276450.6544688057 }, { "content": "fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {\n\n let block = ast::Block::cast(token.parent())?;\n\n let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?;\n\n let expr = extract_trivial_expression(&block_expr)?;\n\n\n\n let block_range = block_expr.syntax().text_range();\n\n let mut buf = expr.syntax().text().to_string();\n\n\n\n // Match block needs to have a comma after the block\n\n if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) {\n\n if !has_comma_after(match_arm.syntax()) {\n\n buf.push(',');\n\n }\n\n }\n\n\n\n edit.replace(block_range, buf);\n\n\n\n Some(())\n\n}\n\n\n", "file_path": "crates/ra_ide_api/src/join_lines.rs", "rank": 22, "score": 274190.17855985207 }, { "content": "fn change_vis(mut ctx: AssistCtx<impl HirDatabase>, vis: ast::Visibility) -> Option<Assist> {\n\n if vis.syntax().text() == \"pub\" {\n\n ctx.add_action(AssistId(\"change_visibility\"), \"change to pub(crate)\", |edit| {\n\n edit.target(vis.syntax().text_range());\n\n edit.replace(vis.syntax().text_range(), \"pub(crate)\");\n\n edit.set_cursor(vis.syntax().text_range().start())\n\n });\n\n\n\n return ctx.build();\n\n }\n\n if vis.syntax().text() == \"pub(crate)\" {\n\n ctx.add_action(AssistId(\"change_visibility\"), \"change to pub\", |edit| {\n\n edit.target(vis.syntax().text_range());\n\n edit.replace(vis.syntax().text_range(), \"pub\");\n\n edit.set_cursor(vis.syntax().text_range().start());\n\n });\n\n\n\n return ctx.build();\n\n }\n\n None\n", "file_path": "crates/ra_assists/src/assists/change_visibility.rs", "rank": 23, "score": 272750.85039026255 }, { "content": "/// Break a string up into its component tokens\n\npub fn tokenize(text: &str) -> Vec<Token> {\n\n if text.is_empty() {\n\n return vec![];\n\n }\n\n let mut text = text;\n\n let mut acc = Vec::new();\n\n if let Some(len) = rustc_lexer::strip_shebang(text) {\n\n acc.push(Token { kind: SHEBANG, len: TextUnit::from_usize(len) });\n\n text = &text[len..];\n\n }\n\n while !text.is_empty() {\n\n let rustc_token = rustc_lexer::first_token(text);\n\n let kind = match rustc_token.kind {\n\n rustc_lexer::TokenKind::LineComment => COMMENT,\n\n rustc_lexer::TokenKind::BlockComment { .. } => COMMENT,\n\n rustc_lexer::TokenKind::Whitespace => WHITESPACE,\n\n rustc_lexer::TokenKind::Ident => {\n\n let token_text = &text[..rustc_token.len];\n\n if token_text == \"_\" {\n\n UNDERSCORE\n", "file_path": "crates/ra_syntax/src/parsing/lexer.rs", "rank": 24, "score": 272041.51141019736 }, { "content": "fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug {\n\n struct DebugFn<F>(F);\n\n\n\n impl<F: Fn(&mut fmt::Formatter<'_>) -> fmt::Result> fmt::Debug for DebugFn<F> {\n\n fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n (&self.0)(fmt)\n\n }\n\n }\n\n\n\n DebugFn(f)\n\n}\n", "file_path": "crates/ra_hir/src/debug.rs", "rank": 25, "score": 271399.5214790859 }, { "content": "pub fn path_from_name_ref(name_ref: ast::NameRef) -> ast::Path {\n\n path_from_text(&name_ref.syntax().to_string())\n\n}\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 26, "score": 270937.53712417505 }, { "content": "fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextUnit) {\n\n if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\\n').count() != 1 {\n\n // The node is either the first or the last in the file\n\n let suff = &token.text()[TextRange::from_to(\n\n offset - token.text_range().start() + TextUnit::of_char('\\n'),\n\n TextUnit::of_str(token.text()),\n\n )];\n\n let spaces = suff.bytes().take_while(|&b| b == b' ').count();\n\n\n\n edit.replace(TextRange::offset_len(offset, ((spaces + 1) as u32).into()), \" \".to_string());\n\n return;\n\n }\n\n\n\n // Special case that turns something like:\n\n //\n\n // ```\n\n // my_function({<|>\n\n // <some-expr>\n\n // })\n\n // ```\n", "file_path": "crates/ra_ide_api/src/join_lines.rs", "rank": 27, "score": 267544.96456245607 }, { "content": "pub fn name_ref(text: &str) -> ast::NameRef {\n\n ast_from_text(&format!(\"fn f() {{ {}; }}\", text))\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 28, "score": 265084.3570147259 }, { "content": "pub fn foo(mut r: WriteHandler<()>) {\n\n r.finished(<|>);\n\n}\n\n\n\n\"#,\n\n );\n\n\n\n assert_eq!(info.parameters(), [\"&mut self\", \"ctx: &mut Self::Context\"]);\n\n assert_eq!(info.active_parameter, Some(1));\n\n assert_eq!(\n\n info.doc().map(|it| it.into()),\n\n Some(\n\n r#\"Method is called when writer finishes.\n\n\n\nBy default this method stops actor's `Context`.\"#\n\n .to_string()\n\n )\n\n );\n\n }\n\n\n", "file_path": "crates/ra_ide_api/src/call_info.rs", "rank": 29, "score": 264390.9574544713 }, { "content": "pub fn path_qualified(qual: ast::Path, name_ref: ast::NameRef) -> ast::Path {\n\n path_from_text(&format!(\"{}::{}\", qual.syntax(), name_ref.syntax()))\n\n}\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 30, "score": 264298.10223557346 }, { "content": "/// Walks the subtree in bfs order, calling `f` for each node.\n\nfn bfs(node: &SyntaxNode, mut f: impl FnMut(SyntaxNode)) {\n\n let mut curr_layer = vec![node.clone()];\n\n let mut next_layer = vec![];\n\n while !curr_layer.is_empty() {\n\n curr_layer.drain(..).for_each(|node| {\n\n next_layer.extend(node.children());\n\n f(node);\n\n });\n\n std::mem::swap(&mut curr_layer, &mut next_layer);\n\n }\n\n}\n", "file_path": "crates/ra_hir/src/source_id.rs", "rank": 31, "score": 262745.55698240583 }, { "content": "/// The entry point of type inference.\n\npub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> {\n\n let _p = profile(\"infer_query\");\n\n let body = def.body(db);\n\n let resolver = def.resolver(db);\n\n let mut ctx = InferenceContext::new(db, body, resolver);\n\n\n\n match def {\n\n DefWithBody::Const(ref c) => ctx.collect_const(&c.data(db)),\n\n DefWithBody::Function(ref f) => ctx.collect_fn(&f.data(db)),\n\n DefWithBody::Static(ref s) => ctx.collect_const(&s.data(db)),\n\n }\n\n\n\n ctx.infer_body();\n\n\n\n Arc::new(ctx.resolve_all())\n\n}\n\n\n", "file_path": "crates/ra_hir/src/ty/infer.rs", "rank": 32, "score": 262328.04794435995 }, { "content": "pub fn extract_trivial_expression(expr: &ast::BlockExpr) -> Option<ast::Expr> {\n\n let block = expr.block()?;\n\n let expr = block.expr()?;\n\n if expr.syntax().text().contains_char('\\n') {\n\n return None;\n\n }\n\n let non_trivial_children = block.syntax().children().filter(|it| match it.kind() {\n\n WHITESPACE | T!['{'] | T!['}'] => false,\n\n _ => it != expr.syntax(),\n\n });\n\n if non_trivial_children.count() > 0 {\n\n return None;\n\n }\n\n Some(expr)\n\n}\n\n\n", "file_path": "crates/ra_fmt/src/lib.rs", "rank": 33, "score": 261715.86192681827 }, { "content": "/// Adds specified children (tokens or nodes) to the current node at the\n\n/// specific position.\n\n///\n\n/// This is a type-unsafe low-level editing API, if you need to use it,\n\n/// prefer to create a type-safe abstraction on top of it instead.\n\npub fn insert_children(\n\n parent: &SyntaxNode,\n\n position: InsertPosition<SyntaxElement>,\n\n to_insert: &mut dyn Iterator<Item = SyntaxElement>,\n\n) -> SyntaxNode {\n\n let mut delta = TextUnit::default();\n\n let to_insert = to_insert.map(|element| {\n\n delta += element.text_range().len();\n\n to_green_element(element)\n\n });\n\n\n\n let old_children = parent.green().children();\n\n\n\n let new_children = match &position {\n\n InsertPosition::First => {\n\n to_insert.chain(old_children.iter().cloned()).collect::<Box<[_]>>()\n\n }\n\n InsertPosition::Last => old_children.iter().cloned().chain(to_insert).collect::<Box<[_]>>(),\n\n InsertPosition::Before(anchor) | InsertPosition::After(anchor) => {\n\n let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 };\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 34, "score": 261686.9685086377 }, { "content": "/// Returns ancestors of the node at the offset, sorted by length. This should\n\n/// do the right thing at an edge, e.g. when searching for expressions at `{\n\n/// <|>foo }` we will get the name reference instead of the whole block, which\n\n/// we would get if we just did `find_token_at_offset(...).flat_map(|t|\n\n/// t.parent().ancestors())`.\n\npub fn ancestors_at_offset(\n\n node: &SyntaxNode,\n\n offset: TextUnit,\n\n) -> impl Iterator<Item = SyntaxNode> {\n\n node.token_at_offset(offset)\n\n .map(|token| token.parent().ancestors())\n\n .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 35, "score": 261686.66689040462 }, { "content": "/// Replaces descendants in the node, according to the mapping.\n\n///\n\n/// This is a type-unsafe low-level editing API, if you need to use it, prefer\n\n/// to create a type-safe abstraction on top of it instead.\n\npub fn replace_descendants(\n\n parent: &SyntaxNode,\n\n map: &FxHashMap<SyntaxElement, SyntaxElement>,\n\n) -> SyntaxNode {\n\n // FIXME: this could be made much faster.\n\n let new_children = parent.children_with_tokens().map(|it| go(map, it)).collect::<Box<[_]>>();\n\n return with_children(parent, new_children);\n\n\n\n fn go(\n\n map: &FxHashMap<SyntaxElement, SyntaxElement>,\n\n element: SyntaxElement,\n\n ) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {\n\n if let Some(replacement) = map.get(&element) {\n\n return match replacement {\n\n NodeOrToken::Node(it) => NodeOrToken::Node(it.green().clone()),\n\n NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()),\n\n };\n\n }\n\n match element {\n\n NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()),\n\n NodeOrToken::Node(it) => {\n\n NodeOrToken::Node(replace_descendants(&it, map).green().clone())\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 36, "score": 261682.7943951206 }, { "content": "/// Replaces all nodes in `to_delete` with nodes from `to_insert`\n\n///\n\n/// This is a type-unsafe low-level editing API, if you need to use it,\n\n/// prefer to create a type-safe abstraction on top of it instead.\n\npub fn replace_children(\n\n parent: &SyntaxNode,\n\n to_delete: RangeInclusive<SyntaxElement>,\n\n to_insert: &mut dyn Iterator<Item = SyntaxElement>,\n\n) -> SyntaxNode {\n\n let start = position_of_child(parent, to_delete.start().clone());\n\n let end = position_of_child(parent, to_delete.end().clone());\n\n let old_children = parent.green().children();\n\n\n\n let new_children = old_children[..start]\n\n .iter()\n\n .cloned()\n\n .chain(to_insert.map(to_green_element))\n\n .chain(old_children[end + 1..].iter().cloned())\n\n .collect::<Box<[_]>>();\n\n with_children(parent, new_children)\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 37, "score": 261682.7943951206 }, { "content": "/// Finds the first sibling in the given direction which is not `trivia`\n\npub fn non_trivia_sibling(element: SyntaxElement, direction: Direction) -> Option<SyntaxElement> {\n\n return match element {\n\n NodeOrToken::Node(node) => node.siblings_with_tokens(direction).skip(1).find(not_trivia),\n\n NodeOrToken::Token(token) => token.siblings_with_tokens(direction).skip(1).find(not_trivia),\n\n };\n\n\n\n fn not_trivia(element: &SyntaxElement) -> bool {\n\n match element {\n\n NodeOrToken::Node(_) => true,\n\n NodeOrToken::Token(token) => !token.kind().is_trivia(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 38, "score": 259246.68063606025 }, { "content": "pub fn record_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordField {\n\n return match expr {\n\n Some(expr) => from_text(&format!(\"{}: {}\", name.syntax(), expr.syntax())),\n\n None => from_text(&name.syntax().to_string()),\n\n };\n\n\n\n fn from_text(text: &str) -> ast::RecordField {\n\n ast_from_text(&format!(\"fn f() {{ S {{ {}, }} }}\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 39, "score": 258263.1056255448 }, { "content": "/// Parses the token tree (result of macro expansion) to an expression\n\npub fn token_tree_to_expr(tt: &tt::Subtree) -> Result<Parse<ast::Expr>, ExpandError> {\n\n let parse = fragment_to_syntax_node(tt, Expr)?;\n\n parse.cast().ok_or_else(|| crate::ExpandError::ConversionError)\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 40, "score": 258088.30360541728 }, { "content": "/// Parses the token tree (result of macro expansion) to a Pattern\n\npub fn token_tree_to_pat(tt: &tt::Subtree) -> Result<Parse<ast::Pat>, ExpandError> {\n\n let parse = fragment_to_syntax_node(tt, Pattern)?;\n\n parse.cast().ok_or_else(|| crate::ExpandError::ConversionError)\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 41, "score": 258088.30360541726 }, { "content": "pub fn classify_literal(text: &str) -> Option<Token> {\n\n let t = rustc_lexer::first_token(text);\n\n if t.len != text.len() {\n\n return None;\n\n }\n\n let kind = match t.kind {\n\n rustc_lexer::TokenKind::Literal { kind, .. } => match_literal_kind(kind),\n\n _ => return None,\n\n };\n\n Some(Token { kind, len: TextUnit::from_usize(t.len) })\n\n}\n", "file_path": "crates/ra_syntax/src/parsing/lexer.rs", "rank": 42, "score": 255046.7285446798 }, { "content": "fn variants(enum_def: &ast::EnumDef) -> impl Iterator<Item = ast::EnumVariant> {\n\n enum_def.variant_list().into_iter().flat_map(|it| it.variants())\n\n}\n\n\n\nimpl EnumVariant {\n\n pub(crate) fn source_impl(\n\n self,\n\n db: &(impl DefDatabase + AstDatabase),\n\n ) -> Source<ast::EnumVariant> {\n\n let src = self.parent.source(db);\n\n let ast = variants(&src.ast)\n\n .zip(db.enum_data(self.parent).variants.iter())\n\n .find(|(_syntax, (id, _))| *id == self.id)\n\n .unwrap()\n\n .0;\n\n Source { file_id: src.file_id, ast }\n\n }\n\n pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> {\n\n db.enum_data(self.parent).variants[self.id].variant_data.clone()\n\n }\n", "file_path": "crates/ra_hir/src/adt.rs", "rank": 43, "score": 254793.18975824973 }, { "content": "/// Parses the token tree (result of macro expansion) to a Type\n\npub fn token_tree_to_ty(tt: &tt::Subtree) -> Result<Parse<ast::TypeRef>, ExpandError> {\n\n let parse = fragment_to_syntax_node(tt, Type)?;\n\n parse.cast().ok_or_else(|| crate::ExpandError::ConversionError)\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 44, "score": 254772.4484317861 }, { "content": "/// Parses the token tree (result of macro expansion) as a sequence of items\n\npub fn token_tree_to_items(tt: &tt::Subtree) -> Result<Parse<ast::MacroItems>, ExpandError> {\n\n let parse = fragment_to_syntax_node(tt, Items)?;\n\n parse.cast().ok_or_else(|| crate::ExpandError::ConversionError)\n\n}\n\n\n\nimpl TokenMap {\n\n pub fn relative_range_of(&self, tt: tt::TokenId) -> Option<TextRange> {\n\n let idx = tt.0 as usize;\n\n self.tokens.get(idx).copied()\n\n }\n\n\n\n fn alloc(&mut self, relative_range: TextRange) -> tt::TokenId {\n\n let id = self.tokens.len();\n\n self.tokens.push(relative_range);\n\n tt::TokenId(id as u32)\n\n }\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 45, "score": 254772.36747787407 }, { "content": "pub fn tuple_struct_pat(\n\n path: ast::Path,\n\n pats: impl Iterator<Item = ast::Pat>,\n\n) -> ast::TupleStructPat {\n\n let pats_str = pats.map(|p| p.syntax().to_string()).join(\", \");\n\n return from_text(&format!(\"{}({})\", path.syntax(), pats_str));\n\n\n\n fn from_text(text: &str) -> ast::TupleStructPat {\n\n ast_from_text(&format!(\"fn f({}: ())\", text))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/make.rs", "rank": 46, "score": 253296.24329259308 }, { "content": "/// Parses the token tree (result of macro expansion) as a sequence of stmts\n\npub fn token_tree_to_macro_stmts(tt: &tt::Subtree) -> Result<Parse<ast::MacroStmts>, ExpandError> {\n\n let parse = fragment_to_syntax_node(tt, Statements)?;\n\n parse.cast().ok_or_else(|| crate::ExpandError::ConversionError)\n\n}\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 47, "score": 251573.4532000495 }, { "content": "fn convert_doc_comment(token: &ra_syntax::SyntaxToken) -> Option<Vec<tt::TokenTree>> {\n\n let comment = ast::Comment::cast(token.clone())?;\n\n let doc = comment.kind().doc?;\n\n\n\n // Make `doc=\"\\\" Comments\\\"\"\n\n let mut meta_tkns = Vec::new();\n\n meta_tkns.push(mk_ident(\"doc\"));\n\n meta_tkns.push(mk_punct('='));\n\n meta_tkns.push(mk_doc_literal(&comment));\n\n\n\n // Make `#![]`\n\n let mut token_trees = Vec::new();\n\n token_trees.push(mk_punct('#'));\n\n if let ast::CommentPlacement::Inner = doc {\n\n token_trees.push(mk_punct('!'));\n\n }\n\n token_trees.push(tt::TokenTree::from(tt::Subtree {\n\n delimiter: tt::Delimiter::Bracket,\n\n token_trees: meta_tkns,\n\n }));\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 48, "score": 248931.5847967263 }, { "content": "pub fn reparse(&self, edit: &AtomTextEdit) -> File {\n\n <|>self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))\n\n}\n\n\",\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_join_lines_block() {\n\n check_join_lines(\n\n r\"\n", "file_path": "crates/ra_ide_api/src/join_lines.rs", "rank": 49, "score": 248606.8603988022 }, { "content": "fn f(#[must_use] self) {}\n", "file_path": "crates/ra_syntax/test_data/parser/inline/ok/0138_self_param_outer_attr.rs", "rank": 51, "score": 244882.9659968605 }, { "content": "#[test]\n\nfn test_doc_comment_single_line_block_strips_suffix_whitespace() {\n\n let file = SourceFile::parse(\n\n r#\"\n\n /** this is mod foo */\n\n mod foo {}\n\n \"#,\n\n )\n\n .ok()\n\n .unwrap();\n\n let module = file.syntax().descendants().find_map(Module::cast).unwrap();\n\n assert_eq!(\"this is mod foo\", module.doc_comment_text().unwrap());\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 52, "score": 244043.14737149884 }, { "content": "fn strange() -> bool { let _x: bool = return true; }\n\n\n", "file_path": "crates/ra_syntax/test_data/parser/ok/0035_weird_exprs.rs", "rank": 53, "score": 243783.90558604203 }, { "content": "fn kind_by_prefix(text: &str) -> CommentKind {\n\n for (prefix, kind) in COMMENT_PREFIX_TO_KIND.iter() {\n\n if text.starts_with(prefix) {\n\n return *kind;\n\n }\n\n }\n\n panic!(\"bad comment text: {:?}\", text)\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/tokens.rs", "rank": 54, "score": 243623.59504631138 }, { "content": "fn node_indent(file: &SourceFile, token: &SyntaxToken) -> Option<SmolStr> {\n\n let ws = match file.syntax().token_at_offset(token.text_range().start()) {\n\n TokenAtOffset::Between(l, r) => {\n\n assert!(r == *token);\n\n l\n\n }\n\n TokenAtOffset::Single(n) => {\n\n assert!(n == *token);\n\n return Some(\"\".into());\n\n }\n\n TokenAtOffset::None => unreachable!(),\n\n };\n\n if ws.kind() != WHITESPACE {\n\n return None;\n\n }\n\n let text = ws.text();\n\n let pos = text.rfind('\\n').map(|it| it + 1).unwrap_or(0);\n\n Some(text[pos..].into())\n\n}\n\n\n", "file_path": "crates/ra_ide_api/src/typing.rs", "rank": 55, "score": 240868.30734560092 }, { "content": "// test self_param\n\n// impl S {\n\n// fn a(self) {}\n\n// fn b(&self,) {}\n\n// fn c(&'a self,) {}\n\n// fn d(&'a mut self, x: i32) {}\n\n// fn e(mut self) {}\n\n// }\n\nfn opt_self_param(p: &mut Parser) {\n\n let m;\n\n if p.at(T![self]) || p.at(T![mut]) && p.nth(1) == T![self] {\n\n m = p.start();\n\n p.eat(T![mut]);\n\n p.eat(T![self]);\n\n // test arb_self_types\n\n // impl S {\n\n // fn a(self: &Self) {}\n\n // fn b(mut self: Box<Self>) {}\n\n // }\n\n if p.at(T![:]) {\n\n types::ascription(p);\n\n }\n\n } else {\n\n let la1 = p.nth(1);\n\n let la2 = p.nth(2);\n\n let la3 = p.nth(3);\n\n let n_toks = match (p.current(), la1, la2, la3) {\n\n (T![&], T![self], _, _) => 2,\n", "file_path": "crates/ra_parser/src/grammar/params.rs", "rank": 56, "score": 238553.3166648624 }, { "content": "// test impl_trait_type\n\n// type A = impl Iterator<Item=Foo<'a>> + 'a;\n\nfn impl_trait_type(p: &mut Parser) {\n\n assert!(p.at(T![impl]));\n\n let m = p.start();\n\n p.bump(T![impl]);\n\n type_params::bounds_without_colon(p);\n\n m.complete(p, IMPL_TRAIT_TYPE);\n\n}\n\n\n", "file_path": "crates/ra_parser/src/grammar/types.rs", "rank": 57, "score": 238428.13482879603 }, { "content": "// FIXME: kill duplication\n\nfn validate_literal(literal: ast::Literal, acc: &mut Vec<SyntaxError>) {\n\n let token = literal.token();\n\n let text = token.text().as_str();\n\n match token.kind() {\n\n BYTE => {\n\n if let Some(end) = text.rfind('\\'') {\n\n if let Some(without_quotes) = text.get(2..end) {\n\n if let Err((off, err)) = unescape::unescape_byte(without_quotes) {\n\n let off = token.text_range().start() + TextUnit::from_usize(off + 2);\n\n acc.push(SyntaxError::new(err.into(), off))\n\n }\n\n }\n\n }\n\n }\n\n CHAR => {\n\n if let Some(end) = text.rfind('\\'') {\n\n if let Some(without_quotes) = text.get(1..end) {\n\n if let Err((off, err)) = unescape::unescape_char(without_quotes) {\n\n let off = token.text_range().start() + TextUnit::from_usize(off + 1);\n\n acc.push(SyntaxError::new(err.into(), off))\n", "file_path": "crates/ra_syntax/src/validation.rs", "rank": 58, "score": 238001.14496603323 }, { "content": "fn prefix_by_kind(kind: CommentKind) -> &'static str {\n\n for (prefix, k) in COMMENT_PREFIX_TO_KIND.iter() {\n\n if *k == kind {\n\n return prefix;\n\n }\n\n }\n\n unreachable!()\n\n}\n\n\n\npub struct Whitespace(SyntaxToken);\n\n\n\nimpl AstToken for Whitespace {\n\n fn cast(token: SyntaxToken) -> Option<Self> {\n\n if token.kind() == WHITESPACE {\n\n Some(Whitespace(token))\n\n } else {\n\n None\n\n }\n\n }\n\n fn syntax(&self) -> &SyntaxToken {\n", "file_path": "crates/ra_syntax/src/ast/tokens.rs", "rank": 59, "score": 237116.82482000053 }, { "content": "fn dump_tokens(tokens: &[crate::Token], text: &str) -> String {\n\n let mut acc = String::new();\n\n let mut offset = 0;\n\n for token in tokens {\n\n let len: u32 = token.len.into();\n\n let len = len as usize;\n\n let token_text = &text[offset..offset + len];\n\n offset += len;\n\n write!(acc, \"{:?} {} {:?}\\n\", token.kind, token.len, token_text).unwrap()\n\n }\n\n acc\n\n}\n", "file_path": "crates/ra_syntax/src/tests.rs", "rank": 61, "score": 234684.51705275354 }, { "content": "fn parse_from_tokens<F>(token_source: &mut dyn TokenSource, tree_sink: &mut dyn TreeSink, f: F)\n\nwhere\n\n F: FnOnce(&mut parser::Parser),\n\n{\n\n let mut p = parser::Parser::new(token_source);\n\n f(&mut p);\n\n let events = p.finish();\n\n event::process(tree_sink, events);\n\n}\n\n\n", "file_path": "crates/ra_parser/src/lib.rs", "rank": 62, "score": 231821.7197794945 }, { "content": "trait Foo { fn foo(&self); }\n", "file_path": "crates/ra_assists/src/assists/add_missing_impl_members.rs", "rank": 63, "score": 231801.20227415147 }, { "content": "/// Parse a use 'tree', such as `some::path` in `use some::path;`\n\n/// Note that this is called both by `use_item` and `use_tree_list`,\n\n/// so handles both `some::path::{inner::path}` and `inner::path` in\n\n/// `use some::path::{inner::path};`\n\nfn use_tree(p: &mut Parser, top_level: bool) {\n\n let m = p.start();\n\n match p.current() {\n\n // Finish the use_tree for cases of e.g.\n\n // `use some::path::{self, *};` or `use *;`\n\n // This does not handle cases such as `use some::path::*`\n\n // N.B. in Rust 2015 `use *;` imports all from crate root\n\n // however in Rust 2018 `use *;` errors: ('cannot glob-import all possible crates')\n\n // FIXME: Add this error (if not out of scope)\n\n\n\n // test use_star\n\n // use *;\n\n // use ::*;\n\n // use some::path::{*};\n\n // use some::path::{::*};\n\n T![*] => p.bump(T![*]),\n\n T![:] if p.at(T![::]) && p.nth(2) == T![*] => {\n\n // Parse `use ::*;`, which imports all from the crate root in Rust 2015\n\n // This is invalid inside a use_tree_list, (e.g. `use some::path::{::*}`)\n\n // but still parses and errors later: ('crate root in paths can only be used in start position')\n", "file_path": "crates/ra_parser/src/grammar/items/use_item.rs", "rank": 64, "score": 230352.35539939842 }, { "content": "fn b(_: impl FnMut(x::Y)) {}\n\n\n", "file_path": "crates/ra_syntax/test_data/parser/ok/0054_qual_path_in_type_arg.rs", "rank": 65, "score": 229820.59283669142 }, { "content": "fn c(_: impl FnMut(&x::Y)) {}\n", "file_path": "crates/ra_syntax/test_data/parser/ok/0054_qual_path_in_type_arg.rs", "rank": 66, "score": 229820.59283669142 }, { "content": "fn name_r(p: &mut Parser, recovery: TokenSet) {\n\n if p.at(IDENT) {\n\n let m = p.start();\n\n p.bump(IDENT);\n\n m.complete(p, NAME);\n\n } else {\n\n p.err_recover(\"expected a name\", recovery);\n\n }\n\n}\n\n\n", "file_path": "crates/ra_parser/src/grammar.rs", "rank": 67, "score": 229750.11472866475 }, { "content": "fn add_vis(mut ctx: AssistCtx<impl HirDatabase>) -> Option<Assist> {\n\n let item_keyword = ctx.token_at_offset().find(|leaf| match leaf.kind() {\n\n T![fn] | T![mod] | T![struct] | T![enum] | T![trait] => true,\n\n _ => false,\n\n });\n\n\n\n let (offset, target) = if let Some(keyword) = item_keyword {\n\n let parent = keyword.parent();\n\n let def_kws = vec![FN_DEF, MODULE, STRUCT_DEF, ENUM_DEF, TRAIT_DEF];\n\n // Parent is not a definition, can't add visibility\n\n if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) {\n\n return None;\n\n }\n\n // Already have visibility, do nothing\n\n if parent.children().any(|child| child.kind() == VISIBILITY) {\n\n return None;\n\n }\n\n (vis_offset(&parent), keyword.text_range())\n\n } else {\n\n let ident = ctx.token_at_offset().find(|leaf| leaf.kind() == IDENT)?;\n", "file_path": "crates/ra_assists/src/assists/change_visibility.rs", "rank": 68, "score": 229541.99331081595 }, { "content": "/// Finds a node of specific Ast type at offset. Note that this is slightly\n\n/// imprecise: if the cursor is strictly between two nodes of the desired type,\n\n/// as in\n\n///\n\n/// ```no-run\n\n/// struct Foo {}|struct Bar;\n\n/// ```\n\n///\n\n/// then the shorter node will be silently preferred.\n\npub fn find_node_at_offset<N: AstNode>(syntax: &SyntaxNode, offset: TextUnit) -> Option<N> {\n\n ancestors_at_offset(syntax, offset).find_map(N::cast)\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 69, "score": 228976.8766920352 }, { "content": "fn is_in_loop_body(leaf: &SyntaxToken) -> bool {\n\n for node in leaf.parent().ancestors() {\n\n if node.kind() == FN_DEF || node.kind() == LAMBDA_EXPR {\n\n break;\n\n }\n\n let loop_body = match_ast! {\n\n match node {\n\n ast::ForExpr(it) => { it.loop_body() },\n\n ast::WhileExpr(it) => { it.loop_body() },\n\n ast::LoopExpr(it) => { it.loop_body() },\n\n _ => None,\n\n }\n\n };\n\n if let Some(body) = loop_body {\n\n if leaf.text_range().is_subrange(&body.syntax().text_range()) {\n\n return true;\n\n }\n\n }\n\n }\n\n false\n\n}\n\n\n", "file_path": "crates/ra_ide_api/src/completion/complete_keyword.rs", "rank": 70, "score": 228689.7499734981 }, { "content": "fn text_of_first_token(node: &SyntaxNode) -> &SmolStr {\n\n node.green().children().first().and_then(|it| it.as_token()).unwrap().text()\n\n}\n\n\n\nimpl ast::Attr {\n\n pub fn as_simple_atom(&self) -> Option<SmolStr> {\n\n match self.input() {\n\n None => self.simple_name(),\n\n Some(_) => None,\n\n }\n\n }\n\n\n\n pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {\n\n match self.input() {\n\n Some(AttrInput::TokenTree(tt)) => Some((self.simple_name()?, tt)),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn as_simple_key_value(&self) -> Option<(SmolStr, SmolStr)> {\n", "file_path": "crates/ra_syntax/src/ast/extensions.rs", "rank": 71, "score": 228263.12376735918 }, { "content": "// test return_expr\n\n// fn foo() {\n\n// return;\n\n// return 92;\n\n// }\n\nfn return_expr(p: &mut Parser) -> CompletedMarker {\n\n assert!(p.at(T![return]));\n\n let m = p.start();\n\n p.bump(T![return]);\n\n if p.at_ts(EXPR_FIRST) {\n\n expr(p);\n\n }\n\n m.complete(p, RETURN_EXPR)\n\n}\n\n\n", "file_path": "crates/ra_parser/src/grammar/expressions/atom.rs", "rank": 72, "score": 226929.33412345967 }, { "content": "fn print(lvl: usize, msgs: &[Message], out: &mut impl Write, longer_than: Duration) {\n\n let mut last = 0;\n\n let indent = repeat(\" \").take(lvl + 1).collect::<String>();\n\n // We output hierarchy for long calls, but sum up all short calls\n\n let mut short = Vec::new();\n\n for (i, &Message { level, duration, message: ref msg }) in msgs.iter().enumerate() {\n\n if level != lvl {\n\n continue;\n\n }\n\n if duration >= longer_than {\n\n writeln!(out, \"{} {:6}ms - {}\", indent, duration.as_millis(), msg)\n\n .expect(\"printing profiling info to stdout\");\n\n\n\n print(lvl + 1, &msgs[last..i], out, longer_than);\n\n } else {\n\n short.push((msg, duration))\n\n }\n\n\n\n last = i;\n\n }\n", "file_path": "crates/ra_prof/src/lib.rs", "rank": 73, "score": 226400.43435248916 }, { "content": "/// Extracts ranges, marked with `<tag> </tag>` paris from the `text`\n\npub fn extract_ranges(mut text: &str, tag: &str) -> (Vec<TextRange>, String) {\n\n let open = format!(\"<{}>\", tag);\n\n let close = format!(\"</{}>\", tag);\n\n let mut ranges = Vec::new();\n\n let mut res = String::new();\n\n let mut stack = Vec::new();\n\n loop {\n\n match text.find('<') {\n\n None => {\n\n res.push_str(text);\n\n break;\n\n }\n\n Some(i) => {\n\n res.push_str(&text[..i]);\n\n text = &text[i..];\n\n if text.starts_with(&open) {\n\n text = &text[open.len()..];\n\n let from = TextUnit::of_str(&res);\n\n stack.push(from);\n\n } else if text.starts_with(&close) {\n", "file_path": "crates/test_utils/src/lib.rs", "rank": 74, "score": 223656.07606430026 }, { "content": "fn def_crates(db: &impl HirDatabase, cur_crate: Crate, ty: &Ty) -> Option<ArrayVec<[Crate; 2]>> {\n\n // Types like slice can have inherent impls in several crates, (core and alloc).\n\n // The corresponding impls are marked with lang items, so we can use them to find the required crates.\n\n macro_rules! lang_item_crate {\n\n ($db:expr, $cur_crate:expr, $($name:expr),+ $(,)?) => {{\n\n let mut v = ArrayVec::<[Crate; 2]>::new();\n\n $(\n\n v.extend($db.lang_item($cur_crate, $name.into()).and_then(|item| item.krate($db)));\n\n )+\n\n Some(v)\n\n }};\n\n }\n\n\n\n match ty {\n\n Ty::Apply(a_ty) => match a_ty.ctor {\n\n TypeCtor::Adt(def_id) => Some(std::iter::once(def_id.krate(db)?).collect()),\n\n TypeCtor::Bool => lang_item_crate!(db, cur_crate, \"bool\"),\n\n TypeCtor::Char => lang_item_crate!(db, cur_crate, \"char\"),\n\n TypeCtor::Float(UncertainFloatTy::Known(f)) => match f.bitness {\n\n // There are two lang items: one in libcore (fXX) and one in libstd (fXX_runtime)\n", "file_path": "crates/ra_hir/src/ty/method_resolution.rs", "rank": 75, "score": 222500.63429384324 }, { "content": "fn parse_query(db: &impl SourceDatabase, file_id: FileId) -> Parse<ast::SourceFile> {\n\n let _p = profile(\"parse_query\");\n\n let text = db.file_text(file_id);\n\n SourceFile::parse(&*text)\n\n}\n\n\n\n/// We don't want to give HIR knowledge of source roots, hence we extract these\n\n/// methods into a separate DB.\n", "file_path": "crates/ra_db/src/lib.rs", "rank": 76, "score": 222363.17802260493 }, { "content": "fn validate_numeric_name(name_ref: Option<ast::NameRef>, errors: &mut Vec<SyntaxError>) {\n\n if let Some(int_token) = int_token(name_ref) {\n\n if int_token.text().chars().any(|c| !c.is_digit(10)) {\n\n errors.push(SyntaxError::new(\n\n SyntaxErrorKind::InvalidTupleIndexFormat,\n\n int_token.text_range(),\n\n ));\n\n }\n\n }\n\n\n\n fn int_token(name_ref: Option<ast::NameRef>) -> Option<SyntaxToken> {\n\n name_ref?.syntax().first_child_or_token()?.into_token().filter(|it| it.kind() == INT_NUMBER)\n\n }\n\n}\n", "file_path": "crates/ra_syntax/src/validation.rs", "rank": 77, "score": 222197.71675160067 }, { "content": "fn a() { [1, 2, @, struct, let] }\n", "file_path": "crates/ra_syntax/test_data/parser/err/0022_bad_exprs.rs", "rank": 78, "score": 222109.6553998668 }, { "content": "pub trait LoopBodyOwner: AstNode {\n\n fn loop_body(&self) -> Option<ast::BlockExpr> {\n\n child_opt(self)\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/traits.rs", "rank": 79, "score": 221152.03035634552 }, { "content": "pub trait DocCommentsOwner: AstNode {\n\n fn doc_comments(&self) -> CommentIter {\n\n CommentIter { iter: self.syntax().children_with_tokens() }\n\n }\n\n\n\n /// Returns the textual content of a doc comment block as a single string.\n\n /// That is, strips leading `///` (+ optional 1 character of whitespace),\n\n /// trailing `*/`, trailing whitespace and then joins the lines.\n\n fn doc_comment_text(&self) -> Option<String> {\n\n let mut has_comments = false;\n\n let docs = self\n\n .doc_comments()\n\n .filter(|comment| comment.kind().doc.is_some())\n\n .map(|comment| {\n\n has_comments = true;\n\n let prefix_len = comment.prefix().len();\n\n\n\n let line = comment.text().as_str();\n\n\n\n // Determine if the prefix or prefix + 1 char is stripped\n", "file_path": "crates/ra_syntax/src/ast/traits.rs", "rank": 80, "score": 221136.96371145593 }, { "content": "fn format_arm(block: &ast::BlockExpr) -> String {\n\n match extract_trivial_expression(block) {\n\n None => block.syntax().text().to_string(),\n\n Some(e) => format!(\"{},\", e.syntax().text()),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::helpers::{check_assist, check_assist_target};\n\n\n\n #[test]\n\n fn test_replace_if_let_with_match_unwraps_simple_expressions() {\n\n check_assist(\n\n replace_if_let_with_match,\n\n \"\n\nimpl VariantData {\n\n pub fn is_struct(&self) -> bool {\n\n if <|>let VariantData::Struct(..) = *self {\n", "file_path": "crates/ra_assists/src/assists/replace_if_let_with_match.rs", "rank": 81, "score": 220394.04154068936 }, { "content": "pub trait FnDefOwner: AstNode {\n\n fn functions(&self) -> AstChildren<ast::FnDef> {\n\n children(self)\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq)]\n\npub enum ItemOrMacro {\n\n Item(ast::ModuleItem),\n\n Macro(ast::MacroCall),\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/traits.rs", "rank": 82, "score": 219110.33625914727 }, { "content": "/// Finds minimal the diff, which, applied to `from`, will result in `to`.\n\n///\n\n/// Specifically, returns a map whose keys are descendants of `from` and values\n\n/// are descendants of `to`, such that `replace_descendants(from, map) == to`.\n\n///\n\n/// A trivial solution is a singletom map `{ from: to }`, but this function\n\n/// tries to find a more fine-grained diff.\n\npub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {\n\n let mut buf = FxHashMap::default();\n\n // FIXME: this is both horrible inefficient and gives larger than\n\n // necessary diff. I bet there's a cool algorithm to diff trees properly.\n\n go(&mut buf, from.clone().into(), to.clone().into());\n\n return TreeDiff { replacements: buf };\n\n\n\n fn go(\n\n buf: &mut FxHashMap<SyntaxElement, SyntaxElement>,\n\n lhs: SyntaxElement,\n\n rhs: SyntaxElement,\n\n ) {\n\n if lhs.kind() == rhs.kind() && lhs.text_range().len() == rhs.text_range().len() {\n\n if match (&lhs, &rhs) {\n\n (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => {\n\n lhs.green() == rhs.green() || lhs.text() == rhs.text()\n\n }\n\n (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(),\n\n _ => false,\n\n } {\n", "file_path": "crates/ra_syntax/src/algo.rs", "rank": 83, "score": 219005.3200831149 }, { "content": "#[test]\n\nfn test_doc_comment_none() {\n\n let file = SourceFile::parse(\n\n r#\"\n\n // non-doc\n\n mod foo {}\n\n \"#,\n\n )\n\n .ok()\n\n .unwrap();\n\n let module = file.syntax().descendants().find_map(Module::cast).unwrap();\n\n assert!(module.doc_comment_text().is_none());\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 84, "score": 217755.45438253102 }, { "content": "#[test]\n\nfn test_doc_comment_of_items() {\n\n let file = SourceFile::parse(\n\n r#\"\n\n //! doc\n\n // non-doc\n\n mod foo {}\n\n \"#,\n\n )\n\n .ok()\n\n .unwrap();\n\n let module = file.syntax().descendants().find_map(Module::cast).unwrap();\n\n assert_eq!(\"doc\", module.doc_comment_text().unwrap());\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 85, "score": 217755.45438253102 }, { "content": "pub fn load(\n\n source_roots: &FxHashMap<SourceRootId, PackageRoot>,\n\n crate_graph: CrateGraph,\n\n vfs: &mut Vfs,\n\n receiver: Receiver<VfsTask>,\n\n) -> AnalysisHost {\n\n let lru_cap = std::env::var(\"RA_LRU_CAP\").ok().and_then(|it| it.parse::<usize>().ok());\n\n let mut host = AnalysisHost::new(lru_cap, FeatureFlags::default());\n\n let mut analysis_change = AnalysisChange::new();\n\n analysis_change.set_crate_graph(crate_graph);\n\n\n\n // wait until Vfs has loaded all roots\n\n let mut roots_loaded = HashSet::new();\n\n for task in receiver {\n\n vfs.handle_task(task);\n\n let mut done = false;\n\n for change in vfs.commit_changes() {\n\n match change {\n\n VfsChange::AddRoot { root, files } => {\n\n let source_root_id = vfs_root_to_id(root);\n", "file_path": "crates/ra_batch/src/lib.rs", "rank": 87, "score": 214591.6356719795 }, { "content": "#[test]\n\nfn item_map_using_self() {\n\n let map = def_map(\n\n \"\n\n //- /lib.rs\n\n mod foo;\n\n use crate::foo::bar::Baz::{self};\n\n //- /foo/mod.rs\n\n pub mod bar;\n\n //- /foo/bar.rs\n\n pub struct Baz;\n\n \",\n\n );\n\n assert_snapshot!(map, @r###\"\n\n ⋮crate\n\n ⋮Baz: t v\n\n ⋮foo: t\n\n ⋮\n\n ⋮crate::foo\n\n ⋮bar: t\n\n ⋮\n\n ⋮crate::foo::bar\n\n ⋮Baz: t v\n\n \"###);\n\n}\n\n\n", "file_path": "crates/ra_hir/src/nameres/tests.rs", "rank": 88, "score": 214259.73638379524 }, { "content": "#[test]\n\nfn test_doc_comment_preserves_newlines() {\n\n let file = SourceFile::parse(\n\n r#\"\n\n /// this\n\n /// is\n\n /// mod\n\n /// foo\n\n mod foo {}\n\n \"#,\n\n )\n\n .ok()\n\n .unwrap();\n\n let module = file.syntax().descendants().find_map(Module::cast).unwrap();\n\n assert_eq!(\"this\\nis\\nmod\\nfoo\", module.doc_comment_text().unwrap());\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 89, "score": 213876.6946935982 }, { "content": "#[test]\n\nfn test_doc_comment_preserves_indents() {\n\n let file = SourceFile::parse(\n\n r#\"\n\n /// doc1\n\n /// ```\n\n /// fn foo() {\n\n /// // ...\n\n /// }\n\n /// ```\n\n mod foo {}\n\n \"#,\n\n )\n\n .ok()\n\n .unwrap();\n\n let module = file.syntax().descendants().find_map(Module::cast).unwrap();\n\n assert_eq!(\"doc1\\n```\\nfn foo() {\\n // ...\\n}\\n```\", module.doc_comment_text().unwrap());\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast.rs", "rank": 90, "score": 213876.6946935982 }, { "content": "fn gen<T>() -> *mut [T; 2] { loop {} }\n", "file_path": "crates/ra_hir/src/ty/tests/coercion.rs", "rank": 91, "score": 212819.24628190073 }, { "content": "/// Convert the syntax node to a `TokenTree` (what macro\n\n/// will consume).\n\npub fn syntax_node_to_token_tree(node: &SyntaxNode) -> Option<(tt::Subtree, TokenMap)> {\n\n let mut token_map = TokenMap::default();\n\n let tt = convert_tt(&mut token_map, node.text_range().start(), node)?;\n\n Some((tt, token_map))\n\n}\n\n\n\n// The following items are what `rustc` macro can be parsed into :\n\n// link: https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/libsyntax/ext/expand.rs#L141\n\n// * Expr(P<ast::Expr>) -> token_tree_to_expr\n\n// * Pat(P<ast::Pat>) -> token_tree_to_pat\n\n// * Ty(P<ast::Ty>) -> token_tree_to_ty\n\n// * Stmts(SmallVec<[ast::Stmt; 1]>) -> token_tree_to_stmts\n\n// * Items(SmallVec<[P<ast::Item>; 1]>) -> token_tree_to_items\n\n//\n\n// * TraitItems(SmallVec<[ast::TraitItem; 1]>)\n\n// * ImplItems(SmallVec<[ast::ImplItem; 1]>)\n\n// * ForeignItems(SmallVec<[ast::ForeignItem; 1]>\n\n\n", "file_path": "crates/ra_mbe/src/syntax_bridge.rs", "rank": 92, "score": 212198.76019990593 }, { "content": "/// Prints backtrace to stderr, useful for debugging.\n\npub fn print_backtrace() {\n\n let bt = backtrace::Backtrace::new();\n\n eprintln!(\"{:?}\", bt);\n\n}\n\n\n\nthread_local!(static IN_SCOPE: RefCell<bool> = RefCell::new(false));\n\n\n\n/// Allows to check if the current code is withing some dynamic scope, can be\n\n/// useful during debugging to figure out why a function is called.\n\npub struct Scope {\n\n prev: bool,\n\n}\n\n\n\nimpl Scope {\n\n pub fn enter() -> Scope {\n\n let prev = IN_SCOPE.with(|slot| std::mem::replace(&mut *slot.borrow_mut(), true));\n\n Scope { prev }\n\n }\n\n pub fn is_active() -> bool {\n\n IN_SCOPE.with(|slot| *slot.borrow())\n", "file_path": "crates/ra_prof/src/lib.rs", "rank": 93, "score": 211520.48892943573 }, { "content": "pub fn do() {\n\n add_one(<|>\n\n}\"#,\n\n );\n\n\n\n assert_eq!(info.parameters(), [\"x: i32\"]);\n\n assert_eq!(info.active_parameter, Some(0));\n\n assert_eq!(info.label(), \"pub fn add_one(x: i32) -> i32\");\n\n assert_eq!(\n\n info.doc().map(|it| it.into()),\n\n Some(\n\n r#\"Adds one to the number given.\n\n\n\n# Examples\n\n\n\n```\n\nlet five = 5;\n\n\n\nassert_eq!(6, my_crate::add_one(5));\n\n```\"#\n\n .to_string()\n\n )\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_fn_signature_with_docs_impl() {\n\n let info = call_info(\n\n r#\"\n", "file_path": "crates/ra_ide_api/src/call_info.rs", "rank": 94, "score": 211514.90177657257 }, { "content": "pub fn run(\n\n verbosity: Verbosity,\n\n memory_usage: bool,\n\n path: &Path,\n\n only: Option<&str>,\n\n) -> Result<()> {\n\n let db_load_time = Instant::now();\n\n let (mut host, roots) = ra_batch::load_cargo(path)?;\n\n let db = host.raw_database();\n\n println!(\"Database loaded, {} roots, {:?}\", roots.len(), db_load_time.elapsed());\n\n let analysis_time = Instant::now();\n\n let mut num_crates = 0;\n\n let mut visited_modules = HashSet::new();\n\n let mut visit_queue = Vec::new();\n\n\n\n let members = roots\n\n .into_iter()\n\n .filter_map(\n\n |(source_root_id, project_root)| {\n\n if project_root.is_member() {\n", "file_path": "crates/ra_cli/src/analysis_stats.rs", "rank": 95, "score": 211514.90177657257 }, { "content": "//! There are many AstNodes, but only a few tokens, so we hand-write them here.\n\n\n\nuse crate::{\n\n ast::AstToken,\n\n SyntaxKind::{COMMENT, WHITESPACE},\n\n SyntaxToken,\n\n};\n\n\n\n#[derive(Debug, Clone, PartialEq, Eq, Hash)]\n\npub struct Comment(SyntaxToken);\n\n\n\nimpl AstToken for Comment {\n\n fn cast(token: SyntaxToken) -> Option<Self> {\n\n if token.kind() == COMMENT {\n\n Some(Comment(token))\n\n } else {\n\n None\n\n }\n\n }\n\n fn syntax(&self) -> &SyntaxToken {\n", "file_path": "crates/ra_syntax/src/ast/tokens.rs", "rank": 96, "score": 39.64481956928746 }, { "content": " None\n\n }\n\n }\n\n}\n\n\n\npub struct CommentIter {\n\n iter: SyntaxElementChildren,\n\n}\n\n\n\nimpl Iterator for CommentIter {\n\n type Item = ast::Comment;\n\n fn next(&mut self) -> Option<ast::Comment> {\n\n self.iter.by_ref().find_map(|el| el.into_token().and_then(ast::Comment::cast))\n\n }\n\n}\n\n\n", "file_path": "crates/ra_syntax/src/ast/traits.rs", "rank": 97, "score": 34.24539334894574 }, { "content": "\n\nimpl ast::ReferenceType {\n\n pub fn is_mut(&self) -> bool {\n\n self.syntax().children_with_tokens().any(|n| n.kind() == T![mut])\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]\n\npub enum SelfParamKind {\n\n /// self\n\n Owned,\n\n /// &self\n\n Ref,\n\n /// &mut self\n\n MutRef,\n\n}\n\n\n\nimpl ast::SelfParam {\n\n pub fn self_kw_token(&self) -> SyntaxToken {\n\n self.syntax()\n", "file_path": "crates/ra_syntax/src/ast/extensions.rs", "rank": 98, "score": 32.2520495957563 } ]
Rust
alacritty/src/macos/proc.rs
djpohly/alacritty
1df7dc5171abfe1eab3e95be964f61c5876198f1
use std::ffi::{CStr, CString, IntoStringError}; use std::fmt::{self, Display, Formatter}; use std::io; use std::mem::{self, MaybeUninit}; use std::os::raw::{c_int, c_void}; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Io(io::Error), IntoString(IntoStringError), InvalidSize, } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::InvalidSize => None, Error::Io(err) => err.source(), Error::IntoString(err) => err.source(), } } } impl Display for Error { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::InvalidSize => write!(f, "Invalid proc_pidinfo return size"), Error::Io(err) => write!(f, "Error getting current working directory: {}", err), Error::IntoString(err) => { write!(f, "Error when parsing current working directory: {}", err) }, } } } impl From<io::Error> for Error { fn from(val: io::Error) -> Self { Error::Io(val) } } impl From<IntoStringError> for Error { fn from(val: IntoStringError) -> Self { Error::IntoString(val) } } pub fn cwd(pid: c_int) -> Result<PathBuf, Error> { let mut info = MaybeUninit::<sys::proc_vnodepathinfo>::uninit(); let info_ptr = info.as_mut_ptr() as *mut c_void; let size = mem::size_of::<sys::proc_vnodepathinfo>() as c_int; let c_str = unsafe { let pidinfo_size = sys::proc_pidinfo(pid, sys::PROC_PIDVNODEPATHINFO, 0, info_ptr, size); match pidinfo_size { c if c < 0 => return Err(io::Error::last_os_error().into()), s if s != size => return Err(Error::InvalidSize), _ => CStr::from_ptr(info.assume_init().pvi_cdir.vip_path.as_ptr()), } }; Ok(CString::from(c_str).into_string().map(PathBuf::from)?) } #[allow(non_camel_case_types)] mod sys { use std::os::raw::{c_char, c_int, c_longlong, c_void}; pub const PROC_PIDVNODEPATHINFO: c_int = 9; type gid_t = c_int; type off_t = c_longlong; type uid_t = c_int; type fsid_t = fsid; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fsid { pub val: [i32; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vinfo_stat { pub vst_dev: u32, pub vst_mode: u16, pub vst_nlink: u16, pub vst_ino: u64, pub vst_uid: uid_t, pub vst_gid: gid_t, pub vst_atime: i64, pub vst_atimensec: i64, pub vst_mtime: i64, pub vst_mtimensec: i64, pub vst_ctime: i64, pub vst_ctimensec: i64, pub vst_birthtime: i64, pub vst_birthtimensec: i64, pub vst_size: off_t, pub vst_blocks: i64, pub vst_blksize: i32, pub vst_flags: u32, pub vst_gen: u32, pub vst_rdev: u32, pub vst_qspare: [i64; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vnode_info { pub vi_stat: vinfo_stat, pub vi_type: c_int, pub vi_pad: c_int, pub vi_fsid: fsid_t, } #[repr(C)] #[derive(Copy, Clone)] pub struct vnode_info_path { pub vip_vi: vnode_info, pub vip_path: [c_char; 1024usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct proc_vnodepathinfo { pub pvi_cdir: vnode_info_path, pub pvi_rdir: vnode_info_path, } extern "C" { pub fn proc_pidinfo( pid: c_int, flavor: c_int, arg: u64, buffer: *mut c_void, buffersize: c_int, ) -> c_int; } } #[cfg(test)] mod tests { use super::*; use std::{env, process}; #[test] fn cwd_matches_current_dir() { assert_eq!(cwd(process::id() as i32).ok(), env::current_dir().ok()); } }
use std::ffi::{CStr, CString, IntoStringError}; use std::fmt::{self, Display, Formatter}; use std::io; use std::mem::{self, MaybeUninit}; use std::os::raw::{c_int, c_void}; use std::path::PathBuf; #[derive(Debug)] pub enum Error { Io(io::Error), IntoString(IntoStringError), InvalidSize, } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Error::InvalidSize => None, Error::Io(err) => err.source(), Error::IntoString(err) => err.source(), } } } impl Display for Error {
} impl From<io::Error> for Error { fn from(val: io::Error) -> Self { Error::Io(val) } } impl From<IntoStringError> for Error { fn from(val: IntoStringError) -> Self { Error::IntoString(val) } } pub fn cwd(pid: c_int) -> Result<PathBuf, Error> { let mut info = MaybeUninit::<sys::proc_vnodepathinfo>::uninit(); let info_ptr = info.as_mut_ptr() as *mut c_void; let size = mem::size_of::<sys::proc_vnodepathinfo>() as c_int; let c_str = unsafe { let pidinfo_size = sys::proc_pidinfo(pid, sys::PROC_PIDVNODEPATHINFO, 0, info_ptr, size); match pidinfo_size { c if c < 0 => return Err(io::Error::last_os_error().into()), s if s != size => return Err(Error::InvalidSize), _ => CStr::from_ptr(info.assume_init().pvi_cdir.vip_path.as_ptr()), } }; Ok(CString::from(c_str).into_string().map(PathBuf::from)?) } #[allow(non_camel_case_types)] mod sys { use std::os::raw::{c_char, c_int, c_longlong, c_void}; pub const PROC_PIDVNODEPATHINFO: c_int = 9; type gid_t = c_int; type off_t = c_longlong; type uid_t = c_int; type fsid_t = fsid; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct fsid { pub val: [i32; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vinfo_stat { pub vst_dev: u32, pub vst_mode: u16, pub vst_nlink: u16, pub vst_ino: u64, pub vst_uid: uid_t, pub vst_gid: gid_t, pub vst_atime: i64, pub vst_atimensec: i64, pub vst_mtime: i64, pub vst_mtimensec: i64, pub vst_ctime: i64, pub vst_ctimensec: i64, pub vst_birthtime: i64, pub vst_birthtimensec: i64, pub vst_size: off_t, pub vst_blocks: i64, pub vst_blksize: i32, pub vst_flags: u32, pub vst_gen: u32, pub vst_rdev: u32, pub vst_qspare: [i64; 2usize], } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct vnode_info { pub vi_stat: vinfo_stat, pub vi_type: c_int, pub vi_pad: c_int, pub vi_fsid: fsid_t, } #[repr(C)] #[derive(Copy, Clone)] pub struct vnode_info_path { pub vip_vi: vnode_info, pub vip_path: [c_char; 1024usize], } #[repr(C)] #[derive(Copy, Clone)] pub struct proc_vnodepathinfo { pub pvi_cdir: vnode_info_path, pub pvi_rdir: vnode_info_path, } extern "C" { pub fn proc_pidinfo( pid: c_int, flavor: c_int, arg: u64, buffer: *mut c_void, buffersize: c_int, ) -> c_int; } } #[cfg(test)] mod tests { use super::*; use std::{env, process}; #[test] fn cwd_matches_current_dir() { assert_eq!(cwd(process::id() as i32).ok(), env::current_dir().ok()); } }
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Error::InvalidSize => write!(f, "Invalid proc_pidinfo return size"), Error::Io(err) => write!(f, "Error getting current working directory: {}", err), Error::IntoString(err) => { write!(f, "Error when parsing current working directory: {}", err) }, } }
function_block-full_function
[ { "content": "pub fn create_shader(kind: GLenum, source: &'static str) -> Result<GLuint, ShaderCreationError> {\n\n let len: [GLint; 1] = [source.len() as GLint];\n\n\n\n let shader = unsafe {\n\n let shader = gl::CreateShader(kind);\n\n gl::ShaderSource(shader, 1, &(source.as_ptr() as *const _), len.as_ptr());\n\n gl::CompileShader(shader);\n\n shader\n\n };\n\n\n\n let mut success: GLint = 0;\n\n unsafe {\n\n gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut success);\n\n }\n\n\n\n if success == GLint::from(gl::TRUE) {\n\n Ok(shader)\n\n } else {\n\n // Read log.\n\n let log = get_shader_info_log(shader);\n\n\n\n // Cleanup.\n\n unsafe {\n\n gl::DeleteShader(shader);\n\n }\n\n\n\n Err(ShaderCreationError::Compile(log))\n\n }\n\n}\n\n\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 0, "score": 184281.8447168667 }, { "content": "/// Check if there is a hint highlighted at the specified point.\n\npub fn highlighted_at<T>(\n\n term: &Term<T>,\n\n config: &Config,\n\n point: Point,\n\n mouse_mods: ModifiersState,\n\n) -> Option<HintMatch> {\n\n let mouse_mode = term.mode().intersects(TermMode::MOUSE_MODE);\n\n\n\n config.ui_config.hints.enabled.iter().find_map(|hint| {\n\n // Check if all required modifiers are pressed.\n\n let highlight = hint.mouse.map_or(false, |mouse| {\n\n mouse.enabled\n\n && mouse_mods.contains(mouse.mods.0)\n\n && (!mouse_mode || mouse_mods.contains(ModifiersState::SHIFT))\n\n });\n\n if !highlight {\n\n return None;\n\n }\n\n\n\n hint.regex.with_compiled(|regex| {\n", "file_path": "alacritty/src/display/hint.rs", "rank": 1, "score": 179189.6758150817 }, { "content": "pub fn derive_deserialize(ident: Ident, data_enum: DataEnum) -> TokenStream {\n\n let visitor = format_ident!(\"{}Visitor\", ident);\n\n\n\n // Create match arm streams and get a list with all available values.\n\n let mut match_arms_stream = TokenStream2::new();\n\n let mut available_values = String::from(\"one of \");\n\n for variant in data_enum.variants.iter().filter(|variant| {\n\n // Skip deserialization for `#[config(skip)]` fields.\n\n variant.attrs.iter().all(|attr| {\n\n !crate::path_ends_with(&attr.path, \"config\") || attr.tokens.to_string() != \"(skip)\"\n\n })\n\n }) {\n\n let variant_ident = &variant.ident;\n\n let variant_str = variant_ident.to_string();\n\n available_values = format!(\"{}`{}`, \", available_values, variant_str);\n\n\n\n let literal = variant_str.to_lowercase();\n\n\n\n match_arms_stream.extend(quote! {\n\n #literal => Ok(#ident :: #variant_ident),\n", "file_path": "alacritty_config_derive/src/de_enum.rs", "rank": 3, "score": 160572.01543108496 }, { "content": "/// Convert a viewport relative point to a terminal point.\n\npub fn viewport_to_point(display_offset: usize, point: Point<usize>) -> Point {\n\n let line = Line(point.line as i32) - display_offset;\n\n Point::new(line, point.column)\n\n}\n\n\n\n/// Calculate the cell dimensions based on font metrics.\n\n///\n\n/// This will return a tuple of the cell width and height.\n", "file_path": "alacritty/src/display/mod.rs", "rank": 4, "score": 157735.44300424017 }, { "content": "/// Convert a terminal point to a viewport relative point.\n\npub fn point_to_viewport(display_offset: usize, point: Point) -> Option<Point<usize>> {\n\n let viewport_line = point.line.0 + display_offset as i32;\n\n usize::try_from(viewport_line).ok().map(|line| Point::new(line, point.column))\n\n}\n\n\n", "file_path": "alacritty/src/display/mod.rs", "rank": 5, "score": 153582.0084155915 }, { "content": "pub fn initialize(\n\n options: &Options,\n\n event_proxy: EventLoopProxy<Event>,\n\n) -> Result<Option<PathBuf>, log::SetLoggerError> {\n\n log::set_max_level(options.log_level());\n\n\n\n let logger = Logger::new(event_proxy);\n\n let path = logger.file_path();\n\n log::set_boxed_logger(Box::new(logger))?;\n\n\n\n Ok(path)\n\n}\n\n\n\npub struct Logger {\n\n logfile: Mutex<OnDemandLogFile>,\n\n stdout: Mutex<LineWriter<Stdout>>,\n\n event_proxy: Mutex<EventLoopProxy<Event>>,\n\n}\n\n\n\nimpl Logger {\n", "file_path": "alacritty/src/logging.rs", "rank": 6, "score": 145939.35302993256 }, { "content": "// Install a panic handler that renders the panic in a classical Windows error\n\n// dialog box as well as writes the panic to STDERR.\n\npub fn attach_handler() {\n\n panic::set_hook(Box::new(|panic_info| {\n\n let _ = writeln!(io::stderr(), \"{}\", panic_info);\n\n let msg = format!(\"{}\\n\\nPress Ctrl-C to Copy\", panic_info);\n\n unsafe {\n\n winuser::MessageBoxW(\n\n ptr::null_mut(),\n\n win32_string(&msg).as_ptr(),\n\n win32_string(\"Alacritty: Runtime Error\").as_ptr(),\n\n winuser::MB_ICONERROR\n\n | winuser::MB_OK\n\n | winuser::MB_SETFOREGROUND\n\n | winuser::MB_TASKMODAL,\n\n );\n\n }\n\n }));\n\n}\n", "file_path": "alacritty/src/panic.rs", "rank": 7, "score": 143601.12473606685 }, { "content": "pub fn set_locale_environment() {\n\n let env_locale_c = CString::new(\"\").unwrap();\n\n let env_locale_ptr = unsafe { setlocale(LC_ALL, env_locale_c.as_ptr()) };\n\n if !env_locale_ptr.is_null() {\n\n let env_locale = unsafe { CStr::from_ptr(env_locale_ptr).to_string_lossy() };\n\n\n\n // Assume `C` locale means unchanged, since it is the default anyways.\n\n if env_locale != \"C\" {\n\n debug!(\"Using environment locale: {}\", env_locale);\n\n return;\n\n }\n\n }\n\n\n\n let system_locale = system_locale();\n\n\n\n // Set locale to system locale.\n\n let system_locale_c = CString::new(system_locale.clone()).expect(\"nul byte in system locale\");\n\n let lc_all = unsafe { setlocale(LC_ALL, system_locale_c.as_ptr()) };\n\n\n\n // Check if system locale was valid or not.\n", "file_path": "alacritty/src/macos/locale.rs", "rank": 8, "score": 139261.6460340748 }, { "content": "pub fn create_program(vertex: GLuint, fragment: GLuint) -> Result<GLuint, ShaderCreationError> {\n\n unsafe {\n\n let program = gl::CreateProgram();\n\n gl::AttachShader(program, vertex);\n\n gl::AttachShader(program, fragment);\n\n gl::LinkProgram(program);\n\n\n\n let mut success: GLint = 0;\n\n gl::GetProgramiv(program, gl::LINK_STATUS, &mut success);\n\n\n\n if success == i32::from(gl::TRUE) {\n\n Ok(program)\n\n } else {\n\n Err(ShaderCreationError::Link(get_program_info_log(program)))\n\n }\n\n }\n\n}\n\n\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 9, "score": 134002.6901789132 }, { "content": "pub fn child_pid() -> pid_t {\n\n PID.load(Ordering::Relaxed) as pid_t\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 10, "score": 133136.977608657 }, { "content": "pub fn derive_deserialize<T>(\n\n ident: Ident,\n\n generics: Generics,\n\n fields: Punctuated<Field, T>,\n\n) -> TokenStream {\n\n // Create all necessary tokens for the implementation.\n\n let GenericsStreams { unconstrained, constrained, phantoms } =\n\n generics_streams(generics.params);\n\n let FieldStreams { flatten, match_assignments } = fields_deserializer(&fields);\n\n let visitor = format_ident!(\"{}Visitor\", ident);\n\n\n\n // Generate deserialization impl.\n\n let tokens = quote! {\n\n #[derive(Default)]\n\n #[allow(non_snake_case)]\n\n struct #visitor < #unconstrained > {\n\n #phantoms\n\n }\n\n\n\n impl<'de, #constrained> serde::de::Visitor<'de> for #visitor < #unconstrained > {\n", "file_path": "alacritty_config_derive/src/de_struct.rs", "rank": 11, "score": 131223.69752602375 }, { "content": "pub fn master_fd() -> RawFd {\n\n FD.load(Ordering::Relaxed) as RawFd\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 12, "score": 131223.69752602375 }, { "content": "/// Load the configuration file.\n\npub fn load(options: &Options) -> Config {\n\n let config_options = options.config_options.clone();\n\n let config_path = options.config_file.clone().or_else(installed_config);\n\n\n\n // Load the config using the following fallback behavior:\n\n // - Config path + CLI overrides\n\n // - CLI overrides\n\n // - Default\n\n let mut config = config_path\n\n .as_ref()\n\n .and_then(|config_path| load_from(config_path, config_options.clone()).ok())\n\n .unwrap_or_else(|| {\n\n let mut config = Config::deserialize(config_options).unwrap_or_default();\n\n match config_path {\n\n Some(config_path) => config.ui_config.config_paths.push(config_path),\n\n None => info!(target: LOG_TARGET_CONFIG, \"No config file found; using default\"),\n\n }\n\n config\n\n });\n\n\n\n after_loading(&mut config, options);\n\n\n\n config\n\n}\n\n\n", "file_path": "alacritty/src/config/mod.rs", "rank": 13, "score": 126467.24086873881 }, { "content": "#[cfg(test)]\n\npub fn platform_key_bindings() -> Vec<KeyBinding> {\n\n vec![]\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]\n\npub enum Key {\n\n Scancode(u32),\n\n Keycode(VirtualKeyCode),\n\n}\n\n\n\nimpl<'a> Deserialize<'a> for Key {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'a>,\n\n {\n\n let value = SerdeValue::deserialize(deserializer)?;\n\n match u32::deserialize(value.clone()) {\n\n Ok(scancode) => Ok(Key::Scancode(scancode)),\n\n Err(_) => {\n\n let keycode = VirtualKeyCode::deserialize(value).map_err(D::Error::custom)?;\n", "file_path": "alacritty/src/config/bindings.rs", "rank": 14, "score": 125839.32749219995 }, { "content": "pub fn default_mouse_bindings() -> Vec<MouseBinding> {\n\n bindings!(\n\n MouseBinding;\n\n MouseButton::Right; MouseAction::ExpandSelection;\n\n MouseButton::Middle, ~BindingMode::VI; Action::PasteSelection;\n\n )\n\n}\n\n\n", "file_path": "alacritty/src/config/bindings.rs", "rank": 15, "score": 125839.32749219995 }, { "content": "pub fn default_key_bindings() -> Vec<KeyBinding> {\n\n let mut bindings = bindings!(\n\n KeyBinding;\n\n Copy; Action::Copy;\n\n Copy, +BindingMode::VI; Action::ClearSelection;\n\n Paste, ~BindingMode::VI; Action::Paste;\n\n L, ModifiersState::CTRL; Action::ClearLogNotice;\n\n L, ModifiersState::CTRL, ~BindingMode::VI, ~BindingMode::SEARCH;\n\n Action::Esc(\"\\x0c\".into());\n\n Tab, ModifiersState::SHIFT, ~BindingMode::VI, ~BindingMode::SEARCH;\n\n Action::Esc(\"\\x1b[Z\".into());\n\n Back, ModifiersState::ALT, ~BindingMode::VI, ~BindingMode::SEARCH;\n\n Action::Esc(\"\\x1b\\x7f\".into());\n\n Back, ModifiersState::SHIFT, ~BindingMode::VI, ~BindingMode::SEARCH;\n\n Action::Esc(\"\\x7f\".into());\n\n Home, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollToTop;\n\n End, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollToBottom;\n\n PageUp, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollPageUp;\n\n PageDown, ModifiersState::SHIFT, ~BindingMode::ALT_SCREEN; Action::ScrollPageDown;\n\n Home, ModifiersState::SHIFT, +BindingMode::ALT_SCREEN,\n", "file_path": "alacritty/src/config/bindings.rs", "rank": 16, "score": 125839.32749219995 }, { "content": "/// Error that can happen when inserting a texture to the Atlas.\n\nenum AtlasInsertError {\n\n /// Texture atlas is full.\n\n Full,\n\n\n\n /// The glyph cannot fit within a single texture.\n\n GlyphTooLarge,\n\n}\n\n\n\nimpl Atlas {\n\n fn new(size: i32) -> Self {\n\n let mut id: GLuint = 0;\n\n unsafe {\n\n gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1);\n\n gl::GenTextures(1, &mut id);\n\n gl::BindTexture(gl::TEXTURE_2D, id);\n\n // Use RGBA texture for both normal and emoji glyphs, since it has no performance\n\n // impact.\n\n gl::TexImage2D(\n\n gl::TEXTURE_2D,\n\n 0,\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 17, "score": 119406.29726495506 }, { "content": "/// Setup environment variables.\n\npub fn setup_env<C>(config: &Config<C>) {\n\n // Default to 'alacritty' terminfo if it is available, otherwise\n\n // default to 'xterm-256color'. May be overridden by user's config\n\n // below.\n\n let terminfo = if terminfo_exists(\"alacritty\") { \"alacritty\" } else { \"xterm-256color\" };\n\n env::set_var(\"TERM\", terminfo);\n\n\n\n // Advertise 24-bit color support.\n\n env::set_var(\"COLORTERM\", \"truecolor\");\n\n\n\n // Prevent child processes from inheriting startup notification env.\n\n env::remove_var(\"DESKTOP_STARTUP_ID\");\n\n\n\n // Set env vars from config.\n\n for (key, value) in config.env.iter() {\n\n env::set_var(key, value);\n\n }\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/mod.rs", "rank": 18, "score": 118248.38873061379 }, { "content": "#[proc_macro_derive(ConfigDeserialize, attributes(config))]\n\npub fn derive_config_deserialize(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n match input.data {\n\n Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => {\n\n de_struct::derive_deserialize(input.ident, input.generics, fields.named)\n\n },\n\n Data::Enum(data_enum) => de_enum::derive_deserialize(input.ident, data_enum),\n\n _ => Error::new(input.ident.span(), UNSUPPORTED_ERROR).to_compile_error().into(),\n\n }\n\n}\n\n\n\n/// Verify that a token path ends with a specific segment.\n\npub(crate) fn path_ends_with(path: &Path, segment: &str) -> bool {\n\n let segments = path.segments.iter();\n\n segments.last().map_or(false, |s| s.ident == segment)\n\n}\n", "file_path": "alacritty_config_derive/src/lib.rs", "rank": 19, "score": 117732.22393517385 }, { "content": "/// Start the daemon and log error on failure.\n\npub fn start_daemon<I, S>(program: &str, args: I)\n\nwhere\n\n I: IntoIterator<Item = S> + Debug + Copy,\n\n S: AsRef<OsStr>,\n\n{\n\n match spawn_daemon(program, args) {\n\n Ok(_) => debug!(\"Launched {} with args {:?}\", program, args),\n\n Err(_) => warn!(\"Unable to launch {} with args {:?}\", program, args),\n\n }\n\n}\n\n\n", "file_path": "alacritty/src/daemon.rs", "rank": 20, "score": 117213.7128157496 }, { "content": "/// Format an option in the format of `parent.field=value` to a serde Value.\n\nfn option_as_value(option: &str) -> Result<Value, serde_yaml::Error> {\n\n let mut yaml_text = String::with_capacity(option.len());\n\n let mut closing_brackets = String::new();\n\n\n\n for (i, c) in option.chars().enumerate() {\n\n match c {\n\n '=' => {\n\n yaml_text.push_str(\": \");\n\n yaml_text.push_str(&option[i + 1..]);\n\n break;\n\n },\n\n '.' => {\n\n yaml_text.push_str(\": {\");\n\n closing_brackets.push('}');\n\n },\n\n _ => yaml_text.push(c),\n\n }\n\n }\n\n\n\n yaml_text += &closing_brackets;\n\n\n\n serde_yaml::from_str(&yaml_text)\n\n}\n\n\n", "file_path": "alacritty/src/cli.rs", "rank": 21, "score": 116983.15360057598 }, { "content": "/// Trait for conversion into the iterator.\n\npub trait IntoRects {\n\n /// Consume the cursor for an iterator of rects.\n\n fn rects(self, size_info: &SizeInfo, thickness: f32) -> CursorRects;\n\n}\n\n\n\nimpl IntoRects for RenderableCursor {\n\n fn rects(self, size_info: &SizeInfo, thickness: f32) -> CursorRects {\n\n let point = self.point();\n\n let x = point.column.0 as f32 * size_info.cell_width() + size_info.padding_x();\n\n let y = point.line as f32 * size_info.cell_height() + size_info.padding_y();\n\n\n\n let mut width = size_info.cell_width();\n\n let height = size_info.cell_height();\n\n\n\n let thickness = (thickness * width as f32).round().max(1.);\n\n\n\n if self.is_wide() {\n\n width *= 2.;\n\n }\n\n\n", "file_path": "alacritty/src/display/cursor.rs", "rank": 22, "score": 116660.94519052115 }, { "content": "/// Merge two serde structures.\n\n///\n\n/// This will take all values from `replacement` and use `base` whenever a value isn't present in\n\n/// `replacement`.\n\npub fn merge(base: Value, replacement: Value) -> Value {\n\n match (base, replacement) {\n\n (Value::Sequence(mut base), Value::Sequence(mut replacement)) => {\n\n base.append(&mut replacement);\n\n Value::Sequence(base)\n\n },\n\n (Value::Mapping(base), Value::Mapping(replacement)) => {\n\n Value::Mapping(merge_mapping(base, replacement))\n\n },\n\n (value, Value::Null) => value,\n\n (_, value) => value,\n\n }\n\n}\n\n\n", "file_path": "alacritty/src/config/serde_utils.rs", "rank": 23, "score": 115820.95486883579 }, { "content": "/// Calculate the size of the window given padding, terminal dimensions and cell size.\n\nfn window_size(\n\n config: &Config,\n\n dimensions: Dimensions,\n\n cell_width: f32,\n\n cell_height: f32,\n\n dpr: f64,\n\n) -> PhysicalSize<u32> {\n\n let padding = config.ui_config.window.padding(dpr);\n\n\n\n let grid_width = cell_width * dimensions.columns.0.max(MIN_COLUMNS) as f32;\n\n let grid_height = cell_height * dimensions.lines.max(MIN_SCREEN_LINES) as f32;\n\n\n\n let width = (padding.0).mul_add(2., grid_width).floor();\n\n let height = (padding.1).mul_add(2., grid_height).floor();\n\n\n\n PhysicalSize::new(width as u32, height as u32)\n\n}\n", "file_path": "alacritty/src/display/mod.rs", "rank": 24, "score": 115270.85731174206 }, { "content": "/// Attempt to reload the configuration file.\n\npub fn reload(config_path: &Path, options: &Options) -> Result<Config> {\n\n // Load config, propagating errors.\n\n let config_options = options.config_options.clone();\n\n let mut config = load_from(config_path, config_options)?;\n\n\n\n after_loading(&mut config, options);\n\n\n\n Ok(config)\n\n}\n\n\n", "file_path": "alacritty/src/config/mod.rs", "rank": 25, "score": 111978.62207379151 }, { "content": "/// Send a message to the active Alacritty socket.\n\npub fn send_message(socket: Option<PathBuf>, message: &[u8]) -> IoResult<()> {\n\n let socket = find_socket(socket)?;\n\n socket.send(message)?;\n\n Ok(())\n\n}\n\n\n\n/// Directory for the IPC socket file.\n", "file_path": "alacritty/src/ipc.rs", "rank": 26, "score": 110386.81677325792 }, { "content": "fn create_gl_window<E>(\n\n mut window: WindowBuilder,\n\n event_loop: &EventLoopWindowTarget<E>,\n\n srgb: bool,\n\n vsync: bool,\n\n dimensions: Option<PhysicalSize<u32>>,\n\n) -> Result<WindowedContext<PossiblyCurrent>> {\n\n if let Some(dimensions) = dimensions {\n\n window = window.with_inner_size(dimensions);\n\n }\n\n\n\n let windowed_context = ContextBuilder::new()\n\n .with_srgb(srgb)\n\n .with_vsync(vsync)\n\n .with_hardware_acceleration(None)\n\n .build_windowed(window, event_loop)?;\n\n\n\n // Make the context current so OpenGL operations can run.\n\n let windowed_context = unsafe { windowed_context.make_current().map_err(|(_, err)| err)? };\n\n\n", "file_path": "alacritty/src/display/window.rs", "rank": 27, "score": 108695.6696575479 }, { "content": "/// Append a single field deserializer to the stream.\n\nfn field_deserializer(field_streams: &mut FieldStreams, field: &Field) -> Result<(), Error> {\n\n let ident = field.ident.as_ref().expect(\"unreachable tuple struct\");\n\n let literal = ident.to_string();\n\n let mut literals = vec![literal.clone()];\n\n\n\n // Create default stream for deserializing fields.\n\n let mut match_assignment_stream = quote! {\n\n match serde::Deserialize::deserialize(value) {\n\n Ok(value) => config.#ident = value,\n\n Err(err) => {\n\n log::error!(target: #LOG_TARGET, \"Config error: {}: {}\", #literal, err);\n\n },\n\n }\n\n };\n\n\n\n // Iterate over all #[config(...)] attributes.\n\n for attr in field.attrs.iter().filter(|attr| crate::path_ends_with(&attr.path, \"config\")) {\n\n let parsed = match attr.parse_args::<Attr>() {\n\n Ok(parsed) => parsed,\n\n Err(_) => continue,\n", "file_path": "alacritty_config_derive/src/de_struct.rs", "rank": 28, "score": 107097.89913487292 }, { "content": "pub fn watch(mut paths: Vec<PathBuf>, event_proxy: EventLoopProxy<Event>) {\n\n // Don't monitor config if there is no path to watch.\n\n if paths.is_empty() {\n\n return;\n\n }\n\n\n\n // Canonicalize paths, keeping the base paths for symlinks.\n\n for i in 0..paths.len() {\n\n if let Ok(canonical_path) = paths[i].canonicalize() {\n\n match paths[i].symlink_metadata() {\n\n Ok(metadata) if metadata.file_type().is_symlink() => paths.push(canonical_path),\n\n _ => paths[i] = canonical_path,\n\n }\n\n }\n\n }\n\n\n\n // The Duration argument is a debouncing period.\n\n let (tx, rx) = mpsc::channel();\n\n let mut watcher = match watcher(tx, DEBOUNCE_DELAY) {\n\n Ok(watcher) => watcher,\n", "file_path": "alacritty/src/config/monitor.rs", "rank": 29, "score": 104046.90920598069 }, { "content": "/// Create an IPC socket.\n\npub fn spawn_ipc_socket(options: &Options, event_proxy: EventLoopProxy<Event>) -> Option<PathBuf> {\n\n // Create the IPC socket and export its path as env variable if necessary.\n\n let socket_path = options.socket.clone().unwrap_or_else(|| {\n\n let mut path = socket_dir();\n\n path.push(format!(\"{}-{}.sock\", socket_prefix(), process::id()));\n\n path\n\n });\n\n env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str());\n\n\n\n let socket = match UnixDatagram::bind(&socket_path) {\n\n Ok(socket) => socket,\n\n Err(err) => {\n\n warn!(\"Unable to create socket: {:?}\", err);\n\n return None;\n\n },\n\n };\n\n\n\n // Spawn a thread to listen on the IPC socket.\n\n thread::spawn_named(\"socket listener\", move || {\n\n // Accept up to 2 bytes to ensure only one byte is received.\n", "file_path": "alacritty/src/ipc.rs", "rank": 30, "score": 102701.86998693284 }, { "content": "pub fn new<C>(config: &Config<C>, size: &SizeInfo) -> Option<Pty> {\n\n let mut pty_handle = 0 as HPCON;\n\n\n\n // Passing 0 as the size parameter allows the \"system default\" buffer\n\n // size to be used. There may be small performance and memory advantages\n\n // to be gained by tuning this in the future, but it's likely a reasonable\n\n // start point.\n\n let (conout, conout_pty_handle) = miow::pipe::anonymous(0).unwrap();\n\n let (conin_pty_handle, conin) = miow::pipe::anonymous(0).unwrap();\n\n\n\n let coord =\n\n coord_from_sizeinfo(size).expect(\"Overflow when creating initial size on pseudoconsole\");\n\n\n\n // Create the Pseudo Console, using the pipes.\n\n let result = unsafe {\n\n CreatePseudoConsole(\n\n coord,\n\n conin_pty_handle.into_raw_handle(),\n\n conout_pty_handle.into_raw_handle(),\n\n 0,\n", "file_path": "alacritty_terminal/src/tty/windows/conpty.rs", "rank": 31, "score": 102280.59083959737 }, { "content": "/// Like `thread::spawn`, but with a `name` argument.\n\npub fn spawn_named<F, T, S>(name: S, f: F) -> JoinHandle<T>\n\nwhere\n\n F: FnOnce() -> T + Send + 'static,\n\n T: Send + 'static,\n\n S: Into<String>,\n\n{\n\n Builder::new().name(name.into()).spawn(f).expect(\"thread spawn works\")\n\n}\n", "file_path": "alacritty_terminal/src/thread.rs", "rank": 32, "score": 102077.28761667362 }, { "content": "/// Converts the string slice into a Windows-standard representation for \"W\"-\n\n/// suffixed function variants, which accept UTF-16 encoded string values.\n\npub fn win32_string<S: AsRef<OsStr> + ?Sized>(value: &S) -> Vec<u16> {\n\n OsStr::new(value).encode_wide().chain(once(0)).collect()\n\n}\n", "file_path": "alacritty_terminal/src/tty/windows/mod.rs", "rank": 33, "score": 100935.55162054952 }, { "content": "/// Result of fallible operations concerning a Window.\n\ntype Result<T> = std::result::Result<T, Error>;\n\n\n\nimpl std::error::Error for Error {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n Error::ContextCreation(err) => err.source(),\n\n Error::Context(err) => err.source(),\n\n Error::Font(err) => err.source(),\n\n }\n\n }\n\n}\n\n\n\nimpl Display for Error {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Error::ContextCreation(err) => write!(f, \"Error creating GL context; {}\", err),\n\n Error::Context(err) => write!(f, \"Error operating on render context; {}\", err),\n\n Error::Font(err) => err.fmt(f),\n\n }\n\n }\n", "file_path": "alacritty/src/display/window.rs", "rank": 34, "score": 99326.25023463588 }, { "content": "/// Create a new TTY and return a handle to interact with it.\n\npub fn new<C>(config: &Config<C>, size: &SizeInfo, window_id: Option<usize>) -> Pty {\n\n let (master, slave) = make_pty(size.to_winsize());\n\n\n\n #[cfg(any(target_os = \"linux\", target_os = \"macos\"))]\n\n if let Ok(mut termios) = termios::tcgetattr(master) {\n\n // Set character encoding to UTF-8.\n\n termios.input_flags.set(InputFlags::IUTF8, true);\n\n let _ = termios::tcsetattr(master, SetArg::TCSANOW, &termios);\n\n }\n\n\n\n let mut buf = [0; 1024];\n\n let pw = get_pw_entry(&mut buf);\n\n\n\n let shell = match config.shell.as_ref() {\n\n Some(shell) => Cow::Borrowed(shell),\n\n None => Cow::Owned(default_shell(&pw)),\n\n };\n\n\n\n let mut builder = Command::new(shell.program());\n\n for arg in shell.args() {\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 35, "score": 96575.18494104559 }, { "content": "pub fn new<C>(config: &Config<C>, size: &SizeInfo, _window_id: Option<usize>) -> Pty {\n\n conpty::new(config, size).expect(\"Failed to create ConPTY backend\")\n\n}\n\n\n\nimpl Pty {\n\n fn new(\n\n backend: impl Into<Backend>,\n\n conout: impl Into<ReadPipe>,\n\n conin: impl Into<WritePipe>,\n\n child_watcher: ChildExitWatcher,\n\n ) -> Self {\n\n Self {\n\n backend: backend.into(),\n\n conout: conout.into(),\n\n conin: conin.into(),\n\n read_token: 0.into(),\n\n write_token: 0.into(),\n\n child_event_token: 0.into(),\n\n child_watcher,\n\n }\n", "file_path": "alacritty_terminal/src/tty/windows/mod.rs", "rank": 36, "score": 95332.5444260589 }, { "content": "#[inline]\n\nfn compute_cell_size(config: &Config, metrics: &crossfont::Metrics) -> (f32, f32) {\n\n let offset_x = f64::from(config.ui_config.font.offset.x);\n\n let offset_y = f64::from(config.ui_config.font.offset.y);\n\n (\n\n (metrics.average_advance + offset_x).floor().max(1.) as f32,\n\n (metrics.line_height + offset_y).floor().max(1.) as f32,\n\n )\n\n}\n\n\n", "file_path": "alacritty/src/display/mod.rs", "rank": 37, "score": 89478.33486081386 }, { "content": "#[cfg(all(feature = \"x11\", not(any(target_os = \"macos\", windows))))]\n\nfn x_embed_window(window: &GlutinWindow, parent_id: std::os::raw::c_ulong) {\n\n let (xlib_display, xlib_window) = match (window.xlib_display(), window.xlib_window()) {\n\n (Some(display), Some(window)) => (display, window),\n\n _ => return,\n\n };\n\n\n\n let xlib = Xlib::open().expect(\"get xlib\");\n\n\n\n unsafe {\n\n let atom = (xlib.XInternAtom)(xlib_display as *mut _, \"_XEMBED\".as_ptr() as *const _, 0);\n\n (xlib.XChangeProperty)(\n\n xlib_display as _,\n\n xlib_window as _,\n\n atom,\n\n atom,\n\n 32,\n\n PropModeReplace,\n\n [0, 1].as_ptr(),\n\n 2,\n\n );\n", "file_path": "alacritty/src/display/window.rs", "rank": 38, "score": 87963.22271632838 }, { "content": "#[derive(ConfigDeserialize, Debug, PartialEq, Eq)]\n\nenum TestEnum {\n\n One,\n\n Two,\n\n Three,\n\n #[config(skip)]\n\n Nine(String),\n\n}\n\n\n\nimpl Default for TestEnum {\n\n fn default() -> Self {\n\n Self::Nine(String::from(\"nine\"))\n\n }\n\n}\n\n\n", "file_path": "alacritty_config_derive/tests/config.rs", "rank": 39, "score": 87713.12317981417 }, { "content": "/// Create an iterator yielding a single beam rect.\n\nfn beam(x: f32, y: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects {\n\n RenderRect::new(x, y, thickness, height, color, 1.).into()\n\n}\n\n\n", "file_path": "alacritty/src/display/cursor.rs", "rank": 40, "score": 84766.90778273347 }, { "content": "fn cubic_bezier(p0: f64, p1: f64, p2: f64, p3: f64, x: f64) -> f64 {\n\n (1.0 - x).powi(3) * p0\n\n + 3.0 * (1.0 - x).powi(2) * x * p1\n\n + 3.0 * (1.0 - x) * x.powi(2) * p2\n\n + x.powi(3) * p3\n\n}\n", "file_path": "alacritty/src/display/bell.rs", "rank": 41, "score": 83314.89058805238 }, { "content": "/// Create an iterator yielding a rect for each side of the hollow block cursor.\n\nfn hollow(x: f32, y: f32, width: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects {\n\n let top_line = RenderRect::new(x, y, width, thickness, color, 1.);\n\n\n\n let vertical_y = y + thickness;\n\n let vertical_height = height - 2. * thickness;\n\n let left_line = RenderRect::new(x, vertical_y, thickness, vertical_height, color, 1.);\n\n\n\n let bottom_y = y + height - thickness;\n\n let bottom_line = RenderRect::new(x, bottom_y, width, thickness, color, 1.);\n\n\n\n let right_x = x + width - thickness;\n\n let right_line = RenderRect::new(right_x, vertical_y, thickness, vertical_height, color, 1.);\n\n\n\n CursorRects {\n\n rects: [Some(top_line), Some(bottom_line), Some(left_line), Some(right_line)],\n\n index: 0,\n\n }\n\n}\n", "file_path": "alacritty/src/display/cursor.rs", "rank": 42, "score": 80710.42458297533 }, { "content": "/// Create an iterator yielding a single underline rect.\n\nfn underline(x: f32, y: f32, width: f32, height: f32, thickness: f32, color: Rgb) -> CursorRects {\n\n let y = y + height - thickness;\n\n RenderRect::new(x, y, width, thickness, color, 1.).into()\n\n}\n\n\n", "file_path": "alacritty/src/display/cursor.rs", "rank": 43, "score": 80710.42458297533 }, { "content": "#[derive(Debug)]\n\nenum Dcs {\n\n /// Begin of the synchronized update.\n\n SyncStart,\n\n\n\n /// End of the synchronized update.\n\n SyncEnd,\n\n}\n\n\n\n/// The processor wraps a `vte::Parser` to ultimately call methods on a Handler.\n\n#[derive(Default)]\n\npub struct Processor {\n\n state: ProcessorState,\n\n parser: vte::Parser,\n\n}\n\n\n\nimpl Processor {\n\n #[inline]\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n", "file_path": "alacritty_terminal/src/ansi.rs", "rank": 44, "score": 79088.04777193445 }, { "content": "fn main() {\n\n let mut version = String::from(env!(\"CARGO_PKG_VERSION\"));\n\n if let Some(commit_hash) = commit_hash() {\n\n version = format!(\"{} ({})\", version, commit_hash);\n\n }\n\n println!(\"cargo:rustc-env=VERSION={}\", version);\n\n\n\n let dest = env::var(\"OUT_DIR\").unwrap();\n\n let mut file = File::create(&Path::new(&dest).join(\"gl_bindings.rs\")).unwrap();\n\n\n\n Registry::new(Api::Gl, (3, 3), Profile::Core, Fallbacks::All, [\"GL_ARB_blend_func_extended\"])\n\n .write_bindings(GlobalGenerator, &mut file)\n\n .unwrap();\n\n\n\n #[cfg(windows)]\n\n embed_resource::compile(\"./windows/windows.rc\");\n\n}\n\n\n", "file_path": "alacritty/build.rs", "rank": 45, "score": 75936.67758810247 }, { "content": "fn main() {\n\n #[cfg(windows)]\n\n panic::attach_handler();\n\n\n\n // When linked with the windows subsystem windows won't automatically attach\n\n // to the console of the parent process, so we do it explicitly. This fails\n\n // silently if the parent has no console.\n\n #[cfg(windows)]\n\n unsafe {\n\n AttachConsole(ATTACH_PARENT_PROCESS);\n\n }\n\n\n\n // Load command line options.\n\n let options = Options::new();\n\n\n\n #[cfg(unix)]\n\n let result = match options.subcommands {\n\n Some(Subcommands::Msg(options)) => msg(options),\n\n None => alacritty(options),\n\n };\n", "file_path": "alacritty/src/main.rs", "rank": 46, "score": 74634.69528833122 }, { "content": "/// Type that handles actions from the parser.\n\n///\n\n/// XXX Should probably not provide default impls for everything, but it makes\n\n/// writing specific handler impls for tests far easier.\n\npub trait Handler {\n\n /// OSC to set window title.\n\n fn set_title(&mut self, _: Option<String>) {}\n\n\n\n /// Set the cursor style.\n\n fn set_cursor_style(&mut self, _: Option<CursorStyle>) {}\n\n\n\n /// Set the cursor shape.\n\n fn set_cursor_shape(&mut self, _shape: CursorShape) {}\n\n\n\n /// A character to be displayed.\n\n fn input(&mut self, _c: char) {}\n\n\n\n /// Set cursor to position.\n\n fn goto(&mut self, _: Line, _: Column) {}\n\n\n\n /// Set cursor to specific row.\n\n fn goto_line(&mut self, _: Line) {}\n\n\n\n /// Set cursor to specific column.\n", "file_path": "alacritty_terminal/src/ansi.rs", "rank": 47, "score": 73631.75328837038 }, { "content": "/// Types that are interested in when the display is resized.\n\npub trait OnResize {\n\n fn on_resize(&mut self, size: &SizeInfo);\n\n}\n\n\n", "file_path": "alacritty_terminal/src/event.rs", "rank": 48, "score": 73631.45900509847 }, { "content": "/// Byte sequences are sent to a `Notify` in response to some events.\n\npub trait Notify {\n\n /// Notify that an escape sequence should be written to the PTY.\n\n ///\n\n /// TODO this needs to be able to error somehow.\n\n fn notify<B: Into<Cow<'static, [u8]>>>(&self, _: B);\n\n}\n\n\n", "file_path": "alacritty_terminal/src/event.rs", "rank": 49, "score": 73626.2519130794 }, { "content": "/// `LoadGlyph` allows for copying a rasterized glyph into graphics memory.\n\npub trait LoadGlyph {\n\n /// Load the rasterized glyph into GPU memory.\n\n fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph;\n\n\n\n /// Clear any state accumulated from previous loaded glyphs.\n\n ///\n\n /// This can, for instance, be used to reset the texture Atlas.\n\n fn clear(&mut self);\n\n}\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n ShaderCreation(ShaderCreationError),\n\n}\n\n\n\nimpl std::error::Error for Error {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n Error::ShaderCreation(err) => err.source(),\n\n }\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 50, "score": 72510.42624612844 }, { "content": "/// Event Loop for notifying the renderer about terminal events.\n\npub trait EventListener {\n\n fn send_event(&self, _event: Event) {}\n\n}\n\n\n\n/// Placeholder implementation for tests.\n\n#[cfg(test)]\n\nimpl EventListener for () {}\n", "file_path": "alacritty_terminal/src/event.rs", "rank": 51, "score": 72510.42624612844 }, { "content": "/// Types that can produce a `libc::winsize`.\n\npub trait ToWinsize {\n\n /// Get a `libc::winsize`.\n\n fn to_winsize(&self) -> winsize;\n\n}\n\n\n\nimpl<'a> ToWinsize for &'a SizeInfo {\n\n fn to_winsize(&self) -> winsize {\n\n winsize {\n\n ws_row: self.screen_lines() as libc::c_ushort,\n\n ws_col: self.columns() as libc::c_ushort,\n\n ws_xpixel: self.width() as libc::c_ushort,\n\n ws_ypixel: self.height() as libc::c_ushort,\n\n }\n\n }\n\n}\n\n\n\nunsafe fn set_nonblocking(fd: c_int) {\n\n use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};\n\n\n\n let res = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);\n\n assert_eq!(res, 0);\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 52, "score": 72510.42624612844 }, { "content": "/// Grid dimensions.\n\npub trait Dimensions {\n\n /// Total number of lines in the buffer, this includes scrollback and visible lines.\n\n fn total_lines(&self) -> usize;\n\n\n\n /// Height of the viewport in lines.\n\n fn screen_lines(&self) -> usize;\n\n\n\n /// Width of the terminal in columns.\n\n fn columns(&self) -> usize;\n\n\n\n /// Index for the last column.\n\n #[inline]\n\n fn last_column(&self) -> Column {\n\n Column(self.columns() - 1)\n\n }\n\n\n\n /// Line farthest up in the grid history.\n\n #[inline]\n\n fn topmost_line(&self) -> Line {\n\n Line(-(self.history_size() as i32))\n", "file_path": "alacritty_terminal/src/grid/mod.rs", "rank": 53, "score": 72510.42624612844 }, { "content": "#[test]\n\nfn scroll_down() {\n\n let mut grid = Grid::<usize>::new(10, 1, 0);\n\n for i in 0..10 {\n\n grid[Line(i as i32)][Column(0)] = i;\n\n }\n\n\n\n grid.scroll_down::<usize>(&(Line(0)..Line(10)), 2);\n\n\n\n assert_eq!(grid[Line(0)][Column(0)], 0); // was 8.\n\n assert_eq!(grid[Line(0)].occ, 0);\n\n assert_eq!(grid[Line(1)][Column(0)], 0); // was 9.\n\n assert_eq!(grid[Line(1)].occ, 0);\n\n assert_eq!(grid[Line(2)][Column(0)], 0);\n\n assert_eq!(grid[Line(2)].occ, 1);\n\n assert_eq!(grid[Line(3)][Column(0)], 1);\n\n assert_eq!(grid[Line(3)].occ, 1);\n\n assert_eq!(grid[Line(4)][Column(0)], 2);\n\n assert_eq!(grid[Line(4)].occ, 1);\n\n assert_eq!(grid[Line(5)][Column(0)], 3);\n\n assert_eq!(grid[Line(5)].occ, 1);\n\n assert_eq!(grid[Line(6)][Column(0)], 4);\n\n assert_eq!(grid[Line(6)].occ, 1);\n\n assert_eq!(grid[Line(7)][Column(0)], 5);\n\n assert_eq!(grid[Line(7)].occ, 1);\n\n assert_eq!(grid[Line(8)][Column(0)], 6);\n\n assert_eq!(grid[Line(8)].occ, 1);\n\n assert_eq!(grid[Line(9)][Column(0)], 7);\n\n assert_eq!(grid[Line(9)].occ, 1);\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 54, "score": 72236.1640343003 }, { "content": "#[inline]\n\nfn load_glyph(\n\n active_tex: &mut GLuint,\n\n atlas: &mut Vec<Atlas>,\n\n current_atlas: &mut usize,\n\n rasterized: &RasterizedGlyph,\n\n) -> Glyph {\n\n // At least one atlas is guaranteed to be in the `self.atlas` list; thus\n\n // the unwrap.\n\n match atlas[*current_atlas].insert(rasterized, active_tex) {\n\n Ok(glyph) => glyph,\n\n Err(AtlasInsertError::Full) => {\n\n *current_atlas += 1;\n\n if *current_atlas == atlas.len() {\n\n let new = Atlas::new(ATLAS_SIZE);\n\n *active_tex = 0; // Atlas::new binds a texture. Ugh this is sloppy.\n\n atlas.push(new);\n\n }\n\n load_glyph(active_tex, atlas, current_atlas, rasterized)\n\n },\n\n Err(AtlasInsertError::GlyphTooLarge) => Glyph {\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 55, "score": 72236.1640343003 }, { "content": "/// Deserialize all configuration files as generic Value.\n\nfn parse_config(\n\n path: &Path,\n\n config_paths: &mut Vec<PathBuf>,\n\n recursion_limit: usize,\n\n) -> Result<Value> {\n\n config_paths.push(path.to_owned());\n\n\n\n let mut contents = fs::read_to_string(path)?;\n\n\n\n // Remove UTF-8 BOM.\n\n if contents.starts_with('\\u{FEFF}') {\n\n contents = contents.split_off(3);\n\n }\n\n\n\n // Load configuration file as Value.\n\n let config: Value = match serde_yaml::from_str(&contents) {\n\n Ok(config) => config,\n\n Err(error) => {\n\n // Prevent parsing error with an empty string and commented out file.\n\n if error.to_string() == \"EOF while parsing a value\" {\n", "file_path": "alacritty/src/config/mod.rs", "rank": 56, "score": 72236.1640343003 }, { "content": "#[test]\n\nfn scroll_up() {\n\n let mut grid = Grid::<usize>::new(10, 1, 0);\n\n for i in 0..10 {\n\n grid[Line(i as i32)][Column(0)] = i;\n\n }\n\n\n\n grid.scroll_up::<usize>(&(Line(0)..Line(10)), 2);\n\n\n\n assert_eq!(grid[Line(0)][Column(0)], 2);\n\n assert_eq!(grid[Line(0)].occ, 1);\n\n assert_eq!(grid[Line(1)][Column(0)], 3);\n\n assert_eq!(grid[Line(1)].occ, 1);\n\n assert_eq!(grid[Line(2)][Column(0)], 4);\n\n assert_eq!(grid[Line(2)].occ, 1);\n\n assert_eq!(grid[Line(3)][Column(0)], 5);\n\n assert_eq!(grid[Line(3)].occ, 1);\n\n assert_eq!(grid[Line(4)][Column(0)], 6);\n\n assert_eq!(grid[Line(4)].occ, 1);\n\n assert_eq!(grid[Line(5)][Column(0)], 7);\n\n assert_eq!(grid[Line(5)].occ, 1);\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 57, "score": 72236.1640343003 }, { "content": "/// Get the length of occupied cells in a line.\n\npub trait LineLength {\n\n /// Calculate the occupied line length.\n\n fn line_length(&self) -> Column;\n\n}\n\n\n\nimpl LineLength for grid::Row<Cell> {\n\n fn line_length(&self) -> Column {\n\n let mut length = Column(0);\n\n\n\n if self[Column(self.len() - 1)].flags.contains(Flags::WRAPLINE) {\n\n return Column(self.len());\n\n }\n\n\n\n for (index, cell) in self[..].iter().rev().enumerate() {\n\n if cell.c != ' '\n\n || cell.extra.as_ref().map(|extra| extra.zerowidth.is_empty()) == Some(false)\n\n {\n\n length = Column(self.len() - index);\n\n break;\n\n }\n", "file_path": "alacritty_terminal/src/term/cell.rs", "rank": 58, "score": 71450.35504267132 }, { "content": "#[test]\n\nfn shrink_reflow() {\n\n let mut grid = Grid::<Cell>::new(1, 5, 2);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = cell('2');\n\n grid[Line(0)][Column(2)] = cell('3');\n\n grid[Line(0)][Column(3)] = cell('4');\n\n grid[Line(0)][Column(4)] = cell('5');\n\n\n\n grid.resize(true, 1, 2);\n\n\n\n assert_eq!(grid.total_lines(), 3);\n\n\n\n assert_eq!(grid[Line(-2)].len(), 2);\n\n assert_eq!(grid[Line(-2)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(-2)][Column(1)], wrap_cell('2'));\n\n\n\n assert_eq!(grid[Line(-1)].len(), 2);\n\n assert_eq!(grid[Line(-1)][Column(0)], cell('3'));\n\n assert_eq!(grid[Line(-1)][Column(1)], wrap_cell('4'));\n\n\n\n assert_eq!(grid[Line(0)].len(), 2);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('5'));\n\n assert_eq!(grid[Line(0)][Column(1)], Cell::default());\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 59, "score": 71129.08716751079 }, { "content": "#[test]\n\nfn config_deserialize() {\n\n let logger = unsafe {\n\n LOGGER = Some(Logger::default());\n\n LOGGER.as_mut().unwrap()\n\n };\n\n\n\n log::set_logger(logger).unwrap();\n\n log::set_max_level(log::LevelFilter::Warn);\n\n\n\n let test: Test = serde_yaml::from_str(\n\n r#\"\n\n field1: 3\n\n field3: 32\n\n nesting:\n\n field1: \"testing\"\n\n field2: None\n\n field3: 99\n\n aliased: 8\n\n flatty: 123\n\n enom_small: \"one\"\n", "file_path": "alacritty_config_derive/tests/config.rs", "rank": 60, "score": 71129.08716751079 }, { "content": "#[test]\n\nfn test_iter() {\n\n let assert_indexed = |value: usize, indexed: Option<Indexed<&usize>>| {\n\n assert_eq!(Some(&value), indexed.map(|indexed| indexed.cell));\n\n };\n\n\n\n let mut grid = Grid::<usize>::new(5, 5, 0);\n\n for i in 0..5 {\n\n for j in 0..5 {\n\n grid[Line(i)][Column(j)] = i as usize * 5 + j;\n\n }\n\n }\n\n\n\n let mut iter = grid.iter_from(Point::new(Line(0), Column(0)));\n\n\n\n assert_eq!(None, iter.prev());\n\n assert_indexed(1, iter.next());\n\n assert_eq!(Column(1), iter.point().column);\n\n assert_eq!(0, iter.point().line);\n\n\n\n assert_indexed(2, iter.next());\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 61, "score": 71129.08716751079 }, { "content": "#[test]\n\nfn scroll_down_with_history() {\n\n let mut grid = Grid::<usize>::new(10, 1, 1);\n\n grid.increase_scroll_limit(1);\n\n for i in 0..10 {\n\n grid[Line(i as i32)][Column(0)] = i;\n\n }\n\n\n\n grid.scroll_down::<usize>(&(Line(0)..Line(10)), 2);\n\n\n\n assert_eq!(grid[Line(0)][Column(0)], 0); // was 8.\n\n assert_eq!(grid[Line(0)].occ, 0);\n\n assert_eq!(grid[Line(1)][Column(0)], 0); // was 9.\n\n assert_eq!(grid[Line(1)].occ, 0);\n\n assert_eq!(grid[Line(2)][Column(0)], 0);\n\n assert_eq!(grid[Line(2)].occ, 1);\n\n assert_eq!(grid[Line(3)][Column(0)], 1);\n\n assert_eq!(grid[Line(3)].occ, 1);\n\n assert_eq!(grid[Line(4)][Column(0)], 2);\n\n assert_eq!(grid[Line(4)].occ, 1);\n\n assert_eq!(grid[Line(5)][Column(0)], 3);\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 62, "score": 71129.08716751079 }, { "content": "#[test]\n\nfn grow_reflow() {\n\n let mut grid = Grid::<Cell>::new(2, 2, 0);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = wrap_cell('2');\n\n grid[Line(1)][Column(0)] = cell('3');\n\n grid[Line(1)][Column(1)] = Cell::default();\n\n\n\n grid.resize(true, 2, 3);\n\n\n\n assert_eq!(grid.total_lines(), 2);\n\n\n\n assert_eq!(grid[Line(0)].len(), 3);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(0)][Column(1)], cell('2'));\n\n assert_eq!(grid[Line(0)][Column(2)], cell('3'));\n\n\n\n // Make sure rest of grid is empty.\n\n assert_eq!(grid[Line(1)].len(), 3);\n\n assert_eq!(grid[Line(1)][Column(0)], Cell::default());\n\n assert_eq!(grid[Line(1)][Column(1)], Cell::default());\n\n assert_eq!(grid[Line(1)][Column(2)], Cell::default());\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 63, "score": 71129.08716751079 }, { "content": "/// This trait defines the behaviour needed to read and/or write to a stream.\n\n/// It defines an abstraction over mio's interface in order to allow either one\n\n/// read/write object or a separate read and write object.\n\npub trait EventedReadWrite {\n\n type Reader: io::Read;\n\n type Writer: io::Write;\n\n\n\n fn register(\n\n &mut self,\n\n _: &mio::Poll,\n\n _: &mut dyn Iterator<Item = mio::Token>,\n\n _: mio::Ready,\n\n _: mio::PollOpt,\n\n ) -> io::Result<()>;\n\n fn reregister(&mut self, _: &mio::Poll, _: mio::Ready, _: mio::PollOpt) -> io::Result<()>;\n\n fn deregister(&mut self, _: &mio::Poll) -> io::Result<()>;\n\n\n\n fn reader(&mut self) -> &mut Self::Reader;\n\n fn read_token(&self) -> mio::Token;\n\n fn writer(&mut self) -> &mut Self::Writer;\n\n fn write_token(&self) -> mio::Token;\n\n}\n\n\n\n/// Events concerning TTY child processes.\n\n#[derive(Debug, PartialEq)]\n\npub enum ChildEvent {\n\n /// Indicates the child has exited.\n\n Exited,\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/mod.rs", "rank": 64, "score": 70441.96133455088 }, { "content": "#[test]\n\nfn shrink_reflow_disabled() {\n\n let mut grid = Grid::<Cell>::new(1, 5, 2);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = cell('2');\n\n grid[Line(0)][Column(2)] = cell('3');\n\n grid[Line(0)][Column(3)] = cell('4');\n\n grid[Line(0)][Column(4)] = cell('5');\n\n\n\n grid.resize(false, 1, 2);\n\n\n\n assert_eq!(grid.total_lines(), 1);\n\n\n\n assert_eq!(grid[Line(0)].len(), 2);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(0)][Column(1)], cell('2'));\n\n}\n\n\n\n// https://github.com/rust-lang/rust-clippy/pull/6375\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 65, "score": 70077.3276128987 }, { "content": "#[test]\n\nfn grow_reflow_disabled() {\n\n let mut grid = Grid::<Cell>::new(2, 2, 0);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = wrap_cell('2');\n\n grid[Line(1)][Column(0)] = cell('3');\n\n grid[Line(1)][Column(1)] = Cell::default();\n\n\n\n grid.resize(false, 2, 3);\n\n\n\n assert_eq!(grid.total_lines(), 2);\n\n\n\n assert_eq!(grid[Line(0)].len(), 3);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(0)][Column(1)], wrap_cell('2'));\n\n assert_eq!(grid[Line(0)][Column(2)], Cell::default());\n\n\n\n assert_eq!(grid[Line(1)].len(), 3);\n\n assert_eq!(grid[Line(1)][Column(0)], cell('3'));\n\n assert_eq!(grid[Line(1)][Column(1)], Cell::default());\n\n assert_eq!(grid[Line(1)][Column(2)], Cell::default());\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 66, "score": 70077.3276128987 }, { "content": "#[test]\n\nfn shrink_reflow_twice() {\n\n let mut grid = Grid::<Cell>::new(1, 5, 2);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = cell('2');\n\n grid[Line(0)][Column(2)] = cell('3');\n\n grid[Line(0)][Column(3)] = cell('4');\n\n grid[Line(0)][Column(4)] = cell('5');\n\n\n\n grid.resize(true, 1, 4);\n\n grid.resize(true, 1, 2);\n\n\n\n assert_eq!(grid.total_lines(), 3);\n\n\n\n assert_eq!(grid[Line(-2)].len(), 2);\n\n assert_eq!(grid[Line(-2)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(-2)][Column(1)], wrap_cell('2'));\n\n\n\n assert_eq!(grid[Line(-1)].len(), 2);\n\n assert_eq!(grid[Line(-1)][Column(0)], cell('3'));\n\n assert_eq!(grid[Line(-1)][Column(1)], wrap_cell('4'));\n\n\n\n assert_eq!(grid[Line(0)].len(), 2);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('5'));\n\n assert_eq!(grid[Line(0)][Column(1)], Cell::default());\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 67, "score": 70077.3276128987 }, { "content": "#[test]\n\nfn grow_reflow_multiline() {\n\n let mut grid = Grid::<Cell>::new(3, 2, 0);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = wrap_cell('2');\n\n grid[Line(1)][Column(0)] = cell('3');\n\n grid[Line(1)][Column(1)] = wrap_cell('4');\n\n grid[Line(2)][Column(0)] = cell('5');\n\n grid[Line(2)][Column(1)] = cell('6');\n\n\n\n grid.resize(true, 3, 6);\n\n\n\n assert_eq!(grid.total_lines(), 3);\n\n\n\n assert_eq!(grid[Line(0)].len(), 6);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(0)][Column(1)], cell('2'));\n\n assert_eq!(grid[Line(0)][Column(2)], cell('3'));\n\n assert_eq!(grid[Line(0)][Column(3)], cell('4'));\n\n assert_eq!(grid[Line(0)][Column(4)], cell('5'));\n\n assert_eq!(grid[Line(0)][Column(5)], cell('6'));\n\n\n\n // Make sure rest of grid is empty.\n\n for r in (1..3).map(Line::from) {\n\n assert_eq!(grid[r].len(), 6);\n\n for c in 0..6 {\n\n assert_eq!(grid[r][Column(c)], Cell::default());\n\n }\n\n }\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 68, "score": 70077.3276128987 }, { "content": "#[cfg(target_os = \"macos\")]\n\nfn socket_prefix() -> String {\n\n String::from(\"Alacritty\")\n\n}\n", "file_path": "alacritty/src/ipc.rs", "rank": 69, "score": 69970.12741280509 }, { "content": "// Panic with the last os error as message.\n\nfn panic_shell_spawn() {\n\n panic!(\"Unable to spawn shell: {}\", Error::last_os_error());\n\n}\n\n\n\nimpl OnResize for Conpty {\n\n fn on_resize(&mut self, sizeinfo: &SizeInfo) {\n\n if let Some(coord) = coord_from_sizeinfo(sizeinfo) {\n\n let result = unsafe { ResizePseudoConsole(self.handle, coord) };\n\n assert_eq!(result, S_OK);\n\n }\n\n }\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/windows/conpty.rs", "rank": 70, "score": 69081.99955995326 }, { "content": "#[test]\n\nfn test_get_pw_entry() {\n\n let mut buf: [i8; 1024] = [0; 1024];\n\n let _pw = get_pw_entry(&mut buf);\n\n}\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 71, "score": 69076.84036839326 }, { "content": "/// Determine system locale based on language and country code.\n\nfn system_locale() -> String {\n\n unsafe {\n\n let locale_class = Class::get(\"NSLocale\").unwrap();\n\n let locale: *const Object = msg_send![locale_class, currentLocale];\n\n let _: () = msg_send![locale_class, release];\n\n\n\n // `localeIdentifier` returns extra metadata with the locale (including currency and\n\n // collator) on newer versions of macOS. This is not a valid locale, so we use\n\n // `languageCode` and `countryCode`, if they're available (macOS 10.12+):\n\n //\n\n // https://developer.apple.com/documentation/foundation/nslocale/1416263-localeidentifier?language=objc\n\n // https://developer.apple.com/documentation/foundation/nslocale/1643060-countrycode?language=objc\n\n // https://developer.apple.com/documentation/foundation/nslocale/1643026-languagecode?language=objc\n\n let is_language_code_supported: bool =\n\n msg_send![locale, respondsToSelector: sel!(languageCode)];\n\n let is_country_code_supported: bool =\n\n msg_send![locale, respondsToSelector: sel!(countryCode)];\n\n let locale_id = if is_language_code_supported && is_country_code_supported {\n\n let language_code: *const Object = msg_send![locale, languageCode];\n\n let language_code_str = nsstring_as_str(language_code).to_owned();\n", "file_path": "alacritty/src/macos/locale.rs", "rank": 72, "score": 68863.05054601558 }, { "content": "#[cfg(target_os = \"macos\")]\n\nfn socket_dir() -> PathBuf {\n\n env::temp_dir()\n\n}\n\n\n", "file_path": "alacritty/src/ipc.rs", "rank": 73, "score": 68863.05054601558 }, { "content": "pub trait GridCell: Sized {\n\n /// Check if the cell contains any content.\n\n fn is_empty(&self) -> bool;\n\n\n\n /// Perform an opinionated cell reset based on a template cell.\n\n fn reset(&mut self, template: &Self);\n\n\n\n fn flags(&self) -> &Flags;\n\n fn flags_mut(&mut self) -> &mut Flags;\n\n}\n\n\n\n#[derive(Debug, Default, Clone, PartialEq, Eq)]\n\npub struct Cursor<T> {\n\n /// The location of this cursor.\n\n pub point: Point,\n\n\n\n /// Template cell when using this cursor.\n\n pub template: T,\n\n\n\n /// Currently configured graphic character sets.\n", "file_path": "alacritty_terminal/src/grid/mod.rs", "rank": 74, "score": 68264.0685681196 }, { "content": "/// Trait for determining if a reset should be performed.\n\npub trait ResetDiscriminant<T> {\n\n /// Value based on which equality for the reset will be determined.\n\n fn discriminant(&self) -> T;\n\n}\n\n\n\nimpl<T: Copy> ResetDiscriminant<T> for T {\n\n fn discriminant(&self) -> T {\n\n *self\n\n }\n\n}\n\n\n\nimpl ResetDiscriminant<Color> for Cell {\n\n fn discriminant(&self) -> Color {\n\n self.bg\n\n }\n\n}\n\n\n\n/// Dynamically allocated cell content.\n\n///\n\n/// This storage is reserved for cell attributes which are rarely set. This allows reducing the\n\n/// allocation required ahead of time for every cell, with some additional overhead when the extra\n\n/// storage is actually required.\n", "file_path": "alacritty_terminal/src/term/cell.rs", "rank": 75, "score": 68264.0685681196 }, { "content": "/// Bidirectional iterator.\n\npub trait BidirectionalIterator: Iterator {\n\n fn prev(&mut self) -> Option<Self::Item>;\n\n}\n\n\n\nimpl<'a, T> BidirectionalIterator for GridIterator<'a, T> {\n\n fn prev(&mut self) -> Option<Self::Item> {\n\n let topmost_line = self.grid.topmost_line();\n\n let last_column = self.grid.last_column();\n\n\n\n // Stop once we've reached the end of the grid.\n\n if self.point == Point::new(topmost_line, Column(0)) {\n\n return None;\n\n }\n\n\n\n match self.point {\n\n Point { column: Column(0), .. } => {\n\n self.point.column = last_column;\n\n self.point.line -= 1;\n\n },\n\n _ => self.point.column -= Column(1),\n\n }\n\n\n\n Some(Indexed { cell: &self.grid[self.point], point: self.point })\n\n }\n\n}\n", "file_path": "alacritty_terminal/src/grid/mod.rs", "rank": 76, "score": 68264.0685681196 }, { "content": "fn commit_hash() -> Option<String> {\n\n Command::new(\"git\")\n\n .args(&[\"rev-parse\", \"--short\", \"HEAD\"])\n\n .output()\n\n .ok()\n\n .and_then(|output| String::from_utf8(output.stdout).ok())\n\n .map(|hash| hash.trim().into())\n\n}\n", "file_path": "alacritty/build.rs", "rank": 77, "score": 68032.23270644443 }, { "content": "#[test]\n\nfn shrink_reflow_empty_cell_inside_line() {\n\n let mut grid = Grid::<Cell>::new(1, 5, 3);\n\n grid[Line(0)][Column(0)] = cell('1');\n\n grid[Line(0)][Column(1)] = Cell::default();\n\n grid[Line(0)][Column(2)] = cell('3');\n\n grid[Line(0)][Column(3)] = cell('4');\n\n grid[Line(0)][Column(4)] = Cell::default();\n\n\n\n grid.resize(true, 1, 2);\n\n\n\n assert_eq!(grid.total_lines(), 2);\n\n\n\n assert_eq!(grid[Line(-1)].len(), 2);\n\n assert_eq!(grid[Line(-1)][Column(0)], cell('1'));\n\n assert_eq!(grid[Line(-1)][Column(1)], wrap_cell(' '));\n\n\n\n assert_eq!(grid[Line(0)].len(), 2);\n\n assert_eq!(grid[Line(0)][Column(0)], cell('3'));\n\n assert_eq!(grid[Line(0)][Column(1)], cell('4'));\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 78, "score": 67215.38304266334 }, { "content": "/// A pseudoterminal (or PTY).\n\n///\n\n/// This is a refinement of EventedReadWrite that also provides a channel through which we can be\n\n/// notified if the PTY child process does something we care about (other than writing to the TTY).\n\n/// In particular, this allows for race-free child exit notification on UNIX (cf. `SIGCHLD`).\n\npub trait EventedPty: EventedReadWrite {\n\n fn child_event_token(&self) -> mio::Token;\n\n\n\n /// Tries to retrieve an event.\n\n ///\n\n /// Returns `Some(event)` on success, or `None` if there are no events to retrieve.\n\n fn next_child_event(&mut self) -> Option<ChildEvent>;\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/mod.rs", "rank": 79, "score": 66387.90086532333 }, { "content": "pub trait ActionContext<T: EventListener> {\n\n fn write_to_pty<B: Into<Cow<'static, [u8]>>>(&self, _data: B) {}\n\n fn mark_dirty(&mut self) {}\n\n fn size_info(&self) -> SizeInfo;\n\n fn copy_selection(&mut self, _ty: ClipboardType) {}\n\n fn start_selection(&mut self, _ty: SelectionType, _point: Point, _side: Side) {}\n\n fn toggle_selection(&mut self, _ty: SelectionType, _point: Point, _side: Side) {}\n\n fn update_selection(&mut self, _point: Point, _side: Side) {}\n\n fn clear_selection(&mut self) {}\n\n fn selection_is_empty(&self) -> bool;\n\n fn mouse_mut(&mut self) -> &mut Mouse;\n\n fn mouse(&self) -> &Mouse;\n\n fn received_count(&mut self) -> &mut usize;\n\n fn suppress_chars(&mut self) -> &mut bool;\n\n fn modifiers(&mut self) -> &mut ModifiersState;\n\n fn scroll(&mut self, _scroll: Scroll) {}\n\n fn window(&mut self) -> &mut Window;\n\n fn display(&mut self) -> &mut Display;\n\n fn terminal(&self) -> &Term<T>;\n\n fn terminal_mut(&mut self) -> &mut Term<T>;\n", "file_path": "alacritty/src/input.rs", "rank": 80, "score": 66380.26068479879 }, { "content": "fn log_config_path(config: &Config) {\n\n if config.ui_config.config_paths.is_empty() {\n\n return;\n\n }\n\n\n\n let mut msg = String::from(\"Configuration files loaded from:\");\n\n for path in &config.ui_config.config_paths {\n\n msg.push_str(&format!(\"\\n {:?}\", path.display()));\n\n }\n\n\n\n info!(\"{}\", msg);\n\n}\n", "file_path": "alacritty/src/main.rs", "rank": 81, "score": 65873.39628504284 }, { "content": "fn ref_test(dir: &Path) {\n\n let recording = read_u8(dir.join(\"alacritty.recording\"));\n\n let serialized_size = fs::read_to_string(dir.join(\"size.json\")).unwrap();\n\n let serialized_grid = fs::read_to_string(dir.join(\"grid.json\")).unwrap();\n\n let serialized_cfg = fs::read_to_string(dir.join(\"config.json\")).unwrap();\n\n\n\n let size: SizeInfo = json::from_str(&serialized_size).unwrap();\n\n let grid: Grid<Cell> = json::from_str(&serialized_grid).unwrap();\n\n let ref_config: RefConfig = json::from_str(&serialized_cfg).unwrap();\n\n\n\n let mut config = MockConfig::default();\n\n config.scrolling.set_history(ref_config.history_size);\n\n\n\n let mut terminal = Term::new(&config, size, Mock);\n\n let mut parser = ansi::Processor::new();\n\n\n\n for byte in recording {\n\n parser.advance(&mut terminal, byte);\n\n }\n\n\n", "file_path": "alacritty_terminal/tests/ref.rs", "rank": 82, "score": 65873.39628504284 }, { "content": "/// Move by whitespace separated word, like W/B/E/gE in vi.\n\nfn word<T: EventListener>(\n\n term: &mut Term<T>,\n\n mut point: Point,\n\n direction: Direction,\n\n side: Side,\n\n) -> Point {\n\n // Make sure we jump above wide chars.\n\n point = term.expand_wide(point, direction);\n\n\n\n if direction == side {\n\n // Skip whitespace until right before a word.\n\n let mut next_point = advance(term, point, direction);\n\n while !is_boundary(term, point, direction) && is_space(term, next_point) {\n\n point = next_point;\n\n next_point = advance(term, point, direction);\n\n }\n\n\n\n // Skip non-whitespace until right inside word boundary.\n\n let mut next_point = advance(term, point, direction);\n\n while !is_boundary(term, point, direction) && !is_space(term, next_point) {\n", "file_path": "alacritty_terminal/src/vi_mode.rs", "rank": 83, "score": 64872.9090405374 }, { "content": "/// Move by semantically separated word, like w/b/e/ge in vi.\n\nfn semantic<T: EventListener>(\n\n term: &mut Term<T>,\n\n mut point: Point,\n\n direction: Direction,\n\n side: Side,\n\n) -> Point {\n\n // Expand semantically based on movement direction.\n\n let expand_semantic = |point: Point| {\n\n // Do not expand when currently on a semantic escape char.\n\n let cell = &term.grid()[point];\n\n if term.semantic_escape_chars().contains(cell.c)\n\n && !cell.flags.intersects(Flags::WIDE_CHAR_SPACER | Flags::LEADING_WIDE_CHAR_SPACER)\n\n {\n\n point\n\n } else if direction == Direction::Left {\n\n term.semantic_search_left(point)\n\n } else {\n\n term.semantic_search_right(point)\n\n }\n\n };\n", "file_path": "alacritty_terminal/src/vi_mode.rs", "rank": 84, "score": 64872.9090405374 }, { "content": "#[cfg(windows)]\n\nfn installed_config() -> Option<PathBuf> {\n\n dirs::config_dir().map(|path| path.join(\"alacritty\\\\alacritty.yml\")).filter(|new| new.exists())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n static DEFAULT_ALACRITTY_CONFIG: &str =\n\n concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/../alacritty.yml\");\n\n\n\n #[test]\n\n fn config_read_eof() {\n\n let config_path: PathBuf = DEFAULT_ALACRITTY_CONFIG.into();\n\n let mut config = read_config(&config_path, Value::Null).unwrap();\n\n config.ui_config.config_paths = Vec::new();\n\n assert_eq!(config, Config::default());\n\n }\n\n}\n", "file_path": "alacritty/src/config/mod.rs", "rank": 85, "score": 64872.9090405374 }, { "content": "#[cfg(not(any(target_os = \"macos\", test)))]\n\nfn common_keybindings() -> Vec<KeyBinding> {\n\n bindings!(\n\n KeyBinding;\n\n V, ModifiersState::CTRL | ModifiersState::SHIFT, ~BindingMode::VI; Action::Paste;\n\n C, ModifiersState::CTRL | ModifiersState::SHIFT; Action::Copy;\n\n F, ModifiersState::CTRL | ModifiersState::SHIFT, ~BindingMode::SEARCH;\n\n Action::SearchForward;\n\n B, ModifiersState::CTRL | ModifiersState::SHIFT, ~BindingMode::SEARCH;\n\n Action::SearchBackward;\n\n C, ModifiersState::CTRL | ModifiersState::SHIFT,\n\n +BindingMode::VI, ~BindingMode::SEARCH; Action::ClearSelection;\n\n Insert, ModifiersState::SHIFT, ~BindingMode::VI; Action::PasteSelection;\n\n Key0, ModifiersState::CTRL; Action::ResetFontSize;\n\n Equals, ModifiersState::CTRL; Action::IncreaseFontSize;\n\n Plus, ModifiersState::CTRL; Action::IncreaseFontSize;\n\n NumpadAdd, ModifiersState::CTRL; Action::IncreaseFontSize;\n\n Minus, ModifiersState::CTRL; Action::DecreaseFontSize;\n\n NumpadSubtract, ModifiersState::CTRL; Action::DecreaseFontSize;\n\n )\n\n}\n\n\n", "file_path": "alacritty/src/config/bindings.rs", "rank": 86, "score": 64872.9090405374 }, { "content": "#[allow(clippy::all)]\n\nfn cell(c: char) -> Cell {\n\n let mut cell = Cell::default();\n\n cell.c = c;\n\n cell\n\n}\n\n\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 87, "score": 64197.1790804328 }, { "content": "/// Really only needed on BSD, but should be fine elsewhere.\n\nfn set_controlling_terminal(fd: c_int) {\n\n let res = unsafe {\n\n // TIOSCTTY changes based on platform and the `ioctl` call is different\n\n // based on architecture (32/64). So a generic cast is used to make sure\n\n // there are no issues. To allow such a generic cast the clippy warning\n\n // is disabled.\n\n #[allow(clippy::cast_lossless)]\n\n libc::ioctl(fd, TIOCSCTTY as _, 0)\n\n };\n\n\n\n if res < 0 {\n\n die!(\"ioctl TIOCSCTTY failed: {}\", io::Error::last_os_error());\n\n }\n\n}\n\n\n", "file_path": "alacritty_terminal/src/tty/unix.rs", "rank": 88, "score": 63920.03410021863 }, { "content": "fn deserialize_bindings<'a, D, T>(\n\n deserializer: D,\n\n mut default: Vec<Binding<T>>,\n\n) -> Result<Vec<Binding<T>>, D::Error>\n\nwhere\n\n D: Deserializer<'a>,\n\n T: Copy + Eq,\n\n Binding<T>: Deserialize<'a>,\n\n{\n\n let values = Vec::<serde_yaml::Value>::deserialize(deserializer)?;\n\n\n\n // Skip all invalid values.\n\n let mut bindings = Vec::with_capacity(values.len());\n\n for value in values {\n\n match Binding::<T>::deserialize(value) {\n\n Ok(binding) => bindings.push(binding),\n\n Err(err) => {\n\n error!(target: LOG_TARGET_CONFIG, \"Config error: {}; ignoring binding\", err);\n\n },\n\n }\n", "file_path": "alacritty/src/config/ui_config.rs", "rank": 89, "score": 63196.691835927355 }, { "content": "fn wrap_cell(c: char) -> Cell {\n\n let mut cell = cell(c);\n\n cell.flags.insert(Flags::WRAPLINE);\n\n cell\n\n}\n", "file_path": "alacritty_terminal/src/grid/tests.rs", "rank": 90, "score": 63196.691835927355 }, { "content": "/// Run main Alacritty entrypoint.\n\n///\n\n/// Creates a window, the terminal state, PTY, I/O event loop, input processor,\n\n/// config change monitor, and runs the main display loop.\n\nfn alacritty(options: Options) -> Result<(), String> {\n\n info!(\"Welcome to Alacritty\");\n\n\n\n // Setup glutin event loop.\n\n let window_event_loop = GlutinEventLoop::<Event>::with_user_event();\n\n\n\n // Initialize the logger as soon as possible as to capture output from other subsystems.\n\n let log_file = logging::initialize(&options, window_event_loop.create_proxy())\n\n .expect(\"Unable to initialize logger\");\n\n\n\n // Load configuration file.\n\n let config = config::load(&options);\n\n log_config_path(&config);\n\n\n\n // Update the log level from config.\n\n log::set_max_level(config.ui_config.debug.log_level);\n\n\n\n // Set environment variables.\n\n tty::setup_env(&config);\n\n\n", "file_path": "alacritty/src/main.rs", "rank": 91, "score": 62737.45391737995 }, { "content": "/// Check if a terminfo entry exists on the system.\n\nfn terminfo_exists(terminfo: &str) -> bool {\n\n // Get first terminfo character for the parent directory.\n\n let first = terminfo.get(..1).unwrap_or_default();\n\n let first_hex = format!(\"{:x}\", first.chars().next().unwrap_or_default() as usize);\n\n\n\n // Return true if the terminfo file exists at the specified location.\n\n macro_rules! check_path {\n\n ($path:expr) => {\n\n if $path.join(first).join(terminfo).exists()\n\n || $path.join(&first_hex).join(terminfo).exists()\n\n {\n\n return true;\n\n }\n\n };\n\n }\n\n\n\n if let Some(dir) = env::var_os(\"TERMINFO\") {\n\n check_path!(PathBuf::from(&dir));\n\n } else if let Some(home) = dirs::home_dir() {\n\n check_path!(home.join(\".terminfo\"));\n", "file_path": "alacritty_terminal/src/tty/mod.rs", "rank": 92, "score": 62243.81689560859 }, { "content": "#[cfg(unix)]\n\nfn msg(options: MessageOptions) -> Result<(), String> {\n\n ipc::send_message(options.socket, &SOCKET_MESSAGE_CREATE_WINDOW).map_err(|err| err.to_string())\n\n}\n\n\n", "file_path": "alacritty/src/main.rs", "rank": 93, "score": 61732.50210588612 }, { "content": " }\n\n}\n\n\n\nimpl Display for Error {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Error::ShaderCreation(err) => {\n\n write!(f, \"There was an error initializing the shaders: {}\", err)\n\n },\n\n }\n\n }\n\n}\n\n\n\nimpl From<ShaderCreationError> for Error {\n\n fn from(val: ShaderCreationError) -> Self {\n\n Error::ShaderCreation(val)\n\n }\n\n}\n\n\n\n/// Text drawing program.\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 96, "score": 27.390924021962157 }, { "content": "}\n\n\n\nimpl Clipboard {\n\n #[cfg(any(not(feature = \"wayland\"), target_os = \"macos\", windows))]\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n #[cfg(all(feature = \"wayland\", not(any(target_os = \"macos\", windows))))]\n\n pub unsafe fn new(display: Option<*mut c_void>) -> Self {\n\n match display {\n\n Some(display) => {\n\n let (selection, clipboard) =\n\n wayland_clipboard::create_clipboards_from_external(display);\n\n Self { clipboard: Box::new(clipboard), selection: Some(Box::new(selection)) }\n\n },\n\n None => Self::default(),\n\n }\n\n }\n\n\n", "file_path": "alacritty/src/clipboard.rs", "rank": 97, "score": 26.660795157489837 }, { "content": "\n\n /// Error during buffer swap.\n\n Context(glutin::ContextError),\n\n}\n\n\n\nimpl std::error::Error for Error {\n\n fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {\n\n match self {\n\n Error::Window(err) => err.source(),\n\n Error::Font(err) => err.source(),\n\n Error::Render(err) => err.source(),\n\n Error::Context(err) => err.source(),\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Error::Window(err) => err.fmt(f),\n", "file_path": "alacritty/src/display/mod.rs", "rank": 98, "score": 26.25208973477721 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl Display for ShaderCreationError {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n match self {\n\n ShaderCreationError::Io(err) => write!(f, \"Unable to read shader: {}\", err),\n\n ShaderCreationError::Compile(log) => {\n\n write!(f, \"Failed compiling shader: {}\", log)\n\n },\n\n ShaderCreationError::Link(log) => write!(f, \"Failed linking shader: {}\", log),\n\n }\n\n }\n\n}\n\n\n\nimpl From<io::Error> for ShaderCreationError {\n\n fn from(val: io::Error) -> Self {\n\n ShaderCreationError::Io(val)\n\n }\n", "file_path": "alacritty/src/renderer/mod.rs", "rank": 99, "score": 24.633982543233053 } ]
Rust
libfat/src/directory/raw_dir_entry.rs
Orycterope/kfs_libfs
538c0156492db7fdbfa69d49f46609861febbd4a
use byteorder::{ByteOrder, LittleEndian}; use structview::{u16_le, u32_le, View}; use crate::attribute::Attributes; use crate::cluster::Cluster; use crate::datetime::FatDateTime; use crate::filesystem::FatFileSystem; use crate::name::{LongFileName, ShortFileName}; use libfs::block::{Block, BlockDevice, BlockIndex}; use libfs::FileSystemError; use libfs::FileSystemResult; #[derive(Clone, Copy, View)] #[repr(C)] pub struct LongFileNameDirEntry { pub order_entry: u8, pub char_part_0: [u16_le; 5], pub attribute: u8, pub lfn_entry_type: u8, pub lfn_checksum: u8, pub char_part_1: [u16_le; 6], pub reserved: u16_le, pub char_part_2: [u16_le; 2], } #[derive(Clone, Copy, View)] #[repr(C)] pub struct ShortFileNameDirEntry { pub name: [u8; ShortFileName::MAX_LEN], pub attribute: u8, pub reserved: u8, pub creation_tenths: u8, pub creation_time: u16_le, pub creation_date: u16_le, pub last_access_date: u16_le, pub high_cluster: u16_le, pub modification_time: u16_le, pub modification_date: u16_le, pub low_cluster: u16_le, pub file_size: u32_le, } #[derive(Clone, Copy)] pub struct FatDirEntry { pub entry_cluster: Cluster, pub entry_index: u32, pub entry_offset: u32, pub data: [u8; Self::LEN], } impl FatDirEntry { pub const LEN: usize = 32; pub fn from_raw( data: &[u8], entry_cluster: Cluster, entry_index: u32, entry_offset: u32, ) -> FatDirEntry { let mut data_copied = [0x0u8; Self::LEN]; data_copied[..data.len()].clone_from_slice(&data[..]); FatDirEntry { entry_cluster, entry_index, entry_offset, data: data_copied, } } pub fn get_first_byte(&self) -> u8 { self.data[0] } pub fn is_free(&self) -> bool { self.get_first_byte() == 0 } pub fn is_deleted(&self) -> bool { self.get_first_byte() == 0xE5 } pub fn set_deleted(&mut self) { self.data[0] = 0xE5; } pub fn clear(&mut self) { self.data = [0x0u8; Self::LEN]; } pub fn flush<T>(&self, fs: &FatFileSystem<T>) -> FileSystemResult<()> where T: BlockDevice, { let mut blocks = [Block::new()]; fs.block_device .read( &mut blocks, fs.partition_start, BlockIndex(self.entry_cluster.to_data_block_index(fs).0 + self.entry_index), ) .or(Err(FileSystemError::ReadFailed))?; let block = &mut blocks[0]; let entry_start = self.entry_offset as usize; let entry_end = entry_start + Self::LEN; for (i, val) in block[entry_start..entry_end].iter_mut().enumerate() { *val = self.data[i]; } fs.block_device .write( &blocks, fs.partition_start, BlockIndex(self.entry_cluster.to_data_block_index(fs).0 + self.entry_index), ) .or(Err(FileSystemError::WriteFailed)) } pub fn attribute(&self) -> Attributes { Attributes::new(self.data[11]) } pub fn set_attribute(&mut self, attribute: Attributes) { self.data[11] = attribute.get_value(); } pub fn is_long_file_name(&self) -> bool { self.attribute().is_lfn() } pub fn long_file_name_raw(&self) -> Option<LongFileName> { if self.is_long_file_name() { Some(LongFileName::from_lfn_dir_entry(self.as_lfn_entry())) } else { None } } pub fn short_name(&self) -> Option<ShortFileName> { if !self.is_long_file_name() { Some(ShortFileName::from_data(&self.as_sfn_entry().name)) } else { None } } pub fn set_lfn_index(&mut self, index: u8) { self.data[0] = index; } pub fn set_short_name(&mut self, short_name: &ShortFileName) { (&mut self.data[0..11]).copy_from_slice(&short_name.as_bytes()); } pub fn set_lfn_entry(&mut self, lfn: &str) { let lfn = LongFileName::from_utf8(lfn); let lfn = lfn.as_contents(); for (i, entry) in lfn.iter().enumerate().take(5) { let index = 1 + i * 2; LittleEndian::write_u16(&mut self.data[index..index + 2], *entry); } for i in 0..6 { let index = 0xE + i * 2; let i = i + 5; LittleEndian::write_u16(&mut self.data[index..index + 2], lfn[i]); } for i in 0..2 { let index = 0x1C + i * 2; let i = i + 11; LittleEndian::write_u16(&mut self.data[index..index + 2], lfn[i]); } } pub fn as_lfn_entry(&self) -> &LongFileNameDirEntry { LongFileNameDirEntry::view(&self.data).unwrap() } pub fn as_sfn_entry(&self) -> &ShortFileNameDirEntry { ShortFileNameDirEntry::view(&self.data).unwrap() } pub fn set_lfn_checksum(&mut self, checksum: u8) { self.data[13] = checksum; } pub fn get_cluster(&self) -> Cluster { let entry = self.as_sfn_entry(); let high_cluster = u32::from(entry.high_cluster.to_int()); let low_cluster = u32::from(entry.low_cluster.to_int()); Cluster(low_cluster | (high_cluster << 16)) } pub fn set_cluster(&mut self, cluster: Cluster) { let value = cluster.0; let high_cluster = ((value >> 16) & 0xFFFF) as u16; let low_cluster = (value & 0xFFFF) as u16; LittleEndian::write_u16(&mut self.data[20..22], high_cluster); LittleEndian::write_u16(&mut self.data[26..28], low_cluster); } pub fn get_file_size(&self) -> u32 { self.as_sfn_entry().file_size.to_int() } pub fn set_file_size(&mut self, new_size: u32) { LittleEndian::write_u32(&mut self.data[28..32], new_size); if new_size == 0 { self.set_cluster(Cluster(0)) } } pub fn get_creation_datetime(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_time = entry.creation_time.to_int(); let seconds = ((raw_time & 0x1f) << 1) as u8; let minutes = ((raw_time >> 5) & 0x3f) as u8; let hour = ((raw_time >> 11) & 0x1f) as u8; let raw_date = entry.creation_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new( 1980 + year, month, day, hour, minutes, seconds, self.data[13], ) } pub fn get_last_access_date(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_date = entry.last_access_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new(1980 + year, month, day, 0, 0, 0, 0) } pub fn get_modification_datetime(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_time = entry.modification_time.to_int(); let seconds = ((raw_time & 0x1f) << 1) as u8; let minutes = ((raw_time >> 5) & 0x3f) as u8; let hour = ((raw_time >> 11) & 0x1f) as u8; let raw_date = entry.modification_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new(1980 + year, month, day, hour, minutes, seconds, 0) } } impl<'a> core::fmt::Debug for FatDirEntry { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "FatDirEntry {{ ")?; write!(f, "{:?} ", self.attribute())?; if self.is_long_file_name() { if let Some(long_file_name) = self.long_file_name_raw() { if let Some(data) = long_file_name.chars() { write!(f, "LongFileName {{{:?}}}", data)?; } else { write!(f, "BROKEN LongFileName")?; } } else { write!(f, "LongFileName {{ \"not a long file name?????\" }}")?; } } else if let Some(short_file_name) = self.short_name() { write!(f, "ShortFileName {{{:?}}}", short_file_name.chars())?; } else { write!(f, "ShortFileName {{ \"not a short file name?????\" }}")?; } write!(f, " }}") } }
use byteorder::{ByteOrder, LittleEndian}; use structview::{u16_le, u32_le, View}; use crate::attribute::Attributes; use crate::cluster::Cluster; use crate::datetime::FatDateTime; use crate::filesystem::FatFileSystem; use crate::name::{LongFileName, ShortFileName}; use libfs::block::{Block, BlockDevice, BlockIndex}; use libfs::FileSystemError; use libfs::FileSystemResult; #[derive(Clone, Copy, View)] #[repr(C)] pub struct LongFileNameDirEntry { pub order_entry: u8, pub char_part_0: [u16_le; 5], pub attribute: u8, pub lfn_entry_type: u8, pub lfn_checksum: u8, pub char_part_1: [u16_le; 6], pub reserved: u16_le, pub char_part_2: [u16_le; 2], } #[derive(Clone, Copy, View)] #[repr(C)] pub struct ShortFileNameDirEntry { pub name: [u8; ShortFileName::MAX_LEN], pub attribute: u8, pub reserved: u8, pub creation_tenths: u8, pub creation_time: u16_le, pub creation_date: u16_le, pub last_access_date: u16_le, pub high_cluster: u16_le, pub modification_time: u16_le, pub modification_date: u16_le, pub low_cluster: u16_le, pub file_size: u32_le, } #[derive(Clone, Copy)] pub struct FatDirEntry { pub entry_cluster: Cluster, pub entry_index: u32, pub entry_offset: u32, pub data: [u8; Self::LEN], } impl FatDirEntry { pub const LEN: usize = 32; pub fn from_raw( data: &[u8], entry_cluster: Cluster, entry_index: u32, entry_offset: u32, ) -> FatDirEntry { let mut data_copied = [0x0u8; Self::LEN]; data_copied[..data.len()].clone_from_slice(&data[..]); FatDirEntry { entry_cluster, entry_index, entry_offset, data: data_copied, } } pub fn get_first_byte(&self) -> u8 { self.data[0] } pub fn is_free(&self) -> bool { self.get_first_byte() == 0 } pub fn is_deleted(&self) -> bool { self.get_first_byte() == 0xE5 } pub fn set_deleted(&mut self) { self.data[0] = 0xE5; } pub fn clear(&mut self) { self.data = [0x0u8; Self::LEN];
file_name() { Some(LongFileName::from_lfn_dir_entry(self.as_lfn_entry())) } else { None } } pub fn short_name(&self) -> Option<ShortFileName> { if !self.is_long_file_name() { Some(ShortFileName::from_data(&self.as_sfn_entry().name)) } else { None } } pub fn set_lfn_index(&mut self, index: u8) { self.data[0] = index; } pub fn set_short_name(&mut self, short_name: &ShortFileName) { (&mut self.data[0..11]).copy_from_slice(&short_name.as_bytes()); } pub fn set_lfn_entry(&mut self, lfn: &str) { let lfn = LongFileName::from_utf8(lfn); let lfn = lfn.as_contents(); for (i, entry) in lfn.iter().enumerate().take(5) { let index = 1 + i * 2; LittleEndian::write_u16(&mut self.data[index..index + 2], *entry); } for i in 0..6 { let index = 0xE + i * 2; let i = i + 5; LittleEndian::write_u16(&mut self.data[index..index + 2], lfn[i]); } for i in 0..2 { let index = 0x1C + i * 2; let i = i + 11; LittleEndian::write_u16(&mut self.data[index..index + 2], lfn[i]); } } pub fn as_lfn_entry(&self) -> &LongFileNameDirEntry { LongFileNameDirEntry::view(&self.data).unwrap() } pub fn as_sfn_entry(&self) -> &ShortFileNameDirEntry { ShortFileNameDirEntry::view(&self.data).unwrap() } pub fn set_lfn_checksum(&mut self, checksum: u8) { self.data[13] = checksum; } pub fn get_cluster(&self) -> Cluster { let entry = self.as_sfn_entry(); let high_cluster = u32::from(entry.high_cluster.to_int()); let low_cluster = u32::from(entry.low_cluster.to_int()); Cluster(low_cluster | (high_cluster << 16)) } pub fn set_cluster(&mut self, cluster: Cluster) { let value = cluster.0; let high_cluster = ((value >> 16) & 0xFFFF) as u16; let low_cluster = (value & 0xFFFF) as u16; LittleEndian::write_u16(&mut self.data[20..22], high_cluster); LittleEndian::write_u16(&mut self.data[26..28], low_cluster); } pub fn get_file_size(&self) -> u32 { self.as_sfn_entry().file_size.to_int() } pub fn set_file_size(&mut self, new_size: u32) { LittleEndian::write_u32(&mut self.data[28..32], new_size); if new_size == 0 { self.set_cluster(Cluster(0)) } } pub fn get_creation_datetime(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_time = entry.creation_time.to_int(); let seconds = ((raw_time & 0x1f) << 1) as u8; let minutes = ((raw_time >> 5) & 0x3f) as u8; let hour = ((raw_time >> 11) & 0x1f) as u8; let raw_date = entry.creation_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new( 1980 + year, month, day, hour, minutes, seconds, self.data[13], ) } pub fn get_last_access_date(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_date = entry.last_access_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new(1980 + year, month, day, 0, 0, 0, 0) } pub fn get_modification_datetime(&self) -> FatDateTime { let entry = self.as_sfn_entry(); let raw_time = entry.modification_time.to_int(); let seconds = ((raw_time & 0x1f) << 1) as u8; let minutes = ((raw_time >> 5) & 0x3f) as u8; let hour = ((raw_time >> 11) & 0x1f) as u8; let raw_date = entry.modification_date.to_int(); let day = (raw_date & 0x1f) as u8; let month = ((raw_date >> 5) & 0xf) as u8; let year = (raw_date >> 9) & 0x7f; FatDateTime::new(1980 + year, month, day, hour, minutes, seconds, 0) } } impl<'a> core::fmt::Debug for FatDirEntry { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "FatDirEntry {{ ")?; write!(f, "{:?} ", self.attribute())?; if self.is_long_file_name() { if let Some(long_file_name) = self.long_file_name_raw() { if let Some(data) = long_file_name.chars() { write!(f, "LongFileName {{{:?}}}", data)?; } else { write!(f, "BROKEN LongFileName")?; } } else { write!(f, "LongFileName {{ \"not a long file name?????\" }}")?; } } else if let Some(short_file_name) = self.short_name() { write!(f, "ShortFileName {{{:?}}}", short_file_name.chars())?; } else { write!(f, "ShortFileName {{ \"not a short file name?????\" }}")?; } write!(f, " }}") } }
} pub fn flush<T>(&self, fs: &FatFileSystem<T>) -> FileSystemResult<()> where T: BlockDevice, { let mut blocks = [Block::new()]; fs.block_device .read( &mut blocks, fs.partition_start, BlockIndex(self.entry_cluster.to_data_block_index(fs).0 + self.entry_index), ) .or(Err(FileSystemError::ReadFailed))?; let block = &mut blocks[0]; let entry_start = self.entry_offset as usize; let entry_end = entry_start + Self::LEN; for (i, val) in block[entry_start..entry_end].iter_mut().enumerate() { *val = self.data[i]; } fs.block_device .write( &blocks, fs.partition_start, BlockIndex(self.entry_cluster.to_data_block_index(fs).0 + self.entry_index), ) .or(Err(FileSystemError::WriteFailed)) } pub fn attribute(&self) -> Attributes { Attributes::new(self.data[11]) } pub fn set_attribute(&mut self, attribute: Attributes) { self.data[11] = attribute.get_value(); } pub fn is_long_file_name(&self) -> bool { self.attribute().is_lfn() } pub fn long_file_name_raw(&self) -> Option<LongFileName> { if self.is_long_
random
[ { "content": "/// Get the last cluster of a cluster chain.\n\npub fn get_last_cluster<T>(\n\n fs: &FatFileSystem<T>,\n\n cluster: Cluster,\n\n) -> Result<Cluster, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n Ok(get_last_and_previous_cluster(fs, cluster)?.0)\n\n}\n\n\n", "file_path": "libfat/src/table.rs", "rank": 0, "score": 93044.43463987265 }, { "content": "/// Get the last cluster and prevous cluster of a cluster chain.\n\npub fn get_last_and_previous_cluster<T>(\n\n fs: &FatFileSystem<T>,\n\n cluster: Cluster,\n\n) -> Result<(Cluster, Option<Cluster>), FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n let mut previous_cluster = None;\n\n let mut current_cluster = cluster;\n\n\n\n while let FatValue::Data(val) = FatValue::get(fs, current_cluster)? {\n\n previous_cluster = Some(current_cluster);\n\n current_cluster = Cluster(val);\n\n }\n\n\n\n Ok((current_cluster, previous_cluster))\n\n}\n\n\n", "file_path": "libfat/src/table.rs", "rank": 1, "score": 90152.4508227347 }, { "content": "/// Compute the whole cluster count of a given FileSystem.\n\npub fn get_free_cluster_count<T>(fs: &FatFileSystem<T>) -> Result<u32, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n let mut current_cluster = Cluster(2);\n\n\n\n let mut res = 0;\n\n\n\n while current_cluster.0 < fs.boot_record.cluster_count {\n\n if let FatValue::Free = FatValue::get(fs, current_cluster)? {\n\n res += 1;\n\n }\n\n\n\n current_cluster = Cluster(current_cluster.0 + 1);\n\n }\n\n\n\n Ok(res)\n\n}\n", "file_path": "libfat/src/table.rs", "rank": 2, "score": 84728.87515060842 }, { "content": "/// Parse the MBR and return an instance to a filesystem at the given partition index.\n\npub fn get_partition<T>(\n\n block_device: T,\n\n index: BlockIndex,\n\n) -> Result<FatFileSystem<T>, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n let mut blocks = [Block::new()];\n\n\n\n /// The Partition Table offset.\n\n const PARITION_TABLE_OFFSET: usize = 446;\n\n\n\n /// The MBR signature offset.\n\n const MBR_SIGNATURE: usize = 510;\n\n\n\n /// The size of a partition table entry.\n\n const PARITION_TABLE_ENTRY_SIZE: usize = 16;\n\n\n\n block_device\n\n .raw_read(&mut blocks, index)\n", "file_path": "libfat/src/lib.rs", "rank": 3, "score": 72257.35310154312 }, { "content": "/// Retrieve the parent of a given path.\n\npub fn get_parent(path: &str) -> (&str, &str) {\n\n let separator_index_opt = path.rfind('/');\n\n\n\n if let Some(separator_index) = separator_index_opt {\n\n let (first, last) = path.split_at(separator_index);\n\n (first, &last[1..])\n\n } else {\n\n (\"\", path)\n\n }\n\n}\n\n\n", "file_path": "libfat/src/utils.rs", "rank": 4, "score": 60235.77603022044 }, { "content": "/// Align the address to the previous alignment.\n\n///\n\n/// The given number should be a power of two to get coherent results!\n\n///\n\n/// # Panics\n\n///\n\n/// Panics on underflow if align is 0.\n\npub fn align_down<T: Num + Not<Output = T> + BitAnd<Output = T> + Copy>(addr: T, align: T) -> T {\n\n addr & !(align - T::one())\n\n}\n\n\n", "file_path": "libfat/src/utils.rs", "rank": 5, "score": 57484.93326419978 }, { "content": "/// Align the address to the next alignment.\n\n///\n\n/// The given number should be a power of two to get coherent results!\n\n///\n\n/// # Panics\n\n///\n\n/// Panics on underflow if align is 0.\n\n/// Panics on overflow if the expression `addr + (align - 1)` overflows.\n\npub fn align_up<T: Num + Not<Output = T> + BitAnd<Output = T> + Copy>(addr: T, align: T) -> T {\n\n align_down(addr + (align - T::one()), align)\n\n}\n\n\n", "file_path": "libfat/src/utils.rs", "rank": 6, "score": 57484.93326419978 }, { "content": "/// Permite to split a path.\n\npub fn split_path(path: &str) -> (&str, Option<&str>) {\n\n let mut path_split = path.trim_matches('/').splitn(2, '/');\n\n\n\n // unwrap will never fail here\n\n let comp = path_split.next().unwrap();\n\n let rest_opt = path_split.next();\n\n\n\n (comp, rest_opt)\n\n}\n", "file_path": "libfat/src/utils.rs", "rank": 7, "score": 57174.45896997665 }, { "content": "/// Treat the block device directly as a filesystem.\n\npub fn get_raw_partition<T>(block_device: T) -> Result<FatFileSystem<T>, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n parse_fat_boot_record(block_device, BlockIndex(0), BlockCount(0))\n\n}\n\n\n", "file_path": "libfat/src/lib.rs", "rank": 8, "score": 45336.82832750046 }, { "content": "/// Represent a cached block in the LRU cache.\n\nstruct CachedBlock {\n\n /// Bool indicating whether this block should be written to device when flushing.\n\n dirty: bool,\n\n /// The data of this block.\n\n data: Block,\n\n}\n\n\n\nimpl<B: BlockDevice> CachedBlockDevice<B> {\n\n /// Creates a new CachedBlockDevice that wraps `device`, and can hold at most `cap` blocks in cache.\n\n pub fn new(device: B, cap: usize) -> CachedBlockDevice<B> {\n\n CachedBlockDevice {\n\n block_device: device,\n\n lru_cache: Mutex::new(LruCache::new(cap)),\n\n }\n\n }\n\n\n\n /// Writes every dirty cached block to device.\n\n ///\n\n /// Note that this will not empty the cache, just perform device writes\n\n /// and update dirty blocks as now non-dirty.\n", "file_path": "libfs/src/block.rs", "rank": 9, "score": 43714.68207158038 }, { "content": "/// Predicate helper used to filter directory entries.\n\nstruct DirectoryFilterPredicate;\n\n\n\nimpl DirectoryFilterPredicate {\n\n /// Accept all entries except \".\" & \"..\".\n\n fn all(entry: &FileSystemResult<FatDirectoryEntry>) -> bool {\n\n if entry.is_err() {\n\n return false;\n\n }\n\n\n\n if let Ok(entry) = entry {\n\n let name = entry.file_name.as_str();\n\n name != \".\" && name != \"..\"\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n /// Only accept directory entries.\n\n fn dirs(entry: &FileSystemResult<FatDirectoryEntry>) -> bool {\n\n if entry.is_err() {\n", "file_path": "libfs_fat/src/lib.rs", "rank": 10, "score": 41282.65779248568 }, { "content": "/// Represent the FAT Volume BootRecord.\n\nstruct FatVolumeBootRecord {\n\n /// The actual data of the boot record.\n\n data: Block,\n\n\n\n /// The type of FAT filesystem.\n\n fat_type: FatFsType,\n\n\n\n /// The count of cluster availaible in the filesystem.\n\n cluster_count: u32,\n\n}\n\n\n\n#[allow(dead_code)]\n\nimpl FatVolumeBootRecord {\n\n /// Create a new FAT volume boot record from raw data.\n\n pub fn new(data: Block) -> FatVolumeBootRecord {\n\n let mut res = FatVolumeBootRecord {\n\n data,\n\n fat_type: FatFsType::Fat12,\n\n cluster_count: 0,\n\n };\n", "file_path": "libfat/src/lib.rs", "rank": 11, "score": 41279.08944068523 }, { "content": "/// Reprsent the FS Info structure of FAT32.\n\nstruct FatFileSystemInfo {\n\n // TODO: select Ordering wisely on operations.\n\n /// The last allocated cluster on the filesystem.\n\n last_cluster: AtomicU32,\n\n\n\n /// The free cluster count on the filesystem.\n\n free_cluster: AtomicU32,\n\n}\n\n\n\nimpl FatFileSystemInfo {\n\n /// Import FS Info from a FAT32 filesystem.\n\n fn from_fs<T>(fs: &FatFileSystem<T>) -> FileSystemResult<Self>\n\n where\n\n T: BlockDevice,\n\n {\n\n let mut blocks = [Block::new()];\n\n\n\n let mut last_cluster = 0xFFFF_FFFF;\n\n let mut free_cluster = 0xFFFF_FFFF;\n\n\n", "file_path": "libfat/src/filesystem.rs", "rank": 12, "score": 41279.08944068523 }, { "content": "/// Represent the operation on a directory.\n\npub trait DirectoryOperations {\n\n /// Read the next directory entries and return the number of entries read.\n\n fn read(&mut self, buf: &mut [DirectoryEntry]) -> FileSystemResult<u64>;\n\n\n\n /// Return the count of entries in the directory.\n\n fn entry_count(&self) -> FileSystemResult<u64>;\n\n}\n\n\n", "file_path": "libfs/src/lib.rs", "rank": 13, "score": 38423.0103254834 }, { "content": "/// Represent the operation on a file.\n\npub trait FileOperations {\n\n /// Read the content of a file at a given ``offset`` in ``buf``.\n\n fn read(&mut self, offset: u64, buf: &mut [u8]) -> FileSystemResult<u64>;\n\n\n\n /// Write the content given ``buf`` at the given ``offset`` in the file.\n\n /// If the file is too small to hold the data and the appendable flag is set, it will resize the file and append the data.\n\n /// If the file is too small to hold the data and the appendable flag isn't set, this will return a FileSystemError::NoSpaceLeft.\n\n fn write(&mut self, offset: u64, buf: &[u8]) -> FileSystemResult<()>;\n\n\n\n /// Flush any data not written on the filesystem.\n\n fn flush(&mut self) -> FileSystemResult<()>;\n\n\n\n /// Resize the file with the given ``size``.\n\n /// If the file isn't open with the appendable flag, it will not be extendable and will return a FileSystemError::NoSpaceLeft.\n\n fn set_len(&mut self, size: u64) -> FileSystemResult<()>;\n\n\n\n /// Return the current file size.\n\n fn get_len(&mut self) -> FileSystemResult<u64>;\n\n}\n\n\n", "file_path": "libfs/src/lib.rs", "rank": 14, "score": 38423.0103254834 }, { "content": "/// A libfat file interface implementing ``FileOperations``.\n\nstruct FileInterface<'a, T> {\n\n /// Internal interface to libfat's filesystem.\n\n fs: &'a libfat::filesystem::FatFileSystem<T>,\n\n\n\n /// The libfat's directory entry of this file.\n\n file_info: FatDirectoryEntry,\n\n\n\n /// The flags applied to the given file.\n\n mode: FileModeFlags,\n\n}\n\n\n\n/// A wrapper arround libfat ``FatFileSystem`` implementing ``FileSystemOperations``.\n\npub struct FatFileSystem<T> {\n\n /// libfat filesystem interface.\n\n inner: libfat::filesystem::FatFileSystem<T>,\n\n}\n\n\n", "file_path": "libfs_fat/src/lib.rs", "rank": 15, "score": 37370.00422675547 }, { "content": "/// A libfat directory reader implementing ``DirectoryOperations``.\n\nstruct DirectoryReader<'a, T> {\n\n /// The opened directory path. Used to get the complete path of every entries.\n\n base_path: [u8; DirectoryEntry::PATH_LEN],\n\n\n\n /// The iterator used to iter over libfat's directory entries.\n\n internal_iter: FatDirectoryEntryIterator<'a, T>,\n\n\n\n /// The filter required by the user.\n\n filter_fn: &'static dyn Fn(&FileSystemResult<FatDirectoryEntry>) -> bool,\n\n\n\n /// The number of entries in the directory after ``filter_fn``.\n\n entry_count: u64,\n\n}\n\n\n", "file_path": "libfs_fat/src/lib.rs", "rank": 16, "score": 37370.00422675547 }, { "content": "/// Represent the operation on a filesystem.\n\npub trait FileSystemOperations {\n\n /// Create a file with a given ``size`` at the specified ``path``.\n\n fn create_file(&self, path: &str, size: u64) -> FileSystemResult<()>;\n\n\n\n /// Create a directory at the specified ``path``.\n\n fn create_directory(&self, path: &str) -> FileSystemResult<()>;\n\n\n\n /// Rename a file at ``old_path`` into ``new_path``.\n\n fn rename_file(&self, old_path: &str, new_path: &str) -> FileSystemResult<()>;\n\n\n\n /// Rename a directory at ``old_path`` into ``new_path``\n\n fn rename_directory(&self, old_path: &str, new_path: &str) -> FileSystemResult<()>;\n\n\n\n /// Delete a file at the specified ``path``.\n\n fn delete_file(&self, path: &str) -> FileSystemResult<()>;\n\n\n\n /// Delete a directory at the specified ``path``.\n\n fn delete_directory(&self, path: &str) -> FileSystemResult<()>;\n\n\n\n /// Open a file at the specified ``path`` with the given ``mode`` flags.\n", "file_path": "libfs/src/lib.rs", "rank": 17, "score": 37271.81295572139 }, { "content": "/// Parse a FAT boot record and return a FatFileSystem instance.\n\nfn parse_fat_boot_record<T>(\n\n block_device: T,\n\n partition_start: BlockIndex,\n\n partition_block_count: BlockCount,\n\n) -> Result<FatFileSystem<T>, FileSystemError>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n let mut blocks = [Block::new()];\n\n\n\n block_device\n\n .read(&mut blocks, partition_start, BlockIndex(0))\n\n .or(Err(FileSystemError::ReadFailed))?;\n\n\n\n let block = &blocks[0];\n\n\n\n let boot_record: FatVolumeBootRecord = FatVolumeBootRecord::new(block.clone());\n\n\n\n if !boot_record.is_valid() {\n\n return Err(FileSystemError::InvalidPartition);\n", "file_path": "libfat/src/lib.rs", "rank": 18, "score": 37062.34021023102 }, { "content": "/// Represent a device holding blocks.\n\npub trait BlockDevice: Sized {\n\n /// Read blocks from the block device starting at the given ``index``.\n\n fn raw_read(&self, blocks: &mut [Block], index: BlockIndex) -> BlockResult<()>;\n\n\n\n /// Write blocks to the block device starting at the given ``index``.\n\n fn raw_write(&self, blocks: &[Block], index: BlockIndex) -> BlockResult<()>;\n\n\n\n /// Read blocks from the block device starting at the given ``partition_start + index``.\n\n fn read(\n\n &self,\n\n blocks: &mut [Block],\n\n partition_start: BlockIndex,\n\n index: BlockIndex,\n\n ) -> BlockResult<()> {\n\n self.raw_read(blocks, BlockIndex(partition_start.0 + index.0))\n\n }\n\n\n\n /// Write blocks to the block device starting at the given ``partition_start + index``.\n\n fn write(\n\n &self,\n", "file_path": "libfs/src/block.rs", "rank": 19, "score": 35750.8045807468 }, { "content": " (self.0 & Self::DIRECTORY) == Self::DIRECTORY\n\n }\n\n\n\n /// Check if the archive bit is set.\n\n pub fn is_archive(self) -> bool {\n\n (self.0 & Self::ARCHIVE) == Self::ARCHIVE\n\n }\n\n\n\n /// Check if it is a long file name.\n\n pub fn is_lfn(self) -> bool {\n\n (self.0 & Self::LFN) == Self::LFN\n\n }\n\n\n\n /// Check if it is a block device.\n\n pub fn is_device(self) -> bool {\n\n (self.0 & Self::DEVICE) == Self::DEVICE\n\n }\n\n\n\n /// Get the raw attribute value.\n\n pub fn get_value(self) -> u8 {\n\n self.0\n\n }\n\n}\n", "file_path": "libfat/src/attribute.rs", "rank": 20, "score": 29415.924631499453 }, { "content": "\n\n /// Indicates that the cluster-chain associated with this entry gets interpreted as subdirectory instead of as a file. Subdirectories have a filesize entry of zero.\n\n pub const DIRECTORY: u8 = 0x10;\n\n\n\n /// Typically set by the filesystem as soon as the file is created or modified to mark the file as \"dirty\", and reset by backup software once the file has been backed up to indicate \"pure\" state.\n\n pub const ARCHIVE: u8 = 0x20;\n\n\n\n /// Define a device file. SHOULDN'T APPEARS ON DISK.\n\n pub const DEVICE: u8 = 0x40;\n\n\n\n /// Indicates a long file name entry.\n\n pub const LFN: u8 = Self::READ_ONLY | Self::HIDDEN | Self::SYSTEM | Self::VOLUME;\n\n\n\n /// Create a new Attributes from a raw u8 value.\n\n pub fn new(value: u8) -> Attributes {\n\n Attributes(value)\n\n }\n\n\n\n /// Check if the read only bit is set.\n\n pub fn is_read_only(self) -> bool {\n", "file_path": "libfat/src/attribute.rs", "rank": 21, "score": 29415.395737772393 }, { "content": "//! FAT entry attribute.\n\n\n\n#[derive(Debug, Clone, Copy)]\n\n/// Represent a 8.3 entry attribute.\n\npub struct Attributes(u8);\n\n\n\nimpl Attributes {\n\n /// The filesystem will not allow a file to be opened for modification.\n\n // TODO: Follow this behaviour.\n\n pub const READ_ONLY: u8 = 0x01;\n\n\n\n /// Hides files or directories from normal directory views.\n\n pub const HIDDEN: u8 = 0x02;\n\n\n\n /// Indicates that the file belongs to the system and must not be physically moved (e.g., during defragmentation), because there may be references into the file using absolute addressing bypassing the file system (boot loaders, kernel images, swap files, extended attributes, etc.).\n\n // TODO: Follow this behaviour.\n\n pub const SYSTEM: u8 = 0x04;\n\n\n\n /// Indicates an optional directory volume label, normally only residing in a volume's root directory.\n\n pub const VOLUME: u8 = 0x08;\n", "file_path": "libfat/src/attribute.rs", "rank": 22, "score": 29414.30416653998 }, { "content": " (self.0 & Self::READ_ONLY) == Self::READ_ONLY\n\n }\n\n\n\n /// Check if the hidden bit is set.\n\n pub fn is_hidden(self) -> bool {\n\n (self.0 & Self::HIDDEN) == Self::HIDDEN\n\n }\n\n\n\n /// Check if the system bit is set.\n\n pub fn is_system(self) -> bool {\n\n (self.0 & Self::SYSTEM) == Self::SYSTEM\n\n }\n\n\n\n /// Check if the volume bit is set.\n\n pub fn is_volume(self) -> bool {\n\n (self.0 & Self::VOLUME) == Self::VOLUME\n\n }\n\n\n\n /// Check if the directory bit is set.\n\n pub fn is_directory(self) -> bool {\n", "file_path": "libfat/src/attribute.rs", "rank": 23, "score": 29409.91905908755 }, { "content": "//! FAT cluster.\n\n\n\nuse super::FatFileSystem;\n\nuse libfs::block::{Block, BlockDevice, BlockIndex};\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\n/// Represent a FAT Cluster position.\n\npub struct Cluster(pub u32);\n\n\n\nimpl Cluster {\n\n /// Compute the offset of the data from the cluster position.\n\n pub fn to_data_block_index<T>(self, fs: &FatFileSystem<T>) -> BlockIndex\n\n where\n\n T: BlockDevice,\n\n {\n\n let first_block_of_cluster = (self.0 - 2) * u32::from(fs.boot_record.blocks_per_cluster());\n\n BlockIndex(fs.first_data_offset.0 + first_block_of_cluster)\n\n }\n\n\n\n /// Compute the offset in the cluster map of the cluster chain.\n", "file_path": "libfat/src/cluster.rs", "rank": 24, "score": 29388.62179489323 }, { "content": " pub fn to_fat_offset(self) -> u32 {\n\n self.0 * 4\n\n }\n\n\n\n /// Compute the block index of a cluster in the cluster map.\n\n pub fn to_fat_block_index<T>(self, fs: &FatFileSystem<T>) -> BlockIndex\n\n where\n\n T: BlockDevice,\n\n {\n\n let fat_offset = self.to_fat_offset();\n\n\n\n let fat_block_index =\n\n u32::from(fs.boot_record.reserved_block_count()) + (fat_offset / Block::LEN_U32);\n\n BlockIndex(fat_block_index)\n\n }\n\n}\n", "file_path": "libfat/src/cluster.rs", "rank": 25, "score": 29383.749053579446 }, { "content": " const EXT_LEN: usize = 3;\n\n\n\n /// The max length of a 8.3 name.\n\n pub const MAX_LEN: usize = ShortFileName::BASE_FILE_NAME_LEN + ShortFileName::EXT_LEN;\n\n\n\n /// Import a 8.3 name from raw data.\n\n pub fn from_data(data: &[u8]) -> Self {\n\n let mut short_name = [0x20u8; ShortFileName::MAX_LEN];\n\n\n\n short_name[..data.len()].clone_from_slice(&data[..]);\n\n ShortFileName {\n\n contents: short_name,\n\n }\n\n }\n\n\n\n /// Import a 8.3 name from a VFAT long name.\n\n pub fn from_unformated_str(context: &mut ShortFileNameContext, name: &str) -> Self {\n\n ShortFileNameGenerator::create(context, name)\n\n }\n\n\n", "file_path": "libfat/src/name.rs", "rank": 26, "score": 29061.40553311174 }, { "content": "\n\n /// The count of name conflicting with this name.\n\n pub last_index_value: usize,\n\n}\n\n\n\nimpl ShortFileNameGenerator {\n\n /// Permite to extract partial part of the VFAT name and format it to 8.3 name.\n\n fn copy_format_sfn_part(dst: &mut [u8], src: &str, is_base_name: bool) -> (usize, bool, bool) {\n\n let mut dst_pos = 0;\n\n let mut lossy_convertion = false;\n\n for c in src.chars() {\n\n if dst_pos == dst.len() {\n\n // SFN is full!\n\n return (dst_pos, false, lossy_convertion);\n\n }\n\n\n\n // remap chars to support 8.3 correctly\n\n let lfn_char = match c {\n\n ' ' | '.' => {\n\n lossy_convertion = true;\n", "file_path": "libfat/src/name.rs", "rank": 27, "score": 29059.33990846002 }, { "content": "\n\n#[derive(Default, Debug)]\n\n/// Represent the context used when generating a 8.3 name.\n\npub struct ShortFileNameContext {\n\n /// Set to true if the checksum needs to be inserted.\n\n pub checksum_inserted: bool,\n\n\n\n /// Cached checksum.\n\n pub checksum: u16,\n\n\n\n /// The file name on 8 bytes.\n\n pub short_name_base: [u8; ShortFileName::BASE_FILE_NAME_LEN],\n\n /// The file name size.\n\n pub short_name_base_len: usize,\n\n\n\n /// The file extension on 3 bytes.\n\n pub short_name_ext: [u8; ShortFileName::EXT_LEN + 1],\n\n\n\n /// The file extension size.\n\n pub short_name_ext_len: usize,\n", "file_path": "libfat/src/name.rs", "rank": 28, "score": 29057.802256997773 }, { "content": "impl LongFileName {\n\n /// The max length of a single LFN entry name.\n\n pub const MAX_LEN: usize = 13;\n\n\n\n /// The max length of a single LFN entry name when represented as Unicode.\n\n pub const MAX_LEN_UNICODE: usize = Self::MAX_LEN * 4;\n\n\n\n /// Import a VFAT long name from a raw FAT directory entry.\n\n pub fn from_lfn_dir_entry(entry: &LongFileNameDirEntry) -> Self {\n\n let mut long_name = [0x0; LongFileName::MAX_LEN];\n\n\n\n let mut index = 0;\n\n for c in &entry.char_part_0 {\n\n long_name[index] = c.to_int();\n\n index += 1;\n\n }\n\n\n\n for c in &entry.char_part_1 {\n\n long_name[index] = c.to_int();\n\n index += 1;\n", "file_path": "libfat/src/name.rs", "rank": 29, "score": 29057.20219532756 }, { "content": "\n\n slice.copy_from_slice(&index_buffer[8 - index_buffer_len..]);\n\n }\n\n\n\n short_name_len = ShortFileName::BASE_FILE_NAME_LEN;\n\n\n\n if context.short_name_ext_len > 1 {\n\n (&mut short_name[short_name_len..short_name_len + context.short_name_ext_len - 1])\n\n .copy_from_slice(&context.short_name_ext[1..context.short_name_ext_len]);\n\n }\n\n\n\n ShortFileName::from_data(&short_name)\n\n }\n\n}\n\n\n\nimpl ShortFileName {\n\n /// The base file name max length.\n\n const BASE_FILE_NAME_LEN: usize = 8;\n\n\n\n /// The extension name max length.\n", "file_path": "libfat/src/name.rs", "rank": 30, "score": 29055.965159135263 }, { "content": " }\n\n\n\n for c in &entry.char_part_2 {\n\n long_name[index] = c.to_int();\n\n index += 1;\n\n }\n\n\n\n LongFileName {\n\n contents: long_name,\n\n }\n\n }\n\n\n\n /// Import a VFAT long name from a Unicode str.\n\n pub fn from_utf8(data: &str) -> Self {\n\n let mut long_name = [0x0u16; LongFileName::MAX_LEN];\n\n\n\n for (i, c) in data.chars().enumerate().take(LongFileName::MAX_LEN) {\n\n c.encode_utf16(&mut long_name[i..]);\n\n }\n\n\n", "file_path": "libfat/src/name.rs", "rank": 31, "score": 29055.080254433902 }, { "content": " true,\n\n );\n\n is_lossy = is_lossy || basename_lossy;\n\n context.short_name_base_len = basename_len;\n\n\n\n context.short_name_ext_len = 0;\n\n if dot_position < lfn.len() {\n\n context.short_name_ext[0] = b'.';\n\n context.short_name_ext_len = 1;\n\n\n\n let mut copy_size = lfn.len() - dot_position;\n\n if copy_size > 3 {\n\n copy_size = 3;\n\n }\n\n\n\n let (ext_len, _ext_fits, ext_lossy) = Self::copy_format_sfn_part(\n\n &mut context.short_name_ext[1..=copy_size],\n\n &lfn[dot_position + 1..],\n\n false,\n\n );\n", "file_path": "libfat/src/name.rs", "rank": 32, "score": 29054.311775593964 }, { "content": "\n\n lossy_convertion = lossy_convertion || (lfn_char != c);\n\n\n\n // 8.3 only support uppercase\n\n let uppercase = lfn_char.to_ascii_uppercase();\n\n dst[dst_pos] = uppercase as u8;\n\n dst_pos += 1;\n\n }\n\n (dst_pos, true, lossy_convertion)\n\n }\n\n\n\n /// Permite to create a 8.3 name out of a context and a VFAT long file name.\n\n pub fn create(context: &mut ShortFileNameContext, lfn: &str) -> ShortFileName {\n\n let mut is_lossy = false;\n\n if context.short_name_base_len == 0 {\n\n let dot_position = lfn.rfind('.').unwrap_or_else(|| lfn.len());\n\n\n\n let (basename_len, _basename_fits, basename_lossy) = Self::copy_format_sfn_part(\n\n &mut context.short_name_base,\n\n &lfn[..dot_position],\n", "file_path": "libfat/src/name.rs", "rank": 33, "score": 29053.78271496784 }, { "content": " LongFileName {\n\n contents: long_name,\n\n }\n\n }\n\n\n\n /// Convert a VFAT long name to a Rust char representation.\n\n pub fn chars(&self) -> Option<[char; Self::MAX_LEN]> {\n\n let val = &self.contents;\n\n\n\n let mut res: [char; Self::MAX_LEN] = [' '; Self::MAX_LEN];\n\n\n\n for (i, c) in core::char::decode_utf16(val.iter().cloned()).enumerate() {\n\n if let Ok(c) = c {\n\n res[i] = c;\n\n } else {\n\n return None;\n\n }\n\n }\n\n\n\n Some(res)\n\n }\n\n\n\n /// Return the raw content of a VFAT long name.\n\n pub fn as_contents(&self) -> [u16; LongFileName::MAX_LEN] {\n\n self.contents\n\n }\n\n}\n", "file_path": "libfat/src/name.rs", "rank": 34, "score": 29053.114525290915 }, { "content": " index_buffer[8 - i] = b'0' + (index % 10) as u8;\n\n index /= 10;\n\n }\n\n\n\n index_buffer[8 - index_buffer_len] = b'~';\n\n\n\n let mut short_name = [0x20u8; ShortFileName::MAX_LEN];\n\n let mut short_name_len = 0;\n\n if context.short_name_base_len != 0 {\n\n (&mut short_name[0..context.short_name_base_len])\n\n .copy_from_slice(&context.short_name_base[0..context.short_name_base_len]);\n\n short_name_len += context.short_name_base_len;\n\n }\n\n\n\n if is_lossy || context.last_index_value > 1 {\n\n let slice = if short_name_len == ShortFileName::BASE_FILE_NAME_LEN {\n\n (&mut short_name[short_name_len - index_buffer_len..short_name_len])\n\n } else {\n\n (&mut short_name[short_name_len..short_name_len + index_buffer_len])\n\n };\n", "file_path": "libfat/src/name.rs", "rank": 35, "score": 29053.056887079605 }, { "content": "//! FAT filename representation.\n\nuse core::num;\n\n\n\nuse super::directory::raw_dir_entry::LongFileNameDirEntry;\n\n\n\n/// Represent a 8.3 name.\n\npub struct ShortFileName {\n\n /// The buffer containing the 8.3 name.\n\n contents: [u8; ShortFileName::MAX_LEN],\n\n}\n\n\n\n/// Represent a VFAT long name.\n\n#[derive(Clone)]\n\npub struct LongFileName {\n\n /// The buffer containing the VFAT long name.\n\n contents: [u16; LongFileName::MAX_LEN],\n\n}\n\n\n\n/// An utilitary to generate 8.3 name out of VFAT long name.\n\npub struct ShortFileNameGenerator;\n", "file_path": "libfat/src/name.rs", "rank": 36, "score": 29052.447138683383 }, { "content": " /// Convert a 8.3 name to a Rust char representation.\n\n pub fn chars(&self) -> [char; ShortFileName::MAX_LEN] {\n\n let mut res: [char; ShortFileName::MAX_LEN] = [' '; ShortFileName::MAX_LEN];\n\n for (index, dst) in res.iter_mut().enumerate().take(self.contents.len()) {\n\n // Remap 0x5 => 0xE5 as it's not a delete marker\n\n if index == 0 && self.contents[index] == 0x5 {\n\n *dst = 'Õ';\n\n } else {\n\n *dst = self.contents[index] as char;\n\n }\n\n }\n\n res\n\n }\n\n\n\n /// Get the raw content of a 8.3 name.\n\n pub fn as_bytes(&self) -> [u8; ShortFileName::MAX_LEN] {\n\n self.contents\n\n }\n\n\n\n /// Compute checksum of short file name\n", "file_path": "libfat/src/name.rs", "rank": 37, "score": 29052.35622212111 }, { "content": " pub fn checksum(short_name: &[u8]) -> u16 {\n\n let mut checksum = num::Wrapping(0u16);\n\n for b in short_name {\n\n checksum = (checksum << 7) + (checksum >> 1) + num::Wrapping(u16::from(*b));\n\n }\n\n checksum.0\n\n }\n\n\n\n /// COmpute checksum of short file name\n\n pub fn checksum_lfn(short_name: &[u8]) -> u8 {\n\n let mut sum = num::Wrapping(0u8);\n\n for b in short_name {\n\n sum = num::Wrapping((sum.0 & 1) << 7)\n\n + num::Wrapping((sum.0 & 0xfe) >> 1)\n\n + num::Wrapping(*b);\n\n }\n\n sum.0\n\n }\n\n}\n\n\n", "file_path": "libfat/src/name.rs", "rank": 38, "score": 29051.25917179429 }, { "content": " context.short_name_ext_len += ext_len;\n\n\n\n is_lossy = is_lossy || ext_lossy;\n\n if ext_lossy {\n\n context.short_name_ext[context.short_name_ext_len - 1] = b'~';\n\n }\n\n }\n\n\n\n if context.short_name_base_len <= 2 {\n\n context.checksum = ShortFileName::checksum(&lfn.as_bytes());\n\n let mut checksum = context.checksum;\n\n\n\n for index in 0..4 {\n\n let number = if checksum % 16 > 9 {\n\n (checksum % 16) as u8 + b'A' - 0xA\n\n } else {\n\n (checksum % 16) as u8 + b'0'\n\n };\n\n\n\n context.short_name_base[context.short_name_base_len + index] = number;\n", "file_path": "libfat/src/name.rs", "rank": 39, "score": 29050.66342638782 }, { "content": "\n\n context.short_name_base[index] = number;\n\n checksum >>= 4;\n\n }\n\n\n\n context.last_index_value = 1;\n\n context.short_name_base_len = 6;\n\n context.checksum_inserted = true;\n\n }\n\n\n\n let mut index_buffer = [0x0u8; ShortFileName::BASE_FILE_NAME_LEN];\n\n\n\n let mut index = context.last_index_value;\n\n let mut index_buffer_len = ShortFileName::BASE_FILE_NAME_LEN;\n\n for i in 1..8 {\n\n if index == 0 {\n\n index_buffer_len = i;\n\n break;\n\n }\n\n\n", "file_path": "libfat/src/name.rs", "rank": 40, "score": 29049.290105029 }, { "content": " checksum >>= 4;\n\n }\n\n\n\n context.short_name_base_len += 4;\n\n context.checksum_inserted = true;\n\n }\n\n }\n\n\n\n context.last_index_value += 1;\n\n\n\n if context.last_index_value > 4 && !context.checksum_inserted {\n\n context.checksum = ShortFileName::checksum(&lfn.as_bytes());\n\n let mut checksum = context.checksum;\n\n\n\n for index in 2..6 {\n\n let number = if checksum % 16 > 9 {\n\n (checksum % 16) as u8 + b'A' - 0xA\n\n } else {\n\n (checksum % 16) as u8 + b'0'\n\n };\n", "file_path": "libfat/src/name.rs", "rank": 41, "score": 29048.8291180361 }, { "content": " continue;\n\n }\n\n\n\n // valid chars\n\n 'A'..='Z' | 'a'..='z' | '0'..='9' => c,\n\n '!' | '#' | '$' | '%' | '&' | '\\'' | '(' | ')' | '-' | '@' | '^' | '_' | '`'\n\n | '{' | '}' | '~' => c,\n\n\n\n // conflict with delete marker, remap to 0x5.\n\n 'Õ' => {\n\n if dst_pos == 0 && is_base_name {\n\n '\\x05'\n\n } else {\n\n 'Õ'\n\n }\n\n }\n\n\n\n // disallowed remap\n\n _ => '_',\n\n };\n", "file_path": "libfat/src/name.rs", "rank": 42, "score": 29041.403103783894 }, { "content": "#[derive(Clone)]\n\npub struct Block {\n\n /// The actual storage of the block.\n\n pub contents: [u8; Block::LEN],\n\n}\n\n\n\n#[derive(Debug, Copy, Clone, Hash, PartialOrd, PartialEq, Ord, Eq)]\n\n/// Represent the position of a block on a block device.\n\npub struct BlockIndex(pub u32);\n\n\n\n#[derive(Debug, Copy, Clone)]\n\n/// Represent the count of blocks that a block device hold.\n\npub struct BlockCount(pub u32);\n\n\n\nimpl Block {\n\n /// The size of a block in bytes.\n\n pub const LEN: usize = 512;\n\n\n\n /// The size of a block in bytes as a 32 bits unsigned value.\n\n pub const LEN_U32: u32 = Self::LEN as u32;\n", "file_path": "libfs/src/block.rs", "rank": 47, "score": 20.009728246283466 }, { "content": "impl DirectoryEntry {\n\n /// The max size of a VFAT long name.\n\n pub const MAX_FILE_NAME_LEN: usize = 255;\n\n\n\n /// The max size of a VFAT long name encoded as Unicode.\n\n // we actually use 256 unicode char because arrayvec doesn't define an implementation for Array<[u8; 1020]>\n\n pub const MAX_FILE_NAME_LEN_UNICODE: usize = 1024;\n\n\n\n /// Read at a given offset of the file into a given buffer.\n\n pub fn read<'a, T>(\n\n &mut self,\n\n fs: &'a FatFileSystem<T>,\n\n offset: u64,\n\n buf: &mut [u8],\n\n ) -> FileSystemResult<u64>\n\n where\n\n T: BlockDevice,\n\n {\n\n if offset >= 0xFFFF_FFFF {\n\n return Ok(0);\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 48, "score": 19.463653960723164 }, { "content": " pub block_index: u32,\n\n\n\n /// The current iteration point in the block.\n\n pub counter: u8,\n\n\n\n /// Used at the first iteration to init the counter.\n\n pub is_first: bool,\n\n}\n\n\n\nimpl<'a, T> FatDirEntryIterator<'a, T>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n /// Create a new iterator from a cluster, a block index and an offset (representing the starting point of the iterator). \n\n pub fn new(\n\n fs: &'a FatFileSystem<T>,\n\n start_cluster: Cluster,\n\n block_index: BlockIndex,\n\n offset: u32,\n\n ) -> Self {\n", "file_path": "libfat/src/directory/raw_dir_entry_iterator.rs", "rank": 49, "score": 18.489192659334396 }, { "content": "\n\n /// The creation UNIX timestamp of the entry.\n\n pub creation_timestamp: u64,\n\n\n\n /// The last access UNIX timestamp of the entry.\n\n pub last_access_timestamp: u64,\n\n\n\n /// The last modification UNIX timestamp of the entry.\n\n pub last_modification_timestamp: u64,\n\n\n\n /// The file size of the entry.\n\n pub file_size: u32,\n\n\n\n /// The file name of the entry.\n\n pub file_name: ArrayString<[u8; Self::MAX_FILE_NAME_LEN_UNICODE]>,\n\n\n\n /// The attributes of the entry.\n\n pub attribute: Attributes,\n\n}\n\n\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 51, "score": 17.706984474347234 }, { "content": "impl core::ops::Deref for Block {\n\n type Target = [u8; Block::LEN];\n\n fn deref(&self) -> &Self::Target {\n\n &self.contents\n\n }\n\n}\n\n\n\nimpl core::ops::DerefMut for Block {\n\n fn deref_mut(&mut self) -> &mut [u8; Block::LEN] {\n\n &mut self.contents\n\n }\n\n}\n\n\n\nimpl BlockIndex {\n\n /// Convert the block index into an offset in bytes.\n\n pub fn into_offset(self) -> u64 {\n\n u64::from(self.0) * (Block::LEN as u64)\n\n }\n\n}\n\n\n\nimpl BlockCount {\n\n /// Convert the block count into a size in bytes.\n\n pub fn into_size(self) -> u64 {\n\n u64::from(self.0) * (Block::LEN as u64)\n\n }\n\n}\n\n\n\n/// Represent a device holding blocks.\n", "file_path": "libfs/src/block.rs", "rank": 54, "score": 17.338467494125403 }, { "content": "\n\n /// Create a new block instance.\n\n pub fn new() -> Block {\n\n Block::default()\n\n }\n\n\n\n /// Return the content of the block.\n\n pub fn as_contents(&self) -> [u8; Block::LEN] {\n\n self.contents\n\n }\n\n}\n\n\n\nimpl Default for Block {\n\n fn default() -> Self {\n\n Block {\n\n contents: [0u8; Self::LEN],\n\n }\n\n }\n\n}\n\n\n", "file_path": "libfs/src/block.rs", "rank": 55, "score": 15.838058053354587 }, { "content": "\n\n /// Create a directory entry in a given parent directory.\n\n fn create_dir_entry(\n\n fs: &'a FatFileSystem<T>,\n\n parent_entry: &DirectoryEntry,\n\n attribute: Attributes,\n\n name: &str,\n\n cluster: Cluster,\n\n file_size: u32,\n\n ) -> FileSystemResult<DirectoryEntry> {\n\n let is_special_entry = name == \".\" || name == \"..\";\n\n let mut count: u32 = 1;\n\n\n\n let mut free_entries_iter = Self::allocate_entries(parent_entry, fs, count)?;\n\n\n\n let mut first_raw_dir_entry = None;\n\n\n\n let short_file_name;\n\n if !is_special_entry {\n\n let mut context: ShortFileNameContext = ShortFileNameContext::default();\n", "file_path": "libfat/src/directory/mod.rs", "rank": 56, "score": 15.81368616549349 }, { "content": " pub fn bytes_per_block(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[11..13])\n\n }\n\n\n\n /// The amount of blocks per cluster.\n\n pub fn blocks_per_cluster(&self) -> u8 {\n\n self.data[13]\n\n }\n\n\n\n /// The count of reserved block.\n\n pub fn reserved_block_count(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[14..16])\n\n }\n\n\n\n /// The number of FAT present in the filesystem.\n\n pub fn fats_count(&self) -> u8 {\n\n self.data[16]\n\n }\n\n\n\n /// The number of childs in the root directory for FAT12/FAT16 filesystem.\n", "file_path": "libfat/src/lib.rs", "rank": 57, "score": 15.711863568094772 }, { "content": " Self::create_dir_entry(\n\n self.fs,\n\n &self.dir_info,\n\n Attributes::new(0),\n\n name,\n\n Cluster(0),\n\n 0,\n\n )?;\n\n\n\n Ok(())\n\n }\n\n\n\n /// Delete a directory or a file with the given name.\n\n pub fn unlink(self, name: &str, is_dir: bool) -> FileSystemResult<()> {\n\n let fs = self.fs;\n\n\n\n let dir_entry = self.find_entry(name)?;\n\n\n\n if dir_entry.attribute.is_directory() != is_dir {\n\n if is_dir {\n", "file_path": "libfat/src/directory/mod.rs", "rank": 58, "score": 15.652043361290833 }, { "content": " break;\n\n }\n\n\n\n cluster_offset = BlockIndex(raw_tmp_offset / Block::LEN_U32);\n\n\n\n let cluster = cluster_opt.unwrap();\n\n let block_start_index = cluster.to_data_block_index(fs);\n\n let tmp_index = cluster_offset.0 % blocks_per_cluster;\n\n let tmp_offset = raw_tmp_offset % Block::LEN_U32;\n\n\n\n device\n\n .read(\n\n &mut blocks,\n\n fs.partition_start,\n\n BlockIndex(block_start_index.0 + tmp_index),\n\n )\n\n .or(Err(FileSystemError::ReadFailed))?;\n\n\n\n let buf_slice = &mut buf[read_size as usize..];\n\n let mut buf_limit = if buf_slice.len() >= Block::LEN {\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 59, "score": 15.356778815330001 }, { "content": " parent_cluster,\n\n 0,\n\n );\n\n\n\n if let Err(err) = res {\n\n // If it fail here, this can be catastrophic but at least we tried our best.\n\n Self::delete_dir_entry(self.fs, &entry)?;\n\n self.fs.free_cluster(cluster, None)?;\n\n return Err(err);\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n /// Create a file with the given name.\n\n pub fn touch(&mut self, name: &str) -> FileSystemResult<()> {\n\n if name.len() > DirectoryEntry::MAX_FILE_NAME_LEN {\n\n return Err(FileSystemError::PathTooLong);\n\n }\n\n\n", "file_path": "libfat/src/directory/mod.rs", "rank": 60, "score": 15.188064059024935 }, { "content": "\n\n if parent_new_dir.clone().find_entry(file_name).is_ok() {\n\n return Err(FileSystemError::FileExists);\n\n }\n\n\n\n parent_new_dir.rename(old_entry, file_name, is_dir)\n\n }\n\n\n\n /// Clean cluster chain data.\n\n /// Used when creating a new directory.\n\n pub(crate) fn clean_cluster_data(&self, cluster: Cluster) -> FileSystemResult<()> {\n\n let blocks = [Block::new()];\n\n let mut block_index = 0;\n\n\n\n for cluster in BlockIndexClusterIter::new(self, cluster, None) {\n\n block_index = (block_index + 1) % u32::from(self.boot_record.blocks_per_cluster());\n\n self.block_device\n\n .write(\n\n &blocks,\n\n self.partition_start,\n", "file_path": "libfat/src/filesystem.rs", "rank": 61, "score": 15.05618314333758 }, { "content": " match self.last_fat {\n\n Some(FatValue::Data(data)) => {\n\n self.current_cluster = Some(Cluster(data));\n\n self.last_fat = FatValue::get(&self.fs, self.current_cluster?).ok();\n\n }\n\n _ => self.current_cluster = None,\n\n };\n\n\n\n Some(res)\n\n }\n\n}\n\n\n\nimpl FatValue {\n\n /// Create a ``FatValue`` from a raw FAT32 value.\n\n pub fn from_u32(val: u32) -> Self {\n\n match val {\n\n 0 => FatValue::Free,\n\n 0x0FFF_FFF7 => FatValue::Bad,\n\n 0x0FFF_FFF8..=0x0FFF_FFFF => FatValue::EndOfChain,\n\n n => FatValue::Data(n as u32),\n", "file_path": "libfat/src/table.rs", "rank": 62, "score": 15.02427287255846 }, { "content": "//! FAT directory managment.\n\n\n\nuse arrayvec::ArrayString;\n\n\n\nuse libfs::block::{BlockDevice, BlockIndex};\n\nuse libfs::FileSystemError;\n\nuse libfs::FileSystemResult;\n\n\n\nuse super::attribute::Attributes;\n\nuse super::block_iter::BlockIndexClusterIter;\n\nuse super::cluster::Cluster;\n\nuse super::name::ShortFileName;\n\nuse super::name::ShortFileNameContext;\n\nuse super::utils;\n\n\n\nuse super::table;\n\n\n\nuse super::FatFileSystem;\n\n\n\npub mod dir_entry;\n", "file_path": "libfat/src/directory/mod.rs", "rank": 63, "score": 14.778854999794573 }, { "content": "//! FATs managment.\n\n\n\nuse super::filesystem::FatFileSystem;\n\nuse super::Cluster;\n\nuse byteorder::{ByteOrder, LittleEndian};\n\nuse libfs::block::{Block, BlockDevice, BlockIndex};\n\n\n\nuse crate::FileSystemError;\n\n\n\n#[derive(Debug, Copy, Clone, PartialEq)]\n\n/// Represent a cluster chan value.\n\npub enum FatValue {\n\n /// Represent a free cluster.\n\n Free,\n\n\n\n /// Represent a used cluster.\n\n Data(u32),\n\n\n\n /// Represent a corrupted cluster (bad sectors)\n\n Bad,\n", "file_path": "libfat/src/table.rs", "rank": 65, "score": 14.757909678711554 }, { "content": " lfn_entry.set_lfn_index(lfn_index);\n\n lfn_entry.set_lfn_entry(&name[(target_index - 1) as usize * 13..]);\n\n lfn_entry.set_lfn_checksum(sfn_checksum as u8);\n\n lfn_entry.flush(fs)?;\n\n }\n\n\n\n count += lfn_count;\n\n } else {\n\n short_file_name = ShortFileName::from_data(&name.as_bytes());\n\n }\n\n\n\n let mut sfn_entry = free_entries_iter.next().unwrap()?;\n\n sfn_entry.clear();\n\n sfn_entry.set_file_size(file_size);\n\n sfn_entry.set_cluster(cluster);\n\n sfn_entry.set_attribute(attribute);\n\n\n\n sfn_entry.set_short_name(&short_file_name);\n\n sfn_entry.flush(fs)?;\n\n\n", "file_path": "libfat/src/directory/mod.rs", "rank": 68, "score": 14.313086816727008 }, { "content": " }\n\n }\n\n\n\n /// Convert a ```FatValue``` to a raw FAT32 value.\n\n pub fn to_u32(self) -> u32 {\n\n match self {\n\n FatValue::Free => 0,\n\n FatValue::Bad => 0x0FFF_FFF7,\n\n FatValue::EndOfChain => 0x0FFF_FFFF,\n\n FatValue::Data(n) => n,\n\n }\n\n }\n\n\n\n /// Create a ```FatValue``` from a raw block and offset.\n\n pub fn from_block(block: &Block, cluster_offset: usize) -> Self {\n\n let val = LittleEndian::read_u32(&block[cluster_offset..cluster_offset + 4]) & 0x0FFF_FFFF;\n\n FatValue::from_u32(val)\n\n }\n\n\n\n /// Get the ```FatValue``` of a given cluster.\n", "file_path": "libfat/src/table.rs", "rank": 69, "score": 14.296242604748265 }, { "content": " short_file_name = ShortFileName::from_unformated_str(&mut context, name);\n\n\n\n let lfn_count = (name.len() as u32 + 12) / 13;\n\n let sfn_checksum = ShortFileName::checksum_lfn(&short_file_name.as_bytes());\n\n\n\n for index in 0..lfn_count {\n\n let target_index = lfn_count - index;\n\n let lfn_index = if target_index == lfn_count {\n\n 0x40u8 + target_index as u8\n\n } else {\n\n target_index as u8\n\n };\n\n\n\n let mut lfn_entry = free_entries_iter.next().unwrap()?;\n\n if first_raw_dir_entry.is_none() {\n\n first_raw_dir_entry = Some(lfn_entry);\n\n }\n\n\n\n lfn_entry.clear();\n\n lfn_entry.set_attribute(Attributes::new(Attributes::LFN));\n", "file_path": "libfat/src/directory/mod.rs", "rank": 70, "score": 14.277179014645533 }, { "content": "\n\n cluster_offset = BlockIndex(raw_tmp_offset / Block::LEN_U32);\n\n\n\n let block_start_index = cluster.to_data_block_index(fs);\n\n let tmp_index = cluster_offset.0 % blocks_per_cluster;\n\n let tmp_offset = raw_tmp_offset % Block::LEN_U32;\n\n\n\n device\n\n .read(\n\n &mut blocks,\n\n fs.partition_start,\n\n BlockIndex(block_start_index.0 + tmp_index),\n\n )\n\n .or(Err(FileSystemError::ReadFailed))?;\n\n\n\n let buf_slice = &buf[write_size as usize..];\n\n let buf_limit = if buf_slice.len() >= Block::LEN {\n\n Block::LEN\n\n } else {\n\n buf_slice.len()\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 71, "score": 14.233327706912403 }, { "content": " pub fn fat_size32(&self) -> u32 {\n\n LittleEndian::read_u32(&self.data[36..40])\n\n }\n\n\n\n /// The block index of the FAT32's filesystem informations.\n\n pub fn fs_info_block(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[48..50])\n\n }\n\n\n\n /// The root directory cluster for FAT12/FAT16 filesystems.\n\n pub fn root_dir_childs_cluster(&self) -> Cluster {\n\n Cluster(LittleEndian::read_u32(&self.data[44..48]))\n\n }\n\n\n\n /// Return the size in cluster of the FAT.\n\n pub fn fat_size(&self) -> u32 {\n\n let result = u32::from(self.fat_size16());\n\n if result != 0 {\n\n result\n\n } else {\n", "file_path": "libfat/src/lib.rs", "rank": 75, "score": 13.910502157625352 }, { "content": " counter: usize,\n\n}\n\n\n\nimpl<'a, T> BlockIndexClusterIter<'a, T>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n /// Create a new iterator from a cluster and a block index.\n\n pub fn new(\n\n fs: &'a FatFileSystem<T>,\n\n cluster: Cluster,\n\n block_index: Option<BlockIndex>,\n\n ) -> Self {\n\n let blocks_per_cluster = fs.boot_record.blocks_per_cluster() as usize;\n\n\n\n let (cluster, block_index) = if let Some(block_index) = block_index {\n\n let cluster_offset = block_index.0 / blocks_per_cluster as u32;\n\n let block_index = BlockIndex(block_index.0 % blocks_per_cluster as u32);\n\n (Cluster(cluster.0 + cluster_offset), Some(block_index))\n\n } else {\n", "file_path": "libfat/src/block_iter.rs", "rank": 76, "score": 13.817547047787505 }, { "content": " }\n\n\n\n /// Rename a directory or a file from a given name to another one.\n\n // FIXME: better error managment\n\n pub fn rename(\n\n self,\n\n dir_entry: DirectoryEntry,\n\n new_name: &str,\n\n is_dir: bool,\n\n ) -> FileSystemResult<()> {\n\n if new_name.len() > DirectoryEntry::MAX_FILE_NAME_LEN {\n\n return Err(FileSystemError::PathTooLong);\n\n }\n\n let old_raw_info = dir_entry.raw_info.unwrap();\n\n\n\n let new_entry_count = ((new_name.len() as u32 + 12) / 13) + 1;\n\n\n\n // can we update in place?\n\n if old_raw_info.entry_count == new_entry_count\n\n && old_raw_info.parent_cluster == self.dir_info.start_cluster\n", "file_path": "libfat/src/directory/mod.rs", "rank": 77, "score": 13.340101260945497 }, { "content": " pub parent_cluster: Cluster,\n\n\n\n /// The first raw entry block index of the child entry in the parent entry.\n\n pub first_entry_block_index: BlockIndex,\n\n\n\n /// The first raw entry offset of the child entry inside the block in the parent entry.\n\n pub first_entry_offset: u32,\n\n\n\n /// The count of raw entries used by the child entry.\n\n pub entry_count: u32,\n\n}\n\n\n\n#[derive(Debug, Clone, Copy)]\n\n/// A high level representation of a directory/file in the directory.\n\npub struct DirectoryEntry {\n\n /// The first cluster used for\n\n pub(crate) start_cluster: Cluster,\n\n\n\n /// The raw informations of the entry inside it parent.\n\n pub(crate) raw_info: Option<DirectoryEntryRawInfo>,\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 80, "score": 13.175796431376058 }, { "content": " };\n\n\n\n let mut lfn_entry = entries_iter.next().unwrap()?;\n\n\n\n lfn_entry.clear();\n\n lfn_entry.set_attribute(Attributes::new(Attributes::LFN));\n\n lfn_entry.set_lfn_index(lfn_index);\n\n lfn_entry.set_lfn_entry(&new_name[(target_index - 1) as usize * 13..]);\n\n lfn_entry.set_lfn_checksum(sfn_checksum as u8);\n\n lfn_entry.flush(self.fs)?;\n\n }\n\n\n\n let mut sfn_entry = entries_iter.next().unwrap()?;\n\n sfn_entry.set_short_name(&short_file_name);\n\n sfn_entry.flush(self.fs)?;\n\n return Ok(());\n\n }\n\n\n\n let new_entry = Self::create_dir_entry(\n\n self.fs,\n", "file_path": "libfat/src/directory/mod.rs", "rank": 81, "score": 13.087934542547817 }, { "content": " FatDirEntryIterator {\n\n counter: (offset / FatDirEntry::LEN as u32) as u8,\n\n block_index: block_index.0,\n\n is_first: true,\n\n cluster_iter: BlockIndexClusterIter::new(fs, start_cluster, Some(block_index)),\n\n last_cluster: None,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T> Iterator for FatDirEntryIterator<'a, T>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n type Item = FileSystemResult<FatDirEntry>;\n\n fn next(&mut self) -> Option<FileSystemResult<FatDirEntry>> {\n\n let entry_per_block_count = (Block::LEN / FatDirEntry::LEN) as u8;\n\n let fs = self.cluster_iter.cluster_iter.fs;\n\n\n\n let cluster_opt = if self.counter == entry_per_block_count || self.is_first {\n", "file_path": "libfat/src/directory/raw_dir_entry_iterator.rs", "rank": 82, "score": 12.999794751008144 }, { "content": " }\n\n\n\n // Allocate a cluster for the directory entries\n\n let cluster = self.fs.alloc_cluster(None)?;\n\n\n\n let clear_res = self.fs.clean_cluster_data(cluster);\n\n\n\n if let Err(error) = clear_res {\n\n // If it fail here, this can be catastrophic but at least we tried our best.\n\n self.fs.free_cluster(cluster, None)?;\n\n return Err(error);\n\n }\n\n\n\n let new_entry_res = Self::create_dir_entry(\n\n self.fs,\n\n &self.dir_info,\n\n Attributes::new(Attributes::DIRECTORY),\n\n name,\n\n cluster,\n\n 0,\n", "file_path": "libfat/src/directory/mod.rs", "rank": 83, "score": 12.97296170949167 }, { "content": " {\n\n let mut entries_iter = FatDirEntryIterator::new(\n\n self.fs,\n\n old_raw_info.parent_cluster,\n\n old_raw_info.first_entry_block_index,\n\n old_raw_info.first_entry_offset,\n\n );\n\n\n\n let mut context: ShortFileNameContext = ShortFileNameContext::default();\n\n let short_file_name = ShortFileName::from_unformated_str(&mut context, new_name);\n\n\n\n let lfn_count = (new_name.len() as u32 + 12) / 13;\n\n let sfn_checksum = ShortFileName::checksum_lfn(&short_file_name.as_bytes());\n\n\n\n for index in 0..lfn_count {\n\n let target_index = lfn_count - index;\n\n let lfn_index = if target_index == lfn_count {\n\n 0x40u8 + target_index as u8\n\n } else {\n\n target_index as u8\n", "file_path": "libfat/src/directory/mod.rs", "rank": 84, "score": 12.889221740530294 }, { "content": "// TODO: Write a proper crate doc.\n\n//! The FAT library\n\n\n\n#![feature(alloc)]\n\n#![no_std]\n\n#![warn(\n\n clippy::cast_possible_wrap,\n\n clippy::cast_sign_loss,\n\n clippy::default_trait_access,\n\n clippy::explicit_into_iter_loop,\n\n clippy::explicit_iter_loop,\n\n clippy::missing_docs_in_private_items,\n\n clippy::mut_mut,\n\n clippy::replace_consts,\n\n clippy::used_underscore_binding,\n\n clippy::wildcard_dependencies,\n\n clippy::wrong_pub_self_convention\n\n)]\n\n\n\npub mod attribute;\n", "file_path": "libfat/src/lib.rs", "rank": 85, "score": 12.833122965701472 }, { "content": " }\n\n\n\n if offset >= u64::from(self.file_size) {\n\n return Ok(0);\n\n }\n\n\n\n let device: &T = &fs.block_device;\n\n\n\n let mut raw_tmp_offset = offset as u32;\n\n let mut cluster_offset = BlockIndex(raw_tmp_offset / Block::LEN_U32);\n\n let mut cluster_block_iterator =\n\n BlockIndexClusterIter::new(fs, self.start_cluster, Some(cluster_offset));\n\n let blocks_per_cluster = u32::from(fs.boot_record.blocks_per_cluster());\n\n\n\n let mut read_size = 0u64;\n\n let mut blocks = [Block::new()];\n\n\n\n while read_size < buf.len() as u64 {\n\n let cluster_opt = cluster_block_iterator.next();\n\n if cluster_opt.is_none() {\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 86, "score": 12.74977296491239 }, { "content": " let entry_count = target_dir.iter().filter(filter_fn).count() as u64;\n\n\n\n let mut data: [u8; DirectoryEntry::PATH_LEN] = [0x0; DirectoryEntry::PATH_LEN];\n\n for (index, c) in path\n\n .as_bytes()\n\n .iter()\n\n .enumerate()\n\n .take(DirectoryEntry::PATH_LEN)\n\n {\n\n data[index] = *c;\n\n }\n\n\n\n // Add '/' if missing at the end\n\n if let Some('/') = path.chars().last() {\n\n // Already valid\n\n } else {\n\n data[path.as_bytes().len()] = 0x2F;\n\n }\n\n\n\n let res = Box::new(DirectoryReader {\n", "file_path": "libfs_fat/src/lib.rs", "rank": 87, "score": 12.690189551379422 }, { "content": "//! High level directory entry representation.\n\nuse arrayvec::ArrayString;\n\n\n\nuse crate::attribute::Attributes;\n\nuse crate::block_iter::BlockIndexClusterIter;\n\nuse crate::cluster::Cluster;\n\nuse crate::filesystem::FatFileSystem;\n\nuse crate::table;\n\nuse crate::utils;\n\n\n\nuse libfs::block::{Block, BlockDevice, BlockIndex};\n\nuse libfs::FileSystemError;\n\nuse libfs::FileSystemResult;\n\n\n\nuse super::raw_dir_entry::FatDirEntry;\n\n\n\n#[derive(Debug, Clone, Copy)]\n\n/// Represent the information of a child entry into in it parent entry.\n\npub(crate) struct DirectoryEntryRawInfo {\n\n /// The first cluster of the parent entry.\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 88, "score": 12.57739079189555 }, { "content": " fn clone(&self) -> Self {\n\n Directory {\n\n dir_info: self.dir_info,\n\n fs: self.fs,\n\n }\n\n }\n\n}\n\n\n\nimpl<'a, T> Directory<'a, T>\n\nwhere\n\n T: BlockDevice,\n\n{\n\n /// Create a directory from a filesystem reference and a directory entry.\n\n pub fn from_entry(fs: &'a FatFileSystem<T>, dir_info: DirectoryEntry) -> Self {\n\n Directory { dir_info, fs }\n\n }\n\n\n\n /// Search an entry inside the directory and if found return it.\n\n pub fn find_entry(self, name: &str) -> FileSystemResult<DirectoryEntry> {\n\n if name.len() > DirectoryEntry::MAX_FILE_NAME_LEN_UNICODE {\n", "file_path": "libfat/src/directory/mod.rs", "rank": 89, "score": 12.534505117931134 }, { "content": " } else {\n\n return Err(FileSystemError::AccessDenied);\n\n }\n\n }\n\n\n\n let device: &T = &fs.block_device;\n\n\n\n let mut raw_tmp_offset = offset as u32;\n\n let mut cluster_offset = BlockIndex(raw_tmp_offset / Block::LEN_U32);\n\n let mut cluster_block_iterator =\n\n BlockIndexClusterIter::new(fs, self.start_cluster, Some(cluster_offset));\n\n let blocks_per_cluster = u32::from(fs.boot_record.blocks_per_cluster());\n\n\n\n let mut write_size = 0u64;\n\n let mut blocks = [Block::new()];\n\n\n\n while write_size < buf.len() as u64 {\n\n let cluster = cluster_block_iterator\n\n .next()\n\n .ok_or(FileSystemError::WriteFailed)?;\n", "file_path": "libfat/src/directory/dir_entry.rs", "rank": 90, "score": 12.52413259300275 }, { "content": "pub(crate) mod block_iter;\n\npub(crate) mod cluster;\n\npub mod datetime;\n\npub mod directory;\n\npub mod filesystem;\n\npub mod name;\n\npub(crate) mod table;\n\nmod utils;\n\n\n\nuse byteorder::{ByteOrder, LittleEndian};\n\nuse libfs::block::{Block, BlockCount, BlockDevice, BlockIndex};\n\n\n\nuse cluster::Cluster;\n\n\n\nuse filesystem::FatFileSystem;\n\n\n\nuse libfs::FileSystemError;\n\n\n\n/// Represent FAT filesystem types.\n\n#[derive(PartialEq)]\n", "file_path": "libfat/src/lib.rs", "rank": 91, "score": 12.229132415147825 }, { "content": " pub fn get<T>(fs: &FatFileSystem<T>, cluster: Cluster) -> Result<FatValue, FileSystemError>\n\n where\n\n T: BlockDevice,\n\n {\n\n let mut blocks = [Block::new()];\n\n\n\n let fat_offset = cluster.to_fat_offset();\n\n let cluster_block_index = cluster.to_fat_block_index(fs);\n\n let cluster_offset = (fat_offset % Block::LEN_U32) as usize;\n\n\n\n fs.block_device\n\n .read(&mut blocks, fs.partition_start, cluster_block_index)\n\n .or(Err(FileSystemError::ReadFailed))?;\n\n\n\n let res = FatValue::from_block(&blocks[0], cluster_offset);\n\n\n\n Ok(res)\n\n }\n\n\n\n /// Write the given ``FatValue``at a given ``Cluster`` in one FAT.\n", "file_path": "libfat/src/table.rs", "rank": 92, "score": 12.186105566163794 }, { "content": " pub fn root_dir_childs_count(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[17..19])\n\n }\n\n\n\n /// The total of blocks of the filesystem. If zero, uses ``total_blocks32``.\n\n pub fn total_blocks16(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[19..21])\n\n }\n\n\n\n /// Return the media type of the FAT filesystem.\n\n pub fn media_type(&self) -> u8 {\n\n self.data[21]\n\n }\n\n\n\n /// Return the size in cluster of the FAT for FAT12/FAT16 filesystems.\n\n pub fn fat_size16(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[22..24])\n\n }\n\n\n\n /// Physical blocks per track (INT 13h CHS geometry). Zero if unusued.\n", "file_path": "libfat/src/lib.rs", "rank": 93, "score": 12.03243515005726 }, { "content": " /// The entry is a file.\n\n File,\n\n /// The entry is a directory.\n\n Directory,\n\n}\n\n\n\n/// Represent an entry inside a directory.\n\npub struct DirectoryEntry {\n\n /// The path of the resource.\n\n pub path: [u8; Self::PATH_LEN],\n\n\n\n /// The type of the resource.\n\n pub entry_type: DirectoryEntryType,\n\n\n\n /// The size of the file. (0 if it's a directory)\n\n pub file_size: u64,\n\n}\n\n\n\nimpl DirectoryEntry {\n\n /// Represent the max path size (in bytes) supported.\n", "file_path": "libfs/src/lib.rs", "rank": 94, "score": 11.942645612855374 }, { "content": " pub fn blocks_per_track(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[24..26])\n\n }\n\n\n\n /// Number of heads (INT 13h CHS geometry). Zero if unused.\n\n pub fn num_heads(&self) -> u16 {\n\n LittleEndian::read_u16(&self.data[26..28])\n\n }\n\n\n\n /// The number of hidden blocks on the FAT filesystem.\n\n pub fn hidden_blocks(&self) -> u32 {\n\n LittleEndian::read_u32(&self.data[28..32])\n\n }\n\n\n\n /// The total block count on a FAT32 filesystem.\n\n pub fn total_blocks32(&self) -> u32 {\n\n LittleEndian::read_u32(&self.data[32..36])\n\n }\n\n\n\n /// Return the size in cluster of the FAT for FAT32 filesystems.\n", "file_path": "libfat/src/lib.rs", "rank": 95, "score": 11.93325589568984 }, { "content": " return Err(FileSystemError::PathTooLong);\n\n }\n\n\n\n let mut lowercase_name: ArrayString<[u8; DirectoryEntry::MAX_FILE_NAME_LEN_UNICODE]> =\n\n ArrayString::new();\n\n for c in name.chars() {\n\n lowercase_name.push(c.to_lowercase().next().unwrap());\n\n }\n\n\n\n for entry in self.iter() {\n\n let entry = entry?;\n\n\n\n let mut file_name: ArrayString<[u8; DirectoryEntry::MAX_FILE_NAME_LEN_UNICODE]> =\n\n ArrayString::new();\n\n\n\n for c in entry.file_name.as_str().chars() {\n\n file_name.push(c.to_lowercase().next().unwrap());\n\n }\n\n\n\n if file_name.as_str() == lowercase_name.as_str() {\n", "file_path": "libfat/src/directory/mod.rs", "rank": 96, "score": 11.625616961186156 }, { "content": " fn raw_put<T>(\n\n fs: &FatFileSystem<T>,\n\n cluster: Cluster,\n\n value: FatValue,\n\n fat_index: u32,\n\n ) -> Result<(), FileSystemError>\n\n where\n\n T: BlockDevice,\n\n {\n\n let mut blocks = [Block::new()];\n\n\n\n let fat_offset = cluster.to_fat_offset();\n\n let cluster_block_index =\n\n BlockIndex(cluster.to_fat_block_index(fs).0 + (fat_index * fs.boot_record.fat_size()));\n\n let cluster_offset = (fat_offset % Block::LEN_U32) as usize;\n\n\n\n fs.block_device\n\n .read(&mut blocks, fs.partition_start, cluster_block_index)\n\n .or(Err(FileSystemError::ReadFailed))?;\n\n\n", "file_path": "libfat/src/table.rs", "rank": 97, "score": 11.607288106271392 }, { "content": "\n\n /// Represent the end of a cluster chain.\n\n EndOfChain,\n\n}\n\n\n\n/// Util iterator used to simplify iteration over cluster.\n\npub struct FatClusterIter<'a, T> {\n\n /// The filesystem it belongs to.\n\n pub(crate) fs: &'a FatFileSystem<T>,\n\n\n\n /// The last cluster returned.\n\n current_cluster: Option<Cluster>,\n\n\n\n /// The last FatValue used.\n\n last_fat: Option<FatValue>,\n\n}\n\n\n\nimpl<'a, T> FatClusterIter<'a, T>\n\nwhere\n\n T: BlockDevice,\n", "file_path": "libfat/src/table.rs", "rank": 98, "score": 11.545293654537037 }, { "content": " last_access_timestamp: 0,\n\n last_modification_timestamp: 0,\n\n file_name: ArrayString::<[_; DirectoryEntry::MAX_FILE_NAME_LEN_UNICODE]>::new(),\n\n attribute: Attributes::new(Attributes::DIRECTORY),\n\n };\n\n\n\n Directory::from_entry(self, dir_info)\n\n }\n\n\n\n /// Create a new directory at the given path.\n\n pub fn mkdir(&self, path: &str) -> FileSystemResult<()> {\n\n let (parent_name, file_name) = utils::get_parent(path);\n\n let mut parent_dir = if parent_name == \"\" {\n\n self.get_root_directory()\n\n } else {\n\n self.get_root_directory().open_dir(parent_name)?\n\n };\n\n\n\n // precheck that it doesn't exist already\n\n if parent_dir.clone().find_entry(file_name).is_ok() {\n", "file_path": "libfat/src/filesystem.rs", "rank": 99, "score": 11.391426840450354 } ]
Rust
src/rust/bitbox02-rust/src/hww/api/ethereum/amount.rs
thisconnect/bitbox02-firmware
e081ac18dc28c2bdffdc58a94afa36a1bb5bade2
use alloc::string::String; use num_bigint::BigUint; pub struct Amount<'a> { pub unit: &'a str, pub decimals: usize, pub value: BigUint, } impl<'a> Amount<'a> { pub fn format(&self) -> String { const TRUNCATE_SIZE: usize = 13; let v = util::decimal::format(&self.value, self.decimals); if v.len() > TRUNCATE_SIZE { format!("{}... {}", &v[..TRUNCATE_SIZE], self.unit) } else { format!("{} {}", v, self.unit) } } } #[cfg(test)] mod tests { use super::*; #[test] pub fn test_format() { struct Test<'a> { bigendian: &'a [u8], decimals: usize, unit: &'a str, expected_result: &'a str, }; let tests = vec![ Test { bigendian: b"", decimals: 6, unit: "LOL", expected_result: "0 LOL", }, Test { bigendian: b"\x0f\x42\x40", decimals: 6, unit: "LOL", expected_result: "1 LOL", }, Test { bigendian: b"\x10\xc8\xe0", decimals: 6, unit: "LOL", expected_result: "1.1 LOL", }, Test { bigendian: b"\x20\x08\x1f\x97\x9a\x5c\x8d\x47\x29\x0e\x3e", decimals: 18, unit: "LOL", expected_result: "38723987.9327... LOL", }, Test { bigendian: b"\x01\xe2\x40", decimals: 8, unit: "LOL", expected_result: "0.00123456 LOL", }, Test { bigendian: b"\x01\xe2\x40", decimals: 8, unit: "LOL", expected_result: "0.00123456 LOL", }, Test { bigendian: b"\x1d\x00\xd3\x28\xcb", decimals: 10, unit: "LOL", expected_result: "12.4567890123 LOL", }, Test { bigendian: b"\x01\x22\x08\x3f\x97\xf2", decimals: 11, unit: "LOL", expected_result: "12.4567890123... LOL", }, ]; for test in tests.iter() { assert_eq!( Amount { unit: test.unit, decimals: test.decimals, value: BigUint::from_bytes_be(test.bigendian), } .format(), test.expected_result ); } } }
use alloc::string::String; use num_bigint::BigUint; pub struct Amount<'a> { pub unit: &'a str, pub decimals: usize, pub value: BigUint, } impl<'a> Amount<'a> { pub fn format(&self) -> String { const TRUNCATE_SIZE: usize = 13; let v = util::decimal::format(&self.value, self.decimals); if v.len() > TRUNCATE_SIZE { format!("{}... {}", &v[..TRUNCATE_SIZE], self.unit) } else { format!("{} {}", v, self.unit) } } } #[cfg(test)] mod tests { use super::*; #[test] pub fn test_format() { struct Test<'a> { bigendian: &'a [u8], decimals: usize, unit: &'a str, expected_result: &'a str, }; let tests = vec![ Test { bigendian: b"", decimals: 6, unit: "LOL", expected_result: "0 LOL", }, Test { bigendian: b"\x0f\x42\x40", decimals: 6, unit: "LOL", expected_result: "1 LOL", }, Test { bigendian: b"\x10\xc8\xe0", decimals: 6, unit: "LOL", expected_result: "1.1 LOL", }, Test { bigendian: b"\x20\x08\x1f\x97\x9a\x5c\x8d\x47\x29\x0e\x3e", decimals: 18, unit: "LOL", expected_result: "38723987.9327... LOL", }, Test { bigendian: b"\x01\xe2\x40", decimals: 8, unit: "LOL", expected_result: "0.00123456 LOL", }, Test { bigendian: b"\x01\xe2\x40", decimals: 8, unit: "LOL", expected_result: "0.00123456 LOL", }, Tes
}
t { bigendian: b"\x1d\x00\xd3\x28\xcb", decimals: 10, unit: "LOL", expected_result: "12.4567890123 LOL", }, Test { bigendian: b"\x01\x22\x08\x3f\x97\xf2", decimals: 11, unit: "LOL", expected_result: "12.4567890123... LOL", }, ]; for test in tests.iter() { assert_eq!( Amount { unit: test.unit, decimals: test.decimals, value: BigUint::from_bytes_be(test.bigendian), } .format(), test.expected_result ); } }
function_block-function_prefixed
[ { "content": "/// Formats integer `value` as `value / 10^decimals`, with up to `decimals` decimal places.\n\n/// E.g. \"123450\" with decimals=3: \"123.45\".\n\n/// Value must consists only of '0'-'9' digits.\n\npub fn format<F: Format>(value: F, decimals: usize) -> String {\n\n let mut v: String = format!(\"{:0>width$}\", value.to_string(), width = decimals + 1);\n\n v.insert(v.len() - decimals, '.');\n\n v.trim_end_matches('0').trim_end_matches('.').into()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_format_int() {\n\n assert_eq!(format(0u64, 0), \"0\");\n\n assert_eq!(format(0u64, 2), \"0\");\n\n assert_eq!(format(0u64, 6), \"0\");\n\n\n\n assert_eq!(format(1u64, 0), \"1\");\n\n assert_eq!(format(1u64, 1), \"0.1\");\n\n assert_eq!(format(1u64, 2), \"0.01\");\n\n assert_eq!(format(1u64, 6), \"0.000001\");\n", "file_path": "src/rust/util/src/decimal.rs", "rank": 0, "score": 487168.7620380739 }, { "content": "/// Converts a satoshi value to a string, suffixed with `unit`, e.g. 1234567890 -> \"12.3456789 BTC\".\n\npub fn format_amount(satoshi: u64, unit: &str) -> String {\n\n let mut s = util::decimal::format(satoshi, 8);\n\n s.push(' ');\n\n s.push_str(unit);\n\n s\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use alloc::vec::Vec;\n\n\n\n #[test]\n\n fn test_format_amount() {\n\n let tests: Vec<(u64, &str)> = vec![\n\n (1234567890, \"12.3456789 LOL\"),\n\n (0, \"0 LOL\"),\n\n (1, \"0.00000001 LOL\"),\n\n (2, \"0.00000002 LOL\"),\n\n (10, \"0.0000001 LOL\"),\n", "file_path": "src/rust/bitbox02-rust/src/apps/bitcoin/util.rs", "rank": 1, "score": 406917.1668596097 }, { "content": "/// Converts a Rust string to a null terminated C string by appending a null\n\n/// terminator. Returns `Err(())` if the input already contians a null byte.\n\npub fn str_to_cstr_vec(input: &str) -> Result<Vec<u8>, ()> {\n\n let bytes = input.as_bytes();\n\n if bytes.contains(&0) {\n\n Err(())\n\n } else {\n\n let mut out = Vec::with_capacity(input.len() + 1);\n\n out.extend_from_slice(bytes);\n\n out.push(0); // null terminator\n\n Ok(out)\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_truncate_str() {\n\n assert_eq!(truncate_str(\"test\", 0), \"\");\n\n assert_eq!(truncate_str(\"test\", 1), \"t\");\n", "file_path": "src/rust/bitbox02/src/util.rs", "rank": 2, "score": 387182.331843089 }, { "content": "/// Serialize a number in the VarInt encoding.\n\n/// https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer\n\npub fn serialize_varint(value: u64) -> Vec<u8> {\n\n let mut out: Vec<u8> = Vec::new();\n\n match value {\n\n 0..=0xFC => out.push(value as _),\n\n 0xFD..=0xFFFF => {\n\n out.push(0xFD);\n\n out.extend_from_slice(&(value as u16).to_le_bytes());\n\n }\n\n 0x10000..=0xFFFFFFFF => {\n\n out.push(0xFE);\n\n out.extend_from_slice(&(value as u32).to_le_bytes());\n\n }\n\n _ => {\n\n out.push(0xFF);\n\n out.extend_from_slice(&(value as u64).to_le_bytes());\n\n }\n\n }\n\n out\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/hww/api/bitcoin/script.rs", "rank": 3, "score": 343418.24738689093 }, { "content": "pub fn commander(input: Vec<u8>) -> Vec<u8> {\n\n let input = bitbox02_sys::in_buffer_t {\n\n data: input.as_ptr() as *const _,\n\n len: input.len() as _,\n\n };\n\n\n\n // Same as (USB_DATA_MAX_LEN - 2) (1 byte reserved for HWW_RSP_* code, 1 byte for\n\n // OP_STATUS_SUCCESS).\n\n const MAX_OUT_LEN: usize = 7607;\n\n let mut output_vec = Vec::with_capacity(MAX_OUT_LEN);\n\n let mut output = bitbox02_sys::buffer_t {\n\n data: output_vec.as_mut_ptr() as *mut _,\n\n len: 0,\n\n max_len: output_vec.capacity() as _,\n\n };\n\n unsafe {\n\n // Safety:\n\n // input is not NULL and the data length is correct.\n\n // output is not NULL and has the correct capacity.\n\n bitbox02_sys::commander(&input as *const _, &mut output as *mut _);\n\n // Safety: commander is guaranteed to set the number of bytes written\n\n // correctly.\n\n output_vec.set_len(output.len as _);\n\n };\n\n output_vec\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/commander.rs", "rank": 4, "score": 342082.85226144193 }, { "content": "pub fn bip39_mnemonic_to_seed(mnemonic: &str) -> Result<zeroize::Zeroizing<Vec<u8>>, ()> {\n\n let mnemonic = zeroize::Zeroizing::new(crate::util::str_to_cstr_vec(mnemonic)?);\n\n let mut seed = zeroize::Zeroizing::new([0u8; 32]);\n\n let mut seed_len: util::c_types::c_uint = 0;\n\n match unsafe {\n\n bitbox02_sys::keystore_bip39_mnemonic_to_seed(\n\n mnemonic.as_ptr(),\n\n seed.as_mut_ptr(),\n\n &mut seed_len,\n\n )\n\n } {\n\n true => Ok(zeroize::Zeroizing::new(seed[..seed_len as usize].to_vec())),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 5, "score": 339434.9885143779 }, { "content": "/// Return 5 words from the BIP39 wordlist, 4 of which are random, and\n\n/// one of them is provided `word`. Returns the position of `word` in\n\n/// the list of words, and the lis of words. This is used to test if\n\n/// the user wrote down the seed words properly.\n\nfn create_random_unique_words(word: &str, length: u8) -> (u8, Vec<zeroize::Zeroizing<String>>) {\n\n fn rand16() -> u16 {\n\n let mut rand = [0u8; 32];\n\n bitbox02::random::mcu_32_bytes(&mut rand);\n\n ((rand[0] as u16) << 8) | (rand[1] as u16)\n\n }\n\n\n\n let index_word = (rand16() as u8) % length;\n\n let mut picked_indices = Vec::new();\n\n let result = (0..length)\n\n .map(|i| {\n\n // The correct word at the right index.\n\n if i == index_word {\n\n return zeroize::Zeroizing::new(word.into());\n\n }\n\n\n\n // A random word everywhere else.\n\n // Loop until we get a unique word, we don't want repeated words in the list.\n\n loop {\n\n let idx = rand16() % keystore::BIP39_WORDLIST_LEN;\n", "file_path": "src/rust/bitbox02-rust/src/hww/api/show_mnemonic.rs", "rank": 6, "score": 338586.94441295025 }, { "content": "fn as_str_vec(v: &[zeroize::Zeroizing<String>]) -> Vec<&str> {\n\n v.iter().map(|s| s.as_str()).collect()\n\n}\n\n\n\n/// Displays all mnemonic words in a scroll-through screen.\n\npub async fn show_mnemonic(words: &[&str]) -> Result<(), CancelError> {\n\n let result = RefCell::new(None);\n\n let mut component = bitbox02::ui::menu_create(bitbox02::ui::MenuParams {\n\n words,\n\n title: None,\n\n select_word_cb: None,\n\n continue_on_last_cb: Some(Box::new(|| {\n\n set_result(&result, ());\n\n })),\n\n cancel_cb: Some(Box::new(|| {\n\n cancel(&result);\n\n })),\n\n });\n\n with_cancel(\"Recovery\\nwords\", &mut component, &result).await\n\n}\n", "file_path": "src/rust/bitbox02-rust/src/workflow/mnemonic.rs", "rank": 7, "score": 329862.9832299528 }, { "content": "/// Parses a utf-8 string out of a null terminated buffer. Returns `Err(())` if there\n\n/// is no null terminator or if the bytes before the null terminator is invalid UTF8.\n\npub fn str_from_null_terminated(input: &[u8]) -> Result<&str, ()> {\n\n let len = input.iter().position(|&c| c == 0).ok_or(())?;\n\n core::str::from_utf8(&input[0..len]).or(Err(()))\n\n}\n\n\n\n/// Macro for creating a stack allocated buffer with the content of a string and a null-terminator\n\n///\n\n/// Example usage:\n\n///\n\n/// ```\n\n/// # #[macro_use] extern crate bitbox02;\n\n/// let name = \"sample_string\";\n\n/// let buf = match str_to_cstr!(name, 50) {\n\n/// Ok(buf) => buf,\n\n/// Err(msg) => panic!(msg),\n\n/// };\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! str_to_cstr {\n\n ($input:expr, $len:expr) => {{\n", "file_path": "src/rust/bitbox02/src/util.rs", "rank": 8, "score": 310561.4464453897 }, { "content": "/// truncate_str truncates string `s` to `len` chars. If `s` is\n\n/// shorter than `len`, the string is returned unchanged (no panics).\n\npub fn truncate_str(s: &str, len: usize) -> &str {\n\n if s.len() > len {\n\n &s[..len]\n\n } else {\n\n s\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/util.rs", "rank": 9, "score": 309453.8123079273 }, { "content": "pub fn decrypt(msg: &[u8]) -> Result<Vec<u8>, Error> {\n\n NOISE_STATE.0.borrow_mut().decrypt(msg).or(Err(Error))\n\n}\n\n\n\n/// Process noise-encrypted messages:\n\n/// - Enforce handshake\n\n/// - Handle pairing verification\n\n/// - Enforce pairing confirmation if the remote party is seen for the first time\n\n/// - Remote party can invoke pairing confirmation anytime after the handshake\n\n/// - Decrypt, process, encrypt\n\n///\n\n/// The result is appended to `usb_out`.\n\n///\n\n/// Returns Err if anything goes wrong:\n\n/// - Invalid OP-code\n\n/// - Noise message in the wrong state (e.g. handshake before init, etc.).\n\npub(crate) async fn process(usb_in: Vec<u8>, usb_out: &mut Vec<u8>) -> Result<(), Error> {\n\n match usb_in.split_first() {\n\n Some((&OP_I_CAN_HAS_HANDSHAEK, b\"\")) => {\n\n // The previous screen was \"See the BitBoxApp\".\n", "file_path": "src/rust/bitbox02-rust/src/hww/noise.rs", "rank": 10, "score": 303021.8404388953 }, { "content": "/// Generates a checksummed ethereum hex address from a 20 byte recipient.\n\n/// `recipient` - 20 byte tail (last 20 bytes of the pubkeyhash).\n\npub fn from_pubkey_hash(recipient: &[u8; 20]) -> String {\n\n let mut hex = [0u8; 40];\n\n hex::encode_to_slice(recipient, &mut hex).unwrap();\n\n let hash = sha3::Keccak256::digest(&hex[..]);\n\n for (i, e) in hex.iter_mut().enumerate() {\n\n let hash_byte = {\n\n let b = hash[i / 2];\n\n if i % 2 == 0 {\n\n b >> 4\n\n } else {\n\n b & 0xf\n\n }\n\n };\n\n if *e > b'9' && hash_byte > 7 {\n\n *e -= 32; // convert to uppercase\n\n }\n\n }\n\n format!(\"0x{}\", unsafe {\n\n // valid utf8 because hex and the uppercasing above is correct.\n\n core::str::from_utf8_unchecked(&hex[..])\n\n })\n\n}\n\n\n", "file_path": "src/rust/apps/ethereum/src/address.rs", "rank": 11, "score": 299758.85582699615 }, { "content": "/// Generates a checksummed ethereum hex address from a 65 byte pubkey.\n\n/// `recipient` - 20 byte tail (last 20 bytes of the pubkeyhash).\n\npub fn from_pubkey(pubkey_uncompressed: &[u8; 65]) -> String {\n\n let hash = sha3::Keccak256::digest(&pubkey_uncompressed[1..]);\n\n from_pubkey_hash(hash[hash.len() - 20..].try_into().unwrap())\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use std::prelude::v1::*;\n\n\n\n #[test]\n\n fn test_from_pubkey_hash() {\n\n assert_eq!(\n\n from_pubkey_hash(\n\n b\"\\xf4\\xc2\\x17\\x10\\xef\\x8b\\x5a\\x5e\\xc4\\xbd\\x37\\x80\\xa6\\x87\\xfe\\x08\\x34\\x46\\xe6\\x7b\",\n\n ),\n\n \"0xF4C21710Ef8b5a5Ec4bd3780A687FE083446e67B\"\n\n );\n\n }\n\n\n", "file_path": "src/rust/apps/ethereum/src/address.rs", "rank": 12, "score": 299758.85582699615 }, { "content": "pub trait Format: ToString {}\n\n\n\nimpl Format for u64 {}\n\n\n\nimpl Format for &BigUint {}\n\n\n", "file_path": "src/rust/util/src/decimal.rs", "rank": 13, "score": 297485.6926939583 }, { "content": "/// Encodes a protobuf Response message.\n\npub fn encode(response: Response) -> Vec<u8> {\n\n let response = pb::Response {\n\n response: Some(response),\n\n };\n\n let mut out = Vec::<u8>::new();\n\n response.encode(&mut out).unwrap();\n\n out\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/hww/api.rs", "rank": 14, "score": 296614.5549077571 }, { "content": "pub fn encrypt(msg: &[u8], out: &mut Vec<u8>) -> Result<(), Error> {\n\n NOISE_STATE.0.borrow_mut().encrypt(msg, out).or(Err(Error))\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/hww/noise.rs", "rank": 15, "score": 291017.3376792981 }, { "content": "pub fn encrypt_and_store_seed(seed: &[u8], password: &str) -> Result<(), ()> {\n\n let password = zeroize::Zeroizing::new(crate::util::str_to_cstr_vec(password)?);\n\n match unsafe {\n\n bitbox02_sys::keystore_encrypt_and_store_seed(\n\n seed.as_ptr(),\n\n seed.len() as _,\n\n password.as_ptr(),\n\n )\n\n } {\n\n true => Ok(()),\n\n false => Err(()),\n\n }\n\n}\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 16, "score": 287091.37769205077 }, { "content": "/// Given 23 initial words, this function returns list of candidate words for the last word, such\n\n/// that the resulting bip39 phrase has a valid checksum. There are always exactly 8 such words.\n\n/// `entered_words` must contain 23 words from the BIP39 wordlist.\n\nfn lastword_choices(entered_words: &[&str]) -> Vec<zeroize::Zeroizing<String>> {\n\n if entered_words.len() != 23 {\n\n panic!(\"must have entered 23 words\");\n\n }\n\n\n\n // A 24 word seedphrase encodes 24*11 bits (33 bytes). The last byte is the checksum (hash over\n\n // the first 32 bytes). The last word, 11 bits, is the last 3 bits of the seed plus 8 bits of\n\n // the checksum. We first need the first 23 words converted to bytes so we can enumerate the 8\n\n // choices for the last word. libwally only lets us convert 24 words if the checksum\n\n // matches. Instead of rolling our own decoding function, we quickly find one valid word by\n\n // brute-force. We need to check at most 256 words for that, as there is exactly one valid word\n\n // for each 256 words block.\n\n let mut seed: zeroize::Zeroizing<Vec<u8>> = {\n\n let mut i = 0;\n\n loop {\n\n let mnemonic = zeroize::Zeroizing::new(format!(\n\n \"{} {}\",\n\n entered_words.join(\" \"),\n\n bitbox02::keystore::get_bip39_word(i).unwrap().as_str(),\n\n ));\n", "file_path": "src/rust/bitbox02-rust/src/workflow/mnemonic.rs", "rank": 17, "score": 281185.7339918576 }, { "content": "/// Validate a user given name. The name must be smaller or equal to `max_len` and larger than 0 in\n\n/// size, consist of printable ASCII characters only (and space), not\n\n/// start or end with whitespace, and contain no whitespace other than space.\n\npub fn validate(name: &str, max_len: usize) -> bool {\n\n if name.is_empty() || name.len() > max_len {\n\n return false;\n\n }\n\n if !ascii::is_printable_ascii(name, ascii::Charset::All) {\n\n return false;\n\n }\n\n // Safe because all_ascii passed.\n\n let bytes = name.as_bytes();\n\n if bytes[0] == b' ' || bytes[bytes.len() - 1] == b' ' {\n\n return false;\n\n }\n\n true\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n extern crate std;\n\n use super::*;\n\n\n", "file_path": "src/rust/util/src/name.rs", "rank": 18, "score": 275771.2591552617 }, { "content": "pub fn trinary_input_string_set_input(component: &mut Component, word: &str) {\n\n unsafe {\n\n bitbox02_sys::trinary_input_string_set_input(\n\n component.component,\n\n crate::str_to_cstr_force!(word, bitbox02_sys::INPUT_STRING_MAX_SIZE as usize).as_ptr(),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/ui/ui.rs", "rank": 19, "score": 263779.83201719425 }, { "content": "pub fn trinary_input_string_set_input(_component: &mut Component, _word: &str) {\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/ui/ui_stub.rs", "rank": 20, "score": 260983.65853316907 }, { "content": "pub fn create_and_store_seed(password: &SafeInputString, host_entropy: &[u8; 32]) -> bool {\n\n unsafe {\n\n bitbox02_sys::keystore_create_and_store_seed(password.as_cstr(), host_entropy.as_ptr())\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 21, "score": 259839.1398832391 }, { "content": "// ug_put_string displays a debug message on the screen for 3 sec.\n\npub fn ug_put_string(x: i16, y: i16, input: &str, inverted: bool) {\n\n match str_to_cstr!(input, 128) {\n\n Ok(buf) => unsafe {\n\n bitbox02_sys::UG_PutString(x, y, buf.as_ptr() as *const _, inverted);\n\n },\n\n Err(msg) => screen_print_debug(msg, 3000),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 22, "score": 259614.84977674356 }, { "content": "#[cfg(feature = \"testing\")]\n\npub fn format_datetime(_timestamp: u32, _timezone_offset: i32, date_only: bool) -> String {\n\n if date_only {\n\n \"<date>\".into()\n\n } else {\n\n \"<datetime>\".into()\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 23, "score": 259452.19430038496 }, { "content": "#[cfg(not(feature = \"testing\"))]\n\npub fn format_datetime(timestamp: u32, timezone_offset: i32, date_only: bool) -> String {\n\n let mut out = [0u8; 100];\n\n unsafe {\n\n bitbox02_sys::util_format_datetime(\n\n timestamp,\n\n timezone_offset,\n\n date_only,\n\n out.as_mut_ptr(),\n\n out.len() as _,\n\n )\n\n }\n\n crate::util::str_from_null_terminated(&out[..])\n\n .unwrap()\n\n .into()\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 24, "score": 259452.19430038496 }, { "content": "/// To be called in response to the host asking for the result of a\n\n/// task.\n\n///\n\n/// If a result is available (state = ResultAvailable), this copies\n\n/// the usb response to `dst` and moves the state to `Nothing`, and\n\n/// returns the Ok(<number of bytes written>).\n\n///\n\n/// If there is no task running, returns `Err(CopyResponseErr::NotReady)` if a task is pending and a\n\n/// response is expected in the future, or `Err(CopyResponseErr::NotRunning)` if no task is running.\n\npub fn copy_response(dst: &mut [u8]) -> Result<usize, CopyResponseErr> {\n\n let mut state = USB_TASK_STATE.0.borrow_mut();\n\n match *state {\n\n UsbTaskState::Nothing => Err(CopyResponseErr::NotRunning),\n\n UsbTaskState::Running(Some(_), ref mut next_request_state) => {\n\n if let WaitingForNextRequestState::SendingResponse(ref response) = next_request_state {\n\n let len = response.len();\n\n dst[..len].copy_from_slice(&response);\n\n *next_request_state = WaitingForNextRequestState::AwaitingRequest;\n\n Ok(len)\n\n } else {\n\n Err(CopyResponseErr::NotReady)\n\n }\n\n }\n\n UsbTaskState::Running(_, _) => Err(CopyResponseErr::NotReady),\n\n UsbTaskState::ResultAvailable(ref response) => {\n\n let len = response.len();\n\n dst[..len].copy_from_slice(&response);\n\n *state = UsbTaskState::Nothing;\n\n Ok(len)\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/async_usb.rs", "rank": 25, "score": 257089.3786821365 }, { "content": "/// Process OP_ATTESTATION.\n\n///\n\n/// On failure, returns < 1 >.\n\n///\n\n/// On success, returns < 0 | bootloader_hash 32 | device_pubkey 64 |\n\n/// certificate 64 | root_pubkey_identifier 32 | challenge_signature 64>\n\nfn api_attestation(usb_in: &[u8]) -> Vec<u8> {\n\n use core::convert::TryInto;\n\n\n\n let usb_in: [u8; 32] = match usb_in.try_into() {\n\n Ok(usb_in) => usb_in,\n\n Err(_) => return [OP_STATUS_FAILURE].to_vec(),\n\n };\n\n\n\n let result = match crate::attestation::perform(usb_in) {\n\n Ok(result) => result,\n\n Err(()) => return [OP_STATUS_FAILURE].to_vec(),\n\n };\n\n\n\n let mut out = Vec::with_capacity(257);\n\n out.push(OP_STATUS_SUCCESS);\n\n out.extend_from_slice(&result.bootloader_hash[..]);\n\n out.extend_from_slice(&result.device_pubkey[..]);\n\n out.extend_from_slice(&result.certificate[..]);\n\n out.extend_from_slice(&result.root_pubkey_identifier[..]);\n\n out.extend_from_slice(&result.challenge_signature[..]);\n", "file_path": "src/rust/bitbox02-rust/src/hww.rs", "rank": 26, "score": 256872.7472087147 }, { "content": "pub fn get_device_name() -> String {\n\n let mut name = [0u8; DEVICE_NAME_MAX_LEN + 1];\n\n unsafe { bitbox02_sys::memory_get_device_name(name.as_mut_ptr()) }\n\n crate::util::str_from_null_terminated(&name[..])\n\n .unwrap()\n\n .into()\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 27, "score": 253768.49018949136 }, { "content": "pub fn get_device_name() -> String {\n\n \"test device name\".into()\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 28, "score": 251240.2816425229 }, { "content": "/// Turn a keypath represented as a list of u32 to a string, e.g. \"m/84'/0'/0'\". Hardened elements\n\n/// are bigger or equal to `HARDENED`\n\npub fn to_string(keypath: &[u32]) -> String {\n\n let s = keypath\n\n .iter()\n\n .map(|&el| {\n\n if el >= HARDENED {\n\n format!(\"{}'\", el - HARDENED)\n\n } else {\n\n format!(\"{}\", el)\n\n }\n\n })\n\n .collect::<Vec<_>>()\n\n .join(\"/\");\n\n // Prepend \"m/\".\n\n format!(\"m/{}\", s)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n extern crate std;\n\n use super::*;\n", "file_path": "src/rust/util/src/bip32.rs", "rank": 29, "score": 249113.17021993897 }, { "content": "/// This mocks an unlocked keystore with a fixed bip39 seed based on these bip39 recovery words:\n\n/// `purity concert above invest pigeon category peace tuition hazard vivid latin since legal speak nation session onion library travel spell region blast estate stay`\n\npub fn mock_unlocked() {\n\n let seed: [u8; 32] = keystore::bip39_mnemonic_to_seed(\"purity concert above invest pigeon category peace tuition hazard vivid latin since legal speak nation session onion library travel spell region blast estate stay\").unwrap().as_slice().try_into().unwrap();\n\n unsafe { bitbox02_sys::mock_state(seed.as_ptr(), core::ptr::null()) }\n\n keystore::unlock_bip39(&crate::input::SafeInputString::new()).unwrap();\n\n}\n", "file_path": "src/rust/bitbox02/src/testing.rs", "rank": 30, "score": 244008.6028337322 }, { "content": "#[cfg(feature = \"testing\")]\n\npub fn version_short() -> &'static str {\n\n \"9.2.0-testing\"\n\n}\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 31, "score": 243526.79249803635 }, { "content": "/// Resolves the `next_request()` future. `waiting_for_next_request()` must be true when calling\n\n/// this, otherwise this function panics.\n\npub fn on_next_request(usb_in: &[u8]) {\n\n let mut state = USB_TASK_STATE.0.borrow_mut();\n\n match *state {\n\n UsbTaskState::Running(\n\n Some(_),\n\n ref mut next_request_state @ WaitingForNextRequestState::AwaitingRequest,\n\n ) => {\n\n // Resolve NEXT_REQUEST future.\n\n *NEXT_REQUEST.0.borrow_mut() = Some(usb_in.to_vec());\n\n\n\n *next_request_state = WaitingForNextRequestState::Idle;\n\n }\n\n _ => panic!(\"on_next_request: wrong state\"),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/async_usb.rs", "rank": 32, "score": 238522.39480977305 }, { "content": "pub fn sha256(input: &[u8], output: &mut [u8]) -> Result<(), ()> {\n\n let res = unsafe {\n\n bitbox02_sys::wally_sha256(\n\n input.as_ptr(),\n\n input.len() as _,\n\n output.as_mut_ptr(),\n\n output.len() as _,\n\n )\n\n };\n\n if res == bitbox02_sys::WALLY_OK as i32 {\n\n Ok(())\n\n } else {\n\n Err(())\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 33, "score": 237517.2468899674 }, { "content": "/// Guaranteed to wipe the provided buffer\n\npub fn zero(dst: &mut [u8]) {\n\n for p in dst {\n\n unsafe { core::ptr::write_volatile(p, 0) };\n\n }\n\n}\n\n\n\n/// Survive forces T to live at least as long as lifetme 'a.\n\npub struct Survive<'a, T: 'a> {\n\n pub data: T,\n\n phantom: core::marker::PhantomData<&'a T>,\n\n}\n\n\n\nimpl<'a, T> Survive<'a, T> {\n\n pub fn new(data: T) -> Self {\n\n Survive {\n\n data,\n\n phantom: core::marker::PhantomData,\n\n }\n\n }\n\n}\n", "file_path": "src/rust/util/src/lib.rs", "rank": 34, "score": 235792.82972857537 }, { "content": "pub fn root_fingerprint() -> Result<[u8; 4], ()> {\n\n let mut fingerprint = [0u8; 4];\n\n match unsafe { bitbox02_sys::keystore_get_root_fingerprint(fingerprint.as_mut_ptr()) } {\n\n true => Ok(fingerprint),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 35, "score": 235792.82972857537 }, { "content": "pub fn bootloader_hash(out: &mut [u8; 32]) {\n\n unsafe {\n\n bitbox02_sys::memory_bootloader_hash(out.as_mut_ptr());\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/securechip.rs", "rank": 36, "score": 229788.236516674 }, { "content": "pub fn bootloader_hash(out: &mut [u8; 32]) {\n\n unsafe {\n\n bitbox02_sys::memory_bootloader_hash(out.as_mut_ptr());\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 37, "score": 229788.236516674 }, { "content": "#[cfg(target_arch = \"x86_64\")]\n\npub fn mcu_32_bytes(out: &mut [u8; 32]) {\n\n extern \"C\" {\n\n fn rand() -> util::c_types::c_int;\n\n }\n\n\n\n for elem in out.iter_mut() {\n\n // Not uniform, but it's only for tests...\n\n *elem = unsafe { rand() as _ };\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_mcu_32_bytes() {\n\n let mut result = [0; 32];\n\n mcu_32_bytes(&mut result);\n\n assert!([0; 32] != result);\n\n }\n\n}\n", "file_path": "src/rust/bitbox02/src/random.rs", "rank": 38, "score": 229788.236516674 }, { "content": "pub fn attestation_sign(challenge: &[u8; 32], signature: &mut [u8; 64]) -> Result<(), ()> {\n\n match unsafe {\n\n bitbox02_sys::securechip_attestation_sign(challenge.as_ptr(), signature.as_mut_ptr())\n\n } {\n\n true => Ok(()),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/securechip.rs", "rank": 39, "score": 228168.87231022885 }, { "content": "/// Spawn a task to be spinned by the executor. This moves the state\n\n/// from Nothing to Running.\n\n///\n\n/// *panics* - can only be called if the state is Nothing, otherwise panics.\n\npub fn spawn<F>(workflow: fn(UsbIn) -> F, usb_in: &[u8])\n\nwhere\n\n F: core::future::Future<Output = UsbOut> + 'static,\n\n{\n\n let mut state = USB_TASK_STATE.0.borrow_mut();\n\n match *state {\n\n UsbTaskState::Nothing => {\n\n let task: Task<UsbOut> = Box::pin(workflow(usb_in.to_vec()));\n\n\n\n *state = UsbTaskState::Running(Some(task), WaitingForNextRequestState::Idle);\n\n }\n\n _ => panic!(\"spawn: wrong state\"),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/async_usb.rs", "rank": 40, "score": 227302.30909968363 }, { "content": "pub fn bootloader_hash(_out: &mut [u8; 32]) {\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 41, "score": 227259.5740200968 }, { "content": "/// Provide mock implementations and data. This also locks the keystore - use `mock_unlocked()` to mock a seeded and unlocked keystore.\n\npub fn mock(data: Data) {\n\n *DATA.0.borrow_mut() = data;\n\n keystore::lock();\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/testing.rs", "rank": 42, "score": 224901.40000954084 }, { "content": "/// `name.as_bytes()` must be smaller or equal to\n\n/// `DEVICE_NAME_MAX_LEN`, otherwise this function panics.\n\npub fn set_device_name(name: &str) -> Result<(), Error> {\n\n match unsafe {\n\n bitbox02_sys::memory_set_device_name(\n\n crate::str_to_cstr_force!(name, DEVICE_NAME_MAX_LEN).as_ptr(),\n\n )\n\n } {\n\n true => Ok(()),\n\n false => Err(Error),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 43, "score": 222416.7404272161 }, { "content": "pub fn screen_print_debug(msg: &str, duration: i32) {\n\n match str_to_cstr!(msg, 200) {\n\n Ok(cstr) => unsafe {\n\n bitbox02_sys::screen_print_debug(cstr.as_ptr() as *const _, duration)\n\n },\n\n Err(errmsg) => unsafe {\n\n bitbox02_sys::screen_print_debug(\n\n str_to_cstr_force!(errmsg, 200).as_ptr() as *const _,\n\n duration,\n\n )\n\n },\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/lib.rs", "rank": 44, "score": 222416.7404272161 }, { "content": "/// Compute the BIP143 signature hash:\n\n/// https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#specification\n\npub fn sighash(args: &Args) -> [u8; 32] {\n\n let mut ctx = Sha256::new();\n\n // https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#specification\n\n // 1.\n\n ctx.update(args.version.to_le_bytes());\n\n // 2.\n\n ctx.update(args.hash_prevouts);\n\n // 3.\n\n ctx.update(args.hash_sequence);\n\n // 4.\n\n ctx.update(args.outpoint_hash);\n\n ctx.update(args.outpoint_index.to_le_bytes());\n\n // 5.\n\n ctx.update(args.sighash_script);\n\n // 6.\n\n ctx.update(args.prevout_value.to_le_bytes());\n\n // 7.\n\n ctx.update(args.sequence.to_le_bytes());\n\n // 8.\n\n ctx.update(args.hash_outputs);\n", "file_path": "src/rust/bitbox02-rust/src/apps/bitcoin/bip143.rs", "rank": 45, "score": 222407.69183386752 }, { "content": "pub fn get_bip39_mnemonic() -> Result<zeroize::Zeroizing<String>, ()> {\n\n let mut mnemonic = zeroize::Zeroizing::new(ZeroizedMnemonic([0u8; 256]));\n\n match unsafe {\n\n bitbox02_sys::keystore_get_bip39_mnemonic(mnemonic.0.as_mut_ptr(), mnemonic.0.len() as _)\n\n } {\n\n false => Err(()),\n\n true => Ok(zeroize::Zeroizing::new(\n\n crate::util::str_from_null_terminated(&mnemonic.0[..])\n\n .unwrap()\n\n .into(),\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 46, "score": 222380.14257804246 }, { "content": "pub fn set_device_name(name: &str) -> Result<(), Error> {\n\n let data = crate::testing::DATA.0.borrow();\n\n data.memory_set_device_name.as_ref().unwrap()(name)\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 47, "score": 220087.95040194452 }, { "content": "pub fn add_noise_remote_static_pubkey(pubkey: &[u8; 32]) -> Result<(), ()> {\n\n match unsafe { bitbox02_sys::memory_add_noise_remote_static_pubkey(pubkey.as_ptr()) } {\n\n true => Ok(()),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 48, "score": 220078.9826989128 }, { "content": "pub fn check_noise_remote_static_pubkey(pubkey: &[u8; 32]) -> bool {\n\n unsafe { bitbox02_sys::memory_check_noise_remote_static_pubkey(pubkey.as_ptr()) }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 49, "score": 220078.9826989128 }, { "content": "/// Creates a trinary input component.\n\n/// `result` - will be asynchronously set to `Some(<password>)` once the user confirms.\n\npub fn trinary_input_string_create<'a, F>(\n\n params: &TrinaryInputStringParams,\n\n confirm_callback: F,\n\n cancel_callback: Option<ContinueCancelCb<'a>>,\n\n) -> Component<'a>\n\nwhere\n\n // Callback must outlive component.\n\n F: FnMut(SafeInputString) + 'a,\n\n{\n\n unsafe extern \"C\" fn c_confirm_callback<F2>(password: *const c_char, param: *mut c_void)\n\n where\n\n F2: FnMut(SafeInputString),\n\n {\n\n let mut password_out = SafeInputString::new();\n\n let cap = password_out.cap();\n\n password_out\n\n .as_mut()\n\n .copy_from_slice(core::slice::from_raw_parts(password, cap));\n\n // The callback is dropped afterwards. This is safe because\n\n // this C callback is guaranteed to be called only once.\n", "file_path": "src/rust/bitbox02/src/ui/ui.rs", "rank": 50, "score": 217866.39848341636 }, { "content": "pub fn print_debug_internal(duration: Duration, msg: &str) {\n\n ug_clear_buffer();\n\n ug_font_select_9x9();\n\n ug_put_string(0, 0, msg, false);\n\n ug_send_buffer();\n\n delay(duration);\n\n}\n\n\n\n/// This is a convenience macro for printing to the screen.\n\n///\n\n/// Example usage:\n\n///\n\n/// ```no_run\n\n/// # #[macro_use] extern crate bitbox02_rust; fn main() {\n\n/// let my_str = \"abc\";\n\n/// print_debug!(1000, \"{}\", &my_str);\n\n/// # }\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! print_debug {\n\n ($duration:expr, $($arg:tt)*) => ({\n\n use core::fmt::Write;\n\n let duration = core::time::Duration::from_millis($duration);\n\n let mut buf = $crate::arrayvec::ArrayString::<[_; 256]>::new();\n\n let _ = write!(buf, $($arg)*);\n\n $crate::general::screen::print_debug_internal(duration, &buf);\n\n })\n\n}\n", "file_path": "src/rust/bitbox02-rust/src/general/screen.rs", "rank": 51, "score": 217820.56542572234 }, { "content": "pub fn add_noise_remote_static_pubkey(_pubkey: &[u8; 32]) -> Result<(), ()> {\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 52, "score": 217811.6764801084 }, { "content": "pub fn check_noise_remote_static_pubkey(_pubkey: &[u8; 32]) -> bool {\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 53, "score": 217811.6764801084 }, { "content": "pub fn perform(host_challenge: [u8; 32]) -> Result<Data, ()> {\n\n let mut result = Data {\n\n bootloader_hash: [0; 32],\n\n device_pubkey: [0; 64],\n\n certificate: [0; 64],\n\n root_pubkey_identifier: [0; 32],\n\n challenge_signature: [0; 64],\n\n };\n\n bitbox02::memory::get_attestation_pubkey_and_certificate(\n\n &mut result.device_pubkey,\n\n &mut result.certificate,\n\n &mut result.root_pubkey_identifier,\n\n )?;\n\n let mut hash: [u8; 32] = [0; 32];\n\n bitbox02::sha256(&host_challenge[..], &mut hash[..])?;\n\n bitbox02::memory::bootloader_hash(&mut result.bootloader_hash);\n\n bitbox02::securechip::attestation_sign(&hash, &mut result.challenge_signature)?;\n\n Ok(result)\n\n}\n", "file_path": "src/rust/bitbox02-rust/src/attestation.rs", "rank": 54, "score": 217602.68277128958 }, { "content": "pub fn sighash(params: SighashParams) -> Result<[u8; 32], ()> {\n\n let mut sighash_out = [0u8; 32];\n\n let result = unsafe {\n\n bitbox02_sys::app_eth_sighash(\n\n bitbox02_sys::eth_sighash_params_t {\n\n nonce: in_buffer_t {\n\n data: params.nonce.as_ptr(),\n\n len: params.nonce.len() as _,\n\n },\n\n gas_price: in_buffer_t {\n\n data: params.gas_price.as_ptr(),\n\n len: params.gas_price.len() as _,\n\n },\n\n gas_limit: in_buffer_t {\n\n data: params.gas_limit.as_ptr(),\n\n len: params.gas_limit.len() as _,\n\n },\n\n recipient: in_buffer_t {\n\n data: params.recipient.as_ptr(),\n\n len: params.recipient.len() as _,\n", "file_path": "src/rust/bitbox02/src/app_eth.rs", "rank": 55, "score": 217602.68277128958 }, { "content": "pub fn trinary_input_string_create<'a, F>(\n\n _params: &TrinaryInputStringParams,\n\n _confirm_callback: F,\n\n _cancel_callback: Option<ContinueCancelCb<'a>>,\n\n) -> Component<'a>\n\nwhere\n\n F: FnMut(SafeInputString) + 'a,\n\n{\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/ui/ui_stub.rs", "rank": 56, "score": 215474.18736378546 }, { "content": "/// Decodes a protofbuf Request message.\n\npub fn decode(input: &[u8]) -> Result<Request, Error> {\n\n match pb::Request::decode(input) {\n\n Ok(pb::Request {\n\n request: Some(request),\n\n }) => Ok(request),\n\n _ => Err(Error::InvalidInput),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02-rust/src/hww/api.rs", "rank": 57, "score": 215273.97363633482 }, { "content": "pub fn get_noise_static_private_key() -> Result<zeroize::Zeroizing<[u8; 32]>, ()> {\n\n let mut out = zeroize::Zeroizing::new([0u8; 32]);\n\n match unsafe { bitbox02_sys::memory_get_noise_static_private_key(out.as_mut_ptr()) } {\n\n true => Ok(out),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory.rs", "rank": 58, "score": 213006.66741753044 }, { "content": "pub fn get_noise_static_private_key() -> Result<zeroize::Zeroizing<[u8; 32]>, ()> {\n\n panic!(\"not implemented\")\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/memory_stub.rs", "rank": 59, "score": 210798.36712760158 }, { "content": "static void _test_util_string_validate_name(void** state)\n\n{\n\n // Max len.\n\n assert_true(util_string_validate_name(\"foo\", 5));\n\n assert_true(util_string_validate_name(\"foo\", 4));\n\n assert_true(util_string_validate_name(\"foo\", 3));\n\n assert_false(util_string_validate_name(\"foo\", 2));\n\n\n\n // Ascii.\n\n assert_true(util_string_validate_name(_all_ascii, 100));\n\n assert_false(util_string_validate_name(\"\\n\", 100));\n\n assert_false(util_string_validate_name(\"\\t\", 100));\n\n\n\n // Starts / ends with space.\n\n assert_false(util_string_validate_name(\" foo\", 100));\n\n assert_false(util_string_validate_name(\"foo \", 100));\n\n\n\n // Can contain space otherwise.\n\n assert_true(util_string_validate_name(\"hello world\", 100));\n\n\n\n // Empty string.\n\n assert_false(util_string_validate_name(\"\", 100));\n", "file_path": "test/unit-test/test_util_string.c", "rank": 60, "score": 209153.21237067215 }, { "content": "/// `idx` must be smaller than BIP39_WORDLIST_LEN.\n\npub fn get_bip39_word(idx: u16) -> Result<zeroize::Zeroizing<String>, ()> {\n\n let mut word_ptr: *mut u8 = core::ptr::null_mut();\n\n match unsafe { bitbox02_sys::keystore_get_bip39_word(idx, &mut word_ptr) } {\n\n false => Err(()),\n\n true => {\n\n let word = unsafe {\n\n let len = crate::util::strlen_ptr(word_ptr);\n\n let slice = core::slice::from_raw_parts(word_ptr, len as _);\n\n zeroize::Zeroizing::new(core::str::from_utf8(&slice[..]).unwrap().into())\n\n };\n\n unsafe {\n\n bitbox02_sys::wally_free_string(word_ptr as _);\n\n }\n\n Ok(word)\n\n }\n\n }\n\n}\n\n\n\n/// An opaque C type which gives access to all BIP39 words.\n\npub struct Bip39Wordlist([*const u8; BIP39_WORDLIST_LEN as usize]);\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 61, "score": 209047.00985496302 }, { "content": "pub fn coin_name(coin: pb::BtcCoin) -> &'static str {\n\n use pb::BtcCoin::*;\n\n match coin {\n\n Btc => \"Bitcoin\",\n\n Tbtc => \"BTC Testnet\",\n\n Ltc => \"Litecoin\",\n\n Tltc => \"LTC Testnet\",\n\n }\n\n}\n\n\n\n/// Processes an xpub api call.\n\nasync fn xpub(\n\n coin: BtcCoin,\n\n xpub_type: XPubType,\n\n keypath: &[u32],\n\n display: bool,\n\n) -> Result<Response, Error> {\n\n let params = params::get(coin);\n\n bitcoin::keypath::validate_xpub(keypath, params.bip44_coin)?;\n\n let xpub_type = match xpub_type {\n", "file_path": "src/rust/bitbox02-rust/src/hww/api/bitcoin.rs", "rank": 62, "score": 208655.2373773794 }, { "content": "pub fn unlock(password: &SafeInputString) -> Result<(), Error> {\n\n let mut remaining_attempts: u8 = 0;\n\n match unsafe { bitbox02_sys::keystore_unlock(password.as_cstr(), &mut remaining_attempts) } {\n\n keystore_error_t::KEYSTORE_OK => Ok(()),\n\n keystore_error_t::KEYSTORE_ERR_INCORRECT_PASSWORD => {\n\n Err(Error::IncorrectPassword { remaining_attempts })\n\n }\n\n keystore_error_t::KEYSTORE_ERR_MAX_ATTEMPTS_EXCEEDED => Err(Error::Unknown),\n\n keystore_error_t::KEYSTORE_ERR_GENERIC => Err(Error::Unknown),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 63, "score": 206329.63922803663 }, { "content": "#[cfg(feature = \"testing\")]\n\npub fn encode_xpub_at_keypath(keypath: &[u32], xpub_type: xpub_type_t) -> Result<String, ()> {\n\n let data = crate::testing::DATA.0.borrow();\n\n data.keystore_encode_xpub_at_keypath.as_ref().unwrap()(keypath, xpub_type)\n\n}\n\n\n\npub struct SignResult {\n\n pub signature: [u8; 64],\n\n pub recid: u8,\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 64, "score": 204694.2587022653 }, { "content": "pub fn unlock_bip39(mnemonic_passphrase: &SafeInputString) -> Result<(), Error> {\n\n if unsafe { bitbox02_sys::keystore_unlock_bip39(mnemonic_passphrase.as_cstr()) } {\n\n Ok(())\n\n } else {\n\n Err(Error::CannotUnlockBIP39)\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 65, "score": 201734.44895843716 }, { "content": "/// Returns true if all bytes are in the given `charset`.\n\npub fn is_printable_ascii<T: AsRef<[u8]>>(bytes: T, charset: Charset) -> bool {\n\n bytes\n\n .as_ref()\n\n .iter()\n\n .all(|&b| (b >= 32 && b <= 126) || (charset == Charset::AllNewline && b == b'\\n'))\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n extern crate std;\n\n use super::*;\n\n\n\n static ALL_ASCII: &[u8] = \"! \\\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\".as_bytes();\n\n\n\n #[test]\n\n fn test_is_printable_ascii() {\n\n // All ascii chars.\n\n assert!(is_printable_ascii(ALL_ASCII, Charset::All));\n\n // Edge cases: highest and lowest non ascii chars.\n\n assert!(!is_printable_ascii(b\"\\x7f\", Charset::All));\n", "file_path": "src/rust/util/src/ascii.rs", "rank": 66, "score": 200814.94061912093 }, { "content": "static const char* _all_ascii =\n\n \"! \\\"#$%&\\'()*+,-./\"\n", "file_path": "test/unit-test/test_util_string.c", "rank": 67, "score": 199787.64772033293 }, { "content": "int main(void)\n\n{\n\n const struct CMUnitTest tests[] = {\n\n cmocka_unit_test(_test_util_string_validate_name),\n\n };\n\n return cmocka_run_group_tests(tests, NULL, NULL);\n", "file_path": "test/unit-test/test_util_string.c", "rank": 68, "score": 199787.64772033293 }, { "content": "static void test_util_format_datetime(void** state)\n\n{\n\n char out[100];\n\n util_format_datetime(1601281809, 0, true, out, sizeof(out));\n\n assert_string_equal(out, \"Mon 2020-09-28\");\n\n\n\n util_format_datetime(1601281809, 0, false, out, sizeof(out));\n\n assert_string_equal(out, \"Mon 2020-09-28\\n08:30\");\n\n\n\n util_format_datetime(1601281809, 18000, false, out, sizeof(out));\n\n assert_string_equal(out, \"Mon 2020-09-28\\n13:30\");\n\n\n\n util_format_datetime(1601281809, -32400, false, out, sizeof(out));\n\n assert_string_equal(out, \"Sun 2020-09-27\\n23:30\");\n", "file_path": "test/unit-test/test_util.c", "rank": 69, "score": 198990.5455898087 }, { "content": "static void _check_pubs(\n\n const char* expected_xpub,\n\n const char* expected_hash160_hex,\n\n const char* expected_pubkey_uncompressed_hex)\n\n{\n\n struct ext_key __attribute__((__cleanup__(keystore_zero_xkey))) xpub;\n\n uint32_t keypath[] = {\n\n 44 + BIP32_INITIAL_HARDENED_CHILD,\n\n 0 + BIP32_INITIAL_HARDENED_CHILD,\n\n 0 + BIP32_INITIAL_HARDENED_CHILD,\n\n 1,\n\n 2,\n\n };\n\n\n\n assert_true(keystore_get_xpub(keypath, 3, &xpub));\n\n char xpub_serialized[120];\n\n assert_true(keystore_encode_xpub(&xpub, XPUB, xpub_serialized, sizeof(xpub_serialized)));\n\n assert_string_equal(xpub_serialized, expected_xpub);\n\n\n\n uint8_t hash160[20];\n\n assert_true(keystore_secp256k1_pubkey_hash160(keypath, 5, hash160));\n\n _assert_equal_memory_hex(hash160, sizeof(hash160), expected_hash160_hex);\n\n\n\n uint8_t pubkey_uncompressed[EC_PUBLIC_KEY_UNCOMPRESSED_LEN];\n\n assert_true(keystore_secp256k1_pubkey_uncompressed(keypath, 5, pubkey_uncompressed));\n\n _assert_equal_memory_hex(\n\n pubkey_uncompressed, sizeof(pubkey_uncompressed), expected_pubkey_uncompressed_hex);\n", "file_path": "test/unit-test/test_keystore_functional.c", "rank": 70, "score": 197591.97617047277 }, { "content": "static void _test_wrong_output_value(void** state)\n\n{\n\n _modification_t invalid = _valid;\n\n invalid.wrong_output_value = true;\n\n _sign(&invalid);\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 71, "score": 197004.55434729936 }, { "content": "static void _test_input_wrong_value(void** state)\n\n{\n\n _modification_t invalid = _valid;\n\n invalid.input_wrong_value = true;\n\n _sign(&invalid);\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 72, "score": 197004.55434729936 }, { "content": "static void _test_wrong_input_value(void** state)\n\n{\n\n _modification_t invalid = _valid;\n\n invalid.wrong_input_value = true;\n\n _sign(&invalid);\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 73, "score": 197004.55434729936 }, { "content": " bool input_wrong_value;\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 74, "score": 195550.71265958474 }, { "content": " bool wrong_input_value;\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 75, "score": 195550.15726962796 }, { "content": " bool wrong_output_value;\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 76, "score": 195543.64069301914 }, { "content": "static void _test_overflow_input_values_pass2(void** state)\n\n{\n\n _modification_t invalid = _valid;\n\n invalid.overflow_input_values_pass2 = true;\n\n _sign(&invalid);\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 77, "score": 195071.3617331502 }, { "content": "static void _test_overflow_input_values_pass1(void** state)\n\n{\n\n _modification_t invalid = _valid;\n\n invalid.overflow_input_values_pass1 = true;\n\n _sign(&invalid);\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 78, "score": 195071.3617331502 }, { "content": "static void update_V(uECC_HashContext* hash_context, uint8_t* K, uint8_t* V)\n\n{\n\n HMAC_init(hash_context, K);\n\n HMAC_update(hash_context, V, hash_context->result_size);\n\n HMAC_finish(hash_context, K, V);\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 79, "score": 194039.85402741836 }, { "content": " bool overflow_input_values_pass1;\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 80, "score": 193484.25713663152 }, { "content": " bool overflow_input_values_pass2;\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 81, "score": 193478.10873967625 }, { "content": "pub fn status_create<'a, F>(text: &str, status_success: bool, callback: F) -> Component<'a>\n\nwhere\n\n // Callback must outlive component.\n\n F: FnMut() + 'a,\n\n{\n\n unsafe extern \"C\" fn c_callback<F2>(param: *mut c_void)\n\n where\n\n F2: FnMut(),\n\n {\n\n // The callback is dropped afterwards. This is safe because\n\n // this C callback is guaranteed to be called only once.\n\n let mut callback = Box::from_raw(param as *mut F2);\n\n callback();\n\n }\n\n\n\n let component = unsafe {\n\n bitbox02_sys::status_create(\n\n crate::str_to_cstr_force!(text, MAX_LABEL_SIZE).as_ptr(), // copied in C\n\n status_success,\n\n Some(c_callback::<F>),\n", "file_path": "src/rust/bitbox02/src/ui/ui.rs", "rank": 82, "score": 192135.12324096423 }, { "content": "void __wrap_rust_bitcoin_util_format_amount(uint64_t satoshi, CStr unit, CStrMut out)\n\n{\n\n check_expected(satoshi);\n\n check_expected(unit.buf);\n\n snprintf(out.buf, out.cap, \"%s\", (const char*)(mock()));\n", "file_path": "test/unit-test/test_btc_sign.c", "rank": 83, "score": 189496.33679911512 }, { "content": "static const sha2_word64 sha512_initial_hash_value[8] = {0x6a09e667f3bcc908ULL,\n\n 0xbb67ae8584caa73bULL,\n\n 0x3c6ef372fe94f82bULL,\n\n 0xa54ff53a5f1d36f1ULL,\n\n 0x510e527fade682d1ULL,\n\n 0x9b05688c2b3e6c1fULL,\n\n 0x1f83d9abfb41bd6bULL,\n", "file_path": "test/unit-test/u2f/sha2.c", "rank": 84, "score": 189472.33187045742 }, { "content": "static const sha2_word32 sha256_initial_hash_value[8] = {0x6a09e667UL,\n\n 0xbb67ae85UL,\n\n 0x3c6ef372UL,\n\n 0xa54ff53aUL,\n\n 0x510e527fUL,\n\n 0x9b05688cUL,\n\n 0x1f83d9abUL,\n", "file_path": "test/unit-test/u2f/sha2.c", "rank": 85, "score": 189472.33187045742 }, { "content": "uECC_VLI_API void uECC_vli_modSub(\n\n uECC_word_t* result,\n\n const uECC_word_t* left,\n\n const uECC_word_t* right,\n\n const uECC_word_t* mod,\n\n wordcount_t num_words)\n\n{\n\n uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words);\n\n if (l_borrow) {\n\n /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x,\n\n we can get the correct result from result + mod (with overflow). */\n\n uECC_vli_add(result, result, mod, num_words);\n\n }\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 86, "score": 189450.1850675124 }, { "content": "uECC_VLI_API void uECC_vli_modAdd(\n\n uECC_word_t* result,\n\n const uECC_word_t* left,\n\n const uECC_word_t* right,\n\n const uECC_word_t* mod,\n\n wordcount_t num_words)\n\n{\n\n uECC_word_t carry = uECC_vli_add(result, left, right, num_words);\n\n if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) {\n\n /* result > mod (result = mod + remainder), so subtract mod to get remainder. */\n\n uECC_vli_sub(result, result, mod, num_words);\n\n }\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 87, "score": 189450.1850675124 }, { "content": "uECC_VLI_API void uECC_vli_modMult(\n\n uECC_word_t* result,\n\n const uECC_word_t* left,\n\n const uECC_word_t* right,\n\n const uECC_word_t* mod,\n\n wordcount_t num_words)\n\n{\n\n uECC_word_t product[2 * uECC_MAX_WORDS];\n\n uECC_vli_mult(product, left, right, num_words);\n\n uECC_vli_mmod(result, product, mod, num_words);\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 88, "score": 189448.71122301975 }, { "content": "uECC_VLI_API void uECC_vli_modInv(\n\n uECC_word_t* result,\n\n const uECC_word_t* input,\n\n const uECC_word_t* mod,\n\n wordcount_t num_words)\n\n{\n\n uECC_word_t a[uECC_MAX_WORDS], b[uECC_MAX_WORDS], u[uECC_MAX_WORDS], v[uECC_MAX_WORDS];\n\n cmpresult_t cmpResult;\n\n\n\n if (uECC_vli_isZero(input, num_words)) {\n\n uECC_vli_clear(result, num_words);\n\n return;\n\n }\n\n\n\n uECC_vli_set(a, input, num_words);\n\n uECC_vli_set(b, mod, num_words);\n\n uECC_vli_clear(u, num_words);\n\n u[0] = 1;\n\n uECC_vli_clear(v, num_words);\n\n while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) {\n\n if (EVEN(a)) {\n\n uECC_vli_rshift1(a, num_words);\n\n vli_modInv_update(u, mod, num_words);\n\n } else if (EVEN(b)) {\n\n uECC_vli_rshift1(b, num_words);\n\n vli_modInv_update(v, mod, num_words);\n\n } else if (cmpResult > 0) {\n\n uECC_vli_sub(a, a, b, num_words);\n\n uECC_vli_rshift1(a, num_words);\n\n if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) {\n\n uECC_vli_add(u, u, mod, num_words);\n\n }\n\n uECC_vli_sub(u, u, v, num_words);\n\n vli_modInv_update(u, mod, num_words);\n\n } else {\n\n uECC_vli_sub(b, b, a, num_words);\n\n uECC_vli_rshift1(b, num_words);\n\n if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) {\n\n uECC_vli_add(v, v, mod, num_words);\n\n }\n\n uECC_vli_sub(v, v, u, num_words);\n\n vli_modInv_update(v, mod, num_words);\n\n }\n\n }\n\n uECC_vli_set(result, u, num_words);\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 89, "score": 189447.6313429073 }, { "content": "static void vli_modInv_update(uECC_word_t* uv, const uECC_word_t* mod, wordcount_t num_words)\n\n{\n\n uECC_word_t carry = 0;\n\n if (!EVEN(uv)) {\n\n carry = uECC_vli_add(uv, uv, mod, num_words);\n\n }\n\n uECC_vli_rshift1(uv, num_words);\n\n if (carry) {\n\n uv[num_words - 1] |= HIGH_BIT_SET;\n\n }\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 90, "score": 189442.71803743634 }, { "content": "uECC_VLI_API void uECC_vli_modMult_fast(\n\n uECC_word_t* result,\n\n const uECC_word_t* left,\n\n const uECC_word_t* right,\n\n uECC_Curve curve)\n\n{\n\n uECC_word_t product[2 * uECC_MAX_WORDS];\n\n uECC_vli_mult(product, left, right, curve->num_words);\n\n#if (uECC_OPTIMIZATION_LEVEL > 0)\n\n curve->mmod_fast(result, product);\n\n#else\n\n uECC_vli_mmod(result, product, curve->p, curve->num_words);\n\n#endif\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 91, "score": 187248.01720697855 }, { "content": "pub fn status_create<'a, F>(_text: &str, _status_success: bool, mut callback: F) -> Component<'a>\n\nwhere\n\n F: FnMut() + 'a,\n\n{\n\n callback();\n\n Component {\n\n is_pushed: false,\n\n _p: PhantomData,\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/ui/ui_stub.rs", "rank": 92, "score": 186292.9822925023 }, { "content": " uECC_word_t b[uECC_MAX_WORDS];\n", "file_path": "test/unit-test/u2f/uECC.c", "rank": 93, "score": 184481.7342048798 }, { "content": "pub fn lock() {\n\n unsafe { bitbox02_sys::keystore_lock() }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 94, "score": 184080.05825802294 }, { "content": "pub fn secp256k1_sign(\n\n keypath: &[u32],\n\n msg: &[u8; 32],\n\n host_nonce: &[u8; 32],\n\n) -> Result<SignResult, ()> {\n\n let mut signature = [0u8; 64];\n\n let mut recid: util::c_types::c_int = 0;\n\n match unsafe {\n\n bitbox02_sys::keystore_secp256k1_sign(\n\n keypath.as_ptr(),\n\n keypath.len() as _,\n\n msg.as_ptr(),\n\n host_nonce.as_ptr(),\n\n signature.as_mut_ptr(),\n\n &mut recid,\n\n )\n\n } {\n\n true => Ok(SignResult {\n\n signature,\n\n recid: recid.try_into().unwrap(),\n\n }),\n\n false => Err(()),\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/keystore.rs", "rank": 95, "score": 182243.68107537884 }, { "content": "pub fn confirm_transaction_address_create<'a, 'b>(\n\n amount: &'a str,\n\n address: &'a str,\n\n callback: AcceptRejectCb<'b>,\n\n) -> Component<'b> {\n\n unsafe extern \"C\" fn c_callback(result: bool, param: *mut c_void) {\n\n let callback = param as *mut AcceptRejectCb;\n\n (*callback)(result);\n\n }\n\n\n\n let callback_param = Box::into_raw(Box::new(callback)) as *mut c_void;\n\n let component = unsafe {\n\n bitbox02_sys::confirm_transaction_address_create(\n\n crate::util::str_to_cstr_vec(amount).unwrap().as_ptr(), // copied in C\n\n crate::util::str_to_cstr_vec(address).unwrap().as_ptr(), // copied in C\n\n Some(c_callback as _),\n\n callback_param,\n\n )\n\n };\n\n Component {\n\n component,\n\n is_pushed: false,\n\n on_drop: Some(Box::new(move || unsafe {\n\n // Drop all callbacks.\n\n drop(Box::from_raw(callback_param as *mut AcceptRejectCb));\n\n })),\n\n _p: PhantomData,\n\n }\n\n}\n\n\n", "file_path": "src/rust/bitbox02/src/ui/ui.rs", "rank": 96, "score": 181228.70288016298 } ]
Rust
debug/src/lib.rs
Simon-Bin/proc-macro-workshop
c8654295d4a10ab10827464267c5f653e4005c91
use std::collections::HashMap; use quote::quote; use syn::parse_quote; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug, attributes(debug))] pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st) { Ok(token_stream) => token_stream, Err(e) => e.to_compile_error(), } .into() } fn do_expand(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let ret = generate_debug_trait(st)?; return Ok(ret); } type StructFields = syn::punctuated::Punctuated<syn::Field, syn::Token!(,)>; fn get_fields_from_derive_input(d: &syn::DeriveInput) -> syn::Result<&StructFields> { if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = d.data { return Ok(named); } Err(syn::Error::new_spanned( d, "Must define on a Struct,not Enum".to_string(), )) } fn generate_debug_trait_core(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let fields = get_fields_from_derive_input(st)?; let struct_name_ident = &st.ident; let struct_name_literal = struct_name_ident.to_string(); let mut fmt_body_stream = proc_macro2::TokenStream::new(); fmt_body_stream.extend(quote!( fmt.debug_struct(#struct_name_literal) )); for field in fields.iter() { let field_name_ident = field.ident.as_ref().unwrap(); let field_name_literal = field_name_ident.to_string(); let mut format_str = "{:?}".to_string(); if let Some(format) = get_custom_format_of_field(field)? { format_str = format; } fmt_body_stream.extend(quote!( .field(#field_name_literal, &format_args!(#format_str,self.#field_name_ident)) )); } fmt_body_stream.extend(quote!( .finish() )); Ok(fmt_body_stream) } fn generate_debug_trait(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let struct_name_ident = &st.ident; let fmt_body_stream = generate_debug_trait_core(st)?; let mut generics_param_to_modify = st.generics.clone(); if let Some(hatch) = get_struct_escape_hatch(st) { generics_param_to_modify.make_where_clause(); generics_param_to_modify .where_clause .as_mut() .unwrap() .predicates .push(syn::parse_str(hatch.as_str()).unwrap()); } else { let fields = get_fields_from_derive_input(st)?; let mut fields_type_names = Vec::new(); let mut phantomdata_type_param_names = Vec::new(); for field in fields { if let Some(s) = get_field_type_name(field)? { fields_type_names.push(s); } if let Some(s) = get_phantomdata_generic_type_name(field)? { phantomdata_type_param_names.push(s); } } let associated_types_map = get_generic_association_types(st); for g in generics_param_to_modify.params.iter_mut() { if let syn::GenericParam::Type(t) = g { let type_param_name = t.ident.to_string(); if phantomdata_type_param_names.contains(&type_param_name) && !fields_type_names.contains(&type_param_name) { continue; } if associated_types_map.contains_key(&type_param_name) && !fields_type_names.contains(&type_param_name) { continue; } t.bounds.push(parse_quote!(std::fmt::Debug)) } } generics_param_to_modify.make_where_clause(); for (_, associated_types) in associated_types_map { for associated_type in associated_types { generics_param_to_modify .where_clause .as_mut() .unwrap() .predicates .push(parse_quote!(#associated_type:std::fmt::Debug)); } } } let (impl_generics, type_generics, where_clause) = generics_param_to_modify.split_for_impl(); let ret_stream = quote!( impl #impl_generics std::fmt::Debug for #struct_name_ident #type_generics #where_clause{ fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { #fmt_body_stream } } ); Ok(ret_stream) } fn get_custom_format_of_field(field: &syn::Field) -> syn::Result<Option<String>> { for attr in &field.attrs { if let Ok(syn::Meta::NameValue(syn::MetaNameValue { ref path, ref lit, .. })) = attr.parse_meta() { if path.is_ident("debug") { if let syn::Lit::Str(ref ident_str) = lit { return Ok(Some(ident_str.value())); } } } } Ok(None) } fn get_phantomdata_generic_type_name(field: &syn::Field) -> syn::Result<Option<String>> { if let syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, .. }) = field.ty { if let Some(syn::PathSegment { ref ident, ref arguments, }) = segments.last() { if ident == "PhantomData" { if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { args, .. }) = arguments { if let Some(syn::GenericArgument::Type(syn::Type::Path(ref gp))) = args.first() { if let Some(generic_ident) = gp.path.segments.first() { return Ok(Some(generic_ident.ident.to_string())); } } } } } } Ok(None) } fn get_field_type_name(field: &syn::Field) -> syn::Result<Option<String>> { if let syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, .. }) = field.ty { if let Some(syn::PathSegment { ref ident, .. }) = segments.last() { return Ok(Some(ident.to_string())); } } return Ok(None); } fn get_generic_association_types(st: &syn::DeriveInput) -> HashMap<String, Vec<syn::TypePath>> { let origin_generic_param_names: Vec<String> = st .generics .params .iter() .filter_map(|f| { if let syn::GenericParam::Type(ty) = f { return Some(ty.ident.to_string()); } return None; }) .collect(); let mut visitor = TypePathVisitor { generic_type_names: origin_generic_param_names, associated_types: HashMap::new(), }; visitor.visit_derive_input(st); return visitor.associated_types; } fn get_struct_escape_hatch(st: &syn::DeriveInput) -> Option<String> { if let Some(inert_arr) = st.attrs.last() { if let Ok(syn::Meta::List(syn::MetaList { nested, .. })) = inert_arr.parse_meta() { if let Some(syn::NestedMeta::Meta(syn::Meta::NameValue(path_value))) = nested.first() { if path_value.path.is_ident("bound") { if let syn::Lit::Str(ref lit) = path_value.lit { return Some(lit.value()); } } } } } None } struct TypePathVisitor { generic_type_names: Vec<String>, associated_types: HashMap<String, Vec<syn::TypePath>>, } impl<'ast> Visit<'ast> for TypePathVisitor { fn visit_type_path(&mut self, node: &'ast syn::TypePath) { if node.path.segments.len() >= 2 { let generic_type_name = node.path.segments[0].ident.to_string(); if self.generic_type_names.contains(&generic_type_name) { self.associated_types .entry(generic_type_name) .or_insert(Vec::new()) .push(node.clone()); } } visit::visit_type_path(self, node); } }
use std::collections::HashMap; use quote::quote; use syn::parse_quote; use syn::visit::{self, Visit}; #[proc_macro_derive(CustomDebug, attributes(debug))] pub fn derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let st = syn::parse_macro_input!(input as syn::DeriveInput); match do_expand(&st) { Ok(token_stream) => token_stream, Err(e) => e.to_compile_error(), } .into() } fn do_expand(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let ret = generate_debug_trait(st)?; return Ok(ret); } type StructFields = syn::punctuated::Punctuated<syn::Field, syn::Token!(,)>; fn get_fields_from_derive_input(d: &syn::DeriveInput) -> syn::Result<&StructFields> { if let syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }), .. }) = d.data { return Ok(named); } Err(syn::Error::new_spanned( d, "Must define on a Struct,not Enum".to_string(), )) } fn generate_debug_trait_core(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let fields = get_fields_from_derive_input(st)?; let struct_name_ident = &st.ident; let struct_name_literal = struct_name_ident.to_string(); let mut fmt_body_stream = proc_macro2::TokenStream::new(); fmt_body_stream.extend(quote!( fmt.debug_struct(#struct_name_literal) )); for field in fields.iter() { let field_name_ident = field.ident.as_ref().unwrap(); let field_name_literal = field_name_ident.to_string(); let mut format_str = "{:?}".to_string(); if let Some(format) = get_custom_format_of_field(field)? { format_str = format; } fmt_body_stream.extend(quote!( .field(#field_name_literal, &format_args!(#format_str,self.#field_name_ident)) )); } fmt_body_stream.extend(quote!( .finish() )); Ok(fmt_body_stream) } fn generate_debug_trait(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> { let struct_name_ident = &st.ident; let fmt_body_stream = generate_debug_trait_core(st)?; let mut generics_param_to_modify = st.generics.clone(); if let Some(hatch) = get_struct_escape_hatch(st) { generics_param_to_modify.make_where_clause(); generics_param_to_modify .where_clause .as_mut() .unwrap() .predicates .push(syn::parse_str(hatch.as_str()).unwrap()); } else { let fields = get_fields_from_derive_input(st)?; let mut fields_type_names = Vec::new(); let mut phantomdata_type_param_names = Vec::new(); for field in fields { if let Some(s) = get_field_type_name(field)? { fields_type_names.push(s); } if let Some(s) = get_phantomdata_generic_type_name(field)? { phantomdata_type_param_names.push(s); } } let associated_types_map = get_generic_association_types(st); for g in generics_param_to_modify.params.iter_mut() { if let syn::GenericParam::Type(t) = g { let type_param_name = t.ident.to_str
tr in &field.attrs { if let Ok(syn::Meta::NameValue(syn::MetaNameValue { ref path, ref lit, .. })) = attr.parse_meta() { if path.is_ident("debug") { if let syn::Lit::Str(ref ident_str) = lit { return Ok(Some(ident_str.value())); } } } } Ok(None) } fn get_phantomdata_generic_type_name(field: &syn::Field) -> syn::Result<Option<String>> { if let syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, .. }) = field.ty { if let Some(syn::PathSegment { ref ident, ref arguments, }) = segments.last() { if ident == "PhantomData" { if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { args, .. }) = arguments { if let Some(syn::GenericArgument::Type(syn::Type::Path(ref gp))) = args.first() { if let Some(generic_ident) = gp.path.segments.first() { return Ok(Some(generic_ident.ident.to_string())); } } } } } } Ok(None) } fn get_field_type_name(field: &syn::Field) -> syn::Result<Option<String>> { if let syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, .. }) = field.ty { if let Some(syn::PathSegment { ref ident, .. }) = segments.last() { return Ok(Some(ident.to_string())); } } return Ok(None); } fn get_generic_association_types(st: &syn::DeriveInput) -> HashMap<String, Vec<syn::TypePath>> { let origin_generic_param_names: Vec<String> = st .generics .params .iter() .filter_map(|f| { if let syn::GenericParam::Type(ty) = f { return Some(ty.ident.to_string()); } return None; }) .collect(); let mut visitor = TypePathVisitor { generic_type_names: origin_generic_param_names, associated_types: HashMap::new(), }; visitor.visit_derive_input(st); return visitor.associated_types; } fn get_struct_escape_hatch(st: &syn::DeriveInput) -> Option<String> { if let Some(inert_arr) = st.attrs.last() { if let Ok(syn::Meta::List(syn::MetaList { nested, .. })) = inert_arr.parse_meta() { if let Some(syn::NestedMeta::Meta(syn::Meta::NameValue(path_value))) = nested.first() { if path_value.path.is_ident("bound") { if let syn::Lit::Str(ref lit) = path_value.lit { return Some(lit.value()); } } } } } None } struct TypePathVisitor { generic_type_names: Vec<String>, associated_types: HashMap<String, Vec<syn::TypePath>>, } impl<'ast> Visit<'ast> for TypePathVisitor { fn visit_type_path(&mut self, node: &'ast syn::TypePath) { if node.path.segments.len() >= 2 { let generic_type_name = node.path.segments[0].ident.to_string(); if self.generic_type_names.contains(&generic_type_name) { self.associated_types .entry(generic_type_name) .or_insert(Vec::new()) .push(node.clone()); } } visit::visit_type_path(self, node); } }
ing(); if phantomdata_type_param_names.contains(&type_param_name) && !fields_type_names.contains(&type_param_name) { continue; } if associated_types_map.contains_key(&type_param_name) && !fields_type_names.contains(&type_param_name) { continue; } t.bounds.push(parse_quote!(std::fmt::Debug)) } } generics_param_to_modify.make_where_clause(); for (_, associated_types) in associated_types_map { for associated_type in associated_types { generics_param_to_modify .where_clause .as_mut() .unwrap() .predicates .push(parse_quote!(#associated_type:std::fmt::Debug)); } } } let (impl_generics, type_generics, where_clause) = generics_param_to_modify.split_for_impl(); let ret_stream = quote!( impl #impl_generics std::fmt::Debug for #struct_name_ident #type_generics #where_clause{ fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { #fmt_body_stream } } ); Ok(ret_stream) } fn get_custom_format_of_field(field: &syn::Field) -> syn::Result<Option<String>> { for at
random
[ { "content": "fn get_fields_from_derive_input(st: &syn::DeriveInput) -> syn::Result<&StructField> {\n\n if let syn::Data::Struct(syn::DataStruct {\n\n fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),\n\n ..\n\n }) = st.data\n\n {\n\n return Ok(named);\n\n }\n\n Err(syn::Error::new_spanned(\n\n st,\n\n \"Must Define On Struct,Not on Enum\",\n\n ))\n\n}\n\n\n", "file_path": "builder/src/lib.rs", "rank": 0, "score": 139677.6856964393 }, { "content": "type StructField = syn::punctuated::Punctuated<syn::Field, syn::Token![,]>;\n\n\n", "file_path": "builder/src/lib.rs", "rank": 5, "score": 106815.94606886491 }, { "content": "fn get_generic_inner_type<'a>(t: &'a syn::Type, outer_ident_name: &str) -> Option<&'a syn::Type> {\n\n if let syn::Type::Path(syn::TypePath {\n\n path: syn::Path { segments, .. },\n\n ..\n\n }) = t\n\n {\n\n if let Some(seg) = segments.last() {\n\n if seg.ident.to_string() == outer_ident_name {\n\n if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {\n\n args,\n\n ..\n\n }) = &seg.arguments\n\n {\n\n if let Some(syn::GenericArgument::Type(inner_type)) = args.first() {\n\n return Some(inner_type);\n\n }\n\n }\n\n }\n\n }\n\n }\n\n None\n\n}\n\n\n", "file_path": "builder/src/lib.rs", "rank": 6, "score": 105949.39306614133 }, { "content": "type Some = ();\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 8, "score": 94402.70379445149 }, { "content": "fn do_expand(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {\n\n let struct_name_literal = st.ident.to_string();\n\n let builder_name_literal = format!(\"{}Builder\", struct_name_literal);\n\n let builder_name_ident = syn::Ident::new(builder_name_literal.as_str(), st.span());\n\n\n\n let struct_ident = &st.ident;\n\n\n\n let builder_struct_fields_def = generate_builder_struct_fields_def(st)?;\n\n let builder_struct_factory_init_clauses = generate_builder_struct_factory_init_clauses(st)?;\n\n let setter_functions = generate_setter_functions(st)?;\n\n let build_function = generate_build_function(st)?;\n\n\n\n let ret = quote! {\n\n pub struct #builder_name_ident{\n\n #builder_struct_fields_def\n\n }\n\n\n\n impl #struct_ident {\n\n pub fn builder()->#builder_name_ident{\n\n #builder_name_ident{\n", "file_path": "builder/src/lib.rs", "rank": 10, "score": 89101.9696538112 }, { "content": "fn generate_setter_functions(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {\n\n let fields = get_fields_from_derive_input(st)?;\n\n\n\n let idents: Vec<_> = fields.iter().map(|f| &f.ident).collect();\n\n let types: Vec<_> = fields.iter().map(|f| &f.ty).collect();\n\n\n\n let mut final_tokenstream = proc_macro2::TokenStream::new();\n\n for (idx, (ident, type_)) in idents.iter().zip(types.iter()).enumerate() {\n\n let tokenstream_piece = if let Some(inner_type) = get_generic_inner_type(type_, \"Option\") {\n\n quote! {\n\n fn #ident(&mut self,#ident:#inner_type) -> &mut Self{\n\n self.#ident = std::option::Option::Some(#ident);\n\n self\n\n }\n\n }\n\n } else if let Some(ref user_specified_ident) =\n\n get_user_specified_ident_for_vec(&fields[idx])?\n\n {\n\n let inner_type = get_generic_inner_type(type_, \"Vec\").ok_or(syn::Error::new(\n\n fields[idx].span(),\n", "file_path": "builder/src/lib.rs", "rank": 13, "score": 86778.56961457833 }, { "content": "fn generate_build_function(st: &syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {\n\n let fields = get_fields_from_derive_input(st)?;\n\n // let types: Vec<_> = fields.iter().map(|f| &f.ty).collect();\n\n\n\n let mut checker_code_pieces = Vec::new();\n\n for idx in 0..fields.len() {\n\n let ident = &fields[idx].ident;\n\n if get_generic_inner_type(&fields[idx].ty, \"Option\").is_none()\n\n && get_user_specified_ident_for_vec(&fields[idx])?.is_none()\n\n {\n\n checker_code_pieces.push(quote::quote! {\n\n if self.#ident.is_none(){\n\n let err = format!(\"{} field is missing\",stringify!(#ident));\n\n return std::result::Result::Err(err.into());\n\n }\n\n })\n\n }\n\n }\n\n\n\n let mut fill_result_clauses = Vec::new();\n", "file_path": "builder/src/lib.rs", "rank": 14, "score": 86778.56961457833 }, { "content": "fn get_user_specified_ident_for_vec(field: &syn::Field) -> syn::Result<Option<syn::Ident>> {\n\n for attr in &field.attrs {\n\n if let Ok(syn::Meta::List(syn::MetaList {\n\n ref path,\n\n ref nested,\n\n ..\n\n })) = attr.parse_meta()\n\n {\n\n if let Some(p) = path.segments.first() {\n\n if p.ident == \"builder\" {\n\n if let Some(syn::NestedMeta::Meta(syn::Meta::NameValue(kv))) = nested.first() {\n\n if kv.path.is_ident(\"each\") {\n\n if let syn::Lit::Str(ref ident_str) = kv.lit {\n\n return Ok(Some(syn::Ident::new(\n\n ident_str.value().as_str(),\n\n attr.span(),\n\n )));\n\n }\n\n } else{\n\n if let Ok(syn::Meta::List(ref list)) = attr.parse_meta() {\n", "file_path": "builder/src/lib.rs", "rank": 16, "score": 84923.32081208538 }, { "content": "#[proc_macro_derive(Builder, attributes(builder))]\n\npub fn derive(input: TokenStream) -> TokenStream {\n\n let st = syn::parse_macro_input!(input as syn::DeriveInput);\n\n match do_expand(&st) {\n\n Ok(token_stream) => token_stream,\n\n Err(e) => e.to_compile_error(),\n\n }\n\n .into()\n\n}\n\n\n", "file_path": "builder/src/lib.rs", "rank": 17, "score": 83806.96261748986 }, { "content": "#[proc_macro]\n\npub fn seq(input: TokenStream) -> TokenStream {\n\n let _ = input;\n\n\n\n unimplemented!()\n\n}\n", "file_path": "seq/src/lib.rs", "rank": 18, "score": 83806.96261748986 }, { "content": "pub trait Trait {\n\n type Value;\n\n}\n\n\n\n#[derive(CustomDebug)]\n\npub struct Field<T: Trait> {\n\n values: Vec<T::Value>,\n\n}\n\n\n", "file_path": "debug/tests/07-associated-type.rs", "rank": 19, "score": 83240.59625421085 }, { "content": "fn main() {\n\n let f = Field {\n\n name: \"F\",\n\n bitmask: 0b00011100,\n\n };\n\n\n\n let debug = format!(\"{:?}\", f);\n\n let expected = r#\"Field { name: \"F\", bitmask: 0b00011100 }\"#;\n\n\n\n assert_eq!(debug, expected);\n\n}\n", "file_path": "debug/tests/03-custom-format.rs", "rank": 21, "score": 78150.04443719608 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/05-match-expr.rs", "rank": 22, "score": 78096.74253064957 }, { "content": "fn main() {\n\n let command = Command::builder()\n\n .executable(\"cargo\".to_owned())\n\n .arg(\"build\".to_owned())\n\n .arg(\"--release\".to_owned())\n\n .build()\n\n .unwrap();\n\n\n\n assert_eq!(command.executable, \"cargo\");\n\n assert_eq!(command.args, vec![\"build\", \"--release\"]);\n\n}\n", "file_path": "builder/tests/07-repeated-field.rs", "rank": 23, "score": 77798.04990739819 }, { "content": "fn main() {\n\n let command = Command::builder()\n\n .executable(\"cargo\".to_owned())\n\n .args(vec![\"build\".to_owned(), \"--release\".to_owned()])\n\n .env(vec![])\n\n .build()\n\n .unwrap();\n\n assert!(command.current_dir.is_none());\n\n\n\n let command = Command::builder()\n\n .executable(\"cargo\".to_owned())\n\n .args(vec![\"build\".to_owned(), \"--release\".to_owned()])\n\n .env(vec![])\n\n .current_dir(\"..\".to_owned())\n\n .build()\n\n .unwrap();\n\n assert!(command.current_dir.is_some());\n\n}\n", "file_path": "builder/tests/06-optional-field.rs", "rank": 24, "score": 77798.04990739819 }, { "content": "fn main() {\n\n let f = Field {\n\n value: \"F\",\n\n bitmask: 0b00011100,\n\n };\n\n\n\n let debug = format!(\"{:?}\", f);\n\n let expected = r#\"Field { value: \"F\", bitmask: 0b00011100 }\"#;\n\n\n\n assert_eq!(debug, expected);\n\n}\n", "file_path": "debug/tests/04-type-parameter.rs", "rank": 25, "score": 77334.77429077827 }, { "content": "fn main() {\n\n // Does not implement Debug, but its associated type does.\n\n struct Id;\n\n\n\n impl Trait for Id {\n\n type Value = u8;\n\n }\n\n\n\n assert_debug::<Field<Id>>();\n\n}\n", "file_path": "debug/tests/07-associated-type.rs", "rank": 26, "score": 77334.77429077827 }, { "content": "fn main() {\n\n assert_eq!(<B24 as Specifier>::BITS, 24);\n\n}\n", "file_path": "bitfield/tests/01-specifier-types.rs", "rank": 27, "score": 77334.77429077827 }, { "content": "#[proc_macro_attribute]\n\npub fn sorted(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let _ = args;\n\n let _ = input;\n\n\n\n unimplemented!()\n\n}\n", "file_path": "sorted/src/lib.rs", "rank": 28, "score": 75230.63012821595 }, { "content": "fn main() {}\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 29, "score": 75211.01379562622 }, { "content": "#[proc_macro_attribute]\n\npub fn bitfield(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let _ = args;\n\n let _ = input;\n\n\n\n unimplemented!()\n\n}\n", "file_path": "bitfield/impl/src/lib.rs", "rank": 30, "score": 73964.82222209478 }, { "content": "fn generate_builder_struct_fields_def(\n\n st: &syn::DeriveInput,\n\n) -> syn::Result<proc_macro2::TokenStream> {\n\n let fields = get_fields_from_derive_input(st)?;\n\n\n\n let idents: Vec<_> = fields.iter().map(|f| &f.ident).collect();\n\n let types: syn::Result<Vec<_>> = fields\n\n .iter()\n\n .map(|f| {\n\n if let Some(inner_type) = get_generic_inner_type(&f.ty, \"Option\") {\n\n Ok(quote! {\n\n std::option::Option<#inner_type>\n\n })\n\n } else if get_user_specified_ident_for_vec(f)?.is_some() {\n\n let origin_type = &f.ty;\n\n Ok(quote! {\n\n #origin_type\n\n })\n\n } else {\n\n let origin_type = &f.ty;\n", "file_path": "builder/src/lib.rs", "rank": 32, "score": 71820.17808440815 }, { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "debug/tests/07-associated-type.rs", "rank": 33, "score": 68161.25661113672 }, { "content": "type Result = ();\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 34, "score": 64544.578514052046 }, { "content": "type Option = ();\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 35, "score": 64544.578514052046 }, { "content": "type None = ();\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 36, "score": 64544.578514052046 }, { "content": "type Box = ();\n\n\n\n#[derive(Builder)]\n\npub struct Command {\n\n executable: String,\n\n}\n\n\n", "file_path": "builder/tests/09-redefined-prelude-types.rs", "rank": 37, "score": 64544.578514052046 }, { "content": "pub trait Trait {\n\n type Value;\n\n}\n\n\n\n#[derive(CustomDebug)]\n\n#[debug(bound = \"T::Value: Debug\")]\n\npub struct Wrapper<T: Trait> {\n\n field: Field<T>,\n\n}\n\n\n", "file_path": "debug/tests/08-escape-hatch.rs", "rank": 38, "score": 55015.93424623427 }, { "content": "type A = B1;\n", "file_path": "bitfield/tests/05-accessor-signatures.rs", "rank": 39, "score": 54785.331793705336 }, { "content": "type A = B1;\n", "file_path": "bitfield/tests/04-multiple-of-8bits.rs", "rank": 40, "score": 54785.331793705336 }, { "content": "type D = B24;\n\n\n\n#[bitfield]\n\npub struct MyFourBytes {\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n}\n\n\n", "file_path": "bitfield/tests/05-accessor-signatures.rs", "rank": 41, "score": 53693.776427079734 }, { "content": "type S = String;\n\n\n\n#[derive(CustomDebug)]\n\npub struct Field<T> {\n\n marker: PhantomData<T>,\n\n string: S,\n\n #[debug = \"0b{:08b}\"]\n\n bitmask: u8,\n\n}\n\n\n", "file_path": "debug/tests/05-phantom-data.rs", "rank": 42, "score": 53693.776427079734 }, { "content": "type B = B3;\n", "file_path": "bitfield/tests/05-accessor-signatures.rs", "rank": 43, "score": 53693.776427079734 }, { "content": "type C = B4;\n", "file_path": "bitfield/tests/04-multiple-of-8bits.rs", "rank": 44, "score": 53693.776427079734 }, { "content": "type D = B23;\n\n\n\n#[bitfield]\n\npub struct NotQuiteFourBytes {\n\n a: A,\n\n b: B,\n\n c: C,\n\n d: D,\n\n}\n\n\n", "file_path": "bitfield/tests/04-multiple-of-8bits.rs", "rank": 45, "score": 53693.776427079734 }, { "content": "type B = B3;\n", "file_path": "bitfield/tests/04-multiple-of-8bits.rs", "rank": 46, "score": 53693.776427079734 }, { "content": "type C = B4;\n", "file_path": "bitfield/tests/05-accessor-signatures.rs", "rank": 47, "score": 53693.776427079734 }, { "content": "fn main() {}\n", "file_path": "main.rs", "rank": 48, "score": 51657.07654173281 }, { "content": "#[derive(CustomDebug)]\n\nstruct Field<T: Trait> {\n\n values: Vec<T::Value>,\n\n}\n\n\n", "file_path": "debug/tests/08-escape-hatch.rs", "rank": 49, "score": 51640.48125633475 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"tests/01-parse.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": "builder/tests/progress.rs", "rank": 50, "score": 49133.81254550912 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n //t.pass(\"tests/01-parse-enum.rs\");\n\n //t.compile_fail(\"tests/02-not-enum.rs\");\n\n //t.compile_fail(\"tests/03-out-of-order.rs\");\n\n //t.compile_fail(\"tests/04-variants-with-data.rs\");\n\n //t.compile_fail(\"tests/05-match-expr.rs\");\n\n //t.compile_fail(\"tests/06-pattern-path.rs\");\n\n //t.compile_fail(\"tests/07-unrecognized-pattern.rs\");\n\n //t.pass(\"tests/08-underscore.rs\");\n\n}\n", "file_path": "sorted/tests/progress.rs", "rank": 51, "score": 49133.81254550912 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n //t.pass(\"tests/01-specifier-types.rs\");\n\n //t.pass(\"tests/02-storage.rs\");\n\n //t.pass(\"tests/03-accessors.rs\");\n\n //t.compile_fail(\"tests/04-multiple-of-8bits.rs\");\n\n //t.pass(\"tests/05-accessor-signatures.rs\");\n\n //t.pass(\"tests/06-enums.rs\");\n\n //t.pass(\"tests/07-optional-discriminant.rs\");\n\n //t.compile_fail(\"tests/08-non-power-of-two.rs\");\n\n //t.compile_fail(\"tests/09-variant-out-of-range.rs\");\n\n //t.pass(\"tests/10-bits-attribute.rs\");\n\n //t.compile_fail(\"tests/11-bits-attribute-wrong.rs\");\n\n //t.pass(\"tests/12-accessors-edge.rs\");\n\n}\n", "file_path": "bitfield/tests/progress.rs", "rank": 52, "score": 49133.81254550912 }, { "content": "fn main() {\n\n assert_eq!(std::mem::size_of::<MyFourBytes>(), 4);\n\n}\n", "file_path": "bitfield/tests/02-storage.rs", "rank": 53, "score": 49133.81254550912 }, { "content": "fn main() {\n\n let mut bitfield = MyFourBytes::new();\n\n assert_eq!(0, bitfield.get_a());\n\n assert_eq!(0, bitfield.get_b());\n\n assert_eq!(0, bitfield.get_c());\n\n assert_eq!(0, bitfield.get_d());\n\n\n\n bitfield.set_c(14);\n\n assert_eq!(0, bitfield.get_a());\n\n assert_eq!(0, bitfield.get_b());\n\n assert_eq!(14, bitfield.get_c());\n\n assert_eq!(0, bitfield.get_d());\n\n}\n", "file_path": "bitfield/tests/03-accessors.rs", "rank": 54, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "builder/tests/01-parse.rs", "rank": 55, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/08-underscore.rs", "rank": 56, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/03-out-of-order.rs", "rank": 57, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/02-not-enum.rs", "rank": 58, "score": 49133.81254550912 }, { "content": "fn main() {\n\n assert_eq!(std::mem::size_of::<RedirectionTableEntry>(), 1);\n\n\n\n // Initialized to all 0 bits.\n\n let mut entry = RedirectionTableEntry::new();\n\n assert_eq!(entry.get_acknowledged(), false);\n\n assert_eq!(entry.get_trigger_mode(), TriggerMode::Edge);\n\n assert_eq!(entry.get_delivery_mode(), DeliveryMode::Fixed);\n\n\n\n entry.set_acknowledged(true);\n\n entry.set_delivery_mode(DeliveryMode::SMI);\n\n assert_eq!(entry.get_acknowledged(), true);\n\n assert_eq!(entry.get_trigger_mode(), TriggerMode::Edge);\n\n assert_eq!(entry.get_delivery_mode(), DeliveryMode::SMI);\n\n}\n", "file_path": "bitfield/tests/06-enums.rs", "rank": 59, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "debug/tests/01-parse.rs", "rank": 60, "score": 49133.81254550912 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n //t.pass(\"tests/01-parse-header.rs\");\n\n //t.pass(\"tests/02-parse-body.rs\");\n\n //t.compile_fail(\"tests/03-expand-four-errors.rs\");\n\n //t.pass(\"tests/04-paste-ident.rs\");\n\n //t.pass(\"tests/05-repeat-section.rs\");\n\n //t.pass(\"tests/06-init-array.rs\");\n\n //t.pass(\"tests/07-inclusive-range.rs\");\n\n //t.compile_fail(\"tests/08-ident-span.rs\");\n\n //t.pass(\"tests/09-interaction-with-macrorules.rs\");\n\n}\n", "file_path": "seq/tests/progress.rs", "rank": 61, "score": 49133.81254550912 }, { "content": "#[test]\n\nfn tests() {\n\n let t = trybuild::TestCases::new();\n\n t.pass(\"tests/01-parse.rs\");\n\n t.pass(\"tests/02-impl-debug.rs\");\n\n t.pass(\"tests/03-custom-format.rs\");\n\n t.pass(\"tests/04-type-parameter.rs\");\n\n t.pass(\"tests/05-phantom-data.rs\");\n\n t.pass(\"tests/06-bound-trouble.rs\");\n\n t.pass(\"tests/07-associated-type.rs\");\n\n t.pass(\"tests/08-escape-hatch.rs\");\n\n}\n", "file_path": "debug/tests/progress.rs", "rank": 62, "score": 49133.81254550912 }, { "content": "fn main() {}\n", "file_path": "bitfield/tests/09-variant-out-of-range.rs", "rank": 63, "score": 48018.556916176094 }, { "content": "fn main() {\n\n assert_eq!(PROCS[32].id, 32);\n\n}\n", "file_path": "seq/tests/06-init-array.rs", "rank": 64, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "bitfield/tests/10-bits-attribute.rs", "rank": 65, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let interrupt = Interrupt::Irq8;\n\n\n\n assert_eq!(interrupt as u8, 8);\n\n assert_eq!(interrupt, Interrupt::Irq8);\n\n}\n", "file_path": "seq/tests/05-repeat-section.rs", "rank": 66, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "seq/tests/09-interaction-with-macrorules.rs", "rank": 67, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "builder/tests/08-unrecognized-attribute.rs", "rank": 68, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let mut x = MyFourBytes::new();\n\n\n\n // I am testing the signatures in this roundabout way to avoid making it\n\n // possible to pass this test with a generic signature that is inconvenient\n\n // for callers, such as `fn get_a<T: From<u64>>(&self) -> T`.\n\n\n\n let a = 1;\n\n x.set_a(a); // expect fn(&mut MyFourBytes, u8)\n\n let b = 1;\n\n x.set_b(b);\n\n let c = 1;\n\n x.set_c(c);\n\n let d = 1;\n\n x.set_d(d); // expect fn(&mut MyFourBytes, u32)\n\n\n\n assert_eq!(size_of_val(&a), 1);\n\n assert_eq!(size_of_val(&b), 1);\n\n assert_eq!(size_of_val(&c), 1);\n\n assert_eq!(size_of_val(&d), 4);\n\n\n\n assert_eq!(size_of_val(&x.get_a()), 1); // expect fn(&MyFourBytes) -> u8\n\n assert_eq!(size_of_val(&x.get_b()), 1);\n\n assert_eq!(size_of_val(&x.get_c()), 1);\n\n assert_eq!(size_of_val(&x.get_d()), 4); // expect fn(&MyFourBytes) -> u32\n\n}\n", "file_path": "bitfield/tests/05-accessor-signatures.rs", "rank": 69, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let e = E::Variant16;\n\n\n\n let desc = match e {\n\n E::Variant16 => \"min\",\n\n E::Variant17 | E::Variant18 | E::Variant19 => \"in between\",\n\n E::Variant20 => \"max\",\n\n };\n\n\n\n assert_eq!(desc, \"min\");\n\n}\n", "file_path": "seq/tests/07-inclusive-range.rs", "rank": 70, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/07-unrecognized-pattern.rs", "rank": 71, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/06-pattern-path.rs", "rank": 72, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let f = Field {\n\n name: \"F\",\n\n bitmask: 0b00011100,\n\n };\n\n\n\n let debug = format!(\"{:?}\", f);\n\n\n\n assert!(debug.starts_with(r#\"Field { name: \"F\",\"#));\n\n}\n", "file_path": "debug/tests/02-impl-debug.rs", "rank": 73, "score": 48018.556916176094 }, { "content": "fn main() {\n\n assert_debug::<One<u8>>();\n\n assert_debug::<Two<u8>>();\n\n}\n", "file_path": "debug/tests/06-bound-trouble.rs", "rank": 74, "score": 48018.556916176094 }, { "content": "fn main() {\n\n // Does not implement Debug.\n\n struct NotDebug;\n\n\n\n assert_debug::<PhantomData<NotDebug>>();\n\n assert_debug::<Field<NotDebug>>();\n\n}\n", "file_path": "debug/tests/05-phantom-data.rs", "rank": 75, "score": 48018.556916176094 }, { "content": "fn main() {\n\n assert_eq!(std::mem::size_of::<RedirectionTableEntry>(), 1);\n\n\n\n // Initialized to all 0 bits.\n\n let mut entry = RedirectionTableEntry::new();\n\n assert_eq!(entry.get_delivery_mode(), DeliveryMode::Init);\n\n\n\n entry.set_delivery_mode(DeliveryMode::Lowest);\n\n assert_eq!(entry.get_delivery_mode(), DeliveryMode::Lowest);\n\n}\n", "file_path": "bitfield/tests/07-optional-discriminant.rs", "rank": 76, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/04-variants-with-data.rs", "rank": 77, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "seq/tests/02-parse-body.rs", "rank": 78, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let mut builder = Command::builder();\n\n builder.executable(\"cargo\".to_owned());\n\n builder.args(vec![\"build\".to_owned(), \"--release\".to_owned()]);\n\n builder.env(vec![]);\n\n builder.current_dir(\"..\".to_owned());\n\n}\n", "file_path": "builder/tests/03-call-setters.rs", "rank": 79, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let sum = f0() + f1() + f2() + f3();\n\n\n\n assert_eq!(sum, 100 + 2 + 4 + 6);\n\n}\n", "file_path": "seq/tests/04-paste-ident.rs", "rank": 80, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let mut bitfield = EdgeCaseBytes::new();\n\n assert_eq!(0, bitfield.get_a());\n\n assert_eq!(0, bitfield.get_b());\n\n assert_eq!(0, bitfield.get_c());\n\n assert_eq!(0, bitfield.get_d());\n\n\n\n let a = 0b1100_0011_1;\n\n let b = 0b101_010;\n\n let c = 0x1675;\n\n let d = 0b1110;\n\n\n\n bitfield.set_a(a);\n\n bitfield.set_b(b);\n\n bitfield.set_c(c);\n\n bitfield.set_d(d);\n\n\n\n assert_eq!(a, bitfield.get_a());\n\n assert_eq!(b, bitfield.get_b());\n\n assert_eq!(c, bitfield.get_c());\n\n assert_eq!(d, bitfield.get_d());\n\n}\n", "file_path": "bitfield/tests/12-accessors-edge.rs", "rank": 81, "score": 48018.556916176094 }, { "content": "fn main() {\n\n struct Id;\n\n\n\n impl Trait for Id {\n\n type Value = u8;\n\n }\n\n\n\n assert_debug::<Wrapper<Id>>();\n\n}\n", "file_path": "debug/tests/08-escape-hatch.rs", "rank": 82, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let command = Command::builder()\n\n .executable(\"cargo\".to_owned())\n\n .args(vec![\"build\".to_owned(), \"--release\".to_owned()])\n\n .env(vec![])\n\n .current_dir(\"..\".to_owned())\n\n .build()\n\n .unwrap();\n\n\n\n assert_eq!(command.executable, \"cargo\");\n\n}\n", "file_path": "builder/tests/05-method-chaining.rs", "rank": 83, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "bitfield/tests/04-multiple-of-8bits.rs", "rank": 84, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let mut builder = Command::builder();\n\n builder.executable(\"cargo\".to_owned());\n\n builder.args(vec![\"build\".to_owned(), \"--release\".to_owned()]);\n\n builder.env(vec![]);\n\n builder.current_dir(\"..\".to_owned());\n\n\n\n let command = builder.build().unwrap();\n\n assert_eq!(command.executable, \"cargo\");\n\n}\n", "file_path": "builder/tests/04-call-build.rs", "rank": 85, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "sorted/tests/01-parse-enum.rs", "rank": 86, "score": 48018.556916176094 }, { "content": "fn main() {\n\n let builder = Command::builder();\n\n\n\n let _ = builder;\n\n}\n", "file_path": "builder/tests/02-create-builder.rs", "rank": 87, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "seq/tests/01-parse-header.rs", "rank": 88, "score": 48018.556916176094 }, { "content": "fn main() {}\n", "file_path": "seq/tests/03-expand-four-errors.rs", "rank": 89, "score": 46986.35178764965 }, { "content": "fn main() {}\n", "file_path": "bitfield/tests/08-non-power-of-two.rs", "rank": 90, "score": 46986.35178764965 }, { "content": "fn main() {}\n", "file_path": "bitfield/tests/11-bits-attribute-wrong.rs", "rank": 91, "score": 46986.35178764965 }, { "content": "// This f0 is written separately to detect whether your macro correctly starts\n\n// with the first iteration at N=1 as specified in the invocation. If the macro\n\n// incorrectly started at N=0 like in the previous tests cases, the first\n\n// generated function would conflict with this one and the program would not\n\n// compile.\n\nfn f0() -> u64 {\n\n 100\n\n}\n\n\n", "file_path": "seq/tests/04-paste-ident.rs", "rank": 92, "score": 45223.58282196909 }, { "content": "fn generate_builder_struct_factory_init_clauses(\n\n st: &syn::DeriveInput,\n\n) -> syn::Result<Vec<proc_macro2::TokenStream>> {\n\n let fields = get_fields_from_derive_input(st)?;\n\n\n\n let idents:syn::Result<Vec<_>> = fields\n\n .iter()\n\n .map(|f| {\n\n let ident = &f.ident;\n\n if get_user_specified_ident_for_vec(f)?.is_some() {\n\n Ok(quote! {\n\n #ident: std::vec::Vec::new()\n\n })\n\n } else {\n\n Ok(quote! {\n\n #ident: std::option::Option::None\n\n })\n\n }\n\n })\n\n .collect();\n\n Ok(idents?)\n\n}\n\n\n", "file_path": "builder/src/lib.rs", "rank": 93, "score": 44304.59194228928 }, { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "debug/tests/06-bound-trouble.rs", "rank": 94, "score": 41892.74942528915 }, { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "debug/tests/08-escape-hatch.rs", "rank": 95, "score": 41892.74942528915 }, { "content": "fn assert_debug<F: Debug>() {}\n\n\n", "file_path": "debug/tests/05-phantom-data.rs", "rank": 96, "score": 41892.74942528915 }, { "content": "#[sorted::check]\n\nfn f(bytes: &[u8]) -> Option<u8> {\n\n #[sorted]\n\n match bytes {\n\n [] => Some(0),\n\n [a] => Some(*a),\n\n [a, b] => Some(a + b),\n\n _other => None,\n\n }\n\n}\n\n\n", "file_path": "sorted/tests/07-unrecognized-pattern.rs", "rank": 97, "score": 39542.92875241695 }, { "content": "//\n\n// - Macro for applying a format string to some runtime value:\n\n// https://doc.rust-lang.org/std/macro.format_args.html\n\n\n\nuse derive_debug::CustomDebug;\n\n\n\n#[derive(CustomDebug)]\n\npub struct Field {\n\n name: &'static str,\n\n #[debug = \"0b{:08b}\"]\n\n bitmask: u8,\n\n}\n\n\n", "file_path": "debug/tests/03-custom-format.rs", "rank": 98, "score": 31353.514620207643 }, { "content": "// Look for a field attribute #[debug = \"...\"] on each field. If present, find a\n\n// way to format the field according to the format string given by the caller in\n\n// the attribute.\n\n//\n\n// In order for the compiler to recognize this inert attribute as associated\n\n// with your derive macro, it will need to be declared at the entry point of the\n\n// derive macro.\n\n//\n\n// #[proc_macro_derive(CustomDebug, attributes(debug))]\n\n//\n\n// These are called inert attributes. The word \"inert\" indicates that these\n\n// attributes do not correspond to a macro invocation on their own; they are\n\n// simply looked at by other macro invocations.\n\n//\n\n//\n\n// Resources:\n\n//\n\n// - Relevant syntax tree types:\n\n// https://docs.rs/syn/1.0/syn/struct.Attribute.html\n\n// https://docs.rs/syn/1.0/syn/enum.Meta.html\n", "file_path": "debug/tests/03-custom-format.rs", "rank": 99, "score": 31343.666699126225 } ]
Rust
src/grpc/node.rs
searsaw/sensei
ee3d45d690c8a2c8a1c91c3b2cf0f27baf844fd4
use std::sync::Arc; pub use super::sensei::node_server::{Node, NodeServer}; use super::{ sensei::{ CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse, CreateInvoiceRequest, CreateInvoiceResponse, DecodeInvoiceRequest, DecodeInvoiceResponse, DeletePaymentRequest, DeletePaymentResponse, GetBalanceRequest, GetBalanceResponse, GetUnusedAddressRequest, GetUnusedAddressResponse, InfoRequest, InfoResponse, KeysendRequest, KeysendResponse, LabelPaymentRequest, LabelPaymentResponse, ListChannelsRequest, ListChannelsResponse, ListPaymentsRequest, ListPaymentsResponse, ListPeersRequest, ListPeersResponse, OpenChannelRequest, OpenChannelResponse, PayInvoiceRequest, PayInvoiceResponse, SignMessageRequest, SignMessageResponse, StartNodeRequest, StartNodeResponse, StopNodeRequest, StopNodeResponse, VerifyMessageRequest, VerifyMessageResponse, }, utils::raw_macaroon_from_metadata, }; use crate::{ services::{ admin::AdminRequest, node::{NodeRequest, NodeResponse}, }, utils, }; use tonic::{metadata::MetadataMap, Response, Status}; pub struct NodeService { pub request_context: Arc<crate::RequestContext>, } impl NodeService { async fn authenticated_request( &self, metadata: MetadataMap, request: NodeRequest, ) -> Result<NodeResponse, tonic::Status> { let macaroon_hex_string = raw_macaroon_from_metadata(metadata)?; let (macaroon, session) = utils::macaroon_with_session_from_hex_str(&macaroon_hex_string) .map_err(|_e| tonic::Status::unauthenticated("invalid macaroon"))?; let pubkey = session.pubkey.clone(); let node_directory = self.request_context.node_directory.lock().await; match node_directory.get(&session.pubkey) { Some(handle) => { handle .node .verify_macaroon(macaroon, session) .await .map_err(|_e| Status::unauthenticated("invalid macaroon: failed to verify"))?; match request { NodeRequest::StopNode {} => { drop(node_directory); let admin_request = AdminRequest::StopNode { pubkey }; let _ = self .request_context .admin_service .call(admin_request) .await .map_err(|_e| Status::unknown("failed to stop node"))?; Ok(NodeResponse::StopNode {}) } _ => handle .node .call(request) .await .map_err(|_e| Status::unknown("error")), } } None => match request { NodeRequest::StartNode { passphrase } => { drop(node_directory); let admin_request = AdminRequest::StartNode { passphrase, pubkey: session.pubkey, }; let _ = self .request_context .admin_service .call(admin_request) .await .map_err(|_e| { Status::unauthenticated( "failed to start node, likely invalid passphrase", ) })?; Ok(NodeResponse::StartNode {}) } _ => Err(Status::not_found("node with that pubkey not found")), }, } } } #[tonic::async_trait] impl Node for NodeService { async fn start_node( &self, request: tonic::Request<StartNodeRequest>, ) -> Result<tonic::Response<StartNodeResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn stop_node( &self, request: tonic::Request<StopNodeRequest>, ) -> Result<tonic::Response<StopNodeResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn get_unused_address( &self, request: tonic::Request<GetUnusedAddressRequest>, ) -> Result<tonic::Response<GetUnusedAddressResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn get_balance( &self, request: tonic::Request<GetBalanceRequest>, ) -> Result<tonic::Response<GetBalanceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn open_channel( &self, request: tonic::Request<OpenChannelRequest>, ) -> Result<tonic::Response<OpenChannelResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn pay_invoice( &self, request: tonic::Request<PayInvoiceRequest>, ) -> Result<tonic::Response<PayInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn decode_invoice( &self, request: tonic::Request<DecodeInvoiceRequest>, ) -> Result<tonic::Response<DecodeInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn keysend( &self, request: tonic::Request<KeysendRequest>, ) -> Result<tonic::Response<KeysendResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn create_invoice( &self, request: tonic::Request<CreateInvoiceRequest>, ) -> Result<tonic::Response<CreateInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn label_payment( &self, request: tonic::Request<LabelPaymentRequest>, ) -> Result<tonic::Response<LabelPaymentResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn delete_payment( &self, request: tonic::Request<DeletePaymentRequest>, ) -> Result<tonic::Response<DeletePaymentResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn connect_peer( &self, request: tonic::Request<ConnectPeerRequest>, ) -> Result<tonic::Response<ConnectPeerResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_channels( &self, request: tonic::Request<ListChannelsRequest>, ) -> Result<tonic::Response<ListChannelsResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_payments( &self, request: tonic::Request<ListPaymentsRequest>, ) -> Result<tonic::Response<ListPaymentsResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn close_channel( &self, request: tonic::Request<CloseChannelRequest>, ) -> Result<tonic::Response<CloseChannelResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn info( &self, request: tonic::Request<InfoRequest>, ) -> Result<tonic::Response<InfoResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_peers( &self, request: tonic::Request<ListPeersRequest>, ) -> Result<tonic::Response<ListPeersResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn sign_message( &self, request: tonic::Request<SignMessageRequest>, ) -> Result<tonic::Response<SignMessageResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn verify_message( &self, request: tonic::Request<VerifyMessageRequest>, ) -> Result<tonic::Response<VerifyMessageResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } }
use std::sync::Arc; pub use super::sensei::node_server::{Node, NodeServer}; use super::{ sensei::{ CloseChannelRequest, CloseChannelResponse, ConnectPeerRequest, ConnectPeerResponse, CreateInvoiceRequest, CreateInvoiceResponse, DecodeInvoiceRequest, DecodeInvoiceResponse, DeletePaymentRequest, DeletePaymentResponse, GetBalanceRequest, GetBalanceResponse, GetUnusedAddressRequest, GetUnusedAddressResponse, InfoRequest, InfoResponse, KeysendRequest, KeysendResponse, LabelPaymentRequest, LabelPaymentResponse, ListChannelsRequest, ListChannelsResponse, ListPaymentsRequest, ListPaymentsResponse, ListPeersRequest, ListPeersResponse, OpenChannelRequest, OpenChannelResponse, PayInvoiceRequest, PayInvoiceResponse, SignMessageRequest, SignMessageResponse, StartNodeRequest, StartNodeResponse, StopNodeRequest, StopNodeResponse, VerifyMessageRequest, VerifyMessageResponse, }, utils::raw_macaroon_from_metadata, }; use crate::{ services::{ admin::AdminRequest, node::{NodeRequest, NodeResponse}, }, utils, }; use tonic::{metadata::MetadataMap, Response, Status}; pub struct NodeService { pub request_context: Arc<crate::RequestContext>, } impl NodeService { async fn authenticated_request( &self, metadata: MetadataMap, request: NodeRequest, ) -> Result<NodeResponse, tonic::Status> { let macaroon_hex_string = raw_macaroon_from_metadata(metadata)?; let (macaroon, session) = utils::macaroon_with_session_from_hex_str(&macaroon_hex_string) .map_err(|_e| tonic::Status::unauthenticated("invalid macaroon"))?; let pubkey = session.pubkey.clone(); let node_directory = self.request_context.node_directory.lock().await; match node_directory.get(&session.pubkey) { Some(handle) => { handle .node .verify_macaroon(macaroon, session) .await .map_err(|_e| Status::unauthenticated("invalid macaroon: failed to verify"))?;
} None => match request { NodeRequest::StartNode { passphrase } => { drop(node_directory); let admin_request = AdminRequest::StartNode { passphrase, pubkey: session.pubkey, }; let _ = self .request_context .admin_service .call(admin_request) .await .map_err(|_e| { Status::unauthenticated( "failed to start node, likely invalid passphrase", ) })?; Ok(NodeResponse::StartNode {}) } _ => Err(Status::not_found("node with that pubkey not found")), }, } } } #[tonic::async_trait] impl Node for NodeService { async fn start_node( &self, request: tonic::Request<StartNodeRequest>, ) -> Result<tonic::Response<StartNodeResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn stop_node( &self, request: tonic::Request<StopNodeRequest>, ) -> Result<tonic::Response<StopNodeResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn get_unused_address( &self, request: tonic::Request<GetUnusedAddressRequest>, ) -> Result<tonic::Response<GetUnusedAddressResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn get_balance( &self, request: tonic::Request<GetBalanceRequest>, ) -> Result<tonic::Response<GetBalanceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn open_channel( &self, request: tonic::Request<OpenChannelRequest>, ) -> Result<tonic::Response<OpenChannelResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn pay_invoice( &self, request: tonic::Request<PayInvoiceRequest>, ) -> Result<tonic::Response<PayInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn decode_invoice( &self, request: tonic::Request<DecodeInvoiceRequest>, ) -> Result<tonic::Response<DecodeInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn keysend( &self, request: tonic::Request<KeysendRequest>, ) -> Result<tonic::Response<KeysendResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn create_invoice( &self, request: tonic::Request<CreateInvoiceRequest>, ) -> Result<tonic::Response<CreateInvoiceResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn label_payment( &self, request: tonic::Request<LabelPaymentRequest>, ) -> Result<tonic::Response<LabelPaymentResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn delete_payment( &self, request: tonic::Request<DeletePaymentRequest>, ) -> Result<tonic::Response<DeletePaymentResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn connect_peer( &self, request: tonic::Request<ConnectPeerRequest>, ) -> Result<tonic::Response<ConnectPeerResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_channels( &self, request: tonic::Request<ListChannelsRequest>, ) -> Result<tonic::Response<ListChannelsResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_payments( &self, request: tonic::Request<ListPaymentsRequest>, ) -> Result<tonic::Response<ListPaymentsResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn close_channel( &self, request: tonic::Request<CloseChannelRequest>, ) -> Result<tonic::Response<CloseChannelResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn info( &self, request: tonic::Request<InfoRequest>, ) -> Result<tonic::Response<InfoResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn list_peers( &self, request: tonic::Request<ListPeersRequest>, ) -> Result<tonic::Response<ListPeersResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn sign_message( &self, request: tonic::Request<SignMessageRequest>, ) -> Result<tonic::Response<SignMessageResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } async fn verify_message( &self, request: tonic::Request<VerifyMessageRequest>, ) -> Result<tonic::Response<VerifyMessageResponse>, tonic::Status> { self.authenticated_request(request.metadata().clone(), request.into_inner().into()) .await? .try_into() .map(Response::new) .map_err(|_e| Status::unknown("unknown error")) } }
match request { NodeRequest::StopNode {} => { drop(node_directory); let admin_request = AdminRequest::StopNode { pubkey }; let _ = self .request_context .admin_service .call(admin_request) .await .map_err(|_e| Status::unknown("failed to stop node"))?; Ok(NodeResponse::StopNode {}) } _ => handle .node .call(request) .await .map_err(|_e| Status::unknown("error")), }
if_condition
[]
Rust
mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/private_join_and_compute.rs
hshshjzsami/incubator-teaclave
1a671e6e9fdb1f1bc2e1b4804ac2e516409bae63
#[cfg(feature = "mesalock_sgx")] use std::prelude::v1::*; use std::collections::HashMap; use std::fmt::Write; use crate::worker::{FunctionType, Worker, WorkerContext}; use mesatee_core::{Error, ErrorKind, Result}; pub struct PrivateJoinAndComputeWorker { worker_id: u32, func_name: String, func_type: FunctionType, input: Option<PrivateJoinAndComputeWorkerInput>, } struct PrivateJoinAndComputeWorkerInput { file_list: Vec<String>, } impl PrivateJoinAndComputeWorker { pub fn new() -> Self { PrivateJoinAndComputeWorker { worker_id: 0, func_name: "private_join_and_compute".to_string(), func_type: FunctionType::Multiparty, input: None, } } } impl Worker for PrivateJoinAndComputeWorker { fn function_name(&self) -> &str { self.func_name.as_str() } fn function_type(&self) -> FunctionType { self.func_type } fn set_id(&mut self, worker_id: u32) { self.worker_id = worker_id; } fn id(&self) -> u32 { self.worker_id } fn prepare_input( &mut self, _dynamic_input: Option<String>, file_ids: Vec<String>, ) -> Result<()> { if file_ids.len() < 2 { return Err(Error::from(ErrorKind::InvalidInputError)); } self.input = Some(PrivateJoinAndComputeWorkerInput { file_list: file_ids, }); Ok(()) } fn execute(&mut self, context: WorkerContext) -> Result<String> { let input = self .input .take() .ok_or_else(|| Error::from(ErrorKind::InvalidInputError))?; let mut counter_map: HashMap<String, usize> = HashMap::new(); let mut add_map: HashMap<String, u32> = HashMap::new(); let number = input.file_list.len(); for file_id in input.file_list.iter() { let plaintext = context.read_file(file_id)?; let records = parse_input(plaintext)?; for (identity, amount) in records.into_iter() { let value = counter_map.get(&identity).cloned().unwrap_or(0); counter_map.insert(identity.to_owned(), value + 1); let value = add_map.get(&identity).cloned().unwrap_or(0); add_map.insert(identity, value + amount); } } counter_map.retain(|_, &mut v| v == number); let mut output = String::new(); for (identity, amount) in add_map.into_iter() { if counter_map.contains_key(&identity) { writeln!(&mut output, "{} : {}", identity, amount) .map_err(|_| Error::from(ErrorKind::OutputGenerationError))?; } } let output_bytes = output.as_bytes().to_vec(); for file_id in input.file_list.iter() { let _result_file = context.save_file_for_file_owner(&output_bytes, file_id)?; } Ok("Finished".to_string()) } } fn parse_input(data: Vec<u8>) -> Result<HashMap<String, u32>> { let data_list = String::from_utf8(data).map_err(|_| Error::from(ErrorKind::InvalidInputError))?; let mut ret: HashMap<String, u32> = HashMap::new(); for data_item in data_list.split('\n') { let pair = data_item.trim(); if pair.len() < 3 { continue; } let kv_pair: Vec<&str> = pair.split(':').collect(); if kv_pair.len() != 2 { continue; } let identity = kv_pair[0].trim().to_string(); let amount = match kv_pair[1].trim().parse::<u32>() { Ok(amount) => amount, Err(_) => continue, }; ret.insert(identity, amount); } Ok(ret) }
#[cfg(feature = "mesalock_sgx")] use std::prelude::v1::*; use std::collections::HashMap; use std::fmt::Write; use crate::worker::{FunctionType, Worker, WorkerContext}; use mesatee_core::{Error, ErrorKind, Result}; pub struct PrivateJoinAndComputeWorker { worker_id: u32, func_name: String, func_type: FunctionType, input: Option<PrivateJoinAndComputeWorkerInput>, } struct PrivateJoinAndComputeWorkerInput { file_list: Vec<String>, } impl PrivateJoinAndComputeWorker { pub fn new() -> Self { PrivateJoinAndComputeWorker { worker_id: 0, func_name: "private_join_and_compute".to_string(), func_type: FunctionType::Multiparty, input: None, } } } impl Worker for PrivateJoinAndComputeWorker { fn function_name(&self) -> &str { self.func_name.as_str() } fn function_type(&self) -> FunctionType { self.func_type } fn set_id(&mut self, worker_id: u32) { self.worker_id = worker_id; } fn id(&self) -> u32 { self.worker_id } fn prepare_input( &mut self, _dynamic_input: Option<String>, file_ids: Vec<String>, ) -> Result<()> { if file_ids.len() < 2 { return Err(Error::from(ErrorKind::InvalidInputError)); } self.input = Some(PrivateJoinAndComputeWorkerInput { file_list: file_ids, }); Ok(()) } fn execute(&mut self, context: WorkerContext) -> Result<String> { let input = self .input .take() .ok_or_else(|| Error::from(ErrorKind::InvalidInputError))?; let mut counter_map: HashMap<String, usize> = HashMap::new(); let mut add_map: HashMap<String, u32> = HashMap::new(); let number = input.file_list.len(); for file_id in input.file_list.iter() { let plaintext = context.read_file(file_id)?; let records = parse_input(plaintext)?; for (identity, amount) in records.into_iter() { let value = counter_map.get(&identity).cloned().unwrap_or(0); counter_map.insert(identity.to_owned(), value + 1); let value = add_map.get(&identity).cloned().unwrap_or(0); add_map.insert(identity, value + amount); } } counter_map.retain(|_, &mut v| v == number); let mut output = String::new(); for (identity, amount) in add_map.into_iter() { if counter_map.contains_key(&identity) { writeln!(&mut output, "{} : {}", identity, amount) .map_err(|_| Error::from(ErrorKind::OutputGenerationError))?; } } let output_bytes = output.as_bytes().to_vec(); for file_id in input.file_list.iter() { let _result_file = context.save_file_for_file_owner(&output_bytes, file_id)?; } Ok("Finished".to_string()) } } fn parse_input(data: Vec<u8>) -> Result<HashMap<String, u32>> { let data_list = String::from_utf8(data).map_err(|_| Error::from(ErrorKind::InvalidInputError))?; let mut ret: HashMap<String, u32> = HashMap::new(); for data_item in data_list.split('\n') { let pair = data_item.trim(); if pair.len() < 3 { continue; } let kv_pair: Vec<&str> = pair.sp
lit(':').collect(); if kv_pair.len() != 2 { continue; } let identity = kv_pair[0].trim().to_string(); let amount = match kv_pair[1].trim().parse::<u32>() { Ok(amount) => amount, Err(_) => continue, }; ret.insert(identity, amount); } Ok(ret) }
function_block-function_prefixed
[ { "content": "pub fn percent_decode(orig: &str) -> Result<String> {\n\n let orig = orig.replace(\"%0A\", \"\");\n\n let v: Vec<&str> = orig.split('%').collect();\n\n let mut ret = String::new();\n\n ret.push_str(v[0]);\n\n if v.len() > 1 {\n\n for s in v[1..].iter() {\n\n let digit = u8::from_str_radix(&s[0..2], 16).map_err(|_| UtilsError::ParseError)?;\n\n ret.push(digit as char);\n\n ret.push_str(&s[2..]);\n\n }\n\n }\n\n Ok(ret)\n\n}\n\n\n", "file_path": "teaclave_utils/src/lib.rs", "rank": 0, "score": 338503.8424053558 }, { "content": "fn parse_input(input: &str, feature_num: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/kmeans.rs", "rank": 1, "score": 316537.9558917518 }, { "content": "pub fn read_file(context_id: &str, context_token: &str, file_id: &str) -> Result<Vec<u8>> {\n\n let mut running_task = RunningTask::retrieve_running_task(context_id, context_token)?;\n\n running_task.read_file(file_id)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/global.rs", "rank": 2, "score": 313344.4230378192 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/dbscan.rs", "rank": 3, "score": 312653.7819108343 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/svm.rs", "rank": 4, "score": 312653.78191083437 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/naive_bayes.rs", "rank": 5, "score": 309307.66979510075 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/neural_net.rs", "rank": 6, "score": 309307.6697951007 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gaussian_processes.rs", "rank": 7, "score": 309307.6697951007 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/lin_reg.rs", "rank": 8, "score": 309307.6697951007 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gen_linear_model.rs", "rank": 9, "score": 306064.1445400532 }, { "content": "fn parse_input_to_matrix(input: &str, input_model_data_columns: usize) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n\n\n\n for feature_str in features {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f64 = trimed_feature_str\n\n .parse()\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gaussian_mixture_model.rs", "rank": 10, "score": 306064.14454005327 }, { "content": "pub fn parse_a_wast(wast_file: &str) -> Result<Vec<Command>, String> {\n\n let wast_content: Vec<u8> = std::fs::read(wast_file).unwrap();\n\n let path = std::path::Path::new(wast_file);\n\n let fnme = path.file_name().unwrap().to_str().unwrap();\n\n let mut parser = ScriptParser::from_source_and_name(&wast_content, fnme).unwrap();\n\n let mut commands: Vec<Command> = Vec::new();\n\n while let Some(command) = match parser.next() {\n\n Ok(x) => x,\n\n _ => {\n\n return Err(\"Error parsing test input\".to_string());\n\n }\n\n } {\n\n commands.push(command);\n\n }\n\n Ok(commands)\n\n}\n\n\n", "file_path": "tests/integration_test/src/wasm/wasmi_faas.rs", "rank": 11, "score": 299161.7389812879 }, { "content": "fn parse_input_to_matrix(input: &str) -> Result<Matrix<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n let mut sample_num = 0;\n\n let columns_num = if !lines.is_empty() && !lines[0].trim().is_empty() {\n\n let first_line: Vec<&str> = lines[0].trim().split(',').collect();\n\n first_line.len()\n\n } else {\n\n 0\n\n };\n\n\n\n if columns_num > 0 {\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut point: Vec<f64> = Vec::new();\n\n let features = trimed_line.split(',');\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/logistic_reg.rs", "rank": 13, "score": 295444.1480179575 }, { "content": "fn parse_input_to_vector(input: &str) -> Result<Vector<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n\n\n if !lines.is_empty() && !lines[0].trim().is_empty() {\n\n for c in input.lines() {\n\n let value = c\n\n .parse::<f64>()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n raw_cluster_data.push(value);\n\n }\n\n }\n\n\n\n let target_data = Vector::new(raw_cluster_data);\n\n Ok(target_data)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/logistic_reg.rs", "rank": 14, "score": 295444.1480179575 }, { "content": "fn parse_train_data(input: &str) -> Result<Vec<Data>> {\n\n let mut v: Vec<f32>;\n\n let mut samples: Vec<Data> = Vec::new();\n\n let mut sample_label_index = 0;\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n\n\n // get the label_index\n\n if !lines.is_empty() && !lines[0].trim().is_empty() {\n\n let first_line: Vec<&str> = lines[0].trim().split(',').collect();\n\n if first_line.len() > 2 {\n\n sample_label_index = first_line.len() - 1;\n\n }\n\n }\n\n\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gbdt_worker.rs", "rank": 15, "score": 295320.9230697698 }, { "content": "fn parse_test_data(input: &str) -> Result<Vec<Data>> {\n\n let mut samples: Vec<Data> = Vec::new();\n\n let lines: Vec<&str> = input.split('\\n').collect();\n\n for line in lines.iter() {\n\n let trimed_line = line.trim();\n\n if trimed_line.is_empty() {\n\n continue;\n\n }\n\n let mut features: Vec<f32> = Vec::new();\n\n for feature_str in trimed_line.split(',') {\n\n let trimed_feature_str = feature_str.trim();\n\n if trimed_feature_str.is_empty() {\n\n continue;\n\n }\n\n let feature: f32 = trimed_feature_str\n\n .parse()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n features.push(feature);\n\n }\n\n let sample = Data::new_test_data(features, None);\n\n samples.push(sample);\n\n }\n\n Ok(samples)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gbdt_worker.rs", "rank": 16, "score": 295320.92306976987 }, { "content": "fn data_to_vector(input: &str) -> Result<Vector<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n for c in input.lines() {\n\n let value = c\n\n .parse::<f64>()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n raw_cluster_data.push(value);\n\n }\n\n\n\n let target_data = Vector::new(raw_cluster_data);\n\n Ok(target_data)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/svm.rs", "rank": 17, "score": 289250.91389368236 }, { "content": "fn data_to_vector(input: &str) -> Result<Vector<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n for c in input.lines() {\n\n let value = c\n\n .parse::<f64>()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n raw_cluster_data.push(value);\n\n }\n\n\n\n let target_data = Vector::new(raw_cluster_data);\n\n Ok(target_data)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/lin_reg.rs", "rank": 18, "score": 285716.0738500989 }, { "content": "fn data_to_vector(input: &str) -> Result<Vector<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n for c in input.lines() {\n\n let value = c\n\n .parse::<f64>()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n raw_cluster_data.push(value);\n\n }\n\n\n\n let target_data = Vector::new(raw_cluster_data);\n\n Ok(target_data)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gaussian_processes.rs", "rank": 19, "score": 285716.0738500989 }, { "content": "fn data_to_vector(input: &str) -> Result<Vector<f64>> {\n\n let mut raw_cluster_data = Vec::new();\n\n\n\n for c in input.lines() {\n\n let value = c\n\n .parse::<f64>()\n\n .map_err(|_| Error::from(ErrorKind::InvalidInputError))?;\n\n raw_cluster_data.push(value);\n\n }\n\n\n\n let target_data = Vector::new(raw_cluster_data);\n\n Ok(target_data)\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/gen_linear_model.rs", "rank": 20, "score": 282310.14668456983 }, { "content": "#[cfg(feature = \"mesalock_sgx\")]\n\npub fn init_service(name: &str) -> Result<()> {\n\n use std::backtrace;\n\n env_logger::init();\n\n\n\n debug!(\"Enclave [{}]: Initializing...\", name);\n\n\n\n if backtrace::enable_backtrace(format!(\"{}.signed.so\", name), backtrace::PrintFormat::Full)\n\n .is_err()\n\n {\n\n error!(\"Cannot enable backtrace\");\n\n return Err(Error::from(ErrorKind::ECallError));\n\n }\n\n if !config::is_runtime_config_initialized() {\n\n error!(\"Runtime config is not initialized\");\n\n return Err(Error::from(ErrorKind::ECallError));\n\n }\n\n crate::rpc::sgx::prelude()?;\n\n\n\n Ok(())\n\n}\n", "file_path": "mesatee_core/src/lib.rs", "rank": 21, "score": 280578.729872873 }, { "content": "pub fn gen_token() -> Result<String> {\n\n use rand::prelude::RngCore;\n\n let mut token: [u8; 16] = [0; 16];\n\n let mut rng = rand::thread_rng();\n\n rng.fill_bytes(&mut token);\n\n let mut hex_token = String::new();\n\n for &byte in &token {\n\n write!(&mut hex_token, \"{:02x}\", byte)\n\n .map_err(|_| mesatee_core::Error::from(mesatee_core::ErrorKind::Unknown))?;\n\n }\n\n Ok(hex_token)\n\n}\n\n\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/data_store.rs", "rank": 22, "score": 275182.9166130173 }, { "content": "pub fn unit_test<F, R>(ncases: &mut u64, failurecases: &mut Vec<String>, f: F, name: &str)\n\nwhere\n\n F: FnOnce() -> R + std::panic::UnwindSafe,\n\n{\n\n *ncases += 1;\n\n let ret = std::panic::catch_unwind(|| {\n\n f();\n\n });\n\n if ret.is_ok() {\n\n println!(\"testing {} ... \\x1B[1;32mok\\x1B[0m!\", name);\n\n } else {\n\n println!(\"testing {} ... \\x1B[1;31mfailed\\x1B[0m!\", name);\n\n failurecases.push(String::from(name));\n\n }\n\n}\n", "file_path": "tests/functional_test/sgx_app/src/unittest.rs", "rank": 23, "score": 273768.56813921395 }, { "content": "pub fn del_file(file_id: &str) -> Result<FileMeta> {\n\n let file_meta = FILE_STORE\n\n .del(&file_id.to_owned())?\n\n .ok_or_else(|| Error::from(ErrorKind::MissingValue))?;\n\n let _lock = UPDATELOCK.lock()?;\n\n del_file_for_user(file_id, &file_meta.user_id)?;\n\n if file_meta.allow_policy == 1 {\n\n for collaborator in file_meta.collaborator_list.iter() {\n\n del_file_for_user(file_id, &collaborator)?;\n\n }\n\n }\n\n Ok(file_meta)\n\n}\n\n\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/data_store.rs", "rank": 24, "score": 272971.06398717174 }, { "content": "pub fn add_file(file_id: &str, file_meta: &FileMeta) -> Result<()> {\n\n let _ = FILE_STORE.set(&file_id.to_owned(), &file_meta)?;\n\n let _lock = UPDATELOCK.lock()?;\n\n add_file_to_user(file_id, &file_meta.user_id)?;\n\n if file_meta.allow_policy == 1 {\n\n for collaborator in file_meta.collaborator_list.iter() {\n\n add_file_to_user(file_id, &collaborator)?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/data_store.rs", "rank": 25, "score": 259670.67745401023 }, { "content": "pub fn cal_hash(data: &[u8]) -> Result<String> {\n\n let digest_alg = &digest::SHA256;\n\n let mut ctx = digest::Context::new(digest_alg);\n\n ctx.update(data);\n\n let digest_result = ctx.finish();\n\n let digest_bytes: &[u8] = digest_result.as_ref();\n\n let mut digest_hex = String::new();\n\n for &byte in digest_bytes {\n\n write!(&mut digest_hex, \"{:02x}\", byte).map_err(|_| Error::from(ErrorKind::Unknown))?;\n\n }\n\n Ok(digest_hex)\n\n}\n\n\n", "file_path": "mesatee_services/tdfs/internal/client/src/file_util.rs", "rank": 26, "score": 256368.7221022279 }, { "content": "pub fn decode_spid(hex: &str) -> Result<sgx_types::sgx_spid_t> {\n\n let mut spid = sgx_types::sgx_spid_t::default();\n\n let hex = hex.trim();\n\n\n\n if hex.len() < 16 * 2 {\n\n return Err(UtilsError::ParseError);\n\n }\n\n\n\n let decoded_vec = decode_hex(hex)?;\n\n\n\n spid.id.copy_from_slice(&decoded_vec[..16]);\n\n\n\n Ok(spid)\n\n}\n\n\n", "file_path": "teaclave_utils/src/lib.rs", "rank": 27, "score": 252972.77234816743 }, { "content": "pub fn try_load(wasm: &[u8], spec_driver: &mut SpecDriver) -> Result<(), Error> {\n\n let module = try_load_module(wasm)?;\n\n let instance = ModuleInstance::new(&module, &ImportsBuilder::default())?;\n\n instance\n\n .run_start(spec_driver.spec_module())\n\n .map_err(|trap| Error::Start(trap))?;\n\n Ok(())\n\n}*/\n\n\n\n/*\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 28, "score": 252111.90989460424 }, { "content": "pub fn send_vec<T>(sock: &mut T, mut buff: Vec<u8>) -> Result<()>\n\nwhere\n\n T: Write,\n\n{\n\n if buff.len() as u64 > BUILD_CONFIG.rpc_max_message_size {\n\n return Err(Error::from(ErrorKind::MsgSizeLimitExceedError));\n\n }\n\n let send_vec = get_send_vec(&mut buff);\n\n\n\n sock.write_all(&send_vec)?;\n\n sock.flush()?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "mesatee_core/src/rpc/sendrecv.rs", "rank": 29, "score": 248652.04390456015 }, { "content": "pub fn receive_vec<T>(sock: &mut T) -> Result<Vec<u8>>\n\nwhere\n\n T: Read,\n\n{\n\n let mut br = BufReader::new(sock);\n\n let mut lbuf: [u8; 8] = [0; 8];\n\n\n\n br.read_exact(&mut lbuf)?;\n\n\n\n let buf_len: u64 = u64::from_be(unsafe { transmute::<[u8; 8], u64>(lbuf) });\n\n if buf_len > BUILD_CONFIG.rpc_max_message_size {\n\n return Err(Error::from(ErrorKind::MsgSizeLimitExceedError));\n\n }\n\n\n\n let mut recv_buf: Vec<u8> = vec![0u8; buf_len as usize];\n\n\n\n br.read_exact(&mut recv_buf)?;\n\n\n\n Ok(recv_buf)\n\n}\n", "file_path": "mesatee_core/src/rpc/sendrecv.rs", "rank": 30, "score": 239590.24680136828 }, { "content": "pub fn send_vec<T>(sock: &mut T, buf: &[u8]) -> Result<()>\n\nwhere\n\n T: Write,\n\n{\n\n let buf_len: u64 = buf.len() as u64;\n\n let lbuf: [u8; 8] = unsafe { transmute(buf_len.to_be()) };\n\n sock.write_all(&lbuf)?;\n\n sock.write_all(&buf)?;\n\n sock.flush()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/integration_test/src/sendrecv.rs", "rank": 31, "score": 239590.24680136828 }, { "content": "pub fn recv_vec<T>(sock: &mut T) -> Result<Vec<u8>>\n\nwhere\n\n T: Read,\n\n{\n\n let mut br = BufReader::new(sock);\n\n let mut lbuf: [u8; 8] = [0; 8];\n\n br.read_exact(&mut lbuf)?;\n\n let buf_len: u64 = u64::from_be(unsafe { transmute::<[u8; 8], u64>(lbuf) });\n\n let mut recv_buf: Vec<u8> = vec![0u8; buf_len as usize];\n\n br.read_exact(&mut recv_buf)?;\n\n Ok(recv_buf)\n\n}\n", "file_path": "tests/integration_test/src/sendrecv.rs", "rank": 32, "score": 239590.24680136828 }, { "content": "pub fn add_task(task_id: &str, task_info: &TaskInfo) -> Result<()> {\n\n let _ = TASK_STORE.set(&task_id.to_owned(), &task_info)?;\n\n let _lock = UPDATELOCK.lock()?;\n\n add_task_to_user(task_id, &task_info.user_id)?;\n\n for collaborator in task_info.collaborator_list.iter() {\n\n add_task_to_user(task_id, &collaborator.user_id)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/data_store.rs", "rank": 33, "score": 235633.54949091334 }, { "content": "pub fn load_enclave_info(content: &str) -> std::collections::HashMap<String, EnclaveMeasurement> {\n\n let config: EnclaveInfoToml =\n\n toml::from_str(&content).expect(\"Content not correct, unable to load enclave info.\");\n\n let mut info_map = std::collections::HashMap::new();\n\n for (k, v) in config.0 {\n\n info_map.insert(k, EnclaveMeasurement::new(v.mr_enclave, v.mr_signer));\n\n }\n\n\n\n info_map\n\n}\n", "file_path": "teaclave_utils/src/lib.rs", "rank": 34, "score": 234014.09062755812 }, { "content": "/// err returns a new Status wrapped in a Result.\n\npub fn err<T>(code: StatusCode, msg: &str) -> Result<T> {\n\n Err(Status::new(code, msg))\n\n}\n\n\n\nimpl From<io::Error> for Status {\n\n fn from(e: io::Error) -> Status {\n\n let c = match e.kind() {\n\n io::ErrorKind::NotFound => StatusCode::NotFound,\n\n io::ErrorKind::InvalidData => StatusCode::Corruption,\n\n io::ErrorKind::InvalidInput => StatusCode::InvalidArgument,\n\n io::ErrorKind::PermissionDenied => StatusCode::PermissionDenied,\n\n _ => StatusCode::IOError,\n\n };\n\n\n\n Status::new(c, e.description())\n\n }\n\n}\n\n\n\nimpl<T> From<sync::PoisonError<T>> for Status {\n\n fn from(_: sync::PoisonError<T>) -> Status {\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/error.rs", "rank": 35, "score": 233385.4742531694 }, { "content": "// Before calling this function, use lock to avoid data race;\n\nfn add_file_to_user(file_id: &str, user_id: &str) -> Result<()> {\n\n let uid = user_id.to_owned();\n\n let id_set = USER_FILE_STORE.get(&uid)?;\n\n match id_set {\n\n Some(mut set) => {\n\n set.insert(file_id.to_owned());\n\n USER_FILE_STORE.set(&uid, &set)?;\n\n }\n\n None => {\n\n let mut set = HashSet::<String>::new();\n\n set.insert(file_id.to_owned());\n\n USER_FILE_STORE.set(&uid, &set)?;\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/data_store.rs", "rank": 36, "score": 233064.9844667951 }, { "content": "// Before calling this function, use lock to avoid data race;\n\nfn del_file_for_user(file_id: &str, user_id: &str) -> Result<()> {\n\n let uid = user_id.to_owned();\n\n let id_set = USER_FILE_STORE.get(&uid)?;\n\n if let Some(mut set) = id_set {\n\n set.remove(&file_id.to_owned());\n\n USER_FILE_STORE.set(&uid, &set)?;\n\n }\n\n Ok(())\n\n}\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/data_store.rs", "rank": 37, "score": 233064.9844667951 }, { "content": "pub fn mask_crc(c: u32) -> u32 {\n\n (c.wrapping_shr(15) | c.wrapping_shl(17)).wrapping_add(MASK_DELTA)\n\n}\n\n\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/log.rs", "rank": 38, "score": 228084.24238353607 }, { "content": "pub fn result_covert(\n\n res: Result<Option<RuntimeValue>, InterpreterError>,\n\n) -> Result<Option<BoundaryValue>, InterpreterError> {\n\n match res {\n\n Ok(None) => Ok(None),\n\n Ok(Some(rv)) => Ok(Some(runtime_value_to_boundary_value(rv))),\n\n Err(x) => Err(x),\n\n }\n\n}\n\n\n\npub struct SpecModule {\n\n table: TableRef,\n\n memory: MemoryRef,\n\n global_i32: GlobalRef,\n\n global_f32: GlobalRef,\n\n global_f64: GlobalRef,\n\n}\n\n\n\nimpl SpecModule {\n\n pub fn new() -> Self {\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 39, "score": 226349.6659381806 }, { "content": "pub fn unmask_crc(mc: u32) -> u32 {\n\n let rot = mc.wrapping_sub(MASK_DELTA);\n\n (rot.wrapping_shr(17) | rot.wrapping_shl(15))\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 #[test]\n\n fn test_crc_mask_crc() {\n\n let crc = crc32::checksum_castagnoli(\"abcde\".as_bytes());\n\n assert_eq!(crc, unmask_crc(mask_crc(crc)));\n\n assert!(crc != mask_crc(crc));\n\n }\n\n\n\n #[test]\n\n fn test_crc_sanity() {\n\n assert_eq!(0x8a9136aa, crc32::checksum_castagnoli(&[0 as u8; 32]));\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/log.rs", "rank": 40, "score": 225637.95918657142 }, { "content": "#[cfg(feature = \"mesalock_sgx\")]\n\npub fn prelude() -> Result<()> {\n\n // Hard coded RACredential validity in seconds for all enclave.\n\n // We may allow each enclave to setup its own validity in the future.\n\n ra::init_ra_credential(86400u64)\n\n}\n\n\n\n#[cfg(feature = \"mesalock_sgx\")]\n\npub struct PipeConfig {\n\n pub fd: c_int,\n\n // the SGX server can optionally verify the identity of the client\n\n pub client_verifier: Option<SgxQuoteVerifier>,\n\n}\n\n\n\n#[cfg(feature = \"mesalock_sgx\")]\n\npub struct Pipe<U, V, X> {\n\n inner: rustls::StreamOwned<rustls::ServerSession, TcpStream>,\n\n u: PhantomData<U>,\n\n v: PhantomData<V>,\n\n x: PhantomData<X>,\n\n}\n", "file_path": "mesatee_core/src/rpc/sgx/mod.rs", "rank": 41, "score": 225549.56877387184 }, { "content": "pub fn spec_to_runtime_value(value: Value) -> RuntimeValue {\n\n match value {\n\n Value::I32(v) => RuntimeValue::I32(v),\n\n Value::I64(v) => RuntimeValue::I64(v),\n\n Value::F32(v) => RuntimeValue::F32(v.into()),\n\n Value::F64(v) => RuntimeValue::F64(v.into()),\n\n }\n\n}*/\n\n\n\n#[derive(Debug)]\n\npub enum Error {\n\n //Load(String),\n\n //Start(Trap),\n\n Script(script::Error),\n\n Interpreter(InterpreterError),\n\n}\n\n\n\nimpl From<InterpreterError> for Error {\n\n fn from(e: InterpreterError) -> Error {\n\n Error::Interpreter(e)\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 42, "score": 221419.36432070914 }, { "content": "pub fn read_current_file(env: &Box<dyn Env>, dbname: &Path) -> Result<String> {\n\n let mut current = String::new();\n\n let mut f = env.open_sequential_file(Path::new(&current_file_name(dbname)))?;\n\n f.read_to_string(&mut current)?;\n\n if current.is_empty() || !current.ends_with('\\n') {\n\n return err(\n\n StatusCode::Corruption,\n\n \"current file is empty or has no newline\",\n\n );\n\n }\n\n Ok(current)\n\n}\n\n\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/version_set.rs", "rank": 43, "score": 221038.84910556796 }, { "content": "pub fn path_to_string(p: &Path) -> String {\n\n p.to_str().map(String::from).unwrap()\n\n}\n\n\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/env.rs", "rank": 44, "score": 216958.748211661 }, { "content": "pub fn boundary_value_to_runtime_value(rv: BoundaryValue) -> RuntimeValue {\n\n match rv {\n\n BoundaryValue::I32(bv) => RuntimeValue::I32(bv),\n\n BoundaryValue::I64(bv) => RuntimeValue::I64(bv),\n\n BoundaryValue::F32(bv) => RuntimeValue::F32(f32::from_bits(bv).into()),\n\n BoundaryValue::F64(bv) => RuntimeValue::F64(f64::from_bits(bv).into()),\n\n }\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 45, "score": 216661.99464592797 }, { "content": "pub fn runtime_value_to_boundary_value(rv: RuntimeValue) -> BoundaryValue {\n\n match rv {\n\n RuntimeValue::I32(rv) => BoundaryValue::I32(rv),\n\n RuntimeValue::I64(rv) => BoundaryValue::I64(rv),\n\n RuntimeValue::F32(rv) => BoundaryValue::F32(rv.to_bits()),\n\n RuntimeValue::F64(rv) => BoundaryValue::F64(rv.to_bits()),\n\n }\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 46, "score": 216661.99464592797 }, { "content": "pub fn unit_test_end(ntestcases: u64, failurecases: Vec<String>) -> usize {\n\n let ntotal = ntestcases as usize;\n\n let nsucc = ntestcases as usize - failurecases.len();\n\n\n\n if !failurecases.is_empty() {\n\n print!(\"\\nfailures: \");\n\n println!(\n\n \" {}\",\n\n failurecases\n\n .iter()\n\n .fold(String::new(), |s, per| s + \"\\n \" + per)\n\n );\n\n }\n\n\n\n if ntotal == nsucc {\n\n print!(\"\\ntest result \\x1B[1;32mok\\x1B[0m. \");\n\n } else {\n\n print!(\"\\ntest result \\x1B[1;31mFAILED\\x1B[0m. \");\n\n }\n\n\n\n println!(\n\n \"{} tested, {} passed, {} failed\",\n\n ntotal,\n\n nsucc,\n\n ntotal - nsucc\n\n );\n\n failurecases.len()\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_app/src/unittest.rs", "rank": 47, "score": 216652.98420391546 }, { "content": "pub fn path_to_str(p: &Path) -> &str {\n\n p.to_str().unwrap()\n\n}\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/env.rs", "rank": 48, "score": 216644.04729693232 }, { "content": "pub fn ob(x: usize, y: usize) -> bool {\n\n let ret: bool;\n\n unsafe {\n\n asm!(\n\n \"cmp %rdx, %rcx \\n\\t\n\n setb %al \\n\\t\"\n\n : \"={al}\"(ret)\n\n : \"{rcx}\"(x), \"{rdx}\" (y)\n\n : \"rcx\", \"rdx\"\n\n : \"volatile\"\n\n );\n\n }\n\n ret\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/psi/basic.rs", "rank": 49, "score": 212238.90007517202 }, { "content": "pub fn oequal(x: usize, y: usize) -> bool {\n\n let ret: bool;\n\n unsafe {\n\n asm!(\n\n \"cmp %rcx, %rdx \\n\\t\n\n sete %al \\n\\t\"\n\n : \"={al}\"(ret)\n\n : \"{rcx}\"(x), \"{rdx}\" (y)\n\n : \"rcx\", \"rdx\"\n\n : \"volatile\"\n\n );\n\n }\n\n ret\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/psi/basic.rs", "rank": 50, "score": 212238.90007517202 }, { "content": "pub fn try_load_module(wasm: &[u8]) -> Result<Module, Error> {\n\n Module::from_buffer(wasm).map_err(|e| Error::Load(e.to_string()))\n\n}*/\n\n\n\n/*\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 51, "score": 211480.4164031645 }, { "content": "pub fn test_one_wasmi(wast_file: &str) {\n\n trace!(\">>>>> test_one_wasmi\");\n\n\n\n let commands = wasmi_faas::parse_a_wast(wast_file).unwrap();\n\n let actions = wasmi_faas::get_sgx_action(&commands);\n\n let request = serde_json::to_string(&actions).unwrap();\n\n\n\n let function_name = \"wasmi_from_buffer\";\n\n let payload = Some(request.as_str());\n\n let response = launch_single_task(&USER_ONE, function_name, payload);\n\n\n\n let results: Vec<Result<Option<BoundaryValue>, FaasInterpreterError>> =\n\n serde_json::from_str(&response).unwrap();\n\n assert!(wasmi_faas::match_result(commands, results));\n\n}\n\n\n", "file_path": "tests/integration_test/src/wasm/mod.rs", "rank": 52, "score": 207813.23390329548 }, { "content": "// Before calling this function, use lock to avoid data race;\n\nfn add_task_to_user(task_id: &str, user_id: &str) -> Result<()> {\n\n let uid = user_id.to_owned();\n\n let id_set = USER_TASK_STORE.get(&uid)?;\n\n match id_set {\n\n Some(mut set) => {\n\n set.insert(task_id.to_owned());\n\n USER_TASK_STORE.set(&uid, &set)?;\n\n }\n\n None => {\n\n let mut set = HashSet::<String>::new();\n\n set.insert(task_id.to_owned());\n\n USER_TASK_STORE.set(&uid, &set)?;\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/data_store.rs", "rank": 53, "score": 207375.30942100746 }, { "content": "fn decode_hex(hex: &str) -> Result<Vec<u8>> {\n\n let mut r: Vec<u8> = Vec::new();\n\n let mut chars = hex.chars().enumerate();\n\n loop {\n\n let (_, first) = match chars.next() {\n\n None => break,\n\n Some(elt) => elt,\n\n };\n\n if first == ' ' {\n\n continue;\n\n }\n\n let (_, second) = chars.next().ok_or_else(|| UtilsError::ParseError)?;\n\n r.push((decode_hex_digit(first)? << 4) | decode_hex_digit(second)?);\n\n }\n\n Ok(r)\n\n}\n\n\n", "file_path": "teaclave_utils/src/lib.rs", "rank": 55, "score": 202090.6213270453 }, { "content": "pub fn verify_user(_user_id: &str, user_token: &str) -> bool {\n\n if user_token == \"error_token\" {\n\n return false;\n\n }\n\n true\n\n}\n\n\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/data_store.rs", "rank": 56, "score": 202017.09433596785 }, { "content": "pub fn verify_user(_user_id: &str, user_token: &str) -> bool {\n\n if user_token == \"error_token\" {\n\n return false;\n\n }\n\n true\n\n}\n\n\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/data_store.rs", "rank": 57, "score": 202017.09433596785 }, { "content": "fn fill_db(db: &mut DB, entries: usize) -> Result<(), Box<dyn Error>> {\n\n for i in 0..entries {\n\n let (k, v) = (gen_string(KEY_LEN), gen_string(VAL_LEN));\n\n db.put(k.as_bytes(), v.as_bytes())?;\n\n if i % 1000 == 0 {\n\n db.flush()?;\n\n\n\n let v2 = db\n\n .get(k.as_bytes())\n\n .ok_or_else(|| Box::new(io::Error::new(ErrorKind::NotFound, \"Key not found\")))?;\n\n assert_eq!(&v.as_bytes()[..], &v2[..]);\n\n\n\n db.delete(k.as_bytes())?;\n\n assert_eq!(true, db.get(k.as_bytes()).is_none());\n\n }\n\n\n\n if i % 100 == 0 {\n\n db.flush()?;\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/tests/leveldb_test.rs", "rank": 58, "score": 199487.24726999525 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n debug!(\"Enclave [KMS]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n", "file_path": "mesatee_services/kms/sgx_trusted_lib/src/sgx.rs", "rank": 59, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectionOutput> {\n\n debug!(\"Enclave [ACS]: Serve Connection.\");\n\n\n\n let acs_config = config::Internal::acs();\n\n assert_eq!(args.port, acs_config.addr.port());\n\n\n\n let enclave_attr = match acs_config.inbound_desc {\n\n config::InboundDesc::Sgx(enclave_attr) => Some(enclave_attr),\n\n _ => unreachable!(),\n\n };\n\n\n\n let server = match SgxTrustedServer::new(ACSEnclave::default(), args.socket_fd, enclave_attr) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"New server failed: {:?}.\", e);\n\n return Ok(ServeConnectionOutput::default());\n\n }\n\n };\n\n let _ = server.start();\n\n\n\n // We discard all enclave internal errors here.\n\n Ok(ServeConnectionOutput::default())\n\n}\n\n\n\nconst MODEL_TEXT: &str = include_str!(\"../../model.conf\");\n\n\n", "file_path": "mesatee_services/acs/sgx_trusted_lib/src/sgx.rs", "rank": 60, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n Ok(InitEnclaveOutput::default())\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/sgx.rs", "rank": 61, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectionOutput> {\n\n debug!(\"Enclave [KMS]: Serve Connection.\");\n\n\n\n let kms_config = config::Internal::kms();\n\n assert_eq!(args.port, kms_config.addr.port());\n\n\n\n let enclave_attr = match kms_config.inbound_desc {\n\n config::InboundDesc::Sgx(enclave_attr) => Some(enclave_attr),\n\n _ => unreachable!(),\n\n };\n\n let server = match SgxTrustedServer::new(KMSEnclave::default(), args.socket_fd, enclave_attr) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"New server failed: {:?}.\", e);\n\n return Ok(ServeConnectionOutput::default());\n\n }\n\n };\n\n let _ = server.start();\n\n\n\n // We discard all enclave internal errors here.\n\n Ok(ServeConnectionOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/kms/sgx_trusted_lib/src/sgx.rs", "rank": 62, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n info!(\"Enclave [Functional Test]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/sgx.rs", "rank": 63, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n debug!(\"Enclave [ACS]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n", "file_path": "mesatee_services/acs/sgx_trusted_lib/src/sgx.rs", "rank": 64, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n debug!(\"Enclave [TMS]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/sgx.rs", "rank": 65, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n Ok(InitEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/kms/sgx_trusted_lib/src/sgx.rs", "rank": 66, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n eprintln!(\"setting up acs model\");\n\n\n\n let ec = unsafe { acs_setup_model(CString::new(MODEL_TEXT).unwrap().as_ptr()) };\n\n\n\n if ec != 0 {\n\n Err(Error::from(ErrorKind::MesaPyError))\n\n } else {\n\n Ok(InitEnclaveOutput::default())\n\n }\n\n}\n\n\n", "file_path": "mesatee_services/acs/sgx_trusted_lib/src/sgx.rs", "rank": 67, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n if cfg!(test_mode) {\n\n crate::data_store::add_test_information();\n\n }\n\n\n\n Ok(InitEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/sgx.rs", "rank": 68, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectionOutput> {\n\n debug!(\"Enclave [TMS]: Serve Connection.\");\n\n\n\n let internal = config::Internal::tms();\n\n let external = config::External::tms();\n\n\n\n if args.port == internal.addr.port() {\n\n let enclave_attr = match internal.inbound_desc {\n\n config::InboundDesc::Sgx(enclave_attr) => Some(enclave_attr),\n\n _ => unreachable!(),\n\n };\n\n\n\n let server = match SgxTrustedServer::new(\n\n TMSInternalEnclave::default(),\n\n args.socket_fd,\n\n enclave_attr,\n\n ) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"New server failed: {:?}.\", e);\n", "file_path": "mesatee_services/tms/sgx_trusted_lib/src/sgx.rs", "rank": 69, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectionOutput> {\n\n debug!(\"Enclave [TDFS]: Serve Connection.\");\n\n let internal = config::Internal::tdfs();\n\n let external = config::External::tdfs();\n\n\n\n let fd = args.socket_fd;\n\n if args.port == internal.addr.port() {\n\n let enclave_attr = match internal.inbound_desc {\n\n config::InboundDesc::Sgx(enclave_attr) => Some(enclave_attr),\n\n _ => unreachable!(),\n\n };\n\n\n\n let server = match SgxTrustedServer::new(DFSInternalEnclave::default(), fd, enclave_attr) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"New server failed: {:?}.\", e);\n\n return Ok(ServeConnectionOutput::default());\n\n }\n\n };\n\n let _ = server.start();\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs", "rank": 70, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n add_test_infomation();\n\n\n\n Ok(InitEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs", "rank": 71, "score": 198351.13863895196 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n debug!(\"Enclave [TDFS]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n", "file_path": "mesatee_services/tdfs/sgx_trusted_lib/src/sgx.rs", "rank": 72, "score": 198351.13863895196 }, { "content": "pub fn match_result(\n\n commands: Vec<Command>,\n\n results: Vec<Result<Option<BoundaryValue>, FaasInterpreterError>>,\n\n) -> bool {\n\n if commands.len() != results.len() {\n\n return false;\n\n }\n\n for (command, result) in commands.iter().zip(results.into_iter()) {\n\n let result: Result<Option<RuntimeValue>, FaasInterpreterError> = answer_convert(result);\n\n let line = &command.line;\n\n match &command.kind {\n\n CommandKind::Module { .. } => {\n\n if result.is_err() {\n\n println!(\"failed to load moduel\");\n\n return false;\n\n }\n\n }\n\n CommandKind::AssertReturn { expected, .. } => {\n\n match result {\n\n Ok(result) => {\n", "file_path": "tests/integration_test/src/wasm/wasmi_faas.rs", "rank": 73, "score": 196701.53324032822 }, { "content": "#[handle_ecall]\n\nfn handle_init_enclave(_args: &InitEnclaveInput) -> Result<InitEnclaveOutput> {\n\n mesatee_core::init_service(env!(\"CARGO_PKG_NAME\"))?;\n\n\n\n register_trusted_worker_statically();\n\n Ok(InitEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs", "rank": 74, "score": 195720.08270954285 }, { "content": "#[handle_ecall]\n\nfn handle_finalize_enclave(_args: &FinalizeEnclaveInput) -> Result<FinalizeEnclaveOutput> {\n\n #[cfg(feature = \"cov\")]\n\n sgx_cov::cov_writeout();\n\n\n\n debug!(\"Enclave [FNS]: Finalized.\");\n\n Ok(FinalizeEnclaveOutput::default())\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs", "rank": 75, "score": 195720.08270954285 }, { "content": "#[handle_ecall]\n\nfn handle_serve_connection(args: &ServeConnectionInput) -> Result<ServeConnectionOutput> {\n\n debug!(\"Enclave [FNS]: Serve Connection.\");\n\n\n\n let fns_config = config::External::fns();\n\n assert_eq!(args.port, fns_config.addr.port());\n\n\n\n let enclave_attr = match fns_config.inbound_desc {\n\n config::InboundDesc::External => None,\n\n _ => unreachable!(),\n\n };\n\n let server = match SgxTrustedServer::new(FNSEnclave::default(), args.socket_fd, enclave_attr) {\n\n Ok(s) => s,\n\n Err(e) => {\n\n error!(\"New server failed: {:?}.\", e);\n\n return Ok(ServeConnectionOutput::default());\n\n }\n\n };\n\n let _ = server.start();\n\n\n\n // We discard all enclave internal errors here.\n\n Ok(ServeConnectionOutput::default())\n\n}\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/sgx/mod.rs", "rank": 76, "score": 195720.08270954288 }, { "content": "// Parameter `pattern` is the expected response pattern defined in `test.toml`.\n\n// We invalidate all regex meta characters by escaping the pattern string.\n\n// Then we empower character `*` (already escaped to `\\\\*`) with a special meaning as regex meta `.*`.\n\nfn create_wildcard_regex(pattern: &str) -> Result<Regex, ExitFailure> {\n\n let escaped_pattern = regex::escape(&pattern.trim());\n\n let p = escaped_pattern.replace(\"\\\\*\", \".*\");\n\n Ok(Regex::new(&p)?)\n\n}\n\n\n", "file_path": "tests/integration_test/src/test.rs", "rank": 77, "score": 194344.37254638062 }, { "content": "/// new_version_iter returns an iterator over the entries in the specified ordered list of table\n\n/// files.\n\npub fn new_version_iter(\n\n files: Vec<FileMetaHandle>,\n\n cache: Shared<TableCache>,\n\n ucmp: Rc<Box<dyn Cmp>>,\n\n) -> VersionIter {\n\n VersionIter {\n\n files: files,\n\n cache: cache,\n\n cmp: InternalKeyCmp(ucmp),\n\n current: None,\n\n current_ix: 0,\n\n }\n\n}\n\n\n\n/// VersionIter iterates over the entries in an ordered list of table files (specifically, for\n\n/// example, the tables in a level).\n\n///\n\n/// Note that VersionIter returns entries of type Deletion.\n\npub struct VersionIter {\n\n // NOTE: Maybe we need to change this to Rc to support modification of the file set after\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/version.rs", "rank": 78, "score": 194150.14127405753 }, { "content": "pub fn int_to_compressiontype(i: u32) -> Option<CompressionType> {\n\n match i {\n\n 0 => Some(CompressionType::CompressionNone),\n\n 1 => Some(CompressionType::CompressionSnappy),\n\n _ => None,\n\n }\n\n}\n\n\n\n/// Options contains general parameters for a LevelDB instance. Most of the names are\n\n/// self-explanatory; the defaults are defined in the `Default` implementation.\n\n///\n\n/// Note: Compression is not yet implemented.\n\n#[derive(Clone)]\n\npub struct Options {\n\n pub cmp: Rc<Box<dyn Cmp>>,\n\n pub env: Rc<Box<dyn Env>>,\n\n pub log: Option<Shared<Logger>>,\n\n pub create_if_missing: bool,\n\n pub error_if_exists: bool,\n\n pub paranoid_checks: bool,\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/options.rs", "rank": 79, "score": 194081.43278133578 }, { "content": "/// truncate_to_userkey performs an in-place conversion from InternalKey to UserKey format.\n\npub fn truncate_to_userkey(ikey: &mut Vec<u8>) {\n\n let len = ikey.len();\n\n assert!(len > 8);\n\n ikey.truncate(len - 8);\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[test]\n\n fn test_memtable_lookupkey() {\n\n use integer_encoding::VarInt;\n\n\n\n let lk1 = LookupKey::new(\"abcde\".as_bytes(), 123);\n\n let lk2 = LookupKey::new(\"xyabxy\".as_bytes(), 97);\n\n\n\n // Assert correct allocation strategy\n\n assert_eq!(lk1.key.len(), 14);\n\n assert_eq!(lk1.key.capacity(), 14);\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/key_types.rs", "rank": 80, "score": 191615.55166355142 }, { "content": "fn wasm_try_load(spec_driver: &mut SpecDriver, wasm: Vec<u8>) -> Result<(), InterpreterError> {\n\n let module = try_load_module(&wasm[..])?;\n\n let instance = ModuleInstance::new(&module, &ImportsBuilder::default())?;\n\n instance\n\n .run_start(spec_driver.spec_module())\n\n .map_err(|trap| {\n\n InterpreterError::Instantiation(format!(\n\n \"ModuleInstance::run_start error on {:?}\",\n\n trap\n\n ))\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm_compute.rs", "rank": 81, "score": 190928.65364380245 }, { "content": "pub fn remove(path: &Path) -> io::Result<()> {\n\n let path = cstr(path)?;\n\n sgx_tprotected_fs::remove(&path).map_err(Error::from_raw_os_error)\n\n}\n\n\n", "file_path": "teaclave_common/protected_fs_rs/src/sgx_fs_inner.rs", "rank": 82, "score": 190875.14352715516 }, { "content": "#[handle_ecall]\n\nfn handle_run_functional_test(_args: &RunFunctionalTestInput) -> Result<RunFunctionalTestOutput> {\n\n let nfailed = rsgx_unit_tests!(\n\n tests::leveldb_test::test_write_a_lot,\n\n tests::protected_fs_test::read_write_large_file,\n\n tests::kms_test::api_create_key,\n\n tests::kms_test::api_get_deleted_key,\n\n tests::tdfs_test::read_not_exist_file,\n\n tests::tdfs_test::save_and_read,\n\n tests::tdfs_test::check_file_permission,\n\n tests::tdfs_test::task_share_file,\n\n tests::tdfs_test::global_share_file,\n\n tests::tms_test::get_task,\n\n tests::tms_test::update_task_result,\n\n tests::tms_test::update_private_result,\n\n tests::tms_test::update_status,\n\n tests::acs_test::access_control_model,\n\n );\n\n\n\n Ok(RunFunctionalTestOutput::new(nfailed))\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/sgx.rs", "rank": 83, "score": 190730.89838190973 }, { "content": "pub fn get_local_access_path(relative_path: &str) -> PathBuf {\n\n let storage_dir = env::var(\"MESATEE_STORAGE_DIR\").unwrap_or_else(|_| \"/tmp\".into());\n\n Path::new(&storage_dir).join(relative_path)\n\n}\n", "file_path": "mesatee_services/tdfs/internal/client/src/file_util.rs", "rank": 84, "score": 190122.1831911832 }, { "content": "pub fn get_trusted_enclave_attr(service_names: Vec<&str>) -> EnclaveAttr {\n\n let measures = service_names\n\n .iter()\n\n .map(|name| *ENCLAVE_IDENTITIES.get(&(*name).to_string()).unwrap())\n\n .collect();\n\n EnclaveAttr { measures }\n\n}\n", "file_path": "mesatee_core/src/config/mod.rs", "rank": 85, "score": 189063.27837123527 }, { "content": "#[cfg(feature = \"mesalock_sgx\")]\n\npub fn export_auto_key(filename: &CStr) -> SysResult<sgx_key_128bit_t> {\n\n let mut key: sgx_key_128bit_t = Default::default();\n\n unsafe { rsgx_fexport_auto_key(filename, &mut key).map(|_| key) }\n\n}\n\n\n\n///\n\n/// The import_auto_key function is used for importing a Protected FS auto key file created on\n\n/// a different enclave or platform.\n\n///\n\n/// # Description\n\n///\n\n/// import_auto_key is used for importing a Protected FS file. After this call returns successfully,\n\n/// the file can be opened normally with export_auto_key.\n\n///\n\n/// # Parameters\n\n///\n\n/// **filename**\n\n///\n\n/// The name of the file to be imported. This should be the name of a file created with the\n\n/// open_auto_key API, on a different enclave or system.\n", "file_path": "teaclave_common/protected_fs_rs/src/sgx_tprotected_fs.rs", "rank": 86, "score": 188902.95398023044 }, { "content": "pub fn register_trusted_worker_statically() {\n\n for _i in 0..10 {\n\n let worker = Box::new(EchoWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n\n let worker = Box::new(PSIWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n\n let worker = Box::new(EchoFileWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n\n let worker = Box::new(BytesPlusOneWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n\n let worker = Box::new(FileBytesPlusOneWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n\n let worker = Box::new(ConcatWorker::new());\n\n let _ = WorkerInfoQueue::register(worker);\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/global.rs", "rank": 87, "score": 188342.7105755752 }, { "content": "/// Deserializes a hex string to a `SgxMeasurement` (i.e., [0; 32]).\n\npub fn from_hex<'de, D>(deserializer: D) -> std::result::Result<SgxMeasurement, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n use serde::de::Error;\n\n use serde::Deserialize;\n\n String::deserialize(deserializer).and_then(|string| {\n\n let v = decode_hex(&string).map_err(|_| Error::custom(\"ParseError\"))?;\n\n let mut array = [0; SGX_HASH_SIZE];\n\n let bytes = &v[..array.len()]; // panics if not enough data\n\n array.copy_from_slice(bytes);\n\n Ok(array)\n\n })\n\n}\n\n\n", "file_path": "teaclave_utils/src/lib.rs", "rank": 88, "score": 188140.00866856123 }, { "content": "fn gen_string(len: usize) -> String {\n\n let mut rng = rand::thread_rng();\n\n iter::repeat(())\n\n .map(|()| rng.sample(Alphanumeric))\n\n .take(len)\n\n .collect()\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/tests/leveldb_test.rs", "rank": 89, "score": 187932.12909273137 }, { "content": "fn init_enclave(enclave_name: &str, debug_launch: i32) -> Result<SgxEnclave> {\n\n let mut launch_token: sgx_launch_token_t = [0; 1024]; // launch_token is deprecated\n\n let mut launch_token_updated: i32 = 0; // launch_token is deprecated\n\n\n\n let mut misc_attr = sgx_misc_attribute_t {\n\n secs_attr: sgx_attributes_t { flags: 0, xfrm: 0 },\n\n misc_select: 0,\n\n };\n\n\n\n let enclave_file = format!(\"{}{}\", enclave_name, ENCLAVE_FILE_SUFFIX);\n\n\n\n let enclave = SgxEnclave::create(\n\n enclave_file,\n\n debug_launch,\n\n &mut launch_token, // launch_token is deprecated\n\n &mut launch_token_updated, // launch_token is deprecated\n\n &mut misc_attr,\n\n )?;\n\n\n\n Ok(enclave)\n\n}\n", "file_path": "teaclave_binder/src/binder.rs", "rank": 90, "score": 187242.86083503353 }, { "content": "#[inline]\n\nfn get_filter_index(offset: usize, base_lg2: u32) -> u32 {\n\n // divide by 2048\n\n (offset >> base_lg2 as usize) as u32\n\n}\n\n\n\n/// A Filter Block is built like this:\n\n///\n\n/// [filter0, filter1, filter2, ..., offset of filter0, offset of filter1, ..., offset of offsets\n\n/// array, log2 of FILTER_BASE]\n\n///\n\n/// where offsets are 4 bytes, offset of offsets is 4 bytes, and log2 of FILTER_BASE is 1 byte.\n\n/// Two consecutive filter offsets may be the same.\n\npub struct FilterBlockBuilder {\n\n policy: BoxedFilterPolicy,\n\n // filters, concatenated\n\n filters: Vec<u8>,\n\n filter_offsets: Vec<usize>,\n\n\n\n // Reset on every start_block()\n\n key_offsets: Vec<usize>,\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/filter_block.rs", "rank": 91, "score": 186997.813805616 }, { "content": "/// This shared test takes an iterator with exactly four elements and tests that it fulfills the\n\n/// generic iterator properties. Every iterator defined in this code base should pass this test.\n\npub fn test_iterator_properties<It: LdbIterator>(mut it: It) {\n\n assert!(!it.valid());\n\n assert!(it.advance());\n\n assert!(it.valid());\n\n let first = current_key_val(&it);\n\n assert!(it.advance());\n\n let second = current_key_val(&it);\n\n assert!(it.advance());\n\n let third = current_key_val(&it);\n\n // fourth (last) element\n\n assert!(it.advance());\n\n assert!(it.valid());\n\n let fourth = current_key_val(&it);\n\n // past end is invalid\n\n assert!(!it.advance());\n\n assert!(!it.valid());\n\n\n\n it.reset();\n\n it.seek(&fourth.as_ref().unwrap().0);\n\n assert!(it.valid());\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/test_util.rs", "rank": 92, "score": 186923.13475594867 }, { "content": "pub fn update_task_result() {\n\n trace!(\"Test TMS: update_task_result.\");\n\n let mut client = setup_tms_internal_client();\n\n\n\n let resp = client\n\n .request_update_task(\"fake\", Some(\"task_result\"), &[], None)\n\n .unwrap();\n\n assert!(resp.success);\n\n\n\n let resp = client.request_get_task(\"fake\").unwrap();\n\n let task_info = resp.task_info;\n\n assert_eq!(\n\n \"task_result\",\n\n task_info.task_result_file_id.unwrap().as_str()\n\n );\n\n\n\n // task not exists\n\n let resp = client\n\n .request_update_task(\"NULL\", Some(\"task_result\"), &[], None)\n\n .unwrap();\n\n assert!(!resp.success);\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/tests/tms_test.rs", "rank": 93, "score": 186162.58096066746 }, { "content": "pub fn update_private_result() {\n\n trace!(\"Test TMS: update_client_private_result.\");\n\n let mut client = setup_tms_internal_client();\n\n\n\n let task_file = TaskFile {\n\n user_id: \"fake\".to_owned(),\n\n file_id: \"client_private_result\".to_owned(),\n\n };\n\n let update_input = [&task_file];\n\n let resp = client\n\n .request_update_task(\"fake\", None, &update_input, None)\n\n .unwrap();\n\n assert!(resp.success);\n\n\n\n let resp = client.request_get_task(\"fake\").unwrap();\n\n let task_info = resp.task_info;\n\n assert_eq!(\n\n \"client_private_result\",\n\n task_info.output_files[0].file_id.as_str()\n\n );\n\n}\n\n\n", "file_path": "tests/functional_test/sgx_trusted_lib/src/tests/tms_test.rs", "rank": 94, "score": 186162.58096066746 }, { "content": "pub fn obinary_search(\n\n b: &[[u8; SGX_HASH_SIZE]],\n\n target: &[u8; SGX_HASH_SIZE],\n\n v2: &mut Vec<u8>,\n\n) -> isize {\n\n let mut lo: isize = 0;\n\n let mut hi: isize = b.len() as isize - 1;\n\n let mut ret: isize = -1;\n\n\n\n while lo <= hi {\n\n let mid = lo + (hi - lo) / 2;\n\n let hit = eq(&b[mid as usize], target);\n\n ret = omov(hit, mid, ret);\n\n v2[mid as usize] = omov(hit, 1, v2[mid as usize] as isize) as u8;\n\n let be = le(&b[mid as usize], target);\n\n lo = omov(be, mid + 1, lo);\n\n hi = omov(be, hi, mid - 1);\n\n }\n\n ret\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/psi/basic.rs", "rank": 95, "score": 185875.68308671322 }, { "content": "pub fn load_module(\n\n wasm: &[u8],\n\n name: &Option<String>,\n\n spec_driver: &mut SpecDriver,\n\n) -> Result<ModuleRef, Error> {\n\n let module = try_load_module(wasm)?;\n\n let instance = ModuleInstance::new(&module, spec_driver)\n\n .map_err(|e| Error::Load(e.to_string()))?\n\n .run_start(spec_driver.spec_module())\n\n .map_err(|trap| Error::Start(trap))?;\n\n\n\n let module_name = name.clone();\n\n spec_driver.add_module(module_name, instance.clone());\n\n\n\n Ok(instance)\n\n}\n\n*/\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/wasm/sgxwasm.rs", "rank": 96, "score": 185875.68308671322 }, { "content": "pub fn oget_intersection(\n\n a: &[[u8; SGX_HASH_SIZE]],\n\n b: &[[u8; SGX_HASH_SIZE]],\n\n v1: &mut Vec<u8>,\n\n v2: &mut Vec<u8>,\n\n) {\n\n let n = a.len();\n\n for i in 0..n {\n\n let ret = obinary_search(b, &a[i], v2);\n\n let miss = oequal(usize::max_value(), ret as usize);\n\n v1[i] = omov(miss as isize, 0, 1) as u8;\n\n }\n\n}\n\n\n", "file_path": "mesatee_services/fns/sgx_trusted_lib/src/trusted_worker/psi/basic.rs", "rank": 97, "score": 185875.68308671322 }, { "content": "/// A memtable key is a bytestring containing (keylen, key, tag, vallen, val). This function\n\n/// builds such a key. It's called key because the underlying Map implementation will only be\n\n/// concerned with keys; the value field is not used (instead, the value is encoded in the key,\n\n/// and for lookups we just search for the next bigger entry).\n\n/// keylen is the length of key + 8 (to account for the tag)\n\npub fn build_memtable_key(key: &[u8], value: &[u8], t: ValueType, seq: SequenceNumber) -> Vec<u8> {\n\n // We are using the original LevelDB approach here -- encoding key and value into the\n\n // key that is used for insertion into the SkipMap.\n\n // The format is: [key_size: varint32, key_data: [u8], flags: u64, value_size: varint32,\n\n // value_data: [u8]]\n\n\n\n let keysize = key.len() + U64_SPACE;\n\n let valsize = value.len();\n\n let mut buf = Vec::new();\n\n buf.resize(\n\n keysize + valsize + keysize.required_space() + valsize.required_space(),\n\n 0,\n\n );\n\n\n\n {\n\n let mut writer = buf.as_mut_slice();\n\n writer.write_varint(keysize).expect(\"write to slice failed\");\n\n writer.write(key).expect(\"write to slice failed\");\n\n writer\n\n .write_fixedint((t as u64) | (seq << 8))\n\n .expect(\"write to slice failed\");\n\n writer.write_varint(valsize).expect(\"write to slice failed\");\n\n writer.write(value).expect(\"write to slice failed\");\n\n assert_eq!(writer.len(), 0);\n\n }\n\n buf\n\n}\n\n\n", "file_path": "teaclave_common/rusty_leveldb_sgx/src/key_types.rs", "rank": 98, "score": 183844.9101777649 }, { "content": "fn get_result(info: &MesateeEnclaveInfo, user_id: &str, user_token: &str, task_id: &str) {\n\n let mesatee = Mesatee::new(info, user_id, user_token, *TMS_ADDR, *TDFS_ADDR).unwrap();\n\n\n\n let task = mesatee.get_task(task_id).unwrap();\n\n let task_info = task.task_info.unwrap();\n\n assert_eq!(task_info.status, TaskStatus::Finished);\n\n println!(\"[+] Task status is Finished\");\n\n\n\n let result_files = mesatee.get_task_results(&task_id).unwrap();\n\n let content = mesatee.get_file(&result_files[0]).unwrap();\n\n let result = String::from_utf8(content).unwrap();\n\n println!(\"{} get result: \\n{}\", user_id, result);\n\n}\n\n\n", "file_path": "examples/private_join_and_compute/src/main.rs", "rank": 99, "score": 183234.68616989264 } ]
Rust
src/main.rs
mentaljam/qgsrepo
d19c60ac2e755d0d4bdce8af37908d5d54678301
extern crate zip; extern crate ini; extern crate xml; mod config; mod qgsmeta; use std::path::PathBuf; use std::fs; use zip::ZipArchive; use ini::Ini; use std::io::Read; use xml::writer; use qgsmeta::{ MetaEntries, metakey, xmlkey }; #[derive(Debug)] enum ExitCodes { Success = 0, NoRootDir, NoOutDir, FileExists, NoIconsDir } macro_rules! exit_with_code { ($code:path) => (std::process::exit($code as i32)) } macro_rules! write_url { ($writer:ident, $cfg:ident, $zip_name:ident) => { let url_tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&MetaEntries::DownloadUrl)); let mut url = $cfg.repourl.clone(); url.push('/'); url.push_str($zip_name.to_str().unwrap()); let url_text = writer::XmlEvent::characters(url.as_str()); $writer.write(url_tag).unwrap(); $writer.write(url_text).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_file { ($writer:ident, $file_name:ident) => { let file_tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&MetaEntries::FileName)); let file_name = writer::XmlEvent::characters($file_name.as_str()); $writer.write(file_tag).unwrap(); $writer.write(file_name).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_icon { ($writer:ident, $cfg:ident, $icon_tag_name:ident, $icon_name:ident) => { let icon_tag = writer::XmlEvent::start_element($icon_tag_name); let mut icon_path = $cfg.iconsdir.clone(); icon_path.push('/'); icon_path.push_str($icon_name.to_str().unwrap()); let icon_text = writer::XmlEvent::characters(icon_path.as_str()); $writer.write(icon_tag).unwrap(); $writer.write(icon_text).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_entries { ($writer:ident, $section:ident, $entries:ident, $func:path) => { for entry in &$entries { match $section.get(metakey(&entry)) { Some(value) => if !value.is_empty() { let tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&entry)); $writer.write(tag).unwrap(); $writer.write($func(value)).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); }, None => () } } } } fn main() { let mut cfg = config::Config::new(); cfg.parse_args(); let root = PathBuf::from(&cfg.reporoot); if !root.is_dir() { println!("Error: the root directory does not exist: \"{:?}\"", root); exit_with_code!(ExitCodes::NoRootDir); } let outpath = { if cfg.outname == "plugins.xml" { root.join(&cfg.outname) } else { let file = PathBuf::from(&cfg.outname); { let dir = file.parent().unwrap(); if !dir.is_dir() { println!("Error: the output file directory does not exist: \"{:?}\"", dir); exit_with_code!(ExitCodes::NoOutDir); } } file } }; if !cfg.force && outpath.is_file() { println!("Error: the output file already exists. Run with the -f option to overwrite: {:?}", outpath); exit_with_code!(ExitCodes::FileExists); } let iconsdir = root.join(&cfg.iconsdir); if cfg.withicons && !iconsdir.is_dir() { println!("Error: the icon directory does not exist: {:?}", iconsdir); exit_with_code!(ExitCodes::NoIconsDir); } let mut outfile = fs::File::create(outpath).unwrap(); let mut xmlwriter = writer::EmitterConfig::new().perform_indent(true).create_writer(&mut outfile); { let plugins = writer::XmlEvent::start_element("plugins"); xmlwriter.write(plugins).unwrap(); } let attr_entries = attr_entries!(); let text_entries = text_entries!(); let cdata_entries = cdata_entries!(); let entries = fs::read_dir(root).unwrap(); let mut icons = Vec::new(); for entry in entries { let path = entry.unwrap().path(); if !path.is_file() || path.extension().unwrap() != "zip" { continue } let zipfile = fs::File::open(&path).unwrap(); let zipname = path.file_name().unwrap(); println!("Processing: {:?}", zipname); let mut zipreader = ZipArchive::new(&zipfile).unwrap(); let plugin_dir = match zipreader.by_index(0) { Result::Ok(zipentry) => { let entry_path = PathBuf::from(zipentry.name()); let mut path_comps = entry_path.iter(); path_comps.next().unwrap().to_string_lossy().into_owned() }, Result::Err(err) => { println!("Warning: could not read zip, skipping: {}", err); continue }, }; let metadata_text = { let metadata_path = format!("{}/metadata.txt", plugin_dir); match zipreader.by_name(metadata_path.as_str()) { Result::Ok(mut metadata) => { let mut md = String::new(); metadata.read_to_string(&mut md).unwrap(); md.push_str("\ndummy=dummy"); md }, Result::Err(err) => { println!("Warning: could not read the \"metadata.txt\", skipping: {}", err); continue } } }; let metadata = match Ini::load_from_str(metadata_text.as_str()) { Result::Ok(metadata) => { metadata }, Result::Err(err) => { println!("Warning: could not parse plugin metadata, skipping: {:?}", err); continue } }; let general = match metadata.section(Some("general".to_owned())) { Some(section) => section, None => { println!("Warning: metadata file does not contain the \"general\" section, skipping"); continue } }; if cfg.strict { let mut ok = true; for entry in required_entries!() { let key = metakey(&entry); if !general.contains_key(key) { println!("Warning: strict check - metadata file does not contain the \"{}\" entry", key); ok = false; break } } if !ok { println!("Warning: strict check - skipping plugin due to bad metadata"); continue } } { let mut pyqgis_plugin = writer::XmlEvent::start_element("pyqgis_plugin"); let mut ok = true; for attr in &attr_entries { let key = metakey(&attr); match general.get(key) { Some(value) => pyqgis_plugin = pyqgis_plugin.attr(xmlkey(&attr), value), None => { println!("Warning: metadata file does not contain the required \"{}\" entry", key); ok = false; } } } if ok { xmlwriter.write(pyqgis_plugin).unwrap(); } else { println!("Warning: skipping plugin due to bad metadata"); continue } } write_url!(xmlwriter, cfg, zipname); write_file!(xmlwriter, plugin_dir); write_entries!(xmlwriter, general, text_entries, writer::XmlEvent::characters); write_entries!(xmlwriter, general, cdata_entries, writer::XmlEvent::cdata); if cfg.withicons { let icon_tag_name = metakey(&MetaEntries::Icon); let zipicon = match general.get(icon_tag_name) { Some(zipicon) => zipicon, None => { xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); continue } }; let zipicon_path = PathBuf::from(format!("{}/{}", plugin_dir, zipicon)); let ext = zipicon_path.extension().unwrap(); let icon_name = { let mut icon_name = PathBuf::from(&zipname); icon_name.set_extension(&ext); icon_name.to_owned() }; icons.push(icon_name.as_os_str().to_owned()); write_icon!(xmlwriter, cfg, icon_tag_name, icon_name); let icon_path = iconsdir.join(&icon_name); if icon_path.exists() { xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); continue } match zipreader.by_name(zipicon_path.to_str().unwrap()) { Result::Ok(icon) => { let mut icon_reader = icon; let mut icon_writer = fs::File::create(&icon_path).unwrap(); match std::io::copy(&mut icon_reader, &mut icon_writer) { Result::Err(err) => println!("Warning: could not extract plugin icon: {:?} - {}", zipicon_path, err), _ => () } }, Result::Err(err) => println!("Warning: could not read plugin icon: {:?} - {}", zipicon_path, err) } } xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); } xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); if cfg.withicons { println!("Removing obsolete icons"); let allicons = fs::read_dir(iconsdir).unwrap(); for entry in allicons { let entry_reader = entry.unwrap(); let entryname = &entry_reader.file_name(); let mut remove = true; for icon in &icons { if entryname == icon { remove = false; break } } if remove { match fs::remove_file(entry_reader.path()) { Result::Ok(_) => println!("{:?}", entryname), Result::Err(err) => println!("Warning: could not remove obsolete icon: {}", err), } } } } exit_with_code!(ExitCodes::Success); }
extern crate zip; extern crate ini; extern crate xml; mod config; mod qgsmeta; use std::path::PathBuf; use std::fs; use zip::ZipArchive; use ini::Ini; use std::io::Read; use xml::writer; use qgsmeta::{ MetaEntries, metakey, xmlkey }; #[derive(Debug)] enum ExitCodes { Success = 0, NoRootDir, NoOutDir, FileExists, NoIconsDir } macro_rules! exit_with_code { ($code:path) => (std::process::exit($code as i32)) } macro_rules! write_url { ($writer:ident, $cfg:ident, $zip_name:ident) => { let url_tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&MetaEntries::DownloadUrl)); let mut url = $cfg.repourl.clone(); url.push('/'); url.push_str($zip_name.to_str().unwrap()); let url_text = writer::XmlEvent::characters(url.as_str()); $writer.write(url_tag).unwrap(); $writer.write(url_text).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_file { ($writer:ident, $file_name:ident) => { let file_tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&MetaEntries::FileName)); let file_name = writer::XmlEvent::characters($file_name.as_str()); $writer.write(file_tag).unwrap(); $writer.write(file_name).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_icon { ($writer:ident, $cfg:ident, $icon_tag_name:ident, $icon_name:ident) => { let icon_tag = writer::XmlEvent::start_element($icon_tag_name); let mut icon_path = $cfg.iconsdir.clone(); icon_path.push('/'); icon_path.push_str($icon_name.to_str().unwrap()); let icon_text = writer::XmlEvent::characters(icon_path.as_str()); $writer.write(icon_tag).unwrap(); $writer.write(icon_text).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); } } macro_rules! write_entries { ($writer:ident, $section:ident, $entries:ident, $func:path) => { for entry in &$entries { match $section.get(metakey(&entry)) { Some(value) => if !value.is_empty() { let tag = writer::XmlEvent::start_element(qgsmeta::xmlkey(&entry)); $writer.write(tag).unwrap(); $writer.write($func(value)).unwrap(); $writer.write(writer::XmlEvent::end_element()).unwrap(); }, None => () } } } } fn main() { let mut cfg = config::Config::new(); cfg.parse_args(); let root = PathBuf::from(&cfg.reporoot); if !root.is_dir() { println!("Error: the root directory does not exist: \"{:?}\"", root); exit_with_code!(ExitCodes::NoRootDir); } let outpath = { if cfg.outname == "plugins.xml" { root.join(&cfg.outname) } else { let file = PathBuf::from(&cfg.outname); { let dir = file.parent().unwrap(); if !dir.is_dir() { println!("Error: the output file directory does not exist: \"{:?}\"", dir); exit_with_code!(ExitCodes::NoOutDir); } } file } }; if !cfg.force && outpath.is_file() { println!("Error: the output file already exists. Run with the -f option to overwrite: {:?}", outpath); exit_with_code!(ExitCodes::FileExists); } let iconsdir = root.join(&cfg.iconsdir); if cfg.withicons && !iconsdir.is_dir() { println!("Error: the icon directory does not exist: {:?}", iconsdir); exit_with_code!(ExitCodes::NoIconsDir); } let mut outfile = fs::File::create(outpath).unwrap(); let mut xmlwriter = writer::EmitterConfig::new().perform_indent(true).create_writer(&mut outfile); { let plugins = writer::XmlEvent::start_element("plugins"); xmlwriter.write(plugins).unwrap(); } let attr_entries = attr_entries!(); let text_entries = text_entries!(); let cdata_entries = cdata_entries!(); let entries = fs::read_dir(root).unwrap(); let mut icons = Vec::new(); for entry in entries { let path = entry.unwrap().path(); if !path.is_file() || path.extension().unwrap() != "zip" { continue } let zipfile = fs::File::open(&path).unwrap(); let zipname = path.file_name().unwrap(); println!("Processing: {:?}", zipname); let mut zipreader = ZipArchive::new(&zipfile).unwrap(); let plugin_dir = match zipreader.by_index(0) { Result::Ok(zipentry) => { let entry_path = PathBuf::from(zipentry.name()); let mut path_comps = entry_path.iter(); path_comps.next().unwrap().to_string_lossy().into_owned() }, Result::Err(err) => { println!("Warning: could not read zip, skipping: {}", err); continue }, }; let metadata_text = { let metadata_path = format!("{}/metadata.txt", plugin_dir); match zipreader.by_name(metadata_path.as_str()) { Result::Ok(mut metadata) => { let mut md = String::new(); metadata.read_to_string(&mut md).unwrap();
md.push_str("\ndummy=dummy"); md }, Result::Err(err) => { println!("Warning: could not read the \"metadata.txt\", skipping: {}", err); continue } } }; let metadata = match Ini::load_from_str(metadata_text.as_str()) { Result::Ok(metadata) => { metadata }, Result::Err(err) => { println!("Warning: could not parse plugin metadata, skipping: {:?}", err); continue } }; let general = match metadata.section(Some("general".to_owned())) { Some(section) => section, None => { println!("Warning: metadata file does not contain the \"general\" section, skipping"); continue } }; if cfg.strict { let mut ok = true; for entry in required_entries!() { let key = metakey(&entry); if !general.contains_key(key) { println!("Warning: strict check - metadata file does not contain the \"{}\" entry", key); ok = false; break } } if !ok { println!("Warning: strict check - skipping plugin due to bad metadata"); continue } } { let mut pyqgis_plugin = writer::XmlEvent::start_element("pyqgis_plugin"); let mut ok = true; for attr in &attr_entries { let key = metakey(&attr); match general.get(key) { Some(value) => pyqgis_plugin = pyqgis_plugin.attr(xmlkey(&attr), value), None => { println!("Warning: metadata file does not contain the required \"{}\" entry", key); ok = false; } } } if ok { xmlwriter.write(pyqgis_plugin).unwrap(); } else { println!("Warning: skipping plugin due to bad metadata"); continue } } write_url!(xmlwriter, cfg, zipname); write_file!(xmlwriter, plugin_dir); write_entries!(xmlwriter, general, text_entries, writer::XmlEvent::characters); write_entries!(xmlwriter, general, cdata_entries, writer::XmlEvent::cdata); if cfg.withicons { let icon_tag_name = metakey(&MetaEntries::Icon); let zipicon = match general.get(icon_tag_name) { Some(zipicon) => zipicon, None => { xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); continue } }; let zipicon_path = PathBuf::from(format!("{}/{}", plugin_dir, zipicon)); let ext = zipicon_path.extension().unwrap(); let icon_name = { let mut icon_name = PathBuf::from(&zipname); icon_name.set_extension(&ext); icon_name.to_owned() }; icons.push(icon_name.as_os_str().to_owned()); write_icon!(xmlwriter, cfg, icon_tag_name, icon_name); let icon_path = iconsdir.join(&icon_name); if icon_path.exists() { xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); continue } match zipreader.by_name(zipicon_path.to_str().unwrap()) { Result::Ok(icon) => { let mut icon_reader = icon; let mut icon_writer = fs::File::create(&icon_path).unwrap(); match std::io::copy(&mut icon_reader, &mut icon_writer) { Result::Err(err) => println!("Warning: could not extract plugin icon: {:?} - {}", zipicon_path, err), _ => () } }, Result::Err(err) => println!("Warning: could not read plugin icon: {:?} - {}", zipicon_path, err) } } xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); } xmlwriter.write(writer::XmlEvent::end_element()).unwrap(); if cfg.withicons { println!("Removing obsolete icons"); let allicons = fs::read_dir(iconsdir).unwrap(); for entry in allicons { let entry_reader = entry.unwrap(); let entryname = &entry_reader.file_name(); let mut remove = true; for icon in &icons { if entryname == icon { remove = false; break } } if remove { match fs::remove_file(entry_reader.path()) { Result::Ok(_) => println!("{:?}", entryname), Result::Err(err) => println!("Warning: could not remove obsolete icon: {}", err), } } } } exit_with_code!(ExitCodes::Success); }
function_block-function_prefix_line
[ { "content": "pub fn xmlkey(entry: &MetaEntries) -> &'static str {\n\n match entry {\n\n &MetaEntries::QgisMinimumVersion => \"qgis_minimum_version\",\n\n &MetaEntries::QgisMaximumVersion => \"qgis_maximum_version\",\n\n &MetaEntries::Author => \"author_name\",\n\n &MetaEntries::DownloadUrl => \"download_url\",\n\n &MetaEntries::FileName => \"file_name\",\n\n _ => metakey(entry)\n\n }\n\n}\n\n\n\nmacro_rules! required_entries {\n\n () => (\n\n vec![\n\n MetaEntries::Name,\n\n MetaEntries::QgisMinimumVersion,\n\n MetaEntries::Description,\n\n MetaEntries::About,\n\n MetaEntries::Version,\n\n MetaEntries::Author,\n", "file_path": "src/qgsmeta.rs", "rank": 0, "score": 58297.84082670527 }, { "content": "pub fn metakey(entry: &MetaEntries) -> &'static str {\n\n match entry {\n\n &MetaEntries::Name => \"name\",\n\n &MetaEntries::Version => \"version\",\n\n &MetaEntries::QgisMinimumVersion => \"qgisMinimumVersion\",\n\n &MetaEntries::QgisMaximumVersion => \"qgisMaximumVersion\",\n\n &MetaEntries::Description => \"description\",\n\n &MetaEntries::About => \"about\",\n\n &MetaEntries::Author => \"author\",\n\n &MetaEntries::Email => \"email\",\n\n &MetaEntries::Changelog => \"changelog\",\n\n &MetaEntries::Experimental => \"experimental\",\n\n &MetaEntries::Deprecated => \"deprecated\",\n\n &MetaEntries::Tags => \"tags\",\n\n &MetaEntries::Homepage => \"homepage\",\n\n &MetaEntries::Repository => \"repository\",\n\n &MetaEntries::Tracker => \"tracker\",\n\n &MetaEntries::Icon => \"icon\",\n\n &MetaEntries::Category => \"category\",\n\n &_ => \"\"\n\n }\n\n}\n\n\n", "file_path": "src/qgsmeta.rs", "rank": 1, "score": 58297.84082670527 }, { "content": "#[cfg(unix)]\n\nfn main() { }\n", "file_path": "build.rs", "rank": 3, "score": 46171.1180883992 }, { "content": "#[cfg(windows)]\n\nfn main() {\n\n if var(\"PROFILE\").unwrap() == \"release\" {\n\n // compile .rc file\n\n let mut res = winres::WindowsResource::new();\n\n res.set_language(0x409);\n\n res.compile().unwrap();\n\n\n\n // prepare for building msi package\n\n let cargo_manifest_dir = var(\"CARGO_MANIFEST_DIR\").unwrap();\n\n // wix source dir\n\n let wix_src_dir = PathBuf::from(&cargo_manifest_dir).join(\"wix\");\n\n // wix build dir\n\n let wix_build_path = PathBuf::from(&var(\"OUT_DIR\").unwrap()).join(\"wix\");\n\n // create wix build dir if does't exist\n\n if !wix_build_path.is_dir() {\n\n fs::create_dir(&wix_build_path).unwrap();\n\n }\n\n\n\n // copy wix files\n\n let mut wxs_files = Vec::new();\n", "file_path": "build.rs", "rank": 4, "score": 46171.1180883992 }, { "content": " \"a directory containing plugin archives\")\n\n .required();\n\n ap.refer(&mut self.repourl)\n\n .add_argument(&\"url\", Store,\n\n \"a repository url for the \\\"download_url\\\" entry\")\n\n .required();\n\n ap.refer(&mut self.outname)\n\n .add_option(&[\"-o\", \"--output\"], Store,\n\n \"an output file name, default is \\\"plugins.xml\\\" in a repository root\");\n\n ap.refer(&mut self.withicons)\n\n .add_option(&[\"--no-icons\"], StoreFalse,\n\n \"do not extract icons\");\n\n ap.refer(&mut self.iconsdir)\n\n .add_option(&[\"--icons-dir\"], Store,\n\n \"a root subdirectory for icons, default is \\\"icons\\\"\");\n\n ap.refer(&mut self.strict)\n\n .add_option(&[\"-s\", \"--strict\"], StoreTrue,\n\n \"strict metadata check\");\n\n ap.refer(&mut self.force)\n\n .add_option(&[\"-f\", \"--force\"], StoreTrue,\n\n \"rewrite an output file if exists\");\n\n ap.add_option(&[\"-v\", \"--version\"],\n\n Print(env!(\"CARGO_PKG_VERSION\").to_string()), \"show version and exit\");\n\n ap.parse_args_or_exit();\n\n }\n\n}\n", "file_path": "src/config.rs", "rank": 6, "score": 17025.499471008385 }, { "content": "}\n\n\n\nimpl Config {\n\n pub fn new() -> Config {\n\n Config {\n\n force: false,\n\n strict: false,\n\n withicons: true,\n\n reporoot: String::new(),\n\n repourl: String::new(),\n\n outname: String::from(\"plugins.xml\"),\n\n iconsdir: String::from(\"icons\")\n\n }\n\n }\n\n\n\n pub fn parse_args(&mut self) {\n\n let mut ap = ArgumentParser::new();\n\n ap.set_description(\"Generates the QGIS repository index file.\");\n\n ap.refer(&mut self.reporoot)\n\n .add_argument(&\"root\", Store,\n", "file_path": "src/config.rs", "rank": 7, "score": 17018.481274736485 }, { "content": "extern crate argparse;\n\n\n\nuse self::argparse::{\n\n ArgumentParser,\n\n Store,\n\n StoreTrue,\n\n StoreFalse,\n\n Print\n\n};\n\n\n\n\n\n#[derive(Debug)]\n\npub struct Config {\n\n pub force: bool,\n\n pub strict: bool,\n\n pub withicons: bool,\n\n pub reporoot: String,\n\n pub repourl: String,\n\n pub outname: String,\n\n pub iconsdir: String\n", "file_path": "src/config.rs", "rank": 8, "score": 17015.86387612018 }, { "content": "#![macro_use]\n\n\n\n#[derive(Debug)]\n\n#[allow(dead_code)]\n\npub enum MetaEntries{\n\n Name,\n\n QgisMinimumVersion,\n\n QgisMaximumVersion,\n\n Description,\n\n About,\n\n Version,\n\n Author,\n\n Email,\n\n Changelog,\n\n Experimental,\n\n Deprecated,\n\n Tags,\n\n Homepage,\n\n Repository,\n\n Tracker,\n\n Icon,\n\n Category,\n\n DownloadUrl,\n\n FileName\n\n}\n\n\n", "file_path": "src/qgsmeta.rs", "rank": 9, "score": 16664.990119074046 }, { "content": " MetaEntries::Version,\n\n MetaEntries::Email,\n\n MetaEntries::Experimental,\n\n MetaEntries::Deprecated,\n\n MetaEntries::Category\n\n ]\n\n )\n\n}\n\n\n\nmacro_rules! cdata_entries {\n\n () => (\n\n vec![\n\n MetaEntries::Description,\n\n MetaEntries::About,\n\n MetaEntries::Homepage,\n\n MetaEntries::Author,\n\n MetaEntries::Repository,\n\n MetaEntries::Tracker,\n\n MetaEntries::Tags\n\n ]\n\n )\n\n}\n", "file_path": "src/qgsmeta.rs", "rank": 10, "score": 16660.671031212154 }, { "content": " MetaEntries::Email,\n\n MetaEntries::Repository\n\n ]\n\n )\n\n}\n\n\n\nmacro_rules! attr_entries {\n\n () => (\n\n vec![\n\n MetaEntries::Name,\n\n MetaEntries::Version\n\n ]\n\n )\n\n}\n\n\n\nmacro_rules! text_entries {\n\n () => (\n\n vec![\n\n MetaEntries::QgisMinimumVersion,\n\n MetaEntries::QgisMaximumVersion,\n", "file_path": "src/qgsmeta.rs", "rank": 11, "score": 16659.273401725666 }, { "content": "# QgsRepo\n\nA simple QGIS repository generator written in Rust.\n\n\n\n[![License](https://img.shields.io/badge/license-zlib-blue.svg)](https://github.com/mentaljam/qgsrepo/blob/master/LICENSE.txt)\n\n[![Release](https://img.shields.io/github/release/mentaljam/qgsrepo.svg)](https://github.com/mentaljam/qgsrepo/releases/latest)\n\n[![Snap Status](https://build.snapcraft.io/badge/mentaljam/qgsrepo.svg)](https://build.snapcraft.io/user/mentaljam/qgsrepo)\n\n\n\nA single binary that allows to generate a QGIS repository index XML file for a plugins directory by extracting metadata from plugins archives.\n\n\n\n## Usage\n\n qgsrepo [OPTIONS] ROOT URL\n\n#### Positional arguments:\n\n root a directory containing plugin archives\n\n url a repository url for the \"download_url\" entry\n\n#### Optional arguments:\n\n -h,--help show this help message and exit\n\n -o,--output OUTPUT an output file name, default is \"plugins.xml\" in a\n\n repository root\n\n --no-icons do not extract icons\n\n --icons-dir ICONS_DIR a root subdirectory for icons, default is \"icons\"\n\n -s,--strict strict metadata check\n\n -f,--force rewrite an output file if exists\n\n -v,--version show version and exit\n\n \n\n## Building\n\n1. [Install](https://www.rust-lang.org/en-US/install.html) the Rust compiler and Cargo\n\n2. Clone sources: `git clone [email protected]:mentaljam/qgsrepo.git`\n\n3. Enter the source directory: `cd qgsrepo`\n\n4. Run cargo build command: `cargo build --release`\n\n\n\n## Packaging\n\n\n\n### Windows installer\n\nAfter build run `target\\release\\build_msi.bat` ([WiX toolset](http://wixtoolset.org/) is required).\n\n\n\nThe latest windows installer package is available in the [releases](https://github.com/mentaljam/qgsrepo/releases/latest) section.\n\n\n\n### Linux\n\nOn Linux systems QgsRepo can be installed with a snap package from The Ubuntu Store: `sudo snap install qgsrepo`.\n", "file_path": "README.md", "rank": 25, "score": 9261.32722055405 }, { "content": "#[cfg(windows)]\n\nextern crate winres;\n\n#[cfg(windows)]\n\nextern crate strfmt;\n\n\n\n#[cfg(windows)]\n\nuse std::env::var;\n\n#[cfg(windows)]\n\nuse std::path::PathBuf;\n\n#[cfg(windows)]\n\nuse std::fs;\n\n#[cfg(windows)]\n\nuse std::io::{\n\n Read,\n\n Write\n\n};\n\n#[cfg(windows)]\n\nuse strfmt::strfmt;\n\n#[cfg(windows)]\n\nuse std::collections::HashMap;\n", "file_path": "build.rs", "rank": 26, "score": 11.522716853425797 }, { "content": " let mut cultures = Vec::new();\n\n {\n\n let files = fs::read_dir(&wix_src_dir).unwrap();\n\n for file in files {\n\n let path = file.unwrap().path();\n\n if !path.is_file() {\n\n continue\n\n }\n\n let ext = path.extension().unwrap().to_str().unwrap();\n\n let stem = path.file_stem().unwrap().to_str().unwrap().to_string();\n\n let copy = match ext {\n\n \"wxs\" => {\n\n wxs_files.push(stem);\n\n true\n\n },\n\n \"wxl\" => {\n\n cultures.push(stem);\n\n true\n\n },\n\n \"wxi\" => true,\n", "file_path": "build.rs", "rank": 27, "score": 9.703119521363215 }, { "content": " \"rtf\" => true,\n\n _ => false\n\n };\n\n if copy {\n\n let name = path.file_name().unwrap();\n\n fs::copy(&path, wix_build_path.join(name)).unwrap();\n\n }\n\n }\n\n }\n\n\n\n // write build_msi.bat\n\n {\n\n let version = var(\"CARGO_PKG_VERSION\").unwrap();\n\n let build_bat_in_path = wix_src_dir.join(\"build_msi.bat.in\");\n\n let mut build_bat_in_reader = fs::File::open(build_bat_in_path).unwrap();\n\n let mut build_bat_data = String::new();\n\n build_bat_in_reader.read_to_string(&mut build_bat_data).unwrap();\n\n let build_dir = PathBuf::from(&cargo_manifest_dir).join(\"target\\\\release\");\n\n let build_bat_path = build_dir.join(\"build_msi.bat\");\n\n let mut vars = HashMap::new();\n", "file_path": "build.rs", "rank": 28, "score": 7.106933803292764 }, { "content": " vars.insert(\"arch\".to_string(), arch!().to_string());\n\n vars.insert(\"win_arch\".to_string(), arch!(win).to_string());\n\n vars.insert(\"out_dir\".to_string(), wix_build_path.to_str().unwrap().to_string());\n\n vars.insert(\"target_dir\".to_string(), build_dir.to_str().unwrap().to_string());\n\n vars.insert(\"version\".to_string(), version);\n\n vars.insert(\"wxs_files\".to_string(), wxs_files.join(\", \"));\n\n vars.insert(\"cultures\".to_string(), cultures.join(\", \"));\n\n build_bat_data = strfmt(&build_bat_data, &vars).unwrap();\n\n let mut build_bat_writer = fs::File::create(build_bat_path).unwrap();\n\n build_bat_writer.write_all(&mut build_bat_data.as_bytes()).unwrap();\n\n }\n\n }\n\n}\n\n\n", "file_path": "build.rs", "rank": 29, "score": 5.869108773153673 }, { "content": "\n\n#[cfg(all(windows, target_pointer_width = \"32\"))]\n\nmacro_rules! arch {\n\n () => (\"x86\");\n\n (win) => (\"win32\");\n\n}\n\n\n\n#[cfg(all(windows, target_pointer_width = \"64\"))]\n\nmacro_rules! arch {\n\n () => (\"x64\");\n\n (win) => (\"win64\");\n\n}\n\n\n\n\n\n#[cfg(windows)]\n", "file_path": "build.rs", "rank": 30, "score": 2.262724827138837 } ]
Rust
src/net/raw/arp.rs
Zrus/arrow-client
61ead64b10cf8bba451d6798abacd58ce89e3233
use std::io; use std::mem; use std::io::Write; use std::net::Ipv4Addr; use crate::utils; use crate::net::raw::ether::packet::{EtherPacketBody, PacketParseError, Result}; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[derive(Debug, Clone)] pub struct ArpPacket { pub htype: u16, pub ptype: u16, pub hlen: u8, pub plen: u8, pub oper: ArpOperation, pub sha: Box<[u8]>, pub spa: Box<[u8]>, pub tha: Box<[u8]>, pub tpa: Box<[u8]>, } #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ArpOperation { REQUEST, REPLY, UNKNOWN(u16), } impl ArpOperation { pub fn code(self) -> u16 { match self { Self::REQUEST => 1, Self::REPLY => 2, Self::UNKNOWN(op) => op, } } } impl From<u16> for ArpOperation { fn from(v: u16) -> Self { match v { 1 => Self::REQUEST, 2 => Self::REPLY, op => Self::UNKNOWN(op), } } } const ARP_HTYPE_EHER: u16 = 0x0001; const ARP_PTYPE_IPV4: u16 = 0x0800; impl ArpPacket { pub fn ipv4_over_ethernet( oper: ArpOperation, sha: MacAddr, spa: Ipv4Addr, tha: MacAddr, tpa: Ipv4Addr, ) -> Self { Self { htype: ARP_HTYPE_EHER, ptype: ARP_PTYPE_IPV4, hlen: 6, plen: 4, oper, sha: sha.octets().to_vec().into_boxed_slice(), spa: spa.octets().to_vec().into_boxed_slice(), tha: tha.octets().to_vec().into_boxed_slice(), tpa: tpa.octets().to_vec().into_boxed_slice(), } } pub fn parse(data: &[u8]) -> Result<Self> { let size = mem::size_of::<RawArpPacketHeader>(); if data.len() < size { Err(PacketParseError::new( "unable to parse ARP packet, not enough data", )) } else { let ptr = data.as_ptr(); let ptr = ptr as *const RawArpPacketHeader; let rh = unsafe { &*ptr }; let hlen = rh.hlen as usize; let plen = rh.plen as usize; let required = size + (hlen << 1) + (plen << 1); if data.len() < required { Err(PacketParseError::new( "unable to parse ARP packet, not enough data", )) } else { let offset_1 = size; let offset_2 = offset_1 + hlen; let offset_3 = offset_2 + plen; let offset_4 = offset_3 + hlen; let sha = &data[offset_1..offset_1 + hlen]; let spa = &data[offset_2..offset_2 + plen]; let tha = &data[offset_3..offset_3 + hlen]; let tpa = &data[offset_4..offset_4 + plen]; let res = Self { htype: u16::from_be(rh.htype), ptype: u16::from_be(rh.ptype), hlen: rh.hlen, plen: rh.plen, oper: ArpOperation::from(u16::from_be(rh.oper)), sha: sha.to_vec().into_boxed_slice(), spa: spa.to_vec().into_boxed_slice(), tha: tha.to_vec().into_boxed_slice(), tpa: tpa.to_vec().into_boxed_slice(), }; Ok(res) } } } } impl Serialize for ArpPacket { fn serialize(&self, w: &mut dyn Write) -> io::Result<()> { let rh = RawArpPacketHeader::new(self); w.write_all(utils::as_bytes(&rh))?; w.write_all(&self.sha)?; w.write_all(&self.spa)?; w.write_all(&self.tha)?; w.write_all(&self.tpa)?; Ok(()) } } impl EtherPacketBody for ArpPacket {} #[repr(packed)] struct RawArpPacketHeader { htype: u16, ptype: u16, hlen: u8, plen: u8, oper: u16, } impl RawArpPacketHeader { fn new(arp: &ArpPacket) -> Self { let operation = arp.oper.code(); Self { htype: arp.htype.to_be(), ptype: arp.ptype.to_be(), hlen: arp.hlen, plen: arp.plen, oper: operation.to_be(), } } } pub mod scanner { use super::*; use std::net::Ipv4Addr; use std::time::Duration; use bytes::Bytes; use crate::net::raw::pcap; use crate::net::raw::devices::EthernetDevice; use crate::net::raw::ether::packet::EtherPacket; use crate::net::raw::ether::MacAddr; use crate::net::raw::pcap::Scanner; use crate::net::raw::utils::Serialize; use crate::net::utils::Ipv4AddrEx; pub struct Ipv4ArpScanner { device: EthernetDevice, scanner: Scanner, } impl Ipv4ArpScanner { pub fn scan_device(device: &EthernetDevice) -> pcap::Result<Vec<(MacAddr, Ipv4Addr)>> { Self::new(device).scan() } fn new(device: &EthernetDevice) -> Self { Self { device: device.clone(), scanner: Scanner::new(&device.name), } } fn scan(&mut self) -> pcap::Result<Vec<(MacAddr, Ipv4Addr)>> { let bcast = MacAddr::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff); let hdst = MacAddr::new(0x00, 0x00, 0x00, 0x00, 0x00, 0x00); let hsrc = self.device.mac_addr; let psrc = self.device.ip_addr; let mask = self.device.netmask.as_u32(); let addr = self.device.ip_addr.as_u32(); let end = addr | !mask; let mut current = (addr & mask) + 1; let mut buffer = Vec::new(); let mut generator = move || { if current < end { let pdst = Ipv4Addr::from(current); let arpp = ArpPacket::ipv4_over_ethernet( ArpOperation::REQUEST, hsrc, psrc, hdst, pdst, ); let pkt = EtherPacket::arp(hsrc, bcast, arpp); buffer.clear(); pkt.serialize(&mut buffer).unwrap(); current += 1; let pkt = Bytes::copy_from_slice(&buffer); Some(pkt) } else { None } }; let filter = format!("arp and ether dst {}", self.device.mac_addr); let packets = self.scanner.sr( &filter, &mut generator, Duration::from_secs(2), Some(Duration::from_secs(20)), )?; let mut hosts = Vec::new(); for ep in packets { if let Some(arp) = ep.body::<ArpPacket>() { let sha = MacAddr::from_slice(arp.sha.as_ref()); let spa = Ipv4Addr::from_slice(arp.spa.as_ref()); hosts.push((sha, spa)); } } Ok(hosts) } } } #[cfg(test)] mod tests { use super::*; use std::net::Ipv4Addr; use crate::net::raw::ether::packet::EtherPacket; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[test] fn test_arp_packet() { let sip = Ipv4Addr::new(192, 168, 3, 7); let smac = MacAddr::new(1, 2, 3, 4, 5, 6); let dip = Ipv4Addr::new(192, 168, 8, 1); let dmac = MacAddr::new(6, 5, 4, 3, 2, 1); let arp = ArpPacket::ipv4_over_ethernet(ArpOperation::REQUEST, smac, sip, dmac, dip); let pkt = EtherPacket::arp(smac, dmac, arp); let mut buf = Vec::new(); pkt.serialize(&mut buf).unwrap(); let ep2 = EtherPacket::parse(buf.as_ref()).unwrap(); let arpp1 = pkt.body::<ArpPacket>().unwrap(); let arpp2 = ep2.body::<ArpPacket>().unwrap(); assert_eq!(arpp1.htype, arpp2.htype); assert_eq!(arpp1.ptype, arpp2.ptype); assert_eq!(arpp1.hlen, arpp2.hlen); assert_eq!(arpp1.plen, arpp2.plen); assert_eq!(arpp1.oper, arpp2.oper); assert_eq!(arpp1.sha, arpp2.sha); assert_eq!(arpp1.spa, arpp2.spa); assert_eq!(arpp1.tha, arpp2.tha); assert_eq!(arpp1.tpa, arpp2.tpa); } }
use std::io; use std::mem; use std::io::Write; use std::net::Ipv4Addr; use crate::utils; use crate::net::raw::ether::packet::{EtherPacketBody, PacketParseError, Result}; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[derive(Debug, Clone)] pub struct ArpPacket { pub htype: u16, pub ptype: u16, pub hlen: u8, pub plen: u8, pub oper: ArpOperation, pub sha: Box<[u8]>, pub spa: Box<[u8]>, pub tha: Box<[u8]>, pub tpa: Box<[u8]>, } #[allow(clippy::upper_case_acronyms)] #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum ArpOperation { REQUEST, REPLY, UNKNOWN(u16), } impl ArpOperation { pub fn code(self) -> u16 { match self { Self::REQUEST => 1, Self::REPLY => 2, Self::UNKNOWN(op) => op, } } } impl From<u16> for ArpOperation { fn from(v: u16) -> Self { match v { 1 => Self::REQUEST, 2 => Self::REPLY, op => Self::UNKNOWN(op), } } } const ARP_HTYPE_EHER: u16 = 0x0001; const ARP_PTYPE_IPV4: u16 = 0x0800; impl ArpPacket { pub fn ipv4_over_ethernet( oper: ArpOperation, sha: MacAddr, spa: Ipv4Addr, tha: MacAddr, tpa: Ipv4Addr, ) -> Self { Self { htype: ARP_HTYPE_EHER, ptype: ARP_PTYPE_IPV4,
pub fn parse(data: &[u8]) -> Result<Self> { let size = mem::size_of::<RawArpPacketHeader>(); if data.len() < size { Err(PacketParseError::new( "unable to parse ARP packet, not enough data", )) } else { let ptr = data.as_ptr(); let ptr = ptr as *const RawArpPacketHeader; let rh = unsafe { &*ptr }; let hlen = rh.hlen as usize; let plen = rh.plen as usize; let required = size + (hlen << 1) + (plen << 1); if data.len() < required { Err(PacketParseError::new( "unable to parse ARP packet, not enough data", )) } else { let offset_1 = size; let offset_2 = offset_1 + hlen; let offset_3 = offset_2 + plen; let offset_4 = offset_3 + hlen; let sha = &data[offset_1..offset_1 + hlen]; let spa = &data[offset_2..offset_2 + plen]; let tha = &data[offset_3..offset_3 + hlen]; let tpa = &data[offset_4..offset_4 + plen]; let res = Self { htype: u16::from_be(rh.htype), ptype: u16::from_be(rh.ptype), hlen: rh.hlen, plen: rh.plen, oper: ArpOperation::from(u16::from_be(rh.oper)), sha: sha.to_vec().into_boxed_slice(), spa: spa.to_vec().into_boxed_slice(), tha: tha.to_vec().into_boxed_slice(), tpa: tpa.to_vec().into_boxed_slice(), }; Ok(res) } } } } impl Serialize for ArpPacket { fn serialize(&self, w: &mut dyn Write) -> io::Result<()> { let rh = RawArpPacketHeader::new(self); w.write_all(utils::as_bytes(&rh))?; w.write_all(&self.sha)?; w.write_all(&self.spa)?; w.write_all(&self.tha)?; w.write_all(&self.tpa)?; Ok(()) } } impl EtherPacketBody for ArpPacket {} #[repr(packed)] struct RawArpPacketHeader { htype: u16, ptype: u16, hlen: u8, plen: u8, oper: u16, } impl RawArpPacketHeader { fn new(arp: &ArpPacket) -> Self { let operation = arp.oper.code(); Self { htype: arp.htype.to_be(), ptype: arp.ptype.to_be(), hlen: arp.hlen, plen: arp.plen, oper: operation.to_be(), } } } pub mod scanner { use super::*; use std::net::Ipv4Addr; use std::time::Duration; use bytes::Bytes; use crate::net::raw::pcap; use crate::net::raw::devices::EthernetDevice; use crate::net::raw::ether::packet::EtherPacket; use crate::net::raw::ether::MacAddr; use crate::net::raw::pcap::Scanner; use crate::net::raw::utils::Serialize; use crate::net::utils::Ipv4AddrEx; pub struct Ipv4ArpScanner { device: EthernetDevice, scanner: Scanner, } impl Ipv4ArpScanner { pub fn scan_device(device: &EthernetDevice) -> pcap::Result<Vec<(MacAddr, Ipv4Addr)>> { Self::new(device).scan() } fn new(device: &EthernetDevice) -> Self { Self { device: device.clone(), scanner: Scanner::new(&device.name), } } fn scan(&mut self) -> pcap::Result<Vec<(MacAddr, Ipv4Addr)>> { let bcast = MacAddr::new(0xff, 0xff, 0xff, 0xff, 0xff, 0xff); let hdst = MacAddr::new(0x00, 0x00, 0x00, 0x00, 0x00, 0x00); let hsrc = self.device.mac_addr; let psrc = self.device.ip_addr; let mask = self.device.netmask.as_u32(); let addr = self.device.ip_addr.as_u32(); let end = addr | !mask; let mut current = (addr & mask) + 1; let mut buffer = Vec::new(); let mut generator = move || { if current < end { let pdst = Ipv4Addr::from(current); let arpp = ArpPacket::ipv4_over_ethernet( ArpOperation::REQUEST, hsrc, psrc, hdst, pdst, ); let pkt = EtherPacket::arp(hsrc, bcast, arpp); buffer.clear(); pkt.serialize(&mut buffer).unwrap(); current += 1; let pkt = Bytes::copy_from_slice(&buffer); Some(pkt) } else { None } }; let filter = format!("arp and ether dst {}", self.device.mac_addr); let packets = self.scanner.sr( &filter, &mut generator, Duration::from_secs(2), Some(Duration::from_secs(20)), )?; let mut hosts = Vec::new(); for ep in packets { if let Some(arp) = ep.body::<ArpPacket>() { let sha = MacAddr::from_slice(arp.sha.as_ref()); let spa = Ipv4Addr::from_slice(arp.spa.as_ref()); hosts.push((sha, spa)); } } Ok(hosts) } } } #[cfg(test)] mod tests { use super::*; use std::net::Ipv4Addr; use crate::net::raw::ether::packet::EtherPacket; use crate::net::raw::ether::MacAddr; use crate::net::raw::utils::Serialize; #[test] fn test_arp_packet() { let sip = Ipv4Addr::new(192, 168, 3, 7); let smac = MacAddr::new(1, 2, 3, 4, 5, 6); let dip = Ipv4Addr::new(192, 168, 8, 1); let dmac = MacAddr::new(6, 5, 4, 3, 2, 1); let arp = ArpPacket::ipv4_over_ethernet(ArpOperation::REQUEST, smac, sip, dmac, dip); let pkt = EtherPacket::arp(smac, dmac, arp); let mut buf = Vec::new(); pkt.serialize(&mut buf).unwrap(); let ep2 = EtherPacket::parse(buf.as_ref()).unwrap(); let arpp1 = pkt.body::<ArpPacket>().unwrap(); let arpp2 = ep2.body::<ArpPacket>().unwrap(); assert_eq!(arpp1.htype, arpp2.htype); assert_eq!(arpp1.ptype, arpp2.ptype); assert_eq!(arpp1.hlen, arpp2.hlen); assert_eq!(arpp1.plen, arpp2.plen); assert_eq!(arpp1.oper, arpp2.oper); assert_eq!(arpp1.sha, arpp2.sha); assert_eq!(arpp1.spa, arpp2.spa); assert_eq!(arpp1.tha, arpp2.tha); assert_eq!(arpp1.tpa, arpp2.tpa); } }
hlen: 6, plen: 4, oper, sha: sha.octets().to_vec().into_boxed_slice(), spa: spa.octets().to_vec().into_boxed_slice(), tha: tha.octets().to_vec().into_boxed_slice(), tpa: tpa.octets().to_vec().into_boxed_slice(), } }
function_block-function_prefix_line
[ { "content": "/// Convert given 32-bit unsigned sum into 16-bit unsigned checksum.\n\npub fn sum_to_checksum(sum: u32) -> u16 {\n\n let mut checksum = sum;\n\n while (checksum & 0xffff_0000) != 0 {\n\n let hw = checksum >> 16;\n\n let lw = checksum & 0xffff;\n\n checksum = lw + hw;\n\n }\n\n\n\n !checksum as u16\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n #[derive(Copy, Clone, Debug, Eq, PartialEq)]\n\n #[repr(packed)]\n\n struct TestType {\n\n b1: u8,\n\n b2: u8,\n", "file_path": "src/net/raw/utils.rs", "rank": 0, "score": 164074.8055877109 }, { "content": "/// Get slice of bytes representing a given object.\n\npub fn as_bytes<T: Sized>(val: &T) -> &[u8] {\n\n let ptr = val as *const T;\n\n let size = mem::size_of::<T>();\n\n unsafe { slice::from_raw_parts(ptr as *const u8, size) }\n\n}\n\n\n", "file_path": "src/utils/mod.rs", "rank": 1, "score": 155071.14534093783 }, { "content": "/// Convert a given slice of Sized type instances to a slice of bytes.\n\npub fn slice_as_bytes<T: Sized>(data: &[T]) -> &[u8] {\n\n let ptr = data.as_ptr();\n\n let size = mem::size_of::<T>();\n\n unsafe { slice::from_raw_parts(ptr as *const u8, size * data.len()) }\n\n}\n\n\n\n/// Convert a given typed pointer into a new vector (copying the data).\n\n///\n\n/// # Safety\n\n/// The given pointer MUST point to an array that contains at least `len`\n\n/// elements. Each element is expected to be of size T.\n\npub unsafe fn vec_from_raw_parts<T: Clone>(ptr: *const T, len: usize) -> Vec<T> {\n\n slice::from_raw_parts(ptr, len).to_vec()\n\n}\n\n\n\n/// Convert a given C-string pointer to a new instance of String.\n\n///\n\n/// # Safety\n\n/// The given pointer MUST point to a NULL terminated C string.\n\npub unsafe fn cstr_to_string(ptr: *const i8) -> String {\n\n let cstr = CStr::from_ptr(ptr as *const _);\n\n let slice = String::from_utf8_lossy(cstr.to_bytes());\n\n slice.to_string()\n\n}\n\n\n", "file_path": "src/utils/mod.rs", "rank": 2, "score": 152176.10395244492 }, { "content": "/// Unwrap a given result or log an error with a given severity and return None.\n\npub fn result_or_log<L, T, E, M>(\n\n logger: &mut L,\n\n severity: Severity,\n\n msg: M,\n\n res: Result<T, E>,\n\n) -> Option<T>\n\nwhere\n\n E: Error + Debug,\n\n L: Logger,\n\n M: Display,\n\n{\n\n match res {\n\n Err(err) => {\n\n log!(logger, severity, \"{} ({})\", msg, err);\n\n None\n\n }\n\n Ok(res) => Some(res),\n\n }\n\n}\n\n\n", "file_path": "src/utils/mod.rs", "rank": 3, "score": 140603.36716354257 }, { "content": "/// Get socket address from a given argument.\n\npub fn get_socket_address<T>(s: T) -> Result<SocketAddr, RuntimeError>\n\nwhere\n\n T: ToSocketAddrs,\n\n{\n\n s.to_socket_addrs()\n\n .ok()\n\n .ok_or_else(|| RuntimeError::new(\"unable to get socket address\"))?\n\n .next()\n\n .ok_or_else(|| RuntimeError::new(\"unable to get socket address\"))\n\n}\n\n\n", "file_path": "src/net/utils.rs", "rank": 4, "score": 140581.3265524473 }, { "content": "fn trim_left(buffer: &[u8]) -> &[u8] {\n\n for i in 0..buffer.len() {\n\n let c = buffer[i] as char;\n\n if !c.is_whitespace() {\n\n return &buffer[i..];\n\n }\n\n }\n\n\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 test_parsing_valid() {\n\n let sdp = \"v=0\\r\\n\".to_string()\n\n + \"o=alice 2890844526 2890844527 IN IP4 host.atlanta.example.com\\r\"\n\n + \"s=\\n\"\n", "file_path": "src/net/rtsp/sdp.rs", "rank": 5, "score": 136381.81324056082 }, { "content": "/// Get MAC address of the first configured ethernet device.\n\nfn get_first_mac() -> Result<MacAddr, ConfigError> {\n\n EthernetDevice::list()\n\n .into_iter()\n\n .next()\n\n .map(|dev| dev.mac_addr)\n\n .ok_or_else(|| ConfigError::new(\"there is no configured ethernet device\"))\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 6, "score": 135036.72377610704 }, { "content": "/// Scan all local networks for RTSP and MJPEG streams and associated HTTP\n\n/// services.\n\npub fn scan_network(\n\n logger: BoxLogger,\n\n discovery_whitelist: Arc<HashSet<String, RandomState>>,\n\n rtsp_paths: Arc<Vec<String>>,\n\n mjpeg_paths: Arc<Vec<String>>,\n\n) -> Result<ScanResult> {\n\n let runtime = tokio::runtime::Builder::new_current_thread()\n\n .enable_io()\n\n .enable_time()\n\n .build()\n\n .map_err(|err| DiscoveryError::new(format!(\"Async IO error: {}\", err)))?;\n\n\n\n let context = Context::new(logger, discovery_whitelist, rtsp_paths, mjpeg_paths);\n\n\n\n let rtsp_port_priorities = context.get_rtsp_port_priorities();\n\n let http_port_priorities = context.get_http_port_priorities();\n\n\n\n let mut report = find_open_ports(context.clone());\n\n\n\n let rtsp_services =\n", "file_path": "src/scanner/discovery.rs", "rank": 7, "score": 132191.66820301572 }, { "content": "/// Diagnose a given connection result and exit with exit code 0 if the\n\n/// connection was successful or the server responded with UNAUTHORIZED,\n\n/// otherwise exit with exit code 1.\n\nfn diagnose_connection_result(connection_result: &Result<String, ArrowError>) -> ! {\n\n match connection_result {\n\n Ok(_) => process::exit(0),\n\n Err(err) => match err.kind() {\n\n ErrorKind::Unauthorized => process::exit(0),\n\n _ => process::exit(1),\n\n },\n\n }\n\n}\n\n\n\n/// Arrow client task. It must be awaited, otherwise it won't do anything.\n\npub struct ArrowClientTask {\n\n inner: Pin<Box<dyn Future<Output = ()> + Send>>,\n\n}\n\n\n\nimpl Future for ArrowClientTask {\n\n type Output = ();\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n self.inner.poll_unpin(cx)\n", "file_path": "src/client.rs", "rank": 8, "score": 124502.01956113371 }, { "content": "/// Helper function for constructing a map of port priorities. Assuming the\n\n/// given list of ports is sorted according to port priority (from highest to\n\n/// lowest), get a map of port -> port_priority pairs.\n\nfn get_port_priorities(ports: &[u16]) -> HashMap<u16, usize> {\n\n let mut res = HashMap::new();\n\n\n\n let len = ports.len();\n\n\n\n for (index, port) in ports.iter().enumerate() {\n\n res.insert(*port, len - index);\n\n }\n\n\n\n res\n\n}\n\n\n\n/// Network scanner context.\n", "file_path": "src/scanner/discovery.rs", "rank": 9, "score": 123419.06855085972 }, { "content": "/// Get MAC address of a given network interface.\n\nfn get_mac(iface: &str) -> Result<MacAddr, ConfigError> {\n\n EthernetDevice::list()\n\n .into_iter()\n\n .find(|dev| dev.name == iface)\n\n .map(|dev| dev.mac_addr)\n\n .ok_or_else(|| ConfigError::new(format!(\"there is no such ethernet device: {}\", iface)))\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 10, "score": 122338.95425801432 }, { "content": "/// Generate a fake MAC address from a given prefix and socket address.\n\n///\n\n/// Note: It is used in case we do not know the device MAC address (e.g. for\n\n/// services passed as command line arguments).\n\nfn get_fake_mac(prefix: u16, addr: &SocketAddr) -> MacAddr {\n\n match &addr {\n\n SocketAddr::V4(ref addr) => get_fake_mac_from_ipv4(prefix, addr),\n\n SocketAddr::V6(ref addr) => get_fake_mac_from_ipv6(prefix, addr),\n\n }\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 11, "score": 120772.73863873951 }, { "content": "#[doc(hidden)]\n\npub fn usage(exit_code: i32) -> ! {\n\n println!(\"USAGE: arrow-client arr-host[:arr-port] [OPTIONS]\\n\");\n\n println!(\" arr-host Angelcam Arrow Service host\");\n\n println!(\" arr-port Angelcam Arrow Service port\\n\");\n\n println!(\"OPTIONS:\\n\");\n\n println!(\" -i iface ethernet interface used for client identification (the first\");\n\n println!(\" configured network interface is used by default)\");\n\n println!(\" -c path path to a CA certificate for Arrow Service identity verification;\");\n\n println!(\" in case the path is a directory, it's scanned recursively for\");\n\n println!(\" all files with the following extensions:\\n\");\n\n println!(\" .der\");\n\n println!(\" .cer\");\n\n println!(\" .crr\");\n\n println!(\" .pem\\n\");\n\n if cfg!(feature = \"discovery\") {\n\n println!(\" -d automatic service discovery\");\n\n println!(\" -D iface limit automatic service discovery only on a given network\");\n\n println!(\" interface (implies -d; can be used multiple times)\");\n\n }\n\n println!(\" -r URL add a given RTSP service\");\n", "file_path": "src/config.rs", "rank": 12, "score": 119177.48349191993 }, { "content": "fn get_fake_mac_from_ipv6(prefix: u16, addr: &SocketAddrV6) -> MacAddr {\n\n let addr = addr.ip();\n\n let segments = addr.segments();\n\n\n\n let e0 = ((prefix >> 8) & 0xff) as u8;\n\n let e1 = (prefix & 0xff) as u8;\n\n let e2 = ((segments[6] >> 8) & 0xff) as u8;\n\n let e3 = (segments[6] & 0xff) as u8;\n\n let e4 = ((segments[7] >> 8) & 0xff) as u8;\n\n let e5 = (segments[7] & 0xff) as u8;\n\n\n\n MacAddr::new(e0, e1, e2, e3, e4, e5)\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 13, "score": 117395.63623577714 }, { "content": "fn get_fake_mac_from_ipv4(prefix: u16, addr: &SocketAddrV4) -> MacAddr {\n\n let a = ((prefix >> 8) & 0xff) as u8;\n\n let b = (prefix & 0xff) as u8;\n\n\n\n let addr = addr.ip();\n\n let octets = addr.octets();\n\n\n\n MacAddr::new(a, b, octets[0], octets[1], octets[2], octets[3])\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 14, "score": 117395.63623577714 }, { "content": "#[cfg(not(feature = \"threads\"))]\n\npub fn run<F>(future: F)\n\nwhere\n\n F: Future<Output = ()>,\n\n{\n\n tokio::runtime::Builder::new_current_thread()\n\n .enable_io()\n\n .enable_time()\n\n .build()\n\n .expect(\"unable to create a tokio runtime\")\n\n .block_on(future)\n\n}\n", "file_path": "src/runtime.rs", "rank": 15, "score": 115318.71417588904 }, { "content": "/// Check if a given session description contains at least one H.264 or\n\n/// a general MPEG4 video stream.\n\nfn is_supported_rtsp_service(sdp: &[u8]) -> bool {\n\n if let Ok(sdp) = SessionDescription::parse(sdp) {\n\n let mut vcodecs = HashSet::new();\n\n\n\n let video_streams = sdp\n\n .media_descriptions\n\n .into_iter()\n\n .filter(|md| md.media_type == MediaType::Video);\n\n\n\n for md in video_streams {\n\n for attr in md.attributes {\n\n if let Ok(rtpmap) = RTPMap::from_attr(&attr) {\n\n vcodecs.insert(rtpmap.encoding.to_uppercase());\n\n }\n\n }\n\n }\n\n\n\n vcodecs.contains(\"H264\")\n\n || vcodecs.contains(\"H264-RCDO\")\n\n || vcodecs.contains(\"H264-SVC\")\n\n || vcodecs.contains(\"MP4V-ES\")\n\n || vcodecs.contains(\"MPEG4-GENERIC\")\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/scanner/discovery.rs", "rank": 16, "score": 115296.96722023631 }, { "content": "/// Unwrap a given result (if possible) or print the error message and exit\n\n/// the process printing application usage.\n\nfn result_or_usage<T, E>(res: Result<T, E>) -> T\n\nwhere\n\n E: Error + Debug,\n\n{\n\n match res {\n\n Ok(res) => res,\n\n Err(err) => {\n\n println!(\"ERROR: {}\\n\", err);\n\n usage(1);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 17, "score": 110345.95887445018 }, { "content": "/// Find open ports on all available hosts within a given network.\n\nfn find_open_ports_in_network(context: Context, device: &EthernetDevice) -> Result<ScanResult> {\n\n let mut logger = context.get_logger();\n\n\n\n let mut report = ScanResult::new();\n\n\n\n log_debug!(\n\n &mut logger,\n\n \"running ARP scan in local network on interface {}\",\n\n device.name\n\n );\n\n\n\n for (mac, ip) in Ipv4ArpScanner::scan_device(device)? {\n\n report.add_host(mac, IpAddr::V4(ip), HR_FLAG_ARP);\n\n }\n\n\n\n log_debug!(\n\n &mut logger,\n\n \"running ICMP echo scan in local network on interface {}\",\n\n device.name\n\n );\n", "file_path": "src/scanner/discovery.rs", "rank": 18, "score": 106199.64859366948 }, { "content": "/// Parse a given RTSP URL and return an RTSP service, a LockedRTSP service or an error.\n\nfn parse_rtsp_url(url: &str) -> Result<Service, ConfigError> {\n\n let url = url\n\n .parse::<Url>()\n\n .map_err(|_| ConfigError::new(format!(\"invalid RTSP URL given: {}\", url)))?;\n\n\n\n let scheme = url.scheme();\n\n\n\n if !scheme.eq_ignore_ascii_case(\"rtsp\") {\n\n return Err(ConfigError::new(format!(\"invalid RTSP URL given: {}\", url)));\n\n }\n\n\n\n let host = url.host();\n\n let port = url.port().unwrap_or(554);\n\n\n\n let socket_addr = net::utils::get_socket_address((host, port)).map_err(|_| {\n\n ConfigError::new(format!(\n\n \"unable to resolve RTSP service address: {}:{}\",\n\n host, port\n\n ))\n\n })?;\n", "file_path": "src/config.rs", "rank": 19, "score": 103903.25218068088 }, { "content": "/// Parse a given HTTP URL and return an MJPEG service, a LockedMJPEG service or an error.\n\nfn parse_mjpeg_url(url: &str) -> Result<Service, ConfigError> {\n\n let url = url\n\n .parse::<Url>()\n\n .map_err(|_| ConfigError::new(format!(\"invalid HTTP URL given: {}\", url)))?;\n\n\n\n let scheme = url.scheme();\n\n\n\n if !scheme.eq_ignore_ascii_case(\"http\") {\n\n return Err(ConfigError::new(format!(\"invalid HTTP URL given: {}\", url)));\n\n }\n\n\n\n let host = url.host();\n\n let port = url.port().unwrap_or(80);\n\n\n\n let socket_addr = net::utils::get_socket_address((host, port)).map_err(|_| {\n\n ConfigError::new(format!(\n\n \"unable to resolve HTTP service address: {}:{}\",\n\n host, port\n\n ))\n\n })?;\n", "file_path": "src/config.rs", "rank": 20, "score": 103903.25218068088 }, { "content": "/// Create a new channel-handler pair.\n\npub fn new(app_context: ApplicationContext) -> (CommandChannel, CommandHandler) {\n\n let (tx, rx) = mpsc::unbounded();\n\n\n\n let rx = CommandHandler::new(app_context, rx, tx.clone());\n\n let tx = CommandChannel::new(tx);\n\n\n\n (tx, rx)\n\n}\n\n\n\n#[cfg(feature = \"discovery\")]\n", "file_path": "src/cmd_handler.rs", "rank": 21, "score": 100129.04515684173 }, { "content": "/// Sum a given Sized type instance as 16-bit unsigned big endian numbers.\n\npub fn sum_type<T: Sized>(data: &T) -> u32 {\n\n let size = mem::size_of::<T>();\n\n let ptr = data as *const T;\n\n unsafe { sum_raw_be(ptr as *const u8, size) }\n\n}\n\n\n", "file_path": "src/net/raw/utils.rs", "rank": 22, "score": 99126.11863063223 }, { "content": "/// Sum a given slice of Sized type instances as 16-bit unsigned big endian\n\n/// numbers.\n\npub fn sum_slice<T: Sized>(data: &[T]) -> u32 {\n\n let size = mem::size_of::<T>();\n\n let ptr = data.as_ptr();\n\n unsafe { sum_raw_be(ptr as *const u8, size * data.len()) }\n\n}\n\n\n\n/// Sum given raw data as 16-bit unsigned big endian numbers.\n\n#[allow(clippy::missing_safety_doc)]\n\n#[allow(clippy::cast_ptr_alignment)]\n\npub unsafe fn sum_raw_be(data: *const u8, size: usize) -> u32 {\n\n let sdata = slice::from_raw_parts(data as *const u16, size >> 1);\n\n let slice = slice::from_raw_parts(data, size);\n\n let mut sum: u32 = 0;\n\n for w in sdata {\n\n sum = sum.wrapping_add(u16::from_be(*w) as u32);\n\n }\n\n\n\n if (size & 0x01) != 0 {\n\n sum.wrapping_add((slice[size - 1] as u32) << 8)\n\n } else {\n\n sum\n\n }\n\n}\n\n\n", "file_path": "src/net/raw/utils.rs", "rank": 23, "score": 99126.11863063223 }, { "content": "#[cfg(not(feature = \"discovery\"))]\n\n#[allow(clippy::unnecessary_wraps)]\n\nfn load_paths<P>(_: P) -> Result<Vec<String>, io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n Ok(Vec::new())\n\n}\n", "file_path": "src/storage.rs", "rank": 24, "score": 96752.88918535066 }, { "content": "/// Helper function for loading persistent config.\n\nfn load_configuration_file<P>(file: P) -> Result<PersistentConfig, io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let mut file = File::open(file)?;\n\n let mut data = String::new();\n\n\n\n file.read_to_string(&mut data)?;\n\n\n\n let object = json::parse(&data).map_err(|err| {\n\n io::Error::new(\n\n io::ErrorKind::Other,\n\n format!(\"unable to parse configuration: {}\", err),\n\n )\n\n })?;\n\n\n\n let config = PersistentConfig::from_json(object)\n\n .map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()))?;\n\n\n\n Ok(config)\n\n}\n\n\n", "file_path": "src/storage.rs", "rank": 25, "score": 95249.19254068797 }, { "content": "#[cfg(feature = \"discovery\")]\n\nfn load_paths<P>(file: P) -> Result<Vec<String>, io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let file = File::open(file)?;\n\n let breader = BufReader::new(file);\n\n\n\n let mut paths = Vec::new();\n\n\n\n for line in breader.lines() {\n\n let path = line?;\n\n if !path.starts_with('#') {\n\n paths.push(path);\n\n }\n\n }\n\n\n\n Ok(paths)\n\n}\n\n\n\n/// Helper function for loading all path variants from a given file.\n", "file_path": "src/storage.rs", "rank": 26, "score": 94930.61383248557 }, { "content": "/// Send all packets using a given network device.\n\nfn send_packets<F>(device: &str, mut packet_generator: F) -> Result<()>\n\nwhere\n\n F: FnMut() -> Option<Bytes>,\n\n{\n\n let mut cap = Capture::builder(device).activate()?;\n\n\n\n while let Some(pkt) = packet_generator() {\n\n cap.write_packet(pkt.as_ref())?;\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/net/raw/pcap/mod.rs", "rank": 27, "score": 92057.27207667867 }, { "content": "/// Helper function for saving client public identity.\n\nfn save_identity_file<P>(identity: &PublicIdentity, file: P) -> Result<(), io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let mut file = File::create(file)?;\n\n\n\n identity.to_json().write(&mut file)?;\n\n\n\n Ok(())\n\n}\n\n\n\n/// Helper function for loading all path variants from a given file.\n", "file_path": "src/storage.rs", "rank": 28, "score": 91564.58006655573 }, { "content": "/// Helper function for saving persistent config.\n\nfn save_configuration_file<P>(config: &PersistentConfig, file: P) -> Result<(), io::Error>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let mut file = File::create(file)?;\n\n\n\n config.to_json().write(&mut file)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/storage.rs", "rank": 29, "score": 91564.58006655573 }, { "content": "/// Find open ports on all available hosts within all local networks\n\n/// accessible directly from this host.\n\nfn find_open_ports(scanner: Context) -> ScanResult {\n\n let discovery_whitelist = scanner.get_discovery_whitelist();\n\n\n\n let mut logger = scanner.get_logger();\n\n\n\n let mut report = ScanResult::new();\n\n\n\n let devices = EthernetDevice::list();\n\n\n\n for dev in devices {\n\n if discovery_whitelist.is_empty() || discovery_whitelist.contains(&dev.name) {\n\n let res = find_open_ports_in_network(scanner.clone(), &dev);\n\n\n\n if let Err(err) = res {\n\n log_warn!(\n\n &mut logger,\n\n \"unable to find open ports in local network on interface {}: {}\",\n\n dev.name,\n\n err\n\n );\n\n } else if let Ok(res) = res {\n\n report.merge(res);\n\n }\n\n }\n\n }\n\n\n\n report\n\n}\n\n\n", "file_path": "src/scanner/discovery.rs", "rank": 30, "score": 90992.32585205862 }, { "content": "fn main() {\n\n build_net_devices();\n\n\n\n if cfg!(feature = \"discovery\") {\n\n // Note: We need to build the wrapper first and then link WinPcap/libpcap. Otherwise, they\n\n // would link in an incorrect order and the dynamic library would be missing a dependency.\n\n build_pcap_wrapper();\n\n link_pcap();\n\n }\n\n}\n\n\n", "file_path": "build.rs", "rank": 31, "score": 75153.98216548216 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nenum Event {\n\n Command(Command),\n\n ScanCompleted,\n\n}\n\n\n", "file_path": "src/cmd_handler.rs", "rank": 32, "score": 73729.74147645732 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nenum SuspendReason {\n\n NotInPairingMode,\n\n UnsupportedProtocolVersion,\n\n}\n\n\n\nimpl SuspendReason {\n\n fn to_string(&self) -> &str {\n\n match *self {\n\n SuspendReason::NotInPairingMode => \"pairing window timeout\",\n\n SuspendReason::UnsupportedProtocolVersion => \"unsupported protocol version\",\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/client.rs", "rank": 33, "score": 73729.74147645732 }, { "content": "#[derive(Debug, Copy, Clone)]\n\nenum ConnectionRetry {\n\n Timeout(Duration),\n\n Suspend(SuspendReason),\n\n}\n\n\n\n/// Reason for suspending the Arrow connection thread.\n", "file_path": "src/client.rs", "rank": 34, "score": 73729.74147645732 }, { "content": "/// Type of the logger backend that should be used.\n\nenum LoggerType {\n\n #[cfg(not(target_os = \"windows\"))]\n\n Syslog,\n\n\n\n Stderr,\n\n StderrPretty,\n\n FileLogger,\n\n}\n\n\n\nimpl Default for LoggerType {\n\n #[cfg(not(target_os = \"windows\"))]\n\n fn default() -> Self {\n\n Self::Syslog\n\n }\n\n\n\n #[cfg(target_os = \"windows\")]\n\n fn default() -> Self {\n\n Self::Stderr\n\n }\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 35, "score": 73724.84099940161 }, { "content": "fn link_pcap() {\n\n if cfg!(target_os = \"windows\") {\n\n // on Windows, we primarily try to find the lib using vcpkg\n\n let lib = vcpkg::Config::new()\n\n .cargo_metadata(true)\n\n .emit_includes(false)\n\n .copy_dlls(false)\n\n .find_package(\"winpcap\");\n\n\n\n // if vcpkg cannot find the lib, we try the env. variables\n\n if lib.is_err() {\n\n if let Some(dir) = dir_from_var(\"WINPCAP_LIB_DIR\") {\n\n emit_lib_path(&dir);\n\n }\n\n\n\n link(\"winpcap\", \"WINPCAP_STATIC\");\n\n }\n\n } else {\n\n // on other platforms, we expect the lib will be in standard paths or the paths will be\n\n // defined using env. variables\n\n if let Some(dir) = dir_from_var(\"LIBPCAP_LIB_DIR\") {\n\n emit_lib_path(&dir);\n\n }\n\n\n\n link(\"pcap\", \"LIBPCAP_STATIC\");\n\n }\n\n}\n", "file_path": "build.rs", "rank": 36, "score": 73559.9049039721 }, { "content": "/// Arrow Client main function.\n\nfn main() {\n\n let config = result_or_usage(Config::from_args(std::env::args()));\n\n\n\n let (client, task) = ArrowClient::new(config);\n\n\n\n // forget the client, we want to run the application indefinitely\n\n std::mem::forget(client);\n\n\n\n runtime::run(task);\n\n}\n", "file_path": "src/main.rs", "rank": 37, "score": 73559.9049039721 }, { "content": "#[derive(Clone)]\n\nstruct Context {\n\n data: Arc<ContextData>,\n\n}\n\n\n\nimpl Context {\n\n /// Create a new network scanner context.\n\n fn new(\n\n logger: BoxLogger,\n\n discovery_whitelist: Arc<HashSet<String>>,\n\n rtsp_paths: Arc<Vec<String>>,\n\n mjpeg_paths: Arc<Vec<String>>,\n\n ) -> Self {\n\n Self {\n\n data: Arc::new(ContextData::new(\n\n logger,\n\n discovery_whitelist,\n\n rtsp_paths,\n\n mjpeg_paths,\n\n )),\n\n }\n", "file_path": "src/scanner/discovery.rs", "rank": 38, "score": 72803.47055008553 }, { "content": "/// Builder for application configuration.\n\nstruct ConfigParser {\n\n arrow_mac: Option<MacAddr>,\n\n arrow_svc_addr: String,\n\n ca_certificates: Vec<PathBuf>,\n\n services: Vec<Service>,\n\n logger_type: LoggerType,\n\n config_file: PathBuf,\n\n config_file_skel: PathBuf,\n\n identity_file: Option<PathBuf>,\n\n state_file: PathBuf,\n\n rtsp_paths_file: PathBuf,\n\n mjpeg_paths_file: PathBuf,\n\n log_file: PathBuf,\n\n discovery: bool,\n\n discovery_whitelist: Vec<String>,\n\n verbose: bool,\n\n diagnostic_mode: bool,\n\n log_file_size: usize,\n\n log_file_rotations: usize,\n\n lock_file: Option<PathBuf>,\n", "file_path": "src/config.rs", "rank": 39, "score": 72798.49703187465 }, { "content": "#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\nenum StreamType {\n\n Supported,\n\n Locked,\n\n Unsupported,\n\n NotFound,\n\n Error,\n\n}\n\n\n\nimpl From<RtspResponse> for StreamType {\n\n fn from(response: RtspResponse) -> Self {\n\n let status_code = response.status_code();\n\n\n\n if status_code == 200 {\n\n if is_supported_rtsp_service(response.body()) {\n\n Self::Supported\n\n } else {\n\n Self::Unsupported\n\n }\n\n } else if status_code == 401 {\n\n Self::Locked\n", "file_path": "src/scanner/discovery.rs", "rank": 40, "score": 72335.68091274987 }, { "content": "fn build_pcap_wrapper() {\n\n let mut wrapper_builder = Build::new();\n\n\n\n if cfg!(target_os = \"windows\") {\n\n // on Windows, we primarily try to find the lib using vcpkg\n\n let lib = vcpkg::Config::new()\n\n .cargo_metadata(false)\n\n .emit_includes(false)\n\n .copy_dlls(false)\n\n .find_package(\"winpcap\");\n\n\n\n if let Ok(lib) = lib {\n\n for include in lib.include_paths {\n\n wrapper_builder.include(include);\n\n }\n\n } else if let Some(dir) = dir_from_var(\"WINPCAP_INCLUDE_DIR\") {\n\n // if vcpkg cannot find the lib, we try the env. variable\n\n wrapper_builder.include(dir);\n\n }\n\n } else if let Some(dir) = dir_from_var(\"LIBPCAP_INCLUDE_DIR\") {\n", "file_path": "build.rs", "rank": 41, "score": 72074.79946850165 }, { "content": "fn build_net_devices() {\n\n Build::new()\n\n .include(\"src\")\n\n .include(\"src/net/raw/devices\")\n\n .file(\"src/net/raw/devices/devices-common.c\")\n\n .file(&format!(\"src/net/raw/devices/devices-{}.c\", get_platform()))\n\n .compile(\"net_devices\");\n\n}\n\n\n", "file_path": "build.rs", "rank": 42, "score": 72074.79946850165 }, { "content": "#[derive(Clone)]\n\nstruct CallbackLogger {\n\n context: Arc<Mutex<CallbackLoggerContext>>,\n\n}\n\n\n\nimpl CallbackLogger {\n\n /// Create a new logger.\n\n fn new(callback: LogCallback, opaque: *mut c_void) -> Self {\n\n Self {\n\n context: Arc::new(Mutex::new(CallbackLoggerContext::new(callback, opaque))),\n\n }\n\n }\n\n}\n\n\n\nimpl Logger for CallbackLogger {\n\n fn log(&mut self, file: &str, line: u32, severity: Severity, msg: Arguments) {\n\n self.context.lock().unwrap().log(file, line, severity, msg)\n\n }\n\n\n\n fn set_level(&mut self, level: Severity) {\n\n let mut context = self.context.lock().unwrap();\n", "file_path": "src/exports/logger.rs", "rank": 43, "score": 71411.3143280659 }, { "content": "/// Arrow session (i.e. connection to an external service).\n\nstruct Session {\n\n context: Arc<Mutex<SessionContext>>,\n\n}\n\n\n\nimpl Session {\n\n /// Create a new session for a given service ID and session ID.\n\n fn new(service_id: u16, session_id: u32, addr: SocketAddr) -> Self {\n\n let context = Arc::new(Mutex::new(SessionContext::new(service_id, session_id)));\n\n\n\n let session = Session {\n\n context: context.clone(),\n\n };\n\n\n\n tokio::spawn(async move {\n\n let transport = SessionTransport::connect(context.clone(), addr);\n\n\n\n match transport.await {\n\n Ok(transport) => transport.await,\n\n Err(err) => context.lock().unwrap().set_error(err),\n\n }\n", "file_path": "src/net/arrow/session.rs", "rank": 44, "score": 71406.34080985501 }, { "content": "/// This future ensures maintaining connection with a remote Arrow Service.\n\nstruct ArrowMainTask {\n\n app_context: ApplicationContext,\n\n cmd_channel: CommandChannel,\n\n logger: BoxLogger,\n\n default_addr: String,\n\n current_addr: String,\n\n last_attempt: Instant,\n\n pairing_mode_timeout: Instant,\n\n diagnostic_mode: bool,\n\n}\n\n\n\nimpl ArrowMainTask {\n\n /// Create a new task.\n\n async fn start(app_context: ApplicationContext, cmd_channel: CommandChannel) {\n\n let logger = app_context.get_logger();\n\n let addr = app_context.get_arrow_service_address();\n\n let diagnostic_mode = app_context.get_diagnostic_mode();\n\n\n\n let now = Instant::now();\n\n\n", "file_path": "src/client.rs", "rank": 45, "score": 71406.34080985501 }, { "content": "/// Internal data for the network scanner context.\n\nstruct ContextData {\n\n logger: BoxLogger,\n\n port_candidates: HashSet<u16>,\n\n rtsp_port_candidates: HashSet<u16>,\n\n http_port_candidates: HashSet<u16>,\n\n rtsp_port_priorities: HashMap<u16, usize>,\n\n http_port_priorities: HashMap<u16, usize>,\n\n discovery_whitelist: Arc<HashSet<String>>,\n\n rtsp_paths: Arc<Vec<String>>,\n\n mjpeg_paths: Arc<Vec<String>>,\n\n request_timeout: Duration,\n\n}\n\n\n\nimpl ContextData {\n\n /// Create new context data for the network scanner context.\n\n fn new(\n\n logger: BoxLogger,\n\n discovery_whitelist: Arc<HashSet<String>>,\n\n rtsp_paths: Arc<Vec<String>>,\n\n mjpeg_paths: Arc<Vec<String>>,\n", "file_path": "src/scanner/discovery.rs", "rank": 46, "score": 71406.34080985501 }, { "content": "/// Internal data of the application context.\n\nstruct ApplicationContextData {\n\n logger: BoxLogger,\n\n config: Config,\n\n scanning: bool,\n\n scan_result: ScanResult,\n\n connection_state: ConnectionState,\n\n event_listeners: Vec<Box<dyn ApplicationEventListener + Send>>,\n\n}\n\n\n\nimpl ApplicationContextData {\n\n /// Take a given application config and create application context data.\n\n fn new(config: Config) -> Self {\n\n Self {\n\n logger: config.get_logger(),\n\n config,\n\n scanning: false,\n\n scan_result: ScanResult::new(),\n\n connection_state: ConnectionState::Disconnected,\n\n event_listeners: Vec::new(),\n\n }\n", "file_path": "src/context.rs", "rank": 47, "score": 71406.34080985501 }, { "content": "#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\nenum ProtocolState {\n\n Handshake,\n\n Established,\n\n}\n\n\n", "file_path": "src/net/arrow/mod.rs", "rank": 48, "score": 71025.96209523425 }, { "content": "/// Process a given connection error and return a ConnectionRetry instance.\n\nfn process_connection_error(\n\n connection_error: ArrowError,\n\n last_attempt: Instant,\n\n pairing_mode_timeout: Instant,\n\n) -> ConnectionRetry {\n\n let now = Instant::now();\n\n\n\n match connection_error.kind() {\n\n // the client is not authorized to access the service yet; check the\n\n // pairing mode timeout\n\n ErrorKind::Unauthorized => {\n\n if (now + Duration::from_secs(600)) < pairing_mode_timeout {\n\n // retry every 10 seconds in the first 10 minutes since the\n\n // first \"unauthorized\" response\n\n ConnectionRetry::Timeout(Duration::from_secs(10))\n\n } else if now < pairing_mode_timeout {\n\n // retry every 30 seconds after the first 10 minutes since the\n\n // first \"unauthorized\" response\n\n ConnectionRetry::Timeout(Duration::from_secs(30))\n\n } else {\n", "file_path": "src/client.rs", "rank": 49, "score": 70687.86112402589 }, { "content": "/// Helper struct.\n\nstruct ConnectionStateListener {\n\n callback: ConnectionStateCallback,\n\n opaque: *mut c_void,\n\n}\n\n\n\nimpl ConnectionStateListener {\n\n /// Create a new connection state listener.\n\n fn new(opaque: *mut c_void, callback: ConnectionStateCallback) -> Self {\n\n Self { callback, opaque }\n\n }\n\n}\n\n\n\nimpl ArrowClientEventListener for ConnectionStateListener {\n\n fn connection_state_changed(&mut self, state: ConnectionState) {\n\n unsafe { (self.callback)(self.opaque, connection_state_to_c_int(state)) }\n\n }\n\n}\n\n\n\nunsafe impl Send for ConnectionStateListener {}\n\n\n", "file_path": "src/exports/mod.rs", "rank": 50, "score": 70108.36211199664 }, { "content": "/// Helper struct for expected ACK messages.\n\nstruct ExpectedAck {\n\n timestamp: Instant,\n\n message_id: u16,\n\n}\n\n\n\nimpl ExpectedAck {\n\n /// Create a new ACK message expectation.\n\n fn new(message_id: u16) -> Self {\n\n Self {\n\n timestamp: Instant::now(),\n\n message_id,\n\n }\n\n }\n\n\n\n /// Check if it's too late for the ACK.\n\n fn timeout(&self) -> bool {\n\n self.timestamp.elapsed() >= ACK_TIMEOUT\n\n }\n\n}\n\n\n", "file_path": "src/net/arrow/mod.rs", "rank": 51, "score": 70108.16220254207 }, { "content": "/// A struct that will remove the async context when dropped.\n\nstruct DropAsyncContext;\n\n\n\nimpl Drop for DropAsyncContext {\n\n fn drop(&mut self) {\n\n ASYNC_CONTEXT.with(|v| {\n\n *v.borrow_mut() = None;\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/net/tls.rs", "rank": 52, "score": 70108.09900476428 }, { "content": "/// Capture handle that can be used for reading and writing raw packets.\n\nstruct Capture {\n\n ptr: *mut c_void,\n\n}\n\n\n\nimpl Capture {\n\n /// Get a builder.\n\n pub fn builder(device: &str) -> CaptureBuilder {\n\n CaptureBuilder::new(device)\n\n }\n\n\n\n /// Read one packet. The packet will be appended to a given buffer. True will be returned if a\n\n /// packet was read, false will be returned in case of timeout.\n\n pub fn read_packet(&mut self, buffer: &mut BytesMut) -> Result<bool> {\n\n let buffer_ptr: *mut BytesMut = buffer;\n\n\n\n let ret =\n\n unsafe { pcap_wrapper__read_packet(self.ptr, read_packet_callback, buffer_ptr as _) };\n\n\n\n if ret >= 0 {\n\n Ok(ret > 0)\n", "file_path": "src/net/raw/pcap/mod.rs", "rank": 53, "score": 70107.84446270921 }, { "content": "/// Incremental line reader. It takes both CR and LF as line separators.\n\nstruct LineReader {\n\n buffer: Vec<u8>,\n\n capacity: usize,\n\n complete: bool,\n\n partial: bool,\n\n}\n\n\n\nimpl LineReader {\n\n /// Create a new line reader with a given line length limit.\n\n fn new(limit: usize) -> Self {\n\n Self {\n\n buffer: Vec::new(),\n\n capacity: limit,\n\n complete: false,\n\n partial: false,\n\n }\n\n }\n\n\n\n /// Get current line.\n\n fn line(&self) -> Option<&[u8]> {\n", "file_path": "src/net/rtsp/sdp.rs", "rank": 54, "score": 70103.26352675437 }, { "content": "/// Session context.\n\nstruct SessionContext {\n\n service_id: u16,\n\n session_id: u32,\n\n input: BytesMut,\n\n output: BytesMut,\n\n buffer_capacity: usize,\n\n session_manager_task: Option<Waker>,\n\n session_transport_task: Option<Waker>,\n\n closed: bool,\n\n error: Option<ConnectionError>,\n\n}\n\n\n\nimpl SessionContext {\n\n /// Create a new session context for a given service ID and session ID.\n\n fn new(service_id: u16, session_id: u32) -> Self {\n\n let buffer_capacity = 8192;\n\n\n\n Self {\n\n service_id,\n\n session_id,\n", "file_path": "src/net/arrow/session.rs", "rank": 55, "score": 70103.26352675437 }, { "content": "/// Stable implementation of the Hasher trait.\n\nstruct StableHasher {\n\n data: Vec<u8>,\n\n}\n\n\n\nimpl StableHasher {\n\n /// Create a new instance of StableHasher with a given capacity of the\n\n /// internal data buffer.\n\n fn new(capacity: usize) -> StableHasher {\n\n StableHasher {\n\n data: Vec::with_capacity(capacity),\n\n }\n\n }\n\n}\n\n\n\nimpl Hasher for StableHasher {\n\n fn finish(&self) -> u64 {\n\n farmhash::fingerprint64(&self.data)\n\n }\n\n\n\n fn write(&mut self, bytes: &[u8]) {\n\n self.data.extend_from_slice(bytes)\n\n }\n\n}\n\n\n", "file_path": "src/svc_table/mod.rs", "rank": 56, "score": 70103.26352675437 }, { "content": "/// Internal context for callback-based loggers.\n\nstruct CallbackLoggerContext {\n\n callback: LogCallback,\n\n opaque: *mut c_void,\n\n level: Severity,\n\n}\n\n\n\nimpl CallbackLoggerContext {\n\n /// Create a new context.\n\n fn new(callback: LogCallback, opaque: *mut c_void) -> Self {\n\n Self {\n\n callback,\n\n opaque,\n\n level: Severity::INFO,\n\n }\n\n }\n\n\n\n /// Log message.\n\n fn log(&self, file: &str, line: u32, severity: Severity, msg: Arguments) {\n\n if severity < self.level {\n\n return;\n", "file_path": "src/exports/logger.rs", "rank": 57, "score": 70103.26352675437 }, { "content": "/// Session transport. It is a future that drives communication with the remote\n\n/// host.\n\nstruct SessionTransport {\n\n context: Arc<Mutex<SessionContext>>,\n\n stream: TcpStream,\n\n}\n\n\n\nimpl SessionTransport {\n\n /// Create a new session transport by connecting to a given host.\n\n async fn connect(\n\n context: Arc<Mutex<SessionContext>>,\n\n addr: SocketAddr,\n\n ) -> Result<Self, ConnectionError> {\n\n let stream = tokio::time::timeout(CONNECTION_TIMEOUT, TcpStream::connect(addr))\n\n .await\n\n .map_err(|_| ConnectionError::new(\"connection timeout\"))?\n\n .map_err(ConnectionError::from)?;\n\n\n\n let transport = Self { context, stream };\n\n\n\n Ok(transport)\n\n }\n", "file_path": "src/net/arrow/session.rs", "rank": 58, "score": 70103.26352675437 }, { "content": "/// RTSP client codec.\n\nstruct ClientCodec {\n\n hdecoder: GenericResponseHeaderDecoder,\n\n bdecoder: Option<FixedSizeBodyDecoder>,\n\n header: Option<GenericResponseHeader>,\n\n ignore_response_body: bool,\n\n}\n\n\n\nimpl ClientCodec {\n\n /// Create a new RTSP client codec.\n\n fn new(max_line_length: usize, max_header_lines: usize, ignore_response_body: bool) -> Self {\n\n let hdecoder = GenericResponseHeaderDecoder::new(max_line_length, max_header_lines);\n\n\n\n Self {\n\n hdecoder,\n\n bdecoder: None,\n\n header: None,\n\n ignore_response_body,\n\n }\n\n }\n\n}\n", "file_path": "src/net/rtsp/mod.rs", "rank": 59, "score": 70103.26352675437 }, { "content": "/// Command handler context.\n\nstruct CommandHandlerContext {\n\n app_context: ApplicationContext,\n\n logger: BoxLogger,\n\n cmd_sender: CommandSender,\n\n last_nw_scan: Option<Instant>,\n\n scanner: Option<JoinHandle<()>>,\n\n}\n\n\n\nimpl CommandHandlerContext {\n\n /// Create a new command handler context.\n\n fn new(app_context: ApplicationContext, cmd_sender: CommandSender) -> Self {\n\n let logger = app_context.get_logger();\n\n\n\n Self {\n\n app_context,\n\n logger,\n\n cmd_sender,\n\n last_nw_scan: None,\n\n scanner: None,\n\n }\n", "file_path": "src/cmd_handler.rs", "rank": 60, "score": 70103.26352675437 }, { "content": "#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\nenum ChunkedDecoderState {\n\n ChunkHeader,\n\n ChunkBody,\n\n ChunkBodyDelimiter,\n\n TrailerPart,\n\n Completed,\n\n}\n\n\n\n/// Decoder for HTTP-like chunked bodies.\n\npub struct ChunkedBodyDecoder {\n\n state: ChunkedDecoderState,\n\n ldecoder: LineDecoder,\n\n body: Vec<u8>,\n\n expected: usize,\n\n ignore: bool,\n\n}\n\n\n\nimpl ChunkedBodyDecoder {\n\n /// Create a new decoder for HTTP-like chunked bodies.\n\n pub fn new(max_line_length: usize, ignore_data: bool) -> Self {\n", "file_path": "src/net/http/generic.rs", "rank": 61, "score": 69797.44931406889 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn test_reader() {\n\n let input = \"Hello, World!!! 1234\\n\\tfoo-bar\";\n\n\n\n let mut reader = Reader::new(input);\n\n\n\n assert!(!reader.is_empty());\n\n assert_eq!(reader.current_char(), Some('H'));\n\n assert_eq!(reader.as_str(), input);\n\n\n\n let word = reader.read_word();\n\n\n\n assert_eq!(word, \"Hello,\");\n\n assert_eq!(reader.as_str(), \" World!!! 1234\\n\\tfoo-bar\");\n\n\n\n reader.skip_whitespace();\n\n\n\n assert_eq!(reader.as_str(), \"World!!! 1234\\n\\tfoo-bar\");\n\n\n\n let c = reader.read_char();\n\n\n", "file_path": "src/utils/string/reader.rs", "rank": 62, "score": 69389.66784574158 }, { "content": "/// Test the service priority filtering function.\n\nfn test_service_filtering() {\n\n let ports = [554, 80];\n\n let mac = MacAddr::new(0, 0, 0, 0, 0, 0);\n\n let ip = Ipv4Addr::new(0, 0, 0, 0);\n\n\n\n let mut services = Vec::new();\n\n\n\n services.push((mac, SocketAddr::V4(SocketAddrV4::new(ip, 80))));\n\n services.push((mac, SocketAddr::V4(SocketAddrV4::new(ip, 554))));\n\n\n\n let port_priorities = get_port_priorities(&ports);\n\n\n\n let services = filter_duplicit_services(services, &port_priorities);\n\n\n\n assert_eq!(services.len(), 1);\n\n assert_eq!(services[0].1.port(), 554);\n\n}\n", "file_path": "src/scanner/discovery.rs", "rank": 63, "score": 69389.66784574158 }, { "content": "/// Arrow client storage.\n\npub trait Storage {\n\n /// Save a given persistent configuration.\n\n fn save_configuration(&mut self, config: &PersistentConfig) -> Result<(), io::Error>;\n\n\n\n /// Create a new empty configuration.\n\n fn create_configuration(&mut self) -> Result<PersistentConfig, io::Error> {\n\n Ok(PersistentConfig::new())\n\n }\n\n\n\n /// Load persistent configuration.\n\n fn load_configuration(&mut self) -> Result<PersistentConfig, io::Error>;\n\n\n\n /// Save connection state.\n\n fn save_connection_state(&mut self, _: ConnectionState) -> Result<(), io::Error> {\n\n Ok(())\n\n }\n\n\n\n /// Load a list of RTSP paths for the device discovery.\n\n fn load_rtsp_paths(&mut self) -> Result<Vec<String>, io::Error> {\n\n Ok(Vec::new())\n", "file_path": "src/storage.rs", "rank": 64, "score": 69213.70767005651 }, { "content": "/// Helper trait for getting Any reference to an object.\n\npub trait AsAny {\n\n /// Get Any reference to this object.\n\n fn as_any(&self) -> &dyn Any;\n\n\n\n /// Get mutable Any reference to this object.\n\n fn as_any_mut(&mut self) -> &mut dyn Any;\n\n}\n\n\n\nimpl<T: Any + 'static> AsAny for T {\n\n fn as_any(&self) -> &dyn Any {\n\n self\n\n }\n\n\n\n fn as_any_mut(&mut self) -> &mut dyn Any {\n\n self\n\n }\n\n}\n\n\n\n/// General purpose runtime error.\n\n#[derive(Debug, Clone)]\n", "file_path": "src/utils/mod.rs", "rank": 65, "score": 69213.70767005651 }, { "content": "/// Helper struct.\n\nstruct NetworkScannerStateListener {\n\n callback: NetworkScannerStateCallback,\n\n opaque: *mut c_void,\n\n}\n\n\n\nimpl NetworkScannerStateListener {\n\n /// Create a new network scanner state listener.\n\n fn new(opaque: *mut c_void, callback: NetworkScannerStateCallback) -> Self {\n\n Self { callback, opaque }\n\n }\n\n}\n\n\n\nimpl ArrowClientEventListener for NetworkScannerStateListener {\n\n fn network_scanner_state_changed(&mut self, scanning: bool) {\n\n unsafe { (self.callback)(self.opaque, c_int::from(scanning)) }\n\n }\n\n}\n\n\n\nunsafe impl Send for NetworkScannerStateListener {}\n\n\n", "file_path": "src/exports/mod.rs", "rank": 66, "score": 68886.07907251801 }, { "content": "#[derive(Clone)]\n\nstruct ServiceTableData {\n\n identifier_map: HashMap<ServiceIdentifier, u16>,\n\n service_map: HashMap<u16, ServiceTableElement>,\n\n version: usize,\n\n}\n\n\n\nimpl ServiceTableData {\n\n /// Create a new instance of ServiceTableData.\n\n fn new() -> Self {\n\n let elem = ServiceTableElement::control();\n\n\n\n let mut identifier_map = HashMap::new();\n\n let mut service_map = HashMap::new();\n\n\n\n identifier_map.insert(elem.service.to_service_identifier(), elem.id);\n\n\n\n service_map.insert(elem.id, elem);\n\n\n\n Self {\n\n identifier_map,\n", "file_path": "src/svc_table/mod.rs", "rank": 67, "score": 68885.95400548661 }, { "content": "#[derive(Clone)]\n\nstruct ServiceTableElement {\n\n /// Service ID.\n\n id: u16,\n\n /// Service.\n\n service: Service,\n\n /// Flag indicating a manually added service.\n\n static_service: bool,\n\n /// Flag indicating static service visibility.\n\n enabled: bool,\n\n /// UNIX timestamp (in UTC) of the last discovery event.\n\n last_seen: i64,\n\n /// Active flag.\n\n active: bool,\n\n}\n\n\n\nimpl ServiceTableElement {\n\n /// Create a new Control Protocol service table element.\n\n fn control() -> Self {\n\n Self::new(0, Service::control(), true, true)\n\n }\n", "file_path": "src/svc_table/mod.rs", "rank": 68, "score": 68885.95400548661 }, { "content": "/// Internal logger implementation.\n\nstruct InternalFileLogger {\n\n level: Severity,\n\n path: PathBuf,\n\n file: File,\n\n written: usize,\n\n limit: usize,\n\n rotations: usize,\n\n}\n\n\n\nimpl InternalFileLogger {\n\n /// Write a given line into the underlaying file and rotate as necessary.\n\n fn write_line(&mut self, line: &str) -> io::Result<()> {\n\n self.write(line.as_bytes())\n\n }\n\n\n\n /// Write given data into the underlaying file and rotate as necessary.\n\n fn write(&mut self, data: &[u8]) -> io::Result<()> {\n\n if (self.written + data.len()) > self.limit {\n\n self.rotate()?;\n\n }\n", "file_path": "src/utils/logger/file.rs", "rank": 69, "score": 68880.98048727572 }, { "content": "/// Capture builder.\n\nstruct CaptureBuilder {\n\n inner: Capture,\n\n}\n\n\n\nimpl CaptureBuilder {\n\n /// Create a new capture builder for a given device.\n\n fn new(device: &str) -> Self {\n\n let device = CString::new(device).unwrap();\n\n\n\n let ptr = unsafe { pcap_wrapper__new(device.as_ptr()) };\n\n\n\n if ptr.is_null() {\n\n panic!(\"Unable to allocate PCAP capture device\");\n\n }\n\n\n\n let capture = Capture { ptr };\n\n\n\n Self { inner: capture }\n\n }\n\n\n", "file_path": "src/net/raw/pcap/mod.rs", "rank": 70, "score": 68880.98048727572 }, { "content": "/// Arrow Client implementation.\n\nstruct ArrowClientContext {\n\n logger: BoxLogger,\n\n app_context: ApplicationContext,\n\n cmd_channel: CommandChannel,\n\n svc_table: SharedServiceTableRef,\n\n cmsg_factory: ControlMessageFactory,\n\n sessions: SessionManager,\n\n messages: VecDeque<ArrowMessage>,\n\n expected_acks: VecDeque<ExpectedAck>,\n\n state: ProtocolState,\n\n task: Option<Waker>,\n\n redirect: Option<String>,\n\n closed: bool,\n\n last_ping: Instant,\n\n last_update_chck: Instant,\n\n last_stable_ver: usize,\n\n}\n\n\n\nimpl ArrowClientContext {\n\n /// Create a new Arrow Client.\n", "file_path": "src/net/arrow/mod.rs", "rank": 71, "score": 68880.98048727572 }, { "content": "/// Session description parser.\n\nstruct SessionDescriptionParser {\n\n sdp: SessionDescription,\n\n}\n\n\n\nimpl SessionDescriptionParser {\n\n /// Parse session description from a given string.\n\n fn parse(sdp: &[u8]) -> Result<SessionDescription> {\n\n let mut parser = Self {\n\n sdp: SessionDescription::new(),\n\n };\n\n\n\n let reader = LineReader::new(4096);\n\n let mut lines = LineIterator::new(reader, sdp);\n\n\n\n parser.process_lines(&mut lines)?;\n\n\n\n Ok(parser.sdp)\n\n }\n\n\n\n /// Process SDP lines.\n", "file_path": "src/net/rtsp/sdp.rs", "rank": 72, "score": 68880.98048727572 }, { "content": "/// Listen for incoming packets matching a given filter until no packets are read for a given\n\n/// soft timeout or until a given hard timeout expires.\n\n///\n\n/// # Arguments\n\n/// * `device` - device name\n\n/// * `filter` - packet filter expression\n\n/// * `packet_timeout` - a soft timeout that will stop the listener if no packet is received for\n\n/// given duration\n\n/// * `total_timeout` - a hard timeout that will stop the listener when it expires\n\n/// * `init_event_tx` - an optional sender that will be used to notify another thread that the\n\n/// listener has been initialized and is receiving packets\n\nfn packet_listener(\n\n device: &str,\n\n filter: &str,\n\n packet_timeout: Duration,\n\n total_timeout: Option<Duration>,\n\n init_event_tx: Option<Sender<()>>,\n\n) -> Result<Vec<EtherPacket>> {\n\n let mut cap = Capture::builder(device)\n\n .max_packet_length(65_536)\n\n .read_timeout(100)\n\n .filter(Some(filter))\n\n .activate()?;\n\n\n\n if let Some(tx) = init_event_tx {\n\n tx.send(()).unwrap_or_default();\n\n }\n\n\n\n let start_time = Instant::now();\n\n\n\n let mut last_packet_time = Instant::now();\n", "file_path": "src/net/raw/pcap/mod.rs", "rank": 73, "score": 68177.73247305094 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn test_deserialization_and_initialization() {\n\n let json = object! {\n\n \"services\" => array![\n\n object!{\n\n \"svc_type\" => 1,\n\n \"mac\" => \"00:00:00:00:00:00\",\n\n \"address\" => \"0.0.0.0:0\",\n\n \"path\" => \"/1\",\n\n \"static_svc\" => true,\n\n \"last_seen\" => 123,\n\n \"active\" => true\n\n },\n\n object!{\n\n \"svc_type\" => 1,\n\n \"mac\" => \"00:00:00:00:00:00\",\n\n \"address\" => \"0.0.0.0:0\",\n\n \"path\" => \"/2\",\n\n \"static_svc\" => true,\n\n \"last_seen\" => 123,\n\n \"active\" => true\n", "file_path": "src/svc_table/mod.rs", "rank": 74, "score": 68171.96598984214 }, { "content": "/// Common trait for objects that can be represented as JSON.\n\npub trait ToJson {\n\n /// Get JSON representation of the object.\n\n fn to_json(&self) -> JsonValue;\n\n}\n", "file_path": "src/utils/json.rs", "rank": 75, "score": 67819.90951132134 }, { "content": "#[repr(packed)]\n\n#[allow(dead_code)]\n\nstruct PseudoIpv4PacketHeader {\n\n src: [u8; 4],\n\n dst: [u8; 4],\n\n res: u8,\n\n protocol: u8,\n\n tcp_len: u16,\n\n}\n\n\n\nimpl PseudoIpv4PacketHeader {\n\n /// Create a new pseudo IPv4 packet header.\n\n fn new(iph: &Ipv4PacketHeader) -> Self {\n\n Self {\n\n src: iph.src.octets(),\n\n dst: iph.dst.octets(),\n\n res: 0,\n\n protocol: iph.protocol.code(),\n\n tcp_len: 0,\n\n }\n\n }\n\n}\n", "file_path": "src/net/raw/tcp.rs", "rank": 76, "score": 67732.20345081855 }, { "content": "#[repr(packed)]\n\n#[allow(dead_code)]\n\nstruct RawIcmpPacketHeader {\n\n icmp_type: u8,\n\n code: u8,\n\n checksum: u16,\n\n rest: u32,\n\n}\n\n\n", "file_path": "src/net/raw/icmp.rs", "rank": 78, "score": 67732.20345081855 }, { "content": "#[repr(packed)]\n\nstruct RawTcpPacketHeader {\n\n sport: u16,\n\n dport: u16,\n\n seq: u32,\n\n ack: u32,\n\n doffset_flags: u16,\n\n wsize: u16,\n\n checksum: u16,\n\n uptr: u16,\n\n}\n\n\n\nimpl RawTcpPacketHeader {\n\n /// Create a new raw TCP packet header.\n\n fn new(iph: &Ipv4PacketHeader, tcp: &TcpPacket) -> Self {\n\n let mut ph = PseudoIpv4PacketHeader::new(iph);\n\n let doffset = 5 + tcp.options.len() as u16;\n\n let doffset_flags = (doffset << 12) | (tcp.flags & 0x01ff);\n\n let tcp_len = (doffset << 2) + tcp.data.len() as u16;\n\n let mut rh = Self {\n\n sport: tcp.sport.to_be(),\n", "file_path": "src/net/raw/tcp.rs", "rank": 79, "score": 67732.20345081855 }, { "content": "#[repr(packed)]\n\n#[allow(dead_code)]\n\nstruct RawIpv4PacketHeader {\n\n vihl: u8,\n\n dscp_ecn: u8,\n\n length: u16,\n\n ident: u16,\n\n flags_foffset: u16,\n\n ttl: u8,\n\n protocol: u8,\n\n checksum: u16,\n\n src: [u8; 4],\n\n dst: [u8; 4],\n\n}\n\n\n\nimpl RawIpv4PacketHeader {\n\n /// Create a new raw IPv4 packet header.\n\n fn new(ip: &Ipv4PacketHeader, dlen: usize) -> RawIpv4PacketHeader {\n\n let size = mem::size_of::<RawIpv4PacketHeader>();\n\n let length = size + (ip.options.len() << 2) + dlen;\n\n let ihl = 5 + ip.options.len() as u8;\n\n let flags_foffset = ((ip.flags as u16) << 13) | (ip.foffset & 0x1fff);\n", "file_path": "src/net/raw/ip.rs", "rank": 80, "score": 67732.20345081855 }, { "content": "#[cfg(test)]\n\n#[test]\n\nfn test_visible_services_iterator() {\n\n let mut table = ServiceTableData::new();\n\n\n\n let mac = MacAddr::zero();\n\n let ip = Ipv4Addr::new(0, 0, 0, 0);\n\n let addr = SocketAddr::V4(SocketAddrV4::new(ip, 0));\n\n\n\n let svc_1 = Service::rtsp(mac, addr, \"/1\".to_string());\n\n let svc_2 = Service::rtsp(mac, addr, \"/2\".to_string());\n\n let svc_3 = Service::rtsp(mac, addr, \"/3\".to_string());\n\n\n\n table.update(svc_1.clone(), true, true);\n\n table.update(svc_2, true, false);\n\n table.update(svc_3.clone(), true, true);\n\n\n\n let mut visible = table.visible().collect::<Vec<_>>();\n\n\n\n visible.sort_by_key(|&(id, _)| id);\n\n\n\n let mut expected = vec![(41839, svc_1), (26230, svc_3)];\n\n\n\n expected.sort_by_key(|&(id, _)| id);\n\n\n\n assert_eq!(visible, expected);\n\n}\n\n\n", "file_path": "src/svc_table/mod.rs", "rank": 81, "score": 67027.49463245076 }, { "content": "#[derive(Clone)]\n\nstruct Element {\n\n id: u16,\n\n service: Service,\n\n}\n\n\n\nimpl Element {\n\n /// Create a new element for the simple service table.\n\n fn new(id: u16, service: Service) -> Self {\n\n Self { id, service }\n\n }\n\n}\n\n\n\nimpl Encode for Element {\n\n fn encode(&self, buf: &mut BytesMut) {\n\n ElementHeader::from(self).encode(buf);\n\n\n\n let path = self.service.path().unwrap_or(\"\");\n\n\n\n buf.extend_from_slice(path.as_bytes());\n\n buf.extend_from_slice(&[0]);\n", "file_path": "src/net/arrow/proto/msg/control/svc_table.rs", "rank": 82, "score": 66655.46871024318 }, { "content": "#[repr(packed)]\n\nstruct RawEtherPacketHeader {\n\n dst: [u8; 6],\n\n src: [u8; 6],\n\n etype: u16,\n\n}\n\n\n\n/// Ethernet packet types.\n\n#[allow(clippy::upper_case_acronyms)]\n\n#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n\npub enum EtherPacketType {\n\n ARP,\n\n IPv4,\n\n UNKNOWN(u16),\n\n}\n\n\n\nimpl EtherPacketType {\n\n /// Get system code of this packet type.\n\n pub fn code(self) -> u16 {\n\n match self {\n\n Self::ARP => ETYPE_ARP,\n", "file_path": "src/net/raw/ether/packet.rs", "rank": 83, "score": 66650.49519203231 }, { "content": "/// Listener for application events.\n\npub trait ApplicationEventListener {\n\n /// Report new connection state.\n\n fn connection_state_changed(&mut self, _: ConnectionState) {}\n\n\n\n /// Report new network scanner state (`true` means that the network scanner is running).\n\n fn network_scanner_state_changed(&mut self, _: bool) {}\n\n}\n\n\n", "file_path": "src/context.rs", "rank": 84, "score": 66515.29535297606 }, { "content": "/// Common trait for serializable objects.\n\npub trait Serialize {\n\n /// Serialize this object using a given writer.\n\n fn serialize(&self, w: &mut dyn Write) -> io::Result<()>;\n\n}\n\n\n\nimpl Serialize for Box<[u8]> {\n\n fn serialize(&self, w: &mut dyn Write) -> io::Result<()> {\n\n w.write_all(self.as_ref())\n\n }\n\n}\n\n\n", "file_path": "src/net/raw/utils.rs", "rank": 85, "score": 66515.29535297606 }, { "content": "/// Line iterator (it uses the line reader).\n\nstruct LineIterator<'a> {\n\n reader: LineReader,\n\n content: &'a [u8],\n\n offset: usize,\n\n}\n\n\n\nimpl<'a> LineIterator<'a> {\n\n /// Create a new line iterator for a given reader and content.\n\n fn new(reader: LineReader, content: &'a [u8]) -> Self {\n\n Self {\n\n reader,\n\n content,\n\n offset: 0,\n\n }\n\n }\n\n\n\n /// Return next line or None if there are no more lines. An error is\n\n /// returned if the line length has been exceeded.\n\n fn next(&mut self) -> Result<Option<Vec<u8>>> {\n\n self.reader.clear();\n", "file_path": "src/net/rtsp/sdp.rs", "rank": 86, "score": 66324.95097257427 }, { "content": "/// A pending TLS connection.\n\nstruct TlsConnect<S> {\n\n handshake: Option<HandshakeResult<S>>,\n\n}\n\n\n\nimpl<S> Future for TlsConnect<S>\n\nwhere\n\n S: AsyncRead + AsyncWrite + Unpin,\n\n{\n\n type Output = Result<TlsStream<S>, TlsError>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {\n\n let _drop_context = set_async_context(cx);\n\n\n\n match self\n\n .handshake\n\n .take()\n\n .expect(\"the future has been already resolved\")\n\n {\n\n Ok(stream) => Poll::Ready(Ok(stream.into())),\n\n Err(HandshakeError::SetupFailure(err)) => Poll::Ready(Err(TlsError::from(err))),\n", "file_path": "src/net/tls.rs", "rank": 87, "score": 66320.19042357685 }, { "content": "/// Filter out duplicit services from a given list using given priorities.\n\nfn filter_duplicit_services<I>(\n\n services: I,\n\n port_priorities: &HashMap<u16, usize>,\n\n) -> Vec<(MacAddr, SocketAddr)>\n\nwhere\n\n I: IntoIterator<Item = (MacAddr, SocketAddr)>,\n\n{\n\n let mut svc_map = HashMap::new();\n\n\n\n for (mac, saddr) in services {\n\n let ip = saddr.ip();\n\n let port = saddr.port();\n\n\n\n svc_map\n\n .entry(ip)\n\n .and_modify(|v| {\n\n let &mut (_, _, old_port) = v;\n\n\n\n let old_priority = port_priorities.get(&old_port).cloned().unwrap_or(0);\n\n let new_priority = port_priorities.get(&port).cloned().unwrap_or(0);\n", "file_path": "src/scanner/discovery.rs", "rank": 88, "score": 65680.95378599453 }, { "content": "#[repr(packed)]\n\n#[allow(dead_code)]\n\nstruct RegisterMessageHeader {\n\n uuid: [u8; 16],\n\n mac: [u8; 6],\n\n passwd: [u8; 16],\n\n}\n\n\n\nimpl RegisterMessageHeader {\n\n /// Create a new REGISTER message header.\n\n fn new(mac: MacAddr, uuid: [u8; 16], password: [u8; 16]) -> Self {\n\n Self {\n\n uuid,\n\n mac: mac.octets(),\n\n passwd: password,\n\n }\n\n }\n\n}\n\n\n\nimpl Encode for RegisterMessageHeader {\n\n fn encode(&self, buf: &mut BytesMut) {\n\n buf.extend_from_slice(utils::as_bytes(self))\n", "file_path": "src/net/arrow/proto/msg/control/register.rs", "rank": 89, "score": 65630.14881232574 }, { "content": "#[repr(packed)]\n\nstruct ElementHeader {\n\n svc_id: u16,\n\n svc_type: u16,\n\n mac_addr: [u8; 6],\n\n ip_version: u8,\n\n ip_addr: [u8; 16],\n\n port: u16,\n\n}\n\n\n\nimpl<'a> From<&'a Element> for ElementHeader {\n\n fn from(element: &'a Element) -> Self {\n\n let service_type = element.service.service_type();\n\n\n\n let null_maddress = MacAddr::new(0, 0, 0, 0, 0, 0);\n\n let null_saddress = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0));\n\n\n\n let maddress = element.service.mac().unwrap_or(null_maddress);\n\n let saddress = element.service.address().unwrap_or(null_saddress);\n\n let iaddress = saddress.ip();\n\n\n", "file_path": "src/net/arrow/proto/msg/control/svc_table.rs", "rank": 90, "score": 65630.14881232574 }, { "content": "/// Ipv4Addr extension.\n\npub trait Ipv4AddrEx {\n\n /// Crete address from slice.\n\n fn from_slice(bytes: &[u8]) -> Ipv4Addr;\n\n\n\n /// Convert a given IPv4 address into big endian 32-bit unsigned number.\n\n fn as_u32(&self) -> u32;\n\n}\n\n\n\nimpl Ipv4AddrEx for Ipv4Addr {\n\n fn from_slice(bytes: &[u8]) -> Ipv4Addr {\n\n assert_eq!(bytes.len(), 4);\n\n\n\n #[allow(clippy::cast_ptr_alignment)]\n\n let ptr = bytes.as_ptr() as *const u32;\n\n let addr = unsafe { u32::from_be(*ptr) };\n\n\n\n Self::from(addr)\n\n }\n\n\n\n fn as_u32(&self) -> u32 {\n\n let octets = self.octets();\n\n\n\n let nr: u32 = unsafe { mem::transmute(octets) };\n\n\n\n nr.to_be()\n\n }\n\n}\n\n\n", "file_path": "src/net/utils.rs", "rank": 91, "score": 65291.57072858939 }, { "content": "/// Common trait for service table implementations.\n\npub trait ServiceTable {\n\n /// Get service with a given ID.\n\n fn get(&self, id: u16) -> Option<Service>;\n\n\n\n /// Get service ID for a given ServiceIdentifier.\n\n fn get_id(&self, identifier: &ServiceIdentifier) -> Option<u16>;\n\n\n\n /// Convert this service table into a trait object.\n\n fn boxed(self) -> BoxServiceTable;\n\n}\n\n\n\n/// Type alias for boxed service table.\n\npub type BoxServiceTable = Box<dyn ServiceTable + Send + Sync>;\n\n\n\nimpl ServiceTable for Box<dyn ServiceTable + Send + Sync> {\n\n fn get(&self, id: u16) -> Option<Service> {\n\n self.as_ref().get(id)\n\n }\n\n\n\n fn get_id(&self, identifier: &ServiceIdentifier) -> Option<u16> {\n\n self.as_ref().get_id(identifier)\n\n }\n\n\n\n fn boxed(self) -> BoxServiceTable {\n\n self\n\n }\n\n}\n\n\n\n/// Service table element.\n", "file_path": "src/svc_table/mod.rs", "rank": 92, "score": 65291.57072858939 }, { "content": "/// IpAddr extension.\n\npub trait IpAddrEx {\n\n /// Get left-aligned byte representation of the IP address.\n\n fn bytes(&self) -> [u8; 16];\n\n\n\n /// Get IP address version.\n\n fn version(&self) -> u8;\n\n}\n\n\n\nimpl IpAddrEx for IpAddr {\n\n fn bytes(&self) -> [u8; 16] {\n\n match &self {\n\n Self::V4(ref ip_addr) => ip_addr.bytes(),\n\n Self::V6(ref ip_addr) => ip_addr.bytes(),\n\n }\n\n }\n\n\n\n fn version(&self) -> u8 {\n\n match &self {\n\n Self::V4(ref ip_addr) => ip_addr.version(),\n\n Self::V6(ref ip_addr) => ip_addr.version(),\n", "file_path": "src/net/utils.rs", "rank": 93, "score": 65291.57072858939 }, { "content": "/// Common trait for objects that can be encoded as a sequence of bytes.\n\npub trait Encode {\n\n /// Serialize this object into a given buffer.\n\n fn encode(&self, buf: &mut BytesMut);\n\n}\n\n\n\nimpl<T: AsRef<[u8]>> Encode for T {\n\n fn encode(&self, buf: &mut BytesMut) {\n\n buf.extend_from_slice(self.as_ref())\n\n }\n\n}\n\n\n", "file_path": "src/net/arrow/proto/codec.rs", "rank": 94, "score": 65291.57072858939 }, { "content": "/// Helper struct.\n\nstruct InnerSslStream<S> {\n\n inner: S,\n\n}\n\n\n\nimpl<S> InnerSslStream<S> {\n\n /// Create a new inner stream.\n\n fn new(stream: S) -> Self {\n\n Self { inner: stream }\n\n }\n\n}\n\n\n\nimpl<S> Read for InnerSslStream<S>\n\nwhere\n\n S: AsyncRead + Unpin,\n\n{\n\n fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {\n\n with_async_context(|cx| {\n\n let inner = Pin::new(&mut self.inner);\n\n\n\n let mut buf = ReadBuf::new(buf);\n", "file_path": "src/net/tls.rs", "rank": 95, "score": 65103.00596934049 }, { "content": "struct ArrowClient<S> {\n\n context: Arc<Mutex<ArrowClientContext>>,\n\n stream: S,\n\n}\n\n\n\nimpl<S> ArrowClient<S> {\n\n /// Create a new instance of Arrow Client.\n\n fn new(app_context: ApplicationContext, cmd_channel: CommandChannel, stream: S) -> Self {\n\n let context = ArrowClientContext::new(app_context, cmd_channel);\n\n\n\n let context = Arc::new(Mutex::new(context));\n\n\n\n let event_handler = context.clone();\n\n\n\n tokio::spawn(async move {\n\n loop {\n\n tokio::time::sleep(Duration::from_secs(1)).await;\n\n\n\n {\n\n let mut context = event_handler.lock().unwrap();\n", "file_path": "src/net/arrow/mod.rs", "rank": 96, "score": 65097.90738409822 }, { "content": "/// Host table element.\n\nstruct Element {\n\n host: HostRecord,\n\n}\n\n\n\nimpl Element {\n\n /// Create a new host table element.\n\n fn new(host: HostRecord) -> Self {\n\n Self { host }\n\n }\n\n}\n\n\n\nimpl Encode for Element {\n\n fn encode(&self, buf: &mut BytesMut) {\n\n ElementHeader::from(self).encode(buf);\n\n\n\n for port in self.host.ports() {\n\n buf.extend_from_slice(utils::as_bytes(&port.to_be()));\n\n }\n\n }\n\n}\n\n\n\nimpl MessageBody for Element {\n\n fn len(&self) -> usize {\n\n let ports = self.host.ports();\n\n\n\n mem::size_of::<ElementHeader>() + (ports.len() * mem::size_of::<u16>())\n\n }\n\n}\n\n\n\n/// Host table header.\n", "file_path": "src/net/arrow/proto/msg/control/scan_report/host_table.rs", "rank": 97, "score": 64666.08702371839 }, { "content": "/// Find open ports on given hosts from a given network.\n\nfn find_open_ports_on_hosts<I>(\n\n context: Context,\n\n device: &EthernetDevice,\n\n hosts: I,\n\n) -> Result<Vec<(MacAddr, SocketAddr)>>\n\nwhere\n\n I: IntoIterator<Item = (MacAddr, IpAddr)>,\n\n{\n\n let mut logger = context.get_logger();\n\n\n\n log_debug!(\n\n &mut logger,\n\n \"running TCP port scan in local network on interface {}\",\n\n device.name\n\n );\n\n\n\n let hosts = hosts.into_iter().filter_map(|(mac, ip)| match ip {\n\n IpAddr::V4(ip) => Some((mac, ip)),\n\n _ => None,\n\n });\n", "file_path": "src/scanner/discovery.rs", "rank": 98, "score": 64458.67099414022 } ]
Rust
crates/eosio_token/src/lib.rs
datudou/rust-eos
636073c21d2ab21af3f853fd09c907a3564a5a4e
use eosio::*; #[eosio_action] fn create(issuer: AccountName, max_supply: Asset) { let receiver = AccountName::receiver(); require_auth(receiver); let symbol = max_supply.symbol; eosio_assert(max_supply.amount > 0, "max-supply must be positive"); let symbol_name = symbol.name(); let table = CurrencyStats::table(receiver, symbol_name); eosio_assert( !table.exists(symbol_name), "token with symbol already existss", ); let stats = CurrencyStats { supply: Asset { amount: 0, symbol }, max_supply, issuer, }; table.emplace(receiver, &stats).assert("write"); } #[eosio_action] fn issue(to: AccountName, quantity: Asset, memo: String) { let receiver = AccountName::receiver(); let symbol = quantity.symbol; eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let table = CurrencyStats::table(receiver, symbol.name()); let cursor = table .find(symbol.name()) .assert("token with symbol does not exist, create token before issue"); let mut st = cursor.get().assert("read"); require_auth(st.issuer); eosio_assert(quantity.amount > 0, "must issue positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply", ); st.supply += quantity; cursor.modify(None, &st).assert("write"); add_balance(st.issuer, quantity, st.issuer); if to != st.issuer { let action = TransferAction { from: st.issuer, to, quantity, memo, }; action .send_inline(vec![Authorization { actor: st.issuer, permission: n!(active).into(), }]) .assert("failed to send inline action"); } } #[eosio_action] fn open(owner: AccountName, symbol: Symbol, ram_payer: AccountName) { require_auth(ram_payer); let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, symbol.name()); let cursor = accounts_table.find(symbol.name()); if cursor.is_none() { let account = Account { balance: Asset { amount: 0, symbol }, }; accounts_table.emplace(ram_payer, &account).assert("write"); } } #[eosio_action] fn close(owner: AccountName, symbol: Symbol) { require_auth(owner); let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, symbol.name()); let cursor = accounts_table .find(symbol.name()) .assert("Balance row already deleted or never existed. Action won't have any effect."); let account = cursor.get().assert("read"); eosio_assert( account.balance.amount == 0, "Cannot close because the balance is not zero.", ); cursor.erase().assert("read"); } #[eosio_action] fn retire(quantity: Asset, memo: String) { eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let receiver = AccountName::receiver(); let symbol = quantity.symbol; let stats_table = CurrencyStats::table(receiver, symbol.name()); let cursor = stats_table .find(symbol.name()) .assert("token with symbol does not exist"); let mut st = cursor.get().assert("error reading stats table"); require_auth(st.issuer); eosio_assert(quantity.amount > 0, "must retire positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); st.supply -= quantity; cursor.modify(None, &st).assert("write"); } #[eosio_action] fn transfer(from: AccountName, to: AccountName, quantity: Asset, memo: String) { eosio_assert(from != to, "cannot transfer to self"); require_auth(from); to.is_account().assert("to account does not exist"); let receiver = AccountName::receiver(); let symbol_name = quantity.symbol.name(); let stats_table = CurrencyStats::table(receiver, symbol_name); let cursor = stats_table .find(symbol_name) .assert("token with symbol does not exist"); let st = cursor.get().assert("read"); require_recipient(from); require_recipient(to); eosio_assert(quantity.amount > 0, "must transfer positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let payer = if to.has_auth() { to } else { from }; sub_balance(from, quantity); add_balance(to, quantity, payer); } eosio_abi!(create, issue, transfer, open, close, retire); #[cfg(feature = "contract")] fn sub_balance(owner: AccountName, value: Asset) { let receiver = AccountName::receiver(); let table = Account::table(receiver, owner); let cursor = table .find(value.symbol.name()) .assert("no balance object found"); let mut account = cursor.get().assert("read"); account.balance -= value; cursor.modify(Some(owner), &account).assert("write"); } #[cfg(feature = "contract")] fn add_balance(owner: AccountName, value: Asset, ram_payer: AccountName) { let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, owner); let cursor = accounts_table.find(value.symbol.name()); match cursor { Some(cursor) => { let mut account = cursor.get().assert("read"); account.balance += value; cursor.modify(Some(ram_payer), &account).assert("write"); } None => { let account = Account { balance: value }; accounts_table.emplace(ram_payer, &account).assert("write"); } } } #[derive(Read, Write, NumBytes, Copy, Clone)] pub struct Account { balance: Asset, } #[cfg(feature = "contract")] impl TableRow for Account { const TABLE_NAME: u64 = n!(accounts); fn primary_key(&self) -> u64 { self.balance.symbol.name().into() } } #[derive(Read, Write, NumBytes, Copy, Clone)] pub struct CurrencyStats { supply: Asset, max_supply: Asset, issuer: AccountName, } #[cfg(feature = "contract")] impl TableRow for CurrencyStats { const TABLE_NAME: u64 = n!(stat); fn primary_key(&self) -> u64 { self.supply.symbol.name().into() } }
use eosio::*; #[eosio_action] fn create(issuer: AccountName, max_supply: Asset) { let receiver = AccountName::receiver(); require_auth(receiver); let symbol = max_supply.symbol; eosio_assert(max_supply.amount > 0, "max-supply must be positive"); let symbol_name = symbol.name(); let table = CurrencyStats::table(receiver, symbol_name); eosio_assert( !table.exists(symbol_name), "token with symbol already existss", ); let stats = CurrencyStats { supply: Asset { amount: 0, symbol }, max_supply, issuer, }; table.emplace(receiver, &stats).assert("write"); } #[eosio_action] fn issue(to: AccountName, quantity: Asset, memo: String) { let receiver = AccountName::receiver(); let symbol = quantity.symbol; eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let table = CurrencyStats::table(receiver, symbol.name()); let cursor = table .find(symbol.name()) .assert("token with symbol does not exist, create token before issue"); let mut st = cursor.get().assert("read"); require_auth(st.issuer); eosio_assert(quantity.amount > 0, "must issue positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); eosio_assert( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply", ); st.supply += quantity; cursor.modify(None, &st).assert("write"); add_balance(st.issuer, quantity, st.issuer); if to != st.issuer { let action = TransferAction {
m_payer); let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, symbol.name()); let cursor = accounts_table.find(symbol.name()); if cursor.is_none() { let account = Account { balance: Asset { amount: 0, symbol }, }; accounts_table.emplace(ram_payer, &account).assert("write"); } } #[eosio_action] fn close(owner: AccountName, symbol: Symbol) { require_auth(owner); let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, symbol.name()); let cursor = accounts_table .find(symbol.name()) .assert("Balance row already deleted or never existed. Action won't have any effect."); let account = cursor.get().assert("read"); eosio_assert( account.balance.amount == 0, "Cannot close because the balance is not zero.", ); cursor.erase().assert("read"); } #[eosio_action] fn retire(quantity: Asset, memo: String) { eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let receiver = AccountName::receiver(); let symbol = quantity.symbol; let stats_table = CurrencyStats::table(receiver, symbol.name()); let cursor = stats_table .find(symbol.name()) .assert("token with symbol does not exist"); let mut st = cursor.get().assert("error reading stats table"); require_auth(st.issuer); eosio_assert(quantity.amount > 0, "must retire positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); st.supply -= quantity; cursor.modify(None, &st).assert("write"); } #[eosio_action] fn transfer(from: AccountName, to: AccountName, quantity: Asset, memo: String) { eosio_assert(from != to, "cannot transfer to self"); require_auth(from); to.is_account().assert("to account does not exist"); let receiver = AccountName::receiver(); let symbol_name = quantity.symbol.name(); let stats_table = CurrencyStats::table(receiver, symbol_name); let cursor = stats_table .find(symbol_name) .assert("token with symbol does not exist"); let st = cursor.get().assert("read"); require_recipient(from); require_recipient(to); eosio_assert(quantity.amount > 0, "must transfer positive quantity"); eosio_assert( quantity.symbol == st.supply.symbol, "symbol precision mismatch", ); eosio_assert(memo.len() <= 256, "memo has more than 256 bytes"); let payer = if to.has_auth() { to } else { from }; sub_balance(from, quantity); add_balance(to, quantity, payer); } eosio_abi!(create, issue, transfer, open, close, retire); #[cfg(feature = "contract")] fn sub_balance(owner: AccountName, value: Asset) { let receiver = AccountName::receiver(); let table = Account::table(receiver, owner); let cursor = table .find(value.symbol.name()) .assert("no balance object found"); let mut account = cursor.get().assert("read"); account.balance -= value; cursor.modify(Some(owner), &account).assert("write"); } #[cfg(feature = "contract")] fn add_balance(owner: AccountName, value: Asset, ram_payer: AccountName) { let receiver = AccountName::receiver(); let accounts_table = Account::table(receiver, owner); let cursor = accounts_table.find(value.symbol.name()); match cursor { Some(cursor) => { let mut account = cursor.get().assert("read"); account.balance += value; cursor.modify(Some(ram_payer), &account).assert("write"); } None => { let account = Account { balance: value }; accounts_table.emplace(ram_payer, &account).assert("write"); } } } #[derive(Read, Write, NumBytes, Copy, Clone)] pub struct Account { balance: Asset, } #[cfg(feature = "contract")] impl TableRow for Account { const TABLE_NAME: u64 = n!(accounts); fn primary_key(&self) -> u64 { self.balance.symbol.name().into() } } #[derive(Read, Write, NumBytes, Copy, Clone)] pub struct CurrencyStats { supply: Asset, max_supply: Asset, issuer: AccountName, } #[cfg(feature = "contract")] impl TableRow for CurrencyStats { const TABLE_NAME: u64 = n!(stat); fn primary_key(&self) -> u64 { self.supply.symbol.name().into() } }
from: st.issuer, to, quantity, memo, }; action .send_inline(vec![Authorization { actor: st.issuer, permission: n!(active).into(), }]) .assert("failed to send inline action"); } } #[eosio_action] fn open(owner: AccountName, symbol: Symbol, ram_payer: AccountName) { require_auth(ra
random
[ { "content": "fn titlecase(s: &str) -> String {\n\n let mut c = s.chars();\n\n match c.next() {\n\n None => String::new(),\n\n Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),\n\n }\n\n}\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 5, "score": 172351.7279401346 }, { "content": "pub fn get_currency_stats(code: AccountName, symbol: &str) -> GetCurrencyStatsBuilder {\n\n GetCurrencyStatsBuilder {\n\n code,\n\n symbol: symbol.into(),\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\npub struct CurrencyStats {\n\n pub supply: String,\n\n pub max_supply: String,\n\n pub issuer: AccountName,\n\n}\n", "file_path": "crates/eosio_rpc/src/chain/get_currency_stats.rs", "rank": 8, "score": 145159.30513923636 }, { "content": "#[cfg(not(feature = \"contract\"))]\n\npub fn expand(_args: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as ItemFn);\n\n let eosio = crate::paths::eosio();\n\n let ident = input.ident;\n\n let decl = input.decl;\n\n let inputs = decl.inputs;\n\n let vis = input.vis;\n\n let mut struct_fields = quote!();\n\n let mut assign_args = quote!();\n\n for input in inputs.iter() {\n\n match input {\n\n FnArg::Captured(input) => {\n\n let pat = &input.pat;\n\n let ty = &input.ty;\n\n let ty_str = quote!(#ty).to_string();\n\n let serde_attr = if ty_str == \"bool\" {\n\n quote!(\n\n #[cfg_attr(\n\n feature = \"serde\",\n\n serde(\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 9, "score": 145039.43976148858 }, { "content": "#[proc_macro_attribute]\n\npub fn eosio_action(args: TokenStream, input: TokenStream) -> TokenStream {\n\n crate::eosio_action::expand(args, input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 10, "score": 145039.43976148858 }, { "content": "#[proc_macro_attribute]\n\npub fn eosio_table(args: TokenStream, input: TokenStream) -> TokenStream {\n\n crate::eosio_table::expand(args, input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 11, "score": 144588.35162055766 }, { "content": "pub fn expand(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let eosio = crate::paths::eosio();\n\n let name = parse_macro_input!(args as Ident);\n\n let name = LitStr::new(format!(\"{}\", quote!(#name)).as_str(), Span::call_site());\n\n let expanded = quote! {\n\n #[derive(Debug, #eosio::TableRow, #eosio::Read, #eosio::Write, #eosio::NumBytes, Clone, PartialEq, PartialOrd)]\n\n #[table_name = #name]\n\n #input\n\n };\n\n TokenStream::from(expanded)\n\n // input\n\n}\n", "file_path": "crates/eosio_macros_impl/src/eosio_table.rs", "rank": 12, "score": 144588.35162055766 }, { "content": "#[proc_macro_derive(NumBytes)]\n\npub fn derive_num_bytes(input: TokenStream) -> TokenStream {\n\n crate::derive_num_bytes::expand(input)\n\n}\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 14, "score": 138466.9991499835 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let name = input.ident;\n\n\n\n let eosio = crate::paths::eosio();\n\n\n\n let mut generics = input.generics;\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n type_param.bounds.push(parse_quote!(#eosio::NumBytes));\n\n }\n\n }\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n let call_site = ::proc_macro2::Span::call_site();\n\n let var = quote!(self);\n\n let add_to_count = match input.data {\n\n Data::Struct(ref data) => match data.fields {\n\n Fields::Named(ref fields) => {\n", "file_path": "crates/eosio_macros_impl/src/derive_num_bytes.rs", "rank": 15, "score": 138462.98168316597 }, { "content": "#[proc_macro_derive(TableRow, attributes(table_name, primary, secondary))]\n\npub fn derive_table_row(input: TokenStream) -> TokenStream {\n\n crate::derive_table_row::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 16, "score": 138180.38285414316 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn expand(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let eosio = crate::paths::eosio();\n\n\n\n let name = input.ident.clone();\n\n\n\n let mut generics = input.generics.clone();\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n type_param.bounds.push(parse_quote!(#eosio::Read));\n\n }\n\n }\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n let table_name = input.attrs.iter().fold(None, |acc, attr| {\n\n match attr.interpret_meta() {\n\n Some(meta) => {\n\n let name = meta.name();\n\n if name == \"table_name\" {\n\n if acc.is_some() {\n", "file_path": "crates/eosio_macros_impl/src/derive_table_row.rs", "rank": 17, "score": 138175.9865808637 }, { "content": "#[cfg(any(feature = \"std\", feature = \"alloc\"))]\n\npub fn name_to_string(name: u64) -> String {\n\n let mut chars = [b'.'; 13];\n\n let mut t = name;\n\n for i in 0..13 {\n\n let charmap_index = t & if i == 0 { 15 } else { 31 };\n\n let c = NAME_CHARS[charmap_index as usize];\n\n chars[12 - i] = c;\n\n t >>= if i == 0 { 4 } else { 5 };\n\n }\n\n ::std::str::from_utf8(&chars)\n\n .unwrap()\n\n .trim_matches('.')\n\n .to_string()\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum ParseSymbolError {\n\n IsEmpty,\n\n TooLong,\n\n BadChar(char),\n\n}\n\n\n", "file_path": "crates/eosio_sys/src/lib.rs", "rank": 18, "score": 135565.11503657803 }, { "content": "pub fn symbol_name_length(symbol: u64) -> usize {\n\n let mut sym = symbol;\n\n sym >>= 8; // skip precision\n\n let mut len = 0;\n\n while sym & 255 > 0 && len <= 7 {\n\n len += 1;\n\n sym >>= 8;\n\n }\n\n len\n\n}\n", "file_path": "crates/eosio_sys/src/lib.rs", "rank": 19, "score": 133421.43294647636 }, { "content": "#[test]\n\nfn basic_symbol_tests() {\n\n let symbol = Symbol::from(361_956_332_546);\n\n assert_eq!(symbol.precision(), 2);\n\n\n\n let name = symbol.name();\n\n let num: u64 = name.into();\n\n assert_eq!(num, 1_413_891_924);\n\n}\n", "file_path": "crates/eosio/tests/symbol_tests.rs", "rank": 20, "score": 133116.97312348807 }, { "content": "#[cfg(feature = \"contract\")]\n\npub trait ActionFn: ToAction + Read + Write + NumBytes + Clone {\n\n fn execute(self);\n\n\n\n fn read_data() -> Result<(Self, usize), ReadError> {\n\n let num_bytes = unsafe { ::eosio_sys::action_data_size() };\n\n let mut bytes = vec![0u8; num_bytes as usize];\n\n let ptr: *mut ::eosio_sys::c_void = &mut bytes[..] as *mut _ as *mut ::eosio_sys::c_void;\n\n unsafe {\n\n ::eosio_sys::read_action_data(ptr, num_bytes);\n\n }\n\n\n\n Self::read(&bytes, 0)\n\n }\n\n\n\n fn send_inline(self, authorization: Vec<Authorization>) -> Result<(), WriteError> {\n\n self.to_action(AccountName::receiver(), authorization)\n\n .send_inline()\n\n }\n\n}\n", "file_path": "crates/eosio/src/action.rs", "rank": 21, "score": 132881.0899694087 }, { "content": "pub fn string_to_symbol(precision: u8, s: &str) -> Result<u64, ParseSymbolError> {\n\n let mut result: u64 = 0;\n\n for (i, c) in s.chars().enumerate() {\n\n if c < 'A' || c > 'Z' {\n\n return Err(ParseSymbolError::BadChar(c));\n\n } else {\n\n result |= (c as u64) << (8 * (i + 1));\n\n }\n\n }\n\n\n\n result |= u64::from(precision);\n\n Ok(result)\n\n}\n\n\n", "file_path": "crates/eosio_sys/src/lib.rs", "rank": 22, "score": 132323.28618830373 }, { "content": "#[test]\n\nfn test_read_pos() {\n\n let bytes = &[\n\n 10, 9, 0, 1, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 20, 4, 3, 2, 1, 1, 1, 1, 1,\n\n ];\n\n let pos = 0;\n\n\n\n let (_, pos) = u8::read(bytes, pos).unwrap();\n\n assert_eq!(pos, 1);\n\n\n\n let (_, pos) = u8::read(bytes, pos).unwrap();\n\n assert_eq!(pos, 2);\n\n\n\n let (_, pos) = u16::read(bytes, pos).unwrap();\n\n assert_eq!(pos, 4);\n\n\n\n let (_, pos) = u32::read(bytes, pos).unwrap();\n\n assert_eq!(pos, 8);\n\n\n\n let (_, pos) = u64::read(bytes, pos).unwrap();\n\n assert_eq!(pos, 16);\n", "file_path": "crates/eosio/tests/bytes_tests.rs", "rank": 23, "score": 122748.46703149927 }, { "content": "#[test]\n\nfn test_write_pos() {\n\n let bytes = &mut [0u8; 1000];\n\n let pos = 0;\n\n\n\n let pos = 1u8.write(bytes, pos).unwrap();\n\n assert_eq!(pos, 1);\n\n\n\n let pos = 1u16.write(bytes, pos).unwrap();\n\n assert_eq!(pos, 3);\n\n\n\n let pos = 1u32.write(bytes, pos).unwrap();\n\n assert_eq!(pos, 7);\n\n\n\n let pos = 1u64.write(bytes, pos).unwrap();\n\n assert_eq!(pos, 15);\n\n}\n", "file_path": "crates/eosio/tests/bytes_tests.rs", "rank": 24, "score": 122748.46703149927 }, { "content": "#[test]\n\nfn test_struct_unnamed_fields() {\n\n #[derive(Read, Write, PartialEq, Debug)]\n\n struct Thing(u64, u64, u32);\n\n\n\n let thing1 = Thing(1, 2, 3);\n\n\n\n let mut bytes = [0u8; 100];\n\n let p1 = thing1.write(&mut bytes, 0).unwrap();\n\n\n\n let (thing2, p2) = Thing::read(&bytes, 0).unwrap();\n\n\n\n assert_eq!(thing1, thing2);\n\n assert_eq!(p1, p2);\n\n assert_eq!(p1, 20);\n\n assert_eq!(thing1.0, 1);\n\n assert_eq!(thing1.1, 2);\n\n assert_eq!(thing1.2, 3);\n\n}\n\n\n", "file_path": "crates/eosio/tests/bytes_tests.rs", "rank": 25, "score": 120177.13061239422 }, { "content": "#[test]\n\nfn test_struct_named_fields() {\n\n #[derive(Read, Write, PartialEq, Debug)]\n\n struct Thing {\n\n a: u64,\n\n b: u64,\n\n c: u32,\n\n }\n\n\n\n let thing1 = Thing { a: 1, b: 2, c: 3 };\n\n\n\n let mut bytes = [0u8; 100];\n\n let p1 = thing1.write(&mut bytes, 0).unwrap();\n\n\n\n let (thing2, p2) = Thing::read(&bytes, 0).unwrap();\n\n\n\n assert_eq!(thing1, thing2);\n\n assert_eq!(p1, p2);\n\n assert_eq!(p1, 20);\n\n assert_eq!(thing1.a, 1);\n\n assert_eq!(thing1.b, 2);\n\n assert_eq!(thing1.c, 3);\n\n}\n\n\n", "file_path": "crates/eosio/tests/bytes_tests.rs", "rank": 26, "score": 120177.13061239422 }, { "content": "fn chars_from_symbol_value(value: u64) -> [char; 7] {\n\n let mut sym = value;\n\n let ff: u64 = 0xff;\n\n let mut chars = [' '; 7];\n\n for c in chars.iter_mut() {\n\n let b = sym & ff;\n\n if b == 0 {\n\n break;\n\n }\n\n *c = b as u8 as char;\n\n sym >>= 8;\n\n }\n\n chars\n\n}\n\n\n\n#[cfg(feature = \"contract\")]\n\nimpl Print for SymbolName {\n\n fn print(&self) {\n\n let chars: [char; 7] = (*self).into();\n\n for &c in chars.iter() {\n", "file_path": "crates/eosio/src/symbol.rs", "rank": 27, "score": 119151.79358609045 }, { "content": "#[proc_macro]\n\npub fn eosio_name(input: TokenStream) -> TokenStream {\n\n crate::eosio_name::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 28, "score": 118363.89965272976 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let Assert { test, message } = parse_macro_input!(input as Assert);\n\n let eosio = crate::paths::eosio();\n\n let expanded = quote! {\n\n unsafe {\n\n #eosio::eosio_assert(\n\n #test,\n\n #eosio::c!(#message)\n\n )\n\n }\n\n };\n\n TokenStream::from(quote!(#expanded))\n\n}\n", "file_path": "crates/eosio_macros_impl/src/eosio_assert.rs", "rank": 29, "score": 118363.89965272976 }, { "content": "#[proc_macro_hack]\n\npub fn eosio_print(input: TokenStream) -> TokenStream {\n\n crate::eosio_print::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 30, "score": 118363.89965272976 }, { "content": "#[proc_macro]\n\npub fn eosio_abi(input: TokenStream) -> TokenStream {\n\n crate::eosio_abi::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 31, "score": 118363.89965272976 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn expand(input: TokenStream) -> TokenStream {\n\n let pairs = parse_macro_input!(input as AbiPairs);\n\n let eosio = crate::paths::eosio();\n\n let actions = pairs.0.into_iter().map(|pair| {\n\n let code = pair\n\n .code\n\n .map(|code| quote!(#eosio::n!(#code)))\n\n .unwrap_or_else(|| quote!(receiver));\n\n let action = pair.action;\n\n quote! {\n\n else if code == #code && action == #eosio::n!(#action) {\n\n #action();\n\n }\n\n }\n\n });\n\n let expanded = quote! {\n\n #[no_mangle]\n\n pub extern \"C\" fn apply(receiver: u64, code: u64, action: u64) {\n\n if action == #eosio::n!(onerror) {\n\n #eosio::eosio_assert(\n", "file_path": "crates/eosio_macros_impl/src/eosio_abi.rs", "rank": 32, "score": 118363.89965272976 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let parser = Punctuated::<Expr, Token![,]>::parse_separated_nonempty;\n\n let eosio = crate::paths::eosio();\n\n let args = parser.parse(input).unwrap();\n\n let mut prints = quote!();\n\n for i in args.iter() {\n\n prints = quote! {\n\n #prints\n\n #eosio::Print::print(&#i);\n\n };\n\n }\n\n TokenStream::from(quote!(#prints))\n\n}\n", "file_path": "crates/eosio_macros_impl/src/eosio_print.rs", "rank": 33, "score": 118363.89965272976 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn expand(input: TokenStream) -> TokenStream {\n\n let ident = parse_macro_input!(input as Ident);\n\n let eosio = crate::paths::eosio();\n\n let identstr = ident.to_string();\n\n\n\n let scope_name_converters = if identstr == \"ScopeName\" {\n\n quote!()\n\n } else {\n\n quote! {\n\n #[automatically_derived]\n\n impl From<#eosio::ScopeName> for #ident {\n\n fn from(scope: #eosio::ScopeName) -> Self {\n\n let value: u64 = scope.into();\n\n value.into()\n\n }\n\n }\n\n\n\n #[automatically_derived]\n\n impl From<#ident> for #eosio::ScopeName {\n\n fn from(name: #ident) -> Self {\n", "file_path": "crates/eosio_macros_impl/src/eosio_name.rs", "rank": 34, "score": 118363.89965272976 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn eosio_exit<C>(code: C)\n\nwhere\n\n C: Into<i32>,\n\n{\n\n let code: i32 = code.into();\n\n unsafe { ::eosio_sys::eosio_exit(code) }\n\n}\n\n\n\neosio_name!(ActionName);\n\n\n\n#[derive(Clone, Debug)]\n\n#[cfg_attr(feature = \"serde\", derive(::serde::Serialize, ::serde::Deserialize))]\n\npub struct Action<Data> {\n\n pub account: AccountName,\n\n pub name: ActionName,\n\n pub authorization: Vec<Authorization>,\n\n pub data: Data,\n\n}\n\n\n\nimpl<Data> NumBytes for Action<Data>\n", "file_path": "crates/eosio/src/action.rs", "rank": 35, "score": 116338.34471036679 }, { "content": "pub fn get_table_rows<Row>(\n\n code: AccountName,\n\n scope: ScopeName,\n\n table: TableName,\n\n) -> GetTableRowsBuilder<Row>\n\nwhere\n\n Row: for<'a> Deserialize<'a> + 'static,\n\n{\n\n GetTableRowsBuilder {\n\n _data: PhantomData,\n\n code,\n\n scope,\n\n table,\n\n json: true,\n\n lower_bound: None,\n\n upper_bound: None,\n\n limit: None,\n\n }\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug, Clone, Default)]\n\npub struct GetTableRows<Row> {\n\n pub rows: Vec<Row>,\n\n pub more: bool,\n\n}\n", "file_path": "crates/eosio_rpc/src/chain/get_table_rows.rs", "rank": 36, "score": 115732.25952063837 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let SymbolInput { precision, name } = parse_macro_input!(input as SymbolInput);\n\n let symbol_result = string_to_symbol(precision.value() as u8, &name.to_string());\n\n\n\n let expanded = match symbol_result {\n\n Ok(symbol) => quote!(#symbol),\n\n Err(error) => {\n\n let span = Span::call_site();\n\n let err = match error {\n\n ParseSymbolError::IsEmpty => span\n\n .error(\"symbol is empty\")\n\n .help(\"EOSIO symbols must be 1-12 characters long\"),\n\n ParseSymbolError::TooLong => span\n\n .error(\"name is too long\")\n\n .help(\"EOSIO symbols must be 1-12 characters long\"),\n\n ParseSymbolError::BadChar(c) => {\n\n let error_message = format!(\"name has bad character '{}'\", c);\n\n let help_message = \"EOSIO symbols can only contain uppercase letters A-Z\";\n\n span.error(error_message).help(help_message)\n\n }\n\n };\n\n err.emit();\n\n quote!(0)\n\n }\n\n };\n\n\n\n TokenStream::from(quote!(#expanded))\n\n}\n", "file_path": "crates/eosio_macros_impl/src/s.rs", "rank": 37, "score": 114391.77191060154 }, { "content": "#[proc_macro_hack]\n\npub fn n(input: TokenStream) -> TokenStream {\n\n crate::n::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 38, "score": 114391.77191060154 }, { "content": "#[proc_macro_hack]\n\npub fn s(input: TokenStream) -> TokenStream {\n\n crate::s::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 39, "score": 114391.77191060154 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let name = parse_macro_input!(input as EosioName);\n\n quote!(#name).into()\n\n}\n", "file_path": "crates/eosio_macros_impl/src/n.rs", "rank": 40, "score": 114391.77191060154 }, { "content": "#[proc_macro_derive(Write)]\n\npub fn derive_write(input: TokenStream) -> TokenStream {\n\n crate::derive_write::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 41, "score": 110455.93974504608 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n\n\n let name = input.ident;\n\n\n\n let eosio = crate::paths::eosio();\n\n\n\n let mut generics = input.generics;\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n type_param.bounds.push(parse_quote!(#eosio));\n\n }\n\n }\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n let call_site = ::proc_macro2::Span::call_site();\n\n let reads = match input.data {\n\n Data::Struct(ref data) => match data.fields {\n\n Fields::Named(ref fields) => {\n\n let field_reads = fields.named.iter().map(|f| {\n", "file_path": "crates/eosio_macros_impl/src/derive_read.rs", "rank": 42, "score": 110455.93974504607 }, { "content": "#[proc_macro_derive(Read)]\n\npub fn derive_read(input: TokenStream) -> TokenStream {\n\n crate::derive_read::expand(input)\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/lib.rs", "rank": 43, "score": 110455.93974504607 }, { "content": "pub fn expand(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n let eosio = crate::paths::eosio();\n\n\n\n let name = input.ident;\n\n\n\n let mut generics = input.generics;\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n type_param.bounds.push(parse_quote!(#eosio::Write));\n\n }\n\n }\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n let call_site = ::proc_macro2::Span::call_site();\n\n let var = quote!(self);\n\n let writes = match input.data {\n\n Data::Struct(ref data) => match data.fields {\n\n Fields::Named(ref fields) => {\n\n let recurse = fields.named.iter().map(|f| {\n", "file_path": "crates/eosio_macros_impl/src/derive_write.rs", "rank": 44, "score": 110455.93974504608 }, { "content": "fn char_to_symbol(c: char) -> Option<char> {\n\n if c >= 'a' && c <= 'z' {\n\n ::std::char::from_u32((c as u32 - 'a' as u32) + 6)\n\n } else if c >= '1' && c <= '5' {\n\n ::std::char::from_u32((c as u32 - '1' as u32) + 1)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub enum ParseNameError {\n\n IsEmpty,\n\n TooLong,\n\n BadChar(char),\n\n}\n\n\n\nimpl ::std::fmt::Display for ParseNameError {\n\n fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {\n\n match *self {\n\n ParseNameError::IsEmpty => write!(f, \"empty string is not a valid EOSIO name\"),\n\n ParseNameError::TooLong => write!(f, \"name is too long, must be 12 chars or less\"),\n\n ParseNameError::BadChar(c) => write!(f, \"name contains invalid character '{}'\", c),\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/eosio_sys/src/lib.rs", "rank": 45, "score": 108740.47823929801 }, { "content": " class token : public contract {\n\n public:\n\n token( account_name self ):contract(self){}\n\n\n\n void create( account_name issuer,\n\n asset maximum_supply);\n\n\n\n void issue( account_name to, asset quantity, string memo );\n\n\n\n void retire( asset quantity, string memo );\n\n\n\n void transfer( account_name from,\n\n account_name to,\n\n asset quantity,\n\n string memo );\n\n\n\n void open( account_name owner, symbol_type symbol, account_name payer );\n\n\n\n void close( account_name owner, symbol_type symbol );\n\n\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 46, "score": 105313.38260219074 }, { "content": "#[cfg(feature = \"contract\")]\n\npub trait TableCursor<T>: IntoIterator\n\nwhere\n\n T: TableRow,\n\n{\n\n fn get(&self) -> Result<T, ReadError>;\n\n fn erase(&self) -> Result<T, ReadError>;\n\n fn modify(&self, payer: Option<AccountName>, item: &T) -> Result<usize, WriteError>;\n\n}\n\n\n\n/// Table index\n", "file_path": "crates/eosio/src/table.rs", "rank": 47, "score": 104906.2452133184 }, { "content": "#[cfg(not(feature = \"contract\"))]\n\npub trait TableRow: NumBytes {\n\n const TABLE_NAME: u64;\n\n\n\n fn primary_key(&self) -> u64;\n\n}\n\n\n", "file_path": "crates/eosio/src/table.rs", "rank": 48, "score": 104537.60339123462 }, { "content": "#[cfg(feature = \"contract\")]\n\npub trait TableRow: Read + Write + NumBytes {\n\n const TABLE_NAME: u64;\n\n\n\n fn primary_key(&self) -> u64;\n\n\n\n fn secondary_keys(&self) -> [Option<&crate::table_secondary::SecondaryTableKey>; 16] {\n\n [None; 16]\n\n }\n\n\n\n fn table<C, S>(code: C, scope: S) -> crate::table_primary::PrimaryTableIndex<Self>\n\n where\n\n C: Into<AccountName>,\n\n S: Into<ScopeName>,\n\n {\n\n crate::table_primary::PrimaryTableIndex::new(code, scope, Self::TABLE_NAME)\n\n }\n\n}\n\n\n\n/// Table Cursor\n", "file_path": "crates/eosio/src/table.rs", "rank": 49, "score": 100032.84857212154 }, { "content": "pub fn string_to_name(s: &str) -> Result<u64, ParseNameError> {\n\n if s.is_empty() {\n\n return Err(ParseNameError::IsEmpty);\n\n }\n\n\n\n if s.len() > 12 {\n\n return Err(ParseNameError::TooLong);\n\n }\n\n\n\n let mut value = 0;\n\n\n\n for (i, c) in s.chars().enumerate() {\n\n if c == '.' {\n\n continue;\n\n }\n\n match char_to_symbol(c) {\n\n Some(symbol) => {\n\n let mut n = symbol as u64;\n\n if i < 12 {\n\n n &= 31u64;\n", "file_path": "crates/eosio_sys/src/lib.rs", "rank": 50, "score": 97629.39765741197 }, { "content": "/// Aborts processing of this action and unwinds all pending changes if the test condition is true\n\npub fn eosio_assert(test: bool, msg: &str) {\n\n #[cfg(feature = \"contract\")]\n\n {\n\n let test = if test { 1 } else { 0 };\n\n let msg_ptr = msg.as_ptr();\n\n let msg_len = msg.len() as u32;\n\n unsafe { ::eosio_sys::eosio_assert_message(test, msg_ptr, msg_len) }\n\n }\n\n}\n\n\n", "file_path": "crates/eosio/src/assert.rs", "rank": 51, "score": 96790.38463022756 }, { "content": "pub fn u64_from_string<'de, D>(deserializer: D) -> Result<u64, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s: String = Deserialize::deserialize(deserializer)?;\n\n s.parse().map_err(de::Error::custom)\n\n}\n", "file_path": "crates/eosio/src/json.rs", "rank": 52, "score": 93108.77586983793 }, { "content": "pub fn f64_from_string<'de, D>(deserializer: D) -> Result<f64, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let s: String = Deserialize::deserialize(deserializer)?;\n\n s.parse().map_err(de::Error::custom)\n\n}\n\n\n", "file_path": "crates/eosio/src/json.rs", "rank": 53, "score": 93108.77586983793 }, { "content": "#[test]\n\nfn test_n() {\n\n assert_eq!(n!(test), 14_605_613_396_213_628_928u64);\n\n assert_eq!(n!(1234), 614_248_767_926_829_056u64);\n\n assert_eq!(n!(123451234512), 614_251_535_012_020_768u64);\n\n assert_eq!(n!(eosio.token), 6_138_663_591_592_764_928u64);\n\n}\n\n\n", "file_path": "crates/eosio_macros/tests/tests.rs", "rank": 54, "score": 90736.8902686047 }, { "content": "#[test]\n\nfn test_s() {\n\n assert_eq!(s!(0, TGFT), 361_956_332_544);\n\n assert_eq!(s!(4, EOS), 1_397_703_940);\n\n assert_eq!(s!(0, EOS), 1_397_703_936);\n\n assert_eq!(s!(1, EDNA), 280_485_971_201);\n\n}\n", "file_path": "crates/eosio_macros/tests/tests.rs", "rank": 55, "score": 90736.8902686047 }, { "content": "#[test]\n\nfn test_constructors() {\n\n assert_eq!(Time::zero().microseconds(), 0);\n\n assert_eq!(Time::from_microseconds(1).microseconds(), 1);\n\n assert_eq!(Time::from_milliseconds(1).microseconds(), 1_000);\n\n assert_eq!(Time::from_seconds(1).microseconds(), 1_000_000);\n\n assert_eq!(Time::from_minutes(1).microseconds(), 60_000_000);\n\n assert_eq!(Time::from_hours(1).microseconds(), 3_600_000_000);\n\n assert_eq!(Time::from_days(1).microseconds(), 86_400_000_000);\n\n}\n\n\n", "file_path": "crates/eosio/tests/time_tests.rs", "rank": 56, "score": 88918.28516006905 }, { "content": "#[test]\n\nfn test_converters() {\n\n assert_eq!(Time::from_milliseconds(1).microseconds(), 1_000);\n\n assert_eq!(Time::from_seconds(1).milliseconds(), 1_000);\n\n assert_eq!(Time::from_minutes(1).seconds(), 60);\n\n assert_eq!(Time::from_hours(1).minutes(), 60);\n\n assert_eq!(Time::from_days(1).hours(), 24);\n\n}\n\n\n", "file_path": "crates/eosio/tests/time_tests.rs", "rank": 57, "score": 88918.28516006905 }, { "content": "#[test]\n\nfn test_min_max() {\n\n let t1 = Time::from_seconds(1);\n\n let t2 = Time::from_seconds(2);\n\n let t3 = Time::from_seconds(3);\n\n assert_eq!(t1.max(t2), t2);\n\n assert_eq!(t1.min(t2), t1);\n\n assert_eq!(t3.max(t2), t3);\n\n assert_eq!(t3.min(t2), t2);\n\n}\n", "file_path": "crates/eosio/tests/time_tests.rs", "rank": 58, "score": 87198.79952763228 }, { "content": "#[eosio_action]\n\nfn create(challenger: AccountName, host: AccountName) {\n\n require_auth(host);\n\n eosio_assert(\n\n challenger != host,\n\n \"challenger shouldn't be the same as host\",\n\n );\n\n\n\n let _self = AccountName::receiver();\n\n let table = Game::table(_self, host);\n\n\n\n eosio_assert(!table.exists(challenger), \"game already exists\");\n\n\n\n let game = Game {\n\n challenger,\n\n host,\n\n turn: host,\n\n winner: n!(none).into(),\n\n board: [0; BOARD_AREA],\n\n };\n\n\n\n table.emplace(host, &game).assert(\"write\");\n\n}\n\n\n", "file_path": "examples/tictactoe/src/lib.rs", "rank": 59, "score": 82270.42680761067 }, { "content": " eosio_assert(existing != statstable.end(), \"token with symbol does not exist, create token before issue\");\n\n const auto &st = *existing;\n\n\n\n require_auth(st.issuer);\n\n eosio_assert(quantity.is_valid(), \"invalid quantity\");\n\n eosio_assert(quantity.amount > 0, \"must issue positive quantity\");\n\n\n\n eosio_assert(quantity.symbol == st.supply.symbol, \"symbol precision mismatch\");\n\n eosio_assert(quantity.amount <= st.max_supply.amount - st.supply.amount, \"quantity exceeds available supply\");\n\n\n\n statstable.update(st, 0, [&](auto &s) {\n\n s.supply += quantity;\n\n });\n\n\n\n add_balance(st.issuer, quantity, st.issuer);\n\n\n\n if (to != st.issuer)\n\n {\n\n SEND_INLINE_ACTION(*this, transfer, {st.issuer, N(active)}, {st.issuer, to, quantity, memo});\n\n }\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 60, "score": 82011.21894485851 }, { "content": "}\n\n\n\nvoid token::retire(asset quantity, string memo)\n\n{\n\n auto sym = quantity.symbol;\n\n eosio_assert(sym.is_valid(), \"invalid symbol name\");\n\n eosio_assert(memo.size() <= 256, \"memo has more than 256 bytes\");\n\n\n\n auto sym_name = sym.name();\n\n stats statstable(_self, sym_name);\n\n auto existing = statstable.find(sym_name);\n\n eosio_assert(existing != statstable.end(), \"token with symbol does not exist\");\n\n const auto &st = *existing;\n\n\n\n require_auth(st.issuer);\n\n eosio_assert(quantity.is_valid(), \"invalid quantity\");\n\n eosio_assert(quantity.amount > 0, \"must retire positive quantity\");\n\n\n\n eosio_assert(quantity.symbol == st.supply.symbol, \"symbol precision mismatch\");\n\n\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 61, "score": 82005.2497231533 }, { "content": " stats statstable(_self, sym.name());\n\n auto existing = statstable.find(sym.name());\n\n eosio_assert(existing == statstable.end(), \"token with symbol already exists\");\n\n\n\n statstable.insert(_self, [&](auto &s) {\n\n s.supply.symbol = maximum_supply.symbol;\n\n s.max_supply = maximum_supply;\n\n s.issuer = issuer;\n\n });\n\n}\n\n\n\nvoid token::issue(account_name to, asset quantity, string memo)\n\n{\n\n auto sym = quantity.symbol;\n\n eosio_assert(sym.is_valid(), \"invalid symbol name\");\n\n eosio_assert(memo.size() <= 256, \"memo has more than 256 bytes\");\n\n\n\n auto sym_name = sym.name();\n\n stats statstable(_self, sym_name);\n\n auto existing = statstable.find(sym_name);\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 62, "score": 82000.70238917474 }, { "content": " require_recipient(to);\n\n\n\n eosio_assert(quantity.is_valid(), \"invalid quantity\");\n\n eosio_assert(quantity.amount > 0, \"must transfer positive quantity\");\n\n eosio_assert(quantity.symbol == st.supply.symbol, \"symbol precision mismatch\");\n\n eosio_assert(memo.size() <= 256, \"memo has more than 256 bytes\");\n\n\n\n auto payer = has_auth(to) ? to : from;\n\n\n\n sub_balance(from, quantity);\n\n add_balance(to, quantity, payer);\n\n}\n\n\n\nvoid token::sub_balance(account_name owner, asset value)\n\n{\n\n accounts from_acnts(_self, owner);\n\n\n\n const auto &from = from_acnts.get(value.symbol.name(), \"no balance object found\");\n\n eosio_assert(from.balance.amount >= value.amount, \"overdrawn balance\");\n\n\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 63, "score": 81996.73672313019 }, { "content": " statstable.update(st, 0, [&](auto &s) {\n\n s.supply -= quantity;\n\n });\n\n\n\n sub_balance(st.issuer, quantity);\n\n}\n\n\n\nvoid token::transfer(account_name from,\n\n account_name to,\n\n asset quantity,\n\n string memo)\n\n{\n\n eosio_assert(from != to, \"cannot transfer to self\");\n\n require_auth(from);\n\n eosio_assert(is_account(to), \"to account does not exist\");\n\n auto sym = quantity.symbol.name();\n\n stats statstable(_self, sym);\n\n const auto &st = statstable.get(sym);\n\n\n\n require_recipient(from);\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 64, "score": 81995.3096693566 }, { "content": "/**\n\n * @file\n\n * @copyright defined in eos/LICENSE.txt\n\n */\n\n\n\n#include <eosio.token/eosio.token.hpp>\n\n\n\nnamespace eosio\n\n{\n\n\n\nvoid token::create(account_name issuer,\n\n asset maximum_supply)\n\n{\n\n require_auth(_self);\n\n\n\n auto sym = maximum_supply.symbol;\n\n eosio_assert(sym.is_valid(), \"invalid symbol name\");\n\n eosio_assert(maximum_supply.is_valid(), \"invalid supply\");\n\n eosio_assert(maximum_supply.amount > 0, \"max-supply must be positive\");\n\n\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 65, "score": 81993.22189725749 }, { "content": " typedef eosio::multi_index<N(stat), currency_stats> stats;\n\n\n\n void sub_balance( account_name owner, asset value );\n\n void add_balance( account_name owner, asset value, account_name ram_payer );\n\n\n\n public:\n\n struct transfer_args {\n\n account_name from;\n\n account_name to;\n\n asset quantity;\n\n string memo;\n\n };\n\n };\n\n\n\n asset token::get_supply( symbol_name sym )const\n\n {\n\n stats statstable( _self, sym );\n\n const auto& st = statstable.get( sym );\n\n return st.supply;\n\n }\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 66, "score": 81991.08670016253 }, { "content": " auto it = acnts.find(symbol.name());\n\n eosio_assert(it != acnts.end(), \"Balance row already deleted or never existed. Action won't have any effect.\");\n\n eosio_assert(it->balance.amount == 0, \"Cannot close because the balance is not zero.\");\n\n acnts.erase(it);\n\n}\n\n\n\n} // namespace eosio\n\n\n\nEOSIO_ABI(eosio::token, (create)(issue)(transfer)(open)(close)(retire))\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 67, "score": 81989.48766347118 }, { "content": " inline asset get_supply( symbol_name sym )const;\n\n\n\n inline asset get_balance( account_name owner, symbol_name sym )const;\n\n\n\n private:\n\n struct account {\n\n asset balance;\n\n\n\n uint64_t primary_key()const { return balance.symbol.name(); }\n\n };\n\n\n\n struct currency_stats {\n\n asset supply;\n\n asset max_supply;\n\n account_name issuer;\n\n\n\n uint64_t primary_key()const { return supply.symbol.name(); }\n\n };\n\n\n\n typedef eosio::multi_index<N(accounts), account> accounts;\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 68, "score": 81985.14606100768 }, { "content": "\n\n asset token::get_balance( account_name owner, symbol_name sym )const\n\n {\n\n accounts accountstable( _self, owner );\n\n const auto& ac = accountstable.get( sym );\n\n return ac.balance;\n\n }\n\n\n\n} /// namespace eosio\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 69, "score": 81978.33060574484 }, { "content": " }\n\n}\n\n\n\nvoid token::open(account_name owner, symbol_type symbol, account_name ram_payer)\n\n{\n\n require_auth(ram_payer);\n\n accounts acnts(_self, owner);\n\n auto it = acnts.find(symbol.name());\n\n if (it == acnts.end())\n\n {\n\n acnts.insert(ram_payer, [&](auto &a) {\n\n a.balance = asset{0, symbol};\n\n });\n\n }\n\n}\n\n\n\nvoid token::close(account_name owner, symbol_type symbol)\n\n{\n\n require_auth(owner);\n\n accounts acnts(_self, owner);\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 70, "score": 81976.4854675053 }, { "content": "/**\n\n * @file\n\n * @copyright defined in eos/LICENSE.txt\n\n */\n\n#pragma once\n\n\n\n#include <eosiolib/asset.hpp>\n\n#include <eosiolib/eosio.hpp>\n\n\n\n#include <string>\n\n\n\nnamespace eosiosystem {\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 71, "score": 81976.06864507314 }, { "content": " from_acnts.update(from, owner, [&](auto &a) {\n\n a.balance -= value;\n\n });\n\n}\n\n\n\nvoid token::add_balance(account_name owner, asset value, account_name ram_payer)\n\n{\n\n accounts to_acnts(_self, owner);\n\n auto to = to_acnts.find(value.symbol.name());\n\n if (to == to_acnts.end())\n\n {\n\n to_acnts.insert(ram_payer, [&](auto &a) {\n\n a.balance = value;\n\n });\n\n }\n\n else\n\n {\n\n to_acnts.update(to, 0, [&](auto &a) {\n\n a.balance += value;\n\n });\n", "file_path": "crates/eosio_token/cpp/eosio.token.cpp", "rank": 72, "score": 81973.60313642003 }, { "content": " class system_contract;\n\n}\n\n\n\nnamespace eosio {\n\n\n\n using std::string;\n\n\n", "file_path": "crates/eosio_token/cpp/eosio.token.hpp", "rank": 73, "score": 79102.68608613135 }, { "content": "pub fn get_currency_balance(\n\n code: AccountName,\n\n account: AccountName,\n\n symbol: &str,\n\n) -> GetCurrencyBalanceBuilder {\n\n GetCurrencyBalanceBuilder {\n\n code,\n\n account,\n\n symbol: symbol.to_string(),\n\n }\n\n}\n\n\n\npub type GetCurrencyBalance = Vec<String>;\n", "file_path": "crates/eosio_rpc/src/chain/get_currency_balance.rs", "rank": 74, "score": 78007.44112280272 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"eosio\"] = [];\n\n\n\n if (window.register_implementors) {\n\n window.register_implementors(implementors);\n\n } else {\n\n window.pending_implementors = implementors;\n\n }\n\n \n\n})()\n", "file_path": "docs/implementors/eosio/trait.TableCursor.js", "rank": 75, "score": 76532.91413024777 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn require_recipient(account: AccountName) {\n\n unsafe { ::eosio_sys::require_recipient(account.0) }\n\n}\n", "file_path": "crates/eosio/src/account.rs", "rank": 76, "score": 76413.47166318784 }, { "content": "#[cfg(feature = \"contract\")]\n\npub fn require_auth(account: AccountName) {\n\n unsafe { ::eosio_sys::require_auth(account.0) }\n\n}\n\n\n\n/// Verifies that `name` exists in the set of provided auths on a action. Throws if not found.\n", "file_path": "crates/eosio/src/account.rs", "rank": 77, "score": 76413.47166318784 }, { "content": "/// Aborts processing of this action and unwinds all pending changes if the test condition is true\n\npub fn eosio_assert_code<C>(test: bool, code: C)\n\nwhere\n\n C: Into<u64>,\n\n{\n\n let test = if test { 1 } else { 0 };\n\n let code: u64 = code.into();\n\n unsafe { ::eosio_sys::eosio_assert_code(test, code) }\n\n}\n\n\n", "file_path": "crates/eosio/src/assert.rs", "rank": 78, "score": 75939.67757806048 }, { "content": "fn accept_char_in_name(ch: char) -> bool {\n\n ch >= 'a' && ch <= 'z' || ch >= '1' && ch <= '5' || ch == '.'\n\n}\n\n\n\nimpl Parse for EosioName {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let mut username = String::new();\n\n while !input.is_empty() {\n\n let segment = input.fork().parse::<TokenTree>()?.to_string();\n\n if !segment.chars().all(accept_char_in_name) {\n\n break;\n\n }\n\n input.parse::<TokenTree>()?;\n\n username += &segment;\n\n }\n\n\n\n string_to_name(username.as_str())\n\n .map(EosioName)\n\n .map_err(|e| {\n\n let message = match e {\n", "file_path": "crates/eosio_macros_impl/src/n.rs", "rank": 79, "score": 74947.1725817662 }, { "content": "pub fn get_info() -> GetInfoBuilder {\n\n GetInfoBuilder {}\n\n}\n\n\n\npub type ChainId = String;\n\n\n\npub type BlockId = String;\n\n\n\npub type BlockNum = u32;\n\n\n\npub type ServerVersion = String;\n\n\n\npub type BlockTimestamp = String;\n\n\n\n#[derive(Deserialize, Serialize, Debug)]\n\npub struct GetInfo {\n\n pub server_version: ServerVersion,\n\n pub server_version_string: String,\n\n pub chain_id: ChainId,\n\n pub head_block_num: BlockNum,\n", "file_path": "crates/eosio_rpc/src/chain/get_info.rs", "rank": 80, "score": 74210.0846417858 }, { "content": "pub trait ToAction: Sized {\n\n const NAME: u64;\n\n\n\n fn to_action(self, account: AccountName, authorization: Vec<Authorization>) -> Action<Self> {\n\n Action {\n\n account,\n\n name: Self::NAME.into(),\n\n authorization,\n\n data: self,\n\n }\n\n }\n\n}\n\n\n", "file_path": "crates/eosio/src/action.rs", "rank": 81, "score": 73674.42168553828 }, { "content": "pub trait NumBytes {\n\n fn num_bytes(&self) -> usize;\n\n}\n\n\n\nmacro_rules! impl_num {\n\n ($($t:ty, $s:expr)*) => ($(\n\n impl Read for $t {\n\n fn read(bytes: &[u8], pos: usize) -> Result<(Self, usize), ReadError> {\n\n let width: usize = $s;\n\n let end_pos = pos + width;\n\n if bytes.len() < end_pos {\n\n return Err(ReadError::NotEnoughBytes);\n\n }\n\n\n\n let mut num = <$t as From<u8>>::from(0 as u8);\n\n for i in 0..width {\n\n match bytes.get(pos + i) {\n\n Some(b) => {\n\n let shift = <$t as From<u8>>::from(i as u8) * <$t as From<u8>>::from(8u8);\n\n num |= <$t as From<u8>>::from(*b) << shift;\n", "file_path": "crates/eosio/src/bytes.rs", "rank": 82, "score": 73387.3059915627 }, { "content": "use crate::proc_macro::TokenStream;\n\nuse quote::quote;\n\nuse syn::{parse_macro_input, FnArg, Ident, ItemFn};\n\n\n\n#[cfg(feature = \"contract\")]\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 83, "score": 71047.8579119887 }, { "content": " let struct_ident = Ident::new(format!(\"{}Action\", struct_name).as_str(), call_site);\n\n\n\n let expanded = quote! {\n\n #[derive(Clone, #eosio::Read, #eosio::Write, #eosio::NumBytes, Default)]\n\n #[cfg_attr(feature = \"serde\", derive(::serde::Serialize, ::serde::Deserialize))]\n\n pub struct #struct_ident {\n\n #(#struct_fields)*\n\n }\n\n\n\n #[automatically_derived]\n\n impl #eosio::ToAction for #struct_ident {\n\n const NAME: u64 = n!(#ident);\n\n }\n\n\n\n #vis fn #ident() { }\n\n };\n\n TokenStream::from(quote!(#expanded))\n\n // input\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 84, "score": 71047.23094967243 }, { "content": " impl #eosio::ActionFn for #struct_ident {\n\n fn execute(self) {\n\n #(#assign_args)*\n\n #block\n\n }\n\n }\n\n\n\n // TODO: keep original function intact so it can be called like normal\n\n #vis fn #ident() {\n\n let (s, _) = #struct_ident::read_data().assert(\"read\");\n\n s.execute();\n\n }\n\n };\n\n TokenStream::from(quote!(#expanded))\n\n // input\n\n}\n\n\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 85, "score": 71046.51363420663 }, { "content": " }\n\n let block = input.block;\n\n\n\n let call_site = ::proc_macro2::Span::call_site();\n\n let struct_name = titlecase(ident.to_string().as_str());\n\n let struct_ident = Ident::new(format!(\"{}Action\", struct_name).as_str(), call_site);\n\n\n\n let expanded = quote! {\n\n #[derive(Clone, #eosio::Read, #eosio::Write, #eosio::NumBytes)]\n\n #[cfg_attr(feature = \"serde\", derive(::serde::Serialize, ::serde::Deserialize))]\n\n pub struct #struct_ident {\n\n #(#struct_fields)*\n\n }\n\n\n\n #[automatically_derived]\n\n impl #eosio::ToAction for #struct_ident {\n\n const NAME: u64 = n!(#ident);\n\n }\n\n\n\n #[automatically_derived]\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 86, "score": 71046.42699700502 }, { "content": " deserialize_with = \"::eosio::json::bool_from_u8\",\n\n serialize_with = \"::eosio::json::bool_to_u8\"\n\n )\n\n )]\n\n )\n\n } else {\n\n quote!()\n\n };\n\n struct_fields = quote! {\n\n #struct_fields\n\n #serde_attr\n\n pub #pat: #ty,\n\n };\n\n }\n\n _ => unimplemented!(),\n\n }\n\n }\n\n\n\n let call_site = ::proc_macro2::Span::call_site();\n\n let struct_name = titlecase(ident.to_string().as_str());\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 87, "score": 71042.39878478508 }, { "content": " deserialize_with = \"::eosio::json::bool_from_u8\",\n\n serialize_with = \"::eosio::json::bool_to_u8\"\n\n )\n\n )]\n\n )\n\n } else {\n\n quote!()\n\n };\n\n struct_fields = quote! {\n\n #struct_fields\n\n #serde_attr\n\n pub #pat: #ty,\n\n };\n\n assign_args = quote! {\n\n #assign_args\n\n let #pat = self.#pat;\n\n };\n\n }\n\n _ => unimplemented!(),\n\n }\n", "file_path": "crates/eosio_macros_impl/src/eosio_action.rs", "rank": 88, "score": 71040.14567093455 }, { "content": "use crate::proc_macro::TokenStream;\n\nuse proc_macro2::{Ident, Span};\n\nuse quote::quote;\n\nuse syn::{parse_macro_input, DeriveInput, LitStr};\n\n\n", "file_path": "crates/eosio_macros_impl/src/eosio_table.rs", "rank": 89, "score": 70466.661255385 }, { "content": "#[cfg(feature = \"contract\")]\n\npub trait TableIndex<'a, K, T>\n\nwhere\n\n T: TableRow + 'a,\n\n{\n\n type Cursor: TableCursor<T> + 'a;\n\n fn lower_bound<N>(&'a self, key: N) -> Option<Self::Cursor>\n\n where\n\n N: Into<K>;\n\n fn upper_bound<N>(&'a self, key: N) -> Option<Self::Cursor>\n\n where\n\n N: Into<K>;\n\n fn emplace(&'a self, payer: AccountName, item: &'a T) -> Result<(), WriteError>;\n\n}\n\n\n\n/// Table iterator\n", "file_path": "crates/eosio/src/table.rs", "rank": 90, "score": 69931.01765686819 }, { "content": "pub trait SecondaryTableKey {\n\n fn end(&self, code: AccountName, scope: ScopeName, table: SecondaryTableName) -> i32;\n\n\n\n fn next(&self, iterator: i32) -> (i32, u64);\n\n\n\n fn erase(&self, iterator: i32);\n\n\n\n fn previous(&self, iterator: i32) -> (i32, u64);\n\n\n\n fn store(\n\n &self,\n\n scope: ScopeName,\n\n table: SecondaryTableName,\n\n payer: AccountName,\n\n id: u64,\n\n ) -> i32;\n\n\n\n fn modify(&self, iterator: i32, payer: AccountName);\n\n\n\n fn lower_bound(\n", "file_path": "crates/eosio/src/table_secondary.rs", "rank": 91, "score": 69931.01765686819 }, { "content": "use crate::account::AccountName;\n\nuse crate::print::Print;\n\nuse eosio_macros::*;\n\n\n\n#[derive(\n\n Debug, PartialEq, Eq, Clone, Copy, Default, Read, Write, NumBytes, Hash, PartialOrd, Ord,\n\n)]\n\npub struct SymbolName(u64);\n\n\n\nimpl From<u64> for SymbolName {\n\n fn from(n: u64) -> Self {\n\n SymbolName(n)\n\n }\n\n}\n\n\n\nimpl From<SymbolName> for u64 {\n\n fn from(s: SymbolName) -> Self {\n\n s.0\n\n }\n\n}\n", "file_path": "crates/eosio/src/symbol.rs", "rank": 92, "score": 69664.32014348611 }, { "content": "\n\nimpl From<SymbolName> for [char; 7] {\n\n fn from(s: SymbolName) -> Self {\n\n chars_from_symbol_value(s.0)\n\n }\n\n}\n\n\n\nimpl ToString for SymbolName {\n\n fn to_string(&self) -> String {\n\n let chars: [char; 7] = (*self).into();\n\n let s: String = chars.iter().collect();\n\n s.trim().to_string()\n\n }\n\n}\n\n\n\nimpl SymbolName {\n\n pub fn is_valid(self) -> bool {\n\n let chars = chars_from_symbol_value(self.0);\n\n for &c in chars.iter() {\n\n if !('A' <= c && c <= 'Z') {\n\n return false;\n\n }\n\n }\n\n true\n\n }\n\n}\n\n\n", "file_path": "crates/eosio/src/symbol.rs", "rank": 93, "score": 69661.84968569253 }, { "content": " }\n\n pub fn name_length(self) -> usize {\n\n ::eosio_sys::symbol_name_length(self.0)\n\n }\n\n pub fn value(self) -> u64 {\n\n self.0\n\n }\n\n pub fn is_valid(self) -> bool {\n\n self.name().is_valid()\n\n }\n\n}\n\n\n\nimpl From<u64> for Symbol {\n\n fn from(n: u64) -> Self {\n\n Symbol(n)\n\n }\n\n}\n\n\n\n#[cfg(feature = \"contract\")]\n\nimpl Print for Symbol {\n", "file_path": "crates/eosio/src/symbol.rs", "rank": 94, "score": 69659.57578436994 }, { "content": " fn print(&self) {\n\n self.precision().print();\n\n ','.print();\n\n self.name().print();\n\n }\n\n}\n\n\n\nimpl PartialEq<u64> for Symbol {\n\n fn eq(&self, other: &u64) -> bool {\n\n self.value() == *other\n\n }\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy, Default, Read, Write, NumBytes)]\n\npub struct ExtendedSymbol {\n\n pub symbol: Symbol,\n\n pub contract: AccountName,\n\n}\n\n\n\n#[cfg(feature = \"contract\")]\n\nimpl Print for ExtendedSymbol {\n\n fn print(&self) {\n\n self.symbol.print();\n\n '@'.print();\n\n self.contract.print();\n\n }\n\n}\n", "file_path": "crates/eosio/src/symbol.rs", "rank": 95, "score": 69659.08117092245 }, { "content": "use crate::account::AccountName;\n\nuse crate::assert::*;\n\nuse crate::lib::*;\n\nuse crate::symbol::Symbol;\n\nuse eosio_macros::*;\n\n\n\n#[derive(Debug, PartialEq, Clone, Copy, Default, Read, Write, NumBytes)]\n\n#[cfg_attr(feature = \"serde\", derive(::serde::Deserialize))]\n\npub struct Asset {\n\n pub amount: i64,\n\n pub symbol: Symbol,\n\n}\n\n\n\nimpl Asset {\n\n pub fn is_valid(&self) -> bool {\n\n self.symbol.is_valid()\n\n }\n\n}\n\n\n\nimpl ToString for Asset {\n", "file_path": "crates/eosio/src/asset.rs", "rank": 99, "score": 18.915011637185966 } ]
Rust
src/lib.rs
Rufflewind/tokio-file-unix
3937ab35a53a34bb78e20e0e9f3483043fb5b231
use std::cell::RefCell; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::{fs, io}; use tokio::io::PollEvented; unsafe fn dupe_file_from_fd(old_fd: RawFd) -> io::Result<fs::File> { let fd = libc::fcntl(old_fd, libc::F_DUPFD_CLOEXEC, 0); if fd < 0 { return Err(io::Error::last_os_error()); } Ok(fs::File::from_raw_fd(fd)) } pub fn raw_stdin() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDIN_FILENO) } } pub fn raw_stdout() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDOUT_FILENO) } } pub fn raw_stderr() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDERR_FILENO) } } pub fn get_nonblocking<F: AsRawFd>(file: &F) -> io::Result<bool> { unsafe { let flags = libc::fcntl(file.as_raw_fd(), libc::F_GETFL); if flags < 0 { return Err(io::Error::last_os_error()); } Ok(flags & libc::O_NONBLOCK != 0) } } pub fn set_nonblocking<F: AsRawFd>(file: &mut F, nonblocking: bool) -> io::Result<()> { unsafe { let fd = file.as_raw_fd(); let previous = libc::fcntl(fd, libc::F_GETFL); if previous < 0 { return Err(io::Error::last_os_error()); } let new = if nonblocking { previous | libc::O_NONBLOCK } else { previous & !libc::O_NONBLOCK }; if libc::fcntl(fd, libc::F_SETFL, new) < 0 { return Err(io::Error::last_os_error()); } Ok(()) } } #[derive(Debug)] pub struct File<F> { file: F, evented: RefCell<Option<mio::Registration>>, } impl<F: AsRawFd> File<F> { pub fn new_nb(mut file: F) -> io::Result<PollEvented<Self>> { set_nonblocking(&mut file, true)?; File::raw_new(file) } pub fn raw_new(file: F) -> io::Result<PollEvented<Self>> { PollEvented::new(File { file: file, evented: Default::default(), }) } } impl<F: AsRawFd> AsRawFd for File<F> { fn as_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } impl<F: AsRawFd> mio::Evented for File<F> { fn register( &self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt, ) -> io::Result<()> { match mio::unix::EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) { Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => { set_nonblocking(&mut self.as_raw_fd(), false)?; let (r, s) = mio::Registration::new2(); r.register(poll, token, interest, opts)?; s.set_readiness(mio::Ready::readable() | mio::Ready::writable())?; *self.evented.borrow_mut() = Some(r); Ok(()) } e => e, } } fn reregister( &self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt, ) -> io::Result<()> { match *self.evented.borrow() { None => mio::unix::EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts), Some(ref r) => r.reregister(poll, token, interest, opts), } } fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { match *self.evented.borrow() { None => mio::unix::EventedFd(&self.as_raw_fd()).deregister(poll), Some(ref r) => mio::Evented::deregister(r, poll), } } } impl<F: io::Read> io::Read for File<F> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.file.read(buf) } } impl<F: io::Write> io::Write for File<F> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.file.write(buf) } fn flush(&mut self) -> io::Result<()> { self.file.flush() } } impl<F: io::Seek> io::Seek for File<F> { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { self.file.seek(pos) } } #[cfg(test)] mod tests { use super::*; use std::os::unix::net::UnixStream; #[test] fn test_nonblocking() -> io::Result<()> { let (sock, _) = UnixStream::pair()?; let mut fd = sock.as_raw_fd(); set_nonblocking(&mut fd, false)?; assert!(!get_nonblocking(&fd)?); set_nonblocking(&mut fd, true)?; assert!(get_nonblocking(&fd)?); set_nonblocking(&mut fd, false)?; assert!(!get_nonblocking(&fd)?); Ok(()) } }
use std::cell::RefCell; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::{fs, io}; use tokio::io::PollEvented; unsafe fn dupe_file_from_fd(old_fd: RawFd) -> io::Result<fs::File> { let fd = libc::fcntl(old_fd, libc::F_DUPFD_CLOEXEC, 0); if fd < 0 { return Err(io::Error::last_os_error()); } Ok(fs::File::from_raw_fd(fd)) } pub fn raw_stdin() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDIN_FILENO) } } pub fn raw_stdout() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDOUT_FILENO) } } pub fn raw_stderr() -> io::Result<fs::File> { unsafe { dupe_file_from_fd(libc::STDERR_FILENO) } } pub fn get_nonblocking<F: AsRawFd>(file: &F) -> io::Result<bool> { unsafe { let flags = libc::fcntl(file.as_raw_fd(), libc::F_GETFL); if flags < 0 { return Err(io::Error::last_os_error()); } Ok(flags & libc::O_NONBLOCK != 0) } } pub fn set_nonblocking<F: AsRawFd>(file: &mut F, nonblocking: bool) -> io::Result<()> { unsafe { let fd = file.as_raw_fd(); let previous = libc::fcntl(fd, libc::F_GETFL); if previous < 0 { return Err(io::Error::last_os_error()); } let new = if nonblocking { previous | libc::O_NONBLOCK } else { previous & !libc::O_NONBLOCK }; if libc::fcntl(fd, libc::F_SETFL, new) < 0 { return Err(io::Error::last_os_error()); } Ok(()) } } #[derive(Debug)] pub struct File<F> { file: F, evented: RefCell<Option<mio::Registration>>, } impl<F: AsRawFd> File<F> { pub fn new_nb(mut file: F) -> io::Result<PollEvented<Self>> { set_nonblocking(&mut file, true)?; File::raw_new(file) } pub fn raw_new(file: F) -> io::Result<PollEvented<Self>> { PollEvented::new(File { file: file, evented: Default::default(), }) } } impl<F: AsRawFd> AsRawFd for File<F> { fn as_raw_fd(&self) -> RawFd { self.file.as_raw_fd() } } impl<F: AsRawFd> mio::Evented for File<F> { fn register( &self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt, ) -> io::Result<()> { match mio::unix::EventedFd(&self.as_raw_fd()).register(poll, token, interest, opts) { Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => { set_nonblocking(&mut self.as_raw_fd(), false)?; let (r, s) = mio::Registration::new2(); r.register(poll, token, interest, opts)?; s.set_readiness(mio::Ready::readable() | mio::Ready::writable())?; *self.evented.borrow_mut() = Some(r); Ok(()) } e => e, } } fn reregister( &self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt, ) -> io::Result<()> { match *self.evented.borrow() { None => mio::unix::EventedFd(&self.as_raw_fd()).reregister(poll, token, interest, opts), Some(ref r) => r.reregister(poll, token, interest, opts), } }
} impl<F: io::Read> io::Read for File<F> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.file.read(buf) } } impl<F: io::Write> io::Write for File<F> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.file.write(buf) } fn flush(&mut self) -> io::Result<()> { self.file.flush() } } impl<F: io::Seek> io::Seek for File<F> { fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { self.file.seek(pos) } } #[cfg(test)] mod tests { use super::*; use std::os::unix::net::UnixStream; #[test] fn test_nonblocking() -> io::Result<()> { let (sock, _) = UnixStream::pair()?; let mut fd = sock.as_raw_fd(); set_nonblocking(&mut fd, false)?; assert!(!get_nonblocking(&fd)?); set_nonblocking(&mut fd, true)?; assert!(get_nonblocking(&fd)?); set_nonblocking(&mut fd, false)?; assert!(!get_nonblocking(&fd)?); Ok(()) } }
fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { match *self.evented.borrow() { None => mio::unix::EventedFd(&self.as_raw_fd()).deregister(poll), Some(ref r) => mio::Evented::deregister(r, poll), } }
function_block-full_function
[ { "content": "fn stringify_error<E: error::Error>(e: E) -> io::Error {\n\n io::Error::new(io::ErrorKind::Other, e.to_string())\n\n}\n\n\n\n#[get(\"/{something}\")]\n\nasync fn index(info: web::Path<String>) -> impl Responder {\n\n format!(\"Hello Got this: {}\", info)\n\n}\n\n\n\n#[actix_rt::main]\n\nasync fn main() -> io::Result<()> {\n\n println!(\"Type something and hit enter!\");\n\n let stdin_fut = async {\n\n let file = tokio_file_unix::raw_stdin()?;\n\n let file = tokio_file_unix::File::new_nb(file)?;\n\n\n\n let client = Client::default();\n\n\n\n let mut framed = FramedRead::new(file, LinesCodec::new());\n\n\n", "file_path": "examples/stdin_actix_web.rs", "rank": 5, "score": 60665.30587290481 }, { "content": "# Changelog\n\n\n\n## 0.6.0\n\n\n\n - `File::to_io` has been removed in favor of having `File::new_nb` and\n\n `File::raw_new` return a `PollEvented` directly.\n\n - `File::get_nonblocking` and `File::set_nonblocking` have been migrated to\n\n module-level.\n\n - `StdFile` has been removed in favor of `raw_stdin`, `raw_stdout`, and\n\n `raw_stderr`.\n\n - `DelimCodec` has been removed in favor of `tokio_util::codec::FramedRead`.\n\n - tokio dependency has been migrated to 0.2.6 and Rust edition to 2018.\n\n\n\n## 0.5.1\n\n\n\n - Add `impl<F: Seek> Seek for File<F>`.\n\n\n\n## 0.5.0\n\n\n\n - Migrate from `tokio-core` to `tokio-reactor`.\n\n - Add `raw_std{in,out,err}` and deprecate `StdFile` in favor of those.\n\n\n\n## 0.4.2\n\n\n\n - Add `File::get_nonblocking`.\n\n\n\n## 0.4.1\n\n\n\n - Improved documentation and added another example `stdin_lines.rs`.\n\n\n\n## 0.4.0\n\n\n\n - Added “support” for regular files (which never block anyway).\n\n https://github.com/Rufflewind/tokio-file-unix/issues/2\n\n - Constructor of `File` is now private.\n\n Use `File::new_nb` or `File::raw_new` instead.\n\n - `File` is no longer `Sync`.\n\n - `File::set_nonblocking` no longer requires `&mut self`, just `&self`.\n\n\n\n## 0.3.0\n\n\n\n - Removed fake implementations of `Read` and `Write` for `StdFile`.\n\n - Upgraded to tokio-io.\n\n\n\n## 0.2.0\n\n\n\n - Added `DelimCodec` and `StdFile`.\n\n - Generalized `File`.\n\n\n\n## 0.1.0\n\n\n\n - Initial release.\n", "file_path": "changelog.md", "rank": 6, "score": 9756.163869382217 }, { "content": "# `tokio-file-unix`\n\n\n\n[![Documentation](https://docs.rs/tokio-file-unix/badge.svg)](https://docs.rs/tokio-file-unix)\n\n[![Crates.io](https://img.shields.io/crates/v/tokio-file-unix.svg)](https://crates.io/crates/tokio-file-unix)\n\n[![Build Status](https://github.com/Rufflewind/tokio-file-unix/actions/workflows/build.yml/badge.svg)](https://github.com/Rufflewind/tokio-file-unix/actions/workflows/build.yml)\n\n\n\nAsynchronous support for file-like objects via [Tokio](https://tokio.rs). **Only supports Unix-like platforms.**\n\n\n\nThis crate is primarily intended for pipes and other files that support nonblocking I/O. Regular files do not support nonblocking I/O, so this crate has no effect on them.\n\n\n\n## Usage\n\n\n\nAdd this to your `Cargo.toml`:\n\n\n\n~~~toml\n\n[dependencies]\n\ntokio-file-unix = \"0.5.1\"\n\n~~~\n\n\n\nNext, add this to the root module of your crate:\n\n\n\n~~~rust\n\nextern crate tokio_file_unix;\n\n~~~\n\n\n\n## Examples\n\n\n\nSee the `examples` directory as well as the documentation.\n\n\n\n## License\n\n\n\nDual-licensed under Apache and MIT.\n", "file_path": "README.md", "rank": 7, "score": 9749.334374758782 }, { "content": "use std::io;\n\nuse tokio::stream::StreamExt;\n\nuse tokio_util::codec::{FramedRead, LinesCodec};\n\n\n\n#[tokio::main]\n\nasync fn main() -> io::Result<()> {\n\n // convert stdin into a nonblocking file;\n\n // this is the only part that makes use of tokio_file_unix\n\n let file = tokio_file_unix::raw_stdin()?;\n\n let file = tokio_file_unix::File::new_nb(file)?;\n\n\n\n let mut framed = FramedRead::new(file, LinesCodec::new());\n\n\n\n println!(\"Type something and hit enter!\");\n\n while let Some(got) = framed.next().await {\n\n println!(\"Got: {:?}\", got);\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/stdin.rs", "rank": 16, "score": 8.433869991144187 }, { "content": "use std::fs::File;\n\nuse std::io::{self, Seek, SeekFrom};\n\nuse tokio::io::AsyncWriteExt;\n\n\n\n#[tokio::main]\n\nasync fn main() -> io::Result<()> {\n\n let file = File::create(\"tests/seek.txt\")?;\n\n file.set_len(0x11)?;\n\n let mut file = tokio_file_unix::File::new_nb(file)?;\n\n\n\n file.write_all(b\"aaaaAAAAaaaaAAAA\\n\").await?;\n\n file.get_mut().seek(SeekFrom::Start(8))?;\n\n file.write_all(&[b'b'; 8]).await?;\n\n file.get_mut().seek(SeekFrom::Start(2))?;\n\n file.write_all(&[b'c'; 4]).await?;\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/seek.rs", "rank": 17, "score": 7.623378389332165 }, { "content": "use actix_web::client::Client;\n\nuse actix_web::{get, web, App, HttpServer, Responder};\n\nuse futures::future::FutureExt;\n\nuse futures::{pin_mut, select};\n\nuse std::{error, io};\n\nuse tokio::stream::StreamExt;\n\nuse tokio_util::codec::{FramedRead, LinesCodec};\n\n\n", "file_path": "examples/stdin_actix_web.rs", "rank": 20, "score": 4.037798459357286 }, { "content": " }\n\n .fuse();\n\n\n\n let server_fut = HttpServer::new(|| App::new().service(index))\n\n .bind(\"127.0.0.1:8080\")?\n\n .run()\n\n .fuse();\n\n\n\n pin_mut!(stdin_fut, server_fut);\n\n select! {\n\n result = stdin_fut => result,\n\n result = server_fut => result,\n\n }\n\n}\n", "file_path": "examples/stdin_actix_web.rs", "rank": 21, "score": 3.1041602646598303 }, { "content": " while let Some(got) = framed.next().await {\n\n println!(\"Sending this: {:?}\", got);\n\n\n\n let mut response = client\n\n .get(format!(\n\n \"http://127.0.0.1:8080/{}\",\n\n got.map_err(stringify_error)?\n\n ))\n\n .send()\n\n .await\n\n .map_err(stringify_error)?;\n\n\n\n let body = response.body().await.map_err(stringify_error)?;\n\n\n\n println!(\n\n \"Got bytes: {:?}\",\n\n String::from_utf8(body.to_vec()).map_err(stringify_error)?,\n\n );\n\n }\n\n Ok(())\n", "file_path": "examples/stdin_actix_web.rs", "rank": 22, "score": 2.296919875789568 } ]
Rust
wasm/src/client.rs
warycat/leetcode_rs
3cb8a1aa569d372443675fab9a63043291316b51
use crate::desktop::Desktop; use crate::media::MediaClient; use crate::pc::PeerConnection; use crate::searchbar::*; use crate::utils::*; use js_sys::JsString; use js_sys::Reflect; use log::info; use rustgym_msg::*; use std::cell::RefCell; use std::collections::HashMap; use uuid::Uuid; use wasm_bindgen::prelude::*; use wasm_bindgen::*; use wasm_bindgen_futures::*; use web_sys::{ MediaStream, MediaStreamTrack, MessageEvent, RtcIceCandidate, RtcIceCandidateInit, RtcSdpType, RtcSessionDescriptionInit, WebSocket, }; #[derive(Debug, Clone)] pub struct Client { client_info: Option<ClientInfo>, ws: WebSocket, _desktop: Desktop, searchbar: Option<SearchBar>, media_client: Option<MediaClient>, media_stream: Option<MediaStream>, pcs: HashMap<Uuid, PeerConnection>, } impl Client { pub fn new() -> Self { let client_info = None; let media_client = None; let searchbar = None; let media_stream = None; let pcs = HashMap::new(); let _desktop = Desktop::new(start_menu(), start_button()); let ws = WebSocket::new(&wsurl()).expect("WebSocket"); let onmessage_cb = Closure::wrap(Box::new(move |e: MessageEvent| { let js_json: JsString = e.data().dyn_into().unwrap(); let rust_json: String = js_json.into(); match serde_json::from_str::<MsgOut>(&rust_json) { Ok(msg) => { process(msg); } Err(err) => { info!("{}", err); } } }) as Box<dyn FnMut(_)>); ws.set_onmessage(Some(onmessage_cb.as_ref().unchecked_ref())); onmessage_cb.forget(); Client { ws, client_info, media_client, media_stream, _desktop, searchbar, pcs, } } fn on_stream_start(&self, client_uuid: Uuid) -> Result<(), JsValue> { self.send_json(MsgIn::StreamStart { client_uuid }) } fn on_offer(&self, caller: Uuid, callee: Uuid, offer_sdp: String) -> Result<(), JsValue> { self.send_json(MsgIn::Offer { caller, callee, offer_sdp, }) } fn on_answer(&self, caller: Uuid, callee: Uuid, answer_sdp: String) -> Result<(), JsValue> { self.send_json(MsgIn::Answer { caller, callee, answer_sdp, }) } pub fn on_ice_candidate( &self, local: Uuid, remote: Uuid, candidate: String, sdp_mid: String, sdp_m_line_index: u16, ) -> Result<(), JsValue> { self.send_json(MsgIn::IceCandidate { local, remote, candidate, sdp_mid, sdp_m_line_index, }) } pub fn on_search_text_change(&self, search_text: String) -> Result<(), JsValue> { self.send_json(MsgIn::SearchText(search_text)) } pub fn on_query_text(&self, query_text: String) -> Result<(), JsValue> { let searchbar = self.searchbar.as_ref().expect("searchbar"); searchbar.update_search_input(&query_text); searchbar.close_search_suggestions()?; self.send_json(MsgIn::QueryText(query_text))?; Ok(()) } fn send_json(&self, msg: MsgIn) -> Result<(), JsValue> { let str = serde_json::to_string(&msg).expect("to_string"); self.ws.send_with_str(&str) } } pub fn process(message: MsgOut) { spawn_local(async move { use MsgOut::*; let res: Result<(), JsValue> = match message { Ping => Ok(()), Pong => Ok(()), SearchSuggestions(suggestions) => render_search_suggestions(suggestions), QueryResults(results) => render_query_results(results), RegistorClient(client_info) => process_register_client(client_info).await, UnRegistorClient(_) => Ok(()), StreamStart { client_uuid } => start_call(client_uuid).await, Offer { caller, callee, offer_sdp, } => process_offer(caller, callee, offer_sdp).await, Answer { caller, callee, answer_sdp, } => process_answer(caller, callee, answer_sdp).await, IceCandidate { local, remote, candidate, sdp_mid, sdp_m_line_index, } => process_ice_candidate(local, remote, candidate, sdp_mid, sdp_m_line_index).await, SessionClients(_) => Ok(()), AllClients(_) => Ok(()), }; match res { Ok(_) => {} Err(err) => { info!("{:?}", err); } } }); } async fn process_ice_candidate( _local: Uuid, remote: Uuid, candidate: String, sdp_mid: String, sdp_m_line_index: u16, ) -> Result<(), JsValue> { if let Some(pc) = get_client().pcs.get(&remote) { info!("ice {} {}", remote, candidate); let mut candidate_init = RtcIceCandidateInit::new(&candidate); candidate_init.sdp_mid(Some(&sdp_mid)); candidate_init.sdp_m_line_index(Some(sdp_m_line_index)); let candidate_obj = RtcIceCandidate::new(&candidate_init)?; let promise = pc.add_ice_candidate_with_opt_rtc_ice_candidate(Some(&candidate_obj)); JsFuture::from(promise).await?; } Ok(()) } async fn process_offer(caller: Uuid, callee: Uuid, offer_sdp: String) -> Result<(), JsValue> { info!("process_offer"); let media_stream = get_client().media_stream.expect("media_stream"); let (pc, answer_sdp) = create_answer(caller, callee, &media_stream, offer_sdp).await?; set_peerconnection(caller, pc); get_client().on_answer(caller, callee, answer_sdp)?; Ok(()) } async fn process_answer(_caller: Uuid, callee: Uuid, answer_sdp: String) -> Result<(), JsValue> { info!("process_answer"); let mut answer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Answer); answer_obj.sdp(&answer_sdp); let srd_promise = get_client() .pcs .get(&callee) .expect("pc") .set_remote_description(&answer_obj); JsFuture::from(srd_promise).await?; Ok(()) } async fn process_register_client(client_info: ClientInfo) -> Result<(), JsValue> { if get_client().client_info.is_none() { info!("set local {}", client_info.client_uuid); info!( "{:?}", client_info.user_agent.as_ref().expect("useragent").family ); let client_uuid = client_info.client_uuid; if client_info.is_media_supported() { let media_stream = get_media_stream().await?; let media_client = get_client().media_client.expect("media_client"); media_client.init_local_video(&media_stream)?; set_media_stream(media_stream); get_client().on_stream_start(client_uuid)?; } set_client_info(client_info); } Ok(()) } async fn start_call(client_uuid: Uuid) -> Result<(), JsValue> { let local_client_info = get_client().client_info.expect("local_client_info"); let caller = local_client_info.client_uuid; let callee = client_uuid; if callee != caller { info!("start_call"); let (pc, offer_sdp) = create_offer( caller, callee, &get_client().media_stream.expect("media_stream"), ) .await?; set_peerconnection(callee, pc); get_client().on_offer(caller, callee, offer_sdp) } else { Ok(()) } } async fn create_offer( caller: Uuid, callee: Uuid, media_stream: &MediaStream, ) -> Result<(PeerConnection, String), JsValue> { let local_client_info = get_client().client_info.expect("local_client_info"); let pc = PeerConnection::new(caller, callee, local_client_info.ice_servers)?; let tracks = media_stream.get_tracks().to_vec(); for item in tracks { let media_stream_track: MediaStreamTrack = item.dyn_into().unwrap(); pc.add_track_0(&media_stream_track, media_stream); } let offer = JsFuture::from(pc.create_offer()).await?; let offer_sdp = Reflect::get(&offer, &JsValue::from_str("sdp"))? .as_string() .unwrap(); let mut offer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Offer); offer_obj.sdp(&offer_sdp); let sld_promise = pc.set_local_description(&offer_obj); JsFuture::from(sld_promise).await?; Ok((pc, offer_sdp)) } async fn create_answer( caller: Uuid, callee: Uuid, media_stream: &MediaStream, offer_sdp: String, ) -> Result<(PeerConnection, String), JsValue> { info!("create_answer"); let local_client_info = get_client().client_info.expect("local_client_info"); let pc = PeerConnection::new(callee, caller, local_client_info.ice_servers)?; let mut offer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Offer); offer_obj.sdp(&offer_sdp); let srd_promise = pc.set_remote_description(&offer_obj); JsFuture::from(srd_promise).await?; let tracks = media_stream.get_tracks().to_vec(); for item in tracks { let media_stream_track: MediaStreamTrack = item.dyn_into().unwrap(); pc.add_track_0(&media_stream_track, media_stream); } let answer = JsFuture::from(pc.create_answer()).await?; let mut answer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Answer); let answer_sdp = Reflect::get(&answer, &JsValue::from_str("sdp"))? .as_string() .unwrap(); answer_obj.sdp(&answer_sdp); let sld_promise = pc.set_local_description(&answer_obj); JsFuture::from(sld_promise).await?; Ok((pc, answer_sdp)) } fn render_search_suggestions(search_suggestions: Vec<String>) -> Result<(), JsValue> { info!("{:?}", search_suggestions); get_client() .searchbar .expect("searchbar") .update_search_suggestions(search_suggestions) } fn render_query_results(query_results: Vec<QueryResult>) -> Result<(), JsValue> { info!("{:?}", query_results); get_client() .searchbar .expect("searchbar") .update_query_results(query_results) } thread_local! { pub static CLIENT: RefCell<Client> = RefCell::new(Client::new()); } pub fn get_client() -> Client { CLIENT.with(|client| client.borrow_mut().clone()) } pub fn set_client_info(client_info: ClientInfo) { CLIENT.with(|client| client.borrow_mut().client_info = Some(client_info)); } pub fn set_searchbar(searchbar: SearchBar) { CLIENT.with(|client| client.borrow_mut().searchbar = Some(searchbar)); } pub fn set_media_client(media_client: MediaClient) { CLIENT.with(|client| client.borrow_mut().media_client = Some(media_client)); } pub fn add_remote_video(remote: Uuid) { CLIENT.with(|client| { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_video(remote) .expect("add_remote_video"); }); } pub fn remove_remote_video(remote: Uuid) { CLIENT.with(|client| { client .borrow_mut() .media_client .as_mut() .expect("media_client") .remove_remote_video(remote) .expect("remove_remote_video"); }); } pub fn add_remote_track(remote: Uuid, track: MediaStreamTrack) { CLIENT.with(|client| match track.kind().as_ref() { "video" => { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_video_track(remote, track) .expect("add_remote_video_track"); } "audio" => { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_audio_track(remote, track) .expect("add_remote_audio_track"); } _ => { info!("{:?} {}", track, track.kind()); } }); } fn set_media_stream(media_stream: MediaStream) { CLIENT.with(|client| client.borrow_mut().media_stream = Some(media_stream)); } fn set_peerconnection(remote_uuid: Uuid, pc: PeerConnection) { CLIENT.with(|client| client.borrow_mut().pcs.insert(remote_uuid, pc)); }
use crate::desktop::Desktop; use crate::media::MediaClient; use crate::pc::PeerConnection; use crate::searchbar::*; use crate::utils::*; use js_sys::JsString; use js_sys::Reflect; use log::info; use rustgym_msg::*; use std::cell::RefCell; use std::collections::HashMap; use uuid::Uuid; use wasm_bindgen::prelude::*; use wasm_bindgen::*; use wasm_bindgen_futures::*; use web_sys::{ MediaStream, MediaStreamTrack, MessageEvent, RtcIceCandidate, RtcIceCandidateInit, RtcSdpType, RtcSessionDescriptionInit, WebSocket, }; #[derive(Debug, Clone)] pub struct Client { client_info: Option<ClientInfo>, ws: WebSocket, _desktop: Desktop, searchbar: Option<SearchBar>, media_client: Option<MediaClient>, media_stream: Option<MediaStream>, pcs: HashMap<Uuid, PeerConnection>, } impl Client { pub fn new() -> Self { let client_info = None; let media_client = None; let searchbar = None; let media_stream = None; let pcs = HashMap::new(); let _desktop = Desktop::new(start_menu(), start_button()); let ws = WebSocket::new(&wsurl()).expect("WebSocket"); let onmessage_cb = Closure::wrap(Box::new(move |e: MessageEvent| { let js_json: JsString = e.data().dyn_into().unwrap(); let rust_json: String = js_json.into(); match serde_json::from_str::<MsgOut>(&rust_json) { Ok(msg) => { process(msg); } Err(err) => { info!("{}", err); } } }) as Box<dyn FnMut(_)>); ws.set_onmessage(Some(onmessage_cb.as_ref().unchecked_ref())); onmessage_cb.forget(); Client { ws, client_info, media_client, media_stream, _desktop, searchbar, pcs, } } fn on_stream_start(&self, client_uuid: Uuid) -> Result<(), JsValue> { self.send_json(MsgIn::StreamStart { client_uuid }) } fn on_offer(&self, caller: Uuid, callee: Uuid, offer_sdp: String) -> Result<(), JsValue> { self.send_json(MsgIn::Offer { caller, callee, offer_sdp, }) } fn on_answer(&self, caller: Uuid, callee: Uuid, answer_sdp: String) -> Result<(), JsValue> { self.send_json(MsgIn::Answer { caller, callee, answer_sdp, }) } pub fn on_ice_candidate( &self, local: Uuid, remote: Uuid, candidate: String, sdp_mid: String, sdp_m_line_index: u16, ) -> Result<(), JsValue> { self.send_json(MsgIn::IceCandidate { local, remote, candidate, sdp_mid, sdp_m_line_index, }) } pub fn on_search_text_change(&self, search_text: String) -> Result<(), JsValue> { self.send_json(MsgIn::SearchText(search_text)) } pub fn on_query_text(&self, query_text: String) -> Result<(), JsValue> { let searchbar = self.searchbar.as_ref().expect("searchbar"); searchbar.update_search_input(&query_text); searchbar.close_search_suggestions()?; self.send_json(MsgIn::QueryText(query_text))?; Ok(()) } fn send_json(&self, msg: MsgIn) -> Result<(), JsValue> { let str = serde_json::to_string(&msg).expect("to_string"); self.ws.send_with_str(&str) } } pub fn process(message: MsgOut) { spawn_local(async move { use MsgOut::*; let res: Result<(), JsValue> = match message { Ping => Ok(()), Pong => Ok(()), SearchSuggestions(suggestions) => render_search_suggestions(suggestions), QueryResults(results) => render_query_results(results), RegistorClient(client_info) => process_register_client(client_info).await, UnRegistorClient(_) => Ok(()), StreamStart { client_uuid } => start_call(client_uuid).await, Offer { caller, callee, offer_sdp, } => process_offer(caller, callee, offer_sdp).await, Answer { caller, callee, answer_sdp, } => process_answer(caller, callee, answer_sdp).await, IceCandidate { local, remote, candidate, sdp_mid, sdp_m_line_index, } => process_ice_candidate(local, remote, candidate, sdp_mid, sdp_m_line_index).await, SessionClients(_) => Ok(()), AllClients(_) => Ok(()), }; match res { Ok(_) => {} Err(err) => { info!("{:?}", err); } } }); } async fn process_ice_candidate( _local: Uuid, remote: Uuid, candidate: String, sdp_mid: String, sdp_m_line_index: u16, ) -> Result<(), JsValue> { if let Some(pc) = get_client().pcs.get(&remote) { info!("ice {} {}", remote, candidate); let mut candidate_init = RtcIceCandidateInit::new(&candidate); candidate_init.sdp_mid(Some(&sdp_mid)); candidate_init.sdp_m_line_index(Some(sdp_m_line_index)); let candidate_obj = RtcIceCandidate::new(&candidate_init)?; let promise = pc.add_ice_candidate_with_opt_rtc_ice_candidate(Some(&candidate_obj)); JsFuture::from(promise).await?; } Ok(()) } async fn process_offer(caller: Uuid, callee: Uuid, offer_sdp: String) -> Result<(), JsValue> { info!("process_offer"); let media_stream = get_client().media_stream.expect("media_stream"); let (pc, answer_sdp) = create_answer(caller, callee, &media_stream, offer_sdp).await?; set_peerconnection(caller, pc); get_client().on_answer(caller, callee, answer_sdp)?; Ok(()) } async fn process_answer(_caller: Uuid, callee: Uuid, answer_sdp: String) -> Result<(), JsValue> { info!("process_answer"); let mut answer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Answer); answer_obj.sdp(&answer_sdp); let srd_promise = get_client() .pcs .get(&callee) .expect("pc") .set_remote_description(&answer_obj); JsFuture::from(srd_promise).await?; Ok(()) } async fn process_register_client(client_info: ClientInfo) -> Result<(), JsValue> { if get_client().client_info.is_none() { info!("set local {}", client_info.client_uuid); info!( "{:?}", client_info.user_agent.as_ref().expect("useragent").family ); let client_uuid = client_info.client_uuid; if client_info.is_media_supported() { let media_stream = get_media_stream().await?; let media_client = get_client().media_client.expect("media_client"); media_client.init_local_video(&media_stream)?; set_media_stream(media_stream); get_client().on_stream_start(client_uuid)?; } set_client_info(client_info); } Ok(()) } async fn start_call(client_uuid: Uuid) -> Result<(), JsValue> { let local_client_info = get_client().client_info.expect("local_client_info"); let caller = local_client_info.client_uuid; let callee = client_uuid; if callee != caller { info!("start_call"); let (pc, offer_sdp) = create_offer( caller, callee, &get_client().media_stream.expect("media_stream"), ) .await?; set_peerconnection(callee, pc); get_client().on_offer(caller, callee, offer_sdp) } else { Ok(()) } } async fn create_offer( caller: Uuid, callee: Uuid, media_stream: &MediaStream, ) -> Result<(PeerConnection, String), JsValue> { let local_client_info = get_client().client_info.expect("local_client_info"); let pc = PeerConnection::new(caller, callee, local_client_info.ice_servers)?; let tracks = media_stream.get_tracks().to_vec(); for item in tracks { let media_stream_track: MediaStreamTrack = item.dyn_into().unwrap(); pc.add_track_0(&media_stream_track, media_stream); } let offer = JsFuture::from(pc.create_offer()).await?; let offer_sdp = Reflect::get(&offer, &JsValue::from_str("sdp"))? .as_string() .unwrap(); let mut offer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Offer); offer_obj.sdp(&offer_sdp); let sld_promise = pc.set_local_description(&offer_obj); JsFuture::from(sld_promise).await?; Ok((pc, offer_sdp)) } async fn create_answer( caller: Uuid, callee: Uuid, media_stream: &MediaStream, offer_sdp: String, ) -> Result<(PeerConnection, String), JsValue> { info!("create_answer"); let local_client_info = get_client().client_info.expect("local_client_info"); let pc = PeerConnection::new(callee, caller, local_client_info.ice_servers)?; let mut offer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Offer); offer_obj.sdp(&offer_sdp); let srd_promise = pc.set_remote_description(&offer_obj); JsFuture::from(srd_promise).await?; let tracks = media_stream.get_tracks().to_vec(); for item in tracks { let media_stream_track: MediaStreamTrack = item.dyn_into().unwrap(); pc.add_track_0(&media_stream_track, media_stream); } let answer = JsFuture::from(pc.create_answer()).await?; let mut answer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Answer); let answer_sdp = Reflect::get(&answer, &JsValue::from_str("sdp"))? .as_string() .unwrap(); answer_obj.sdp(&answer_sdp); let sld_promise = pc.set_local_description(&answer_obj); JsFuture::from(sld_promise).await?; Ok((pc, answer_sdp)) } fn render_search_suggestions(search_suggestions: Vec<String>) -> Result<(), JsValue> { info!("{:?}", search_suggestions); get_client() .searchbar .expect("searchbar") .update_search_suggestions(search_suggestions) } fn render_query_results(query_results: Vec<QueryResult>) -> Result<(), JsValue> { info!("{:?}", query_results); get_client() .searchbar .expect("searchbar") .update_query_results(query_results) } thread_local! { pub static CLIENT: RefCell<Client> = RefCell::new(Client::new()); } pub fn get_client() -> Client { CLIENT.with(|client| client.borrow_mut().clone()) } pub fn set_client_info(client_info: ClientInfo) { CLIENT.with(|client| client.borrow_mut().client_info = Some(client_info)); } pub fn set_searchbar(searchbar: SearchBar) { CLIENT.with(|client| client.borrow_mut().searchbar = Some(searchbar)); } pub fn set_media_client(media_client: MediaClient) { CLIENT.with(|client| client.borrow_mut().media_client = Some(media_client)); } pub fn add_remote_video(remote: Uuid) { CLIENT.with(|client| { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_video(remote) .expect("add_remote_video"); }); } pub fn remove_remote_video(remote: Uuid) { CLIENT.with(|client| { client .borrow_mut() .media_client .as_mut() .expect("media_client") .remove_remote_video(remote) .expect("remove_remote_video"); }); } pub fn add_remote_track(remote: Uuid, track: MediaStreamTrack) {
fn set_media_stream(media_stream: MediaStream) { CLIENT.with(|client| client.borrow_mut().media_stream = Some(media_stream)); } fn set_peerconnection(remote_uuid: Uuid, pc: PeerConnection) { CLIENT.with(|client| client.borrow_mut().pcs.insert(remote_uuid, pc)); }
CLIENT.with(|client| match track.kind().as_ref() { "video" => { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_video_track(remote, track) .expect("add_remote_video_track"); } "audio" => { client .borrow_mut() .media_client .as_mut() .expect("media_client") .add_remote_audio_track(remote, track) .expect("add_remote_audio_track"); } _ => { info!("{:?} {}", track, track.kind()); } }); }
function_block-function_prefix_line
[ { "content": "pub fn nsstring_from_str(string: &str) -> NSString {\n\n const UTF8_ENCODING: usize = 4;\n\n\n\n let cls = class!(NSString);\n\n let bytes = string.as_ptr() as *const c_void;\n\n unsafe {\n\n let obj: *mut objc::runtime::Object = msg_send![cls, alloc];\n\n let obj: *mut objc::runtime::Object = msg_send![\n\n obj,\n\n initWithBytes:bytes\n\n length:string.len()\n\n encoding:UTF8_ENCODING\n\n ];\n\n let _: *mut c_void = msg_send![obj, autorelease];\n\n NSString(obj)\n\n }\n\n}\n", "file_path": "metaldnn/src/metaldnn.rs", "rank": 6, "score": 396399.54894275614 }, { "content": "fn solve(reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let s = reader.collect_string();\n\n let n: usize = reader.parse_line();\n\n let res = repeated_string(s, n);\n\n writeln!(writer, \"{}\", res).unwrap();\n\n}\n\n\n", "file_path": "hackerrank/src/repeated_string/mod.rs", "rank": 9, "score": 343577.8503061879 }, { "content": "pub fn init_pool(database_url: &str) -> Result<SqlitePool, PoolError> {\n\n let manager = ConnectionManager::<SqliteConnection>::new(database_url);\n\n Pool::builder().build(manager)\n\n}\n\n\n", "file_path": "server/src/db.rs", "rank": 10, "score": 336346.9417145619 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args: Vec<usize> = reader.parse_vec();\n\n let n = args[0];\n\n let k = args[1] as i32;\n\n let s: Vec<char> = reader.collect_string().chars().collect();\n\n let mut g = 0;\n\n for i in 0..n / 2 {\n\n if s[i] != s[n - 1 - i] {\n\n g += 1;\n\n }\n\n }\n\n let res = (g - k).abs();\n\n writeln!(writer, \"Case #{}: {}\", case_no, res).unwrap();\n\n}\n\n\n\ngoogle_test_gen!(test, \"input.txt\", \"output.txt\");\n", "file_path": "google/src/kickstart/year2021/round01/_1_k_goodness_string/mod.rs", "rank": 11, "score": 319923.2598646416 }, { "content": "pub fn wsurl() -> String {\n\n let window: Window = window().expect(\"window\");\n\n let location: Location = window.location();\n\n let protocol: String = location.protocol().expect(\"protocol\");\n\n let host: String = location.host().expect(\"host\");\n\n let ws_protocol = if protocol == \"https:\" {\n\n \"wss://\"\n\n } else {\n\n \"ws://\"\n\n };\n\n format!(\"{}{}/ws/\", ws_protocol, host)\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 13, "score": 304959.45872825175 }, { "content": "fn solve(reader: &mut impl RustGymRead, writer: &mut impl Write) {\n\n let line: i32 = reader.parse_line();\n\n write!(writer, \"{}\", line).unwrap();\n\n}\n\n\n", "file_path": "hackerrank/src/main.rs", "rank": 14, "score": 298225.1551465458 }, { "content": "fn solve(reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let n = reader.parse_line();\n\n let c: Vec<i32> = reader.parse_vec();\n\n let res = jumping_on_the_clouds(n, c);\n\n write!(writer, \"{}\", res).unwrap();\n\n}\n\n\n", "file_path": "hackerrank/src/jumping_on_the_clouds/mod.rs", "rank": 15, "score": 295845.07921616774 }, { "content": "fn solve(reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let n: usize = reader.parse_line();\n\n let arr: Vec<i32> = reader.parse_vec();\n\n write!(writer, \"{}\", sock_merchant(n, arr)).unwrap();\n\n}\n\n\n", "file_path": "hackerrank/src/sock_merchant/mod.rs", "rank": 16, "score": 295845.07921616774 }, { "content": "fn solve(reader: &mut impl RustGymRead, writer: &mut impl Write) {\n\n writeln!(writer, \"Hello, World.\").unwrap();\n\n let line = reader.collect_string();\n\n write!(writer, \"{}\", line).unwrap();\n\n}\n\n\n\ntest_gen!(test00, \"input00.txt\", \"output00.txt\");\n\ntest_gen!(test01, \"input01.txt\", \"output01.txt\");\n", "file_path": "hackerrank/src/hello_world/mod.rs", "rank": 17, "score": 293531.81437595445 }, { "content": "pub fn init() -> Result<(), JsValue> {\n\n log::set_logger(&LOGGER)\n\n .map(|_| log::set_max_level(LOG_LEVEL_FILTER))\n\n .map_err(|e| JsValue::from_str(&e.to_string()))\n\n}\n", "file_path": "wasm/src/logger.rs", "rank": 18, "score": 289525.65462655603 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let line = reader.collect_string();\n\n writeln!(writer, \"Case #{}: {}\", case_no, line).unwrap();\n\n}\n\n\n\nmod codejam;\n\nmod kickstart;\n", "file_path": "google/src/main.rs", "rank": 19, "score": 287139.7352555492 }, { "content": "fn get_clang_args() -> Vec<&'static str> {\n\n let target_os = env::var(\"CARGO_CFG_TARGET_OS\").expect(\"CARGO_CFG_TARGET_OS is set by cargo.\");\n\n if target_os.contains(\"macos\") {\n\n return vec![\"-x\", \"objective-c\", \"-fblocks\", \"-isysroot\", MACOS_ROOT];\n\n }\n\n if target_os.contains(\"ios\") {\n\n return vec![\"-x\", \"objective-c\", \"-fblocks\", \"-isysroot\", IOS_ROOT];\n\n }\n\n panic!();\n\n}\n\n\n", "file_path": "metaldnn-sys/build.rs", "rank": 20, "score": 286379.3413878581 }, { "content": "fn hostname(url: &str) -> String {\n\n let parts: Vec<&str> = url.split('/').collect();\n\n parts[2].to_string()\n\n}\n\n\n\nimpl Solution {\n\n fn crawl(start_url: String, html_parser: HtmlParser) -> Vec<String> {\n\n let pool = ThreadPool::new(4);\n\n let mut queue = vec![];\n\n let mut visited = HashSet::new();\n\n let start_hostname = hostname(&start_url);\n\n if visited.insert(start_url.clone()) {\n\n queue.push(start_url);\n\n }\n\n while !queue.is_empty() {\n\n let (tx, rx) = channel();\n\n while let Some(url) = queue.pop() {\n\n let tx = tx.clone();\n\n let html_parser = html_parser.clone();\n\n pool.execute(move || {\n", "file_path": "leetcode/src/d12/_1242_web_crawler_multithreaded.rs", "rank": 21, "score": 282876.92750703427 }, { "content": "fn next_pass(password: &str) -> String {\n\n let val = decode(password);\n\n let mut x = val;\n\n loop {\n\n x += 1;\n\n let s = encode(x);\n\n if rule1(&s) && rule2(&s) && rule3(&s) {\n\n break;\n\n }\n\n }\n\n encode(x).into_iter().map(|b| b as char).collect()\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day11/mod.rs", "rank": 22, "score": 282876.92750703427 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let n = reader.parse_line();\n\n let mut max_line = \"\".to_string();\n\n let mut res = 0;\n\n for _ in 0..n {\n\n let line = reader.collect_string();\n\n if line > max_line {\n\n max_line = line;\n\n } else {\n\n res += 1;\n\n }\n\n }\n\n writeln!(writer, \"Case #{}: {}\", case_no, res).unwrap();\n\n}\n\n\n\ngoogle_test_gen!(test, \"input.txt\", \"output.txt\");\n", "file_path": "google/src/kickstart/year2013/round01/_1_moist/mod.rs", "rank": 23, "score": 278259.44954382797 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args: Vec<usize> = reader.parse_vec();\n\n let n = args[0];\n\n let b = args[1] as i32;\n\n let mut houses: Vec<i32> = reader.parse_vec();\n\n houses.sort_unstable();\n\n let mut sum = 0;\n\n let mut res = 0;\n\n for i in 0..n {\n\n if houses[i] + sum <= b {\n\n sum += houses[i];\n\n res += 1;\n\n }\n\n }\n\n writeln!(writer, \"Case #{}: {}\", case_no, res).unwrap();\n\n}\n\n\n\ngoogle_test_gen!(test, \"input.txt\", \"output.txt\");\n", "file_path": "google/src/kickstart/year2020/round01/_1_allocation/mod.rs", "rank": 24, "score": 278259.44954382797 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args = reader.parse_vec();\n\n let r = args[0];\n\n let c = args[1];\n\n let a: Vec<Vec<i32>> = reader.parse_mat(r);\n\n let mut up: Vec<Vec<usize>> = vec![vec![0; c]; r];\n\n let mut left: Vec<Vec<usize>> = vec![vec![0; c]; r];\n\n let mut down: Vec<Vec<usize>> = vec![vec![0; c]; r];\n\n let mut right: Vec<Vec<usize>> = vec![vec![0; c]; r];\n\n for i in 0..r {\n\n for j in 0..c {\n\n if a[i][j] == 1 {\n\n up[i][j] = 1;\n\n left[i][j] = 1;\n\n if i > 0 {\n\n up[i][j] += up[i - 1][j];\n\n }\n\n if j > 0 {\n\n left[i][j] += left[i][j - 1];\n\n }\n", "file_path": "google/src/kickstart/year2021/round01/_2_l_shaped_plots/mod.rs", "rank": 25, "score": 276186.1431158562 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args: Vec<usize> = reader.parse_vec();\n\n let r = args[0];\n\n let c = args[1];\n\n let mut queue: BinaryHeap<(i64, usize, usize)> = BinaryHeap::new();\n\n let a: Vec<Vec<i64>> = reader.parse_mat(r);\n\n for i in 0..r {\n\n for j in 0..c {\n\n queue.push((a[i][j], i, j));\n\n }\n\n }\n\n let mut b: Vec<Vec<i64>> = a.clone();\n\n let mut res = 0;\n\n while let Some((h, i, j)) = queue.pop() {\n\n res += h - a[i][j];\n\n if i > 0 && h - 1 > b[i - 1][j] {\n\n b[i - 1][j] = h - 1;\n\n queue.push((h - 1, i - 1, j));\n\n }\n\n if j > 0 && h - 1 > b[i][j - 1] {\n", "file_path": "google/src/kickstart/year2021/round01/_3_rabbit_house/mod.rs", "rank": 26, "score": 276186.1431158562 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args: Vec<f64> = reader.parse_vec();\n\n let v = args[0];\n\n let d = args[1];\n\n let res = degree(v, d);\n\n writeln!(writer, \"Case #{}: {:.7}\", case_no, res).unwrap();\n\n}\n\n\n", "file_path": "google/src/kickstart/year2013/round01/_2_captain_hammer/mod.rs", "rank": 27, "score": 276186.1431158562 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let args: Vec<f64> = reader.parse_vec();\n\n let f = args[0];\n\n let r0 = args[1];\n\n let t = args[2];\n\n let r = args[3];\n\n let g = args[4];\n\n let res = probability(f, r0, t, r, g);\n\n writeln!(writer, \"Case #{}: {:.6}\", case_no, res).unwrap();\n\n}\n\n\n", "file_path": "google/src/codejam/year2008/round01/_1_fly_swatter/mod.rs", "rank": 28, "score": 276186.1431158562 }, { "content": "fn solve(case_no: usize, reader: &mut impl BufRead, writer: &mut impl Write) {\n\n let m = reader.parse_line();\n\n let mut ids: HashMap<String, usize> = HashMap::new();\n\n let pairs: Vec<Vec<usize>> = reader\n\n .collect_mat(m)\n\n .iter()\n\n .map(|row| {\n\n row.iter()\n\n .map(|s| {\n\n let size = ids.len();\n\n *ids.entry(s.to_string()).or_insert(size)\n\n })\n\n .collect()\n\n })\n\n .collect();\n\n let n = ids.len();\n\n let mut adj: Vec<Vec<usize>> = vec![vec![]; n];\n\n for pair in pairs {\n\n let u = pair[0];\n\n let v = pair[1];\n", "file_path": "google/src/kickstart/year2013/round01/_3_bad_horse/mod.rs", "rank": 29, "score": 276186.1431158562 }, { "content": "pub fn nsstring_as_str(nsstr: &objc::runtime::Object) -> &str {\n\n let bytes = unsafe {\n\n let bytes: *const std::os::raw::c_char = msg_send![nsstr, UTF8String];\n\n bytes as *const u8\n\n };\n\n let len: NSUInteger = unsafe { msg_send![nsstr, length] };\n\n unsafe {\n\n let bytes = std::slice::from_raw_parts(bytes, len as usize);\n\n std::str::from_utf8(bytes).unwrap()\n\n }\n\n}\n\n\n", "file_path": "metaldnn/src/metaldnn.rs", "rank": 30, "score": 273728.10245178844 }, { "content": "pub fn button_label(label: &str) -> HtmlButtonElement {\n\n let button: HtmlButtonElement = document()\n\n .create_element(\"button\")\n\n .expect(\"create_element\")\n\n .dyn_into()\n\n .expect(\"HtmlButtonElement\");\n\n button.set_attribute(\"aria-label\", label).unwrap();\n\n button\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 31, "score": 272310.91923936876 }, { "content": "pub fn div_class(class_name: &str) -> HtmlDivElement {\n\n let div: HtmlDivElement = document()\n\n .create_element(\"div\")\n\n .expect(\"create_element\")\n\n .dyn_into()\n\n .expect(\"HtmlDivElement\");\n\n div.set_class_name(class_name);\n\n div\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 32, "score": 269340.9536438597 }, { "content": "fn download_mnist(out_dir: &str) -> Result<(), io::Error> {\n\n let mut handle = Easy::new();\n\n for filename in FILES {\n\n let file_url = format!(\"{}/{}\", URL, filename);\n\n let file_path = format!(\"{}/{}\", out_dir, filename);\n\n let mut file = File::create(file_path)?;\n\n handle.url(&file_url).unwrap();\n\n handle.write_function(move |data| {\n\n file.write_all(data).unwrap();\n\n Ok(data.len())\n\n })?;\n\n handle.perform()?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mnist-data/build.rs", "rank": 33, "score": 268884.01069089177 }, { "content": "pub fn remove_children(node: &HtmlElement) -> Result<(), JsValue> {\n\n while let Some(child) = node.first_child() {\n\n node.remove_child(&child)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 34, "score": 262669.52499135985 }, { "content": "pub fn video_window(_id: &str, name: &str, video: HtmlVideoElement) -> HtmlDivElement {\n\n let title_bar_text = div_class(\"title-bar-text\");\n\n title_bar_text.set_text_content(Some(name));\n\n let title_bar_controls = div_class(\"title-bar-controls\");\n\n let minimize = button_label(\"Minimize\");\n\n let maximize = button_label(\"Maximize\");\n\n let close = button_label(\"Close\");\n\n title_bar_controls\n\n .append_with_node_3(&minimize, &maximize, &close)\n\n .expect(\"title_bar_controls\");\n\n let title_bar = div_class(\"title-bar\");\n\n title_bar\n\n .append_with_node_2(&title_bar_text, &title_bar_controls)\n\n .expect(\"title_bar\");\n\n let window_body = div_class(\"window-body\");\n\n window_body.append_with_node_1(&video).expect(\"window_body\");\n\n let root = div_class(\"window video\");\n\n root.append_with_node_2(&title_bar, &window_body)\n\n .expect(\"root\");\n\n root\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 35, "score": 262279.9526992228 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let start = it.next().unwrap().parse::<i32>().unwrap();\n\n let words: Vec<String> = it\n\n .next()\n\n .unwrap()\n\n .split(',')\n\n .map(|s| s.to_string())\n\n .collect();\n\n let ids1: Vec<i32> = words.iter().filter_map(|w| w.parse::<i32>().ok()).collect();\n\n let ids2: Vec<(i32, i32)> = words\n\n .iter()\n\n .enumerate()\n\n .filter_map(|(i, w)| {\n\n if let Ok(x) = w.parse::<i32>() {\n\n Some((i as i32, x))\n\n } else {\n\n None\n\n }\n\n })\n\n .collect();\n\n let res1 = earliest_bus(start, &ids1);\n\n let res2 = earliest_time(&ids2);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day13/mod.rs", "rank": 37, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let entries: Vec<i32> = it.map(|s| s.parse::<i32>().unwrap()).collect();\n\n let res1 = product_of_two_sum(&entries, 2020);\n\n let res2 = product_of_three_sum(entries, 2020);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day1/mod.rs", "rank": 38, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut codes: Vec<Code> = vec![];\n\n for line in it {\n\n let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();\n\n let val = words[1].parse::<i32>().unwrap();\n\n match words[0].as_str() {\n\n \"nop\" => {\n\n codes.push(Code::Nop(val));\n\n }\n\n \"acc\" => {\n\n codes.push(Code::Acc(val));\n\n }\n\n \"jmp\" => {\n\n codes.push(Code::Jmp(val));\n\n }\n\n _ => {}\n\n }\n\n }\n\n let mut vm = VM::new(codes.clone());\n", "file_path": "adventofcode/src/year2020/day8/mod.rs", "rank": 39, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut grid1: Vec<Vec<i32>> = vec![vec![0; 1000]; 1000];\n\n let mut grid2: Vec<Vec<i32>> = vec![vec![0; 1000]; 1000];\n\n for line in it {\n\n let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();\n\n let data = if words[1] == \"on\" || words[1] == \"off\" {\n\n (2, 4, if words[1] == \"on\" { 1 } else { 0 })\n\n } else {\n\n (1, 3, 2)\n\n };\n\n let cord1: Vec<usize> = words[data.0]\n\n .split(',')\n\n .map(|s| s.parse::<usize>().unwrap())\n\n .collect();\n\n let cord2: Vec<usize> = words[data.1]\n\n .split(',')\n\n .map(|s| s.parse::<usize>().unwrap())\n\n .collect();\n\n light1(&mut grid1, data.2, &cord1, &cord2);\n\n light2(&mut grid2, data.2, &cord1, &cord2);\n\n }\n\n let res1: i32 = grid1.iter().map(|r| r.iter().sum::<i32>()).sum();\n\n let res2: i32 = grid2.iter().map(|r| r.iter().sum::<i32>()).sum();\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day6/mod.rs", "rank": 40, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let nums: Vec<i32> = it\n\n .next()\n\n .unwrap()\n\n .split(',')\n\n .map(|s| s.parse::<i32>().unwrap())\n\n .collect();\n\n let res1 = sequence(&nums, 2020);\n\n let res2 = sequence(&nums, 30000000);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day15/mod.rs", "rank": 41, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut res1 = 0;\n\n let mut hs: HashSet<i32> = HashSet::new();\n\n for line in it {\n\n let mut id = 0;\n\n for c in line.chars() {\n\n let x = match c {\n\n 'F' => 0,\n\n 'B' => 1,\n\n 'L' => 0,\n\n 'R' => 1,\n\n _ => panic!(),\n\n };\n\n id <<= 1;\n\n id |= x;\n\n hs.insert(id);\n\n }\n\n res1 = res1.max(id);\n\n }\n\n let res2 = middle(&hs);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day5/mod.rs", "rank": 42, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut color: HashMap<(String, String), usize> = HashMap::new();\n\n let mut rules: Vec<Vec<String>> = vec![];\n\n for line in it {\n\n let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();\n\n rules.push(words);\n\n }\n\n for rule in &rules {\n\n let size = color.len();\n\n color\n\n .entry((rule[0].to_string(), rule[1].to_string()))\n\n .or_insert(size);\n\n }\n\n let k = color[&(\"shiny\".to_string(), \"gold\".to_string())];\n\n let n = color.len();\n\n let mut adj: Vec<Vec<(usize, i32)>> = vec![vec![]; n];\n\n\n\n for rule in &rules {\n\n if rule[4] == \"no\" {\n", "file_path": "adventofcode/src/year2020/day7/mod.rs", "rank": 43, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap()).peekable();\n\n let mut res1 = 0;\n\n let mut res2 = 0;\n\n while it.peek().is_some() {\n\n let mut set: HashSet<char> = HashSet::new();\n\n let mut count: HashMap<char, usize> = HashMap::new();\n\n let mut k: usize = 0;\n\n while let Some(line) = it.next() {\n\n if line.is_empty() {\n\n break;\n\n } else {\n\n k += 1;\n\n for c in line.chars() {\n\n set.insert(c);\n\n *count.entry(c).or_default() += 1;\n\n }\n\n }\n\n }\n\n res1 += set.len();\n\n res2 += count.values().filter(|&&v| v == k).count();\n\n }\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n\nadventofcode!(test, \"input.txt\", \"output.txt\");\n", "file_path": "adventofcode/src/year2020/day6/mod.rs", "rank": 44, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut res1 = 0;\n\n let mut res2 = 0;\n\n for line in it {\n\n if nice1(&line) {\n\n res1 += 1;\n\n }\n\n if nice2(&line) {\n\n res2 += 1;\n\n }\n\n }\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day5/mod.rs", "rank": 45, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let line = it.next().unwrap();\n\n\n\n let res1 = search(1000000, &line, \"00000\");\n\n let res2 = search(10000000, &line, \"000000\");\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day4/mod.rs", "rank": 46, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let mut valid_ranges: Vec<[i32; 4]> = vec![];\n\n let mut departure_fields: Vec<usize> = vec![];\n\n let mut fid = 0;\n\n while let Some(line) = it.next() {\n\n if line.is_empty() {\n\n break;\n\n } else {\n\n let parts: Vec<_> = line.split_whitespace().collect();\n\n if parts[0] == \"departure\" {\n\n departure_fields.push(fid);\n\n }\n\n let n = parts.len();\n\n let r1: Vec<i32> = parts[n - 3]\n\n .split('-')\n\n .map(|w| w.parse::<i32>().unwrap())\n\n .collect();\n\n let r2: Vec<i32> = parts[n - 1]\n\n .split('-')\n", "file_path": "adventofcode/src/year2020/day16/mod.rs", "rank": 47, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut active1: HashSet<(i32, i32, i32)> = HashSet::new();\n\n let mut active2: HashSet<(i32, i32, i32, i32)> = HashSet::new();\n\n for (i, line) in it.enumerate() {\n\n for (j, c) in line.chars().enumerate() {\n\n if c == '#' {\n\n active1.insert((i as i32, j as i32, 0));\n\n active2.insert((i as i32, j as i32, 0, 0));\n\n }\n\n }\n\n }\n\n let res1 = cycle1(&active1, 6);\n\n let res2 = cycle2(&active2, 6);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day17/mod.rs", "rank": 48, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n #[allow(clippy::redundant_closure)]\n\n let instructions: Vec<Instruction> = it.map(|s| Instruction::new(s)).collect();\n\n let res1 = manhattan_distance1(&instructions);\n\n let res2 = manhattan_distance2(&instructions);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day12/mod.rs", "rank": 49, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut quote = 0;\n\n let mut escape = 0;\n\n let mut ascii = 0;\n\n let mut lines = 0;\n\n for line in it {\n\n let mut lit = line.chars();\n\n while let Some(c) = lit.next() {\n\n match c {\n\n '\"' => {\n\n quote += 1;\n\n }\n\n '\\\\' => {\n\n if let Some('x') = lit.next() {\n\n ascii += 1;\n\n lit.next();\n\n lit.next();\n\n } else {\n\n escape += 1;\n", "file_path": "adventofcode/src/year2015/day8/mod.rs", "rank": 50, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut grid: Vec<Vec<char>> = vec![];\n\n for line in it {\n\n grid.push(line.chars().collect());\n\n }\n\n\n\n let res1 = number_of_trees(&grid, 1, 1);\n\n let res2 = number_of_trees(&grid, 3, 1);\n\n let res3 = number_of_trees(&grid, 5, 1);\n\n let res4 = number_of_trees(&grid, 7, 1);\n\n let res5 = number_of_trees(&grid, 1, 2);\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n writeln!(writer, \"{}\", res1 * res2 * res3 * res4 * res5).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day3/mod.rs", "rank": 51, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let line = it.next().unwrap();\n\n let val = serde_json::from_str(&line).unwrap();\n\n let res1 = dfs1(&val);\n\n let red: Value = json!(\"red\");\n\n let res2 = dfs2(&val, &red);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day12/mod.rs", "rank": 52, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut res1 = 0;\n\n let mut res2 = 0;\n\n for line in it {\n\n let mut cit = line.chars();\n\n let mut lo = 0;\n\n let mut hi = 0;\n\n while let Some(c) = cit.next() {\n\n if c == '-' {\n\n break;\n\n } else {\n\n lo *= 10;\n\n lo += (c as u8 - b'0') as usize;\n\n }\n\n }\n\n while let Some(c) = cit.next() {\n\n if c == ' ' {\n\n break;\n\n } else {\n", "file_path": "adventofcode/src/year2020/day2/mod.rs", "rank": 53, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap()).peekable();\n\n let valid_set: HashSet<String> =\n\n HashSet::from_iter(vec_string![\"byr\", \"iyr\", \"eyr\", \"hgt\", \"hcl\", \"ecl\", \"pid\"]);\n\n let mut res1 = 0;\n\n let mut res2 = 0;\n\n while it.peek().is_some() {\n\n let mut set1: HashSet<String> = HashSet::new();\n\n let mut set2: HashSet<String> = HashSet::new();\n\n while let Some(line) = it.next() {\n\n if line.is_empty() {\n\n break;\n\n } else {\n\n for pair in line.split_whitespace() {\n\n let mut pit = pair.split(':');\n\n let field = pit.next().unwrap();\n\n let value = pit.next().unwrap();\n\n set1.insert(field.to_string());\n\n if match field {\n\n \"byr\" => byr(value),\n", "file_path": "adventofcode/src/year2020/day4/mod.rs", "rank": 54, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let mut rules: HashMap<i32, Rule> = HashMap::new();\n\n let mut messages: Vec<Vec<char>> = vec![];\n\n while let Some(line) = it.next() {\n\n if line.is_empty() {\n\n break;\n\n }\n\n let parts: Vec<String> = line.split(':').map(|s| s.to_string()).collect();\n\n let lhs = parts[0].parse::<i32>().unwrap();\n\n let words: Vec<String> = parts[1].split_whitespace().map(|s| s.to_string()).collect();\n\n if words[0].parse::<i32>().is_err() {\n\n let v: Vec<char> = words[0].chars().collect();\n\n rules.insert(lhs, Rule::Single(v[1]));\n\n } else {\n\n let multi: Vec<Vec<i32>> = words\n\n .split(|x| x == \"|\")\n\n .map(|v| v.iter().map(|x| x.parse::<i32>().unwrap()).collect())\n\n .collect();\n\n rules.insert(lhs, Rule::Multi(multi));\n", "file_path": "adventofcode/src/year2020/day19/mod.rs", "rank": 55, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let adapters: Vec<i32> = it.map(|s| s.parse::<i32>().unwrap()).collect();\n\n let res1 = part1(&adapters);\n\n let res2 = part2(&adapters);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day10/mod.rs", "rank": 56, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut res1 = 0;\n\n let mut res2 = 0;\n\n for line in it {\n\n let sides: Vec<i32> = line.split('x').map(|s| s.parse::<i32>().unwrap()).collect();\n\n res1 += paper(&sides);\n\n res2 += ribbon(&sides);\n\n }\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day2/mod.rs", "rank": 57, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut stmt: HashMap<Tok, Vec<Tok>> = HashMap::new();\n\n let mut adj: HashMap<Tok, Vec<Tok>> = HashMap::new();\n\n let mut values1: HashMap<Tok, u16> = HashMap::new();\n\n let mut values2: HashMap<Tok, u16> = HashMap::new();\n\n for line in it {\n\n let mut tokens: Vec<Tok> = line.split_whitespace().map(parse_token).collect();\n\n let last = tokens.pop().unwrap();\n\n tokens.pop();\n\n stmt.insert(last.clone(), tokens.to_vec());\n\n for i in 0..tokens.len() {\n\n if let Tok::Id(_) = tokens[i] {\n\n adj.entry(tokens[i].clone()).or_default().push(last.clone());\n\n }\n\n }\n\n }\n\n let mut ovalues = HashMap::new();\n\n eval(&mut values1, &adj, &stmt, &ovalues);\n\n let res1 = *values1.entry(Tok::Id(\"a\".to_string())).or_default();\n\n ovalues.insert(Tok::Id(\"b\".to_string()), res1);\n\n eval(&mut values2, &adj, &stmt, &ovalues);\n\n let res2 = *values2.entry(Tok::Id(\"a\".to_string())).or_default();\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day7/mod.rs", "rank": 58, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let nums: Vec<i64> = it.map(|s| s.parse::<i64>().unwrap()).collect();\n\n let size = 25;\n\n let res1 = invalid_number(&nums, size);\n\n let res2 = encryption_weakness(&nums, res1);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day9/mod.rs", "rank": 59, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let line = it.next().unwrap();\n\n let res1: String = next_pass(&line);\n\n let res2: String = next_pass(&res1);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day11/mod.rs", "rank": 60, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let grid: Vec<Vec<char>> = it.map(|s| s.chars().collect()).collect();\n\n let res1 = simulate1(grid.clone());\n\n let res2 = simulate2(grid);\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day11/mod.rs", "rank": 61, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let mut s = it.next().unwrap();\n\n let mut res1 = 0;\n\n for i in 0..50 {\n\n s = look_and_say(s);\n\n if i == 39 {\n\n res1 = s.len();\n\n }\n\n }\n\n let res2 = s.len();\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day10/mod.rs", "rank": 62, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut instructions: Vec<Instruction> = vec![];\n\n for line in it {\n\n let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();\n\n if words[0] == \"mask\" {\n\n let mut zero = 0u64;\n\n let mut one = 0u64;\n\n let mut floating = 0u64;\n\n let mut mask = words[2].to_string();\n\n for i in 0..36 {\n\n let c = mask.pop().unwrap();\n\n if c == '0' {\n\n zero |= 1 << i;\n\n }\n\n if c == '1' {\n\n one |= 1 << i;\n\n }\n\n if c == 'X' {\n\n floating |= 1 << i;\n", "file_path": "adventofcode/src/year2020/day14/mod.rs", "rank": 63, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut exprs: Vec<Vec<Tok>> = vec![];\n\n for line in it {\n\n let tokens = parse_expr(&line);\n\n exprs.push(tokens);\n\n }\n\n let res1: i64 = exprs.iter().map(|e| eval_expr1(e)).sum();\n\n let res2: i64 = exprs.iter().map(|e| eval_expr2(e)).sum();\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2020/day18/mod.rs", "rank": 64, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let line = it.next().unwrap();\n\n let res1: i32 = line.chars().map(|c| if c == '(' { 1 } else { -1 }).sum();\n\n let mut floor = 0;\n\n let mut res2 = 0;\n\n for (i, c) in line.char_indices() {\n\n res2 = i + 1;\n\n floor += if c == '(' { 1 } else { -1 };\n\n if floor == -1 {\n\n break;\n\n }\n\n }\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n\nadventofcode!(test, \"input.txt\", \"output.txt\");\n", "file_path": "adventofcode/src/year2015/day1/mod.rs", "rank": 65, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let mut it = reader.lines().map(|l| l.unwrap());\n\n let line = it.next().unwrap();\n\n let mut x = 0;\n\n let mut y = 0;\n\n let mut hs1: HashSet<(i32, i32)> = HashSet::new();\n\n let mut hs2: HashSet<(i32, i32)> = HashSet::new();\n\n let mut xs: [i32; 2] = [0, 0];\n\n let mut ys: [i32; 2] = [0, 0];\n\n hs1.insert((0, 0));\n\n hs2.insert((0, 0));\n\n for (i, c) in line.char_indices() {\n\n let j = i % 2;\n\n match c {\n\n '>' => {\n\n x += 1;\n\n xs[j] += 1;\n\n }\n\n '<' => {\n\n x -= 1;\n", "file_path": "adventofcode/src/year2015/day3/mod.rs", "rank": 66, "score": 259914.91022880492 }, { "content": "pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {\n\n let it = reader.lines().map(|l| l.unwrap());\n\n let mut id: HashMap<String, usize> = HashMap::new();\n\n let mut adj: HashMap<usize, Vec<(usize, i32)>> = HashMap::new();\n\n for line in it {\n\n let words: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect();\n\n let size = id.len();\n\n let u = *id.entry(words[0].clone()).or_insert(size);\n\n let size = id.len();\n\n let v = *id.entry(words[2].clone()).or_insert(size);\n\n let val = words[4].parse::<i32>().unwrap();\n\n adj.entry(u).or_default().push((v, val));\n\n adj.entry(v).or_default().push((u, val));\n\n }\n\n let n = id.len();\n\n let mut res1 = std::i32::MAX;\n\n let mut res2 = 0;\n\n for i in 0..n {\n\n let mut visited = HashSet::new();\n\n visited.insert(i);\n\n dfs(i, 0, &mut visited, &mut res1, &mut res2, &adj, n);\n\n visited.remove(&i);\n\n }\n\n writeln!(writer, \"{}\", res1).unwrap();\n\n writeln!(writer, \"{}\", res2).unwrap();\n\n}\n\n\n", "file_path": "adventofcode/src/year2015/day9/mod.rs", "rank": 67, "score": 259914.91022880492 }, { "content": "fn decode_mnist(out_dir: &str) -> Result<MNIST, io::Error> {\n\n let train_images_gz = fs::read(format!(\"{}/{}\", out_dir, FILES[0]))?;\n\n assert_eq!(train_images_gz.len(), 9912422);\n\n let train_labels_gz = fs::read(format!(\"{}/{}\", out_dir, FILES[1]))?;\n\n assert_eq!(train_labels_gz.len(), 28881);\n\n let test_images_gz = fs::read(format!(\"{}/{}\", out_dir, FILES[2]))?;\n\n assert_eq!(test_images_gz.len(), 1648877);\n\n let test_labels_gz = fs::read(format!(\"{}/{}\", out_dir, FILES[3]))?;\n\n assert_eq!(test_labels_gz.len(), 4542);\n\n let train_images = decode_images(&train_images_gz, N_TRING as u32)?;\n\n assert_eq!(train_images.len(), N_TRING);\n\n let test_images = decode_images(&test_images_gz, N_TEST as u32)?;\n\n assert_eq!(test_images.len(), N_TEST);\n\n let train_labels = decode_labels(&train_labels_gz, N_TRING as u32)?;\n\n assert_eq!(train_labels.len(), N_TRING);\n\n let test_labels = decode_labels(&test_labels_gz, N_TEST as u32)?;\n\n assert_eq!(test_labels.len(), N_TEST);\n\n Ok(MNIST {\n\n train_images,\n\n test_images,\n\n train_labels,\n\n test_labels,\n\n })\n\n}\n\n\n", "file_path": "mnist-data/build.rs", "rank": 68, "score": 259812.41022156295 }, { "content": "pub fn load_mnist_data() -> Result<MnistData, io::Error> {\n\n let mnist = bincode::deserialize(BYTES).unwrap();\n\n Ok(mnist)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n use crate::*;\n\n let mnist = load_mnist_data().unwrap();\n\n assert_eq!(mnist.train_images.len(), 60000);\n\n }\n\n}\n", "file_path": "mnist-data/src/lib.rs", "rank": 69, "score": 259812.07979022083 }, { "content": "fn exact_matches(a: &str, b: &str) -> usize {\n\n a.chars().zip(b.chars()).filter(|(a, b)| a == b).count()\n\n}\n\n\n\nimpl Solution {\n\n fn find_secret_word(words: Vec<String>, master: &Master) {\n\n let n = words.len();\n\n let mut matrix: Vec<Vec<usize>> = vec![vec![0; n]; n];\n\n let mut excluded: Vec<bool> = vec![false; n];\n\n for i in 0..n {\n\n for j in i + 1..n {\n\n let count = exact_matches(&words[i], &words[j]);\n\n matrix[i][j] = count;\n\n matrix[j][i] = count;\n\n }\n\n }\n\n let mut rng = thread_rng();\n\n\n\n for _ in 0..10 {\n\n let mut id = rng.gen_range(0, n);\n", "file_path": "leetcode/src/d8/_843_guess_the_word.rs", "rank": 70, "score": 258294.86032730906 }, { "content": "fn get_results(objects: Vec<String>, pool: &SqlitePool) -> Result<Vec<QueryResult>> {\n\n use rustgym_schema::schema::adventofcode_description::dsl::*;\n\n use rustgym_schema::schema::google_problem::dsl::*;\n\n use rustgym_schema::schema::leetcode_question::dsl::*;\n\n let mut res = vec![];\n\n let conn = pool.get()?;\n\n for object in objects {\n\n let parts: Vec<&str> = object.split('_').collect();\n\n match parts[0] {\n\n \"leetcode\" => {\n\n let id_ = parts[1].parse::<i32>()?;\n\n let question: LeetcodeQuestion = leetcode_question\n\n .filter(rustgym_schema::schema::leetcode_question::dsl::id.eq(id_))\n\n .first(&conn)?;\n\n let query_result = QueryResult::new(\n\n parts[1].to_string(),\n\n question.title.to_string(),\n\n question.href(),\n\n question.from(),\n\n );\n", "file_path": "server/src/agents/search.rs", "rank": 71, "score": 257696.06764875233 }, { "content": "pub fn rom_md5(header_size: usize, data: &[u8]) -> String {\n\n let digest = md5::compute(&data[header_size..]);\n\n format!(\"{:X}\", digest)\n\n}\n\n\n", "file_path": "openvgdb/src/lib.rs", "rank": 72, "score": 256454.4698787029 }, { "content": "pub fn update_session(session: Session) -> Result<SessionData, Error> {\n\n let count = if let Some(count) = session.get::<i32>(\"count\")? {\n\n count + 1\n\n } else {\n\n 1\n\n };\n\n session.set(\"count\", count)?;\n\n\n\n let name = if let Some(name) = session.get::<String>(\"name\")? {\n\n name\n\n } else {\n\n let n = CHARACTERS.len();\n\n let k = thread_rng().gen::<usize>();\n\n let name = CHARACTERS[k % n];\n\n name.to_string()\n\n };\n\n session.set(\"name\", name.to_string())?;\n\n\n\n let uuid = if let Some(uuid) = session.get::<Uuid>(\"uuid\")? {\n\n uuid\n\n } else {\n\n Uuid::new_v4()\n\n };\n\n session.set(\"uuid\", uuid)?;\n\n\n\n let session_data = SessionData { count, name, uuid };\n\n Ok(session_data)\n\n}\n", "file_path": "server/src/session_data.rs", "rank": 73, "score": 253836.39506192727 }, { "content": "pub fn generate_turn_rest_api_cred(\n\n name: &str,\n\n turn_static_auth_secret: &str,\n\n ttl: i64,\n\n) -> (String, String) {\n\n let now = Utc::now();\n\n let timestamp = now.timestamp() + ttl;\n\n let usercombo = format!(\"{}:{}\", timestamp, name);\n\n let signed_key = hmac::Key::new(\n\n hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,\n\n turn_static_auth_secret.as_bytes(),\n\n );\n\n let signature = hmac::sign(&signed_key, usercombo.as_bytes());\n\n let credential = BASE64.encode(signature.as_ref());\n\n (usercombo, credential)\n\n}\n\n\n\npub async fn ws_index(\n\n data: web::Data<AppData>,\n\n req: HttpRequest,\n", "file_path": "server/src/agents/websocket.rs", "rank": 74, "score": 251658.17656781976 }, { "content": "fn create_mnist(out_dir: &str, mnist: MNIST) -> Result<(), io::Error> {\n\n let bytes = bincode::serialize(&mnist).unwrap();\n\n let output_file = format!(\"{}/{}\", out_dir, \"mnist.bin\");\n\n fs::write(output_file, bytes)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "mnist-data/build.rs", "rank": 75, "score": 251466.22241619148 }, { "content": "pub fn local_video() -> HtmlVideoElement {\n\n document()\n\n .get_element_by_id(\"local_video\")\n\n .expect(\"get_element_by_id\")\n\n .dyn_into()\n\n .expect(\"HtmlVideoElement\")\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 76, "score": 248440.2889371179 }, { "content": "pub fn remote_videos() -> HtmlDivElement {\n\n document()\n\n .get_element_by_id(\"remote_videos\")\n\n .expect(\"get_element_by_id\")\n\n .dyn_into()\n\n .expect(\"HtmlDivElement\")\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 77, "score": 248438.8484512982 }, { "content": "pub fn search_results() -> HtmlTableSectionElement {\n\n document()\n\n .get_element_by_id(\"search_results\")\n\n .expect(\"get_element_by_id\")\n\n .dyn_into()\n\n .expect(\"HtmlTableSectionElement\")\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 78, "score": 245212.62163988283 }, { "content": "pub fn start_button() -> HtmlButtonElement {\n\n document()\n\n .get_element_by_id(\"start_button\")\n\n .expect(\"get_element_by_id\")\n\n .dyn_into()\n\n .expect(\"HtmlButtonElement\")\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 80, "score": 240895.48257265848 }, { "content": "pub fn request_animation_frame(f: &Closure<dyn FnMut()>) {\n\n let window: Window = window().expect(\"window\");\n\n window\n\n .request_animation_frame(f.as_ref().unchecked_ref())\n\n .expect(\"should register `requestAnimationFrame` OK\");\n\n}\n\n\n", "file_path": "wasm/src/utils.rs", "rank": 81, "score": 240746.0726295826 }, { "content": "pub fn conn(pool: web::Data<SqlitePool>) -> Result<SqlitePooledConnection, Error> {\n\n pool.get().map_err(ErrorInternalServerError)\n\n}\n", "file_path": "server/src/db.rs", "rank": 83, "score": 238211.99663479862 }, { "content": "fn cleanup(html: String) -> String {\n\n let text = html2text::from_read(html.as_bytes(), html.len());\n\n let text: String = text\n\n .chars()\n\n .map(|c| if c.is_ascii_alphabetic() { c } else { ' ' })\n\n .collect();\n\n text\n\n}\n\n\n", "file_path": "ingest/src/main.rs", "rank": 84, "score": 219987.28024913784 }, { "content": "fn cleanup(text: String) -> String {\n\n text.chars()\n\n .map(|c| if c.is_ascii_alphabetic() { c } else { ' ' })\n\n .collect()\n\n}\n\n\n", "file_path": "server/src/agents/search.rs", "rank": 85, "score": 217946.42970826873 }, { "content": "struct Solution;\n\n\n\nimpl Solution {\n\n fn di_string_match(s: String) -> Vec<i32> {\n\n let n = s.len() + 1;\n\n let nums: Vec<i32> = (0..n).map(|i| i as i32).collect();\n\n let mut res: Vec<i32> = vec![];\n\n let mut l = 0;\n\n let mut r = n - 1;\n\n for c in s.chars() {\n\n match c {\n\n 'I' => {\n\n res.push(nums[l]);\n\n l += 1;\n\n }\n\n 'D' => {\n\n res.push(nums[r]);\n\n r -= 1;\n\n }\n\n _ => (),\n\n }\n\n }\n\n res.push(nums[l]);\n\n res\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d9/_942_di_string_match.rs", "rank": 86, "score": 216842.22147831327 }, { "content": "struct Solution;\n\n\n\nimpl Solution {\n\n fn string_matching(words: Vec<String>) -> Vec<String> {\n\n let n = words.len();\n\n let mut res = vec![];\n\n for i in 0..n {\n\n let mut found = false;\n\n for j in 0..n {\n\n if !found && i != j && words[j].contains(&words[i]) {\n\n found = true;\n\n }\n\n }\n\n if found {\n\n res.push(words[i].to_string());\n\n }\n\n }\n\n res\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d14/_1408_string_matching_in_an_array.rs", "rank": 87, "score": 216842.22147831327 }, { "content": "struct Solution;\n\n\n\nimpl Solution {\n\n fn repeated_string_match(a: String, b: String) -> i32 {\n\n let mut s = String::new();\n\n let n = a.len();\n\n let m = b.len();\n\n if n == 0 || m == 0 {\n\n return -1;\n\n }\n\n let mut k = m / n;\n\n if k * n < m {\n\n k += 1;\n\n }\n\n for _ in 0..k {\n\n s += &a;\n\n }\n\n if s.contains(&b) {\n\n return k as i32;\n\n }\n\n s += &a;\n\n if s.contains(&b) {\n\n return (k + 1) as i32;\n\n }\n\n -1\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d6/_686_repeated_string_match.rs", "rank": 88, "score": 216842.22147831327 }, { "content": "fn look_and_say(s: String) -> String {\n\n let mut it = s.chars().peekable();\n\n let mut res = \"\".to_string();\n\n while let Some(c) = it.next() {\n\n let mut count = 1;\n\n while let Some(&next_c) = it.peek() {\n\n if next_c == c {\n\n it.next();\n\n count += 1;\n\n } else {\n\n break;\n\n }\n\n }\n\n res += &format!(\"{}{}\", count, c);\n\n }\n\n res\n\n}\n\n\n\nadventofcode_ignore!(test, \"input.txt\", \"output.txt\");\n", "file_path": "adventofcode/src/year2015/day10/mod.rs", "rank": 89, "score": 215975.57291199447 }, { "content": "#[test]\n\nfn test() {\n\n let words = vec_string![\"mass\", \"as\", \"hero\", \"superhero\"];\n\n let res = vec_string![\"as\", \"hero\"];\n\n assert_eq!(Solution::string_matching(words), res);\n\n let words = vec_string![\"leetcode\", \"et\", \"code\"];\n\n let res = vec_string![\"et\", \"code\"];\n\n assert_eq!(Solution::string_matching(words), res);\n\n let words = vec_string![\"blue\", \"green\", \"bu\"];\n\n let res = vec_string![];\n\n assert_eq!(Solution::string_matching(words), res);\n\n}\n", "file_path": "leetcode/src/d14/_1408_string_matching_in_an_array.rs", "rank": 90, "score": 215527.68943882993 }, { "content": "#[test]\n\nfn test() {\n\n let a = \"abcd\".to_string();\n\n let b = \"cdabcdab\".to_string();\n\n assert_eq!(Solution::repeated_string_match(a, b), 3);\n\n}\n", "file_path": "leetcode/src/d6/_686_repeated_string_match.rs", "rank": 91, "score": 215527.68943882993 }, { "content": "#[test]\n\nfn test() {\n\n let s = \"IDID\".to_string();\n\n let res = vec![0, 4, 1, 3, 2];\n\n assert_eq!(Solution::di_string_match(s), res);\n\n let s = \"III\".to_string();\n\n let res = vec![0, 1, 2, 3];\n\n assert_eq!(Solution::di_string_match(s), res);\n\n let s = \"DDI\".to_string();\n\n let res = vec![3, 2, 0, 1];\n\n assert_eq!(Solution::di_string_match(s), res);\n\n}\n", "file_path": "leetcode/src/d9/_942_di_string_match.rs", "rank": 92, "score": 215527.68943882993 }, { "content": "struct Solution;\n\n\n\nimpl Solution {\n\n fn count_matches(items: Vec<Vec<String>>, rule_key: String, rule_value: String) -> i32 {\n\n let i = match rule_key.as_str() {\n\n \"type\" => 0,\n\n \"color\" => 1,\n\n \"name\" => 2,\n\n _ => panic!(),\n\n };\n\n items\n\n .into_iter()\n\n .filter(|item| item[i] == rule_value)\n\n .count() as i32\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d17/_1773_count_items_matching_a_rule.rs", "rank": 93, "score": 213618.54294701718 }, { "content": "struct Solution;\n\n\n\nimpl Solution {\n\n fn minimum_moves(s: String) -> i32 {\n\n let mut s: Vec<char> = s.chars().collect();\n\n let n = s.len();\n\n let mut res = 0;\n\n for i in 0..n {\n\n if s[i] == 'X' {\n\n res += 1;\n\n s[i] = 'O';\n\n if i + 1 < n {\n\n s[i + 1] = 'O';\n\n }\n\n if i + 2 < n {\n\n s[i + 2] = 'O';\n\n }\n\n }\n\n }\n\n res\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d20/_2027_minimum_moves_to_convert_string.rs", "rank": 94, "score": 213336.46047053055 }, { "content": "struct Solution;\n\n\n\nuse std::collections::HashMap;\n\n\n\nimpl Solution {\n\n fn can_convert_string(s: String, t: String, k: i32) -> bool {\n\n let n = s.len();\n\n let m = t.len();\n\n if n != m {\n\n return false;\n\n }\n\n let s: Vec<i32> = s.bytes().map(|b| (b - b'a') as i32).collect();\n\n let t: Vec<i32> = t.bytes().map(|b| (b - b'a') as i32).collect();\n\n let mut count: HashMap<i32, i32> = HashMap::new();\n\n for i in 0..n {\n\n if s[i] == t[i] {\n\n continue;\n\n }\n\n *count.entry((26 + t[i] - s[i]) % 26).or_default() += 1;\n\n }\n\n let mut max = 0;\n\n for (k, v) in count {\n\n max = max.max((v - 1) * 26 + k);\n\n }\n\n max <= k\n\n }\n\n}\n\n\n", "file_path": "leetcode/src/d15/_1540_can_convert_string_in_k_moves.rs", "rank": 95, "score": 213336.46047053055 }, { "content": "#[test]\n\nfn test() {\n\n let items = vec_vec_string![\n\n [\"phone\", \"blue\", \"pixel\"],\n\n [\"computer\", \"silver\", \"lenovo\"],\n\n [\"phone\", \"gold\", \"iphone\"]\n\n ];\n\n let rule_key = \"color\".to_string();\n\n let rule_value = \"silver\".to_string();\n\n let res = 1;\n\n assert_eq!(Solution::count_matches(items, rule_key, rule_value), res);\n\n let items = vec_vec_string![\n\n [\"phone\", \"blue\", \"pixel\"],\n\n [\"computer\", \"silver\", \"phone\"],\n\n [\"phone\", \"gold\", \"iphone\"]\n\n ];\n\n let rule_key = \"type\".to_string();\n\n let rule_value = \"phone\".to_string();\n\n let res = 2;\n\n assert_eq!(Solution::count_matches(items, rule_key, rule_value), res);\n\n}\n", "file_path": "leetcode/src/d17/_1773_count_items_matching_a_rule.rs", "rank": 96, "score": 212310.290837866 }, { "content": "#[test]\n\nfn test() {\n\n let s = \"input\".to_string();\n\n let t = \"ouput\".to_string();\n\n let k = 9;\n\n let res = true;\n\n assert_eq!(Solution::can_convert_string(s, t, k), res);\n\n let s = \"abc\".to_string();\n\n let t = \"bcd\".to_string();\n\n let k = 10;\n\n let res = false;\n\n assert_eq!(Solution::can_convert_string(s, t, k), res);\n\n let s = \"aab\".to_string();\n\n let t = \"bbb\".to_string();\n\n let k = 27;\n\n let res = true;\n\n assert_eq!(Solution::can_convert_string(s, t, k), res);\n\n}\n", "file_path": "leetcode/src/d15/_1540_can_convert_string_in_k_moves.rs", "rank": 97, "score": 212028.20836137937 }, { "content": "#[test]\n\nfn test() {\n\n let s = \"XXX\".to_string();\n\n let res = 1;\n\n assert_eq!(Solution::minimum_moves(s), res);\n\n let s = \"XXOX\".to_string();\n\n let res = 2;\n\n assert_eq!(Solution::minimum_moves(s), res);\n\n let s = \"OOOO\".to_string();\n\n let res = 0;\n\n assert_eq!(Solution::minimum_moves(s), res);\n\n}\n", "file_path": "leetcode/src/d20/_2027_minimum_moves_to_convert_string.rs", "rank": 98, "score": 212028.20836137937 }, { "content": "fn main() -> Result<()> {\n\n use rustgym_schema::schema::adventofcode_description::dsl::*;\n\n use rustgym_schema::schema::google_problem::dsl::*;\n\n use rustgym_schema::schema::leetcode_description::dsl::*;\n\n use rustgym_schema::schema::leetcode_question::dsl::*;\n\n\n\n let channel = IngestChannel::start(SONIC_URL, SONIC_PASS)?;\n\n let conn = SqliteConnection::establish(DATABASE_URL)?;\n\n\n\n let leetcode_questions: Vec<LeetcodeQuestion> = leetcode_question.load(&conn)?;\n\n for item in leetcode_questions {\n\n let object = format!(\"leetcode_{}\", item.id);\n\n let text = cleanup(item.title);\n\n channel.push(SONIC_COLLECTION, SONIC_BUCKET, &object, &text)?;\n\n }\n\n\n\n let leetcode_descriptions: Vec<LeetcodeDescription> = leetcode_description.load(&conn)?;\n\n for item in leetcode_descriptions {\n\n let object = format!(\"leetcode_{}\", item.id);\n\n let text = cleanup(item.html);\n", "file_path": "ingest/src/main.rs", "rank": 99, "score": 210699.2567151998 } ]
Rust
src/logging.rs
Cerber-Ursi/batch_run
61a24e0ccc1fdd3f1e67ebb5b12735ba007a0747
use termcolor::{ Color::{self, *}, WriteColor, }; use termcolor_output::colored; use crate::entry::{Entry, Expected}; use crate::normalize; use std::io; use std::path::Path; pub(crate) fn no_entries(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}No entries were provided to runner. Maybe the files are not created yet, or the glob path is wrong.\n{}", reset!(), fg!(Some(Yellow)), reset!() )?; Ok(()) } pub(crate) fn ok(log: &mut impl WriteColor) -> io::Result<()> { colored!(log, "{}ok{}\n", fg!(Some(Green)), reset!()) } pub(crate) fn log_entry_start(entry: &Entry, log: &mut impl WriteColor) -> io::Result<()> { let display_name = entry .path() .file_name() .unwrap_or_else(|| entry.path().as_os_str()) .to_string_lossy(); let expected = match entry.expected() { Expected::RunMatch => " [should run and generate output]", Expected::CompileFail => " [should fail to compile]", }; write_entry_header(log, &display_name, expected) } pub(crate) fn log_entry_fail_to_start(entry: &Entry, buf: &mut impl WriteColor) -> io::Result<()> { write_entry_header(buf, &entry.path().as_os_str().to_string_lossy(), "") } fn write_entry_header(buf: &mut impl WriteColor, name: &str, expected: &str) -> io::Result<()> { colored!( buf, "{}batch entry {}{}{}{} ... ", reset!(), bold!(true), name, bold!(false), expected ) } pub(crate) fn log_wip_write( buf: &mut impl WriteColor, wip_path: &Path, path: &Path, string: &str, ) -> io::Result<()> { let wip_path = wip_path.to_string_lossy(); let path = path.to_string_lossy(); colored!( buf, "{}{}wip\n\nNOTE{}: writing the following output to `{}`.\nMove this file to {} to accept it as correct.\n", reset!(), fg!(Some(Yellow)), reset!(), wip_path, path, )?; snippet(buf, Yellow, string) } pub(crate) fn log_overwrite( buf: &mut impl WriteColor, path: &Path, string: &str, ) -> io::Result<()> { let path = path.to_string_lossy(); colored!( buf, "{}{}wip\n\nNOTE{}: writing the following output to {}.", reset!(), fg!(Some(Yellow)), reset!(), path )?; snippet(buf, Yellow, string) } pub(crate) fn mismatch(log: &mut impl WriteColor, expected: &str, actual: &str) -> io::Result<()> { colored!( log, "{}{}mismatch{}\n\n", bold!(true), fg!(Some(Red)), reset!() )?; log_snapshot(log, Blue, "EXPECTED", expected.as_bytes())?; log_snapshot(log, Red, "ACTUAL", actual.as_bytes())?; Ok(()) } pub(crate) fn build_status_mismatch(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}{}error: {}", reset!(), bold!(true), fg!(Some(Red)), bold!(false) ) } pub(crate) fn unexpected_build_success(log: &mut impl WriteColor) -> io::Result<()> { build_status_mismatch(log)?; colored!( log, "Expected test case to fail to compile, but it succeeded.{}\n", reset!() ) } pub(crate) fn unexpected_build_error(log: &mut impl WriteColor, error: &[u8]) -> io::Result<()> { build_status_mismatch(log)?; colored!(log, "Entry failed to build; compiler output:{}\n", reset!())?; snippet(log, Red, &normalize::trim(error)) } pub(crate) fn log_snapshot( log: &mut impl WriteColor, color: Color, header: &str, snapshot: &[u8], ) -> io::Result<()> { if !snapshot.is_empty() { colored!(log, "{}{}{}:", bold!(true), fg!(Some(color)), header)?; snippet(log, color, &normalize::trim(snapshot))?; } Ok(()) } fn snippet(log: &mut impl WriteColor, color: Color, content: &str) -> io::Result<()> { let dotted_line = "┈".repeat(60); colored!(log, "\n{}{}{}\n", reset!(), fg!(Some(color)), dotted_line)?; for line in content.lines() { colored!(log, "{}{}\n", fg!(Some(color)), line)?; } colored!(log, "{}{}{}\n", fg!(Some(color)), dotted_line, reset!()) }
use termcolor::{ Color::{self, *}, WriteColor, }; use termcolor_output::colored; use crate::entry::{Entry, Expected}; use crate::normalize; use std::io; use std::path::Path; pub(crate) fn no_entries(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}No entries were provided to runner. Maybe the files are not created yet, or the glob path is wrong.\n{}", reset!(), fg!(Some(Yellow)), reset!() )?; Ok(()) } pub(crate) fn ok(log: &mut impl WriteColor) -> io::Result<()> { colored!(log, "{}ok{}\n", fg!(Some(Green)), reset!()) } pub(crate) fn log_entry_start(entry: &Entry, log: &mut impl WriteColor) -> io::Result<()> { let display_name = entry .path() .file_name() .unwrap_or_else(|| entry.path().as_os_str()) .to_string_lossy(); let expected = match entry.expected() { Expected::RunMatch => " [should run and generate output]", Expected::CompileFail => " [should fail to compile]", }; write_entry_header(log, &display_name, expected) } pub(crate) fn log_entry_fail_to_start(entry: &Entry, buf: &mut impl WriteColor) -> io::Result<()> { write_entry_header(buf, &entry.path().as_os_str().to_string_lossy(), "") } fn write_entry_header(buf: &mut impl WriteColor, name: &str, expected: &str) -> io::Result<()> { colored!( buf, "{}batch entry {}{}{}{} ... ", reset!(), bold!(true), name, bold!(false), expected ) } pub(crate) fn log_wip_write( buf: &mut impl WriteColor, wip_path: &Path, path: &Path, string: &str, ) -> io::Result<()> { let wip_path = wip_path.to_string_lossy(); let path = path.to_string_lossy(); colored!( buf, "{}{}wip\n\nNOTE{}: writing the following output to `{}`.\nMove this file to {} to accept it as correct.\n", reset!(), fg!(Some(Yellow)), reset!(), wip_path, path, )?; snippet(buf, Yellow, string) } pub(crate) fn log_overwrite( buf: &mut impl
mut impl WriteColor, color: Color, content: &str) -> io::Result<()> { let dotted_line = "┈".repeat(60); colored!(log, "\n{}{}{}\n", reset!(), fg!(Some(color)), dotted_line)?; for line in content.lines() { colored!(log, "{}{}\n", fg!(Some(color)), line)?; } colored!(log, "{}{}{}\n", fg!(Some(color)), dotted_line, reset!()) }
WriteColor, path: &Path, string: &str, ) -> io::Result<()> { let path = path.to_string_lossy(); colored!( buf, "{}{}wip\n\nNOTE{}: writing the following output to {}.", reset!(), fg!(Some(Yellow)), reset!(), path )?; snippet(buf, Yellow, string) } pub(crate) fn mismatch(log: &mut impl WriteColor, expected: &str, actual: &str) -> io::Result<()> { colored!( log, "{}{}mismatch{}\n\n", bold!(true), fg!(Some(Red)), reset!() )?; log_snapshot(log, Blue, "EXPECTED", expected.as_bytes())?; log_snapshot(log, Red, "ACTUAL", actual.as_bytes())?; Ok(()) } pub(crate) fn build_status_mismatch(log: &mut impl WriteColor) -> io::Result<()> { colored!( log, "{}{}{}error: {}", reset!(), bold!(true), fg!(Some(Red)), bold!(false) ) } pub(crate) fn unexpected_build_success(log: &mut impl WriteColor) -> io::Result<()> { build_status_mismatch(log)?; colored!( log, "Expected test case to fail to compile, but it succeeded.{}\n", reset!() ) } pub(crate) fn unexpected_build_error(log: &mut impl WriteColor, error: &[u8]) -> io::Result<()> { build_status_mismatch(log)?; colored!(log, "Entry failed to build; compiler output:{}\n", reset!())?; snippet(log, Red, &normalize::trim(error)) } pub(crate) fn log_snapshot( log: &mut impl WriteColor, color: Color, header: &str, snapshot: &[u8], ) -> io::Result<()> { if !snapshot.is_empty() { colored!(log, "{}{}{}:", bold!(true), fg!(Some(color)), header)?; snippet(log, color, &normalize::trim(snapshot))?; } Ok(()) } fn snippet(log: &
random
[ { "content": "fn write_wip(path: &Path, content: &str, log: &mut impl WriteColor) -> EntryResult<Infallible> {\n\n let wip_dir = Path::new(\"wip\");\n\n create_dir_all(wip_dir)?;\n\n\n\n let gitignore_path = wip_dir.join(\".gitignore\");\n\n write(gitignore_path, \"*\\n\")?;\n\n\n\n let stderr_name = path\n\n .file_name()\n\n .expect(\"Failed to write expected content to WIP folder - corrupt path\");\n\n let wip_path = wip_dir.join(stderr_name);\n\n logging::log_wip_write(log, &wip_path, path, content)?;\n\n\n\n write(wip_path, content).map_err(EntryError::WriteExpected)?;\n\n\n\n Err(EntryFailed::ExpectedNotExist(NoExpected::ToWip(\n\n content.to_owned(),\n\n )))\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 1, "score": 245140.1812738969 }, { "content": "pub fn build_entry(builder: &BinaryBuilder, main: &Path, run: bool) -> EntryResult<Output> {\n\n let mut cmd = rustc();\n\n builder.args_to_command(&mut cmd, main);\n\n cmd.arg(if run {\n\n \"--emit=link\"\n\n } else {\n\n \"--emit=dep-info\"\n\n });\n\n cmd.output().map_err(EntryError::Rustc).map_err(Into::into)\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 3, "score": 131109.54414988414 }, { "content": "fn drop(name: &str, bin_created: bool) {\n\n remove_file(BIN_DIR.join(name).with_extension(\"rs\")).unwrap_or_else(|_| {\n\n eprintln!(\n\n \"Unable to remove temporary file {}, please check it and remove manually\",\n\n name\n\n )\n\n });\n\n if bin_created {\n\n remove_dir(&*BIN_DIR).unwrap_or_else(|_| {\n\n eprintln!(\n\n \"Unable to remove directory {}, please check it and remove manually\",\n\n BIN_DIR\n\n .to_str()\n\n .unwrap_or(\"[ERROR BUILDING BIN_DIR PATH, PLEASE CONTACT US!]\")\n\n )\n\n });\n\n }\n\n}\n\n\n\npub struct BinaryBuilder {\n", "file_path": "src/binary.rs", "rank": 4, "score": 123890.21587337411 }, { "content": "pub fn capture_build_command(bin_name: &str) -> BatchResult<String> {\n\n let mut cmd = raw_cargo();\n\n cmd.current_dir(var_os(\"CARGO_MANIFEST_DIR\").unwrap());\n\n rustflags::set_env(&mut cmd);\n\n cmd.arg(\"build\");\n\n if info::opt_level() == \"release\" {\n\n cmd.arg(\"--release\");\n\n };\n\n cmd.arg(\"--bin\")\n\n .arg(bin_name)\n\n .arg(\"--verbose\")\n\n .output()\n\n .map_err(BatchError::Cargo)\n\n .map_err(Into::into)\n\n // .map(|out| { println!(\"Cargo output: \\\"{}\\\"\", String::from_utf8(out.clone().stderr).unwrap()); out })\n\n .map(extract_build_command)\n\n .map(trim_build_command)\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 5, "score": 123710.8321080932 }, { "content": "fn into_builder(name: &str) -> BatchResult<BinaryBuilder> {\n\n let cmd = cargo_rustc::capture_build_command(name)?;\n\n\n\n let args = cmd\n\n .split_ascii_whitespace()\n\n .scan(\"\", |prev, cur| {\n\n let out = if prev == &\"-L\" {\n\n vec![\"-L\", cur]\n\n } else if prev == &\"--cfg\" {\n\n vec![\"--cfg\", cur]\n\n } else if prev == &\"--extern\" {\n\n vec![\"--extern\", cur]\n\n } else if cur.starts_with(\"--edition\") {\n\n vec![cur]\n\n } else {\n\n vec![]\n\n };\n\n *prev = cur;\n\n Some(out)\n\n })\n\n .flatten()\n\n .map(String::from)\n\n .collect();\n\n\n\n Ok(BinaryBuilder { args })\n\n}\n", "file_path": "src/binary.rs", "rank": 6, "score": 120370.08087313047 }, { "content": "pub fn run_entry() -> EntryResult<Output> {\n\n Command::new(&*TARGET_BIN)\n\n .output()\n\n .map_err(EntryError::RunFailed)\n\n .map_err(Into::into)\n\n}\n", "file_path": "src/cargo_rustc.rs", "rank": 7, "score": 112374.47259121611 }, { "content": "fn process(original: &str) -> String {\n\n let mut normalized = String::new();\n\n\n\n for line in original.lines() {\n\n if let Some(line) = filter_map(line) {\n\n normalized += &line;\n\n if !normalized.ends_with(\"\\n\\n\") {\n\n normalized.push('\\n');\n\n }\n\n }\n\n }\n\n\n\n trim(normalized)\n\n}\n\n\n", "file_path": "src/normalize.rs", "rank": 8, "score": 109215.73749735541 }, { "content": "fn extract_build_command(out: Output) -> String {\n\n String::from_utf8(out.stderr)\n\n .expect(\"Cargo produced non-UTF-8 output\")\n\n .lines()\n\n // .inspect(|line| println!(\"Cargo output: {}\", line))\n\n .filter(|line| line.trim_start().starts_with(\"Running `\"))\n\n .last()\n\n .expect(\"No running command in cargo output\")\n\n .to_owned()\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 9, "score": 104615.25397820951 }, { "content": "fn filter_map(line: &str) -> Option<String> {\n\n lazy_static::lazy_static! {\n\n static ref CUT_OUT: Vec<&'static str> = vec![\n\n \"error: aborting due to\",\n\n \"For more information about this error, try `rustc --explain\",\n\n \"For more information about an error, try `rustc --explain\",\n\n \"Some errors have detailed explanations:\",\n\n ];\n\n };\n\n // stripping out final compilation lines\n\n if CUT_OUT.iter().any(|prefix| line.trim().starts_with(prefix)) {\n\n None\n\n } else {\n\n Some(line.to_owned())\n\n }\n\n}\n\n\n", "file_path": "src/normalize.rs", "rank": 10, "score": 101138.88392342377 }, { "content": "fn match_lines_with_backslashes(left: &[String], right: &[String]) -> bool {\n\n left.iter().zip_longest(right).all(|pair| {\n\n if let EitherOrBoth::Both(left, right) = pair {\n\n match_with_backslashes(left, right)\n\n } else {\n\n false\n\n }\n\n })\n\n}\n", "file_path": "src/mismatch.rs", "rank": 11, "score": 92365.38495604793 }, { "content": "// Public, to be used in compile-fail output matching.\n\npub fn match_with_backslashes(left: &str, right: &str) -> bool {\n\n left.replace('\\\\', \"/\") == right.replace('\\\\', \"/\")\n\n}\n\n\n", "file_path": "src/mismatch.rs", "rank": 12, "score": 91642.63402511191 }, { "content": "/// Trim the bytes stream with minimal reallocations.\n\npub fn trim<S: AsRef<[u8]>>(output: S) -> String {\n\n let bytes = output.as_ref();\n\n let mut normalized = String::from_utf8_lossy(bytes).to_string();\n\n\n\n let len = normalized.trim_end().len();\n\n normalized.truncate(len);\n\n\n\n if !normalized.is_empty() {\n\n normalized.push('\\n');\n\n }\n\n\n\n normalized\n\n}\n", "file_path": "src/normalize.rs", "rank": 13, "score": 90757.46343968218 }, { "content": "fn new() -> BatchResult<(String, bool)> {\n\n let bin_needed = BIN_DIR.exists().not();\n\n let bin_created = bin_needed && create_dir(&*BIN_DIR).map(|_| true)?;\n\n let mut name = \"batch_runner_check_\".to_owned();\n\n loop {\n\n // it is _still_ possible to break this somehow... but let's assume it doesn't\n\n if BIN_DIR.join(&name).with_extension(\"rs\").exists() {\n\n name.push_str(&format!(\"{:x}\", random::<u8>()));\n\n } else {\n\n break;\n\n }\n\n }\n\n write(BIN_DIR.join(&name).with_extension(\"rs\"), b\"fn main() {}\")?;\n\n Ok((name, bin_created))\n\n}\n\n\n", "file_path": "src/binary.rs", "rank": 14, "score": 88466.16081487651 }, { "content": "fn main() {}\n", "file_path": "tests/basic/compile-fail.rs", "rank": 15, "score": 78660.4745690464 }, { "content": "fn main() {\n\n assert!(false);\n\n}\n", "file_path": "tests/basic/run-fail.rs", "rank": 16, "score": 78496.9110287476 }, { "content": "fn trim_build_command(line: String) -> String {\n\n line.trim_start_matches(\"Running\")\n\n .trim()\n\n .trim_matches('`')\n\n .to_owned()\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 17, "score": 76883.50842088797 }, { "content": "fn main() {\n\n println!(\"Stdout\");\n\n eprintln!(\"Stderr\");\n\n}\n", "file_path": "tests/ui-cases/run-ok.rs", "rank": 18, "score": 75707.50791288006 }, { "content": "pub fn check_run_match(\n\n path: &Path,\n\n output: Output,\n\n update_mode: Update,\n\n log: &mut impl WriteColor,\n\n) -> EntryResult<()> {\n\n // TODO propagate error\n\n let output: LocalOutput = output.try_into().expect(\"No status code\");\n\n\n\n // In this case, the expected output is the file representing the output - let's read it!\n\n let snapshot_path = path.with_extension(\"snapshot\");\n\n\n\n // But first, check if it ever exists...\n\n if !snapshot_path.exists() {\n\n // logging::fail_output(log, Warn, &build_stdout);\n\n\n\n let data =\n\n to_string_pretty(&output, PrettyConfig::default()).expect(\"Serialization failed\");\n\n // both write_wip and write_overwrite are \"always-fallible\", and this is statically guaranteed\n\n // so we know, that this branch will always return early\n", "file_path": "src/snapshot.rs", "rank": 19, "score": 74955.78896043067 }, { "content": "pub fn check_compile_fail(\n\n path: &Path,\n\n output: Output,\n\n update_mode: Update,\n\n log: &mut impl WriteColor,\n\n) -> EntryResult<()> {\n\n // early exit if the entry has indeed compiled\n\n if output.status.success() {\n\n logging::unexpected_build_success(log)?;\n\n return Err(EntryFailed::ShouldNotCompile);\n\n }\n\n\n\n let variations = diagnostics(&output.stderr);\n\n let preferred = variations.preferred();\n\n // In this case, the expected output is simply a string - let's read it!\n\n let stderr_path = path.with_extension(\"stderr\");\n\n\n\n // But first, check if it ever exists...\n\n if !stderr_path.exists() {\n\n // logging::fail_output(log, Warn, &build_stdout);\n", "file_path": "src/snapshot.rs", "rank": 20, "score": 74908.49221890909 }, { "content": "pub fn buf() -> Buffer {\n\n WRITER.buffer()\n\n}\n\n\n", "file_path": "src/term.rs", "rank": 21, "score": 73797.51623597112 }, { "content": "compile_error!(\"ERROR\");\n", "file_path": "tests/ui-cases/compile-fail-ok.rs", "rank": 22, "score": 69071.67396870736 }, { "content": "pub fn make_vec() -> Vec<String> {\n\n let mut rustflags = Vec::new();\n\n\n\n for &lint in IGNORED_LINTS {\n\n rustflags.push(\"-A\".to_owned());\n\n rustflags.push(lint.to_owned());\n\n }\n\n\n\n rustflags\n\n}\n\n\n", "file_path": "src/rustflags.rs", "rank": 23, "score": 66538.54303325061 }, { "content": "/// Generate the `Variations` object from the raw stderr output.\n\npub fn diagnostics(output: &[u8]) -> Variations {\n\n let from_bytes = String::from_utf8_lossy(output)\n\n .to_string()\n\n .replace(\"\\r\\n\", \"\\n\");\n\n\n\n let variations = [Basic].iter().map(|_| process(&from_bytes)).collect();\n\n\n\n Variations { variations }\n\n}\n\n\n", "file_path": "src/normalize.rs", "rank": 24, "score": 66053.97423351936 }, { "content": "compile_error!(\"Unexpected error\");\n", "file_path": "tests/ui-cases/run-unexpected-compile-fail.rs", "rank": 25, "score": 65784.30244760576 }, { "content": "pub fn set_env(cmd: &mut Command) {\n\n let mut rustflags = match env::var_os(RUSTFLAGS) {\n\n Some(rustflags) => rustflags,\n\n None => return,\n\n };\n\n\n\n for flag in make_vec() {\n\n rustflags.push(\" \");\n\n rustflags.push(flag);\n\n }\n\n\n\n cmd.env(RUSTFLAGS, rustflags);\n\n}\n", "file_path": "src/rustflags.rs", "rank": 26, "score": 64528.43707537888 }, { "content": "fn bytes_to_lines(input: &[u8]) -> Vec<String> {\n\n String::from_utf8_lossy(input)\n\n .to_string()\n\n .replace(\"\\r\\n\", \"\\n\")\n\n .lines()\n\n .map(String::from)\n\n .collect()\n\n}\n", "file_path": "src/mismatch.rs", "rank": 27, "score": 63276.082352722246 }, { "content": "pub fn print(buf: Option<Buffer>) -> Result<(), PrintError> {\n\n buf.ok_or(PrintError::AlreadyPrinted)\n\n .and_then(|buf| WRITER.print(&buf).map_err(PrintError::Io))\n\n}\n\n\n\n// pub fn direct<'a>() -> RwLockWriteGuard<'a, StandardStream> {\n\n// TERM.write().unwrap_or_else(PoisonError::into_inner)\n\n// }\n", "file_path": "src/term.rs", "rank": 28, "score": 58937.83496392667 }, { "content": "fn write_overwrite(\n\n path: &Path,\n\n content: &str,\n\n log: &mut impl WriteColor,\n\n) -> EntryResult<Infallible> {\n\n logging::log_overwrite(log, path, content)?;\n\n\n\n write(path, content).map_err(EntryError::WriteExpected)?;\n\n\n\n Err(EntryFailed::ExpectedNotExist(NoExpected::Direct(\n\n content.to_owned(),\n\n )))\n\n}\n", "file_path": "src/snapshot.rs", "rank": 29, "score": 57036.68911988059 }, { "content": "fn main() {\n\n let b = batch_run::Batch::new();\n\n b.compile_fail(\"tests/ui-cases/compile-*.rs\");\n\n b.run_match(\"tests/ui-cases/run-*.rs\");\n\n b.run().unwrap().assert_all_ok();\n\n}\n", "file_path": "tests/ui-runner/main.rs", "rank": 30, "score": 54833.928327198955 }, { "content": "fn main() {}\n", "file_path": "tests/basic/run-pass.rs", "rank": 31, "score": 54510.447080597805 }, { "content": "fn main() {\n\n println!(\"Unexpected output!\");\n\n}\n", "file_path": "tests/ui-cases/run-mismatch.rs", "rank": 32, "score": 52514.41865215506 }, { "content": "fn main() {\n\n println!(\"It works, unexpectedly!\");\n\n}\n", "file_path": "tests/ui-cases/compile-success-unexpected.rs", "rank": 33, "score": 50835.45867610694 }, { "content": "compile_error!(\"ERROR\");\n\n\n", "file_path": "tests/basic/compile-fail.rs", "rank": 34, "score": 50273.86621413855 }, { "content": "compile_error!(\"Not the error we expected\");\n", "file_path": "tests/ui-cases/compile-fail-mismatch.rs", "rank": 35, "score": 45881.25851351199 }, { "content": "#[derive(Debug)]\n\nstruct SingleMismatch<T = String>\n\nwhere\n\n T: Clone,\n\n{\n\n expected: T,\n\n actual: T,\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct CompileFailMismatch(SingleMismatch);\n\n#[derive(Debug)]\n\npub struct RunMismatch(SingleMismatch<LocalOutput>);\n\n\n\nimpl RunMismatch {\n\n pub fn new(expected: LocalOutput, actual: LocalOutput) -> Self {\n\n RunMismatch(SingleMismatch { expected, actual })\n\n }\n\n}\n\n\n\nimpl CompileFailMismatch {\n\n pub fn new<S1: Into<String>, S2: Into<String>>(expected: S1, actual: S2) -> Self {\n\n CompileFailMismatch(SingleMismatch {\n\n expected: expected.into(),\n\n actual: actual.into(),\n\n })\n\n }\n\n}\n", "file_path": "src/mismatch.rs", "rank": 36, "score": 41744.73187597211 }, { "content": "fn main() {\n\n let out_dir = env::var(\"OUT_DIR\")\n\n .expect(\"OUT_DIR not set, check if your Cargo version isn't really ancient\");\n\n let dest_path = Path::new(&out_dir).join(\"info.rs\");\n\n let mut f = File::create(&dest_path).expect(\"Unable to create file in OUT_DIR\");\n\n\n\n f.write_all(\n\n format!(\n\n \"\n\nmod info {{\n\n pub fn opt_level() -> &'static str {{\n\n \\\"{}\\\"\n\n }}\n\n\n\n pub fn rustc() -> &'static str {{\n\n \\\"{}\\\"\n\n }}\n\n}}\n\n \",\n\n env::var(\"PROFILE\")\n\n .expect(\"PROFILE not set, check if your Cargo version isn't too old\"),\n\n env::var(\"RUSTC\").expect(\"RUSTC not set, check if your Cargo version isn't too old\"),\n\n )\n\n .as_bytes(),\n\n )\n\n .expect(\"Unable to write to OUT_DIR\");\n\n}\n", "file_path": "build.rs", "rank": 37, "score": 34158.20890736034 }, { "content": "Batch Run\n\n=========\n\n\n\n[![Latest Version](https://img.shields.io/crates/v/batch_run.svg)](https://crates.io/crates/batch_run)\n\n[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/batch_run)\n\n\n\n`batch_run` is a runner for a set of Rust source files, based on [dtolnay's `trybuild`](https://github.com/dtolnay/trybuild).\n\nIt can be useful when you have a bunch of Rust sources which are not complex enough to be\n\npacked into dedicated crates, but which are (by their meaning) not just integration test cases.\n\nIt also checks for output correctness, either on compile-time (for `compile_fail` cases)\n\nor at runtime (for `run_pass` cases).\n\n\n\n```toml\n\n[dependencies]\n\nbatch_run = \"1.0\"\n\n```\n\n\n\n*Compiler support: requires rustc 1.31+*\n\n\n\n<br>\n\n\n\n## Compile-fail cases\n\n\n\nA minimal batch_run setup looks like this:\n\n\n\n```rust\n\nfn main() {\n\n let b = batch_run::Batch::new();\n\n b.compile_fail(\"batches/ui/*.rs\");\n\n match b.run() {\n\n Ok(()) => {},\n\n Err(err) => println!(\"{:?}\", err)\n\n };\n\n}\n\n```\n\n\n\nThis program will individually compile each of the\n\nsource files matching the glob pattern, expect them to fail to compile, and\n\nassert that the compiler's error message matches an adjacently named _*.stderr_\n\nfile containing the expected output (same file name as the test except with a\n\ndifferent extension). If it doesn't match, the program will print the error message\n\nwith expected vs actual compiler output.\n\n\n\nDependencies listed under `[dependencies]` and `[dev-dependencies]` in the project's Cargo.toml\n\nare accessible from within the batch, just like on ordinary `cargo run`.\n\n\n\nA compile\\_fail case that fails to fail to compile is also a failure.\n\n\n\n<br>\n\n\n", "file_path": "README.md", "rank": 38, "score": 33857.09891846219 }, { "content": "## Run-pass cases\n\n\n\nIn the run_pass cases, we not only check that the code compiles, but also actually run it\n\nand match the stdout/stderr output with the corresponding _*.stdout_/_*.stderr_ files.\n\n\n\nYou can mix compile_fail and run_pass cases in one batch:\n\n\n\n```rust\n\nfn main() {\n\n let t = batch_run::Batch::new();\n\n t.run_pass(\"batches/01-parse-header.rs\");\n\n t.run_pass(\"batches/02-parse-body.rs\");\n\n t.compile_fail(\"batches/03-expand-four-errors.rs\");\n\n t.run_pass(\"batches/04-paste-ident.rs\");\n\n t.run_pass(\"batches/05-repeat-section.rs\");\n\n}\n\n```\n\n\n\n<br>\n\n\n\n## Details\n\n\n\nThat's the entire API.\n\n\n\n<br>\n\n\n\n## Workflow\n\n\n\n(TODO)\n\n\n\n#### License\n\n\n\n<sup>\n\nLicensed under either of <a href=\"LICENSE-APACHE\">Apache License, Version\n\n2.0</a> or <a href=\"LICENSE-MIT\">MIT license</a> at your option.\n\n</sup>\n\n\n\n<br>\n\n\n\n<sub>\n\nUnless you explicitly state otherwise, any contribution intentionally submitted\n\nfor inclusion in this crate by you, as defined in the Apache-2.0 license, shall\n\nbe dual licensed as above, without any additional terms or conditions.\n\n</sub>\n", "file_path": "README.md", "rank": 39, "score": 33848.70413393437 }, { "content": "#[test]\n\nfn basic() {\n\n let t = batch_run::Batch::new();\n\n t.compile_fail(\"tests/basic/compile-fail.rs\");\n\n t.run_match(\"tests/basic/run-*.rs\");\n\n t.run_match(\"tests/basic/print-*.rs\");\n\n t.run().unwrap().assert_all_ok();\n\n}\n\n\n", "file_path": "tests/test.rs", "rank": 40, "score": 32884.90515252308 }, { "content": "#[test]\n\nfn ui() {\n\n let t = batch_run::Batch::new();\n\n t.run_match(\"tests/ui-runner/main.rs\");\n\n t.run().unwrap().assert_all_ok();\n\n}\n", "file_path": "tests/test.rs", "rank": 41, "score": 32884.90515252308 }, { "content": "fn main() {\n\n println!(\"{:?}\", \"STDOUT\".chars());\n\n eprintln!(\"{:?}\", \"STDERR\".chars());\n\n}\n", "file_path": "tests/basic/print-both.rs", "rank": 42, "score": 31733.594571801987 }, { "content": "fn main() {\n\n println!(\"{:?}\", \"STDOUT\".chars());\n\n println!(\"Testing at path /basic/print-stdout\");\n\n}\n", "file_path": "tests/basic/print-stdout.rs", "rank": 43, "score": 30687.5466727468 }, { "content": "fn main() {\n\n eprintln!(\"{:?}\", \"STDERR\".chars());\n\n}\n", "file_path": "tests/basic/print-stderr.rs", "rank": 44, "score": 30687.5466727468 }, { "content": "fn rustc() -> Command {\n\n let mut cmd = Command::new(info::rustc());\n\n cmd.current_dir(var_os(\"CARGO_MANIFEST_DIR\").unwrap());\n\n cmd.args(&[\n\n \"-o\",\n\n TARGET_BIN.to_str().expect(\"Non-UTF-8 symbols in path\"),\n\n ]);\n\n cmd\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 45, "score": 29987.331657651062 }, { "content": "fn raw_cargo() -> Command {\n\n Command::new(option_env!(\"CARGO\").unwrap_or(\"cargo\"))\n\n}\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 46, "score": 29032.741498403986 }, { "content": "use crate::binary::BUILDER;\n\nuse crate::config::Config;\n\nuse crate::entry::{expand_globs, Entry};\n\nuse crate::logging;\n\nuse crate::result::{BatchResult, BatchRunResult};\n\n\n\nuse termcolor::{StandardStream, WriteColor};\n\n\n\n#[derive(Debug, Default)]\n\npub struct Runner {\n\n entries: Vec<Entry>,\n\n}\n\n\n\nimpl Runner {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n pub fn add_entry(&mut self, entry: Entry) {\n\n self.entries.push(entry);\n", "file_path": "src/runner.rs", "rank": 47, "score": 28006.638318567377 }, { "content": "\n\n let builder = &*BUILDER;\n\n\n\n print!(\"\\n\\n\");\n\n\n\n if entries.is_empty() {\n\n let mut log = cfg.writer().build();\n\n logging::no_entries(&mut log)?;\n\n Ok(BatchRunResult::NoEntries(Some(log)))\n\n } else {\n\n Ok(BatchRunResult::ResultsMap(\n\n entries\n\n .into_iter()\n\n .map(|entry| (entry.path().display().to_string(), entry.run(builder, &cfg)))\n\n .collect(),\n\n ))\n\n }\n\n }\n\n}\n", "file_path": "src/runner.rs", "rank": 48, "score": 28003.719508058737 }, { "content": " }\n\n\n\n pub fn run(&mut self) -> BatchResult<BatchRunResult<StandardStream>> {\n\n let config = Config::from_env()?;\n\n self.run_with_config(config)\n\n }\n\n pub fn run_with_config<W: WriteColor>(\n\n &mut self,\n\n cfg: Config<W>,\n\n ) -> BatchResult<BatchRunResult<W>> {\n\n let cwd = std::env::current_dir()?;\n\n std::env::set_current_dir(\n\n std::env::var_os(\"CARGO_MANIFEST_DIR\").expect(\"Couldn't get manifest dir\"),\n\n )?;\n\n let res = self.run_impl(cfg);\n\n std::env::set_current_dir(cwd)?;\n\n res\n\n }\n\n fn run_impl<W: WriteColor>(&mut self, cfg: Config<W>) -> BatchResult<BatchRunResult<W>> {\n\n let entries = expand_globs(&self.entries, &cfg.writer());\n", "file_path": "src/runner.rs", "rank": 49, "score": 28001.356147806313 }, { "content": "\n\n pub fn run_match<P: AsRef<Path>>(&self, path: P) {\n\n self.runner\n\n .borrow_mut()\n\n .add_entry(Entry::new(path, Expected::RunMatch));\n\n }\n\n\n\n pub fn compile_fail<P: AsRef<Path>>(&self, path: P) {\n\n self.runner\n\n .borrow_mut()\n\n .add_entry(Entry::new(path, Expected::CompileFail));\n\n }\n\n\n\n pub fn run(mut self) -> BatchResult {\n\n self.has_run = true;\n\n self.runner.borrow_mut().run()\n\n }\n\n}\n\n\n\n#[doc(hidden)]\n", "file_path": "src/batch.rs", "rank": 50, "score": 27760.70553805358 }, { "content": "use crate::entry::{Entry, Expected};\n\nuse crate::result::BatchResult;\n\nuse crate::runner::Runner;\n\nuse std::cell::RefCell;\n\nuse std::path::Path;\n\nuse std::thread;\n\n\n\n#[derive(Debug, Default)]\n\npub struct Batch {\n\n runner: RefCell<Runner>,\n\n has_run: bool,\n\n}\n\n\n\nimpl Batch {\n\n pub fn new() -> Self {\n\n Batch {\n\n runner: RefCell::new(Runner::new()),\n\n has_run: false,\n\n }\n\n }\n", "file_path": "src/batch.rs", "rank": 51, "score": 27754.784963189086 }, { "content": "impl Drop for Batch {\n\n fn drop(&mut self) {\n\n if !thread::panicking() && !self.has_run {\n\n self.runner\n\n .borrow_mut()\n\n .run()\n\n .map(|_| ())\n\n .unwrap_or_else(|err| println!(\"{}\", err));\n\n }\n\n }\n\n}\n", "file_path": "src/batch.rs", "rank": 52, "score": 27748.714806052845 }, { "content": "use termcolor::WriteColor;\n\n\n\nuse std::fs::File;\n\nuse std::path::{Path, PathBuf};\n\n\n\nuse crate::binary::BinaryBuilder;\n\nuse crate::cargo_rustc;\n\nuse crate::config::{Config, WriterBuilder};\n\nuse crate::logging;\n\nuse crate::normalize::diagnostics;\n\nuse crate::result::{\n\n error::{EntryError, EntryFailed},\n\n EntryOutput, EntryResult,\n\n};\n\nuse crate::snapshot::{check_compile_fail, check_run_match};\n\n\n\n#[derive(Copy, Clone, Debug)]\n\npub enum Expected {\n\n RunMatch,\n\n CompileFail,\n", "file_path": "src/entry.rs", "rank": 59, "score": 27506.82856256634 }, { "content": " Self {\n\n path: path.as_ref().to_owned(),\n\n expected,\n\n }\n\n }\n\n\n\n fn run<W: WriteColor>(\n\n &self,\n\n builder: &BinaryBuilder,\n\n cfg: &Config<W>,\n\n log: &mut impl WriteColor,\n\n ) -> EntryResult<()> {\n\n logging::log_entry_start(self, log)?;\n\n self.try_open()?;\n\n\n\n let mut output =\n\n cargo_rustc::build_entry(builder, &self.path, self.expected.is_run_pass())?;\n\n\n\n let check = match self.expected {\n\n Expected::RunMatch => {\n", "file_path": "src/entry.rs", "rank": 60, "score": 27505.38191455151 }, { "content": " // early exit if the entry has not compiled\n\n if !output.status.success() {\n\n let stderr = diagnostics(&output.stderr).preferred().to_owned();\n\n logging::unexpected_build_error(log, stderr.as_bytes())?;\n\n return Err(EntryFailed::ShouldCompile(stderr));\n\n }\n\n output = cargo_rustc::run_entry()?;\n\n check_run_match\n\n }\n\n Expected::CompileFail => check_compile_fail,\n\n };\n\n check(&self.path, output, cfg.update_mode(), log)\n\n .and_then(|_| logging::ok(log).map_err(Into::into))\n\n }\n\n\n\n fn try_open(&self) -> EntryResult<()> {\n\n if self.path.exists() {\n\n return Ok(());\n\n }\n\n match File::open(&self.path) {\n", "file_path": "src/entry.rs", "rank": 61, "score": 27504.328772399476 }, { "content": "}\n\n\n\nimpl Expected {\n\n pub fn is_run_pass(self) -> bool {\n\n use Expected::*;\n\n match self {\n\n RunMatch => true,\n\n CompileFail => false,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug)]\n\npub struct Entry {\n\n path: PathBuf,\n\n expected: Expected,\n\n}\n\n\n\nimpl Entry {\n\n pub fn new<P: AsRef<Path>>(path: P, expected: Expected) -> Self {\n", "file_path": "src/entry.rs", "rank": 62, "score": 27502.522106634882 }, { "content": "\n\n vec\n\n}\n\n\n\nimpl<W: WriteColor> ExpandedEntry<W> {\n\n pub fn run(self, builder: &BinaryBuilder, cfg: &Config<W>) -> EntryOutput<W> {\n\n let Self {\n\n error,\n\n raw_entry,\n\n mut log,\n\n } = self;\n\n let res = match error {\n\n None => raw_entry.run(builder, cfg, &mut log),\n\n Some(error) => {\n\n // explicitly silence the io::Error - we have another error to show up\n\n let _ = logging::log_entry_fail_to_start(&raw_entry, &mut log);\n\n Err(error)\n\n }\n\n };\n\n EntryOutput::new(res, log)\n\n }\n\n\n\n pub fn path(&self) -> &Path {\n\n &self.raw_entry.path\n\n }\n\n}\n", "file_path": "src/entry.rs", "rank": 63, "score": 27500.979779693957 }, { "content": " Ok(_) => Ok(()),\n\n Err(err) => Err(EntryError::Open(self.path.clone(), err).into()),\n\n }\n\n }\n\n pub fn path(&self) -> &Path {\n\n &self.path\n\n }\n\n pub fn expected(&self) -> Expected {\n\n self.expected\n\n }\n\n}\n\n\n\npub struct ExpandedEntry<W: WriteColor> {\n\n log: W,\n\n raw_entry: Entry,\n\n error: Option<EntryFailed>,\n\n}\n\n\n\npub(crate) fn expand_globs<W: WriteColor>(\n\n entries: &[Entry],\n", "file_path": "src/entry.rs", "rank": 64, "score": 27500.35760607826 }, { "content": " writer: &WriterBuilder<W>,\n\n) -> Vec<ExpandedEntry<W>> {\n\n fn glob(pattern: &str) -> EntryResult<Vec<PathBuf>> {\n\n let mut paths = glob::glob(pattern)?\n\n .map(|entry| entry.map_err(EntryFailed::from))\n\n .collect::<EntryResult<Vec<PathBuf>>>()?;\n\n paths.sort();\n\n Ok(paths)\n\n }\n\n\n\n let mut vec = Vec::new();\n\n\n\n for entry in entries {\n\n let mut expanded = ExpandedEntry {\n\n raw_entry: entry.clone(),\n\n error: None,\n\n log: writer.build(),\n\n };\n\n if let Some(utf8) = entry.path.to_str() {\n\n if utf8.contains('*') {\n", "file_path": "src/entry.rs", "rank": 65, "score": 27499.334674167603 }, { "content": " match glob(utf8) {\n\n Ok(paths) => {\n\n for path in paths {\n\n vec.push(ExpandedEntry {\n\n raw_entry: Entry {\n\n path,\n\n expected: expanded.raw_entry.expected,\n\n },\n\n error: None,\n\n log: writer.build(),\n\n });\n\n }\n\n continue;\n\n }\n\n Err(error) => expanded.error = Some(error),\n\n }\n\n }\n\n }\n\n vec.push(expanded);\n\n }\n", "file_path": "src/entry.rs", "rank": 66, "score": 27495.56780609841 }, { "content": "use crate::{\n\n config::Update,\n\n logging,\n\n mismatch::{match_with_backslashes, CompileFailMismatch, LocalOutput, RunMismatch},\n\n normalize::diagnostics,\n\n result::{\n\n error::NoExpected,\n\n error::{EntryError, EntryFailed},\n\n EntryResult,\n\n },\n\n};\n\nuse ron::{\n\n de::from_str,\n\n ser::{to_string_pretty, PrettyConfig},\n\n};\n\nuse std::path::Path;\n\nuse std::{\n\n convert::{Infallible, TryInto},\n\n fs::{create_dir_all, read_to_string, write},\n\n process::Output,\n\n};\n\nuse termcolor::WriteColor;\n\n\n", "file_path": "src/snapshot.rs", "rank": 67, "score": 28.82620471394865 }, { "content": "use crate::mismatch::{CompileFailMismatch, RunMismatch};\n\nuse glob::{GlobError, PatternError};\n\nuse std::ffi::OsString;\n\nuse std::io;\n\nuse std::path::PathBuf;\n\nuse thiserror::Error;\n\n\n\n#[derive(Debug, Error)]\n\npub enum EntryFailed {\n\n #[error(\"Entry should compile, but compilation failed\")]\n\n ShouldCompile(String),\n\n #[error(\"Entry should not compile, but it compiled successfully\")]\n\n ShouldNotCompile,\n\n #[error(\"There's no expected output for entry. {0}\")]\n\n ExpectedNotExist(#[source] NoExpected),\n\n #[error(\"Compiler error mismatch\")]\n\n CompileFailMismatch(CompileFailMismatch),\n\n #[error(\"Runtime output mismatch\")]\n\n RunMismatch(RunMismatch),\n\n #[error(\"Internal error\")]\n", "file_path": "src/result/error.rs", "rank": 68, "score": 24.11219031100966 }, { "content": "use crate::term;\n\nuse glob::{GlobError, PatternError};\n\nuse std::io;\n\nuse termcolor::{Buffer, StandardStream, WriteColor};\n\n\n\npub mod error;\n\nuse error::*;\n\n\n\npub enum BatchRunResult<W: WriteColor = StandardStream> {\n\n NoEntries(Option<W>),\n\n ResultsMap(Vec<(String, EntryOutput<W>)>),\n\n}\n\npub type BatchResult<T = BatchRunResult> = std::result::Result<T, BatchError>;\n\n\n\nimpl<W: WriteColor> BatchRunResult<W> {\n\n pub fn errors(&self) -> Option<Vec<(&String, &EntryFailed)>> {\n\n if let BatchRunResult::ResultsMap(map) = self {\n\n Some(\n\n map.iter()\n\n .filter_map(|(file, res)| res.err().map(|err| (file, err)))\n", "file_path": "src/result.rs", "rank": 69, "score": 21.95531135035385 }, { "content": "//!\n\n//! ## Compile-fail cases\n\n//!\n\n//! A minimal batch_run setup looks like this:\n\n//!\n\n//! ```rust\n\n//! let b = batch_run::Batch::new();\n\n//! b.compile_fail(\"batches/ui/*.rs\");\n\n//! match b.run() {\n\n//! Ok(_) => {},\n\n//! Err(err) => println!(\"{:?}\", err)\n\n//! };\n\n//! ```\n\n//!\n\n//! This program will individually compile each of the\n\n//! source files matching the glob pattern, expect them to fail to compile, and\n\n//! assert that the compiler's error message matches an adjacently named _*.stderr_\n\n//! file containing the expected output (same file name as the test except with a\n\n//! different extension). If it doesn't match, the program will print the error message\n\n//! with expected vs actual compiler output.\n", "file_path": "src/lib.rs", "rank": 70, "score": 21.70090924583678 }, { "content": " // with stabilization of \"never\" type, we can guarantee this here, too\n\n // but for now, just trust us\n\n // (joking... you can always check the signatures)\n\n match update_mode {\n\n Update::Wip => write_wip(&snapshot_path, &data, log)?,\n\n Update::Overwrite => write_overwrite(&snapshot_path, &data, log)?,\n\n };\n\n }\n\n\n\n // ok, well - the file does exist, but does it contain the same that we've got?\n\n let string = &read_to_string(&snapshot_path)\n\n .map_err(EntryError::ReadExpected)?\n\n .replace(\"\\r\\n\", \"\\n\");\n\n let expected = from_str(string).expect(\"Deserialization failed\");\n\n\n\n if output.matches(&expected) {\n\n return Ok(());\n\n }\n\n\n\n let data = to_string_pretty(&output, PrettyConfig::default()).expect(\"Serialization failed\");\n", "file_path": "src/snapshot.rs", "rank": 71, "score": 21.35000907687225 }, { "content": " }\n\n panic!(\"Assertion failed, see errors in stderr above\");\n\n }\n\n }\n\n}\n\nimpl BatchRunResult<Buffer> {\n\n pub fn print_all(&mut self) -> std::result::Result<(), PrintError> {\n\n match self {\n\n BatchRunResult::NoEntries(buf) => term::print(buf.take()),\n\n BatchRunResult::ResultsMap(map) => map\n\n .iter_mut()\n\n .map(|(_, out)| out)\n\n .try_for_each(EntryOutput::print),\n\n }\n\n }\n\n}\n\n\n\npub type EntryResult<T = ()> = std::result::Result<T, EntryFailed>;\n\npub struct EntryOutput<W: WriteColor> {\n\n res: EntryResult,\n", "file_path": "src/result.rs", "rank": 72, "score": 21.30913611014768 }, { "content": " match update_mode {\n\n Update::Wip => {\n\n logging::mismatch(log, string, &data)?;\n\n Err(EntryFailed::RunMismatch(RunMismatch::new(expected, output)))\n\n }\n\n Update::Overwrite => {\n\n // TODO propagate the serialization-deserialization errors\n\n write_overwrite(&snapshot_path, &data, log).map(|_| ())\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 73, "score": 19.538053950061787 }, { "content": " buf: Option<W>,\n\n}\n\nimpl<W: WriteColor> EntryOutput<W> {\n\n pub(crate) fn new(res: EntryResult, buf: W) -> Self {\n\n Self {\n\n res,\n\n buf: Some(buf),\n\n }\n\n }\n\n pub fn is_ok(&self) -> bool {\n\n self.res.is_ok()\n\n }\n\n pub fn err(&self) -> Option<&EntryFailed> {\n\n self.res.as_ref().err()\n\n }\n\n}\n\nimpl EntryOutput<Buffer> {\n\n pub fn print(&mut self) -> std::result::Result<(), PrintError> {\n\n term::print(self.buf.take())\n\n }\n", "file_path": "src/result.rs", "rank": 74, "score": 18.168592203719967 }, { "content": "\n\n match update_mode {\n\n Update::Wip => {\n\n logging::mismatch(log, &expected, preferred)?;\n\n Err(EntryFailed::CompileFailMismatch(CompileFailMismatch::new(\n\n expected, preferred,\n\n )))\n\n }\n\n Update::Overwrite => write_overwrite(&stderr_path, preferred, log).map(|_| ()),\n\n }\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 75, "score": 18.022982439306872 }, { "content": "use crate::result::{error::BatchError, BatchResult};\n\nuse crate::result::{error::EntryError, EntryResult};\n\nuse lazy_static::lazy_static;\n\nuse std::{\n\n env::{consts::EXE_EXTENSION, var_os},\n\n path::{Path, PathBuf},\n\n process::{Command, Output},\n\n};\n\n\n\nuse crate::binary::BinaryBuilder;\n\nuse crate::rustflags;\n\n\n\nlazy_static! {\n\n static ref TARGET_BIN: PathBuf = {\n\n let mut tmp: PathBuf = [\".\", \"target\", \"batch\"].iter().collect();\n\n // TODO configurable?\n\n std::fs::create_dir_all(&tmp).expect(\"Unable to create batch executable in target directory; check your access rights\");\n\n tmp.push(&format!(\"{:x}\", rand::random::<u64>()));\n\n tmp.with_extension(EXE_EXTENSION)\n\n };\n\n}\n\n\n\ninclude!(concat!(env!(\"OUT_DIR\"), \"/info.rs\"));\n\n\n", "file_path": "src/cargo_rustc.rs", "rank": 76, "score": 16.583509220776325 }, { "content": "\n\n#[derive(Debug, Error)]\n\npub enum ConfigError {\n\n #[error(\"Incorrect value of BATCH_RUN environmental variable: expected either \\\"Overwrite\\\" or \\\"Wip\\\", got {}\", .0.to_string_lossy())]\n\n UpdateEnvVar(OsString),\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum EntryError {\n\n #[error(\"Failed to execute rustc: {0}\")]\n\n Rustc(#[source] io::Error),\n\n // TODO - is it used/necessary?\n\n #[error(\"Cargo reported an error\")]\n\n CargoFail,\n\n #[error(\"Error executing glob: {0}\")]\n\n Glob(#[source] GlobError),\n\n #[error(\"General IO error: {0}\")]\n\n Io(#[source] io::Error),\n\n #[error(\"Unable to open provided path: {}, error: {}\", .0.display(), .1)]\n\n Open(PathBuf, #[source] io::Error),\n", "file_path": "src/result/error.rs", "rank": 77, "score": 16.468597418073667 }, { "content": " None => return Ok(Update::default()),\n\n };\n\n\n\n match var.as_os_str().to_str() {\n\n Some(\"wip\") => Ok(Update::Wip),\n\n Some(\"overwrite\") => Ok(Update::Overwrite),\n\n _ => Err(BatchError::ConfigError(ConfigError::UpdateEnvVar(var))),\n\n }\n\n }\n\n}\n\n\n\npub struct WriterBuilder<W: WriteColor>(Rc<dyn Fn() -> W>);\n\nimpl<W: WriteColor> Clone for WriterBuilder<W> {\n\n fn clone(&self) -> Self {\n\n Self(Rc::clone(&self.0))\n\n }\n\n}\n\n\n\nimpl<W: WriteColor> WriterBuilder<W> {\n\n pub fn new(inner: Box<dyn Fn() -> W>) -> Self\n", "file_path": "src/config.rs", "rank": 78, "score": 16.12671864430243 }, { "content": "use crate::result::{error::BatchError, error::ConfigError, BatchResult};\n\nuse std::{env, rc::Rc};\n\nuse termcolor::{Buffer, ColorChoice, StandardStream, WriteColor};\n\n\n\n#[derive(PartialEq, Debug, Copy, Clone)]\n\npub enum Update {\n\n Wip,\n\n Overwrite,\n\n}\n\n\n\nimpl Default for Update {\n\n fn default() -> Self {\n\n Update::Wip\n\n }\n\n}\n\n\n\nimpl Update {\n\n fn env() -> BatchResult<Self> {\n\n let var = match env::var_os(\"BATCH_RUN\") {\n\n Some(var) => var,\n", "file_path": "src/config.rs", "rank": 79, "score": 15.575101113270804 }, { "content": "//!\n\n//! Dependencies listed under `[dependencies]` in the project's Cargo.toml are\n\n//! accessible from within the batch.\n\n//!\n\n//! A compile\\_fail case that fails to fail to compile is also a failure.\n\n//!\n\n//! <br>\n\n//!\n\n//! ## Run-match cases\n\n//!\n\n//! In the run_match cases, we not only check that the code compiles, but also actually run it\n\n//! and match the stdout/stderr output with the corresponding _*.stdout_/_*.stderr_ files.\n\n//!\n\n//! You can mix compile_fail and run_match cases in one batch:\n\n//!\n\n//! ```rust\n\n//! let t = batch_run::Batch::new();\n\n//! t.run_match(\"batches/01-parse-header.rs\");\n\n//! t.run_match(\"batches/02-parse-body.rs\");\n\n//! t.compile_fail(\"batches/03-expand-four-errors.rs\");\n", "file_path": "src/lib.rs", "rank": 80, "score": 15.481449852605714 }, { "content": "\n\n // both write_wip and write_overwrite are \"always-fallible\", and this is statically guaranteed\n\n // so we know, that this branch will always return early\n\n // with stabilization of \"never\" type, we can guarantee this here, too\n\n // but for now, just trust us\n\n // (joking... you can always check the signatures)\n\n match update_mode {\n\n Update::Wip => write_wip(&stderr_path, preferred, log)?,\n\n Update::Overwrite => write_overwrite(&stderr_path, preferred, log)?,\n\n };\n\n }\n\n\n\n // ok, well - the file does exist, but does it contain the same that we've got?\n\n let expected = read_to_string(&stderr_path)\n\n .map_err(EntryError::ReadExpected)?\n\n .replace(\"\\r\\n\", \"\\n\");\n\n\n\n if variations.any(|stderr| match_with_backslashes(&expected, stderr)) {\n\n return Ok(());\n\n }\n", "file_path": "src/snapshot.rs", "rank": 81, "score": 15.17584490573774 }, { "content": "use crate::cargo_rustc;\n\nuse crate::result::BatchResult;\n\nuse lazy_static::lazy_static;\n\nuse rand::random;\n\nuse std::{\n\n env::var_os,\n\n ffi::OsString,\n\n fs::{create_dir, remove_dir, remove_file, write},\n\n ops::Not,\n\n path::{Path, PathBuf},\n\n process::Command,\n\n};\n\n\n\nlazy_static! {\n\n static ref BIN_DIR: PathBuf = [\n\n var_os(\"CARGO_MANIFEST_DIR\").unwrap(),\n\n OsString::from(\"src\"),\n\n OsString::from(\"bin\")\n\n ]\n\n .iter()\n\n .collect();\n\n pub static ref BUILDER: BinaryBuilder = BinaryBuilder::new().unwrap();\n\n}\n\n\n", "file_path": "src/binary.rs", "rank": 82, "score": 15.03477405884561 }, { "content": " args: Vec<String>,\n\n}\n\n\n\nimpl BinaryBuilder {\n\n pub fn new() -> BatchResult<Self> {\n\n let (name, bin_created) = new()?;\n\n let builder = into_builder(&name);\n\n drop(&name, bin_created);\n\n builder\n\n }\n\n pub fn args_to_command(&self, cmd: &mut Command, main: &Path) {\n\n cmd.args(&self.args).arg(main);\n\n }\n\n}\n", "file_path": "src/binary.rs", "rank": 83, "score": 14.565441049364726 }, { "content": "use itertools::{EitherOrBoth, Itertools};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::{convert::TryFrom, error::Error, process::Output};\n\n\n\n#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]\n\npub struct LocalOutput {\n\n status: i32,\n\n stdout: Vec<String>,\n\n stderr: Vec<String>,\n\n}\n\nimpl LocalOutput {\n\n // This is an *extremely* hacky thing.\n\n // In fact, I'm ignoring every backslash in the output by replacing them with forward slashes,\n\n // so that the paths, if the program writes them (either correctly or during panic) are\n\n // compared independently of the platform separator.\n\n // I'm not really sure if this is a way to go, but...\n\n pub fn matches(&self, other: &LocalOutput) -> bool {\n\n self.status == other.status\n\n && match_lines_with_backslashes(&self.stdout, &other.stdout)\n\n && match_lines_with_backslashes(&self.stderr, &other.stderr)\n", "file_path": "src/mismatch.rs", "rank": 84, "score": 12.389043547579695 }, { "content": "//! Batch Run\n\n//! =========\n\n//!\n\n//! [![Latest Version](https://img.shields.io/crates/v/batch_run.svg)](https://crates.io/crates/batch_run)\n\n//! [![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/batch_run)\n\n//!\n\n//! `batch_run` is a runner for a set of Rust source files, based on [dtolnay's `trybuild`](https://github.com/dtolnay/trybuild).\n\n//! It can be useful when you have a bunch of Rust sources which are not complex enough to be\n\n//! packed into dedicated crates, but which are (by their meaning) not just integration test cases.\n\n//! It also checks for output correctness, either on compile-time (for `compile_fail` cases)\n\n//! or at runtime (for `run_pass` cases).\n\n//!\n\n//! ```toml\n\n//! [dependencies]\n\n//! batch_run = \"1.0\"\n\n//! ```\n\n//!\n\n//! *Compiler support: requires rustc 1.31+*\n\n//!\n\n//! <br>\n", "file_path": "src/lib.rs", "rank": 85, "score": 12.260780308566979 }, { "content": "use std::{env, fs::File, io::Write, path::Path};\n\n\n", "file_path": "build.rs", "rank": 86, "score": 10.782237508001526 }, { "content": "}\n\n\n\nimpl From<io::Error> for BatchError {\n\n fn from(err: io::Error) -> Self {\n\n BatchError::Io(err)\n\n }\n\n}\n\n\n\nimpl From<GlobError> for EntryError {\n\n fn from(err: GlobError) -> Self {\n\n EntryError::Glob(err)\n\n }\n\n}\n\n\n\nimpl From<PatternError> for EntryError {\n\n fn from(err: PatternError) -> Self {\n\n EntryError::Pattern(err)\n\n }\n\n}\n\n\n", "file_path": "src/result.rs", "rank": 87, "score": 10.722788522331946 }, { "content": "mod entry;\n\nmod logging;\n\nmod mismatch;\n\nmod normalize;\n\nmod runner;\n\nmod rustflags;\n\nmod snapshot;\n\nmod term;\n\n\n\npub mod config;\n\npub mod result;\n\npub use crate::batch::Batch;\n", "file_path": "src/lib.rs", "rank": 88, "score": 10.586526965508437 }, { "content": " Error(#[source] EntryError),\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum NoExpected {\n\n #[error(\"Output written to WIP folder\")]\n\n ToWip(String),\n\n #[error(\"Output written directly to snapshot\")]\n\n Direct(String),\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum BatchError {\n\n #[error(\"Failed to execute cargo: {0}\")]\n\n Cargo(#[source] io::Error),\n\n #[error(\"Configuration error: {0}\")]\n\n ConfigError(#[source] ConfigError),\n\n #[error(\"General IO error: {0}\")]\n\n Io(#[source] io::Error),\n\n}\n", "file_path": "src/result/error.rs", "rank": 89, "score": 10.147011220920643 }, { "content": " #[error(\"Incorrect glob pattern: {0}\")]\n\n Pattern(#[source] PatternError),\n\n #[error(\"Error reading snapshot: {0}\")]\n\n ReadExpected(#[source] io::Error),\n\n #[error(\"Cannot execute compiled binary: {0}\")]\n\n RunFailed(#[source] io::Error),\n\n #[error(\"Error writing snapshot: {0}\")]\n\n WriteExpected(#[source] io::Error),\n\n}\n\n\n\n#[derive(Debug, Error)]\n\npub enum PrintError {\n\n #[error(\"The internal buffer was already printed\")]\n\n AlreadyPrinted,\n\n #[error(\"I/O error while printing: {0}\")]\n\n Io(#[source] std::io::Error),\n\n}\n", "file_path": "src/result/error.rs", "rank": 90, "score": 9.843212190675267 }, { "content": "pub struct Config<W: WriteColor> {\n\n update_mode: Update,\n\n writer: WriterBuilder<W>,\n\n}\n\n\n\nimpl Default for Config<StandardStream> {\n\n fn default() -> Self {\n\n Self {\n\n update_mode: Default::default(),\n\n writer: Default::default(),\n\n }\n\n }\n\n}\n\n\n\nimpl Config<StandardStream> {\n\n pub fn from_env() -> BatchResult<Self> {\n\n Ok(Self {\n\n update_mode: Update::env()?,\n\n writer: WriterBuilder::default(),\n\n })\n", "file_path": "src/config.rs", "rank": 91, "score": 8.59209768828715 }, { "content": "//! t.run_match(\"batches/04-paste-ident.rs\");\n\n//! t.run_match(\"batches/05-repeat-section.rs\");\n\n//! ```\n\n//!\n\n//! <br>\n\n//!\n\n//! ## Details\n\n//!\n\n//! That's the entire API for now.\n\n//!\n\n//! <br>\n\n//!\n\n//! ## Workflow\n\n//!\n\n//! (TODO)\n\n//!\n\n\n\nmod batch;\n\nmod binary;\n\nmod cargo_rustc;\n", "file_path": "src/lib.rs", "rank": 92, "score": 8.089119793568113 }, { "content": "// use std::sync::{PoisonError, RwLock, RwLockWriteGuard};\n\nuse crate::result::error::PrintError;\n\n\n\nuse lazy_static::lazy_static;\n\nuse termcolor::{\n\n Buffer,\n\n BufferWriter,\n\n ColorChoice,\n\n // StandardStream\n\n};\n\n\n\nlazy_static! {\n\n static ref WRITER: BufferWriter = BufferWriter::stdout(ColorChoice::Auto);\n\n // static ref TERM: RwLock<StandardStream> =\n\n // RwLock::new(StandardStream::stdout(ColorChoice::Auto));\n\n}\n\n\n", "file_path": "src/term.rs", "rank": 93, "score": 8.014486951230008 }, { "content": "impl From<io::Error> for EntryError {\n\n fn from(err: io::Error) -> Self {\n\n EntryError::Io(err)\n\n }\n\n}\n\n\n\nimpl<T: Into<EntryError>> From<T> for EntryFailed {\n\n fn from(input: T) -> Self {\n\n Self::Error(input.into())\n\n }\n\n}\n", "file_path": "src/result.rs", "rank": 94, "score": 7.525141955458713 }, { "content": "//! Normalization primitives for rustc output.\n\n//!\n\n//! Since we're using rustc directly (not cargo), it seems that there is little boilerplate\n\n//! in the compilation output, but it still appears to be.\n\n//! This module is designed to provide a way to remove the unnecessary lines,\n\n//! so they won't appear in either the *.stderr files or in the processing output.\n\n\n\n/// Possible normalizations of the rustc output, arranged from the least to the most preferable.\n\n///\n\n/// For now, there's only one, but we should keep this as a way to generalize later.\n\n#[derive(PartialOrd, PartialEq, Copy, Clone)]\n", "file_path": "src/normalize.rs", "rank": 95, "score": 7.4891670560602215 }, { "content": " }\n\n}\n\nimpl TryFrom<Output> for LocalOutput {\n\n // TODO make some real error and propagate it\n\n type Error = Box<dyn Error>;\n\n fn try_from(input: Output) -> Result<Self, Box<dyn Error>> {\n\n Ok(Self {\n\n status: input.status.code().ok_or(\"No status code\")?,\n\n stdout: bytes_to_lines(&input.stdout),\n\n stderr: bytes_to_lines(&input.stderr),\n\n })\n\n }\n\n}\n", "file_path": "src/mismatch.rs", "rank": 96, "score": 6.781198346950912 }, { "content": "use std::env;\n\nuse std::process::Command;\n\n\n\nconst RUSTFLAGS: &str = \"RUSTFLAGS\";\n\nconst IGNORED_LINTS: &[&str] = &[\"dead_code\"];\n\n\n", "file_path": "src/rustflags.rs", "rank": 97, "score": 6.02929912793471 }, { "content": " where\n\n W: 'static,\n\n {\n\n Self(Rc::new(inner))\n\n }\n\n pub(crate) fn build(&self) -> W {\n\n self.0()\n\n }\n\n}\n\nimpl Default for WriterBuilder<StandardStream> {\n\n fn default() -> Self {\n\n Self(Rc::new(|| StandardStream::stderr(ColorChoice::Always)))\n\n }\n\n}\n\nimpl WriterBuilder<Buffer> {\n\n pub fn buffer() -> Self {\n\n Self(Rc::new(crate::term::buf))\n\n }\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 98, "score": 5.811896517095532 }, { "content": " }\n\n}\n\nimpl<W: WriteColor> Config<W> {\n\n pub fn with_update_mode(self, update_mode: Update) -> Self {\n\n Self {\n\n update_mode,\n\n ..self\n\n }\n\n }\n\n pub fn update_mode(&self) -> Update {\n\n self.update_mode\n\n }\n\n pub fn with_writer<W2: WriteColor>(self, writer: WriterBuilder<W2>) -> Config<W2> {\n\n Config {\n\n writer,\n\n update_mode: self.update_mode,\n\n }\n\n }\n\n pub fn with_buffer(self) -> Config<Buffer> {\n\n Config {\n\n update_mode: self.update_mode,\n\n writer: WriterBuilder::buffer(),\n\n }\n\n }\n\n pub fn writer(&self) -> WriterBuilder<W> {\n\n self.writer.clone()\n\n }\n\n}\n", "file_path": "src/config.rs", "rank": 99, "score": 5.463371206491174 } ]
Rust
src/compiler/compiler.rs
mthom26/monkey-lang
92289eca2a3216ee6042403ecaf1d63e05e29dc0
use crate::{ compiler::{make_op, OpCode, SymbolTable}, evaluator::Object, lexer::lexer, parser::{parse, Expression, Operator, Prefix, Statement}, }; const GLOBAL: &str = "GLOBAL"; #[derive(Debug, PartialEq)] pub struct ByteCode { pub instructions: Vec<u8>, pub constants: Vec<Object>, } impl ByteCode { fn new() -> Self { ByteCode { instructions: vec![], constants: vec![], } } } pub struct Compiler { byte_code: ByteCode, symbol_table: SymbolTable, } impl Compiler { pub fn from_source(input: &str) -> ByteCode { let mut compiler = Compiler { byte_code: ByteCode::new(), symbol_table: SymbolTable::new(), }; let mut tokens = lexer(input.as_bytes()); let ast = parse(&mut tokens); compiler.compile_statements(ast); compiler.byte_code } fn compile_statements(&mut self, ast: Vec<Statement>) { for statement in ast { match statement { Statement::ExpressionStatement(expr) => { self.compile_expression(expr); self.add_instruction(OpCode::OpPop); } Statement::Let { name, value } => { self.compile_expression(value); let symbol_index = self.symbol_table.define(name, GLOBAL.to_owned()); self.add_instruction(OpCode::OpSetGlobal(symbol_index)); } _ => unimplemented!(), } } } fn compile_expression(&mut self, expr: Expression) { match expr { Expression::Int(val) => { let index = self.add_constant(Object::Int(val)); self.add_instruction(OpCode::OpConstant(index)); } Expression::Boolean(val) => { match val { true => self.add_instruction(OpCode::OpTrue), false => self.add_instruction(OpCode::OpFalse), }; } Expression::Ident(val) => { match self.symbol_table.resolve(val) { Some(index) => self.add_instruction(OpCode::OpGetGlobal(index)), None => panic!("Undefined variable"), }; } Expression::Infix { left, op, right } => { self.compile_expression(*left); self.compile_expression(*right); match op { Operator::PLUS => self.add_instruction(OpCode::OpAdd), Operator::MINUS => self.add_instruction(OpCode::OpSub), Operator::MULTIPLY => self.add_instruction(OpCode::OpMul), Operator::DIVIDE => self.add_instruction(OpCode::OpDiv), Operator::GREATER => self.add_instruction(OpCode::OpGreater), Operator::LESS => self.add_instruction(OpCode::OpLess), Operator::EQUAL => self.add_instruction(OpCode::OpEqual), Operator::NEQUAL => self.add_instruction(OpCode::OpNotEqual), }; } Expression::Prefix { prefix, value } => { self.compile_expression(*value); match prefix { Prefix::MINUS => self.add_instruction(OpCode::OpMinus), Prefix::BANG => self.add_instruction(OpCode::OpBang), }; } Expression::If { condition, consequence, alternative, } => { self.compile_expression(*condition); let jmp_false = self.byte_code.instructions.len(); self.add_instruction(OpCode::OpJmpIfFalse(9999)); self.compile_statements(consequence); if self.is_last_instruction_pop() { self.remove_last_pop(); } if alternative.len() == 0 { let new_jmp_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp_false, OpCode::OpJmpIfFalse(new_jmp_pos)); } else { let jmp = self.byte_code.instructions.len(); self.add_instruction(OpCode::OpJmp(9999)); let jmp_false_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp_false, OpCode::OpJmpIfFalse(jmp_false_pos)); self.compile_statements(alternative); if self.is_last_instruction_pop() { self.remove_last_pop(); } let jmp_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp, OpCode::OpJmp(jmp_pos)); } } _ => unimplemented!(), } } fn add_constant(&mut self, object: Object) -> u16 { self.byte_code.constants.push(object); (self.byte_code.constants.len() - 1) as u16 } fn add_instruction(&mut self, op_code: OpCode) -> u16 { let new_instruction_position = self.byte_code.instructions.len(); let op_bytes = make_op(op_code); self.byte_code.instructions.extend(op_bytes); new_instruction_position as u16 } fn is_last_instruction_pop(&self) -> bool { self.byte_code.instructions.last() == Some(&make_op(OpCode::OpPop)[0]) } fn remove_last_pop(&mut self) { self.byte_code.instructions.pop(); } fn replace_op(&mut self, pos: usize, opcode: OpCode) { let bytes = make_op(opcode); for (i, byte) in bytes.iter().enumerate() { self.byte_code.instructions[pos + i] = *byte; } } } #[cfg(test)] mod tests { use crate::{ compiler::{ByteCode, Compiler}, evaluator::Object, }; fn compiled(input: &str) -> ByteCode { Compiler::from_source(input) } #[test] fn test_basic_expressions() { let input = "3"; let expected = ByteCode { instructions: vec![1, 0, 0, 6], constants: vec![Object::Int(3)], }; assert_eq!(expected, compiled(input)); let input = "1 + 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 2, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 + 2 + 3"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 1, 0, 1, 2, 1, 0, 2, 2, 6, ], constants: vec![Object::Int(1), Object::Int(2), Object::Int(3)], }; assert_eq!(expected, compiled(input)); let input = "1 - 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 3, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 * 2 - 3 / 3 + 4"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 1, 0, 1, 4, 1, 0, 2, 1, 0, 3, 5, 3, 1, 0, 4, 2, 6, ], constants: vec![ Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(3), Object::Int(4), ], }; assert_eq!(expected, compiled(input)); } #[test] fn test_booleans() { let input = "true"; let expected = ByteCode { instructions: vec![7, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); let input = "false;"; let expected = ByteCode { instructions: vec![8, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); } #[test] fn test_comparison_operators() { let input = "1 > 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 9, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 < 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 10, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 == 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 11, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 != 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 12, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); } #[test] fn test_prefixes() { let input = "-1"; let expected = ByteCode { instructions: vec![1, 0, 0, 14, 6], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); let input = "!false"; let expected = ByteCode { instructions: vec![8, 13, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); } #[test] fn test_if() { let input = "if(true) { 10 }"; let expected = ByteCode { instructions: vec![7, 16, 0, 7, 1, 0, 0, 6], constants: vec![Object::Int(10)], }; assert_eq!(expected, compiled(input)); let input = "if(true) { 10 } else { 20 }"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 7, 16, 0, 10, 1, 0, 0, 15, 0, 13, 1, 0, 1, 6, ], constants: vec![Object::Int(10), Object::Int(20)], }; assert_eq!(expected, compiled(input)); } #[test] fn test_globals() { let input = "let one = 1; let two = 2;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 1, 0, 1, 17, 0, 1, ], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "let one = 1; let two = one; let three = two;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 18, 0, 0, 17, 0, 1, 18, 0, 1, 17, 0, 2, ], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); let input = "let x = 1; x;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 18, 0, 0, 6, ], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); } }
use crate::{ compiler::{make_op, OpCode, SymbolTable}, evaluator::Object, lexer::lexer, parser::{parse, Expression, Operator, Prefix, Statement}, }; const GLOBAL: &str = "GLOBAL"; #[derive(Debug, PartialEq)] pub struct ByteCode { pub instructions: Vec<u8>, pub constants: Vec<Object>, } impl ByteCode { fn new() -> Self { ByteCode { instructions: vec![], constants: vec![], } } } pub struct Compiler { byte_code: ByteCode, symbol_table: SymbolTable, } impl Compiler { pub fn from_source(input: &str) -> ByteCode { let mut compiler = Compiler { byte_code: ByteCode::new(), symbol_table: SymbolTable::new(), }; let mut tokens = lexer(input.as_bytes()); let ast = parse(&mut tokens); compiler.compile_statements(ast); compiler.byte_code } fn compile_statements(&mut self, ast: Vec<Statement>) { for statement in ast { match statement { Statement::ExpressionStatement(expr) => { self.compile_expression(expr); self.add_instruction(OpCode::OpPop); } Statement::Let { name, value } => { self.compile_expression(value); let symbol_index = self.symbol_table.define(name, GLOBAL.to_owned()); self.add_instruction(OpCode::OpSetGlobal(symbol_index)); } _ => unimplemented!(), } } } fn compile_expression(&mut self, expr: Expression) { match expr { Expression::Int(val) => { let index = self.add_constant(Object::Int(val)); self.add_instruction(OpCode::OpConstant(index)); } Expression::Boolean(val) => { match val { true => self.add_instruction(OpCode::OpTrue), false => self.add_instruction(OpCode::OpFalse), }; } Expression::Ident(val) => { match self.symbol_table.resolve(val) { Some(index) => self.add_instruction(OpCode::OpGetGlobal(index)), None => panic!("Undefined variable"), }; } Expression::Infix { left, op, right } => { self.compile_expression(*left); self.compile_expression(*right); match op { Operator::PLUS => self.add_instruction(OpCode::OpAdd), Operator::MINUS => self.add_instruction(OpCode::OpSub), Operator::MULTIPLY => self.add_instruction(OpCode::OpMul), Operator::DIVIDE => self.add_instruction(OpCode::OpDiv), Operator::GREATER => self.add_instruction(OpCode::OpGreater), Operator::LESS => self.add_instruction(OpCode::OpLess), Operator::EQUAL => self.add_instruction(OpCode::OpEqual), Operator::NEQUAL => self.add_instruction(OpCode::OpNotEqual), }; } Expression::Prefix { prefix, value } => { self.compile_expression(*value); match prefix { Prefix::MINUS => self.add_instruction(OpCode::OpMinus), Prefix::BANG => self.add_instruction(OpCode::OpBang), }; } Expression::If { condition, consequence, alternative, } => { self.compile_expression(*condition); let jmp_false = self.byte_code.instructions.len(); self.add_instruction(OpCode::OpJmpIfFalse(9999)); self.compile_statements(consequence); if self.is_last_instruction_pop() { self.remove_last_pop(); } if alternative.len() == 0 { let new_jmp_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp_false, OpCode::OpJmpIfFalse(new_jmp_pos)); } else { let jmp = self.byte_code.instructions.len(); self.add_instruction(OpCode::OpJmp(9999)); let jmp_false_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp_false, OpCode::OpJmpIfFalse(jmp_false_pos)); self.compile_statements(alternative); if self.is_last_instruction_pop() { self.remove_last_pop(); } let jmp_pos = self.byte_code.instructions.len() as u16; self.replace_op(jmp, OpCode::OpJmp(jmp_pos)); } } _ => unimplemented!(), } } fn add_constant(&mut self, object: Object) -> u16 { self.byte_code.constants.push(object); (self.byte_code.constants.len() - 1) as u16 } fn add_instruction(&mut self, op_code: OpCode) -> u16 { let new_instruction_position = self.byte_code.instructions.len(); let op_bytes = make_op(op_code); self.byte_code.instructions.extend(op_bytes); new_instruction_position as u16 } fn is_last_instruction_pop(&self) -> bool { self.byte_code.instructions.last() == Some(&make_op(OpCode::OpPop)[0]) } fn remove_last_pop(&mut self) { self.byte_code.instructions.pop(); } fn replace_op(&mut self, pos: usize, opcode: OpCode) { let bytes = make_op(opcode); for (i, byte) in bytes.iter().enumerate() { self.byte_code.instructions[pos + i] = *byte; } } } #[cfg(test)] mod tests { use crate::{ compiler::{ByteCode, Compiler}, evaluator::Object, }; fn compiled(input: &str) -> ByteCode { Compiler::from_source(input) } #[test] fn test_basic_expressions() { let input = "3"; let expected = ByteCode { instructions: vec![1, 0, 0, 6], constants: vec![Object::Int(3)], }; assert_eq!(expected, compiled(input)); let input = "1 + 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 2, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 + 2 + 3"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 1, 0, 1, 2, 1, 0, 2, 2, 6, ], constants: vec![Object::Int(1), Object::Int(2), Object::Int(3)], }; assert_eq!(expected, compiled(input)); let input = "1 - 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 3, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 * 2 - 3 / 3 + 4"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 1, 0, 1, 4, 1, 0, 2, 1, 0, 3, 5, 3, 1, 0, 4, 2, 6, ], constants: vec![ Object::Int(1), Object::Int(2), Object::Int(3), Object::Int(3), Object::Int(4), ], }; assert_eq!(expected, compiled(input)); } #[test] fn test_booleans() { let input = "true"; let expected = ByteCode { instructions: vec![7, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); let input = "false;"; let expected = ByteCode { instructions: vec![8, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); } #[test] fn test_comparison_operators() { let input = "1 > 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 9, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 < 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 10, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 == 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 11, 6], constants: vec![Object::I
input = "let x = 1; x;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 18, 0, 0, 6, ], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); } }
nt(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "1 != 2"; let expected = ByteCode { instructions: vec![1, 0, 0, 1, 0, 1, 12, 6], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); } #[test] fn test_prefixes() { let input = "-1"; let expected = ByteCode { instructions: vec![1, 0, 0, 14, 6], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); let input = "!false"; let expected = ByteCode { instructions: vec![8, 13, 6], constants: vec![], }; assert_eq!(expected, compiled(input)); } #[test] fn test_if() { let input = "if(true) { 10 }"; let expected = ByteCode { instructions: vec![7, 16, 0, 7, 1, 0, 0, 6], constants: vec![Object::Int(10)], }; assert_eq!(expected, compiled(input)); let input = "if(true) { 10 } else { 20 }"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 7, 16, 0, 10, 1, 0, 0, 15, 0, 13, 1, 0, 1, 6, ], constants: vec![Object::Int(10), Object::Int(20)], }; assert_eq!(expected, compiled(input)); } #[test] fn test_globals() { let input = "let one = 1; let two = 2;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 1, 0, 1, 17, 0, 1, ], constants: vec![Object::Int(1), Object::Int(2)], }; assert_eq!(expected, compiled(input)); let input = "let one = 1; let two = one; let three = two;"; #[rustfmt::skip] let expected = ByteCode { instructions: vec![ 1, 0, 0, 17, 0, 0, 18, 0, 0, 17, 0, 1, 18, 0, 1, 17, 0, 2, ], constants: vec![Object::Int(1)], }; assert_eq!(expected, compiled(input)); let
random
[ { "content": "pub fn eval(ast: Vec<Statement>, env: &mut Environment) -> Object {\n\n let result = eval_block(ast, env);\n\n\n\n // If final result is a Return unwrap it...\n\n match result {\n\n Object::Return(val) => *val,\n\n _ => result,\n\n }\n\n}\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 0, "score": 172347.63644036872 }, { "content": "pub fn parse(tokens: &mut VecDeque<Token>) -> Vec<Statement> {\n\n let mut statements: Vec<Statement> = Vec::new();\n\n\n\n loop {\n\n match &tokens[0] {\n\n Token::EOF => break,\n\n Token::LET => {\n\n tokens.pop_front(); // Discard LET Token\n\n let statement = parse_let(tokens);\n\n assert_eq!(Token::SEMICOLON, tokens.pop_front().unwrap());\n\n statements.push(statement);\n\n }\n\n Token::RETURN => {\n\n tokens.pop_front(); // Discard RETURN Token\n\n let statement = parse_return(tokens);\n\n assert_eq!(Token::SEMICOLON, tokens.pop_front().unwrap());\n\n statements.push(statement);\n\n }\n\n Token::RBRACE => break, // We must be at end of a block so break\n\n _ => {\n", "file_path": "src/parser.rs", "rank": 1, "score": 170612.48664909962 }, { "content": "pub fn eval_block(ast: Vec<Statement>, env: &mut Environment) -> Object {\n\n let mut result = Object::Null;\n\n\n\n for statement in ast {\n\n match statement {\n\n Statement::ExpressionStatement(exp) => {\n\n result = eval_expression(exp, env);\n\n }\n\n Statement::Return { value } => {\n\n result = Object::Return(Box::new(eval_expression(value, env)));\n\n }\n\n Statement::Let { name, value } => {\n\n let new_value = eval_expression(value, env);\n\n env.set(name, new_value.clone());\n\n result = new_value\n\n }\n\n }\n\n\n\n match result {\n\n Object::Return(_) => break,\n\n _ => (),\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 2, "score": 168037.30980785508 }, { "content": "fn parse_let(tokens: &mut VecDeque<Token>) -> Statement {\n\n let name = match tokens.pop_front() {\n\n Some(Token::IDENT(name)) => name.clone(),\n\n _ => panic!(\"Parse error in let statement. Expected Identifier.\"),\n\n };\n\n\n\n match tokens.pop_front() {\n\n Some(Token::ASSIGN) => (),\n\n _ => panic!(\"Parse error in let statement. Expected ASSIGN Token.\"),\n\n };\n\n\n\n let value = parse_expression(tokens, Precedence::LOWEST);\n\n\n\n Statement::Let { name, value }\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 3, "score": 154855.4573350227 }, { "content": "fn parse_infix(tokens: &mut VecDeque<Token>, left: Expression) -> Expression {\n\n // println!(\"parse_infix: {:?}\", &tokens[0]);\n\n let (op, precedence) = match tokens.pop_front() {\n\n Some(Token::MINUS) => (Operator::MINUS, Token::MINUS.precedence()),\n\n Some(Token::PLUS) => (Operator::PLUS, Token::PLUS.precedence()),\n\n Some(Token::ASTERISK) => (Operator::MULTIPLY, Token::ASTERISK.precedence()),\n\n Some(Token::SLASH) => (Operator::DIVIDE, Token::SLASH.precedence()),\n\n Some(Token::EQ) => (Operator::EQUAL, Token::EQ.precedence()),\n\n Some(Token::NEQ) => (Operator::NEQUAL, Token::NEQ.precedence()),\n\n Some(Token::GT) => (Operator::GREATER, Token::GT.precedence()),\n\n Some(Token::LT) => (Operator::LESS, Token::LT.precedence()),\n\n _ => panic!(\"Parse Infix called on invalid Token.\"),\n\n };\n\n\n\n let right_exp = parse_expression(tokens, precedence);\n\n\n\n Expression::Infix {\n\n left: Box::new(left),\n\n op,\n\n right: Box::new(right_exp),\n", "file_path": "src/parser.rs", "rank": 4, "score": 148106.60189295866 }, { "content": "fn eval_builtin(fn_name: &str, args: Vec<Object>) -> Object {\n\n match (fn_name, args.as_slice()) {\n\n (\"len\", [Object::String(val)]) => Object::Int(val.len() as isize),\n\n (\"lowerCase\", [Object::String(val)]) => Object::String(val.to_lowercase()),\n\n (\"upperCase\", [Object::String(val)]) => Object::String(val.to_uppercase()),\n\n _ => Object::Null,\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n\n evaluator::{eval, Environment, Object},\n\n lexer::lexer,\n\n parser::{parse, Expression, Statement},\n\n };\n\n\n\n // Convenience function to lex, parse and eval an input\n\n fn evaluated(input: &str) -> Object {\n\n let mut tokens = lexer(input.as_bytes());\n", "file_path": "src/evaluator/evaluator.rs", "rank": 5, "score": 141760.57737165713 }, { "content": "pub fn make_op(opcode: OpCode) -> Vec<u8> {\n\n match opcode {\n\n OpCode::OpConstant(operand) => {\n\n let mut output = vec![0x01];\n\n let int_one = (operand >> 8) as u8;\n\n let int_two = operand as u8;\n\n output.push(int_one);\n\n output.push(int_two);\n\n output\n\n }\n\n OpCode::OpAdd => vec![0x02],\n\n OpCode::OpSub => vec![0x03],\n\n OpCode::OpMul => vec![0x04],\n\n OpCode::OpDiv => vec![0x05],\n\n OpCode::OpPop => vec![0x06],\n\n OpCode::OpTrue => vec![0x07],\n\n OpCode::OpFalse => vec![0x08],\n\n OpCode::OpGreater => vec![0x09],\n\n OpCode::OpLess => vec![0x0a],\n\n OpCode::OpEqual => vec![0x0b],\n", "file_path": "src/compiler/code.rs", "rank": 6, "score": 139324.2239451797 }, { "content": "fn parse_return(tokens: &mut VecDeque<Token>) -> Statement {\n\n let value = parse_expression(tokens, Precedence::LOWEST);\n\n\n\n Statement::Return { value }\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 7, "score": 137296.99994447787 }, { "content": "pub fn lexer(input: &[u8]) -> VecDeque<Token> {\n\n let mut pos = 0;\n\n let mut tokens = VecDeque::new();\n\n\n\n loop {\n\n if pos >= input.len() {\n\n tokens.push_back(Token::EOF);\n\n break;\n\n }\n\n match input[pos] {\n\n ch if is_letter(ch) => {\n\n let (new_pos, token) = read_letters(pos, input);\n\n tokens.push_back(token);\n\n pos = new_pos;\n\n }\n\n ch if is_digit(ch) => {\n\n let (new_pos, token) = read_digits(pos, input);\n\n tokens.push_back(token);\n\n pos = new_pos;\n\n }\n", "file_path": "src/lexer.rs", "rank": 8, "score": 133413.86383579514 }, { "content": "fn parse_expression(tokens: &mut VecDeque<Token>, precedence: Precedence) -> Expression {\n\n // println!(\"parse_expression: {:?}\", &tokens[0]);\n\n let mut left_exp = match tokens.pop_front() {\n\n Some(Token::INT(val)) => Expression::Int(val),\n\n Some(Token::TRUE) => Expression::Boolean(true),\n\n Some(Token::FALSE) => Expression::Boolean(false),\n\n Some(Token::STRING(val)) => Expression::String(val),\n\n Some(Token::IDENT(name)) => {\n\n if tokens[0] == Token::LPAREN {\n\n // Ident followed by LPAREN is a function call\n\n assert_eq!(Token::LPAREN, tokens.pop_front().unwrap());\n\n let mut args = vec![];\n\n\n\n loop {\n\n match tokens[0] {\n\n Token::RPAREN => break,\n\n _ => {\n\n let arg = parse_expression(tokens, Precedence::LOWEST);\n\n args.push(arg);\n\n }\n", "file_path": "src/parser.rs", "rank": 9, "score": 122281.4202056345 }, { "content": "fn eval_expression(exp: Expression, env: &mut Environment) -> Object {\n\n match exp {\n\n Expression::Int(val) => Object::Int(val),\n\n Expression::Boolean(val) => Object::Boolean(val),\n\n Expression::String(val) => Object::String(val),\n\n Expression::Prefix { prefix, value } => match prefix {\n\n Prefix::BANG => match eval_expression(*value, env) {\n\n Object::Boolean(val) => Object::Boolean(!val),\n\n _ => panic!(\"'!' operator only valid for boolean types\"),\n\n },\n\n Prefix::MINUS => match eval_expression(*value, env) {\n\n Object::Int(val) => Object::Int(-val),\n\n _ => panic!(\"'-' operator only valid for integer types\"),\n\n },\n\n },\n\n Expression::Infix { left, op, right } => match op {\n\n // Integer operations\n\n Operator::PLUS => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Int(l_val + r_val),\n\n _ => panic!(\"'+' operator only valid on integers\"),\n", "file_path": "src/evaluator/evaluator.rs", "rank": 10, "score": 104001.31309738292 }, { "content": "fn read_letters(start_pos: usize, input: &[u8]) -> (usize, Token) {\n\n let mut pos = start_pos;\n\n let mut identifier = Vec::new();\n\n // Add next character to identifier until next character is not a letter\n\n while pos < input.len() && is_letter(input[pos]) {\n\n identifier.push(input[pos]);\n\n pos += 1;\n\n }\n\n\n\n let token = is_keyword(&identifier);\n\n (pos - 1, token)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 11, "score": 103641.97495341775 }, { "content": "fn read_string(start_pos: usize, input: &[u8]) -> (usize, Token) {\n\n let mut pos = start_pos + 1;\n\n let mut value = Vec::new();\n\n\n\n while input[pos] != 39 {\n\n value.push(input[pos]);\n\n pos += 1;\n\n }\n\n\n\n let token = Token::STRING(String::from_utf8_lossy(&value).to_string());\n\n (pos, token)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 12, "score": 103641.97495341775 }, { "content": "fn read_digits(start_pos: usize, input: &[u8]) -> (usize, Token) {\n\n let mut pos = start_pos;\n\n let mut identifier = Vec::new();\n\n // Add next character to identifier until next character is not a letter\n\n while pos < input.len() && is_digit(input[pos]) {\n\n identifier.push(input[pos]);\n\n pos += 1;\n\n }\n\n\n\n let num: isize = String::from_utf8_lossy(&identifier)\n\n .to_string()\n\n .parse()\n\n .unwrap();\n\n\n\n let token = Token::INT(num);\n\n (pos - 1, token)\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 13, "score": 103641.97495341775 }, { "content": "pub fn two_u8_to_usize(int_one: u8, int_two: u8) -> usize {\n\n ((int_one as usize) << 8) | int_two as usize\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::compiler::{make_op, two_u8_to_usize, OpCode};\n\n\n\n #[test]\n\n fn make_op_constant() {\n\n let op = make_op(OpCode::OpConstant(65534));\n\n let expected = vec![0x01, 255, 254];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpConstant(4449));\n\n let expected = vec![0x01, 17, 97];\n\n assert_eq!(expected, op);\n\n }\n\n\n\n #[test]\n", "file_path": "src/compiler/code.rs", "rank": 14, "score": 85334.10579300119 }, { "content": "// Peek at the next character in input\n\nfn peek_next_char(start_pos: usize, input: &[u8]) -> u8 {\n\n if start_pos >= input.len() {\n\n // We must be at the EOF, outer loop should catch this so it\n\n // might not be needed here...\n\n return 0;\n\n }\n\n input[start_pos + 1]\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::lexer::{is_letter, lexer, Token};\n\n use std::collections::VecDeque;\n\n\n\n #[test]\n\n fn lex_tokens() {\n\n let input = \"{}();,\";\n\n\n\n let tokens = lexer(input.as_bytes());\n\n let expected = VecDeque::from(vec![\n", "file_path": "src/lexer.rs", "rank": 15, "score": 70858.89488749343 }, { "content": "fn is_digit(ch: u8) -> bool {\n\n b'0' <= ch && ch <= b'9'\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 16, "score": 67827.67577419554 }, { "content": "#[rustfmt::skip]\n\nfn is_letter(ch: u8) -> bool {\n\n b'a' <= ch && ch <= b'z' ||\n\n b'A' <= ch && ch <= b'Z' ||\n\n b'_' == ch\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 17, "score": 67827.67577419554 }, { "content": "fn is_keyword(chars: &[u8]) -> Token {\n\n match chars {\n\n [b'l', b'e', b't'] => Token::LET,\n\n [b'f', b'n'] => Token::FN,\n\n [b'i', b'f'] => Token::IF,\n\n [b'e', b'l', b's', b'e'] => Token::ELSE,\n\n [b'r', b'e', b't', b'u', b'r', b'n'] => Token::RETURN,\n\n [b't', b'r', b'u', b'e'] => Token::TRUE,\n\n [b'f', b'a', b'l', b's', b'e'] => Token::FALSE,\n\n chars => Token::IDENT(String::from_utf8_lossy(chars).to_string()),\n\n }\n\n}\n\n\n", "file_path": "src/lexer.rs", "rank": 18, "score": 66907.65107380893 }, { "content": "mod code;\n\nmod compiler;\n\nmod symbol_table;\n\npub use code::{make_op, two_u8_to_usize, OpCode};\n\npub use compiler::{ByteCode, Compiler};\n\npub use symbol_table::SymbolTable;\n", "file_path": "src/compiler/mod.rs", "rank": 19, "score": 49045.38041908712 }, { "content": "fn main() {\n\n let mut rl = rustyline::Editor::<()>::new();\n\n let mut env = Environment::new();\n\n\n\n loop {\n\n match rl.readline(\">> \") {\n\n Ok(line) => {\n\n let mut tokens = lexer(line.as_bytes());\n\n let ast = parse(&mut tokens);\n\n let evaluated = eval(ast, &mut env);\n\n\n\n match evaluated {\n\n Object::Int(val) => println!(\"{}\", val),\n\n Object::Boolean(val) => println!(\"{}\", val),\n\n Object::Null => println!(\"Null\"),\n\n _ => println!(\"Evaluation Error\"),\n\n }\n\n }\n\n Err(ReadlineError::Interrupted) => break, // 'Ctrl-c' pressed\n\n Err(_) => println!(\"No Input\"),\n\n }\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 20, "score": 42597.292224048346 }, { "content": "mod environment;\n\nmod evaluator;\n\npub use environment::Environment;\n\npub use evaluator::{eval, Object};\n", "file_path": "src/evaluator/mod.rs", "rank": 40, "score": 25258.364207130366 }, { "content": " let op = make_op(OpCode::OpJmpIfFalse(65534));\n\n let expected = vec![0x10, 255, 254];\n\n assert_eq!(expected, op);\n\n }\n\n\n\n #[test]\n\n fn test_globals() {\n\n let op = make_op(OpCode::OpSetGlobal(65534));\n\n let expected = vec![0x11, 255, 254];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpGetGlobal(65534));\n\n let expected = vec![0x12, 255, 254];\n\n assert_eq!(expected, op);\n\n }\n\n\n\n #[test]\n\n fn test_two_u8_to_usize() {\n\n let input = two_u8_to_usize(1, 1);\n\n let expected = 257;\n\n assert_eq!(expected, input);\n\n\n\n let input = two_u8_to_usize(10, 77);\n\n let expected = 2637;\n\n assert_eq!(expected, input);\n\n }\n\n}\n", "file_path": "src/compiler/code.rs", "rank": 41, "score": 23801.28858337103 }, { "content": "pub enum OpCode {\n\n OpConstant(u16),\n\n OpAdd,\n\n OpSub,\n\n OpMul,\n\n OpDiv,\n\n OpPop,\n\n OpTrue,\n\n OpFalse,\n\n OpGreater,\n\n OpLess,\n\n OpEqual,\n\n OpNotEqual,\n\n OpBang,\n\n OpMinus,\n\n OpJmp(u16),\n\n OpJmpIfFalse(u16),\n\n OpSetGlobal(u16),\n\n OpGetGlobal(u16),\n\n}\n\n\n", "file_path": "src/compiler/code.rs", "rank": 42, "score": 23797.30846572883 }, { "content": "\n\n let op = make_op(OpCode::OpNotEqual);\n\n let expected = vec![0x0c];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpBang);\n\n let expected = vec![0x0d];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpMinus);\n\n let expected = vec![0x0e];\n\n assert_eq!(expected, op);\n\n }\n\n\n\n #[test]\n\n fn test_jumps() {\n\n let op = make_op(OpCode::OpJmp(65534));\n\n let expected = vec![0x0f, 255, 254];\n\n assert_eq!(expected, op);\n\n\n", "file_path": "src/compiler/code.rs", "rank": 43, "score": 23793.4901046594 }, { "content": "\n\n let op = make_op(OpCode::OpTrue);\n\n let expected = vec![0x07];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpFalse);\n\n let expected = vec![0x08];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpGreater);\n\n let expected = vec![0x09];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpLess);\n\n let expected = vec![0x0a];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpEqual);\n\n let expected = vec![0x0b];\n\n assert_eq!(expected, op);\n", "file_path": "src/compiler/code.rs", "rank": 44, "score": 23791.175384039867 }, { "content": " OpCode::OpNotEqual => vec![0x0c],\n\n OpCode::OpBang => vec![0x0d],\n\n OpCode::OpMinus => vec![0x0e],\n\n OpCode::OpJmp(operand) => {\n\n let mut output = vec![0x0f];\n\n let int_one = (operand >> 8) as u8;\n\n let int_two = operand as u8;\n\n output.push(int_one);\n\n output.push(int_two);\n\n output\n\n }\n\n OpCode::OpJmpIfFalse(operand) => {\n\n let mut output = vec![0x10];\n\n let int_one = (operand >> 8) as u8;\n\n let int_two = operand as u8;\n\n output.push(int_one);\n\n output.push(int_two);\n\n output\n\n }\n\n OpCode::OpSetGlobal(operand) => {\n", "file_path": "src/compiler/code.rs", "rank": 45, "score": 23791.173948713338 }, { "content": " fn make_ops() {\n\n let op = make_op(OpCode::OpAdd);\n\n let expected = vec![0x02];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpSub);\n\n let expected = vec![0x03];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpMul);\n\n let expected = vec![0x04];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpDiv);\n\n let expected = vec![0x05];\n\n assert_eq!(expected, op);\n\n\n\n let op = make_op(OpCode::OpPop);\n\n let expected = vec![0x06];\n\n assert_eq!(expected, op);\n", "file_path": "src/compiler/code.rs", "rank": 46, "score": 23789.71230000656 }, { "content": " let mut output = vec![0x11];\n\n let int_one = (operand >> 8) as u8;\n\n let int_two = operand as u8;\n\n output.push(int_one);\n\n output.push(int_two);\n\n output\n\n }\n\n OpCode::OpGetGlobal(operand) => {\n\n let mut output = vec![0x12];\n\n let int_one = (operand >> 8) as u8;\n\n let int_two = operand as u8;\n\n output.push(int_one);\n\n output.push(int_two);\n\n output\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/compiler/code.rs", "rank": 47, "score": 23788.207532612967 }, { "content": " SymbolTable {\n\n symbols: HashMap::new(),\n\n next_index: 0,\n\n }\n\n }\n\n\n\n pub fn define(&mut self, name: String, scope: String) -> u16 {\n\n let symbol = Symbol::new(self.next_index, scope);\n\n self.symbols.insert(name, symbol);\n\n self.next_index += 1;\n\n self.next_index - 1\n\n }\n\n\n\n pub fn resolve(&self, name: String) -> Option<u16> {\n\n let symbol = self.symbols.get(&name);\n\n\n\n match symbol {\n\n Some(val) => Some(val.index),\n\n None => None,\n\n }\n\n }\n\n}\n", "file_path": "src/compiler/symbol_table.rs", "rank": 48, "score": 22394.29564749109 }, { "content": "use std::collections::HashMap;\n\n\n\npub struct Symbol {\n\n index: u16,\n\n scope: String,\n\n}\n\n\n\nimpl Symbol {\n\n pub fn new(index: u16, scope: String) -> Self {\n\n Symbol { index, scope }\n\n }\n\n}\n\n\n\npub struct SymbolTable {\n\n symbols: HashMap<String, Symbol>,\n\n next_index: u16,\n\n}\n\n\n\nimpl SymbolTable {\n\n pub fn new() -> Self {\n", "file_path": "src/compiler/symbol_table.rs", "rank": 49, "score": 22391.25456536724 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n\n lexer::lexer,\n\n parser::{parse, Expression, Operator, Prefix, Statement},\n\n };\n\n\n\n #[test]\n\n fn parse_basic_let_statement() {\n\n let input = \"let var_name = 8;\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::Let {\n\n name: \"var_name\".to_owned(),\n\n value: Expression::Int(8),\n", "file_path": "src/parser.rs", "rank": 50, "score": 39.070350707291375 }, { "content": " let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::If {\n\n condition: Box::new(Expression::Int(7)),\n\n consequence: vec![Statement::ExpressionStatement(Expression::Infix {\n\n left: Box::new(Expression::Int(1)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(3)),\n\n })],\n\n alternative: vec![Statement::ExpressionStatement(Expression::Int(8))],\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn test_prefixes() {\n\n let input = \"let a = -33;\n\n let b = !true;\n\n let c = -1 + 2 + 3;\";\n", "file_path": "src/parser.rs", "rank": 51, "score": 37.41293994995799 }, { "content": "\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![\n\n Statement::Let {\n\n name: \"a\".to_owned(),\n\n value: Expression::Prefix {\n\n prefix: Prefix::MINUS,\n\n value: Box::new(Expression::Int(33)),\n\n },\n\n },\n\n Statement::Let {\n\n name: \"b\".to_owned(),\n\n value: Expression::Prefix {\n\n prefix: Prefix::BANG,\n\n value: Box::new(Expression::Boolean(true)),\n\n },\n\n },\n\n Statement::Let {\n", "file_path": "src/parser.rs", "rank": 52, "score": 35.07393014882739 }, { "content": " let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::Infix {\n\n left: Box::new(Expression::Int(1)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Infix {\n\n left: Box::new(Expression::Int(2)),\n\n op: Operator::MULTIPLY,\n\n right: Box::new(Expression::Int(3)),\n\n }),\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn test_if_statement() {\n\n let input = \"if (7) { 1 + 3 } else { 8 }\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n", "file_path": "src/parser.rs", "rank": 53, "score": 34.53394241104522 }, { "content": " let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::Infix {\n\n left: Box::new(Expression::Int(2)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Infix {\n\n left: Box::new(Expression::Int(5)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(8)),\n\n }),\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn parse_operators() {\n\n let input = \"1 + 2 * 3\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n", "file_path": "src/parser.rs", "rank": 54, "score": 34.0499650541421 }, { "content": " fn parse_basic_expression() {\n\n let input = \"2 + 5 + 8\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::Infix {\n\n left: Box::new(Expression::Infix {\n\n left: Box::new(Expression::Int(2)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(5)),\n\n }),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(8)),\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 55, "score": 33.48424237369416 }, { "content": " Statement::Let {\n\n name: \"name\".to_owned(),\n\n value: Expression::String(\"spyro\".to_owned()),\n\n },\n\n Statement::ExpressionStatement(Expression::If {\n\n condition: Box::new(Expression::Ident(\"hello\".to_owned())),\n\n consequence: vec![\n\n Statement::Let {\n\n name: \"y\".to_owned(),\n\n value: Expression::Ident(\"x\".to_owned()),\n\n },\n\n Statement::ExpressionStatement(Expression::Int(11)),\n\n ],\n\n alternative: vec![Statement::ExpressionStatement(Expression::Infix {\n\n left: Box::new(Expression::Int(2)),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Infix {\n\n left: Box::new(Expression::Int(3)),\n\n op: Operator::MULTIPLY,\n\n right: Box::new(Expression::Int(9)),\n", "file_path": "src/parser.rs", "rank": 56, "score": 32.27416670068767 }, { "content": " let y = x;\n\n 11\n\n } else {\n\n 2 + 3 * 9\n\n }\n\n \n\n return 1;\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![\n\n Statement::Let {\n\n name: \"x\".to_owned(),\n\n value: Expression::Int(7),\n\n },\n\n Statement::Let {\n\n name: \"hello\".to_owned(),\n\n value: Expression::Boolean(true),\n\n },\n", "file_path": "src/parser.rs", "rank": 57, "score": 31.41590322655159 }, { "content": "use crate::lexer::Token;\n\nuse std::collections::VecDeque;\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Statement {\n\n Let { name: String, value: Expression },\n\n Return { value: Expression },\n\n ExpressionStatement(Expression),\n\n}\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Expression {\n\n Int(isize),\n\n Boolean(bool),\n\n Ident(String),\n\n String(String),\n\n Infix {\n\n left: Box<Expression>,\n\n op: Operator,\n\n right: Box<Expression>,\n", "file_path": "src/parser.rs", "rank": 58, "score": 30.082343637043518 }, { "content": "use crate::{\n\n compiler::{two_u8_to_usize, ByteCode},\n\n evaluator::Object,\n\n};\n\nuse std::mem;\n\n\n\nconst STACK_SIZE: usize = 2048;\n\nconst GLOBAL_SIZE: usize = 2048; // Setting this too high causes an overflow\n\n\n\npub struct Vm {\n\n instructions: Vec<u8>,\n\n constants: Vec<Object>,\n\n stack: [Object; STACK_SIZE],\n\n globals: [Object; GLOBAL_SIZE],\n\n stack_pointer: usize,\n\n}\n\n\n\nimpl Vm {\n\n fn new(bytecode: ByteCode) -> Self {\n\n Vm {\n", "file_path": "src/vm.rs", "rank": 59, "score": 30.066068591301498 }, { "content": " let input = \"add(2, 7)\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::FnCall {\n\n function: Box::new(Expression::Ident(\"add\".to_owned())),\n\n args: vec![Expression::Int(2), Expression::Int(7)],\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn test_mock_program() {\n\n let input = \"let x = 7;\n\n let hello = true;\n\n let name = 'spyro';\n\n\n\n if(hello) {\n", "file_path": "src/parser.rs", "rank": 60, "score": 30.0493581627439 }, { "content": " name: \"c\".to_owned(),\n\n value: Expression::Infix {\n\n left: Box::new(Expression::Infix {\n\n left: Box::new(Expression::Prefix {\n\n prefix: Prefix::MINUS,\n\n value: Box::new(Expression::Int(1)),\n\n }),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(2)),\n\n }),\n\n op: Operator::PLUS,\n\n right: Box::new(Expression::Int(3)),\n\n },\n\n },\n\n ];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 61, "score": 29.80562234025618 }, { "content": " fn test_fn_literal() {\n\n let input = \"fn(a, b) {\n\n return 23;\n\n }\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::ExpressionStatement(Expression::FnLiteral {\n\n parameters: vec![\"a\".to_owned(), \"b\".to_owned()],\n\n body: vec![Statement::Return {\n\n value: Expression::Int(23),\n\n }],\n\n })];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn test_function_call() {\n", "file_path": "src/parser.rs", "rank": 62, "score": 28.72597366254066 }, { "content": " alternative\n\n }\n\n _ => Vec::new(),\n\n };\n\n\n\n Expression::If {\n\n condition: Box::new(condition),\n\n consequence,\n\n alternative,\n\n }\n\n }\n\n Some(Token::MINUS) => Expression::Prefix {\n\n prefix: Prefix::MINUS,\n\n value: Box::new(parse_expression(tokens, Precedence::PREFIX)),\n\n },\n\n Some(Token::BANG) => Expression::Prefix {\n\n prefix: Prefix::BANG,\n\n value: Box::new(parse_expression(tokens, Precedence::PREFIX)),\n\n },\n\n Some(Token::FN) => {\n", "file_path": "src/parser.rs", "rank": 63, "score": 27.367588294506437 }, { "content": " }];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn parse_basic_return_statement() {\n\n let input = \"return 5;\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![Statement::Return {\n\n value: Expression::Int(5),\n\n }];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 64, "score": 25.67874667479615 }, { "content": " // OpJmpIfFalse\n\n match self.pop() {\n\n Object::Boolean(true) => {\n\n ip += 3;\n\n }\n\n Object::Boolean(false) => {\n\n let new_ip = two_u8_to_usize(\n\n self.instructions[ip + 1],\n\n self.instructions[ip + 2],\n\n );\n\n ip = new_ip;\n\n }\n\n _ => panic!(\"Invalid OpJmpIfFalse operand\"),\n\n }\n\n }\n\n 0x11 => {\n\n // OpSetGlobal\n\n let global_index =\n\n two_u8_to_usize(self.instructions[ip + 1], self.instructions[ip + 2]);\n\n self.globals[global_index] = self.pop();\n", "file_path": "src/vm.rs", "rank": 65, "score": 25.35582241494736 }, { "content": "use crate::evaluator::Object;\n\nuse std::collections::HashMap;\n\n\n\npub struct Environment {\n\n store: HashMap<String, Object>,\n\n}\n\n\n\nimpl Environment {\n\n pub fn new() -> Self {\n\n Environment {\n\n store: HashMap::new(),\n\n }\n\n }\n\n\n\n pub fn get(&self, key: &str) -> Option<Object> {\n\n let val = self.store.get(key).map(|val| val.clone());\n\n val.clone()\n\n }\n\n\n\n pub fn set(&mut self, key: String, value: Object) {\n\n self.store.insert(key, value);\n\n }\n\n}\n", "file_path": "src/evaluator/environment.rs", "rank": 66, "score": 24.95570279458052 }, { "content": " },\n\n Prefix {\n\n prefix: Prefix,\n\n value: Box<Expression>,\n\n },\n\n If {\n\n condition: Box<Expression>,\n\n consequence: Vec<Statement>,\n\n alternative: Vec<Statement>,\n\n },\n\n FnLiteral {\n\n parameters: Vec<String>,\n\n body: Vec<Statement>,\n\n },\n\n FnCall {\n\n function: Box<Expression>,\n\n args: Vec<Expression>,\n\n },\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 67, "score": 24.80845909372317 }, { "content": "\n\n #[test]\n\n fn test_env() {\n\n let input = \"let a = 3; return a;\";\n\n let expected = Object::Int(3);\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n\n #[test]\n\n fn test_fn_literals() {\n\n let input = \"fn() { return 1; }\";\n\n let expected = Object::Function {\n\n parameters: vec![],\n\n body: vec![Statement::Return {\n\n value: Expression::Int(1),\n\n }],\n\n };\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"fn(a, b) { return true; }\";\n", "file_path": "src/evaluator/evaluator.rs", "rank": 68, "score": 24.638561994230404 }, { "content": " fn parse_multiple_epressions() {\n\n let input = \"1; 2; 3;\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n\n let statements = parse(&mut tokens);\n\n\n\n let expected = vec![\n\n Statement::ExpressionStatement(Expression::Int(1)),\n\n Statement::ExpressionStatement(Expression::Int(2)),\n\n Statement::ExpressionStatement(Expression::Int(3)),\n\n ];\n\n\n\n assert_eq!(expected, statements);\n\n }\n\n\n\n #[test]\n\n fn parse_parenthesised_expression() {\n\n let input = \"2 + (5 + 8)\";\n\n\n\n let mut tokens = lexer(input.as_bytes());\n", "file_path": "src/parser.rs", "rank": 69, "score": 24.410934228795835 }, { "content": " Operator::NEQUAL => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Boolean(l_val != r_val),\n\n (Object::Boolean(l_val), Object::Boolean(r_val)) => Object::Boolean(l_val != r_val),\n\n _ => panic!(\"Problem in Infix not equality check\"),\n\n },\n\n Operator::GREATER => {\n\n match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Boolean(l_val > r_val),\n\n _ => panic!(\"Problem in Infix greater than check\"),\n\n }\n\n }\n\n Operator::LESS => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Boolean(l_val < r_val),\n\n _ => panic!(\"Problem in Infix less than check\"),\n\n },\n\n },\n\n Expression::If {\n\n condition,\n\n consequence,\n\n alternative,\n", "file_path": "src/evaluator/evaluator.rs", "rank": 70, "score": 23.505378013840343 }, { "content": " } => match eval_expression(*condition, env) {\n\n Object::Boolean(true) => eval_block(consequence, env),\n\n Object::Boolean(false) => {\n\n if alternative.len() == 0 {\n\n return Object::Null;\n\n }\n\n eval_block(alternative, env)\n\n }\n\n _ => panic!(\"If conditional must evaluate to a boolean\"),\n\n },\n\n Expression::Ident(name) => env\n\n .get(&name)\n\n .expect(\"Attempted to access invalid variable\"),\n\n Expression::FnLiteral { parameters, body } => Object::Function { parameters, body },\n\n Expression::FnCall { function, args } => {\n\n let (parameters, body) = match *function {\n\n Expression::Ident(name) => match env.get(&name) {\n\n Some(Object::Function { parameters, body }) => (parameters, body),\n\n None => {\n\n // Handle built in functions\n", "file_path": "src/evaluator/evaluator.rs", "rank": 71, "score": 23.11717595646429 }, { "content": " let expected = Object::Function {\n\n parameters: vec![\"a\".to_owned(), \"b\".to_owned()],\n\n body: vec![Statement::Return {\n\n value: Expression::Boolean(true),\n\n }],\n\n };\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n\n #[test]\n\n fn test_fn_calls() {\n\n let input = \"let ret = fn(x) { return x; }; ret(5)\";\n\n let expected = Object::Int(5);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"let ret = fn(x, y) { return x + y; }; ret(5, 9)\";\n\n let expected = Object::Int(14);\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 72, "score": 22.78658211488702 }, { "content": "use crate::{\n\n evaluator::Environment,\n\n parser::{Expression, Operator, Prefix, Statement},\n\n};\n\n\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Object {\n\n Null,\n\n Int(isize),\n\n Boolean(bool),\n\n String(String),\n\n Return(Box<Object>),\n\n Function {\n\n parameters: Vec<String>,\n\n body: Vec<Statement>,\n\n },\n\n}\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 73, "score": 22.537965177078195 }, { "content": " let statements = parse(&mut tokens);\n\n let mut env = Environment::new();\n\n eval(statements, &mut env)\n\n }\n\n\n\n #[test]\n\n fn test_expression_eval() {\n\n let input = \"5\";\n\n let expected = Object::Int(5);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"false\";\n\n let expected = Object::Boolean(false);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"'hello'\";\n\n let expected = Object::String(\"hello\".to_owned());\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 74, "score": 22.019501158995393 }, { "content": " let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(true), vm.stack[0]);\n\n\n\n let input = \"3 != 7\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(true), vm.stack[0]);\n\n }\n\n\n\n #[test]\n\n fn test_prefixes() {\n\n let input = \"-2\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(-2), vm.stack[0]);\n\n\n\n let input = \"!true\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n", "file_path": "src/vm.rs", "rank": 75, "score": 21.262100932921367 }, { "content": " },\n\n Operator::MINUS => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Int(l_val - r_val),\n\n _ => panic!(\"'-' operator only valid on integers\"),\n\n },\n\n Operator::MULTIPLY => match (eval_expression(*left, env), eval_expression(*right, env))\n\n {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Int(l_val * r_val),\n\n _ => panic!(\"'*' operator only valid on integers\"),\n\n },\n\n Operator::DIVIDE => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Int(l_val / r_val),\n\n _ => panic!(\"'/' operator only valid on integers\"),\n\n },\n\n // Comparison operations\n\n Operator::EQUAL => match (eval_expression(*left, env), eval_expression(*right, env)) {\n\n (Object::Int(l_val), Object::Int(r_val)) => Object::Boolean(l_val == r_val),\n\n (Object::Boolean(l_val), Object::Boolean(r_val)) => Object::Boolean(l_val == r_val),\n\n _ => panic!(\"Problem in Infix equality check\"),\n\n },\n", "file_path": "src/evaluator/evaluator.rs", "rank": 76, "score": 21.054827680143337 }, { "content": " instructions: bytecode.instructions,\n\n constants: bytecode.constants,\n\n stack: unsafe { mem::zeroed() },\n\n globals: unsafe { mem::zeroed() },\n\n stack_pointer: 0,\n\n }\n\n }\n\n\n\n fn run(&mut self) {\n\n let mut ip = 0;\n\n\n\n while ip < self.instructions.len() {\n\n match self.instructions[ip] {\n\n 0x01 => {\n\n // OpConstant\n\n let const_index =\n\n two_u8_to_usize(self.instructions[ip + 1], self.instructions[ip + 2]);\n\n\n\n self.push(self.constants[const_index].clone());\n\n ip += 3;\n", "file_path": "src/vm.rs", "rank": 77, "score": 20.852467887694843 }, { "content": " compiler::{ByteCode, Compiler},\n\n evaluator::Object,\n\n vm::Vm,\n\n };\n\n\n\n fn compiled(input: &str) -> ByteCode {\n\n Compiler::from_source(input)\n\n }\n\n\n\n #[test]\n\n fn test_basics() {\n\n let input = \"7\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(7), vm.stack[0]);\n\n\n\n let input = \"1 + 2\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(3), vm.stack[0]);\n", "file_path": "src/vm.rs", "rank": 78, "score": 20.793348835269658 }, { "content": " assert_eq!(Object::Boolean(false), vm.stack[0]);\n\n\n\n let input = \"!!true\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(true), vm.stack[0]);\n\n }\n\n\n\n #[test]\n\n fn test_conditionals() {\n\n let input = \"if(true) { 10 }\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(10), vm.stack[0]);\n\n\n\n let input = \"if(false) { 10 } else { 20 }\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(20), vm.stack[0]);\n\n }\n", "file_path": "src/vm.rs", "rank": 79, "score": 20.56742226941022 }, { "content": " #[test]\n\n fn test_keywords() {\n\n let input = \"let x = true; if hello == false { fn y() }\";\n\n\n\n let tokens = lexer(input.as_bytes());\n\n let expected = VecDeque::from(vec![\n\n Token::LET,\n\n Token::IDENT(\"x\".to_owned()),\n\n Token::ASSIGN,\n\n Token::TRUE,\n\n Token::SEMICOLON,\n\n Token::IF,\n\n Token::IDENT(\"hello\".to_owned()),\n\n Token::EQ,\n\n Token::FALSE,\n\n Token::LBRACE,\n\n Token::FN,\n\n Token::IDENT(\"y\".to_owned()),\n\n Token::LPAREN,\n\n Token::RPAREN,\n", "file_path": "src/lexer.rs", "rank": 80, "score": 20.51323738587405 }, { "content": " Token::RBRACE,\n\n Token::EOF,\n\n ]);\n\n\n\n assert_eq!(expected, tokens);\n\n }\n\n\n\n #[test]\n\n fn test_string() {\n\n let input = \"let name = 'jimmy * 123';\";\n\n\n\n let tokens = lexer(input.as_bytes());\n\n let expected = VecDeque::from(vec![\n\n Token::LET,\n\n Token::IDENT(\"name\".to_owned()),\n\n Token::ASSIGN,\n\n Token::STRING(\"jimmy * 123\".to_owned()),\n\n Token::SEMICOLON,\n\n Token::EOF,\n\n ]);\n\n\n\n assert_eq!(expected, tokens);\n\n }\n\n}\n", "file_path": "src/lexer.rs", "rank": 81, "score": 20.337094618352076 }, { "content": "\n\n #[test]\n\n fn test_let_statements() {\n\n let input = \"let x = 1; x;\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(1), vm.stack[0]);\n\n\n\n let input = \"let x = 2; let y = x; y;\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(2), vm.stack[0]);\n\n\n\n let input = \"let x = 1; let y = 2; x + y;\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(3), vm.stack[0]);\n\n }\n\n}\n", "file_path": "src/vm.rs", "rank": 82, "score": 20.31225314835421 }, { "content": " Object::Boolean(val) => self.push(Object::Boolean(!val)),\n\n _ => panic!(\"Invalid OpBang operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0e => {\n\n // OpMinus\n\n match self.pop() {\n\n Object::Int(val) => self.push(Object::Int(-val)),\n\n _ => panic!(\"Invalid OpMinus operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0f => {\n\n // OpJmp\n\n let new_ip =\n\n two_u8_to_usize(self.instructions[ip + 1], self.instructions[ip + 2]);\n\n ip = new_ip;\n\n }\n\n 0x10 => {\n", "file_path": "src/vm.rs", "rank": 83, "score": 19.71770780371559 }, { "content": "\n\n let input = \"true;\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(true), vm.stack[0]);\n\n }\n\n\n\n #[test]\n\n fn test_comparisons() {\n\n let input = \"1 < 2\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(true), vm.stack[0]);\n\n\n\n let input = \"1 > 2\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(false), vm.stack[0]);\n\n\n\n let input = \"3 == 3\";\n", "file_path": "src/vm.rs", "rank": 84, "score": 19.435349015977767 }, { "content": " let expected = VecDeque::from(vec![\n\n Token::RBRACE,\n\n Token::LET,\n\n Token::IDENT(\"hello\".to_owned()),\n\n Token::RPAREN,\n\n Token::LBRACE,\n\n Token::SEMICOLON,\n\n Token::EOF,\n\n ]);\n\n\n\n assert_eq!(expected, tokens);\n\n }\n\n\n\n #[test]\n\n fn ignore_all_whitespace() {\n\n let input = \"let x = 4;\n\n let y = 30;\n\n let z = { hello };\";\n\n\n\n let tokens = lexer(input.as_bytes());\n", "file_path": "src/lexer.rs", "rank": 85, "score": 17.69343871632514 }, { "content": " }\n\n\n\n #[test]\n\n fn test_if_conditionals() {\n\n let input = \"if(true) { 1 }\";\n\n let expected = Object::Int(1);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"if(false) { 1 } else { 2 }\";\n\n let expected = Object::Int(2);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"if(2 > 1) { true } else { false }\";\n\n let expected = Object::Boolean(true);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"if(2 < 1) { true } else { false }\";\n\n let expected = Object::Boolean(false);\n\n assert_eq!(expected, evaluated(input));\n\n\n", "file_path": "src/evaluator/evaluator.rs", "rank": 86, "score": 17.34191158976837 }, { "content": " Token::LBRACE,\n\n Token::RBRACE,\n\n Token::LPAREN,\n\n Token::RPAREN,\n\n Token::SEMICOLON,\n\n Token::COMMA,\n\n Token::EOF,\n\n ]);\n\n\n\n assert_eq!(expected, tokens);\n\n }\n\n\n\n #[test]\n\n fn lex_digits() {\n\n let input = \"let x = 67; hello num3ber 9\";\n\n\n\n let tokens = lexer(input.as_bytes());\n\n let expected = VecDeque::from(vec![\n\n Token::LET,\n\n Token::IDENT(\"x\".to_owned()),\n", "file_path": "src/lexer.rs", "rank": 87, "score": 17.202219704090982 }, { "content": " #[test]\n\n fn test_builtins() {\n\n let input = \"let str = 'hello'; len(str)\";\n\n let expected = Object::Int(5);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"let str = 'hello'; upperCase(str)\";\n\n let expected = Object::String(\"HELLO\".to_owned());\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"let str = 'hElLO'; lowerCase(str)\";\n\n let expected = Object::String(\"hello\".to_owned());\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n}\n", "file_path": "src/evaluator/evaluator.rs", "rank": 88, "score": 17.070448378658188 }, { "content": "\n\n assert_eq!(expected, tokens);\n\n }\n\n\n\n #[test]\n\n fn test_double_character_tokens() {\n\n let input = \"= == !=;\";\n\n\n\n let tokens = lexer(input.as_bytes());\n\n let expected = VecDeque::from(vec![\n\n Token::ASSIGN,\n\n Token::EQ,\n\n Token::NEQ,\n\n Token::SEMICOLON,\n\n Token::EOF,\n\n ]);\n\n\n\n assert_eq!(expected, tokens);\n\n }\n\n\n", "file_path": "src/lexer.rs", "rank": 89, "score": 16.834350726819476 }, { "content": " #[test]\n\n fn test_prefixes() {\n\n let input = \"!true\";\n\n let expected = Object::Boolean(false);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"!!false\";\n\n let expected = Object::Boolean(false);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"-27\";\n\n let expected = Object::Int(-27);\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n\n #[test]\n\n fn test_infixes() {\n\n let input = \"2 + 3\";\n\n let expected = Object::Int(5);\n\n assert_eq!(expected, evaluated(input));\n", "file_path": "src/evaluator/evaluator.rs", "rank": 90, "score": 16.629056836778183 }, { "content": " ip += 3;\n\n }\n\n 0x12 => {\n\n // OpGetGlobal\n\n let global_index =\n\n two_u8_to_usize(self.instructions[ip + 1], self.instructions[ip + 2]);\n\n self.push(self.globals[global_index].clone());\n\n ip += 3;\n\n }\n\n invalid => panic!(\"Invalid instruction: {}\", invalid),\n\n }\n\n }\n\n }\n\n\n\n fn push(&mut self, obj: Object) {\n\n if self.stack_pointer >= STACK_SIZE {\n\n panic!(\"Stack overflow\");\n\n }\n\n\n\n self.stack[self.stack_pointer] = obj;\n", "file_path": "src/vm.rs", "rank": 91, "score": 16.51331762080344 }, { "content": " }\n\n\n\n match tokens.pop_front().unwrap() {\n\n Token::RPAREN => break,\n\n Token::COMMA => continue,\n\n _ => panic!(\"Unexpected error when parsing function call.\"),\n\n }\n\n }\n\n\n\n Expression::FnCall {\n\n function: Box::new(Expression::Ident(name)),\n\n args,\n\n }\n\n } else {\n\n Expression::Ident(name)\n\n }\n\n }\n\n Some(Token::LPAREN) => {\n\n let exp = parse_expression(tokens, Precedence::LOWEST);\n\n match tokens.pop_front() {\n", "file_path": "src/parser.rs", "rank": 92, "score": 15.692316506720921 }, { "content": " (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Boolean(left == right));\n\n }\n\n _ => panic!(\"Invalid OpEqual operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0c => {\n\n // OpNotEqual\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Boolean(left != right));\n\n }\n\n _ => panic!(\"Invalid OpNotEqual operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0d => {\n\n // OpBang\n\n match self.pop() {\n", "file_path": "src/vm.rs", "rank": 93, "score": 15.632026876992033 }, { "content": " (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Boolean(left > right));\n\n }\n\n _ => panic!(\"Invalid OpGreater operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0a => {\n\n // OpLess\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Boolean(left < right));\n\n }\n\n _ => panic!(\"Invalid OpLess operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x0b => {\n\n // OpEqual\n\n match (self.pop(), self.pop()) {\n", "file_path": "src/vm.rs", "rank": 94, "score": 15.552675037717336 }, { "content": " }\n\n 0x02 => {\n\n // OpAdd\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Int(left + right));\n\n }\n\n _ => panic!(\"Invalid OpAdd operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x03 => {\n\n // OpSub\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Int(left - right));\n\n }\n\n _ => panic!(\"Invalid OpSub operand\"),\n\n };\n\n ip += 1;\n", "file_path": "src/vm.rs", "rank": 95, "score": 15.552675037717336 }, { "content": " let input = \"if(2 - 3 + 29 == 4 * 7) { 1 } else { 2 }\";\n\n let expected = Object::Int(1);\n\n assert_eq!(expected, evaluated(input));\n\n }\n\n\n\n #[test]\n\n fn test_return() {\n\n let input = \"return 2; 7\";\n\n let expected = Object::Int(2);\n\n assert_eq!(expected, evaluated(input));\n\n\n\n let input = \"if(true) {\n\n if(true) {\n\n return 2;\n\n }\n\n return 1;\n\n }\";\n\n let expected = Object::Int(2);\n\n assert_eq!(expected, evaluated(input));\n\n }\n", "file_path": "src/evaluator/evaluator.rs", "rank": 96, "score": 15.503111773411185 }, { "content": " self.stack_pointer += 1;\n\n }\n\n\n\n fn pop(&mut self) -> Object {\n\n self.stack_pointer -= 1;\n\n self.stack[self.stack_pointer].clone()\n\n }\n\n\n\n // Utility function to observe stack\n\n fn print_stack(&self, num: usize) {\n\n println!(\"Vm Stack\");\n\n for i in 0..num {\n\n println!(\"{}: {:?}\", i, self.stack[i]);\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::{\n", "file_path": "src/vm.rs", "rank": 97, "score": 15.33953287071091 }, { "content": " }\n\n 0x04 => {\n\n // OpMul\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n self.push(Object::Int(left * right));\n\n }\n\n _ => panic!(\"Invalid OpMul operand\"),\n\n };\n\n ip += 1;\n\n }\n\n 0x05 => {\n\n // OpDiv\n\n match (self.pop(), self.pop()) {\n\n (Object::Int(right), Object::Int(left)) => {\n\n // TODO Handle remainders, currently they are truncated\n\n self.push(Object::Int(left / right));\n\n }\n\n _ => panic!(\"Invalid OpDiv operand\"),\n\n };\n", "file_path": "src/vm.rs", "rank": 98, "score": 15.24362601855521 }, { "content": "\n\n let input = \"2 * 3\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(6), vm.stack[0]);\n\n\n\n let input = \"2 * 2 + 6 / 2 - 9\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(-2), vm.stack[0]);\n\n\n\n let input = \"1; 2; 3;\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Int(3), vm.stack[0]);\n\n\n\n let input = \"false\";\n\n let mut vm = Vm::new(compiled(input));\n\n vm.run();\n\n assert_eq!(Object::Boolean(false), vm.stack[0]);\n", "file_path": "src/vm.rs", "rank": 99, "score": 14.942436998102702 } ]
Rust
macros/component-definition-derive/src/lib.rs
Max-Meldrum/kompact
8b77733d8b4da2c74e7d97058ea5ce774d488547
#![recursion_limit = "128"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{parse_macro_input, DeriveInput}; use std::iter::Iterator; #[proc_macro_derive(ComponentDefinition)] pub fn component_definition(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let gen = impl_component_definition(&ast); gen.into() } fn impl_component_definition(ast: &syn::DeriveInput) -> TokenStream2 { let name = &ast.ident; let name_str = format!("{}", name); if let syn::Data::Struct(ref vdata) = ast.data { let generics = &ast.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let fields = &vdata.fields; let mut ports: Vec<(&syn::Field, PortField)> = Vec::new(); let mut ctx_field: Option<&syn::Field> = None; for field in fields.iter() { let cf = identify_field(field); match cf { ComponentField::Ctx => { ctx_field = Some(field); } ComponentField::Port(pf) => ports.push((field, pf)), ComponentField::Other => (), } } let (ctx_setup, ctx_access) = match ctx_field { Some(f) => { let id = &f.ident; let setup = quote! { self.#id.initialise(self_component.clone()); }; let access = quote! { self.#id }; (setup, access) } None => panic!("No ComponentContext found for {:?}!", name), }; let port_setup = ports .iter() .map(|&(f, _)| { let id = &f.ident; quote! { self.#id.set_parent(self_component.clone()); } }) .collect::<Vec<_>>(); let port_handles_skip = ports .iter() .enumerate() .map(|(i, &(f, ref t))| { let id = &f.ident; let handle = t.as_handle(); quote! { if skip <= #i { if count >= max_events { return ExecuteResult::new(false, count, #i); } #[allow(unreachable_code)] { if let Some(event) = self.#id.dequeue() { let res = #handle count += 1; done_work = true; if let Handled::BlockOn(blocking_future) = res { self.ctx_mut().set_blocking(blocking_future); return ExecuteResult::new(true, count, #i); } } } } } }) .collect::<Vec<_>>(); let port_handles = ports .iter() .enumerate() .map(|(i, &(f, ref t))| { let id = &f.ident; let handle = t.as_handle(); quote! { if count >= max_events { return ExecuteResult::new(false, count, #i); } #[allow(unreachable_code)] { if let Some(event) = self.#id.dequeue() { let res = #handle count += 1; done_work = true; if let Handled::BlockOn(blocking_future) = res { self.ctx_mut().set_blocking(blocking_future); return ExecuteResult::new(true, count, #i); } } } } }) .collect::<Vec<_>>(); let exec = if port_handles.is_empty() { quote! { fn execute(&mut self, _max_events: usize, _skip: usize) -> ExecuteResult { ExecuteResult::new(false, 0, 0) } } } else { quote! { fn execute(&mut self, max_events: usize, skip: usize) -> ExecuteResult { let mut count: usize = 0; let mut done_work = true; #(#port_handles_skip)* while done_work { done_work = false; #(#port_handles)* } ExecuteResult::new(false, count, 0) } } }; let port_ref_impls = ports .iter() .map(|p| { let (field, port_field) = p; let id = &field.ident; match port_field { PortField::Required(ty) => quote! { impl #impl_generics RequireRef< #ty > for #name #ty_generics #where_clause { fn required_ref(&mut self) -> RequiredRef< #ty > { self.#id.share() } fn connect_to_provided(&mut self, prov: ProvidedRef< #ty >) -> () { self.#id.connect(prov) } } }, PortField::Provided(ty) => quote! { impl #impl_generics ProvideRef< #ty > for #name #ty_generics #where_clause { fn provided_ref(&mut self) -> ProvidedRef< #ty > { self.#id.share() } fn connect_to_required(&mut self, req: RequiredRef< #ty >) -> () { self.#id.connect(req) } } }, } }) .collect::<Vec<_>>(); fn make_match(f: &syn::Field, t: &syn::Type) -> TokenStream2 { let f = &f.ident; quote! { id if id == ::std::any::TypeId::of::<#t>() => Some(&mut self.#f as &mut dyn ::std::any::Any), } } let provided_matches: Vec<_> = ports .iter() .filter_map(|(f, p)| match p { PortField::Provided(t) => Some((*f, t)), _ => None, }) .map(|(f, t)| make_match(f, t)) .collect(); let required_matches: Vec<_> = ports .iter() .filter_map(|(f, p)| match p { PortField::Required(t) => Some((*f, t)), _ => None, }) .map(|(f, t)| make_match(f, t)) .collect(); quote! { impl #impl_generics ComponentDefinition for #name #ty_generics #where_clause { fn setup(&mut self, self_component: ::std::sync::Arc<Component<Self>>) -> () { #ctx_setup #(#port_setup)* } #exec fn ctx_mut(&mut self) -> &mut ComponentContext<Self> { &mut #ctx_access } fn ctx(&self) -> &ComponentContext<Self> { &#ctx_access } fn type_name() -> &'static str { #name_str } } impl #impl_generics DynamicPortAccess for #name #ty_generics #where_clause { fn get_provided_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> { match port_id { #(#provided_matches)* _ => None, } } fn get_required_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> { match port_id { #(#required_matches)* _ => None, } } } #(#port_ref_impls)* } } else { panic!("#[derive(ComponentDefinition)] is only defined for structs, not for enums!"); } } #[allow(clippy::large_enum_variant)] #[derive(Debug)] enum ComponentField { Ctx, Port(PortField), Other, } #[derive(Debug)] enum PortField { Required(syn::Type), Provided(syn::Type), } impl PortField { fn as_handle(&self) -> TokenStream2 { match *self { PortField::Provided(ref ty) => quote! { Provide::<#ty>::handle(self, event); }, PortField::Required(ref ty) => quote! { Require::<#ty>::handle(self, event); }, } } } const REQP: &str = "RequiredPort"; const PROVP: &str = "ProvidedPort"; const CTX: &str = "ComponentContext"; const KOMPICS: &str = "kompact"; fn identify_field(f: &syn::Field) -> ComponentField { if let syn::Type::Path(ref patht) = f.ty { let path = &patht.path; let port_seg_opt = if path.segments.len() == 1 { Some(&path.segments[0]) } else if path.segments.len() == 2 { if path.segments[0].ident == KOMPICS { Some(&path.segments[1]) } else { None } } else { None }; if let Some(seg) = port_seg_opt { if seg.ident == REQP { ComponentField::Port(PortField::Required(extract_port_type(seg))) } else if seg.ident == PROVP { ComponentField::Port(PortField::Provided(extract_port_type(seg))) } else if seg.ident == CTX { ComponentField::Ctx } else { ComponentField::Other } } else { ComponentField::Other } } else { ComponentField::Other } } fn extract_port_type(seg: &syn::PathSegment) -> syn::Type { match seg.arguments { syn::PathArguments::AngleBracketed(ref abppd) => { match abppd.args.first().expect("Invalid type argument!") { syn::GenericArgument::Type(ty) => ty.clone(), _ => panic!("Wrong generic argument type in {:?}", seg), } } _ => panic!("Wrong path parameter type! {:?}", seg), } }
#![recursion_limit = "128"] extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::quote; use syn::{parse_macro_input, DeriveInput}; use std::iter::Iterator; #[proc_macro_derive(ComponentDefinition)] pub fn component_definition(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as DeriveInput); let gen = impl_component_definition(&ast); gen.into() } fn impl_component_definition(ast: &syn::DeriveInput) -> TokenStream2 { let name = &ast.ident; let name_str = format!("{}", name); if let syn::Data::Struct(ref vdata) = ast.data { let generics = &ast.generics; let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let fields = &vdata.fields; let mut ports: Vec<(&syn::Field, PortField)> = Vec::new(); let mut ctx_field: Option<&syn::Field> = None; for field in fields.iter() { let cf = identify_field(field); match cf { ComponentField::Ctx => { ctx_field = Some(field); } ComponentField::Port(pf) => ports.push((field, pf)), ComponentField::Other => (), } } let (ctx_setup, ctx_access) = match ctx_field { Some(f) => { let id = &f.ident; let setup = quote! { self.#id.initialise(self_component.clone()); }; let access = quote! { self.#id }; (setup, access) } None => panic!("No ComponentContext found for {:?}!", name), }; let port_setup = ports .iter() .map(|&(f, _)| { let id = &f.ident; quote! { self.#id.set_parent(self_component.clone()); } }) .collect::<Vec<_>>(); let port_handles_skip = ports .iter() .enumerate() .map(|(i, &(f, ref t))| { let id = &f.ident; let handle = t.as_handle(); quote! { if skip <= #i { if count >= max_events { return ExecuteResult::new(false, count, #i); } #[allow(unreachable_code)] { if let Some(event) = self.#id.dequeue() { let res = #handle count += 1; done_work = true; if let Handled::BlockOn(blocking_future) = res { self.ctx_mut().set_blocking(blocking_future); return ExecuteResult::new(true, count, #i); } } } } } }) .collect::<Vec<_>>(); let port_handles = ports .iter() .enumerate() .map(|(i, &(f, ref t))| { let id = &f.ident; let handle = t.as_handle(); quote! { if count >= max_events { return ExecuteResult::new(false, count, #i); } #[allow(unreachable_code)] { if let Some(event) = self.#id.dequeue() { let res = #handle count += 1; done_work = true; if let Handled::BlockOn(blocking_future) = res { self.ctx_mut().set_blocking(blocking_future); return ExecuteResult::new(true, count, #i); } } } } }) .collect::<Vec<_>>(); let exec = if port_handles.is_empty() { quote! { fn execute(&mut self, _max_events: usize, _skip: usize) -> ExecuteResult { ExecuteResult::new(false, 0, 0) } } } else { quote! { fn execute(&mut self, max_events: usize, skip: usize) -> ExecuteResult { let mut count: usize = 0; let mut done_work = true; #(#port_handles_skip)* while done_work { done_work = false; #(#port_handles)* } ExecuteResult::new(false, count, 0) } } }; let port_ref_impls = ports .iter() .map(|p| { let (field, port_field) = p; let id = &field.ident; match port_field { PortField::Required(ty) => quote! { impl #impl_generics RequireRef< #ty > for #name #ty_generics #where_clause { fn required_ref(&mut self) -> RequiredRef< #ty > { self.#id.share() } fn connect_to_provided(&mut self, prov: ProvidedRef< #ty >) -> () { self.#id.connect(prov) } } }, PortField::Provided(t
#[allow(clippy::large_enum_variant)] #[derive(Debug)] enum ComponentField { Ctx, Port(PortField), Other, } #[derive(Debug)] enum PortField { Required(syn::Type), Provided(syn::Type), } impl PortField { fn as_handle(&self) -> TokenStream2 { match *self { PortField::Provided(ref ty) => quote! { Provide::<#ty>::handle(self, event); }, PortField::Required(ref ty) => quote! { Require::<#ty>::handle(self, event); }, } } } const REQP: &str = "RequiredPort"; const PROVP: &str = "ProvidedPort"; const CTX: &str = "ComponentContext"; const KOMPICS: &str = "kompact"; fn identify_field(f: &syn::Field) -> ComponentField { if let syn::Type::Path(ref patht) = f.ty { let path = &patht.path; let port_seg_opt = if path.segments.len() == 1 { Some(&path.segments[0]) } else if path.segments.len() == 2 { if path.segments[0].ident == KOMPICS { Some(&path.segments[1]) } else { None } } else { None }; if let Some(seg) = port_seg_opt { if seg.ident == REQP { ComponentField::Port(PortField::Required(extract_port_type(seg))) } else if seg.ident == PROVP { ComponentField::Port(PortField::Provided(extract_port_type(seg))) } else if seg.ident == CTX { ComponentField::Ctx } else { ComponentField::Other } } else { ComponentField::Other } } else { ComponentField::Other } } fn extract_port_type(seg: &syn::PathSegment) -> syn::Type { match seg.arguments { syn::PathArguments::AngleBracketed(ref abppd) => { match abppd.args.first().expect("Invalid type argument!") { syn::GenericArgument::Type(ty) => ty.clone(), _ => panic!("Wrong generic argument type in {:?}", seg), } } _ => panic!("Wrong path parameter type! {:?}", seg), } }
y) => quote! { impl #impl_generics ProvideRef< #ty > for #name #ty_generics #where_clause { fn provided_ref(&mut self) -> ProvidedRef< #ty > { self.#id.share() } fn connect_to_required(&mut self, req: RequiredRef< #ty >) -> () { self.#id.connect(req) } } }, } }) .collect::<Vec<_>>(); fn make_match(f: &syn::Field, t: &syn::Type) -> TokenStream2 { let f = &f.ident; quote! { id if id == ::std::any::TypeId::of::<#t>() => Some(&mut self.#f as &mut dyn ::std::any::Any), } } let provided_matches: Vec<_> = ports .iter() .filter_map(|(f, p)| match p { PortField::Provided(t) => Some((*f, t)), _ => None, }) .map(|(f, t)| make_match(f, t)) .collect(); let required_matches: Vec<_> = ports .iter() .filter_map(|(f, p)| match p { PortField::Required(t) => Some((*f, t)), _ => None, }) .map(|(f, t)| make_match(f, t)) .collect(); quote! { impl #impl_generics ComponentDefinition for #name #ty_generics #where_clause { fn setup(&mut self, self_component: ::std::sync::Arc<Component<Self>>) -> () { #ctx_setup #(#port_setup)* } #exec fn ctx_mut(&mut self) -> &mut ComponentContext<Self> { &mut #ctx_access } fn ctx(&self) -> &ComponentContext<Self> { &#ctx_access } fn type_name() -> &'static str { #name_str } } impl #impl_generics DynamicPortAccess for #name #ty_generics #where_clause { fn get_provided_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> { match port_id { #(#provided_matches)* _ => None, } } fn get_required_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> { match port_id { #(#required_matches)* _ => None, } } } #(#port_ref_impls)* } } else { panic!("#[derive(ComponentDefinition)] is only defined for structs, not for enums!"); } }
function_block-function_prefixed
[ { "content": "/// Connect two port instances.\n\n///\n\n/// The providing port instance must be given as first argument, and the requiring instance second.\n\npub fn biconnect_ports<P: Port>(prov: &mut ProvidedPort<P>, req: &mut RequiredPort<P>) -> () {\n\n let prov_share = prov.share();\n\n let req_share = req.share();\n\n prov.connect(req_share);\n\n req.connect(prov_share);\n\n}\n\n\n", "file_path": "core/src/utils.rs", "rank": 0, "score": 343682.8816710911 }, { "content": "/// A convenience abstraction over concrete port instance fields\n\n///\n\n/// This trait is usually automatically derived when using `#[derive(ComponentDefinition)]`.\n\npub trait RequireRef<P: Port + 'static> {\n\n /// Returns a required reference to this component's port instance of type `P`\n\n fn required_ref(&mut self) -> RequiredRef<P>;\n\n /// Connects this component's required port instance of type `P` to `prov`\n\n fn connect_to_provided(&mut self, prov: ProvidedRef<P>) -> ();\n\n}\n\n\n", "file_path": "core/src/component/mod.rs", "rank": 1, "score": 235603.85191666716 }, { "content": "/// Blocks the current waiting for `f` to be completed or for the `timeout` to expire\n\n///\n\n/// If the timeout expires first, then `f` is returned so it can be retried if desired.\n\npub fn block_until<F>(timeout: Duration, mut f: F) -> Result<<F as Future>::Output, F>\n\nwhere\n\n F: Future + Unpin,\n\n{\n\n block_on(async {\n\n async_std::future::timeout(timeout, &mut f)\n\n .await\n\n .map_err(|_| ())\n\n })\n\n .map_err(|_| f)\n\n}\n\n\n", "file_path": "core/src/utils.rs", "rank": 2, "score": 222809.50726124528 }, { "content": "/// A convenience abstraction over concrete port instance fields\n\n///\n\n/// This trait is usually automatically derived when using `#[derive(ComponentDefinition)]`.\n\npub trait ProvideRef<P: Port + 'static> {\n\n /// Returns a provided reference to this component's port instance of type `P`\n\n fn provided_ref(&mut self) -> ProvidedRef<P>;\n\n /// Connects this component's provided port instance of type `P` to `req`\n\n fn connect_to_required(&mut self, req: RequiredRef<P>) -> ();\n\n}\n\n\n", "file_path": "core/src/component/mod.rs", "rank": 3, "score": 210994.5328961803 }, { "content": "/// Same as [ProvideRef](ProvideRef), but for instances that must be locked first\n\n///\n\n/// This is used, for example, with an `Arc<Component<_>>`.\n\npub trait LockingProvideRef<P: Port + 'static> {\n\n /// Returns a required reference to this component's port instance of type `P`\n\n fn provided_ref(&self) -> ProvidedRef<P>;\n\n /// Connects this component's required port instance of type `P` to `prov`\n\n fn connect_to_required(&self, req: RequiredRef<P>) -> ();\n\n}\n\n\n", "file_path": "core/src/component/mod.rs", "rank": 4, "score": 206645.84924061788 }, { "content": "/// Same as [RequireRef](RequireRef), but for instances that must be locked first\n\n///\n\n/// This is used, for example, with an `Arc<Component<_>>`.\n\npub trait LockingRequireRef<P: Port + 'static> {\n\n /// Returns a required reference to this component's port instance of type `P`\n\n fn required_ref(&self) -> RequiredRef<P>;\n\n /// Connects this component's required port instance of type `P` to `prov`\n\n fn connect_to_provided(&self, prov: ProvidedRef<P>) -> ();\n\n}\n\n\n\nimpl<P, CD> LockingProvideRef<P> for Arc<Component<CD>>\n\nwhere\n\n P: Port + 'static,\n\n CD: ComponentTraits + ComponentLifecycle + Provide<P> + ProvideRef<P>,\n\n{\n\n fn provided_ref(&self) -> ProvidedRef<P> {\n\n self.on_definition(|cd| ProvideRef::provided_ref(cd))\n\n }\n\n\n\n fn connect_to_required(&self, req: RequiredRef<P>) -> () {\n\n self.on_definition(|cd| ProvideRef::connect_to_required(cd, req))\n\n }\n\n}\n", "file_path": "core/src/component/mod.rs", "rank": 5, "score": 206645.84924061788 }, { "content": "pub fn insert_benches_usize(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Inserts usize\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_insert_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_insert_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_insert_fx(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"XX\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_insert_xx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"BTree\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_usize_insert_btree(b, size),\n\n );\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 6, "score": 202649.74415553123 }, { "content": "pub fn lookup_benches_usize(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Lookups usize\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_lookup_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_lookup_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_lookup_fx(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"XX\", data_size), data_size, |b, &size| {\n\n tests::bench_usize_lookup_xx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"BTree\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_usize_lookup_btree(b, size),\n\n );\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 7, "score": 202649.74415553123 }, { "content": "fn impl_actor(ast: &syn::DeriveInput) -> TokenStream2 {\n\n let name = &ast.ident;\n\n if let syn::Data::Struct(_) = ast.data {\n\n let generics = &ast.generics;\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n\n\n quote! {\n\n impl #impl_generics ActorRaw for #name #ty_generics #where_clause {\n\n\n\n type Message = Never;\n\n\n\n fn receive(&mut self, env: MsgEnvelope<Self::Message>) -> Handled {\n\n warn!(self.log(), \"Got msg, but component isn't handling any: {:?}\", env);\n\n Handled::Ok\n\n }\n\n }\n\n }\n\n } else {\n\n //Nope. This is an Enum. We cannot handle these!\n\n panic!(\"#[derive(Actor)] is only defined for structs, not for enums!\");\n\n }\n\n}\n", "file_path": "macros/actor-derive/src/lib.rs", "rank": 8, "score": 191978.15002431202 }, { "content": "pub fn do_with_message<F>(f: F, m: Message) -> u64\n\nwhere\n\n F: Fn(&dyn Any) -> u64 + 'static,\n\n{\n\n match m {\n\n Message::StaticRef(r) => f(r),\n\n Message::Owned(b) => f(b.as_ref()),\n\n Message::Shared(s) => f(s.as_ref()),\n\n }\n\n}\n\n\n\npub struct IntBox(u64);\n\n\n", "file_path": "experiments/dynamic-benches/src/do_with.rs", "rank": 9, "score": 188134.21236097725 }, { "content": "/// Extracts a [NetMessage](NetMessage) from the provided buffer\n\n///\n\n/// This expects the format from [serialise_msg](serialise_msg).\n\npub fn deserialise_chunk_ref(mut buffer: ChunkRef) -> Result<NetMessage, SerError> {\n\n // if buffer.remaining() < 1 {\n\n // return Err(SerError::InvalidData(\"Not enough bytes available\".into()));\n\n // }\n\n // gonna fail below anyway\n\n\n\n let src = ActorPath::deserialise(&mut buffer)?;\n\n let dst = ActorPath::deserialise(&mut buffer)?;\n\n let ser_id = buffer.get_ser_id();\n\n\n\n let envelope = NetMessage::with_chunk_ref(ser_id, src, dst, buffer);\n\n\n\n Ok(envelope)\n\n}\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 11, "score": 179929.19044998375 }, { "content": "/// A trait implementing handling of provided events of `P`\n\n///\n\n/// This is equivalent to a Kompics *Handler* subscribed on a provided port of type `P`.\n\npub trait Provide<P: Port + 'static> {\n\n /// Handle the port's `event`\n\n ///\n\n /// # Note\n\n ///\n\n /// Remember that components usually run on a shared thread pool,\n\n /// so you shouldn't ever block in this method unless you know what you are doing.\n\n fn handle(&mut self, event: P::Request) -> Handled;\n\n}\n\n\n", "file_path": "core/src/component/mod.rs", "rank": 12, "score": 179169.2523358912 }, { "content": "/// A trait implementing handling of required events of `P`\n\n///\n\n/// This is equivalent to a Kompics *Handler* subscribed on a required port of type `P`.\n\npub trait Require<P: Port + 'static> {\n\n /// Handle the port's `event`\n\n ///\n\n /// # Note\n\n ///\n\n /// Remember that components usually run on a shared thread pool,\n\n /// so you shouldn't ever block in this method unless you know what you are doing.\n\n fn handle(&mut self, event: P::Indication) -> Handled;\n\n}\n\n\n", "file_path": "core/src/component/mod.rs", "rank": 13, "score": 179169.2523358912 }, { "content": "pub fn do_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Do_With Benches\");\n\n g.bench_function(\"bench Box<dyn Any>\", |b| tests::bench_any_box(b));\n\n g.bench_function(\"bench &Box<dyn Any>\", |b| tests::bench_any_box_ref(b));\n\n g.bench_function(\"bench Box<dyn Any>.as_ref()\", |b| {\n\n tests::bench_any_ref_from_box(b)\n\n });\n\n g.bench_function(\"bench &dyn Any\", |b| tests::bench_any_ref(b));\n\n g.bench_function(\"bench Message &'static Any\", |b| {\n\n tests::bench_msg_with_any_ref(b)\n\n });\n\n g.bench_function(\"bench Message Box<dyn Any>\", |b| {\n\n tests::bench_msg_with_any_box(b)\n\n });\n\n g.bench_function(\"bench Message Arc<dyn Any>\", |b| {\n\n tests::bench_msg_with_shared_any(b)\n\n });\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/do_with.rs", "rank": 14, "score": 178670.41793623593 }, { "content": "pub fn ping_pong_latency_static_threads(b: &mut Bencher, threads: &usize) {\n\n use ppstatic::*;\n\n ping_pong_latency(b, *threads, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 15, "score": 176655.40888339572 }, { "content": "/// Connect two components on their instances of port type `P`.\n\n///\n\n/// The component providing the port must be given as first argument, and the requiring component second.\n\n///\n\n/// This function can fail with a [`TryDualLockError`](enum.TryDualLockError.html), if one of the mutexes can not be acquired immediately.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use kompact::prelude::*;\n\n/// # use kompact::doctest_helpers::*;\n\n///\n\n///\n\n/// let system = KompactConfig::default().build().expect(\"system\");\n\n/// let c1 = system.create(TestComponent1::new);\n\n/// let c2 = system.create(TestComponent2::new);\n\n/// biconnect_components::<TestPort,_,_>(&c1, &c2).expect(\"connection\");\n\n/// ```\n\npub fn biconnect_components<P, C1, C2>(\n\n provider: &Arc<Component<C1>>,\n\n requirer: &Arc<Component<C2>>,\n\n) -> Result<(), TryDualLockError>\n\nwhere\n\n P: Port + 'static,\n\n C1: ComponentDefinition + Sized + 'static + Provide<P> + ProvideRef<P>,\n\n C2: ComponentDefinition + Sized + 'static + Require<P> + RequireRef<P>,\n\n{\n\n on_dual_definition(provider, requirer, |prov, req| {\n\n let prov_share: ProvidedRef<P> = prov.provided_ref();\n\n let req_share: RequiredRef<P> = req.required_ref();\n\n ProvideRef::connect_to_required(prov, req_share);\n\n RequireRef::connect_to_provided(req, prov_share);\n\n })\n\n}\n\n\n", "file_path": "core/src/utils.rs", "rank": 16, "score": 175776.8902840984 }, { "content": "pub fn tell_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Tell/Trigger Benches\");\n\n g.bench_function(\"bench tell ActorRef\", |b| tests::bench_tell_actor_ref(b));\n\n g.bench_function(\"bench tell Recipient\", |b| tests::bench_tell_recipient(b));\n\n g.bench_function(\"bench tell ActorRef (Strong)\", |b| {\n\n tests::bench_tell_actor_ref_strong(b)\n\n });\n\n g.bench_function(\"bench trigger Port\", |b| tests::bench_trigger_port(b));\n\n //g.bench_function(\"bench tell ActorPath\", |b| tests::bench_tell_actor_path(b));\n\n g.finish();\n\n}\n\n\n\nmod tests {\n\n use super::*;\n\n use criterion::Bencher;\n\n use std::time::Duration;\n\n\n\n pub fn bench_clone_recipient(b: &mut Bencher) {\n\n let sys = KompactConfig::default().build().expect(\"System\");\n\n let tester = sys.create(TestActor::new);\n", "file_path": "experiments/dynamic-benches/src/actorrefs.rs", "rank": 17, "score": 171509.3091642452 }, { "content": "pub fn lookup_benches(c: &mut Criterion) {\n\n lookup_benches_uuid(c);\n\n lookup_benches_socket(c);\n\n lookup_benches_usize(c);\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 18, "score": 171509.3091642452 }, { "content": "pub fn clone_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Clone Benches\");\n\n g.bench_function(\"bench clone ActorRef\", |b| tests::bench_clone_actor_ref(b));\n\n g.bench_function(\"bench clone Recipient\", |b| tests::bench_clone_recipient(b));\n\n g.bench_function(\"bench clone ActorPath\", |b| {\n\n tests::bench_clone_actor_path(b)\n\n });\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/actorrefs.rs", "rank": 19, "score": 171509.3091642452 }, { "content": "pub fn insert_benches(c: &mut Criterion) {\n\n insert_benches_uuid(c);\n\n insert_benches_socket(c);\n\n insert_benches_usize(c);\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 20, "score": 171509.3091642452 }, { "content": "pub fn insert_benches_uuid(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Inserts UUID\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_insert_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_insert_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_insert_fx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"FX-IM-INSERT\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_uuid_insert_fx_im_insert(b, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"FX-IM-UPDATE\", data_size),\n\n data_size,\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 21, "score": 168258.913650189 }, { "content": "pub fn latch_overhead(c: &mut Criterion) {\n\n c.bench_function(\"Synchronoise Latch\", latch_synchronoise);\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 22, "score": 168258.913650189 }, { "content": "pub fn lookup_benches_socket(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Lookups Socket\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_lookup_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_lookup_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_lookup_fx(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"XX\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_lookup_xx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"Radix\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_socket_lookup_radix(b, size),\n\n );\n\n #[cfg(nightly)]\n\n g.bench_with_input(\n\n BenchmarkId::new(\"ByteRadix\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_socket_lookup_byteradix(b, size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 23, "score": 168258.913650189 }, { "content": "pub fn ping_latency_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Ping Latency Benches\");\n\n for pairs in [1usize].iter() {\n\n g.throughput(Throughput::Elements(\n\n 2u64 * LATENCY_MSG_COUNT * (*pairs as u64),\n\n ));\n\n g.bench_with_input(\n\n BenchmarkId::new(\"ports\", pairs),\n\n pairs,\n\n tests::ping_pong_latency_ports,\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"strong-refs\", pairs),\n\n pairs,\n\n tests::ping_pong_latency_strong_ref,\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"weak-refs\", pairs),\n\n pairs,\n\n tests::ping_pong_latency_weak_ref,\n", "file_path": "experiments/dynamic-benches/src/pingperf.rs", "rank": 24, "score": 168258.913650189 }, { "content": "pub fn insert_benches_socket(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Inserts Socket\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_insert_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_insert_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_insert_fx(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"XX\", data_size), data_size, |b, &size| {\n\n tests::bench_socket_insert_xx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"Radix\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_socket_insert_radix(b, size),\n\n );\n\n #[cfg(nightly)]\n\n g.bench_with_input(\n\n BenchmarkId::new(\"Byte Radix\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_socket_insert_byteradix(b, size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 25, "score": 168258.913650189 }, { "content": "pub fn ping_throughput_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Ping Benches\");\n\n for pairs in [1usize, 2usize, 4usize, 8usize, 16usize].iter() {\n\n g.throughput(Throughput::Elements(2u64 * MSG_COUNT * (*pairs as u64)));\n\n g.bench_with_input(\n\n BenchmarkId::new(\"ports\", pairs),\n\n pairs,\n\n tests::ping_pong_throughput_ports,\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"strong-refs\", pairs),\n\n pairs,\n\n tests::ping_pong_throughput_strong_ref,\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"weak-refs\", pairs),\n\n pairs,\n\n tests::ping_pong_throughput_weak_ref,\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"ask\", pairs),\n\n pairs,\n\n tests::ping_pong_throughput_ask,\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/pingperf.rs", "rank": 26, "score": 168258.913650189 }, { "content": "pub fn latch_synchronoise(b: &mut Bencher) {\n\n use std::sync::Arc;\n\n use synchronoise::CountdownEvent;\n\n\n\n b.iter_custom(|num_iterations| {\n\n let mut outer_latches: Vec<Arc<CountdownEvent>> = vec![(); num_iterations as usize]\n\n .drain(..)\n\n .map(|_| Arc::new(CountdownEvent::new(1)))\n\n .collect();\n\n let mut inner_latches: Vec<Arc<CountdownEvent>> = vec![(); num_iterations as usize]\n\n .drain(..)\n\n .map(|_| Arc::new(CountdownEvent::new(1)))\n\n .collect();\n\n let mut outer_latches_thread = outer_latches.clone();\n\n let mut inner_latches_thread = inner_latches.clone();\n\n std::thread::spawn(move || {\n\n loop {\n\n if let Some(wait_latch) = outer_latches_thread.pop() {\n\n wait_latch.wait();\n\n let write_latch = inner_latches_thread.pop().unwrap(); // both vectors are same size\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 27, "score": 168258.913650189 }, { "content": "pub fn loop_benches(c: &mut Criterion) {\n\n final_clone_bench(c);\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/loop_opts.rs", "rank": 28, "score": 168258.913650189 }, { "content": "pub fn lookup_benches_uuid(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Hash Lookups UUID\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(BenchmarkId::new(\"SIP\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_lookup_sip(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FNV\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_lookup_fnv(b, size)\n\n });\n\n g.bench_with_input(BenchmarkId::new(\"FX\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_lookup_fx(b, size)\n\n });\n\n g.bench_with_input(\n\n BenchmarkId::new(\"FX-IM\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_uuid_lookup_fx_im(b, size),\n\n );\n\n g.bench_with_input(BenchmarkId::new(\"XX\", data_size), data_size, |b, &size| {\n\n tests::bench_uuid_lookup_xx(b, size)\n\n });\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 29, "score": 168258.913650189 }, { "content": "/// Applies function `f` to the component definitions of `c1` and `c2`, while holding both mutexes.\n\n///\n\n/// As locking two mutexes is a deadlock risk, this method fails immediately if one of the mutexes can not be acquired.\n\n///\n\n/// This method is used internally by [`biconnect_components`](prelude/fn.biconnect_components.html) and can be used\n\n/// directly for the same purpose, if some additional work needs to be done on one or both component definitions and\n\n/// it is desirable to avoid acquiring the same mutex again.\n\n///\n\n/// This function can fail with a [`TryDualLockError`](enum.TryDualLockError.html), if one of the mutexes can not be acquired immediately.\n\npub fn on_dual_definition<C1, C2, F, T>(\n\n c1: &Arc<Component<C1>>,\n\n c2: &Arc<Component<C2>>,\n\n f: F,\n\n) -> Result<T, TryDualLockError>\n\nwhere\n\n C1: ComponentDefinition + Sized + 'static,\n\n C2: ComponentDefinition + Sized + 'static,\n\n F: FnOnce(&mut C1, &mut C2) -> T,\n\n{\n\n //c1.on_definition(|cd1| c2.on_definition(|cd2| f(cd1, cd2)))\n\n let mut cd1 = c1.mutable_core.try_lock().map_err(|e| match e {\n\n TryLockError::Poisoned(_) => TryDualLockError::LeftPoisoned,\n\n TryLockError::WouldBlock => TryDualLockError::LeftWouldBlock,\n\n })?;\n\n let mut cd2 = c2.mutable_core.try_lock().map_err(|e| match e {\n\n TryLockError::Poisoned(_) => TryDualLockError::RightPoisoned,\n\n TryLockError::WouldBlock => TryDualLockError::RightWouldBlock,\n\n })?;\n\n Ok(f(&mut cd1.definition, &mut cd2.definition))\n\n}\n\n\n", "file_path": "core/src/utils.rs", "rank": 30, "score": 168253.831274636 }, { "content": "pub fn kompact_network_latency(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Ping Pong RTT\");\n\n g.bench_function(\"Ping Pong RTT (Static)\", ping_pong_latency_static);\n\n g.bench_function(\"Ping Pong RTT (Indexed)\", ping_pong_latency_indexed);\n\n g.bench_function(\n\n \"Ping Pong RTT Pipeline All (Static)\",\n\n ping_pong_latency_pipeline_static,\n\n );\n\n g.bench_function(\n\n \"Ping Pong RTT Pipeline All (Indexed)\",\n\n ping_pong_latency_pipeline_indexed,\n\n );\n\n g.finish();\n\n\n\n let mut group = c.benchmark_group(\"Ping Pong RTT (Static) by Threadpool Size\");\n\n for threads in 1..8 {\n\n group.bench_with_input(\n\n BenchmarkId::from_parameter(threads),\n\n &threads,\n\n ping_pong_latency_static_threads,\n\n );\n\n }\n\n group.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 31, "score": 165202.37004476646 }, { "content": "pub fn insert_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Inserts\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.throughput(Throughput::Elements(*data_size as u64));\n\n g.bench_with_input(\n\n BenchmarkId::new(\"SequenceTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_insert(b, sequence_store::ActorStore::new, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"PathTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_insert(b, ActorStore::new, size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/actor_store/mod.rs", "rank": 32, "score": 165202.37004476646 }, { "content": "pub fn cleanup_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Cleanup\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(\n\n BenchmarkId::new(\"SequenceTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_cleanup(b, sequence_store::ActorStore::new, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"PathTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_cleanup(b, ActorStore::new, size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/actor_store/mod.rs", "rank": 33, "score": 165202.37004476646 }, { "content": "pub fn lookup_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Lookups\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.throughput(Throughput::Elements(*data_size as u64));\n\n g.bench_with_input(\n\n BenchmarkId::new(\"SequenceTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_lookup(b, sequence_store::ActorStore::new(), size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"PathTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_lookup(b, ActorStore::new(), size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/actor_store/mod.rs", "rank": 34, "score": 165202.37004476646 }, { "content": "pub fn kompact_network_throughput(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Ping Pong Throughput with Pipelining\");\n\n g.throughput(Throughput::Elements(2 * MSG_COUNT));\n\n for pipeline in [1u64, 10u64, 100u64, 1000u64].iter() {\n\n //...[1u64, ...\n\n g.bench_with_input(\n\n BenchmarkId::from_parameter(pipeline),\n\n pipeline,\n\n ping_pong_throughput_static,\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 35, "score": 165202.37004476646 }, { "content": "fn setup_system(name: &'static str, threads: usize) -> KompactSystem {\n\n let mut cfg = KompactConfig::new();\n\n cfg.label(name.to_string());\n\n cfg.threads(threads);\n\n cfg.system_components(DeadletterBox::new, {\n\n let net_config = NetworkConfig::new(\"127.0.0.1:0\".parse().expect(\"Address should work\"));\n\n net_config.build()\n\n });\n\n cfg.build().expect(\"KompactSystem\")\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 36, "score": 162740.2849923889 }, { "content": "pub fn ping_pong_latency_indexed(b: &mut Bencher) {\n\n use ppindexed::*;\n\n ping_pong_latency(b, 1, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 37, "score": 162322.83866160337 }, { "content": "pub fn group_lookup_benches(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"GroupLookups\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.throughput(Throughput::Elements(1));\n\n g.bench_with_input(\n\n BenchmarkId::new(\"SequenceTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_group_lookup(b, sequence_store::ActorStore::new(), size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"PathTrie\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_group_lookup(b, ActorStore::new(), size),\n\n );\n\n }\n\n g.finish();\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/actor_store/mod.rs", "rank": 38, "score": 162322.8386616034 }, { "content": "pub fn ping_pong_latency_static(b: &mut Bencher) {\n\n use ppstatic::*;\n\n ping_pong_latency(b, 1, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 39, "score": 162322.83866160337 }, { "content": "pub fn ping_pong_latency_pipeline_indexed(b: &mut Bencher) {\n\n use pppipelineindexed::*;\n\n ping_pong_latency(b, 1, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 40, "score": 159605.37538391945 }, { "content": "pub fn ping_pong_latency_pipeline_static(b: &mut Bencher) {\n\n use pppipelinestatic::*;\n\n ping_pong_latency(b, 1, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 41, "score": 159605.37538391945 }, { "content": "/// Serialises the msg into `buf` and returns a [ChunkRef](net::buffers::ChunkRef) of the serialised\n\n/// data to be used in [tell_preserialised()](actors::ActorPath#method.tell_preserialised)\n\npub fn preserialise_msg<B>(msg: &B, buf: &mut BufferEncoder) -> Result<ChunkRef, SerError>\n\nwhere\n\n B: Serialisable + ?Sized,\n\n{\n\n if let Some(hint) = msg.size_hint() {\n\n buf.try_reserve(hint);\n\n }\n\n buf.put_ser_id(msg.ser_id()); // ser_id\n\n Serialisable::serialise(msg, buf)?; // data\n\n if let Some(chunk_lease) = buf.get_chunk_lease() {\n\n Ok(chunk_lease.into_chunk_ref())\n\n } else {\n\n Err(SerError::BufferError(\"Could not get chunk\".to_string()))\n\n }\n\n}\n\n\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 43, "score": 154030.67863210308 }, { "content": "pub fn load_usize_data(data_size: usize) -> Vec<usize> {\n\n let mut v: Vec<usize> = Vec::with_capacity(data_size);\n\n for i in 0..data_size {\n\n v.push(i);\n\n }\n\n v\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 44, "score": 153009.384844976 }, { "content": "pub fn do_with_any_ref(a: &dyn Any) -> u64 {\n\n if let Some(ref ib) = a.downcast_ref::<IntBox>() {\n\n ib.0\n\n } else {\n\n unimplemented!();\n\n }\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/do_with.rs", "rank": 45, "score": 152205.95691287998 }, { "content": "/// A Kompact port specifies the API of an abstraction\n\n///\n\n/// Such an API consists of *requests*, which are events handled by a provider component,\n\n/// and *indications*, which are events triggered by providers and handled by components that require the abstraction.\n\n///\n\n/// All events on ports must be safe to send between threads, and must be cloneable,\n\n/// as multiple components may be connected to a single port,\n\n/// in which case each component will receive its own copy of the event.\n\n/// For types that are expensive to clone, but read-only, the usage of an [Arc](std::sync::Arc) is recommended.\n\n///\n\n/// # Example\n\n///\n\n/// Consider an abstraction that sums up numbers it is given, and can be asked to provide the current total.\n\n///\n\n/// ```\n\n/// use kompact::prelude::*;\n\n///\n\n/// #[derive(Clone, Debug)]\n\n/// struct Sum(u64);\n\n///\n\n/// #[derive(Clone, Debug)]\n\n/// enum SumRequest {\n\n/// Number(u64),\n\n/// Query \n\n/// }\n\n///\n\n/// struct SummerPort;\n\n/// impl Port for SummerPort {\n\n/// type Indication = Sum;\n\n/// type Request = SumRequest;\n\n/// }\n\n/// ```\n\npub trait Port {\n\n /// Indications are triggered by provider components (see [Provide](Provide))\n\n /// and handled by requiring components (see [Require](Require)).\n\n type Indication: Sized + Send + 'static + Clone + Debug;\n\n /// Requests are triggered by requiring components (see [Require](Require))\n\n /// and handled by provider components (see [Provide](Provide)).\n\n type Request: Sized + Send + 'static + Clone + Debug;\n\n}\n\n\n", "file_path": "core/src/ports.rs", "rank": 46, "score": 152091.87446809222 }, { "content": "pub fn ping_pong_throughput_static(b: &mut Bencher, pipeline: &u64) {\n\n use ppstatic::pipelined::*;\n\n ping_pong_latency(\n\n b,\n\n 4,\n\n |ponger| Pinger::with(MSG_COUNT, *pipeline, ponger),\n\n Ponger::new,\n\n |pinger| pinger.on_definition(|cd| cd.experiment_port()),\n\n );\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 47, "score": 149277.60006180382 }, { "content": "struct CommonPortData<P: Port + 'static> {\n\n provide_channels: Vec<ProvidedRef<P>>,\n\n require_channels: Vec<RequiredRef<P>>,\n\n}\n\n\n\nimpl<P: Port + 'static> CommonPortData<P> {\n\n fn new() -> CommonPortData<P> {\n\n CommonPortData {\n\n provide_channels: Vec::new(),\n\n require_channels: Vec::new(),\n\n }\n\n }\n\n}\n\n\n\n/// An instance of a port type `P` that is marked as provided\n\n///\n\n/// Any component `C` that holds an instance of a provided port for `P`\n\n/// *must* also implement [`Provide<P>`](Provide).\n\n///\n\n/// # Example\n", "file_path": "core/src/ports.rs", "rank": 49, "score": 144288.38882590225 }, { "content": "pub fn do_with_any_box_ref(a: &Box<dyn Any>) -> u64 {\n\n if let Some(ref ib) = a.downcast_ref::<IntBox>() {\n\n ib.0\n\n } else {\n\n unimplemented!();\n\n }\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/do_with.rs", "rank": 50, "score": 142727.06750839113 }, { "content": "#[proc_macro_derive(Actor)]\n\npub fn actor(input: TokenStream) -> TokenStream {\n\n // Parse the input stream\n\n let ast = parse_macro_input!(input as DeriveInput);\n\n\n\n // Build the impl\n\n let gen = impl_actor(&ast);\n\n\n\n //println!(\"Derived code:\\n{}\", gen.clone().into_string());\n\n\n\n // Return the generated impl\n\n gen.into()\n\n}\n\n\n", "file_path": "macros/actor-derive/src/lib.rs", "rank": 51, "score": 141855.28599465347 }, { "content": "/// A mechanism for dynamically getting references to provided/required ports from a component.\n\n///\n\n/// Should only be used if working with concrete types, or strict generic bounds (i.e. [`Provide`],\n\n/// [`ProvideRef`], etc.) is not an option. This is the case, for example, when working with\n\n/// `Arc<dyn `[`AbstractComponent`]`>`.\n\npub trait DynamicPortAccess {\n\n /// **Internal API**. Dynamically obtain a mutable reference to a [`ProvidedPort`] if `self`\n\n /// provides a port of the type indicated by the passed `port_id`.\n\n ///\n\n /// This is a low-level API that is automatically implemented by\n\n /// `#[derive(ComponentDefinition)]`. Prefer the more strongly typed\n\n /// [`get_provided_port`](trait.DynamicComponentDefinition.html#method.get_provided_port).\n\n fn get_provided_port_as_any(&mut self, port_id: std::any::TypeId) -> Option<&mut dyn Any>;\n\n\n\n /// **Internal API**. Dynamically obtain a mutable reference to a [`RequiredPort`] if `self`\n\n /// requires a port of the type indicated by the passed `port_id`.\n\n ///\n\n /// This is a low-level API that is automatically implemented by\n\n /// `#[derive(ComponentDefinition)]`. Prefer the more strongly typed\n\n /// [`get_required_port`](trait.DynamicComponentDefinition.html#method.get_required_port).\n\n fn get_required_port_as_any(&mut self, port_id: std::any::TypeId) -> Option<&mut dyn Any>;\n\n}\n\n\n\nimpl<'a, M: MessageBounds> dyn DynamicComponentDefinition<Message = M> + 'a {\n\n /// Dynamically obtain a mutable reference to a [`ProvidedPort<P>`](ProvidedPort) if `self`\n", "file_path": "core/src/component/definition.rs", "rank": 52, "score": 139267.50063575586 }, { "content": "/// Extracts a [NetMessage](NetMessage) from the provided buffer\n\n///\n\n/// This expects the format from [serialise_msg](serialise_msg).\n\npub fn deserialise_chunk_lease(mut buffer: ChunkLease) -> Result<NetMessage, SerError> {\n\n // if buffer.remaining() < 1 {\n\n // return Err(SerError::InvalidData(\"Not enough bytes available\".into()));\n\n // }\n\n // gonna fail below anyway\n\n\n\n let src = ActorPath::deserialise(&mut buffer)?;\n\n let dst = ActorPath::deserialise(&mut buffer)?;\n\n let ser_id = buffer.get_ser_id();\n\n\n\n let envelope = NetMessage::with_chunk_ref(ser_id, src, dst, buffer.into_chunk_ref());\n\n\n\n Ok(envelope)\n\n}\n\n\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 53, "score": 139124.90349743582 }, { "content": " /// A trait to put a `SerId` into a mutable buffer.\n\n pub trait SerIdBufMut {\n\n /// Serialises a `SerId` into this buffer.\n\n fn put_ser_id(&mut self, ser_id: SerId) -> ();\n\n }\n\n\n\n impl<B: Buf> SerIdBuf for B {\n\n fn get_ser_id(&mut self) -> SerId {\n\n self.get_u8()\n\n }\n\n }\n\n\n\n impl<B: BufMut> SerIdBufMut for B {\n\n fn put_ser_id(&mut self, ser_id: SerId) -> () {\n\n self.put_u8(ser_id)\n\n }\n\n }\n\n}\n\n\n\npub use ser_id::*;\n\n\n", "file_path": "core/src/serialisation/mod.rs", "rank": 55, "score": 135500.93673078468 }, { "content": "pub fn load_uuid_data(data_size: usize) -> Vec<Uuid> {\n\n let mut v: Vec<Uuid> = Vec::with_capacity(data_size);\n\n for _i in 0..data_size {\n\n v.push(Uuid::new_v4());\n\n }\n\n v\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 56, "score": 133318.55949974566 }, { "content": "pub fn load_addr_data(data_size: usize) -> Vec<SocketAddr> {\n\n let mut v: Vec<SocketAddr> = Vec::with_capacity(data_size);\n\n for i in 0..data_size {\n\n let bytes: [u8; 4] = unsafe { std::mem::transmute(i as u32) };\n\n let port_bytes = [bytes[0], bytes[1]];\n\n let port: u16 = unsafe { std::mem::transmute(port_bytes) };\n\n v.push(SocketAddr::new(\n\n IpAddr::V4(Ipv4Addr::new(10, 0, bytes[3], bytes[2])),\n\n port,\n\n ));\n\n }\n\n v\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 57, "score": 130747.6709748959 }, { "content": "/// Serialise a forwarded message\n\n///\n\n/// Uses the same format as [serialise_msg](serialise_msg).\n\npub fn embed_msg(msg: NetMessage, buf: &mut BufferEncoder) -> Result<ChunkLease, SerError> {\n\n // Reserve space for the header:\n\n buf.pad(FRAME_HEAD_LEN as usize);\n\n\n\n msg.sender.serialise(buf)?; // src\n\n msg.receiver.serialise(buf)?; // dst\n\n let NetData { ser_id, data } = msg.data;\n\n buf.put_ser_id(ser_id); // ser_id\n\n match data {\n\n HeapOrSer::Boxed(b) => {\n\n b.serialise(buf)?;\n\n }\n\n HeapOrSer::Serialised(bytes) => {\n\n buf.put(bytes);\n\n }\n\n HeapOrSer::ChunkLease(chunk_lease) => {\n\n buf.put(chunk_lease);\n\n }\n\n HeapOrSer::ChunkRef(chunk_ref) => {\n\n buf.put(chunk_ref);\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 58, "score": 129577.73066799287 }, { "content": "/// Creates a new [NetMessage](NetMessage) from the provided fields\n\n///\n\n/// It allocates a new [BytesMut](bytes::BytesMut)\n\n/// according to the message's size hint.\n\n/// The message's serialised data is then stored in this buffer.\n\npub fn serialise_to_msg(\n\n src: ActorPath,\n\n dst: ActorPath,\n\n msg: Box<dyn Serialisable>,\n\n) -> Result<NetMessage, SerError> {\n\n if let Some(size) = msg.size_hint() {\n\n let mut buf = BytesMut::with_capacity(size);\n\n match msg.serialise(&mut buf) {\n\n Ok(_) => {\n\n let envelope = NetMessage::with_bytes(msg.ser_id(), src, dst, buf.freeze());\n\n Ok(envelope)\n\n }\n\n Err(ser_err) => Err(ser_err),\n\n }\n\n } else {\n\n Err(SerError::Unknown(\"Unknown serialisation size\".into()))\n\n }\n\n}\n\n\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 59, "score": 127710.58047058943 }, { "content": "/// Removes the global default logger\n\n///\n\n/// This causes the remaining messages to be flushed to the output.\n\n///\n\n/// This can't be undone (as in, calling `default_logger()` afterwards again will panic),\n\n/// so make sure you use this only right before exiting the programme.\n\npub fn drop_default_logger() {\n\n unsafe {\n\n drop(DEFAULT_ROOT_LOGGER.take());\n\n }\n\n}\n\n\n", "file_path": "core/src/runtime/mod.rs", "rank": 60, "score": 127705.38333705062 }, { "content": "pub fn as_binary() {\n\n use ppstatic::*;\n\n ping_pong_latency_bin(100000, Pinger::new, Ponger::new, |pinger| {\n\n pinger.on_definition(|cd| cd.experiment_port())\n\n });\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 61, "score": 127701.1807454509 }, { "content": "fn ping_pong_latency<Pinger, PingerF, Ponger, PongerF, PortF>(\n\n b: &mut Bencher,\n\n threads: usize,\n\n pinger_func: PingerF,\n\n ponger_func: PongerF,\n\n port_func: PortF,\n\n) where\n\n Pinger: ComponentDefinition + 'static,\n\n Ponger: ComponentDefinition + 'static,\n\n PingerF: Fn(ActorPath) -> Pinger,\n\n PongerF: Fn() -> Ponger,\n\n PortF: Fn(&std::sync::Arc<Component<Pinger>>) -> ProvidedRef<ExperimentPort>,\n\n{\n\n // Setup\n\n let sys1 = setup_system(\"test-system-1\", threads);\n\n let sys2 = setup_system(\"test-system-2\", threads);\n\n\n\n let timeout = Duration::from_millis(500);\n\n\n\n let (ponger, ponger_f) = sys2.create_and_register(ponger_func);\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 62, "score": 126658.38011107514 }, { "content": "/// Serialises message- and frame-headers and appends the `content`\n\n/// [ChunkRef](net::buffers::ChunkRef) returning a complete network-message as a `ChunkRef`.\n\npub fn serialise_msg_with_preserialised(\n\n src: &ActorPath,\n\n dst: &ActorPath,\n\n content: ChunkRef,\n\n buf: &mut BufferEncoder,\n\n) -> Result<ChunkRef, SerError> {\n\n // Reserve space for the header:\n\n buf.pad(FRAME_HEAD_LEN as usize);\n\n src.serialise(buf)?; // src\n\n dst.serialise(buf)?; // dst\n\n if let Some(mut header) = buf.get_chunk_lease() {\n\n let len = header.capacity() + content.capacity() - FRAME_HEAD_LEN as usize;\n\n header.insert_head(FrameHead::new(FrameType::Data, len));\n\n Ok(header.into_chunk_ref_with_tail(content))\n\n } else {\n\n Err(SerError::BufferError(\"Could not get chunk\".to_string()))\n\n }\n\n}\n\n\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 63, "score": 125251.40169256335 }, { "content": "fn ping_pong_latency_bin<Pinger, PingerF, Ponger, PongerF, PortF>(\n\n iterations: u64,\n\n pinger_func: PingerF,\n\n ponger_func: PongerF,\n\n port_func: PortF,\n\n) -> Duration\n\nwhere\n\n Pinger: ComponentDefinition + 'static,\n\n Ponger: ComponentDefinition + 'static,\n\n PingerF: Fn(ActorPath) -> Pinger,\n\n PongerF: Fn() -> Ponger,\n\n PortF: Fn(&std::sync::Arc<Component<Pinger>>) -> ProvidedRef<ExperimentPort>,\n\n{\n\n // Setup\n\n let sys1 = setup_system(\"test-system-1\", 1);\n\n let sys2 = setup_system(\"test-system-2\", 1);\n\n\n\n let timeout = Duration::from_millis(500);\n\n\n\n let (ponger, ponger_f) = sys2.create_and_register(ponger_func);\n", "file_path": "experiments/dynamic-benches/src/network_latency.rs", "rank": 64, "score": 124493.32778158659 }, { "content": "/// Serialises the provided actor paths and message\n\n///\n\n/// It tries to reserve space for the full message in the [BufferEncoder](net::buffers::BufferEncoder)\n\n/// according to the message's size hint. Then serialises and [frames](net::frames) the full message\n\n/// with headers and extracts a [ChunkLease](net::buffers::ChunkLease)\n\n///\n\n/// # Format\n\n///\n\n/// The serialized and framed format is:\n\n/// frame_head 9 bytes including indicating the type and length of the frame.\n\n/// source ActorPath\n\n/// path_type u8\n\n/// path `[u8; 16]` if [unique path](ActorPath::Unique), else a length-prefixed UTF-8 encoded string\n\n/// destination ActorPath\n\n/// (see above for specific format)\n\n/// ser_id u64\n\n/// message raw bytes\n\npub fn serialise_msg<B>(\n\n src: &ActorPath,\n\n dst: &ActorPath,\n\n msg: &B,\n\n buf: &mut BufferEncoder,\n\n) -> Result<ChunkLease, SerError>\n\nwhere\n\n B: Serialisable + ?Sized,\n\n{\n\n // Check size hint and try to reserve space to avoid chaining\n\n let mut reserve_size = 0;\n\n if let Some(hint) = msg.size_hint() {\n\n reserve_size += hint;\n\n }\n\n if let Some(hint) = src.size_hint() {\n\n reserve_size += hint;\n\n }\n\n if let Some(hint) = dst.size_hint() {\n\n reserve_size += hint;\n\n }\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 65, "score": 121188.5559426136 }, { "content": "fn final_clone_bench(c: &mut Criterion) {\n\n let mut g = c.benchmark_group(\"Final Clone Optimisation\");\n\n for data_size in DATA_SIZES.iter() {\n\n g.bench_with_input(\n\n BenchmarkId::new(\"for loop\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_clone_for_loop(b, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"for_each\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_clone_for_each(b, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"while\", data_size),\n\n data_size,\n\n |b, &size| tests::bench_clone_while(b, size),\n\n );\n\n g.bench_with_input(\n\n BenchmarkId::new(\"for_each_with\", data_size),\n", "file_path": "experiments/dynamic-benches/src/loop_opts.rs", "rank": 66, "score": 116626.31375828695 }, { "content": " /// Additional iterator functions\n\n pub trait IterExtras: Iterator {\n\n /// Iterate over each item in the iterator and apply a function to it and a clone of the given value `t`\n\n ///\n\n /// Behaves like `iterator.for_each(|item| f(item, t.clone()))`, except that it avoids cloning\n\n /// in the case where the iterator contains a single item or for the last item in a larger iterator.\n\n ///\n\n /// Use this when cloning `T` is relatively expensive compared to `f`.\n\n fn for_each_with<T, F>(mut self, t: T, mut f: F)\n\n where\n\n T: Clone,\n\n F: FnMut(Self::Item, T),\n\n {\n\n let mut current: Option<Self::Item> = self.next();\n\n let mut next: Option<Self::Item> = self.next();\n\n while next.is_some() {\n\n let item = current.take().unwrap();\n\n f(item, t.clone());\n\n current = next;\n\n next = self.next();\n\n }\n", "file_path": "core/src/utils.rs", "rank": 67, "score": 114248.47303369161 }, { "content": "/// A routing policy described how to route a given `msg` over\n\n/// a given set of `members`\n\npub trait RoutingPolicy<Ref, M>: fmt::Debug {\n\n /// Route the `msg` to the appropriate `members`\n\n ///\n\n /// A logger should be provided to allow debugging and handle potential routing errors.\n\n fn route(&self, members: &[&Ref], msg: M, logger: &KompactLogger);\n\n\n\n /// Create a boxed copy of this policy\n\n ///\n\n /// Used to make trait objects of this policy cloneable\n\n fn boxed_clone(&self) -> Box<dyn RoutingPolicy<Ref, M> + Send + Sync>;\n\n\n\n /// Provide the broadcast part of this policy, if any\n\n fn broadcast(&self) -> Option<&(dyn RoutingPolicy<Ref, M> + Send + Sync)>;\n\n\n\n /// Provide the select part of this policy, if any\n\n fn select(&self) -> Option<&(dyn RoutingPolicy<Ref, M> + Send + Sync)>;\n\n}\n\n\n\n/// Round-robin dispatch policy\n\n///\n", "file_path": "core/src/routing/groups.rs", "rank": 68, "score": 110836.19825111736 }, { "content": " /// Additional iterator functions\n\n pub trait IterExtras: Iterator + Sized {\n\n /// Iterate over each item in the iterator and apply a function to it and a clone of the given value `t`\n\n ///\n\n /// Behaves like `iterator.for_each(|item| f(item, t.clone()))`, except that it avoids cloning\n\n /// in the case where the iterator contains a single item or for the last item in a larger iterator.\n\n ///\n\n /// Use this when cloning `T` is relatively expensive compared to `f`.\n\n fn for_each_with<T, F>(mut self, t: T, mut f: F)\n\n where\n\n T: Clone,\n\n F: FnMut(Self::Item, T),\n\n {\n\n let mut current: Option<Self::Item> = self.next();\n\n let mut next: Option<Self::Item> = self.next();\n\n while next.is_some() {\n\n let item = current.take().unwrap();\n\n f(item, t.clone());\n\n current = next;\n\n next = self.next();\n\n }\n", "file_path": "core/src/utils.rs", "rank": 69, "score": 110060.12657556272 }, { "content": "/// Split the `&str` into segments using [PATH_SEP](crate::constants::PATH_SEP)\n\npub fn parse_path(s: &str) -> Vec<String> {\n\n s.split(PATH_SEP)\n\n .into_iter()\n\n .map(|v| v.to_string())\n\n .collect()\n\n}\n\n\n", "file_path": "core/src/actors/paths.rs", "rank": 70, "score": 109760.99916715964 }, { "content": "pub fn do_with_any_box(a: Box<dyn Any>) -> u64 {\n\n if let Some(ref ib) = a.downcast_ref::<IntBox>() {\n\n ib.0\n\n } else {\n\n unimplemented!();\n\n }\n\n}\n\n\n", "file_path": "experiments/dynamic-benches/src/do_with.rs", "rank": 71, "score": 109731.48244782962 }, { "content": "#[test]\n\nfn named_registration() {\n\n const ACTOR_NAME: &str = \"ponger\";\n\n let system = system_from_network_config(NetworkConfig::default());\n\n\n\n let ponger = system.create(PongerAct::new_lazy);\n\n system.start(&ponger);\n\n\n\n let _res = system.register_by_alias(&ponger, ACTOR_NAME).wait_expect(\n\n Duration::from_millis(1000),\n\n \"Single registration with unique alias should succeed.\",\n\n );\n\n\n\n let res = system\n\n .register_by_alias(&ponger, ACTOR_NAME)\n\n .wait_timeout(Duration::from_millis(1000))\n\n .expect(\"Registration never completed.\");\n\n\n\n assert_eq!(\n\n res,\n\n Err(RegistrationError::DuplicateEntry),\n", "file_path": "core/tests/dispatch_integration_tests.rs", "rank": 72, "score": 107142.26570178567 }, { "content": "pub fn socket_to_bytes(socket: &SocketAddr) -> [u8; 6] {\n\n let mut bytes = [0u8; 6];\n\n\n\n match socket {\n\n SocketAddr::V4(socket4) => {\n\n let octets = socket4.ip().octets();\n\n bytes[0] = octets[0];\n\n bytes[1] = octets[1];\n\n bytes[2] = octets[2];\n\n bytes[3] = octets[3];\n\n }\n\n _ => panic!(\"Only use V4 sockets!\"),\n\n }\n\n\n\n let port: [u8; 2] = unsafe { std::mem::transmute(socket.port()) };\n\n bytes[4] = port[0];\n\n bytes[5] = port[1];\n\n\n\n bytes\n\n}\n\n\n\npub const VAL: &str = \"Test me!\";\n\n\n", "file_path": "experiments/dynamic-benches/src/hashes.rs", "rank": 73, "score": 105555.01111198745 }, { "content": "#[test]\n\nfn remote_forwarding_named() {\n\n let system1 = system_from_network_config(NetworkConfig::default());\n\n let system2 = system_from_network_config(NetworkConfig::default());\n\n let system3 = system_from_network_config(NetworkConfig::default());\n\n\n\n let (ponger, _pof) = system1.create_and_register(PongerAct::new_lazy);\n\n let pnf = system1.register_by_alias(&ponger, \"ponger\");\n\n let ponger_path = pnf.wait_expect(Duration::from_millis(1000), \"Ponger failed to register!\");\n\n\n\n let (forwarder, _fof) = system2.create_and_register(move || ForwarderAct::new(ponger_path));\n\n let fnf = system2.register_by_alias(&forwarder, \"forwarder\");\n\n let forwarder_path =\n\n fnf.wait_expect(Duration::from_millis(1000), \"Forwarder failed to register!\");\n\n\n\n let (pinger, pif) = system3.create_and_register(move || PingerAct::new_lazy(forwarder_path));\n\n let _pinger_path = pif.wait_expect(Duration::from_millis(1000), \"Pinger failed to register!\");\n\n\n\n system1.start(&ponger);\n\n system2.start(&forwarder);\n\n system3.start(&pinger);\n", "file_path": "core/tests/dispatch_integration_tests.rs", "rank": 74, "score": 104497.07616934598 }, { "content": "/// Kompact's default fault recovery policy is to simply ignore the fault\n\npub fn default_recovery_function(ctx: FaultContext) -> RecoveryHandler {\n\n ctx.ignore()\n\n}\n\n\n\n/// A concrete component instance\n\n///\n\n/// The component class itself is application agnostic,\n\n/// but it contains the application specific [ComponentDefinition](ComponentDefinition).\n\npub struct Component<CD: ComponentTraits> {\n\n core: ComponentCore,\n\n custom_scheduler: Option<dedicated_scheduler::DedicatedThreadScheduler>,\n\n pub(crate) mutable_core: Mutex<ComponentMutableCore<CD>>,\n\n ctrl_queue: ConcurrentQueue<ControlEvent>,\n\n msg_queue: TypedMsgQueue<CD::Message>,\n\n // system components don't have supervision\n\n supervisor: Option<ProvidedRef<SupervisionPort>>,\n\n logger: KompactLogger,\n\n recovery_function: Mutex<Box<RecoveryFunction>>,\n\n}\n\n\n", "file_path": "core/src/component/actual_component.rs", "rank": 75, "score": 104466.0313390196 }, { "content": "/// Methods for things that contain a [SystemPath](SystemPath)\n\npub trait SystemField {\n\n /// Returns a reference to the system path\n\n fn system(&self) -> &SystemPath;\n\n\n\n /// Returns the transport protocol used in the system path\n\n fn protocol(&self) -> Transport {\n\n self.system().protocol()\n\n }\n\n\n\n /// Returns the address used in the system path\n\n fn address(&self) -> &IpAddr {\n\n &self.system().address()\n\n }\n\n\n\n /// Returns the port used in the system path\n\n fn port(&self) -> u16 {\n\n self.system().port()\n\n }\n\n}\n\n\n\nimpl SystemField for SystemPath {\n\n fn system(&self) -> &SystemPath {\n\n self\n\n }\n\n}\n\n\n", "file_path": "core/src/actors/paths.rs", "rank": 76, "score": 104077.49183043567 }, { "content": "/// A trait that acts like a stable `TypeId` for serialisation\n\n///\n\n/// Requires ids to be assigned manually in some consistent fashion\n\n/// so they can be reliable compared between in different binaries and rust versions.\n\n///\n\n/// This trait is used with serialisers that can deal with a large number of types\n\n/// but require some internal differentiation, such as [Serde](crate::serialisation::serde_serialisers),\n\n/// for example.\n\npub trait SerialisationId {\n\n /// The serialisation id for this type\n\n const SER_ID: SerId;\n\n}\n\n\n", "file_path": "core/src/serialisation/core.rs", "rank": 77, "score": 104071.30465937768 }, { "content": "#[inline(always)]\n\nfn system_path_put_into_buf(path: &SystemPath, buf: &mut dyn BufMut) -> Result<(), SerError> {\n\n match *path.address() {\n\n IpAddr::V4(ref ip) => buf.put_slice(&ip.octets()),\n\n IpAddr::V6(ref ip) => buf.put_slice(&ip.octets()),\n\n // TODO support named Domain\n\n }\n\n buf.put_u16(path.port());\n\n Ok(())\n\n}\n", "file_path": "core/src/messaging/framing.rs", "rank": 78, "score": 103043.75141460469 }, { "content": "/// A factory trait for [recipients](Recipient)\n\n///\n\n/// This trait is blanket implemented for all [ActorRefFactory](ActorRefFactory)\n\n/// implementations where the message type is `From<T>`.\n\npub trait Receiver<T> {\n\n /// Produce a recipient for `T`\n\n fn recipient(&self) -> Recipient<T>;\n\n}\n\nimpl<M, T, A> Receiver<T> for A\n\nwhere\n\n T: fmt::Debug + 'static,\n\n M: From<T> + MessageBounds,\n\n A: ActorRefFactory<Message = M>,\n\n{\n\n fn recipient(&self) -> Recipient<T> {\n\n self.actor_ref().recipient()\n\n }\n\n}\n\nimpl<T> Receiver<T> for Recipient<T> {\n\n fn recipient(&self) -> Recipient<T> {\n\n self.clone()\n\n }\n\n}\n\n\n", "file_path": "core/src/actors/refs.rs", "rank": 79, "score": 101859.98837042892 }, { "content": "/// Check that the given path is valid as an insert path\n\n///\n\n/// Insert paths must not contain the following characters:\n\n/// - [PATH_SEP](crate::constants::PATH_SEP)\n\n/// - [UNIQUE_PATH_SEP](crate::constants::UNIQUE_PATH_SEP)\n\n/// - [BROADCAST_MARKER](crate::constants::BROADCAST_MARKER)\n\n/// - [SELECT_MARKER](crate::constants::SELECT_MARKER)\n\npub fn validate_insert_path(path: &[String]) -> Result<(), PathParseError> {\n\n for segment in path.iter() {\n\n validate_insert_path_segment(segment)?;\n\n }\n\n Ok(())\n\n}\n\n\n\npub(crate) fn validate_lookup_path_segment(\n\n segment: &str,\n\n is_last: bool,\n\n) -> Result<(), PathParseError> {\n\n if segment.is_empty() {\n\n return Err(PathParseError::Form(\n\n \"Path segments may not be empty!\".to_string(),\n\n ));\n\n }\n\n let len = segment.len();\n\n for c in segment.chars() {\n\n match c {\n\n PATH_SEP => return Err(PathParseError::IllegalCharacter(PATH_SEP)),\n", "file_path": "core/src/actors/paths.rs", "rank": 80, "score": 101837.04318957697 }, { "content": "/// Check that the given path is valid as a lookup path\n\n///\n\n/// Lookup paths must not contain the following characters:\n\n/// - [PATH_SEP](crate::constants::PATH_SEP)\n\n/// - [UNIQUE_PATH_SEP](crate::constants::UNIQUE_PATH_SEP)\n\n/// - [BROADCAST_MARKER](crate::constants::BROADCAST_MARKER) unless as the only item in the last string\n\n/// - [SELECT_MARKER](crate::constants::SELECT_MARKER) unless as the only item in the last string\n\npub fn validate_lookup_path(path: &[String]) -> Result<(), PathParseError> {\n\n let len = path.len();\n\n for (index, segment) in path.iter().enumerate() {\n\n validate_lookup_path_segment(segment, (index + 1) == len)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "core/src/actors/paths.rs", "rank": 81, "score": 101836.88925035897 }, { "content": " /// A trait to retrieve a `SerId` from a buffer.\n\n pub trait SerIdBuf {\n\n /// Deserialises a `SerId` from this buffer.\n\n fn get_ser_id(&mut self) -> SerId;\n\n }\n\n\n", "file_path": "core/src/serialisation/mod.rs", "rank": 82, "score": 101420.72729681912 }, { "content": "/// A trait that allows to determine the number of bytes in a `SerId`.\n\npub trait SerIdSize {\n\n /// The number of bytes in a concrete implementation of `SerId`.\n\n fn size(&self) -> usize;\n\n}\n\n\n\n#[cfg(feature = \"ser_id_64\")]\n\nmod ser_id {\n\n use super::SerIdSize;\n\n use bytes::{Buf, BufMut};\n\n\n\n /// Type alias for the concrete implementation of serialisation ids.\n\n ///\n\n /// This version is activated by the `ser_id_64` feature flag, and uses a `u64` as the underlying size.\n\n pub type SerId = u64;\n\n\n\n impl SerIdSize for SerId {\n\n fn size(&self) -> usize {\n\n 8\n\n }\n\n }\n\n\n", "file_path": "core/src/serialisation/mod.rs", "rank": 83, "score": 101420.60605216408 }, { "content": "/// A trait for things that have associated [actor references](ActorRef)\n\npub trait ActorRefFactory {\n\n /// The type of messages carried by references produced by this factory\n\n type Message: MessageBounds;\n\n\n\n /// Returns the associated actor reference\n\n fn actor_ref(&self) -> ActorRef<Self::Message>;\n\n}\n\n\n", "file_path": "core/src/actors/mod.rs", "rank": 84, "score": 101229.65396009757 }, { "content": "/// A marker trait for messags that expect a response\n\n///\n\n/// Messages with this trait can be [replied](Request::reply) to.\n\npub trait Request: MessageBounds {\n\n /// The type of the response that is expected\n\n type Response;\n\n\n\n /// Fulfill this request by supplying a response of the appropriate type\n\n fn reply(&self, resp: Self::Response);\n\n}\n\n\n\n/// A generic type for request-response messages\n\n///\n\n/// This type contains information about the target actor\n\n/// for the response, as well as the actual request itself.\n\n///\n\n/// Implementations can also be [dereferenced](std::ops::Deref::deref())\n\n/// to the request message and [replied](Request::reply) to with a\n\n/// response.\n\n#[derive(Debug)]\n\npub struct WithSender<Req: MessageBounds, Resp: MessageBounds> {\n\n sender: ActorRef<Resp>,\n\n content: Req,\n", "file_path": "core/src/actors/refs.rs", "rank": 85, "score": 99217.84635968275 }, { "content": "/// A factory trait to produce instances of [TimerRef](timer::TimerRef)\n\npub trait TimerRefFactory {\n\n /// Returns the timer reference for associated with this factory\n\n fn timer_ref(&self) -> TimerRef;\n\n}\n\n\n\n/// Opaque reference to a scheduled instance of a timer\n\n///\n\n/// Use this to cancel the timer with [cancel_timer](Timer::cancel_timer).\n\n///\n\n/// Instances are returned from functions that schedule timers, such as\n\n/// [schedule_once](Timer::schedule_once) and [schedule_periodic](Timer::schedule_periodic).\n\n#[derive(Clone, Debug, PartialEq, Eq)]\n\npub struct ScheduledTimer(Uuid);\n\n\n\nimpl ScheduledTimer {\n\n /// Create a `ScheduledTimer` from a [Uuid](Uuid) handle\n\n pub fn from_uuid(id: Uuid) -> ScheduledTimer {\n\n ScheduledTimer(id)\n\n }\n\n}\n\n\n", "file_path": "core/src/timer/timer_manager.rs", "rank": 86, "score": 98766.47979093809 }, { "content": "/// A trait for things that can deal with [network messages](NetMessage)\n\npub trait DynActorRefFactory {\n\n /// Returns the associated dynamic actor reference\n\n fn dyn_ref(&self) -> DynActorRef;\n\n}\n\n\n\nimpl<F> DynActorRefFactory for F\n\nwhere\n\n F: ActorRefFactory + ?Sized,\n\n{\n\n fn dyn_ref(&self) -> DynActorRef {\n\n self.actor_ref().dyn_ref()\n\n }\n\n}\n\n\n", "file_path": "core/src/actors/mod.rs", "rank": 87, "score": 98760.69556247734 }, { "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": "feature-tests/protobuf-test/src/messages/example.rs", "rank": 88, "score": 96970.12468377578 }, { "content": "fn remove_count(number: u64) -> u64 {\n\n number & !FLAG_MASK\n\n}\n\n\n", "file_path": "core/src/component/lifecycle.rs", "rank": 89, "score": 95787.95741539553 }, { "content": "/// Creates a new [Serialised](Serialised) from the provided fields\n\n///\n\n/// It allocates a new [BytesMut](bytes::BytesMut)\n\n/// according to the message's size hint.\n\n/// The message's serialised data is then stored in this buffer.\n\npub fn serialise_to_serialised<S>(ser: &S) -> Result<Serialised, SerError>\n\nwhere\n\n S: Serialisable + ?Sized,\n\n{\n\n if let Some(size) = ser.size_hint() {\n\n let mut buf = BytesMut::with_capacity(size);\n\n ser.serialise(&mut buf).map(|_| Serialised {\n\n ser_id: ser.ser_id(),\n\n data: buf.freeze(),\n\n })\n\n } else {\n\n Err(SerError::Unknown(\"Unknown serialisation size\".into()))\n\n }\n\n}\n\n\n", "file_path": "core/src/serialisation/ser_helpers.rs", "rank": 90, "score": 95742.6265325553 }, { "content": "/// Produces a new `KPromise`/`KFuture` pair.\n\npub fn promise<T: Send + Sized>() -> (KPromise<T>, KFuture<T>) {\n\n let (tx, rx) = oneshot::channel();\n\n let f = KFuture { result_channel: rx };\n\n let p = KPromise { result_channel: tx };\n\n (p, f)\n\n}\n\n\n\n/// An error returned when a promise can't be fulfilled.\n\n#[derive(Debug)]\n\npub enum PromiseErr {\n\n /// Indicates that the paired future was already dropped.\n\n ChannelBroken,\n\n /// Indicates that this promise has somehow been fulfilled before.\n\n AlreadyFulfilled,\n\n}\n\nimpl error::Error for PromiseErr {\n\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n\n None\n\n }\n\n}\n", "file_path": "core/src/utils.rs", "rank": 91, "score": 95595.02215059125 }, { "content": "/// A limited version of a [KompactSystem](KompactSystem)\n\n///\n\n/// This is meant for use from within components, where blocking APIs\n\n/// are unacceptable.\n\npub trait SystemHandle: Dispatching + CanCancelTimers {\n\n /// Create a new component\n\n ///\n\n /// Uses `f` to create an instance of a [ComponentDefinition](ComponentDefinition),\n\n /// which is the initialised to form a [Component](Component).\n\n /// Since components are shared between threads, the created component\n\n /// is wrapped into an [Arc](std::sync::Arc).\n\n ///\n\n /// Newly created components are not started automatically.\n\n /// Use [start](KompactSystem::start) or [start_notify](KompactSystem::start_notify)\n\n /// to start a newly created component, once it is connected properly.\n\n ///\n\n /// If you need address this component via the network, see the [register](KompactSystem::register) function.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n\n /// # use kompact::prelude::*;\n\n /// # use kompact::doctest_helpers::*;\n\n /// # let system = KompactConfig::default().build().expect(\"system\");\n", "file_path": "core/src/runtime/system.rs", "rank": 92, "score": 90744.64658997802 }, { "content": "#[inline(always)]\n\nfn system_path_from_buf(buf: &mut dyn Buf) -> Result<(SystemPathHeader, SystemPath), SerError> {\n\n // Deserialize system path\n\n let fields: u8 = buf.get_u8();\n\n let header = SystemPathHeader::try_from(fields)?;\n\n let address: IpAddr = match header.address_type {\n\n AddressType::IPv4 => {\n\n if buf.remaining() < 4 {\n\n return Err(SerError::InvalidData(\n\n \"Could not parse 4 bytes for IPv4 address\".into(),\n\n ));\n\n } else {\n\n let mut ip_bytes = [0u8; 4];\n\n buf.copy_to_slice(&mut ip_bytes);\n\n IpAddr::from(ip_bytes)\n\n }\n\n }\n\n AddressType::IPv6 => {\n\n if buf.remaining() < 16 {\n\n return Err(SerError::InvalidData(\n\n \"Could not parse 16 bytes for IPv6 address\".into(),\n", "file_path": "core/src/messaging/framing.rs", "rank": 93, "score": 90403.30729503585 } ]
Rust
src/log.rs
kornelski/rustracing
117cbd127e5467c4f8303c4dcab9a874d99fdfb2
#[cfg(feature = "stacktrace")] use backtrace::Backtrace; use std::borrow::Cow; use std::time::SystemTime; #[derive(Debug)] pub struct LogBuilder { fields: Vec<LogField>, time: Option<SystemTime>, } impl LogBuilder { pub fn field<T: Into<LogField>>(&mut self, field: T) -> &mut Self { self.fields.push(field.into()); self } pub fn time(&mut self, time: SystemTime) -> &mut Self { self.time = Some(time); self } pub fn std(&mut self) -> StdLogFieldsBuilder { StdLogFieldsBuilder(self) } pub fn error(&mut self) -> StdErrorLogFieldsBuilder { self.field(LogField::new("event", "error")); StdErrorLogFieldsBuilder(self) } pub(crate) fn new() -> Self { LogBuilder { fields: Vec::new(), time: None, } } pub(crate) fn finish(mut self) -> Option<Log> { if self.fields.is_empty() { None } else { self.fields.reverse(); self.fields.sort_by(|a, b| a.name.cmp(&b.name)); self.fields.dedup_by(|a, b| a.name == b.name); Some(Log { fields: self.fields, time: self.time.unwrap_or_else(SystemTime::now), }) } } } #[derive(Debug, Clone)] pub struct Log { fields: Vec<LogField>, time: SystemTime, } impl Log { pub fn fields(&self) -> &[LogField] { &self.fields } pub fn time(&self) -> SystemTime { self.time } } #[derive(Debug, Clone)] pub struct LogField { name: Cow<'static, str>, value: Cow<'static, str>, } impl LogField { pub fn new<N, V>(name: N, value: V) -> Self where N: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { LogField { name: name.into(), value: value.into(), } } pub fn name(&self) -> &str { self.name.as_ref() } pub fn value(&self) -> &str { self.value.as_ref() } } impl<N, V> From<(N, V)> for LogField where N: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from((n, v): (N, V)) -> Self { LogField::new(n, v) } } #[derive(Debug)] pub struct StdLogFieldsBuilder<'a>(&'a mut LogBuilder); impl<'a> StdLogFieldsBuilder<'a> { pub fn event<T>(&mut self, event: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("event", event)); self } pub fn message<T>(&mut self, message: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("message", message)); self } #[cfg(feature = "stacktrace")] pub fn stack(&mut self) -> &mut Self { self.0 .field(LogField::new("stack", format!("{:?}", Backtrace::new()))); self } } #[derive(Debug)] pub struct StdErrorLogFieldsBuilder<'a>(&'a mut LogBuilder); impl<'a> StdErrorLogFieldsBuilder<'a> { pub fn kind<T>(&mut self, kind: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("error.kind", kind)); self } pub fn message<T>(&mut self, message: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("message", message)); self } #[cfg(feature = "stacktrace")] pub fn stack(&mut self) -> &mut Self { self.0 .field(LogField::new("stack", format!("{:?}", Backtrace::new()))); self } }
#[cfg(feature = "stacktrace")] use backtrace::Backtrace; use std::borrow::Cow; use std::time::SystemTime; #[derive(Debug)] pub struct LogBuilder { fields: Vec<LogField>,
lue: V) -> Self where N: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { LogField { name: name.into(), value: value.into(), } } pub fn name(&self) -> &str { self.name.as_ref() } pub fn value(&self) -> &str { self.value.as_ref() } } impl<N, V> From<(N, V)> for LogField where N: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { fn from((n, v): (N, V)) -> Self { LogField::new(n, v) } } #[derive(Debug)] pub struct StdLogFieldsBuilder<'a>(&'a mut LogBuilder); impl<'a> StdLogFieldsBuilder<'a> { pub fn event<T>(&mut self, event: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("event", event)); self } pub fn message<T>(&mut self, message: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("message", message)); self } #[cfg(feature = "stacktrace")] pub fn stack(&mut self) -> &mut Self { self.0 .field(LogField::new("stack", format!("{:?}", Backtrace::new()))); self } } #[derive(Debug)] pub struct StdErrorLogFieldsBuilder<'a>(&'a mut LogBuilder); impl<'a> StdErrorLogFieldsBuilder<'a> { pub fn kind<T>(&mut self, kind: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("error.kind", kind)); self } pub fn message<T>(&mut self, message: T) -> &mut Self where T: Into<Cow<'static, str>>, { self.0.field(LogField::new("message", message)); self } #[cfg(feature = "stacktrace")] pub fn stack(&mut self) -> &mut Self { self.0 .field(LogField::new("stack", format!("{:?}", Backtrace::new()))); self } }
time: Option<SystemTime>, } impl LogBuilder { pub fn field<T: Into<LogField>>(&mut self, field: T) -> &mut Self { self.fields.push(field.into()); self } pub fn time(&mut self, time: SystemTime) -> &mut Self { self.time = Some(time); self } pub fn std(&mut self) -> StdLogFieldsBuilder { StdLogFieldsBuilder(self) } pub fn error(&mut self) -> StdErrorLogFieldsBuilder { self.field(LogField::new("event", "error")); StdErrorLogFieldsBuilder(self) } pub(crate) fn new() -> Self { LogBuilder { fields: Vec::new(), time: None, } } pub(crate) fn finish(mut self) -> Option<Log> { if self.fields.is_empty() { None } else { self.fields.reverse(); self.fields.sort_by(|a, b| a.name.cmp(&b.name)); self.fields.dedup_by(|a, b| a.name == b.name); Some(Log { fields: self.fields, time: self.time.unwrap_or_else(SystemTime::now), }) } } } #[derive(Debug, Clone)] pub struct Log { fields: Vec<LogField>, time: SystemTime, } impl Log { pub fn fields(&self) -> &[LogField] { &self.fields } pub fn time(&self) -> SystemTime { self.time } } #[derive(Debug, Clone)] pub struct LogField { name: Cow<'static, str>, value: Cow<'static, str>, } impl LogField { pub fn new<N, V>(name: N, va
random
[ { "content": "/// This trait allows to insert fields in a HTTP header.\n\npub trait SetHttpHeaderField {\n\n /// Sets the value of the field named `name` in the HTTP header to `value`.\n\n fn set_http_header_field(&mut self, name: &str, value: &str) -> Result<()>;\n\n}\n\nimpl<S: BuildHasher> SetHttpHeaderField for HashMap<String, String, S> {\n\n fn set_http_header_field(&mut self, name: &str, value: &str) -> Result<()> {\n\n self.insert(name.to_owned(), value.to_owned());\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 0, "score": 42464.681296663635 }, { "content": "/// This trait allows to iterate over the fields of a HTTP header.\n\npub trait IterHttpHeaderFields<'a> {\n\n /// Iterator for traversing HTTP header fields.\n\n type Fields: Iterator<Item = (&'a str, &'a [u8])>;\n\n\n\n /// Returns an iterator for traversing the HTTP header fields.\n\n fn fields(&'a self) -> Self::Fields;\n\n}\n\nimpl<'a, K, V, S> IterHttpHeaderFields<'a> for HashMap<K, V, S>\n\nwhere\n\n K: AsRef<str> + Eq + Hash,\n\n V: AsRef<[u8]>,\n\n S: BuildHasher,\n\n{\n\n type Fields = Box<dyn Iterator<Item = (&'a str, &'a [u8])> + 'a>;\n\n\n\n fn fields(&'a self) -> Self::Fields {\n\n Box::new(self.iter().map(|x| (x.0.as_ref(), x.1.as_ref())))\n\n }\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 1, "score": 40716.40528729677 }, { "content": "#[derive(Debug)]\n\nstruct SpanInner<T> {\n\n operation_name: Cow<'static, str>,\n\n start_time: SystemTime,\n\n finish_time: Option<SystemTime>,\n\n references: Vec<SpanReference<T>>,\n\n tags: Vec<Tag>,\n\n logs: Vec<Log>,\n\n context: SpanContext<T>,\n\n span_tx: SpanSender<T>,\n\n}\n\n\n\n/// Finished span.\n\n#[derive(Debug)]\n\npub struct FinishedSpan<T> {\n\n operation_name: Cow<'static, str>,\n\n start_time: SystemTime,\n\n finish_time: SystemTime,\n\n references: Vec<SpanReference<T>>,\n\n tags: Vec<Tag>,\n\n logs: Vec<Log>,\n", "file_path": "src/span.rs", "rank": 2, "score": 29331.00834572483 }, { "content": "/// This trait represents carriers which support **Text Map** format.\n\n///\n\n/// **Text Map** is an arbitrary string-to-string map with an unrestricted character set\n\n/// for both keys and values.\n\npub trait TextMap {\n\n /// Sets the value of `key` in the map to `value`.\n\n fn set(&mut self, key: &str, value: &str);\n\n\n\n /// Gets the value of `key'.\n\n fn get(&self, key: &str) -> Option<&str>;\n\n}\n\nimpl<S: BuildHasher> TextMap for HashMap<String, String, S> {\n\n fn set(&mut self, key: &str, value: &str) {\n\n self.insert(key.to_owned(), value.to_owned());\n\n }\n\n fn get(&self, key: &str) -> Option<&str> {\n\n self.get(key).map(|v| v.as_ref())\n\n }\n\n}\n\nimpl TextMap for BTreeMap<String, String> {\n\n fn set(&mut self, key: &str, value: &str) {\n\n self.insert(key.to_owned(), value.to_owned());\n\n }\n\n fn get(&self, key: &str) -> Option<&str> {\n\n self.get(key).map(|v| v.as_ref())\n\n }\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 3, "score": 28152.47983022556 }, { "content": "/// `Sampler` decides whether a new trace should be sampled or not.\n\npub trait Sampler<T> {\n\n /// This method decides whether a trace with given `span` should be sampled.\n\n fn is_sampled(&self, span: &CandidateSpan<T>) -> bool;\n\n\n\n /// Returns the sampler that samples a trace if `self` or `other` decides to sample it.\n\n fn or<U>(self, other: U) -> OrSampler<Self, U>\n\n where\n\n Self: Sized,\n\n U: Sampler<T>,\n\n {\n\n OrSampler(self, other)\n\n }\n\n\n\n /// Returns the sampler that samples a trace if both of `self` and `other` decides to sample it.\n\n fn and<U>(self, other: U) -> AndSampler<Self, U>\n\n where\n\n Self: Sized,\n\n U: Sampler<T>,\n\n {\n\n AndSampler(self, other)\n", "file_path": "src/sampler.rs", "rank": 4, "score": 26404.203820858696 }, { "content": "/// This trait allows to inject `SpanContext` to binary stream.\n\npub trait InjectToBinary<T>: Sized\n\nwhere\n\n T: Write,\n\n{\n\n /// Injects `context` to `carrier`.\n\n fn inject_to_binary(context: &SpanContext<Self>, carrier: &mut T) -> Result<()>;\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 5, "score": 23045.20765969729 }, { "content": "/// A cheap reference-to-reference conversion that has a possibility to fail.\n\npub trait MaybeAsRef<T: ?Sized> {\n\n /// Performs the conversion.\n\n fn maybe_as_ref(&self) -> Option<&T>;\n\n}\n\nimpl<T, U> MaybeAsRef<T> for Option<U>\n\nwhere\n\n U: MaybeAsRef<T>,\n\n{\n\n fn maybe_as_ref(&self) -> Option<&T> {\n\n self.as_ref().and_then(|u| u.maybe_as_ref())\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 it_works() {\n\n struct Foo;\n", "file_path": "src/convert.rs", "rank": 6, "score": 23045.20765969729 }, { "content": "/// This trait allows to extract `SpanContext` from binary stream.\n\npub trait ExtractFromBinary<T>: Sized\n\nwhere\n\n T: Read,\n\n{\n\n /// Extracts `SpanContext` from `carrier`.\n\n ///\n\n /// If `carrier` contains no span context, it will return `Ok(None)`.\n\n fn extract_from_binary(carrier: &mut T) -> Result<Option<SpanContext<Self>>>;\n\n}\n", "file_path": "src/carrier.rs", "rank": 7, "score": 23045.20765969729 }, { "content": "/// This trait allows to extract `SpanContext` from `TextMap`.\n\npub trait ExtractFromTextMap<T>: Sized\n\nwhere\n\n T: TextMap,\n\n{\n\n /// Extracts `SpanContext` from `carrier`.\n\n ///\n\n /// If `carrier` contains no span context, it will return `Ok(None)`.\n\n fn extract_from_text_map(carrier: &T) -> Result<Option<SpanContext<Self>>>;\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 8, "score": 22155.886145179364 }, { "content": "/// This trait allows to inject `SpanContext` to `TextMap`.\n\npub trait InjectToTextMap<T>: Sized\n\nwhere\n\n T: TextMap,\n\n{\n\n /// Injects `context` to `carrier`.\n\n fn inject_to_text_map(context: &SpanContext<Self>, carrier: &mut T) -> Result<()>;\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 9, "score": 22155.886145179364 }, { "content": "/// This trait allows to inject `SpanContext` to HTTP header.\n\npub trait InjectToHttpHeader<T>: Sized\n\nwhere\n\n T: SetHttpHeaderField,\n\n{\n\n /// Injects `context` to `carrier`.\n\n fn inject_to_http_header(context: &SpanContext<Self>, carrier: &mut T) -> Result<()>;\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 10, "score": 22155.886145179364 }, { "content": "/// This trait allows to extract `SpanContext` from HTTP header.\n\npub trait ExtractFromHttpHeader<'a, T>: Sized\n\nwhere\n\n T: IterHttpHeaderFields<'a>,\n\n{\n\n /// Extracts `SpanContext` from `carrier`.\n\n ///\n\n /// If `carrier` contains no span context, it will return `Ok(None)`.\n\n fn extract_from_http_header(carrier: &'a T) -> Result<Option<SpanContext<Self>>>;\n\n}\n\n\n", "file_path": "src/carrier.rs", "rank": 11, "score": 21248.460472697072 }, { "content": "//! Span.\n\nuse crate::carrier;\n\nuse crate::convert::MaybeAsRef;\n\nuse crate::log::{Log, LogBuilder, StdErrorLogFieldsBuilder};\n\nuse crate::sampler::{AllSampler, Sampler};\n\nuse crate::tag::{StdTag, Tag, TagValue};\n\nuse crate::Result;\n\nuse std::borrow::Cow;\n\nuse std::io::{Read, Write};\n\nuse std::time::SystemTime;\n\n\n\n/// Finished span receiver.\n\npub type SpanReceiver<T> = crossbeam_channel::Receiver<FinishedSpan<T>>;\n\n/// Sender of finished spans to the destination channel.\n\npub type SpanSender<T> = crossbeam_channel::Sender<FinishedSpan<T>>;\n\n\n\n/// Span.\n\n///\n\n/// When this span is dropped, it will be converted to `FinishedSpan` and\n\n/// it will be sent to the associated `SpanReceiver`.\n", "file_path": "src/span.rs", "rank": 15, "score": 6.126599416959062 }, { "content": "pub mod span;\n\npub mod tag;\n\n\n\nmod error;\n\nmod tracer;\n\n\n\n/// This crate specific `Result` type.\n\npub type Result<T> = std::result::Result<T, Error>;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use crate::sampler::AllSampler;\n\n use crate::tag::{StdTag, Tag};\n\n use std::thread;\n\n use std::time::Duration;\n\n\n\n #[test]\n\n fn it_works() {\n\n let (span_tx, span_rx) = crossbeam_channel::bounded(10);\n", "file_path": "src/lib.rs", "rank": 17, "score": 5.531048395317512 }, { "content": "//!\n\n//! # References\n\n//!\n\n//! - [The OpenTracing Semantic Specification (v1.1)][specification]\n\n//!\n\n//! [opentracing]: http://opentracing.io/\n\n//! [specification]: https://github.com/opentracing/specification/blob/master/specification.md\n\n//! [rustracing_jaeger]: https://github.com/sile/rustracing_jaeger\n\n#![warn(missing_docs)]\n\n#![allow(clippy::new_ret_no_self)]\n\n#[macro_use]\n\nextern crate trackable;\n\n\n\npub use crate::error::{Error, ErrorKind};\n\npub use crate::tracer::Tracer;\n\n\n\npub mod carrier;\n\npub mod convert;\n\npub mod log;\n\npub mod sampler;\n", "file_path": "src/lib.rs", "rank": 19, "score": 5.254717839148821 }, { "content": "use trackable::error::ErrorKind as TrackableErrorKind;\n\nuse trackable::error::TrackableError;\n\n\n\n/// This crate specific error type.\n\n#[derive(Debug, Clone, TrackableError)]\n\npub struct Error(TrackableError<ErrorKind>);\n\n\n\n/// The list of the possible error kinds\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n\npub enum ErrorKind {\n\n /// Input data is invalid.\n\n InvalidInput,\n\n\n\n /// Other errors (e.g., I/O error).\n\n Other,\n\n}\n\nimpl TrackableErrorKind for ErrorKind {}\n", "file_path": "src/error.rs", "rank": 23, "score": 4.247954447398096 }, { "content": "//! Span tag.\n\nuse std::borrow::Cow;\n\nuse std::net::{IpAddr, SocketAddr};\n\n\n\n/// Span tag.\n\n#[derive(Debug, Clone)]\n\npub struct Tag {\n\n name: Cow<'static, str>,\n\n value: TagValue,\n\n}\n\nimpl Tag {\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use rustracing::tag::{Tag, TagValue};\n\n ///\n\n /// let tag = Tag::new(\"foo\", \"bar\");\n\n /// assert_eq!(tag.name(), \"foo\");\n\n /// assert_eq!(tag.value(), &TagValue::from(\"bar\"));\n\n /// ```\n", "file_path": "src/tag.rs", "rank": 24, "score": 4.13213193283886 }, { "content": " }\n\n\n\n /// Sets the finish time of this span.\n\n pub fn set_finish_time<F>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> SystemTime,\n\n {\n\n if let Some(inner) = self.0.as_mut() {\n\n inner.finish_time = Some(f());\n\n }\n\n }\n\n\n\n /// Sets the tag to this span.\n\n pub fn set_tag<F>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> Tag,\n\n {\n\n use std::iter::once;\n\n self.set_tags(|| once(f()));\n\n }\n", "file_path": "src/span.rs", "rank": 25, "score": 4.103707686369897 }, { "content": "#[derive(Debug)]\n\npub struct Span<T>(Option<SpanInner<T>>);\n\nimpl<T> Span<T> {\n\n /// Makes an inactive span.\n\n ///\n\n /// This span is never traced.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use rustracing::span::Span;\n\n ///\n\n /// let span = Span::<()>::inactive();\n\n /// assert!(! span.is_sampled());\n\n /// ```\n\n pub fn inactive() -> Self {\n\n Span(None)\n\n }\n\n\n\n /// Returns a handle of this span.\n", "file_path": "src/span.rs", "rank": 26, "score": 4.0652072982976595 }, { "content": "/// all the way into the depths of a storage system),\n\n/// and with it some powerful costs: use this feature with care.\n\n///\n\n/// Use this feature thoughtfully and with care.\n\n/// Every key and value is copied into every local and remote child of the associated `Span`,\n\n/// and that can add up to a lot of network and cpu overhead.\n\n#[derive(Debug, Clone)]\n\npub struct BaggageItem {\n\n name: String,\n\n value: String,\n\n}\n\nimpl BaggageItem {\n\n /// Makes a new `BaggageItem` instance.\n\n pub fn new(name: &str, value: &str) -> Self {\n\n BaggageItem {\n\n name: name.to_owned(),\n\n value: value.to_owned(),\n\n }\n\n }\n\n\n", "file_path": "src/span.rs", "rank": 27, "score": 4.0534775442795485 }, { "content": " pub fn extract_from_text_map<C>(carrier: &C) -> Result<Option<Self>>\n\n where\n\n C: carrier::TextMap,\n\n T: carrier::ExtractFromTextMap<C>,\n\n {\n\n track!(T::extract_from_text_map(carrier))\n\n }\n\n\n\n /// Extracts a context from the **HTTP Header** `carrier`.\n\n pub fn extract_from_http_header<'a, C>(carrier: &'a C) -> Result<Option<Self>>\n\n where\n\n C: carrier::IterHttpHeaderFields<'a>,\n\n T: carrier::ExtractFromHttpHeader<'a, C>,\n\n {\n\n track!(T::extract_from_http_header(carrier))\n\n }\n\n\n\n /// Extracts a context from the **Binary** `carrier`.\n\n pub fn extract_from_binary<C>(carrier: &mut C) -> Result<Option<Self>>\n\n where\n", "file_path": "src/span.rs", "rank": 29, "score": 3.4266529475256986 }, { "content": "//! Traits for representing carriers that propagate span contexts across process boundaries.\n\nuse crate::span::SpanContext;\n\nuse crate::Result;\n\nuse std::collections::{BTreeMap, HashMap};\n\nuse std::hash::{BuildHasher, Hash};\n\nuse std::io::{Read, Write};\n\n\n\n/// This trait allows to inject `SpanContext` to `TextMap`.\n", "file_path": "src/carrier.rs", "rank": 30, "score": 3.4002639580899436 }, { "content": "//! `Sampler` trait and its built-in implementations.\n\nuse crate::span::CandidateSpan;\n\nuse crate::{ErrorKind, Result};\n\nuse rand::{self, Rng};\n\n\n\n/// `Sampler` decides whether a new trace should be sampled or not.\n", "file_path": "src/sampler.rs", "rank": 31, "score": 3.357209570394937 }, { "content": "\n\n /// Injects this context to the **HTTP Header** `carrier`.\n\n pub fn inject_to_http_header<C>(&self, carrier: &mut C) -> Result<()>\n\n where\n\n C: carrier::SetHttpHeaderField,\n\n T: carrier::InjectToHttpHeader<C>,\n\n {\n\n track!(T::inject_to_http_header(self, carrier))\n\n }\n\n\n\n /// Injects this context to the **Binary** `carrier`.\n\n pub fn inject_to_binary<C>(&self, carrier: &mut C) -> Result<()>\n\n where\n\n C: Write,\n\n T: carrier::InjectToBinary<C>,\n\n {\n\n track!(T::inject_to_binary(self, carrier))\n\n }\n\n\n\n /// Extracts a context from the **Text Map** `carrier`.\n", "file_path": "src/span.rs", "rank": 32, "score": 3.3564160107911984 }, { "content": "use crate::sampler::Sampler;\n\nuse crate::span::{SpanReceiver, SpanSender, StartSpanOptions};\n\nuse std::borrow::Cow;\n\nuse std::sync::Arc;\n\n\n\n/// Tracer.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// use rustracing::Tracer;\n\n/// use rustracing::sampler::AllSampler;\n\n///\n\n/// let (span_tx, span_rx) = crossbeam_channel::bounded(10);\n\n/// let tracer = Tracer::with_sender(AllSampler, span_tx);\n\n/// {\n\n/// let _span = tracer.span(\"foo\").start_with_state(());\n\n/// }\n\n/// let span = span_rx.try_recv().unwrap();\n\n/// assert_eq!(span.operation_name(), \"foo\");\n", "file_path": "src/tracer.rs", "rank": 33, "score": 3.3231666183531696 }, { "content": "//! [OpenTracing][opentracing] API for Rust\n\n//!\n\n//! # Examples\n\n//!\n\n//! ```\n\n//! use rustracing::sampler::AllSampler;\n\n//! use rustracing::tag::Tag;\n\n//! use rustracing::Tracer;\n\n//! use std::thread;\n\n//! use std::time::Duration;\n\n//!\n\n//! // Creates a tracer\n\n//! let (span_tx, span_rx) = crossbeam_channel::bounded(10);\n\n//! let tracer = Tracer::with_sender(AllSampler, span_tx);\n\n//! {\n\n//! // Starts \"parent\" span\n\n//! let parent_span = tracer.span(\"parent\").start_with_state(());\n\n//! thread::sleep(Duration::from_millis(10));\n\n//! {\n\n//! // Starts \"child\" span\n", "file_path": "src/lib.rs", "rank": 34, "score": 3.2337520851130375 }, { "content": " /// E.g., `\"elasticsearch\"`, `\"a_custom_microservice\"`, `\"memcache\"`\n\n pub fn peer_service<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"peer.service\", value.into())\n\n }\n\n\n\n /// Makes a `\"samplingpriority\"` tag.\n\n ///\n\n /// If greater than `0`, a hint to the `Tracer` to do its best to capture the trace.\n\n /// If `0`, a hint to the trace to not-capture the trace.\n\n /// If absent, the `Tracer` should use its default sampling mechanism.\n\n pub fn sampling_priority(value: u32) -> Tag {\n\n Tag::new(\"sampling.priority\", i64::from(value))\n\n }\n\n\n\n /// Makes a `\"span.ind\"` tag.\n\n ///\n\n /// Either `\"client\"` or `\"server\"` for the appropriate roles in an RPC,\n\n /// and `\"producer\"` or `\"consumer\"` for the appropriate roles in a messaging scenario.\n\n pub fn span_kind<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"span.kind\", value.into())\n\n }\n\n}\n", "file_path": "src/tag.rs", "rank": 35, "score": 3.201775882341704 }, { "content": " /// Makes a `\"http.url\"` tag.\n\n ///\n\n /// It indicates URL of the request being handled in this segment of the trace, in standard URI format.\n\n ///\n\n /// E.g., `\"https://domain.net/path/to?resource=here\"`\n\n pub fn http_url<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"http.url\", value.into())\n\n }\n\n\n\n /// Makes a `\"message_bus.destination\" tag.\n\n ///\n\n /// It indicates an address at which messages can be exchanged.\n\n ///\n\n /// E.g. A Kafka record has an associated `\"topic name\"` that can be extracted by\n\n /// the instrumented producer or consumer and stored using this tag.\n\n pub fn message_bus_destination<V>(value: V) -> Tag\n\n where\n", "file_path": "src/tag.rs", "rank": 36, "score": 3.2008071891816376 }, { "content": " {\n\n if let Some(inner) = self.0.as_mut() {\n\n let mut builder = LogBuilder::new();\n\n f(&mut builder);\n\n if let Some(log) = builder.finish() {\n\n inner.logs.push(log);\n\n }\n\n }\n\n }\n\n\n\n /// Logs an error.\n\n ///\n\n /// This is a simple wrapper of `log` method\n\n /// except that the `StdTag::error()` tag will be set in this method.\n\n pub fn error_log<F>(&mut self, f: F)\n\n where\n\n F: FnOnce(&mut StdErrorLogFieldsBuilder),\n\n {\n\n if let Some(inner) = self.0.as_mut() {\n\n let mut builder = LogBuilder::new();\n", "file_path": "src/span.rs", "rank": 37, "score": 3.0368120184948566 }, { "content": " V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"message_bus.destination\", value.into())\n\n }\n\n\n\n /// Makes a `\"peer.address\"` tag.\n\n ///\n\n /// It indicates remote \"address\", suitable for use in a networking client library.\n\n ///\n\n /// This may be a `\"ip:port\"`, a bare `\"hostname\"`, a FQDN,\n\n /// or even a JDBC substring like `\"mysql://prod-db:3306\"`.\n\n pub fn peer_address<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"peer.address\", value.into())\n\n }\n\n\n\n /// Makes a `\"peer.hostname\"` tag.\n\n ///\n", "file_path": "src/tag.rs", "rank": 38, "score": 2.9130827455486257 }, { "content": " &self.logs\n\n }\n\n\n\n /// Returns the tags of this span.\n\n pub fn tags(&self) -> &[Tag] {\n\n &self.tags\n\n }\n\n\n\n /// Returns the references of this span.\n\n pub fn references(&self) -> &[SpanReference<T>] {\n\n &self.references\n\n }\n\n\n\n /// Returns the context of this span.\n\n pub fn context(&self) -> &SpanContext<T> {\n\n &self.context\n\n }\n\n}\n\n\n\n/// Span context.\n", "file_path": "src/span.rs", "rank": 39, "score": 2.6170275773789315 }, { "content": " context: SpanContext<T>,\n\n}\n\nimpl<T> FinishedSpan<T> {\n\n /// Returns the operation name of this span.\n\n pub fn operation_name(&self) -> &str {\n\n self.operation_name.as_ref()\n\n }\n\n\n\n /// Returns the start time of this span.\n\n pub fn start_time(&self) -> SystemTime {\n\n self.start_time\n\n }\n\n\n\n /// Returns the finish time of this span.\n\n pub fn finish_time(&self) -> SystemTime {\n\n self.finish_time\n\n }\n\n\n\n /// Returns the logs recorded during this span.\n\n pub fn logs(&self) -> &[Log] {\n", "file_path": "src/span.rs", "rank": 40, "score": 2.5248174731693473 }, { "content": " pub fn span(&self) -> &T {\n\n match *self {\n\n SpanReference::ChildOf(ref x) | SpanReference::FollowsFrom(ref x) => x,\n\n }\n\n }\n\n\n\n /// Returns `true` if this is a `ChildOf` reference.\n\n pub fn is_child_of(&self) -> bool {\n\n if let SpanReference::ChildOf(_) = *self {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n\n\n /// Returns `true` if this is a `FollowsFrom` reference.\n\n pub fn is_follows_from(&self) -> bool {\n\n if let SpanReference::FollowsFrom(_) = *self {\n\n true\n\n } else {\n", "file_path": "src/span.rs", "rank": 41, "score": 2.506286025180352 }, { "content": " pub fn new<N, V>(name: N, value: V) -> Self\n\n where\n\n N: Into<Cow<'static, str>>,\n\n V: Into<TagValue>,\n\n {\n\n Tag {\n\n name: name.into(),\n\n value: value.into(),\n\n }\n\n }\n\n\n\n /// Returns the name of this tag.\n\n pub fn name(&self) -> &str {\n\n self.name.as_ref()\n\n }\n\n\n\n /// Returns the value of this tag.\n\n pub fn value(&self) -> &TagValue {\n\n &self.value\n\n }\n", "file_path": "src/tag.rs", "rank": 42, "score": 2.476346447734983 }, { "content": " pub fn handle(&self) -> SpanHandle<T>\n\n where\n\n T: Clone,\n\n {\n\n SpanHandle(\n\n self.0\n\n .as_ref()\n\n .map(|inner| (inner.context.clone(), inner.span_tx.clone())),\n\n )\n\n }\n\n\n\n /// Returns `true` if this span is sampled (i.e., being traced).\n\n pub fn is_sampled(&self) -> bool {\n\n self.0.is_some()\n\n }\n\n\n\n /// Returns the context of this span.\n\n pub fn context(&self) -> Option<&SpanContext<T>> {\n\n self.0.as_ref().map(|x| &x.context)\n\n }\n", "file_path": "src/span.rs", "rank": 43, "score": 2.447113730354964 }, { "content": " false\n\n }\n\n }\n\n}\n\n\n\n/// Candidate span for tracing.\n\n#[derive(Debug)]\n\npub struct CandidateSpan<'a, T: 'a> {\n\n tags: &'a [Tag],\n\n references: &'a [SpanReference<T>],\n\n baggage_items: &'a [BaggageItem],\n\n}\n\nimpl<'a, T: 'a> CandidateSpan<'a, T> {\n\n /// Returns the tags of this span.\n\n pub fn tags(&self) -> &[Tag] {\n\n self.tags\n\n }\n\n\n\n /// Returns the references of this span.\n\n pub fn references(&self) -> &[SpanReference<T>] {\n", "file_path": "src/span.rs", "rank": 44, "score": 2.432754667286716 }, { "content": " /// Returns the name of this item.\n\n pub fn name(&self) -> &str {\n\n &self.name\n\n }\n\n\n\n /// Returns the value of this item.\n\n pub fn value(&self) -> &str {\n\n &self.value\n\n }\n\n}\n\n\n\n/// Span reference.\n\n#[derive(Debug, Clone)]\n\n#[allow(missing_docs)]\n\npub enum SpanReference<T> {\n\n ChildOf(T),\n\n FollowsFrom(T),\n\n}\n\nimpl<T> SpanReference<T> {\n\n /// Returns the span context state of this reference.\n", "file_path": "src/span.rs", "rank": 45, "score": 2.432754667286716 }, { "content": "pub struct NullSampler;\n\nimpl<T> Sampler<T> for NullSampler {\n\n fn is_sampled(&self, _span: &CandidateSpan<T>) -> bool {\n\n false\n\n }\n\n}\n\n\n\n/// This samples all traces.\n\n#[derive(Debug, Clone)]\n\npub struct AllSampler;\n\nimpl<T> Sampler<T> for AllSampler {\n\n fn is_sampled(&self, _span: &CandidateSpan<T>) -> bool {\n\n true\n\n }\n\n}\n\n\n\n/// `or` combinator.\n\n#[derive(Debug, Clone)]\n\npub struct OrSampler<A, B>(A, B);\n\nimpl<A, B, T> Sampler<T> for OrSampler<A, B>\n", "file_path": "src/sampler.rs", "rank": 46, "score": 2.2979184496831175 }, { "content": " }\n\n\n\n /// Returns the implementation-dependent state of this context.\n\n pub fn state(&self) -> &T {\n\n &self.state\n\n }\n\n\n\n /// Returns the baggage items associated with this context.\n\n pub fn baggage_items(&self) -> &[BaggageItem] {\n\n &self.baggage_items\n\n }\n\n\n\n /// Injects this context to the **Text Map** `carrier`.\n\n pub fn inject_to_text_map<C>(&self, carrier: &mut C) -> Result<()>\n\n where\n\n C: carrier::TextMap,\n\n T: carrier::InjectToTextMap<C>,\n\n {\n\n track!(T::inject_to_text_map(self, carrier))\n\n }\n", "file_path": "src/span.rs", "rank": 47, "score": 2.285252364228397 }, { "content": "impl<'a, S: 'a, T: 'a> StartSpanOptions<'a, S, T>\n\nwhere\n\n S: Sampler<T>,\n\n{\n\n /// Sets the start time of this span.\n\n pub fn start_time(mut self, time: SystemTime) -> Self {\n\n self.start_time = Some(time);\n\n self\n\n }\n\n\n\n /// Sets the tag to this span.\n\n pub fn tag(mut self, tag: Tag) -> Self {\n\n self.tags.push(tag);\n\n self\n\n }\n\n\n\n /// Adds the `ChildOf` reference to this span.\n\n pub fn child_of<C>(mut self, context: &C) -> Self\n\n where\n\n C: MaybeAsRef<SpanContext<T>>,\n", "file_path": "src/span.rs", "rank": 48, "score": 2.235954205635644 }, { "content": " .iter()\n\n .find(|t| t.name() == \"sampling.priority\")\n\n .map(|t| t.value())\n\n {\n\n n > 0\n\n } else {\n\n self.sampler.is_sampled(&self.span())\n\n }\n\n }\n\n}\n\n\n\n/// Immutable handle of `Span`.\n\n#[derive(Debug, Clone)]\n\npub struct SpanHandle<T>(Option<(SpanContext<T>, SpanSender<T>)>);\n\nimpl<T> SpanHandle<T> {\n\n /// Returns `true` if this span is sampled (i.e., being traced).\n\n pub fn is_sampled(&self) -> bool {\n\n self.0.is_some()\n\n }\n\n\n", "file_path": "src/span.rs", "rank": 49, "score": 2.1115077748192617 }, { "content": " /// Returns the context of this span.\n\n pub fn context(&self) -> Option<&SpanContext<T>> {\n\n self.0.as_ref().map(|&(ref context, _)| context)\n\n }\n\n\n\n /// Gets the baggage item that has the name `name`.\n\n pub fn get_baggage_item(&self, name: &str) -> Option<&BaggageItem> {\n\n if let Some(context) = self.context() {\n\n context.baggage_items.iter().find(|x| x.name == name)\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Starts a `ChildOf` span if this span is sampled.\n\n pub fn child<N, F>(&self, operation_name: N, f: F) -> Span<T>\n\n where\n\n N: Into<Cow<'static, str>>,\n\n T: Clone,\n\n F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,\n", "file_path": "src/span.rs", "rank": 50, "score": 2.089462046968005 }, { "content": "\n\n /// Sets the tags to this span.\n\n pub fn set_tags<F, I>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> I,\n\n I: IntoIterator<Item = Tag>,\n\n {\n\n if let Some(inner) = self.0.as_mut() {\n\n for tag in f() {\n\n inner.tags.retain(|x| x.name() != tag.name());\n\n inner.tags.push(tag);\n\n }\n\n }\n\n }\n\n\n\n /// Sets the baggage item to this span.\n\n pub fn set_baggage_item<F>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> BaggageItem,\n\n {\n", "file_path": "src/span.rs", "rank": 51, "score": 2.0797320865198725 }, { "content": "}\n\n\n\n/// Boxed version of `Sampler`.\n\npub type BoxSampler<T> = Box<dyn Sampler<T> + Send + Sync + 'static>;\n\n\n\n/// This samples a certain percentage of traces.\n\n#[derive(Debug, Clone)]\n\npub struct ProbabilisticSampler {\n\n sampling_rate: f64,\n\n}\n\nimpl ProbabilisticSampler {\n\n /// Makes a new `ProbabilisticSampler` instance.\n\n ///\n\n /// # Errors\n\n ///\n\n /// If `sampling_rate` is not in the range `0.0...1.0`,\n\n /// it will return an error with the kind `ErrorKind::InvalidInput`.\n\n pub fn new(sampling_rate: f64) -> Result<Self> {\n\n track_assert!(0.0 <= sampling_rate, ErrorKind::InvalidInput);\n\n track_assert!(sampling_rate <= 1.0, ErrorKind::InvalidInput);\n", "file_path": "src/sampler.rs", "rank": 52, "score": 2.078984505834914 }, { "content": "\n\n /// Sets the operation name of this span.\n\n pub fn set_operation_name<F, N>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> N,\n\n N: Into<Cow<'static, str>>,\n\n {\n\n if let Some(inner) = self.0.as_mut() {\n\n inner.operation_name = f().into();\n\n }\n\n }\n\n\n\n /// Sets the start time of this span.\n\n pub fn set_start_time<F>(&mut self, f: F)\n\n where\n\n F: FnOnce() -> SystemTime,\n\n {\n\n if let Some(inner) = self.0.as_mut() {\n\n inner.start_time = f();\n\n }\n", "file_path": "src/span.rs", "rank": 53, "score": 2.0488985921806147 }, { "content": " pub fn db_statement<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"db.statement\", value.into())\n\n }\n\n\n\n /// Makes a `\"db.type\"` tag.\n\n ///\n\n /// It indicates database type.\n\n ///\n\n /// For any SQL database, `\"sql\"`.\n\n /// For others, the lower-case database category, e.g. `\"cassandra\"`, `\"hbase\"`, or `\"redis\"`.\n\n pub fn db_type<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"db.type\", value.into())\n\n }\n\n\n", "file_path": "src/tag.rs", "rank": 54, "score": 2.0043252890697483 }, { "content": " /// Makes a `\"db.user\"` tag.\n\n ///\n\n /// It indicates username for accessing database.\n\n ///\n\n /// E.g., `\"readonly_user\"` or `\"reporting_user\"`\n\n pub fn db_user<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"db.user\", value.into())\n\n }\n\n\n\n /// Makes a `\"error\"` tag that has the value `true`.\n\n ///\n\n /// It indicates the application considers the operation represented by the `Span` to have failed.\n\n pub fn error() -> Tag {\n\n Tag::new(\"error\", true)\n\n }\n\n\n\n /// Makes a `\"http.method\"` tag.\n", "file_path": "src/tag.rs", "rank": 55, "score": 1.9341953534905487 }, { "content": " ///\n\n /// It indicates HTTP method of the request for the associated `Span`.\n\n ///\n\n /// E.g., `\"GET\"`, `\"POST\"`\n\n pub fn http_method<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"http.method\", value.into())\n\n }\n\n\n\n /// Makes a `\"http.status_code\"` tag.\n\n ///\n\n /// It indicates HTTP response status code for the associated `Span`.\n\n ///\n\n /// E.g., 200, 503, 404\n\n pub fn http_status_code(value: u16) -> Tag {\n\n Tag::new(\"http.status_code\", i64::from(value))\n\n }\n\n\n", "file_path": "src/tag.rs", "rank": 56, "score": 1.9341953534905487 }, { "content": "/// ```\n\n#[derive(Debug)]\n\npub struct Tracer<S, T> {\n\n sampler: Arc<S>,\n\n span_tx: SpanSender<T>,\n\n}\n\nimpl<S: Sampler<T>, T> Tracer<S, T> {\n\n /// This constructor is mainly for backward compatibility, it has the same interface\n\n /// as in previous versions except the type of `SpanReceiver`.\n\n /// It builds an unbounded channel which may cause memory issues if there is no reader,\n\n /// prefer `with_sender()` alternative with a bounded one.\n\n pub fn new(sampler: S) -> (Self, SpanReceiver<T>) {\n\n let (span_tx, span_rx) = crossbeam_channel::unbounded();\n\n (Self::with_sender(sampler, span_tx), span_rx)\n\n }\n\n\n\n /// Makes a new `Tracer` instance.\n\n pub fn with_sender(sampler: S, span_tx: SpanSender<T>) -> Self {\n\n Tracer {\n\n sampler: Arc::new(sampler),\n", "file_path": "src/tracer.rs", "rank": 57, "score": 1.9245731314601395 }, { "content": " self.references\n\n }\n\n\n\n /// Returns the baggage items of this span.\n\n pub fn baggage_items(&self) -> &[BaggageItem] {\n\n self.baggage_items\n\n }\n\n}\n\n\n\n/// Options for starting a span.\n\n#[derive(Debug)]\n\npub struct StartSpanOptions<'a, S: 'a, T: 'a> {\n\n operation_name: Cow<'static, str>,\n\n start_time: Option<SystemTime>,\n\n tags: Vec<Tag>,\n\n references: Vec<SpanReference<T>>,\n\n baggage_items: Vec<BaggageItem>,\n\n span_tx: &'a SpanSender<T>,\n\n sampler: &'a S,\n\n}\n", "file_path": "src/span.rs", "rank": 58, "score": 1.9207541852322434 }, { "content": "}\n\n\n\n/// [Standard span tags][tags].\n\n/// [tags]: https://github.com/opentracing/specification/blob/master/semantic_conventions.md#span-tags-table\n\n#[derive(Debug)]\n\npub struct StdTag;\n\nimpl StdTag {\n\n /// Makes a `\"component\"` tag.\n\n ///\n\n /// It indicates the software package, framework, library,\n\n /// or module that generated the associated `Span`.\n\n ///\n\n /// E.g., `\"grpc\"`, `\"django\"`, `\"JDBI\"`.\n\n pub fn component<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"component\", value.into())\n\n }\n\n\n", "file_path": "src/tag.rs", "rank": 59, "score": 1.9074985392745631 }, { "content": "rustracing\n\n==========\n\n\n\n[![Crates.io: rustracing](https://img.shields.io/crates/v/rustracing.svg)](https://crates.io/crates/rustracing)\n\n[![Documentation](https://docs.rs/rustracing/badge.svg)](https://docs.rs/rustracing)\n\n[![Actions Status](https://github.com/sile/rustracing/workflows/CI/badge.svg)](https://github.com/sile/rustracing/actions)\n\n[![Coverage Status](https://coveralls.io/repos/github/sile/rustracing/badge.svg?branch=master)](https://coveralls.io/github/sile/rustracing?branch=master)\n\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n\n\n\n[OpenTracing] API for Rust.\n\n\n\n[Documentation](https://docs.rs/rustracing)\n\n\n\nExamples\n\n--------\n\n\n\n```rust\n\nuse rustracing::sampler::AllSampler;\n\nuse rustracing::tag::Tag;\n\nuse rustracing::Tracer;\n\nuse std::thread;\n\nuse std::time::Duration;\n\n\n\n// Creates a tracer\n\nlet (span_tx, span_rx) = crossbeam_channel::bounded(10);\n\nlet tracer = Tracer::with_sender(AllSampler, span_tx);\n\n{\n\n // Starts \"parent\" span\n\n let parent_span = tracer.span(\"parent\").start_with_state(());\n\n thread::sleep(Duration::from_millis(10));\n\n {\n\n // Starts \"child\" span\n\n let mut child_span = tracer\n\n .span(\"child_span\")\n\n .child_of(&parent_span)\n\n .tag(Tag::new(\"key\", \"value\"))\n\n .start_with_state(());\n\n\n\n child_span.log(|log| {\n\n log.error().message(\"a log message\");\n\n });\n\n } // The \"child\" span dropped and will be sent to `span_rx`\n\n} // The \"parent\" span dropped and will be sent to `span_rx`\n\n\n\n// Outputs finished spans to the standard output\n\nwhile let Ok(span) = span_rx.try_recv() {\n\n println!(\"# SPAN: {:?}\", span);\n\n}\n\n```\n\n\n\nAs an actual usage example of the crate and an implementation of the [OpenTracing] API,\n\nit may be helpful to looking at [rustracing_jaeger] crate.\n\n\n\nReferences\n\n----------\n\n\n\n- [The OpenTracing Semantic Specification (v1.1)][specification]\n\n\n\n[OpenTracing]: http://opentracing.io/\n\n[specification]: https://github.com/opentracing/specification/blob/master/specification.md\n\n[rustracing_jaeger]: https://github.com/sile/rustracing_jaeger\n", "file_path": "README.md", "rank": 60, "score": 1.9056993226301024 }, { "content": " if let Some(inner) = self.0.as_mut() {\n\n let item = f();\n\n inner.context.baggage_items.retain(|x| x.name != item.name);\n\n inner.context.baggage_items.push(item);\n\n }\n\n }\n\n\n\n /// Gets the baggage item that has the name `name`.\n\n pub fn get_baggage_item(&self, name: &str) -> Option<&BaggageItem> {\n\n if let Some(inner) = self.0.as_ref() {\n\n inner.context.baggage_items.iter().find(|x| x.name == name)\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n /// Logs structured data.\n\n pub fn log<F>(&mut self, f: F)\n\n where\n\n F: FnOnce(&mut LogBuilder),\n", "file_path": "src/span.rs", "rank": 61, "score": 1.894424600924488 }, { "content": " pub fn peer_ip(value: IpAddr) -> Tag {\n\n match value {\n\n IpAddr::V4(v) => Tag::new(\"peer.ipv4\", v.to_string()),\n\n IpAddr::V6(v) => Tag::new(\"peer.ipv6\", v.to_string()),\n\n }\n\n }\n\n\n\n /// Makes a `\"peer.port\"` tag.\n\n ///\n\n /// It indicates remote port.\n\n ///\n\n /// E.g., `80`\n\n pub fn peer_port(value: u16) -> Tag {\n\n Tag::new(\"peer.port\", i64::from(value))\n\n }\n\n\n\n /// Makes a `\"peer.service\"` tag.\n\n ///\n\n /// It indicates remote service name (for some unspecified definition of `\"service\"`).\n\n ///\n", "file_path": "src/tag.rs", "rank": 62, "score": 1.8815286593602392 }, { "content": " span_tx,\n\n }\n\n }\n\n\n\n /// Returns `StartSpanOptions` for starting a span which has the name `operation_name`.\n\n pub fn span<N>(&self, operation_name: N) -> StartSpanOptions<S, T>\n\n where\n\n N: Into<Cow<'static, str>>,\n\n {\n\n StartSpanOptions::new(operation_name, &self.span_tx, &self.sampler)\n\n }\n\n}\n\nimpl<S, T> Tracer<S, T> {\n\n /// Clone with the given `sampler`.\n\n pub fn clone_with_sampler<U: Sampler<T>>(&self, sampler: U) -> Tracer<U, T> {\n\n Tracer {\n\n sampler: Arc::new(sampler),\n\n span_tx: self.span_tx.clone(),\n\n }\n\n }\n", "file_path": "src/tracer.rs", "rank": 63, "score": 1.7729098839005402 }, { "content": " /// It indicates remote hostname.\n\n ///\n\n /// E.g., `\"opentracing.io\"`, `\"internal.dns.name\"`\n\n pub fn peer_hostname<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"peer.hostname\", value.into())\n\n }\n\n\n\n /// Makes a `\"peer.ipXX\"` and `\"peer.port\"` tags.\n\n pub fn peer_addr(value: SocketAddr) -> Vec<Tag> {\n\n vec![Self::peer_ip(value.ip()), Self::peer_port(value.port())]\n\n }\n\n\n\n /// Makes a tag which has the name either `\"peer.ipv4\"` or `\"peer.ipv6\"` depending on the value.\n\n ///\n\n /// It indicates remote IP address.\n\n ///\n\n /// E.g., `\"127.0.0.1\"`, `\"2001:0db8:85a3:0000:0000:8a2e:0370:7334\"`\n", "file_path": "src/tag.rs", "rank": 64, "score": 1.7285596497253943 }, { "content": " /// Starts a `FollowsFrom` span if this span is sampled.\n\n pub fn follower<N, F>(&self, operation_name: N, f: F) -> Span<T>\n\n where\n\n N: Into<Cow<'static, str>>,\n\n T: Clone,\n\n F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,\n\n {\n\n self.handle().follower(operation_name, f)\n\n }\n\n\n\n pub(crate) fn new(\n\n operation_name: Cow<'static, str>,\n\n start_time: SystemTime,\n\n references: Vec<SpanReference<T>>,\n\n tags: Vec<Tag>,\n\n state: T,\n\n baggage_items: Vec<BaggageItem>,\n\n span_tx: SpanSender<T>,\n\n ) -> Self {\n\n let context = SpanContext::new(state, baggage_items);\n", "file_path": "src/span.rs", "rank": 65, "score": 1.6761475550296152 }, { "content": "///\n\n/// Each `SpanContext` encapsulates the following state:\n\n///\n\n/// - `T`: OpenTracing-implementation-dependent state (for example, trace and span ids) needed to refer to a distinct `Span` across a process boundary\n\n/// - `BaggageItems`: These are just key:value pairs that cross process boundaries\n\n#[derive(Debug, Clone)]\n\npub struct SpanContext<T> {\n\n state: T,\n\n baggage_items: Vec<BaggageItem>,\n\n}\n\nimpl<T> SpanContext<T> {\n\n /// Makes a new `SpanContext` instance.\n\n pub fn new(state: T, mut baggage_items: Vec<BaggageItem>) -> Self {\n\n baggage_items.reverse();\n\n baggage_items.sort_by(|a, b| a.name().cmp(b.name()));\n\n baggage_items.dedup_by(|a, b| a.name() == b.name());\n\n SpanContext {\n\n state,\n\n baggage_items,\n\n }\n", "file_path": "src/span.rs", "rank": 67, "score": 1.5713292750769046 }, { "content": " self.baggage_items\n\n .extend(context.baggage_items().iter().cloned());\n\n }\n\n self\n\n }\n\n\n\n /// Starts a new span.\n\n pub fn start(mut self) -> Span<T>\n\n where\n\n T: for<'b> From<CandidateSpan<'b, T>>,\n\n {\n\n self.normalize();\n\n if !self.is_sampled() {\n\n return Span(None);\n\n }\n\n let state = T::from(self.span());\n\n Span::new(\n\n self.operation_name,\n\n self.start_time.unwrap_or_else(SystemTime::now),\n\n self.references,\n", "file_path": "src/span.rs", "rank": 68, "score": 1.529110459372464 }, { "content": " self.tags,\n\n state,\n\n self.baggage_items,\n\n self.span_tx.clone(),\n\n )\n\n }\n\n\n\n /// Starts a new span with the explicit `state`.\n\n pub fn start_with_state(mut self, state: T) -> Span<T> {\n\n self.normalize();\n\n if !self.is_sampled() {\n\n return Span(None);\n\n }\n\n Span::new(\n\n self.operation_name,\n\n self.start_time.unwrap_or_else(SystemTime::now),\n\n self.references,\n\n self.tags,\n\n state,\n\n self.baggage_items,\n", "file_path": "src/span.rs", "rank": 69, "score": 1.5123766921205584 }, { "content": "where\n\n A: Sampler<T>,\n\n B: Sampler<T>,\n\n{\n\n fn is_sampled(&self, span: &CandidateSpan<T>) -> bool {\n\n self.0.is_sampled(span) || self.1.is_sampled(span)\n\n }\n\n}\n\n\n\n/// `and` combinator.\n\n#[derive(Debug, Clone)]\n\npub struct AndSampler<A, B>(A, B);\n\nimpl<A, B, T> Sampler<T> for AndSampler<A, B>\n\nwhere\n\n A: Sampler<T>,\n\n B: Sampler<T>,\n\n{\n\n fn is_sampled(&self, span: &CandidateSpan<T>) -> bool {\n\n self.0.is_sampled(span) && self.1.is_sampled(span)\n\n }\n\n}\n", "file_path": "src/sampler.rs", "rank": 70, "score": 1.4339166088602657 }, { "content": " self.span_tx.clone(),\n\n )\n\n }\n\n\n\n pub(crate) fn new<N>(operation_name: N, span_tx: &'a SpanSender<T>, sampler: &'a S) -> Self\n\n where\n\n N: Into<Cow<'static, str>>,\n\n {\n\n StartSpanOptions {\n\n operation_name: operation_name.into(),\n\n start_time: None,\n\n tags: Vec::new(),\n\n references: Vec::new(),\n\n baggage_items: Vec::new(),\n\n span_tx,\n\n sampler,\n\n }\n\n }\n\n\n\n fn normalize(&mut self) {\n", "file_path": "src/span.rs", "rank": 71, "score": 1.4047656621710258 }, { "content": "}\n\n\n\n/// Span tag value.\n\n#[derive(Debug, Clone, PartialEq, PartialOrd)]\n\n#[allow(missing_docs)]\n\npub enum TagValue {\n\n String(Cow<'static, str>),\n\n Boolean(bool),\n\n Integer(i64),\n\n Float(f64),\n\n}\n\nimpl From<&'static str> for TagValue {\n\n fn from(f: &'static str) -> Self {\n\n TagValue::String(Cow::Borrowed(f))\n\n }\n\n}\n\nimpl From<String> for TagValue {\n\n fn from(f: String) -> Self {\n\n TagValue::String(Cow::Owned(f))\n\n }\n", "file_path": "src/tag.rs", "rank": 72, "score": 1.3631958295442614 }, { "content": " Ok(ProbabilisticSampler { sampling_rate })\n\n }\n\n}\n\nimpl<T> Sampler<T> for ProbabilisticSampler {\n\n fn is_sampled(&self, _span: &CandidateSpan<T>) -> bool {\n\n rand::thread_rng().gen_range(0.0, 1.0) < self.sampling_rate\n\n }\n\n}\n\n\n\n/// This samples traces which have one or more references.\n\n#[derive(Debug, Clone)]\n\npub struct PassiveSampler;\n\nimpl<T> Sampler<T> for PassiveSampler {\n\n fn is_sampled(&self, span: &CandidateSpan<T>) -> bool {\n\n !span.references().is_empty()\n\n }\n\n}\n\n\n\n/// This samples no traces.\n\n#[derive(Debug, Clone)]\n", "file_path": "src/sampler.rs", "rank": 73, "score": 1.3114512020152467 }, { "content": " /// Makes a `\"db.instance\"` tag.\n\n ///\n\n /// It indicates database instance name.\n\n ///\n\n /// E.g., In java, if the jdbc.url=`\"jdbc:mysql://127.0.0.1:3306/customers\"`,\n\n /// the instance name is `\"customers\"`.\n\n pub fn db_instance<V>(value: V) -> Tag\n\n where\n\n V: Into<Cow<'static, str>>,\n\n {\n\n Tag::new(\"db.instance\", value.into())\n\n }\n\n\n\n /// Makes a `\"db.statement\"` tag.\n\n ///\n\n /// It indicates a database statement for the given database type.\n\n ///\n\n /// E.g.,\n\n /// for db.type=`\"sql\"`, `\"SELECT * FROM wuser_table\"`;\n\n /// for db.type=`\"redis\"`, `\"SET mykey 'WuValue'\"`.\n", "file_path": "src/tag.rs", "rank": 74, "score": 1.2991230687692896 }, { "content": " T: Clone,\n\n {\n\n if let Some(context) = context.maybe_as_ref() {\n\n let reference = SpanReference::ChildOf(context.state().clone());\n\n self.references.push(reference);\n\n self.baggage_items\n\n .extend(context.baggage_items().iter().cloned());\n\n }\n\n self\n\n }\n\n\n\n /// Adds the `FollowsFrom` reference to this span.\n\n pub fn follows_from<C>(mut self, context: &C) -> Self\n\n where\n\n C: MaybeAsRef<SpanContext<T>>,\n\n T: Clone,\n\n {\n\n if let Some(context) = context.maybe_as_ref() {\n\n let reference = SpanReference::FollowsFrom(context.state().clone());\n\n self.references.push(reference);\n", "file_path": "src/span.rs", "rank": 75, "score": 1.2751493051728948 }, { "content": " f(&mut builder.error());\n\n if let Some(log) = builder.finish() {\n\n inner.logs.push(log);\n\n }\n\n if inner.tags.iter().find(|x| x.name() == \"error\").is_none() {\n\n inner.tags.push(StdTag::error());\n\n }\n\n }\n\n }\n\n\n\n /// Starts a `ChildOf` span if this span is sampled.\n\n pub fn child<N, F>(&self, operation_name: N, f: F) -> Span<T>\n\n where\n\n N: Into<Cow<'static, str>>,\n\n T: Clone,\n\n F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,\n\n {\n\n self.handle().child(operation_name, f)\n\n }\n\n\n", "file_path": "src/span.rs", "rank": 76, "score": 1.2751493051728948 }, { "content": " {\n\n if let Some(&(ref context, ref span_tx)) = self.0.as_ref() {\n\n let options =\n\n StartSpanOptions::new(operation_name, span_tx, &AllSampler).child_of(context);\n\n f(options)\n\n } else {\n\n Span::inactive()\n\n }\n\n }\n\n\n\n /// Starts a `FollowsFrom` span if this span is sampled.\n\n pub fn follower<N, F>(&self, operation_name: N, f: F) -> Span<T>\n\n where\n\n N: Into<Cow<'static, str>>,\n\n T: Clone,\n\n F: FnOnce(StartSpanOptions<AllSampler, T>) -> Span<T>,\n\n {\n\n if let Some(&(ref context, ref span_tx)) = self.0.as_ref() {\n\n let options =\n\n StartSpanOptions::new(operation_name, span_tx, &AllSampler).follows_from(context);\n\n f(options)\n\n } else {\n\n Span::inactive()\n\n }\n\n }\n\n}\n", "file_path": "src/span.rs", "rank": 77, "score": 1.1201206464746947 } ]
Rust
santa/src/before_level.rs
balbok0/abstreet
3af15fefdb2772c83864c08724318418da8190a9
use std::collections::{BTreeSet, HashSet}; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use abstutil::prettyprint_usize; use geom::Time; use map_gui::load::MapLoader; use map_gui::tools::PopupMsg; use map_gui::ID; use map_model::BuildingID; use widgetry::{ ButtonBuilder, Color, ControlState, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Image, Key, Line, Outcome, Panel, RewriteColor, State, Text, TextExt, VerticalAlignment, Widget, }; use crate::buildings::{BldgState, Buildings}; use crate::game::Game; use crate::levels::Level; use crate::meters::{custom_bar, make_bar}; use crate::vehicles::Vehicle; use crate::{App, Transition}; const ZOOM: f64 = 2.0; pub struct Picker { vehicle_panel: Panel, instructions_panel: Panel, upzone_panel: Panel, level: Level, bldgs: Buildings, current_picks: BTreeSet<BuildingID>, draw_start: Drawable, } impl Picker { pub fn new(ctx: &mut EventCtx, app: &App, level: Level) -> Box<dyn State<App>> { MapLoader::new( ctx, app, level.map.clone(), Box::new(move |ctx, app| { app.session.music.change_song(&level.music); ctx.canvas.cam_zoom = ZOOM; let start = app .map .get_i(app.map.find_i_by_osm_id(level.start).unwrap()) .polygon .center(); ctx.canvas.center_on_map_pt(start); let bldgs = Buildings::new(ctx, app, HashSet::new()); let mut txt = Text::new(); txt.add_line(Line(format!("Ready for {}?", level.title)).small_heading()); txt.add_line(format!( "Goal: deliver {} presents", prettyprint_usize(level.goal) )); txt.add_line(format!("Time limit: {}", level.time_limit)); txt.add_appended(vec![ Line("Deliver presents to "), Line("single-family homes").fg(app.cs.residential_building), Line(" and "), Line("apartments").fg(app.session.colors.apartment), ]); txt.add_appended(vec![ Line("Raise your blood sugar by visiting "), Line("stores").fg(app.session.colors.store), ]); let instructions_panel = Panel::new(Widget::col(vec![ txt.into_widget(ctx), Widget::row(vec![ GeomBatch::load_svg_bytes( &ctx.prerender, widgetry::include_labeled_bytes!("../../widgetry/icons/arrow_keys.svg"), ) .into_widget(ctx), Text::from_all(vec![ Line("arrow keys").fg(ctx.style().text_hotkey_color), Line(" to move (or "), Line("WASD").fg(ctx.style().text_hotkey_color), Line(")"), ]) .into_widget(ctx), ]), Widget::row(vec![ Image::from_path("system/assets/tools/mouse.svg").into_widget(ctx), Text::from_all(vec![ Line("mouse scroll wheel or touchpad") .fg(ctx.style().text_hotkey_color), Line(" to zoom in or out"), ]) .into_widget(ctx), ]), Text::from_all(vec![ Line("Escape key").fg(ctx.style().text_hotkey_color), Line(" to pause"), ]) .into_widget(ctx), ])) .aligned(HorizontalAlignment::LeftInset, VerticalAlignment::TopInset) .build(ctx); let draw_start = map_gui::tools::start_marker(ctx, start, 3.0); let current_picks = app .session .upzones_per_level .get(level.title.clone()) .clone(); let upzone_panel = make_upzone_panel(ctx, app, current_picks.len()); Transition::Replace(Box::new(Picker { vehicle_panel: make_vehicle_panel(ctx, app), upzone_panel, instructions_panel, level, bldgs, current_picks, draw_start: ctx.upload(draw_start), })) }), ) } fn randomly_pick_upzones(&mut self, app: &App) { let mut choices = Vec::new(); for (b, state) in &self.bldgs.buildings { if let BldgState::Undelivered(_) = state { if !self.current_picks.contains(b) { choices.push(*b); } } } let mut rng = XorShiftRng::seed_from_u64(42); choices.shuffle(&mut rng); let n = app.session.upzones_unlocked - self.current_picks.len(); assert!(choices.len() >= n); self.current_picks.extend(choices.into_iter().take(n)); } } impl State<App> for Picker { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if app.session.upzones_unlocked > 0 && !app.session.upzones_explained { app.session.upzones_explained = true; return explain_upzoning(ctx); } ctx.canvas_movement(); if ctx.redo_mouseover() { app.current_selection = app.mouseover_unzoomed_buildings(ctx).filter(|id| { match self.bldgs.buildings[&id.as_building()] { BldgState::Undelivered(_) => true, _ => false, } }); } if let Some(ID::Building(b)) = app.current_selection { if ctx.normal_left_click() { if self.current_picks.contains(&b) { self.current_picks.remove(&b); } else if self.current_picks.len() < app.session.upzones_unlocked { self.current_picks.insert(b); } self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } } match self.upzone_panel.event(ctx) { Outcome::Clicked(x) => match x.as_ref() { "Start game" => { app.current_selection = None; app.session .upzones_per_level .set(self.level.title.clone(), self.current_picks.clone()); app.session.save(); return Transition::Replace(Game::new( ctx, app, self.level.clone(), Vehicle::get(&app.session.current_vehicle), self.current_picks.clone().into_iter().collect(), )); } "Randomly choose upzones" => { self.randomly_pick_upzones(app); self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } "Clear upzones" => { self.current_picks.clear(); self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } "help" => { return explain_upzoning(ctx); } _ => unreachable!(), }, _ => {} } match self.vehicle_panel.event(ctx) { Outcome::Clicked(x) => { app.session.current_vehicle = x; self.vehicle_panel = make_vehicle_panel(ctx, app); } _ => {} } app.session.update_music(ctx); Transition::Keep } fn draw(&self, g: &mut GfxCtx, app: &App) { self.vehicle_panel.draw(g); self.upzone_panel.draw(g); self.instructions_panel.draw(g); app.session.music.draw(g); g.redraw(&self.bldgs.draw_all); for b in &self.current_picks { g.draw_polygon(Color::PINK, app.map.get_b(*b).polygon.clone()); } if let Some(ID::Building(b)) = app.current_selection { g.draw_polygon(app.cs.selected, app.map.get_b(b).polygon.clone()); } g.redraw(&self.draw_start); } } fn make_vehicle_panel(ctx: &mut EventCtx, app: &App) -> Panel { let mut buttons = Vec::new(); for name in &app.session.vehicles_unlocked { let vehicle = Vehicle::get(name); let batch = vehicle .animate(ctx.prerender, Time::START_OF_DAY) .scale(10.0); buttons.push( if name == &app.session.current_vehicle { batch .into_widget(ctx) .container() .padding(5) .outline((2.0, Color::WHITE)) } else { let normal = batch.clone().color(RewriteColor::MakeGrayscale); let hovered = batch; ButtonBuilder::new() .custom_batch(normal, ControlState::Default) .custom_batch(hovered, ControlState::Hovered) .build_widget(ctx, name) } .centered_vert(), ); buttons.push(Widget::vert_separator(ctx, 150.0)); } buttons.pop(); let vehicle = Vehicle::get(&app.session.current_vehicle); let (max_speed, max_energy) = Vehicle::max_stats(); Panel::new(Widget::col(vec![ Line("Pick Santa's vehicle") .small_heading() .into_widget(ctx), Widget::row(buttons), Line(&vehicle.name).small_heading().into_widget(ctx), Widget::row(vec![ "Speed:".text_widget(ctx), custom_bar( ctx, app.session.colors.boost, vehicle.speed / max_speed, Text::new(), ) .align_right(), ]), Widget::row(vec![ "Energy:".text_widget(ctx), custom_bar( ctx, app.session.colors.energy, (vehicle.max_energy as f64) / (max_energy as f64), Text::new(), ) .align_right(), ]), ])) .aligned(HorizontalAlignment::RightInset, VerticalAlignment::TopInset) .build(ctx) } fn make_upzone_panel(ctx: &mut EventCtx, app: &App, num_picked: usize) -> Panel { if app.session.upzones_unlocked == 0 { return Panel::new( ctx.style() .btn_solid_primary .text("Start game") .hotkey(Key::Enter) .build_def(ctx) .container(), ) .aligned( HorizontalAlignment::RightInset, VerticalAlignment::BottomInset, ) .build(ctx); } Panel::new(Widget::col(vec![ Widget::row(vec![ Line("Upzoning").small_heading().into_widget(ctx), ctx.style() .btn_plain .icon("system/assets/tools/info.svg") .build_widget(ctx, "help") .align_right(), ]), Widget::row(vec![ Image::from_path("system/assets/tools/mouse.svg").into_widget(ctx), Line("Select the houses you want to turn into stores") .fg(ctx.style().text_hotkey_color) .into_widget(ctx), ]), Widget::row(vec![ "Upzones chosen:".text_widget(ctx), make_bar(ctx, Color::PINK, num_picked, app.session.upzones_unlocked), ]), Widget::row(vec![ ctx.style() .btn_outline .text("Randomly choose upzones") .disabled(num_picked == app.session.upzones_unlocked) .build_def(ctx), ctx.style() .btn_outline .text("Clear upzones") .disabled(num_picked == 0) .build_def(ctx) .align_right(), ]), if num_picked == app.session.upzones_unlocked { ctx.style() .btn_solid_primary .text("Start game") .hotkey(Key::Enter) .build_def(ctx) } else { ctx.style() .btn_solid_primary .text("Finish upzoning before playing") .disabled(true) .build_def(ctx) }, ])) .aligned( HorizontalAlignment::RightInset, VerticalAlignment::BottomInset, ) .build(ctx) } fn explain_upzoning(ctx: &mut EventCtx) -> Transition { Transition::Push(PopupMsg::new( ctx, "Upzoning power unlocked", vec![ "It's hard to deliver to houses far away from shops, isn't it?", "You've gained the power to change the zoning code for a residential building.", "You can now transform a single-family house into a multi-use building,", "with shops on the ground floor, and people living above.", "", "Where should you place the new store?", ], )) }
use std::collections::{BTreeSet, HashSet}; use rand::seq::SliceRandom; use rand::SeedableRng; use rand_xorshift::XorShiftRng; use abstutil::prettyprint_usize; use geom::Time; use map_gui::load::MapLoader; use map_gui::tools::PopupMsg; use map_gui::ID; use map_model::BuildingID; use widgetry::{ ButtonBuilder, Color, ControlState, Drawable, EventCtx, GeomBatch, GfxCtx, HorizontalAlignment, Image, Key, Line, Outcome, Panel, RewriteColor, State, Text, TextExt, VerticalAlignment, Widget, }; use crate::buildings::{BldgState, Buildings}; use crate::game::Game; use crate::levels::Level; use crate::meters::{custom_bar, make_bar}; use crate::vehicles::Vehicle; use crate::{App, Transition}; const ZOOM: f64 = 2.0; pub struct Picker { vehicle_panel: Panel, instructions_panel: Panel, upzone_panel: Panel, level: Level, bldgs: Buildings, current_picks: BTreeSet<BuildingID>, draw_start: Drawable, } impl Picker { pub fn new(ctx: &mut EventCtx, app: &App, level: Level) -> Box<dyn State<App>> { MapLoader::new( ctx, app, level.map.clone(), Box::new(move |ctx, app| { app.session.music.change_song(&level.music); ctx.canvas.cam_zoom = ZOOM; let start = app .map .get_i(app.map.find_i_by_osm_id(level.start).unwrap()) .polygon .center(); ctx.canvas.center_on_map_pt(start); let bldgs = Buildings::new(ctx, app, HashSet::new()); let mut txt = Text::new(); txt.add_line(Line(format!("Ready for {}?", level.title)).small_heading()); txt.add_line(format!( "Goal: deliver {} presents", prettyprint_usize(level.goal) )); txt.add_line(format!("Time limit: {}", level.time_limit)); txt.add_appended(vec![ Line("Deliver presents to "), Line("single-family homes").fg(app.cs.residential_building), Line(" and "), Line("apartments").fg(app.session.colors.apartment), ]); txt.add_appended(vec![ Line("Raise your blood sugar by visiting "), Line("stores").fg(app.session.colors.store), ]); let instructions_panel = Panel::new(Widget::col(vec![ txt.into_widget(ctx), Widget::row(vec![ GeomBatch::load_svg_bytes( &ctx.prerender, widgetry::include_labeled_bytes!("../../widgetry/icons/arrow_keys.svg"), ) .into_widget(ctx), Text::from_all(vec![ Line("arrow keys").fg(ctx.style().text_hotkey_color), Line(" to move (or "), Line("WASD").fg(ctx.style().text_hotkey_color), Line(")"), ]) .into_widget(ctx), ]), Widget::row(vec![ Image::from_path("system/assets/tools/mouse.svg").into_widget(ctx), Text::from_all(vec![ Line("mouse scroll wheel or touchpad") .fg(ctx.style().text_hotkey_color), Line(" to zoom in or out"), ]) .into_widget(ctx), ]), Text::from_all(vec![ Line("Escape key").fg(ctx.style().text_hotkey_color), Line(" to pause"), ]) .into_widget(ctx), ])) .aligned(HorizontalAlignment::LeftInset, VerticalAlignment::TopInset) .build(ctx); let draw_start = map_gui::tools::start_marker(ctx, start, 3.0); let current_picks = app .session .upzones_per_level .get(level.title.clone()) .clone(); let upzone_panel = make_upzone_panel(ctx, app, current_picks.len()); Transition::Replace(Box::new(Picker { vehicle_panel: make_vehicle_panel(ctx, ap
fn randomly_pick_upzones(&mut self, app: &App) { let mut choices = Vec::new(); for (b, state) in &self.bldgs.buildings { if let BldgState::Undelivered(_) = state { if !self.current_picks.contains(b) { choices.push(*b); } } } let mut rng = XorShiftRng::seed_from_u64(42); choices.shuffle(&mut rng); let n = app.session.upzones_unlocked - self.current_picks.len(); assert!(choices.len() >= n); self.current_picks.extend(choices.into_iter().take(n)); } } impl State<App> for Picker { fn event(&mut self, ctx: &mut EventCtx, app: &mut App) -> Transition { if app.session.upzones_unlocked > 0 && !app.session.upzones_explained { app.session.upzones_explained = true; return explain_upzoning(ctx); } ctx.canvas_movement(); if ctx.redo_mouseover() { app.current_selection = app.mouseover_unzoomed_buildings(ctx).filter(|id| { match self.bldgs.buildings[&id.as_building()] { BldgState::Undelivered(_) => true, _ => false, } }); } if let Some(ID::Building(b)) = app.current_selection { if ctx.normal_left_click() { if self.current_picks.contains(&b) { self.current_picks.remove(&b); } else if self.current_picks.len() < app.session.upzones_unlocked { self.current_picks.insert(b); } self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } } match self.upzone_panel.event(ctx) { Outcome::Clicked(x) => match x.as_ref() { "Start game" => { app.current_selection = None; app.session .upzones_per_level .set(self.level.title.clone(), self.current_picks.clone()); app.session.save(); return Transition::Replace(Game::new( ctx, app, self.level.clone(), Vehicle::get(&app.session.current_vehicle), self.current_picks.clone().into_iter().collect(), )); } "Randomly choose upzones" => { self.randomly_pick_upzones(app); self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } "Clear upzones" => { self.current_picks.clear(); self.upzone_panel = make_upzone_panel(ctx, app, self.current_picks.len()); } "help" => { return explain_upzoning(ctx); } _ => unreachable!(), }, _ => {} } match self.vehicle_panel.event(ctx) { Outcome::Clicked(x) => { app.session.current_vehicle = x; self.vehicle_panel = make_vehicle_panel(ctx, app); } _ => {} } app.session.update_music(ctx); Transition::Keep } fn draw(&self, g: &mut GfxCtx, app: &App) { self.vehicle_panel.draw(g); self.upzone_panel.draw(g); self.instructions_panel.draw(g); app.session.music.draw(g); g.redraw(&self.bldgs.draw_all); for b in &self.current_picks { g.draw_polygon(Color::PINK, app.map.get_b(*b).polygon.clone()); } if let Some(ID::Building(b)) = app.current_selection { g.draw_polygon(app.cs.selected, app.map.get_b(b).polygon.clone()); } g.redraw(&self.draw_start); } } fn make_vehicle_panel(ctx: &mut EventCtx, app: &App) -> Panel { let mut buttons = Vec::new(); for name in &app.session.vehicles_unlocked { let vehicle = Vehicle::get(name); let batch = vehicle .animate(ctx.prerender, Time::START_OF_DAY) .scale(10.0); buttons.push( if name == &app.session.current_vehicle { batch .into_widget(ctx) .container() .padding(5) .outline((2.0, Color::WHITE)) } else { let normal = batch.clone().color(RewriteColor::MakeGrayscale); let hovered = batch; ButtonBuilder::new() .custom_batch(normal, ControlState::Default) .custom_batch(hovered, ControlState::Hovered) .build_widget(ctx, name) } .centered_vert(), ); buttons.push(Widget::vert_separator(ctx, 150.0)); } buttons.pop(); let vehicle = Vehicle::get(&app.session.current_vehicle); let (max_speed, max_energy) = Vehicle::max_stats(); Panel::new(Widget::col(vec![ Line("Pick Santa's vehicle") .small_heading() .into_widget(ctx), Widget::row(buttons), Line(&vehicle.name).small_heading().into_widget(ctx), Widget::row(vec![ "Speed:".text_widget(ctx), custom_bar( ctx, app.session.colors.boost, vehicle.speed / max_speed, Text::new(), ) .align_right(), ]), Widget::row(vec![ "Energy:".text_widget(ctx), custom_bar( ctx, app.session.colors.energy, (vehicle.max_energy as f64) / (max_energy as f64), Text::new(), ) .align_right(), ]), ])) .aligned(HorizontalAlignment::RightInset, VerticalAlignment::TopInset) .build(ctx) } fn make_upzone_panel(ctx: &mut EventCtx, app: &App, num_picked: usize) -> Panel { if app.session.upzones_unlocked == 0 { return Panel::new( ctx.style() .btn_solid_primary .text("Start game") .hotkey(Key::Enter) .build_def(ctx) .container(), ) .aligned( HorizontalAlignment::RightInset, VerticalAlignment::BottomInset, ) .build(ctx); } Panel::new(Widget::col(vec![ Widget::row(vec![ Line("Upzoning").small_heading().into_widget(ctx), ctx.style() .btn_plain .icon("system/assets/tools/info.svg") .build_widget(ctx, "help") .align_right(), ]), Widget::row(vec![ Image::from_path("system/assets/tools/mouse.svg").into_widget(ctx), Line("Select the houses you want to turn into stores") .fg(ctx.style().text_hotkey_color) .into_widget(ctx), ]), Widget::row(vec![ "Upzones chosen:".text_widget(ctx), make_bar(ctx, Color::PINK, num_picked, app.session.upzones_unlocked), ]), Widget::row(vec![ ctx.style() .btn_outline .text("Randomly choose upzones") .disabled(num_picked == app.session.upzones_unlocked) .build_def(ctx), ctx.style() .btn_outline .text("Clear upzones") .disabled(num_picked == 0) .build_def(ctx) .align_right(), ]), if num_picked == app.session.upzones_unlocked { ctx.style() .btn_solid_primary .text("Start game") .hotkey(Key::Enter) .build_def(ctx) } else { ctx.style() .btn_solid_primary .text("Finish upzoning before playing") .disabled(true) .build_def(ctx) }, ])) .aligned( HorizontalAlignment::RightInset, VerticalAlignment::BottomInset, ) .build(ctx) } fn explain_upzoning(ctx: &mut EventCtx) -> Transition { Transition::Push(PopupMsg::new( ctx, "Upzoning power unlocked", vec![ "It's hard to deliver to houses far away from shops, isn't it?", "You've gained the power to change the zoning code for a residential building.", "You can now transform a single-family house into a multi-use building,", "with shops on the ground floor, and people living above.", "", "Where should you place the new store?", ], )) }
p), upzone_panel, instructions_panel, level, bldgs, current_picks, draw_start: ctx.upload(draw_start), })) }), ) }
function_block-function_prefixed
[ { "content": "pub fn custom_bar(ctx: &mut EventCtx, filled_color: Color, pct_full: f64, txt: Text) -> Widget {\n\n let total_width = 300.0;\n\n let height = 32.0;\n\n let radius = 4.0;\n\n\n\n let mut batch = GeomBatch::new();\n\n // Background\n\n batch.push(\n\n Color::hex(\"#666666\"),\n\n Polygon::rounded_rectangle(total_width, height, radius),\n\n );\n\n // Foreground\n\n if let Some(poly) = Polygon::maybe_rounded_rectangle(pct_full * total_width, height, radius) {\n\n batch.push(filled_color, poly);\n\n }\n\n // Text\n\n let label = txt.render_autocropped(ctx);\n\n let dims = label.get_dims();\n\n batch.append(label.translate(10.0, height / 2.0 - dims.height / 2.0));\n\n batch.into_widget(ctx)\n\n}\n\n\n", "file_path": "santa/src/meters.rs", "rank": 0, "score": 569339.9537906479 }, { "content": "fn build_panel(ctx: &mut EventCtx, app: &App, start: &Building, isochrone: &Isochrone) -> Panel {\n\n let mut rows = Vec::new();\n\n\n\n rows.push(\n\n Line(\"15-minute neighborhood explorer\")\n\n .small_heading()\n\n .into_widget(ctx),\n\n );\n\n\n\n rows.push(\n\n ctx.style()\n\n .btn_popup_icon_text(\n\n \"system/assets/tools/map.svg\",\n\n nice_map_name(app.map.get_name()),\n\n )\n\n .hotkey(lctrl(Key::L))\n\n .build_widget(ctx, \"change map\"),\n\n );\n\n\n\n rows.push(\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 1, "score": 489676.6936279838 }, { "content": "pub fn info(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, app, details, id, Tab::BldgInfo(id)),\n\n info_body(ctx, app, details, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/building.rs", "rank": 2, "score": 473907.9025242169 }, { "content": "pub fn people(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, app, details, id, Tab::BldgPeople(id)),\n\n people_body(ctx, app, details, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/building.rs", "rank": 3, "score": 473907.9025242169 }, { "content": "// TODO Preview the map, add padding, add the linear gradient...\n\nfn locked_level(ctx: &mut EventCtx, app: &App, level: &Level, idx: usize) -> Widget {\n\n let mut batch = level_btn(ctx, app, level, idx);\n\n let hitbox = batch.get_bounds().get_rectangle();\n\n let center = hitbox.center();\n\n batch.push(app.cs.fade_map_dark, hitbox);\n\n batch.append(GeomBatch::load_svg(ctx, \"system/assets/tools/locked.svg\").centered_on(center));\n\n batch.into_widget(ctx)\n\n}\n\n\n", "file_path": "santa/src/title.rs", "rank": 5, "score": 462926.648788841 }, { "content": "fn unlocked_level(ctx: &mut EventCtx, app: &App, level: &Level, idx: usize) -> Widget {\n\n let normal = level_btn(ctx, app, level, idx);\n\n let hovered = normal\n\n .clone()\n\n .color(RewriteColor::Change(Color::WHITE, Color::WHITE.alpha(0.6)));\n\n\n\n ButtonBuilder::new()\n\n .custom_batch(normal, ControlState::Default)\n\n .custom_batch(hovered, ControlState::Hovered)\n\n .build_widget(ctx, &level.title)\n\n}\n\n\n", "file_path": "santa/src/title.rs", "rank": 6, "score": 462921.0513896537 }, { "content": "fn make_tool_panel(ctx: &mut EventCtx, app: &App) -> Widget {\n\n let buttons = ctx\n\n .style()\n\n .btn_floating\n\n .btn()\n\n .image_dims(ScreenDims::square(20.0))\n\n // the default transparent button background is jarring for these buttons which are floating\n\n // in a transparent panel.\n\n .bg_color(app.cs.inner_panel_bg, ControlState::Default)\n\n .padding(8);\n\n\n\n Widget::col(vec![\n\n (if ctx.canvas.cam_zoom >= app.opts.min_zoom_for_detail {\n\n buttons\n\n .clone()\n\n .image_path(\"system/assets/minimap/zoom_out_fully.svg\")\n\n .build_widget(ctx, \"zoom out fully\")\n\n } else {\n\n buttons\n\n .clone()\n", "file_path": "game/src/sandbox/minimap.rs", "rank": 7, "score": 446041.8322623292 }, { "content": "pub fn apply_map_edits(ctx: &mut EventCtx, app: &mut App, edits: MapEdits) {\n\n let mut timer = Timer::new(\"apply map edits\");\n\n\n\n let (roads_changed, turns_deleted, turns_added, mut modified_intersections) =\n\n app.primary.map.must_apply_edits(edits);\n\n\n\n if !roads_changed.is_empty() || !modified_intersections.is_empty() {\n\n app.primary\n\n .draw_map\n\n .draw_all_unzoomed_roads_and_intersections =\n\n DrawMap::regenerate_unzoomed_layer(&app.primary.map, &app.cs, ctx, &mut timer);\n\n }\n\n\n\n for r in roads_changed {\n\n let road = app.primary.map.get_r(r);\n\n app.primary.draw_map.roads[r.0].clear_rendering();\n\n\n\n // An edit to one lane potentially affects markings in all lanes in the same road, because\n\n // of one-way markings, driving lines, etc.\n\n for l in road.all_lanes() {\n", "file_path": "game/src/edit/mod.rs", "rank": 8, "score": 438849.3913569879 }, { "content": "pub fn warp_to_id(ctx: &mut EventCtx, app: &mut App, input: &str) -> Transition {\n\n if let Some(t) = inner_warp_to_id(ctx, app, input) {\n\n t\n\n } else {\n\n Transition::Replace(PopupMsg::new(\n\n ctx,\n\n \"Bad warp ID\",\n\n vec![format!(\"{} isn't a valid ID\", input)],\n\n ))\n\n }\n\n}\n\n\n", "file_path": "game/src/common/warp.rs", "rank": 10, "score": 424105.2074829749 }, { "content": "fn info_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let b = app.primary.map.get_b(id);\n\n\n\n let mut kv = Vec::new();\n\n\n\n kv.push((\"Address\", b.address.clone()));\n\n if let Some(ref names) = b.name {\n\n kv.push((\"Name\", names.get(app.opts.language.as_ref()).to_string()));\n\n }\n\n if app.opts.dev {\n\n kv.push((\"OSM ID\", format!(\"{}\", b.orig_id.inner())));\n\n }\n\n\n\n let num_spots = b.num_parking_spots();\n\n if app.primary.sim.infinite_parking() {\n\n kv.push((\n\n \"Parking\",\n\n format!(\n", "file_path": "game/src/info/building.rs", "rank": 11, "score": 423560.19634671335 }, { "content": "fn people_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BuildingID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n // Two caveats about these counts:\n\n // 1) A person might use multiple modes through the day, but this just picks a single category.\n\n // 2) Only people currently in the building currently are counted, whether or not that's their\n\n // home.\n\n let mut drivers = 0;\n\n let mut cyclists = 0;\n\n let mut others = 0;\n\n\n\n let mut ppl: Vec<(Time, Widget)> = Vec::new();\n\n for p in app.primary.sim.bldg_to_people(id) {\n\n let person = app.primary.sim.get_person(p);\n\n\n\n let mut has_car = false;\n\n let mut has_bike = false;\n\n for vehicle in &person.vehicles {\n\n if vehicle.vehicle_type == VehicleType::Car {\n\n has_car = true;\n", "file_path": "game/src/info/building.rs", "rank": 12, "score": 423560.19634671335 }, { "content": "pub fn make_bar(ctx: &mut EventCtx, filled_color: Color, value: usize, max: usize) -> Widget {\n\n let pct_full = if max == 0 {\n\n 0.0\n\n } else {\n\n (value as f64) / (max as f64)\n\n };\n\n let txt = Text::from(format!(\n\n \"{} / {}\",\n\n prettyprint_usize(value),\n\n prettyprint_usize(max)\n\n ));\n\n custom_bar(ctx, filled_color, pct_full, txt)\n\n}\n", "file_path": "santa/src/meters.rs", "rank": 13, "score": 423036.5975528937 }, { "content": "fn make_panel(ctx: &mut EventCtx, app: &App) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Widget::row(vec![\n\n Line(\"Commute map by block\")\n\n .small_heading()\n\n .into_widget(ctx),\n\n ctx.style().btn_close_widget(ctx),\n\n ]),\n\n Toggle::choice(ctx, \"from / to this block\", \"from\", \"to\", Key::Space, true),\n\n Toggle::switch(ctx, \"include borders\", None, true),\n\n Widget::row(vec![\n\n \"Departing from:\".text_widget(ctx).margin_right(20),\n\n Slider::area(ctx, 0.15 * ctx.canvas.window_width, 0.0).named(\"depart from\"),\n\n ]),\n\n Widget::row(vec![\n\n \"Departing until:\".text_widget(ctx).margin_right(20),\n\n Slider::area(ctx, 0.15 * ctx.canvas.window_width, 1.0).named(\"depart until\"),\n\n ]),\n\n checkbox_per_mode(ctx, app, &TripMode::all().into_iter().collect()),\n\n ColorLegend::gradient(ctx, &app.cs.good_to_bad_red, vec![\"0\", \"0\"]).named(\"scale\"),\n\n \"None selected\".text_widget(ctx).named(\"current\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Right, VerticalAlignment::Top)\n\n .build(ctx)\n\n}\n", "file_path": "game/src/sandbox/dashboards/commuter.rs", "rank": 14, "score": 422025.46045816457 }, { "content": "fn level_btn(ctx: &mut EventCtx, app: &App, level: &Level, idx: usize) -> GeomBatch {\n\n let mut txt = Text::new();\n\n txt.add_line(Line(format!(\"LEVEL {}\", idx + 1)).small_heading());\n\n txt.add_line(Line(&level.title).small_heading());\n\n txt.add_line(&level.description);\n\n let batch = txt.wrap_to_pct(ctx, 15).render_autocropped(ctx);\n\n\n\n // Add padding\n\n let (mut batch, hitbox) = batch\n\n .batch()\n\n .container()\n\n .padding(EdgeInsets {\n\n top: 20.0,\n\n bottom: 20.0,\n\n left: 10.0,\n\n right: 10.0,\n\n })\n\n .to_geom(ctx, None);\n\n batch.unshift(app.cs.unzoomed_bike, hitbox);\n\n batch\n\n}\n\n\n", "file_path": "santa/src/title.rs", "rank": 15, "score": 421960.0041776416 }, { "content": "fn inner_warp_to_id(ctx: &mut EventCtx, app: &mut App, line: &str) -> Option<Transition> {\n\n if line.is_empty() {\n\n return None;\n\n }\n\n if line == \"j\" {\n\n if let Some((pt, zoom)) = app.primary.last_warped_from {\n\n return Some(Transition::Replace(Warping::new(\n\n ctx,\n\n pt,\n\n Some(zoom),\n\n None,\n\n &mut app.primary,\n\n )));\n\n }\n\n return None;\n\n }\n\n\n\n let id = match usize::from_str_radix(&line[1..line.len()], 10) {\n\n Ok(idx) => match line.chars().next().unwrap() {\n\n 'r' => {\n", "file_path": "game/src/common/warp.rs", "rank": 16, "score": 420370.4899626606 }, { "content": "pub fn stop(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusStopID) -> Widget {\n\n let header = Widget::row(vec![\n\n Line(\"Bus stop\").small_heading().into_widget(ctx),\n\n header_btns(ctx),\n\n ]);\n\n\n\n Widget::custom_col(vec![header, stop_body(ctx, app, details, id).tab_body(ctx)])\n\n}\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 17, "score": 420008.65921408427 }, { "content": "pub fn bus_status(ctx: &mut EventCtx, app: &App, details: &mut Details, id: CarID) -> Widget {\n\n Widget::custom_col(vec![\n\n bus_header(ctx, app, details, id, Tab::BusStatus(id)),\n\n bus_status_body(ctx, app, details, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 18, "score": 420008.65921408427 }, { "content": "pub fn route(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusRouteID) -> Widget {\n\n let header = {\n\n let map = &app.primary.map;\n\n let route = map.get_br(id);\n\n\n\n Widget::row(vec![\n\n Line(format!(\"Route {}\", route.short_name))\n\n .small_heading()\n\n .into_widget(ctx),\n\n header_btns(ctx),\n\n ])\n\n };\n\n\n\n Widget::custom_col(vec![\n\n header,\n\n route_body(ctx, app, details, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 19, "score": 420008.65921408427 }, { "content": "pub fn info(ctx: &mut EventCtx, app: &App, details: &mut Details, id: ParkingLotID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, details, id, Tab::ParkingLot(id)),\n\n info_body(ctx, app, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/parking_lot.rs", "rank": 20, "score": 415576.6176443477 }, { "content": "pub fn area(ctx: &EventCtx, app: &App, _: &mut Details, id: AreaID) -> Widget {\n\n let header = Widget::row(vec![\n\n Line(id.to_string()).small_heading().into_widget(ctx),\n\n header_btns(ctx),\n\n ]);\n\n\n\n Widget::custom_col(vec![header, area_body(ctx, app, id).tab_body(ctx)])\n\n}\n\n\n", "file_path": "game/src/info/debug.rs", "rank": 21, "score": 415242.9451770718 }, { "content": "// TODO Kinda misnomer\n\npub fn tool_panel(ctx: &mut EventCtx) -> Panel {\n\n Panel::new(Widget::row(vec![\n\n ctx.style()\n\n .btn_plain\n\n .icon(\"system/assets/tools/home.svg\")\n\n .hotkey(Key::Escape)\n\n .build_widget(ctx, \"back\"),\n\n ctx.style()\n\n .btn_plain\n\n .icon(\"system/assets/tools/settings.svg\")\n\n .build_widget(ctx, \"settings\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Left, VerticalAlignment::BottomAboveOSD)\n\n .build(ctx)\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 22, "score": 415002.5981139481 }, { "content": "fn make_topcenter(ctx: &mut EventCtx, app: &App) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Line(\"Editing map\")\n\n .small_heading()\n\n .into_widget(ctx)\n\n .centered_horiz(),\n\n ctx.style()\n\n .btn_solid_primary\n\n .text(format!(\n\n \"Finish & resume from {}\",\n\n app.primary\n\n .suspended_sim\n\n .as_ref()\n\n .unwrap()\n\n .time()\n\n .ampm_tostring()\n\n ))\n\n .hotkey(Key::Escape)\n\n .build_widget(ctx, \"finish editing\"),\n\n ]))\n\n .aligned(HorizontalAlignment::Center, VerticalAlignment::Top)\n\n .build(ctx)\n\n}\n\n\n", "file_path": "game/src/edit/mod.rs", "rank": 23, "score": 412389.20619312034 }, { "content": "fn make_changelist(ctx: &mut EventCtx, app: &App) -> Panel {\n\n // TODO Support redo. Bit harder here to reset the redo_stack when the edits\n\n // change, because nested other places modify it too.\n\n let edits = app.primary.map.get_edits();\n\n let mut col = vec![\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_outline\n\n .popup(&edits.edits_name)\n\n .hotkey(lctrl(Key::P))\n\n .build_widget(ctx, \"manage proposals\"),\n\n \"autosaved\"\n\n .text_widget(ctx)\n\n .container()\n\n .padding(10)\n\n .bg(Color::hex(\"#5D9630\")),\n\n ]),\n\n ColorLegend::row(\n\n ctx,\n\n app.cs.edits_layer,\n", "file_path": "game/src/edit/mod.rs", "rank": 24, "score": 412389.20619312034 }, { "content": "fn make_controls(ctx: &mut EventCtx, app: &App, opts: &Options, legend: Option<Widget>) -> Panel {\n\n let model = app.primary.sim.get_pandemic_model().unwrap();\n\n let pct = 100.0 / (model.count_total() as f64);\n\n\n\n let mut col = vec![\n\n header(ctx, \"Pandemic model\"),\n\n Text::from_multiline(vec![\n\n Line(format!(\n\n \"{} Sane ({:.1}%)\",\n\n prettyprint_usize(model.count_sane()),\n\n (model.count_sane() as f64) * pct\n\n )),\n\n Line(format!(\n\n \"{} Exposed ({:.1}%)\",\n\n prettyprint_usize(model.count_exposed()),\n\n (model.count_exposed() as f64) * pct\n\n )),\n\n Line(format!(\n\n \"{} Infected ({:.1}%)\",\n\n prettyprint_usize(model.count_infected()),\n", "file_path": "game/src/layer/pandemic.rs", "rank": 25, "score": 411422.06639360124 }, { "content": "fn make_controls(ctx: &mut EventCtx, app: &App, opts: &Options, legend: Option<Widget>) -> Panel {\n\n let (total_ppl, ppl_in_bldg, ppl_off_map) = app.primary.sim.num_ppl();\n\n\n\n let mut col = vec![\n\n header(\n\n ctx,\n\n &format!(\"Population: {}\", prettyprint_usize(total_ppl)),\n\n ),\n\n Widget::row(vec![\n\n Widget::row(vec![\n\n Image::from_path(\"system/assets/tools/home.svg\").into_widget(ctx),\n\n Line(prettyprint_usize(ppl_in_bldg))\n\n .small()\n\n .into_widget(ctx),\n\n ]),\n\n Line(format!(\"Off-map: {}\", prettyprint_usize(ppl_off_map)))\n\n .small()\n\n .into_widget(ctx),\n\n ])\n\n .centered(),\n", "file_path": "game/src/layer/population.rs", "rank": 26, "score": 411422.0663936013 }, { "content": "pub fn info(ctx: &EventCtx, app: &App, details: &mut Details, id: IntersectionID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, app, details, id, Tab::IntersectionInfo(id)),\n\n info_body(ctx, app, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/intersection.rs", "rank": 27, "score": 410261.73831501626 }, { "content": "pub fn debug(ctx: &EventCtx, app: &App, details: &mut Details, id: LaneID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, app, details, id, Tab::LaneDebug(id)),\n\n debug_body(ctx, app, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/lane.rs", "rank": 28, "score": 410261.7383150162 }, { "content": "pub fn info(ctx: &EventCtx, app: &App, details: &mut Details, id: LaneID) -> Widget {\n\n Widget::custom_col(vec![\n\n header(ctx, app, details, id, Tab::LaneInfo(id)),\n\n info_body(ctx, app, id).tab_body(ctx),\n\n ])\n\n}\n\n\n", "file_path": "game/src/info/lane.rs", "rank": 29, "score": 410261.7383150162 }, { "content": "pub fn execute(ctx: &mut EventCtx, app: &mut App, id: ID, action: &str) -> Transition {\n\n let mut tut = app.session.tutorial.as_mut().unwrap();\n\n let response = match (id, action.as_ref()) {\n\n (ID::Car(c), \"draw WASH ME\") => {\n\n let is_parked = app\n\n .primary\n\n .sim\n\n .agent_to_trip(AgentID::Car(ESCORT))\n\n .is_none();\n\n if c == ESCORT {\n\n if is_parked {\n\n tut.prank_done = true;\n\n PopupMsg::new(\n\n ctx,\n\n \"Prank in progress\",\n\n vec![\"You quickly scribble on the window...\"],\n\n )\n\n } else {\n\n PopupMsg::new(\n\n ctx,\n", "file_path": "game/src/sandbox/gameplay/tutorial.rs", "rank": 30, "score": 402441.4425561583 }, { "content": "pub fn execute(ctx: &mut EventCtx, app: &mut App, id: ID, action: &str) -> Transition {\n\n match (id, action.as_ref()) {\n\n (ID::Building(b), \"start a trip here\") => {\n\n Transition::Push(spawner::AgentSpawner::new(ctx, app, Some(b)))\n\n }\n\n (ID::Intersection(id), \"spawn agents here\") => {\n\n spawn_agents_around(id, app);\n\n Transition::Keep\n\n }\n\n _ => unreachable!(),\n\n }\n\n}\n", "file_path": "game/src/sandbox/gameplay/freeform/mod.rs", "rank": 31, "score": 397834.10310733505 }, { "content": "fn header(ctx: &EventCtx, app: &App, details: &mut Details, id: BuildingID, tab: Tab) -> Widget {\n\n let mut rows = vec![];\n\n\n\n rows.push(Widget::row(vec![\n\n Line(id.to_string()).small_heading().into_widget(ctx),\n\n header_btns(ctx),\n\n ]));\n\n\n\n rows.push(make_tabs(\n\n ctx,\n\n &mut details.hyperlinks,\n\n tab,\n\n vec![(\"Info\", Tab::BldgInfo(id)), (\"People\", Tab::BldgPeople(id))],\n\n ));\n\n\n\n draw_occupants(details, app, id, None);\n\n // TODO Draw cars parked inside?\n\n\n\n Widget::custom_col(rows)\n\n}\n\n\n", "file_path": "game/src/info/building.rs", "rank": 32, "score": 392120.7946733018 }, { "content": "fn launch(ctx: &mut EventCtx, app: &App, edits: PermanentMapEdits) -> Transition {\n\n #[cfg(not(target_arch = \"wasm32\"))]\n\n {\n\n if !abstio::file_exists(edits.map_name.path()) {\n\n return map_gui::tools::prompt_to_download_missing_data(ctx, edits.map_name.clone());\n\n }\n\n }\n\n\n\n Transition::Push(MapLoader::new(\n\n ctx,\n\n app,\n\n edits.map_name.clone(),\n\n Box::new(move |ctx, app| {\n\n // Apply edits before setting up the sandbox, for simplicity\n\n let maybe_err = ctx.loading_screen(\"apply edits\", |ctx, mut timer| {\n\n match edits.to_edits(&app.primary.map) {\n\n Ok(edits) => {\n\n apply_map_edits(ctx, app, edits);\n\n app.primary\n\n .map\n", "file_path": "game/src/pregame/proposals.rs", "rank": 33, "score": 390393.72257592436 }, { "content": "/// Make it clear the map can't be interacted with right now.\n\npub fn grey_out_map(g: &mut GfxCtx, app: &dyn AppLike) {\n\n g.fork_screenspace();\n\n // TODO - OSD height\n\n g.draw_polygon(\n\n app.cs().fade_map_dark,\n\n Polygon::rectangle(g.canvas.window_width, g.canvas.window_height),\n\n );\n\n g.unfork();\n\n}\n\n\n", "file_path": "map_gui/src/tools/mod.rs", "rank": 34, "score": 389833.71310715866 }, { "content": "fn contingency_table(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let total_width = 500.0;\n\n let total_height = 300.0;\n\n\n\n let points = filter.get_trips(app);\n\n if points.is_empty() {\n\n return Widget::nothing();\n\n }\n\n\n\n // bucket by trip duration _before_ changes\n\n let num_buckets = 10;\n\n let (_, endpts) = points\n\n .iter()\n\n .map(|(b, _a)| b)\n\n .max()\n\n .unwrap()\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 35, "score": 380969.43240500987 }, { "content": "fn schedule_body(ctx: &mut EventCtx, app: &App, id: PersonID) -> Widget {\n\n let mut rows = vec![];\n\n let person = app.primary.sim.get_person(id);\n\n let mut rng = XorShiftRng::seed_from_u64(id.0 as u64);\n\n\n\n // TODO Proportional 24-hour timeline would be easier to understand\n\n let mut last_t = Time::START_OF_DAY;\n\n for t in &person.trips {\n\n let trip = app.primary.sim.trip_info(*t);\n\n let at = match trip.start {\n\n TripEndpoint::Bldg(b) => {\n\n let b = app.primary.map.get_b(b);\n\n if b.amenities.is_empty() {\n\n b.address.clone()\n\n } else {\n\n let list = b\n\n .amenities\n\n .iter()\n\n .map(|a| a.names.get(app.opts.language.as_ref()))\n\n .collect::<Vec<_>>();\n", "file_path": "game/src/info/person.rs", "rank": 36, "score": 380969.43240500987 }, { "content": "fn scatter_plot(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let points = filter.get_trips(app);\n\n if points.is_empty() {\n\n return Widget::nothing();\n\n }\n\n\n\n Widget::col(vec![\n\n Line(\"Trip time before and after\")\n\n .small_heading()\n\n .into_widget(ctx),\n\n CompareTimes::new(\n\n ctx,\n\n format!(\n\n \"Trip time before \\\"{}\\\"\",\n\n app.primary.map.get_edits().edits_name\n\n ),\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 37, "score": 380969.43240500987 }, { "content": "fn summary_boxes(ctx: &mut EventCtx, app: &App, filter: &Filter) -> Widget {\n\n if app.has_prebaked().is_none() {\n\n return Widget::nothing();\n\n }\n\n\n\n let mut num_same = 0;\n\n let mut num_faster = 0;\n\n let mut num_slower = 0;\n\n let mut sum_faster = Duration::ZERO;\n\n let mut sum_slower = Duration::ZERO;\n\n for (_, b, a, mode) in app\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .both_finished_trips(app.primary.sim.time(), app.prebaked())\n\n {\n\n if !filter.modes.contains(&mode) {\n\n continue;\n\n }\n\n let same = if let Some(pct) = filter.changes_pct {\n", "file_path": "game/src/sandbox/dashboards/summaries.rs", "rank": 38, "score": 380969.43240500987 }, { "content": "fn make_elevation(ctx: &EventCtx, color: Color, walking: bool, path: &Path, map: &Map) -> Widget {\n\n let mut pts: Vec<(Distance, Distance)> = Vec::new();\n\n let mut dist = Distance::ZERO;\n\n for step in path.get_steps() {\n\n if let PathStep::Turn(t) = step {\n\n pts.push((dist, map.get_i(t.parent).elevation));\n\n }\n\n dist += step.as_traversable().length(map);\n\n }\n\n // TODO Show roughly where we are in the trip; use distance covered by current path for this\n\n LinePlot::new(\n\n ctx,\n\n vec![Series {\n\n label: if walking {\n\n \"Elevation for walking\"\n\n } else {\n\n \"Elevation for biking\"\n\n }\n\n .to_string(),\n\n color,\n\n pts,\n\n }],\n\n PlotOptions::fixed(),\n\n )\n\n}\n\n\n", "file_path": "game/src/info/trip.rs", "rank": 39, "score": 377830.3095527984 }, { "content": "fn draw_banned_turns(ctx: &mut EventCtx, app: &App) -> Drawable {\n\n let mut batch = GeomBatch::new();\n\n let map = &app.primary.map;\n\n for i in map.all_intersections() {\n\n let mut pairs: HashSet<(RoadID, RoadID)> = HashSet::new();\n\n // Don't call out one-ways, so use incoming/outgoing roads, and just for cars.\n\n for l1 in i.get_incoming_lanes(map, PathConstraints::Car) {\n\n for l2 in i.get_outgoing_lanes(map, PathConstraints::Car) {\n\n pairs.insert((map.get_l(l1).parent, map.get_l(l2).parent));\n\n }\n\n }\n\n for t in &i.turns {\n\n let r1 = map.get_l(t.src).parent;\n\n let r2 = map.get_l(t.dst).parent;\n\n pairs.remove(&(r1, r2));\n\n }\n\n\n\n for (r1, r2) in pairs {\n\n if let Ok(pl) = PolyLine::new(vec![\n\n map.get_r(r1).center_pts.middle(),\n", "file_path": "game/src/debug/mod.rs", "rank": 40, "score": 377638.2121077058 }, { "content": "fn traffic_signal_body(ctx: &mut EventCtx, app: &App, id: IntersectionID) -> Widget {\n\n let mut rows = vec![];\n\n // Slightly inaccurate -- the turn rendering may slightly exceed the intersection polygon --\n\n // but this is close enough.\n\n let bounds = app.primary.map.get_i(id).polygon.get_bounds();\n\n // Pick a zoom so that we fit a fixed width in pixels\n\n let zoom = 150.0 / bounds.width();\n\n let bbox = Polygon::rectangle(zoom * bounds.width(), zoom * bounds.height());\n\n\n\n let signal = app.primary.map.get_traffic_signal(id);\n\n {\n\n let mut txt = Text::new();\n\n txt.add_line(Line(format!(\"{} stages\", signal.stages.len())).small_heading());\n\n txt.add_line(format!(\"Signal offset: {}\", signal.offset));\n\n {\n\n let mut total = Duration::ZERO;\n\n for s in &signal.stages {\n\n total += s.stage_type.simple_duration();\n\n }\n\n // TODO Say \"normally\" or something?\n", "file_path": "game/src/info/intersection.rs", "rank": 41, "score": 376645.06013213407 }, { "content": "fn current_demand_body(ctx: &mut EventCtx, app: &App, id: IntersectionID) -> Widget {\n\n let mut rows = vec![];\n\n let mut total_demand = 0;\n\n let mut demand_per_movement: Vec<(&PolyLine, usize)> = Vec::new();\n\n for m in app.primary.map.get_traffic_signal(id).movements.values() {\n\n let demand = app\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .demand\n\n .get(&m.id)\n\n .cloned()\n\n .unwrap_or(0);\n\n if demand > 0 {\n\n total_demand += demand;\n\n demand_per_movement.push((&m.geom, demand));\n\n }\n\n }\n\n\n\n let mut batch = GeomBatch::new();\n", "file_path": "game/src/info/intersection.rs", "rank": 42, "score": 376645.06013213407 }, { "content": "/// Creates the top row for any layer panel.\n\npub fn header(ctx: &mut EventCtx, name: &str) -> Widget {\n\n Widget::row(vec![\n\n Image::from_path(\"system/assets/tools/layers.svg\")\n\n .into_widget(ctx)\n\n .centered_vert(),\n\n name.text_widget(ctx).centered_vert(),\n\n ctx.style().btn_close_widget(ctx),\n\n ])\n\n}\n\n\n\npub const PANEL_PLACEMENT: (HorizontalAlignment, VerticalAlignment) = (\n\n HorizontalAlignment::Percent(0.02),\n\n VerticalAlignment::Percent(0.2),\n\n);\n", "file_path": "game/src/layer/mod.rs", "rank": 43, "score": 376278.0143478558 }, { "content": "fn search_osm(filter: String, ctx: &mut EventCtx, app: &mut App) -> Transition {\n\n let mut num_matches = 0;\n\n let mut batch = GeomBatch::new();\n\n\n\n // TODO Case insensitive\n\n let map = &app.primary.map;\n\n let color = Color::RED.alpha(0.8);\n\n for r in map.all_roads() {\n\n if r.osm_tags\n\n .inner()\n\n .iter()\n\n .any(|(k, v)| format!(\"{} = {}\", k, v).contains(&filter))\n\n {\n\n num_matches += 1;\n\n batch.push(color, r.get_thick_polygon(map));\n\n }\n\n }\n\n for a in map.all_areas() {\n\n if a.osm_tags\n\n .inner()\n", "file_path": "game/src/debug/mod.rs", "rank": 44, "score": 374371.6257351454 }, { "content": "fn bio_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: PersonID) -> Widget {\n\n let mut rows = vec![];\n\n let person = app.primary.sim.get_person(id);\n\n let mut rng = XorShiftRng::seed_from_u64(id.0 as u64);\n\n\n\n let mut svg_data = Vec::new();\n\n svg_face::generate_face(&mut svg_data, &mut rng).unwrap();\n\n let batch = GeomBatch::load_svg_bytes_uncached(&svg_data).autocrop();\n\n let dims = batch.get_dims();\n\n let batch = batch.scale((200.0 / dims.width).min(200.0 / dims.height));\n\n rows.push(batch.into_widget(ctx).centered_horiz());\n\n\n\n let nickname = petname::Petnames::default().generate(&mut rng, 2, \" \");\n\n let age = rng.gen_range(5..100);\n\n\n\n let mut table = vec![(\"Nickname\", nickname), (\"Age\", age.to_string())];\n\n if app.opts.dev {\n\n table.push((\"Debug ID\", format!(\"{:?}\", person.orig_id)));\n\n }\n\n rows.extend(make_table(ctx, table));\n", "file_path": "game/src/info/person.rs", "rank": 45, "score": 374263.3892757745 }, { "content": "fn info_body(ctx: &mut EventCtx, app: &App, id: ParkingLotID) -> Widget {\n\n let mut rows = vec![];\n\n let pl = app.primary.map.get_pl(id);\n\n let capacity = pl.capacity();\n\n\n\n rows.push(\n\n format!(\n\n \"{} / {} spots available\",\n\n prettyprint_usize(app.primary.sim.get_free_lot_spots(pl.id).len()),\n\n prettyprint_usize(capacity)\n\n )\n\n .text_widget(ctx),\n\n );\n\n\n\n let mut series = vec![Series {\n\n label: format!(\"After \\\"{}\\\"\", app.primary.map.get_edits().edits_name),\n\n color: app.cs.after_changes,\n\n pts: app.primary.sim.get_analytics().parking_lot_availability(\n\n app.primary.sim.time(),\n\n pl.id,\n", "file_path": "game/src/info/parking_lot.rs", "rank": 46, "score": 372496.91472054843 }, { "content": "fn route_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusRouteID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let map = &app.primary.map;\n\n let route = map.get_br(id);\n\n rows.push(\n\n Text::from(&route.full_name)\n\n .wrap_to_pct(ctx, 20)\n\n .into_widget(ctx),\n\n );\n\n\n\n if app.opts.dev {\n\n rows.push(\n\n ctx.style()\n\n .btn_outline\n\n .text(\"Open OSM relation\")\n\n .build_widget(ctx, format!(\"open {}\", route.osm_rel_id)),\n\n );\n\n }\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 47, "score": 370421.4107116004 }, { "content": "fn stop_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: BusStopID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let bs = app.primary.map.get_bs(id);\n\n let sim = &app.primary.sim;\n\n\n\n rows.push(Line(&bs.name).into_widget(ctx));\n\n\n\n let all_arrivals = &sim.get_analytics().bus_arrivals;\n\n for r in app.primary.map.get_routes_serving_stop(id) {\n\n // Full names can overlap, so include the ID\n\n let label = format!(\"{} ({})\", r.full_name, r.id);\n\n rows.push(\n\n ctx.style()\n\n .btn_outline\n\n .text(format!(\"Route {}\", r.short_name))\n\n .build_widget(ctx, &label),\n\n );\n\n details.hyperlinks.insert(label, Tab::BusRoute(r.id));\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 48, "score": 370421.4107116004 }, { "content": "fn bus_status_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: CarID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let route = app\n\n .primary\n\n .map\n\n .get_br(app.primary.sim.bus_route_id(id).unwrap());\n\n\n\n rows.push(\n\n ctx.style()\n\n .btn_outline\n\n .text(format!(\"Serves route {}\", route.short_name))\n\n .build_def(ctx),\n\n );\n\n details.hyperlinks.insert(\n\n format!(\"Serves route {}\", route.short_name),\n\n Tab::BusRoute(route.id),\n\n );\n\n\n\n rows.push(\n\n Line(format!(\n\n \"Currently has {} passengers\",\n\n app.primary.sim.num_transit_passengers(id),\n\n ))\n\n .into_widget(ctx),\n\n );\n\n\n\n Widget::col(rows)\n\n}\n\n\n", "file_path": "game/src/info/bus.rs", "rank": 49, "score": 370421.4107116004 }, { "content": "fn parked_car_body(ctx: &mut EventCtx, app: &App, details: &mut Details, id: CarID) -> Widget {\n\n // TODO prev trips, next trips, etc\n\n let mut rows = vec![];\n\n\n\n let p = app.primary.sim.get_owner_of_car(id).unwrap();\n\n rows.push(\n\n ctx.style()\n\n .btn_outline\n\n .text(format!(\"Owned by {}\", p))\n\n .build_def(ctx),\n\n );\n\n details.hyperlinks.insert(\n\n format!(\"Owned by {}\", p),\n\n Tab::PersonTrips(p, BTreeMap::new()),\n\n );\n\n\n\n if let Some(p) = app.primary.sim.lookup_parked_car(id) {\n\n match p.spot {\n\n ParkingSpot::Onstreet(_, _) | ParkingSpot::Lot(_, _) => {\n\n ctx.canvas.center_on_map_pt(\n", "file_path": "game/src/info/person.rs", "rank": 50, "score": 370421.4107116003 }, { "content": "fn calc_all_routes(ctx: &EventCtx, app: &mut App) -> (usize, Drawable) {\n\n let agents = app.primary.sim.active_agents();\n\n let mut batch = GeomBatch::new();\n\n let mut cnt = 0;\n\n let sim = &app.primary.sim;\n\n let map = &app.primary.map;\n\n for maybe_trace in Timer::new(\"calculate all routes\").parallelize(\n\n \"route to geometry\",\n\n Parallelism::Fastest,\n\n agents,\n\n |id| {\n\n sim.trace_route(id, map)\n\n .map(|trace| trace.make_polygons(NORMAL_LANE_THICKNESS))\n\n },\n\n ) {\n\n if let Some(t) = maybe_trace {\n\n cnt += 1;\n\n batch.push(app.cs.route, t);\n\n }\n\n }\n\n (cnt, ctx.upload(batch))\n\n}\n\n\n", "file_path": "game/src/debug/mod.rs", "rank": 51, "score": 370360.35223343864 }, { "content": "fn intro_story(ctx: &mut EventCtx) -> Box<dyn State<App>> {\n\n CutsceneBuilder::new(\"Introduction\")\n\n .boss(\n\n \"Argh, the mayor's on my case again about the West Seattle bridge. This day couldn't \\\n\n get any worse.\",\n\n )\n\n .player(\"Er, hello? Boss? I'm --\")\n\n .boss(\"Yet somehow it did.. You're the new recruit. Yeah, yeah. Come in.\")\n\n .boss(\n\n \"Due to budget cuts, we couldn't hire a real traffic engineer, so we just called some \\\n\n know-it-all from Reddit who seems to think they can fix Seattle traffic.\",\n\n )\n\n .player(\"Yes, hi, my name is --\")\n\n .boss(\"We can't afford name-tags, didn't you hear, budget cuts? Your name doesn't matter.\")\n\n .player(\"What about my Insta handle?\")\n\n .boss(\"-glare-\")\n\n .boss(\n\n \"Look, you think fixing traffic is easy? Hah! You can't fix one intersection without \\\n\n breaking ten more.\",\n\n )\n", "file_path": "game/src/sandbox/gameplay/tutorial.rs", "rank": 52, "score": 367881.67579166 }, { "content": "fn make_controls(ctx: &mut EventCtx, tabs: &mut TabController) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Text::from(Line(\"widgetry demo\").big_heading_styled()).into_widget(ctx),\n\n Widget::col(vec![\n\n Text::from(\n\n \"Click and drag the background to pan, use touchpad or scroll wheel to zoom\",\n\n )\n\n .into_widget(ctx),\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_outline\n\n .text(\"New faces\")\n\n .hotkey(Key::F)\n\n .build_widget(ctx, \"generate new faces\"),\n\n Toggle::switch(ctx, \"Draw scrollable canvas\", None, true),\n\n Toggle::switch(ctx, \"Show timeseries\", lctrl(Key::T), false),\n\n ]),\n\n \"Stopwatch: ...\"\n\n .text_widget(ctx)\n\n .named(\"stopwatch\")\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 53, "score": 365467.4031844058 }, { "content": "pub fn maybe_exit_sandbox(ctx: &mut EventCtx) -> Transition {\n\n Transition::Push(ChooseSomething::new(\n\n ctx,\n\n \"Are you ready to leave this mode?\",\n\n vec![\n\n Choice::string(\"keep playing\"),\n\n Choice::string(\"quit to main screen\").key(Key::Q),\n\n ],\n\n Box::new(|resp, ctx, app| {\n\n if resp == \"keep playing\" {\n\n return Transition::Pop;\n\n }\n\n\n\n if app.primary.map.unsaved_edits() {\n\n return Transition::Multi(vec![\n\n Transition::Push(Box::new(BackToMainMenu)),\n\n Transition::Push(SaveEdits::new(\n\n ctx,\n\n app,\n\n \"Do you want to save your proposal first?\",\n", "file_path": "game/src/sandbox/mod.rs", "rank": 54, "score": 363747.82512001705 }, { "content": "/// `is_enabled`: are (car, bike, bus, pedestrian) toggles enabled\n\n/// returns Widgets for (car, bike, bus, pedestrian)\n\nfn make_agent_toggles(ctx: &mut EventCtx, app: &App, is_enabled: [bool; 4]) -> Vec<Widget> {\n\n use widgetry::{include_labeled_bytes, Color, GeomBatchStack, RewriteColor, Toggle};\n\n let [is_car_enabled, is_bike_enabled, is_bus_enabled, is_pedestrian_enabled] = is_enabled;\n\n\n\n pub fn colored_checkbox(\n\n ctx: &EventCtx,\n\n action: &str,\n\n is_enabled: bool,\n\n color: Color,\n\n icon: &str,\n\n label: &str,\n\n tooltip: Text,\n\n ) -> Widget {\n\n let buttons = ctx\n\n .style()\n\n .btn_plain\n\n .btn()\n\n .label_text(label)\n\n .padding(4.0)\n\n .tooltip(tooltip)\n", "file_path": "game/src/sandbox/minimap.rs", "rank": 55, "score": 362719.4525558611 }, { "content": "fn mouseover_unzoomed_agent_circle(ctx: &mut EventCtx, app: &mut App) {\n\n let cursor = if let Some(pt) = ctx.canvas.get_cursor_in_map_space() {\n\n pt\n\n } else {\n\n return;\n\n };\n\n\n\n for (id, _, _) in app\n\n .primary\n\n .agents\n\n .borrow_mut()\n\n .calculate_unzoomed_agents(ctx, app)\n\n .query(\n\n Circle::new(cursor, Distance::meters(3.0))\n\n .get_bounds()\n\n .as_bbox(),\n\n )\n\n {\n\n if let Some(pt) = app\n\n .primary\n\n .sim\n\n .canonical_pt_for_agent(*id, &app.primary.map)\n\n {\n\n if Circle::new(pt, unzoomed_agent_radius(id.to_vehicle_type())).contains_pt(cursor) {\n\n app.primary.current_selection = Some(ID::from_agent(*id));\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "game/src/sandbox/mod.rs", "rank": 56, "score": 360742.2301645777 }, { "content": "fn make_top_panel(ctx: &mut EventCtx, app: &App, can_undo: bool, can_redo: bool) -> Panel {\n\n let row = vec![\n\n ctx.style()\n\n .btn_solid_primary\n\n .text(\"Finish\")\n\n .hotkey(Key::Enter)\n\n .build_def(ctx),\n\n ctx.style()\n\n .btn_outline\n\n .text(\"Preview\")\n\n .hotkey(lctrl(Key::P))\n\n .build_def(ctx),\n\n ctx.style()\n\n .btn_plain\n\n .icon(\"system/assets/tools/undo.svg\")\n\n .disabled(!can_undo)\n\n .hotkey(lctrl(Key::Z))\n\n .build_widget(ctx, \"undo\"),\n\n ctx.style()\n\n .btn_plain\n", "file_path": "game/src/edit/traffic_signals/mod.rs", "rank": 57, "score": 358532.87689417426 }, { "content": "fn bus_header(ctx: &mut EventCtx, app: &App, details: &mut Details, id: CarID, tab: Tab) -> Widget {\n\n let route = app.primary.sim.bus_route_id(id).unwrap();\n\n\n\n if let Some(pt) = app\n\n .primary\n\n .sim\n\n .canonical_pt_for_agent(AgentID::Car(id), &app.primary.map)\n\n {\n\n ctx.canvas.center_on_map_pt(pt);\n\n }\n\n\n\n let mut rows = vec![];\n\n rows.push(Widget::row(vec![\n\n Line(format!(\n\n \"{} (route {})\",\n\n id,\n\n app.primary.map.get_br(route).short_name\n\n ))\n\n .small_heading()\n\n .into_widget(ctx),\n", "file_path": "game/src/info/bus.rs", "rank": 59, "score": 355623.6923989471 }, { "content": "fn export_for_leaflet(ctx: &mut EventCtx, app: &App) {\n\n let name = app.primary.map.get_name();\n\n let bounds = app.primary.map.get_bounds();\n\n let map_length = bounds.width().max(bounds.height());\n\n\n\n // At zoom level N, the entire map fits into (N + 1) * (N + 1) tiles\n\n for zoom_level in 0..=25 {\n\n let num_tiles = zoom_level + 1;\n\n // How do we fit the entire map_length into this many tiles?\n\n let zoom = 256.0 * (num_tiles as f64) / map_length;\n\n ctx.request_update(UpdateType::ScreenCaptureEverything {\n\n dir: format!(\n\n \"screenshots/{}/{}/{}/{}\",\n\n name.city.country, name.city.city, name.map, zoom_level\n\n ),\n\n zoom,\n\n dims: ScreenDims::new(256.0, 256.0),\n\n leaflet_naming: true,\n\n });\n\n }\n\n}\n\n\n", "file_path": "game/src/debug/mod.rs", "rank": 60, "score": 354596.1110939493 }, { "content": "fn traffic_body(ctx: &mut EventCtx, app: &App, id: LaneID, opts: &DataOptions) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n // Since this applies to the entire road, ignore lane type.\n\n let mut txt = Text::from(\"Traffic over entire road, not just this lane\");\n\n txt.add_line(format!(\n\n \"Since midnight: {} commuters and vehicles crossed\",\n\n prettyprint_usize(app.primary.sim.get_analytics().road_thruput.total_for(r.id))\n\n ));\n\n rows.push(txt.into_widget(ctx));\n\n\n\n rows.push(opts.to_controls(ctx, app));\n\n\n\n let r = map.get_l(id).parent;\n\n let time = if opts.show_end_of_day {\n\n app.primary.sim.get_end_of_day()\n", "file_path": "game/src/info/lane.rs", "rank": 61, "score": 354582.9020333275 }, { "content": "fn traffic_body(ctx: &mut EventCtx, app: &App, id: IntersectionID, opts: &DataOptions) -> Widget {\n\n let mut rows = vec![];\n\n let mut txt = Text::new();\n\n\n\n txt.add_line(format!(\n\n \"Since midnight: {} commuters and vehicles crossed\",\n\n prettyprint_usize(\n\n app.primary\n\n .sim\n\n .get_analytics()\n\n .intersection_thruput\n\n .total_for(id)\n\n )\n\n ));\n\n rows.push(txt.into_widget(ctx));\n\n\n\n rows.push(opts.to_controls(ctx, app));\n\n\n\n let time = if opts.show_end_of_day {\n\n app.primary.sim.get_end_of_day()\n", "file_path": "game/src/info/intersection.rs", "rank": 62, "score": 354582.9020333275 }, { "content": "fn draw_unwalkable_roads(ctx: &mut EventCtx, app: &App, opts: &Options) -> Drawable {\n\n let allow_shoulders = match opts {\n\n Options::Walking(ref opts) => opts.allow_shoulders,\n\n Options::Biking => {\n\n return Drawable::empty(ctx);\n\n }\n\n };\n\n\n\n let mut batch = GeomBatch::new();\n\n 'ROADS: for road in app.map.all_roads() {\n\n if road.is_light_rail() {\n\n continue;\n\n }\n\n for (_, _, lt) in road.lanes_ltr() {\n\n if lt == LaneType::Sidewalk || (lt == LaneType::Shoulder && allow_shoulders) {\n\n continue 'ROADS;\n\n }\n\n }\n\n // TODO Skip highways\n\n batch.push(Color::BLUE.alpha(0.5), road.get_thick_polygon(&app.map));\n\n }\n\n ctx.upload(batch)\n\n}\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 63, "score": 354510.1436651716 }, { "content": "fn make_pagination(ctx: &mut EventCtx, total: usize, skip: usize) -> Widget {\n\n let next = ctx\n\n .style()\n\n .btn_next()\n\n .disabled(skip + 1 + ROWS >= total)\n\n .hotkey(Key::RightArrow);\n\n let prev = ctx\n\n .style()\n\n .btn_prev()\n\n .disabled(skip == 0)\n\n .hotkey(Key::LeftArrow);\n\n\n\n Widget::row(vec![\n\n prev.build_widget(ctx, \"previous\"),\n\n format!(\n\n \"{}-{} of {}\",\n\n if total > 0 {\n\n prettyprint_usize(skip + 1)\n\n } else {\n\n \"0\".to_string()\n\n },\n\n prettyprint_usize((skip + 1 + ROWS).min(total)),\n\n prettyprint_usize(total)\n\n )\n\n .text_widget(ctx)\n\n .centered_vert(),\n\n next.build_widget(ctx, \"next\"),\n\n ])\n\n}\n\n\n", "file_path": "widgetry/src/widgets/table.rs", "rank": 64, "score": 346931.3076906227 }, { "content": "fn make_btn(ctx: &mut EventCtx, num: usize) -> Widget {\n\n let title = match num {\n\n 0 => \"Edit 0 signals\".to_string(),\n\n 1 => \"Edit 1 signal\".to_string(),\n\n _ => format!(\"Edit {} signals\", num),\n\n };\n\n ctx.style()\n\n .btn_solid_primary\n\n .text(title)\n\n .disabled(num == 0)\n\n .hotkey(hotkeys(vec![Key::Enter, Key::E]))\n\n .build_widget(ctx, \"edit\")\n\n}\n", "file_path": "game/src/edit/traffic_signals/picker.rs", "rank": 65, "score": 346898.9861259385 }, { "content": "// This prepares a bunch of geometry (colored polygons) and uploads it to the GPU once. Then it can\n\n// be redrawn cheaply later.\n\nfn setup_scrollable_canvas(ctx: &mut EventCtx) -> Drawable {\n\n let mut batch = GeomBatch::new();\n\n batch.push(\n\n Color::hex(\"#4E30A6\"),\n\n Polygon::rounded_rectangle(5000.0, 5000.0, 25.0),\n\n );\n\n // SVG support using lyon and usvg. Map-space means don't scale for high DPI monitors.\n\n batch\n\n .append(GeomBatch::load_svg(ctx, \"system/assets/pregame/logo.svg\").translate(300.0, 300.0));\n\n // Text rendering also goes through lyon and usvg.\n\n batch.append(\n\n Text::from(Line(\"Awesome vector text thanks to usvg and lyon\").fg(Color::hex(\"#DF8C3D\")))\n\n .render_autocropped(ctx)\n\n .scale(2.0)\n\n .centered_on(Pt2D::new(600.0, 500.0))\n\n .rotate(Angle::degrees(-30.0)),\n\n );\n\n\n\n let mut rng = if cfg!(target_arch = \"wasm32\") {\n\n XorShiftRng::seed_from_u64(0)\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 66, "score": 345684.0012792395 }, { "content": "fn header(ctx: &EventCtx, app: &App, details: &mut Details, id: LaneID, tab: Tab) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n let label = if l.is_shoulder() {\n\n \"Shoulder\"\n\n } else if l.is_sidewalk() {\n\n \"Sidewalk\"\n\n } else {\n\n \"Lane\"\n\n };\n\n\n\n // Navbar\n\n rows.push(Widget::row(vec![\n\n Line(format!(\"{} #{}\", label, id.0))\n\n .small_heading()\n\n .into_widget(ctx),\n", "file_path": "game/src/info/lane.rs", "rank": 67, "score": 342823.987602363 }, { "content": "fn transition(app: &mut App, tut: &mut TutorialState) -> Transition {\n\n tut.reset_state();\n\n let mode = GameplayMode::Tutorial(tut.current);\n\n Transition::Replace(SandboxMode::simple_new(app, mode))\n\n}\n\n\n\nimpl TutorialState {\n\n // These're mutex to each state, but still important to reset. Otherwise if you go back to a\n\n // previous interaction stage, it'll just be automatically marked done.\n\n fn reset_state(&mut self) {\n\n self.inspected_bike_lane = false;\n\n self.inspected_building = false;\n\n self.inspected_stop_sign = false;\n\n self.inspected_border = false;\n\n self.was_paused = true;\n\n self.num_pauses = 0;\n\n self.score_delivered = false;\n\n self.following_car = false;\n\n self.car_parked = false;\n\n self.prank_done = false;\n", "file_path": "game/src/sandbox/gameplay/tutorial.rs", "rank": 68, "score": 340403.81520821 }, { "content": "#[allow(non_snake_case)]\n\npub fn Line<S: Into<String>>(text: S) -> TextSpan {\n\n TextSpan {\n\n text: text.into(),\n\n fg_color: None,\n\n size: DEFAULT_FONT_SIZE,\n\n font: DEFAULT_FONT,\n\n underlined: false,\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct Text {\n\n // The bg_color will cover the entire block, but some lines can have extra highlighting.\n\n lines: Vec<(Option<Color>, Vec<TextSpan>)>,\n\n // TODO Stop using this as much as possible.\n\n bg_color: Option<Color>,\n\n}\n\n\n\nimpl From<TextSpan> for Text {\n\n fn from(line: TextSpan) -> Text {\n", "file_path": "widgetry/src/text.rs", "rank": 69, "score": 339248.328135212 }, { "content": "/// Match OSM buildings to parcels, scraping the number of housing units.\n\n// TODO It's expensive to load the huge zoning_parcels.bin file for every map.\n\npub fn match_parcels_to_buildings(map: &mut Map, shapes: &ExtraShapes, timer: &mut Timer) {\n\n let mut parcels_with_housing: Vec<(Polygon, usize)> = Vec::new();\n\n // TODO We should refactor something like FindClosest, but for polygon containment\n\n // The quadtree's ID is just an index into parcels_with_housing.\n\n let mut quadtree: QuadTree<usize> = QuadTree::default(map.get_bounds().as_bbox());\n\n timer.start_iter(\"index all parcels\", shapes.shapes.len());\n\n for shape in &shapes.shapes {\n\n timer.next();\n\n if let Some(units) = shape\n\n .attributes\n\n .get(\"EXIST_UNITS\")\n\n .and_then(|x| x.parse::<usize>().ok())\n\n {\n\n if let Some(ring) = map\n\n .get_gps_bounds()\n\n .try_convert(&shape.points)\n\n .and_then(|pts| Ring::new(pts).ok())\n\n {\n\n let polygon = ring.to_polygon();\n\n quadtree\n", "file_path": "importer/src/seattle.rs", "rank": 70, "score": 331947.5480566618 }, { "content": "fn current_status(ctx: &EventCtx, person: &Person, map: &Map) -> Widget {\n\n (match person.state {\n\n PersonState::Inside(b) => {\n\n // TODO hyperlink\n\n format!(\"Currently inside {}\", map.get_b(b).address).text_widget(ctx)\n\n }\n\n PersonState::Trip(_) => unreachable!(),\n\n PersonState::OffMap => \"Currently outside the map boundaries\".text_widget(ctx),\n\n })\n\n .margin_vert(16)\n\n}\n\n\n", "file_path": "game/src/info/person.rs", "rank": 71, "score": 330044.1188865949 }, { "content": "fn area_body(ctx: &EventCtx, app: &App, id: AreaID) -> Widget {\n\n let mut rows = vec![];\n\n let area = app.primary.map.get_a(id);\n\n\n\n if let Some(osm_id) = area.osm_id {\n\n rows.push(\n\n ctx.style()\n\n .btn_outline\n\n .text(\"Open in OSM\")\n\n .build_widget(ctx, format!(\"open {}\", osm_id)),\n\n );\n\n }\n\n\n\n rows.extend(make_table(\n\n ctx,\n\n area.osm_tags\n\n .inner()\n\n .iter()\n\n .map(|(k, v)| (k.to_string(), v.to_string()))\n\n .collect(),\n\n ));\n\n\n\n Widget::col(rows)\n\n}\n", "file_path": "game/src/info/debug.rs", "rank": 72, "score": 327902.83143854915 }, { "content": "fn info_body(ctx: &EventCtx, app: &App, id: IntersectionID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let i = app.primary.map.get_i(id);\n\n\n\n let mut txt = Text::from(\"Connecting\");\n\n let mut road_names = BTreeSet::new();\n\n for r in &i.roads {\n\n road_names.insert(\n\n app.primary\n\n .map\n\n .get_r(*r)\n\n .get_name(app.opts.language.as_ref()),\n\n );\n\n }\n\n for r in road_names {\n\n txt.add_line(format!(\" {}\", r));\n\n }\n\n rows.push(txt.into_widget(ctx));\n\n\n", "file_path": "game/src/info/intersection.rs", "rank": 73, "score": 327902.83143854915 }, { "content": "fn info_body(ctx: &EventCtx, app: &App, id: LaneID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n let mut kv = Vec::new();\n\n\n\n if !l.is_walkable() {\n\n kv.push((\"Type\", l.lane_type.describe().to_string()));\n\n }\n\n if r.is_private() {\n\n let mut ban = Vec::new();\n\n for p in PathConstraints::all() {\n\n if !r.access_restrictions.allow_through_traffic.contains(p) {\n\n ban.push(format!(\"{:?}\", p).to_ascii_lowercase());\n\n }\n\n }\n\n if !ban.is_empty() {\n", "file_path": "game/src/info/lane.rs", "rank": 74, "score": 327902.83143854915 }, { "content": "fn debug_body(ctx: &EventCtx, app: &App, id: LaneID) -> Widget {\n\n let mut rows = vec![];\n\n\n\n let map = &app.primary.map;\n\n let l = map.get_l(id);\n\n let r = map.get_r(l.parent);\n\n\n\n let mut kv = Vec::new();\n\n\n\n kv.push((\"Parent\".to_string(), r.id.to_string()));\n\n\n\n if l.lane_type.is_for_moving_vehicles() {\n\n kv.push((\n\n \"Driving blackhole\".to_string(),\n\n l.driving_blackhole.to_string(),\n\n ));\n\n kv.push((\n\n \"Biking blackhole\".to_string(),\n\n l.biking_blackhole.to_string(),\n\n ));\n", "file_path": "game/src/info/lane.rs", "rank": 75, "score": 327902.83143854915 }, { "content": "// TODO Can we automatically transform text and SVG colors?\n\nfn cutscene_pt1_task(ctx: &mut EventCtx) -> Widget {\n\n let icon_builder = Image::empty().color(Color::BLACK).dims(50.0);\n\n Widget::custom_col(vec![\n\n Text::from_multiline(vec![\n\n Line(format!(\n\n \"Don't let anyone be delayed by one traffic signal more than {}!\",\n\n THRESHOLD\n\n ))\n\n .fg(Color::BLACK),\n\n Line(\"Survive as long as possible through 24 hours of a busy weekday.\")\n\n .fg(Color::BLACK),\n\n ])\n\n .into_widget(ctx)\n\n .margin_below(30),\n\n Widget::custom_row(vec![\n\n Widget::col(vec![\n\n Line(\"Time\").fg(Color::BLACK).into_widget(ctx),\n\n icon_builder\n\n .clone()\n\n .source_path(\"system/assets/tools/time.svg\")\n", "file_path": "game/src/sandbox/gameplay/fix_traffic_signals.rs", "rank": 76, "score": 326077.91625069326 }, { "content": "fn make_select_panel(ctx: &mut EventCtx, selector: &RoadSelector) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Line(\"Edit many roads\").small_heading().into_widget(ctx),\n\n selector.make_controls(ctx),\n\n Widget::row(vec![\n\n ctx.style()\n\n .btn_outline\n\n .text(format!(\"Edit {} roads\", selector.roads.len()))\n\n .disabled(selector.roads.is_empty())\n\n .hotkey(hotkeys(vec![Key::E, Key::Enter]))\n\n .build_widget(ctx, \"edit roads\"),\n\n ctx.style()\n\n .btn_outline\n\n .text(format!(\n\n \"Export {} roads to shared-row\",\n\n selector.roads.len()\n\n ))\n\n .build_widget(ctx, \"export roads to shared-row\"),\n\n ctx.style()\n\n .btn_outline\n", "file_path": "game/src/edit/bulk.rs", "rank": 77, "score": 323875.58290380903 }, { "content": "fn make_panel(ctx: &mut EventCtx, story: &StoryMap, mode: &Mode, dirty: bool) -> Panel {\n\n Panel::new(Widget::col(vec![\n\n Widget::row(vec![\n\n Line(\"Story map editor\").small_heading().into_widget(ctx),\n\n Widget::vert_separator(ctx, 30.0),\n\n ctx.style()\n\n .btn_outline\n\n .popup(&story.name)\n\n .hotkey(lctrl(Key::L))\n\n .build_widget(ctx, \"load\"),\n\n ctx.style()\n\n .btn_plain\n\n .icon(\"system/assets/tools/save.svg\")\n\n .hotkey(lctrl(Key::S))\n\n .disabled(!dirty)\n\n .build_widget(ctx, \"save\"),\n\n ctx.style().btn_close_widget(ctx),\n\n ]),\n\n Widget::row(vec![\n\n ctx.style()\n", "file_path": "game/src/devtools/story.rs", "rank": 78, "score": 322390.60797777167 }, { "content": "/// This import from GTFS:\n\n/// - is specific to Seattle, whose files don't seem to match https://developers.google.com/transit/gtfs/reference\n\n/// - is probably wrong\n\npub fn add_gtfs_schedules(map: &mut Map) {\n\n let city = CityName::seattle();\n\n // https://www.openstreetmap.org/relation/8616968 as an example, mapping to\n\n // https://kingcounty.gov/depts/transportation/metro/schedules-maps/route/048.aspx\n\n\n\n let mut trip_marker_to_route: BTreeMap<String, BusRouteID> = BTreeMap::new();\n\n for br in map.all_bus_routes() {\n\n if let Some(ref m) = br.gtfs_trip_marker {\n\n // Dunno what the :0 thing is\n\n trip_marker_to_route.insert(m.split(\":\").next().unwrap().to_string(), br.id);\n\n }\n\n }\n\n\n\n // Each route has a bunch of trips throughout the day\n\n let mut trip_marker_to_trips: MultiMap<String, String> = MultiMap::new();\n\n for rec in\n\n csv::Reader::from_reader(File::open(city.input_path(\"google_transit/trips.txt\")).unwrap())\n\n .deserialize()\n\n {\n\n let rec: TripRecord = rec.unwrap();\n", "file_path": "importer/src/seattle.rs", "rank": 79, "score": 322288.70357487164 }, { "content": "pub fn make_crosswalk(batch: &mut GeomBatch, turn: &Turn, map: &Map, cs: &ColorScheme) {\n\n if make_rainbow_crosswalk(batch, turn, map) {\n\n return;\n\n }\n\n\n\n // This size also looks better for shoulders\n\n let width = SIDEWALK_THICKNESS;\n\n // Start at least width out to not hit sidewalk corners. Also account for the thickness of the\n\n // crosswalk line itself. Center the lines inside these two boundaries.\n\n let boundary = width;\n\n let tile_every = width * 0.6;\n\n let line = {\n\n // The middle line in the crosswalk geometry is the main crossing line.\n\n let pts = turn.geom.points();\n\n if pts.len() < 3 {\n\n println!(\n\n \"Not rendering crosswalk for {}; its geometry was squished earlier\",\n\n turn.id\n\n );\n\n return;\n", "file_path": "map_gui/src/render/intersection.rs", "rank": 80, "score": 321615.08440921985 }, { "content": "/// Simple second-pass after generating all signals. Find pairs of traffic signals very close to\n\n/// each other with 2 stages each, see if the primary movement of the first stages lead to each\n\n/// other, and flip the order of stages if not. This is often wrong when the most common movement is\n\n/// actually turning left then going straight (near Mercer for example), but not sure how we could\n\n/// know that without demand data.\n\npub fn synchronize(map: &mut Map) {\n\n let mut seen = HashSet::new();\n\n let mut pairs = Vec::new();\n\n let handmapped = traffic_signal_data::load_all_data().unwrap();\n\n for i in map.all_intersections() {\n\n if !i.is_traffic_signal() || seen.contains(&i.id) || handmapped.contains_key(&i.orig_id.0) {\n\n continue;\n\n }\n\n if let Some(list) = IntersectionCluster::autodetect(i.id, map) {\n\n let list = list.into_iter().collect::<Vec<_>>();\n\n if list.len() == 2\n\n && map.get_traffic_signal(list[0]).stages.len() == 2\n\n && map.get_traffic_signal(list[1]).stages.len() == 2\n\n {\n\n pairs.push((list[0], list[1]));\n\n seen.insert(list[0]);\n\n seen.insert(list[1]);\n\n }\n\n }\n\n }\n", "file_path": "map_model/src/make/traffic_signals/mod.rs", "rank": 81, "score": 320442.5566752973 }, { "content": "// Adjust the path to start on the building's border, not center\n\nfn trim_path(poly: &Polygon, path: Line) -> Line {\n\n for bldg_line in poly.points().windows(2) {\n\n if let Some(l1) = Line::new(bldg_line[0], bldg_line[1]) {\n\n if let Some(hit) = l1.intersection(&path) {\n\n if let Some(l2) = Line::new(hit, path.pt2()) {\n\n return l2;\n\n }\n\n }\n\n }\n\n }\n\n // Just give up\n\n path\n\n}\n\n\n", "file_path": "map_model/src/make/buildings.rs", "rank": 82, "score": 319516.0140529399 }, { "content": "fn draw_star(ctx: &mut EventCtx, b: &Building) -> GeomBatch {\n\n GeomBatch::load_svg(ctx, \"system/assets/tools/star.svg\")\n\n .centered_on(b.polygon.center())\n\n .color(RewriteColor::ChangeAll(Color::BLACK))\n\n}\n\n\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 83, "score": 317016.27486156527 }, { "content": "pub fn color_for_mode(app: &App, m: TripMode) -> Color {\n\n match m {\n\n TripMode::Walk => app.cs.unzoomed_pedestrian,\n\n TripMode::Bike => app.cs.unzoomed_bike,\n\n TripMode::Transit => app.cs.unzoomed_bus,\n\n TripMode::Drive => app.cs.unzoomed_car,\n\n }\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 84, "score": 316988.4862542761 }, { "content": "fn options_to_controls(ctx: &mut EventCtx, opts: &Options) -> Widget {\n\n let mut rows = vec![Toggle::choice(\n\n ctx,\n\n \"walking / biking\",\n\n \"walking\",\n\n \"biking\",\n\n None,\n\n match opts {\n\n Options::Walking(_) => true,\n\n Options::Biking => false,\n\n },\n\n )];\n\n match opts {\n\n Options::Walking(ref opts) => {\n\n rows.push(Toggle::switch(\n\n ctx,\n\n \"Allow walking on the shoulder of the road without a sidewalk\",\n\n None,\n\n opts.allow_shoulders,\n\n ));\n", "file_path": "fifteen_min/src/viewer.rs", "rank": 85, "score": 316558.94709967106 }, { "content": "/// Construct the final model of bus/train stops and routes. This is quite broken currently, so not\n\n/// going to describe how it works.\n\npub fn make_stops_and_routes(map: &mut Map, raw_routes: &Vec<RawBusRoute>, timer: &mut Timer) {\n\n timer.start(\"make transit stops and routes\");\n\n let matcher = Matcher::new(raw_routes, map, timer);\n\n\n\n // TODO I'm assuming the vehicle_pos <-> driving_pos relation is one-to-one...\n\n let mut pt_to_stop: BTreeMap<(Position, Position), BusStopID> = BTreeMap::new();\n\n for r in raw_routes {\n\n if let Err(err) = make_route(map, r, &mut pt_to_stop, &matcher) {\n\n warn!(\"Skipping route {} ({}): {}\", r.full_name, r.osm_rel_id, err);\n\n }\n\n }\n\n\n\n // Remove orphaned bus stops. This messes up the BusStopID indexing.\n\n for id in map\n\n .bus_stops\n\n .keys()\n\n .filter(|id| map.get_routes_serving_stop(**id).is_empty())\n\n .cloned()\n\n .collect::<Vec<_>>()\n\n {\n\n map.bus_stops.remove(&id);\n\n map.lanes[id.sidewalk.0].bus_stops.remove(&id);\n\n }\n\n\n\n timer.stop(\"make transit stops and routes\");\n\n}\n\n\n", "file_path": "map_model/src/make/transit.rs", "rank": 86, "score": 315618.4285284688 }, { "content": "/// Fill in empty space between one-way roads.\n\npub fn find_medians(map: &Map) -> Vec<Polygon> {\n\n // TODO Needs more work\n\n if true {\n\n return Vec::new();\n\n }\n\n\n\n let mut candidates = Vec::new();\n\n for r in map.all_roads() {\n\n if r.osm_tags.is(\"dual_carriageway\", \"yes\") {\n\n // TODO Always to the left? Maybe driving side matters; test in southbank too\n\n let lanes_ltr = r.lanes_ltr();\n\n candidates.push(lanes_ltr[0].0);\n\n }\n\n }\n\n\n\n let mut visited = BTreeSet::new();\n\n let mut polygons = Vec::new();\n\n for start in candidates {\n\n if visited.contains(&start) {\n\n continue;\n\n }\n\n if let Some((poly, lanes)) = map.get_l(start).trace_around_block(map) {\n\n polygons.push(poly);\n\n visited.extend(lanes);\n\n }\n\n }\n\n\n\n polygons\n\n}\n", "file_path": "map_model/src/make/medians.rs", "rank": 87, "score": 314307.59385212447 }, { "content": "pub fn distribute_residents(map: &mut map_model::Map, timer: &mut Timer) {\n\n for shape in abstio::read_binary::<ExtraShapes>(\n\n \"data/input/de/berlin/planning_areas.bin\".to_string(),\n\n timer,\n\n )\n\n .shapes\n\n {\n\n let pts = map.get_gps_bounds().convert(&shape.points);\n\n if pts\n\n .iter()\n\n .all(|pt| !map.get_boundary_polygon().contains_pt(*pt))\n\n {\n\n continue;\n\n }\n\n let region = Ring::must_new(pts).to_polygon();\n\n // Deterministically seed using the planning area's ID.\n\n let mut rng =\n\n XorShiftRng::seed_from_u64(shape.attributes[\"spatial_name\"].parse::<u64>().unwrap());\n\n\n\n for (home, n) in popdat::distribute_population_to_homes(\n", "file_path": "importer/src/berlin.rs", "rank": 88, "score": 314250.5951600338 }, { "content": "pub fn color_for_agent_type(app: &App, a: AgentType) -> Color {\n\n match a {\n\n AgentType::Pedestrian => app.cs.unzoomed_pedestrian,\n\n AgentType::Bike => app.cs.unzoomed_bike,\n\n AgentType::Bus | AgentType::Train => app.cs.unzoomed_bus,\n\n AgentType::TransitRider => app.cs.bus_trip,\n\n AgentType::Car => app.cs.unzoomed_car,\n\n }\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 89, "score": 312895.2922198177 }, { "content": "fn make_btn(ctx: &mut EventCtx, num: usize) -> Widget {\n\n let title = match num {\n\n 0 => \"Record 0 intersections\".to_string(),\n\n 1 => \"Record 1 intersection\".to_string(),\n\n _ => format!(\"Record {} intersections\", num),\n\n };\n\n ctx.style()\n\n .btn_solid_primary\n\n .text(title)\n\n .disabled(num == 0)\n\n .hotkey(Key::Enter)\n\n .build_widget(ctx, \"record\")\n\n}\n", "file_path": "game/src/sandbox/misc_tools.rs", "rank": 90, "score": 312578.7434297254 }, { "content": "fn challenge_header(ctx: &mut EventCtx, title: &str) -> Widget {\n\n Widget::row(vec![\n\n Line(title).small_heading().into_widget(ctx).centered_vert(),\n\n ctx.style()\n\n .btn_plain\n\n .icon(\"system/assets/tools/info.svg\")\n\n .build_widget(ctx, \"instructions\")\n\n .centered_vert(),\n\n Widget::vert_separator(ctx, 50.0),\n\n ctx.style()\n\n .btn_outline\n\n .icon_text(\"system/assets/tools/pencil.svg\", \"Edit map\")\n\n .hotkey(lctrl(Key::E))\n\n .build_widget(ctx, \"edit map\")\n\n .centered_vert(),\n\n ])\n\n .padding(5)\n\n}\n\n\n\npub struct FinalScore {\n", "file_path": "game/src/sandbox/gameplay/mod.rs", "rank": 91, "score": 312578.7434297254 }, { "content": "pub fn list_names<F: Fn(TextSpan) -> TextSpan>(txt: &mut Text, styler: F, names: BTreeSet<String>) {\n\n let len = names.len();\n\n for (idx, n) in names.into_iter().enumerate() {\n\n if idx != 0 {\n\n if idx == len - 1 {\n\n if len == 2 {\n\n txt.append(Line(\" and \"));\n\n } else {\n\n txt.append(Line(\", and \"));\n\n }\n\n } else {\n\n txt.append(Line(\", \"));\n\n }\n\n }\n\n txt.append(styler(Line(n)));\n\n }\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 92, "score": 308545.0422770974 }, { "content": "// TODO This needs to update turn restrictions too\n\npub fn clip_map(map: &mut RawMap, timer: &mut Timer) {\n\n timer.start(\"clipping map to boundary\");\n\n\n\n // So we can use retain_btreemap without borrowing issues\n\n let boundary_polygon = map.boundary_polygon.clone();\n\n let boundary_ring = Ring::must_new(boundary_polygon.points().clone());\n\n\n\n // This is kind of indirect and slow, but first pass -- just remove roads that start or end\n\n // outside the boundary polygon.\n\n retain_btreemap(&mut map.roads, |_, r| {\n\n let first_in = boundary_polygon.contains_pt(r.center_points[0]);\n\n let last_in = boundary_polygon.contains_pt(*r.center_points.last().unwrap());\n\n let light_rail_ok = if r.is_light_rail() {\n\n // Make sure it's in the boundary somewhere\n\n r.center_points\n\n .iter()\n\n .any(|pt| boundary_polygon.contains_pt(*pt))\n\n } else {\n\n false\n\n };\n", "file_path": "convert_osm/src/clip.rs", "rank": 93, "score": 307926.0166318236 }, { "content": "pub fn color_for_trip_phase(app: &App, tpt: TripPhaseType) -> Color {\n\n match tpt {\n\n TripPhaseType::Driving => app.cs.unzoomed_car,\n\n TripPhaseType::Walking => app.cs.unzoomed_pedestrian,\n\n TripPhaseType::Biking => app.cs.bike_trip,\n\n TripPhaseType::Parking => app.cs.parking_trip,\n\n TripPhaseType::WaitingForBus(_, _) => app.cs.bus_layer,\n\n TripPhaseType::RidingBus(_, _, _) => app.cs.bus_trip,\n\n TripPhaseType::Cancelled | TripPhaseType::Finished => unreachable!(),\n\n TripPhaseType::DelayedStart => Color::YELLOW,\n\n }\n\n}\n\n\n", "file_path": "game/src/common/mod.rs", "rank": 94, "score": 305227.0033750355 }, { "content": "// TODO Move to geom?\n\nfn squish_polygons_together(mut polygons: Vec<Polygon>) -> Vec<(f64, f64)> {\n\n if polygons.len() == 1 {\n\n return vec![(0.0, 0.0)];\n\n }\n\n\n\n // Can't be too big, or polygons could silently swap places. To be careful, pick something a\n\n // bit smaller than the smallest polygon.\n\n let step_size = 0.8\n\n * polygons.iter().fold(std::f64::MAX, |x, p| {\n\n x.min(p.get_bounds().width()).min(p.get_bounds().height())\n\n });\n\n\n\n let mut translations: Vec<(f64, f64)> =\n\n std::iter::repeat((0.0, 0.0)).take(polygons.len()).collect();\n\n // Once a polygon hits another while moving, stop adjusting it. Otherwise, go round-robin.\n\n let mut indices: VecDeque<usize> = (0..polygons.len()).collect();\n\n\n\n let mut attempts = 0;\n\n while !indices.is_empty() {\n\n let idx = indices.pop_front().unwrap();\n", "file_path": "game/src/edit/traffic_signals/mod.rs", "rank": 95, "score": 304894.08808411646 }, { "content": "/// Highlights intersections which were \"slow\" on the map\n\nfn highlight_slow_intersections(ctx: &EventCtx, app: &App, details: &mut Details, id: TripID) {\n\n if let Some(delays) = app\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .trip_intersection_delays\n\n .get(&id)\n\n {\n\n for (id, time) in delays {\n\n let intersection = app.primary.map.get_i(id.parent);\n\n let (normal_delay_time, slow_delay_time) = if intersection.is_traffic_signal() {\n\n (30, 120)\n\n } else {\n\n (5, 30)\n\n };\n\n let (fg_color, bg_color) = if *time < normal_delay_time {\n\n (Color::WHITE, app.cs.normal_slow_intersection)\n\n } else if *time < slow_delay_time {\n\n (Color::BLACK, app.cs.slow_intersection)\n\n } else {\n", "file_path": "game/src/info/trip.rs", "rank": 96, "score": 304496.593276053 }, { "content": "/// Highlights lanes which were \"slow\" on the map\n\nfn highlight_slow_lanes(ctx: &EventCtx, app: &App, details: &mut Details, id: TripID) {\n\n if let Some(lane_speeds) = app\n\n .primary\n\n .sim\n\n .get_analytics()\n\n .lane_speed_percentage\n\n .get(&id)\n\n {\n\n for (id, speed_percent) in lane_speeds.iter() {\n\n let lane = app.primary.map.get_l(*id);\n\n let (fg_color, bg_color) = if speed_percent > &95 {\n\n (Color::WHITE, app.cs.normal_slow_intersection)\n\n } else if speed_percent > &60 {\n\n (Color::BLACK, app.cs.slow_intersection)\n\n } else {\n\n (Color::WHITE, app.cs.very_slow_intersection)\n\n };\n\n details.unzoomed.push(\n\n bg_color,\n\n lane.lane_center_pts.make_polygons(Distance::meters(10.0)),\n", "file_path": "game/src/info/trip.rs", "rank": 97, "score": 304496.593276053 }, { "content": "fn make_tabs(ctx: &mut EventCtx) -> TabController {\n\n let style = ctx.style();\n\n\n\n let mut tabs = TabController::new(\"demo_tabs\");\n\n\n\n let gallery_bar_item = style.btn_tab.text(\"Component Gallery\");\n\n let gallery_content = Widget::col(vec![\n\n Text::from(Line(\"Text\").big_heading_styled().size(18)).into_widget(ctx),\n\n Text::from_all(vec![\n\n Line(\"You can \"),\n\n Line(\"change fonts \").big_heading_plain(),\n\n Line(\"on the same \").small().fg(Color::BLUE),\n\n Line(\"line!\").small_heading(),\n\n ])\n\n .bg(Color::GREEN)\n\n .into_widget(ctx),\n\n // Button Style Gallery\n\n Text::from(Line(\"Buttons\").big_heading_styled().size(18)).into_widget(ctx),\n\n Widget::row(vec![\n\n style\n", "file_path": "widgetry_demo/src/lib.rs", "rank": 98, "score": 304470.4407766704 }, { "content": "pub fn lctrl(key: Key) -> MultiKey {\n\n MultiKey::LCtrl(key)\n\n}\n\n\n", "file_path": "widgetry/src/event.rs", "rank": 99, "score": 303648.1060989375 } ]
Rust
src/ast/expr.rs
1tgr/simplejit-demo
750a1f628452d42836d0da5fc415fcef7750c045
use crate::ast::{ArithmeticKind, ComparisonKind, EnvId, IdentId}; use derive_more::{Display, TryInto}; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)] #[display(fmt = "{}", "_0")] pub struct ExprId(salsa::InternId); impl salsa::InternKey for ExprId { fn from_intern_id(v: salsa::InternId) -> Self { Self(v) } fn as_intern_id(&self) -> salsa::InternId { self.0 } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Arithmetic { pub lhs: ExprId, pub op: ArithmeticKind, pub rhs: ExprId, } impl Arithmetic { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lhs, op: _, rhs } = self; visitor.visit_expr(lhs)?; visitor.visit_expr(rhs)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lhs = transform.transform_expr(self.lhs)?; self.rhs = transform.transform_expr(self.rhs)?; Ok(Expr::Arithmetic(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Assign { pub lvalue: ExprId, pub expr: ExprId, } impl Assign { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lvalue, expr } = self; visitor.visit_expr(lvalue)?; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lvalue = transform.transform_expr(self.lvalue)?; self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Assign(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Block { pub stmts: Vec<ExprId>, } impl Block { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { stmts } = self; for expr in stmts { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for stmt in self.stmts.iter_mut() { *stmt = transform.transform_expr(*stmt)?; } Ok(Expr::Block(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Call { pub env: Option<EnvId>, pub name: IdentId, pub args: Vec<ExprId>, } impl Call { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { env: _, name: _, args } = self; for expr in args { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for expr in self.args.iter_mut() { *expr = transform.transform_expr(*expr)?; } Ok(Expr::Call(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Comparison { pub lhs: ExprId, pub op: ComparisonKind, pub rhs: ExprId, } impl Comparison { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lhs, op: _, rhs } = self; visitor.visit_expr(lhs)?; visitor.visit_expr(rhs)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lhs = transform.transform_expr(self.lhs)?; self.rhs = transform.transform_expr(self.rhs)?; Ok(Expr::Comparison(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Deref { pub expr: ExprId, } impl Deref { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { expr } = self; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Deref(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Dot { pub expr: ExprId, pub field_name: IdentId, } impl Dot { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { expr, field_name: _ } = self; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Dot(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct GlobalDataAddr { pub name: IdentId, } impl GlobalDataAddr { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(), V::Error> { let Self { name: _name } = self; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::GlobalDataAddr(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Identifier { pub env: Option<EnvId>, pub name: IdentId, } impl Identifier { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(), V::Error> { Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::Identifier(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct IfElse { pub condition: ExprId, pub then_body: ExprId, pub else_body: ExprId, } impl IfElse { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { condition, then_body, else_body } = self; visitor.visit_expr(condition)?; visitor.visit_expr(then_body)?; visitor.visit_expr(else_body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.condition = transform.transform_expr(self.condition)?; self.then_body = transform.transform_expr(self.then_body)?; self.else_body = transform.transform_expr(self.else_body)?; Ok(Expr::IfElse(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Index { pub base: ExprId, pub offset: ExprId, } impl Index { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { base, offset } = self; visitor.visit_expr(base)?; visitor.visit_expr(offset)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.base = transform.transform_expr(self.base)?; self.offset = transform.transform_expr(self.offset)?; Ok(Expr::Index(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Literal { pub value: i32, } impl Literal { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(), V::Error> { let Self { value: _value } = self; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::Literal(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Scope { pub scope_env: EnvId, pub decl_name: IdentId, pub decl_expr: ExprId, pub body: ExprId, } impl Scope { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { scope_env: _, decl_name: _, decl_expr, body, } = self; visitor.visit_expr(decl_expr)?; visitor.visit_expr(body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.decl_expr = transform.transform_expr(self.decl_expr)?; self.body = transform.transform_expr(self.body)?; Ok(Expr::Scope(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct StructInit { pub name: IdentId, pub fields: im_rc::HashMap<IdentId, ExprId>, } impl StructInit { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { name: _, fields } = self; for &expr in fields.values() { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for (_, expr_mut) in self.fields.iter_mut() { *expr_mut = transform.transform_expr(*expr_mut)?; } Ok(Expr::StructInit(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct WhileLoop { pub condition: ExprId, pub body: ExprId, } impl WhileLoop { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { condition, body } = self; visitor.visit_expr(condition)?; visitor.visit_expr(body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.condition = transform.transform_expr(self.condition)?; self.body = transform.transform_expr(self.body)?; Ok(Expr::WhileLoop(self)) } } macro_rules! expr_enum { ( $( [ $ty:ident, $visit:ident, $transform:ident, $map:ident ] ),* ) => { #[derive(Clone, Debug, Hash, PartialEq, Eq, TryInto)] #[try_into(owned, ref, ref_mut)] pub enum Expr { $( $ty($ty), )* } impl Expr { pub fn walk<V: ExprVisitor + ?Sized>(self, expr_id: ExprId, visitor: &mut V) -> Result<(), V::Error> { match self { $( Self::$ty(expr) => visitor.$visit(expr_id, expr), )* } } pub fn transform<T: ExprTransform + ?Sized>(self, expr_id: ExprId, transform: &mut T) -> Result<Self, T::Error> { match self { $( Self::$ty(expr) => transform.$transform(expr_id, expr), )* } } pub fn map<M: ExprMap + ?Sized>(self, map: &mut M, expr_id: ExprId) -> M::Value { match self { $( Self::$ty(expr) => map.$map(expr_id, expr), )* } } } pub trait ExprVisitor { type Error; fn lookup_expr(&self, expr: ExprId) -> Expr; $( #[allow(unused_variables)] fn $visit(&mut self, expr_id: ExprId, expr: $ty) -> Result<(), Self::Error> { expr.walk(self) } )* fn visit_expr(&mut self, expr: ExprId) -> Result<(), Self::Error> { self.lookup_expr(expr).walk(expr, self) } } pub trait ExprTransform { type Error; fn lookup_expr(&self, expr: ExprId) -> Expr; fn intern_expr(&self, expr: Expr) -> ExprId; $( #[allow(unused_variables)] fn $transform(&mut self, expr_id: ExprId, expr: $ty) -> Result<Expr, Self::Error> { expr.transform(self) } )* fn transform_expr(&mut self, expr: ExprId) -> Result<ExprId, Self::Error> { self.lookup_expr(expr).transform(expr, self).map(|expr| self.intern_expr(expr)) } } pub trait ExprMap { type Value; fn lookup_expr(&self, expr: ExprId) -> Expr; $( fn $map(&mut self, expr_id: ExprId, expr: $ty) -> Self::Value; )* fn map_expr(&mut self, expr: ExprId) -> Self::Value { self.lookup_expr(expr).map(self, expr) } } }; } expr_enum! { [ Arithmetic, visit_arithmetic, transform_arithmetic, map_arithmetic ], [ Assign, visit_assign, transform_assign, map_assign ], [ Block, visit_block, transform_block, map_block ], [ Call, visit_call, transform_call, map_call ], [ Comparison, visit_comparison, transform_comparison, map_comparison ], [ Deref, visit_deref, transform_deref, map_deref ], [ Dot, visit_dot, transform_dot, map_dot ], [ GlobalDataAddr, visit_global_data_addr, transform_global_data_addr, map_global_data_addr ], [ Identifier, visit_identifier, transform_identifier, map_identifier ], [ IfElse, visit_if_else, transform_if_else, map_if_else ], [ Index, visit_index, transform_index, map_index ], [ Literal, visit_literal, transform_literal, map_literal ], [ Scope, visit_scope, transform_scope, map_scope ], [ StructInit, visit_struct_init, transform_struct_init, map_struct_init ], [ WhileLoop, visit_while_loop, transform_while_loop, map_while_loop ] }
use crate::ast::{ArithmeticKind, ComparisonKind, EnvId, IdentId}; use derive_more::{Display, TryInto}; #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)] #[display(fmt = "{}", "_0")] pub struct ExprId(salsa::InternId); impl salsa::InternKey for ExprId { fn from_intern_id(v: salsa::InternId) -> Self { Self(v) } fn as_intern_id(&self) -> salsa::InternId { self.0 } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Arithmetic { pub lhs: ExprId, pub op: ArithmeticKind, pub rhs: ExprId, } impl Arithmetic { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lhs, op: _, rhs } = self; visitor.visit_expr(lhs)?; visitor.visit_expr(rhs)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lhs = transform.transform_expr(self.lhs)?; self.rhs = transform.transform_expr(self.rhs)?; Ok(Expr::Arithmetic(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Assign { pub lvalue: ExprId, pub expr: ExprId, } impl Assign { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lvalue, expr } = self; visitor.visit_expr(lvalue)?; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lvalue = transform.transform_expr(self.lvalue)?; self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Assign(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Block { pub stmts: Vec<ExprId>, } impl Block { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { stmts } = self; for expr in stmts { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for stmt in self.stmts.iter_mut() { *stmt = transform.transform_expr(*stmt)?; } Ok(Expr::Block(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Call { pub env: Option<EnvId>, pub name: IdentId, pub args: Vec<ExprId>, } impl Call { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { env: _, name: _, args } = self; for expr in args { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for expr in self.args.iter_mut() { *expr = transform.transform_expr(*expr)?; } Ok(Expr::Call(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Comparison { pub lhs: ExprId, pub op: ComparisonKind, pub rhs: ExprId, } impl Comparison { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { lhs, op: _, rhs } = self; visitor.visit_expr(lhs)?; visitor.visit_expr(rhs)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.lhs = transform.transform_expr(self.lhs)?; self.rhs = transform.transform_expr(self.rhs)?; Ok(Expr::Comparison(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Deref { pub expr: ExprId, } impl Deref { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { expr } = self; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Deref(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Dot { pub expr: ExprId, pub field_name: IdentId, } impl Dot { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { expr, field_name: _ } = self; visitor.visit_expr(expr)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.expr = transform.transform_expr(self.expr)?; Ok(Expr::Dot(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct GlobalDataAddr { pub name: IdentId, } impl GlobalDataAddr { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(), V::Error> { let Self { name: _name } = self; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::GlobalDataAddr(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Identifier { pub env: Option<EnvId>, pub name: IdentId, } impl Identifier { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(
pub enum Expr { $( $ty($ty), )* } impl Expr { pub fn walk<V: ExprVisitor + ?Sized>(self, expr_id: ExprId, visitor: &mut V) -> Result<(), V::Error> { match self { $( Self::$ty(expr) => visitor.$visit(expr_id, expr), )* } } pub fn transform<T: ExprTransform + ?Sized>(self, expr_id: ExprId, transform: &mut T) -> Result<Self, T::Error> { match self { $( Self::$ty(expr) => transform.$transform(expr_id, expr), )* } } pub fn map<M: ExprMap + ?Sized>(self, map: &mut M, expr_id: ExprId) -> M::Value { match self { $( Self::$ty(expr) => map.$map(expr_id, expr), )* } } } pub trait ExprVisitor { type Error; fn lookup_expr(&self, expr: ExprId) -> Expr; $( #[allow(unused_variables)] fn $visit(&mut self, expr_id: ExprId, expr: $ty) -> Result<(), Self::Error> { expr.walk(self) } )* fn visit_expr(&mut self, expr: ExprId) -> Result<(), Self::Error> { self.lookup_expr(expr).walk(expr, self) } } pub trait ExprTransform { type Error; fn lookup_expr(&self, expr: ExprId) -> Expr; fn intern_expr(&self, expr: Expr) -> ExprId; $( #[allow(unused_variables)] fn $transform(&mut self, expr_id: ExprId, expr: $ty) -> Result<Expr, Self::Error> { expr.transform(self) } )* fn transform_expr(&mut self, expr: ExprId) -> Result<ExprId, Self::Error> { self.lookup_expr(expr).transform(expr, self).map(|expr| self.intern_expr(expr)) } } pub trait ExprMap { type Value; fn lookup_expr(&self, expr: ExprId) -> Expr; $( fn $map(&mut self, expr_id: ExprId, expr: $ty) -> Self::Value; )* fn map_expr(&mut self, expr: ExprId) -> Self::Value { self.lookup_expr(expr).map(self, expr) } } }; } expr_enum! { [ Arithmetic, visit_arithmetic, transform_arithmetic, map_arithmetic ], [ Assign, visit_assign, transform_assign, map_assign ], [ Block, visit_block, transform_block, map_block ], [ Call, visit_call, transform_call, map_call ], [ Comparison, visit_comparison, transform_comparison, map_comparison ], [ Deref, visit_deref, transform_deref, map_deref ], [ Dot, visit_dot, transform_dot, map_dot ], [ GlobalDataAddr, visit_global_data_addr, transform_global_data_addr, map_global_data_addr ], [ Identifier, visit_identifier, transform_identifier, map_identifier ], [ IfElse, visit_if_else, transform_if_else, map_if_else ], [ Index, visit_index, transform_index, map_index ], [ Literal, visit_literal, transform_literal, map_literal ], [ Scope, visit_scope, transform_scope, map_scope ], [ StructInit, visit_struct_init, transform_struct_init, map_struct_init ], [ WhileLoop, visit_while_loop, transform_while_loop, map_while_loop ] }
), V::Error> { Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::Identifier(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct IfElse { pub condition: ExprId, pub then_body: ExprId, pub else_body: ExprId, } impl IfElse { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { condition, then_body, else_body } = self; visitor.visit_expr(condition)?; visitor.visit_expr(then_body)?; visitor.visit_expr(else_body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.condition = transform.transform_expr(self.condition)?; self.then_body = transform.transform_expr(self.then_body)?; self.else_body = transform.transform_expr(self.else_body)?; Ok(Expr::IfElse(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Index { pub base: ExprId, pub offset: ExprId, } impl Index { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { base, offset } = self; visitor.visit_expr(base)?; visitor.visit_expr(offset)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.base = transform.transform_expr(self.base)?; self.offset = transform.transform_expr(self.offset)?; Ok(Expr::Index(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Literal { pub value: i32, } impl Literal { pub fn walk<V: ExprVisitor + ?Sized>(self, _visitor: &mut V) -> Result<(), V::Error> { let Self { value: _value } = self; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(self, _transform: &mut T) -> Result<Expr, T::Error> { Ok(Expr::Literal(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct Scope { pub scope_env: EnvId, pub decl_name: IdentId, pub decl_expr: ExprId, pub body: ExprId, } impl Scope { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { scope_env: _, decl_name: _, decl_expr, body, } = self; visitor.visit_expr(decl_expr)?; visitor.visit_expr(body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.decl_expr = transform.transform_expr(self.decl_expr)?; self.body = transform.transform_expr(self.body)?; Ok(Expr::Scope(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct StructInit { pub name: IdentId, pub fields: im_rc::HashMap<IdentId, ExprId>, } impl StructInit { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { name: _, fields } = self; for &expr in fields.values() { visitor.visit_expr(expr)?; } Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { for (_, expr_mut) in self.fields.iter_mut() { *expr_mut = transform.transform_expr(*expr_mut)?; } Ok(Expr::StructInit(self)) } } #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct WhileLoop { pub condition: ExprId, pub body: ExprId, } impl WhileLoop { pub fn walk<V: ExprVisitor + ?Sized>(self, visitor: &mut V) -> Result<(), V::Error> { let Self { condition, body } = self; visitor.visit_expr(condition)?; visitor.visit_expr(body)?; Ok(()) } pub fn transform<T: ExprTransform + ?Sized>(mut self, transform: &mut T) -> Result<Expr, T::Error> { self.condition = transform.transform_expr(self.condition)?; self.body = transform.transform_expr(self.body)?; Ok(Expr::WhileLoop(self)) } } macro_rules! expr_enum { ( $( [ $ty:ident, $visit:ident, $transform:ident, $map:ident ] ),* ) => { #[derive(Clone, Debug, Hash, PartialEq, Eq, TryInto)] #[try_into(owned, ref, ref_mut)]
random
[ { "content": "fn lower_function(db: &dyn Lower, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)> {\n\n let mut envs = HashMap::new();\n\n let global_env = db.global_env()?;\n\n envs.insert(EnvId::GLOBAL, global_env.clone());\n\n\n\n let mut index = 2;\n\n let env = EnvId::from(NonZeroU32::new(index).unwrap());\n\n index += 1;\n\n\n\n let Env { mut bindings, ty_bindings } = global_env;\n\n let Function { signature, param_names, body } = db.function(name)?;\n\n let Signature { param_tys, return_ty: _ } = signature;\n\n for (index, (name, ty)) in param_names.into_iter().zip(param_tys).enumerate() {\n\n bindings.insert(name, (env, Binding::Param(Param { index, ty })));\n\n }\n\n\n\n envs.insert(env, Env { bindings, ty_bindings });\n\n\n\n let body = LowerExprTransform {\n\n db,\n\n env,\n\n envs: &mut envs,\n\n index: &mut index,\n\n }\n\n .transform_expr(body)?;\n\n\n\n Ok((Rc::new(envs), body))\n\n}\n\n\n", "file_path": "src/lower.rs", "rank": 0, "score": 195557.08565269556 }, { "content": "fn function_body(db: &dyn Parse, name: IdentId) -> Result<ExprId> {\n\n let Function {\n\n signature: _,\n\n param_names: _,\n\n body,\n\n } = db.function(name)?;\n\n\n\n Ok(body)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 1, "score": 153618.60576950858 }, { "content": "fn unify_function(db: &dyn TypeCk, name: IdentId) -> Result<Rc<HashMap<ExprId, TypeId>>> {\n\n let Signature { param_tys: _, return_ty } = db.function_signature(name)?;\n\n let (_, body) = db.lower_function(name)?;\n\n let mut context = UnifyExprContext::new(db, name);\n\n context.unify_expr(body, return_ty)?;\n\n Ok(Rc::new(context.into_expr_type_map()))\n\n}\n", "file_path": "src/type_ck.rs", "rank": 2, "score": 143440.72321156526 }, { "content": "fn compile<DB: Jit + ?Sized>(db: &mut DB, name: IdentId) -> Result<i32> {\n\n db.reset_module();\n\n db.clif_ctx(name)?;\n\n\n\n let signature = db.function_signature(name)?;\n\n let cl_func_id = db.clif_func_id(false, name, signature).unwrap();\n\n\n\n db.with_module_mut(|module| {\n\n module.finalize_definitions();\n\n\n\n let code = module.get_finalized_function(cl_func_id);\n\n let code = unsafe { mem::transmute::<*const u8, fn() -> i32>(code) };\n\n Ok(code())\n\n })\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 3, "score": 140687.4117908495 }, { "content": "fn global_env(db: &dyn Parse) -> Result<Env> {\n\n let mut bindings = im_rc::HashMap::new();\n\n let mut ty_bindings = im_rc::HashMap::new();\n\n\n\n for (&name, item) in db.module()?.iter() {\n\n match item.clone() {\n\n Item::Extern(item) => {\n\n let Extern { signature } = item;\n\n bindings.insert(name, (EnvId::GLOBAL, Binding::Extern(signature)));\n\n }\n\n\n\n Item::Function(item) => {\n\n let Function {\n\n signature,\n\n param_names: _,\n\n body: _,\n\n } = item;\n\n\n\n bindings.insert(name, (EnvId::GLOBAL, Binding::Function(signature)));\n\n }\n\n\n\n Item::Struct(item) => {\n\n ty_bindings.insert(name, TyBinding::Struct(item));\n\n }\n\n }\n\n }\n\n\n\n Ok(Env { bindings, ty_bindings })\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 6, "score": 125527.34505311336 }, { "content": "fn function(db: &dyn Parse, name: IdentId) -> Result<Function> {\n\n let functions = db.functions()?;\n\n let function = functions.get(&name).ok_or_else(|| error!(\"undefined function {}\", db.lookup_intern_ident(name)))?;\n\n Ok(function.clone())\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 7, "score": 122145.72244406413 }, { "content": "fn clif_ctx(db: &dyn Jit, name: IdentId) -> Result<Context> {\n\n let signature = db.function_signature(name)?;\n\n let (_, body) = db.lower_function(name)?;\n\n let mut ctx = ClifContext::new();\n\n ctx.func.signature = db.clif_signature(signature.clone())?;\n\n\n\n let func_ctx_pool = db.func_ctx_pool();\n\n let mut func_ctx = func_ctx_pool.pull(FunctionBuilderContext::new);\n\n func_ctx.clear();\n\n\n\n let mut builder = FunctionBuilder::new(&mut ctx.func, &mut func_ctx);\n\n\n\n let param_values = {\n\n let entry_block = builder.create_block();\n\n builder.append_block_params_for_function_params(entry_block);\n\n builder.switch_to_block(entry_block);\n\n builder.seal_block(entry_block);\n\n builder.block_params(entry_block).to_vec()\n\n };\n\n\n", "file_path": "src/jit.rs", "rank": 8, "score": 119956.74140821405 }, { "content": "fn function_signature(db: &dyn Parse, name: IdentId) -> Result<Signature> {\n\n let Function {\n\n signature,\n\n param_names: _,\n\n body: _,\n\n } = db.function(name)?;\n\n\n\n Ok(signature)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 9, "score": 119956.74140821405 }, { "content": "fn clif_data_id(db: &dyn Jit, name: IdentId) -> Result<ClifDataId> {\n\n let name = db.lookup_intern_ident(name);\n\n db.with_module_mut(|module| Ok(module.declare_data(&name, Linkage::Export, true, false)?))\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 10, "score": 114256.95379624996 }, { "content": "fn function_names(db: &dyn Parse) -> Result<Vec<IdentId>> {\n\n let functions = db.functions()?;\n\n let mut names = functions.keys().copied().collect::<Vec<_>>();\n\n names.sort_by_key(|&name| db.lookup_intern_ident(name));\n\n Ok(names)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 11, "score": 107856.60456841924 }, { "content": "fn compile<DB: Jit + ?Sized>(db: &mut DB) -> Result<i32> {\n\n let name = db.intern_ident(\"Main\".to_owned());\n\n assert_eq!(db.function_names().unwrap(), vec![name]);\n\n\n\n db.reset_module();\n\n db.clif_ctx(name)?;\n\n\n\n let signature = db.function_signature(name)?;\n\n let clif_func_id = db.clif_func_id(false, name, signature).unwrap();\n\n\n\n db.with_module_mut(|module| {\n\n module.finalize_definitions();\n\n\n\n let code = module.get_finalized_function(clif_func_id);\n\n let code = unsafe { mem::transmute::<*const u8, fn() -> i32>(code) };\n\n Ok(code())\n\n })\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 12, "score": 103625.6063878799 }, { "content": "fn module(db: &dyn Parse) -> Result<Rc<HashMap<IdentId, Item>>> {\n\n let input = db.source();\n\n let items = parser::module(&input)?;\n\n\n\n let items = items\n\n .into_iter()\n\n .map(|(name, i)| {\n\n let name = db.intern_ident(name);\n\n let i = db.intern_frontend_item(i);\n\n (name, i)\n\n })\n\n .collect();\n\n\n\n Ok(Rc::new(items))\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 13, "score": 99020.87242510184 }, { "content": "fn functions(db: &dyn Parse) -> Result<Rc<HashMap<IdentId, Function>>> {\n\n let items = db.module()?;\n\n\n\n let functions = items\n\n .iter()\n\n .filter_map(|(&name, item)| {\n\n let item = item.try_into().ok()?;\n\n Some((name, Function::clone(item)))\n\n })\n\n .collect();\n\n\n\n Ok(Rc::new(functions))\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 14, "score": 99020.87242510184 }, { "content": "fn clif_func_id(db: &dyn Jit, external: bool, name: IdentId, signature: Signature) -> Result<ClifFuncId> {\n\n let name = db.lookup_intern_ident(name);\n\n let signature = db.clif_signature(signature)?;\n\n let linkage = if external { Linkage::Import } else { Linkage::Export };\n\n db.with_module_mut(|module| Ok(module.declare_function(&name, linkage, &signature)?))\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 15, "score": 97515.92666467113 }, { "content": "fn do_test_jit<F>(name: &str, source_text: &str, assert: F) -> Result<()>\n\nwhere\n\n F: FnOnce(*const u8),\n\n{\n\n let mut db = Database::default();\n\n db.set_source(source_text.to_owned());\n\n\n\n for name in db.function_names()? {\n\n db.clif_ctx(name)?;\n\n }\n\n\n\n let name = db.intern_ident(name.to_owned());\n\n let signature = db.function_signature(name)?;\n\n let cl_func_id = db.clif_func_id(false, name, signature)?;\n\n\n\n let cl_data_id = db.clif_data_id(db.intern_ident(\"hello_string\".to_owned()))?;\n\n let mut data_ctx = DataContext::new();\n\n data_ctx.define(b\"hello world!\\0\".to_vec().into_boxed_slice());\n\n\n\n db.with_module_mut(|module| {\n", "file_path": "tests/jit_tests.rs", "rank": 16, "score": 97143.35877431126 }, { "content": "struct LowerExprTransform<'a, DB: ?Sized> {\n\n db: &'a DB,\n\n env: EnvId,\n\n envs: &'a mut HashMap<EnvId, Env>,\n\n index: &'a mut u32,\n\n}\n\n\n\nimpl<'a, DB: Intern + ?Sized> LowerExprTransform<'a, DB> {\n\n fn make_scope(&mut self, mut env: Env, decl_name: IdentId, decl_expr: ExprId, mut stmts: Vec<ExprId>) -> result::Result<Scope, Infallible> {\n\n let scope_env = EnvId::from(NonZeroU32::new(*self.index).unwrap());\n\n *self.index += 1;\n\n\n\n let decl_expr = self.transform_expr(decl_expr)?;\n\n env.bindings.insert(decl_name, (scope_env, Binding::Variable(Variable { decl_expr })));\n\n self.envs.insert(scope_env, env);\n\n\n\n LowerExprTransform {\n\n db: self.db,\n\n env: scope_env,\n\n envs: self.envs,\n", "file_path": "src/lower.rs", "rank": 17, "score": 93133.02057497992 }, { "content": "struct UnifyExprVisitor<'a, 'b, DB: ?Sized> {\n\n context: &'a mut UnifyExprContext<'b, DB>,\n\n ty: TypeId,\n\n}\n\n\n\nimpl<'a, 'b, DB: Lower + ?Sized> UnifyExprVisitor<'a, 'b, DB> {\n\n fn unify_type(&mut self, b: TypeId) -> Result<TypeId> {\n\n self.context.unify_type(self.ty, b)\n\n }\n\n}\n\n\n\nimpl<'a, 'b, DB: Lower + ?Sized> ExprMap for UnifyExprVisitor<'a, 'b, DB> {\n\n type Value = Result<TypeId>;\n\n\n\n fn lookup_expr(&self, expr: ExprId) -> Expr {\n\n self.context.db.lookup_intern_expr(expr)\n\n }\n\n\n\n fn map_arithmetic(&mut self, _expr_id: ExprId, expr: Arithmetic) -> Result<TypeId> {\n\n let Arithmetic { lhs, op: _, rhs } = expr;\n", "file_path": "src/unify.rs", "rank": 18, "score": 91787.7559526253 }, { "content": "#[test]\n\nfn test_source_update() -> Result<()> {\n\n let mut db = Database::default();\n\n\n\n {\n\n db.set_source(String::from(\n\n r\"\n", "file_path": "src/tests.rs", "rank": 19, "score": 90783.0101601461 }, { "content": "#[test]\n\nfn test_noop_update() -> Result<()> {\n\n let mut db = Database::default();\n\n let name = db.intern_ident(\"Main\".to_owned());\n\n\n\n let func1 = {\n\n db.set_source(String::from(\n\n r\"\n", "file_path": "src/tests.rs", "rank": 20, "score": 90783.0101601461 }, { "content": "struct PrettyPrintExprVisitor<'a, 'b, DB: ?Sized> {\n\n p: &'a PrettyPrintExpr<'a, DB>,\n\n f: &'a mut fmt::Formatter<'b>,\n\n}\n\n\n\nimpl<'a, 'b, DB: Lower + ?Sized> ExprVisitor for PrettyPrintExprVisitor<'a, 'b, DB> {\n\n type Error = fmt::Error;\n\n\n\n fn lookup_expr(&self, expr: ExprId) -> Expr {\n\n self.p.db.lookup_intern_expr(expr)\n\n }\n\n\n\n fn visit_arithmetic(&mut self, _expr_id: ExprId, expr: Arithmetic) -> fmt::Result {\n\n let Arithmetic { lhs, op, rhs } = expr;\n\n\n\n let op = match op {\n\n ArithmeticKind::Add => \"+\",\n\n ArithmeticKind::Sub => \"-\",\n\n ArithmeticKind::Mul => \"*\",\n\n ArithmeticKind::Div => \"/\",\n", "file_path": "src/pretty.rs", "rank": 21, "score": 88716.59333456933 }, { "content": "fn bench_compile(c: &mut Criterion) {\n\n let mut db = Database::default();\n\n let name = db.intern_ident(\"Main\".to_owned());\n\n let mut counter = 0;\n\n\n\n c.bench_function(\"compile\", |b| {\n\n b.iter(|| {\n\n db.set_source(format!(\n\n r\"\n", "file_path": "benches/bench.rs", "rank": 22, "score": 87396.26561643009 }, { "content": "fn bench_noop_change(c: &mut Criterion) {\n\n let mut db = Database::default();\n\n let name = db.intern_ident(\"Main\".to_owned());\n\n let mut counter = 0;\n\n\n\n c.bench_function(\"noop_change\", |b| {\n\n b.iter(|| {\n\n db.set_source(format!(\n\n r\"\n", "file_path": "benches/bench.rs", "rank": 23, "score": 85188.75471402501 }, { "content": "fn bench_typeck_big_function(c: &mut Criterion) {\n\n let mut db = Database::default();\n\n let name = db.intern_ident(\"Main\".to_owned());\n\n let mut s = String::new();\n\n let mut counter = 0;\n\n\n\n c.bench_function(\"typeck_big_function\", |b| {\n\n b.iter(|| {\n\n s.clear();\n\n writeln!(s, \"fn Main() -> i32 {{\")?;\n\n writeln!(s, \" A = 0\")?;\n\n\n\n for index in counter..counter + 1000 {\n\n writeln!(s, \" A = A + {}\", index)?;\n\n }\n\n\n\n writeln!(s, \" A\")?;\n\n writeln!(s, \"}}\")?;\n\n\n\n db.set_source(s.clone());\n\n db.unify_function(name)?;\n\n counter += 1;\n\n Ok(()) as Result<()>\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, bench_noop_change, bench_compile, bench_typeck_big_function);\n\ncriterion_main!(benches);\n", "file_path": "benches/bench.rs", "rank": 24, "score": 83170.79576364314 }, { "content": "fn do_test_ir(source_text: &str, ir: &str) -> Result<()> {\n\n let mut db = Database::default();\n\n db.set_source(source_text.to_owned());\n\n\n\n let mut actual_ir = String::new();\n\n for name in db.function_names()? {\n\n let ctx = db.clif_ctx(name)?;\n\n codegen::write_function(&mut actual_ir, &ctx.func, &DisplayFunctionAnnotations::default())?;\n\n }\n\n\n\n print!(\"{}\", actual_ir);\n\n assert_eq!(actual_ir, ir);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/jit_tests.rs", "rank": 26, "score": 71818.68332012923 }, { "content": "fn do_test_pretty(source_text: &str, pretty_text: &str) -> Result<()> {\n\n let mut db = Database::default();\n\n db.set_source(source_text.to_owned());\n\n\n\n let items = db.module()?;\n\n let mut item_names = items.keys().copied().collect::<Vec<_>>();\n\n item_names.sort_by_key(|&name| db.lookup_intern_ident(name));\n\n\n\n let mut actual_pretty_text = String::new();\n\n for name in item_names {\n\n match &items[&name] {\n\n Item::Extern(_) => writeln!(actual_pretty_text, \"extern fn {}\", db.lookup_intern_ident(name))?,\n\n Item::Function(item) => {\n\n let (_, body) = db.lower_function(name)?;\n\n let mut item = item.clone();\n\n item.body = body;\n\n write!(&mut actual_pretty_text, \"{}\", db.pretty_print_function(name, &item))?;\n\n }\n\n Item::Struct(_) => writeln!(actual_pretty_text, \"struct {}\", db.lookup_intern_ident(name))?,\n\n }\n\n }\n\n\n\n print!(\"{}\", actual_pretty_text);\n\n assert_eq!(actual_pretty_text, pretty_text);\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/jit_tests.rs", "rank": 27, "score": 70372.04193362544 }, { "content": "fn clif_struct_field_range(db: &dyn Jit, field_tys: Vec<TypeId>, index: usize) -> Result<Range<usize>> {\n\n let mut prev_acc = 0;\n\n let mut acc = 0;\n\n for &ty in &field_tys[..index + 1] {\n\n let ty = db.clif_type(ty)?;\n\n prev_acc = acc;\n\n acc += ty.len();\n\n }\n\n\n\n Ok(prev_acc..acc)\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 28, "score": 69911.07303004844 }, { "content": "fn compile_error<DB: Jit + ?Sized>(db: &mut DB, text: &str) {\n\n assert_eq!(compile(db).expect_err(\"expected compilation error\").to_string(), text);\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 29, "score": 67192.86694208514 }, { "content": "fn clif_signature(db: &dyn Jit, signature: Signature) -> Result<ClifSignature> {\n\n let Signature { param_tys, return_ty } = signature;\n\n let call_conv = db.clif_default_call_conv();\n\n let params = param_tys\n\n .into_iter()\n\n .map(|ty| db.clif_type(ty))\n\n .process_results(|i| i.flatten().map(AbiParam::new).collect())?;\n\n\n\n let returns = db.clif_type(return_ty)?.map(AbiParam::new);\n\n Ok(ClifSignature { call_conv, params, returns })\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 30, "score": 67028.80090021327 }, { "content": "fn clif_default_call_conv(db: &dyn Jit) -> CallConv {\n\n db.with_module(|module| module.isa().default_call_conv())\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 31, "score": 64639.85323633039 }, { "content": "fn clif_type(db: &dyn Jit, ty: TypeId) -> Result<Vec<ClifType>> {\n\n match db.lookup_intern_type(ty) {\n\n Type::Bool => Ok(vec![types::B1]),\n\n Type::Integer(ty) => {\n\n let Integer { signed: _signed, bits } = ty;\n\n Ok(vec![ClifType::int(bits).unwrap()])\n\n }\n\n Type::Named(ty) => {\n\n let ty_binding = db.ty_binding(ty)?;\n\n let Struct { field_names: _, field_tys } = ty_binding.try_into().unwrap();\n\n field_tys.into_iter().map(|ty| db.clif_type(ty)).process_results(|i| i.flatten().collect())\n\n }\n\n Type::Number => panic!(\"didn't expect number type to survive unification\"),\n\n Type::Pointer(_) => Ok(vec![db.clif_pointer_type()]),\n\n Type::Var(_) => panic!(\"didn't expect type variable to survive unification\"),\n\n Type::Unit => Ok(vec![]),\n\n }\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 32, "score": 63006.714139922085 }, { "content": "#[derive(Clone, Copy)]\n\nstruct Indent {\n\n count: u32,\n\n}\n\n\n\nimpl<'a> fmt::Display for Indent {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n for _ in 0..self.count {\n\n f.write_str(\" \")?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\npub struct PrettyPrintExpr<'a, DB: ?Sized> {\n\n db: &'a DB,\n\n function_name: IdentId,\n\n indent: Indent,\n\n expr: ExprId,\n\n}\n", "file_path": "src/pretty.rs", "rank": 33, "score": 56093.09534734895 }, { "content": "trait ProcessResultsExt<T, E>: IntoIterator<Item = result::Result<T, E>> + Sized {\n\n fn process_results<F, R>(self, processor: F) -> result::Result<R, E>\n\n where\n\n F: FnOnce(ProcessResults<Self::IntoIter, E>) -> R,\n\n {\n\n itertools::process_results(self, processor)\n\n }\n\n}\n\n\n\nimpl<I, T, E> ProcessResultsExt<T, E> for I where I: IntoIterator<Item = result::Result<T, E>> {}\n\n\n\npub use database::Database;\n\npub use intern::{Intern, InternExt};\n\npub use jit::{Context, Jit};\n\npub use lower::Lower;\n\npub use parse::Parse;\n\npub use pretty::{PrettyExt, PrettyPrintExpr, PrettyPrintFunction, PrettyPrintType};\n\npub use source::Source;\n\npub use target::{Target, TargetExt};\n\npub use type_ck::TypeCk;\n", "file_path": "src/lib.rs", "rank": 34, "score": 52504.81024479073 }, { "content": "#[salsa::query_group(SourceDatabase)]\n\npub trait Source {\n\n #[salsa::input]\n\n fn source(&self) -> String;\n\n}\n", "file_path": "src/source.rs", "rank": 35, "score": 51283.59576674712 }, { "content": "#[salsa::query_group(TargetDatabase)]\n\npub trait Target {\n\n #[salsa::input]\n\n fn module(&self) -> Rc<RefCell<SimpleJITModule>>;\n\n\n\n #[salsa::input]\n\n fn func_ctx_pool(&self) -> Rc<Pool<FunctionBuilderContext>>;\n\n}\n\n\n", "file_path": "src/target.rs", "rank": 36, "score": 51283.59576674712 }, { "content": "#[salsa::query_group(InternDatabase)]\n\npub trait Intern {\n\n #[salsa::interned]\n\n fn intern_ident(&self, ident: String) -> IdentId;\n\n\n\n #[salsa::interned]\n\n fn intern_expr(&self, expr: Expr) -> ExprId;\n\n\n\n #[salsa::interned]\n\n fn intern_type(&self, ty: Type) -> TypeId;\n\n\n\n fn bool_type(&self) -> TypeId;\n\n fn integer_type(&self, signed: bool, bits: u16) -> TypeId;\n\n fn number_type(&self) -> TypeId;\n\n fn pointer_type(&self, pointee: TypeId) -> TypeId;\n\n fn unit_type(&self) -> TypeId;\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 37, "score": 51283.59576674712 }, { "content": "struct FunctionTranslator<'a, 'b> {\n\n db: &'a dyn Jit,\n\n function_name: IdentId,\n\n builder: &'a mut FunctionBuilder<'b>,\n\n param_values: Vec<ClifValue>,\n\n expr_types: &'a HashMap<ExprId, TypeId>,\n\n clif_variables: HashMap<(EnvId, IdentId), Vec<ClifVariable>>,\n\n clif_functions: HashMap<(EnvId, IdentId), ClifFuncRef>,\n\n clif_data: HashMap<ClifDataId, ClifGlobalValue>,\n\n index: usize,\n\n}\n\n\n\nimpl<'a, 'b> FunctionTranslator<'a, 'b> {\n\n fn new(db: &'a dyn Jit, function_name: IdentId, builder: &'a mut FunctionBuilder<'b>, param_values: Vec<ClifValue>, expr_types: &'a HashMap<ExprId, TypeId>) -> Self {\n\n Self {\n\n db,\n\n function_name,\n\n builder,\n\n param_values,\n\n expr_types,\n", "file_path": "src/jit.rs", "rank": 38, "score": 50833.40796551008 }, { "content": "pub trait PrettyExt {\n\n fn pretty_print_expr(&self, function_name: IdentId, expr: ExprId) -> PrettyPrintExpr<'_, Self> {\n\n PrettyPrintExpr {\n\n db: self,\n\n function_name,\n\n indent: Indent { count: 0 },\n\n expr,\n\n }\n\n }\n\n\n\n fn pretty_print_function<'a>(&'a self, name: IdentId, function: &'a Function) -> PrettyPrintFunction<'a, Self> {\n\n PrettyPrintFunction { db: self, name, function }\n\n }\n\n\n\n fn pretty_print_type(&self, ty: TypeId) -> PrettyPrintType<'_, Self> {\n\n PrettyPrintType { db: self, ty }\n\n }\n\n}\n\n\n\nimpl<T: ?Sized> PrettyExt for T {}\n\n\n", "file_path": "src/pretty.rs", "rank": 39, "score": 49928.68769863744 }, { "content": "#[salsa::query_group(LowerDatabase)]\n\npub trait Lower: Parse {\n\n fn lower_function(&self, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)>;\n\n}\n\n\n", "file_path": "src/lower.rs", "rank": 40, "score": 48270.24644689144 }, { "content": "fn Other() -> i32 {{\n\n {}\n\n}}\n\n\",\n\n counter\n\n ));\n\n\n\n assert_eq!(compile(&mut db, name)?, 123);\n\n counter += 1;\n\n Ok(()) as Result<()>\n\n })\n\n });\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 41, "score": 47205.03072933959 }, { "content": "pub trait ParseExt: Parse {\n\n fn ty_binding(&self, name: IdentId) -> Result<TyBinding> {\n\n let Env { bindings: _, ty_bindings } = self.global_env()?;\n\n let ty_binding = ty_bindings.get(&name).ok_or_else(|| error!(\"using undeclared type {}\", self.lookup_intern_ident(name)))?;\n\n Ok(ty_binding.clone())\n\n }\n\n}\n\n\n\nimpl<T: Parse + ?Sized> ParseExt for T {}\n", "file_path": "src/parse.rs", "rank": 42, "score": 47042.60829627616 }, { "content": "pub trait InternExt: Intern {\n\n fn intern_frontend_expr(&self, expr: frontend::Expr) -> ExprId {\n\n use frontend::Expr as E;\n\n\n\n let expr = match expr {\n\n E::Arithmetic(lhs, op, rhs) => {\n\n let lhs = self.intern_frontend_expr(*lhs);\n\n let rhs = self.intern_frontend_expr(*rhs);\n\n Expr::Arithmetic(Arithmetic { lhs, op, rhs })\n\n }\n\n\n\n E::Assign(lvalue, expr) => {\n\n let lvalue = self.intern_frontend_expr(*lvalue);\n\n let expr = self.intern_frontend_expr(*expr);\n\n Expr::Assign(Assign { lvalue, expr })\n\n }\n\n\n\n E::Call(name, args) => {\n\n let name = self.intern_ident(name);\n\n let args = args.into_iter().map(|expr| self.intern_frontend_expr(expr)).collect();\n", "file_path": "src/intern.rs", "rank": 43, "score": 47042.60829627616 }, { "content": "pub trait TargetExt: Target {\n\n fn reset_module(&mut self) {\n\n let builder = SimpleJITBuilder::new(cranelift_module::default_libcall_names());\n\n let module = SimpleJITModule::new(builder);\n\n self.set_module(Rc::new(RefCell::new(module)));\n\n }\n\n\n\n fn with_module<T, F: FnOnce(&SimpleJITModule) -> T>(&self, f: F) -> T {\n\n f(&self.module().borrow())\n\n }\n\n\n\n fn with_module_mut<T, F: FnOnce(&mut SimpleJITModule) -> T>(&self, f: F) -> T {\n\n f(&mut self.module().borrow_mut())\n\n }\n\n}\n\n\n\nimpl<T: Target + ?Sized> TargetExt for T {}\n", "file_path": "src/target.rs", "rank": 44, "score": 47042.60829627616 }, { "content": "pub trait LowerExt: Lower {\n\n fn binding_pair(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<(EnvId, Binding)> {\n\n let (envs, _) = self.lower_function(function_name)?;\n\n let Env { bindings, ty_bindings: _ } = &envs[&env];\n\n let binding = bindings\n\n .get(&name)\n\n .ok_or_else(|| error!(\"reading from undeclared variable {}\", self.lookup_intern_ident(name)))?;\n\n\n\n Ok(binding.clone())\n\n }\n\n\n\n fn binding_decl_env(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<EnvId> {\n\n let (decl_env, _) = self.binding_pair(function_name, env, name)?;\n\n Ok(decl_env)\n\n }\n\n\n\n fn binding(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<Binding> {\n\n let (_, binding) = self.binding_pair(function_name, env, name)?;\n\n Ok(binding)\n\n }\n\n}\n\n\n\nimpl<T: Lower + ?Sized> LowerExt for T {}\n\n\n", "file_path": "src/lower.rs", "rank": 45, "score": 47042.60829627616 }, { "content": "#[salsa::query_group(TypeCkDatabase)]\n\npub trait TypeCk: Lower {\n\n fn unify_function(&self, name: IdentId) -> Result<Rc<HashMap<ExprId, TypeId>>>;\n\n}\n\n\n", "file_path": "src/type_ck.rs", "rank": 46, "score": 45925.11231490334 }, { "content": "fn Main() -> i32 {\n\n 123\n\n}\n\n\n", "file_path": "src/tests.rs", "rank": 47, "score": 45753.221962271164 }, { "content": "fn Zzz() -> i32 {\n\nbroken\n\n}\n\n\",\n\n ));\n\n\n\n db.unify_function(name)?\n\n };\n\n\n\n assert_eq!(func1, func2);\n\n Ok(())\n\n}\n", "file_path": "src/tests.rs", "rank": 48, "score": 45753.221962271164 }, { "content": "fn Main() -> i32 {{\n\n {}\n\n}}\n\n\",\n\n counter\n\n ));\n\n\n\n assert_eq!(compile(&mut db, name)?, counter);\n\n counter += 1;\n\n Ok(()) as Result<()>\n\n })\n\n });\n\n}\n\n\n", "file_path": "benches/bench.rs", "rank": 49, "score": 45753.221962271164 }, { "content": "#[salsa::query_group(ParseDatabase)]\n\npub trait Parse: Source + Intern {\n\n fn module(&self) -> Result<Rc<HashMap<IdentId, Item>>>;\n\n fn functions(&self) -> Result<Rc<HashMap<IdentId, Function>>>;\n\n fn function_names(&self) -> Result<Vec<IdentId>>;\n\n fn function(&self, name: IdentId) -> Result<Function>;\n\n fn function_body(&self, name: IdentId) -> Result<ExprId>;\n\n fn function_signature(&self, name: IdentId) -> Result<Signature>;\n\n fn global_env(&self) -> Result<Env>;\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 50, "score": 45600.32422610157 }, { "content": "fn refine<DB: Intern + ?Sized>(db: &DB, ty_bindings: &HashMap<i32, TypeId>, ty: TypeId) -> Type {\n\n match db.lookup_intern_type(ty) {\n\n Type::Var(ty) => ty_bindings.get(&ty).map_or(Type::Var(ty), |&ty| refine(db, ty_bindings, ty)),\n\n ty => ty,\n\n }\n\n}\n\n\n", "file_path": "src/unify.rs", "rank": 51, "score": 41093.26176228886 }, { "content": "#[salsa::query_group(JITDatabase)]\n\npub trait Jit: Parse + Lower + Target + TypeCk {\n\n fn clif_pointer_type(&self) -> ClifType;\n\n fn clif_default_call_conv(&self) -> CallConv;\n\n fn clif_type(&self, ty: TypeId) -> Result<Vec<ClifType>>;\n\n fn clif_struct_field_range(&self, field_tys: Vec<TypeId>, field_index: usize) -> Result<Range<usize>>;\n\n fn clif_signature(&self, signature: Signature) -> Result<ClifSignature>;\n\n fn clif_func_id(&self, external: bool, name: IdentId, signature: Signature) -> Result<ClifFuncId>;\n\n fn clif_data_id(&self, name: IdentId) -> Result<ClifDataId>;\n\n fn clif_ctx(&self, function_name: IdentId) -> Result<Context>;\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 52, "score": 40138.208228351694 }, { "content": "fn unit_type(db: &dyn Intern) -> TypeId {\n\n db.intern_type(Type::Unit)\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 53, "score": 36763.63858327262 }, { "content": "fn number_type(db: &dyn Intern) -> TypeId {\n\n db.intern_type(Type::Number)\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 54, "score": 36763.63858327262 }, { "content": "fn bool_type(db: &dyn Intern) -> TypeId {\n\n db.intern_type(Type::Bool)\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 55, "score": 36763.63858327262 }, { "content": "fn clif_pointer_type(db: &dyn Jit) -> ClifType {\n\n db.with_module(|module| module.target_config().pointer_type())\n\n}\n\n\n", "file_path": "src/jit.rs", "rank": 56, "score": 35929.765224084054 }, { "content": "fn pointer_type(db: &dyn Intern, pointee: TypeId) -> TypeId {\n\n db.intern_type(Type::Pointer(pointee))\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 57, "score": 32736.581246512374 }, { "content": "fn integer_type(db: &dyn Intern, signed: bool, bits: u16) -> TypeId {\n\n db.intern_type(Type::Integer(Integer { signed, bits }))\n\n}\n\n\n", "file_path": "src/intern.rs", "rank": 58, "score": 30700.271844320807 }, { "content": " Arithmetic(Box<Expr>, ArithmeticKind, Box<Expr>),\n\n Assign(Box<Expr>, Box<Expr>),\n\n Call(String, Vec<Expr>),\n\n Comparison(Box<Expr>, ComparisonKind, Box<Expr>),\n\n Deref(Box<Expr>),\n\n Dot(Box<Expr>, String),\n\n GlobalDataAddr(String),\n\n Identifier(String),\n\n IfElse(Box<Expr>, Vec<Expr>, Vec<Expr>),\n\n Index(Box<Expr>, Box<Expr>),\n\n Literal(i32),\n\n StructInit(String, Vec<(String, Box<Expr>)>),\n\n WhileLoop(Box<Expr>, Vec<Expr>),\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub enum Type {\n\n I32,\n\n Named(String),\n\n Pointer(Box<Type>),\n", "file_path": "src/frontend.rs", "rank": 79, "score": 26.560770928591843 }, { "content": " index: self.index,\n\n }\n\n .transform_stmts(&mut stmts)?;\n\n\n\n let body = self.db.intern_block(stmts);\n\n\n\n Ok(Scope {\n\n scope_env,\n\n decl_name,\n\n decl_expr,\n\n body,\n\n })\n\n }\n\n\n\n fn transform_stmts(&mut self, stmts: &mut Vec<ExprId>) -> result::Result<(), Infallible> {\n\n for (index, expr_mut) in stmts.iter_mut().enumerate() {\n\n if let Expr::Assign(assign) = self.db.lookup_intern_expr(*expr_mut) {\n\n let Assign { lvalue, expr: decl_expr } = assign;\n\n\n\n if let Expr::Identifier(lvalue) = self.db.lookup_intern_expr(lvalue) {\n", "file_path": "src/lower.rs", "rank": 80, "score": 26.130772139903264 }, { "content": " let Identifier { env: _, name } = lvalue;\n\n let env = self.envs[&self.env].clone();\n\n\n\n if !env.bindings.contains_key(&name) {\n\n let body = stmts.split_off(index + 1);\n\n let scope = self.make_scope(env, name, decl_expr, body)?;\n\n stmts[index] = self.intern_expr(Expr::Scope(scope));\n\n return Ok(());\n\n }\n\n }\n\n }\n\n\n\n *expr_mut = self.transform_expr(*expr_mut)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl<'a, DB: Intern + InternExt + ?Sized> ExprTransform for LowerExprTransform<'a, DB> {\n", "file_path": "src/lower.rs", "rank": 81, "score": 25.50450471380409 }, { "content": " let struct_lvalue = match self.db.lookup_intern_expr(expr) {\n\n Expr::Dot(expr) => self.translate_lvalue_dot(expr)?,\n\n Expr::Identifier(expr) => self.translate_lvalue_identifier(expr)?,\n\n _ => unreachable!(),\n\n };\n\n\n\n let range = self.struct_field_range(expr, field_name)?;\n\n Ok(struct_lvalue[range].to_vec())\n\n }\n\n\n\n fn translate_rvalue_dot(&mut self, expr: Dot) -> Result<Vec<ClifValue>> {\n\n let Dot { expr, field_name } = expr;\n\n let struct_value = self.map_expr(expr)?;\n\n let range = self.struct_field_range(expr, field_name)?;\n\n Ok(struct_value[range].to_vec())\n\n }\n\n\n\n fn translate_lvalue_identifier(&mut self, expr: Identifier) -> Result<Vec<ClifVariable>> {\n\n let Identifier { env, name } = expr;\n\n self.translate_variable(env.unwrap(), name)\n", "file_path": "src/jit.rs", "rank": 82, "score": 24.869441846559347 }, { "content": " Expr::Call(Call { env: None, name, args })\n\n }\n\n\n\n E::Comparison(lhs, op, rhs) => {\n\n let lhs = self.intern_frontend_expr(*lhs);\n\n let rhs = self.intern_frontend_expr(*rhs);\n\n Expr::Comparison(Comparison { lhs, op, rhs })\n\n }\n\n\n\n E::Deref(expr) => {\n\n let expr = self.intern_frontend_expr(*expr);\n\n Expr::Deref(Deref { expr })\n\n }\n\n\n\n E::Dot(expr, name) => {\n\n let expr = self.intern_frontend_expr(*expr);\n\n let name = self.intern_ident(name);\n\n Expr::Dot(Dot { expr, field_name: name })\n\n }\n\n\n", "file_path": "src/intern.rs", "rank": 83, "score": 24.64281766754769 }, { "content": "use crate::ast::expr::ExprId;\n\nuse crate::ast::ty::TypeId;\n\nuse crate::ast::{IdentId, Signature};\n\nuse derive_more::TryInto;\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Extern {\n\n pub signature: Signature,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Function {\n\n pub signature: Signature,\n\n pub param_names: Vec<IdentId>,\n\n pub body: ExprId,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Struct {\n\n pub field_names: Vec<IdentId>,\n", "file_path": "src/ast/item.rs", "rank": 84, "score": 24.622989079292765 }, { "content": "use crate::ast::IdentId;\n\nuse derive_more::Display;\n\n\n\n#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)]\n\n#[display(fmt = \"{}\", \"_0\")]\n\npub struct TypeId(salsa::InternId);\n\n\n\nimpl salsa::InternKey for TypeId {\n\n fn from_intern_id(v: salsa::InternId) -> Self {\n\n Self(v)\n\n }\n\n\n\n fn as_intern_id(&self) -> salsa::InternId {\n\n self.0\n\n }\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Integer {\n\n pub signed: bool,\n", "file_path": "src/ast/ty.rs", "rank": 85, "score": 23.77829720422946 }, { "content": " fn transform_call(&mut self, _expr_id: ExprId, mut expr: Call) -> result::Result<Expr, Infallible> {\n\n expr.env = Some(self.env);\n\n expr.transform(self)\n\n }\n\n\n\n fn transform_identifier(&mut self, _expr_id: ExprId, mut expr: Identifier) -> result::Result<Expr, Infallible> {\n\n expr.env = Some(self.env);\n\n expr.transform(self)\n\n }\n\n}\n", "file_path": "src/lower.rs", "rank": 86, "score": 23.32096963250487 }, { "content": "use derive_more::{Display, From, Into};\n\nuse im_rc::HashMap;\n\nuse std::num::NonZeroU32;\n\n\n\n#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display)]\n\n#[display(fmt = \"{}\", \"_0\")]\n\npub struct IdentId(salsa::InternId);\n\n\n\nimpl salsa::InternKey for IdentId {\n\n fn from_intern_id(v: salsa::InternId) -> Self {\n\n Self(v)\n\n }\n\n\n\n fn as_intern_id(&self) -> salsa::InternId {\n\n self.0\n\n }\n\n}\n\n\n\n#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, Display, From, Into)]\n\n#[display(fmt = \"{}\", \"_0\")]\n", "file_path": "src/ast/mod.rs", "rank": 87, "score": 23.293298936280575 }, { "content": " }\n\n\n\n fn translate_rvalue_identifier(&mut self, expr: Identifier) -> Result<Vec<ClifValue>> {\n\n let Identifier { env, name } = expr;\n\n let value = self.translate_variable(env.unwrap(), name)?;\n\n Ok(value.map(|variable| self.builder.use_var(variable)))\n\n }\n\n}\n\n\n\nimpl<'a, 'b> ExprMap for FunctionTranslator<'a, 'b> {\n\n type Value = Result<Vec<ClifValue>>;\n\n\n\n fn lookup_expr(&self, expr: ExprId) -> Expr {\n\n self.db.lookup_intern_expr(expr)\n\n }\n\n\n\n fn map_arithmetic(&mut self, _expr_id: ExprId, expr: Arithmetic) -> Result<Vec<ClifValue>> {\n\n let Arithmetic { lhs, op, rhs } = expr;\n\n let lhs = self.map_expr(lhs)?.into_single_item().unwrap();\n\n let rhs = self.map_expr(rhs)?.into_single_item().unwrap();\n", "file_path": "src/jit.rs", "rank": 88, "score": 23.288943039833317 }, { "content": "#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub enum ArithmeticKind {\n\n Add,\n\n Sub,\n\n Mul,\n\n Div,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub enum ComparisonKind {\n\n Eq,\n\n Ne,\n\n Lt,\n\n Le,\n\n Gt,\n\n Ge,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub enum Expr {\n", "file_path": "src/frontend.rs", "rank": 89, "score": 22.9231303566995 }, { "content": "pub struct EnvId(NonZeroU32);\n\n\n\nimpl EnvId {\n\n pub const GLOBAL: Self = Self(unsafe { NonZeroU32::new_unchecked(1) });\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Signature {\n\n pub param_tys: Vec<TypeId>,\n\n pub return_ty: TypeId,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Env {\n\n pub bindings: HashMap<IdentId, (EnvId, Binding)>,\n\n pub ty_bindings: HashMap<IdentId, TyBinding>,\n\n}\n\n\n\nmod binding;\n\nmod expr;\n", "file_path": "src/ast/mod.rs", "rank": 90, "score": 22.797622199574715 }, { "content": "\n\n fn visit_deref(&mut self, _expr_id: ExprId, expr: Deref) -> fmt::Result {\n\n let Deref { expr } = expr;\n\n write!(self.f, \"*{}\", self.p.with_expr(expr))\n\n }\n\n\n\n fn visit_dot(&mut self, _expr_id: ExprId, expr: Dot) -> fmt::Result {\n\n let Dot { expr, field_name: name } = expr;\n\n write!(self.f, \"{}.{}\", self.p.with_expr(expr), self.p.db.lookup_intern_ident(name))\n\n }\n\n\n\n fn visit_global_data_addr(&mut self, _expr_id: ExprId, expr: GlobalDataAddr) -> fmt::Result {\n\n let GlobalDataAddr { name } = expr;\n\n write!(self.f, \"&{}\", self.p.db.lookup_intern_ident(name))\n\n }\n\n\n\n fn visit_identifier(&mut self, _expr_id: ExprId, expr: Identifier) -> fmt::Result {\n\n let Identifier { env, name } = expr;\n\n write!(self.f, \"{}@\", self.p.db.lookup_intern_ident(name))?;\n\n if let Some(env) = env {\n", "file_path": "src/pretty.rs", "rank": 91, "score": 22.45209015037942 }, { "content": "use crate::ast::expr::ExprId;\n\nuse crate::ast::ty::TypeId;\n\nuse crate::ast::Signature;\n\nuse derive_more::TryInto;\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Param {\n\n pub index: usize,\n\n pub ty: TypeId,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\npub struct Variable {\n\n pub decl_expr: ExprId,\n\n}\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq, TryInto)]\n\n#[try_into(owned, ref, ref_mut)]\n\npub enum Binding {\n\n Extern(Signature),\n\n Function(Signature),\n\n Param(Param),\n\n Variable(Variable),\n\n}\n", "file_path": "src/ast/binding.rs", "rank": 92, "score": 22.210133814398823 }, { "content": " block_expr = Some(expr);\n\n }\n\n\n\n if let Some(expr) = block_expr {\n\n self.context.unify_expr(expr, self.ty)?;\n\n Ok(self.ty)\n\n } else {\n\n self.unify_type(self.context.db.unit_type())\n\n }\n\n }\n\n\n\n fn map_call(&mut self, _expr_id: ExprId, expr: Call) -> Result<TypeId> {\n\n let Call { env, name, args } = expr;\n\n let binding = self.context.db.binding(self.context.function_name, env.unwrap(), name)?;\n\n let Signature { param_tys, return_ty } = binding.try_into().map_err(|_| error!(\"only functions can be called\"))?;\n\n ensure_eq!(args.len(), param_tys.len());\n\n for (expr, ty) in args.into_iter().zip(param_tys) {\n\n self.context.unify_expr(expr, ty)?;\n\n }\n\n\n", "file_path": "src/unify.rs", "rank": 93, "score": 22.038171535673744 }, { "content": "use std::rc::Rc;\n\n\n\n#[derive(Clone)]\n\npub struct Context(Rc<ClifContext>);\n\n\n\nimpl PartialEq for Context {\n\n #[allow(clippy::vtable_address_comparisons)]\n\n fn eq(&self, other: &Self) -> bool {\n\n Rc::ptr_eq(&self.0, &other.0)\n\n }\n\n}\n\n\n\nimpl Eq for Context {}\n\n\n\nimpl ops::Deref for Context {\n\n type Target = ClifContext;\n\n\n\n fn deref(&self) -> &Self::Target {\n\n &self.0\n\n }\n\n}\n\n\n\n#[salsa::query_group(JITDatabase)]\n", "file_path": "src/jit.rs", "rank": 94, "score": 22.025212538286922 }, { "content": "use crate::ast::item::Struct;\n\nuse derive_more::TryInto;\n\n\n\n#[derive(Clone, Debug, Hash, PartialEq, Eq, TryInto)]\n\n#[try_into(owned, ref, ref_mut)]\n\npub enum TyBinding {\n\n Struct(Struct),\n\n}\n", "file_path": "src/ast/ty_binding.rs", "rank": 95, "score": 21.84360610973786 }, { "content": " .or_insert_with(|| db.with_module_mut(|module| module.declare_func_in_func(func, &mut builder.func)))\n\n };\n\n\n\n let arg_values = args\n\n .into_iter()\n\n .map(|expr| self.map_expr(expr))\n\n .process_results(|values| values.flatten().collect::<Vec<_>>())?;\n\n\n\n let call = self.builder.ins().call(local_callee, &arg_values);\n\n Ok(self.builder.inst_results(call).to_vec())\n\n }\n\n\n\n fn map_comparison(&mut self, _expr_id: ExprId, expr: Comparison) -> Result<Vec<ClifValue>> {\n\n let Comparison { lhs, op, rhs } = expr;\n\n let lhs = self.map_expr(lhs)?.into_single_item().unwrap();\n\n let rhs = self.map_expr(rhs)?.into_single_item().unwrap();\n\n\n\n let cc = match op {\n\n ComparisonKind::Eq => IntCC::Equal,\n\n ComparisonKind::Ne => IntCC::NotEqual,\n", "file_path": "src/jit.rs", "rank": 96, "score": 21.327477723854745 }, { "content": " let ty = self.context.db.number_type();\n\n self.context.unify_expr(lhs, ty)?;\n\n self.context.unify_expr(rhs, ty)?;\n\n self.unify_type(ty)\n\n }\n\n\n\n fn map_assign(&mut self, _expr_id: ExprId, expr: Assign) -> Result<TypeId> {\n\n let Assign { lvalue, expr } = expr;\n\n ensure!(matches!(self.context.db.lookup_intern_expr(lvalue), Expr::Deref(_) | Expr::Dot(_) | Expr::Identifier(_) | Expr::Index(_)));\n\n self.context.unify_expr(lvalue, self.ty)?;\n\n self.context.unify_expr(expr, self.ty)?;\n\n Ok(self.ty)\n\n }\n\n\n\n fn map_block(&mut self, _expr_id: ExprId, expr: Block) -> Result<TypeId> {\n\n let Block { stmts } = expr;\n\n let mut block_expr = None;\n\n for expr in stmts {\n\n let ty = self.context.new_var();\n\n self.context.unify_expr(expr, ty)?;\n", "file_path": "src/unify.rs", "rank": 97, "score": 21.26671864613794 }, { "content": " self.unify_type(return_ty)\n\n }\n\n\n\n fn map_comparison(&mut self, _expr_id: ExprId, expr: Comparison) -> Result<TypeId> {\n\n let Comparison { lhs, op: _, rhs } = expr;\n\n let ty = self.context.db.number_type();\n\n self.context.unify_expr(lhs, ty)?;\n\n self.context.unify_expr(rhs, ty)?;\n\n self.unify_type(self.context.db.bool_type())\n\n }\n\n\n\n fn map_deref(&mut self, _expr_id: ExprId, expr: Deref) -> Result<TypeId> {\n\n let Deref { expr } = expr;\n\n self.context.unify_expr(expr, self.context.db.pointer_type(self.ty))?;\n\n Ok(self.ty)\n\n }\n\n\n\n fn map_dot(&mut self, _expr_id: ExprId, expr: Dot) -> Self::Value {\n\n let Dot { expr, field_name } = expr;\n\n let struct_ty = self.context.new_var();\n", "file_path": "src/unify.rs", "rank": 98, "score": 21.16037860385981 }, { "content": "\n\n let value = match op {\n\n ArithmeticKind::Add => self.builder.ins().iadd(lhs, rhs),\n\n ArithmeticKind::Sub => self.builder.ins().isub(lhs, rhs),\n\n ArithmeticKind::Mul => self.builder.ins().imul(lhs, rhs),\n\n ArithmeticKind::Div => self.builder.ins().udiv(lhs, rhs),\n\n };\n\n\n\n Ok(vec![value])\n\n }\n\n\n\n fn map_assign(&mut self, _expr_id: ExprId, expr: Assign) -> Result<Vec<ClifValue>> {\n\n let Assign { lvalue, expr: assign_expr } = expr;\n\n let value = self.map_expr(assign_expr)?;\n\n let value2 = value.clone();\n\n\n\n match self.db.lookup_intern_expr(lvalue) {\n\n Expr::Deref(expr) => {\n\n let Deref { expr } = expr;\n\n let value = value.into_single_item().unwrap();\n", "file_path": "src/jit.rs", "rank": 99, "score": 21.09195778037342 } ]
Rust
07-rust/stm32f446/stm32f446_pac/src/otg_hs_global/otg_hs_gahbcfg.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register OTG_HS_GAHBCFG"] pub type R = crate::R<u32, super::OTG_HS_GAHBCFG>; #[doc = "Writer for register OTG_HS_GAHBCFG"] pub type W = crate::W<u32, super::OTG_HS_GAHBCFG>; #[doc = "Register OTG_HS_GAHBCFG `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_GAHBCFG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `GINT`"] pub type GINT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GINT`"] pub struct GINT_W<'a> { w: &'a mut W, } impl<'a> GINT_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 `HBSTLEN`"] pub type HBSTLEN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HBSTLEN`"] pub struct HBSTLEN_W<'a> { w: &'a mut W, } impl<'a> HBSTLEN_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 1)) | (((value as u32) & 0x0f) << 1); self.w } } #[doc = "Reader of field `DMAEN`"] pub type DMAEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMAEN`"] pub struct DMAEN_W<'a> { w: &'a mut W, } impl<'a> DMAEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `TXFELVL`"] pub type TXFELVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXFELVL`"] pub struct TXFELVL_W<'a> { w: &'a mut W, } impl<'a> TXFELVL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `PTXFELVL`"] pub type PTXFELVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PTXFELVL`"] pub struct PTXFELVL_W<'a> { w: &'a mut W, } impl<'a> PTXFELVL_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 } } impl R { #[doc = "Bit 0 - Global interrupt mask"] #[inline(always)] pub fn gint(&self) -> GINT_R { GINT_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 1:4 - Burst length/type"] #[inline(always)] pub fn hbstlen(&self) -> HBSTLEN_R { HBSTLEN_R::new(((self.bits >> 1) & 0x0f) as u8) } #[doc = "Bit 5 - DMA enable"] #[inline(always)] pub fn dmaen(&self) -> DMAEN_R { DMAEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 7 - TxFIFO empty level"] #[inline(always)] pub fn txfelvl(&self) -> TXFELVL_R { TXFELVL_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Periodic TxFIFO empty level"] #[inline(always)] pub fn ptxfelvl(&self) -> PTXFELVL_R { PTXFELVL_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Global interrupt mask"] #[inline(always)] pub fn gint(&mut self) -> GINT_W { GINT_W { w: self } } #[doc = "Bits 1:4 - Burst length/type"] #[inline(always)] pub fn hbstlen(&mut self) -> HBSTLEN_W { HBSTLEN_W { w: self } } #[doc = "Bit 5 - DMA enable"] #[inline(always)] pub fn dmaen(&mut self) -> DMAEN_W { DMAEN_W { w: self } } #[doc = "Bit 7 - TxFIFO empty level"] #[inline(always)] pub fn txfelvl(&mut self) -> TXFELVL_W { TXFELVL_W { w: self } } #[doc = "Bit 8 - Periodic TxFIFO empty level"] #[inline(always)] pub fn ptxfelvl(&mut self) -> PTXFELVL_W { PTXFELVL_W { w: self } } }
#[doc = "Reader of register OTG_HS_GAHBCFG"] pub type R = crate::R<u32, super::OTG_HS_GAHBCFG>; #[doc = "Writer for register OTG_HS_GAHBCFG"] pub type W = crate::W<u32, super::OTG_HS_GAHBCFG>; #[doc = "Register OTG_HS_GAHBCFG `reset()`'s with value 0"] impl crate::ResetValue for super::OTG_HS_GAHBCFG { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `GINT`"] pub type GINT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `GINT`"] pub struct GINT_W<'a> { w: &'a mut W, } impl<'a> GINT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r
HBSTLEN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HBSTLEN`"] pub struct HBSTLEN_W<'a> { w: &'a mut W, } impl<'a> HBSTLEN_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 1)) | (((value as u32) & 0x0f) << 1); self.w } } #[doc = "Reader of field `DMAEN`"] pub type DMAEN_R = crate::R<bool, bool>; #[doc = "Write proxy for field `DMAEN`"] pub struct DMAEN_W<'a> { w: &'a mut W, } impl<'a> DMAEN_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "Reader of field `TXFELVL`"] pub type TXFELVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXFELVL`"] pub struct TXFELVL_W<'a> { w: &'a mut W, } impl<'a> TXFELVL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `PTXFELVL`"] pub type PTXFELVL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PTXFELVL`"] pub struct PTXFELVL_W<'a> { w: &'a mut W, } impl<'a> PTXFELVL_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 } } impl R { #[doc = "Bit 0 - Global interrupt mask"] #[inline(always)] pub fn gint(&self) -> GINT_R { GINT_R::new((self.bits & 0x01) != 0) } #[doc = "Bits 1:4 - Burst length/type"] #[inline(always)] pub fn hbstlen(&self) -> HBSTLEN_R { HBSTLEN_R::new(((self.bits >> 1) & 0x0f) as u8) } #[doc = "Bit 5 - DMA enable"] #[inline(always)] pub fn dmaen(&self) -> DMAEN_R { DMAEN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 7 - TxFIFO empty level"] #[inline(always)] pub fn txfelvl(&self) -> TXFELVL_R { TXFELVL_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - Periodic TxFIFO empty level"] #[inline(always)] pub fn ptxfelvl(&self) -> PTXFELVL_R { PTXFELVL_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Global interrupt mask"] #[inline(always)] pub fn gint(&mut self) -> GINT_W { GINT_W { w: self } } #[doc = "Bits 1:4 - Burst length/type"] #[inline(always)] pub fn hbstlen(&mut self) -> HBSTLEN_W { HBSTLEN_W { w: self } } #[doc = "Bit 5 - DMA enable"] #[inline(always)] pub fn dmaen(&mut self) -> DMAEN_W { DMAEN_W { w: self } } #[doc = "Bit 7 - TxFIFO empty level"] #[inline(always)] pub fn txfelvl(&mut self) -> TXFELVL_W { TXFELVL_W { w: self } } #[doc = "Bit 8 - Periodic TxFIFO empty level"] #[inline(always)] pub fn ptxfelvl(&mut self) -> PTXFELVL_W { PTXFELVL_W { w: self } } }
"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 `HBSTLEN`"] pub type
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/stm32f0x1/stm32f0x1_pac/src/generic.rs", "rank": 0, "score": 192988.70578231275 }, { "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": 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/stm32l0x1/stm32l0x1_pac/src/generic.rs", "rank": 2, "score": 192988.70578231278 }, { "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": 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; 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": 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/stm32l0x1/stm32l0x1_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/stm32f446/stm32f446_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/stm32f0x1/stm32f0x1_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/stm32l0x1/rust-blink-l031k6/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/stm32f0x1/rust-blink-f031k6/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/stm32l0x1/stm32l0x1_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/stm32f446/stm32f446_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/stm32f0x1/stm32f0x1_pac/src/generic.rs", "rank": 19, "score": 79431.945204443 }, { "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": 20, "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": 21, "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": 22, "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": 23, "score": 57472.86116302295 }, { "content": " CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */\n", "file_path": "03-gpio/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 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": 37, "score": 53618.229617090416 }, { "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": 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 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": 42, "score": 52453.166317740535 }, { "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": 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_4.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_5.c", "rank": 46, "score": 52453.10204254395 }, { "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": 47, "score": 52451.65401680738 }, { "content": "BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL;\n", "file_path": "06-freertos/freertos/Source/include/mpu_prototypes.h", "rank": 48, "score": 52451.65401680738 }, { "content": "static void prvResetNextTaskUnblockTime( void );\n", "file_path": "06-freertos/freertos/Source/tasks.c", "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_4.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_5.c", "rank": 52, "score": 51332.692742444764 }, { "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": 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_xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) 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 portMAX_PRIGROUP_BITS\t\t\t\t( ( uint8_t ) 7 )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 60, "score": 50252.61011734772 }, { "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": 61, "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": 62, "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": 63, "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": 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_CM4F/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_CM0/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_SYSTICK_COUNT_FLAG_BIT\t\t( 1UL << 16UL )\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_PEND_SYSTICK_CLEAR_BIT\t\t( 1UL << 25UL )\n", "file_path": "06-freertos/freertos/Source/portable/GCC/ARM_CM4F/port.c", "rank": 75, "score": 48234.16899054223 }, { "content": "#[doc = \"Reader of register FS_GAHBCFG\"]\n\npub type R = crate::R<u32, super::FS_GAHBCFG>;\n\n#[doc = \"Writer for register FS_GAHBCFG\"]\n\npub type W = crate::W<u32, super::FS_GAHBCFG>;\n\n#[doc = \"Register FS_GAHBCFG `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::FS_GAHBCFG {\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 `GINT`\"]\n\npub type GINT_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `GINT`\"]\n\npub struct GINT_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> GINT_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/otg_fs_global/fs_gahbcfg.rs", "rank": 76, "score": 94.24298772747656 }, { "content": "#[doc = \"Reader of register CR\"]\n\npub type R = crate::R<u32, super::CR>;\n\n#[doc = \"Writer for register CR\"]\n\npub type W = crate::W<u32, super::CR>;\n\n#[doc = \"Register CR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR {\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 `RESET`\"]\n\npub type RESET_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `RESET`\"]\n\npub struct RESET_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RESET_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/crc/cr.rs", "rank": 78, "score": 90.4078660906435 }, { "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 `RTC_OUT_RMP`\"]\n\npub type RTC_OUT_RMP_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `RTC_OUT_RMP`\"]\n\npub struct RTC_OUT_RMP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> RTC_OUT_RMP_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/rtc/or.rs", "rank": 79, "score": 89.17099855862358 }, { "content": "#[doc = \"Reader of register SR\"]\n\npub type R = crate::R<u32, super::SR>;\n\n#[doc = \"Writer for register SR\"]\n\npub type W = crate::W<u32, super::SR>;\n\n#[doc = \"Register SR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SR {\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 `UIF`\"]\n\npub type UIF_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `UIF`\"]\n\npub struct UIF_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> UIF_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim6/sr.rs", "rank": 80, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register ALRMAR\"]\n\npub type R = crate::R<u32, super::ALRMAR>;\n\n#[doc = \"Writer for register ALRMAR\"]\n\npub type W = crate::W<u32, super::ALRMAR>;\n\n#[doc = \"Register ALRMAR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::ALRMAR {\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 `MSK4`\"]\n\npub type MSK4_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `MSK4`\"]\n\npub struct MSK4_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> MSK4_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/rtc/alrmar.rs", "rank": 81, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register CTRL\"]\n\npub type R = crate::R<u32, super::CTRL>;\n\n#[doc = \"Writer for register CTRL\"]\n\npub type W = crate::W<u32, super::CTRL>;\n\n#[doc = \"Register CTRL `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CTRL {\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 `ENABLE`\"]\n\npub type ENABLE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `ENABLE`\"]\n\npub struct ENABLE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ENABLE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/stk/ctrl.rs", "rank": 82, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register FPSCR\"]\n\npub type R = crate::R<u32, super::FPSCR>;\n\n#[doc = \"Writer for register FPSCR\"]\n\npub type W = crate::W<u32, super::FPSCR>;\n\n#[doc = \"Register FPSCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::FPSCR {\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 `IOC`\"]\n\npub type IOC_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `IOC`\"]\n\npub struct IOC_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> IOC_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/fpu/fpscr.rs", "rank": 83, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register CR2\"]\n\npub type R = crate::R<u32, super::CR2>;\n\n#[doc = \"Writer for register CR2\"]\n\npub type W = crate::W<u32, super::CR2>;\n\n#[doc = \"Register CR2 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR2 {\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 `OIS1N`\"]\n\npub type OIS1N_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `OIS1N`\"]\n\npub struct OIS1N_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> OIS1N_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/tim16/cr2.rs", "rank": 84, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register CCR1\"]\n\npub type R = crate::R<u32, super::CCR1>;\n\n#[doc = \"Writer for register CCR1\"]\n\npub type W = crate::W<u32, super::CCR1>;\n\n#[doc = \"Register CCR1 `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CCR1 {\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 `EN`\"]\n\npub type EN_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `EN`\"]\n\npub struct EN_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> EN_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/dma1/ccr1.rs", "rank": 85, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register AHB3RSTR\"]\n\npub type R = crate::R<u32, super::AHB3RSTR>;\n\n#[doc = \"Writer for register AHB3RSTR\"]\n\npub type W = crate::W<u32, super::AHB3RSTR>;\n\n#[doc = \"Register AHB3RSTR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::AHB3RSTR {\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 `FMCRST`\"]\n\npub type FMCRST_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `FMCRST`\"]\n\npub struct FMCRST_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> FMCRST_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/rcc/ahb3rstr.rs", "rank": 86, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register IER\"]\n\npub type R = crate::R<u32, super::IER>;\n\n#[doc = \"Writer for register IER\"]\n\npub type W = crate::W<u32, super::IER>;\n\n#[doc = \"Register IER `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::IER {\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 `ADRDYIE`\"]\n\npub type ADRDYIE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `ADRDYIE`\"]\n\npub struct ADRDYIE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> ADRDYIE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/adc/ier.rs", "rank": 87, "score": 88.76084142928104 }, { "content": "#[doc = \"Reader of register CCER\"]\n\npub type R = crate::R<u32, super::CCER>;\n\n#[doc = \"Writer for register CCER\"]\n\npub type W = crate::W<u32, super::CCER>;\n\n#[doc = \"Register CCER `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CCER {\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 `CC1NP`\"]\n\npub type CC1NP_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `CC1NP`\"]\n\npub struct CC1NP_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CC1NP_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim10/ccer.rs", "rank": 88, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register SR\"]\n\npub type R = crate::R<u32, super::SR>;\n\n#[doc = \"Writer for register SR\"]\n\npub type W = crate::W<u32, super::SR>;\n\n#[doc = \"Register SR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SR {\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 `CC1OF`\"]\n\npub type CC1OF_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `CC1OF`\"]\n\npub struct CC1OF_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CC1OF_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/tim16/sr.rs", "rank": 89, "score": 88.76084142928103 }, { "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 `PE`\"]\n\npub type PE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `PE`\"]\n\npub struct PE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> PE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/i2c1/cr1.rs", "rank": 90, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register DIER\"]\n\npub type R = crate::R<u32, super::DIER>;\n\n#[doc = \"Writer for register DIER\"]\n\npub type W = crate::W<u32, super::DIER>;\n\n#[doc = \"Register DIER `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DIER {\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 `CC1IE`\"]\n\npub type CC1IE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `CC1IE`\"]\n\npub struct CC1IE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> CC1IE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim11/dier.rs", "rank": 91, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register APB2RSTR\"]\n\npub type R = crate::R<u32, super::APB2RSTR>;\n\n#[doc = \"Writer for register APB2RSTR\"]\n\npub type W = crate::W<u32, super::APB2RSTR>;\n\n#[doc = \"Register APB2RSTR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::APB2RSTR {\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 `DBGRST`\"]\n\npub type DBGRST_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `DBGRST`\"]\n\npub struct DBGRST_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DBGRST_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/rcc/apb2rstr.rs", "rank": 92, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register DIER\"]\n\npub type R = crate::R<u32, super::DIER>;\n\n#[doc = \"Writer for register DIER\"]\n\npub type W = crate::W<u32, super::DIER>;\n\n#[doc = \"Register DIER `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::DIER {\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 `TDE`\"]\n\npub type TDE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `TDE`\"]\n\npub struct TDE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> TDE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim3/dier.rs", "rank": 93, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register CR\"]\n\npub type R = crate::R<u32, super::CR>;\n\n#[doc = \"Writer for register CR\"]\n\npub type W = crate::W<u32, super::CR>;\n\n#[doc = \"Register CR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::CR {\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 `TSEDGE`\"]\n\npub type TSEDGE_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `TSEDGE`\"]\n\npub struct TSEDGE_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> TSEDGE_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/rtc/cr.rs", "rank": 94, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register APB1ENR\"]\n\npub type R = crate::R<u32, super::APB1ENR>;\n\n#[doc = \"Writer for register APB1ENR\"]\n\npub type W = crate::W<u32, super::APB1ENR>;\n\n#[doc = \"Register APB1ENR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::APB1ENR {\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 `LPTIM1EN`\"]\n\npub type LPTIM1EN_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `LPTIM1EN`\"]\n\npub struct LPTIM1EN_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> LPTIM1EN_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32l0x1/stm32l0x1_pac/src/rcc/apb1enr.rs", "rank": 95, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register SR\"]\n\npub type R = crate::R<u32, super::SR>;\n\n#[doc = \"Writer for register SR\"]\n\npub type W = crate::W<u32, super::SR>;\n\n#[doc = \"Register SR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SR {\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 `DMAUDR2`\"]\n\npub type DMAUDR2_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `DMAUDR2`\"]\n\npub struct DMAUDR2_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> DMAUDR2_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/dac/sr.rs", "rank": 96, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register SWIER\"]\n\npub type R = crate::R<u32, super::SWIER>;\n\n#[doc = \"Writer for register SWIER\"]\n\npub type W = crate::W<u32, super::SWIER>;\n\n#[doc = \"Register SWIER `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SWIER {\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 `SWIER0`\"]\n\npub type SWIER0_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `SWIER0`\"]\n\npub struct SWIER0_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> SWIER0_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/exti/swier.rs", "rank": 97, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register SMCR\"]\n\npub type R = crate::R<u32, super::SMCR>;\n\n#[doc = \"Writer for register SMCR\"]\n\npub type W = crate::W<u32, super::SMCR>;\n\n#[doc = \"Register SMCR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::SMCR {\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 `MSM`\"]\n\npub type MSM_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `MSM`\"]\n\npub struct MSM_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> MSM_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f446/stm32f446_pac/src/tim9/smcr.rs", "rank": 98, "score": 88.76084142928103 }, { "content": "#[doc = \"Reader of register LCKR\"]\n\npub type R = crate::R<u32, super::LCKR>;\n\n#[doc = \"Writer for register LCKR\"]\n\npub type W = crate::W<u32, super::LCKR>;\n\n#[doc = \"Register LCKR `reset()`'s with value 0\"]\n\nimpl crate::ResetValue for super::LCKR {\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 `LCKK`\"]\n\npub type LCKK_R = crate::R<bool, bool>;\n\n#[doc = \"Write proxy for field `LCKK`\"]\n\npub struct LCKK_W<'a> {\n\n w: &'a mut W,\n\n}\n\nimpl<'a> LCKK_W<'a> {\n\n #[doc = r\"Sets the field bit\"]\n", "file_path": "07-rust/stm32f0x1/stm32f0x1_pac/src/gpiof/lckr.rs", "rank": 99, "score": 88.76084142928103 } ]
Rust
pkg-core/rate-core/src/actors/app_bind/actor/assets.rs
transparencies/rillrate
a1a6f76e84211224a85bb9fd92602d33f095229e
use super::AppBind; use crate::assets::Assets; use anyhow::Error; use async_trait::async_trait; use meio::{Context, IdOf, LiteTask, Scheduled, TaskEliminated, TaskError}; use reqwest::Url; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::fs::File; use tokio::io::AsyncReadExt; impl AppBind { pub(super) async fn init_assets(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> { let path = self .options .env_var .and_then(|env_var| std::env::var(env_var).ok()); if let Some(path) = path { if path.starts_with("http") { log::info!("Assets: env-url."); let url: Url = path.parse()?; ctx.spawn_task(FetchUiPack(url), (), ()); } else { log::info!("Assets: env-path."); self.assets = self.read_assets(&path).await?; log::warn!("Assets overriden to: {}", path); } } else if let Some(data) = self.options.embedded.as_ref() { log::info!("Assets: embedded."); let assets = Assets::parse(data)?; self.assets = AssetsMode::Packed(assets); log::info!("Embedded assets used."); } else if let Some(url) = self.options.url.clone() { log::info!("Assets: url."); ctx.spawn_task(FetchUiPack(url), (), ()); } Ok(()) } async fn read_assets(&mut self, path: &str) -> Result<AssetsMode, Error> { let asset_path = Path::new(path).to_path_buf(); if asset_path.exists() { let metadata = tokio::fs::metadata(&asset_path).await?; if metadata.is_dir() { Ok(AssetsMode::Local(asset_path)) } else { let data = read_file(&asset_path).await?; let assets = Assets::parse(&data)?; Ok(AssetsMode::Packed(assets)) } } else { Err(Error::msg(format!("Can't load assets from {}", path))) } } } pub async fn read_file(path: &Path) -> Result<Vec<u8>, Error> { let mut file = File::open(path).await?; let mut content = Vec::new(); file.read_to_end(&mut content).await?; Ok(content) } pub enum AssetsMode { Loading, Local(PathBuf), Packed(Assets), Failed(String), } pub struct FetchUiPack(Url); #[async_trait] impl LiteTask for FetchUiPack { type Output = Assets; async fn interruptable_routine(mut self) -> Result<Self::Output, Error> { log::info!("Fetching UI assets..."); let bytes = reqwest::get(self.0) .await? .error_for_status()? .bytes() .await?; let assets = Assets::parse(&bytes)?; Ok(assets) } } #[async_trait] impl TaskEliminated<FetchUiPack, ()> for AppBind { async fn handle( &mut self, _id: IdOf<FetchUiPack>, _tag: (), result: Result<Assets, TaskError>, ctx: &mut Context<Self>, ) -> Result<(), Error> { match result { Ok(assets) => { self.assets = AssetsMode::Packed(assets); log::info!("Assets pack attached."); Ok(()) } Err(err) => { self.assets = AssetsMode::Failed(err.to_string()); ctx.address() .schedule(ReInitAssets, Instant::now() + Duration::from_secs(5))?; log::error!("Can't load UI pack: {}", err); Err(err.into()) } } } } struct ReInitAssets; #[async_trait] impl Scheduled<ReInitAssets> for AppBind { async fn handle( &mut self, _: Instant, _: ReInitAssets, ctx: &mut Context<Self>, ) -> Result<(), Error> { self.init_assets(ctx).await?; Ok(()) } }
use super::AppBind; use crate::assets::Assets; use anyhow::Error; use async_trait::async_trait; use meio::{Context, IdOf, LiteTask, Scheduled, TaskEliminated, TaskError}; use reqwest::Url; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::fs::File; use tokio::io::AsyncReadExt; impl AppBind { pub(super) async fn init_assets(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> { let path = self .options .env_var .and_then(|env_var| std::env::var(env_var).ok()); if let Some(path) = path {
} else if let Some(data) = self.options.embedded.as_ref() { log::info!("Assets: embedded."); let assets = Assets::parse(data)?; self.assets = AssetsMode::Packed(assets); log::info!("Embedded assets used."); } else if let Some(url) = self.options.url.clone() { log::info!("Assets: url."); ctx.spawn_task(FetchUiPack(url), (), ()); } Ok(()) } async fn read_assets(&mut self, path: &str) -> Result<AssetsMode, Error> { let asset_path = Path::new(path).to_path_buf(); if asset_path.exists() { let metadata = tokio::fs::metadata(&asset_path).await?; if metadata.is_dir() { Ok(AssetsMode::Local(asset_path)) } else { let data = read_file(&asset_path).await?; let assets = Assets::parse(&data)?; Ok(AssetsMode::Packed(assets)) } } else { Err(Error::msg(format!("Can't load assets from {}", path))) } } } pub async fn read_file(path: &Path) -> Result<Vec<u8>, Error> { let mut file = File::open(path).await?; let mut content = Vec::new(); file.read_to_end(&mut content).await?; Ok(content) } pub enum AssetsMode { Loading, Local(PathBuf), Packed(Assets), Failed(String), } pub struct FetchUiPack(Url); #[async_trait] impl LiteTask for FetchUiPack { type Output = Assets; async fn interruptable_routine(mut self) -> Result<Self::Output, Error> { log::info!("Fetching UI assets..."); let bytes = reqwest::get(self.0) .await? .error_for_status()? .bytes() .await?; let assets = Assets::parse(&bytes)?; Ok(assets) } } #[async_trait] impl TaskEliminated<FetchUiPack, ()> for AppBind { async fn handle( &mut self, _id: IdOf<FetchUiPack>, _tag: (), result: Result<Assets, TaskError>, ctx: &mut Context<Self>, ) -> Result<(), Error> { match result { Ok(assets) => { self.assets = AssetsMode::Packed(assets); log::info!("Assets pack attached."); Ok(()) } Err(err) => { self.assets = AssetsMode::Failed(err.to_string()); ctx.address() .schedule(ReInitAssets, Instant::now() + Duration::from_secs(5))?; log::error!("Can't load UI pack: {}", err); Err(err.into()) } } } } struct ReInitAssets; #[async_trait] impl Scheduled<ReInitAssets> for AppBind { async fn handle( &mut self, _: Instant, _: ReInitAssets, ctx: &mut Context<Self>, ) -> Result<(), Error> { self.init_assets(ctx).await?; Ok(()) } }
if path.starts_with("http") { log::info!("Assets: env-url."); let url: Url = path.parse()?; ctx.spawn_task(FetchUiPack(url), (), ()); } else { log::info!("Assets: env-path."); self.assets = self.read_assets(&path).await?; log::warn!("Assets overriden to: {}", path); }
if_condition
[ { "content": "/// Install the engine.\n\npub fn install(name: impl ToString) -> Result<(), Error> {\n\n RillRate::install(name)\n\n}\n\n\n", "file_path": "rillrate/src/lib.rs", "rank": 0, "score": 234472.19064612628 }, { "content": "pub fn typed_var<T>(name: &'static str) -> Result<Option<T>, Error>\n\nwhere\n\n T: FromStr,\n\n Error: From<T::Err>,\n\n{\n\n match var(name) {\n\n Ok(value) => {\n\n let t = value.parse().map_err(Error::from)?;\n\n Ok(Some(t))\n\n }\n\n Err(VarError::NotPresent) => Ok(None),\n\n Err(err) => Err(err.into()),\n\n }\n\n}\n\n\n", "file_path": "pkg-core/rill-config/src/env.rs", "rank": 1, "score": 202059.71430397808 }, { "content": "/// Uninstall the engine.\n\npub fn uninstall() -> Result<(), Error> {\n\n RillRate::uninstall()\n\n}\n", "file_path": "rillrate/src/lib.rs", "rank": 2, "score": 194706.17629505153 }, { "content": "fn impl_tracer_opts(ast: &syn::DeriveInput) -> Result<TokenStream, Error> {\n\n let data = match &ast.data {\n\n syn::Data::Struct(data) => match &data.fields {\n\n syn::Fields::Named(fields) => {\n\n let ident = &ast.ident;\n\n let mut methods = Vec::new();\n\n for field in fields.named.iter() {\n\n let ident = field.ident.as_ref().ok_or_else(|| {\n\n Error::new(\n\n ast.span(),\n\n \"TracerOpts is not supported fields of tuple structs\",\n\n )\n\n })?;\n\n match extract_opt_type(field) {\n\n Some((cont, ty)) if cont == \"Option\" => {\n\n methods.push(quote! {\n\n pub fn #ident(mut self, value: impl Into<#ty>) -> Self {\n\n self.#ident = Some(value.into());\n\n self\n\n }\n", "file_path": "pkg-core/rill-derive/src/lib.rs", "rank": 3, "score": 191729.97780246244 }, { "content": "pub fn embed_config() -> Result<(), Error> {\n\n // TODO: Move to the separate create (rate-config)\n\n let root = env::var(\"CARGO_MANIFEST_DIR\")?;\n\n let out = env::var(\"OUT_DIR\")?;\n\n let source = format!(\"{}/config\", root);\n\n let dest = format!(\"{}/config.tar.gz\", out);\n\n rate_core::assets::build::pack(&source, &dest)?;\n\n println!(\"cargo:rustc-env=RR_CONFIG={}\", dest);\n\n Ok(())\n\n}\n", "file_path": "pkg-core/rate-config/src/build.rs", "rank": 4, "score": 183470.45139907824 }, { "content": "/// Generates a `Timestamp` of converts `SystemTime` to it.\n\n// TODO: How to avoid errors here?\n\npub fn time_to_ts(opt_system_time: Option<SystemTime>) -> Result<Timestamp, SystemTimeError> {\n\n opt_system_time\n\n .unwrap_or_else(SystemTime::now)\n\n .duration_since(SystemTime::UNIX_EPOCH)\n\n .map(Timestamp::from)\n\n}\n", "file_path": "pkg-packs/basis/src/frames/timed_event.rs", "rank": 5, "score": 179283.08476354496 }, { "content": "/// Adds a class to the VTag.\n\n/// You can also provide multiple classes separated by ascii whitespaces.\n\n///\n\n/// Note that this has a complexity of O(n),\n\n/// where n is the number of classes already in VTag plus\n\n/// the number of classes to be added.\n\nfn add_class(vtag: &mut VTag, class: impl Into<Classes>) {\n\n let mut classes: Classes = vtag\n\n .attributes\n\n .iter()\n\n .find(|(k, _)| *k == \"class\")\n\n .map(|(_, v)| Classes::from(v.to_owned()))\n\n .unwrap_or_default();\n\n classes.push(class);\n\n vtag.add_attribute(\"class\", classes.to_string());\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-app/src/markdown.rs", "rank": 6, "score": 160732.40042685752 }, { "content": "pub fn unpack<T, P>(v: T) -> Result<P, Error>\n\nwhere\n\n T: AsRef<[u8]>,\n\n P: for<'a> Deserialize<'a>,\n\n{\n\n let data = v.as_ref();\n\n flexbuffers::from_slice(data).map_err(Error::from)\n\n}\n", "file_path": "pkg-core/rill-protocol/src/encoding.rs", "rank": 7, "score": 159615.99821145085 }, { "content": "pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T, Error>\n\nwhere\n\n T: Deserialize<'a>,\n\n{\n\n //bincode::deserialize(v).map_err(Error::from)\n\n flexbuffers::from_slice(v).map_err(Error::from)\n\n //serde_json::from_slice(v).map_err(Error::from)\n\n}\n\n\n", "file_path": "pkg-core/rill-protocol/src/encoding.rs", "rank": 8, "score": 159448.4627997965 }, { "content": "/// Updates node directly by `NodeRef`\n\npub fn set_node(node_ref: &mut NodeRef, value: impl ToString) {\n\n let value = value.to_string();\n\n if let Some(node) = node_ref.cast::<HtmlElement>() {\n\n node.set_inner_text(&value);\n\n } else {\n\n log::error!(\n\n \"Can't cast node {:?} to HtmlElement set it to {}\",\n\n node_ref,\n\n value\n\n );\n\n }\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-ui/src/utils.rs", "rank": 9, "score": 156618.8157080993 }, { "content": "pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error>\n\nwhere\n\n T: Serialize,\n\n{\n\n //bincode::serialize(value).map_err(Error::from)\n\n flexbuffers::to_vec(value).map_err(Error::from)\n\n //serde_json::to_vec(value).map_err(Error::from)\n\n}\n\n\n", "file_path": "pkg-core/rill-protocol/src/encoding.rs", "rank": 10, "score": 152880.21432777663 }, { "content": "pub fn from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>\n\nwhere\n\n T: FromStr,\n\n T::Err: Display,\n\n D: Deserializer<'de>,\n\n{\n\n let s = <String>::deserialize(deserializer)?;\n\n T::from_str(&s).map_err(Error::custom)\n\n}\n", "file_path": "pkg-core/rate-config/src/config/cases.rs", "rank": 11, "score": 146690.5752308368 }, { "content": "pub fn pack<T: ?Sized, P: From<Vec<u8>>>(value: &T) -> Result<P, Error>\n\nwhere\n\n T: Serialize,\n\n{\n\n flexbuffers::to_vec(value).map_err(Error::from).map(P::from)\n\n}\n\n\n", "file_path": "pkg-core/rill-protocol/src/encoding.rs", "rank": 12, "score": 142731.31036801686 }, { "content": "fn render_default(path: &Path) -> Html {\n\n html! {\n\n <div class=\"d-flex flex-row align-items-center\">\n\n <div class=\"text-center p-1 mt-1 fw-bold\">{ \"No render!\" }</div>\n\n <div class=\"text-center p-1\">{ path }</div>\n\n </div>\n\n }\n\n}\n\n\n\n#[derive(Clone)]\n\npub struct RenderRule {\n\n pub render: RenderFn,\n\n pub size: Size,\n\n pub grow: bool,\n\n}\n\n\n\nimpl RenderRule {\n\n // TODO: Use `new(Width::Min(200), Height::Fixed(...))\n\n fn new<T, M>(width: i32, height: i32, grow: bool) -> Self\n\n where\n", "file_path": "pkg-dashboard/rate-app/src/cards/render.rs", "rank": 13, "score": 138820.27706544142 }, { "content": "pub fn sustain<Y: Copy>(mut iter: impl Iterator<Item = (i64, Y)>, last_x: i64) -> Vec<(i64, Y)> {\n\n let mut result = Vec::new();\n\n if let Some((mut prev_x, mut prev_y)) = iter.next() {\n\n result.push((prev_x, prev_y));\n\n for (next_x, next_y) in iter {\n\n let diff = next_x - prev_x;\n\n let shift = (diff as f32 * 0.1) as i64;\n\n result.push((next_x - shift, prev_y));\n\n result.push((next_x, next_y));\n\n prev_x = next_x;\n\n prev_y = next_y;\n\n }\n\n result.push((last_x, prev_y));\n\n }\n\n result\n\n}\n\n\n\n/*\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 14, "score": 131257.6241234625 }, { "content": "fn render_card<T, M>(path: &Path) -> Html\n\nwhere\n\n T: Component<Message = M, Properties = SingleFlowProps>,\n\n{\n\n html! {\n\n <T path=path.clone() />\n\n }\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-app/src/cards/render.rs", "rank": 15, "score": 131123.642660225 }, { "content": "pub fn client() -> Path {\n\n Path::single(\"@self\")\n\n}\n", "file_path": "pkg-core/rill-protocol/src/flow/location.rs", "rank": 16, "score": 126496.60278525302 }, { "content": "pub fn server() -> Path {\n\n Path::single(\"@server\")\n\n}\n\n\n", "file_path": "pkg-core/rill-protocol/src/flow/location.rs", "rank": 17, "score": 126496.60278525302 }, { "content": "pub fn js_err(value: JsValue) -> Error {\n\n Error::msg(value.as_string().unwrap_or_else(|| \"js error\".into()))\n\n}\n\n*/\n\n\n", "file_path": "pkg-dashboard/rate-ui/src/utils.rs", "rank": 18, "score": 115512.08379842526 }, { "content": "pub fn remove_class(node_ref: &mut NodeRef, class: &str) {\n\n use js_sys::Array;\n\n use wasm_bindgen::JsValue;\n\n\n\n if let Some(node) = node_ref.cast::<HtmlElement>() {\n\n let array = Array::new();\n\n array.push(&JsValue::from_str(class));\n\n node.class_list().remove(&array);\n\n }\n\n}\n\n*/\n", "file_path": "pkg-dashboard/rate-ui/src/utils.rs", "rank": 19, "score": 106896.02642057594 }, { "content": "fn extract_opt_type(field: &Field) -> Option<(&syn::Ident, &syn::Type)> {\n\n let path = if let syn::Type::Path(type_path) = &field.ty {\n\n if type_path.qself.is_some() {\n\n return None;\n\n } else {\n\n &type_path.path\n\n }\n\n } else {\n\n return None;\n\n };\n\n let segment = path.segments.last()?;\n\n /*\n\n if segment.ident != \"Option\" {\n\n return None;\n\n }\n\n */\n\n let generic_params =\n\n if let syn::PathArguments::AngleBracketed(generic_params) = &segment.arguments {\n\n generic_params\n\n } else {\n\n return None;\n\n };\n\n if let syn::GenericArgument::Type(ty) = generic_params.args.first()? {\n\n Some((&segment.ident, ty))\n\n } else {\n\n None\n\n }\n\n}\n", "file_path": "pkg-core/rill-derive/src/lib.rs", "rank": 20, "score": 104939.75362434091 }, { "content": "/// Wraps with timed event\n\npub fn timed<T>(event: T) -> Option<TimedEvent<T>> {\n\n time_to_ts(None)\n\n .map(move |timestamp| TimedEvent { timestamp, event })\n\n .ok()\n\n}\n\n\n", "file_path": "pkg-packs/basis/src/frames/timed_event.rs", "rank": 21, "score": 104939.75362434091 }, { "content": "pub trait WiredWidget<M>: Widget<Tag = Option<Path>, Meta = M> {\n\n type Flow: Flow;\n\n\n\n fn state_changed(&mut self, _reloaded: bool, _ctx: &mut Context<Self>) {}\n\n\n\n fn state_update(\n\n &mut self,\n\n _tag: &Path,\n\n _event: &<Self::Flow as Flow>::Event,\n\n _reloaded: &mut bool,\n\n _ctx: &mut Context<Self>,\n\n ) {\n\n }\n\n}\n\n\n\n#[derive(Properties, Clone, PartialEq)]\n\npub struct SingleFlowProps {\n\n pub path: Path,\n\n #[prop_or_default]\n\n pub triggered: Option<Callback<()>>,\n", "file_path": "pkg-dashboard/rate-ui/src/widget/wired_widget.rs", "rank": 22, "score": 102710.58432159078 }, { "content": "pub fn set_style(node_ref: &mut NodeRef, key: &str, value: &str) {\n\n if let Some(node) = node_ref.cast::<HtmlElement>() {\n\n if let Err(_err) = node.style().set_property(key, value) {\n\n log::error!(\"Can't set property of {:?} to {}={}\", node_ref, key, value);\n\n }\n\n } else {\n\n log::error!(\n\n \"Can't cast node {:?} to HtmlElement to update style {}={}\",\n\n node_ref,\n\n key,\n\n value\n\n );\n\n }\n\n}\n\n\n\n/*\n", "file_path": "pkg-dashboard/rate-ui/src/utils.rs", "rank": 23, "score": 100534.52725020194 }, { "content": "pub fn add() {\n\n let mut tab = Layout::new([\"Prog Layout\", \"First Tab\"]);\n\n tab.set_container(Align {\n\n alignment: Alignment::TOP_CENTER,\n\n child: Text {\n\n text: \"Text\".into(),\n\n align: TextAlign::Center,\n\n }\n\n .boxed(),\n\n });\n\n tab.register();\n\n}\n", "file_path": "demo/src/layout.rs", "rank": 24, "score": 68417.86612252981 }, { "content": "fn main() {\n\n wasm_logger::init(wasm_logger::Config::new(log::Level::Trace));\n\n yew::start_app::<rate_app::app::App>();\n\n}\n", "file_path": "pkg-dashboard/rate-app/src/main.rs", "rank": 25, "score": 68134.14149272238 }, { "content": "pub fn loading_view() -> Html {\n\n html! {\n\n <common::Spinner />\n\n }\n\n}\n\n*/\n\n\n\npub struct SingleHook;\n\n\n\nimpl AgentHook for SingleHook {\n\n type Agent = LiveAgent;\n\n}\n\n\n\nimpl<T> OnWireEvent<SingleHook> for T\n\nwhere\n\n T: WiredWidget<SingleFlowMeta<Self>>,\n\n{\n\n fn on_wire(\n\n &mut self,\n\n tag: &Self::Tag,\n", "file_path": "pkg-dashboard/rate-ui/src/widget/wired_widget.rs", "rank": 26, "score": 60056.54931683212 }, { "content": "pub fn sustain_soft<Y: Copy>(\n\n mut iter: impl Iterator<Item = (i64, Y)>,\n\n last: Option<i64>,\n\n) -> Vec<(i64, Y)> {\n\n let mut result = Vec::new();\n\n if let Some((mut prev_x, mut prev_y)) = iter.next() {\n\n result.push((prev_x, prev_y));\n\n for (next_x, next_y) in iter {\n\n let diff = ((next_x - prev_x) as f32 * 0.2) as i64;\n\n result.push((next_x - diff, prev_y));\n\n result.push((next_x, next_y));\n\n prev_x = next_x;\n\n prev_y = next_y;\n\n }\n\n if let Some(last_x) = last {\n\n result.push((last_x, prev_y));\n\n }\n\n }\n\n result\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 27, "score": 59444.95254952021 }, { "content": "fn make_tag(t: Tag) -> VTag {\n\n match t {\n\n Tag::Paragraph => VTag::new(\"p\"),\n\n Tag::Heading(n) => {\n\n assert!(n > 0);\n\n assert!(n < 7);\n\n VTag::new(format!(\"h{}\", n))\n\n }\n\n Tag::BlockQuote => {\n\n let mut el = VTag::new(\"blockquote\");\n\n el.add_attribute(\"class\", \"blockquote\");\n\n el\n\n }\n\n Tag::CodeBlock(code_block_kind) => {\n\n let mut el = VTag::new(\"code\");\n\n\n\n if let CodeBlockKind::Fenced(lang) = code_block_kind {\n\n // Different color schemes may be used for different code blocks,\n\n // but a different library (likely js based at the moment) would be necessary to actually provide the\n\n // highlighting support by locating the language classes and applying dom transforms\n", "file_path": "pkg-dashboard/rate-app/src/markdown.rs", "rank": 28, "score": 59444.95254952021 }, { "content": "fn rev(s: String) -> String {\n\n s.chars().rev().collect()\n\n}\n\n\n\nimpl WiredWidget<SingleFlowMeta<Self>> for CounterCardWidget {\n\n type Flow = CounterState;\n\n\n\n fn state_changed(&mut self, _reloaded: bool, ctx: &mut Context<Self>) {\n\n ctx.redraw();\n\n }\n\n}\n", "file_path": "pkg-dashboard/rate-app/src/cards/prime/visual/counter.rs", "rank": 29, "score": 58616.3845447043 }, { "content": "/// Renders a string of Markdown to HTML with the default options (footnotes\n\n/// disabled, tables enabled).\n\npub fn render(src: &str) -> Html {\n\n let mut elems = vec![];\n\n let mut spine = vec![];\n\n\n\n macro_rules! add_child {\n\n ($child:expr) => {{\n\n let l = spine.len();\n\n assert_ne!(l, 0);\n\n spine[l - 1].add_child($child);\n\n }};\n\n }\n\n\n\n let mut options = Options::empty();\n\n options.insert(Options::ENABLE_TABLES);\n\n\n\n for ev in Parser::new_ext(src, options) {\n\n match ev {\n\n Event::Start(tag) => {\n\n spine.push(make_tag(tag));\n\n }\n", "file_path": "pkg-dashboard/rate-app/src/markdown.rs", "rank": 30, "score": 58173.23718272002 }, { "content": "pub fn formatter_sec(input: &i64) -> String {\n\n let input = input.abs();\n\n format!(\"{} sec\", input / 1_000)\n\n /*\n\n if input % 60_000 == 0 {\n\n format!(\"{} min\", input / 60_000)\n\n } else {\n\n format!(\"{} sec\", input / 1_000)\n\n }\n\n */\n\n}\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 31, "score": 57340.167651028496 }, { "content": "pub fn formatter_gb(input: &f32) -> String {\n\n format!(\"{:.0} Gb\", input / 1_000_000.0)\n\n}\n\n*/\n\n\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 32, "score": 57340.167651028496 }, { "content": "pub fn formatter_pct(input: &f32) -> String {\n\n format!(\"{:.0} %\", input)\n\n}\n\n*/\n\n\n\n/*\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 33, "score": 57340.167651028496 }, { "content": "pub fn formatter_plain(input: &f32) -> String {\n\n input.to_string()\n\n}\n\n\n\n/*\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 34, "score": 57340.167651028496 }, { "content": "pub fn formatter_kib(input: &f32) -> String {\n\n format!(\"{:.0} KiB/s\", input / 1_024.0)\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 35, "score": 57340.167651028496 }, { "content": "fn preffered_sizes() -> HashMap<StreamType, RenderRule> {\n\n use super::prime;\n\n use rrpack_prime::{control, transparent, visual};\n\n let mut preffered_sizes: HashMap<StreamType, RenderRule> = HashMap::new();\n\n\n\n preffered_sizes.insert(\n\n transparent::alert::AlertState::stream_type(),\n\n RenderRule::new::<prime::transparent::AlertCard, _>(100, 100, false),\n\n );\n\n\n\n preffered_sizes.insert(\n\n control::click::ClickState::stream_type(),\n\n RenderRule::new::<prime::control::ClickCard, _>(140, 100, false),\n\n );\n\n preffered_sizes.insert(\n\n control::input::InputState::stream_type(),\n\n RenderRule::new::<prime::control::InputCard, _>(300, 100, false),\n\n );\n\n preffered_sizes.insert(\n\n control::selector::SelectorState::stream_type(),\n", "file_path": "pkg-dashboard/rate-app/src/cards/render.rs", "rank": 36, "score": 56339.19569767013 }, { "content": "#[proc_macro_derive(TracerOpts)]\n\npub fn tracer_opts(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n match impl_tracer_opts(&input) {\n\n Ok(output) => output,\n\n Err(error) => error.to_compile_error().into(),\n\n }\n\n}\n\n\n", "file_path": "pkg-core/rill-derive/src/lib.rs", "rank": 37, "score": 55789.522491546064 }, { "content": "pub fn sustain_sharp<X: Copy, Y: Copy>(\n\n mut iter: impl Iterator<Item = (X, Y)>,\n\n last: Option<X>,\n\n) -> Vec<(X, Y)> {\n\n let mut result = Vec::new();\n\n if let Some((prev_x, mut prev_y)) = iter.next() {\n\n result.push((prev_x, prev_y));\n\n for (next_x, next_y) in iter {\n\n result.push((next_x, prev_y));\n\n result.push((next_x, next_y));\n\n //prev_x = next_x;\n\n prev_y = next_y;\n\n }\n\n if let Some(last_x) = last {\n\n result.push((last_x, prev_y));\n\n }\n\n }\n\n result\n\n}\n\n*/\n\n\n", "file_path": "pkg-dashboard/rate-app/src/canvas.rs", "rank": 38, "score": 55409.116626109826 }, { "content": "pub fn spinner(reason: &'static str) -> Html {\n\n html! {\n\n <Spinner reason=reason />\n\n }\n\n}\n\n\n\n#[derive(Debug, Properties, Clone)]\n\npub struct Props {\n\n pub reason: &'static str,\n\n}\n\n\n\npub struct Spinner {\n\n reason: &'static str,\n\n}\n\n\n\nimpl Component for Spinner {\n\n type Message = ();\n\n type Properties = Props;\n\n\n\n fn create(props: Self::Properties, _link: ComponentLink<Self>) -> Self {\n", "file_path": "pkg-dashboard/rate-app/src/blocks/spinner.rs", "rank": 39, "score": 55409.116626109826 }, { "content": "fn unpack_single(element: SingleBoxedElement) -> basis::BoxedElement {\n\n match element {\n\n Some(boxed) => boxed.into(),\n\n None => Box::new(Element::Spacer(Spacer {\n\n flex: None,\n\n maintenance: Some(true),\n\n }))\n\n .into(),\n\n }\n\n}\n\n\n\npub type MultiBoxedElement = Option<Vec<Element>>;\n\n\n", "file_path": "pkg-core/rate-config/src/config/cases.rs", "rank": 40, "score": 54366.28250793881 }, { "content": "fn splitnum(value: i64) -> (String, String, String) {\n\n let s = value.to_string();\n\n let mut chars = s.chars().rev();\n\n let mut ones: String = (&mut chars).take(3).collect();\n\n let mut thousands: String = (&mut chars).take(3).collect();\n\n let mut millions: String = chars.collect();\n\n const NO_PRINT: char = '_';\n\n if ones.is_empty() {\n\n ones.push(NO_PRINT);\n\n }\n\n if thousands.is_empty() {\n\n thousands.push(NO_PRINT);\n\n }\n\n if millions.is_empty() {\n\n millions.push(NO_PRINT);\n\n }\n\n (rev(millions), rev(thousands), rev(ones))\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-app/src/cards/prime/visual/counter.rs", "rank": 41, "score": 53924.22182156189 }, { "content": "pub trait Supervisor: Actor + InteractionHandler<link::GetClientAssistant<Self>> {\n\n type ClientAssistant: Actor\n\n + StartedBy<ClientSession<Self>>\n\n + InterruptedBy<ClientSession<Self>>\n\n + ActionHandler<link::ServiceIncoming>;\n\n}\n", "file_path": "pkg-core/rate-core/src/actors/supervisor/actor.rs", "rank": 42, "score": 53568.041502819615 }, { "content": "fn render_group((name, streams): (EntryId, ResolvedGroup)) -> Html {\n\n html! {\n\n <div yew=\"render_group\">\n\n <div class=\"text-primary p-2\">{ name }</div>\n\n <super::GroupViewer streams=streams />\n\n </div>\n\n }\n\n}\n\n\n\nimpl NotificationHandler<DataChanged<ExplorerState>> for DashboardWidget {\n\n fn handle(\n\n &mut self,\n\n _event: DataChanged<ExplorerState>,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n ctx.redraw();\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-dashboard/rate-app/src/explorer/dashboard.rs", "rank": 43, "score": 53227.52552550637 }, { "content": "fn unpack_many(elements: MultiBoxedElement) -> Vec<basis::Element> {\n\n let elements = elements.unwrap_or_default();\n\n if elements.is_empty() {\n\n vec![basis::Spacer {\n\n flex: OrderedFloat(1.0),\n\n maintenance: true,\n\n }\n\n .into()]\n\n } else {\n\n elements.into_iter().map(From::<Element>::from).collect()\n\n }\n\n}\n\n\n\n/*\n\nimpl From<SingleBoxedElement> for basis::BoxedElement {\n\n fn from(value: SingleBoxedElement) -> Self {\n\n }\n\n}\n\n*/\n\n\n", "file_path": "pkg-core/rate-config/src/config/cases.rs", "rank": 44, "score": 53227.52552550637 }, { "content": "pub fn new_tf<T>(secs: i64) -> TimedFrame<T> {\n\n TimedFrame::new((secs + 1) * 1_000)\n\n}\n", "file_path": "pkg-packs/basis/src/frames/timed_frame.rs", "rank": 45, "score": 52205.15487745932 }, { "content": " Self::from(entries)\n\n }\n\n}\n\n\n\nimpl<const T: usize> From<String> for FixedPath<T> {\n\n fn from(s: String) -> Self {\n\n let s: &str = s.as_ref();\n\n Self::from(s)\n\n }\n\n}\n\n\n\nimpl<const T: usize> From<&str> for FixedPath<T> {\n\n fn from(s: &str) -> Self {\n\n let entries: Result<[EntryId; T], ()> = s\n\n .parse::<Path>()\n\n .map_err(drop)\n\n .map(Vec::from)\n\n .and_then(|vec| vec.try_into().map_err(drop));\n\n match entries {\n\n Ok(entries) => Self { entries },\n", "file_path": "pkg-packs/basis/src/paths/fixed_path.rs", "rank": 46, "score": 51314.91954455212 }, { "content": " Err(_) => Self::unassigned(EntryId::from(s)),\n\n }\n\n }\n\n}\n\n\n\nimpl<const T: usize> From<FixedPath<T>> for String {\n\n fn from(path: FixedPath<T>) -> Self {\n\n path.entries.join(\".\")\n\n }\n\n}\n", "file_path": "pkg-packs/basis/src/paths/fixed_path.rs", "rank": 47, "score": 51312.05973307689 }, { "content": " .try_into()\n\n .unwrap();\n\n Self { entries }\n\n }\n\n}\n\n\n\nimpl<const T: usize> From<FixedPath<T>> for Path {\n\n fn from(this: FixedPath<T>) -> Self {\n\n Path::from_iter(this.entries)\n\n }\n\n}\n\n\n\nimpl<const T: usize> From<[&str; T]> for FixedPath<T> {\n\n fn from(array: [&str; T]) -> Self {\n\n let entries: [EntryId; T] = array\n\n .iter()\n\n .map(|item| EntryId::from(*item))\n\n .collect::<Vec<_>>()\n\n .try_into()\n\n .unwrap();\n", "file_path": "pkg-packs/basis/src/paths/fixed_path.rs", "rank": 48, "score": 51312.01981777796 }, { "content": "use derive_more::From;\n\nuse rill_protocol::io::provider::{EntryId, Path};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::convert::TryInto;\n\nuse std::iter::{repeat, FromIterator};\n\n\n\n/// `Live` bacause of `Live` product approach.\n\n#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, From)]\n\n#[serde(from = \"String\", into = \"String\")]\n\npub struct FixedPath<const T: usize> {\n\n pub entries: [EntryId; T],\n\n}\n\n\n\nimpl<const T: usize> FixedPath<T> {\n\n fn unassigned(name: EntryId) -> Self {\n\n let entry = EntryId::from(\"unassigned\");\n\n let entries: [EntryId; T] = repeat(entry)\n\n .take(T - 1)\n\n .chain([name])\n\n .collect::<Vec<_>>()\n", "file_path": "pkg-packs/basis/src/paths/fixed_path.rs", "rank": 49, "score": 51311.69389768423 }, { "content": "use super::FixedPath;\n\nuse rill_protocol::io::provider::EntryId;\n\n\n\npub type AutoPath = FixedPath<4>;\n\n\n\nimpl AutoPath {\n\n pub fn package(&self) -> &EntryId {\n\n &self.entries[0]\n\n }\n\n\n\n pub fn dashboard(&self) -> &EntryId {\n\n &self.entries[1]\n\n }\n\n\n\n pub fn group(&self) -> &EntryId {\n\n &self.entries[2]\n\n }\n\n\n\n pub fn name(&self) -> &EntryId {\n\n &self.entries[3]\n\n }\n\n}\n", "file_path": "pkg-packs/basis/src/paths/auto_path.rs", "rank": 50, "score": 51310.7221519524 }, { "content": "use super::FixedPath;\n\n\n\npub type LayoutPath = FixedPath<2>;\n", "file_path": "pkg-packs/basis/src/paths/layout_path.rs", "rank": 51, "score": 51308.159641014056 }, { "content": "/// Creates a new control channel.\n\npub fn channel<T: Flow>() -> (ActionSender<T>, ActionReceiver<T>) {\n\n mpsc::unbounded_channel()\n\n}\n\n\n\npub(crate) struct TracerOperator<T: Flow> {\n\n pub mode: TracerMode<T>,\n\n pub control_rx: Option<ControlReceiver<T>>,\n\n}\n\n\n\npub(crate) enum TracerMode<T: Flow> {\n\n /// Real-time mode\n\n Push {\n\n state: T,\n\n receiver: Option<DataReceiver<T>>,\n\n },\n\n /// Pulling for intensive streams with high-load activities\n\n Pull {\n\n // TODO: Replace with `Arc` since data channel used\n\n // to detect Tracers's termination\n\n state: Weak<Mutex<T>>,\n\n interval: Option<Duration>,\n\n },\n\n}\n\n\n", "file_path": "pkg-core/rill-engine/src/tracers/tracer.rs", "rank": 52, "score": 50613.54405479893 }, { "content": "pub fn diff<'a, K, B, U>(basic: B, updated: U) -> (Vec<K>, Vec<K>)\n\nwhere\n\n K: Hash + Eq + Clone + 'a,\n\n B: IntoIterator<Item = &'a K>,\n\n U: IntoIterator<Item = &'a K>,\n\n{\n\n let basic: HashSet<_> = basic.into_iter().collect();\n\n let updated: HashSet<_> = updated.into_iter().collect();\n\n let to_add: Vec<_> = updated.difference(&basic).map(|k| (*k).clone()).collect();\n\n let to_remove: Vec<_> = basic.difference(&updated).map(|k| (*k).clone()).collect();\n\n (to_add, to_remove)\n\n}\n\n\n", "file_path": "pkg-core/rill-protocol/src/diff.rs", "rank": 53, "score": 45275.13640272808 }, { "content": "use thiserror::Error;\n\n\n\n#[derive(Debug, Error)]\n\n#[error(\"inner value already taken\")]\n\npub struct AlreadyTaken;\n\n\n\n#[derive(Debug, Error)]\n\n#[error(\"inner value was not set\")]\n\npub struct NotSet;\n", "file_path": "rillrate/src/actors/error.rs", "rank": 54, "score": 44325.34675711823 }, { "content": "pub fn diff_full<'a, K, B, U>(basic: B, updated: U) -> (Vec<K>, Vec<K>, Vec<K>)\n\nwhere\n\n K: Hash + Eq + Clone + 'a,\n\n B: IntoIterator<Item = &'a K>,\n\n U: IntoIterator<Item = &'a K>,\n\n{\n\n let basic: HashSet<_> = basic.into_iter().collect();\n\n let updated: HashSet<_> = updated.into_iter().collect();\n\n let to_add: Vec<_> = updated.difference(&basic).map(|k| (*k).clone()).collect();\n\n let to_remove: Vec<_> = basic.difference(&updated).map(|k| (*k).clone()).collect();\n\n let to_check: Vec<_> = basic.intersection(&updated).map(|k| (*k).clone()).collect();\n\n (to_add, to_remove, to_check)\n\n}\n", "file_path": "pkg-core/rill-protocol/src/diff.rs", "rank": 55, "score": 42579.52920721015 }, { "content": "mod auto_path;\n\npub use auto_path::AutoPath;\n\n\n\nmod fixed_path;\n\nuse fixed_path::FixedPath;\n\n\n\nmod layout_path;\n\npub use layout_path::LayoutPath;\n", "file_path": "pkg-packs/basis/src/paths/mod.rs", "rank": 56, "score": 41972.97447916468 }, { "content": "use super::state::*;\n\nuse crate::manifest::description::PackFlowDescription;\n\nuse derive_more::{Deref, DerefMut};\n\nuse rill_engine::tracers::tracer::Tracer;\n\nuse rill_protocol::flow::core::FlowMode;\n\nuse rill_protocol::io::provider::Path;\n\n\n\n#[derive(Debug, Deref, DerefMut, Clone)]\n\npub struct PathsTracer {\n\n tracer: Tracer<PathsState>,\n\n}\n\n\n\nimpl PathsTracer {\n\n #[allow(clippy::new_without_default)]\n\n pub fn new() -> Self {\n\n let path = PathsSpec::path();\n\n let state = PathsSpec.into();\n\n let tracer = Tracer::new(state, path, FlowMode::Realtime);\n\n Self { tracer }\n\n }\n", "file_path": "pkg-packs/basis/src/manifest/paths/tracer.rs", "rank": 57, "score": 40924.05445079194 }, { "content": "\n\nimpl From<PathsSpec> for PathsState {\n\n fn from(_spec: PathsSpec) -> Self {\n\n Self {\n\n records: BTreeMap::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl Flow for PathsState {\n\n type Action = ();\n\n type Event = PathsEvent;\n\n\n\n fn stream_type() -> StreamType {\n\n StreamType::from(module_path!())\n\n }\n\n\n\n fn apply(&mut self, event: Self::Event) {\n\n match event {\n\n PathsEvent::Add { path, description } => {\n", "file_path": "pkg-packs/basis/src/manifest/paths/state.rs", "rank": 58, "score": 40921.814942471116 }, { "content": "use crate::manifest::description::PackFlowDescription;\n\nuse rill_protocol::flow::core::Flow;\n\nuse rill_protocol::io::provider::{Path, StreamType};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::collections::BTreeMap;\n\n\n\nimpl PathsSpec {\n\n pub fn path() -> Path {\n\n \"rillrate.manifest.paths\".parse().unwrap()\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct PathsSpec;\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct PathsState {\n\n #[serde(with = \"vectorize\")]\n\n pub records: BTreeMap<Path, PackFlowDescription>,\n\n}\n", "file_path": "pkg-packs/basis/src/manifest/paths/state.rs", "rank": 59, "score": 40917.21403967283 }, { "content": "use super::tracer::PathsTracer;\n\nuse once_cell::sync::Lazy;\n\n\n\npub static PATHS: Lazy<PathsTracer> = Lazy::new(PathsTracer::new);\n", "file_path": "pkg-packs/basis/src/manifest/paths/global.rs", "rank": 60, "score": 40914.877117273914 }, { "content": "\n\n pub fn add_path(&self, path: Path, description: PackFlowDescription) {\n\n let msg = PathsEvent::Add { path, description };\n\n self.tracer.send(msg, None);\n\n }\n\n\n\n pub fn remove_path(&self, path: Path) {\n\n let msg = PathsEvent::Remove { path };\n\n self.tracer.send(msg, None);\n\n }\n\n}\n", "file_path": "pkg-packs/basis/src/manifest/paths/tracer.rs", "rank": 61, "score": 40910.44760804378 }, { "content": " self.records.insert(path, description);\n\n }\n\n PathsEvent::Remove { path } => {\n\n self.records.remove(&path);\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum PathsEvent {\n\n Add {\n\n path: Path,\n\n description: PackFlowDescription,\n\n },\n\n Remove {\n\n path: Path,\n\n },\n\n}\n", "file_path": "pkg-packs/basis/src/manifest/paths/state.rs", "rank": 62, "score": 40910.437393193926 }, { "content": "pub mod state;\n\npub use state::*;\n\n\n\n#[cfg(feature = \"engine\")]\n\npub mod tracer;\n\n#[cfg(feature = \"engine\")]\n\npub use tracer::*;\n\n\n\n#[cfg(feature = \"engine\")]\n\npub mod global;\n", "file_path": "pkg-packs/basis/src/manifest/paths/mod.rs", "rank": 63, "score": 40909.26092029192 }, { "content": "use crate::tracers::tracer::Tracer;\n\nuse derive_more::{Deref, DerefMut};\n\nuse rill_protocol::flow::meta::path::{PathEvent, PathState};\n\nuse rill_protocol::io::provider::{Description, Path};\n\n\n\n/// This tracer that informs about entries.\n\n#[derive(Debug, Deref, DerefMut, Clone)]\n\npub struct PathTracer {\n\n tracer: Tracer<PathState>,\n\n}\n\n\n\nimpl PathTracer {\n\n /// Create a new instance of the `Tracer`.\n\n pub fn new(path: Path, description: Description) -> Self {\n\n let state = PathState::new(description);\n\n let tracer = Tracer::new_push(state, path);\n\n Self { tracer }\n\n }\n\n\n\n /// Add an path\n", "file_path": "pkg-core/rill-engine/src/tracers/meta/path.rs", "rank": 64, "score": 39918.57508127085 }, { "content": "use crate::flow::core::Flow;\n\nuse crate::flow::location::Location;\n\nuse crate::io::provider::{Description, Path, StreamType};\n\nuse serde::{Deserialize, Serialize};\n\nuse std::collections::BTreeMap;\n\n\n\npub const PATHS: Location = Location::new(\"meta:paths\");\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub struct PathState {\n\n /// Description of the provider\n\n pub description: Description,\n\n #[serde(with = \"vectorize\")]\n\n pub paths: BTreeMap<Path, Description>,\n\n}\n\n\n\n#[allow(clippy::new_without_default)]\n\nimpl PathState {\n\n pub fn new(description: Description) -> Self {\n\n Self {\n", "file_path": "pkg-core/rill-protocol/src/flow/meta/path.rs", "rank": 65, "score": 39915.018068886064 }, { "content": " description,\n\n paths: BTreeMap::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl Flow for PathState {\n\n type Action = ();\n\n type Event = PathEvent;\n\n\n\n fn stream_type() -> StreamType {\n\n StreamType::from(\"rillrate::meta::path::v0\")\n\n }\n\n\n\n fn apply(&mut self, event: Self::Event) {\n\n match event {\n\n PathEvent::AddPath { path, description } => {\n\n self.paths.insert(path, description);\n\n }\n\n PathEvent::RemovePath { path } => {\n", "file_path": "pkg-core/rill-protocol/src/flow/meta/path.rs", "rank": 66, "score": 39913.66884133583 }, { "content": " self.paths.remove(&path);\n\n }\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Serialize, Deserialize)]\n\npub enum PathEvent {\n\n AddPath {\n\n path: Path,\n\n description: Description,\n\n },\n\n RemovePath {\n\n path: Path,\n\n },\n\n}\n", "file_path": "pkg-core/rill-protocol/src/flow/meta/path.rs", "rank": 67, "score": 39905.102292605865 }, { "content": " pub fn add(&self, path: Path, description: Description) {\n\n let data = PathEvent::AddPath { path, description };\n\n self.tracer.send(data, None);\n\n }\n\n\n\n /// Remove an path\n\n pub fn del(&self, path: Path) {\n\n let data = PathEvent::RemovePath { path };\n\n self.tracer.send(data, None);\n\n }\n\n}\n", "file_path": "pkg-core/rill-engine/src/tracers/meta/path.rs", "rank": 68, "score": 39905.068134910085 }, { "content": "struct NotificationImpl<IN> {\n\n event: Option<IN>,\n\n}\n\n\n\nimpl<T, IN> WidgetCallbackFn<T> for NotificationImpl<IN>\n\nwhere\n\n T: NotificationHandler<IN> + Widget,\n\n{\n\n fn handle(&mut self, widget: &mut T, context: &mut Context<T>) -> Result<(), Error> {\n\n if let Some(event) = self.event.take() {\n\n widget.handle(event, context)?;\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "pkg-dashboard/rate-ui/src/widget/mod.rs", "rank": 69, "score": 39046.40258493356 }, { "content": "#[derive(Error, Debug)]\n\nenum ConnectorError {\n\n #[error(\"can't get window object\")]\n\n NoWindow,\n\n #[error(\"can't convert location to a string\")]\n\n NoString,\n\n}\n\n\n\nimpl LiveAgent {\n\n fn status_to_wires(&mut self, live_status: LiveStatus) {\n\n for runtime in self.wires.values_mut() {\n\n let action = WireAction::Status(live_status.clone());\n\n runtime.wire_action(action, &mut self.link);\n\n }\n\n }\n\n\n\n fn send_service_envelope(\n\n &mut self,\n\n service_envelope: ServiceEnvelope<ClientProtocol, ClientRequest, ClientServiceResponse>,\n\n ) {\n\n if let Some(ws) = self.ws.as_mut() {\n", "file_path": "pkg-dashboard/rate-ui/src/agents/live/agent.rs", "rank": 70, "score": 38091.22030701373 }, { "content": "struct AsyncCallback<F, Fut> {\n\n func: F,\n\n fut: PhantomData<Fut>,\n\n}\n\n\n\nimpl<F, Fut> AsyncCallback<F, Fut> {\n\n fn new(func: F) -> Self {\n\n Self {\n\n func,\n\n fut: PhantomData,\n\n }\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T, F, Fut> ActionCallback<T> for AsyncCallback<F, Fut>\n\nwhere\n\n T: Flow,\n\n F: Fn(ActionEnvelope<T>) -> Fut,\n\n F: Send + Sync + 'static,\n\n Fut: Future<Output = Result<(), Error>>,\n\n Fut: Send + 'static,\n\n{\n\n async fn handle_activity(&mut self, envelope: ActionEnvelope<T>) -> Result<(), Error> {\n\n (self.func)(envelope).await\n\n }\n\n}\n", "file_path": "pkg-core/rill-engine/src/tracers/tracer.rs", "rank": 71, "score": 37287.39080867624 }, { "content": "pub trait WidgetCallbackFn<T: Widget> {\n\n fn handle(&mut self, widget: &mut T, context: &mut Context<T>) -> Result<(), Error>;\n\n}\n\n\n\npub enum Msg<T: Widget> {\n\n // TODO: Implement handlers as traits. Envelope-based.\n\n LiveIncomingWired(WireEnvelope<ClientReqId, LiveResponse>),\n\n GraphicsIncoming(GraphicsResponse),\n\n Event(T::Event),\n\n InPlace(Box<dyn WidgetCallbackFn<T>>),\n\n}\n\n\n\npub struct WidgetRuntime<T: Widget> {\n\n widget: T,\n\n context: WidgetContext<T>,\n\n}\n\n\n\nimpl<T: Widget> Component for WidgetRuntime<T> {\n\n type Message = Msg<T>;\n\n type Properties = T::Properties;\n", "file_path": "pkg-dashboard/rate-ui/src/widget/mod.rs", "rank": 72, "score": 35402.786497309186 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl ActionHandler<Reload> for ConfigWatcher {\n\n async fn handle(&mut self, _event: Reload, _ctx: &mut Context<Self>) -> Result<(), Error> {\n\n self.read_from_dir().await\n\n }\n\n}\n\n\n\n// TODO: How about to use plain actions for `HeartBeat`?\n\n#[async_trait]\n\nimpl OnTick for ConfigWatcher {\n\n async fn tick(&mut self, _: Tick, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n self.read_and_watch(ctx).await;\n\n Ok(())\n\n }\n\n\n\n async fn done(&mut self, _ctx: &mut Context<Self>) -> Result<(), Error> {\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rate-config/src/actors/config_watcher/actor.rs", "rank": 74, "score": 34.57995425940857 }, { "content": " async fn finished(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: core::Flow> InstantActionHandler<RegisterTracer<T>> for RillConnector {\n\n async fn handle(\n\n &mut self,\n\n msg: RegisterTracer<T>,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n let description = msg.description;\n\n let path = description.path.clone();\n\n log::info!(\"Add tracer: {}\", path);\n\n let record = self.recorders.dig(path.clone());\n\n if record.get_link().is_none() {\n\n let packed_desc = Description::clone(&description);\n\n let sender = self.sender.clone();\n", "file_path": "pkg-core/rill-engine/src/actors/connector/actor/parcel.rs", "rank": 75, "score": 33.79746479392473 }, { "content": " }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: RillPoolTask> InstantActionHandler<AttachTask<T>> for RillPool {\n\n async fn handle(&mut self, msg: AttachTask<T>, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.spawn_task(msg, (), Group::Tasks);\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: RillPoolTask> TaskEliminated<AttachTask<T>, ()> for RillPool {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<AttachTask<T>>,\n\n _tag: (),\n\n _result: Result<(), TaskError>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n", "file_path": "pkg-core/rill-engine/src/actors/pool/actor/parcel.rs", "rank": 76, "score": 32.318056351954475 }, { "content": "use super::{Group, NodeSupervisor};\n\nuse anyhow::Error;\n\nuse async_trait::async_trait;\n\nuse meio::{Context, Eliminated, IdOf};\n\nuse rate_core::actors::node::Node;\n\n\n\nimpl NodeSupervisor {\n\n pub fn spawn_node(&mut self, ctx: &mut Context<Self>) {\n\n let node = Node::new(\n\n self.config.clone(),\n\n ctx.address().clone(),\n\n self.global_acl.clone(),\n\n );\n\n let addr = ctx.spawn_actor(node, Group::Node);\n\n self.node = Some(addr.link());\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl Eliminated<Node<Self>> for NodeSupervisor {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<Node<Self>>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n Ok(())\n\n }\n\n}\n", "file_path": "rillrate/src/actors/supervisor/actor/node.rs", "rank": 77, "score": 31.868439182483584 }, { "content": " options: AssetsOptions,\n\n}\n\n\n\nimpl AppBind {\n\n pub fn new(server: HttpServerLink, options: AssetsOptions) -> Self {\n\n Self {\n\n server,\n\n assets: AssetsMode::Loading,\n\n options,\n\n }\n\n }\n\n}\n\n\n\nimpl Actor for AppBind {\n\n type GroupBy = ();\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Actor> StartedBy<T> for AppBind {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n", "file_path": "pkg-core/rate-core/src/actors/app_bind/actor.rs", "rank": 78, "score": 31.757295244582444 }, { "content": "use super::{\n\n assets::{self, AssetsMode},\n\n AppBind,\n\n};\n\nuse anyhow::Error;\n\nuse async_trait::async_trait;\n\nuse meio::{Context, InteractionHandler};\n\nuse meio_connect::headers::{ContentType, HeaderMapExt};\n\nuse meio_connect::hyper::{Body, Request, Response, StatusCode};\n\nuse meio_connect::server::{FromRequest, Req, WebRoute};\n\nuse std::path::{Path, PathBuf};\n\n\n\nimpl AppBind {\n\n pub(super) async fn app_bind_route(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n let app_route = AppRoute {\n\n prefix: self.options.prefix,\n\n };\n\n let route = WebRoute::new(app_route, ctx.address().clone());\n\n self.server.add_route(route).await?;\n\n Ok(())\n", "file_path": "pkg-core/rate-core/src/actors/app_bind/actor/app_route.rs", "rank": 79, "score": 31.508319985841815 }, { "content": "impl<T: Actor> InterruptedBy<T> for RillEngine {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl Eliminated<RillConnector> for RillEngine {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<RillConnector>,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n/*\n", "file_path": "pkg-core/rill-engine/src/actors/engine/actor.rs", "rank": 80, "score": 31.44192941221879 }, { "content": " Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl InstantActionHandler<WsClientStatus<ProviderProtocol>> for RillConnector {\n\n async fn handle(\n\n &mut self,\n\n status: WsClientStatus<ProviderProtocol>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n match status {\n\n WsClientStatus::Connected { sender } => {\n\n // TODO: Resend new sender to all `Recorders`\n\n self.sender.set(sender);\n\n\n\n for desc in self.registered.values_mut() {\n\n // TODO: Use `Pathfinder::walk` to perform that\n\n let path = &desc.path;\n\n let link = self.recorders.find_mut(path).and_then(Record::get_link_mut);\n", "file_path": "pkg-core/rill-engine/src/actors/connector/actor.rs", "rank": 81, "score": 31.031567481565837 }, { "content": "use super::{Group, NodeSupervisor};\n\nuse anyhow::Error;\n\nuse async_trait::async_trait;\n\nuse meio::{Context, Eliminated, IdOf};\n\nuse rate_config::actors::config_watcher::ConfigWatcher;\n\n\n\nimpl NodeSupervisor {\n\n pub(super) fn spawn_config_watcher(&mut self, ctx: &mut Context<Self>) {\n\n let config_watcher = ConfigWatcher::new();\n\n ctx.spawn_actor(config_watcher, Group::ConfigWatcher);\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl Eliminated<ConfigWatcher> for NodeSupervisor {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<ConfigWatcher>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n Ok(())\n\n }\n\n}\n", "file_path": "rillrate/src/actors/supervisor/actor/config.rs", "rank": 82, "score": 30.951792757706556 }, { "content": "use super::{Group, RillPool};\n\nuse crate::distributor::ParcelDistributor;\n\nuse anyhow::Error;\n\nuse async_trait::async_trait;\n\nuse meio::{\n\n Consumer, Context, IdOf, InstantAction, InstantActionHandler, LiteTask, Parcel, TaskEliminated,\n\n TaskError,\n\n};\n\nuse once_cell::sync::Lazy;\n\nuse thiserror::Error;\n\n\n\npub(crate) static DISTRIBUTOR: Lazy<ParcelDistributor<RillPool>> =\n\n Lazy::new(ParcelDistributor::new);\n\n\n\nimpl RillPool {\n\n pub(super) async fn attach_distributor(\n\n &mut self,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n let rx = DISTRIBUTOR.take_receiver().await?;\n", "file_path": "pkg-core/rill-engine/src/actors/pool/actor/parcel.rs", "rank": 83, "score": 30.795109647799954 }, { "content": "impl TaskEliminated<WsClient<ProviderProtocol, Self>, ()> for RillConnector {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<WsClient<ProviderProtocol, Self>>,\n\n _tag: (),\n\n _result: Result<(), TaskError>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n // TODO: Drop unfinished tasks\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: core::Flow> Eliminated<Recorder<T>> for RillConnector {\n\n async fn handle(\n\n &mut self,\n\n id: IdOf<Recorder<T>>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n", "file_path": "pkg-core/rill-engine/src/actors/connector/actor.rs", "rank": 84, "score": 30.56452662133363 }, { "content": "}\n\n\n\nimpl Actor for RillPool {\n\n type GroupBy = Group;\n\n}\n\n\n\n#[async_trait]\n\nimpl StartedBy<RillEngine> for RillPool {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.termination_sequence(vec![Group::ParcelStream, Group::Tasks]);\n\n self.attach_distributor(ctx).await?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl InterruptedBy<RillEngine> for RillPool {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n self.detach_distributor();\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rill-engine/src/actors/pool/actor.rs", "rank": 85, "score": 30.35857251556604 }, { "content": "\n\n fn name(&self) -> String {\n\n \"Router\".into()\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> StartedBy<Node<T>> for Router<T> {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.termination_sequence(Group::iter().collect());\n\n self.init_internal(ctx).await?;\n\n self.init_external(ctx).await?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> InterruptedBy<Node<T>> for Router<T> {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rate-core/src/actors/router/actor.rs", "rank": 86, "score": 29.975817595778125 }, { "content": " }\n\n\n\n async fn failed(\n\n &mut self,\n\n tag: FinalFlowTag,\n\n _reason: TaskError,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n InteractionDone::<plink::UnsubscribeFromPath, FinalFlowTag>::handle(self, tag, (), ctx)\n\n .await\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> ActionHandler<link::ServiceOutgoing> for ClientSession<T> {\n\n async fn handle(\n\n &mut self,\n\n msg: link::ServiceOutgoing,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n let service_envelope = ServiceEnvelope::Service(msg.request);\n\n self.handler.send(service_envelope);\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rate-core/src/actors/client_session/actor.rs", "rank": 87, "score": 29.934940809248 }, { "content": "impl Actor for ProviderSession {\n\n type GroupBy = ();\n\n\n\n fn name(&self) -> String {\n\n format!(\"ProviderSession({})\", self.handler.addr())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> StartedBy<Router<T>> for ProviderSession {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n let worker = self.handler.worker(ctx.address().clone());\n\n ctx.spawn_task(worker, (), ());\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> InterruptedBy<Router<T>> for ProviderSession {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n", "file_path": "pkg-core/rate-core/src/actors/provider_session/actor.rs", "rank": 88, "score": 29.838470444339485 }, { "content": "#[async_trait]\n\nimpl<T: Supervisor> InterruptedBy<T> for Node<T> {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n log::info!(\"Terminating the node...\");\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> Eliminated<HttpServer> for Node<T> {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<HttpServer>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n log::info!(\"HttpServer finished\");\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rate-core/src/actors/node/actor.rs", "rank": 89, "score": 29.818813200815175 }, { "content": " entries.push(self.global_acl.id().clone());\n\n } else {\n\n entries.push(entry_id);\n\n }\n\n }\n\n entries.into()\n\n }\n\n\n\n async fn subscribe_or_act(\n\n &mut self,\n\n direct_id: ClientReqId,\n\n path: Path,\n\n action: Option<RecorderAction>,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n // SUBSCRIBING\n\n // TODO: Fix `ValidPath` shit\n\n // TODO: Return error for invalid paths\n\n // TODO: Use `AliasPath` instead (to prevent potential mistakes on refactoring)\n\n #[allow(clippy::collapsible_if)]\n", "file_path": "pkg-core/rate-core/src/actors/client_session/actor.rs", "rank": 90, "score": 29.70227932782433 }, { "content": " self.spawn_assets(ctx)?;\n\n\n\n //let rest_server = self.spawn_rest_server(ctx);\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl InterruptedBy<System> for NodeSupervisor {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl InteractionHandler<link::GetClientAssistant<Self>> for NodeSupervisor {\n\n async fn handle(\n\n &mut self,\n\n msg: link::GetClientAssistant<Self>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<NodeClientAssistant, Error> {\n\n Ok(NodeClientAssistant::new(msg.link, msg.session_acl))\n\n }\n\n}\n", "file_path": "rillrate/src/actors/supervisor/actor.rs", "rank": 91, "score": 29.524041212335852 }, { "content": " self.url.clone(),\n\n Some(Duration::from_secs(1)),\n\n ctx.address().clone(),\n\n );\n\n ctx.spawn_task(client, (), Group::WsConnection);\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Actor> InterruptedBy<T> for RillClient {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl InstantActionHandler<WsClientStatus<ClientProtocol>> for RillClient {\n", "file_path": "pkg-core/rill-client/src/actors/client/actor.rs", "rank": 92, "score": 29.419729964142235 }, { "content": " TracerMode::Push { .. } => {\n\n log::error!(\n\n \"Pulling tick received in the push mode for: {}\",\n\n self.description.path\n\n );\n\n }\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: core::Flow> ActionHandler<link::DoRecorderRequest> for Recorder<T> {\n\n async fn handle(\n\n &mut self,\n\n msg: link::DoRecorderRequest,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n if !ctx.is_terminating() {\n", "file_path": "pkg-core/rill-engine/src/actors/recorder/actor.rs", "rank": 93, "score": 29.363425955846445 }, { "content": " Ok(())\n\n }\n\n\n\n async fn failed(\n\n &mut self,\n\n _tag: Internal,\n\n err: TaskError,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n log::error!(\"Can't wait for an internal server: {}\", err);\n\n ctx.shutdown();\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> Eliminated<RillEngine> for Node<T> {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<RillEngine>,\n\n _ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n log::info!(\"RillEngine finished\");\n\n Ok(())\n\n }\n\n}\n", "file_path": "pkg-core/rate-core/src/actors/node/actor.rs", "rank": 94, "score": 29.347920041088692 }, { "content": " ctx.attach(rx, (), Group::ParcelStream);\n\n Ok(())\n\n }\n\n\n\n pub(super) fn detach_distributor(&mut self) {\n\n DISTRIBUTOR.sender.close_channel();\n\n // NEVER terminate the group. The channel above has to be drained!!!\n\n //ctx.terminate_group(Group::ParcelStream);\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl Consumer<Parcel<Self>> for RillPool {\n\n async fn handle(&mut self, parcel: Parcel<Self>, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.address().unpack_parcel(parcel)\n\n }\n\n\n\n async fn finished(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n ctx.shutdown();\n\n Ok(())\n", "file_path": "pkg-core/rill-engine/src/actors/pool/actor/parcel.rs", "rank": 95, "score": 29.11398027039722 }, { "content": "use super::{Group, NodeSupervisor};\n\nuse crate::actors::error::NotSet;\n\nuse anyhow::Error;\n\nuse async_trait::async_trait;\n\nuse meio::{Context, Eliminated, IdOf, InteractionDone};\n\nuse meio_connect::server::HttpServerLink;\n\nuse rate_core::actors::app_bind::{AppBind, AssetsOptions};\n\nuse rate_core::actors::node::WaitHttpServer;\n\n\n\nimpl NodeSupervisor {\n\n // TODO: Avoid returning error here\n\n pub(super) fn spawn_assets(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n let node = self.node.as_mut().ok_or(NotSet)?;\n\n // TODO: Change this bool.\n\n let task = node.wait_for_server(true);\n\n ctx.spawn_task(task, (), Group::Assets);\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "rillrate/src/actors/supervisor/actor/assets.rs", "rank": 96, "score": 28.91801671947175 }, { "content": "#[async_trait]\n\nimpl Eliminated<RillPool> for RillEngine {\n\n async fn handle(&mut self, _id: IdOf<RillPool>, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n if !ctx.is_terminating() {\n\n log::error!(\"Callbacks pool terminated!\");\n\n }\n\n Ok(())\n\n }\n\n}\n\n*/\n", "file_path": "pkg-core/rill-engine/src/actors/engine/actor.rs", "rank": 97, "score": 28.686854545733482 }, { "content": "#[async_trait]\n\nimpl<T: Supervisor> InteractionDone<supervisor_link::GetClientAssistant<T>, ()>\n\n for ClientSession<T>\n\n{\n\n async fn handle(\n\n &mut self,\n\n _tag: (),\n\n assistant: T::ClientAssistant,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n let addr = ctx.spawn_actor(assistant, Group::Assistant);\n\n self.assistant = Some(addr.link());\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Supervisor> InterruptedBy<Router<T>> for ClientSession<T> {\n\n async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {\n\n self.start_graceful_shutdown(ctx).await;\n", "file_path": "pkg-core/rate-core/src/actors/client_session/actor.rs", "rank": 98, "score": 28.629248067001615 }, { "content": " let resp = ClientResponse::Error(reason);\n\n self.distribute_response(msg.0.direction, resp);\n\n }\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\n#[async_trait]\n\nimpl TaskEliminated<WsProcessor<ProviderProtocol, Self>, ()> for ProviderSession {\n\n async fn handle(\n\n &mut self,\n\n _id: IdOf<WsProcessor<ProviderProtocol, Self>>,\n\n _tag: (),\n\n _result: Result<TermReason, TaskError>,\n\n ctx: &mut Context<Self>,\n\n ) -> Result<(), Error> {\n\n self.graceful_shutdown(ctx).await;\n\n Ok(())\n\n }\n", "file_path": "pkg-core/rate-core/src/actors/provider_session/actor.rs", "rank": 99, "score": 28.45927952628948 } ]
Rust
tests/parse/valid/control_flow.rs
JSAbrahams/mamba
66ae435a4abf496aae945a78e4fdfa8e4785d854
use mamba::lex::tokenize; use mamba::parse::ast::Node; use mamba::parse::ast::AST; use mamba::parse::parse; use mamba::parse::parse_direct; use crate::common::*; #[test] fn for_statements() { let source = resource_content(true, &["control_flow"], "for_statements.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn for_statement_verify() { let source = String::from("for a in c do d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, collection, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not for.") }, _ => panic!("ast was not script.") }; assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(collection.node, Node::Id { lit: String::from("c") }); assert_eq!(body.node, Node::Id { lit: String::from("d") }); } #[test] fn for_range_step_verify() { let source = String::from("for a in c .. d step e do f"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, col, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not foreach.") }, _ => panic!("ast was not script.") }; match col.node { Node::Range { from, to, inclusive, step } => { assert_eq!(from.node, Node::Id { lit: String::from("c") }); assert_eq!(to.node, Node::Id { lit: String::from("d") }); assert!(!inclusive); assert_eq!(step.clone().unwrap().node, Node::Id { lit: String::from("e") }); } _ => panic!("Expected range") } assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("f") }); } #[test] fn for_range_incl_verify() { let source = String::from("for a in c ..= d do f"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, col, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not foreach.") }, _ => panic!("ast was not script.") }; match col.node { Node::Range { from, to, inclusive, step } => { assert_eq!(from.node, Node::Id { lit: String::from("c") }); assert_eq!(to.node, Node::Id { lit: String::from("d") }); assert!(inclusive); assert_eq!(step, None); } _ => panic!("Expected range") } assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("f") }); } #[test] fn if_stmt() { let source = resource_content(true, &["control_flow"], "if.mamba"); assert!(parse(&tokenize(&source).unwrap()).is_ok()); } #[test] fn if_verify() { let source = String::from("if a then c"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let _statements; let (cond, then, el) = match ast.node { Node::Script { statements, .. } => { _statements = statements; match &_statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond, then, el), _ => panic!("first element script was not if.") } } _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(then.node, Node::Id { lit: String::from("c") }); assert_eq!(el.is_none(), true); } #[test] fn if_with_block_verify() { let source = String::from("if a then\n c\n d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, then, el) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond.clone(), then.clone(), el.clone()), _ => panic!("first element script was not if.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(el.is_none(), true); let block = match then.node { Node::Block { statements } => statements, other => panic!("then of if was not block, was: {:?}", other) }; assert_eq!(block.len(), 2); assert_eq!(block[0].node, Node::Id { lit: String::from("c") }); assert_eq!(block[1].node, Node::Id { lit: String::from("d") }); } #[test] fn if_else_verify() { let source = String::from("if a then c else d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let _statements; let (cond, then, el) = match ast.node { Node::Script { statements, .. } => { _statements = statements; match &_statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond, then, el), _ => panic!("first element script was not if.") } } _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(then.node, Node::Id { lit: String::from("c") }); assert_eq!(el.as_ref().unwrap().node, Node::Id { lit: String::from("d") }); } #[test] fn match_statements() { let source = resource_content(true, &["control_flow"], "match.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn match_verify() { let source = String::from("match a\n a => b\n c => d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, cases) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::Match { cond, cases } => (cond.clone(), cases.clone()), _ => panic!("first element script was not match.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(cases.len(), 2); let (cond1, expr1, cond2, expr2) = match (&cases[0], &cases[1]) { ( AST { node: Node::Case { cond: cond1, body: expr1 }, .. }, AST { node: Node::Case { cond: cond2, body: expr2 }, .. } ) => match (&cond1.node, &cond2.node) { ( Node::ExpressionType { expr: cond1, .. }, Node::ExpressionType { expr: cond2, .. } ) => (cond1, expr1, cond2, expr2), other => panic!("expected expression type: {:?}", other) }, _ => panic!("Cases incorrect.") }; assert_eq!(cond1.node, Node::Id { lit: String::from("a") }); assert_eq!(expr1.node, Node::Id { lit: String::from("b") }); assert_eq!(cond2.node, Node::Id { lit: String::from("c") }); assert_eq!(expr2.node, Node::Id { lit: String::from("d") }); } #[test] fn while_statements() { let source = resource_content(true, &["control_flow"], "while.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn while_verify() { let source = String::from("while a do d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::While { cond, body } => (cond.clone(), body.clone()), _ => panic!("first element script was not while.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("d") }); }
use mamba::lex::tokenize; use mamba::parse::ast::Node; use mamba::parse::ast::AST; use mamba::parse::parse; use mamba::parse::parse_direct; use crate::common::*; #[test] fn for_statements() { let source = resource_content(true, &["control_flow"], "for_statements.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn for_statement_verify() { let source = String::from("for a in c do d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, collection, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not for.") }, _ => panic!("ast was not script.") }; assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(collection.node, Node::Id { lit: String::from("c") }); assert_eq!(body.node, Node::Id { lit: String::from("d") }); } #[test] fn for_range_step_verify() { let source = String::from("for a in c .. d step e do f"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, col, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not foreach.") }, _ => panic!("ast was not script.") };
assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("f") }); } #[test] fn for_range_incl_verify() { let source = String::from("for a in c ..= d do f"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (expr, col, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::For { expr, col, body } => (expr.clone(), col.clone(), body.clone()), _ => panic!("first element script was not foreach.") }, _ => panic!("ast was not script.") }; match col.node { Node::Range { from, to, inclusive, step } => { assert_eq!(from.node, Node::Id { lit: String::from("c") }); assert_eq!(to.node, Node::Id { lit: String::from("d") }); assert!(inclusive); assert_eq!(step, None); } _ => panic!("Expected range") } assert_eq!(expr.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("f") }); } #[test] fn if_stmt() { let source = resource_content(true, &["control_flow"], "if.mamba"); assert!(parse(&tokenize(&source).unwrap()).is_ok()); } #[test] fn if_verify() { let source = String::from("if a then c"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let _statements; let (cond, then, el) = match ast.node { Node::Script { statements, .. } => { _statements = statements; match &_statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond, then, el), _ => panic!("first element script was not if.") } } _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(then.node, Node::Id { lit: String::from("c") }); assert_eq!(el.is_none(), true); } #[test] fn if_with_block_verify() { let source = String::from("if a then\n c\n d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, then, el) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond.clone(), then.clone(), el.clone()), _ => panic!("first element script was not if.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(el.is_none(), true); let block = match then.node { Node::Block { statements } => statements, other => panic!("then of if was not block, was: {:?}", other) }; assert_eq!(block.len(), 2); assert_eq!(block[0].node, Node::Id { lit: String::from("c") }); assert_eq!(block[1].node, Node::Id { lit: String::from("d") }); } #[test] fn if_else_verify() { let source = String::from("if a then c else d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let _statements; let (cond, then, el) = match ast.node { Node::Script { statements, .. } => { _statements = statements; match &_statements.first().expect("script empty.").node { Node::IfElse { cond, then, el } => (cond, then, el), _ => panic!("first element script was not if.") } } _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(then.node, Node::Id { lit: String::from("c") }); assert_eq!(el.as_ref().unwrap().node, Node::Id { lit: String::from("d") }); } #[test] fn match_statements() { let source = resource_content(true, &["control_flow"], "match.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn match_verify() { let source = String::from("match a\n a => b\n c => d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, cases) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::Match { cond, cases } => (cond.clone(), cases.clone()), _ => panic!("first element script was not match.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(cases.len(), 2); let (cond1, expr1, cond2, expr2) = match (&cases[0], &cases[1]) { ( AST { node: Node::Case { cond: cond1, body: expr1 }, .. }, AST { node: Node::Case { cond: cond2, body: expr2 }, .. } ) => match (&cond1.node, &cond2.node) { ( Node::ExpressionType { expr: cond1, .. }, Node::ExpressionType { expr: cond2, .. } ) => (cond1, expr1, cond2, expr2), other => panic!("expected expression type: {:?}", other) }, _ => panic!("Cases incorrect.") }; assert_eq!(cond1.node, Node::Id { lit: String::from("a") }); assert_eq!(expr1.node, Node::Id { lit: String::from("b") }); assert_eq!(cond2.node, Node::Id { lit: String::from("c") }); assert_eq!(expr2.node, Node::Id { lit: String::from("d") }); } #[test] fn while_statements() { let source = resource_content(true, &["control_flow"], "while.mamba"); parse(&tokenize(&source).unwrap()).unwrap(); } #[test] fn while_verify() { let source = String::from("while a do d"); let ast = parse_direct(&tokenize(&source).unwrap()).unwrap(); let (cond, body) = match ast.node { Node::Script { statements, .. } => match &statements.first().expect("script empty.").node { Node::While { cond, body } => (cond.clone(), body.clone()), _ => panic!("first element script was not while.") }, _ => panic!("ast was not script.") }; assert_eq!(cond.node, Node::Id { lit: String::from("a") }); assert_eq!(body.node, Node::Id { lit: String::from("d") }); }
match col.node { Node::Range { from, to, inclusive, step } => { assert_eq!(from.node, Node::Id { lit: String::from("c") }); assert_eq!(to.node, Node::Id { lit: String::from("d") }); assert!(!inclusive); assert_eq!(step.clone().unwrap().node, Node::Id { lit: String::from("e") }); } _ => panic!("Expected range") }
if_condition
[ { "content": "#[test]\n\n#[ignore]\n\nfn core_match_statements() {\n\n let source = resource_content(true, &[\"control_flow\"], \"match.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/control_flow.rs", "rank": 1, "score": 198184.49970102464 }, { "content": "#[test]\n\nfn range_step_verify() {\n\n let source = String::from(\"hello .. world step 2\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (from, to, inclusive, step) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Range { from, to, inclusive, step } =>\n\n (from.clone(), to.clone(), inclusive.clone(), step.clone()),\n\n _ => panic!(\"first element script was not range.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(from.node, Node::Id { lit: String::from(\"hello\") });\n\n assert_eq!(to.node, Node::Id { lit: String::from(\"world\") });\n\n assert!(!inclusive);\n\n assert_eq!(step.unwrap().node, Node::Int { lit: String::from(\"2\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 2, "score": 194246.66689201444 }, { "content": "#[test]\n\nfn tuple_single_is_expr_verify() {\n\n let source = String::from(\"(a)\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let _statements;\n\n let lit = match ast.node {\n\n Node::Script { statements, .. } => {\n\n _statements = statements;\n\n match &_statements.first().expect(\"script empty.\").node {\n\n Node::Id { lit } => lit,\n\n _ => panic!(\"first element script was not tuple.\")\n\n }\n\n }\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(lit.as_str(), \"a\");\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 3, "score": 194199.869245771 }, { "content": "/// Generate constraint for collection by taking first element\n\n///\n\n/// The assumption here being that every element in the set has the same type.\n\npub fn constr_col(collection: &AST, constr: &mut ConstrBuilder) -> TypeResult<ConstrBuilder> {\n\n let col = match &collection.node {\n\n Node::Set { elements } | Node::List { elements } | Node::Tuple { elements } =>\n\n if let Some(first) = elements.first() {\n\n for element in elements {\n\n constr.add(\n\n \"collection\",\n\n &Expected::try_from(element)?,\n\n &Expected::try_from(first)?\n\n )\n\n }\n\n Expect::Collection {\n\n ty: Box::from(Expected::new(&first.pos, &Expression { ast: first.clone() }))\n\n }\n\n } else {\n\n Expect::Collection { ty: Box::from(Expected::new(&collection.pos, &ExpressionAny)) }\n\n },\n\n\n\n _ => Expect::Collection { ty: Box::from(Expected::new(&collection.pos, &ExpressionAny)) }\n\n };\n\n\n\n let col_exp = Expected::new(&collection.pos, &col);\n\n constr.add(\"collection\", &col_exp, &Expected::try_from(collection)?);\n\n Ok(constr.clone())\n\n}\n\n\n", "file_path": "src/check/constrain/generate/collection.rs", "rank": 4, "score": 188431.2017822806 }, { "content": "pub fn parse_match_cases(it: &mut LexIterator) -> ParseResult<Vec<AST>> {\n\n let start = it.eat(&Token::Indent, \"match cases\")?;\n\n let mut cases = vec![];\n\n it.peek_while_not_token(&Token::Dedent, &mut |it, _| {\n\n cases.push(*it.parse(&parse_match_case, \"match case\", &start)?);\n\n it.eat_if(&Token::NL);\n\n Ok(())\n\n })?;\n\n\n\n it.eat(&Token::Dedent, \"match cases\")?;\n\n Ok(cases)\n\n}\n\n\n", "file_path": "src/parse/control_flow_expr.rs", "rank": 5, "score": 184208.7751931849 }, { "content": "#[test]\n\nfn match_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"control_flow\"], &[\"control_flow\", \"target\"], \"match\")\n\n}\n", "file_path": "tests/output/valid/control_flow.rs", "rank": 6, "score": 176244.36455615735 }, { "content": "pub fn gen_ty(ast: &AST, _: &Environment, _: &Context, _: &ConstrBuilder) -> Constrained {\n\n match &ast.node {\n\n Node::QuestionOp { .. } =>\n\n Err(vec![TypeErr::new(&ast.pos, \"Nullable type annotation cannot be top level\")]),\n\n Node::TypeTup { .. } =>\n\n Err(vec![TypeErr::new(&ast.pos, \"Type tuple annotation cannot be top level\")]),\n\n Node::TypeUnion { .. } =>\n\n Err(vec![TypeErr::new(&ast.pos, \"Type union annotation cannot be top level\")]),\n\n Node::Type { .. } =>\n\n Err(vec![TypeErr::new(&ast.pos, \"Type annotation cannot be top level\")]),\n\n Node::TypeFun { .. } =>\n\n Err(vec![TypeErr::new(&ast.pos, \"Type annotation function cannot be top level\")]),\n\n _ => Err(vec![TypeErr::new(&ast.pos, \"Expected type annotation\")])\n\n }\n\n}\n", "file_path": "src/check/constrain/generate/ty.rs", "rank": 7, "score": 172995.48049170058 }, { "content": "pub fn python_src_to_stmts(python_src: &String) -> Vec<Statement> {\n\n python_parser::file_input(python_parser::make_strspan(python_src.as_ref())).unwrap().1\n\n}\n", "file_path": "tests/common.rs", "rank": 8, "score": 164322.18816007854 }, { "content": "pub fn parse_handle(expr_or_stmt: AST, it: &mut LexIterator) -> ParseResult {\n\n let start = &it.start_pos(\"handle\")?;\n\n it.eat(&Token::Handle, \"handle\")?;\n\n it.eat(&Token::NL, \"handle\")?;\n\n\n\n let cases = it.parse_vec(&parse_match_cases, \"handle\", start)?;\n\n let end = cases.last().map_or(start, |stmt| &stmt.pos);\n\n\n\n let node = Node::Handle { expr_or_stmt: Box::from(expr_or_stmt), cases: cases.clone() };\n\n Ok(Box::from(AST::new(&start.union(&end), node)))\n\n}\n", "file_path": "src/parse/expr_or_stmt.rs", "rank": 9, "score": 163500.84466424503 }, { "content": "pub fn parse_raise(expr_or_stmt: AST, it: &mut LexIterator) -> ParseResult {\n\n let start = &it.start_pos(\"raise\")?;\n\n it.eat(&Token::Raises, \"raise\")?;\n\n\n\n it.eat(&Token::LSBrack, \"raise\")?;\n\n let errors = it.parse_vec(&parse_generics, \"raise\", start)?;\n\n it.eat(&Token::RSBrack, \"raise\")?;\n\n it.eat_if(&Token::RSBrack);\n\n let end = errors.last().map_or(start, |stmt| &stmt.pos);\n\n\n\n let node = Node::Raises { expr_or_stmt: Box::from(expr_or_stmt), errors: errors.clone() };\n\n Ok(Box::from(AST::new(&start.union(&end), node)))\n\n}\n\n\n", "file_path": "src/parse/expr_or_stmt.rs", "rank": 10, "score": 163500.84466424503 }, { "content": "#[test]\n\nfn list_verify() {\n\n let elements = vec![\n\n to_pos_unboxed!(Node::ENum { num: String::from(\"a\"), exp: String::from(\"100\") }),\n\n to_pos_unboxed!(Node::Real { lit: String::from(\"3000.5\") }),\n\n ];\n\n let tuple = to_pos!(Node::List { elements });\n\n let core = desugar(&tuple);\n\n\n\n let core_elements = match core {\n\n Ok(Core::List { elements }) => elements,\n\n other => panic!(\"Expected tuple but got {:?}\", other)\n\n };\n\n\n\n assert_eq!(core_elements[0], Core::ENum { num: String::from(\"a\"), exp: String::from(\"100\") });\n\n assert_eq!(core_elements[1], Core::Float { float: String::from(\"3000.5\") });\n\n}\n\n\n", "file_path": "tests/desugar/collection.rs", "rank": 11, "score": 162071.10501048405 }, { "content": "#[test]\n\nfn tuple_verify() {\n\n let elements = vec![\n\n to_pos_unboxed!(Node::ENum { num: String::from(\"a\"), exp: String::from(\"100\") }),\n\n to_pos_unboxed!(Node::Real { lit: String::from(\"3000.5\") }),\n\n ];\n\n let tuple = to_pos!(Node::Tuple { elements });\n\n let core = desugar(&tuple);\n\n\n\n let core_elements = match core {\n\n Ok(Core::Tuple { elements }) => elements,\n\n other => panic!(\"Expected tuple but got {:?}\", other)\n\n };\n\n\n\n assert_eq!(core_elements[0], Core::ENum { num: String::from(\"a\"), exp: String::from(\"100\") });\n\n assert_eq!(core_elements[1], Core::Float { float: String::from(\"3000.5\") });\n\n}\n\n\n", "file_path": "tests/desugar/collection.rs", "rank": 12, "score": 162071.10501048405 }, { "content": "#[test]\n\nfn core_tuple() {\n\n let source = resource_content(true, &[\"collection\"], \"tuple.mamba\");\n\n to_py!(source);\n\n}\n", "file_path": "tests/core/collection.rs", "rank": 13, "score": 162071.10501048405 }, { "content": "#[test]\n\nfn core_set() {\n\n let source = resource_content(true, &[\"collection\"], \"set.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/collection.rs", "rank": 14, "score": 162071.10501048405 }, { "content": "#[test]\n\nfn set_verify() {\n\n let elements = vec![\n\n to_pos_unboxed!(Node::Id { lit: String::from(\"a\") }),\n\n to_pos_unboxed!(Node::Bool { lit: true }),\n\n ];\n\n let set = to_pos!(Node::Set { elements });\n\n let core = desugar(&set);\n\n\n\n let core_elements = match core {\n\n Ok(Core::Set { elements }) => elements,\n\n other => panic!(\"Expected set but got {:?}\", other)\n\n };\n\n\n\n assert_eq!(core_elements[0], Core::Id { lit: String::from(\"a\") });\n\n assert_eq!(core_elements[1], Core::Bool { boolean: true });\n\n}\n\n\n", "file_path": "tests/desugar/collection.rs", "rank": 15, "score": 162071.10501048405 }, { "content": "#[test]\n\nfn core_list() {\n\n let source = resource_content(true, &[\"collection\"], \"tuple.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/collection.rs", "rank": 16, "score": 162071.10501048405 }, { "content": "#[test]\n\n#[ignore]\n\nfn core_map() {\n\n let source = resource_content(true, &[\"collection\"], \"map.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/collection.rs", "rank": 17, "score": 162071.02136147767 }, { "content": "#[test]\n\nfn as_statement() {\n\n let source = resource_content(false, &[\"type\", \"function\"], \"as_statement.mamba\");\n\n check_all(&[(*parse(&tokenize(&source).unwrap()).unwrap(), None, None)]).unwrap_err();\n\n}\n\n\n", "file_path": "tests/check/invalid/function.rs", "rank": 18, "score": 162055.43827324332 }, { "content": "fn equal_vec(this: &[AST], other: &[AST]) -> bool {\n\n if this.len() != other.len() {\n\n false\n\n } else {\n\n for (left, right) in this.iter().zip(other) {\n\n if !left.equal_structure(right) {\n\n return false;\n\n }\n\n }\n\n true\n\n }\n\n}\n\n\n\nimpl Display for Node {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {\n\n let name = match &self {\n\n Node::File { .. } => String::from(\"file\"),\n\n Node::Import { .. } => String::from(\"import\"),\n\n Node::FromImport { .. } => String::from(\"from import\"),\n\n Node::Class { .. } => String::from(\"class\"),\n", "file_path": "src/parse/ast/node.rs", "rank": 19, "score": 158887.34536744602 }, { "content": "#[test]\n\nfn parse_set() {\n\n let source = resource_content(true, &[\"collection\"], \"set.mamba\");\n\n assert!(parse(&tokenize(&source).unwrap()).is_ok());\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 20, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn set_verify() {\n\n let source = String::from(\"{a, b}\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let _statements;\n\n let elements = match ast.node {\n\n Node::Script { statements, .. } => {\n\n _statements = statements;\n\n match &_statements.first().expect(\"script empty.\").node {\n\n Node::Set { elements } => elements,\n\n _ => panic!(\"first element script was not set.\")\n\n }\n\n }\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(elements[0].node, Node::Id { lit: String::from(\"a\") });\n\n assert_eq!(elements[1].node, Node::Id { lit: String::from(\"b\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 21, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn list_verify() {\n\n let source = String::from(\"[a, b]\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let _statements;\n\n let elements = match ast.node {\n\n Node::Script { statements, .. } => {\n\n _statements = statements;\n\n match &_statements.first().expect(\"script empty.\").node {\n\n Node::List { elements } => elements,\n\n _ => panic!(\"first element script was not list.\")\n\n }\n\n }\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(elements[0].node, Node::Id { lit: String::from(\"a\") });\n\n assert_eq!(elements[1].node, Node::Id { lit: String::from(\"b\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 22, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn parse_tuple() {\n\n let source = resource_content(true, &[\"collection\"], \"tuple.mamba\");\n\n parse(&tokenize(&source).unwrap()).unwrap();\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 23, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn list_builder_verify() {\n\n let item = to_pos!(Node::Id { lit: String::from(\"a\") });\n\n let conditions = vec![];\n\n let list_builder = to_pos!(Node::ListBuilder { item, conditions });\n\n\n\n let desugar_result = desugar(&list_builder);\n\n assert!(desugar_result.is_err());\n\n}\n", "file_path": "tests/desugar/collection.rs", "rank": 24, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn list_expression() {\n\n let source = resource_content(true, &[\"collection\"], \"tuple.mamba\");\n\n parse(&tokenize(&source).unwrap()).unwrap();\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 25, "score": 158805.95428817853 }, { "content": "#[test]\n\nfn set_builder_verify() {\n\n let item = to_pos!(Node::Id { lit: String::from(\"a\") });\n\n let conditions = vec![];\n\n let list_builder = to_pos!(Node::SetBuilder { item, conditions });\n\n\n\n let desugar_result = desugar(&list_builder);\n\n assert!(desugar_result.is_err());\n\n}\n\n\n", "file_path": "tests/desugar/collection.rs", "rank": 26, "score": 158805.95428817853 }, { "content": "#[test]\n\n#[ignore]\n\nfn parse_map() {\n\n let source = resource_content(true, &[\"collection\"], \"map.mamba\");\n\n parse(&tokenize(&source).unwrap()).unwrap();\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 27, "score": 158805.87063917215 }, { "content": "#[test]\n\nfn from_import_as_verify() {\n\n let _break = to_pos!(Node::FromImport {\n\n id: to_pos!(Node::Id { lit: String::from(\"f\") }),\n\n import: to_pos!(Node::Import {\n\n import: vec![to_pos_unboxed!(Node::Id { lit: String::from(\"a\") })],\n\n _as: vec![to_pos_unboxed!(Node::Id { lit: String::from(\"b\") })]\n\n })\n\n });\n\n\n\n assert_eq!(desugar(&_break).unwrap(), Core::FromImport {\n\n from: Box::from(Core::Id { lit: String::from(\"f\") }),\n\n import: Box::from(Core::ImportAs {\n\n imports: vec![Core::Id { lit: String::from(\"a\") }],\n\n alias: vec![Core::Id { lit: String::from(\"b\") }]\n\n })\n\n });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 28, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn print_verify() {\n\n let expr = to_pos!(Node::Str { lit: String::from(\"a\"), expressions: vec![] });\n\n let print_stmt = to_pos!(Node::Print { expr });\n\n assert_eq!(desugar(&print_stmt).unwrap(), Core::Print {\n\n expr: Box::from(Core::Str { string: String::from(\"a\") })\n\n });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 30, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn core_while_statements() {\n\n let source = resource_content(true, &[\"control_flow\"], \"while.mamba\");\n\n to_py!(source);\n\n}\n", "file_path": "tests/core/control_flow.rs", "rank": 31, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn return_verify() {\n\n let expr = to_pos!(Node::Str { lit: String::from(\"a\"), expressions: vec![] });\n\n let print_stmt = to_pos!(Node::Return { expr });\n\n\n\n assert_eq!(desugar(&print_stmt).unwrap(), Core::Return {\n\n expr: Box::from(Core::Str { string: String::from(\"a\") })\n\n });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 32, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn break_verify() {\n\n let _break = to_pos!(Node::Break);\n\n assert_eq!(desugar(&_break).unwrap(), Core::Break);\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 33, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn core_for_statements() {\n\n let source = resource_content(true, &[\"control_flow\"], \"for_statements.mamba\");\n\n to_py!(source);\n\n}\n\n\n", "file_path": "tests/core/control_flow.rs", "rank": 34, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn statement_as_param() {\n\n let source = resource_content(false, &[\"type\", \"function\"], \"statement_as_param.mamba\");\n\n check_all(&[(*parse(&tokenize(&source).unwrap()).unwrap(), None, None)]).unwrap_err();\n\n}\n\n\n", "file_path": "tests/check/invalid/function.rs", "rank": 35, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn self_verify() {\n\n let _break = to_pos!(Node::_Self);\n\n assert_eq!(desugar(&_break).unwrap(), Core::Id { lit: String::from(\"self\") });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 36, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn pass_verify() {\n\n let pass = to_pos!(Node::Pass);\n\n assert_eq!(desugar(&pass).unwrap(), Core::Pass);\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 38, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn continue_verify() {\n\n let _continue = to_pos!(Node::Continue);\n\n assert_eq!(desugar(&_continue).unwrap(), Core::Continue);\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 39, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn init_verify() {\n\n let _break = to_pos!(Node::Init);\n\n assert_eq!(desugar(&_break).unwrap(), Core::Id { lit: String::from(\"init\") });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 40, "score": 158790.68834173994 }, { "content": "#[test]\n\nfn import_verify() {\n\n let _break = to_pos!(Node::Import {\n\n import: vec![to_pos_unboxed!(Node::Id { lit: String::from(\"a\") })],\n\n _as: vec![to_pos_unboxed!(Node::Id { lit: String::from(\"b\") })]\n\n });\n\n\n\n assert_eq!(desugar(&_break).unwrap(), Core::ImportAs {\n\n imports: vec![Core::Id { lit: String::from(\"a\") }],\n\n alias: vec![Core::Id { lit: String::from(\"b\") }]\n\n });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 41, "score": 158790.68834173994 }, { "content": "fn parse_post_expr(pre: &AST, it: &mut LexIterator) -> ParseResult {\n\n it.peek(\n\n &|it, lex| match lex.token {\n\n Token::Assign => {\n\n let res = parse_reassignment(pre, it)?;\n\n parse_post_expr(&res, it)\n\n }\n\n Token::LRBrack | Token::Point => {\n\n let res = parse_call(pre, it)?;\n\n parse_post_expr(&res, it)\n\n }\n\n _ =>\n\n if is_start_expression_exclude_unary(lex) {\n\n let res = parse_call(pre, it)?;\n\n parse_post_expr(&res, it)\n\n } else {\n\n Ok(Box::from(pre.clone()))\n\n },\n\n },\n\n Ok(Box::from(pre.clone()))\n\n )\n\n}\n\n\n", "file_path": "src/parse/expression.rs", "rank": 42, "score": 158774.46695160362 }, { "content": "/// Check if AST is reassignable: is reassignable if valid identifier.\n\nfn check_reassignable(ast: &AST) -> TypeResult<()> {\n\n match &ast.node {\n\n Node::PropertyCall { property, .. } => check_reassignable(property),\n\n _ =>\n\n if Identifier::try_from(ast).is_ok() {\n\n Ok(())\n\n } else {\n\n let msg = format!(\"Cannot reassign to {}\", &ast.node);\n\n Err(vec![TypeErr::new(&ast.pos, &msg)])\n\n },\n\n }\n\n}\n", "file_path": "src/check/constrain/generate/call.rs", "rank": 43, "score": 157336.7895961032 }, { "content": "pub fn parse_expressions(it: &mut LexIterator) -> ParseResult<Vec<AST>> {\n\n let start = it.start_pos(\"expression\")?;\n\n let mut expressions = vec![];\n\n it.peek_while_fn(&is_start_expression, &mut |it, _| {\n\n expressions.push(*it.parse(&parse_expression, \"expressions\", &start)?);\n\n it.eat_if(&Token::Comma);\n\n Ok(())\n\n })?;\n\n Ok(expressions)\n\n}\n", "file_path": "src/parse/collection.rs", "rank": 44, "score": 155954.51569707802 }, { "content": "#[test]\n\nfn using_old_resource_in_with() {\n\n let source = resource_content(false, &[\"type\", \"error\"], \"using_old_resource_in_with.mamba\");\n\n check_all(&[(*parse(&tokenize(&source).unwrap()).unwrap(), None, None)]).unwrap_err();\n\n}\n\n\n", "file_path": "tests/check/invalid/error.rs", "rank": 45, "score": 155943.20201097685 }, { "content": "// TODO look at whether we can handle class and type tokens more elegantly\n\npub fn parse_statements(it: &mut LexIterator) -> ParseResult<Vec<AST>> {\n\n let start = it.start_pos(\"block\")?;\n\n let mut statements: Vec<AST> = Vec::new();\n\n\n\n it.peek_while_not_tokens(\n\n &[Token::Dedent, Token::Class, Token::Type],\n\n &mut |it, lex| match &lex.token {\n\n Token::NL => {\n\n it.eat(&Token::NL, \"block\")?;\n\n Ok(())\n\n }\n\n Token::Comment(comment) => {\n\n let end = it.eat(&Token::Comment(comment.clone()), \"block\")?;\n\n let node = Node::Comment { comment: comment.clone() };\n\n statements.push(AST::new(&lex.pos.union(&end), node));\n\n Ok(())\n\n }\n\n Token::DocStr(doc_str) => {\n\n let end = it.eat(&Token::DocStr(doc_str.clone()), \"block\")?;\n\n let node = Node::DocStr { lit: doc_str.clone() };\n", "file_path": "src/parse/block.rs", "rank": 46, "score": 155941.56831515848 }, { "content": "#[test]\n\nfn range_step_verify() {\n\n let from = to_pos!(Node::Id { lit: String::from(\"a\") });\n\n let to = to_pos!(Node::Id { lit: String::from(\"b\") });\n\n let step = Some(to_pos!(Node::Id { lit: String::from(\"c\") }));\n\n let range = to_pos!(Node::Range { from, to, inclusive: false, step });\n\n\n\n let (from, to, step) = match desugar(&range) {\n\n Ok(Core::Range { from, to, step }) => (from, to, step),\n\n other => panic!(\"Expected range but was {:?}\", other)\n\n };\n\n\n\n assert_eq!(*from, Core::Id { lit: String::from(\"a\") });\n\n assert_eq!(*to, Core::Id { lit: String::from(\"b\") });\n\n assert_eq!(*step, Core::Id { lit: String::from(\"c\") });\n\n}\n", "file_path": "tests/desugar/control_flow.rs", "rank": 47, "score": 155932.7670295942 }, { "content": "#[test]\n\nfn if_then_missing_body() {\n\n let source = String::from(\"if a then b else\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 48, "score": 155913.30016832624 }, { "content": "#[test]\n\nfn if_missing_body() {\n\n let source = String::from(\"if a then\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 49, "score": 155913.30016832624 }, { "content": "#[test]\n\nfn while_missing_body() {\n\n let source = String::from(\"while a do\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 50, "score": 155913.30016832624 }, { "content": "#[test]\n\nfn fun_def_with_body_verify() {\n\n let definition = to_pos!(Node::FunDef {\n\n id: to_pos!(Node::Id { lit: String::from(\"fun\") }),\n\n pure: false,\n\n private: false,\n\n fun_args: vec![\n\n to_pos_unboxed!(Node::Id { lit: String::from(\"arg1\") }),\n\n to_pos_unboxed!(Node::Id { lit: String::from(\"arg2\") })\n\n ],\n\n ret_ty: None,\n\n raises: vec![],\n\n body: Some(to_pos!(Node::Real { lit: String::from(\"2.4\") }))\n\n });\n\n\n\n let (private, id, args, body) = match desugar(&definition) {\n\n Ok(Core::FunDef { private, id, arg, body, .. }) => (private, id, arg, body),\n\n other => panic!(\"Expected fun def but got: {:?}.\", other)\n\n };\n\n\n\n assert_eq!(private, false);\n\n assert_eq!(*id, Core::Id { lit: String::from(\"fun\") });\n\n\n\n assert_eq!(args.len(), 2);\n\n assert_eq!(args[0], Core::Id { lit: String::from(\"arg1\") });\n\n assert_eq!(args[1], Core::Id { lit: String::from(\"arg2\") });\n\n assert_eq!(*body, Core::Float { float: String::from(\"2.4\") });\n\n}\n\n\n", "file_path": "tests/desugar/definition.rs", "rank": 51, "score": 155913.30016832624 }, { "content": "#[test]\n\nfn for_missing_body() {\n\n let source = String::from(\"for a in c\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 52, "score": 155913.30016832624 }, { "content": "#[test]\n\nfn tuple_empty_verify() {\n\n let source = String::from(\"()\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let _statements;\n\n let elements = match ast.node {\n\n Node::Script { statements, .. } => {\n\n _statements = statements;\n\n match &_statements.first().expect(\"script empty.\").node {\n\n Node::Tuple { elements } => elements,\n\n _ => panic!(\"first element script was not tuple.\")\n\n }\n\n }\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(elements.len(), 0);\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 54, "score": 155703.69637347964 }, { "content": "#[test]\n\nfn set_builder_verify() {\n\n let source = String::from(\"{a | c, d}\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (items, conditions) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::SetBuilder { item, conditions } => (item.clone(), conditions.clone()),\n\n _ => panic!(\"first element script was not set builder.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(items.node, Node::Id { lit: String::from(\"a\") });\n\n\n\n assert_eq!(conditions.len(), 2);\n\n assert_eq!(conditions[0].node, Node::Id { lit: String::from(\"c\") });\n\n assert_eq!(conditions[1].node, Node::Id { lit: String::from(\"d\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 55, "score": 155703.69637347964 }, { "content": "#[test]\n\nfn tuple_multiple_verify() {\n\n let source = String::from(\"(d, c)\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let _statements;\n\n let elements = match ast.node {\n\n Node::Script { statements, .. } => {\n\n _statements = statements;\n\n match &_statements.first().expect(\"script empty.\").node {\n\n Node::Tuple { elements } => elements,\n\n _ => panic!(\"first element script was not tuple.\")\n\n }\n\n }\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(elements.len(), 2);\n\n assert_eq!(elements[0].node, Node::Id { lit: String::from(\"d\") });\n\n assert_eq!(elements[1].node, Node::Id { lit: String::from(\"c\") });\n\n}\n", "file_path": "tests/parse/valid/collection.rs", "rank": 56, "score": 155703.69637347964 }, { "content": "#[test]\n\nfn list_builder_verify() {\n\n let source = String::from(\"[a | c, d]\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (items, conditions) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::ListBuilder { item, conditions } => (item.clone(), conditions.clone()),\n\n _ => panic!(\"first element script was not list builder.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(items.node, Node::Id { lit: String::from(\"a\") });\n\n\n\n assert_eq!(conditions.len(), 2);\n\n assert_eq!(conditions[0].node, Node::Id { lit: String::from(\"c\") });\n\n assert_eq!(conditions[1].node, Node::Id { lit: String::from(\"d\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/collection.rs", "rank": 57, "score": 155703.69637347964 }, { "content": "#[test]\n\nfn print_verify() {\n\n let source = String::from(\"print some_value\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let expr = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Print { expr } => expr.clone(),\n\n _ => panic!(\"first element script was not reassign.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(expr.node, Node::Id { lit: String::from(\"some_value\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 59, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn range_missing_to() {\n\n let source = String::from(\"a ..\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 60, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn pure_file() {\n\n let source = String::from(\"pure\");\n\n let ast = parse(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let pure = match ast.node {\n\n Node::File { pure, .. } => pure,\n\n _ => panic!(\"ast was not file.\")\n\n };\n\n\n\n assert!(pure);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 61, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn underscore_verify() {\n\n let source = String::from(\"_\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let ast = match ast.node {\n\n Node::Script { statements, .. } => statements.first().expect(\"script empty.\").clone(),\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(ast.node, Node::Underscore);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 62, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn raises_empty_verify() {\n\n let type_def = to_pos!(Node::Raises {\n\n expr_or_stmt: Box::from(to_pos!(Node::Id { lit: String::from(\"a\") })),\n\n errors: vec![]\n\n });\n\n assert_eq!(desugar(&type_def).unwrap(), Core::Id { lit: String::from(\"a\") });\n\n}\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 63, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn quest_or_on_nothing() {\n\n let source = String::from(\"?or\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 64, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn reassign_verify() {\n\n let source = String::from(\"id <- new_value\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (left, right) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Reassign { left, right } => (left.clone(), right.clone()),\n\n _ => panic!(\"first element script was not reassign.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(left.node, Node::Id { lit: String::from(\"id\") });\n\n assert_eq!(right.node, Node::Id { lit: String::from(\"new_value\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 65, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn return_verify() {\n\n let source = String::from(\"return some_value\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let expr = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Return { expr } => expr.clone(),\n\n _ => panic!(\"first element script was not reassign.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(expr.node, Node::Id { lit: String::from(\"some_value\") });\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 66, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn return_empty_verify() {\n\n let print_stmt = to_pos!(Node::ReturnEmpty);\n\n assert_eq!(desugar(&print_stmt).unwrap(), Core::Return { expr: Box::from(Core::None) });\n\n}\n\n\n", "file_path": "tests/desugar/expression_and_statements.rs", "rank": 67, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn pass_verify() {\n\n let source = String::from(\"pass\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let ast = match ast.node {\n\n Node::Script { statements, .. } => statements.first().expect(\"script empty.\").clone(),\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(ast.node, Node::Pass);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 68, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn import_as_verify() {\n\n let source = String::from(\"import a, b as c, d\");\n\n let ast = parse(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let imports = match ast.node {\n\n Node::File { modules, .. } => modules,\n\n _ => panic!(\"ast was not file.\")\n\n };\n\n\n\n assert_eq!(imports.len(), 1);\n\n let (_use, _as) = match &imports[0].node {\n\n Node::Import { import, _as } => (import, _as),\n\n other => panic!(\"Expected import but was {:?}.\", other)\n\n };\n\n\n\n assert_eq!(_use.len(), 2);\n\n assert_eq!(_use[0].node, Node::Id { lit: String::from(\"a\") });\n\n assert_eq!(_use[1].node, Node::Id { lit: String::from(\"b\") });\n\n assert_eq!(_as.len(), 2);\n\n assert_eq!(_as[0].node, Node::Id { lit: String::from(\"c\") });\n\n assert_eq!(_as[1].node, Node::Id { lit: String::from(\"d\") });\n\n}\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 69, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn range_verify() {\n\n let source = String::from(\"hello .. world\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (from, to, inclusive, step) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Range { from, to, inclusive, step } =>\n\n (from.clone(), to.clone(), inclusive.clone(), step.clone()),\n\n _ => panic!(\"first element script was not range.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(from.node, Node::Id { lit: String::from(\"hello\") });\n\n assert_eq!(to.node, Node::Id { lit: String::from(\"world\") });\n\n assert!(!inclusive);\n\n assert_eq!(step, None);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 70, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn import_verify() {\n\n let source = String::from(\"import c\");\n\n let ast = parse(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let imports = match ast.node {\n\n Node::File { modules, .. } => modules,\n\n _ => panic!(\"ast was not file.\")\n\n };\n\n\n\n assert_eq!(imports.len(), 1);\n\n let (_use, _as) = match &imports[0].node {\n\n Node::Import { import, _as } => (import, _as),\n\n other => panic!(\"Expected import but was {:?}.\", other)\n\n };\n\n\n\n assert_eq!(_use.len(), 1);\n\n assert_eq!(_use[0].node, Node::Id { lit: String::from(\"c\") });\n\n assert_eq!(_as.len(), 0);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 71, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn from_import_verify() {\n\n let source = String::from(\"from a import b\");\n\n let ast = parse(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let imports = match ast.node {\n\n Node::File { modules, .. } => modules,\n\n _ => panic!(\"ast was not file.\")\n\n };\n\n\n\n assert_eq!(imports.len(), 1);\n\n let (id, _use, _as) = match &imports[0].node {\n\n Node::FromImport { id, import } => match &import.node {\n\n Node::Import { import, _as } => (id, import, _as),\n\n other => panic!(\"Expected import but was {:?}.\", other)\n\n },\n\n other => panic!(\"Expected from import but was {:?}.\", other)\n\n };\n\n\n\n assert_eq!(id.node, Node::Id { lit: String::from(\"a\") });\n\n assert_eq!(_use.len(), 1);\n\n assert_eq!(_use[0].node, Node::Id { lit: String::from(\"b\") });\n\n assert_eq!(_as.len(), 0);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 72, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn range_missing_from() {\n\n let source = String::from(\".. b\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 73, "score": 155688.81122307276 }, { "content": "#[test]\n\nfn match_missing_arms() {\n\n let source = String::from(\"match a with\\n \");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 75, "score": 152928.73158225731 }, { "content": "#[test]\n\nfn match_missing_condition() {\n\n let source = String::from(\"match\\n a => b\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 76, "score": 152928.73158225731 }, { "content": "#[test]\n\nfn quest_or_missing_alternative() {\n\n let source = String::from(\"a ?or\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 77, "score": 152737.91537094896 }, { "content": "#[test]\n\nfn range_inc_missing_from() {\n\n let source = String::from(\"..= b\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 78, "score": 152737.91537094896 }, { "content": "#[test]\n\nfn print_missing_arg() {\n\n let source = String::from(\"print\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 79, "score": 152737.91537094896 }, { "content": "#[test]\n\nfn reassign_missing_value() {\n\n let source = String::from(\"a <-\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 80, "score": 152737.91537094896 }, { "content": "#[test]\n\nfn range_incl_verify() {\n\n let source = String::from(\"foo ..= bar\");\n\n let ast = parse_direct(&tokenize(&source).unwrap()).unwrap();\n\n\n\n let (from, to, inclusive, step) = match ast.node {\n\n Node::Script { statements, .. } => match &statements.first().expect(\"script empty.\").node {\n\n Node::Range { from, to, inclusive, step } =>\n\n (from.clone(), to.clone(), inclusive.clone(), step.clone()),\n\n _ => panic!(\"first element script was not range inclusive.\")\n\n },\n\n _ => panic!(\"ast was not script.\")\n\n };\n\n\n\n assert_eq!(from.node, Node::Id { lit: String::from(\"foo\") });\n\n assert_eq!(to.node, Node::Id { lit: String::from(\"bar\") });\n\n assert!(inclusive);\n\n assert_eq!(step, None);\n\n}\n\n\n", "file_path": "tests/parse/valid/expression_and_statement.rs", "rank": 81, "score": 152737.91537094896 }, { "content": "#[test]\n\nfn range_incl_missing_to() {\n\n let source = String::from(\"a ..=\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/expression_and_statement.rs", "rank": 82, "score": 152737.91537094896 }, { "content": "fn field_name(ast: &AST) -> TypeResult<String> {\n\n match &ast.node {\n\n Node::Id { lit } => Ok(lit.clone()),\n\n _ => Err(vec![TypeErr::new(&ast.pos, \"Expected valid identifier\")])\n\n }\n\n}\n", "file_path": "src/check/context/field/generic.rs", "rank": 83, "score": 152229.57785079448 }, { "content": "#[test]\n\nfn match_missing_arms_no_newline() {\n\n let source = String::from(\"match a\");\n\n parse_direct(&tokenize(&source).unwrap()).unwrap_err();\n\n}\n\n\n", "file_path": "tests/parse/invalid/control_flow.rs", "rank": 84, "score": 150113.52199317253 }, { "content": "pub fn function_name(ast: &AST) -> TypeResult<DirectName> {\n\n Ok(DirectName::from(match &ast.node {\n\n Node::Id { lit } => lit.as_str(),\n\n Node::Init => \"init\",\n\n Node::SqrtOp => \"sqrt\",\n\n Node::GeOp => function::GE,\n\n Node::LeOp => function::LE,\n\n Node::EqOp => function::EQ,\n\n Node::AddOp => function::ADD,\n\n Node::SubOp => function::SUB,\n\n Node::PowOp => function::POW,\n\n Node::MulOp => function::MUL,\n\n Node::ModOp => function::MOD,\n\n Node::DivOp => function::DIV,\n\n Node::FDivOp => function::FDIV,\n\n _ => return Err(vec![TypeErr::new(&ast.pos, \"Expected valid function name\")])\n\n }))\n\n}\n", "file_path": "src/check/context/function/generic.rs", "rank": 85, "score": 146126.9087792087 }, { "content": "pub fn argument_name(ast: &AST) -> Result<String, TypeErr> {\n\n match &ast.node {\n\n Node::Id { lit } => Ok(lit.clone()),\n\n Node::_Self => Ok(String::from(SELF)),\n\n _ => Err(TypeErr::new(&ast.pos, \"Expected identifier\"))\n\n }\n\n}\n", "file_path": "src/check/context/arg/generic.rs", "rank": 86, "score": 143195.31664142176 }, { "content": "fn equal_optional(this: &Option<Box<AST>>, that: &Option<Box<AST>>) -> bool {\n\n if let (Some(this), Some(that)) = (this, that) {\n\n this.equal_structure(that)\n\n } else {\n\n true\n\n }\n\n}\n\n\n", "file_path": "src/parse/ast/node.rs", "rank": 87, "score": 142930.33892381226 }, { "content": "#[test]\n\nfn with_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"error\"], &[\"error\", \"target\"], \"with\")\n\n}\n", "file_path": "tests/output/valid/error.rs", "rank": 88, "score": 142833.23231494805 }, { "content": "#[test]\n\nfn call_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"function\"], &[\"function\", \"target\"], \"calls\")\n\n}\n\n\n", "file_path": "tests/output/valid/function.rs", "rank": 89, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn handle_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"error\"], &[\"error\", \"target\"], \"handle\")\n\n}\n\n\n", "file_path": "tests/output/valid/error.rs", "rank": 90, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn for_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"control_flow\"], &[\"control_flow\", \"target\"], \"for_statements\")\n\n}\n\n\n", "file_path": "tests/output/valid/control_flow.rs", "rank": 91, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn parent_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"class\"], &[\"class\", \"target\"], \"parent\")\n\n}\n\n\n", "file_path": "tests/output/valid/class.rs", "rank": 92, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn definition_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"function\"], &[\"function\", \"target\"], \"definition\")\n\n}\n\n\n", "file_path": "tests/output/valid/function.rs", "rank": 93, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn if_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"control_flow\"], &[\"control_flow\", \"target\"], \"if\")\n\n}\n\n\n", "file_path": "tests/output/valid/control_flow.rs", "rank": 94, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn raise_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"error\"], &[\"error\", \"target\"], \"raise\")\n\n}\n\n\n", "file_path": "tests/output/valid/error.rs", "rank": 95, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn exception_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"error\"], &[\"error\", \"target\"], \"exception\")\n\n}\n\n\n", "file_path": "tests/output/valid/error.rs", "rank": 96, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn import_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"class\"], &[\"class\", \"target\"], \"import\")\n\n}\n\n\n", "file_path": "tests/output/valid/class.rs", "rank": 97, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn types_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"class\"], &[\"class\", \"target\"], \"types\")\n\n}\n", "file_path": "tests/output/valid/class.rs", "rank": 98, "score": 140157.93582353095 }, { "content": "#[test]\n\nfn while_ast_verify() -> Result<(), Vec<String>> {\n\n test_directory(true, &[\"control_flow\"], &[\"control_flow\", \"target\"], \"while\")\n\n}\n\n\n", "file_path": "tests/output/valid/control_flow.rs", "rank": 99, "score": 140157.93582353095 } ]
Rust
src/lib/ui/carnelian/src/render/generic/spinel/composition.rs
re995/fuchsia
02cb86f760af2aac974ba654186b73af8c16638f
use std::{ops::RangeBounds, ptr, slice}; use euclid::default::{Rect, Size2D}; use spinel_rs_sys::*; use crate::{ color::Color, drawing::DisplayRotation, render::generic::{ spinel::{init, InnerContext, Spinel}, BlendMode, Composition, Fill, FillRule, Layer, Style, }, }; fn group_layers( spn_styling: SpnStyling, top_group: SpnGroupId, layers: &[Layer<Spinel>], layer_id_start: u32, ) { fn cmds_len(style: &Style) -> usize { let fill_rule_len = match style.fill_rule { FillRule::NonZero => 1, FillRule::EvenOdd => 1, }; let fill_len = match &style.fill { Fill::Solid(..) => 3, Fill::Gradient(..) => 3, }; let blend_mode_len = match style.blend_mode { BlendMode::Over => 1, _ => 1, }; 1 + fill_rule_len + fill_len + blend_mode_len } for (i, Layer { style, .. }) in layers.iter().enumerate() { let cmds = unsafe { let len = cmds_len(style); let data = init(|ptr| { spn!(spn_styling_group_layer( spn_styling, top_group, layer_id_start + i as u32, len as u32, ptr )) }); slice::from_raw_parts_mut(data, len) }; cmds[0] = SpnCommand::SpnStylingOpcodeCoverWipZero; let mut cursor = 1; match style.fill_rule { FillRule::NonZero => { cmds[cursor] = SpnCommand::SpnStylingOpcodeCoverNonzero; cursor += 1; } FillRule::EvenOdd => { cmds[cursor] = SpnCommand::SpnStylingOpcodeCoverEvenodd; cursor += 1; } } match &style.fill { Fill::Solid(color) => { let color = color.to_linear_premult_rgba(); unsafe { spn_styling_layer_fill_rgba_encoder(&mut cmds[cursor], color.as_ptr()); } cursor += 3; } Fill::Gradient(gradient) => { let color = gradient.stops.first().unwrap().0.to_linear_premult_rgba(); unsafe { spn_styling_layer_fill_rgba_encoder(&mut cmds[cursor], color.as_ptr()); } cursor += 3; } } cmds[cursor] = match style.blend_mode { BlendMode::Over => SpnCommand::SpnStylingOpcodeBlendOver, _ => SpnCommand::SpnStylingOpcodeBlendOver, } } } #[derive(Clone, Debug)] pub struct SpinelComposition { pub(crate) layers: Vec<Layer<Spinel>>, pub(crate) background_color: [f32; 4], } impl SpinelComposition { pub(crate) fn set_up_spn_composition( &self, context: &InnerContext, raster_builder: SpnRasterBuilder, composition: SpnComposition, previous_rasters: &mut Vec<SpnRaster>, size: Size2D<u32>, display_rotation: DisplayRotation, clip: Rect<u32>, ) { unsafe { let clip = [clip.min_x(), clip.min_y(), clip.max_x(), clip.max_y()]; spn!(spn_composition_reset(composition)); spn!(spn_composition_set_clip(composition, clip.as_ptr(),)); } for raster in previous_rasters.drain(..) { let i = self.layers.len(); unsafe { spn!(spn_composition_place(composition, &raster, &(i as u32), ptr::null(), 1)); } context.get_checked().map(|context| unsafe { spn!(spn_raster_release(context, &raster as *const _, 1)) }); } for (i, Layer { raster, .. }) in self.layers.iter().enumerate() { for (paths, txty) in raster.rasters.iter() { unsafe { spn!(spn_raster_builder_begin(raster_builder)); } for (path, transform) in paths.iter() { const SPINEL_TRANSFORM_MULTIPLIER: f32 = 32.0; let transform = transform .then_translate(*txty) .then(&display_rotation.transform(&size.to_f32())); let transform = SpnTransform { sx: transform.m11 * SPINEL_TRANSFORM_MULTIPLIER, shx: transform.m21 * SPINEL_TRANSFORM_MULTIPLIER, tx: transform.m31 * SPINEL_TRANSFORM_MULTIPLIER, shy: transform.m12 * SPINEL_TRANSFORM_MULTIPLIER, sy: transform.m22 * SPINEL_TRANSFORM_MULTIPLIER, ty: transform.m32 * SPINEL_TRANSFORM_MULTIPLIER, w0: 0.0, w1: 0.0, }; let clip = SpnClip { x0: std::f32::MIN, y0: std::f32::MIN, x1: std::f32::MAX, y1: std::f32::MAX, }; unsafe { spn!(spn_raster_builder_add( raster_builder, &*path.path, ptr::null_mut(), &transform, ptr::null_mut(), &clip, 1, )); } } let raster = unsafe { init(|ptr| spn!(spn_raster_builder_end(raster_builder, ptr))) }; unsafe { spn!(spn_composition_place(composition, &raster, &(i as u32), ptr::null(), 1)); } previous_rasters.push(raster); } } } pub(crate) fn spn_styling( &self, context: &InnerContext, needs_linear_to_srgb_opcode: bool, ) -> Option<SpnStyling> { const PARENTS: u32 = 0; const ENTER_CMDS: u32 = 1; const GROUP_SIZE: u32 = 6; const MAX_LAYER_CMDS: u32 = 6; let leave_cmds: u32 = if needs_linear_to_srgb_opcode { 5 } else { 4 }; let num_clear_layers = 1; let len = self.layers.len() as u32 + num_clear_layers; let styling_len = len * MAX_LAYER_CMDS + PARENTS + ENTER_CMDS + leave_cmds + GROUP_SIZE; let spn_styling = context.get_checked().map(|context| unsafe { init(|ptr| spn!(spn_styling_create(context, ptr, len, styling_len))) })?; let top_group = unsafe { init(|ptr| spn!(spn_styling_group_alloc(spn_styling, ptr))) }; unsafe { spn!(spn_styling_group_parents(spn_styling, top_group, PARENTS, ptr::null_mut())); if len != 0 { spn!(spn_styling_group_range_lo(spn_styling, top_group, 0)); spn!(spn_styling_group_range_hi(spn_styling, top_group, len - 1)); } } let cmds_enter = unsafe { let data = init(|ptr| spn!(spn_styling_group_enter(spn_styling, top_group, ENTER_CMDS, ptr))); slice::from_raw_parts_mut(data, 1) }; cmds_enter[0] = SpnCommand::SpnStylingOpcodeColorAccZero; let cmds_leave = unsafe { let data = init(|ptr| spn!(spn_styling_group_leave(spn_styling, top_group, leave_cmds, ptr))); slice::from_raw_parts_mut(data, leave_cmds as usize) }; unsafe { spn_styling_background_over_encoder(&mut cmds_leave[0], self.background_color.as_ptr()); } if needs_linear_to_srgb_opcode { cmds_leave[3] = SpnCommand::SpnStylingOpcodeColorAccLinearToSrgb; cmds_leave[4] = SpnCommand::SpnStylingOpcodeColorAccStoreToSurface; } else { cmds_leave[3] = SpnCommand::SpnStylingOpcodeColorAccStoreToSurface; } group_layers(spn_styling, top_group, &self.layers, 0); let clear_cmds = unsafe { let data = init(|ptr| { let len = 5; spn!(spn_styling_group_layer( spn_styling, top_group, self.layers.len() as u32, len, ptr )) }); slice::from_raw_parts_mut(data, len as usize) }; clear_cmds[0] = SpnCommand::SpnStylingOpcodeCoverWipZero; unsafe { spn_styling_layer_fill_rgba_encoder(&mut clear_cmds[1], self.background_color.as_ptr()); } clear_cmds[4] = SpnCommand::SpnStylingOpcodeBlendOver; unsafe { spn!(spn_styling_seal(spn_styling)); } Some(spn_styling) } } impl Composition<Spinel> for SpinelComposition { fn new(background_color: Color) -> Self { Self { layers: vec![], background_color: background_color.to_linear_premult_rgba() } } fn with_layers( layers: impl IntoIterator<Item = Layer<Spinel>>, background_color: Color, ) -> Self { Self { layers: layers.into_iter().collect(), background_color: background_color.to_linear_premult_rgba(), } } fn clear(&mut self) { self.layers.clear(); } fn replace<R, I>(&mut self, range: R, with: I) where R: RangeBounds<usize>, I: IntoIterator<Item = Layer<Spinel>>, { self.layers.splice(range, with); } }
use std::{ops::RangeBounds, ptr, slice}; use euclid::default::{Rect, Size2D}; use spinel_rs_sys::*; use crate::{ color::Color, drawing::DisplayRotation, render::generic::{ spinel::{init, InnerContext, Spinel}, BlendMode, Composition, Fill, FillRule, Layer, Style, }, }; fn group_layers( spn_styling: SpnStyling, top_group: SpnGroupId, layers: &[Layer<Spinel>], layer_id_start: u32, ) { fn cmds_len(style: &Style) -> usize { let fill_rule_len = match style.fill_rule { FillRule::NonZero => 1, FillRule::EvenOdd => 1, }; let fill_len = match &style.fill { Fill::Solid(..) => 3, Fill::Gradient(..) => 3, }; let blend_mode_len = match style.blend_mode { BlendMode::Over => 1, _ => 1, }; 1 + fill_rule_len + fill_len + blend_mode_len } for (i, Layer { style, .. }) in layers.iter().enumerate() { let cmds = unsafe { let len = cmds_len(style); let data =
; slice::from_raw_parts_mut(data, len) }; cmds[0] = SpnCommand::SpnStylingOpcodeCoverWipZero; let mut cursor = 1; match style.fill_rule { FillRule::NonZero => { cmds[cursor] = SpnCommand::SpnStylingOpcodeCoverNonzero; cursor += 1; } FillRule::EvenOdd => { cmds[cursor] = SpnCommand::SpnStylingOpcodeCoverEvenodd; cursor += 1; } } match &style.fill { Fill::Solid(color) => { let color = color.to_linear_premult_rgba(); unsafe { spn_styling_layer_fill_rgba_encoder(&mut cmds[cursor], color.as_ptr()); } cursor += 3; } Fill::Gradient(gradient) => { let color = gradient.stops.first().unwrap().0.to_linear_premult_rgba(); unsafe { spn_styling_layer_fill_rgba_encoder(&mut cmds[cursor], color.as_ptr()); } cursor += 3; } } cmds[cursor] = match style.blend_mode { BlendMode::Over => SpnCommand::SpnStylingOpcodeBlendOver, _ => SpnCommand::SpnStylingOpcodeBlendOver, } } } #[derive(Clone, Debug)] pub struct SpinelComposition { pub(crate) layers: Vec<Layer<Spinel>>, pub(crate) background_color: [f32; 4], } impl SpinelComposition { pub(crate) fn set_up_spn_composition( &self, context: &InnerContext, raster_builder: SpnRasterBuilder, composition: SpnComposition, previous_rasters: &mut Vec<SpnRaster>, size: Size2D<u32>, display_rotation: DisplayRotation, clip: Rect<u32>, ) { unsafe { let clip = [clip.min_x(), clip.min_y(), clip.max_x(), clip.max_y()]; spn!(spn_composition_reset(composition)); spn!(spn_composition_set_clip(composition, clip.as_ptr(),)); } for raster in previous_rasters.drain(..) { let i = self.layers.len(); unsafe { spn!(spn_composition_place(composition, &raster, &(i as u32), ptr::null(), 1)); } context.get_checked().map(|context| unsafe { spn!(spn_raster_release(context, &raster as *const _, 1)) }); } for (i, Layer { raster, .. }) in self.layers.iter().enumerate() { for (paths, txty) in raster.rasters.iter() { unsafe { spn!(spn_raster_builder_begin(raster_builder)); } for (path, transform) in paths.iter() { const SPINEL_TRANSFORM_MULTIPLIER: f32 = 32.0; let transform = transform .then_translate(*txty) .then(&display_rotation.transform(&size.to_f32())); let transform = SpnTransform { sx: transform.m11 * SPINEL_TRANSFORM_MULTIPLIER, shx: transform.m21 * SPINEL_TRANSFORM_MULTIPLIER, tx: transform.m31 * SPINEL_TRANSFORM_MULTIPLIER, shy: transform.m12 * SPINEL_TRANSFORM_MULTIPLIER, sy: transform.m22 * SPINEL_TRANSFORM_MULTIPLIER, ty: transform.m32 * SPINEL_TRANSFORM_MULTIPLIER, w0: 0.0, w1: 0.0, }; let clip = SpnClip { x0: std::f32::MIN, y0: std::f32::MIN, x1: std::f32::MAX, y1: std::f32::MAX, }; unsafe { spn!(spn_raster_builder_add( raster_builder, &*path.path, ptr::null_mut(), &transform, ptr::null_mut(), &clip, 1, )); } } let raster = unsafe { init(|ptr| spn!(spn_raster_builder_end(raster_builder, ptr))) }; unsafe { spn!(spn_composition_place(composition, &raster, &(i as u32), ptr::null(), 1)); } previous_rasters.push(raster); } } } pub(crate) fn spn_styling( &self, context: &InnerContext, needs_linear_to_srgb_opcode: bool, ) -> Option<SpnStyling> { const PARENTS: u32 = 0; const ENTER_CMDS: u32 = 1; const GROUP_SIZE: u32 = 6; const MAX_LAYER_CMDS: u32 = 6; let leave_cmds: u32 = if needs_linear_to_srgb_opcode { 5 } else { 4 }; let num_clear_layers = 1; let len = self.layers.len() as u32 + num_clear_layers; let styling_len = len * MAX_LAYER_CMDS + PARENTS + ENTER_CMDS + leave_cmds + GROUP_SIZE; let spn_styling = context.get_checked().map(|context| unsafe { init(|ptr| spn!(spn_styling_create(context, ptr, len, styling_len))) })?; let top_group = unsafe { init(|ptr| spn!(spn_styling_group_alloc(spn_styling, ptr))) }; unsafe { spn!(spn_styling_group_parents(spn_styling, top_group, PARENTS, ptr::null_mut())); if len != 0 { spn!(spn_styling_group_range_lo(spn_styling, top_group, 0)); spn!(spn_styling_group_range_hi(spn_styling, top_group, len - 1)); } } let cmds_enter = unsafe { let data = init(|ptr| spn!(spn_styling_group_enter(spn_styling, top_group, ENTER_CMDS, ptr))); slice::from_raw_parts_mut(data, 1) }; cmds_enter[0] = SpnCommand::SpnStylingOpcodeColorAccZero; let cmds_leave = unsafe { let data = init(|ptr| spn!(spn_styling_group_leave(spn_styling, top_group, leave_cmds, ptr))); slice::from_raw_parts_mut(data, leave_cmds as usize) }; unsafe { spn_styling_background_over_encoder(&mut cmds_leave[0], self.background_color.as_ptr()); } if needs_linear_to_srgb_opcode { cmds_leave[3] = SpnCommand::SpnStylingOpcodeColorAccLinearToSrgb; cmds_leave[4] = SpnCommand::SpnStylingOpcodeColorAccStoreToSurface; } else { cmds_leave[3] = SpnCommand::SpnStylingOpcodeColorAccStoreToSurface; } group_layers(spn_styling, top_group, &self.layers, 0); let clear_cmds = unsafe { let data = init(|ptr| { let len = 5; spn!(spn_styling_group_layer( spn_styling, top_group, self.layers.len() as u32, len, ptr )) }); slice::from_raw_parts_mut(data, len as usize) }; clear_cmds[0] = SpnCommand::SpnStylingOpcodeCoverWipZero; unsafe { spn_styling_layer_fill_rgba_encoder(&mut clear_cmds[1], self.background_color.as_ptr()); } clear_cmds[4] = SpnCommand::SpnStylingOpcodeBlendOver; unsafe { spn!(spn_styling_seal(spn_styling)); } Some(spn_styling) } } impl Composition<Spinel> for SpinelComposition { fn new(background_color: Color) -> Self { Self { layers: vec![], background_color: background_color.to_linear_premult_rgba() } } fn with_layers( layers: impl IntoIterator<Item = Layer<Spinel>>, background_color: Color, ) -> Self { Self { layers: layers.into_iter().collect(), background_color: background_color.to_linear_premult_rgba(), } } fn clear(&mut self) { self.layers.clear(); } fn replace<R, I>(&mut self, range: R, with: I) where R: RangeBounds<usize>, I: IntoIterator<Item = Layer<Spinel>>, { self.layers.splice(range, with); } }
init(|ptr| { spn!(spn_styling_group_layer( spn_styling, top_group, layer_id_start + i as u32, len as u32, ptr )) })
call_expression
[]
Rust
bsync/src/db.rs
losfair/blkredo
1151cd23acfd231ce10fedce4401a00e2339ed93
use std::{ convert::TryInto, path::Path, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use anyhow::Result; use parking_lot::Mutex; use rusqlite::{params, Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use thiserror::Error; use crate::{blob::ZERO_BLOCK_HASH, util::align_block}; macro_rules! migration { ($id:ident, $($version:expr,)*) => { static $id: &'static [(&'static str, &'static str)] = &[ $(($version, include_str!(concat!("./migration/", $version, ".sql"))),)* ]; }; } migration!(VERSIONS, "000001", "000002", "000003",); static SNAPSHOT_ID: AtomicU64 = AtomicU64::new(0); #[derive(Clone)] pub struct Database { db: Arc<Mutex<Connection>>, instance_id: Arc<str>, } #[derive(Clone)] pub struct ConsistentPoint { pub lsn: u64, pub size: u64, pub created_at: u64, } pub enum RedoContentOrHash<'a> { Content(&'a [u8]), Hash([u8; 32]), } impl Database { pub fn open_file(path: &Path, create: bool) -> Result<Self> { #[derive(Error, Debug)] #[error("migration failed: {0}")] struct MigrationError(anyhow::Error); let mut flags: OpenFlags = OpenFlags::SQLITE_OPEN_READ_WRITE; if create { flags |= OpenFlags::SQLITE_OPEN_CREATE; } let mut db = Connection::open_with_flags(path, flags)?; db.execute_batch( r#" pragma journal_mode = wal; "#, )?; db.busy_handler(Some(|i| { log::debug!("Waiting for lock on database (attempt {})", i); std::thread::sleep(Duration::from_millis(100)); true }))?; run_migration(&mut db).map_err(MigrationError)?; let instance_id: String = db .query_row( "select v from bsync_config where k = 'instance_id'", params![], |r| r.get(0), ) .expect("missing instance_id in bsync_config"); log::info!( "Opened database at {:?} with instance id {}.", path, instance_id ); Ok(Self { db: Arc::new(Mutex::new(db)), instance_id: Arc::from(instance_id.as_str()), }) } pub fn instance_id(&self) -> &str { &*self.instance_id } pub fn snapshot(&self, lsn: u64) -> Result<Snapshot> { let id = SNAPSHOT_ID.fetch_add(1, Ordering::Relaxed); let table_name = format!("snapshot_{}", id); let db = self.db.lock(); let start = Instant::now(); db.execute_batch(&format!( r#" create temp table {} ( block_id integer not null primary key, hash blob not null ); insert into temp.{} (block_id, hash) select block_id, hash from redo_v1 where lsn in ( select max(lsn) from redo_v1 where lsn <= {} group by block_id ); "#, table_name, table_name, lsn ))?; log::info!( "Materialized snapshot at LSN {} in {:?}.", lsn, start.elapsed() ); Ok(Snapshot { db: self.clone(), table_name, }) } pub fn write_redo<'a>( &self, base_lsn: u64, data: impl IntoIterator<Item = (u64, RedoContentOrHash<'a>)>, ) -> Result<u64> { #[derive(Error, Debug)] #[error("base lsn mismatch: expecting {0}, got {1}")] struct LsnMismatch(u64, u64); #[derive(Error, Debug)] #[error("block with hash {0} was assumed to exist in CAS but does not exist anymore - did you run `bsync squash` just now? please retry.")] struct MissingHash(String); let mut db = self.db.lock(); let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let max_lsn: Option<u64>; { let mut get_max_lsn_stmt = txn.prepare_cached("select max(lsn) from redo_v1").unwrap(); let mut has_cas_stmt = txn .prepare_cached("select hash from cas_v1 where hash = ?") .unwrap(); let mut insert_cas_compressed_stmt = txn .prepare_cached("insert into cas_v1 (hash, content, compressed) values(?, ?, 1)") .unwrap(); let mut insert_redo_stmt = txn .prepare_cached("insert into redo_v1 (block_id, hash) values(?, ?)") .unwrap(); let prev_max_lsn: Option<u64> = get_max_lsn_stmt.query_row(params![], |r| r.get(0)).unwrap(); let prev_max_lsn = prev_max_lsn.unwrap_or(0); if prev_max_lsn != base_lsn { return Err(LsnMismatch(base_lsn, prev_max_lsn).into()); } for (block_id, body) in data { let hash: [u8; 32] = match body { RedoContentOrHash::Content(x) => blake3::hash(x).into(), RedoContentOrHash::Hash(x) => x, }; let has_cas: Option<Vec<u8>> = has_cas_stmt .query_row(params![&hash[..]], |r| r.get(0)) .optional() .unwrap(); if has_cas.is_none() { match body { RedoContentOrHash::Content(content) => { let content = align_block(content); let content = zstd::encode_all(&*content, 3)?; insert_cas_compressed_stmt .execute(params![&hash[..], &content[..]]) .unwrap(); } RedoContentOrHash::Hash(_) => return Err(MissingHash(hex::encode(&hash)).into()), } } insert_redo_stmt .execute(params![block_id, &hash[..]]) .unwrap(); } max_lsn = get_max_lsn_stmt .query_row(params![], |r| r.get(0)) .optional() .unwrap(); } txn.commit().unwrap(); Ok(max_lsn.unwrap_or(0)) } pub fn max_lsn(&self) -> u64 { let x: Option<u64> = self .db .lock() .prepare_cached("select max(lsn) from redo_v1") .unwrap() .query_row(params![], |r| r.get(0)) .unwrap(); x.unwrap_or(0) } pub fn exists_in_cas(&self, hash: &[u8; 32]) -> bool { let v: Option<u32> = self .db .lock() .query_row( "select 1 from cas_v1 where hash = ?", params![&hash[..]], |r| r.get(0), ) .optional() .unwrap(); v.is_some() } pub fn list_consistent_point(&self) -> Vec<ConsistentPoint> { let db = self.db.lock(); let mut stmt = db .prepare_cached("select lsn, size, created_at from consistent_point_v1 order by lsn asc") .unwrap(); stmt .query_map(params![], |r| { Ok(ConsistentPoint { lsn: r.get(0)?, size: r.get(1)?, created_at: r.get(2)?, }) }) .unwrap() .collect::<Result<_, rusqlite::Error>>() .unwrap() } pub fn add_consistent_point(&self, lsn: u64, size: u64) { let db = self.db.lock(); let now = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); let mut stmt = db .prepare_cached( "insert or ignore into consistent_point_v1 (lsn, size, created_at) values(?, ?, ?)", ) .unwrap(); stmt.execute(params![lsn, size, now]).unwrap(); } pub fn squash(&self, start_lsn: u64, end_lsn: u64) -> Result<()> { let mut db = self.db.lock(); let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; txn.execute_batch(&format!(r#" delete from consistent_point_v1 where lsn > {from} and lsn < {to}; create temp table squash ( `lsn` integer not null primary key ); insert into temp.squash (lsn) select max(lsn) from redo_v1 where lsn > {from} and lsn <= {to} group by block_id; delete from redo_v1 where lsn > {from} and lsn <= {to} and not exists (select * from temp.squash where lsn = redo_v1.lsn); drop table temp.squash; "#, from = start_lsn, to = end_lsn)).unwrap(); txn.commit().unwrap(); Ok(()) } pub fn cas_gc(&self) { let db = self.db.lock(); db.execute_batch( r#" delete from cas_v1 where hash not in (select hash from redo_v1); "#, ) .unwrap(); } pub fn vacuum(&self) { self.db.lock().execute_batch("vacuum;").unwrap(); } } pub struct Snapshot { db: Database, table_name: String, } impl Snapshot { pub fn read_block(&self, block_id: u64) -> Option<Vec<u8>> { let hash = self.read_block_hash(block_id)?; if hash == *ZERO_BLOCK_HASH { return None; } let db = self.db.db.lock(); let mut stmt = db .prepare_cached( r#" select content, compressed from cas_v1 where hash = ? "#, ) .unwrap(); let (content, compressed): (Vec<u8>, bool) = stmt .query_row(params![&hash[..]], |r| Ok((r.get(0)?, r.get(1)?))) .optional() .unwrap()?; if compressed { let content = zstd::decode_all(&content[..]).expect("read_block: decompression failed"); Some(content) } else { Some(content) } } pub fn read_block_hash(&self, block_id: u64) -> Option<[u8; 32]> { let db = self.db.db.lock(); let mut stmt = db .prepare_cached(&format!( "select hash from temp.{} where block_id = ?", self.table_name )) .unwrap(); let hash: Vec<u8> = stmt .query_row(params![block_id], |r| r.get(0)) .optional() .unwrap()?; Some(hash.try_into().unwrap()) } } impl Drop for Snapshot { fn drop(&mut self) { self .db .db .lock() .execute_batch(&format!( r#" drop table temp.{}; "#, &self.table_name )) .unwrap(); } } fn run_migration(db: &mut Connection) -> Result<()> { #[derive(Error, Debug)] #[error("database schema version is newer than the supported version")] struct SchemaTooNew; let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let table_exists: u32 = txn.query_row( "select count(*) from sqlite_master where type='table' and name='bsync_config'", params![], |r| r.get(0), )?; let current_version: Option<String> = if table_exists == 1 { Some(txn.query_row( "select v from bsync_config where k = 'schema_version'", params![], |r| r.get(0), )?) } else { None }; let current_version: u64 = current_version.map(|x| x.parse()).transpose()?.unwrap_or(0); let latest_version: u64 = VERSIONS.last().unwrap().0.parse().unwrap(); if current_version > latest_version { return Err(SchemaTooNew.into()); } for &(version, sql) in VERSIONS { let version: u64 = version.parse().unwrap(); if version > current_version { txn.execute_batch(sql)?; log::info!("Applied migration {}.", version); } } txn.execute( "replace into bsync_config (k, v) values('schema_version', ?)", params![format!("{}", latest_version)], )?; txn.commit()?; Ok(()) }
use std::{ convert::TryInto, path::Path, sync::{ atomic::{AtomicU64, Ordering}, Arc, }, time::{Duration, Instant, SystemTime, UNIX_EPOCH}, }; use anyhow::Result; use parking_lot::Mutex; use rusqlite::{params, Connection, OpenFlags, OptionalExtension, TransactionBehavior}; use thiserror::Error; use crate::{blob::ZERO_BLOCK_HASH, util::align_block}; macro_rules! migration { ($id:ident, $($version:expr,)*) => { static $id: &'static [(&'static str, &'static str)] = &[ $(($version, include_str!(concat!("./migration/", $version, ".sql"))),)* ]; }; } migration!(VERSIONS, "000001", "000002", "000003",); static SNAPSHOT_ID: AtomicU64 = AtomicU64::new(0); #[derive(Clone)] pub struct Database { db: Arc<Mutex<Connection>>, instance_id: Arc<str>, } #[derive(Clone)] pub struct ConsistentPoint { pub lsn: u64, pub size: u64, pub created_at: u64, } pub enum RedoContentOrHash<'a> { Content(&'a [u8]), Hash([u8; 32]), } impl Database { pub fn open_file(path: &Path, create: bool) -> Result<Self> { #[derive(Error, Debug)] #[error("migration failed: {0}")] struct MigrationError(anyhow::Error); let mut flags: OpenFlags = OpenFlags::SQLITE_OPEN_READ_WRITE; if create { flags |= OpenFlags::SQLITE_OPEN_CREATE; } let mut db = Connection::open_with_flags(path, flags)?; db.execute_batch( r#" pragma journal_mode = wal; "#, )?; db.busy_handler(Some(|i| { log::debug!("Waiting for lock on database (attempt {})", i); std::thread::sleep(Duration::from_millis(100)); true }))?; run_migration(&mut db).map_err(MigrationError)?; let instance_id: String = db .query_row( "select v from bsync_config where k = 'instance_id'", params![], |r| r.get(0), ) .expect("missing instance_id in bsync_config"); log::info!( "Opened database at {:?} with instance id {}.", path, instance_id ); Ok(Self { db: Arc::new(Mutex::new(db)), instance_id: Arc::from(instance_id.as_str()), }) } pub fn instance_id(&self) -> &str { &*self.instance_id } pub fn snapshot(&self, lsn: u64) -> Result<Snapshot> { let id = SNAPSHOT_ID.fetch_add(1, Ordering::Relaxed); let table_name = format!("snapshot_{}", id); let db = self.db.lock(); let start = Instant::now(); db.execute_batch(&format!( r#" create temp table {} ( block_id integer not null primary key, hash blob not null ); insert into temp.{} (block_id, hash) select block_id, hash from redo_v1 where lsn in ( select max(lsn) from redo_v1 where lsn <= {} group by block_id ); "#, table_name, table_name, lsn ))?; log::info!( "Materialized snapshot at LSN {} in {:?}.", lsn, start.elapsed() ); Ok(Snapshot { db: self.clone(), table_name, }) } pub fn write_redo<'a>( &self, base_lsn: u64, data: impl IntoIterator<Item = (u64, RedoContentOrHash<'a>)>, ) -> Result<u64> { #[derive(Error, Debug)] #[error("base lsn mismatch: expecting {0}, got {1}")] struct LsnMismatch(u64, u64); #[derive(Error, Debug)] #[error("block with hash {0} was assumed to exist in CAS but does not exist anymore - did you run `bsync squash` just now? please retry.")] struct MissingHash(String); let mut db = self.db.lock(); let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let max_lsn: Option<u64>; { let mut get_max_lsn_stmt = txn.prepare_cached("select max(lsn) from redo_v1").unwrap(); let mut has_cas_stmt = txn .prepare_cached("select hash from cas_v1 where hash = ?") .unwrap(); let mut insert_cas_compressed_stmt = txn .prepare_cached("insert into cas_v1 (hash, content, compressed) values(?, ?, 1)") .unwrap(); let mut insert_redo_stmt = txn .prepare_cache
lsn > {from} and lsn <= {to} and not exists (select * from temp.squash where lsn = redo_v1.lsn); drop table temp.squash; "#, from = start_lsn, to = end_lsn)).unwrap(); txn.commit().unwrap(); Ok(()) } pub fn cas_gc(&self) { let db = self.db.lock(); db.execute_batch( r#" delete from cas_v1 where hash not in (select hash from redo_v1); "#, ) .unwrap(); } pub fn vacuum(&self) { self.db.lock().execute_batch("vacuum;").unwrap(); } } pub struct Snapshot { db: Database, table_name: String, } impl Snapshot { pub fn read_block(&self, block_id: u64) -> Option<Vec<u8>> { let hash = self.read_block_hash(block_id)?; if hash == *ZERO_BLOCK_HASH { return None; } let db = self.db.db.lock(); let mut stmt = db .prepare_cached( r#" select content, compressed from cas_v1 where hash = ? "#, ) .unwrap(); let (content, compressed): (Vec<u8>, bool) = stmt .query_row(params![&hash[..]], |r| Ok((r.get(0)?, r.get(1)?))) .optional() .unwrap()?; if compressed { let content = zstd::decode_all(&content[..]).expect("read_block: decompression failed"); Some(content) } else { Some(content) } } pub fn read_block_hash(&self, block_id: u64) -> Option<[u8; 32]> { let db = self.db.db.lock(); let mut stmt = db .prepare_cached(&format!( "select hash from temp.{} where block_id = ?", self.table_name )) .unwrap(); let hash: Vec<u8> = stmt .query_row(params![block_id], |r| r.get(0)) .optional() .unwrap()?; Some(hash.try_into().unwrap()) } } impl Drop for Snapshot { fn drop(&mut self) { self .db .db .lock() .execute_batch(&format!( r#" drop table temp.{}; "#, &self.table_name )) .unwrap(); } } fn run_migration(db: &mut Connection) -> Result<()> { #[derive(Error, Debug)] #[error("database schema version is newer than the supported version")] struct SchemaTooNew; let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let table_exists: u32 = txn.query_row( "select count(*) from sqlite_master where type='table' and name='bsync_config'", params![], |r| r.get(0), )?; let current_version: Option<String> = if table_exists == 1 { Some(txn.query_row( "select v from bsync_config where k = 'schema_version'", params![], |r| r.get(0), )?) } else { None }; let current_version: u64 = current_version.map(|x| x.parse()).transpose()?.unwrap_or(0); let latest_version: u64 = VERSIONS.last().unwrap().0.parse().unwrap(); if current_version > latest_version { return Err(SchemaTooNew.into()); } for &(version, sql) in VERSIONS { let version: u64 = version.parse().unwrap(); if version > current_version { txn.execute_batch(sql)?; log::info!("Applied migration {}.", version); } } txn.execute( "replace into bsync_config (k, v) values('schema_version', ?)", params![format!("{}", latest_version)], )?; txn.commit()?; Ok(()) }
d("insert into redo_v1 (block_id, hash) values(?, ?)") .unwrap(); let prev_max_lsn: Option<u64> = get_max_lsn_stmt.query_row(params![], |r| r.get(0)).unwrap(); let prev_max_lsn = prev_max_lsn.unwrap_or(0); if prev_max_lsn != base_lsn { return Err(LsnMismatch(base_lsn, prev_max_lsn).into()); } for (block_id, body) in data { let hash: [u8; 32] = match body { RedoContentOrHash::Content(x) => blake3::hash(x).into(), RedoContentOrHash::Hash(x) => x, }; let has_cas: Option<Vec<u8>> = has_cas_stmt .query_row(params![&hash[..]], |r| r.get(0)) .optional() .unwrap(); if has_cas.is_none() { match body { RedoContentOrHash::Content(content) => { let content = align_block(content); let content = zstd::encode_all(&*content, 3)?; insert_cas_compressed_stmt .execute(params![&hash[..], &content[..]]) .unwrap(); } RedoContentOrHash::Hash(_) => return Err(MissingHash(hex::encode(&hash)).into()), } } insert_redo_stmt .execute(params![block_id, &hash[..]]) .unwrap(); } max_lsn = get_max_lsn_stmt .query_row(params![], |r| r.get(0)) .optional() .unwrap(); } txn.commit().unwrap(); Ok(max_lsn.unwrap_or(0)) } pub fn max_lsn(&self) -> u64 { let x: Option<u64> = self .db .lock() .prepare_cached("select max(lsn) from redo_v1") .unwrap() .query_row(params![], |r| r.get(0)) .unwrap(); x.unwrap_or(0) } pub fn exists_in_cas(&self, hash: &[u8; 32]) -> bool { let v: Option<u32> = self .db .lock() .query_row( "select 1 from cas_v1 where hash = ?", params![&hash[..]], |r| r.get(0), ) .optional() .unwrap(); v.is_some() } pub fn list_consistent_point(&self) -> Vec<ConsistentPoint> { let db = self.db.lock(); let mut stmt = db .prepare_cached("select lsn, size, created_at from consistent_point_v1 order by lsn asc") .unwrap(); stmt .query_map(params![], |r| { Ok(ConsistentPoint { lsn: r.get(0)?, size: r.get(1)?, created_at: r.get(2)?, }) }) .unwrap() .collect::<Result<_, rusqlite::Error>>() .unwrap() } pub fn add_consistent_point(&self, lsn: u64, size: u64) { let db = self.db.lock(); let now = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); let mut stmt = db .prepare_cached( "insert or ignore into consistent_point_v1 (lsn, size, created_at) values(?, ?, ?)", ) .unwrap(); stmt.execute(params![lsn, size, now]).unwrap(); } pub fn squash(&self, start_lsn: u64, end_lsn: u64) -> Result<()> { let mut db = self.db.lock(); let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?; txn.execute_batch(&format!(r#" delete from consistent_point_v1 where lsn > {from} and lsn < {to}; create temp table squash ( `lsn` integer not null primary key ); insert into temp.squash (lsn) select max(lsn) from redo_v1 where lsn > {from} and lsn <= {to} group by block_id; delete from redo_v1 where
random
[ { "content": "pub fn sha256hash(data: &[u8]) -> [u8; 32] {\n\n let mut h = Sha256::new();\n\n h.update(data);\n\n h.finalize().into()\n\n}\n", "file_path": "bsync/src/util.rs", "rank": 1, "score": 161150.78567438372 }, { "content": "pub fn align_block(data: &[u8]) -> Cow<[u8]> {\n\n let block_size = LOG_BLOCK_SIZE as usize;\n\n assert!(data.len() <= block_size);\n\n if data.len() < block_size {\n\n log::debug!(\n\n \"align_block: padding data of length {} to {}\",\n\n data.len(),\n\n block_size\n\n );\n\n let mut v = Vec::with_capacity(block_size);\n\n v.extend_from_slice(data);\n\n v.extend(std::iter::repeat(0u8).take(block_size - data.len()));\n\n Cow::Owned(v)\n\n } else {\n\n Cow::Borrowed(data)\n\n }\n\n}\n\n\n", "file_path": "bsync/src/util.rs", "rank": 2, "score": 141328.77137909445 }, { "content": "alter table `cas_v1` add column compressed integer not null default 0;\n", "file_path": "bsync/src/migration/000003.sql", "rank": 3, "score": 137669.0833274132 }, { "content": "fn write_snapshot(db: &Database, cp: &ConsistentPoint, path: &Path) -> Result<()> {\n\n let snapshot = db.snapshot(cp.lsn)?;\n\n let mut output = OpenOptions::new()\n\n .create(true)\n\n .write(true)\n\n .truncate(true)\n\n .open(path)?;\n\n let output_md = output.metadata()?;\n\n let blkdev = output_md.file_type().is_block_device();\n\n let mut last_is_seek = false;\n\n for offset in (0usize..cp.size as usize).step_by(LOG_BLOCK_SIZE) {\n\n let write_len = (offset + LOG_BLOCK_SIZE)\n\n .min(cp.size as usize)\n\n .checked_sub(offset)\n\n .unwrap();\n\n assert!(write_len > 0);\n\n if let Some(block) = snapshot.read_block(offset as u64 / LOG_BLOCK_SIZE as u64) {\n\n assert_eq!(block.len(), LOG_BLOCK_SIZE);\n\n output.write_all(&block[..write_len])?;\n\n last_is_seek = false;\n", "file_path": "bsync/src/cmd_replay.rs", "rank": 4, "score": 124303.74611440033 }, { "content": "create table `bsync_config` (\n\n `k` text not null primary key,\n\n `v` text not null\n\n);\n", "file_path": "bsync/src/migration/000001.sql", "rank": 5, "score": 113176.92031790887 }, { "content": "fn exec_oneshot_in(channel: &mut Channel, cmd: &str) -> Result<String> {\n\n exec_oneshot_bin_in(channel, cmd, |_| (), |x| Box::new(x))\n\n .and_then(|x| String::from_utf8(x).map_err(anyhow::Error::from))\n\n}\n\n\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 6, "score": 113149.12346174892 }, { "content": "fn exec_oneshot(sess: &mut Session, cmd: &str) -> Result<String> {\n\n let mut channel = sess.channel_session()?;\n\n exec_oneshot_in(&mut channel, cmd)\n\n}\n\n\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 7, "score": 113149.12346174892 }, { "content": "create table `redo_v1` (\n\n `lsn` integer not null primary key autoincrement,\n\n `block_id` integer not null,\n\n `hash` blob not null\n\n);\n\n\n", "file_path": "bsync/src/migration/000001.sql", "rank": 8, "score": 110837.40885017422 }, { "content": "-- Content-addressable storage for blocks. Keyed by the BLAKE3 hash\n\n-- of `content`.\n\ncreate table `cas_v1` (\n\n `hash` blob not null primary key,\n\n `content` blob not null\n\n);\n\n\n", "file_path": "bsync/src/migration/000001.sql", "rank": 9, "score": 110579.37495244328 }, { "content": "create table `consistent_point_v1` (\n\n `lsn` integer not null primary key,\n\n `size` integer not null,\n\n `created_at` integer not null\n\n);\n\n\n", "file_path": "bsync/src/migration/000001.sql", "rank": 10, "score": 88812.92146450302 }, { "content": "enum FetchOrAssumeExist {\n\n Fetch(usize),\n\n AssumeExistWithHash(usize, [u8; 32]),\n\n}\n\n\n\nimpl Pullcmd {\n\n pub fn run(&self) -> Result<()> {\n\n #[derive(Error, Debug)]\n\n #[error(\"received invalid hash from remote: {0}\")]\n\n struct InvalidRemoteHash(String);\n\n #[derive(Error, Debug)]\n\n #[error(\"expecting {0} bytes from remote, got {1}\")]\n\n struct ByteCountMismatch(usize, usize);\n\n #[derive(Error, Debug)]\n\n #[error(\"total size mismatch - expecting {0}, got {1}\")]\n\n struct TotalSizeMismatch(u64, u64);\n\n #[derive(Error, Debug)]\n\n #[error(\"remote architecture not supported: {0}\")]\n\n struct ArchNotSupported(String);\n\n #[derive(Error, Debug)]\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 11, "score": 87949.44850026604 }, { "content": "fn do_listen(addr: &str) -> Result<GenericListener, std::io::Error> {\n\n if let Some(path) = addr.strip_prefix(\"unix:\") {\n\n let _ = std::fs::remove_file(&path);\n\n Ok(GenericListener::Unix(UnixListener::bind(path)?))\n\n } else {\n\n Ok(GenericListener::Tcp(TcpListener::bind(addr)?))\n\n }\n\n}\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 12, "score": 86215.86552928368 }, { "content": "fn exec_oneshot_bin_in<D: for<'a> FnMut(&'a mut dyn Read) -> Box<dyn Read + 'a>>(\n\n channel: &mut Channel,\n\n cmd: &str,\n\n mut progress: impl FnMut(usize),\n\n mut decoder_gen: D,\n\n) -> Result<Vec<u8>> {\n\n #[derive(Debug, Error)]\n\n #[error(\"remote returned error {0}\")]\n\n struct RemoteError(i32);\n\n\n\n channel.exec(cmd)?;\n\n let mut data = Vec::new();\n\n {\n\n let mut reader = decoder_gen(&mut *channel);\n\n let mut reader = BufReader::new(&mut *reader);\n\n loop {\n\n let buf = reader.fill_buf()?;\n\n if buf.len() == 0 {\n\n break;\n\n }\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 13, "score": 64368.785398139255 }, { "content": "fn exec_oneshot_bin<D: for<'a> FnMut(&'a mut dyn Read) -> Box<dyn Read + 'a>>(\n\n sess: &mut Session,\n\n cmd: &str,\n\n progress: impl FnMut(usize),\n\n decoder_gen: D,\n\n) -> Result<Vec<u8>> {\n\n let mut channel = sess.channel_session()?;\n\n exec_oneshot_bin_in(&mut channel, cmd, progress, decoder_gen)\n\n}\n\n\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 14, "score": 64368.785398139255 }, { "content": "insert into `bsync_config` (k, v) values(\n\n \"instance_id\",\n\n hex(randomblob(16))\n\n);\n", "file_path": "bsync/src/migration/000002.sql", "rank": 15, "score": 57804.79469739328 }, { "content": "-- Content-addressable storage for blocks. Keyed by the BLAKE3 hash\n\n-- of `content`.\n", "file_path": "bsync/src/migration/000001.sql", "rank": 16, "score": 57799.53497132063 }, { "content": "#[derive(Debug, StructOpt)]\n\nenum Subcmd {\n\n Pull(Pullcmd),\n\n Replay(Replaycmd),\n\n List(Listcmd),\n\n Squash(SquashCmd),\n\n Serve(Servecmd),\n\n}\n\n\n", "file_path": "bsync/src/main.rs", "rank": 17, "score": 50420.069998112376 }, { "content": "#[derive(Debug, StructOpt)]\n\nstruct Opt {\n\n #[structopt(subcommand)]\n\n subcommand: Subcmd,\n\n}\n\n\n", "file_path": "bsync/src/main.rs", "rank": 18, "score": 50420.069998112376 }, { "content": "struct Service {\n\n snapshot: Arc<Snapshot>,\n\n cursor: u64,\n\n cache: LruCache<usize, Vec<u8>>,\n\n}\n\n\n\nimpl Service {\n\n fn read_block<'a>(&'a mut self, index: usize) -> &'a [u8] {\n\n let cache = &mut self.cache;\n\n\n\n // XXX: Matching with `Some(x)` gives lifetime errors\n\n if cache.peek(&index).is_some() {\n\n return cache.get(&index).unwrap();\n\n } else if let Some(x) = self.snapshot.read_block(index as u64) {\n\n cache.put(index, x);\n\n cache.peek(&index).unwrap()\n\n } else {\n\n &ZERO_BLOCK[..]\n\n }\n\n }\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 19, "score": 48871.52932176185 }, { "content": "#[derive(Serialize)]\n\nstruct OutputEntry {\n\n lsn: u64,\n\n created_at: u64,\n\n size: u64,\n\n}\n\n\n\nimpl Listcmd {\n\n pub fn run(&self) -> Result<()> {\n\n let db = Database::open_file(&self.db, false)?;\n\n let cp_list = db.list_consistent_point();\n\n\n\n if self.json {\n\n let out: Vec<OutputEntry> = cp_list\n\n .iter()\n\n .map(|x| OutputEntry {\n\n lsn: x.lsn,\n\n created_at: x.created_at,\n\n size: x.size,\n\n })\n\n .collect();\n", "file_path": "bsync/src/cmd_list.rs", "rank": 20, "score": 47473.596578532306 }, { "content": "enum GenericListener {\n\n Tcp(TcpListener),\n\n Unix(UnixListener),\n\n}\n\n\n\nimpl GenericListener {\n\n fn incoming<'a>(\n\n &'a self,\n\n ) -> Box<dyn Iterator<Item = Result<Box<dyn ReadAndWrite>, std::io::Error>> + 'a> {\n\n match self {\n\n Self::Tcp(lis) => Box::new(\n\n lis\n\n .incoming()\n\n .map(|x| x.map(|x| Box::new(x) as Box<dyn ReadAndWrite>)),\n\n ),\n\n Self::Unix(lis) => Box::new(\n\n lis\n\n .incoming()\n\n .map(|x| x.map(|x| Box::new(x) as Box<dyn ReadAndWrite>)),\n\n ),\n\n }\n\n }\n\n}\n\n\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 21, "score": 47473.596578532306 }, { "content": "fn main() {\n\n let mut args = std::env::args();\n\n args.next().unwrap();\n\n\n\n let path = args.next().expect(\"expecting path\");\n\n let chunk_size: usize = args.next().expect(\"expecting chunk size\").parse().unwrap();\n\n let op = args.next().expect(\"expecting op\");\n\n\n\n assert!(chunk_size > 0);\n\n let mut f = File::open(&path).unwrap();\n\n let stdout = stdout();\n\n let mut stdout = BufWriter::new(stdout.lock());\n\n let mut buf = vec![0u8; chunk_size];\n\n\n\n ioprio::set_priority(\n\n ioprio::Target::Process(ioprio::Pid::from_raw(0)),\n\n ioprio::Priority::new(ioprio::Class::BestEffort(ioprio::BePriorityLevel::lowest())),\n\n )\n\n .unwrap();\n\n\n", "file_path": "bsync-transmit/src/main.rs", "rank": 22, "score": 45605.0463078387 }, { "content": "fn main() -> Result<()> {\n\n pretty_env_logger::init_timed();\n\n let opt = Opt::from_args();\n\n match &opt.subcommand {\n\n Subcmd::Pull(cmd) => {\n\n cmd.run()?;\n\n }\n\n Subcmd::Replay(cmd) => {\n\n cmd.run()?;\n\n }\n\n Subcmd::List(cmd) => {\n\n cmd.run()?;\n\n }\n\n Subcmd::Squash(cmd) => {\n\n cmd.run()?;\n\n }\n\n Subcmd::Serve(cmd) => {\n\n cmd.run()?;\n\n }\n\n }\n\n Ok(())\n\n}\n", "file_path": "bsync/src/main.rs", "rank": 23, "score": 44127.366816400376 }, { "content": "use lazy_static::lazy_static;\n\nuse phf::phf_map;\n\n\n\nuse crate::config::LOG_BLOCK_SIZE;\n\n\n\nstatic X86_64_BLKXMIT: &'static [u8] =\n\n include_bytes!(\"../bsync-transmit-dist/bsync-transmit.x86_64-unknown-linux-musl\");\n\n\n\npub static ARCH_BLKXMIT: phf::Map<&'static str, &'static [u8]> = phf_map! {\n\n \"x86_64\" => X86_64_BLKXMIT,\n\n \"amd64\" => X86_64_BLKXMIT, // FreeBSD `uname -m` outputs `amd64` instead of `x86_64`\n\n \"aarch64\" => include_bytes!(\"../bsync-transmit-dist/bsync-transmit.aarch64-unknown-linux-musl\"),\n\n};\n\n\n\npub static ZERO_BLOCK: [u8; LOG_BLOCK_SIZE] = [0; LOG_BLOCK_SIZE];\n\n\n\nlazy_static! {\n\n pub static ref ZERO_BLOCK_HASH: [u8; 32] = blake3::hash(&ZERO_BLOCK).into();\n\n}\n", "file_path": "bsync/src/blob.rs", "rank": 24, "score": 33210.59440609871 }, { "content": "use std::path::PathBuf;\n\n\n\nuse anyhow::Result;\n\nuse structopt::StructOpt;\n\nuse thiserror::Error;\n\n\n\nuse crate::db::Database;\n\n\n\n/// Squash logs.\n\n#[derive(Debug, StructOpt)]\n\npub struct SquashCmd {\n\n /// Start LSN.\n\n #[structopt(long)]\n\n start_lsn: u64,\n\n\n\n /// End LSN.\n\n #[structopt(long)]\n\n end_lsn: u64,\n\n\n\n /// Data loss confirmation.\n", "file_path": "bsync/src/cmd_squash.rs", "rank": 44, "score": 31317.228141274787 }, { "content": " #[structopt(long)]\n\n data_loss: bool,\n\n\n\n /// Vacuum the database after squash.\n\n #[structopt(long)]\n\n vacuum: bool,\n\n\n\n /// Path to the database.\n\n #[structopt(long)]\n\n db: PathBuf,\n\n}\n\n\n\nimpl SquashCmd {\n\n pub fn run(&self) -> Result<()> {\n\n #[derive(Error, Debug)]\n\n enum E {\n\n #[error(\"the provided `start_lsn` is not a consistent point\")]\n\n InconsistentStart,\n\n\n\n #[error(\"the provided `end_lsn` is not a consistent point\")]\n", "file_path": "bsync/src/cmd_squash.rs", "rank": 45, "score": 31313.361165545375 }, { "content": " InconsistentEnd,\n\n\n\n #[error(\"squash removes history - please confirm by adding the flag `--data-loss`.\")]\n\n DataLoss,\n\n }\n\n\n\n let db = Database::open_file(&self.db, false)?;\n\n let cp_list = db.list_consistent_point();\n\n if self.start_lsn != 0 {\n\n match cp_list.iter().find(|x| x.lsn == self.start_lsn) {\n\n Some(_) => {}\n\n None => return Err(E::InconsistentStart.into()),\n\n }\n\n }\n\n match cp_list.iter().find(|x| x.lsn == self.end_lsn) {\n\n Some(_) => {}\n\n None => return Err(E::InconsistentEnd.into()),\n\n };\n\n\n\n if !self.data_loss {\n", "file_path": "bsync/src/cmd_squash.rs", "rank": 46, "score": 31306.08083357284 }, { "content": " return Err(E::DataLoss.into());\n\n }\n\n\n\n db.squash(self.start_lsn, self.end_lsn)?;\n\n db.cas_gc();\n\n if self.vacuum {\n\n db.vacuum();\n\n }\n\n println!(\"Success.\");\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "bsync/src/cmd_squash.rs", "rank": 47, "score": 31303.609002429952 }, { "content": " pub db: String,\n\n\n\n /// Local pull lock path.\n\n pub pull_lock: Option<String>,\n\n}\n\n\n\nimpl BackupConfig {\n\n pub fn must_load_from_file(path: &Path) -> Self {\n\n let text = std::fs::read_to_string(&path).unwrap_or_else(|e| {\n\n log::error!(\n\n \"cannot open backup config at {}: {}\",\n\n path.to_string_lossy(),\n\n e\n\n );\n\n std::process::exit(1);\n\n });\n\n serde_yaml::from_str(&text).unwrap_or_else(|e| {\n\n log::error!(\n\n \"cannot parse backup config at {}: {}\",\n\n path.to_string_lossy(),\n\n e\n\n );\n\n std::process::exit(1);\n\n })\n\n }\n\n}\n", "file_path": "bsync/src/config.rs", "rank": 48, "score": 7784.548309354676 }, { "content": " pub user: String,\n\n\n\n /// Path to SSH private key. Agent auth is used if this is empty.\n\n pub key: Option<String>,\n\n\n\n /// Remote image path.\n\n pub image: String,\n\n\n\n /// Host verification method.\n\n #[serde(default)]\n\n pub verify: HostVerification,\n\n\n\n /// Scripts.\n\n pub scripts: Option<BackupRemoteScripts>,\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub struct BackupRemoteScripts {\n\n pub no_pull_lock: Option<bool>,\n\n pub pre_pull: Option<String>,\n", "file_path": "bsync/src/config.rs", "rank": 49, "score": 7777.118188152456 }, { "content": "mod blob;\n\nmod cmd_list;\n\nmod cmd_pull;\n\nmod cmd_replay;\n\nmod cmd_serve;\n\nmod cmd_squash;\n\nmod config;\n\nmod db;\n\nmod util;\n\n\n\nuse anyhow::Result;\n\nuse cmd_list::Listcmd;\n\nuse cmd_pull::Pullcmd;\n\nuse cmd_replay::Replaycmd;\n\nuse cmd_serve::Servecmd;\n\nuse cmd_squash::SquashCmd;\n\nuse structopt::StructOpt;\n\n\n\n#[derive(Debug, StructOpt)]\n", "file_path": "bsync/src/main.rs", "rank": 50, "score": 7774.278863125915 }, { "content": "use serde::Deserialize;\n\nuse std::path::Path;\n\n\n\npub const LOG_BLOCK_SIZE: usize = 262144;\n\n\n\n#[derive(Deserialize)]\n\npub struct BackupConfig {\n\n pub remote: BackupRemoteConfig,\n\n pub local: BackupLocalConfig,\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub struct BackupRemoteConfig {\n\n /// Remote address.\n\n pub server: String,\n\n\n\n /// SSH port number. Defaults to 22.\n\n pub port: Option<u16>,\n\n\n\n /// SSH username.\n", "file_path": "bsync/src/config.rs", "rank": 51, "score": 7774.267658079173 }, { "content": " pub post_pull: Option<String>,\n\n}\n\n\n\n#[derive(Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub enum HostVerification {\n\n Insecure,\n\n Known,\n\n Dnssec,\n\n}\n\n\n\nimpl Default for HostVerification {\n\n fn default() -> Self {\n\n Self::Known\n\n }\n\n}\n\n\n\n#[derive(Deserialize)]\n\npub struct BackupLocalConfig {\n\n /// Local database path.\n", "file_path": "bsync/src/config.rs", "rank": 52, "score": 7772.797192183867 }, { "content": "use std::borrow::Cow;\n\n\n\nuse sha2::{Digest, Sha256};\n\n\n\nuse crate::config::LOG_BLOCK_SIZE;\n\n\n", "file_path": "bsync/src/util.rs", "rank": 53, "score": 7769.696204453591 }, { "content": " db::{Database, Snapshot},\n\n};\n\n\n\n/// Start a read-only NBD server for the version at the given LSN.\n\n#[derive(Debug, StructOpt)]\n\npub struct Servecmd {\n\n /// The LSN to use.\n\n #[structopt(long)]\n\n lsn: u64,\n\n\n\n /// Path to the database.\n\n #[structopt(long)]\n\n db: PathBuf,\n\n\n\n /// Listen address. Examples: `127.0.0.1:2929`, `unix:/tmp/bsync.sock`\n\n #[structopt(short, long)]\n\n listen: String,\n\n}\n\n\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 54, "score": 7384.968434090858 }, { "content": " lsn = db.write_redo(\n\n lsn,\n\n chunk\n\n .iter()\n\n .copied()\n\n .map(|x| match x {\n\n FetchOrAssumeExist::Fetch(x) => (\n\n *x,\n\n RedoContentOrHash::Content(output_chunks.next().unwrap()),\n\n ),\n\n FetchOrAssumeExist::AssumeExistWithHash(x, h) => (*x, RedoContentOrHash::Hash(*h)),\n\n })\n\n .map(|(offset, data)| ((offset / LOG_BLOCK_SIZE) as u64, data)),\n\n )?;\n\n log::info!(\n\n \"Written {} redo log entries, of which {} are fetched. Total download size is {} bytes. Last LSN is {}.\",\n\n chunk.len(),\n\n fetch_chunk.len(),\n\n output.len(),\n\n lsn,\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 55, "score": 7381.467555023009 }, { "content": "\n\nuse crate::{\n\n blob::{ARCH_BLKXMIT, ZERO_BLOCK_HASH},\n\n config::{BackupConfig, HostVerification, LOG_BLOCK_SIZE},\n\n db::{Database, RedoContentOrHash},\n\n util::sha256hash,\n\n};\n\n\n\nconst DIFF_BATCH_SIZE: usize = 16384;\n\nconst DATA_FETCH_BATCH_SIZE: usize = 256; // 16MiB batches\n\n\n\n/// Incrementally pull updates from a remote image.\n\n#[derive(Debug, StructOpt)]\n\npub struct Pullcmd {\n\n /// Path to the config.\n\n #[structopt(short, long)]\n\n config: PathBuf,\n\n}\n\n\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 56, "score": 7379.146184312573 }, { "content": " /// Path to the output file.\n\n #[structopt(short, long)]\n\n output: PathBuf,\n\n\n\n /// The LSN to use.\n\n #[structopt(long)]\n\n lsn: u64,\n\n\n\n /// Path to the database.\n\n #[structopt(long)]\n\n db: PathBuf,\n\n}\n\n\n\nimpl Replaycmd {\n\n pub fn run(&self) -> Result<()> {\n\n #[derive(Error, Debug)]\n\n enum E {\n\n #[error(\"the provided LSN is not a consistent point\")]\n\n Inconsistent,\n\n }\n", "file_path": "bsync/src/cmd_replay.rs", "rank": 57, "score": 7378.394441903056 }, { "content": "\n\nimpl Servecmd {\n\n pub fn run(&self) -> Result<()> {\n\n #[derive(Error, Debug)]\n\n enum E {\n\n #[error(\"the provided LSN is not a consistent point\")]\n\n Inconsistent,\n\n }\n\n\n\n let db = Database::open_file(&self.db, false)?;\n\n let cp_list = db.list_consistent_point();\n\n let cp = match cp_list.iter().find(|x| x.lsn == self.lsn) {\n\n Some(x) => x,\n\n None => return Err(E::Inconsistent.into()),\n\n };\n\n let snapshot = Arc::new(db.snapshot(cp.lsn)?);\n\n\n\n let listener = do_listen(&self.listen)?;\n\n for conn in listener.incoming() {\n\n let mut conn = conn?;\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 58, "score": 7378.302757418593 }, { "content": "use serde::Serialize;\n\nuse std::path::PathBuf;\n\n\n\nuse anyhow::Result;\n\nuse chrono::NaiveDateTime;\n\nuse prettytable::{cell, row, Table};\n\nuse structopt::StructOpt;\n\n\n\nuse crate::db::Database;\n\n\n\n/// List all consistent points.\n\n#[derive(Debug, StructOpt)]\n\npub struct Listcmd {\n\n /// Path to the database.\n\n #[structopt(long)]\n\n db: PathBuf,\n\n\n\n /// Print in json.\n\n #[structopt(long)]\n\n json: bool,\n\n}\n\n\n\n#[derive(Serialize)]\n", "file_path": "bsync/src/cmd_list.rs", "rank": 59, "score": 7378.2300899255315 }, { "content": "use std::{\n\n fs::OpenOptions,\n\n io::{Seek, SeekFrom, Write},\n\n os::unix::prelude::FileTypeExt,\n\n path::{Path, PathBuf},\n\n};\n\n\n\nuse anyhow::Result;\n\nuse structopt::StructOpt;\n\nuse thiserror::Error;\n\n\n\nuse crate::{\n\n blob::ZERO_BLOCK,\n\n config::LOG_BLOCK_SIZE,\n\n db::{ConsistentPoint, Database},\n\n};\n\n\n\n/// Replay logs and build an image of the block device at a given point in time.\n\n#[derive(Debug, StructOpt)]\n\npub struct Replaycmd {\n", "file_path": "bsync/src/cmd_replay.rs", "rank": 60, "score": 7378.073675981805 }, { "content": " .ok_or_else(|| ArchNotSupported(remote_arch.to_string()))?;\n\n let transmit_sha256 = hex::encode(sha256hash(transmit_image));\n\n let transmit_filename = format!(\"transmit.{}.{}\", db.instance_id(), transmit_sha256);\n\n\n\n let maybe_upload_path: String = exec_oneshot(\n\n &mut sess,\n\n &format!(\n\n r#\"\n\nif [ -f ~/.bsync/{filename} ]; then\n\n echo {hash} ~/.bsync/{filename} | sha256sum -c - > /dev/null\n\n if [ $? -eq 0 ]; then\n\n exit 0\n\n fi\n\nfi\n\nmkdir -p ~/.bsync\n\necho -n \"$HOME/.bsync\"\n\n\"#,\n\n filename = escape(Cow::Borrowed(transmit_filename.as_str())),\n\n hash = escape(Cow::Borrowed(transmit_sha256.as_str()))\n\n ),\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 61, "score": 7377.629343130107 }, { "content": " )?\n\n .trim()\n\n .parse()?;\n\n log::info!(\"Remote image size is {} bytes.\", remote_image_size);\n\n\n\n let mut lsn = db.max_lsn();\n\n let snapshot = db.snapshot(lsn)?;\n\n log::info!(\"Starting from LSN {}.\", lsn);\n\n\n\n let mut fetch_list: Vec<FetchOrAssumeExist> = vec![];\n\n\n\n let gen_pb_style = |name: &str| {\n\n ProgressStyle::default_bar().template(\n\n &format!(\"{{spinner:.green}} {} [{{elapsed_precise}}] [{{wide_bar:.cyan/blue}}] {{bytes}}/{{total_bytes}}\", name),\n\n )\n\n .progress_chars(\"#>-\")\n\n };\n\n\n\n let bar = ProgressBar::new(remote_image_size);\n\n bar.set_style(gen_pb_style(\"Diff\"));\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 62, "score": 7376.139754261803 }, { "content": " #[error(\"remote os not supported: {0}\")]\n\n struct OsNotSupported(String);\n\n\n\n #[derive(Error, Debug)]\n\n #[error(\"`remote.scripts` requested but `local.pull_lock` is not set. If this is really the intended config, set `remote.scripts.no_pull_lock` to `true`.\")]\n\n struct PullLockRequired;\n\n\n\n #[derive(Error, Debug)]\n\n #[error(\"cannot acquire pull lock on {0}: {1}\")]\n\n struct LockAcquire(String, std::io::Error);\n\n\n\n #[derive(Error, Debug)]\n\n #[error(\"no host key\")]\n\n struct NoHostKey;\n\n\n\n #[derive(Error, Debug)]\n\n #[error(\"host key verification error: {0}\")]\n\n struct HostKeyVerifyError(&'static str);\n\n\n\n let config = BackupConfig::must_load_from_file(&self.config);\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 63, "score": 7375.613103617784 }, { "content": "use std::{\n\n io::{Read, Seek, SeekFrom, Write},\n\n net::TcpListener,\n\n os::unix::net::UnixListener,\n\n path::PathBuf,\n\n sync::Arc,\n\n};\n\n\n\nuse anyhow::Result;\n\nuse lru::LruCache;\n\nuse nbd::{\n\n server::{handshake, transmission},\n\n Export,\n\n};\n\nuse structopt::StructOpt;\n\nuse thiserror::Error;\n\n\n\nuse crate::{\n\n blob::ZERO_BLOCK,\n\n config::LOG_BLOCK_SIZE,\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 64, "score": 7375.430301612604 }, { "content": " log::debug!(\"block at offset {} changed\", offset);\n\n let rh = <[u8; 32]>::try_from(rh)?;\n\n if seen_hashes.contains(&rh) || db.exists_in_cas(&rh) {\n\n fetch_list.push(FetchOrAssumeExist::AssumeExistWithHash(offset, rh));\n\n } else {\n\n fetch_list.push(FetchOrAssumeExist::Fetch(offset));\n\n }\n\n seen_hashes.insert(rh);\n\n }\n\n }\n\n }\n\n bar.finish();\n\n drop(bar);\n\n\n\n log::info!(\"{} blocks changed. Fetching changes.\", fetch_list.len());\n\n let bar = ProgressBar::new(\n\n fetch_list\n\n .iter()\n\n .filter(|x| matches!(x, FetchOrAssumeExist::Fetch(_)))\n\n .count() as u64\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 65, "score": 7374.795620323285 }, { "content": "use std::{\n\n borrow::Cow,\n\n collections::HashSet,\n\n convert::TryFrom,\n\n fs::OpenOptions,\n\n io::{BufRead, BufReader, Read, Write},\n\n net::{IpAddr, SocketAddr, TcpStream},\n\n path::{Path, PathBuf},\n\n str::FromStr,\n\n};\n\n\n\nuse anyhow::Result;\n\nuse fs2::FileExt;\n\nuse indicatif::{ProgressBar, ProgressStyle};\n\nuse itertools::Itertools;\n\nuse shell_escape::unix::escape;\n\nuse size_format::SizeFormatterBinary;\n\nuse ssh2::{Channel, CheckResult, KnownHostFileKind, Session};\n\nuse structopt::StructOpt;\n\nuse thiserror::Error;\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 66, "score": 7374.517414377093 }, { "content": " let remote = &config.remote;\n\n\n\n // Unique access.\n\n if let Some(scripts) = &config.remote.scripts {\n\n if !scripts.no_pull_lock.unwrap_or(false) && config.local.pull_lock.is_none() {\n\n return Err(PullLockRequired.into());\n\n }\n\n }\n\n let _pull_lock_file = if let Some(path) = &config.local.pull_lock {\n\n let f = OpenOptions::new()\n\n .create(true)\n\n .read(true)\n\n .write(true)\n\n .open(path)?;\n\n f.try_lock_exclusive()\n\n .map_err(|e| LockAcquire(path.clone(), e))?;\n\n log::info!(\"Acquired pull lock at {}.\", path);\n\n Some(f)\n\n } else {\n\n None\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 67, "score": 7373.933330457856 }, { "content": " match op.as_str() {\n\n \"hash\" => {\n\n let initial_offset: usize = args\n\n .next()\n\n .expect(\"expecting initial offset\")\n\n .parse()\n\n .unwrap();\n\n let chunk_count: usize = args.next().expect(\"expecting chunk count\").parse().unwrap();\n\n assert!(chunk_count > 0);\n\n assert!(initial_offset % chunk_size == 0);\n\n let end_offset = initial_offset\n\n .checked_add(chunk_size.checked_mul(chunk_count).unwrap())\n\n .unwrap();\n\n\n\n // We're not using `metadata.len` here because of the need to deal with block devices.\n\n f.seek(SeekFrom::End(0)).unwrap();\n\n let file_len = f.stream_position().unwrap();\n\n let end_offset = usize::try_from(file_len).unwrap().min(end_offset);\n\n f.seek(SeekFrom::Start(initial_offset as u64)).unwrap();\n\n\n", "file_path": "bsync-transmit/src/main.rs", "rank": 68, "score": 7373.7797435126695 }, { "content": "\n\n // XXX: This may become large if we are synchronizing a big block device -\n\n // should we store this in SQLite instead?\n\n let mut seen_hashes: HashSet<[u8; 32]> = HashSet::new();\n\n\n\n for chunk in &(0usize..remote_image_size as usize)\n\n .step_by(LOG_BLOCK_SIZE)\n\n .chunks(DIFF_BATCH_SIZE)\n\n {\n\n let chunk = chunk.collect_vec();\n\n let mut microprogress: usize = 0;\n\n bar.set_position(chunk[0] as u64);\n\n let script = format!(\n\n \"~/.bsync/{} {} {} hash {} {}\",\n\n escape(Cow::Borrowed(transmit_filename.as_str())),\n\n escape(Cow::Borrowed(remote.image.as_str())),\n\n LOG_BLOCK_SIZE,\n\n chunk[0],\n\n chunk.len(),\n\n );\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 69, "score": 7373.147008757354 }, { "content": " * LOG_BLOCK_SIZE as u64,\n\n );\n\n bar.set_style(gen_pb_style(\"Fetch\"));\n\n let mut total_download_bytes: usize = 0;\n\n let mut total_reuse_bytes: usize = 0;\n\n for chunk in &fetch_list.iter().chunks(DATA_FETCH_BATCH_SIZE) {\n\n let chunk = chunk.collect_vec();\n\n let fetch_chunk = chunk\n\n .iter()\n\n .filter_map(|x| {\n\n if let FetchOrAssumeExist::Fetch(x) = x {\n\n Some(*x)\n\n } else {\n\n None\n\n }\n\n })\n\n .collect_vec();\n\n\n\n // Don't pass empty string to remote.\n\n let output: Vec<u8> = if fetch_chunk.len() == 0 {\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 70, "score": 7373.105489714208 }, { "content": " let svc = Service {\n\n cache: LruCache::new(100),\n\n snapshot: snapshot.clone(),\n\n cursor: 0,\n\n };\n\n let e = Export {\n\n size: cp.size,\n\n readonly: true,\n\n ..Default::default()\n\n };\n\n std::thread::spawn(move || {\n\n let res = handshake(&mut conn, &e).and_then(|()| transmission(&mut conn, svc));\n\n if let Err(e) = res {\n\n log::error!(\"error while handling connection: {}\", e);\n\n }\n\n });\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 71, "score": 7372.825579417776 }, { "content": " let output = exec_oneshot_bin(\n\n &mut sess,\n\n &script,\n\n |inc| {\n\n microprogress += inc;\n\n bar.set_position(chunk[0] as u64 + (microprogress as u64 / 32) * LOG_BLOCK_SIZE as u64);\n\n },\n\n |x| Box::new(x),\n\n )?;\n\n if output.len() != chunk.len() * 32 {\n\n return Err(ByteCountMismatch(chunk.len() * 32, output.len()).into());\n\n }\n\n let remote_hashes = output.chunks(32);\n\n let local_hashes = chunk.iter().map(|x| {\n\n snapshot\n\n .read_block_hash((*x / LOG_BLOCK_SIZE) as u64)\n\n .unwrap_or(*ZERO_BLOCK_HASH)\n\n });\n\n for (&offset, (lh, rh)) in chunk.iter().zip(local_hashes.zip(remote_hashes)) {\n\n if lh != rh {\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 72, "score": 7372.754424079882 }, { "content": " for offset in (initial_offset..end_offset).step_by(chunk_size) {\n\n let end_offset = offset.checked_add(chunk_size).unwrap().min(end_offset);\n\n let read_len = end_offset.checked_sub(offset).unwrap();\n\n assert!(read_len > 0);\n\n f.read_exact(&mut buf[..read_len]).unwrap();\n\n buf[read_len..].fill(0);\n\n\n\n let hash: [u8; 32] = blake3::hash(&buf).into();\n\n stdout.write_all(&hash[..]).unwrap();\n\n }\n\n }\n\n \"dump\" => {\n\n let offset_list: Vec<usize> = args\n\n .next()\n\n .expect(\"expecting offset list\")\n\n .split(\",\")\n\n .map(|x| x.parse().expect(\"bad offset\"))\n\n .collect();\n\n f.seek(SeekFrom::End(0)).unwrap();\n\n let file_size = f.stream_position().unwrap();\n", "file_path": "bsync-transmit/src/main.rs", "rank": 73, "score": 7372.487485659696 }, { "content": " println!(\"{}\", serde_json::to_string_pretty(&out)?);\n\n } else {\n\n let mut table = Table::new();\n\n table.set_format(*prettytable::format::consts::FORMAT_CLEAN);\n\n table.set_titles(row![\"LSN\", \"CREATED\"]);\n\n for cp in &cp_list {\n\n let created_at = NaiveDateTime::from_timestamp(cp.created_at as i64, 0);\n\n table.add_row(row![cp.lsn, created_at]);\n\n }\n\n table.print_tty(false);\n\n }\n\n Ok(())\n\n }\n\n}\n", "file_path": "bsync/src/cmd_list.rs", "rank": 74, "score": 7371.941916829178 }, { "content": "}\n\n\n\nimpl Read for Service {\n\n fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {\n\n let start_pos = self.cursor as usize;\n\n let end_pos = start_pos as usize + buf.len();\n\n let start_block = start_pos / LOG_BLOCK_SIZE;\n\n let end_block = (end_pos - 1) / LOG_BLOCK_SIZE;\n\n\n\n let mut current_pos = start_pos;\n\n log::trace!(\"requested read with pos {} len {}\", current_pos, buf.len());\n\n\n\n for blkid in start_block..=end_block {\n\n let blk = self.read_block(blkid);\n\n let blk = &blk[current_pos % LOG_BLOCK_SIZE..];\n\n let buf_offset = current_pos - start_pos;\n\n let buf_copy_len = buf.len().checked_sub(buf_offset).unwrap().min(blk.len());\n\n\n\n log::trace!(\n\n \"copy {} bytes from block {} offset {} to buf[{}..{}]\",\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 75, "score": 7371.739563247635 }, { "content": " \"read only block device\",\n\n ))\n\n }\n\n\n\n fn flush(&mut self) -> std::io::Result<()> {\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl Seek for Service {\n\n fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {\n\n match pos {\n\n SeekFrom::Start(x) => {\n\n self.cursor = x;\n\n Ok(x)\n\n }\n\n _ => unimplemented!(),\n\n }\n\n }\n\n}\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 76, "score": 7371.3611803752465 }, { "content": " .scripts\n\n .as_ref()\n\n .and_then(|x| x.pre_pull.as_ref())\n\n {\n\n log::info!(\"Running pre_pull script.\");\n\n let out = exec_oneshot(&mut sess, script)?;\n\n log::info!(\"pre_pull output: {}\", out);\n\n println!(\"Finished running pre_pull script.\");\n\n }\n\n\n\n // Get the size of the remote image.\n\n //\n\n // The image might be created by `pre_pull`.\n\n let remote_image_size: u64 = exec_oneshot(\n\n &mut sess,\n\n &format!(\n\n \"blockdev --getsize64 {} || stat -c \\\"%s\\\" {}\",\n\n escape(Cow::Borrowed(remote.image.as_str())),\n\n escape(Cow::Borrowed(remote.image.as_str())),\n\n ),\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 77, "score": 7371.287876775102 }, { "content": " sess.userauth_pubkey_file(&remote.user, None, Path::new(x), None)?;\n\n } else {\n\n sess.userauth_agent(&remote.user)?;\n\n }\n\n\n\n let db = Database::open_file(Path::new(&config.local.db), true)?;\n\n\n\n let remote_uname = exec_oneshot(&mut sess, \"uname -m; uname -s\")?;\n\n let mut remote_uname_segs = remote_uname.split(\"\\n\");\n\n let remote_arch = remote_uname_segs.next().unwrap_or(\"\");\n\n let remote_os = remote_uname_segs.next().unwrap_or(\"\");\n\n\n\n if remote_os != \"Linux\" && remote_os != \"FreeBSD\" {\n\n return Err(OsNotSupported(remote_os.to_string()).into());\n\n }\n\n\n\n log::info!(\"Remote platform: {}/{}\", remote_arch, remote_os);\n\n\n\n let transmit_image = *ARCH_BLKXMIT\n\n .get(&remote_arch)\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 78, "score": 7370.756777593077 }, { "content": " vec![]\n\n } else {\n\n let script = format!(\n\n \"~/.bsync/{} {} {} dump {}\",\n\n escape(Cow::Borrowed(transmit_filename.as_str())),\n\n escape(Cow::Borrowed(remote.image.as_str())),\n\n LOG_BLOCK_SIZE,\n\n fetch_chunk.iter().map(|x| format!(\"{}\", x)).join(\",\"),\n\n );\n\n exec_oneshot_bin(\n\n &mut sess,\n\n &script,\n\n |inc| bar.inc(inc as u64),\n\n |x| Box::new(snap::read::FrameDecoder::new(x)),\n\n )?\n\n };\n\n if output.len() != fetch_chunk.len() * LOG_BLOCK_SIZE {\n\n return Err(ByteCountMismatch(fetch_chunk.len() * LOG_BLOCK_SIZE, output.len()).into());\n\n }\n\n let mut output_chunks = output.chunks(LOG_BLOCK_SIZE);\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 79, "score": 7370.344790006352 }, { "content": " let mut encoder = snap::write::FrameEncoder::new(&mut stdout);\n\n\n\n for offset in offset_list {\n\n let end_offset = offset\n\n .checked_add(chunk_size)\n\n .unwrap()\n\n .min(file_size as usize);\n\n let read_len = end_offset.checked_sub(offset).unwrap();\n\n assert!(read_len > 0);\n\n f.seek(SeekFrom::Start(offset as u64)).unwrap();\n\n f.read_exact(&mut buf[..read_len]).unwrap();\n\n buf[read_len..].fill(0);\n\n encoder.write_all(&buf).unwrap();\n\n }\n\n }\n\n _ => panic!(\"bad op: {}\", op),\n\n }\n\n stdout.flush().unwrap();\n\n}\n", "file_path": "bsync-transmit/src/main.rs", "rank": 80, "score": 7370.205296938103 }, { "content": " );\n\n total_download_bytes += output.len();\n\n total_reuse_bytes += (chunk.len() - fetch_chunk.len()) * LOG_BLOCK_SIZE;\n\n }\n\n bar.finish();\n\n drop(bar);\n\n\n\n db.add_consistent_point(lsn, remote_image_size);\n\n println!(\n\n \"Downloaded {}B and reused {}B.\",\n\n SizeFormatterBinary::new(total_download_bytes as u64),\n\n SizeFormatterBinary::new(total_reuse_bytes as u64),\n\n );\n\n\n\n if let Some(script) = config\n\n .remote\n\n .scripts\n\n .as_ref()\n\n .and_then(|x| x.post_pull.as_ref())\n\n {\n\n log::info!(\"Running post_pull script.\");\n\n let out = exec_oneshot(&mut sess, script)?;\n\n log::info!(\"post_pull output: {}\", out);\n\n println!(\"Finished running post_pull script.\");\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 81, "score": 7369.643242830599 }, { "content": " };\n\n\n\n // Establish SSH session.\n\n let addr = SocketAddr::new(IpAddr::from_str(&remote.server)?, remote.port.unwrap_or(22));\n\n let tcp = TcpStream::connect(addr).unwrap();\n\n let mut sess = Session::new()?;\n\n sess.set_tcp_stream(tcp);\n\n sess.handshake()?;\n\n\n\n let (host_key, _host_key_type) = sess.host_key().ok_or(NoHostKey)?;\n\n match config.remote.verify {\n\n HostVerification::Insecure => {\n\n log::warn!(\"`remote.verify` is set to `insecure`, skipping host key verification\");\n\n }\n\n HostVerification::Known => {\n\n let mut known_hosts = sess.known_hosts()?;\n\n if let Some(home) = dirs::home_dir() {\n\n let _ = known_hosts.read_file(&home.join(\".ssh/known_hosts\"), KnownHostFileKind::OpenSSH);\n\n }\n\n match known_hosts.check(&remote.server, host_key) {\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 82, "score": 7369.506846332713 }, { "content": " buf_copy_len,\n\n blkid,\n\n current_pos % LOG_BLOCK_SIZE,\n\n buf_offset,\n\n buf_offset + buf_copy_len,\n\n );\n\n\n\n buf[buf_offset..buf_offset + buf_copy_len].copy_from_slice(&blk[..buf_copy_len]);\n\n current_pos += buf_copy_len;\n\n }\n\n\n\n self.cursor += buf.len() as u64;\n\n Ok(buf.len())\n\n }\n\n}\n\n\n\nimpl Write for Service {\n\n fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {\n\n Err(std::io::Error::new(\n\n std::io::ErrorKind::Other,\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 83, "score": 7369.499959311755 }, { "content": "\n\n let db = Database::open_file(&self.db, false)?;\n\n let cp_list = db.list_consistent_point();\n\n let cp = match cp_list.iter().find(|x| x.lsn == self.lsn) {\n\n Some(x) => x,\n\n None => return Err(E::Inconsistent.into()),\n\n };\n\n write_snapshot(&db, cp, &self.output)?;\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "bsync/src/cmd_replay.rs", "rank": 84, "score": 7369.37365803101 }, { "content": " } else if blkdev {\n\n output.write_all(&ZERO_BLOCK)?;\n\n last_is_seek = false;\n\n } else {\n\n output.seek(SeekFrom::Current(write_len as i64)).unwrap();\n\n last_is_seek = true;\n\n }\n\n }\n\n\n\n // It seems that seeking without writing doesn't enlarge the file\n\n if last_is_seek {\n\n output.seek(SeekFrom::Current(-1)).unwrap();\n\n output.write_all(&[0])?;\n\n }\n\n drop(output);\n\n println!(\"Image written to {}.\", path.to_string_lossy());\n\n Ok(())\n\n}\n", "file_path": "bsync/src/cmd_replay.rs", "rank": 85, "score": 7367.312416657807 }, { "content": " CheckResult::Match => {}\n\n CheckResult::NotFound => {\n\n return Err(\n\n HostKeyVerifyError(\"not found - please connect to the remote host once\").into(),\n\n );\n\n }\n\n CheckResult::Mismatch => {\n\n return Err(HostKeyVerifyError(\"mismatch - possible mitm\").into());\n\n }\n\n CheckResult::Failure => {\n\n return Err(HostKeyVerifyError(\"unknown\").into());\n\n }\n\n }\n\n }\n\n HostVerification::Dnssec => {\n\n return Err(HostKeyVerifyError(\"dnssec not yet implemented\").into());\n\n }\n\n }\n\n\n\n if let Some(x) = &remote.key {\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 86, "score": 7367.147893876289 }, { "content": " data.extend_from_slice(buf);\n\n let len = buf.len();\n\n reader.consume(len);\n\n progress(len);\n\n }\n\n }\n\n channel.wait_close()?;\n\n\n\n let sig = channel.exit_signal()?;\n\n let status = channel.exit_status()?;\n\n let mut msg = String::new();\n\n channel.stderr().read_to_string(&mut msg)?;\n\n\n\n // We get `status == 0` if the program is killed by a signal - so do another check here.\n\n if let Some(sig) = sig.exit_signal {\n\n log::error!(\"remote signal: {}, stderr: {}\", sig, msg);\n\n return Err(RemoteError(1).into());\n\n }\n\n\n\n if status != 0 {\n\n log::error!(\"remote returned error {}, stderr: {}\", status, msg);\n\n return Err(RemoteError(status).into());\n\n }\n\n\n\n log::debug!(\"remote stderr: {}\", msg);\n\n Ok(data)\n\n}\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 87, "score": 7366.998396230598 }, { "content": " )?;\n\n\n\n if !maybe_upload_path.is_empty() {\n\n let upload_path = format!(\"{}/{}\", maybe_upload_path, transmit_filename);\n\n let mut remote_file = sess.scp_send(\n\n Path::new(&upload_path),\n\n 0o755,\n\n transmit_image.len() as u64,\n\n None,\n\n )?;\n\n remote_file.write_all(transmit_image)?;\n\n remote_file.send_eof()?;\n\n remote_file.wait_eof()?;\n\n remote_file.close()?;\n\n remote_file.wait_close()?;\n\n println!(\"Installed transmit on remote host at {}.\", upload_path);\n\n }\n\n\n\n if let Some(script) = config\n\n .remote\n", "file_path": "bsync/src/cmd_pull.rs", "rank": 88, "score": 7365.741232052525 }, { "content": "use std::{\n\n convert::TryFrom,\n\n fs::File,\n\n io::{stdout, BufWriter, Read, Seek, SeekFrom, Write},\n\n};\n\n\n", "file_path": "bsync-transmit/src/main.rs", "rank": 89, "score": 7364.739968963277 }, { "content": "trait ReadAndWrite: Read + Write + Send {}\n\n\n\nimpl<T: Read + Write + Send> ReadAndWrite for T {}\n\n\n", "file_path": "bsync/src/cmd_serve.rs", "rank": 90, "score": 5846.823293104995 }, { "content": "# bsync\n\n\n\nIncremental, multi-version remote backup tool for block devices.\n\n\n\nThe on-disk backup format is a SQLite database and I've been dogfooding this on my homelab servers for a while, so I consider this quite stable.\n\n\n\n## Install\n\n\n\nbsync implements pull-style synchronization and should be installed on the backup destination (pull-side) host. Get the latest binary from [Releases](https://github.com/losfair/bsync/releases).\n\n\n\nThe [release workflow](https://github.com/losfair/bsync/blob/main/.github/workflows/ci.yml) builds `bsync` for:\n\n\n\n- Linux (x86_64, binary and `.deb`)\n\n- macOS (x86_64, binary)\n\n- FreeBSD (x86_64, binary)\n\n\n\n## Usage\n\n\n\n`bsync` works over SSH and pulls changes to a block device from the remote host (backup source). Linux (x86\\_64, AArch64) is currently the only supported OS on the backup source.\n\n\n\nPull changes (see \"Example config\" below for an example of `config.yaml`):\n\n\n\n```\n\n$ bsync pull -c ./config.yaml\n\n```\n\n\n\nList local versions:\n\n\n\n```\n\n$ bsync list --db ./backup.db\n\n LSN CREATED \n\n 21800 2021-10-19 08:21:51\n\n 22267 2021-10-19 08:46:24\n\n 30245 2021-10-20 00:22:38\n\n 35319 2021-10-20 08:22:15\n\n```\n\n\n\nBuild an image of the block device at a given point in time:\n\n\n\n```\n\n# Find `lsn` from `bsync list` output\n\n$ bsync replay --db ./backup.db --lsn 30245 --output ./replay.img\n\n```\n\n\n\nStart an NBD server to serve a read-only version of the block device at a given point in time:\n\n\n\n```\n\n$ bsync serve --db ./backup.db --lsn 30245 --listen 127.0.0.1:2939\n\n# Or, to listen on a unix socket\n\n$ bsync serve --db ./backup.db --lsn 30245 --listen unix:/tmp/bsync.sock\n\n```\n\n\n\nSquash the backup to remove historic versions and free up space:\n\n\n\n```\n\n# Remove versions between LSN 21800 and 30245 (boundaries excluded) so that the remaining versions are\n\n# 21800, 30245, 35319\n\n$ bsync squash --db ./backup.db --start-lsn 21800 --end-lsn 30245 \n\n```\n\n\n\n## Example config\n\n\n", "file_path": "README.md", "rank": 91, "score": 14.616334611867227 }, { "content": "The schema of the config file is defined as `BackupConfig` in [src/config.rs](https://github.com/losfair/bsync/blob/main/bsync/src/config.rs) and can be used as a reference.\n\n\n\nNote that bsync doesn't automatically snapshot your volumes yet so please add your own snapshot logic (LVM, zvol, etc.) in `remote.scripts.pre_pull` to ensure data consistency. An example for backing up LVM thin volumes (taken from my homelab servers):\n\n\n\n```yaml\n\nremote:\n\n server: 192.168.1.1\n\n user: root\n\n image: /dev/mapper/VG_data01-data--auto--snapshot--do--not--touch\n\n scripts:\n\n pre_pull: |\n\n set -e\n\n lvremove -y VG_data01/data-auto-snapshot-do-not-touch || true\n\n lvcreate -s VG_data01/data -n data-auto-snapshot-do-not-touch\n\n lvchange -ay -Ky VG_data01/data-auto-snapshot-do-not-touch\n\n post_pull: |\n\n lvremove -y VG_data01/data-auto-snapshot-do-not-touch\n\nlocal:\n\n db: /backup/store.db\n\n pull_lock: /backup/store.lock\n\n```\n", "file_path": "README.md", "rank": 92, "score": 11.913411515220139 } ]
Rust
src/network/message/coinbase/mod.rs
yobicash/yobi
20e639f8ffcf0ba8dea4123d3d4ef5a7a815e072
use libyobicash::errors::YErrorKind as LibErrorKind; use libyobicash::utils::random::*; use libyobicash::utils::time::*; use libyobicash::utils::version::*; use libyobicash::crypto::hash::digest::YDigest64; use libyobicash::crypto::hash::sha::YSHA512; use libyobicash::coinbase::YCoinbase; use bytes::{BytesMut, BufMut, BigEndian, ByteOrder}; use network::rpc_method::YRPCMethod; use version::*; use errors::*; #[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)] pub struct YGetCbReq { pub id: YDigest64, pub version: YVersion, pub time: YTime, pub nonce: u32, pub method: YRPCMethod, pub cb_id: YDigest64, } impl YGetCbReq { pub fn new(cb_id: YDigest64) -> YHResult<YGetCbReq> { let mut req = YGetCbReq { id: YDigest64::default(), version: default_version(), time: YTime::now(), nonce: YRandom::u32(), method: YRPCMethod::GetCb, cb_id: cb_id, }; req.id = req.calc_id()?; Ok(req) } pub fn check(&self) -> YHResult<()> { if self.id != self.calc_id()? { return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into()); } if self.version.major() > default_version().major() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into()); } if self.time > YTime::now() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into()); } if self.method != YRPCMethod::GetCb { return Err(YHErrorKind::InvalidRPCMethod.into()); } Ok(()) } pub fn calc_id(&self) -> YHResult<YDigest64> { let mut buf = BytesMut::new(); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb_id.to_bytes()); Ok(YSHA512::hash(&buf.to_vec())) } pub fn to_bytes(&self) -> YHResult<Vec<u8>> { self.check()?; let mut buf = BytesMut::new(); buf.put(self.id.to_bytes()); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb_id.to_bytes()); Ok(buf.to_vec()) } pub fn from_bytes(buf: &[u8]) -> YHResult<YGetCbReq> { if buf.len() != 156 { return Err(YHErrorKind::InvalidLength.into()); } let mut b = BytesMut::new(); b.extend_from_slice(buf); let id = YDigest64::from_bytes(b.get(0..64).unwrap())?; let version = YVersion::from_bytes(b.get(64..76).unwrap())?; let time = YTime::from_bytes(b.get(76..84).unwrap())?; let nonce = BigEndian::read_u32(b.get(84..88).unwrap()); let method = BigEndian::read_u32(b.get(88..92).unwrap()).into(); let cb_id = YDigest64::from_bytes(b.get(92..156).unwrap())?; let get_cb_req = YGetCbReq { id: id, version: version, time: time, nonce: nonce, method: method, cb_id: cb_id, }; get_cb_req.check()?; Ok(get_cb_req) } } #[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct YGetCbRes { pub id: YDigest64, pub version: YVersion, pub time: YTime, pub nonce: u32, pub method: YRPCMethod, pub cb: YCoinbase, } impl YGetCbRes { pub fn new(cb: &YCoinbase) -> YHResult<YGetCbRes> { let mut res = YGetCbRes { id: YDigest64::default(), version: default_version(), time: YTime::now(), nonce: YRandom::u32(), method: YRPCMethod::GetCb, cb: cb.clone(), }; res.id = res.calc_id()?; Ok(res) } pub fn check(&self) -> YHResult<()> { if self.id != self.calc_id()? { return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into()); } if self.version.major() > default_version().major() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into()); } if self.time > YTime::now() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into()); } if self.method != YRPCMethod::GetCb { return Err(YHErrorKind::InvalidRPCMethod.into()); } self.cb.check()?; Ok(()) } pub fn calc_id(&self) -> YHResult<YDigest64> { let mut buf = BytesMut::new(); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb.to_bytes()?); Ok(YSHA512::hash(&buf.to_vec())) } pub fn to_bytes(&self) -> YHResult<Vec<u8>> { self.check()?; let mut buf = BytesMut::new(); buf.put(self.id.to_bytes()); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb.to_bytes()?); Ok(buf.to_vec()) } pub fn from_bytes(buf: &[u8]) -> YHResult<YGetCbRes> { if buf.len() < 192 { return Err(YHErrorKind::InvalidLength.into()); } let mut b = BytesMut::new(); b.extend_from_slice(buf); let id = YDigest64::from_bytes(b.get(0..64).unwrap())?; let version = YVersion::from_bytes(b.get(64..76).unwrap())?; let time = YTime::from_bytes(b.get(76..84).unwrap())?; let nonce = BigEndian::read_u32(b.get(84..88).unwrap()); let method = BigEndian::read_u32(b.get(88..92).unwrap()).into(); let cb = YCoinbase::from_bytes(b.get(92..).unwrap())?; let get_cb_res = YGetCbRes { id: id, version: version, time: time, nonce: nonce, method: method, cb: cb, }; get_cb_res.check()?; Ok(get_cb_res) } }
use libyobicash::errors::YErrorKind as LibErrorKind; use libyobicash::utils::random::*; use libyobicash::utils::time::*; use libyobicash::utils::version::*; use libyobicash::crypto::hash::digest::YDigest64; use libyobicash::crypto::hash::sha::YSHA512; use libyobicash::coinbase::YCoinbase; use bytes::{BytesMut, BufMut, BigEndian, ByteOrder}; use network::rpc_method::YRPCMethod; use version::*; use errors::*; #[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)] pub struct YGetCbReq { pub id: YDigest64, pub version: YVersion, pub time: YTime, pub nonce: u32, pub method: YRPCMethod, pub cb_id: YDigest64, } impl YGetCbReq { pub fn new(cb_id: YDigest64) -> YHResult<YGetCbReq> { let mut req = YGetCbReq { id: YDigest64::default(), version: default_version(), time: YTime::now(), nonce: YRandom::u32(), method: YRPCMethod::GetCb, cb_id: cb_id, }; req.id = req.calc_id()?; Ok(req) } pub fn check(&self) -> YHResult<()> { if self.id != self.calc_id()? { return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into()); } if self.version.major() > default_version().major() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into()); } if self.time > YTime::now() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into()); } if self.method != YRPCMethod::GetCb { return Err(YHErrorKind::InvalidRPCMethod.into()); } Ok(()) } pub fn calc_id(&self) -> YHResult<YDigest64> { let mut buf = BytesMut::new(); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb_id.to_bytes()); Ok(YSHA512::hash(&buf.to_vec())) } pub fn to_bytes(&self) -> YHResult<Vec<u8>> { self.check()?; let mut buf = BytesMut::new(); buf.put(self.id.to_bytes()); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb_id.to_bytes()); Ok(buf.to_vec()) } pub fn from_bytes(buf: &[u8]) -> YHResult<YGetCbReq> { if buf.len() != 156 { return Err(YHErrorKind::InvalidLength.into()); } let mut b = BytesMut::new(); b.extend_from_slice(buf); let id = YDigest64::from_bytes(b.get(0..64).unwrap())?; let version = YVersion::from_bytes(b.get(64..76).unwrap())?; let time = YTime::from_bytes(b.get(76..84).unwrap())?; let nonce = BigEndian::read_u32(b.get(84..88).unwrap()); let method = BigEndian::read_u32(b.get(88..92).unwrap()).into(); let cb_id = YDigest64::from_bytes(b.get(92..156).unwrap())?; let get_cb_req = YGetCbReq { id: id, version: version, time: time, nonce: nonce, method: method, cb_id: cb_id, }; get_cb_req.check()?; Ok(get_cb_req) } } #[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct YGetCbRes { pub id: YDigest64, pub version: YVersion, pub time: YTime, pub nonce: u32, pub method: YRPCMethod, pub cb: YCoinbase, } impl YGetCbRes { pub fn new(cb: &YCoinbase) -> YHResult<YGetCbRes> { let mut res = YGetCbRes { id: YDigest64::default(), version: default_version(), time: YTime::now(), nonce: YRandom::u32(), method: YRPCMethod::GetCb, cb: cb.clone(), }; res.id = res.calc_id()?; Ok(res) } pub fn check(&self) -> YHResult<()> { if self.id != self.calc_id()? { return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into()); } if self.version.major() > default_version().major() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into()); } if self.time > YTime::now() { return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into()); } if self.method != YRPCMethod::GetCb { return Err(YHErrorKind::InvalidRPCMethod.into()); } self.cb.check()?; Ok(()) } pub fn
BigEndian::read_u32(b.get(88..92).unwrap()).into(); let cb = YCoinbase::from_bytes(b.get(92..).unwrap())?; let get_cb_res = YGetCbRes { id: id, version: version, time: time, nonce: nonce, method: method, cb: cb, }; get_cb_res.check()?; Ok(get_cb_res) } }
calc_id(&self) -> YHResult<YDigest64> { let mut buf = BytesMut::new(); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb.to_bytes()?); Ok(YSHA512::hash(&buf.to_vec())) } pub fn to_bytes(&self) -> YHResult<Vec<u8>> { self.check()?; let mut buf = BytesMut::new(); buf.put(self.id.to_bytes()); buf.put(&self.version.to_bytes()?[..]); buf.put(&self.time.to_bytes()[..]); buf.put_u32::<BigEndian>(self.nonce); buf.put(self.method.to_bytes()); buf.put(self.cb.to_bytes()?); Ok(buf.to_vec()) } pub fn from_bytes(buf: &[u8]) -> YHResult<YGetCbRes> { if buf.len() < 192 { return Err(YHErrorKind::InvalidLength.into()); } let mut b = BytesMut::new(); b.extend_from_slice(buf); let id = YDigest64::from_bytes(b.get(0..64).unwrap())?; let version = YVersion::from_bytes(b.get(64..76).unwrap())?; let time = YTime::from_bytes(b.get(76..84).unwrap())?; let nonce = BigEndian::read_u32(b.get(84..88).unwrap()); let method =
random
[ { "content": "pub fn default_version() -> YVersion {\n\n YVersion::from_str(VERSION).unwrap()\n\n}\n", "file_path": "src/version/mod.rs", "rank": 0, "score": 144484.94624858562 }, { "content": "fn main() {\n\n /*\n\n let opt = YNodeOpt::from_args();\n\n println!(\"yobicashd opt: {:?}\", opt);\n\n */\n\n\n\n /*\n\n YConfig::create_default().unwrap();\n\n println!(\"default config written\");\n\n */\n\n\n\n // TODO\n\n /*\n\n let server = YServer::default();\n\n println!(\"default server created\");\n\n server.run();\n\n println!(\"default server started ad 127.0.0.1:2112\");\n\n */\n\n}\n", "file_path": "src/yobicashd.rs", "rank": 1, "score": 40404.468237664645 }, { "content": "fn main() {\n\n let opt = YClientOpt::from_args();\n\n println!(\"yobicash client opt: {:?}\", opt) \n\n}\n", "file_path": "src/yobicash_cli.rs", "rank": 2, "score": 38983.31839841902 }, { "content": "pub trait YStorage\n\n where Self: Sized\n\n{\n\n type Config;\n\n\n\n fn create(config: Self::Config) -> YHResult<Self>;\n\n\n\n fn open(config: Self::Config) -> YHResult<Self>;\n\n\n\n fn close(&mut self) -> YHResult<()>;\n\n\n\n fn reset(&mut self) -> YHResult<Self>;\n\n\n\n fn destroy(&mut self) -> YHResult<()>;\n\n\n\n fn put(&mut self, buck: &YStoreBuck, key: &YStoreKey, value: &YStoreValue) -> YHResult<()>;\n\n\n\n fn lookup(&self, buck: &YStoreBuck, key: &YStoreKey) -> YHResult<bool>;\n\n\n\n fn get(&self, buck: &YStoreBuck, key: &YStoreKey) -> YHResult<YStoreItem>;\n\n\n\n fn count(&self, buck: &YStoreBuck) -> YHResult<u32>;\n\n\n\n fn list(&self, buck: &YStoreBuck, skip: u32, count: u32) -> YHResult<Vec<YStoreKey>>;\n\n\n\n fn list_reverse(&self, buck: &YStoreBuck, skip: u32, count: u32) -> YHResult<Vec<YStoreKey>>;\n\n\n\n fn delete(&mut self, buck: &YStoreBuck, key: &YStoreKey) -> YHResult<()>;\n\n}\n", "file_path": "src/store/common/mod.rs", "rank": 3, "score": 35749.37317214026 }, { "content": "use libyobicash::utils::version::YVersion;\n\nuse ::VERSION;\n\n\n", "file_path": "src/version/mod.rs", "rank": 4, "score": 34686.54345672968 }, { "content": "use libyobicash::errors::YError as LibError;\n\nuse libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse unqlite::Error as UnQLiteError;\n\nuse serde_json::Error as JSONError;\n\nuse std::string::FromUtf8Error;\n\nuse std::io::Error as IOError;\n\n\n\nerror_chain! {\n\n types {\n\n YHError, YHErrorKind, YHResultExt, YHResult;\n\n }\n\n\n\n links {\n\n Lib(LibError, LibErrorKind);\n\n }\n\n\n\n foreign_links {\n\n IO(IOError);\n\n Store(UnQLiteError);\n\n JSON(JSONError);\n", "file_path": "src/errors/mod.rs", "rank": 5, "score": 34504.55714341608 }, { "content": " ParsingFailure {\n\n description(\"Parsing failure\")\n\n }\n\n\n\n InvalidDifficulty {\n\n description(\"Invalid difficulty\")\n\n }\n\n\n\n InvalidCoinKind {\n\n description(\"Invalid coin kind\")\n\n }\n\n\n\n InvalidCoin {\n\n description(\"Invalid coin\")\n\n }\n\n\n\n InvalidRPCMethod {\n\n description(\"Invalid message rpc method\")\n\n }\n\n\n", "file_path": "src/errors/mod.rs", "rank": 6, "score": 34499.27311064081 }, { "content": " String(FromUtf8Error);\n\n }\n\n\n\n errors {\n\n InvalidPassword {\n\n description(\"Invalid password\")\n\n }\n\n\n\n InvalidKey {\n\n description(\"Invalid key\")\n\n }\n\n\n\n InvalidLength {\n\n description(\"Invalid length\")\n\n }\n\n\n\n InvalidValue {\n\n description(\"Invalid value\") \n\n }\n\n\n", "file_path": "src/errors/mod.rs", "rank": 7, "score": 34499.23869998722 }, { "content": " InvalidIp {\n\n description(\"Invalid ip\")\n\n }\n\n\n\n MaxConnectionsReached {\n\n description(\"Max connections reached\")\n\n }\n\n\n\n FailedConnection {\n\n description(\"Failed connection\")\n\n }\n\n\n\n NotConnected {\n\n description(\"Not connected\")\n\n }\n\n\n\n Other(desc: String) {\n\n description(desc.as_str())\n\n }\n\n }\n\n}\n", "file_path": "src/errors/mod.rs", "rank": 8, "score": 34495.612873366954 }, { "content": " InvalidMessagePrefix {\n\n description(\"Invalid message prefix\")\n\n }\n\n\n\n InvalidMessageKind {\n\n description(\"Invalid message kind\")\n\n }\n\n\n\n InvalidMessageStatus {\n\n description(\"Invalid message status\")\n\n }\n\n\n\n InvalidRequest {\n\n description(\"Invalid request\")\n\n }\n\n\n\n InvalidResponse {\n\n description(\"Invalid response\")\n\n }\n\n\n", "file_path": "src/errors/mod.rs", "rank": 9, "score": 34495.612873366954 }, { "content": " UnknownValue {\n\n description(\"Unknown value\")\n\n }\n\n\n\n NotEnoughFunds {\n\n description(\"Not enough funds\")\n\n }\n\n \n\n NotFound {\n\n description(\"Not found\")\n\n }\n\n\n\n AlreadyFound {\n\n description(\"Already found\")\n\n }\n\n\n\n InvalidLevel {\n\n description(\"Invalid level\")\n\n }\n\n\n", "file_path": "src/errors/mod.rs", "rank": 10, "score": 34495.612873366954 }, { "content": "use bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse std::convert::From;\n\nuse errors::*;\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub enum YRPCMethod {\n\n Ping=0,\n\n ListPeers=1,\n\n ListData=2,\n\n GetData=3,\n\n ListTxAncestors=4,\n\n GetTx=5,\n\n ConfirmTx=6,\n\n GetCb=7,\n\n Unknown,\n\n}\n\n\n\nimpl Default for YRPCMethod {\n\n fn default() -> YRPCMethod {\n\n YRPCMethod::Ping\n", "file_path": "src/network/rpc_method/mod.rs", "rank": 11, "score": 31960.105988989442 }, { "content": " pub fn to_bytes(&self) -> Vec<u8> {\n\n let mut buf = BytesMut::new();\n\n buf.put_u32::<BigEndian>(*self as u32);\n\n buf.to_vec()\n\n }\n\n\n\n pub fn from_bytes(b: &[u8]) -> YHResult<YRPCMethod> {\n\n if b.len() != 4 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n Ok(BigEndian::read_u32(b).into())\n\n }\n\n}\n", "file_path": "src/network/rpc_method/mod.rs", "rank": 12, "score": 31951.258386822057 }, { "content": " }\n\n}\n\n\n\nimpl From<u32> for YRPCMethod {\n\n fn from(n: u32) -> YRPCMethod {\n\n match n {\n\n 0 => YRPCMethod::Ping,\n\n 1 => YRPCMethod::ListPeers,\n\n 2 => YRPCMethod::ListData,\n\n 3 => YRPCMethod::GetData,\n\n 4 => YRPCMethod::ListTxAncestors,\n\n 5 => YRPCMethod::GetTx,\n\n 6 => YRPCMethod::ConfirmTx,\n\n 7 => YRPCMethod::GetCb,\n\n _ => YRPCMethod::Unknown,\n\n }\n\n }\n\n}\n\n\n\nimpl YRPCMethod {\n", "file_path": "src/network/rpc_method/mod.rs", "rank": 13, "score": 31940.226735323085 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::random::*;\n\nuse libyobicash::utils::time::*;\n\nuse libyobicash::utils::version::*;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::hash::sha::YSHA512;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse network::rpc_method::YRPCMethod;\n\nuse version::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YErrorRes {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub message: String,\n\n}\n", "file_path": "src/network/message/error/mod.rs", "rank": 14, "score": 31818.31689977293 }, { "content": " buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.message.as_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.message.as_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YErrorRes> {\n\n if buf.len() < 92 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n", "file_path": "src/network/message/error/mod.rs", "rank": 15, "score": 31808.276168749504 }, { "content": " let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let message = String::from_utf8_lossy(b.get(92..).unwrap()).into_owned();\n\n Ok(YErrorRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n message: message,\n\n })\n\n }\n\n}\n", "file_path": "src/network/message/error/mod.rs", "rank": 16, "score": 31807.586481534137 }, { "content": "\n\nimpl YErrorRes {\n\n pub fn new(method: YRPCMethod, message: String) -> YHResult<YErrorRes> {\n\n let mut res = YErrorRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: method,\n\n message: message,\n\n };\n\n res.id = res.calc_id()?;\n\n Ok(res)\n\n }\n\n\n\n pub fn from_error(method: YRPCMethod, err: YHError) -> YHResult<YErrorRes> {\n\n let msg = String::from(err.description());\n\n YErrorRes::new(method, msg)\n\n }\n\n\n", "file_path": "src/network/message/error/mod.rs", "rank": 17, "score": 31806.995504994164 }, { "content": " pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.message.len() > 20 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n", "file_path": "src/network/message/error/mod.rs", "rank": 18, "score": 31802.28963231494 }, { "content": " id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n tx_id: tx_id,\n\n };\n\n conf_tx_req.check()?;\n\n Ok(conf_tx_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YConfirmTxRes {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub ack: bool,\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 20, "score": 42.167712204470234 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::random::*;\n\nuse libyobicash::utils::time::*;\n\nuse libyobicash::utils::version::*;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::hash::sha::YSHA512;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse models::peer::YPeer;\n\nuse network::rpc_method::YRPCMethod;\n\nuse version::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YListPeersReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub max: u32,\n", "file_path": "src/network/message/peer/mod.rs", "rank": 21, "score": 41.66665721400171 }, { "content": " id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n count: count,\n\n data: data,\n\n };\n\n Ok(ls_data_res)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YGetDataReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub checksum: YDigest64,\n", "file_path": "src/network/message/data/mod.rs", "rank": 22, "score": 41.3875721243746 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::random::*;\n\nuse libyobicash::utils::time::*;\n\nuse libyobicash::utils::version::*;\n\nuse libyobicash::crypto::hash::sha::YSHA512;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::data::YData;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse network::rpc_method::YRPCMethod;\n\nuse version::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YListDataReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub tx_id: YDigest64,\n", "file_path": "src/network/message/data/mod.rs", "rank": 23, "score": 41.31854683325203 }, { "content": " let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let ping_req = YPingReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n };\n\n ping_req.check()?;\n\n Ok(ping_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YPingRes {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n", "file_path": "src/network/message/ping/mod.rs", "rank": 24, "score": 41.27019288571647 }, { "content": " method: method,\n\n count: count,\n\n txs: txs,\n\n };\n\n ls_txs_res.check()?;\n\n Ok(ls_txs_res)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YListTxDescendantsReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub tx_id: YDigest64,\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 26, "score": 40.83281732378908 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::random::*;\n\nuse libyobicash::utils::time::*;\n\nuse libyobicash::utils::version::*;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::hash::sha::YSHA512;\n\nuse libyobicash::transaction::YTransaction;\n\nuse libyobicash::coinbase::YCoinbase;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse network::rpc_method::YRPCMethod;\n\nuse version::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YListTxAncestorsReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 27, "score": 40.24327989968835 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::random::*;\n\nuse libyobicash::utils::time::*;\n\nuse libyobicash::utils::version::*;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::hash::sha::YSHA512;\n\nuse libyobicash::crypto::elliptic::keys::YPublicKey;\n\nuse libyobicash::amount::YAmount;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse network::rpc_method::YRPCMethod;\n\nuse version::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YPingReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n", "file_path": "src/network/message/ping/mod.rs", "rank": 28, "score": 40.070511864572026 }, { "content": " method: method,\n\n tx: tx,\n\n };\n\n get_tx_res.check()?;\n\n Ok(get_tx_res)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YConfirmTxReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub tx_id: YDigest64,\n\n}\n\n\n\nimpl YConfirmTxReq {\n\n pub fn new(tx_id: YDigest64) -> YHResult<YConfirmTxReq> {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 29, "score": 39.15387249800687 }, { "content": " let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let tx_id = YDigest64::from_bytes(b.get(92..156).unwrap())?;\n\n let ls_data_req = YListDataReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n tx_id: tx_id,\n\n };\n\n ls_data_req.check()?;\n\n Ok(ls_data_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YListDataRes {\n\n pub id: YDigest64,\n", "file_path": "src/network/message/data/mod.rs", "rank": 30, "score": 38.404456723410156 }, { "content": " let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let tx_id = YDigest64::from_bytes(b.get(92..156).unwrap())?;\n\n let ls_txs_req = YListTxAncestorsReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n tx_id: tx_id,\n\n };\n\n ls_txs_req.check()?;\n\n Ok(ls_txs_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YListTxAncestorsRes {\n\n pub id: YDigest64,\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 31, "score": 38.020387225003084 }, { "content": " let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let max = BigEndian::read_u32(b.get(92..96).unwrap());\n\n let ls_peers_req = YListPeersReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n max: max,\n\n };\n\n ls_peers_req.check()?;\n\n Ok(ls_peers_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YListPeersRes {\n", "file_path": "src/network/message/peer/mod.rs", "rank": 32, "score": 37.79026737304814 }, { "content": " }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n\npub struct YGetTxRes {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub tx: YTransaction,\n\n}\n\n\n\nimpl YGetTxRes {\n\n pub fn new(tx: &YTransaction) -> YHResult<YGetTxRes> {\n\n let mut res = YGetTxRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 33, "score": 36.3356719399399 }, { "content": " let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let checksum = YDigest64::from_bytes(b.get(92..156).unwrap())?;\n\n let get_data_req = YGetDataReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n checksum: checksum,\n\n };\n\n get_data_req.check()?;\n\n Ok(get_data_req)\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)]\n", "file_path": "src/network/message/data/mod.rs", "rank": 34, "score": 36.26648905856238 }, { "content": "}\n\n\n\nimpl YPingReq {\n\n pub fn new() -> YHResult<YPingReq> {\n\n let mut req = YPingReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::Ping,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n", "file_path": "src/network/message/ping/mod.rs", "rank": 40, "score": 33.157948626880945 }, { "content": "}\n\n\n\nimpl YListPeersReq {\n\n pub fn new(max: u32) -> YHResult<YListPeersReq> {\n\n let mut req = YListPeersReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListPeers,\n\n max: max,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n", "file_path": "src/network/message/peer/mod.rs", "rank": 41, "score": 32.64164271498911 }, { "content": "\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YPingReq> {\n\n if buf.len() != 92 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n", "file_path": "src/network/message/ping/mod.rs", "rank": 42, "score": 32.13705483198782 }, { "content": " let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YConfirmTxReq> {\n\n if buf.len() != 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let tx_id = YDigest64::from_bytes(b.get(92..156).unwrap())?;\n\n let conf_tx_req = YConfirmTxReq {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 43, "score": 31.766151129808428 }, { "content": "}\n\n\n\nimpl YGetDataReq {\n\n pub fn new(checksum: YDigest64) -> YHResult<YGetDataReq> {\n\n let mut req = YGetDataReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::GetData,\n\n checksum: checksum,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n", "file_path": "src/network/message/data/mod.rs", "rank": 44, "score": 31.595618685530955 }, { "content": "}\n\n\n\nimpl YListDataReq {\n\n pub fn new(tx_id: YDigest64) -> YHResult<YListDataReq> {\n\n let mut req = YListDataReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListData,\n\n tx_id: tx_id,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n", "file_path": "src/network/message/data/mod.rs", "rank": 45, "score": 31.50365483524703 }, { "content": "pub struct YGetTxReq {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub tx_id: YDigest64,\n\n}\n\n\n\nimpl YGetTxReq {\n\n pub fn new(tx_id: YDigest64) -> YHResult<YGetTxReq> {\n\n let mut req = YGetTxReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::GetTx,\n\n tx_id: tx_id,\n\n };\n\n req.id = req.calc_id()?;\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 46, "score": 31.497176971100647 }, { "content": " return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let tx_id = YDigest64::from_bytes(b.get(92..156).unwrap())?;\n\n let get_tx_req = YGetTxReq {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n tx_id: tx_id,\n\n };\n\n get_tx_req.check()?;\n\n Ok(get_tx_req)\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 47, "score": 31.436223374159642 }, { "content": " }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.checksum.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YGetDataReq> {\n\n if buf.len() != 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n", "file_path": "src/network/message/data/mod.rs", "rank": 49, "score": 31.151618242108455 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse std::convert::From;\n\nuse store::common::YStoreBuck;\n\nuse errors::*;\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub enum YBucket {\n\n Transactions=0,\n\n Coinbases=1,\n\n Data=2,\n\n UTXO=3,\n\n Wallets=4,\n\n PeersByIp=5,\n\n PeersByLastTime=6,\n\n Keys=7,\n\n Unknown,\n\n}\n\n\n\nimpl Default for YBucket {\n", "file_path": "src/models/bucket/mod.rs", "rank": 50, "score": 31.0383890316069 }, { "content": " let mut req = YConfirmTxReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ConfirmTx,\n\n tx_id: tx_id,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 51, "score": 30.770762482795515 }, { "content": " pub tx_id: YDigest64,\n\n}\n\n\n\nimpl YListTxAncestorsReq {\n\n pub fn new(tx_id: YDigest64) -> YHResult<YListTxAncestorsReq> {\n\n let mut req = YListTxAncestorsReq {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListTxAncestors,\n\n tx_id: tx_id,\n\n };\n\n req.id = req.calc_id()?;\n\n Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 52, "score": 30.630323282670858 }, { "content": " return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::Ping {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n", "file_path": "src/network/message/ping/mod.rs", "rank": 53, "score": 30.616459071338607 }, { "content": " Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YGetTxRes> {\n\n if buf.len() < 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let tx = YTransaction::from_bytes(b.get(92..).unwrap())?;\n\n let get_tx_res = YGetTxRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 54, "score": 30.58316100777414 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::time::YTime;\n\nuse libyobicash::utils::random::YRandom;\n\nuse serde_json;\n\nuse bytes::{BytesMut, BufMut, BigEndian};\n\nuse std::net::Ipv4Addr;\n\nuse store::common::*;\n\nuse models::bucket::*;\n\nuse network::host::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub struct YPeer {\n\n pub host: YHost,\n\n pub last_time: YTime,\n\n}\n\n\n\nimpl Default for YPeer {\n\n fn default() -> YPeer {\n\n YPeer::new(YHost::default())\n", "file_path": "src/models/peer/mod.rs", "rank": 55, "score": 30.579109324317393 }, { "content": " pub fn from_bytes(buf: &[u8]) -> YHResult<YGetDataRes> {\n\n if buf.len() < 192 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let data = YData::from_bytes(b.get(92..).unwrap())?;\n\n let get_data_res = YGetDataRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n data: data,\n\n };\n\n get_data_res.check()?;\n\n Ok(get_data_res)\n\n }\n\n}\n", "file_path": "src/network/message/data/mod.rs", "rank": 56, "score": 30.358499763438246 }, { "content": " }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.max as u32);\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YListPeersReq> {\n\n if buf.len() != 96 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n", "file_path": "src/network/message/peer/mod.rs", "rank": 57, "score": 30.26926791016687 }, { "content": " if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::GetData {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.checksum.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n", "file_path": "src/network/message/data/mod.rs", "rank": 58, "score": 30.156982196025062 }, { "content": "\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YPingRes> {\n\n if buf.len() < 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let public_key = YPublicKey::from_bytes(b.get(92..156).unwrap())?;\n\n let price = YAmount::from_bytes(b.get(156..).unwrap());\n\n let ping_res = YPingRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n public_key: public_key,\n\n price: price,\n\n };\n\n ping_res.check()?;\n\n Ok(ping_res)\n\n }\n\n}\n", "file_path": "src/network/message/ping/mod.rs", "rank": 59, "score": 29.816422006129862 }, { "content": " let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let ack_n = BigEndian::read_u32(b.get(92..96).unwrap());\n\n let mut ack = false;\n\n match ack_n {\n\n 0 => {},\n\n 1 => { ack = true; },\n\n _ => { return Err(YHErrorKind::Other(\"Invalid ack\".to_string()).into()); }\n\n }\n\n let cb = YCoinbase::from_bytes(b.get(96..).unwrap())?;\n\n let confirm_tx_res = YConfirmTxRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n\n method: method,\n\n ack: ack,\n\n cb: cb,\n\n };\n\n confirm_tx_res.check()?;\n\n Ok(confirm_tx_res)\n\n }\n\n}\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 60, "score": 29.481191869333426 }, { "content": " if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::ListPeers {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.max as u32);\n\n Ok(YSHA512::hash(&buf.to_vec()))\n", "file_path": "src/network/message/peer/mod.rs", "rank": 61, "score": 29.273791331547415 }, { "content": " pub cb: YCoinbase,\n\n}\n\n\n\nimpl YConfirmTxRes {\n\n pub fn new(ack: bool, cb: &YCoinbase) -> YHResult<YConfirmTxRes> {\n\n let mut res = YConfirmTxRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ConfirmTx,\n\n ack: ack,\n\n cb: cb.clone(),\n\n };\n\n res.id = res.calc_id()?;\n\n Ok(res)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 62, "score": 28.907580887832545 }, { "content": "\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YListDataReq> {\n\n if buf.len() != 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n", "file_path": "src/network/message/data/mod.rs", "rank": 63, "score": 28.874608360254037 }, { "content": " return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::ConfirmTx {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 64, "score": 28.821290635117325 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::utils::time::YTime;\n\nuse libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::elliptic::keys::YSecretKey;\n\nuse libyobicash::crypto::mac::YMACCode;\n\nuse libyobicash::amount::YAmount;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse serde_json;\n\nuse errors::*;\n\n\n\n#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub enum YCoinKind {\n\n Coinbase=0,\n\n Transaction=1,\n\n}\n\n\n\nimpl YCoinKind {\n\n pub fn to_bytes(&self) -> Vec<u8> {\n\n match *self {\n\n YCoinKind::Coinbase => {\n", "file_path": "src/models/coin/mod.rs", "rank": 65, "score": 28.696851387652274 }, { "content": " self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YGetTxReq> {\n\n if buf.len() != 156 {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 66, "score": 28.22678676715554 }, { "content": " buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.ack as u32);\n\n buf.put(self.cb.to_bytes()?);\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.ack as u32);\n\n buf.put(self.cb.to_bytes()?);\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YConfirmTxRes> {\n\n if buf.len() < 96 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 67, "score": 27.944144152326107 }, { "content": " if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::ListData {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n", "file_path": "src/network/message/data/mod.rs", "rank": 68, "score": 27.89214389830988 }, { "content": " buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.public_key.to_bytes());\n\n buf.put(self.price.to_bytes());\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.public_key.to_bytes());\n\n buf.put(self.price.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n", "file_path": "src/network/message/ping/mod.rs", "rank": 69, "score": 27.823047398260098 }, { "content": "use bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse serde_json;\n\nuse errors::*;\n\nuse std::net::{SocketAddr, SocketAddrV4, IpAddr, Ipv4Addr};\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub struct YHost(pub SocketAddr);\n\n\n\nimpl Default for YHost {\n\n fn default() -> YHost {\n\n YHost::new([127, 0, 0 , 1], 2112)\n\n }\n\n}\n\n\n\nimpl YHost {\n\n pub fn new(addr: [u8; 4], port: u16) -> YHost {\n\n let ip = Ipv4Addr::from(addr);\n\n YHost(SocketAddr::V4(SocketAddrV4::new(ip, port)))\n\n }\n\n\n", "file_path": "src/network/host/mod.rs", "rank": 70, "score": 27.8155563309085 }, { "content": "use libyobicash::crypto::elliptic::keys::*;\n\nuse serde_json;\n\nuse bytes::{BufMut, BytesMut};\n\nuse store::common::*;\n\nuse models::bucket::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YKeys {\n\n pub sk: YSecretKey,\n\n pub pk: YPublicKey,\n\n}\n\n\n\nimpl YKeys {\n\n pub fn new() -> YKeys {\n\n let sk = YSecretKey::random();\n\n let pk = sk.to_public();\n\n YKeys {\n\n sk: sk,\n\n pk: pk,\n", "file_path": "src/models/keys/mod.rs", "rank": 71, "score": 27.6076027679135 }, { "content": " Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YListTxAncestorsReq> {\n\n if buf.len() != 156 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 72, "score": 27.49111510325415 }, { "content": " return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::ConfirmTx {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n self.cb.check()?;\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 73, "score": 27.413948720558892 }, { "content": "use libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::crypto::mac::YMACCode;\n\nuse libyobicash::data::YData as LibData;\n\nuse serde_json;\n\nuse bytes::BufMut;\n\nuse store::common::*;\n\nuse models::bucket::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YData(pub LibData);\n\n\n\nimpl YData {\n\n pub fn new(data: &LibData) -> YHResult<YData> {\n\n data.check()?;\n\n Ok(YData(data.clone()))\n\n }\n\n\n\n pub fn internal(&self) -> LibData {\n\n self.0.clone()\n", "file_path": "src/models/data/mod.rs", "rank": 74, "score": 27.349927544502663 }, { "content": " pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub count: u32,\n\n pub data: Vec<YData>,\n\n}\n\n\n\nimpl YListDataRes {\n\n pub fn new(data: &Vec<YData>) -> YHResult<YListDataRes> {\n\n let mut res = YListDataRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListData,\n\n count: data.len() as u32,\n\n data: data.clone(),\n\n };\n\n res.id = res.calc_id()?;\n", "file_path": "src/network/message/data/mod.rs", "rank": 75, "score": 27.22254995594737 }, { "content": " }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::ListTxAncestors {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx_id.to_bytes());\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 76, "score": 27.21022566626087 }, { "content": " pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub public_key: YPublicKey,\n\n pub price: YAmount,\n\n}\n\n\n\nimpl YPingRes {\n\n pub fn new(pk: YPublicKey, price: &YAmount) -> YHResult<YPingRes> {\n\n let mut res = YPingRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::Ping,\n\n public_key: pk,\n\n price: price.clone(),\n\n };\n\n res.id = res.calc_id()?;\n\n Ok(res)\n\n }\n", "file_path": "src/network/message/ping/mod.rs", "rank": 77, "score": 27.120345222611263 }, { "content": "use libyobicash::crypto::hash::digest::YDigest64;\n\nuse libyobicash::utxo::YUTXO as LibUTXO;\n\nuse bytes::{BufMut, BigEndian};\n\nuse serde_json;\n\nuse store::common::*;\n\nuse models::bucket::*;\n\nuse models::transaction::*;\n\nuse models::coinbase::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Default, Serialize, Deserialize)]\n\npub struct YUTXO(pub LibUTXO);\n\n\n\nimpl YUTXO {\n\n pub fn new(utxo: &LibUTXO) -> YUTXO {\n\n YUTXO(utxo.clone())\n\n }\n\n\n\n pub fn internal(&self) -> LibUTXO {\n\n self.0.clone()\n", "file_path": "src/models/utxo/mod.rs", "rank": 78, "score": 26.943917410686524 }, { "content": " pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub count: u32,\n\n pub peers: Vec<YPeer>,\n\n}\n\n\n\nimpl YListPeersRes {\n\n pub fn new(peers: &Vec<YPeer>) -> YHResult<YListPeersRes> {\n\n let mut res = YListPeersRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListPeers,\n\n count: peers.len() as u32,\n\n peers: peers.clone(),\n\n };\n", "file_path": "src/network/message/peer/mod.rs", "rank": 79, "score": 26.913302278052306 }, { "content": "pub struct YGetDataRes {\n\n pub id: YDigest64,\n\n pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub data: YData,\n\n}\n\n\n\nimpl YGetDataRes {\n\n pub fn new(data: &YData) -> YHResult<YGetDataRes> {\n\n let mut res = YGetDataRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::GetData,\n\n data: data.clone(),\n\n };\n\n res.id = res.calc_id()?;\n", "file_path": "src/network/message/data/mod.rs", "rank": 80, "score": 26.810504813006037 }, { "content": " pub version: YVersion,\n\n pub time: YTime,\n\n pub nonce: u32,\n\n pub method: YRPCMethod,\n\n pub count: u32,\n\n pub txs: Vec<YTransaction>,\n\n}\n\n\n\nimpl YListTxAncestorsRes {\n\n pub fn new(txs: &Vec<YTransaction>) -> YHResult<YListTxAncestorsRes> {\n\n let mut res = YListTxAncestorsRes {\n\n id: YDigest64::default(),\n\n version: default_version(),\n\n time: YTime::now(),\n\n nonce: YRandom::u32(),\n\n method: YRPCMethod::ListTxAncestors,\n\n count: txs.len() as u32,\n\n txs: txs.clone(),\n\n };\n\n res.id = res.calc_id()?;\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 81, "score": 26.78345667554738 }, { "content": " }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.count as u32);\n\n for i in 0..self.count as usize {\n\n let data_buf = self.data[i].to_bytes()?;\n\n let data_size = data_buf.len();\n\n buf.put_u32::<BigEndian>(data_size as u32);\n\n buf.put(data_buf);\n\n }\n\n Ok(buf.to_vec())\n\n }\n\n\n", "file_path": "src/network/message/data/mod.rs", "rank": 82, "score": 26.57380395829035 }, { "content": " pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.data.to_bytes()?);\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.data.to_bytes()?);\n\n Ok(buf.to_vec())\n\n }\n\n\n", "file_path": "src/network/message/data/mod.rs", "rank": 83, "score": 26.550842671774934 }, { "content": "\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::Ping {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n", "file_path": "src/network/message/ping/mod.rs", "rank": 84, "score": 26.047557989595425 }, { "content": " self.tx.check()?;\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx.to_bytes()?);\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put(self.tx.to_bytes()?);\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 85, "score": 25.499043822263822 }, { "content": "use libyobicash::errors::YErrorKind as LibErrorKind;\n\nuse libyobicash::amount::YAmount;\n\nuse libyobicash::crypto::key::YKey32;\n\nuse libyobicash::crypto::encryption::symmetric::YSymmetricEncryption as YSE;\n\nuse serde_json;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse store::common::*;\n\nuse models::bucket::*;\n\nuse models::coin::*;\n\nuse errors::*;\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub struct YWallet {\n\n pub name: String,\n\n pub balance: YAmount,\n\n pub scoins: Vec<YCoin>,\n\n pub ucoins: Vec<YCoin>,\n\n}\n\n\n\nimpl YWallet {\n", "file_path": "src/models/wallet/mod.rs", "rank": 86, "score": 25.287870369990248 }, { "content": " data.check()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.count as u32);\n\n for i in 0..self.count as usize {\n\n let data_buf = self.data[i].to_bytes()?;\n\n let data_size = data_buf.len();\n\n buf.put_u32::<BigEndian>(data_size as u32);\n\n buf.put(data_buf);\n\n }\n\n Ok(YSHA512::hash(&buf.to_vec()))\n", "file_path": "src/network/message/data/mod.rs", "rank": 87, "score": 25.05609538340619 }, { "content": " for peer in self.peers.clone() {\n\n peer.check()?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put_u32::<BigEndian>(self.nonce);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.count as u32);\n\n for i in 0..self.count as usize {\n\n let peer_buf = self.peers[i].to_bytes()?;\n\n let peer_size = peer_buf.len();\n\n buf.put_u32::<BigEndian>(peer_size as u32);\n\n buf.put(peer_buf);\n\n }\n\n Ok(YSHA512::hash(&buf.to_vec()))\n", "file_path": "src/network/message/peer/mod.rs", "rank": 89, "score": 24.79055469033441 }, { "content": " Ok(req)\n\n }\n\n\n\n pub fn check(&self) -> YHResult<()> {\n\n if self.id != self.calc_id()? {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidChecksum).into());\n\n }\n\n if self.version.major() > default_version().major() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidVersion(self.version.to_string())).into());\n\n }\n\n if self.time > YTime::now() {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidTime).into());\n\n }\n\n if self.method != YRPCMethod::GetTx {\n\n return Err(YHErrorKind::InvalidRPCMethod.into());\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 90, "score": 24.729000144797293 }, { "content": " let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let count = BigEndian::read_u32(b.get(92..96).unwrap());\n\n let mut tx_buf = BytesMut::new();\n\n tx_buf.extend_from_slice(b.get(96..).unwrap());\n\n let mut txs = Vec::new();\n\n for i in 0..count as usize {\n\n let size = BigEndian::read_u32(tx_buf.get(i..i+4).unwrap()) as usize;\n\n txs.push(YTransaction::from_bytes(b.get(i+4..i+4+size).unwrap())?);\n\n }\n\n let ls_txs_res = YListTxAncestorsRes {\n\n id: id,\n\n version: version,\n\n time: time,\n\n nonce: nonce,\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 91, "score": 24.261140850390937 }, { "content": "\n\nimpl YBucket {\n\n pub fn to_bytes(&self) -> Vec<u8> {\n\n let mut buf = BytesMut::new();\n\n buf.put_u32::<BigEndian>(*self as u32);\n\n buf.to_vec()\n\n }\n\n\n\n pub fn to_store_buck(&self) -> YStoreBuck {\n\n self.to_bytes()\n\n }\n\n\n\n pub fn from_bytes(b: &[u8]) -> YHResult<YBucket> {\n\n if b.len() != 4 {\n\n return Err(YHErrorKind::Lib(LibErrorKind::InvalidLength).into());\n\n }\n\n Ok(BigEndian::read_u32(b).into())\n\n }\n\n}\n", "file_path": "src/models/bucket/mod.rs", "rank": 92, "score": 23.946745490444894 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl From<u32> for YCoinKind {\n\n fn from(n: u32) -> YCoinKind {\n\n match n {\n\n 0 => YCoinKind::Coinbase,\n\n 1 => YCoinKind::Transaction,\n\n _ => panic!(\"Invalid kind\"),\n\n }\n\n }\n\n}\n\n\n\n#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]\n\npub struct YCoin {\n\n pub date: YTime,\n\n pub sk: YSecretKey,\n\n pub kind: YCoinKind,\n\n pub id: YDigest64,\n", "file_path": "src/models/coin/mod.rs", "rank": 93, "score": 23.856834065791478 }, { "content": " pub fn from_bytes(buf: &[u8]) -> YHResult<YListDataRes> {\n\n if buf.len() < 96 {\n\n return Err(YHErrorKind::InvalidLength.into());\n\n }\n\n let mut b = BytesMut::new();\n\n b.extend_from_slice(buf);\n\n let id = YDigest64::from_bytes(b.get(0..64).unwrap())?;\n\n let version = YVersion::from_bytes(b.get(64..76).unwrap())?;\n\n let time = YTime::from_bytes(b.get(76..84).unwrap())?;\n\n let nonce = BigEndian::read_u32(b.get(84..88).unwrap());\n\n let method = BigEndian::read_u32(b.get(88..92).unwrap()).into();\n\n let count = BigEndian::read_u32(b.get(92..96).unwrap());\n\n let mut data_buf = BytesMut::new();\n\n data_buf.extend_from_slice(b.get(96..).unwrap());\n\n let mut data = Vec::new();\n\n for i in 0..count as usize {\n\n let size = BigEndian::read_u32(data_buf.get(i..i+4).unwrap()) as usize;\n\n data.push(YData::from_bytes(b.get(i+4..i+4+size).unwrap())?);\n\n }\n\n let ls_data_res = YListDataRes {\n", "file_path": "src/network/message/data/mod.rs", "rank": 94, "score": 23.620818718716233 }, { "content": "use serde_json as json;\n\nuse bytes::{BytesMut, BufMut, BigEndian, ByteOrder};\n\nuse network::message::ping::*;\n\nuse network::message::peer::*;\n\nuse network::message::data::*;\n\nuse network::message::transaction::*;\n\nuse network::message::coinbase::*;\n\nuse network::message::prefix::*;\n\nuse errors::*;\n\n\n\npub const YREQUEST_STATUS: u32 = 0;\n\n\n\n#[derive(Clone, Debug, Serialize, Deserialize)]\n\npub enum YRequest {\n\n Ping(YPingReq),\n\n ListPeers(YListPeersReq),\n\n GetData(YGetDataReq),\n\n ListData(YListDataReq),\n\n GetTx(YGetTxReq),\n\n ConfirmTx(YConfirmTxReq),\n", "file_path": "src/network/message/request/mod.rs", "rank": 95, "score": 23.58954981750892 }, { "content": " tx.check()?\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn calc_id(&self) -> YHResult<YDigest64> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(&self.version.to_bytes()?[..]);\n\n buf.put(&self.time.to_bytes()[..]);\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.count as u32);\n\n for i in 0..self.count as usize {\n\n let tx_buf = self.txs[i].to_bytes()?;\n\n let tx_size = tx_buf.len();\n\n buf.put_u32::<BigEndian>(tx_size as u32);\n\n buf.put(tx_buf);\n\n }\n\n Ok(YSHA512::hash(&buf.to_vec()))\n\n }\n", "file_path": "src/network/message/transaction/mod.rs", "rank": 96, "score": 23.510215560223696 }, { "content": " ListTxAncestors(YListTxAncestorsReq),\n\n GetCb(YGetCbReq),\n\n}\n\n\n\nimpl YRequest {\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n let mut buf = BytesMut::new();\n\n let mut req_buf = Vec::new();\n\n\n\n buf.put_u32::<BigEndian>(YMESSAGE_PREFIX);\n\n buf.put_u32::<BigEndian>(YREQUEST_STATUS);\n\n \n\n match *self {\n\n YRequest::Ping(ref req) => {\n\n buf.put_u32::<BigEndian>(0);\n\n req_buf = req.to_bytes()?;\n\n },\n\n YRequest::ListPeers(ref req) => {\n\n buf.put_u32::<BigEndian>(1);\n\n req_buf = req.to_bytes()?;\n", "file_path": "src/network/message/request/mod.rs", "rank": 97, "score": 23.508603341060105 }, { "content": " }\n\n\n\n pub fn to_bytes(&self) -> YHResult<Vec<u8>> {\n\n self.check()?;\n\n let mut buf = BytesMut::new();\n\n buf.put(self.id.to_bytes());\n\n buf.put(self.method.to_bytes());\n\n buf.put_u32::<BigEndian>(self.count as u32);\n\n for i in 0..self.count as usize {\n\n let peer_buf = self.peers[i].to_bytes()?;\n\n let peer_size = peer_buf.len();\n\n buf.put_u32::<BigEndian>(peer_size as u32);\n\n buf.put(peer_buf);\n\n }\n\n Ok(buf.to_vec())\n\n }\n\n\n\n pub fn from_bytes(buf: &[u8]) -> YHResult<YListPeersRes> {\n\n if buf.len() < 96 {\n\n return Err(YHErrorKind::InvalidLength.into());\n", "file_path": "src/network/message/peer/mod.rs", "rank": 98, "score": 23.370330897997544 }, { "content": "use serde::{Serialize, Deserialize};\n\nuse serde_json as json;\n\nuse std::net::TcpListener;\n\nuse std::thread;\n\nuse std::sync::{Arc, Mutex};\n\nuse std::io::prelude::*;\n\nuse std::fmt::Debug;\n\nuse config::*;\n\nuse store::common::*;\n\nuse errors::*;\n\n\n\n#[derive(Debug)]\n\npub struct YServer {\n\n pub config: YConfig,\n\n pub storage_kind: YStorageKind,\n\n pub storage_mode: YStorageMode,\n\n pub difficulty: Option<u32>,\n\n}\n\n\n\nimpl Default for YServer {\n", "file_path": "src/network/server/mod.rs", "rank": 99, "score": 23.336077939191433 } ]
Rust
src/syndication.rs
qezz/rjbot
14ae18305ea36588750b8c34f49c749bd98217c3
use crate::context::Context; use atom_syndication::{Error as AtomError, Feed as AtomFeed}; use bytes::buf::BufExt; use carapax::{methods::SendMessage, types::ParseMode, ExecuteError}; use reqwest::{Error as HttpError, StatusCode}; use rss::{self, Channel as RssChannel, Error as RssError}; use std::{error::Error, fmt, str::FromStr, time::Duration}; use tokio::time::error::Elapsed; use tokio_postgres::Error as PostgresError; pub struct Syndication { context: Context, } impl Syndication { pub fn new(context: Context) -> Self { Self { context } } async fn get_feeds(&self) -> Result<Vec<Feed>, SyndicationError> { let mut result = Vec::new(); let rows = self .context .pg_client .query( "SELECT id, url, kind, last_entry FROM feeds WHERE extract(epoch from (now() - last_update)) >= timeout OR last_update IS NULL", &[], ) .await .map_err(SyndicationError::GetFeeds)?; for row in rows { let id: i32 = row.get(0); let url: String = row.get(1); let kind: String = row.get(2); let last_entry: Option<String> = row.get(3); result.push(Feed { id, url, kind: kind.parse()?, last_entry, }) } Ok(result) } async fn get_last_entries( &self, url: &str, kind: FeedKind, last_id: Option<String>, ) -> Result<Vec<Post>, SyndicationError> { let rep = self.context.http_client.get(url).send().await?; let status = rep.status(); if !status.is_success() { return Err(SyndicationError::BadStatus(status)); } let data = rep.bytes().await?; let new_entries = match kind { FeedKind::Rss => { let channel = RssChannel::read_from(data.reader())?; let items = channel.into_items(); if items.is_empty() { vec![] } else { let pos = items.iter().position(|e| match (e.guid(), last_id.clone()) { (Some(guid), Some(last_id)) => guid.value() == last_id, _ => false, }); if let Some(pos) = pos { items[..pos].iter().rev().filter_map(Post::try_from_rss).collect() } else { items[..=0].iter().filter_map(Post::try_from_rss).collect() } } } FeedKind::Atom => { let feed = AtomFeed::read_from(data.reader())?; let entries = feed.entries(); if entries.is_empty() { vec![] } else { let pos = entries.iter().position(|e| { if let Some(last_id) = last_id.clone() { return e.id() == last_id; } false }); if let Some(pos) = pos { entries[..pos].iter().rev().filter_map(Post::try_from_atom).collect() } else { entries[..=0].iter().filter_map(Post::try_from_atom).collect() } } } }; Ok(new_entries) } pub async fn run(self) -> Result<(), SyndicationError> { let interval = Duration::from_secs(60); let fetch_timeout = Duration::from_secs(600); loop { for feed in self.get_feeds().await? { let _feed_clone = feed.clone(); let last_entry_future = self.get_last_entries(&feed.url, feed.kind, feed.last_entry); let timeout_result = tokio::time::timeout(fetch_timeout, last_entry_future).await; let result = || -> Result<Vec<Post>, SyndicationError> { let new_entries = timeout_result??; Ok(new_entries) }; match result() { Ok(ref entries) => { for entry in entries { let formatted_entry = format!( r#"<a href="{}">{}</a>"#, entry.link, ParseMode::Html.escape(entry.title.clone()), ); self.context .api .execute( SendMessage::new(self.context.config.chat_id, formatted_entry) .parse_mode(ParseMode::Html), ) .await .map_err(SyndicationError::SendMessage)?; self.context .pg_client .execute("UPDATE feeds SET last_entry = $2 WHERE id = $1", &[&feed.id, &entry.id]) .await .map_err(SyndicationError::UpdateFeed)?; } self.context .pg_client .execute("UPDATE feeds SET last_update = now() WHERE id = $1", &[&feed.id]) .await .map_err(SyndicationError::UpdateFeed)?; } Err(err) => { log::error!("inner syndication error: {}, ({:?})", err, err); } } } tokio::time::sleep(interval).await } } } #[derive(Clone, Debug)] struct Feed { id: i32, url: String, kind: FeedKind, last_entry: Option<String>, } #[derive(Clone, Debug)] enum FeedKind { Atom, Rss, } impl FromStr for FeedKind { type Err = SyndicationError; fn from_str(raw: &str) -> Result<Self, Self::Err> { Ok(match raw { "atom" => FeedKind::Atom, "rss" => FeedKind::Rss, _ => return Err(SyndicationError::UnknownFeedKind(String::from(raw))), }) } } #[derive(Debug)] pub enum SyndicationError { Atom(AtomError), BadStatus(StatusCode), GetFeeds(PostgresError), HttpRequest(HttpError), Rss(RssError), SendMessage(ExecuteError), Timeout(Elapsed), UpdateFeed(PostgresError), UnknownFeedKind(String), } impl From<AtomError> for SyndicationError { fn from(err: AtomError) -> Self { SyndicationError::Atom(err) } } impl From<HttpError> for SyndicationError { fn from(err: HttpError) -> Self { SyndicationError::HttpRequest(err) } } impl From<RssError> for SyndicationError { fn from(err: RssError) -> Self { SyndicationError::Rss(err) } } impl From<Elapsed> for SyndicationError { fn from(err: Elapsed) -> Self { SyndicationError::Timeout(err) } } impl Error for SyndicationError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { SyndicationError::GetFeeds(err) => Some(err), SyndicationError::HttpRequest(err) => Some(err), SyndicationError::Rss(err) => Some(err), SyndicationError::SendMessage(err) => Some(err), SyndicationError::UpdateFeed(err) => Some(err), _ => None, } } } impl fmt::Display for SyndicationError { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { match self { SyndicationError::Atom(err) => write!(out, "failed to parse atom feed: {}", err), SyndicationError::BadStatus(status) => write!(out, "server repsond with {} status code", status), SyndicationError::GetFeeds(err) => write!(out, "failed to get feeds: {}", err), SyndicationError::HttpRequest(err) => write!(out, "http request error: {}", err), SyndicationError::Rss(err) => write!(out, "failed to parse RSS: {}", err), SyndicationError::SendMessage(err) => write!(out, "failed to send message: {}", err), SyndicationError::Timeout(elapsed) => write!(out, "timeout elapsed: {}", elapsed), SyndicationError::UpdateFeed(err) => write!(out, "failed to update feed: {}", err), SyndicationError::UnknownFeedKind(kind) => write!(out, "unknown feed kind: {}", kind), } } } #[derive(Debug)] pub struct Post { link: String, title: String, id: Option<String>, } impl Post { pub fn try_from_rss(item: &rss::Item) -> Option<Self> { match (item.title(), item.link()) { (Some(title), Some(link)) => Some(Post { title: title.into(), link: link.into(), id: item.guid().map(|x| x.value().to_string()), }), _ => None, } } pub fn try_from_atom(entry: &atom_syndication::Entry) -> Option<Self> { let links = entry.links(); if links.is_empty() { None } else { let link = &links[0]; let title = link.title().unwrap_or_else(|| entry.title()); Some(Post { title: title.into(), link: link.href().into(), id: Some(entry.id().to_string()), }) } } }
use crate::context::Context; use atom_syndication::{Error as AtomError, Feed as AtomFeed}; use bytes::buf::BufExt; use carapax::{methods::SendMessage, types::ParseMode, ExecuteError}; use reqwest::{Error as HttpError, StatusCode}; use rss::{self, Channel as RssChannel, Error as RssError}; use std::{error::Error, fmt, str::FromStr, time::Duration}; use tokio::time::error::Elapsed; use tokio_postgres::Error as PostgresError; pub struct Syndication { context: Context, } impl Syndication { pub fn new(context: Context) -> Self { Self { context } } async fn get_feeds(&self) -> Result<Vec<Feed>, SyndicationError> { let mut result = Vec::new(); let rows = self .context .pg_client .query( "SELECT id, url, kind, last_entry FROM feeds WHERE extract(epoch from (now() - last_update)) >= timeout OR last_update IS NULL", &[], ) .await .map_err(SyndicationError::GetFeeds)?; for row in rows { let id: i32 = row.get(0); let url: String = row.get(1); let kind: String = row.get(2); let last_entry: Option<String> = row.get(3); result.push(Feed { id, url, kind: kind.parse()?, last_entry, }) } Ok(result) } async fn get_last_entries( &self, url: &str, kind: FeedKind, last_id: Option<String>, ) -> Result<Vec<Post>, SyndicationError> { let rep = self.context.http_client.get(url).send().await?; let status = rep.status(); if !status.is_success() { return Err(SyndicationError::BadStatus(status)); } let data = rep.bytes().await?; let new_entries = match kind { FeedKind::Rss => { let channel = RssChannel::read_from(data.reader())?; let items = channel.into_items(); if items.is_empty() { vec![] } else { let pos = items.iter().position(|e| match (e.guid(), last_id.clone()) { (Some(guid), Some(last_id)) => guid.value() == last_id, _ => false, }); if let Some(pos) = pos { items[..pos].iter().rev().filter_map(Post::try_from_rss).collect() } else { items[..=0].iter().filter_map(Post::try_from_rss).collect() } } } FeedKind::Atom => { let feed = AtomFeed::read_from(data.reader())?; let entries = feed.entries(); if entries.is_empty() { vec![] } else { let pos = entries.iter().position(|e| { if let Some(last_id) = last_id.clone() { return e.id() == last_id; } false }); if let Some(pos) = pos { entries[..pos].iter().rev().filter_map(Post::try_from_atom).collect() } else { entries[..=0].iter().filter_map(Post::try_from_atom).collect() } } } }; Ok(new_entries) } pub async fn run(self) -> Result<(), SyndicationError> { let interval = Duration::from_secs(60); let fetch_timeout = Duration::from_secs(600); loop { for feed in self.get_feeds().await? { let _feed_clone = feed.clone(); let last_entry_future = self.get_last_entries(&feed.url, feed.kind, feed.last_entry); let timeout_result = tokio::time::timeout(fetch_timeout, last_entry_future).await; let result = || -> Result<Vec<Post>, SyndicationError> { let new_entries = timeout_result??; Ok(new_entries) }; match result() { Ok(ref entries) => { for entry in entries { let formatted_entry = format!( r#"<a href="{}">{}</a>"#, entry.link, ParseMode::Html.escape(entry.title.clone()), ); self.context .api .execute( SendMessage::new(self.context.config.chat_id, formatted_entry) .parse_mode(ParseMode::Html), ) .await .map_err(SyndicationError::SendMessage)?; self.context .pg_client .execute("UPDATE feeds SET last_entry = $2 WHERE id = $1", &[&feed.id, &entry.id]) .await .map_err(SyndicationError::UpdateFeed)?; } self.context .pg_client .execute("UPDATE feeds SET last_update = now() WHERE id = $1", &[&feed.id]) .await .map_err(SyndicationError::UpdateFeed)?; } Err(err) => { log::error!("inner syndication error: {}, ({:?})", err, err); } } } tokio::time::sleep(interval).await } } } #[derive(Clone, Debug)] struct Feed { id: i32, url: String, kind: FeedKind, last_entry: Option<String>, } #[derive(Clone, Debug)] enum FeedKind { Atom, Rss, } impl FromStr for FeedKind { type Err = SyndicationError; fn from_str(raw: &str) -> Result<Self, Self::Err> { Ok(match raw { "atom" => FeedKind::Atom, "rss" => FeedKind::Rss, _ => return Err(SyndicationError::UnknownFeedKind(String::from(raw))), }) } } #[derive(Debug)] pub enum SyndicationError { Atom(AtomError), BadStatus(StatusCode), GetFeeds(PostgresError), HttpRequest(HttpError), Rss(RssError), SendMessage(ExecuteError), Timeout(Elapsed), UpdateFeed(PostgresError), UnknownFeedKind(String), } impl From<AtomError> for SyndicationError { fn from(err: AtomError) -> Self { SyndicationError::Atom(err) } } impl From<HttpError> for SyndicationError { fn from(err: HttpError) -> Self { SyndicationError::HttpRequest(err) } } impl From<RssError> for SyndicationError { fn from(err: RssError) -> Self { SyndicationError::Rss(err) } } impl From<Elapsed> for SyndicationError { fn from(err: Elapsed) -> Self { SyndicationError::Timeout(err) } } impl Error for SyndicationError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { SyndicationError::GetFeeds(err) => Some(err), SyndicationError::HttpRequest(err) => Some(err), SyndicationError::Rss(err) => Some(err), SyndicationError::SendMessage(err) => Some(err), SyndicationError::UpdateFeed(err) => Some(err), _ => None, } } } impl fmt::Display for SyndicationError { fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { match self { SyndicationError::Atom(err) => write!(out, "failed to parse atom feed: {}", err), SyndicationError::BadStatus(status) => write!(out, "server repsond with {} status code", status), SyndicationError::GetFeeds(err) => write!(out, "failed to get feeds: {}", err), SyndicationError::HttpRequest(err) => write!(out, "http request error: {}", err), SyndicationError::Rss(err) => write!(out, "failed to parse RSS: {}", err), SyndicationError::SendMessage(err) => write!(out, "failed to send message: {}", err), SyndicationError::Timeout(elapsed) => write!(out, "timeout elapsed: {}", elapsed), SyndicationError::UpdateFeed(err) => write!(out, "failed to update feed: {}", err), SyndicationError::UnknownFeedKind(kind) => write!(out, "unknown feed kind: {}", kind), } } } #[derive(Debug)] pub struct Post { link: String, title: String, id: Option<String>, } impl Post { pub fn try_from_rss(item: &rss::Item) -> Option<Self> { match (item.title(), item.link()) { (Some(title), Some(link)) => Some(Post { title: title.into(), link: link.into(), id: item.guid().map(|x| x.value().to_string()), }), _ => None, } } pub fn try_from_atom(entry: &atom_syndication::Entry) -> Option<Self> { let links = entry.links(); if links.is_empty() { None } else { let link = &links[0];
}
let title = link.title().unwrap_or_else(|| entry.title()); Some(Post { title: title.into(), link: link.href().into(), id: Some(entry.id().to_string()), }) } }
function_block-function_prefix_line
[]
Rust
src/utils.rs
matteopolak/stock-display
d03ad470d7ef786f3652dd8ea5ba5523316d0f3a
use colored::{ColoredString, Colorize}; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::style::{PointMarker, PointStyle}; use plotlib::view::ContinuousView; use reqwest::{header, Client, Error, Response}; use std::collections::VecDeque; use std::io::{self, Write}; use std::str; use std::time::{Duration, SystemTime}; use termsize::{self, Size}; use crate::constants; use crate::structs; pub fn get_input_string(phrase: &str, input_length: usize) -> String { let mut input: String = String::with_capacity(input_length); print!("{}", phrase); io::stdout().flush().ok(); io::stdin() .read_line(&mut input) .expect("Could not read from stdin"); if input.ends_with('\n') { input.pop(); if input.ends_with('\r') { input.pop(); } } input } pub fn pretty_print_data( ticker: &str, points: &VecDeque<(f64, f64)>, current_price: f64, last_price: f64, average_price: f64, width: u32, height: u32, index: u32, (mtd, qtd, ytd): (f64, f64, f64), ) -> () { let plot: Plot = Plot::new(Vec::from_iter(points.clone().into_iter())).point_style( PointStyle::new() .marker(PointMarker::Circle) .colour("#DD3355"), ); let view: ContinuousView = ContinuousView::new().add(plot).x_range( (if index <= width { 0 } else { index - width }) as f64, width as f64, ); println!( "{}", Page::single(&view) .dimensions(width, height) .to_text() .unwrap() ); println!( " {} | Price: {} | Last: {} | Average: {} | Change: {} | MTD: {} | QTD: {} | YTD: {}", ticker.cyan(), round_and_whiten(current_price), round_and_whiten(last_price), diff_without_sign(average_price, current_price), diff_with_sign(last_price, current_price), diff_with_sign_percent(mtd, current_price), diff_with_sign_percent(qtd, current_price), diff_with_sign_percent(ytd, current_price), ); } pub fn round_and_whiten(num: f64) -> ColoredString { format!("${:.2}", num).white() } pub fn diff_with_sign(old: f64, new: f64) -> ColoredString { let diff = new - old; let greater = diff >= 0.; let string = format!("{}${:.2}", if greater { '+' } else { '-' }, diff.abs()); if greater { string.green() } else { string.red() } } pub fn diff_without_sign(old: f64, new: f64) -> ColoredString { let diff = new - old; let string = format!("${:.2}", old); if diff >= 0. { string.green() } else { string.red() } } pub fn diff_with_sign_percent(old: f64, new: f64) -> ColoredString { let diff = new - old; let string = format!("{:+.2}%", diff / old * 100.); if diff >= 0. { string.green() } else { string.red() } } pub fn sleep(s: u64) -> tokio::time::Sleep { tokio::time::sleep(tokio::time::Duration::from_secs(s)) } pub fn terminal_size() -> (u32, u32) { let Size { cols: x, rows: y } = termsize::get().unwrap(); (x as u32 - 15, y as u32 - 6) } pub async fn stock_price(uri: &str, client: &Client) -> Option<f64> { let request: Result<Response, Error> = client .get(uri) .header(header::ACCEPT_LANGUAGE, "en-US;q=0.9") .header(header::ACCEPT_ENCODING, "text") .header(header::USER_AGENT, constants::USER_AGENT_HEADER) .send() .await; if let Ok(response) = request { let json: structs::NasdaqDataWrap = match response.json::<structs::NasdaqDataWrap>().await { Ok(j) => j, Err(_) => return None, }; let raw: Vec<u8> = json .data .primaryData .lastSalePrice .into_bytes() .into_iter() .skip(1) .collect::<Vec<u8>>(); let price: f64 = str::from_utf8(&raw).unwrap().parse::<f64>().unwrap(); return Some(price); } None } pub async fn is_valid_ticker(ticker: &str, client: &Client) -> bool { if !(1..5).contains(&ticker.len()) { return false; } let uri: String = constants::NASDAQ_API_ENDPOINT.replace("{ticker}", ticker); let request: Result<Response, Error> = client .get(uri) .header(header::ACCEPT_LANGUAGE, "en-US;q=0.9") .header(header::ACCEPT_ENCODING, "text") .header(header::USER_AGENT, constants::USER_AGENT_HEADER) .send() .await; if let Ok(response) = request { let status = match response.json::<structs::NasdaqStatusWrap>().await { Ok(j) => j.status.rCode, Err(_) => return false, }; return status == 200; } false } pub async fn ticker_history(ticker: &str, client: &Client) -> Option<(f64, f64, f64)> { let year = current_year(); let uri = constants::MARKETSTACK_API_ENDPOINT .replace("{ticker}", ticker) .replace("{start}", &format!("{}-01-01", year)) .replace("{end}", &format!("{}-12-31", year)); let request: Result<Response, Error> = client.get(uri).send().await; if let Ok(response) = request { let days = match response.json::<structs::NameStackDataWrap>().await { Ok(j) => j.data, Err(_) => return None, }; let length = days.len(); let last = match days.get(length - 1) { Some(d) => d, None => return None, }; let mtd = days.get(29).unwrap_or(last).open; let qtd = days.get(90).unwrap_or(last).open; let ytd = days.get(364).unwrap_or(last).open; return Some((mtd, qtd, ytd)); } None } pub fn current_year() -> u64 { let now: Duration = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .expect("We must be in the past..."); 1970 + now.as_secs() / 31536000 }
use colored::{ColoredString, Colorize}; use plotlib::page::Page; use plotlib::repr::Plot; use plotlib::style::{PointMarker, PointStyle}; use plotlib::view::ContinuousView; use reqwest::{header, Client, Error, Response}; use std::collections::VecDeque; use std::io::{self, Write}; use std::str; use std::time::{Duration, SystemTime}; use termsize::{self, Size}; use crate::constants; use crate::structs; pub fn get_input_string(phrase: &str, input_length: usize) -> String { let mut input: String = String::with_capacity(input_length); print!("{}", phrase); io::stdout().flush().ok(); io::stdin() .read_line(&mut input) .expect("Could not read from stdin"); if input.ends_with('\n') { input.pop(); if input.ends_with('\r') { input.pop(); } } input } pub fn pretty_print_data( ticker: &str, points: &VecDeque<(f64, f64)>, current_price: f64, last_price: f64, average_price: f64, width: u32, height: u32, index: u32, (mtd, qtd, ytd): (f64, f64, f64), ) -> () { let plot: Plot = Plot::new(Vec::from_iter(points.clone().into_iter())).point_style( PointStyle::new() .marker(PointMarker::Circle) .colour("#DD3355"), ); let view: ContinuousView = ContinuousView::new().add(plot).x_range( (if index <= width { 0 } else { index - width }) as f64, width as f64, ); println!( "{}", Page::single(&view) .dimensions(width, height) .to_text() .unwrap() ); println!( " {} | Price: {} | Last: {} | Average: {} | Change: {} | MTD: {} | QTD: {} | YTD: {}", ticker.cyan(), round_and_whiten(current_price), round_and_whiten(last_price), diff_without_sign(average_price, current_price), diff_with_sign(last_price, current_price), diff_with_sign_percent(mtd, current_price), diff_with_sign_percent(qtd, current_price), diff_with_sign_percent(ytd, current_price), ); } pub fn round_and_whiten(num: f64) -> ColoredString { format!("${:.2}", num).white() } pub fn diff_with_sign(old: f64, new: f64) -> ColoredString { let diff = new - old; let greater = diff >= 0.; let string = format!("{}${:.2}", if greater { '+' } else { '-' }, diff.abs()); if greater { string.green() } else { string.red() } } pub fn diff_without_sign(old: f64, new: f64) -> ColoredString { let diff = new - old; let string = format!("${:.2}", old); if diff >= 0. { string.green() } else { string.red() } } pub fn diff_with_sign_percent(old: f64, new: f64) -> ColoredString { let diff = new - old; let string = format!("{:+.2}%", diff / old * 100.); if diff >= 0. { string.green() } else { string.red() } } pub fn sleep(s: u64) -> tokio::time::Sleep { tokio::time::sleep(tokio::time::Duration::from_secs(s)) } pub fn terminal_size() -> (u32, u32) { let Size { cols: x, rows: y } = termsize::get().unwrap(); (x as u32 - 15, y as u32 - 6) } pub async fn stock_price(uri: &str, client: &Client) -> Option<f64> { let request: Result<Response, Error> = client .get(uri) .header(header::ACCEPT_LANGUAGE, "en-US;q=0.9") .header(header::ACCEPT_ENCODING, "text") .header(header::USER_AGENT, constants::USER_AGENT_HEADER) .send() .await; if let Ok(response) = request { let json: structs::NasdaqDataWrap = match response.json::<structs::NasdaqDataWrap>().await { Ok(j) => j, Err(_) => return None, }; let raw: Vec<u8> =
; } let uri: String = constants::NASDAQ_API_ENDPOINT.replace("{ticker}", ticker); let request: Result<Response, Error> = client .get(uri) .header(header::ACCEPT_LANGUAGE, "en-US;q=0.9") .header(header::ACCEPT_ENCODING, "text") .header(header::USER_AGENT, constants::USER_AGENT_HEADER) .send() .await; if let Ok(response) = request { let status = match response.json::<structs::NasdaqStatusWrap>().await { Ok(j) => j.status.rCode, Err(_) => return false, }; return status == 200; } false } pub async fn ticker_history(ticker: &str, client: &Client) -> Option<(f64, f64, f64)> { let year = current_year(); let uri = constants::MARKETSTACK_API_ENDPOINT .replace("{ticker}", ticker) .replace("{start}", &format!("{}-01-01", year)) .replace("{end}", &format!("{}-12-31", year)); let request: Result<Response, Error> = client.get(uri).send().await; if let Ok(response) = request { let days = match response.json::<structs::NameStackDataWrap>().await { Ok(j) => j.data, Err(_) => return None, }; let length = days.len(); let last = match days.get(length - 1) { Some(d) => d, None => return None, }; let mtd = days.get(29).unwrap_or(last).open; let qtd = days.get(90).unwrap_or(last).open; let ytd = days.get(364).unwrap_or(last).open; return Some((mtd, qtd, ytd)); } None } pub fn current_year() -> u64 { let now: Duration = SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .expect("We must be in the past..."); 1970 + now.as_secs() / 31536000 }
json .data .primaryData .lastSalePrice .into_bytes() .into_iter() .skip(1) .collect::<Vec<u8>>(); let price: f64 = str::from_utf8(&raw).unwrap().parse::<f64>().unwrap(); return Some(price); } None } pub async fn is_valid_ticker(ticker: &str, client: &Client) -> bool { if !(1..5).contains(&ticker.len()) { return false
random
[ { "content": "\t// create a counter\n\n\tlet mut i: u32 = 1;\n\n\n\n\t// create some utility variables for metrics\n\n\tlet mut first: bool = true;\n\n\tlet mut last_price: f64 = 0.;\n\n\tlet mut total_price: f64 = 0.;\n\n\n\n\tlet history = match utils::ticker_history(&ticker, &client).await {\n\n\t\tSome(h) => h,\n\n\t\tNone => return,\n\n\t};\n\n\n\n\twhile let Some(price) = utils::stock_price(&uri, &client).await {\n\n\t\tlet (x, y) = utils::terminal_size();\n\n\n\n\t\ttotal_price += price;\n\n\n\n\t\tif first {\n\n\t\t\tfirst = false;\n", "file_path": "src/main.rs", "rank": 12, "score": 18.34268734349122 }, { "content": "\t}\n\n\n\n\t// this is only reached when the loop is broken out of,\n\n\t// which only happens when the stock price can not be fetched\n\n\tprintln!(\" {} Error fetching ticker data\", \"X\".red());\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n\tuse super::*;\n\n\tuse colored::Colorize;\n\n\n\n\t#[tokio::test]\n\n\tasync fn test_ticker_history() {\n\n\t\tlet client: Client = Client::builder()\n\n\t\t\t.min_tls_version(reqwest::tls::Version::TLS_1_2)\n\n\t\t\t.build()\n\n\t\t\t.unwrap();\n\n\n\n\t\tassert!(utils::ticker_history(\"AAPL\", &client).await.is_some());\n", "file_path": "src/main.rs", "rank": 14, "score": 16.102806524156883 }, { "content": "\t\t\tlast_price = price;\n\n\t\t}\n\n\n\n\t\t// if it's larger than the scroll window, then\n\n\t\t// remove the first entry\n\n\t\tif i > x as u32 {\n\n\t\t\tpoints.pop_front();\n\n\t\t}\n\n\n\n\t\t// add the next point to the end of the vector\n\n\t\tpoints.push_back((i as f64, price));\n\n\n\n\t\t// clear the terminal\n\n\t\tterminal.clear_screen().unwrap();\n\n\n\n\t\t// print out the price\n\n\t\tutils::pretty_print_data(\n\n\t\t\t&ticker,\n\n\t\t\t&points,\n\n\t\t\tprice,\n", "file_path": "src/main.rs", "rank": 17, "score": 13.701618441472904 }, { "content": "\t\t\t&input_ticker.white()\n\n\t\t);\n\n\t};\n\n\n\n\t// clear the terminal\n\n\tterminal.clear_screen().unwrap();\n\n\n\n\t// hide the cursor\n\n\tterminal.hide_cursor().unwrap();\n\n\n\n\t// build the URI from the ticker name\n\n\tlet uri: String = constants::NASDAQ_API_ENDPOINT.replace(\"{ticker}\", &ticker);\n\n\n\n\t// create a vector to store data for the chart\n\n\t//\n\n\t// note: a VecDeque is similar to a Vec, except that\n\n\t// it uses a ring buffer to efficiently allow popping (removing)\n\n\t// and pushing (adding) to the front *and* back\n\n\tlet mut points: VecDeque<(f64, f64)> = VecDeque::new();\n\n\n", "file_path": "src/main.rs", "rank": 19, "score": 11.998708905321411 }, { "content": "#![feature(int_log)]\n\n\n\nuse colored::Colorize;\n\nuse reqwest::Client;\n\nuse std::collections::VecDeque;\n\n\n\nmod constants;\n\nmod structs;\n\nmod utils;\n\n\n\n#[tokio::main]\n\nasync fn main() -> () {\n\n\tlet terminal = console::Term::stdout();\n\n\n\n\t// create a new http client from which to dispatch requests\n\n\tlet client: Client = Client::builder()\n\n\t\t.min_tls_version(reqwest::tls::Version::TLS_1_2)\n\n\t\t.build()\n\n\t\t.unwrap();\n\n\n", "file_path": "src/main.rs", "rank": 21, "score": 11.471807574889858 }, { "content": "\t// note: this loop will continue looping until it is broken\n\n\t// out of (with a value here, which is what the variable\n\n\t// is going to be assigned to)\n\n\tlet ticker: String = loop {\n\n\t\t// get the stock ticker from the user\n\n\t\t// of 5 bytes, which is the maximum length of a ticker\n\n\t\tlet input_ticker: String =\n\n\t\t\tutils::get_input_string(&format!(\" {} Stock ticker: \", \"…\".yellow()), 5)\n\n\t\t\t\t.to_uppercase();\n\n\n\n\t\t// if the ticker is valid...\n\n\t\tif utils::is_valid_ticker(&input_ticker, &client).await {\n\n\t\t\t// break out of the loop with the ticker\n\n\t\t\tbreak input_ticker;\n\n\t\t}\n\n\n\n\t\t// if not, say it's invalid and start again\n\n\t\tprintln!(\n\n\t\t\t\" {} The ticker {} is invalid, please try again\",\n\n\t\t\t\"X\".red(),\n", "file_path": "src/main.rs", "rank": 22, "score": 11.290031342479821 }, { "content": "\t}\n\n\n\n\t#[tokio::test]\n\n\tasync fn test_stock_price() {\n\n\t\tlet client: Client = Client::builder()\n\n\t\t\t.min_tls_version(reqwest::tls::Version::TLS_1_2)\n\n\t\t\t.build()\n\n\t\t\t.unwrap();\n\n\n\n\t\tlet uri: String = constants::NASDAQ_API_ENDPOINT.replace(\"{ticker}\", \"AAPL\");\n\n\n\n\t\tassert!(utils::stock_price(&uri, &client).await.is_some());\n\n\t}\n\n\n\n\t#[tokio::test]\n\n\tasync fn test_valid_is_valid_ticker() {\n\n\t\tlet client: Client = Client::builder()\n\n\t\t\t.min_tls_version(reqwest::tls::Version::TLS_1_2)\n\n\t\t\t.build()\n\n\t\t\t.unwrap();\n", "file_path": "src/main.rs", "rank": 23, "score": 11.158683228281589 }, { "content": "\n\n\t\tassert_eq!(utils::is_valid_ticker(\"AAPL\", &client).await, true);\n\n\t}\n\n\n\n\t#[tokio::test]\n\n\tasync fn test_invalid_is_valid_ticker() {\n\n\t\tlet client: Client = Client::builder()\n\n\t\t\t.min_tls_version(reqwest::tls::Version::TLS_1_2)\n\n\t\t\t.build()\n\n\t\t\t.unwrap();\n\n\n\n\t\tassert_eq!(utils::is_valid_ticker(\"AAPLAAPL\", &client).await, false);\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_positive_diff_with_sign_percent() {\n\n\t\tassert_eq!(utils::diff_with_sign_percent(5., 10.), \"+100.00%\".green());\n\n\t}\n\n\n\n\t#[test]\n", "file_path": "src/main.rs", "rank": 25, "score": 9.974132856074725 }, { "content": "\t\t\tlast_price,\n\n\t\t\ttotal_price / i as f64,\n\n\t\t\tx as u32,\n\n\t\t\ty as u32,\n\n\t\t\ti,\n\n\t\t\thistory,\n\n\t\t);\n\n\n\n\t\t// increase the counter by 1\n\n\t\t// note: Rust does not support pre- or\n\n\t\t// post-incrementing to avoid a lot of undefined\n\n\t\t// behaviour (like with C/C++), so this is the\n\n\t\t// only other way to increment\n\n\t\t//\n\n\t\t// fun fact: `n = ++i + i;` is still undefined\n\n\t\t// behaviour in C and C++\n\n\t\ti += 1;\n\n\n\n\t\t// wait 5 seconds\n\n\t\tutils::sleep(5).await;\n", "file_path": "src/main.rs", "rank": 26, "score": 9.41609037382078 }, { "content": "#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NasdaqStatus {\n\n\tpub rCode: u16,\n\n}\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NasdaqPrimaryData {\n\n\tpub lastSalePrice: String,\n\n}\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NameStackDataWrap {\n\n\tpub data: Vec<NameStackData>,\n\n}\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize, Clone)]\n\npub struct NameStackData {\n\n\tpub open: f64,\n\n}\n", "file_path": "src/structs.rs", "rank": 27, "score": 6.995023806635922 }, { "content": "pub const NASDAQ_API_ENDPOINT: &str =\n\n\t\"https://api.nasdaq.com/api/quote/{ticker}/info?assetclass=stocks\";\n\npub const USER_AGENT_HEADER: &str = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36\";\n\npub const MARKETSTACK_API_ENDPOINT: &str = \"http://api.marketstack.com/v1/eod?access_key=51d7cbf4ff50d6af109c7f65477b2633&symbols={ticker}&date_from={start}&date_end={end}&limit=366\";\n", "file_path": "src/constants.rs", "rank": 28, "score": 5.720222509436382 }, { "content": "use serde::Deserialize;\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NasdaqDataWrap {\n\n\tpub data: NasdaqData,\n\n}\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NasdaqData {\n\n\tpub primaryData: NasdaqPrimaryData,\n\n}\n\n\n\n#[allow(non_snake_case)]\n\n#[derive(Deserialize)]\n\npub struct NasdaqStatusWrap {\n\n\tpub status: NasdaqStatus,\n\n}\n\n\n", "file_path": "src/structs.rs", "rank": 29, "score": 3.8935852042051735 }, { "content": "\tfn test_negative_diff_with_sign_percent() {\n\n\t\tassert_eq!(utils::diff_with_sign_percent(10., 5.), \"-50.00%\".red());\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_positive_diff_without_sign() {\n\n\t\tassert_eq!(utils::diff_without_sign(5., 10.), \"$5.00\".green());\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_negative_diff_without_sign() {\n\n\t\tassert_eq!(utils::diff_without_sign(10., 5.), \"$10.00\".red());\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_positive_diff_with_sign() {\n\n\t\tassert_eq!(utils::diff_with_sign(5., 10.), \"+$5.00\".green());\n\n\t}\n\n\n\n\t#[test]\n", "file_path": "src/main.rs", "rank": 30, "score": 2.77890760459251 }, { "content": "# Stock Display 📈\n\n![Build Status](https://github.com/matteopolak/stock-display/actions/workflows/rust.yml/badge.svg)\n\n[![Coverage Status](https://coveralls.io/repos/github/matteopolak/stock-display/badge.svg?branch=main)](https://coveralls.io/github/matteopolak/stock-display?branch=main)\n\n[![License:MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n[![Rust:Nightly](https://img.shields.io/badge/rust-nightly-blue.svg)](https://www.rust-lang.org/tools/install)\n\n\n\n[stock-display](https://github.com/matteopolak/stock-display) is a lightweight stock metrics provider built with Rust. It provides\n\nhistorical data comparisons, price changes, and a plot of real-time stock prices.\n\n\n\n## Install\n\n\n\nSee the [Rust install guide](https://www.rust-lang.org/tools/install) for [Rust nightly](https://doc.rust-lang.org/book/appendix-07-nightly-rust.html),\n\nto [build from source with cargo](https://doc.rust-lang.org/cargo/commands/cargo-build.html), and to [run the unit tests](https://doc.rust-lang.org/cargo/commands/cargo-test.html).\n\n\n\n```\n\n$ cargo +nightly build --release\n\n```\n\n\n\n### Pre-built binaries\n\n\n\nBinaries are released on major releases for Windows platforms and can be located [in the releases tab](https://github.com/matteopolak/stock-display/releases).\n\n\n\n## License\n", "file_path": "README.md", "rank": 31, "score": 1.9207656762776675 }, { "content": "\tfn test_negative_diff_with_sign() {\n\n\t\tassert_eq!(utils::diff_with_sign(10., 5.), \"-$5.00\".red());\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_round_and_whiten() {\n\n\t\tassert_eq!(utils::round_and_whiten(10.365), \"$10.37\".white());\n\n\t}\n\n\n\n\t#[test]\n\n\tfn test_current_year() {\n\n\t\t// check if the year is four digits\n\n\t\t// it's rounded down every time since it's an\n\n\t\t// integer, so I need to check for 3\n\n\t\t//\n\n\t\t// log10(1000) = 3\n\n\t\t// log10(9999) = 3.999\n\n\t\tassert_eq!(utils::current_year().log10(), 3);\n\n\t}\n\n}\n", "file_path": "src/main.rs", "rank": 32, "score": 1.9065842274315112 } ]
Rust
src/bin/nydus-image/main.rs
cloudaice/image-service
7c982b2db3282d2616d37134cef8dd9ec2df426d
#[macro_use(crate_version, crate_authors)] extern crate clap; extern crate stderrlog; mod builder; mod node; mod stargz; mod tree; mod validator; #[macro_use] extern crate log; extern crate serde; const BLOB_ID_MAXIMUM_LENGTH: usize = 1024; use clap::{App, Arg, SubCommand}; use vmm_sys_util::tempfile::TempFile; use std::collections::BTreeMap; use std::fs::metadata; use std::fs::rename; use std::io::{self, Result, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; use builder::SourceType; use nydus_utils::einval; use nydus_utils::log_level_to_verbosity; use rafs::metadata::digest; use rafs::storage::{backend, compress, factory}; use validator::Validator; fn upload_blob( backend: Arc<dyn backend::BlobBackendUploader>, blob_id: &str, blob_path: &Path, ) -> Result<()> { backend .upload(blob_id, blob_path, |(current, total)| { io::stdout().flush().unwrap(); print!("\r"); print!( "Backend blob uploading: {}/{} bytes ({}%)", current, total, current * 100 / total, ); }) .map_err(|e| { error!("upload_blob backend.upload {:?}", e); e })?; print!("\r"); io::stdout().flush().unwrap(); Ok(()) } fn get_readahead_files(source: &Path) -> Result<BTreeMap<PathBuf, Option<u64>>> { let stdin = io::stdin(); let mut files = BTreeMap::new(); let source_path = source.canonicalize().unwrap(); loop { let mut file = String::new(); let ret = stdin.read_line(&mut file); match ret { Ok(size) => { if size == 0 { break; } let file_name = file.trim(); if file_name.is_empty() { continue; } let path = Path::new(file_name); if !path.exists() { warn!("{} does not exist, ignore it!", path.to_str().unwrap()); continue; } let canonicalized_name; match path.canonicalize() { Ok(p) => { if !p.starts_with(&source_path) { continue; } canonicalized_name = p; } Err(_) => continue, } let file_name_trimmed = Path::new("/").join( canonicalized_name .strip_prefix(&source_path) .unwrap() .to_path_buf(), ); debug!( "readahead file: {}, trimmed file name {}", file_name, file_name_trimmed.to_str().unwrap() ); files.insert(file_name_trimmed, None); } Err(err) => { error!("Failed to parse readahead files: {}", err); } } } Ok(files) } fn main() -> Result<()> { let cmd = App::new("nydus image builder") .version(crate_version!()) .author(crate_authors!()) .about("Build image using nydus format.") .subcommand( SubCommand::with_name("create") .about("dump image bootstrap and upload blob to storage backend") .arg( Arg::with_name("SOURCE") .help("source directory") .required(true) .index(1), ) .arg( Arg::with_name("source-type") .long("source-type") .help("source type") .takes_value(true) .default_value("directory") .possible_values(&["directory", "stargz_index"]) ) .arg( Arg::with_name("blob") .long("blob") .help("blob file path") .takes_value(true), ) .arg( Arg::with_name("bootstrap") .long("bootstrap") .help("bootstrap file path (required)") .takes_value(true), ) .arg( Arg::with_name("blob-id") .long("blob-id") .help("blob id (as object id in backend)") .takes_value(true), ) .arg( Arg::with_name("compressor") .long("compressor") .help("how blob will be compressed: none, lz4_block (default)") .takes_value(true) .required(false) .default_value("lz4_block"), ) .arg( Arg::with_name("digester") .long("digester") .help("how inode and blob chunk will be digested: blake3 (default), sha256") .takes_value(true) .required(false) .default_value("blake3"), ) .arg( Arg::with_name("parent-bootstrap") .long("parent-bootstrap") .help("bootstrap file path of parent (optional)") .takes_value(true) .required(false), ) .arg( Arg::with_name("backend-type") .long("backend-type") .help("blob storage backend type (enable backend upload if specified)") .takes_value(true), ) .arg( Arg::with_name("backend-config") .long("backend-config") .help("blob storage backend config (json)") .takes_value(true), ) .arg( Arg::with_name("prefetch-policy") .long("prefetch-policy") .help("Prefetch policy: fs(issued from Fs layer), blob(issued from backend/blob layer), none(no readahead is needed)") .takes_value(true) .required(false) .default_value("none"), ) .arg( Arg::with_name("repeatable") .long("repeatable") .help("Produce environment independent image") .takes_value(false) .required(false), ) .arg( Arg::with_name("disable-check") .long("disable-check") .help("Disable to validate bootstrap file after building") .takes_value(false) .required(false) ) ) .subcommand( SubCommand::with_name("check") .about("validate image bootstrap") .arg( Arg::with_name("bootstrap") .long("bootstrap") .help("bootstrap file path (required)") .takes_value(true), ) ) .arg( Arg::with_name("log-level") .long("log-level") .default_value("info") .help("Specify log level: trace, debug, info, warn, error") .takes_value(true) .required(false) .global(true), ) .get_matches(); let v = cmd .value_of("log-level") .unwrap() .parse() .unwrap_or(log::LevelFilter::Warn); stderrlog::new() .quiet(false) .verbosity(log_level_to_verbosity(v)) .timestamp(stderrlog::Timestamp::Second) .init() .unwrap(); if let Some(matches) = cmd.subcommand_matches("create") { let source_path = Path::new(matches.value_of("SOURCE").expect("SOURCE is required")); let source_type: SourceType = matches .value_of("source-type") .expect("source-type is required") .parse()?; let source_file = metadata(source_path) .map_err(|e| einval!(format!("failed to get source path {:?}", e)))?; let mut blob_id = String::new(); if let Some(p_blob_id) = matches.value_of("blob-id") { blob_id = String::from(p_blob_id); if blob_id.len() > BLOB_ID_MAXIMUM_LENGTH { return Err(einval!(format!( "blob id is limited to length {}", BLOB_ID_MAXIMUM_LENGTH ))); } } let mut compressor = matches.value_of("compressor").unwrap_or_default().parse()?; let mut digester = matches.value_of("digester").unwrap_or_default().parse()?; let repeatable = matches.is_present("repeatable"); match source_type { SourceType::Directory => { if !source_file.is_dir() { return Err(einval!("source must be a directory")); } } SourceType::StargzIndex => { if !source_file.is_file() { return Err(einval!("source must be a JSON file")); } if blob_id.trim() == "" { return Err(einval!("blob-id can't be empty")); } if compressor != compress::Algorithm::GZip { trace!("compressor set to {}", compress::Algorithm::GZip); } compressor = compress::Algorithm::GZip; if digester != digest::Algorithm::Sha256 { trace!("digester set to {}", digest::Algorithm::Sha256); } digester = digest::Algorithm::Sha256; } } let bootstrap_path = Path::new( matches .value_of("bootstrap") .expect("bootstrap is required"), ); let temp_file = TempFile::new_with_prefix("").unwrap(); let mut blob_path = matches .value_of("blob") .map(|p| Path::new(p)) .unwrap_or_else(|| temp_file.as_path()); let mut parent_bootstrap = Path::new(""); if let Some(_parent_bootstrap) = matches.value_of("parent-bootstrap") { parent_bootstrap = Path::new(_parent_bootstrap); } let prefetch_policy = matches .value_of("prefetch-policy") .unwrap_or_default() .parse()?; let hint_readahead_files = if prefetch_policy != builder::PrefetchPolicy::None { get_readahead_files(source_path)? } else { BTreeMap::new() }; let mut ib = builder::Builder::new( source_type, source_path, blob_path, bootstrap_path, parent_bootstrap, blob_id, compressor, digester, hint_readahead_files, prefetch_policy, !repeatable, )?; let (blob_ids, blob_size) = ib.build()?; if !matches.is_present("disable-check") { let mut validator = Validator::new(&bootstrap_path)?; match validator.check(false) { Ok(valid) => { if !valid { return Err(einval!("Failed to build bootstrap from source")); } } Err(err) => { return Err(err); } } } if blob_size > 0 { let blob_id = blob_ids.last().unwrap(); let mut uploaded = false; if let Some(backend_type) = matches.value_of("backend-type") { if let Some(backend_config) = matches.value_of("backend-config") { let config = factory::BackendConfig { backend_type: backend_type.to_owned(), backend_config: serde_json::from_str(backend_config).map_err(|e| { error!("failed to parse backend_config json: {}", e); e })?, }; let blob_backend = factory::new_uploader(config).unwrap(); upload_blob(blob_backend, blob_id.as_str(), blob_path)?; uploaded = true; } } if !uploaded && blob_path == temp_file.as_path() { trace!("rename {:?} to {}", blob_path, blob_id); rename(blob_path, blob_id)?; blob_path = Path::new(blob_id); } } if blob_size > 0 { info!( "build finished, blob id: {:?}, blob file: {:?}", blob_ids, blob_path ); } else { info!("build finished, blob id: {:?}", blob_ids); } } if let Some(matches) = cmd.subcommand_matches("check") { let bootstrap_path = Path::new( matches .value_of("bootstrap") .expect("bootstrap is required"), ); let mut validator = Validator::new(bootstrap_path)?; match validator.check(true) { Ok(valid) => { if valid { info!("Bootstrap is valid"); } else { return Err(einval!("Bootstrap is invalid")); } } Err(err) => { return Err(err); } } } Ok(()) }
#[macro_use(crate_version, crate_authors)] extern crate clap; extern crate stderrlog; mod builder; mod node; mod stargz; mod tree; mod validator; #[macro_use] extern crate log; extern crate serde; const BLOB_ID_MAXIMUM_LENGTH: usize = 1024; use clap::{App, Arg, SubCommand}; use vmm_sys_util::tempfile::TempFile; use std::collections::BTreeMap; use std::fs::metadata; use std::fs::rename; use std::io::{self, Result, Write}; use std::path::{Path, PathBuf}; use std::sync::Arc; use builder::SourceType; use nydus_utils::einval; use nydus_utils::log_level_to_verbosity; use rafs::metadata::digest; use rafs::storage::{backend, compress, factory}; use validator::Validator; fn upload_blob( backend: Arc<dyn backend::BlobBackendUploader>, blob_id: &str, blob_path: &Path, ) -> Result<()> { backend .upload(blob_id, blob_path, |(current, total)| { io::stdout().flush().unwrap(); print!("\r"); print!( "Backend blob uploading: {}/{} bytes ({}%)", current, total, current * 100 / total, ); }) .map_err(|e| { error!("upload_blob backend.upload {:?}", e); e })?; print!("\r"); io::stdout().flush().unwrap(); Ok(()) } fn get_readahead_files(source: &Path) -> Result<BTreeMap<PathBuf, Option<u64>>> { let stdin = io::stdin(); let mut files = BTreeMap::new(); let source_path = source.canonicalize().unwrap(); loop { let mut file = String::new(); let ret = stdin.read_line(&mut file); match ret { Ok(size) => { if size == 0 { break; } let file_name = file.trim(); if file_name.is_empty() { continue; } let path = Path::new(file_name); if !path.exists() { warn!("{} does not exist, ignore it!", path.to_str().unwrap()); continue; } let canonicalized_name; match path.canonicalize() { Ok(p) => { if !p.starts_with(&source_path) { continue; } canonicalized_name = p; } Err(_) => continue, } let file_name_trimmed = Path::new("/").join( canonicalized_name .strip_prefix(&source_path) .unwrap() .to_path_buf(), ); debug!( "readahead file: {}, trimmed file name {}", file_name, file_name_trimmed.to_str().unwrap() ); files.insert(file_name_trimmed, None); } Err(err) => { error!("Failed to parse readahead files: {}", err); } } } Ok(files) } fn main() -> Result<()> { let cmd = App::new("nydus image builder") .version(crate_version!()) .author(crate_authors!()) .about("Build image using nydus format.") .subcommand( SubCommand::with_name("create") .about("dump image bootstrap and upload blob to storage backend") .arg( Arg::with_name("SOURCE") .help("source directory") .required(true) .index(1), ) .arg( Arg::with_name("source-type") .long("source-type") .help("source type") .takes_value(true) .default_value("directory") .possible_values(&["directory", "stargz_index"]) ) .arg( Arg::with_name("blob") .long("blob") .help("blob file path") .takes_value(true), ) .arg( Arg::with_name("bootstrap") .long("bootstrap") .help("bootstrap file path (required)") .takes_value(true), ) .arg( Arg::with_name("blob-id") .long("blob-id") .help("blob id (as object id in backend)") .takes_value(true), ) .arg( Arg::with_name("compressor") .long("compressor") .help("how blob will be compressed: none, lz4_block (default)") .takes_value(true) .required(false) .default_value("lz4_block"), ) .arg( Arg::with_name("digester") .long("digester") .help("how inode and blob chunk will be digested: blake3 (default), sha256") .takes_value(true) .required(false) .default_value("blake3"), ) .arg( Arg::with_name("parent-bootstrap") .long("parent-bootstrap") .help("bootstrap file path of parent (optional)") .takes_value(true) .required(false), ) .arg( Arg::with_name("backend-type") .long("backend-type") .help("blob storage backend type (enable backend upload if specified)") .takes_value(true), ) .arg( Arg::with_name("backend-config") .long("backend-config") .help("blob storage backend config (json)") .takes_value(true), ) .arg( Arg::with_name("prefetch-policy") .long("prefetch-policy") .help("Prefetch policy: fs(issued from Fs layer), blob(issued from backend/blob layer), none(no readahead is needed)") .takes_value(true) .required(false) .default_value("none"), ) .arg( Arg::with_name("repeatable") .long("repeatable") .help("Produce environment independent image") .takes_value(false) .required(false), ) .arg( Arg::with_name("disable-check") .long("disable-check") .help("Disable to validate bootstrap file after building") .takes_value(false) .required(false) ) ) .subcommand( SubCommand::with_name("check") .about("validate image bootstrap") .arg( Arg::with_name("bootstrap") .long("bootstrap") .help("bootstrap file path (required)") .takes_value(true), ) ) .arg( Arg::with_name("log-level") .long("log-level") .default_value("info") .help("Specify log level: trace, debug, info, warn, error") .takes_value(true) .required(false) .global(true), ) .get_matches(); let v = cmd .value_of("log-level") .unwrap() .parse() .unwrap_or(log::LevelFilter::Warn); stderrlog::new() .quiet(false) .verbosity(log_level_to_verbosity(v)) .timestamp(stderrlog::Timestamp::Second) .init() .unwrap(); if let Some(matches) = cmd.subcommand_matches("create") { let source_path = Path::new(matches.value_of("SOURCE").expect("SOURCE is required")); let source_type: SourceType = matches .value_of("source-type") .expect("source-type is required") .parse()?; let source_file = metadata(source_path) .map_err(|e| einval!(format!("failed to get source path {:?}", e)))?; let mut blob_id = String::new(); if let Some(p_blob_id) = matches.value_of("blob-id") { blob_id = String::from(p_blob_id); if blob_id.len() > BLOB_ID_MAXIMUM_LENGTH { return Err(einval!(format!( "blob id is limited to length {}", BLOB_ID_MAXIMUM_LENGTH ))); } } let mut compressor = matches.value_of("compressor").unwrap_or_default().parse()?; let mut digester = matches.value_of("digester").unwrap_or_default().parse()?; let repeatable = matches.is_present("repeatable"); match source_type { SourceType::Directory => { if !source_file.is_dir() { return Err(einval!("source must be a directory")); } } SourceType::StargzIndex => { if !source_file.is_file() { return Err(einval!("source must be a JSON file")); } if blob_id.trim() == "" { return Err(einval!("blob-id can't be empty")); } if compressor != compress::Algorithm::GZip { trace!("compressor set to {}", compress::Algorithm::GZip); } compressor = compress::Algorithm::GZip; if digester != digest::Algorithm::Sha256 { trace!("digester set to {}", digest::Algorithm::Sha256); } digester = digest::Algorithm::Sha256; } } let bootstrap_path = Path::new( matches .value_of("bootstrap") .expect("bootstrap is required"), ); let temp_file = TempFile::new_with_prefix("").unwrap(); let mut blob_path = matches .value_of("blob") .map(|p| Path::new(p)) .unwrap_or_else(|| temp_file.as_path()); let mut parent_bootstrap = Path::new(""); if let Some(_parent_bootstrap) = matches.value_of("parent-bootstrap") { parent_bootstrap = Path::new(_parent_bootstrap); } let prefetch_policy = matches .value_of("prefetch-policy") .unwrap_or_default() .parse()?; let hint_readahead_files = if prefetch_policy != builder::PrefetchPolicy::None { get_readahead_files(source_path)? } else { BTreeMap::new() }; let mut ib = builder::Builder::new( source_type, source_path, blob_path, bootstrap_path, parent_bootstrap, blob_id, compressor, digester, hint_readahead_files, prefetch_policy, !repeatable, )?; let (blob_ids, blob_size) = ib.build()?; if !matches.is_present("disable-check") { let mut validator = Validator::new(&bootstrap_path)?; match validator.check(false) { Ok(valid) => { if !valid { return Err(einval!("Failed to build bootstrap from source")); } } Err(err) => { return Err(err); } } } if blob_size > 0 { let blob_id = blob_ids.last().unwrap(); let mut uploaded = false;
if !uploaded && blob_path == temp_file.as_path() { trace!("rename {:?} to {}", blob_path, blob_id); rename(blob_path, blob_id)?; blob_path = Path::new(blob_id); } } if blob_size > 0 { info!( "build finished, blob id: {:?}, blob file: {:?}", blob_ids, blob_path ); } else { info!("build finished, blob id: {:?}", blob_ids); } } if let Some(matches) = cmd.subcommand_matches("check") { let bootstrap_path = Path::new( matches .value_of("bootstrap") .expect("bootstrap is required"), ); let mut validator = Validator::new(bootstrap_path)?; match validator.check(true) { Ok(valid) => { if valid { info!("Bootstrap is valid"); } else { return Err(einval!("Bootstrap is invalid")); } } Err(err) => { return Err(err); } } } Ok(()) }
if let Some(backend_type) = matches.value_of("backend-type") { if let Some(backend_config) = matches.value_of("backend-config") { let config = factory::BackendConfig { backend_type: backend_type.to_owned(), backend_config: serde_json::from_str(backend_config).map_err(|e| { error!("failed to parse backend_config json: {}", e); e })?, }; let blob_backend = factory::new_uploader(config).unwrap(); upload_blob(blob_backend, blob_id.as_str(), blob_path)?; uploaded = true; } }
if_condition
[ { "content": "pub fn new_uploader(mut config: BackendConfig) -> Result<Arc<dyn BlobBackendUploader>> {\n\n // Disable http timeout for upload request\n\n config.backend_config[\"connect_timeout\"] = 0.into();\n\n config.backend_config[\"timeout\"] = 0.into();\n\n match config.backend_type.as_str() {\n\n #[cfg(feature = \"backend-oss\")]\n\n \"oss\" => {\n\n let backend = oss::new(config.backend_config)?;\n\n Ok(Arc::new(backend) as Arc<dyn BlobBackendUploader>)\n\n }\n\n #[cfg(feature = \"backend-registry\")]\n\n \"registry\" => {\n\n let backend = registry::new(config.backend_config)?;\n\n Ok(Arc::new(backend) as Arc<dyn BlobBackendUploader>)\n\n }\n\n #[cfg(feature = \"backend-localfs\")]\n\n \"localfs\" => {\n\n let backend = localfs::new(config.backend_config)?;\n\n Ok(Arc::new(backend) as Arc<dyn BlobBackendUploader>)\n\n }\n\n _ => Err(einval!(format!(\n\n \"unsupported backend type '{}'\",\n\n config.backend_type\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "rafs/src/storage/factory.rs", "rank": 0, "score": 346951.15808855224 }, { "content": "pub fn new(config: serde_json::value::Value) -> Result<LocalFs> {\n\n let config: LocalFsConfig = serde_json::from_value(config).map_err(|e| einval!(e))?;\n\n\n\n if config.blob_file.is_empty() && config.dir.is_empty() {\n\n return Err(einval!(\"blob file or dir is required\"));\n\n }\n\n\n\n if !config.blob_file.is_empty() {\n\n return Ok(LocalFs {\n\n blob_file: config.blob_file,\n\n readahead: config.readahead,\n\n readahead_sec: config.readahead_sec,\n\n file_table: RwLock::new(HashMap::new()),\n\n ..Default::default()\n\n });\n\n }\n\n\n\n Ok(LocalFs {\n\n dir: config.dir,\n\n readahead: config.readahead,\n\n readahead_sec: config.readahead_sec,\n\n file_table: RwLock::new(HashMap::new()),\n\n ..Default::default()\n\n })\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 1, "score": 284239.6426188372 }, { "content": "type FileTableEntry = (File, Option<Arc<LocalFsAccessLog>>);\n\n\n\n#[derive(Default)]\n\npub struct LocalFs {\n\n // the specified blob file\n\n blob_file: String,\n\n // directory to blob files\n\n dir: String,\n\n // readahead blob file\n\n readahead: bool,\n\n // number of seconds to record blob access logs\n\n readahead_sec: u32,\n\n // blobid-File map\n\n file_table: RwLock<HashMap<String, FileTableEntry>>,\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 2, "score": 277618.44862984336 }, { "content": "pub fn new_backend(config: BackendConfig) -> Result<Arc<dyn BlobBackend + Send + Sync>> {\n\n match config.backend_type.as_str() {\n\n #[cfg(feature = \"backend-oss\")]\n\n \"oss\" => {\n\n Ok(Arc::new(oss::new(config.backend_config)?) as Arc<dyn BlobBackend + Send + Sync>)\n\n }\n\n #[cfg(feature = \"backend-registry\")]\n\n \"registry\" => {\n\n Ok(Arc::new(registry::new(config.backend_config)?)\n\n as Arc<dyn BlobBackend + Send + Sync>)\n\n }\n\n #[cfg(feature = \"backend-localfs\")]\n\n \"localfs\" => {\n\n Ok(Arc::new(localfs::new(config.backend_config)?)\n\n as Arc<dyn BlobBackend + Send + Sync>)\n\n }\n\n _ => Err(einval!(format!(\n\n \"unsupported backend type '{}'\",\n\n config.backend_type\n\n ))),\n\n }\n\n}\n\n\n", "file_path": "rafs/src/storage/factory.rs", "rank": 3, "score": 268267.56765624275 }, { "content": "#[allow(clippy::useless_let_if_seq)]\n\npub fn new(config: serde_json::value::Value) -> Result<Registry> {\n\n let common_config: CommonConfig =\n\n serde_json::from_value(config.clone()).map_err(|e| einval!(e))?;\n\n let force_upload = common_config.force_upload;\n\n let retry_limit = common_config.retry_limit;\n\n let request = Request::new(common_config)?;\n\n\n\n let config: RegistryConfig = serde_json::from_value(config).map_err(|e| einval!(e))?;\n\n\n\n let username;\n\n let password;\n\n\n\n if config.auth.trim().is_empty() {\n\n username = String::new();\n\n password = String::new();\n\n } else {\n\n let auth = base64::decode(config.auth.as_bytes()).map_err(|e| {\n\n einval!(format!(\n\n \"Invalid base64 encoded registry auth config: {:?}\",\n\n e\n", "file_path": "rafs/src/storage/backend/registry.rs", "rank": 4, "score": 258752.1383960342 }, { "content": "pub fn new(config: serde_json::value::Value) -> Result<OSS> {\n\n let common_config: CommonConfig =\n\n serde_json::from_value(config.clone()).map_err(|e| einval!(e))?;\n\n let force_upload = common_config.force_upload;\n\n let retry_limit = common_config.retry_limit;\n\n let request = Request::new(common_config)?;\n\n\n\n let config: OssConfig = serde_json::from_value(config).map_err(|e| einval!(e))?;\n\n\n\n Ok(OSS {\n\n scheme: config.scheme,\n\n endpoint: config.endpoint,\n\n access_key_id: config.access_key_id,\n\n access_key_secret: config.access_key_secret,\n\n bucket_name: config.bucket_name,\n\n request,\n\n force_upload,\n\n retry_limit,\n\n })\n\n}\n", "file_path": "rafs/src/storage/backend/oss.rs", "rank": 5, "score": 258747.58917701134 }, { "content": "fn check_compact<'a>(work_dir: &'a PathBuf, bootstrap_name: &str, rafs_mode: &str) -> Result<()> {\n\n let nydusd = nydusd::new(\n\n work_dir,\n\n false,\n\n false,\n\n rafs_mode.parse()?,\n\n bootstrap_name.to_string(),\n\n true,\n\n )?;\n\n\n\n nydusd.start()?;\n\n let result_path = format!(\"repeatable/{}.result\", bootstrap_name);\n\n nydusd.check(result_path.as_str())?;\n\n nydusd.stop();\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 6, "score": 247402.5513973374 }, { "content": "/// Parse a 'buf' to xattr value by xattr name.\n\npub fn parse_xattr_value(data: &[u8], size: usize, name: &OsStr) -> Result<Option<XattrValue>> {\n\n let mut value = None;\n\n\n\n parse_xattr(data, size, |_name, _value| {\n\n if _name == name {\n\n value = Some(_value);\n\n // stop the iteration if we found the xattr name.\n\n return false;\n\n }\n\n true\n\n })?;\n\n\n\n Ok(value)\n\n}\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 7, "score": 246019.77655064716 }, { "content": "fn default_merging_size() -> usize {\n\n 128 * 1024\n\n}\n\n\n\n#[derive(Clone, Default, Deserialize)]\n\npub struct FsPrefetchControl {\n\n #[serde(default)]\n\n enable: bool,\n\n #[serde(default = \"default_threads_count\")]\n\n threads_count: usize,\n\n #[serde(default = \"default_merging_size\")]\n\n merging_size: usize,\n\n}\n\n\n\n/// Rafs storage backend configuration information.\n\n#[derive(Clone, Default, Deserialize)]\n\npub struct RafsConfig {\n\n pub device: factory::Config,\n\n pub mode: String,\n\n #[serde(default)]\n", "file_path": "rafs/src/fs.rs", "rank": 8, "score": 219194.46613087843 }, { "content": "pub fn log_level_to_verbosity(level: log::LevelFilter) -> usize {\n\n level as usize - 1\n\n}\n\n\n", "file_path": "utils/src/lib.rs", "rank": 9, "score": 207871.92931233617 }, { "content": "pub fn export_files_stats(name: &Option<String>) -> Result<String, String> {\n\n let ios_set = IOS_SET.read().unwrap();\n\n\n\n match name {\n\n Some(k) => ios_set\n\n .get(k)\n\n .ok_or_else(|| \"No such id\".to_string())\n\n .map(|v| v.export_files_stats()),\n\n None => {\n\n if ios_set.len() == 1 {\n\n if let Some(ios) = ios_set.values().next() {\n\n return Ok(ios.export_files_stats());\n\n }\n\n }\n\n Err(\"No metrics counter was specified.\".to_string())\n\n }\n\n }\n\n}\n\n\n", "file_path": "rafs/src/io_stats.rs", "rank": 10, "score": 207291.82394038257 }, { "content": "/// Umount a fuse file system\n\nfn fuse_kern_umount(mountpoint: &str, file: File) -> io::Result<()> {\n\n let mut fds = [PollFd::new(file.as_raw_fd(), PollFlags::empty())];\n\n let res = poll(&mut fds, 0);\n\n\n\n // Drop to close fuse session fd, otherwise synchronous umount\n\n // can recurse into filesystem and deadlock.\n\n drop(file);\n\n\n\n if res.is_ok() {\n\n // POLLERR means the file system is already umounted,\n\n // or the connection was severed via /sys/fs/fuse/connections/NNN/abort\n\n if let Some(event) = fds[0].revents() {\n\n if event == PollFlags::POLLERR {\n\n return Ok(());\n\n }\n\n }\n\n }\n\n\n\n umount2(mountpoint, MntFlags::MNT_DETACH).map_err(|e| eother!(e))\n\n}\n", "file_path": "utils/src/fuse.rs", "rank": 11, "score": 207027.7550646421 }, { "content": "pub fn copyv(src: &[u8], dst: &[VolatileSlice], offset: u64, mut max_size: usize) -> Result<usize> {\n\n let mut offset = offset as usize;\n\n let mut size: usize = 0;\n\n if max_size > src.len() {\n\n max_size = src.len()\n\n }\n\n\n\n for s in dst.iter() {\n\n if offset >= src.len() || size >= src.len() {\n\n break;\n\n }\n\n let mut len = max_size - size;\n\n if offset + len > src.len() {\n\n len = src.len() - offset;\n\n }\n\n\n\n s.write_slice(&src[offset..offset + len], 0)\n\n .map_err(|e| einval!(e))?;\n\n offset += len;\n\n size += len;\n\n }\n\n\n\n Ok(size)\n\n}\n\n\n", "file_path": "rafs/src/storage/utils.rs", "rank": 12, "score": 206966.5820673252 }, { "content": "fn default_readahead_sec() -> u32 {\n\n BLOB_ACCESS_RECORD_SECOND\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 13, "score": 206776.12622132557 }, { "content": "fn default_http_scheme() -> String {\n\n \"https\".to_string()\n\n}\n", "file_path": "rafs/src/storage/backend/mod.rs", "rank": 14, "score": 206434.41157715162 }, { "content": "pub fn export_files_access_pattern(name: &Option<String>) -> Result<String, String> {\n\n let ios_set = IOS_SET.read().unwrap();\n\n match name {\n\n Some(k) => ios_set\n\n .get(k)\n\n .ok_or_else(|| \"No such Id\".to_string())\n\n .map(|v| v.export_files_access_patterns()),\n\n None => {\n\n if ios_set.len() == 1 {\n\n if let Some(ios) = ios_set.values().next() {\n\n return Ok(ios.export_files_access_patterns());\n\n }\n\n }\n\n Err(\"No records was specified.\".to_string())\n\n }\n\n }\n\n}\n\n\n", "file_path": "rafs/src/io_stats.rs", "rank": 15, "score": 203279.04625407653 }, { "content": "pub fn toggle_files_recording(name: &Option<String>, switch: bool) -> Result<(), String> {\n\n if let Some(name) = name {\n\n let ios_set = IOS_SET.read().unwrap();\n\n let v = ios_set.get(name).ok_or_else(|| \"No such id\".to_string())?;\n\n v.toggle_files_recording(switch);\n\n Ok(())\n\n } else {\n\n Err(\"Invalid id passed!\".to_string())\n\n }\n\n}\n\n\n", "file_path": "rafs/src/io_stats.rs", "rank": 16, "score": 199608.7756235082 }, { "content": "// For compatibility reason, we use liblz4 version to compress/decompress directly\n\n// with data blocks so that we don't really care about lz4 header magic numbers like\n\n// as being done with all these rust lz4 implementations\n\npub fn compress(src: &[u8], algorithm: Algorithm) -> Result<(Cow<[u8]>, bool)> {\n\n let src_size = src.len();\n\n if src_size == 0 {\n\n return Ok((Cow::Borrowed(src), false));\n\n }\n\n\n\n let compressed = match algorithm {\n\n Algorithm::None => return Ok((Cow::Borrowed(src), false)),\n\n Algorithm::LZ4Block => lz4_compress(src)?,\n\n Algorithm::GZip => {\n\n let dst: Vec<u8> = Vec::new();\n\n let mut gz = GzEncoder::new(dst, Compression::default());\n\n gz.write_all(src)?;\n\n gz.finish()?\n\n }\n\n };\n\n\n\n // Abandon compressed data when compression ratio greater than COMPRESSION_MINIMUM_RATIO\n\n if (COMPRESSION_MINIMUM_RATIO == 100 && compressed.len() >= src_size)\n\n || ((100 * compressed.len() / src_size) >= COMPRESSION_MINIMUM_RATIO)\n\n {\n\n return Ok((Cow::Borrowed(src), false));\n\n }\n\n Ok((Cow::Owned(compressed), true))\n\n}\n\n\n", "file_path": "rafs/src/storage/compress/mod.rs", "rank": 17, "score": 197596.9648745949 }, { "content": "/// Parse a 'buf' to xattr name list.\n\npub fn parse_xattr_names(data: &[u8], size: usize) -> Result<Vec<XattrName>> {\n\n let mut result = Vec::new();\n\n\n\n parse_xattr(data, size, |name, _| {\n\n result.push(name.as_bytes().to_vec());\n\n true\n\n })?;\n\n\n\n Ok(result)\n\n}\n\n\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 18, "score": 197230.01390168467 }, { "content": "// Rafs blob backend upload API\n\npub trait BlobBackendUploader {\n\n fn upload(\n\n &self,\n\n blob_id: &str,\n\n blob_path: &Path,\n\n callback: fn((usize, usize)),\n\n ) -> Result<usize>;\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/mod.rs", "rank": 19, "score": 194562.58900698723 }, { "content": "/// Parse a 'buf' to xattr pair then callback.\n\npub fn parse_xattr<F>(data: &[u8], size: usize, mut cb: F) -> Result<()>\n\nwhere\n\n F: FnMut(&OsStr, XattrValue) -> bool,\n\n{\n\n let mut i: usize = 0;\n\n let mut rest_data = &data[0..size];\n\n\n\n while i < size {\n\n let (pair_size, rest) = rest_data.split_at(size_of::<u32>());\n\n let pair_size = u32::from_le_bytes(\n\n pair_size\n\n .try_into()\n\n .map_err(|_| einval!(\"failed to parse xattr pair size\"))?,\n\n ) as usize;\n\n i += size_of::<u32>();\n\n\n\n let (pair, rest) = rest.split_at(pair_size);\n\n if let Some(pos) = pair.iter().position(|&c| c == 0) {\n\n let (name, value) = pair.split_at(pos);\n\n let name = OsStr::from_bytes(name);\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 20, "score": 190034.81595067738 }, { "content": "pub fn exec(cmd: &str, output: bool) -> Result<String> {\n\n info!(\"exec `{}`\", cmd);\n\n\n\n if output {\n\n let output = Command::new(\"sh\")\n\n .arg(\"-c\")\n\n .arg(cmd)\n\n .env(\"RUST_BACKTRACE\", \"1\")\n\n .output()?;\n\n\n\n if !output.status.success() {\n\n return Err(eother!(\"exit with non-zero status\"));\n\n }\n\n let stdout = std::str::from_utf8(&output.stdout).map_err(|e| einval!(e))?;\n\n let stderr = std::str::from_utf8(&output.stderr).map_err(|e| einval!(e))?;\n\n\n\n return Ok(stdout.to_string() + &stderr.to_string());\n\n }\n\n\n\n let mut child = Command::new(\"sh\")\n", "file_path": "utils/src/exec.rs", "rank": 21, "score": 185715.74461387942 }, { "content": "func getParentSnapshotID(s storage.Snapshot) string {\n\n\tif len(s.ParentIDs) == 0 {\n\n\t\treturn \"\"\n\n\t}\n\n\treturn s.ParentIDs[0]\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/fs.go", "rank": 22, "score": 184365.70431571285 }, { "content": "fn default_threads_count() -> usize {\n\n 8\n\n}\n\n\n", "file_path": "rafs/src/fs.rs", "rank": 23, "score": 179960.91073176695 }, { "content": "/// Decompress a source slice or file stream into destination slice, with provided compression algorithm.\n\n/// Use the file as decompress source if provided.\n\npub fn decompress(\n\n src: &[u8],\n\n src_file: Option<File>,\n\n dst: &mut [u8],\n\n algorithm: Algorithm,\n\n) -> Result<usize> {\n\n match algorithm {\n\n Algorithm::None => Ok(dst.len()),\n\n Algorithm::LZ4Block => lz4_decompress(src, dst),\n\n Algorithm::GZip => {\n\n if let Some(f) = src_file {\n\n let mut gz = GzDecoder::new(BufReader::new(f));\n\n gz.read_exact(dst)?;\n\n } else {\n\n let mut gz = GzDecoder::new(src);\n\n gz.read_exact(dst)?;\n\n };\n\n Ok(dst.len())\n\n }\n\n }\n", "file_path": "rafs/src/storage/compress/mod.rs", "rank": 24, "score": 179074.91630147383 }, { "content": "func TestValidate_ConfigFile_NotExists(t *testing.T) {\n\n\tvar cfg Config\n\n\terr := Validate(&command.Args{\n\n\t\tValidateSignature: false,\n\n\t\tRootDir: \"/root\",\n\n\t\tAddress: \"/root/rpc\",\n\n\t\tConfigPath: \"testdata/happypath/notexists.json\",\n\n\t\tLogLevel: \"debug\",\n\n\t}, &cfg)\n\n\tassert.NotNil(t, err)\n", "file_path": "contrib/nydus-snapshotter/cmd/containerd-nydus-grpc/app/snapshotter/validate_test.go", "rank": 25, "score": 176217.9158603609 }, { "content": "pub fn export_global_stats(name: &Option<String>) -> Result<String, String> {\n\n // With only one rafs instance, we allow caller to ask for an unknown ios name.\n\n let ios_set = IOS_SET.read().unwrap();\n\n\n\n match name {\n\n Some(k) => ios_set\n\n .get(k)\n\n .ok_or_else(|| \"No such id\".to_string())\n\n .map(|v| v.export_global_stats()),\n\n None => {\n\n if ios_set.len() == 1 {\n\n if let Some(ios) = ios_set.values().next() {\n\n return Ok(ios.export_global_stats());\n\n }\n\n }\n\n Err(\"No metrics counter was specified.\".to_string())\n\n }\n\n }\n\n}\n\n\n", "file_path": "rafs/src/io_stats.rs", "rank": 26, "score": 175138.35902135234 }, { "content": "pub fn new_rw_layer(\n\n config: Config,\n\n compressor: compress::Algorithm,\n\n digester: digest::Algorithm,\n\n) -> Result<Box<dyn RafsCache + Send + Sync>> {\n\n let backend = new_backend(config.backend)?;\n\n match config.cache.cache_type.as_str() {\n\n \"blobcache\" => Ok(\n\n Box::new(blobcache::new(config.cache, backend, compressor, digester)?)\n\n as Box<dyn RafsCache + Send + Sync>,\n\n ),\n\n _ => Ok(Box::new(dummycache::new(\n\n config.cache,\n\n backend,\n\n compressor,\n\n digester,\n\n )?) as Box<dyn RafsCache + Send + Sync>),\n\n }\n\n}\n", "file_path": "rafs/src/storage/factory.rs", "rank": 27, "score": 174557.56889616937 }, { "content": "fn is_chunk_continuous(prior: &RafsBio, cur: &RafsBio) -> bool {\n\n let prior_cki = &prior.chunkinfo;\n\n let cur_cki = &cur.chunkinfo;\n\n\n\n let prior_end = prior_cki.compress_offset() + prior_cki.compress_size() as u64;\n\n let cur_offset = cur_cki.compress_offset();\n\n\n\n if prior_end == cur_offset && prior.blob_id == cur.blob_id {\n\n return true;\n\n }\n\n\n\n false\n\n}\n\n\n", "file_path": "rafs/src/storage/cache/mod.rs", "rank": 28, "score": 173749.96664437797 }, { "content": "pub fn readv(fd: RawFd, bufs: &[VolatileSlice], offset: u64, max_size: usize) -> Result<usize> {\n\n if bufs.is_empty() {\n\n return Ok(0);\n\n }\n\n\n\n let mut size: usize = 0;\n\n let mut iovecs: Vec<IoVec<&mut [u8]>> = Vec::new();\n\n\n\n for buf in bufs {\n\n let mut exceed = false;\n\n let len = if size + buf.len() > max_size {\n\n exceed = true;\n\n max_size - size\n\n } else {\n\n buf.len()\n\n };\n\n size += len;\n\n let iov = IoVec::from_mut_slice(unsafe { from_raw_parts_mut(buf.as_ptr(), len) });\n\n iovecs.push(iov);\n\n if exceed {\n", "file_path": "rafs/src/storage/utils.rs", "rank": 29, "score": 171214.01127006882 }, { "content": "\tParentBootstrapPath string\n", "file_path": "contrib/nydusify/nydus/builder.go", "rank": 30, "score": 170459.62159856234 }, { "content": "#[test]\n\nfn integration_test_init() -> Result<()> {\n\n stderrlog::new()\n\n .quiet(false)\n\n .timestamp(stderrlog::Timestamp::Second)\n\n .verbosity(log::LevelFilter::Trace as usize - 1)\n\n .init()\n\n .map_err(|e| eother!(e))\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 31, "score": 168802.19849764026 }, { "content": "#[test]\n\nfn integration_test_directory_6() -> Result<()> {\n\n test(\"none\", false, true, \"cached\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 32, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_5() -> Result<()> {\n\n test(\"gzip\", true, true, \"cached\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 33, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_3() -> Result<()> {\n\n test(\"gzip\", false, false, \"direct\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 34, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_7() -> Result<()> {\n\n test(\"lz4_block\", false, true, \"cached\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 35, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_4() -> Result<()> {\n\n test(\"none\", true, false, \"direct\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 36, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_1() -> Result<()> {\n\n test(\"lz4_block\", true, false, \"direct\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 37, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_8() -> Result<()> {\n\n test(\"lz4_block\", true, true, \"cached\")\n\n}\n\n\n\nconst COMPAT_BOOTSTRAPS: &'static [&'static str] = &[\n\n \"blake3-lz4_block-non_repeatable\",\n\n \"sha256-nocompress-repeatable\",\n\n];\n\n\n", "file_path": "tests/smoke.rs", "rank": 38, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_directory_2() -> Result<()> {\n\n test(\"lz4_block\", false, false, \"direct\")\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 39, "score": 168754.25935975765 }, { "content": "#[test]\n\nfn integration_test_stargz() -> Result<()> {\n\n info!(\"\\n\\n==================== testing run: stargz test\");\n\n\n\n let tmp_dir = TempDir::new().map_err(|e| eother!(e))?;\n\n let work_dir = tmp_dir.as_path().to_path_buf();\n\n\n\n let _ = exec(\n\n format!(\"cp -a tests/texture/stargz/* {:?}\", work_dir).as_str(),\n\n false,\n\n )?;\n\n\n\n let mut builder = builder::new(&work_dir);\n\n\n\n builder.build_stargz_lower()?;\n\n builder.build_stargz_upper()?;\n\n\n\n let nydusd = nydusd::new(\n\n &work_dir,\n\n true,\n\n true,\n", "file_path": "tests/smoke.rs", "rank": 40, "score": 168472.44127029323 }, { "content": "/// A customized buf allocator that avoids zeroing\n\npub fn alloc_buf(size: usize) -> Vec<u8> {\n\n let mut buf = Vec::with_capacity(size);\n\n unsafe { buf.set_len(size) };\n\n buf\n\n}\n\n\n", "file_path": "rafs/src/storage/utils.rs", "rank": 41, "score": 166481.2928061874 }, { "content": "pub fn respond(resp: Response) -> Result<Response> {\n\n if is_success_status(resp.status()) {\n\n return Ok(resp);\n\n }\n\n let message = resp.text().map_err(|e| epipe!(e))?;\n\n Err(eio!(message))\n\n}\n\n\n\nimpl Request {\n\n fn build_client(proxy: &str, config: &CommonConfig) -> Result<Client> {\n\n let connect_timeout = if config.connect_timeout != 0 {\n\n Some(Duration::from_secs(config.connect_timeout))\n\n } else {\n\n None\n\n };\n\n let timeout = if config.timeout != 0 {\n\n Some(Duration::from_secs(config.timeout))\n\n } else {\n\n None\n\n };\n", "file_path": "rafs/src/storage/backend/request.rs", "rank": 42, "score": 165916.70122673444 }, { "content": "\tparentBootstrapPath string\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 43, "score": 165873.77656038362 }, { "content": "\tBootstrapFileNameInLayer = \"image.boot\"\n", "file_path": "contrib/nydusify/registry/registry.go", "rank": 44, "score": 165772.43744237965 }, { "content": "func (build *BuildFlow) getLatestBlobPath() (string, error) {\n\n\tblobs, err := ioutil.ReadDir(build.blobsDir)\n\n\tif err != nil {\n\n\t\treturn \"\", err\n\n\t}\n\n\n\n\tfor _, blobPath := range blobs {\n\n\t\tblobID := blobPath.Name()\n\n\t\texist := false\n\n\t\tfor _, existBlobID := range build.blobIDs {\n\n\t\t\tif existBlobID == blobID {\n\n\t\t\t\texist = true\n\n\t\t\t\tbreak\n\n\t\t\t}\n\n\t\t}\n\n\t\tif !exist {\n\n\t\t\tbuild.blobIDs = append(build.blobIDs, blobID)\n\n\t\t\treturn filepath.Join(build.blobsDir, blobID), nil\n\n\t\t}\n\n\t}\n\n\n\n\treturn \"\", nil\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 45, "score": 165466.30864640215 }, { "content": "/// Rafs blob backend API\n\npub trait BlobBackend {\n\n /// prefetch blob if supported\n\n /// TODO: Now `blob_readahead_offset` is type of `u32`. Better that we can change\n\n /// it to u64 someday.\n\n fn prefetch_blob(\n\n &self,\n\n _blob_id: &str,\n\n _blob_readahead_offset: u32,\n\n _blob_readahead_size: u32,\n\n ) -> Result<()> {\n\n Ok(())\n\n }\n\n\n\n #[inline]\n\n fn retry_limit(&self) -> u8 {\n\n 0\n\n }\n\n\n\n /// Get whole blob size\n\n fn blob_size(&self, blob_id: &str) -> Result<u64>;\n", "file_path": "rafs/src/storage/backend/mod.rs", "rank": 46, "score": 161838.9244359283 }, { "content": "/// Parse a `buf` to utf-8 string.\n\npub fn parse_string(buf: &[u8]) -> Result<(&str, &str)> {\n\n std::str::from_utf8(buf)\n\n .map(|origin| {\n\n if let Some(pos) = origin.find('\\0') {\n\n origin.split_at(pos)\n\n } else {\n\n (origin, \"\")\n\n }\n\n })\n\n .map_err(|e| einval!(format!(\"failed in parsing string, {:?}\", e)))\n\n}\n\n\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 47, "score": 160331.73607680545 }, { "content": "type Config struct {\n\n\tAddress string\n\n\tConvertVpcRegistry bool\n\n\tDaemonCfg nydus.DaemonConfig\n\n\tPublicKeyFile string\n\n\tRootDir string\n\n\tValidateSignature bool\n\n\tNydusdBinaryPath string\n\n\tNydusImageBinaryPath string\n\n\tSharedDaemon bool\n", "file_path": "contrib/nydus-snapshotter/cmd/containerd-nydus-grpc/app/snapshotter/validate.go", "rank": 48, "score": 158805.4694814616 }, { "content": "/// A customized readahead function to ask kernel to fault in all pages from offset to end.\n\n///\n\n/// Call libc::readahead on every 128KB range because otherwise readahead stops at kernel bdi\n\n/// readahead size which is 128KB by default.\n\npub fn readahead(fd: libc::c_int, mut offset: u64, end: u64) {\n\n let mut count;\n\n offset = round_down_4k(offset);\n\n loop {\n\n if offset >= end {\n\n break;\n\n }\n\n // Kernel default 128KB readahead size\n\n count = std::cmp::min(128 << 10, end - offset);\n\n unsafe { libc::readahead(fd, offset as i64, count as usize) };\n\n offset += count;\n\n }\n\n}\n\n\n", "file_path": "rafs/src/storage/utils.rs", "rank": 49, "score": 157760.28315486372 }, { "content": "pub fn new<'a>(work_dir: &'a PathBuf) -> Builder<'a> {\n\n Builder { work_dir }\n\n}\n\n\n\nimpl<'a> Builder<'a> {\n\n fn create_dir(&mut self, path: &PathBuf) -> Result<()> {\n\n fs::create_dir_all(path)?;\n\n Ok(())\n\n }\n\n\n\n fn create_file(&mut self, path: &PathBuf, data: &[u8]) -> Result<()> {\n\n File::create(path)?.write_all(data)?;\n\n Ok(())\n\n }\n\n\n\n fn copy_file(&mut self, src: &PathBuf, dst: &PathBuf) -> Result<u64> {\n\n fs::copy(src, dst)\n\n }\n\n\n\n fn create_symlink(&mut self, src: &PathBuf, dst: &PathBuf) -> Result<()> {\n", "file_path": "tests/builder.rs", "rank": 50, "score": 157002.34503684577 }, { "content": "type AccessLogEntry = (u64, u32, u32);\n\n\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 51, "score": 156033.6824111396 }, { "content": "type FilesStatsCounters = RwLock<Vec<Arc<Option<InodeIOStats>>>>;\n\n\n\n/// Block size separated counters.\n\n/// 1K; 4K; 16K; 64K, 128K.\n\nconst BLOCK_READ_COUNT_MAX: usize = 5;\n\n\n\n/// <=200us, <=500us, <=1ms, <=20ms, <=50ms, <=100ms, <=500ms, >500ms\n\nconst READ_LATENCY_RANGE_MAX: usize = 8;\n\n\n\nlazy_static! {\n\n pub static ref IOS_SET: RwLock<HashMap<String, Arc<GlobalIOStats>>> = Default::default();\n\n}\n\n\n\n#[derive(Default, Debug, Serialize, Deserialize)]\n\npub struct GlobalIOStats {\n\n // Whether to enable each file accounting switch.\n\n // As fop accounting might consume much memory space, it is disabled by default.\n\n // But global fop accounting is always working within each Rafs.\n\n files_account_enabled: AtomicBool,\n\n access_pattern_enabled: AtomicBool,\n", "file_path": "rafs/src/io_stats.rs", "rank": 52, "score": 153800.78350014947 }, { "content": "#[inline]\n\npub fn align_to_rafs(size: usize) -> usize {\n\n if size & (RAFS_ALIGNMENT - 1) == 0 {\n\n return size;\n\n }\n\n size + (RAFS_ALIGNMENT - (size & (RAFS_ALIGNMENT - 1)))\n\n}\n\n\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 53, "score": 150448.11027520744 }, { "content": "#[derive(Clone, Deserialize)]\n\nstruct LocalFsConfig {\n\n #[serde(default)]\n\n readahead: bool,\n\n #[serde(default = \"default_readahead_sec\")]\n\n readahead_sec: u32,\n\n #[serde(default)]\n\n blob_file: String,\n\n #[serde(default)]\n\n dir: String,\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 54, "score": 150211.57956236947 }, { "content": "func (layer *Layer) isCompressedType() bool {\n\n\treturn (strings.HasSuffix(string(layer.mediaType), \"+gzip\") ||\n\n\t\tstrings.HasSuffix(string(layer.mediaType), \".gzip\"))\n", "file_path": "contrib/nydusify/registry/layer.go", "rank": 55, "score": 147290.7474407805 }, { "content": "type digest string\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/digest.go", "rank": 56, "score": 146828.65017652622 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage stargz\n\n\n\nimport \"strings\"\n\n\n\ntype digest string\n\n\n\nfunc (d digest) String() string {\n\n\treturn string(d)\n\n}\n\n\n\nfunc (d digest) Sha256() string {\n\n\tpair := strings.Split(string(d), \":\")\n\n\treturn pair[1]\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/digest.go", "rank": 57, "score": 146725.43930082055 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage stargz\n\n\n\nimport (\n\n\t\"errors\"\n\n\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/meta\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/nydus\"\n\n)\n\n\n\nfunc WithMeta(root string) NewFSOpt {\n\n\treturn func(d *filesystem) error {\n\n\t\tif root == \"\" {\n\n\t\t\treturn errors.New(\"rootDir is required\")\n\n\t\t}\n\n\t\td.FileSystemMeta = meta.FileSystemMeta{\n\n\t\t\tRootDir: root,\n\n\t\t}\n\n\t\treturn nil\n\n\t}\n\n}\n\n\n\nfunc WithNydusdBinaryPath(p string) NewFSOpt {\n\n\treturn func(d *filesystem) error {\n\n\t\tif p == \"\" {\n\n\t\t\treturn errors.New(\"nydusd binary path is required\")\n\n\t\t}\n\n\t\td.nydusdBinaryPath = p\n\n\t\treturn nil\n\n\t}\n\n}\n\n\n\nfunc WithNydusImageBinaryPath(p string) NewFSOpt {\n\n\treturn func(d *filesystem) error {\n\n\t\tif p == \"\" {\n\n\t\t\treturn errors.New(\"nydus image binary path is required\")\n\n\t\t}\n\n\t\td.nydusdImageBinaryPath = p\n\n\t\treturn nil\n\n\t}\n\n}\n\n\n\nfunc WithDaemonConfig(cfg nydus.DaemonConfig) NewFSOpt {\n\n\treturn func(d *filesystem) error {\n\n\t\tif (nydus.DaemonConfig{}) == cfg {\n\n\t\t\treturn errors.New(\"daemon config is empty\")\n\n\t\t}\n\n\t\td.daemonCfg = cfg\n\n\t\treturn nil\n\n\t}\n\n}\n\n\n\ntype NewFSOpt func(d *filesystem) error\n\n\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/config.go", "rank": 58, "score": 146562.74593245258 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage stargz\n\n\n\nimport (\n\n\t\"context\"\n\n\t\"fmt\"\n\n\t\"io\"\n\n\t\"os\"\n\n\t\"os/exec\"\n\n\t\"path/filepath\"\n\n\t\"time\"\n\n\n\n\t\"github.com/containerd/containerd/log\"\n\n\t\"github.com/containerd/containerd/snapshots/storage\"\n\n\t\"github.com/pkg/errors\"\n\n\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/auth\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/daemon\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/errdefs\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/meta\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/nydus\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/label\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/process\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/utils/retry\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/snapshot\"\n\n)\n\n\n\ntype filesystem struct {\n\n\tmeta.FileSystemMeta\n\n\tmanager *process.Manager\n\n\tdaemonCfg nydus.DaemonConfig\n\n\tresolver *Resolver\n\n\tvpcRegistry bool\n\n\tnydusdBinaryPath string\n\n\tnydusdImageBinaryPath string\n\n}\n\n\n\nfunc NewFileSystem(opt ...NewFSOpt) (snapshot.FileSystem, error) {\n\n\tvar fs filesystem\n\n\tfor _, o := range opt {\n\n\t\terr := o(&fs)\n\n\t\tif err != nil {\n\n\t\t\treturn nil, err\n\n\t\t}\n\n\t}\n\n\tfs.resolver = NewResolver()\n\n\tfs.manager = process.NewManager(process.Opt{\n\n\t\tNydusdBinaryPath: fs.nydusdBinaryPath,\n\n\t})\n\n\treturn &fs, nil\n\n}\n\n\n\nfunc parseLabels(labels map[string]string) (rRef, rDigest string) {\n\n\tif ref, ok := labels[label.ImageRef]; ok {\n\n\t\trRef = ref\n\n\t}\n\n\tif layerDigest, ok := labels[label.CRIDigest]; ok {\n\n\t\trDigest = layerDigest\n\n\t}\n\n\treturn\n\n}\n\n\n\nfunc (f *filesystem) PrepareLayer(ctx context.Context, s storage.Snapshot, labels map[string]string) error {\n\n\tstart := time.Now()\n\n\tdefer func() {\n\n\t\tduration := time.Since(start)\n\n\t\tlog.G(ctx).Infof(\"total stargz prepare layer duration %d\", duration.Milliseconds())\n\n\t}()\n\n\tref, layerDigest := parseLabels(labels)\n\n\tif ref == \"\" || layerDigest == \"\" {\n\n\t\treturn fmt.Errorf(\"can not find ref and digest from label %+v\", labels)\n\n\t}\n\n\tkeychain, err := auth.FromLabels(labels)\n\n\tif err != nil {\n\n\t\treturn errors.Wrap(err, \"failed to find image pull auth info from labels\")\n\n\t}\n\n\tblob, err := f.resolver.GetBlob(ref, layerDigest, keychain)\n\n\tif err != nil {\n\n\t\treturn errors.Wrapf(err, \"failed to get blob from ref %s, digest %s\", ref, layerDigest)\n\n\t}\n\n\tr, err := blob.ReadToc()\n\n\tif err != nil {\n\n\t\treturn errors.Wrapf(err, \"failed to read toc from ref %s, digest %s\", ref, layerDigest)\n\n\t}\n\n\tstarGzToc, err := os.OpenFile(filepath.Join(f.UpperPath(s.ID), stargzToc), os.O_CREATE|os.O_RDWR, 0755)\n\n\tif err != nil {\n\n\t\treturn errors.Wrap(err, \"failed to create stargz index\")\n\n\t}\n\n\t_, err = io.Copy(starGzToc, r)\n\n\tif err != nil {\n\n\t\treturn errors.Wrap(err, \"failed to save stargz index\")\n\n\t}\n\n\toptions := []string{\n\n\t\t\"create\",\n\n\t\t\"--source-type\", \"stargz_index\",\n\n\t\t\"--bootstrap\", filepath.Join(f.UpperPath(s.ID), \"image.boot\"),\n\n\t\t\"--blob-id\", digest(layerDigest).Sha256(),\n\n\t\t\"--repeatable\",\n\n\t\t\"--disable-check\",\n\n\t}\n\n\tif getParentSnapshotID(s) != \"\" {\n\n\t\tparentBootstrap := filepath.Join(f.UpperPath(getParentSnapshotID(s)), \"image.boot\")\n\n\t\tif _, err := os.Stat(parentBootstrap); err != nil {\n\n\t\t\treturn fmt.Errorf(\"failed to find parentBootstrap from %s\", parentBootstrap)\n\n\t\t}\n\n\t\toptions = append(options,\n\n\t\t\t\"--parent-bootstrap\", parentBootstrap)\n\n\t}\n\n\toptions = append(options, filepath.Join(f.UpperPath(s.ID), stargzToc))\n\n\tlog.G(ctx).Infof(\"nydus image command %v\", options)\n\n\tcmd := exec.Command(f.nydusdImageBinaryPath, options...)\n\n\tcmd.Stderr = os.Stderr\n\n\tcmd.Stdout = os.Stdout\n\n\treturn cmd.Run()\n\n}\n\n\n\nfunc getParentSnapshotID(s storage.Snapshot) string {\n\n\tif len(s.ParentIDs) == 0 {\n\n\t\treturn \"\"\n\n\t}\n\n\treturn s.ParentIDs[0]\n\n}\n\n\n\nfunc (f *filesystem) Support(ctx context.Context, labels map[string]string) bool {\n\n\tref, layerDigest := parseLabels(labels)\n\n\tif ref == \"\" || layerDigest == \"\" {\n\n\t\treturn false\n\n\t}\n\n\tlog.G(ctx).Infof(\"image ref %s digest %s\", ref, layerDigest)\n\n\tkeychain, err := auth.FromLabels(labels)\n\n\tif err != nil {\n\n\t\treturn false\n\n\t}\n\n\tblob, err := f.resolver.GetBlob(ref, layerDigest, keychain)\n\n\tif err != nil {\n\n\t\treturn false\n\n\t}\n\n\toff, err := blob.getTocOffset()\n\n\treturn err == nil && off > 0\n\n}\n\n\n\nfunc (f *filesystem) createNewDaemon(snapshotID string, imageID string) (*daemon.Daemon, error) {\n\n\td, err := daemon.NewDaemon(\n\n\t\tdaemon.WithSnapshotID(snapshotID),\n\n\t\tdaemon.WithSocketDir(f.SocketRoot()),\n\n\t\tdaemon.WithConfigDir(f.ConfigRoot()),\n\n\t\tdaemon.WithSnapshotDir(f.SnapshotRoot()),\n\n\t\tdaemon.WithLogDir(f.LogRoot()),\n\n\t\tdaemon.WithCacheDir(f.CacheRoot()),\n\n\t\tdaemon.WithImageID(imageID),\n\n\t)\n\n\tif err != nil {\n\n\t\treturn nil, err\n\n\t}\n\n\terr = f.manager.NewDaemon(d)\n\n\tif err != nil {\n\n\t\treturn nil, err\n\n\t}\n\n\treturn d, nil\n\n}\n\n\n\nfunc (f *filesystem) Mount(ctx context.Context, snapshotID string, labels map[string]string) error {\n\n\timageID, ok := labels[label.ImageRef]\n\n\tif !ok {\n\n\t\treturn fmt.Errorf(\"failed to find image ref of snapshot %s, labels %v\", snapshotID, labels)\n\n\t}\n\n\td, err := f.createNewDaemon(snapshotID, imageID)\n\n\t// if daemon already exists for snapshotID, just return\n\n\tif err != nil {\n\n\t\tif errdefs.IsAlreadyExists(err) {\n\n\t\t\treturn nil\n\n\t\t}\n\n\t\treturn err\n\n\t}\n\n\tdefer func() {\n\n\t\tif err != nil {\n\n\t\t\t_ = f.manager.DestroyDaemon(d)\n\n\t\t}\n\n\t}()\n\n\terr = f.mount(d, labels)\n\n\tif err != nil {\n\n\t\treturn errors.Wrapf(err, \"failed to start daemon %s\", d.ID)\n\n\t}\n\n\treturn nil\n\n}\n\n\n\nfunc (f *filesystem) mount(d *daemon.Daemon, labels map[string]string) error {\n\n\terr := f.generateDaemonConfig(d, labels)\n\n\tif err != nil {\n\n\t\treturn err\n\n\t}\n\n\treturn f.manager.StartDaemon(d)\n\n}\n\n\n\nfunc (f *filesystem) generateDaemonConfig(d *daemon.Daemon, labels map[string]string) error {\n\n\tcfg, err := nydus.NewDaemonConfig(f.daemonCfg, d, f.vpcRegistry, labels)\n\n\tif err != nil {\n\n\t\treturn errors.Wrapf(err, \"failed to generate daemon config for daemon %s\", d.ID)\n\n\t}\n\n\tcfg.Device.Cache.Compressed = true\n\n\tcfg.DigestValidate = false\n\n\treturn nydus.SaveConfig(cfg, d.ConfigFile())\n\n}\n\n\n\nfunc (f *filesystem) WaitUntilReady(ctx context.Context, snapshotID string) error {\n\n\ts, err := f.manager.GetBySnapshotID(snapshotID)\n\n\tif err != nil {\n\n\t\treturn err\n\n\t}\n\n\treturn retry.Do(func() error {\n\n\t\tinfo, err := s.CheckStatus()\n\n\t\tif err != nil {\n\n\t\t\treturn err\n\n\t\t}\n\n\t\tlog.G(ctx).Infof(\"daemon %s snapshotID %s info %v\", s.ID, snapshotID, info)\n\n\t\tif info.State != \"Running\" {\n\n\t\t\treturn errors.Wrap(err, fmt.Sprintf(\"daemon %s snapshotID %s is not ready\", s.ID, snapshotID))\n\n\t\t}\n\n\t\treturn nil\n\n\t},\n\n\t\tretry.Attempts(3),\n\n\t\tretry.LastErrorOnly(true),\n\n\t\tretry.Delay(100*time.Millisecond),\n\n\t)\n\n}\n\n\n\nfunc (f *filesystem) Umount(ctx context.Context, mountPoint string) error {\n\n\tid := filepath.Base(mountPoint)\n\n\tlog.G(ctx).Infof(\"umount nydus daemon of id %s, mountpoint %s\", id, mountPoint)\n\n\treturn f.manager.DestroyBySnapshotID(id)\n\n}\n\n\n\nfunc (f *filesystem) Cleanup(ctx context.Context) error {\n\n\tfor _, d := range f.manager.ListDaemons() {\n\n\t\terr := f.Umount(ctx, filepath.Dir(d.MountPoint()))\n\n\t\tif err != nil {\n\n\t\t\tlog.G(ctx).Infof(\"failed to umount %s err %+v\", d.MountPoint(), err)\n\n\t\t}\n\n\t}\n\n\treturn nil\n\n}\n\n\n\nfunc (f *filesystem) MountPoint(snapshotID string) (string, error) {\n\n\tif d, err := f.manager.GetBySnapshotID(snapshotID); err == nil {\n\n\t\treturn d.MountPoint(), nil\n\n\t}\n\n\treturn \"\", fmt.Errorf(\"failed to find mountpoint of snapshot %s\", snapshotID)\n\n}\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/fs.go", "rank": 59, "score": 146411.4856068004 }, { "content": "\tdefaultLogLevel = logrus.InfoLevel\n", "file_path": "contrib/nydus-snapshotter/cmd/containerd-nydus-grpc/pkg/command/flags.go", "rank": 60, "score": 146085.24682813502 }, { "content": "// Access entries can be either mmapped or Vec-allocated.\n\n// Use mmap for read case and Vec-allocated for write case.\n\nstruct LocalFsAccessLog {\n\n log_path: String, // log file path\n\n log_fd: RawFd, // log file fd\n\n log_base: *const u8, // mmaped access log base\n\n log_size: usize, // log file size\n\n blob_fd: RawFd, // blob fd for readahead\n\n blob_size: usize, // blob file size\n\n records: ManuallyDrop<Mutex<Vec<AccessLogEntry>>>, // access records\n\n}\n\n\n\nunsafe impl Send for LocalFsAccessLog {}\n\n\n\nunsafe impl Sync for LocalFsAccessLog {}\n\n\n\nimpl LocalFsAccessLog {\n\n fn new() -> LocalFsAccessLog {\n\n LocalFsAccessLog {\n\n log_path: \"\".to_string(),\n\n log_fd: -1,\n\n log_base: std::ptr::null(),\n", "file_path": "rafs/src/storage/backend/localfs.rs", "rank": 61, "score": 146009.89859362887 }, { "content": "type DigestData = [u8; RAFS_DIGEST_LENGTH];\n\n\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\n\npub enum Algorithm {\n\n Blake3,\n\n Sha256,\n\n}\n\n\n\nimpl fmt::Display for Algorithm {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\nimpl FromStr for Algorithm {\n\n type Err = Error;\n\n\n\n fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {\n\n match s {\n\n \"blake3\" => Ok(Self::Blake3),\n\n \"sha256\" => Ok(Self::Sha256),\n\n _ => Err(einval!(\"digest algorithm should be blake3 or sha256\")),\n\n }\n\n }\n\n}\n\n\n", "file_path": "rafs/src/metadata/digest.rs", "rank": 62, "score": 145711.1221628487 }, { "content": "func main() {\n\n\tflags := command.NewFlags()\n\n\tapp := &cli.App{\n\n\t\tName: \"containerd-nydus-grpc\",\n\n\t\tUsage: \"nydus containerd proxy snapshotter plugin\",\n\n\t\tVersion: Version,\n\n\t\tFlags: flags.F,\n\n\t\tAction: func(c *cli.Context) error {\n\n\t\t\tctx := logging.WithContext()\n\n\t\t\tif err := logging.SetUp(flags.Args.LogLevel); err != nil {\n\n\t\t\t\treturn errors.Wrap(err, \"failed to prepare logger\")\n\n\t\t\t}\n\n\n\n\t\t\tvar cfg snapshotter.Config\n\n\t\t\tif err := snapshotter.Validate(flags.Args, &cfg); err != nil {\n\n\t\t\t\treturn errors.Wrap(err, \"invalid argument\")\n\n\t\t\t}\n\n\t\t\treturn snapshotter.Start(ctx, cfg)\n\n\t\t},\n\n\t}\n\n\tif err := app.Run(os.Args); err != nil {\n\n\t\tif errdefs.IsConnectionClosed(err) {\n\n\t\t\tlog.L.Info(\"snapshotter exited\")\n\n\t\t\treturn\n\n\t\t}\n\n\t\tlog.L.WithError(err).Fatal(\"failed to start nydus snapshotter\")\n\n\t}\n", "file_path": "contrib/nydus-snapshotter/cmd/containerd-nydus-grpc/main.go", "rank": 63, "score": 144469.2683024465 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage stargz\n\n\n\nimport \"testing\"\n\n\n\nfunc Test_digest_Sha256(t *testing.T) {\n\n\ttests := []struct {\n\n\t\tname string\n\n\t\td digest\n\n\t\twant string\n\n\t}{\n\n\t\t{\n\n\t\t\tname: \"testdigest\",\n\n\t\t\td: digest(\"sha256:12345\"),\n\n\t\t\twant: \"12345\",\n\n\t\t},\n\n\n\n\t}\n\n\tfor _, tt := range tests {\n\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\tif got := tt.d.Sha256(); got != tt.want {\n\n\t\t\t\tt.Errorf(\"Sha256() = %v, want %v\", got, tt.want)\n\n\t\t\t}\n\n\t\t})\n\n\t}\n\n}\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/digest_test.go", "rank": 64, "score": 144222.77082749008 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage stargz\n\n\n\nimport (\n\n\t\"encoding/json\"\n\n\t\"fmt\"\n\n\t\"io/ioutil\"\n\n\t\"os\"\n\n\t\"path/filepath\"\n\n\t\"testing\"\n\n\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/meta\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/filesystem/nydus\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/label\"\n\n\t\"gitlab.alipay-inc.com/antsys/nydus-snapshotter/pkg/process\"\n\n)\n\n\n\nfunc ensureExists(path string) error {\n\n\t_, err := os.Stat(path)\n\n\tif err != nil {\n\n\t\treturn fmt.Errorf(\"%s not exists\", path)\n\n\t}\n\n\treturn nil\n\n}\n\n\n\nfunc Test_filesystem_createNewDaemon(t *testing.T) {\n\n\tsnapshotRoot := \"testdata/snapshot\"\n\n\terr := os.MkdirAll(snapshotRoot, 0755)\n\n\trequire.Nil(t, err)\n\n\tdefer func() {\n\n\t\t_ = os.RemoveAll(snapshotRoot)\n\n\t}()\n\n\tf := filesystem{\n\n\t\tFileSystemMeta: meta.FileSystemMeta{\n\n\t\t\tRootDir: snapshotRoot,\n\n\t\t},\n\n\t\tmanager: process.NewManager(process.Opt{\n\n\t\t\tNydusdBinaryPath: \"\",\n\n\t\t}),\n\n\t\tdaemonCfg: nydus.DaemonConfig{},\n\n\t\tresolver: nil,\n\n\t\tvpcRegistry: false,\n\n\t}\n\n\t_, err = f.createNewDaemon(\"1\", \"example.com/test/testimage:0.1\")\n\n\trequire.Nil(t, err)\n\n}\n\n\n\nfunc Test_filesystem_generateDaemonConfig(t *testing.T) {\n\n\tsnapshotRoot := \"testdata/snapshot\"\n\n\terr := os.MkdirAll(snapshotRoot, 0755)\n\n\trequire.Nil(t, err)\n\n\tdefer func() {\n\n\t\t_ = os.RemoveAll(snapshotRoot)\n\n\t}()\n\n\n\n\tcontent, err := ioutil.ReadFile(\"testdata/config/nydus.json\")\n\n\trequire.Nil(t, err)\n\n\tvar cfg nydus.DaemonConfig\n\n\terr = json.Unmarshal(content, &cfg)\n\n\trequire.Nil(t, err)\n\n\tf := filesystem{\n\n\t\tFileSystemMeta: meta.FileSystemMeta{\n\n\t\t\tRootDir: snapshotRoot,\n\n\t\t},\n\n\t\tmanager: process.NewManager(process.Opt{\n\n\t\t\tNydusdBinaryPath: \"\",\n\n\t\t}),\n\n\t\tdaemonCfg: cfg,\n\n\t\tresolver: nil,\n\n\t\tvpcRegistry: false,\n\n\t}\n\n\td, err := f.createNewDaemon(\"1\", \"example.com/test/testimage:0.1\")\n\n\terr = f.generateDaemonConfig(d, map[string]string{\n\n\t\tlabel.ImagePullUsername: \"mock\",\n\n\t\tlabel.ImagePullSecret: \"mock\",\n\n\t})\n\n\trequire.Nil(t, err)\n\n\tassert.Nil(t, ensureExists(filepath.Join(snapshotRoot, \"config\", d.ID, \"config.json\")))\n\n\tassert.Nil(t, ensureExists(filepath.Join(snapshotRoot, \"cache\")))\n\n\tassert.Nil(t, ensureExists(filepath.Join(snapshotRoot, \"logs\", d.ID)))\n\n\tassert.Nil(t, ensureExists(filepath.Join(snapshotRoot, \"socket\", d.ID)))\n\n}\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/fs_test.go", "rank": 65, "score": 143917.0701623283 }, { "content": "pub fn new(id: &str) -> Arc<GlobalIOStats> {\n\n let c = Arc::new(GlobalIOStats {\n\n id: id.to_string(),\n\n ..Default::default()\n\n });\n\n IOS_SET.write().unwrap().insert(id.to_string(), c.clone());\n\n c.init();\n\n c\n\n}\n\n\n", "file_path": "rafs/src/io_stats.rs", "rank": 66, "score": 143775.7274796678 }, { "content": "/// Check hash of data matches provided one\n\npub fn digest_check(data: &[u8], digest: &RafsDigest, digester: digest::Algorithm) -> bool {\n\n digest == &RafsDigest::from_buf(data, digester)\n\n}\n", "file_path": "rafs/src/storage/utils.rs", "rank": 67, "score": 143655.49960039268 }, { "content": "func main() {\n\n\tlogrus.SetFormatter(&logrus.TextFormatter{\n\n\t\tFullTimestamp: true,\n\n\t})\n\n\n\n\tapp := &cli.App{\n\n\t\tName: \"Nydusify\",\n\n\t\tUsage: \"Nydus image converter tool\",\n\n\t}\n\n\n\n\tapp.Commands = []*cli.Command{\n\n\t\t{\n\n\t\t\tName: \"convert\",\n\n\t\t\tUsage: \"Convert source image to nydus image\",\n\n\t\t\tFlags: []cli.Flag{\n\n\t\t\t\t&cli.StringFlag{Name: \"source\", Required: true, Usage: \"Source image reference\", EnvVars: []string{\"SOURCE\"}},\n\n\t\t\t\t&cli.StringFlag{Name: \"target\", Required: true, Usage: \"Target image reference\", EnvVars: []string{\"TARGET\"}},\n\n\n\n\t\t\t\t&cli.BoolFlag{Name: \"source-insecure\", Required: false, Usage: \"Allow http/insecure source registry communication\", EnvVars: []string{\"SOURCE_INSECURE\"}},\n\n\t\t\t\t&cli.BoolFlag{Name: \"target-insecure\", Required: false, Usage: \"Allow http/insecure target registry communication\", EnvVars: []string{\"TARGET_INSECURE\"}},\n\n\n\n\t\t\t\t&cli.StringFlag{Name: \"work-dir\", Value: \"./tmp\", Usage: \"Work directory path for image conversion\", EnvVars: []string{\"WORK_DIR\"}},\n\n\t\t\t\t&cli.StringFlag{Name: \"prefetch-dir\", Value: \"/\", Usage: \"Prefetch directory for nydus image, use absolute path of rootfs\", EnvVars: []string{\"PREFETCH_DIR\"}},\n\n\t\t\t\t&cli.StringFlag{Name: \"nydus-image\", Value: \"./nydus-image\", Usage: \"The nydus-image binary path\", EnvVars: []string{\"NYDUS_IMAGE\"}},\n\n\t\t\t\t&cli.StringFlag{Name: \"signature-key\", Value: \"\", Usage: \"Private key path for image signature\", EnvVars: []string{\"SIGNATURE_KEY\"}},\n\n\t\t\t\t&cli.BoolFlag{Name: \"multi-platform\", Value: false, Usage: \"Add manifest index (multiple platforms, OCI & Nydus) for target image\", EnvVars: []string{\"MULTI-PLATFORM\"}},\n\n\t\t\t\t&cli.BoolFlag{Name: \"silent\", Value: false, Usage: \"Disable to show conversion progress\", EnvVars: []string{\"SILENT\"}},\n\n\t\t\t},\n\n\t\t\tAction: func(c *cli.Context) error {\n\n\t\t\t\tconverter, err := converter.New(converter.Option{\n\n\t\t\t\t\tSource: c.String(\"source\"),\n\n\t\t\t\t\tTarget: c.String(\"target\"),\n\n\t\t\t\t\tSourceInsecure: c.Bool(\"source-insecure\"),\n\n\t\t\t\t\tTargetInsecure: c.Bool(\"target-insecure\"),\n\n\n\n\t\t\t\t\tWorkDir: c.String(\"work-dir\"),\n\n\t\t\t\t\tPrefetchDir: c.String(\"prefetch-dir\"),\n\n\t\t\t\t\tNydusImagePath: c.String(\"nydus-image\"),\n\n\t\t\t\t\tSignatureKeyPath: c.String(\"signature-key\"),\n\n\t\t\t\t\tMultiPlatform: c.Bool(\"multi-platform\"),\n\n\t\t\t\t\tSilent: c.Bool(\"silent\"),\n\n\t\t\t\t})\n\n\t\t\t\tif err != nil {\n\n\t\t\t\t\treturn err\n\n\t\t\t\t}\n\n\n\n\t\t\t\treturn converter.Convert()\n\n\t\t\t},\n\n\t\t},\n\n\t}\n\n\n\n\tif err := app.Run(os.Args); err != nil {\n\n\t\tlogrus.Fatal(err)\n\n\t}\n", "file_path": "contrib/nydusify/cmd/nydusify.go", "rank": 68, "score": 143624.39226355375 }, { "content": "\tname string\n", "file_path": "contrib/nydusify/registry/layer.go", "rank": 69, "score": 143595.81794473866 }, { "content": "func (job *LayerJob) SetSourceLayer(sourceLayer v1.Layer) {\n\n\tjob.SourceLayer = sourceLayer\n", "file_path": "contrib/nydusify/registry/layer_job.go", "rank": 70, "score": 143459.82235463022 }, { "content": "fn generate_merged_requests(\n\n bios: &mut [RafsBio],\n\n tx: &mut spmc::Sender<MergedBackendRequest>,\n\n merging_size: usize,\n\n) {\n\n bios.sort_by_key(|entry| entry.chunkinfo.compress_offset());\n\n let mut index: usize = 1;\n\n if bios.is_empty() {\n\n return;\n\n }\n\n let first_cki = &bios[0].chunkinfo;\n\n let mut mr = MergedBackendRequest::default();\n\n mr.merge_begin(Arc::clone(first_cki), &bios[0].blob_id);\n\n\n\n if bios.len() == 1 {\n\n tx.send(mr).unwrap();\n\n return;\n\n }\n\n\n\n loop {\n", "file_path": "rafs/src/storage/cache/mod.rs", "rank": 71, "score": 141383.23797303997 }, { "content": "\tbuilder *Builder\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 72, "score": 140622.2445618906 }, { "content": "func (build *BuildFlow) GetBootstrap() string {\n\n\treturn build.bootstrapPath\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 73, "score": 140506.88000021124 }, { "content": "func (d digest) Sha256() string {\n\n\tpair := strings.Split(string(d), \":\")\n\n\treturn pair[1]\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/digest.go", "rank": 74, "score": 140359.24272335178 }, { "content": "\tBootstrapPath string\n", "file_path": "contrib/nydusify/nydus/builder.go", "rank": 75, "score": 139403.08797268645 }, { "content": "\tBlobPath string\n", "file_path": "contrib/nydusify/nydus/builder.go", "rank": 76, "score": 139369.3661851312 }, { "content": "\tcompressedSize *int64\n", "file_path": "contrib/nydusify/registry/layer.go", "rank": 77, "score": 139342.74968928393 }, { "content": "\tcompressedDigest *v1.Hash\n", "file_path": "contrib/nydusify/registry/layer.go", "rank": 78, "score": 139317.4175527368 }, { "content": "\tsourcePath string\n", "file_path": "contrib/nydusify/registry/layer.go", "rank": 79, "score": 139283.1546033087 }, { "content": "\tBackendType string\n", "file_path": "contrib/nydusify/nydus/builder.go", "rank": 80, "score": 139042.3181985288 }, { "content": "\tBackendConfig string\n", "file_path": "contrib/nydusify/nydus/builder.go", "rank": 81, "score": 138861.88386950718 }, { "content": "\tbootstrapPath string\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 82, "score": 135551.7028197195 }, { "content": "\tbackendConfig string\n", "file_path": "contrib/nydusify/nydus/build_flow.go", "rank": 83, "score": 135025.51505063297 }, { "content": "type Blob struct {\n\n\tref string\n\n\tdigest string\n\n\tsr *io.SectionReader\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/resolver.go", "rank": 84, "score": 134891.01109703392 }, { "content": "\tdigest string\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/resolver.go", "rank": 85, "score": 134866.33265912655 }, { "content": "func Test_digest_Sha256(t *testing.T) {\n\n\ttests := []struct {\n\n\t\tname string\n\n\t\td digest\n\n\t\twant string\n\n\t}{\n\n\t\t{\n\n\t\t\tname: \"testdigest\",\n\n\t\t\td: digest(\"sha256:12345\"),\n\n\t\t\twant: \"12345\",\n\n\t\t},\n\n\n\n\t}\n\n\tfor _, tt := range tests {\n\n\t\tt.Run(tt.name, func(t *testing.T) {\n\n\t\t\tif got := tt.d.Sha256(); got != tt.want {\n\n\t\t\t\tt.Errorf(\"Sha256() = %v, want %v\", got, tt.want)\n\n\t\t\t}\n\n\t\t})\n\n\t}\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/digest_test.go", "rank": 86, "score": 134038.94280996377 }, { "content": "pub fn extract_query_part(req: &Request, key: &str) -> Option<String> {\n\n // Splicing req.uri with \"http:\" prefix might look weird, but since it depends on\n\n // crate `Url` to generate query_pairs HashMap, which is working on top of Url not Uri.\n\n // Better that we can add query part support to Micro-http in the future. But\n\n // right now, below way makes it easy to obtain query parts from uri.\n\n let http_prefix: String = String::from(\"http:\");\n\n let url = Url::parse((http_prefix + &req.uri().get_abs_path().to_string()).as_str()).unwrap();\n\n let v: Option<String> = None;\n\n for (k, v) in url.query_pairs().into_owned() {\n\n if k.as_str() != key.chars().as_str() {\n\n continue;\n\n } else {\n\n trace!(\"Got query part {:?}\", (k, &v));\n\n return Some(v);\n\n }\n\n }\n\n v\n\n}\n\n\n", "file_path": "api/src/http.rs", "rank": 87, "score": 133895.46819574377 }, { "content": "fn default_work_dir() -> String {\n\n \".\".to_string()\n\n}\n\n\n", "file_path": "rafs/src/storage/cache/blobcache.rs", "rank": 88, "score": 133295.2119987415 }, { "content": "func WithNydusImageBinaryPath(p string) NewFSOpt {\n\n\treturn func(d *filesystem) error {\n\n\t\tif p == \"\" {\n\n\t\t\treturn errors.New(\"nydus image binary path is required\")\n\n\t\t}\n\n\t\td.nydusdImageBinaryPath = p\n\n\t\treturn nil\n\n\t}\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/config.go", "rank": 89, "score": 132432.84256129796 }, { "content": "/*\n\n * Copyright (c) 2020. Ant Group. All rights reserved.\n\n *\n\n * SPDX-License-Identifier: Apache-2.0\n\n */\n\n\n\npackage main\n\n\n\nvar (\n\n\tVersion = \"development\"\n\n)\n", "file_path": "contrib/nydus-snapshotter/cmd/containerd-nydus-grpc/version.go", "rank": 90, "score": 132418.30474742167 }, { "content": "\tnydusdImageBinaryPath string\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/fs.go", "rank": 91, "score": 132292.91513618367 }, { "content": "type HmacSha1 = Hmac<Sha1>;\n\n\n\n#[derive(Debug)]\n\npub struct OSS {\n\n request: Arc<Request>,\n\n access_key_id: String,\n\n access_key_secret: String,\n\n scheme: String,\n\n endpoint: String,\n\n bucket_name: String,\n\n force_upload: bool,\n\n retry_limit: u8,\n\n}\n\n\n", "file_path": "rafs/src/storage/backend/oss.rs", "rank": 92, "score": 129883.36713489823 }, { "content": "pub fn bytes_to_os_str(buf: &[u8]) -> &OsStr {\n\n OsStr::from_bytes(buf)\n\n}\n\n\n", "file_path": "rafs/src/metadata/layout.rs", "rank": 93, "score": 129167.56640588492 }, { "content": "\tErrAlreadyExists = errors.New(\"already exists\")\n", "file_path": "contrib/nydus-snapshotter/pkg/errdefs/errors.go", "rank": 94, "score": 128592.85674962554 }, { "content": "func getSize(url string, tr http.RoundTripper) (int64, error) {\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\n\tdefer cancel()\n\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n\n\tif err != nil {\n\n\t\treturn 0, nil\n\n\t}\n\n\treq.Close = false\n\n\treq.Header.Set(\"Range\", \"bytes=0-0\")\n\n\tres, err := tr.RoundTrip(req)\n\n\tif err != nil {\n\n\t\treturn 0, err\n\n\t}\n\n\tdefer func() {\n\n\t\tio.Copy(ioutil.Discard, res.Body)\n\n\t\tres.Body.Close()\n\n\t}()\n\n\tif res.StatusCode/100 != 2 {\n\n\t\treturn 0, fmt.Errorf(\"failed to HEAD request with code %d\", res.StatusCode)\n\n\t}\n\n\tcontentRange := res.Header.Get(\"Content-Range\")\n\n\ttotalSize := strings.Split(contentRange, \"/\")[1]\n\n\treturn strconv.ParseInt(totalSize, 10, 64)\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/resolver.go", "rank": 95, "score": 128277.31428997157 }, { "content": "#[test]\n\nfn integration_test_compact() -> Result<()> {\n\n info!(\"\\n\\n==================== testing run: compact test\");\n\n\n\n let tmp_dir = TempDir::new().map_err(|e| eother!(e))?;\n\n let work_dir = tmp_dir.as_path().to_path_buf();\n\n let _ = exec(\n\n format!(\"cp -a tests/texture/repeatable/* {:?}\", work_dir).as_str(),\n\n false,\n\n )?;\n\n\n\n for mode in vec![\"direct\", \"cached\"].iter() {\n\n for bs in COMPAT_BOOTSTRAPS.iter() {\n\n check_compact(&work_dir, bs, mode)?;\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/smoke.rs", "rank": 96, "score": 128247.26752266771 }, { "content": "func GetSnapshotInfo(ctx context.Context, ms *storage.MetaStore, key string) (string, snapshots.Info, snapshots.Usage, error) {\n\n\tctx, t, err := ms.TransactionContext(ctx, false)\n\n\tif err != nil {\n\n\t\treturn \"\", snapshots.Info{}, snapshots.Usage{}, err\n\n\t}\n\n\tdefer t.Rollback()\n\n\tid, info, usage, err := storage.GetInfo(ctx, key)\n\n\tif err != nil {\n\n\t\treturn \"\", snapshots.Info{}, snapshots.Usage{}, err\n\n\t}\n\n\n\n\treturn id, info, usage, nil\n", "file_path": "contrib/nydus-snapshotter/pkg/snapshot/storage.go", "rank": 97, "score": 127707.19542468061 }, { "content": "func (r *Resolver) GetBlob(ref, digest string, keychain authn.Keychain) (*Blob, error) {\n\n\tstart := time.Now()\n\n\tdefer func() {\n\n\t\tduration := time.Since(start)\n\n\t\tlog.L.Infof(\"get blob duration %d\", duration.Milliseconds())\n\n\t}()\n\n\n\n\tsr, err := r.resolve(ref, digest, keychain)\n\n\tif err != nil {\n\n\t\treturn nil, err\n\n\t}\n\n\treturn &Blob{\n\n\t\tref: ref,\n\n\t\tdigest: digest,\n\n\t\tsr: sr,\n\n\t}, nil\n", "file_path": "contrib/nydus-snapshotter/pkg/filesystem/stargz/resolver.go", "rank": 98, "score": 124976.46097297041 }, { "content": "# Nydus Image Builder\n\n\n\n`nydus-image` tool converts a directory tree (usually an image layer) into two parts: `bootstrap` and `blob`:\n\n\n\n- `bootstrap` is a file presenting filesystem metadata information of the directory;\n\n- `blob` stores all files data in the directory;\n\n\n\n## Build Nydus Image From Directory Source\n\n\n\n```shell\n\nnydus-image create \\\n\n --bootstrap /path/to/bootstrap\n\n --backend-type localfs\n\n --backend-config '{\"dir\":\"/path/to/blobs\"}'\n\n /path/to/source/dir\n\n```\n\n\n\n## Use Different Storage Backend\n\n\n\nSome examples with backend config:\n\n\n\nLocalfs Backend:\n\n\n\n``` shell\n\n# Build blob file to specified file path\n\n--backend_type localfs --backend_config '{\"blob_file\":\"/path/to/blob\"}'\n\n# Build blob file to specified directory path\n\n--backend_type localfs --backend_config '{\"dir\":\"/path/to/blobs\"}'\n\n```\n\n\n\nOSS Backend:\n\n\n\n``` shell\n\n--backend_type localfs --backend_config '{\"endpoint\":\"region.aliyuncs.com\",\"access_key_id\":\"\",\"access_key_secret\":\"\",\"bucket_name\":\"\"}'\n\n```\n\n\n\nContainer Image Registry Backend:\n\n\n\n``` shell\n\n--backend_config '{\"scheme\":\"https\",\"host\":\"my-registry:5000\",\"repo\":\"test/repo\",\"auth\":\"<base64_encoded_auth>\"}'\n\n```\n\n\n\n## Layered Build Nydus Image\n\n\n\n`nydus-image` tool supports to build Nydus image from multiple layers of image:\n\n\n\n```shell\n\n# Build from lower layer\n\nnydus-image create \\\n\n --bootstrap /path/to/parent-bootstrap\n\n --backend-type localfs\n\n --backend-config '{\"dir\":\"/path/to/blobs\"}'\n\n /path/to/lower/dir\n\n# Build from upper layer based on lower layer\n\nnydus-image create \\\n\n --parent-bootstrap /path/to/parent-bootstrap\n\n --bootstrap /path/to/bootstrap\n\n --backend-type localfs\n\n --backend-config '{\"dir\":\"/path/to/blobs\"}'\n\n /path/to/upper/dir\n\n```\n\n\n\n## Build Nydus Image From Stargz Index\n\n\n\n### Convert image layer to stargz format\n\n\n\n```shell\n\ntar --xattrs --selinux -czvf ./layer.tar.gz <layer-directory>\n\nstargzify file:layer.tar.gz file:layer.stargz\n\ntar -xzvf layer.stargz stargz.index.json\n\n```\n\n\n", "file_path": "docs/nydus-image.md", "rank": 99, "score": 65.63506449981097 } ]
Rust
vehicle-information-service/examples/server.rs
buesima/vehicle-information-service
086b9ba38947cc266867c4700e11f4e9ea727810
#[macro_use] extern crate log; extern crate structopt; use actix::prelude::*; use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use futures::prelude::*; use futures_util::compat::Stream01CompatExt; use serde_json::json; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use structopt::StructOpt; use tokio_socketcan; use vehicle_information_service::{AppState, KnownError, Router, Set, SignalManager, UpdateSignal}; const PATH_PRIVATE_EXAMPLE_PRINT_SET: &str = "Private.Example.Print.Set"; const PATH_PRIVATE_EXAMPLE_INTERVAL: &str = "Private.Example.Interval"; const PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID: &str = "Private.Example.SocketCan.Last.Frame.Id"; #[derive(StructOpt, Debug, Clone)] #[structopt(name = "Vehicle Information Service Demo")] struct Opt { #[structopt( short = "c", long = "can", default_value = "vcan0", help = "CAN Interface" )] can_interface: String, #[structopt( short = "p", long = "port", default_value = "14430", help = "Websocket Port" )] port: u16, } fn main() { env_logger::init(); let sys = actix::System::new("vis-server-example"); let opt = Opt::from_args(); let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), opt.port); info!("Starting server"); HttpServer::new(move || { let app_state: AppState = Default::default(); let interval_signal_source = IntervalSignalSource::new(app_state.signal_manager_addr().clone()); interval_signal_source.start(); let can_id_stream = tokio_socketcan::CANSocket::open(&opt.can_interface) .unwrap() .compat() .map_ok(|frame| frame.id()); app_state.spawn_stream_signal_source( PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID.into(), can_id_stream, ); let example_set = PrintSetRecipient::start_default(); app_state.add_set_recipient( PATH_PRIVATE_EXAMPLE_PRINT_SET.into(), example_set.recipient().clone(), ); App::new() .data(app_state) .wrap(middleware::Logger::default()) .configure(Router::configure_routes) .default_service(web::route().to(|| HttpResponse::NotFound())) }) .bind(socket_addr) .unwrap() .start(); let _ = sys.run(); } pub(crate) struct IntervalSignalSource { signal_manager_addr: Addr<SignalManager>, interval_handle: Option<SpawnHandle>, count: Arc<AtomicUsize>, } impl IntervalSignalSource { pub fn new(signal_manager_addr: Addr<SignalManager>) -> Self { IntervalSignalSource { signal_manager_addr, interval_handle: None, count: Default::default(), } } } impl Actor for IntervalSignalSource { type Context = Context<Self>; fn started(&mut self, ctx: &mut Context<Self>) { self.interval_handle = self.interval_handle.or_else(|| { Some(ctx.run_interval(Duration::from_secs(1), |act, _ctx| { let v = act.count.fetch_add(1, Ordering::SeqCst); let update = UpdateSignal { path: PATH_PRIVATE_EXAMPLE_INTERVAL.into(), value: json!(v), }; act.signal_manager_addr.do_send(update); })) }); } } #[derive(Default)] struct PrintSetRecipient {} impl Actor for PrintSetRecipient { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Context<Self>) { info!( "Print `set`-recipient started, PATH: {}", PATH_PRIVATE_EXAMPLE_PRINT_SET ); } fn stopped(&mut self, _ctx: &mut Context<Self>) { info!( "Print `set`-recipient stopped, PATH: {}", PATH_PRIVATE_EXAMPLE_PRINT_SET ); } } impl Handler<Set> for PrintSetRecipient { type Result = Result<(), KnownError>; fn handle(&mut self, msg: Set, _ctx: &mut Context<Self>) -> Result<(), KnownError> { info!("Received SET for path `{}`, value: {}", msg.path, msg.value); Ok(()) } }
#[macro_use] extern crate log; extern crate structopt; use actix::prelude::*; use actix_web::{middleware, web, App, HttpResponse, HttpServer}; use futures::prelude::*; use futures_util::compat::Stream01CompatExt; use serde_json::json; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; use structopt::StructOpt; use tokio_socketcan; use vehicle_information_service::{AppState, KnownError, Router, Set, SignalManager, UpdateSignal}; const PATH_PRIVATE_EXAMPLE_PRINT_SET: &str = "Private.Example.Print.Set"; const PATH_PRIVATE_EXAMPLE_INTERVAL: &str = "Private.Example.Interval"; const PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID: &str = "Private.Example.SocketCan.Last.Frame.Id"; #[derive(StructOpt, Debug, Clone)] #[structopt(name = "Vehicle Information Service Demo")] struct Opt { #[structopt( short = "c", long = "can", default_value = "vcan0", help = "CAN Interface" )] can_interface: String, #[structopt( short = "p", long = "port", default_value = "14430", help = "Websocket Port" )] port: u16, } fn main() { env_logger::init(); let sys = actix::System::new("vis-server-example"); let opt = Opt::from_args(); let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), opt.port); info!("Starting server"); HttpServer::new(move || { let app_state: AppState = Default::default(); let interval_signal_source = IntervalSignalSource::new(app_state.signal_manager_addr().clone()); interval_signal_source.start(); let can_id_stream = tokio_socketcan::CANSocket::open(&opt.can_interface) .unwrap() .compat() .map_ok(|frame| frame.id()); app_state.spawn_stream_signal_source( PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID.into(), can_id_stream, ); let example_set = PrintSetRecipient::start_default(); app_state.add_set_recipient( PATH_PRIVATE_EXAMPLE_PRINT_SET.into(), example_set.recipient().clone(), ); App::new() .data(app_state) .wrap(middleware::Logger::default()) .configure(Router::configure_routes) .default_service(web::route().to(|| HttpResponse::NotFound())) }) .bind(socket_addr) .unwrap() .start(); let _ = sys.run(); } pub(crate) struct IntervalSignalSource { signal_manager_addr: Addr<SignalManager>, interval_handle: Option<SpawnHandle>, count: Arc<AtomicUsize>, } impl IntervalSignalSource { pub fn new(signal_manager_addr: Addr<SignalManager>) -> Self { IntervalSignalSource { signal_manager_addr, interval_handle: None, count: Default::default(), } } } impl Actor for IntervalSignalSource { type Context = Context<Self>; fn started(&mut self, ctx: &mut Context<Self>) { self.interval_handle = self.interval_handle.or_else(|| { Some(ctx.run_interval(Duration::from_secs(1), |act, _ctx| { let v = act.count.fetch_add(1, Ordering::SeqCst); let update = UpdateSignal { path: PATH_PRIVATE_EXAMPLE_INTERVAL.int
} #[derive(Default)] struct PrintSetRecipient {} impl Actor for PrintSetRecipient { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Context<Self>) { info!( "Print `set`-recipient started, PATH: {}", PATH_PRIVATE_EXAMPLE_PRINT_SET ); } fn stopped(&mut self, _ctx: &mut Context<Self>) { info!( "Print `set`-recipient stopped, PATH: {}", PATH_PRIVATE_EXAMPLE_PRINT_SET ); } } impl Handler<Set> for PrintSetRecipient { type Result = Result<(), KnownError>; fn handle(&mut self, msg: Set, _ctx: &mut Context<Self>) -> Result<(), KnownError> { info!("Received SET for path `{}`, value: {}", msg.path, msg.value); Ok(()) } }
o(), value: json!(v), }; act.signal_manager_addr.do_send(update); })) }); }
function_block-function_prefixed
[ { "content": "///\n\n/// Does the val match the filter criteria\n\n/// Returns:\n\n/// Ok(true) : E.g. value changed sufficiently or there was no filter set\n\n/// Ok(false) : Did not reach change threshold\n\n/// Err(...): Occurs when the value is not an integer, filters only work for ints\n\n///\n\npub fn matches(\n\n val: &Value,\n\n last_value: &Option<(SystemTime, Value)>,\n\n filters_opt: &Option<Filters>,\n\n) -> Result<bool, Error> {\n\n debug!(\n\n \"Matches filter val {:?}, last value {:?}, filters {:?}\",\n\n val, last_value, filters_opt\n\n );\n\n\n\n let changed_exp = last_value.as_ref().map_or(true, |v| val != &v.1);\n\n\n\n let filters_exp = if let Some(filters) = filters_opt {\n\n let interval_exp = interval(SystemTime::now(), last_value, filters);\n\n\n\n let range_exp = is_in_filter_range(&val, filters)?;\n\n let min_change_exp = is_min_change(&val, last_value, filters)?;\n\n debug!(\n\n \"Matches filter val {:?}, last value {:?}, filters {:?}, changed_exp? {}, range_exp? {}, min_change_exp? {}\",\n\n val, last_value, filters, changed_exp, range_exp, min_change_exp,\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 3, "score": 95695.87136440145 }, { "content": "pub fn new_unsubscribe_error(\n\n request_id: ReqID,\n\n subscription_id: SubscriptionID,\n\n error: ActionError,\n\n) -> ActionErrorResponse {\n\n ActionErrorResponse::Unsubscribe {\n\n request_id,\n\n subscription_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 4, "score": 89728.44570459725 }, { "content": "pub fn unix_timestamp_ms() -> u128 {\n\n unix_timestamp().map(|t| t.as_millis()).unwrap_or_default()\n\n}\n\n\n\n///\n\n/// Serialize response type and wrap the result ready to be returned by the websocket lib\n\n///\n\npub(crate) fn serialize_result<F>(\n\n result: &Result<ActionSuccessResponse, ActionErrorResponse>,\n\n internal_server_error: F,\n\n) -> String\n\nwhere\n\n F: FnOnce() -> ActionErrorResponse,\n\n{\n\n match result {\n\n Ok(success) => to_string(&success).unwrap_or_else(|_| {\n\n let error = internal_server_error();\n\n to_string(&error).unwrap_or_default()\n\n }),\n\n Err(error) => to_string(&error).unwrap_or_else(|_| {\n\n let error = internal_server_error();\n\n to_string(&error).unwrap_or_default()\n\n }),\n\n }\n\n}\n", "file_path": "vehicle-information-service/src/lib.rs", "rank": 5, "score": 86898.64701822014 }, { "content": "pub fn new_set_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::Set {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 6, "score": 85524.1956650556 }, { "content": "pub fn new_deserialization_error() -> ActionError {\n\n // TODO this does not appear to be specified in spec\n\n StatusCode::BAD_REQUEST.into()\n\n}\n\n\n\n///\n\n/// An error that is listed in the specification error table.\n\n/// [Error Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#errors)\n\n///\n\npub struct KnownError(StatusCode, &'static str, &'static str);\n\n\n\nimpl From<KnownError> for ActionError {\n\n fn from(known_error: KnownError) -> Self {\n\n Self {\n\n number: known_error.0.as_u16(),\n\n reason: known_error.1.to_string(),\n\n message: known_error.2.to_string(),\n\n }\n\n }\n\n}\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 7, "score": 83475.67013444452 }, { "content": "fn ws_index(\n\n state: web::Data<AppState>,\n\n r: HttpRequest,\n\n stream: web::Payload,\n\n) -> Result<actix_web::HttpResponse, actix_web::Error> {\n\n let addr = state.signal_manager_addr.clone();\n\n ws::start(ClientSession::new(addr), &r, stream)\n\n}\n\n\n\nimpl Router {\n\n /// Create a new instance of a Router\n\n pub fn configure_routes(cfg: &mut web::ServiceConfig) {\n\n cfg.service(web::resource(\"/\").route(web::get().to(ws_index)));\n\n }\n\n}\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 8, "score": 82114.33493366872 }, { "content": "struct SubscriptionIDVisitor;\n\n\n\nimpl<'de> Visitor<'de> for SubscriptionIDVisitor {\n\n type Value = SubscriptionID;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"an integer or a uuid\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n if let Ok(uuid) = uuid::Uuid::from_str(value) {\n\n Ok(SubscriptionID::SubscriptionIDUUID(uuid))\n\n } else if let Ok(number) = value.parse() {\n\n Ok(SubscriptionID::SubscriptionIDInt(number))\n\n } else {\n\n Err(E::custom(format!(\n\n \"string is not a uuid nor an integer: {}\",\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 9, "score": 81143.83506377976 }, { "content": "pub fn new_authorize_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::Authorize {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 10, "score": 65629.24474730308 }, { "content": "pub fn new_subscribe_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::Subscribe {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 11, "score": 65629.24474730308 }, { "content": "pub fn new_unsubscribe_all_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::UnsubscribeAll {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 12, "score": 65629.24474730308 }, { "content": "pub fn new_get_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::Get {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 13, "score": 65629.24474730308 }, { "content": "pub fn new_get_metadata_error(request_id: ReqID, error: ActionError) -> ActionErrorResponse {\n\n ActionErrorResponse::GetMetadata {\n\n request_id,\n\n error,\n\n timestamp: unix_timestamp_ms(),\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_error.rs", "rank": 14, "score": 64572.28111508457 }, { "content": "#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(tag = \"action\")]\n\nstruct AuthorizeMessage {\n\n tokens: Value,\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n}\n\n\n\nimpl Handler for Authorize {\n\n type Result = Result<Ok, Error>;\n\n fn handle(&mut self, authorize: Authorize, ctx: &mut ws::WebsocketContext<Self>) -> Self::Result {\n\n unimplemented!();\n\n }\n\n}", "file_path": "vehicle-information-service/src/action/authorize.rs", "rank": 15, "score": 56480.512964627735 }, { "content": "#[derive(Debug)]\n\nstruct GetMetadata {\n\n path: ActionPath,\n\n request_id: ReqID,\n\n}", "file_path": "vehicle-information-service/src/action/get_metadata.rs", "rank": 16, "score": 55314.88847065487 }, { "content": "#[derive(Clone, Debug)]\n\nstruct SerdeNumber(Number);\n\n\n\nimpl SerdeNumber {\n\n fn abs(self) -> Self {\n\n if self.0.is_u64() {\n\n self\n\n } else if self.0.is_i64() {\n\n Self(self.0.as_i64().unwrap_or(9999).abs().into())\n\n } else {\n\n Self(\n\n Number::from_f64(self.0.as_f64().unwrap_or_default().abs()).unwrap_or_else(|| {\n\n Number::from_f64(0.0).expect(\"Unexpected number conversion error\")\n\n }),\n\n )\n\n }\n\n }\n\n}\n\n\n\nimpl PartialEq for SerdeNumber {\n\n fn eq(&self, other: &Self) -> bool {\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 17, "score": 54470.06952779856 }, { "content": "///\n\n/// Changed by at least x compared to last value.\n\n/// Returns None if there is no last value.\n\n///\n\nfn is_min_change(\n\n val: &Value,\n\n last_value: &Option<(SystemTime, Value)>,\n\n filters: &Filters,\n\n) -> Result<bool, Error> {\n\n debug!(\"Last value {:?}, new value {:?}\", last_value, val);\n\n\n\n if let Some(ref filter_min_change) = filters.min_change {\n\n if let Some((_time, value)) = last_value {\n\n let num = value_as_number(val)?;\n\n let as_number = value_as_number(value)?;\n\n return Ok((as_number - num).abs() >= SerdeNumber(filter_min_change.clone()));\n\n }\n\n }\n\n\n\n // no filter min change in subscription or no last value yet\n\n Ok(true)\n\n}\n\n\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 18, "score": 54109.843999457225 }, { "content": "\n\n let stream_signal_source = s.try_for_each(move |item| {\n\n let update = UpdateSignal {\n\n path: ActionPath(path.to_string()),\n\n value: json!(item),\n\n };\n\n signal_manager_addr.do_send(update);\n\n\n\n futures::future::ready(Ok(()))\n\n });\n\n\n\n actix::spawn(\n\n stream_signal_source\n\n .map_err(|e| warn!(\"Signal source stream error: {:?}\", e))\n\n .compat(),\n\n );\n\n }\n\n}\n\n\n\nimpl Default for AppState {\n\n fn default() -> Self {\n\n Self {\n\n signal_manager_addr: SignalManager::start_default(),\n\n }\n\n }\n\n}\n\n\n\npub struct Router {}\n\n\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 25, "score": 42115.92230474432 }, { "content": " client_connection_id: ClientConnectionId,\n\n\n\n signal_manager_addr: Addr<SignalManager>,\n\n}\n\n\n\nimpl ClientSession {\n\n pub fn new(signal_manager_addr: Addr<SignalManager>) -> Self {\n\n Self {\n\n client_connection_id: Uuid::new_v4(),\n\n signal_manager_addr,\n\n }\n\n }\n\n}\n\n\n\nimpl Actor for ClientSession {\n\n type Context = ws::WebsocketContext<Self>;\n\n\n\n fn started(&mut self, _ctx: &mut Self::Context) {\n\n info!(\"Client {} started\", self.client_connection_id);\n\n }\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 26, "score": 42115.84755487273 }, { "content": "// SPDX-License-Identifier: MIT\n\n\n\nuse actix::prelude::*;\n\nuse actix_web::{web, HttpRequest};\n\nuse actix_web_actors::ws;\n\n\n\nuse futures::prelude::*;\n\nuse http::status::StatusCode;\n\nuse serde_json::{from_str, json, to_string};\n\nuse uuid::Uuid;\n\n\n\nuse crate::action;\n\nuse crate::api_error::*;\n\nuse crate::api_type::*;\n\nuse crate::serialize_result;\n\nuse crate::signal_manager::{SignalManager, UpdateSignal};\n\n\n\npub struct ClientSession {\n\n /// Each client is assigned a unique identifier after connecting.\n\n /// This identifier can be used to identify the client in the logs.\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 27, "score": 42115.71707304583 }, { "content": " ws::Message::Nop => (),\n\n }\n\n }\n\n}\n\n\n\npub struct AppState {\n\n signal_manager_addr: Addr<SignalManager>,\n\n}\n\n\n\nimpl AppState {\n\n pub fn signal_manager_addr(&self) -> Addr<SignalManager> {\n\n self.signal_manager_addr.clone()\n\n }\n\n\n\n /// Set the path to the given value.\n\n pub fn set_signal<T>(&self, path: ActionPath, value: T)\n\n where\n\n T: serde::ser::Serialize,\n\n {\n\n self.signal_manager_addr.do_send(UpdateSignal {\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 28, "score": 42111.268935677115 }, { "content": "\n\nimpl Handler<ActionSuccessResponse> for ClientSession {\n\n type Result = ();\n\n fn handle(&mut self, msg: ActionSuccessResponse, ctx: &mut Self::Context) {\n\n // TODO replace subscribe error with subscription error\n\n let serialized = serialize_result(&Ok(msg), || {\n\n new_subscribe_error(ReqID::ReqIDInt(0), StatusCode::INTERNAL_SERVER_ERROR.into())\n\n });\n\n ctx.text(serialized)\n\n }\n\n}\n\n\n\nimpl Handler<ActionErrorResponse> for ClientSession {\n\n type Result = ();\n\n fn handle(&mut self, msg: ActionErrorResponse, ctx: &mut Self::Context) {\n\n // TODO replace subscribe error with subscription error\n\n let serialized = serialize_result(&Err(msg), || {\n\n new_subscribe_error(ReqID::ReqIDInt(0), StatusCode::INTERNAL_SERVER_ERROR.into())\n\n });\n\n ctx.text(serialized)\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 29, "score": 42108.08954637287 }, { "content": " }\n\n}\n\n\n\nimpl StreamHandler<ws::Message, ws::ProtocolError> for ClientSession {\n\n fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {\n\n debug!(\"WS: {:?}\", msg);\n\n match msg {\n\n ws::Message::Ping(msg) => {\n\n debug!(\"Responding to `Ping` message: {} with Pong\", msg);\n\n ctx.pong(&msg);\n\n }\n\n ws::Message::Pong(_) => {}\n\n ws::Message::Binary(_bin) => {\n\n warn!(\"Binary message payload. This message will be ignored.\");\n\n }\n\n ws::Message::Text(ref txt) => {\n\n // deserialize and dispatch VIS action\n\n\n\n match from_str::<Action>(txt) {\n\n Err(e) => {\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 30, "score": 42107.68938873478 }, { "content": "\n\n fn stopped(&mut self, ctx: &mut Self::Context) {\n\n // Cleanup client subscriptions\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n\n message: action::UnsubscribeAll { request_id: None },\n\n });\n\n\n\n info!(\"Client {} stopped\", self.client_connection_id);\n\n }\n\n}\n\n\n\nimpl Message for ActionSuccessResponse {\n\n type Result = ();\n\n}\n\n\n\nimpl Message for ActionErrorResponse {\n\n type Result = ();\n\n}\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 31, "score": 42107.40766931167 }, { "content": " path,\n\n value: json!(value),\n\n });\n\n }\n\n\n\n /// Register a `set` action recipient. This recipient will receive all `set` action requests for all clients.\n\n pub fn add_set_recipient(&self, path: ActionPath, recipient: Recipient<action::Set>) {\n\n self.signal_manager_addr\n\n .do_send(action::AddSetRecipient { path, recipient });\n\n }\n\n\n\n /// Spawn a new signal stream source. A signal stream will provide signal updates for the given path.\n\n pub fn spawn_stream_signal_source<St>(&self, path: ActionPath, s: St)\n\n where\n\n St: TryStream + Unpin,\n\n St: 'static,\n\n St::Ok: serde::Serialize,\n\n St::Error: std::fmt::Debug,\n\n {\n\n let signal_manager_addr = self.signal_manager_addr.clone();\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 32, "score": 42106.88232631517 }, { "content": " } => {\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n\n message: action::Set {\n\n request_id,\n\n path,\n\n value,\n\n },\n\n });\n\n }\n\n // TODO implement\n\n Action::Authorize { request_id, .. } => {\n\n if let Ok(serialized) = to_string(&new_authorize_error(\n\n request_id,\n\n StatusCode::NOT_IMPLEMENTED.into(),\n\n )) {\n\n ctx.text(serialized)\n\n }\n\n }\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 33, "score": 42102.065634348146 }, { "content": " warn!(\"Deserialization error {}\", e);\n\n let err = new_deserialization_error();\n\n if let Ok(serialized) = to_string(&err) {\n\n ctx.text(serialized);\n\n }\n\n }\n\n Ok(action) => {\n\n debug!(\n\n \"Received action {:?} for client connection_id {}\",\n\n action, self.client_connection_id\n\n );\n\n match action {\n\n Action::Subscribe {\n\n path,\n\n request_id,\n\n filters,\n\n } => {\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 34, "score": 42101.485240273 }, { "content": " Action::Get { path, request_id } => {\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n\n message: action::Get { request_id, path },\n\n });\n\n }\n\n Action::UnsubscribeAll { request_id } => {\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n\n message: action::UnsubscribeAll {\n\n request_id: Some(request_id),\n\n },\n\n });\n\n }\n\n Action::Set {\n\n request_id,\n\n path,\n\n value,\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 35, "score": 42100.21180064619 }, { "content": " // TODO implement\n\n Action::GetMetadata { request_id, .. } => {\n\n if let Ok(serialized) = to_string(&new_get_metadata_error(\n\n request_id,\n\n StatusCode::NOT_IMPLEMENTED.into(),\n\n )) {\n\n ctx.text(serialized)\n\n }\n\n }\n\n }\n\n }\n\n };\n\n }\n\n ws::Message::Close(close_reason) => {\n\n info!(\n\n \"Client {} sent Close message, reason: {:?}\",\n\n self.client_connection_id, close_reason\n\n );\n\n ctx.stop();\n\n }\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 36, "score": 42097.964250409415 }, { "content": " message: action::Subscribe {\n\n path,\n\n request_id,\n\n filters,\n\n },\n\n });\n\n }\n\n Action::Unsubscribe {\n\n request_id,\n\n subscription_id,\n\n } => {\n\n self.signal_manager_addr.do_send(action::ClientMessage {\n\n client_connection_id: self.client_connection_id,\n\n client_addr: ctx.address(),\n\n message: action::Unsubscribe {\n\n request_id,\n\n subscription_id,\n\n },\n\n });\n\n }\n", "file_path": "vehicle-information-service/src/router.rs", "rank": 37, "score": 42097.1891974558 }, { "content": "///\n\n/// Extract a Number from a JSON Value or return Error if not possible.\n\n///\n\nfn value_as_number(val: &Value) -> Result<SerdeNumber, Error> {\n\n if let Value::Number(ref num) = *val {\n\n Ok(SerdeNumber(num.clone()))\n\n } else {\n\n Err(Error::ValueIsNotANumber)\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 38, "score": 42019.00916157836 }, { "content": "type Result<T> = core::result::Result<T, VISClientError>;\n\n\n\npub struct VISClient {\n\n #[allow(dead_code)]\n\n server_address: String,\n\n client: websocket::client::r#async::Client<TcpStream>,\n\n}\n\n\n\nimpl VISClient {\n\n #[allow(clippy::needless_lifetimes)] // Clippy false positive\n\n pub async fn connect(server_address: &str) -> Result<Self> {\n\n let (client, _headers) = ClientBuilder::new(server_address)?\n\n .async_connect_insecure()\n\n .compat()\n\n .await?;\n\n debug!(\"Connected to: {}\", server_address);\n\n Ok(Self {\n\n server_address: server_address.to_string(),\n\n client,\n\n })\n", "file_path": "vehicle-information-service-client/src/lib.rs", "rank": 39, "score": 41884.23267014387 }, { "content": "/// SET request\n\n/// https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-setrequest\n\n///\n\n#[derive(Clone, Debug)]\n\npub struct Set {\n\n pub path: ActionPath,\n\n pub value: Value,\n\n pub request_id: ReqID,\n\n}\n\n\n\nimpl Message for Set {\n\n type Result = Result<(), KnownError>;\n\n}\n\n\n\nimpl Message for ClientMessage<Set> {\n\n type Result = ();\n\n}\n\n\n\nimpl Handler<ClientMessage<Set>> for SignalManager {\n\n type Result = ();\n", "file_path": "vehicle-information-service/src/action/set.rs", "rank": 40, "score": 40970.159721642296 }, { "content": " // No recipient for the requested path\n\n msg.client_addr.do_send(ActionErrorResponse::Set {\n\n request_id: msg.message.request_id,\n\n timestamp: unix_timestamp_ms(),\n\n error: NOT_FOUND_INVALID_PATH.into(),\n\n });\n\n }\n\n }\n\n}\n\n\n\npub struct AddSetRecipient {\n\n pub path: ActionPath,\n\n pub recipient: Recipient<Set>,\n\n}\n\n\n\nimpl Message for AddSetRecipient {\n\n type Result = ();\n\n}\n\n\n\nimpl Handler<AddSetRecipient> for SignalManager {\n\n type Result = ();\n\n\n\n fn handle(&mut self, msg: AddSetRecipient, _ctx: &mut Self::Context) {\n\n self.set_recipients.insert(msg.path, msg.recipient);\n\n }\n\n}\n", "file_path": "vehicle-information-service/src/action/set.rs", "rank": 41, "score": 40967.03188248746 }, { "content": "// SPDX-License-Identifier: MIT\n\n\n\n//!\n\n//! Dispatch client Set requests to a registered set receivers and register\n\n//! new Set receivers.\n\n//!\n\n\n\nuse crate::action::ClientMessage;\n\nuse crate::api_error::{\n\n ActionErrorResponse, KnownError, NOT_FOUND_INVALID_PATH, SERVICE_UNAVAILABLE,\n\n};\n\nuse crate::api_type::ReqID;\n\nuse crate::signal_manager::SignalManager;\n\nuse actix::prelude::*;\n\nuse log::warn;\n\nuse serde_json::Value;\n\n\n\nuse crate::api_type::{ActionPath, ActionSuccessResponse};\n\nuse crate::unix_timestamp_ms;\n\n\n", "file_path": "vehicle-information-service/src/action/set.rs", "rank": 42, "score": 40965.69994561791 }, { "content": "\n\n fn handle(&mut self, msg: ClientMessage<Set>, _ctx: &mut Self::Context) {\n\n let recipients = self.set_recipients.clone();\n\n if let Some(recipient) = recipients.get(&msg.message.path) {\n\n let set_message = msg.message.clone();\n\n if let Err(e) = recipient.do_send(set_message) {\n\n warn!(\"Failed to deliver Set message to recipient: {}\", e);\n\n msg.client_addr.do_send(ActionErrorResponse::Set {\n\n request_id: msg.message.request_id,\n\n timestamp: unix_timestamp_ms(),\n\n error: SERVICE_UNAVAILABLE.into(),\n\n });\n\n return;\n\n }\n\n\n\n msg.client_addr.do_send(ActionSuccessResponse::Set {\n\n request_id: msg.message.request_id,\n\n timestamp: unix_timestamp_ms(),\n\n });\n\n } else {\n", "file_path": "vehicle-information-service/src/action/set.rs", "rank": 43, "score": 40963.28299577841 }, { "content": " }\n\n}\n\n\n\nimpl From<&str> for ActionPath {\n\n fn from(s: &str) -> Self {\n\n Self(s.to_string())\n\n }\n\n}\n\n\n\n///\n\n/// [Action](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#action)\n\n///\n\n#[derive(Hash, Eq, PartialEq, Serialize, Deserialize, Clone, Copy, Debug)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub enum ActionType {\n\n ///\n\n /// Enables client to pass security tokens for Security Principals to the server to support access-control.\n\n ///\n\n #[serde(alias = \"authorize\")]\n\n #[serde(alias = \"Authorize\")]\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 44, "score": 40192.42583869467 }, { "content": " where\n\n D: Deserializer<'de>,\n\n {\n\n deserializer.deserialize_string(SubscriptionIDVisitor)\n\n }\n\n}\n\n\n\n///\n\n/// The path to the desired vehicle signal(s), as defined by the Vehicle Signal Specification (VSS).\n\n///\n\n/// # Examples\n\n/// `ActionPath(\"Signal.Vehicle.Speed\".to_string())`\n\n///\n\n#[derive(Clone, Serialize, Deserialize, Debug)]\n\npub struct ActionPath(pub String);\n\n\n\nimpl ActionPath {\n\n /// Create a new instance out of a str\n\n pub fn new(path: &str) -> ActionPath {\n\n ActionPath(path.to_string())\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 45, "score": 40187.653949815074 }, { "content": " ///\n\n /// SET request\n\n /// [Set Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-setrequest)\n\n ///\n\n #[serde(alias = \"set\")]\n\n #[serde(alias = \"Set\")]\n\n Set {\n\n path: ActionPath,\n\n value: Value,\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n },\n\n ///\n\n /// SUBSCRIBE request\n\n /// [Subscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#subscribe)\n\n ///\n\n #[serde(alias = \"subscribe\")]\n\n #[serde(alias = \"Subscribe\")]\n\n Subscribe {\n\n path: ActionPath,\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 46, "score": 40180.329424154595 }, { "content": " let d_sub_id_uuid = serde_json::from_str(&s_sub_id_uuid).unwrap();\n\n assert_eq!(sub_id_uuid, d_sub_id_uuid);\n\n }\n\n}\n\n\n\n/// Unique id value specified by the client.\n\n/// Returned by the server in the response and used by\n\n/// client to link the request and response messages.\n\n/// May be a Universally Unique Identifier (UUID)\n\n#[derive(PartialEq, Eq, Debug, Clone, Copy)]\n\npub enum ReqID {\n\n ReqIDInt(u64),\n\n ReqIDUUID(uuid::Uuid),\n\n}\n\n\n\nimpl fmt::Display for ReqID {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n ReqID::ReqIDInt(i) => write!(f, \"ReqId int {}\", i),\n\n ReqID::ReqIDUUID(u) => write!(f, \"ReqId uuid {}\", u),\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 47, "score": 40178.60676575278 }, { "content": " }\n\n}\n\n\n\nimpl PartialEq for ActionPath {\n\n fn eq(&self, other: &Self) -> bool {\n\n self.0.to_lowercase() == other.0.to_lowercase()\n\n }\n\n}\n\n\n\nimpl Eq for ActionPath {}\n\n\n\nimpl Hash for ActionPath {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n self.0.to_lowercase().hash(state);\n\n }\n\n}\n\n\n\nimpl fmt::Display for ActionPath {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", self.0)\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 48, "score": 40177.44637444121 }, { "content": "#[serde(rename_all = \"camelCase\")]\n\npub enum ActionSuccessResponse {\n\n ///\n\n /// Response for successful GET request\n\n /// [Get Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-getrequest)\n\n ///\n\n Get {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n value: Value,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n ///\n\n /// Response for successful SET request\n\n /// [Set Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-setrequest)\n\n ///\n\n Set {\n\n #[serde(rename = \"requestId\")]\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 49, "score": 40177.44269998019 }, { "content": "// SPDX-License-Identifier: MIT\n\n\n\n//!\n\n//! Types as defined by the VIS specification.\n\n//!\n\nuse crate::api_error::ActionErrorResponse;\n\nuse actix::Message;\n\nuse serde::de::{self, Visitor};\n\nuse serde::{Deserialize, Deserializer, Serialize, Serializer};\n\nuse serde_json::{Number, Value};\n\nuse std::fmt;\n\nuse std::hash::{Hash, Hasher};\n\nuse std::str::FromStr;\n\nuse uuid;\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::api_type::*;\n\n use serde_json;\n\n\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 50, "score": 40177.29632601681 }, { "content": " ///\n\n /// Allows the client to notify the server that it should no longer receive notifications for\n\n /// any active subscription.\n\n ///\n\n #[serde(alias = \"unsubscribeAll\")]\n\n #[serde(alias = \"UnsubscribeAll\")]\n\n UnsubscribeAll,\n\n}\n\n\n\nimpl fmt::Display for ActionType {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n let msg = match *self {\n\n ActionType::Authorize => \"AUTHORIZE\",\n\n ActionType::GetMetadata => \"GET_METADATA\",\n\n ActionType::Get => \"GET\",\n\n ActionType::Set => \"SET\",\n\n ActionType::Subscribe => \"SUBSCRIBE\",\n\n ActionType::Subscription => \"SUBSCRIPTION\",\n\n ActionType::Unsubscribe => \"UNSUBSCRIBE\",\n\n ActionType::UnsubscribeAll => \"UNSUBSCRIBE_ALL\",\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 51, "score": 40176.97899575451 }, { "content": " #[test]\n\n fn action_path_equality_caseinsensite() {\n\n assert_eq!(\n\n ActionPath(\"path\".to_string()),\n\n ActionPath(\"PATH\".to_string())\n\n );\n\n assert_eq!(\n\n ActionPath(\"pAtH\".to_string()),\n\n ActionPath(\"PaTh\".to_string())\n\n );\n\n }\n\n\n\n #[test]\n\n fn serialize_deserialize_req_id_int() {\n\n let req_id_int = ReqID::ReqIDInt(100);\n\n let s_req_id_int = serde_json::to_string(&req_id_int).unwrap();\n\n let d_req_id_int = serde_json::from_str(&s_req_id_int).unwrap();\n\n assert_eq!(req_id_int, d_req_id_int);\n\n }\n\n\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 52, "score": 40176.4387052526 }, { "content": " /// [Metadata Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-metadatarequest)\n\n ///\n\n #[serde(alias = \"getMetadata\")]\n\n #[serde(alias = \"GetMetadata\")]\n\n GetMetadata {\n\n path: ActionPath,\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n },\n\n ///\n\n /// GET request\n\n /// [Get Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-getrequest)\n\n ///\n\n #[serde(alias = \"get\")]\n\n #[serde(alias = \"Get\")]\n\n Get {\n\n path: ActionPath,\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n },\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 53, "score": 40176.20400711329 }, { "content": "///\n\n#[derive(Hash, Eq, PartialEq, Debug, Clone, Copy)]\n\npub enum SubscriptionID {\n\n SubscriptionIDInt(i64),\n\n SubscriptionIDUUID(uuid::Uuid),\n\n}\n\n\n\nimpl fmt::Display for SubscriptionID {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match *self {\n\n SubscriptionID::SubscriptionIDInt(i) => write!(f, \"SubId int {}\", i),\n\n SubscriptionID::SubscriptionIDUUID(u) => write!(f, \"SubId uuid {}\", u),\n\n }\n\n }\n\n}\n\n\n\nimpl Default for SubscriptionID {\n\n fn default() -> Self {\n\n let id = uuid::Uuid::new_v4();\n\n SubscriptionID::SubscriptionIDUUID(id)\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 54, "score": 40176.2003944953 }, { "content": " #[serde(rename = \"minChange\")]\n\n pub min_change: Option<Number>,\n\n}\n\n\n\n#[derive(Serialize, Deserialize, Debug)]\n\n#[serde(tag = \"action\", rename_all = \"camelCase\")]\n\npub enum Action {\n\n ///\n\n /// AUTHORIZE request\n\n /// [Authorize Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#dfn-authorizerequest)\n\n ///\n\n #[serde(alias = \"authorize\")]\n\n #[serde(alias = \"Authorize\")]\n\n Authorize {\n\n tokens: Value,\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n },\n\n ///\n\n /// Metadata request\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 55, "score": 40175.71622180113 }, { "content": " /// [Subscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#subscribe)\n\n ///\n\n Subscribe {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n #[serde(rename = \"subscriptionId\")]\n\n subscription_id: SubscriptionID,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n}\n\n\n\n///\n\n/// Websocket client connection id\n\n///\n\npub type ClientConnectionId = uuid::Uuid;\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 56, "score": 40175.33495463156 }, { "content": " impl<'de> Visitor<'de> for ReqIDVisitor {\n\n type Value = ReqID;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n\n formatter.write_str(\"an integer or a uuid\")\n\n }\n\n\n\n fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n if let Ok(uuid) = uuid::Uuid::from_str(value) {\n\n Ok(ReqID::ReqIDUUID(uuid))\n\n } else if let Ok(number) = value.parse() {\n\n Ok(ReqID::ReqIDInt(number))\n\n } else {\n\n Err(E::custom(format!(\n\n \"string is not a uuid nor an integer: {}\",\n\n value\n\n )))\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 57, "score": 40175.23293823892 }, { "content": "}\n\n\n\n/// Custom implementation because by spec it's not a JSON Number or JSON String(UUID)\n\n/// but a JSON string that contains an UUID or int\n\nimpl Serialize for SubscriptionID {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n match *self {\n\n SubscriptionID::SubscriptionIDInt(i) => serializer.serialize_str(&i.to_string()),\n\n SubscriptionID::SubscriptionIDUUID(u) => serializer.serialize_str(&u.to_string()),\n\n }\n\n }\n\n}\n\n\n\n/// Custom implementation because by spec it's not a JSON Number or JSON String(UUID)\n\n/// but a JSON string that contains an UUID or int\n\nimpl<'de> Deserialize<'de> for SubscriptionID {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 58, "score": 40175.040175446076 }, { "content": " deserializer.deserialize_string(ReqIDVisitor)\n\n }\n\n}\n\n\n\n/// Custom implementation because by spec it's not a JSON Number or JSON String(UUID)\n\n/// but a JSON string that contains an UUID or int\n\nimpl Serialize for ReqID {\n\n fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>\n\n where\n\n S: Serializer,\n\n {\n\n match *self {\n\n ReqID::ReqIDInt(i) => serializer.serialize_str(&i.to_string()),\n\n ReqID::ReqIDUUID(u) => serializer.serialize_str(&u.to_string()),\n\n }\n\n }\n\n}\n\n\n\n///\n\n/// Value returned by the server to uniquely identify each subscription.\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 59, "score": 40174.93348437992 }, { "content": " #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n #[serde(default)]\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n filters: Option<Filters>,\n\n },\n\n ///\n\n /// [Unsubscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#unsubscribe)\n\n ///\n\n #[serde(alias = \"unsubscribe\")]\n\n #[serde(alias = \"Unsubscribe\")]\n\n Unsubscribe {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n #[serde(rename = \"subscriptionId\")]\n\n subscription_id: SubscriptionID,\n\n },\n\n ///\n\n /// [Unsubscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#unsubscribe)\n\n ///\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 60, "score": 40174.75777520836 }, { "content": " };\n\n write!(f, \"{}\", msg)\n\n }\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize, Debug)]\n\npub struct FilterRange {\n\n #[serde(default)]\n\n pub below: Option<Number>,\n\n #[serde(default)]\n\n pub above: Option<Number>,\n\n}\n\n\n\n#[derive(Clone, Serialize, Deserialize, Debug)]\n\npub struct Filters {\n\n #[serde(default)]\n\n pub interval: Option<u64>,\n\n #[serde(default)]\n\n pub range: Option<FilterRange>,\n\n #[serde(default)]\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 61, "score": 40174.66089520785 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl Default for ReqID {\n\n fn default() -> Self {\n\n let id = uuid::Uuid::new_v4();\n\n ReqID::ReqIDUUID(id)\n\n }\n\n}\n\n\n\n/// Custom implementation because by spec it's not a JSON Number or JSON String(UUID)\n\n/// but a JSON string that contains an UUID or int\n\nimpl<'de> Deserialize<'de> for ReqID {\n\n fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>\n\n where\n\n D: Deserializer<'de>,\n\n {\n\n struct ReqIDVisitor;\n\n\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 62, "score": 40173.2724205501 }, { "content": " request_id: ReqID,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n ///\n\n /// [Unsubscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#unsubscribe)\n\n ///\n\n Unsubscribe {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n #[serde(rename = \"subscriptionId\")]\n\n subscription_id: SubscriptionID,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n ///\n\n /// [Unsubscribe-All Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#unsubscribe-all)\n\n ///\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 63, "score": 40172.85591055114 }, { "content": " }\n\n }\n\n\n\n fn visit_string<E>(self, value: String) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n if let Ok(uuid) = uuid::Uuid::from_str(&value) {\n\n Ok(ReqID::ReqIDUUID(uuid))\n\n } else if let Ok(number) = value.parse() {\n\n Ok(ReqID::ReqIDInt(number))\n\n } else {\n\n Err(E::custom(format!(\n\n \"string is not a uuid nor an integer: {}\",\n\n value\n\n )))\n\n }\n\n }\n\n }\n\n\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 64, "score": 40172.471929232524 }, { "content": " value\n\n )))\n\n }\n\n }\n\n\n\n fn visit_string<E>(self, value: String) -> Result<Self::Value, E>\n\n where\n\n E: de::Error,\n\n {\n\n if let Ok(uuid) = uuid::Uuid::from_str(&value) {\n\n Ok(SubscriptionID::SubscriptionIDUUID(uuid))\n\n } else if let Ok(number) = value.parse() {\n\n Ok(SubscriptionID::SubscriptionIDInt(number))\n\n } else {\n\n Err(E::custom(format!(\n\n \"string is not a uuid nor an integer: {}\",\n\n value\n\n )))\n\n }\n\n }\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 65, "score": 40172.411103919665 }, { "content": " #[test]\n\n fn serialize_deserialize_req_id_uuid() {\n\n let req_id_uuid = ReqID::ReqIDUUID(uuid::Uuid::new_v4());\n\n let s_req_id_uuid = serde_json::to_string(&req_id_uuid).unwrap();\n\n let d_req_id_uuid = serde_json::from_str(&s_req_id_uuid).unwrap();\n\n assert_eq!(req_id_uuid, d_req_id_uuid);\n\n }\n\n\n\n #[test]\n\n fn serialize_deserialize_subscription_id_int() {\n\n let sub_id_int = SubscriptionID::SubscriptionIDInt(100);\n\n let s_sub_id_int = serde_json::to_string(&sub_id_int).unwrap();\n\n let d_sub_id_int = serde_json::from_str(&s_sub_id_int).unwrap();\n\n assert_eq!(sub_id_int, d_sub_id_int);\n\n }\n\n\n\n #[test]\n\n fn serialize_deserialize_subscription_id_uuid() {\n\n let sub_id_uuid = SubscriptionID::SubscriptionIDUUID(uuid::Uuid::new_v4());\n\n let s_sub_id_uuid = serde_json::to_string(&sub_id_uuid).unwrap();\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 66, "score": 40172.40028278812 }, { "content": " #[serde(alias = \"unsubscribeAll\")]\n\n #[serde(alias = \"UnsubscribeAll\")]\n\n UnsubscribeAll {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n },\n\n}\n\n\n\nimpl Message for Action {\n\n type Result = Result<ActionSuccessResponse, ActionErrorResponse>;\n\n}\n\n\n\nimpl fmt::Display for Action {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{:?}\", self)\n\n }\n\n}\n\n\n\n#[derive(PartialEq, Debug, Serialize, Deserialize)]\n\n#[serde(tag = \"action\")]\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 67, "score": 40171.73376039406 }, { "content": " UnsubscribeAll {\n\n #[serde(rename = \"requestId\")]\n\n request_id: ReqID,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n ///\n\n /// [Subscribe Doc](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html#idl-def-subscriptionnotification)\n\n ///\n\n Subscription {\n\n #[serde(rename = \"subscriptionId\")]\n\n subscription_id: SubscriptionID,\n\n value: Value,\n\n // serde_json currently does not support deserializing u128\n\n #[serde(skip_deserializing)]\n\n timestamp: u128,\n\n },\n\n ///\n\n /// Response for successful SUBSCRIBE request\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 68, "score": 40170.840570887005 }, { "content": " /// Enables the client to request notifications containing a JSON data structure with values for one or more vehicle\n\n /// signals and/or data attributes. The client requests that it is notified when the signal changes on the server.\n\n ///\n\n #[serde(alias = \"subscribe\")]\n\n #[serde(alias = \"Subscribe\")]\n\n Subscribe,\n\n ///\n\n /// Enables the server to send notifications to the client containing a JSON data structure with values for one or\n\n /// more vehicle signals and/or data attributes.\n\n ///\n\n #[serde(alias = \"subscription\")]\n\n #[serde(alias = \"Subscription\")]\n\n Subscription,\n\n ///\n\n /// Allows the client to notify the server that it should no longer receive notifications based\n\n /// on that subscription.\n\n ///\n\n #[serde(alias = \"unsubscribe\")]\n\n #[serde(alias = \"Unsubscribe\")]\n\n Unsubscribe,\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 69, "score": 40170.35107348153 }, { "content": " Authorize,\n\n ///\n\n /// Allows the client to request metadata describing signals and data attributes that are potentially accessible.\n\n ///\n\n #[serde(alias = \"getMetadata\")]\n\n #[serde(alias = \"GetMetadata\")]\n\n GetMetadata,\n\n ///\n\n /// Enables the client to get a value once.\n\n ///\n\n #[serde(alias = \"get\")]\n\n #[serde(alias = \"Get\")]\n\n Get,\n\n ///\n\n /// Enables the client to set a value once.\n\n ///\n\n #[serde(alias = \"set\")]\n\n #[serde(alias = \"Set\")]\n\n Set,\n\n ///\n", "file_path": "vehicle-information-service/src/api_type.rs", "rank": 70, "score": 40168.35012480214 }, { "content": "///\n\n/// Below or above filter\n\n///\n\nfn is_in_filter_range(val: &Value, filters: &Filters) -> Result<bool, Error> {\n\n if let Some(ref range) = filters.range {\n\n let num = value_as_number(val)?;\n\n let below = range.clone().below.map_or(true, |b| num <= SerdeNumber(b));\n\n let above = range.clone().above.map_or(true, |a| num >= SerdeNumber(a));\n\n Ok(below && above)\n\n } else {\n\n // No range filter\n\n Ok(true)\n\n }\n\n}\n\n\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 71, "score": 39936.08506087508 }, { "content": "fn interval(now: SystemTime, last_value: &Option<(SystemTime, Value)>, filters: &Filters) -> bool {\n\n last_value.as_ref().map_or(true, |v| {\n\n now.duration_since(v.0)\n\n .ok()\n\n .as_ref()\n\n .and_then(|d| filters.interval.map(|i| Duration::from_millis(i) <= *d))\n\n .unwrap_or(true)\n\n })\n\n}\n\n\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 72, "score": 35949.16707187528 }, { "content": "# Vehicle Information Service\n\n\n\n[![Build Status](https://travis-ci.org/Daimler/vehicle-information-service.svg?branch=master)](https://travis-ci.org/Daimler/vehicle-information-service)\n\n\n\nThis is an implementation of the [Vehicle Information Service standard](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html).\n\nThe goal of the implementation is to make it simple to implement VIS actions for vehicle signals.\n\nE.g. `Subscribe`, `Get` and `Set`, while efficiently handling Websocket connections, clients and subscriptions.\n\n\n\n# NOTICE\n\n\n\nBefore you use the program in productive use, please take all necessary precautions,\n\ne.g. testing and verifying the program with regard to your specific use.\n\nThe program was tested solely for our own use cases, which might differ from yours.\n\n\n\n# Example\n\n\n\nFor a full example, that is guaranteed to build, check the `examples/` folder.\n\nA brief glimpse is given here:\n\n\n\n```rust\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n\nuse actix::prelude::*;\n\nuse actix_web::server;\n\nuse std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\nuse tokio_socketcan;\n\n\n\nuse vehicle_information_service::{KnownError, Router, Set, SignalManager, UpdateSignal};\n\n\n\nconst PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID: &str = \"Private.Example.SocketCan.Last.Frame.Id\";\n\n\n\nfn main() {\n\n env_logger::init();\n\n\n\n let sys = actix::System::new(\"vis-example\");\n\n\n\n let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 14430);\n\n\n\n server::new(|| {\n\n let app = Router::start();\n\n\n\n let can_id_stream = tokio_socketcan::CANSocket::open(\"vcan0\")\n\n .expect(\"Failed to initialize CanSocket\")\n\n .map(|frame| frame.id());\n\n\n\n app.state()\n\n .spawn_stream_signal_source(PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID.into(), can_id_stream);\n\n })\n\n .bind(socket_addr)\n\n .unwrap()\n\n .start();\n\n\n\n let _ = sys.run();\n\n}\n\n```\n\n\n", "file_path": "vehicle-information-service/README.md", "rank": 73, "score": 33499.02078853562 }, { "content": "## Limitations\n\n- For now this implementation does not support path wildcards.\n\n- The `getMetadata` action is currently unsupported.\n\n- The `authorize` action is currently unsupported.\n\n\n\n# Tests\n\nUnit tests can be executed using\n\n\n\n```\n\ncargo test\n\n```\n\n\n\nIntegration tests are located in the vehicle-information-service-client.\n\nCurrently the server example has to be started manually before running the integration tests.\n\n```\n\ncd vehicle-information-service && cargo run --example server -- --port 14430 --can vcan0 &\n\ncd ../vehicle-information-service-client && cargo test\n\n```\n\n\n\n# Code of Conduct\n\n\n\nPlease read our [Code of Conduct](https://github.com/Daimler/daimler-foss/blob/master/CODE_OF_CONDUCT.md) as it is our base for interaction.\n\n\n\n# Provider Information\n\n\n", "file_path": "vehicle-information-service/README.md", "rank": 74, "score": 33485.64716983569 }, { "content": "# Running\n\nThe \"server\" example demonstrates a simple VIS server that uses [SocketCAN](https://www.kernel.org/doc/html/v4.17/networking/can.html)\n\nas a signal source, as well as a simple counter signal source .\n\nYou may run the example by setting up a vcan and running the example server executable.\n\n\n\n```\n\n# Set up vcan\n\nsudo modprobe vcan && \\\n\n sudo ip link add dev vcan0 type vcan && \\\n\n sudo ip link set up vcan0\n\n\n\n# Run executable\n\nRUST_LOG=debug cargo +nightly run --example server -- --port 14430 --can vcan0\n\n```\n\n\n\n## Websocket Client\n\n```\n\n# Open websocket connection with wscat\n\nwscat -c \"localhost:14430\"\n\n{ \"action\": \"subscribe\", \"path\": \"Private.Example.Interval\", \"requestId\": \"d2c7c1a2-f5aa-4fce-9d34-3323fdf20236\"}\n\n{ \"action\": \"subscribe\", \"path\": \"Private.Example.Interval\", \"requestId\": \"1005\", \"filters\": { \"range\": { \"above\": 5, \"below\": 10 } }}\n\n{ \"action\": \"subscribe\", \"path\": \"Private.Example.Interval\", \"requestId\": \"1006\", \"filters\": { \"minChange\": \"abc\" } }\n\n{ \"action\": \"subscribe\", \"path\": \"Private.Example.Interval\", \"requestId\": \"1007\", \"filters\": { \"interval\": 3, \"range\": { \"above\": 10, \"below\": 20 } } }\n\n{ \"action\": \"unsubscribe\", \"subscriptionId\": \"4afdcdce-d5f9-48de-8f8e-1250e53b2dcd\", \"requestId\": \"1008\"}\n\n{ \"action\": \"unsubscribeAll\", \"requestId\": \"1009\"}\n\n{ \"action\": \"get\", \"path\": \"Private.Example.Interval\", \"requestId\": \"1010\"}\n\n{ \"action\": \"get\", \"path\": \"Private.Example.SocketCan.Last.Frame.Id\", \"requestId\": \"1011\"}\n\n{ \"action\": \"subscribe\", \"path\": \"Private.Example.SocketCan.Last.Frame.Id\", \"requestId\": \"1012\"}\n\n```\n\n\n\n## Output\n\n```\n\n$ wscat -c \"localhost:14430\"\n\n\n\nconnected (press CTRL+C to quit)\n\n> { \"action\": \"subscribe\", \"path\": \"Private.Example.Interval\", \"requestId\": \"1004\"}\n\n\n\n< {\"action\":\"subscribe\",\"requestId\":\"1004\",\"subscriptionId\":\"2b1c7a38-0c6d-4eb3-a5cb-352245bfd596\",\"timestamp\":1511351899913}\n\n\n\n< {\"action\":\"subscriptionNotification\",\"subscriptionId\":\"2b1c7a38-0c6d-4eb3-a5cb-352245bfd596\",\"value\": 1, \"timestamp\":1511351902760}\n\n```\n\n\n", "file_path": "vehicle-information-service/README.md", "rank": 75, "score": 33482.276091020605 }, { "content": "The MIT License\n\n\n\nCopyright (c) 2019 Daimler TSS GmbH\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in\n\nall copies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", "file_path": "vehicle-information-service/LICENSE.md", "rank": 76, "score": 33468.96570295048 }, { "content": "# Vehicle Information Service Client\n\n\n\n[![Build Status](https://travis-ci.org/Daimler/vehicle-information-service.svg?branch=master)](https://travis-ci.org/Daimler/vehicle-information-service)\n\n\n\nThis is a client implementation for the [Vehicle Information Service standard](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html).\n\n\n\n# NOTICE\n\n\n\nBefore you use the program in productive use, please take all necessary precautions,\n\ne.g. testing and verifying the program with regard to your specific use.\n\nThe program was tested solely for our own use cases, which might differ from yours.\n\n\n\n# Example\n\nThe \"get\"-example will run a get request, asking for the value of \"Private.Example.Interval\".\n\nMake sure the vehicle-communication-service example server is running and run.\n\n```\n\ncargo run --example get\n\n\n\n> cargo run --example get\n\n Finished dev [unoptimized + debuginfo] target(s) in 0.27s\n\n Running `/tmp/vehicle-information-service/target/debug/examples/get`\n\nInterval: 1\n\n```\n\n\n\n# Code of Conduct\n\n\n\nPlease read our [Code of Conduct](https://github.com/Daimler/daimler-foss/blob/master/CODE_OF_CONDUCT.md) as it is our base for interaction.\n\n\n\n# Provider Information\n\n\n", "file_path": "vehicle-information-service-client/README.md", "rank": 77, "score": 32766.524165959287 }, { "content": "The MIT License\n\n\n\nCopyright (c) 2019 Daimler TSS GmbH\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in\n\nall copies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", "file_path": "vehicle-information-service-client/LICENSE.md", "rank": 78, "score": 32753.814847981794 }, { "content": "# Vehicle Information Service\n\n\n\n[![Build Status](https://travis-ci.org/Daimler/vehicle-information-service.svg?branch=master)](https://travis-ci.org/Daimler/vehicle-information-service)\n\n\n\nThis is an implementation of the [Vehicle Information Service standard](https://w3c.github.io/automotive/vehicle_data/vehicle_information_service.html).\n\n\n\n# NOTICE\n\n\n\nBefore you use the program in productive use, please take all necessary precautions,\n\ne.g. testing and verifying the program with regard to your specific use.\n\nThe program was tested solely for our own use cases, which might differ from yours.\n\n\n\n# Code of Conduct\n\n\n\nPlease read our [Code of Conduct](https://github.com/Daimler/daimler-foss/blob/master/CODE_OF_CONDUCT.md) as it is our base for interaction.\n\n\n\n# Provider Information\n\n\n\nPlease visit <https://www.daimler-tss.com/en/imprint/> for information on the provider.\n", "file_path": "README.md", "rank": 79, "score": 32270.35029337712 }, { "content": "The MIT License\n\n\n\nCopyright (c) 2019 Daimler TSS GmbH\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\n\nof this software and associated documentation files (the \"Software\"), to deal\n\nin the Software without restriction, including without limitation the rights\n\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\ncopies of the Software, and to permit persons to whom the Software is\n\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in\n\nall copies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n", "file_path": "LICENSE.md", "rank": 80, "score": 32259.14655187828 }, { "content": "// SPDX-License-Identifier: MIT\n\n\n\n//!\n\n//! For more examples check the Github repositories `examples/` folder.\n\n//!\n\n//! Example:\n\n//! ```rust,no_run\n\n//!\n\n//! #[macro_use]\n\n//! extern crate log;\n\n//!\n\n//! use actix::prelude::*;\n\n//! use actix_web::{middleware, web, App, HttpResponse, HttpServer};\n\n//! use futures::stream::Stream;\n\n//! use futures_util::try_stream::TryStreamExt;\n\n//! use futures_util::compat::Stream01CompatExt;\n\n//! use std::net::{IpAddr, Ipv4Addr, SocketAddr};\n\n//! use tokio_socketcan;\n\n//!\n\n//! use vehicle_information_service::{AppState, KnownError, Router, Set, SignalManager, UpdateSignal};\n", "file_path": "vehicle-information-service/src/lib.rs", "rank": 81, "score": 12176.412389616327 }, { "content": "extern crate log;\n\n#[macro_use]\n\nextern crate serde_derive;\n\n\n\nmod action;\n\npub mod api_error;\n\npub mod api_type;\n\nmod filter;\n\nmod router;\n\nmod signal_manager;\n\n\n\npub use action::set::Set;\n\npub use api_error::KnownError;\n\npub use api_type::ActionPath;\n\npub use router::{AppState, Router};\n\npub use signal_manager::{SignalManager, UpdateSignal};\n\n\n\nuse serde_json::to_string;\n\nuse std::time::{Duration, SystemTime, UNIX_EPOCH};\n\n\n\nuse crate::api_error::ActionErrorResponse;\n\nuse crate::api_type::ActionSuccessResponse;\n\n\n\npub(crate) fn unix_timestamp() -> Option<Duration> {\n\n SystemTime::now().duration_since(UNIX_EPOCH).ok()\n\n}\n\n\n", "file_path": "vehicle-information-service/src/lib.rs", "rank": 82, "score": 12176.15779094486 }, { "content": "//!\n\n//! App::new()\n\n//! .data(app_state)\n\n//! .wrap(middleware::Logger::default())\n\n//! .configure(Router::configure_routes)\n\n//! .default_service(web::route().to(|| HttpResponse::NotFound()))\n\n//! })\n\n//! .bind(socket_addr)\n\n//! .unwrap()\n\n//! .start();\n\n//!\n\n//! let _ = sys.run();\n\n//! }\n\n//!```\n\n//!\n\n\n\n#![deny(clippy::all)]\n\n#![feature(async_await, allow_fail)]\n\n\n\n#[macro_use]\n", "file_path": "vehicle-information-service/src/lib.rs", "rank": 83, "score": 12165.420143289142 }, { "content": "//!\n\n//! const PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID: &str = \"Private.Example.SocketCan.Last.Frame.Id\";\n\n//!\n\n//! fn main() {\n\n//! env_logger::init();\n\n//!\n\n//! let sys = actix::System::new(\"vis-example\");\n\n//!\n\n//! let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 14430);\n\n//!\n\n//! HttpServer::new(move || {\n\n//! let app_state: AppState = Default::default();\n\n//!\n\n//! let can_id_stream = tokio_socketcan::CANSocket::open(\"vcan0\")\n\n//! .expect(\"Failed to initialize CanSocket\")\n\n//! .compat()\n\n//! .map_ok(|frame| frame.id());\n\n//!\n\n//! app_state\n\n//! .spawn_stream_signal_source(PATH_PRIVATE_EXAMPLE_SOCKETCAN_LAST_FRAME_ID.into(), can_id_stream);\n", "file_path": "vehicle-information-service/src/lib.rs", "rank": 84, "score": 12161.252538500437 }, { "content": " self.0\n\n .as_i64()\n\n .unwrap_or_default()\n\n .partial_cmp(&other.0.as_i64().unwrap_or_default())\n\n } else {\n\n self.0\n\n .as_f64()\n\n .as_ref()\n\n .and_then(|x| other.0.as_f64().as_ref().and_then(|y| x.partial_cmp(y)))\n\n }\n\n }\n\n}\n\n\n\nimpl Ord for SerdeNumber {\n\n fn cmp(&self, other: &Self) -> Ordering {\n\n self.partial_cmp(other).unwrap_or(Ordering::Equal)\n\n }\n\n}\n\n\n\nimpl Sub for SerdeNumber {\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 85, "score": 12160.821779628477 }, { "content": "// SPDX-License-Identifier: MIT\n\n\n\nuse crate::api_type::Filters;\n\nuse serde_json::{Number, Value};\n\nuse std::cmp::{Ord, Ordering};\n\nuse std::ops::Sub;\n\nuse std::time::{Duration, SystemTime};\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::api_type::{FilterRange, Filters};\n\n use crate::filter;\n\n use crate::filter::{\n\n interval, is_in_filter_range, is_min_change, value_as_number, SerdeNumber,\n\n };\n\n use serde_json::{json, Value};\n\n use std::time::{Duration, SystemTime};\n\n\n\n #[test]\n\n fn value_as_number_ok_when_int() {\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 86, "score": 12159.77963544747 }, { "content": " if self.0.is_u64() && other.0.is_u64() {\n\n self.0.as_u64() == other.0.as_u64()\n\n } else if self.0.is_i64() && other.0.is_i64() {\n\n self.0.as_i64() == other.0.as_i64()\n\n } else {\n\n self.0.as_f64() == other.0.as_f64()\n\n }\n\n }\n\n}\n\n\n\nimpl Eq for SerdeNumber {}\n\n\n\nimpl PartialOrd for SerdeNumber {\n\n fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n\n if self.0.is_u64() && other.0.is_u64() {\n\n self.0\n\n .as_u64()\n\n .unwrap_or_default()\n\n .partial_cmp(&other.0.as_u64().unwrap_or_default())\n\n } else if self.0.is_i64() && other.0.is_i64() {\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 87, "score": 12158.95927384218 }, { "content": " type Output = Self;\n\n\n\n #[allow(clippy::suspicious_arithmetic_impl)]\n\n fn sub(self, other: Self) -> Self {\n\n if self.0.is_u64() && other.0.is_u64() {\n\n Self(\n\n (self\n\n .0\n\n .as_u64()\n\n .unwrap_or_default()\n\n .wrapping_sub(other.0.as_u64().unwrap_or_default()))\n\n .into(),\n\n )\n\n } else if self.0.is_i64() && other.0.is_i64() {\n\n Self(\n\n (self\n\n .0\n\n .as_i64()\n\n .unwrap_or_default()\n\n .wrapping_sub(other.0.as_i64().unwrap_or_default()))\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 88, "score": 12158.318543747513 }, { "content": " let later = now.clone() + Duration::from_secs(10);\n\n assert!(interval(\n\n later,\n\n &Some((now, Value::String(\"a\".to_owned()))),\n\n &f,\n\n ));\n\n }\n\n\n\n #[test]\n\n fn interval_false_when_duration_to_last_val_smaller_than_interval() {\n\n let f = Filters {\n\n interval: Some(1000000),\n\n range: None,\n\n min_change: None,\n\n };\n\n let now = SystemTime::now();\n\n let later = now.clone() + Duration::from_millis(10);\n\n assert!(!interval(later, &Some((now, Value::Null)), &f));\n\n }\n\n\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 89, "score": 12156.16111699311 }, { "content": " min_change: None,\n\n });\n\n assert_eq!(\n\n Ok(false),\n\n filter::matches(\n\n &Value::String(\"a\".to_owned()),\n\n &Some((SystemTime::now(), Value::String(\"a\".to_owned()))),\n\n &f,\n\n )\n\n );\n\n }\n\n\n\n #[test]\n\n fn matches_filter_false_when_no_filter_set_and_value_not_changed() {\n\n let last_val = &Some((SystemTime::now(), Value::Number(100.into())));\n\n let filter = None;\n\n assert_eq!(\n\n Ok(false),\n\n filter::matches(&Value::Number(100.into()), last_val, &filter,)\n\n );\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 90, "score": 12155.893119672275 }, { "content": " let f = Some(Filters {\n\n interval: None,\n\n range: None,\n\n min_change: None,\n\n });\n\n assert_eq!(\n\n Ok(true),\n\n filter::matches(\n\n &Value::String(\"a\".to_owned()),\n\n &Some((SystemTime::now(), Value::String(\"b\".to_owned()))),\n\n &f,\n\n )\n\n );\n\n }\n\n\n\n #[test]\n\n fn matches_filter_false_when_string_unchanged() {\n\n let f = Some(Filters {\n\n interval: None,\n\n range: None,\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 91, "score": 12155.544982430498 }, { "content": " .into(),\n\n )\n\n } else {\n\n Self(\n\n Number::from_f64(\n\n self.0\n\n .as_f64()\n\n .unwrap_or_default()\n\n .abs()\n\n .sub(other.0.as_f64().unwrap_or_default().abs()),\n\n )\n\n .unwrap_or_else(|| 0.into()),\n\n )\n\n }\n\n }\n\n}\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 92, "score": 12155.033969756552 }, { "content": " min_change: None,\n\n },\n\n )\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_in_filter_range_true_when_no_filter_set() {\n\n let fr = FilterRange {\n\n below: None,\n\n above: None,\n\n };\n\n assert_eq!(\n\n Ok(true),\n\n is_in_filter_range(\n\n &json!(100),\n\n &Filters {\n\n interval: None,\n\n range: Some(fr),\n\n min_change: None,\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 93, "score": 12154.504944692326 }, { "content": " },\n\n )\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_in_filter_range_true_when_above_and_below_set() {\n\n let fr = FilterRange {\n\n below: Some(120.into()),\n\n above: Some(100.into()),\n\n };\n\n assert_eq!(\n\n Ok(true),\n\n is_in_filter_range(\n\n &json!(110),\n\n &Filters {\n\n interval: None,\n\n range: Some(fr),\n\n min_change: None,\n\n },\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 94, "score": 12154.054869641763 }, { "content": " );\n\n }\n\n\n\n #[test]\n\n fn is_in_filter_range_false_when_above_and_below_set_float_signal() {\n\n let fr = FilterRange {\n\n below: Some(120.into()),\n\n above: Some(115.into()),\n\n };\n\n assert_eq!(\n\n Ok(false),\n\n is_in_filter_range(\n\n &json!(110.0),\n\n &Filters {\n\n interval: None,\n\n range: Some(fr),\n\n min_change: None,\n\n },\n\n )\n\n );\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 95, "score": 12153.935490600848 }, { "content": " )\n\n );\n\n }\n\n\n\n #[test]\n\n fn is_in_filter_range_true_when_above_and_below_set_float_signal() {\n\n let fr = FilterRange {\n\n below: Some(120.into()),\n\n above: Some(100.into()),\n\n };\n\n assert_eq!(\n\n Ok(true),\n\n is_in_filter_range(\n\n &json!(110.0),\n\n &Filters {\n\n interval: None,\n\n range: Some(fr),\n\n min_change: None,\n\n },\n\n )\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 96, "score": 12153.935490600848 }, { "content": " }\n\n\n\n #[test]\n\n fn matches_filter_true_when_no_filter_set_and_value_changed() {\n\n let last_val = &Some((SystemTime::now(), Value::Number(100.into())));\n\n let filter = None;\n\n assert_eq!(\n\n Ok(true),\n\n filter::matches(&Value::Number(101.into()), last_val, &filter,)\n\n );\n\n }\n\n\n\n #[test]\n\n fn interval_true_when_duration_to_last_val_greater_than_interval() {\n\n let f = Filters {\n\n interval: Some(100),\n\n range: None,\n\n min_change: None,\n\n };\n\n let now = SystemTime::now();\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 97, "score": 12153.334220097055 }, { "content": " Ok(true),\n\n filter::matches(&json!(100.1), &Some((SystemTime::now(), json!(106.7))), &f,)\n\n );\n\n }\n\n\n\n #[test]\n\n fn matches_filter_false_when_float_unchanged() {\n\n let f = Some(Filters {\n\n interval: None,\n\n range: None,\n\n min_change: Some(5.into()),\n\n });\n\n assert_eq!(\n\n Ok(false),\n\n filter::matches(&json!(100.1), &Some((SystemTime::now(), json!(100.5))), &f,)\n\n );\n\n }\n\n\n\n #[test]\n\n fn matches_filter_true_when_string_changed() {\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 98, "score": 12153.220380372795 }, { "content": " #[test]\n\n fn serde_number_eq() {\n\n assert_eq!(SerdeNumber(1.into()), SerdeNumber(1.into()));\n\n assert!(SerdeNumber(1.into()) != SerdeNumber(100.into()));\n\n let u: i64 = -100;\n\n assert!(SerdeNumber(u.into()).abs() == SerdeNumber(100.into()));\n\n assert!((SerdeNumber(u.into()) - SerdeNumber(u.into())).abs() == SerdeNumber(0.into()));\n\n assert!(SerdeNumber(u.into()).abs() >= SerdeNumber(100.into()));\n\n assert!(SerdeNumber(u.into()).abs() > SerdeNumber(50.into()));\n\n }\n\n}\n\n\n\n#[derive(Eq, PartialEq, Debug)]\n\npub enum Error {\n\n ValueIsNotANumber,\n\n}\n\n\n\n///\n\n/// Does the val match the filter criteria\n\n/// Returns:\n\n/// Ok(true) : E.g. value changed sufficiently or there was no filter set\n\n/// Ok(false) : Did not reach change threshold\n\n/// Err(...): Occurs when the value is not an integer, filters only work for ints\n\n///\n", "file_path": "vehicle-information-service/src/filter.rs", "rank": 99, "score": 12152.722391806084 } ]
Rust
tests/common/mod.rs
jedel1043/regress
2c3de40bc72b1875b47fdca77b23a4c6ce22c6f9
pub fn test_parse_fails(pattern: &str) { let res = regress::Regex::new(pattern); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } pub fn test_parse_fails_flags(pattern: &str, flags: &str) { let res = regress::Regex::with_flags(pattern, flags); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } fn format_match(r: &regress::Match, input: &str) -> String { let mut result = input[r.range()].to_string(); for cg in r.captures.iter() { result.push(','); if let Some(cg) = cg { result.push_str(&input[cg.clone()]) } } result } pub trait StringTestHelpers { fn test_eq(&self, s: &str); } impl StringTestHelpers for String { fn test_eq(&self, rhs: &str) { assert_eq!(self.as_str(), rhs) } } pub trait VecTestHelpers { fn test_eq(&self, rhs: Vec<&str>); } impl VecTestHelpers for Vec<&str> { fn test_eq(&self, rhs: Vec<&str>) { assert_eq!(*self, rhs) } } #[derive(Debug, Clone)] pub struct TestCompiledRegex { re: regress::Regex, tc: TestConfig, } impl TestCompiledRegex { pub fn matches(&'_ self, input: &'_ str, start: usize) -> Vec<regress::Match> { use regress::backends as rbe; match (self.tc.use_ascii(input), self.tc.backend) { (true, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (false, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (true, Backend::Backtracking) => { rbe::find_ascii::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } (false, Backend::Backtracking) => { rbe::find::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } } } pub fn find(&self, input: &str) -> Option<regress::Match> { self.matches(input, 0).into_iter().next() } pub fn match1f(&self, input: &str) -> String { match self.find(input) { Some(m) => format_match(&m, input), None => panic!("Failed to match {}", input), } } pub fn match1_named_group(&self, input: &str, group: &str) -> String { match self.find(input) { Some(m) => match m.named_group(group) { Some(r) => match input.get(r.clone()) { Some(str) => str.to_string(), None => panic!("Cannot get range from string input {:?}", r), }, None => panic!("Named capture group does not exist {}", group), }, None => panic!("Failed to match {}", input), } } pub fn match1_vec<'a, 'b>(&'a self, input: &'b str) -> Vec<Option<&'b str>> { let mut result = Vec::new(); let m: regress::Match = self.find(input).expect("Failed to match"); result.push(Some(&input[m.range()])); for cr in m.captures { result.push(cr.map(|r| &input[r])); } result } pub fn test_fails(&self, input: &str) { assert!(self.find(input).is_none(), "Should not have matched") } pub fn test_succeeds(&self, input: &str) { assert!(self.find(input).is_some(), "Should have matched") } pub fn match_all_from(&'_ self, input: &'_ str, start: usize) -> Vec<regress::Range> { self.matches(input, start) .into_iter() .map(move |m| m.range()) .collect() } pub fn match_all<'a, 'b>(&'a self, input: &'b str) -> Vec<&'b str> { self.matches(input, 0) .into_iter() .map(move |m| &input[m.range()]) .collect() } pub fn run_global_match(&self, input: &str) -> String { self.matches(input, 0) .into_iter() .map(move |m| format_match(&m, input)) .collect::<Vec<String>>() .join(",") } } #[derive(Debug, Copy, Clone)] enum Backend { PikeVM, Backtracking, } #[derive(Debug, Copy, Clone)] pub struct TestConfig { ascii: bool, optimize: bool, backend: Backend, } impl TestConfig { pub fn use_ascii(&self, s: &str) -> bool { self.ascii && s.is_ascii() } pub fn compile(&self, pattern: &str) -> TestCompiledRegex { self.compilef(pattern, "") } pub fn compilef(&self, pattern: &str, flags_str: &str) -> TestCompiledRegex { let mut flags = regress::Flags::from(flags_str); flags.no_opt = !self.optimize; let re = regress::Regex::with_flags(pattern, flags); assert!( re.is_ok(), "Failed to parse! flags: {} pattern: {}, error: {}", flags_str, pattern, re.unwrap_err() ); TestCompiledRegex { re: re.unwrap(), tc: *self, } } pub fn test_match_succeeds(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_succeeds(input) } pub fn test_match_fails(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_fails(input) } } pub fn test_with_configs<F>(func: F) where F: Fn(TestConfig), { func(TestConfig { ascii: true, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: true, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: true, optimize: true, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: true, backend: Backend::Backtracking, }); }
pub fn test_parse_fails(pattern: &str) { let res = regress::Regex::new(pattern); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } pub fn test_parse_fails_flags(pattern: &str, flags: &str) { let res = regress::Regex::with_flags(pattern, flags); assert!(res.is_err(), "Pattern should not have parsed: {}", pattern); } fn format_match(r: &regress::Match, input: &str) -> String { let mut result = input[r.range()].to_string(); for cg in r.captures.iter() { result.push(','); if let Some(cg) = cg { result.push_str(&input[cg.clone()]) } } result } pub trait StringTestHelpers { fn test_eq(&self, s: &str); } impl StringTestHelpers for String { fn test_eq(&self, rhs: &str) { assert_eq!(self.as_str(), rhs) } } pub trait VecTestHelpers { fn test_eq(&self, rhs: Vec<&str>); } impl VecTestHelpers for Vec<&str> { fn test_eq(&self, rhs: Vec<&str>) { assert_eq!(*self, rhs) } } #[derive(Debug, Clone)] pub struct TestCompiledRegex { re: regress::Regex, tc: TestConfig, } impl TestCompiledRegex { pub fn matches(&'_ self, input: &'_ str, start: usize) -> Vec<regress::Match> { use regress::backends as rbe; match (self.tc.use_ascii(input), self.tc.backend) { (true, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (false, Backend::PikeVM) => { rbe::find::<rbe::PikeVMExecutor>(&self.re, input, start).collect() } (true, Backend::Backtracking) => { rbe::find_ascii::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } (false, Backend::Backtracking) => { rbe::find::<rbe::BacktrackExecutor>(&self.re, input, start).collect() } } } pub fn find(&self, input: &str) -> Option<regress::Match> { self.matches(input, 0).into_iter().next() } pub fn match1f(&self, input: &str) -> String { match self.find(input) { Some(m) => format_match(&m, input), None => panic!("Failed to match {}", input), } } pub fn match1_named_group(&self, input: &str, group: &str) -> String { match self.find(input) { Some(m) => match m.named_group(group) {
pub fn match1_vec<'a, 'b>(&'a self, input: &'b str) -> Vec<Option<&'b str>> { let mut result = Vec::new(); let m: regress::Match = self.find(input).expect("Failed to match"); result.push(Some(&input[m.range()])); for cr in m.captures { result.push(cr.map(|r| &input[r])); } result } pub fn test_fails(&self, input: &str) { assert!(self.find(input).is_none(), "Should not have matched") } pub fn test_succeeds(&self, input: &str) { assert!(self.find(input).is_some(), "Should have matched") } pub fn match_all_from(&'_ self, input: &'_ str, start: usize) -> Vec<regress::Range> { self.matches(input, start) .into_iter() .map(move |m| m.range()) .collect() } pub fn match_all<'a, 'b>(&'a self, input: &'b str) -> Vec<&'b str> { self.matches(input, 0) .into_iter() .map(move |m| &input[m.range()]) .collect() } pub fn run_global_match(&self, input: &str) -> String { self.matches(input, 0) .into_iter() .map(move |m| format_match(&m, input)) .collect::<Vec<String>>() .join(",") } } #[derive(Debug, Copy, Clone)] enum Backend { PikeVM, Backtracking, } #[derive(Debug, Copy, Clone)] pub struct TestConfig { ascii: bool, optimize: bool, backend: Backend, } impl TestConfig { pub fn use_ascii(&self, s: &str) -> bool { self.ascii && s.is_ascii() } pub fn compile(&self, pattern: &str) -> TestCompiledRegex { self.compilef(pattern, "") } pub fn compilef(&self, pattern: &str, flags_str: &str) -> TestCompiledRegex { let mut flags = regress::Flags::from(flags_str); flags.no_opt = !self.optimize; let re = regress::Regex::with_flags(pattern, flags); assert!( re.is_ok(), "Failed to parse! flags: {} pattern: {}, error: {}", flags_str, pattern, re.unwrap_err() ); TestCompiledRegex { re: re.unwrap(), tc: *self, } } pub fn test_match_succeeds(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_succeeds(input) } pub fn test_match_fails(&self, pattern: &str, flags_str: &str, input: &str) { let cr = self.compilef(pattern, flags_str); cr.test_fails(input) } } pub fn test_with_configs<F>(func: F) where F: Fn(TestConfig), { func(TestConfig { ascii: true, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::PikeVM, }); func(TestConfig { ascii: true, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: false, backend: Backend::Backtracking, }); func(TestConfig { ascii: true, optimize: true, backend: Backend::Backtracking, }); func(TestConfig { ascii: false, optimize: true, backend: Backend::Backtracking, }); }
Some(r) => match input.get(r.clone()) { Some(str) => str.to_string(), None => panic!("Cannot get range from string input {:?}", r), }, None => panic!("Named capture group does not exist {}", group), }, None => panic!("Failed to match {}", input), } }
function_block-function_prefix_line
[ { "content": "/// Try parsing a given pattern.\n\n/// Return the resulting IR regex, or an error.\n\npub fn try_parse(pattern: &str, flags: api::Flags) -> Result<ir::Regex, Error> {\n\n // for q in 0..=0x10FFFF {\n\n // if let Some(c) = core::char::from_u32(q) {\n\n // let cc = folds::fold(c);\n\n // if (c as u32) > 127 && (cc as u32) < 127 {\n\n // println!(\"Bad CP: {}\", q);\n\n // }\n\n // }\n\n // }\n\n\n\n let mut p = Parser {\n\n input: pattern.chars().map(u32::from).peekable(),\n\n flags,\n\n loop_count: 0,\n\n group_count: 0,\n\n named_group_indices: HashMap::new(),\n\n group_count_max: 0,\n\n max_backref: 0,\n\n has_lookbehind: false,\n\n };\n\n p.try_parse()\n\n}\n", "file_path": "src/parse.rs", "rank": 2, "score": 193646.50739522176 }, { "content": "fn exec_re_on_string(re: &Regex, input: &str) {\n\n let mut matches = re.find_iter(input);\n\n if let Some(res) = matches.next() {\n\n let count = 1 + matches.count();\n\n println!(\"Match: {}, total: {}\", format_match(&res, input), count);\n\n } else {\n\n println!(\"No match\");\n\n }\n\n}\n\n\n", "file_path": "regress-tool/src/regress-tool.rs", "rank": 3, "score": 193050.00144249352 }, { "content": "fn format_match(r: &regress::Match, input: &str) -> String {\n\n let mut result = input[r.range()].to_string();\n\n for cg in r.captures.iter() {\n\n result.push(',');\n\n if let Some(cg) = cg {\n\n result.push_str(&input[cg.clone()])\n\n }\n\n }\n\n result\n\n}\n\n\n", "file_path": "regress-tool/src/regress-tool.rs", "rank": 4, "score": 192333.10310246565 }, { "content": "/// \\return the start predicate for a Regex.\n\npub fn predicate_for_re(re: &ir::Regex) -> StartPredicate {\n\n compute_start_predicate(&re.node)\n\n .unwrap_or(AbstractStartPredicate::Arbitrary)\n\n .resolve_to_insn()\n\n}\n", "file_path": "src/startpredicate.rs", "rank": 6, "score": 160318.60947423862 }, { "content": "fn non_matching_captures_tc(tc: TestConfig) {\n\n assert_eq!(\n\n tc.compile(\"aa(b)?aa\").match1_vec(\"aaaa\"),\n\n &[Some(\"aaaa\"), None]\n\n );\n\n assert_eq!(\n\n tc.compile(r\"(\\1a)aa\").match1_vec(\"aaa\"),\n\n &[Some(\"aaa\"), Some(\"a\")]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 7, "score": 150904.51740896233 }, { "content": "fn test_zero_length_matches_tc(tc: TestConfig) {\n\n tc.compile(\".*?\").match_all(\"a\").test_eq(vec![\"\", \"\"]);\n\n tc.compile(\".*?\")\n\n .match_all(\"\\u{0251}\")\n\n .test_eq(vec![\"\", \"\"]);\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 8, "score": 146797.59352104724 }, { "content": "fn successful_match<Input: InputIndexer>(\n\n input: Input,\n\n start: Input::Position,\n\n state: &State<Input::Position>,\n\n named_captures: HashMap<String, u16>,\n\n) -> Match {\n\n let group_to_offset = |mr: &GroupData<Input::Position>| -> Option<Range<usize>> {\n\n mr.as_range().map(|r| Range {\n\n start: input.pos_to_offset(r.start),\n\n end: input.pos_to_offset(r.end),\n\n })\n\n };\n\n let captures = state.groups.iter().map(group_to_offset).collect();\n\n Match {\n\n range: input.pos_to_offset(start)..input.pos_to_offset(state.pos),\n\n captures,\n\n named_captures,\n\n }\n\n}\n\n\n", "file_path": "src/pikevm.rs", "rank": 9, "score": 145442.79094616277 }, { "content": "// A helper type that holds a string and allows indexing into it.\n\npub trait InputIndexer: core::fmt::Debug + Copy + Clone\n\nwhere\n\n Self::CharProps: matchers::CharProperties<Element = Self::Element>,\n\n{\n\n /// The char type, typically u8 or char.\n\n type Element: ElementType;\n\n\n\n /// The CharProperties to use for the given element.\n\n type CharProps: matchers::CharProperties<Element = Self::Element>;\n\n\n\n /// A type which references a position in the input string.\n\n type Position: PositionType;\n\n\n\n /// \\return the byte contents.\n\n fn contents(&self) -> &[u8];\n\n\n\n /// \\return the length of the contents, in bytes.\n\n fn bytelength(&self) -> usize {\n\n self.contents().len()\n\n }\n", "file_path": "src/indexing.rs", "rank": 10, "score": 144320.69858540248 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_named_capture_groups_tc(tc: TestConfig) {\n\n // From 262 test/built-ins/RegExp/named-groups/lookbehind.js\n\n tc.compilef(r#\"(?<=(?<a>\\w){3})f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,c\");\n\n tc.compilef(r#\"(?<=(?<a>\\w){4})f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,b\");\n\n tc.compilef(r#\"(?<=(?<a>\\w)+)f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,a\");\n\n tc.compilef(r#\"(?<=(?<a>\\w){6})f\"#, \"\").test_fails(\"abcdef\");\n\n tc.compilef(r#\"((?<=\\w{3}))f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,\");\n\n tc.compilef(r#\"(?<a>(?<=\\w{3}))f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,\");\n\n tc.compilef(r#\"(?<!(?<a>\\d){3})f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,\");\n\n tc.compilef(r#\"(?<!(?<a>\\D){3})f\"#, \"\").test_fails(\"abcdef\");\n\n tc.compilef(r#\"(?<!(?<a>\\D){3})f|f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,\");\n\n tc.compilef(r#\"(?<a>(?<!\\D{3}))f|f\"#, \"\").match1f(\"abcdef\").test_eq(\"f,\");\n\n\n\n // From 262 test/built-ins/RegExp/named-groups/non-unicode-match.js\n\n tc.compilef(r#\"(?<a>a)\"#, \"\").match1f(\"bab\").test_eq(\"a,a\");\n\n tc.compilef(r#\"(?<a42>a)\"#, \"\").match1f(\"bab\").test_eq(\"a,a\");\n\n tc.compilef(r#\"(?<_>a)\"#, \"\").match1f(\"bab\").test_eq(\"a,a\");\n\n tc.compilef(r#\"(?<$>a)\"#, \"\").match1f(\"bab\").test_eq(\"a,a\");\n\n tc.compilef(r#\".(?<$>a).\"#, \"\").match1f(\"bab\").test_eq(\"bab,a\");\n\n tc.compilef(r#\".(?<a>a)(.)\"#, \"\").match1f(\"bab\").test_eq(\"bab,a,b\");\n", "file_path": "tests/tests.rs", "rank": 11, "score": 143018.9879746474 }, { "content": "#[derive(Debug)]\n\nstruct MatchAttempter<'a, Input: InputIndexer> {\n\n states: Vec<State<Input::Position>>,\n\n re: &'a CompiledRegex,\n\n}\n\n\n\nimpl<'a, Input: InputIndexer> MatchAttempter<'a, Input> {\n\n fn new(re: &'a CompiledRegex) -> Self {\n\n Self {\n\n states: Vec::new(),\n\n re,\n\n }\n\n }\n\n\n\n fn try_at_pos<Dir: Direction>(\n\n &mut self,\n\n input: Input,\n\n init_state: &mut State<Input::Position>,\n\n dir: Dir,\n\n ) -> bool {\n\n debug_assert!(self.states.is_empty(), \"Should be no states\");\n", "file_path": "src/pikevm.rs", "rank": 12, "score": 141797.0362069356 }, { "content": "#[derive(Debug)]\n\nstruct MatchAttempter<'a, Input: InputIndexer> {\n\n re: &'a CompiledRegex,\n\n bts: Vec<BacktrackInsn<Input>>,\n\n s: State<Input::Position>,\n\n}\n\n\n\nimpl<'a, Input: InputIndexer> MatchAttempter<'a, Input> {\n\n fn new(re: &'a CompiledRegex, entry: Input::Position) -> Self {\n\n Self {\n\n re,\n\n bts: vec![BacktrackInsn::Exhausted],\n\n s: State {\n\n loops: vec![LoopData::new(entry); re.loops as usize],\n\n groups: vec![GroupData::new(); re.groups as usize],\n\n },\n\n }\n\n }\n\n\n\n #[inline(always)]\n\n fn push_backtrack(&mut self, bt: BacktrackInsn<Input>) {\n", "file_path": "src/classicalbacktrack.rs", "rank": 13, "score": 141797.0362069356 }, { "content": "pub fn optimize(r: &mut Regex) {\n\n run_pass(r, &mut simplify_brackets);\n\n loop {\n\n let mut changed = false;\n\n changed |= run_pass(r, &mut decat);\n\n if r.flags.icase {\n\n changed |= run_pass(r, &mut unfold_icase_chars);\n\n }\n\n changed |= run_pass(r, &mut unroll_loops);\n\n changed |= run_pass(r, &mut promote_1char_loops);\n\n changed |= run_pass(r, &mut form_literal_bytes);\n\n changed |= run_pass(r, &mut remove_empties);\n\n if !changed {\n\n break;\n\n }\n\n }\n\n}\n", "file_path": "src/optimizer.rs", "rank": 15, "score": 139881.01173630363 }, { "content": "fn test_1_error(pattern: &str, expected_err: &str) {\n\n let res = regress::Regex::new(pattern);\n\n assert!(res.is_err(), \"Pattern should not have parsed: {}\", pattern);\n\n\n\n let err = res.err().unwrap().text;\n\n assert!(\n\n err.contains(expected_err),\n\n \"Error text '{}' did not contain '{}' for pattern '{}'\",\n\n err,\n\n expected_err,\n\n pattern\n\n );\n\n}\n\n\n", "file_path": "tests/syntax_error_tests.rs", "rank": 16, "score": 139720.59465240277 }, { "content": "// Fold every character in \\p input, then find all the prefolds.\n\npub fn fold_code_points(mut input: CodePointSet) -> CodePointSet {\n\n let mut folded = input.clone();\n\n for iv in input.intervals() {\n\n fold_interval(*iv, &mut folded)\n\n }\n\n\n\n // Reuse input storage.\n\n input.clone_from(&folded);\n\n for iv in folded.intervals() {\n\n unfold_interval(*iv, &mut input);\n\n }\n\n input\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub struct PropertyEscape {\n\n pub name: Option<UnicodePropertyName>,\n\n pub value: UnicodePropertyValue,\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub enum UnicodePropertyName {\n\n GeneralCategory,\n\n Script,\n\n ScriptExtensions,\n\n}\n\n\n", "file_path": "src/unicode.rs", "rank": 17, "score": 139011.7549331549 }, { "content": "#[inline(always)]\n\npub fn try_match_lit<Input: InputIndexer, Dir: Direction, Bytes: ByteSeq>(\n\n input: &Input,\n\n dir: Dir,\n\n pos: &mut Input::Position,\n\n bytes: &Bytes,\n\n) -> bool {\n\n let len = Bytes::LENGTH;\n\n debug_assert!(len > 0, \"Should not have zero length\");\n\n if let Some(subr_slice) = try_slice(input, dir, pos, len) {\n\n bytes.equals_known_len(subr_slice)\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "src/cursor.rs", "rank": 18, "score": 136484.387362096 }, { "content": "/// Check whether the \\p orig_range within \\p cursor matches position \\p pos.\n\npub fn backref<Input: InputIndexer, Dir: Direction>(\n\n input: &Input,\n\n dir: Dir,\n\n orig_range: core::ops::Range<Input::Position>,\n\n pos: &mut Input::Position,\n\n) -> bool {\n\n cursor::subrange_eq(input, dir, pos, orig_range.start, orig_range.end)\n\n}\n\n\n", "file_path": "src/matchers.rs", "rank": 19, "score": 135009.4349544033 }, { "content": "#[inline(always)]\n\npub fn next<Input: InputIndexer, Dir: Direction>(\n\n input: &Input,\n\n _dir: Dir,\n\n pos: &mut Input::Position,\n\n) -> Option<Input::Element> {\n\n if Dir::FORWARD {\n\n input.next_right(pos)\n\n } else {\n\n input.next_left(pos)\n\n }\n\n}\n\n\n\n/// \\return the next *byte*, or None if at the end, updating the position.\n\n/// Note this may break UTF8 sequences.\n", "file_path": "src/cursor.rs", "rank": 20, "score": 135004.17361551322 }, { "content": "/// If the subrange [start, end) is byte-for-byte equal to a range of the same length starting (if FORWARD is true) or ending (if FORWARD\n\n/// is false) at \\p pos, then return true and then advance (or retreat) the position.\n\n/// On failure, return false and the position is unspecified.\n\npub fn subrange_eq<Input: InputIndexer, Dir: Direction>(\n\n input: &Input,\n\n dir: Dir,\n\n pos: &mut Input::Position,\n\n start: Input::Position,\n\n end: Input::Position,\n\n) -> bool {\n\n if let Some(subr_slice) = try_slice(input, dir, pos, end - start) {\n\n subr_slice == input.slice(start, end)\n\n } else {\n\n false\n\n }\n\n}\n\n\n\n/// \\return the next character, updating the position.\n", "file_path": "src/cursor.rs", "rank": 21, "score": 130896.12587344096 }, { "content": "pub fn backref_icase<Input: InputIndexer, Dir: Direction>(\n\n input: &Input,\n\n dir: Dir,\n\n orig_range: core::ops::Range<Input::Position>,\n\n pos: &mut Input::Position,\n\n) -> bool {\n\n let ref_input = input.subinput(orig_range);\n\n let mut ref_pos = if Dir::FORWARD {\n\n ref_input.left_end()\n\n } else {\n\n ref_input.right_end()\n\n };\n\n while let Some(c1) = cursor::next(&ref_input, dir, &mut ref_pos) {\n\n let mut matched = false;\n\n if let Some(c2) = cursor::next(input, dir, pos) {\n\n matched = Input::CharProps::fold_equals(c1, c2)\n\n }\n\n if !matched {\n\n return false;\n\n }\n\n }\n\n true\n\n}\n", "file_path": "src/matchers.rs", "rank": 22, "score": 130885.04627685118 }, { "content": "#[inline(always)]\n\npub fn next_byte<Input: InputIndexer, Dir: Direction>(\n\n input: &Input,\n\n _dir: Dir,\n\n pos: &mut Input::Position,\n\n) -> Option<u8> {\n\n let res;\n\n if Dir::FORWARD {\n\n res = input.peek_byte_right(*pos);\n\n *pos += if res.is_some() { 1 } else { 0 };\n\n } else {\n\n res = input.peek_byte_left(*pos);\n\n *pos -= if res.is_some() { 1 } else { 0 };\n\n }\n\n res\n\n}\n", "file_path": "src/cursor.rs", "rank": 23, "score": 130885.04627685118 }, { "content": "/// A trait for executing a regex.\n\npub trait Executor<'r, 't>: MatchProducer {\n\n /// The ASCII variant.\n\n type AsAscii: Executor<'r, 't>;\n\n\n\n /// Construct a new Executor.\n\n fn new(re: &'r CompiledRegex, text: &'t str) -> Self;\n\n}\n\n\n\n/// A struct which enables iteration over matches.\n\n#[derive(Debug)]\n\npub struct Matches<Producer: MatchProducer> {\n\n mp: Producer,\n\n position: Option<Producer::Position>,\n\n}\n\n\n\nimpl<Producer: MatchProducer> Matches<Producer> {\n\n pub fn new(mp: Producer, start: usize) -> Self {\n\n let position = mp.initial_position(start);\n\n Matches { mp, position }\n\n }\n\n}\n\n\n\nimpl<Producer: MatchProducer> Iterator for Matches<Producer> {\n\n type Item = Match;\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let pos = self.position?;\n\n self.mp.next_match(pos, &mut self.position)\n\n }\n\n}\n", "file_path": "src/exec.rs", "rank": 24, "score": 129702.44300967455 }, { "content": "#[rustfmt::skip]\n\nfn run_pcre_match_tests_config(tc: TestConfig) {\n\n let run1_match = |pattern: &str, flags_str: &str, input: &str| -> String {\n\n let cr = tc.compilef(pattern, flags_str);\n\n cr.match1f(input)\n\n };\n\n\n\n let test_eq = |left: String, right: &str| {\n\n assert_eq!(left.as_str(), right)\n\n };\n\n\n\n test_eq(run1_match(\"abc\", \"i\", \"abc\"), \"abc\"); // \"abc\"\n\n test_eq(run1_match(\"abc\", \"i\", \"defabc\"), \"abc\"); // \"abc\"\n\n test_eq(run1_match(\"abc\", \"i\", \"Aabc\"), \"abc\"); // \"abc\"\n\n test_eq(run1_match(\"abc\", \"i\", \"Adefabc\"), \"abc\"); // \"abc\"\n\n test_eq(run1_match(\"abc\", \"i\", \"ABC\"), \"ABC\"); // \"abc\"\n\n test_eq(run1_match(\"^abc\", \"i\", \"abc\"), \"abc\"); // \"^abc\"\n\n test_eq(run1_match(\"^abc$\", \"i\", \"abc\"), \"abc\"); // \"^abc$\"\n\n test_eq(run1_match(\"cat|dog|elephant\", \"i\", \"this sentence eventually mentions a cat\"), \"cat\"); // \"cat|dog|elephant\"\n\n test_eq(run1_match(\"cat|dog|elephant\", \"i\", \"this sentences rambles on and on for a while and then reaches elephant\"), \"elephant\"); // \"cat|dog|elephant\"\n\n test_eq(run1_match(\"cat|dog|elephant\", \"i\", \"this sentence eventually mentions a cat\"), \"cat\"); // \"cat|dog|elephant\"\n", "file_path": "tests/pcre_tests.rs", "rank": 25, "score": 129493.63023062429 }, { "content": "pub fn unicode_property_value_general_category_from_str(\n\n s: &str,\n\n) -> Option<UnicodePropertyValueGeneralCategory> {\n\n use UnicodePropertyValueGeneralCategory::*;\n\n match s {\n\n \"Pe\" | \"Close_Punctuation\" => Some(ClosePunctuation),\n\n \"Pc\" | \"Connector_Punctuation\" => Some(ConnectorPunctuation),\n\n \"cntrl\" | \"Cc\" | \"Control\" => Some(Control),\n\n \"Sc\" | \"Currency_Symbol\" => Some(CurrencySymbol),\n\n \"Pd\" | \"Dash_Punctuation\" => Some(DashPunctuation),\n\n \"digit\" | \"Nd\" | \"Decimal_Number\" => Some(DecimalNumber),\n\n \"Me\" | \"Enclosing_Mark\" => Some(EnclosingMark),\n\n \"Pf\" | \"Final_Punctuation\" => Some(FinalPunctuation),\n\n \"Cf\" | \"Format\" => Some(Format),\n\n \"Pi\" | \"Initial_Punctuation\" => Some(InitialPunctuation),\n\n \"Nl\" | \"Letter_Number\" => Some(LetterNumber),\n\n \"Zl\" | \"Line_Separator\" => Some(LineSeparator),\n\n \"Ll\" | \"Lowercase_Letter\" => Some(LowercaseLetter),\n\n \"Sm\" | \"Math_Symbol\" => Some(MathSymbol),\n\n \"Lm\" | \"Modifier_Letter\" => Some(ModifierLetter),\n", "file_path": "src/unicodetables.rs", "rank": 26, "score": 129230.12661289527 }, { "content": "/// A trait for things that match a single Element.\n\npub trait SingleCharMatcher<Input: InputIndexer, Dir: Direction> {\n\n /// \\return whether we match the character at the given position, advancing\n\n /// the position if so. On a false return, the position is unspecified.\n\n fn matches(&self, input: &Input, dir: Dir, pos: &mut Input::Position) -> bool;\n\n}\n\n\n\n/// Insn::Char\n\npub struct Char<Input: InputIndexer> {\n\n pub c: Input::Element,\n\n}\n\nimpl<Input: InputIndexer, Dir: Direction> SingleCharMatcher<Input, Dir> for Char<Input> {\n\n #[inline(always)]\n\n fn matches(&self, input: &Input, dir: Dir, pos: &mut Input::Position) -> bool {\n\n match cursor::next(input, dir, pos) {\n\n Some(c2) => c2 == self.c,\n\n _ => false,\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/scm.rs", "rank": 27, "score": 128049.13794852265 }, { "content": "/// A helper function for formatting bitmaps, using - ranges.\n\nfn format_bitmap<Func>(name: &str, f: &mut fmt::Formatter<'_>, contains: Func) -> fmt::Result\n\nwhere\n\n Func: Fn(u8) -> bool,\n\n{\n\n write!(f, \"{}[\", name)?;\n\n let mut idx = 0;\n\n let mut maybe_space = \"\";\n\n while idx <= 256 {\n\n // Compute the next value not contained.\n\n let mut end = idx;\n\n while end <= 256 && contains(end as u8) {\n\n end += 1;\n\n }\n\n match end - idx {\n\n 0 => (),\n\n 1 => write!(f, \"{}{}\", maybe_space, idx)?,\n\n _ => write!(f, \"{}{}-{}\", maybe_space, idx, end - 1)?,\n\n };\n\n if end > idx {\n\n maybe_space = \" \";\n", "file_path": "src/bytesearch.rs", "rank": 28, "score": 126417.19847484074 }, { "content": "fn try_match_state<Input: InputIndexer, Dir: Direction>(\n\n re: &CompiledRegex,\n\n input: &Input,\n\n s: &mut State<Input::Position>,\n\n dir: Dir,\n\n) -> StateMatch<Input::Position> {\n\n macro_rules! nextinsn_or_fail {\n\n ($e:expr) => {\n\n if $e {\n\n s.ip += 1;\n\n StateMatch::Continue\n\n } else {\n\n StateMatch::Fail\n\n }\n\n };\n\n }\n\n match &re.insns[s.ip] {\n\n Insn::Goal => StateMatch::Complete,\n\n Insn::JustFail => StateMatch::Fail,\n\n &Insn::Char(c) => match cursor::next(input, dir, &mut s.pos) {\n", "file_path": "src/pikevm.rs", "rank": 29, "score": 123601.98767556023 }, { "content": "pub fn unicode_property_value_from_str(s: &str) -> Option<UnicodePropertyValue> {\n\n if let Some(t) = unicodetables::unicode_property_binary_from_str(s) {\n\n Some(UnicodePropertyValue::Binary(t))\n\n } else if let Some(t) = unicodetables::unicode_property_value_general_category_from_str(s) {\n\n Some(UnicodePropertyValue::GeneralCategory(t))\n\n } else {\n\n unicodetables::unicode_property_value_script_from_str(s).map(UnicodePropertyValue::Script)\n\n }\n\n}\n\n\n\npub(crate) fn is_character_class(c: u32, property_escape: &PropertyEscape) -> bool {\n\n if let Some(c) = char::from_u32(c) {\n\n match property_escape.name {\n\n Some(UnicodePropertyName::GeneralCategory) => match &property_escape.value {\n\n UnicodePropertyValue::GeneralCategory(t) => {\n\n unicodetables::is_property_value_general_category(c, t)\n\n }\n\n _ => false,\n\n },\n\n Some(UnicodePropertyName::Script) => match &property_escape.value {\n", "file_path": "src/unicode.rs", "rank": 30, "score": 123570.21647976997 }, { "content": "pub fn unicode_property_binary_from_str(s: &str) -> Option<UnicodePropertyBinary> {\n\n use UnicodePropertyBinary::*;\n\n match s {\n\n \"Alpha\" | \"Alphabetic\" => Some(Alphabetic),\n\n \"CI\" | \"Case_Ignorable\" => Some(CaseIgnorable),\n\n \"Cased\" => Some(Cased),\n\n \"CWCF\" | \"Changes_When_Casefolded\" => Some(ChangesWhenCasefolded),\n\n \"CWCM\" | \"Changes_When_Casemapped\" => Some(ChangesWhenCasemapped),\n\n \"CWL\" | \"Changes_When_Lowercased\" => Some(ChangesWhenLowercased),\n\n \"CWT\" | \"Changes_When_Titlecased\" => Some(ChangesWhenTitlecased),\n\n \"CWU\" | \"Changes_When_Uppercased\" => Some(ChangesWhenUppercased),\n\n \"DI\" | \"Default_Ignorable_Code_Point\" => Some(DefaultIgnorableCodePoint),\n\n \"Gr_Base\" | \"Grapheme_Base\" => Some(GraphemeBase),\n\n \"Gr_Ext\" | \"Grapheme_Extend\" => Some(GraphemeExtend),\n\n \"IDC\" | \"ID_Continue\" => Some(IDContinue),\n\n \"IDS\" | \"ID_Start\" => Some(IDStart),\n\n \"Math\" => Some(Math),\n\n \"XIDC\" | \"XID_Continue\" => Some(XIDContinue),\n\n \"XIDS\" | \"XID_Start\" => Some(XIDStart),\n\n \"AHex\" | \"ASCII_Hex_Digit\" => Some(ASCIIHexDigit),\n", "file_path": "src/unicodetables.rs", "rank": 31, "score": 123570.21647976995 }, { "content": "pub fn unicode_property_name_from_str(s: &str) -> Option<UnicodePropertyName> {\n\n use UnicodePropertyName::*;\n\n\n\n match s {\n\n \"General_Category\" | \"gc\" => Some(GeneralCategory),\n\n \"Script\" | \"sc\" => Some(Script),\n\n \"Script_Extensions\" | \"scx\" => Some(ScriptExtensions),\n\n _ => None,\n\n }\n\n}\n\n\n\n#[derive(Debug, Copy, Clone)]\n\npub enum UnicodePropertyValue {\n\n Binary(unicodetables::UnicodePropertyBinary),\n\n GeneralCategory(unicodetables::UnicodePropertyValueGeneralCategory),\n\n Script(unicodetables::UnicodePropertyValueScript),\n\n}\n\n\n", "file_path": "src/unicode.rs", "rank": 32, "score": 123570.21647976995 }, { "content": "fn test_lookbehinds_tc(tc: TestConfig) {\n\n tc.compilef(r\"(?<=efg)..\", \"\")\n\n .match1f(\"abcdefghijk123456\")\n\n .test_eq(\"hi\");\n\n tc.compilef(r\"(?<=\\d{3}).*\", \"\")\n\n .match1f(\"abcdefghijk123456\")\n\n .test_eq(\"456\");\n\n tc.test_match_succeeds(r\"(?<=\\d{3}.*)\", \"\", \"abcdefghijk123456\");\n\n tc.compilef(r\"(?<![a-z])..\", \"\")\n\n .match1f(\"abcdefghijk123456\")\n\n .test_eq(\"ab\");\n\n tc.compilef(r\"(?<![a-z])\\d{2}\", \"\")\n\n .match1f(\"abcdefghijk123456\")\n\n .test_eq(\"23\");\n\n tc.compilef(r\"(?<=x{3,4})\\d\", \"\")\n\n .match1f(\"1yxx2xxx3xxxx4xxxxx5xxxxxx6xxxxxxx7xxxxxxxx8\")\n\n .test_eq(\"3\");\n\n tc.compilef(r\"(?<=(?:xx){3})\\d\", \"\")\n\n .match1f(\"1yxx2xxx3xxxx4xxxxx5xxxxxx6xxxxxxx7xxxxxxxx8\")\n\n .test_eq(\"6\");\n", "file_path": "tests/tests.rs", "rank": 33, "score": 123145.51311675785 }, { "content": "fn test_multiline_tc(tc: TestConfig) {\n\n tc.compilef(r\"^abc\", \"\").match1f(\"abc\").test_eq(\"abc\");\n\n tc.compile(r\"^def\").test_fails(\"abc\\ndef\");\n\n tc.compilef(r\"^def\", \"m\").match1f(\"abc\\ndef\").test_eq(\"def\");\n\n tc.compilef(r\"^def\", \"m\")\n\n .match1f(\"abc\\n\\rdef\")\n\n .test_eq(\"def\");\n\n\n\n tc.compile(r\"(a*)^(a*)$\").test_fails(\"aa\\raaa\");\n\n tc.compilef(r\"(a*)^(a*)$\", \"m\")\n\n .match1f(\"aa\\raaa\")\n\n .test_eq(\"aa,,aa\");\n\n tc.compilef(r\"[ab]$\", \"\").match1f(\"a\\rb\").test_eq(\"b\");\n\n tc.compilef(r\"[ab]$\", \"m\").match1f(\"a\\rb\").test_eq(\"a\");\n\n\n\n tc.compilef(r\"^\\d\", \"m\")\n\n .match_all(\"aaa\\n789\\r\\nccc\\r\\n345\")\n\n .test_eq(vec![\"7\", \"3\"]);\n\n tc.compilef(r\"\\d$\", \"m\")\n\n .match_all(\"aaa789\\n789\\r\\nccc10\\r\\n345\")\n\n .test_eq(vec![\"9\", \"9\", \"0\", \"5\"]);\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 34, "score": 123145.51311675785 }, { "content": "fn test_dotall_tc(tc: TestConfig) {\n\n tc.compile(r\".\").test_fails(\"\\n\");\n\n tc.compilef(r\".\", \"s\").match1f(\"\\n\").test_eq(\"\\n\");\n\n\n\n tc.compile(r\".\").test_fails(\"\\r\");\n\n tc.compilef(r\".\", \"s\").match1f(\"\\r\").test_eq(\"\\r\");\n\n\n\n tc.compile(r\".\").test_fails(\"\\u{2028}\");\n\n tc.compilef(r\".\", \"s\")\n\n .match1f(\"\\u{2028}\")\n\n .test_eq(\"\\u{2028}\");\n\n\n\n tc.compile(r\".\").test_fails(\"\\u{2029}\");\n\n tc.compilef(r\".\", \"s\")\n\n .match1f(\"\\u{2029}\")\n\n .test_eq(\"\\u{2029}\");\n\n\n\n tc.compile(\"abc.def\").test_fails(\"abc\\ndef\");\n\n tc.compilef(\"abc.def\", \"s\")\n\n .match1f(\"abc\\ndef\")\n\n .test_eq(\"abc\\ndef\");\n\n\n\n tc.compile(\".*\").match1f(\"abc\\ndef\").test_eq(\"abc\");\n\n tc.compilef(\".*\", \"s\")\n\n .match1f(\"abc\\ndef\")\n\n .test_eq(\"abc\\ndef\");\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 35, "score": 123145.51311675785 }, { "content": "/// Call a function on every Node, which may mutate the node.\n\n/// If \\p postorder is true, then process children before the node;\n\n/// otherwise process children after the node.\n\n/// If postorder is false, the function should return true to process children,\n\n/// false to avoid descending into children. If postorder is true, the return\n\n/// value is ignored.\n\npub fn walk_mut<F>(postorder: bool, n: &mut Node, func: &mut F)\n\nwhere\n\n F: FnMut(&mut Node, &mut Walk),\n\n{\n\n let mut walker = MutWalker {\n\n func,\n\n postorder,\n\n walk: Walk::default(),\n\n };\n\n walker.process(n);\n\n}\n\n\n\n/// A regex in IR form.\n\npub struct Regex {\n\n pub node: Node,\n\n pub flags: api::Flags,\n\n}\n\n\n\nimpl Regex {}\n\n\n", "file_path": "src/ir.rs", "rank": 36, "score": 122676.1231643454 }, { "content": "fn display_node(node: &Node, depth: usize, f: &mut fmt::Formatter) -> fmt::Result {\n\n for _ in 0..depth {\n\n write!(f, \"..\")?;\n\n }\n\n match node {\n\n Node::Empty => {\n\n writeln!(f, \"Empty\")?;\n\n }\n\n Node::Goal => {\n\n writeln!(f, \"Goal\")?;\n\n }\n\n Node::Char { c, icase: _ } => {\n\n writeln!(f, \"'{}'\", &c.to_string())?;\n\n }\n\n Node::ByteSequence(bytes) => {\n\n write!(f, \"ByteSeq{} 0x\", bytes.len())?;\n\n for &b in bytes {\n\n write!(f, \"{:x}\", b)?;\n\n }\n\n writeln!(f)?;\n", "file_path": "src/ir.rs", "rank": 37, "score": 121815.35800439585 }, { "content": "fn run_misc_tests_tc(tc: TestConfig) {\n\n tc.compilef(r\"(a+)(?!(\\1))\", \"\")\n\n .match1f(\"aaaaaa\")\n\n .test_eq(\"aaaaaa,aaaaaa,\");\n\n tc.compilef(r\"\\1(a)\", \"\").match1f(\"aa\").test_eq(\"a,a\"); // see 15.10.2.11_A1_T5 from test262\n\n tc.compilef(r\"((a)|(b))*?c\", \"\")\n\n .match1f(\"abc\")\n\n .test_eq(\"abc,b,,b\");\n\n\n\n tc.compilef(r\"(?=(a+))\", \"\")\n\n .match1f(\"baaabac\")\n\n .test_eq(\",aaa\");\n\n tc.compilef(r\"(?=(a+))a*b\\1\", \"\")\n\n .match1f(\"baaabac\")\n\n .test_eq(\"aba,a\");\n\n assert_eq!(\n\n tc.compile(r\"(.*?)a(?!(a+)b\\2c)\\2(.*)\")\n\n .match1_vec(\"baaabaac\"),\n\n vec![Some(\"baaabaac\"), Some(\"ba\"), None, Some(\"abaac\")]\n\n );\n\n tc.compilef(r\"\\0\", \"\").match1f(\"abc\\0def\").test_eq(\"\\0\");\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 38, "score": 120166.93080029654 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_regexp_tc(tc: TestConfig) {\n\n // From regexp.js\n\n tc.compilef(\"[\\u{0}]\", \"\").match1f(\"[\\u{0}]\").test_eq(\"\\u{0}\");\n\n tc.compilef(\"[\\u{0}]\", \"\").match1f(\"[\\u{0}]\").test_eq(\"\\u{0}\");\n\n tc.compilef(\"^.\", \"m\").run_global_match(\"aA\\nbB\\rcC\\r\\ndD\\u{2028}eE\\u{2029}fF\").test_eq(\"a,b,c,d,e,f\");\n\n tc.compilef(\".$\", \"m\").run_global_match(\"aA\\nbB\\rcC\\r\\ndD\\u{2028}eE\\u{2029}fF\").test_eq(\"A,B,C,D,E,F\");\n\n tc.compilef(\"^[^]\", \"m\").run_global_match(\"aA\\nbB\\rcC\\r\\ndD\\u{2028}eE\\u{2029}fF\").test_eq(\"a,b,c,\\n,d,e,f\");\n\n tc.compilef(\"[^]$\", \"m\").run_global_match(\"aA\\nbB\\rcC\\r\\ndD\\u{2028}eE\\u{2029}fF\").test_eq(\"A,B,C,\\r,D,E,F\");\n\n tc.test_match_succeeds(\"\\\\ca\", \"\", \"\\u{1}\");\n\n tc.compilef(\"\\\\ca\", \"\").test_fails(\"\\\\ca\");\n\n tc.compilef(\"\\\\ca\", \"\").test_fails(\"ca\");\n\n // Skipping Unicode-unsavvy \\c[a/]\n\n // Skipping Unicode-unsavvy \\c[a/]\n\n tc.test_match_succeeds(\"^[\\\\cM]$\", \"\", \"\\r\");\n\n tc.compilef(\"^[\\\\cM]$\", \"\").test_fails(\"M\");\n\n tc.compilef(\"^[\\\\cM]$\", \"\").test_fails(\"c\");\n\n tc.compilef(\"^[\\\\cM]$\", \"\").test_fails(\"\\\\\");\n\n tc.compilef(\"^[\\\\cM]$\", \"\").test_fails(\"\\u{3}\");\n\n // Skipping Unicode-unsavvy ^[\\c]]$\n\n // Skipping Unicode-unsavvy ^[\\c]]$\n", "file_path": "tests/tests.rs", "rank": 39, "score": 120166.93080029654 }, { "content": "#[rustfmt::skip]\n\nfn test_lookbehinds_mjsunit_tc(tc: TestConfig) {\n\n // alternations.js\n\n tc.compilef(r\".*(?<=(..|...|....))(.*)\", \"\").match1f(\"xabcd\").test_eq(\"xabcd,cd,\");\n\n tc.compilef(r\".*(?<=(xx|...|....))(.*)\", \"\").match1f(\"xabcd\").test_eq(\"xabcd,bcd,\");\n\n tc.compilef(r\".*(?<=(xx|...))(.*)\", \"\").match1f(\"xxabcd\").test_eq(\"xxabcd,bcd,\");\n\n tc.compilef(r\".*(?<=(xx|xxx))(.*)\", \"\").match1f(\"xxabcd\").test_eq(\"xxabcd,xx,abcd\");\n\n\n\n // back-references-to-captures.js\n\n tc.compilef(r\"(?<=\\1(\\w))d\", \"i\").match1f(\"abcCd\").test_eq(\"d,C\");\n\n tc.compilef(r\"(?<=\\1([abx]))d\", \"\").match1f(\"abxxd\").test_eq(\"d,x\");\n\n tc.compilef(r\"(?<=\\1(\\w+))c\", \"\").match1f(\"ababc\").test_eq(\"c,ab\");\n\n tc.compilef(r\"(?<=\\1(\\w+))c\", \"i\").match1f(\"ababc\").test_eq(\"c,ab\");\n\n tc.compilef(r\"(?<=\\1(\\w+))c\", \"\").match1f(\"ababbc\").test_eq(\"c,b\");\n\n tc.test_match_fails(r\"(?<=\\1(\\w+))c\", \"\", \"ababdc\");\n\n tc.compilef(r\"(?<=(\\w+)\\1)c\", \"\").match1f(\"ababc\").test_eq(\"c,abab\");\n\n\n\n // back-references.js\n\n tc.compilef(\"(.)(?<=(\\\\1\\\\1))\", \"\").match1f(\"abb\").test_eq(\"b,b,bb\");\n\n tc.compilef(\"(.)(?<=(\\\\1\\\\1))\", \"i\").match1f(\"abB\").test_eq(\"B,B,bB\");\n\n tc.compilef(\"((\\\\w)\\\\w)(?<=\\\\1\\\\2\\\\1)\", \"i\").match1f(\"aabAaBa\").test_eq(\"aB,aB,a\");\n", "file_path": "tests/tests.rs", "rank": 40, "score": 120166.93080029654 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_standalones_tc(tc: TestConfig) {\n\n // From regexp-standalones.js\n\n tc.compilef(r\"^\\d\", \"m\").run_global_match(\"aaa\\n789\\r\\nccc\\r\\n345\").test_eq(\"7,3\");\n\n tc.compilef(r\"\\d$\", \"m\").run_global_match(\"aaa\\n789\\r\\nccc\\r\\n345\").test_eq(\"9,5\");\n\n\n\n tc.compilef(r\"^\\d\", \"m\").run_global_match(\"aaa\\n789\\r\\nccc\\r\\nddd\").test_eq(\"7\");\n\n tc.compilef(r\"\\d$\", \"m\").run_global_match(\"aaa\\n789\\r\\nccc\\r\\nddd\").test_eq(\"9\");\n\n\n\n tc.compilef(r\"[\\S]+\", \"\").match1f(\"\\u{00BF}\\u{00CD}\\u{00BB}\\u{00A7}\").test_eq(\"\\u{00BF}\\u{00CD}\\u{00BB}\\u{00A7}\");\n\n tc.compilef(r\"[\\S]+\", \"\").match1f(\"\\u{00BF}\\u{00CD} \\u{00BB}\\u{00A7}\").test_eq(\"\\u{00BF}\\u{00CD}\");\n\n\n\n tc.compilef(r\"[\\S]+\", \"\").match1f(\"\\u{4e00}\\u{ac00}\\u{4e03}\\u{4e00}\").test_eq(\"\\u{4e00}\\u{ac00}\\u{4e03}\\u{4e00}\");\n\n tc.compilef(r\"[\\S]+\", \"\").match1f(\"\\u{4e00}\\u{ac00} \\u{4e03}\\u{4e00}\").test_eq(\"\\u{4e00}\\u{ac00}\");\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 41, "score": 120166.93080029654 }, { "content": "/// A trait for finding the next match in a regex.\n\n/// This is broken out from Executor to avoid needing to thread lifetimes\n\n/// around.\n\npub trait MatchProducer: core::fmt::Debug {\n\n /// The position type of our indexer.\n\n type Position: PositionType;\n\n\n\n /// \\return an initial position for the given start offset.\n\n fn initial_position(&self, offset: usize) -> Option<Self::Position>;\n\n\n\n /// Attempt to match at the given location.\n\n /// \\return either the Match and the position to start looking for the next\n\n /// match, or None on failure.\n\n fn next_match(\n\n &mut self,\n\n pos: Self::Position,\n\n next_start: &mut Option<Self::Position>,\n\n ) -> Option<Match>;\n\n}\n\n\n", "file_path": "src/exec.rs", "rank": 42, "score": 119361.20675755024 }, { "content": "pub trait Direction: core::fmt::Debug + Copy + Clone {\n\n const FORWARD: bool;\n\n fn new() -> Self;\n\n}\n\n\n\nimpl Direction for Forward {\n\n const FORWARD: bool = true;\n\n #[inline(always)]\n\n fn new() -> Self {\n\n Forward {}\n\n }\n\n}\n\n\n\nimpl Direction for Backward {\n\n const FORWARD: bool = false;\n\n #[inline(always)]\n\n fn new() -> Self {\n\n Backward {}\n\n }\n\n}\n\n\n\n/// \\return a slice of bytes of length \\p len starting (or ending if not FORWARD) at \\p pos.\n\n/// Advance (retreat) pos by that many bytes.\n", "file_path": "src/cursor.rs", "rank": 43, "score": 119000.6128926394 }, { "content": "fn run_regexp_multiline_tests_tc(tc: TestConfig) {\n\n // From regexp-multiline.js\n\n tc.test_match_succeeds(\"^bar\", \"\", \"bar\");\n\n tc.test_match_succeeds(\"^bar\", \"\", \"bar\\nfoo\");\n\n tc.compilef(\"^bar\", \"\").test_fails(\"foo\\nbar\");\n\n tc.test_match_succeeds(\"^bar\", \"m\", \"bar\");\n\n tc.test_match_succeeds(\"^bar\", \"m\", \"bar\\nfoo\");\n\n tc.test_match_succeeds(\"^bar\", \"m\", \"foo\\nbar\");\n\n tc.test_match_succeeds(\"bar$\", \"\", \"bar\");\n\n tc.compilef(\"bar$\", \"\").test_fails(\"bar\\nfoo\");\n\n tc.test_match_succeeds(\"bar$\", \"\", \"foo\\nbar\");\n\n tc.test_match_succeeds(\"bar$\", \"m\", \"bar\");\n\n tc.test_match_succeeds(\"bar$\", \"m\", \"bar\\nfoo\");\n\n tc.test_match_succeeds(\"bar$\", \"m\", \"foo\\nbar\");\n\n tc.compilef(\"^bxr\", \"\").test_fails(\"bar\");\n\n tc.compilef(\"^bxr\", \"\").test_fails(\"bar\\nfoo\");\n\n tc.compilef(\"^bxr\", \"m\").test_fails(\"bar\");\n\n tc.compilef(\"^bxr\", \"m\").test_fails(\"bar\\nfoo\");\n\n tc.compilef(\"^bxr\", \"m\").test_fails(\"foo\\nbar\");\n\n tc.compilef(\"bxr$\", \"\").test_fails(\"bar\");\n", "file_path": "tests/tests.rs", "rank": 44, "score": 117415.16139908312 }, { "content": "fn run_regexp_capture_test_tc(tc: TestConfig) {\n\n // regexp-captures.js\n\n tc.test_match_succeeds(r\"^(((N({)?)|(R)|(U)|(V)|(B)|(H)|(n((n)|(r)|(v)|(h))?)|(r(r)?)|(v)|(b((n)|(b))?)|(h))|((Y)|(A)|(E)|(o(u)?)|(p(u)?)|(q(u)?)|(s)|(t)|(u)|(w)|(x(u)?)|(y)|(z)|(a((T)|(A)|(L))?)|(c)|(e)|(f(u)?)|(g(u)?)|(i)|(j)|(l)|(m(u)?)))+\", \"\", \"Avtnennan gunzvmu pubExnY nEvln vaTxh rmuhguhaTxnY\");\n\n\n\n // regexp-capture.js\n\n assert_eq!(\n\n tc.compilef(\"(x)?\\\\1y\", \"\").match1_vec(\"y\"),\n\n vec![Some(\"y\"), None]\n\n );\n\n assert_eq!(\n\n tc.compilef(\"(x)?y\", \"\").match1_vec(\"y\"),\n\n vec![Some(\"y\"), None]\n\n );\n\n assert_eq!(\n\n tc.compilef(\"(x)?\\\\1y\", \"\").match1_vec(\"y\"),\n\n vec![Some(\"y\"), None]\n\n );\n\n assert_eq!(\n\n tc.compilef(\"(x)?y\", \"\").match1_vec(\"y\"),\n\n vec![Some(\"y\"), None]\n", "file_path": "tests/tests.rs", "rank": 45, "score": 117415.16139908312 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_unicode_escape_tc(tc: TestConfig) {\n\n // From 262 test/language/literals/regexp/u-unicode-esc.js\n\n tc.compilef(r#\"\\u{0}\"#, \"\").test_succeeds(\"\\u{0}\");\n\n tc.compilef(r#\"\\u{1}\"#, \"\").test_succeeds(\"\\u{1}\");\n\n tc.compilef(r#\"\\u{1}\"#, \"\").test_fails(\"u\");\n\n tc.compilef(r#\"\\u{3f}\"#, \"\").test_succeeds(\"?\");\n\n tc.compilef(r#\"\\u{000000003f}\"#, \"\").test_succeeds(\"?\");\n\n tc.compilef(r#\"\\u{3F}\"#, \"\").test_succeeds(\"?\");\n\n tc.compilef(r#\"\\u{10ffff}\"#, \"\").test_succeeds(\"\\u{10ffff}\");\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 46, "score": 117415.16139908312 }, { "content": "fn unicode_escape_property_binary_any_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 7] = [\n\n \"\\u{0}\",\n\n \"\\u{F}\",\n\n \"\\u{FF}\",\n\n \"\\u{FFF}\",\n\n \"\\u{FFFF}\",\n\n \"\\u{FFFFF}\",\n\n \"\\u{10FFFF}\",\n\n ];\n\n const REGEXES: [&str; 1] = [\"^\\\\p{Any}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 47, "score": 117415.16139908312 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_lookahead_tests_tc(tc: TestConfig) {\n\n // From regexp-lookahead.js\n\n tc.test_match_succeeds(r#\"^(?=a)\"#, \"\", \"a\");\n\n tc.test_match_fails(r#\"^(?=a)\"#, \"\", \"b\");\n\n tc.compilef(r#\"^(?=a)\"#, \"\").match1f(\"a\").test_eq(\"\");\n\n tc.test_match_succeeds(r#\"^(?=\\woo)f\\w\"#, \"\", \"foo\");\n\n tc.test_match_fails(r#\"^(?=\\woo)f\\w\"#, \"\", \"boo\");\n\n tc.test_match_fails(r#\"^(?=\\woo)f\\w\"#, \"\", \"fao\");\n\n tc.test_match_fails(r#\"^(?=\\woo)f\\w\"#, \"\", \"foa\");\n\n tc.compilef(r#\"^(?=\\woo)f\\w\"#, \"\").match1f(\"foo\").test_eq(\"fo\");\n\n tc.test_match_succeeds(r#\"(?=\\w).(?=\\W)\"#, \"\", r#\".a! \"#);\n\n tc.test_match_fails(r#\"(?=\\w).(?=\\W)\"#, \"\", r#\".! \"#);\n\n tc.test_match_succeeds(r#\"(?=\\w).(?=\\W)\"#, \"\", r#\".ab! \"#);\n\n tc.compilef(r#\"(?=\\w).(?=\\W)\"#, \"\").match1f(r#\".ab! \"#).test_eq(\"b\");\n\n tc.test_match_succeeds(r#\"(?=f(?=[^f]o))..\"#, \"\", r#\", foo!\"#);\n\n tc.test_match_fails(r#\"(?=f(?=[^f]o))..\"#, \"\", r#\", fo!\"#);\n\n tc.test_match_fails(r#\"(?=f(?=[^f]o))..\"#, \"\", \", ffo\");\n\n tc.compilef(r#\"(?=f(?=[^f]o))..\"#, \"\").match1f(r#\", foo!\"#).test_eq(\"fo\");\n\n tc.test_match_succeeds(r#\"^[^'\"]*(?=(['\"])).*\\1(\\w+)\\1\"#, \"\", \" 'foo' \");\n\n tc.test_match_succeeds(r#\"^[^'\"]*(?=(['\"])).*\\1(\\w+)\\1\"#, \"\", r#\" \"foo\" \"#);\n", "file_path": "tests/tests.rs", "rank": 48, "score": 117415.16139908312 }, { "content": "pub fn unicode_property_value_script_from_str(s: &str) -> Option<UnicodePropertyValueScript> {\n\n use UnicodePropertyValueScript::*;\n\n match s {\n\n \"Adlm\" | \"Adlam\" => Some(Adlam),\n\n \"Ahom\" => Some(Ahom),\n\n \"Hluw\" | \"Anatolian_Hieroglyphs\" => Some(AnatolianHieroglyphs),\n\n \"Arab\" | \"Arabic\" => Some(Arabic),\n\n \"Armn\" | \"Armenian\" => Some(Armenian),\n\n \"Avst\" | \"Avestan\" => Some(Avestan),\n\n \"Bali\" | \"Balinese\" => Some(Balinese),\n\n \"Bamu\" | \"Bamum\" => Some(Bamum),\n\n \"Bass\" | \"Bassa_Vah\" => Some(BassaVah),\n\n \"Batk\" | \"Batak\" => Some(Batak),\n\n \"Beng\" | \"Bengali\" => Some(Bengali),\n\n \"Bhks\" | \"Bhaiksuki\" => Some(Bhaiksuki),\n\n \"Bopo\" | \"Bopomofo\" => Some(Bopomofo),\n\n \"Brah\" | \"Brahmi\" => Some(Brahmi),\n\n \"Brai\" | \"Braille\" => Some(Braille),\n\n \"Bugi\" | \"Buginese\" => Some(Buginese),\n\n \"Buhd\" | \"Buhid\" => Some(Buhid),\n", "file_path": "src/unicodetables.rs", "rank": 49, "score": 117250.76297624604 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn run_regexp_named_groups_unicode_malformed_tc() {\n\n // From 262 test/annexB/built-ins/RegExp/named-groups/non-unicode-malformed-lookbehind.js\n\n test_parse_fails(r#\"\\k<a>(?<=>)a\"#);\n\n test_parse_fails(r#\"(?<=>)\\k<a>\"#);\n\n test_parse_fails(r#\"\\k<a>(?<!a)a\"#);\n\n test_parse_fails(r#\"(?<!a>)\\k<a>\"#);\n\n\n\n // From 262 test/annexB/built-ins/RegExp/named-groups/non-unicode-malformed.js\n\n test_parse_fails(r#\"\\k<a>\"#);\n\n test_parse_fails(r#\"\\k<4>\"#);\n\n test_parse_fails(r#\"\\k<a\"#);\n\n test_parse_fails(r#\"\\k\"#);\n\n\n\n // TODO: This test fails, because we accept alphabetic ascii characters in otherwise invalid escapes, due to PCRE tests.\n\n //test_parse_fails(r#\"(?<a>\\a)\"#);\n\n\n\n test_parse_fails(r#\"\\k<a>\"#);\n\n test_parse_fails(r#\"\\k<a\"#);\n\n test_parse_fails(r#\"\\k<a>(<a>x)\"#);\n\n test_parse_fails(r#\"\\k<a>\\1\"#);\n\n test_parse_fails(r#\"\\1(b)\\k<a>\"#);\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 50, "score": 115366.08125653664 }, { "content": "fn unicode_escape_property_binary_assigned_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 6] = [\n\n \"\\u{377}\",\n\n \"\\u{c69}\",\n\n \"\\u{2d96}\",\n\n \"\\u{11a47}\",\n\n \"\\u{1d51c}\",\n\n \"\\u{10fffd}\",\n\n ];\n\n const REGEXES: [&str; 1] = [\"^\\\\p{Assigned}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n", "file_path": "tests/tests.rs", "rank": 51, "score": 114864.69960707717 }, { "content": "fn unicode_escape_property_binary_ascii_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 7] = [\n\n \"\\u{0}\", \"\\u{A}\", \"\\u{17}\", \"\\u{2A}\", \"\\u{3C}\", \"\\u{63}\", \"\\u{7F}\",\n\n ];\n\n const REGEXES: [&str; 1] = [\"^\\\\p{ASCII}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 52, "score": 114864.69960707717 }, { "content": "#[allow(unreachable_code)]\n\nfn run_regexp_unicode_burns_test_tc(tc: TestConfig) {\n\n // These tests are extracted from regexp-capture-3.js.\n\n // All of these are cases where a naive engine would enter an infinite loop.\n\n // Termination is success. These depend on the v8 optimization where a regex\n\n // is known to only match Unicode strings, and so cannot match an ascii-only\n\n // string. We do not yet have this optimization so these tests are disabled.\n\n let _ = tc;\n\n return;\n\n let input = \"The truth about forever is that it is happening right now\";\n\n tc.compilef(\"(((.*)*)*x)\\u{100}\", \"\").match1f(input);\n\n tc.compilef(\"(((.*)*)*\\u{100})foo\", \"\").match1f(input);\n\n tc.compilef(\"\\u{100}(((.*)*)*x)\", \"\").match1f(input);\n\n tc.compilef(\"(((.*)*)*x)\\u{100}\", \"\").match1f(input);\n\n tc.compilef(\"[\\u{107}\\u{103}\\u{100}](((.*)*)*x)\", \"\")\n\n .match1f(input);\n\n tc.compilef(\"(((.*)*)*x)[\\u{107}\\u{103}\\u{100}]\", \"\")\n\n .match1f(input);\n\n tc.compilef(\"[^\\\\x00-\\\\xff](((.*)*)*x)\", \"\").match1f(input);\n\n tc.compilef(\"(((.*)*)*x)[^\\\\x00-\\\\xff]\", \"\").match1f(input);\n\n tc.compilef(\"(?!(((.*)*)*x)\\u{100})foo\", \"\").match1f(input);\n", "file_path": "tests/tests.rs", "rank": 53, "score": 114864.69960707717 }, { "content": "#[rustfmt::skip]\n\nfn run_regexp_unicode_property_classes_tc(tc: TestConfig) {\n\n // TODO: tests\n\n tc.compilef(r#\"\\p{Script=Buhid}\"#, \"\").test_succeeds(\"ᝀᝁᝂᝃᝄᝅᝆᝇᝈᝉᝊᝋᝌᝍᝎᝏᝐᝑ\\u{1752}\\u{1753}ᝀᝁᝂᝃᝄᝅᝆᝇᝈᝉᝊᝋᝌᝍᝎᝏᝐᝑ\\u{1752}\\u{1753}\");\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 54, "score": 114864.69960707717 }, { "content": "fn run_regexp_loop_capture_tests_tc(tc: TestConfig) {\n\n // From regexp-loop-capture.js\n\n assert_eq!(\n\n tc.compile(r\"(?:(a)|(b)|(c))+\").match1_vec(\"abc\"),\n\n vec![Some(\"abc\"), None, None, Some(\"c\")]\n\n );\n\n assert_eq!(\n\n tc.compile(r\"(?:(a)|b)*\").match1_vec(\"ab\"),\n\n vec![Some(\"ab\"), None]\n\n );\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 55, "score": 114864.69960707717 }, { "content": "/// A trait which references a position in an input string.\n\n/// The intent is that this may be satisfied via indexes or pointers.\n\n/// Positions must be subtractable, producing usize; they also obey other \"pointer arithmetic\" ideas.\n\npub trait PositionType:\n\n core::fmt::Debug + Copy + Clone + PartialEq + Eq + PartialOrd + Ord\n\nwhere\n\n Self: ops::Add<usize, Output = Self>,\n\n Self: ops::Sub<usize, Output = Self>,\n\n Self: ops::Sub<Self, Output = usize>,\n\n Self: ops::AddAssign<usize>,\n\n Self: ops::SubAssign<usize>,\n\n{\n\n}\n\n\n\n/// Choose the preferred position type with this alias.\n\n#[cfg(feature = \"index-positions\")]\n\npub type DefPosition<'a> = IndexPosition<'a>;\n\n\n\n#[cfg(not(feature = \"index-positions\"))]\n\npub type DefPosition<'a> = RefPosition<'a>;\n\n\n\n/// A simple index-based position.\n\n/// It remembers the lifetime of the slice it is tied to.\n", "file_path": "src/position.rs", "rank": 56, "score": 113684.82952609085 }, { "content": "pub trait SliceHelp {\n\n type Item;\n\n\n\n /// Given that self is sorted according to f, returns the range of indexes\n\n /// where f indicates equal elements.\n\n fn equal_range_by<'a, F>(&'a self, f: F) -> core::ops::Range<usize>\n\n where\n\n F: FnMut(&'a Self::Item) -> Ordering;\n\n}\n\n\n\nimpl<T> SliceHelp for [T] {\n\n type Item = T;\n\n fn equal_range_by<'a, F>(&'a self, mut f: F) -> core::ops::Range<usize>\n\n where\n\n F: FnMut(&'a Self::Item) -> Ordering,\n\n {\n\n let left = self\n\n .binary_search_by(|v| f(v).then(Ordering::Greater))\n\n .unwrap_err();\n\n let right = self[left..]\n", "file_path": "src/util.rs", "rank": 57, "score": 113667.04862600131 }, { "content": "/// Facilities for searching bytes.\n\npub trait ByteSearcher {\n\n /// Search for ourselves in a slice of bytes.\n\n /// The length of the slice is unspecified and may be 0.\n\n /// \\return the next index of ourselves in the slice, or None.\n\n fn find_in(&self, rhs: &[u8]) -> Option<usize>;\n\n}\n\n\n", "file_path": "src/bytesearch.rs", "rank": 58, "score": 113667.04862600131 }, { "content": "/// A ByteSet is any set of bytes.\n\npub trait ByteSet {\n\n /// \\return whether the ByteSet contains the byte.\n\n fn contains(&self, b: u8) -> bool;\n\n}\n\n\n\n/// A ByteArraySet wraps a small array and uses linear equality.\n\n#[derive(Copy, Clone, Debug)]\n\n#[repr(align(4))]\n\npub struct ByteArraySet<ArraySet: SmallArraySet>(pub ArraySet);\n\n\n\n/// Cover over contains() to avoid bumping into native contains call.\n\nimpl<ArraySet: SmallArraySet> ByteArraySet<ArraySet> {\n\n #[inline(always)]\n\n pub fn contains(self, b: u8) -> bool {\n\n self.0.contains(b)\n\n }\n\n}\n\n\n\nimpl<ArraySet: SmallArraySet> ByteSearcher for ByteArraySet<ArraySet> {\n\n #[inline(always)]\n\n fn find_in(&self, rhs: &[u8]) -> Option<usize> {\n\n self.0.find_in(rhs)\n\n }\n\n}\n\n\n", "file_path": "src/bytesearch.rs", "rank": 59, "score": 113667.04862600131 }, { "content": "// A type which may be an Element.\n\npub trait ElementType:\n\n core::fmt::Debug\n\n + Copy\n\n + Clone\n\n + core::cmp::Eq\n\n + core::cmp::Ord\n\n + core::convert::Into<u32>\n\n + core::convert::TryFrom<u32>\n\n{\n\n /// Return the length of ourself in bytes.\n\n fn bytelength(self) -> usize;\n\n\n\n /// Return another ElementType as self.\n\n #[inline(always)]\n\n fn try_from<Elem: ElementType>(v: Elem) -> Option<Self> {\n\n // Annoying there is no char->u8 conversion.\n\n let vv: u32 = v.into();\n\n vv.try_into().ok()\n\n }\n\n\n", "file_path": "src/indexing.rs", "rank": 60, "score": 113667.04862600131 }, { "content": "pub trait CharProperties {\n\n type Element: ElementType;\n\n\n\n /// Case-fold an element.\n\n fn fold(c: Self::Element) -> Self::Element;\n\n\n\n /// \\return whether these two elements fold to the same value.\n\n fn fold_equals(c1: Self::Element, c2: Self::Element) -> bool {\n\n c1 == c2 || Self::fold(c1) == Self::fold(c2)\n\n }\n\n\n\n /// \\return whether this is a word char.\n\n /// ES9 21.2.2.6.2.\n\n fn is_word_char(c: Self::Element) -> bool {\n\n let c = c.as_u32();\n\n 'a' as u32 <= c && c <= 'z' as u32\n\n || 'A' as u32 <= c && c <= 'Z' as u32\n\n || '0' as u32 <= c && c <= '9' as u32\n\n || c == '_' as u32\n\n }\n", "file_path": "src/matchers.rs", "rank": 61, "score": 113667.04862600131 }, { "content": "fn unicode_escape_property_gc_other_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 702] = [\n\n \"\\u{0}\",\n\n \"\\u{7f}\",\n\n \"\\u{ad}\",\n\n \"\\u{600}\",\n\n \"\\u{61c}\",\n\n \"\\u{6dd}\",\n\n \"\\u{70f}\",\n\n \"\\u{8e2}\",\n\n \"\\u{180e}\",\n\n \"\\u{200b}\",\n\n \"\\u{202a}\",\n\n \"\\u{2060}\",\n\n \"\\u{2066}\",\n\n \"\\u{feff}\",\n\n \"\\u{fff9}\",\n\n \"\\u{110bd}\",\n\n \"\\u{110cd}\",\n\n \"\\u{13430}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 62, "score": 112493.79708622684 }, { "content": "fn unicode_escape_property_binary_diacritic_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 215] = [\n\n \"\\u{5e}\",\n\n \"\\u{60}\",\n\n \"\\u{a8}\",\n\n \"\\u{af}\",\n\n \"\\u{b4}\",\n\n \"\\u{b7}\",\n\n \"\\u{b8}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c2}\",\n\n \"\\u{2c6}\",\n\n \"\\u{2d2}\",\n\n \"\\u{2e0}\",\n\n \"\\u{2e5}\",\n\n \"\\u{2ec}\",\n\n \"\\u{2ed}\",\n\n \"\\u{2ee}\",\n\n \"\\u{2ef}\",\n\n \"\\u{300}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 63, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_patternsyntax_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 248] = [\n\n \"\\u{21}\", \"\\u{24}\", \"\\u{25}\", \"\\u{28}\", \"\\u{29}\", \"\\u{2a}\", \"\\u{2b}\", \"\\u{2c}\", \"\\u{2d}\",\n\n \"\\u{2e}\", \"\\u{3a}\", \"\\u{3c}\", \"\\u{3f}\", \"\\u{5b}\", \"\\u{5c}\", \"\\u{5d}\", \"\\u{5e}\", \"\\u{60}\",\n\n \"\\u{7b}\", \"\\u{7c}\", \"\\u{7d}\", \"\\u{7e}\", \"\\u{a1}\", \"\\u{a2}\", \"\\u{a6}\", \"\\u{a7}\", \"\\u{a9}\",\n\n \"\\u{ab}\", \"\\u{ac}\", \"\\u{ae}\", \"\\u{b0}\", \"\\u{b1}\", \"\\u{b6}\", \"\\u{bb}\", \"\\u{bf}\", \"\\u{d7}\",\n\n \"\\u{f7}\", \"\\u{2010}\", \"\\u{2016}\", \"\\u{2018}\", \"\\u{2019}\", \"\\u{201a}\", \"\\u{201b}\",\n\n \"\\u{201d}\", \"\\u{201e}\", \"\\u{201f}\", \"\\u{2020}\", \"\\u{2030}\", \"\\u{2039}\", \"\\u{203a}\",\n\n \"\\u{203b}\", \"\\u{2041}\", \"\\u{2044}\", \"\\u{2045}\", \"\\u{2046}\", \"\\u{2047}\", \"\\u{2052}\",\n\n \"\\u{2053}\", \"\\u{2055}\", \"\\u{2190}\", \"\\u{2195}\", \"\\u{219a}\", \"\\u{219c}\", \"\\u{21a0}\",\n\n \"\\u{21a1}\", \"\\u{21a3}\", \"\\u{21a4}\", \"\\u{21a6}\", \"\\u{21a7}\", \"\\u{21ae}\", \"\\u{21af}\",\n\n \"\\u{21ce}\", \"\\u{21d0}\", \"\\u{21d2}\", \"\\u{21d3}\", \"\\u{21d4}\", \"\\u{21d5}\", \"\\u{21f4}\",\n\n \"\\u{2300}\", \"\\u{2308}\", \"\\u{2309}\", \"\\u{230a}\", \"\\u{230b}\", \"\\u{230c}\", \"\\u{2320}\",\n\n \"\\u{2322}\", \"\\u{2329}\", \"\\u{232a}\", \"\\u{232b}\", \"\\u{237c}\", \"\\u{237d}\", \"\\u{239b}\",\n\n \"\\u{23b4}\", \"\\u{23dc}\", \"\\u{23e2}\", \"\\u{2427}\", \"\\u{2440}\", \"\\u{244b}\", \"\\u{2500}\",\n\n \"\\u{25b7}\", \"\\u{25b8}\", \"\\u{25c1}\", \"\\u{25c2}\", \"\\u{25f8}\", \"\\u{2600}\", \"\\u{266f}\",\n\n \"\\u{2670}\", \"\\u{2768}\", \"\\u{2769}\", \"\\u{276a}\", \"\\u{276b}\", \"\\u{276c}\", \"\\u{276d}\",\n\n \"\\u{276e}\", \"\\u{276f}\", \"\\u{2770}\", \"\\u{2771}\", \"\\u{2772}\", \"\\u{2773}\", \"\\u{2774}\",\n\n \"\\u{2775}\", \"\\u{2794}\", \"\\u{27c0}\", \"\\u{27c5}\", \"\\u{27c6}\", \"\\u{27c7}\", \"\\u{27e6}\",\n\n \"\\u{27e7}\", \"\\u{27e8}\", \"\\u{27e9}\", \"\\u{27ea}\", \"\\u{27eb}\", \"\\u{27ec}\", \"\\u{27ed}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 64, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_graphemebase_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1670] = [\n\n \"\\u{20}\",\n\n \"\\u{21}\",\n\n \"\\u{24}\",\n\n \"\\u{25}\",\n\n \"\\u{28}\",\n\n \"\\u{29}\",\n\n \"\\u{2a}\",\n\n \"\\u{2b}\",\n\n \"\\u{2c}\",\n\n \"\\u{2d}\",\n\n \"\\u{2e}\",\n\n \"\\u{30}\",\n\n \"\\u{3a}\",\n\n \"\\u{3c}\",\n\n \"\\u{3f}\",\n\n \"\\u{41}\",\n\n \"\\u{5b}\",\n\n \"\\u{5c}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 65, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_cased_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 155] = [\n\n \"\\u{41}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c4}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c0}\",\n\n \"\\u{2e0}\",\n\n \"\\u{345}\",\n\n \"\\u{370}\",\n\n \"\\u{376}\",\n\n \"\\u{37a}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 66, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_asciihexdigit_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 3] = [\"\\u{30}\", \"\\u{41}\", \"\\u{61}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{ASCII_Hex_Digit}+$\", \"^\\\\p{AHex}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 67, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_alphabetic_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1084] = [\n\n \"\\u{41}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bb}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c0}\",\n\n \"\\u{1c4}\",\n\n \"\\u{294}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c6}\",\n\n \"\\u{2e0}\",\n\n \"\\u{2ec}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 68, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_quotationmark_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 28] = [\n\n \"\\u{22}\", \"\\u{27}\", \"\\u{ab}\", \"\\u{bb}\", \"\\u{2018}\", \"\\u{2019}\", \"\\u{201a}\", \"\\u{201b}\",\n\n \"\\u{201d}\", \"\\u{201e}\", \"\\u{201f}\", \"\\u{2039}\", \"\\u{203a}\", \"\\u{2e42}\", \"\\u{300c}\",\n\n \"\\u{300d}\", \"\\u{300e}\", \"\\u{300f}\", \"\\u{301d}\", \"\\u{301e}\", \"\\u{fe41}\", \"\\u{fe42}\",\n\n \"\\u{fe43}\", \"\\u{fe44}\", \"\\u{ff02}\", \"\\u{ff07}\", \"\\u{ff62}\", \"\\u{ff63}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Quotation_Mark}+$\", \"^\\\\p{QMark}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 69, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_softdotted_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 31] = [\n\n \"\\u{69}\",\n\n \"\\u{12f}\",\n\n \"\\u{249}\",\n\n \"\\u{268}\",\n\n \"\\u{29d}\",\n\n \"\\u{2b2}\",\n\n \"\\u{3f3}\",\n\n \"\\u{456}\",\n\n \"\\u{458}\",\n\n \"\\u{1d62}\",\n\n \"\\u{1d96}\",\n\n \"\\u{1da4}\",\n\n \"\\u{1da8}\",\n\n \"\\u{1e2d}\",\n\n \"\\u{1ecb}\",\n\n \"\\u{2071}\",\n\n \"\\u{2148}\",\n\n \"\\u{2c7c}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 70, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_deprecated_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 9] = [\n\n \"\\u{149}\",\n\n \"\\u{673}\",\n\n \"\\u{f77}\",\n\n \"\\u{f79}\",\n\n \"\\u{17a3}\",\n\n \"\\u{206a}\",\n\n \"\\u{2329}\",\n\n \"\\u{232a}\",\n\n \"\\u{e0001}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Deprecated}+$\", \"^\\\\p{Dep}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 71, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_idsbinaryoperator_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 2] = [\"\\u{2ff0}\", \"\\u{2ff4}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{IDS_Binary_Operator}+$\", \"^\\\\p{IDSB}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 72, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_defaultignorablecodepoint_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 26] = [\n\n \"\\u{ad}\",\n\n \"\\u{34f}\",\n\n \"\\u{61c}\",\n\n \"\\u{115f}\",\n\n \"\\u{17b4}\",\n\n \"\\u{180b}\",\n\n \"\\u{180e}\",\n\n \"\\u{200b}\",\n\n \"\\u{202a}\",\n\n \"\\u{2060}\",\n\n \"\\u{2065}\",\n\n \"\\u{2066}\",\n\n \"\\u{3164}\",\n\n \"\\u{fe00}\",\n\n \"\\u{feff}\",\n\n \"\\u{ffa0}\",\n\n \"\\u{fff0}\",\n\n \"\\u{1bca0}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 73, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_dash_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 22] = [\n\n \"\\u{2d}\",\n\n \"\\u{58a}\",\n\n \"\\u{5be}\",\n\n \"\\u{1400}\",\n\n \"\\u{1806}\",\n\n \"\\u{2010}\",\n\n \"\\u{2053}\",\n\n \"\\u{207b}\",\n\n \"\\u{208b}\",\n\n \"\\u{2212}\",\n\n \"\\u{2e17}\",\n\n \"\\u{2e1a}\",\n\n \"\\u{2e3a}\",\n\n \"\\u{2e40}\",\n\n \"\\u{301c}\",\n\n \"\\u{3030}\",\n\n \"\\u{30a0}\",\n\n \"\\u{fe31}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 74, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_idcontinue_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1269] = [\n\n \"\\u{30}\",\n\n \"\\u{41}\",\n\n \"\\u{5f}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{b7}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bb}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c0}\",\n\n \"\\u{1c4}\",\n\n \"\\u{294}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 75, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_changeswhencasemapped_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 124] = [\n\n \"\\u{41}\",\n\n \"\\u{61}\",\n\n \"\\u{b5}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{139}\",\n\n \"\\u{18e}\",\n\n \"\\u{19c}\",\n\n \"\\u{1ac}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1bf}\",\n\n \"\\u{1c4}\",\n\n \"\\u{222}\",\n\n \"\\u{23a}\",\n\n \"\\u{256}\",\n\n \"\\u{259}\",\n\n \"\\u{25b}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 76, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_xidcontinue_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1273] = [\n\n \"\\u{30}\",\n\n \"\\u{41}\",\n\n \"\\u{5f}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{b7}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bb}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c0}\",\n\n \"\\u{1c4}\",\n\n \"\\u{294}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 77, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_hexdigit_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 6] = [\n\n \"\\u{30}\", \"\\u{41}\", \"\\u{61}\", \"\\u{ff10}\", \"\\u{ff21}\", \"\\u{ff41}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Hex_Digit}+$\", \"^\\\\p{Hex}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 78, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_changeswhenuppercased_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 619] = [\n\n \"\\u{61}\",\n\n \"\\u{b5}\",\n\n \"\\u{df}\",\n\n \"\\u{f8}\",\n\n \"\\u{101}\",\n\n \"\\u{103}\",\n\n \"\\u{105}\",\n\n \"\\u{107}\",\n\n \"\\u{109}\",\n\n \"\\u{10b}\",\n\n \"\\u{10d}\",\n\n \"\\u{10f}\",\n\n \"\\u{111}\",\n\n \"\\u{113}\",\n\n \"\\u{115}\",\n\n \"\\u{117}\",\n\n \"\\u{119}\",\n\n \"\\u{11b}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 79, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_caseignorable_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 460] = [\n\n \"\\u{27}\",\n\n \"\\u{2e}\",\n\n \"\\u{3a}\",\n\n \"\\u{5e}\",\n\n \"\\u{60}\",\n\n \"\\u{a8}\",\n\n \"\\u{ad}\",\n\n \"\\u{af}\",\n\n \"\\u{b4}\",\n\n \"\\u{b7}\",\n\n \"\\u{b8}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c2}\",\n\n \"\\u{2c6}\",\n\n \"\\u{2d2}\",\n\n \"\\u{2e0}\",\n\n \"\\u{2e5}\",\n\n \"\\u{2ec}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 80, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_changeswhencasefolded_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 614] = [\n\n \"\\u{41}\",\n\n \"\\u{b5}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{100}\",\n\n \"\\u{102}\",\n\n \"\\u{104}\",\n\n \"\\u{106}\",\n\n \"\\u{108}\",\n\n \"\\u{10a}\",\n\n \"\\u{10c}\",\n\n \"\\u{10e}\",\n\n \"\\u{110}\",\n\n \"\\u{112}\",\n\n \"\\u{114}\",\n\n \"\\u{116}\",\n\n \"\\u{118}\",\n\n \"\\u{11a}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 81, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_idstart_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 697] = [\n\n \"\\u{41}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bb}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c0}\",\n\n \"\\u{1c4}\",\n\n \"\\u{294}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c6}\",\n\n \"\\u{2e0}\",\n\n \"\\u{2ec}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 82, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_graphemeextend_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 357] = [\n\n \"\\u{300}\",\n\n \"\\u{483}\",\n\n \"\\u{488}\",\n\n \"\\u{591}\",\n\n \"\\u{5bf}\",\n\n \"\\u{5c1}\",\n\n \"\\u{5c4}\",\n\n \"\\u{5c7}\",\n\n \"\\u{610}\",\n\n \"\\u{64b}\",\n\n \"\\u{670}\",\n\n \"\\u{6d6}\",\n\n \"\\u{6df}\",\n\n \"\\u{6e7}\",\n\n \"\\u{6ea}\",\n\n \"\\u{711}\",\n\n \"\\u{730}\",\n\n \"\\u{7a6}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 83, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_ideographic_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 20] = [\n\n \"\\u{3006}\",\n\n \"\\u{3007}\",\n\n \"\\u{3021}\",\n\n \"\\u{3038}\",\n\n \"\\u{3400}\",\n\n \"\\u{4e00}\",\n\n \"\\u{f900}\",\n\n \"\\u{fa70}\",\n\n \"\\u{16fe4}\",\n\n \"\\u{17000}\",\n\n \"\\u{18800}\",\n\n \"\\u{18d00}\",\n\n \"\\u{1b170}\",\n\n \"\\u{20000}\",\n\n \"\\u{2a700}\",\n\n \"\\u{2b740}\",\n\n \"\\u{2b820}\",\n\n \"\\u{2ceb0}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 84, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_bidicontrol_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 4] = [\"\\u{61c}\", \"\\u{200e}\", \"\\u{202a}\", \"\\u{2066}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Bidi_Control}+$\", \"^\\\\p{Bidi_C}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 85, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_noncharactercodepoint_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 18] = [\n\n \"\\u{fdd0}\",\n\n \"\\u{fffe}\",\n\n \"\\u{1fffe}\",\n\n \"\\u{2fffe}\",\n\n \"\\u{3fffe}\",\n\n \"\\u{4fffe}\",\n\n \"\\u{5fffe}\",\n\n \"\\u{6fffe}\",\n\n \"\\u{7fffe}\",\n\n \"\\u{8fffe}\",\n\n \"\\u{9fffe}\",\n\n \"\\u{afffe}\",\n\n \"\\u{bfffe}\",\n\n \"\\u{cfffe}\",\n\n \"\\u{dfffe}\",\n\n \"\\u{efffe}\",\n\n \"\\u{ffffe}\",\n\n \"\\u{10fffe}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Noncharacter_Code_Point}+$\", \"^\\\\p{NChar}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 86, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_lowercase_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 665] = [\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{ba}\",\n\n \"\\u{df}\",\n\n \"\\u{f8}\",\n\n \"\\u{101}\",\n\n \"\\u{103}\",\n\n \"\\u{105}\",\n\n \"\\u{107}\",\n\n \"\\u{109}\",\n\n \"\\u{10b}\",\n\n \"\\u{10d}\",\n\n \"\\u{10f}\",\n\n \"\\u{111}\",\n\n \"\\u{113}\",\n\n \"\\u{115}\",\n\n \"\\u{117}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 87, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_extender_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 32] = [\n\n \"\\u{b7}\",\n\n \"\\u{2d0}\",\n\n \"\\u{640}\",\n\n \"\\u{7fa}\",\n\n \"\\u{b55}\",\n\n \"\\u{e46}\",\n\n \"\\u{ec6}\",\n\n \"\\u{180a}\",\n\n \"\\u{1843}\",\n\n \"\\u{1aa7}\",\n\n \"\\u{1c36}\",\n\n \"\\u{1c7b}\",\n\n \"\\u{3005}\",\n\n \"\\u{3031}\",\n\n \"\\u{309d}\",\n\n \"\\u{30fc}\",\n\n \"\\u{a015}\",\n\n \"\\u{a60c}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 88, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_logicalorderexception_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 7] = [\n\n \"\\u{e40}\", \"\\u{ec0}\", \"\\u{19b5}\", \"\\u{19ba}\", \"\\u{aab5}\", \"\\u{aab9}\", \"\\u{aabb}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Logical_Order_Exception}+$\", \"^\\\\p{LOE}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 89, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_xidstart_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 700] = [\n\n \"\\u{41}\",\n\n \"\\u{61}\",\n\n \"\\u{aa}\",\n\n \"\\u{b5}\",\n\n \"\\u{ba}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{f8}\",\n\n \"\\u{1bb}\",\n\n \"\\u{1bc}\",\n\n \"\\u{1c0}\",\n\n \"\\u{1c4}\",\n\n \"\\u{294}\",\n\n \"\\u{295}\",\n\n \"\\u{2b0}\",\n\n \"\\u{2c6}\",\n\n \"\\u{2e0}\",\n\n \"\\u{2ec}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 90, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_changeswhentitlecased_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 618] = [\n\n \"\\u{61}\",\n\n \"\\u{b5}\",\n\n \"\\u{df}\",\n\n \"\\u{f8}\",\n\n \"\\u{101}\",\n\n \"\\u{103}\",\n\n \"\\u{105}\",\n\n \"\\u{107}\",\n\n \"\\u{109}\",\n\n \"\\u{10b}\",\n\n \"\\u{10d}\",\n\n \"\\u{10f}\",\n\n \"\\u{111}\",\n\n \"\\u{113}\",\n\n \"\\u{115}\",\n\n \"\\u{117}\",\n\n \"\\u{119}\",\n\n \"\\u{11b}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 91, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_sentenceterminal_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 76] = [\n\n \"\\u{21}\",\n\n \"\\u{2e}\",\n\n \"\\u{3f}\",\n\n \"\\u{589}\",\n\n \"\\u{61e}\",\n\n \"\\u{6d4}\",\n\n \"\\u{700}\",\n\n \"\\u{7f9}\",\n\n \"\\u{837}\",\n\n \"\\u{839}\",\n\n \"\\u{83d}\",\n\n \"\\u{964}\",\n\n \"\\u{104a}\",\n\n \"\\u{1362}\",\n\n \"\\u{1367}\",\n\n \"\\u{166e}\",\n\n \"\\u{1735}\",\n\n \"\\u{1803}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 92, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_idstrinaryoperator_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1] = [\"\\u{2ff2}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{IDS_Trinary_Operator}+$\", \"^\\\\p{IDST}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 93, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_radical_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 3] = [\"\\u{2e80}\", \"\\u{2e9b}\", \"\\u{2f00}\"];\n\n const REGEXES: [&str; 1] = [\"^\\\\p{Radical}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 94, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_joincontrol_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1] = [\"\\u{200c}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Join_Control}+$\", \"^\\\\p{Join_C}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 95, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_patternwhitespace_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 6] = [\n\n \"\\u{9}\", \"\\u{20}\", \"\\u{85}\", \"\\u{200e}\", \"\\u{2028}\", \"\\u{2029}\",\n\n ];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Pattern_White_Space}+$\", \"^\\\\p{Pat_WS}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 96, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_changeswhenlowercased_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 601] = [\n\n \"\\u{41}\",\n\n \"\\u{c0}\",\n\n \"\\u{d8}\",\n\n \"\\u{100}\",\n\n \"\\u{102}\",\n\n \"\\u{104}\",\n\n \"\\u{106}\",\n\n \"\\u{108}\",\n\n \"\\u{10a}\",\n\n \"\\u{10c}\",\n\n \"\\u{10e}\",\n\n \"\\u{110}\",\n\n \"\\u{112}\",\n\n \"\\u{114}\",\n\n \"\\u{116}\",\n\n \"\\u{118}\",\n\n \"\\u{11a}\",\n\n \"\\u{11c}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 97, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_math_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 240] = [\n\n \"\\u{2b}\",\n\n \"\\u{3c}\",\n\n \"\\u{5e}\",\n\n \"\\u{7c}\",\n\n \"\\u{7e}\",\n\n \"\\u{ac}\",\n\n \"\\u{b1}\",\n\n \"\\u{d7}\",\n\n \"\\u{f7}\",\n\n \"\\u{3d0}\",\n\n \"\\u{3d5}\",\n\n \"\\u{3f0}\",\n\n \"\\u{3f4}\",\n\n \"\\u{3f6}\",\n\n \"\\u{606}\",\n\n \"\\u{2016}\",\n\n \"\\u{2032}\",\n\n \"\\u{2040}\",\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 98, "score": 110283.78439099595 }, { "content": "fn unicode_escape_property_binary_regionalindicator_tc(tc: TestConfig) {\n\n const CODE_POINTS: [&str; 1] = [\"\\u{1f1e6}\"];\n\n const REGEXES: [&str; 2] = [\"^\\\\p{Regional_Indicator}+$\", \"^\\\\p{RI}+$\"];\n\n for regex in REGEXES {\n\n let regex = tc.compile(regex);\n\n for code_point in CODE_POINTS {\n\n regex.test_succeeds(code_point);\n\n }\n\n }\n\n}\n\n\n", "file_path": "tests/unicode_property_escapes.rs", "rank": 99, "score": 110283.78439099595 } ]
Rust
mqtt/mqtt-policy/src/substituter.rs
dmolokanov/iotedge
a42fe5abbb98b6de32fd832ac75e0e8ebd740a10
use mqtt_broker::auth::Activity; use policy::{Request, Result, Substituter}; #[allow(clippy::doc_markdown)] #[derive(Debug)] pub struct MqttSubstituter { device_id: String, } impl MqttSubstituter { pub fn new(device_id: impl Into<String>) -> Self { Self { device_id: device_id.into(), } } fn device_id(&self) -> &str { &self.device_id } fn replace_variable(&self, value: &str, context: &Request<Activity>) -> String { match context.context() { Some(context) => { let mut result = value.to_owned(); for variable in VariableIter::new(value) { result = match variable { crate::CLIENT_ID_VAR => replace( &result, variable, context.client_info().client_id().as_str(), ), crate::IDENTITY_VAR => { replace(&result, variable, context.client_info().auth_id().as_str()) } crate::DEVICE_ID_VAR => { replace(&result, variable, extract_device_id(context)) } crate::MODULE_ID_VAR => { replace(&result, variable, extract_module_id(context)) } crate::EDGEHUB_ID_VAR => replace(&result, variable, self.device_id()), _ => result, }; } result } None => value.to_owned(), } } } impl Substituter for MqttSubstituter { type Context = Activity; fn visit_identity(&self, value: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } fn visit_resource(&self, value: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } } #[derive(Debug)] pub(super) struct VariableIter<'a> { value: &'a str, index: usize, } impl<'a> VariableIter<'a> { pub fn new(value: &'a str) -> Self { Self { value, index: 0 } } } impl<'a> Iterator for VariableIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { let value = &self.value[self.index..]; if let Some(start) = value.find("{{") { if let Some(end) = value.find("}}") { if start < end { self.index = self.index + end + 2; return Some(&value[start..end + 2]); } } } None } } fn replace(value: &str, variable: &str, substitution: &str) -> String { value.replace(variable, substitution) } fn extract_device_id(activity: &Activity) -> &str { let auth_id = activity.client_info().auth_id().as_str(); auth_id.split('/').next().unwrap_or_default() } fn extract_module_id(activity: &Activity) -> &str { let auth_id = activity.client_info().auth_id().as_str(); auth_id.split('/').nth(1).unwrap_or_default() } #[cfg(test)] mod tests { use proptest::prelude::*; use test_case::test_case; use crate::tests; use super::*; #[test_case("{{iot:identity}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:identity variable")] #[test_case("namespace-{{iot:identity}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:identity variable substring")] #[test_case("{{mqtt:client_id}}", "test_device_auth_id", "test_device_client_id", "test_device_client_id"; "mqtt:client_id variable")] #[test_case("namespace-{{mqtt:client_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_client_id-suffix"; "mqtt:client_id variable substring")] #[test_case("{{iot:device_id}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:device_id variable")] #[test_case("namespace-{{iot:device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:device_id variable substring")] #[test_case("{{iot:module_id}}", "test_device_id/test_module_id", "test_device_client_id", "test_module_id"; "iot:module_id variable")] #[test_case("namespace-{{iot:module_id}}-suffix", "test_device_id/test_module_id", "test_device_client_id", "namespace-test_module_id-suffix"; "iot:module_id variable substring")] #[test_case("{{iot:this_device_id}}", "test_device_auth_id", "test_device_client_id", "edge_device"; "iot:this_device_id variable")] #[test_case("namespace-{{iot:this_device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-edge_device-suffix"; "iot:this_device_id variable substring")] #[test_case("{{invalid}}", "test_device_auth_id", "test_device_client_id", "{{invalid}}"; "invalid variable")] #[test_case("{{{}bad}}}", "test_device_auth_id", "test_device_client_id", "{{{}bad}}}"; "bad variable")] #[test_case("{{{}bad}", "test_device_auth_id", "test_device_client_id", "{{{}bad}"; "bad variable 2")] #[test_case("{}bad}}", "test_device_auth_id", "test_device_client_id", "{}bad}}"; "bad variable 3")] #[test_case("{{iot:this_device_id}}{{iot:module_id}}", "test_device_auth_id/test_module", "test_device_client_id", "edge_devicetest_module"; "multiple variable")] #[test_case("namespace-{{iot:this_device_id}}/{{iot:module_id}}-suffix", "test_device_auth_id/test_module", "test_device_client_id", "namespace-edge_device/test_module-suffix"; "multiple variable substring")] fn visit_identity_test(input: &str, auth_id: &str, client_id: &str, expected: &str) { let request = Request::with_context( "some_identity", "some_operation", "some_resource", tests::create_connect_activity(client_id, auth_id), ) .unwrap(); assert_eq!( expected, MqttSubstituter::new("edge_device") .visit_identity(input, &request) .unwrap() ); } #[test_case("{{iot:identity}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:identity variable")] #[test_case("namespace-{{iot:identity}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:identity variable substring")] #[test_case("{{mqtt:client_id}}", "test_device_auth_id", "test_device_client_id", "test_device_client_id"; "mqtt:client_id variable")] #[test_case("namespace-{{mqtt:client_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_client_id-suffix"; "mqtt:client_id variable substring")] #[test_case("{{iot:device_id}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:device_id variable")] #[test_case("namespace-{{iot:device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:device_id variable substring")] #[test_case("{{iot:module_id}}", "test_device_id/test_module_id", "test_device_client_id", "test_module_id"; "iot:module_id variable")] #[test_case("namespace-{{iot:module_id}}-suffix", "test_device_id/test_module_id", "test_device_client_id", "namespace-test_module_id-suffix"; "iot:module_id variable substring")] #[test_case("{{iot:this_device_id}}", "test_device_auth_id", "test_device_client_id", "edge_device"; "iot:this_device_id variable")] #[test_case("namespace-{{iot:this_device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-edge_device-suffix"; "iot:this_device_id variable substring")] #[test_case("{{invalid}}", "test_device_auth_id", "test_device_client_id", "{{invalid}}"; "invalid variable")] #[test_case("{{{}bad}}}", "test_device_auth_id", "test_device_client_id", "{{{}bad}}}"; "bad variable")] #[test_case("{{{}bad}", "test_device_auth_id", "test_device_client_id", "{{{}bad}"; "bad variable 2")] #[test_case("{}bad}}", "test_device_auth_id", "test_device_client_id", "{}bad}}"; "bad variable 3")] #[test_case("{{iot:this_device_id}}{{iot:module_id}}", "test_device_auth_id/test_module", "test_device_client_id", "edge_devicetest_module"; "multiple variable")] #[test_case("namespace-{{iot:this_device_id}}/{{iot:module_id}}-suffix", "test_device_auth_id/test_module", "test_device_client_id", "namespace-edge_device/test_module-suffix"; "multiple variable substring")] fn visit_resource_test(input: &str, auth_id: &str, client_id: &str, expected: &str) { let request = Request::with_context( "some_identity", "some_operation", "some_resource", tests::create_publish_activity(client_id, auth_id), ) .unwrap(); assert_eq!( expected, MqttSubstituter::new("edge_device") .visit_resource(input, &request) .unwrap() ); } proptest! { #[test] fn iterator_does_not_crash(value in "[a-z\\{\\}]+") { drop(VariableIter::new(&value).collect::<Vec<_>>()); } } }
use mqtt_broker::auth::Activity; use policy::{Request, Result, Substituter}; #[allow(clippy::doc_markdown)] #[derive(Debug)] pub struct MqttSubstituter { device_id: String, } impl MqttSubstituter { pub fn new(device_id: impl Into<String>) -> Self { Self { device_id: device_id.into(), } } fn device_id(&self) -> &str { &self.device_id } fn replace_variable(&self, value: &str, context: &Request<Activity>) -> String { match context.context() { Some(context) => { let mut result = value.to_owned(); for variable in VariableIter::new(value) { result = match variable { crate::CLIENT_ID_VAR => replace( &result, variable, context.client_info().client_id().as_str(), ), crate::IDENTITY_VAR => { replace(&result, variable, context.client_info().auth_id().as_str()) } crate::DEVICE_ID_VAR => { replace(&result, variable, extract_device_id(context)) } crate::MODULE_ID_VAR => { replace(&result, variable, extract_module_id(context)) } crate::EDGEHUB_ID_VAR => replace(&result, variable, self.device_id()), _ => result, }; } result } None => value.to_owned(), } } } impl Substituter for MqttSubstituter { type Context = Activity; fn visit_identity(&self, va
:device_id variable")] #[test_case("namespace-{{iot:device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:device_id variable substring")] #[test_case("{{iot:module_id}}", "test_device_id/test_module_id", "test_device_client_id", "test_module_id"; "iot:module_id variable")] #[test_case("namespace-{{iot:module_id}}-suffix", "test_device_id/test_module_id", "test_device_client_id", "namespace-test_module_id-suffix"; "iot:module_id variable substring")] #[test_case("{{iot:this_device_id}}", "test_device_auth_id", "test_device_client_id", "edge_device"; "iot:this_device_id variable")] #[test_case("namespace-{{iot:this_device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-edge_device-suffix"; "iot:this_device_id variable substring")] #[test_case("{{invalid}}", "test_device_auth_id", "test_device_client_id", "{{invalid}}"; "invalid variable")] #[test_case("{{{}bad}}}", "test_device_auth_id", "test_device_client_id", "{{{}bad}}}"; "bad variable")] #[test_case("{{{}bad}", "test_device_auth_id", "test_device_client_id", "{{{}bad}"; "bad variable 2")] #[test_case("{}bad}}", "test_device_auth_id", "test_device_client_id", "{}bad}}"; "bad variable 3")] #[test_case("{{iot:this_device_id}}{{iot:module_id}}", "test_device_auth_id/test_module", "test_device_client_id", "edge_devicetest_module"; "multiple variable")] #[test_case("namespace-{{iot:this_device_id}}/{{iot:module_id}}-suffix", "test_device_auth_id/test_module", "test_device_client_id", "namespace-edge_device/test_module-suffix"; "multiple variable substring")] fn visit_identity_test(input: &str, auth_id: &str, client_id: &str, expected: &str) { let request = Request::with_context( "some_identity", "some_operation", "some_resource", tests::create_connect_activity(client_id, auth_id), ) .unwrap(); assert_eq!( expected, MqttSubstituter::new("edge_device") .visit_identity(input, &request) .unwrap() ); } #[test_case("{{iot:identity}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:identity variable")] #[test_case("namespace-{{iot:identity}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:identity variable substring")] #[test_case("{{mqtt:client_id}}", "test_device_auth_id", "test_device_client_id", "test_device_client_id"; "mqtt:client_id variable")] #[test_case("namespace-{{mqtt:client_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_client_id-suffix"; "mqtt:client_id variable substring")] #[test_case("{{iot:device_id}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:device_id variable")] #[test_case("namespace-{{iot:device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:device_id variable substring")] #[test_case("{{iot:module_id}}", "test_device_id/test_module_id", "test_device_client_id", "test_module_id"; "iot:module_id variable")] #[test_case("namespace-{{iot:module_id}}-suffix", "test_device_id/test_module_id", "test_device_client_id", "namespace-test_module_id-suffix"; "iot:module_id variable substring")] #[test_case("{{iot:this_device_id}}", "test_device_auth_id", "test_device_client_id", "edge_device"; "iot:this_device_id variable")] #[test_case("namespace-{{iot:this_device_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-edge_device-suffix"; "iot:this_device_id variable substring")] #[test_case("{{invalid}}", "test_device_auth_id", "test_device_client_id", "{{invalid}}"; "invalid variable")] #[test_case("{{{}bad}}}", "test_device_auth_id", "test_device_client_id", "{{{}bad}}}"; "bad variable")] #[test_case("{{{}bad}", "test_device_auth_id", "test_device_client_id", "{{{}bad}"; "bad variable 2")] #[test_case("{}bad}}", "test_device_auth_id", "test_device_client_id", "{}bad}}"; "bad variable 3")] #[test_case("{{iot:this_device_id}}{{iot:module_id}}", "test_device_auth_id/test_module", "test_device_client_id", "edge_devicetest_module"; "multiple variable")] #[test_case("namespace-{{iot:this_device_id}}/{{iot:module_id}}-suffix", "test_device_auth_id/test_module", "test_device_client_id", "namespace-edge_device/test_module-suffix"; "multiple variable substring")] fn visit_resource_test(input: &str, auth_id: &str, client_id: &str, expected: &str) { let request = Request::with_context( "some_identity", "some_operation", "some_resource", tests::create_publish_activity(client_id, auth_id), ) .unwrap(); assert_eq!( expected, MqttSubstituter::new("edge_device") .visit_resource(input, &request) .unwrap() ); } proptest! { #[test] fn iterator_does_not_crash(value in "[a-z\\{\\}]+") { drop(VariableIter::new(&value).collect::<Vec<_>>()); } } }
lue: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } fn visit_resource(&self, value: &str, context: &Request<Self::Context>) -> Result<String> { Ok(self.replace_variable(value, context)) } } #[derive(Debug)] pub(super) struct VariableIter<'a> { value: &'a str, index: usize, } impl<'a> VariableIter<'a> { pub fn new(value: &'a str) -> Self { Self { value, index: 0 } } } impl<'a> Iterator for VariableIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { let value = &self.value[self.index..]; if let Some(start) = value.find("{{") { if let Some(end) = value.find("}}") { if start < end { self.index = self.index + end + 2; return Some(&value[start..end + 2]); } } } None } } fn replace(value: &str, variable: &str, substitution: &str) -> String { value.replace(variable, substitution) } fn extract_device_id(activity: &Activity) -> &str { let auth_id = activity.client_info().auth_id().as_str(); auth_id.split('/').next().unwrap_or_default() } fn extract_module_id(activity: &Activity) -> &str { let auth_id = activity.client_info().auth_id().as_str(); auth_id.split('/').nth(1).unwrap_or_default() } #[cfg(test)] mod tests { use proptest::prelude::*; use test_case::test_case; use crate::tests; use super::*; #[test_case("{{iot:identity}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot:identity variable")] #[test_case("namespace-{{iot:identity}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_auth_id-suffix"; "iot:identity variable substring")] #[test_case("{{mqtt:client_id}}", "test_device_auth_id", "test_device_client_id", "test_device_client_id"; "mqtt:client_id variable")] #[test_case("namespace-{{mqtt:client_id}}-suffix", "test_device_auth_id", "test_device_client_id", "namespace-test_device_client_id-suffix"; "mqtt:client_id variable substring")] #[test_case("{{iot:device_id}}", "test_device_auth_id", "test_device_client_id", "test_device_auth_id"; "iot
random
[ { "content": "pub fn ensure_not_empty_with_context<D, F>(value: &str, context: F) -> Result<(), Context<D>>\n\nwhere\n\n D: fmt::Display + Send + Sync,\n\n F: FnOnce() -> D,\n\n{\n\n if value.trim().is_empty() {\n\n return Err(ErrorKind::ArgumentEmpty(String::new()).context(context()));\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(clippy::semicolon_if_nothing_returned)]\n\nmod tests {\n\n use crate::error::{Error, ErrorKind};\n\n\n\n macro_rules! check_ok {\n\n ($expected:expr, $f:block) => {\n\n let result: Result<_, Error> = async { $f }.await;\n", "file_path": "edgelet/edgelet-utils/src/macros.rs", "rank": 1, "score": 443445.3720936426 }, { "content": "pub fn arb_topic() -> impl Strategy<Value = String> {\n\n \"\\\\PC+(/\\\\PC+)*\"\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 2, "score": 390267.3788331556 }, { "content": "pub fn arb_topic_filter_weighted() -> impl Strategy<Value = String> {\n\n let max = 10;\n\n prop_oneof![\n\n arb_topic_filter().prop_map(|topic| topic.to_string()),\n\n (0..max).prop_map(|n| format!(\"topic/{}\", n)),\n\n ]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 3, "score": 381604.0517846849 }, { "content": "pub fn arb_username() -> impl Strategy<Value = Option<String>> {\n\n prop_oneof![\"\\\\PC*\".prop_map(Some), Just(None)]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 4, "score": 378994.34194202046 }, { "content": "pub fn arb_password() -> impl Strategy<Value = Option<String>> {\n\n prop_oneof![\"\\\\PC*\".prop_map(Some), Just(None)]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 5, "score": 378994.34194202046 }, { "content": "pub fn prepare_cert_uri_module(hub_name: &str, device_id: &str, module_id: &str) -> String {\n\n format!(\n\n \"URI: azureiot://{}/devices/{}/modules/{}\",\n\n hub_name, device_id, module_id\n\n )\n\n}\n\n\n\nconst ALLOWED_CHAR_DNS: char = '-';\n\nconst DNS_MAX_SIZE: usize = 63;\n\n\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 6, "score": 348154.9078430636 }, { "content": "pub fn append_dns_san_entries(sans: &str, names: &[&str]) -> String {\n\n let mut dns_ip_sans = names\n\n .iter()\n\n .filter_map(|name| {\n\n if IpAddr::from_str(name).is_ok() {\n\n Some(format!(\"IP:{}\", name))\n\n } else if name.trim().is_empty() {\n\n None\n\n } else {\n\n Some(name.to_lowercase())\n\n }\n\n })\n\n .collect::<Vec<String>>()\n\n .join(\", \");\n\n dns_ip_sans.push_str(\", \");\n\n dns_ip_sans.push_str(sans);\n\n dns_ip_sans\n\n}\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 7, "score": 340368.87639194145 }, { "content": "/// The name returned from here must conform to following rules (as per RFC 1035):\n\n/// - length must be <= 63 characters\n\n/// - must be all lower case alphanumeric characters or '-'\n\n/// - must start with an alphabet\n\n/// - must end with an alphanumeric character\n\npub fn sanitize_dns_label(name: &str) -> String {\n\n name.trim_start_matches(|c: char| !c.is_ascii_alphabetic())\n\n .trim_end_matches(|c: char| !c.is_ascii_alphanumeric())\n\n .to_lowercase()\n\n .chars()\n\n .filter(|c| c.is_ascii_alphanumeric() || c == &ALLOWED_CHAR_DNS)\n\n .take(DNS_MAX_SIZE)\n\n .collect::<String>()\n\n}\n\n\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 8, "score": 339113.77076798404 }, { "content": "pub fn workload(url: &str) -> Result<WorkloadClient, Error> {\n\n let url = Url::parse(url).map_err(|e| Error::ParseUrl(url.to_string(), e))?;\n\n\n\n let (connector, scheme) = match url.scheme() {\n\n #[cfg(unix)]\n\n \"unix\" => (\n\n Connector::Unix(UnixConnector),\n\n Scheme::Unix(url.path().to_string()),\n\n ),\n\n \"http\" => (\n\n Connector::Http(HttpConnector::new()),\n\n Scheme::Http(url.to_string()),\n\n ),\n\n _ => return Err(Error::UnrecognizedUrlScheme(url.to_string())),\n\n };\n\n\n\n let client = Client::builder().build(connector);\n\n Ok(WorkloadClient::new(client, scheme))\n\n}\n\n\n", "file_path": "mqtt/edgelet-client/src/lib.rs", "rank": 9, "score": 320439.5300659905 }, { "content": "pub fn parse_since(since: &str) -> Result<i32, Error> {\n\n if let Ok(datetime) = DateTime::parse_from_rfc3339(since) {\n\n let temp: Result<i32, _> = datetime.timestamp().try_into();\n\n Ok(temp.context(ErrorKind::ParseSince)?)\n\n } else if let Ok(epoch) = since.parse() {\n\n Ok(epoch)\n\n } else if let Ok(duration) = parse_duration(since) {\n\n let nano: Result<i64, _> = duration.as_nanos().try_into();\n\n let nano = nano.context(ErrorKind::ParseSince)?;\n\n\n\n let temp: Result<i32, _> = (Local::now() - Duration::nanoseconds(nano))\n\n .timestamp()\n\n .try_into();\n\n Ok(temp.context(ErrorKind::ParseSince)?)\n\n } else {\n\n Err(Error::from(ErrorKind::ParseSince))\n\n }\n\n}\n\n\n\n#[cfg(test)]\n", "file_path": "edgelet/edgelet-core/src/parse_since.rs", "rank": 10, "score": 317028.89957016683 }, { "content": "fn visit_resource(value: &str) -> Result<(), Error> {\n\n if value.is_empty() {\n\n return Err(Error::InvalidResource(value.into()));\n\n }\n\n for variable in VariableIter::new(value) {\n\n if VALID_VARIABLES.get(variable).is_none() {\n\n return Err(Error::InvalidResourceVariable(variable.into()));\n\n }\n\n }\n\n if TopicFilter::from_str(value).is_err() {\n\n return Err(Error::InvalidResource(value.into()));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mqtt/mqtt-policy/src/validator.rs", "rank": 11, "score": 316881.41993807245 }, { "content": "fn visit_operation(value: &str) -> Result<(), Error> {\n\n match value {\n\n \"mqtt:publish\" | \"mqtt:subscribe\" | \"mqtt:connect\" => Ok(()),\n\n _ => Err(Error::InvalidOperation(value.into())),\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-policy/src/validator.rs", "rank": 12, "score": 316881.41993807245 }, { "content": "fn visit_identity(value: &str) -> Result<(), Error> {\n\n if value.is_empty() {\n\n return Err(Error::InvalidIdentity(value.into()));\n\n }\n\n for variable in VariableIter::new(value) {\n\n if VALID_VARIABLES.get(variable).is_none() {\n\n return Err(Error::InvalidIdentityVariable(variable.into()));\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mqtt/mqtt-policy/src/validator.rs", "rank": 13, "score": 316881.41993807245 }, { "content": "// The resolution of the regular expression is done by using a stack.\n\n// For example: &(!(0),1,1)\n\n// Stack fills up: Stack = ['&', '(', '!', '(','0']\n\n// When \")\" is encounter, the deepest boolean expression is solved:\n\n// Stack result Stack = ['&', '(', '1']\n\n// Stack fills up: Stack = ['&', '(', '1','0','0']\n\n// When \")\" is encounter, the last boolean expression is solved:\n\n// First all the value are load in temporary stack: tmp_fifo = ['1','0','0']\n\n// Then the operator '&' is extracted and the expression is solved\n\nfn solve_boolean_expression(expression: &str) -> Result<String, Error> {\n\n let mut fifo = Vec::new();\n\n\n\n for c in expression.chars() {\n\n match c {\n\n '(' | ',' | ' ' => (),\n\n '!' | '|' | '&' => fifo.push(Expr::Operator(c)),\n\n '1' => fifo.push(Expr::Value(true)),\n\n '0' => fifo.push(Expr::Value(false)),\n\n ')' => {\n\n let mut tmp_fifo = vec![];\n\n while let Some(Expr::Value(v)) = fifo.last() {\n\n tmp_fifo.push(*v);\n\n fifo.pop();\n\n }\n\n\n\n if let Some(Expr::Operator(val)) = fifo.pop() {\n\n let result = match val {\n\n '!' => {\n\n if tmp_fifo.len() > 1 {\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_parser.rs", "rank": 14, "score": 314565.4146041042 }, { "content": "fn encode_utf8_str<B>(item: &str, dst: &mut B) -> Result<(), EncodeError>\n\nwhere\n\n B: ByteBuf,\n\n{\n\n let len = item.len();\n\n dst.put_u16_bytes(\n\n len.try_into()\n\n .map_err(|_| EncodeError::StringTooLarge(len))?,\n\n );\n\n\n\n dst.put_slice_bytes(item.as_bytes());\n\n\n\n Ok(())\n\n}\n\n\n\n/// A tokio decoder for MQTT-format \"remaining length\" numbers.\n\n///\n\n/// These numbers are encoded with a variable-length scheme that uses the MSB of each byte as a continuation bit.\n\n///\n\n/// Ref: 2.2.3 Remaining Length\n", "file_path": "mqtt/mqtt3/src/proto/mod.rs", "rank": 15, "score": 311914.17394342064 }, { "content": "// Comma in env var name is forbidden because of that\n\n// We use this instead of simpler regex because we cannot match overlapping regular expression with regex.\n\nfn replace_env_var_with_boolean(expression: &str) -> String {\n\n let mut fifo = Vec::new();\n\n let mut flush_fifo = Vec::new();\n\n\n\n for c in expression.chars() {\n\n match c {\n\n '(' | '!' | '&' | '|' => fifo.push(c),\n\n ')' | ',' => {\n\n if flush_fifo.len() == 1 && Some('0') == flush_fifo.pop() {\n\n fifo.push('0');\n\n } else if flush_fifo.len() > 1 {\n\n fifo.push('1');\n\n };\n\n fifo.push(c);\n\n flush_fifo.clear();\n\n }\n\n _ => flush_fifo.push(c),\n\n }\n\n }\n\n\n\n fifo.iter().collect()\n\n}\n\n\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_parser.rs", "rank": 18, "score": 307243.1522907431 }, { "content": "pub fn arb_publish() -> impl Strategy<Value = Publish> {\n\n prop_oneof![\n\n (arb_packet_identifier(), arb_proto_publish())\n\n .prop_map(|(id, publish)| Publish::QoS0(id, publish)),\n\n (arb_packet_identifier(), arb_proto_publish())\n\n .prop_map(|(id, publish)| Publish::QoS12(id, publish)),\n\n ]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 19, "score": 307208.8425674082 }, { "content": "pub fn arb_payload() -> impl Strategy<Value = Bytes> {\n\n vec(num::u8::ANY, 0..128).prop_map(Bytes::from)\n\n}\n\n\n\nprop_compose! {\n\n pub fn arb_publication()(\n\n topic_name in arb_topic(),\n\n qos in arb_qos(),\n\n retain in proptest::bool::ANY,\n\n payload in arb_payload(),\n\n ) -> proto::Publication {\n\n proto::Publication {\n\n topic_name,\n\n qos,\n\n retain,\n\n payload,\n\n }\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 20, "score": 307208.8425674082 }, { "content": "pub fn arb_port() -> impl Strategy<Value = u16> {\n\n proptest::num::u16::ANY\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 21, "score": 307208.8425674081 }, { "content": "pub fn arb_ip() -> impl Strategy<Value = IpAddr> {\n\n IpAddr::arbitrary()\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 22, "score": 303692.19759212574 }, { "content": "pub fn arb_clientid() -> impl Strategy<Value = ClientId> {\n\n // TODO: Add in # and + once the broker can handle them\n\n \"[a-zA-Z0-9_()!@%,'=\\\\*\\\\$\\\\?\\\\-]{1,23}\".prop_map(Into::into)\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 23, "score": 303692.19759212574 }, { "content": "pub fn string_or_struct<'de, T, D>(deserializer: D) -> StdResult<T, D::Error>\n\nwhere\n\n T: Deserialize<'de> + FromStr<Err = serde_json::Error>,\n\n D: Deserializer<'de>,\n\n{\n\n // This is a Visitor that forwards string types to T's `FromStr` impl and\n\n // forwards map types to T's `Deserialize` impl. The `PhantomData` is to\n\n // keep the compiler from complaining about T being an unused generic type\n\n // parameter. We need T in order to know the Value type for the Visitor\n\n // impl.\n\n struct StringOrStruct<T>(PhantomData<fn() -> T>);\n\n\n\n impl<'de, T> Visitor<'de> for StringOrStruct<T>\n\n where\n\n T: Deserialize<'de> + FromStr<Err = serde_json::Error>,\n\n {\n\n type Value = T;\n\n\n\n fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n formatter.write_str(\"string or map\")\n", "file_path": "edgelet/edgelet-utils/src/ser_de.rs", "rank": 24, "score": 300813.832385762 }, { "content": "pub fn arb_auth_id() -> impl Strategy<Value = AuthId> {\n\n prop_oneof![\n\n \"[a-zA-Z0-9]{1,23}\".prop_map(AuthId::from),\n\n Just(AuthId::Anonymous)\n\n ]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 25, "score": 300278.56831375835 }, { "content": "fn is_variable_rule(value: &str) -> bool {\n\n lazy_static! {\n\n static ref VAR_PATTERN: Regex =\n\n Regex::new(r#\"\\{\\{[^\\{\\}]+\\}\\}\"#).expect(\"failed to create a Regex from pattern\");\n\n }\n\n VAR_PATTERN.is_match(value)\n\n}\n\n\n", "file_path": "mqtt/policy/src/core/builder.rs", "rank": 26, "score": 299708.00975066074 }, { "content": "fn get_expiration(cert: &str) -> Result<String, http_common::server::Error> {\n\n let cert = openssl::x509::X509::from_pem(cert.as_bytes())\n\n .map_err(|_| edgelet_http::error::server_error(\"failed to parse cert\"))?;\n\n\n\n // openssl::asn1::Asn1TimeRef does not expose any way to convert the ASN1_TIME to a Rust-friendly type\n\n //\n\n // Its Display impl uses ASN1_TIME_print, so we convert it into a String and parse it back\n\n // into a chrono::DateTime<chrono::Utc>\n\n let expiration = cert.not_after().to_string();\n\n let expiration = chrono::NaiveDateTime::parse_from_str(&expiration, \"%b %e %H:%M:%S %Y GMT\")\n\n .expect(\"cert not_after should parse\");\n\n let expiration = chrono::DateTime::<chrono::Utc>::from_utc(expiration, chrono::Utc);\n\n\n\n Ok(expiration.to_rfc3339())\n\n}\n\n\n", "file_path": "edgelet/edgelet-http-workload/src/module/cert/mod.rs", "rank": 27, "score": 298656.05464008043 }, { "content": "pub fn execute(config: &Path) -> Result<(), std::borrow::Cow<'static, str>> {\n\n // In production, running as root is the easiest way to guarantee the tool has write access to every service's config file.\n\n // But it's convenient to not do this for the sake of development because the the development machine doesn't necessarily\n\n // have the package installed and the users created, and it's easier to have the config files owned by the current user anyway.\n\n //\n\n // So when running as root, get the four users appropriately.\n\n // Otherwise, if this is a debug build, fall back to using the current user.\n\n // Otherwise, tell the user to re-run as root.\n\n let (aziotks_user, aziotcs_user, aziotid_user, aziottpm_user, iotedge_user) =\n\n if nix::unistd::Uid::current().is_root() {\n\n let aziotks_user = nix::unistd::User::from_name(\"aziotks\")\n\n .map_err(|err| format!(\"could not query aziotks user information: {}\", err))?\n\n .ok_or(\"could not query aziotks user information\")?;\n\n\n\n let aziotcs_user = nix::unistd::User::from_name(\"aziotcs\")\n\n .map_err(|err| format!(\"could not query aziotcs user information: {}\", err))?\n\n .ok_or(\"could not query aziotcs user information\")?;\n\n\n\n let aziotid_user = nix::unistd::User::from_name(\"aziotid\")\n\n .map_err(|err| format!(\"could not query aziotid user information: {}\", err))?\n", "file_path": "edgelet/iotedge/src/config/apply.rs", "rank": 28, "score": 298026.137684411 }, { "content": "pub fn arb_broker_event() -> impl Strategy<Value = BrokerEvent> {\n\n prop_oneof![\n\n arb_client_id_weighted().prop_flat_map(\n\n |id| arb_connect(id).prop_map(|p| BrokerEvent::ConnReq(client_id(&p.client_id), p))\n\n ),\n\n arb_client_id_weighted()\n\n .prop_map(|id| BrokerEvent::Disconnect(client_id(&id), proto::Disconnect)),\n\n arb_client_id_weighted().prop_flat_map(\n\n |id| arb_subscribe().prop_map(move |p| BrokerEvent::Subscribe(client_id(&id), p))\n\n ),\n\n arb_client_id_weighted()\n\n .prop_flat_map(|id| arb_unsubscribe()\n\n .prop_map(move |p| BrokerEvent::Unsubscribe(client_id(&id), p))),\n\n arb_client_id_weighted().prop_map(|id| BrokerEvent::CloseSession(client_id(&id))),\n\n arb_client_id_weighted().prop_map(|id| BrokerEvent::DropConnection(client_id(&id))),\n\n ]\n\n}\n", "file_path": "mqtt/mqtt-broker/tests/broker_model.rs", "rank": 29, "score": 296963.49350222363 }, { "content": "/// Identical to https://github.com/mehcode/config-rs/blob/0.8.0/src/file/format/yaml.rs#L32-L68\n\n/// except that it does not lower-case hash keys.\n\n///\n\n/// Unfortunately the `ValueKind` enum used by the `Value` constructor is not exported from the crate.\n\n/// It does however impl `From` for the various corresponding standard types, so this code uses those.\n\n/// The only difference is the fallback `_` case at the end.\n\nfn from_yaml_value(uri: Option<&String>, value: Yaml) -> Result<Value, ConfigError> {\n\n match value {\n\n Yaml::String(value) => Ok(Value::new(uri, value)),\n\n Yaml::Real(value) => {\n\n // TODO: Figure out in what cases this can fail?\n\n Ok(Value::new(\n\n uri,\n\n value\n\n .parse::<f64>()\n\n .map_err(|err| ConfigError::Foreign(Box::new(err)))?,\n\n ))\n\n }\n\n Yaml::Integer(value) => Ok(Value::new(uri, value)),\n\n Yaml::Boolean(value) => Ok(Value::new(uri, value)),\n\n Yaml::Hash(table) => {\n\n let mut m = HashMap::new();\n\n for (key, value) in table {\n\n if let Yaml::String(key) = key {\n\n m.insert(key, from_yaml_value(uri, value)?);\n\n }\n", "file_path": "edgelet/edgelet-utils/src/yaml_file_source.rs", "rank": 30, "score": 296873.80807039025 }, { "content": "pub fn arb_qos() -> impl Strategy<Value = proto::QoS> {\n\n prop_oneof![\n\n Just(proto::QoS::AtMostOnce),\n\n Just(proto::QoS::AtLeastOnce),\n\n Just(proto::QoS::ExactlyOnce),\n\n ]\n\n}\n\n\n\nprop_compose! {\n\n pub fn arb_subscription()(\n\n filter in arb_topic_filter(),\n\n max_qos in arb_qos(),\n\n ) -> Subscription {\n\n Subscription::new(filter, max_qos)\n\n }\n\n}\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 31, "score": 295140.1420590163 }, { "content": "pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(key: K, value: V) -> Result<EnvVar<K>, VarError> {\n\n let old_value = std::env::var_os(key.as_ref());\n\n std::env::set_var(key.as_ref(), value);\n\n\n\n Ok(EnvVar::new(key, old_value))\n\n}\n\n\n\npub struct EnvVar<K: AsRef<OsStr>> {\n\n key: K,\n\n old_value: Option<OsString>,\n\n}\n\n\n\nimpl<K: AsRef<OsStr>> EnvVar<K> {\n\n pub fn new(key: K, old_value: Option<OsString>) -> Self {\n\n Self { key, old_value }\n\n }\n\n}\n\n\n\nimpl<K: AsRef<OsStr>> Drop for EnvVar<K> {\n\n fn drop(&mut self) {\n\n if let Some(value) = self.old_value.take() {\n\n std::env::set_var(self.key.as_ref(), value);\n\n } else {\n\n std::env::remove_var(self.key.as_ref());\n\n }\n\n }\n\n}\n", "file_path": "mqtt/mqtt-broker-tests-util/src/env.rs", "rank": 32, "score": 293943.649186246 }, { "content": "type StoreCreateFn<S> = dyn Fn(&str) -> PersistResult<PublicationStore<S>>;\n", "file_path": "mqtt/mqtt-bridge/src/pump/builder.rs", "rank": 33, "score": 293588.98647747043 }, { "content": "pub fn arb_packet_identifier() -> impl Strategy<Value = proto::PacketIdentifier> {\n\n (1_u16..=u16::max_value())\n\n .prop_map(|i| proto::PacketIdentifier::new(i).expect(\"packet identifier failed\"))\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 34, "score": 291825.06724748155 }, { "content": "pub fn arb_client_id() -> impl Strategy<Value = proto::ClientId> {\n\n prop_oneof![\n\n Just(proto::ClientId::ServerGenerated),\n\n \"[a-zA-Z0-9]{1,23}\".prop_map(proto::ClientId::IdWithCleanSession),\n\n \"[a-zA-Z0-9]{1,23}\".prop_map(proto::ClientId::IdWithExistingSession)\n\n ]\n\n}\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 35, "score": 291825.06724748155 }, { "content": "pub fn get_string_from_file<P: AsRef<Path>>(path: P) -> Result<String, anyhow::Error> {\n\n let str = fs::read_to_string(path).context(\"Unable to read file\")?;\n\n Ok(str)\n\n}\n", "file_path": "edge-modules/api-proxy-module/src/utils/file.rs", "rank": 36, "score": 291729.28527177416 }, { "content": "pub fn create_client_from_module_env(address: &str) -> Result<Client<ClientIoSource>, VarError> {\n\n let provider_settings = get_provider_settings_from_env()?;\n\n let io_source = io_source_from_provider(provider_settings.clone(), address);\n\n\n\n let client_id = format!(\n\n \"{}/{}\",\n\n provider_settings.device_id().to_owned(),\n\n provider_settings.module_id().to_owned()\n\n );\n\n\n\n let api_version = \"2010-01-01\";\n\n let username = Some(format!(\n\n \"{}/{}/{}/?api-version={}\",\n\n provider_settings.iothub_hostname().to_owned(),\n\n provider_settings.device_id().to_owned(),\n\n provider_settings.module_id().to_owned(),\n\n api_version.to_owned()\n\n ));\n\n\n\n info!(\n", "file_path": "mqtt/mqtt-broker-tests-util/src/client.rs", "rank": 37, "score": 289752.2254923452 }, { "content": "pub fn arb_client_id_weighted() -> impl Strategy<Value = proto::ClientId> {\n\n let max = 10;\n\n prop_oneof![\n\n Just(proto::ClientId::ServerGenerated),\n\n \"[a-zA-Z0-9]{1,23}\".prop_map(proto::ClientId::IdWithCleanSession),\n\n \"[a-zA-Z0-9]{1,23}\".prop_map(proto::ClientId::IdWithExistingSession),\n\n (0..max).prop_map(|s| proto::ClientId::IdWithCleanSession(format!(\"client_{}\", s))),\n\n (0..max).prop_map(|s| proto::ClientId::IdWithExistingSession(format!(\"client_{}\", s)))\n\n ]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 38, "score": 288604.3396062933 }, { "content": "fn save_raw_config(twin: &HashMap<String, Value>) -> Result<()> {\n\n let config = twin\n\n .get(PROXY_CONFIG_TAG)\n\n .ok_or_else(|| anyhow!(\"Key {} not found in twin\", PROXY_CONFIG_TAG))?;\n\n\n\n let config = config\n\n .as_str()\n\n .context(\"Cannot extract json as base64 string\")?;\n\n\n\n let bytes =\n\n base64::decode(config).map_err(|err| anyhow!(\"Cannot decode base64. Caused by {}\", err))?;\n\n\n\n file::write_binary_to_file(&bytes, PROXY_CONFIG_PATH_RAW).map_err(|err| {\n\n anyhow!(\n\n \"Cannot write config file to path: {}. Caused by {}\",\n\n PROXY_CONFIG_PATH_RAW,\n\n err\n\n )\n\n })?;\n\n Ok(())\n\n}\n\n\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_monitor.rs", "rank": 39, "score": 287559.5805467904 }, { "content": "pub fn arb_pidq() -> impl Strategy<Value = proto::PacketIdentifierDupQoS> {\n\n prop_oneof![\n\n Just(proto::PacketIdentifierDupQoS::AtMostOnce),\n\n (arb_packet_identifier(), bool::ANY)\n\n .prop_map(|(id, dup)| proto::PacketIdentifierDupQoS::AtLeastOnce(id, dup)),\n\n (arb_packet_identifier(), bool::ANY)\n\n .prop_map(|(id, dup)| proto::PacketIdentifierDupQoS::ExactlyOnce(id, dup)),\n\n ]\n\n}\n\n\n\nprop_compose! {\n\n pub fn arb_proto_publish()(\n\n pidq in arb_pidq(),\n\n retain in bool::ANY,\n\n topic_name in arb_topic(),\n\n payload in arb_payload(),\n\n ) -> proto::Publish {\n\n proto::Publish {\n\n packet_identifier_dup_qos: pidq,\n\n retain,\n\n topic_name,\n\n payload,\n\n }\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 40, "score": 285473.98795865144 }, { "content": "pub fn parse_query(query: &str) -> HashMap<&str, &str> {\n\n query\n\n .split('&')\n\n .filter_map(|seg| {\n\n if seg.is_empty() {\n\n None\n\n } else {\n\n let mut tokens = seg.splitn(2, '=');\n\n tokens.next().map(|key| {\n\n let val = tokens.next().unwrap_or(\"\");\n\n (key, val)\n\n })\n\n }\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "edgelet/edgelet-utils/src/lib.rs", "rank": 41, "score": 277683.8766558234 }, { "content": "pub fn version_with_source_version() -> String {\n\n (&VERSION_WITH_SOURCE_VERSION).to_string()\n\n}\n\n\n", "file_path": "edgelet/edgelet-core/src/lib.rs", "rank": 42, "score": 275205.62826938485 }, { "content": "/// DNS names must conform to following rules per RFC 1035:\n\n/// - Length less than 64 characters\n\n/// - Contains only lowercase alphanumeric characters or '-'\n\n/// - Starts and ends with an alphanumeric character\n\n///\n\n/// This function removes illegal characters from a given DNS name and trims it to 63 characters.\n\npub fn sanitize_dns_name(name: String) -> String {\n\n name.trim_start_matches(|c: char| !c.is_ascii_alphabetic())\n\n .trim_end_matches(|c: char| !c.is_ascii_alphanumeric())\n\n .to_lowercase()\n\n .chars()\n\n .filter(|c| c.is_ascii_alphanumeric() || c == &'-')\n\n .take(63)\n\n .collect::<String>()\n\n}\n\n\n", "file_path": "edgelet/edgelet-http-workload/src/module/cert/mod.rs", "rank": 43, "score": 273065.81064156984 }, { "content": "// make sure to replace all edgehub-specific log levels to rust-compatible\n\nfn sanitize_log_level(log_level: impl Into<String>) -> String {\n\n let mut log_level: String = log_level.into().to_lowercase();\n\n for (key, value) in &EDGEHUB_2_RUST_LOG_LEVELS {\n\n if log_level.contains(key) {\n\n log_level = log_level.replace(key, value);\n\n }\n\n }\n\n log_level\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::sanitize_log_level;\n\n\n\n #[test]\n\n fn known_log_level_test() {\n\n assert_eq!(\"trace\", sanitize_log_level(\"verbose\"));\n\n assert_eq!(\"debug\", sanitize_log_level(\"debug\"));\n\n assert_eq!(\"info\", sanitize_log_level(\"information\"));\n\n assert_eq!(\"info\", sanitize_log_level(\"info\"));\n", "file_path": "mqtt/mqttd/src/tracing/edgehub.rs", "rank": 44, "score": 271994.5129842567 }, { "content": "fn to_serde_enum(val: impl Into<String>) -> String {\n\n format!(\"{:?}\", val.into())\n\n}\n\n\n", "file_path": "edgelet/iotedge/src/check/checks/container_connect_upstream.rs", "rank": 45, "score": 269608.326015439 }, { "content": "fn to_shell_var(val: impl Into<String>) -> String {\n\n let dollar = String::from(\"$\");\n\n let val_str = val.into();\n\n dollar + &val_str\n\n}\n\n\n", "file_path": "edgelet/iotedge/src/check/checks/container_connect_upstream.rs", "rank": 46, "score": 269608.326015439 }, { "content": "pub fn version() -> &'static str {\n\n &VERSION\n\n}\n\n\n", "file_path": "edgelet/edgelet-core/src/lib.rs", "rank": 47, "score": 269561.3255251011 }, { "content": "fn validate_length(id: &str) -> Result<(), ClientError> {\n\n let _: u16 = id.len().try_into().map_err(ClientError::StringTooLarge)?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "mqtt/mqtt-bridge/src/client.rs", "rank": 48, "score": 254104.1581916691 }, { "content": "fn parse_boolean_expression(expression: &str) -> String {\n\n let expression = replace_env_var_with_boolean(expression);\n\n match solve_boolean_expression(&expression) {\n\n Ok(x) => x,\n\n Err(e) => {\n\n error!(\"{}\", e);\n\n expression\n\n }\n\n }\n\n}\n\n\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_parser.rs", "rank": 49, "score": 253825.54535950103 }, { "content": "/// Creates an authorizer from a function.\n\n/// It wraps any provided function with an interface aligned with authorizer.\n\npub fn authorize_fn_ok<F>(f: F) -> impl Authorizer\n\nwhere\n\n F: Fn(&Activity) -> Authorization + Sync + 'static,\n\n{\n\n move |activity: &Activity| Ok::<_, Infallible>(f(activity))\n\n}\n\n\n\nimpl<F, E> Authorizer for F\n\nwhere\n\n F: Fn(&Activity) -> Result<Authorization, E> + Sync,\n\n E: StdError,\n\n{\n\n type Error = E;\n\n\n\n fn authorize(&self, activity: &Activity) -> Result<Authorization, Self::Error> {\n\n self(activity)\n\n }\n\n}\n\n\n\n/// Default implementation that always denies any operation a client intends to perform.\n", "file_path": "mqtt/mqtt-broker/src/auth/authorization.rs", "rank": 50, "score": 252556.90419027966 }, { "content": "pub fn start() -> Result<(JoinHandle<Result<()>>, ShutdownHandle), Error> {\n\n let shutdown_signal = Arc::new(Notify::new());\n\n let shutdown_handle = ShutdownHandle(shutdown_signal.clone());\n\n\n\n let token_server: JoinHandle<Result<()>> = tokio::spawn(async move {\n\n let token_client = get_token_client()?;\n\n let token_client = Arc::new(token_client);\n\n\n\n loop {\n\n let wait_shutdown = shutdown_signal.notified();\n\n let local_token_client = token_client.clone();\n\n\n\n let make_svc = make_service_fn(move |_conn| {\n\n let token_client_clone = local_token_client.clone();\n\n async move {\n\n Ok::<_, Error>(service_fn(move |req| {\n\n server_callback(req, token_client_clone.clone())\n\n }))\n\n }\n\n });\n", "file_path": "edge-modules/api-proxy-module/src/token_service/token_server.rs", "rank": 51, "score": 252555.58255051903 }, { "content": "fn translate(topic_name: &str) -> Option<String> {\n\n const DEVICE_OR_MODULE_ID: &str = r\"(?P<device_id>[^/]+)(/(?P<module_id>[^/]+))?\";\n\n\n\n lazy_static! {\n\n static ref UPSTREAM_TOPIC_PATTERNS: RegexSet = RegexSet::new(&[\n\n format!(\"\\\\$iothub/{}/twin/res/(?P<params>.*)\", DEVICE_OR_MODULE_ID),\n\n format!(\n\n \"\\\\$iothub/{}/twin/desired/(?P<params>.*)\",\n\n DEVICE_OR_MODULE_ID\n\n ),\n\n format!(\n\n \"\\\\$iothub/{}/methods/post/(?P<params>.*)\",\n\n DEVICE_OR_MODULE_ID\n\n )\n\n ])\n\n .expect(\"upstream topic patterns\");\n\n };\n\n\n\n if UPSTREAM_TOPIC_PATTERNS.is_match(topic_name) {\n\n Some(topic_name.replace(\"$iothub\", \"$downstream\"))\n", "file_path": "mqtt/mqtt-bridge/src/upstream/rpc/remote.rs", "rank": 52, "score": 251714.0106732683 }, { "content": "/// A type for a future that will be resolved to when `Bridge` exits.\n\ntype BridgeFuture = BoxFuture<'static, (String, Result<Result<(), BridgeError>, JoinError>)>;\n\n\n\n/// Encapsulates logic from `BridgeController` on how it manages with\n\n/// `BridgeFuture`s.\n\n///\n\n/// It represents a `FusedStream` of `Bridge` futures which resolves to a pair\n\n/// bridge name and exit result. It stores shutdown handles for each `Bridge`\n\n/// internally to request a stop when needed.\n\n#[derive(Default)]\n\npub(crate) struct Bridges {\n\n bridge_handles: HashMap<String, BridgeHandle>,\n\n config_updaters: HashMap<String, ConfigUpdater>,\n\n bridges: FuturesUnordered<BridgeFuture>,\n\n}\n\n\n\nimpl Bridges {\n\n pub(crate) async fn start_bridge<S>(&mut self, bridge: Bridge<S>, settings: &ConnectionSettings)\n\n where\n\n S: StreamWakeableState + Send + 'static,\n\n {\n", "file_path": "mqtt/mqtt-bridge/src/controller/bridges.rs", "rank": 53, "score": 251135.40759294998 }, { "content": "pub fn init_config() -> Result<Config, ConfigError> {\n\n let default_update_period = \"1.0\";\n\n let default_push_period = \"5.0\";\n\n let matches = App::new(\"obs_agent_client\")\n\n .arg(\n\n Arg::with_name(\"update-period\")\n\n .short(\"u\") \n\n .long(\"update-period\")\n\n .default_value(default_update_period)\n\n .help(\"Period in seconds betweeen successive updates of each instrument with a new metric measurement.\")\n\n )\n\n .arg(\n\n Arg::with_name(\"push-period\")\n\n .short(\"p\")\n\n .long(\"push-period\")\n\n .default_value(default_push_period)\n\n .help(\"Period in seconds between successive pushes of measurements out of the client.\")\n\n )\n\n .arg(\n\n Arg::with_name(\"otlp-endpoint\")\n", "file_path": "test/modules/obsagent-client/src/config.rs", "rank": 54, "score": 251090.61598453135 }, { "content": "fn resource(activity: &Activity) -> &str {\n\n match activity.operation() {\n\n // this is intentional. mqtt:connect should have empty resource.\n\n Operation::Connect => \"\",\n\n Operation::Publish(publish) => publish.publication().topic_name(),\n\n Operation::Subscribe(subscribe) => subscribe.topic_filter(),\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use matches::assert_matches;\n\n use test_case::test_case;\n\n\n\n use mqtt_broker::auth::{Activity, Authorization, Authorizer};\n\n\n\n use crate::auth::authorization::tests;\n\n\n\n use super::{Error, PolicyAuthorizer, PolicyUpdate};\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/auth/authorization/policy.rs", "rank": 55, "score": 250185.77696949858 }, { "content": "fn operation(activity: &Activity) -> &str {\n\n match activity.operation() {\n\n Operation::Connect => \"mqtt:connect\",\n\n Operation::Publish(_) => \"mqtt:publish\",\n\n Operation::Subscribe(_) => \"mqtt:subscribe\",\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/auth/authorization/policy.rs", "rank": 56, "score": 250185.77696949858 }, { "content": "fn identity(activity: &Activity) -> &str {\n\n activity.client_info().auth_id().as_str() //TODO: think about anonymous case.\n\n}\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/auth/authorization/policy.rs", "rank": 57, "score": 250185.77696949858 }, { "content": "fn validate_length(id: &str) -> Result<(), TryFromIntError> {\n\n let _: u16 = id.len().try_into()?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "mqtt/mqtt-util/src/client_io.rs", "rank": 58, "score": 248912.55826045998 }, { "content": "pub fn is_virtualized_env() -> Result<Option<bool>, Error> {\n\n if cfg!(target_os = \"linux\") {\n\n let status = Command::new(\"systemd-detect-virt\")\n\n .status()\n\n .context(ErrorKind::GetVirtualizationStatus)?;\n\n\n\n match status.code() {\n\n Some(0) => Ok(Some(true)),\n\n _ => Ok(Some(false)),\n\n }\n\n } else {\n\n Ok(None)\n\n }\n\n}\n", "file_path": "edgelet/edgelet-core/src/virtualization.rs", "rank": 59, "score": 247720.1207190435 }, { "content": "pub fn get_sdk_client() -> Result<Client, Error> {\n\n let client = match Client::new_for_edge_module(\n\n Tcp,\n\n None,\n\n TWIN_CONFIG_MAX_BACK_OFF,\n\n TWIN_CONFIG_KEEP_ALIVE,\n\n ) {\n\n Ok(client) => client,\n\n Err(err) => return Err(anyhow::anyhow!(\"Could not create client: {}\", err)),\n\n };\n\n\n\n Ok(client)\n\n}\n\n\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_monitor.rs", "rank": 60, "score": 243638.58646432403 }, { "content": "pub fn translate_outgoing_publish(publish: &mut proto::Publish) {\n\n if let Some(new_topic) = TRANSLATE_C2D.to_external(&publish.topic_name) {\n\n debug!(\n\n \"Translating outgoing publication {} to {}\",\n\n publish.topic_name, new_topic\n\n );\n\n publish.topic_name = new_topic;\n\n }\n\n}\n\n\n\nconst DEVICE_ID: &str = r\"(?P<device_id>[^/]+)\";\n\n\n\nconst MODULE_ID: &str = r\"(?P<module_id>[^/]+)\";\n\n\n\nconst DEVICE_OR_MODULE_ID: &str = r\"(?P<device_id>[^/]+)(/(?P<module_id>[^/]+))?\";\n\n\n\nmacro_rules! translate_d2c {\n\n ($(\n\n $translate_name:ident {\n\n to_internal { $new_from:expr, $new_to:expr }\n", "file_path": "mqtt/mqtt-edgehub/src/topic/translation.rs", "rank": 61, "score": 242870.74596782972 }, { "content": "fn parse_config(parse_config: &mut ConfigParser) -> Result<()> {\n\n //Read \"raw configuration\". Contains environment variables and sections.\n\n //Extract IO calls from core function for mocking\n\n let str = file::get_string_from_file(PROXY_CONFIG_PATH_RAW)?;\n\n\n\n let str = parse_config.get_parsed_config(&str)?;\n\n //Extract IO calls from core function for mocking\n\n file::write_binary_to_file(str.as_bytes(), PROXY_CONFIG_PATH_PARSED)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "edge-modules/api-proxy-module/src/monitors/config_monitor.rs", "rank": 62, "score": 241733.15235394757 }, { "content": "pub fn init_client(docker_url: &Url) -> Result<DockerApiClient> {\n\n // build the hyper client\n\n let client: Client<_, Body> = Connector::new(docker_url)\n\n .map_err(|e| Error::from(ErrorKind::Initialization(e.to_string())))?\n\n .into_client();\n\n\n\n // extract base path - the bit that comes after the scheme\n\n let base_path = docker_url\n\n .to_base_path()\n\n .context(ErrorKind::Initialization(\"\".to_owned()))?\n\n .to_str()\n\n .ok_or_else(|| ErrorKind::Initialization(\"\".to_owned()))?\n\n .to_string();\n\n let uri_composer = Box::new(|base_path: &str, path: &str| {\n\n // https://docs.rs/hyperlocal/0.6.0/src/hyperlocal/lib.rs.html#59\n\n let host = hex::encode(base_path.as_bytes());\n\n let host_str = format!(\"unix://{}:0{}\", host, path);\n\n let result: Uri = host_str.parse()?;\n\n\n\n Ok(result)\n", "file_path": "edgelet/edgelet-docker/src/runtime.rs", "rank": 63, "score": 240046.45193653335 }, { "content": "/// Creates an authenticator from a function.\n\n/// It wraps any provided function with an interface aligned with authenticator.\n\npub fn authenticate_fn_ok<F>(f: F) -> impl Authenticator<Error = Infallible>\n\nwhere\n\n F: Fn(AuthenticationContext) -> Option<AuthId> + Sync + 'static,\n\n{\n\n move |context| Ok(f(context))\n\n}\n\n\n\n#[async_trait]\n\nimpl<F, E> Authenticator for F\n\nwhere\n\n F: Fn(AuthenticationContext) -> Result<Option<AuthId>, E> + Sync,\n\n E: StdError + 'static,\n\n{\n\n type Error = E;\n\n\n\n async fn authenticate(\n\n &self,\n\n context: AuthenticationContext,\n\n ) -> Result<Option<AuthId>, Self::Error> {\n\n self(context)\n", "file_path": "mqtt/mqtt-broker/src/auth/authentication.rs", "rank": 64, "score": 239662.13677512459 }, { "content": "pub fn get_token_client() -> Result<TokenClient, Error> {\n\n let device_id =\n\n env::var(\"IOTEDGE_DEVICEID\").context(format!(\"Missing env var {}\", \"IOTEDGE_DEVICEID\"))?;\n\n let module_id =\n\n env::var(\"IOTEDGE_MODULEID\").context(format!(\"Missing env var {}\", \"IOTEDGE_MODULEID\"))?;\n\n let generation_id = env::var(\"IOTEDGE_MODULEGENERATIONID\")\n\n .context(format!(\"Missing env var {}\", \"IOTEDGE_MODULEGENERATIONID\"))?;\n\n let iothub_hostname = env::var(\"IOTEDGE_IOTHUBHOSTNAME\")\n\n .context(format!(\"Missing env var {}\", \"IOTEDGE_IOTHUBHOSTNAME\"))?;\n\n let workload_url = env::var(\"IOTEDGE_WORKLOADURI\")\n\n .context(format!(\"Missing env var {}\", \"IOTEDGE_WORKLOADURI\"))?;\n\n\n\n let work_load_api_client =\n\n edgelet_client::workload(&workload_url).context(\"Could not get workload client\")?;\n\n\n\n Ok(TokenClient::new(\n\n device_id,\n\n module_id,\n\n generation_id,\n\n iothub_hostname,\n", "file_path": "edge-modules/api-proxy-module/src/token_service/token_server.rs", "rank": 65, "score": 239014.2603791245 }, { "content": "pub fn serde_clone<T>(inp: &T) -> Result<T>\n\nwhere\n\n T: Serialize + DeserializeOwned,\n\n{\n\n Ok(serde_json::to_string(inp)\n\n .and_then(|s| serde_json::from_str(&s))\n\n .context(ErrorKind::SerdeClone)?)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use std::str::FromStr;\n\n\n\n use serde_derive::{Deserialize, Serialize};\n\n use serde_json::json;\n\n\n\n use super::{serde_clone, string_or_struct, StdResult};\n\n\n\n #[derive(Debug, Deserialize)]\n\n struct Options {\n", "file_path": "edgelet/edgelet-utils/src/ser_de.rs", "rank": 66, "score": 237398.6404482807 }, { "content": "fn arb_segment() -> impl Strategy<Value = Segment> {\n\n prop_oneof![\n\n \"[^+#\\0/]+\".prop_map(Segment::Level),\n\n Just(Segment::SingleLevelWildcard),\n\n Just(Segment::MultiLevelWildcard),\n\n ]\n\n}\n\n\n\nprop_compose! {\n\n pub fn arb_topic_filter()(\n\n segments in vec(arb_segment(), 1..20),\n\n multi in bool::ANY,\n\n ) -> TopicFilter {\n\n let mut filtered = vec![];\n\n for segment in segments {\n\n if segment != Segment::MultiLevelWildcard {\n\n filtered.push(segment);\n\n }\n\n }\n\n\n\n if multi || filtered.is_empty() {\n\n filtered.push(Segment::MultiLevelWildcard);\n\n }\n\n\n\n TopicFilter::new(filtered)\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/src/proptest.rs", "rank": 67, "score": 231178.24807651652 }, { "content": "fn publish_to(session: &mut Session, publication: &proto::Publication) -> Result<(), Error> {\n\n if let Some(event) = session.publish_to(publication)? {\n\n session.send(event)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n\npub struct BrokerBuilder<Z> {\n\n state: Option<BrokerSnapshot>,\n\n authorizer: Z,\n\n config: BrokerConfig,\n\n}\n\n\n\nimpl Default for BrokerBuilder<DenyAll> {\n\n fn default() -> Self {\n\n Self {\n\n state: None,\n\n authorizer: DenyAll,\n\n config: BrokerConfig::default(),\n", "file_path": "mqtt/mqtt-broker/src/broker.rs", "rank": 68, "score": 229429.82689895076 }, { "content": "fn arb_op() -> impl Strategy<Value = Op> {\n\n prop_oneof![\n\n Just(Op::Load),\n\n Just(Op::Store(BrokerSnapshot::default())),\n\n proptest::sample::select(FAILPOINTS).prop_map(|f| Op::AddFailpoint(f)),\n\n proptest::sample::select(FAILPOINTS).prop_map(|f| Op::RemoveFailpoint(f)),\n\n ]\n\n}\n\n\n", "file_path": "mqtt/mqtt-broker/tests/persist_failpoints.rs", "rank": 69, "score": 228459.9608664646 }, { "content": "pub fn translate_incoming_unsubscribe(client_id: &ClientId, unsubscribe: &mut proto::Unsubscribe) {\n\n for unsub_from in &mut unsubscribe.unsubscribe_from {\n\n if let Some(new_topic) = TRANSLATE_C2D.to_internal(unsub_from, client_id) {\n\n *unsub_from = new_topic;\n\n }\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/topic/translation.rs", "rank": 70, "score": 223757.08710345597 }, { "content": "pub fn translate_incoming_publish(client_id: &ClientId, publish: &mut proto::Publish) {\n\n if let Some(new_topic) = TRANSLATE_D2C.to_internal(&publish.topic_name, client_id) {\n\n debug!(\n\n \"Translating incoming publication {} to {}\",\n\n publish.topic_name, new_topic\n\n );\n\n publish.topic_name = new_topic;\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/topic/translation.rs", "rank": 71, "score": 223757.08710345597 }, { "content": "pub fn translate_incoming_subscribe(client_id: &ClientId, subscribe: &mut proto::Subscribe) {\n\n for mut sub_to in &mut subscribe.subscribe_to {\n\n if let Some(new_topic) = TRANSLATE_C2D.to_internal(&sub_to.topic_filter, client_id) {\n\n debug!(\n\n \"Translating subscription {} to {}\",\n\n sub_to.topic_filter, new_topic\n\n );\n\n sub_to.topic_filter = new_topic;\n\n }\n\n }\n\n}\n\n\n", "file_path": "mqtt/mqtt-edgehub/src/topic/translation.rs", "rank": 72, "score": 223757.08710345597 }, { "content": "fn init_meter(period: Duration, otlp_endpoint: String) -> metrics::Result<PushController> {\n\n let export_config = ExporterConfig {\n\n endpoint: otlp_endpoint,\n\n ..ExporterConfig::default()\n\n };\n\n opentelemetry_otlp::new_metrics_pipeline(tokio::spawn, delayed_interval)\n\n .with_export_config(export_config)\n\n .with_aggregator_selector(selectors::simple::Selector::Histogram(vec![\n\n 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9,\n\n ]))\n\n .with_period(period)\n\n .build()\n\n}\n\n\n\npub async fn run(config: Config) -> Result<(), OTelClientError> {\n\n let _started = init_meter(\n\n config.otel_config.push_period,\n\n config.otel_config.otlp_endpoint.clone(),\n\n )\n\n .map_err(OTelClientError::MetricsPipelineInitError)?;\n", "file_path": "test/modules/obsagent-client/src/otel_client.rs", "rank": 73, "score": 223709.66728920105 }, { "content": "fn update_pump(pump_diff: PumpDiff, current: &mut HashMap<String, TopicRule>) {\n\n let (added, removed) = pump_diff.into_parts();\n\n\n\n for added in added {\n\n current.insert(added.subscribe_to(), added);\n\n }\n\n\n\n for updated in &removed {\n\n current.remove(&updated.subscribe_to());\n\n }\n\n}\n\n\n\n#[derive(Debug, Deserialize)]\n\npub struct BridgeControllerUpdate(Vec<BridgeUpdate>);\n\n\n\nimpl BridgeControllerUpdate {\n\n pub fn from_bridge_topic_rules(name: &str, subs: &[TopicRule], forwards: &[TopicRule]) -> Self {\n\n let subscriptions = subs\n\n .iter()\n\n .map(|s| Direction::In(s.clone()))\n", "file_path": "mqtt/mqtt-bridge/src/config_update.rs", "rank": 74, "score": 221801.9909794953 }, { "content": "fn make_topics(rules: &[TopicRule]) -> Result<HashMap<String, TopicMapper>, BridgeError> {\n\n let topic_filters: Vec<TopicMapper> = rules\n\n .iter()\n\n .map(|topic| topic.clone().try_into())\n\n .collect::<Result<Vec<_>, _>>()?;\n\n\n\n let topic_filters = topic_filters\n\n .iter()\n\n .map(|topic| (topic.subscribe_to(), topic.clone()))\n\n .collect::<HashMap<_, _>>();\n\n\n\n Ok(topic_filters)\n\n}\n", "file_path": "mqtt/mqtt-bridge/src/pump/builder.rs", "rank": 75, "score": 221491.9700685271 }, { "content": "fn check_agent_image_version_nested(agent_image: &str) -> CheckResult {\n\n // We don't match the repo mcr.microsoft.com because in nested edge we expect the repo to be $upstream:443\n\n //\n\n // If the image spec doesn't match what we expected, it's a custom image, and we can't make\n\n // any determination of whether it's the right version or not. In that case we assume it is right.\n\n\n\n let re = Regex::new(r\".*?/azureiotedge-agent:(?P<Major>\\d+)\\.(?P<Minor>\\d+).*\")\n\n .expect(\"hard-coded regex cannot fail to parse\");\n\n\n\n if let Some(caps) = re.captures(agent_image) {\n\n let major = caps\n\n .name(\"Major\")\n\n .and_then(|version| version.as_str().parse::<u32>().ok());\n\n let minor = caps\n\n .name(\"Minor\")\n\n .and_then(|version| version.as_str().parse::<u32>().ok());\n\n\n\n if let (Some(major), Some(minor)) = (major, minor) {\n\n if major < 1 || (major == 1) && (minor < 2) {\n\n return CheckResult::Failed(\n", "file_path": "edgelet/iotedge/src/check/checks/check_agent_image.rs", "rank": 76, "score": 218242.63643566176 }, { "content": "fn base64_decode(data: String) -> Result<Vec<u8>, http_common::server::Error> {\n\n base64::decode(data).map_err(|err| {\n\n edgelet_http::error::bad_request(format!(\"invalid base64 encoding: {}\", err))\n\n })\n\n}\n\n\n\nasync fn master_encryption_key(\n\n client: &KeyClient,\n\n) -> Result<aziot_key_common::KeyHandle, http_common::server::Error> {\n\n client\n\n .create_key_if_not_exists(\n\n \"iotedge_master_encryption_id\",\n\n aziot_key_common::CreateKeyValue::Generate,\n\n &[aziot_key_common::KeyUsage::Encrypt],\n\n )\n\n .await\n\n .map_err(|err| {\n\n edgelet_http::error::server_error(format!(\n\n \"unable to load master encryption key: {}\",\n\n err\n\n ))\n\n })\n\n}\n", "file_path": "edgelet/edgelet-http-workload/src/module/data/mod.rs", "rank": 77, "score": 217604.49533852786 }, { "content": "pub fn write_binary_to_file<P: AsRef<Path>>(content: &[u8], path: P) -> Result<()> {\n\n let mut f = File::create(path).context(\"Cannot create file\")?;\n\n f.write_all(content)\n\n .context(\"File: Cannot write to file \")?;\n\n f.sync_data().context(\"File: cannot sync data\")?;\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "edge-modules/api-proxy-module/src/utils/file.rs", "rank": 78, "score": 211788.22911190687 }, { "content": "fn match_m2m_publish(packet: &Packet) -> Option<(proto::PacketIdentifier, String)> {\n\n const ANYTHING_BUT_SLASH: &str = r\"[^/]+\";\n\n lazy_static! {\n\n static ref M2M_PUBLISH_PATTERN: Regex = Regex::new(&format!(\n\n \"\\\\$edgehub/{}/{}/{}/inputs/.+\",\n\n ANYTHING_BUT_SLASH, ANYTHING_BUT_SLASH, ANYTHING_BUT_SLASH\n\n ))\n\n .expect(\"failed to create new Regex from pattern\");\n\n }\n\n\n\n let (packet_identifier_dup_qos, topic_name) = match packet {\n\n Packet::Publish(proto::Publish {\n\n packet_identifier_dup_qos,\n\n topic_name,\n\n ..\n\n }) => (packet_identifier_dup_qos, topic_name),\n\n _ => return None,\n\n };\n\n\n\n let packet_identifier = match packet_identifier_dup_qos {\n", "file_path": "mqtt/mqtt-edgehub/src/connection/delivery.rs", "rank": 79, "score": 210884.59722054258 }, { "content": "fn make_hyper_uri(scheme: &Scheme, path: &str) -> Result<Uri, Box<dyn StdError + Send + Sync>> {\n\n match scheme {\n\n #[cfg(unix)]\n\n Scheme::Unix(base) => Ok(hyperlocal::Uri::new(base, path).into()),\n\n Scheme::Http(base) => {\n\n let base = Url::parse(base)?;\n\n let url = base.join(path)?;\n\n let url = url.as_str().parse()?;\n\n Ok(url)\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub(crate) enum Scheme {\n\n #[cfg(unix)]\n\n Unix(String),\n\n Http(String),\n\n}\n\n\n", "file_path": "mqtt/edgelet-client/src/lib.rs", "rank": 80, "score": 206307.06140411083 }, { "content": "/// Coverts `openssl::asn1::Asn1TimeRef` into `chrono::DateTime<chrono::Utc>`.\n\n///\n\n/// `openssl::asn1::Asn1TimeRef` does not expose any way to convert the `ASN1_TIME` to a Rust-friendly type.\n\n/// Its Display impl uses `ASN1_TIME_print`, so we convert it into a String and parse it back\n\n/// into a `chrono::DateTime<chrono::Utc>`\n\npub fn parse_openssl_time(time: &Asn1TimeRef) -> ParseResult<DateTime<Utc>> {\n\n let time = time.to_string();\n\n let time = NaiveDateTime::parse_from_str(&time, \"%b %e %H:%M:%S %Y GMT\")?;\n\n Ok(DateTime::<Utc>::from_utc(time, Utc))\n\n}\n\n\n\n#[derive(Debug, thiserror::Error)]\n\npub enum ServerCertificateError {\n\n #[error(\"unable to read file content {0}\")]\n\n ReadFile(PathBuf, #[source] std::io::Error),\n\n\n\n #[error(transparent)]\n\n OpenSsl(#[from] openssl::error::ErrorStack),\n\n\n\n #[error(transparent)]\n\n Asn1Time(#[from] chrono::ParseError),\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(clippy::semicolon_if_nothing_returned)]\n", "file_path": "mqtt/mqtt-broker/src/tls.rs", "rank": 81, "score": 205776.0716988282 }, { "content": "fn sanitize_url(url: String) -> String {\n\n url.trim_end_matches(\".git\").replace(\"www.\", \"\").to_string()\n\n}\n\n\n\nimpl Git2Tree {\n\n fn format(&self, level: i32, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n if self.root.flag {\n\n writeln!(\n\n f,\n\n \"*** FAILURE *** Line which follows has a mismatched commit\"\n\n )?;\n\n }\n\n for _l in 0..level {\n\n write!(f, \" \")?;\n\n }\n\n write!(f, \"|- \")?;\n\n write!(f, \"{}\\n\", self.root)?;\n\n for child in self.children.iter() {\n\n child.format(level + 1, f)?;\n\n }\n", "file_path": "tools/check_submodules/src/tree.rs", "rank": 82, "score": 203503.83788502953 }, { "content": "type Result<T> = std::result::Result<T, Error>;\n\n\n\nconst API_VERSION: &str = \"2020-07-07\";\n\n\n\n#[derive(serde::Serialize, Clone)]\n\npub struct MgmtConfig {}\n\n\n\npub struct MgmtModule {\n\n pub details: ModuleDetails,\n\n pub image: String,\n\n}\n\n\n\npub struct MgmtClient {\n\n client: Client<Connector, Body>,\n\n host: String,\n\n}\n\n\n\nimpl MgmtClient {\n\n pub fn new(url: &Url) -> Result<Self> {\n\n let client: Client<_, Body> = Connector::new(url)\n", "file_path": "edgelet/iotedge/src/client.rs", "rank": 83, "score": 203193.48231965312 }, { "content": "#[cfg(unix)]\n\nfn parse_os_release_line(line: &str) -> Option<(&str, &str)> {\n\n let line = line.trim();\n\n\n\n let mut parts = line.split('=');\n\n\n\n let key = parts\n\n .next()\n\n .expect(\"split line will have at least one part\");\n\n\n\n let value = parts.next()?;\n\n\n\n // The value is essentially a shell string, so it can be quoted in single or double quotes, and can have escaped sequences using backslash.\n\n // For simplicitly, just trim the quotes instead of implementing a full shell string grammar.\n\n let value = if (value.starts_with('\\'') && value.ends_with('\\''))\n\n || (value.starts_with('\"') && value.ends_with('\"'))\n\n {\n\n &value[1..(value.len() - 1)]\n\n } else {\n\n value\n\n };\n\n\n\n Some((key, value))\n\n}\n", "file_path": "edgelet/iotedge/src/check/additional_info.rs", "rank": 84, "score": 200579.0893865854 }, { "content": "fn main() -> Result<()> {\n\n let json = r#\"{\n\n \"schemaVersion\": \"2020-10-30\",\n\n \"statements\": [\n\n {\n\n \"effect\": \"allow\",\n\n \"identities\": [\n\n \"actor_a\"\n\n ],\n\n \"operations\": [\n\n \"write\"\n\n ],\n\n \"resources\": [\n\n \"resource_1\"\n\n ]\n\n }\n\n ]\n\n }\"#;\n\n\n\n let policy = PolicyBuilder::from_json(json)\n", "file_path": "mqtt/policy/examples/evaluate.rs", "rank": 85, "score": 198178.2877551869 }, { "content": "fn find_first_block<T>(readable: &mut T) -> BincodeResult<BlockHeaderWithCrc>\n\nwhere\n\n T: Read + Seek,\n\n{\n\n // We don't need any explicit returns elsewhere as EOF should be an ERR.\n\n\n\n // There shouldn't be any issues from cast as block size is less than u64 max and usize max always.\n\n #[allow(clippy::cast_possible_truncation)]\n\n let serialized_block_size = *SERIALIZED_BLOCK_SIZE as usize;\n\n let buffer_size = (serialized_block_size * 2) as usize;\n\n\n\n // Read two blocks worth of data and scan to see if there is a block.\n\n // If not, then read another block worth of data and continue...\n\n let mut buf = vec![0; buffer_size];\n\n readable.read_exact(&mut buf)?;\n\n\n\n let all_zeroes = vec![0; buffer_size];\n\n loop {\n\n if buf == all_zeroes {\n\n readable.read_exact(&mut buf)?;\n", "file_path": "mqtt/mqtt-bridge/src/persist/waking_state/ring_buffer/mod.rs", "rank": 86, "score": 197609.95468461968 }, { "content": "fn main() -> Result<()> {\n\n init_logging();\n\n info!(\"Starting Watchdog\");\n\n\n\n let experimental_features_enabled = std::env::var(\"experimentalFeatures__enabled\")\n\n .unwrap_or_else(|_| \"false\".to_string())\n\n == \"true\";\n\n\n\n let mqtt_broker_enabled = std::env::var(\"experimentalFeatures__mqttBrokerEnabled\")\n\n .unwrap_or_else(|_| \"false\".to_string())\n\n == \"true\";\n\n\n\n let should_shutdown = register_shutdown_listener()\n\n .context(\"Failed to register sigterm listener. Shutting down.\")?;\n\n\n\n let edgehub_handle = run(\n\n \"Edge Hub\",\n\n \"dotnet\",\n\n vec![\"/app/Microsoft.Azure.Devices.Edge.Hub.Service.dll\".to_string()],\n\n Arc::clone(&should_shutdown),\n", "file_path": "edge-hub/watchdog/src/main.rs", "rank": 87, "score": 196059.91302412184 }, { "content": "/// Edge Hub log level can be set via `RuntimeLogLevel` env var.\n\n/// The following values are allowed: fatal, error, warning, info, debug, verbose.\n\n///\n\n/// To make it work with rust log levels, we do a simple pre-processing.\n\n/// E.g: this string: `warning,mqtt_broker::broker=debug` becomes `warn,mqtt_broker::broker=debug`.\n\npub fn init() {\n\n let mut log_level =\n\n env::var(EDGE_HUB_LOG_LEVEL_ENV).map_or_else(|_| \"info\".into(), sanitize_log_level);\n\n\n\n log_level = sanitize_log_level(log_level);\n\n\n\n let subscriber = fmt::Subscriber::builder()\n\n .with_max_level(Level::TRACE)\n\n .event_format(Format::edgehub())\n\n .with_env_filter(EnvFilter::new(log_level.clone()))\n\n .finish();\n\n let _ = tracing::subscriber::set_global_default(subscriber);\n\n\n\n let filter = log_level.parse().unwrap_or(LevelFilter::Info);\n\n let _ = LogTracer::init_with_filter(filter);\n\n}\n\n\n", "file_path": "mqtt/mqttd/src/tracing/edgehub.rs", "rank": 88, "score": 195908.35537055103 }, { "content": "pub fn not_found(\n\n message: impl std::convert::Into<std::borrow::Cow<'static, str>>,\n\n) -> http_common::server::Error {\n\n http_common::server::Error {\n\n status_code: http::StatusCode::NOT_FOUND,\n\n message: message.into(),\n\n }\n\n}\n\n\n", "file_path": "edgelet/edgelet-http/src/error.rs", "rank": 89, "score": 195897.29172822594 }, { "content": "pub fn init() {\n\n let log_level = EnvFilter::try_from_env(BROKER_LOG_LEVEL_ENV)\n\n .or_else(|_| EnvFilter::try_from_default_env())\n\n .unwrap_or_else(|_| EnvFilter::new(\"info\"));\n\n\n\n let subscriber = Subscriber::builder()\n\n .with_max_level(Level::TRACE)\n\n .with_env_filter(log_level)\n\n .finish();\n\n let _ = tracing::subscriber::set_global_default(subscriber);\n\n}\n", "file_path": "mqtt/mqttd/src/tracing/generic.rs", "rank": 90, "score": 195897.29172822594 }, { "content": "pub fn run(\n\n name: impl Into<String>,\n\n program: impl Into<String>,\n\n args: Vec<String>,\n\n should_shutdown: Arc<AtomicBool>,\n\n) -> Result<JoinHandle<()>> {\n\n let name = name.into();\n\n\n\n let child = Command::new(program.into())\n\n .args(args)\n\n .stdout(Stdio::inherit())\n\n .spawn()\n\n .with_context(|| format!(\"Failed to start {:?} process.\", name))?;\n\n\n\n let handle = thread::spawn(move || {\n\n info!(\"Launched {} process with pid {}\", name, child.id());\n\n\n\n let mut child_process = ChildProcess::new(name, child);\n\n\n\n while child_process.is_running() && !should_shutdown.load(Ordering::Relaxed) {\n", "file_path": "edge-hub/watchdog/src/child.rs", "rank": 91, "score": 195897.29172822594 }, { "content": "pub fn execute(\n\n connection_string: String,\n\n out_config_file: &Path,\n\n force: bool,\n\n) -> Result<(), std::borrow::Cow<'static, str>> {\n\n if !force && out_config_file.exists() {\n\n return Err(format!(\n\n \"\\\n\nFile {} already exists. Azure IoT Edge has already been configured.\n\n\n\nTo have the configuration take effect, run:\n\n\n\n sudo iotedge config apply\n\n\n\nTo reconfigure IoT Edge, run:\n\n\n\n sudo iotedge config mp --force\n\n\",\n\n out_config_file.display()\n\n )\n", "file_path": "edgelet/iotedge/src/config/mp.rs", "rank": 92, "score": 195897.29172822594 }, { "content": "type CommitId = String;\n", "file_path": "tools/check_submodules/src/tree.rs", "rank": 93, "score": 195761.76297521195 }, { "content": "type RemoteUrl = String;\n", "file_path": "tools/check_submodules/src/tree.rs", "rank": 94, "score": 195761.76297521195 }, { "content": "/// Search a query string for the provided key.\n\npub fn find_query(\n\n key: &str,\n\n query: &[(std::borrow::Cow<'_, str>, std::borrow::Cow<'_, str>)],\n\n) -> Option<String> {\n\n query.iter().find_map(|q| {\n\n if q.0 == key {\n\n let value = percent_encoding::percent_decode_str(&q.1)\n\n .decode_utf8()\n\n .ok()?\n\n .to_string();\n\n\n\n Some(value)\n\n } else {\n\n None\n\n }\n\n })\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n", "file_path": "edgelet/edgelet-http/src/lib.rs", "rank": 95, "score": 193850.28293632902 }, { "content": "pub fn bad_request(\n\n message: impl std::convert::Into<std::borrow::Cow<'static, str>>,\n\n) -> http_common::server::Error {\n\n http_common::server::Error {\n\n status_code: http::StatusCode::BAD_REQUEST,\n\n message: message.into(),\n\n }\n\n}\n\n\n\n// This function is only used by auth, so it doesn't need to be externally callable.\n\npub(crate) fn forbidden() -> http_common::server::Error {\n\n http_common::server::Error {\n\n status_code: http::StatusCode::FORBIDDEN,\n\n message: \"forbidden\".into(),\n\n }\n\n}\n\n\n", "file_path": "edgelet/edgelet-http/src/error.rs", "rank": 96, "score": 193843.59937452996 }, { "content": "pub fn notary_init(\n\n home_dir: &Path,\n\n registry_server_hostname: &str,\n\n cert_buf: &[u8],\n\n) -> Result<PathBuf, Error> {\n\n // Validate inputs\n\n if registry_server_hostname.is_empty() {\n\n return Err(ErrorKind::InitializeNotary(\"hostname is empty\".to_owned()).into());\n\n }\n\n\n\n if cert_buf.is_empty() {\n\n return Err(\n\n ErrorKind::InitializeNotary(\"root ca pem string content is empty\".to_owned()).into(),\n\n );\n\n }\n\n\n\n // Directory structure example\n\n // home directory : /var/lib/aziot/edged\n\n // notary directory : /var/lib/aziot/edged/notary\n\n // hostname directory : /var/lib/aziot/edged/notary/sanitized_hostname\n", "file_path": "edgelet/edgelet-docker/src/notary.rs", "rank": 97, "score": 193843.59937452996 }, { "content": "pub fn execute(\n\n old_config_file: &Path,\n\n new_config_file: &Path,\n\n force: bool,\n\n) -> Result<(), std::borrow::Cow<'static, str>> {\n\n // In production, the command needs to run as root. But it's convenient for developers to run as the current user.\n\n //\n\n // So if this is a debug build, use the current user. Otherwise, tell the user to re-run as root.\n\n let root_user = {\n\n let current_uid = nix::unistd::Uid::current();\n\n if current_uid.is_root() {\n\n let root_user = nix::unistd::User::from_uid(current_uid)\n\n .map_err(|err| format!(\"could not query root user information: {}\", err))?\n\n .ok_or(\"could not query root user information\")?;\n\n\n\n root_user\n\n } else if cfg!(debug_assertions) {\n\n let current_user = nix::unistd::User::from_uid(nix::unistd::Uid::current())\n\n .map_err(|err| format!(\"could not query current user information: {}\", err))?\n\n .ok_or(\"could not query current user information\")?;\n", "file_path": "edgelet/iotedge/src/config/import/mod.rs", "rank": 98, "score": 193843.59937452996 }, { "content": "pub fn runtime_state(\n\n id: Option<&str>,\n\n response_state: Option<&InlineResponse200State>,\n\n) -> ModuleRuntimeState {\n\n response_state.map_or_else(ModuleRuntimeState::default, |state| {\n\n let status = state\n\n .status()\n\n .and_then(|status| match status {\n\n \"created\" | \"paused\" | \"restarting\" => Some(ModuleStatus::Stopped),\n\n \"removing\" | \"exited\" => status_from_exit_code(state.exit_code()),\n\n \"dead\" => Some(ModuleStatus::Dead),\n\n \"running\" => Some(ModuleStatus::Running),\n\n _ => Some(ModuleStatus::Unknown),\n\n })\n\n .unwrap_or(ModuleStatus::Unknown);\n\n ModuleRuntimeState::default()\n\n .with_status(status)\n\n .with_exit_code(state.exit_code())\n\n .with_status_description(state.status().map(ToOwned::to_owned))\n\n .with_started_at(\n", "file_path": "edgelet/edgelet-docker/src/module.rs", "rank": 99, "score": 193843.59937452996 } ]
Rust
libtransact/src/context/manager/sync.rs
leebradley/transact
6aca715a5cd5b89e08e2906e48e046f210c56387
/* * Copyright 2019 Bitwise IO, Inc. * Copyright 2019 Cargill Incorporated * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ----------------------------------------------------------------------------- */ use std::sync::{Arc, Mutex}; use crate::context::error::ContextManagerError; use crate::context::{manager, ContextId, ContextLifecycle}; use crate::protocol::receipt::{Event, TransactionReceipt}; use crate::state::Read; #[derive(Clone)] pub struct ContextManager { internal_manager: Arc<Mutex<manager::ContextManager>>, } impl ContextManager { pub fn new(database: Box<dyn Read<StateId = String, Key = String, Value = Vec<u8>>>) -> Self { ContextManager { internal_manager: Arc::new(Mutex::new(manager::ContextManager::new(database))), } } pub fn get( &self, context_id: &ContextId, keys: &[String], ) -> Result<Vec<(String, Vec<u8>)>, ContextManagerError> { self.internal_manager .lock() .expect("Lock in the get method was poisoned") .get(context_id, keys) } pub fn set_state( &self, context_id: &ContextId, key: String, value: Vec<u8>, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in set_state was poisoned") .set_state(context_id, key, value) } pub fn delete_state( &self, context_id: &ContextId, key: &str, ) -> Result<Option<Vec<u8>>, ContextManagerError> { self.internal_manager .lock() .expect("Lock in delete_state was poisoned") .delete_state(context_id, key) } pub fn add_event( &self, context_id: &ContextId, event: Event, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in add_event was poisoned") .add_event(context_id, event) } pub fn add_data( &self, context_id: &ContextId, data: Vec<u8>, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in add_data was poisoned") .add_data(context_id, data) } } impl ContextLifecycle for ContextManager { fn create_context(&mut self, dependent_contexts: &[ContextId], state_id: &str) -> ContextId { self.internal_manager .lock() .expect("Lock in create_context was poisoned") .create_context(dependent_contexts, state_id) } fn drop_context(&mut self, context_id: ContextId) { self.internal_manager .lock() .expect("Lock in drop_context was poisoned") .drop_context(context_id) } fn get_transaction_receipt( &self, context_id: &ContextId, transaction_id: &str, ) -> Result<TransactionReceipt, ContextManagerError> { self.internal_manager .lock() .expect("Lock in get_transaction_receipt was poisoned") .get_transaction_receipt(context_id, transaction_id) } fn clone_box(&self) -> Box<dyn ContextLifecycle> { Box::new(self.clone()) } }
/* * Copyright 2019 Bitwise IO, Inc. * Copyright 2019 Cargill Incorporated * * 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. * --------------------------------------------------------------
pub fn get( &self, context_id: &ContextId, keys: &[String], ) -> Result<Vec<(String, Vec<u8>)>, ContextManagerError> { self.internal_manager .lock() .expect("Lock in the get method was poisoned") .get(context_id, keys) } pub fn set_state( &self, context_id: &ContextId, key: String, value: Vec<u8>, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in set_state was poisoned") .set_state(context_id, key, value) } pub fn delete_state( &self, context_id: &ContextId, key: &str, ) -> Result<Option<Vec<u8>>, ContextManagerError> { self.internal_manager .lock() .expect("Lock in delete_state was poisoned") .delete_state(context_id, key) } pub fn add_event( &self, context_id: &ContextId, event: Event, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in add_event was poisoned") .add_event(context_id, event) } pub fn add_data( &self, context_id: &ContextId, data: Vec<u8>, ) -> Result<(), ContextManagerError> { self.internal_manager .lock() .expect("Lock in add_data was poisoned") .add_data(context_id, data) } } impl ContextLifecycle for ContextManager { fn create_context(&mut self, dependent_contexts: &[ContextId], state_id: &str) -> ContextId { self.internal_manager .lock() .expect("Lock in create_context was poisoned") .create_context(dependent_contexts, state_id) } fn drop_context(&mut self, context_id: ContextId) { self.internal_manager .lock() .expect("Lock in drop_context was poisoned") .drop_context(context_id) } fn get_transaction_receipt( &self, context_id: &ContextId, transaction_id: &str, ) -> Result<TransactionReceipt, ContextManagerError> { self.internal_manager .lock() .expect("Lock in get_transaction_receipt was poisoned") .get_transaction_receipt(context_id, transaction_id) } fn clone_box(&self) -> Box<dyn ContextLifecycle> { Box::new(self.clone()) } }
--------------- */ use std::sync::{Arc, Mutex}; use crate::context::error::ContextManagerError; use crate::context::{manager, ContextId, ContextLifecycle}; use crate::protocol::receipt::{Event, TransactionReceipt}; use crate::state::Read; #[derive(Clone)] pub struct ContextManager { internal_manager: Arc<Mutex<manager::ContextManager>>, } impl ContextManager { pub fn new(database: Box<dyn Read<StateId = String, Key = String, Value = Vec<u8>>>) -> Self { ContextManager { internal_manager: Arc::new(Mutex::new(manager::ContextManager::new(database))), } }
random
[ { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/up.sql", "rank": 0, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/up.sql", "rank": 1, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/down.sql", "rank": 2, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/up.sql", "rank": 3, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/down.sql", "rank": 4, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/down.sql", "rank": 5, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/up.sql", "rank": 6, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/down.sql", "rank": 7, "score": 165368.19925065702 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-21-043900-multiple-tree-support/up.sql", "rank": 8, "score": 162872.98501985933 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/up.sql", "rank": 9, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/up.sql", "rank": 10, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/down.sql", "rank": 11, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/up.sql", "rank": 12, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/down.sql", "rank": 13, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/down.sql", "rank": 14, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/down.sql", "rank": 15, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/up.sql", "rank": 16, "score": 154403.89431502853 }, { "content": "-- Copyright 2021 Cargill Incorporated\n", "file_path": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-21-043900-multiple-tree-support/up.sql", "rank": 17, "score": 151800.57277773504 }, { "content": "/// `state::Write` provides a way to write to a particular state storage system.\n\n///\n\n/// It provides the ability for the caller to either compute the next `StateId` -\n\n/// useful for validating expected results - or committing the results to an\n\n/// underlying store.\n\n///\n\n/// A `StateId`, in the context of Write, is used to indicate the\n\n/// starting state on which the changes will be applied. It can be thought of\n\n/// as the identifier of a checkpoint or snapshot.\n\n///\n\n/// All operations are made using `StateChange` instances. These are the\n\n/// ordered set of changes to be applied onto the given `StateId`.\n\n///\n\n/// Implementations are expected to be thread-safe.\n\npub trait Write: Sync + Send + Clone {\n\n /// A reference to a checkpoint in state. It could be a merkle hash for\n\n /// a merkle database.\n\n type StateId;\n\n /// The Key that is being stored in state.\n\n type Key;\n\n /// The Value that is being stored in state.\n\n type Value;\n\n\n\n /// Given a `StateId` and a slice of `StateChange` values, persist the\n\n /// state changes and return the resulting next `StateId` value.\n\n ///\n\n /// This function will persist the state values to the\n\n /// underlying storage mechanism.\n\n ///\n\n /// # Errors\n\n ///\n\n /// Any issues with committing the processing results will return a\n\n /// `StateWriteError`.\n\n fn commit(\n", "file_path": "libtransact/src/state/mod.rs", "rank": 18, "score": 71136.33103946129 }, { "content": "/// Compute a state address for a given contract.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `name` - the name of the contract\n\n/// * `version` - the version of the contract\n\npub fn compute_contract_address(name: &str, version: &str) -> Result<Vec<u8>, AddressingError> {\n\n let s = String::from(name) + \",\" + version;\n\n let hash = sha512_hash(s.as_bytes());\n\n Ok([CONTRACT_ADDRESS_PREFIX_BYTES, &hash[..32]].concat())\n\n}\n\n\n", "file_path": "libtransact/src/protocol/sabre.rs", "rank": 19, "score": 57256.734456145896 }, { "content": "fn find_scar<P: AsRef<Path>>(name: &str, version: &str, paths: &[P]) -> Result<PathBuf, Error> {\n\n let file_name_pattern = format!(\"{}_*.scar\", name);\n\n\n\n validate_scar_file_name(name)?;\n\n\n\n let version_req = VersionReq::parse(version)?;\n\n\n\n // Start with all scar files that match the name, from all paths\n\n paths\n\n .iter()\n\n .map(|path| {\n\n let file_path_pattern = path.as_ref().join(&file_name_pattern);\n\n let pattern_string = file_path_pattern\n\n .to_str()\n\n .ok_or_else(|| Error::new(\"name is not valid UTF-8\"))?;\n\n Ok(glob(pattern_string)?)\n\n })\n\n .collect::<Result<Vec<_>, Error>>()?\n\n .into_iter()\n\n .flatten()\n", "file_path": "libtransact/src/contract/archive/mod.rs", "rank": 20, "score": 52492.319236351716 }, { "content": "fn apply_write_check(\n\n write_check_data: &SmallbankTransactionPayload_WriteCheckTransactionData,\n\n context: &mut dyn TransactionContext,\n\n) -> Result<(), ApplyError> {\n\n match load_account(write_check_data.get_customer_id(), context)? {\n\n None => {\n\n warn!(\"Invalid transaction: during WRITE_CHECK, Account must exist\");\n\n Err(ApplyError::InvalidTransaction(\"Account must exist\".into()))\n\n }\n\n Some(mut account) => {\n\n let balance = account.get_checking_balance() - write_check_data.get_amount();\n\n account.set_checking_balance(balance);\n\n save_account(&account, context)\n\n }\n\n }\n\n}\n\n\n", "file_path": "libtransact/src/families/smallbank/handler.rs", "rank": 21, "score": 44819.94140311073 }, { "content": "/// Compute a state address for a given smart permission.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `org_id` - the organization's id\n\n/// * `name` - smart permission name\n\npub fn compute_smart_permission_address(\n\n org_id: &str,\n\n name: &str,\n\n) -> Result<Vec<u8>, AddressingError> {\n\n let org_id_hash = sha512_hash(org_id.as_bytes());\n\n let name_hash = sha512_hash(name.as_bytes());\n\n Ok([\n\n SMART_PERMISSION_ADDRESS_PREFIX_BYTES,\n\n &org_id_hash[..3],\n\n &name_hash[..29],\n\n ]\n\n .concat())\n\n}\n\n\n", "file_path": "libtransact/src/protocol/sabre.rs", "rank": 22, "score": 43796.1437768611 }, { "content": "/// Writes the given change log entry to the database\n\nfn write_change_log(\n\n db_writer: &mut dyn DatabaseWriter,\n\n root_hash: &[u8],\n\n change_log: &ChangeLogEntry,\n\n) -> Result<(), StateDatabaseError> {\n\n db_writer.index_put(CHANGE_LOG_INDEX, root_hash, &change_log.to_bytes()?)?;\n\n Ok(())\n\n}\n\n\n", "file_path": "libtransact/src/state/merkle/kv/mod.rs", "rank": 23, "score": 43786.88686047 }, { "content": "fn command_namespace_permissions_txn(\n\n signer: &dyn Signer,\n\n) -> Result<Transaction, SabreCommandExecutorError> {\n\n CreateNamespaceRegistryPermissionActionBuilder::new()\n\n .with_namespace(COMMAND_PREFIX.into())\n\n .with_contract_name(COMMAND_NAME.into())\n\n .with_read(true)\n\n .with_write(true)\n\n .into_payload_builder()\n\n .map_err(|err| {\n\n SabreCommandExecutorError::Internal(format!(\n\n \"Unable to get sabre payload for create namespace registry permission: {}\",\n\n err\n\n ))\n\n })?\n\n .into_transaction_builder()\n\n .map_err(|err| {\n\n SabreCommandExecutorError::Internal(format!(\n\n \"Unable to get transaction builder for create namespace registry permission: {}\",\n\n err\n", "file_path": "examples/sabre_command_executor/src/main.rs", "rank": 24, "score": 42798.51899257615 }, { "content": "fn make_smallbank_write_check_txn(\n\n rng: &mut StdRng,\n\n num_accounts: usize,\n\n accounts: &[u32],\n\n) -> smallbank::SmallbankTransactionPayload_WriteCheckTransactionData {\n\n let mut payload = smallbank::SmallbankTransactionPayload_WriteCheckTransactionData::new();\n\n // value in range should always exist\n\n let customer_id = accounts[rng.gen_range(0, num_accounts)];\n\n payload.set_customer_id(customer_id);\n\n payload.set_amount(rng.gen_range(10, 200));\n\n\n\n payload\n\n}\n\n\n", "file_path": "libtransact/src/families/smallbank/workload/playlist.rs", "rank": 25, "score": 41842.650691296134 }, { "content": "// Validate that the scar file name does not contain underscores, otherwise return an error.\n\nfn validate_scar_file_name(name: &str) -> Result<(), Error> {\n\n if name.contains('_') {\n\n return Err(Error::new(&format!(\n\n \"invalid scar file name, must not include '_': {}\",\n\n name\n\n )));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "libtransact/src/contract/archive/mod.rs", "rank": 26, "score": 40081.423148981725 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/up.sql", "rank": 27, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/up.sql", "rank": 28, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/down.sql", "rank": 29, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-06-30-121000-initialize-tables/down.sql", "rank": 30, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-15-013200-initialize-tables/down.sql", "rank": 31, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/down.sql", "rank": 32, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-07-29-105100-change-log/up.sql", "rank": 33, "score": 38488.77994439278 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/postgres/migrations/2021-07-29-105100-change-log/up.sql", "rank": 34, "score": 38488.77994439278 }, { "content": "// Validate that the metadata collected from the manifest contains a contract name which matches\n\n// the name of the scar file. This includes swapping any underscores which appear in the contract\n\n// name with dashes, as underscores are not allowed in scar file names.\n\nfn validate_metadata(file_name: &str, contract_name: &str) -> Result<(), Error> {\n\n if file_name != contract_name.replace(\"_\", \"-\") {\n\n return Err(Error::new(&format!(\n\n \"scar file name `{}` does not match contract name in manifest `{}`\",\n\n file_name, contract_name,\n\n )));\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "libtransact/src/contract/archive/mod.rs", "rank": 35, "score": 38451.55893523505 }, { "content": "-- Copyright 2021 Cargill Incorporated\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": "libtransact/src/state/merkle/sql/migration/sqlite/migrations/2021-06-21-043900-multiple-tree-support/up.sql", "rank": 36, "score": 37722.69172819623 }, { "content": "fn write_vec_as_hex(f: &mut fmt::Formatter, field_name: &str, data: &[Vec<u8>]) -> fmt::Result {\n\n write!(f, \"{}: [\", field_name)?;\n\n f.write_str(\n\n &data\n\n .iter()\n\n .map(|datum| format!(\"{:?}\", hex::encode(datum)))\n\n .collect::<Vec<_>>()\n\n .join(\", \"),\n\n )?;\n\n f.write_str(\"]\")\n\n}\n\n\n\nimpl From<hex::FromHexError> for ProtoConversionError {\n\n fn from(e: hex::FromHexError) -> Self {\n\n ProtoConversionError::SerializationError(format!(\"{}\", e))\n\n }\n\n}\n\n\n\nimpl From<std::string::FromUtf8Error> for ProtoConversionError {\n\n fn from(e: std::string::FromUtf8Error) -> Self {\n", "file_path": "libtransact/src/protocol/transaction.rs", "rank": 37, "score": 36227.458661044846 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Batches of transactions.\n\n//!\n", "file_path": "libtransact/src/protocol/batch.rs", "rank": 38, "score": 136.21211339883502 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! The fundamental transaction.\n\n//!\n", "file_path": "libtransact/src/protocol/transaction.rs", "rank": 39, "score": 136.21211339883504 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\n//! # Hyperledger Transact\n\n//!\n", "file_path": "libtransact/src/lib.rs", "rank": 40, "score": 136.21211339883502 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\nuse cylinder::SigningError;\n\n\n", "file_path": "libtransact/src/workload/error.rs", "rank": 41, "score": 135.92462110370624 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! Methods for interacting with State.\n\n//!\n", "file_path": "libtransact/src/state/mod.rs", "rank": 42, "score": 135.4634425205112 }, { "content": "/*\n\n * Copyright 2017 Bitwise IO, Inc.\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\n//! Traits for handling the execution of a transaction.\n\n//!\n", "file_path": "libtransact/src/handler/mod.rs", "rank": 43, "score": 134.72308883451916 }, { "content": "/*\n\n * Copyright 2017 Bitwise IO, Inc.\n\n * Copyright 2019 Cargill Incorporated\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::error::Error;\n\n\n\n#[derive(Debug)]\n", "file_path": "libtransact/src/handler/error.rs", "rank": 44, "score": 134.47349488096393 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse std::io::Write;\n\n\n\nuse diesel::{\n", "file_path": "libtransact/src/state/merkle/sql/models/sqlite.rs", "rank": 45, "score": 134.07851901517827 }, { "content": "/*\n\n * Copyright 2019 Bitwise IO, Inc.\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! Batch scheduling with transaction execution APIs\n\n//!\n", "file_path": "libtransact/src/scheduler/mod.rs", "rank": 46, "score": 133.99091294256402 }, { "content": "/*\n\n * Copyright 2017 Bitwise IO, Inc.\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\n//! A struct for wrapping a `sabre_sdk::TransactionContext`.\n\n//!\n", "file_path": "libtransact/src/handler/sabre.rs", "rank": 47, "score": 133.99091294256402 }, { "content": "/*\n\n * Copyright 2019 Bitwise IO, Inc.\n\n * Copyright 2019 Cargill Incorporated\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 mod sync;\n\n\n\nuse std::collections::HashMap;\n", "file_path": "libtransact/src/context/manager/mod.rs", "rank": 49, "score": 133.05360830344736 }, { "content": "/*\n\n * Copyright 2018 Intel Corporation\n\n * Copyright 2019 Bitwise IO, Inc.\n\n * Copyright 2021 Cargill Incorporated\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\n\n#[cfg(feature = \"state-merkle-leaf-reader\")]\n", "file_path": "libtransact/src/state/merkle/mod.rs", "rank": 50, "score": 131.76412920653132 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2019 Cargill Incorporated\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\n\nuse crate::protocol::transaction::TransactionPair;\n\nuse std::{error::Error, fmt};\n", "file_path": "libtransact/src/execution/adapter/error.rs", "rank": 51, "score": 131.59373335949076 }, { "content": "// Copyright 2020 Cargill Incorporated\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\nmod state;\n", "file_path": "libtransact/tests/mod.rs", "rank": 52, "score": 130.10775343384847 }, { "content": "/*\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\nuse std::collections::BTreeMap;\n\nuse std::io::Cursor;\n\n\n", "file_path": "libtransact/src/state/merkle/node.rs", "rank": 53, "score": 130.02821903326566 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\npub mod tree;\n", "file_path": "libtransact/src/scheduler/parallel/mod.rs", "rank": 54, "score": 129.36822722928866 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2020 Cargill Incorporated\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\n\nextern crate protoc_rust;\n\n\n\nuse protoc_rust::Customize;\n\n\n\nuse std::env;\n\nuse std::fs;\n\nuse std::fs::File;\n\nuse std::io::Write;\n\nuse std::path::Path;\n\n\n", "file_path": "libtransact/build.rs", "rank": 55, "score": 129.12828114788726 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\n\n * Copyright 2019-2021 Cargill Incorporated\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#[cfg(feature = \"workload-batch-gen\")]\n\npub mod batch_gen;\n\npub mod error;\n", "file_path": "libtransact/src/workload/mod.rs", "rank": 56, "score": 129.08358469553733 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\npub mod playlist;\n\n\n\nuse cylinder::Signer;\n", "file_path": "libtransact/src/families/command/workload/mod.rs", "rank": 57, "score": 128.39583123065154 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\nuse protobuf::Message;\n\nuse protobuf::RepeatedField;\n\n\n", "file_path": "libtransact/src/protocol/command.rs", "rank": 58, "score": 128.282522971939 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse std::error::Error;\n\nuse std::fmt;\n\n\n", "file_path": "libtransact/src/state/merkle/error.rs", "rank": 59, "score": 128.282522971939 }, { "content": "/*\n\n * Copyright 2017 Intel Corporation\n\n * Copyright 2021 Cargill Incorporated\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::error::Error;\n\nuse std::fmt;\n\nuse std::io::Error as StdIoError;\n", "file_path": "libtransact/src/families/smallbank/workload/error.rs", "rank": 60, "score": 128.2247831608777 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\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 std::fs::File;\n\nuse std::io::Write;\n\nuse std::time::Duration;\n\n\n\nuse clap::ArgMatches;\n\nuse transact::families::smallbank::workload::playlist::{\n", "file_path": "cli/src/action/playlist.rs", "rank": 61, "score": 127.81919172961595 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! A Sabre compatible Smallbank smart contract\n\n\n\n#[macro_use]\n", "file_path": "examples/sabre_smallbank/src/main.rs", "rank": 62, "score": 127.69218394601008 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\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\n\nuse std::error::Error;\n\nuse std::fmt;\n\n\n", "file_path": "libtransact/src/state/error.rs", "rank": 63, "score": 127.6417273503457 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\n\n * Copyright 2018 Intel Corporation\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\n\nuse protobuf::Message;\n\nuse sha2::{Digest, Sha512};\n", "file_path": "libtransact/src/families/smallbank/handler.rs", "rank": 64, "score": 127.46295075278542 }, { "content": "/*\n\n * Copyright 2020-2021 Cargill Incorporated\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\n\n//! An Sqlite-backed implementation of the database traits.\n\n//!\n\n//! # Note\n", "file_path": "libtransact/src/database/sqlite.rs", "rank": 65, "score": 127.19989993091062 }, { "content": "// Copyright 2020 Cargill Incorporated\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#[cfg(feature = \"state-merkle\")]\n\nmod merkle;\n", "file_path": "libtransact/tests/state/mod.rs", "rank": 66, "score": 127.19989993091062 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse std::collections::HashMap;\n\n\n\n#[cfg(feature = \"sqlite\")]\n", "file_path": "libtransact/src/state/merkle/sql/operations/insert_nodes.rs", "rank": 67, "score": 126.99633722596444 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! A basic Command Transaction Family\n\n\n\nuse std::{thread, time};\n", "file_path": "libtransact/src/families/command/handler.rs", "rank": 68, "score": 126.99633722596442 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! A Sabre compatible Command family smart contract\n\n\n\n#[macro_use]\n", "file_path": "examples/sabre_command/src/main.rs", "rank": 69, "score": 126.99633722596441 }, { "content": "/*\n\n * Copyright 2020 Cargill Incorporated\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\n\nuse glob::PatternError;\n\nuse semver::Error as SemverError;\n\n\n", "file_path": "libtransact/src/contract/archive/error.rs", "rank": 70, "score": 126.9046196514455 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse std::collections::BTreeMap;\n\n\n\nuse diesel::prelude::*;\n", "file_path": "libtransact/src/state/merkle/sql/operations/get_path.rs", "rank": 71, "score": 126.90461965144549 }, { "content": "/*\n\n * Copyright 2019 Bitwise IO, Inc.\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\n\nmod error;\n\nmod internal;\n\nmod reader;\n", "file_path": "libtransact/src/execution/executor/mod.rs", "rank": 72, "score": 126.54566389611111 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\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\n\n//! The `receipts` module contains structs that supply information on the processing\n\n//! of `Transaction`s\n\n\n", "file_path": "libtransact/src/protocol/receipt.rs", "rank": 73, "score": 126.54566389611112 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Provides the MigrationManageer trait.\n\n\n\n#[cfg(feature = \"postgres\")]\n", "file_path": "libtransact/src/state/merkle/sql/migration/mod.rs", "rank": 74, "score": 126.49339871851427 }, { "content": "/*\n\n * Copyright 2018 Intel Corporation\n\n * Copyright 2019 Bitwise IO, Inc.\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\n\nmod change_log;\n\nmod error;\n", "file_path": "libtransact/src/state/merkle/kv/mod.rs", "rank": 75, "score": 126.38903420964812 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\n\n * Copyright 2017 Intel Corporation\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\n\n//! Tools for generating signed batches from a stream of transactions\n\n\n", "file_path": "libtransact/src/workload/batch_gen.rs", "rank": 76, "score": 126.33736739337812 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\n\n * Copyright 2017 Intel Corporation\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\n\n//! Tools for generating signed batches from a stream of transactions\n\n\n", "file_path": "libtransact/src/workload/source.rs", "rank": 77, "score": 126.3373673933781 }, { "content": "/*\n\n * Copyright 2018 Intel Corporation\n\n * Copyright 2021 Cargill Incorporated\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\n\npub mod error;\n\npub mod playlist;\n", "file_path": "libtransact/src/families/smallbank/workload/mod.rs", "rank": 78, "score": 126.3373673933781 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! A Backend implementation for SQLite databases.\n\n\n\nuse std::convert::TryFrom;\n", "file_path": "libtransact/src/state/merkle/sql/backend/sqlite.rs", "rank": 79, "score": 126.30816052388008 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse std::collections::HashMap;\n\n\n\nuse diesel::dsl::{delete, update};\n", "file_path": "libtransact/src/state/merkle/sql/operations/prune_entries.rs", "rank": 80, "score": 126.22696593443928 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! A `Scheduler` which schedules transaction for execution one at time.\n\n\n\nmod core;\n", "file_path": "libtransact/src/scheduler/serial/mod.rs", "rank": 81, "score": 125.79480495677734 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Provides a runner to submit `BatchWorkload`s\n\n\n\nuse std::collections::HashMap;\n", "file_path": "libtransact/src/workload/runner.rs", "rank": 82, "score": 125.62752621399454 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! Implementation of the components used for interfacing with the component\n\n//! reponsible for the execution of transactions (usually the Executor).\n\n\n", "file_path": "libtransact/src/scheduler/serial/execution.rs", "rank": 83, "score": 125.62752621399454 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\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//! Module containing InternalError implementation.\n\n\n\nuse std::error;\n\nuse std::fmt;\n\n\n", "file_path": "libtransact/src/error/internal.rs", "rank": 84, "score": 125.55667798395974 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\nuse diesel::dsl::insert_into;\n\n#[cfg(feature = \"sqlite\")]\n\nuse diesel::dsl::select;\n", "file_path": "libtransact/src/state/merkle/sql/operations/get_or_create_tree.rs", "rank": 85, "score": 125.55667798395973 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\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\n\n//! Contains execution adapter components and interfaces that proxy the `Transaction`\n\n//! and its associated state.\n\n\n", "file_path": "libtransact/src/execution/adapter/mod.rs", "rank": 86, "score": 125.15565224244074 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\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\n\n//! Contains components that are used to directly execute a `Transaction`\n\n//! and return a `execution::adapter::ExecutionResult`.\n\n\n", "file_path": "libtransact/src/execution/mod.rs", "rank": 87, "score": 125.00539151034634 }, { "content": "/*\n\n * Copyright 2018 Bitwise IO, Inc.\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\n\n//! Protobuf structs and associated conversion traits.\n\n\n\nuse std::error::Error as StdError;\n", "file_path": "libtransact/src/protos.rs", "rank": 88, "score": 125.00539151034633 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! Implementation of core scheduler thread.\n\n\n\nuse crate::context::manager::ContextManagerError;\n", "file_path": "libtransact/src/scheduler/serial/core.rs", "rank": 89, "score": 124.95430950972363 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Tools for generating command family transactions\n\nuse protobuf::RepeatedField;\n\nuse rand::prelude::*;\n", "file_path": "libtransact/src/families/command/workload/playlist.rs", "rank": 90, "score": 124.89363460384506 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Errors related to SQL-backed merkle-radix state representation.\n\n\n\nuse std::error::Error;\n", "file_path": "libtransact/src/state/merkle/sql/error.rs", "rank": 91, "score": 124.28838838470423 }, { "content": "/*\n\n * Copyright 2021 Cargill Incorporated\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\n\n#[cfg(feature = \"sqlite\")]\n\nuse diesel::dsl::select;\n\nuse diesel::dsl::{delete, insert_into, update};\n", "file_path": "libtransact/src/state/merkle/sql/operations/update_index.rs", "rank": 92, "score": 124.23771726666205 }, { "content": "/*\n\n * Copyright 2017 Intel Corporation\n\n * Copyright 2021 Cargill Incorporated\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\n\n//! Tools for generating YAML playlists of transactions and continous payloads\n\nuse std::borrow::Cow;\n", "file_path": "libtransact/src/families/smallbank/workload/playlist.rs", "rank": 93, "score": 124.22336430028945 }, { "content": "// Copyright 2021 Cargill Incorporated\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//! An example application that uses the command family workload to generate\n\n//! transactions and run them with Sabre\n\n\n\n#[macro_use]\n\nextern crate log;\n\n\n", "file_path": "examples/sabre_command_executor/src/main.rs", "rank": 94, "score": 124.19664758284779 }, { "content": "// Copyright 2018-2021 Cargill Incorporated\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 std::error::Error;\n\nuse std::fmt;\n\n\n\nuse clap::Error as ClapError;\n\n\n\n#[derive(Debug)]\n", "file_path": "cli/src/error.rs", "rank": 95, "score": 123.95625277803974 }, { "content": "// Copyright 2021 Cargill Incorporated\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 std::error::Error;\n\nuse std::fmt;\n\n\n\nuse clap::Error as ClapError;\n\n\n\n#[derive(Debug)]\n", "file_path": "examples/sabre_command_executor/src/error.rs", "rank": 96, "score": 123.95625277803978 }, { "content": "/*\n\n * Copyright 2019-2021 Cargill Incorporated\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\n\n//! Transact structs for batches, transactions and receipts.\n\n//!\n\n//! These structs cover the core protocols of the Transact system. Batches of transactions are\n", "file_path": "libtransact/src/protocol/mod.rs", "rank": 97, "score": 123.7451510677624 }, { "content": "/*\n\n * Copyright 2019 Bitwise IO, Inc.\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\n\nuse super::internal::{ExecutorCommand, ExecutorCommandSender};\n\n\n\nuse crate::scheduler::ExecutionTask;\n", "file_path": "libtransact/src/execution/executor/reader.rs", "rank": 98, "score": 123.63903922614377 }, { "content": "/*\n\n * Copyright 2019 Cargill Incorporated\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\n\n//! Implementation of core MultiScheduler thread.\n\n\n\nuse crate::scheduler::{BatchExecutionResult, SchedulerError};\n", "file_path": "libtransact/src/scheduler/multi/core.rs", "rank": 99, "score": 123.62964349646764 } ]
Rust
src/bin/aoc2021/day12.rs
knutwalker/aoc
711aa804ab14fc2c376db5a4140a845fa902068d
use aoc::ProcessInput; use indexmap::IndexSet; use std::{convert::Infallible, str::FromStr}; type Input = Cave; type Output = usize; register!( "input/day12.txt"; (cave: input!(process Input)) -> Output { cave.count_paths(false); cave.count_paths(true); } ); #[derive(Clone, Copy, Debug)] pub struct Cave { graph: [u16; 16], start: u8, end: u8, on_visit: u16, } impl Cave { fn count_paths(self, can_visit_twice: bool) -> usize { fn iterate(c: &Cave, node: u8, visited: u16, twice: bool) -> usize { let mut to_visit = c.graph[usize::from(node)]; to_visit &= !visited | [0, c.on_visit][usize::from(twice)]; let mut paths = 0; while to_visit != 0 { let next = to_visit & to_visit.wrapping_neg(); to_visit &= to_visit - 1; let next_node = next.trailing_zeros() as u8; if next_node == c.end { paths += 1; } else { let next_twice = twice && next & visited != next; let next_visited = visited | (c.on_visit & next); paths += iterate(c, next_node, next_visited, next_twice); } } paths } iterate( &self, self.start, 1 << self.start, can_visit_twice, ) } } impl ProcessInput for Cave { type In = input!(parse Connection); type Out = Self; fn process(input: <Self::In as aoc::PuzzleInput>::Out) -> Self::Out { let mut ids = IndexSet::new(); let mut graph = [0; 16]; for path in input { let source = ids.insert_full(path.source).0; let target = ids.insert_full(path.target).0; graph[source] |= 1 << target; graph[target] |= 1 << source; } let on_visit = ids .iter() .map(|id| match id { CaveType::Small(_) => 1, _ => 0, }) .enumerate() .fold(0, |on_visit, (id, ov)| on_visit | (ov << id)); let start = ids.get_index_of(&CaveType::Start).unwrap() as u8; let end = ids.get_index_of(&CaveType::End).unwrap() as u8; Self { graph, start, end, on_visit, } } } #[derive(Clone, Debug)] pub struct Connection { source: CaveType, target: CaveType, } impl FromStr for Connection { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { let (source, target) = s.split_once('-').unwrap(); Ok(Self { source: source.parse()?, target: target.parse()?, }) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum CaveType { Start, End, Small(String), Big(String), } impl FromStr for CaveType { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "start" => Self::Start, "end" => Self::End, small if small.as_bytes()[0].is_ascii_lowercase() => Self::Small(small.to_string()), big => Self::Big(big.to_string()), }) } } #[cfg(test)] mod tests { use super::*; use aoc::{Solution, SolutionExt}; use test::Bencher; #[test] fn test_ex() { let input = r#" start-A start-b A-c A-b b-d A-end b-end "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 10); assert_eq!(res2, 36); } #[test] fn test_ex2() { let input = r#" dc-end HN-start start-kj dc-start dc-HN LN-dc HN-end kj-sa kj-HN kj-dc "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 19); assert_eq!(res2, 103); } #[test] fn test_ex3() { let input = r#" fs-end he-DX fs-he start-DX pj-DX end-zg zg-sl zg-pj pj-he RW-he fs-DX pj-RW zg-RW start-pj he-WI zg-he pj-fs start-RW "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 226); assert_eq!(res2, 3509); } #[test] fn test() { let (res1, res2) = Solver::run_on_input(); assert_eq!(res1, 5756); assert_eq!(res2, 144_603); } #[bench] fn bench_parsing(b: &mut Bencher) { let input = Solver::puzzle_input(); b.bytes = input.len() as u64; b.iter(|| Solver::parse_input(input)); } #[bench] fn bench_pt1(b: &mut Bencher) { let cave = Solver::parse_input(Solver::puzzle_input()); b.iter(|| cave.count_paths(false)); } #[bench] fn bench_pt2(b: &mut Bencher) { let cave = Solver::parse_input(Solver::puzzle_input()); b.iter(|| cave.count_paths(true)); } }
use aoc::ProcessInput; use indexmap::IndexSet; use std::{convert::Infallible, str::FromStr}; type Input = Cave; type Output = usize; register!( "input/day12.txt"; (cave: input!(process Input)) -> Output { cave.count_paths(false); cave.count_paths(true); } ); #[derive(Clone, Copy, Debug)] pub struct Cave { graph: [u16; 16], start: u8, end: u8, on_visit: u16, } impl Cave { fn count_paths(self, can_visit_twice: bool) -> usize { fn iterate(c: &Cave, node: u8, visited: u16, twice: bool) -> usize { let mut to_visit = c.graph[usize::from(node)]; to_visit &= !visited | [0, c.on_visit][usize::from(twice)]; let mut paths = 0; while to_visit != 0 { let next = to_visit & to_visit.wrapping_neg(); to_visit &= to_visit - 1; let next_node = next.trailing_zeros() as u8; if next_node == c.end { paths += 1; } else { let next_twice = twice && next & visited != next; let next_visited = visited | (c.on_visit & next); paths += iterate(c, next_node, next_visited, next_twice); } } paths } iterate( &self, self.start, 1 << self.start, can_visit_twice, ) } } impl ProcessInput for Cave { type In = input!(parse Connection); type Out = Self; fn process(input: <Self::In as aoc::PuzzleInput>::Out) -> Self::Out { let mut ids = IndexSet::new(); let mut graph = [0; 16]; for path in input { let source = ids.insert_full(path.source).0; let target = ids.insert_full(path.target).0; graph[source] |= 1 << target; graph[target] |= 1 << source; } let on_visit = ids .iter() .map(|id| match id { CaveType::Small(_) => 1, _ => 0, }) .enumerate() .fold(0, |on_visit, (id, ov)| on_visit | (ov << id)); let start = ids.get_index_of(&CaveType::Start).unwrap() as u8; let end = ids.get_index_of(&CaveType::End).unwrap() as u8; Self { graph, start, end, on_visit, } } } #[derive(Clone, Debug)] pub struct Connection { source: CaveType, target: CaveType, } impl FromStr for Connection { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { let (source, target) = s.split_once('-').unwrap(); Ok(Self { source: source.parse()?, target: target.parse()?, }) } } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum CaveType { Start, End, Small(String), Big(String), } impl FromStr for CaveType { type Err = Infallible; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "start" => Self::Start, "end" => Self::End, small if small.as_bytes()[0].is_ascii_lowercase() => Self::Small(small.to_string()), big => Self::Big(big.to_string()), }) } } #[cfg(test)] mod tests { use super::*; use aoc::{Solution, SolutionExt}; use test::Bencher; #[test] fn test_ex() { let input = r#" start-A start-b A-c A-b b-d A-end b-end "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 10); assert_eq!(res2, 36); } #[test] fn test_ex2() { let input = r#" dc-end HN-start start-kj dc-start dc-HN LN-dc HN-end kj-sa kj-HN kj-dc "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 19); assert_eq!(res2, 103); } #[test] fn test_ex3() { let input = r#" fs-end he-DX fs-he start-DX pj-DX end-zg zg-sl zg-pj pj-he RW-
#[test] fn test() { let (res1, res2) = Solver::run_on_input(); assert_eq!(res1, 5756); assert_eq!(res2, 144_603); } #[bench] fn bench_parsing(b: &mut Bencher) { let input = Solver::puzzle_input(); b.bytes = input.len() as u64; b.iter(|| Solver::parse_input(input)); } #[bench] fn bench_pt1(b: &mut Bencher) { let cave = Solver::parse_input(Solver::puzzle_input()); b.iter(|| cave.count_paths(false)); } #[bench] fn bench_pt2(b: &mut Bencher) { let cave = Solver::parse_input(Solver::puzzle_input()); b.iter(|| cave.count_paths(true)); } }
he fs-DX pj-RW zg-RW start-pj he-WI zg-he pj-fs start-RW "#; let (res1, res2) = Solver::run_on(input); assert_eq!(res1, 226); assert_eq!(res2, 3509); }
function_block-function_prefixed
[ { "content": "pub fn lines(s: &str) -> impl Iterator<Item = &str> + '_ {\n\n s.lines().map(str::trim).filter(|line| !line.is_empty())\n\n}\n\n\n\npub struct PuzzleSolution<T> {\n\n pub part1: T,\n\n pub part2: T,\n\n pub parse_time: Duration,\n\n pub part1_time: Duration,\n\n pub part2_time: Duration,\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 0, "score": 98708.18918508127 }, { "content": "pub trait ProcessInput {\n\n type In: PuzzleInput;\n\n type Out;\n\n\n\n fn process(input: <Self::In as PuzzleInput>::Out) -> Self::Out;\n\n}\n\n\n\nimpl PuzzleInput for () {\n\n type Out = Self;\n\n\n\n fn from_input(_input: &str) -> Self::Out {}\n\n}\n\n\n\npub struct Blocks<T>(PhantomData<T>);\n\n\n\nimpl<T> PuzzleInput for Blocks<T>\n\nwhere\n\n T: PuzzleInput,\n\n{\n\n type Out = Vec<T::Out>;\n", "file_path": "src/lib.rs", "rank": 1, "score": 47704.266949715355 }, { "content": "pub trait PuzzleInput\n\nwhere\n\n Self: Sized,\n\n{\n\n type Out;\n\n\n\n fn from_input(input: &str) -> Self::Out;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 2, "score": 36552.195722499164 }, { "content": "pub trait SolutionExt: Solution {\n\n fn run_on(input: &str) -> (Self::Output, Self::Output) {\n\n let input = Self::parse_input(input);\n\n let PuzzleSolution { part1, part2, .. } = Self::run(input, Duration::ZERO);\n\n (part1, part2)\n\n }\n\n\n\n fn run_on_input() -> (Self::Output, Self::Output) {\n\n let input = Self::puzzle_input();\n\n Self::run_on(input)\n\n }\n\n}\n\n\n\nimpl<T: Solution> SolutionExt for T {}\n\n\n\npub struct ResultLine {\n\n prefix: String,\n\n duration: Duration,\n\n solution: Option<Box<dyn Display>>,\n\n}\n", "file_path": "src/lib.rs", "rank": 3, "score": 29536.377652439853 }, { "content": "pub trait Solution {\n\n type Input: PuzzleInput;\n\n type Output;\n\n\n\n fn puzzle_input() -> &'static str;\n\n\n\n #[inline]\n\n fn parse_input(input: &str) -> <Self::Input as PuzzleInput>::Out {\n\n <Self::Input as PuzzleInput>::from_input(input)\n\n }\n\n\n\n fn run(\n\n input: <Self::Input as PuzzleInput>::Out,\n\n parse_time: Duration,\n\n ) -> PuzzleSolution<Self::Output>;\n\n\n\n fn solve() -> PuzzleSolution<Self::Output> {\n\n let input = Self::puzzle_input();\n\n let start = Instant::now();\n\n let input = Self::parse_input(input);\n\n let parse_time = start.elapsed();\n\n Self::run(input, parse_time)\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 4, "score": 22081.747929202003 }, { "content": "pub trait PopFirst {\n\n type Out;\n\n\n\n fn pop_first(self) -> Self::Out;\n\n}\n\n\n\nimpl<T> PopFirst for Vec<T> {\n\n type Out = T;\n\n\n\n fn pop_first(self) -> Self::Out {\n\n self.into_iter().next().unwrap()\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 5, "score": 21185.271533920197 }, { "content": "pub trait MedianExt<T> {\n\n fn median(self) -> T;\n\n}\n\n\n\nimpl<'a, T: Ord> MedianExt<&'a T> for &'a mut [T] {\n\n #[inline]\n\n fn median(self) -> &'a T {\n\n let index = self.len() / 2;\n\n self.select_nth_unstable(index).1\n\n }\n\n}\n\n\n\nimpl<T: Ord + Copy> MedianExt<T> for Vec<T> {\n\n #[inline]\n\n fn median(mut self) -> T {\n\n *(self.as_mut_slice().median())\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 6, "score": 19635.785739998548 }, { "content": "\n\n fn from_input(input: &str) -> Self::Out {\n\n input.split(\"\\n\\n\").map(|l| T::from_input(l)).collect()\n\n }\n\n}\n\n\n\npub struct Parsing<T>(PhantomData<T>);\n\n\n\nimpl<T> PuzzleInput for Parsing<T>\n\nwhere\n\n T: FromStr,\n\n <T as FromStr>::Err: Debug,\n\n{\n\n type Out = Vec<T>;\n\n\n\n fn from_input(input: &str) -> Self::Out {\n\n lines(input).map(|l| T::from_str(l).unwrap()).collect()\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 7, "score": 8.600257133199307 }, { "content": " };\n\n}\n\n\n\ndef_impl!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize);\n\n\n\n#[derive(Copy, Clone, Debug, PartialEq, Eq)]\n\npub struct MinMax<T> {\n\n pub min: T,\n\n pub max: T,\n\n}\n\n\n\nimpl<T: MinDefault + MaxDefault> Default for MinMax<T> {\n\n fn default() -> Self {\n\n Self {\n\n min: MinDefault::min_default(),\n\n max: MaxDefault::max_default(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 8, "score": 8.595654169669144 }, { "content": " fn puzzle_input() -> &'static str {\n\n ::std::include_str!($file)\n\n }\n\n\n\n #[inline]\n\n fn run(\n\n mut $input: <$input_ty as $crate::PuzzleInput>::Out,\n\n parse_time: ::std::time::Duration,\n\n ) -> $crate::PuzzleSolution<Self::Output> {\n\n let start = ::std::time::Instant::now();\n\n let part1 = $part1;\n\n let part1_time = start.elapsed();\n\n let start = ::std::time::Instant::now();\n\n let part2 = $part2;\n\n let part2_time = start.elapsed();\n\n\n\n $crate::PuzzleSolution {\n\n part1,\n\n part2,\n\n part1_time,\n", "file_path": "src/lib.rs", "rank": 9, "score": 6.363405310019829 }, { "content": "pub struct As<T>(PhantomData<T>);\n\n\n\nimpl<T> PuzzleInput for As<T>\n\nwhere\n\n T: From<String>,\n\n{\n\n type Out = Vec<T>;\n\n\n\n fn from_input(input: &str) -> Self::Out {\n\n lines(input).map(|l| T::from(String::from(l))).collect()\n\n }\n\n}\n\n\n\npub struct Post<T>(PhantomData<T>);\n\n\n\nimpl<T> PuzzleInput for Post<T>\n\nwhere\n\n T: ProcessInput,\n\n{\n\n type Out = T::Out;\n", "file_path": "src/lib.rs", "rank": 10, "score": 6.110040783442007 }, { "content": "\n\n (chunk $input_ty:ty) => {\n\n input!(blocks input!($input_ty))\n\n };\n\n\n\n (first $input_ty:ty) => {\n\n input!(process $crate::First<$input_ty>)\n\n };\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! register {\n\n ($file:literal; ($input:ident: $input_ty:ty) -> $output_ty:ty { $part1:expr; $part2:expr $(;)? }) => {\n\n pub(crate) struct Solver;\n\n\n\n impl $crate::Solution for Solver {\n\n type Input = $input_ty;\n\n type Output = $output_ty;\n\n\n\n #[inline]\n", "file_path": "src/lib.rs", "rank": 11, "score": 5.805298765009399 }, { "content": "impl<A: Copy + Ord + MinDefault + MaxDefault> FromIterator<A> for MinMax<A> {\n\n fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {\n\n iter.into_iter().fold(MinMax::default(), |mut mn, x| {\n\n mn.max = mn.max.max(x);\n\n mn.min = mn.min.min(x);\n\n mn\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 12, "score": 5.781625833989077 }, { "content": "\n\n fn from_input(input: &str) -> Self::Out {\n\n let input = T::In::from_input(input);\n\n T::process(input)\n\n }\n\n}\n\n\n\npub struct First<T>(PhantomData<T>);\n\n\n\nimpl<T> ProcessInput for First<T>\n\nwhere\n\n T: PuzzleInput,\n\n T::Out: PopFirst,\n\n{\n\n type In = T;\n\n\n\n type Out = <T::Out as PopFirst>::Out;\n\n\n\n fn process(input: <T as PuzzleInput>::Out) -> Self::Out {\n\n <T::Out as PopFirst>::pop_first(input)\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 13, "score": 5.68160825626513 }, { "content": " part2_time,\n\n parse_time,\n\n }\n\n }\n\n }\n\n };\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! aoc_main {\n\n ($($day:literal => $md:ident),+ $(,)?) => {\n\n use ::aoc::{PuzzleSolution, Solution};\n\n $(mod $md);+;\n\n\n\n fn main() {\n\n let mut total_time = ::std::time::Duration::ZERO;\n\n ::std::env::args()\n\n .skip(1)\n\n .flat_map(|s| s.parse::<u8>())\n\n .for_each(|day| match day {\n", "file_path": "src/lib.rs", "rank": 14, "score": 4.401328440903798 }, { "content": "use std::{\n\n fmt::Debug,\n\n fmt::Display,\n\n marker::PhantomData,\n\n str::FromStr,\n\n time::{Duration, Instant},\n\n};\n\n\n\n#[macro_export]\n\nmacro_rules! poop {\n\n ($($arg:tt)*) => {\n\n {\n\n #[cfg(debug_assertions)]\n\n {\n\n println!($($arg)*);\n\n }\n\n }\n\n };\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 15, "score": 4.286799465772341 }, { "content": "\n\nimpl ResultLine {\n\n pub fn solution<T>(part: u8, duration: Duration, solution: T) -> Self\n\n where\n\n T: Display + 'static,\n\n {\n\n Self::new(format!(\"Part {}\", part), duration, Some(Box::new(solution)))\n\n }\n\n\n\n pub fn note<T>(note: &T, duration: Duration) -> Self\n\n where\n\n T: Display + ?Sized,\n\n {\n\n Self::new(note.to_string(), duration, None)\n\n }\n\n\n\n fn new(prefix: String, duration: Duration, solution: Option<Box<dyn Display>>) -> Self {\n\n Self {\n\n prefix,\n\n duration,\n", "file_path": "src/lib.rs", "rank": 16, "score": 4.163931273483082 }, { "content": " solution,\n\n }\n\n }\n\n}\n\n\n\nimpl Display for ResultLine {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n use owo_colors::{OwoColorize, Stream::Stdout};\n\n const DEFAULT_WIDTH: usize = 42;\n\n\n\n let duration = format!(\" ({})\", humantime::format_duration(self.duration));\n\n\n\n write!(\n\n f,\n\n \"{}{}\",\n\n self.prefix,\n\n duration.if_supports_color(Stdout, |d| d.dimmed())\n\n )?;\n\n\n\n if let Some(solution) = self.solution.as_deref() {\n", "file_path": "src/lib.rs", "rank": 17, "score": 3.440423805476581 }, { "content": "macro_rules! input {\n\n (verbatim $input_ty:ty) => {\n\n $input_ty\n\n };\n\n\n\n ($input_ty:ty) => {\n\n $crate::As<$input_ty>\n\n };\n\n\n\n (parse $input_ty:ty) => {\n\n $crate::Parsing<$input_ty>\n\n };\n\n\n\n (blocks $input_ty:ty) => {\n\n $crate::Blocks<$input_ty>\n\n };\n\n\n\n (process $input_ty:ty) => {\n\n $crate::Post<$input_ty>\n\n };\n", "file_path": "src/lib.rs", "rank": 18, "score": 2.292775522666868 }, { "content": " let max_width = f.width().unwrap_or(DEFAULT_WIDTH);\n\n let printed_width = self.prefix.chars().count() + duration.chars().count();\n\n let dots = max_width.saturating_sub(printed_width).saturating_sub(2);\n\n let dots = \".\".repeat(dots);\n\n\n\n write!(\n\n f,\n\n \" {} \",\n\n dots.if_supports_color(Stdout, |t| t.bright_black())\n\n )?;\n\n\n\n let solution = solution.to_string();\n\n let mut solution = solution.lines().filter(|l| !l.is_empty());\n\n\n\n write!(\n\n f,\n\n \"{}\",\n\n solution\n\n .next()\n\n .unwrap()\n", "file_path": "src/lib.rs", "rank": 19, "score": 1.5992623003420405 } ]
Rust
Assembler/src/asm/statement.rs
karannewatia/SCALE-MAMBA
467b33a6c80050789204ea3ee3b5cf0113354f85
use super::{Instruction, IoInstruction, Statement}; use crate::binary::instructions::RegisterMode; use crate::compiler::Compiler; use crate::lexer::{MapAllValues, Register}; use crate::span::Spanned; use crate::transforms::vectorize; use std::num::NonZeroU32; struct RegisterModeRead; struct RegisterModeWrite; trait RegisterModeTrait { const MODE: RegisterMode; } impl RegisterModeTrait for RegisterModeRead { const MODE: RegisterMode = RegisterMode::Read; } impl RegisterModeTrait for RegisterModeWrite { const MODE: RegisterMode = RegisterMode::Write; } #[derive(Clone, Debug)] pub struct RegisterIterator { v: NonZeroU32, registers: Vec<Register>, } impl RegisterIterator { pub fn is_empty(&self) -> bool { self.registers.is_empty() } } impl<'a> IntoIterator for &'a RegisterIterator { type Item = Register; type IntoIter = Box<dyn Iterator<Item = Register> + 'a>; fn into_iter(self) -> Self::IntoIter { let v = self.v; Box::new(self.registers.iter().flat_map(move |&r| vectorize(v, r))) } } impl IntoIterator for RegisterIterator { type Item = Register; type IntoIter = Box<dyn Iterator<Item = Register>>; fn into_iter(self) -> Self::IntoIter { let v = self.v; Box::new( self.registers .into_iter() .flat_map(move |r| vectorize(v, r)), ) } } impl<'a> Statement<'a> { pub fn write_registers(&self, cx: &Compiler) -> RegisterIterator { RegisterIterator { v: self.vectorized.elem, registers: self.write_registers_base(cx), } } pub fn read_registers(&self, cx: &Compiler) -> RegisterIterator { RegisterIterator { v: self.vectorized.elem, registers: self.read_registers_base(cx), } } pub fn write_registers_base(&self, cx: &Compiler) -> Vec<Register> { self.read_registers_generic::<RegisterModeWrite>(cx) } pub fn read_registers_base(&self, cx: &Compiler) -> Vec<Register> { self.read_registers_generic::<RegisterModeRead>(cx) } fn read_registers_generic<T: RegisterModeTrait>(&self, cx: &Compiler) -> Vec<Register> { use crate::binary::instructions::ArgTy; let relexed = self.relex(cx).0; let (instr, args) = match relexed.fetch_instr(cx) { Some(i) => i, None => return Vec::new(), }; let mut list = Vec::new(); let mut args_iter = args.iter(); for decl_arg in instr.args { match decl_arg.ty { ArgTy::Register(_, mode) if mode == T::MODE => { list.push(args_iter.next().unwrap().require(cx).elem) } ArgTy::List { element_type, len_arg, } => { let arg_pos = instr .args .iter() .position(|arg| arg.name == len_arg) .unwrap(); let len: Spanned<i32> = args[arg_pos].require(cx); let len = match &instr.args[arg_pos].ty { ArgTy::Int { signed: false, offset, } => len.elem - offset, ty => panic!("invalid array length type {:?}", ty), }; match element_type { ArgTy::List { .. } => unimplemented!("nested lists"), ArgTy::Register(_, mode) if *mode == T::MODE => { for _ in 0..len { list.push(args_iter.next().unwrap().require(cx).elem); } } _ => { for _ in 0..len { args_iter.next().unwrap(); } } } } _ => { args_iter.next().unwrap(); } } } assert_eq!(args_iter.next(), None, "{:?}", relexed); list } pub fn memory_read(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.mem_read } pub fn memory_write(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.mem_write } pub fn replace_registers(&mut self, cx: &Compiler, mut f: impl FnMut(Register) -> Register) { match &mut self.instr { Instruction::Assign { destination, value } => { destination.map_all_values(cx, &mut f); value.map_all_values(cx, &mut f); } Instruction::Io { instr: IoInstruction::OutputShares { registers }, .. } => { for register in registers { register.map_all_values(cx, &mut f); } } Instruction::StartOpen { registers } => { for register in registers { register.map_all_values(cx, &mut f); } } Instruction::StopOpen { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } Instruction::General { destinations, values, .. } => { for value in values { value.map_all_values(cx, &mut f); } for dest in destinations { dest.map_all_values(cx, &mut f); } } Instruction::Nop => {} Instruction::Io { instr, .. } => instr.replace_registers(cx, &mut f), } } pub fn is_barrier(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.barrier } pub fn is_startopen(&self) -> bool { matches!(self.instr, Instruction::StartOpen { .. }) } pub fn is_stopopen(&self) -> bool { matches!(self.instr, Instruction::StopOpen { .. }) } } impl IoInstruction { pub fn replace_registers(&mut self, cx: &Compiler, mut f: impl FnMut(Register) -> Register) { match self { IoInstruction::InputShares { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } IoInstruction::OutputShares { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } } } }
use super::{Instruction, IoInstruction, Statement}; use crate::binary::instructions::RegisterMode; use crate::compiler::Compiler; use crate::lexer::{MapAllValues, Register}; use crate::span::Spanned; use crate::transforms::vectorize; use std::num::NonZeroU32; struct RegisterModeRead; struct RegisterModeWrite; trait RegisterModeTrait { const MODE: RegisterMode; } impl RegisterModeTrait for RegisterModeRead { const MODE: RegisterMode = RegisterMode::Read; } impl RegisterModeTrait for RegisterModeWrite { const MODE: RegisterMode = RegisterMode::Write; } #[derive(Clone, Debug)] pub struct RegisterIterator { v: NonZeroU32, registers: Vec<Register>, } impl RegisterIterator { pub fn is_empty(&self) -> bool { self.registers.is_empty() } } impl<'a> IntoIterator for &'a RegisterIterator { type Item = Register; type IntoIter = Box<dyn Iterator<Item = Register> + 'a>; fn into_iter(self) -> Self::IntoIter { let v = self.v; Box::new(self.registers.iter().flat_map(move |&r| vectorize(v, r))) } } impl IntoIterator for RegisterIterator { type Item = Register; type IntoIter = Box<dyn Iterator<Item = Register>>; fn into_iter(self) -> Self::IntoIter { let v = self.v; Box::new( self.registers .into_iter() .flat_map(move |r| vectorize(v, r)), ) } } impl<'a> Statement<'a> { pub fn write_registers(&self, cx: &Compiler) -> RegisterIterator { RegisterIterator { v: self.vectorized.elem, registers: self.write_registers_base(cx), } } pub fn read_registers(&self, cx: &Compiler) -> RegisterIterator { RegisterIterator { v: self.vectorized.elem, registers: self.read_registers_base(cx), } } pub fn write_registers_base(&self, cx: &Compiler) -> Vec<Register> { self.read_registers_generic::<RegisterModeWrite>(cx) } pub fn read_registers_base(&self, cx: &Compiler) -> Vec<Register> { self.read_registers_generic::<RegisterModeRead>(cx) } fn read_registers_generic<T: RegisterModeTrait>(&self, cx: &Compiler) -> Vec<Register> { use crate::binary::instructions::ArgTy; let relexed = self.relex(cx).0; let (instr, args) = match relexed.fetch_instr(cx) { Some(i) => i, None => return Vec::new(), }; let mut list = Vec::new(); let mut args_iter = args.iter(); for decl_arg in instr.args { match decl_arg.ty { ArgTy::Register(_, mode) if mode == T::MODE => { list.push(args_iter.next().unwrap().require(cx).elem) } ArgTy::List { element_type, len_arg, } => { let arg_pos = instr .args .iter() .position(|arg| arg.name == len_arg) .unwrap(); let len: Spanned<i32> = args[arg_pos].require(cx); let len = match &instr.args[arg_pos].ty { ArgTy::Int { signed: false, offset, } => len.elem - offset, ty => panic!("invalid array length type {:?}", ty), }; match element_type { ArgTy::List { .. } => unimplemented!("nested lists"), ArgTy::Register(_, mode) if *mode == T::MODE => { for _ in 0..len { list.push(args_iter.next().unwrap().require(cx).elem); } } _ => { for _ in 0..len { args_iter.next().unwrap(); } } } } _ => { args_iter.next().unwrap(); } } } assert_eq!(args_iter.next(), None, "{:?}", relexed); list } pub fn memory_read(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.mem_read } pub fn memory_write(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.mem_write } pub fn replace_registers(&mut self, cx: &Compiler, mut f: impl FnMut(Register) -> Register) { match &mut self.instr { Instruction::Assign { destination, value } => { destination.map_all_values(cx, &mut f); value.map_all_values(cx, &mut f); } Instruction::Io { instr: IoInstruction::OutputShares { registers }, .. } => { for register in registers { register.map_all_values(cx, &mut f); } } Instruction::StartOpen { registers } => { for register in registers { register.map_all_values(cx, &mut f); } } Instruction::StopOpen { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } Instruction::General { destinations, values, .. } => { for value in values { value.map_all_values(cx, &mut f); } for dest in destinations { dest.map_all_values(cx, &mut f); } } Instruction::Nop => {} Instruction::Io { instr, .. } => instr.replace_registers(cx, &mut f), } } pub fn is_barrier(&self, cx: &Compiler) -> bool { let relexed = self.relex(cx).0; let (instr, _) = match relexed.fetch_instr(cx) { Some(i) => i, None => return false, }; instr.barrier } pub fn is_startopen(&self) -> bool { matches!(self.instr, Instruction::StartOpen { .. }) } pub fn is_stopopen(&self) -> bool { matches!(self.instr, Instruction::StopOpen { .. }) } } impl IoInstruction { pub fn replace_registers(&mut self, cx: &Compiler, mut f: impl FnMut(Register) -> Register) {
}
match self { IoInstruction::InputShares { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } IoInstruction::OutputShares { registers } => { for reg in registers { reg.map_all_values(cx, &mut f); } } } }
function_block-function_prefix_line
[ { "content": "/// Returns `true` if the statement is valid\n\npub fn validate(cx: &Compiler, stmt: &Statement<'_>) -> bool {\n\n let relexed = stmt.relex(cx);\n\n let (instr, args) = match relexed.0.fetch_instr(cx) {\n\n Some(i) => i,\n\n None => return true,\n\n };\n\n for (arg_index, (should, &is)) in instr.args.iter().zip(args).enumerate() {\n\n match should.ty {\n\n ArgTy::Player | ArgTy::Channel | ArgTy::Int { .. } => match is.elem {\n\n Operand::Register(_) => {\n\n cx.report(ExpectedGot {\n\n expected: format!(\n\n \"constant as argument {} to {}\",\n\n arg_index,\n\n relexed.0.display(cx)\n\n ),\n\n got: is,\n\n });\n\n return false;\n\n }\n", "file_path": "Assembler/src/transforms/validate.rs", "rank": 0, "score": 343088.0965155149 }, { "content": "pub trait CompileTimeLengthIterator<const N: u64> {}\n\n\n\nimpl<I, const N: u64> CompileTimeLengthIterator<N> for Iter<I, N> {}\n\n\n\nimpl<I: CompileTimeLengthIterator<N>, const N: u64> CompileTimeLengthIterator<N>\n\n for core::iter::Rev<I>\n\n{\n\n}\n\n\n\npub struct Iter<I, const N: u64> {\n\n iter: I,\n\n}\n\n\n\nimpl<I: Iterator, const N: u64> Iter<I, N> {\n\n pub unsafe fn new(iter: I) -> Self {\n\n Self { iter }\n\n }\n\n}\n\n\n\nimpl<I: Iterator, const N: u64> Iterator for Iter<I, N> {\n", "file_path": "WebAssembly/scale_std/src/iter.rs", "rank": 1, "score": 304254.818016304 }, { "content": "fn check_ty_for_impl(ty: &ArgTy) -> bool {\n\n match ty {\n\n ArgTy::Int { .. }\n\n | ArgTy::Player\n\n | ArgTy::Channel\n\n | ArgTy::Register(RegisterKind::Regint, ..)\n\n | ArgTy::Register(RegisterKind::Bit, ..) => false,\n\n ArgTy::Register(RegisterKind::Secret, ..)\n\n | ArgTy::Register(RegisterKind::SecretBit, ..)\n\n | ArgTy::Register(RegisterKind::Clear, ..)\n\n | ArgTy::Register(RegisterKind::SecretRegint, ..) => true,\n\n ArgTy::List { .. } => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 2, "score": 298923.26322113693 }, { "content": "fn byte_to_bits(b: u8) -> impl Iterator<Item = bool> {\n\n (0..8).rev().map(move |i| (b >> i) & 1 == 1)\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 4, "score": 274728.38919365813 }, { "content": "#[inline(always)]\n\npub fn require_bit_length<const BIT_LENGTH: u32>(_: ConstU32<BIT_LENGTH>) {\n\n unsafe { __reqbl(BIT_LENGTH) }\n\n}\n\n\n\n// Crash the system\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 6, "score": 242912.93551455505 }, { "content": "// Returns \n\n// false: if there is more than one instruction which reads this source register\n\n// and more than one instruction which writes this destination register\n\n// true: if only one which reads\n\nfn is_removable<'a>(cx: &'a Compiler, body: &Body<'a>, source: Register, destination: Register) \n\n -> bool\n\n{\n\n let mut cnts=0;\n\n let mut cntd=0;\n\n for block in &body.blocks {\n\n for stmt in &block.stmts {\n\n for x in stmt.read_registers_base(cx) {\n\n if x == source {\n\n if cnts==0 { cnts=1 }\n\n else { return false; }\n\n }\n\n }\n\n for x in stmt.write_registers_base(cx) {\n\n if x == destination {\n\n if cntd==0 { cntd=1 }\n\n else { return false; }\n\n }\n\n }\n\n }\n", "file_path": "Assembler/src/transforms/destination_propagation.rs", "rank": 7, "score": 241054.84963537945 }, { "content": "type F = fn() -> !;\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 8, "score": 235057.02404020948 }, { "content": "pub trait Error: std::fmt::Debug + Sized {\n\n fn print(self, cx: &Compiler) -> Snippet<'_>;\n\n /// Whether compilation should not succeed\n\n fn fatal(&self) -> bool {\n\n true\n\n }\n\n fn spans(&self) -> &[Span];\n\n fn slices<'a>(\n\n &self,\n\n cx: &'a Compiler,\n\n label: &'a str,\n\n annotation_type: AnnotationType,\n\n ) -> Vec<Slice<'a>> {\n\n self.spans()\n\n .iter()\n\n .filter_map(|&span| cx.get_file(span).map(|(p, f)| (p, f, span)))\n\n .map(move |(path, file, span)| {\n\n let (line_start, range, source) = crate::errors::line(span.snippet(cx), file);\n\n Slice {\n\n source: cx.strings.push_get(source),\n", "file_path": "Assembler/src/compiler.rs", "rank": 9, "score": 231522.4494012343 }, { "content": "pub fn atan_sfix<const K: u64, const F: u64, const KAPPA: u64>(\n\n x: SecretFixed<K, F, KAPPA>,\n\n) -> SecretFixed<K, F, KAPPA>\n\nwhere\n\n ConstU64<{ K - F }>: ,\n\n ConstU64<{ 2 * K }>: ,\n\n ConstU64<{ 2 * F }>: ,\n\n ConstU64<{ 2 * (K - F) }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ F + 1 }>: ,\n\n ConstI32<{ f_as_i32(F) }>: ,\n\n ConstI32<{ f_as_i32(K) }>: ,\n\n ConstU64<{ ClearFixed::<K, F>::THETA }>: ,\n\n ConstU64<{ SecretFixed::<K, F, KAPPA>::THETA }>: ,\n\n{\n\n let ans = kernel_atan::<SecretFixed<K, F, KAPPA>, ClearFixed<K, F>, SecretModp>(x);\n\n ans\n\n}\n\n\n\n/***********************************\n\n * Exponenentiation *\n\n ***********************************/\n\n\n", "file_path": "WebAssembly/scale_std/src/math_generic.rs", "rank": 10, "score": 224991.66095358273 }, { "content": "fn pop_ty_fn_name(ty: &ArgTy) -> &'static str {\n\n match ty {\n\n ArgTy::Int { signed: true, .. } => unimplemented!(),\n\n ArgTy::Int { signed: false, .. } => unimplemented!(),\n\n ArgTy::Register(RegisterKind::Secret, ..) => \"secret_modp\",\n\n ArgTy::Register(RegisterKind::SecretBit, ..) => \"secret_bit\",\n\n ArgTy::Register(RegisterKind::Clear, ..) => \"clear_modp\",\n\n ArgTy::Register(RegisterKind::Regint, ..) => \"i64\",\n\n ArgTy::Register(RegisterKind::Bit, ..) => \"bool\",\n\n ArgTy::Register(RegisterKind::SecretRegint, ..) => \"secret_i64\",\n\n ArgTy::List { .. } => unimplemented!(),\n\n ArgTy::Player => unimplemented!(),\n\n ArgTy::Channel => unimplemented!(),\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 12, "score": 223983.9841103845 }, { "content": "fn table_start<F: Write>(mut f: F, i: impl std::fmt::Display) -> io::Result<()> {\n\n write!(f, \"b{} [shape=\\\"none\\\" label=<\", i)?;\n\n write!(f, r#\"<table border=\"0\" cellborder=\"1\" cellspacing=\"0\">\"#)?;\n\n write!(f, r#\"<tr><td align=\"left\" balign=\"left\">\"#)?;\n\n Ok(())\n\n}\n", "file_path": "Assembler/src/asm/graphviz.rs", "rank": 13, "score": 219839.51580206506 }, { "content": "pub trait Expected {\n\n const EXPECTED: &'static str;\n\n}\n", "file_path": "Assembler/src/compiler.rs", "rank": 14, "score": 211577.3630627715 }, { "content": "fn asm_ty(ty: &ArgTy) -> proc_macro2::TokenStream {\n\n match ty {\n\n ArgTy::Int { signed: true, .. } => quote!(i32),\n\n ArgTy::Int { signed: false, .. } => quote!(u32),\n\n ArgTy::Register(RegisterKind::Secret, ..) => quote!(crate::SecretModp),\n\n ArgTy::Register(RegisterKind::SecretBit, ..) => quote!(crate::RawSecretBit),\n\n ArgTy::Register(RegisterKind::Clear, ..) => quote!(crate::ClearModp),\n\n ArgTy::Register(RegisterKind::Regint, ..) => quote!(i64),\n\n ArgTy::Register(RegisterKind::Bit, ..) => quote!(bool),\n\n ArgTy::Register(RegisterKind::SecretRegint, ..) => quote!(crate::SecretI64),\n\n ArgTy::List { .. } => unimplemented!(),\n\n ArgTy::Player => quote!(u32),\n\n ArgTy::Channel => quote!(u32),\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 15, "score": 209097.28184451364 }, { "content": "fn print_ty(ty: &ArgTy) -> proc_macro2::TokenStream {\n\n match ty {\n\n ArgTy::Int { signed: true, .. } => quote!(crate::ConstI32),\n\n ArgTy::Int { signed: false, .. } => quote!(crate::ConstU32),\n\n ArgTy::Register(RegisterKind::Secret, ..) => quote!(crate::SecretModp),\n\n ArgTy::Register(RegisterKind::SecretBit, ..) => quote!(crate::RawSecretBit),\n\n ArgTy::Register(RegisterKind::Clear, ..) => quote!(crate::ClearModp),\n\n ArgTy::Register(RegisterKind::Regint, ..) => quote!(i64),\n\n ArgTy::Register(RegisterKind::Bit, ..) => quote!(bool),\n\n ArgTy::Register(RegisterKind::SecretRegint, ..) => quote!(crate::SecretI64),\n\n ArgTy::List { .. } => unimplemented!(),\n\n ArgTy::Player => quote!(crate::Player),\n\n ArgTy::Channel => quote!(crate::Channel),\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 16, "score": 209097.28184451364 }, { "content": "pub fn list_optimizations() {\n\n for pass in PASSES {\n\n println!(\"{}\", pass().name());\n\n }\n\n}\n\n\n", "file_path": "Assembler/src/transforms.rs", "rank": 17, "score": 207918.29180367445 }, { "content": "pub trait AsRegisterKind {\n\n fn as_register_kind(&self) -> RegisterKind;\n\n}\n\n\n\nimpl AsRegisterKind for ValType {\n\n fn as_register_kind(&self) -> RegisterKind {\n\n match self {\n\n ValType::I32 | ValType::I64 => RegisterKind::Regint,\n\n ValType::F32 => RegisterKind::Secret,\n\n ValType::F64 => RegisterKind::SecretRegint,\n\n ValType::V128 => RegisterKind::Clear,\n\n ValType::Externref => unreachable!(),\n\n ValType::Funcref => unreachable!(),\n\n }\n\n }\n\n}\n\n\n\nimpl Stack {\n\n pub fn dump_stack(&self) {\n\n trace!(\"{:#?}\", self.stack);\n", "file_path": "WebAssembly/src/stack.rs", "rank": 18, "score": 203493.2363170171 }, { "content": "fn split_args(all: &[Arg]) -> Option<(&[Arg], &[Arg])> {\n\n if all.iter().any(|arg| matches!(arg.ty, ArgTy::List { .. })) {\n\n return None;\n\n }\n\n for (i, arg) in all.iter().enumerate() {\n\n if let ArgTy::Register(_, RegisterMode::Write) = arg.ty {\n\n continue;\n\n }\n\n let (ret, arg) = all.split_at(i);\n\n return Some((arg, ret));\n\n }\n\n Some((&[], all))\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 19, "score": 202553.54795834952 }, { "content": "fn table_end<F: Write>(mut f: F) -> io::Result<()> {\n\n write!(f, \"</td></tr>\")?;\n\n writeln!(f, \"</table>\")?;\n\n writeln!(f, \">];\")?;\n\n Ok(())\n\n}\n\n\n", "file_path": "Assembler/src/asm/graphviz.rs", "rank": 20, "score": 201948.39156527742 }, { "content": "fn read_input(source: PathBuf, f: impl Read, cx: &Compiler, input_format: InputFormat) -> Body<'_> {\n\n match input_format {\n\n InputFormat::Assembly => cx.parse_asm(source, f),\n\n InputFormat::Bytecode => cx.parse_bytecode(source, f),\n\n }\n\n}\n\n\n", "file_path": "Assembler/src/main.rs", "rank": 21, "score": 199820.29101197878 }, { "content": "pub fn parse<'a>(cx: &'a Compiler, input: &'a [u8]) -> Vec<Lexical<'a>> {\n\n let op2instr: HashMap<_, _> = instructions::INSTRUCTIONS\n\n .iter()\n\n .flat_map(|group| group.instructions)\n\n .map(|i| (i.opcode, i))\n\n .collect();\n\n\n\n let mut current = input;\n\n let mut lexicals = Vec::new();\n\n let mut read = |eof_ok| {\n\n if eof_ok && current.is_empty() {\n\n return Err(());\n\n }\n\n let mut bytes = [0; 4];\n\n match current.read_exact(&mut bytes) {\n\n Ok(()) => Ok(u32::from_be_bytes(bytes)),\n\n Err(err) => {\n\n cx.report(Io { err });\n\n Err(())\n\n }\n", "file_path": "Assembler/src/binary.rs", "rank": 22, "score": 199238.9323512715 }, { "content": "pub trait TestValue {\n\n #[track_caller]\n\n fn test_value(self, val: Self);\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 23, "score": 198931.03069834705 }, { "content": "#[inline(always)]\n\npub fn clear_registers() {\n\n unsafe { __clear_registers() }\n\n}\n\n\n\n// GC call\n\n#[inline(always)]\n\npub unsafe fn execute_garbled_circuit<const ID: u32>(_: ConstU32<ID>) {\n\n __gc(ID)\n\n}\n\n\n\n// LF call\n\n#[inline(always)]\n\npub unsafe fn execute_local_function<const ID: u32>(_: ConstU32<ID>) {\n\n __lf(ID)\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 24, "score": 198411.26285829613 }, { "content": "pub fn parse<'a>(cx: &'a Compiler, file: u32) -> Vec<Lexical<'a>> {\n\n Span::lines(cx, file)\n\n .filter_map(|span| Lexical::parse(cx, span))\n\n .collect()\n\n}\n\n\n\nimpl<'a> Lexical<'a> {\n\n pub fn parse(cx: &'a Compiler, span: Span) -> Option<Self> {\n\n // remove comments\n\n let (start, comment) = span.split_at_first_char('#', cx);\n\n let comment = comment.unwrap_or_else(|| span.end()).trim(cx);\n\n let line = start.trim(cx);\n\n let (instruction, args) = line.split_at_first_char(' ', cx);\n\n let args = args\n\n .map(|args| {\n\n args.split(',', cx)\n\n .map(|arg| parse_operand(cx, arg))\n\n .collect()\n\n })\n\n .unwrap_or_default();\n", "file_path": "Assembler/src/lexer/parser.rs", "rank": 25, "score": 196968.71817081724 }, { "content": "#[proc_macro]\n\npub fn impls(_: TokenStream) -> TokenStream {\n\n let groups = documentation::INSTRUCTIONS\n\n .iter()\n\n .enumerate()\n\n .map(|(i, group)| {\n\n let instructions = group.instructions.iter().filter_map(|instr| {\n\n let (args, ret) = split_args(instr.args)?;\n\n let ret_types = ret.iter().map(|r| print_ty(&r.ty));\n\n let arg_names: Vec<_> = args\n\n .iter()\n\n .map(|a| quote::format_ident!(\"__{}\", a.name))\n\n .collect();\n\n let arg_types: Vec<_> = args.iter().map(|a| print_ty(&a.ty)).collect();\n\n let name = instr.name.to_lowercase();\n\n let comments = instr.comment.lines().map(|line| {\n\n let line = line.trim();\n\n quote!(#[doc = #line])\n\n });\n\n let name_ident = quote::format_ident!(\"__{}\", name);\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 26, "score": 195768.69774518214 }, { "content": "pub trait MapAllValues<T> {\n\n fn map_all_values(&mut self, cx: &Compiler, f: impl FnMut(T) -> T);\n\n}\n\n\n\nimpl<\n\n T: std::fmt::Display + std::fmt::Debug + Copy,\n\n U: Expected + Default + TryFrom<T> + Into<T> + Copy + std::fmt::Display,\n\n > MapAllValues<T> for Spanned<U>\n\n{\n\n fn map_all_values(&mut self, cx: &Compiler, mut f: impl FnMut(T) -> T) {\n\n *self = self.map(|this| f(this.into())).require(cx);\n\n }\n\n}\n\n\n\nimpl MapAllValues<Register> for Spanned<Operand> {\n\n fn map_all_values(&mut self, _cx: &Compiler, mut f: impl FnMut(Register) -> Register) {\n\n match self.elem {\n\n Operand::Value(_) => {}\n\n Operand::Register(reg) => self.elem = Operand::Register(f(reg)),\n\n }\n", "file_path": "Assembler/src/lexer.rs", "rank": 27, "score": 194838.9250675088 }, { "content": "pub trait FAbs {\n\n fn fabs(self) -> Self;\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 28, "score": 194649.25399511546 }, { "content": "#[inline(always)]\n\npub fn stop_clock<const ID: i32>(_: ConstI32<ID>) {\n\n unsafe { __stop_clock(ID) }\n\n}\n\n\n\n// Requests a given minimum bit length of the prime\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 29, "score": 193475.90017041407 }, { "content": "#[inline(always)]\n\npub fn start_clock<const ID: i32>(_: ConstI32<ID>) {\n\n unsafe { __start_clock(ID) }\n\n}\n\n\n\n// Stops the clock and prints the time\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 30, "score": 193475.90017041407 }, { "content": "#[proc_macro_attribute]\n\npub fn main(attrs: TokenStream, item: TokenStream) -> TokenStream {\n\n let fn_ = syn::parse_macro_input!(item as syn::ItemFn);\n\n\n\n let assign_attrs: AssignAttrs = match syn::parse(attrs) {\n\n Ok(attrs) => attrs,\n\n Err(_) => {\n\n return TokenStream::from(\n\n Error::new_spanned(fn_, \"cannot parse attributes\").to_compile_error(),\n\n );\n\n }\n\n };\n\n\n\n let left = assign_attrs.left;\n\n let right = assign_attrs.right;\n\n\n\n let res = quote! {\n\n scale::__main!{\n\n #(#left = #right;)*\n\n }\n\n\n\n #fn_\n\n };\n\n\n\n TokenStream::from(res)\n\n}\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 31, "score": 192452.0464799485 }, { "content": "#[inline(always)]\n\npub fn reg_carry(\n\n b: Array<SecretModp, 2>,\n\n a: Array<SecretModp, 2>,\n\n compute_p: bool,\n\n) -> Array<SecretModp, 2> {\n\n let mut ans: Array<SecretModp, 2> = Array::uninitialized();\n\n if compute_p {\n\n ans.set(0, &(*a.get_unchecked(0) * *b.get_unchecked(0)));\n\n }\n\n ans.set(\n\n 1,\n\n &(*a.get_unchecked(1) + *a.get_unchecked(0) * *b.get_unchecked(1)),\n\n );\n\n ans\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 32, "score": 190125.5431915715 }, { "content": "pub fn substr_offset(substr: &str, main_str: &str) -> Option<usize> {\n\n let sub_ptr = substr.as_bytes().as_ptr() as usize;\n\n let main_ptr = main_str.as_bytes().as_ptr() as usize;\n\n if main_ptr <= sub_ptr && (sub_ptr + substr.len()) <= (main_ptr + main_str.len()) {\n\n Some(sub_ptr - main_ptr)\n\n } else {\n\n None\n\n }\n\n}\n\n\n\nimpl Drop for Compiler {\n\n fn drop(&mut self) {\n\n if !std::thread::panicking() && self.error_count.get() > 0 {\n\n panic!(\"do not drop `Compiler` types without checking for errors, use `.check_for_errors()` before doing so\");\n\n }\n\n }\n\n}\n\n\n\npub struct ErrorReported(());\n\n\n\nimpl std::fmt::Debug for ErrorReported {\n\n fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n fmt.write_str(\"Error already reported\")\n\n }\n\n}\n\n\n", "file_path": "Assembler/src/compiler.rs", "rank": 33, "score": 185580.15663746803 }, { "content": "#[allow(non_snake_case)]\n\nfn AppRcr<const K: u64, const F: u64, const KAPPA: u64>(\n\n b: SecretModp,\n\n _: ConstU64<K>,\n\n _: ConstU64<F>,\n\n _: ConstU64<KAPPA>,\n\n) -> SecretModp\n\nwhere\n\n ConstU64<{ 2 * (K - F) }>: ,\n\n ConstU64<{ 2 * K }>: ,\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n{\n\n let a: i64 = (2.9142 * ((1_i64 << K) as f64)) as i64;\n\n let alpha = ClearModp::from(a);\n\n\n\n let Nm = Norm(b, ConstU64::<K>, ConstU64::<KAPPA>);\n\n let c = *Nm.get_unchecked(0);\n\n let v = *Nm.get_unchecked(1);\n\n let d = alpha - c - c;\n\n let w_int: SecretInteger<{ 2 * K }, KAPPA> = SecretInteger::from(d * v);\n", "file_path": "WebAssembly/scale_std/src/fixed_point.rs", "rank": 34, "score": 184580.66159373283 }, { "content": "fn approximate_reciprocal<const K: u64, const F: u64, const THETA: u64>(\n\n divisor: ClearModp,\n\n _: ConstU64<K>,\n\n _: ConstU64<F>,\n\n _: ConstU64<THETA>,\n\n) -> ClearModp\n\nwhere\n\n ConstI32<{ f_as_i32(K) }>: ,\n\n{\n\n let bits: Slice<ClearModp> = BitDec_ClearModp(divisor, K);\n\n let mut cnt_leading_zeros = ClearModp::from(0);\n\n let mut flag: i64 = 0;\n\n let mut normalized_divisor = divisor;\n\n\n\n for i in 0..K {\n\n flag = flag | i64::from(*bits.get_unchecked(K - 1 - i));\n\n if flag == 0 {\n\n cnt_leading_zeros = cnt_leading_zeros + ClearModp::from(1);\n\n normalized_divisor = normalized_divisor + normalized_divisor;\n\n }\n", "file_path": "WebAssembly/scale_std/src/fixed_point.rs", "rank": 35, "score": 184580.66159373283 }, { "content": "class Array(object):\n\n \"\"\" Array objects \"\"\"\n\n\n\n def __init__(self, length, value_type, address=None):\n\n if value_type in _types:\n\n value_type = _types[value_type]\n\n self.address = address\n\n self.length = length\n\n self.value_type = value_type\n\n if address is None:\n\n self.address = self._malloc()\n\n\n\n def _malloc(self):\n\n return program.malloc(self.length, self.value_type)\n\n\n\n def delete(self):\n\n if program:\n\n program.free(self.address, self.value_type.reg_type)\n\n\n\n def get_address(self, index):\n\n if isinstance(index, int) and self.length is not None:\n\n index += self.length * (index < 0)\n\n if index >= self.length or index < 0:\n\n raise IndexError('index %s, length %s' % \\\n\n (str(index), str(self.length)))\n\n return self.address + index\n\n\n\n def get_slice(self, index):\n\n if index.stop is None and self.length is None:\n\n raise CompilerError('Cannot slice array of unknown length')\n\n return index.start or 0, index.stop or self.length, index.step or 1\n\n\n\n def __getitem__(self, index):\n\n if isinstance(index, slice):\n\n start, stop, step = self.get_slice(index)\n\n res_length = (stop - start - 1) / step + 1\n\n res = Array(res_length, self.value_type)\n\n\n\n @library.for_range(res_length)\n\n def f(i):\n\n res[i] = self[start + i * step]\n\n\n\n return res\n\n return self._load(self.get_address(index))\n\n\n\n def __setitem__(self, index, value):\n\n if isinstance(index, slice):\n\n start, stop, step = self.get_slice(index)\n\n source_index = MemValue(0)\n\n\n\n @library.for_range(start, stop, step)\n\n def f(i):\n\n self[i] = value[source_index]\n\n source_index.iadd(1)\n\n\n\n return\n\n self._store(self.value_type.conv(value), self.get_address(index))\n\n\n\n def _load(self, address):\n\n return self.value_type.load_mem(address)\n\n\n\n def _store(self, value, address):\n\n value.store_in_mem(address)\n\n\n\n def __len__(self):\n\n return self.length\n\n\n\n def __iter__(self):\n\n for i in range(self.length):\n\n yield self[i]\n\n\n\n def assign(self, other):\n\n if isinstance(other, Array):\n\n def loop(i):\n\n self[i] = other[i]\n\n\n\n library.range_loop(loop, len(self))\n\n elif isinstance(other, Tape.Register):\n\n if len(other) == self.length:\n\n self[0] = other\n\n else:\n\n raise CompilerError('Length mismatch between array and vector')\n\n else:\n\n for i, j in enumerate(other):\n\n self[i] = j\n\n return self\n\n\n\n def assign_all(self, value):\n\n mem_value = MemValue(value)\n\n n_loops = 8 if len(self) > 2 ** 20 else 1\n\n\n\n @library.for_range_multithread(n_loops, 1024, len(self))\n\n def f(i):\n\n self[i] = mem_value\n\n\n", "file_path": "Compiler/types.py", "rank": 36, "score": 184027.33820709487 }, { "content": "#[instrument(skip(stmts))]\n\nfn find_elements(stmts: &[Statement<'_>]) -> Option<(Register, Register, i32)> {\n\n let mut iter = stmts.iter().rev();\n\n let neg = iter.next()?;\n\n let one = iter.next()?;\n\n let eq = iter.next()?;\n\n let constant = iter.next()?;\n\n\n\n let (constant, val) = constant.instr.as_assign()?;\n\n let eq_val = val.try_as_int().ok()?;\n\n\n\n let (eq_result, a, b) = eq.instr.as_binop(\"eqint\")?;\n\n let eq_reg = match (a == constant, b == constant) {\n\n (true, true) => unreachable!(),\n\n (true, false) => b,\n\n (false, true) => a,\n\n (false, false) => return None,\n\n };\n\n\n\n let (one, val) = one.instr.as_assign()?;\n\n if val.try_as_int().ok()? != 1 {\n\n return None;\n\n }\n\n\n\n let (dest, a, b) = neg.instr.as_binop(\"subint\")?;\n\n if a != one || b != eq_result {\n\n return None;\n\n }\n\n Some((dest, eq_reg, eq_val))\n\n}\n", "file_path": "Assembler/src/transforms/cmp.rs", "rank": 37, "score": 183604.802650814 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\n#[allow(unused_variables)]\n\npub fn Gauss_Elim<const N: u64, const M: u64>(\n\n A: &Matrix<ClearModp, N, M>,\n\n) -> Matrix<ClearModp, N, M> {\n\n let (col, row, B) = unsafe {\n\n execute_local_function!(GAUSS_ELIM(\n\n N as i64,\n\n M as i64,\n\n *A\n\n ) ->\n\n i64,\n\n i64,\n\n Matrix::<ClearModp, N, M>\n\n )\n\n };\n\n\n\n #[cfg(all(debug_assertions, not(feature = \"emulate\")))]\n\n if row != (N as i64) || col != (M as i64) {\n\n crash();\n\n }\n\n\n\n B\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/local_functions.rs", "rank": 38, "score": 181859.51617456472 }, { "content": "#[inline(always)]\n\npub fn close_channel<const C: u32>(_: Channel<C>) {\n\n unsafe {\n\n __close_channel(C);\n\n }\n\n}\n\n\n\n/*\n\n\n", "file_path": "WebAssembly/scale/src/io.rs", "rank": 39, "score": 181720.17436409445 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn BitLT<const K: u64>(\n\n a: ClearModp,\n\n bb: impl IntoIterator<Item = SecretModp> + CompileTimeLengthIterator<K>,\n\n) -> SecretModp {\n\n let mut ab: Array<ClearModp, K> = Array::uninitialized();\n\n let mut sb: Array<SecretModp, K> = Array::uninitialized();\n\n ab.set(K - 1, &(a % ClearModp::from(ConstI32::<2>)));\n\n let mut temp = a;\n\n for i in 1..K {\n\n temp = (temp - *ab.get_unchecked(K - i)) / ClearModp::from(ConstI32::<2>);\n\n ab.set(K - i - 1, &(temp % ClearModp::from(ConstI32::<2>)));\n\n }\n\n for (i, v) in bb.into_iter().enumerate() {\n\n sb.set(K - 1 - i as u64, &(ConstI32::<1> - v));\n\n }\n\n let c: SecretModp = CarryOut(&ab.slice(..), &sb.slice(..), ClearModp::from(ConstI32::<1>));\n\n return ConstI32::<1> - c;\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 40, "score": 180927.4039098763 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn SHA3(istate: Array<SecretI64, 25>) -> Array<SecretI64, 25> {\n\n let ostate = unsafe { execute_garbled_circuit!(SHA_3(istate) -> Array<SecretI64,25>) };\n\n ostate\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/circuits.rs", "rank": 41, "score": 180537.13138148256 }, { "content": "pub fn main(args: Args) -> Result<(), Error> {\n\n // Load wasm input\n\n let buf = if let Some(file) = args.input {\n\n std::fs::read(file)?\n\n } else {\n\n let stdin = std::io::stdin();\n\n let mut stdin = stdin.lock();\n\n let mut buf = Vec::new();\n\n stdin.read_to_end(&mut buf)?;\n\n buf\n\n };\n\n\n\n // Parse wasm input\n\n let config = walrus::ModuleConfig::new();\n\n let module = config.parse(&buf)?;\n\n let exports: HashMap<String, &ExportItem> = module\n\n .exports\n\n .iter()\n\n .map(|export| (export.name.to_owned(), &export.item))\n\n .collect();\n", "file_path": "WebAssembly/src/lib.rs", "rank": 42, "score": 180226.0142986595 }, { "content": " /// A helper trait that is implemented for all register types\n\n /// and has bounds for all operations implemented by those types.\n\n /// This allows one to easily write code that is generic over\n\n /// the various register types.\n\n pub trait AnyRegister: $($bound+)* Sized {}\n\n };\n\n}\n\n\n\nimpl AnyRegister for ClearModp {}\n\nimpl AnyRegister for SecretModp {}\n\nimpl AnyRegister for i64 {}\n\nimpl AnyRegister for SecretI64 {}\n\n\n\nuse core::ops::*;\n\n\n\nany_register! {\n\n Stack,\n\n alloc::GetAllocator,\n\n Add<Output = Self>,\n\n Sub<Output = Self>,\n\n Mul<Output = Self>,\n\n StoreInMem<i64>,\n\n LoadFromMem<i64>\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 43, "score": 179358.84498973138 }, { "content": "#[allow(non_snake_case)]\n\npub fn Clear_Int2Fl<const K: u64, const L: u64>(\n\n a_int: ClearInteger<K>,\n\n _: ConstU64<L>,\n\n) -> Array<ClearModp, 5>\n\nwhere\n\n ConstU64<{ L - 1 }>: ,\n\n ConstU64<{ L + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - L - 1 }>: ,\n\n{\n\n let s = a_int.ltz();\n\n let z = a_int.eqz();\n\n let a = a_int.rep();\n\n let aa = (ClearModp::from(1) - s - s) * a;\n\n let vec_a = BitDec_ClearModp(aa, K - 1);\n\n let mut rev_a: Slice<ClearModp> = Slice::uninitialized(K - 1);\n\n for i in 0..K - 1 {\n\n rev_a.set(i, &*vec_a.get_unchecked(K - 2 - i));\n\n }\n", "file_path": "WebAssembly/scale_std/src/float_subroutines.rs", "rank": 44, "score": 179141.47181060258 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn BitIncrement<const K: u64>(ab: &Array<SecretModp, K>) -> Slice<SecretModp> {\n\n let mut d: Slice<Array<SecretModp, 2>> = Slice::uninitialized(K);\n\n d.get_mut_unchecked(0).set(1, &(*ab.get_unchecked(0)));\n\n d.get_mut_unchecked(0)\n\n .set(0, &(SecretModp::from(1) - *ab.get_unchecked(0)));\n\n for i in 1..K {\n\n d.get_mut_unchecked(i).set(1, &(SecretModp::from(0)));\n\n d.get_mut_unchecked(i).set(0, &(*ab.get_unchecked(i)));\n\n }\n\n let c: Slice<Array<SecretModp, 2>> = PreOpL2(reg_carry, &d);\n\n\n\n let mut s: Slice<SecretModp> = Slice::uninitialized(K + 1);\n\n s.set(\n\n 0,\n\n &(*ab.get_unchecked(0) + SecretModp::from(1)\n\n - ConstI32::<2> * *c.get_unchecked(0).get_unchecked(1)),\n\n );\n\n for i in 1..K {\n\n s.set(\n\n i,\n\n &(*ab.get_unchecked(i) + *c.get_unchecked(i - 1).get_unchecked(1)\n\n - ConstI32::<2> * *c.get_unchecked(i).get_unchecked(1)),\n\n );\n\n }\n\n s.set(K, &*c.get_unchecked(K - 1).get_unchecked(1));\n\n return s;\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 45, "score": 179046.7742458526 }, { "content": "#[allow(non_snake_case)]\n\npub fn Pade<S, C, const N: u64>(poly_p: Array<C, N>, poly_q: Array<C, N>, x: S) -> S\n\nwhere\n\n S: Float,\n\n S: Add<S, Output = S>,\n\n S: Mul<S, Output = S>,\n\n S: Div<S, Output = S>,\n\n S: Mul<C, Output = S>,\n\n S: From<C>,\n\n C: Float,\n\n{\n\n let mut num: S = S::from(*poly_p.get_unchecked(0));\n\n let mut den: S = S::from(*poly_q.get_unchecked(0));\n\n let mut x_pow = x;\n\n for i in 1..N {\n\n num = num + x_pow * *poly_p.get_unchecked(i);\n\n den = den + x_pow * *poly_q.get_unchecked(i);\n\n x_pow = x_pow * x;\n\n }\n\n num / den\n\n}\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 46, "score": 178787.7678010863 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\n#[allow(unused_variables)]\n\npub fn Matrix_Mul_CS<const N: u64, const L: u64, const M: u64>(\n\n A: &Matrix<ClearModp, N, L>,\n\n B: &Matrix<SecretModp, L, M>,\n\n) -> Matrix<SecretModp, N, M> {\n\n let (col, row, C) = unsafe {\n\n execute_local_function!(C_MULT_S(\n\n N as i64,\n\n L as i64,\n\n *A,\n\n L as i64,\n\n M as i64,\n\n *B\n\n ) ->\n\n i64,\n\n i64,\n\n Matrix::<SecretModp, N, M>\n\n )\n\n };\n\n\n\n #[cfg(all(debug_assertions, not(feature = \"emulate\")))]\n\n if row != (N as i64) || col != (M as i64) {\n\n crash();\n\n }\n\n\n\n C\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/local_functions.rs", "rank": 47, "score": 176310.06432439043 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\n#[allow(unused_variables)]\n\npub fn Matrix_Mul_CC<const N: u64, const L: u64, const M: u64>(\n\n A: &Matrix<ClearModp, N, L>,\n\n B: &Matrix<ClearModp, L, M>,\n\n) -> Matrix<ClearModp, N, M> {\n\n let (col, row, C) = unsafe {\n\n execute_local_function!(C_MULT_C(\n\n N as i64,\n\n L as i64,\n\n *A,\n\n L as i64,\n\n M as i64,\n\n *B\n\n ) ->\n\n i64,\n\n i64,\n\n Matrix::<ClearModp, N, M>\n\n )\n\n };\n\n\n\n #[cfg(all(debug_assertions, not(feature = \"emulate\")))]\n\n if row != (N as i64) || col != (M as i64) {\n\n crash();\n\n }\n\n\n\n C\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/local_functions.rs", "rank": 48, "score": 176310.06432439043 }, { "content": "#[allow(non_snake_case)]\n\npub fn Secret_Int2Fl<const K: u64, const L: u64, const KAPPA: u64>(\n\n a_int: SecretInteger<K, KAPPA>,\n\n _: ConstU64<L>,\n\n) -> Array<SecretModp, 5>\n\nwhere\n\n ConstU64<{ L - 1 }>: ,\n\n ConstU64<{ L + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - L - 1 }>: ,\n\n{\n\n let s = a_int.ltz();\n\n let z = a_int.eqz();\n\n let a = a_int.rep();\n\n let aa = (SecretModp::from(1) - s - s) * a;\n\n let vec_a = BitDec::<{ K - 1 }, { K - 1 }, KAPPA>(aa);\n\n let mut rev_a: Slice<SecretModp> = Slice::uninitialized(K - 1);\n\n for i in 0..K - 1 {\n\n rev_a.set(i, &*vec_a.get_unchecked(K - 2 - i));\n\n }\n", "file_path": "WebAssembly/scale_std/src/float_subroutines.rs", "rank": 49, "score": 176310.06432439043 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn PRandM<const K: u64, const M: u64, const KAPPA: u64>(\n\n) -> (SecretModp, SecretModp, Array<SecretModp, M>) {\n\n // We are not using the `require_bit_length` wrapper here, as we can't do math in const generics yet.\n\n unsafe { __reqbl((K + KAPPA) as u32) };\n\n let mut rb: Array<SecretModp, M> = Array::uninitialized();\n\n for i in 0u64..M {\n\n rb.set(i, &SecretModp::get_random_bit());\n\n }\n\n let r: SecretModp = SumBits(&rb.slice(..));\n\n let r2: SecretModp = PRandInt(K + KAPPA - M);\n\n return (r2, r, rb);\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 50, "score": 176310.06432439043 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\n#[allow(unused_variables)]\n\npub fn Matrix_Mul_SC<const N: u64, const L: u64, const M: u64>(\n\n A: &Matrix<SecretModp, N, L>,\n\n B: &Matrix<ClearModp, L, M>,\n\n) -> Matrix<SecretModp, N, M> {\n\n let (col, row, C) = unsafe {\n\n execute_local_function!(S_MULT_C(\n\n N as i64,\n\n L as i64,\n\n *A,\n\n L as i64,\n\n M as i64,\n\n *B\n\n ) ->\n\n i64,\n\n i64,\n\n Matrix::<SecretModp, N, M>\n\n )\n\n };\n\n\n\n #[cfg(all(debug_assertions, not(feature = \"emulate\")))]\n\n if row != (N as i64) || col != (M as i64) {\n\n crash();\n\n }\n\n\n\n C\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/local_functions.rs", "rank": 51, "score": 176310.06432439043 }, { "content": "fn test_approx<const K: u64, const F: u64>(a: ClearFixed<K, F>, val: ClearFixed<K, F>) -> ClearModp\n\nwhere\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n{\n\n let lower = val - ClearFixed::from(0.00001);\n\n let upper = val + ClearFixed::from(0.00001);\n\n let ok = a.gt(lower) & a.lt(upper);\n\n ok\n\n}\n\n\n\n\n\n\n\n\n", "file_path": "RustPrograms/examples/test_sfix/main.rs", "rank": 52, "score": 176061.74373734405 }, { "content": "#[inline(always)]\n\npub fn carry(b: Array<SecretModp, 2>, a: Array<SecretModp, 2>) -> Array<SecretModp, 2> {\n\n let mut ans: Array<SecretModp, 2> = Array::uninitialized();\n\n ans.set(0, &(*a.get_unchecked(0) * *b.get_unchecked(0)));\n\n ans.set(\n\n 1,\n\n &(*a.get_unchecked(1) + *a.get_unchecked(0) * *b.get_unchecked(1)),\n\n );\n\n ans\n\n}\n\n\n\n/* ######################################\n\n * ##### Helper functions #####\n\n * ###################################### */\n\nconst fn num_bits<T>() -> usize {\n\n core::mem::size_of::<T>() * 8\n\n}\n\n\n\n#[inline(always)]\n\npub const fn ceil_log_2(a: u32) -> u32 {\n\n let mut check = 0;\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 53, "score": 175344.12964254685 }, { "content": "fn test_approx<const K: u64, const F: u64>(a: ClearFixed<K, F>, val: ClearFixed<K, F>) -> ClearModp\n\nwhere\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n{\n\n let lower = val - ClearFixed::from(0.00001);\n\n let upper = val + ClearFixed::from(0.00001);\n\n let ok = a.gt(lower) & a.lt(upper);\n\n ok\n\n}\n\n\n\n\n\n/* This test a relative error */\n", "file_path": "RustPrograms/examples/test_sfix_lib/main.rs", "rank": 54, "score": 174139.4693038018 }, { "content": "fn test_ratio<const K: u64, const F: u64>(a: ClearFixed<K, F>, val: ClearFixed<K, F>) -> ClearModp\n\nwhere\n\n // HACK: due to a bug in the Rust compiler, constraints from SecretFixed are being picked up here\n\n ConstU64<{ 2 * F }>: ,\n\n ConstU64<{ 2 * K }>: ,\n\n ConstU64<{ 2 * (K - F) }>: ,\n\n // All constraints below are correct, only those above should not be required.\n\n ConstU64<{ K + 1 }>: ,\n\n ConstU64<{ K - 1 }>: ,\n\n ConstU64<{ ClearFixed::<K, F>::THETA }>: ,\n\n ConstI32<{ f_as_i32(F) }>: ,\n\n ConstI32<{ f_as_i32(K) }>: ,\n\n{\n\n let test = a/val;\n\n let lower = ClearFixed::from(0.9995);\n\n let upper = ClearFixed::from(1.0005);\n\n let ok = test.gt(lower) & test.lt(upper);\n\n ok\n\n}\n\n\n\n\n\n\n\n\n", "file_path": "RustPrograms/examples/test_sfix_lib/main.rs", "rank": 55, "score": 174139.4693038018 }, { "content": "#[inline(always)]\n\npub fn open_channel<const C: u32>(_: Channel<C>) -> i64 {\n\n unsafe { __open_channel(C) }\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/io.rs", "rank": 56, "score": 173610.65269700793 }, { "content": "// Evaluate polynomial using Horner's Rule\n\npub fn poly_eval<S, C, const N: u64>(poly: Array<C, N>, x: S) -> S\n\nwhere\n\n S: Float,\n\n S: Add<C, Output = S>,\n\n S: Mul<S, Output = S>,\n\n C: Float,\n\n{\n\n let mut sum: S = S::from(0_i64);\n\n for i in 0..N {\n\n sum = sum * x + *poly.get_unchecked(N - 1 - i);\n\n }\n\n sum\n\n}\n\n\n\n// Evaluate Pade approximation\n\n// P and Q must have same degree\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 57, "score": 173343.13851973455 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn SHA512(mess: Array<SecretI64, 16>, state: Array<SecretI64, 8>) -> Array<SecretI64, 8> {\n\n let ostate = unsafe { execute_garbled_circuit!(SHA_512(mess,state) -> Array<SecretI64,8>) };\n\n ostate\n\n}\n\n\n\n/**************************\n\n * IEEE FP Operations *\n\n **************************/\n\n\n\nconst FP_ADD: u32 = 120;\n\nconst FP_MUL: u32 = 121;\n\nconst FP_DIV: u32 = 122;\n\nconst FP_EQ: u32 = 123;\n\nconst FP_F2I: u32 = 124;\n\nconst FP_I2F: u32 = 125;\n\nconst FP_SQRT: u32 = 126;\n\nconst FP_LT: u32 = 127;\n\nconst FP_FLOOR: u32 = 128;\n\nconst FP_CEIL: u32 = 129;\n\n\n", "file_path": "WebAssembly/scale_std/src/circuits.rs", "rank": 58, "score": 172930.74283320302 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn SHA256(mess: Array<SecretI64, 8>, state: Array<SecretI64, 4>) -> Array<SecretI64, 4> {\n\n let ostate = unsafe { execute_garbled_circuit!(SHA_256(mess,state) -> Array<SecretI64,4>) };\n\n ostate\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/circuits.rs", "rank": 59, "score": 172930.74283320302 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn PreOpL<T>(op: impl Fn(T, T) -> T + Copy, items: &Slice<T>) -> Slice<T>\n\nwhere\n\n T: Modp<SecretModp> + Copy,\n\n{\n\n let k: u64 = items.len();\n\n let logk: u64 = ceil_log_2(k as u32).into();\n\n let kmax: u64 = two_power(logk);\n\n let mut output: Slice<T> = Slice::uninitialized(k);\n\n for i in 0..k {\n\n output.set(i, &*items.get_unchecked(i));\n\n }\n\n for i in 0u64..logk {\n\n for j in 0u64..(kmax / two_power(i + 1)) {\n\n let y: u64 = two_power(i) + j * two_power(i + 1) - 1;\n\n let zmax: u64 = two_power(i) + 1;\n\n for z in 1u64..zmax {\n\n if y + z < k {\n\n output.set(\n\n y + z,\n\n &op(*output.get_unchecked(y), *output.get_unchecked(y + z)),\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 60, "score": 171857.9564302598 }, { "content": "fn clean(map: &mut BTreeMap<u32, NonZeroU32>) {\n\n if let Some((&cur_r, &cur_v)) = map.iter().next() {\n\n let mut cur_r = cur_r;\n\n let mut cur_v = cur_v;\n\n let mut all: Vec<_> = map.iter().map(|(&r, &v)| (r, v)).collect();\n\n let mut first = true;\n\n all.retain(|&(r, v)| {\n\n if first {\n\n first = false;\n\n return true;\n\n }\n\n // Is the register part of the current registers vectorized elements?\n\n if r < cur_r + cur_v.get() {\n\n // Is the register *also* vectorized and goes beyond the current vector register?\n\n let end = r + v.get();\n\n let cur_end = cur_r + cur_v.get();\n\n if end > cur_end {\n\n // expand register\n\n cur_v = NonZeroU32::new(cur_v.get() + end - cur_end).unwrap();\n\n }\n", "file_path": "Assembler/src/transforms/register_reuse.rs", "rank": 61, "score": 168789.8162700122 }, { "content": "fn ty_generics(\n\n ty: &ArgTy,\n\n generics: usize,\n\n) -> (Option<proc_macro2::TokenStream>, Option<proc_macro2::Ident>) {\n\n let ty = match ty {\n\n ArgTy::Int { signed: true, .. } => Some(quote!(i32)),\n\n ArgTy::Int { signed: false, .. } => Some(quote!(u32)),\n\n ArgTy::Register(RegisterKind::Secret, ..) => None,\n\n ArgTy::Register(RegisterKind::SecretBit, ..) => None,\n\n ArgTy::Register(RegisterKind::Clear, ..) => None,\n\n ArgTy::Register(RegisterKind::Regint, ..) => None,\n\n ArgTy::Register(RegisterKind::Bit, ..) => None,\n\n ArgTy::Register(RegisterKind::SecretRegint, ..) => None,\n\n ArgTy::List { .. } => unimplemented!(),\n\n ArgTy::Player => Some(quote!(u32)),\n\n ArgTy::Channel => Some(quote!(u32)),\n\n };\n\n match ty {\n\n None => (None, None),\n\n Some(ty) => {\n\n let ident = quote::format_ident!(\"{}\", GENERICS[generics]);\n\n (Some(quote!(const #ident: #ty,)), Some(ident))\n\n }\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 62, "score": 168223.29216935934 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn Pow2<const K: u64, const KAPPA: u64>(a: SecretModp) -> SecretModp\n\nwhere\n\n ConstU64<{ CeilLog2::<K>::RESULT }>: ,\n\n{\n\n let mut d = BitDec::<{ CeilLog2::<K>::RESULT }, { CeilLog2::<K>::RESULT }, KAPPA>(a);\n\n for i in 0..CeilLog2::<K>::RESULT {\n\n d.set(\n\n i,\n\n &(modp_two_power(1 << i) * *d.get_unchecked(i) + ClearModp::from(1)\n\n - *d.get_unchecked(i)),\n\n );\n\n }\n\n KOpL(mul_op, &d)\n\n}\n\n\n\n/* As the next function should always be inlined the multiple\n\n * return values should work\n\n */\n\n/* For a in [0..k) this converts it into unary form */\n", "file_path": "WebAssembly/scale_std/src/integer.rs", "rank": 63, "score": 165566.34873015498 }, { "content": "fn is_even(num: &BigInt) -> bool {\n\n let nn: u32 = (num % BigInt::from(2)).to_u32().unwrap();\n\n if nn == 0 {\n\n true\n\n } else {\n\n false\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/emulated_impls/numb_th.rs", "rank": 64, "score": 164514.80300252387 }, { "content": "/// The interface of a single transformation\n\npub trait Pass {\n\n fn apply<'a>(&mut self, cx: &'a Compiler, body: &mut Body<'a>);\n\n fn name(&self) -> &'static str;\n\n}\n\n\n", "file_path": "Assembler/src/transforms.rs", "rank": 65, "score": 163755.20067449665 }, { "content": "/// Applies the given function to the register and all its contiguous vectorized registers\n\npub fn vectorize(\n\n v: NonZeroU32,\n\n reg: Register,\n\n) -> impl Iterator<Item = Register> + Clone + ExactSizeIterator {\n\n (0..v.get()).map(move |i| reg.map(|j| i + j))\n\n}\n", "file_path": "Assembler/src/transforms.rs", "rank": 66, "score": 163242.33024485983 }, { "content": "#[allow(non_snake_case)]\n\nfn Clear_MSB<const K: u64>(b: ClearModp, _: ConstU64<K>) -> Array<ClearModp, K> {\n\n let x_order = BitDec_ClearModp(b, K);\n\n // Invert x\n\n let mut x: Slice<ClearModp> = Slice::uninitialized(K);\n\n for i in 0..K {\n\n x.set(i, &*x_order.get_unchecked(K - 1 - i));\n\n }\n\n let y = x.PreOr();\n\n let mut z: Array<ClearModp, K> = Array::uninitialized();\n\n for i in 0..(K - 1) {\n\n z.set(\n\n i,\n\n &(*y.get_unchecked(K - 1 - i) - *y.get_unchecked(K - 2 - i)),\n\n );\n\n }\n\n z.set(K - 1, &*y.get_unchecked(0));\n\n z\n\n}\n\n\n\n// Similar to norm_SQ [see Documentation],\n\n// but saves rounds by not calculating m, v and c.\n", "file_path": "WebAssembly/scale_std/src/sqrt.rs", "rank": 67, "score": 161529.64862950484 }, { "content": "#[allow(non_snake_case)]\n\nfn Clear_norm_simplified_SQ<const K: u64>(b: ClearModp, _: ConstU64<K>) -> Array<ClearModp, 2> {\n\n let z = Clear_MSB(b, ConstU64::<K>);\n\n\n\n // Construct m\n\n let mut m_odd = ClearModp::from(0);\n\n for i in (0..K).step_by(2) {\n\n m_odd = m_odd + *z.get_unchecked(i);\n\n }\n\n\n\n // Construct w, changes from what is on the paper\n\n let mut w = ClearModp::from(0);\n\n for i in 1..(K / 2 + 1) {\n\n let wi = *z.get_unchecked(2 * i - 1) + *z.get_unchecked(2 * i);\n\n w = w + modp_two_power(i) * wi;\n\n }\n\n let mut ans: Array<ClearModp, 2> = Array::uninitialized();\n\n ans.set(0, &m_odd);\n\n ans.set(1, &w);\n\n ans\n\n}\n", "file_path": "WebAssembly/scale_std/src/sqrt.rs", "rank": 68, "score": 159250.55268246154 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn BitDecFull(a: SecretModp) -> Array<SecretModp, BITLENP> {\n\n if BITLEN > 63 {\n\n return BitDecFullBig(a);\n\n }\n\n let mut abits: Array<SecretModp, BITLENP> = Array::uninitialized();\n\n let mut bbits: Array<SecretModp, BITLENP> = Array::uninitialized();\n\n let mut pbits: Array<ClearModp, { BITLENP + 1 }> = Array::uninitialized();\n\n let mut p: i64 = 0;\n\n for i in 0u64..BITLENP {\n\n pbits.set(i, &ClearModp::from(P[(BITLEN - 1 - i) as usize] as i64));\n\n p += (two_power(i) * (P[(BITLEN - 1 - i) as usize] as u64)) as i64;\n\n }\n\n // Loop until we get some random integers less than p\n\n let mut cond: i64 = 0;\n\n while cond == 0 {\n\n for i in 0u64..BITLENP {\n\n bbits.set(i, &SecretModp::get_random_bit());\n\n }\n\n cond = i64::from(BitLTFull(&bbits.slice(..), &pbits.slice(..)).reveal());\n\n }\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 69, "score": 157729.63757286785 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn BitDec<const K: u64, const M: u64, const KAPPA: u64>(a: SecretModp) -> Slice<SecretModp> {\n\n let random = PRandM::<K, M, KAPPA>();\n\n let r_prime: SecretModp = random.0;\n\n let r: SecretModp = random.1;\n\n let rb: Array<SecretModp, M> = random.2;\n\n let cons: ClearModp = modp_two_power(K) + modp_two_power(K + KAPPA);\n\n let sc: SecretModp = a + cons - modp_two_power(M) * r_prime - r;\n\n let c = sc.clone().reveal().clone();\n\n let cb: Slice<ClearModp> = BitDec_ClearModp(c, M);\n\n return BitAdd(&cb, &rb.slice(..)).slice(..M);\n\n}\n\n\n\nconst BITLEN: u64 = P.len() as u64;\n\n\n\nconst BITLENP: u64 = {\n\n let mut a = BITLEN;\n\n while !P[(BITLEN - a + 1) as usize - 1] {\n\n a = a - 1;\n\n }\n\n a\n\n};\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 70, "score": 157586.28496695237 }, { "content": "/// Helper type giving us access to the `!` type on the stable compiler\n\npub trait HasOutput {\n\n type Output;\n\n}\n\n\n\nimpl<O> HasOutput for fn() -> O {\n\n type Output = O;\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 71, "score": 156993.35933710844 }, { "content": "pub trait Test {\n\n #[track_caller]\n\n fn test(self);\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 72, "score": 156980.92558309354 }, { "content": "pub trait Rand {\n\n fn rand(self) -> i64;\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! execute_garbled_circuit {\n\n ($id:ident($($arg:expr),*) -> $($ret:ty),*) => {{\n\n $(Stack::push(&$arg);)*\n\n execute_garbled_circuit(ConstU32::<$id>);\n\n ($(<$ret>::pop()),*)\n\n }};\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! execute_local_function {\n\n ($id:ident($($arg:expr),*) -> $($ret:ty),*) => {{\n\n $(Stack::push(&$arg);)*\n\n execute_local_function(ConstU32::<$id>);\n\n ($(<$ret>::pop()),*)\n\n }};\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 73, "score": 156980.92558309354 }, { "content": "pub trait Stack {\n\n /// Push a new item to the stack\n\n ///\n\n /// SAFETY: this function is unsafe, because runtime function calls also\n\n /// generate these instructions, and thus modifying the stack must be done\n\n /// very carefully.\n\n unsafe fn push(val: &Self);\n\n /// Read and remove the top item from the stack\n\n ///\n\n /// SAFETY: this function is unsafe, because runtime function calls also\n\n /// generate these instructions, and thus modifying the stack must be done\n\n /// very carefully.\n\n unsafe fn pop() -> Self;\n\n /// Read an item at the given stack address\n\n unsafe fn peek(addr: StackAddress) -> Self;\n\n /// Replace the item at the given stack address\n\n ///\n\n /// SAFETY: this function is unsafe, because runtime function calls also\n\n /// generate these instructions, and thus modifying the stack must be done\n\n /// very carefully.\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 74, "score": 156980.92558309354 }, { "content": "pub trait Output {\n\n fn output<const C: u32>(self, ch: Channel<C>);\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 75, "score": 156980.92558309354 }, { "content": "pub trait Allocate {\n\n /// This constant states how many elements will get allocated for each element\n\n /// given to `free`.\n\n const N: u64;\n\n unsafe fn free(&self, n: u64);\n\n fn allocate(&self, n: u64) -> u64;\n\n}\n\n\n\nimpl Allocate for &'static Allocator<ClearModp> {\n\n const N: u64 = 1;\n\n\n\n #[inline(always)]\n\n unsafe fn free(&self, addr: u64) {\n\n __deletec(addr as i64);\n\n }\n\n\n\n #[inline(always)]\n\n fn allocate(&self, n: u64) -> u64 {\n\n unsafe { __newc(n as i64) as u64 }\n\n }\n", "file_path": "WebAssembly/scale/src/alloc.rs", "rank": 76, "score": 156980.92558309354 }, { "content": "pub trait Print {\n\n fn print(self);\n\n}\n\n\n\nimpl Print for &'static str {\n\n #[inline(always)]\n\n fn print(self) {\n\n for &c in self.as_bytes() {\n\n unsafe { crate::__print_char_regint(c.into()) }\n\n }\n\n }\n\n}\n\n\n\n#[macro_export]\n\nmacro_rules! print {\n\n ($($e:expr),*) => {\n\n $($crate::Print::print($e);)*\n\n }\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/print.rs", "rank": 77, "score": 156980.92558309354 }, { "content": "pub trait Reveal {\n\n type Output;\n\n fn reveal(&self) -> Self::Output;\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 78, "score": 156980.92558309354 }, { "content": "pub trait Input {\n\n fn input<const C: u32>(ch: Channel<C>) -> Self;\n\n}\n\n\n\n#[cfg(not(feature = \"emulate\"))]\n\nmod testing;\n\n\n\n#[cfg(feature = \"emulate\")]\n\nmod testing_emulated;\n\n\n\npub mod alloc;\n\n\n\npub use scale_impl_generator::main;\n\n\n\n#[doc(hidden)]\n\n#[macro_export]\n\nmacro_rules! __main {\n\n (KAPPA = $kappa:expr;) => {\n\n use $crate::print;\n\n use $crate::*;\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 79, "score": 156980.92558309354 }, { "content": "#[inline(always)]\n\npub fn restart() {\n\n unsafe { __restart() }\n\n}\n\n\n\n// Clear Memory\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 80, "score": 156474.68655608039 }, { "content": "#[inline(always)]\n\npub fn crash() {\n\n unsafe { __crash() }\n\n}\n\n\n\n// Restart the system\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 81, "score": 156474.68655608039 }, { "content": "#[cfg_attr(not(feature = \"emulate\"), no_mangle)]\n\npub fn main() {\n\n let a = unsafe { __ldsi(42) };\n\n let a = unsafe { __convsintsreg(a) };\n\n let b = unsafe { __private_input(1, 20) };\n\n unsafe { __private_output(b, 2, 69) };\n\n let b = unsafe { __convsintsreg(b) };\n\n let mut d = b;\n\n let n = unsafe { __ldsi(3) };\n\n let n = unsafe { __convsintsreg(n) };\n\n while unsafe { __opensbit(__ltzsint(__subsint(d, n))) } {\n\n let e = unsafe { __convsregsint(d) };\n\n unsafe { __private_output(e, 2, 420) };\n\n d += a;\n\n }\n\n}\n", "file_path": "WebAssembly/scale/examples/secret.rs", "rank": 82, "score": 156474.68655608039 }, { "content": "fn bigint_to_bits(int: BigInt) -> Vec<bool> {\n\n assert_eq!(int.sign(), num_bigint::Sign::Plus);\n\n assert_eq!(BigInt::from(515_u16).to_bytes_be().1, vec![2, 3]);\n\n assert_eq!(BigInt::from(14_u16).to_bytes_be().1, vec![14]);\n\n int.to_bytes_be()\n\n .1\n\n .into_iter()\n\n .flat_map(byte_to_bits)\n\n .collect()\n\n}\n\n\n", "file_path": "WebAssembly/scale/impl_generator/src/lib.rs", "rank": 83, "score": 156141.936926597 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn CarryOutAux(a: &Slice<Array<SecretModp, 2>>) -> SecretModp {\n\n let mut k: u64 = a.len();\n\n let mut offset: u64 = 0;\n\n if k == 1 {\n\n return *a.get_unchecked(0).get_unchecked(1);\n\n }\n\n if k % 2 == 1 {\n\n offset = 1;\n\n k += 1;\n\n }\n\n let mut u: Slice<Array<SecretModp, 2>> = Slice::uninitialized(k / 2);\n\n for i in offset..k / 2 {\n\n let arr: Array<SecretModp, 2> = reg_carry(\n\n a.get_unchecked(2 * i + 1 - offset).clone(),\n\n a.get_unchecked(2 * i - offset).clone(),\n\n i != k / 2 - 1,\n\n );\n\n u.get_mut_unchecked(i).set(0, &*arr.get_unchecked(0));\n\n u.get_mut_unchecked(i).set(1, &*arr.get_unchecked(1));\n\n }\n\n if offset == 1 {\n\n u.get_mut_unchecked(0)\n\n .set(0, &*a.get_unchecked(0).get_unchecked(0));\n\n u.get_mut_unchecked(0)\n\n .set(1, &*a.get_unchecked(0).get_unchecked(1));\n\n }\n\n return CarryOutAux(&u);\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 84, "score": 156089.28020388837 }, { "content": "#[inline(always)]\n\n#[allow(non_snake_case)]\n\npub fn BitDecFullBig(a: SecretModp) -> Array<SecretModp, BITLENP> {\n\n // Returns secret shared bit decomposition of\n\n let mut abits: Array<SecretModp, BITLENP> = Array::uninitialized();\n\n let mut bbits: Array<SecretModp, BITLENP> = Array::uninitialized();\n\n let mut pbits: Array<ClearModp, { BITLENP + 1 }> = Array::uninitialized();\n\n for i in 0u64..BITLENP {\n\n pbits.set(i, &ClearModp::from(P[(BITLEN - 1 - i) as usize] as i64));\n\n }\n\n // Loop until we get some random integers less than p\n\n let mut cond: i64 = 0;\n\n while cond == 0 {\n\n for i in 0u64..BITLENP {\n\n bbits.set(i, &SecretModp::get_random_bit());\n\n }\n\n // FIXME: make `BitLTFull` accept `Array`s\n\n let v = BitLTFull(&bbits.slice(..), &pbits.slice(..)).reveal();\n\n cond = i64::from(v);\n\n }\n\n // FIXME: make `SumBits` accept `Array`s\n\n let b: SecretModp = SumBits(&bbits.slice(..));\n", "file_path": "WebAssembly/scale_std/src/bit_protocols.rs", "rank": 85, "score": 155159.29002201548 }, { "content": "pub trait Visitor<'a> {\n\n fn cx(&self) -> &'a Compiler;\n\n fn visit_body(&mut self, body: &mut Body<'a>) {\n\n self.walk_body(body)\n\n }\n\n fn walk_body(&mut self, body: &mut Body<'a>) {\n\n let Body { blocks } = body;\n\n for block in blocks {\n\n self.visit_block(block);\n\n }\n\n }\n\n\n\n fn visit_block(&mut self, block: &mut Block<'a>) {\n\n self.walk_block(block)\n\n }\n\n fn walk_block(&mut self, block: &mut Block<'a>) {\n\n let Block { stmts, terminator } = block;\n\n for stmt in stmts {\n\n self.visit_stmt(stmt);\n\n }\n", "file_path": "Assembler/src/visitor.rs", "rank": 86, "score": 155080.67190341 }, { "content": "// Note test_mem is never implemented for secret types\n\n// - This makes things a bit simpler\n\npub trait TestMem {\n\n #[track_caller]\n\n fn test_mem<const I: u32>(self, t_location: ConstU32<I>);\n\n}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 87, "score": 153933.1780108889 }, { "content": "pub trait Floor {\n\n fn floor(self) -> Self;\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 88, "score": 153927.7285816637 }, { "content": "pub trait Sqrt {\n\n fn sqrt(self) -> Self;\n\n}\n\n\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 89, "score": 153927.7285816637 }, { "content": "pub trait Float:\n\n Copy\n\n + From<i64>\n\n + From<f64>\n\n + Floor\n\n + FAbs\n\n + Sqrt\n\n + Constants\n\n + LoadFromMem<i64>\n\n + StoreInMem<i64>\n\n + GetAllocator\n\n{\n\n}\n\n\n\nimpl Float for ClearIEEE {}\n\n\n\nimpl Float for SecretIEEE {}\n\n\n\nimpl<const K: u64, const F: u64> Float for ClearFixed<K, F>\n\nwhere\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 90, "score": 153927.7285816637 }, { "content": "pub trait RevealIfSecret {\n\n type Output;\n\n fn reveal_if_secret(&self) -> Self::Output;\n\n}\n\n\n\nmod clear_modp;\n\nmod i64;\n\nmod io;\n\nmod print;\n\nmod secret_bit;\n\nmod secret_i64;\n\nmod secret_modp;\n\nmod system;\n\n\n\npub use io::*;\n\npub use print::*;\n\npub use system::*;\n\n\n\n#[cfg(not(feature = \"emulate\"))]\n\nextern \"Rust\" {\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 91, "score": 153927.7285816637 }, { "content": "pub trait InnerModp:\n\n AnyRegister\n\n + From<ClearModp>\n\n + Into<SecretModp>\n\n + RevealIfSecret\n\n + Mul<ClearModp, Output = Self>\n\n + Add<ClearModp, Output = Self>\n\n + Sub<ClearModp, Output = Self>\n\n + Mul<SecretModp, Output = SecretModp>\n\n + Add<SecretModp, Output = SecretModp>\n\n + Sub<SecretModp, Output = SecretModp>\n\n{\n\n}\n\n\n\nimpl InnerModp for ClearModp {}\n\nimpl InnerModp for SecretModp {}\n\n\n", "file_path": "WebAssembly/scale/src/lib.rs", "rank": 92, "score": 153927.7285816637 }, { "content": "pub trait Constants\n\nwhere\n\n Self: From<f64>,\n\n{\n\n #[inline(always)]\n\n fn two_pi() -> Self {\n\n Self::from(6.2831853071795864769252867665590057684)\n\n }\n\n #[inline(always)]\n\n fn pi() -> Self {\n\n Self::from(3.1415926535897932384626433832795028842)\n\n }\n\n #[inline(always)]\n\n fn half_pi() -> Self {\n\n Self::from(1.5707963267948966192313216916397514421)\n\n }\n\n #[inline(always)]\n\n fn ln2() -> Self {\n\n Self::from(0.69314718055994530941723212145817656807)\n\n }\n\n #[inline(always)]\n\n fn e() -> Self {\n\n Self::from(2.7182818284590452353602874713526624978)\n\n }\n\n}\n\n\n\n/* Make some supertraits to help in where clauses */\n\n\n", "file_path": "WebAssembly/scale_std/src/math.rs", "rank": 93, "score": 153927.7285816637 }, { "content": "#[cfg_attr(not(feature = \"emulate\"), no_mangle)]\n\npub fn main() {\n\n let y = black_box(5);\n\n for i in 0..y {\n\n unsafe { __print_reg(__convint(i)) };\n\n }\n\n unsafe { __print_reg(__ldi(42)) };\n\n}\n", "file_path": "WebAssembly/scale/examples/control_flow.rs", "rank": 94, "score": 153427.51384276053 }, { "content": "#[inline(always)]\n\npub fn clear_memory() {\n\n unsafe { __clear_memory() }\n\n}\n\n\n\n// Clear Registers\n", "file_path": "WebAssembly/scale/src/system.rs", "rank": 95, "score": 153427.51384276053 }, { "content": "fn parse_operand(cx: &Compiler, span: Span) -> Spanned<Operand> {\n\n let span = span.trim(cx);\n\n let s = span.snippet(cx).to_ascii_lowercase();\n\n match &*s {\n\n \"true\" => return span.with(Operand::Value(Const::Bool(true))),\n\n \"false\" => return span.with(Operand::Value(Const::Bool(false))),\n\n _ => {}\n\n }\n\n let mut chars = s.chars();\n\n let mut id_span = span;\n\n let mkfn: fn(u32) -> Register = {\n\n match chars.next() {\n\n None => {\n\n return cx\n\n .report(crate::errors::ExpectedOperand { span })\n\n .with(Operand::Value(Const::Int(i32::min_value())))\n\n }\n\n Some('c') => {\n\n id_span = id_span.eat_one();\n\n |i| Register::Clear(register::Clear(i))\n", "file_path": "Assembler/src/lexer/parser.rs", "rank": 96, "score": 153409.13115204964 }, { "content": "fn catch_or_neg_one(f: impl FnOnce() -> Result<()>) -> c_int {\n\n std::panic::catch_unwind(std::panic::AssertUnwindSafe(f))\n\n .map_err(|_| error!(\"panic caught before going back to C\"))\n\n .and_then(|val| val.map(|_| 0_i32).map_err(|e| error!(\"{}\", e)))\n\n .unwrap_or(-1_i32)\n\n}\n\n\n\n#[no_mangle]\n\n#[must_use]\n\npub extern \"C\" fn scale_io_close(handle: &mut ScaleMambaHandle) -> c_int {\n\n catch_or_neg_one(|| handle.handler.close())\n\n}\n\n\n\n#[no_mangle]\n\n#[must_use]\n\npub extern \"C\" fn scale_io_open_channel(handle: &ScaleMambaHandle, channel: c_uint) -> c_int {\n\n catch_or_neg_one(|| handle.handler.open_channel(channel))\n\n}\n\n\n\n#[no_mangle]\n", "file_path": "src/src/scale_mamba_handler.rs", "rank": 97, "score": 153191.31802191603 }, { "content": "pub fn generate_bytecode<'a>(\n\n cx: &'a Compiler,\n\n asm: &[Lexical<'a>],\n\n mut dest: impl std::io::Write,\n\n) -> std::io::Result<()> {\n\n for lex in asm {\n\n let get_instr = |name: &str, span| match name2instr(name) {\n\n Some(val) => val,\n\n None => {\n\n cx.report(UnimplementedInstruction { span, name });\n\n name2instr(\"crash\").unwrap()\n\n }\n\n };\n\n let (opcode, args) = if lex.instruction.starts_with('v') {\n\n let instr = &get_instr(&lex.instruction[1..], lex.span);\n\n assert!(instr.vectorizable);\n\n let (v, args) = lex.args.split_first().unwrap();\n\n let v: u32 = cx.checked_from(*v).elem;\n\n // magic number 9 taken from SCALE documentation\n\n (instr.opcode | v << 9, args)\n", "file_path": "Assembler/src/binary.rs", "rank": 98, "score": 151105.42029521876 }, { "content": "pub fn run_optimizations<'a>(\n\n cx: &'a Compiler,\n\n body: &mut Body<'a>,\n\n dump: Option<PathBuf>,\n\n optimizations: &[String],\n\n) {\n\n let passes: std::collections::HashMap<_, _> = PASSES\n\n .iter()\n\n .map(|p| {\n\n let pass = p();\n\n (pass.name(), p)\n\n })\n\n .collect();\n\n for pass in optimizations {\n\n let mut pass = (passes.get(pass.as_str()).expect(\"unknown pass\"))();\n\n println!(\"run_optimizations: {}\", pass.name());\n\n info!(\"opt pass: {}\", pass.name());\n\n pass.apply(cx, body);\n\n if let Some(dump) = &dump {\n\n dump_pass(cx, body, dump, pass.name());\n\n }\n\n }\n\n}\n\n\n", "file_path": "Assembler/src/transforms.rs", "rank": 99, "score": 151105.42029521876 } ]
Rust
firmware_rust/AirQualitySensor/src/bin/firmware.rs
Tao173/AirQualitySensor
735faece883f3b21394d61d2431b15c6accc54d8
#![no_main] #![no_std] use firmware as _; use firmware::hal; #[rtic::app(device = firmware::hal::stm32, peripherals = true, dispatchers = [USART1, USART2])] mod app { use super::hal; use hal::gpio; use hal::prelude::*; use hal::stm32; use hal::timer; use systick_monotonic::*; use firmware::subsystems::{Galvos, LEDs, Sensor, GALVO_CALIBRATION}; #[monotonic(binds = SysTick, default = true)] type SystickMono = Systick<1000>; #[local] struct LocalResources { next_sensor_tick: <SystickMono as rtic::Monotonic>::Instant, next_led_tick: <SystickMono as rtic::Monotonic>::Instant, next_galvo_tick: <SystickMono as rtic::Monotonic>::Instant, watchdog: hal::watchdog::IndependedWatchdog, } #[shared] struct SharedResources { sensor_subsystem: Sensor, galvo_subsystem: Galvos< timer::pwm::PwmPin<stm32::TIM16, timer::Channel1>, timer::pwm::PwmPin<stm32::TIM14, timer::Channel1>, timer::pwm::PwmPin<stm32::TIM1, timer::Channel1>, >, led_subsystem: LEDs< gpio::gpioa::PA0<gpio::Output<gpio::PushPull>>, gpio::gpioa::PA1<gpio::Output<gpio::PushPull>>, gpio::gpioa::PA2<gpio::Output<gpio::PushPull>>, >, i2c: hal::i2c::I2c< stm32::I2C2, gpio::gpioa::PA12<gpio::Output<gpio::OpenDrain>>, gpio::gpioa::PA11<gpio::Output<gpio::OpenDrain>>, >, } #[init] fn init(ctx: init::Context) -> (SharedResources, LocalResources, init::Monotonics) { ctx.device.RCC.ahbenr.modify(|_, w| w.dmaen().set_bit()); defmt::println!("Finomnis' AirQualitySensor - Galvo Version"); let mut rcc = ctx.device.RCC.constrain(); let gpioa = ctx.device.GPIOA.split(&mut rcc); let i2c_sda = gpioa.pa12.into_open_drain_output(); let i2c_scl = gpioa.pa11.into_open_drain_output(); let delay = ctx.core.SYST.delay(&mut rcc); let i2c = ctx .device .I2C2 .i2c(i2c_sda, i2c_scl, hal::i2c::Config::new(100.khz()), &mut rcc); let now = monotonics::now(); let sensor_subsystem = Sensor::new(); let next_sensor_tick = now; sensor_tick::spawn_at(next_sensor_tick).unwrap(); let led_subsystem = LEDs::new( gpioa.pa0.into_push_pull_output(), gpioa.pa1.into_push_pull_output(), gpioa.pa2.into_push_pull_output(), ); let next_led_tick = now + 1.millis(); led_tick::spawn_at(next_led_tick).unwrap(); let pwm1 = ctx.device.TIM16.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa6); let pwm2 = ctx.device.TIM14.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa4); let pwm3 = ctx.device.TIM1.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa7); let galvo_subsystem = Galvos::new(( (pwm1, false, GALVO_CALIBRATION.0), (pwm2, false, GALVO_CALIBRATION.1), (pwm3, true, GALVO_CALIBRATION.2), )); let next_galvo_tick = now + 2.millis(); galvo_tick::spawn_at(next_galvo_tick).unwrap(); let mut watchdog = ctx.device.IWDG.constrain(); watchdog.start(2000.ms()); watchdog_wagger::spawn_at(monotonics::now()).unwrap(); ( SharedResources { i2c, sensor_subsystem, led_subsystem, galvo_subsystem, }, LocalResources { next_sensor_tick, next_led_tick, next_galvo_tick, watchdog, }, init::Monotonics(Systick::new(delay.release(), rcc.clocks.sys_clk.0)), ) } #[task(shared = [i2c, sensor_subsystem, led_subsystem, galvo_subsystem], local = [next_sensor_tick])] fn sensor_tick(mut ctx: sensor_tick::Context) { let next_sensor_tick = ctx.local.next_sensor_tick; let delay = ctx.shared.i2c.lock(|i2c| { ctx.shared.sensor_subsystem.lock(|sensor_subsystem| { let (delay, changed) = sensor_subsystem.tick(i2c); if changed { ctx.shared.led_subsystem.lock(|led_subsystem| { led_subsystem.update_leds(sensor_subsystem.get_value()) }); ctx.shared.galvo_subsystem.lock(|galvo_subsystem| { galvo_subsystem.update_values(sensor_subsystem.get_value()) }); } delay }) }); *next_sensor_tick = *next_sensor_tick + delay.millis(); sensor_tick::spawn_at(*next_sensor_tick).unwrap(); } #[task(shared = [sensor_subsystem, led_subsystem], local = [next_led_tick])] fn led_tick(mut ctx: led_tick::Context) { let next_led_tick = ctx.local.next_led_tick; let sensor_value = ctx.shared.sensor_subsystem.lock(|s| s.get_value().clone()); let delay = ctx.shared.led_subsystem.lock(|s| s.tick(&sensor_value)); *next_led_tick = *next_led_tick + delay.millis(); led_tick::spawn_at(*next_led_tick).unwrap(); } #[task(shared = [galvo_subsystem], local = [next_galvo_tick])] fn galvo_tick(mut ctx: galvo_tick::Context) { let next_galvo_tick = ctx.local.next_galvo_tick; let delay = ctx.shared.galvo_subsystem.lock(|s| s.tick()); *next_galvo_tick = *next_galvo_tick + delay.millis(); galvo_tick::spawn_at(*next_galvo_tick).unwrap(); } #[task(local = [watchdog])] fn watchdog_wagger(ctx: watchdog_wagger::Context) { ctx.local.watchdog.feed(); watchdog_wagger::spawn_at(monotonics::now() + 100.millis()).unwrap(); } }
#![no_main] #![no_std] use firmware as _; use firmware::hal; #[rtic::app(device = firmware::hal::stm32, peripherals = true, dispatchers = [USART1, USART2])] mod app { use super::hal; use hal::gpio; use hal::prelude::*; use hal::stm32; use hal::timer; use systick_monotonic::*; use firmware::subsystems::{Galvos, LEDs, Sensor, GALVO_CALIBRATION}; #[monotonic(binds = SysTick, default = true)] type SystickMono = Systick<1000>; #[local] struct LocalResources { next_sensor_tick: <SystickMono as rtic::Monotonic>::Instant, next_led_tick: <SystickMono as rtic::Monotonic>::Instant, next_galvo_tick: <SystickMono as rtic::Monotonic>::Instant, watchdog: hal::watchdog::IndependedWatchdog, } #[shared] struct SharedResources { sensor_subsystem: Sensor, galvo_subsystem: Galvos< timer::pwm::PwmPin<stm32::TIM16, timer::Channel1>, timer::pwm::PwmPin<stm32::TIM14, timer::Channel1>, timer::pwm::PwmPin<stm32::TIM1, timer::Channel1>, >, led_subsystem: LEDs< gpio::gpioa::PA0<gpio::Output<gpio::PushPull>>, gpio::gpioa::PA1<gpio::Output<gpio::PushPull>>, gpio::gpioa::PA2<gpio::Output<gpio::PushPull>>, >, i2c: hal::i2c::I2c< stm32::I2C2, gpio::gpioa::PA12<gpio::Output<gpio::OpenDrain>>, gpio::gpioa::PA11<gpio::Output<gpio::OpenDrain>>, >, } #[init] fn init(ctx: init::Context) -> (SharedResources, LocalResources, init::Monotonics) { ctx.device.RCC.ahbenr.modify(|_, w| w.dmaen().set_bit()); defmt::println!("Finomnis' AirQualitySensor - Galvo Version"); let mut rcc = ctx.device.RCC.constrain(); let gpioa = ctx.device.GPIOA.split(&mut rcc); let i2c_sda = gpioa.pa12.into_open_drain_output(); let i2c_scl = gpioa.pa11.into_open_drain_output(); l
into_push_pull_output(), gpioa.pa1.into_push_pull_output(), gpioa.pa2.into_push_pull_output(), ); let next_led_tick = now + 1.millis(); led_tick::spawn_at(next_led_tick).unwrap(); let pwm1 = ctx.device.TIM16.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa6); let pwm2 = ctx.device.TIM14.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa4); let pwm3 = ctx.device.TIM1.pwm(1.khz(), &mut rcc).bind_pin(gpioa.pa7); let galvo_subsystem = Galvos::new(( (pwm1, false, GALVO_CALIBRATION.0), (pwm2, false, GALVO_CALIBRATION.1), (pwm3, true, GALVO_CALIBRATION.2), )); let next_galvo_tick = now + 2.millis(); galvo_tick::spawn_at(next_galvo_tick).unwrap(); let mut watchdog = ctx.device.IWDG.constrain(); watchdog.start(2000.ms()); watchdog_wagger::spawn_at(monotonics::now()).unwrap(); ( SharedResources { i2c, sensor_subsystem, led_subsystem, galvo_subsystem, }, LocalResources { next_sensor_tick, next_led_tick, next_galvo_tick, watchdog, }, init::Monotonics(Systick::new(delay.release(), rcc.clocks.sys_clk.0)), ) } #[task(shared = [i2c, sensor_subsystem, led_subsystem, galvo_subsystem], local = [next_sensor_tick])] fn sensor_tick(mut ctx: sensor_tick::Context) { let next_sensor_tick = ctx.local.next_sensor_tick; let delay = ctx.shared.i2c.lock(|i2c| { ctx.shared.sensor_subsystem.lock(|sensor_subsystem| { let (delay, changed) = sensor_subsystem.tick(i2c); if changed { ctx.shared.led_subsystem.lock(|led_subsystem| { led_subsystem.update_leds(sensor_subsystem.get_value()) }); ctx.shared.galvo_subsystem.lock(|galvo_subsystem| { galvo_subsystem.update_values(sensor_subsystem.get_value()) }); } delay }) }); *next_sensor_tick = *next_sensor_tick + delay.millis(); sensor_tick::spawn_at(*next_sensor_tick).unwrap(); } #[task(shared = [sensor_subsystem, led_subsystem], local = [next_led_tick])] fn led_tick(mut ctx: led_tick::Context) { let next_led_tick = ctx.local.next_led_tick; let sensor_value = ctx.shared.sensor_subsystem.lock(|s| s.get_value().clone()); let delay = ctx.shared.led_subsystem.lock(|s| s.tick(&sensor_value)); *next_led_tick = *next_led_tick + delay.millis(); led_tick::spawn_at(*next_led_tick).unwrap(); } #[task(shared = [galvo_subsystem], local = [next_galvo_tick])] fn galvo_tick(mut ctx: galvo_tick::Context) { let next_galvo_tick = ctx.local.next_galvo_tick; let delay = ctx.shared.galvo_subsystem.lock(|s| s.tick()); *next_galvo_tick = *next_galvo_tick + delay.millis(); galvo_tick::spawn_at(*next_galvo_tick).unwrap(); } #[task(local = [watchdog])] fn watchdog_wagger(ctx: watchdog_wagger::Context) { ctx.local.watchdog.feed(); watchdog_wagger::spawn_at(monotonics::now() + 100.millis()).unwrap(); } }
et delay = ctx.core.SYST.delay(&mut rcc); let i2c = ctx .device .I2C2 .i2c(i2c_sda, i2c_scl, hal::i2c::Config::new(100.khz()), &mut rcc); let now = monotonics::now(); let sensor_subsystem = Sensor::new(); let next_sensor_tick = now; sensor_tick::spawn_at(next_sensor_tick).unwrap(); let led_subsystem = LEDs::new( gpioa.pa0.
function_block-random_span
[]
Rust
third-party/rust/shed/futures_stats/src/futures01.rs
baioc/antlir
e3b47407b72c4aee835adf4e68fccd9abff457f2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use futures_01_ext::{BoxFuture, BoxFutureNonSend, BoxStream, FutureExt, StreamExt}; use futures_old::{Async, Future, IntoFuture, Poll, Stream}; use std::time::{Duration, Instant}; use super::{FutureStats, StreamStats}; pub struct TimedFuture<F> { inner: F, start: Option<Instant>, poll_count: u64, poll_time: Duration, } impl<F> TimedFuture<F> { fn new(future: F) -> Self { TimedFuture { inner: future, start: None, poll_count: 0, poll_time: Duration::from_secs(0), } } } impl<F: Future> Future for TimedFuture<F> { type Item = (Result<F::Item, F::Error>, FutureStats); type Error = !; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let _ = self.start.get_or_insert_with(Instant::now); self.poll_count += 1; let poll_start = Instant::now(); let poll = self.inner.poll(); self.poll_time += poll_start.elapsed(); let res = match poll { Ok(Async::NotReady) => return Ok(Async::NotReady), Ok(Async::Ready(v)) => Ok(v), Err(e) => Err(e), }; let stats = FutureStats { completion_time: self.start.expect("start time not set").elapsed(), poll_time: self.poll_time, poll_count: self.poll_count, }; Ok(Async::Ready((res, stats))) } } pub struct TimedStream<S, C, R> where R: IntoFuture<Item = (), Error = ()> + 'static, S: Stream, { inner: S, callback: Option<C>, callback_future: Option<R::Future>, start: Option<Instant>, stream_result: Option<Result<(), S::Error>>, count: usize, poll_count: u64, poll_time: Duration, first_item_time: Option<Duration>, } impl<S, C, R> TimedStream<S, C, R> where R: IntoFuture<Item = (), Error = ()> + 'static, S: Stream, { fn new(stream: S, callback: C) -> Self { TimedStream { inner: stream, callback: Some(callback), callback_future: None, start: None, stream_result: None, count: 0, poll_count: 0, poll_time: Duration::from_secs(0), first_item_time: None, } } } impl<S, C, R> Stream for TimedStream<S, C, R> where S: Stream, C: FnOnce(StreamStats, Result<(), &S::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, { type Item = S::Item; type Error = S::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if self.callback_future.is_some() { return self.poll_callback_future(); } let _ = self.start.get_or_insert_with(Instant::now); self.poll_count += 1; let poll_start = Instant::now(); let poll = self.inner.poll(); self.poll_time += poll_start.elapsed(); match poll { Ok(Async::NotReady) => Ok(Async::NotReady), notfinished @ Ok(Async::Ready(Some(_))) => { self.count += 1; if self.count == 1 { self.first_item_time = Some(self.start.expect("start time not set").elapsed()); } notfinished } Ok(Async::Ready(None)) => { let callback_future = self.run_callback(Ok(())); self.stream_result = Some(Ok(())); self.callback_future = Some(callback_future.into_future()); self.poll_callback_future() } Err(err) => { let callback_future = self.run_callback(Err(&err)); self.stream_result = Some(Err(err)); self.callback_future = Some(callback_future.into_future()); self.poll_callback_future() } } } } impl<S, C, R> TimedStream<S, C, R> where S: Stream, C: FnOnce(StreamStats, Result<(), &S::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, { fn run_callback(&mut self, res: Result<(), &S::Error>) -> R { let stats = StreamStats { completion_time: self.start.expect("start time not set").elapsed(), poll_time: self.poll_time, poll_count: self.poll_count, count: self.count, first_item_time: self.first_item_time, }; let callback = self.callback.take().expect("callback was already called"); callback(stats, res) } fn poll_callback_future( &mut self, ) -> Poll<Option<<Self as Stream>::Item>, <Self as Stream>::Error> { if let Some(ref mut fut) = self.callback_future { let poll = fut.poll(); if poll == Ok(Async::NotReady) { return Ok(Async::NotReady); } let stream_result = self .stream_result .take() .expect("stream result should have been set"); match stream_result { Ok(()) => Ok(Async::Ready(None)), Err(err) => Err(err), } } else { panic!("callback future is not set!"); } } } fn time_future<F, C, R>(future: F, callback: C) -> impl Future<Item = F::Item, Error = F::Error> where F: Future, C: FnOnce(FutureStats, Result<&F::Item, &F::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: 'static, { TimedFuture::new(future).then(|res| { let (res, stats) = res.expect("unexpected unreachable err"); callback(stats, res.as_ref()).into_future().then(|_| res) }) } fn future_with_timing<F>( future: F, ) -> impl Future<Item = (FutureStats, F::Item), Error = (FutureStats, F::Error)> where F: Future, { TimedFuture::new(future).then(|res| { let (real_res, stats) = res.expect("unexpected unreachable err"); match real_res { Ok(r) => Ok((stats, r)), Err(e) => Err((stats, e)), } }) } pub trait Timed: Future + Sized + Send + 'static { fn timed<C, R>(self, callback: C) -> BoxFuture<Self::Item, Self::Error> where C: FnOnce(FutureStats, Result<&Self::Item, &Self::Error>) -> R + Send + 'static, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: Send + 'static, Self::Item: Send, Self::Error: Send, { time_future(self, callback).boxify() } fn collect_timing(self) -> BoxFuture<(FutureStats, Self::Item), (FutureStats, Self::Error)> where Self::Item: Send, Self::Error: Send, { future_with_timing(self).boxify() } } pub trait TimedNonSend: Future + Sized + 'static { fn timed_nonsend<C, R>(self, callback: C) -> BoxFutureNonSend<Self::Item, Self::Error> where C: FnOnce(FutureStats, Result<&Self::Item, &Self::Error>) -> R + 'static, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: 'static, { time_future(self, callback).boxify_nonsend() } fn collect_timing( self, ) -> BoxFutureNonSend<(FutureStats, Self::Item), (FutureStats, Self::Error)> { future_with_timing(self).boxify_nonsend() } } impl<T: Future + Send + 'static> Timed for T {} impl<T: Future + 'static> TimedNonSend for T {} pub trait TimedStreamTrait: Stream + Sized + Send + 'static { fn timed<C, R>(self, callback: C) -> BoxStream<Self::Item, Self::Error> where C: FnOnce(StreamStats, Result<(), &Self::Error>) -> R + Send + 'static, R: IntoFuture<Item = (), Error = ()> + Send + 'static, R::Future: 'static, <R as futures_old::IntoFuture>::Future: Send, Self::Item: Send, Self::Error: Send, { TimedStream::new(self, callback).boxify() } } impl<T: Stream + Send + 'static> TimedStreamTrait for T {} #[cfg(test)] mod tests { use super::*; use anyhow::Error; use futures_old::future::{err, ok}; use futures_old::stream::{iter_ok, once}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; #[test] fn test_timed_stream_simple() { let callback_called = Arc::new(AtomicBool::new(false)); const TEST_COUNT: usize = 3; let s: BoxStream<_, ()> = iter_ok([0; TEST_COUNT].iter()) .timed({ let callback_called = callback_called.clone(); move |stats, _| { assert_eq!(stats.count, TEST_COUNT); callback_called.store(true, Ordering::SeqCst); Ok(()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ())); assert!(callback_called.load(Ordering::SeqCst)); } #[test] fn test_timed_stream_error() { let callback_called = Arc::new(AtomicBool::new(false)); let err_happened = Arc::new(AtomicBool::new(false)); let err_reported = Arc::new(AtomicBool::new(false)); let s: BoxStream<(), _> = once(Err(Error::msg("err"))) .timed({ let callback_called = callback_called.clone(); let err_reported = err_reported.clone(); move |_, res| { callback_called.store(true, Ordering::SeqCst); err_reported.store(res.is_err(), Ordering::SeqCst); Ok(()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ()).map_err({ let err_happened = err_happened.clone(); move |_| err_happened.store(true, Ordering::SeqCst) })); assert!(callback_called.load(Ordering::SeqCst)); assert!(err_happened.load(Ordering::SeqCst)); assert!(err_reported.load(Ordering::SeqCst)); } #[test] fn test_timed_with_future() { let sleep_fut = tokio_timer::sleep(Duration::from_millis(300)); let future_called = Arc::new(AtomicBool::new(false)); let s: BoxStream<_, ()> = iter_ok([1, 2, 3].iter()) .timed({ let future_called = future_called.clone(); move |_, _| { sleep_fut .map(move |_| { future_called.store(true, Ordering::SeqCst); () }) .map_err(|_| ()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ())); assert!(future_called.load(Ordering::SeqCst)); } #[test] fn test_timed_with_err_and_future() { let sleep_fut = tokio_timer::sleep(Duration::from_millis(300)); let future_called = Arc::new(AtomicBool::new(false)); let err_happened = Arc::new(AtomicBool::new(false)); let err_reported = Arc::new(AtomicBool::new(false)); let s: BoxStream<(), _> = once(Err(Error::msg("err"))) .timed({ let err_reported = err_reported.clone(); let future_called = future_called.clone(); move |_, res| { err_reported.store(res.is_err(), Ordering::SeqCst); sleep_fut .map(move |_| { future_called.store(true, Ordering::SeqCst); () }) .map_err(|_| ()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ()).map_err({ let err_happened = err_happened.clone(); move |_| { err_happened.store(true, Ordering::SeqCst); () } })); assert!(err_happened.load(Ordering::SeqCst)); assert!(err_reported.load(Ordering::SeqCst)); assert!(future_called.load(Ordering::SeqCst)); } #[test] fn test_collect_timings_with_future_ok() { let result_ok = Arc::new(AtomicBool::new(false)); let f: BoxFuture<u32, ()> = ok(123).boxify(); let f = Timed::collect_timing(f) .map({ let result_ok = result_ok.clone(); move |(_, r)| { result_ok.store(r == 123, Ordering::SeqCst); () } }) .map(|_| ()) .map_err(|_| ()) .boxify(); tokio_old::run(f); assert!(result_ok.load(Ordering::SeqCst)); } #[test] fn test_collect_timings_with_future_error() { let err_ok = Arc::new(AtomicBool::new(false)); let f: BoxFuture<(), u32> = err(123).boxify(); let f = Timed::collect_timing(f) .map_err({ let err_ok = err_ok.clone(); move |(_, r)| { err_ok.store(r == 123, Ordering::SeqCst); () } }) .map(|_| ()) .map_err(|_| ()) .boxify(); tokio_old::run(f); assert!(err_ok.load(Ordering::SeqCst)); } }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ use futures_01_ext::{BoxFuture, BoxFutureNonSend, BoxStream, FutureExt, StreamExt}; use futures_old::{Async, Future, IntoFuture, Poll, Stream}; use std::time::{Duration, Instant}; use super::{FutureStats, StreamStats}; pub struct TimedFuture<F> { inner: F, start: Option<Instant>, poll_count: u64, poll_time: Duration, } impl<F> TimedFuture<F> { fn new(future: F) -> Self { TimedFuture { inner: future, start: None, poll_count: 0, poll_time: Duration::from_secs(0), } } } impl<F: Future> Future for TimedFuture<F> { type Item = (Result<F::Item, F::Error>, FutureStats); type Error = !; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let _ = self.start.get_or_insert_with(Instant::now); self.poll_count += 1; let poll_start = Instant::now(); let poll = self.inner.poll(); self.poll_time += poll_start.elapsed(); let res = match poll { Ok(Async::NotReady) => return Ok(Async::NotReady), Ok(Async::Ready(v)) => Ok(v), Err(e) => Err(e), }; let stats = FutureStats { completion_time: self.start.expect("start time not set").elapsed(), poll_time: self.poll_time, poll_count: self.poll_count, }; Ok(Async::Ready((res, stats))) } } pub struct TimedStream<S, C, R> where R: IntoFuture<Item = (), Error = ()> + 'static, S: Stream, { inner: S, callback: Option<C>, callback_future: Option<R::Future>, start: Option<Instant>, stream_result: Option<Result<(), S::Error>>, count: usize, poll_count: u64, poll_time: Duration, first_item_time: Option<Duration>, } impl<S, C, R> TimedStream<S, C, R> where R: IntoFuture<Item = (), Error = ()> + 'static, S: Stream, { fn new(stream: S, callback: C) -> Self { TimedStream { inner: stream, callback: Some(callback), callback_future: None, start: None, stream_result: None, count: 0, poll_count: 0, poll_time: Duration::from_secs(0), first_item_time: None, } } } impl<S, C, R> Stream for TimedStream<S, C, R> where S: Stream, C: FnOnce(StreamStats, Result<(), &S::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, { type Item = S::Item; type Error = S::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { if self.callback_future.is_some() { return self.poll_callback_future(); } let _ = self.start.get_or_insert_with(Instant::now); self.poll_count += 1; let poll_start = Instant::now(); let poll = self.inner.poll(); self.poll_time += poll_start.elapsed(); match poll { Ok(Async::NotReady) => Ok(Async::NotReady), notfinished @ Ok(Async::Ready(Some(_))) => { self.count += 1; if self.count == 1 { self.first_item_time = Some(self.start.expect("start time not set").elapsed()); } notfinished } Ok(Async::Ready(None)) => { let callback_future = self.run_callback(Ok(())); self.stream_result = Some(Ok(())); self.callback_future = Some(callback_future.into_future()); self.poll_callback_future() } Err(err) => { let callback_future = self.run_callback(Err(&err)); self.stream_result = Some(Err(err)); self.callback_future = Some(callback_future.into_future()); self.poll_callback_future() } } } } impl<S, C, R> TimedStream<S, C, R> where S: Stream, C: FnOnce(StreamStats, Result<(), &S::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, { fn run_callback(&mut self, res: Result<(), &S::Error>) -> R { let stats = StreamStats { completion_time: self.start.expect("start time not set").elapsed(), poll_time: self.poll_time, poll_count: self.poll_count, count: self.count, first_item_time: self.first_item_time, }; let callback = self.callback.take().expect("callback was already called"); callback(stats, res) } fn poll_callback_future( &mut self, ) -> Poll<Option<<Self as Stream>::Item>, <Self as Stream>::Error> { if let Some(ref mut fut) = self.callback_future { let poll = fut.poll(); if poll == Ok(Async::NotReady) { return Ok(Async::NotReady); } let stream_result = self .stream_result .take() .expect("stream result should have been set"); match stream_result { Ok(()) => Ok(Async::Ready(None)), Err(err) => Err(err), } } else { panic!("callback future is not set!"); } } } fn time_future<F, C, R>(future: F, callback: C) -> impl Future<Item = F::Item, Error = F::Error> where F: Future, C: FnOnce(FutureStats, Result<&F::Item, &F::Error>) -> R, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: 'static, { TimedFuture::new(future).then(|res| { let (res, stats) = res.expect("unexpected unreachable err"); callback(stats, res.as_ref()).into_future().then(|_| res) }) } fn future_with_timing<F>( future: F, ) -> impl Future<Item = (FutureStats, F::Item), Error = (FutureStats, F::Error)> where F: Future, { TimedFuture::new(future).then(|res| { let (real_res, stats) = res.expect("unexpected unreachable err"); match real_res { Ok(r) => Ok((stats, r)), Err(e) => Err((stats, e)), } }) } pub trait Timed: Future + Sized + Send + 'static { fn timed<C, R>(self, callback: C) -> BoxFuture<Self::Item, Self::Error> where C: FnOnce(FutureStats, Result<&Self::Item, &Self::Error>) -> R + Send + 'static, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: Send + 'static, Self::Item: Send, Self::Error: Send, { time_future(self, callback).boxify() } fn collect_timing(self) -> BoxFuture<(FutureStats, Self::Item), (FutureStats, Self::Error)> where Self::Item: Send, Self::Error: Send, { future_with_timing(self).boxify() } } pub trait TimedNonSend: Future + Sized + 'static { fn timed_nonsend<C, R>(self, callback: C) -> BoxFutureNonSend<Self::Item, Self::Error> where C: FnOnce(FutureStats, Result<&Self::Item, &Self::Error>) -> R + 'static, R: IntoFuture<Item = (), Error = ()> + 'static, R::Future: 'static, { time_future(self, callback).boxify_nonsend() } fn collect_timing( self, ) -> BoxFutureNonSend<(FutureStats, Self::Item), (FutureStats, Self::Error)> { future_with_timing(self).boxify_nonsend() } } impl<T: Future + Send + 'static> Timed for T {} impl<T: Future + 'static> TimedNonSend for T {} pub trait TimedStreamTrait: Stream + Sized + Send + 'static { fn timed<C, R>(self, callback: C) -> BoxStream<Self::Item, Self::Error> where C: FnOnce(StreamStats, Result<(), &Self::Error>) -> R + Send + 'static, R: IntoFuture<Item = (), Error = ()> + Send + 'static, R::Future: 'static, <R as futures_old::IntoFuture>::Future: Send, Self::Item: Send, Self::Error: Send, { TimedStream::new(self, callback).boxify() } } impl<T: Stream + Send + 'static> TimedStreamTrait for T {} #[cfg(test)] mod tests { use super::*; use anyhow::Error; use futures_old::future::{err, ok}; use futures_old::stream::{iter_ok, once}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; #[test] fn test_timed_stream_simple() { let callback_called = Arc::new(AtomicBool::new(false)); const TEST_COUNT: usize
; move |stats, _| { assert_eq!(stats.count, TEST_COUNT); callback_called.store(true, Ordering::SeqCst); Ok(()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ())); assert!(callback_called.load(Ordering::SeqCst)); } #[test] fn test_timed_stream_error() { let callback_called = Arc::new(AtomicBool::new(false)); let err_happened = Arc::new(AtomicBool::new(false)); let err_reported = Arc::new(AtomicBool::new(false)); let s: BoxStream<(), _> = once(Err(Error::msg("err"))) .timed({ let callback_called = callback_called.clone(); let err_reported = err_reported.clone(); move |_, res| { callback_called.store(true, Ordering::SeqCst); err_reported.store(res.is_err(), Ordering::SeqCst); Ok(()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ()).map_err({ let err_happened = err_happened.clone(); move |_| err_happened.store(true, Ordering::SeqCst) })); assert!(callback_called.load(Ordering::SeqCst)); assert!(err_happened.load(Ordering::SeqCst)); assert!(err_reported.load(Ordering::SeqCst)); } #[test] fn test_timed_with_future() { let sleep_fut = tokio_timer::sleep(Duration::from_millis(300)); let future_called = Arc::new(AtomicBool::new(false)); let s: BoxStream<_, ()> = iter_ok([1, 2, 3].iter()) .timed({ let future_called = future_called.clone(); move |_, _| { sleep_fut .map(move |_| { future_called.store(true, Ordering::SeqCst); () }) .map_err(|_| ()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ())); assert!(future_called.load(Ordering::SeqCst)); } #[test] fn test_timed_with_err_and_future() { let sleep_fut = tokio_timer::sleep(Duration::from_millis(300)); let future_called = Arc::new(AtomicBool::new(false)); let err_happened = Arc::new(AtomicBool::new(false)); let err_reported = Arc::new(AtomicBool::new(false)); let s: BoxStream<(), _> = once(Err(Error::msg("err"))) .timed({ let err_reported = err_reported.clone(); let future_called = future_called.clone(); move |_, res| { err_reported.store(res.is_err(), Ordering::SeqCst); sleep_fut .map(move |_| { future_called.store(true, Ordering::SeqCst); () }) .map_err(|_| ()) } }) .boxify(); tokio_old::run(s.collect().map(|_| ()).map_err({ let err_happened = err_happened.clone(); move |_| { err_happened.store(true, Ordering::SeqCst); () } })); assert!(err_happened.load(Ordering::SeqCst)); assert!(err_reported.load(Ordering::SeqCst)); assert!(future_called.load(Ordering::SeqCst)); } #[test] fn test_collect_timings_with_future_ok() { let result_ok = Arc::new(AtomicBool::new(false)); let f: BoxFuture<u32, ()> = ok(123).boxify(); let f = Timed::collect_timing(f) .map({ let result_ok = result_ok.clone(); move |(_, r)| { result_ok.store(r == 123, Ordering::SeqCst); () } }) .map(|_| ()) .map_err(|_| ()) .boxify(); tokio_old::run(f); assert!(result_ok.load(Ordering::SeqCst)); } #[test] fn test_collect_timings_with_future_error() { let err_ok = Arc::new(AtomicBool::new(false)); let f: BoxFuture<(), u32> = err(123).boxify(); let f = Timed::collect_timing(f) .map_err({ let err_ok = err_ok.clone(); move |(_, r)| { err_ok.store(r == 123, Ordering::SeqCst); () } }) .map(|_| ()) .map_err(|_| ()) .boxify(); tokio_old::run(f); assert!(err_ok.load(Ordering::SeqCst)); } }
= 3; let s: BoxStream<_, ()> = iter_ok([0; TEST_COUNT].iter()) .timed({ let callback_called = callback_called.clone()
random
[ { "content": "/// A trait that provides the `timed` method to [futures_old::Stream] for gathering stats\n\npub trait TimedStreamExt: Stream + Sized {\n\n /// Combinator that returns a stream that will gather some statistics and\n\n /// pass them for inspection to the provided callback when the stream\n\n /// completes.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use futures_stats::TimedStreamExt;\n\n /// use futures::stream::{self, StreamExt};\n\n ///\n\n /// # futures::executor::block_on(async {\n\n /// let out = stream::iter([0u32; 3].iter())\n\n /// .timed(|stats| {\n\n /// async move {\n\n /// assert_eq!(stats.count, 3);\n\n /// }\n\n /// })\n\n /// .collect::<Vec<u32>>()\n\n /// .await;\n", "file_path": "third-party/rust/shed/futures_stats/src/futures03.rs", "rank": 4, "score": 418555.64824540645 }, { "content": "fn gen_container(mut container: ItemStruct) -> Result<TokenStream, Error> {\n\n let facet_crate = format_ident!(\"{}\", facet_crate_name());\n\n let members = ContainerMembers::extract(&mut container)?;\n\n let container_name = &container.ident;\n\n\n\n let attr_impls = gen_attr_impls(&facet_crate, container_name, &members);\n\n let buildable_impl = gen_buildable_impl(&facet_crate, &container_name, &members);\n\n let async_buildable_impl = gen_async_buildable_impl(&facet_crate, &container_name, &members);\n\n\n\n Ok(quote! {\n\n #container\n\n\n\n #( #attr_impls )*\n\n\n\n #buildable_impl\n\n\n\n #async_buildable_impl\n\n })\n\n}\n\n\n", "file_path": "third-party/rust/shed/facet/proc_macros/container_impl.rs", "rank": 5, "score": 415567.6211133282 }, { "content": "/// Optimised collect iterator into Vec, which might be a Result.\n\n///\n\n/// If we do a standard .collect() on the iterator it will never have a good size hint,\n\n/// as the lower bound will always be zero, so might reallocate several times.\n\n/// We know the Vec will either be thrown away, or exactly `len`, so aim if we do allocate,\n\n/// make sure it is at `len`. However, if the first element throws an error, we don't need\n\n/// to allocate at all, so special case that.\n\nfn collect_result<T, E>(mut it: impl ExactSizeIterator<Item = Result<T, E>>) -> Result<Vec<T>, E> {\n\n match it.next() {\n\n None => Ok(Vec::new()),\n\n Some(Err(e)) => Err(e),\n\n Some(Ok(x)) => {\n\n // +1 for the element we have already consumed\n\n let mut res = Vec::with_capacity(it.len() + 1);\n\n res.push(x);\n\n for x in it {\n\n res.push(x?);\n\n }\n\n Ok(res)\n\n }\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/gazebo/gazebo/src/ext/vec.rs", "rank": 6, "score": 409530.89336024324 }, { "content": "fn gen_factory(params: Params, mut factory_impl: ItemImpl) -> Result<TokenStream, Error> {\n\n let factory_ty = extract_type_ident(&factory_impl.self_ty)?;\n\n\n\n let facets = Facets::extract_from_impl(&params, &mut factory_impl)?;\n\n\n\n let factory_builder = gen_factory_builder(&params, &factory_ty, &facets)?;\n\n\n\n Ok(quote! {\n\n #factory_impl\n\n\n\n #factory_builder\n\n })\n\n}\n\n\n", "file_path": "third-party/rust/shed/facet/proc_macros/factory_impl.rs", "rank": 7, "score": 369862.3789364784 }, { "content": "/// This function must be called exactly once before accessing any of the stats,\n\n/// otherwise it will panic.\n\n/// If it won't be called a default stats manager factory will be assumed that\n\n/// does nothing. (Facebook only: the default will use fb303 counters)\n\npub fn register_stats_manager_factory(factory: impl StatsManagerFactory + Send + Sync + 'static) {\n\n let mut global_factory = STATS_MANAGER_FACTORY.write().expect(\"poisoned lock\");\n\n assert!(\n\n global_factory.is_none(),\n\n \"Called stats::stats_manager::register_stats_manager_factory more than once\"\n\n );\n\n global_factory.replace(Box::new(factory));\n\n}\n\n\n\n#[doc(hidden)]\n", "file_path": "third-party/rust/shed/stats/src/lib.rs", "rank": 8, "score": 364199.28925260855 }, { "content": "/// A trait that provides the `timed` method to [futures_old::Future] for gathering stats\n\npub trait TimedFutureExt: Future + Sized {\n\n /// Combinator that returns a future that will gather some statistics and\n\n /// return them together with the result of inner future.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use futures_stats::TimedFutureExt;\n\n ///\n\n /// # futures::executor::block_on(async {\n\n /// let (stats, value) = async { 123u32 }.timed().await;\n\n /// assert_eq!(value, 123);\n\n /// assert!(stats.poll_count > 0);\n\n /// # });\n\n /// ```\n\n fn timed(self) -> TimedFuture<Self> {\n\n TimedFuture::new(self)\n\n }\n\n}\n\n\n\nimpl<T: Future> TimedFutureExt for T {}\n\n\n", "file_path": "third-party/rust/shed/futures_stats/src/futures03.rs", "rank": 9, "score": 351694.00791722006 }, { "content": "fn gen_attribute(facet: Item) -> Result<TokenStream, Error> {\n\n let vis;\n\n let name;\n\n let facet_ty;\n\n\n\n match &facet {\n\n Item::Trait(facet) => {\n\n vis = &facet.vis;\n\n name = &facet.ident;\n\n facet_ty = quote!(dyn #name + ::std::marker::Send + ::std::marker::Sync + 'static);\n\n }\n\n Item::Struct(facet) => {\n\n vis = &facet.vis;\n\n name = &facet.ident;\n\n facet_ty = quote!(#name);\n\n }\n\n Item::Enum(facet) => {\n\n vis = &facet.vis;\n\n name = &facet.ident;\n\n facet_ty = quote!(#name);\n", "file_path": "third-party/rust/shed/facet/proc_macros/facet_impl.rs", "rank": 10, "score": 349834.47405432595 }, { "content": "/// A trait implemented by default for all Streams which extends the standard\n\n/// functionality.\n\npub trait FbStreamExt: Stream {\n\n /// Creates a stream wrapper and a future. The future will resolve into the wrapped stream when\n\n /// the stream wrapper returns None. It uses ConservativeReceiver to ensure that deadlocks are\n\n /// easily caught when one tries to poll on the receiver before consuming the stream.\n\n fn return_remainder(self) -> (ReturnRemainder<Self>, ConservativeReceiver<Self>)\n\n where\n\n Self: Sized,\n\n {\n\n ReturnRemainder::new(self)\n\n }\n\n\n\n /// Like [futures::stream::StreamExt::buffered] call,\n\n /// but can also limit number of futures in a buffer by \"weight\".\n\n fn buffered_weight_limited<'a, I, Fut>(\n\n self,\n\n params: BufferedParams,\n\n ) -> WeightLimitedBufferedStream<'a, Self, I>\n\n where\n\n Self: Sized + Send + 'a,\n\n Self: Stream<Item = (Fut, u64)>,\n", "file_path": "third-party/rust/shed/futures_ext/src/stream/mod.rs", "rank": 11, "score": 344670.92300170806 }, { "content": " pub trait HistogramStatic {\n\n fn add_value(&'static self, value: i64);\n\n fn add_repeated_value(&'static self, value: i64, nsamples: u32);\n\n }\n\n\n\n impl<T: Histogram> HistogramStatic for LocalKey<T> {\n\n fn add_value(&'static self, value: i64) {\n\n self.with(|s| s.add_value(value));\n\n }\n\n\n\n fn add_repeated_value(&'static self, value: i64, nsamples: u32) {\n\n self.with(|s| s.add_repeated_value(value, nsamples));\n\n }\n\n }\n\n}\n\npub use localkey_impls::*;\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 12, "score": 343422.53746539104 }, { "content": " pub trait CounterStatic {\n\n fn increment_value(&'static self, value: i64);\n\n }\n\n\n\n impl<T: Counter> CounterStatic for LocalKey<T> {\n\n fn increment_value(&'static self, value: i64) {\n\n self.with(|s| T::increment_value(s, value));\n\n }\n\n }\n\n\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 13, "score": 343422.53746539104 }, { "content": " pub trait TimeseriesStatic {\n\n fn add_value(&'static self, value: i64);\n\n fn add_value_aggregated(&'static self, value: i64, nsamples: u32);\n\n }\n\n\n\n impl<T: Timeseries> TimeseriesStatic for LocalKey<T> {\n\n fn add_value(&'static self, value: i64) {\n\n self.with(|s| s.add_value(value));\n\n }\n\n\n\n fn add_value_aggregated(&'static self, value: i64, nsamples: u32) {\n\n self.with(|s| s.add_value_aggregated(value, nsamples));\n\n }\n\n }\n\n\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 14, "score": 343422.5374653911 }, { "content": "/// A trait that provides the `timed` method to [futures_old::Future] for gathering stats\n\npub trait TimedTryFutureExt: TryFuture + Sized {\n\n /// Combinator that returns a future that will gather some statistics and\n\n /// return them together with the result of inner future.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use futures_stats::TimedTryFutureExt;\n\n ///\n\n /// # futures::executor::block_on(async {\n\n /// let (stats, value) = async { Result::<_, ()>::Ok(123u32) }.try_timed().await.unwrap();\n\n /// assert_eq!(value, 123);\n\n /// assert!(stats.poll_count > 0);\n\n /// # });\n\n /// ```\n\n fn try_timed(self) -> TimedTryFuture<Self> {\n\n TimedTryFuture::new(self)\n\n }\n\n}\n\n\n\nimpl<T: TryFuture> TimedTryFutureExt for T {}\n\n\n", "file_path": "third-party/rust/shed/futures_stats/src/futures03.rs", "rank": 15, "score": 341436.6057332689 }, { "content": "/// Trait that provides a function for making a decoding layer on top of Stream of Bytes\n\npub trait StreamLayeredExt: Stream<Item = Bytes> {\n\n /// Returnes a Stream that will yield decoded chunks of Bytes as they come\n\n /// using provided [Decoder]\n\n fn decode<Dec>(self, decoder: Dec) -> decode::LayeredDecode<Self, Dec>\n\n where\n\n Self: Sized,\n\n Dec: Decoder;\n\n}\n\n\n\nimpl<T> StreamLayeredExt for T\n\nwhere\n\n T: Stream<Item = Bytes>,\n\n{\n\n fn decode<Dec>(self, decoder: Dec) -> decode::LayeredDecode<Self, Dec>\n\n where\n\n Self: Sized,\n\n Dec: Decoder,\n\n {\n\n decode::decode(self, decoder)\n\n }\n", "file_path": "third-party/rust/shed/futures_01_ext/src/lib.rs", "rank": 16, "score": 339359.84106963547 }, { "content": "fn create_std_error<E: Debug>(err: E) -> std_io::Error {\n\n std_io::Error::new(std_io::ErrorKind::Other, format!(\"{:?}\", err))\n\n}\n\n\n\nimpl<E, S> std_io::Write for SinkToAsyncWrite<S>\n\nwhere\n\n S: Sink<SinkItem = Bytes, SinkError = E>,\n\n E: Debug,\n\n{\n\n fn write(&mut self, buf: &[u8]) -> ::std::io::Result<usize> {\n\n let bytes = Bytes::from(buf);\n\n match self.sink.start_send(bytes) {\n\n Ok(AsyncSink::Ready) => Ok(buf.len()),\n\n Ok(AsyncSink::NotReady(_)) => Err(std_io::Error::new(\n\n std_io::ErrorKind::WouldBlock,\n\n \"channel is busy\",\n\n )),\n\n Err(err) => Err(create_std_error(err)),\n\n }\n\n }\n", "file_path": "third-party/rust/shed/futures_01_ext/src/lib.rs", "rank": 17, "score": 337668.8995803582 }, { "content": "/// A trait implemented by default for all Streams which extends the standard\n\n/// functionality.\n\npub trait StreamExt: Stream {\n\n /// Fork elements in a stream out to two sinks, depending on a predicate\n\n ///\n\n /// If the predicate returns false, send the item to `out1`, otherwise to\n\n /// `out2`. `streamfork()` acts in a similar manner to `forward()` in that it\n\n /// keeps operating until the input stream ends, and then returns everything\n\n /// in the resulting Future.\n\n ///\n\n /// The predicate returns a `Result` so that it can fail (if there's a malformed\n\n /// input that can't be assigned to either output).\n\n fn streamfork<Out1, Out2, F, E>(\n\n self,\n\n out1: Out1,\n\n out2: Out2,\n\n pred: F,\n\n ) -> streamfork::Forker<Self, Out1, Out2, F, E>\n\n where\n\n Self: Sized,\n\n Out1: Sink<SinkItem = Self::Item>,\n\n Out2: Sink<SinkItem = Self::Item, SinkError = Out1::SinkError>,\n", "file_path": "third-party/rust/shed/futures_01_ext/src/lib.rs", "rank": 18, "score": 331182.11266238213 }, { "content": "/// Given an input stream, split its error out to a separate Future, and returning that\n\n/// error Future and an infallable Stream. There are two outcomes:\n\n/// 1. The stream has no error - the error future never resolves\n\n/// 2. The stream has an error - the output stream terminates, and the error future\n\n/// resolves to the error\n\npub fn split_err<S: Stream>(\n\n s: S,\n\n) -> (\n\n impl Stream<Item = S::Item, Error = !>,\n\n impl Future<Item = !, Error = S::Error>,\n\n) {\n\n let (tx, rx) = oneshot::channel();\n\n\n\n (\n\n ErrSplitter {\n\n inner: s,\n\n err_tx: Some(tx),\n\n },\n\n ErrFuture { err_rx: Some(rx) },\n\n )\n\n}\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/split_err.rs", "rank": 20, "score": 326444.6850059076 }, { "content": "/// \"Context\" support for streams where the error is an implementation of anyhow::Error.\n\npub trait StreamFailureErrorExt: Stream + Sized {\n\n /// Add context to the error returned by this stream\n\n fn context<D>(self, context: D) -> ContextErrorStream<Self, D>\n\n where\n\n D: Display + Clone + Send + Sync + 'static;\n\n\n\n /// Add context created by provided function to the error returned by this stream\n\n fn with_context<D, F>(self, f: F) -> WithContextErrorStream<Self, F>\n\n where\n\n D: Display + Clone + Send + Sync + 'static,\n\n F: FnMut() -> D;\n\n}\n\n\n\nimpl<S> StreamFailureErrorExt for S\n\nwhere\n\n S: Stream<Error = Error> + Sized,\n\n{\n\n fn context<D>(self, displayable: D) -> ContextErrorStream<Self, D>\n\n where\n\n D: Display + Clone + Send + Sync + 'static,\n", "file_path": "third-party/rust/shed/failure_ext/src/context_streams.rs", "rank": 21, "score": 325932.86616937723 }, { "content": "/// Creates a new future that supports polling another future behind [`tokio::sync::Mutex`].\n\n///\n\n/// When some future-like struct is behind a lock, polling with the mutex locked easily creates\n\n/// deadlock since no one else will be able to make progress on the lock-protected struct.\n\n///\n\n/// Note the closure should return a `Poll<Result<(), E>>` instead of `Poll<()>`. This allows the\n\n/// closure to surface errors happened in polling.\n\n///\n\n/// # Examples\n\n///\n\n/// ```\n\n/// # #[tokio::main]\n\n/// # async fn main() {\n\n/// use std::task::Poll;\n\n/// use tokio::sync::Mutex;\n\n/// use fbthrift_util::poll_with_lock;\n\n///\n\n/// struct Foobar(i32);\n\n/// let lock = Mutex::new(Foobar(132));\n\n///\n\n/// let locked_future = poll_with_lock(\n\n/// &lock,\n\n/// |_locked, _ctx| Poll::Ready(Result::<(), ()>::Ok(()))\n\n/// );\n\n///\n\n/// assert_eq!(locked_future.await.unwrap().0, 132);\n\n/// # }\n\n/// ```\n\npub fn poll_with_lock<'a, T, F, E>(lock: &'a Mutex<T>, f: F) -> PollWithLock<'a, T, F, E>\n\nwhere\n\n F: FnMut(&mut MutexGuard<'a, T>, &mut Context<'_>) -> Poll<Result<(), E>> + Unpin,\n\n{\n\n PollWithLock { lock, f }\n\n}\n\n\n\nimpl<'a, T, F, E> Future for PollWithLock<'a, T, F, E>\n\nwhere\n\n F: FnMut(&mut MutexGuard<'a, T>, &mut Context<'_>) -> Poll<Result<(), E>> + Unpin,\n\n{\n\n type Output = Result<MutexGuard<'a, T>, E>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Self::Output> {\n\n let mut fut = Box::pin(self.lock.lock());\n\n match fut.as_mut().poll(ctx) {\n\n Poll::Ready(mut locked) => match (&mut self.f)(&mut locked, ctx) {\n\n Poll::Ready(Ok(())) => Poll::Ready(Ok(locked)),\n\n Poll::Ready(Err(e)) => Poll::Ready(Err(e)),\n\n Poll::Pending => Poll::Pending,\n\n },\n\n Poll::Pending => Poll::Pending,\n\n }\n\n }\n\n}\n", "file_path": "third-party/rust/shed/fbthrift_ext/util/lib.rs", "rank": 22, "score": 322060.0369296026 }, { "content": "fn extract_type_ident(ty: &Type) -> Result<Ident, Error> {\n\n if let Type::Path(type_path) = ty {\n\n if let Some(ident) = type_path.path.get_ident() {\n\n return Ok(ident.clone());\n\n }\n\n }\n\n Err(Error::new(\n\n ty.span(),\n\n \"facet::factory impl must be for a local concrete type\",\n\n ))\n\n}\n\n\n", "file_path": "third-party/rust/shed/facet/proc_macros/factory_impl.rs", "rank": 23, "score": 321714.3825590168 }, { "content": "pub fn tokio_test<F>(f: F) -> <F as Future>::Output\n\nwhere\n\n F: Future,\n\n{\n\n tokio::runtime::Builder::new()\n\n .basic_scheduler()\n\n .enable_all()\n\n .build()\n\n .unwrap()\n\n .block_on(f)\n\n}\n\n\n", "file_path": "third-party/rust/shed/fbinit/fbinit-tokio-02/lib.rs", "rank": 24, "score": 319170.31468623306 }, { "content": "pub fn tokio_test<F>(f: F) -> <F as Future>::Output\n\nwhere\n\n F: Future,\n\n{\n\n tokio::runtime::Builder::new_current_thread()\n\n .enable_all()\n\n .build()\n\n .unwrap()\n\n .block_on(f)\n\n}\n\n\n", "file_path": "third-party/rust/shed/fbinit/fbinit-tokio/lib.rs", "rank": 25, "score": 319170.31468623306 }, { "content": "#[inline]\n\npub fn send_discard<T, E>(\n\n sender: mpsc::Sender<T>,\n\n value: T,\n\n) -> impl Future<Item = (), Error = E> + Send\n\nwhere\n\n T: Send,\n\n E: Send,\n\n{\n\n sender.send(value).then(|_| Ok(()))\n\n}\n\n\n\n/// Replacement for BoxFuture, deprecated in upstream futures-rs.\n\npub type BoxFuture<T, E> = Box<dyn Future<Item = T, Error = E> + Send>;\n\n/// Replacement for BoxFutureNonSend, deprecated in upstream futures-rs.\n\npub type BoxFutureNonSend<T, E> = Box<dyn Future<Item = T, Error = E>>;\n\n/// Replacement for BoxStream, deprecated in upstream futures-rs.\n\npub type BoxStream<T, E> = Box<dyn Stream<Item = T, Error = E> + Send>;\n\n/// Replacement for BoxStreamNonSend, deprecated in upstream futures-rs.\n\npub type BoxStreamNonSend<T, E> = Box<dyn Stream<Item = T, Error = E>>;\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/lib.rs", "rank": 26, "score": 316732.8947054486 }, { "content": "/// Create a default drain that outputs to stderr and inlines all KV values except for supported\n\n/// error_chain errors.\n\n/// # Example:\n\n/// ```\n\n/// use slog::{info, o, Logger};\n\n/// use slog_glog_fmt::default_drain;\n\n///\n\n/// fn main() {\n\n/// let logger = Logger::root(default_drain(), o!());\n\n/// info!(logger, \"Hello world!\");\n\n/// }\n\n/// ```\n\npub fn default_drain() -> impl Drain<Ok = (), Err = Never> {\n\n let decorator = TermDecorator::new().build();\n\n let drain = GlogFormat::new(decorator, ErrorCategorizer).fuse();\n\n sync::Mutex::new(drain).fuse()\n\n}\n\n\n", "file_path": "third-party/rust/shed/slog_glog_fmt/src/glog_format.rs", "rank": 27, "score": 316578.9577700943 }, { "content": "/// Fork a Stream into two\n\n///\n\n/// Returns a Future for a process that consumes items from a Stream and\n\n/// forwards them to two sinks depending on a predicate. If the predicate\n\n/// returns false, send the value to out1, otherwise out2.\n\npub fn streamfork<In, Out1, Out2, F, E>(\n\n inp: In,\n\n out1: Out1,\n\n out2: Out2,\n\n pred: F,\n\n) -> Forker<In, Out1, Out2, F, E>\n\nwhere\n\n In: Stream,\n\n Out1: Sink<SinkItem = In::Item>,\n\n Out2: Sink<SinkItem = In::Item, SinkError = Out1::SinkError>,\n\n F: FnMut(&In::Item) -> Result<bool, E>,\n\n E: From<In::Error> + From<Out1::SinkError> + From<Out2::SinkError>,\n\n{\n\n Forker {\n\n inp: Some(inp.fuse()),\n\n out1: Out::new(out1),\n\n out2: Out::new(out2),\n\n pred,\n\n finished: None,\n\n }\n", "file_path": "third-party/rust/shed/futures_01_ext/src/streamfork.rs", "rank": 28, "score": 312299.309261651 }, { "content": "/// Descend into all the nested type values within a type, or return None if you don't know how\n\nfn descend_type(ty: &mut Type, op: impl Fn(&mut Type) -> Option<()>) -> Option<()> {\n\n match ty {\n\n Type::Array(x) => op(&mut x.elem),\n\n Type::Group(x) => op(&mut x.elem),\n\n Type::Never(_) => Some(()),\n\n Type::Paren(x) => op(&mut x.elem),\n\n Type::Path(x) => {\n\n if let Some(qself) = &mut x.qself {\n\n op(&mut qself.ty)?;\n\n }\n\n for p in x.path.segments.iter_mut() {\n\n match &mut p.arguments {\n\n PathArguments::None => {}\n\n PathArguments::AngleBracketed(x) => {\n\n x.args.iter_mut().try_for_each(|x| match x {\n\n GenericArgument::Type(x) => op(x),\n\n _ => Some(()),\n\n })?\n\n }\n\n PathArguments::Parenthesized(x) => {\n", "file_path": "third-party/rust/gazebo/gazebo_derive/src/coerce.rs", "rank": 29, "score": 310515.49229592626 }, { "content": "#[doc(hidden)]\n\npub trait FacetRef<T: ?Sized + Send + Sync + 'static> {\n\n fn facet_ref(&self) -> &T;\n\n}\n\n\n\nimpl<T, C> FacetRef<T> for Arc<C>\n\nwhere\n\n T: ?Sized + Send + Sync + 'static,\n\n C: FacetRef<T>,\n\n{\n\n #[inline]\n\n fn facet_ref(&self) -> &T {\n\n <C as FacetRef<T>>::facet_ref(self)\n\n }\n\n}\n\n\n\nimpl<T, C> FacetRef<T> for &Arc<C>\n\nwhere\n\n T: ?Sized + Send + Sync + 'static,\n\n C: FacetRef<T>,\n\n{\n\n #[inline]\n\n fn facet_ref(&self) -> &T {\n\n <C as FacetRef<T>>::facet_ref(*self)\n\n }\n\n}\n\n\n\n// Trait implemented by containers that can provide an arc to facets of\n\n// type T.\n", "file_path": "third-party/rust/shed/facet/src/lib.rs", "rank": 30, "score": 308554.91656894056 }, { "content": "#[doc(hidden)]\n\npub trait FacetArc<T: ?Sized + Send + Sync + 'static> {\n\n fn facet_arc(&self) -> Arc<T>;\n\n}\n\n\n\nimpl<T, C> FacetArc<T> for Arc<C>\n\nwhere\n\n T: ?Sized + Send + Sync + 'static,\n\n C: FacetArc<T>,\n\n{\n\n #[inline]\n\n fn facet_arc(&self) -> Arc<T> {\n\n <C as FacetArc<T>>::facet_arc(self)\n\n }\n\n}\n\n\n\nimpl<T, C> FacetArc<T> for &Arc<C>\n\nwhere\n\n T: ?Sized + Send + Sync + 'static,\n\n C: FacetArc<T>,\n\n{\n\n #[inline]\n\n fn facet_arc(&self) -> Arc<T> {\n\n <C as FacetArc<T>>::facet_arc(*self)\n\n }\n\n}\n", "file_path": "third-party/rust/shed/facet/src/lib.rs", "rank": 31, "score": 308554.91656894056 }, { "content": "#[test]\n\nfn test_bounded_traversal_stream() -> Result<()> {\n\n // tree\n\n // 0\n\n // / \\\n\n // 1 2\n\n // / / \\\n\n // 5 3 4\n\n let tree = Tree::new(\n\n 0,\n\n vec![\n\n Tree::new(1, vec![Tree::leaf(5)]),\n\n Tree::new(2, vec![Tree::leaf(3), Tree::leaf(4)]),\n\n ],\n\n );\n\n\n\n let tick = Tick::new();\n\n let log: StateLog<BTreeSet<usize>> = StateLog::new();\n\n let reference: StateLog<BTreeSet<usize>> = StateLog::new();\n\n let mut rt = Runtime::new()?;\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 32, "score": 307746.42524858954 }, { "content": "fn diagnostic_display(diagnostic: &Diagnostic, f: &mut Formatter<'_>) -> fmt::Result {\n\n CallStackFmt(&diagnostic.call_stack).fmt(f)?;\n\n let annotation_label = format!(\"{:#}\", diagnostic.message);\n\n // I set color to false here to make the comparison easier with tests (coloring\n\n // adds in pretty strange unicode chars).\n\n let display_list = get_display_list_for_diagnostic(&annotation_label, diagnostic, false);\n\n writeln!(f, \"{}\", display_list)\n\n}\n\n\n", "file_path": "third-party/rust/starlark-rust/starlark/src/errors/mod.rs", "rank": 33, "score": 305549.3779207528 }, { "content": "/// A trait implemented by default for all TryStreams which extends the standard\n\n/// functionality.\n\npub trait FbTryStreamExt: TryStream {\n\n /// Like [futures::stream::StreamExt::buffered] call, but for `TryStream` and\n\n /// can also limit number of futures in a buffer by \"weight\".\n\n fn try_buffered_weight_limited<'a, I, Fut, E>(\n\n self,\n\n params: BufferedParams,\n\n ) -> WeightLimitedBufferedTryStream<'a, Self, I, E>\n\n where\n\n Self: Sized + Send + 'a,\n\n Self: TryStream<Ok = (Fut, u64), Error = E>,\n\n Fut: TryFuture<Ok = I, Error = E>,\n\n {\n\n WeightLimitedBufferedTryStream::new(params, self)\n\n }\n\n\n\n /// Convert a Stream of Result<Result<I, E1>, E2> into a Stream of Result<I, E1>, assuming E2\n\n /// can convert into E1.\n\n #[allow(clippy::type_complexity)]\n\n fn flatten_err<I, E1, E2>(\n\n self,\n", "file_path": "third-party/rust/shed/futures_ext/src/stream/mod.rs", "rank": 34, "score": 304406.62496227166 }, { "content": "fn build_set_data(start: usize, size: usize) -> Vec<String> {\n\n let mut index = 0;\n\n let mut data = Vec::with_capacity(size);\n\n for n in start.. {\n\n for word1 in WORDS.iter() {\n\n for word2 in WORDS.iter() {\n\n data.push(format!(\"{}.{}.{}\", word1, n, word2));\n\n index += 1;\n\n if index >= size {\n\n return data;\n\n }\n\n }\n\n }\n\n }\n\n unreachable!()\n\n}\n\n\n\nmacro_rules! make_set_bench {\n\n ($name:ident, $set:ident, [ $(,)? ]) => {};\n\n ($name:ident, $set:ident, [ $(,)? $count:literal $( $counts:tt )* ]) => {\n", "file_path": "third-party/rust/shed/sorted_vector_map/benches/set.rs", "rank": 35, "score": 304117.9349769141 }, { "content": "#[auto_impl(Box)]\n\npub trait Counter {\n\n /// Increments the counter by the given amount.\n\n fn increment_value(&self, value: i64);\n\n}\n\n\n\n/// Timeseries is a type of stat that can aggregate data send to it into\n\n/// predefined intervals of time. Example aggregations are average, sum or rate.\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 36, "score": 298618.6562370915 }, { "content": "#[auto_impl(Box)]\n\npub trait Timeseries {\n\n /// Adds value to the timeseries. It is being aggregated based on ExportType\n\n fn add_value(&self, value: i64);\n\n\n\n /// You might want to call this method when you have a very hot counter to avoid some\n\n /// congestions on it.\n\n /// Value is the sum of values of the samples and nsamples is the number of samples.\n\n /// Please notice that difference in the value semantic compared to\n\n /// `Histogram::add_repeated_value`.\n\n fn add_value_aggregated(&self, value: i64, nsamples: u32);\n\n}\n\n\n\n/// Histogram is a type of stat that can aggregate data send to it into\n\n/// predefined buckets. Example aggregations are average, sum or P50 (percentile).\n\n/// The aggregation should also happen on an interval basis, since its rarely\n\n/// useful to see aggregated all-time stats of a service running for many days.\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 37, "score": 298618.6562370915 }, { "content": "#[auto_impl(Box)]\n\npub trait Histogram {\n\n /// Adds value to the histogram. It is being aggregated based on ExportType\n\n fn add_value(&self, value: i64);\n\n\n\n /// You might want to call this method when you have a very hot counter to avoid some\n\n /// congestions on it.\n\n /// Value is the value of a single samples and nsamples is the number of samples.\n\n /// Please notice that difference in the value semantic compared to\n\n /// `Timeseries::add_value_aggregated`.\n\n fn add_repeated_value(&self, value: i64, nsamples: u32);\n\n}\n\n\n\nmod localkey_impls {\n\n use super::*;\n\n use std::thread::LocalKey;\n\n\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 38, "score": 298618.6562370915 }, { "content": "/// Upon the first call to this function it will return a future that results in\n\n/// periodically calling aggregation of stats.\n\n/// On subsequent calls it will return `Error::StatsScheduled` that contain the\n\n/// future, so that the caller might still use it, but knows that it is not the\n\n/// first this function was called.\n\n///\n\n/// # Examples\n\n///\n\n/// ```no_run\n\n/// use stats::schedule_stats_aggregation_preview;\n\n/// use tokio::spawn;\n\n///\n\n/// let s = schedule_stats_aggregation_preview().unwrap();\n\n/// spawn(s);\n\n/// ```\n\npub fn schedule_stats_aggregation_preview() -> Result<SchedulerPreview, StatsScheduledErrorPreview>\n\n{\n\n let stream = tokio_shim::time::interval_stream(Duration::from_secs(1));\n\n let scheduler = schedule_stats_on_stream_preview(stream);\n\n\n\n if STATS_SCHEDULED.swap(true, atomic::Ordering::Relaxed) {\n\n Err(StatsScheduledErrorPreview(scheduler))\n\n } else {\n\n Ok(scheduler)\n\n }\n\n}\n\n\n\n/// Schedules aggregation of stats on the provided stream. This method should not\n\n/// be used directly, it is here for testing purposes\n", "file_path": "third-party/rust/shed/stats/src/thread_local_aggregator.rs", "rank": 39, "score": 298129.49413787195 }, { "content": "/// \"Context\" support for futures where the error is anyhow::Error.\n\npub trait FutureFailureErrorExt: Future + Sized {\n\n /// Add context to the error returned by this future\n\n fn context<D>(self, context: D) -> ContextErrorFut<Self, D>\n\n where\n\n D: Display + Send + Sync + 'static;\n\n\n\n /// Add context created by provided function to the error returned by this future\n\n fn with_context<D, F>(self, f: F) -> WithContextErrorFut<Self, F>\n\n where\n\n D: Display + Send + Sync + 'static,\n\n F: FnOnce() -> D;\n\n}\n\n\n\nimpl<F> FutureFailureErrorExt for F\n\nwhere\n\n F: Future<Error = Error> + Sized,\n\n{\n\n fn context<D>(self, displayable: D) -> ContextErrorFut<Self, D>\n\n where\n\n D: Display + Send + Sync + 'static,\n", "file_path": "third-party/rust/shed/failure_ext/src/context_futures.rs", "rank": 40, "score": 297467.6767692941 }, { "content": "fn extract_delegate_facets(attr: &Attribute) -> Result<Vec<Type>, Error> {\n\n let mut facets = Vec::new();\n\n let args: Punctuated<Type, Token![,]> = attr.parse_args_with(Punctuated::parse_terminated)?;\n\n for mut arg in args {\n\n if let Type::TraitObject(obj) = &mut arg {\n\n obj.bounds.push(syn::parse2(quote!(::std::marker::Send))?);\n\n obj.bounds.push(syn::parse2(quote!(::std::marker::Sync))?);\n\n obj.bounds.push(syn::parse2(quote!('static))?);\n\n }\n\n facets.push(arg);\n\n }\n\n Ok(facets)\n\n}\n", "file_path": "third-party/rust/shed/facet/proc_macros/container_impl.rs", "rank": 41, "score": 295261.27016350016 }, { "content": "#[auto_impl(Box)]\n\npub trait SingletonCounter {\n\n /// Sets the value of the counter\n\n fn set_value(&self, fb: FacebookInit, value: i64);\n\n\n\n /// Increment the value of the counter\n\n fn increment_value(&self, fb: FacebookInit, value: i64);\n\n\n\n /// Gets the current value of the counter\n\n fn get_value(&self, fb: FacebookInit) -> Option<i64>;\n\n}\n\n\n\n/// Counter is the simplest type of aggregated stat, it behaves as a single number that can be\n\n/// incremented.\n", "file_path": "third-party/rust/shed/stats/traits/stat_types.rs", "rank": 42, "score": 294688.4227193577 }, { "content": "/// Type alias for easier definition of TryShared\n\ntype NewSharedError = fn(Error) -> SharedError;\n\n\n\npub(crate) fn try_shared<Fut>(fut: Fut) -> TryShared<Fut>\n\nwhere\n\n <Fut as TryFuture>::Ok: Clone,\n\n Fut: TryFuture<Error = Error> + Sized,\n\n{\n\n fut.map_err(IntoSharedError::<SharedError>::shared_error as NewSharedError)\n\n .shared()\n\n}\n", "file_path": "third-party/rust/shed/futures_ext/src/future/try_shared.rs", "rank": 43, "score": 292899.38385206764 }, { "content": "/// A trait implemented by default for all Futures which extends the standard\n\n/// functionality.\n\npub trait FutureExt: Future + Sized {\n\n /// Map a `Future` to have `Item=()` and `Error=()`. This is\n\n /// useful when a future is being used to drive a computation\n\n /// but the actual results aren't interesting (such as when used\n\n /// with `Handle::spawn()`).\n\n fn discard(self) -> Discard<Self> {\n\n Discard(self)\n\n }\n\n\n\n /// Create a `Send`able boxed version of this `Future`.\n\n #[inline]\n\n fn boxify(self) -> BoxFuture<Self::Item, Self::Error>\n\n where\n\n Self: 'static + Send,\n\n {\n\n // TODO: (rain1) T21801845 rename to 'boxed' once gone from upstream.\n\n Box::new(self)\n\n }\n\n\n\n /// Create a non-`Send`able boxed version of this `Future`.\n", "file_path": "third-party/rust/shed/futures_01_ext/src/lib.rs", "rank": 44, "score": 292066.87110492587 }, { "content": "#[inline]\n\nfn next_future<I>(elems: &mut I) -> Option<<I::Item as IntoFuture>::Future>\n\nwhere\n\n I: Iterator,\n\n I::Item: IntoFuture,\n\n{\n\n elems.next().map(IntoFuture::into_future)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use std::result;\n\n\n\n use futures::sync::mpsc;\n\n use futures::task;\n\n use futures::{Future, Sink, Stream};\n\n\n\n use super::*;\n\n\n\n #[test]\n\n fn test_basic() {\n", "file_path": "third-party/rust/shed/futures_01_ext/src/futures_ordered.rs", "rank": 45, "score": 291741.81775816815 }, { "content": "#[must_use = \"futures do nothing unless you `.await` or poll them\"]\n\nstruct ErrFuture<E> {\n\n err_rx: Option<oneshot::Receiver<E>>,\n\n}\n\n\n\nimpl<E> Future for ErrFuture<E> {\n\n type Item = !;\n\n type Error = E;\n\n\n\n fn poll(&mut self) -> Poll<!, E> {\n\n match self.err_rx.take() {\n\n None => Ok(Async::NotReady),\n\n Some(mut rx) => match rx.poll() {\n\n Ok(Async::Ready(err)) => Err(err),\n\n Ok(Async::NotReady) => {\n\n self.err_rx = Some(rx);\n\n Ok(Async::NotReady)\n\n }\n\n Err(_) => Ok(Async::NotReady),\n\n },\n\n }\n", "file_path": "third-party/rust/shed/futures_01_ext/src/split_err.rs", "rank": 46, "score": 291445.2223877263 }, { "content": "/// Convert a list of streams into a `Stream` of results from the streams.\n\n///\n\n/// This essentially takes a list of streams (e.g. a vector, an iterator, etc.)\n\n/// and bundles them together into a single stream.\n\n/// The stream will yield items as they become available on the underlying\n\n/// streams internally, in the order they become available.\n\n///\n\n/// Note that the returned set can also be used to dynamically push more\n\n/// futures into the set as they become available.\n\npub fn select_all<I>(streams: I) -> SelectAll<I::Item>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: Stream,\n\n{\n\n let mut set = SelectAll::default();\n\n\n\n for stream in streams {\n\n set.push(stream);\n\n }\n\n\n\n set\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use futures::stream::iter_ok;\n\n\n\n #[test]\n\n fn select_all_many_streams() {\n\n let mut rt = tokio::runtime::Runtime::new().unwrap();\n\n let streams: Vec<_> = (1..5).map(|i| iter_ok::<_, ()>(0..i)).collect();\n\n let result = rt.block_on(select_all(streams).collect()).unwrap();\n\n assert_eq!(result.len(), 10);\n\n }\n\n}\n", "file_path": "third-party/rust/shed/futures_01_ext/src/select_all.rs", "rank": 47, "score": 290486.10092553264 }, { "content": "/// `bounded_traversal` traverses implicit asynchronous tree specified by `init`\n\n/// and `unfold` arguments, and it also does backward pass with `fold` operation.\n\n/// All `unfold` and `fold` operations are executed in parallel if they do not\n\n/// depend on each other (not related by ancestor-descendant relation in implicit tree)\n\n/// with amount of concurrency constrained by `scheduled_max`.\n\n///\n\n/// ## `init: In`\n\n/// Is the root of the implicit tree to be traversed\n\n///\n\n/// ## `unfold: FnMut(In) -> impl IntoFuture<Item = (OutCtx, impl IntoIterator<Item = In>)>`\n\n/// Asynchronous function which given input value produces list of its children. And context\n\n/// associated with current node. If this list is empty, it is a leaf of the tree, and `fold`\n\n/// will be run on this node.\n\n///\n\n/// ## `fold: FnMut(OutCtx, impl Iterator<Out>) -> impl IntoFuture<Item=Out>`\n\n/// Aynchronous function which given node context and output of `fold` for its chidlren\n\n/// should produce new output value.\n\n///\n\n/// ## return value `impl Future<Item = Out>`\n\n/// Result of running fold operation on the root of the tree.\n\n///\n\npub fn bounded_traversal<In, Ins, Out, OutCtx, Unfold, UFut, Fold, FFut>(\n\n scheduled_max: usize,\n\n init: In,\n\n unfold: Unfold,\n\n fold: Fold,\n\n) -> impl Future<Item = Out, Error = UFut::Error>\n\nwhere\n\n Unfold: FnMut(In) -> UFut,\n\n UFut: IntoFuture<Item = (OutCtx, Ins)>,\n\n Ins: IntoIterator<Item = In>,\n\n Fold: FnMut(OutCtx, Iter<Out>) -> FFut,\n\n FFut: IntoFuture<Item = Out, Error = UFut::Error>,\n\n{\n\n BoundedTraversal::new(scheduled_max, init, unfold, fold)\n\n}\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tree.rs", "rank": 48, "score": 288163.28202290216 }, { "content": "pub fn evaluate(result: &mut Child) -> bool {\n\n return shell::evaluate(result);\n\n}\n", "file_path": "tools/testinfra/runner/src/pyunit.rs", "rank": 49, "score": 286126.49396405986 }, { "content": "pub fn evaluate(result: &mut Child) -> bool {\n\n return shell::evaluate(result);\n\n}\n", "file_path": "tools/testinfra/runner/src/rust.rs", "rank": 50, "score": 286126.49396405986 }, { "content": "/// Validates a spec into a (possibly empty) set of runnable tests.\n\npub fn validate(spec: TestSpec) -> Result<Vec<Test>> {\n\n for &exclude in EXCLUDED_LABELS {\n\n if spec.labels.contains(exclude) {\n\n return Ok(vec![]);\n\n }\n\n }\n\n\n\n // we'll collect all validation errors we can find\n\n let mut error = String::new();\n\n\n\n if spec.command.len() < 1 {\n\n let msg = format!(\" Error: Empty command line\\n\");\n\n error.push_str(&msg);\n\n }\n\n\n\n // if requirements were specified, we better verify they're there\n\n for req in spec.required_paths.clone().unwrap_or(vec![]) {\n\n if !req.exists() {\n\n let msg = format!(\" Error: Missing requirement {}\\n\", req.display());\n\n error.push_str(&msg);\n", "file_path": "tools/testinfra/runner/src/buck_test.rs", "rank": 51, "score": 285845.5872384303 }, { "content": "/// \"Context\" support for streams where the error is an implementation of std::error::Error.\n\npub trait StreamFailureExt: Stream + Sized {\n\n /// Add context to the error returned by this stream\n\n fn context<D>(self, context: D) -> ContextStream<Self, D>\n\n where\n\n D: Display + Clone + Send + Sync + 'static;\n\n\n\n /// Add context created by provided function to the error returned by this stream\n\n fn with_context<D, F>(self, f: F) -> WithContextStream<Self, F>\n\n where\n\n D: Display + Clone + Send + Sync + 'static,\n\n F: FnMut() -> D;\n\n}\n\n\n\nimpl<S> StreamFailureExt for S\n\nwhere\n\n S: Stream + Sized,\n\n S::Error: StdError + Send + Sync + 'static,\n\n{\n\n fn context<D>(self, displayable: D) -> ContextStream<Self, D>\n\n where\n", "file_path": "third-party/rust/shed/failure_ext/src/context_streams.rs", "rank": 52, "score": 285321.9004290624 }, { "content": "/// A trait representing Starlark values which are simple - they\n\n/// aren't mutable and can't contain other Starlark values.\n\n///\n\n/// Let's define a simple object, where `+x` makes the string uppercase:\n\n///\n\n/// ```\n\n/// use starlark::values::{Heap, StarlarkValue, Value};\n\n/// use starlark::{starlark_simple_value, starlark_type};\n\n///\n\n/// #[derive(Debug)]\n\n/// struct MyObject(String);\n\n/// starlark_simple_value!(MyObject);\n\n/// impl<'v> StarlarkValue<'v> for MyObject {\n\n/// starlark_type!(\"my_object\");\n\n///\n\n/// // We can choose to implement whichever methods we want.\n\n/// // All other operations will result in runtime errors.\n\n/// fn plus(&self, heap: &'v Heap) -> anyhow::Result<Value<'v>> {\n\n/// Ok(heap.alloc(MyObject(self.0.to_uppercase())))\n\n/// }\n\n/// }\n\n/// ```\n\n///\n\n/// The [`starlark_simple_value!`] macro defines instances of [`AnyLifetime`],\n\n/// [`AllocValue`](crate::values::AllocValue),\n\n/// [`AllocFrozenValue`](crate::values::AllocFrozenValue), [`SimpleValue`] and\n\n/// [`FromValue`](crate::values::FromValue). It also defines a method:\n\n///\n\n/// ```\n\n/// # use crate::starlark::values::*;\n\n/// # struct MyObject;\n\n/// impl MyObject {\n\n/// pub fn from_value<'v>(x: Value<'v>) -> Option<ARef<'v, MyObject>> {\n\n/// # unimplemented!(\n\n/// # r#\"\n\n/// ...\n\n/// # \"#);\n\n/// }\n\n/// }\n\n/// ```\n\n///\n\n/// All users defining [`SimpleValue`] should use this macro.\n\npub trait SimpleValue: StarlarkValue<'static> + Send + Sync {}\n\n\n", "file_path": "third-party/rust/starlark-rust/starlark/src/values/traits.rs", "rank": 53, "score": 279358.81109009736 }, { "content": "// Tree for test purposes\n\nstruct Tree {\n\n id: usize,\n\n children: Vec<Tree>,\n\n}\n\n\n\nimpl Tree {\n\n fn new(id: usize, children: Vec<Tree>) -> Self {\n\n Self { id, children }\n\n }\n\n\n\n fn leaf(id: usize) -> Self {\n\n Self::new(id, vec![])\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 54, "score": 277441.61411693215 }, { "content": "pub fn tokio_main<F>(f: F) -> <F as Future>::Output\n\nwhere\n\n F: Future,\n\n{\n\n tokio::runtime::Builder::new_multi_thread()\n\n .enable_all()\n\n .build()\n\n .unwrap()\n\n .block_on(f)\n\n}\n", "file_path": "third-party/rust/shed/fbinit/fbinit-tokio/lib.rs", "rank": 55, "score": 276825.55857702286 }, { "content": "pub fn tokio_main<F>(f: F) -> <F as Future>::Output\n\nwhere\n\n F: Future,\n\n{\n\n tokio::runtime::Builder::new()\n\n .threaded_scheduler()\n\n .enable_all()\n\n .build()\n\n .unwrap()\n\n .block_on(f)\n\n}\n", "file_path": "third-party/rust/shed/fbinit/fbinit-tokio-02/lib.rs", "rank": 56, "score": 276825.55857702286 }, { "content": "/// Convert error implementing [failure::Fail] to [anyhow::Error]\n\npub fn convert(fail: impl Fail) -> Error {\n\n convert_ref(&fail)\n\n}\n\n\n", "file_path": "third-party/rust/shed/failure_ext/src/convert.rs", "rank": 57, "score": 274313.2499759133 }, { "content": "#[test]\n\nfn test() -> Result<()> {\n\n let mut cmd = get_command!(\"test\");\n\n cmd.assert()\n\n .failure()\n\n .code(101)\n\n .stdout(\"I'm on an adventure!\\n\")\n\n .stderr(predicates::str::starts_with(\n\n \"PANIC: I paniced! Everything's awful! 1234\\n\",\n\n ));\n\n Ok(())\n\n}\n\n\n", "file_path": "third-party/rust/shed/panichandler/test/testrunner.rs", "rank": 58, "score": 271876.17447067087 }, { "content": "/// A trait implemented by default for all Futures which extends the standard\n\n/// functionality.\n\npub trait FbFutureExt: Future {\n\n /// Construct a new [tokio_shim::time::Timeout].\n\n fn timeout(self, timeout: Duration) -> Timeout<Self>\n\n where\n\n Self: Sized,\n\n {\n\n tokio_shim::time::timeout(timeout, self)\n\n }\n\n\n\n /// Call the `on_cancel` callback if this future is cancelled (dropped\n\n /// without completion).\n\n fn on_cancel<F: FnOnce()>(self, on_cancel: F) -> OnCancel<Self, F>\n\n where\n\n Self: Sized,\n\n {\n\n OnCancel::new(self, on_cancel)\n\n }\n\n\n\n /// Call the `on_cancel` callback if this future is cancelled (dropped\n\n /// without completion). Pass additional data extracted from the\n", "file_path": "third-party/rust/shed/futures_ext/src/future/mod.rs", "rank": 59, "score": 271395.5366663679 }, { "content": "/// Similar to the Histogram trait, but accepts the args parameter for accessing dynamic\n\n/// histograms created at runtime.\n\npub trait DynamicHistogram<'a, T> {\n\n /// Dynamic version of `Histogram::add_value`\n\n fn add_value(&'a self, value: i64, args: T);\n\n\n\n /// Dynamic version of `Histogram::add_repeated_value`\n\n fn add_repeated_value(&'a self, value: i64, nsamples: u32, args: T);\n\n}\n\n\n\nimpl<'a, T> DynamicHistogram<'a, T> for DynamicStat<T, BoxHistogram> {\n\n fn add_value(&'a self, value: i64, args: T) {\n\n self.get_or_default(args, |s| s.add_value(value));\n\n }\n\n\n\n fn add_repeated_value(&'a self, value: i64, nsamples: u32, args: T) {\n\n self.get_or_default(args, |s| s.add_repeated_value(value, nsamples));\n\n }\n\n}\n\n\n\nimpl<T> DynamicHistogram<'static, T> for LocalKey<DynamicStat<T, BoxHistogram>> {\n\n fn add_value(&'static self, value: i64, args: T) {\n\n self.with(|s| s.add_value(value, args));\n\n }\n\n\n\n fn add_repeated_value(&'static self, value: i64, nsamples: u32, args: T) {\n\n self.with(|s| s.add_repeated_value(value, nsamples, args));\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/stats/traits/dynamic_stat_types.rs", "rank": 60, "score": 271222.7042423469 }, { "content": "/// Similar to the Counter trait, but accepts the args parameter for accessing dynamic counters\n\n/// created at runtime.\n\npub trait DynamicCounter<'a, T> {\n\n /// Dynamic version of `Counter::increment_value`\n\n fn increment_value(&'a self, value: i64, args: T);\n\n}\n\n\n\nimpl<'a, T> DynamicCounter<'a, T> for DynamicStat<T, BoxCounter> {\n\n fn increment_value(&'a self, value: i64, args: T) {\n\n self.get_or_default(args, |s| s.increment_value(value));\n\n }\n\n}\n\n\n\nimpl<T> DynamicCounter<'static, T> for LocalKey<DynamicStat<T, BoxCounter>> {\n\n fn increment_value(&'static self, value: i64, args: T) {\n\n self.with(|s| s.increment_value(value, args));\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/stats/traits/dynamic_stat_types.rs", "rank": 61, "score": 271222.7042423469 }, { "content": "/// Similar to Timeseries trait, but accepts the args parameter for accessing dynamic timeseries\n\n/// created in runtime.\n\npub trait DynamicTimeseries<'a, T> {\n\n /// Dynamic version of `Timeseries::add_value`\n\n fn add_value(&'a self, value: i64, args: T);\n\n\n\n /// Dynamic version of `Timeseries::add_value_aggregated`\n\n fn add_value_aggregated(&'a self, value: i64, nsamples: u32, args: T);\n\n}\n\n\n\nimpl<'a, T> DynamicTimeseries<'a, T> for DynamicStat<T, BoxTimeseries> {\n\n fn add_value(&'a self, value: i64, args: T) {\n\n self.get_or_default(args, |s| s.add_value(value));\n\n }\n\n\n\n fn add_value_aggregated(&'a self, value: i64, nsamples: u32, args: T) {\n\n self.get_or_default(args, |s| s.add_value_aggregated(value, nsamples));\n\n }\n\n}\n\n\n\nimpl<T> DynamicTimeseries<'static, T> for LocalKey<DynamicStat<T, BoxTimeseries>> {\n\n fn add_value(&'static self, value: i64, args: T) {\n\n self.with(|s| s.add_value(value, args));\n\n }\n\n\n\n fn add_value_aggregated(&'static self, value: i64, nsamples: u32, args: T) {\n\n self.with(|s| s.add_value_aggregated(value, nsamples, args));\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/stats/traits/dynamic_stat_types.rs", "rank": 62, "score": 271222.7042423469 }, { "content": "#[test]\n\nfn test_tick() -> Result<()> {\n\n use futures::stream::{FuturesUnordered, Stream};\n\n\n\n let log = Arc::new(Mutex::new(Vec::new()));\n\n let mut reference = Vec::new();\n\n let tick = Tick::new();\n\n let mut runtime = Runtime::new()?;\n\n\n\n let mut futs: FuturesUnordered<Box<dyn Future<Item = (), Error = ()> + Sync + Send>> =\n\n FuturesUnordered::new();\n\n futs.push(Box::new(tick.sleep(3).map({\n\n let log = log.clone();\n\n move |t| log.with(|l| l.push((3, t)))\n\n })));\n\n futs.push(Box::new(tick.sleep(1).map({\n\n let log = log.clone();\n\n move |t| log.with(|l| l.push((1, t)))\n\n })));\n\n futs.push(Box::new(tick.sleep(2).map({\n\n let log = log.clone();\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 63, "score": 270163.3520287289 }, { "content": "fn err<T>(codemap: &CodeMap, span: Span, err: DialectError) -> anyhow::Result<T> {\n\n Err(Diagnostic::new(err, span, codemap.dupe()))\n\n}\n\n\n\nimpl Dialect {\n\n pub(crate) fn check_lambda<T>(\n\n &self,\n\n codemap: &CodeMap,\n\n x: Spanned<T>,\n\n ) -> anyhow::Result<Spanned<T>> {\n\n if self.enable_lambda {\n\n Ok(x)\n\n } else {\n\n err(codemap, x.span, DialectError::Lambda)\n\n }\n\n }\n\n\n\n pub(crate) fn check_def<T>(\n\n &self,\n\n codemap: &CodeMap,\n", "file_path": "third-party/rust/starlark-rust/starlark/src/syntax/dialect.rs", "rank": 64, "score": 269568.97595220176 }, { "content": "/// Creates a stream which returns results of the futures given.\n\n///\n\n/// The returned stream will serially drive execution for all of its underlying\n\n/// futures. Errors from a future will be returned immediately, but the stream\n\n/// will still be valid and\n\npub fn futures_ordered<I>(iter: I) -> FuturesOrdered<I>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: IntoFuture,\n\n{\n\n let mut elems = iter.into_iter();\n\n let current = next_future(&mut elems);\n\n FuturesOrdered { elems, current }\n\n}\n\n\n\nimpl<I> Stream for FuturesOrdered<I>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: IntoFuture,\n\n{\n\n type Item = <I::Item as IntoFuture>::Item;\n\n type Error = <I::Item as IntoFuture>::Error;\n\n\n\n fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {\n\n match self.current.take() {\n", "file_path": "third-party/rust/shed/futures_01_ext/src/futures_ordered.rs", "rank": 65, "score": 268397.0458917437 }, { "content": "/// A trait implemented by default for all Futures which extends the standard\n\n/// functionality.\n\npub trait FbTryFutureExt: Future {\n\n /// Create a cloneable handle to this future where all handles will resolve\n\n /// to the same result.\n\n ///\n\n /// Similar to [futures::future::Shared], but instead works on Futures\n\n /// returning Result where Err is [anyhow::Error].\n\n /// This is achieved by storing [anyhow::Error] in [std::sync::Arc].\n\n fn try_shared(self) -> TryShared<Self>\n\n where\n\n Self: TryFuture<Error = Error> + Sized,\n\n <Self as TryFuture>::Ok: Clone,\n\n {\n\n self::try_shared::try_shared(self)\n\n }\n\n\n\n /// Convert a Future of Result<Result<I, E1>, E2> into a Future of Result<I, E1>, assuming E2\n\n /// can convert into E1.\n\n #[allow(clippy::type_complexity)]\n\n fn flatten_err<I, E1, E2>(\n\n self,\n", "file_path": "third-party/rust/shed/futures_ext/src/future/mod.rs", "rank": 66, "score": 268098.43468925485 }, { "content": "/// Similar to the SingletonCounter trait, but accepts the args parameter for accessing dynamic\n\n/// histograms created at runtime.\n\npub trait DynamicSingletonCounter<'a, T> {\n\n /// Dynamic version of `SingletonCounter::set_value`\n\n fn set_value(&'a self, fb: FacebookInit, value: i64, args: T);\n\n\n\n /// Dynamic version of `SingletonCounter::get_value`\n\n fn get_value(&'a self, fb: FacebookInit, args: T) -> Option<i64>;\n\n}\n\n\n\nimpl<'a, T> DynamicSingletonCounter<'a, T> for DynamicStat<T, BoxSingletonCounter> {\n\n fn set_value(&'a self, fb: FacebookInit, value: i64, args: T) {\n\n self.get_or_default(args, |s| s.set_value(fb, value));\n\n }\n\n\n\n fn get_value(&'a self, fb: FacebookInit, args: T) -> Option<i64> {\n\n self.get_or_default(args, |s| s.get_value(fb))\n\n }\n\n}\n\n\n\nimpl<T> DynamicSingletonCounter<'static, T> for LocalKey<DynamicStat<T, BoxSingletonCounter>> {\n\n fn set_value(&'static self, fb: FacebookInit, value: i64, args: T) {\n\n self.with(|s| s.set_value(fb, value, args))\n\n }\n\n\n\n fn get_value(&'static self, fb: FacebookInit, args: T) -> Option<i64> {\n\n self.with(|s| s.get_value(fb, args))\n\n }\n\n}\n", "file_path": "third-party/rust/shed/stats/traits/dynamic_stat_types.rs", "rank": 67, "score": 267691.2583785505 }, { "content": "/// A trait implemented for [Instant] that extends the standard functionality.\n\npub trait InstantExt {\n\n /// Returns the amount of time elapsed from this `Instant` to a later one.\n\n /// Corollary to `std::time::Instant::duration_since()`.\n\n fn duration_until(&self, later: Self) -> Duration;\n\n}\n\n\n\nimpl InstantExt for Instant {\n\n fn duration_until(&self, later: Self) -> Duration {\n\n later.duration_since(*self)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use quickcheck::quickcheck;\n\n\n\n quickcheck! {\n\n fn millis_checked(x: u64) -> bool {\n\n let dur = Duration::from_millis(x);\n", "file_path": "third-party/rust/shed/time_ext/src/lib.rs", "rank": 68, "score": 266957.21859773627 }, { "content": "/// A trait implemented for [Duration] that extends the standard functionality.\n\npub trait DurationExt {\n\n /// Returns the number of whole milliseconds contained in this `Duration`.\n\n /// Results in an error if the resulting value would overflow a `u64`.\n\n fn as_millis_u64(&self) -> Result<u64>;\n\n\n\n /// Returns the number of whole milliseconds contained in this `Duration`.\n\n /// Does not check for overflow.\n\n fn as_millis_unchecked(&self) -> u64;\n\n\n\n /// Returns the number of whole microseconds contained in this `Duration`.\n\n /// Results in an error if the resulting value would overflow a `u64`.\n\n fn as_micros_u64(&self) -> Result<u64>;\n\n\n\n /// Returns the number of whole microseconds contained in this `Duration`.\n\n /// Does not check for overflow.\n\n fn as_micros_unchecked(&self) -> u64;\n\n\n\n /// Returns the number of whole nanoseconds contained in this `Duration`.\n\n /// Results in an error if the resulting value would overflow a `u64`.\n\n fn as_nanos_u64(&self) -> Result<u64>;\n", "file_path": "third-party/rust/shed/time_ext/src/lib.rs", "rank": 69, "score": 266956.2910432477 }, { "content": "#[test]\n\nfn test_bounded_traversal() -> Result<()> {\n\n // tree\n\n // 0\n\n // / \\\n\n // 1 2\n\n // / / \\\n\n // 5 3 4\n\n let tree = Tree::new(\n\n 0,\n\n vec![\n\n Tree::new(1, vec![Tree::leaf(5)]),\n\n Tree::new(2, vec![Tree::leaf(3), Tree::leaf(4)]),\n\n ],\n\n );\n\n\n\n let tick = Tick::new();\n\n let log: StateLog<String> = StateLog::new();\n\n let reference: StateLog<String> = StateLog::new();\n\n let mut rt = Runtime::new()?;\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 70, "score": 266534.0799551393 }, { "content": "struct ErrSplitter<S: Stream> {\n\n inner: S,\n\n err_tx: Option<oneshot::Sender<S::Error>>,\n\n}\n\n\n\nimpl<S: Stream> Stream for ErrSplitter<S> {\n\n type Item = S::Item;\n\n type Error = !;\n\n\n\n fn poll(&mut self) -> Poll<Option<S::Item>, !> {\n\n match self.inner.poll() {\n\n Ok(Async::Ready(v)) => Ok(Async::Ready(v)),\n\n Ok(Async::NotReady) => Ok(Async::NotReady),\n\n Err(err) => {\n\n self.err_tx.take().map(|tx| tx.send(err));\n\n // If we're generating an error then this error-less stream is never going\n\n // to finish.\n\n Ok(Async::NotReady)\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/split_err.rs", "rank": 71, "score": 264273.71380280535 }, { "content": "#[doc(hidden)]\n\npub fn schedule_stats_on_stream_preview<S>(stream: S) -> SchedulerPreview\n\nwhere\n\n S: NewStream + Send + 'static,\n\n{\n\n stream\n\n .for_each(|_| {\n\n STATS_AGGREGATOR.aggregate();\n\n ready(())\n\n })\n\n .boxed()\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n lazy_static! {\n\n // Those tests work on global state so they cannot be run in parallel\n\n static ref TEST_MUTEX: Mutex<()> = Mutex::new(());\n\n }\n", "file_path": "third-party/rust/shed/stats/src/thread_local_aggregator.rs", "rank": 72, "score": 264055.62645871856 }, { "content": "#[test]\n\nfn test_bounded_traversal_dag() -> Result<()> {\n\n // dag\n\n // 0\n\n // / \\\n\n // 1 2\n\n // \\ / \\\n\n // 3 4\n\n // / \\\n\n // 5 6\n\n // \\ /\n\n // 7\n\n // |\n\n // 4 - will be resolved by the time it is reached\n\n let dag = hashmap! {\n\n 0 => vec![1, 2],\n\n 1 => vec![3],\n\n 2 => vec![3, 4],\n\n 3 => vec![5, 6],\n\n 4 => vec![],\n\n 5 => vec![7],\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 73, "score": 263039.12077935453 }, { "content": "/// Create a default root logger for Facebook services\n\npub fn facebook_logger() -> Result<Logger> {\n\n let decorator = PlainSyncDecorator::new(io::stderr());\n\n let drain = GlogFormat::new(decorator, FacebookCategorizer).fuse();\n\n Ok(Logger::root(drain, o!(FacebookKV::new()?)))\n\n}\n\n\n", "file_path": "third-party/rust/shed/slog_glog_fmt/src/glog_format.rs", "rank": 74, "score": 262818.80886505137 }, { "content": "/// Get the remaining unallocated space in the cache\n\npub fn get_available_space() -> Result<usize> {\n\n Ok(0)\n\n}\n\n\n", "file_path": "third-party/rust/shed/cachelib_stub/src/oss/lrucache.rs", "rank": 75, "score": 262790.47119660326 }, { "content": "// Add a bound to every type parameter.\n\npub fn add_trait_bounds(mut generics: Generics, bound: &TypeParamBound) -> Generics {\n\n for param in &mut generics.params {\n\n if let GenericParam::Type(ref mut type_param) = *param {\n\n type_param.bounds.push(bound.clone());\n\n }\n\n }\n\n generics\n\n}\n\n\n", "file_path": "third-party/rust/gazebo/gazebo_derive/src/util.rs", "rank": 76, "score": 261285.78738496592 }, { "content": "/// Prior to invoking `systemctl switch-root`, some setup work is required.\n\n/// Mainly, we need to fiddle with mounts so that /sysroot is the rw snapshot for\n\n/// the current bootid. This is necessary so that the newly invoked systemd has\n\n/// the correct root mount point.\n\npub fn switch_root(log: Logger, opts: Opts) -> Result<()> {\n\n let log = log.new(o!(\"snapshot\" => opts.snapshot.clone()));\n\n let (device, options) = find_rootdisk_device().context(\"failed to find /rootdisk device\")?;\n\n let options: Vec<_> = options.split(',').map(|s| s.to_string()).collect();\n\n let options = replace_subvol(options, &opts.snapshot);\n\n // TODO: for vmtest, no matter how we mount the rootfs, /proc/mounts will\n\n // always report that the device is /dev/vda. There are ways to work around\n\n // this to generically find the writable device (/dev/vdb) if this hack\n\n // stops working at some point, but for now this is way easier. For example:\n\n // seedroot.service can mount /dev/vdb instead of just remounting /dev/vda,\n\n // and then /sys/fs/btrfs/$uuid/devices will show the correct writable\n\n // device\n\n let device = match device.as_str() {\n\n \"/dev/vda\" => \"/dev/vdb\".into(),\n\n _ => device,\n\n };\n\n std::fs::create_dir(\"/sysroot\").context(\"failed to mkdir /sysroot\")?;\n\n debug!(log, \"mounting subvolume on {}\", device);\n\n mount(MountOpts {\n\n source: device.clone(),\n", "file_path": "antlir/linux/metalctl/src/switch_root.rs", "rank": 77, "score": 259953.39171740029 }, { "content": "#[test]\n\nfn test_bounded_traversal_dag_with_cycle() -> Result<()> {\n\n // graph with cycle\n\n // 0\n\n // / \\\n\n // 1 2\n\n // \\ /\n\n // 3\n\n // |\n\n // 2 <- forms cycle\n\n let graph = hashmap! {\n\n 0 => vec![1, 2],\n\n 1 => vec![3],\n\n 2 => vec![3],\n\n 3 => vec![2],\n\n };\n\n\n\n let tick = Tick::new();\n\n let log: StateLog<String> = StateLog::new();\n\n let reference: StateLog<String> = StateLog::new();\n\n let mut rt = Runtime::new()?;\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/tests.rs", "rank": 78, "score": 259670.9945797918 }, { "content": "/// Serialize structs, maps, sequences and tuples as function calls\n\npub fn function_call<T: Serialize>(name: &str, args: &T) -> Result<String, ser::Error> {\n\n let mut ser = ser::Serializer::new_pretty();\n\n let mut s = ser::CallSerializer::with(&mut ser, name);\n\n\n\n args.serialize(&mut s)?;\n\n\n\n mem::drop(s);\n\n\n\n Ok(ser.output())\n\n}\n", "file_path": "third-party/rust/shed/serde_starlark/src/lib.rs", "rank": 79, "score": 259144.97522697525 }, { "content": "pub fn helloWorld() -> &'static str {\n\n \"Hello world!\"\n\n}\n", "file_path": "third-party/rust/shed/codegen_includer_proc_macro/tests/fixtures/lib.rs", "rank": 80, "score": 257792.63350904058 }, { "content": "/// Find the number of times a `needle` occurs within a string, non-overlapping.\n\npub fn count_matches(x: &str, needle: &str) -> usize {\n\n if needle.len() == 1 {\n\n // If we are searching for a 1-byte string, we can provide a much faster path.\n\n // Since it is one byte, given how UTF8 works, all the resultant slices must be UTF8 too.\n\n count_matches_byte(x, needle.as_bytes()[0])\n\n } else {\n\n x.matches(needle).count()\n\n }\n\n}\n", "file_path": "third-party/rust/starlark-rust/starlark/src/values/fast_string.rs", "rank": 81, "score": 256977.00758300637 }, { "content": "/// \"Context\" support for futures where the error is an implementation of std::error::Error.\n\npub trait FutureFailureExt: Future + Sized {\n\n /// Add context to the error returned by this future\n\n fn context<D>(self, context: D) -> ContextFut<Self, D>\n\n where\n\n D: Display + Send + Sync + 'static;\n\n\n\n /// Add context created by provided function to the error returned by this future\n\n fn with_context<D, F>(self, f: F) -> WithContextFut<Self, F>\n\n where\n\n D: Display + Send + Sync + 'static,\n\n F: FnOnce() -> D;\n\n}\n\n\n\nimpl<F> FutureFailureExt for F\n\nwhere\n\n F: Future + Sized,\n\n F::Error: StdError + Send + Sync + 'static,\n\n{\n\n fn context<D>(self, displayable: D) -> ContextFut<Self, D>\n\n where\n", "file_path": "third-party/rust/shed/failure_ext/src/context_futures.rs", "rank": 82, "score": 256854.77506679192 }, { "content": "/// `bounded_traversal_stream` traverses implicit asynchronous tree specified by `init`\n\n/// and `unfold` arguments. All `unfold` operations are executed in parallel if they\n\n/// do not depend on each other (not related by ancestor-descendant relation in implicit\n\n/// tree) with amount of concurrency constrained by `scheduled_max`. Main difference\n\n/// with `bounded_traversal` is that this one is not structure perserving, and returns\n\n/// stream.\n\n///\n\n/// ## `init: InsInit`\n\n/// Is the root(s) of the implicit tree to be traversed\n\n///\n\n/// ## `unfold: FnMut(In) -> impl IntoFuture<Item = (Out, impl IntoIterator<Item = In>)>`\n\n/// Asynchronous function which given input value produces list of its children and output\n\n/// value.\n\n///\n\n/// ## return value `impl Stream<Item = Out>`\n\n/// Stream of all `Out` values\n\n///\n\npub fn bounded_traversal_stream<In, InsInit, Ins, Out, Unfold, UFut>(\n\n scheduled_max: usize,\n\n init: InsInit,\n\n mut unfold: Unfold,\n\n) -> impl Stream<Item = Out, Error = UFut::Error>\n\nwhere\n\n Unfold: FnMut(In) -> UFut,\n\n UFut: IntoFuture<Item = (Out, Ins)>,\n\n InsInit: IntoIterator<Item = In>,\n\n Ins: IntoIterator<Item = In>,\n\n{\n\n let mut unscheduled = VecDeque::from_iter(init);\n\n let mut scheduled = FuturesUnordered::new();\n\n stream::poll_fn(move || {\n\n loop {\n\n if scheduled.is_empty() && unscheduled.is_empty() {\n\n return Ok(Async::Ready(None));\n\n }\n\n\n\n for item in unscheduled\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/stream.rs", "rank": 83, "score": 256673.96533720655 }, { "content": "pub fn get_cached_or_fill<T, F>(\n\n _cache_pool: &VolatileLruCachePool,\n\n _cache_key: String,\n\n fetch: F,\n\n) -> BoxFuture<Option<T>, Error>\n\nwhere\n\n T: abomonation::Abomonation + Clone + Send + 'static,\n\n F: FnOnce() -> BoxFuture<Option<T>, Error>,\n\n{\n\n fetch()\n\n}\n\n\n", "file_path": "third-party/rust/shed/cachelib_stub/src/oss/abomonation_future_cache.rs", "rank": 84, "score": 255767.0342218129 }, { "content": "#[inline]\n\npub fn retry_write<T: AsyncWrite>(writer: &mut T, buf: &[u8]) -> io::Result<usize> {\n\n // tokio-io doesn't handle EINTR well at the moment, so retry here. See\n\n // https://github.com/tokio-rs/tokio-io/issues/37 for some discussion.\n\n loop {\n\n match writer.write(buf) {\n\n Ok(n) => return Ok(n),\n\n Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}\n\n Err(e) => return Err(e),\n\n }\n\n }\n\n}\n", "file_path": "third-party/rust/shed/async_compression/src/retry.rs", "rank": 85, "score": 255649.25975667575 }, { "content": "#[proc_macro_attribute]\n\npub fn test(args: TokenStream, input: TokenStream) -> TokenStream {\n\n expand(\n\n Mode::Test,\n\n parse_macro_input!(args with Punctuated::parse_terminated),\n\n parse_macro_input!(input),\n\n )\n\n .unwrap_or_else(|err| err.to_compile_error())\n\n .into()\n\n}\n", "file_path": "third-party/rust/shed/fbinit/macros/lib.rs", "rank": 86, "score": 255571.05855282367 }, { "content": "#[starlark_module]\n\npub fn global(builder: &mut GlobalsBuilder) {\n\n #[starlark_type(Struct::TYPE)]\n\n fn r#struct(args: Arguments<'v, '_>) -> Struct<'v> {\n\n args.no_positional_args(heap)?;\n\n Ok(Struct {\n\n fields: args.names()?.content,\n\n })\n\n }\n\n}\n\n\n\n#[starlark_module]\n\npub(crate) fn struct_methods(builder: &mut GlobalsBuilder) {\n\n fn to_json(this: Value) -> String {\n\n this.to_json()\n\n }\n\n}\n", "file_path": "third-party/rust/starlark-rust/starlark/src/stdlib/structs.rs", "rank": 87, "score": 254371.82997226377 }, { "content": "/// If you set this as the root logger at the start of your tests\n\n/// you will actually see log lines for failed tests. It looks the same\n\n/// as `facebook_logger`.\n\n/// Note: this may not show logs from threads not under the test runner\n\n/// <https://docs.rs/slog-term/2.8.0/slog_term/struct.TestStdoutWriter.html#note>\n\npub fn logger_that_can_work_in_tests() -> Result<Logger> {\n\n let decorator = PlainSyncDecorator::new(slog_term::TestStdoutWriter);\n\n let drain = GlogFormat::new(decorator, FacebookCategorizer).fuse();\n\n Ok(Logger::root(drain, o!(FacebookKV::new()?)))\n\n}\n\n\n\n/// A slog `Drain` for glog-formatted logs.\n\npub struct GlogFormat<D: Decorator, C: KVCategorizer> {\n\n decorator: D,\n\n categorizer: C,\n\n}\n\n\n\nimpl<D: Decorator, C: KVCategorizer> GlogFormat<D, C> {\n\n /// Create a glog-formatted `Drain` using the provided `Decorator`, and `Categorizer`\n\n pub fn new(decorator: D, categorizer: C) -> GlogFormat<D, C> {\n\n GlogFormat {\n\n decorator,\n\n categorizer,\n\n }\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/slog_glog_fmt/src/glog_format.rs", "rank": 88, "score": 254367.6761622739 }, { "content": "#[starlark_module]\n\npub fn global(builder: &mut GlobalsBuilder) {\n\n fn assert_type(ref v: Value, ref ty: Value) -> NoneType {\n\n v.check_type(ty, Some(\"v\"))?;\n\n Ok(NoneType)\n\n }\n\n\n\n fn is_type(ref v: Value, ref ty: Value) -> bool {\n\n v.is_type(ty)\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::assert;\n\n\n\n #[test]\n\n fn test_types() {\n\n let a = assert::Assert::new();\n\n a.is_true(\n\n r#\"\n", "file_path": "third-party/rust/starlark-rust/starlark/src/stdlib/typing.rs", "rank": 89, "score": 254221.46780236822 }, { "content": "/// Find the number of times a `needle` byte occurs within a string.\n\n/// If the needle represents a complete character, this will be equivalent to doing\n\n/// search for that character in the string.\n\npub fn count_matches_byte(x: &str, needle: u8) -> usize {\n\n x.as_bytes().iter().filter(|x| **x == needle).count()\n\n}\n\n\n", "file_path": "third-party/rust/starlark-rust/starlark/src/values/fast_string.rs", "rank": 90, "score": 252924.8491778823 }, { "content": "#[auto_impl(Box)]\n\npub trait StatsManager {\n\n /// Function to be called periodically to aggregate all the stats owned by\n\n /// this manager.\n\n fn aggregate(&self);\n\n\n\n /// Create a new instance of [BoxCounter] and bind it to self for\n\n /// aggregation purposes.\n\n /// Provided name is the name of the counter.\n\n fn create_counter(&self, name: &str) -> BoxCounter;\n\n\n\n /// Create new instance of [BoxTimeseries] and bind it to self for\n\n /// aggregation purposes.\n\n /// Provided name is the name of the timeseries.\n\n /// [AggregationType] decides which types of aggragation are exported by\n\n /// the returned timeseries. The actual implementation is free to assume\n\n /// some defaults if `aggregation_type` is empty.\n\n /// The `intervals` provides a list of intervals at which data should be\n\n /// aggregated, the actual implementation is free (and encouraged) to assume\n\n /// some defaults if `intervals` is empty.\n\n fn create_timeseries(\n", "file_path": "third-party/rust/shed/stats/traits/stats_manager.rs", "rank": 91, "score": 252852.4242940382 }, { "content": "pub trait StatsManagerFactory {\n\n fn create(&self) -> BoxStatsManager;\n\n}\n\n\n\npub type BoxStatsManager = Box<dyn StatsManager + Send + Sync>;\n\n\n\n#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]\n\npub enum AggregationType {\n\n Sum,\n\n Count,\n\n Average,\n\n Rate,\n\n Percent,\n\n}\n\n\n\npub struct BucketConfig {\n\n pub width: u32,\n\n pub min: u32,\n\n pub max: u32,\n\n}\n\n\n", "file_path": "third-party/rust/shed/stats/traits/stats_manager.rs", "rank": 92, "score": 250243.27907364906 }, { "content": "fn convert_ref(fail: &(impl Fail + ?Sized)) -> Error {\n\n match fail.cause() {\n\n Some(cause) => convert_ref(cause).context(fail.to_string()),\n\n None => Error::new(ErrorMessage {\n\n display: fail.to_string(),\n\n debug: format!(\"{:?}\", fail),\n\n }),\n\n }\n\n}\n\n\n", "file_path": "third-party/rust/shed/failure_ext/src/convert.rs", "rank": 93, "score": 247865.85964668257 }, { "content": "fn build_map_data(start: usize, size: usize) -> Vec<(String, usize)> {\n\n let mut index = 0;\n\n let mut data = Vec::with_capacity(size);\n\n for n in start.. {\n\n for word1 in WORDS.iter() {\n\n for word2 in WORDS.iter() {\n\n data.push((format!(\"{}.{}.{}\", word1, n, word2), index));\n\n index += 1;\n\n if index >= size {\n\n return data;\n\n }\n\n }\n\n }\n\n }\n\n unreachable!()\n\n}\n\n\n\nmacro_rules! make_map_bench {\n\n ($name:ident, $map:ident, [ $(,)? ]) => {};\n\n ($name:ident, $map:ident, [ $(,)? $count:literal $( $counts:tt )* ]) => {\n", "file_path": "third-party/rust/shed/sorted_vector_map/benches/map.rs", "rank": 94, "score": 246834.50729206347 }, { "content": "/// The function converts RowField object into Rust type.\n\npub fn opt_try_from_rowfield<T>(_field: RowField) -> Result<Option<T>, MysqlError> {\n\n unimplemented!(\"This is a stub\");\n\n}\n", "file_path": "third-party/rust/shed/sql/common/mysql/mysql_stub/mod.rs", "rank": 95, "score": 246736.61071834064 }, { "content": "fn test_values(container: impl OneRef + TwoRef) {\n\n assert_eq!(container.one().get(), 1);\n\n assert_eq!(container.two().get(), 2);\n\n}\n\n\n", "file_path": "third-party/rust/shed/facet/test/static_test.rs", "rank": 96, "score": 245559.8560382561 }, { "content": "struct BytesStreamFutureInner<S, Dec> {\n\n bs: BytesStream<S>,\n\n decoder: Dec,\n\n is_readable: bool,\n\n}\n\n\n\nimpl<S, Dec> BytesStreamFutureInner<S, Dec>\n\nwhere\n\n S: Stream<Item = Bytes>,\n\n Dec: Decoder,\n\n Dec::Error: From<S::Error>,\n\n{\n\n fn poll(&mut self) -> Poll<Option<Dec::Item>, Dec::Error> {\n\n loop {\n\n if self.is_readable {\n\n if self.bs.stream_done {\n\n return Ok(Async::Ready(self.decoder.decode_eof(&mut self.bs.bytes)?));\n\n }\n\n\n\n if let Some(frame) = self.decoder.decode(&mut self.bs.bytes)? {\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bytes_stream/bytes_stream_future.rs", "rank": 97, "score": 245318.35108559654 }, { "content": "/// `bounded_traversal_dag` traverses implicit asynchronous DAG specified by `init`\n\n/// and `unfold` arguments, and it also does backward pass with `fold` operation.\n\n/// All `unfold` and `fold` operations are executed in parallel if they do not\n\n/// depend on each other (not related by ancestor-descendant relation in implicit DAG)\n\n/// with amount of concurrency constrained by `scheduled_max`.\n\n///\n\n/// ## Difference between `bounded_traversal_dag` and `bounded_traversal`\n\n/// Obvious difference is that `bounded_traversal_dag` correctly handles DAGs\n\n/// (`bounded_traversal` treats all children references as distinct and its execution time\n\n/// is proportional to number of paths from the root, since DAG can be constructed to contain\n\n/// `O(exp(N))` path it might cause problems) but it comes with a price:\n\n/// - `bounded_traversal_dag` keeps `Out` result of computation for all the nodes\n\n/// but `bounded_traversal` only keeps results for nodes that have not been completely\n\n/// evaluatated\n\n/// - `In` has additional constraints to be `Eq + Hash + Clone`\n\n/// - `Out` has additional constraint to be `Clone`\n\n///\n\n/// ## `init: In`\n\n/// Is the root of the implicit tree to be traversed\n\n///\n\n/// ## `unfold: FnMut(In) -> impl IntoFuture<Item = (OutCtx, impl IntoIterator<Item = In>)>`\n\n/// Asynchronous function which given input value produces list of its children. And context\n\n/// associated with current node. If this list is empty, it is a leaf of the tree, and `fold`\n\n/// will be run on this node.\n\n///\n\n/// ## `fold: FnMut(OutCtx, impl Iterator<Out>) -> impl IntoFuture<Item=Out>`\n\n/// Aynchronous function which given node context and output of `fold` for its chidlren\n\n/// should produce new output value.\n\n///\n\n/// ## return value `impl Future<Item = Option<Out>>`\n\n/// Result of running fold operation on the root of the tree. `None` indiciate that cycle\n\n/// has been found.\n\n///\n\npub fn bounded_traversal_dag<In, Ins, Out, OutCtx, Unfold, UFut, Fold, FFut>(\n\n scheduled_max: usize,\n\n init: In,\n\n unfold: Unfold,\n\n fold: Fold,\n\n) -> impl Future<Item = Option<Out>, Error = UFut::Error>\n\nwhere\n\n In: Eq + Hash + Clone,\n\n Out: Clone,\n\n Unfold: FnMut(In) -> UFut,\n\n UFut: IntoFuture<Item = (OutCtx, Ins)>,\n\n Ins: IntoIterator<Item = In>,\n\n Fold: FnMut(OutCtx, Iter<Out>) -> FFut,\n\n FFut: IntoFuture<Item = Out, Error = UFut::Error>,\n\n{\n\n BoundedTraversalDAG::new(scheduled_max, init, unfold, fold)\n\n}\n\n\n", "file_path": "third-party/rust/shed/futures_01_ext/src/bounded_traversal/dag.rs", "rank": 98, "score": 244664.03678782188 }, { "content": "pub fn to_string<T>(value: &T) -> Result<String, ser::Error>\n\nwhere\n\n T: Serialize,\n\n{\n\n let mut s = ser::Serializer::new();\n\n\n\n value.serialize(&mut s)?;\n\n\n\n Ok(s.output())\n\n}\n\n\n", "file_path": "third-party/rust/shed/serde_starlark/src/lib.rs", "rank": 99, "score": 244080.49796511594 } ]
Rust
src/io/seq.rs
lskatz/ROSS.rs
6dfc202ac7e2b94769657f53c450954daa7ce267
use std::collections::HashMap; use std::clone::Clone; #[test] fn test_new_seq() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let cleanable = Seq::new(&id,&seq,&qual); let formatted = format!("@{}\n{}\n+\n{}", &id, &seq, &qual); assert_eq!(cleanable.to_string(), formatted); } #[test] fn test_cleanable() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let mut cleanable = Seq::new(&id,&seq,&qual); cleanable.lower_ambiguity_q(); cleanable.trim(); assert_eq!(cleanable.to_string(), "@MY_ID\nATNGG\n+\nAB!DE".to_string()); } #[derive(Debug)] pub struct Seq { pub id: String, pub seq: String, pub qual: String, pub pairid: String, pub thresholds: HashMap<String,f32>, } pub trait Cleanable{ fn new (id: &String, seq: &String, qual: &String) -> Seq; fn blank () -> Seq; fn is_blank (&self) -> bool; fn from_string (seq_str: &String) -> Seq; fn sanitize_id(id: &String) -> String; fn lower_ambiguity_q(&mut self) -> (); fn trim(&mut self) -> (); fn is_high_quality(&mut self) -> bool; fn to_string(&self) -> String; fn print(&self) -> (); } impl Cleanable for Seq { fn new (id: &String, seq: &String, qual: &String) -> Seq{ let id_copy = Self::sanitize_id(&id); let mut thresholds = HashMap::new(); thresholds.insert("min_avg_qual".to_string(),20.0); thresholds.insert("min_length".to_string(),100.0); thresholds.insert("min_trim_qual".to_string(),20.0); return Seq{ id: id_copy, seq: seq.clone(), qual: qual.clone(), pairid: String::new(), thresholds: thresholds, }; } fn blank () -> Seq{ return Seq::new(&String::new(),&String::new(),&String::new()); } fn is_blank (&self) -> bool { if self.seq.len() == 0 && self.qual.len() == 0 { return true; } return false; } fn from_string (seq_str: &String) -> Seq { let mut lines = seq_str.lines(); let id = lines.next().expect("Could not parse ID"); let seq = lines.next().expect("Could not parse sequence"); lines.next().expect("Could not parse +"); let qual_opt = lines.next(); if qual_opt == None { return Seq::blank(); } let qual = qual_opt.expect("Could not read the qual line"); return Seq{ id: id.to_string(), seq: seq.to_string(), qual: qual.to_string(), pairid: String::new(), thresholds: HashMap::new(), } } fn sanitize_id(id: &String) -> String { if id.len() == 0 { return String::new(); } let mut id_copy = id.clone(); if id_copy.chars().nth(0).expect("ID was empty") == '@' { id_copy.pop(); } return id_copy; } fn lower_ambiguity_q(&mut self){ let zero_score:char = 33 as char; let low_score :char = (33 + 0) as u8 as char; let mut low_qual_idx = vec![false; self.seq.len()]; for (i,nt) in self.seq.chars().enumerate(){ if nt == 'N' || nt == 'n' || self.qual.chars().nth(i).expect("Expected a char") < low_score { low_qual_idx[i] = true; } } let mut new_seq =String::new(); let mut new_qual=String::new(); for (i,nt) in self.seq.chars().enumerate(){ if low_qual_idx[i] { new_seq.push('N'); new_qual.push(zero_score); } else{ new_seq.push(nt); new_qual.push_str(&self.qual[i..i+1]); } } self.seq=new_seq; self.qual=new_qual; } fn trim(&mut self) { let min_qual = *self.thresholds.entry("min_trim_qual".to_string()) .or_insert(0.0) as u8; let mut trim5=0; let mut trim3=&self.qual.len()-0; for qual in self.qual.chars(){ if qual as u8 - 33 < min_qual { trim5+=1; } else { break; } } for qual in self.qual.chars().rev() { if qual as u8 - 33 < min_qual { trim3-=1; } else { break; } } if trim5 >= trim3 { self.qual = String::new(); self.seq = String::new(); } else { self.qual = self.qual[trim5..trim3].to_string(); self.seq = self.seq[trim5..trim3].to_string(); } } fn is_high_quality(&mut self) -> bool { let min_length = self.thresholds.get(&"min_length".to_string()).expect("min_length does not look like a number"); let seq_len = self.seq.len() as f32; if seq_len < *min_length { return false; } let mut total_qual = 0; for qual in self.qual.chars() { total_qual += qual as u32; } let avg_qual = (total_qual as f32/seq_len) - 33.0; let min_qual = self.thresholds.get(&"min_avg_qual".to_string()).expect("min_avg_qual does not look like a number"); if avg_qual < *min_qual { return false; } return true; } fn to_string(&self) -> String { let mut entry = String::new(); if self.id.len() > 0 && self.id.chars().nth(0).expect("Seq ID was not set") != '@' { entry.push('@'); } entry.push_str(self.id.trim()); entry.push_str("\n"); entry.push_str(self.seq.trim()); entry.push_str("\n+\n"); entry.push_str(&self.qual.trim()); return entry; } fn print(&self) -> () { println!("{}",self.to_string()); } } impl Clone for Seq { fn clone(&self) -> Seq { return Seq{ id: self.id.clone(), seq: self.seq.clone(), qual: self.qual.clone(), pairid: self.pairid.clone(), thresholds: self.thresholds.clone(), } } }
use std::collections::HashMap; use std::clone::Clone; #[test] fn test_new_seq() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let cleanable = Seq::new(&id,&seq,&qual); let formatted = format!("@{}\n{}\n+\n{}", &id, &seq, &qual); assert_eq!(cleanable.to_string(), formatted); } #[test] fn test_cleanable() { let id = "MY_ID".to_string(); let seq = "AATNGGCC".to_string(); let qual = "#ABCDE!!".to_string(); let mut cleanable = Seq::new(&id,&seq,&qual); cleanable.lower_ambiguity_q(); cleanable.trim(); assert_eq!(cleanable.to_string(), "@MY_ID\nATNGG\n+\nAB!DE".to_string()); } #[derive(Debug)] pub struct Seq { pub id: String, pub seq: String, pub qual: String, pub pairid: String, pub thresholds: HashMap<String,f32>, } pub trait Cleanable{ fn new (id: &String, seq: &String, qual: &String) -> Seq; fn blank () -> Seq; fn is_blank (&self) -> bool; fn from_string (seq_str: &String) -> Seq; fn sanitize_id(id: &String) -> String; fn lower_ambiguity_q(&mut self) -> (); fn trim(&mut self) -> (); fn is_high_quality(&mut self) -> bool; fn to_string(&self) -> String; fn print(&self) -> (); } impl Cleanable for Seq { fn new (id: &String, seq: &String, qual: &String) -> Seq{ let id_copy = Self::sanitize_id(&id); let mut thresholds = HashMap::new(); thresholds.insert("min_avg_qual".to_string(),20.0); thresholds.insert("min_length".to_string(),100.0); thresholds.insert("min_trim_qual".to_string(),20.0); return Seq{ id: id_copy, seq: seq.clone(), qual: qual.clone(), pairid: String::new(), thresholds: thresholds, }; } fn blank () -> Seq{ return Seq::new(&String::new(),&String::new(),&String::new()); } fn is_blank (&self) -> bool { if self.seq.len() == 0 && self.qual.len() == 0 { return true; }
mber"); let seq_len = self.seq.len() as f32; if seq_len < *min_length { return false; } let mut total_qual = 0; for qual in self.qual.chars() { total_qual += qual as u32; } let avg_qual = (total_qual as f32/seq_len) - 33.0; let min_qual = self.thresholds.get(&"min_avg_qual".to_string()).expect("min_avg_qual does not look like a number"); if avg_qual < *min_qual { return false; } return true; } fn to_string(&self) -> String { let mut entry = String::new(); if self.id.len() > 0 && self.id.chars().nth(0).expect("Seq ID was not set") != '@' { entry.push('@'); } entry.push_str(self.id.trim()); entry.push_str("\n"); entry.push_str(self.seq.trim()); entry.push_str("\n+\n"); entry.push_str(&self.qual.trim()); return entry; } fn print(&self) -> () { println!("{}",self.to_string()); } } impl Clone for Seq { fn clone(&self) -> Seq { return Seq{ id: self.id.clone(), seq: self.seq.clone(), qual: self.qual.clone(), pairid: self.pairid.clone(), thresholds: self.thresholds.clone(), } } }
return false; } fn from_string (seq_str: &String) -> Seq { let mut lines = seq_str.lines(); let id = lines.next().expect("Could not parse ID"); let seq = lines.next().expect("Could not parse sequence"); lines.next().expect("Could not parse +"); let qual_opt = lines.next(); if qual_opt == None { return Seq::blank(); } let qual = qual_opt.expect("Could not read the qual line"); return Seq{ id: id.to_string(), seq: seq.to_string(), qual: qual.to_string(), pairid: String::new(), thresholds: HashMap::new(), } } fn sanitize_id(id: &String) -> String { if id.len() == 0 { return String::new(); } let mut id_copy = id.clone(); if id_copy.chars().nth(0).expect("ID was empty") == '@' { id_copy.pop(); } return id_copy; } fn lower_ambiguity_q(&mut self){ let zero_score:char = 33 as char; let low_score :char = (33 + 0) as u8 as char; let mut low_qual_idx = vec![false; self.seq.len()]; for (i,nt) in self.seq.chars().enumerate(){ if nt == 'N' || nt == 'n' || self.qual.chars().nth(i).expect("Expected a char") < low_score { low_qual_idx[i] = true; } } let mut new_seq =String::new(); let mut new_qual=String::new(); for (i,nt) in self.seq.chars().enumerate(){ if low_qual_idx[i] { new_seq.push('N'); new_qual.push(zero_score); } else{ new_seq.push(nt); new_qual.push_str(&self.qual[i..i+1]); } } self.seq=new_seq; self.qual=new_qual; } fn trim(&mut self) { let min_qual = *self.thresholds.entry("min_trim_qual".to_string()) .or_insert(0.0) as u8; let mut trim5=0; let mut trim3=&self.qual.len()-0; for qual in self.qual.chars(){ if qual as u8 - 33 < min_qual { trim5+=1; } else { break; } } for qual in self.qual.chars().rev() { if qual as u8 - 33 < min_qual { trim3-=1; } else { break; } } if trim5 >= trim3 { self.qual = String::new(); self.seq = String::new(); } else { self.qual = self.qual[trim5..trim3].to_string(); self.seq = self.seq[trim5..trim3].to_string(); } } fn is_high_quality(&mut self) -> bool { let min_length = self.thresholds.get(&"min_length".to_string()).expect("min_length does not look like a nu
random
[ { "content": "/// Propagate an error by printing invalid read(s)\n\npub fn eexit() -> () {\n\n println!(\"{}\\n{}\\n{}\\n{}\",INVALID_ID,INVALID_SEQ,INVALID_PLUS,INVALID_QUAL);\n\n std::process::exit(1);\n\n}\n\n\n\n/// Rewrite print!() so that it doesn't panic on broken\n\n/// pipe.\n\n#[macro_export]\n\nmacro_rules! print (\n\n // The extra scope is necessary so we don't leak imports\n\n ($($arg:tt)*) => ({\n\n // The `write!()` macro is written so it can use `std::io::Write`\n\n // or `std::fmt::Write`, this import sets which to use\n\n use std::io::{self, Write};\n\n if let Err(_) = write!(io::stdout(), $($arg)*) {\n\n // Optionally write the error to stderr\n\n ::std::process::exit(0);\n\n }\n\n \n\n })\n\n);\n\n\n", "file_path": "src/lib.rs", "rank": 3, "score": 86668.36420000087 }, { "content": "/// a function that reads an options object and adds fasten default options.\n\npub fn fasten_base_options() -> Options{\n\n let mut opts = Options::new();\n\n opts.optflag(\"h\", \"help\", \"Print this help menu.\");\n\n opts.optopt(\"n\",\"numcpus\",\"Number of CPUs (default: 1)\",\"INT\");\n\n opts.optflag(\"p\",\"paired-end\",\"The input reads are interleaved paired-end\");\n\n opts.optflag(\"\",\"verbose\",\"Print more status messages\");\n\n opts.optflag(\"\",\"version\",\"Print the version of Fasten and exit\");\n\n\n\n return opts;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 4, "score": 77931.8992142833 }, { "content": "/// Test whether we can read the test data quickly.\n\nfn test_the_fast_reader () {\n\n use std::fs::File;\n\n let my_file = File::open(\"testdata/four_reads.fastq\").expect(\"Could not open file\");\n\n let my_buffer=BufReader::new(my_file);\n\n let mut fastq_reader=FastqReader::new(my_buffer);\n\n let seq_obj = fastq_reader.next().expect(\"Could not read four_reads.fastq\");\n\n assert_eq!(seq_obj.seq.trim(), \"AAAGTGCTCTTAACTTGTCCCGCTCCACATCAGCGCGACATCAATCGACATTAAACCGAGTATCTTGTCAGCCTGGGGTGACGATGCGTCCCATTAAAGT\");\n\n}\n\n\n\n/// A FastQ reader\n\npub struct FastqReader<R: io::Read> {\n\n reader: io::BufReader<R>,\n\n quickly: bool,\n\n}\n\n\n\nimpl<R: io::Read> FastqReader<R>{\n\n pub fn new(reader: R) -> FastqReader<R> {\n\n FastqReader {\n\n reader : BufReader::new(reader),\n\n quickly: true,\n", "file_path": "src/io/fastq.rs", "rank": 5, "score": 72712.67083746406 }, { "content": "/// Test whether we can read the test data carefully.\n\nfn test_the_careful_reader () {\n\n use std::fs::File;\n\n let my_file = File::open(\"testdata/four_reads.fastq\").expect(\"Could not open file\");\n\n let my_buffer=BufReader::new(my_file);\n\n let mut fastq_reader=FastqReader::new_careful(my_buffer);\n\n let seq_obj = fastq_reader.next().expect(\"Could not read four_reads.fastq\");\n\n assert_eq!(seq_obj.seq.trim(), \"AAAGTGCTCTTAACTTGTCCCGCTCCACATCAGCGCGACATCAATCGACATTAAACCGAGTATCTTGTCAGCCTGGGGTGACGATGCGTCCCATTAAAGT\");\n\n}\n\n\n\n#[test]\n", "file_path": "src/io/fastq.rs", "rank": 6, "score": 72712.67083746406 }, { "content": "/// Print a formatted message to stderr \n\npub fn logmsg<S: AsRef<str>>(stringlike: S) {\n\n let args: Vec<_> = env::args().collect();\n\n // is there a better way to get the basename of the program???\n\n let program = Path::file_name(Path::new(&args[0])).unwrap().to_str().unwrap();\n\n let str_ref = stringlike.as_ref();\n\n eprintln!(\"{}: {}\", &program, str_ref);\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 7, "score": 66240.50662522129 }, { "content": "/// a function that processes the options on the command line\n\n/// The brief is a str that describes the program without using the program\n\n/// name, e.g., \"counts kmers\" for fasten_kmer.\n\n/// This function also takes care of --version.\n\n/// If --help is invoked, then the program name, the brief, and the usage()\n\n/// are all printed to stdout and then the program exits with 0.\n\n// TODO if possible add in default somehow for numcpus\n\npub fn fasten_base_options_matches(brief:&str, opts:Options) -> Matches{\n\n let args: Vec<String> = env::args().collect();\n\n let matches = opts.parse(&args[1..]).expect(\"ERROR: could not parse parameters\");\n\n\n\n if matches.opt_present(\"version\") {\n\n println!(\"Fasten v{}\", &VERSION);\n\n std::process::exit(0);\n\n }\n\n if matches.opt_present(\"h\") {\n\n let prog_name = Path::new(&args[0])\n\n .file_stem().unwrap()\n\n .to_str().unwrap();\n\n println!(\"{}: {}\\n\\n{}\", \n\n &prog_name,\n\n &brief,\n\n &opts.usage(\n\n &opts.short_usage(&prog_name)\n\n ),\n\n );\n\n std::process::exit(0);\n\n }\n\n\n\n return matches;\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 8, "score": 64381.539732532285 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [];\n", "file_path": "docs/implementors/fasten/io/seq/trait.Cleanable.js", "rank": 9, "score": 61991.05375433974 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R:&nbsp;<a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/std/io/trait.Read.html\\\" title=\\\"trait std::io::Read\\\">Read</a>&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/iter/traits/iterator/trait.Iterator.html\\\" title=\\\"trait core::iter::traits::iterator::Iterator\\\">Iterator</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt;\",\"synthetic\":false,\"types\":[\"fasten::io::fastq::FastqReader\"]}];\n", "file_path": "docs/implementors/core/iter/traits/iterator/trait.Iterator.js", "rank": 20, "score": 27853.41593467624 }, { "content": "if(!String.prototype.startsWith){String.prototype.startsWith=function(searchString,position){position=position||0;return this.indexOf(searchString,position)===position}}if(!String.prototype.endsWith){String.prototype.endsWith=function(suffix,length){var l=length||this.length;return this.indexOf(suffix,l-suffix.length)!==-1}}if(!DOMTokenList.prototype.add){DOMTokenList.prototype.add=function(className){if(className&&!hasClass(this,className)){if(this.className&&this.className.length>0){this.className+=\" \"+className}else{this.className=className}}}}if(!DOMTokenList.prototype.remove){DOMTokenList.prototype.remove=function(className){if(className&&this.className){this.className=(\" \"+this.className+\" \").replace(\" \"+className+\" \",\" \").trim()}}}function getVar(name){var el=document.getElementById(\"rustdoc-vars\");if(el){return el.attributes[\"data-\"+name].value}else{return null}}function resourcePath(basename,extension){return getVar(\"root-path\")+basename+getVar(\"resource-suffix\")+extension}(function(){window.rootPath=getVar(\"root-path\");window.currentCrate=getVar(\"current-crate\");window.searchJS=resourcePath(\"search\",\".js\");window.searchIndexJS=resourcePath(\"search-index\",\".js\");var sidebarVars=document.getElementById(\"sidebar-vars\");if(sidebarVars){window.sidebarCurrent={name:sidebarVars.attributes[\"data-name\"].value,ty:sidebarVars.attributes[\"data-ty\"].value,relpath:sidebarVars.attributes[\"data-relpath\"].value,}}}());function getVirtualKey(ev){if(\"key\"in ev&&typeof ev.key!=\"undefined\"){return ev.key}var c=ev.charCode||ev.keyCode;if(c==27){return\"Escape\"}return String.fromCharCode(c)}var THEME_PICKER_ELEMENT_ID=\"theme-picker\";var THEMES_ELEMENT_ID=\"theme-choices\";var MAIN_ID=\"main-content\";function getThemesElement(){return document.getElementById(THEMES_ELEMENT_ID)}function getThemePickerElement(){return document.getElementById(THEME_PICKER_ELEMENT_ID)}function getNakedUrl(){return window.location.href.split(\"?\")[0].split(\"#\")[0]}function showThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"block\";themePicker.style.borderBottomRightRadius=\"0\";themePicker.style.borderBottomLeftRadius=\"0\"}function hideThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"none\";themePicker.style.borderBottomRightRadius=\"3px\";themePicker.style.borderBottomLeftRadius=\"3px\"}(function(){var themeChoices=getThemesElement();var themePicker=getThemePickerElement();var availableThemes=getVar(\"themes\").split(\",\");function switchThemeButtonState(){if(themeChoices.style.display===\"block\"){hideThemeButtonState()}else{showThemeButtonState()}}function handleThemeButtonsBlur(e){var active=document.activeElement;var related=e.relatedTarget;if(active.id!==THEME_PICKER_ELEMENT_ID&&(!active.parentNode||active.parentNode.id!==THEMES_ELEMENT_ID)&&(!related||(related.id!==THEME_PICKER_ELEMENT_ID&&(!related.parentNode||related.parentNode.id!==THEMES_ELEMENT_ID)))){hideThemeButtonState()}}themePicker.onclick=switchThemeButtonState;themePicker.onblur=handleThemeButtonsBlur;availableThemes.forEach(function(item){var but=document.createElement(\"button\");but.textContent=item;but.onclick=function(){switchTheme(window.currentTheme,window.mainTheme,item,true);useSystemTheme(false)};but.onblur=handleThemeButtonsBlur;themeChoices.appendChild(but)})}());(function(){\"use strict\";window.searchState={loadingText:\"Loading search results...\",input:document.getElementsByClassName(\"search-input\")[0],outputElement:function(){return document.getElementById(\"search\")},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:function(){if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},focus:function(){searchState.input.focus()},defocus:function(){searchState.input.blur()},showResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(main,\"hidden\");removeClass(search,\"hidden\");searchState.mouseMovedAfterSearch=false;document.title=searchState.title},hideResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(search,\"hidden\");removeClass(main,\"hidden\");document.title=searchState.titleBeforeSearch;if(searchState.browserSupportsHistoryApi()){history.replaceState(\"\",window.currentCrate+\" - Rust\",getNakedUrl()+window.location.hash)}},getQueryStringParams:function(){var params={};window.location.search.substring(1).split(\"&\").map(function(s){var pair=s.split(\"=\");params[decodeURIComponent(pair[0])]=typeof pair[1]===\"undefined\"?null:decodeURIComponent(pair[1])});return params},putBackSearch:function(search_input){var search=searchState.outputElement();if(search_input.value!==\"\"&&hasClass(search,\"hidden\")){searchState.showResults(search);if(searchState.browserSupportsHistoryApi()){var extra=\"?search=\"+encodeURIComponent(search_input.value);history.replaceState(search_input.value,\"\",getNakedUrl()+extra+window.location.hash)}document.title=searchState.title}},browserSupportsHistoryApi:function(){return window.history&&typeof window.history.pushState===\"function\"},setup:function(){var search_input=searchState.input;if(!searchState.input){return}function loadScript(url){var script=document.createElement('script');script.src=url;document.head.append(script)}var searchLoaded=false;function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(window.searchJS);loadScript(window.searchIndexJS)}}search_input.addEventListener(\"focus\",function(){searchState.putBackSearch(this);search_input.origPlaceholder=searchState.input.placeholder;search_input.placeholder=\"Type your search here.\";loadSearch()});search_input.addEventListener(\"blur\",function(){search_input.placeholder=searchState.input.origPlaceholder});if(search_input.value!=''){loadSearch()}searchState.addCrateDropdown(window.ALL_CRATES);var params=searchState.getQueryStringParams();if(params.search!==undefined){var search=searchState.outputElement();search.innerHTML=\"<h3 class=\\\"search-loading\\\">\"+searchState.loadingText+\"</h3>\";searchState.showResults(search);loadSearch()}},addCrateDropdown:function(crates){var elem=document.getElementById(\"crate-search\");if(!elem){return}var savedCrate=getSettingValue(\"saved-filter-crate\");for(var i=0,len=crates.length;i<len;++i){var option=document.createElement(\"option\");option.value=crates[i];option.innerText=crates[i];elem.appendChild(option);if(crates[i]===savedCrate){elem.value=savedCrate}}},};function getPageId(){if(window.location.hash){var tmp=window.location.hash.replace(/^#/,\"\");if(tmp.length>0){return tmp}}return null}function showSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){addClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(sidebar){addClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(!filler){var div=document.createElement(\"div\");div.id=\"sidebar-filler\";sidebar.appendChild(div)}}}function hideSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){removeClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];removeClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(filler){filler.remove()}document.getElementsByTagName(\"body\")[0].style.marginTop=\"\"}var toggleAllDocsId=\"toggle-all-docs\";var main=document.getElementById(MAIN_ID);var savedHash=\"\";function handleHashes(ev){var elem;var search=searchState.outputElement();if(ev!==null&&search&&!hasClass(search,\"hidden\")&&ev.newURL){searchState.hideResults(search);var hash=ev.newURL.slice(ev.newURL.indexOf(\"#\")+1);if(searchState.browserSupportsHistoryApi()){history.replaceState(hash,\"\",getNakedUrl()+window.location.search+\"#\"+hash)}elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}if(savedHash!==window.location.hash){savedHash=window.location.hash;if(savedHash.length===0){return}expandSection(savedHash.slice(1))}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName===\"DETAILS\"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function getHelpElement(build){if(build){buildHelperPopup()}return document.getElementById(\"help\")}function displayHelp(display,ev,help){if(display){help=help?help:getHelpElement(true);if(hasClass(help,\"hidden\")){ev.preventDefault();removeClass(help,\"hidden\");addClass(document.body,\"blur\")}}else{help=help?help:getHelpElement(false);if(help&&!hasClass(help,\"hidden\")){ev.preventDefault();addClass(help,\"hidden\");removeClass(document.body,\"blur\")}}}function handleEscape(ev){var help=getHelpElement(false);var search=searchState.outputElement();if(help&&!hasClass(help,\"hidden\")){displayHelp(false,ev,help)}else if(search&&!hasClass(search,\"hidden\")){searchState.clearInputTimeout();ev.preventDefault();searchState.hideResults(search)}searchState.defocus();hideThemeButtonState()}var disableShortcuts=getSettingValue(\"disable-shortcuts\")===\"true\";function handleShortcut(ev){if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName===\"INPUT\"){switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break;case\"s\":case\"S\":displayHelp(false,ev);ev.preventDefault();searchState.focus();break;case\"+\":case\"-\":ev.preventDefault();toggleAllDocs();break;case\"?\":displayHelp(true,ev);break;case\"t\":case\"T\":displayHelp(false,ev);ev.preventDefault();var themePicker=getThemePickerElement();themePicker.click();themePicker.focus();break;default:if(getThemePickerElement().parentNode.contains(ev.target)){handleThemeKeyDown(ev)}}}}function handleThemeKeyDown(ev){var active=document.activeElement;var themes=getThemesElement();switch(getVirtualKey(ev)){case\"ArrowUp\":ev.preventDefault();if(active.previousElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.previousElementSibling.focus()}else{showThemeButtonState();themes.lastElementChild.focus()}break;case\"ArrowDown\":ev.preventDefault();if(active.nextElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.nextElementSibling.focus()}else{showThemeButtonState();themes.firstElementChild.focus()}break;case\"Enter\":case\"Return\":case\"Space\":if(ev.target.id===THEME_PICKER_ELEMENT_ID&&themes.style.display===\"none\"){ev.preventDefault();showThemeButtonState();themes.firstElementChild.focus()}break;case\"Home\":ev.preventDefault();themes.firstElementChild.focus();break;case\"End\":ev.preventDefault();themes.lastElementChild.focus();break}}document.addEventListener(\"keypress\",handleShortcut);document.addEventListener(\"keydown\",handleShortcut);(function(){var x=document.getElementsByClassName(\"version-selector\");if(x.length>0){x[0].onchange=function(){var i,match,url=document.location.href,stripped=\"\",len=window.rootPath.match(/\\.\\.\\//g).length+1;for(i=0;i<len;++i){match=url.match(/\\/[^/]*$/);if(i<len-1){stripped=match[0]+stripped}url=url.substring(0,url.length-match[0].length)}var selectedVersion=document.getElementsByClassName(\"version-selector\")[0].value;url+=\"/\"+selectedVersion+stripped;document.location.href=url}}}());window.initSidebarItems=function(items){var sidebar=document.getElementsByClassName(\"sidebar-elems\")[0];var others;var current=window.sidebarCurrent;function addSidebarCrates(crates){if(!hasClass(document.body,\"crate\")){return}var div=document.createElement(\"div\");div.className=\"block crate\";div.innerHTML=\"<h3>Crates</h3>\";var ul=document.createElement(\"ul\");div.appendChild(ul);for(var i=0;i<crates.length;++i){var klass=\"crate\";if(window.rootPath!==\"./\"&&crates[i]===window.currentCrate){klass+=\" current\"}var link=document.createElement(\"a\");link.href=window.rootPath+crates[i]+\"/index.html\";link.className=klass;link.textContent=crates[i];var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}others.appendChild(div)}function block(shortty,longty){var filtered=items[shortty];if(!filtered){return}var div=document.createElement(\"div\");div.className=\"block \"+shortty;var h3=document.createElement(\"h3\");h3.textContent=longty;div.appendChild(h3);var ul=document.createElement(\"ul\");for(var i=0,len=filtered.length;i<len;++i){var item=filtered[i];var name=item[0];var desc=item[1];var klass=shortty;if(name===current.name&&shortty===current.ty){klass+=\" current\"}var path;if(shortty===\"mod\"){path=name+\"/index.html\"}else{path=shortty+\".\"+name+\".html\"}var link=document.createElement(\"a\");link.href=current.relpath+path;link.title=desc;link.className=klass;link.textContent=name;var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);others.appendChild(div)}if(sidebar){others=document.createElement(\"div\");others.className=\"others\";sidebar.appendChild(others);var isModule=hasClass(document.body,\"mod\");if(!isModule){block(\"primitive\",\"Primitive Types\");block(\"mod\",\"Modules\");block(\"macro\",\"Macros\");block(\"struct\",\"Structs\");block(\"enum\",\"Enums\");block(\"union\",\"Unions\");block(\"constant\",\"Constants\");block(\"static\",\"Statics\");block(\"trait\",\"Traits\");block(\"fn\",\"Functions\");block(\"type\",\"Type Definitions\");block(\"foreigntype\",\"Foreign Types\");block(\"keyword\",\"Keywords\");block(\"traitalias\",\"Trait Aliases\")}addSidebarCrates(window.ALL_CRATES)}};window.register_implementors=function(imp){var implementors=document.getElementById(\"implementors-list\");var synthetic_implementors=document.getElementById(\"synthetic-implementors-list\");if(synthetic_implementors){var inlined_types=new Set();onEachLazy(synthetic_implementors.getElementsByClassName(\"impl\"),function(el){var aliases=el.getAttribute(\"data-aliases\");if(!aliases){return}aliases.split(\",\").forEach(function(alias){inlined_types.add(alias)})})}var currentNbImpls=implementors.getElementsByClassName(\"impl\").length;var traitName=document.querySelector(\"h1.fqn > .in-band > .trait\").textContent;var baseIdName=\"impl-\"+traitName+\"-\";var libs=Object.getOwnPropertyNames(imp);for(var i=0,llength=libs.length;i<llength;++i){if(libs[i]===window.currentCrate){continue}var structs=imp[libs[i]];struct_loop:for(var j=0,slength=structs.length;j<slength;++j){var struct=structs[j];var list=struct.synthetic?synthetic_implementors:implementors;if(struct.synthetic){for(var k=0,stlength=struct.types.length;k<stlength;k++){if(inlined_types.has(struct.types[k])){continue struct_loop}inlined_types.add(struct.types[k])}}var code=document.createElement(\"h3\");code.innerHTML=struct.text;addClass(code,\"code-header\");addClass(code,\"in-band\");onEachLazy(code.getElementsByTagName(\"a\"),function(elem){var href=elem.getAttribute(\"href\");if(href&&href.indexOf(\"http\")!==0){elem.setAttribute(\"href\",window.rootPath+href)}});var currentId=baseIdName+currentNbImpls;var anchor=document.createElement(\"a\");anchor.href=\"#\"+currentId;addClass(anchor,\"anchor\");var display=document.createElement(\"div\");display.id=currentId;addClass(display,\"impl\");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return\"+\"}return\"\\u2212\"}function toggleAllDocs(){var innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}var sectionIsCollapsed=false;if(hasClass(innerToggle,\"will-expand\")){removeClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hasClass(e,\"type-contents-toggle\")){e.open=true}});innerToggle.title=\"collapse all docs\"}else{addClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(e.parentNode.id!==MAIN_ID||(!hasClass(e,\"implementors-toggle\")&&!hasClass(e,\"type-contents-toggle\"))){e.open=false}});sectionIsCollapsed=true;innerToggle.title=\"expand all docs\"}innerToggle.children[0].innerText=labelForToggleButton(sectionIsCollapsed)}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}(function(){var toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}var hideMethodDocs=getSettingValue(\"auto-hide-method-docs\")===\"true\";var hideImplementations=getSettingValue(\"auto-hide-trait-implementations\")===\"true\";var hideLargeItemContents=getSettingValue(\"auto-hide-large-items\")!==\"false\";function setImplementorsTogglesOpen(id,open){var list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName(\"implementors-toggle\"),function(e){e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen(\"trait-implementations-list\",false);setImplementorsTogglesOpen(\"blanket-implementations-list\",false)}onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hideLargeItemContents&&hasClass(e,\"type-contents-toggle\")){e.open=true}if(hideMethodDocs&&hasClass(e,\"method-toggle\")){e.open=false}});var pageId=getPageId();if(pageId!==null){expandSection(pageId)}}());(function(){var lineNumbersFunc=function(){};if(getSettingValue(\"line-numbers\")===\"true\"){lineNumbersFunc=function(x){var count=x.textContent.split(\"\\n\").length;var elems=[];for(var i=0;i<count;++i){elems.push(i+1)}var node=document.createElement(\"pre\");addClass(node,\"line-number\");node.innerHTML=elems.join(\"\\n\");x.parentNode.insertBefore(node,x)}}onEachLazy(document.getElementsByClassName(\"rust-example-rendered\"),function(e){if(hasClass(e,\"compile_fail\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#f00\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}else if(hasClass(e,\"ignore\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#ff9200\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}lineNumbersFunc(e)})}());function handleClick(id,f){var elem=document.getElementById(id);if(elem){elem.addEventListener(\"click\",f)}}handleClick(\"help-button\",function(ev){displayHelp(true,ev)});onEachLazy(document.getElementsByTagName(\"a\"),function(el){if(el.hash){el.addEventListener(\"click\",function(){expandSection(el.hash.slice(1))})}});onEachLazy(document.querySelectorAll(\".rustdoc-toggle > summary:not(.hideme)\"),function(el){el.addEventListener(\"click\",function(e){if(e.target.tagName!=\"SUMMARY\"&&e.target.tagName!=\"A\"){e.preventDefault()}})});onEachLazy(document.getElementsByClassName(\"notable-traits\"),function(e){e.onclick=function(){this.getElementsByClassName('notable-traits-tooltiptext')[0].classList.toggle(\"force-tooltip\")}});var sidebar_menu=document.getElementsByClassName(\"sidebar-menu\")[0];if(sidebar_menu){sidebar_menu.onclick=function(){var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(hasClass(sidebar,\"mobile\")){hideSidebar()}else{showSidebar()}}}var buildHelperPopup=function(){var popup=document.createElement(\"aside\");addClass(popup,\"hidden\");popup.id=\"help\";popup.addEventListener(\"click\",function(ev){if(ev.target===popup){displayHelp(false,ev)}});var book_info=document.createElement(\"span\");book_info.className=\"top\";book_info.innerHTML=\"You can find more information in \\\n", "file_path": "docs/main.js", "rank": 21, "score": 26606.84602212633 }, { "content": "if(!String.prototype.startsWith){String.prototype.startsWith=function(searchString,position){position=position||0;return this.indexOf(searchString,position)===position}}if(!String.prototype.endsWith){String.prototype.endsWith=function(suffix,length){var l=length||this.length;return this.indexOf(suffix,l-suffix.length)!==-1}}if(!DOMTokenList.prototype.add){DOMTokenList.prototype.add=function(className){if(className&&!hasClass(this,className)){if(this.className&&this.className.length>0){this.className+=\" \"+className}else{this.className=className}}}}if(!DOMTokenList.prototype.remove){DOMTokenList.prototype.remove=function(className){if(className&&this.className){this.className=(\" \"+this.className+\" \").replace(\" \"+className+\" \",\" \").trim()}}}function getVar(name){var el=document.getElementById(\"rustdoc-vars\");if(el){return el.attributes[\"data-\"+name].value}else{return null}}function resourcePath(basename,extension){return getVar(\"root-path\")+basename+getVar(\"resource-suffix\")+extension}(function(){window.rootPath=getVar(\"root-path\");window.currentCrate=getVar(\"current-crate\");window.searchJS=resourcePath(\"search\",\".js\");window.searchIndexJS=resourcePath(\"search-index\",\".js\");var sidebarVars=document.getElementById(\"sidebar-vars\");if(sidebarVars){window.sidebarCurrent={name:sidebarVars.attributes[\"data-name\"].value,ty:sidebarVars.attributes[\"data-ty\"].value,relpath:sidebarVars.attributes[\"data-relpath\"].value,}}}());function getVirtualKey(ev){if(\"key\"in ev&&typeof ev.key!=\"undefined\"){return ev.key}var c=ev.charCode||ev.keyCode;if(c==27){return\"Escape\"}return String.fromCharCode(c)}var THEME_PICKER_ELEMENT_ID=\"theme-picker\";var THEMES_ELEMENT_ID=\"theme-choices\";var MAIN_ID=\"main-content\";function getThemesElement(){return document.getElementById(THEMES_ELEMENT_ID)}function getThemePickerElement(){return document.getElementById(THEME_PICKER_ELEMENT_ID)}function getNakedUrl(){return window.location.href.split(\"?\")[0].split(\"#\")[0]}function showThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"block\";themePicker.style.borderBottomRightRadius=\"0\";themePicker.style.borderBottomLeftRadius=\"0\"}function hideThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"none\";themePicker.style.borderBottomRightRadius=\"3px\";themePicker.style.borderBottomLeftRadius=\"3px\"}(function(){var themeChoices=getThemesElement();var themePicker=getThemePickerElement();var availableThemes=getVar(\"themes\").split(\",\");function switchThemeButtonState(){if(themeChoices.style.display===\"block\"){hideThemeButtonState()}else{showThemeButtonState()}}function handleThemeButtonsBlur(e){var active=document.activeElement;var related=e.relatedTarget;if(active.id!==THEME_PICKER_ELEMENT_ID&&(!active.parentNode||active.parentNode.id!==THEMES_ELEMENT_ID)&&(!related||(related.id!==THEME_PICKER_ELEMENT_ID&&(!related.parentNode||related.parentNode.id!==THEMES_ELEMENT_ID)))){hideThemeButtonState()}}themePicker.onclick=switchThemeButtonState;themePicker.onblur=handleThemeButtonsBlur;availableThemes.forEach(function(item){var but=document.createElement(\"button\");but.textContent=item;but.onclick=function(){switchTheme(window.currentTheme,window.mainTheme,item,true);useSystemTheme(false)};but.onblur=handleThemeButtonsBlur;themeChoices.appendChild(but)})}());(function(){\"use strict\";window.searchState={loadingText:\"Loading search results...\",input:document.getElementsByClassName(\"search-input\")[0],outputElement:function(){return document.getElementById(\"search\")},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:function(){if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},focus:function(){searchState.input.focus()},defocus:function(){searchState.input.blur()},showResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(main,\"hidden\");removeClass(search,\"hidden\");searchState.mouseMovedAfterSearch=false;document.title=searchState.title},hideResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(search,\"hidden\");removeClass(main,\"hidden\");document.title=searchState.titleBeforeSearch;if(searchState.browserSupportsHistoryApi()){history.replaceState(\"\",window.currentCrate+\" - Rust\",getNakedUrl()+window.location.hash)}},getQueryStringParams:function(){var params={};window.location.search.substring(1).split(\"&\").map(function(s){var pair=s.split(\"=\");params[decodeURIComponent(pair[0])]=typeof pair[1]===\"undefined\"?null:decodeURIComponent(pair[1])});return params},putBackSearch:function(search_input){var search=searchState.outputElement();if(search_input.value!==\"\"&&hasClass(search,\"hidden\")){searchState.showResults(search);if(searchState.browserSupportsHistoryApi()){var extra=\"?search=\"+encodeURIComponent(search_input.value);history.replaceState(search_input.value,\"\",getNakedUrl()+extra+window.location.hash)}document.title=searchState.title}},browserSupportsHistoryApi:function(){return window.history&&typeof window.history.pushState===\"function\"},setup:function(){var search_input=searchState.input;if(!searchState.input){return}function loadScript(url){var script=document.createElement('script');script.src=url;document.head.append(script)}var searchLoaded=false;function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(window.searchJS);loadScript(window.searchIndexJS)}}search_input.addEventListener(\"focus\",function(){searchState.putBackSearch(this);search_input.origPlaceholder=searchState.input.placeholder;search_input.placeholder=\"Type your search here.\";loadSearch()});search_input.addEventListener(\"blur\",function(){search_input.placeholder=searchState.input.origPlaceholder});if(search_input.value!=''){loadSearch()}searchState.addCrateDropdown(window.ALL_CRATES);var params=searchState.getQueryStringParams();if(params.search!==undefined){var search=searchState.outputElement();search.innerHTML=\"<h3 class=\\\"search-loading\\\">\"+searchState.loadingText+\"</h3>\";searchState.showResults(search);loadSearch()}},addCrateDropdown:function(crates){var elem=document.getElementById(\"crate-search\");if(!elem){return}var savedCrate=getSettingValue(\"saved-filter-crate\");for(var i=0,len=crates.length;i<len;++i){var option=document.createElement(\"option\");option.value=crates[i];option.innerText=crates[i];elem.appendChild(option);if(crates[i]===savedCrate){elem.value=savedCrate}}},};function getPageId(){if(window.location.hash){var tmp=window.location.hash.replace(/^#/,\"\");if(tmp.length>0){return tmp}}return null}function showSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){addClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(sidebar){addClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(!filler){var div=document.createElement(\"div\");div.id=\"sidebar-filler\";sidebar.appendChild(div)}}}function hideSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){removeClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];removeClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(filler){filler.remove()}document.getElementsByTagName(\"body\")[0].style.marginTop=\"\"}var toggleAllDocsId=\"toggle-all-docs\";var main=document.getElementById(MAIN_ID);var savedHash=\"\";function handleHashes(ev){var elem;var search=searchState.outputElement();if(ev!==null&&search&&!hasClass(search,\"hidden\")&&ev.newURL){searchState.hideResults(search);var hash=ev.newURL.slice(ev.newURL.indexOf(\"#\")+1);if(searchState.browserSupportsHistoryApi()){history.replaceState(hash,\"\",getNakedUrl()+window.location.search+\"#\"+hash)}elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}if(savedHash!==window.location.hash){savedHash=window.location.hash;if(savedHash.length===0){return}expandSection(savedHash.slice(1))}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName===\"DETAILS\"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function getHelpElement(build){if(build){buildHelperPopup()}return document.getElementById(\"help\")}function displayHelp(display,ev,help){if(display){help=help?help:getHelpElement(true);if(hasClass(help,\"hidden\")){ev.preventDefault();removeClass(help,\"hidden\");addClass(document.body,\"blur\")}}else{help=help?help:getHelpElement(false);if(help&&!hasClass(help,\"hidden\")){ev.preventDefault();addClass(help,\"hidden\");removeClass(document.body,\"blur\")}}}function handleEscape(ev){var help=getHelpElement(false);var search=searchState.outputElement();if(help&&!hasClass(help,\"hidden\")){displayHelp(false,ev,help)}else if(search&&!hasClass(search,\"hidden\")){searchState.clearInputTimeout();ev.preventDefault();searchState.hideResults(search)}searchState.defocus();hideThemeButtonState()}var disableShortcuts=getSettingValue(\"disable-shortcuts\")===\"true\";function handleShortcut(ev){if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName===\"INPUT\"){switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break;case\"s\":case\"S\":displayHelp(false,ev);ev.preventDefault();searchState.focus();break;case\"+\":case\"-\":ev.preventDefault();toggleAllDocs();break;case\"?\":displayHelp(true,ev);break;case\"t\":case\"T\":displayHelp(false,ev);ev.preventDefault();var themePicker=getThemePickerElement();themePicker.click();themePicker.focus();break;default:if(getThemePickerElement().parentNode.contains(ev.target)){handleThemeKeyDown(ev)}}}}function handleThemeKeyDown(ev){var active=document.activeElement;var themes=getThemesElement();switch(getVirtualKey(ev)){case\"ArrowUp\":ev.preventDefault();if(active.previousElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.previousElementSibling.focus()}else{showThemeButtonState();themes.lastElementChild.focus()}break;case\"ArrowDown\":ev.preventDefault();if(active.nextElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.nextElementSibling.focus()}else{showThemeButtonState();themes.firstElementChild.focus()}break;case\"Enter\":case\"Return\":case\"Space\":if(ev.target.id===THEME_PICKER_ELEMENT_ID&&themes.style.display===\"none\"){ev.preventDefault();showThemeButtonState();themes.firstElementChild.focus()}break;case\"Home\":ev.preventDefault();themes.firstElementChild.focus();break;case\"End\":ev.preventDefault();themes.lastElementChild.focus();break}}document.addEventListener(\"keypress\",handleShortcut);document.addEventListener(\"keydown\",handleShortcut);(function(){var x=document.getElementsByClassName(\"version-selector\");if(x.length>0){x[0].onchange=function(){var i,match,url=document.location.href,stripped=\"\",len=window.rootPath.match(/\\.\\.\\//g).length+1;for(i=0;i<len;++i){match=url.match(/\\/[^/]*$/);if(i<len-1){stripped=match[0]+stripped}url=url.substring(0,url.length-match[0].length)}var selectedVersion=document.getElementsByClassName(\"version-selector\")[0].value;url+=\"/\"+selectedVersion+stripped;document.location.href=url}}}());window.initSidebarItems=function(items){var sidebar=document.getElementsByClassName(\"sidebar-elems\")[0];var others;var current=window.sidebarCurrent;function addSidebarCrates(crates){if(!hasClass(document.body,\"crate\")){return}var div=document.createElement(\"div\");div.className=\"block crate\";div.innerHTML=\"<h3>Crates</h3>\";var ul=document.createElement(\"ul\");div.appendChild(ul);for(var i=0;i<crates.length;++i){var klass=\"crate\";if(window.rootPath!==\"./\"&&crates[i]===window.currentCrate){klass+=\" current\"}var link=document.createElement(\"a\");link.href=window.rootPath+crates[i]+\"/index.html\";link.className=klass;link.textContent=crates[i];var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}others.appendChild(div)}function block(shortty,longty){var filtered=items[shortty];if(!filtered){return}var div=document.createElement(\"div\");div.className=\"block \"+shortty;var h3=document.createElement(\"h3\");h3.textContent=longty;div.appendChild(h3);var ul=document.createElement(\"ul\");for(var i=0,len=filtered.length;i<len;++i){var item=filtered[i];var name=item[0];var desc=item[1];var klass=shortty;if(name===current.name&&shortty===current.ty){klass+=\" current\"}var path;if(shortty===\"mod\"){path=name+\"/index.html\"}else{path=shortty+\".\"+name+\".html\"}var link=document.createElement(\"a\");link.href=current.relpath+path;link.title=desc;link.className=klass;link.textContent=name;var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);others.appendChild(div)}if(sidebar){others=document.createElement(\"div\");others.className=\"others\";sidebar.appendChild(others);var isModule=hasClass(document.body,\"mod\");if(!isModule){block(\"primitive\",\"Primitive Types\");block(\"mod\",\"Modules\");block(\"macro\",\"Macros\");block(\"struct\",\"Structs\");block(\"enum\",\"Enums\");block(\"union\",\"Unions\");block(\"constant\",\"Constants\");block(\"static\",\"Statics\");block(\"trait\",\"Traits\");block(\"fn\",\"Functions\");block(\"type\",\"Type Definitions\");block(\"foreigntype\",\"Foreign Types\");block(\"keyword\",\"Keywords\");block(\"traitalias\",\"Trait Aliases\")}addSidebarCrates(window.ALL_CRATES)}};window.register_implementors=function(imp){var implementors=document.getElementById(\"implementors-list\");var synthetic_implementors=document.getElementById(\"synthetic-implementors-list\");if(synthetic_implementors){var inlined_types=new Set();onEachLazy(synthetic_implementors.getElementsByClassName(\"impl\"),function(el){var aliases=el.getAttribute(\"data-aliases\");if(!aliases){return}aliases.split(\",\").forEach(function(alias){inlined_types.add(alias)})})}var currentNbImpls=implementors.getElementsByClassName(\"impl\").length;var traitName=document.querySelector(\"h1.fqn > .in-band > .trait\").textContent;var baseIdName=\"impl-\"+traitName+\"-\";var libs=Object.getOwnPropertyNames(imp);for(var i=0,llength=libs.length;i<llength;++i){if(libs[i]===window.currentCrate){continue}var structs=imp[libs[i]];struct_loop:for(var j=0,slength=structs.length;j<slength;++j){var struct=structs[j];var list=struct.synthetic?synthetic_implementors:implementors;if(struct.synthetic){for(var k=0,stlength=struct.types.length;k<stlength;k++){if(inlined_types.has(struct.types[k])){continue struct_loop}inlined_types.add(struct.types[k])}}var code=document.createElement(\"h3\");code.innerHTML=struct.text;addClass(code,\"code-header\");addClass(code,\"in-band\");onEachLazy(code.getElementsByTagName(\"a\"),function(elem){var href=elem.getAttribute(\"href\");if(href&&href.indexOf(\"http\")!==0){elem.setAttribute(\"href\",window.rootPath+href)}});var currentId=baseIdName+currentNbImpls;var anchor=document.createElement(\"a\");anchor.href=\"#\"+currentId;addClass(anchor,\"anchor\");var display=document.createElement(\"div\");display.id=currentId;addClass(display,\"impl\");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return\"+\"}return\"\\u2212\"}function toggleAllDocs(){var innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}var sectionIsCollapsed=false;if(hasClass(innerToggle,\"will-expand\")){removeClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hasClass(e,\"type-contents-toggle\")){e.open=true}});innerToggle.title=\"collapse all docs\"}else{addClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(e.parentNode.id!==MAIN_ID||(!hasClass(e,\"implementors-toggle\")&&!hasClass(e,\"type-contents-toggle\"))){e.open=false}});sectionIsCollapsed=true;innerToggle.title=\"expand all docs\"}innerToggle.children[0].innerText=labelForToggleButton(sectionIsCollapsed)}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}(function(){var toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}var hideMethodDocs=getSettingValue(\"auto-hide-method-docs\")===\"true\";var hideImplementations=getSettingValue(\"auto-hide-trait-implementations\")===\"true\";var hideLargeItemContents=getSettingValue(\"auto-hide-large-items\")!==\"false\";function setImplementorsTogglesOpen(id,open){var list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName(\"implementors-toggle\"),function(e){e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen(\"trait-implementations-list\",false);setImplementorsTogglesOpen(\"blanket-implementations-list\",false)}onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hideLargeItemContents&&hasClass(e,\"type-contents-toggle\")){e.open=true}if(hideMethodDocs&&hasClass(e,\"method-toggle\")){e.open=false}});var pageId=getPageId();if(pageId!==null){expandSection(pageId)}}());(function(){var lineNumbersFunc=function(){};if(getSettingValue(\"line-numbers\")===\"true\"){lineNumbersFunc=function(x){var count=x.textContent.split(\"\\n\").length;var elems=[];for(var i=0;i<count;++i){elems.push(i+1)}var node=document.createElement(\"pre\");addClass(node,\"line-number\");node.innerHTML=elems.join(\"\\n\");x.parentNode.insertBefore(node,x)}}onEachLazy(document.getElementsByClassName(\"rust-example-rendered\"),function(e){if(hasClass(e,\"compile_fail\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#f00\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}else if(hasClass(e,\"ignore\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#ff9200\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}lineNumbersFunc(e)})}());function handleClick(id,f){var elem=document.getElementById(id);if(elem){elem.addEventListener(\"click\",f)}}handleClick(\"help-button\",function(ev){displayHelp(true,ev)});onEachLazy(document.getElementsByTagName(\"a\"),function(el){if(el.hash){el.addEventListener(\"click\",function(){expandSection(el.hash.slice(1))})}});onEachLazy(document.querySelectorAll(\".rustdoc-toggle > summary:not(.hideme)\"),function(el){el.addEventListener(\"click\",function(e){if(e.target.tagName!=\"SUMMARY\"&&e.target.tagName!=\"A\"){e.preventDefault()}})});onEachLazy(document.getElementsByClassName(\"notable-traits\"),function(e){e.onclick=function(){this.getElementsByClassName('notable-traits-tooltiptext')[0].classList.toggle(\"force-tooltip\")}});var sidebar_menu=document.getElementsByClassName(\"sidebar-menu\")[0];if(sidebar_menu){sidebar_menu.onclick=function(){var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(hasClass(sidebar,\"mobile\")){hideSidebar()}else{showSidebar()}}}var buildHelperPopup=function(){var popup=document.createElement(\"aside\");addClass(popup,\"hidden\");popup.id=\"help\";popup.addEventListener(\"click\",function(ev){if(ev.target===popup){displayHelp(false,ev)}});var book_info=document.createElement(\"span\");book_info.className=\"top\";book_info.innerHTML=\"You can find more information in \\\n", "file_path": "docs/main.js", "rank": 22, "score": 25977.055935938915 }, { "content": "if(!String.prototype.startsWith){String.prototype.startsWith=function(searchString,position){position=position||0;return this.indexOf(searchString,position)===position}}if(!String.prototype.endsWith){String.prototype.endsWith=function(suffix,length){var l=length||this.length;return this.indexOf(suffix,l-suffix.length)!==-1}}if(!DOMTokenList.prototype.add){DOMTokenList.prototype.add=function(className){if(className&&!hasClass(this,className)){if(this.className&&this.className.length>0){this.className+=\" \"+className}else{this.className=className}}}}if(!DOMTokenList.prototype.remove){DOMTokenList.prototype.remove=function(className){if(className&&this.className){this.className=(\" \"+this.className+\" \").replace(\" \"+className+\" \",\" \").trim()}}}function getVar(name){var el=document.getElementById(\"rustdoc-vars\");if(el){return el.attributes[\"data-\"+name].value}else{return null}}function resourcePath(basename,extension){return getVar(\"root-path\")+basename+getVar(\"resource-suffix\")+extension}(function(){window.rootPath=getVar(\"root-path\");window.currentCrate=getVar(\"current-crate\");window.searchJS=resourcePath(\"search\",\".js\");window.searchIndexJS=resourcePath(\"search-index\",\".js\");var sidebarVars=document.getElementById(\"sidebar-vars\");if(sidebarVars){window.sidebarCurrent={name:sidebarVars.attributes[\"data-name\"].value,ty:sidebarVars.attributes[\"data-ty\"].value,relpath:sidebarVars.attributes[\"data-relpath\"].value,}}}());function getVirtualKey(ev){if(\"key\"in ev&&typeof ev.key!=\"undefined\"){return ev.key}var c=ev.charCode||ev.keyCode;if(c==27){return\"Escape\"}return String.fromCharCode(c)}var THEME_PICKER_ELEMENT_ID=\"theme-picker\";var THEMES_ELEMENT_ID=\"theme-choices\";var MAIN_ID=\"main-content\";function getThemesElement(){return document.getElementById(THEMES_ELEMENT_ID)}function getThemePickerElement(){return document.getElementById(THEME_PICKER_ELEMENT_ID)}function getNakedUrl(){return window.location.href.split(\"?\")[0].split(\"#\")[0]}function showThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"block\";themePicker.style.borderBottomRightRadius=\"0\";themePicker.style.borderBottomLeftRadius=\"0\"}function hideThemeButtonState(){var themePicker=getThemePickerElement();var themeChoices=getThemesElement();themeChoices.style.display=\"none\";themePicker.style.borderBottomRightRadius=\"3px\";themePicker.style.borderBottomLeftRadius=\"3px\"}(function(){var themeChoices=getThemesElement();var themePicker=getThemePickerElement();var availableThemes=getVar(\"themes\").split(\",\");function switchThemeButtonState(){if(themeChoices.style.display===\"block\"){hideThemeButtonState()}else{showThemeButtonState()}}function handleThemeButtonsBlur(e){var active=document.activeElement;var related=e.relatedTarget;if(active.id!==THEME_PICKER_ELEMENT_ID&&(!active.parentNode||active.parentNode.id!==THEMES_ELEMENT_ID)&&(!related||(related.id!==THEME_PICKER_ELEMENT_ID&&(!related.parentNode||related.parentNode.id!==THEMES_ELEMENT_ID)))){hideThemeButtonState()}}themePicker.onclick=switchThemeButtonState;themePicker.onblur=handleThemeButtonsBlur;availableThemes.forEach(function(item){var but=document.createElement(\"button\");but.textContent=item;but.onclick=function(){switchTheme(window.currentTheme,window.mainTheme,item,true);useSystemTheme(false)};but.onblur=handleThemeButtonsBlur;themeChoices.appendChild(but)})}());(function(){\"use strict\";window.searchState={loadingText:\"Loading search results...\",input:document.getElementsByClassName(\"search-input\")[0],outputElement:function(){return document.getElementById(\"search\")},title:document.title,titleBeforeSearch:document.title,timeout:null,currentTab:0,focusedByTab:[null,null,null],clearInputTimeout:function(){if(searchState.timeout!==null){clearTimeout(searchState.timeout);searchState.timeout=null}},focus:function(){searchState.input.focus()},defocus:function(){searchState.input.blur()},showResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(main,\"hidden\");removeClass(search,\"hidden\");searchState.mouseMovedAfterSearch=false;document.title=searchState.title},hideResults:function(search){if(search===null||typeof search==='undefined'){search=searchState.outputElement()}addClass(search,\"hidden\");removeClass(main,\"hidden\");document.title=searchState.titleBeforeSearch;if(searchState.browserSupportsHistoryApi()){history.replaceState(\"\",window.currentCrate+\" - Rust\",getNakedUrl()+window.location.hash)}},getQueryStringParams:function(){var params={};window.location.search.substring(1).split(\"&\").map(function(s){var pair=s.split(\"=\");params[decodeURIComponent(pair[0])]=typeof pair[1]===\"undefined\"?null:decodeURIComponent(pair[1])});return params},putBackSearch:function(search_input){var search=searchState.outputElement();if(search_input.value!==\"\"&&hasClass(search,\"hidden\")){searchState.showResults(search);if(searchState.browserSupportsHistoryApi()){var extra=\"?search=\"+encodeURIComponent(search_input.value);history.replaceState(search_input.value,\"\",getNakedUrl()+extra+window.location.hash)}document.title=searchState.title}},browserSupportsHistoryApi:function(){return window.history&&typeof window.history.pushState===\"function\"},setup:function(){var search_input=searchState.input;if(!searchState.input){return}function loadScript(url){var script=document.createElement('script');script.src=url;document.head.append(script)}var searchLoaded=false;function loadSearch(){if(!searchLoaded){searchLoaded=true;loadScript(window.searchJS);loadScript(window.searchIndexJS)}}search_input.addEventListener(\"focus\",function(){searchState.putBackSearch(this);search_input.origPlaceholder=searchState.input.placeholder;search_input.placeholder=\"Type your search here.\";loadSearch()});search_input.addEventListener(\"blur\",function(){search_input.placeholder=searchState.input.origPlaceholder});if(search_input.value!=''){loadSearch()}searchState.addCrateDropdown(window.ALL_CRATES);var params=searchState.getQueryStringParams();if(params.search!==undefined){var search=searchState.outputElement();search.innerHTML=\"<h3 class=\\\"search-loading\\\">\"+searchState.loadingText+\"</h3>\";searchState.showResults(search);loadSearch()}},addCrateDropdown:function(crates){var elem=document.getElementById(\"crate-search\");if(!elem){return}var savedCrate=getSettingValue(\"saved-filter-crate\");for(var i=0,len=crates.length;i<len;++i){var option=document.createElement(\"option\");option.value=crates[i];option.innerText=crates[i];elem.appendChild(option);if(crates[i]===savedCrate){elem.value=savedCrate}}},};function getPageId(){if(window.location.hash){var tmp=window.location.hash.replace(/^#/,\"\");if(tmp.length>0){return tmp}}return null}function showSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){addClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(sidebar){addClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(!filler){var div=document.createElement(\"div\");div.id=\"sidebar-filler\";sidebar.appendChild(div)}}}function hideSidebar(){var elems=document.getElementsByClassName(\"sidebar-elems\")[0];if(elems){removeClass(elems,\"show-it\")}var sidebar=document.getElementsByClassName(\"sidebar\")[0];removeClass(sidebar,\"mobile\");var filler=document.getElementById(\"sidebar-filler\");if(filler){filler.remove()}document.getElementsByTagName(\"body\")[0].style.marginTop=\"\"}var toggleAllDocsId=\"toggle-all-docs\";var main=document.getElementById(MAIN_ID);var savedHash=\"\";function handleHashes(ev){var elem;var search=searchState.outputElement();if(ev!==null&&search&&!hasClass(search,\"hidden\")&&ev.newURL){searchState.hideResults(search);var hash=ev.newURL.slice(ev.newURL.indexOf(\"#\")+1);if(searchState.browserSupportsHistoryApi()){history.replaceState(hash,\"\",getNakedUrl()+window.location.search+\"#\"+hash)}elem=document.getElementById(hash);if(elem){elem.scrollIntoView()}}if(savedHash!==window.location.hash){savedHash=window.location.hash;if(savedHash.length===0){return}expandSection(savedHash.slice(1))}}function onHashChange(ev){hideSidebar();handleHashes(ev)}function openParentDetails(elem){while(elem){if(elem.tagName===\"DETAILS\"){elem.open=true}elem=elem.parentNode}}function expandSection(id){openParentDetails(document.getElementById(id))}function getHelpElement(build){if(build){buildHelperPopup()}return document.getElementById(\"help\")}function displayHelp(display,ev,help){if(display){help=help?help:getHelpElement(true);if(hasClass(help,\"hidden\")){ev.preventDefault();removeClass(help,\"hidden\");addClass(document.body,\"blur\")}}else{help=help?help:getHelpElement(false);if(help&&!hasClass(help,\"hidden\")){ev.preventDefault();addClass(help,\"hidden\");removeClass(document.body,\"blur\")}}}function handleEscape(ev){var help=getHelpElement(false);var search=searchState.outputElement();if(help&&!hasClass(help,\"hidden\")){displayHelp(false,ev,help)}else if(search&&!hasClass(search,\"hidden\")){searchState.clearInputTimeout();ev.preventDefault();searchState.hideResults(search)}searchState.defocus();hideThemeButtonState()}var disableShortcuts=getSettingValue(\"disable-shortcuts\")===\"true\";function handleShortcut(ev){if(ev.ctrlKey||ev.altKey||ev.metaKey||disableShortcuts){return}if(document.activeElement.tagName===\"INPUT\"){switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break}}else{switch(getVirtualKey(ev)){case\"Escape\":handleEscape(ev);break;case\"s\":case\"S\":displayHelp(false,ev);ev.preventDefault();searchState.focus();break;case\"+\":case\"-\":ev.preventDefault();toggleAllDocs();break;case\"?\":displayHelp(true,ev);break;case\"t\":case\"T\":displayHelp(false,ev);ev.preventDefault();var themePicker=getThemePickerElement();themePicker.click();themePicker.focus();break;default:if(getThemePickerElement().parentNode.contains(ev.target)){handleThemeKeyDown(ev)}}}}function handleThemeKeyDown(ev){var active=document.activeElement;var themes=getThemesElement();switch(getVirtualKey(ev)){case\"ArrowUp\":ev.preventDefault();if(active.previousElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.previousElementSibling.focus()}else{showThemeButtonState();themes.lastElementChild.focus()}break;case\"ArrowDown\":ev.preventDefault();if(active.nextElementSibling&&ev.target.id!==THEME_PICKER_ELEMENT_ID){active.nextElementSibling.focus()}else{showThemeButtonState();themes.firstElementChild.focus()}break;case\"Enter\":case\"Return\":case\"Space\":if(ev.target.id===THEME_PICKER_ELEMENT_ID&&themes.style.display===\"none\"){ev.preventDefault();showThemeButtonState();themes.firstElementChild.focus()}break;case\"Home\":ev.preventDefault();themes.firstElementChild.focus();break;case\"End\":ev.preventDefault();themes.lastElementChild.focus();break}}document.addEventListener(\"keypress\",handleShortcut);document.addEventListener(\"keydown\",handleShortcut);(function(){var x=document.getElementsByClassName(\"version-selector\");if(x.length>0){x[0].onchange=function(){var i,match,url=document.location.href,stripped=\"\",len=window.rootPath.match(/\\.\\.\\//g).length+1;for(i=0;i<len;++i){match=url.match(/\\/[^/]*$/);if(i<len-1){stripped=match[0]+stripped}url=url.substring(0,url.length-match[0].length)}var selectedVersion=document.getElementsByClassName(\"version-selector\")[0].value;url+=\"/\"+selectedVersion+stripped;document.location.href=url}}}());window.initSidebarItems=function(items){var sidebar=document.getElementsByClassName(\"sidebar-elems\")[0];var others;var current=window.sidebarCurrent;function addSidebarCrates(crates){if(!hasClass(document.body,\"crate\")){return}var div=document.createElement(\"div\");div.className=\"block crate\";div.innerHTML=\"<h3>Crates</h3>\";var ul=document.createElement(\"ul\");div.appendChild(ul);for(var i=0;i<crates.length;++i){var klass=\"crate\";if(window.rootPath!==\"./\"&&crates[i]===window.currentCrate){klass+=\" current\"}var link=document.createElement(\"a\");link.href=window.rootPath+crates[i]+\"/index.html\";link.className=klass;link.textContent=crates[i];var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}others.appendChild(div)}function block(shortty,longty){var filtered=items[shortty];if(!filtered){return}var div=document.createElement(\"div\");div.className=\"block \"+shortty;var h3=document.createElement(\"h3\");h3.textContent=longty;div.appendChild(h3);var ul=document.createElement(\"ul\");for(var i=0,len=filtered.length;i<len;++i){var item=filtered[i];var name=item[0];var desc=item[1];var klass=shortty;if(name===current.name&&shortty===current.ty){klass+=\" current\"}var path;if(shortty===\"mod\"){path=name+\"/index.html\"}else{path=shortty+\".\"+name+\".html\"}var link=document.createElement(\"a\");link.href=current.relpath+path;link.title=desc;link.className=klass;link.textContent=name;var li=document.createElement(\"li\");li.appendChild(link);ul.appendChild(li)}div.appendChild(ul);others.appendChild(div)}if(sidebar){others=document.createElement(\"div\");others.className=\"others\";sidebar.appendChild(others);var isModule=hasClass(document.body,\"mod\");if(!isModule){block(\"primitive\",\"Primitive Types\");block(\"mod\",\"Modules\");block(\"macro\",\"Macros\");block(\"struct\",\"Structs\");block(\"enum\",\"Enums\");block(\"union\",\"Unions\");block(\"constant\",\"Constants\");block(\"static\",\"Statics\");block(\"trait\",\"Traits\");block(\"fn\",\"Functions\");block(\"type\",\"Type Definitions\");block(\"foreigntype\",\"Foreign Types\");block(\"keyword\",\"Keywords\");block(\"traitalias\",\"Trait Aliases\")}addSidebarCrates(window.ALL_CRATES)}};window.register_implementors=function(imp){var implementors=document.getElementById(\"implementors-list\");var synthetic_implementors=document.getElementById(\"synthetic-implementors-list\");if(synthetic_implementors){var inlined_types=new Set();onEachLazy(synthetic_implementors.getElementsByClassName(\"impl\"),function(el){var aliases=el.getAttribute(\"data-aliases\");if(!aliases){return}aliases.split(\",\").forEach(function(alias){inlined_types.add(alias)})})}var currentNbImpls=implementors.getElementsByClassName(\"impl\").length;var traitName=document.querySelector(\"h1.fqn > .in-band > .trait\").textContent;var baseIdName=\"impl-\"+traitName+\"-\";var libs=Object.getOwnPropertyNames(imp);for(var i=0,llength=libs.length;i<llength;++i){if(libs[i]===window.currentCrate){continue}var structs=imp[libs[i]];struct_loop:for(var j=0,slength=structs.length;j<slength;++j){var struct=structs[j];var list=struct.synthetic?synthetic_implementors:implementors;if(struct.synthetic){for(var k=0,stlength=struct.types.length;k<stlength;k++){if(inlined_types.has(struct.types[k])){continue struct_loop}inlined_types.add(struct.types[k])}}var code=document.createElement(\"h3\");code.innerHTML=struct.text;addClass(code,\"code-header\");addClass(code,\"in-band\");onEachLazy(code.getElementsByTagName(\"a\"),function(elem){var href=elem.getAttribute(\"href\");if(href&&href.indexOf(\"http\")!==0){elem.setAttribute(\"href\",window.rootPath+href)}});var currentId=baseIdName+currentNbImpls;var anchor=document.createElement(\"a\");anchor.href=\"#\"+currentId;addClass(anchor,\"anchor\");var display=document.createElement(\"div\");display.id=currentId;addClass(display,\"impl\");display.appendChild(anchor);display.appendChild(code);list.appendChild(display);currentNbImpls+=1}}};if(window.pending_implementors){window.register_implementors(window.pending_implementors)}function labelForToggleButton(sectionIsCollapsed){if(sectionIsCollapsed){return\"+\"}return\"\\u2212\"}function toggleAllDocs(){var innerToggle=document.getElementById(toggleAllDocsId);if(!innerToggle){return}var sectionIsCollapsed=false;if(hasClass(innerToggle,\"will-expand\")){removeClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hasClass(e,\"type-contents-toggle\")){e.open=true}});innerToggle.title=\"collapse all docs\"}else{addClass(innerToggle,\"will-expand\");onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(e.parentNode.id!==MAIN_ID||(!hasClass(e,\"implementors-toggle\")&&!hasClass(e,\"type-contents-toggle\"))){e.open=false}});sectionIsCollapsed=true;innerToggle.title=\"expand all docs\"}innerToggle.children[0].innerText=labelForToggleButton(sectionIsCollapsed)}function insertAfter(newNode,referenceNode){referenceNode.parentNode.insertBefore(newNode,referenceNode.nextSibling)}(function(){var toggles=document.getElementById(toggleAllDocsId);if(toggles){toggles.onclick=toggleAllDocs}var hideMethodDocs=getSettingValue(\"auto-hide-method-docs\")===\"true\";var hideImplementations=getSettingValue(\"auto-hide-trait-implementations\")===\"true\";var hideLargeItemContents=getSettingValue(\"auto-hide-large-items\")!==\"false\";function setImplementorsTogglesOpen(id,open){var list=document.getElementById(id);if(list!==null){onEachLazy(list.getElementsByClassName(\"implementors-toggle\"),function(e){e.open=open})}}if(hideImplementations){setImplementorsTogglesOpen(\"trait-implementations-list\",false);setImplementorsTogglesOpen(\"blanket-implementations-list\",false)}onEachLazy(document.getElementsByClassName(\"rustdoc-toggle\"),function(e){if(!hideLargeItemContents&&hasClass(e,\"type-contents-toggle\")){e.open=true}if(hideMethodDocs&&hasClass(e,\"method-toggle\")){e.open=false}});var pageId=getPageId();if(pageId!==null){expandSection(pageId)}}());(function(){var lineNumbersFunc=function(){};if(getSettingValue(\"line-numbers\")===\"true\"){lineNumbersFunc=function(x){var count=x.textContent.split(\"\\n\").length;var elems=[];for(var i=0;i<count;++i){elems.push(i+1)}var node=document.createElement(\"pre\");addClass(node,\"line-number\");node.innerHTML=elems.join(\"\\n\");x.parentNode.insertBefore(node,x)}}onEachLazy(document.getElementsByClassName(\"rust-example-rendered\"),function(e){if(hasClass(e,\"compile_fail\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#f00\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}else if(hasClass(e,\"ignore\")){e.addEventListener(\"mouseover\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"#ff9200\"});e.addEventListener(\"mouseout\",function(){this.parentElement.previousElementSibling.childNodes[0].style.color=\"\"})}lineNumbersFunc(e)})}());function handleClick(id,f){var elem=document.getElementById(id);if(elem){elem.addEventListener(\"click\",f)}}handleClick(\"help-button\",function(ev){displayHelp(true,ev)});onEachLazy(document.getElementsByTagName(\"a\"),function(el){if(el.hash){el.addEventListener(\"click\",function(){expandSection(el.hash.slice(1))})}});onEachLazy(document.querySelectorAll(\".rustdoc-toggle > summary:not(.hideme)\"),function(el){el.addEventListener(\"click\",function(e){if(e.target.tagName!=\"SUMMARY\"&&e.target.tagName!=\"A\"){e.preventDefault()}})});onEachLazy(document.getElementsByClassName(\"notable-traits\"),function(e){e.onclick=function(){this.getElementsByClassName('notable-traits-tooltiptext')[0].classList.toggle(\"force-tooltip\")}});var sidebar_menu=document.getElementsByClassName(\"sidebar-menu\")[0];if(sidebar_menu){sidebar_menu.onclick=function(){var sidebar=document.getElementsByClassName(\"sidebar\")[0];if(hasClass(sidebar,\"mobile\")){hideSidebar()}else{showSidebar()}}}var buildHelperPopup=function(){var popup=document.createElement(\"aside\");addClass(popup,\"hidden\");popup.id=\"help\";popup.addEventListener(\"click\",function(ev){if(ev.target===popup){displayHelp(false,ev)}});var book_info=document.createElement(\"span\");book_info.className=\"top\";book_info.innerHTML=\"You can find more information in \\\n", "file_path": "docs/main.js", "rank": 23, "score": 25376.390999500734 }, { "content": "# File formats\n\n\n\nAll scripts in this software package accept fastq files and print fastq files, unless otherwise noted. When the reads are paired end, this software package reads interleaved fastq files and prints them. All input and output files must be uncompressed.\n\n\n\n## Interleaved fastq\n\n\n\nThe interleaved fastq format is where the first read of a pair (R1) is immediately followed by its pair (R2). Normally, R1 and R2 are \"split\" into separate files. For example using the test data in this repository:\n\n\n\n $ cat testdata/four_reads.pe.fastq | perl -lane 'print if($i++ % 2 == 0);'\n\n @read0/1\n\n +\n\n @read0/2\n\n +\n\n @read1/1\n\n +\n\n @read1/2\n\n +\n\n @read2/1\n\n +\n\n @read2/2\n\n +\n\n @read3/1\n\n +\n\n @read3/2\n\n +\n\n\n", "file_path": "docs-md/file-formats.md", "rank": 24, "score": 22399.232870317872 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/fmt/trait.Debug.html\\\" title=\\\"trait core::fmt::Debug\\\">Debug</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":false,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/fmt/trait.Debug.html\\\" title=\\\"trait core::fmt::Debug\\\">Debug</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":false,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/fmt/trait.Debug.js", "rank": 25, "score": 21002.215085965396 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; Freeze for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: Freeze,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl Freeze for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Freeze.html\\\" title=\\\"trait core::marker::Freeze\\\">Freeze</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Freeze.html\\\" title=\\\"trait core::marker::Freeze\\\">Freeze</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/marker/trait.Freeze.js", "rank": 26, "score": 21002.215085965396 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Sync.html\\\" title=\\\"trait core::marker::Sync\\\">Sync</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Sync.html\\\" title=\\\"trait core::marker::Sync\\\">Sync</a>,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Sync.html\\\" title=\\\"trait core::marker::Sync\\\">Sync</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Sync.html\\\" title=\\\"trait core::marker::Sync\\\">Sync</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Sync.html\\\" title=\\\"trait core::marker::Sync\\\">Sync</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/marker/trait.Sync.js", "rank": 27, "score": 21002.215085965396 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Send.html\\\" title=\\\"trait core::marker::Send\\\">Send</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Send.html\\\" title=\\\"trait core::marker::Send\\\">Send</a>,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Send.html\\\" title=\\\"trait core::marker::Send\\\">Send</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Send.html\\\" title=\\\"trait core::marker::Send\\\">Send</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Send.html\\\" title=\\\"trait core::marker::Send\\\">Send</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/marker/trait.Send.js", "rank": 28, "score": 21002.215085965396 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/clone/trait.Clone.html\\\" title=\\\"trait core::clone::Clone\\\">Clone</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":false,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/clone/trait.Clone.html\\\" title=\\\"trait core::clone::Clone\\\">Clone</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":false,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/clone/trait.Clone.html\\\" title=\\\"trait core::clone::Clone\\\">Clone</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":false,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/clone/trait.Clone.js", "rank": 29, "score": 21002.215085965396 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Unpin.html\\\" title=\\\"trait core::marker::Unpin\\\">Unpin</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Unpin.html\\\" title=\\\"trait core::marker::Unpin\\\">Unpin</a>,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Unpin.html\\\" title=\\\"trait core::marker::Unpin\\\">Unpin</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Unpin.html\\\" title=\\\"trait core::marker::Unpin\\\">Unpin</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/marker/trait.Unpin.html\\\" title=\\\"trait core::marker::Unpin\\\">Unpin</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/marker/trait.Unpin.js", "rank": 30, "score": 21002.215085965396 }, { "content": "initSidebarItems({\"struct\":[[\"Seq\",\"A sequence struct that contains the ID, sequence, and quality cigar line\"]],\"trait\":[[\"Cleanable\",\"A sequence that can be cleaned\"]]});", "file_path": "docs/fasten/io/seq/sidebar-items.js", "rank": 31, "score": 20783.507941081683 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.UnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::UnwindSafe\\\">UnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.UnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::UnwindSafe\\\">UnwindSafe</a>,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.UnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::UnwindSafe\\\">UnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.UnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::UnwindSafe\\\">UnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.UnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::UnwindSafe\\\">UnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/panic/unwind_safe/trait.UnwindSafe.js", "rank": 32, "score": 19840.741585203275 }, { "content": "(function() {var implementors = {};\n\nimplementors[\"fasten\"] = [{\"text\":\"impl&lt;R&gt; <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.RefUnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::RefUnwindSafe\\\">RefUnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/fastq/struct.FastqReader.html\\\" title=\\\"struct fasten::io::fastq::FastqReader\\\">FastqReader</a>&lt;R&gt; <span class=\\\"where fmt-newline\\\">where<br>&nbsp;&nbsp;&nbsp;&nbsp;R: <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.RefUnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::RefUnwindSafe\\\">RefUnwindSafe</a>,&nbsp;</span>\",\"synthetic\":true,\"types\":[\"fasten::io::fastq::FastqReader\"]},{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.RefUnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::RefUnwindSafe\\\">RefUnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten/io/seq/struct.Seq.html\\\" title=\\\"struct fasten::io::seq::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten::io::seq::Seq\"]}];\n\nimplementors[\"fasten_convert\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.RefUnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::RefUnwindSafe\\\">RefUnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten_convert/struct.FastenSeq.html\\\" title=\\\"struct fasten_convert::FastenSeq\\\">FastenSeq</a>\",\"synthetic\":true,\"types\":[\"fasten_convert::FastenSeq\"]}];\n\nimplementors[\"fasten_sort\"] = [{\"text\":\"impl <a class=\\\"trait\\\" href=\\\"https://doc.rust-lang.org/1.59.0/core/panic/unwind_safe/trait.RefUnwindSafe.html\\\" title=\\\"trait core::panic::unwind_safe::RefUnwindSafe\\\">RefUnwindSafe</a> for <a class=\\\"struct\\\" href=\\\"fasten_sort/struct.Seq.html\\\" title=\\\"struct fasten_sort::Seq\\\">Seq</a>\",\"synthetic\":true,\"types\":[\"fasten_sort::Seq\"]}];\n", "file_path": "docs/implementors/core/panic/unwind_safe/trait.RefUnwindSafe.js", "rank": 33, "score": 19481.61471609005 }, { "content": " \n\n // burn the plus sign\n\n let mut _plus = String::new();\n\n self.reader.read_line(&mut _plus).expect(\"ERROR: plus sign line not found\");\n\n\n\n self.reader.read_line(&mut qual).expect(\"ERROR: could not read qual line\");\n\n\n\n let seq = Seq::new(&id, &seq, &qual);\n\n\n\n return Some(seq)\n\n }\n\n // Read a fastq entry in the most correct way possible,\n\n // allowing for whitespace in seq and qual lines.\n\n else {\n\n let whitespace_regex = Regex::new(r\"(\\s+)\").expect(\"malformed regex\");\n\n\n\n let mut id= String::new();\n\n let mut seq= String::new();\n\n let mut qual= String::new();\n\n\n", "file_path": "src/io/fastq.rs", "rank": 34, "score": 15.273199488213507 }, { "content": " let mut id= String::new();\n\n let mut seq= String::new();\n\n let mut qual= String::new();\n\n\n\n // Read the ID of the entry\n\n match self.reader.read_line(&mut id) {\n\n Ok(n) => {\n\n // if we're expecting an ID line, but\n\n // there are zero bytes read, then we are\n\n // at the end of the file. Break.\n\n if n < 1 {\n\n return None;\n\n }\n\n }\n\n Err(error) => {\n\n panic!(\"ERROR: could not read the ID line: {}\",error);\n\n }\n\n };\n\n\n\n self.reader.read_line(&mut seq).expect(\"ERROR: could not read sequence line\");\n", "file_path": "src/io/fastq.rs", "rank": 35, "score": 14.03698936785026 }, { "content": " }\n\n }\n\n pub fn new_careful(reader: R) -> FastqReader<R> {\n\n FastqReader {\n\n reader : BufReader::new(reader),\n\n quickly: false,\n\n }\n\n }\n\n}\n\n\n\nimpl<R: Read> Iterator for FastqReader<R> {\n\n type Item = Seq;\n\n\n\n /// There are two flavors of next: either read \n\n /// quickly or read carefully, depending on the \n\n /// 'quickly' bool.\n\n fn next(&mut self) -> Option<Seq> {\n\n // Read a fastq entry but assume that there are only\n\n // four lines per entry (id, seq, plus, qual).\n\n if self.quickly {\n", "file_path": "src/io/fastq.rs", "rank": 36, "score": 13.551180759110384 }, { "content": " let read_length :usize=seq.len(); \n\n \n\n // build onto the qual line until it has the right\n\n // number of bytes.\n\n 'qual: loop{\n\n let mut buf = String::new();\n\n match self.reader.read_line(&mut buf) {\n\n Ok(n) => {\n\n if n < 1 {\n\n panic!(\"ERROR: incomplete entry (no qual line), seqid {}\\nbuf {}\", id.trim(),buf);\n\n }\n\n else {\n\n qual.push_str(&buf);\n\n }\n\n qual = whitespace_regex.replace_all(&qual,\"\").into_owned();\n\n if qual.len() >= read_length {\n\n break 'qual;\n\n }\n\n }\n\n Err(error) => {\n", "file_path": "src/io/fastq.rs", "rank": 37, "score": 10.814055694310595 }, { "content": " panic!(\"ERROR while reading qual for ID {}: {}\",buf.trim(),error);\n\n }\n\n }\n\n }\n\n\n\n let seq = Seq::new(&id, &seq, &qual);\n\n return Some(seq)\n\n }\n\n }\n\n\n\n}\n\n\n", "file_path": "src/io/fastq.rs", "rank": 38, "score": 10.44366071374246 }, { "content": "//! ```\n\n\n\nextern crate regex;\n\nextern crate statistical;\n\nextern crate getopts;\n\nuse std::env;\n\nuse std::path::Path;\n\n\n\nuse getopts::Options;\n\nuse getopts::Matches;\n\n\n\n/// input/output methods\n\npub mod io;\n\n\n\nconst VERSION: &'static str = env!(\"CARGO_PKG_VERSION\");\n\n\n\n/// Have some strings that can be printed which could be\n\n/// used to propagate errors between piped scripts.\n\n\n\n/// Invalid fastq ID (no @)\n\nstatic INVALID_ID :&'static str= \"invalid_id\";\n\n/// Invalid sequence (underscore)\n\nstatic INVALID_SEQ :&'static str= \"invalid_seq\";\n\n/// Invalid plus line (no +)\n\nstatic INVALID_PLUS:&'static str= \"invalid_plus\";\n\n/// Invalid qual line (~ is chr 126 when the normal max number is 40)\n\nstatic INVALID_QUAL:&'static str= \"invalid_qual\";\n\n\n\n/// Propagate an error by printing invalid read(s)\n", "file_path": "src/lib.rs", "rank": 39, "score": 10.352400797781664 }, { "content": "use std::io;\n\nuse std::io::prelude::*;\n\nuse std::io::BufReader;\n\nuse io::seq::Seq;\n\nuse io::seq::Cleanable;\n\n\n\nuse regex::Regex;\n\n\n\n#[test]\n\n/// Test whether we can read the test data carefully.\n", "file_path": "src/io/fastq.rs", "rank": 40, "score": 10.283323564851411 }, { "content": " // Read the ID of the entry\n\n match self.reader.read_line(&mut id) {\n\n Ok(n) => {\n\n // if we're expecting an ID line, but\n\n // there are zero bytes read, then we are\n\n // at the end of the file. Break.\n\n if n < 1 {\n\n return None;\n\n }\n\n }\n\n Err(error) => {\n\n panic!(\"ERROR: {}\",error);\n\n }\n\n \n\n }\n\n // Read the DNA line of the entry and count\n\n // how long it is.\n\n 'dna: loop{\n\n let mut buf = String::new();\n\n match self.reader.read_line(&mut buf) {\n", "file_path": "src/io/fastq.rs", "rank": 41, "score": 8.364410972756481 }, { "content": " Ok(n) => {\n\n if n < 1 {\n\n panic!(\"ERROR: incomplete entry (no seq line), seqid {}\\nbuf {}\", id.trim(),buf);\n\n }\n\n // if we hit the qual line, then it is a single\n\n // character, +\n\n else if &buf[0..1] == \"+\" {\n\n break 'dna;\n\n }\n\n else {\n\n seq.push_str(&buf);\n\n }\n\n }\n\n Err(error) => {\n\n panic!(\"ERROR while reading seq for ID {}: {}\",id.trim(),error);\n\n }\n\n }\n\n }\n\n // remove all whitespace\n\n seq = whitespace_regex.replace_all(&seq,\"\").into_owned();\n", "file_path": "src/io/fastq.rs", "rank": 42, "score": 6.857681345032271 }, { "content": "# Materials\n\n\n\nWe leveraged the Cargo packaging system in Rust to create a basic framework for interleaved fastq file manipulation.\n\nEach executable reads from `stdin` and prints reads to `stdout` and only performs one function at a time.\n\nThe core executables perform these fundamental functions:\n\n1) converting to and from interleaved format, \n\n2) converting to and from other sequence file formats,\n\n3) 'straightening' fastq files to a more standard 4-line-per-entry format.\n\n\n\nThere are 18 executables including but not limited to read metrics, read cleaning, kmer counting, read validation, and regular expressions for interleaved fastq files.\n\n\n\nWe have also taken advantage of Rust to make comprehensive documentation, available at lskatz.github.io/lskatz/fasten/fasten. Continuous integration was implemented in GitHub Actions for unit testing, containerizing, and benchmarking. Benchmarking was performed against other mainstream packages using `hyperfine` using 100 replicates and 2 burn-ins.\n\n\n\n# Results\n\n\n\nDocumentation, the container, and code are available at github.com/lskatz/fasten.\n\n\n\n[!Six benchmarks. From left to right, then to bottom: Searching for a sequence in a fastq file with either `seqkit grep` or `fasten_regex`; downsampling reads using either `fasten sample` or `seqtk sample`; interleaving reads from R1 and R2 files not using `fasten_progress`, using it before shuffle, or using it after shuffle; sorting fastq entries by sequence with `fasten_sort` or `seqkit sort`; sorting sequences by id; and converting nonstandard fastq files to a format whose entries are four lines each.](benchmarks.png)\n\n\n", "file_path": "paper/immem.md", "rank": 43, "score": 5.733300204418754 }, { "content": "pub mod fastq;\n\npub mod seq;\n\n\n", "file_path": "src/io/mod.rs", "rank": 44, "score": 5.517005506921723 }, { "content": "[![Crates.io](https://img.shields.io/badge/crates.io-v0.1-green.svg)](https://crates.io/crates/fasten)\n\n\n\n# Fasten\n\n\n\nPerform random operations on fastq files, using unix streaming. Secure your analysis with Fasten!\n\n\n\n## Synopsis\n\n\n\n### read metrics\n\n \n\n $ cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | fasten_metrics | column -t\n\n totalLength numReads avgReadLength avgQual\n\n 800 8 100 19.53875\n\n\n\n### read cleaning\n\n\n\n $ cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | \\\n\n fasten_clean --paired-end --min-length 2 | \\\n\n gzip -c > cleaned.shuffled.fastq.gz\n\n\n\n $ zcat cleaned.shuffled.fastq.gz | fasten_metrics | column -t\n\n totalLength numReads avgReadLength avgQual\n\n 800 8 100 19.53875\n\n # No reads were actually filtered with cleaning, with --min-length=2\n\n\n\n_etc_\n\n\n\n## Installation\n\n\n\nFasten is programmed in the Rust programming language. More information about Rust, including installation and the executable `cargo`, can be found at [rust-lang.org](https://www.rust-lang.org).\n\n\n\nAfter downloading, use the Rust executable `cargo` like so:\n\n\n\n cd fasten\n\n cargo build --release\n\n export PATH=$PATH:$(pwd)/fasten/target/release\n\n\n\nAll executables will be in the directory `fasten/target/release`.\n\n\n\n## General usage\n\n\n\nAll scripts accept the parameters, read uncompressed fastq format from stdin, and print uncompressed fastq format to stdout. All paired end fastq files must be in interleaved format, and they are written in [interleaved format](./docs/file-formats.md), except when deshuffling with `fasten_shuffle`.\n\n\n\n* `--help`\n\n* `--numcpus` Not all scripts will take advantage of numcpus. (not currently implemented)\n\n* `--paired-end` Input reads are interleaved paired end\n\n* `--verbose` Print more status messages\n\n\n\n## Documentation\n\n\n\nPlease see the inline documentation at https://lskatz.github.io/fasten/fasten\n\n\n\nThis documentation was built with `cargo docs --no-deps`\n\n\n", "file_path": "README.md", "rank": 45, "score": 3.984795599386783 }, { "content": "## Mutate a genome\n\n\n\nAlthough you could mutate a fastq file randomly with `fasten_mutate --snps`,\n\nit would be too random and would only cause a messy pileup or assembly\n\ndownstream.\n\n\n\nAlso, you might want to mutate a genome assembly. However, that is not why\n\nyou are browsing the fasten package. This package is for raw reads\n\nand not assemblies.\n\n\n\nFor raw reads, it might be smarter to mutate certain loci, represented by kmers in the genome.\n\nIn this case, we use `fasten_replace` in a loop.\n\nThis example is mostly untested and so please test it before using it in production.\n\n\n\n k=15\n\n read_len=250-1;\n\n NTs=\"ATCG\"\n\n for kmer in $kmer_array; do \n\n echo -ne . >&2 # progress bar\n\n pos=$(shuf -i 1-$read_len -n 1)\n\n nt=${NT:$(shuf -i 0-3 -n 1):1} \n\n replace_str=${kmer:0:$pos}$nt${kmer:$(($pos+1))}\n\n zcat $interleaved | \\\n\n fasten_replace --paired-end --find $kmer --replace $replace_str --which SEQ |\\\n\n gzip -c > $interleaved.tmp && mv $interleaved.tmp $interleaved;\n\n done \n\n echo >&2 # finish the progress bar\n\n\n", "file_path": "docs-md/one-liners.md", "rank": 46, "score": 3.660617966303529 }, { "content": "---\n\ntitle: 'Fasten with Pipes'\n\ntags:\n\n - command line\n\n - fastq manipulation\n\n - interleaved fastq\n\nauthors:\n\n - name: Lee S. Katz\n\n affiliation: \"1, 2\"\n\n orcid: 0000-0002-2533-9161\n\n - name: Henk C. den Bakker\n\n orcid: 0000-0002-4086-1580\n\n affiliation: 1\n\naffiliations:\n\n - name: Enteric Diseases Laboratory Branch (EDLB), Centers for Disease Control and Prevention, Atlanta, GA, USA\n\n index: 1\n\n - name: Center for Food Safety, University of Georgia, Griffin, GA, USA\n\n index: 2\n\nbibliography: paper.bib\n\n---\n\n\n\n# Background\n\n\n\nThere are still many gaps for basic bioinformatics on the command line for basic file formats.\n\nHistorically for fastq files, bioinformaticians have been able to use many different tools such as `seqkit`, `seqtk` or FASTX-Toolkit.\n\nWhen considering one genome sample and a set of paired end reads, it can be confusing or overwhelming to have two files per sample.\n\nTherefore, some bioinformaticians have used the interleaved fastq file format.\n\nHowever, it is not well supported in mainstream tools.\n\nHere, we provide Fasten to the community to address these needs.\n\n\n", "file_path": "paper/immem.md", "rank": 47, "score": 3.1908275881351402 }, { "content": "Copyright 2014-2021 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.\n\n\n\nThis Font Software is licensed under the SIL Open Font License, Version 1.1.\n\n\n\nThis license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL\n\n\n\n\n\n-----------------------------------------------------------\n\nSIL OPEN FONT LICENSE Version 1.1 - 26 February 2007\n\n-----------------------------------------------------------\n\n\n\nPREAMBLE\n\nThe goals of the Open Font License (OFL) are to stimulate worldwide\n\ndevelopment of collaborative font projects, to support the font creation\n\nefforts of academic and linguistic communities, and to provide a free and\n\nopen framework in which fonts may be shared and improved in partnership\n\nwith others.\n\n\n\nThe OFL allows the licensed fonts to be used, studied, modified and\n\nredistributed freely as long as they are not sold by themselves. The\n\nfonts, including any derivative works, can be bundled, embedded,\n\nredistributed and/or sold with any software provided that any reserved\n\nnames are not used by derivative works. The fonts and derivatives,\n\nhowever, cannot be released under any other type of license. The\n\nrequirement for fonts to remain under this license does not apply\n\nto any document created using the fonts or their derivatives.\n\n\n\nDEFINITIONS\n\n\"Font Software\" refers to the set of files released by the Copyright\n\nHolder(s) under this license and clearly marked as such. This may\n\ninclude source files, build scripts and documentation.\n\n\n\n\"Reserved Font Name\" refers to any names specified as such after the\n\ncopyright statement(s).\n\n\n\n\"Original Version\" refers to the collection of Font Software components as\n\ndistributed by the Copyright Holder(s).\n\n\n\n\"Modified Version\" refers to any derivative made by adding to, deleting,\n\nor substituting -- in part or in whole -- any of the components of the\n\nOriginal Version, by changing formats or by porting the Font Software to a\n", "file_path": "docs/SourceSerif4-LICENSE.md", "rank": 48, "score": 3.0551342689112477 }, { "content": "//! Perform random operations on fastq files, using unix streaming.\n\n//! Secure your analysis with Fasten!\n\n//! # Synopsis\n\n//! ## read metrics\n\n//! ```text\n\n//! \n\n//! $ cat testdata/R1.fastq testdata/R2.fastq | \\\n\n//! fasten_shuffle | fasten_metrics | column -t\n\n//! totalLength numReads avgReadLength avgQual\n\n//! 800 8 100 19.53875\n\n//! ```\n\n//! \n\n//! ## read cleaning\n\n//!\n\n//! ```text\n\n//! $ cat testdata/R1.fastq testdata/R2.fastq | \\\n\n//! fasten_shuffle | \\\n\n//! fasten_clean --paired-end --min-length 2 | \\\n\n//! gzip -c > cleaned.shuffled.fastq.gz\n\n//! \n", "file_path": "src/lib.rs", "rank": 49, "score": 2.7524666473703263 }, { "content": "## Adapter discovery\n\n\n\nWhat adapters are being used for your reads? Maybe you should trim them! Many adapters are 19mers but they can be different lengths.\n\n\n\n zcat file.fastq.gz | \\\n\n fasten_trimmer --last-base 19 | \\\n\n fasten_kmer --kmer-length 19 | \\\n\n sort -k2,2nr | head -n 1\n\n\n\n => ATCGGAAGAGCACACGTCT\t146\n\n\n\nOr why not just try many kmer lengths?\n\n\n\n for length in $(seq 6 65); do \n\n zcat file.fastq.gz | \\\n\n fasten_trimmer --last-base $length | \\\n\n fasten_kmer --kmer-length $length | \\\n\n sort -k2,2nr | \\\n\n head -n 2; \n\n done;\n\n\n\n => CCGGCG 1623\n\n ...\n\n ATCGGAAGAGCACACGTCTGAACTCCAGTCACGTGGCCTTATCTCGTATGCCGTCTTCTGCTTGA 24\n\n\n\nWant it to go faster by subsampling? Use `fasten_sample --frequency 0.1` to go 10x faster.\n\n\n\n for length in $(seq 6 65); do \n\n zcat file.fastq.gz | \\\n\n fasten_sample --frequency 0.1 |\\\n\n fasten_trimmer --last-base $length | \\\n\n fasten_kmer --kmer-length $length | \\\n\n sort -k2,2nr | \\\n\n head -n 2; \n\n done;\n\n \n\n## Translation to RNA\n\n\n\n zcat dna.fastq.gz | fasten_replace --find 'T' --replace 'U' | \\\n\n gzip -c > rna.fastq.gz\n\n\n\n## Extract a certain motif, keeping paired end reads intact\n\n\n\n zcat file.fastq.gz | fasten_regex --regex 'ATG' --paired-end | \\\n\n gzip -c > start-sites.fastq.gz\n\n\n\nChoose a few different motifs with regex magic\n\n\n\n zcat file.fastq.gz | fasten_regex --regex 'ATG|GTG|TTG' --paired-end | \\\n\n gzip -c > start-sites.fastq.gz\n\n \n\n zcat file.fastq.gz | fasten_regex --regex '[AGT]TG' --paired-end | \\\n\n gzip -c > start-sites.fastq.gz\n\n\n", "file_path": "docs-md/one-liners.md", "rank": 50, "score": 2.381242865402948 }, { "content": "new environment.\n\n\n\n\"Author\" refers to any designer, engineer, programmer, technical\n\nwriter or other person who contributed to the Font Software.\n\n\n\nPERMISSION & CONDITIONS\n\nPermission is hereby granted, free of charge, to any person obtaining\n\na copy of the Font Software, to use, study, copy, merge, embed, modify,\n\nredistribute, and sell modified and unmodified copies of the Font\n\nSoftware, subject to the following conditions:\n\n\n\n1) Neither the Font Software nor any of its individual components,\n\nin Original or Modified Versions, may be sold by itself.\n\n\n\n2) Original or Modified Versions of the Font Software may be bundled,\n\nredistributed and/or sold with any software, provided that each copy\n\ncontains the above copyright notice and this license. These can be\n\nincluded either as stand-alone text files, human-readable headers or\n\nin the appropriate machine-readable metadata fields within text or\n\nbinary files as long as those fields can be easily viewed by the user.\n\n\n\n3) No Modified Version of the Font Software may use the Reserved Font\n\nName(s) unless explicit written permission is granted by the corresponding\n\nCopyright Holder. This restriction only applies to the primary font name as\n\npresented to the users.\n\n\n\n4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font\n\nSoftware shall not be used to promote, endorse or advertise any\n\nModified Version, except to acknowledge the contribution(s) of the\n\nCopyright Holder(s) and the Author(s) or with their explicit written\n\npermission.\n\n\n\n5) The Font Software, modified or unmodified, in part or in whole,\n\nmust be distributed entirely under this license, and must not be\n\ndistributed under any other license. The requirement for fonts to\n\nremain under this license does not apply to any document created\n\nusing the Font Software.\n\n\n\nTERMINATION\n\nThis license becomes null and void if any of the above conditions are\n\nnot met.\n\n\n\nDISCLAIMER\n\nTHE FONT SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF\n\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\n\nOF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE\n\nCOPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n\nINCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL\n\nDAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\nFROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM\n\nOTHER DEALINGS IN THE FONT SOFTWARE.\n", "file_path": "docs/SourceSerif4-LICENSE.md", "rank": 51, "score": 1.93274170933101 }, { "content": "## Other documentation\n\n\n\n* Some workflows are shown in the [one-liners](./docs/one-liners.md) page.\n\n* Some wrapper scripts are noted in the [scripts](./docs/scripts.md) page.\n\n\n\n## Fasten script descriptions\n\n\n\n|script |Description|\n\n|-------------------|-----------|\n\n|[`fasten_clean`](https://lskatz.github.io/fasten/fasten_clean) | Trims and cleans a fastq file.|\n\n|[`fasten_convert`](https://lskatz.github.io/fasten/fasten_convert) | Converts between different sequence formats like fastq, sam, fasta.|\n\n|[`fasten_straighten`](https://lskatz.github.io/fasten/fasten_straighten)| Convert any fastq file to a standard four-line-per-entry format.|\n\n|[`fasten_metrics`](https://lskatz.github.io/fasten/fasten_metrics) | Prints basic read metrics.|\n\n|[`fasten_pe`](https://lskatz.github.io/fasten/fasten_pe) | Determines paired-endedness based on read IDs.|\n\n|[`fasten_randomize`](https://lskatz.github.io/fasten/fasten_randomize) | Randomizes reads from input |\n\n|[`fasten_combine`](https://lskatz.github.io/fasten/fasten_combine) | Combines identical reads and updates quality scores.|\n\n|[`fasten_kmer`](https://lskatz.github.io/fasten/fasten_kmer) | Kmer counting.|\n\n|[`fasten_sample`](https://lskatz.github.io/fasten/fasten_sample) | Downsamples reads.|\n\n|[`fasten_shuffle`](https://lskatz.github.io/fasten/fasten_shuffle) | Shuffles or deshuffles paired end reads.|\n\n|[`fasten_validate`](https://lskatz.github.io/fasten/fasten_validate) | Validates your reads|\n\n|[`fasten_quality_filter`](https://lskatz.github.io/fasten/fasten_quality_filter) | Transforms nucleotides to \"N\" if the quality is low | |\n\n|[`fasten_trim`](https://lskatz.github.io/fasten/fasten_trim) | Blunt-end trims reads | |\n\n|[`fasten_replace`](https://lskatz.github.io/fasten/fasten_replace) | Find and replace using regex | |\n\n|[`fasten_mutate`](https://lskatz.github.io/fasten/fasten_mutate) | introduce random mutations | |\n\n|[`fasten_regex`](https://lskatz.github.io/fasten/fasten_regex) | Filter for reads using regex | |\n\n|[`fasten_progress`](https://lskatz.github.io/fasten/fasten_progress) | Add progress to any place in the pipeline | |\n\n|[`fasten_sort`](https://lskatz.github.io/fasten/fasten_sort) | Sort fastq entries | |\n\n\n", "file_path": "README.md", "rank": 52, "score": 1.8685386961950514 }, { "content": "# Wrapper scripts\n\n\n\nDue to the UNIX-style pipes that this project enforces, it is sometimes necessary to use a wrapper script to bring things together. Here are some included wrapper scripts, located in the scripts directory.\n\n\n\n## Read metrics\n\n\n\nThe script readMetrics.sh runs read metrics on a group of files. Usage: `readMetrics.sh *.fastq[.gz]`.\n\n\n", "file_path": "docs-md/scripts.md", "rank": 53, "score": 1.6452110687059067 }, { "content": "//! $ zcat cleaned.shuffled.fastq.gz | fasten_metrics | column -t\n\n//! totalLength numReads avgReadLength avgQual\n\n//! 800 8 100 19.53875\n\n//! ```\n\n//! _NOTE_: No reads were actually filtered with cleaning, with --min-length=2\n\n//!\n\n//! ## Kmer counting\n\n//! ```text\n\n//! $ cat testdata/R1.fastq | \\\n\n//! fasten_kmer -k 21 > 21mers.tsv\n\n//! ```\n\n//! \n\n//! ## Read sampling\n\n//! ```text\n\n//! $ cat testdata/R1.fastq testdata/R2.fastq | \\\n\n//! fasten_shuffle | \\\n\n//! fasten_sample --paired-end --frequency 0.1 > 10percent.fastq\n\n//! ```\n\n//!\n\n//! # Advanced\n", "file_path": "src/lib.rs", "rank": 54, "score": 1.4087903700971778 }, { "content": "# Conclusions\n\n\n\nFasten is a powerful manipulation suite for interleaved fastq files, written in Rust.\n\nWe benchmarked Fasten on several categories. It did not run faster than other software in some categories\n\nbut it did run fastest when sorting sequences.\n\nWe also tested whether `fasten_progress` slowed computation in certain situations.\n\nWe conclude that creating a progress meter before a blocking operation such as `fasten_shuffle`\n\nadds a substantial delay in computation. When speed is important, a progress meter is better placed after any blocking steps in a pipe.\n\n\n\nFasten touts a comprehensive manual, continuous integration, and integration into the command line with unix pipes.\n\nIt is well poised to be a crucial module for daily work on the command line.\n\n\n\n\n", "file_path": "paper/immem.md", "rank": 55, "score": 1.3407460296737281 }, { "content": "### Interleave split reads and feed directly to the cleaning script \n\n\n\n cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | \\\n\n fasten_clean --min-trim-quality 30\n\n\n\n### Interleave split reads, feed directly to the cleaning script, and then see how well it cleaned the reads\n\n\n\n cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | \\\n\n fasten_clean --min-trim-quality 30 | \\\n\n fasten_metrics --each-read\n\n\n\n### Interleave split reads, randomly print 40% of the reads\n\n\n\n cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | \\\n\n fasten_sample --paired-end --frequency 0.4\n\n\n\n## read cleaning\n\n\n\nFasten cleans reads by trimming and filtering. View those options by running `fasten_clean --help`\n\n\n\n zcat some_file.fastq.gz | \\\n\n fasten_clean --min-trim-quality 30 --min-avg-quality 20 --min-length 50 | \\\n\n gzip -c > cleaned.fastq.gz\n\n\n\n## In-place fastq compression\n\n\n\nThis works by sorting by GC content, which plays into how the gzip algorithm works.\n\n`fasten_shuffle.pl` is used to shuffle the forward and reverse reads and then used to\n\ndeshuffle them. The actual reads remain the same but are sorted differently, yielding\n\nan estimated 10-30% compression gain. Please see this blog for more details. http://thegenomefactory.blogspot.com.au/2012/11/sorting-fastq-files-by-sequence-length.html?m=1\n\n\n\n cat testdata/R1.fastq testdata/R2.fastq | fasten_shuffle | \\\n\n paste - - - - - - - - | \\\n\n perl -F'\\t' -lane '@GC=(\"$F[1]$F[5]\"=~/[GCgc]/g); print join(\"\\t\",scalar(@GC)/length(\"$F[1]$F[5]\"), @F);' | \\\n\n sort -k1,1n | \\\n\n cut -f2- | \\\n\n tr '\\t' '\\n' | \\\n\n fasten_shuffle --deshuffle -1 1.fastq -2 2.fastq\n\n gzip 1.fastq 2.fastq\n\n\n\nNext, run `ls -lhS` on the original and sorted reads to check their size.\n\n\n", "file_path": "docs-md/one-liners.md", "rank": 56, "score": 1.1046655411099882 }, { "content": "# One-liners\n\n<!-- vim-markdown-toc GFM -->\n\n\n\n* [Read metrics for a set of files](#read-metrics-for-a-set-of-files)\n\n* [Generate interleaved reads](#generate-interleaved-reads)\n\n * [Interleave split reads and feed directly to the cleaning script](#interleave-split-reads-and-feed-directly-to-the-cleaning-script)\n\n * [Interleave split reads, feed directly to the cleaning script, and then see how well it cleaned the reads](#interleave-split-reads-feed-directly-to-the-cleaning-script-and-then-see-how-well-it-cleaned-the-reads)\n\n * [Interleave split reads, randomly print 40% of the reads](#interleave-split-reads-randomly-print-40-of-the-reads)\n\n* [read cleaning](#read-cleaning)\n\n* [In-place fastq compression](#in-place-fastq-compression)\n\n* [Adapter discovery](#adapter-discovery)\n\n* [Translation to RNA](#translation-to-rna)\n\n* [Extract a certain motif, keeping paired end reads intact](#extract-a-certain-motif-keeping-paired-end-reads-intact)\n\n* [Mutate a genome](#mutate-a-genome)\n\n\n\n<!-- vim-markdown-toc -->\n\n\n\nThese are random one-liners or similar that make use of Fasten.\n\nSome or many of them are large and so they will be displayed on multiple lines for readability.\n\n\n\nFirst, it might make sense to change your path, for readability. Choose either 'debug' or 'release' at the end of the path, depending on how you compiled Fasten.rs.\n\n\n\n export PATH=$PATH:~/src/Fasten.rs/target/debug\n\n\n\n## Read metrics for a set of files\n\n\n\n for i in *.fastq.gz; do\n\n echo -ne \"$i\\t\";\n\n zcat $i | fasten_metrics\n\n done | sort | uniq | column -t\n\n\n\n## Generate interleaved reads \n\n\n\nMost scripts in Fasten require interleaved reads, and so you should use `fasten_shuffle` to shuffle them. The following example goes a step further with `grep` to help show you that the reads are interleaved.\n\n\n\n cat testdata/R1.fastq testdata/R2.fastq | \\\n\n fasten_shuffle | \\\n\n grep '^@read'\n\n\n", "file_path": "docs-md/one-liners.md", "rank": 57, "score": 1.1010889299065965 } ]
Rust
build/header_generator.rs
u1roh/dxf-rs
76c334dce6bd863b847882a9581b1fdba67d2b68
extern crate xmltree; use self::xmltree::Element; use crate::ExpectedType; use crate::other_helpers::*; use crate::xml_helpers::*; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Write}; use std::iter::Iterator; use std::path::Path; pub fn generate_header(generated_dir: &Path) { let element = load_xml(); let mut fun = String::new(); fun.push_str(" // The contents of this file are automatically generated and should not be modified directly. See the `build` directory. // types from `lib.rs`. use crate::{ CodePair, Color, DxfError, DxfResult, Handle, LineWeight, Point, Vector, }; use crate::code_pair_writer::CodePairWriter; use crate::helper_functions::*; use crate::enums::*; use crate::enum_primitive::FromPrimitive; use std::io::Write; use std::time::Duration; extern crate chrono; use self::chrono::{DateTime, Local, Utc}; extern crate uuid; use self::uuid::Uuid; ".trim_start()); generate_struct(&mut fun, &element); generate_default(&mut fun, &element); fun.push_str("impl Header {\n"); generate_flags(&mut fun, &element); generate_set_defaults(&mut fun, &element); generate_set_header_value(&mut fun, &element); generate_add_code_pairs(&mut fun, &element); fun.push_str("}\n"); let mut file = File::create(generated_dir.join("header.rs")).ok().unwrap(); file.write_all(fun.as_bytes()).ok().unwrap(); } fn generate_struct(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str("/// Contains common properties for the DXF file.\n"); fun.push_str("#[cfg_attr(feature = \"serialize\", derive(Serialize, Deserialize))]\n"); fun.push_str("pub struct Header {\n"); for v in &element.children { let field_name = field(v); if !seen_fields.contains(&field_name) { seen_fields.insert(field_name.clone()); let mut comment = format!("The ${} header variable. {}", name(&v), comment(&v)); if !min_version(&v).is_empty() { comment.push_str(&format!(" Minimum AutoCAD version: {}.", min_version(&v))); } if !max_version(&v).is_empty() { comment.push_str(&format!(" Maximum AutoCAD version: {}.", max_version(&v))); } fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub {field}: {typ},\n", field = field(&v), typ = typ(&v) )); } } fun.push_str("}\n"); fun.push_str("\n"); } fn generate_default(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str("impl Default for Header {\n"); fun.push_str(" fn default() -> Self {\n"); fun.push_str(" Header {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!( " {field}: {default_value}, // ${name}\n", field = field(&v), default_value = default_value(&v), name = name(&v) )); } } fun.push_str(" }\n"); fun.push_str(" }\n"); fun.push_str("}\n"); fun.push_str("\n"); } fn generate_flags(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); if v.children.len() > 0 { fun.push_str(&format!(" // {} flags\n", field(&v))); } for f in &v.children { let mut comment = format!("{}", comment(&f)); if !min_version(&v).is_empty() { comment.push_str(&format!(" Minimum AutoCAD version: {}.", min_version(&v))); } if !max_version(&v).is_empty() { comment.push_str(&format!(" Maximum AutoCAD version: {}.", max_version(&v))); } fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub fn get_{flag}(&self) -> bool {{\n", flag = name(&f) )); fun.push_str(&format!( " self.{field} & {mask} != 0\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub fn set_{flag}(&mut self, val: bool) {{\n", flag = name(&f) )); fun.push_str(&format!(" if val {{\n")); fun.push_str(&format!( " self.{field} |= {mask};\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(" else {\n"); fun.push_str(&format!( " self.{field} &= !{mask};\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(" }\n"); } } } } fn generate_set_defaults(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str(" /// Sets the default values on the header.\n"); fun.push_str(" pub fn set_defaults(&mut self) {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!( " self.{field} = {default_value}; // ${name}\n", field = field(&v), default_value = default_value(&v), name = name(&v) )); } } fun.push_str(" }\n"); } fn generate_set_header_value(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str(" #[allow(clippy::cognitive_complexity)] // generated method\n"); fun.push_str(" pub(crate) fn set_header_value(&mut self, variable: &str, pair: &CodePair) -> DxfResult<()> {\n"); fun.push_str(" match variable {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!(" \"${name}\" => {{", name = name(&v))); let variables_with_name: Vec<&Element> = element .children .iter() .filter(|&vv| name(&vv) == name(&v)) .collect(); if variables_with_name.len() == 1 { fun.push_str(" "); if code(&v) < 0 { fun.push_str(&format!("self.{field}.set(&pair)?;", field = field(&v))); } else { let read_cmd = get_read_command(&v); fun.push_str(&format!( "verify_code(&pair, {code})?; self.{field} = {cmd};", code = code(&v), field = field(&v), cmd = read_cmd )); } fun.push_str(" "); } else { fun.push_str("\n"); fun.push_str(" match pair.code {\n"); let expected_codes: Vec<i32> = variables_with_name.iter().map(|&vv| code(&vv)).collect(); for v in &variables_with_name { let read_cmd = get_read_command(&v); fun.push_str(&format!( " {code} => self.{field} = {cmd},\n", code = code(&v), field = field(&v), cmd = read_cmd )); } fun.push_str(&format!(" _ => return Err(DxfError::UnexpectedCodePair(pair.clone(), String::from(\"expected code {:?}\"))),\n", expected_codes)); fun.push_str(" }\n"); fun.push_str(" "); } fun.push_str("},\n"); } } fun.push_str(" _ => (),\n"); fun.push_str(" }\n"); fun.push_str("\n"); fun.push_str(" Ok(())\n"); fun.push_str(" }\n"); } fn get_read_command(element: &Element) -> String { let reader_override = reader_override(&element); if !reader_override.is_empty() { reader_override } else { let expected_type = ExpectedType::get_expected_type(code(element)).unwrap(); let reader_fun = get_reader_function(&expected_type); let converter = if read_converter(&element).is_empty() { String::from("{}") } else { read_converter(&element).clone() }; converter.replace("{}", &format!("pair.{}()?", reader_fun)) } } fn generate_add_code_pairs(fun: &mut String, element: &Element) { fun.push_str(" #[allow(clippy::cognitive_complexity)] // long function, no good way to simplify this\n"); fun.push_str(" pub(crate) fn write_code_pairs<T>(&self, writer: &mut CodePairWriter<T>) -> DxfResult<()>\n"); fun.push_str(" where T: Write + ?Sized {\n"); fun.push_str("\n"); for v in &element.children { if suppress_writing(&v) { continue; } let mut parts = vec![]; if !min_version(&v).is_empty() { parts.push(format!("self.version >= AcadVersion::{}", min_version(&v))); } if !max_version(&v).is_empty() { parts.push(format!("self.version <= AcadVersion::{}", max_version(&v))); } if dont_write_default(&v) { parts.push(format!("self.{} != {}", field(&v), default_value(&v))); } let indent = match parts.len() { 0 => "", _ => " ", }; fun.push_str(&format!(" // ${}\n", name(&v))); if parts.len() > 0 { fun.push_str(&format!(" if {} {{\n", parts.join(" && "))); } fun.push_str(&format!( " {indent}writer.write_code_pair(&CodePair::new_str(9, \"${name}\"))?;\n", name = name(&v), indent = indent )); let write_converter = if write_converter(&v).is_empty() { String::from("{}") } else { write_converter(&v).clone() }; if code(&v) > 0 { let expected_type = get_code_pair_type(&ExpectedType::get_expected_type(code(&v)).unwrap()); let field_name = field(&v); let value = format!("self.{}", field_name); let value = write_converter.replace("{}", &*value); fun.push_str(&format!( " {indent}writer.write_code_pair(&CodePair::new_{typ}({code}, {value}))?;\n", code = code(&v), value = value, typ = expected_type, indent = indent )); } else { for i in 0..code(&v).abs() { let (code, fld) = match i { 0 => (10, "x"), 1 => (20, "y"), 2 => (30, "z"), _ => panic!("unexpected number of values"), }; let value = write_converter.replace("{}", &format!("self.{}.{}", field(&v), fld)); fun.push_str(&format!(" {indent}writer.write_code_pair(&CodePair::new_f64({code}, {value}))?;\n", code=code, value=value, indent=indent)); } } if parts.len() > 0 { fun.push_str(" }\n"); } fun.push_str("\n"); } fun.push_str(" Ok(())\n"); fun.push_str(" }\n"); } fn load_xml() -> Element { let file = File::open("spec/HeaderVariablesSpec.xml").unwrap(); let file = BufReader::new(file); Element::parse(file).unwrap() } fn dont_write_default(element: &Element) -> bool { attr(element, "DontWriteDefault") == "true" } fn field(element: &Element) -> String { attr(element, "Field") } fn mask(element: &Element) -> String { attr(element, "Mask") } fn read_converter(element: &Element) -> String { attr(element, "ReadConverter") } fn reader_override(element: &Element) -> String { attr(element, "ReaderOverride") } fn write_converter(element: &Element) -> String { attr(element, "WriteConverter") }
extern crate xmltree; use self::xmltree::Element; use crate::ExpectedType; use crate::other_helpers::*; use crate::xml_helpers::*; use std::collections::HashSet; use std::fs::File; use std::io::{BufReader, Write}; use std::iter::Iterator; use std::path::Path; pub fn generate_header(generated_dir: &Path) { let element = load_xml(); let mut fun = String::new(); fun.push_str(" // The contents of this file are automatically generated and should not be modified directly. See the `build` directory. // types from `lib.rs`. use crate::{ CodePair, Color, DxfError, DxfResult, Handle, LineWeight, Point, Vector, }; use crate::code_pair_writer::CodePairWriter; use crate::helper_functions::*; use crate::enums::*; use crate::enum_primitive::FromPrimitive; use std::io::Write; use std::time::Duration; extern crate chrono; use self::chrono::{DateTime, Local, Utc}; extern crate uuid; use self::uuid::Uuid; ".trim_start()); generate_struct(&mut fun, &element); generate_default(&mut fun, &element); fun.push_str("impl Header {\n"); generate_flags(&mut fun, &element); generate_set_defaults(&mut fun, &element); generate_set_header_value(&mut fun, &element); generate_add_code_pairs(&mut fun, &element); fun.push_str("}\n"); let mut file = File::create(generated_dir.join("header.rs")).ok().unwrap(); file.write_all(fun.as_bytes()).ok().unwrap(); } fn generate_struct(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str("/// Contains common properties for the DXF file.\n"); fun.push_str("#[cfg_attr(feature = \"serialize\", derive(Serialize, Deserialize))]\n"); fun.push_str("pub struct Header {\n"); for v in &element.children { let field_name = field(v); if !seen_fields.contains(&field_name) { seen_fields.insert(field_name.clone()); let mut comment = format!("The ${} header variable. {}", name(&v), comment(&v)); if !min_version(&v).is_empty() { comment.push_str(&format!(" Minimum AutoCAD version: {}.", min_version(&v))); } if !max_version(&v).is_empty() { comment.push_str(&format!(" Maximum AutoCAD version: {}.", max_version(&v))); } fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub {field}: {typ},\n", field = field(&v), typ = typ(&v) )); } } fun.push_str("}\n"); fun.push_str("\n"); } fn generate_default(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str("impl Default for Header {\n"); fun.push_str(" fn default() -> Self {\n"); fun.push_str(" Header {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!( " {field}: {default_value}, // ${name}\n", field = field(&v), default_value = default_value(&v), name = name(&v) )); } } fun.push_str(" }\n"); fun.push_str(" }\n"); fun.push_str("}\n"); fun.push_str("\n"); } fn generate_flags(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); if v.children.len() > 0 { fun.push_str(&format!(" // {} flags\n", field(&v))); } for f in &v.children { let mut comment = format!("{}", comment(&f)); if !min_version(&v).is_empty() { comment.push_str(&format!(" Minimum AutoCAD version: {}.", min_version(&v))); } if !max_version(&v).is_empty() { comment.push_str(&format!(" Maximum AutoCAD version: {}.", max_version(&v))); } fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub fn get_{flag}(&self) -> bool {{\n", flag = name(&f) )); fun.push_str(&format!( " self.{field} & {mask} != 0\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(&format!(" /// {}\n", comment)); fun.push_str(&format!( " pub fn set_{flag}(&mut self, val: bool) {{\n", flag = name(&f) )); fun.push_str(&format!(" if val {{\n")); fun.push_str(&format!( " self.{field} |= {mask};\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(" else {\n"); fun.push_str(&format!( " self.{field} &= !{mask};\n", field = field(&v), mask = mask(&f) )); fun.push_str(" }\n"); fun.push_str(" }\n"); } } } } fn generate_set_defaults(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str(" /// Sets the default values on the header.\n"); fun.push_str(" pub fn set_defaults(&mut self) {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!( " self.{field} = {default_value}; // ${name}\n", field = field(&v), default_value = default_value(&v), name = name(&v) )); } } fun.push_str(" }\n"); } fn generate_set_header_value(fun: &mut String, element: &Element) { let mut seen_fields = HashSet::new(); fun.push_str(" #[allow(clippy::cognitive_complexity)] // generated method\n"); fun.push_str(" pub(crate) fn set_header_value(&mut self, variable: &str, pair: &CodePair) -> DxfResult<()> {\n"); fun.push_str(" match variable {\n"); for v in &element.children { if !seen_fields.contains(&field(&v)) { seen_fields.insert(field(&v)); fun.push_str(&format!(" \"${name}\" => {{", name = name(&v))); let variables_with_name: Vec<&Element> = element .children .iter() .filter(|&vv| name(&vv) == name(&v)) .collect(); if variables_with_name.len() == 1 { fun.push_str(" ");
fun.push_str(" "); } else { fun.push_str("\n"); fun.push_str(" match pair.code {\n"); let expected_codes: Vec<i32> = variables_with_name.iter().map(|&vv| code(&vv)).collect(); for v in &variables_with_name { let read_cmd = get_read_command(&v); fun.push_str(&format!( " {code} => self.{field} = {cmd},\n", code = code(&v), field = field(&v), cmd = read_cmd )); } fun.push_str(&format!(" _ => return Err(DxfError::UnexpectedCodePair(pair.clone(), String::from(\"expected code {:?}\"))),\n", expected_codes)); fun.push_str(" }\n"); fun.push_str(" "); } fun.push_str("},\n"); } } fun.push_str(" _ => (),\n"); fun.push_str(" }\n"); fun.push_str("\n"); fun.push_str(" Ok(())\n"); fun.push_str(" }\n"); } fn get_read_command(element: &Element) -> String { let reader_override = reader_override(&element); if !reader_override.is_empty() { reader_override } else { let expected_type = ExpectedType::get_expected_type(code(element)).unwrap(); let reader_fun = get_reader_function(&expected_type); let converter = if read_converter(&element).is_empty() { String::from("{}") } else { read_converter(&element).clone() }; converter.replace("{}", &format!("pair.{}()?", reader_fun)) } } fn generate_add_code_pairs(fun: &mut String, element: &Element) { fun.push_str(" #[allow(clippy::cognitive_complexity)] // long function, no good way to simplify this\n"); fun.push_str(" pub(crate) fn write_code_pairs<T>(&self, writer: &mut CodePairWriter<T>) -> DxfResult<()>\n"); fun.push_str(" where T: Write + ?Sized {\n"); fun.push_str("\n"); for v in &element.children { if suppress_writing(&v) { continue; } let mut parts = vec![]; if !min_version(&v).is_empty() { parts.push(format!("self.version >= AcadVersion::{}", min_version(&v))); } if !max_version(&v).is_empty() { parts.push(format!("self.version <= AcadVersion::{}", max_version(&v))); } if dont_write_default(&v) { parts.push(format!("self.{} != {}", field(&v), default_value(&v))); } let indent = match parts.len() { 0 => "", _ => " ", }; fun.push_str(&format!(" // ${}\n", name(&v))); if parts.len() > 0 { fun.push_str(&format!(" if {} {{\n", parts.join(" && "))); } fun.push_str(&format!( " {indent}writer.write_code_pair(&CodePair::new_str(9, \"${name}\"))?;\n", name = name(&v), indent = indent )); let write_converter = if write_converter(&v).is_empty() { String::from("{}") } else { write_converter(&v).clone() }; if code(&v) > 0 { let expected_type = get_code_pair_type(&ExpectedType::get_expected_type(code(&v)).unwrap()); let field_name = field(&v); let value = format!("self.{}", field_name); let value = write_converter.replace("{}", &*value); fun.push_str(&format!( " {indent}writer.write_code_pair(&CodePair::new_{typ}({code}, {value}))?;\n", code = code(&v), value = value, typ = expected_type, indent = indent )); } else { for i in 0..code(&v).abs() { let (code, fld) = match i { 0 => (10, "x"), 1 => (20, "y"), 2 => (30, "z"), _ => panic!("unexpected number of values"), }; let value = write_converter.replace("{}", &format!("self.{}.{}", field(&v), fld)); fun.push_str(&format!(" {indent}writer.write_code_pair(&CodePair::new_f64({code}, {value}))?;\n", code=code, value=value, indent=indent)); } } if parts.len() > 0 { fun.push_str(" }\n"); } fun.push_str("\n"); } fun.push_str(" Ok(())\n"); fun.push_str(" }\n"); } fn load_xml() -> Element { let file = File::open("spec/HeaderVariablesSpec.xml").unwrap(); let file = BufReader::new(file); Element::parse(file).unwrap() } fn dont_write_default(element: &Element) -> bool { attr(element, "DontWriteDefault") == "true" } fn field(element: &Element) -> String { attr(element, "Field") } fn mask(element: &Element) -> String { attr(element, "Mask") } fn read_converter(element: &Element) -> String { attr(element, "ReadConverter") } fn reader_override(element: &Element) -> String { attr(element, "ReaderOverride") } fn write_converter(element: &Element) -> String { attr(element, "WriteConverter") }
if code(&v) < 0 { fun.push_str(&format!("self.{field}.set(&pair)?;", field = field(&v))); } else { let read_cmd = get_read_command(&v); fun.push_str(&format!( "verify_code(&pair, {code})?; self.{field} = {cmd};", code = code(&v), field = field(&v), cmd = read_cmd )); }
if_condition
[ { "content": "/// Formats an `f64` value with up to 12 digits of precision, ensuring at least one trailing digit after the decimal.\n\nfn format_f64(val: f64) -> String {\n\n // format with 12 digits of precision\n\n let mut val = format!(\"{:.12}\", val);\n\n\n\n // trim trailing zeros\n\n while val.ends_with('0') {\n\n val.pop();\n\n }\n\n\n\n // ensure it doesn't end with a decimal\n\n if val.ends_with('.') {\n\n val.push('0');\n\n }\n\n\n\n val\n\n}\n", "file_path": "src/code_pair_value.rs", "rank": 0, "score": 212134.85330100294 }, { "content": "pub fn all() -> dxf::DxfResult<()> {\n\n apply_line_types_to_entities()?;\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/src/line_type_examples.rs", "rank": 1, "score": 179537.7838120641 }, { "content": "fn apply_line_types_to_entities() -> dxf::DxfResult<()> {\n\n let mut drawing = Drawing::new();\n\n\n\n //\n\n // create a new line type named \"dashed-lines\"...\n\n //\n\n let mut line_type = dxf::tables::LineType::default();\n\n line_type.name = String::from(\"dashed-lines\");\n\n line_type.total_pattern_length = 1.0;\n\n // line pattern contains 2 elements; positive values draw a line, negative values draw a gap\n\n // the following draws 3/4 of a line with a 1/4 gap\n\n line_type.element_count = 2;\n\n line_type.dash_dot_space_lengths.push(0.75);\n\n line_type.dash_dot_space_lengths.push(-0.25);\n\n drawing.add_line_type(line_type);\n\n\n\n //\n\n // create a new line entity that applies the specified line type by name\n\n //\n\n let line = Line::new(Point::new(0.0, 0.0, 0.0), Point::new(10.0, 10.0, 0.0));\n\n let mut line = Entity::new(EntityType::Line(line));\n\n line.common.line_type_name = String::from(\"dashed-lines\");\n\n drawing.add_entity(line);\n\n\n\n drawing.save_file(\"apply_line_types_to_entities.dxf\")?;\n\n Ok(())\n\n}\n", "file_path": "examples/src/line_type_examples.rs", "rank": 2, "score": 143759.90736246528 }, { "content": "fn set_i32(data: &mut Vec<u8>, offset: usize, value: i32) -> DxfResult<()> {\n\n let expected_length = offset + 4;\n\n if data.len() < expected_length {\n\n return Err(DxfError::UnexpectedEndOfInput);\n\n }\n\n\n\n data[offset] = value as u8;\n\n data[offset + 1] = (value >> 8) as u8;\n\n data[offset + 2] = (value >> 16) as u8;\n\n data[offset + 3] = (value >> 24) as u8;\n\n Ok(())\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 3, "score": 142753.5998961398 }, { "content": "fn update_thumbnail_data_offset_in_situ(data: &mut Vec<u8>) -> DxfResult<bool> {\n\n // calculate the image data offset\n\n let dib_header_size = get_i32(&data, FILE_HEADER_LENGTH)? as usize;\n\n\n\n // calculate the palette size\n\n let palette_size = if dib_header_size >= BITMAP_HEADER_PALETTE_COUNT_OFFSET + 4 {\n\n let palette_color_count = get_u32(\n\n &data,\n\n FILE_HEADER_LENGTH + BITMAP_HEADER_PALETTE_COUNT_OFFSET,\n\n )? as usize;\n\n palette_color_count * 4 // always 4 bytes: BGRA\n\n } else {\n\n return Ok(false);\n\n };\n\n\n\n // set the image data offset\n\n let image_data_offset = FILE_HEADER_LENGTH + dib_header_size + palette_size;\n\n set_i32(data, IMAGE_DATA_OFFSET_OFFSET, image_data_offset as i32)?;\n\n\n\n Ok(true)\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 4, "score": 134942.06715618836 }, { "content": "fn main() -> dxf::DxfResult<()> {\n\n line_type_examples::all()?;\n\n Ok(())\n\n}\n", "file_path": "examples/src/main.rs", "rank": 5, "score": 117482.83468043272 }, { "content": "#[test]\n\nfn read_file_with_comments() {\n\n let file = parse_drawing(\n\n vec![\n\n \"999\", \"comment\", \"0\", \"SECTION\", \"999\", \"\", // empty comment\n\n \"2\", \"ENTITIES\", \"0\", \"LINE\", \"999\", \"comment\", \"10\", \"1.1\", \"999\", \"comment\", \"20\",\n\n \"2.2\", \"999\", \"comment\", \"0\", \"ENDSEC\", \"0\", \"EOF\", \"999\", \"comment\",\n\n ]\n\n .join(\"\\r\\n\")\n\n .trim(),\n\n );\n\n let entities = file.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(1.1, 2.2, 0.0), line.p1);\n\n }\n\n _ => panic!(\"expected a LINE\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 6, "score": 110416.69537608617 }, { "content": "#[test]\n\nfn write_binary_file() {\n\n for version in &[AcadVersion::R12, AcadVersion::R13] {\n\n println!(\"checking version {:?}\", version);\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = *version;\n\n let buf = to_binary(&drawing);\n\n\n\n // check binary sentinel\n\n let sentinel = from_utf8(&buf[0..20]).ok().unwrap();\n\n assert_eq!(\"AutoCAD Binary DXF\\r\\n\", sentinel);\n\n\n\n // check \"SECTION\" text at expected offset\n\n let sec_offset = if *version <= AcadVersion::R12 { 23 } else { 24 };\n\n let sec_end = sec_offset + 7;\n\n let sec_text = from_utf8(&buf[sec_offset..sec_end]).ok().unwrap();\n\n assert_eq!(\"SECTION\", sec_text);\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 7, "score": 110382.5154277244 }, { "content": "#[test]\n\nfn test_unicode_escape_2() {\n\n assert_eq!(\n\n \"\\\\U+0410\\\\U+0430\\\\U+042F\\\\U+044F\",\n\n escape_unicode_to_ascii(\"АаЯя\")\n\n );\n\n}\n\n\n\npub(crate) fn un_escape_ascii_to_unicode(val: &str) -> String {\n\n let mut result = String::from(\"\");\n\n let mut seq = String::from(\"\");\n\n let mut in_escape_sequence = false;\n\n let mut sequence_start = 0;\n\n\n\n for (i, c) in val.chars().enumerate() {\n\n if !in_escape_sequence {\n\n if c == '\\\\' {\n\n in_escape_sequence = true;\n\n sequence_start = i;\n\n seq.clear();\n\n seq.push(c);\n", "file_path": "src/code_pair_value.rs", "rank": 8, "score": 110084.6138137642 }, { "content": "#[test]\n\nfn test_ascii_unescape() {\n\n // values in the middle of the string\n\n assert_eq!(\n\n \"Repère pièce\",\n\n un_escape_ascii_to_unicode(\"Rep\\\\U+00E8re pi\\\\U+00E8ce\")\n\n );\n\n\n\n // value is entire string\n\n assert_eq!(\"你好\", un_escape_ascii_to_unicode(\"\\\\U+4F60\\\\U+597D\"));\n\n}\n\n\n", "file_path": "src/code_pair_value.rs", "rank": 9, "score": 110084.6138137642 }, { "content": "#[test]\n\nfn test_unicode_escape_1() {\n\n // values in the middle of a string\n\n assert_eq!(\n\n \"Rep\\\\U+00E8re pi\\\\U+00E8ce\",\n\n escape_unicode_to_ascii(\"Repère pièce\")\n\n );\n\n\n\n // value is the entire string\n\n assert_eq!(\"\\\\U+4F60\\\\U+597D\", escape_unicode_to_ascii(\"你好\"));\n\n}\n\n\n", "file_path": "src/code_pair_value.rs", "rank": 10, "score": 110084.6138137642 }, { "content": "#[test]\n\nfn write_string_with_control_characters() {\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = AcadVersion::R2004;\n\n drawing.header.last_saved_by = String::from(\"a\\u{7}^\\u{1E} b\");\n\n assert_contains(&drawing, String::from(\"a^G^ ^^ b\"));\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 11, "score": 106475.9716140518 }, { "content": "#[test]\n\nfn read_binary_file_after_writing() {\n\n for version in &[AcadVersion::R12, AcadVersion::R13] {\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = *version;\n\n let line = Line {\n\n p1: Point::new(1.1, 2.2, 3.3),\n\n p2: Point::new(4.4, 5.5, 6.6),\n\n ..Default::default()\n\n };\n\n drawing.add_entity(Entity::new(EntityType::Line(line)));\n\n let mut buf = Cursor::new(vec![]);\n\n drawing.save_binary(&mut buf).ok().unwrap();\n\n buf.seek(SeekFrom::Start(0)).ok().unwrap();\n\n let mut reader = BufReader::new(&mut buf);\n\n let drawing = unwrap_drawing(Drawing::load(&mut reader));\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(1.1, 2.2, 3.3), line.p1);\n\n assert_eq!(Point::new(4.4, 5.5, 6.6), line.p2);\n\n }\n\n _ => panic!(\"expected a line\"),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 12, "score": 106444.16507080627 }, { "content": "#[test]\n\nfn test_escape_control_characters() {\n\n assert_eq!(\"a^G^ ^^ b\", escape_control_characters(\"a\\u{7}^\\u{1E} b\"));\n\n}\n\n\n\npub(crate) fn escape_unicode_to_ascii(val: &str) -> String {\n\n let mut result = String::from(\"\");\n\n\n\n for c in val.chars() {\n\n let b = c as u32;\n\n if b >= 128 {\n\n result.push_str(&format!(\"\\\\U+{:04X}\", b));\n\n } else {\n\n result.push(c);\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "src/code_pair_value.rs", "rank": 13, "score": 106158.70334685023 }, { "content": "#[test]\n\nfn test_set_i32() {\n\n let mut data = vec![0x00u8; 6];\n\n set_i32(&mut data, 1, 0x12345678).unwrap();\n\n assert_eq!(vec![0x00, 0x78, 0x56, 0x34, 0x12, 0x00], data);\n\n}\n", "file_path": "src/thumbnail.rs", "rank": 14, "score": 84748.63297176479 }, { "content": "fn f64_to_adjusted_duration(f: f64) -> ChronoDuration {\n\n let days_since_dublin = f - 2_415_020.0; // julian dublin offset, e.g., December 31, 1899 12:00AM\n\n let secs_per_day = 24i64 * 60 * 60;\n\n let seconds = days_since_dublin * secs_per_day as f64;\n\n // functions consuming this need to use 1900/01/01 instead of 1899/12/31 as a base\n\n // so we counter the extra day and leap second here\n\n ChronoDuration::seconds(seconds as i64 - secs_per_day + 1)\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 15, "score": 82163.4340754045 }, { "content": "#[test]\n\nfn parse_empty_uuid_test() {\n\n let _empty = as_uuid(String::from(\"\"));\n\n}\n\n\n\npub(crate) fn as_i16(b: bool) -> i16 {\n\n if b {\n\n 1\n\n } else {\n\n 0\n\n }\n\n}\n\n\n\npub(crate) fn uuid_string(u: &Uuid) -> String {\n\n format!(\"{}\", u)\n\n}\n\n\n\npub(crate) fn combine_points_2<F, T>(\n\n v1: &mut Vec<f64>,\n\n v2: &mut Vec<f64>,\n\n result: &mut Vec<T>,\n", "file_path": "src/helper_functions.rs", "rank": 16, "score": 78868.36688848418 }, { "content": "#[test]\n\nfn parse_hex_string_test() {\n\n let mut bytes = vec![];\n\n parse_hex_string(&String::from(\"012345\"), &mut bytes, 0).unwrap();\n\n assert_eq!(vec![0x01u8, 0x23, 0x45], bytes);\n\n}\n\n\n\n#[cfg(test)]\n\n#[allow(dead_code)]\n\npub mod tests {\n\n use crate::*;\n\n use std::io::{BufRead, BufReader, Cursor, Seek, SeekFrom};\n\n\n\n pub fn unwrap_drawing(result: DxfResult<Drawing>) -> Drawing {\n\n match result {\n\n Ok(drawing) => drawing,\n\n Err(e) => panic!(\"unable to load drawing: {:?}: {}\", e, e),\n\n }\n\n }\n\n\n\n pub fn parse_drawing(s: &str) -> Drawing {\n", "file_path": "src/helper_functions.rs", "rank": 17, "score": 78856.98630387995 }, { "content": "#[test]\n\nfn write_unicode_as_ascii() {\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = AcadVersion::R2004;\n\n drawing.header.project_name = String::from(\"è\");\n\n assert_contains(\n\n &drawing,\n\n vec![\" 9\", \"$PROJECTNAME\", \" 1\", \"\\\\U+00E8\"].join(\"\\r\\n\"),\n\n );\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 18, "score": 78840.34993997894 }, { "content": "#[test]\n\nfn write_unicode_as_utf8() {\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = AcadVersion::R2007;\n\n drawing.header.project_name = String::from(\"è\");\n\n assert_contains(\n\n &drawing,\n\n vec![\" 9\", \"$PROJECTNAME\", \" 1\", \"è\"].join(\"\\r\\n\"),\n\n );\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 19, "score": 78840.34993997894 }, { "content": "#[test]\n\nfn read_dxb_after_writing() {\n\n let mut drawing = Drawing::new();\n\n let line = Line::new(Point::new(1.0, 2.0, 3.0), Point::new(4.0, 5.0, 6.0));\n\n drawing.add_entity(Entity::new(EntityType::Line(line)));\n\n let mut buf = Cursor::new(vec![]);\n\n drawing.save_dxb(&mut buf).ok().unwrap();\n\n buf.seek(SeekFrom::Start(0)).ok().unwrap();\n\n let mut reader = BufReader::new(&mut buf);\n\n let drawing = unwrap_drawing(Drawing::load(&mut reader));\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(1.0, 2.0, 3.0), line.p1);\n\n assert_eq!(Point::new(4.0, 5.0, 6.0), line.p2);\n\n }\n\n _ => panic!(\"expected a line\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 20, "score": 78840.34993997894 }, { "content": "#[test]\n\nfn read_dxb_file() {\n\n let data = vec![\n\n // DXB sentinel \"AutoCAD DXB 1.0\\r\\n\"\n\n b'A', b'u', b't', b'o', b'C', b'A', b'D', b' ', b'D', b'X', b'B', b' ', b'1', b'.', b'0',\n\n b'\\r', b'\\n', 0x1A, 0x0, // color\n\n 136, // type specifier for new color\n\n 0x01, 0x00, // color index 1\n\n // line\n\n 0x01, // type specifier\n\n 0x01, 0x00, // p1.x = 0x0001\n\n 0x02, 0x00, // p1.y = 0x0002\n\n 0x03, 0x00, // p1.z = 0x0003\n\n 0x04, 0x00, // p2.x = 0x0004\n\n 0x05, 0x00, // p2.y = 0x0005\n\n 0x06, 0x00, // p2.z = 0x0006\n\n 0x0, // null terminator\n\n ];\n\n let drawing = Drawing::load(&mut data.as_slice()).unwrap();\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n assert_eq!(Some(1), entities[0].common.color.index());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(1.0, 2.0, 3.0), line.p1);\n\n assert_eq!(Point::new(4.0, 5.0, 6.0), line.p2);\n\n }\n\n _ => panic!(\"expected a line\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 21, "score": 78823.79369074768 }, { "content": "#[test]\n\nfn totally_empty_file() {\n\n let _file = parse_drawing(\"\");\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 22, "score": 78823.79369074768 }, { "content": "#[test]\n\nfn read_binary_file() {\n\n // `diamond-bin.dxf` is a pre-R13 binary file\n\n let drawing = unwrap_drawing(Drawing::load_file(\"./src/misc_tests/diamond-bin.dxf\"));\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n assert_eq!(12, entities.len());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(45.0, 45.0, 0.0), line.p1);\n\n assert_eq!(Point::new(45.0, -45.0, 0.0), line.p2);\n\n }\n\n _ => panic!(\"expected a line\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 23, "score": 78823.79369074768 }, { "content": "#[test]\n\nfn set_thumbnail_offset_for_bitmapinfoheader_palette_256() {\n\n let mut data: Vec<u8> = vec![\n\n b'B', b'M', // magic number\n\n 0x00, 0x00, 0x00, 0x00, // file length; not needed for this test\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, 0x00, 0x00, // the image data offset that will be filled in\n\n 0x28, 0x00, 0x00, 0x00, // BITMAPINFOHEADER length\n\n 0x00, 0x00, 0x00, 0x00, // width (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // height (not needed)\n\n 0x00, 0x00, // color planes (not needed)\n\n 0x00, 0x00, // bits per pixel (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // compression (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // image size (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // horizontal resolution (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // vertical resolution (not needed)\n\n 0x00, 0x01, 0x00,\n\n 0x00, // color palette count (0 means default of 2^n)\n\n // rest of struct not needed\n\n ];\n\n assert!(update_thumbnail_data_offset_in_situ(&mut data).unwrap());\n\n assert_eq!(0x0436, get_i32(&data, IMAGE_DATA_OFFSET_OFFSET).unwrap());\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 24, "score": 78762.83398130958 }, { "content": "#[test]\n\nfn set_pointer_on_entity() {\n\n let mut drawing = Drawing::new();\n\n drawing.header.version = AcadVersion::R2007;\n\n let material = Object {\n\n common: Default::default(),\n\n specific: ObjectType::Material(Material {\n\n name: String::from(\"material-name\"),\n\n ..Default::default()\n\n }),\n\n };\n\n let mut line = Entity {\n\n common: Default::default(),\n\n specific: EntityType::Line(Default::default()),\n\n };\n\n assert_eq!(Handle(0), material.common.handle);\n\n\n\n let material = drawing.add_object(material);\n\n assert_eq!(Handle(0x10), material.common.handle);\n\n line.common.set_material(material).ok().unwrap();\n\n drawing.add_entity(line);\n", "file_path": "src/misc_tests/pointers.rs", "rank": 25, "score": 78762.83398130958 }, { "content": "#[test]\n\nfn set_thumbnail_offset_for_bitmapv4header_palette_256() {\n\n let mut data: Vec<u8> = vec![\n\n b'B', b'M', // magic number\n\n 0x00, 0x00, 0x00, 0x00, // file length; not needed for this test\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, 0x00, 0x00, // the image data offset that will be filled in\n\n 0x6C, 0x00, 0x00, 0x00, // BITMAPV4HEADER length\n\n 0x00, 0x00, 0x00, 0x00, // width (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // height (not needed)\n\n 0x00, 0x00, // color planes (not needed)\n\n 0x00, 0x00, // bits per pixel (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // compression (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // image size (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // horizontal resolution (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // vertical resolution (not needed)\n\n 0x00, 0x01, 0x00,\n\n 0x00, // color palette count (0 means default of 2^n)\n\n // rest of struct not needed\n\n ];\n\n assert!(update_thumbnail_data_offset_in_situ(&mut data).unwrap());\n\n assert_eq!(0x047A, get_i32(&data, IMAGE_DATA_OFFSET_OFFSET).unwrap());\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 26, "score": 78762.83398130958 }, { "content": "#[test]\n\nfn read_string_with_control_characters() {\n\n let drawing = parse_drawing(\n\n vec![\n\n \"0\",\n\n \"SECTION\",\n\n \"2\",\n\n \"HEADER\",\n\n \"9\",\n\n \"$LASTSAVEDBY\",\n\n \"1\",\n\n \"a^G^ ^^ b\",\n\n \"0\",\n\n \"ENDSEC\",\n\n \"0\",\n\n \"EOF\",\n\n ]\n\n .join(\"\\n\")\n\n .as_str(),\n\n );\n\n assert_eq!(\"a\\u{7}^\\u{1E} b\", drawing.header.last_saved_by);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 27, "score": 76235.09109942068 }, { "content": "#[test]\n\nfn dont_write_utf8_bom() {\n\n let drawing = Drawing::new();\n\n let mut buf = Cursor::new(vec![]);\n\n drawing.save(&mut buf).ok().unwrap();\n\n buf.seek(SeekFrom::Start(0)).ok().unwrap();\n\n let vec = buf.into_inner();\n\n\n\n // file should start directly with a code, not a UTF-8 BOM\n\n assert_eq!(b' ', vec[0]);\n\n assert_eq!(b' ', vec[1]);\n\n assert_eq!(b'0', vec[2]);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 28, "score": 76219.14944319261 }, { "content": "#[test]\n\nfn empty_file_no_trailing_newline() {\n\n let _file = parse_drawing(\"0\\nEOF\");\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 29, "score": 76203.28455617515 }, { "content": "#[test]\n\nfn empty_file_trailing_newline() {\n\n let _file = parse_drawing(\"0\\nEOF\\n\");\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 30, "score": 76203.28455617515 }, { "content": "#[test]\n\nfn read_dxb_file_with_polyline() {\n\n let data = vec![\n\n // DXB sentinel \"AutoCAD DXB 1.0\\r\\n\"\n\n b'A', b'u', b't', b'o', b'C', b'A', b'D', b' ', b'D', b'X', b'B', b' ', b'1', b'.', b'0',\n\n b'\\r', b'\\n', 0x1A, 0x0, 19, // polyline\n\n 0x00, 0x00, // is closed = false\n\n 20, // vertex\n\n 0x01, 0x00, // x\n\n 0x02, 0x00, // y\n\n 20, // vertex\n\n 0x03, 0x00, // x\n\n 0x04, 0x00, // y\n\n 17, // seqend\n\n 0x0, // null terminator\n\n ];\n\n let drawing = Drawing::load(&mut data.as_slice()).unwrap();\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n match entities[0].specific {\n\n EntityType::Polyline(ref poly) => {\n\n let vertices = poly.vertices().collect::<Vec<_>>();\n\n assert_eq!(2, vertices.len());\n\n assert_eq!(Point::new(1.0, 2.0, 0.0), vertices[0].location);\n\n assert_eq!(Point::new(3.0, 4.0, 0.0), vertices[1].location);\n\n }\n\n _ => panic!(\"expected a polyline\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 31, "score": 76203.28455617515 }, { "content": "#[test]\n\nfn set_thumbnail_offset_for_bitmapinfoheader_non_palette() {\n\n let mut data: Vec<u8> = vec![\n\n b'B', b'M', // magic number\n\n 0x00, 0x00, 0x00, 0x00, // file length; not needed for this test\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, 0x00, 0x00, // the image data offset that will be filled in\n\n 0x28, 0x00, 0x00, 0x00, // BITMAPINFOHEADER length\n\n 0x00, 0x00, 0x00, 0x00, // width (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // height (not needed)\n\n 0x00, 0x00, // color planes (not needed)\n\n 0x00, 0x00, // bits per pixel (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // compression (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // image size (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // horizontal resolution (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // vertical resolution (not needed)\n\n 0x00, 0x00, 0x00,\n\n 0x00, // color palette count (0 means default of 2^n)\n\n // rest of struct not needed\n\n ];\n\n assert!(update_thumbnail_data_offset_in_situ(&mut data).unwrap());\n\n assert_eq!(0x36, get_i32(&data, IMAGE_DATA_OFFSET_OFFSET).unwrap());\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 32, "score": 76144.87042569518 }, { "content": "#[test]\n\nfn set_thumbnail_offset_for_bitmapv4header_non_palette() {\n\n let mut data: Vec<u8> = vec![\n\n b'B', b'M', // magic number\n\n 0x00, 0x00, 0x00, 0x00, // file length; not needed for this test\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, // reserved\n\n 0x00, 0x00, 0x00, 0x00, // the image data offset that will be filled in\n\n 0x6C, 0x00, 0x00, 0x00, // BITMAPV4HEADER length\n\n 0x00, 0x00, 0x00, 0x00, // width (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // height (not needed)\n\n 0x00, 0x00, // color planes (not needed)\n\n 0x00, 0x00, // bits per pixel (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // compression (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // image size (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // horizontal resolution (not needed)\n\n 0x00, 0x00, 0x00, 0x00, // vertical resolution (not needed)\n\n 0x00, 0x00, 0x00,\n\n 0x00, // color palette count (0 means default of 2^n)\n\n // rest of struct not needed\n\n ];\n\n assert!(update_thumbnail_data_offset_in_situ(&mut data).unwrap());\n\n assert_eq!(0x7A, get_i32(&data, IMAGE_DATA_OFFSET_OFFSET).unwrap());\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 33, "score": 76144.87042569518 }, { "content": "#[test]\n\nfn follow_object_pointer_to_entity_collection() {\n\n let drawing = parse_drawing(\n\n vec![\n\n \" 0\",\n\n \"SECTION\",\n\n \" 2\",\n\n \"OBJECTS\",\n\n \" 0\",\n\n \"GROUP\",\n\n \"340\",\n\n \"ABCD\",\n\n \" 0\",\n\n \"ENDSEC\",\n\n \" 0\",\n\n \"SECTION\",\n\n \" 2\",\n\n \"ENTITIES\",\n\n \" 0\",\n\n \"TEXT\",\n\n \" 5\",\n", "file_path": "src/misc_tests/pointers.rs", "rank": 34, "score": 73839.52784495556 }, { "content": "#[test]\n\nfn parse_regular_and_windows_style_uuids_test() {\n\n let _regular = as_uuid(String::from(\"a2a7a23e-975b-4b54-968c-150d4c32a9b6\"));\n\n let _windows = as_uuid(String::from(\"{a2a7a23e-975b-4b54-968c-150d4c32a9b6}\"));\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 35, "score": 73833.8589268724 }, { "content": "#[test]\n\nfn read_binary_file_post_r13() {\n\n // post R13 binary files have 2 byte codes and single byte booleans\n\n let data = vec![\n\n // binary header\n\n b'A', b'u', b't', b'o', b'C', b'A', b'D', b' ', b'B', b'i', b'n', b'a', b'r', b'y', b' ',\n\n b'D', b'X', b'F', b'\\r', b'\\n', 0x1A, 0x00, // 0/SECTION\n\n 0x00, 0x00, b'S', b'E', b'C', b'T', b'I', b'O', b'N', 0x00, // 2/HEADER\n\n 0x02, 0x00, b'H', b'E', b'A', b'D', b'E', b'R', 0x00, // 9/$LWDISPLAY\n\n 0x09, 0x00, b'$', b'L', b'W', b'D', b'I', b'S', b'P', b'L', b'A', b'Y', 0x00, 0x22, 0x01,\n\n 0x01, // 290/true\n\n 0x00, 0x00, b'E', b'N', b'D', b'S', b'E', b'C', 0x00, // 0/ENDSEC\n\n 0x00, 0x00, b'E', b'O', b'F', 0x00, // 0/EOF\n\n ];\n\n let drawing = Drawing::load(&mut data.as_slice()).unwrap();\n\n assert!(drawing.header.display_linewieght_in_model_and_layout_tab);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 36, "score": 73792.85911954545 }, { "content": "fn read_thumbnail_bytes_from_code_pairs<T>(\n\n iter: &mut CodePairPutBack<T>,\n\n) -> DxfResult<Option<Vec<u8>>>\n\nwhere\n\n T: Read,\n\n{\n\n // get the length; we don't really care about this since we'll just read whatever's there\n\n let _length = match iter.next() {\n\n Some(Ok(pair @ CodePair { code: 0, .. })) => {\n\n // likely 0/ENDSEC\n\n iter.put_back(Ok(pair));\n\n return Ok(None);\n\n }\n\n Some(Ok(pair @ CodePair { code: 90, .. })) => pair.assert_i32()? as usize,\n\n Some(Ok(pair)) => {\n\n return Err(DxfError::UnexpectedCode(pair.code, pair.offset));\n\n }\n\n Some(Err(e)) => return Err(e),\n\n None => return Ok(None),\n\n };\n", "file_path": "src/thumbnail.rs", "rank": 37, "score": 73444.19992317515 }, { "content": "use std::io::{Read, Write};\n\n\n\nuse crate::{CodePair, DxfResult, Handle, SectionGeometrySettings};\n\n\n\nuse crate::code_pair_put_back::CodePairPutBack;\n\nuse crate::code_pair_writer::CodePairWriter;\n\nuse crate::helper_functions::*;\n\n\n\n#[derive(Clone, Debug, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Serialize, Deserialize))]\n\npub struct SectionTypeSettings {\n\n pub section_type: i32,\n\n pub is_generation_option: bool,\n\n pub source_object_handles: Vec<Handle>,\n\n pub destination_object_handle: Handle,\n\n pub destination_file_name: String,\n\n pub geometry_settings: Vec<SectionGeometrySettings>,\n\n}\n\n\n\nimpl Default for SectionTypeSettings {\n", "file_path": "src/section_type_settings.rs", "rank": 38, "score": 72533.10082276941 }, { "content": " fn default() -> Self {\n\n SectionTypeSettings {\n\n section_type: 0,\n\n is_generation_option: false,\n\n source_object_handles: vec![],\n\n destination_object_handle: Handle::empty(),\n\n destination_file_name: String::new(),\n\n geometry_settings: vec![],\n\n }\n\n }\n\n}\n\n\n\n// internal visibility only\n\nimpl SectionTypeSettings {\n\n pub(crate) fn read<I>(iter: &mut CodePairPutBack<I>) -> DxfResult<Option<SectionTypeSettings>>\n\n where\n\n I: Read,\n\n {\n\n // check the first pair and only continue if it's not 0\n\n match iter.next() {\n", "file_path": "src/section_type_settings.rs", "rank": 39, "score": 72529.14779744267 }, { "content": " None => return Ok(Some(ss)),\n\n };\n\n\n\n match pair.code {\n\n 1 => {\n\n ss.destination_file_name = pair.assert_string()?;\n\n }\n\n 2 => {\n\n // value should be \"SectionGeometrySettings\", but it doesn't really matter\n\n while let Some(gs) = SectionGeometrySettings::read(iter)? {\n\n ss.geometry_settings.push(gs);\n\n }\n\n }\n\n 3 => (), // value should be \"SectionTypeSettingsEnd\", but it doesn't really matter\n\n 90 => {\n\n ss.section_type = pair.assert_i32()?;\n\n }\n\n 91 => {\n\n ss.is_generation_option = as_bool(pair.assert_i32()? as i16);\n\n }\n", "file_path": "src/section_type_settings.rs", "rank": 40, "score": 72517.17055409057 }, { "content": " writer.write_code_pair(&CodePair::new_str(1, \"SectionTypeSettings\"))?;\n\n writer.write_code_pair(&CodePair::new_i32(90, self.section_type))?;\n\n writer.write_code_pair(&CodePair::new_i32(\n\n 91,\n\n i32::from(as_i16(self.is_generation_option)),\n\n ))?;\n\n writer.write_code_pair(&CodePair::new_i32(\n\n 92,\n\n self.source_object_handles.len() as i32,\n\n ))?;\n\n for handle in &self.source_object_handles {\n\n writer.write_code_pair(&CodePair::new_string(330, &handle.as_string()))?;\n\n }\n\n writer.write_code_pair(&CodePair::new_string(\n\n 331,\n\n &self.destination_object_handle.as_string(),\n\n ))?;\n\n writer.write_code_pair(&CodePair::new_string(1, &self.destination_file_name))?;\n\n writer.write_code_pair(&CodePair::new_i32(93, self.geometry_settings.len() as i32))?;\n\n writer.write_code_pair(&CodePair::new_str(2, \"SectionGeometrySettings\"))?;\n\n for geometry_settings in &self.geometry_settings {\n\n geometry_settings.write(writer)?;\n\n }\n\n writer.write_code_pair(&CodePair::new_str(3, \"SectionTypeSettingsEnd\"))?;\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/section_type_settings.rs", "rank": 41, "score": 72516.94925902366 }, { "content": " 92 => (), // source objects count; we just read as many as we're given\n\n 93 => (), // generation settings count; we just read as many as we're given\n\n 330 => {\n\n ss.source_object_handles.push(pair.as_handle()?);\n\n }\n\n 331 => {\n\n ss.destination_object_handle = pair.as_handle()?;\n\n }\n\n _ => {\n\n // unexpected end; put the pair back and return what we have\n\n iter.put_back(Ok(pair));\n\n return Ok(Some(ss));\n\n }\n\n }\n\n }\n\n }\n\n pub(crate) fn write<T>(&self, writer: &mut CodePairWriter<T>) -> DxfResult<()>\n\n where\n\n T: Write + ?Sized,\n\n {\n", "file_path": "src/section_type_settings.rs", "rank": 42, "score": 72513.26686951236 }, { "content": " Some(Ok(pair @ CodePair { code: 0, .. })) => {\n\n iter.put_back(Ok(pair));\n\n return Ok(None);\n\n }\n\n Some(Ok(pair)) => {\n\n iter.put_back(Ok(pair));\n\n }\n\n Some(Err(e)) => return Err(e),\n\n None => return Ok(None),\n\n }\n\n\n\n let mut ss = SectionTypeSettings::default();\n\n loop {\n\n let pair = match iter.next() {\n\n Some(Ok(pair @ CodePair { code: 0, .. })) => {\n\n iter.put_back(Ok(pair));\n\n return Ok(Some(ss));\n\n }\n\n Some(Ok(pair)) => pair,\n\n Some(Err(e)) => return Err(e),\n", "file_path": "src/section_type_settings.rs", "rank": 43, "score": 72504.53725212174 }, { "content": "\n\nimpl Display for CodePairValue {\n\n fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{:?}\", self) // fall back to debug\n\n }\n\n}\n\n\n\npub(crate) fn escape_control_characters(val: &str) -> String {\n\n fn needs_escaping(c: char) -> bool {\n\n let c = c as u32;\n\n c <= 0x1F || c == 0x5E\n\n }\n\n\n\n let mut result = String::from(\"\");\n\n for c in val.chars() {\n\n if needs_escaping(c) {\n\n result.push('^');\n\n match c as u8 {\n\n 0x00 => result.push('@'),\n\n 0x01 => result.push('A'),\n", "file_path": "src/code_pair_value.rs", "rank": 44, "score": 72286.75728912995 }, { "content": "use std::borrow::Cow;\n\nuse std::fmt;\n\nuse std::fmt::{Debug, Display, Formatter};\n\n\n\n/// Contains the data portion of a `CodePair`.\n\n#[derive(PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Serialize, Deserialize))]\n\npub enum CodePairValue {\n\n Boolean(i16),\n\n Integer(i32),\n\n Long(i64),\n\n Short(i16),\n\n Double(f64),\n\n Str(String),\n\n Binary(Vec<u8>),\n\n}\n\n\n\n// internal visibility only\n\nimpl CodePairValue {\n\n pub(crate) fn un_escape_string(val: &'_ str) -> Cow<'_, str> {\n", "file_path": "src/code_pair_value.rs", "rank": 45, "score": 72284.22885550311 }, { "content": "\n\nimpl Debug for CodePairValue {\n\n fn fmt(&self, f: &mut Formatter) -> fmt::Result {\n\n match self {\n\n CodePairValue::Boolean(s) => write!(f, \"{}\", s),\n\n CodePairValue::Integer(i) => write!(f, \"{: >9}\", i),\n\n CodePairValue::Long(l) => write!(f, \"{}\", l),\n\n CodePairValue::Short(s) => write!(f, \"{: >6}\", s),\n\n CodePairValue::Double(d) => write!(f, \"{}\", format_f64(*d)),\n\n CodePairValue::Str(ref s) => write!(f, \"{}\", s),\n\n CodePairValue::Binary(ref b) => {\n\n let mut line = String::new();\n\n for s in b {\n\n line.push_str(&format!(\"{:02X}\", s));\n\n }\n\n write!(f, \"{}\", line)\n\n }\n\n }\n\n }\n\n}\n", "file_path": "src/code_pair_value.rs", "rank": 46, "score": 72277.26282252154 }, { "content": " result.into()\n\n } else {\n\n val.into()\n\n }\n\n }\n\n}\n\n\n\nimpl Clone for CodePairValue {\n\n fn clone(&self) -> Self {\n\n match self {\n\n CodePairValue::Boolean(b) => CodePairValue::Boolean(*b),\n\n CodePairValue::Integer(i) => CodePairValue::Integer(*i),\n\n CodePairValue::Long(l) => CodePairValue::Long(*l),\n\n CodePairValue::Short(s) => CodePairValue::Short(*s),\n\n CodePairValue::Double(d) => CodePairValue::Double(*d),\n\n CodePairValue::Str(ref s) => CodePairValue::Str(String::from(s.as_str())),\n\n CodePairValue::Binary(ref b) => CodePairValue::Binary(b.clone()),\n\n }\n\n }\n\n}\n", "file_path": "src/code_pair_value.rs", "rank": 47, "score": 72273.95312494122 }, { "content": " fn needs_un_escaping(c: char) -> bool {\n\n c == '^'\n\n }\n\n\n\n if let Some(first) = val.find(needs_un_escaping) {\n\n let mut result = String::from(&val[0..first]);\n\n result.reserve(val.len() - first);\n\n let rest = val[first..].chars();\n\n let mut do_escape = false;\n\n for c in rest {\n\n match c {\n\n '^' if !do_escape => do_escape = true,\n\n _ => {\n\n if do_escape {\n\n do_escape = false;\n\n let c = match c {\n\n '@' => 0x00,\n\n 'A' => 0x01,\n\n 'B' => 0x02,\n\n 'C' => 0x03,\n", "file_path": "src/code_pair_value.rs", "rank": 48, "score": 72267.80092807095 }, { "content": " 'D' => 0x04,\n\n 'E' => 0x05,\n\n 'F' => 0x06,\n\n 'G' => 0x07,\n\n 'H' => 0x08,\n\n 'I' => 0x09,\n\n 'J' => 0x0A,\n\n 'K' => 0x0B,\n\n 'L' => 0x0C,\n\n 'M' => 0x0D,\n\n 'N' => 0x0E,\n\n 'O' => 0x0F,\n\n 'P' => 0x10,\n\n 'Q' => 0x11,\n\n 'R' => 0x12,\n\n 'S' => 0x13,\n\n 'T' => 0x14,\n\n 'U' => 0x15,\n\n 'V' => 0x16,\n\n 'W' => 0x17,\n", "file_path": "src/code_pair_value.rs", "rank": 49, "score": 72258.87738802953 }, { "content": " } else {\n\n result.push(c);\n\n }\n\n } else {\n\n seq.push(c);\n\n if i == sequence_start + 6 {\n\n in_escape_sequence = false;\n\n if seq.starts_with(\"\\\\U+\") {\n\n let code_str = &seq[3..];\n\n let decoded = match u32::from_str_radix(code_str, 16) {\n\n Ok(code) => match std::char::from_u32(code) {\n\n Some(c) => c,\n\n None => '?',\n\n },\n\n Err(_) => '?',\n\n };\n\n result.push(decoded);\n\n } else {\n\n result.push_str(&seq);\n\n }\n\n\n\n seq.clear();\n\n }\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n", "file_path": "src/code_pair_value.rs", "rank": 50, "score": 72257.6463365173 }, { "content": " 0x16 => result.push('V'),\n\n 0x17 => result.push('W'),\n\n 0x18 => result.push('X'),\n\n 0x19 => result.push('Y'),\n\n 0x1A => result.push('Z'),\n\n 0x1B => result.push('['),\n\n 0x1C => result.push('\\\\'),\n\n 0x1D => result.push(']'),\n\n 0x1E => result.push('^'),\n\n 0x1F => result.push('_'),\n\n 0x5E => result.push(' '),\n\n _ => panic!(\"this should never happen\"),\n\n }\n\n } else {\n\n result.push(c);\n\n }\n\n }\n\n\n\n result\n\n}\n\n\n\n#[test]\n", "file_path": "src/code_pair_value.rs", "rank": 51, "score": 72254.22766335786 }, { "content": " 0x02 => result.push('B'),\n\n 0x03 => result.push('C'),\n\n 0x04 => result.push('D'),\n\n 0x05 => result.push('E'),\n\n 0x06 => result.push('F'),\n\n 0x07 => result.push('G'),\n\n 0x08 => result.push('H'),\n\n 0x09 => result.push('I'),\n\n 0x0A => result.push('J'),\n\n 0x0B => result.push('K'),\n\n 0x0C => result.push('L'),\n\n 0x0D => result.push('M'),\n\n 0x0E => result.push('N'),\n\n 0x0F => result.push('O'),\n\n 0x10 => result.push('P'),\n\n 0x11 => result.push('Q'),\n\n 0x12 => result.push('R'),\n\n 0x13 => result.push('S'),\n\n 0x14 => result.push('T'),\n\n 0x15 => result.push('U'),\n", "file_path": "src/code_pair_value.rs", "rank": 52, "score": 72254.0711854113 }, { "content": " 'X' => 0x18,\n\n 'Y' => 0x19,\n\n 'Z' => 0x1A,\n\n '[' => 0x1B,\n\n '\\\\' => 0x1C,\n\n ']' => 0x1D,\n\n '^' => 0x1E,\n\n '_' => 0x1F,\n\n ' ' => b'^',\n\n _ => c as u8, // invalid escape sequence, just keep the character\n\n };\n\n\n\n result.push(c as char);\n\n } else {\n\n result.push(c);\n\n }\n\n }\n\n }\n\n }\n\n\n", "file_path": "src/code_pair_value.rs", "rank": 53, "score": 72251.98574036022 }, { "content": "use crate::{CodePair, CodePairValue, DxfError, DxfResult, ExpectedType};\n\n\n\nuse crate::code_pair_value::un_escape_ascii_to_unicode;\n\nuse crate::helper_functions::*;\n\nuse encoding_rs::Encoding;\n\nuse std::io::Read;\n\n\n\npub(crate) struct CodePairIter<T: Read> {\n\n reader: T,\n\n string_encoding: &'static Encoding,\n\n first_line: String,\n\n read_first_line: bool,\n\n read_as_text: bool,\n\n is_post_r13_binary: bool,\n\n returned_binary_pair: bool,\n\n binary_detection_complete: bool,\n\n offset: usize,\n\n}\n\n\n\nimpl<T: Read> CodePairIter<T> {\n", "file_path": "src/code_pair_iter.rs", "rank": 54, "score": 72221.524568288 }, { "content": " };\n\n let value_line = CodePairValue::un_escape_string(&value_line);\n\n CodePairValue::Str(value_line.into_owned())\n\n }\n\n ExpectedType::Binary => {\n\n let mut data = vec![];\n\n match parse_hex_string(&value_line, &mut data, self.offset) {\n\n Ok(()) => CodePairValue::Binary(data),\n\n Err(e) => return Some(Err(e)),\n\n }\n\n }\n\n };\n\n\n\n Some(Ok(CodePair::new(code, value, code_offset)))\n\n }\n\n fn read_code_pair_binary(&mut self) -> Option<DxfResult<CodePair>> {\n\n // Read code. If no data is available, fail gracefully.\n\n let mut code = match read_u8(&mut self.reader) {\n\n Some(Ok(c)) => i32::from(c),\n\n Some(Err(e)) => return Some(Err(DxfError::IoError(e))),\n", "file_path": "src/code_pair_iter.rs", "rank": 55, "score": 72213.5836955313 }, { "content": " pub fn new(reader: T, string_encoding: &'static Encoding, first_line: String) -> Self {\n\n CodePairIter {\n\n reader,\n\n string_encoding,\n\n first_line,\n\n read_first_line: false,\n\n read_as_text: true,\n\n is_post_r13_binary: false,\n\n returned_binary_pair: false,\n\n binary_detection_complete: false,\n\n offset: 0,\n\n }\n\n }\n\n pub fn read_as_utf8(&mut self) {\n\n self.string_encoding = encoding_rs::UTF_8;\n\n }\n\n fn detect_binary_or_text_file(&mut self) -> DxfResult<()> {\n\n match &*self.first_line {\n\n \"AutoCAD Binary DXF\" => {\n\n // swallow the next two bytes\n", "file_path": "src/code_pair_iter.rs", "rank": 56, "score": 72213.12583884464 }, { "content": " };\n\n let (value, read_bytes) = match expected_type {\n\n ExpectedType::Boolean => {\n\n // after R13 bools are encoded as a single byte\n\n let (b_value, read_bytes) = if self.is_post_r13_binary {\n\n (\n\n i16::from(try_from_dxf_result!(read_u8_strict(&mut self.reader))),\n\n 1,\n\n )\n\n } else {\n\n (try_from_dxf_result!(read_i16(&mut self.reader)), 2)\n\n };\n\n (CodePairValue::Boolean(b_value), read_bytes)\n\n }\n\n ExpectedType::Integer => (\n\n CodePairValue::Integer(try_from_dxf_result!(read_i32(&mut self.reader))),\n\n 4,\n\n ),\n\n ExpectedType::Long => (\n\n CodePairValue::Long(try_from_dxf_result!(read_i64(&mut self.reader))),\n", "file_path": "src/code_pair_iter.rs", "rank": 57, "score": 72212.11978343497 }, { "content": " Some(Ok(CodePair::new(code, value, self.offset)))\n\n }\n\n fn read_string_binary(&mut self) -> DxfResult<String> {\n\n let mut s = String::new();\n\n loop {\n\n match read_u8(&mut self.reader) {\n\n Some(Ok(0)) => break,\n\n Some(Ok(c)) => s.push(c as char),\n\n Some(Err(e)) => return Err(DxfError::IoError(e)),\n\n None => return Err(DxfError::UnexpectedEndOfInput),\n\n }\n\n }\n\n\n\n Ok(s)\n\n }\n\n}\n\n\n\nimpl<T: Read> Iterator for CodePairIter<T> {\n\n type Item = DxfResult<CodePair>;\n\n fn next(&mut self) -> Option<DxfResult<CodePair>> {\n", "file_path": "src/code_pair_iter.rs", "rank": 58, "score": 72211.53974895013 }, { "content": " 8,\n\n ),\n\n ExpectedType::Short => (\n\n CodePairValue::Short(try_from_dxf_result!(read_i16(&mut self.reader))),\n\n 2,\n\n ),\n\n ExpectedType::Double => (\n\n CodePairValue::Double(try_from_dxf_result!(read_f64(&mut self.reader))),\n\n 8,\n\n ),\n\n ExpectedType::Str => {\n\n let mut value = try_from_dxf_result!(self.read_string_binary());\n\n if !self.returned_binary_pair && code == 0 && value == \"\" {\n\n // If this is the first pair being read and the code is 0, the only valid string value is \"SECTION\".\n\n // If the read value is instead empty, that means the string reader found a single 0x00 byte which\n\n // indicates that this is a post R13 binary file where codes are always read as 2 bytes. The 0x00\n\n // byte was really the second byte of {0x00, 0x00}, so we need to do one more string read to catch\n\n // the reader up.\n\n self.is_post_r13_binary = true;\n\n self.offset += 1; // account for the NULL byte that was interpreted as an empty string\n", "file_path": "src/code_pair_iter.rs", "rank": 59, "score": 72211.0946479105 }, { "content": " value = try_from_dxf_result!(self.read_string_binary()); // now read the actual value\n\n }\n\n (\n\n CodePairValue::Str(CodePairValue::un_escape_string(&value).into_owned()),\n\n value.len() + 1, // +1 to account for the NULL terminator\n\n )\n\n }\n\n ExpectedType::Binary => {\n\n let length = try_from_dxf_result!(read_u8_strict(&mut self.reader)) as usize;\n\n let mut data = vec![];\n\n for _ in 0..length {\n\n data.push(try_from_dxf_result!(read_u8_strict(&mut self.reader)));\n\n }\n\n\n\n (CodePairValue::Binary(data), length + 1) // +1 to account for initial length byte\n\n }\n\n };\n\n self.offset += read_bytes;\n\n self.returned_binary_pair = true;\n\n\n", "file_path": "src/code_pair_iter.rs", "rank": 60, "score": 72210.6116684081 }, { "content": " return None;\n\n }\n\n\n\n let code_offset = self.offset;\n\n let code = try_into_option!(parse_i32(String::from(code_line), code_offset));\n\n\n\n // Read value. If no line is available die horribly.\n\n self.offset += 1;\n\n let value_line = match read_line(&mut self.reader, false, self.string_encoding) {\n\n Some(Ok(v)) => v,\n\n Some(Err(e)) => return Some(Err(e)),\n\n None => return Some(Err(DxfError::UnexpectedEndOfInput)),\n\n };\n\n\n\n // construct the value pair\n\n let expected_type = match ExpectedType::get_expected_type(code) {\n\n Some(t) => t,\n\n None => return Some(Err(DxfError::UnexpectedEnumValue(self.offset))),\n\n };\n\n let value = match expected_type {\n", "file_path": "src/code_pair_iter.rs", "rank": 61, "score": 72210.26383537218 }, { "content": " }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use crate::code_pair_iter::CodePairIter;\n\n use crate::CodePair;\n\n\n\n fn read_in_binary(data: Vec<u8>) -> CodePair {\n\n let mut reader = CodePairIter::<&[u8]> {\n\n reader: data.as_slice(),\n\n string_encoding: encoding_rs::WINDOWS_1252,\n\n first_line: String::from(\"not-important\"),\n\n read_first_line: true,\n\n read_as_text: false,\n\n is_post_r13_binary: true,\n\n returned_binary_pair: true,\n\n binary_detection_complete: true,\n\n offset: 0,\n", "file_path": "src/code_pair_iter.rs", "rank": 62, "score": 72207.45196890335 }, { "content": " ExpectedType::Boolean => {\n\n CodePairValue::Boolean(try_into_option!(parse_i16(value_line, self.offset)))\n\n }\n\n ExpectedType::Integer => {\n\n CodePairValue::Integer(try_into_option!(parse_i32(value_line, self.offset)))\n\n }\n\n ExpectedType::Long => {\n\n CodePairValue::Long(try_into_option!(parse_i64(value_line, self.offset)))\n\n }\n\n ExpectedType::Short => {\n\n CodePairValue::Short(try_into_option!(parse_i16(value_line, self.offset)))\n\n }\n\n ExpectedType::Double => {\n\n CodePairValue::Double(try_into_option!(parse_f64(value_line, self.offset)))\n\n }\n\n ExpectedType::Str => {\n\n let value_line = if self.string_encoding == encoding_rs::WINDOWS_1252 {\n\n un_escape_ascii_to_unicode(&value_line)\n\n } else {\n\n value_line\n", "file_path": "src/code_pair_iter.rs", "rank": 63, "score": 72203.70594901011 }, { "content": " None => return None,\n\n };\n\n self.offset += 1;\n\n\n\n // If reading a larger code and no data is available, die horribly.\n\n if self.is_post_r13_binary {\n\n // post R13 codes are 2 bytes, read the second byte of the code\n\n let high_byte = i32::from(try_from_dxf_result!(read_u8_strict(&mut self.reader)));\n\n code += high_byte << 8;\n\n self.offset += 1;\n\n } else if code == 255 {\n\n // pre R13 codes are either 1 or 3 bytes\n\n code = i32::from(try_from_dxf_result!(read_i16(&mut self.reader)));\n\n self.offset += 2;\n\n }\n\n\n\n // Read value. If no data is available die horribly.\n\n let expected_type = match ExpectedType::get_expected_type(code) {\n\n Some(t) => t,\n\n None => return Some(Err(DxfError::UnexpectedEnumValue(self.offset))),\n", "file_path": "src/code_pair_iter.rs", "rank": 64, "score": 72201.59837797454 }, { "content": " }\n\n fn read_code_pair_text(&mut self) -> Option<DxfResult<CodePair>> {\n\n // Read code. If no line is available, fail gracefully.\n\n let code_line = if self.read_first_line {\n\n self.offset += 1;\n\n match read_line(&mut self.reader, true, encoding_rs::WINDOWS_1252) {\n\n Some(Ok(v)) => v,\n\n Some(Err(e)) => return Some(Err(e)),\n\n None => return None,\n\n }\n\n } else {\n\n self.read_first_line = true;\n\n\n\n // .clone() is fine because it'll only ever be called once and the only valid\n\n // values that might be cloned are: \"0\" and \"999\"; all others are errors.\n\n self.first_line.clone()\n\n };\n\n let code_line = code_line.trim();\n\n if code_line.is_empty() {\n\n // might be an empty file only containing a newline\n", "file_path": "src/code_pair_iter.rs", "rank": 65, "score": 72201.23903719768 }, { "content": " loop {\n\n if !self.binary_detection_complete {\n\n match self.detect_binary_or_text_file() {\n\n Ok(_) => (),\n\n Err(e) => return Some(Err(e)),\n\n }\n\n }\n\n\n\n let pair = if self.read_as_text {\n\n self.read_code_pair_text()\n\n } else {\n\n self.read_code_pair_binary()\n\n };\n\n\n\n match pair {\n\n Some(Ok(CodePair { code, .. })) if code != 999 => return pair,\n\n Some(Ok(_)) => (), // a 999 comment code, try again\n\n Some(Err(_)) => return pair,\n\n None => return None,\n\n }\n", "file_path": "src/code_pair_iter.rs", "rank": 66, "score": 72200.52139061157 }, { "content": " );\n\n }\n\n\n\n #[test]\n\n fn read_binary_chunk_in_ascii() {\n\n let data = \"310\\r\\n0102\";\n\n let mut reader = CodePairIter::<&[u8]> {\n\n reader: data.as_bytes(),\n\n string_encoding: encoding_rs::WINDOWS_1252,\n\n first_line: String::from(\"not-important\"),\n\n read_first_line: true,\n\n read_as_text: true,\n\n is_post_r13_binary: false,\n\n returned_binary_pair: false,\n\n binary_detection_complete: true,\n\n offset: 0,\n\n };\n\n let pair = reader.read_code_pair_text().unwrap().unwrap();\n\n assert_eq!(310, pair.code);\n\n assert_eq!(\n", "file_path": "src/code_pair_iter.rs", "rank": 67, "score": 72198.04949680944 }, { "content": " };\n\n reader.read_code_pair_binary().unwrap().unwrap()\n\n }\n\n\n\n #[test]\n\n fn read_string_in_binary() {\n\n // code 0x0001, value 0x41 = \"A\", NUL\n\n let pair = read_in_binary(vec![0x01, 0x00, 0x41, 0x00]);\n\n assert_eq!(1, pair.code);\n\n assert_eq!(\"A\", pair.assert_string().expect(\"should be a string\"));\n\n }\n\n\n\n #[test]\n\n fn read_binary_chunk_in_binary() {\n\n // code 0x136, length 2, data [0x01, 0x02]\n\n let pair = read_in_binary(vec![0x36, 0x01, 0x02, 0x01, 0x02]);\n\n assert_eq!(310, pair.code);\n\n assert_eq!(\n\n vec![0x01, 0x02],\n\n pair.assert_binary().expect(\"should be binary\")\n", "file_path": "src/code_pair_iter.rs", "rank": 68, "score": 72195.9226952024 }, { "content": " vec![0x01, 0x02],\n\n pair.assert_binary().expect(\"should be binary\")\n\n );\n\n }\n\n\n\n #[test]\n\n fn read_code_450_in_binary() {\n\n // code 450 = 0x1C2, value = 37 (0x25)\n\n let pair = read_in_binary(vec![0xC2, 0x01, 0x25, 0x00, 0x00, 0x00]);\n\n assert_eq!(450, pair.code);\n\n assert_eq!(37, pair.assert_i32().expect(\"should be int\"));\n\n }\n\n}\n", "file_path": "src/code_pair_iter.rs", "rank": 69, "score": 72192.39554041911 }, { "content": " assert_or_err!(\n\n try_option_io_result_into_err!(read_u8(&mut self.reader)),\n\n 0x1A,\n\n 18\n\n );\n\n assert_or_err!(\n\n try_option_io_result_into_err!(read_u8(&mut self.reader)),\n\n 0x00,\n\n 19\n\n );\n\n self.read_as_text = false;\n\n self.offset = 20;\n\n }\n\n _ => {\n\n self.read_as_text = true;\n\n self.offset = 1;\n\n }\n\n }\n\n self.binary_detection_complete = true;\n\n Ok(())\n", "file_path": "src/code_pair_iter.rs", "rank": 70, "score": 72188.35000456046 }, { "content": "fn get_u32(data: &[u8], offset: usize) -> DxfResult<u32> {\n\n let expected_length = offset + 4;\n\n if data.len() < expected_length {\n\n return Err(DxfError::UnexpectedEndOfInput);\n\n }\n\n\n\n let value = data[offset] as u32\n\n + ((data[offset + 1] as u32) << 8)\n\n + ((data[offset + 2] as u32) << 16)\n\n + ((data[offset + 3] as u32) << 24);\n\n Ok(value)\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 71, "score": 71167.7363165715 }, { "content": "fn get_i32(data: &[u8], offset: usize) -> DxfResult<i32> {\n\n let expected_length = offset + 4;\n\n if data.len() < expected_length {\n\n return Err(DxfError::UnexpectedEndOfInput);\n\n }\n\n\n\n let value = data[offset] as i32\n\n + ((data[offset + 1] as i32) << 8)\n\n + ((data[offset + 2] as i32) << 16)\n\n + ((data[offset + 3] as i32) << 24);\n\n Ok(value)\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 72, "score": 71167.7363165715 }, { "content": "fn read_thumbnail_from_bytes(data: &[u8]) -> DxfResult<Option<image::DynamicImage>> {\n\n let image = image::load_from_memory(&data)?;\n\n Ok(Some(image))\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 73, "score": 67478.50873108323 }, { "content": "struct Oda {\n\n temp_path: String,\n\n input_path: String,\n\n output_path: String,\n\n oda_path: String,\n\n}\n\n\n\nimpl Drop for Oda {\n\n fn drop(&mut self) {\n\n if panicking() {\n\n println!(\"Test drawings at '{}'\", self.temp_path);\n\n } else {\n\n remove_dir_all(Path::new(&self.temp_path)).unwrap();\n\n }\n\n }\n\n}\n\n\n\nimpl Oda {\n\n pub fn convert_drawing(&self, drawing: &Drawing, version: AcadVersion) -> Drawing {\n\n drawing\n", "file_path": "src/misc_tests/integration.rs", "rank": 74, "score": 56585.77486313944 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n let dxf_path = &args[1];\n\n let mut json_path = dxf_path.clone();\n\n json_path.push_str(\".json\");\n\n\n\n let drawing = Drawing::load_file(&dxf_path).unwrap();\n\n let json = serde_json::to_string_pretty(&drawing).unwrap();\n\n\n\n let file = File::create(&json_path).unwrap();\n\n let mut writer = BufWriter::new(file);\n\n writer.write_all(json.as_bytes()).unwrap();\n\n}\n", "file_path": "dxf2json/src/main.rs", "rank": 75, "score": 51975.78816406516 }, { "content": "#[test]\n\nfn test_get_u32() {\n\n let data: Vec<u8> = vec![0x00, 0x78, 0x56, 0x34, 0x12, 0x00];\n\n let value = get_u32(&data, 1).unwrap();\n\n assert_eq!(0x12345678, value);\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 76, "score": 50261.672219435044 }, { "content": "#[test]\n\nfn test_get_i32() {\n\n let data: Vec<u8> = vec![0x00, 0x78, 0x56, 0x34, 0x12, 0x00];\n\n let value = get_i32(&data, 1).unwrap();\n\n assert_eq!(0x12345678, value);\n\n}\n\n\n", "file_path": "src/thumbnail.rs", "rank": 77, "score": 50261.672219435044 }, { "content": "#[test]\n\nfn unsupported_section() {\n\n let _file = from_section(\n\n \"UNSUPPORTED_SECTION\",\n\n vec![\"1\", \"garbage value 1\", \"2\", \"garbage value 2\"]\n\n .join(\"\\n\")\n\n .as_str(),\n\n );\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 78, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn as_datetime_conversion_test() {\n\n // from AutoDesk spec: 2451544.91568287 = 31 December 1999, 9:58:35PM\n\n assert_eq!(\n\n Local.ymd(1999, 12, 31).and_hms(21, 58, 35),\n\n as_datetime_local(2_451_544.915_682_87)\n\n );\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 79, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn enum_out_of_bounds() {\n\n let file = from_section(\n\n \"HEADER\",\n\n vec![\" 9\", \"$DIMZIN\", \" 70\", \" 8\"].join(\"\\r\\n\").trim(),\n\n );\n\n assert_eq!(\n\n UnitZeroSuppression::SuppressZeroFeetAndZeroInches,\n\n file.header.dimension_unit_zero_suppression\n\n );\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 80, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn parse_i32_test() {\n\n assert_eq!(2, parse_i32(\" 2 \".to_string(), 0).unwrap());\n\n}\n\n\n\npub(crate) fn parse_i64(s: String, offset: usize) -> DxfResult<i64> {\n\n match s.trim().parse::<i64>() {\n\n Ok(l) => Ok(l),\n\n Err(e) => Err(DxfError::ParseIntError(e, offset)),\n\n }\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 81, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn no_pointer_bound() {\n\n let drawing = from_section(\"ENTITIES\", vec![\" 0\", \"LINE\"].join(\"\\r\\n\").as_str());\n\n let entities = drawing.entities().collect::<Vec<_>>();\n\n match entities[0].common.get_material(&drawing) {\n\n None => (),\n\n _ => panic!(\"expected None\"),\n\n }\n\n}\n\n\n", "file_path": "src/misc_tests/pointers.rs", "rank": 82, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn parse_i64_test() {\n\n assert_eq!(2, parse_i64(\" 2 \".to_string(), 0).unwrap());\n\n}\n\n\n\npub(crate) fn parse_i16(s: String, offset: usize) -> DxfResult<i16> {\n\n match s.trim().parse::<f64>() {\n\n Ok(s) => Ok(s as i16),\n\n Err(e) => Err(DxfError::ParseFloatError(e, offset)),\n\n }\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 83, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn parse_i16_test() {\n\n assert_eq!(2, parse_i16(\" 2 \".to_string(), 0).unwrap());\n\n\n\n // some files write shorts as a double\n\n assert_eq!(2, parse_i16(\" 2.0 \".to_string(), 0).unwrap());\n\n}\n\n\n\npub(crate) fn read_color_value(layer: &mut Layer, color: i16) -> Color {\n\n layer.is_layer_on = color >= 0;\n\n Color::from_raw_value(color.abs())\n\n}\n\n\n\npub(crate) fn read_line<T>(\n\n reader: &mut T,\n\n allow_bom: bool,\n\n encoding: &'static Encoding,\n\n) -> Option<DxfResult<String>>\n\nwhere\n\n T: Read + ?Sized,\n\n{\n", "file_path": "src/helper_functions.rs", "rank": 84, "score": 48703.75926778125 }, { "content": "#[test]\n\n#[allow(clippy::float_cmp)]\n\nfn as_double_conversion_test() {\n\n // from AutoDesk spec: 2451544.91568287[04] = 31 December 1999, 9:58:35PM\n\n assert_eq!(\n\n 2_451_544.915_682_870_4,\n\n as_double_local(Local.ymd(1999, 12, 31).and_hms(21, 58, 35))\n\n );\n\n}\n\n\n\npub(crate) fn duration_as_double(duration: StdDuration) -> f64 {\n\n duration.as_secs() as f64\n\n}\n\n\n\npub(crate) fn as_duration(d: f64) -> StdDuration {\n\n StdDuration::from_secs(d as u64)\n\n}\n\n\n\npub(crate) fn as_uuid(s: String) -> Uuid {\n\n let mut reconstructed = String::new();\n\n let s = if s.starts_with('{') && s.ends_with('}') {\n\n // reconstruct the string without the braces\n", "file_path": "src/helper_functions.rs", "rank": 85, "score": 48703.75926778125 }, { "content": "#[test]\n\n#[allow(clippy::float_cmp)]\n\nfn parse_f64_test() {\n\n assert_eq!(2.5, parse_f64(\" 2.5 \".to_string(), 0).unwrap());\n\n}\n\n\n\npub(crate) fn parse_i32(s: String, offset: usize) -> DxfResult<i32> {\n\n match s.trim().parse::<i32>() {\n\n Ok(i) => Ok(i),\n\n Err(e) => Err(DxfError::ParseIntError(e, offset)),\n\n }\n\n}\n\n\n", "file_path": "src/helper_functions.rs", "rank": 86, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn round_trip() {\n\n // drawing with one entity and one auto-added layer\n\n let mut drawing = Drawing::new();\n\n drawing.clear();\n\n drawing.add_entity(Entity {\n\n common: Default::default(),\n\n specific: EntityType::Line(Default::default()),\n\n });\n\n assert_eq!(1, drawing.entities().count());\n\n assert_eq!(1, drawing.layers().count());\n\n\n\n // ensure they're still there\n\n let drawing = parse_drawing(&to_test_string(&drawing));\n\n assert_eq!(1, drawing.entities().count());\n\n assert_eq!(1, drawing.layers().count());\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 87, "score": 48703.75926778125 }, { "content": "#[test]\n\nfn parse_as_ascii_text() {\n\n // if version <= R2004 (AC1018) stream is ASCII\n\n let file = from_section(\n\n \"HEADER\",\n\n \"\n\n 9\n\n$ACADVER\n\n 1\n\nAC1018\n\n 9\n\n$PROJECTNAME\n\n 1\n\n\\\\U+00E8\"\n\n .trim_start(),\n\n );\n\n assert_eq!(\"è\", file.header.project_name);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 88, "score": 47281.62820300223 }, { "content": "#[test]\n\nfn parse_as_utf8_text() {\n\n // if version >= R2007 (AC1021) stream is UTF-8\n\n let file = from_section(\n\n \"HEADER\",\n\n \"\n\n 9\n\n$ACADVER\n\n 1\n\nAC1021\n\n 9\n\n$PROJECTNAME\n\n 1\n\nè\"\n\n .trim_start(),\n\n );\n\n assert_eq!(\"è\", file.header.project_name);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 89, "score": 47281.62820300223 }, { "content": "#[test]\n\nfn parse_with_leading_bom() {\n\n let buf = vec![\n\n 0xEFu8, 0xBB, 0xBF, // UTF-8 byte representation of BOM\n\n b'0', b'\\n', b'E', b'O', b'F',\n\n ];\n\n let _drawing = Drawing::load(&mut buf.as_slice());\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 90, "score": 47281.62820300223 }, { "content": "#[test]\n\nfn read_with_alternate_encoding() {\n\n let head = \"\n\n 0\n\nSECTION\n\n 2\n\nHEADER\n\n 9\n\n$PROJECTNAME\n\n 1\"\n\n .trim();\n\n let tail = \"\n\n 0\n\nENDSEC\n\n 0\n\nEOF\"\n\n .trim();\n\n let mut bytes = head.as_bytes().to_vec();\n\n bytes.push(b'\\r');\n\n bytes.push(b'\\n');\n\n bytes.push(0xB2); // these two bytes represent the character `不` in GB18030 encoding\n", "file_path": "src/misc_tests/encoding.rs", "rank": 91, "score": 47281.62820300223 }, { "content": "#[test]\n\nfn read_lf_and_crlf() {\n\n let code_pairs = vec![\n\n \"0\", \"SECTION\", \"2\", \"HEADER\", \"9\", \"$ACADVER\", \"1\", \"AC1027\", \"0\", \"ENDSEC\", \"0\", \"EOF\",\n\n ];\n\n\n\n let lf_file = parse_drawing(code_pairs.join(\"\\n\").as_str());\n\n assert_eq!(AcadVersion::R2013, lf_file.header.version);\n\n\n\n let crlf_file = parse_drawing(code_pairs.join(\"\\r\\n\").as_str());\n\n assert_eq!(AcadVersion::R2013, crlf_file.header.version);\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 92, "score": 47281.62820300223 }, { "content": "#[test]\n\nfn thumbnail_round_trip_grayscale() {\n\n // 1x1 px grayscale image, white\n\n let mut imgbuf = image::ImageBuffer::new(1, 1);\n\n imgbuf.put_pixel(0, 0, image::Luma([255]));\n\n let thumbnail = DynamicImage::ImageLuma8(imgbuf);\n\n\n\n let round_tripped = round_trip_thumbnail(thumbnail);\n\n assert_eq!((1, 1), round_tripped.dimensions());\n\n assert_eq!(\n\n image::Rgba([255u8, 255, 255, 255]),\n\n round_tripped.get_pixel(0, 0)\n\n ); // it comes back as RGB\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 93, "score": 45978.268928561476 }, { "content": "#[test]\n\nfn follow_entity_pointer_to_object() {\n\n let drawing = parse_drawing(\n\n vec![\n\n \" 0\",\n\n \"SECTION\",\n\n \" 2\",\n\n \"OBJECTS\",\n\n \" 0\",\n\n \"MATERIAL\",\n\n \" 5\",\n\n \"ABCD\",\n\n \" 1\",\n\n \"material-name\",\n\n \" 0\",\n\n \"ENDSEC\",\n\n \" 0\",\n\n \"SECTION\",\n\n \" 2\",\n\n \"ENTITIES\",\n\n \" 0\",\n", "file_path": "src/misc_tests/pointers.rs", "rank": 94, "score": 45978.268928561476 }, { "content": "#[test]\n\nfn parse_with_bom_like_in_the_middle() {\n\n let head = \"\n\n 0\n\nSECTION\n\n 2\n\nHEADER\n\n 9\n\n$PROJECTNAME\n\n 1\"\n\n .trim();\n\n let tail = \"\n\n 0\n\nENDSEC\n\n 0\n\nEOF\"\n\n .trim();\n\n let mut bytes = head.as_bytes().to_vec();\n\n bytes.push(b'\\r');\n\n bytes.push(b'\\n');\n\n bytes.push(0xEF); // these three bytes represent the character `ア` in UTF8\n", "file_path": "src/misc_tests/encoding.rs", "rank": 95, "score": 45978.268928561476 }, { "content": "#[test]\n\nfn thumbnail_round_trip_rgb8() {\n\n // 1x1 px image, red pixel\n\n let mut imgbuf = image::ImageBuffer::new(1, 1);\n\n imgbuf.put_pixel(0, 0, image::Rgb([255u8, 0, 0]));\n\n let thumbnail = DynamicImage::ImageRgb8(imgbuf);\n\n\n\n let round_tripped = round_trip_thumbnail(thumbnail);\n\n assert_eq!((1, 1), round_tripped.dimensions());\n\n assert_eq!(\n\n image::Rgba([255u8, 0, 0, 255]),\n\n round_tripped.get_pixel(0, 0)\n\n );\n\n}\n\n\n", "file_path": "src/misc_tests/encoding.rs", "rank": 96, "score": 45978.268928561476 }, { "content": "#[test]\n\nfn simple_line_can_be_read_by_oda() {\n\n let oda = require_oda!();\n\n let mut drawing = Drawing::new();\n\n drawing.add_entity(Entity {\n\n common: Default::default(),\n\n specific: EntityType::Line(Line {\n\n p1: Point::new(1.0, 2.0, 3.0),\n\n p2: Point::new(4.0, 5.0, 6.0),\n\n ..Default::default()\n\n }),\n\n });\n\n\n\n let round_tripped = oda.convert_drawing(&drawing, AcadVersion::R2000);\n\n let entities = round_tripped.entities().collect::<Vec<_>>();\n\n assert_eq!(1, entities.len());\n\n match entities[0].specific {\n\n EntityType::Line(ref line) => {\n\n assert_eq!(Point::new(1.0, 2.0, 3.0), line.p1);\n\n assert_eq!(Point::new(4.0, 5.0, 6.0), line.p2);\n\n }\n\n _ => panic!(\"expected a line\"),\n\n }\n\n}\n", "file_path": "src/misc_tests/integration.rs", "rank": 97, "score": 44779.39871409391 }, { "content": "#[derive(Clone, Copy, Debug, Eq, PartialEq)]\n\n#[cfg_attr(feature = \"serialize\", derive(Serialize, Deserialize))]\n\npub struct Handle(pub u64);\n\n\n\nimpl Handle {\n\n pub fn empty() -> Self {\n\n Handle(0)\n\n }\n\n pub fn next_handle_value(self) -> Self {\n\n Handle(self.0 + 1)\n\n }\n\n pub fn is_empty(self) -> bool {\n\n self.0 == 0\n\n }\n\n pub fn as_string(self) -> String {\n\n format!(\"{:X}\", self.0)\n\n }\n\n}\n", "file_path": "src/handle.rs", "rank": 98, "score": 40424.94523515273 }, { "content": " pub fn origin() -> Point {\n\n Point::new(0.0, 0.0, 0.0)\n\n }\n\n pub(crate) fn set(&mut self, pair: &CodePair) -> DxfResult<()> {\n\n match pair.code {\n\n 10 => self.x = pair.assert_f64()?,\n\n 20 => self.y = pair.assert_f64()?,\n\n 30 => self.z = pair.assert_f64()?,\n\n _ => {\n\n return Err(DxfError::UnexpectedCodePair(\n\n pair.clone(),\n\n String::from(\"expected code [10, 20, 30] for point\"),\n\n ))\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/point.rs", "rank": 99, "score": 40421.28278810569 } ]
Rust
src/lib.rs
liborty/sets
bef54da79d35c0a56305d122471a7cc386d20bd4
pub mod traitimpls; pub mod mutimpls; use std::ops::{Deref,DerefMut}; use indxvec::{MinMax,wv,Indices,merge::*}; pub fn trivindex(asc:bool,n:usize) -> Vec<usize> { if asc { (0..n).collect() } else { (0..n).rev().collect() } } pub struct Set<T> { pub v: Vec<T> } impl<T: std::fmt::Display> std::fmt::Display for Set<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!(f, "Unordered Set:\n{}",wv(&self.v)) } } impl<T> Deref for Set<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.v } } impl<T> DerefMut for Set<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.v } } impl<T> Set<T> where T: Copy { pub fn from_slice(s: &[T]) -> Self { Set { v: s.to_vec() } } pub fn from_indexed(s: &IndexedSet<T>) -> Self { Set{ v: s.v.to_vec() } } pub fn from_ranked(s: &RankedSet<T>) -> Self { Set{ v: s.v.to_vec() } } } pub struct OrderedSet<T> { pub ascending: bool, pub v: Vec<T>, } impl<T: std::fmt::Display> std::fmt::Display for OrderedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Ordered Set:\n{}", s, wv(&self.v) ) } } impl<T> Deref for OrderedSet<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.v } } impl<T> DerefMut for OrderedSet<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.v } } impl<T> OrderedSet<T> { pub fn from_asc_slice(s: &[T]) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:true, v: s.to_vec() } } pub fn from_desc_slice(s: &[T]) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:false, v: s.to_vec() } } pub fn from_slice(s: &[T], asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: sortm(s,asc) } } pub fn from_set(s: &Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: sortm(&s.v,asc) } } pub fn from_indexed(s: &IndexedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: s.i.unindex(&s.v,asc == s.ascending) } } pub fn from_ranked(s: &RankedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: s.i.invindex().unindex(&s.v,asc == s.ascending) } } } pub struct IndexedSet<T> { pub ascending: bool, pub v: Vec<T>, pub i: Vec<usize>, } impl<'a,T: std::fmt::Display> std::fmt::Display for IndexedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Indexed Set\nSet: {}\nIndex: {}", s, wv(&self.v), wv(&self.i) ) } } impl<'a,T> IndexedSet<T> { pub fn from_slice(s: &'a[T], asc:bool) -> Self where T:PartialOrd+Copy { if asc { IndexedSet{ ascending:true, v:s.to_vec(), i:sortidx(s) } } else { IndexedSet{ ascending:false, v:s.to_vec(), i:sortidx(s).revindex() } } } pub fn from_set(s: &'a Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc { IndexedSet{ ascending:true, v:s.v.to_vec(), i:sortidx(&s.v) } } else { IndexedSet{ ascending:false, v:s.v.to_vec(), i:sortidx(&s.v).revindex() } } } pub fn from_ordered(s: &'a OrderedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { IndexedSet{ ascending:asc, v:s.v.to_vec(), i:trivindex(asc == s.ascending,s.len()) } } pub fn from_ranked(s: &'a RankedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc == s.ascending { IndexedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex() } } else { IndexedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.complindex().invindex() } } } } pub struct RankedSet<T> { pub ascending: bool, pub v: Vec<T>, pub i: Vec<usize>, } impl<'a,T: std::fmt::Display> std::fmt::Display for RankedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Ranked Set\nSet: {}\nRanks: {}", s, wv(&self.v), wv(&self.i) ) } } impl<T> RankedSet<T> { pub fn from_slice(s: &[T], asc:bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.to_vec(), i:rank(s,asc) } } pub fn from_set(s: &Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.v.to_vec(), i:rank(s,asc) } } pub fn from_ordered(s: &OrderedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.v.to_vec(), i:trivindex(asc == s.ascending,s.len()) } } pub fn from_indexed(s: &IndexedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc == s.ascending { RankedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex() } } else { RankedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex().complindex() } } } } pub trait SetOps<T> { fn reverse(&self) -> Self; fn nonrepeat(&self) -> Self; fn infsup(&self) -> MinMax<T>; fn member(&self, m: T) -> bool; fn search(&self, m: T) -> Option<usize>; fn union(&self, s: &Self) -> OrderedSet<T>; fn intersection(&self, s: &Self) -> OrderedSet<T>; fn difference(&self, s: &Self) -> OrderedSet<T>; } pub trait MutSetOps<T> { fn mreverse(&mut self); fn mnonrepeat(&mut self); fn munion(&mut self, s: &Self); fn mintersection(&mut self, s: &Self); fn mdifference(&mut self, s: &Self); }
pub mod traitimpls; pub mod mutimpls; use std::ops::{Deref,DerefMut}; use indxvec::{MinMax,wv,Indices,merge::*}; pub fn trivindex(asc:bool,n:usize) -> Vec<usize> { if asc { (0..n).collect() } else { (0..n).rev().collect() } } pub struct Set<T> { pub v: Vec<T> } impl<T: std::fmt::Display> std::fmt::Display for Set<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!(f, "Unordered Set:\n{}",wv(&self.v)) } } impl<T> Deref for Set<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.v } } impl<T> DerefMut for Set<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.v } } impl<T> Set<T> where T: Copy { pub fn from_slice(s: &[T]) -> Self { Set { v: s.to_vec() } } pub fn from_indexed(s: &IndexedSet<T>) -> Self { Set{ v: s.v.to_vec() } } pub fn from_ranked(s: &RankedSet<T>) -> Self { Set{ v: s.v.to_vec() } } } pub struct OrderedSet<T> { pub ascending: bool, pub v: Vec<T>, } impl<T: std::fmt::Display> std::fmt::Display for OrderedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(
} impl<T> Deref for OrderedSet<T> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.v } } impl<T> DerefMut for OrderedSet<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.v } } impl<T> OrderedSet<T> { pub fn from_asc_slice(s: &[T]) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:true, v: s.to_vec() } } pub fn from_desc_slice(s: &[T]) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:false, v: s.to_vec() } } pub fn from_slice(s: &[T], asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: sortm(s,asc) } } pub fn from_set(s: &Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: sortm(&s.v,asc) } } pub fn from_indexed(s: &IndexedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: s.i.unindex(&s.v,asc == s.ascending) } } pub fn from_ranked(s: &RankedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { OrderedSet{ ascending:asc, v: s.i.invindex().unindex(&s.v,asc == s.ascending) } } } pub struct IndexedSet<T> { pub ascending: bool, pub v: Vec<T>, pub i: Vec<usize>, } impl<'a,T: std::fmt::Display> std::fmt::Display for IndexedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Indexed Set\nSet: {}\nIndex: {}", s, wv(&self.v), wv(&self.i) ) } } impl<'a,T> IndexedSet<T> { pub fn from_slice(s: &'a[T], asc:bool) -> Self where T:PartialOrd+Copy { if asc { IndexedSet{ ascending:true, v:s.to_vec(), i:sortidx(s) } } else { IndexedSet{ ascending:false, v:s.to_vec(), i:sortidx(s).revindex() } } } pub fn from_set(s: &'a Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc { IndexedSet{ ascending:true, v:s.v.to_vec(), i:sortidx(&s.v) } } else { IndexedSet{ ascending:false, v:s.v.to_vec(), i:sortidx(&s.v).revindex() } } } pub fn from_ordered(s: &'a OrderedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { IndexedSet{ ascending:asc, v:s.v.to_vec(), i:trivindex(asc == s.ascending,s.len()) } } pub fn from_ranked(s: &'a RankedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc == s.ascending { IndexedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex() } } else { IndexedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.complindex().invindex() } } } } pub struct RankedSet<T> { pub ascending: bool, pub v: Vec<T>, pub i: Vec<usize>, } impl<'a,T: std::fmt::Display> std::fmt::Display for RankedSet<T> where T:Copy { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let n = self.v.len(); if n == 0 { return writeln!(f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Ranked Set\nSet: {}\nRanks: {}", s, wv(&self.v), wv(&self.i) ) } } impl<T> RankedSet<T> { pub fn from_slice(s: &[T], asc:bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.to_vec(), i:rank(s,asc) } } pub fn from_set(s: &Set<T>, asc: bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.v.to_vec(), i:rank(s,asc) } } pub fn from_ordered(s: &OrderedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { RankedSet{ ascending:asc, v:s.v.to_vec(), i:trivindex(asc == s.ascending,s.len()) } } pub fn from_indexed(s: &IndexedSet<T>, asc: bool) -> Self where T:PartialOrd+Copy { if asc == s.ascending { RankedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex() } } else { RankedSet{ ascending: asc, v: s.v.to_vec(), i:s.i.invindex().complindex() } } } } pub trait SetOps<T> { fn reverse(&self) -> Self; fn nonrepeat(&self) -> Self; fn infsup(&self) -> MinMax<T>; fn member(&self, m: T) -> bool; fn search(&self, m: T) -> Option<usize>; fn union(&self, s: &Self) -> OrderedSet<T>; fn intersection(&self, s: &Self) -> OrderedSet<T>; fn difference(&self, s: &Self) -> OrderedSet<T>; } pub trait MutSetOps<T> { fn mreverse(&mut self); fn mnonrepeat(&mut self); fn munion(&mut self, s: &Self); fn mintersection(&mut self, s: &Self); fn mdifference(&mut self, s: &Self); }
f,"[]") } let s = if self.ascending { String::from("Ascending") } else { String::from("Descending") }; writeln!(f, "{} Ordered Set:\n{}", s, wv(&self.v) ) }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn conversions() { \n\n let v = vec![1.,14.,2.,13.,3.,12.,4.,11.,5.,10.,10.,6.,9.,7.,8.,16.];\n\n let setv = Set::from_slice(&v); \n\n println!(\"{}\",setv); // Display of Set \n\n println!(\"Slice-> {}\",OrderedSet::from_slice(&v,true)); // sorted data but index lost\n\n println!(\"Set-> {}\",OrderedSet::from_set(&setv,false)); // descending sorted data, index lost \n\n let ix = IndexedSet::from_set(&setv,false); \n\n println!(\"Set-> {}\",&ix);\n\n let ss = OrderedSet::from_indexed(&ix,false); \n\n println!(\"Indexed-> {}\",ss); \n\n println!(\"Ordered-> {}\",IndexedSet::from_ordered(&ss,false)); \n\n println!(\"Ordered-> {}\",RankedSet::from_ordered(&ss,true)); \n\n let rx = RankedSet::from_slice(&v,false);\n\n println!(\"Slice->{}\",&rx);\n\n println!(\"Ranked->{}\",IndexedSet::from_ranked(&rx,true)); \n\n println!(\"Ranked->{}\",OrderedSet::from_ranked(&rx,true)); \n\n println!(\"Indexed->{}\",RankedSet::from_indexed(&ix,true));\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 3, "score": 27325.308665060304 }, { "content": "#[test]\n\nfn mutabletest() { \n\n let v = vec![1.,14.,2.,13.,3.,12.,4.,11.,5.,10.,10.,6.,9.,7.,8.,16.]; \n\n let mut setv = RankedSet::from_slice(&v,false); \n\n println!(\"{}\",setv); // Display of Set \n\n let mut setw = RankedSet::from_slice(&[20.,19.,18.,17.,16.,15.],true);\n\n println!(\"{}\",setw);\n\n setw.munion(&setv);\n\n println!(\"Union-> {}\",&setw);\n\n setv.mintersection(&setw);\n\n println!(\"Intersection-> {}\",&setv);\n\n setw.mdifference(&setv);\n\n println!(\"Difference-> {}\",&setw);\n\n}\n\n \n", "file_path": "tests/tests.rs", "rank": 4, "score": 27325.308665060304 }, { "content": "#[test]\n\nfn settest() { \n\n let v = vec![1.,14.,2.,13.,3.,12.,4.,11.,5.,10.,10.,6.,9.,7.,8.,16.]; \n\n let setv = RankedSet::from_slice(&v,false); \n\n println!(\"{}\",setv); // Display of Set\n\n println!(\"Reverse-> {}\",setv.reverse()); \n\n println!(\"Nonrepeat-> {}\",setv.nonrepeat()); // Display of Set \n\n println!(\"Is {} a member? {}\\n\",wi(&0.0),wi(&setv.member(0.0))); \n\n println!(\"Infsup: {}\",setv.infsup());\n\n let setw = RankedSet::from_slice(&[20.,19.,18.,17.,16.,15.],true);\n\n println!(\"{}\",setw);\n\n let us = setw.union(&setv);\n\n println!(\"Union-> {}\",&us);\n\n println!(\"Intersection-> {}\",setw.intersection(&setv));\n\n println!(\"Difference-> {}\",setv.difference(&setw));\n\n}\n\n\n", "file_path": "tests/tests.rs", "rank": 5, "score": 27325.308665060304 }, { "content": "#[test]\n\nfn nlptest() { \n\n let sentence1 = \"Alphabetic ordering puts capital Letters first.\";\n\n let sentence2 = \"It sorts by Letters, ordering by Letters\"; \n\n let v1 = sentence1.split(' ').collect::<Vec<_>>();\n\n let v2 = sentence2.split(' ').collect::<Vec<_>>(); \n\n let setv = RankedSet::from_slice(&v1,false); \n\n println!(\"{}\",setv); // Display of Set\n\n println!(\"Reverse-> {}\",setv.reverse()); \n\n println!(\"Nonrepeat-> {}\",setv.nonrepeat()); // Display of Set \n\n println!(\"Is {} a member? {}\\n\",wi(&\"Spain\"),wi(&setv.member(\"Spain\"))); \n\n println!(\"Infsup: {}\",setv.infsup());\n\n let setw = RankedSet::from_slice(&v2,true);\n\n println!(\"{}\",setw);\n\n let us = setw.union(&setv);\n\n println!(\"Union-> {}\",&us);\n\n println!(\"Intersection-> {}\",setw.intersection(&setv));\n\n println!(\"Difference-> {}\",setv.difference(&setw));\n\n}", "file_path": "tests/tests.rs", "rank": 6, "score": 27325.308665060304 }, { "content": "use crate::{trivindex,Set,OrderedSet,IndexedSet,RankedSet,MutSetOps};\n\nuse indxvec::{Indices,merge::*};\n\n\n\nimpl<T> MutSetOps<T> for Set<T> where T:Copy+PartialOrd {\n\n\n\n /// Reverses a vec by iterating over only half of its length\n\n /// and swapping the items\n\n fn mreverse(&mut self) { \n\n let n = self.v.len();\n\n for i in 0..n/2 {\n\n let temp = self.v[i];\n\n self.v[i] = self.v[n-i-1];\n\n self.v[n-i-1] = temp } \n\n }\n\n\n\n /// Deletes any repetitions\n\n fn mnonrepeat(&mut self) { self.v = sansrepeat(&self.v) }\n\n\n\n /// Union of two unordered sets, assigned to self \n\n fn munion(&mut self, s: &Self) {\n", "file_path": "src/mutimpls.rs", "rank": 7, "score": 19578.057427320404 }, { "content": "impl<T> MutSetOps<T> for OrderedSet<T> where T:Copy+PartialOrd {\n\n\n\n /// Reverses a vec by iterating over only half of its length\n\n /// and swapping the items\n\n fn mreverse(&mut self) { \n\n self.ascending = !self.ascending;\n\n let n = self.v.len();\n\n for i in 0..n/2 {\n\n let temp = self.v[i];\n\n self.v[i] = self.v[n-i-1];\n\n self.v[n-i-1] = temp } \n\n }\n\n\n\n /// Deletes any repetitions\n\n fn mnonrepeat(&mut self) { self.v = sansrepeat(&self.v) } \n\n\n\n /// Ascending union of two ordered sets, reassigned to self \n\n fn munion(&mut self, s: &Self) { \n\n if self.ascending {\n\n if s.ascending { self.v = unite(&self.v,&s.v) }\n", "file_path": "src/mutimpls.rs", "rank": 8, "score": 19576.598165493855 }, { "content": " }\n\n\n\n /// Ascending complement of s in self (i.e. self-s)\n\n fn mdifference(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = diff(&self.v,&s.v) } \n\n else { self.v = diff(&self.v, &revs(&s.v)) } \n\n }\n\n else {\n\n self.ascending = true; \n\n if s.ascending { self.v = diff(&revs(&self.v),&s.v) } \n\n else { self.v = diff(&revs(&self.v), &revs(&s.v)) } \n\n }\n\n }\n\n}\n\n\n\n/// These are generally better than OrderedSet(s) for bulky end types, as\n\n/// there is not so much of moving them around.\n\nimpl<T> MutSetOps<T> for IndexedSet<T> where T: Copy+PartialOrd {\n\n\n", "file_path": "src/mutimpls.rs", "rank": 9, "score": 19576.40452304868 }, { "content": "/// The primitive functions from `indxvec` all expect indexed sets, \n\n/// so for now we convert from ranks to sort indices using `.invindex()`.\n\n/// Even though that is a simple operation, for lots of set operations, \n\n/// it will be slightly quicker to work in IndexedSet(s) \n\n/// and only to rank the final result.\n\nimpl<T> MutSetOps<T> for RankedSet<T> where T: Copy+PartialOrd {\n\n /// just make the ranks descending\n\n fn mreverse(&mut self) {\n\n self.ascending = !self.ascending;\n\n self.i = self.i.complindex() \n\n }\n\n \n\n /// deletes repetitions.\n\n fn mnonrepeat(&mut self) { \n\n let clean = &sansrepeat(&self.v);\n\n self.v = clean.to_vec();\n\n self.i = rank(clean, self.ascending ) \n\n } \n\n \n\n /// Union of two IndexedSets. \n", "file_path": "src/mutimpls.rs", "rank": 10, "score": 19575.852410773106 }, { "content": " /// just reverse the index\n\n fn mreverse(&mut self) {\n\n self.ascending = !self.ascending;\n\n self.i = self.i.revindex() \n\n }\n\n \n\n /// deletes repetitions.\n\n fn mnonrepeat(&mut self) { \n\n let clean = &sansrepeat(&self.v);\n\n self.v = clean.to_vec();\n\n self.i = sortidx(clean) \n\n } \n\n\n\n /// Union of two IndexedSets reassigned to self. \n\n /// self will be ascending ordered \n\n fn munion(&mut self, s: &Self) { \n\n if self.ascending { \n\n if s.ascending { self.v = unite_indexed(&self.v,&self.i,&s.v, &s.i) }\n\n else { self.v = unite_indexed(&self.v, &self.i,&s.v, &s.i.revindex() ) } \n\n }\n", "file_path": "src/mutimpls.rs", "rank": 11, "score": 19574.707958731822 }, { "content": " let s1 = sortm(&self.v,true);\n\n let s2 = sortm(&s.v,true);\n\n self.v = unite(&s1,&s2) \n\n }\n\n\n\n /// Intersection of two unordered sets, assigned to self\n\n fn mintersection(&mut self, s: &Self) {\n\n let s1 = sortm(self,true);\n\n let s2 = sortm(s,true);\n\n self.v = intersect(&s1,&s2) \n\n }\n\n\n\n /// Complement of s in self (i.e. self -= s)\n\n fn mdifference(&mut self, s: &Self) {\n\n let s1 = sortm(self,true);\n\n let s2 = sortm(s,true); \n\n self.v = diff(&s1,&s2) \n\n } \n\n}\n\n\n", "file_path": "src/mutimpls.rs", "rank": 12, "score": 19574.201831090697 }, { "content": " fn munion(&mut self, s: &Self) { \n\n if self.ascending {\n\n if s.ascending { self.v = unite_indexed(&self.v,&self.i.invindex(),&s.v, &s.i.invindex()) }\n\n else { self.v = unite_indexed(&self.v, &self.i.invindex(),&s.v, &s.i.invindex().revindex() ) } \n\n }\n\n else {\n\n self.ascending = true; \n\n if s.ascending { self.v = unite_indexed(&self.v, &self.i.invindex().revindex(),&s.v,&s.i.invindex()) } \n\n else { self.v = unite_indexed(&self.v, &self.i.invindex().revindex(), &s.v, &s.i.invindex().revindex()) } \n\n }\n\n // result ranks will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n } \n\n \n\n /// Intersection of two IndexedSets\n\n fn mintersection(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = intersect_indexed(&self.v,&self.i.invindex(),&s.v, &s.i.invindex()) }\n\n else { self.v = intersect_indexed(&self.v, &self.i.invindex(),&s.v, &s.i.invindex().revindex() ) } \n\n }\n", "file_path": "src/mutimpls.rs", "rank": 13, "score": 19574.18724772261 }, { "content": " else { self.v = unite(&self.v, &revs(&s.v)) }\n\n }\n\n else {\n\n self.ascending = true; // the result is always ascending\n\n if s.ascending { self.v = unite(&revs(&self.v),&s.v) }\n\n else { self.v = unite(&revs(&self.v), &revs(&s.v)) } \n\n }\n\n } \n\n\n\n /// Ascending intersection of two sets, assigned to the self \n\n fn mintersection(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = intersect(&self.v,&s.v) }\n\n else { self.v = intersect(&self.v, &revs(&s.v)) }\n\n }\n\n else {\n\n self.ascending = true; // the result is always ascending\n\n if s.ascending { self.v = intersect(&revs(&self.v),&s.v) } \n\n else { self.v = intersect(&revs(&self.v), &revs(&s.v)) } \n\n }\n", "file_path": "src/mutimpls.rs", "rank": 14, "score": 19574.035043614032 }, { "content": " else {\n\n self.ascending = true; \n\n if s.ascending { self.v = unite_indexed(&self.v, &self.i.revindex(),&s.v,&s.i) } \n\n else { self.v = unite_indexed(&self.v, &self.i.revindex(), &s.v, &s.i.revindex()) } \n\n }\n\n // result index will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n } \n\n \n\n /// Intersection of two IndexedSets\n\n fn mintersection(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = intersect_indexed(&self.v,&self.i,&s.v, &s.i) }\n\n else { self.v = intersect_indexed(&self.v, &self.i,&s.v, &s.i.revindex() ) } \n\n }\n\n else {\n\n self.ascending = true; \n\n if s.ascending { self.v = intersect_indexed(&self.v, &self.i.revindex(),&s.v,&s.i) } \n\n else { self.v = intersect_indexed(&self.v, &self.i.revindex(), &s.v, &s.i.revindex()) } \n\n }\n", "file_path": "src/mutimpls.rs", "rank": 15, "score": 19573.624872284043 }, { "content": " // result index will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n }\n\n \n\n /// Complement of s in self (i.e. self-s)\n\n fn mdifference(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = diff_indexed(&self.v,&self.i,&s.v, &s.i) }\n\n else { self.v = diff_indexed(&self.v, &self.i,&s.v, &s.i.revindex() ) } \n\n }\n\n else {\n\n self.ascending = true; \n\n if s.ascending { self.v = intersect_indexed(&self.v, &self.i.revindex(),&s.v,&s.i) } \n\n else { self.v = intersect_indexed(&self.v, &self.i.revindex(), &s.v, &s.i.revindex()) } \n\n }\n\n // result index will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n }\n\n}\n\n\n", "file_path": "src/mutimpls.rs", "rank": 16, "score": 19572.659996118524 }, { "content": " else {\n\n self.ascending = true; \n\n if s.ascending { self.v = intersect_indexed(&self.v, &self.i.invindex().revindex(),&s.v,&s.i.invindex()) } \n\n else { self.v = intersect_indexed(&self.v, &self.i.invindex().revindex(), &s.v, &s.i.invindex().revindex()) } \n\n }\n\n // result ranks will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n }\n\n \n\n /// Complement of s in self (i.e. self-s)\n\n fn mdifference(&mut self, s: &Self) {\n\n if self.ascending {\n\n if s.ascending { self.v = diff_indexed(&self.v,&self.i.invindex(),&s.v, &s.i.invindex()) }\n\n else { self.v = diff_indexed(&self.v, &self.i.invindex(),&s.v, &s.i.invindex().revindex() ) } \n\n }\n\n else {\n\n self.ascending = true; \n\n if s.ascending { self.v = intersect_indexed(&self.v, &self.i.invindex().revindex(),&s.v,&s.i.invindex()) } \n\n else { self.v = intersect_indexed(&self.v, &self.i.invindex().revindex(), &s.v, &s.i.invindex().revindex()) } \n\n }\n\n // result ranks will be of the new size but in all cases trivial and ascending\n\n self.i = trivindex(true,self.v.len()); \n\n }\n\n}", "file_path": "src/mutimpls.rs", "rank": 17, "score": 19572.188980239145 }, { "content": " fn member(&self, m: T) -> bool { \n\n let opt = member(&self.v,m);\n\n opt.is_some() \n\n }\n\n\n\n /// Search a Set for m. Returns index of the first m.\n\n fn search(&self, m: T) -> Option<usize> {\n\n member(&self.v,m)\n\n }\n\n\n\n /// Union of two unordered sets of the same type - \n\n fn union(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = sortm(self,true);\n\n let s2 = sortm(s,true);\n\n OrderedSet { ascending:true,v:unite(&s1,&s2) }\n\n }\n\n\n\n /// Intersection of two sets of the same type\n\n fn intersection(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = sortm(self,true);\n", "file_path": "src/traitimpls.rs", "rank": 18, "score": 19417.02115113477 }, { "content": " \n\n /// True if m is a member of the set\n\n fn member(&self, m: T) -> bool { \n\n let opt = if self.ascending { memsearch_indexed(&self.v,&self.i.invindex(),m) }\n\n else { memsearchdesc_indexed(&self.v,&self.i.invindex(),m) };\n\n opt.is_some() \n\n }\n\n \n\n /// Search a Set for m. Returns index of the first m.\n\n fn search(&self, m: T) -> Option<usize> {\n\n if self.ascending { memsearch_indexed(&self.v,&self.i.invindex(),m) }\n\n else { memsearchdesc_indexed(&self.v,&self.i.invindex(),m) } \n\n }\n\n \n\n /// Union of two RankedSets. Returns an OrderedSet \n\n fn union(&self, s: &Self) -> OrderedSet<T> { \n\n if self.ascending {\n\n if s.ascending { OrderedSet{ ascending:self.ascending, v: unite_indexed(&self.v,&self.i.invindex(),&s.v, &s.i.invindex())} }\n\n else { OrderedSet { ascending:true, v: unite_indexed(&self.v, &self.i.invindex(),&s.v, &s.i.invindex().revindex() ) } }\n\n }\n", "file_path": "src/traitimpls.rs", "rank": 19, "score": 19416.27644464635 }, { "content": " \n\n /// Search a Set for m. Returns index of the first m.\n\n fn search(&self, m: T) -> Option<usize> {\n\n if self.ascending { memsearch_indexed(&self.v,&self.i,m) }\n\n else { memsearchdesc_indexed(&self.v,&self.i,m) } \n\n }\n\n \n\n /// Union of two IndexedSets. Returns an OrderedSet. \n\n fn union(&self, s: &Self) -> OrderedSet<T> { \n\n if self.ascending {\n\n if s.ascending { OrderedSet{ ascending:self.ascending, v: unite_indexed(&self.v,&self.i,&s.v, &s.i)} }\n\n else { OrderedSet { ascending:true, v: unite_indexed(&self.v, &self.i,&s.v, &s.i.revindex() ) } }\n\n }\n\n else if s.ascending { OrderedSet { ascending:true, v:unite_indexed(&self.v, &self.i.revindex(),&s.v,&s.i) } }\n\n else { OrderedSet { ascending:true, v:unite_indexed(&self.v, &self.i.revindex(), &s.v, &s.i.revindex()) } } \n\n } \n\n \n\n /// Intersection of two sets of the same type. \n\n /// Via OrderedSet for convenience, for now.\n\n /// Probably should use intersect_indexed as in `union` above.\n", "file_path": "src/traitimpls.rs", "rank": 20, "score": 19416.193210849116 }, { "content": " fn nonrepeat(&self) -> Self { \n\n Self { ascending: self.ascending, v: sansrepeat(&self.v) }\n\n }\n\n\n\n /// Finds minimum, minimum's first index, maximum, maximum's first index\n\n /// Much simpler for OrderedSet than for Set.\n\n fn infsup(&self) -> MinMax<T> {\n\n let last = self.v.len()-1;\n\n if self.ascending { MinMax{min:self.v[0],minindex:0,max:self.v[last],maxindex:last} }\n\n else { MinMax{min:self.v[last],minindex:last,max:self.v[0],maxindex:0} }\n\n }\n\n\n\n /// True if m is a member of the set\n\n fn member(&self, m: T) -> bool { \n\n let opt = if self.ascending { memsearch(&self.v,m) }\n\n else { memsearchdesc(&self.v,m) };\n\n opt.is_some() \n\n }\n\n\n\n /// Search a Set for m. Returns index of the first m.\n", "file_path": "src/traitimpls.rs", "rank": 21, "score": 19415.72913304297 }, { "content": "\n\n /// Complement of s in self (i.e. self-s)\n\n fn difference(&self, s: &Self) -> OrderedSet<T> {\n\n let rself; let rs; \n\n OrderedSet { ascending:true, v:diff(\n\n if self.ascending {&self.v} else {rself = revs(&self.v); &rself},\n\n if s.ascending {&s.v} else {rs = revs(&s.v); &rs}) } \n\n }\n\n}\n\n\n\n/// These are generally better than OrderedSet(s) for bulky end types, as\n\n/// there is not so much of moving them around.\n\nimpl<T> SetOps<T> for IndexedSet<T> where T: Copy+PartialOrd {\n\n\n\n /// just reverse the index\n\n fn reverse(&self) -> Self where T: Copy {\n\n Self { ascending: !self.ascending, v: self.v.to_vec(), i: self.i.revindex() }\n\n }\n\n \n\n /// Deletes repetitions.\n", "file_path": "src/traitimpls.rs", "rank": 22, "score": 19415.35966705323 }, { "content": " let s2 = sortm(s,true);\n\n OrderedSet { ascending:true,v:intersect(&s1,&s2) }\n\n }\n\n\n\n /// Complement of s in self (i.e. self-s)\n\n fn difference(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = sortm(self,true);\n\n let s2 = sortm(s,true); \n\n OrderedSet { ascending:true,v:diff(&s1,&s2) } \n\n }\n\n \n\n}\n\n\n\nimpl<T> SetOps<T> for OrderedSet<T> where T: Copy+PartialOrd {\n\n\n\n fn reverse(&self) -> Self where T: Copy {\n\n Self { ascending: !self.ascending, v: revs(&self.v) }\n\n }\n\n\n\n /// Deletes any repetitions, in either order\n", "file_path": "src/traitimpls.rs", "rank": 23, "score": 19415.313937297247 }, { "content": "use crate::{SetOps,Set,OrderedSet,IndexedSet,RankedSet};\n\nuse indxvec::{MinMax,Indices,merge::*};\n\n\n\nimpl<T> SetOps<T> for Set<T> where T:Copy+PartialOrd {\n\n\n\n fn reverse(&self) -> Self {\n\n Self { v: revs(&self.v) }\n\n }\n\n\n\n /// Deletes any repetitions\n\n fn nonrepeat(&self) -> Self { \n\n Self { v: sansrepeat(&self.v) }\n\n }\n\n\n\n /// Finds minimum, minimum's first index, maximum, maximum's first index of &[T] \n\n fn infsup(&self) -> MinMax<T> {\n\n minmax(&self.v) \n\n }\n\n\n\n /// True if m is a member of the set\n", "file_path": "src/traitimpls.rs", "rank": 24, "score": 19415.02611741583 }, { "content": " else if s.ascending { OrderedSet { ascending:true, v:unite_indexed(&self.v, &self.i.invindex().revindex(),&s.v,&s.i.invindex()) } }\n\n else { OrderedSet { ascending:true, v:unite_indexed(&self.v, &self.i.invindex().revindex(), &s.v, &s.i.invindex().revindex()) } } \n\n } \n\n \n\n /// Intersection of two RankedSets. \n\n /// Via OrderedSet for convenience, for now.\n\n /// Todo: Probably should use intersect_indexed as in `union` above.\n\n fn intersection(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = OrderedSet::from_ranked(self,true);\n\n let s2 = OrderedSet::from_ranked(s,true);\n\n s1.intersection(&s2)\n\n }\n\n \n\n /// Complement of s in self (i.e. self-s)\n\n fn difference(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = OrderedSet::from_ranked(self,true);\n\n let s2 = OrderedSet::from_ranked(s,true); \n\n s1.difference(&s2) \n\n } \n\n\n\n}", "file_path": "src/traitimpls.rs", "rank": 25, "score": 19414.07855853833 }, { "content": " fn intersection(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = OrderedSet::from_indexed(self,true);\n\n let s2 = OrderedSet::from_indexed(s,true);\n\n s1.intersection(&s2)\n\n }\n\n \n\n /// Complement of s in self (i.e. self-s)\n\n fn difference(&self, s: &Self) -> OrderedSet<T> {\n\n let s1 = OrderedSet::from_indexed(self,true);\n\n let s2 = OrderedSet::from_indexed(s,true); \n\n s1.difference(&s2) \n\n }\n\n}\n\n\n\n/// For lots of set operations, it is probably better to work in IndexedSet(s) \n\n/// and then only to rank the final result.\n\nimpl<T> SetOps<T> for RankedSet<T> where T: Copy+PartialOrd {\n\n\n\n /// switches between ascending and descending ranks, \n\n /// which is what is logically expected here \n", "file_path": "src/traitimpls.rs", "rank": 26, "score": 19413.42870221359 }, { "content": " fn nonrepeat(&self) -> Self { \n\n let clean = &sansrepeat(&self.v);\n\n Self { ascending: self.ascending, v: clean.to_vec(), i:sortidx(clean) } \n\n }\n\n \n\n /// Finds minimum, minimum's first index, maximum, maximum's first index\n\n fn infsup(&self) -> MinMax<T> {\n\n let last = self.v.len()-1;\n\n let firstval = self.v[self.i[0]];\n\n let lastval = self.v[self.i[last]];\n\n if self.ascending { MinMax{min:firstval,minindex:self.i[0],max:lastval,maxindex:self.i[last]} }\n\n else { MinMax{min:lastval,minindex:self.i[last],max:firstval,maxindex:self.i[0]} }\n\n }\n\n \n\n /// True if m is a member of the set\n\n fn member(&self, m: T) -> bool where T: PartialOrd { \n\n let opt = if self.ascending { memsearch_indexed(&self.v,&self.i,m) }\n\n else { memsearchdesc_indexed(&self.v,&self.i,m) };\n\n opt.is_some() \n\n }\n", "file_path": "src/traitimpls.rs", "rank": 27, "score": 19413.40913000925 }, { "content": " fn search(&self, m: T) -> Option<usize> where T: PartialOrd {\n\n if self.ascending { memsearch(&self.v,m) }\n\n else { memsearchdesc(&self.v,m) } \n\n }\n\n\n\n /// Union of two ordered sets \n\n fn union(&self, s: &Self) -> OrderedSet<T> { \n\n let rself; let rs; \n\n OrderedSet { ascending:true, v:unite(\n\n if self.ascending {&self.v} else {rself = revs(&self.v); &rself},\n\n if s.ascending {&s.v} else {rs = revs(&s.v); &rs}) } \n\n } \n\n\n\n /// Intersection of two sets of the same type\n\n fn intersection(&self, s: &Self) -> OrderedSet<T> {\n\n let rself; let rs; \n\n OrderedSet { ascending:true, v:intersect(\n\n if self.ascending {&self.v} else {rself = revs(&self.v); &rself},\n\n if s.ascending {&s.v} else {rs = revs(&s.v); &rs}) } \n\n }\n", "file_path": "src/traitimpls.rs", "rank": 28, "score": 19413.39539615891 }, { "content": " /// but it is not the same as a literal reversal of the ranks!\n\n fn reverse(&self) -> Self {\n\n Self { ascending: !self.ascending, v: self.v.to_vec(), i: self.i.complindex() }\n\n }\n\n \n\n /// Deletes repetitions.\n\n fn nonrepeat(&self) -> Self { \n\n let clean = &sansrepeat(&self.v);\n\n Self { ascending: self.ascending, v: clean.to_vec(), i:rank(clean, self.ascending ) } \n\n }\n\n \n\n /// Finds minimum, minimum's first index, maximum, maximum's first index\n\n fn infsup(&self) -> MinMax<T> {\n\n let last = self.v.len()-1;\n\n let si = self.i.invindex(); // ranks -> sort index\n\n let firstval = self.v[si[0]];\n\n let lastval = self.v[si[last]];\n\n if self.ascending { MinMax{min:firstval,minindex:si[0],max:lastval,maxindex:si[last]} }\n\n else { MinMax{min:lastval,minindex:si[last],max:firstval,maxindex:si[0]} }\n\n }\n", "file_path": "src/traitimpls.rs", "rank": 29, "score": 19411.78824456233 }, { "content": "## Trait SetOps\n\n\n\nImplements the following methods for all four types of sets (structs):\n\n\n\n`reverse, nonrepeat, infsup, member, search, union, intersection, difference`.\n\n\n\n Some of these methods are more efficient for the ordered and indexed sets, rather than for the unordered sets. For example, `member` and `search` are then able to use binary search. Union is like the classical merge but only one copy of items that were present in both input sets is kept. To remove repetitions from a set at any other time, use `nonrepeat`.\n\n\n\n`Union`, `intersection` and `difference` when applied to IndexedSet(s) and RankedSet(s) return an OrderedSet as a result. When necessary, this result can be explicitly converted to other types of sets.\n\n\n\nAlternatively, `munion, minteresection and mdifference`, (where 'm' stands for 'mutable', see below), will overwrite `self` with the resulting set of the same type.\n\n\n\n## Trait MutSetOps\n\n\n\nImplements the following methods for all four types of sets:\n\n\n\n`mreverse, mnonrepeat, munion, mintersection, mdifference`.\n\n\n\nThey overwrite the mutable set to which they are applied with the result. Thus they are not *functional* but in this context of handling potentially large vectors, they are in some cases simpler and more efficient.\n\n\n", "file_path": "README.md", "rank": 30, "score": 11953.088519412828 }, { "content": "# Sets\n\n\n\n[<img alt=\"GitHub last commit\" src=\"https://img.shields.io/github/last-commit/liborty/sets/HEAD?logo=github\">](https://github.com/liborty/sets)\n\n[<img alt=\"crates.io\" src=\"https://img.shields.io/crates/v/sets?logo=rust\">](https://crates.io/crates/sets)\n\n[<img alt=\"crates.io\" src=\"https://img.shields.io/crates/d/sets?logo=rust\">](https://crates.io/crates/sets)\n\n[<img alt=\"docs.rs\" src=\"https://img.shields.io/docsrs/sets?logo=rust&logoColor=white\">](https://docs.rs/sets/)\n\n\n\n## Description\n\n\n\nCrate `sets` consists mostly of structs `Set, OrderedSet, IndexedSet, RankedSet`, which are type-safe wrappers for the more primitive imported functions and methods from crate `indxvec`.\n\n\n\nThe main capabilities of `sets` include: efficient sorting, ranking, merging, searching and indices manipulations. The structs contain generic vectors `Vec<T>`. Thus they will work with vectors or slices of primitive end types but also with any arbitrarily complex end type `T`, as long as the required traits `PartialOrd` and `Copy`, are implemented for `T`.\n\n\n\n## Usage\n\n\n\nInsert into your Cargo.toml file [dependencies] section: `sets = \"^1\"` \n\nImport into your source file(s) the four structs for the four different types of sets and the two traits `SetOps` and `MutSetOps`. The following 'use' declaration imports everything:\n\n\n\n```use sets::{Set,OrderedSet,IndexedSet,RankedSet,SetOps,MutSetOps};```\n\n\n\nThe initialisers and convertors are associated with their structs, hence the `::` syntax, e.g.: \n\n```let s = Set::from_slice(&v);```\n\n\n\nThe rest are methods of the traits `SetOps`, and `MutSetOps` e.g.:\n\n\n\n```rust\n\n// new mutable set with unique elements \n\nlet mut su = s.nonrepeat();\n\n// transformed into the opposite order \n\nsu.mreverse; \n\n```\n\n\n\nIt is highly recommended to read and run `tests/tests.rs` for many more examples of usage. Use a single thread to run them. It may be a bit slower but it will write the results in the right order:\n\n\n\n`cargo test --release -- --test-threads=1 --nocapture --color always`\n\n\n", "file_path": "README.md", "rank": 31, "score": 11951.119233563457 }, { "content": "## Release Notes (Latest First)\n\n\n\n**Version 1.0.1** - some tidying up of code, no changes of functionality.\n\n\n\n**Version 1.0.0** - stable version with some minor improvements to README.md (this document). Updated to `indxvec = \"^1\"` and Rust edition 2021.\n\n\n\n**Version 0.1.8** - 'infsup' now returns struct MinMax (defined in crate 'sets').\n\n\n\n**Version 0.1.7** - just some cosmetic cleaning up. No change of functionality from the previous version.\n\n\n\n**Version 0.1.6** - implemented `MutSetOps` for all set types and added some tests.\n\n\n\n**Version 0.1.5** - implemented `SetOps` for `RankedSet`, making the implementations now complete. Future work: adding mutable sets.\n\n\n\n**Version 0.1.4** - updated readme, implemented `SetOps` for `IndexedSet`.\n\n\n\n**Version 0.1.3** - fixed readme typos, improved tests, implemented `SetOps` for `OrderedSet`.\n\n\n\n**Version 0.1.2** - implemented `SetOps` trait for struct `Set`. The other three structs will follow in the next versions.\n\n\n\n**Version 0.1.1** - competed the associated functions for all initiations and conversions of the four set structs.\n\n\n\n**Version 0.1.0** - first version, includes creation and conversions of the structs representing the four types of sets.\n", "file_path": "README.md", "rank": 32, "score": 11949.693252770334 }, { "content": "#![allow(unused_imports)]\n\n#![allow(dead_code)]\n\n#[cfg(test)]\n\n\n\n// use anyhow::{Result};\n\nuse sets::{Set,OrderedSet,IndexedSet,RankedSet,SetOps,MutSetOps};\n\nuse indxvec::{wi,wv,Indices,merge::*};\n\n\n\n#[test]\n", "file_path": "tests/tests.rs", "rank": 43, "score": 6.224015745603571 } ]
Rust
vrp-cli/src/extensions/generate/plan.rs
valerivp/vrp
27ee30e5f4c44e051e5cec1248e606305b52fc00
#[cfg(test)] #[path = "../../../tests/unit/extensions/generate/plan_test.rs"] mod plan_test; use super::get_random_item; use vrp_core::utils::{DefaultRandom, Random}; use vrp_pragmatic::format::problem::{Job, JobPlace, JobTask, Plan, Problem}; use vrp_pragmatic::format::Location; pub(crate) fn generate_plan( problem_proto: &Problem, locations: Option<Vec<Location>>, jobs_size: usize, area_size: Option<f64>, ) -> Result<Plan, String> { let rnd = DefaultRandom::default(); let get_location_fn = get_location_fn(problem_proto, locations, area_size)?; let time_windows = get_plan_time_windows(&problem_proto.plan); let demands = get_plan_demands(&problem_proto.plan); let durations = get_plan_durations(&problem_proto.plan); let generate_tasks = |tasks: &Option<Vec<JobTask>>, keep_original_demand: bool| { tasks.as_ref().map(|tasks| { tasks .iter() .map(|task| JobTask { places: task .places .iter() .map(|_| JobPlace { location: get_location_fn(&rnd), duration: get_random_item(durations.as_slice(), &rnd).cloned().unwrap(), times: get_random_item(time_windows.as_slice(), &rnd).cloned(), }) .collect(), demand: if keep_original_demand { task.demand.clone() } else { get_random_item(demands.as_slice(), &rnd).cloned() }, tag: None, }) .collect::<Vec<_>>() }) }; let jobs = (1..=jobs_size) .map(|job_idx| { let job_proto = get_random_item(problem_proto.plan.jobs.as_slice(), &rnd).unwrap(); let keep_original_demand = job_proto.pickups.as_ref().map_or(false, |t| !t.is_empty()) && job_proto.deliveries.as_ref().map_or(false, |t| !t.is_empty()); Job { id: format!("job{}", job_idx), pickups: generate_tasks(&job_proto.pickups, keep_original_demand), deliveries: generate_tasks(&job_proto.deliveries, keep_original_demand), replacements: generate_tasks(&job_proto.replacements, false), services: generate_tasks(&job_proto.services, true), priority: job_proto.priority, skills: job_proto.skills.clone(), value: job_proto.value, } }) .collect(); Ok(Plan { jobs, relations: None }) } fn get_location_fn( problem_proto: &Problem, locations: Option<Vec<Location>>, area_size: Option<f64>, ) -> Result<Box<dyn Fn(&DefaultRandom) -> Location>, String> { if let Some(locations) = locations { Ok(Box::new(move |rnd| get_random_item(locations.as_slice(), &rnd).cloned().expect("cannot get any location"))) } else { let bounding_box = if let Some(area_size) = area_size { if area_size > 0. { get_bounding_box_from_size(&problem_proto.plan, area_size) } else { return Err("area size must be positive".to_string()); } } else { get_bounding_box_from_plan(&problem_proto.plan) }; Ok(Box::new(move |rnd| { let lat = rnd.uniform_real((bounding_box.0).0, (bounding_box.1).0); let lng = rnd.uniform_real((bounding_box.0).1, (bounding_box.1).1); Location::Coordinate { lat, lng } })) } } fn get_bounding_box_from_plan(plan: &Plan) -> ((f64, f64), (f64, f64)) { let mut lat_min = f64::MAX; let mut lat_max = f64::MIN; let mut lng_min = f64::MAX; let mut lng_max = f64::MIN; get_plan_places(&plan).map(|job_place| job_place.location.to_lat_lng()).for_each(|(lat, lng)| { lat_min = lat_min.min(lat); lat_max = lat_max.max(lat); lng_min = lng_min.min(lng); lng_max = lng_max.max(lng); }); ((lat_min, lng_min), (lat_max, lng_max)) } fn get_bounding_box_from_size(plan: &Plan, area_size: f64) -> ((f64, f64), (f64, f64)) { const WGS84_A: f64 = 6_378_137.0; const WGS84_B: f64 = 6_356_752.3; let deg_to_rad = |deg| std::f64::consts::PI * deg / 180.; let rad_to_deg = |rad| 180. * rad / std::f64::consts::PI; let ((min_lat, min_lng), (max_lat, max_lng)) = get_bounding_box_from_plan(plan); let center_lat = min_lat + (max_lat - min_lat) / 2.; let center_lng = min_lng + (max_lng - min_lng) / 2.; let lat = deg_to_rad(center_lat); let lng = deg_to_rad(center_lng); let an = WGS84_A * WGS84_A * lat.cos(); let bn = WGS84_B * WGS84_B * lat.sin(); let ad = WGS84_A * lat.cos(); let bd = WGS84_B * lat.sin(); let half_size = area_size; let radius = ((an * an + bn * bn) / (ad * ad + bd * bd)).sqrt(); let pradius = radius * lat.cos(); let lat_min = rad_to_deg(lat - half_size / radius); let lat_max = rad_to_deg(lat + half_size / radius); let lon_min = rad_to_deg(lng - half_size / pradius); let lon_max = rad_to_deg(lng + half_size / pradius); ((lat_min, lon_min), (lat_max, lon_max)) } fn get_plan_time_windows(plan: &Plan) -> Vec<Vec<Vec<String>>> { get_plan_places(&plan).flat_map(|job_place| job_place.times.iter()).cloned().collect() } fn get_plan_demands(plan: &Plan) -> Vec<Vec<i32>> { plan.jobs .iter() .flat_map(|job| get_job_tasks(job)) .filter_map(|job_task| job_task.demand.as_ref()) .cloned() .collect() } fn get_plan_durations(plan: &Plan) -> Vec<f64> { get_plan_places(&plan).map(|job_place| job_place.duration).collect() } fn get_plan_places(plan: &Plan) -> impl Iterator<Item = &JobPlace> { plan.jobs.iter().flat_map(|job| get_job_tasks(job)).flat_map(|job_task| job_task.places.iter()) } fn get_job_tasks(job: &Job) -> impl Iterator<Item = &JobTask> { job.pickups .iter() .flat_map(|tasks| tasks.iter()) .chain(job.deliveries.iter().flat_map(|tasks| tasks.iter())) .chain(job.replacements.iter().flat_map(|tasks| tasks.iter())) .chain(job.services.iter().flat_map(|tasks| tasks.iter())) }
#[cfg(test)] #[path = "../../../tests/unit/extensions/generate/plan_test.rs"] mod plan_test; use super::get_random_item; use vrp_core::utils::{DefaultRandom, Random}; use vrp_pragmatic::format::problem::{Job, JobPlace, JobTask, Plan, Problem}; use vrp_pragmatic::format::Location; pub(crate) fn generate_plan( problem_proto: &Problem, locations: Option<Vec<Location>>, jobs_size: usize, area_size: Option<f64>, ) -> Result<Plan, String> { let rnd = DefaultRandom::default(); let get_location_fn = get_location_fn(problem_proto, locations, area_size)?; let time_windows = get_plan_time_windows(&problem_proto.plan); let demands = get_plan_demands(&problem_proto.plan); let durations = get_plan_durations(&problem_proto.plan); let generate_tasks = |tasks: &Option<Vec<JobTask>>, keep_original_demand: bool| { tasks.as_ref().map(|tasks| { tasks .iter() .map(|task| JobTask { places: task .places .iter() .map(|_| JobPlace { location: get_location_fn(&rnd), duration: get_random_item(durations.as_slice(), &rnd).cloned().unwrap(), times: get_random_item(time_windows.as_slice(), &rnd).cloned(), }) .collect(), demand: if keep_original_demand { task.demand.clone() } else { get_random_item(demands.as_slice(), &rnd).cloned() }, tag: None, }) .collect::<Vec<_>>() }) }; let jobs = (1..=jobs_size) .map(|job_idx| { let job_proto = get_random_item(problem_proto.plan.jobs.as_slice(), &rnd).unwrap(); let keep_original_demand = job_proto.pickups.as_ref().map_or(false, |t| !t.is_empty()) && job_proto.deliveries.as_ref().map_or(false, |t| !t.is_empty()); Job { id: format!("job{}", job_idx), pickups: generate_tasks(&job_proto.pickups, keep_original_demand), deliveries: generate_tasks(&job_proto.deliveries, keep_original_demand), replacements: generate_tasks(&job_proto.replacements, false), services: generate_tasks(&job_proto.services, true), priority: job_proto.priority, skills: job_proto.skills.clone(), value: job_proto.value, } }) .collect(); Ok(Plan { jobs, relations: None }) } fn get_location_fn( problem_proto: &Problem, locations: Option<Vec<Location>>, area_size: Option<f64>, ) -> Result<Box<dyn Fn(&DefaultRandom) -> Location>, String> { if let Some(locations) = locations { Ok(Box::new(move |rnd| get_random_item(locations.as_slice(), &rnd).cloned().expect("cannot get any location"))) } else { let bounding_box = if let Some(area_size) = area_size { if area_size > 0. { get_bounding_box_from_size(&problem_proto.plan, area_size) } else { return Err("area size must be positive".to_string()); } } else { get_bounding_box_from_plan(&problem_proto.plan) }; Ok(Box::new(move |rnd| { let lat = rnd.uniform_real((bounding_box.0).0, (bounding_box.1).0); let lng = rnd.uniform_real((bounding_box.0).1, (bounding_box.1).1); Location::Coordinate { lat, lng } })) } } fn get_bounding_box_from_plan(plan: &Plan) -> ((f64, f64), (f64, f64)) { let mut lat_min = f64::MAX; let mut lat_max = f64::MIN; let mut lng_min = f64::MAX; let mut lng_max = f64::MIN; get_plan_places(&plan).map(|job_place| job_place.location.to_lat_lng()).for_each(|(lat, lng)| { lat_min = lat_min.min(lat); lat_max = lat_max.max(lat); lng_min = lng_min.min(lng); lng_max = lng_max.max(lng); }); ((lat_min, lng_min), (lat_max, lng_max)) } fn get_bounding_box_from_size(plan: &Plan, area_size: f64) -> ((f64, f64), (f64, f64)) { const WGS84_A: f64 = 6_378_137.0; const WGS84_B: f64 = 6_356_752.3; let deg_to_rad = |deg| std::f64::consts::PI * deg / 180.; let rad_to_deg = |rad| 180. * rad / std::f64::consts::PI; let ((min_lat, min_lng), (max_lat, max_lng)) = get_bounding_box_from_plan(plan); let center_lat = min_lat + (max_lat - min_lat) / 2.; let center_lng = min_lng + (max_lng - min_lng) / 2.; let lat = deg_to_rad(center_lat); let lng = deg_to_rad(center_lng);
fn get_plan_time_windows(plan: &Plan) -> Vec<Vec<Vec<String>>> { get_plan_places(&plan).flat_map(|job_place| job_place.times.iter()).cloned().collect() } fn get_plan_demands(plan: &Plan) -> Vec<Vec<i32>> { plan.jobs .iter() .flat_map(|job| get_job_tasks(job)) .filter_map(|job_task| job_task.demand.as_ref()) .cloned() .collect() } fn get_plan_durations(plan: &Plan) -> Vec<f64> { get_plan_places(&plan).map(|job_place| job_place.duration).collect() } fn get_plan_places(plan: &Plan) -> impl Iterator<Item = &JobPlace> { plan.jobs.iter().flat_map(|job| get_job_tasks(job)).flat_map(|job_task| job_task.places.iter()) } fn get_job_tasks(job: &Job) -> impl Iterator<Item = &JobTask> { job.pickups .iter() .flat_map(|tasks| tasks.iter()) .chain(job.deliveries.iter().flat_map(|tasks| tasks.iter())) .chain(job.replacements.iter().flat_map(|tasks| tasks.iter())) .chain(job.services.iter().flat_map(|tasks| tasks.iter())) }
let an = WGS84_A * WGS84_A * lat.cos(); let bn = WGS84_B * WGS84_B * lat.sin(); let ad = WGS84_A * lat.cos(); let bd = WGS84_B * lat.sin(); let half_size = area_size; let radius = ((an * an + bn * bn) / (ad * ad + bd * bd)).sqrt(); let pradius = radius * lat.cos(); let lat_min = rad_to_deg(lat - half_size / radius); let lat_max = rad_to_deg(lat + half_size / radius); let lon_min = rad_to_deg(lng - half_size / pradius); let lon_max = rad_to_deg(lng + half_size / pradius); ((lat_min, lon_min), (lat_max, lon_max)) }
function_block-function_prefix_line
[ { "content": "pub fn create_pickup_delivery_job(id: &str, pickup_location: Vec<f64>, delivery_location: Vec<f64>) -> Job {\n\n Job {\n\n pickups: Some(vec![JobTask { tag: Some(\"p1\".to_string()), ..create_task(pickup_location.clone()) }]),\n\n deliveries: Some(vec![JobTask { tag: Some(\"d1\".to_string()), ..create_task(delivery_location.clone()) }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 0, "score": 506190.012170336 }, { "content": "pub fn create_delivery_job_with_times(id: &str, location: Vec<f64>, times: Vec<(i32, i32)>, duration: f64) -> Job {\n\n Job {\n\n deliveries: Some(vec![JobTask {\n\n places: vec![JobPlace { duration, times: convert_times(&times), ..create_job_place(location) }],\n\n demand: Some(vec![1]),\n\n tag: None,\n\n }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 1, "score": 503519.8122355346 }, { "content": "pub fn create_delivery_job_with_duration(id: &str, location: Vec<f64>, duration: f64) -> Job {\n\n Job {\n\n deliveries: Some(vec![JobTask {\n\n places: vec![JobPlace { duration, ..create_job_place(location) }],\n\n demand: Some(vec![1]),\n\n tag: None,\n\n }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 2, "score": 498243.869895339 }, { "content": "pub fn create_delivery_job_with_value(id: &str, location: Vec<f64>, value: f64) -> Job {\n\n Job { deliveries: Some(vec![create_task(location.clone())]), value: Some(value), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 3, "score": 498126.5524082761 }, { "content": "pub fn create_pickup_job_with_demand(id: &str, location: Vec<f64>, demand: Vec<i32>) -> Job {\n\n Job { pickups: Some(vec![JobTask { demand: Some(demand), ..create_task(location) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 4, "score": 494868.3015773551 }, { "content": "pub fn create_delivery_job_with_demand(id: &str, location: Vec<f64>, demand: Vec<i32>) -> Job {\n\n Job { deliveries: Some(vec![JobTask { demand: Some(demand), ..create_task(location) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 5, "score": 494854.951713149 }, { "content": "pub fn create_delivery_job_with_skills(id: &str, location: Vec<f64>, skills: JobSkills) -> Job {\n\n Job { skills: Some(skills), ..create_delivery_job(id, location) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 6, "score": 481285.39048498863 }, { "content": "pub fn create_delivery_job_with_priority(id: &str, location: Vec<f64>, priority: i32) -> Job {\n\n Job { priority: Some(priority), ..create_delivery_job(id, location) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 7, "score": 473606.4149102499 }, { "content": "pub fn create_replacement_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { replacements: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 8, "score": 442373.79657003377 }, { "content": "pub fn create_service_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { services: Some(vec![JobTask { demand: None, ..create_task(location.clone()) }]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 9, "score": 442373.79657003377 }, { "content": "pub fn create_pickup_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { pickups: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 10, "score": 442355.50734679354 }, { "content": "pub fn create_delivery_job(id: &str, location: Vec<f64>) -> Job {\n\n Job { deliveries: Some(vec![create_task(location.clone())]), ..create_job(id) }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 11, "score": 442341.2796940869 }, { "content": "pub fn create_test_job(lat: f64, lng: f64) -> Job {\n\n Job {\n\n pickups: Some(vec![JobTask {\n\n places: vec![JobPlace {\n\n location: Location::Coordinate { lat, lng },\n\n times: Some(vec![create_test_time_window()]),\n\n ..create_empty_job_place()\n\n }],\n\n demand: Some(vec![1]),\n\n ..create_empty_job_task()\n\n }]),\n\n ..create_empty_job()\n\n }\n\n}\n", "file_path": "vrp-cli/tests/helpers/generate.rs", "rank": 12, "score": 424058.328939724 }, { "content": "fn add_tag(dimens: &mut Dimensions, tag: &Option<String>) {\n\n if let Some(tag) = tag {\n\n dimens.set_value(\"tag\", tag.clone());\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 13, "score": 404340.40439879516 }, { "content": "pub fn get_job_time_windows(problem: &Problem) -> Vec<(f64, f64)> {\n\n problem\n\n .jobs\n\n .all()\n\n .map(|j| match j {\n\n Job::Single(j) => j\n\n .places\n\n .first()\n\n .unwrap()\n\n .times\n\n .first()\n\n .map(|span| span.as_time_window().unwrap())\n\n .map(|tw| (tw.start, tw.end))\n\n .unwrap(),\n\n _ => panic!(),\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 14, "score": 403336.79138078593 }, { "content": "pub fn get_job_id(job: &Job) -> &String {\n\n job.dimens().get_id().unwrap()\n\n}\n\n\n\npub struct SingleBuilder {\n\n single: Single,\n\n}\n\n\n\nimpl Default for SingleBuilder {\n\n fn default() -> Self {\n\n Self { single: test_single() }\n\n }\n\n}\n\n\n\nimpl SingleBuilder {\n\n pub fn id(&mut self, id: &str) -> &mut Self {\n\n self.single.dimens.set_value(\"id\", id.to_string());\n\n self\n\n }\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 15, "score": 401195.0608287785 }, { "content": "pub fn get_job_durations(problem: &Problem) -> Vec<f64> {\n\n problem\n\n .jobs\n\n .all()\n\n .map(|j| match j {\n\n Job::Single(j) => j.places.first().unwrap().duration,\n\n _ => panic!(),\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 17, "score": 392151.7861151499 }, { "content": "pub fn get_job_ids(problem: &Problem) -> Vec<String> {\n\n problem.jobs.all().map(|j| get_job_id(&j).to_owned()).collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 18, "score": 391916.3495075042 }, { "content": "fn add_conditional_job(job_index: &mut JobIndex, jobs: &mut Vec<Job>, job_id: String, single: Single) {\n\n let job = Job::Single(Arc::new(single));\n\n job_index.insert(job_id, job.clone());\n\n jobs.push(job);\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 19, "score": 390159.69022722135 }, { "content": "fn get_job_ids(jobs: &Vec<Job>) -> Vec<String> {\n\n jobs.iter().map(|job| job.id.clone()).collect()\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/relations.rs", "rank": 20, "score": 386940.16529095557 }, { "content": "fn coord(lat: f64, lng: f64) -> Location {\n\n Location::Coordinate { lat, lng }\n\n}\n\n\n\nparameterized_test! {can_detect_invalid_area, (allowed_areas, expected), {\n\n can_detect_invalid_area_impl(allowed_areas, expected);\n\n}}\n\n\n\ncan_detect_invalid_area! {\n\n case01: (None, None),\n\n case02: (Some(vec![vec![coord(0., 0.), coord(0., 1.), coord(1., 1.)]]), None),\n\n case03: (Some(vec![vec![coord(0., 0.), coord(0., 1.), coord(1., 1.), coord(1., 0.)]]), None),\n\n\n\n case04: (Some(vec![]), Some(())),\n\n case05: (Some(vec![vec![]]), Some(())),\n\n case06: (Some(vec![vec![coord(0., 0.)]]), Some(())),\n\n case07: (Some(vec![vec![coord(0., 0.), coord(0., 1.)]]), Some(())),\n\n case08: (Some(vec![vec![coord(0., 0.), coord(0., 1.), coord(1., 1.)], vec![coord(0., 1.)]]), Some(())),\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/validation/vehicles_test.rs", "rank": 22, "score": 386250.6196436016 }, { "content": "pub fn create_task(location: Vec<f64>) -> JobTask {\n\n JobTask { places: vec![create_job_place(location)], demand: Some(vec![1]), tag: None }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 23, "score": 381699.1174612333 }, { "content": "fn get_vehicle_id_from_job(job: &Arc<Single>) -> Option<&String> {\n\n job.dimens.get_value::<String>(\"vehicle_id\")\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/mod.rs", "rank": 24, "score": 376791.781351464 }, { "content": "fn check_none_of(job_skills: &JobSkills, vehicle_skills: &Option<&HashSet<String>>) -> bool {\n\n match (job_skills.none_of.as_ref(), vehicle_skills) {\n\n (Some(job_skills), Some(vehicle_skills)) => job_skills.is_disjoint(vehicle_skills),\n\n _ => true,\n\n }\n\n}\n", "file_path": "vrp-pragmatic/src/constraints/skills.rs", "rank": 25, "score": 376257.55675608234 }, { "content": "fn create_condition(vehicle_id: String, shift_index: usize) -> Arc<dyn Fn(&Actor) -> bool + Sync + Send> {\n\n Arc::new(move |actor: &Actor| {\n\n *actor.vehicle.dimens.get_id().unwrap() == vehicle_id\n\n && *actor.vehicle.dimens.get_value::<usize>(\"shift_index\").unwrap() == shift_index\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 26, "score": 372949.43674380844 }, { "content": "pub fn create_delivery_job_with_index(id: &str, index: usize) -> Job {\n\n Job {\n\n deliveries: Some(vec![JobTask {\n\n places: vec![JobPlace { times: None, location: Location::Reference { index }, duration: 1. }],\n\n demand: Some(vec![1]),\n\n tag: None,\n\n }]),\n\n ..create_job(id)\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 27, "score": 368832.49030350044 }, { "content": "fn add_value(dimens: &mut Dimensions, value: Option<f64>) {\n\n if let Some(value) = value {\n\n dimens.set_value(\"value\", value);\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 28, "score": 368710.3580384082 }, { "content": "/// Gets locations serialized in json.\n\npub fn get_locations_serialized(problem: &Problem) -> Result<String, String> {\n\n // TODO validate the problem?\n\n\n\n let locations = get_unique_locations(&problem);\n\n let mut buffer = String::new();\n\n let writer = unsafe { BufWriter::new(buffer.as_mut_vec()) };\n\n serde_json::to_writer_pretty(writer, &locations).map_err(|err| err.to_string())?;\n\n\n\n Ok(buffer)\n\n}\n\n\n", "file_path": "vrp-cli/src/lib.rs", "rank": 29, "score": 366853.9432264421 }, { "content": "pub fn get_job_id(job: &Job) -> &String {\n\n job.dimens().get_id().unwrap()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 32, "score": 361107.2867228713 }, { "content": "fn job_task_size(tasks: &Option<Vec<JobTask>>) -> usize {\n\n tasks.as_ref().map_or(0, |p| p.len())\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/mod.rs", "rank": 33, "score": 359269.9672061174 }, { "content": "fn get_vehicle_skills(problem_proto: &Problem) -> Vec<Option<Vec<String>>> {\n\n get_from_vehicle(problem_proto, |vehicle| vehicle.skills.clone())\n\n}\n\n\n", "file_path": "vrp-cli/src/extensions/generate/fleet.rs", "rank": 34, "score": 356946.43748498854 }, { "content": "pub fn get_customer_id(job: &Job) -> String {\n\n get_job_id(job).to_owned()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 35, "score": 355584.58941749984 }, { "content": "fn format_time(time: f64) -> String {\n\n Utc.timestamp(time as i64, 0).to_rfc3339_opts(SecondsFormat::Secs, true)\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/lib.rs", "rank": 36, "score": 354452.02417873836 }, { "content": "fn get_lng_lat(location: &Location) -> Result<(f64, f64), Error> {\n\n match location {\n\n Location::Coordinate { lat, lng } => Ok((*lng, *lat)),\n\n Location::Reference { index: _ } => {\n\n Err(Error::new(ErrorKind::InvalidData, \"geojson cannot be used with location indices\"))\n\n }\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/solution/geo_serializer.rs", "rank": 37, "score": 354343.0754085259 }, { "content": "pub fn create_job_place(location: Vec<f64>) -> JobPlace {\n\n JobPlace { times: None, location: location.to_loc(), duration: 1. }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 38, "score": 352391.27670183696 }, { "content": "pub fn get_customer_id(job: &Job) -> String {\n\n job.dimens().get_id().unwrap().clone()\n\n}\n", "file_path": "vrp-core/tests/helpers/models/domain.rs", "rank": 39, "score": 351879.8661279386 }, { "content": "/// Returns job locations.\n\nfn get_job_locations<'a>(job: &'a Job) -> Box<dyn Iterator<Item = Option<Location>> + 'a> {\n\n match job {\n\n Job::Single(single) => Box::new(single.places.iter().map(|p| p.location)),\n\n Job::Multi(multi) => Box::new(multi.jobs.iter().flat_map(|j| j.places.iter().map(|p| p.location))),\n\n }\n\n}\n\n\n", "file_path": "vrp-core/src/models/problem/jobs.rs", "rank": 40, "score": 348639.51317764795 }, { "content": "fn get_vehicles_sizes(problem_proto: &Problem) -> Vec<usize> {\n\n get_from_vehicle(problem_proto, |vehicle| vehicle.vehicle_ids.len())\n\n}\n", "file_path": "vrp-cli/src/extensions/generate/fleet.rs", "rank": 43, "score": 337769.4879279727 }, { "content": "fn check_all_of(job_skills: &JobSkills, vehicle_skills: &Option<&HashSet<String>>) -> bool {\n\n match (job_skills.all_of.as_ref(), vehicle_skills) {\n\n (Some(job_skills), Some(vehicle_skills)) => job_skills.is_subset(vehicle_skills),\n\n (Some(skills), None) if skills.is_empty() => true,\n\n (Some(_), None) => false,\n\n _ => true,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/skills.rs", "rank": 44, "score": 337339.4506418572 }, { "content": "fn check_one_of(job_skills: &JobSkills, vehicle_skills: &Option<&HashSet<String>>) -> bool {\n\n match (job_skills.one_of.as_ref(), vehicle_skills) {\n\n (Some(job_skills), Some(vehicle_skills)) => job_skills.iter().any(|skill| vehicle_skills.contains(skill)),\n\n (Some(skills), None) if skills.is_empty() => true,\n\n (Some(_), None) => false,\n\n _ => true,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/skills.rs", "rank": 45, "score": 334429.285870354 }, { "content": "fn get_single(places: Vec<(Option<Location>, Duration, Vec<TimeSpan>)>, coord_index: &CoordIndex) -> Single {\n\n Single {\n\n places: places\n\n .into_iter()\n\n .map(|(location, duration, times)| Place {\n\n location: location.as_ref().and_then(|l| coord_index.get_by_loc(l)),\n\n duration,\n\n times,\n\n })\n\n .collect(),\n\n dimens: Default::default(),\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 46, "score": 333245.77425681415 }, { "content": "pub fn get_sorted_customer_ids_from_jobs(jobs: &[Job]) -> Vec<String> {\n\n let mut ids = jobs.iter().map(|job| get_customer_id(&job)).collect::<Vec<String>>();\n\n ids.sort();\n\n ids\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/domain.rs", "rank": 47, "score": 331740.19377237034 }, { "content": "fn get_job(index: usize, jobs: &Jobs) -> vrp_core::models::problem::Job {\n\n jobs.all().collect::<Vec<_>>().get(index).unwrap().clone()\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/format/problem/reader_test.rs", "rank": 48, "score": 326819.83166326524 }, { "content": "/// Gets average costs across all profiles.\n\nfn get_average_costs(problem: &Problem, min_points: usize) -> Vec<f64> {\n\n let mut costs = problem.fleet.profiles.iter().fold(vec![0.; problem.jobs.size()], |mut acc, profile| {\n\n problem.jobs.all().enumerate().for_each(|(idx, job)| {\n\n acc[idx] += problem\n\n .jobs\n\n .neighbors(profile, &job, Timestamp::default())\n\n .filter(|(_, cost)| *cost > 0.)\n\n .nth(min_points - 1)\n\n // TODO consider time window difference as extra cost?\n\n .map(|(_, cost)| *cost)\n\n .unwrap_or(0.);\n\n });\n\n acc\n\n });\n\n\n\n costs.iter_mut().for_each(|cost| *cost /= problem.fleet.profiles.len() as f64);\n\n\n\n costs\n\n}\n\n\n", "file_path": "vrp-core/src/solver/mutation/ruin/cluster_removal.rs", "rank": 49, "score": 326440.37923976453 }, { "content": "fn returns_proper_job_neighbours_impl(index: usize, expected: Vec<String>) {\n\n let p1 = Profile::new(1, None);\n\n let fleet = FleetBuilder::default()\n\n .add_driver(test_driver())\n\n .add_vehicles(vec![\n\n VehicleBuilder::default().id(\"v1\").profile(p1.clone()).details(vec![test_vehicle_detail()]).build(),\n\n VehicleBuilder::default().id(\"v2\").profile(p1.clone()).details(vec![test_vehicle_detail()]).build(),\n\n ])\n\n .build();\n\n let species = vec![\n\n SingleBuilder::default().id(\"s0\").location(Some(0)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s1\").location(Some(1)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s2\").location(Some(2)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s3\").location(Some(3)).build_as_job_ref(),\n\n SingleBuilder::default().id(\"s4\").location(Some(4)).build_as_job_ref(),\n\n ];\n\n let jobs = Jobs::new(&fleet, species.clone(), &create_profile_aware_transport_cost());\n\n\n\n let result: Vec<String> =\n\n jobs.neighbors(&p1, species.get(index).unwrap(), 0.0).map(|(j, _)| get_job_id(j).clone()).collect();\n", "file_path": "vrp-core/tests/unit/models/problem/jobs_test.rs", "rank": 50, "score": 323783.51230797725 }, { "content": "fn is_reserved_job_id(job_id: &str) -> bool {\n\n job_id == \"departure\" || job_id == \"arrival\" || job_id == \"break\" || job_id == \"reload\" || job_id == \"dispatch\"\n\n}\n", "file_path": "vrp-pragmatic/src/validation/mod.rs", "rank": 51, "score": 321839.1426759174 }, { "content": "/// Checks whether given location is inside area using ray casting algorithm.\n\n/// Location is interpreted as 2D point, area - as 2D polygon.\n\nfn is_location_in_area(location: &(f64, f64), outer_shape: &[(f64, f64)]) -> bool {\n\n let &(x, y) = location;\n\n\n\n let mut is_inside = false;\n\n let mut i = 0;\n\n let mut j = outer_shape.len() - 1;\n\n\n\n while i < outer_shape.len() {\n\n let &(ix, iy) = outer_shape.get(i).unwrap();\n\n let &(jx, jy) = outer_shape.get(j).unwrap();\n\n\n\n if ((ix > x) != (jx > x)) && (y < (jy - iy) * (x - ix) / (jx - ix) + iy) {\n\n is_inside = !is_inside;\n\n }\n\n\n\n j = i;\n\n i += 1;\n\n }\n\n\n\n is_inside\n\n}\n", "file_path": "vrp-core/src/construction/constraints/area.rs", "rank": 52, "score": 318986.47986124334 }, { "content": "/// Generates job plan.\n\npub fn generate_plan(jobs_proto: impl Strategy<Value = Vec<Job>>) -> impl Strategy<Value = Plan> {\n\n jobs_proto.prop_map(|jobs| Plan { jobs, relations: None })\n\n}\n\n\n\nprop_compose! {\n\n fn job_prototype(\n\n pickups_proto: impl Strategy<Value = Option<Vec<JobTask>>>,\n\n deliveries_proto: impl Strategy<Value = Option<Vec<JobTask>>>,\n\n replacements_proto: impl Strategy<Value = Option<Vec<JobTask>>>,\n\n services_proto: impl Strategy<Value = Option<Vec<JobTask>>>,\n\n priority_proto: impl Strategy<Value = Option<i32>>,\n\n skills_proto: impl Strategy<Value = Option<JobSkills>>,\n\n value_proto: impl Strategy<Value = Option<f64>>,\n\n )\n\n (\n\n pickups in pickups_proto,\n\n deliveries in deliveries_proto,\n\n replacements in replacements_proto,\n\n services in services_proto,\n\n priority in priority_proto,\n", "file_path": "vrp-pragmatic/tests/generator/jobs.rs", "rank": 53, "score": 316554.0737698064 }, { "content": "fn add_vehicle_skills(dimens: &mut Dimensions, skills: &Option<Vec<String>>) {\n\n if let Some(skills) = skills {\n\n dimens.set_value(\"skills\", skills.iter().cloned().collect::<HashSet<_>>());\n\n }\n\n}\n", "file_path": "vrp-pragmatic/src/format/problem/fleet_reader.rs", "rank": 54, "score": 314908.53658840765 }, { "content": "pub fn get_job_simple_demand(job: &Job) -> &Demand<SingleDimLoad> {\n\n match job {\n\n Job::Single(single) => &single.dimens,\n\n Job::Multi(multi) => &multi.dimens,\n\n }\n\n .get_demand()\n\n .unwrap()\n\n}\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 55, "score": 313373.8679126041 }, { "content": "fn matrix(profile: Option<&str>, timestamp: Option<f64>, fill_value: i64, size: usize) -> Matrix {\n\n Matrix {\n\n profile: profile.map(|p| p.to_string()),\n\n timestamp: timestamp.map(|t| format_time(t)),\n\n travel_times: vec![fill_value; size],\n\n distances: vec![fill_value; size],\n\n error_codes: None,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/format/problem/fleet_reader_test.rs", "rank": 56, "score": 313101.0070615818 }, { "content": "pub fn test_place_with_location(location: Option<Location>) -> Place {\n\n Place { location, duration: DEFAULT_JOB_DURATION, times: vec![DEFAULT_JOB_TIME_SPAN] }\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 57, "score": 311170.242284109 }, { "content": "pub fn get_job_demands(problem: &Problem) -> Vec<i32> {\n\n problem.jobs.all().map(|j| get_job_simple_demand(&j).delivery.0).map(|d| d.value).collect()\n\n}\n\n\n", "file_path": "vrp-scientific/tests/helpers/analysis.rs", "rank": 58, "score": 310233.5570859828 }, { "content": "fn insert_new_activity(route: &mut Route, single: Arc<Single>, place: Place, time: TimeWindow) {\n\n let activity =\n\n Activity { place, schedule: Schedule { arrival: time.start, departure: time.end }, job: Some(single) };\n\n route.tour.insert_last(activity);\n\n}\n", "file_path": "vrp-pragmatic/src/format/solution/initial_reader.rs", "rank": 59, "score": 309425.20174151077 }, { "content": "pub fn all_of_skills(skills: Vec<String>) -> JobSkills {\n\n JobSkills { all_of: Some(skills), one_of: None, none_of: None }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 60, "score": 308403.9222348 }, { "content": "fn add_job_skills(dimens: &mut Dimensions, skills: &Option<FormatJobSkills>) {\n\n if let Some(skills) = skills {\n\n dimens.set_value(\n\n \"skills\",\n\n ConstraintJobSkills {\n\n all_of: skills.all_of.as_ref().map(|all_of| all_of.iter().cloned().collect()),\n\n one_of: skills.one_of.as_ref().map(|any_of| any_of.iter().cloned().collect()),\n\n none_of: skills.none_of.as_ref().map(|none_of| none_of.iter().cloned().collect()),\n\n },\n\n );\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 61, "score": 305273.20725416864 }, { "content": "fn get_break_time_windows(break_job: &'_ Arc<Single>, departure: f64) -> impl Iterator<Item = TimeWindow> + '_ {\n\n break_job.places.first().unwrap().times.iter().map(move |span| span.to_time_window(departure))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/breaks.rs", "rank": 62, "score": 303606.73836878367 }, { "content": "fn get_tour_by_vehicle_id(vehicle_id: &str, shift_index: Option<usize>, solution: &Solution) -> Result<Tour, String> {\n\n solution\n\n .tours\n\n .iter()\n\n .find(|tour| tour.vehicle_id == vehicle_id && tour.shift_index == shift_index.unwrap_or(0))\n\n .cloned()\n\n .ok_or_else(|| format!(\"cannot find tour for '{}'\", vehicle_id))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/relations.rs", "rank": 63, "score": 302191.0240724281 }, { "content": "pub fn create_job(id: &str) -> Job {\n\n Job {\n\n id: id.to_string(),\n\n pickups: None,\n\n deliveries: None,\n\n replacements: None,\n\n services: None,\n\n priority: None,\n\n skills: None,\n\n value: None,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/helpers/problem.rs", "rank": 64, "score": 301720.92953586706 }, { "content": "/// Mark job as ignored only if it has break type and vehicle id is not present in routes\n\nfn is_required_job(routes: &[RouteContext], route_index: Option<usize>, job: &Job, default: bool) -> bool {\n\n match job {\n\n Job::Single(job) => {\n\n if is_break_single(job) {\n\n if let Some(route_index) = route_index {\n\n is_time(routes.get(route_index).unwrap(), job)\n\n } else {\n\n let vehicle_id = get_vehicle_id_from_job(job).unwrap();\n\n let shift_index = get_shift_index(&job.dimens);\n\n routes\n\n .iter()\n\n .any(move |rc| is_correct_vehicle(&rc.route, &vehicle_id, shift_index) && is_time(rc, job))\n\n }\n\n } else {\n\n default\n\n }\n\n }\n\n Job::Multi(_) => default,\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/breaks.rs", "rank": 65, "score": 300666.433353456 }, { "content": "#[test]\n\nfn can_use_two_pickup_delivery_jobs_and_relation_with_one_vehicle() {\n\n let problem = Problem {\n\n plan: Plan {\n\n jobs: vec![\n\n create_pickup_delivery_job(\"job1\", vec![20., 0.], vec![15., 0.]),\n\n create_pickup_delivery_job(\"job2\", vec![5., 0.], vec![20., 0.]),\n\n ],\n\n relations: Some(vec![Relation {\n\n type_field: RelationType::Sequence,\n\n jobs: to_strings(vec![\"job1\", \"job2\", \"job1\", \"job2\"]),\n\n vehicle_id: \"my_vehicle_1\".to_string(),\n\n shift_index: None,\n\n }]),\n\n },\n\n fleet: Fleet {\n\n vehicles: vec![VehicleType {\n\n shifts: vec![create_default_vehicle_shift_with_locations((10., 0.), (10., 0.))],\n\n ..create_default_vehicle_type()\n\n }],\n\n profiles: create_default_matrix_profiles(),\n", "file_path": "vrp-pragmatic/tests/features/pickdev/relation_pick_dev.rs", "rank": 66, "score": 299652.8345468255 }, { "content": "/// Generates matrix routes. See `generate_matrix_routes`.\n\npub fn generate_matrix_routes_with_defaults(rows: usize, cols: usize, is_open_vrp: bool) -> (Problem, Solution) {\n\n generate_matrix_routes(\n\n rows,\n\n cols,\n\n is_open_vrp,\n\n |id, location| test_single_with_id_and_location(id, location),\n\n |v| v,\n\n |data| (data.clone(), data),\n\n )\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/solver/mod.rs", "rank": 67, "score": 298507.24220098887 }, { "content": "fn get_activity_ids(tour: &Tour) -> Vec<String> {\n\n tour.stops\n\n .iter()\n\n .flat_map(|stop| {\n\n // TODO consider job tags within multi jobs\n\n stop.activities.iter().map(|a| a.job_id.clone())\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/relations.rs", "rank": 68, "score": 294421.4985156364 }, { "content": "fn can_use_break_between_two_jobs_in_relation_impl(relation_type: RelationType, jobs: Vec<String>) {\n\n let solution =\n\n get_solution(relation_type, 1., Some(vec![vec![3., 0.].to_loc()]), get_permissive_break_time(), jobs, true);\n\n\n\n assert_eq!(\n\n solution,\n\n Solution {\n\n statistic: Statistic {\n\n cost: 26.,\n\n distance: 6,\n\n duration: 10,\n\n times: Timing { driving: 6, serving: 2, waiting: 0, break_time: 2 },\n\n },\n\n tours: vec![Tour {\n\n vehicle_id: \"my_vehicle_1\".to_string(),\n\n type_id: \"my_vehicle\".to_string(),\n\n shift_index: 0,\n\n stops: vec![\n\n create_stop_with_activity(\n\n \"departure\",\n", "file_path": "vrp-pragmatic/tests/features/breaks/relation_break_test.rs", "rank": 69, "score": 294408.25311581837 }, { "content": "/// Estimates DBSCAN epsilon parameter.\n\nfn estimate_epsilon(problem: &Problem, min_points: usize) -> f64 {\n\n // for each job get distance to its nth neighbor\n\n let mut costs = get_average_costs(problem, min_points);\n\n\n\n // sort all distances in ascending order and form the curve\n\n costs.sort_by(|&a, &b| compare_floats(a, b));\n\n let curve = costs.into_iter().enumerate().map(|(idx, cost)| Point::new(idx as f64, cost)).collect::<Vec<_>>();\n\n\n\n // get max curvature approximation and return it as a guess for optimal epsilon value\n\n get_max_curvature(curve.as_slice())\n\n}\n\n\n", "file_path": "vrp-core/src/solver/mutation/ruin/cluster_removal.rs", "rank": 70, "score": 294168.203783771 }, { "content": "pub fn test_single_with_id_and_location(id: &str, location: Option<Location>) -> Arc<Single> {\n\n let mut single = Single { places: vec![test_place_with_location(location)], dimens: Default::default() };\n\n single.dimens.set_id(id);\n\n Arc::new(single)\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/jobs.rs", "rank": 71, "score": 291404.548953584 }, { "content": "fn generate_matrix_from_sizes(rows: usize, cols: usize) -> Vec<f64> {\n\n let size = cols * rows;\n\n let mut data = vec![0.; size * size];\n\n\n\n (0..size).for_each(|i| {\n\n let (left1, right1) = (i / rows, i % rows);\n\n ((i + 1)..size).for_each(|j| {\n\n let (left2, right2) = (j / rows, j % rows);\n\n let left_delta = left1 as f64 - left2 as f64;\n\n let right_delta = right1 as f64 - right2 as f64;\n\n\n\n let value = (left_delta * left_delta + right_delta * right_delta).sqrt();\n\n\n\n let sym_j = (j as i32 + (j as i32 - i as i32) * (size as i32 - 1)) as usize;\n\n\n\n data[i * size + j] = value;\n\n data[i * size + sym_j] = value;\n\n });\n\n });\n\n\n\n data\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/solver/mod.rs", "rank": 72, "score": 290383.46613016824 }, { "content": "fn add_priority(dimens: &mut Dimensions, priority: Option<i32>) {\n\n if let Some(priority) = priority {\n\n dimens.set_value(\"priority\", priority);\n\n }\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 73, "score": 289965.8707161515 }, { "content": "/// Gets solution serialized in json.\n\npub fn get_solution_serialized(problem: Arc<CoreProblem>, config: Config) -> Result<String, String> {\n\n let (solution, _, metrics) = create_builder_from_config(problem.clone(), &config)\n\n .and_then(|builder| builder.build())\n\n .and_then(|solver| solver.solve())\n\n .map_err(|err| {\n\n FormatError::new(\n\n \"E0003\".to_string(),\n\n \"cannot find any solution\".to_string(),\n\n format!(\"please submit a bug and share original problem and routing matrix. Error: '{}'\", err),\n\n )\n\n .to_json()\n\n })?;\n\n\n\n let mut buffer = String::new();\n\n let writer = unsafe { BufWriter::new(buffer.as_mut_vec()) };\n\n if let Some(metrics) = metrics {\n\n (solution, metrics).write_pragmatic_json(&problem, writer)?;\n\n } else {\n\n solution.write_pragmatic_json(&problem, writer)?;\n\n }\n\n\n\n Ok(buffer)\n\n}\n\n\n", "file_path": "vrp-cli/src/lib.rs", "rank": 74, "score": 289279.44393071695 }, { "content": "fn get_location_index(location: &Location, coord_index: &CoordIndex) -> Result<usize, String> {\n\n coord_index.get_by_loc(location).ok_or_else(|| format!(\"cannot find coordinate in coord index: {:?}\", location))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/routing.rs", "rank": 75, "score": 287191.2397174879 }, { "content": "fn get_priority(job: &Job) -> Option<i32> {\n\n match job {\n\n Job::Single(job) => job.dimens.get_value::<i32>(\"priority\"),\n\n Job::Multi(job) => job.dimens.get_value::<i32>(\"priority\"),\n\n }\n\n .cloned()\n\n}\n", "file_path": "vrp-pragmatic/src/constraints/priorities.rs", "rank": 76, "score": 286455.42404719815 }, { "content": "fn get_job_id(single: &Arc<Single>) -> String {\n\n Activity {\n\n place: Place { location: 0, duration: 0.0, time: TimeWindow::new(0., 0.) },\n\n schedule: Schedule { arrival: 0.0, departure: 0.0 },\n\n job: Some(single.clone()),\n\n }\n\n .retrieve_job()\n\n .unwrap()\n\n .dimens()\n\n .get_id()\n\n .cloned()\n\n .expect(\"cannot get job id\")\n\n}\n", "file_path": "vrp-pragmatic/src/format/solution/activity_matcher.rs", "rank": 77, "score": 286375.37409307796 }, { "content": "pub fn get_vehicle_id(vehicle: &Vehicle) -> &String {\n\n vehicle.dimens.get_id().unwrap()\n\n}\n\n\n", "file_path": "vrp-core/tests/helpers/models/problem/fleet.rs", "rank": 78, "score": 286274.1303743294 }, { "content": "fn parse_times(times: &Option<Vec<Vec<String>>>) -> Vec<TimeSpan> {\n\n times.as_ref().map_or(vec![TimeSpan::Window(TimeWindow::max())], |tws| {\n\n tws.iter().map(|tw| TimeSpan::Window(parse_time_window(tw))).collect()\n\n })\n\n}\n", "file_path": "vrp-pragmatic/src/format/problem/job_reader.rs", "rank": 79, "score": 286180.8912818932 }, { "content": "fn get_profile_index_map(api_problem: &ApiProblem) -> HashMap<String, usize> {\n\n api_problem.fleet.profiles.iter().fold(Default::default(), |mut acc, profile| {\n\n if acc.get(&profile.name).is_none() {\n\n acc.insert(profile.name.clone(), acc.len());\n\n }\n\n acc\n\n })\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/format/problem/fleet_reader.rs", "rank": 81, "score": 285389.21802248305 }, { "content": "fn get_matrix_value(idx: usize, matrix_values: &[i64]) -> Result<i64, String> {\n\n matrix_values\n\n .get(idx)\n\n .cloned()\n\n .ok_or_else(|| format!(\"attempt to get value out of bounds: {} vs {}\", idx, matrix_values.len()))\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/checker/routing.rs", "rank": 82, "score": 284346.28192159155 }, { "content": "pub fn default_pickup_delivery_prototype() -> impl Strategy<Value = Job> {\n\n pickup_delivery_prototype(\n\n default_job_place_prototype(),\n\n default_job_place_prototype(),\n\n generate_simple_demand(1..4),\n\n generate_no_priority(),\n\n generate_no_jobs_skills(),\n\n generate_no_jobs_value(),\n\n )\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/defaults.rs", "rank": 83, "score": 284328.5181073813 }, { "content": "fn as_lat_lon(location: Location) -> (f64, f64) {\n\n match location {\n\n Location::Coordinate { lat, lng } => (lat, lng),\n\n _ => panic!(\"approximation requires coordinates\"),\n\n }\n\n}\n", "file_path": "vrp-pragmatic/src/utils/approx_transporation.rs", "rank": 84, "score": 284270.56089175463 }, { "content": "fn can_use_break_last_in_relation_impl(relation_type: RelationType, jobs: Vec<String>) {\n\n let solution =\n\n get_solution(relation_type, 1., Some(vec![vec![3., 0.].to_loc()]), get_permissive_break_time(), jobs, true);\n\n\n\n assert_eq!(\n\n solution,\n\n Solution {\n\n statistic: Statistic {\n\n cost: 26.,\n\n distance: 6,\n\n duration: 10,\n\n times: Timing { driving: 6, serving: 2, waiting: 0, break_time: 2 },\n\n },\n\n tours: vec![Tour {\n\n vehicle_id: \"my_vehicle_1\".to_string(),\n\n type_id: \"my_vehicle\".to_string(),\n\n shift_index: 0,\n\n stops: vec![\n\n create_stop_with_activity(\n\n \"departure\",\n", "file_path": "vrp-pragmatic/tests/features/breaks/relation_break_test.rs", "rank": 85, "score": 284086.4638182436 }, { "content": "fn get_vehicle_ids(vehicles: &Vec<VehicleType>) -> Vec<String> {\n\n vehicles.iter().flat_map(|vehicle| vehicle.vehicle_ids.iter().cloned()).collect()\n\n}\n", "file_path": "vrp-pragmatic/tests/generator/relations.rs", "rank": 86, "score": 283864.0502916229 }, { "content": "/// Checks time window rules.\n\npub fn check_raw_time_windows(tws: &[Vec<String>], skip_intersection_check: bool) -> bool {\n\n let tws = get_time_windows(tws);\n\n check_time_windows(&tws, skip_intersection_check)\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/validation/common.rs", "rank": 87, "score": 282129.6143229372 }, { "content": "/// Returns min cost between job and location.\n\nfn get_cost_between_job_and_location(\n\n profile: &Profile,\n\n costs: &Costs,\n\n transport: &(dyn TransportCost + Send + Sync),\n\n job: &Job,\n\n to: Location,\n\n) -> Cost {\n\n get_job_locations(job)\n\n .map(|from| match from {\n\n Some(from) => get_cost_between_locations(&profile, costs, transport, from, to),\n\n _ => DEFAULT_COST,\n\n })\n\n .min_by(|a, b| a.partial_cmp(b).unwrap_or(Less))\n\n .unwrap_or(DEFAULT_COST)\n\n}\n\n\n", "file_path": "vrp-core/src/models/problem/jobs.rs", "rank": 88, "score": 281248.6215329771 }, { "content": "/// Get lists of problem.\n\npub fn get_unique_locations(problem: &Problem) -> Vec<Location> {\n\n CoordIndex::new(&problem).unique()\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/lib.rs", "rank": 89, "score": 280535.9366301918 }, { "content": "/// Returns variance and mean.\n\nfn get_variance_mean(values: &[f64]) -> (f64, f64) {\n\n let mean = get_mean(values);\n\n\n\n let (first, second) = values.iter().fold((0., 0.), |acc, v| {\n\n let dev = v - mean;\n\n (acc.0 + dev * dev, acc.1 + dev)\n\n });\n\n\n\n // NOTE Bessel's correction is not used here\n\n ((first - (second * second / values.len() as f64)) / (values.len() as f64), mean)\n\n}\n\n\n", "file_path": "vrp-core/src/algorithms/statistics/basics.rs", "rank": 90, "score": 279717.7336137793 }, { "content": "fn is_dispatch_job(job: &Job) -> bool {\n\n job.as_single().and_then(|single| single.dimens.get_value::<String>(\"type\")).map_or(false, |t| t == \"dispatch\")\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/dispatch.rs", "rank": 91, "score": 278905.75171304005 }, { "content": "fn get_init_solution(problem: Problem, solution: &Solution) -> Result<Solution, String> {\n\n let environment = Arc::new(Environment::default());\n\n let matrix = create_matrix_from_problem(&problem);\n\n let core_problem = Arc::new(\n\n (problem, vec![matrix]).read_pragmatic().unwrap_or_else(|err| panic!(\"cannot read core problem: {:?}\", err)),\n\n );\n\n\n\n let core_solution = to_core_solution(solution, core_problem.clone(), create_random())?;\n\n\n\n // NOTE: get statistic/tours updated\n\n let insertion_ctx = InsertionContext::new_from_solution(core_problem.clone(), (core_solution, None), environment);\n\n let core_solution = insertion_ctx.solution.to_solution(core_problem.extras.clone());\n\n\n\n let mut buffer = String::new();\n\n let writer = unsafe { BufWriter::new(buffer.as_mut_vec()) };\n\n core_solution.write_pragmatic_json(&core_problem, writer).expect(\"cannot serialize result solution\");\n\n\n\n deserialize_solution(BufReader::new(buffer.as_bytes())).map_err(|err| format!(\"cannot read solution: {}\", err))\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/format/solution/initial_reader_test.rs", "rank": 92, "score": 278428.79472427856 }, { "content": "/// Generates jobs.\n\npub fn generate_jobs(job_proto: impl Strategy<Value = Job>, range: Range<usize>) -> impl Strategy<Value = Vec<Job>> {\n\n prop::collection::vec(job_proto, range)\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/generator/jobs.rs", "rank": 93, "score": 278386.1623801503 }, { "content": "fn get_random_item<'a, T>(items: &'a [T], rnd: &DefaultRandom) -> Option<&'a T> {\n\n if items.is_empty() {\n\n return None;\n\n }\n\n\n\n let idx = rnd.uniform_int(0, items.len() as i32 - 1) as usize;\n\n items.get(idx)\n\n}\n", "file_path": "vrp-cli/src/extensions/generate/mod.rs", "rank": 94, "score": 275195.10779274337 }, { "content": "fn get_cost_between_locations(\n\n profile: &Profile,\n\n costs: &Costs,\n\n transport: &(dyn TransportCost + Send + Sync),\n\n from: Location,\n\n to: Location,\n\n) -> f64 {\n\n let distance = transport.distance(&profile, from, to, DEFAULT_DEPARTURE);\n\n let duration = transport.duration(&profile, from, to, DEFAULT_DEPARTURE);\n\n\n\n if distance < 0. || duration < 0. {\n\n // NOTE this happens if matrix uses negative values as a marker of unreachable location\n\n UNREACHABLE_COST\n\n } else {\n\n distance * costs.per_distance + duration * costs.per_driving_time\n\n }\n\n}\n\n\n", "file_path": "vrp-core/src/models/problem/jobs.rs", "rank": 95, "score": 273889.619966479 }, { "content": "fn assert_location(actual: &Location, expected: (f64, f64)) {\n\n let (lat, lng) = actual.to_lat_lng();\n\n\n\n assert_eq!(lat, expected.0);\n\n assert_eq!(lng, expected.1);\n\n}\n\n\n", "file_path": "vrp-pragmatic/tests/unit/format/problem/model_test.rs", "rank": 97, "score": 272648.2429630025 }, { "content": "fn is_correct_vehicle(route: &Route, target_id: &str, target_shift: usize) -> bool {\n\n route.actor.vehicle.dimens.get_id().unwrap() == target_id\n\n && get_shift_index(&route.actor.vehicle.dimens) == target_shift\n\n}\n\n\n", "file_path": "vrp-pragmatic/src/constraints/mod.rs", "rank": 98, "score": 272148.46724656894 }, { "content": "/// Gets mean of values.\n\npub fn get_mean(values: &[f64]) -> f64 {\n\n let sum: f64 = values.iter().sum();\n\n sum / values.len() as f64\n\n}\n\n\n", "file_path": "vrp-core/src/algorithms/statistics/basics.rs", "rank": 99, "score": 271758.3866810437 } ]
Rust
src/container/initials.rs
olehbozhok/rsmorphy
fa23ba0306af4df8b1cd867d46415e2baac82837
use std::{borrow::Cow, fmt}; use crate::{ analyzer::MorphAnalyzer, container::{abc::*, decode::*, paradigm::ParadigmId, stack::StackSource, Lex, Score}, opencorpora::tag::OpencorporaTagReg, }; #[derive(Debug, Clone, Copy, PartialEq)] pub enum InitialsKind { FirstName, Patronym, } #[derive(Debug, Clone, PartialEq)] pub struct Initials { pub letter: Cow<'static, str>, pub kind: InitialsKind, pub tag_idx: u8, } impl Initials { pub fn iter_lexeme<'s: 'i, 'm: 'i, 'i>( &'s self, morph: &'m MorphAnalyzer, ) -> impl Iterator<Item = Lex> + 'i { let base: u8 = match self.kind { InitialsKind::FirstName => 0, InitialsKind::Patronym => 12, }; (0..morph.units.initials.tags.len() / 2).map(move |tag_idx| { let container = Initials { tag_idx: base + tag_idx as u8, ..self.clone() }; Lex::from_stack(morph, StackSource::from(container)) }) } } impl Source for Initials { fn score(&self) -> Score { Score::Real(0.1) } fn is_lemma(&self) -> bool { unimplemented!() } fn is_known(&self) -> bool { unimplemented!() } fn get_word(&self) -> Cow<str> { self.letter.clone() } fn get_normal_form(&self, _morph: &MorphAnalyzer) -> Cow<str> { self.letter.clone() } fn get_tag<'a>(&self, morph: &'a MorphAnalyzer) -> &'a OpencorporaTagReg { &morph.units.initials.tags[self.tag_idx as usize].0 } fn try_get_para_id(&self) -> Option<ParadigmId> { None } fn write_word<W: fmt::Write>(&self, f: &mut W) -> fmt::Result { write!(f, "{}", self.letter) } fn write_normal_form<W: fmt::Write>(&self, f: &mut W, _morph: &MorphAnalyzer) -> fmt::Result { write!(f, "{}", self.letter) } fn get_lexeme(&self, morph: &MorphAnalyzer) -> Vec<Lex> { self.iter_lexeme(morph).collect() } fn get_lemma(&self, morph: &MorphAnalyzer) -> Lex { self.iter_lexeme(morph).next().unwrap() } } impl MorphySerde for Initials { fn encode<W: fmt::Write>(&self, f: &mut W) -> fmt::Result { write!( f, "i:{}{}{},{}", match self.kind { InitialsKind::FirstName => "n", InitialsKind::Patronym => "p", }, match (self.tag_idx / 6) % 2 { 0 => "m", 1 => "f", _ => unreachable!(), }, self.tag_idx % 6, self.letter ) } fn decode(s: &str) -> Result<(&str, Self), DecodeError> { let s = follow_str(s, "i").map_err(|_| DecodeError::UnknownPartType)?; let s = follow_str(s, ":")?; let (s, kind) = take_1_char(s)?; let (s, gender) = take_1_char(s)?; let (s, case) = take_1_char(s)?; let (s, word) = take_str_until_char_is(follow_str(s, ",")?, ';')?; let letter = Cow::from(word.to_string()); let tag_idx = decode_tag_idx(kind, gender, case)?; let kind = match kind { 'n' => InitialsKind::FirstName, 'p' => InitialsKind::Patronym, _ => Err(DecodeError::UnknownPartType)?, }; Ok(( s, Initials { kind, tag_idx, letter, }, )) } } fn decode_tag_idx(kind: char, gender: char, case: char) -> Result<u8, DecodeError> { let kind = match kind { 'n' => 0, 'p' => 1, _ => Err(DecodeError::UnknownPartType)?, }; let gender = match gender { 'm' => 0, 'f' => 1, _ => Err(DecodeError::UnknownPartType)?, }; let case = match case { '0'..='5' => case as u8 - b'0', _ => Err(DecodeError::UnknownPartType)?, }; Ok(kind * 12 + gender * 6 + case) }
use std::{borrow::Cow, fmt}; use crate::{ analyzer::MorphAnalyzer, container::{abc::*, decode::*, paradigm::ParadigmId, stack::StackSource, Lex, Score}, opencorpora::tag::OpencorporaTagReg, }; #[derive(Debug, Clone, Copy, PartialEq)] pub enum InitialsKind { FirstName, Patronym, } #[derive(Debug, Clone, PartialEq)] pub struct Initials { pub letter: Cow<'static, str>, pub kind: InitialsKind, pub tag_idx: u8, } impl Initials { pub fn iter_lexeme<'s: 'i, 'm: 'i, 'i>( &'s self, morph: &'m MorphAnalyzer, ) -> impl Iterator<Item = Lex> + 'i { let base: u8 = match self.kind { InitialsKind::FirstName => 0, InitialsKind::Patronym => 12, }; (0..morph.units.initials.tags.len() / 2).map(move |tag_idx| { let container = Initials { tag_idx: base + tag_idx as u8, ..self.clone() }; Lex::from_stack(morph, StackSource::from(container)) }) } } impl Source for Initials { fn score(&self) -> Score { Score::Real(0.1) } fn is_lemma(&self) -> bool { unimplemented!() } fn is_known(&self) -> bool { unimplemented!() } fn get_word(&self) -> Cow<str> { self.letter.clone() } fn get_normal_form(&self, _morph: &MorphAnalyzer) -> Cow<str> { self.letter.clone() } fn get_tag<'a>(&self, morph: &'a MorphAnalyzer) -> &'a OpencorporaTagReg { &morph.units.initials.tags[self.tag_idx as usize].0 } fn try_get_para_id(&self) -> Option<ParadigmId> { None } fn write_word<W: fmt::Write>(&self, f: &mut W) -> fmt::Result { write!(f, "{}", self.letter) } fn write_normal_form<W: fmt::Write>(&self, f: &mut W, _morph: &MorphAnalyzer) -> fmt::Result { write!(f, "{}", self.letter) } fn get_lexeme(&self, morph: &MorphAnalyzer) -> Vec<Lex> { self.iter_lexeme(morph).collect() } fn get_lemma(&self, morph: &MorphAnalyzer) -> Lex { self.iter_lexeme(morph).next().unwrap() } } impl MorphySerde for Initials { fn encode<W: fmt::Write>(&self, f: &mut W) -> fmt::Result { write!( f, "i:{}{}{},{}", match self.kind { InitialsKind::FirstName => "n", InitialsKind::Patronym => "p", }, match (self.tag_idx / 6) % 2 { 0 => "m", 1 => "f", _ => unreachable!(), }, self.tag_idx % 6, self.letter ) }
} fn decode_tag_idx(kind: char, gender: char, case: char) -> Result<u8, DecodeError> { let kind = match kind { 'n' => 0, 'p' => 1, _ => Err(DecodeError::UnknownPartType)?, }; let gender = match gender { 'm' => 0, 'f' => 1, _ => Err(DecodeError::UnknownPartType)?, }; let case = match case { '0'..='5' => case as u8 - b'0', _ => Err(DecodeError::UnknownPartType)?, }; Ok(kind * 12 + gender * 6 + case) }
fn decode(s: &str) -> Result<(&str, Self), DecodeError> { let s = follow_str(s, "i").map_err(|_| DecodeError::UnknownPartType)?; let s = follow_str(s, ":")?; let (s, kind) = take_1_char(s)?; let (s, gender) = take_1_char(s)?; let (s, case) = take_1_char(s)?; let (s, word) = take_str_until_char_is(follow_str(s, ",")?, ';')?; let letter = Cow::from(word.to_string()); let tag_idx = decode_tag_idx(kind, gender, case)?; let kind = match kind { 'n' => InitialsKind::FirstName, 'p' => InitialsKind::Patronym, _ => Err(DecodeError::UnknownPartType)?, }; Ok(( s, Initials { kind, tag_idx, letter, }, )) }
function_block-full_function
[ { "content": "pub fn take_str_until<P>(s: &str, mut predicate: P) -> Result<(&str, &str), DecodeError>\n\nwhere\n\n P: FnMut(char) -> bool,\n\n{\n\n let mut pos = 0;\n\n for ch in s.chars() {\n\n if (predicate)(ch) {\n\n break;\n\n } else {\n\n pos += ch.len_utf8();\n\n }\n\n }\n\n Ok((&s[pos..], &s[..pos]))\n\n}\n\n\n", "file_path": "src/container/decode/take.rs", "rank": 0, "score": 284345.32392704417 }, { "content": "pub fn take_str_while_char<P>(s: &str, mut predicate: P) -> Result<(&str, &str), DecodeError>\n\nwhere\n\n P: FnMut(char) -> bool,\n\n{\n\n let mut pos = 0;\n\n for ch in s.chars() {\n\n if (predicate)(ch) {\n\n pos += ch.len_utf8();\n\n } else {\n\n break;\n\n }\n\n }\n\n Ok((&s[pos..], &s[..pos]))\n\n}\n\n\n", "file_path": "src/container/decode/take.rs", "rank": 1, "score": 280678.8404195092 }, { "content": "pub fn take_str_while<'s, P>(s: &'s str, mut predicate: P) -> Result<(&'s str, &'s str), DecodeError>\n\n where\n\n P: FnMut(char) -> bool\n\n{\n\n let mut pos = 0;\n\n for ch in s.chars() {\n\n if (predicate)(ch) {\n\n pos += ch.len_utf8();\n\n } else {\n\n break;\n\n }\n\n }\n\n Ok( (&s[pos ..], &s[.. pos]) )\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 2, "score": 279644.25799907214 }, { "content": "pub fn take_str_until<'s, P>(s: &'s str, mut predicate: P) -> Result<(&'s str, &'s str), DecodeError>\n\n where\n\n P: FnMut(char) -> bool\n\n{\n\n let mut pos = 0;\n\n for ch in s.chars() {\n\n if (predicate)(ch) {\n\n break;\n\n } else {\n\n pos += ch.len_utf8();\n\n }\n\n }\n\n Ok( (&s[pos ..], &s[.. pos]) )\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 3, "score": 279644.25799907214 }, { "content": "pub fn unescape<'s: 'i, 'i>(s: &'s str) -> impl Iterator<Item = &'s str> + 'i {\n\n // trace!(r#\"unescape: \"{}\"\"#, s);\n\n let i1 = s.split(\"\");\n\n let i2 = i1.clone().skip(1);\n\n let mut esc = false;\n\n i1.zip(i2)\n\n .filter(move |&(c1, c2)| {\n\n // trace!(r#\"c1, c2: \"{}\", \"{}\"\"#, c1, c2);\n\n // FIXME a bug in clippy; https://github.com/rust-lang-nursery/rust-clippy/issues/860\n\n #[allow(clippy::match_same_arms)]\n\n match (esc, c1, c2) {\n\n (false, r\"\\\", \"\") => true,\n\n (false, r\"\\\", _) => {\n\n esc = true;\n\n false\n\n }\n\n (true, _, _) => {\n\n esc = false;\n\n true\n\n }\n\n _ => true,\n\n }\n\n })\n\n .map(|(c1, _)| c1)\n\n}\n", "file_path": "src/container/decode/mod.rs", "rank": 4, "score": 227143.5567833772 }, { "content": "pub fn escape<'s: 'i, 'i>(s: &'s str) -> impl Iterator<Item = &'s str> + 'i {\n\n s.split(\"\").map(|ch| match ch {\n\n r\"\\\" => r\"\\\\\",\n\n r\":\" => r\"\\:\",\n\n r\";\" => r\"\\;\",\n\n r\",\" => r\"\\,\",\n\n _ => ch,\n\n })\n\n}\n\n\n\n/**\n\n```\n\nuse rsmorphy::container::decode::unescape;\n\n\n\nassert_eq!(unescape(r\"a\\,b\").collect::<String>(), String::from(r\"a,b\"));\n\nassert_eq!(unescape(r\"a\\;b\").collect::<String>(), String::from(r\"a;b\"));\n\nassert_eq!(unescape(r\"a\\:b\").collect::<String>(), String::from(r\"a:b\"));\n\nassert_eq!(unescape(r\"a\\\\b\").collect::<String>(), String::from(r\"a\\b\"));\n\nassert_eq!(unescape(r\"a\\\") .collect::<String>(), String::from(r\"a\\\"));\n\n```\n\n*/\n", "file_path": "src/container/decode/mod.rs", "rank": 5, "score": 227143.5567833772 }, { "content": "pub fn print_row_parsed(morph: &MorphAnalyzer, n: usize, &Parsed { ref lex, score }: &Parsed) {\n\n println!(\n\n r#\"{num:2}. {score:7.5} :: {lex:20} — {norm:20} :: {enc:35} :: {tag:40}\"#,\n\n num = n + 1,\n\n score = score.value(),\n\n lex = lex.get_word(),\n\n norm = lex.get_normal_form(morph),\n\n tag = lex.get_tag(morph).string.as_str(),\n\n enc = lex.stack.encoded()\n\n );\n\n}\n\n\n", "file_path": "examples/util/mod.rs", "rank": 6, "score": 211496.30498929488 }, { "content": "pub fn print_row_lex(morph: &MorphAnalyzer, n: usize, lex: &Lex) {\n\n println!(\n\n r#\"{num:2}. {score:7.5} :: {lex:20} — {norm:20} :: {enc:35} :: {tag:40}\"#,\n\n num = n + 1,\n\n score = Score::Fake(0.0).value(), //lex.score.value(),\n\n lex = lex.get_word(),\n\n norm = lex.get_normal_form(morph),\n\n tag = lex.get_tag(morph).string.as_str(),\n\n enc = lex.stack.encoded()\n\n );\n\n}\n\n\n", "file_path": "examples/util/mod.rs", "rank": 7, "score": 209471.68671133416 }, { "content": "pub fn follow_str<'s, 'm>(s: &'s str, m: &'m str) -> Result<(&'s str, &'m str), DecodeError> {\n\n if s.len() < m.len() {\n\n Err(DecodeError::UnexpectedEnd)?;\n\n }\n\n if s.as_bytes().iter().zip(m.as_bytes().iter()).all(|(a, b)| a == b) {\n\n Ok((&s[m.len() .. ], m))\n\n } else {\n\n Err(DecodeError::DoesntMatch)\n\n }\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 8, "score": 201689.62560209443 }, { "content": "pub fn take_1_char(s: &str) -> Result<(&str, char), DecodeError> {\n\n let ch = s.chars().next().ok_or(DecodeError::UnexpectedEnd)?;\n\n Ok((&s[ch.len_utf8() .. ], ch))\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 10, "score": 199593.64033616794 }, { "content": "pub fn follow_str<'s, 'm>(s: &'s str, m: &'m str) -> Result<&'s str, DecodeError> {\n\n if s.len() < m.len() {\n\n // FIXME maybe DoesntMatch?\n\n Err(DecodeError::UnexpectedEnd)?;\n\n }\n\n if s.as_bytes()\n\n .iter()\n\n .zip(m.as_bytes().iter())\n\n .all(|(a, b)| a == b)\n\n {\n\n Ok(&s[m.len()..])\n\n } else {\n\n Err(DecodeError::DoesntMatch)\n\n }\n\n}\n", "file_path": "src/container/decode/follow.rs", "rank": 11, "score": 199313.806656913 }, { "content": "pub fn take_1_char(s: &str) -> Result<(&str, char), DecodeError> {\n\n let ch = s.chars().next().ok_or(DecodeError::UnexpectedEnd)?;\n\n Ok((&s[ch.len_utf8()..], ch))\n\n}\n\n\n", "file_path": "src/container/decode/take.rs", "rank": 12, "score": 196307.3652732484 }, { "content": "pub fn take_str_while_char_is(s: &str, chr: char) -> Result<(&str, &str), DecodeError> {\n\n take_str_while_char(s, |ch| ch == chr)\n\n}\n\n\n", "file_path": "src/container/decode/take.rs", "rank": 13, "score": 195653.91642530268 }, { "content": "pub fn take_str_until_char_is(s: &str, chr: char) -> Result<(&str, &str), DecodeError> {\n\n take_str_until(s, |ch| ch == chr)\n\n}\n", "file_path": "src/container/decode/take.rs", "rank": 14, "score": 195653.91642530268 }, { "content": "pub fn is_digit(chr: char) -> bool {\n\n chr.is_digit(10)\n\n}\n\n\n", "file_path": "src/container/decode/predicate.rs", "rank": 15, "score": 194855.82368377456 }, { "content": "pub fn take_str_while_char<'s>(s: &'s str, chr: char) -> Result<(&'s str, &'s str), DecodeError> {\n\n take_str_while(s, |ch| ch == chr )\n\n}\n\n\n", "file_path": "src/container/decode_.rs", "rank": 16, "score": 193454.1264698306 }, { "content": "pub fn take_str_until_char<'s>(s: &'s str, chr: char) -> Result<(&'s str, &'s str), DecodeError> {\n\n take_str_until(s, |ch| ch == chr )\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 17, "score": 193454.1264698306 }, { "content": "pub fn is_hex_digit(chr: char) -> bool {\n\n chr.is_digit(16)\n\n}\n", "file_path": "src/container/decode/predicate.rs", "rank": 18, "score": 190846.33678534155 }, { "content": "pub fn is_punctuation(token: &str) -> bool {\n\n !token.is_empty()\n\n && token.chars().any(|ch| ch.is_punctuation())\n\n && token\n\n .chars()\n\n .all(|ch| ch.is_punctuation() || ch.is_whitespace())\n\n}\n\n\n\n/**\n\n Return True if token looks like a Roman number:\n\n\n\n ```\n\n use rsmorphy::shapes::is_roman_number;\n\n\n\n assert!(is_roman_number(\"II\"));\n\n assert!(is_roman_number(\"IX\"));\n\n\n\n assert!(!is_roman_number(\"XIIIII\"));\n\n assert!(!is_roman_number(\"\"));\n\n ```\n\n*/\n", "file_path": "src/shapes.rs", "rank": 19, "score": 188712.68671305894 }, { "content": "pub fn is_latin(token: &str) -> bool {\n\n token.is_ascii() && token.as_bytes().iter().cloned().any(is_ascii_alpha)\n\n}\n\n\n\n/**\n\n Return True if a word contains only spaces and punctuation marks\n\n and there is at least one punctuation mark:\n\n\n\n ```\n\n use rsmorphy::shapes::is_punctuation;\n\n\n\n assert!(is_punctuation(\", \"));\n\n assert!(is_punctuation(\"..!\"));\n\n\n\n assert!(!is_punctuation(\"x\"));\n\n assert!(!is_punctuation(\" \"));\n\n assert!(!is_punctuation(\"\"));\n\n ```\n\n*/\n", "file_path": "src/shapes.rs", "rank": 20, "score": 188712.68671305894 }, { "content": "pub fn map_parse_int<'s, 'm, T>( (s, m): (&'s str, &'m str) ) -> Result<(&'s str, T), DecodeError>\n\n where\n\n T: FromStr<Err = ParseIntError>\n\n{\n\n Ok( (s, T::from_str(m)?) )\n\n}\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 21, "score": 188365.39084402463 }, { "content": "pub fn map_parse_float<'s, 'm, T>( (s, m): (&'s str, &'m str) ) -> Result<(&'s str, T), DecodeError>\n\n where\n\n T: FromStr<Err = ParseFloatError>\n\n{\n\n Ok( (s, T::from_str(m)?) )\n\n}\n\n\n", "file_path": "src/container/decode_.rs", "rank": 22, "score": 188365.39084402463 }, { "content": "pub fn parse_float<'s, 'm, T>((s, m): (&'s str, &'m str)) -> Result<(&'s str, T), DecodeError>\n\nwhere\n\n T: FromStr<Err = ParseFloatError>,\n\n{\n\n Ok((s, T::from_str(m)?))\n\n}\n", "file_path": "src/container/decode/map.rs", "rank": 23, "score": 188365.39084402463 }, { "content": "pub fn parse_int<'s, 'm, T>((s, m): (&'s str, &'m str)) -> Result<(&'s str, T), DecodeError>\n\nwhere\n\n T: FromStr<Err = ParseIntError>,\n\n{\n\n Ok((s, T::from_str(m)?))\n\n}\n\n\n", "file_path": "src/container/decode/map.rs", "rank": 24, "score": 188365.39084402463 }, { "content": "#[inline]\n\npub fn is_ascii_alpha(ch: u8) -> bool {\n\n let ch = ch | 0x20;\n\n ch >= b'a' && ch <= b'z'\n\n}\n\n\n\n/**\n\n Return True if all token letters are latin and there is at\n\n least one latin letter in the token:\n\n\n\n ```\n\n use rsmorphy::shapes::is_latin;\n\n\n\n assert!(is_latin(\"foo\"));\n\n assert!(is_latin(\"123-FOO\"));\n\n\n\n assert!(!is_latin(\"123\"));\n\n assert!(!is_latin(\":)\"));\n\n assert!(!is_latin(\"\"));\n\n ```\n\n*/\n", "file_path": "src/shapes.rs", "rank": 25, "score": 188232.49665598784 }, { "content": "/// Check if a unit has a leaf as a child or not.\n\npub fn has_leaf(base: u32) -> bool {\n\n base & HAS_LEAF_BIT != 0\n\n}\n\n\n", "file_path": "src/dawg/units.rs", "rank": 26, "score": 188016.25614238385 }, { "content": "pub fn parse_hex_int<'s, 'm, T>((s, m): (&'s str, &'m str)) -> Result<(&'s str, T), DecodeError>\n\nwhere\n\n T: Num<FromStrRadixErr = ParseIntError>,\n\n{\n\n Ok((s, T::from_str_radix(m, 16)?))\n\n}\n\n\n", "file_path": "src/container/decode/map.rs", "rank": 27, "score": 185537.4875469798 }, { "content": "pub fn is_roman_number(token: &str) -> bool {\n\n roman::from(token).is_some()\n\n}\n", "file_path": "src/shapes.rs", "rank": 28, "score": 185084.6719298791 }, { "content": "pub fn try_parse_int<'s, 'm, T>((s, m): (&'s str, &'m str)) -> Option<(&'s str, T)>\n\nwhere\n\n T: FromStr<Err = ParseIntError>,\n\n{\n\n parse_int((s, m)).ok()\n\n}\n\n\n", "file_path": "src/container/decode/map.rs", "rank": 29, "score": 182544.5960409154 }, { "content": "fn print_lexeme(morph: &MorphAnalyzer, lex: &Lex) {\n\n for (i, lex) in lex.iter_lexeme(morph).enumerate() {\n\n print_row_lex(morph, i, &lex);\n\n }\n\n}\n\n\n", "file_path": "examples/lexeme.rs", "rank": 30, "score": 165612.62549740722 }, { "content": "pub fn input_loop<F>(f: F)\n\nwhere\n\n F: Fn(&str),\n\n{\n\n println!(\"Press Ctrl-C to exit.\");\n\n let mut rl = Editor::<()>::new();\n\n loop {\n\n let readline = rl.readline(\"Word to parse: \");\n\n match readline {\n\n Ok(line) => {\n\n rl.add_history_entry(line.to_string());\n\n f(line.trim());\n\n }\n\n Err(ReadlineError::Interrupted) => {\n\n println!(\"Ctrl-C\");\n\n break;\n\n }\n\n Err(ReadlineError::Eof) => {\n\n println!(\"Ctrl-D\");\n\n break;\n\n }\n\n Err(err) => {\n\n println!(\"Error: {:?}\", err);\n\n break;\n\n }\n\n }\n\n }\n\n}\n", "file_path": "examples/util/mod.rs", "rank": 31, "score": 157228.25977997293 }, { "content": "fn table(morph: &MorphAnalyzer, s: &str) {\n\n for (i, parsed) in morph.parse(s).into_iter().enumerate() {\n\n print_row_parsed(morph, i, &parsed);\n\n }\n\n}\n\n\n", "file_path": "examples/parse.rs", "rank": 32, "score": 151560.4226569065 }, { "content": "fn list(morph: &MorphAnalyzer, s: &str) {\n\n let set = BTreeSet::from_iter(\n\n morph\n\n .parse(s)\n\n .into_iter()\n\n .map(|parsed| parsed.lex.get_lemma(morph).encoded()),\n\n );\n\n for (i, id) in set.into_iter().enumerate() {\n\n let lemma = Lex::from_id(morph, id).unwrap();\n\n println!(\" === {}. {} ===\", i + 1, lemma.get_word());\n\n print_lexeme(morph, &lemma);\n\n }\n\n}\n\n\n", "file_path": "examples/lexeme.rs", "rank": 33, "score": 151560.4226569065 }, { "content": "fn table(morph: &MorphAnalyzer, s: &str) {\n\n for (i, parsed) in morph.parse(s).into_iter().enumerate() {\n\n let enc = parsed.lex.encoded();\n\n let (s, dec) = Lex::decode(&enc).unwrap();\n\n let decoded = Parsed {\n\n lex: dec,\n\n score: parsed.score,\n\n }; //dec.score()\n\n assert_eq!(s, \"\");\n\n print_row_parsed(morph, i, &parsed);\n\n print_row_parsed(morph, i, &decoded);\n\n println!();\n\n }\n\n}\n\n\n", "file_path": "examples/enc-dec.rs", "rank": 34, "score": 149007.79306241535 }, { "content": "/// Read a label with a leaf flag from a non-leaf unit.\n\npub fn label(base: u32) -> u32 {\n\n base & (IS_LEAF_BIT | 0x0000_00FF)\n\n}\n\n\n", "file_path": "src/dawg/units.rs", "rank": 35, "score": 137283.1459233426 }, { "content": "/// Check if a unit corresponds to a leaf or not.\n\npub fn value(base: u32) -> u32 {\n\n base & (IS_LEAF_BIT ^ PRECISION_MASK)\n\n}\n\n\n", "file_path": "src/dawg/units.rs", "rank": 36, "score": 137283.1459233426 }, { "content": "/// Read an offset to child units from a non-leaf unit.\n\npub fn offset(base: u32) -> u32 {\n\n (base >> 10) << ((base & EXTENSION_BIT) >> 6)\n\n}\n", "file_path": "src/dawg/units.rs", "rank": 37, "score": 137283.1459233426 }, { "content": "fn try_decode<T: MorphySerde + Into<StackSource>>(\n\n s: &str,\n\n) -> Result<Option<(&str, StackSource)>, DecodeError> {\n\n Ok(match T::decode(s) {\n\n Err(DecodeError::UnknownPartType) => None,\n\n Err(e) => Err(e)?,\n\n Ok((s, v)) => Some((s, v.into())),\n\n })\n\n}\n", "file_path": "src/container/stack/source.rs", "rank": 38, "score": 135571.1089663532 }, { "content": "pub trait Source {\n\n // TODO move out `score` from a word container\n\n fn score(&self) -> Score;\n\n fn is_lemma(&self) -> bool;\n\n fn is_known(&self) -> bool;\n\n fn get_word(&self) -> Cow<str>;\n\n fn get_normal_form(&self, morph: &MorphAnalyzer) -> Cow<str>;\n\n fn get_tag<'m>(&self, morph: &'m MorphAnalyzer) -> &'m OpencorporaTagReg;\n\n fn try_get_para_id(&self) -> Option<ParadigmId>;\n\n fn write_word<W: fmt::Write>(&self, f: &mut W) -> fmt::Result;\n\n fn write_normal_form<W: fmt::Write>(&self, f: &mut W, morph: &MorphAnalyzer) -> fmt::Result;\n\n fn get_lexeme(&self, morph: &MorphAnalyzer) -> Vec<Lex>;\n\n fn get_lemma(&self, morph: &MorphAnalyzer) -> Lex;\n\n}\n\n\n", "file_path": "src/container/abc.rs", "rank": 39, "score": 119366.50589661708 }, { "content": "/// Returns all splits of a `word` (taking into account `min_reminder` and `max_prefix_length`).\n\npub fn word_splits<'w: 'i, 'i, Rem, Pref>(\n\n word: &'w str,\n\n min_reminder: Rem,\n\n max_prefix_length: Pref,\n\n) -> impl Iterator<Item = (&'w str, &'w str)> + 'i\n\nwhere\n\n Rem: Into<Option<usize>>,\n\n Pref: Into<Option<usize>>,\n\n{\n\n let min_reminder = min_reminder.into().unwrap_or(3);\n\n let max_prefix_length = max_prefix_length.into().unwrap_or(5);\n\n let char_len = word.chars().count();\n\n\n\n let max_split = if char_len > min_reminder {\n\n min(max_prefix_length, char_len - min_reminder)\n\n } else {\n\n 0\n\n };\n\n\n\n log::trace!(\"max_split: {}\", max_split);\n", "file_path": "src/util.rs", "rank": 40, "score": 101915.91411606045 }, { "content": "pub fn add_parsed_if_not_seen(\n\n morph: &MorphAnalyzer,\n\n result: &mut ParseResult,\n\n seen_parses: &mut SeenSet,\n\n parsed: Parsed,\n\n) {\n\n if seen_parses.insert(&parsed.lex.as_seen(morph)) {\n\n result.push(parsed);\n\n }\n\n}\n\n\n", "file_path": "src/util.rs", "rank": 41, "score": 95407.71127074225 }, { "content": "pub trait MorphySerde: Sized {\n\n fn encode<W: fmt::Write>(&self, f: &mut W) -> fmt::Result;\n\n fn decode(s: &str) -> Result<(&str, Self), DecodeError>;\n\n\n\n fn encoded(&self) -> String {\n\n let mut s = String::new();\n\n self.encode(&mut s).unwrap();\n\n s\n\n }\n\n}\n", "file_path": "src/container/abc.rs", "rank": 42, "score": 78909.85289290335 }, { "content": "fn load_paradigms<R: Read>(reader: &mut R) -> Vec<Vec<ParadigmEntry>> {\n\n let paradigms_count = reader.read_u16::<LittleEndian>().unwrap();\n\n (0..paradigms_count)\n\n .map(|_| {\n\n let paradigm_len = reader.read_u16::<LittleEndian>().unwrap();\n\n (0..paradigm_len)\n\n .map(|_| reader.read_u16::<LittleEndian>().unwrap())\n\n .collect::<Vec<u16>>()\n\n })\n\n .map(ParadigmEntry::build)\n\n .collect()\n\n}\n", "file_path": "src/opencorpora/dictionary.rs", "rank": 43, "score": 77098.90088495366 }, { "content": "use std::{cmp::Ordering, ops::Mul};\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq)]\n\npub enum Score {\n\n /// Evaluated from the dictionary or other source.\n\n Real(f64),\n\n /// Evaluated out of thin air.\n\n Fake(f64),\n\n}\n\n\n\nimpl Score {\n\n pub fn value(&self) -> f64 {\n\n match *self {\n\n Score::Real(v) | Score::Fake(v) => v,\n\n }\n\n }\n\n\n\n pub fn value_ref_mut(&mut self) -> &mut f64 {\n\n match *self {\n\n Score::Real(ref mut v) | Score::Fake(ref mut v) => v,\n", "file_path": "src/container/score.rs", "rank": 44, "score": 72533.5667828826 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl PartialOrd for Score {\n\n fn partial_cmp(&self, other: &Score) -> Option<Ordering> {\n\n self.value().partial_cmp(&other.value())\n\n }\n\n}\n\n\n\nimpl Mul for Score {\n\n type Output = Self;\n\n fn mul(self, rhs: Self) -> Self::Output {\n\n match (self, rhs) {\n\n (Score::Real(a), Score::Real(b)) => Score::Real(a * b),\n\n _ => Score::Fake(self.value() * rhs.value()),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/container/score.rs", "rank": 45, "score": 72521.15798002461 }, { "content": "impl Mul<f64> for Score {\n\n type Output = Self;\n\n fn mul(self, rhs: f64) -> Self::Output {\n\n match self {\n\n Score::Real(v) => Score::Real(v * rhs),\n\n Score::Fake(v) => Score::Fake(v * rhs),\n\n }\n\n }\n\n}\n", "file_path": "src/container/score.rs", "rank": 46, "score": 72521.02832450172 }, { "content": "use std::{borrow::Cow, fmt};\n\n\n\nuse crate::{\n\n analyzer::MorphAnalyzer,\n\n container::{abc::*, decode::*, paradigm::ParadigmId, stack::StackParticle, Score, Seen},\n\n opencorpora::{GrammemeSet, OpencorporaTagReg},\n\n};\n\n\n\npub type Lexeme = Vec<Lex>;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub struct Lex {\n\n pub stack: StackParticle,\n\n}\n\n\n\nimpl Lex {\n\n pub fn from_id<S>(_morph: &MorphAnalyzer, id: S) -> Result<Self, DecodeError>\n\n where\n\n S: AsRef<str>,\n\n {\n", "file_path": "src/container/lex.rs", "rank": 47, "score": 72426.73621350352 }, { "content": "impl MorphySerde for Lex {\n\n fn encode<W: fmt::Write>(&self, f: &mut W) -> fmt::Result {\n\n write!(f, \"ru:\")?;\n\n self.stack.encode(f)\n\n }\n\n\n\n fn decode(s: &str) -> Result<(&str, Self), DecodeError> {\n\n let s = follow_str(s, \"ru\").map_err(|_| DecodeError::UnknownPartType)?;\n\n let (s, stack) = StackParticle::decode(follow_str(s, \":\")?)?;\n\n Ok((s, Lex { stack }))\n\n }\n\n}\n", "file_path": "src/container/lex.rs", "rank": 48, "score": 72422.24521852809 }, { "content": "\n\n fn write_normal_form<W: fmt::Write>(&self, f: &mut W, morph: &MorphAnalyzer) -> fmt::Result {\n\n self.stack.write_normal_form(f, morph)\n\n }\n\n\n\n fn get_lexeme(&self, morph: &MorphAnalyzer) -> Vec<Lex> {\n\n self.stack.get_lexeme(morph)\n\n }\n\n\n\n fn get_lemma(&self, morph: &MorphAnalyzer) -> Lex {\n\n self.stack.get_lemma(morph)\n\n }\n\n}\n\n\n\nimpl fmt::Display for Lex {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n self.write_word(f)\n\n }\n\n}\n\n\n", "file_path": "src/container/lex.rs", "rank": 49, "score": 72418.16020322057 }, { "content": " Ok(Self::decode(id.as_ref()).map(|(_, lex)| lex)?)\n\n }\n\n\n\n pub fn from_stack<S>(_morph: &MorphAnalyzer, stack: S) -> Self\n\n where\n\n S: Into<StackParticle>,\n\n {\n\n Lex {\n\n stack: stack.into(),\n\n }\n\n }\n\n\n\n pub fn iter_lexeme<'s: 'i, 'm: 'i, 'i>(\n\n &'s self,\n\n morph: &'m MorphAnalyzer,\n\n ) -> impl Iterator<Item = Lex> + 'i {\n\n self.stack.iter_lexeme(morph)\n\n }\n\n\n\n pub fn as_seen<'m>(&'m self, morph: &'m MorphAnalyzer) -> Seen<'m> {\n", "file_path": "src/container/lex.rs", "rank": 50, "score": 72412.79088151526 }, { "content": "\n\n fn get_word(&self) -> Cow<str> {\n\n self.stack.get_word()\n\n }\n\n\n\n fn get_normal_form(&self, morph: &MorphAnalyzer) -> Cow<str> {\n\n self.stack.get_normal_form(morph)\n\n }\n\n\n\n fn get_tag<'m>(&self, morph: &'m MorphAnalyzer) -> &'m OpencorporaTagReg {\n\n self.stack.get_tag(morph)\n\n }\n\n\n\n fn try_get_para_id(&self) -> Option<ParadigmId> {\n\n self.stack.try_get_para_id()\n\n }\n\n\n\n fn write_word<W: fmt::Write>(&self, f: &mut W) -> fmt::Result {\n\n self.stack.write_word(f)\n\n }\n", "file_path": "src/container/lex.rs", "rank": 51, "score": 72412.24878374628 }, { "content": " .count();\n\n (lex, hsl)\n\n })\n\n .max_by_key(|&(_, hsl)| hsl)\n\n .map(|(lex, _)| lex)\n\n }\n\n}\n\n\n\nimpl Source for Lex {\n\n fn score(&self) -> Score {\n\n self.stack.score()\n\n }\n\n\n\n fn is_lemma(&self) -> bool {\n\n self.stack.is_lemma()\n\n }\n\n\n\n fn is_known(&self) -> bool {\n\n self.stack.is_known()\n\n }\n", "file_path": "src/container/lex.rs", "rank": 52, "score": 72410.92283057937 }, { "content": " Seen {\n\n word: self.get_word(),\n\n tag: self.get_tag(morph),\n\n para_id: self.stack.try_get_para_id(),\n\n }\n\n }\n\n\n\n pub fn get_plural<'m>(&self, morph: &'m MorphAnalyzer, num: usize) -> Option<Lex> {\n\n self.inflect(morph, &self.get_tag(morph).numeral_agreement_grammemes(num))\n\n }\n\n\n\n pub fn inflect(&self, morph: &MorphAnalyzer, required: &GrammemeSet) -> Option<Lex> {\n\n let new_grammemes = self.get_tag(morph).prepare_required(morph, required);\n\n self.iter_lexeme(morph)\n\n .map(|lex| {\n\n let hsl = lex\n\n .get_tag(morph)\n\n .grammemes\n\n .set\n\n .intersection(&new_grammemes.set)\n", "file_path": "src/container/lex.rs", "rank": 53, "score": 72403.15375540816 }, { "content": "use std::{\n\n str::FromStr,\n\n num::{\n\n ParseIntError,\n\n ParseFloatError\n\n }\n\n};\n\n\n\npub enum DecodeError {\n\n UnexpectedEnd,\n\n UnknownPartType,\n\n DoesntMatch,\n\n ParseIntError(ParseIntError),\n\n ParseFloatError(ParseFloatError)\n\n}\n\n\n\n\n\nimpl From<ParseIntError> for DecodeError {\n\n fn from(e: ParseIntError) -> Self {\n\n DecodeError::ParseIntError(e)\n", "file_path": "src/container/decode_.rs", "rank": 61, "score": 71998.91946871273 }, { "content": " }\n\n}\n\n\n\nimpl From<ParseFloatError> for DecodeError {\n\n fn from(e: ParseFloatError) -> Self {\n\n DecodeError::ParseFloatError(e)\n\n }\n\n}\n\n\n\n\n\npub fn (chr: char) {ch.is_digit(10)\n\n\n\n\n", "file_path": "src/container/decode_.rs", "rank": 62, "score": 71993.35524449829 }, { "content": "use std::{borrow::Cow, fmt};\n\n\n\nuse crate::{\n\n analyzer::MorphAnalyzer,\n\n container::{\n\n abc::*, paradigm::ParadigmId, Dictionary, HyphenAdverb, Initials, Lex, Score, Shaped,\n\n Unknown,\n\n },\n\n opencorpora::OpencorporaTagReg,\n\n};\n\n\n\nuse self::StackSource::*;\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum StackSource {\n\n Dictionary(Dictionary),\n\n HyphenAdverb(HyphenAdverb),\n\n Initials(Initials),\n\n Shaped(Shaped),\n\n Unknown(Unknown),\n", "file_path": "src/container/stack/source.rs", "rank": 63, "score": 70104.25847709869 }, { "content": " }\n\n }\n\n\n\n fn get_lemma(&self, morph: &MorphAnalyzer) -> Lex {\n\n match *self {\n\n Dictionary(ref source) => source.get_lemma(morph),\n\n HyphenAdverb(ref source) => source.get_lemma(morph),\n\n Initials(ref source) => source.get_lemma(morph),\n\n Shaped(ref source) => source.get_lemma(morph),\n\n Unknown(ref source) => source.get_lemma(morph),\n\n }\n\n }\n\n}\n\n\n\nimpl MorphySerde for StackSource {\n\n fn encode<W: fmt::Write>(&self, f: &mut W) -> fmt::Result {\n\n match *self {\n\n Dictionary(ref source) => source.encode(f),\n\n HyphenAdverb(ref source) => source.encode(f),\n\n Initials(ref source) => source.encode(f),\n", "file_path": "src/container/stack/source.rs", "rank": 64, "score": 70103.4157451014 }, { "content": " }\n\n }\n\n\n\n fn write_normal_form<W: fmt::Write>(&self, f: &mut W, morph: &MorphAnalyzer) -> fmt::Result {\n\n match *self {\n\n Dictionary(ref source) => source.write_normal_form(f, morph),\n\n HyphenAdverb(ref source) => source.write_normal_form(f, morph),\n\n Initials(ref source) => source.write_normal_form(f, morph),\n\n Shaped(ref source) => source.write_normal_form(f, morph),\n\n Unknown(ref source) => source.write_normal_form(f, morph),\n\n }\n\n }\n\n\n\n fn get_lexeme(&self, morph: &MorphAnalyzer) -> Vec<Lex> {\n\n match *self {\n\n Dictionary(ref source) => source.get_lexeme(morph),\n\n HyphenAdverb(ref source) => source.get_lexeme(morph),\n\n Initials(ref source) => source.get_lexeme(morph),\n\n Shaped(ref source) => source.get_lexeme(morph),\n\n Unknown(ref source) => source.get_lexeme(morph),\n", "file_path": "src/container/stack/source.rs", "rank": 65, "score": 70101.90482568952 }, { "content": " Shaped(ref source) => source.encode(f),\n\n Unknown(ref source) => source.encode(f),\n\n }\n\n }\n\n\n\n fn decode(s: &str) -> Result<(&str, Self), DecodeError> {\n\n Ok(match try_decode::<Dictionary>(s)? {\n\n Some(v) => v,\n\n None => match try_decode::<HyphenAdverb>(s)? {\n\n Some(v) => v,\n\n None => match try_decode::<Initials>(s)? {\n\n Some(v) => v,\n\n None => match try_decode::<Shaped>(s)? {\n\n Some(v) => v,\n\n None => match try_decode::<Unknown>(s)? {\n\n Some(v) => v,\n\n None => Err(DecodeError::UnknownPartType)?,\n\n },\n\n },\n\n },\n\n },\n\n })\n\n }\n\n}\n\n\n", "file_path": "src/container/stack/source.rs", "rank": 66, "score": 70100.7240351882 }, { "content": " Unknown(source) => Some(source),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn iter_lexeme<'s: 'i, 'm: 'i, 'i>(\n\n &'s self,\n\n morph: &'m MorphAnalyzer,\n\n ) -> Box<dyn Iterator<Item = Lex> + 'i> {\n\n match self {\n\n Dictionary(source) => Box::new(source.iter_lexeme(morph)),\n\n HyphenAdverb(source) => Box::new(source.iter_lexeme(morph)),\n\n Initials(source) => Box::new(source.iter_lexeme(morph)),\n\n Shaped(source) => Box::new(source.iter_lexeme(morph)),\n\n Unknown(source) => Box::new(source.iter_lexeme(morph)),\n\n }\n\n }\n\n\n\n pub fn title_rus(&self) -> &'static str {\n\n match self {\n", "file_path": "src/container/stack/source.rs", "rank": 67, "score": 70098.04559266729 }, { "content": " }\n\n }\n\n\n\n fn try_get_para_id(&self) -> Option<ParadigmId> {\n\n match *self {\n\n Dictionary(ref source) => source.try_get_para_id(),\n\n HyphenAdverb(ref source) => source.try_get_para_id(),\n\n Initials(ref source) => source.try_get_para_id(),\n\n Shaped(ref source) => source.try_get_para_id(),\n\n Unknown(ref source) => source.try_get_para_id(),\n\n }\n\n }\n\n\n\n fn write_word<W: fmt::Write>(&self, f: &mut W) -> fmt::Result {\n\n match *self {\n\n Dictionary(ref source) => source.write_word(f),\n\n HyphenAdverb(ref source) => source.write_word(f),\n\n Initials(ref source) => source.write_word(f),\n\n Shaped(ref source) => source.write_word(f),\n\n Unknown(ref source) => source.write_word(f),\n", "file_path": "src/container/stack/source.rs", "rank": 68, "score": 70096.86803757095 }, { "content": " _ => None,\n\n }\n\n }\n\n\n\n pub fn as_initials(&self) -> Option<&Initials> {\n\n match self {\n\n Initials(source) => Some(source),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn as_shaped(&self) -> Option<&Shaped> {\n\n match self {\n\n Shaped(source) => Some(source),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn as_unknown(&self) -> Option<&Unknown> {\n\n match self {\n", "file_path": "src/container/stack/source.rs", "rank": 69, "score": 70096.15552358757 }, { "content": "}\n\n\n\nimpl StackSource {\n\n pub fn new<T>(source: T) -> Self\n\n where\n\n T: Into<StackSource>,\n\n {\n\n source.into()\n\n }\n\n\n\n pub fn as_dictionary(&self) -> Option<&Dictionary> {\n\n match self {\n\n Dictionary(source) => Some(source),\n\n _ => None,\n\n }\n\n }\n\n\n\n pub fn as_hyphen_adverb(&self) -> Option<&HyphenAdverb> {\n\n match self {\n\n HyphenAdverb(source) => Some(source),\n", "file_path": "src/container/stack/source.rs", "rank": 70, "score": 70095.07552402095 }, { "content": "}\n\n\n\nimpl Source for StackSource {\n\n fn score(&self) -> Score {\n\n match *self {\n\n Dictionary(ref source) => source.score(),\n\n HyphenAdverb(ref source) => source.score(),\n\n Initials(ref source) => source.score(),\n\n Shaped(ref source) => source.score(),\n\n Unknown(ref source) => source.score(),\n\n }\n\n }\n\n\n\n fn is_lemma(&self) -> bool {\n\n match *self {\n\n Dictionary(ref source) => source.is_lemma(),\n\n HyphenAdverb(ref source) => source.is_lemma(),\n\n Initials(ref source) => source.is_lemma(),\n\n Shaped(ref source) => source.is_lemma(),\n\n Unknown(ref source) => source.is_lemma(),\n", "file_path": "src/container/stack/source.rs", "rank": 71, "score": 70094.66192086317 }, { "content": " Dictionary(dict_source) => match dict_source.word_lower().is_known() {\n\n true => \"Словарное слово\",\n\n false => \"Неизвестное слово\",\n\n },\n\n HyphenAdverb(_) => \"Наречие с дефисом\",\n\n Initials(_) => \"Инициал\",\n\n Shaped(_) => \"Не слово\",\n\n Unknown(_) => \"Неизвестное слово\",\n\n }\n\n }\n\n}\n\n\n\nimpl From<Dictionary> for StackSource {\n\n fn from(source: Dictionary) -> Self {\n\n Dictionary(source)\n\n }\n\n}\n\n\n\nimpl From<HyphenAdverb> for StackSource {\n\n fn from(source: HyphenAdverb) -> Self {\n", "file_path": "src/container/stack/source.rs", "rank": 72, "score": 70092.01056438652 }, { "content": " HyphenAdverb(source)\n\n }\n\n}\n\n\n\nimpl From<Initials> for StackSource {\n\n fn from(source: Initials) -> Self {\n\n Initials(source)\n\n }\n\n}\n\n\n\nimpl From<Shaped> for StackSource {\n\n fn from(source: Shaped) -> Self {\n\n Shaped(source)\n\n }\n\n}\n\n\n\nimpl From<Unknown> for StackSource {\n\n fn from(source: Unknown) -> Self {\n\n Unknown(source)\n\n }\n", "file_path": "src/container/stack/source.rs", "rank": 73, "score": 70091.98922968905 }, { "content": " }\n\n }\n\n\n\n fn get_normal_form(&self, morph: &MorphAnalyzer) -> Cow<str> {\n\n match *self {\n\n Dictionary(ref source) => source.get_normal_form(morph),\n\n HyphenAdverb(ref source) => source.get_normal_form(morph),\n\n Initials(ref source) => source.get_normal_form(morph),\n\n Shaped(ref source) => source.get_normal_form(morph),\n\n Unknown(ref source) => source.get_normal_form(morph),\n\n }\n\n }\n\n\n\n fn get_tag<'m>(&self, morph: &'m MorphAnalyzer) -> &'m OpencorporaTagReg {\n\n match *self {\n\n Dictionary(ref source) => source.get_tag(morph),\n\n HyphenAdverb(ref source) => source.get_tag(morph),\n\n Initials(ref source) => source.get_tag(morph),\n\n Shaped(ref source) => source.get_tag(morph),\n\n Unknown(ref source) => source.get_tag(morph),\n", "file_path": "src/container/stack/source.rs", "rank": 74, "score": 70090.87224615864 }, { "content": " }\n\n }\n\n\n\n fn is_known(&self) -> bool {\n\n match *self {\n\n Dictionary(ref source) => source.is_known(),\n\n HyphenAdverb(ref source) => source.is_known(),\n\n Initials(ref source) => source.is_known(),\n\n Shaped(ref source) => source.is_known(),\n\n Unknown(ref source) => source.is_known(),\n\n }\n\n }\n\n\n\n fn get_word(&self) -> Cow<str> {\n\n match *self {\n\n Dictionary(ref source) => source.get_word(),\n\n HyphenAdverb(ref source) => source.get_word(),\n\n Initials(ref source) => source.get_word(),\n\n Shaped(ref source) => source.get_word(),\n\n Unknown(ref source) => source.get_word(),\n", "file_path": "src/container/stack/source.rs", "rank": 75, "score": 70089.88040586398 }, { "content": "use std::{\n\n num::{ParseFloatError, ParseIntError},\n\n str::FromStr,\n\n};\n\n\n\nuse num::Num;\n\n\n\nuse crate::container::decode::error::DecodeError;\n\n\n", "file_path": "src/container/decode/map.rs", "rank": 76, "score": 69786.72787094173 }, { "content": "use std::num::{ParseFloatError, ParseIntError};\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum DecodeError {\n\n /// A decoder expects more\n\n UnexpectedEnd,\n\n /// An unexpected type code reached\n\n UnknownPartType,\n\n /// An input doesnt match the current pattern\n\n DoesntMatch,\n\n /// The number decoder failed to parse an integer\n\n ParseIntError(ParseIntError),\n\n /// The number decoder failed to parse a float\n\n ParseFloatError(ParseFloatError),\n\n}\n\n\n\nimpl From<ParseIntError> for DecodeError {\n\n fn from(e: ParseIntError) -> Self {\n\n DecodeError::ParseIntError(e)\n\n }\n\n}\n\n\n\nimpl From<ParseFloatError> for DecodeError {\n\n fn from(e: ParseFloatError) -> Self {\n\n DecodeError::ParseFloatError(e)\n\n }\n\n}\n", "file_path": "src/container/decode/error.rs", "rank": 77, "score": 69785.73707646254 }, { "content": "use crate::container::decode::error::DecodeError;\n\n\n", "file_path": "src/container/decode/follow.rs", "rank": 78, "score": 69783.94159548679 }, { "content": "use crate::container::decode::error::DecodeError;\n\n\n", "file_path": "src/container/decode/take.rs", "rank": 79, "score": 69783.94159548679 }, { "content": "pub mod error;\n\npub mod follow;\n\npub mod map;\n\npub mod predicate;\n\npub mod take;\n\n\n\npub use self::{follow::*, map::*, predicate::*, take::*};\n\n\n\n/**\n\n```\n\nuse rsmorphy::container::decode::escape;\n\n\n\nassert_eq!(escape(r\"a,b\").collect::<String>(), String::from(r\"a\\,b\"));\n\nassert_eq!(escape(r\"a;b\").collect::<String>(), String::from(r\"a\\;b\"));\n\nassert_eq!(escape(r\"a:b\").collect::<String>(), String::from(r\"a\\:b\"));\n\nassert_eq!(escape(r\"a\\b\").collect::<String>(), String::from(r\"a\\\\b\"));\n\n```\n\n*/\n", "file_path": "src/container/decode/mod.rs", "rank": 80, "score": 69780.15619178789 }, { "content": "struct PathLoader {\n\n dict_path: PathBuf,\n\n}\n\n\n\nimpl PathLoader {\n\n fn new<P>(p: P) -> Self\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let dict_path = p.as_ref().into();\n\n PathLoader { dict_path }\n\n }\n\n\n\n fn path<S>(&self, name: S) -> PathBuf\n\n where\n\n S: AsRef<Path>,\n\n {\n\n self.dict_path.join(name)\n\n }\n\n\n", "file_path": "src/opencorpora/dictionary.rs", "rank": 81, "score": 61004.7736658599 }, { "content": "fn main() {\n\n let mut f = File::create(\"src/release.rs\").expect(\"Can't create a file\");\n\n\n\n let res = Command::new(\"rustc\")\n\n .arg(\"--version\")\n\n .output()\n\n .expect(\"Can't get rustc version\");\n\n\n\n let version = from_utf8(&res.stdout).expect(\"Can't convert from utf-8\");\n\n\n\n writeln!(f, r\"pub static RUSTC_VERSION: &str = {:?};\", version).expect(\"Can't write to a file\");\n\n}\n", "file_path": "build.rs", "rank": 82, "score": 50469.88565488031 }, { "content": "pub trait DawgValue {\n\n fn new_in_place<F>(f: F) -> Self\n\n where\n\n F: FnOnce(&mut [u8]);\n\n}\n\n\n\n#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]\n\npub struct HH(pub u16, pub u16);\n\n\n\n#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]\n\npub struct HHH(pub u16, pub u16, pub u16);\n\n\n\nimpl DawgValue for HH {\n\n #[inline(always)]\n\n fn new_in_place<F>(f: F) -> Self\n\n where\n\n F: FnOnce(&mut [u8]),\n\n {\n\n let mut buf = [0_u8; 4];\n\n f(&mut buf);\n", "file_path": "src/dawg/value.rs", "rank": 83, "score": 50369.27476689384 }, { "content": "pub trait AnalyzerUnit {\n\n fn parse(\n\n &self,\n\n morph: &MorphAnalyzer,\n\n result: &mut ParseResult,\n\n word: &str,\n\n word_lower: &str,\n\n seen_parses: &mut SeenSet,\n\n );\n\n}\n", "file_path": "src/analyzer/units/abc.rs", "rank": 84, "score": 49414.16214875397 }, { "content": "fn main() {\n\n let morph_ru = MorphAnalyzer::from_file(dict_ru::DICT_PATH);\n\n\n\n //let lex = Lex::from_id(&morph_ru, \"ru:d:стали,388,4\").unwrap();\n\n //print_row_lex(&morph_ru, 0, &lex.inflect(&morph_ru, &GrammemeSet::from_str(\"plur,ablt\")).unwrap());\n\n //print_row_lex(&morph_ru, 1, &lex.inflect(&morph_ru, &GrammemeSet::from_str(\"femn,sing,ablt,V-ey\")).unwrap());\n\n //println!();\n\n\n\n let apple = Lex::from_id(&morph_ru, \"ru:d:яблоко,22c\").unwrap();\n\n let bread = Lex::from_id(&morph_ru, \"ru:d:хлеб,878\").unwrap();\n\n // let fish = Lex::from_id(&morph_ru, \"ru:d:рыба,35\").unwrap();\n\n\n\n let ablt_set = GrammemeSet::new(\"ablt\");\n\n\n\n println!(\n\n \" ::: {} {} + {} {} = {} {}\",\n\n 1,\n\n apple.get_plural(&morph_ru, 1).unwrap(),\n\n 4,\n\n apple.get_plural(&morph_ru, 4).unwrap(),\n", "file_path": "examples/inflect.rs", "rank": 85, "score": 49259.59245885738 }, { "content": "fn main() {\n\n let morph_ru = MorphAnalyzer::from_file(dict_ru::DICT_PATH);\n\n\n\n input_loop(|word| table(&morph_ru, word))\n\n}\n", "file_path": "examples/parse.rs", "rank": 86, "score": 49259.59245885738 }, { "content": "fn main() {\n\n let morph_ru = MorphAnalyzer::from_file(dict_ru::DICT_PATH);\n\n\n\n input_loop(|word| list(&morph_ru, word));\n\n}\n", "file_path": "examples/lexeme.rs", "rank": 87, "score": 49259.59245885738 }, { "content": "fn main() {\n\n let morph_ru = MorphAnalyzer::from_file(dict_ru::DICT_PATH);\n\n\n\n // table(&morph_ru, \"яблоко\");\n\n // table(&morph_ru, \"хлеб\");\n\n // table(&morph_ru, \"рыба\");\n\n // table(&morph_ru, \"стали\");\n\n table(&morph_ru, \"того\");\n\n // table(&morph_ru, \"И\");\n\n // table(&morph_ru, \"БГ\");\n\n // table(&morph_ru, \"БГ-с\");\n\n // table(&morph_ru, \"смотри-ка\");\n\n // table(&morph_ru, \"человек-пароход\");\n\n // table(&morph_ru, \"интернет-магазин\");\n\n // table(&morph_ru, \"по-русски\");\n\n // table(&morph_ru, \"по-западному\");\n\n // table(&morph_ru, \"псевдокошку\");\n\n // table(&morph_ru, \"байткод\");\n\n // table(&morph_ru, \"бутявкать\");\n\n // table(&morph_ru, \"бутявкает\");\n", "file_path": "examples/enc-dec.rs", "rank": 88, "score": 48123.68583820245 }, { "content": "fn main() -> io::Result<()> {\n\n let dict_path = Path::new(\"./data\").canonicalize()?;\n\n\n\n let mut f = File::create(\"src/release.rs\")\n\n .expect(\"Can't create a file\");\n\n\n\n let res = Command::new(\"rustc\")\n\n .arg(\"--version\")\n\n .output()\n\n .expect(\"Can't get rustc version\");\n\n\n\n let version = from_utf8(&res.stdout)\n\n .expect(\"Can't convert from utf-8\");\n\n\n\n writeln!(f, r\"pub static RUSTC_VERSION: &str = {:?};\", version)\n\n .expect(\"Can't write to a file\");\n\n\n\n writeln!(f, r\"pub const DICT_PATH: &str = {:?};\", dict_path)\n\n .expect(\"Can't write to a file\");\n\n\n\n Ok(())\n\n}\n", "file_path": "dict/uk/build.rs", "rank": 89, "score": 44181.22766739459 }, { "content": "fn main() -> io::Result<()> {\n\n let dict_path = Path::new(\"./data\").canonicalize()?;\n\n\n\n let mut f = File::create(\"src/release.rs\")\n\n .expect(\"Can't create a file\");\n\n\n\n writeln!(f, r\"pub const DICT_PATH: &str = {:?};\", dict_path)?;\n\n\n\n Ok(())\n\n}\n", "file_path": "dict/ru/build.rs", "rank": 90, "score": 44181.22766739459 }, { "content": "use std::path::Path;\n\n\n\nuse crate::{\n\n analyzer::units::*,\n\n container::{ParseResult, SeenSet},\n\n estimator::SingleTagProbabilityEstimator,\n\n opencorpora::dictionary::Dictionary,\n\n};\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct Units {\n\n pub dictionary: DictionaryAnalyzer,\n\n pub initials: InitialsAnalyzer,\n\n pub latin: LatinAnalyzer,\n\n pub number: NumberAnalyzer,\n\n pub roman: RomanAnalyzer,\n\n pub punct: PunctuationAnalyzer,\n\n pub ha: HyphenAdverbAnalyzer,\n\n pub hsp: HyphenSeparatedParticleAnalyzer,\n\n pub hword: HyphenatedWordsAnalyzer,\n", "file_path": "src/analyzer/morph.rs", "rank": 91, "score": 37689.9115859997 }, { "content": " estimator,\n\n units,\n\n }\n\n }\n\n\n\n /// Loads `Dictionary` from disk and creates `MorphAnalyzer`\n\n pub fn from_file<P>(p: P) -> Self\n\n where\n\n P: AsRef<Path>,\n\n {\n\n let dict = Dictionary::from_file(p);\n\n // TODO consider move into dict?\n\n // char_substitutes = dictionary.words.compile_replaces(char_substitutes or {})\n\n MorphAnalyzer::new(dict)\n\n }\n\n\n\n /// Analyze the word and return a list of `Parsed`:\n\n pub fn parse(&self, word: &str) -> ParseResult {\n\n let word_lower = word.to_lowercase();\n\n\n", "file_path": "src/analyzer/morph.rs", "rank": 92, "score": 37688.3108138532 }, { "content": " pub kp: KnownPrefixAnalyzer,\n\n pub ks: KnownSuffixAnalyzer,\n\n pub up: UnknownPrefixAnalyzer,\n\n pub unknown: UnknownAnalyzer,\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub struct MorphAnalyzer {\n\n pub dict: Dictionary,\n\n pub estimator: SingleTagProbabilityEstimator,\n\n pub units: Units,\n\n}\n\n\n\nimpl MorphAnalyzer {\n\n /// Creates `MorphAnalyzer` with preloaded dict\n\n pub fn new(dict: Dictionary) -> Self {\n\n let estimator = SingleTagProbabilityEstimator {};\n\n let units = Units::default();\n\n MorphAnalyzer {\n\n dict,\n", "file_path": "src/analyzer/morph.rs", "rank": 93, "score": 37687.91498048578 }, { "content": " let mut result = look_over();\n\n self.estimator\n\n .apply_to_parses(self, word, &word_lower, &mut result);\n\n result\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use env_logger;\n\n\n\n use crate::MorphAnalyzer;\n\n\n\n lazy_static::lazy_static! {\n\n static ref RU: MorphAnalyzer = MorphAnalyzer::from_file(dict_ru::DICT_PATH);\n\n }\n\n\n\n #[test]\n\n fn load_ru() {\n\n env_logger::init();\n", "file_path": "src/analyzer/morph.rs", "rank": 94, "score": 37686.36395688616 }, { "content": " let look_over = || -> ParseResult {\n\n let mut result = ParseResult::new();\n\n let mut seen = SeenSet::default();\n\n\n\n macro_rules! look_in (\n\n ($t: ident) => {{\n\n self.units.$t.parse(self, &mut result, word, &word_lower, &mut seen);\n\n }};\n\n ($t: ident, return) => {{\n\n self.units.$t.parse(self, &mut result, word, &word_lower, &mut seen);\n\n if !result.is_empty() { return result };\n\n }}\n\n );\n\n\n\n look_in!(dictionary);\n\n look_in!(initials, return);\n\n\n\n look_in!(number, return);\n\n\n\n look_in!(punct, return);\n", "file_path": "src/analyzer/morph.rs", "rank": 95, "score": 37680.37241002042 }, { "content": " let _ = RU.dict;\n\n }\n\n\n\n #[test]\n\n fn parse() {\n\n assert_eq!(RU.parse(\"минимальный\").len(), 2);\n\n assert_eq!(RU.parse(\"менимальный\").len(), 3);\n\n }\n\n\n\n #[test]\n\n fn parse_one_letter() {\n\n assert_eq!(RU.parse(\"с\").len(), 25);\n\n }\n\n\n\n #[test]\n\n fn parse_one_letter_and_dot() {\n\n assert_eq!(RU.parse(\"м.\").len(), 1);\n\n }\n\n\n\n #[test]\n", "file_path": "src/analyzer/morph.rs", "rank": 96, "score": 37677.19362342934 }, { "content": "\n\n look_in!(roman);\n\n look_in!(latin, return);\n\n\n\n look_in!(hsp, return);\n\n\n\n look_in!(ha, return);\n\n\n\n look_in!(hword, return);\n\n\n\n look_in!(kp, return);\n\n\n\n look_in!(up);\n\n look_in!(ks, return);\n\n\n\n look_in!(unknown, return);\n\n\n\n unreachable!();\n\n };\n\n\n", "file_path": "src/analyzer/morph.rs", "rank": 97, "score": 37676.80038467985 }, { "content": " fn parse_unknown_two_letter() {\n\n assert_eq!(RU.parse(\"ТМ\").len(), 1);\n\n assert_eq!(RU.parse(\"КТ\").len(), 1);\n\n assert_eq!(RU.parse(\"1С\").len(), 1);\n\n }\n\n\n\n #[test]\n\n fn parse_dash() {\n\n assert_eq!(RU.parse(\"Р-ка\").len(), 1);\n\n assert_eq!(RU.parse(\"з-то\").len(), 1);\n\n }\n\n}\n", "file_path": "src/analyzer/morph.rs", "rank": 98, "score": 37676.30721110563 }, { "content": "\n\nimpl Number {\n\n pub fn try_from_str<S>(s: S) -> Option<Self>\n\n where\n\n S: AsRef<str>,\n\n {\n\n use self::Number::*;\n\n TAG_RE\n\n .captures_iter(s.as_ref())\n\n .next()\n\n .and_then(|cap| match &cap[1] {\n\n \"sing\" => Some(Sing),\n\n \"plur\" => Some(Plur),\n\n _ => None,\n\n })\n\n }\n\n\n\n pub fn to_grammeme(self) -> Grammeme {\n\n use self::Number::*;\n\n match self {\n", "file_path": "src/opencorpora/kind/number.rs", "rank": 99, "score": 36094.2681037541 } ]
Rust
tests/unit_test.rs
ShadowPower/shadow-music-cloud
719b0e3aa59126efdf54020213b629e1e7072452
use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use anyhow::Result; use radix_fmt::radix; use rayon::prelude::*; use shadow_music_cloud::repository::file_info; use shadow_music_cloud::{ action, command::actor::act, infra::transcoder, model::dto::FileInfo, }; use shadow_music_cloud::{ command::{ action::{Action, ContextData}, command::Command, }, config::app_config, infra::{file_utils, hash_utils}, }; struct WriteValueCommand; impl Command for WriteValueCommand { fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> { println!("execute TestCommand"); std::thread::sleep(std::time::Duration::from_millis(1000)); context.insert( "data", ContextData::String("string from another command".to_string()), ); Ok(()) } } struct ReadValueCommand; impl Command for ReadValueCommand { fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> { match context.get("data") { Some(ContextData::String(s)) => println!("{}", s), _ => println!("no value"), } Ok(()) } } #[test] fn test_action() { let test_action = action![WriteValueCommand, ReadValueCommand]; act(test_action); std::thread::sleep(std::time::Duration::from_millis(1000)); } #[test] fn test_file_hash() { let audio_file_info_list = file_utils::list_audio_file(); for audio_file_info in audio_file_info_list { let hash = hash_utils::hash_media_file_info(&audio_file_info); println!("{}", base62::encode(hash)); println!("{}", radix(hash, 36)); } } #[test] fn test_audio_hash() -> Result<()> { let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let mut path = PathBuf::new(); path.push(Path::new(app_config::AUDIO_PATH)); path.push(audio_file_info.path.clone()); println!("{}", audio_file_info.path.display()); match hash_utils::hash_audio_data(&path) { Ok(hash) => println!("{}", base62::encode(hash)), Err(e) => println!("{}", e), } }); Ok(()) } #[test] fn test_audio_transcode() -> Result<()> { ffmpeg_next::util::log::set_level(ffmpeg_next::util::log::Level::Error); let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let path = PathBuf::from(app_config::AUDIO_PATH).join(&audio_file_info.path); let transcoder = transcoder::Transcoder { output_filter_spec: None, codec: Some("libopus".to_string()), channels: Some(2), sample_rate: Some(48000), bit_rate: Some(96000), max_bit_rate: Some(320000), }; let mut output_path = PathBuf::new(); output_path.push(Path::new(app_config::OTHER_AUDIO_QUALITY_PATH)); let mut output_file_path = audio_file_info.path.clone(); output_file_path.set_extension("opus"); output_path.push(output_file_path); fs::create_dir_all(&output_path.parent().unwrap()).unwrap(); let start = std::time::SystemTime::now(); transcoder.transcode(&path, &output_path).unwrap(); let end = std::time::SystemTime::now(); println!("{}, {}", end.duration_since(start).unwrap().as_secs(), audio_file_info.path.display()); }); Ok(()) } #[test] fn test_storage() { let test_data = FileInfo { path: ["test", "test2"] .into_iter() .map(|s| s.to_string()) .collect(), file_type: "audio".to_string(), size: 1000, last_modified: 2000, file_info_hash: "TestData".to_string(), cue_media_path: None, cue_media_file_info_hash: None, cover_hash: Some("TestData".to_string()), medias: vec![], }; file_info::set(&"TestData".to_string(), &test_data); let data_from_storage = file_info::get(&"TestData".to_string()).unwrap(); println!("{:?}", data_from_storage); } #[test] fn test_media_info() { let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { println!("{:?} \n", FileInfo::from_simple(audio_file_info)); }); }
use std::{ collections::HashMap, fs, path::{Path, PathBuf}, }; use anyhow::Result; use radix_fmt::radix; use rayon::prelude::*; use shadow_music_cloud::repository::file_info; use shadow_music_cloud::{ action, command::actor::act, infra::transcoder, model::dto::FileInfo, }; use shadow_music_cloud::{ command::{ action::{Action, ContextData}, command::Command, }, config::app_config, infra::{file_utils, hash_utils}, }; struct WriteValueCommand; impl Command for WriteValueCommand { fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> { println!("execute TestCommand"); std::thread::sleep(std::time::Duration::from_millis(1000)); context.insert( "data", ContextData::String("string from another command".to_string()), ); Ok(()) } } struct ReadValueCommand; impl Command for ReadValueCommand { fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> { match context.get("data") { Some(ContextData::String(s)) => println!("{}", s), _ => println!("no value"), } Ok(()) } } #[test] fn test_action() { let test_action = action![WriteValueCommand, ReadValueCommand]; act(test_action); std::thread::sleep(std::time::Duration::from_millis(1000)); } #[test] fn test_file_hash() { let audio_file_info_list = file_utils::list_audio_file(); for audio_file_info in audio_file_info_list { let hash = hash_utils::hash_media_file_info(&audi
tils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let path = PathBuf::from(app_config::AUDIO_PATH).join(&audio_file_info.path); let transcoder = transcoder::Transcoder { output_filter_spec: None, codec: Some("libopus".to_string()), channels: Some(2), sample_rate: Some(48000), bit_rate: Some(96000), max_bit_rate: Some(320000), }; let mut output_path = PathBuf::new(); output_path.push(Path::new(app_config::OTHER_AUDIO_QUALITY_PATH)); let mut output_file_path = audio_file_info.path.clone(); output_file_path.set_extension("opus"); output_path.push(output_file_path); fs::create_dir_all(&output_path.parent().unwrap()).unwrap(); let start = std::time::SystemTime::now(); transcoder.transcode(&path, &output_path).unwrap(); let end = std::time::SystemTime::now(); println!("{}, {}", end.duration_since(start).unwrap().as_secs(), audio_file_info.path.display()); }); Ok(()) } #[test] fn test_storage() { let test_data = FileInfo { path: ["test", "test2"] .into_iter() .map(|s| s.to_string()) .collect(), file_type: "audio".to_string(), size: 1000, last_modified: 2000, file_info_hash: "TestData".to_string(), cue_media_path: None, cue_media_file_info_hash: None, cover_hash: Some("TestData".to_string()), medias: vec![], }; file_info::set(&"TestData".to_string(), &test_data); let data_from_storage = file_info::get(&"TestData".to_string()).unwrap(); println!("{:?}", data_from_storage); } #[test] fn test_media_info() { let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { println!("{:?} \n", FileInfo::from_simple(audio_file_info)); }); }
o_file_info); println!("{}", base62::encode(hash)); println!("{}", radix(hash, 36)); } } #[test] fn test_audio_hash() -> Result<()> { let audio_file_info_list = file_utils::list_audio_file(); audio_file_info_list.par_iter().for_each(|audio_file_info| { let mut path = PathBuf::new(); path.push(Path::new(app_config::AUDIO_PATH)); path.push(audio_file_info.path.clone()); println!("{}", audio_file_info.path.display()); match hash_utils::hash_audio_data(&path) { Ok(hash) => println!("{}", base62::encode(hash)), Err(e) => println!("{}", e), } }); Ok(()) } #[test] fn test_audio_transcode() -> Result<()> { ffmpeg_next::util::log::set_level(ffmpeg_next::util::log::Level::Error); let audio_file_info_list = file_u
random
[ { "content": "/// 计算 Hash 值\n\nfn hash(f: &dyn Fn(&mut Xxh3)) -> u128 {\n\n let mut hasher = Xxh3::with_seed(HASH_SEED);\n\n f(&mut hasher);\n\n hasher.digest128()\n\n}\n\n\n", "file_path": "src/infra/hash_utils.rs", "rank": 3, "score": 111744.02618786754 }, { "content": "/// 计算媒体文件音频数据的 Hash 值\n\n/// @param file_path 媒体文件路径\n\n/// @return 音频数据 Hash 值\n\npub fn hash_audio_data(file_path: &PathBuf) -> Result<u128> {\n\n let mut hasher = Xxh3::with_seed(HASH_SEED);\n\n let mut input_ctx = format::input(file_path)?;\n\n if let Some(audio_stream_index) = get_best_audio_stream_index(&input_ctx) {\n\n for (stream, packet) in input_ctx.packets() {\n\n if stream.index() == audio_stream_index {\n\n match packet.data() {\n\n Some(data) => {\n\n hasher.write(data);\n\n },\n\n _ => {}\n\n }\n\n }\n\n }\n\n } else {\n\n return Err(anyhow!(\"No audio stream found\"));\n\n }\n\n Ok(hasher.digest128())\n\n}\n\n\n", "file_path": "src/infra/hash_utils.rs", "rank": 5, "score": 110746.70727409437 }, { "content": "/// 执行动作\n\n/// @param action 动作\n\npub fn act(action: Box<Action>) {\n\n let mut actor = GLOBAL_ACTOR.lock().unwrap();\n\n match actor.add_action(action) {\n\n Ok(_) => {},\n\n Err(error) => {\n\n println!(\"{}\", error);\n\n }\n\n }\n\n}", "file_path": "src/command/actor.rs", "rank": 7, "score": 99443.68381836911 }, { "content": "/// 计算数据的 Hash 值\n\n/// @param data 数据\n\n/// @return Hash 值\n\npub fn hash_data(data: &[u8]) -> u128 {\n\n let mut hasher = Xxh3::with_seed(HASH_SEED);\n\n hasher.write(data);\n\n hasher.digest128()\n\n}", "file_path": "src/infra/hash_utils.rs", "rank": 8, "score": 96361.90499198945 }, { "content": "/// 计算文件的 Hash 值\n\n/// @param file_path 文件路径\n\n/// @return Hash 值\n\npub fn hash_file(file_path: &PathBuf) -> Result<u128> {\n\n let mut hasher = Xxh3::with_seed(HASH_SEED);\n\n let mut file = std::fs::File::open(file_path)?;\n\n let mut buffer = [0u8; 256];\n\n loop {\n\n let read_size = file.read(&mut buffer)?;\n\n if read_size == 0 {\n\n break;\n\n }\n\n hasher.write(&buffer[0..read_size]);\n\n }\n\n Ok(hasher.digest128())\n\n}\n\n\n", "file_path": "src/infra/hash_utils.rs", "rank": 9, "score": 96019.74712688147 }, { "content": "/// 计算文件信息 Hash\n\nstruct CalcFileInfoHash;\n\nimpl Command for CalcFileInfoHash {\n\n fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> {\n\n if let ContextData::FileList(file_list) = context.get_mut(\"simple_file_list\").unwrap() {\n\n // 计算 Hash\n\n file_list.par_iter_mut().for_each(|file_info| {\n\n let hash = radix(hash_utils::hash_media_file_info(file_info), 36).to_string();\n\n file_info.file_info_hash = Some(hash);\n\n });\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/command/command.rs", "rank": 10, "score": 91843.94714114448 }, { "content": "/// 获取最佳音频流\n\n/// @param input_ctx 输入媒体文件上下文\n\n/// @return 最佳音频流\n\npub fn find_best_stream(input_ctx: &format::context::Input) -> Result<Stream> {\n\n input_ctx\n\n .streams()\n\n .best(media::Type::Audio)\n\n .with_context(|| \"Failed to find best stream\")\n\n}\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 12, "score": 81742.34955996338 }, { "content": "pub fn sync(data: &HashMap<String, FileInfo>) {\n\n // 删除\n\n for item in FILE_INFO_DB.iter() {\n\n let (file_info_hash, _) = item.unwrap();\n\n let file_info_hash = std::str::from_utf8(&file_info_hash).unwrap().to_string();\n\n if !data.contains_key(&file_info_hash) {\n\n remove(&file_info_hash);\n\n }\n\n }\n\n // 添加\n\n for item in data.iter() {\n\n let (file_info_hash, file_info) = item;\n\n if !FILE_INFO_DB.contains_key(file_info_hash).unwrap() {\n\n set(file_info_hash, file_info);\n\n }\n\n }\n\n}", "file_path": "src/repository/file_info.rs", "rank": 13, "score": 75856.16806463816 }, { "content": "/// 清理旧数据\n\nstruct CleanStorage;\n\nimpl Command for CleanStorage {\n\n fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> {\n\n if let ContextData::FileList(simple_file_list) = context.get(\"simple_file_list\").unwrap() {\n\n // 获取文件 Hash 集合\n\n let file_info_hash_set: HashSet<String> = simple_file_list.iter().map(|simple_file_info| {\n\n simple_file_info.file_info_hash.as_ref().unwrap().clone()\n\n }).collect();\n\n\n\n // 清理旧的文件信息\n\n let old_file_info_hash_set = file_info::list_key();\n\n old_file_info_hash_set.into_iter().for_each(|old_file_info_hash| {\n\n if file_info_hash_set.contains(&old_file_info_hash) {\n\n // 删除数据库中的文件信息\n\n file_info::remove(&old_file_info_hash);\n\n }\n\n });\n\n }\n\n \n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/command/command.rs", "rank": 14, "score": 75010.36390893527 }, { "content": "/// 生成详细的媒体信息并存储,同时提取专辑封面\n\nstruct GenerateStorage;\n\nimpl Command for GenerateStorage {\n\n fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> {\n\n if let ContextData::FileList(simple_file_list) = context.get(\"simple_file_list\").unwrap() {\n\n // 生成详细的文件信息\n\n let file_info_list: Vec<FileInfo> = simple_file_list.par_iter()\n\n .map(FileInfo::from_simple)\n\n .collect();\n\n\n\n context.insert(\"file_info\", ContextData::FileInfo(file_info_list));\n\n }\n\n Ok(())\n\n }\n\n}", "file_path": "src/command/command.rs", "rank": 15, "score": 75010.36390893527 }, { "content": "/// 扫描目录下的所有音频文件\n\nstruct ScanMediaFile;\n\nimpl Command for ScanMediaFile {\n\n fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()> {\n\n let audio_file_list = file_utils::list_audio_file();\n\n context.insert(\"simple_file_list\", ContextData::FileList(audio_file_list));\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/command/command.rs", "rank": 16, "score": 73126.34671653001 }, { "content": "/// 根据输出的文件路径猜测音频编码\n\n/// @param path 输出文件路径\n\n/// @param output_ctx 输出媒体文件上下文\n\n/// @return 音频编码\n\npub fn guess_codec_by_path<P: AsRef<Path>>(path: &P, output_ctx: &format::context::Output) -> Result<codec::Audio> {\n\n Ok(encoder::find(output_ctx.format().codec(path, media::Type::Audio))\n\n .with_context(|| \"Failed to find audio codec\")?\n\n .audio()?)\n\n}\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 19, "score": 65464.83954400475 }, { "content": "/// 根据名称创建音频编码\n\n/// @param name 音频编码库名称(例如: \"libopus\")\n\n/// @return 音频编码\n\npub fn create_codec_by_name(name: &str) -> Result<codec::Audio> {\n\n Ok(encoder::find_by_name(name)\n\n .with_context(|| format!(\"Failed to find {} codec\", name))?\n\n .audio()?)\n\n}\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 20, "score": 54944.041419758985 }, { "content": "/// 根据音频流创建音频解码器\n\n/// @param stream 音频流\n\n/// @return 音频解码器\n\npub fn create_decoder_by_stream(stream: Stream) -> Result<decoder::Audio> {\n\n let context = codec::context::Context::from_parameters(stream.parameters())?;\n\n let mut decoder = context.decoder().audio()?;\n\n decoder.set_parameters(stream.parameters())?;\n\n Ok(decoder)\n\n}\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 21, "score": 54944.041419758985 }, { "content": "/// 命令\n\n/// 一组命令组合成一个动作\n\n/// 动作中的命令会按顺序串行执行\n\n/// 多个命令之间可以共享内存\n\npub trait Command {\n\n /// 执行命令\n\n /// @param context 动作上下文\n\n fn execute(&self, context: &mut HashMap<&str, ContextData>) -> Result<()>;\n\n /// 失败时的回滚\n\n /// @param context 动作上下文\n\n fn rollback(&self, _context: &mut HashMap<&str, ContextData>) {\n\n // do nothing\n\n }\n\n}\n\n\n", "file_path": "src/command/command.rs", "rank": 22, "score": 54387.61879692502 }, { "content": "/// 获取最佳音频流索引\n\n/// @param input_ctx 输入媒体文件上下文\n\n/// @return 最佳音频流索引\n\npub fn get_best_audio_stream_index(input_ctx: &format::context::Input) -> Option<usize> {\n\n input_ctx.streams().best(media::Type::Audio).map(|stream| stream.index())\n\n}\n\n\n\n// ---- 用于转码 ----\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 23, "score": 51048.43672530609 }, { "content": " executed_command_stack.push(command);\n\n match command.execute(&mut action_context) {\n\n Err(err) => {\n\n println!(\"Error from command: {}\", err);\n\n // 倒过来执行回滚操作\n\n while let Some(command) = executed_command_stack.pop() {\n\n command.rollback(&mut action_context);\n\n }\n\n break;\n\n },\n\n _ => {}\n\n }\n\n }\n\n }\n\n}\n\n\n\n/// 将一组命令包装成动作\n\n/// \n\n/// 例子:\n\n/// ```\n", "file_path": "src/command/action.rs", "rank": 24, "score": 49810.74625831836 }, { "content": "impl Action {\n\n pub fn new() -> Action {\n\n Action {\n\n commands: Vec::new(),\n\n }\n\n }\n\n\n\n pub fn add_command(&mut self, command: Box<dyn Command + Send + Sync>) {\n\n self.commands.push(command);\n\n }\n\n\n\n pub fn add_commands(&mut self, commands: Vec<Box<dyn Command + Send + Sync>>) {\n\n self.commands.extend(commands);\n\n }\n\n\n\n pub fn execute(&self) {\n\n let mut action_context: HashMap<&str, ContextData> = HashMap::new();\n\n // 存放已经执行过的命令\n\n let mut executed_command_stack: Vec<&Box<dyn Command + Send + Sync>> = Vec::new();\n\n for command in self.commands.iter() {\n", "file_path": "src/command/action.rs", "rank": 25, "score": 49810.18871081685 }, { "content": "use std::collections::HashMap;\n\n\n\nuse crate::model::dto::{SimpleFileInfo, FileInfo};\n\n\n\nuse super::command::Command;\n\n\n\n#[derive(Debug)]\n\npub enum ContextData {\n\n String(String),\n\n FileList(Vec<SimpleFileInfo>),\n\n FileInfo(Vec<FileInfo>),\n\n}\n\n\n\n/// 动作\n\n/// 包含一组命令\n\n/// 可以并行执行不同动作\n\npub struct Action {\n\n commands: Vec<Box<dyn Command + Send + Sync>>,\n\n}\n\n\n", "file_path": "src/command/action.rs", "rank": 26, "score": 49808.11520295389 }, { "content": "/// action![DownloadCommand, OpenCommand, PlayCommand];\n\n/// ```\n\n#[macro_export]\n\nmacro_rules! action {\n\n ($($command:expr),*) => {\n\n {\n\n let mut action = Action::new();\n\n $(\n\n action.add_command(Box::new($command));\n\n )*\n\n Box::new(action)\n\n }\n\n };\n\n}", "file_path": "src/command/action.rs", "rank": 27, "score": 49805.44251908729 }, { "content": "/// 生成缩略图\n\n/// @param input 输入文件\n\n/// @param output 输出文件\n\npub fn convert_to_thumbnail<P: AsRef<Path>>(input: &P, output: &P) -> Result<()> {\n\n let img = image::open(input)?;\n\n let new_width = cmp::min(img.width(), 512);\n\n let new_heigth = cmp::min(img.height(), 512);\n\n \n\n let scaled = img.resize(new_width, new_heigth, FilterType::Triangle);\n\n fs::create_dir_all(output.as_ref().parent().unwrap())?;\n\n let mut output_file = fs::File::create(output)?;\n\n scaled.write_to(&mut output_file, ImageOutputFormat::Jpeg(80))?;\n\n Ok(())\n\n}", "file_path": "src/infra/image_utils.rs", "rank": 28, "score": 49473.55409146755 }, { "content": "/// 计算文件信息的 Hash 值\n\n/// @param file_info 文件信息\n\n/// @return Hash 值\n\npub fn hash_media_file_info(file_info: &SimpleFileInfo) -> u128 {\n\n // 简单处理不同平台的文件路径差异\n\n let origin_file_path = file_info.path.as_os_str().to_str().unwrap();\n\n let unify_file_path = origin_file_path.replace(\"\\\\\", \"/\");\n\n hash(&|hasher| {\n\n hasher.write(unify_file_path.as_bytes());\n\n hasher.write_u64(file_info.size);\n\n hasher.write_u128(file_info.last_modified);\n\n })\n\n}\n\n\n", "file_path": "src/infra/hash_utils.rs", "rank": 29, "score": 46988.356936253214 }, { "content": "/// 从媒体文件中获取标签\n\n/// @param file_path 媒体文件路径\n\n/// @return 标签\n\npub fn get_tags_from_media_file<P: AsRef<Path>>(file_path: &P) -> Result<lofty::Tag> {\n\n let tagged_file = lofty::Probe::open(file_path)?.read(true)?;\n\n\n\n let tag = tagged_file.primary_tag()\n\n .unwrap_or(tagged_file.first_tag().with_context(|| \"No tags found\")?);\n\n\n\n Ok(tag.clone())\n\n}\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 30, "score": 46896.72823662972 }, { "content": "/// 从媒体文件中获取属性\n\n/// @param file_path 媒体文件路径\n\n/// @return 属性\n\npub fn get_properties_from_media_file<P: AsRef<Path>>(file_path: &P) -> Result<lofty::FileProperties> {\n\n Ok(lofty::Probe::open(file_path)?.read(true)?.properties().clone())\n\n}", "file_path": "src/infra/audio_utils.rs", "rank": 31, "score": 46134.40696117762 }, { "content": "pub fn remove(file_info_hash: &String) {\n\n FILE_INFO_DB.remove(file_info_hash).unwrap();\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 32, "score": 45986.906578076145 }, { "content": "pub fn list_key() -> HashSet<String> {\n\n let mut file_infos: HashSet<String> = HashSet::new();\n\n for item in FILE_INFO_DB.iter() {\n\n let (key, _) = item.unwrap();\n\n file_infos.insert(String::from_utf8(key.to_vec()).unwrap());\n\n }\n\n file_infos\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 33, "score": 45986.906578076145 }, { "content": "pub fn list() -> HashMap<String, FileInfo> {\n\n let mut file_infos: HashMap<String, FileInfo> = HashMap::new();\n\n for item in FILE_INFO_DB.iter() {\n\n let (key, value) = item.unwrap();\n\n let file_info: FileInfo = serde_json::from_slice(&value).unwrap();\n\n file_infos.insert(String::from_utf8(key.to_vec()).unwrap(), file_info);\n\n }\n\n file_infos\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 34, "score": 43993.11823052533 }, { "content": "/// 字符串列表转路径\n\n/// @param list 字符串列表\n\n/// @returns 路径\n\npub fn list_to_path(list: &Vec<String>) -> PathBuf {\n\n list.iter().fold(PathBuf::new(), |mut path, e| {\n\n path.push(e);\n\n path\n\n })\n\n}", "file_path": "src/infra/file_utils.rs", "rank": 35, "score": 41275.25082815623 }, { "content": "/// 路径转字符串列表\n\n/// @param path 路径\n\n/// @returns 字符串列表\n\npub fn path_to_list(path: &PathBuf) -> Vec<String> {\n\n path.iter().map(|e| e.to_str().unwrap().to_string()).collect()\n\n}\n\n\n", "file_path": "src/infra/file_utils.rs", "rank": 36, "score": 41275.25082815623 }, { "content": "pub fn get(file_info_hash: &String) -> Option<FileInfo> {\n\n match FILE_INFO_DB.get(file_info_hash) {\n\n Ok(Some(value)) => {\n\n let file_info: FileInfo = serde_json::from_slice(&value).unwrap();\n\n Some(file_info)\n\n }, \n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 37, "score": 41075.09141750775 }, { "content": "pub fn set(file_info_hash: &String, file_info: &FileInfo) {\n\n let value = serde_json::to_vec(file_info).unwrap();\n\n FILE_INFO_DB.insert(file_info_hash, value).unwrap();\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 38, "score": 40044.53856844794 }, { "content": "pub fn clear() {\n\n FILE_INFO_DB.clear().unwrap();\n\n}\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 39, "score": 32632.697545770927 }, { "content": "pub fn filter(\n\n spec: &str,\n\n decoder: &codec::decoder::Audio,\n\n encoder: &codec::encoder::Audio,\n\n) -> Result<filter::Graph> {\n\n let mut filter = filter::Graph::new();\n\n\n\n let args = format!(\n\n \"time_base={}:sample_rate={}:sample_fmt={}:channel_layout=0x{:x}\",\n\n decoder.time_base(),\n\n decoder.rate(),\n\n decoder.format().name(),\n\n decoder.channel_layout().bits()\n\n );\n\n\n\n filter.add(&filter::find(\"abuffer\").unwrap(), \"in\", &args)?;\n\n filter.add(&filter::find(\"abuffersink\").unwrap(), \"out\", \"\")?;\n\n\n\n let mut out = filter.get(\"out\").unwrap();\n\n out.set_sample_format(encoder.format());\n", "file_path": "src/infra/audio_filter.rs", "rank": 40, "score": 32632.697545770927 }, { "content": "use anyhow::{Result, Ok};\n\nuse radix_fmt::radix;\n\nuse rayon::iter::{IntoParallelRefIterator, ParallelIterator, IntoParallelRefMutIterator};\n\nuse std::{collections::{HashMap, HashSet}, fs, path::PathBuf};\n\n\n\nuse crate::{\n\n infra::{file_utils, hash_utils},\n\n model::dto::FileInfo,\n\n repository::file_info, config::app_config,\n\n};\n\n\n\nuse super::action::ContextData;\n\n\n\n/// 命令\n\n/// 一组命令组合成一个动作\n\n/// 动作中的命令会按顺序串行执行\n\n/// 多个命令之间可以共享内存\n", "file_path": "src/command/command.rs", "rank": 42, "score": 31159.689112432865 }, { "content": "/// 创建编码器,并配置输出上下文\n\n/// @param codec 音频编码\n\n/// @param output_ctx 输出媒体文件上下文\n\n/// @param channels 通道数\n\n/// @param sample_rate 采样率\n\n/// @param bit_rate 码率\n\n/// @param max_bit_rate 最大码率\n\n/// @return 编码器,输出时间基\n\npub fn create_encoder_with_output_ctx(\n\n codec: codec::Audio,\n\n output_ctx: &mut format::context::Output,\n\n channels: i32,\n\n source_sample_rate: i32,\n\n target_sample_rate: i32,\n\n bit_rate: usize,\n\n max_bit_rate: usize,\n\n) -> Result<(encoder::Audio, ffmpeg::Rational)> {\n\n let global = output_ctx\n\n .format()\n\n .flags()\n\n .contains(format::flag::Flags::GLOBAL_HEADER);\n\n\n\n let mut output = output_ctx.add_stream(codec)?;\n\n let context = codec::context::Context::from_parameters(output.parameters())?;\n\n let mut encoder = context.encoder().audio()?;\n\n\n\n if global {\n\n encoder.set_flags(codec::flag::Flags::GLOBAL_HEADER);\n", "file_path": "src/infra/audio_utils.rs", "rank": 43, "score": 30297.47890309609 }, { "content": "/// 获取媒体目录下的所有音频文件信息\n\n/// @returns 音频文件信息列表\n\npub fn list_audio_file() -> Vec<SimpleFileInfo> {\n\n let mut audio_file_list: Vec<SimpleFileInfo> = Vec::new();\n\n let dir_map = WalkDir::new(app_config::AUDIO_PATH)\n\n .follow_links(true)\n\n .into_iter()\n\n .filter_map(|e| e.ok());\n\n for entry in dir_map {\n\n if entry.file_type().is_file() {\n\n if let Some(ext) = entry.path().extension() {\n\n let ext: &str = &ext.to_str().unwrap().to_lowercase();\n\n if AUDIO_EXTENSIONS.contains(ext) {\n\n audio_file_list.push(dir_entry_to_simple_file_info(&entry));\n\n }\n\n }\n\n }\n\n }\n\n audio_file_list\n\n}\n\n\n", "file_path": "src/infra/file_utils.rs", "rank": 44, "score": 26652.32475776915 }, { "content": "pub fn time_to_millis(time: &SystemTime) -> u128 {\n\n time.duration_since(UNIX_EPOCH).unwrap().as_millis()\n\n}", "file_path": "src/infra/time_utils.rs", "rank": 45, "score": 26500.59835021916 }, { "content": "/// 将 DirEntry 转换成文件信息结构体\n\n/// @param entry DirEntry\n\n/// @returns 文件信息结构体\n\nfn dir_entry_to_simple_file_info(dir_entry: &DirEntry) -> SimpleFileInfo {\n\n // 得到相对于媒体目录的路径,实际使用时需要拼接\n\n let path = dir_entry.path().strip_prefix(app_config::AUDIO_PATH).unwrap();\n\n let metadata = dir_entry.metadata().unwrap();\n\n let size = metadata.len();\n\n let last_modified = time_utils::time_to_millis(&metadata.modified().unwrap());\n\n SimpleFileInfo::new(path, size, last_modified)\n\n}\n\n \n", "file_path": "src/infra/file_utils.rs", "rank": 46, "score": 24721.607949864785 }, { "content": " pub fn new() -> Actor {\n\n let (sender, receiver) = channel();\n\n let actor = Actor {\n\n tx: sender\n\n };\n\n std::thread::spawn(move || {\n\n loop {\n\n match receiver.recv() {\n\n Ok(action) => {\n\n THREAD_POOL.spawn(move || action.execute());\n\n },\n\n Err(error) => {\n\n if error.to_string().contains(\"closed channel\") {\n\n break;\n\n }\n\n println!(\"{}\", error);\n\n }\n\n }\n\n }\n\n });\n", "file_path": "src/command/actor.rs", "rank": 47, "score": 24497.68860224622 }, { "content": " actor\n\n }\n\n\n\n pub fn add_action(&mut self, action: Box<Action>) -> Result<(), SendError<Box<Action>>> {\n\n self.tx.send(action)\n\n }\n\n}\n\n\n\n/// 执行动作\n\n/// @param action 动作\n", "file_path": "src/command/actor.rs", "rank": 48, "score": 24497.374643344283 }, { "content": "use std::sync::{mpsc::{SendError, Sender, channel}, Mutex};\n\n\n\nuse once_cell::sync::Lazy;\n\nuse rayon::ThreadPool;\n\n\n\nuse super::action::Action;\n\n\n\npub static GLOBAL_ACTOR: Lazy<Mutex<Actor>> = Lazy::new(|| {\n\n Mutex::new(Actor::new())\n\n});\n\n\n\nstatic THREAD_POOL: Lazy<ThreadPool> = Lazy::new(|| { rayon::ThreadPoolBuilder::new().num_threads(num_cpus::get()).build().unwrap() });\n\n\n\n/// 动作执行者\n\n/// 注意:不是 Actor 设计模式\n\npub struct Actor {\n\n tx: Sender<Box<Action>>,\n\n}\n\n\n\nimpl Actor {\n", "file_path": "src/command/actor.rs", "rank": 49, "score": 24496.23886277366 }, { "content": "pub mod command;\n\npub mod action;\n\npub mod actor;\n", "file_path": "src/command/mod.rs", "rank": 50, "score": 24494.90237896187 }, { "content": "use std::{hash::Hasher, path::PathBuf, io::Read};\n\n\n\nuse ffmpeg_next::format;\n\nuse xxhash_rust::xxh3::Xxh3;\n\nuse anyhow::*;\n\n\n\nuse crate::{\n\n model::dto::SimpleFileInfo,\n\n config::app_config::HASH_SEED\n\n};\n\n\n\nuse super::audio_utils::get_best_audio_stream_index;\n\n\n\n/// 计算 Hash 值\n", "file_path": "src/infra/hash_utils.rs", "rank": 51, "score": 23454.766632060553 }, { "content": "# shadow-music-cloud\n\nRust练手项目,一个在线音乐服务端\n", "file_path": "README.md", "rank": 52, "score": 15770.315600970906 }, { "content": "extern crate ffmpeg_next as ffmpeg;\n\n\n\nuse std::path::Path;\n\n\n\nuse anyhow::{Context, Ok, Result};\n\nuse ffmpeg::{codec, decoder, encoder, format, media, Stream};\n\n\n\n/// 获取最佳音频流索引\n\n/// @param input_ctx 输入媒体文件上下文\n\n/// @return 最佳音频流索引\n", "file_path": "src/infra/audio_utils.rs", "rank": 53, "score": 9.38845131128205 }, { "content": "use actix_web::{get, post, HttpResponse, Responder, web, Result};\n\n\n\nuse crate::{infra::{file_utils}};\n\n\n\n#[get(\"/media/list\")]\n\npub async fn list() -> Result<impl Responder> {\n\n let audio_files = file_utils::list_audio_file();\n\n // TODO\n\n Ok(web::Json(audio_files))\n\n}\n\n\n\n#[post(\"/media/list-diff\")]\n\npub async fn list_diff(file_info_hashs: web::Json<Vec<String>>) -> impl Responder {\n\n for file_info_hash in file_info_hashs.into_inner() {\n\n println!(\"{}\", file_info_hash);\n\n }\n\n HttpResponse::Ok().body(\"not implemented\")\n\n}", "file_path": "src/service/media.rs", "rank": 54, "score": 8.886536865627658 }, { "content": " fs::create_dir_all(&cover_path.parent().unwrap()).unwrap();\n\n let mut cover_file = File::create(&cover_path).unwrap();\n\n cover_file.write_all(cover_picture.data()).unwrap();\n\n }\n\n }\n\n },\n\n Err(err) => println!(\"{}\", err),\n\n }\n\n // 计算音频数据 Hash\n\n match hash_utils::hash_audio_data(&media_file_path) {\n\n Ok(hash) => media_info.audio_hash = radix(hash, 36).to_string(),\n\n Err(err) => println!(\"{}\", err),\n\n }\n\n\n\n FileInfo {\n\n path: simple.path.components()\n\n .map(|x| x.as_os_str().to_string_lossy().into_owned())\n\n .collect(),\n\n file_type: if simple.path.extension() == Some(OsStr::new(\"cue\")) {\n\n \"cuesheet\".to_string()\n", "file_path": "src/model/dto.rs", "rank": 55, "score": 8.803158362741927 }, { "content": "use std::{path::Path, cmp, fs};\n\n\n\nuse anyhow::Result;\n\nuse image::{imageops::FilterType, ImageOutputFormat};\n\n\n\n/// 生成缩略图\n\n/// @param input 输入文件\n\n/// @param output 输出文件\n", "file_path": "src/infra/image_utils.rs", "rank": 56, "score": 8.29928892392024 }, { "content": " output_ctx: &mut format::context::Output\n\n ) -> Result<()> {\n\n // 取得编码后的音频数据\n\n let mut encoded = Packet::empty();\n\n while encoder.receive_packet(&mut encoded).is_ok() {\n\n encoded.set_stream(0);\n\n encoded.rescale_ts(decoder.time_base(), output_time_base);\n\n encoded.write_interleaved(output_ctx)?;\n\n }\n\n Ok(())\n\n }\n\n\n\n fn receive_and_process_decoded_frame (\n\n decoder: &mut decoder::Audio,\n\n filter: &mut filter::Graph,\n\n encoder: &mut encoder::Audio,\n\n output_time_base: ffmpeg::Rational,\n\n output_ctx: &mut format::context::Output\n\n ) -> Result<()> {\n\n // 取得解码后的音频数据\n", "file_path": "src/infra/transcoder.rs", "rank": 57, "score": 7.509404184096134 }, { "content": "extern crate ffmpeg_next as ffmpeg;\n\n\n\nuse anyhow::{Ok, Result};\n\nuse ffmpeg::{codec, filter};\n\n\n", "file_path": "src/infra/audio_filter.rs", "rank": 58, "score": 7.094635134458754 }, { "content": " match disc {\n\n ItemValue::Text(text) => media_info.disc = text.parse().unwrap_or(1),\n\n ItemValue::Locator(text) => media_info.disc = text.parse().unwrap_or(1),\n\n ItemValue::Binary(binary) => {\n\n panic!(\"{} has binary disc number: {:?}\", simple.path.display(), binary)\n\n },\n\n }\n\n } else {\n\n media_info.disc = 1;\n\n }\n\n // 提取专辑封面\n\n if tag.picture_count() > 0 {\n\n let first_picture = tag.pictures().first().unwrap();\n\n let cover_picture = tag.get_picture_type(lofty::PictureType::CoverFront)\n\n .unwrap_or(first_picture);\n\n let picture_data_hash = radix(hash_utils::hash_data(cover_picture.data()), 36).to_string();\n\n let cover_path = PathBuf::from(config::app_config::ORIGIN_COVER_PATH).join(&picture_data_hash);\n\n cover_hash = Some(picture_data_hash);\n\n // 保存专辑封面到文件\n\n if !cover_path.exists() {\n", "file_path": "src/model/dto.rs", "rank": 59, "score": 6.74776499503953 }, { "content": "use std::{\n\n path::{PathBuf, Path}, ffi::OsStr, fs::{File, self}, io::Write\n\n};\n\n\n\nuse lofty::{TagItem, ItemKey, ItemValue, Accessor};\n\nuse radix_fmt::radix;\n\nuse serde::{Deserialize, Serialize};\n\n\n\nuse crate::{infra::{hash_utils, audio_utils}, config};\n\n\n\n/// 媒体信息\n\n#[derive(Debug, Serialize, Deserialize, Default)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct MediaInfo {\n\n /// 序号\n\n pub track: u32,\n\n /// 光碟序号\n\n pub disc: u32,\n\n /// 标题\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n", "file_path": "src/model/dto.rs", "rank": 60, "score": 6.455910107209606 }, { "content": " }\n\n }\n\n}\n\n\n\nimpl FileInfo {\n\n /// 从简略文件信息生成媒体文件信息\n\n /// 会将专辑封面保存到文件\n\n pub fn from_simple(simple: &SimpleFileInfo) -> FileInfo {\n\n // 注:目前不支持 cuesheet 文件\n\n let mut media_info = MediaInfo::default();\n\n let mut cover_hash: Option<String> = None;\n\n\n\n let media_file_path = PathBuf::from(config::app_config::AUDIO_PATH).join(&simple.path);\n\n // 获取音频属性\n\n match audio_utils::get_properties_from_media_file(&media_file_path) {\n\n Ok(properties) => {\n\n media_info.bitrate = properties.audio_bitrate().unwrap_or(0);\n\n media_info.duration = properties.duration().as_micros();\n\n },\n\n Err(err) => println!(\"{}\", err),\n", "file_path": "src/model/dto.rs", "rank": 61, "score": 6.2145564809872464 }, { "content": "extern crate ffmpeg_next as ffmpeg;\n\n\n\nuse std::path::Path;\n\n\n\nuse anyhow::{Ok, Result};\n\nuse ffmpeg::{format, frame, Packet, decoder, encoder, filter};\n\n\n\nuse super::{audio_utils, audio_filter};\n\n\n\npub struct Transcoder {\n\n pub output_filter_spec: Option<String>,\n\n pub codec: Option<String>,\n\n pub channels: Option<i32>,\n\n pub sample_rate: Option<i32>,\n\n pub bit_rate: Option<usize>,\n\n pub max_bit_rate: Option<usize>,\n\n}\n\n\n\nimpl Transcoder {\n\n fn process_filtered_frames(\n", "file_path": "src/infra/transcoder.rs", "rank": 62, "score": 6.064931398686394 }, { "content": " filter: &mut filter::Graph,\n\n decoder: &mut decoder::Audio,\n\n encoder: &mut encoder::Audio,\n\n output_time_base: ffmpeg::Rational,\n\n output_ctx: &mut format::context::Output\n\n ) -> Result<()> {\n\n let mut filtered = frame::Audio::empty();\n\n // 从音频滤镜接收解码后的帧\n\n while filter.get(\"out\").unwrap().sink().frame(&mut filtered).is_ok() {\n\n // 发送给编码器处理\n\n encoder.send_frame(&filtered)?;\n\n Transcoder::receive_and_process_encoded_packet(decoder, encoder, output_time_base, output_ctx)?;\n\n }\n\n Ok(())\n\n }\n\n\n\n fn receive_and_process_encoded_packet(\n\n decoder: &mut decoder::Audio,\n\n encoder: &mut encoder::Audio,\n\n output_time_base: ffmpeg::Rational,\n", "file_path": "src/infra/transcoder.rs", "rank": 63, "score": 6.062134448900071 }, { "content": "use std::collections::{HashMap, HashSet};\n\n\n\nuse once_cell::sync::Lazy;\n\nuse sled::Db;\n\n\n\nuse crate::{config::app_config::FILE_INFO_STORAGE_PATH, model::dto::FileInfo};\n\n\n\n// TODO\n\n// 检查没有访问权限\n\n// 检查磁盘已满\n\n\n\nstatic FILE_INFO_DB: Lazy<Db> = Lazy::new(|| {\n\n sled::open(FILE_INFO_STORAGE_PATH).unwrap()\n\n});\n\n\n", "file_path": "src/repository/file_info.rs", "rank": 64, "score": 5.623074749812425 }, { "content": "use std::{collections::HashSet, path::PathBuf};\n\nuse once_cell::sync::Lazy;\n\nuse walkdir::{WalkDir, DirEntry};\n\n\n\nuse crate::{config::app_config, model::dto::SimpleFileInfo};\n\n\n\nuse super::time_utils;\n\n\n\n/// Supported audio file extensions.\n\nstatic AUDIO_EXTENSIONS : Lazy<HashSet<&'static str>> = Lazy::new(|| {\n\n [\"wav\", \"mp3\", \"flac\", \"ogg\", \"m4a\", \"aac\", \"wma\", \"opus\"]\n\n .iter()\n\n .cloned()\n\n .collect()\n\n});\n\n\n\n/// 获取媒体目录下的所有音频文件信息\n\n/// @returns 音频文件信息列表\n", "file_path": "src/infra/file_utils.rs", "rank": 65, "score": 5.15472049369743 }, { "content": "use std::time::{SystemTime, UNIX_EPOCH};\n\n\n", "file_path": "src/infra/time_utils.rs", "rank": 66, "score": 5.016557733801166 }, { "content": "use actix_web::{App, HttpServer, middleware};\n\nuse shadow_music_cloud::{service::*};\n\n\n\n#[actix_web::main]\n\nasync fn main() -> std::io::Result<()> {\n\n HttpServer::new(|| {\n\n App::new()\n\n .wrap(middleware::Compress::default())\n\n .service(media::list)\n\n .service(media::list_diff)\n\n })\n\n .bind((\"127.0.0.1\", 8080))?\n\n .run()\n\n .await\n\n}", "file_path": "src/main.rs", "rank": 67, "score": 4.5964654287916975 }, { "content": " let mut decoded = frame::Audio::empty();\n\n while decoder.receive_frame(&mut decoded).is_ok() {\n\n let timestamp = decoded.timestamp();\n\n decoded.set_pts(timestamp);\n\n\n\n // 发送给音频滤镜\n\n filter.get(\"in\").unwrap().source().add(&decoded)?;\n\n Transcoder::process_filtered_frames(filter, decoder, encoder, output_time_base, output_ctx)?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn transcode<P: AsRef<Path>>(&self, input: &P, output: &P) -> Result<()> {\n\n // 输入输出上下文\n\n let mut input_ctx = format::input(&input)?;\n\n let mut output_ctx = format::output(&output)?;\n\n\n\n // 创建解码器\n\n let audio_stream = audio_utils::find_best_stream(&input_ctx)?;\n\n let audio_stream_index = audio_stream.index();\n", "file_path": "src/infra/transcoder.rs", "rank": 68, "score": 4.38840615358924 }, { "content": " filter.get(\"in\").unwrap().source().flush()?;\n\n Transcoder::process_filtered_frames(&mut filter, &mut decoder, &mut encoder, output_time_base, &mut output_ctx)?;\n\n\n\n // 编码结束\n\n encoder.send_eof()?;\n\n Transcoder::receive_and_process_encoded_packet(&mut decoder, &mut encoder, output_time_base, &mut output_ctx)?;\n\n\n\n // 写文件尾\n\n output_ctx.write_trailer()?;\n\n Ok(())\n\n }\n\n}", "file_path": "src/infra/transcoder.rs", "rank": 69, "score": 4.282144656622714 }, { "content": " }\n\n // 获取音频标签\n\n match audio_utils::get_tags_from_media_file(&media_file_path) {\n\n Ok(tag) => {\n\n // 如果文件有标签\n\n media_info.title = tag.title().map(|s| s.to_string());\n\n media_info.artist = tag.artist().map(|s| s.to_string());\n\n media_info.album = tag.album().map(|s| s.to_string());\n\n if let Some(track) = tag.get_item_ref(&ItemKey::TrackNumber).map(TagItem::value) {\n\n match track {\n\n ItemValue::Text(text) => media_info.track = text.parse().unwrap_or(1),\n\n ItemValue::Locator(text) => media_info.track = text.parse().unwrap_or(1),\n\n ItemValue::Binary(binary) => {\n\n panic!(\"{} has binary track number: {:?}\", simple.path.display(), binary)\n\n },\n\n }\n\n } else {\n\n media_info.track = 1;\n\n }\n\n if let Some(disc) = tag.get_item_ref(&ItemKey::DiscNumber).map(TagItem::value) {\n", "file_path": "src/model/dto.rs", "rank": 70, "score": 4.112568638605275 }, { "content": "\n\n let filter_spec = self.output_filter_spec.as_deref().unwrap_or(\"anull\");\n\n let mut filter = audio_filter::filter(filter_spec, &decoder, &encoder)?;\n\n\n\n // 开始转码\n\n for (stream, mut packet) in input_ctx.packets() {\n\n // 取出容器内的音频数据\n\n if stream.index() == audio_stream_index {\n\n // 转换时间基\n\n packet.rescale_ts(stream.time_base(), decoder.time_base());\n\n decoder.send_packet(&packet)?;\n\n Transcoder::receive_and_process_decoded_frame(&mut decoder, &mut filter, &mut encoder, output_time_base, &mut output_ctx)?;\n\n }\n\n }\n\n\n\n // 解码结束\n\n decoder.send_eof()?;\n\n Transcoder::receive_and_process_decoded_frame(&mut decoder, &mut filter, &mut encoder, output_time_base, &mut output_ctx)?;\n\n\n\n // flush filter\n", "file_path": "src/infra/transcoder.rs", "rank": 71, "score": 2.923751337339962 }, { "content": " } else {\n\n \"audio\".to_string()\n\n },\n\n size: simple.size,\n\n last_modified: simple.last_modified,\n\n file_info_hash: simple.file_info_hash.as_ref().unwrap_or({\n\n &radix(hash_utils::hash_media_file_info(simple), 36).to_string()\n\n }).to_string(),\n\n cue_media_path: None,\n\n cue_media_file_info_hash: None,\n\n cover_hash: cover_hash,\n\n medias: vec![media_info],\n\n }\n\n }\n\n}", "file_path": "src/model/dto.rs", "rank": 72, "score": 2.8796976956418483 }, { "content": " pub medias: Vec<MediaInfo>,\n\n}\n\n\n\n#[derive(Debug, Serialize, Deserialize, Clone)]\n\n#[serde(rename_all = \"camelCase\")]\n\npub struct SimpleFileInfo {\n\n pub path: PathBuf,\n\n pub size: u64,\n\n pub last_modified: u128,\n\n /// 文件路径+大小+修改时间 Hash\n\n pub file_info_hash: Option<String>,\n\n}\n\n\n\nimpl SimpleFileInfo {\n\n pub fn new(path: &Path, size: u64, last_modified: u128) -> SimpleFileInfo {\n\n SimpleFileInfo {\n\n path: path.to_path_buf(),\n\n size: size,\n\n last_modified: last_modified,\n\n file_info_hash: None,\n", "file_path": "src/model/dto.rs", "rank": 73, "score": 2.721943420074838 }, { "content": "pub struct FileInfo {\n\n /// 文件路径\n\n pub path: Vec<String>,\n\n /// 文件类型 audio/cuesheet\n\n pub file_type: String,\n\n /// 文件大小\n\n pub size: u64,\n\n /// 修改时间\n\n pub last_modified: u128,\n\n /// 文件路径+大小+修改时间 Hash\n\n pub file_info_hash: String,\n\n /// cuesheet 关联的媒体文件路径\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub cue_media_path: Option<String>,\n\n /// cuesheet 关联的媒体文件 Hash\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub cue_media_file_info_hash: Option<String>,\n\n /// 专辑封面 Hash\n\n pub cover_hash: Option<String>,\n\n /// 媒体文件信息\n", "file_path": "src/model/dto.rs", "rank": 74, "score": 2.5868078121672715 }, { "content": "pub mod infra;\n\npub mod model;\n\npub mod service;\n\npub mod config;\n\npub mod command;\n\npub mod repository;", "file_path": "src/lib.rs", "rank": 75, "score": 1.9592973448266888 }, { "content": " pub title: Option<String>,\n\n /// 歌手\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub artist: Option<String>,\n\n /// 专辑\n\n #[serde(skip_serializing_if = \"Option::is_none\")]\n\n pub album: Option<String>,\n\n /// 音频数据 Hash\n\n pub audio_hash: String,\n\n /// 起始位置(毫秒)\n\n pub index_time: u128,\n\n /// 时长(毫秒)\n\n pub duration: u128,\n\n /// 比特率(比特每秒)\n\n pub bitrate: u32,\n\n}\n\n\n\n/// 文件信息\n\n#[derive(Debug, Serialize, Deserialize)]\n\n#[serde(rename_all = \"camelCase\")]\n", "file_path": "src/model/dto.rs", "rank": 76, "score": 1.771805700962211 }, { "content": " let mut decoder = audio_utils::create_decoder_by_stream(audio_stream)?;\n\n\n\n // 编码器参数\n\n let codec = self.codec\n\n .as_deref()\n\n .map(|name| {audio_utils::create_codec_by_name(name)})\n\n .unwrap_or(audio_utils::guess_codec_by_path(output, &output_ctx))?;\n\n let channels = self.channels.unwrap_or(decoder.channel_layout().channels());\n\n let sample_rate = self.sample_rate.unwrap_or(decoder.rate() as i32);\n\n let bit_rate = self.bit_rate.unwrap_or(decoder.bit_rate());\n\n let max_bit_rate = self.max_bit_rate.unwrap_or(decoder.max_bit_rate());\n\n\n\n // 创建编码器并配置输出上下文\n\n let (mut encoder, output_time_base) = audio_utils::create_encoder_with_output_ctx(\n\n codec, &mut output_ctx, channels, decoder.rate() as i32,\n\n sample_rate, bit_rate, max_bit_rate)?;\n\n\n\n // 写文件头\n\n output_ctx.set_metadata(input_ctx.metadata().to_owned());\n\n output_ctx.write_header()?;\n", "file_path": "src/infra/transcoder.rs", "rank": 77, "score": 1.532235698585533 }, { "content": "pub mod file_utils;\n\npub mod hash_utils;\n\npub mod time_utils;\n\npub mod audio_utils;\n\npub mod transcoder;\n\npub mod audio_filter;\n\npub mod image_utils;", "file_path": "src/infra/mod.rs", "rank": 78, "score": 1.5224697009270831 }, { "content": " encoder.set_rate(target_sample_rate);\n\n encoder.set_time_base((1, source_sample_rate));\n\n output.set_time_base((1, source_sample_rate));\n\n\n\n let encoder = encoder.open_as(codec)?;\n\n output.set_parameters(&encoder);\n\n\n\n Ok((encoder, output.time_base()))\n\n}\n\n\n\n// ---- 文件信息 ----\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 79, "score": 1.4299190316164845 }, { "content": " out.set_channel_layout(encoder.channel_layout());\n\n out.set_sample_rate(encoder.rate());\n\n\n\n filter.output(\"in\", 0)?.input(\"out\", 0)?.parse(spec)?;\n\n filter.validate()?;\n\n\n\n if let Some(codec) = encoder.codec() {\n\n if !codec\n\n .capabilities()\n\n .contains(ffmpeg::codec::capabilities::Capabilities::VARIABLE_FRAME_SIZE)\n\n {\n\n filter\n\n .get(\"out\")\n\n .unwrap()\n\n .sink()\n\n .set_frame_size(encoder.frame_size());\n\n }\n\n }\n\n\n\n Ok(filter)\n\n}\n", "file_path": "src/infra/audio_filter.rs", "rank": 80, "score": 1.2275022420422301 }, { "content": "pub static AUDIO_PATH: &str = \"music\";\n\npub static FILE_INFO_STORAGE_PATH: &str = \"cache/file-index\";\n\npub static ORIGIN_COVER_PATH: &str = \"cache/cover/origin\";\n\npub static SMALL_COVER_PATH: &str = \"cache/cover/small\";\n\npub static OTHER_AUDIO_QUALITY_PATH: &str = \"cache/audio\";\n\npub static HASH_SEED: u64 = 1145141919810;", "file_path": "src/config/app_config.rs", "rank": 81, "score": 1.114532264748823 }, { "content": " }\n\n\n\n let channel_layout = codec\n\n .channel_layouts()\n\n .map(|cls| cls.best(channels))\n\n .unwrap_or(ffmpeg::channel_layout::ChannelLayout::STEREO);\n\n encoder.set_channel_layout(channel_layout);\n\n encoder.set_channels(channel_layout.channels());\n\n\n\n encoder.set_format(\n\n codec\n\n .formats()\n\n .expect(\"Unknown supported formats\")\n\n .next()\n\n .with_context(|| \"Failed to find supported format\")?,\n\n );\n\n\n\n encoder.set_bit_rate(bit_rate);\n\n encoder.set_max_bit_rate(max_bit_rate);\n\n\n", "file_path": "src/infra/audio_utils.rs", "rank": 82, "score": 1.0366199961638474 } ]
Rust
qsharp-ast/src/ast/specialization.rs
msoeken/qsharp
1c1d9b81b7e97af516749574bf92eb99d420d2a5
use itertools::Itertools; use proc_macro2::Ident; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::Paren, Result, Token, }; use crate::ast::{kw, utilities::peek_and_consume, Scope}; #[derive(Debug, PartialEq, Clone)] pub enum SpecializationParameter { Identifier(String), Dots, } #[derive(Debug, PartialEq)] pub enum SpecializationGenerator { Auto, Self_, Invert, Distribute, Intrinsic, Provided(Option<Vec<SpecializationParameter>>, Scope), } impl SpecializationGenerator { pub fn scope(&self) -> Option<&Scope> { match self { Self::Provided(_, scope) => Some(scope), _ => None, } } } #[derive(Debug, PartialEq, PartialOrd, Clone, Copy)] pub enum SpecializationKind { Body, Adjoint, Controlled, ControlledAdjoint, } #[derive(Debug, PartialEq)] pub struct Specialization { kind: SpecializationKind, generator: SpecializationGenerator, } impl PartialOrd for Specialization { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { self.kind.partial_cmp(&other.kind) } } impl Specialization { pub fn body(scope: Scope) -> Self { Self { kind: SpecializationKind::Body, generator: SpecializationGenerator::Provided(None, scope), } } pub fn adjoint(scope: Scope) -> Self { Self { kind: SpecializationKind::Adjoint, generator: SpecializationGenerator::Provided(None, scope), } } pub fn controlled(scope: Scope) -> Self { Self { kind: SpecializationKind::Controlled, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } } pub fn controlled_adjoint(scope: Scope) -> Self { Self { kind: SpecializationKind::ControlledAdjoint, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } } pub fn body_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Body, generator, } } pub fn adjoint_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Adjoint, generator, } } pub fn controlled_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Controlled, generator, } } pub fn controlled_adjoint_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::ControlledAdjoint, generator, } } pub fn kind(&self) -> SpecializationKind { self.kind } pub fn generator(&self) -> &SpecializationGenerator { &self.generator } pub fn generator_mut(&mut self) -> &mut SpecializationGenerator { &mut self.generator } pub fn set_generator(&mut self, generator: SpecializationGenerator) { self.generator = generator; } } impl Parse for SpecializationParameter { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![.]) { input.parse::<Token![.]>()?; input.parse::<Token![.]>()?; input.parse::<Token![.]>()?; Ok(SpecializationParameter::Dots) } else { let ident: Ident = input.parse()?; Ok(SpecializationParameter::Identifier(ident.to_string())) } } } impl Parse for SpecializationGenerator { fn parse(input: ParseStream) -> Result<Self> { if input.peek(kw::auto) { input.parse::<kw::auto>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Auto) } else if input.peek(Token![self]) { input.parse::<Token![self]>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Self_) } else if input.peek(kw::invert) { input.parse::<kw::invert>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Invert) } else if input.peek(kw::distribute) { input.parse::<kw::distribute>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Distribute) } else if input.peek(kw::intrinsic) { input.parse::<kw::intrinsic>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Intrinsic) } else { let tuple = if input.peek(Paren) { let buffer; parenthesized!(buffer in input); let items: Punctuated<SpecializationParameter, Token![,]> = Punctuated::parse_separated_nonempty(&buffer)?; Some(items.into_iter().collect_vec()) } else { None }; let scope = input.parse()?; Ok(SpecializationGenerator::Provided(tuple, scope)) } } } impl Parse for Specialization { fn parse(input: ParseStream) -> Result<Self> { let mut is_body = 0; let mut is_adjoint = 0; let mut is_controlled = 0; loop { if peek_and_consume(input, kw::body)? { is_body += 1; } else if peek_and_consume(input, kw::adjoint)? { is_adjoint += 1; } else if peek_and_consume(input, kw::controlled)? { is_controlled += 1; } else { break; } } let kind = match (is_body, is_adjoint, is_controlled) { (1, 0, 0) => SpecializationKind::Body, (0, 1, 0) => SpecializationKind::Adjoint, (0, 0, 1) => SpecializationKind::Controlled, (0, 1, 1) => SpecializationKind::ControlledAdjoint, _ => { return Err(input.error("invalid specialization keyword")); } }; let generator: SpecializationGenerator = input.parse()?; Ok(Specialization { kind, generator }) } } #[cfg(test)] mod tests { use super::*; use syn::Result; fn parse_specialization(s: &str) -> Result<Specialization> { syn::parse_str(s) } #[test] fn test_specializations() -> Result<()> { parse_specialization("body intrinsic;")?; parse_specialization("adjoint controlled distribute;")?; Ok(()) } }
use itertools::Itertools; use proc_macro2::Ident; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::Paren, Result, Token, }; use crate::ast::{kw, utilities::peek_and_consume, Scope}; #[derive(Debug, PartialEq, Clone)] pub enum SpecializationParameter { Identifier(String), Dots, } #[derive(Debug, PartialEq)] pub enum SpecializationGenerator { Auto, Self_, Invert, Distribute, Intrinsic, Provided(Option<Vec<SpecializationParameter>>, Scope), } impl SpecializationGenerator { pub fn scope(&self) -> Option<&Scope> { match self { Self::Provided(_, scope) => Some(scope), _ => None, } } } #[derive(Debug, PartialEq, PartialOrd, Clone, Copy)] pub enum SpecializationKind { Body, Adjoint, Controlled, ControlledAdjoint, } #[derive(Debug, PartialEq)] pub struct Specialization { kind: SpecializationKind, generator: SpecializationGenerator, } impl PartialOrd for Specialization { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { self.kind.partial_cmp(&other.kind) } } impl Specialization { pub fn body(scope: Scope) -> Self { Self { kind: SpecializationKind::Body, generator: SpecializationGenerator::Provided(None, scope), } } pub fn adjoint(scope: Scope) -> Self { Self { kind: SpecializationKind::Adjoint, generator: SpecializationGenerator::Provided(None, scope), } }
pub fn controlled_adjoint(scope: Scope) -> Self { Self { kind: SpecializationKind::ControlledAdjoint, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } } pub fn body_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Body, generator, } } pub fn adjoint_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Adjoint, generator, } } pub fn controlled_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::Controlled, generator, } } pub fn controlled_adjoint_with(generator: SpecializationGenerator) -> Self { Self { kind: SpecializationKind::ControlledAdjoint, generator, } } pub fn kind(&self) -> SpecializationKind { self.kind } pub fn generator(&self) -> &SpecializationGenerator { &self.generator } pub fn generator_mut(&mut self) -> &mut SpecializationGenerator { &mut self.generator } pub fn set_generator(&mut self, generator: SpecializationGenerator) { self.generator = generator; } } impl Parse for SpecializationParameter { fn parse(input: ParseStream) -> Result<Self> { if input.peek(Token![.]) { input.parse::<Token![.]>()?; input.parse::<Token![.]>()?; input.parse::<Token![.]>()?; Ok(SpecializationParameter::Dots) } else { let ident: Ident = input.parse()?; Ok(SpecializationParameter::Identifier(ident.to_string())) } } } impl Parse for SpecializationGenerator { fn parse(input: ParseStream) -> Result<Self> { if input.peek(kw::auto) { input.parse::<kw::auto>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Auto) } else if input.peek(Token![self]) { input.parse::<Token![self]>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Self_) } else if input.peek(kw::invert) { input.parse::<kw::invert>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Invert) } else if input.peek(kw::distribute) { input.parse::<kw::distribute>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Distribute) } else if input.peek(kw::intrinsic) { input.parse::<kw::intrinsic>()?; input.parse::<Token![;]>()?; Ok(SpecializationGenerator::Intrinsic) } else { let tuple = if input.peek(Paren) { let buffer; parenthesized!(buffer in input); let items: Punctuated<SpecializationParameter, Token![,]> = Punctuated::parse_separated_nonempty(&buffer)?; Some(items.into_iter().collect_vec()) } else { None }; let scope = input.parse()?; Ok(SpecializationGenerator::Provided(tuple, scope)) } } } impl Parse for Specialization { fn parse(input: ParseStream) -> Result<Self> { let mut is_body = 0; let mut is_adjoint = 0; let mut is_controlled = 0; loop { if peek_and_consume(input, kw::body)? { is_body += 1; } else if peek_and_consume(input, kw::adjoint)? { is_adjoint += 1; } else if peek_and_consume(input, kw::controlled)? { is_controlled += 1; } else { break; } } let kind = match (is_body, is_adjoint, is_controlled) { (1, 0, 0) => SpecializationKind::Body, (0, 1, 0) => SpecializationKind::Adjoint, (0, 0, 1) => SpecializationKind::Controlled, (0, 1, 1) => SpecializationKind::ControlledAdjoint, _ => { return Err(input.error("invalid specialization keyword")); } }; let generator: SpecializationGenerator = input.parse()?; Ok(Specialization { kind, generator }) } } #[cfg(test)] mod tests { use super::*; use syn::Result; fn parse_specialization(s: &str) -> Result<Specialization> { syn::parse_str(s) } #[test] fn test_specializations() -> Result<()> { parse_specialization("body intrinsic;")?; parse_specialization("adjoint controlled distribute;")?; Ok(()) } }
pub fn controlled(scope: Scope) -> Self { Self { kind: SpecializationKind::Controlled, generator: SpecializationGenerator::Provided( Some(vec![SpecializationParameter::Identifier("ctls".into())]), scope, ), } }
function_block-full_function
[ { "content": "pub fn peek_and_consume<T: Peek>(input: ParseStream, token: T) -> Result<bool>\n\nwhere\n\n T::Token: Parse,\n\n{\n\n Ok(if input.peek(token) {\n\n input.parse::<T::Token>()?;\n\n true\n\n } else {\n\n false\n\n })\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 0, "score": 202559.42941397236 }, { "content": "fn normalize_controlled_adjoint(body: &mut CallableBody, parameters: Vec<SpecializationParameter>) {\n\n // first make sure that specialization has a provided generator\n\n match body.controlled_adjoint_mut().map(|spec| spec.generator()) {\n\n Some(SpecializationGenerator::Provided(..)) => {}\n\n Some(SpecializationGenerator::Self_) => {\n\n let scope = body.controlled_scope().unwrap().clone();\n\n //specialization.set_generator(SpecializationGenerator::Provided(None, scope));\n\n body.controlled_adjoint_mut()\n\n .unwrap()\n\n .set_generator(SpecializationGenerator::Provided(Some(parameters), scope))\n\n }\n\n Some(SpecializationGenerator::Auto) => {\n\n let scope = body.controlled_scope().unwrap().clone().adjoint();\n\n body.controlled_adjoint_mut()\n\n .unwrap()\n\n .set_generator(SpecializationGenerator::Provided(Some(parameters), scope))\n\n }\n\n Some(_) => {\n\n todo!();\n\n }\n", "file_path": "qsharp-ast/src/analysis/normalize.rs", "rank": 1, "score": 180305.8282194941 }, { "content": "pub fn peek_and_consume_ellipsis(input: ParseStream) -> Result<bool> {\n\n if input.peek(Token![.]) && input.peek2(Token![.]) && input.peek3(Token![.]) {\n\n input.parse::<Token![.]>()?;\n\n input.parse::<Token![.]>()?;\n\n input.parse::<Token![.]>()?;\n\n Ok(true)\n\n } else {\n\n Ok(false)\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 2, "score": 171160.25694692778 }, { "content": "pub fn peek_and_consume_single_quote(input: ParseStream) -> Result<bool> {\n\n if let Some((TokenTree::Punct(punct), _)) = input.cursor().token_tree() {\n\n if punct.as_char() == '\\'' {\n\n input.parse::<TokenTree>()?;\n\n return Ok(true);\n\n }\n\n }\n\n\n\n Ok(false)\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 3, "score": 169306.0467401796 }, { "content": "pub fn parse_many<T: Parse>(input: ParseStream) -> Result<Vec<T>> {\n\n repeat(())\n\n .take_while(|_| !input.is_empty())\n\n .map(|_| input.parse())\n\n .collect()\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 4, "score": 157738.49987938127 }, { "content": "fn normalize_controlled(body: &mut CallableBody) -> Vec<SpecializationParameter> {\n\n // first make sure that specialization has a provided generator\n\n match body.controlled_mut().map(|spec| spec.generator()) {\n\n Some(SpecializationGenerator::Provided(None, _)) => {\n\n panic!(\"controlled specialization has no specialization parameters\")\n\n }\n\n Some(SpecializationGenerator::Provided(Some(parameters), _)) => parameters.clone(),\n\n Some(SpecializationGenerator::Auto) => {\n\n let scope = body.body_scope().unwrap().clone().controlled();\n\n let parameters = vec![SpecializationParameter::Identifier(\"__ctls\".into())];\n\n body.controlled_mut()\n\n .unwrap()\n\n .set_generator(SpecializationGenerator::Provided(\n\n Some(parameters.clone()),\n\n scope,\n\n ));\n\n parameters\n\n }\n\n Some(_) => {\n\n todo!();\n\n }\n\n // if there's no controlled, there'll also be no controlled adjoint\n\n None => vec![],\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/normalize.rs", "rank": 5, "score": 154138.1378779113 }, { "content": "pub fn expect_ident(ident: Ident, name: &str) -> Result<()> {\n\n if ident != name {\n\n Err(Error::new(ident.span(), format!(\"expected `{}`\", name)))\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 6, "score": 149237.40885471538 }, { "content": "#[proc_macro]\n\npub fn qsharp(item: TokenStream) -> TokenStream {\n\n let mut result = parse_macro_input!(item as ProgramWithOptions);\n\n result.program.normalize();\n\n\n\n let mut codegen = Codegen::new();\n\n if let Some(sim_trait) = result.sim_trait {\n\n codegen.set_sim_trait(&sim_trait);\n\n }\n\n\n\n codegen.visit_program(&result.program).into()\n\n}\n", "file_path": "qsharp/src/lib.rs", "rank": 7, "score": 148515.7479190505 }, { "content": "pub fn H(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.h(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 8, "score": 143292.23990426463 }, { "content": "pub fn T(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.t(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 9, "score": 143292.23990426463 }, { "content": "pub fn S(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.s(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 10, "score": 143292.23990426463 }, { "content": "pub fn X(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.x(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 11, "score": 143292.23990426463 }, { "content": "pub fn X_adj(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.x(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 12, "score": 141507.17442565333 }, { "content": "pub fn T_adj(sim: &mut impl QSharpIntrinsics, q: usize) {\n\n sim.t_adj(q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 13, "score": 141507.17442565333 }, { "content": "pub fn M(sim: &mut impl QSharpIntrinsics, q: usize) -> bool {\n\n sim.m(q)\n\n}\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 14, "score": 139391.18656972024 }, { "content": "pub fn CNOT(sim: &mut impl QSharpIntrinsics, ctl: usize, tgt: usize) {\n\n sim.cnot(ctl, tgt);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 15, "score": 134076.95257762147 }, { "content": "#[doc(hidden)]\n\n#[allow(dead_code, non_snake_case)]\n\npub fn CopyAndUpdate<__S: IntoSpans<[Span; 1]>>(span: __S) -> CopyAndUpdate {\n\n CopyAndUpdate {\n\n span: IntoSpans::into_spans(span)[0],\n\n }\n\n}\n\n\n\nimpl Default for CopyAndUpdate {\n\n fn default() -> Self {\n\n CopyAndUpdate {\n\n span: Span::call_site(),\n\n }\n\n }\n\n}\n\n\n\nimpl syn::token::CustomToken for CopyAndUpdate {\n\n fn peek(cursor: Cursor) -> bool {\n\n if let Some((ident, rest)) = cursor.ident() {\n\n if ident != \"w\" {\n\n false\n\n } else if let Some((punct, _)) = rest.punct() {\n", "file_path": "qsharp-ast/src/ast/kw.rs", "rank": 16, "score": 133121.2469470921 }, { "content": "pub fn CNOT_adj(sim: &mut impl QSharpIntrinsics, ctl: usize, tgt: usize) {\n\n sim.cnot(ctl, tgt);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 17, "score": 132478.6248994084 }, { "content": "pub fn X_ctl(sim: &mut impl QSharpIntrinsics, ctls: Array<usize>, q: usize) {\n\n sim.mcx(&ctls, q);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Intrinsic.rs", "rank": 18, "score": 130697.5614490367 }, { "content": "fn normalize_adjoint(body: &mut CallableBody) {\n\n // first make sure that specialization has a provided generator\n\n match body.adjoint_mut().map(|spec| spec.generator()) {\n\n Some(SpecializationGenerator::Provided(..)) => {}\n\n Some(SpecializationGenerator::Self_) => {\n\n let scope = body.body_scope().unwrap().clone();\n\n body.adjoint_mut()\n\n .unwrap()\n\n .set_generator(SpecializationGenerator::Provided(None, scope))\n\n }\n\n Some(SpecializationGenerator::Auto) => {\n\n let scope = body.body_scope().unwrap().clone().adjoint();\n\n body.adjoint_mut()\n\n .unwrap()\n\n .set_generator(SpecializationGenerator::Provided(None, scope))\n\n }\n\n Some(_) => {\n\n todo!();\n\n }\n\n None => {}\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/normalize.rs", "rank": 19, "score": 128757.07330170812 }, { "content": "#[inline]\n\npub fn Head<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> T {\n\n array[0].clone()\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 20, "score": 124916.99472547318 }, { "content": "#[inline]\n\npub fn Tail<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> T {\n\n array[array.len() - 1].clone()\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 21, "score": 124916.99472547318 }, { "content": "pub fn has_extra_parens<PredicateFn>(input: ParseStream, predicate: PredicateFn) -> bool\n\nwhere\n\n PredicateFn: Fn(TokenTree) -> bool,\n\n{\n\n if let Some((into, _, _)) = input.cursor().group(proc_macro2::Delimiter::Parenthesis) {\n\n into.token_stream().into_iter().any(|tree| predicate(tree))\n\n } else {\n\n false\n\n }\n\n}\n", "file_path": "qsharp-ast/src/ast/utilities.rs", "rank": 22, "score": 124161.87332773447 }, { "content": "#[inline]\n\npub fn Head_adj<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> T {\n\n array[0].clone()\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 23, "score": 123476.42074685627 }, { "content": "#[inline]\n\npub fn Tail_adj<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> T {\n\n array[array.len() - 1].clone()\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 24, "score": 123476.42074685627 }, { "content": "#[inline]\n\npub fn Rest<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> Array<T> {\n\n Rc::new(array[1..].to_vec())\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 25, "score": 122053.7136023573 }, { "content": "fn parse_characteristics_union(input: ParseStream) -> Result<Rc<Characteristics>> {\n\n let terms: Punctuated<Rc<Characteristics>, Token![+]> =\n\n Punctuated::parse_separated_nonempty_with(input, parse_characteristics_intersection)?;\n\n\n\n // we know iter is non empty\n\n Ok(terms.into_iter().reduce(Characteristics::union).unwrap())\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/characteristics.rs", "rank": 26, "score": 120793.31189490951 }, { "content": "fn parse_numeric_literal(input: ParseStream) -> Result<Rc<Expression>> {\n\n // TODO string\n\n\n\n let literal: Lit = input.parse()?;\n\n\n\n match literal {\n\n Lit::Str(lit) => Ok(Expression::string_literal(lit.value())),\n\n Lit::ByteStr(_) | Lit::Byte(_) | Lit::Char(_) | Lit::Verbatim(_) => {\n\n Err(input.error(\"unsupported literal\"))\n\n }\n\n Lit::Int(lit) => match lit.suffix() {\n\n \"\" => Ok(Expression::int_literal(lit.base10_parse::<i64>()?)),\n\n \"l\" | \"L\" => {\n\n let integer = lit.base10_digits().parse::<Integer>();\n\n let integer = integer.map_err(|_| input.error(\"cannot parse BigInt literal\"))?;\n\n Ok(Expression::big_int_literal(integer))\n\n }\n\n other => Err(input.error(format!(\"unsupported suffix {}\", other))),\n\n },\n\n Lit::Float(lit) => Ok(Expression::double_literal(lit.base10_parse::<f64>()?)),\n", "file_path": "qsharp-ast/src/ast/expression.rs", "rank": 27, "score": 120793.31189490951 }, { "content": "fn parse_characteristics_intersection(input: ParseStream) -> Result<Rc<Characteristics>> {\n\n let terms: Punctuated<Rc<Characteristics>, Token![*]> =\n\n Punctuated::parse_separated_nonempty_with(input, parse_characteristics_terminal)?;\n\n\n\n // we know iter is non empty\n\n Ok(terms\n\n .into_iter()\n\n .reduce(Characteristics::intersection)\n\n .unwrap())\n\n}\n\n\n\npub(crate) fn parse_characteristics(input: ParseStream) -> Result<Rc<Characteristics>> {\n\n // We use the precedence climbing parsing method (see, e.g., https://en.wikipedia.org/wiki/Operator-precedence_parser)\n\n parse_characteristics_union(input)\n\n}\n\n\n\nimpl Parse for Characteristics {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let characteristics = parse_characteristics(input)?;\n\n Rc::try_unwrap(characteristics).map_err(|_| input.error(\"cannot extract characteristics\"))\n", "file_path": "qsharp-ast/src/ast/characteristics.rs", "rank": 28, "score": 120793.31189490951 }, { "content": "fn parse_characteristics_terminal(input: ParseStream) -> Result<Rc<Characteristics>> {\n\n if input.peek(Paren) {\n\n let buffer;\n\n parenthesized!(buffer in input);\n\n parse_characteristics_union(&buffer)\n\n } else if input.peek(syn::Ident) {\n\n let ident: Ident = input.parse()?;\n\n match ident.to_string().as_str() {\n\n \"Adj\" => Ok(Characteristics::adj()),\n\n \"Ctl\" => Ok(Characteristics::ctl()),\n\n other => Err(input.error(format!(\"invalid characteristics {}\", other))),\n\n }\n\n } else {\n\n Err(input.error(\"unexpected token in parsing characteristics\"))\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/ast/characteristics.rs", "rank": 29, "score": 120793.31189490951 }, { "content": "#[inline]\n\npub fn Rest_adj<Sim: QSharpIntrinsics, T: Clone>(_sim: &mut Sim, array: Array<T>) -> Array<T> {\n\n Rc::new(array[1..].to_vec())\n\n}\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 30, "score": 120660.90525762645 }, { "content": "fn main() -> Result<()> {\n\n let mut total = 0;\n\n let mut fails = vec![];\n\n let mut count = 0;\n\n\n\n let mut args = args();\n\n\n\n args.next();\n\n\n\n for path in args {\n\n count += 1;\n\n\n\n let mut input = fs::read_to_string(&path).unwrap();\n\n\n\n input = input.trim().strip_bom().into();\n\n\n\n let now = Instant::now();\n\n\n\n match syn::parse_str::<Program>(&input) {\n\n Ok(_) => {\n", "file_path": "qsharp-ast/examples/bench.rs", "rank": 31, "score": 120281.3562500973 }, { "content": "#[test]\n\nfn test_and() -> Result<()> {\n\n let code = \"\n\n namespace Common {\n\n open Microsoft.Quantum.Intrinsic;\n\n\n\n operation And(ctl1: Qubit, ctl2: Qubit, tgt: Qubit) : Unit is Adj {\n\n body (...) {\n\n H(tgt);\n\n T(tgt);\n\n CNOT(ctl1, tgt);\n\n CNOT(ctl2, tgt);\n\n CNOT(tgt, ctl1);\n\n CNOT(tgt, ctl2);\n\n Adjoint T(ctl1);\n\n Adjoint T(ctl2);\n\n T(tgt);\n\n CNOT(tgt, ctl2);\n\n CNOT(tgt, ctl1);\n\n H(tgt);\n\n S(tgt);\n", "file_path": "qsharp-codegen/tests/realistic.rs", "rank": 32, "score": 120281.3562500973 }, { "content": "#[test]\n\nfn test_sum() -> Result<()> {\n\n let code = \"\n\n namespace Common {\n\n open Microsoft.Quantum.Arrays;\n\n open Microsoft.Quantum.Diagnostics;\n\n open Microsoft.Quantum.Intrinsic;\n\n open Circuits;\n\n\n\n internal operation Sum(carryIn : Qubit, x : Qubit, y : Qubit) : Unit is Adj+Ctl {\n\n body (...) {\n\n CNOT(carryIn, y);\n\n CNOT(x, y);\n\n }\n\n\n\n adjoint self;\n\n\n\n controlled (ctls, ...) {\n\n EqualityFactI(Length(ctls), 1, \\\"Number of control lines must be 1\\\");\n\n\n\n use q = Qubit();\n", "file_path": "qsharp-codegen/tests/realistic.rs", "rank": 33, "score": 118551.79637988568 }, { "content": "#[test]\n\nfn test_swap() -> Result<()> {\n\n let code = \"\n\n namespace Common {\n\n open Microsoft.Quantum.Intrinsic;\n\n\n\n operation SWAP(q1: Qubit, q2: Qubit) : Unit is Adj+Ctl {\n\n body (...) {\n\n within {\n\n CNOT(q2, q1);\n\n } apply {\n\n CNOT(q1, q2);\n\n }\n\n }\n\n\n\n adjoint self;\n\n }\n\n }\n\n \";\n\n\n\n let mut ast: Program = syn::parse_str(code)?;\n\n ast.normalize();\n\n\n\n let _rust = Codegen::new().visit_program(&ast);\n\n\n\n println!(\"{}\", _rust);\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "qsharp-codegen/tests/realistic.rs", "rank": 34, "score": 118551.79637988568 }, { "content": "fn peek_operator(input: ParseStream, parse_with_index: bool) -> Result<Operator> {\n\n let cursor = input.cursor();\n\n\n\n if let Some((ident, rest)) = cursor.ident() {\n\n match ident.to_string().as_str() {\n\n \"w\" => {\n\n if let Some((punct, _)) = rest.punct() {\n\n if punct.as_char() == '/' {\n\n return Ok(Operator::CopyAndUpdate);\n\n }\n\n }\n\n }\n\n \"or\" => return Ok(Operator::LogicalOr),\n\n \"and\" => return Ok(Operator::LogicalAnd),\n\n _ => {}\n\n }\n\n } else if let Some((punct, rest)) = cursor.punct() {\n\n match punct.as_char() {\n\n '.' => {\n\n if let Some((punct2, rest2)) = rest.punct() {\n", "file_path": "qsharp-ast/src/ast/expression.rs", "rank": 35, "score": 116851.98730970125 }, { "content": "/// we set `parse_call` to false when parsing a primary after `Adjoint` or\n\n/// `Controlled`, because the call operator has a lower precedence; otherwise,\n\n/// it's always true\n\nfn parse_primary(input: ParseStream, parse_call: bool) -> Result<Rc<Expression>> {\n\n // TODO optimize order or use low-level cursor API for lookahead\n\n let mut prefix = if input.peek(Paren) {\n\n let buffer;\n\n parenthesized!(buffer in input);\n\n if buffer.is_empty() {\n\n Ok(Expression::unit_value())\n\n } else {\n\n let first_expr = parse_expression(&buffer, false)?;\n\n\n\n if buffer.is_empty() {\n\n Ok(first_expr)\n\n } else {\n\n let mut values = vec![first_expr];\n\n while !buffer.is_empty() {\n\n buffer.parse::<Token![,]>()?;\n\n values.push(parse_expression(&buffer, false)?);\n\n }\n\n Ok(Expression::tuple_literal(values))\n\n }\n", "file_path": "qsharp-ast/src/ast/expression.rs", "rank": 36, "score": 113213.58576411032 }, { "content": "pub fn type_from_expression(\n\n expr: &Expression,\n\n symbol_table: &HashMap<QualifiedName, Rc<TypeKind>>,\n\n) -> Option<Rc<TypeKind>> {\n\n match expr {\n\n Expression::UnitValue => Some(TypeKind::unit()),\n\n Expression::Missing => todo!(),\n\n Expression::Identifier(name, None) => symbol_table.get(name).cloned(),\n\n Expression::IntLiteral(_) => Some(TypeKind::int()),\n\n Expression::BigIntLiteral(_) => Some(TypeKind::big_int()),\n\n Expression::DoubleLiteral(_) => Some(TypeKind::double()),\n\n Expression::BoolLiteral(_) => Some(TypeKind::bool()),\n\n Expression::StringLiteral(_) => Some(TypeKind::string()),\n\n Expression::PauliLiteral(_) => Some(TypeKind::pauli()),\n\n Expression::ResultLiteral(_) => Some(TypeKind::result()),\n\n Expression::ArrayLiteral(items) => {\n\n let first = type_from_expression(items.first()?, symbol_table)?;\n\n\n\n // all items must be of the same type\n\n for expr in items.iter().skip(1) {\n", "file_path": "qsharp-ast/src/analysis/expression.rs", "rank": 37, "score": 112781.20257540447 }, { "content": "#[allow(non_snake_case)]\n\nfn Z(sim: &mut impl MyIntrinsics) {\n\n sim.z();\n\n}\n\n\n\nqsharp! {\n\n impl MyIntrinsics\n\n\n\n namespace Operations {\n\n operation Operation() : Unit {\n\n X();\n\n Y();\n\n Z();\n\n Y();\n\n X();\n\n }\n\n }\n\n}\n\n\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 38, "score": 108506.05878601028 }, { "content": "#[allow(non_snake_case)]\n\nfn X(sim: &mut impl MyIntrinsics) {\n\n sim.x();\n\n}\n\n\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 39, "score": 108506.05878601028 }, { "content": "#[allow(non_snake_case)]\n\nfn Y(sim: &mut impl MyIntrinsics) {\n\n sim.y();\n\n}\n\n\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 40, "score": 108506.05878601028 }, { "content": "pub fn flatten_bindings<'a, 'b>(\n\n binding: &'a SymbolBinding,\n\n initializer: &'b QubitInitializer,\n\n) -> Vec<(&'a str, &'b QubitInitializer)> {\n\n match (binding, initializer) {\n\n (SymbolBinding::Identifier(name), QubitInitializer::Single)\n\n | (SymbolBinding::Identifier(name), QubitInitializer::Register(_)) => {\n\n vec![(name.as_str(), initializer)]\n\n }\n\n (SymbolBinding::Tuple(_), QubitInitializer::Tuple(_)) => todo!(),\n\n _ => unreachable!(),\n\n }\n\n}\n", "file_path": "qsharp-codegen/src/codegen/symbol_binding.rs", "rank": 41, "score": 106707.79338265455 }, { "content": "#[inline]\n\npub fn EqualityFactI<Sim: QSharpIntrinsics>(\n\n sim: &mut Sim,\n\n actual: i64,\n\n expected: i64,\n\n message: String,\n\n) {\n\n Fact(sim, actual == expected, message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 42, "score": 101040.43107178682 }, { "content": "#[inline]\n\npub fn Fact_ctl<Sim: QSharpIntrinsics>(\n\n _sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n (actual, message): (bool, String),\n\n) {\n\n assert!(actual, \"{}\", message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 43, "score": 101040.43107178682 }, { "content": "#[inline]\n\npub fn EqualityFactI_ctl<Sim: QSharpIntrinsics>(\n\n sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n (actual, expected, message): (i64, i64, String),\n\n) {\n\n Fact(sim, actual == expected, message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 44, "score": 99761.63452891732 }, { "content": "#[inline]\n\npub fn EqualityFactI_adj<Sim: QSharpIntrinsics>(\n\n sim: &mut Sim,\n\n actual: i64,\n\n expected: i64,\n\n message: String,\n\n) {\n\n Fact_adj(sim, actual == expected, message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 45, "score": 99761.63452891732 }, { "content": "#[inline]\n\npub fn Fact_ctl_adj<Sim: QSharpIntrinsics>(\n\n _sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n (actual, message): (bool, String),\n\n) {\n\n assert!(actual, \"{}\", message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 46, "score": 99761.63452891732 }, { "content": "#[inline]\n\npub fn EqualityFactI_ctl_adj<Sim: QSharpIntrinsics>(\n\n sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n (actual, expected, message): (i64, i64, String),\n\n) {\n\n Fact(sim, actual == expected, message);\n\n}\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 47, "score": 98531.72311456752 }, { "content": "#[inline]\n\npub fn Length_ctl<Sim: QSharpIntrinsics, T>(\n\n _sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n array: Array<T>,\n\n) -> i64 {\n\n array.len() as i64\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Core.rs", "rank": 48, "score": 97871.742538233 }, { "content": "#[inline]\n\npub fn Length_ctl_adj<Sim: QSharpIntrinsics, T>(\n\n _sim: &mut Sim,\n\n _ctls: Array<usize>,\n\n array: Array<T>,\n\n) -> i64 {\n\n array.len() as i64\n\n}\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Core.rs", "rank": 49, "score": 96641.83112388321 }, { "content": "fn augment_callable_type_kind(\n\n type_kind: &TypeKind,\n\n characteristic: Rc<Characteristics>,\n\n) -> Option<Rc<TypeKind>> {\n\n match type_kind {\n\n TypeKind::Operation(args, return_type, rhs) => {\n\n Some(TypeKind::operation_with_characteristics(\n\n args.clone(),\n\n return_type.clone(),\n\n characteristics_union(characteristic, rhs),\n\n ))\n\n }\n\n TypeKind::Function(args, return_type, rhs) => {\n\n Some(TypeKind::function_with_characteristics(\n\n args.clone(),\n\n return_type.clone(),\n\n characteristics_union(characteristic, rhs),\n\n ))\n\n }\n\n _ => None,\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/expression.rs", "rank": 50, "score": 89961.42585807192 }, { "content": "#[inline]\n\npub fn EmptyArray<Sim: QSharpIntrinsics, T>(_sim: &mut Sim) -> Array<T> {\n\n Rc::new(Vec::new())\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Arrays.rs", "rank": 51, "score": 85097.83862795384 }, { "content": "pub fn AssertAllZero<Sim: QSharpIntrinsics>(_sim: &mut Sim, _qubits: Array<usize>) {\n\n // TODO\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 52, "score": 85097.83862795384 }, { "content": "/// Checks whether `actual` is the same as `expected`, if not `None`, otherwise,\n\n/// returns `None`.\n\nfn with_type_check(actual: Option<Rc<TypeKind>>, expected: &Rc<TypeKind>) -> Option<Rc<TypeKind>> {\n\n actual.filter(|kind| expected == kind)\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/expression.rs", "rank": 53, "score": 84510.2204827289 }, { "content": "pub fn AssertAllZero_adj<Sim: QSharpIntrinsics>(_sim: &mut Sim, _qubits: Array<usize>) {\n\n // TODO\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 54, "score": 84074.88235900554 }, { "content": "#[inline]\n\npub fn Fact<Sim: QSharpIntrinsics>(_sim: &mut Sim, actual: bool, message: String) {\n\n assert!(actual, \"{}\", message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 55, "score": 84028.12520190605 }, { "content": "#[inline]\n\npub fn Fact_adj<Sim: QSharpIntrinsics>(_sim: &mut Sim, actual: bool, message: String) {\n\n assert!(actual, \"{}\", message);\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Diagnostics.rs", "rank": 56, "score": 83005.16893295773 }, { "content": "#[inline]\n\npub fn Length<Sim: QSharpIntrinsics, T>(_sim: &mut Sim, array: Array<T>) -> i64 {\n\n array.len() as i64\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Core.rs", "rank": 57, "score": 82018.57569510961 }, { "content": "#[inline]\n\npub fn Length_adj<Sim: QSharpIntrinsics, T>(_sim: &mut Sim, array: Array<T>) -> i64 {\n\n array.len() as i64\n\n}\n\n\n", "file_path": "qsharp-runtime/src/Microsoft/Quantum/Core.rs", "rank": 58, "score": 81030.7011765033 }, { "content": "struct ProgramWithOptions {\n\n program: Program,\n\n sim_trait: Option<String>,\n\n}\n\n\n\nimpl Parse for ProgramWithOptions {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let sim_trait = if input.peek(Token![impl]) {\n\n input.parse::<Token![impl]>()?;\n\n let ident: Ident = input.parse()?;\n\n Some(ident.to_string())\n\n } else {\n\n None\n\n };\n\n\n\n let program = input.parse()?;\n\n\n\n Ok(Self { program, sim_trait })\n\n }\n\n}\n\n\n", "file_path": "qsharp/src/lib.rs", "rank": 59, "score": 68898.96463392254 }, { "content": "struct TestSimulator {}\n\n\n\nimpl QSharpIntrinsics for TestSimulator {\n\n fn x(&mut self, _q: usize) {}\n\n fn y(&mut self, _q: usize) {}\n\n fn z(&mut self, _q: usize) {}\n\n fn h(&mut self, _q: usize) {}\n\n fn s(&mut self, _q: usize) {}\n\n fn t(&mut self, _q: usize) {}\n\n fn t_adj(&mut self, _q: usize) {}\n\n fn cnot(&mut self, _ctl: usize, _tgt: usize) {}\n\n fn m(&mut self, _q: usize) -> bool {\n\n true\n\n }\n\n\n\n fn mcx(&mut self, _ctls: &[usize], _q: usize) {}\n\n\n\n fn allocate(&mut self) -> usize {\n\n todo!()\n\n }\n", "file_path": "qsharp/tests/arrays.rs", "rank": 60, "score": 68898.96463392254 }, { "content": "#[derive(Default)]\n\nstruct ToffoliSimulator {\n\n state: FixedBitSet,\n\n num_qubits: usize,\n\n free_list: Vec<usize>,\n\n}\n\n\n\nimpl ToffoliSimulator {\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n}\n\n\n\nimpl QSharpIntrinsics for ToffoliSimulator {\n\n fn x(&mut self, q: usize) {\n\n self.state.toggle(q);\n\n }\n\n\n\n fn y(&mut self, _q: usize) {\n\n panic!(\"cannot simulate non-classical quantum instruction\");\n\n }\n", "file_path": "qsharp/tests/integer.rs", "rank": 61, "score": 68898.96463392254 }, { "content": "#[derive(Debug, Clone, Copy)]\n\nenum Operator {\n\n CopyAndUpdate, // w/ <- | ternary | left | 1 |\n\n Range, // .. | infix | left | 2 |\n\n Conditional, // ? | | ternary | right | 5 |\n\n LogicalOr, // or | infix | left | 10 |\n\n LogicalOrDeprecated, // || | infix | left | 10 |\n\n LogicalAnd, // and | infix | left | 11 |\n\n LogicalAndDeprecated, // && | infix | left | 11 |\n\n BitwiseOr, // ||| | infix | left | 12 |\n\n BitwiseXor, // ^^^ | infix | left | 13 |\n\n BitwiseAnd, // &&& | infix | left | 14 |\n\n Equality, // == | infix | left | 20 |\n\n Inequality, // != | infix | left | 20 |\n\n LessThanOrEqual, // <= | infix | left | 25 |\n\n LessThan, // < | infix | left | 25 |\n\n GreaterThanOrEqual, // >= | infix | left | 25 |\n\n GreaterThan, // > | infix | left | 25 |\n\n RightShift, // >>> | infix | left | 28 |\n\n LeftShift, // <<< | infix | left | 28 |\n\n Addition, // + | infix | left | 30 |\n", "file_path": "qsharp-ast/src/ast/expression.rs", "rank": 62, "score": 68293.43896171344 }, { "content": "#[derive(Default)]\n\nstruct TestSimulator {\n\n gates: Vec<u8>,\n\n}\n\n\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 63, "score": 67981.20679674935 }, { "content": "pub trait MyIntrinsics {\n\n fn x(&mut self);\n\n fn y(&mut self);\n\n fn z(&mut self);\n\n}\n\n\n\nimpl MyIntrinsics for TestSimulator {\n\n fn x(&mut self) {\n\n self.gates.push(0);\n\n }\n\n\n\n fn y(&mut self) {\n\n self.gates.push(1);\n\n }\n\n\n\n fn z(&mut self) {\n\n self.gates.push(2);\n\n }\n\n}\n\n\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 64, "score": 60923.22890972321 }, { "content": "pub trait Mapper {\n\n type Output;\n\n\n\n fn visit_program(&mut self, program: &Program) -> Self::Output {\n\n let namespaces = program\n\n .namespaces\n\n .iter()\n\n .map(|namespace| self.visit_namespace(namespace))\n\n .collect_vec();\n\n self.map_program(&namespaces)\n\n }\n\n\n\n fn map_program(&mut self, namespaces: &[Self::Output]) -> Self::Output;\n\n\n\n fn visit_namespace(&mut self, namespace: &Namespace) -> Self::Output {\n\n let name = self.visit_qualified_name(namespace.name());\n\n let items = namespace\n\n .items\n\n .iter()\n\n .map(|item| self.visit_namespace_item(item))\n", "file_path": "qsharp-ast/src/utilities/mapper.rs", "rank": 65, "score": 60059.62490785552 }, { "content": "pub trait Transformer {\n\n fn visit_callable(&mut self, callable: Callable) -> Callable {\n\n let body = self.visit_callable_body(callable.body);\n\n\n\n Callable { body, ..callable }\n\n }\n\n\n\n fn visit_callable_body(&mut self, callable_body: CallableBody) -> CallableBody {\n\n match callable_body {\n\n CallableBody::Simple(scope) => CallableBody::Simple(self.visit_scope(scope)),\n\n CallableBody::Multiple(specializations) => CallableBody::Multiple(\n\n specializations\n\n .into_iter()\n\n .map(|specialization| self.visit_specialization(specialization))\n\n .collect(),\n\n ),\n\n }\n\n }\n\n\n\n fn visit_expression(&mut self, expression: Rc<Expression>) -> Rc<Expression> {\n", "file_path": "qsharp-ast/src/utilities/transformer.rs", "rank": 66, "score": 60059.62490785552 }, { "content": "pub trait VisitorMut {\n\n fn pre_callable(&mut self, _callable: &mut Callable) {}\n\n fn post_callable(&mut self, _callable: &mut Callable) {}\n\n fn visit_callable(&mut self, callable: &mut Callable) {\n\n self.pre_callable(callable);\n\n self.visit_callable_body(&mut callable.body);\n\n self.post_callable(callable);\n\n }\n\n\n\n fn pre_callable_body(&mut self, _callable_body: &mut CallableBody) {}\n\n fn post_callable_body(&mut self, _callable_body: &mut CallableBody) {}\n\n fn visit_callable_body(&mut self, callable_body: &mut CallableBody) {\n\n self.pre_callable_body(callable_body);\n\n match callable_body {\n\n CallableBody::Simple(scope) => self.visit_scope(scope),\n\n CallableBody::Multiple(specializations) => {\n\n for specialization in specializations {\n\n self.visit_specialization(specialization);\n\n }\n\n }\n", "file_path": "qsharp-ast/src/utilities/visitor.rs", "rank": 67, "score": 59234.13361361996 }, { "content": "pub trait QSharpIntrinsics {\n\n fn x(&mut self, q: usize);\n\n fn y(&mut self, q: usize);\n\n fn z(&mut self, q: usize);\n\n fn h(&mut self, q: usize);\n\n fn s(&mut self, q: usize);\n\n fn t(&mut self, q: usize);\n\n fn t_adj(&mut self, q: usize);\n\n fn cnot(&mut self, ctl: usize, tgt: usize);\n\n fn m(&mut self, q: usize) -> bool;\n\n\n\n fn mcx(&mut self, ctls: &[usize], q: usize);\n\n\n\n fn allocate(&mut self) -> usize;\n\n fn allocate_many(&mut self, count: usize) -> Array<usize>;\n\n fn release(&mut self, q: usize);\n\n fn release_many(&mut self, qs: Array<usize>);\n\n}\n\n\n\npub type Array<T> = Rc<Vec<T>>;\n\n\n\n//impl<T> Iterator for Array<T> {\n\n// type Item = T;\n\n//\n\n// fn next(&mut self) -> Option<Self::Item> {\n\n// todo!()\n\n// }\n\n//}\n", "file_path": "qsharp-runtime/src/types.rs", "rank": 68, "score": 59234.13361361996 }, { "content": "#[test]\n\nfn test_arithmetic() {\n\n qsharp! {\n\n namespace Arithmetic {\n\n open Microsoft.Quantum.Arrays;\n\n open Microsoft.Quantum.Diagnostics;\n\n open Microsoft.Quantum.Intrinsic;\n\n\n\n operation ApplyAnd(ctl1: Qubit, ctl2: Qubit, tgt: Qubit) : Unit is Adj {\n\n body (...) {\n\n Controlled X([ctl1, ctl2], tgt);\n\n }\n\n\n\n adjoint self;\n\n }\n\n\n\n operation Add(x : Qubit[], y : Qubit[]) : Unit is Adj+Ctl {\n\n let n = Length(x);\n\n Fact(n > 0, \"Bitwidth must be at least 1\");\n\n\n\n if Length(y) == n + 1 {\n", "file_path": "qsharp/tests/integer.rs", "rank": 69, "score": 57290.52977506345 }, { "content": "#[test]\n\nfn test_array() {\n\n qsharp! {\n\n namespace Array {\n", "file_path": "qsharp/tests/arrays.rs", "rank": 70, "score": 57290.52977506345 }, { "content": "#[test]\n\nfn test_the_answer() {\n\n let mut sim = PrintSimulator {};\n\n\n\n //Circuits::ApplyAnd(&mut sim, 0, 1, 2);\n\n\n\n Arithmetic::Carry(&mut sim, 0, 1, 2, 3);\n\n}\n", "file_path": "qsharp/tests/test.rs", "rank": 71, "score": 57290.52977506345 }, { "content": "/// Checks whether `actual` is any of `expected`, if not `None`, otherwise,\n\n/// returns `None`.\n\nfn with_type_check_in(\n\n actual: Option<Rc<TypeKind>>,\n\n expected: &[Rc<TypeKind>],\n\n) -> Option<Rc<TypeKind>> {\n\n actual.filter(|kind| expected.contains(kind))\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/expression.rs", "rank": 72, "score": 55542.07963556149 }, { "content": "/// Creates the union of two characteristics; if right-hand-side is `None`, it\n\n/// returns the left-hand-side\n\nfn characteristics_union(\n\n lhs: Rc<Characteristics>,\n\n rhs: &Option<Rc<Characteristics>>,\n\n) -> Rc<Characteristics> {\n\n if let Some(rhs) = rhs {\n\n Characteristics::union(lhs, rhs.clone())\n\n } else {\n\n lhs\n\n }\n\n}\n\n\n", "file_path": "qsharp-ast/src/analysis/expression.rs", "rank": 73, "score": 55541.15163227003 }, { "content": "#[test]\n\nfn test_sim_trait() {\n\n let mut sim = TestSimulator::default();\n\n\n\n assert!(sim.gates.is_empty());\n\n\n\n Operations::Operation(&mut sim);\n\n\n\n assert_eq!(sim.gates, vec![0, 1, 2, 1, 0]);\n\n}\n", "file_path": "qsharp/tests/sim_trait.rs", "rank": 74, "score": 55537.13106098787 }, { "content": "fn parse_expression_1(\n\n input: ParseStream,\n\n lhs: Rc<Expression>,\n\n min_precedence: u32,\n\n parse_with_index: bool,\n\n) -> Result<Rc<Expression>> {\n\n let mut lhs = lhs;\n\n\n\n let mut lookahead = peek_operator(input, parse_with_index);\n\n\n\n while let Ok(operator) = lookahead {\n\n if operator.precedence() < min_precedence {\n\n break;\n\n }\n\n let extra = operator.consume(input)?;\n\n let mut rhs = parse_primary(input, true)?;\n\n\n\n lookahead = peek_operator(input, parse_with_index);\n\n while let Ok(operator2) = lookahead {\n\n if operator2.precedence() <= operator.precedence() {\n", "file_path": "qsharp-ast/src/ast/expression.rs", "rank": 75, "score": 55537.13106098787 }, { "content": "fn expression_to_rust(\n\n expr: &Expression,\n\n mapper: &mut Codegen,\n\n is_adjoint: bool,\n\n controlled: usize,\n\n) -> proc_macro2::TokenStream {\n\n match expr {\n\n Expression::UnitValue => quote! { () },\n\n Expression::Identifier(name, type_parameters) => {\n\n // TODO use QualifiedName's to_rust function\n\n let mut name = name.join(\"::\");\n\n assert!(controlled <= 1);\n\n if controlled == 1 {\n\n name += \"_ctl\";\n\n }\n\n if is_adjoint {\n\n name += \"_adj\";\n\n }\n\n let name = format_ident!(\"{}\", name);\n\n\n", "file_path": "qsharp-codegen/src/codegen/expression.rs", "rank": 76, "score": 55537.13106098787 }, { "content": "fn generate_parameters_directly(\n\n parameter: &Rc<Parameter>,\n\n mapper: &mut impl Mapper<Output = proc_macro2::TokenStream>,\n\n) -> proc_macro2::TokenStream {\n\n let (names, kind) = unzip_parameters(parameter);\n\n\n\n let names = tokenize_tree(&names, mapper);\n\n let kind = tokenize_tree(&kind, mapper);\n\n\n\n quote! { #names: #kind }\n\n}\n\n\n\n#[derive(Debug, PartialEq)]\n\npub(crate) enum Tree<T> {\n\n Leaf(T),\n\n Branch(Vec<Tree<T>>),\n\n}\n\n\n\nimpl<T> Tree<T> {\n\n pub fn leaf(element: impl Into<T>) -> Self {\n", "file_path": "qsharp-codegen/src/codegen/callable.rs", "rank": 77, "score": 54718.46765480915 }, { "content": "use syn::{\n\n braced,\n\n parse::{Parse, ParseStream},\n\n Result,\n\n};\n\n\n\nuse crate::{\n\n ast::Statement,\n\n utilities::{AdjointTransformer, ControlledTransformer, Transformer},\n\n};\n\n\n\nuse super::utilities::parse_many;\n\n\n\n/// A Q# scope is a sequence of Q# statements inside `{ ... }`\n\n#[derive(Debug, Default, PartialEq, Clone)]\n\npub struct Scope {\n\n pub(crate) statements: Vec<Statement>,\n\n}\n\n\n\nimpl Scope {\n", "file_path": "qsharp-ast/src/ast/scope.rs", "rank": 78, "score": 39786.194388346594 }, { "content": " pub fn controlled(self) -> Self {\n\n ControlledTransformer {}.visit_scope(self)\n\n }\n\n}\n\n\n\n/// Parses scope without parsing the braces\n\npub(crate) fn parse_scope_statements(input: ParseStream) -> Result<Scope> {\n\n Ok(Scope {\n\n statements: parse_many(input)?,\n\n })\n\n}\n\n\n\nimpl Parse for Scope {\n\n fn parse(input: ParseStream) -> Result<Self> {\n\n let inner;\n\n braced!(inner in input);\n\n\n\n Ok(Self {\n\n statements: parse_many(&inner)?,\n\n })\n", "file_path": "qsharp-ast/src/ast/scope.rs", "rank": 79, "score": 39779.51995602308 }, { "content": "use std::rc::Rc;\n\n\n\nuse itertools::{Either, Itertools};\n\n\n\nuse crate::{\n\n ast::{Expression, Scope, Statement},\n\n utilities::Transformer,\n\n};\n\n\n\npub(crate) struct AdjointTransformer {}\n\n\n\nimpl Transformer for AdjointTransformer {\n\n fn visit_scope(&mut self, scope: Scope) -> Scope {\n\n let (mut statements, mut adjoints): (Vec<Statement>, Vec<Statement>) = scope\n\n .statements\n\n .into_iter()\n\n .partition_map(|statement| match statement {\n\n Statement::Let(..) | Statement::QubitAllocation(..) => {\n\n Either::Left(self.visit_statement(statement))\n\n }\n", "file_path": "qsharp-ast/src/utilities/adjoint.rs", "rank": 80, "score": 39777.21202232484 }, { "content": "use std::rc::Rc;\n\n\n\nuse crate::{\n\n ast::{Expression, Scope},\n\n utilities::Transformer,\n\n};\n\n\n\npub(crate) struct ControlledTransformer {}\n\n\n\nimpl Transformer for ControlledTransformer {\n\n fn visit_within_apply_statement(\n\n &mut self,\n\n within_scope: Scope,\n\n apply_scope: Scope,\n\n ) -> (Scope, Scope) {\n\n (within_scope, self.visit_scope(apply_scope))\n\n }\n\n\n\n fn visit_expression(&mut self, expression: Rc<Expression>) -> Rc<Expression> {\n\n if let Expression::Call(caller, args) = expression.as_ref() {\n", "file_path": "qsharp-ast/src/utilities/controlled.rs", "rank": 81, "score": 39774.13860363184 }, { "content": " }\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n\n\n use syn::Result;\n\n\n\n fn parse_scope(s: &str) -> Result<Scope> {\n\n syn::parse_str(s)\n\n }\n\n\n\n #[test]\n\n fn test_empty_scope() -> Result<()> {\n\n let scope = parse_scope(\"{}\")?;\n\n\n\n assert!(scope.statements.is_empty());\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "qsharp-ast/src/ast/scope.rs", "rank": 82, "score": 39774.12593307475 }, { "content": " pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n pub fn with_statements(statements: Vec<Statement>) -> Self {\n\n Self { statements }\n\n }\n\n\n\n pub fn statements(&self) -> &[Statement] {\n\n &self.statements\n\n }\n\n\n\n pub fn statements_mut(&mut self) -> &mut Vec<Statement> {\n\n &mut self.statements\n\n }\n\n\n\n pub fn adjoint(self) -> Self {\n\n AdjointTransformer {}.visit_scope(self)\n\n }\n\n\n", "file_path": "qsharp-ast/src/ast/scope.rs", "rank": 83, "score": 39773.26099586306 }, { "content": " _ => Either::Right(self.visit_statement(statement)),\n\n });\n\n\n\n adjoints.reverse();\n\n statements.append(&mut adjoints);\n\n\n\n Scope { statements }\n\n }\n\n\n\n fn visit_within_apply_statement(\n\n &mut self,\n\n within_scope: Scope,\n\n apply_scope: Scope,\n\n ) -> (Scope, Scope) {\n\n (within_scope, self.visit_scope(apply_scope))\n\n }\n\n\n\n fn visit_expression(&mut self, expression: Rc<Expression>) -> Rc<Expression> {\n\n if let Expression::Call(caller, args) = expression.as_ref() {\n\n Expression::call(Expression::adjoint(caller.clone()), args.clone())\n\n } else {\n\n expression\n\n }\n\n }\n\n}\n", "file_path": "qsharp-ast/src/utilities/adjoint.rs", "rank": 84, "score": 39769.1303457382 }, { "content": " let args_ctl = vec![\n\n Expression::simple_identifier(\"__ctls\"),\n\n Expression::tuple_literal(args.clone()),\n\n ];\n\n\n\n Expression::call(Expression::controlled(caller.clone()), args_ctl)\n\n } else {\n\n expression\n\n }\n\n }\n\n}\n", "file_path": "qsharp-ast/src/utilities/controlled.rs", "rank": 85, "score": 39764.024934916204 }, { "content": " pub fn operation_with_characteristics(\n\n from: Rc<Self>,\n\n to: Rc<Self>,\n\n characteristics: Rc<Characteristics>,\n\n ) -> Rc<Self> {\n\n Rc::new(Self::Operation(from, to, Some(characteristics)))\n\n }\n\n}\n\n\n\npub(crate) fn parse_type(input: ParseStream) -> Result<Rc<TypeKind>> {\n\n // TODO type parameter types\n\n if peek_and_consume(input, Token![_])? {\n\n return Ok(TypeKind::missing());\n\n }\n\n\n\n // We first derive a type prefix. This might be followed by some token\n\n // that indicates a special type, e.g., array, tuple.\n\n let mut prefix = if input.peek(syn::token::Paren) {\n\n let buffer;\n\n parenthesized!(buffer in input);\n", "file_path": "qsharp-ast/src/ast/type_kind.rs", "rank": 99, "score": 38544.87584972385 } ]
Rust
src/lib/ui/carnelian/src/app/strategies/base.rs
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
use crate::{ app::{ strategies::{framebuffer::FrameBufferAppStrategy, scenic::ScenicAppStrategy}, AppAssistantPtr, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self}, view::{ strategies::base::{FrameBufferParams, ViewStrategyParams, ViewStrategyPtr}, ViewKey, }, }; use anyhow::Error; use async_trait::async_trait; use fidl_fuchsia_input_report as hid_input_report; use fidl_fuchsia_ui_scenic::ScenicMarker; use fidl_fuchsia_ui_scenic::ScenicProxy; use fuchsia_async::{self as fasync}; use fuchsia_component::client::connect_to_service; use fuchsia_framebuffer::{FrameBuffer, FrameUsage, VSyncMessage}; use fuchsia_zircon::{Duration, Time}; use futures::{ channel::mpsc::{unbounded, UnboundedSender}, StreamExt, TryFutureExt, }; use std::{cell::RefCell, collections::HashMap, rc::Rc}; #[async_trait(?Send)] pub(crate) trait AppStrategy { async fn create_view_strategy( &self, key: ViewKey, render_options: RenderOptions, app_sender: UnboundedSender<MessageInternal>, strategy_params: ViewStrategyParams, ) -> Result<ViewStrategyPtr, Error>; fn supports_scenic(&self) -> bool; fn create_view_for_testing(&self, _: &UnboundedSender<MessageInternal>) -> Result<(), Error> { Ok(()) } fn start_services( &self, _outgoing_services_names: Vec<&'static str>, _app_sender: UnboundedSender<MessageInternal>, ) -> Result<(), Error> { Ok(()) } fn get_scenic_proxy(&self) -> Option<&ScenicProxy>; fn get_frame_buffer(&self) -> Option<FrameBufferPtr> { None } fn get_frame_buffer_size(&self) -> Option<IntSize>; fn get_pixel_size(&self) -> u32; fn get_pixel_format(&self) -> fuchsia_framebuffer::PixelFormat; fn get_linear_stride_bytes(&self) -> u32; async fn post_setup( &mut self, _pixel_format: fuchsia_framebuffer::PixelFormat, _internal_sender: &InternalSender, ) -> Result<(), Error>; fn handle_input_report( &mut self, _device_id: &input::DeviceId, _input_report: &hid_input_report::InputReport, ) -> Vec<input::Event> { Vec::new() } fn handle_register_input_device( &mut self, _device_id: &input::DeviceId, _device_descriptor: &hid_input_report::DeviceDescriptor, ) { } } pub(crate) type AppStrategyPtr = Box<dyn AppStrategy>; pub(crate) async fn create_app_strategy( assistant: &AppAssistantPtr, next_view_key: ViewKey, internal_sender: &InternalSender, ) -> Result<AppStrategyPtr, Error> { let render_options = assistant.get_render_options(); let usage = if render_options.use_spinel { FrameUsage::Gpu } else { FrameUsage::Cpu }; let (sender, mut receiver) = unbounded::<VSyncMessage>(); let fb = FrameBuffer::new(usage, None, Some(sender)).await; if fb.is_err() { let scenic = connect_to_service::<ScenicMarker>()?; Ok::<AppStrategyPtr, Error>(Box::new(ScenicAppStrategy { scenic })) } else { let fb = fb.unwrap(); let vsync_interval = Duration::from_nanos(100_000_000_000 / fb.get_config().refresh_rate_e2 as i64); let vsync_internal_sender = internal_sender.clone(); fasync::Task::local( async move { while let Some(VSyncMessage { display_id: _, timestamp, cookie, .. }) = receiver.next().await { vsync_internal_sender .unbounded_send(MessageInternal::HandleVSyncParametersChanged( Time::from_nanos(timestamp as i64), vsync_interval, cookie, )) .expect("unbounded_send"); vsync_internal_sender .unbounded_send(MessageInternal::RenderAllViews) .expect("unbounded_send"); } Ok(()) } .unwrap_or_else(|e: anyhow::Error| { println!("error {:#?}", e); }), ) .detach(); let config = fb.get_config(); let size = IntSize::new(config.width as i32, config.height as i32); let frame_buffer_ptr = Rc::new(RefCell::new(fb)); let strat = FrameBufferAppStrategy { frame_buffer: frame_buffer_ptr.clone(), view_key: next_view_key, input_report_handlers: HashMap::new(), }; internal_sender .unbounded_send(MessageInternal::CreateView(ViewStrategyParams::FrameBuffer( FrameBufferParams { frame_buffer: frame_buffer_ptr, pixel_format: strat.get_pixel_format(), size, }, ))) .unwrap_or_else(|err| panic!("unbounded send failed: {}", err)); Ok(Box::new(strat)) } }
use crate::{ app::{ strategies::{framebuffer::FrameBufferAppStrategy, scenic::ScenicAppStrategy}, AppAssistantPtr, FrameBufferPtr, InternalSender, MessageInternal, RenderOptions, }, geometry::IntSize, input::{self}, view::{ strategies::base::{FrameBufferParams, ViewStrategyParams, ViewStrategyPtr}, ViewKey, }, }; use anyhow::Error; use async_trait::async_trait; use fidl_fuchsia_input_report as hid_input_report; use fidl_fuchsia_ui_scenic::ScenicMarker; use fidl_fuchsia_ui_scenic::ScenicProxy; use fuchsia_async::{self as fasync}; use fuchsia_component::client::connect_to_service; use fuchsia_framebuffer::{FrameBuffer, FrameUsage, VSyncMessage}; use fuchsia_zircon::{Duration, Time}; use futures::{ channel::mpsc::{unbounded, UnboundedSender}, StreamExt, TryFutureExt, }; use std::{cell::RefCell, collections::HashMap, rc::Rc}; #[async_trait(?Send)] pub(crate) trait AppStrategy { async fn create_view_strategy( &self, key: ViewKey, render_options: RenderOptions, app_sender: UnboundedSender<MessageInternal>, strategy_params: ViewStrategyParams, ) -> Result<ViewStrategyPtr, Error>; fn supports_scenic(&self) -> bool; fn create_view_for_testing(&self, _: &UnboundedSender<MessageInternal>) -> Result<(), Error> { Ok(()) } fn start_services( &self, _outgoing_services_names: Vec<&'static str>, _app_sender: UnboundedSender<MessageInternal>, ) -> Result<(), Error> { Ok(()) } fn get_scenic_proxy(&self) -> Option<&ScenicProxy>; fn get_frame_buffer(&self) -> Option<FrameBufferPtr> { None } fn get_frame_buffer_size(&self) -> Option<IntSize>; fn get_pixel_size(&self) -> u32; fn get_pixel_format(&self) -> fuchsia_framebuffer::PixelFormat; fn get_linear_stride_bytes(&self) -> u32; async fn post_setup( &mut self, _pixel_format: fuchsia_framebuffer::PixelFormat, _internal_sender: &InternalSender, ) -> Result<(), Error>; fn handle_input_report( &mut self, _device_id: &input::DeviceId, _input_report: &hid_input_report::InputReport, ) -> Vec<input::Event> { Vec::new() } fn handle_register_input_device( &mut self, _device_id: &input::DeviceId, _device_descriptor: &hid_input_report::DeviceDescriptor, ) { } } pub(crate) type AppStrategyPtr = Box<dyn AppStrategy>;
pub(crate) async fn create_app_strategy( assistant: &AppAssistantPtr, next_view_key: ViewKey, internal_sender: &InternalSender, ) -> Result<AppStrategyPtr, Error> { let render_options = assistant.get_render_options(); let usage = if render_options.use_spinel { FrameUsage::Gpu } else { FrameUsage::Cpu }; let (sender, mut receiver) = unbounded::<VSyncMessage>(); let fb = FrameBuffer::new(usage, None, Some(sender)).await; if fb.is_err() { let scenic = connect_to_service::<ScenicMarker>()?; Ok::<AppStrategyPtr, Error>(Box::new(ScenicAppStrategy { scenic })) } else { let fb = fb.unwrap(); let vsync_interval = Duration::from_nanos(100_000_000_000 / fb.get_config().refresh_rate_e2 as i64); let vsync_internal_sender = internal_sender.clone(); fasync::Task::local( async move { while let Some(VSyncMessage { display_id: _, timestamp, cookie, .. }) = receiver.next().await { vsync_internal_sender .unbounded_send(MessageInternal::HandleVSyncParametersChanged( Time::from_nanos(timestamp as i64), vsync_interval, cookie, )) .expect("unbounded_send"); vsync_internal_sender .unbounded_send(MessageInternal::RenderAllViews) .expect("unbounded_send"); } Ok(()) } .unwrap_or_else(|e: anyhow::Error| { println!("error {:#?}", e); }), ) .detach(); let config = fb.get_config(); let size = IntSize::new(config.width as i32, config.height as i32); let frame_buffer_ptr = Rc::new(RefCell::new(fb)); let strat = FrameBufferAppStrategy { frame_buffer: frame_buffer_ptr.clone(), view_key: next_view_key, input_report_handlers: HashMap::new(), }; internal_sender .unbounded_send(MessageInternal::CreateView(ViewStrategyParams::FrameBuffer( FrameBufferParams { frame_buffer: frame_buffer_ptr, pixel_format: strat.get_pixel_format(), size, }, ))) .unwrap_or_else(|err| panic!("unbounded send failed: {}", err)); Ok(Box::new(strat)) } }
function_block-full_function
[]
Rust
mailin/src/smtp.rs
trevyn/mailin
368bfe2b97b94ca19b9234d05ba0030cfacc6b3f
use std::net::IpAddr; use std::str; use crate::fsm::StateMachine; use crate::response::*; use crate::{AuthMechanism, Handler}; use either::{Left, Right}; #[derive(Clone)] pub enum Cmd<'a> { Ehlo { domain: &'a str, }, Helo { domain: &'a str, }, Mail { reverse_path: &'a str, is8bit: bool, }, Rcpt { forward_path: &'a str, }, Data, Rset, Noop, StartTls, Quit, Vrfy, AuthPlain { authorization_id: String, authentication_id: String, password: String, }, AuthPlainEmpty, AuthResponse { response: &'a [u8], }, DataEnd, StartedTls, } pub(crate) struct Credentials { pub authorization_id: String, pub authentication_id: String, pub password: String, } pub struct Session<H: Handler> { name: String, handler: H, fsm: StateMachine, } #[derive(Clone)] pub struct SessionBuilder { name: String, start_tls_extension: bool, auth_mechanisms: Vec<AuthMechanism>, } impl SessionBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), start_tls_extension: false, auth_mechanisms: Vec::with_capacity(4), } } pub fn enable_start_tls(&mut self) -> &mut Self { self.start_tls_extension = true; self } pub fn enable_auth(&mut self, auth: AuthMechanism) -> &mut Self { self.auth_mechanisms.push(auth); self } pub fn build<H: Handler>(&self, remote: IpAddr, handler: H) -> Session<H> { Session { name: self.name.clone(), handler, fsm: StateMachine::new( remote, self.auth_mechanisms.clone(), self.start_tls_extension, ), } } } impl<H: Handler> Session<H> { pub fn greeting(&self) -> Response { Response::dynamic(220, format!("{} ESMTP", self.name), Vec::new()) } pub fn tls_active(&mut self) { self.command(Cmd::StartedTls); } pub fn process(&mut self, line: &[u8]) -> Response { let response = match self.fsm.process_line(&mut self.handler, line) { Left(cmd) => self.command(cmd), Right(res) => res, }; response.log(); response } fn command(&mut self, cmd: Cmd) -> Response { self.fsm.command(&mut self.handler, cmd) } } #[cfg(test)] mod tests { use super::*; use crate::fsm::SmtpState; use std::net::Ipv4Addr; use ternop::ternary; struct EmptyHandler {} impl Handler for EmptyHandler {} struct DataHandler(Vec<u8>); impl Handler for DataHandler { fn data(&mut self, buf: &[u8]) -> std::io::Result<()> { self.0.extend(buf); Ok(()) } } macro_rules! assert_state { ($val:expr, $n:pat ) => {{ assert!( match $val { $n => true, _ => false, }, "{:?} !~ {}", $val, stringify!($n) ) }}; } fn new_session() -> Session<EmptyHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); SessionBuilder::new("some.name").build(addr, EmptyHandler {}) } fn new_data_session() -> Session<DataHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); SessionBuilder::new("some.name").build(addr, DataHandler(vec![])) } #[test] fn helo_ehlo() { let mut session = new_session(); let res1 = session.process(b"helo a.domain\r\n"); assert_eq!(res1.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); let res2 = session.process(b"ehlo b.domain\r\n"); assert_eq!(res2.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn mail_from() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Mail); } #[test] fn domain_badchars() { let mut session = new_session(); let res = session.process(b"helo world\x40\xff\r\n"); assert_eq!(res.code, 500); assert_state!(session.fsm.current_state(), SmtpState::Idle); } #[test] fn rcpt_to() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res1 = session.process(b"rcpt to:<[email protected]>\r\n"); assert_eq!(res1.code, 250); let res2 = session.process(b"rcpt to:<[email protected]>\r\n"); assert_eq!(res2.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Rcpt); } #[test] fn data() { let mut session = new_data_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello World\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); assert_eq!(&session.handler.0, b"Hello World\r\n"); } #[test] fn dot_stuffed_data() { let mut session = new_data_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello World\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b"..\r\n"); assert_eq!(res3.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); assert_eq!(&session.handler.0, b"Hello World\r\n.\r\n"); } #[test] fn data_8bit() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]> body=8bitmime\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello 8bit world \x40\x7f\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn rset_hello() { let mut session = new_session(); session.process(b"helo some.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn rset_idle() { let mut session = new_session(); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Idle); } #[test] fn quit() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res = session.process(b"quit\r\n"); assert_eq!(res.code, 221); assert_eq!(res.action, Action::Close); assert_state!(session.fsm.current_state(), SmtpState::Invalid); } #[test] fn vrfy() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); let res1 = session.process(b"vrfy kraken\r\n"); assert_eq!(res1.code, 252); assert_state!(session.fsm.current_state(), SmtpState::Hello); session.process(b"mail from:<[email protected]>\r\n"); let res2 = session.process(b"vrfy boat\r\n"); assert_eq!(res2.code, 503); assert_state!(session.fsm.current_state(), SmtpState::Mail); } struct AuthHandler {} impl Handler for AuthHandler { fn auth_plain( &mut self, authorization_id: &str, authentication_id: &str, password: &str, ) -> Response { ternary!( authorization_id == "test" && authentication_id == "test" && password == "1234", AUTH_OK, INVALID_CREDENTIALS ) } } fn new_auth_session(with_start_tls: bool) -> Session<AuthHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let mut builder = SessionBuilder::new("some.domain"); builder.enable_auth(AuthMechanism::Plain); if with_start_tls { builder.enable_start_tls(); } builder.build(addr, AuthHandler {}) } fn start_tls(session: &mut Session<AuthHandler>) { let res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); let res = session.process(b"starttls\r\n"); assert_eq!(res.code, 220); session.tls_active(); } #[test] fn noauth_denied() { let mut session = new_auth_session(true); session.process(b"ehlo a.domain\r\n"); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 503); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn auth_plain_param() { let mut session = new_auth_session(true); start_tls(&mut session); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn bad_auth_plain_param() { let mut session = new_auth_session(true); start_tls(&mut session); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain eGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 535); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn auth_plain_challenge() { let mut session = new_auth_session(true); start_tls(&mut session); let res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); let res = session.process(b"auth plain\r\n"); assert_eq!(res.code, 334); if res != EMPTY_AUTH_CHALLENGE { panic!("Server did not send empty challenge"); } assert_state!(session.fsm.current_state(), SmtpState::Auth); let res = session.process(b"dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn auth_without_tls() { let mut session = new_auth_session(true); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 503); } #[test] fn bad_auth_plain_challenge() { let mut session = new_auth_session(true); start_tls(&mut session); session.process(b"ehlo a.domain\r\n"); session.process(b"auth plain\r\n"); let res = session.process(b"eGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 535); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn rset_with_auth() { let mut session = new_auth_session(true); start_tls(&mut session); let res = session.process(b"ehlo some.domain\r\n"); assert_eq!(res.code, 250); let res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 250); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } }
use std::net::IpAddr; use std::str; use crate::fsm::StateMachine; use crate::response::*; use crate::{AuthMechanism, Handler}; use either::{Left, Right}; #[derive(Clone)] pub enum Cmd<'a> { Ehlo { domain: &'a str, }, Helo { domain: &'a str, }, Mail { reverse_path: &'a str, is8bit: bool, }, Rcpt { forward_path: &'a str, }, Data, Rset, Noop, StartTls, Quit, Vrfy, AuthPlain { authorization_id: String, authentication_id: String, password: String, }, AuthPlainEmpty, AuthResponse { response: &'a [u8], }, DataEnd, StartedTls, } pub(crate) struct Credentials { pub authorization_id: String, pub authentication_id: String, pub password: String, } pub struct Session<H: Handler> { name: String, handler: H, fsm: StateMachine, } #[derive(Clone)] pub struct SessionBuilder { name: String, start_tls_extension: bool, auth_mechanisms: Vec<AuthMechanism>, } impl SessionBuilder { pub fn new<S: Into<String>>(name: S) -> Self { Self { name: name.into(), start_tls_extension: false, auth_mech
dr; use ternop::ternary; struct EmptyHandler {} impl Handler for EmptyHandler {} struct DataHandler(Vec<u8>); impl Handler for DataHandler { fn data(&mut self, buf: &[u8]) -> std::io::Result<()> { self.0.extend(buf); Ok(()) } } macro_rules! assert_state { ($val:expr, $n:pat ) => {{ assert!( match $val { $n => true, _ => false, }, "{:?} !~ {}", $val, stringify!($n) ) }}; } fn new_session() -> Session<EmptyHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); SessionBuilder::new("some.name").build(addr, EmptyHandler {}) } fn new_data_session() -> Session<DataHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); SessionBuilder::new("some.name").build(addr, DataHandler(vec![])) } #[test] fn helo_ehlo() { let mut session = new_session(); let res1 = session.process(b"helo a.domain\r\n"); assert_eq!(res1.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); let res2 = session.process(b"ehlo b.domain\r\n"); assert_eq!(res2.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn mail_from() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Mail); } #[test] fn domain_badchars() { let mut session = new_session(); let res = session.process(b"helo world\x40\xff\r\n"); assert_eq!(res.code, 500); assert_state!(session.fsm.current_state(), SmtpState::Idle); } #[test] fn rcpt_to() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res1 = session.process(b"rcpt to:<[email protected]>\r\n"); assert_eq!(res1.code, 250); let res2 = session.process(b"rcpt to:<[email protected]>\r\n"); assert_eq!(res2.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Rcpt); } #[test] fn data() { let mut session = new_data_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello World\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); assert_eq!(&session.handler.0, b"Hello World\r\n"); } #[test] fn dot_stuffed_data() { let mut session = new_data_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello World\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b"..\r\n"); assert_eq!(res3.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); assert_eq!(&session.handler.0, b"Hello World\r\n.\r\n"); } #[test] fn data_8bit() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]> body=8bitmime\r\n"); session.process(b"rcpt to:<[email protected]>\r\n"); let res1 = session.process(b"data\r\n"); assert_eq!(res1.code, 354); let res2 = session.process(b"Hello 8bit world \x40\x7f\r\n"); assert_eq!(res2.action, Action::NoReply); let res3 = session.process(b".\r\n"); assert_eq!(res3.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn rset_hello() { let mut session = new_session(); session.process(b"helo some.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn rset_idle() { let mut session = new_session(); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::Idle); } #[test] fn quit() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); session.process(b"mail from:<[email protected]>\r\n"); let res = session.process(b"quit\r\n"); assert_eq!(res.code, 221); assert_eq!(res.action, Action::Close); assert_state!(session.fsm.current_state(), SmtpState::Invalid); } #[test] fn vrfy() { let mut session = new_session(); session.process(b"helo a.domain\r\n"); let res1 = session.process(b"vrfy kraken\r\n"); assert_eq!(res1.code, 252); assert_state!(session.fsm.current_state(), SmtpState::Hello); session.process(b"mail from:<[email protected]>\r\n"); let res2 = session.process(b"vrfy boat\r\n"); assert_eq!(res2.code, 503); assert_state!(session.fsm.current_state(), SmtpState::Mail); } struct AuthHandler {} impl Handler for AuthHandler { fn auth_plain( &mut self, authorization_id: &str, authentication_id: &str, password: &str, ) -> Response { ternary!( authorization_id == "test" && authentication_id == "test" && password == "1234", AUTH_OK, INVALID_CREDENTIALS ) } } fn new_auth_session(with_start_tls: bool) -> Session<AuthHandler> { let addr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let mut builder = SessionBuilder::new("some.domain"); builder.enable_auth(AuthMechanism::Plain); if with_start_tls { builder.enable_start_tls(); } builder.build(addr, AuthHandler {}) } fn start_tls(session: &mut Session<AuthHandler>) { let res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); let res = session.process(b"starttls\r\n"); assert_eq!(res.code, 220); session.tls_active(); } #[test] fn noauth_denied() { let mut session = new_auth_session(true); session.process(b"ehlo a.domain\r\n"); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 503); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn auth_plain_param() { let mut session = new_auth_session(true); start_tls(&mut session); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn bad_auth_plain_param() { let mut session = new_auth_session(true); start_tls(&mut session); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain eGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 535); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn auth_plain_challenge() { let mut session = new_auth_session(true); start_tls(&mut session); let res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); let res = session.process(b"auth plain\r\n"); assert_eq!(res.code, 334); if res != EMPTY_AUTH_CHALLENGE { panic!("Server did not send empty challenge"); } assert_state!(session.fsm.current_state(), SmtpState::Auth); let res = session.process(b"dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); assert_state!(session.fsm.current_state(), SmtpState::Hello); } #[test] fn auth_without_tls() { let mut session = new_auth_session(true); let mut res = session.process(b"ehlo a.domain\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 503); } #[test] fn bad_auth_plain_challenge() { let mut session = new_auth_session(true); start_tls(&mut session); session.process(b"ehlo a.domain\r\n"); session.process(b"auth plain\r\n"); let res = session.process(b"eGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 535); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } #[test] fn rset_with_auth() { let mut session = new_auth_session(true); start_tls(&mut session); let res = session.process(b"ehlo some.domain\r\n"); assert_eq!(res.code, 250); let res = session.process(b"auth plain dGVzdAB0ZXN0ADEyMzQ=\r\n"); assert_eq!(res.code, 235); let res = session.process(b"mail from:<[email protected]>\r\n"); assert_eq!(res.code, 250); let res = session.process(b"rset\r\n"); assert_eq!(res.code, 250); assert_state!(session.fsm.current_state(), SmtpState::HelloAuth); } }
anisms: Vec::with_capacity(4), } } pub fn enable_start_tls(&mut self) -> &mut Self { self.start_tls_extension = true; self } pub fn enable_auth(&mut self, auth: AuthMechanism) -> &mut Self { self.auth_mechanisms.push(auth); self } pub fn build<H: Handler>(&self, remote: IpAddr, handler: H) -> Session<H> { Session { name: self.name.clone(), handler, fsm: StateMachine::new( remote, self.auth_mechanisms.clone(), self.start_tls_extension, ), } } } impl<H: Handler> Session<H> { pub fn greeting(&self) -> Response { Response::dynamic(220, format!("{} ESMTP", self.name), Vec::new()) } pub fn tls_active(&mut self) { self.command(Cmd::StartedTls); } pub fn process(&mut self, line: &[u8]) -> Response { let response = match self.fsm.process_line(&mut self.handler, line) { Left(cmd) => self.command(cmd), Right(res) => res, }; response.log(); response } fn command(&mut self, cmd: Cmd) -> Response { self.fsm.command(&mut self.handler, cmd) } } #[cfg(test)] mod tests { use super::*; use crate::fsm::SmtpState; use std::net::Ipv4Ad
random
[ { "content": "fn handle_rset(fsm: &StateMachine, domain: &str) -> (Response, Option<Box<dyn State>>) {\n\n match fsm.auth_state {\n\n AuthState::Unavailable => (\n\n OK,\n\n Some(Box::new(Hello {\n\n domain: domain.to_string(),\n\n })),\n\n ),\n\n _ => (\n\n OK,\n\n Some(Box::new(HelloAuth {\n\n domain: domain.to_string(),\n\n })),\n\n ),\n\n }\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 0, "score": 191992.33235807752 }, { "content": "fn run<H>(name: &str, server_state: &ServerState<H>) -> Result<(), Error>\n\nwhere\n\n H: Handler + Clone + Send,\n\n{\n\n let mut pool = Pool::new(server_state.num_threads);\n\n let localaddr = server_state.listener.local_addr()?;\n\n info!(\"{} SMTP started on {}\", name, localaddr);\n\n for conn in server_state.listener.incoming() {\n\n let stream = conn?;\n\n let builder = server_state.session_builder.clone();\n\n let acceptor = server_state.ssl.clone();\n\n let handler_clone = server_state.handler.clone();\n\n pool.scoped(|scope| {\n\n scope.execute(move || handle_connection(stream, &builder, acceptor, handler_clone));\n\n });\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mailin-embedded/src/running.rs", "rank": 1, "score": 179888.58655234228 }, { "content": "fn hello_domain(buf: &[u8]) -> IResult<&[u8], &str> {\n\n map_res(is_not(b\" \\t\\r\\n\" as &[u8]), str::from_utf8)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 2, "score": 179154.87864573929 }, { "content": "fn mail_path(buf: &[u8]) -> IResult<&[u8], &str> {\n\n map_res(is_not(b\" <>\\t\\r\\n\" as &[u8]), str::from_utf8)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 3, "score": 179089.00612690934 }, { "content": "// Return a parser to match the given command\n\nfn cmd(cmd_tag: &[u8]) -> impl Fn(&[u8]) -> IResult<&[u8], (&[u8], &[u8])> + '_ {\n\n move |buf: &[u8]| pair(tag_no_case(cmd_tag), space)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 4, "score": 164669.04782680768 }, { "content": "struct Rcpt {\n\n domain: String,\n\n reverse_path: String,\n\n is8bit: bool,\n\n forward_path: Vec<String>,\n\n}\n\n\n\nimpl State for Rcpt {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Rcpt\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n", "file_path": "mailin/src/fsm.rs", "rank": 5, "score": 162769.9249317023 }, { "content": "struct Data {\n\n domain: String,\n\n}\n\n\n\nimpl State for Data {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Data\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n _fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::DataEnd => {\n\n let res = handler.data_end();\n\n transform_state(self, res, |s| Box::new(Hello { domain: s.domain }))\n", "file_path": "mailin/src/fsm.rs", "rank": 6, "score": 162769.9249317023 }, { "content": "struct Mail {\n\n domain: String,\n\n reverse_path: String,\n\n is8bit: bool,\n\n}\n\n\n\nimpl State for Mail {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Mail\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::Rcpt { forward_path } => {\n", "file_path": "mailin/src/fsm.rs", "rank": 7, "score": 162689.07961480442 }, { "content": "fn match_unstructured(header: &[u8]) -> impl Fn(&[u8]) -> IResult<&[u8], &[u8]> + '_ {\n\n move |buf: &[u8]| {\n\n let value_parser = preceded(match_header_key(header), unstructured_value);\n\n terminated(value_parser, tag(b\"\\r\\n\"))(buf)\n\n }\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 8, "score": 160848.10579510863 }, { "content": "fn match_header_key(header: &[u8]) -> impl Fn(&[u8]) -> IResult<&[u8], &[u8]> + '_ {\n\n move |buf: &[u8]| terminated(tag_no_case(header), colon_space)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 9, "score": 159163.91993032233 }, { "content": "fn handle_connection<H: Handler>(\n\n stream: TcpStream,\n\n session_builder: &SessionBuilder,\n\n ssl: Option<SslImpl>,\n\n handler: H,\n\n) {\n\n let remote = stream\n\n .peer_addr()\n\n .map(|saddr| saddr.ip())\n\n .unwrap_or_else(|_| \"0.0.0.0\".parse().unwrap());\n\n debug!(\"New connection from {}\", remote);\n\n stream.set_read_timeout(Some(*FIVE_MINUTES)).ok();\n\n stream.set_write_timeout(Some(*FIVE_MINUTES)).ok();\n\n let bufstream = BufStream::new(stream);\n\n if let Err(err) = start_session(session_builder, remote, bufstream, ssl, handler) {\n\n error!(\"({}) {}\", remote, err);\n\n }\n\n}\n", "file_path": "mailin-embedded/src/running.rs", "rank": 10, "score": 156921.94694690855 }, { "content": "fn start_session<H: Handler>(\n\n session_builder: &SessionBuilder,\n\n remote: IpAddr,\n\n mut stream: BufStream<TcpStream>,\n\n ssl: Option<SslImpl>,\n\n handler: H,\n\n) -> Result<(), Error> {\n\n let mut session = session_builder.build(remote, handler);\n\n write_response(&mut stream, &session.greeting())?;\n\n let res = handle_session(&mut session, &mut stream)?;\n\n if let SessionResult::UpgradeTls = res {\n\n let inner_stream = stream\n\n .into_inner()\n\n .map_err(|e| Error::with_source(\"Cannot flush original TcpStream\", e))?;\n\n let tls = upgrade_tls(inner_stream, ssl)?;\n\n session.tls_active();\n\n let mut buf_tls = BufStream::new(tls);\n\n handle_session(&mut session, &mut buf_tls)?;\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "mailin-embedded/src/running.rs", "rank": 11, "score": 156921.94694690855 }, { "content": "fn quit(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n value(Cmd::Quit, tag_no_case(b\"quit\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 12, "score": 154793.22706534195 }, { "content": "fn noop(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n value(Cmd::Noop, tag_no_case(b\"noop\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 13, "score": 154793.22706534195 }, { "content": "fn helo(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let parse_domain = preceded(cmd(b\"helo\"), hello_domain);\n\n map(parse_domain, |domain| Cmd::Helo { domain })(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 14, "score": 154774.7044675739 }, { "content": "fn rset(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n value(Cmd::Rset, tag_no_case(b\"rset\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 15, "score": 154774.7044675739 }, { "content": "fn ehlo(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let parse_domain = preceded(cmd(b\"ehlo\"), hello_domain);\n\n map(parse_domain, |domain| Cmd::Ehlo { domain })(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 16, "score": 154774.7044675739 }, { "content": "fn data(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n value(Cmd::Data, tag_no_case(b\"data\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 17, "score": 154734.62587916804 }, { "content": "fn rcpt(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let preamble = pair(cmd(b\"rcpt\"), tag_no_case(b\"to:<\"));\n\n let mail_path_parser = preceded(preamble, mail_path);\n\n let parser = terminated(mail_path_parser, tag(b\">\"));\n\n map(parser, |path| Cmd::Rcpt { forward_path: path })(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 18, "score": 154734.62587916804 }, { "content": "fn mail(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let preamble = pair(cmd(b\"mail\"), tag_no_case(b\"from:<\"));\n\n let mail_path_parser = preceded(preamble, mail_path);\n\n let parser = separated_pair(mail_path_parser, tag(b\">\"), is8bitmime);\n\n map(parser, |r| Cmd::Mail {\n\n reverse_path: r.0,\n\n is8bit: r.1,\n\n })(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 19, "score": 154666.65530076792 }, { "content": "fn is8bitmime(buf: &[u8]) -> IResult<&[u8], bool> {\n\n body_eq_8bit(buf).or(Ok((buf, false)))\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 20, "score": 154463.73751996105 }, { "content": "fn take_all(buf: &[u8]) -> IResult<&[u8], &str> {\n\n map_res(is_not(b\"\\r\\n\" as &[u8]), str::from_utf8)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 21, "score": 153905.97812865305 }, { "content": "fn is_base64(chr: u8) -> bool {\n\n is_alphanumeric(chr) || (chr == b'+') || (chr == b'/' || chr == b'=')\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 22, "score": 151123.9495940315 }, { "content": "fn body_eq_8bit(buf: &[u8]) -> IResult<&[u8], bool> {\n\n let preamble = pair(space, tag_no_case(b\"body=\"));\n\n let is8bit = alt((\n\n value(true, tag_no_case(b\"8bitmime\")),\n\n value(false, tag_no_case(b\"7bit\")),\n\n ));\n\n preceded(preamble, is8bit)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 23, "score": 149670.31057156355 }, { "content": "fn ctl(c: u8) -> bool {\n\n c == b'\\r' || c == b'\\n'\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 24, "score": 148221.94786534485 }, { "content": "fn tspecial(c: u8) -> bool {\n\n c == b'('\n\n || c == b')'\n\n || c == b'<'\n\n || c == b'>'\n\n || c == b'@'\n\n || c == b','\n\n || c == b';'\n\n || c == b':'\n\n || c == b'\\\\'\n\n || c == b'\"'\n\n || c == b'/'\n\n || c == b'['\n\n || c == b']'\n\n || c == b'?'\n\n || c == b'='\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 25, "score": 148221.94786534485 }, { "content": "fn is_content(content_type: &Option<ContentType>, check_is: &[u8]) -> bool {\n\n content_type\n\n .as_ref()\n\n .filter(|c| match &c.mime_type {\n\n Mime::Type(m) => m.as_slice() == check_is,\n\n _ => false,\n\n })\n\n .is_some()\n\n}\n", "file_path": "mime-event/src/message_handler.rs", "rank": 26, "score": 148064.73537821684 }, { "content": "// Parse an authentication response from the client\n\npub fn parse_auth_response(line: &[u8]) -> Result<&[u8], Response> {\n\n auth_response(line).map(|r| r.1).map_err(|_| SYNTAX_ERROR)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 27, "score": 144409.55793620044 }, { "content": "fn parameter_map<'a>(key: &'a str, value: &str) -> HashMap<&'a [u8], Vec<u8>> {\n\n let mut ret = HashMap::new();\n\n ret.insert(key.as_bytes(), value.as_bytes().to_vec());\n\n ret\n\n}\n", "file_path": "mime-event/tests/events.rs", "rank": 28, "score": 143981.7925420932 }, { "content": "fn next_string(it: &mut dyn Iterator<Item = &[u8]>) -> String {\n\n it.next()\n\n .map(|s| str::from_utf8(s).unwrap_or_default())\n\n .unwrap_or_default()\n\n .to_owned()\n\n}\n\n\n\n//---- Tests --------------------------------------------------------------------\n\n\n\nmod tests {\n\n #[allow(unused_imports)]\n\n use super::*;\n\n\n\n #[test]\n\n fn auth_initial() {\n\n let res = parse(b\"auth plain dGVzdAB0ZXN0ADEyMzQ=\\r\\n\");\n\n match res {\n\n Ok(Cmd::AuthPlain {\n\n authorization_id,\n\n authentication_id,\n", "file_path": "mailin/src/parser.rs", "rank": 29, "score": 137153.05648960263 }, { "content": "fn starttls(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n value(Cmd::StartTls, tag_no_case(b\"starttls\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 30, "score": 132858.83002659574 }, { "content": "fn vrfy(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let preamble = preceded(cmd(b\"vrfy\"), take_all);\n\n value(Cmd::Vrfy, preamble)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 31, "score": 132858.83002659574 }, { "content": "// Parse a line from the client\n\npub fn parse(line: &[u8]) -> Result<Cmd, Response> {\n\n command(line).map(|r| r.1).map_err(|e| match e {\n\n nom::Err::Incomplete(_) => MISSING_PARAMETER,\n\n nom::Err::Error(_) => SYNTAX_ERROR,\n\n nom::Err::Failure(_) => SYNTAX_ERROR,\n\n })\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 32, "score": 132449.27094583365 }, { "content": "fn quoted_string(buf: &[u8]) -> IResult<&[u8], Vec<u8>> {\n\n let qs = preceded(tag(b\"\\\"\"), in_quotes);\n\n terminated(qs, tag(b\"\\\"\"))(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 33, "score": 130752.71578823894 }, { "content": "fn parse_message<'a>(message: &[u8], handler: TestHandler<'a>) -> io::Result<TestHandler<'a>> {\n\n let writer = io::sink();\n\n let mut parser = EventParser::new(writer, handler);\n\n for line in message.split(|ch| *ch == b'\\n') {\n\n let mut buf = line.to_vec();\n\n buf.extend_from_slice(b\"\\r\\n\");\n\n parser.write_all(&buf)?;\n\n }\n\n Ok(parser.end())\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 34, "score": 127058.18980189944 }, { "content": "/// A `Handler` makes decisions about incoming mail commands.\n\n///\n\n/// A Handler implementation must be provided by code using the mailin library.\n\n///\n\n/// All methods have a default implementation that does nothing. A separate handler instance\n\n/// should be created for each connection.\n\n///\n\n/// # Examples\n\n/// ```\n\n/// # use mailin::{Handler, Response};\n\n/// # use mailin::response::{OK, BAD_HELLO, NO_MAILBOX};\n\n///\n\n/// # use std::net::IpAddr;\n\n/// # struct MyHandler{};\n\n/// impl Handler for MyHandler {\n\n/// fn helo(&mut self, ip: IpAddr, domain: &str) -> Response {\n\n/// if domain == \"this.is.spam.com\" {\n\n/// OK\n\n/// } else {\n\n/// BAD_HELLO\n\n/// }\n\n/// }\n\n///\n\n/// fn rcpt(&mut self, to: &str) -> Response {\n\n/// if to == \"alienscience\" {\n\n/// OK\n\n/// } else {\n\n/// NO_MAILBOX\n\n/// }\n\n/// }\n\n/// }\n\n/// ```\n\npub trait Handler {\n\n /// Called when a client sends a ehlo or helo message\n\n fn helo(&mut self, _ip: IpAddr, _domain: &str) -> Response {\n\n response::OK\n\n }\n\n\n\n /// Called when a mail message is started\n\n fn mail(&mut self, _ip: IpAddr, _domain: &str, _from: &str) -> Response {\n\n response::OK\n\n }\n\n\n\n /// Called when a mail recipient is set\n\n fn rcpt(&mut self, _to: &str) -> Response {\n\n response::OK\n\n }\n\n\n\n /// Called when a data command is received\n\n fn data_start(\n\n &mut self,\n\n _domain: &str,\n", "file_path": "mailin/src/lib.rs", "rank": 35, "score": 121986.68038817968 }, { "content": "#[derive(Clone)]\n\nstruct Handler<'a> {\n\n mxdns: &'a MxDns,\n\n statsd: Option<&'a statsd::Client>,\n\n mailstore: MailStore,\n\n}\n\n\n\nimpl<'a> mailin_embedded::Handler for Handler<'a> {\n\n fn helo(&mut self, ip: IpAddr, _domain: &str) -> Response {\n\n self.incr_stat(\"helo\");\n\n if ip == Ipv4Addr::new(127, 0, 0, 1) {\n\n return OK;\n\n }\n\n // Does the reverse DNS match the forward dns?\n\n let rdns = self.mxdns.fcrdns(ip);\n\n match rdns {\n\n Ok(ref res) if !res.is_confirmed() => {\n\n self.incr_stat(\"fail.fcrdns\");\n\n BAD_HELLO\n\n }\n\n _ => {\n", "file_path": "mailin-server/src/main.rs", "rank": 36, "score": 121613.25120913907 }, { "content": "pub fn slurp<P>(path: P) -> Result<Vec<u8>, Error>\n\nwhere\n\n P: AsRef<Path> + Display,\n\n{\n\n let mut file =\n\n File::open(&path).map_err(|e| Error::with_source(format!(\"Cannot open {}\", path), e))?;\n\n let mut ret = Vec::with_capacity(1024);\n\n file.read_to_end(&mut ret)?;\n\n Ok(ret)\n\n}\n", "file_path": "mailin-embedded/src/ossl.rs", "rank": 37, "score": 120415.40172113379 }, { "content": "/// A Handler receives parser events\n\npub trait Handler {\n\n /// Method that receives parser events\n\n fn event(&mut self, ev: Event);\n\n}\n\n\n", "file_path": "mime-event/src/parser.rs", "rank": 38, "score": 119669.75426711501 }, { "content": "struct ServerState<H>\n\nwhere\n\n H: Handler + Clone + Send,\n\n{\n\n listener: TcpListener,\n\n handler: H,\n\n session_builder: SessionBuilder,\n\n ssl: Option<SslImpl>,\n\n num_threads: u32,\n\n}\n\n\n\npub(crate) fn serve<H>(config: Server<H>) -> Result<(), Error>\n\nwhere\n\n H: Handler + Clone + Send,\n\n{\n\n let mut session_builder = SessionBuilder::new(config.name.clone());\n\n if config.ssl.is_some() {\n\n session_builder.enable_start_tls();\n\n }\n\n for auth in &config.auth {\n", "file_path": "mailin-embedded/src/running.rs", "rank": 39, "score": 117493.91480844206 }, { "content": "fn handle_helo(\n\n current: Box<dyn State>,\n\n fsm: &StateMachine,\n\n handler: &mut dyn Handler,\n\n domain: &str,\n\n) -> (Response, Option<Box<dyn State>>) {\n\n match fsm.auth_state {\n\n AuthState::Unavailable => {\n\n let res = handler.helo(fsm.ip, domain);\n\n next_state(current, res, || {\n\n Box::new(Hello {\n\n domain: domain.to_owned(),\n\n })\n\n })\n\n }\n\n _ => {\n\n // If authentication is required the client should be using EHLO\n\n (BAD_HELLO, Some(current))\n\n }\n\n }\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 40, "score": 116281.6135012315 }, { "content": "fn handle_ehlo(\n\n current: Box<dyn State>,\n\n fsm: &StateMachine,\n\n handler: &mut dyn Handler,\n\n domain: &str,\n\n) -> (Response, Option<Box<dyn State>>) {\n\n let mut res = handler.helo(fsm.ip, domain);\n\n if res.code == 250 {\n\n res = fsm.ehlo_response();\n\n }\n\n match fsm.auth_state {\n\n AuthState::Unavailable => next_state(current, res, || {\n\n Box::new(Hello {\n\n domain: domain.to_owned(),\n\n })\n\n }),\n\n AuthState::RequiresAuth | AuthState::Authenticated => next_state(current, res, || {\n\n Box::new(HelloAuth {\n\n domain: domain.to_owned(),\n\n })\n\n }),\n\n }\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 41, "score": 116281.6135012315 }, { "content": "fn default_handler(\n\n current: Box<dyn State>,\n\n fsm: &StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: &Cmd,\n\n) -> (Response, Option<Box<dyn State>>) {\n\n match *cmd {\n\n Cmd::Quit => (GOODBYE, None),\n\n Cmd::Helo { domain } => handle_helo(current, fsm, handler, domain),\n\n Cmd::Ehlo { domain } => handle_ehlo(current, fsm, handler, domain),\n\n _ => unhandled(current),\n\n }\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 42, "score": 115949.92435358217 }, { "content": "fn is_content_text(content_type: &Option<ContentType>) -> bool {\n\n content_type.is_none() || is_content(content_type, b\"text/plain\")\n\n}\n\n\n", "file_path": "mime-event/src/message_handler.rs", "rank": 43, "score": 112670.11916067044 }, { "content": "fn empty(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n Ok((buf, b\"\" as &[u8]))\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 44, "score": 112622.38824933278 }, { "content": "// Match one or more spaces\n\nfn space(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n take_while1(|b| b == b' ')(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 45, "score": 112622.38824933278 }, { "content": "fn auth_initial(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n preceded(space, take_while1(is_base64))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 46, "score": 111154.81119025702 }, { "content": "fn auth_response(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n terminated(take_while1(is_base64), tag(\"\\r\\n\"))(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 47, "score": 111154.81119025702 }, { "content": "fn space(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n take_while1(|c| c == b' ')(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 48, "score": 109756.34435168849 }, { "content": "fn token(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n take_while1(|c| c != b' ' && !tspecial(c) && !ctl(c))(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 49, "score": 109756.34435168849 }, { "content": "fn parameter(buf: &[u8]) -> IResult<&[u8], (&[u8], Vec<u8>)> {\n\n let preamble = pair(tag(b\";\"), space);\n\n let (i, attribute) = preceded(preamble, token)(buf)?;\n\n let (i, value) = preceded(tag(b\"=\"), parameter_value)(i)?;\n\n Ok((i, (attribute, value)))\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 50, "score": 109472.65180856298 }, { "content": "fn unstructured_value(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n is_not(\"\\r\\n\")(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 51, "score": 108421.79162633608 }, { "content": "fn header_key(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n take_while1(|c| c != b':' && c != b' ')(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 52, "score": 108421.79162633608 }, { "content": "fn colon_space(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n recognize(pair(tag(b\":\"), space))(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 53, "score": 108421.79162633608 }, { "content": "fn header_value_with_parameters(buf: &[u8]) -> IResult<&[u8], &[u8]> {\n\n is_not(\";\\r\\n\")(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 54, "score": 107146.49568914612 }, { "content": "fn in_quotes(buf: &[u8]) -> IResult<&[u8], Vec<u8>> {\n\n let mut ret = Vec::new();\n\n let mut i = 0;\n\n while i < buf.len() && buf[i] != b'\"' {\n\n if buf[i] == b'\\\\' {\n\n i += 1;\n\n }\n\n ret.push(buf[i]);\n\n i += 1;\n\n }\n\n Ok((&buf[i..], ret))\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 55, "score": 106699.87893584423 }, { "content": "fn parameters(buf: &[u8]) -> IResult<&[u8], HashMap<&[u8], Vec<u8>>> {\n\n fold_many0(parameter, HashMap::new, |mut acc: HashMap<_, _>, item| {\n\n acc.insert(item.0, item.1);\n\n acc\n\n })(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 56, "score": 105842.54958733983 }, { "content": "fn parameter_value(buf: &[u8]) -> IResult<&[u8], Vec<u8>> {\n\n let token_vec = map(token, |b: &[u8]| b.to_vec());\n\n alt((token_vec, quoted_string))(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 57, "score": 105424.58299865428 }, { "content": "fn auth(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n preceded(cmd(b\"auth\"), auth_plain)(buf)\n\n}\n\n\n\n//---- Helper functions ---------------------------------------------------------\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 58, "score": 104251.01937586884 }, { "content": "fn command(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n terminated(\n\n alt((\n\n helo, ehlo, mail, rcpt, data, rset, quit, vrfy, noop, starttls, auth,\n\n )),\n\n tag(b\"\\r\\n\"),\n\n )(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 59, "score": 104251.01937586884 }, { "content": "fn to(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"To\"), Header::To)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 60, "score": 102667.70783567737 }, { "content": "fn auth_plain(buf: &[u8]) -> IResult<&[u8], Cmd> {\n\n let parser = preceded(tag_no_case(b\"plain\"), alt((auth_initial, empty)));\n\n map(parser, sasl_plain_cmd)(buf)\n\n}\n\n\n", "file_path": "mailin/src/parser.rs", "rank": 61, "score": 102667.70783567737 }, { "content": "fn from(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"From\"), Header::From)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 62, "score": 102667.70783567737 }, { "content": "fn field(value: &[u8]) -> Option<Vec<u8>> {\n\n Some(value.to_vec())\n\n}\n\n\n", "file_path": "mime-event/tests/message.rs", "rank": 63, "score": 102667.70783567737 }, { "content": "fn to(to: &str) -> Event {\n\n header(Header::To(to.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 64, "score": 101571.05357538871 }, { "content": "fn from(from: &str) -> Event {\n\n header(Header::From(from.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 65, "score": 101571.05357538871 }, { "content": "fn reply_to(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Reply-To\"), Header::ReplyTo)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 66, "score": 101164.6095708964 }, { "content": "fn unstructured(buf: &[u8]) -> IResult<&[u8], Header> {\n\n let (i, key) = terminated(header_key, colon_space)(buf)?;\n\n let (i, value) = terminated(unstructured_value, tag(b\"\\r\\n\"))(i)?;\n\n Ok((i, Header::Unstructured(key, value)))\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 67, "score": 101164.6095708964 }, { "content": "fn sender(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Sender\"), Header::Sender)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 68, "score": 101164.6095708964 }, { "content": "fn date(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Date\"), Header::Date)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 69, "score": 101164.6095708964 }, { "content": "fn content(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(header_with_params(b\"Content-Type\"), |v| {\n\n Header::ContentType {\n\n mime_type: v.0,\n\n parameters: v.1,\n\n }\n\n })(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 70, "score": 101164.6095708964 }, { "content": "fn subject(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Subject\"), Header::Subject)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 71, "score": 101164.6095708964 }, { "content": "fn content_type<'a>(mime: &'a str, param_key: &'a str, param_value: &str) -> Event<'a> {\n\n Event::Header(Header::ContentType {\n\n mime_type: mime.as_bytes(),\n\n parameters: parameter_map(param_key, param_value),\n\n })\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 72, "score": 100327.10786111397 }, { "content": "fn message_id(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Message-ID\"), Header::MessageId)(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 73, "score": 99735.5779327873 }, { "content": "fn content_disposition(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(header_with_params(b\"Content-Disposition\"), |v| {\n\n Header::ContentDisposition {\n\n disposition_type: v.0,\n\n parameters: v.1,\n\n }\n\n })(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 74, "score": 99735.5779327873 }, { "content": "fn content_description(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(match_unstructured(b\"Content-Description\"), |v| {\n\n Header::ContentDescription(v)\n\n })(buf)\n\n}\n\n\n", "file_path": "mime-event/src/line_parser.rs", "rank": 75, "score": 99735.5779327873 }, { "content": "fn header_end(buf: &[u8]) -> IResult<&[u8], Header> {\n\n map(tag(b\"\\r\\n\"), |_| Header::End)(buf)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use maplit::hashmap;\n\n use pretty_assertions::assert_eq;\n\n\n\n #[test]\n\n fn unstructured_header() {\n\n let tok = header(b\"X-sender: <[email protected]>\\r\\n\").unwrap();\n\n assert_eq!(\n\n tok,\n\n Header::Unstructured(b\"X-sender\", b\"<[email protected]>\")\n\n )\n\n }\n\n\n\n #[test]\n", "file_path": "mime-event/src/line_parser.rs", "rank": 76, "score": 99735.5779327873 }, { "content": "fn unstructured_header<'a>(key: &'a str, value: &'a str) -> Event<'a> {\n\n Event::Header(Header::Unstructured(key.as_bytes(), value.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 77, "score": 98411.16312184925 }, { "content": "struct Hello {\n\n domain: String,\n\n}\n\n\n\nimpl State for Hello {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Hello\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::Mail {\n\n reverse_path,\n\n is8bit,\n", "file_path": "mailin/src/fsm.rs", "rank": 78, "score": 97721.27040093925 }, { "content": "struct Auth {\n\n domain: String,\n\n mechanism: AuthMechanism,\n\n}\n\n\n\nimpl State for Auth {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Auth\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::AuthResponse { response } => {\n\n let res = match self.mechanism {\n", "file_path": "mailin/src/fsm.rs", "rank": 79, "score": 97721.27040093925 }, { "content": "struct Idle {}\n\n\n\nimpl State for Idle {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::Idle\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::StartedTls => {\n\n fsm.tls = TlsState::Active;\n\n (EMPTY_RESPONSE, Some(self))\n\n }\n\n Cmd::Rset => (OK, Some(self)),\n\n _ => default_handler(self, fsm, handler, &cmd),\n\n }\n\n }\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 80, "score": 97721.27040093925 }, { "content": "fn body(block: &str) -> Event {\n\n Event::Body(block.as_bytes())\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 81, "score": 97576.44446274632 }, { "content": "fn subject(subject: &str) -> Event {\n\n header(Header::Subject(subject.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 82, "score": 97576.44446274632 }, { "content": "fn date(date: &str) -> Event {\n\n header(Header::Date(date.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 83, "score": 97576.44446274632 }, { "content": "enum AuthState {\n\n Unavailable,\n\n RequiresAuth,\n\n Authenticated,\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 84, "score": 95778.07420649742 }, { "content": "#[derive(PartialEq)]\n\nenum TlsState {\n\n Unavailable,\n\n Inactive,\n\n Active,\n\n}\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 85, "score": 95778.07420649742 }, { "content": "struct HelloAuth {\n\n domain: String,\n\n}\n\n\n\nimpl State for HelloAuth {\n\n #[cfg(test)]\n\n fn id(&self) -> SmtpState {\n\n SmtpState::HelloAuth\n\n }\n\n\n\n fn handle(\n\n self: Box<Self>,\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n cmd: Cmd,\n\n ) -> (Response, Option<Box<dyn State>>) {\n\n match cmd {\n\n Cmd::StartTls => (START_TLS, Some(Box::new(Idle {}))),\n\n Cmd::AuthPlain {\n\n ref authorization_id,\n", "file_path": "mailin/src/fsm.rs", "rank": 86, "score": 95268.05336657148 }, { "content": "fn ssl_builder(cert_path: String, key_path: String) -> Result<SslAcceptorBuilder, Error> {\n\n let mut builder = SslAcceptor::mozilla_modern(SslMethod::tls())?;\n\n let cert_pem = slurp(cert_path)?;\n\n let cert = X509::from_pem(&cert_pem)?;\n\n let key_pem = slurp(key_path)?;\n\n let pkey = PKey::private_key_from_pem(&key_pem)?;\n\n builder.set_private_key(&pkey)?;\n\n builder.set_certificate(&cert)?;\n\n builder.check_private_key()?;\n\n Ok(builder)\n\n}\n\n\n", "file_path": "mailin-embedded/src/ossl.rs", "rank": 87, "score": 94746.5833118255 }, { "content": "fn message_id(message_id: &str) -> Event {\n\n header(Header::MessageId(message_id.as_bytes()))\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 88, "score": 94075.04450472974 }, { "content": "#[derive(Debug, PartialEq)]\n\nenum Target {\n\n Top,\n\n TopAlternative,\n\n Alternative,\n\n FirstMixed,\n\n Attachments,\n\n Inlines,\n\n Other,\n\n}\n\n\n\nimpl Default for Target {\n\n fn default() -> Self {\n\n Target::Top\n\n }\n\n}\n\n\n\nimpl Handler for MessageHandler {\n\n fn event(&mut self, ev: Event) {\n\n match ev {\n\n Event::Start => (),\n", "file_path": "mime-event/src/message_handler.rs", "rank": 89, "score": 93728.20047053916 }, { "content": "fn sasl_plain_cmd(param: &[u8]) -> Cmd {\n\n if param.is_empty() {\n\n Cmd::AuthPlainEmpty\n\n } else {\n\n let creds = decode_sasl_plain(param);\n\n Cmd::AuthPlain {\n\n authorization_id: creds.authorization_id,\n\n authentication_id: creds.authentication_id,\n\n password: creds.password,\n\n }\n\n }\n\n}\n\n\n\n// Decodes the base64 encoded plain authentication parameter\n\npub(crate) fn decode_sasl_plain(param: &[u8]) -> Credentials {\n\n let decoded = base64::decode(param);\n\n if let Ok(bytes) = decoded {\n\n let mut fields = bytes.split(|b| b == &0u8);\n\n let authorization_id = next_string(&mut fields);\n\n let authentication_id = next_string(&mut fields);\n", "file_path": "mailin/src/parser.rs", "rank": 90, "score": 92390.77707208745 }, { "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\n\n", "file_path": "mailin-server/src/main.rs", "rank": 91, "score": 91515.64939910601 }, { "content": "pub fn join_all<I>(it: I) -> JoinAll<I::Item>\n\nwhere\n\n I: IntoIterator,\n\n I::Item: Future,\n\n I::Item: Unpin,\n\n{\n\n let state: Vec<_> = it\n\n .into_iter()\n\n .map(|fut| FutureState::Pending { fut })\n\n .collect();\n\n JoinAll { state }\n\n}\n\n\n\nimpl<F> Future for JoinAll<F>\n\nwhere\n\n F: Future,\n\n F: Unpin,\n\n{\n\n type Output = Vec<F::Output>;\n\n\n", "file_path": "mxdns/src/join_all.rs", "rank": 92, "score": 91416.1572201533 }, { "content": "struct TestHandler<'a> {\n\n current: usize,\n\n expected_events: Vec<Event<'a>>,\n\n}\n\n\n\nimpl<'a> TestHandler<'a> {\n\n fn new(expected_events: Vec<Event<'a>>) -> Self {\n\n Self {\n\n current: 0,\n\n expected_events,\n\n }\n\n }\n\n\n\n fn final_check(&self) {\n\n assert_eq!(self.current, self.expected_events.len());\n\n }\n\n}\n\n\n\nimpl<'a> Handler for TestHandler<'a> {\n\n fn event<'b>(&mut self, ev: Event) {\n\n if let Some(expected) = self.expected_events.get(self.current) {\n\n assert_eq!(*expected, ev);\n\n }\n\n self.current += 1;\n\n }\n\n}\n\n\n", "file_path": "mime-event/tests/events.rs", "rank": 93, "score": 90869.51614039823 }, { "content": "fn setup_logger(log_dir: Option<String>) -> Result<(), Error> {\n\n let log_level = LevelFilter::Info;\n\n // Try to create a terminal logger, if this fails use a simple logger to stdout\n\n let term_logger = TermLogger::new(\n\n log_level,\n\n Config::default(),\n\n TerminalMode::Stdout,\n\n ColorChoice::Auto,\n\n );\n\n // Create a trace logger that writes SMTP interaction to file\n\n if let Some(dir) = log_dir {\n\n let log_path = Path::new(&dir);\n\n let datetime = Local::now().format(\"%Y%m%d%H%M%S\").to_string();\n\n let filename = format!(\"smtp-{}.log\", datetime);\n\n let filepath = log_path.join(&filename);\n\n let file = File::create(&filepath)?;\n\n CombinedLogger::init(vec![\n\n term_logger,\n\n WriteLogger::new(LevelFilter::Trace, Config::default(), file),\n\n ])\n\n .map_err(|err| format_err!(\"Cannot initialize logger: {}\", err))\n\n } else {\n\n CombinedLogger::init(vec![term_logger])\n\n .map_err(|err| format_err!(\"Cannot initialize logger: {}\", err))\n\n }\n\n}\n\n\n", "file_path": "mailin-server/src/main.rs", "rank": 94, "score": 86901.15786442997 }, { "content": "fn load_key(filename: &str) -> Result<PrivateKey, Error> {\n\n let keyfile = fs::File::open(filename)?;\n\n let mut reader = BufReader::new(keyfile);\n\n let rsa_keys = rustls_pemfile::rsa_private_keys(&mut reader)\n\n .map_err(|_| Error::new(\"Unparseable RSA key\"))?;\n\n let keyfile = fs::File::open(filename)?;\n\n let mut reader = BufReader::new(keyfile);\n\n let pkcs8_keys = rustls_pemfile::pkcs8_private_keys(&mut reader)\n\n .map_err(|_| Error::new(\"Unparseable PKCS8 key\"))?;\n\n\n\n // Prefer to load pkcs8 keys\n\n pkcs8_keys\n\n .first()\n\n .or_else(|| rsa_keys.first())\n\n .cloned()\n\n .map(PrivateKey)\n\n .ok_or_else(|| Error::new(\"No RSA or PKCS8 keys found\"))\n\n}\n", "file_path": "mailin-embedded/src/rtls.rs", "rank": 95, "score": 86163.76783452166 }, { "content": "fn authenticate(\n\n fsm: &mut StateMachine,\n\n handler: &mut dyn Handler,\n\n authorization_id: &str,\n\n authentication_id: &str,\n\n password: &str,\n\n) -> Response {\n\n let auth_res = handler.auth_plain(authorization_id, authentication_id, password);\n\n fsm.auth_state = ternary!(\n\n auth_res.code == 235,\n\n AuthState::Authenticated,\n\n AuthState::RequiresAuth\n\n );\n\n auth_res\n\n}\n\n\n\n//------------------------------------------------------------------------------\n\n\n", "file_path": "mailin/src/fsm.rs", "rank": 96, "score": 85891.39932513192 }, { "content": "fn handle_session<H, S>(session: &mut Session<H>, stream: &mut S) -> Result<SessionResult, Error>\n\nwhere\n\n S: BufRead + Write,\n\n H: Handler,\n\n{\n\n let mut line = Vec::with_capacity(80);\n\n loop {\n\n line.clear();\n\n let num_bytes = stream.read_until(b'\\n', &mut line)?;\n\n if num_bytes == 0 {\n\n break;\n\n }\n\n let res = session.process(&line);\n\n match res.action {\n\n Action::Reply => {\n\n write_response(stream, &res)?;\n\n }\n\n Action::Close => {\n\n write_response(stream, &res)?;\n\n if res.is_error {\n", "file_path": "mailin-embedded/src/running.rs", "rank": 97, "score": 85335.08571784881 }, { "content": "fn parse_message(message: &[u8]) -> io::Result<Message> {\n\n let writer = io::sink();\n\n let mut parser = MessageParser::new(writer);\n\n for line in message.split(|ch| *ch == b'\\n') {\n\n let mut buf = line.to_vec();\n\n buf.extend_from_slice(b\"\\r\\n\");\n\n parser.write_all(&buf)?;\n\n }\n\n Ok(parser.end())\n\n}\n", "file_path": "mime-event/tests/message.rs", "rank": 98, "score": 84636.01628359783 }, { "content": "fn load_certs(filename: &str) -> Result<Vec<Certificate>, Error> {\n\n let certfile = fs::File::open(filename)?;\n\n let mut reader = BufReader::new(certfile);\n\n let ret: Vec<Certificate> = rustls_pemfile::certs(&mut reader)\n\n .map_err(|_| Error::new(\"Unparseable certificates\"))?\n\n .into_iter()\n\n .map(Certificate)\n\n .collect();\n\n Ok(ret)\n\n}\n\n\n", "file_path": "mailin-embedded/src/rtls.rs", "rank": 99, "score": 84157.45761002437 } ]
Rust
src/output.rs
sthagen/mitsuhiko-insta
c27c8bde0bbcf38da480feefdf3eba18138ef9a3
use std::{path::Path, time::Duration}; use similar::{Algorithm, ChangeTag, TextDiff}; use crate::snapshot::Snapshot; use crate::utils::{format_rust_expression, style, term_width}; pub fn print_snapshot_summary( workspace_root: &Path, snapshot: &Snapshot, snapshot_file: Option<&Path>, mut line: Option<u32>, ) { if line.is_none() { line = snapshot.metadata().assertion_line(); } if let Some(snapshot_file) = snapshot_file { let snapshot_file = workspace_root .join(snapshot_file) .strip_prefix(workspace_root) .ok() .map(|x| x.to_path_buf()) .unwrap_or_else(|| snapshot_file.to_path_buf()); println!( "Snapshot file: {}", style(snapshot_file.display()).cyan().underlined() ); } if let Some(name) = snapshot.snapshot_name() { println!("Snapshot: {}", style(name).yellow()); } else { println!("Snapshot: {}", style("<inline>").dim()); } if let Some(ref value) = snapshot.metadata().get_relative_source(workspace_root) { println!( "Source: {}{}", style(value.display()).cyan(), if let Some(line) = line { format!(":{}", style(line).bold()) } else { "".to_string() } ); } if let Some(ref value) = snapshot.metadata().input_file() { println!("Input file: {}", style(value).cyan()); } } pub fn print_snapshot_diff( workspace_root: &Path, new: &Snapshot, old_snapshot: Option<&Snapshot>, snapshot_file: Option<&Path>, mut line: Option<u32>, ) { if line.is_none() { line = new.metadata().assertion_line(); } print_snapshot_summary(workspace_root, new, snapshot_file, line); let old_contents = old_snapshot.as_ref().map_or("", |x| x.contents_str()); let new_contents = new.contents_str(); if !old_contents.is_empty() { println!("{}", style("-old snapshot").red()); println!("{}", style("+new results").green()); } else { println!("{}", style("+new results").green()); } print_changeset( old_contents, new_contents, new.metadata().expression.as_deref(), ); } pub fn print_snapshot_diff_with_title( workspace_root: &Path, new_snapshot: &Snapshot, old_snapshot: Option<&Snapshot>, line: u32, snapshot_file: Option<&Path>, ) { let width = term_width(); println!( "{title:━^width$}", title = style(" Snapshot Differences ").bold(), width = width ); print_snapshot_diff( workspace_root, new_snapshot, old_snapshot, snapshot_file, Some(line), ); } pub fn print_snapshot_summary_with_title( workspace_root: &Path, new_snapshot: &Snapshot, old_snapshot: Option<&Snapshot>, line: u32, snapshot_file: Option<&Path>, ) { let _old_snapshot = old_snapshot; let width = term_width(); println!( "{title:━^width$}", title = style(" Snapshot Summary ").bold(), width = width ); print_snapshot_summary(workspace_root, new_snapshot, snapshot_file, Some(line)); println!("{title:━^width$}", title = "", width = width); } pub fn print_changeset(old: &str, new: &str, expr: Option<&str>) { let width = term_width(); let diff = TextDiff::configure() .algorithm(Algorithm::Patience) .timeout(Duration::from_millis(500)) .diff_lines(old, new); if let Some(expr) = expr { println!("{:─^1$}", "", width,); println!("{}", style(format_rust_expression(expr))); } println!("────────────┬{:─^1$}", "", width.saturating_sub(13)); let mut has_changes = false; for (idx, group) in diff.grouped_ops(4).iter().enumerate() { if idx > 0 { println!("┈┈┈┈┈┈┈┈┈┈┈┈┼{:┈^1$}", "", width.saturating_sub(13)); } for op in group { for change in diff.iter_inline_changes(&op) { match change.tag() { ChangeTag::Insert => { has_changes = true; print!( "{:>5} {:>5} │{}", "", style(change.new_index().unwrap()).cyan().dim().bold(), style("+").green(), ); for &(emphasized, change) in change.values() { if emphasized { print!("{}", style(change).green().underlined()); } else { print!("{}", style(change).green()); } } } ChangeTag::Delete => { has_changes = true; print!( "{:>5} {:>5} │{}", style(change.old_index().unwrap()).cyan().dim(), "", style("-").red(), ); for &(emphasized, change) in change.values() { if emphasized { print!("{}", style(change).red().underlined()); } else { print!("{}", style(change).red()); } } } ChangeTag::Equal => { print!( "{:>5} {:>5} │ ", style(change.old_index().unwrap()).cyan().dim(), style(change.new_index().unwrap()).cyan().dim().bold(), ); for &(_, change) in change.values() { print!("{}", style(change).dim()); } } } if change.missing_newline() { println!(); } } } } if !has_changes { println!( "{:>5} {:>5} │{}", "", style("-").dim(), style(" snapshots are matching").cyan(), ); } println!("────────────┴{:─^1$}", "", width.saturating_sub(13),); }
use std::{path::Path, time::Duration}; use similar::{Algorithm, ChangeTag, TextDiff}; use crate::snapshot::Snapshot; use crate::utils::{format_rust_expression, style, term_width}; pub fn print_snapshot_summary( workspace_root: &Path, snapshot: &Snapshot, snapshot_file: Option<&Path>, mut line: Option<u32>, ) { if line.is_none() { line = snapshot.metadata().assertion_line(); } if let Some(snapshot_file) = snapshot_file { let snapshot_file = workspace_root .join(snapshot_file) .strip_prefix(workspace_root) .ok() .map(|x| x.to_path_buf()) .unwrap_or_else(|| snapshot_file.to_path_buf()); println!( "Snapshot file: {}", style(snapshot_file.display()).cyan().underlined() ); } if let Some(name) = snapshot.snapshot_name() { println!("Snapshot: {}", style(name).yellow()); } else { println!("Snapshot: {}", style("<inline>").dim()); } if let Some(ref value) = snapshot.metadata().get_relative_source(workspace_root) { println!( "Source: {}{}", style(value.display()).cyan(), if let Some(line) = line { format!(":{}", style(line).bold()) } else { "".to_string() } ); } if let Some(ref value) = snapshot.metadata().input_file() { println!("Input file: {}", style(value).cyan()); } } pub fn print_snapshot_diff( workspace_root: &Path, new: &Snapshot, old_snapshot: Option<&Snapshot>, snapshot_file: Option<&Path>, mut line: Option<u32>, ) { if line.is_none() { line = new.metadata().assertion_line(); } print_snapshot_summary(workspace_root, new, snapshot_file, line); let old_contents = old_snapshot.as_ref().map_or("", |x| x.contents_str()); let new_contents = new.contents_str(); if !old_contents.is_empty() { println!("{}", style("-old snapshot").red()); println!("{}", style("+new results").green()); } else { println!("{}", style("+new results").green()); } print_changeset( old_contents, new_contents, new.metadata().expression.as_deref(), ); } pub fn print_snapshot_diff_with_title( workspace_root: &Path, new_snapshot: &Snapshot, old_snapshot: Option<&Snapshot>, line: u32, snapshot_file: Option<&Path>, ) { let width = term_width(); println!( "{title:━^width$}", title = style(" Snapshot Differences ").bold(), width = width ); print_snapshot_diff( workspace_root, new_snapshot, old_snapshot, snapshot_file, Some(line), ); } pub fn print_snapshot_summary_with_title( wo
width = term_width(); println!( "{title:━^width$}", title = style(" Snapshot Summary ").bold(), width = width ); print_snapshot_summary(workspace_root, new_snapshot, snapshot_file, Some(line)); println!("{title:━^width$}", title = "", width = width); } pub fn print_changeset(old: &str, new: &str, expr: Option<&str>) { let width = term_width(); let diff = TextDiff::configure() .algorithm(Algorithm::Patience) .timeout(Duration::from_millis(500)) .diff_lines(old, new); if let Some(expr) = expr { println!("{:─^1$}", "", width,); println!("{}", style(format_rust_expression(expr))); } println!("────────────┬{:─^1$}", "", width.saturating_sub(13)); let mut has_changes = false; for (idx, group) in diff.grouped_ops(4).iter().enumerate() { if idx > 0 { println!("┈┈┈┈┈┈┈┈┈┈┈┈┼{:┈^1$}", "", width.saturating_sub(13)); } for op in group { for change in diff.iter_inline_changes(&op) { match change.tag() { ChangeTag::Insert => { has_changes = true; print!( "{:>5} {:>5} │{}", "", style(change.new_index().unwrap()).cyan().dim().bold(), style("+").green(), ); for &(emphasized, change) in change.values() { if emphasized { print!("{}", style(change).green().underlined()); } else { print!("{}", style(change).green()); } } } ChangeTag::Delete => { has_changes = true; print!( "{:>5} {:>5} │{}", style(change.old_index().unwrap()).cyan().dim(), "", style("-").red(), ); for &(emphasized, change) in change.values() { if emphasized { print!("{}", style(change).red().underlined()); } else { print!("{}", style(change).red()); } } } ChangeTag::Equal => { print!( "{:>5} {:>5} │ ", style(change.old_index().unwrap()).cyan().dim(), style(change.new_index().unwrap()).cyan().dim().bold(), ); for &(_, change) in change.values() { print!("{}", style(change).dim()); } } } if change.missing_newline() { println!(); } } } } if !has_changes { println!( "{:>5} {:>5} │{}", "", style("-").dim(), style(" snapshots are matching").cyan(), ); } println!("────────────┴{:─^1$}", "", width.saturating_sub(13),); }
rkspace_root: &Path, new_snapshot: &Snapshot, old_snapshot: Option<&Snapshot>, line: u32, snapshot_file: Option<&Path>, ) { let _old_snapshot = old_snapshot; let
function_block-random_span
[ { "content": "/// Memoizes a snapshot file in the reference file.\n\npub fn memoize_snapshot_file(snapshot_file: &Path) {\n\n if let Ok(path) = env::var(\"INSTA_SNAPSHOT_REFERENCES_FILE\") {\n\n let mut f = fs::OpenOptions::new()\n\n .write(true)\n\n .append(true)\n\n .create(true)\n\n .open(path)\n\n .unwrap();\n\n f.write_all(format!(\"{}\\n\", snapshot_file.display()).as_bytes())\n\n .unwrap();\n\n }\n\n}\n", "file_path": "src/env.rs", "rank": 0, "score": 229399.25141942615 }, { "content": "pub fn glob_exec<F: FnMut(&Path)>(base: &Path, pattern: &str, mut f: F) {\n\n let glob = GlobBuilder::new(pattern)\n\n .case_insensitive(true)\n\n .literal_separator(true)\n\n .build()\n\n .unwrap()\n\n .compile_matcher();\n\n\n\n let walker = WalkDir::new(base).follow_links(true);\n\n let mut glob_found_matches = false;\n\n let mut settings = Settings::clone_current();\n\n\n\n for file in walker {\n\n let file = file.unwrap();\n\n let path = file.path();\n\n let stripped_path = path.strip_prefix(base).unwrap_or(path);\n\n if !glob.is_match(stripped_path) {\n\n continue;\n\n }\n\n\n", "file_path": "src/glob.rs", "rank": 1, "score": 188318.20628317533 }, { "content": "/// Returns the term width that insta should use.\n\npub fn term_width() -> usize {\n\n #[cfg(feature = \"colors\")]\n\n {\n\n console::Term::stdout().size().1 as usize\n\n }\n\n #[cfg(not(feature = \"colors\"))]\n\n {\n\n 74\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 5, "score": 166246.9587362131 }, { "content": "/// This prints the information about the snapshot\n\nfn print_snapshot_info(ctx: &SnapshotAssertionContext, new_snapshot: &Snapshot) {\n\n match get_output_behavior() {\n\n OutputBehavior::Summary => {\n\n print_snapshot_summary_with_title(\n\n ctx.cargo_workspace.as_path(),\n\n new_snapshot,\n\n ctx.old_snapshot.as_ref(),\n\n ctx.assertion_line,\n\n ctx.snapshot_file.as_deref(),\n\n );\n\n }\n\n OutputBehavior::Diff => {\n\n print_snapshot_diff_with_title(\n\n ctx.cargo_workspace.as_path(),\n\n new_snapshot,\n\n ctx.old_snapshot.as_ref(),\n\n ctx.assertion_line,\n\n ctx.snapshot_file.as_deref(),\n\n );\n\n }\n\n _ => {}\n\n }\n\n}\n\n\n", "file_path": "src/runtime.rs", "rank": 6, "score": 156503.06025493445 }, { "content": "/// Converts a path into a string that can be persisted.\n\npub fn path_to_storage<P: AsRef<Path>>(path: P) -> String {\n\n #[cfg(windows)]\n\n {\n\n path.as_ref().to_str().unwrap().replace('\\\\', \"/\")\n\n }\n\n\n\n #[cfg(not(windows))]\n\n {\n\n path.as_ref().to_string_lossy().into()\n\n }\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 7, "score": 153518.45935100073 }, { "content": "#[allow(clippy::too_many_arguments)]\n\npub fn assert_snapshot(\n\n refval: ReferenceValue<'_>,\n\n new_snapshot_value: &str,\n\n manifest_dir: &str,\n\n function_name: &str,\n\n module_path: &str,\n\n assertion_file: &str,\n\n assertion_line: u32,\n\n expr: &str,\n\n) -> Result<(), Box<dyn Error>> {\n\n let ctx = SnapshotAssertionContext::prepare(\n\n refval,\n\n manifest_dir,\n\n function_name,\n\n module_path,\n\n assertion_file,\n\n assertion_line,\n\n )?;\n\n\n\n let new_snapshot = ctx.new_snapshot(new_snapshot_value.into(), expr);\n", "file_path": "src/runtime.rs", "rank": 8, "score": 147938.63054544234 }, { "content": "/// Tries to format a given rust expression with rustfmt\n\npub fn format_rust_expression(value: &str) -> Cow<'_, str> {\n\n const PREFIX: &str = \"const x:() = \";\n\n const SUFFIX: &str = \";\\n\";\n\n if let Ok(mut proc) = Command::new(\"rustfmt\")\n\n .arg(\"--emit=stdout\")\n\n .arg(\"--edition=2018\")\n\n .stdin(Stdio::piped())\n\n .stdout(Stdio::piped())\n\n .stderr(Stdio::null())\n\n .spawn()\n\n {\n\n {\n\n let stdin = proc.stdin.as_mut().unwrap();\n\n stdin.write_all(PREFIX.as_bytes()).unwrap();\n\n stdin.write_all(value.as_bytes()).unwrap();\n\n stdin.write_all(SUFFIX.as_bytes()).unwrap();\n\n }\n\n if let Ok(output) = proc.wait_with_output() {\n\n if output.status.success() {\n\n // slice between after the prefix and before the suffix\n", "file_path": "src/utils.rs", "rank": 9, "score": 146050.89301547958 }, { "content": "/// Is insta told to force update snapshots?\n\npub fn force_update_snapshots() -> bool {\n\n match env::var(\"INSTA_FORCE_UPDATE_SNAPSHOTS\").ok().as_deref() {\n\n None | Some(\"\") | Some(\"0\") => false,\n\n Some(\"1\") => true,\n\n _ => panic!(\"invalid value for INSTA_FORCE_UPDATE_SNAPSHOTS\"),\n\n }\n\n}\n\n\n", "file_path": "src/env.rs", "rank": 12, "score": 136557.45898615863 }, { "content": "pub fn find_snapshots<'a>(\n\n root: PathBuf,\n\n extensions: &'a [&'a str],\n\n no_ignore: bool,\n\n) -> impl Iterator<Item = Result<SnapshotContainer, Box<dyn Error>>> + 'a {\n\n let mut builder = WalkBuilder::new(root.clone());\n\n builder\n\n .hidden(false)\n\n .standard_filters(!no_ignore)\n\n .filter_entry(|e| e.file_type().map_or(false, |x| x.is_file()) || !is_hidden(e));\n\n\n\n let mut override_builder = OverrideBuilder::new(&root);\n\n override_builder\n\n .add(\".*.pending-snap\")\n\n .unwrap()\n\n .add(\"*.snap.new\")\n\n .unwrap();\n\n\n\n for ext in extensions {\n\n override_builder.add(&format!(\"*.{}.new\", ext)).unwrap();\n", "file_path": "cargo-insta/src/cargo.rs", "rank": 13, "score": 136553.65408085682 }, { "content": "pub fn serialize_value<S: Serialize>(\n\n s: &S,\n\n format: SerializationFormat,\n\n location: SnapshotLocation,\n\n) -> String {\n\n let serializer = ContentSerializer::<ValueError>::new();\n\n let content = Serialize::serialize(s, serializer).unwrap();\n\n serialize_content(content, format, location)\n\n}\n\n\n", "file_path": "src/serialization.rs", "rank": 14, "score": 133940.62342005418 }, { "content": "#[cfg(feature = \"redactions\")]\n\npub fn serialize_value_redacted<S: Serialize>(\n\n s: &S,\n\n redactions: &[(crate::redaction::Selector, crate::redaction::Redaction)],\n\n format: SerializationFormat,\n\n location: SnapshotLocation,\n\n) -> String {\n\n let serializer = ContentSerializer::<ValueError>::new();\n\n let mut content = Serialize::serialize(s, serializer).unwrap();\n\n for (selector, redaction) in redactions {\n\n content = selector.redact(content, &redaction);\n\n }\n\n serialize_content(content, format, location)\n\n}\n", "file_path": "src/serialization.rs", "rank": 15, "score": 130767.1692574961 }, { "content": "/// Returns the intended snapshot update behavior.\n\npub fn get_snapshot_update_behavior(unseen: bool) -> SnapshotUpdate {\n\n match env::var(\"INSTA_UPDATE\").ok().as_deref() {\n\n None | Some(\"\") | Some(\"auto\") => {\n\n if is_ci() {\n\n SnapshotUpdate::NoUpdate\n\n } else {\n\n SnapshotUpdate::NewFile\n\n }\n\n }\n\n Some(\"always\") | Some(\"1\") => SnapshotUpdate::InPlace,\n\n Some(\"new\") => SnapshotUpdate::NewFile,\n\n Some(\"unseen\") => {\n\n if unseen {\n\n SnapshotUpdate::NewFile\n\n } else {\n\n SnapshotUpdate::InPlace\n\n }\n\n }\n\n Some(\"no\") => SnapshotUpdate::NoUpdate,\n\n _ => panic!(\"invalid value for INSTA_UPDATE\"),\n\n }\n\n}\n\n\n", "file_path": "src/env.rs", "rank": 16, "score": 128340.21379124481 }, { "content": "#[test]\n\nfn test_inline_snapshot_value_newline() {\n\n // https://github.com/mitsuhiko/insta/issues/39\n\n assert_eq!(get_inline_snapshot_value(\"\\n\"), \"\");\n\n}\n", "file_path": "src/snapshot.rs", "rank": 17, "score": 126399.71544985955 }, { "content": "/// Helper function that returns the real inline snapshot value from a given\n\n/// frozen value string. If the string starts with the '⋮' character\n\n/// (optionally prefixed by whitespace) the alternative serialization format\n\n/// is picked which has slightly improved indentation semantics.\n\n///\n\n/// This also changes all newlines to \\n\n\nfn get_inline_snapshot_value(frozen_value: &str) -> String {\n\n // TODO: could move this into the SnapshotContents `from_inline` method\n\n // (the only call site)\n\n\n\n if frozen_value.trim_start().starts_with('⋮') {\n\n // legacy format - retain so old snapshots still work\n\n let mut buf = String::new();\n\n let mut line_iter = frozen_value.lines();\n\n let mut indentation = 0;\n\n\n\n for line in &mut line_iter {\n\n let line_trimmed = line.trim_start();\n\n if line_trimmed.is_empty() {\n\n continue;\n\n }\n\n indentation = line.len() - line_trimmed.len();\n\n // 3 because '⋮' is three utf-8 bytes long\n\n buf.push_str(&line_trimmed[3..]);\n\n buf.push('\\n');\n\n break;\n", "file_path": "src/snapshot.rs", "rank": 18, "score": 122141.73013770631 }, { "content": "pub fn get_package_metadata(manifest_path: Option<&Path>) -> Result<Metadata, Box<dyn Error>> {\n\n let mut cmd = process::Command::new(get_cargo());\n\n cmd.arg(\"metadata\")\n\n .arg(\"--no-deps\")\n\n .arg(\"--format-version=1\");\n\n if let Some(manifest_path) = manifest_path {\n\n if !fs::metadata(manifest_path)\n\n .ok()\n\n .map_or(false, |x| x.is_file())\n\n {\n\n return Err(err_msg(\n\n \"the manifest-path must be a path to a Cargo.toml file\",\n\n ));\n\n }\n\n cmd.arg(\"--manifest-path\").arg(manifest_path.as_os_str());\n\n }\n\n let output = cmd.output()?;\n\n if !output.status.success() {\n\n let msg = String::from_utf8_lossy(&output.stderr);\n\n return Err(err_msg(format!(\n\n \"cargo erroried getting metadata: {}\",\n\n msg.trim()\n\n )));\n\n }\n\n Ok(serde_json::from_slice(&output.stdout)?)\n\n}\n\n\n", "file_path": "cargo-insta/src/cargo.rs", "rank": 19, "score": 121673.70546941346 }, { "content": "#[test]\n\nfn test_snapshot_path() {\n\n with_settings!({snapshot_path => \"snapshots2\"}, {\n\n assert_yaml_snapshot!(vec![1, 2, 3]);\n\n });\n\n}\n\n\n", "file_path": "tests/test_settings.rs", "rank": 20, "score": 120165.77278030738 }, { "content": "pub fn serialize_content(\n\n mut content: Content,\n\n format: SerializationFormat,\n\n location: SnapshotLocation,\n\n) -> String {\n\n content = Settings::with(|settings| {\n\n if settings.sort_maps() {\n\n content.sort_maps();\n\n }\n\n #[cfg(feature = \"redactions\")]\n\n {\n\n for (selector, redaction) in settings.iter_redactions() {\n\n content = selector.redact(content, redaction);\n\n }\n\n }\n\n content\n\n });\n\n\n\n match format {\n\n SerializationFormat::Yaml => {\n", "file_path": "src/serialization.rs", "rank": 21, "score": 114774.38506495202 }, { "content": "// Removes excess indentation, removes excess whitespace at start & end\n\n// and changes newlines to \\n.\n\nfn normalize_inline_snapshot(snapshot: &str) -> String {\n\n let indentation = min_indentation(snapshot);\n\n snapshot\n\n .trim_end()\n\n .lines()\n\n .skip_while(|l| l.is_empty())\n\n .map(|l| l.get(indentation..).unwrap_or(\"\"))\n\n .collect::<Vec<&str>>()\n\n .join(\"\\n\")\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 22, "score": 114210.87936411874 }, { "content": "/// Returns the cargo workspace for a manifest\n\npub fn get_cargo_workspace(manifest_dir: &str) -> Arc<PathBuf> {\n\n // we really do not care about poisoning here.\n\n let mut workspaces = WORKSPACES.lock().unwrap_or_else(|x| x.into_inner());\n\n if let Some(rv) = workspaces.get(manifest_dir) {\n\n rv.clone()\n\n } else {\n\n // If INSTA_WORKSPACE_ROOT environment variable is set, use the value\n\n // as-is. This is useful for those users where the compiled in\n\n // CARGO_MANIFEST_DIR points to some transient location. This can easily\n\n // happen if the user builds the test in one directory but then tries to\n\n // run it in another: even if sources are available in the new\n\n // directory, in the past we would always go with the compiled-in value.\n\n // The compiled-in directory may not even exist anymore.\n\n let path = if let Ok(workspace_root) = std::env::var(\"INSTA_WORKSPACE_ROOT\") {\n\n Arc::new(PathBuf::from(workspace_root))\n\n } else {\n\n #[derive(Deserialize)]\n\n struct Manifest {\n\n workspace_root: PathBuf,\n\n }\n", "file_path": "src/env.rs", "rank": 23, "score": 114166.29860723045 }, { "content": "fn min_indentation(snapshot: &str) -> usize {\n\n let lines = snapshot.trim_end().lines();\n\n\n\n if lines.clone().count() <= 1 {\n\n // not a multi-line string\n\n return 0;\n\n }\n\n\n\n lines\n\n .filter(|l| !l.is_empty())\n\n .map(count_leading_spaces)\n\n .min()\n\n .unwrap_or(0)\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 24, "score": 111348.5861053959 }, { "content": "/// Are we running in in a CI environment?\n\npub fn is_ci() -> bool {\n\n env::var(\"CI\").is_ok() || env::var(\"TF_BUILD\").is_ok()\n\n}\n\n\n\n#[cfg(feature = \"colors\")]\n\npub use console::style;\n\n\n\n#[cfg(not(feature = \"colors\"))]\n\nmod fake_colors {\n\n pub struct FakeStyledObject<D>(D);\n\n\n\n macro_rules! style_attr {\n\n ($($name:ident)*) => {\n\n $(\n\n #[inline]\n\n pub fn $name(self) -> FakeStyledObject<D> { self }\n\n )*\n\n }\n\n }\n\n\n", "file_path": "src/utils.rs", "rank": 25, "score": 110371.91077006434 }, { "content": "/// Creates a dynamic redaction that sorts the value at the selector.\n\n///\n\n/// This is useful to force something like a set or map to be ordered to make\n\n/// it deterministic. This is necessary as insta's serialization support is\n\n/// based on serde which does not have native set support. As a result vectors\n\n/// (which need to retain order) and sets (which should be given a stable order)\n\n/// look the same.\n\n///\n\n/// ```rust\n\n/// # use insta::{Settings, sorted_redaction};\n\n/// # let mut settings = Settings::new();\n\n/// settings.add_redaction(\".flags\", sorted_redaction());\n\n/// ```\n\npub fn sorted_redaction() -> Redaction {\n\n fn sort(mut value: Content, _path: ContentPath) -> Content {\n\n match value.resolve_inner_mut() {\n\n Content::Seq(ref mut val) => {\n\n val.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n\n }\n\n Content::Map(ref mut val) => {\n\n val.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n\n }\n\n Content::Struct(_, ref mut fields)\n\n | Content::StructVariant(_, _, _, ref mut fields) => {\n\n fields.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))\n\n }\n\n _ => {}\n\n }\n\n value\n\n }\n\n dynamic_redaction(sort)\n\n}\n\n\n", "file_path": "src/redaction.rs", "rank": 26, "score": 107966.91314206115 }, { "content": "/// Is insta instructed to fail in tests?\n\npub fn force_pass() -> bool {\n\n match env::var(\"INSTA_FORCE_PASS\").ok().as_deref() {\n\n None | Some(\"\") | Some(\"0\") => false,\n\n Some(\"1\") => true,\n\n _ => panic!(\"invalid value for INSTA_FORCE_PASS\"),\n\n }\n\n}\n\n\n", "file_path": "src/env.rs", "rank": 27, "score": 107953.4523506545 }, { "content": "fn count_leading_spaces(value: &str) -> usize {\n\n value.chars().take_while(|x| x.is_whitespace()).count()\n\n}\n\n\n", "file_path": "src/snapshot.rs", "rank": 28, "score": 107742.33726247695 }, { "content": "/// Returns the intended output behavior for insta.\n\npub fn get_output_behavior() -> OutputBehavior {\n\n match env::var(\"INSTA_OUTPUT\").ok().as_deref() {\n\n None | Some(\"\") | Some(\"diff\") => OutputBehavior::Diff,\n\n Some(\"summary\") => OutputBehavior::Summary,\n\n Some(\"minimal\") => OutputBehavior::Minimal,\n\n Some(\"none\") => OutputBehavior::Nothing,\n\n _ => panic!(\"invalid value for INSTA_OUTPUT\"),\n\n }\n\n}\n\n\n", "file_path": "src/env.rs", "rank": 29, "score": 103605.77880483758 }, { "content": "pub fn get_cargo() -> String {\n\n env::var(\"CARGO\")\n\n .ok()\n\n .unwrap_or_else(|| \"cargo\".to_string())\n\n}\n\n\n", "file_path": "cargo-insta/src/cargo.rs", "rank": 30, "score": 103605.77880483758 }, { "content": "#[test]\n\nfn test_snapshot_contents() {\n\n use similar_asserts::assert_eq;\n\n let snapshot_contents = SnapshotContents(\"testing\".to_string());\n\n assert_eq!(snapshot_contents.to_inline(0), r#\"\"testing\"\"#);\n\n\n\n let t = &\"\n\na\n\nb\"[1..];\n\n assert_eq!(\n\n SnapshotContents(t.to_string()).to_inline(0),\n\n \"r###\\\"\n\na\n\nb\n\n\\\"###\"\n\n );\n\n\n\n let t = &\"\n\na\n\nb\"[1..];\n\n assert_eq!(\n", "file_path": "src/snapshot.rs", "rank": 31, "score": 98719.73103097477 }, { "content": "#[test]\n\nfn test_normalize_inline_snapshot() {\n\n use similar_asserts::assert_eq;\n\n // here we do exact matching (rather than `assert_snapshot`)\n\n // to ensure we're not incorporating the modifications this library makes\n\n let t = r#\"\n\n 1\n\n 2\n\n \"#;\n\n assert_eq!(\n\n normalize_inline_snapshot(t),\n\n r###\"\n\n1\n\n2\"###[1..]\n\n );\n\n\n\n let t = r#\"\n\n 1\n\n 2\"#;\n\n assert_eq!(\n\n normalize_inline_snapshot(t),\n", "file_path": "src/snapshot.rs", "rank": 32, "score": 96546.869854524 }, { "content": "pub fn run() -> Result<(), Box<dyn Error>> {\n\n // chop off cargo\n\n let mut args: Vec<_> = env::args_os().collect();\n\n if env::var(\"CARGO\").is_ok() && args.get(1).and_then(|x| x.to_str()) == Some(\"insta\") {\n\n args.remove(1);\n\n }\n\n\n\n let opts = Opts::from_iter(args);\n\n\n\n let color = opts.color.as_ref().map(|x| x.as_str()).unwrap_or(\"auto\");\n\n handle_color(color)?;\n\n match opts.command {\n\n Command::Review(cmd) => process_snapshots(cmd, None),\n\n Command::Accept(cmd) => process_snapshots(cmd, Some(Operation::Accept)),\n\n Command::Reject(cmd) => process_snapshots(cmd, Some(Operation::Reject)),\n\n Command::Test(cmd) => test_run(cmd, color),\n\n Command::PendingSnapshots(cmd) => pending_snapshots_cmd(cmd),\n\n }\n\n}\n", "file_path": "cargo-insta/src/cli.rs", "rank": 33, "score": 90407.28529830382 }, { "content": "/// Creates a dynamic redaction.\n\n///\n\n/// This can be used to redact a value with a different value but instead of\n\n/// statically declaring it a dynamic value can be computed. This can also\n\n/// be used to perform assertions before replacing the value.\n\n///\n\n/// The closure is passed two arguments: the value as [`Content`]\n\n/// and the path that was selected (as [`ContentPath`])\n\n///\n\n/// Example:\n\n///\n\n/// ```rust\n\n/// # use insta::{Settings, dynamic_redaction};\n\n/// # let mut settings = Settings::new();\n\n/// settings.add_redaction(\".id\", dynamic_redaction(|value, path| {\n\n/// assert_eq!(path.to_string(), \".id\");\n\n/// assert_eq!(\n\n/// value\n\n/// .as_str()\n\n/// .unwrap()\n\n/// .chars()\n\n/// .filter(|&c| c == '-')\n\n/// .count(),\n\n/// 4\n\n/// );\n\n/// \"[uuid]\"\n\n/// }));\n\n/// ```\n\npub fn dynamic_redaction<I, F>(func: F) -> Redaction\n\nwhere\n\n I: Into<Content>,\n\n F: Fn(Content, ContentPath<'_>) -> I + Send + Sync + 'static,\n\n{\n\n Redaction::Dynamic(Box::new(move |c, p| func(c, p).into()))\n\n}\n\n\n", "file_path": "src/redaction.rs", "rank": 34, "score": 89974.92600383007 }, { "content": "#[test]\n\nfn test_min_indentation() {\n\n use similar_asserts::assert_eq;\n\n let t = r#\"\n\n 1\n\n 2\n\n \"#;\n\n assert_eq!(min_indentation(t), 3);\n\n\n\n let t = r#\"\n\n 1\n\n 2\"#;\n\n assert_eq!(min_indentation(t), 4);\n\n\n\n let t = r#\"\n\n 1\n\n 2\n\n \"#;\n\n assert_eq!(min_indentation(t), 12);\n\n\n\n let t = r#\"\n", "file_path": "src/snapshot.rs", "rank": 35, "score": 89562.50833260844 }, { "content": "fn get_snapshot_filename(\n\n module_path: &str,\n\n snapshot_name: &str,\n\n cargo_workspace: &Path,\n\n base: &str,\n\n) -> PathBuf {\n\n let root = Path::new(cargo_workspace);\n\n let base = Path::new(base);\n\n Settings::with(|settings| {\n\n root.join(base.parent().unwrap())\n\n .join(settings.snapshot_path())\n\n .join({\n\n use std::fmt::Write;\n\n let mut f = String::new();\n\n if settings.prepend_module_to_snapshot() {\n\n write!(&mut f, \"{}__\", module_path.replace(\"::\", \"__\")).unwrap();\n\n }\n\n write!(\n\n &mut f,\n\n \"{}.snap\",\n\n snapshot_name.replace(\"/\", \"__\").replace(\"\\\\\", \"__\")\n\n )\n\n .unwrap();\n\n f\n\n })\n\n })\n\n}\n\n\n", "file_path": "src/runtime.rs", "rank": 36, "score": 89562.50833260844 }, { "content": "#[test]\n\nfn test_format_rust_expression() {\n\n use crate::assert_snapshot;\n\n assert_snapshot!(format_rust_expression(\"vec![1,2,3]\"), @\"vec![1, 2, 3]\");\n\n assert_snapshot!(format_rust_expression(\"vec![1,2,3].iter()\"), @\"vec![1, 2, 3].iter()\");\n\n assert_snapshot!(format_rust_expression(r#\" \"aoeu\"\"#), @r###\"\"aoeu\"\"###);\n\n assert_snapshot!(format_rust_expression(r#\" \"aoe😄\"\"#), @r###\"\"aoe😄\"\"###);\n\n assert_snapshot!(format_rust_expression(\"😄😄😄😄😄\"), @\"😄😄😄😄😄\")\n\n}\n", "file_path": "src/utils.rs", "rank": 37, "score": 88471.3899374274 }, { "content": "#[test]\n\nfn test_single_line() {\n\n assert_snapshot!(\"Testing\", @\"Testing\");\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 38, "score": 88445.26438603384 }, { "content": "#[test]\n\nfn test_with_random_value() {\n\n assert_yaml_snapshot!(\"user\", &User {\n\n id: 42,\n\n username: \"john_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\"\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 39, "score": 88265.78040183791 }, { "content": "#[allow(clippy::too_many_arguments)]\n\nfn query_snapshot(\n\n workspace_root: &Path,\n\n term: &Term,\n\n new: &Snapshot,\n\n old: Option<&Snapshot>,\n\n pkg: Option<&Package>,\n\n line: Option<u32>,\n\n i: usize,\n\n n: usize,\n\n snapshot_file: Option<&Path>,\n\n) -> Result<Operation, Box<dyn Error>> {\n\n term.clear_screen()?;\n\n println!(\n\n \"{}{}{}\",\n\n style(\"Reviewing [\").bold(),\n\n style(format!(\"{}/{}\", i, n)).yellow().bold(),\n\n style(\"]:\").bold(),\n\n );\n\n\n\n if let Some(pkg) = pkg {\n", "file_path": "cargo-insta/src/cli.rs", "rank": 40, "score": 87179.86003087371 }, { "content": "#[test]\n\nfn test_multiline_with_empty_lines() {\n\n assert_snapshot!(\"# first\\nsecond\\n third\\n\\n# alternative\", @r###\"\n\n # first\n\n second\n\n third\n\n\n\n # alternative\n\n \"###);\n\n}\n", "file_path": "tests/test_inline.rs", "rank": 41, "score": 86184.73553846542 }, { "content": "#[test]\n\nfn test_unnamed_single_line() {\n\n assert_snapshot!(\"Testing\");\n\n assert_snapshot!(\"Testing-2\");\n\n}\n\n\n\n// We used to use the thread name for snapshot name detection. This is unreliable\n\n// so this test now basically does exactly the same as `test_unnamed_single_line`.\n", "file_path": "tests/test_inline.rs", "rank": 42, "score": 86184.73553846542 }, { "content": "#[test]\n\nfn test_with_random_value_json() {\n\n assert_json_snapshot!(\"user_json\", &User {\n\n id: 9999,\n\n username: \"jason_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"ssn goes here\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\",\n\n \".extra\" => \"[extra]\"\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 43, "score": 86011.514171695 }, { "content": "#[cfg(feature = \"ron\")]\n\n#[test]\n\nfn test_with_random_value_ron() {\n\n insta::assert_ron_snapshot!(\"user_ron\", &User {\n\n id: 53,\n\n username: \"john_ron\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\"\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 44, "score": 86011.514171695 }, { "content": "#[cfg(feature = \"toml\")]\n\n#[test]\n\nfn test_with_random_value_toml() {\n\n insta::assert_toml_snapshot!(\"user_toml\", &User {\n\n id: 53,\n\n username: \"john_ron\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\"\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 45, "score": 86011.514171695 }, { "content": "#[cfg(feature = \"csv\")]\n\n#[test]\n\nfn test_with_random_value_csv() {\n\n insta::assert_csv_snapshot!(\"user_csv\", &User {\n\n id: 44,\n\n username: \"julius_csv\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\"\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 46, "score": 86011.514171695 }, { "content": "fn detect_snapshot_name(function_name: &str, module_path: &str) -> Result<String, &'static str> {\n\n let name = Cow::Borrowed(function_name);\n\n\n\n // clean test name first\n\n let mut name = name.rsplit(\"::\").next().unwrap();\n\n let mut test_prefixed = false;\n\n if name.starts_with(\"test_\") {\n\n name = &name[5..];\n\n test_prefixed = true;\n\n }\n\n\n\n // next check if we need to add a suffix\n\n let name = add_suffix_to_snapshot_name(Cow::Borrowed(name));\n\n let key = format!(\"{}::{}\", module_path.replace(\"::\", \"__\"), name);\n\n\n\n // because fn foo and fn test_foo end up with the same snapshot name we\n\n // make sure we detect this here and raise an error.\n\n let mut name_clash_detection = TEST_NAME_CLASH_DETECTION\n\n .lock()\n\n .unwrap_or_else(|x| x.into_inner());\n", "file_path": "src/runtime.rs", "rank": 47, "score": 85257.53825577963 }, { "content": "#[test]\n\nfn test_snapshot_no_module_prepending() {\n\n with_settings!({prepend_module_to_snapshot => false}, {\n\n assert_yaml_snapshot!(vec![1, 2, 3]);\n\n });\n\n}\n", "file_path": "tests/test_settings.rs", "rank": 48, "score": 84963.48411093513 }, { "content": "#[test]\n\nfn test_unnamed_thread_single_line() {\n\n let builder = thread::Builder::new().name(\"foo::lol::something\".into());\n\n\n\n let handler = builder\n\n .spawn(|| {\n\n assert_snapshot!(\"Testing-thread\");\n\n assert_snapshot!(\"Testing-thread-2\");\n\n })\n\n .unwrap();\n\n\n\n handler.join().unwrap();\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 49, "score": 84076.63830717457 }, { "content": "#[test]\n\nfn test_with_random_value_json_settings() {\n\n let mut settings = Settings::new();\n\n settings.add_redaction(\".id\", \"[id]\");\n\n settings.add_redaction(\".extra\", \"[extra]\");\n\n settings.bind(|| {\n\n assert_json_snapshot!(\n\n \"user_json_settings\",\n\n &User {\n\n id: 122,\n\n username: \"jason_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"ssn goes here\".to_string(),\n\n }\n\n );\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 50, "score": 83909.25725802251 }, { "content": "#[test]\n\nfn test_with_random_value_and_trailing_comma() {\n\n assert_yaml_snapshot!(\"user\", &User {\n\n id: 11,\n\n username: \"john_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => \"[id]\",\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 51, "score": 83909.25725802251 }, { "content": "#[test]\n\nfn test_with_random_value_json_settings2() {\n\n with_settings!({redactions => vec![\n\n (\".id\", \"[id]\".into()),\n\n (\".extra\", \"[extra]\".into()),\n\n ]}, {\n\n assert_json_snapshot!(\n\n &User {\n\n id: 975,\n\n username: \"jason_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"ssn goes here\".to_string(),\n\n }\n\n );\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 52, "score": 83909.25725802251 }, { "content": "#[cfg(feature = \"csv\")]\n\n#[test]\n\nfn test_csv_inline_multiple_values() {\n\n #[derive(Serialize)]\n\n pub struct Email(String);\n\n\n\n #[derive(Serialize)]\n\n pub struct User {\n\n id: u32,\n\n username: String,\n\n email: Email,\n\n }\n\n\n\n let user1 = User {\n\n id: 1453,\n\n username: \"mehmed-doe\".into(),\n\n email: Email(\"[email protected]\".into()),\n\n };\n\n let user2 = User {\n\n id: 1455,\n\n username: \"mehmed-doe-di\".into(),\n\n email: Email(\"[email protected]\".into()),\n\n };\n\n\n\n assert_csv_snapshot!(vec![user1, user2], @r###\"\n\n id,username,email\n\n 1453,mehmed-doe,[email protected]\n\n 1455,mehmed-doe-di,[email protected]\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 53, "score": 83909.25725802251 }, { "content": "#[test]\n\nfn test_with_random_value_inline_callback() {\n\n assert_yaml_snapshot!(\"user\", &User {\n\n id: 23,\n\n username: \"john_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"\".to_string(),\n\n }, {\n\n \".id\" => insta::dynamic_redaction(|value, path| {\n\n assert_eq!(path.to_string(), \".id\");\n\n assert_eq!(value.as_u64().unwrap(), 23);\n\n \"[id]\"\n\n }),\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 54, "score": 83909.25725802251 }, { "content": "fn load_snapshot_containers<'a>(\n\n loc: &'a LocationInfo,\n\n) -> Result<Vec<(SnapshotContainer, Option<&'a Package>)>, Box<dyn Error>> {\n\n let mut snapshot_containers = vec![];\n\n match loc.packages {\n\n Some(ref packages) => {\n\n for package in packages.iter() {\n\n for snapshot_container in package.iter_snapshot_containers(&loc.exts, loc.no_ignore)\n\n {\n\n snapshot_containers.push((snapshot_container?, Some(package)));\n\n }\n\n }\n\n }\n\n None => {\n\n for snapshot_container in\n\n find_snapshots(loc.workspace_root.clone(), &loc.exts, loc.no_ignore)\n\n {\n\n snapshot_containers.push((snapshot_container?, None));\n\n }\n\n }\n\n }\n\n Ok(snapshot_containers)\n\n}\n\n\n", "file_path": "cargo-insta/src/cli.rs", "rank": 55, "score": 82567.80644198324 }, { "content": "/// Finalizes the assertion based on the update result.\n\nfn finalize_assertion(ctx: &SnapshotAssertionContext, update_result: SnapshotUpdate) {\n\n if update_result == SnapshotUpdate::NewFile && get_output_behavior() != OutputBehavior::Nothing\n\n {\n\n println!(\n\n \"{hint}\",\n\n hint = style(\"To update snapshots run `cargo insta review`\").dim(),\n\n );\n\n }\n\n\n\n if update_result != SnapshotUpdate::InPlace && !force_pass() {\n\n if get_output_behavior() != OutputBehavior::Nothing {\n\n println!(\n\n \"{hint}\",\n\n hint = style(\n\n \"Stopped on the first failure. Run `cargo insta test` to run all snapshots.\"\n\n )\n\n .dim(),\n\n );\n\n }\n\n panic!(\n", "file_path": "src/runtime.rs", "rank": 56, "score": 78488.31759423265 }, { "content": "pub fn err_msg<S: Into<String>>(s: S) -> Box<dyn Error> {\n\n Box::new(ErrMsg(s.into()))\n\n}\n", "file_path": "cargo-insta/src/utils.rs", "rank": 57, "score": 77906.14036112593 }, { "content": "#[test]\n\nfn test_json_snapshot() {\n\n let user = User {\n\n id: 42,\n\n email: \"[email protected]\".into(),\n\n };\n\n insta::assert_json_snapshot!(&user, {\n\n \".id\" => \"[user_id]\",\n\n }, @\"\");\n\n}\n", "file_path": "cargo-insta/integration-tests/test-input/test_json_inline.rs", "rank": 58, "score": 75857.00877618388 }, { "content": "#[test]\n\nfn test_yaml_snapshot() {\n\n let user = User {\n\n id: 42,\n\n email: \"[email protected]\".into(),\n\n };\n\n insta::assert_yaml_snapshot!(&user, {\n\n \".id\" => \"[user_id]\",\n\n }, @\"\");\n\n}\n", "file_path": "cargo-insta/integration-tests/test-input/test_yaml_inline.rs", "rank": 59, "score": 75857.00877618388 }, { "content": "fn test_run(mut cmd: TestCommand, color: &str) -> Result<(), Box<dyn Error>> {\n\n let mut proc = process::Command::new(get_cargo());\n\n proc.arg(\"test\");\n\n\n\n // when unreferenced snapshots should be deleted we need to instruct\n\n // insta to dump referenced snapshots somewhere.\n\n let snapshot_ref_file = if cmd.delete_unreferenced_snapshots {\n\n let snapshot_ref_file = env::temp_dir().join(Uuid::new_v4().to_string());\n\n proc.env(\"INSTA_SNAPSHOT_REFERENCES_FILE\", &snapshot_ref_file);\n\n Some(snapshot_ref_file)\n\n } else {\n\n None\n\n };\n\n\n\n // if INSTA_UPDATE is set as environment variable we're using it to\n\n // override some arguments. The logic is is quite weird because we\n\n // don't support all of the same values and we also want to override\n\n // it through the command line switches.\n\n match env::var(\"INSTA_UPDATE\").ok().as_deref() {\n\n Some(\"auto\") | Some(\"new\") => {}\n", "file_path": "cargo-insta/src/cli.rs", "rank": 60, "score": 74548.94946112862 }, { "content": "#[test]\n\nfn test_remove_existing_value() {\n\n insta::assert_snapshot!(\"this is the new value\", @\"this is the old value\");\n\n}\n\n\n", "file_path": "cargo-insta/integration-tests/test-input/test_basic_utf8_inline.rs", "rank": 61, "score": 73771.76262616714 }, { "content": " private resolveUnnamedSnapshot(\n\n document: TextDocument,\n\n position: Position,\n\n noInline: boolean\n\n ): SnapshotMatch | null {\n\n function unnamedSnapshotAt(lineno: number): boolean {\n\n const line = document.lineAt(lineno).text;\n\n return !!(\n\n line.match(UNNAMED_SNAPSHOT_ASSERTION) &&\n\n !line.match(NAMED_SNAPSHOT_ASSERTION) &&\n\n (noInline || !line.match(STRING_INLINE_SNAPSHOT_ASSERTION))\n\n );\n\n }\n\n\n\n // if we can't find an unnnamed snapshot at the given position we bail.\n\n if (!unnamedSnapshotAt(position.line)) {\n\n return null;\n\n }\n\n\n\n // otherwise scan backwards for unnamed snapshot matches until we find\n\n // a test function declaration.\n\n let snapshotNumber = 1;\n\n let scanLine = position.line - 1;\n\n let functionName = null;\n\n let isInline = !!document.lineAt(position.line).text.match(INLINE_MARKER);\n\n console.log(\"inline\", document.lineAt(position.line), isInline);\n\n\n\n while (scanLine >= 0) {\n\n // stop if we find a test function declaration\n\n let functionMatch;\n\n const line = document.lineAt(scanLine);\n\n if (\n\n scanLine > 1 &&\n\n (functionMatch = line.text.match(FUNCTION)) &&\n\n document.lineAt(scanLine - 1).text.match(TEST_DECL)\n\n ) {\n\n functionName = functionMatch[1];\n\n break;\n\n }\n\n if (!isInline && line.text.match(INLINE_MARKER)) {\n\n isInline = true;\n\n }\n\n if (unnamedSnapshotAt(scanLine)) {\n\n // TODO: do not increment if the snapshot at that location\n\n snapshotNumber++;\n\n }\n\n scanLine--;\n\n }\n\n\n\n // if we couldn't find a function or an unexpected inline snapshot we have to bail.\n\n if (!functionName || (noInline && isInline)) {\n\n return null;\n\n }\n\n\n\n let snapshotName = null;\n\n let line = null;\n\n let path = null;\n\n let localModuleName = null;\n\n\n\n if (isInline) {\n\n line = position.line;\n\n path = document.fileName;\n\n } else {\n\n snapshotName = `${functionName.match(SNAPSHOT_FUNCTION_STRIP)![1]}${\n\n snapshotNumber > 1 ? `-${snapshotNumber}` : \"\"\n\n }`;\n\n const fileNameMatch = document.fileName.match(FILENAME_PARTITION);\n\n if (!fileNameMatch) {\n\n return null;\n\n }\n\n path = fileNameMatch[1];\n\n localModuleName = fileNameMatch[2];\n\n }\n\n\n\n return {\n\n snapshotName,\n\n line,\n\n path,\n\n localModuleName,\n\n snapshotType: isInline ? \"inline\" : \"named\",\n\n };\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 62, "score": 73636.05157331418 }, { "content": " private resolveNamedSnapshot(\n\n document: TextDocument,\n\n position: Position\n\n ): SnapshotMatch | null {\n\n const line =\n\n (position.line >= 1 ? document.lineAt(position.line - 1).text : \"\") +\n\n document.lineAt(position.line).text;\n\n\n\n const snapshotMatch = line.match(NAMED_SNAPSHOT_ASSERTION);\n\n if (!snapshotMatch) {\n\n return null;\n\n }\n\n const snapshotName = snapshotMatch[1];\n\n const fileNameMatch = document.fileName.match(FILENAME_PARTITION);\n\n if (!fileNameMatch) {\n\n return null;\n\n }\n\n const path = fileNameMatch[1];\n\n const localModuleName = fileNameMatch[2];\n\n return {\n\n snapshotName,\n\n line: null,\n\n path,\n\n localModuleName,\n\n snapshotType: \"named\",\n\n };\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 63, "score": 73635.94647145986 }, { "content": " public findSnapshotAtLocation(\n\n document: TextDocument,\n\n position: Position,\n\n token: CancellationToken,\n\n noInline: boolean = false\n\n ): Thenable<ResolvedSnapshotMatch | null> {\n\n const snapshotMatch =\n\n this.resolveNamedSnapshot(document, position) ||\n\n this.resolveUnnamedSnapshot(document, position, noInline);\n\n if (!snapshotMatch) {\n\n return Promise.resolve(null);\n\n }\n\n\n\n if (snapshotMatch.snapshotType === \"inline\") {\n\n return Promise.resolve({\n\n snapshotUri: document.uri,\n\n ...snapshotMatch,\n\n });\n\n }\n\n\n\n const getSearchPath = function (\n\n mode: \"exact\" | \"wildcard-prefix\" | \"wildcard-all\"\n\n ): string {\n\n return workspace.asRelativePath(\n\n `${snapshotMatch.path}/snapshots/${mode !== \"exact\" ? \"*__\" : \"\"}${\n\n snapshotMatch.localModuleName\n\n }${mode === \"wildcard-all\" ? \"__*\" : \"\"}__${\n\n snapshotMatch.snapshotName\n\n }.snap`\n\n );\n\n };\n\n\n\n function findFiles(path: string): Thenable<Uri | null> {\n\n return workspace\n\n .findFiles(path, \"\", 1, token)\n\n .then((results) => results[0] || null);\n\n }\n\n\n\n // we try to find the file in three passes:\n\n // - exact matchin the snapshot folder.\n\n // - with a wildcard module prefix (crate__foo__NAME__SNAP)\n\n // - with a wildcard module prefix and suffix (crate__foo__NAME__tests__SNAP)\n\n // This is needed since snapshots can be contained in submodules. Since\n\n // getting the actual module name is tedious we just hope the match is\n\n // unique.\n\n return findFiles(getSearchPath(\"exact\"))\n\n .then((rv) => rv || findFiles(getSearchPath(\"wildcard-prefix\")))\n\n .then((rv) => rv || findFiles(getSearchPath(\"wildcard-all\")))\n\n .then((snapshot) =>\n\n snapshot ? { snapshotUri: snapshot, ...snapshotMatch } : null\n\n );\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 64, "score": 73632.19339142367 }, { "content": "export class Snapshot extends TreeItem {\n\n public key: string;\n\n public inlineInfo?: InlineSnapshotInfo;\n\n\n\n constructor(public rootUri: Uri, snapshotInfo: any) {\n\n super(Uri.file(snapshotInfo.path));\n\n const relPath = workspace.asRelativePath(snapshotInfo.path);\n\n const line = snapshotInfo.line;\n\n this.label = line !== undefined ? `${relPath}:${line}` : relPath;\n\n this.key =\n\n line !== undefined ? `${snapshotInfo.path}:${line}` : snapshotInfo.path;\n\n\n\n if (snapshotInfo.type === \"inline_snapshot\") {\n\n this.description = snapshotInfo.name || \"(inline)\";\n\n this.inlineInfo = {\n\n oldSnapshot:\n\n snapshotInfo.old_snapshot === null\n\n ? undefined\n\n : snapshotInfo.old_snapshot,\n\n newSnapshot: snapshotInfo.new_snapshot,\n\n line: snapshotInfo.line,\n\n expression:\n\n snapshotInfo.expression === null\n\n ? undefined\n\n : snapshotInfo.expression,\n\n name: snapshotInfo.name === null ? undefined : snapshotInfo.name,\n\n };\n\n }\n\n\n\n this.command = {\n\n command: \"mitsuhiko.insta.open-snapshot-diff\",\n\n title: \"\",\n\n arguments: [this],\n\n };\n\n }\n\n\n\n contextValue = \"pendingInstaSnapshot\";\n", "file_path": "vscode-insta/src/Snapshot.ts", "rank": 65, "score": 73038.8661683678 }, { "content": "#[test]\n\nfn test_remove_existing_value_multiline() {\n\n insta::assert_snapshot!(\n\n \"this is the new value\",\n\n @\"this is\\\n\n this is the old value\\\n\n it really is\"\n\n );\n\n}\n", "file_path": "cargo-insta/integration-tests/test-input/test_basic_utf8_inline.rs", "rank": 66, "score": 72404.79918964783 }, { "content": "export class SnapshotPathProvider implements DefinitionProvider {\n\n /**\n\n * This looks up an explicitly named snapshot (simple case)\n\n */\n\n private resolveNamedSnapshot(\n\n document: TextDocument,\n\n position: Position\n\n ): SnapshotMatch | null {\n\n const line =\n\n (position.line >= 1 ? document.lineAt(position.line - 1).text : \"\") +\n\n document.lineAt(position.line).text;\n\n\n\n const snapshotMatch = line.match(NAMED_SNAPSHOT_ASSERTION);\n\n if (!snapshotMatch) {\n\n return null;\n\n }\n\n const snapshotName = snapshotMatch[1];\n\n const fileNameMatch = document.fileName.match(FILENAME_PARTITION);\n\n if (!fileNameMatch) {\n\n return null;\n\n }\n\n const path = fileNameMatch[1];\n\n const localModuleName = fileNameMatch[2];\n\n return {\n\n snapshotName,\n\n line: null,\n\n path,\n\n localModuleName,\n\n snapshotType: \"named\",\n\n };\n\n }\n\n\n\n /**\n\n * This locates an implicitly (unnamed) snapshot.\n\n */\n\n private resolveUnnamedSnapshot(\n\n document: TextDocument,\n\n position: Position,\n\n noInline: boolean\n\n ): SnapshotMatch | null {\n\n function unnamedSnapshotAt(lineno: number): boolean {\n\n const line = document.lineAt(lineno).text;\n\n return !!(\n\n line.match(UNNAMED_SNAPSHOT_ASSERTION) &&\n\n !line.match(NAMED_SNAPSHOT_ASSERTION) &&\n\n (noInline || !line.match(STRING_INLINE_SNAPSHOT_ASSERTION))\n\n );\n\n }\n\n\n\n // if we can't find an unnnamed snapshot at the given position we bail.\n\n if (!unnamedSnapshotAt(position.line)) {\n\n return null;\n\n }\n\n\n\n // otherwise scan backwards for unnamed snapshot matches until we find\n\n // a test function declaration.\n\n let snapshotNumber = 1;\n\n let scanLine = position.line - 1;\n\n let functionName = null;\n\n let isInline = !!document.lineAt(position.line).text.match(INLINE_MARKER);\n\n console.log(\"inline\", document.lineAt(position.line), isInline);\n\n\n\n while (scanLine >= 0) {\n\n // stop if we find a test function declaration\n\n let functionMatch;\n\n const line = document.lineAt(scanLine);\n\n if (\n\n scanLine > 1 &&\n\n (functionMatch = line.text.match(FUNCTION)) &&\n\n document.lineAt(scanLine - 1).text.match(TEST_DECL)\n\n ) {\n\n functionName = functionMatch[1];\n\n break;\n\n }\n\n if (!isInline && line.text.match(INLINE_MARKER)) {\n\n isInline = true;\n\n }\n\n if (unnamedSnapshotAt(scanLine)) {\n\n // TODO: do not increment if the snapshot at that location\n\n snapshotNumber++;\n\n }\n\n scanLine--;\n\n }\n\n\n\n // if we couldn't find a function or an unexpected inline snapshot we have to bail.\n\n if (!functionName || (noInline && isInline)) {\n\n return null;\n\n }\n\n\n\n let snapshotName = null;\n\n let line = null;\n\n let path = null;\n\n let localModuleName = null;\n\n\n\n if (isInline) {\n\n line = position.line;\n\n path = document.fileName;\n\n } else {\n\n snapshotName = `${functionName.match(SNAPSHOT_FUNCTION_STRIP)![1]}${\n\n snapshotNumber > 1 ? `-${snapshotNumber}` : \"\"\n\n }`;\n\n const fileNameMatch = document.fileName.match(FILENAME_PARTITION);\n\n if (!fileNameMatch) {\n\n return null;\n\n }\n\n path = fileNameMatch[1];\n\n localModuleName = fileNameMatch[2];\n\n }\n\n\n\n return {\n\n snapshotName,\n\n line,\n\n path,\n\n localModuleName,\n\n snapshotType: isInline ? \"inline\" : \"named\",\n\n };\n\n }\n\n\n\n public findSnapshotAtLocation(\n\n document: TextDocument,\n\n position: Position,\n\n token: CancellationToken,\n\n noInline: boolean = false\n\n ): Thenable<ResolvedSnapshotMatch | null> {\n\n const snapshotMatch =\n\n this.resolveNamedSnapshot(document, position) ||\n\n this.resolveUnnamedSnapshot(document, position, noInline);\n\n if (!snapshotMatch) {\n\n return Promise.resolve(null);\n\n }\n\n\n\n if (snapshotMatch.snapshotType === \"inline\") {\n\n return Promise.resolve({\n\n snapshotUri: document.uri,\n\n ...snapshotMatch,\n\n });\n\n }\n\n\n\n const getSearchPath = function (\n\n mode: \"exact\" | \"wildcard-prefix\" | \"wildcard-all\"\n\n ): string {\n\n return workspace.asRelativePath(\n\n `${snapshotMatch.path}/snapshots/${mode !== \"exact\" ? \"*__\" : \"\"}${\n\n snapshotMatch.localModuleName\n\n }${mode === \"wildcard-all\" ? \"__*\" : \"\"}__${\n\n snapshotMatch.snapshotName\n\n }.snap`\n\n );\n\n };\n\n\n\n function findFiles(path: string): Thenable<Uri | null> {\n\n return workspace\n\n .findFiles(path, \"\", 1, token)\n\n .then((results) => results[0] || null);\n\n }\n\n\n\n // we try to find the file in three passes:\n\n // - exact matchin the snapshot folder.\n\n // - with a wildcard module prefix (crate__foo__NAME__SNAP)\n\n // - with a wildcard module prefix and suffix (crate__foo__NAME__tests__SNAP)\n\n // This is needed since snapshots can be contained in submodules. Since\n\n // getting the actual module name is tedious we just hope the match is\n\n // unique.\n\n return findFiles(getSearchPath(\"exact\"))\n\n .then((rv) => rv || findFiles(getSearchPath(\"wildcard-prefix\")))\n\n .then((rv) => rv || findFiles(getSearchPath(\"wildcard-all\")))\n\n .then((snapshot) =>\n\n snapshot ? { snapshotUri: snapshot, ...snapshotMatch } : null\n\n );\n\n }\n\n\n\n public provideDefinition(\n\n document: TextDocument,\n\n position: Position,\n\n token: CancellationToken\n\n ): ProviderResult<Definition> {\n\n return this.findSnapshotAtLocation(document, position, token, true).then(\n\n (match) => {\n\n if (!match) {\n\n return null;\n\n }\n\n return workspace.fs.readFile(match.snapshotUri).then((contents) => {\n\n const stringContents = Buffer.from(contents).toString(\"utf-8\");\n\n const header = stringContents.match(SNAPSHOT_HEADER);\n\n let location = new Position(0, 0);\n\n if (header) {\n\n location = new Position(header[0].match(/\\n/g)!.length + 1, 0);\n\n }\n\n return new Location(match.snapshotUri, location);\n\n });\n\n }\n\n );\n\n }\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 67, "score": 72175.05524375786 }, { "content": "fn pending_snapshots_cmd(cmd: PendingSnapshotsCommand) -> Result<(), Box<dyn Error>> {\n\n let loc = handle_target_args(&cmd.target_args)?;\n\n let mut snapshot_containers = load_snapshot_containers(&loc)?;\n\n\n\n for (snapshot_container, _package) in snapshot_containers.iter_mut() {\n\n let target_file = snapshot_container.target_file().to_path_buf();\n\n let is_inline = snapshot_container.snapshot_file().is_none();\n\n for snapshot_ref in snapshot_container.iter_snapshots() {\n\n if cmd.as_json {\n\n let info = if is_inline {\n\n SnapshotKey::InlineSnapshot {\n\n path: &target_file,\n\n line: snapshot_ref.line.unwrap(),\n\n name: snapshot_ref.new.snapshot_name(),\n\n old_snapshot: snapshot_ref.old.as_ref().map(|x| x.contents_str()),\n\n new_snapshot: snapshot_ref.new.contents_str(),\n\n expression: snapshot_ref.new.metadata().expression(),\n\n }\n\n } else {\n\n SnapshotKey::NamedSnapshot { path: &target_file }\n", "file_path": "cargo-insta/src/cli.rs", "rank": 68, "score": 72073.54748115098 }, { "content": "pub fn find_packages(metadata: &Metadata, all: bool) -> Result<Vec<Package>, Box<dyn Error>> {\n\n if all {\n\n Ok(find_all_packages(metadata))\n\n } else {\n\n let default_manifest = get_default_manifest()?\n\n .ok_or_else(|| {\n\n err_msg(\n\n \"Could not find `Cargo.toml` in the current folder or any parent directory.\",\n\n )\n\n })?\n\n .canonicalize()?;\n\n let mut rv = vec![];\n\n for package in &metadata.packages {\n\n if package.manifest_path.canonicalize()? == default_manifest {\n\n rv.push(package.clone());\n\n }\n\n }\n\n if rv.is_empty() {\n\n // if we don't find anything we're in a workspace root that has no\n\n // root member in which case --all is implied.\n\n Ok(find_all_packages(metadata))\n\n } else {\n\n Ok(rv)\n\n }\n\n }\n\n}\n", "file_path": "cargo-insta/src/cargo.rs", "rank": 69, "score": 71145.5197831975 }, { "content": " public provideDefinition(\n\n document: TextDocument,\n\n position: Position,\n\n token: CancellationToken\n\n ): ProviderResult<Definition> {\n\n return this.findSnapshotAtLocation(document, position, token, true).then(\n\n (match) => {\n\n if (!match) {\n\n return null;\n\n }\n\n return workspace.fs.readFile(match.snapshotUri).then((contents) => {\n\n const stringContents = Buffer.from(contents).toString(\"utf-8\");\n\n const header = stringContents.match(SNAPSHOT_HEADER);\n\n let location = new Position(0, 0);\n\n if (header) {\n\n location = new Position(header[0].match(/\\n/g)!.length + 1, 0);\n\n }\n\n return new Location(match.snapshotUri, location);\n\n });\n\n }\n\n );\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 70, "score": 69387.42285081887 }, { "content": "/// If there is a suffix on the settings, append it to the snapshot name.\n\nfn add_suffix_to_snapshot_name(name: Cow<'_, str>) -> Cow<'_, str> {\n\n Settings::with(|settings| {\n\n settings\n\n .snapshot_suffix()\n\n .map(|suffix| Cow::Owned(format!(\"{}@{}\", name, suffix)))\n\n .unwrap_or_else(|| name)\n\n })\n\n}\n\n\n", "file_path": "src/runtime.rs", "rank": 71, "score": 67027.11510261716 }, { "content": "fn get_default_manifest() -> Result<Option<PathBuf>, Box<dyn Error>> {\n\n let output = process::Command::new(get_cargo())\n\n .arg(\"locate-project\")\n\n .output()?;\n\n if output.status.success() {\n\n let loc: ProjectLocation = serde_json::from_slice(&output.stdout)?;\n\n Ok(Some(loc.root))\n\n } else {\n\n Ok(None)\n\n }\n\n}\n\n\n", "file_path": "cargo-insta/src/cargo.rs", "rank": 72, "score": 64178.42274915493 }, { "content": "const SNAPSHOT_HEADER: RegExp = /^---\\s*$(.*?)^---\\s*$/ms;\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 73, "score": 63354.56479582913 }, { "content": "const SNAPSHOT_FUNCTION_STRIP: RegExp = /^test_(.*?)$/;\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 74, "score": 61844.35996300833 }, { "content": "const NAMED_SNAPSHOT_ASSERTION: RegExp = /(?:\\binsta::)?(?:assert(?:_\\w+)?_snapshot!)\\(\\s*['\"]([^'\"]+)['\"]\\s*,/;\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 75, "score": 61844.35996300833 }, { "content": "const UNNAMED_SNAPSHOT_ASSERTION: RegExp = /(?:\\binsta::)?(?:assert(?:_\\w+)?_snapshot!)\\(/;\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 76, "score": 61844.35996300833 }, { "content": "const STRING_INLINE_SNAPSHOT_ASSERTION: RegExp = /(?:\\binsta::)?(?:assert(?:_\\w+)?_snapshot!)\\(\\s*['\"]([^'\"]+)['\"]\\s*,\\s*@(r#*)?[\"']/;\n", "file_path": "vscode-insta/src/SnapshotPathProvider.ts", "rank": 77, "score": 60406.69483048189 }, { "content": "fn process_snapshots(cmd: ProcessCommand, op: Option<Operation>) -> Result<(), Box<dyn Error>> {\n\n let term = Term::stdout();\n\n\n\n let loc = handle_target_args(&cmd.target_args)?;\n\n let mut snapshot_containers = load_snapshot_containers(&loc)?;\n\n\n\n let snapshot_count = snapshot_containers.iter().map(|x| x.0.len()).sum();\n\n\n\n if snapshot_count == 0 {\n\n if !cmd.quiet {\n\n println!(\"{}: no snapshots to review\", style(\"done\").bold());\n\n }\n\n return Ok(());\n\n }\n\n\n\n let mut accepted = vec![];\n\n let mut rejected = vec![];\n\n let mut skipped = vec![];\n\n let mut num = 0;\n\n\n", "file_path": "cargo-insta/src/cli.rs", "rank": 78, "score": 58401.00419059091 }, { "content": "#[test]\n\nfn test_embedded_test() {\n\n assert_snapshot!(\"embedded\", \"Just a string\");\n\n}\n", "file_path": "src/test.rs", "rank": 79, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_simple() {\n\n assert_debug_snapshot!(vec![1, 2, 3, 4], @r###\"\n\n [\n\n 1,\n\n 2,\n\n 3,\n\n 4,\n\n ]\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 80, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_ordering() {\n\n #[derive(Debug, Serialize)]\n\n pub struct User {\n\n id: u64,\n\n username: String,\n\n flags: HashSet<String>,\n\n }\n\n\n\n let mut settings = Settings::new();\n\n settings.add_redaction(\".id\", \"[id]\");\n\n settings.sort_selector(\".flags\");\n\n settings.bind(|| {\n\n assert_json_snapshot!(\n\n \"user_json_flags\",\n\n &User {\n\n id: 122,\n\n username: \"jason_doe\".to_string(),\n\n flags: vec![\"zzz\".into(), \"foo\".into(), \"aha\".into(), \"is_admin\".into()]\n\n .into_iter()\n\n .collect(),\n\n }\n\n );\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 81, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_with_callbacks() {\n\n let mut settings = Settings::new();\n\n settings.add_dynamic_redaction(\".id\", |value, path| {\n\n assert_eq!(path.to_string(), \".id\");\n\n assert_eq!(value.as_u64().unwrap(), 1234);\n\n \"[id]\"\n\n });\n\n settings.bind(|| {\n\n assert_json_snapshot!(\n\n \"user_json_settings_callback\",\n\n &User {\n\n id: 1234,\n\n username: \"jason_doe\".to_string(),\n\n email: Email(\"[email protected]\".to_string()),\n\n extra: \"extra here\".to_string(),\n\n }\n\n );\n\n });\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 82, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_range_checks() {\n\n use similar_asserts::assert_eq;\n\n assert_eq!(PathItem::Index(0, 10).range_check(None, Some(-1)), true);\n\n assert_eq!(PathItem::Index(9, 10).range_check(None, Some(-1)), false);\n\n assert_eq!(PathItem::Index(0, 10).range_check(Some(1), Some(-1)), false);\n\n assert_eq!(PathItem::Index(1, 10).range_check(Some(1), Some(-1)), true);\n\n assert_eq!(PathItem::Index(9, 10).range_check(Some(1), Some(-1)), false);\n\n assert_eq!(PathItem::Index(0, 10).range_check(Some(1), None), false);\n\n assert_eq!(PathItem::Index(1, 10).range_check(Some(1), None), true);\n\n assert_eq!(PathItem::Index(9, 10).range_check(Some(1), None), true);\n\n}\n", "file_path": "src/redaction.rs", "rank": 83, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_display() {\n\n let td = TestDisplay;\n\n assert_display_snapshot!(\"display\", td);\n\n}\n\n\n", "file_path": "tests/test_basic.rs", "rank": 84, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_crlf() {\n\n insta::assert_snapshot!(\"foo\\r\\nbar\\r\\nbaz\");\n\n}\n\n\n", "file_path": "tests/test_bugs.rs", "rank": 85, "score": 56398.26285211811 }, { "content": "fn main() {\n\n if let Err(err) = cli::run() {\n\n let exit_code = if let Some(ref exit) = err.downcast_ref::<utils::QuietExit>() {\n\n exit.0\n\n } else {\n\n println!(\"{} {}\", style(\"error:\").red().bold(), err);\n\n 1\n\n };\n\n std::process::exit(exit_code);\n\n }\n\n}\n", "file_path": "cargo-insta/src/main.rs", "rank": 86, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_simple() {\n\n let mut map = HashMap::new();\n\n map.insert(\"a\", \"first value\");\n\n map.insert(\"b\", \"second value\");\n\n map.insert(\"c\", \"third value\");\n\n map.insert(\"d\", \"fourth value\");\n\n\n\n let mut settings = Settings::new();\n\n settings.set_sort_maps(true);\n\n settings.bind(|| {\n\n assert_yaml_snapshot!(&map, @r###\"\n\n ---\n\n a: first value\n\n b: second value\n\n c: third value\n\n d: fourth value\n\n \"###);\n\n });\n\n}\n\n\n", "file_path": "tests/test_settings.rs", "rank": 87, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_newline() {\n\n // https://github.com/mitsuhiko/insta/issues/39\n\n assert_snapshot!(\"\\n\", @\"\n\n\");\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 88, "score": 56398.26285211811 }, { "content": "#[test]\n\nfn test_selector_parser() {\n\n macro_rules! assert_selector_snapshot {\n\n ($short:expr, $sel:expr) => {\n\n assert_debug_snapshot!($short, Selector::parse($sel).unwrap());\n\n };\n\n }\n\n\n\n assert_selector_snapshot!(\"foo_bar\", \".foo.bar\");\n\n assert_selector_snapshot!(\"foo_bar_alt\", \".foo[\\\"bar\\\"]\");\n\n assert_selector_snapshot!(\"foo_bar_full_range\", \".foo.bar[]\");\n\n assert_selector_snapshot!(\"foo_bar_range_to\", \".foo.bar[:10]\");\n\n assert_selector_snapshot!(\"foo_bar_range_from\", \".foo.bar[10:]\");\n\n assert_selector_snapshot!(\"foo_bar_range\", \".foo.bar[10:20]\");\n\n assert_selector_snapshot!(\"foo_bar_deep\", \".foo.bar.**\");\n\n}\n\n\n\n#[derive(Serialize)]\n\npub struct Email(String);\n\n\n\n#[derive(Serialize)]\n\npub struct User {\n\n id: u32,\n\n username: String,\n\n email: Email,\n\n extra: String,\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 89, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_debug_vector() {\n\n assert_debug_snapshot!(\"debug_vector\", vec![1, 2, 3]);\n\n}\n\n\n", "file_path": "tests/test_basic.rs", "rank": 90, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_redact_recursive() {\n\n #[derive(Serialize)]\n\n pub struct Node {\n\n id: u64,\n\n next: Option<Box<Node>>,\n\n }\n\n\n\n let root = Node {\n\n id: 0,\n\n next: Some(Box::new(Node { id: 1, next: None })),\n\n };\n\n\n\n assert_json_snapshot!(root, {\n\n \".**.id\" => \"[id]\",\n\n }, @r###\"\n\n {\n\n \"id\": \"[id]\",\n\n \"next\": {\n\n \"id\": \"[id]\",\n\n \"next\": null\n\n }\n\n }\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_redaction.rs", "rank": 91, "score": 55214.629345854 }, { "content": "#[cfg(feature = \"toml\")]\n\n#[test]\n\nfn test_toml_inline() {\n\n #[derive(Serialize)]\n\n pub struct Email(String);\n\n\n\n #[derive(Serialize)]\n\n pub struct User {\n\n id: u32,\n\n username: String,\n\n email: Email,\n\n }\n\n\n\n assert_toml_snapshot!(User {\n\n id: 42,\n\n username: \"peter-doe\".into(),\n\n email: Email(\"[email protected]\".into()),\n\n }, @r###\"\n\n id = 42\n\n username = 'peter-doe'\n\n email = '[email protected]'\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 92, "score": 55214.629345854 }, { "content": "#[cfg(feature = \"csv\")]\n\n#[test]\n\nfn test_csv_inline() {\n\n #[derive(Serialize)]\n\n pub struct Email(String);\n\n\n\n #[derive(Serialize)]\n\n pub struct User {\n\n id: u32,\n\n username: String,\n\n email: Email,\n\n }\n\n\n\n assert_csv_snapshot!(User {\n\n id: 1453,\n\n username: \"mehmed-doe\".into(),\n\n email: Email(\"[email protected]\".into()),\n\n }, @r###\"\n\n id,username,email\n\n 1453,mehmed-doe,[email protected]\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 93, "score": 55214.629345854 }, { "content": "#[cfg(feature = \"ron\")]\n\n#[test]\n\nfn test_ron_inline() {\n\n #[derive(Serialize)]\n\n pub struct Email(String);\n\n\n\n #[derive(Serialize)]\n\n pub struct User {\n\n id: u32,\n\n username: String,\n\n email: Email,\n\n }\n\n\n\n assert_ron_snapshot!(User {\n\n id: 42,\n\n username: \"peter-doe\".into(),\n\n email: Email(\"[email protected]\".into()),\n\n }, @r###\"\n\n User(\n\n id: 42,\n\n username: \"peter-doe\",\n\n email: Email(\"[email protected]\"),\n\n )\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 94, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_basic_globbing() {\n\n insta::glob!(\"inputs/*.txt\", |path| {\n\n let contents = std::fs::read_to_string(path).unwrap();\n\n insta::assert_json_snapshot!(&contents);\n\n });\n\n}\n\n\n", "file_path": "tests/test_glob.rs", "rank": 95, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_yaml_vector() {\n\n assert_yaml_snapshot!(\"yaml_vector\", vec![1, 2, 3]);\n\n}\n\n\n", "file_path": "tests/test_basic.rs", "rank": 96, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_yaml_inline() {\n\n #[derive(Serialize)]\n\n pub struct User {\n\n id: u32,\n\n username: String,\n\n email: String,\n\n }\n\n\n\n assert_yaml_snapshot!(User {\n\n id: 42,\n\n username: \"peter-pan\".into(),\n\n email: \"[email protected]\".into()\n\n }, @r###\"\n\n ---\n\n id: 42\n\n username: peter-pan\n\n email: [email protected]\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 97, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_trailing_crlf() {\n\n insta::assert_snapshot!(\"foo\\r\\nbar\\r\\nbaz\\r\\n\");\n\n}\n\n\n", "file_path": "tests/test_bugs.rs", "rank": 98, "score": 55214.629345854 }, { "content": "#[test]\n\nfn test_json_inline() {\n\n assert_json_snapshot!(vec![\"foo\", \"bar\"], @r###\"\n\n [\n\n \"foo\",\n\n \"bar\"\n\n ]\n\n \"###);\n\n}\n\n\n", "file_path": "tests/test_inline.rs", "rank": 99, "score": 55214.629345854 } ]
Rust
tests/geometry/dual_quaternion.rs
zyansheep/nalgebra
e913beca889dc278d1c0d6cadd2008d3f9bcc0af
#![cfg(feature = "proptest-support")] #![allow(non_snake_case)] use na::{DualQuaternion, Point3, Unit, UnitDualQuaternion, UnitQuaternion, Vector3}; use crate::proptest::*; use proptest::{prop_assert, proptest}; proptest!( #[test] fn isometry_equivalence(iso in isometry3(), p in point3(), v in vector3()) { let dq = UnitDualQuaternion::from_isometry(&iso); prop_assert!(relative_eq!(iso * p, dq * p, epsilon = 1.0e-7)); prop_assert!(relative_eq!(iso * v, dq * v, epsilon = 1.0e-7)); } #[test] fn inverse_is_identity(i in unit_dual_quaternion(), p in point3(), v in vector3()) { let ii = i.inverse(); prop_assert!(relative_eq!(i * ii, UnitDualQuaternion::identity(), epsilon = 1.0e-7) && relative_eq!(ii * i, UnitDualQuaternion::identity(), epsilon = 1.0e-7) && relative_eq!((i * ii) * p, p, epsilon = 1.0e-7) && relative_eq!((ii * i) * p, p, epsilon = 1.0e-7) && relative_eq!((i * ii) * v, v, epsilon = 1.0e-7) && relative_eq!((ii * i) * v, v, epsilon = 1.0e-7)); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn multiply_equals_alga_transform( dq in unit_dual_quaternion(), v in vector3(), p in point3() ) { prop_assert!(dq * v == dq.transform_vector(&v) && dq * p == dq.transform_point(&p) && relative_eq!( dq.inverse() * v, dq.inverse_transform_vector(&v), epsilon = 1.0e-7 ) && relative_eq!( dq.inverse() * p, dq.inverse_transform_point(&p), epsilon = 1.0e-7 )); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn composition( dq in unit_dual_quaternion(), uq in unit_quaternion(), t in translation3(), v in vector3(), p in point3() ) { prop_assert!(relative_eq!((uq * dq) * v, uq * (dq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((uq * dq) * p, uq * (dq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * uq) * v, dq * (uq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * uq) * p, dq * (uq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((t * dq) * v, (dq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((t * dq) * p, t * (dq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * t) * v, dq * v, epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * t) * p, dq * (t * p), epsilon = 1.0e-7)); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn sclerp_is_defined_for_identical_orientations( dq in unit_dual_quaternion(), s in -1.0f64..2.0f64, t in translation3(), ) { prop_assert!(relative_eq!(dq.sclerp(&dq, 0.0), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, 0.5), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, 1.0), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, s), dq, epsilon = 1.0e-7)); let unit = UnitDualQuaternion::identity(); prop_assert!(relative_eq!(unit.sclerp(&unit, 0.0), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, 0.5), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, 1.0), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, s), unit, epsilon = 1.0e-7)); let dq2 = t * dq; prop_assert!(relative_eq!(dq.sclerp(&dq2, 0.0).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, 0.5).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, 1.0).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, s).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!( dq.sclerp(&dq2, s).translation().vector, dq.translation().vector.lerp(&dq2.translation().vector, s), epsilon = 1.0e-7 )); let unit2 = t * unit; prop_assert!(relative_eq!(unit.sclerp(&unit2, 0.0).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 0.5).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 1.0).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, s).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!( unit.sclerp(&unit2, s).translation().vector, unit.translation().vector.lerp(&unit2.translation().vector, s), epsilon = 1.0e-7 )); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn sclerp_is_not_defined_for_opposite_orientations( dq in unit_dual_quaternion(), s in 0.1f64..0.9f64, t in translation3(), t2 in translation3(), v in vector3(), ) { let iso = dq.to_isometry(); let rot = iso.rotation; if let Some((axis, angle)) = rot.axis_angle() { let flipped = UnitQuaternion::from_axis_angle(&axis, angle + std::f64::consts::PI); let dqf = flipped * rot.inverse() * dq.clone(); prop_assert!(dq.try_sclerp(&dqf, 0.5, 1.0e-7).is_none()); prop_assert!(dq.try_sclerp(&dqf, s, 1.0e-7).is_none()); } let dq2 = t * dq; let iso2 = dq2.to_isometry(); let rot2 = iso2.rotation; if let Some((axis, angle)) = rot2.axis_angle() { let flipped = UnitQuaternion::from_axis_angle(&axis, angle + std::f64::consts::PI); let dq3f = t2 * flipped * rot.inverse() * dq.clone(); prop_assert!(dq2.try_sclerp(&dq3f, 0.5, 1.0e-7).is_none()); prop_assert!(dq2.try_sclerp(&dq3f, s, 1.0e-7).is_none()); } if let Some(axis) = Unit::try_new(v, 1.0e-7) { let unit = UnitDualQuaternion::identity(); let flip = UnitQuaternion::from_axis_angle(&axis, std::f64::consts::PI); let unitf = flip * unit; prop_assert!(unit.try_sclerp(&unitf, 0.5, 1.0e-7).is_none()); prop_assert!(unit.try_sclerp(&unitf, s, 1.0e-7).is_none()); let unit2f = t * unit * flip; prop_assert!(unit.try_sclerp(&unit2f, 0.5, 1.0e-7).is_none()); prop_assert!(unit.try_sclerp(&unit2f, s, 1.0e-7).is_none()); } } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn all_op_exist( dq in dual_quaternion(), udq in unit_dual_quaternion(), uq in unit_quaternion(), s in PROPTEST_F64, t in translation3(), v in vector3(), p in point3() ) { let dqMs: DualQuaternion<_> = dq * s; let dqMdq: DualQuaternion<_> = dq * dq; let dqMudq: DualQuaternion<_> = dq * udq; let udqMdq: DualQuaternion<_> = udq * dq; let iMi: UnitDualQuaternion<_> = udq * udq; let iMuq: UnitDualQuaternion<_> = udq * uq; let iDi: UnitDualQuaternion<_> = udq / udq; let iDuq: UnitDualQuaternion<_> = udq / uq; let iMp: Point3<_> = udq * p; let iMv: Vector3<_> = udq * v; let iMt: UnitDualQuaternion<_> = udq * t; let tMi: UnitDualQuaternion<_> = t * udq; let uqMi: UnitDualQuaternion<_> = uq * udq; let uqDi: UnitDualQuaternion<_> = uq / udq; let mut dqMs1 = dq; let mut dqMdq1 = dq; let mut dqMdq2 = dq; let mut dqMudq1 = dq; let mut dqMudq2 = dq; let mut iMt1 = udq; let mut iMt2 = udq; let mut iMi1 = udq; let mut iMi2 = udq; let mut iMuq1 = udq; let mut iMuq2 = udq; let mut iDi1 = udq; let mut iDi2 = udq; let mut iDuq1 = udq; let mut iDuq2 = udq; dqMs1 *= s; dqMdq1 *= dq; dqMdq2 *= &dq; dqMudq1 *= udq; dqMudq2 *= &udq; iMt1 *= t; iMt2 *= &t; iMi1 *= udq; iMi2 *= &udq; iMuq1 *= uq; iMuq2 *= &uq; iDi1 /= udq; iDi2 /= &udq; iDuq1 /= uq; iDuq2 /= &uq; prop_assert!(dqMs == dqMs1 && dqMdq == dqMdq1 && dqMdq == dqMdq2 && dqMudq == dqMudq1 && dqMudq == dqMudq2 && iMt == iMt1 && iMt == iMt2 && iMi == iMi1 && iMi == iMi2 && iMuq == iMuq1 && iMuq == iMuq2 && iDi == iDi1 && iDi == iDi2 && iDuq == iDuq1 && iDuq == iDuq2 && dqMs == &dq * s && dqMdq == &dq * &dq && dqMdq == dq * &dq && dqMdq == &dq * dq && dqMudq == &dq * &udq && dqMudq == dq * &udq && dqMudq == &dq * udq && udqMdq == &udq * &dq && udqMdq == udq * &dq && udqMdq == &udq * dq && iMi == &udq * &udq && iMi == udq * &udq && iMi == &udq * udq && iMuq == &udq * &uq && iMuq == udq * &uq && iMuq == &udq * uq && iDi == &udq / &udq && iDi == udq / &udq && iDi == &udq / udq && iDuq == &udq / &uq && iDuq == udq / &uq && iDuq == &udq / uq && iMp == &udq * &p && iMp == udq * &p && iMp == &udq * p && iMv == &udq * &v && iMv == udq * &v && iMv == &udq * v && iMt == &udq * &t && iMt == udq * &t && iMt == &udq * t && tMi == &t * &udq && tMi == t * &udq && tMi == &t * udq && uqMi == &uq * &udq && uqMi == uq * &udq && uqMi == &uq * udq && uqDi == &uq / &udq && uqDi == uq / &udq && uqDi == &uq / udq) } );
#![cfg(feature = "proptest-support")] #![allow(non_snake_case)] use na::{DualQuaternion, Point3, Unit, UnitDualQuaternion, UnitQuaternion, Vector3}; use crate::proptest::*; use proptest::{prop_assert, proptest}; proptest!( #[test] fn isometry_equivalence(iso in isometry3(), p in point3(), v in vector3()) { let dq = UnitDualQuaternion::from_isometry(&iso); prop_assert!(relative_eq!(iso * p, dq * p, epsilon = 1.0e-7)); prop_assert!(relative_eq!(iso * v, dq * v, epsilon = 1.0e-7)); } #[test] fn inverse_is_identity(i in unit_dual_quaternion(), p in point3(), v in vector3()) { let ii = i.inverse(); prop_assert!(relative_eq!(i * ii, UnitDualQuaternion::identity(), epsilon = 1.0e-7) && relative_eq!(ii * i, UnitDualQuaternion::identity(), epsilon = 1.0e-7) && relative_eq!((i * ii) * p, p, epsilon = 1.0e-7) && relative_eq!((ii * i) * p, p, epsilon = 1.0e-7) && relative_eq!((i * ii) * v, v, epsilon = 1.0e-7) && relative_eq!((ii * i) * v, v, epsilon = 1.0e-7)); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn multiply_equals_alga_transform( dq in unit_dual_quaternion(), v in vector3(), p in point3() ) { prop_assert!(dq * v == dq.transform_vector(&v) && dq * p == dq.transform_point(&p) && relative_eq!( dq.inverse() * v, dq.inverse_transform_vector(&v), epsilon = 1.0e-7 ) && relative_eq!( dq.inverse() * p, dq.inverse_transform_point(&p), epsilon = 1.0e-7 )); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn composition( dq in unit_dual_quaternion(), uq in unit_quaternion(), t in translation3(), v in vector3(), p in point3() ) { prop_assert!(relative_eq!((uq * dq) * v, uq * (dq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((uq * dq) * p, uq * (dq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * uq) * v, dq * (uq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * uq) * p, dq * (uq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((t * dq) * v, (dq * v), epsilon = 1.0e-7)); prop_assert!(relative_eq!((t * dq) * p, t * (dq * p), epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * t) * v, dq * v, epsilon = 1.0e-7)); prop_assert!(relative_eq!((dq * t) * p, dq * (t * p), epsilon = 1.0e-7)); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn sclerp_is_defined_for_identical_orientations( dq in unit_dual_quaternion(), s in -1.0f64..2.0f64, t in translation3(), ) { prop_assert!(relative_eq!(dq.sclerp(&dq, 0.0), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, 0.5), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, 1.0), dq, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq, s), dq, epsilon = 1.0e-7)); let unit = UnitDualQuaternion::identity(); prop_assert!(relative_eq!(unit.sclerp(&unit, 0.0), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, 0.5), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, 1.0), unit, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit, s), unit, epsilon = 1.0e-7)); let dq2 = t * dq; prop_assert!(relative_eq!(dq.sclerp(&dq2, 0.0).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, 0.5).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, 1.0).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(dq.sclerp(&dq2, s).real, dq.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!( dq.sclerp(&dq2, s).translation().vector, dq.translation().vector.lerp(&dq2.translation().vector, s), epsilon = 1.0e-7 )); let unit2 = t * unit; prop_assert!(relative_eq!(unit.sclerp(&unit2, 0.0).real, unit.real, epsilon =
fn all_op_exist( dq in dual_quaternion(), udq in unit_dual_quaternion(), uq in unit_quaternion(), s in PROPTEST_F64, t in translation3(), v in vector3(), p in point3() ) { let dqMs: DualQuaternion<_> = dq * s; let dqMdq: DualQuaternion<_> = dq * dq; let dqMudq: DualQuaternion<_> = dq * udq; let udqMdq: DualQuaternion<_> = udq * dq; let iMi: UnitDualQuaternion<_> = udq * udq; let iMuq: UnitDualQuaternion<_> = udq * uq; let iDi: UnitDualQuaternion<_> = udq / udq; let iDuq: UnitDualQuaternion<_> = udq / uq; let iMp: Point3<_> = udq * p; let iMv: Vector3<_> = udq * v; let iMt: UnitDualQuaternion<_> = udq * t; let tMi: UnitDualQuaternion<_> = t * udq; let uqMi: UnitDualQuaternion<_> = uq * udq; let uqDi: UnitDualQuaternion<_> = uq / udq; let mut dqMs1 = dq; let mut dqMdq1 = dq; let mut dqMdq2 = dq; let mut dqMudq1 = dq; let mut dqMudq2 = dq; let mut iMt1 = udq; let mut iMt2 = udq; let mut iMi1 = udq; let mut iMi2 = udq; let mut iMuq1 = udq; let mut iMuq2 = udq; let mut iDi1 = udq; let mut iDi2 = udq; let mut iDuq1 = udq; let mut iDuq2 = udq; dqMs1 *= s; dqMdq1 *= dq; dqMdq2 *= &dq; dqMudq1 *= udq; dqMudq2 *= &udq; iMt1 *= t; iMt2 *= &t; iMi1 *= udq; iMi2 *= &udq; iMuq1 *= uq; iMuq2 *= &uq; iDi1 /= udq; iDi2 /= &udq; iDuq1 /= uq; iDuq2 /= &uq; prop_assert!(dqMs == dqMs1 && dqMdq == dqMdq1 && dqMdq == dqMdq2 && dqMudq == dqMudq1 && dqMudq == dqMudq2 && iMt == iMt1 && iMt == iMt2 && iMi == iMi1 && iMi == iMi2 && iMuq == iMuq1 && iMuq == iMuq2 && iDi == iDi1 && iDi == iDi2 && iDuq == iDuq1 && iDuq == iDuq2 && dqMs == &dq * s && dqMdq == &dq * &dq && dqMdq == dq * &dq && dqMdq == &dq * dq && dqMudq == &dq * &udq && dqMudq == dq * &udq && dqMudq == &dq * udq && udqMdq == &udq * &dq && udqMdq == udq * &dq && udqMdq == &udq * dq && iMi == &udq * &udq && iMi == udq * &udq && iMi == &udq * udq && iMuq == &udq * &uq && iMuq == udq * &uq && iMuq == &udq * uq && iDi == &udq / &udq && iDi == udq / &udq && iDi == &udq / udq && iDuq == &udq / &uq && iDuq == udq / &uq && iDuq == &udq / uq && iMp == &udq * &p && iMp == udq * &p && iMp == &udq * p && iMv == &udq * &v && iMv == udq * &v && iMv == &udq * v && iMt == &udq * &t && iMt == udq * &t && iMt == &udq * t && tMi == &t * &udq && tMi == t * &udq && tMi == &t * udq && uqMi == &uq * &udq && uqMi == uq * &udq && uqMi == &uq * udq && uqDi == &uq / &udq && uqDi == uq / &udq && uqDi == &uq / udq) } );
1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 0.5).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, 1.0).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!(unit.sclerp(&unit2, s).real, unit.real, epsilon = 1.0e-7)); prop_assert!(relative_eq!( unit.sclerp(&unit2, s).translation().vector, unit.translation().vector.lerp(&unit2.translation().vector, s), epsilon = 1.0e-7 )); } #[cfg_attr(rustfmt, rustfmt_skip)] #[test] fn sclerp_is_not_defined_for_opposite_orientations( dq in unit_dual_quaternion(), s in 0.1f64..0.9f64, t in translation3(), t2 in translation3(), v in vector3(), ) { let iso = dq.to_isometry(); let rot = iso.rotation; if let Some((axis, angle)) = rot.axis_angle() { let flipped = UnitQuaternion::from_axis_angle(&axis, angle + std::f64::consts::PI); let dqf = flipped * rot.inverse() * dq.clone(); prop_assert!(dq.try_sclerp(&dqf, 0.5, 1.0e-7).is_none()); prop_assert!(dq.try_sclerp(&dqf, s, 1.0e-7).is_none()); } let dq2 = t * dq; let iso2 = dq2.to_isometry(); let rot2 = iso2.rotation; if let Some((axis, angle)) = rot2.axis_angle() { let flipped = UnitQuaternion::from_axis_angle(&axis, angle + std::f64::consts::PI); let dq3f = t2 * flipped * rot.inverse() * dq.clone(); prop_assert!(dq2.try_sclerp(&dq3f, 0.5, 1.0e-7).is_none()); prop_assert!(dq2.try_sclerp(&dq3f, s, 1.0e-7).is_none()); } if let Some(axis) = Unit::try_new(v, 1.0e-7) { let unit = UnitDualQuaternion::identity(); let flip = UnitQuaternion::from_axis_angle(&axis, std::f64::consts::PI); let unitf = flip * unit; prop_assert!(unit.try_sclerp(&unitf, 0.5, 1.0e-7).is_none()); prop_assert!(unit.try_sclerp(&unitf, s, 1.0e-7).is_none()); let unit2f = t * unit * flip; prop_assert!(unit.try_sclerp(&unit2f, 0.5, 1.0e-7).is_none()); prop_assert!(unit.try_sclerp(&unit2f, s, 1.0e-7).is_none()); } } #[cfg_attr(rustfmt, rustfmt_skip)] #[test]
random
[ { "content": "fn length_on_direction_with_unit(v: &Vector3<f32>, dir: &Unit<Vector3<f32>>) -> f32 {\n\n // No need to normalize `dir`: we know that it is non-zero and normalized.\n\n v.dot(dir.as_ref())\n\n}\n\n\n", "file_path": "examples/unit_wrapper.rs", "rank": 0, "score": 256287.2837648631 }, { "content": "pub fn unit_quaternion() -> impl Strategy<Value = UnitQuaternion<f64>> {\n\n vector3().prop_map(|v| UnitQuaternion::new(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 1, "score": 247399.01367394795 }, { "content": "pub fn isometry3() -> impl Strategy<Value = Isometry3<f64>> {\n\n vector6().prop_map(|v| Isometry3::new(v.xyz(), Vector3::new(v.w, v.a, v.b)))\n\n}\n\n\n\n// pub fn similarity2() -> impl Strategy<Value = Similarity2<f64>> {\n\n// vector4().prop_map(|v| Similarity2::new(v.xy(), v.z, v.w))\n\n// }\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 2, "score": 240460.90496780886 }, { "content": "pub fn translation3() -> impl Strategy<Value = Translation3<f64>> {\n\n vector3().prop_map(|v| Translation3::from(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 3, "score": 240460.90496780886 }, { "content": "pub fn point3() -> impl Strategy<Value = Point3<f64>> {\n\n vector3().prop_map(|v| Point3::from(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 4, "score": 240457.9322176549 }, { "content": "pub fn unit_dual_quaternion() -> impl Strategy<Value = UnitDualQuaternion<f64>> {\n\n isometry3().prop_map(|iso| UnitDualQuaternion::from_isometry(&iso))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 5, "score": 239270.8757054782 }, { "content": "fn length_on_direction_without_unit(v: &Vector3<f32>, dir: &Vector3<f32>) -> f32 {\n\n // Obligatory normalization of the direction vector (and test, for robustness).\n\n if let Some(unit_dir) = dir.try_normalize(1.0e-6) {\n\n v.dot(&unit_dir)\n\n } else {\n\n // Normalization failed because the norm was too small.\n\n panic!(\"Invalid input direction.\")\n\n }\n\n}\n\n\n", "file_path": "examples/unit_wrapper.rs", "rank": 6, "score": 227031.86230792972 }, { "content": "/// Reflects a 3D vector wrt. the 3D plane with normal `plane_normal`.\n\n/// /!\\ This is an exact replicate of `reflect_wrt_hyperplane2, but for 3D.\n\nfn reflect_wrt_hyperplane3<T>(plane_normal: &Unit<Vector3<T>>, vector: &Vector3<T>) -> Vector3<T>\n\nwhere\n\n T: RealField,\n\n{\n\n let n = plane_normal.as_ref(); // Get the underlying Vector3\n\n vector - n * (n.dot(vector) * na::convert(2.0))\n\n}\n\n\n", "file_path": "examples/dimensional_genericity.rs", "rank": 7, "score": 206566.82360160045 }, { "content": "#[test]\n\n#[ignore]\n\nfn coo_no_duplicates_generates_admissible_matrices() {\n\n //TODO\n\n}\n\n\n\n#[cfg(feature = \"slow-tests\")]\n\nmod slow {\n\n use nalgebra::DMatrix;\n\n use nalgebra_sparse::proptest::{\n\n coo_no_duplicates, coo_with_duplicates, csc, csr, sparsity_pattern,\n\n };\n\n\n\n use itertools::Itertools;\n\n use proptest::strategy::ValueTree;\n\n use proptest::test_runner::TestRunner;\n\n\n\n use proptest::prelude::*;\n\n\n\n use nalgebra_sparse::csr::CsrMatrix;\n\n use std::collections::HashSet;\n\n use std::iter::repeat;\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 8, "score": 204100.6741722116 }, { "content": "pub fn unit_complex() -> impl Strategy<Value = UnitComplex<f64>> {\n\n PROPTEST_F64.prop_map(|v| UnitComplex::new(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 9, "score": 189973.90117966058 }, { "content": "#[test]\n\nfn test_matrix_output_types() {\n\n // Test that the dimension types are correct for the given inputs\n\n let _: MatrixStrategy<_, U3, U4> = matrix(-5..5, Const::<3>, Const::<4>);\n\n let _: MatrixStrategy<_, U3, U3> = matrix(-5..5, Const::<3>, Const::<3>);\n\n let _: MatrixStrategy<_, U3, Dynamic> = matrix(-5..5, Const::<3>, 1..=5);\n\n let _: MatrixStrategy<_, Dynamic, U3> = matrix(-5..5, 1..=5, Const::<3>);\n\n let _: MatrixStrategy<_, Dynamic, Dynamic> = matrix(-5..5, 1..=5, 1..=5);\n\n}\n\n\n\n// Below we have some tests to ensure that specific instances of OMatrix are usable\n\n// in a typical proptest scenario where we (implicitly) use the `Arbitrary` trait\n\nproptest! {\n\n #[test]\n\n fn ensure_arbitrary_test_compiles_matrix3(_: Matrix3<i32>) {}\n\n\n\n #[test]\n\n fn ensure_arbitrary_test_compiles_matrixmn_u3_dynamic(_: OMatrix<i32, U3, Dynamic>) {}\n\n\n\n #[test]\n\n fn ensure_arbitrary_test_compiles_matrixmn_dynamic_u3(_: OMatrix<i32, Dynamic, U3>) {}\n", "file_path": "tests/proptest/mod.rs", "rank": 10, "score": 178081.97400222166 }, { "content": "#[test]\n\nfn cs_cholesky() {\n\n let mut a = Matrix5::new(\n\n 40.0, 0.0, 0.0, 0.0, 0.0,\n\n 2.0, 60.0, 0.0, 0.0, 0.0,\n\n 1.0, 0.0, 11.0, 0.0, 0.0,\n\n 0.0, 0.0, 0.0, 50.0, 0.0,\n\n 1.0, 0.0, 0.0, 4.0, 10.0\n\n );\n\n a.fill_upper_triangle_with_lower_triangle();\n\n test_cholesky(a);\n\n\n\n let a = Matrix5::from_diagonal(&Vector5::new(40.0, 60.0, 11.0, 50.0, 10.0));\n\n test_cholesky(a);\n\n\n\n let mut a = Matrix5::new(\n\n 40.0, 0.0, 0.0, 0.0, 0.0,\n\n 2.0, 60.0, 0.0, 0.0, 0.0,\n\n 1.0, 0.0, 11.0, 0.0, 0.0,\n\n 1.0, 0.0, 0.0, 50.0, 0.0,\n\n 0.0, 0.0, 0.0, 4.0, 10.0\n", "file_path": "nalgebra-sparse/tests/unit_tests/cholesky.rs", "rank": 11, "score": 173724.49224431225 }, { "content": "/// Helper function to help us call dense GEMM with our `Op` type\n\nfn dense_gemm<'a>(\n\n beta: i32,\n\n c: impl Into<DMatrixSliceMut<'a, i32>>,\n\n alpha: i32,\n\n a: Op<impl Into<DMatrixSlice<'a, i32>>>,\n\n b: Op<impl Into<DMatrixSlice<'a, i32>>>,\n\n) {\n\n let mut c = c.into();\n\n let a = a.convert();\n\n let b = b.convert();\n\n\n\n use Op::{NoOp, Transpose};\n\n match (a, b) {\n\n (NoOp(a), NoOp(b)) => c.gemm(alpha, &a, &b, beta),\n\n (Transpose(a), NoOp(b)) => c.gemm(alpha, &a.transpose(), &b, beta),\n\n (NoOp(a), Transpose(b)) => c.gemm(alpha, &a, &b.transpose(), beta),\n\n (Transpose(a), Transpose(b)) => c.gemm(alpha, &a.transpose(), &b.transpose(), beta),\n\n }\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 12, "score": 171364.4107619842 }, { "content": "#[test]\n\nfn test_convert_csr_coo() {\n\n let csr = CsrMatrix::try_from_csr_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 2, 5],\n\n vec![1, 3, 0, 2, 3],\n\n vec![5, 4, 1, 1, 4],\n\n )\n\n .unwrap();\n\n\n\n let expected_coo = CooMatrix::try_from_triplets(\n\n 3,\n\n 4,\n\n vec![0, 1, 2, 2, 2],\n\n vec![1, 3, 0, 2, 3],\n\n vec![5, 4, 1, 1, 4],\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(convert_csr_coo(&csr), expected_coo);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 13, "score": 170000.0168365574 }, { "content": "#[test]\n\nfn test_convert_coo_csc() {\n\n // No duplicates\n\n {\n\n let coo = {\n\n let mut coo = CooMatrix::new(3, 4);\n\n coo.push(1, 3, 4);\n\n coo.push(0, 1, 2);\n\n coo.push(2, 0, 1);\n\n coo.push(2, 3, 2);\n\n coo.push(2, 2, 1);\n\n coo\n\n };\n\n\n\n let expected_csc = CscMatrix::try_from_csc_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 2, 3, 5],\n\n vec![2, 0, 2, 1, 2],\n\n vec![1, 2, 1, 4, 2],\n\n )\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 14, "score": 170000.0168365574 }, { "content": "#[test]\n\nfn test_convert_csc_coo() {\n\n let csc = CscMatrix::try_from_csc_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 2, 3, 5],\n\n vec![2, 0, 2, 1, 2],\n\n vec![1, 2, 1, 4, 2],\n\n )\n\n .unwrap();\n\n\n\n let expected_coo = CooMatrix::try_from_triplets(\n\n 3,\n\n 4,\n\n vec![2, 0, 2, 1, 2],\n\n vec![0, 1, 2, 3, 3],\n\n vec![1, 2, 1, 4, 2],\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(convert_csc_coo(&csc), expected_coo);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 15, "score": 170000.0168365574 }, { "content": "#[test]\n\nfn test_convert_coo_csr() {\n\n // No duplicates\n\n {\n\n let coo = {\n\n let mut coo = CooMatrix::new(3, 4);\n\n coo.push(1, 3, 4);\n\n coo.push(0, 1, 2);\n\n coo.push(2, 0, 1);\n\n coo.push(2, 3, 2);\n\n coo.push(2, 2, 1);\n\n coo\n\n };\n\n\n\n let expected_csr = CsrMatrix::try_from_csr_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 2, 5],\n\n vec![1, 3, 0, 2, 3],\n\n vec![2, 4, 1, 1, 2],\n\n )\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 16, "score": 170000.0168365574 }, { "content": "#[test]\n\nfn test_convert_dense_coo() {\n\n // No duplicates\n\n {\n\n #[rustfmt::skip]\n\n let entries = &[1, 0, 3,\n\n 0, 5, 0];\n\n // The COO representation of a dense matrix is not unique.\n\n // Here we implicitly test that the coo matrix is indeed constructed from column-major\n\n // iteration of the dense matrix.\n\n let dense = DMatrix::from_row_slice(2, 3, entries);\n\n let coo = CooMatrix::try_from_triplets(2, 3, vec![0, 1, 0], vec![0, 1, 2], vec![1, 5, 3])\n\n .unwrap();\n\n\n\n assert_eq!(CooMatrix::from(&dense), coo);\n\n assert_eq!(DMatrix::from(&coo), dense);\n\n }\n\n\n\n // Duplicates\n\n // No duplicates\n\n {\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 17, "score": 170000.0168365574 }, { "content": "fn test_cholesky(a: Matrix5<f64>) {\n\n // TODO: Test \"refactor\"\n\n\n\n let cs_a = CscMatrix::from(&a);\n\n\n\n let chol_a = Cholesky::new(a).unwrap();\n\n let chol_cs_a = CscCholesky::factor(&cs_a).unwrap();\n\n\n\n let l = chol_a.l();\n\n let cs_l = chol_cs_a.take_l();\n\n\n\n let l = DMatrix::from_iterator(l.nrows(), l.ncols(), l.iter().cloned());\n\n let cs_l_mat = DMatrix::from(&cs_l);\n\n assert_matrix_eq!(l, cs_l_mat, comp = abs, tol = 1e-12);\n\n}", "file_path": "nalgebra-sparse/tests/unit_tests/cholesky.rs", "rank": 18, "score": 167215.64256449693 }, { "content": "#[test]\n\nfn test_convert_csr_csc_bidirectional() {\n\n let csr = CsrMatrix::try_from_csr_data(\n\n 3,\n\n 4,\n\n vec![0, 3, 4, 6],\n\n vec![1, 2, 3, 0, 1, 3],\n\n vec![5, 3, 2, 2, 1, 4],\n\n )\n\n .unwrap();\n\n\n\n let csc = CscMatrix::try_from_csc_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 3, 4, 6],\n\n vec![1, 0, 2, 0, 0, 2],\n\n vec![2, 5, 1, 3, 2, 4],\n\n )\n\n .unwrap();\n\n\n\n assert_eq!(convert_csr_csc(&csr), csc);\n\n assert_eq!(convert_csc_csr(&csc), csr);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 19, "score": 166898.969725746 }, { "content": "#[test]\n\nfn test_convert_csr_dense_bidirectional() {\n\n let csr = CsrMatrix::try_from_csr_data(\n\n 3,\n\n 4,\n\n vec![0, 3, 4, 6],\n\n vec![1, 2, 3, 0, 1, 3],\n\n vec![5, 3, 2, 2, 1, 4],\n\n )\n\n .unwrap();\n\n\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(3, 4, &[\n\n 0, 5, 3, 2,\n\n 2, 0, 0, 0,\n\n 0, 1, 0, 4\n\n ]);\n\n\n\n assert_eq!(convert_csr_dense(&csr), dense);\n\n assert_eq!(convert_dense_csr(&dense), csr);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 20, "score": 166898.969725746 }, { "content": "#[test]\n\nfn test_convert_csc_dense_bidirectional() {\n\n let csc = CscMatrix::try_from_csc_data(\n\n 3,\n\n 4,\n\n vec![0, 1, 3, 4, 6],\n\n vec![1, 0, 2, 0, 0, 2],\n\n vec![2, 5, 1, 3, 2, 4],\n\n )\n\n .unwrap();\n\n\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(3, 4, &[\n\n 0, 5, 3, 2,\n\n 2, 0, 0, 0,\n\n 0, 1, 0, 4\n\n ]);\n\n\n\n assert_eq!(convert_csc_dense(&csc), dense);\n\n assert_eq!(convert_dense_csc(&dense), csc);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 21, "score": 166898.969725746 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_complex_general() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix array complex general\n\n%\n\n2 2\n\n1 0\n\n1 0\n\n1 0\n\n1 0\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<Complex<f32>>(file_str).unwrap();\n\n let expected = dmatrix![\n\n Complex::<f32>{re:1.0,im:0.0},Complex::<f32>{re:1.0,im:0.0};\n\n Complex::<f32>{re:1.0,im:0.0},Complex::<f32>{re:1.0,im:0.0};\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 22, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_complex_hermitian() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix coordinate complex hermitian\n\n%\n\n 5 5 7\n\n 1 1 1.0 0.0\n\n 2 2 10.5 0.0\n\n 4 2 250.5 22.22\n\n 3 3 0.015 0.0\n\n 4 4 -2.8e2 0.0\n\n 5 5 12.0 0.0\n\n 5 4 0.0 33.32\n\n\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<Complex<f64>>(file_str).unwrap();\n\n let expected = dmatrix![\n\n Complex::<f64>{re:1.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0},Complex::<f64>{re:0.0,im:0.0};\n\n Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:10.5,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:250.5,im:-22.22},Complex::<f64>{re:0.0,im:0.0};\n\n Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.015,im:0.0}, Complex::<f64>{re:0.0,im:0.0},Complex::<f64>{re:0.0,im:0.0};\n\n Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:250.5,im:22.22}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:-280.0,im:0.0},Complex::<f64>{re:0.0,im:-33.32};\n\n Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:0.0}, Complex::<f64>{re:0.0,im:33.32},Complex::<f64>{re:12.0,im:0.0};\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 23, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_int_symmetric() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix coordinate integer symmetric\n\n%\n\n 5 5 9\n\n 1 1 11\n\n 2 2 22\n\n 3 2 23\n\n 3 3 33\n\n 4 2 24\n\n 4 4 44\n\n 5 1 -15\n\n 5 3 35\n\n 5 5 55\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<i128>(file_str).unwrap();\n\n let expected = dmatrix![\n\n 11, 0, 0, 0, -15;\n\n 0, 22, 23, 24, 0;\n\n 0, 23, 33, 0, 35;\n\n 0, 24, 0, 44, 0;\n\n -15, 0, 35, 0, 55;\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 24, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_pattern_general() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix coordinate pattern general\n\n%\n\n 5 5 10\n\n 1 1\n\n 1 5\n\n 2 3\n\n 2 4\n\n 3 2\n\n 3 5\n\n 4 1\n\n 5 2\n\n 5 4\n\n 5 5\n\n\"#;\n\n let pattern_matrix = load_coo_from_matrix_market_str::<()>(file_str).unwrap();\n\n let nrows = pattern_matrix.nrows();\n\n let ncols = pattern_matrix.ncols();\n\n let (row_idx, col_idx, val) = pattern_matrix.disassemble();\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 25, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_real_skew() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix coordinate real skew-symmetric\n\n%\n\n 5 5 4\n\n 3 2 -23.0\n\n 4 2 -24.0\n\n 5 1 -15.0\n\n 5 3 -35.0\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<f64>(file_str).unwrap();\n\n let expected = dmatrix![\n\n 0.0, 0.0, 0.0, 0.0, 15.0;\n\n 0.0, 0.0, 23.0, 24.0, 0.0;\n\n 0.0, -23.0, 0.0, 0.0, 35.0;\n\n 0.0, -24.0, 0.0, 0.0, 0.0;\n\n -15.0, 0.0, -35.0, 0.0, 0.0;\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 26, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_real_general() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix CoOrdinate real general\n\n% This is also an example of free-format features.\n\n%=================================================================================\n\n%\n\n% This ASCII file represents a sparse MxN matrix with L\n\n% nonzeros in the following Matrix Market format:\n\n%\n\n% +----------------------------------------------+\n\n% |%%MatrixMarket matrix coordinate real general | <--- header line\n\n% |% | <--+\n\n% |% comments | |-- 0 or more comment lines\n\n% |% | <--+\n\n% | M T L | <--- rows, columns, entries\n\n% | I1 J1 A(I1, J1) | <--+\n\n% | I2 J2 A(I2, J2) | |\n\n% | I3 J3 A(I3, J3) | |-- L lines\n\n% | . . . | |\n\n% | IL JL A(IL, JL) | <--+\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 27, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_real_symmetric() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix array real symmetric\n\n%\n\n4 4\n\n1.0\n\n2.0\n\n3.0\n\n4.0\n\n5.0\n\n6.0\n\n7.0\n\n8.0\n\n9.0\n\n10.0\n\n\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<f32>(file_str).unwrap();\n\n let expected = dmatrix![\n\n 1.0, 2.0, 3.0, 4.0;\n\n 2.0, 5.0, 6.0, 7.0;\n\n 3.0, 6.0, 8.0, 9.0;\n\n 4.0, 7.0, 9.0, 10.0;\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 28, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_complex_hermitian() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix array complex hermitian\n\n%\n\n4 4\n\n1.0 0.0\n\n2.0 2.0\n\n3.0 3.0\n\n4.0 4.0\n\n5.0 0.0\n\n6.0 6.0\n\n7.0 7.0\n\n8.0 0.0\n\n9.0 9.0\n\n10.0 0.0\n\n\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<Complex<f64>>(file_str).unwrap();\n\n let expected = dmatrix![\n\n Complex::<f64>{re:1.0,im:0.0}, Complex::<f64>{re:2.0,im:-2.0} ,Complex::<f64>{re:3.0,im:-3.0} ,Complex::<f64>{re:4.0,im:-4.0};\n\n Complex::<f64>{re:2.0,im:2.0}, Complex::<f64>{re:5.0,im:0.0} ,Complex::<f64>{re:6.0,im:-6.0} ,Complex::<f64>{re:7.0,im:-7.0};\n\n Complex::<f64>{re:3.0,im:3.0}, Complex::<f64>{re:6.0,im:6.0} ,Complex::<f64>{re:8.0,im:0.0} ,Complex::<f64>{re:9.0,im:-9.0};\n\n Complex::<f64>{re:4.0,im:4.0}, Complex::<f64>{re:7.0,im:7.0} ,Complex::<f64>{re:9.0,im:9.0} ,Complex::<f64>{re:10.0,im:0.0};\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 29, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_int_skew() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix array integer skew-symmetric\n\n%\n\n4 4\n\n1\n\n2\n\n3\n\n4\n\n5\n\n6\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<i32>(file_str).unwrap();\n\n let expected = dmatrix![\n\n 0,-1,-2,-3;\n\n 1, 0,-4,-5;\n\n 2, 4, 0,-6;\n\n 3, 5, 6, 0;\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 30, "score": 166898.82544166487 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_real_general() {\n\n let file_str = r#\"\n\n%%MatrixMarket matrix array real general\n\n%\n\n4 3\n\n1.0\n\n2.0\n\n3.0\n\n4.0\n\n5.0\n\n6.0\n\n7.0\n\n8.0\n\n9.0\n\n10.0\n\n11.0\n\n12.0\n\n\n\n\"#;\n\n let sparse_mat = load_coo_from_matrix_market_str::<f32>(file_str).unwrap();\n\n let expected = dmatrix![\n\n 1.0, 5.0, 9.0;\n\n 2.0, 6.0, 10.0;\n\n 3.0, 7.0, 11.0;\n\n 4.0, 8.0, 12.0;\n\n ];\n\n assert_matrix_eq!(sparse_mat, expected);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 31, "score": 166898.82544166487 }, { "content": "#[test]\n\nfn csr_matrix_valid_data() {\n\n // Construct matrix from valid data and check that selected methods return results\n\n // that agree with expectations.\n\n\n\n {\n\n // A CSR matrix with zero explicitly stored entries\n\n let offsets = vec![0, 0, 0, 0];\n\n let indices = vec![];\n\n let values = Vec::<i32>::new();\n\n let mut matrix = CsrMatrix::try_from_csr_data(3, 2, offsets, indices, values).unwrap();\n\n\n\n assert_eq!(matrix, CsrMatrix::zeros(3, 2));\n\n\n\n assert_eq!(matrix.nrows(), 3);\n\n assert_eq!(matrix.ncols(), 2);\n\n assert_eq!(matrix.nnz(), 0);\n\n assert_eq!(matrix.row_offsets(), &[0, 0, 0, 0]);\n\n assert_eq!(matrix.col_indices(), &[]);\n\n assert_eq!(matrix.values(), &[]);\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 32, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn csc_matrix_col_iter() {\n\n // Note: this is the transpose of the matrix used for the similar csr_matrix_row_iter test\n\n // (this way the actual tests are almost identical, due to the transposed relationship\n\n // between CSR and CSC)\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(4, 3, &[\n\n 0, 3, 0,\n\n 1, 0, 4,\n\n 2, 0, 0,\n\n 0, 0, 5,\n\n ]);\n\n let csc = CscMatrix::from(&dense);\n\n\n\n // Immutable iterator\n\n {\n\n let mut col_iter = csc.col_iter();\n\n\n\n {\n\n let col = col_iter.next().unwrap();\n\n assert_eq!(col.nrows(), 4);\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 33, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn csc_matrix_valid_data() {\n\n // Construct matrix from valid data and check that selected methods return results\n\n // that agree with expectations.\n\n\n\n {\n\n // A CSC matrix with zero explicitly stored entries\n\n let offsets = vec![0, 0, 0, 0];\n\n let indices = vec![];\n\n let values = Vec::<i32>::new();\n\n let mut matrix = CscMatrix::try_from_csc_data(2, 3, offsets, indices, values).unwrap();\n\n\n\n assert_eq!(matrix, CscMatrix::zeros(2, 3));\n\n\n\n assert_eq!(matrix.nrows(), 2);\n\n assert_eq!(matrix.ncols(), 3);\n\n assert_eq!(matrix.nnz(), 0);\n\n assert_eq!(matrix.col_offsets(), &[0, 0, 0, 0]);\n\n assert_eq!(matrix.row_indices(), &[]);\n\n assert_eq!(matrix.values(), &[]);\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 34, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn coo_push_out_of_bounds_entries() {\n\n {\n\n // 0x0 matrix\n\n let coo = CooMatrix::new(0, 0);\n\n assert_panics!(coo.clone().push(0, 0, 1));\n\n }\n\n\n\n {\n\n // 0x1 matrix\n\n assert_panics!(CooMatrix::new(0, 1).push(0, 0, 1));\n\n }\n\n\n\n {\n\n // 1x0 matrix\n\n assert_panics!(CooMatrix::new(1, 0).push(0, 0, 1));\n\n }\n\n\n\n {\n\n // Arbitrary matrix dimensions\n\n let coo = CooMatrix::new(3, 2);\n\n assert_panics!(coo.clone().push(3, 0, 1));\n\n assert_panics!(coo.clone().push(2, 2, 1));\n\n assert_panics!(coo.clone().push(3, 2, 1));\n\n }\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 35, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn csr_matrix_row_iter() {\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(3, 4, &[\n\n 0, 1, 2, 0,\n\n 3, 0, 0, 0,\n\n 0, 4, 0, 5\n\n ]);\n\n let csr = CsrMatrix::from(&dense);\n\n\n\n // Immutable iterator\n\n {\n\n let mut row_iter = csr.row_iter();\n\n\n\n {\n\n let row = row_iter.next().unwrap();\n\n assert_eq!(row.ncols(), 4);\n\n assert_eq!(row.nnz(), 2);\n\n assert_eq!(row.col_indices(), &[1, 2]);\n\n assert_eq!(row.values(), &[1, 2]);\n\n assert_eq!(row.get_entry(0), Some(SparseEntry::Zero));\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 36, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn coo_push_valid_entries() {\n\n let mut coo = CooMatrix::new(3, 3);\n\n\n\n coo.push(0, 0, 1);\n\n assert_eq!(coo.triplet_iter().collect::<Vec<_>>(), vec![(0, 0, &1)]);\n\n\n\n coo.push(0, 0, 2);\n\n assert_eq!(\n\n coo.triplet_iter().collect::<Vec<_>>(),\n\n vec![(0, 0, &1), (0, 0, &2)]\n\n );\n\n\n\n coo.push(2, 2, 3);\n\n assert_eq!(\n\n coo.triplet_iter().collect::<Vec<_>>(),\n\n vec![(0, 0, &1), (0, 0, &2), (2, 2, &3)]\n\n );\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 37, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn coo_construction_for_valid_data() {\n\n // Test that construction with try_from_triplets succeeds, that the state of the\n\n // matrix afterwards is as expected, and that the dense representation matches expectations.\n\n\n\n {\n\n // Zero matrix\n\n let coo =\n\n CooMatrix::<i32>::try_from_triplets(3, 2, Vec::new(), Vec::new(), Vec::new()).unwrap();\n\n assert_eq!(coo.nrows(), 3);\n\n assert_eq!(coo.ncols(), 2);\n\n assert!(coo.triplet_iter().next().is_none());\n\n assert!(coo.row_indices().is_empty());\n\n assert!(coo.col_indices().is_empty());\n\n assert!(coo.values().is_empty());\n\n\n\n assert_eq!(DMatrix::from(&coo), DMatrix::repeat(3, 2, 0));\n\n }\n\n\n\n {\n\n // Arbitrary matrix, no duplicates\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 38, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn sparsity_pattern_valid_data() {\n\n // Construct pattern from valid data and check that selected methods return results\n\n // that agree with expectations.\n\n\n\n {\n\n // A pattern with zero explicitly stored entries\n\n let pattern =\n\n SparsityPattern::try_from_offsets_and_indices(3, 2, vec![0, 0, 0, 0], Vec::new())\n\n .unwrap();\n\n\n\n assert_eq!(pattern.major_dim(), 3);\n\n assert_eq!(pattern.minor_dim(), 2);\n\n assert_eq!(pattern.nnz(), 0);\n\n assert_eq!(pattern.major_offsets(), &[0, 0, 0, 0]);\n\n assert_eq!(pattern.minor_indices(), &[]);\n\n assert_eq!(pattern.lane(0), &[]);\n\n assert_eq!(pattern.lane(1), &[]);\n\n assert_eq!(pattern.lane(2), &[]);\n\n assert!(pattern.entries().next().is_none());\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/pattern.rs", "rank": 39, "score": 166321.9846058827 }, { "content": "#[test]\n\nfn matrix_shrinking_satisfies_constraints() {\n\n // We use a deterministic test runner to make the test \"stable\".\n\n let mut runner = TestRunner::deterministic();\n\n\n\n let strategy = matrix(-1..=2, 1..=3, 2..=4);\n\n\n\n let num_matrices = 25;\n\n\n\n macro_rules! maybeprintln {\n\n ($($arg:tt)*) => {\n\n // Uncomment the below line to enable printing of matrix sequences. This is handy\n\n // for manually inspecting the sequences of simplified matrices.\n\n // println!($($arg)*)\n\n };\n\n }\n\n\n\n maybeprintln!(\"========================== (begin generation process)\");\n\n\n\n for _ in 0..num_matrices {\n\n let mut tree = strategy\n", "file_path": "tests/proptest/mod.rs", "rank": 40, "score": 164767.49948080292 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_dense_real_general_empty() {\n\n // Test several valid zero-shapes of a dense matrix\n\n let shapes = vec![ (0, 0), (1, 0), (0, 1) ];\n\n let strings: Vec<String> = shapes\n\n .iter()\n\n .map(|(m, n)| format!(\"%%MatrixMarket matrix array real general\\n {} {}\", m, n))\n\n .collect();\n\n\n\n for (shape,string) in shapes.iter().zip(strings.iter()) {\n\n let sparse_mat = load_coo_from_matrix_market_str::<f32>(string).unwrap();\n\n assert_eq!(sparse_mat.nrows(), shape.0);\n\n assert_eq!(sparse_mat.ncols(), shape.1);\n\n assert_eq!(sparse_mat.nnz(), 0);\n\n }\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 41, "score": 163941.80055630786 }, { "content": "#[test]\n\n#[rustfmt::skip]\n\nfn test_matrixmarket_sparse_real_general_empty() {\n\n // Test several valid zero-shapes of a sparse matrix\n\n let shapes = vec![ (0, 0), (1, 0), (0, 1) ];\n\n let strings: Vec<String> = shapes\n\n .iter()\n\n .map(|(m, n)| format!(\"%%MatrixMarket matrix coordinate real general\\n {} {} 0\", m, n))\n\n .collect();\n\n\n\n for (shape,string) in shapes.iter().zip(strings.iter()) {\n\n let sparse_mat = load_coo_from_matrix_market_str::<f32>(string).unwrap();\n\n assert_eq!(sparse_mat.nrows(), shape.0);\n\n assert_eq!(sparse_mat.ncols(), shape.1);\n\n assert_eq!(sparse_mat.nnz(), 0);\n\n }\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/matrix_market.rs", "rank": 42, "score": 163941.80055630786 }, { "content": "fn print_norm<T: RealField>(v: &Vector3<T>) {\n\n // NOTE: alternatively, nalgebra already defines `v.norm()`.\n\n let norm = v.dot(v).sqrt();\n\n\n\n // The RealField bound implies that T is Display so we can\n\n // use \"{}\" instead of \"{:?}\" for the format string.\n\n println!(\"{}\", norm)\n\n}\n\n\n", "file_path": "examples/scalar_genericity.rs", "rank": 43, "score": 163031.98141915307 }, { "content": "#[test]\n\nfn coo_push_matrix_valid_entries() {\n\n let mut coo = CooMatrix::new(3, 3);\n\n\n\n // Works with static\n\n {\n\n // new is row-major...\n\n let inserted = nalgebra::SMatrix::<i32, 2, 2>::new(1, 2, 3, 4);\n\n coo.push_matrix(1, 1, &inserted);\n\n\n\n // insert happens column-major, so expect transposition when read this way\n\n assert_eq!(\n\n coo.triplet_iter().collect::<Vec<_>>(),\n\n vec![(1, 1, &1), (2, 1, &3), (1, 2, &2), (2, 2, &4)]\n\n );\n\n }\n\n\n\n // Works with owned dynamic\n\n {\n\n let inserted = nalgebra::DMatrix::<i32>::repeat(1, 2, 5);\n\n coo.push_matrix(0, 0, &inserted);\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 44, "score": 162904.3830814604 }, { "content": "#[test]\n\nfn csr_disassemble_avoids_clone_when_owned() {\n\n // Test that disassemble avoids cloning the sparsity pattern when it holds the sole reference\n\n // to the pattern. We do so by checking that the pointer to the data is unchanged.\n\n\n\n let offsets = vec![0, 2, 2, 5];\n\n let indices = vec![0, 5, 1, 2, 3];\n\n let values = vec![0, 1, 2, 3, 4];\n\n let offsets_ptr = offsets.as_ptr();\n\n let indices_ptr = indices.as_ptr();\n\n let values_ptr = values.as_ptr();\n\n let matrix = CsrMatrix::try_from_csr_data(3, 6, offsets, indices, values).unwrap();\n\n\n\n let (offsets, indices, values) = matrix.disassemble();\n\n assert_eq!(offsets.as_ptr(), offsets_ptr);\n\n assert_eq!(indices.as_ptr(), indices_ptr);\n\n assert_eq!(values.as_ptr(), values_ptr);\n\n}\n\n\n\n// Rustfmt makes this test much harder to read by expanding some of the one-liners to 4-liners,\n\n// so for now we skip rustfmt...\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 45, "score": 162904.3830814604 }, { "content": "#[test]\n\nfn sparsity_pattern_try_from_invalid_data() {\n\n {\n\n // Empty offset array (invalid length)\n\n let pattern = SparsityPattern::try_from_offsets_and_indices(0, 0, Vec::new(), Vec::new());\n\n assert_eq!(\n\n pattern,\n\n Err(SparsityPatternFormatError::InvalidOffsetArrayLength)\n\n );\n\n }\n\n\n\n {\n\n // Offset array invalid length for arbitrary data\n\n let offsets = vec![0, 3, 5];\n\n let indices = vec![0, 1, 2, 3, 5];\n\n\n\n let pattern = SparsityPattern::try_from_offsets_and_indices(3, 6, offsets, indices);\n\n assert!(matches!(\n\n pattern,\n\n Err(SparsityPatternFormatError::InvalidOffsetArrayLength)\n\n ));\n", "file_path": "nalgebra-sparse/tests/unit_tests/pattern.rs", "rank": 46, "score": 162904.3830814604 }, { "content": "#[test]\n\nfn csc_disassemble_avoids_clone_when_owned() {\n\n // Test that disassemble avoids cloning the sparsity pattern when it holds the sole reference\n\n // to the pattern. We do so by checking that the pointer to the data is unchanged.\n\n\n\n let offsets = vec![0, 2, 2, 5];\n\n let indices = vec![0, 5, 1, 2, 3];\n\n let values = vec![0, 1, 2, 3, 4];\n\n let offsets_ptr = offsets.as_ptr();\n\n let indices_ptr = indices.as_ptr();\n\n let values_ptr = values.as_ptr();\n\n let matrix = CscMatrix::try_from_csc_data(6, 3, offsets, indices, values).unwrap();\n\n\n\n let (offsets, indices, values) = matrix.disassemble();\n\n assert_eq!(offsets.as_ptr(), offsets_ptr);\n\n assert_eq!(indices.as_ptr(), indices_ptr);\n\n assert_eq!(values.as_ptr(), values_ptr);\n\n}\n\n\n\n// Rustfmt makes this test much harder to read by expanding some of the one-liners to 4-liners,\n\n// so for now we skip rustfmt...\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 47, "score": 162904.3830814604 }, { "content": "#[test]\n\nfn coo_push_matrix_out_of_bounds_entries() {\n\n // 0x0\n\n {\n\n let inserted = nalgebra::SMatrix::<i32, 1, 1>::new(1);\n\n assert_panics!(CooMatrix::new(0, 0).push_matrix(0, 0, &inserted));\n\n }\n\n // 0x1\n\n {\n\n let inserted = nalgebra::SMatrix::<i32, 1, 1>::new(1);\n\n assert_panics!(CooMatrix::new(1, 0).push_matrix(0, 0, &inserted));\n\n }\n\n // 1x0\n\n {\n\n let inserted = nalgebra::SMatrix::<i32, 1, 1>::new(1);\n\n assert_panics!(CooMatrix::new(0, 1).push_matrix(0, 0, &inserted));\n\n }\n\n\n\n // 3x3 exceeds col-dim\n\n {\n\n let inserted = nalgebra::SMatrix::<i32, 1, 2>::repeat(1);\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 48, "score": 162904.3830814604 }, { "content": "#[rustfmt::skip]\n\n#[test]\n\nfn csr_matrix_get_index_entry() {\n\n // Test .get_entry(_mut) and .index_entry(_mut) methods\n\n\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(2, 3, &[\n\n 1, 0, 3,\n\n 0, 5, 6\n\n ]);\n\n let csr = CsrMatrix::from(&dense);\n\n\n\n assert_eq!(csr.get_entry(0, 0), Some(SparseEntry::NonZero(&1)));\n\n assert_eq!(csr.index_entry(0, 0), SparseEntry::NonZero(&1));\n\n assert_eq!(csr.get_entry(0, 1), Some(SparseEntry::Zero));\n\n assert_eq!(csr.index_entry(0, 1), SparseEntry::Zero);\n\n assert_eq!(csr.get_entry(0, 2), Some(SparseEntry::NonZero(&3)));\n\n assert_eq!(csr.index_entry(0, 2), SparseEntry::NonZero(&3));\n\n assert_eq!(csr.get_entry(1, 0), Some(SparseEntry::Zero));\n\n assert_eq!(csr.index_entry(1, 0), SparseEntry::Zero);\n\n assert_eq!(csr.get_entry(1, 1), Some(SparseEntry::NonZero(&5)));\n\n assert_eq!(csr.index_entry(1, 1), SparseEntry::NonZero(&5));\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 49, "score": 162904.23879737928 }, { "content": "#[rustfmt::skip]\n\n#[test]\n\nfn csc_matrix_get_index_entry() {\n\n // Test .get_entry(_mut) and .index_entry(_mut) methods\n\n\n\n #[rustfmt::skip]\n\n let dense = DMatrix::from_row_slice(2, 3, &[\n\n 1, 0, 3,\n\n 0, 5, 6\n\n ]);\n\n let csc = CscMatrix::from(&dense);\n\n\n\n assert_eq!(csc.get_entry(0, 0), Some(SparseEntry::NonZero(&1)));\n\n assert_eq!(csc.index_entry(0, 0), SparseEntry::NonZero(&1));\n\n assert_eq!(csc.get_entry(0, 1), Some(SparseEntry::Zero));\n\n assert_eq!(csc.index_entry(0, 1), SparseEntry::Zero);\n\n assert_eq!(csc.get_entry(0, 2), Some(SparseEntry::NonZero(&3)));\n\n assert_eq!(csc.index_entry(0, 2), SparseEntry::NonZero(&3));\n\n assert_eq!(csc.get_entry(1, 0), Some(SparseEntry::Zero));\n\n assert_eq!(csc.index_entry(1, 0), SparseEntry::Zero);\n\n assert_eq!(csc.get_entry(1, 1), Some(SparseEntry::NonZero(&5)));\n\n assert_eq!(csc.index_entry(1, 1), SparseEntry::NonZero(&5));\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 50, "score": 162904.23879737928 }, { "content": "pub fn dmatrix_<ScalarStrategy>(\n\n scalar_strategy: ScalarStrategy,\n\n) -> impl Strategy<Value = OMatrix<ScalarStrategy::Value, Dynamic, Dynamic>>\n\nwhere\n\n ScalarStrategy: Strategy + Clone + 'static,\n\n ScalarStrategy::Value: Scalar,\n\n DefaultAllocator: Allocator<ScalarStrategy::Value, Dynamic, Dynamic>,\n\n{\n\n matrix(scalar_strategy, PROPTEST_MATRIX_DIM, PROPTEST_MATRIX_DIM)\n\n}\n\n\n\n// pub fn dvector_<T>(range: RangeInclusive<T>) -> impl Strategy<Value = DVector<T>>\n\n// where\n\n// RangeInclusive<T>: Strategy<Value = T>,\n\n// T: Scalar + PartialEq + Copy,\n\n// DefaultAllocator: Allocator<T, Dynamic>,\n\n// {\n\n// vector(range, PROPTEST_MATRIX_DIM)\n\n// }\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 51, "score": 160422.68130879084 }, { "content": "#[test]\n\nfn coo_try_from_triplets_panics_on_mismatched_vectors() {\n\n // Check that try_from_triplets panics when the triplet vectors have different lengths\n\n macro_rules! assert_errs {\n\n ($result:expr) => {\n\n assert!(matches!(\n\n $result.unwrap_err().kind(),\n\n SparseFormatErrorKind::InvalidStructure\n\n ))\n\n };\n\n }\n\n\n\n assert_errs!(CooMatrix::<i32>::try_from_triplets(\n\n 3,\n\n 5,\n\n vec![1, 2],\n\n vec![0],\n\n vec![0]\n\n ));\n\n assert_errs!(CooMatrix::<i32>::try_from_triplets(\n\n 3,\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 52, "score": 159656.54126930784 }, { "content": "#[test]\n\nfn coo_try_from_triplets_reports_out_of_bounds_indices() {\n\n {\n\n // 0x0 matrix\n\n let result = CooMatrix::<i32>::try_from_triplets(0, 0, vec![0], vec![0], vec![2]);\n\n assert!(matches!(\n\n result.unwrap_err().kind(),\n\n SparseFormatErrorKind::IndexOutOfBounds\n\n ));\n\n }\n\n\n\n {\n\n // 1x1 matrix, row out of bounds\n\n let result = CooMatrix::<i32>::try_from_triplets(1, 1, vec![1], vec![0], vec![2]);\n\n assert!(matches!(\n\n result.unwrap_err().kind(),\n\n SparseFormatErrorKind::IndexOutOfBounds\n\n ));\n\n }\n\n\n\n {\n", "file_path": "nalgebra-sparse/tests/unit_tests/coo.rs", "rank": 53, "score": 159656.54126930784 }, { "content": "#[test]\n\nfn csr_matrix_try_from_invalid_csr_data() {\n\n let invalid_data: InvalidCsDataExamples = InvalidCsDataExamples::new();\n\n {\n\n // Empty offset array (invalid length)\n\n let (offsets, indices, values) = invalid_data.empty_offset_array;\n\n let matrix = CsrMatrix::try_from_csr_data(0, 0, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n\n );\n\n }\n\n\n\n {\n\n // Offset array invalid length for arbitrary data\n\n let (offsets, indices, values) =\n\n invalid_data.offset_array_invalid_length_for_arbitrary_data;\n\n let matrix = CsrMatrix::try_from_csr_data(3, 6, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 54, "score": 159656.54126930784 }, { "content": "#[test]\n\nfn csc_matrix_try_from_invalid_csc_data() {\n\n let invalid_data: InvalidCsDataExamples = InvalidCsDataExamples::new();\n\n {\n\n // Empty offset array (invalid length)\n\n let (offsets, indices, values) = invalid_data.empty_offset_array;\n\n let matrix = CscMatrix::try_from_csc_data(0, 0, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n\n );\n\n }\n\n\n\n {\n\n // Offset array invalid length for arbitrary data\n\n let (offsets, indices, values) =\n\n invalid_data.offset_array_invalid_length_for_arbitrary_data;\n\n let matrix = CscMatrix::try_from_csc_data(6, 3, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 55, "score": 159656.54126930784 }, { "content": "#[test]\n\nfn csc_matrix_valid_data_unsorted_column_indices() {\n\n let valid_data: ValidCsDataExamples = ValidCsDataExamples::new();\n\n\n\n let (offsets, indices, values) = valid_data.valid_unsorted_cs_data;\n\n let csc = CscMatrix::try_from_unsorted_csc_data(5, 4, offsets, indices, values).unwrap();\n\n\n\n let (offsets2, indices2, values2) = valid_data.valid_cs_data;\n\n let expected_csc = CscMatrix::try_from_csc_data(5, 4, offsets2, indices2, values2).unwrap();\n\n\n\n assert_eq!(csc, expected_csc);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 56, "score": 156565.7974840036 }, { "content": "#[test]\n\nfn csr_matrix_try_from_unsorted_invalid_csr_data() {\n\n let invalid_data: InvalidCsDataExamples = InvalidCsDataExamples::new();\n\n {\n\n // Empty offset array (invalid length)\n\n let (offsets, indices, values) = invalid_data.empty_offset_array;\n\n let matrix = CsrMatrix::try_from_unsorted_csr_data(0, 0, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n\n );\n\n }\n\n\n\n {\n\n // Offset array invalid length for arbitrary data\n\n let (offsets, indices, values) =\n\n invalid_data.offset_array_invalid_length_for_arbitrary_data;\n\n let matrix = CsrMatrix::try_from_unsorted_csr_data(3, 6, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 57, "score": 156565.7974840036 }, { "content": "#[test]\n\nfn csr_matrix_valid_data_unsorted_column_indices() {\n\n let valid_data: ValidCsDataExamples = ValidCsDataExamples::new();\n\n\n\n let (offsets, indices, values) = valid_data.valid_unsorted_cs_data;\n\n let csr = CsrMatrix::try_from_unsorted_csr_data(4, 5, offsets, indices, values).unwrap();\n\n\n\n let (offsets2, indices2, values2) = valid_data.valid_cs_data;\n\n let expected_csr = CsrMatrix::try_from_csr_data(4, 5, offsets2, indices2, values2).unwrap();\n\n\n\n assert_eq!(csr, expected_csr);\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/csr.rs", "rank": 58, "score": 156565.7974840036 }, { "content": "#[test]\n\nfn csc_matrix_try_from_unsorted_invalid_csc_data() {\n\n let invalid_data: InvalidCsDataExamples = InvalidCsDataExamples::new();\n\n {\n\n // Empty offset array (invalid length)\n\n let (offsets, indices, values) = invalid_data.empty_offset_array;\n\n let matrix = CscMatrix::try_from_unsorted_csc_data(0, 0, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n\n );\n\n }\n\n\n\n {\n\n // Offset array invalid length for arbitrary data\n\n let (offsets, indices, values) =\n\n invalid_data.offset_array_invalid_length_for_arbitrary_data;\n\n let matrix = CscMatrix::try_from_unsorted_csc_data(6, 3, offsets, indices, values);\n\n assert_eq!(\n\n matrix.unwrap_err().kind(),\n\n &SparseFormatErrorKind::InvalidStructure\n", "file_path": "nalgebra-sparse/tests/unit_tests/csc.rs", "rank": 59, "score": 156565.7974840036 }, { "content": " }\n\n\n\n #[cfg(feature = \"slow-tests\")]\n\n #[test]\n\n fn coo_no_duplicates_samples_all_admissible_outputs() {\n\n // Note: This test basically mirrors a similar test for `matrix` in the `nalgebra` repo.\n\n\n\n // Test that the proptest generation covers all possible outputs for a small space of inputs\n\n // given enough samples.\n\n\n\n // We use a deterministic test runner to make the test \"stable\".\n\n let mut runner = TestRunner::deterministic();\n\n\n\n // This number needs to be high enough so that we with high probability sample\n\n // all possible cases\n\n let num_generated_matrices = 500000;\n\n\n\n let values = -1..=1;\n\n let rows = 0..=2;\n\n let cols = 0..=3;\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 60, "score": 155798.51046330977 }, { "content": " #[cfg(feature = \"slow-tests\")]\n\n #[test]\n\n fn csc_samples_all_admissible_outputs() {\n\n // We use a deterministic test runner to make the test \"stable\".\n\n let mut runner = TestRunner::deterministic();\n\n\n\n // This number needs to be high enough so that we with high probability sample\n\n // all possible cases\n\n let num_generated_matrices = 500000;\n\n\n\n let values = -1..=1;\n\n let rows = 0..=2;\n\n let cols = 0..=3;\n\n let max_nnz = rows.end() * cols.end();\n\n let strategy = csc(values.clone(), rows.clone(), cols.clone(), max_nnz);\n\n\n\n let all_combinations = generate_all_possible_matrices(values, rows, cols);\n\n\n\n let visited_combinations =\n\n sample_matrix_output_space(strategy, &mut runner, num_generated_matrices);\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 61, "score": 155793.70636303068 }, { "content": "\n\n let visited_combinations =\n\n sample_matrix_output_space(strategy, &mut runner, num_generated_matrices);\n\n\n\n // Here we cannot verify that the set of visited combinations is *equal* to\n\n // all possible outcomes with the given constraints, however the\n\n // strategy should be able to generate all matrices that fit the constraints.\n\n // In other words, we need to determine that set of all admissible matrices\n\n // is contained in the set of visited matrices\n\n assert!(all_combinations.is_subset(&visited_combinations));\n\n }\n\n\n\n #[cfg(feature = \"slow-tests\")]\n\n #[test]\n\n fn csr_samples_all_admissible_outputs() {\n\n // We use a deterministic test runner to make the test \"stable\".\n\n let mut runner = TestRunner::deterministic();\n\n\n\n // This number needs to be high enough so that we with high probability sample\n\n // all possible cases\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 62, "score": 155793.59317946545 }, { "content": " // a different \"success\" criterion, since coo_with_duplicates is able to generate\n\n // matrices with values outside of the value constraints. See below for details.\n\n\n\n // We use a deterministic test runner to make the test \"stable\".\n\n let mut runner = TestRunner::deterministic();\n\n\n\n // This number needs to be high enough so that we with high probability sample\n\n // all possible cases\n\n let num_generated_matrices = 500000;\n\n\n\n let values = -1..=1;\n\n let rows = 0..=2;\n\n let cols = 0..=3;\n\n let max_nnz = rows.end() * cols.end();\n\n let strategy = coo_with_duplicates(values.clone(), rows.clone(), cols.clone(), max_nnz, 2);\n\n\n\n // Enumerate all possible combinations that fit the constraints\n\n // (note: this is only a subset of the matrices that can be generated by\n\n // `coo_with_duplicates`)\n\n let all_combinations = generate_all_possible_matrices(values, rows, cols);\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 63, "score": 155792.64924301417 }, { "content": " // To do this, we generate the values as the (multi) Cartesian product\n\n // of the value sets. For example, for a 2x2 matrices, we consider\n\n // all possible 4-element arrays that the matrices can take by\n\n // considering all elements in the cartesian product\n\n // V x V x V x V\n\n // where V is the set of eligible values, e.g. V := -1 ..= 1\n\n let values_iter = repeat(value_range.clone())\n\n .take(n_values)\n\n .multi_cartesian_product();\n\n for matrix_values in values_iter {\n\n all_combinations.insert(DMatrix::from_row_slice(\n\n nrows,\n\n ncols,\n\n &matrix_values,\n\n ));\n\n }\n\n }\n\n }\n\n }\n\n all_combinations\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 64, "score": 155790.81931551034 }, { "content": "#[test]\n\n#[ignore]\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 65, "score": 155789.99489552848 }, { "content": "\n\n assert_eq!(visited_combinations.len(), all_combinations.len());\n\n assert_eq!(\n\n visited_combinations, all_combinations,\n\n \"Did not sample all possible values.\"\n\n );\n\n }\n\n\n\n #[cfg(feature = \"slow-tests\")]\n\n #[test]\n\n fn sparsity_pattern_samples_all_admissible_outputs() {\n\n let mut runner = TestRunner::deterministic();\n\n\n\n let num_generated_patterns = 50000;\n\n\n\n let major_dims = 0..=2;\n\n let minor_dims = 0..=3;\n\n let max_nnz = major_dims.end() * minor_dims.end();\n\n let strategy = sparsity_pattern(major_dims.clone(), minor_dims.clone(), max_nnz);\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 66, "score": 155789.78230285822 }, { "content": " let max_nnz = rows.end() * cols.end();\n\n let strategy = coo_no_duplicates(values.clone(), rows.clone(), cols.clone(), max_nnz);\n\n\n\n // Enumerate all possible combinations\n\n let all_combinations = generate_all_possible_matrices(values, rows, cols);\n\n\n\n let visited_combinations =\n\n sample_matrix_output_space(strategy, &mut runner, num_generated_matrices);\n\n\n\n assert_eq!(visited_combinations.len(), all_combinations.len());\n\n assert_eq!(\n\n visited_combinations, all_combinations,\n\n \"Did not sample all possible values.\"\n\n );\n\n }\n\n\n\n #[cfg(feature = \"slow-tests\")]\n\n #[test]\n\n fn coo_with_duplicates_samples_all_admissible_outputs() {\n\n // This is almost the same as the test for coo_no_duplicates, except that we need\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 67, "score": 155789.48392688748 }, { "content": " num_samples: usize,\n\n ) -> HashSet<DMatrix<i32>>\n\n where\n\n S: Strategy,\n\n DMatrix<i32>: for<'b> From<&'b S::Value>,\n\n {\n\n sample_strategy(strategy, runner)\n\n .take(num_samples)\n\n .map(|matrix| DMatrix::from(&matrix))\n\n .collect()\n\n }\n\n\n\n fn sample_strategy<'a, S: 'a + Strategy>(\n\n strategy: S,\n\n runner: &'a mut TestRunner,\n\n ) -> impl 'a + Iterator<Item = S::Value> {\n\n repeat(()).map(move |_| {\n\n let tree = strategy\n\n .new_tree(runner)\n\n .expect(\"Tree generation should not fail\");\n\n let value = tree.current();\n\n value\n\n })\n\n }\n\n}\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 68, "score": 155787.52033846278 }, { "content": " let visited_patterns: HashSet<_> = sample_strategy(strategy, &mut runner)\n\n .take(num_generated_patterns)\n\n .map(|pattern| {\n\n // We represent patterns as dense matrices with 1 if an entry is occupied,\n\n // 0 otherwise\n\n let values = vec![1; pattern.nnz()];\n\n CsrMatrix::try_from_pattern_and_values(pattern, values).unwrap()\n\n })\n\n .map(|csr| DMatrix::from(&csr))\n\n .collect();\n\n\n\n let all_possible_patterns = generate_all_possible_matrices(0..=1, major_dims, minor_dims);\n\n\n\n assert_eq!(visited_patterns.len(), all_possible_patterns.len());\n\n assert_eq!(visited_patterns, all_possible_patterns);\n\n }\n\n\n\n fn sample_matrix_output_space<S>(\n\n strategy: S,\n\n runner: &mut TestRunner,\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 69, "score": 155787.18712373404 }, { "content": " use std::ops::RangeInclusive;\n\n\n\n fn generate_all_possible_matrices(\n\n value_range: RangeInclusive<i32>,\n\n rows_range: RangeInclusive<usize>,\n\n cols_range: RangeInclusive<usize>,\n\n ) -> HashSet<DMatrix<i32>> {\n\n // Enumerate all possible combinations\n\n let mut all_combinations = HashSet::new();\n\n for nrows in rows_range {\n\n for ncols in cols_range.clone() {\n\n // For the given number of rows and columns\n\n let n_values = nrows * ncols;\n\n\n\n if n_values == 0 {\n\n // If we have zero rows or columns, the set of matrices with the given\n\n // rows and columns is a single element: an empty matrix\n\n all_combinations.insert(DMatrix::from_row_slice(nrows, ncols, &[]));\n\n } else {\n\n // Otherwise, we need to sample all possible matrices.\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 70, "score": 155787.02295079952 }, { "content": " let num_generated_matrices = 500000;\n\n\n\n let values = -1..=1;\n\n let rows = 0..=2;\n\n let cols = 0..=3;\n\n let max_nnz = rows.end() * cols.end();\n\n let strategy = csr(values.clone(), rows.clone(), cols.clone(), max_nnz);\n\n\n\n let all_combinations = generate_all_possible_matrices(values, rows, cols);\n\n\n\n let visited_combinations =\n\n sample_matrix_output_space(strategy, &mut runner, num_generated_matrices);\n\n\n\n assert_eq!(visited_combinations.len(), all_combinations.len());\n\n assert_eq!(\n\n visited_combinations, all_combinations,\n\n \"Did not sample all possible values.\"\n\n );\n\n }\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/proptest.rs", "rank": 71, "score": 155783.77966199655 }, { "content": "fn pattern_strategy() -> impl Strategy<Value = SparsityPattern> {\n\n sparsity_pattern(PROPTEST_MATRIX_DIM, PROPTEST_MATRIX_DIM, PROPTEST_MAX_NNZ)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 72, "score": 149058.54287008735 }, { "content": "fn trans_strategy() -> impl Strategy<Value = bool> + Clone {\n\n proptest::bool::ANY\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 73, "score": 147778.39951484764 }, { "content": "/// Default epsilon value used for approximate comparison.\n\npub fn epsilon<T: AbsDiffEq<Epsilon = T>>() -> T {\n\n T::default_epsilon()\n\n}\n\n\n", "file_path": "nalgebra-glm/src/ext/scalar_constants.rs", "rank": 74, "score": 146167.52189829637 }, { "content": "fn positive_definite() -> impl Strategy<Value=CscMatrix<f64>> {\n\n let csc_f64 = csc(value_strategy::<f64>(),\n\n PROPTEST_MATRIX_DIM,\n\n PROPTEST_MATRIX_DIM,\n\n PROPTEST_MAX_NNZ);\n\n csc_f64\n\n .prop_map(|x| {\n\n // Add a small multiple of the identity to ensure positive definiteness\n\n x.transpose() * &x + CscMatrix::identity(x.ncols())\n\n })\n\n}\n\n\n\nproptest! {\n\n #[test]\n\n fn cholesky_correct_for_positive_definite_matrices(\n\n matrix in positive_definite()\n\n ) {\n\n let cholesky = CscCholesky::factor(&matrix).unwrap();\n\n let l = cholesky.take_l();\n\n let matrix_reconstructed = &l * l.transpose();\n", "file_path": "nalgebra-sparse/tests/unit_tests/cholesky.rs", "rank": 75, "score": 144833.34499650385 }, { "content": "fn dense_strategy() -> impl Strategy<Value = DMatrix<i32>> {\n\n matrix(\n\n PROPTEST_I32_VALUE_STRATEGY,\n\n PROPTEST_MATRIX_DIM,\n\n PROPTEST_MATRIX_DIM,\n\n )\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 76, "score": 144833.34499650385 }, { "content": "#[test]\n\nfn point_const_fn() {\n\n // Ensure that vector! can be used in const contexts\n\n const _: Point<i32, 0> = point![];\n\n const _: Point1<i32> = point![1];\n\n const _: Point2<i32> = point![1, 2];\n\n const _: Point6<i32> = point![1, 2, 3, 4, 5, 6];\n\n}\n\n\n\n// Skip rustfmt because it just makes the test bloated without making it more readable\n", "file_path": "nalgebra-macros/tests/tests.rs", "rank": 77, "score": 144777.19712166928 }, { "content": "#[test]\n\nfn vector_const_fn() {\n\n // Ensure that vector! can be used in const contexts\n\n const _: SVector<i32, 0> = vector![];\n\n const _: Vector1<i32> = vector![1];\n\n const _: Vector2<i32> = vector![1, 2];\n\n const _: Vector6<i32> = vector![1, 2, 3, 4, 5, 6];\n\n}\n\n\n", "file_path": "nalgebra-macros/tests/tests.rs", "rank": 78, "score": 144777.19712166928 }, { "content": "#[test]\n\nfn matrix_const_fn() {\n\n // Ensure that matrix! can be used in const contexts\n\n const _: SMatrix<i32, 0, 0> = matrix![];\n\n const _: SMatrix<i32, 1, 2> = matrix![1, 2];\n\n const _: SMatrix<i32, 2, 3> = matrix![1, 2, 3; 4, 5, 6];\n\n}\n\n\n\n// Skip rustfmt because it just makes the test bloated without making it more readable\n", "file_path": "nalgebra-macros/tests/tests.rs", "rank": 79, "score": 144777.19712166928 }, { "content": "/// Represents the sparsity pattern of a CSR matrix as a dense matrix with 0/1\n\nfn dense_csr_pattern(pattern: &SparsityPattern) -> DMatrix<i32> {\n\n let boolean_csr =\n\n CsrMatrix::try_from_pattern_and_values(pattern.clone(), vec![1; pattern.nnz()]).unwrap();\n\n DMatrix::from(&boolean_csr)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 80, "score": 143303.8138228651 }, { "content": "/// Represents the sparsity pattern of a CSC matrix as a dense matrix with 0/1\n\nfn dense_csc_pattern(pattern: &SparsityPattern) -> DMatrix<i32> {\n\n let boolean_csc =\n\n CscMatrix::try_from_pattern_and_values(pattern.clone(), vec![1; pattern.nnz()]).unwrap();\n\n DMatrix::from(&boolean_csc)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 81, "score": 143303.8138228651 }, { "content": "pub fn isometry2() -> impl Strategy<Value = Isometry2<f64>> {\n\n vector3().prop_map(|v| Isometry2::new(v.xy(), v.z))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 82, "score": 142849.7970090999 }, { "content": "pub fn quaternion() -> impl Strategy<Value = Quaternion<f64>> {\n\n vector4().prop_map(|v| Quaternion::from(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 83, "score": 142849.7970090999 }, { "content": "pub fn rotation2() -> impl Strategy<Value = Rotation2<f64>> {\n\n PROPTEST_F64.prop_map(|v| Rotation2::new(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 84, "score": 142849.7970090999 }, { "content": "pub fn rotation3() -> impl Strategy<Value = Rotation3<f64>> {\n\n vector3().prop_map(|v| Rotation3::new(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 85, "score": 142849.7970090999 }, { "content": "pub fn similarity3() -> impl Strategy<Value = Similarity3<f64>> {\n\n vector(PROPTEST_F64, Const::<7>)\n\n .prop_map(|v| Similarity3::new(v.xyz(), Vector3::new(v[3], v[4], v[5]), v[6]))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 86, "score": 142849.7970090999 }, { "content": "pub fn point2() -> impl Strategy<Value = Point2<f64>> {\n\n vector2().prop_map(|v| Point2::from(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 87, "score": 142849.7970090999 }, { "content": "pub fn translation2() -> impl Strategy<Value = Translation2<f64>> {\n\n vector2().prop_map(|v| Translation2::from(v))\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 88, "score": 142849.7970090999 }, { "content": "fn dense_strategy() -> impl Strategy<Value = DMatrix<i32>> {\n\n matrix(-5..=5, 0..=6, 0..=6)\n\n}\n\n\n\nproptest! {\n\n\n\n #[test]\n\n fn convert_dense_coo_roundtrip(dense in matrix(-5 ..= 5, 0 ..=6, 0..=6)) {\n\n let coo = convert_dense_coo(&dense);\n\n let dense2 = convert_coo_dense(&coo);\n\n prop_assert_eq!(&dense, &dense2);\n\n }\n\n\n\n #[test]\n\n fn convert_coo_dense_coo_roundtrip(coo in coo_strategy()) {\n\n // We cannot compare the result of the roundtrip coo -> dense -> coo directly for\n\n // two reasons:\n\n // 1. the COO matrices will generally have different ordering of elements\n\n // 2. explicitly stored zero entries in the original matrix will be discarded\n\n // when converting back to COO\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 89, "score": 142023.6704676254 }, { "content": "fn coo_strategy() -> impl Strategy<Value = CooMatrix<i32>> {\n\n coo_with_duplicates(-5..=5, 0..=6usize, 0..=6usize, 40, 2)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 90, "score": 142023.6704676254 }, { "content": "fn csr_strategy() -> impl Strategy<Value = CsrMatrix<i32>> {\n\n csr(-5..=5, 0..=6usize, 0..=6usize, 40)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 91, "score": 142023.6704676254 }, { "content": "fn csc_invertible_diagonal() -> impl Strategy<Value = CscMatrix<f64>> {\n\n let non_zero_values =\n\n value_strategy::<f64>().prop_filter(\"Only non-zeros values accepted\", |x| x != &0.0);\n\n\n\n vector(non_zero_values, PROPTEST_MATRIX_DIM).prop_map(|d| {\n\n let mut matrix = CscMatrix::identity(d.len());\n\n matrix.values_mut().clone_from_slice(&d.as_slice());\n\n matrix\n\n })\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 92, "score": 142023.6704676254 }, { "content": "/// Component-wise approximate non-equality beween two scalars.\n\npub fn epsilon_not_equal2<T: AbsDiffEq<Epsilon = T>>(x: T, y: T, epsilon: T) -> bool {\n\n abs_diff_ne!(x, y, epsilon = epsilon)\n\n}\n\n*/\n", "file_path": "nalgebra-glm/src/gtc/epsilon.rs", "rank": 93, "score": 139724.0623134327 }, { "content": "/// Component-wise approximate equality beween two scalars.\n\npub fn epsilon_equal2<T: AbsDiffEq<Epsilon = T>>(x: T, y: T, epsilon: T) -> bool {\n\n abs_diff_eq!(x, y, epsilon = epsilon)\n\n}\n\n\n", "file_path": "nalgebra-glm/src/gtc/epsilon.rs", "rank": 94, "score": 139724.0623134327 }, { "content": "/// Constructs pairs (a, b) where a and b have the same dimensions\n\nfn spadd_pattern_strategy() -> impl Strategy<Value = (SparsityPattern, SparsityPattern)> {\n\n pattern_strategy().prop_flat_map(|a| {\n\n let b = sparsity_pattern(a.major_dim(), a.minor_dim(), PROPTEST_MAX_NNZ);\n\n (Just(a), b)\n\n })\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/ops.rs", "rank": 95, "score": 139340.0349327523 }, { "content": "fn coo_no_duplicates_strategy() -> impl Strategy<Value = CooMatrix<i32>> {\n\n coo_no_duplicates(-5..=5, 0..=6usize, 0..=6usize, 40)\n\n}\n\n\n", "file_path": "nalgebra-sparse/tests/unit_tests/convert_serial.rs", "rank": 96, "score": 139340.0349327523 }, { "content": "pub fn dmatrix() -> impl Strategy<Value = DMatrix<f64>> {\n\n matrix(PROPTEST_F64, PROPTEST_MATRIX_DIM, PROPTEST_MATRIX_DIM)\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 97, "score": 139302.63958999782 }, { "content": "pub fn dvector() -> impl Strategy<Value = DVector<f64>> {\n\n vector(PROPTEST_F64, PROPTEST_MATRIX_DIM)\n\n}\n\n\n", "file_path": "tests/proptest/mod.rs", "rank": 98, "score": 139302.63958999782 }, { "content": "#[test]\n\nfn matrix_trybuild_tests() {\n\n let t = trybuild::TestCases::new();\n\n\n\n // Verify error message when we give a matrix with mismatched dimensions\n\n t.compile_fail(\"tests/trybuild/matrix_mismatched_dimensions.rs\");\n\n}\n\n\n", "file_path": "nalgebra-macros/tests/tests.rs", "rank": 99, "score": 137968.45206963993 } ]
Rust
tiled/src/json_parser.rs
lenscas/hv-dev
7ae07cb889b20f382acd7293d80dfe3319a91123
use crate::*; use hv::prelude::*; impl Tileset { pub fn json_parse_tileset( v: &Value, first_gid: u32, path_prefix: Option<&str>, tileset_number: u8, slab: &mut slab::Slab<Object>, filename: String, ) -> Result<Self> { let json_obj = v .as_object() .ok_or(anyhow!("Tileset file did not contain a json dictionary"))?; let tile_array = json_obj .get("tiles") .map_or::<Result<&[Value]>, _>(Ok(&[][..]), |t_arr| { Ok(t_arr .as_array() .ok_or_else(|| anyhow!("Tiles are not an array"))? .as_slice()) })?; let mut tiles = HashMap::new(); for tile_obj in tile_array.iter() { let tile = Tile::json_parse_tile(tile_obj, tileset_number, slab)?; tiles.insert(tile.id, tile); } Ok(Tileset { columns: json_obj .get("columns") .ok_or_else(|| anyhow!("Should've gotten columns"))? .as_u64() .ok_or_else(|| anyhow!("Columns value wasn't a u64"))? .try_into() .expect("Bruh how many columns does your tileset have"), images: vec![Image::from_json(json_obj, path_prefix)?], tilecount: json_obj .get("tilecount") .ok_or_else(|| anyhow!("Should've gotten tilecount"))? .as_u64() .ok_or_else(|| anyhow!("Tilecount value wasn't a u64"))? .try_into() .expect("Bruh how many tiles does your tileset have"), tile_width: json_obj .get("tilewidth") .ok_or_else(|| anyhow!("Should've gotten tilewidth"))? .as_u64() .ok_or_else(|| anyhow!("Tilewidth value wasn't a u64"))? .try_into() .expect("Tiles are too thicc"), tile_height: json_obj .get("tileheight") .ok_or_else(|| anyhow!("Should've gotten tileheight"))? .as_u64() .ok_or_else(|| anyhow!("Tileheight value wasn't a u64"))? .try_into() .expect("Tiles are too tall owo"), spacing: json_obj .get("spacing") .ok_or_else(|| anyhow!("Should've gotten spacing"))? .as_u64() .ok_or_else(|| anyhow!("Spacing value wasn't a u64"))? .try_into() .expect( "God help you if you actually have 2,147,483,647 pixels in between each tile", ), name: json_obj .get("name") .ok_or_else(|| anyhow!("Should've gotten a name"))? .as_str() .ok_or_else(|| anyhow!("Name wasn't a valid string"))? .to_owned(), margin: json_obj .get("margin") .ok_or_else(|| anyhow!("Should've gotten a margin"))? .as_u64() .ok_or_else(|| anyhow!("Margin value wasn't a u64"))? .try_into() .expect( "God help you if you actually have 2,147,483,647 pixels AROUND your tileset", ), properties: Properties::json_parse_properties(v)?, filename: Some(filename), tiles, first_gid, }) } } impl Animation { fn json_parse_animation(v: &[Value], tileset: u8) -> Result<Self> { let mut animation_frames = Vec::with_capacity(v.len()); for entry in v.iter() { animation_frames.push(( TileId( entry .get("tileid") .ok_or_else(|| anyhow!("Couldn't find a tileid in the animation"))? .as_u64() .ok_or_else(|| anyhow!("Tileid should be a u64"))? .try_into() .expect("Tile ids should fit into u32s probably"), TileMetaData::new(tileset, false, false, false), ), entry .get("duration") .ok_or_else(|| anyhow!("Couldn't find a duration in the animation"))? .as_u64() .ok_or_else(|| anyhow!("Duration should be a u64"))? .try_into() .expect("Duration should probably fit in a u32"), )); } Ok(Animation(animation_frames)) } } impl Properties { fn json_parse_properties(v: &Value) -> Result<Self> { let mut properties = HashMap::new(); if let Some(p) = v.get("properties") { let properties_arr = p .as_array() .ok_or_else(|| anyhow!("Couldn't turn properties into an array"))?; if properties_arr.len() > 1 { return Err(anyhow!( "Properties array was greater than 1, not sure if this is expected" )); } for (k, v) in properties_arr[0] .as_object() .ok_or_else(|| { anyhow!("Properties first element couldn't be turned into an object") })? .iter() { properties.insert(k.clone(), Property::from_json_entry(v)?); } } Ok(Properties(properties)) } } impl Tile { fn json_parse_tile(v: &Value, tileset_num: u8, slab: &mut slab::Slab<Object>) -> Result<Self> { let objectgroup = match v.get("objectGroup") { Some(v) => { Some(ObjectGroup::json_parse_object_group(v, u32::MAX, false, slab, None)?.0) } None => None, }; let tile_id: u32 = v .get("id") .ok_or_else(|| anyhow!("Tile entry had no tile id"))? .as_u64() .ok_or_else(|| anyhow!("Could not turn tile id into u64"))? .try_into() .expect("Tile id greater than max u32"); Ok(Tile { id: TileId( tile_id + 1, TileMetaData::new(tileset_num, false, false, false), ), tile_type: v .get("type") .map(|s| { s.as_str() .map(ToOwned::to_owned) .ok_or_else(|| anyhow!("Tile type wasn't a string")) }) .transpose()?, probability: v .get("probability") .map(Value::as_f64) .unwrap_or(Some(0.0)) .ok_or_else(|| anyhow!("Probability wasn't a float"))? as f32, properties: Properties::json_parse_properties(v)?, animation: v .get("animation") .map(|a| { Animation::json_parse_animation( a.as_array() .ok_or_else(|| anyhow!("Animation values weren't an array"))?, tileset_num, ) }) .transpose()?, objectgroup, }) } } impl ObjectGroup { fn json_parse_object_group( objg_obj: &Value, llid: u32, from_obj_layer: bool, slab: &mut slab::Slab<Object>, tileset_ids: Option<&[u8]>, ) -> Result<(ObjectGroup, Vec<(ObjectId, ObjectRef)>), Error> { let mut obj_ids_and_refs = Vec::new(); let mut object_name_map = HashMap::new(); for object in objg_obj .get("objects") .ok_or_else(|| anyhow!("Didn't find objects in the objectgroup"))? .as_array() .ok_or_else(|| anyhow!("Couldn't retrieve objects as an array"))? .iter() { let object = Object::json_parse_object(object, from_obj_layer, tileset_ids)?; let val = object_name_map .entry(object.name.clone()) .or_insert_with(Vec::new); val.push(object.id); obj_ids_and_refs.push((object.id, ObjectRef(slab.insert(object)))); } Ok(( ObjectGroup { name: objg_obj .get("name") .ok_or_else(|| anyhow!("Object group did not have a name"))? .as_str() .ok_or_else(|| anyhow!("Name couldn't be converted to a string"))? .to_owned(), opacity: objg_obj .get("opacity") .ok_or_else(|| anyhow!("Object group did not have an opacity"))? .as_f64() .ok_or_else(|| anyhow!("Opacity couldn't be converted to a f64"))? as f32, visible: objg_obj .get("visible") .ok_or_else(|| anyhow!("Object group did not have a visibility"))? .as_bool() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))?, obj_group_type: ObjGroupType::json_parse_obj_group_type(objg_obj)?, properties: Properties::json_parse_properties(objg_obj)?, draworder: DrawOrder::json_parse_draw_order(objg_obj)?, id: ObjectLayerId { glid: objg_obj .get("id") .ok_or_else(|| anyhow!("Object group did not have an id"))? .as_u64() .ok_or_else(|| anyhow!("Id couldn't be converted to a u64"))? .try_into() .expect("Too many objects"), llid, }, layer_index: objg_obj .get("layer_index") .map(|l_i| { l_i.as_u64() .ok_or_else(|| anyhow!("Layer index couldn't be turned into a u64")) .map(|n| n.try_into().expect("Layer indexes too large")) }) .transpose()?, off_x: objg_obj .get("x") .ok_or_else(|| anyhow!("Didn't find x offset in object group"))? .as_u64() .ok_or_else(|| anyhow!("Couldn't turn x offset to u64"))? .try_into() .expect("X offset too large"), off_y: objg_obj .get("y") .ok_or_else(|| anyhow!("Didn't find y offset in object group"))? .as_u64() .ok_or_else(|| anyhow!("Couldn't turn y offset to u64"))? .try_into() .expect("Y offset too large"), color: objg_obj.get("color").map_or( Ok(Color::from_rgb(0xA0, 0xA0, 0xA4)), |c| { c.as_str() .ok_or_else(|| anyhow!("Color wasn't a string")) .and_then(Color::from_tiled_hex) }, )?, tintcolor: objg_obj .get("tintcolor") .map(|s| { s.as_str() .ok_or_else(|| anyhow!("Tintcolor value wasn't a string")) .and_then(Color::from_tiled_hex) }) .transpose()?, object_refs: obj_ids_and_refs.iter().map(|i| i.1).collect(), object_name_map, }, obj_ids_and_refs, )) } } impl ObjGroupType { fn json_parse_obj_group_type(v: &Value) -> Result<Self> { match v .get("type") .ok_or_else(|| anyhow!("Object group did not contain key type"))? .as_str() .ok_or_else(|| anyhow!("Object group type couldn't be turned into a string"))? { "objectgroup" => Ok(ObjGroupType::ObjectGroup), s => Err(anyhow!("Unsupported object group type: {}", s)), } } } impl DrawOrder { fn json_parse_draw_order(v: &Value) -> Result<Self> { match v .get("draworder") .ok_or_else(|| anyhow!("Object group did not contain draworder"))? .as_str() .ok_or_else(|| anyhow!("Draworder couldn't be turned into a string"))? { "index" => Ok(DrawOrder::Index), s => Err(anyhow!("Unsupported draworder: {}", s)), } } } impl Object { fn json_parse_object( object: &Value, from_obj_layer: bool, _tileset_ids: Option<&[u8]>, ) -> Result<Self> { Ok(Object { name: object .get("name") .ok_or_else(|| anyhow!("Object did not have a name"))? .as_str() .ok_or_else(|| anyhow!("Name couldn't be converted to a string"))? .to_owned(), visible: object .get("visible") .ok_or_else(|| anyhow!("Object did not have a visibility"))? .as_bool() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))?, obj_type: object .get("type") .ok_or_else(|| anyhow!("Object did not have a type"))? .as_str() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))? .to_owned(), height: object .get("height") .ok_or_else(|| anyhow!("Object did not have a height"))? .as_f64() .ok_or_else(|| anyhow!("Height couldn't be converted to a f64"))? as f32, width: object .get("width") .ok_or_else(|| anyhow!("Object did not have a width"))? .as_f64() .ok_or_else(|| anyhow!("Width couldn't be converted to a f64"))? as f32, rotation: object .get("rotation") .ok_or_else(|| anyhow!("Object did not have a rotation"))? .as_f64() .ok_or_else(|| anyhow!("Rotation couldn't be converted to a f64"))? as f32, x: object .get("x") .ok_or_else(|| anyhow!("Object did not have an x pos"))? .as_f64() .ok_or_else(|| anyhow!("X pos couldn't be converted to a f64"))? as f32, y: object .get("y") .ok_or_else(|| anyhow!("Object did not have an y pos"))? .as_f64() .ok_or_else(|| anyhow!("Y pos couldn't be converted to a f64"))? as f32, properties: Properties::json_parse_properties(object)?, text: None, tile_id: None, id: ObjectId::new( object .get("id") .ok_or_else(|| anyhow!("Object did not have an ID"))? .as_u64() .ok_or_else(|| anyhow!("ID couldn't be represented as u64"))? .try_into() .expect("ID greater than u32 MAX"), from_obj_layer, ), shape: Some(ObjectShape::from_json(object)?), }) } }
use crate::*; use hv::prelude::*; impl Tileset { pub fn json_parse_tileset( v: &Value, first_gid: u32, path_prefix: Option<&str>, tileset_number: u8, slab: &mut slab::Slab<Object>, filename: String, ) -> Result<Self> { let json_obj = v .as_object() .ok_or(anyhow!("Tileset file did not contain a json dictionary"))?; let tile_array = json_obj .get("tiles") .map_or::<Result<&[Value]>, _>(Ok(&[][..]), |t_arr| { Ok(t_arr .as_array() .ok_or_else(|| anyhow!("Tiles are not an array"))? .as_slice()) })?; let mut tiles = HashMap::new(); for tile_obj in tile_array.iter() { let tile = Tile::json_parse_tile(tile_obj, tileset_number, slab)?; tiles.insert(tile.id, tile); } Ok(Tileset { columns: json_obj .get("columns") .ok_or_else(|| anyhow!("Should've gotten columns"))? .as_u64() .ok_or_else(|| anyhow!("Columns value wasn't a u64"))? .try_into() .expect("Bruh how many columns does your tileset have"), images: vec![Image::from_json(json_obj, path_prefix)?], tilecount: json_obj .get("tilecount") .ok_or_else(|| anyhow!("Should've gotten tilecount"))? .as_u64() .ok_or_else(|| anyhow!("Tilecount value wasn't a u64"))? .try_into() .expect("Bruh how many tiles does your tileset have"), tile_width: json_obj .get("tilewidth") .ok_or_else(|| anyhow!("Should've gotten tilewidth"))? .as_u64() .ok_or_else(|| anyhow!("Tilewidth value wasn't a u64"))? .try_into() .expect("Tiles are too thicc"), tile_height: json_obj .get("tileheight") .ok_or_else(|| anyhow!("Should've gotten tileheight"))? .as_u64() .ok_or_else(|| anyhow!("Tileheight value wasn't a u64"))? .try_into() .expect("Tiles are too tall owo"), spacing: json_obj .get("spacing") .ok_or_else(|| anyhow!("Should've gotten spacing"))? .as_u64() .ok_or_else(|| anyhow!("Spacing value wasn't a u64"))? .try_into() .expect( "God help you if you actually have 2,147,483,647 pixels in between each tile", ), name: json_obj .get("name") .ok_or_else(|| anyhow!("Should've gotten a name"))? .as_str() .ok_or_else(|| anyhow!("Name wasn't a valid string"))? .to_owned(), margin: json_obj .get("margin") .ok_or_else(|| anyhow!("Should've gotten a margin"))? .as_u64() .ok_or_else(|| anyhow!("Margin value wasn't a u64"))? .try_into() .expect( "God help you if you actually have 2,147,483,647 pixels AROUND your tileset", ), properties: Properties::json_parse_properties(v)?, filename: Some(filename), tiles, first_gid, }) } } impl Animation { fn json_parse_animation(v: &[Value], tileset: u8) -> Result<Self> { let mut animation_frames = Vec::with_capacity(v.len()); for entry in v.iter() { animation_frames.push(( TileId( entry .get("tileid") .ok_or_else(|| anyhow!("Couldn't find a tileid in the animation"))? .as_u64() .ok_or_else(|| anyhow!("Tileid should be a u64"))? .try_into() .expect("Tile ids should fit into u32s probably"), TileMetaData::new(tileset, false, false, false), ), entry .get("duration") .ok_or_else(|| anyhow!("Couldn't find a duration in the animation"))? .as_u64() .ok_or_else(|| anyhow!("Duration should be a u64"))? .try_into() .expect("Duration should probably fit in a u32"), )); } Ok(Animation(animation_frames)) } } impl Properties { fn json_parse_properties(v: &Value) -> Result<Self> { let mut properties = HashMap::new(); if let Some(p) = v.get("properties") { let properties_arr = p .as_array() .ok_or_else(|| anyhow!("Couldn't turn properties into an array"))?; if properties_arr.len() > 1 { return Err(anyhow!( "Properties array was greater than 1, not sure if this is expected" )); } for (k, v) in properties_arr[0] .as_object() .ok_or_else(|| { anyhow!("Properties first element couldn't be turned into an object") })? .iter() { properties.insert(k.clone(), Property::from_json_entry(v)?); } } Ok(Properties(properties)) } } impl Tile { fn json_parse_tile(v: &Value, tileset_num: u8, slab: &mut slab::Slab<Object>) -> Result<Self> { let objectgroup = match v.get("objectGroup") { Some(v) => { Some(ObjectGroup::json_parse_object_group(v, u32::MAX, false, slab, None)?.0) } None => None, }; let tile_id: u32 = v .get("id") .ok_or_else(|| anyhow!("Tile entry had no tile id"))? .as_u64() .ok_or_else(|| anyhow!("Could not turn tile id into u64"))? .try_into() .expect("Tile id greater than max u32"); Ok(Tile { id: TileId( tile_id + 1, TileMetaData::new(tileset_num, false, false, false), ), tile_type: v .get("type") .map(|s| { s.as_str() .map(ToOwned::to_owned) .ok_or_else(|| anyhow!("Tile type wasn't a string")) }) .transpose()?, probability: v .get("probability") .map(Value::as_f64) .unwrap_or(Some(0.0)) .ok_or_else(|| anyhow!("Probability wasn't a float"))? as f32, properties: Properties::json_parse_properties(v)?, animation: v .get("animation") .map(|a| { Animation::json_parse_animation( a.as_array() .ok_or_else(|| anyhow!("Animation values weren't an array"))?, tileset_num, ) }) .transpose()?, objectgroup, }) } } impl ObjectGroup { fn json_parse_object_group( objg_obj: &Value, llid: u32, from_obj_layer: bool, slab: &mut slab::Slab<Object>, tileset_ids: Option<&[u8]>, ) -> Result<(ObjectGroup, Vec<(ObjectId, ObjectRef)>), Error> { let mut obj_ids_and_refs = Vec::new(); let mut object_name_map = HashMap::new(); for object in objg_obj .get("objects") .ok_or_else(|| anyhow!("Didn't find objects in the objectgroup"))? .as_array() .ok_or_else(|| anyhow!("Couldn't retrieve objects as an array"))? .iter() { let object = Object::json_parse_object(object, from_obj_layer, tileset_ids)?; let val = object_name_map .entry(object.name.clone()) .or_insert_with(Vec::new); val.push(object.id); obj_ids_and_refs.push((object.id, ObjectRef(slab.insert(object)))); } Ok(( ObjectGroup { name: objg_obj .get("name") .ok_or_else(|| anyhow!("Object group did not have a name"))? .as_str() .ok_or_else(|| anyhow!("Name couldn't be converted to a string"))? .to_owned(), opacity: objg_obj .get("opacity") .ok_or_else(|| anyhow!("Object group did not have an opacity"))? .as_f64() .ok_or_else(|| anyhow!("Opacity couldn't be converted to a f64"))? as f32, visible: objg_obj .get("visible") .ok_or_else(|| anyhow!("Object group did not have a visibility"))? .as_bool() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))?, obj_group_type: ObjGroupType::json_parse_obj_group_type(objg_obj)?, properties: Properties::json_parse_properties(objg_obj)?, draworder: DrawOrder::json_parse_draw_order(objg_obj)?, id: ObjectLayerId { glid: objg_obj .get("id") .ok_or_else(|| anyhow!("Object group did not have an id"))? .as_u64() .ok_or_else(|| anyhow!("Id couldn't be converted to a u64"))? .try_into() .expect("Too many objects"), llid, }, layer_index: objg_obj .get("layer_index") .map(|l_i| { l_i.as_u64() .ok_or_else(|| anyhow!("Layer index couldn't be turned into a u64")) .map(|n| n.try_into().expect("Layer indexes too large")) }) .transpose()?, off_x: objg_obj .get("x") .ok_or_else(|| anyhow!("Didn't find x offset in object group"))? .as_u64() .ok_or_else(|| anyhow!("Couldn't turn x offset to u64"))? .try_into() .expect("X offset too large"), off_y: objg_obj .get("y") .ok_or_else(|| anyhow!("Didn't find y offset in object group"))? .as_u64() .ok_or_else(|| anyhow!("Couldn't turn y offset to u64"))? .try_into() .expect("Y offset too large"), color: objg_obj.get("color").map_or( Ok(Color::from_rgb(0xA0, 0xA0, 0xA4)), |c| { c.as_str() .ok_or_else(|| anyhow!("Color wasn't a string")) .and_then(Color::from_tiled_hex) }, )?, tintcolor: objg_obj .get("tintcolor") .map(|s| { s.as_str() .ok_or_else(|| anyhow!("Tintcolor value wasn't a string")) .and_then(Color::from_tiled_hex) }) .transpose()?, object_refs: obj_ids_and_refs.iter().map(|i| i.1).collect(), object_name_map, }, obj_ids_and_refs, )) } } impl ObjGroupType { fn json_parse_obj_group_type(v: &Value) -> Result<Self> { match v .get("type") .ok_or_else(|| anyhow!("Object group did not contain key type"))? .as_str() .ok_or_else(|| anyhow!("Object group type couldn't be turned into a string"))? { "objectgroup" => Ok(ObjGroupType::ObjectGroup), s => Err(anyhow!("Unsupported object group type: {}", s)), } } } impl DrawOrder { fn json_parse_draw_order(v: &Value) -> Result<Self> { match v .get("draworder") .ok_or_else(|| anyhow!("Object group did not contain draworder"))? .as_str() .ok_or_else(|| anyhow!("Draworder couldn't be turned into a string"))? { "index" => Ok(DrawOrder::Index), s => Err(anyhow!("Unsupported draworder: {}", s)), } } } impl Object { fn json_parse_object( object: &Value, from_obj_layer: bool, _tileset_ids: Option<&[u8]>, ) -> Result<Self> {
} }
Ok(Object { name: object .get("name") .ok_or_else(|| anyhow!("Object did not have a name"))? .as_str() .ok_or_else(|| anyhow!("Name couldn't be converted to a string"))? .to_owned(), visible: object .get("visible") .ok_or_else(|| anyhow!("Object did not have a visibility"))? .as_bool() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))?, obj_type: object .get("type") .ok_or_else(|| anyhow!("Object did not have a type"))? .as_str() .ok_or_else(|| anyhow!("Visibility couldn't be converted to a bool"))? .to_owned(), height: object .get("height") .ok_or_else(|| anyhow!("Object did not have a height"))? .as_f64() .ok_or_else(|| anyhow!("Height couldn't be converted to a f64"))? as f32, width: object .get("width") .ok_or_else(|| anyhow!("Object did not have a width"))? .as_f64() .ok_or_else(|| anyhow!("Width couldn't be converted to a f64"))? as f32, rotation: object .get("rotation") .ok_or_else(|| anyhow!("Object did not have a rotation"))? .as_f64() .ok_or_else(|| anyhow!("Rotation couldn't be converted to a f64"))? as f32, x: object .get("x") .ok_or_else(|| anyhow!("Object did not have an x pos"))? .as_f64() .ok_or_else(|| anyhow!("X pos couldn't be converted to a f64"))? as f32, y: object .get("y") .ok_or_else(|| anyhow!("Object did not have an y pos"))? .as_f64() .ok_or_else(|| anyhow!("Y pos couldn't be converted to a f64"))? as f32, properties: Properties::json_parse_properties(object)?, text: None, tile_id: None, id: ObjectId::new( object .get("id") .ok_or_else(|| anyhow!("Object did not have an ID"))? .as_u64() .ok_or_else(|| anyhow!("ID couldn't be represented as u64"))? .try_into() .expect("ID greater than u32 MAX"), from_obj_layer, ), shape: Some(ObjectShape::from_json(object)?), })
call_expression
[ { "content": "pub fn to_chunks(data: &[TileId], width: u32, height: u32) -> Chunks {\n\n let mut chunks = Chunks::default();\n\n for y in 0..height {\n\n for x in 0..width {\n\n let (chunk_x, chunk_y, tile_x, tile_y) =\n\n to_chunk_indices_and_subindices(x as i32, y as i32);\n\n chunks.set_tile(\n\n chunk_x,\n\n chunk_y,\n\n ((tile_y * CHUNK_SIZE) + tile_x) as usize,\n\n data[(y * width + x) as usize],\n\n );\n\n }\n\n }\n\n chunks\n\n}\n\n\n\n#[derive(Debug, Clone)]\n\npub enum Encoding {\n\n Lua,\n", "file_path": "tiled/src/tile_layer.rs", "rank": 0, "score": 314019.58191872935 }, { "content": "fn next_word_boundary_char_index(it: impl Iterator<Item = char>, mut index: usize) -> usize {\n\n let mut it = it.skip(index);\n\n if let Some(_first) = it.next() {\n\n index += 1;\n\n\n\n if let Some(second) = it.next() {\n\n index += 1;\n\n for next in it {\n\n if is_word_char(next) != is_word_char(second) {\n\n break;\n\n }\n\n index += 1;\n\n }\n\n }\n\n }\n\n index\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 1, "score": 294819.34815217805 }, { "content": "/// A convenience function to convert a Rust `Duration` type\n\n/// to a (less precise but more useful) `f64`.\n\n///\n\n/// Does not make sure that the `Duration` is within the bounds\n\n/// of the `f64`.\n\npub fn duration_to_f64(d: time::Duration) -> f64 {\n\n let seconds = d.as_secs() as f64;\n\n let nanos = f64::from(d.subsec_nanos());\n\n seconds + (nanos * 1e-9)\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 2, "score": 291177.4345220291 }, { "content": "/// A convenience function to create a Rust `Duration` type\n\n/// from a (less precise but more useful) `f64`.\n\n///\n\n/// Only handles positive numbers correctly.\n\npub fn f64_to_duration(t: f64) -> time::Duration {\n\n debug_assert!(t > 0.0, \"f64_to_duration passed a negative number!\");\n\n let seconds = t.trunc();\n\n let nanos = t.fract() * 1e9;\n\n time::Duration::new(seconds as u64, nanos as u32)\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 3, "score": 291166.09378056665 }, { "content": "/// A convenience function to convert a Rust `Duration` type\n\n/// to a (less precise but more useful) `f32`.\n\n///\n\n/// Does not make sure that the `Duration` is within the bounds\n\n/// of the `f32`.\n\npub fn duration_to_f32(d: time::Duration) -> f32 {\n\n let seconds = d.as_secs() as f32;\n\n let nanos = d.subsec_nanos() as f32;\n\n seconds + (nanos * 1e-9)\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 4, "score": 291083.92077401566 }, { "content": "/// A convenience function to create a Rust `Duration` type\n\n/// from a (less precise but more useful) `f32`.\n\n///\n\n/// Only handles positive numbers correctly.\n\npub fn f32_to_duration(t: f32) -> time::Duration {\n\n debug_assert!(t > 0.0, \"f64_to_duration passed a negative number!\");\n\n let seconds = t.trunc();\n\n let nanos = t.fract() * 1e9;\n\n time::Duration::new(seconds as u64, nanos as u32)\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 5, "score": 291072.593455615 }, { "content": "pub fn to_chunk_indices_and_subindices(x: i32, y: i32) -> (i32, i32, u32, u32) {\n\n let (chunk_x, tile_x) = (\n\n x.div_euclid(CHUNK_SIZE as i32),\n\n x.rem_euclid(CHUNK_SIZE as i32) as u32,\n\n );\n\n let (chunk_y, tile_y) = (\n\n y.div_euclid(CHUNK_SIZE as i32),\n\n y.rem_euclid(CHUNK_SIZE as i32) as u32,\n\n );\n\n (chunk_x, chunk_y, tile_x, tile_y)\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct Chunks(pub HashMap<(i32, i32), Chunk>);\n\n\n\nimpl Chunks {\n\n pub fn new() -> Self {\n\n Chunks(HashMap::default())\n\n }\n\n\n", "file_path": "tiled/src/tile_layer.rs", "rank": 6, "score": 264776.38688974525 }, { "content": "fn delete_selected_ccursor_range(text: &mut dyn TextBuffer, [min, max]: [CCursor; 2]) -> CCursor {\n\n text.delete_char_range(min.index..max.index);\n\n CCursor {\n\n index: min.index,\n\n prefer_next_row: true,\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 7, "score": 234312.6734696193 }, { "content": "pub fn clean(path: &str) -> String {\n\n let out = clean_internal(path.as_bytes());\n\n // The code only matches/modifies ascii tokens and leaves the rest of\n\n // the bytes as they are, so if the input string is valid utf8 the result\n\n // will also be valid utf8.\n\n unsafe { String::from_utf8_unchecked(out) }\n\n}\n\n\n", "file_path": "hv/crates/hv-vfs/src/path_clean.rs", "rank": 8, "score": 231012.81551335932 }, { "content": "/// Convenience function for getting the [`Type`] for some `T`.\n\npub fn of<T: 'static>() -> Type<T> {\n\n Type::of()\n\n}\n\n\n", "file_path": "hv/crates/hv-alchemy/src/lib.rs", "rank": 9, "score": 229568.2445462458 }, { "content": "fn make_registry() -> HashMap<TypeId, &'static TypeTable> {\n\n fn smart_pointers<T: 'static>(_: Type<T>) {\n\n use alloc::{\n\n rc::{Rc, Weak as RcWeak},\n\n sync::{Arc, Weak as ArcWeak},\n\n };\n\n\n\n typed::<Rc<T>>().add_clone();\n\n typed::<RcWeak<T>>().add_clone();\n\n typed::<Arc<T>>().add_clone();\n\n typed::<ArcWeak<T>>().add_clone();\n\n typed::<&'static T>().add_clone().add_copy();\n\n }\n\n\n\n fn wrappers<T: 'static>(_: Type<T>) {\n\n smart_pointers::<T>(typed());\n\n smart_pointers::<core::cell::RefCell<T>>(typed());\n\n smart_pointers::<AtomicRefCell<T>>(typed());\n\n }\n\n\n", "file_path": "hv/crates/hv-alchemy/src/lib.rs", "rank": 10, "score": 222634.7846101066 }, { "content": "fn delete_previous_word(text: &mut dyn TextBuffer, max_ccursor: CCursor) -> CCursor {\n\n let min_ccursor = ccursor_previous_word(text.as_ref(), max_ccursor);\n\n delete_selected_ccursor_range(text, [min_ccursor, max_ccursor])\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 11, "score": 221632.94734663554 }, { "content": "/// Pauses the current thread for the target duration.\n\n/// Just calls [`std::thread::sleep()`](https://doc.rust-lang.org/std/thread/fn.sleep.html)\n\n/// so it's as accurate as that is (which is usually not very).\n\npub fn sleep(duration: time::Duration) {\n\n thread::sleep(duration);\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 12, "score": 220083.76483164373 }, { "content": "/// Returns a `Duration` representing how long each\n\n/// frame should be to match the given fps.\n\n///\n\n/// Approximately.\n\nfn fps_as_duration(fps: u32) -> time::Duration {\n\n let target_dt_seconds = 1.0 / f64::from(fps);\n\n f64_to_duration(target_dt_seconds)\n\n}\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 13, "score": 218799.02432603785 }, { "content": "fn move_single_cursor(cursor: &mut Cursor, galley: &Galley, key: Key, modifiers: &Modifiers) {\n\n match key {\n\n Key::ArrowLeft => {\n\n if modifiers.alt || modifiers.ctrl {\n\n // alt on mac, ctrl on windows\n\n *cursor = galley.from_ccursor(ccursor_previous_word(galley.text(), cursor.ccursor));\n\n } else if modifiers.mac_cmd {\n\n *cursor = galley.cursor_begin_of_row(cursor);\n\n } else {\n\n *cursor = galley.cursor_left_one_character(cursor);\n\n }\n\n }\n\n Key::ArrowRight => {\n\n if modifiers.alt || modifiers.ctrl {\n\n // alt on mac, ctrl on windows\n\n *cursor = galley.from_ccursor(ccursor_next_word(galley.text(), cursor.ccursor));\n\n } else if modifiers.mac_cmd {\n\n *cursor = galley.cursor_end_of_row(cursor);\n\n } else {\n\n *cursor = galley.cursor_right_one_character(cursor);\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 14, "score": 216430.6571838348 }, { "content": "/// Accepts and returns character offset (NOT byte offset!).\n\nfn find_line_start(text: &str, current_index: CCursor) -> CCursor {\n\n // We know that new lines, '\\n', are a single byte char, but we have to\n\n // work with char offsets because before the new line there may be any\n\n // number of multi byte chars.\n\n // We need to know the char index to be able to correctly set the cursor\n\n // later.\n\n let chars_count = text.chars().count();\n\n\n\n let position = text\n\n .chars()\n\n .rev()\n\n .skip(chars_count - current_index.index)\n\n .position(|x| x == '\\n');\n\n\n\n match position {\n\n Some(pos) => CCursor::new(current_index.index - pos),\n\n None => CCursor::new(0),\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 15, "score": 211563.92389142548 }, { "content": "struct Color(f32, f32, f32, f32);\n\n\n\n// A system that simulates 2D kinematic motion.\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 16, "score": 208783.9197441183 }, { "content": "fn decrease_indentation(ccursor: &mut CCursor, text: &mut dyn TextBuffer) {\n\n let line_start = find_line_start(text.as_ref(), *ccursor);\n\n\n\n let remove_len = if text.as_ref()[line_start.index..].starts_with('\\t') {\n\n Some(1)\n\n } else if text.as_ref()[line_start.index..]\n\n .chars()\n\n .take(text::TAB_SIZE)\n\n .all(|c| c == ' ')\n\n {\n\n Some(text::TAB_SIZE)\n\n } else {\n\n None\n\n };\n\n\n\n if let Some(len) = remove_len {\n\n text.delete_char_range(line_start.index..(line_start.index + len));\n\n if *ccursor != line_start {\n\n *ccursor -= len;\n\n }\n\n }\n\n}\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 17, "score": 203406.4205296154 }, { "content": "// A system that tracks the average color of entities.\n\nfn find_average_color(\n\n context: SystemContext,\n\n (average_color, spawned): (&mut Color, &SpawnedEntities),\n\n &mut query: &mut QueryMarker<&Color>,\n\n) {\n\n *average_color = Color(0.0, 0.0, 0.0, 0.0);\n\n for (_entity, color) in context.query(query).iter() {\n\n average_color.0 += color.0;\n\n average_color.1 += color.1;\n\n average_color.2 += color.2;\n\n average_color.3 += color.3;\n\n }\n\n let entities = (spawned.no_acceleration + spawned.with_acceleration) as f32;\n\n average_color.0 /= entities;\n\n average_color.1 /= entities;\n\n average_color.2 /= entities;\n\n average_color.3 /= entities;\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 18, "score": 199504.26833041018 }, { "content": "fn is_word_char(c: char) -> bool {\n\n c.is_ascii_alphanumeric() || c == '_'\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 19, "score": 199458.0812969933 }, { "content": "// A system that recolors entities based on their kinematic properties.\n\nfn color(\n\n context: SystemContext,\n\n (spawned, rng): (&SpawnedEntities, &mut StdRng),\n\n &mut query: &mut QueryMarker<(&Position, &Velocity, &mut Color)>,\n\n) {\n\n // Of course, it's possible to use resources mutably and still batch queries if\n\n // mutation happens outside batching.\n\n let blue = rng.gen_range(0.0..1.0);\n\n hv_yaks::batch(\n\n &mut context.query(query),\n\n spawned.batch_size_all(),\n\n |_entity, (pos, vel, mut col)| {\n\n col.0 = pos.0.abs() / 1000.0;\n\n col.1 = vel.1.abs() / 100.0;\n\n col.2 = blue;\n\n },\n\n );\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 20, "score": 196512.9114010947 }, { "content": "/// Convenience function for marking some `T` as being convertible into some `U`.\n\npub fn convertible<T: 'static, U: 'static + From<T>>() {\n\n of::<T>().add_into::<U>();\n\n of::<U>().add_from::<T>();\n\n}\n\n\n", "file_path": "hv/crates/hv-alchemy/src/lib.rs", "rank": 21, "score": 194236.85171579217 }, { "content": "fn insert_text(ccursor: &mut CCursor, text: &mut dyn TextBuffer, text_to_insert: &str) {\n\n ccursor.index += text.insert_text(text_to_insert, ccursor.index);\n\n}\n\n\n\n// ----------------------------------------------------------------------------\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 22, "score": 192185.60994016373 }, { "content": "fn to_egui_key(key: hv_input::Key) -> Option<egui::Key> {\n\n use egui::Key as Ek;\n\n use hv_input::Key as Hk;\n\n let ek = match key {\n\n Hk::Down => Ek::ArrowDown,\n\n Hk::Left => Ek::ArrowLeft,\n\n Hk::Right => Ek::ArrowRight,\n\n Hk::Up => Ek::ArrowUp,\n\n\n\n Hk::Escape => Ek::Escape,\n\n Hk::Tab => Ek::Tab,\n\n Hk::Backspace => Ek::Backspace,\n\n Hk::Enter => Ek::Enter,\n\n Hk::Space => Ek::Space,\n\n\n\n Hk::Insert => Ek::Insert,\n\n Hk::Delete => Ek::Delete,\n\n Hk::Home => Ek::Home,\n\n Hk::End => Ek::End,\n\n Hk::PageUp => Ek::PageUp,\n", "file_path": "hv/crates/hv-gui/src/lib.rs", "rank": 23, "score": 190053.46288861136 }, { "content": "fn delete_next_char(text: &mut dyn TextBuffer, ccursor: CCursor) -> CCursor {\n\n delete_selected_ccursor_range(text, [ccursor, ccursor + 1])\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 24, "score": 189229.35386929277 }, { "content": "fn delete_previous_char(text: &mut dyn TextBuffer, ccursor: CCursor) -> CCursor {\n\n if ccursor.index > 0 {\n\n let max_ccursor = ccursor;\n\n let min_ccursor = max_ccursor - 1;\n\n delete_selected_ccursor_range(text, [min_ccursor, max_ccursor])\n\n } else {\n\n ccursor\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 25, "score": 189229.35386929277 }, { "content": "fn delete_next_word(text: &mut dyn TextBuffer, min_ccursor: CCursor) -> CCursor {\n\n let max_ccursor = ccursor_next_word(text.as_ref(), min_ccursor);\n\n delete_selected_ccursor_range(text, [min_ccursor, max_ccursor])\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 26, "score": 186954.50607496887 }, { "content": "type Undoer = egui::util::undoer::Undoer<(Section<CCursorRange>, String)>;\n\n\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\n#[cfg_attr(feature = \"serde\", derive(serde::Deserialize, serde::Serialize))]\n\npub enum Section<T> {\n\n History(T),\n\n Buffer(T),\n\n}\n\n\n\nimpl<T: Default> Default for Section<T> {\n\n fn default() -> Self {\n\n Self::Buffer(T::default())\n\n }\n\n}\n\n\n\nimpl<T> Section<T> {\n\n pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Section<U> {\n\n match self {\n\n Self::History(t) => Section::History(f(t)),\n\n Self::Buffer(t) => Section::Buffer(f(t)),\n", "file_path": "hv/crates/hv-console/src/widget/state.rs", "rank": 27, "score": 186717.5954932044 }, { "content": "/// The core implementation. It performs the following, lexically:\n\n/// 1. Reduce multiple slashes to a single slash.\n\n/// 2. Eliminate `.` path name elements (the current directory).\n\n/// 3. Eliminate `..` path name elements (the parent directory) and the non-`.` non-`..`, element that precedes them.\n\n/// 4. Leave intact `..` elements that begin a path.\n\n///\n\n/// If the result of this process is an empty string, return the string `\".\"`, representing the current directory.\n\nfn clean_internal(path: &[u8]) -> Vec<u8> {\n\n static DOT: u8 = b'.';\n\n static SEP: u8 = b'/';\n\n\n\n fn is_sep(b: u8) -> bool {\n\n b == b'/' || b == b'\\\\'\n\n }\n\n\n\n if path.is_empty() {\n\n return vec![DOT];\n\n }\n\n\n\n let rooted = is_sep(path[0]);\n\n let n = path.len();\n\n\n\n // Invariants:\n\n // - reading from path; r is index of next byte to process.\n\n // - dotdot is index in out where .. must stop, either because it is the\n\n // leading slash or it is a leading ../../.. prefix.\n\n //\n", "file_path": "hv/crates/hv-vfs/src/path_clean.rs", "rank": 28, "score": 185112.52923191775 }, { "content": "/// Yields the current timeslice to the OS.\n\n///\n\n/// This just calls [`std::thread::yield_now()`](https://doc.rust-lang.org/std/thread/fn.yield_now.html)\n\n/// but it's handy to have here.\n\npub fn yield_now() {\n\n thread::yield_now();\n\n}\n\n\n", "file_path": "hv/crates/hv-timer/src/lib.rs", "rank": 29, "score": 183323.19466703606 }, { "content": "fn typed<T: 'static>() -> Type<T> {\n\n Type::new()\n\n}\n\n\n\nmacro_rules! add_types {\n\n ($m:ident, $closure:expr; $($t:ty),*) => {{\n\n $({\n\n let t = <Type<$t>>::new();\n\n $closure(t);\n\n $m.insert(TypeId::of::<$t>(), t.as_untyped());\n\n })*\n\n }}\n\n}\n\n\n", "file_path": "hv/crates/hv-alchemy/src/lib.rs", "rank": 30, "score": 179883.1939128646 }, { "content": "pub fn syntax_highlighter<'a>(\n\n theme: &'a CodeTheme,\n\n language: &'a str,\n\n) -> impl FnMut(&egui::Ui, &str, f32) -> Arc<Galley> + 'a {\n\n |ui: &egui::Ui, string: &str, wrap_width: f32| {\n\n let mut layout_job = self::syntax_highlight::highlight(ui.ctx(), theme, string, language);\n\n layout_job.wrap_width = wrap_width;\n\n ui.fonts().layout_job(layout_job)\n\n }\n\n}\n", "file_path": "hv/crates/hv-console/src/widget.rs", "rank": 31, "score": 178859.96666384864 }, { "content": "fn delete_selected(text: &mut dyn TextBuffer, cursor_range: &CursorRange) -> CCursor {\n\n let [min, max] = cursor_range.sorted();\n\n delete_selected_ccursor_range(text, [min.ccursor, max.ccursor])\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 32, "score": 176689.7507983119 }, { "content": "type Command<'a> = ArenaBox<'a, dyn FnMut(&mut World, &mut Resources) -> Result<()> + Send>;\n\n\n\nconst CHUNK_SIZE: usize = 1024;\n\n\n\npub struct CommandBuffer {\n\n inner: Elastic<StretchedCommandBufferInner>,\n\n}\n\n\n\nstatic_assertions::assert_impl_all!(CommandBuffer: LuaUserData, Send, Sync);\n\n\n\nimpl CommandBuffer {\n\n pub fn push(\n\n &mut self,\n\n command: impl FnOnce(&mut World, &mut Resources) -> Result<()> + Send + 'static,\n\n ) {\n\n let mut inner = self.inner.try_borrow_as_parameterized_mut().unwrap();\n\n let bump = unsafe { &*inner.bump.get() };\n\n let mut command = Some(command);\n\n let wrapped = move |world: &'_ mut World, resources: &'_ mut Resources| {\n\n (command.take().unwrap())(world, resources)\n", "file_path": "altar/src/command_buffer.rs", "rank": 33, "score": 175925.14452254117 }, { "content": "// Unpack coordinates created with `pack_coords`.\n\nfn unpack_coords(packed: u64) -> Vector3<i32> {\n\n let b = packed.to_le_bytes();\n\n // retrieve the sign from the most significant bit.\n\n let mut xb = ((b[2] as i8).signum() as i32).to_le_bytes();\n\n xb[0..3].copy_from_slice(&b[0..3]);\n\n let mut yb = ((b[5] as i8).signum() as i32).to_le_bytes();\n\n yb[0..3].copy_from_slice(&b[3..6]);\n\n let mut zb = ((b[7] as i8).signum() as i32).to_le_bytes();\n\n zb[0..2].copy_from_slice(&b[6..8]);\n\n Vector3::new(\n\n i32::from_le_bytes(xb),\n\n i32::from_le_bytes(yb),\n\n i32::from_le_bytes(zb),\n\n )\n\n}\n\n\n\n#[derive(Debug, Default, Clone)]\n\npub struct Intersections {\n\n buf: Vec<u64>,\n\n}\n", "file_path": "altar/src/lattice/collider_map.rs", "rank": 34, "score": 173994.79402507888 }, { "content": "// Pack three i32 coordinates into 3 bytes, 3 bytes, and 2 bytes.\n\nfn pack_coords(coords: Vector3<i32>) -> u64 {\n\n assert!(coords.x.abs() < (1 << 23) - 1);\n\n assert!(coords.y.abs() < (1 << 23) - 1);\n\n assert!(coords.z.abs() < (1 << 15) - 1);\n\n\n\n let x = coords.x.to_le_bytes();\n\n let y = coords.y.to_le_bytes();\n\n let z = coords.z.to_le_bytes();\n\n u64::from_le_bytes([x[0], x[1], x[2], y[0], y[1], y[2], z[0], z[1]])\n\n}\n\n\n", "file_path": "altar/src/lattice/collider_map.rs", "rank": 35, "score": 173994.79402507888 }, { "content": "pub trait VFile: Read + Write + Seek + Debug + Send + Sync {}\n\n\n\nimpl<T> VFile for T where T: Read + Write + Seek + Debug + Send + Sync {}\n\n\n\n/// Options for opening files\n\n///\n\n/// We need our own version of this structure because the one in\n\n/// `std` annoyingly doesn't let you read the read/write/create/etc\n\n/// state out of it.\n\n#[must_use]\n\n#[derive(Debug, Default, Copy, Clone, PartialEq)]\n\npub struct OpenOptions {\n\n read: bool,\n\n write: bool,\n\n create: bool,\n\n append: bool,\n\n truncate: bool,\n\n}\n\n\n\nimpl OpenOptions {\n", "file_path": "hv/crates/hv-vfs/src/lib.rs", "rank": 36, "score": 169247.5001682877 }, { "content": "fn dummy_system(_: SystemContext, _: (), _: &mut ()) {}\n\n\n", "file_path": "hv/crates/hv-yaks/tests/builder.rs", "rank": 37, "score": 165136.15904205546 }, { "content": "#[test]\n\nfn contains() {\n\n let mut resources = Resources::new();\n\n resources.insert(One(1));\n\n\n\n assert!(resources.contains::<One>());\n\n assert!(!resources.contains::<Two>());\n\n\n\n resources.insert(Two(2));\n\n assert!(resources.contains::<Two>());\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 38, "score": 161501.73025345698 }, { "content": "#[test]\n\nfn entry() {\n\n let mut resources = Resources::new();\n\n\n\n resources.insert(One(0));\n\n resources\n\n .entry::<One>()\n\n .and_modify(|ref1| ref1.0 += 1)\n\n .or_insert(One(5));\n\n\n\n resources\n\n .entry::<Two>()\n\n .and_modify(|ref2| ref2.0 = 5)\n\n .or_default();\n\n\n\n let resources = resources;\n\n\n\n let ref1 = resources.get::<One>().unwrap();\n\n let ref2 = resources.get::<Two>().unwrap();\n\n\n\n assert_eq!(ref1.0, 1);\n\n assert_eq!(ref2.0, 2);\n\n}\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 39, "score": 161498.04252859968 }, { "content": "/// Distributes over a `rayon` thread pool the work of applying a function to items in a query. See\n\n/// [`hv_ecs::QueryBorrow::iter_batched()`](../hv-ecs/struct.QueryBorrow.html#method.iter_batched).\n\n///\n\n/// If the default `parallel` feature is disabled the functionality is identical to\n\n/// `query_borrow.iter().for_each(for_each)`.\n\n///\n\n/// Calling `batch()` standalone will use the global `rayon` thread pool:\n\n/// ```rust\n\n/// # struct Pos;\n\n/// # struct Vel;\n\n/// # impl std::ops::AddAssign<&Vel> for Pos {\n\n/// # fn add_assign(&mut self, _: &Vel) {}\n\n/// # }\n\n/// # let world = hv_ecs::World::new();\n\n/// # let num_entities = 64;\n\n/// hv_yaks::batch(\n\n/// &mut world.query::<(&mut Pos, &Vel)>(),\n\n/// num_entities / 16,\n\n/// |_entity, (pos, vel)| {\n\n/// *pos += vel;\n\n/// },\n\n/// );\n\n/// ```\n\n/// Alternatively, a specific thread pool can be used via\n\n/// [`rayon::ThreadPool::install()`](../rayon/struct.ThreadPool.html#method.install):\n\n/// ```rust\n\n/// # struct Pos;\n\n/// # struct Vel;\n\n/// # impl std::ops::AddAssign<&Vel> for Pos {\n\n/// # fn add_assign(&mut self, _: &Vel) {}\n\n/// # }\n\n/// # let world = hv_ecs::World::new();\n\n/// # let num_entities = 64;\n\n/// # #[cfg(feature = \"parallel\")]\n\n/// # let thread_pool =\n\n/// # {\n\n/// # rayon::ThreadPoolBuilder::new().build().unwrap()\n\n/// # };\n\n/// # #[cfg(not(feature = \"parallel\"))]\n\n/// # let thread_pool =\n\n/// # {\n\n/// # struct DummyPool;\n\n/// # impl DummyPool {\n\n/// # fn install(&self, mut closure: impl FnMut()) {\n\n/// # closure();\n\n/// # }\n\n/// # }\n\n/// # DummyPool\n\n/// # };\n\n/// thread_pool.install(|| {\n\n/// hv_yaks::batch(\n\n/// &mut world.query::<(&mut Pos, &Vel)>(),\n\n/// num_entities / 16,\n\n/// |_entity, (pos, vel)| {\n\n/// *pos += vel;\n\n/// },\n\n/// )\n\n/// });\n\n/// ```\n\n/// `batch()` can be called in systems, where it will use whichever thread pool is used by the\n\n/// system or the executor it's in:\n\n/// ```rust\n\n/// # use hv_yaks::{QueryMarker, Executor};\n\n/// # struct Pos;\n\n/// # struct Vel;\n\n/// # impl std::ops::AddAssign<&Vel> for Pos {\n\n/// # fn add_assign(&mut self, _: &Vel) {}\n\n/// # }\n\n/// # let world = hv_ecs::World::new();\n\n/// # let mut num_entities = 64;\n\n/// # #[cfg(feature = \"parallel\")]\n\n/// # let thread_pool =\n\n/// # {\n\n/// # rayon::ThreadPoolBuilder::new().num_threads(2).build().unwrap()\n\n/// # };\n\n/// # #[cfg(not(feature = \"parallel\"))]\n\n/// # let thread_pool =\n\n/// # {\n\n/// # struct DummyPool;\n\n/// # impl DummyPool {\n\n/// # fn install(&self, mut closure: impl FnMut()) {\n\n/// # closure();\n\n/// # }\n\n/// # }\n\n/// # DummyPool\n\n/// # };\n\n/// let mut executor = Executor::<(u32, )>::builder()\n\n/// .system(|context, num_entities: &u32, &mut query: &mut QueryMarker<(&mut Pos, &Vel)>| {\n\n/// hv_yaks::batch(\n\n/// &mut context.query(query),\n\n/// num_entities / 16,\n\n/// |_entity, (pos, vel)| {\n\n/// *pos += vel;\n\n/// },\n\n/// )\n\n/// })\n\n/// .build();\n\n///\n\n/// executor.run(&world, &mut num_entities);\n\n///\n\n/// thread_pool.install(|| {\n\n/// let mut executor = Executor::<(u32, )>::builder()\n\n/// .system(|context, num_entities: &u32, &mut query: &mut QueryMarker<(&mut Pos, &Vel)>| {\n\n/// hv_yaks::batch(\n\n/// &mut context.query(query),\n\n/// num_entities / 16,\n\n/// |_entity, (pos, vel)| {\n\n/// *pos += vel;\n\n/// },\n\n/// )\n\n/// })\n\n/// .build();\n\n///\n\n/// executor.run(&world, &mut num_entities);\n\n/// });\n\n/// ```\n\npub fn batch<'query, 'world, Q, F>(\n\n query_borrow: &'query mut QueryBorrow<'world, Q>,\n\n batch_size: u32,\n\n for_each: F,\n\n) where\n\n Q: Query + Send + Sync + 'query,\n\n F: Fn(Entity, <<Q as Query>::Fetch as Fetch<'query>>::Item) + Send + Sync,\n\n{\n\n #[cfg(feature = \"parallel\")]\n\n {\n\n use rayon::prelude::{ParallelBridge, ParallelIterator};\n\n query_borrow\n\n .iter_batched(batch_size)\n\n .par_bridge()\n\n .for_each(|batch| batch.for_each(|(entity, components)| for_each(entity, components)));\n\n }\n\n #[cfg(not(feature = \"parallel\"))]\n\n {\n\n query_borrow\n\n .iter()\n\n .for_each(|(entity, components)| for_each(entity, components));\n\n }\n\n}\n", "file_path": "hv/crates/hv-yaks/src/batch.rs", "rank": 40, "score": 161280.11478776793 }, { "content": "// Can't #[derive] on something w/ a type macro in it. (?? what?)\n\ntype ValidBits = BitArr!(for 256);\n\n\n\n#[derive(Debug)]\n\npub struct Chunk<T> {\n\n data: Box<[MaybeUninit<T>; CHUNK_AREA]>,\n\n valid: ValidBits,\n\n}\n\n\n\nimpl<T: Clone> Clone for Chunk<T> {\n\n fn clone(&self) -> Self {\n\n let mut new_chunk = Chunk::default();\n\n for index in self.valid.iter_ones() {\n\n new_chunk.data[index].write(unsafe { self.data[index].assume_init_ref() }.clone());\n\n }\n\n new_chunk.valid = self.valid;\n\n new_chunk\n\n }\n\n}\n\n\n\nimpl<T> Index<SubCoords> for Chunk<T> {\n", "file_path": "altar/src/lattice/chunk_map.rs", "rank": 41, "score": 158093.3180841156 }, { "content": "#[proc_macro_derive(Query)]\n\npub fn derive_query(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n match query::derive(input) {\n\n Ok(ts) => ts,\n\n Err(e) => e.to_compile_error(),\n\n }\n\n .into()\n\n}\n", "file_path": "hv/crates/hv-ecs-derive/src/lib.rs", "rank": 42, "score": 157512.55885937257 }, { "content": "#[proc_macro_derive(Bundle)]\n\npub fn derive_bundle(input: TokenStream) -> TokenStream {\n\n let input = parse_macro_input!(input as DeriveInput);\n\n match bundle::derive(input) {\n\n Ok(ts) => ts,\n\n Err(e) => e.to_compile_error(),\n\n }\n\n .into()\n\n}\n\n\n\n/// Implement `Query` for a struct\n\n///\n\n/// Queries structs can be passed to the type parameter of `World::query`. They must have exactly\n\n/// one lifetime parameter, and all of their fields must be queries (e.g. references) using that\n\n/// lifetime.\n\n///\n\n/// # Example\n\n/// ```ignore\n\n/// #[derive(Query, Debug, PartialEq)]\n\n/// struct Foo<'a> {\n\n/// x: &'a i32,\n", "file_path": "hv/crates/hv-ecs-derive/src/lib.rs", "rank": 43, "score": 157512.55885937257 }, { "content": "/// Specifies how a specific type may be borrowed from a tuple of cells.\n\npub trait Contains<R0, M0> {\n\n fn borrow(&self) -> &R0;\n\n\n\n #[allow(clippy::mut_from_ref)]\n\n fn borrow_mut(&self) -> &mut R0;\n\n\n\n unsafe fn release(&self);\n\n\n\n unsafe fn release_mut(&self);\n\n\n\n #[cfg(feature = \"parallel\")]\n\n fn set_resource_bit(bitset: &mut FixedBitSet);\n\n}\n\n\n\nimpl<R0> Contains<R0, ()> for (ResourceCell<R0>,) {\n\n fn borrow(&self) -> &R0 {\n\n self.0.borrow()\n\n }\n\n\n\n fn borrow_mut(&self) -> &mut R0 {\n", "file_path": "hv/crates/hv-yaks/src/resource/contains.rs", "rank": 44, "score": 157053.1005449904 }, { "content": "/// Returns `Some(new_cursor)` if we did mutate `text`.\n\nfn on_key_press(\n\n cursor_range: &mut CursorRange,\n\n text: &mut dyn TextBuffer,\n\n galley: &Galley,\n\n key: Key,\n\n modifiers: &Modifiers,\n\n) -> Option<CCursorRange> {\n\n match key {\n\n Key::Backspace => {\n\n let ccursor = if modifiers.mac_cmd {\n\n delete_paragraph_before_cursor(text, galley, cursor_range)\n\n } else if let Some(cursor) = cursor_range.single() {\n\n if modifiers.alt || modifiers.ctrl {\n\n // alt on mac, ctrl on windows\n\n delete_previous_word(text, cursor.ccursor)\n\n } else {\n\n delete_previous_char(text, cursor.ccursor)\n\n }\n\n } else {\n\n delete_selected(text, cursor_range)\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 45, "score": 155933.8278626384 }, { "content": "// A system that tracks the highest velocity among all entities.\n\nfn find_highest_velocity(\n\n context: SystemContext,\n\n highest: &mut Velocity,\n\n &mut query: &mut QueryMarker<&Velocity>,\n\n) {\n\n // This cannot be batched as is because it needs mutable access to `highest`;\n\n // however, it's possible to work around that by using channels and/or `RwLock`.\n\n for (_entity, vel) in context.query(query).iter() {\n\n if vel.0 * vel.0 + vel.1 * vel.1 > highest.0 * highest.0 + highest.1 * highest.1 {\n\n highest.0 = vel.0;\n\n highest.1 = vel.1;\n\n }\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 46, "score": 155932.0690465043 }, { "content": "type SystemClosure<'closure, Cells> = dyn FnMut(SystemContext, &Cells) + Send + Sync + 'closure;\n", "file_path": "hv/crates/hv-yaks/src/executor/mod.rs", "rank": 47, "score": 155169.40161382515 }, { "content": "pub trait VMetadata {\n\n /// Returns whether or not it is a directory.\n\n /// Note that zip files don't actually have directories, awkwardly,\n\n /// just files with very long names.\n\n fn is_dir(&self) -> bool;\n\n /// Returns whether or not it is a file.\n\n fn is_file(&self) -> bool;\n\n /// Returns the length of the thing. If it is a directory,\n\n /// the result of this is undefined/platform dependent.\n\n fn len(&self) -> u64;\n\n /// Returns true if `len` is zero.\n\n fn is_empty(&self) -> bool {\n\n self.len() == 0\n\n }\n\n}\n\n\n\n/// A VFS that points to a directory and uses it as the root of its\n\n/// file hierarchy.\n\n///\n\n/// It IS allowed to have symlinks in it! They're surprisingly\n", "file_path": "hv/crates/hv-vfs/src/lib.rs", "rank": 48, "score": 154752.0218351191 }, { "content": "pub fn derive(input: DeriveInput) -> Result<TokenStream2> {\n\n let ident = input.ident;\n\n let vis = input.vis;\n\n let data = match input.data {\n\n syn::Data::Struct(s) => s,\n\n _ => {\n\n return Err(Error::new_spanned(\n\n ident,\n\n \"derive(Query) may only be applied to structs\",\n\n ))\n\n }\n\n };\n\n let lifetime = input\n\n .generics\n\n .lifetimes()\n\n .next()\n\n .map(|x| x.lifetime.clone());\n\n let lifetime = match lifetime {\n\n Some(x) => x,\n\n None => {\n", "file_path": "hv/crates/hv-ecs-derive/src/query.rs", "rank": 49, "score": 154590.2422945004 }, { "content": "pub fn derive(input: DeriveInput) -> Result<TokenStream2> {\n\n let ident = input.ident;\n\n let data = match input.data {\n\n syn::Data::Struct(s) => s,\n\n _ => {\n\n return Err(Error::new_spanned(\n\n ident,\n\n \"derive(Bundle) does not support enums or unions\",\n\n ))\n\n }\n\n };\n\n let (tys, field_members) = struct_fields(&data.fields);\n\n let field_idents = member_as_idents(&field_members);\n\n let generics = add_additional_bounds_to_generic_params(input.generics);\n\n\n\n let dyn_bundle_code = gen_dynamic_bundle_impl(&ident, &generics, &field_members, &tys);\n\n let bundle_code = if tys.is_empty() {\n\n gen_unit_struct_bundle_impl(ident, &generics)\n\n } else {\n\n gen_bundle_impl(&ident, &generics, &field_members, &field_idents, &tys)\n\n };\n\n let mut ts = dyn_bundle_code;\n\n ts.extend(bundle_code);\n\n Ok(ts)\n\n}\n\n\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 50, "score": 154590.2422945004 }, { "content": "fn query_fetch_ty(lifetime: &Lifetime, ty: &Type) -> TokenStream2 {\n\n struct Visitor<'a> {\n\n replace: &'a Lifetime,\n\n }\n\n impl syn::visit_mut::VisitMut for Visitor<'_> {\n\n fn visit_lifetime_mut(&mut self, l: &mut Lifetime) {\n\n if l == self.replace {\n\n *l = Lifetime::new(\"'static\", Span::call_site());\n\n }\n\n }\n\n }\n\n\n\n let mut ty = ty.clone();\n\n syn::visit_mut::visit_type_mut(&mut Visitor { replace: lifetime }, &mut ty);\n\n quote! {\n\n <#ty as ::hecs::Query>::Fetch\n\n }\n\n}\n", "file_path": "hv/crates/hv-ecs-derive/src/query.rs", "rank": 51, "score": 154064.87536460304 }, { "content": "#[allow(clippy::type_complexity)]\n\npub fn update(\n\n context: SystemContext,\n\n (dt, tick, atom_map, pipeline): (&UpdateDt, &UpdateTick, &AtomMap, &mut PhysicsPipeline),\n\n (\n\n ref mut all_colliders_query,\n\n ref mut dynamic_objects_query,\n\n ref mut with_physics_and_dynamic_query,\n\n physics_query_marker,\n\n ref mut update_target_pos_query,\n\n ref mut motion_clamping_query,\n\n ref mut all_physics_objects_query,\n\n ): &mut (\n\n PreparedQuery<&mut Physics>,\n\n PreparedQuery<DynamicBody<&mut Physics>>,\n\n PreparedQuery<DynamicBody<With<Physics, ()>>>,\n\n QueryMarker<&mut Physics>,\n\n PreparedQuery<With<Velocity, (&mut Physics, Satisfies<&CcdEnabled>)>>,\n\n PreparedQuery<DynamicBody<With<CcdEnabled, With<Physics, ()>>>>,\n\n PreparedQuery<(&mut Position, Option<&mut Velocity>, &mut Physics)>,\n\n ),\n", "file_path": "altar/src/physics.rs", "rank": 52, "score": 153916.87551721354 }, { "content": "pub fn run(\n\n title: &str,\n\n window_kind: WindowKind,\n\n resources: &mut Resources,\n\n event_loop: &mut impl EventLoop<GL33Context>,\n\n) -> Result<()> {\n\n let GlfwSurface {\n\n events_rx,\n\n mut context,\n\n } = GlfwSurface::new(|glfw| {\n\n let (mut window, events) = match window_kind {\n\n WindowKind::Fullscreen { width, height } => glfw.with_primary_monitor(|glfw, m| {\n\n let m = m.ok_or_else(|| {\n\n GlfwSurfaceError::UserError(anyhow!(\n\n \"no primary monitor - cannot create fullscreen window\"\n\n ))\n\n })?;\n\n glfw.create_window(\n\n width as u32,\n\n height as u32,\n", "file_path": "altar/src/glfw.rs", "rank": 53, "score": 153911.55156060273 }, { "content": "fn gen_bundle_impl(\n\n ident: &syn::Ident,\n\n generics: &syn::Generics,\n\n field_members: &[syn::Member],\n\n field_idents: &[Cow<syn::Ident>],\n\n tys: &[&syn::Type],\n\n) -> TokenStream2 {\n\n let num_tys = tys.len();\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n let with_static_ids_inner = quote! {\n\n {\n\n let mut tys = [#((::std::mem::align_of::<#tys>(), ::std::any::TypeId::of::<#tys>())),*];\n\n tys.sort_unstable_by(|x, y| {\n\n ::std::cmp::Ord::cmp(&x.0, &y.0)\n\n .reverse()\n\n .then(::std::cmp::Ord::cmp(&x.1, &y.1))\n\n });\n\n let mut ids = [::std::any::TypeId::of::<()>(); #num_tys];\n\n for (id, info) in ::std::iter::Iterator::zip(ids.iter_mut(), tys.iter()) {\n\n *id = info.1;\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 54, "score": 153310.7996947995 }, { "content": "/// This is a utility Trait that fetches the next ptr from\n\n/// an object.\n\npub trait GetNextMut {\n\n type NextPtr;\n\n fn get_next(&mut self) -> &mut Self::NextPtr;\n\n}\n", "file_path": "hv/crates/hv-atom/src/lib.rs", "rank": 55, "score": 152074.1207339193 }, { "content": "fn gen_dynamic_bundle_impl(\n\n ident: &syn::Ident,\n\n generics: &syn::Generics,\n\n field_members: &[syn::Member],\n\n tys: &[&syn::Type],\n\n) -> TokenStream2 {\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n quote! {\n\n unsafe impl #impl_generics ::hv::ecs::DynamicBundle for #ident #ty_generics #where_clause {\n\n fn key(&self) -> ::core::option::Option<::core::any::TypeId> {\n\n ::core::option::Option::Some(::core::any::TypeId::of::<Self>())\n\n }\n\n\n\n fn with_ids<__hv::ecs__T>(&self, f: impl ::std::ops::FnOnce(&[::std::any::TypeId]) -> __hv::ecs__T) -> __hv::ecs__T {\n\n <Self as ::hv::ecs::Bundle>::with_static_ids(f)\n\n }\n\n\n\n fn type_info(&self) -> ::std::vec::Vec<::hv::ecs::TypeInfo> {\n\n <Self as ::hv::ecs::Bundle>::static_type_info()\n\n }\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 56, "score": 150801.036007154 }, { "content": " function types.string(x, visited, accum)\n\n local alen = #accum\n\n if visited[x] then\n\n accum[alen + 1] = \"\\208\"\n\n accum[alen + 2] = number_to_str(visited[x])\n\n else\n\n visited[x] = visited[NEXT]\n\n visited[NEXT] = visited[NEXT] + 1\n\n accum[alen + 1] = \"\\206\"\n\n accum[alen + 2] = number_to_str(#x)\n\n accum[alen + 3] = x\n\n end\n\n end\n\n\n\n local function check_custom_type(x, visited, accum)\n\n local res = resources[x]\n\n if res then\n\n accum[#accum + 1] = \"\\211\"\n\n types[type(res)](res, visited, accum)\n\n return true\n", "file_path": "hv/crates/hv-script/resources/binser.lua", "rank": 57, "score": 149692.31977047253 }, { "content": "fn hv_filesystem_loader<'lua>(lua: &'lua Lua, path: LuaString<'lua>) -> LuaResult<LuaValue<'lua>> {\n\n // `package.path`\n\n let package_path = lua\n\n .globals()\n\n .get::<_, LuaTable>(\"package\")?\n\n .get::<_, LuaString>(\"path\")?;\n\n\n\n // Shouldn't ever be bad unicode, tbh. If either of these are bad unicode, something else is\n\n // very wrong.\n\n let package_path = package_path.to_str()?;\n\n let path = path.to_str()?;\n\n\n\n // First, look for a `Filesystem` in our Lua app data.\n\n if let Some(mut fs) = lua.app_data_mut::<Filesystem>() {\n\n return hv_filesystem_do_load(lua, package_path, path, &mut *fs);\n\n } else if let Some(fs_elastic) = lua.app_data_ref::<ElasticMut<Filesystem>>() {\n\n if let Ok(mut fs) = fs_elastic.try_borrow_mut() {\n\n return hv_filesystem_do_load(lua, package_path, path, &mut *fs);\n\n }\n\n }\n", "file_path": "hv/crates/hv-script/src/api.rs", "rank": 58, "score": 148034.70297700638 }, { "content": "/// Types that can be stored in [`Resources`], automatically implemented for all applicable.\n\n///\n\n/// [`Resources`]: struct.Resources.html\n\npub trait Resource: Downcast + 'static {}\n\n\n\nimpl<T> Resource for T where T: 'static {}\n\n\n\nimpl_downcast!(Resource);\n\n\n\n/// A [`Resource`] container, for storing at most one resource of each specific type.\n\n///\n\n/// Internally, this is a [`FxHashMap`] of [`TypeId`] to [`RwLock`]. None of the methods are\n\n/// blocking, however: accessing a resource in a way that would break borrow rules will\n\n/// return the [`InvalidBorrow`] error instead.\n\n///\n\n/// [`Resource`]: trait.Resource.html\n\n/// [`FxHashMap`]: ../fxhash/type.FxHashMap.html\n\n/// [`TypeId`]: https://doc.rust-lang.org/std/any/struct.TypeId.html\n\n/// [`RwLock`]: ../parking_lot/type.RwLock.html\n\n/// [`InvalidBorrow`]: enum.InvalidBorrow.html\n\n#[derive(Default)]\n\npub struct Resources {\n\n resources: FxHashMap<TypeId, RwLock<Box<dyn Resource>>>,\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/src/map.rs", "rank": 59, "score": 147657.32994327525 }, { "content": "fn add_additional_bounds_to_generic_params(mut generics: syn::Generics) -> syn::Generics {\n\n generics.type_params_mut().for_each(|tp| {\n\n tp.bounds\n\n .push(syn::TypeParamBound::Trait(make_component_trait_bound()))\n\n });\n\n generics\n\n}\n\n\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 60, "score": 147447.33282863934 }, { "content": "struct ArcRefMutGuard<C: ?Sized> {\n\n cell: Arc<AtomicRefCell<C>>,\n\n borrow: AtomicBorrowRefMut,\n\n}\n\n\n\nimpl<C: ?Sized> Drop for ArcRefMutGuard<C> {\n\n fn drop(&mut self) {\n\n self.borrow.release(&self.cell.borrows);\n\n }\n\n}\n\n\n\n/// A wrapper type for a mutably borrowed value from an `ArcRefCell<T>`.\n\npub struct ArcRefMut<T: ?Sized, C: ?Sized = T> {\n\n value: *mut T,\n\n guard: ArcRefMutGuard<C>,\n\n\n\n #[cfg(feature = \"track-leases\")]\n\n lease: Lease,\n\n}\n\n\n", "file_path": "hv/crates/hv-cell/src/lib.rs", "rank": 61, "score": 146775.40820383746 }, { "content": "fn byte_index_from_char_index(s: &str, char_index: usize) -> usize {\n\n for (ci, (bi, _)) in s.char_indices().enumerate() {\n\n if ci == char_index {\n\n return bi;\n\n }\n\n }\n\n s.len()\n\n}\n", "file_path": "hv/crates/hv-console/src/widget/text_buffer.rs", "rank": 62, "score": 146534.57978888223 }, { "content": "/// Abstracts over non-blocking guarded mutable borrows from behind mutable references\n\n/// (for example, `RefCell::get_mut`, or calling `.write()` on an `&mut Arc<RwLock<T>>`.)\n\npub trait NonBlockingGuardedMutBorrowMut<T: ?Sized> {\n\n /// The guard type (for example, `std::sync::RwLockWriteGuard<'a, T>`.)\n\n type MutGuardMut<'a>: Deref<Target = T> + DerefMut\n\n where\n\n T: 'a,\n\n Self: 'a;\n\n /// The type returned in the case the value cannot be borrowed.\n\n type MutBorrowMutError<'a>\n\n where\n\n T: 'a,\n\n Self: 'a;\n\n\n\n /// Attempt to perform the borrow.\n\n fn try_nonblocking_guarded_mut_borrow_mut(\n\n &mut self,\n\n ) -> Result<Self::MutGuardMut<'_>, Self::MutBorrowMutError<'_>>;\n\n}\n\n\n\nimpl<'a, T: ?Sized> NonBlockingGuardedBorrow<T> for &'a T {\n\n type Guard<'b>\n", "file_path": "hv/crates/hv-guarded-borrow/src/lib.rs", "rank": 63, "score": 146448.6861401988 }, { "content": "/// A generic event loop trait.\n\npub trait EventLoop<C> {\n\n /// Initialize the event loop given the acquired context type.\n\n fn init(&mut self, _resources: &mut Resources, _lua: &Lua, _context: &mut C) -> Result<()> {\n\n Ok(())\n\n }\n\n\n\n fn tick(\n\n &mut self,\n\n resources: &mut Resources,\n\n lua: &Lua,\n\n context: &mut C,\n\n ) -> Result<ControlFlow<(), ()>>;\n\n}\n\n\n", "file_path": "altar/src/event_loop.rs", "rank": 64, "score": 146425.173196279 }, { "content": "pub trait FixedTimestepLoop<C> {\n\n fn init(&mut self, _resources: &mut Resources, _lua: &Lua, _context: &mut C) -> Result<()> {\n\n Ok(())\n\n }\n\n\n\n fn pre_tick(&mut self, resources: &mut Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n\n\n fn update(&mut self, resources: &mut Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n fn draw(&mut self, resources: &mut Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n\n\n fn post_tick(\n\n &mut self,\n\n resources: &mut Resources,\n\n lua: &Lua,\n\n context: &mut C,\n\n ) -> Result<ControlFlow<(), ()>>;\n\n}\n", "file_path": "altar/src/event_loop.rs", "rank": 65, "score": 144515.60873900156 }, { "content": "pub trait Scene<C, T> {\n\n /// Called once on the scene when it is created, before any other hooks.\n\n fn load(&mut self, resources: &Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n\n\n /// Called before `update`/`draw` on a tick.\n\n fn pre_tick(&mut self, resources: &Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n\n\n /// A logical update w/ a fixed timestep. Called zero or more times per frame, depending on how\n\n /// much time has passed since the last logical timestep/update.\n\n ///\n\n /// The delta-time is provided in a [`Dt`](crate::types::Dt) entry in the resource map.\n\n fn update(&mut self, resources: &Resources, lua: &Lua, context: &mut C) -> Result<()>;\n\n\n\n /// If true, also update the scene \"below\" this on the scene stack. Default implementation\n\n /// returns `false`.\n\n fn update_previous(&self) -> bool {\n\n false\n\n }\n\n\n\n /// A render update. Always called once per tick.\n", "file_path": "altar/src/scene.rs", "rank": 66, "score": 144385.55887298062 }, { "content": "pub fn collect_wireframes<B>(\n\n context: SystemContext,\n\n wireframe_renderer: &mut WireframeRenderer<B>,\n\n dynamic_wireframes: &mut PreparedQuery<(\n\n Or<&DynamicWireframe, &StaticWireframe>,\n\n &Transform,\n\n Option<&Color>,\n\n )>,\n\n) where\n\n B: WireframeBackend,\n\n{\n\n for (_, (wireframe, transform, maybe_color)) in\n\n context.prepared_query(dynamic_wireframes).iter()\n\n {\n\n let instance = WireframeInstance {\n\n color: maybe_color\n\n .copied()\n\n .map(LinearColor::from)\n\n .unwrap_or(LinearColor::WHITE),\n\n tx: transform.tx,\n", "file_path": "altar/src/render/wireframe.rs", "rank": 67, "score": 143209.6761028787 }, { "content": "fn struct_fields(fields: &syn::Fields) -> (Vec<&syn::Type>, Vec<syn::Member>) {\n\n match fields {\n\n syn::Fields::Named(ref fields) => fields\n\n .named\n\n .iter()\n\n .map(|f| (&f.ty, syn::Member::Named(f.ident.clone().unwrap())))\n\n .unzip(),\n\n syn::Fields::Unnamed(ref fields) => fields\n\n .unnamed\n\n .iter()\n\n .enumerate()\n\n .map(|(i, f)| {\n\n (\n\n &f.ty,\n\n syn::Member::Unnamed(syn::Index {\n\n index: i as u32,\n\n span: Span::call_site(),\n\n }),\n\n )\n\n })\n\n .unzip(),\n\n syn::Fields::Unit => (Vec::new(), Vec::new()),\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 68, "score": 141096.6590041951 }, { "content": "fn ccursor_previous_word(text: &str, ccursor: CCursor) -> CCursor {\n\n let num_chars = text.chars().count();\n\n CCursor {\n\n index: num_chars\n\n - next_word_boundary_char_index(text.chars().rev(), num_chars - ccursor.index),\n\n prefer_next_row: true,\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 69, "score": 140293.36521510448 }, { "content": "fn select_word_at(text: &str, ccursor: CCursor) -> CCursorRange {\n\n if ccursor.index == 0 {\n\n CCursorRange::two(ccursor, ccursor_next_word(text, ccursor))\n\n } else {\n\n let it = text.chars();\n\n let mut it = it.skip(ccursor.index - 1);\n\n if let Some(char_before_cursor) = it.next() {\n\n if let Some(char_after_cursor) = it.next() {\n\n if is_word_char(char_before_cursor) && is_word_char(char_after_cursor) {\n\n let min = ccursor_previous_word(text, ccursor + 1);\n\n let max = ccursor_next_word(text, min);\n\n CCursorRange::two(min, max)\n\n } else if is_word_char(char_before_cursor) {\n\n let min = ccursor_previous_word(text, ccursor);\n\n let max = ccursor_next_word(text, min);\n\n CCursorRange::two(min, max)\n\n } else if is_word_char(char_after_cursor) {\n\n let max = ccursor_next_word(text, ccursor);\n\n CCursorRange::two(ccursor, max)\n\n } else {\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 70, "score": 140293.36521510448 }, { "content": "fn ccursor_next_word(text: &str, ccursor: CCursor) -> CCursor {\n\n CCursor {\n\n index: next_word_boundary_char_index(text.chars(), ccursor.index),\n\n prefer_next_row: false,\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 71, "score": 140293.36521510448 }, { "content": "fn to_egui_modifiers(mods: KeyMods) -> egui::Modifiers {\n\n egui::Modifiers {\n\n alt: mods.alt,\n\n ctrl: mods.ctrl,\n\n shift: mods.shift,\n\n mac_cmd: false,\n\n command: mods.cmd,\n\n }\n\n}\n", "file_path": "hv/crates/hv-gui/src/lib.rs", "rank": 72, "score": 137820.63597249612 }, { "content": "pub fn create_lua_context() -> Result<Lua> {\n\n Ok(Lua::new())\n\n}\n", "file_path": "altar/src/api.rs", "rank": 73, "score": 137473.66947408539 }, { "content": "/// Abstracts over non-blocking guarded mutable borrows from behind immutable references\n\n/// (for example, `RefCell::try_borrow_mut`.)\n\npub trait NonBlockingGuardedBorrowMut<T: ?Sized> {\n\n /// The guard type (for example, `std::cell::RefMut<'a, T>`.)\n\n type GuardMut<'a>: Deref<Target = T> + DerefMut\n\n where\n\n T: 'a,\n\n Self: 'a;\n\n /// The type returned in the case the value cannot be borrowed.\n\n type BorrowMutError<'a>\n\n where\n\n T: 'a,\n\n Self: 'a;\n\n\n\n /// Attempt to perform the borrow.\n\n fn try_nonblocking_guarded_borrow_mut(\n\n &self,\n\n ) -> Result<Self::GuardMut<'_>, Self::BorrowMutError<'_>>;\n\n}\n\n\n", "file_path": "hv/crates/hv-guarded-borrow/src/lib.rs", "rank": 74, "score": 136238.9087241897 }, { "content": "// Example components and/or resources.\n\nstruct Position(f32, f32);\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 75, "score": 131097.3139924748 }, { "content": "struct Acceleration(f32, f32);\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 76, "score": 131097.3139924748 }, { "content": "struct Velocity(f32, f32);\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 77, "score": 131097.3139924748 }, { "content": "/// Memoized Code highlighting\n\npub fn highlight(ctx: &egui::Context, theme: &CodeTheme, code: &str, language: &str) -> LayoutJob {\n\n impl egui::util::cache::ComputerMut<(&CodeTheme, &str, &str), LayoutJob> for Highlighter {\n\n fn compute(&mut self, (theme, code, lang): (&CodeTheme, &str, &str)) -> LayoutJob {\n\n self.highlight(theme, code, lang)\n\n }\n\n }\n\n\n\n type HighlightCache<'a> = egui::util::cache::FrameCache<LayoutJob, Highlighter>;\n\n\n\n let mut memory = ctx.memory();\n\n let highlight_cache = memory.caches.cache::<HighlightCache<'_>>();\n\n highlight_cache.get((theme, code, language))\n\n}\n\n\n", "file_path": "hv/crates/hv-console/src/widget/syntax_highlight.rs", "rank": 78, "score": 129635.301191543 }, { "content": "fn downcast_resource<T: Resource>(resource: Box<dyn Resource>) -> T {\n\n *resource\n\n .downcast::<T>()\n\n .unwrap_or_else(|_| panic!(\"downcasting resources should always succeed\"))\n\n}\n\n\n\nimpl Resources {\n\n /// Creates an empty container. Functionally identical to [`::default()`].\n\n ///\n\n /// [`default`]: #method.default\n\n pub fn new() -> Self {\n\n Self::default()\n\n }\n\n\n\n /// Returns `true` if a resource of type `T` exists in the container.\n\n pub fn contains<T: Resource>(&self) -> bool {\n\n self.resources.contains_key(&TypeId::of::<T>())\n\n }\n\n\n\n /// Inserts the given resource of type `T` into the container.\n", "file_path": "hv/crates/hv-resources/src/map.rs", "rank": 79, "score": 129422.04556139799 }, { "content": "fn main() {\n\n let mut world = World::new();\n\n let mut entities = 0u32;\n\n world.spawn_batch((0..100u32).map(|index| {\n\n entities += 1;\n\n (index,)\n\n }));\n\n world.spawn_batch((0..100u32).map(|index| {\n\n entities += 1;\n\n (index, index as f32)\n\n }));\n\n let mut increment = 5usize;\n\n let mut average = 0f32;\n\n let mut executor = Executor::<(u32, usize, f32)>::builder()\n\n .system_with_handle(\n\n |context, (entities, average): (&u32, &mut f32), &mut query: &mut QueryMarker<&f32>| {\n\n *average = 0.0;\n\n for (_entity, float) in context.query(query).iter() {\n\n *average += *float;\n\n }\n", "file_path": "hv/crates/hv-yaks/examples/crate_doc_example.rs", "rank": 80, "score": 122074.45538150377 }, { "content": "pub trait TiledBackend:\n\n TessBackend<Vertex, u16, (), Interleaved>\n\n + ShaderBackend\n\n + PipelineBackend<Dim2>\n\n + FramebufferBackend<Dim2>\n\n + RenderGateBackend\n\n + TessGateBackend<Vertex, u16, (), Interleaved>\n\n + TextureBackend<Dim2Array, SRGBA8UI>\n\n + PipelineTexture<Dim2Array, SRGBA8UI>\n\n + for<'a> VertexSlice<'a, Vertex, u16, (), Interleaved, Vertex>\n\n + for<'a> IndexSlice<'a, Vertex, u16, (), Interleaved>\n\n + for<'a> Uniformable<'a, Mat44<f32>, Target = Mat44<f32>>\n\n + for<'a> Uniformable<\n\n 'a,\n\n TextureBinding<Dim2Array, NormUnsigned>,\n\n Target = TextureBinding<Dim2Array, NormUnsigned>,\n\n >\n\n{\n\n}\n\n\n", "file_path": "altar/src/render/terracotta.rs", "rank": 81, "score": 120733.97069937695 }, { "content": " function types.number(x, visited, accum) accum[#accum + 1] = number_to_str(x) end\n\n\n", "file_path": "hv/crates/hv-script/resources/binser.lua", "rank": 82, "score": 120068.52231731109 }, { "content": "// no reason to generate a static for unit structs\n\nfn gen_unit_struct_bundle_impl(ident: syn::Ident, generics: &syn::Generics) -> TokenStream2 {\n\n let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();\n\n quote! {\n\n unsafe impl #impl_generics ::hv::ecs::Bundle for #ident #ty_generics #where_clause {\n\n #[allow(non_camel_case_types)]\n\n fn with_static_ids<__hv::ecs__T>(f: impl ::std::ops::FnOnce(&[::std::any::TypeId]) -> __hv::ecs__T) -> __hv::ecs__T { f(&[]) }\n\n fn static_type_info() -> ::std::vec::Vec<::hv::ecs::TypeInfo> { ::std::vec::Vec::new() }\n\n\n\n unsafe fn get(\n\n mut f: impl ::std::ops::FnMut(::hv::ecs::TypeInfo) -> ::std::option::Option<::std::ptr::NonNull<u8>>,\n\n ) -> ::std::result::Result<Self, ::hv::ecs::MissingComponent> {\n\n ::std::result::Result::Ok(Self {/* for some reason this works for all unit struct variations */})\n\n }\n\n }\n\n }\n\n}\n\n\n", "file_path": "hv/crates/hv-ecs-derive/src/bundle.rs", "rank": 83, "score": 120059.80265693807 }, { "content": "#[allow(clippy::type_complexity)]\n\nfn system_with_two_queries(\n\n context: hv_yaks::SystemContext,\n\n (entities, average): (&u32, &f32),\n\n &mut (with_f32, without_f32): &mut (\n\n QueryMarker<With<f32, &mut u32>>,\n\n QueryMarker<Without<f32, &mut u32>>,\n\n ),\n\n) {\n\n hv_yaks::batch(\n\n &mut context.query(with_f32),\n\n entities / 8,\n\n |_entity, unsigned| {\n\n *unsigned += average.round() as u32;\n\n },\n\n );\n\n hv_yaks::batch(\n\n &mut context.query(without_f32),\n\n entities / 8,\n\n |_entity, unsigned| {\n\n *unsigned *= average.round() as u32;\n\n },\n\n );\n\n}\n", "file_path": "hv/crates/hv-yaks/examples/crate_doc_example.rs", "rank": 84, "score": 119050.39342691042 }, { "content": " function types.boolean(x, visited, accum) accum[#accum + 1] = x and \"\\204\" or \"\\205\" end\n\n\n", "file_path": "hv/crates/hv-script/resources/binser.lua", "rank": 85, "score": 117564.68561025313 }, { "content": "#[allow(clippy::type_complexity)]\n\nfn motion(\n\n // Thin wrapper over `&hv_ecs::World`.\n\n context: SystemContext,\n\n // A resource this system requires. Can be a single one, or any tuple up to 16.\n\n spawned: &SpawnedEntities,\n\n // Queries this system will execute. Can be a single one, or any tuple up to 16.\n\n &mut (no_acceleration, with_acceleration): &mut (\n\n // `QueryMarker` is a zero-sized type that can be fed into methods of `SystemContext`.\n\n QueryMarker<hv_ecs::Without<Acceleration, (&mut Position, &Velocity)>>,\n\n QueryMarker<(&mut Position, &mut Velocity, &Acceleration)>,\n\n ),\n\n) {\n\n // A helper function that automatically spreads the batches across threads of a\n\n // `rayon::ThreadPool` - either the global one if called standalone, or a specific one\n\n // when used with a `rayon::ThreadPool::install()`.\n\n hv_yaks::batch(\n\n &mut context.query(no_acceleration),\n\n spawned.batch_size_no_acceleration(),\n\n |_entity, (mut pos, vel)| {\n\n pos.0 += vel.0;\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 86, "score": 115946.18137885998 }, { "content": "#[test]\n\nfn remove() {\n\n let mut resources = Resources::new();\n\n resources.insert(One(0));\n\n\n\n resources.get_mut::<One>().unwrap().0 = 1;\n\n\n\n assert_eq!(resources.remove::<One>().unwrap(), One(1));\n\n assert!(resources.remove::<One>().is_none());\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 87, "score": 115940.85742224916 }, { "content": "fn main() {\n\n // Trying to parse a passed argument, if any.\n\n let to_spawn: u32 = std::env::args()\n\n .nth(1)\n\n .ok_or(())\n\n .and_then(|arg| arg.parse::<u32>().map_err(|_| ()))\n\n .unwrap_or(100_000);\n\n // Initializing resources.\n\n let mut rng = StdRng::from_entropy();\n\n let mut world = World::new();\n\n let mut average_color = Color(0.0, 0.0, 0.0, 0.0);\n\n let mut highest_velocity = Velocity(0.0, 0.0);\n\n let mut spawned = SpawnedEntities {\n\n no_acceleration: 0,\n\n with_acceleration: 0,\n\n };\n\n\n\n // Spawning entities.\n\n world.spawn_batch((0..(to_spawn / 2)).map(|_| {\n\n spawned.no_acceleration += 1;\n", "file_path": "hv/crates/hv-yaks/examples/convoluted.rs", "rank": 88, "score": 115940.85742224916 }, { "content": "#[test]\n\nfn insert() {\n\n let mut resources = Resources::new();\n\n assert!(resources.insert(One(1)).is_none());\n\n assert!(resources.insert(Two(2)).is_none());\n\n assert_eq!(resources.insert(One(5)), Some(One(1)));\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 89, "score": 115940.85742224916 }, { "content": "struct C(usize);\n\n\n", "file_path": "hv/crates/hv-yaks/tests/executor.rs", "rank": 90, "score": 114966.54711379873 }, { "content": "#[allow(clippy::too_many_arguments)]\n\nfn events(\n\n ui: &mut egui::Ui,\n\n state: &mut ConsoleState,\n\n history: &mut dyn TextBuffer,\n\n history_index: &mut usize,\n\n buffer: &mut dyn TextBuffer,\n\n history_galley: &mut Arc<Galley>,\n\n buffer_galley: &mut Arc<Galley>,\n\n layouter: &mut dyn FnMut(&Ui, &str, f32) -> Arc<Galley>,\n\n focus_id: Id,\n\n wrap_width: f32,\n\n default_cursor_range: Section<CursorRange>,\n\n) -> (bool, Option<String>, Section<CursorRange>) {\n\n let mut cursor_range = state\n\n .cursor_range(&*history_galley, &*buffer_galley)\n\n .unwrap_or(default_cursor_range);\n\n\n\n // We feed state to the undoer both before and after handling input\n\n // so that the undoer creates automatic saves even when there are no events for a while.\n\n state.undoer.lock().feed_state(\n", "file_path": "hv/crates/hv-console/src/widget/builder.rs", "rank": 91, "score": 114092.05128689884 }, { "content": "#[test]\n\n#[should_panic(expected = \"system 1 depends on itself\")]\n\nfn self_dependency() {\n\n Executor::<()>::builder()\n\n .system_with_handle(dummy_system, 0)\n\n .system_with_handle_and_deps(dummy_system, 1, vec![1])\n\n .build();\n\n}\n", "file_path": "hv/crates/hv-yaks/tests/builder.rs", "rank": 92, "score": 114091.97643997917 }, { "content": "#[test]\n\n#[should_panic(expected = \"system 0 already exists\")]\n\nfn duplicate_handle() {\n\n Executor::<()>::builder()\n\n .system_with_handle(dummy_system, 0)\n\n .system_with_handle(dummy_system, 0)\n\n .build();\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/tests/builder.rs", "rank": 93, "score": 114091.92504928578 }, { "content": "#[test]\n\n#[should_panic(expected = \"could not resolve dependencies of system 1: no system 2 found\")]\n\nfn invalid_dependency() {\n\n Executor::<()>::builder()\n\n .system_with_handle(dummy_system, 0)\n\n .system_with_handle_and_deps(dummy_system, 1, vec![2])\n\n .build();\n\n}\n\n\n\n#[test]\n\n#[should_panic(\n\n expected = \"could not resolve dependencies of a handle-less system: no system 1 found\"\n\n)]\n", "file_path": "hv/crates/hv-yaks/tests/builder.rs", "rank": 94, "score": 114091.8251745972 }, { "content": "#[test]\n\nfn orthogonal_borrow() {\n\n let mut resources = Resources::new();\n\n resources.insert(One(0));\n\n resources.insert(Two(0));\n\n let resources = resources;\n\n\n\n {\n\n let mut ref1 = resources.get_mut::<One>().unwrap();\n\n let mut ref2 = resources.get_mut::<Two>().unwrap();\n\n\n\n ref1.0 += 1;\n\n ref2.0 += 2;\n\n }\n\n\n\n let ref1 = resources.get::<One>().unwrap();\n\n let ref2 = resources.get::<Two>().unwrap();\n\n\n\n assert_eq!(ref1.0, 1);\n\n assert_eq!(ref2.0, 2);\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 95, "score": 114086.62766806045 }, { "content": "#[test]\n\nfn systems_single() {\n\n let world = World::new();\n\n let mut a = A(0);\n\n let mut b = B(1);\n\n let mut c = C(2);\n\n let mut executor = Executor::<(A, B, C)>::builder()\n\n .system(|_, (a, b, c): (&mut A, &B, &C), _: &mut ()| {\n\n a.0 = b.0 + c.0;\n\n })\n\n .build();\n\n executor.run(&world, (&mut a, &mut b, &mut c));\n\n assert_eq!(a.0, 3);\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/tests/executor.rs", "rank": 96, "score": 114086.62766806045 }, { "content": "#[test]\n\nfn smoke_test() {\n\n let world = hv_ecs::World::new();\n\n\n\n fn dummy_system(_: SystemContext, _: (), _: &mut ()) {}\n\n dummy_system.run(&world, ());\n\n\n\n let mut counter = 0i32;\n\n fn increment_system(_: SystemContext, value: &mut i32, _: &mut ()) {\n\n *value += 1;\n\n }\n\n increment_system.run(&world, &mut counter);\n\n assert_eq!(counter, 1);\n\n\n\n let increment = 3usize;\n\n fn sum_system(_: SystemContext, (a, b): (&mut i32, &usize), _: &mut ()) {\n\n *a += *b as i32;\n\n }\n\n sum_system.run(&world, (&mut counter, &increment));\n\n assert_eq!(counter, 4);\n\n sum_system.run(&world, (&mut counter, &increment));\n\n assert_eq!(counter, 7);\n\n}\n", "file_path": "hv/crates/hv-yaks/src/run.rs", "rank": 97, "score": 114086.62766806045 }, { "content": "#[test]\n\nfn systems_two() {\n\n let world = World::new();\n\n let mut a = A(0);\n\n let mut b = B(1);\n\n let mut c = C(2);\n\n let mut executor = Executor::<(A, B, C)>::builder()\n\n .system(|_, (a, b): (&mut A, &B), _: &mut ()| {\n\n a.0 += b.0;\n\n })\n\n .system(|_, (a, c): (&mut A, &C), _: &mut ()| {\n\n a.0 += c.0;\n\n })\n\n .build();\n\n executor.run(&world, (&mut a, &mut b, &mut c));\n\n assert_eq!(a.0, 3);\n\n}\n\n\n", "file_path": "hv/crates/hv-yaks/tests/executor.rs", "rank": 98, "score": 114086.62766806045 }, { "content": "#[test]\n\nfn multiple_borrow() {\n\n let mut resources = Resources::new();\n\n resources.insert(One(1));\n\n let resources = resources;\n\n\n\n let ref1 = resources.get::<One>().unwrap();\n\n let ref2 = resources.get::<One>().unwrap();\n\n\n\n assert_eq!(*ref1, *ref2)\n\n}\n\n\n", "file_path": "hv/crates/hv-resources/tests/tests.rs", "rank": 99, "score": 114086.62766806045 } ]
Rust
src/sql/src/plan/scope.rs
jtcohen6/materialize
88815e32ea26a5ee3abf04c2bbb49ee27ace22d4
use itertools::Itertools; use repr::ColumnName; use crate::names::PartialName; use crate::plan::error::PlanError; use crate::plan::expr::ColumnRef; use sql_parser::ast::Raw; #[derive(Debug, Clone, PartialEq)] pub struct ScopeItemName { pub table_name: Option<PartialName>, pub column_name: Option<ColumnName>, pub priority: bool, } #[derive(Debug, Clone, PartialEq)] pub struct ScopeItem { pub names: Vec<ScopeItemName>, pub expr: Option<sql_parser::ast::Expr<Raw>>, pub nameable: bool, } #[derive(Debug, Clone, PartialEq)] pub struct Scope { pub items: Vec<ScopeItem>, pub outer_scope: Option<Box<Scope>>, } impl ScopeItem { pub fn from_column_name(column_name: Option<ColumnName>) -> Self { ScopeItem { names: vec![ScopeItemName { table_name: None, column_name, priority: false, }], expr: None, nameable: true, } } pub fn is_from_table(&self, table_name: &PartialName) -> bool { self.names.iter().find_map(|n| n.table_name.as_ref()) == Some(table_name) } pub fn short_display_name(&self) -> String { match self.names.get(0) { None => "?".into(), Some(name) => { let column_name = match &name.column_name { None => "?column?", Some(column_name) => column_name.as_str(), }; match &name.table_name { None => column_name.into(), Some(table_name) => format!("{}.{}", table_name.item, column_name), } } } } } impl Scope { pub fn empty(outer_scope: Option<Scope>) -> Self { Scope { items: vec![], outer_scope: outer_scope.map(Box::new), } } pub fn from_source<I, N>( table_name: Option<PartialName>, column_names: I, outer_scope: Option<Scope>, ) -> Self where I: IntoIterator<Item = Option<N>>, N: Into<ColumnName>, { let mut scope = Scope::empty(outer_scope); scope.items = column_names .into_iter() .map(|column_name| ScopeItem { names: vec![ScopeItemName { table_name: table_name.clone(), column_name: column_name.map(|n| n.into()), priority: false, }], expr: None, nameable: true, }) .collect(); scope } pub fn column_names(&self) -> impl Iterator<Item = Option<&ColumnName>> { self.items.iter().map(|item| { item.names .iter() .filter_map(|n| n.column_name.as_ref()) .next() }) } pub fn len(&self) -> usize { self.items.len() } pub fn all_items(&self) -> Vec<(usize, usize, &ScopeItem)> { let mut items = vec![]; let mut level = 0; let mut scope = self; loop { for (column, item) in scope.items.iter().enumerate() { items.push((level, column, item)); } if let Some(outer_scope) = &scope.outer_scope { scope = outer_scope; level += 1; } else { break; } } items } fn resolve<'a, Matches>( &'a self, matches: Matches, name_in_error: &str, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> where Matches: Fn(&ScopeItemName) -> bool, { let mut results = self .all_items() .into_iter() .flat_map(|(level, column, item)| { item.names .iter() .map(move |name| (level, column, item, name)) }) .filter(|(_level, _column, item, name)| (matches)(name) && item.nameable) .sorted_by_key(|(level, _column, _item, name)| (*level, !name.priority)); match results.next() { None => Err(PlanError::UnknownColumn(name_in_error.to_owned())), Some((level, column, _item, name)) => { if results .find(|(level2, column2, item, name2)| { column != *column2 && level == *level2 && item.nameable && name.priority == name2.priority }) .is_none() { Ok((ColumnRef { level, column }, name)) } else { Err(PlanError::AmbiguousColumn(name_in_error.to_owned())) } } } } pub fn resolve_column<'a>( &'a self, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| item.column_name.as_ref() == Some(column_name), column_name.as_str(), ) } pub fn resolve_table_column<'a>( &'a self, table_name: &PartialName, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| { item.table_name.as_ref() == Some(table_name) && item.column_name.as_ref() == Some(column_name) }, &format!("{}.{}", table_name, column_name), ) } pub fn resolve_expr<'a>(&'a self, expr: &sql_parser::ast::Expr<Raw>) -> Option<ColumnRef> { self.items .iter() .enumerate() .find(|(_, item)| item.expr.as_ref() == Some(expr)) .map(|(i, _)| ColumnRef { level: 0, column: i, }) } pub fn product(self, right: Self) -> Self { Scope { items: self .items .into_iter() .chain(right.items.into_iter()) .collect(), outer_scope: self.outer_scope, } } pub fn project(&self, columns: &[usize]) -> Self { Scope { items: columns.iter().map(|&i| self.items[i].clone()).collect(), outer_scope: self.outer_scope.clone(), } } }
use itertools::Itertools; use repr::ColumnName; use crate::names::PartialName; use crate::plan::error::PlanError; use crate::plan::expr::ColumnRef; use sql_parser::ast::Raw; #[derive(Debug, Clone, PartialEq)] pub struct ScopeItemName { pub table_name: Option<PartialName>, pub column_name: Option<ColumnName>, pub priority: bool, } #[derive(Debug, Clone, PartialEq)] pub struct ScopeItem { pub names: Vec<ScopeItemName>, pub expr: Option<sql_parser::ast::Expr<Raw>>, pub nameable: bool, } #[derive(Debug, Clone, PartialEq)] pub struct Scope { pub items: Vec<ScopeItem>, pub outer_scope: Option<Box<Scope>>, } impl ScopeItem { pub fn from_column_name(column_name: Option<ColumnName>) -> Self { ScopeItem { names: vec![ScopeItemName { table_name: None, column_name, priority: false, }], expr: None, nameable: true, } } pub fn is_from_table(&self, table_name: &PartialName) -> bool { self.names.iter().find_map(|n| n.table_name.as_ref()) == Some(table_name) } pub fn short_display_name(&self) -> String { match self.names.get(0) { None => "?".into(), Some(name) => { let column_name = match &name.column_name { None => "?column?", Some(column_name) => column_name.as_str(), }; match &name.table_name { None => column_name.into(), Some(table_name) => format!("{}.{}", table_name.item, column_name), } } } } } impl Scope { pub fn empty(outer_scope: Option<Scope>) -> Self { Scope { items: vec![], outer_scope: outer_scope.map(Box::new), } } pub fn from_source<I, N>( table_name: Option<PartialName>, column_names: I, outer_scope: Option<Scope>, ) -> Self where I: IntoIterator<Item = Option<N>>, N: Into<ColumnName>, { let mut scope = Scope::empty(outer_scope); scope.items = column_names .into_iter() .map(|column_name| ScopeItem { names: vec![ScopeItemName { table_name: table_name.clone(), column_name: column_name.map(|n| n.into()), priority: false, }], expr: None, nameable: true, }) .collect(); scope } pub fn column_names(&self) -> impl Iterator<Item = Option<&ColumnName>> { self.items.iter().map(|item| { item.names .iter() .filter_map(|n| n.column_name.as_ref()) .next() }) } pub fn len(&self) -> usize { self.items.len() } pub fn all_items(&self) -> Vec<(usize, usize, &ScopeItem)> { let mut items = vec![]; let mut level = 0; let mut scope = self; loop { for (column, item) in scope.items.iter().enumerate() { items.push((level, column, item)); } if let Some(outer_scope) = &scope.outer_scope { scope = outer_scope; level += 1; } else { break; } } items } fn resolve<'a, Matches>( &'a self, matches: Matches, name_in_error: &str, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> where Matches: Fn(&ScopeItemName) -> bool, { let mut results = self .all_items() .into_iter() .flat_map(|(level, column, item)| { item.names .iter() .map(move |name| (level, column, item, name)) }) .filter(|(_level, _column, item, name)| (matches)(name) && item.nameable) .sorted_by_key(|(level, _column, _item, name)| (*level, !name.priority)); match results.next() { None => Err(PlanError::UnknownColumn(name_in_error.to_owned())), Some((level, column, _item, name)) => { if results .find(|(level2, column2, item, name2)| { column != *column2 && level == *level2 && item.nameable && name.priority == name2.priority }) .is_none() { Ok((ColumnRef { level, column }, name)) } else { Err(PlanError::AmbiguousColumn(name_in_error.to_owned())) } } } }
pub fn resolve_table_column<'a>( &'a self, table_name: &PartialName, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| { item.table_name.as_ref() == Some(table_name) && item.column_name.as_ref() == Some(column_name) }, &format!("{}.{}", table_name, column_name), ) } pub fn resolve_expr<'a>(&'a self, expr: &sql_parser::ast::Expr<Raw>) -> Option<ColumnRef> { self.items .iter() .enumerate() .find(|(_, item)| item.expr.as_ref() == Some(expr)) .map(|(i, _)| ColumnRef { level: 0, column: i, }) } pub fn product(self, right: Self) -> Self { Scope { items: self .items .into_iter() .chain(right.items.into_iter()) .collect(), outer_scope: self.outer_scope, } } pub fn project(&self, columns: &[usize]) -> Self { Scope { items: columns.iter().map(|&i| self.items[i].clone()).collect(), outer_scope: self.outer_scope.clone(), } } }
pub fn resolve_column<'a>( &'a self, column_name: &ColumnName, ) -> Result<(ColumnRef, &'a ScopeItemName), PlanError> { self.resolve( |item: &ScopeItemName| item.column_name.as_ref() == Some(column_name), column_name.as_str(), ) }
function_block-full_function
[ { "content": "fn pad_formats(formats: Vec<pgrepr::Format>, n: usize) -> Result<Vec<pgrepr::Format>, String> {\n\n match (formats.len(), n) {\n\n (0, e) => Ok(vec![pgrepr::Format::Text; e]),\n\n (1, e) => Ok(iter::repeat(formats[0]).take(e).collect()),\n\n (a, e) if a == e => Ok(formats),\n\n (a, e) => Err(format!(\n\n \"expected {} field format specifiers, but got {}\",\n\n e, a\n\n )),\n\n }\n\n}\n\n\n", "file_path": "src/pgwire/src/protocol.rs", "rank": 0, "score": 517032.58995500166 }, { "content": "/// Merges streams together, yielding items as they become available.\n\n///\n\n/// Like [`stream::select_all`], except that ready items from earlier streams\n\n/// are preferred to later streams. For example, all ready items from the first\n\n/// stream in `streams` will be yielded before moving on to the second stream in\n\n/// `streams. This can cause starvation, so use with care.\n\npub fn select_all_biased<S>(mut streams: Vec<S>) -> impl Stream<Item = S::Item>\n\nwhere\n\n S: Stream + Unpin,\n\n{\n\n stream::poll_fn(move |cx| {\n\n let mut i = 0;\n\n while i < streams.len() {\n\n match streams[i].poll_next_unpin(cx) {\n\n Poll::Ready(Some(v)) => return Poll::Ready(Some(v)),\n\n Poll::Ready(None) => {\n\n streams.remove(i);\n\n }\n\n Poll::Pending => i += 1,\n\n }\n\n }\n\n if streams.is_empty() {\n\n Poll::Ready(None)\n\n } else {\n\n Poll::Pending\n\n }\n", "file_path": "src/ore/src/future.rs", "rank": 1, "score": 471795.6979846038 }, { "content": "/// Unescapes a testdrive byte string.\n\n///\n\n/// The escape character is `\\` and the only interesting escape sequence is\n\n/// `\\xNN`, where each `N` is a valid hexadecimal digit. All other characters\n\n/// following a backslash are taken literally.\n\npub fn unescape(s: &[u8]) -> Result<Vec<u8>, String> {\n\n let mut out = vec![];\n\n let mut s = s.iter().copied().fuse();\n\n while let Some(b) = s.next() {\n\n match b {\n\n b'\\\\' if s.next() == Some(b'x') => match (next_hex(&mut s), next_hex(&mut s)) {\n\n (Some(c1), Some(c0)) => out.push((c1 << 4) + c0),\n\n _ => return Err(\"invalid hexadecimal escape\".into()),\n\n },\n\n b'\\\\' => continue,\n\n _ => out.push(b),\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/testdrive/src/format/bytes.rs", "rank": 2, "score": 465476.0083034481 }, { "content": "pub fn object_name(mut name: ObjectName) -> Result<PartialName, PlanError> {\n\n if name.0.len() < 1 || name.0.len() > 3 {\n\n return Err(PlanError::MisqualifiedName(name.to_string()));\n\n }\n\n let out = PartialName {\n\n item: ident(\n\n name.0\n\n .pop()\n\n .expect(\"name checked to have at least one component\"),\n\n ),\n\n schema: name.0.pop().map(ident),\n\n database: name.0.pop().map(ident),\n\n };\n\n assert!(name.0.is_empty());\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/sql/src/normalize.rs", "rank": 3, "score": 460542.5818744515 }, { "content": "fn parse_line(line: &str) -> Result<Vec<(String, Option<String>)>, String> {\n\n let mut results = Vec::new();\n\n if let Some(remainder) = line.strip_prefix(\"data: \") {\n\n let mut parsed_json = json::parse(remainder);\n\n if let Ok(parsed_json) = &mut parsed_json {\n\n if parsed_json.is_array() {\n\n for member in parsed_json.members_mut() {\n\n results.push(parse_entry(member))\n\n }\n\n } else {\n\n results.push(parse_entry(parsed_json))\n\n }\n\n } else {\n\n return Err(format!(\"broken line: {}\", line));\n\n }\n\n }\n\n Ok(results)\n\n}\n\n\n", "file_path": "play/mbta/src/main.rs", "rank": 4, "score": 442168.05961806886 }, { "content": "fn split_line(pos: usize, line: &str) -> Result<Vec<String>, InputError> {\n\n let mut out = Vec::new();\n\n let mut field = String::new();\n\n let mut in_quotes = None;\n\n let mut escaping = false;\n\n for (i, c) in line.char_indices() {\n\n if in_quotes.is_none() && c.is_whitespace() {\n\n if !field.is_empty() {\n\n out.push(field);\n\n field = String::new();\n\n }\n\n } else if c == '\"' && !escaping {\n\n if in_quotes.is_none() {\n\n in_quotes = Some(i)\n\n } else {\n\n in_quotes = None;\n\n out.push(field);\n\n field = String::new();\n\n }\n\n } else if c == '\\\\' && !escaping && in_quotes.is_some() {\n", "file_path": "src/testdrive/src/parser.rs", "rank": 5, "score": 442156.029477653 }, { "content": "pub fn indent(s: &str, n: usize) -> String {\n\n let space = \" \".repeat(n);\n\n let s = s.replace(\"\\n\", &format!(\"\\n{}\", space));\n\n space + &s\n\n}\n", "file_path": "src/sqllogictest/src/util.rs", "rank": 6, "score": 441502.15080569923 }, { "content": "/// Lexes a SQL query.\n\n///\n\n/// Returns a list of tokens alongside their corresponding byte offset in the\n\n/// input string. Returns an error if the SQL query is lexically invalid.\n\n///\n\n/// See the module documentation for more information about the lexical\n\n/// structure of SQL.\n\npub fn lex(query: &str) -> Result<Vec<(Token, usize)>, ParserError> {\n\n let buf = &mut LexBuf::new(query);\n\n let mut tokens = vec![];\n\n while let Some(ch) = buf.next() {\n\n let pos = buf.pos() - ch.len_utf8();\n\n let token = match ch {\n\n _ if ch.is_ascii_whitespace() => continue,\n\n '-' if buf.consume('-') => {\n\n lex_line_comment(buf);\n\n continue;\n\n }\n\n '/' if buf.consume('*') => {\n\n lex_multiline_comment(buf)?;\n\n continue;\n\n }\n\n '\\'' => Token::String(lex_string(buf)?),\n\n 'x' | 'X' if buf.consume('\\'') => Token::HexString(lex_string(buf)?),\n\n 'e' | 'E' if buf.consume('\\'') => lex_extended_string(buf)?,\n\n 'A'..='Z' | 'a'..='z' | '_' | '\\u{80}'..=char::MAX => lex_ident(buf),\n\n '\"' => lex_quoted_ident(buf)?,\n", "file_path": "src/sql-parser/src/lexer.rs", "rank": 7, "score": 441249.7241389956 }, { "content": "/// Parses a [`bool`] from `s`.\n\n///\n\n/// The accepted values are \"true\", \"false\", \"yes\", \"no\", \"on\", \"off\", \"1\", and\n\n/// \"0\", or any unambiguous prefix of one of those values. Leading or trailing\n\n/// whitespace is permissible.\n\npub fn parse_bool(s: &str) -> Result<bool, ParseError> {\n\n match s.trim().to_lowercase().as_str() {\n\n \"t\" | \"tr\" | \"tru\" | \"true\" | \"y\" | \"ye\" | \"yes\" | \"on\" | \"1\" => Ok(true),\n\n \"f\" | \"fa\" | \"fal\" | \"fals\" | \"false\" | \"n\" | \"no\" | \"of\" | \"off\" | \"0\" => Ok(false),\n\n _ => Err(ParseError::new(\"boolean\", s)),\n\n }\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 8, "score": 439045.85478888184 }, { "content": "/// Creates a type whose [`fmt::Display`] implementation outputs each item in\n\n/// `iter` separated by `separator`.\n\npub fn separated<'a, I>(separator: &'a str, iter: I) -> impl fmt::Display + 'a\n\nwhere\n\n I: IntoIterator,\n\n I::IntoIter: Clone + 'a,\n\n I::Item: fmt::Display + 'a,\n\n{\n\n struct Separated<'a, I> {\n\n separator: &'a str,\n\n iter: I,\n\n }\n\n\n\n impl<'a, I> fmt::Display for Separated<'a, I>\n\n where\n\n I: Iterator + Clone,\n\n I::Item: fmt::Display,\n\n {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n for (i, item) in self.iter.clone().enumerate() {\n\n if i != 0 {\n\n write!(f, \"{}\", self.separator)?;\n", "file_path": "src/expr/src/explain.rs", "rank": 9, "score": 435568.39528030244 }, { "content": "fn tokenize_timezone(value: &str) -> Result<Vec<TimeStrToken>, String> {\n\n let mut toks: Vec<TimeStrToken> = vec![];\n\n let mut num_buf = String::with_capacity(4);\n\n // If the timezone string has a colon, we need to parse all numbers naively.\n\n // Otherwise we need to parse long sequences of digits as [..hhhhmm]\n\n let split_nums: bool = !value.contains(':');\n\n\n\n // Takes a string and tries to parse it as a number token and insert it into\n\n // the token list\n\n fn parse_num(\n\n toks: &mut Vec<TimeStrToken>,\n\n n: &str,\n\n split_nums: bool,\n\n idx: usize,\n\n ) -> Result<(), String> {\n\n if n.is_empty() {\n\n return Ok(());\n\n }\n\n\n\n let (first, second) = if n.len() > 2 && split_nums {\n", "file_path": "src/repr/src/adt/datetime.rs", "rank": 10, "score": 425835.13498251303 }, { "content": "fn write_fn_name(out: &mut String, s: &str) {\n\n // Simplify associated type names so that e.g. `T::FooBar` becomes\n\n // `visit_foo_bar`.\n\n let s = s.splitn(2, \"::\").last().unwrap();\n\n for c in s.chars() {\n\n if c.is_ascii_uppercase() {\n\n out.push('_');\n\n out.push(c.to_ascii_lowercase());\n\n } else {\n\n out.push(c);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/walkabout/src/gen.rs", "rank": 11, "score": 419683.06801930495 }, { "content": "pub fn format_string<F>(buf: &mut F, s: &str) -> Nestable\n\nwhere\n\n F: FormatBuffer,\n\n{\n\n buf.write_str(s);\n\n Nestable::MayNeedEscaping\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 12, "score": 418429.54213566415 }, { "content": "/// Parses a SQL string containing one SQL expression.\n\npub fn parse_expr(sql: &str) -> Result<Expr<Raw>, ParserError> {\n\n let tokens = lexer::lex(sql)?;\n\n let mut parser = Parser::new(sql, tokens);\n\n let expr = parser.parse_expr()?;\n\n if parser.next_token().is_some() {\n\n parser_err!(\n\n parser,\n\n parser.peek_prev_pos(),\n\n \"extra token after expression\"\n\n )\n\n } else {\n\n Ok(expr)\n\n }\n\n}\n\n\n\nmacro_rules! maybe {\n\n ($e:expr) => {{\n\n if let Some(v) = $e {\n\n return Ok(v);\n\n }\n\n }};\n\n}\n\n\n", "file_path": "src/sql-parser/src/parser.rs", "rank": 13, "score": 416677.6229342224 }, { "content": "/// Like `format_bool`, but returns a string with a static lifetime.\n\n///\n\n/// This function should be preferred to `format_bool` when applicable, as it\n\n/// avoids an allocation.\n\npub fn format_bool_static(b: bool) -> &'static str {\n\n match b {\n\n true => \"t\",\n\n false => \"f\",\n\n }\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 14, "score": 414106.4766514744 }, { "content": "fn check_col_index(name: &str, e: &Expr<Raw>, max: usize) -> Result<Option<usize>, anyhow::Error> {\n\n match e {\n\n Expr::Value(Value::Number(n)) => {\n\n let n = n\n\n .parse::<usize>()\n\n .with_context(|| anyhow!(\"unable to parse column reference in {}: {}\", name, n))?;\n\n if n < 1 || n > max {\n\n bail!(\n\n \"column reference {} in {} is out of range (1 - {})\",\n\n n,\n\n name,\n\n max\n\n );\n\n }\n\n Ok(Some(n - 1))\n\n }\n\n _ => Ok(None),\n\n }\n\n}\n\n\n", "file_path": "src/sql/src/plan/query.rs", "rank": 15, "score": 413727.8319885207 }, { "content": "fn collect_items<P>(path: P, out: &mut Vec<DeriveInput>) -> Result<()>\n\nwhere\n\n P: AsRef<Path>,\n\n{\n\n let path = path.as_ref();\n\n let dir = path.parent().expect(\"missing parent directory\");\n\n let stem = path\n\n .file_stem()\n\n .expect(\"missing file stem\")\n\n .to_str()\n\n .expect(\"file stem is not valid UTF-8\");\n\n\n\n let src =\n\n fs::read_to_string(path).with_context(|| format!(\"Failed to read {}\", path.display()))?;\n\n let file =\n\n syn::parse_file(&src).with_context(|| format!(\"Failed to parse {}\", path.display()))?;\n\n\n\n for item in file.items {\n\n match item {\n\n Item::Mod(item) if item.content.is_none() => {\n", "file_path": "src/walkabout/src/parse.rs", "rank": 16, "score": 413289.1296568526 }, { "content": "pub fn parse_bytes(s: &str) -> Result<Vec<u8>, ParseError> {\n\n // If the input starts with \"\\x\", then the remaining bytes are hex encoded\n\n // [0]. Otherwise the bytes use the traditional \"escape\" format. [1]\n\n //\n\n // [0]: https://www.postgresql.org/docs/current/datatype-binary.html#id-1.5.7.12.9\n\n // [1]: https://www.postgresql.org/docs/current/datatype-binary.html#id-1.5.7.12.10\n\n if let Some(remainder) = s.strip_prefix(r\"\\x\") {\n\n hex::decode(remainder).map_err(|e| ParseError::new(\"bytea\", s).with_details(e))\n\n } else {\n\n parse_bytes_traditional(s)\n\n }\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 17, "score": 411692.6547795861 }, { "content": "fn any_matches(haystack: &[String], needle: &str) -> bool {\n\n haystack.iter().any(|s| s.contains(needle))\n\n}\n", "file_path": "demo/billing/src/main.rs", "rank": 18, "score": 406403.9755264673 }, { "content": "/// Replaces column references that occur once with the referenced expression.\n\n///\n\n/// This method in-lines expressions that are only referenced once, and then\n\n/// collects expressions that are no longer referenced, updating column indexes.\n\nfn inline_single_use(exprs: &mut Vec<MirScalarExpr>, projection: &mut [usize], input_arity: usize) {\n\n // Determine which columns are referred to by which others.\n\n let mut referenced = vec![0; input_arity + exprs.len()];\n\n for column in projection.iter() {\n\n referenced[*column] += 1;\n\n }\n\n for expr in exprs.iter() {\n\n expr.visit(&mut |e| {\n\n if let MirScalarExpr::Column(i) = e {\n\n referenced[*i] += 1;\n\n }\n\n })\n\n }\n\n\n\n // Any column with a single reference should be in-lined in\n\n // to its referrer. This process does not change the number\n\n // of references to a column, other than from one to zero,\n\n // and should be tractable with a single linear pass.\n\n for index in 0..exprs.len() {\n\n let (prior, expr) = exprs.split_at_mut(index);\n", "file_path": "src/transform/src/cse/map.rs", "rank": 19, "score": 403479.2064146872 }, { "content": "/// Changes the `name` used in an item's `CREATE` statement. To complete a\n\n/// rename operation, you must also call `create_stmt_rename_refs` on all dependent\n\n/// items.\n\npub fn create_stmt_rename(create_stmt: &mut Statement<Raw>, to_item_name: String) {\n\n // TODO(sploiselle): Support renaming schemas and databases.\n\n match create_stmt {\n\n Statement::CreateIndex(CreateIndexStatement { name, .. }) => {\n\n *name = Some(Ident::new(to_item_name));\n\n }\n\n Statement::CreateSink(CreateSinkStatement { name, .. })\n\n | Statement::CreateSource(CreateSourceStatement { name, .. })\n\n | Statement::CreateView(CreateViewStatement { name, .. })\n\n | Statement::CreateTable(CreateTableStatement { name, .. }) => {\n\n name.0[2] = Ident::new(to_item_name);\n\n }\n\n _ => unreachable!(\"Internal error: only catalog items can be renamed\"),\n\n }\n\n}\n\n\n", "file_path": "src/sql/src/ast/transform.rs", "rank": 20, "score": 402511.6803683117 }, { "content": "pub fn transform_expr(scx: &StatementContext, expr: &mut Expr<Raw>) -> Result<(), anyhow::Error> {\n\n run_transforms(scx, |t, expr| t.visit_expr_mut(expr), expr)\n\n}\n\n\n", "file_path": "src/sql/src/plan/transform_ast.rs", "rank": 21, "score": 401065.95746523095 }, { "content": "pub fn build_sleep(mut cmd: BuiltinCommand) -> Result<SleepAction, String> {\n\n let arg = cmd.args.string(\"duration\")?;\n\n let time = parse_duration::parse(&arg).map_err(|e| e.to_string())?;\n\n Ok(SleepAction { time })\n\n}\n\n\n\nimpl SyncAction for SleepAction {\n\n fn undo(&self, _: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n fn redo(&self, _: &mut State) -> Result<(), String> {\n\n let mut rng = rand::thread_rng();\n\n let sleep = rng.gen_range(Duration::from_secs(0)..self.time);\n\n println!(\"Sleeping for {:?}\", sleep);\n\n thread::sleep(sleep);\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/testdrive/src/action/sleep.rs", "rank": 22, "score": 397514.6836821841 }, { "content": "pub fn build_append(mut cmd: BuiltinCommand) -> Result<AppendAction, String> {\n\n let path = build_path(&mut cmd)?;\n\n let compression = build_compression(&mut cmd)?;\n\n cmd.args.done()?;\n\n let mut contents = vec![];\n\n for line in cmd.input {\n\n contents.extend(bytes::unescape(line.as_bytes())?);\n\n contents.push(b'\\n');\n\n }\n\n Ok(AppendAction {\n\n path,\n\n contents,\n\n compression,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for AppendAction {\n\n async fn undo(&self, _: &mut State) -> Result<(), String> {\n\n // Files are written to a fresh temporary directory, so no need to\n", "file_path": "src/testdrive/src/action/file.rs", "rank": 23, "score": 397514.6836821841 }, { "content": "pub fn build_delete(mut cmd: BuiltinCommand) -> Result<DeleteAction, String> {\n\n let path = build_path(&mut cmd)?;\n\n cmd.args.done()?;\n\n Ok(DeleteAction { path })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for DeleteAction {\n\n async fn undo(&self, _: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let path = state.temp_dir.path().join(&self.path);\n\n println!(\"Deleting file {}\", path.display());\n\n tokio::fs::remove_file(&path)\n\n .await\n\n .map_err(|e| e.to_string())\n\n }\n\n}\n", "file_path": "src/testdrive/src/action/file.rs", "rank": 24, "score": 397514.6836821841 }, { "content": "fn any_matches(haystack: &[String], needle: &str) -> bool {\n\n haystack.iter().any(|s| s.contains(needle))\n\n}\n", "file_path": "test/performance/perf-upsert/src/main.rs", "rank": 25, "score": 395746.1119807167 }, { "content": "pub fn build_append(mut cmd: BuiltinCommand) -> Result<AppendAction, String> {\n\n let path = cmd.args.string(\"path\")?;\n\n let records = cmd.input;\n\n cmd.args.done()?;\n\n if path.contains(path::MAIN_SEPARATOR) {\n\n // The goal isn't security, but preventing mistakes.\n\n return Err(\"separators in paths are forbidden\".into());\n\n }\n\n Ok(AppendAction { path, records })\n\n}\n\n\n\nimpl SyncAction for AppendAction {\n\n fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let path = state.temp_dir.path().join(&self.path);\n\n println!(\"Appending to {}\", path.display());\n\n let file = OpenOptions::new()\n\n .read(true)\n\n .write(true)\n\n .open(path)\n\n .map_err(|e| e.to_string())?;\n\n let mut writer = Writer::append_to(file).map_err(|e| e.to_string())?;\n\n write_records(&mut writer, &self.records)?;\n\n Ok(())\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/avro_ocf.rs", "rank": 26, "score": 393258.5716255638 }, { "content": "pub fn build_verify(mut cmd: BuiltinCommand) -> Result<VerifyAction, String> {\n\n let _format = cmd.args.string(\"format\")?;\n\n let sink = cmd.args.string(\"sink\")?;\n\n let consistency = match cmd.args.opt_string(\"consistency\").as_deref() {\n\n Some(\"debezium\") => Some(SinkConsistencyFormat::Debezium),\n\n Some(s) => return Err(format!(\"unknown sink consistency format {}\", s)),\n\n None => None,\n\n };\n\n\n\n let expected_messages = cmd.input;\n\n cmd.args.done()?;\n\n Ok(VerifyAction {\n\n sink,\n\n consistency,\n\n expected_messages,\n\n })\n\n}\n\n\n", "file_path": "src/testdrive/src/action/kafka/verify.rs", "rank": 27, "score": 393258.5716255638 }, { "content": "pub fn build_ingest(mut cmd: BuiltinCommand) -> Result<IngestAction, String> {\n\n let topic_prefix = format!(\"testdrive-{}\", cmd.args.string(\"topic\")?);\n\n let partition = cmd.args.opt_parse::<i32>(\"partition\")?.unwrap_or(0);\n\n let format = match cmd.args.string(\"format\")?.as_str() {\n\n \"avro\" => Format::Avro {\n\n schema: cmd.args.string(\"schema\")?,\n\n },\n\n \"protobuf\" => Format::Protobuf {\n\n message: cmd.args.parse(\"message\")?,\n\n },\n\n \"bytes\" => Format::Bytes { terminator: None },\n\n f => return Err(format!(\"unknown format: {}\", f)),\n\n };\n\n let key_format = match cmd.args.opt_string(\"key-format\").as_deref() {\n\n Some(\"avro\") => Some(Format::Avro {\n\n schema: cmd.args.string(\"key-schema\")?,\n\n }),\n\n Some(\"protobuf\") => Some(Format::Protobuf {\n\n message: cmd.args.parse(\"key-message\")?,\n\n }),\n", "file_path": "src/testdrive/src/action/kafka/ingest.rs", "rank": 28, "score": 393258.5716255638 }, { "content": "pub fn build_write(mut cmd: BuiltinCommand) -> Result<WriteAction, String> {\n\n let path = cmd.args.string(\"path\")?;\n\n let schema = cmd.args.string(\"schema\")?;\n\n let codec = cmd.args.opt_parse(\"codec\")?;\n\n\n\n let records = cmd.input;\n\n cmd.args.done()?;\n\n if path.contains(path::MAIN_SEPARATOR) {\n\n // The goal isn't security, but preventing mistakes.\n\n return Err(\"separators in paths are forbidden\".into());\n\n }\n\n Ok(WriteAction {\n\n path,\n\n schema,\n\n records,\n\n codec,\n\n })\n\n}\n\n\n\nimpl SyncAction for WriteAction {\n", "file_path": "src/testdrive/src/action/avro_ocf.rs", "rank": 29, "score": 393258.5716255638 }, { "content": "pub fn build_verify(mut cmd: BuiltinCommand) -> Result<VerifyAction, String> {\n\n let sink = cmd.args.string(\"sink\")?;\n\n let expected = cmd.input;\n\n cmd.args.done()?;\n\n if sink.contains(path::MAIN_SEPARATOR) {\n\n // The goal isn't security, but preventing mistakes.\n\n return Err(\"separators in file sink names are forbidden\".into());\n\n }\n\n Ok(VerifyAction { sink, expected })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for VerifyAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let path = retry::retry_for(Duration::from_secs(8), |_| async {\n\n let row = state\n", "file_path": "src/testdrive/src/action/avro_ocf.rs", "rank": 30, "score": 393258.5716255638 }, { "content": "pub fn build_verify(mut cmd: BuiltinCommand) -> Result<VerifyAction, String> {\n\n let stream_prefix = cmd.args.string(\"stream\")?;\n\n let expected_records: HashSet<String> = cmd.input.into_iter().collect();\n\n\n\n cmd.args.done()?;\n\n\n\n Ok(VerifyAction {\n\n stream_prefix,\n\n expected_records,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for VerifyAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let stream_name = format!(\"testdrive-{}-{}\", self.stream_prefix, state.seed);\n", "file_path": "src/testdrive/src/action/kinesis/verify.rs", "rank": 31, "score": 393258.5716255638 }, { "content": "pub fn build_ingest(mut cmd: BuiltinCommand) -> Result<IngestAction, String> {\n\n let stream_prefix = format!(\"testdrive-{}\", cmd.args.string(\"stream\")?);\n\n match cmd.args.string(\"format\")?.as_str() {\n\n \"bytes\" => (),\n\n f => return Err(format!(\"unsupported message format for Kinesis: {}\", f)),\n\n }\n\n cmd.args.done()?;\n\n\n\n Ok(IngestAction {\n\n stream_prefix,\n\n rows: cmd.input,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for IngestAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n", "file_path": "src/testdrive/src/action/kinesis/ingest.rs", "rank": 32, "score": 393258.57162556384 }, { "content": "/// Parses a SQL string containing zero or more SQL statements.\n\npub fn parse_statements(sql: &str) -> Result<Vec<Statement<Raw>>, ParserError> {\n\n let tokens = lexer::lex(sql)?;\n\n Parser::new(sql, tokens).parse_statements()\n\n}\n\n\n", "file_path": "src/sql-parser/src/parser.rs", "rank": 33, "score": 390806.59866814397 }, { "content": "pub fn build_create_bucket(mut cmd: BuiltinCommand) -> Result<CreateBucketAction, String> {\n\n Ok(CreateBucketAction {\n\n bucket: cmd.args.string(\"bucket\")?,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for CreateBucketAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n println!(\"Creating S3 Bucket {}\", self.bucket);\n\n\n\n match state\n\n .s3_client\n\n .create_bucket(CreateBucketRequest {\n\n bucket: self.bucket.clone(),\n\n create_bucket_configuration: Some(CreateBucketConfiguration {\n", "file_path": "src/testdrive/src/action/s3.rs", "rank": 34, "score": 389160.8711019199 }, { "content": "pub fn build_put_object(mut cmd: BuiltinCommand) -> Result<PutObjectAction, String> {\n\n Ok(PutObjectAction {\n\n bucket: cmd.args.string(\"bucket\")?,\n\n key: cmd.args.string(\"key\")?,\n\n contents: cmd.input.join(\"\\n\"),\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for PutObjectAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n println!(\"Creating S3 Bucket {}\", self.bucket);\n\n\n\n state\n\n .s3_client\n\n .put_object(PutObjectRequest {\n", "file_path": "src/testdrive/src/action/s3.rs", "rank": 35, "score": 389160.87110191997 }, { "content": "pub fn parse(line_reader: &mut LineReader) -> Result<Vec<PosCommand>, InputError> {\n\n let mut out = Vec::new();\n\n while let Some((pos, line)) = line_reader.peek() {\n\n let pos = *pos;\n\n let command = match line.chars().next() {\n\n Some('$') => Command::Builtin(parse_builtin(line_reader)?),\n\n Some('>') => Command::Sql(parse_sql(line_reader)?),\n\n Some('!') => Command::FailSql(parse_fail_sql(line_reader)?),\n\n Some('#') => {\n\n // Comment line.\n\n line_reader.next();\n\n continue;\n\n }\n\n _ => {\n\n return Err(InputError {\n\n msg: \"unexpected input line at beginning of file\".into(),\n\n pos,\n\n });\n\n }\n\n };\n\n out.push(PosCommand { command, pos });\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/testdrive/src/parser.rs", "rank": 36, "score": 386241.5244155474 }, { "content": "/// Resolves the operator to a set of function implementations.\n\npub fn resolve_op(op: &str) -> Result<&'static [FuncImpl<HirScalarExpr>], anyhow::Error> {\n\n match OP_IMPLS.get(op) {\n\n Some(Func::Scalar(impls)) => Ok(impls),\n\n Some(_) => unreachable!(\"all operators must be scalar functions\"),\n\n // TODO: these require sql arrays\n\n // JsonContainsAnyFields\n\n // JsonContainsAllFields\n\n // TODO: these require json paths\n\n // JsonGetPath\n\n // JsonGetPathAsText\n\n // JsonDeletePath\n\n // JsonContainsPath\n\n // JsonApplyPathPredicate\n\n None => unsupported!(op),\n\n }\n\n}\n", "file_path": "src/sql/src/func.rs", "rank": 37, "score": 386057.49159970606 }, { "content": "/// Writes a boolean value into `buf`.\n\n///\n\n/// `true` is encoded as the char `'t'` and `false` is encoded as the char\n\n/// `'f'`.\n\npub fn format_bool<F>(buf: &mut F, b: bool) -> Nestable\n\nwhere\n\n F: FormatBuffer,\n\n{\n\n buf.write_str(format_bool_static(b));\n\n Nestable::Yes\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 38, "score": 385414.4338710344 }, { "content": "fn item_generics(item: &Item, suffix: &str) -> String {\n\n if item.generics().is_empty() {\n\n \"\".into()\n\n } else {\n\n let generics = item\n\n .generics()\n\n .iter()\n\n .map(|g| f!(\"{g.name}{suffix}\"))\n\n .join(\", \");\n\n format!(\"<{}>\", generics)\n\n }\n\n}\n", "file_path": "src/walkabout/src/gen.rs", "rank": 39, "score": 384513.5313297217 }, { "content": "fn lex_embedded_element<'a>(buf: &mut LexBuf<'a>) -> Result<Cow<'a, str>, String> {\n\n let pos = buf.pos();\n\n assert!(matches!(buf.next(), Some('{')));\n\n let mut depth = 1;\n\n let mut in_escape = false;\n\n while depth > 0 {\n\n match buf.next() {\n\n Some('\\\\') => {\n\n buf.next(); // Next character is escaped, so ignore it\n\n }\n\n Some('\"') => in_escape = !in_escape, // Begin or end escape\n\n Some('{') if !in_escape => depth += 1,\n\n Some('}') if !in_escape => depth -= 1,\n\n Some(_) => (),\n\n None => bail!(\"unterminated embedded element\"),\n\n }\n\n }\n\n let s = &buf.inner()[pos..buf.pos()];\n\n Ok(Cow::Borrowed(s))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 40, "score": 383229.6159430993 }, { "content": "fn lex_quoted_element<'a>(buf: &mut LexBuf<'a>) -> Result<Cow<'a, str>, String> {\n\n assert!(buf.consume('\"'));\n\n let s = buf.take_while(|ch| !matches!(ch, '\"' | '\\\\'));\n\n\n\n // `Cow::Borrowed` optimization for quoted strings without escapes\n\n if let Some('\"') = buf.peek() {\n\n buf.next();\n\n return Ok(s.into());\n\n }\n\n\n\n let mut s = s.to_string();\n\n loop {\n\n match buf.next() {\n\n Some('\\\\') => match buf.next() {\n\n Some(c) => s.push(c),\n\n None => bail!(\"unterminated quoted string\"),\n\n },\n\n Some('\"') => break,\n\n Some(c) => s.push(c),\n\n None => bail!(\"unterminated quoted string\"),\n\n }\n\n }\n\n Ok(s.into())\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 41, "score": 383229.6159430993 }, { "content": "pub fn build_create_topic(mut cmd: BuiltinCommand) -> Result<CreateTopicAction, String> {\n\n let topic_prefix = format!(\"testdrive-{}\", cmd.args.string(\"topic\")?);\n\n let partitions = cmd.args.opt_parse(\"partitions\")?.unwrap_or(1);\n\n let compression = cmd\n\n .args\n\n .opt_string(\"compression\")\n\n .unwrap_or_else(|| \"producer\".into());\n\n cmd.args.done()?;\n\n\n\n Ok(CreateTopicAction {\n\n topic_prefix,\n\n partitions,\n\n compression,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for CreateTopicAction {\n\n async fn undo(&self, state: &mut State) -> Result<(), String> {\n\n let metadata = state\n", "file_path": "src/testdrive/src/action/kafka/create_topic.rs", "rank": 42, "score": 381406.5978514062 }, { "content": "pub fn build_add_partitions(mut cmd: BuiltinCommand) -> Result<AddPartitionsAction, String> {\n\n let topic_prefix = format!(\"testdrive-{}\", cmd.args.string(\"topic\")?);\n\n let partitions = cmd.args.opt_parse(\"total-partitions\")?.unwrap_or(1);\n\n cmd.args.done()?;\n\n\n\n Ok(AddPartitionsAction {\n\n topic_prefix,\n\n partitions,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for AddPartitionsAction {\n\n async fn undo(&self, _: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let topic_name = format!(\"{}-{}\", self.topic_prefix, state.seed);\n\n println!(\n", "file_path": "src/testdrive/src/action/kafka/add_partitions.rs", "rank": 43, "score": 381406.59785140614 }, { "content": "pub fn build_create_stream(mut cmd: BuiltinCommand) -> Result<CreateStreamAction, String> {\n\n let stream_name = format!(\"testdrive-{}\", cmd.args.string(\"stream\")?);\n\n let shard_count = cmd.args.parse(\"shards\")?;\n\n cmd.args.done()?;\n\n\n\n Ok(CreateStreamAction {\n\n stream_name,\n\n shard_count,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for CreateStreamAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let stream_name = format!(\"{}-{}\", self.stream_name, state.seed);\n\n println!(\"Creating Kinesis stream {}\", stream_name);\n", "file_path": "src/testdrive/src/action/kinesis/create_stream.rs", "rank": 44, "score": 381406.5978514062 }, { "content": "/// Builds a regular expression that matches the same strings as a SQL\n\n/// LIKE pattern.\n\npub fn build_regex(pattern: &str, flags: &str) -> Result<Regex, EvalError> {\n\n // LIKE patterns always cover the whole string, so we anchor the regex on\n\n // both sides. An underscore (`_`) in a LIKE pattern matches any single\n\n // character and a percent sign (`%`) matches any sequence of zero or more\n\n // characters, so we translate those operators to their equivalent regex\n\n // operators, `.` and `.*`, respectively. Other characters match themselves\n\n // and are copied directly, unless they have special meaning in a regex, in\n\n // which case they are escaped in the regex with a backslash (`\\`).\n\n //\n\n // Note that characters in LIKE patterns may also be escaped by preceding\n\n // them with a backslash. This has no effect on most characters, but it\n\n // removes the special meaning from the underscore and percent sign\n\n // operators, and means that matching a literal backslash requires doubling\n\n // the backslash.\n\n //\n\n // TODO(benesch): SQL permits selecting a different escape character than\n\n // the backslash via LIKE '...' ESCAPE '...'. We will need to support this\n\n // syntax eventually.\n\n let mut regex = String::from(\"^\");\n\n let mut escape = false;\n", "file_path": "src/expr/src/scalar/like_pattern.rs", "rank": 45, "score": 379725.8408211502 }, { "content": "fn invent_column_name(ecx: &ExprContext, expr: &Expr<Raw>) -> Option<ScopeItemName> {\n\n let name = match expr {\n\n Expr::Identifier(names) => names.last().map(|n| normalize::column_name(n.clone())),\n\n Expr::Function(func) => {\n\n let name = normalize::object_name(func.name.clone()).ok()?;\n\n if name.schema.as_deref() == Some(\"mz_internal\") {\n\n None\n\n } else {\n\n Some(name.item.into())\n\n }\n\n }\n\n Expr::Coalesce { .. } => Some(\"coalesce\".into()),\n\n Expr::NullIf { .. } => Some(\"nullif\".into()),\n\n Expr::Array { .. } => Some(\"array\".into()),\n\n Expr::List { .. } => Some(\"list\".into()),\n\n Expr::Cast { expr, .. } => return invent_column_name(ecx, expr),\n\n Expr::FieldAccess { field, .. } => Some(normalize::column_name(field.clone())),\n\n Expr::Exists { .. } => Some(\"exists\".into()),\n\n Expr::Subquery(query) => {\n\n // A bit silly to have to plan the query here just to get its column\n", "file_path": "src/sql/src/plan/query.rs", "rank": 46, "score": 377886.24853809667 }, { "content": "pub fn build_update_shards(mut cmd: BuiltinCommand) -> Result<UpdateShardCountAction, String> {\n\n let stream_name = format!(\"testdrive-{}\", cmd.args.string(\"stream\")?);\n\n let target_shard_count = cmd.args.parse(\"shards\")?;\n\n cmd.args.done()?;\n\n\n\n Ok(UpdateShardCountAction {\n\n stream_name,\n\n target_shard_count,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for UpdateShardCountAction {\n\n async fn undo(&self, _state: &mut State) -> Result<(), String> {\n\n Ok(())\n\n }\n\n\n\n async fn redo(&self, state: &mut State) -> Result<(), String> {\n\n let stream_name = format!(\"{}-{}\", self.stream_name, state.seed);\n\n println!(\n", "file_path": "src/testdrive/src/action/kinesis/update_shards.rs", "rank": 47, "score": 377734.4746262778 }, { "content": "pub fn build_sql(mut cmd: SqlCommand, timeout: Duration) -> Result<SqlAction, String> {\n\n let stmts = sql_parser::parser::parse_statements(&cmd.query)\n\n .map_err(|e| format!(\"unable to parse SQL: {}: {}\", cmd.query, e))?;\n\n if stmts.len() != 1 {\n\n return Err(format!(\"expected one statement, but got {}\", stmts.len()));\n\n }\n\n if let SqlOutput::Full { expected_rows, .. } = &mut cmd.expected_output {\n\n // TODO(benesch): one day we'll support SQL queries where order matters.\n\n expected_rows.sort();\n\n }\n\n Ok(SqlAction {\n\n cmd,\n\n stmt: stmts.into_element(),\n\n timeout,\n\n })\n\n}\n\n\n\n#[async_trait]\n\nimpl Action for SqlAction {\n\n async fn undo(&self, state: &mut State) -> Result<(), String> {\n", "file_path": "src/testdrive/src/action/sql.rs", "rank": 48, "score": 375594.8588044202 }, { "content": "/// Rewrites `query`'s references of `from` to `to` or errors if too ambiguous.\n\nfn rewrite_query(from: FullName, to: String, query: &mut Query<Raw>) -> Result<(), String> {\n\n let from_ident = Ident::new(from.item.clone());\n\n let to_ident = Ident::new(to);\n\n let qual_depth =\n\n QueryIdentAgg::determine_qual_depth(&from_ident, Some(to_ident.clone()), query)?;\n\n CreateSqlRewriter::rewrite_query_with_qual_depth(from, to_ident.clone(), qual_depth, query);\n\n // Ensure that our rewrite didn't didn't introduce ambiguous\n\n // references to `to_name`.\n\n match QueryIdentAgg::determine_qual_depth(&to_ident, None, query) {\n\n Ok(_) => Ok(()),\n\n Err(e) => Err(e),\n\n }\n\n}\n\n\n", "file_path": "src/sql/src/ast/transform.rs", "rank": 49, "score": 375063.32026370626 }, { "content": "pub fn build_regex(needle: &str, flags: &str) -> Result<regex::Regex, EvalError> {\n\n let mut regex = RegexBuilder::new(needle);\n\n for f in flags.chars() {\n\n match f {\n\n 'i' => {\n\n regex.case_insensitive(true);\n\n }\n\n 'c' => {\n\n regex.case_insensitive(false);\n\n }\n\n _ => return Err(EvalError::InvalidRegexFlag(f)),\n\n }\n\n }\n\n Ok(regex.build()?)\n\n}\n\n\n", "file_path": "src/expr/src/scalar/func.rs", "rank": 50, "score": 374596.2417399631 }, { "content": "/// Initialize global logger, using the [`tracing_subscriber`] crate.\n\n///\n\n/// The default log level will be set to the value passed in.\n\n///\n\n/// It is safe to call `init_logging_level` multiple times. Since `cargo test` does\n\n/// not run tests in any particular order, each must call `init_logging`.\n\npub fn init_logging_default(level: &str) {\n\n LOG_INIT.call_once(|| {\n\n let filter = EnvFilter::try_from_env(\"MZ_LOG\")\n\n .or_else(|_| EnvFilter::try_new(level))\n\n .unwrap();\n\n FmtSubscriber::builder().with_env_filter(filter).init();\n\n });\n\n}\n", "file_path": "src/ore/src/test.rs", "rank": 51, "score": 369896.03836027253 }, { "content": "/// Extracts deduplicated column names and types from a relation description.\n\npub fn column_names_and_types(desc: RelationDesc) -> Vec<(ColumnName, ColumnType)> {\n\n // Invent names for columns that don't have a name.\n\n let mut columns: Vec<_> = desc\n\n .into_iter()\n\n .enumerate()\n\n .map(|(i, (name, ty))| match name {\n\n None => (ColumnName::from(format!(\"column{}\", i + 1)), ty),\n\n Some(name) => (name, ty),\n\n })\n\n .collect();\n\n\n\n // Deduplicate names.\n\n let mut seen = HashSet::new();\n\n for (name, _ty) in &mut columns {\n\n let stem_len = name.as_str().len();\n\n let mut i = 1;\n\n while seen.contains(name) {\n\n name.as_mut_str().truncate(stem_len);\n\n if name.as_str().ends_with(|c: char| c.is_ascii_digit()) {\n\n name.as_mut_str().push('_');\n\n }\n\n name.as_mut_str().push_str(&i.to_string());\n\n i += 1;\n\n }\n\n seen.insert(name);\n\n }\n\n columns\n\n}\n\n\n", "file_path": "src/interchange/src/avro.rs", "rank": 52, "score": 369227.3712588082 }, { "content": "pub fn zig_i64(n: i64, buffer: &mut Vec<u8>) {\n\n encode_variable(((n << 1) ^ (n >> 63)) as u64, buffer)\n\n}\n\n\n", "file_path": "src/avro/src/util.rs", "rank": 53, "score": 368266.21686113934 }, { "content": "pub fn zig_i32(n: i32, buffer: &mut Vec<u8>) {\n\n zig_i64(n as i64, buffer)\n\n}\n\n\n", "file_path": "src/avro/src/util.rs", "rank": 54, "score": 368266.21686113934 }, { "content": "fn find_trivial_column_equivalences(expr: &HirScalarExpr) -> Vec<(usize, usize)> {\n\n use BinaryFunc::*;\n\n use HirScalarExpr::*;\n\n let mut exprs = vec![expr];\n\n let mut equivalences = vec![];\n\n while let Some(expr) = exprs.pop() {\n\n match expr {\n\n CallBinary {\n\n func: Eq,\n\n expr1,\n\n expr2,\n\n } => {\n\n if let (\n\n Column(ColumnRef {\n\n level: 0,\n\n column: l,\n\n }),\n\n Column(ColumnRef {\n\n level: 0,\n\n column: r,\n", "file_path": "src/sql/src/plan/query.rs", "rank": 55, "score": 367318.77312518854 }, { "content": "pub fn validate_descriptors(message_name: &str, descriptors: &Descriptors) -> Result<RelationDesc> {\n\n let proto_name = proto_message_name(message_name);\n\n let message = descriptors.message_by_name(&proto_name).ok_or_else(|| {\n\n anyhow!(\n\n \"Message {:?} not found in file descriptor set: {}\",\n\n proto_name,\n\n descriptors\n\n .iter_messages()\n\n .map(|m| m.name())\n\n .collect::<Vec<_>>()\n\n .join(\", \")\n\n )\n\n })?;\n\n let column_types = message\n\n .fields()\n\n .iter()\n\n .map(|f| {\n\n Ok(ColumnType {\n\n /// All the fields have to be optional, so mark a field as\n\n /// nullable if it doesn't have any defaults\n", "file_path": "src/interchange/src/protobuf.rs", "rank": 56, "score": 366666.71355466475 }, { "content": "fn plan_current_timestamp(ecx: &ExprContext, name: &str) -> Result<HirScalarExpr, anyhow::Error> {\n\n match ecx.qcx.lifetime {\n\n QueryLifetime::OneShot => Ok(HirScalarExpr::literal(\n\n Datum::from(ecx.qcx.scx.pcx.wall_time),\n\n ScalarType::TimestampTz,\n\n )),\n\n QueryLifetime::Static => bail!(\"{} cannot be used in static queries\", name),\n\n }\n\n}\n\n\n", "file_path": "src/sql/src/func.rs", "rank": 57, "score": 363895.8415515967 }, { "content": "/// Rewrites predicates that contain subqueries so that the subqueries\n\n/// appear in their own later predicate when possible.\n\n///\n\n/// For example, this function rewrites this expression\n\n///\n\n/// ```text\n\n/// Filter {\n\n/// predicates: [a = b AND EXISTS (<subquery 1>) AND c = d AND (<subquery 2>) = e]\n\n/// }\n\n/// ```\n\n///\n\n/// like so:\n\n///\n\n/// ```text\n\n/// Filter {\n\n/// predicates: [\n\n/// a = b AND c = d,\n\n/// EXISTS (<subquery>),\n\n/// (<subquery 2>) = e,\n\n/// ]\n\n/// }\n\n/// ```\n\n///\n\n/// The rewrite causes decorrelation to incorporate prior predicates into\n\n/// the outer relation upon which the subquery is evaluated. In the above\n\n/// rewritten example, the `EXISTS (<subquery>)` will only be evaluated for\n\n/// outer rows where `a = b AND c = d`. The second subquery, `(<subquery 2>)\n\n/// = e`, will be further restricted to outer rows that match `A = b AND c =\n\n/// d AND EXISTS(<subquery>)`. This can vastly reduce the cost of the\n\n/// subquery, especially when the original conjunction contains join keys.\n\npub fn split_subquery_predicates(expr: &mut HirRelationExpr) {\n\n fn walk_relation(expr: &mut HirRelationExpr) {\n\n expr.visit_mut(&mut |expr| match expr {\n\n HirRelationExpr::Map { scalars, .. } => {\n\n for scalar in scalars {\n\n walk_scalar(scalar);\n\n }\n\n }\n\n HirRelationExpr::CallTable { exprs, .. } => {\n\n for expr in exprs {\n\n walk_scalar(expr);\n\n }\n\n }\n\n HirRelationExpr::Filter { predicates, .. } => {\n\n let mut subqueries = vec![];\n\n for predicate in &mut *predicates {\n\n walk_scalar(predicate);\n\n extract_conjuncted_subqueries(predicate, &mut subqueries);\n\n }\n\n // TODO(benesch): we could be smarter about the order in which\n", "file_path": "src/sql/src/plan/transform_expr.rs", "rank": 58, "score": 362774.2640512065 }, { "content": "fn decode_row(row: Row) -> Result<Vec<String>, String> {\n\n enum ArrayElement<T> {\n\n Null,\n\n NonNull(T),\n\n }\n\n\n\n impl<T> fmt::Display for ArrayElement<T>\n\n where\n\n T: fmt::Display,\n\n {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n ArrayElement::Null => f.write_str(\"NULL\"),\n\n ArrayElement::NonNull(t) => t.fmt(f),\n\n }\n\n }\n\n }\n\n\n\n impl<'a, T> FromSql<'a> for ArrayElement<T>\n\n where\n", "file_path": "src/testdrive/src/action/sql.rs", "rank": 59, "score": 362437.2924038271 }, { "content": "/// Rewrites quantified comparisons into simpler EXISTS operators.\n\n///\n\n/// Note that this transformation is only valid when the expression is\n\n/// used in a context where the distinction between `FALSE` and `NULL`\n\n/// is immaterial, e.g., in a `WHERE` clause or a `CASE` condition, or\n\n/// when the inputs to the comparison are non-nullable. This function is careful\n\n/// to only apply the transformation when it is valid to do so.\n\n///\n\n/// WHERE (SELECT any(<pred>) FROM <rel>)\n\n/// =>\n\n/// WHERE EXISTS(SELECT * FROM <rel> WHERE <pred>)\n\n///\n\n/// WHERE (SELECT all(<pred>) FROM <rel>)\n\n/// =>\n\n/// WHERE NOT EXISTS(SELECT * FROM <rel> WHERE (NOT <pred>) OR <pred> IS NULL)\n\n///\n\n/// See Section 3.5 of \"Execution Strategies for SQL Subqueries\" by\n\n/// M. Elhemali, et al.\n\npub fn try_simplify_quantified_comparisons(expr: &mut HirRelationExpr) {\n\n fn walk_relation(expr: &mut HirRelationExpr, outers: &[RelationType]) {\n\n match expr {\n\n HirRelationExpr::Map { scalars, input } => {\n\n walk_relation(input, outers);\n\n let mut outers = outers.to_vec();\n\n outers.push(input.typ(&outers, &NO_PARAMS));\n\n for scalar in scalars {\n\n walk_scalar(scalar, &outers, false);\n\n let (inner, outers) = outers\n\n .split_last_mut()\n\n .expect(\"outers known to have at least one element\");\n\n let scalar_type = scalar.typ(&outers, inner, &NO_PARAMS);\n\n inner.column_types.push(scalar_type);\n\n }\n\n }\n\n HirRelationExpr::Filter { predicates, input } => {\n\n walk_relation(input, outers);\n\n let mut outers = outers.to_vec();\n\n outers.push(input.typ(&outers, &NO_PARAMS));\n", "file_path": "src/sql/src/plan/transform_expr.rs", "rank": 60, "score": 359474.5554425339 }, { "content": "fn build_path(cmd: &mut BuiltinCommand) -> Result<String, String> {\n\n let path = cmd.args.string(\"path\")?;\n\n if path.contains(path::MAIN_SEPARATOR) {\n\n // The goal isn't security, but preventing mistakes.\n\n Err(\"separators in paths are forbidden\".into())\n\n } else {\n\n Ok(path)\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "rank": 61, "score": 358386.67942277726 }, { "content": "/// Substituted `${}`-delimited variables from `vars` into `msg`\n\nfn substitute_vars(msg: &str, vars: &HashMap<String, String>) -> Result<String, String> {\n\n lazy_static! {\n\n static ref RE: Regex = Regex::new(r\"\\$\\{([^}]+)\\}\").unwrap();\n\n }\n\n let mut err = None;\n\n let out = RE.replace_all(msg, |caps: &Captures| {\n\n let name = &caps[1];\n\n if let Some(val) = vars.get(name) {\n\n val\n\n } else {\n\n err = Some(format!(\"unknown variable: {}\", name));\n\n \"#VAR-MISSING#\"\n\n }\n\n });\n\n match err {\n\n Some(err) => Err(err),\n\n None => Ok(out.into_owned()),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action.rs", "rank": 62, "score": 358072.58594966796 }, { "content": "/// Retrieves the value of the next hexadecimal digit in `iter`, if the next\n\n/// byte is a valid hexadecimal digit.\n\nfn next_hex<I>(iter: &mut I) -> Option<u8>\n\nwhere\n\n I: Iterator<Item = u8>,\n\n{\n\n iter.next().and_then(|c| match c {\n\n b'A'..=b'F' => Some(c - b'A' + 10),\n\n b'a'..=b'f' => Some(c - b'a' + 10),\n\n b'0'..=b'9' => Some(c - b'0'),\n\n _ => None,\n\n })\n\n}\n", "file_path": "src/testdrive/src/format/bytes.rs", "rank": 63, "score": 356696.001814132 }, { "content": "// This function is derived from code in the avro_rs project. Update the license\n\n// header on this file accordingly if you move it to a new home.\n\npub fn from_json(json: &JsonValue, schema: SchemaNode) -> Result<Value, String> {\n\n match (json, schema.inner) {\n\n (JsonValue::Null, SchemaPiece::Null) => Ok(Value::Null),\n\n (JsonValue::Bool(b), SchemaPiece::Boolean) => Ok(Value::Boolean(*b)),\n\n (JsonValue::Number(ref n), SchemaPiece::Int) => Ok(Value::Int(\n\n n.as_i64()\n\n .unwrap()\n\n .try_into()\n\n .map_err(|e: TryFromIntError| e.to_string())?,\n\n )),\n\n (JsonValue::Number(ref n), SchemaPiece::Long) => Ok(Value::Long(n.as_i64().unwrap())),\n\n (JsonValue::Number(ref n), SchemaPiece::Float) => {\n\n Ok(Value::Float(n.as_f64().unwrap() as f32))\n\n }\n\n (JsonValue::Number(ref n), SchemaPiece::Double) => Ok(Value::Double(n.as_f64().unwrap())),\n\n (JsonValue::Number(ref n), SchemaPiece::Date) => Ok(Value::Date(\n\n chrono::NaiveDate::from_ymd(1970, 1, 1) + chrono::Duration::days(n.as_i64().unwrap()),\n\n )),\n\n (JsonValue::Number(ref n), SchemaPiece::TimestampMilli) => {\n\n let ts = n.as_i64().unwrap();\n", "file_path": "src/testdrive/src/format/avro.rs", "rank": 64, "score": 356515.05771435576 }, { "content": "/// Creates a type whose [`fmt::Display`] implementation outputs item preceded\n\n/// by `open` and followed by `close`.\n\npub fn bracketed<'a, D>(open: &'a str, close: &'a str, contents: D) -> impl fmt::Display + 'a\n\nwhere\n\n D: fmt::Display + 'a,\n\n{\n\n struct Bracketed<'a, D> {\n\n open: &'a str,\n\n close: &'a str,\n\n contents: D,\n\n }\n\n\n\n impl<'a, D> fmt::Display for Bracketed<'a, D>\n\n where\n\n D: fmt::Display,\n\n {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}{}{}\", self.open, self.contents, self.close)\n\n }\n\n }\n\n\n\n Bracketed {\n", "file_path": "src/expr/src/explain.rs", "rank": 65, "score": 355071.7826232303 }, { "content": "/// Create a new vector that re-uses the same allocation as an old one.\n\n/// The element types must have the same size and alignment.\n\npub fn repurpose_allocation<T1, T2>(mut v: Vec<T1>) -> Vec<T2> {\n\n assert!(size_of::<T1>() == size_of::<T2>());\n\n assert!(align_of::<T1>() == align_of::<T2>());\n\n v.clear();\n\n let cap = v.capacity();\n\n let p = v.as_mut_ptr().cast();\n\n std::mem::forget(v);\n\n // This is safe because `T1` and `T2` have the same size and alignment,\n\n // `p`'s allocation is no longer owned by `v` (since that has been forgotten),\n\n // and `p` was previously allocated with capacity `cap`.\n\n unsafe { Vec::from_raw_parts(p, 0, cap) }\n\n}\n", "file_path": "src/ore/src/vec.rs", "rank": 66, "score": 348621.8216904625 }, { "content": "fn format_name(format: u8) -> String {\n\n match format {\n\n 0 => \"text\".to_string(),\n\n 1 => \"binary\".to_string(),\n\n _ => format!(\"unknown: {}\", format),\n\n }\n\n}\n\n\n", "file_path": "src/pgtest/src/lib.rs", "rank": 67, "score": 346335.80766378425 }, { "content": "fn slurp_all(line_reader: &mut LineReader) -> Vec<String> {\n\n let mut out = Vec::new();\n\n while let Some((_, line)) = slurp_one(line_reader) {\n\n out.push(line);\n\n }\n\n out\n\n}\n\n\n", "file_path": "src/testdrive/src/parser.rs", "rank": 68, "score": 346286.0987000901 }, { "content": "fn fold_fn_name(s: &str) -> String {\n\n let mut out = String::from(\"fold\");\n\n write_fn_name(&mut out, s);\n\n out\n\n}\n\n\n", "file_path": "src/walkabout/src/gen.rs", "rank": 69, "score": 345979.32829792413 }, { "content": "fn validate_schema_1(schema: SchemaNode) -> anyhow::Result<Vec<(ColumnName, ColumnType)>> {\n\n match schema.inner {\n\n SchemaPiece::Record { fields, .. } => {\n\n let mut columns = vec![];\n\n let mut seen_avro_nodes = Default::default();\n\n for f in fields {\n\n columns.extend(get_named_columns(\n\n &mut seen_avro_nodes,\n\n schema.step(&f.schema),\n\n &f.name,\n\n )?);\n\n }\n\n Ok(columns)\n\n }\n\n _ => bail!(\"row schemas must be records, got: {:?}\", schema.inner),\n\n }\n\n}\n\n\n", "file_path": "src/interchange/src/avro.rs", "rank": 70, "score": 342608.58436962636 }, { "content": "fn lex_string(buf: &mut LexBuf) -> Result<String, ParserError> {\n\n let mut s = String::new();\n\n loop {\n\n let pos = buf.pos() - 1;\n\n loop {\n\n match buf.next() {\n\n Some('\\'') if buf.consume('\\'') => s.push('\\''),\n\n Some('\\'') => break,\n\n Some(c) => s.push(c),\n\n None => bail!(pos, \"unterminated quoted string\"),\n\n }\n\n }\n\n if !lex_to_adjacent_string(buf) {\n\n return Ok(s);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/sql-parser/src/lexer.rs", "rank": 71, "score": 342283.86444659415 }, { "content": "/// Parses an [`i32`] from `s`.\n\n///\n\n/// Valid values are whatever the [`FromStr`] implementation on `i32` accepts,\n\n/// plus leading and trailing whitespace.\n\npub fn parse_int32(s: &str) -> Result<i32, ParseError> {\n\n s.trim()\n\n .parse()\n\n .map_err(|e| ParseError::new(\"integer\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 72, "score": 338282.3731204198 }, { "content": "/// parse\n\n///\n\n/// ```text\n\n/// <unquoted interval string> ::=\n\n/// [ <sign> ] { <year-month literal> | <day-time literal> }\n\n/// <year-month literal> ::=\n\n/// <years value> [ <minus sign> <months value> ]\n\n/// | <months value>\n\n/// <day-time literal> ::=\n\n/// <day-time interval>\n\n/// | <time interval>\n\n/// <day-time interval> ::=\n\n/// <days value> [ <space> <hours value> [ <colon> <minutes value>\n\n/// [ <colon> <seconds value> ] ] ]\n\n/// <time interval> ::=\n\n/// <hours value> [ <colon> <minutes value> [ <colon> <seconds value> ] ]\n\n/// | <minutes value> [ <colon> <seconds value> ]\n\n/// | <seconds value>\n\n/// ```\n\npub fn parse_interval(s: &str) -> Result<Interval, ParseError> {\n\n parse_interval_w_disambiguator(s, DateTimeField::Second)\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 73, "score": 338280.9914041068 }, { "content": "pub fn parse_schema(schema: &str) -> anyhow::Result<Schema> {\n\n let schema = serde_json::from_str(schema)?;\n\n Ok(Schema::parse(&schema)?)\n\n}\n\n\n", "file_path": "src/interchange/src/avro.rs", "rank": 74, "score": 338276.1406903778 }, { "content": "pub fn parse_jsonb(s: &str) -> Result<Jsonb, ParseError> {\n\n s.trim()\n\n .parse()\n\n .map_err(|e| ParseError::new(\"jsonb\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 75, "score": 338276.1406903778 }, { "content": "/// Parses an `f32` from `s`.\n\npub fn parse_float32(s: &str) -> Result<f32, ParseError> {\n\n fast_float::parse(s).map_err(|_| ParseError::new(\"real\", s))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 76, "score": 338276.1406903778 }, { "content": "/// Parses an `i64` from `s`.\n\npub fn parse_int64(s: &str) -> Result<i64, ParseError> {\n\n s.trim()\n\n .parse()\n\n .map_err(|e| ParseError::new(\"bigint\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 77, "score": 338276.1406903778 }, { "content": "/// Parses an `f64` from `s`.\n\npub fn parse_float64(s: &str) -> Result<f64, ParseError> {\n\n fast_float::parse(s).map_err(|_| ParseError::new(\"double precision\", s))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 78, "score": 338276.1406903778 }, { "content": "pub fn parse_uuid(s: &str) -> Result<Uuid, ParseError> {\n\n s.trim()\n\n .parse()\n\n .map_err(|e| ParseError::new(\"uuid\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 79, "score": 338276.1406903778 }, { "content": "pub fn parse_decimal(s: &str) -> Result<Decimal, ParseError> {\n\n s.trim()\n\n .parse()\n\n .map_err(|e| ParseError::new(\"numeric\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 80, "score": 338276.1406903778 }, { "content": "fn proto_message_name(message_name: &str) -> String {\n\n // Prepend a . (following the serde-protobuf naming scheme to list root paths\n\n // for packaged messages) if the message is part of a package and the user hasn't\n\n // already specified a root path\n\n if message_name.is_empty() || !message_name.contains('.') || message_name.starts_with('.') {\n\n message_name.to_string()\n\n } else {\n\n format!(\".{}\", message_name)\n\n }\n\n}\n\n\n", "file_path": "src/interchange/src/protobuf.rs", "rank": 81, "score": 337704.84856834495 }, { "content": "fn analyze_generic_bounds<'a, I>(bounds: I) -> Result<Vec<String>>\n\nwhere\n\n I: IntoIterator<Item = &'a syn::TypeParamBound>,\n\n{\n\n let mut out = vec![];\n\n for b in bounds {\n\n match b {\n\n syn::TypeParamBound::Trait(t) if t.path.segments.len() != 1 => {\n\n bail!(\n\n \"Unable to analyze trait bound with more than one path segment: {}\",\n\n b.to_token_stream()\n\n )\n\n }\n\n syn::TypeParamBound::Trait(t) => out.push(t.path.segments[0].ident.to_string()),\n\n _ => bail!(\"Unable to analyze non-trait bound: {}\", b.to_token_stream()),\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/walkabout/src/ir.rs", "rank": 82, "score": 337307.38509316836 }, { "content": "/// Create a new `rdkafka::ClientConfig` with the provided\n\n/// [`options`](https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md),\n\n/// and test its ability to create an `rdkafka::consumer::BaseConsumer`.\n\n///\n\n/// Expected to test the output of `extract_security_config`.\n\n///\n\n/// # Errors\n\n///\n\n/// - `librdkafka` cannot create a BaseConsumer using the provided `options`.\n\n/// For example, when using Kerberos auth, and the named principal does not\n\n/// exist.\n\npub fn test_config(options: &BTreeMap<String, String>) -> Result<(), anyhow::Error> {\n\n let mut config = rdkafka::ClientConfig::new();\n\n for (k, v) in options {\n\n config.set(k, v);\n\n }\n\n\n\n match config.create_with_context(RDKafkaErrCheckContext::default()) {\n\n Ok(consumer) => {\n\n let consumer: BaseConsumer<RDKafkaErrCheckContext> = consumer;\n\n if let Ok(err_string) = consumer.context().error.lock() {\n\n if !err_string.is_empty() {\n\n bail!(\"librdkafka: {}\", *err_string)\n\n }\n\n };\n\n }\n\n Err(e) => {\n\n match e {\n\n rdkafka::error::KafkaError::ClientCreation(s) => {\n\n // Rewrite error message to provide Materialize-specific guidance.\n\n if s == \"Invalid sasl.kerberos.kinit.cmd value: Property \\\n", "file_path": "src/sql/src/kafka_util.rs", "rank": 83, "score": 335940.046651262 }, { "content": "fn plan_table_alias(mut scope: Scope, alias: Option<&TableAlias>) -> Result<Scope, anyhow::Error> {\n\n if let Some(TableAlias {\n\n name,\n\n columns,\n\n strict,\n\n }) = alias\n\n {\n\n if (columns.len() > scope.items.len()) || (*strict && columns.len() != scope.items.len()) {\n\n bail!(\n\n \"{} has {} columns available but {} columns specified\",\n\n name,\n\n scope.items.len(),\n\n columns.len()\n\n );\n\n }\n\n\n\n let table_name = normalize::ident(name.to_owned());\n\n for (i, item) in scope.items.iter_mut().enumerate() {\n\n let column_name = columns\n\n .get(i)\n", "file_path": "src/sql/src/plan/query.rs", "rank": 84, "score": 335532.89723140985 }, { "content": "fn parse_bytes_traditional(s: &str) -> Result<Vec<u8>, ParseError> {\n\n // Bytes are interpreted literally, save for the special escape sequences\n\n // \"\\\\\", which represents a single backslash, and \"\\NNN\", where each N\n\n // is an octal digit, which represents the byte whose octal value is NNN.\n\n let mut out = Vec::new();\n\n let mut bytes = s.as_bytes().iter().fuse();\n\n while let Some(&b) = bytes.next() {\n\n if b != b'\\\\' {\n\n out.push(b);\n\n continue;\n\n }\n\n match bytes.next() {\n\n None => {\n\n return Err(ParseError::new(\"bytea\", s).with_details(\"ends with escape character\"))\n\n }\n\n Some(b'\\\\') => out.push(b'\\\\'),\n\n b => match (b, bytes.next(), bytes.next()) {\n\n (Some(d2 @ b'0'..=b'3'), Some(d1 @ b'0'..=b'7'), Some(d0 @ b'0'..=b'7')) => {\n\n out.push(((d2 - b'0') << 6) + ((d1 - b'0') << 3) + (d0 - b'0'));\n\n }\n\n _ => {\n\n return Err(ParseError::new(\"bytea\", s).with_details(\"invalid escape sequence\"))\n\n }\n\n },\n\n }\n\n }\n\n Ok(out)\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 85, "score": 335317.77608261537 }, { "content": "/// Construct a Batch that depends on `state`\n\n///\n\n/// In particular this will have somewhat sensible values for all fields, and\n\n/// will be the next time slice after `state.last_time`, incrementing `last_time` to now\n\npub fn random_batch(rng: &mut impl Rng, state: &mut RecordState) -> Batch {\n\n let id = Uuid::new_v4();\n\n\n\n let dur_val = rng.gen_range(15..1_000);\n\n let dur = chrono::Duration::seconds(dur_val);\n\n let interval_start_time = state.last_time.clone();\n\n let interval_start = protobuf_timestamp(state.last_time);\n\n state.last_time = state.last_time.checked_add_signed(dur).unwrap();\n\n let interval_end = protobuf_timestamp(state.last_time);\n\n\n\n let mut records = RepeatedField::<Record>::new();\n\n\n\n for _ in 0..rng.gen_range(1..50) {\n\n records.push(random_record(rng, interval_start_time, dur_val));\n\n }\n\n\n\n let mut batch = Batch::new();\n\n batch.set_id(id.to_string());\n\n batch.set_interval_start(interval_start);\n\n batch.set_interval_end(interval_end);\n\n batch.set_records(records);\n\n\n\n batch\n\n}\n\n\n", "file_path": "demo/billing/src/randomizer.rs", "rank": 86, "score": 334502.7260672471 }, { "content": "/// Parses a `NaiveTime` from `s`, using the following grammar.\n\n///\n\n/// ```text\n\n/// <time value> ::=\n\n/// <hours value> <colon> <minutes value> <colon> <seconds integer value>\n\n/// [ <period> [ <seconds fraction> ] ]\n\n/// ```\n\npub fn parse_time(s: &str) -> Result<NaiveTime, ParseError> {\n\n ParsedDateTime::build_parsed_datetime_time(&s)\n\n .and_then(|pdt| pdt.compute_time())\n\n .map_err(|e| ParseError::new(\"time\", s).with_details(e))\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 87, "score": 334291.511457441 }, { "content": "/// Parses a [`NaiveDate`] from `s`.\n\npub fn parse_date(s: &str) -> Result<NaiveDate, ParseError> {\n\n match parse_timestamp_string(s) {\n\n Ok((date, _, _)) => Ok(date),\n\n Err(e) => Err(ParseError::new(\"date\", s).with_details(e)),\n\n }\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 88, "score": 334285.6314793817 }, { "content": "pub fn csv_extract(a: Datum, n_cols: usize) -> Vec<(Row, Diff)> {\n\n let bytes = a.unwrap_str().as_bytes();\n\n let mut row_packer = RowPacker::new();\n\n let mut csv_reader = csv::ReaderBuilder::new()\n\n .has_headers(false)\n\n .from_reader(bytes);\n\n csv_reader\n\n .records()\n\n .filter_map(|res| match res {\n\n Ok(sr) if sr.len() == n_cols => {\n\n Some((row_packer.pack(sr.iter().map(|s| Datum::String(s))), 1))\n\n }\n\n _ => None,\n\n })\n\n .collect()\n\n}\n\n\n", "file_path": "src/expr/src/relation/func.rs", "rank": 89, "score": 331562.49330322066 }, { "content": "fn write_records<W>(writer: &mut Writer<W>, records: &[String]) -> Result<(), String>\n\nwhere\n\n W: Write,\n\n{\n\n let schema = writer.schema().clone();\n\n for record in records {\n\n let record = avro::from_json(\n\n &serde_json::from_str(record).map_err(|e| format!(\"parsing avro datum: {}\", e))?,\n\n schema.top_node(),\n\n )?;\n\n writer\n\n .append(record)\n\n .map_err(|e| format!(\"writing avro record: {}\", e))?;\n\n }\n\n writer\n\n .flush()\n\n .map_err(|e| format!(\"flushing avro writer: {}\", e))?;\n\n Ok(())\n\n}\n\n\n\npub struct VerifyAction {\n\n sink: String,\n\n expected: Vec<String>,\n\n}\n\n\n", "file_path": "src/testdrive/src/action/avro_ocf.rs", "rank": 90, "score": 331412.9982128479 }, { "content": "fn build_compression(cmd: &mut BuiltinCommand) -> Result<Compression, String> {\n\n match cmd.args.opt_string(\"compression\") {\n\n Some(s) => s.parse(),\n\n None => Ok(Compression::None),\n\n }\n\n}\n\n\n", "file_path": "src/testdrive/src/action/file.rs", "rank": 91, "score": 331112.4222867277 }, { "content": "pub fn load_config(config_path: Option<&str>, cli_queries: Option<&str>) -> Result<Config> {\n\n let conf = load_raw_config(config_path);\n\n\n\n // Get everything into the normalized QueryGroup representation\n\n let mut config = Config::try_from(conf)?;\n\n\n\n // filter to only things enabled in the command line OR the config file\n\n //\n\n // TODO: consider if this would be better to just flip the enabled flag to true/false and retail everthing\n\n if let Some(queries) = cli_queries {\n\n let enabled_qs: Vec<_> = queries.split(',').collect();\n\n if !enabled_qs.is_empty() {\n\n debug!(\"filtering to queries: {:?}\", enabled_qs);\n\n config.groups = config\n\n .groups\n\n .into_iter()\n\n .filter(|qg| enabled_qs.contains(&&*qg.name))\n\n .collect();\n\n }\n\n } else {\n", "file_path": "src/peeker/src/args.rs", "rank": 92, "score": 330833.2102230454 }, { "content": "/// Parses a `NaiveDateTime` from `s`.\n\npub fn parse_timestamp(s: &str) -> Result<NaiveDateTime, ParseError> {\n\n match parse_timestamp_string(s) {\n\n Ok((date, time, _)) => Ok(date.and_time(time)),\n\n Err(e) => Err(ParseError::new(\"timestamp\", s).with_details(e)),\n\n }\n\n}\n\n\n", "file_path": "src/repr/src/strconv.rs", "rank": 93, "score": 330455.59353184653 }, { "content": "fn validate_fields<'a, I>(items: &BTreeMap<String, Item>, fields: I) -> Result<()>\n\nwhere\n\n I: IntoIterator<Item = &'a Field>,\n\n{\n\n for f in fields {\n\n match &f.ty {\n\n Type::Local(s) if !items.contains_key(s) => {\n\n bail!(\n\n \"Unable to analyze non built-in type that is not defined in input: {}\",\n\n s\n\n );\n\n }\n\n _ => (),\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "src/walkabout/src/ir.rs", "rank": 94, "score": 329433.68434142275 }, { "content": "/// Parse a query result type string into a vec of expected types\n\nfn parse_types(input: &str) -> Result<Vec<Type>, anyhow::Error> {\n\n input\n\n .chars()\n\n .map(|char| {\n\n Ok(match char {\n\n 'T' => Type::Text,\n\n 'I' => Type::Integer,\n\n 'R' => Type::Real,\n\n 'B' => Type::Bool,\n\n 'O' => Type::Oid,\n\n _ => bail!(\"Unexpected type char {} in: {}\", char, input),\n\n })\n\n })\n\n .collect()\n\n}\n\n\n\nlazy_static! {\n\n static ref WHITESPACE_REGEX: Regex = Regex::new(r\"\\s+\").unwrap();\n\n}\n\n\n", "file_path": "src/sqllogictest/src/parser.rs", "rank": 95, "score": 329185.7753582112 }, { "content": "fn split_at<'a>(input: &mut &'a str, sep: &Regex) -> Result<&'a str, anyhow::Error> {\n\n match sep.find(input) {\n\n Some(found) => {\n\n let result = &input[..found.start()];\n\n *input = &input[found.end()..];\n\n Ok(result)\n\n }\n\n None => bail!(\"Couldn't split {:?} at {:?}\", input, sep),\n\n }\n\n}\n\n\n", "file_path": "src/sqllogictest/src/parser.rs", "rank": 96, "score": 328341.53047118156 }, { "content": "/// Use the following grammar to parse `s` into:\n\n///\n\n/// - `NaiveDate`\n\n/// - `NaiveTime`\n\n/// - Timezone string\n\n///\n\n/// `NaiveDate` and `NaiveTime` are appropriate to compute a `NaiveDateTime`,\n\n/// which can be used in conjunction with a timezone string to generate a\n\n/// `DateTime<Utc>`.\n\n///\n\n/// ```text\n\n/// <unquoted timestamp string> ::=\n\n/// <date value> <space> <time value> [ <time zone interval> ]\n\n/// <date value> ::=\n\n/// <years value> <minus sign> <months value> <minus sign> <days value>\n\n/// <time zone interval> ::=\n\n/// <sign> <hours value> <colon> <minutes value>\n\n/// ```\n\nfn parse_timestamp_string(s: &str) -> Result<(NaiveDate, NaiveTime, datetime::Timezone), String> {\n\n if s.is_empty() {\n\n return Err(\"timestamp string is empty\".into());\n\n }\n\n\n\n // PostgreSQL special date-time inputs\n\n // https://www.postgresql.org/docs/12/datatype-datetime.html#id-1.5.7.13.18.8\n\n // We should add support for other values here, e.g. infinity\n\n // which @quodlibetor is willing to add to the chrono package.\n\n if s == \"epoch\" {\n\n return Ok((\n\n NaiveDate::from_ymd(1970, 1, 1),\n\n NaiveTime::from_hms(0, 0, 0),\n\n Default::default(),\n\n ));\n\n }\n\n\n\n let (ts_string, tz_string) = datetime::split_timestamp_string(s);\n\n\n\n let pdt = ParsedDateTime::build_parsed_datetime_timestamp(&ts_string)?;\n", "file_path": "src/repr/src/strconv.rs", "rank": 97, "score": 327388.29041036486 }, { "content": "fn build_timezone_offset_second(tokens: &[TimeStrToken], value: &str) -> Result<Timezone, String> {\n\n use TimeStrToken::*;\n\n let all_formats = [\n\n vec![Plus, Num(0, 1), Colon, Num(0, 1), Colon, Num(0, 1)],\n\n vec![Dash, Num(0, 1), Colon, Num(0, 1), Colon, Num(0, 1)],\n\n vec![Plus, Num(0, 1), Colon, Num(0, 1)],\n\n vec![Dash, Num(0, 1), Colon, Num(0, 1)],\n\n vec![Plus, Num(0, 1), Num(0, 1), Num(0, 1)],\n\n vec![Dash, Num(0, 1), Num(0, 1), Num(0, 1)],\n\n vec![Plus, Num(0, 1), Num(0, 1)],\n\n vec![Dash, Num(0, 1), Num(0, 1)],\n\n vec![Plus, Num(0, 1)],\n\n vec![Dash, Num(0, 1)],\n\n vec![TzName(\"\".to_string())],\n\n vec![Zulu],\n\n ];\n\n\n\n let mut is_positive = true;\n\n let mut hour_offset: Option<i64> = None;\n\n let mut minute_offset: Option<i64> = None;\n", "file_path": "src/repr/src/adt/datetime.rs", "rank": 98, "score": 326518.702444886 }, { "content": "pub fn build(cmds: Vec<PosCommand>, state: &State) -> Result<Vec<PosAction>, Error> {\n\n let mut out = Vec::new();\n\n let mut vars = HashMap::new();\n\n let mut sql_timeout = DEFAULT_SQL_TIMEOUT;\n\n\n\n vars.insert(\"testdrive.kafka-addr\".into(), state.kafka_addr.clone());\n\n vars.insert(\n\n \"testdrive.kafka-addr-resolved\".into(),\n\n state\n\n .kafka_addr\n\n .to_socket_addrs()\n\n .ok()\n\n .and_then(|mut addrs| addrs.next())\n\n .map(|addr| addr.to_string())\n\n .unwrap_or_else(|| \"#RESOLUTION-FAILURE#\".into()),\n\n );\n\n vars.insert(\n\n \"testdrive.schema-registry-url\".into(),\n\n state.schema_registry_url.to_string(),\n\n );\n", "file_path": "src/testdrive/src/action.rs", "rank": 99, "score": 326107.91547184635 } ]
Rust
matrix_sdk_appservice/tests/tests.rs
DevinR528/matrix-rust-sdk
4c09c6272bb3636e20d99177357cd31b80a2c1bf
use std::env; use matrix_sdk::{ api_appservice, api_appservice::Registration, async_trait, events::{room::member::MemberEventContent, AnyEvent, AnyStateEvent, SyncStateEvent}, room::Room, EventHandler, Raw, }; use matrix_sdk_appservice::*; use matrix_sdk_test::async_test; use serde_json::json; fn registration_string() -> String { include_str!("../tests/registration.yaml").to_owned() } async fn appservice(registration: Option<Registration>) -> Result<Appservice> { env::set_var("RUST_LOG", "mockito=debug,matrix_sdk=debug"); let _ = tracing_subscriber::fmt::try_init(); let registration = match registration { Some(registration) => registration.into(), None => AppserviceRegistration::try_from_yaml_str(registration_string()).unwrap(), }; let homeserver_url = mockito::server_url(); let server_name = "localhost"; Ok(Appservice::new(homeserver_url.as_ref(), server_name, registration).await?) } fn member_json() -> serde_json::Value { json!({ "content": { "avatar_url": null, "displayname": "example", "membership": "join" }, "event_id": "$151800140517rfvjc:localhost", "membership": "join", "origin_server_ts": 151800140, "room_id": "!ahpSDaDUPCCqktjUEF:localhost", "sender": "@example:localhost", "state_key": "@example:localhost", "type": "m.room.member", "prev_content": { "avatar_url": null, "displayname": "example", "membership": "invite" }, "unsigned": { "age": 297036, "replaces_state": "$151800111315tsynI:localhost" } }) } #[async_test] async fn test_event_handler() -> Result<()> { let appservice = appservice(None).await?; struct Example {} impl Example { pub fn new() -> Self { Self {} } } #[async_trait] impl EventHandler for Example { async fn on_state_member(&self, room: Room, event: &SyncStateEvent<MemberEventContent>) { dbg!(room, event); } } appservice .client() .set_event_handler(Box::new(Example::new())) .await; let event = serde_json::from_value::<AnyStateEvent>(member_json()).unwrap(); let event: Raw<AnyEvent> = AnyEvent::State(event).into(); let events = vec![event]; let incoming = api_appservice::event::push_events::v1::IncomingRequest::new( "any_txn_id".to_owned(), events, ); appservice.client().receive_transaction(incoming).await?; Ok(()) } #[async_test] async fn test_transaction() -> Result<()> { let appservice = appservice(None).await?; let event = serde_json::from_value::<AnyStateEvent>(member_json()).unwrap(); let event: Raw<AnyEvent> = AnyEvent::State(event).into(); let events = vec![event]; let incoming = api_appservice::event::push_events::v1::IncomingRequest::new( "any_txn_id".to_owned(), events, ); appservice.client().receive_transaction(incoming).await?; Ok(()) } #[async_test] async fn test_verify_hs_token() -> Result<()> { let appservice = appservice(None).await?; let registration = appservice.registration(); assert!(appservice.hs_token_matches(&registration.hs_token)); Ok(()) } mod registration { use super::*; #[test] fn test_registration() -> Result<()> { let registration: Registration = serde_yaml::from_str(&registration_string())?; let registration: AppserviceRegistration = registration.into(); assert_eq!(registration.id, "appservice"); Ok(()) } #[test] fn test_registration_from_yaml_file() -> Result<()> { let registration = AppserviceRegistration::try_from_yaml_file("./tests/registration.yaml")?; assert_eq!(registration.id, "appservice"); Ok(()) } #[test] fn test_registration_from_yaml_str() -> Result<()> { let registration = AppserviceRegistration::try_from_yaml_str(registration_string())?; assert_eq!(registration.id, "appservice"); Ok(()) } }
use std::env; use matrix_sdk::{ api_appservice, api_appservice::Registration, async_trait, events::{room::member::MemberEventContent, AnyEvent, AnyStateEvent, SyncStateEvent}, room::Room, EventHandler, Raw, }; use matrix_sdk_appservice::*; use matrix_sdk_test::async_test; use serde_json::json; fn registration_string() -> String { include_str!("../tests/registration.yaml").to_owned() } async fn appservice(registration: Option<Registration>) -> Result<Appservice> { env::set_var("RUST_LOG", "mockito=debug,matrix_sdk=debug"); let _ = tracing_subscriber::fmt::try_init(); let registration =
; let homeserver_url = mockito::server_url(); let server_name = "localhost"; Ok(Appservice::new(homeserver_url.as_ref(), server_name, registration).await?) } fn member_json() -> serde_json::Value { json!({ "content": { "avatar_url": null, "displayname": "example", "membership": "join" }, "event_id": "$151800140517rfvjc:localhost", "membership": "join", "origin_server_ts": 151800140, "room_id": "!ahpSDaDUPCCqktjUEF:localhost", "sender": "@example:localhost", "state_key": "@example:localhost", "type": "m.room.member", "prev_content": { "avatar_url": null, "displayname": "example", "membership": "invite" }, "unsigned": { "age": 297036, "replaces_state": "$151800111315tsynI:localhost" } }) } #[async_test] async fn test_event_handler() -> Result<()> { let appservice = appservice(None).await?; struct Example {} impl Example { pub fn new() -> Self { Self {} } } #[async_trait] impl EventHandler for Example { async fn on_state_member(&self, room: Room, event: &SyncStateEvent<MemberEventContent>) { dbg!(room, event); } } appservice .client() .set_event_handler(Box::new(Example::new())) .await; let event = serde_json::from_value::<AnyStateEvent>(member_json()).unwrap(); let event: Raw<AnyEvent> = AnyEvent::State(event).into(); let events = vec![event]; let incoming = api_appservice::event::push_events::v1::IncomingRequest::new( "any_txn_id".to_owned(), events, ); appservice.client().receive_transaction(incoming).await?; Ok(()) } #[async_test] async fn test_transaction() -> Result<()> { let appservice = appservice(None).await?; let event = serde_json::from_value::<AnyStateEvent>(member_json()).unwrap(); let event: Raw<AnyEvent> = AnyEvent::State(event).into(); let events = vec![event]; let incoming = api_appservice::event::push_events::v1::IncomingRequest::new( "any_txn_id".to_owned(), events, ); appservice.client().receive_transaction(incoming).await?; Ok(()) } #[async_test] async fn test_verify_hs_token() -> Result<()> { let appservice = appservice(None).await?; let registration = appservice.registration(); assert!(appservice.hs_token_matches(&registration.hs_token)); Ok(()) } mod registration { use super::*; #[test] fn test_registration() -> Result<()> { let registration: Registration = serde_yaml::from_str(&registration_string())?; let registration: AppserviceRegistration = registration.into(); assert_eq!(registration.id, "appservice"); Ok(()) } #[test] fn test_registration_from_yaml_file() -> Result<()> { let registration = AppserviceRegistration::try_from_yaml_file("./tests/registration.yaml")?; assert_eq!(registration.id, "appservice"); Ok(()) } #[test] fn test_registration_from_yaml_str() -> Result<()> { let registration = AppserviceRegistration::try_from_yaml_str(registration_string())?; assert_eq!(registration.id, "appservice"); Ok(()) } }
match registration { Some(registration) => registration.into(), None => AppserviceRegistration::try_from_yaml_str(registration_string()).unwrap(), }
if_condition
[ { "content": "fn encode_key_info(info: &RequestedKeyInfo) -> String {\n\n format!(\n\n \"{}{}{}{}\",\n\n info.room_id, info.sender_key, info.algorithm, info.session_id\n\n )\n\n}\n\n\n\n/// An in-memory only store that will forget all the E2EE key once it's dropped.\n\n#[derive(Debug, Clone)]\n\npub struct MemoryStore {\n\n sessions: SessionStore,\n\n inbound_group_sessions: GroupSessionStore,\n\n tracked_users: Arc<DashSet<UserId>>,\n\n users_for_key_query: Arc<DashSet<UserId>>,\n\n olm_hashes: Arc<DashMap<String, DashSet<String>>>,\n\n devices: DeviceStore,\n\n identities: Arc<DashMap<UserId, UserIdentities>>,\n\n outgoing_key_requests: Arc<DashMap<Uuid, OutgoingKeyRequest>>,\n\n key_requests_by_info: Arc<DashMap<String, Uuid>>,\n\n}\n", "file_path": "matrix_sdk_crypto/src/store/memorystore.rs", "rank": 1, "score": 106905.96083876619 }, { "content": "/// Encode the input as base64 with no padding.\n\npub fn encode(input: impl AsRef<[u8]>) -> String {\n\n encode_config(input, STANDARD_NO_PAD)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/utilities.rs", "rank": 2, "score": 101866.62524065425 }, { "content": "/// Encode the input as URL safe base64 with no padding.\n\npub fn encode_url_safe(input: impl AsRef<[u8]>) -> String {\n\n encode_config(input, URL_SAFE_NO_PAD)\n\n}\n", "file_path": "matrix_sdk_crypto/src/utilities.rs", "rank": 3, "score": 98328.9389198208 }, { "content": "/// Get the extra info that will be used when we generate a MAC and need to send\n\n/// it out\n\n///\n\n/// # Arguments\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\nfn extra_mac_info_send(ids: &SasIds, flow_id: &str) -> String {\n\n format!(\n\n \"MATRIX_KEY_VERIFICATION_MAC{first_user}{first_device}\\\n\n {second_user}{second_device}{transaction_id}\",\n\n first_user = ids.account.user_id(),\n\n first_device = ids.account.device_id(),\n\n second_user = ids.other_device.user_id(),\n\n second_device = ids.other_device.device_id(),\n\n transaction_id = flow_id,\n\n )\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 4, "score": 94484.84519147518 }, { "content": "/// Get the extra info that will be used when we check the MAC of a\n\n/// m.key.verification.key event.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\nfn extra_mac_info_receive(ids: &SasIds, flow_id: &str) -> String {\n\n format!(\n\n \"MATRIX_KEY_VERIFICATION_MAC{first_user}{first_device}\\\n\n {second_user}{second_device}{transaction_id}\",\n\n first_user = ids.other_device.user_id(),\n\n first_device = ids.other_device.device_id(),\n\n second_user = ids.account.user_id(),\n\n second_device = ids.account.device_id(),\n\n transaction_id = flow_id,\n\n )\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 5, "score": 94484.78876912163 }, { "content": "fn decrypt_helper(ciphertext: &str, passphrase: &str) -> Result<String, KeyExportError> {\n\n let decoded = decode(ciphertext)?;\n\n\n\n let mut decoded = Cursor::new(decoded);\n\n\n\n let mut salt = [0u8; SALT_SIZE];\n\n let mut iv = [0u8; IV_SIZE];\n\n let mut mac = [0u8; MAC_SIZE];\n\n let mut derived_keys = [0u8; KEY_SIZE * 2];\n\n\n\n let version = decoded.read_u8()?;\n\n decoded.read_exact(&mut salt)?;\n\n decoded.read_exact(&mut iv)?;\n\n\n\n let rounds = decoded.read_u32::<BigEndian>()?;\n\n let ciphertext_start = decoded.position() as usize;\n\n\n\n decoded.seek(SeekFrom::End(-32))?;\n\n let ciphertext_end = decoded.position() as usize;\n\n\n", "file_path": "matrix_sdk_crypto/src/file_encryption/key_export.rs", "rank": 6, "score": 88799.20316395327 }, { "content": "/// Calculate the commitment for a accept event from the public key and the\n\n/// start event.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `public_key` - Our own ephemeral public key that is used for the\n\n/// interactive verification.\n\n///\n\n/// * `content` - The `m.key.verification.start` event content that started the\n\n/// interactive verification process.\n\npub fn calculate_commitment(public_key: &str, content: impl Into<StartContent>) -> String {\n\n let content = content.into().canonical_json();\n\n let content_string = content.to_string();\n\n\n\n encode(\n\n Sha256::new()\n\n .chain(&public_key)\n\n .chain(&content_string)\n\n .finalize(),\n\n )\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 7, "score": 88508.0042437517 }, { "content": "fn encrypt_helper(mut plaintext: &mut [u8], passphrase: &str, rounds: u32) -> String {\n\n let mut salt = [0u8; SALT_SIZE];\n\n let mut iv = [0u8; IV_SIZE];\n\n let mut derived_keys = [0u8; KEY_SIZE * 2];\n\n\n\n getrandom(&mut salt).expect(\"Can't generate randomness\");\n\n getrandom(&mut iv).expect(\"Can't generate randomness\");\n\n\n\n let mut iv = u128::from_be_bytes(iv);\n\n iv &= !(1 << 63);\n\n\n\n pbkdf2::<Hmac<Sha512>>(passphrase.as_bytes(), &salt, rounds, &mut derived_keys);\n\n let (key, hmac_key) = derived_keys.split_at(KEY_SIZE);\n\n\n\n let mut aes = Aes256Ctr::new_var(&key, &iv.to_be_bytes()).expect(\"Can't create AES object\");\n\n\n\n aes.apply_keystream(&mut plaintext);\n\n\n\n let mut payload: Vec<u8> = vec![];\n\n\n", "file_path": "matrix_sdk_crypto/src/file_encryption/key_export.rs", "rank": 8, "score": 85665.05362038926 }, { "content": "#[proc_macro_attribute]\n\npub fn async_test(_attr: TokenStream, item: TokenStream) -> TokenStream {\n\n let attrs = r#\"\n\n #[cfg_attr(target_arch = \"wasm32\", wasm_bindgen_test)]\n\n #[cfg_attr(not(target_arch = \"wasm32\"), tokio::test)]\n\n \"#;\n\n\n\n let mut out: TokenStream = attrs.parse().unwrap();\n\n out.extend(item);\n\n out\n\n}\n", "file_path": "matrix_sdk_test_macros/src/lib.rs", "rank": 9, "score": 80684.6718927122 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\nfn main() {\n\n panic!(\"This example doesn't run on WASM\");\n\n}\n", "file_path": "matrix_sdk_base/examples/state_inspector.rs", "rank": 10, "score": 68463.50184412184 }, { "content": "fn hoist_member_event(\n\n event: &Raw<StateEvent<MemberEventContent>>,\n\n) -> StdResult<StateEvent<MemberEventContent>, serde_json::Error> {\n\n let prev_content = serde_json::from_str::<AdditionalEventData>(event.json().get())?\n\n .unsigned\n\n .prev_content;\n\n\n\n let mut e = event.deserialize()?;\n\n\n\n if e.prev_content.is_none() {\n\n e.prev_content = prev_content.and_then(|e| e.deserialize().ok());\n\n }\n\n\n\n Ok(e)\n\n}\n\n\n", "file_path": "matrix_sdk_base/src/client.rs", "rank": 11, "score": 67297.7674036298 }, { "content": "/// Get the extra info that will be used when we generate bytes for the short\n\n/// auth string.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// * `we_started` - Flag signaling if the SAS process was started on our side.\n\nfn extra_info_sas(\n\n ids: &SasIds,\n\n own_pubkey: &str,\n\n their_pubkey: &str,\n\n flow_id: &str,\n\n we_started: bool,\n\n) -> String {\n\n let our_info = format!(\n\n \"{}|{}|{}\",\n\n ids.account.user_id(),\n\n ids.account.device_id(),\n\n own_pubkey\n\n );\n\n let their_info = format!(\n\n \"{}|{}|{}\",\n\n ids.other_device.user_id(),\n\n ids.other_device.device_id(),\n\n their_pubkey\n\n );\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 12, "score": 65153.505103902426 }, { "content": "fn hoist_room_event_prev_content(\n\n event: &Raw<AnySyncRoomEvent>,\n\n) -> StdResult<AnySyncRoomEvent, serde_json::Error> {\n\n let prev_content = serde_json::from_str::<AdditionalEventData>(event.json().get())\n\n .map(|more_unsigned| more_unsigned.unsigned)\n\n .map(|additional| additional.prev_content)?\n\n .and_then(|p| p.deserialize().ok());\n\n\n\n let mut ev = event.deserialize()?;\n\n\n\n match &mut ev {\n\n AnySyncRoomEvent::State(AnySyncStateEvent::RoomMember(ref mut member))\n\n if member.prev_content.is_none() =>\n\n {\n\n member.prev_content = prev_content;\n\n }\n\n _ => (),\n\n }\n\n\n\n Ok(ev)\n", "file_path": "matrix_sdk_base/src/client.rs", "rank": 13, "score": 65143.969692301456 }, { "content": "fn wrap_key_request_content(\n\n recipient: UserId,\n\n id: Uuid,\n\n content: &RoomKeyRequestToDeviceEventContent,\n\n) -> Result<OutgoingRequest, serde_json::Error> {\n\n let mut messages = BTreeMap::new();\n\n\n\n messages\n\n .entry(recipient)\n\n .or_insert_with(BTreeMap::new)\n\n .insert(DeviceIdOrAllDevices::AllDevices, to_raw_value(content)?);\n\n\n\n Ok(OutgoingRequest {\n\n request_id: id,\n\n request: Arc::new(\n\n ToDeviceRequest {\n\n event_type: EventType::RoomKeyRequest,\n\n txn_id: id,\n\n messages,\n\n }\n", "file_path": "matrix_sdk_crypto/src/key_request.rs", "rank": 14, "score": 65143.969692301456 }, { "content": "fn criterion() -> Criterion {\n\n #[cfg(target_os = \"linux\")]\n\n let criterion = Criterion::default().with_profiler(perf::FlamegraphProfiler::new(100));\n\n #[cfg(not(target_os = \"linux\"))]\n\n let criterion = Criterion::default();\n\n\n\n criterion\n\n}\n\n\n\ncriterion_group! {\n\n name = benches;\n\n config = criterion();\n\n targets = keys_query, keys_claiming, room_key_sharing, devices_missing_sessions_collecting,\n\n}\n\ncriterion_main!(benches);\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 15, "score": 63635.075963142226 }, { "content": "/// Get the decimal version of the short authentication string.\n\n///\n\n/// Returns a tuple containing three 4 digit integer numbers that represent\n\n/// the short auth string.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `sas` - The Olm SAS object that can be used to generate bytes using the\n\n/// shared secret.\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// * `we_started` - Flag signaling if the SAS process was started on our side.\n\n///\n\n/// # Panics\n\n///\n\n/// This will panic if the public key of the other side wasn't set.\n\npub fn get_decimal(\n\n sas: &OlmSas,\n\n ids: &SasIds,\n\n their_pubkey: &str,\n\n flow_id: &str,\n\n we_started: bool,\n\n) -> (u16, u16, u16) {\n\n let bytes = sas\n\n .generate_bytes(\n\n &extra_info_sas(&ids, &sas.public_key(), their_pubkey, &flow_id, we_started),\n\n 5,\n\n )\n\n .expect(\"Can't generate bytes\");\n\n\n\n bytes_to_decimal(bytes)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 16, "score": 61491.35566602483 }, { "content": "/// Get the emoji version of the short authentication string.\n\n///\n\n/// Returns seven tuples where the first element is the emoji and the\n\n/// second element the English description of the emoji.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `sas` - The Olm SAS object that can be used to generate bytes using the\n\n/// shared secret.\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// * `we_started` - Flag signaling if the SAS process was started on our side.\n\n///\n\n/// # Panics\n\n///\n\n/// This will panic if the public key of the other side wasn't set.\n\npub fn get_emoji(\n\n sas: &OlmSas,\n\n ids: &SasIds,\n\n their_pubkey: &str,\n\n flow_id: &str,\n\n we_started: bool,\n\n) -> [(&'static str, &'static str); 7] {\n\n let bytes = sas\n\n .generate_bytes(\n\n &extra_info_sas(&ids, &sas.public_key(), their_pubkey, &flow_id, we_started),\n\n 6,\n\n )\n\n .expect(\"Can't generate bytes\");\n\n\n\n bytes_to_emoji(bytes)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 17, "score": 61490.116760000965 }, { "content": "/// Transform state event by hoisting `prev_content` field from `unsigned` to the top level.\n\n///\n\n/// Due to a [bug in synapse][synapse-bug], `prev_content` often ends up in `unsigned` contrary to\n\n/// the C2S spec. Some more discussion can be found [here][discussion]. Until this is fixed in\n\n/// synapse or handled in Ruma, we use this to hoist up `prev_content` to the top level.\n\n///\n\n/// [synapse-bug]: <https://github.com/matrix-org/matrix-doc/issues/684#issuecomment-641182668>\n\n/// [discussion]: <https://github.com/matrix-org/matrix-doc/issues/684#issuecomment-641182668>\n\npub fn hoist_and_deserialize_state_event(\n\n event: &Raw<AnySyncStateEvent>,\n\n) -> StdResult<AnySyncStateEvent, serde_json::Error> {\n\n let prev_content = serde_json::from_str::<AdditionalEventData>(event.json().get())?\n\n .unsigned\n\n .prev_content;\n\n\n\n let mut ev = event.deserialize()?;\n\n\n\n if let AnySyncStateEvent::RoomMember(ref mut member) = ev {\n\n if member.prev_content.is_none() {\n\n member.prev_content = prev_content.and_then(|e| e.deserialize().ok());\n\n }\n\n }\n\n\n\n Ok(ev)\n\n}\n\n\n", "file_path": "matrix_sdk_base/src/client.rs", "rank": 18, "score": 61484.728305650744 }, { "content": "fn alice_id() -> UserId {\n\n user_id!(\"@alice:example.org\")\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 19, "score": 61481.27825181388 }, { "content": "pub fn content_to_request(\n\n recipient: &UserId,\n\n recipient_device: &DeviceId,\n\n content: AnyToDeviceEventContent,\n\n) -> ToDeviceRequest {\n\n let mut messages = BTreeMap::new();\n\n let mut user_messages = BTreeMap::new();\n\n\n\n user_messages.insert(\n\n DeviceIdOrAllDevices::DeviceId(recipient_device.into()),\n\n serde_json::value::to_raw_value(&content).expect(\"Can't serialize to-device content\"),\n\n );\n\n messages.insert(recipient.clone(), user_messages);\n\n\n\n let event_type = match content {\n\n AnyToDeviceEventContent::KeyVerificationAccept(_) => EventType::KeyVerificationAccept,\n\n AnyToDeviceEventContent::KeyVerificationStart(_) => EventType::KeyVerificationStart,\n\n AnyToDeviceEventContent::KeyVerificationKey(_) => EventType::KeyVerificationKey,\n\n AnyToDeviceEventContent::KeyVerificationMac(_) => EventType::KeyVerificationMac,\n\n AnyToDeviceEventContent::KeyVerificationCancel(_) => EventType::KeyVerificationCancel,\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 20, "score": 61481.27825181388 }, { "content": "/// Get the index of the emoji of the short authentication string.\n\n///\n\n/// Returns seven u8 numbers in the range from 0 to 63 inclusive, those numbers\n\n/// can be converted to a unique emoji defined by the spec using the\n\n/// [emoji_from_index](#method.emoji_from_index) method.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `sas` - The Olm SAS object that can be used to generate bytes using the\n\n/// shared secret.\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// * `we_started` - Flag signaling if the SAS process was started on our side.\n\n///\n\n/// # Panics\n\n///\n\n/// This will panic if the public key of the other side wasn't set.\n\npub fn get_emoji_index(\n\n sas: &OlmSas,\n\n ids: &SasIds,\n\n their_pubkey: &str,\n\n flow_id: &str,\n\n we_started: bool,\n\n) -> [u8; 7] {\n\n let bytes = sas\n\n .generate_bytes(\n\n &extra_info_sas(&ids, &sas.public_key(), their_pubkey, &flow_id, we_started),\n\n 6,\n\n )\n\n .expect(\"Can't generate bytes\");\n\n\n\n bytes_to_emoji_index(bytes)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 21, "score": 60493.301442018506 }, { "content": "/// Get the content for a m.key.verification.mac event.\n\n///\n\n/// Returns a tuple that contains the list of verified devices and the list of\n\n/// verified master keys.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `sas` - The Olm SAS object that can be used to MACs\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// * `event` - The m.key.verification.mac event that was sent to us by\n\n/// the other side.\n\npub fn receive_mac_event(\n\n sas: &OlmSas,\n\n ids: &SasIds,\n\n flow_id: &str,\n\n sender: &UserId,\n\n content: &MacContent,\n\n) -> Result<(Vec<ReadOnlyDevice>, Vec<UserIdentities>), CancelCode> {\n\n let mut verified_devices = Vec::new();\n\n let mut verified_identities = Vec::new();\n\n\n\n let info = extra_mac_info_receive(&ids, flow_id);\n\n\n\n trace!(\n\n \"Received a key.verification.mac event from {} {}\",\n\n sender,\n\n ids.other_device.device_id()\n\n );\n\n\n\n let mut keys = content.mac().keys().cloned().collect::<Vec<String>>();\n\n keys.sort();\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 22, "score": 60489.345368363574 }, { "content": "fn print_result(sas: &Sas) {\n\n let device = sas.other_device();\n\n\n\n println!(\n\n \"Successfully verified device {} {} {:?}\",\n\n device.user_id(),\n\n device.device_id(),\n\n device.local_trust_state()\n\n );\n\n}\n\n\n\nasync fn print_devices(user_id: &UserId, client: &Client) {\n\n println!(\"Devices of user {}\", user_id);\n\n\n\n for device in client.get_user_devices(user_id).await.unwrap().devices() {\n\n println!(\n\n \" {:<10} {:<30} {:<}\",\n\n device.device_id(),\n\n device.display_name().as_deref().unwrap_or_default(),\n\n device.is_trusted()\n", "file_path": "matrix_sdk/examples/emoji_verification.rs", "rank": 23, "score": 59806.666621683995 }, { "content": "pub fn get_scope() -> Scope {\n\n gen_scope(\"/\"). // handle legacy routes\n\n service(gen_scope(\"/_matrix/app/v1\"))\n\n}\n\n\n", "file_path": "matrix_sdk_appservice/src/actix.rs", "rank": 24, "score": 59806.666621683995 }, { "content": "/// Try to decrypt a reader into a list of exported room keys.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `passphrase` - The passphrase that was used to encrypt the exported keys.\n\n///\n\n/// # Examples\n\n/// ```no_run\n\n/// # use std::io::Cursor;\n\n/// # use matrix_sdk_crypto::{OlmMachine, decrypt_key_export};\n\n/// # use matrix_sdk_common::identifiers::user_id;\n\n/// # use futures::executor::block_on;\n\n/// # let alice = user_id!(\"@alice:example.org\");\n\n/// # let machine = OlmMachine::new(&alice, \"DEVICEID\".into());\n\n/// # block_on(async {\n\n/// # let export = Cursor::new(\"\".to_owned());\n\n/// let exported_keys = decrypt_key_export(export, \"1234\").unwrap();\n\n/// machine.import_keys(exported_keys, |_, _| {}).await.unwrap();\n\n/// # });\n\n/// ```\n\npub fn decrypt_key_export(\n\n mut input: impl Read,\n\n passphrase: &str,\n\n) -> Result<Vec<ExportedRoomKey>, KeyExportError> {\n\n let mut x: String = String::new();\n\n\n\n input.read_to_string(&mut x)?;\n\n\n\n if !(x.trim_start().starts_with(HEADER) && x.trim_end().ends_with(FOOTER)) {\n\n return Err(KeyExportError::InvalidHeaders);\n\n }\n\n\n\n let payload: String = x\n\n .lines()\n\n .filter(|l| !(l.starts_with(HEADER) || l.starts_with(FOOTER)))\n\n .collect();\n\n\n\n Ok(serde_json::from_str(&decrypt_helper(\n\n &payload, passphrase,\n\n )?)?)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/file_encryption/key_export.rs", "rank": 25, "score": 59550.17502029041 }, { "content": "/// Encrypt the list of exported room keys using the given passphrase.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `keys` - A list of sessions that should be encrypted.\n\n///\n\n/// * `passphrase` - The passphrase that will be used to encrypt the exported\n\n/// room keys.\n\n///\n\n/// * `rounds` - The number of rounds that should be used for the key\n\n/// derivation when the passphrase gets turned into an AES key. More rounds are\n\n/// increasingly computationally intensive and as such help against bruteforce\n\n/// attacks. Should be at least `10000`, while values in the `100000` ranges\n\n/// should be preferred.\n\n///\n\n/// # Panics\n\n///\n\n/// This method will panic if it can't get enough randomness from the OS to\n\n/// encrypt the exported keys securely.\n\n///\n\n/// # Examples\n\n/// ```no_run\n\n/// # use matrix_sdk_crypto::{OlmMachine, encrypt_key_export};\n\n/// # use matrix_sdk_common::identifiers::{user_id, room_id};\n\n/// # use futures::executor::block_on;\n\n/// # let alice = user_id!(\"@alice:example.org\");\n\n/// # let machine = OlmMachine::new(&alice, \"DEVICEID\".into());\n\n/// # block_on(async {\n\n/// let room_id = room_id!(\"!test:localhost\");\n\n/// let exported_keys = machine.export_keys(|s| s.room_id() == &room_id).await.unwrap();\n\n/// let encrypted_export = encrypt_key_export(&exported_keys, \"1234\", 1);\n\n/// # });\n\n/// ```\n\npub fn encrypt_key_export(\n\n keys: &[ExportedRoomKey],\n\n passphrase: &str,\n\n rounds: u32,\n\n) -> Result<String, SerdeError> {\n\n let mut plaintext = serde_json::to_string(keys)?.into_bytes();\n\n let ciphertext = encrypt_helper(&mut plaintext, passphrase, rounds);\n\n Ok([HEADER.to_owned(), ciphertext, FOOTER.to_owned()].join(\"\\n\"))\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/file_encryption/key_export.rs", "rank": 26, "score": 59549.003658245005 }, { "content": "fn alice_device_id() -> DeviceIdBox {\n\n \"JLAFKJWSCS\".into()\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 27, "score": 59535.74221554248 }, { "content": "fn keys_query_response() -> get_keys::Response {\n\n let data = include_bytes!(\"./keys_query.json\");\n\n let data: Value = serde_json::from_slice(data).unwrap();\n\n let data = response_from_file(&data);\n\n get_keys::Response::try_from_http_response(data).expect(\"Can't parse the keys upload response\")\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 29, "score": 56812.29998617942 }, { "content": "fn keys_claim_response() -> claim_keys::Response {\n\n let data = include_bytes!(\"./keys_claim.json\");\n\n let data: Value = serde_json::from_slice(data).unwrap();\n\n let data = response_from_file(&data);\n\n claim_keys::Response::try_from_http_response(data)\n\n .expect(\"Can't parse the keys upload response\")\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 30, "score": 56812.29998617942 }, { "content": "fn gen_scope(scope: &str) -> Scope {\n\n web::scope(scope)\n\n .service(push_transactions)\n\n .service(query_user_id)\n\n .service(query_room_alias)\n\n}\n\n\n\n#[tracing::instrument]\n\n#[put(\"/transactions/{txn_id}\")]\n\nasync fn push_transactions(\n\n request: IncomingRequest<api::event::push_events::v1::IncomingRequest>,\n\n appservice: Data<Appservice>,\n\n) -> Result<HttpResponse, Error> {\n\n if !appservice.hs_token_matches(request.access_token) {\n\n return Ok(HttpResponse::Unauthorized().finish());\n\n }\n\n\n\n appservice\n\n .client()\n\n .receive_transaction(request.incoming)\n", "file_path": "matrix_sdk_appservice/src/actix.rs", "rank": 31, "score": 56653.414927233025 }, { "content": "fn huge_keys_query_resopnse() -> get_keys::Response {\n\n let data = include_bytes!(\"./keys_query_2000_members.json\");\n\n let data: Value = serde_json::from_slice(data).unwrap();\n\n let data = response_from_file(&data);\n\n get_keys::Response::try_from_http_response(data).expect(\"Can't parse the keys query response\")\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 32, "score": 55908.41326924562 }, { "content": "pub fn keys_claiming(c: &mut Criterion) {\n\n let runtime = Arc::new(\n\n Builder::new_multi_thread()\n\n .build()\n\n .expect(\"Can't create runtime\"),\n\n );\n\n\n\n let keys_query_response = keys_query_response();\n\n let uuid = Uuid::new_v4();\n\n\n\n let response = keys_claim_response();\n\n\n\n let count = response\n\n .one_time_keys\n\n .values()\n\n .fold(0, |acc, d| acc + d.len());\n\n\n\n let mut group = c.benchmark_group(\"Olm session creation\");\n\n group.throughput(Throughput::Elements(count as u64));\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 33, "score": 53981.63700114086 }, { "content": "pub fn keys_query(c: &mut Criterion) {\n\n let runtime = Builder::new_multi_thread()\n\n .build()\n\n .expect(\"Can't create runtime\");\n\n let machine = OlmMachine::new(&alice_id(), &alice_device_id());\n\n let response = keys_query_response();\n\n let uuid = Uuid::new_v4();\n\n\n\n let count = response\n\n .device_keys\n\n .values()\n\n .fold(0, |acc, d| acc + d.len())\n\n + response.master_keys.len()\n\n + response.self_signing_keys.len()\n\n + response.user_signing_keys.len();\n\n\n\n let mut group = c.benchmark_group(\"Keys querying\");\n\n group.throughput(Throughput::Elements(count as u64));\n\n\n\n let name = format!(\"{} device and cross signing keys\", count);\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 34, "score": 53981.63700114086 }, { "content": "pub fn room_key_sharing(c: &mut Criterion) {\n\n let runtime = Builder::new_multi_thread()\n\n .build()\n\n .expect(\"Can't create runtime\");\n\n\n\n let keys_query_response = keys_query_response();\n\n let uuid = Uuid::new_v4();\n\n let response = keys_claim_response();\n\n let room_id = room_id!(\"!test:localhost\");\n\n\n\n let to_device_response = ToDeviceResponse::new();\n\n let users: Vec<UserId> = keys_query_response.device_keys.keys().cloned().collect();\n\n\n\n let count = response\n\n .one_time_keys\n\n .values()\n\n .fold(0, |acc, d| acc + d.len());\n\n\n\n let machine = OlmMachine::new(&alice_id(), &alice_device_id());\n\n runtime\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 35, "score": 53032.96699701193 }, { "content": "pub fn devices_missing_sessions_collecting(c: &mut Criterion) {\n\n let runtime = Builder::new_multi_thread()\n\n .build()\n\n .expect(\"Can't create runtime\");\n\n\n\n let machine = OlmMachine::new(&alice_id(), &alice_device_id());\n\n let response = huge_keys_query_resopnse();\n\n let uuid = Uuid::new_v4();\n\n let users: Vec<UserId> = response.device_keys.keys().cloned().collect();\n\n\n\n let count = response\n\n .device_keys\n\n .values()\n\n .fold(0, |acc, d| acc + d.len());\n\n\n\n let mut group = c.benchmark_group(\"Devices missing sessions collecting\");\n\n group.throughput(Throughput::Elements(count as u64));\n\n\n\n let name = format!(\"{} devices\", count);\n\n\n", "file_path": "matrix_sdk_crypto/benches/crypto_bench.rs", "rank": 36, "score": 52129.080280078124 }, { "content": "/// Get specific API responses for testing\n\npub fn sync_response(kind: SyncResponseFile) -> SyncResponse {\n\n let data: &JsonValue = match kind {\n\n SyncResponseFile::All => &test_json::MORE_SYNC,\n\n SyncResponseFile::Default => &test_json::SYNC,\n\n SyncResponseFile::DefaultWithSummary => &test_json::DEFAULT_SYNC_SUMMARY,\n\n SyncResponseFile::Invite => &test_json::INVITE_SYNC,\n\n SyncResponseFile::Leave => &test_json::LEAVE_SYNC,\n\n SyncResponseFile::Voip => &test_json::VOIP_SYNC,\n\n };\n\n\n\n let response = Response::builder()\n\n .body(data.to_string().as_bytes().to_vec())\n\n .unwrap();\n\n SyncResponse::try_from_http_response(response).unwrap()\n\n}\n\n\n", "file_path": "matrix_sdk_test/src/lib.rs", "rank": 37, "score": 51266.87888614217 }, { "content": "fn bytes_to_emoji_index(bytes: Vec<u8>) -> [u8; 7] {\n\n let bytes: Vec<u64> = bytes.iter().map(|b| *b as u64).collect();\n\n // Join the 6 bytes into one 64 bit unsigned int. This u64 will contain 48\n\n // bits from our 6 bytes.\n\n let mut num: u64 = bytes[0] << 40;\n\n num += bytes[1] << 32;\n\n num += bytes[2] << 24;\n\n num += bytes[3] << 16;\n\n num += bytes[4] << 8;\n\n num += bytes[5];\n\n\n\n // Take the top 42 bits of our 48 bits from the u64 and convert each 6 bits\n\n // into a 6 bit number.\n\n [\n\n ((num >> 42) & 63) as u8,\n\n ((num >> 36) & 63) as u8,\n\n ((num >> 30) & 63) as u8,\n\n ((num >> 24) & 63) as u8,\n\n ((num >> 18) & 63) as u8,\n\n ((num >> 12) & 63) as u8,\n\n ((num >> 6) & 63) as u8,\n\n ]\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 38, "score": 49902.15913117163 }, { "content": "/// Get a tuple of an emoji and a description of the emoji using a number.\n\n///\n\n/// This is taken directly from the [spec]\n\n///\n\n/// # Panics\n\n///\n\n/// The spec defines 64 unique emojis, this function panics if the index is\n\n/// bigger than 63.\n\n///\n\n/// [spec]: https://matrix.org/docs/spec/client_server/latest#sas-method-emoji\n\nfn emoji_from_index(index: u8) -> (&'static str, &'static str) {\n\n match index {\n\n 0 => (\"🐶\", \"Dog\"),\n\n 1 => (\"🐱\", \"Cat\"),\n\n 2 => (\"🦁\", \"Lion\"),\n\n 3 => (\"🐎\", \"Horse\"),\n\n 4 => (\"🦄\", \"Unicorn\"),\n\n 5 => (\"🐷\", \"Pig\"),\n\n 6 => (\"🐘\", \"Elephant\"),\n\n 7 => (\"🐰\", \"Rabbit\"),\n\n 8 => (\"🐼\", \"Panda\"),\n\n 9 => (\"🐓\", \"Rooster\"),\n\n 10 => (\"🐧\", \"Penguin\"),\n\n 11 => (\"🐢\", \"Turtle\"),\n\n 12 => (\"🐟\", \"Fish\"),\n\n 13 => (\"🐙\", \"Octopus\"),\n\n 14 => (\"🦋\", \"Butterfly\"),\n\n 15 => (\"🌷\", \"Flower\"),\n\n 16 => (\"🌳\", \"Tree\"),\n\n 17 => (\"🌵\", \"Cactus\"),\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 39, "score": 47949.640368774555 }, { "content": "fn bytes_to_decimal(bytes: Vec<u8>) -> (u16, u16, u16) {\n\n let bytes: Vec<u16> = bytes.into_iter().map(|b| b as u16).collect();\n\n\n\n // This bitwise operation is taken from the [spec]\n\n // [spec]: https://matrix.org/docs/spec/client_server/latest#sas-method-decimal\n\n let first = bytes[0] << 5 | bytes[1] >> 3;\n\n let second = (bytes[1] & 0x7) << 10 | bytes[2] << 2 | bytes[3] >> 6;\n\n let third = (bytes[3] & 0x3F) << 7 | bytes[4] >> 1;\n\n\n\n (first + 1000, second + 1000, third + 1000)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 40, "score": 47945.42895933711 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\npub fn spawn<F, T>(future: F) -> JoinHandle<T>\n\nwhere\n\n F: Future<Output = T> + 'static,\n\n{\n\n let fut = future.unit_error();\n\n let (fut, handle) = fut.remote_handle();\n\n spawn_local(fut);\n\n\n\n JoinHandle { handle }\n\n}\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\npub struct JoinHandle<T> {\n\n handle: RemoteHandle<Result<T, ()>>,\n\n}\n\n\n\n#[cfg(target_arch = \"wasm32\")]\n\nimpl<T: 'static> Future for JoinHandle<T> {\n\n type Output = Result<T, ()>;\n\n\n\n fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {\n\n Pin::new(&mut self.handle).poll(cx)\n\n }\n\n}\n", "file_path": "matrix_sdk_common/src/executor.rs", "rank": 41, "score": 47812.472499990545 }, { "content": "pub fn response_from_file(json: &serde_json::Value) -> Response<Vec<u8>> {\n\n Response::builder()\n\n .status(200)\n\n .body(json.to_string().as_bytes().to_vec())\n\n .unwrap()\n\n}\n", "file_path": "matrix_sdk_test/src/lib.rs", "rank": 42, "score": 46989.13776740836 }, { "content": "fn bytes_to_emoji(bytes: Vec<u8>) -> [(&'static str, &'static str); 7] {\n\n let numbers = bytes_to_emoji_index(bytes);\n\n\n\n // Convert the 6 bit number into a emoji/description tuple.\n\n [\n\n emoji_from_index(numbers[0]),\n\n emoji_from_index(numbers[1]),\n\n emoji_from_index(numbers[2]),\n\n emoji_from_index(numbers[3]),\n\n emoji_from_index(numbers[4]),\n\n emoji_from_index(numbers[5]),\n\n emoji_from_index(numbers[6]),\n\n ]\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 43, "score": 45384.409426196595 }, { "content": "/// Decode the input as base64 with no padding.\n\npub fn decode(input: impl AsRef<[u8]>) -> Result<Vec<u8>, DecodeError> {\n\n decode_config(input, STANDARD_NO_PAD)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/utilities.rs", "rank": 44, "score": 44677.224013053004 }, { "content": "/// Decode the input as URL safe base64 with no padding.\n\npub fn decode_url_safe(input: impl AsRef<[u8]>) -> Result<Vec<u8>, DecodeError> {\n\n decode_config(input, URL_SAFE_NO_PAD)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/utilities.rs", "rank": 45, "score": 43202.84178073258 }, { "content": "// These methods are only here because Serialize and Deserialize don't seem to\n\n// be implemented for WASM.\n\nfn atomic_bool_serializer<S>(x: &AtomicBool, s: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let value = x.load(Ordering::SeqCst);\n\n s.serialize_some(&value)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/identities/mod.rs", "rank": 46, "score": 42585.17809894771 }, { "content": "fn atomic_bool_deserializer<'de, D>(deserializer: D) -> Result<Arc<AtomicBool>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let value = bool::deserialize(deserializer)?;\n\n Ok(Arc::new(AtomicBool::new(value)))\n\n}\n", "file_path": "matrix_sdk_crypto/src/identities/mod.rs", "rank": 47, "score": 42511.37536803974 }, { "content": "fn auth_data<'a>(user: &UserId, password: &str, session: Option<&'a str>) -> AuthData<'a> {\n\n let mut auth_parameters = BTreeMap::new();\n\n let identifier = json!({\n\n \"type\": \"m.id.user\",\n\n \"user\": user,\n\n });\n\n\n\n auth_parameters.insert(\"identifier\".to_owned(), identifier);\n\n auth_parameters.insert(\"password\".to_owned(), password.to_owned().into());\n\n\n\n AuthData::DirectRequest {\n\n kind: \"m.login.password\",\n\n auth_parameters,\n\n session,\n\n }\n\n}\n\n\n\nasync fn bootstrap(client: Client, user_id: UserId, password: String) {\n\n println!(\"Bootstrapping a new cross signing identity, press enter to continue.\");\n\n\n", "file_path": "matrix_sdk/examples/cross_signing_bootstrap.rs", "rank": 48, "score": 42041.04935409654 }, { "content": "fn local_trust_serializer<S>(x: &Atomic<LocalTrust>, s: S) -> Result<S::Ok, S::Error>\n\nwhere\n\n S: Serializer,\n\n{\n\n let value = x.load(Ordering::SeqCst);\n\n s.serialize_some(&value)\n\n}\n\n\n", "file_path": "matrix_sdk_crypto/src/identities/device.rs", "rank": 49, "score": 41349.5829414037 }, { "content": "fn local_trust_deserializer<'de, D>(deserializer: D) -> Result<Arc<Atomic<LocalTrust>>, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n let value = LocalTrust::deserialize(deserializer)?;\n\n Ok(Arc::new(Atomic::new(value)))\n\n}\n\n\n\n#[derive(Clone)]\n\n/// A device represents a E2EE capable client of an user.\n\npub struct Device {\n\n pub(crate) inner: ReadOnlyDevice,\n\n pub(crate) private_identity: Arc<Mutex<PrivateCrossSigningIdentity>>,\n\n pub(crate) verification_machine: VerificationMachine,\n\n pub(crate) own_identity: Option<OwnUserIdentity>,\n\n pub(crate) device_owner_identity: Option<UserIdentities>,\n\n}\n\n\n\nimpl std::fmt::Debug for Device {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n", "file_path": "matrix_sdk_crypto/src/identities/device.rs", "rank": 50, "score": 41230.25849640668 }, { "content": "/// Get the content for a m.key.verification.mac event.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `sas` - The Olm SAS object that can be used to generate the MAC\n\n///\n\n/// * `ids` - The ids that are used for this SAS authentication flow.\n\n///\n\n/// * `flow_id` - The unique id that identifies this SAS verification process.\n\n///\n\n/// # Panics\n\n///\n\n/// This will panic if the public key of the other side wasn't set.\n\npub fn get_mac_content(sas: &OlmSas, ids: &SasIds, flow_id: &FlowId) -> MacContent {\n\n let mut mac: BTreeMap<String, String> = BTreeMap::new();\n\n\n\n let key_id = DeviceKeyId::from_parts(DeviceKeyAlgorithm::Ed25519, ids.account.device_id());\n\n let key = ids.account.identity_keys().ed25519();\n\n let info = extra_mac_info_send(ids, flow_id.as_str());\n\n\n\n mac.insert(\n\n key_id.to_string(),\n\n sas.calculate_mac(key, &format!(\"{}{}\", info, key_id))\n\n .expect(\"Can't calculate SAS MAC\"),\n\n );\n\n\n\n // TODO Add the cross signing master key here if we trust/have it.\n\n\n\n let mut keys = mac.keys().cloned().collect::<Vec<String>>();\n\n keys.sort();\n\n let keys = sas\n\n .calculate_mac(&keys.join(\",\"), &format!(\"{}KEY_IDS\", &info))\n\n .expect(\"Can't calculate SAS MAC\");\n", "file_path": "matrix_sdk_crypto/src/verification/sas/helpers.rs", "rank": 51, "score": 40721.95107726546 }, { "content": "#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\n\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n\npub trait HttpSend: AsyncTraitDeps {\n\n /// The method abstracting sending request types and receiving response types.\n\n ///\n\n /// This is called by the client every time it wants to send anything to a homeserver.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `request` - The http request that has been converted from a ruma `Request`.\n\n ///\n\n /// * `request_config` - The config used for this request.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```\n\n /// use std::convert::TryFrom;\n\n /// use matrix_sdk::{HttpSend, async_trait, HttpError, RequestConfig, Bytes};\n\n ///\n\n /// #[derive(Debug)]\n\n /// struct Client(reqwest::Client);\n\n ///\n", "file_path": "matrix_sdk/src/http_client.rs", "rank": 52, "score": 39380.2152714275 }, { "content": "#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\n\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n\npub trait StateStore: AsyncTraitDeps {\n\n /// Save the given filter id under the given name.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `filter_name` - The name that should be used to store the filter id.\n\n ///\n\n /// * `filter_id` - The filter id that should be stored in the state store.\n\n async fn save_filter(&self, filter_name: &str, filter_id: &str) -> Result<()>;\n\n\n\n /// Save the set of state changes in the store.\n\n async fn save_changes(&self, changes: &StateChanges) -> Result<()>;\n\n\n\n /// Get the filter id that was stored under the given filter name.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `filter_name` - The name that was used to store the filter id.\n\n async fn get_filter(&self, filter_name: &str) -> Result<Option<String>>;\n\n\n", "file_path": "matrix_sdk_base/src/store/mod.rs", "rank": 53, "score": 38428.384756882006 }, { "content": "#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\n\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n\npub trait CryptoStore: AsyncTraitDeps {\n\n /// Load an account that was previously stored.\n\n async fn load_account(&self) -> Result<Option<ReadOnlyAccount>>;\n\n\n\n /// Save the given account in the store.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `account` - The account that should be stored.\n\n async fn save_account(&self, account: ReadOnlyAccount) -> Result<()>;\n\n\n\n /// Try to load a private cross signing identity, if one is stored.\n\n async fn load_identity(&self) -> Result<Option<PrivateCrossSigningIdentity>>;\n\n\n\n /// Save the set of changes to the store.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `changes` - The set of changes that should be stored.\n\n async fn save_changes(&self, changes: Changes) -> Result<()>;\n", "file_path": "matrix_sdk_crypto/src/store/mod.rs", "rank": 54, "score": 38428.384756882006 }, { "content": "#[cfg(target_arch = \"wasm32\")]\n\npub trait AsyncTraitDeps: std::fmt::Debug + Send + Sync {}\n\n#[cfg(target_arch = \"wasm32\")]\n\nimpl<T: std::fmt::Debug + Send + Sync> AsyncTraitDeps for T {}\n", "file_path": "matrix_sdk_common/src/lib.rs", "rank": 55, "score": 36650.708236583 }, { "content": " sender.to_owned(),\n\n sender_key.to_owned(),\n\n ));\n\n }\n\n }\n\n }\n\n }\n\n\n\n Ok(decrypted)\n\n }\n\n\n\n /// Decrypt an Olm message, creating a new Olm session if possible.\n\n async fn decrypt_olm_message(\n\n &self,\n\n sender: &UserId,\n\n sender_key: &str,\n\n message: OlmMessage,\n\n ) -> OlmResult<(SessionType, Raw<AnyToDeviceEvent>, String)> {\n\n // First try to decrypt using an existing session.\n\n let (session, plaintext) = if let Some(d) = self\n", "file_path": "matrix_sdk_crypto/src/olm/account.rs", "rank": 58, "score": 15.514651752975636 }, { "content": "use tracing::error;\n\nuse tracing::warn;\n\n\n\n#[doc(inline)]\n\npub use matrix_sdk::api_appservice as api;\n\n\n\n#[cfg(feature = \"actix\")]\n\nmod actix;\n\nmod error;\n\n\n\npub use error::Error;\n\npub type Result<T> = std::result::Result<T, Error>;\n\npub type Host = String;\n\npub type Port = u16;\n\n\n\n/// Appservice Registration\n\n#[derive(Debug, Clone)]\n\npub struct AppserviceRegistration {\n\n inner: Registration,\n\n}\n", "file_path": "matrix_sdk_appservice/src/lib.rs", "rank": 59, "score": 15.259752508260025 }, { "content": " &self,\n\n _: Room,\n\n _: &SyncEphemeralRoomEvent<TypingEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"typing event\".to_string())\n\n }\n\n async fn on_non_room_receipt(\n\n &self,\n\n _: Room,\n\n _: &SyncEphemeralRoomEvent<ReceiptEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"receipt event\".to_string())\n\n }\n\n async fn on_presence_event(&self, _: &PresenceEvent) {\n\n self.0.lock().await.push(\"presence event\".to_string())\n\n }\n\n async fn on_unrecognized_event(&self, _: Room, _: &RawJsonValue) {\n\n self.0.lock().await.push(\"unrecognized event\".to_string())\n\n }\n\n async fn on_custom_event(&self, _: Room, _: &CustomEvent<'_>) {\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 60, "score": 14.76700232569931 }, { "content": " ///\n\n ///\n\n /// # Examples\n\n /// ```no_run\n\n /// # use std::convert::TryFrom;\n\n /// # use matrix_sdk::Client;\n\n /// # use matrix_sdk::api::r0::account::register::{Request as RegistrationRequest, RegistrationKind};\n\n /// # use matrix_sdk::api::r0::uiaa::AuthData;\n\n /// # use matrix_sdk::identifiers::DeviceId;\n\n /// # use matrix_sdk_common::assign;\n\n /// # use futures::executor::block_on;\n\n /// # use url::Url;\n\n /// # let homeserver = Url::parse(\"http://example.com\").unwrap();\n\n /// # block_on(async {\n\n ///\n\n /// let request = assign!(RegistrationRequest::new(), {\n\n /// username: Some(\"user\"),\n\n /// password: Some(\"password\"),\n\n /// auth: Some(AuthData::FallbackAcknowledgement { session: \"foobar\" }),\n\n /// });\n", "file_path": "matrix_sdk/src/client.rs", "rank": 61, "score": 14.610208917874596 }, { "content": " async fn on_unrecognized_event(&self, _: Room, _: &RawJsonValue) {}\n\n\n\n /// Fires when `Client` receives a `Event::Custom` event or if deserialization fails\n\n /// because the event was unknown to ruma.\n\n ///\n\n /// The only guarantee this method can give about the event is that it is in the\n\n /// shape of a valid matrix event.\n\n async fn on_custom_event(&self, _: Room, _: &CustomEvent<'_>) {}\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::*;\n\n use matrix_sdk_common::{async_trait, locks::Mutex};\n\n use matrix_sdk_test::{async_test, test_json};\n\n use mockito::{mock, Matcher};\n\n use std::{sync::Arc, time::Duration};\n\n\n\n #[cfg(target_arch = \"wasm32\")]\n\n pub use wasm_bindgen_test::*;\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 62, "score": 14.587535058325109 }, { "content": " pub async fn sign(&self, string: &str) -> String {\n\n self.inner.lock().await.sign(string)\n\n }\n\n\n\n /// Store the account as a base64 encoded string.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `pickle_mode` - The mode that was used to pickle the account, either an\n\n /// unencrypted mode or an encrypted using passphrase.\n\n pub async fn pickle(&self, pickle_mode: PicklingMode) -> PickledAccount {\n\n let pickle = AccountPickle(self.inner.lock().await.pickle(pickle_mode));\n\n\n\n PickledAccount {\n\n user_id: self.user_id().to_owned(),\n\n device_id: self.device_id().to_owned(),\n\n pickle,\n\n shared: self.shared(),\n\n uploaded_signed_key_count: self.uploaded_key_count(),\n\n }\n", "file_path": "matrix_sdk_crypto/src/olm/account.rs", "rank": 63, "score": 14.502577220785291 }, { "content": " async fn get_filter(&self, filter_id: &str) -> Result<Option<String>> {\n\n self.get_filter(filter_id).await\n\n }\n\n\n\n async fn get_sync_token(&self) -> Result<Option<String>> {\n\n self.get_sync_token().await\n\n }\n\n\n\n async fn get_presence_event(&self, user_id: &UserId) -> Result<Option<Raw<PresenceEvent>>> {\n\n self.get_presence_event(user_id).await\n\n }\n\n\n\n async fn get_state_event(\n\n &self,\n\n room_id: &RoomId,\n\n event_type: EventType,\n\n state_key: &str,\n\n ) -> Result<Option<Raw<AnySyncStateEvent>>> {\n\n self.get_state_event(room_id, event_type, state_key).await\n\n }\n", "file_path": "matrix_sdk_base/src/store/memory_store.rs", "rank": 64, "score": 14.313378194843056 }, { "content": "use std::{convert::TryFrom, env};\n\n\n\nuse actix_web::{App, HttpServer};\n\nuse matrix_sdk::{\n\n async_trait,\n\n events::{\n\n room::member::{MemberEventContent, MembershipState},\n\n SyncStateEvent,\n\n },\n\n identifiers::UserId,\n\n room::Room,\n\n EventHandler,\n\n};\n\nuse matrix_sdk_appservice::{Appservice, AppserviceRegistration};\n\n\n", "file_path": "matrix_sdk_appservice/examples/actix_autojoin.rs", "rank": 65, "score": 13.86248257724193 }, { "content": "#[cfg(feature = \"actix\")]\n\nmod actix {\n\n use actix_web::{test, App};\n\n use matrix_sdk_appservice::*;\n\n use std::env;\n\n\n\n async fn appservice() -> Appservice {\n\n env::set_var(\n\n \"RUST_LOG\",\n\n \"mockito=debug,matrix_sdk=debug,ruma=debug,actix_web=debug\",\n\n );\n\n let _ = tracing_subscriber::fmt::try_init();\n\n\n\n Appservice::new(\n\n mockito::server_url().as_ref(),\n\n \"test.local\",\n\n AppserviceRegistration::try_from_yaml_file(\"./tests/registration.yaml\").unwrap(),\n\n )\n\n .await\n\n .unwrap()\n", "file_path": "matrix_sdk_appservice/tests/actix.rs", "rank": 66, "score": 13.669954972328892 }, { "content": " ///\n\n /// ```no_run\n\n /// # use matrix_sdk::Client;\n\n /// # use futures::executor::block_on;\n\n /// # use url::Url;\n\n /// use matrix_sdk::Sas;\n\n /// use matrix_sdk_base::crypto::AcceptSettings;\n\n /// use matrix_sdk::events::key::verification::ShortAuthenticationString;\n\n /// # let homeserver = Url::parse(\"http://example.com\").unwrap();\n\n /// # let client = Client::new(homeserver).unwrap();\n\n /// # let flow_id = \"someID\";\n\n /// # block_on(async {\n\n /// let sas = client.get_verification(flow_id).await.unwrap();\n\n ///\n\n /// let only_decimal = AcceptSettings::with_allowed_methods(\n\n /// vec![ShortAuthenticationString::Decimal]\n\n /// );\n\n /// sas.accept_with_settings(only_decimal).await.unwrap();\n\n /// # });\n\n /// ```\n", "file_path": "matrix_sdk/src/sas.rs", "rank": 67, "score": 13.545923062027768 }, { "content": "#[cfg(feature = \"sled_state_store\")]\n\nuse std::path::Path;\n\n\n\nuse dashmap::DashMap;\n\nuse matrix_sdk_common::{\n\n api::r0::push::get_notifications::Notification,\n\n async_trait,\n\n events::{\n\n presence::PresenceEvent, room::member::MemberEventContent, AnyBasicEvent,\n\n AnyStrippedStateEvent, AnySyncStateEvent, EventContent, EventType,\n\n },\n\n identifiers::{RoomId, UserId},\n\n locks::RwLock,\n\n AsyncTraitDeps, Raw,\n\n};\n\n#[cfg(feature = \"sled_state_store\")]\n\nuse sled::Db;\n\n\n\nuse crate::{\n\n deserialized_responses::{MemberEvent, StrippedMemberEvent},\n", "file_path": "matrix_sdk_base/src/store/mod.rs", "rank": 68, "score": 13.270942496413294 }, { "content": " sync::Arc,\n\n time::SystemTime,\n\n};\n\n\n\nuse futures::{\n\n stream::{self, Stream},\n\n TryStreamExt,\n\n};\n\nuse matrix_sdk_common::{\n\n async_trait,\n\n events::{\n\n presence::PresenceEvent,\n\n room::member::{MemberEventContent, MembershipState},\n\n AnyBasicEvent, AnySyncStateEvent, EventType,\n\n },\n\n identifiers::{RoomId, UserId},\n\n Raw,\n\n};\n\nuse serde::{Deserialize, Serialize};\n\n\n", "file_path": "matrix_sdk_base/src/store/sled_store/mod.rs", "rank": 69, "score": 13.142452723877668 }, { "content": " ///\n\n /// * `content_type` - The type of the media, this will be used as the\n\n /// content-type header.\n\n ///\n\n /// * `reader` - A `Reader` that will be used to fetch the raw bytes of the\n\n /// media.\n\n ///\n\n /// * `txn_id` - A unique `Uuid` that can be attached to a `MessageEvent`\n\n /// held in its unsigned field as `transaction_id`. If not given one is\n\n /// created for the message.\n\n ///\n\n /// # Examples\n\n ///\n\n /// ```no_run\n\n /// # use std::{path::PathBuf, fs::File, io::Read};\n\n /// # use matrix_sdk::{Client, identifiers::room_id};\n\n /// # use url::Url;\n\n /// # use mime;\n\n /// # use futures::executor::block_on;\n\n /// # block_on(async {\n", "file_path": "matrix_sdk/src/room/joined.rs", "rank": 70, "score": 13.116318123853688 }, { "content": "//! * have the goal to have a consistent room state available by leveraging the stores that the matrix-sdk provides\n\n//!\n\n//! # Quickstart\n\n//!\n\n//! ```no_run\n\n//! # async {\n\n//! use matrix_sdk_appservice::{Appservice, AppserviceRegistration};\n\n//!\n\n//! let homeserver_url = \"http://127.0.0.1:8008\";\n\n//! let server_name = \"localhost\";\n\n//! let registration = AppserviceRegistration::try_from_yaml_str(\n\n//! r\"\n\n//! id: appservice\n\n//! url: http://127.0.0.1:9009\n\n//! as_token: as_token\n\n//! hs_token: hs_token\n\n//! sender_localpart: _appservice\n\n//! namespaces:\n\n//! users:\n\n//! - exclusive: true\n", "file_path": "matrix_sdk_appservice/src/lib.rs", "rank": 71, "score": 13.077455060803906 }, { "content": " }\n\n\n\n /// Returns the unique identifier for this session.\n\n pub fn session_id(&self) -> &str {\n\n &self.session_id\n\n }\n\n\n\n /// Store the session as a base64 encoded string.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `pickle_mode` - The mode that was used to pickle the session, either\n\n /// an unencrypted mode or an encrypted using passphrase.\n\n pub async fn pickle(&self, pickle_mode: PicklingMode) -> PickledSession {\n\n let pickle = self.inner.lock().await.pickle(pickle_mode);\n\n\n\n PickledSession {\n\n pickle: SessionPickle::from(pickle),\n\n sender_key: self.sender_key.to_string(),\n\n creation_time: *self.creation_time,\n", "file_path": "matrix_sdk_crypto/src/olm/session.rs", "rank": 72, "score": 12.812297775097733 }, { "content": "\n\n async fn get_account_data_event(\n\n &self,\n\n event_type: EventType,\n\n ) -> Result<Option<Raw<AnyBasicEvent>>> {\n\n self.get_account_data_event(event_type).await\n\n }\n\n\n\n async fn get_room_account_data_event(\n\n &self,\n\n room_id: &RoomId,\n\n event_type: EventType,\n\n ) -> Result<Option<Raw<AnyBasicEvent>>> {\n\n self.get_room_account_data_event(room_id, event_type).await\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use std::{convert::TryFrom, time::SystemTime};\n", "file_path": "matrix_sdk_base/src/store/sled_store/mod.rs", "rank": 73, "score": 12.76048927513478 }, { "content": " /// * `registration` - The [Appservice Registration] to use when interacting with the homserver.\n\n ///\n\n /// [Appservice Registration]: https://matrix.org/docs/spec/application_service/r0.1.2#registration\n\n pub async fn new(\n\n homeserver_url: impl TryInto<Url, Error = url::ParseError>,\n\n server_name: impl TryInto<ServerNameBox, Error = identifiers::Error>,\n\n registration: AppserviceRegistration,\n\n ) -> Result<Self> {\n\n let homeserver_url = homeserver_url.try_into()?;\n\n let server_name = server_name.try_into()?;\n\n\n\n let client = create_client(&homeserver_url, &server_name, &registration, None).await?;\n\n\n\n Ok(Appservice {\n\n homeserver_url,\n\n server_name,\n\n registration,\n\n client_sender_localpart: client,\n\n })\n\n }\n", "file_path": "matrix_sdk_appservice/src/lib.rs", "rank": 74, "score": 12.750644639434247 }, { "content": "pub use async_trait::async_trait;\n\npub use instant;\n\n#[cfg(feature = \"appservice\")]\n\npub use ruma::{\n\n api::{appservice as api_appservice, IncomingRequest, OutgoingRequestAppserviceExt},\n\n serde::{exports::serde::de::value::Error as SerdeError, urlencoded},\n\n};\n\npub use ruma::{\n\n api::{\n\n client as api,\n\n error::{\n\n FromHttpRequestError, FromHttpResponseError, IntoHttpError, MatrixError, ServerError,\n\n },\n\n AuthScheme, EndpointError, IncomingResponse, OutgoingRequest, SendAccessToken,\n\n },\n\n assign, directory, encryption, events, identifiers, int, presence, push,\n\n serde::{CanonicalJsonValue, Raw},\n\n thirdparty, uint, Int, Outgoing, UInt,\n\n};\n\n\n", "file_path": "matrix_sdk_common/src/lib.rs", "rank": 75, "score": 12.64437419161683 }, { "content": " \"found the wrong `Error` type {:?}, expected `Error::RumaResponse\",\n\n err\n\n );\n\n }\n\n } else {\n\n panic!(\"this request should return an `Err` variant\")\n\n }\n\n }\n\n\n\n #[tokio::test]\n\n async fn register_error() {\n\n let homeserver = Url::from_str(&mockito::server_url()).unwrap();\n\n let client = Client::new(homeserver).unwrap();\n\n\n\n let _m = mock(\n\n \"POST\",\n\n Matcher::Regex(r\"^/_matrix/client/r0/register\\?.*$\".to_string()),\n\n )\n\n .with_status(403)\n\n .with_body(test_json::REGISTRATION_RESPONSE_ERR.to_string())\n", "file_path": "matrix_sdk/src/client.rs", "rank": 76, "score": 12.639716270205055 }, { "content": " /// [`restore_login`]: #method.restore_login\n\n #[cfg(all(feature = \"sso_login\", not(target_arch = \"wasm32\")))]\n\n #[cfg_attr(\n\n feature = \"docs\",\n\n doc(cfg(all(sso_login, not(target_arch = \"wasm32\"))))\n\n )]\n\n pub async fn login_with_sso<C>(\n\n &self,\n\n use_sso_login_url: impl Fn(String) -> C,\n\n server_url: Option<&str>,\n\n server_response: Option<&str>,\n\n device_id: Option<&str>,\n\n initial_device_display_name: Option<&str>,\n\n ) -> Result<login::Response>\n\n where\n\n C: Future<Output = Result<()>>,\n\n {\n\n info!(\"Logging in to {}\", self.homeserver);\n\n let (signal_tx, signal_rx) = oneshot::channel();\n\n let (data_tx, data_rx) = oneshot::channel();\n", "file_path": "matrix_sdk/src/client.rs", "rank": 77, "score": 12.626184662202888 }, { "content": "\n\n use matrix_sdk_common::{\n\n events::{\n\n room::{\n\n member::{MemberEventContent, MembershipState},\n\n power_levels::PowerLevelsEventContent,\n\n },\n\n AnySyncStateEvent, EventType, Unsigned,\n\n },\n\n identifiers::{room_id, user_id, EventId, UserId},\n\n Raw,\n\n };\n\n use matrix_sdk_test::async_test;\n\n use serde_json::json;\n\n\n\n use super::{SledStore, StateChanges};\n\n use crate::deserialized_responses::MemberEvent;\n\n\n\n fn user_id() -> UserId {\n\n user_id!(\"@example:localhost\")\n", "file_path": "matrix_sdk_base/src/store/sled_store/mod.rs", "rank": 78, "score": 12.620338973496423 }, { "content": " self.0.lock().await.push(\"custom event\".to_string())\n\n }\n\n async fn on_room_notification(&self, _: Room, _: Notification) {\n\n self.0.lock().await.push(\"notification\".to_string())\n\n }\n\n }\n\n\n\n use crate::{identifiers::user_id, Client, Session, SyncSettings};\n\n\n\n async fn get_client() -> Client {\n\n let session = Session {\n\n access_token: \"1234\".to_owned(),\n\n user_id: user_id!(\"@example:localhost\"),\n\n device_id: \"DEVICEID\".into(),\n\n };\n\n let homeserver = url::Url::parse(&mockito::server_url()).unwrap();\n\n let client = Client::new(homeserver).unwrap();\n\n client.restore_login(session).await.unwrap();\n\n client\n\n }\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 79, "score": 12.54711001307627 }, { "content": "use matrix_sdk_common::{\n\n async_trait,\n\n events::{\n\n presence::PresenceEvent,\n\n room::member::{MemberEventContent, MembershipState},\n\n AnyBasicEvent, AnyStrippedStateEvent, AnySyncStateEvent, EventType,\n\n },\n\n identifiers::{RoomId, UserId},\n\n instant::Instant,\n\n Raw,\n\n};\n\n\n\nuse tracing::info;\n\n\n\nuse crate::deserialized_responses::{MemberEvent, StrippedMemberEvent};\n\n\n\nuse super::{Result, RoomInfo, StateChanges, StateStore};\n\n\n\n#[derive(Debug, Clone)]\n\npub struct MemoryStore {\n", "file_path": "matrix_sdk_base/src/store/memory_store.rs", "rank": 80, "score": 12.469957909316213 }, { "content": " ///\n\n /// Alternatively, if the whole session isn't stored the [`login`] method\n\n /// can be used with a device id.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `session` - A session that the user already has from a\n\n /// previous login call.\n\n ///\n\n /// [`login`]: #method.login\n\n pub async fn restore_login(&self, session: Session) -> Result<()> {\n\n Ok(self.base_client.restore_login(session).await?)\n\n }\n\n\n\n /// Register a user to the server.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `registration` - The easiest way to create this request is using the `register::Request`\n\n /// itself.\n", "file_path": "matrix_sdk/src/client.rs", "rank": 81, "score": 12.420931931402782 }, { "content": " /// # Example\n\n /// ```no_run\n\n /// # use futures::executor::block_on;\n\n /// # use matrix_sdk::Client;\n\n /// # use url::Url;\n\n /// # let homeserver = Url::parse(\"http://example.com\").unwrap();\n\n /// # block_on(async {\n\n /// let user = \"example\";\n\n /// let client = Client::new(homeserver).unwrap();\n\n /// client.login(user, \"password\", None, None).await.unwrap();\n\n ///\n\n /// if let Some(name) = client.display_name().await.unwrap() {\n\n /// println!(\"Logged in as user '{}' with display name '{}'\", user, name);\n\n /// }\n\n /// # })\n\n /// ```\n\n pub async fn display_name(&self) -> Result<Option<String>> {\n\n let user_id = self.user_id().await.ok_or(Error::AuthenticationRequired)?;\n\n let request = get_display_name::Request::new(&user_id);\n\n let response = self.send(request, None).await?;\n", "file_path": "matrix_sdk/src/client.rs", "rank": 82, "score": 12.305648606594112 }, { "content": " /// Get the last stored sync token.\n\n async fn get_sync_token(&self) -> Result<Option<String>>;\n\n\n\n /// Get the stored presence event for the given user.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `user_id` - The id of the user for which we wish to fetch the presence\n\n /// event for.\n\n async fn get_presence_event(&self, user_id: &UserId) -> Result<Option<Raw<PresenceEvent>>>;\n\n\n\n /// Get a state event out of the state store.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `room_id` - The id of the room the state event was received for.\n\n ///\n\n /// * `event_type` - The event type of the state event.\n\n async fn get_state_event(\n\n &self,\n", "file_path": "matrix_sdk_base/src/store/mod.rs", "rank": 83, "score": 12.100836350637314 }, { "content": "\n\n let device_keys = if !self.shared() {\n\n Some(self.device_keys().await)\n\n } else {\n\n None\n\n };\n\n\n\n let one_time_keys = self.signed_one_time_keys().await.ok();\n\n\n\n Some((device_keys, one_time_keys))\n\n }\n\n\n\n /// Mark the current set of one-time keys as being published.\n\n pub(crate) async fn mark_keys_as_published(&self) {\n\n self.inner.lock().await.mark_keys_as_published();\n\n }\n\n\n\n /// Sign the given string using the accounts signing key.\n\n ///\n\n /// Returns the signature as a base64 encoded string.\n", "file_path": "matrix_sdk_crypto/src/olm/account.rs", "rank": 84, "score": 12.062019427052322 }, { "content": " /// associated with the device_id. Only necessary the first time you\n\n /// login with this device_id. It can be changed later.\n\n ///\n\n /// # Example\n\n /// ```no_run\n\n /// # use std::convert::TryFrom;\n\n /// # use matrix_sdk::Client;\n\n /// # use matrix_sdk::identifiers::DeviceId;\n\n /// # use matrix_sdk_common::assign;\n\n /// # use futures::executor::block_on;\n\n /// # use url::Url;\n\n /// # let homeserver = Url::parse(\"https://example.com\").unwrap();\n\n /// # let redirect_url = \"http://localhost:1234\";\n\n /// # let login_token = \"token\";\n\n /// # block_on(async {\n\n /// let client = Client::new(homeserver).unwrap();\n\n /// let sso_url = client.get_sso_login_url(redirect_url);\n\n ///\n\n /// // Let the user authenticate at the SSO URL\n\n /// // Receive the loginToken param at redirect_url\n", "file_path": "matrix_sdk/src/client.rs", "rank": 85, "score": 11.990612175129053 }, { "content": " /// # use matrix_sdk_common::identifiers::user_id;\n\n /// # use futures::executor::block_on;\n\n /// # let alice = user_id!(\"@alice:example.org\");\n\n /// # let machine = OlmMachine::new(&alice, \"DEVICEID\".into());\n\n /// # block_on(async {\n\n /// # let export = Cursor::new(\"\".to_owned());\n\n /// let exported_keys = decrypt_key_export(export, \"1234\").unwrap();\n\n /// machine.import_keys(exported_keys, |_, _| {}).await.unwrap();\n\n /// # });\n\n /// ```\n\n pub async fn import_keys(\n\n &self,\n\n exported_keys: Vec<ExportedRoomKey>,\n\n progress_listener: impl Fn(usize, usize),\n\n ) -> StoreResult<(usize, usize)> {\n\n struct ShallowSessions {\n\n inner: BTreeMap<Arc<RoomId>, u32>,\n\n }\n\n\n\n impl ShallowSessions {\n", "file_path": "matrix_sdk_crypto/src/machine.rs", "rank": 86, "score": 11.97648197251092 }, { "content": " .send_attachment(\"image\", &mime::IMAGE_JPEG, &mut media, None)\n\n .await\n\n .unwrap();\n\n\n\n assert_eq!(event_id!(\"$h29iv0s8:example.com\"), response.event_id)\n\n }\n\n\n\n #[tokio::test]\n\n async fn room_redact() {\n\n use matrix_sdk_common::uuid::Uuid;\n\n\n\n let client = logged_in_client().await;\n\n\n\n let _m = mock(\n\n \"PUT\",\n\n Matcher::Regex(r\"^/_matrix/client/r0/rooms/.*/redact/.*?/.*?\".to_string()),\n\n )\n\n .with_status(200)\n\n .match_header(\"authorization\", \"Bearer 1234\")\n\n .with_body(test_json::EVENT_ID.to_string())\n", "file_path": "matrix_sdk/src/client.rs", "rank": 87, "score": 11.719547065855668 }, { "content": " }\n\n\n\n async fn save_filter(&self, filter_name: &str, filter_id: &str) -> Result<()> {\n\n self.filters\n\n .insert(filter_name.to_string(), filter_id.to_string());\n\n\n\n Ok(())\n\n }\n\n\n\n async fn get_filter(&self, filter_name: &str) -> Result<Option<String>> {\n\n Ok(self.filters.get(filter_name).map(|f| f.to_string()))\n\n }\n\n\n\n async fn get_sync_token(&self) -> Result<Option<String>> {\n\n Ok(self.sync_token.read().unwrap().clone())\n\n }\n\n\n\n async fn save_changes(&self, changes: &StateChanges) -> Result<()> {\n\n let now = Instant::now();\n\n\n", "file_path": "matrix_sdk_base/src/store/memory_store.rs", "rank": 88, "score": 11.647999284011972 }, { "content": "/// file.\n\n#[derive(Debug, Serialize, Deserialize)]\n\npub struct EncryptionInfo {\n\n #[serde(rename = \"v\")]\n\n /// The version of the encryption scheme.\n\n pub version: String,\n\n /// The web key that was used to encrypt the file.\n\n pub web_key: JsonWebKey,\n\n /// The initialization vector that was used to encrypt the file.\n\n pub iv: String,\n\n /// The hashes that can be used to check the validity of the file.\n\n pub hashes: BTreeMap<String, String>,\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::{AttachmentDecryptor, AttachmentEncryptor, EncryptionInfo};\n\n use serde_json::json;\n\n use std::io::{Cursor, Read};\n\n\n", "file_path": "matrix_sdk_crypto/src/file_encryption/attachments.rs", "rank": 89, "score": 11.618250606795463 }, { "content": "\n\n async fn delete_outgoing_key_request(&self, request_id: Uuid) -> Result<()> {\n\n self.outgoing_key_requests\n\n .remove(&request_id)\n\n .and_then(|(_, i)| {\n\n let key_info_string = encode_key_info(&i.info);\n\n self.key_requests_by_info.remove(&key_info_string)\n\n });\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use crate::{\n\n identities::device::test::get_device,\n\n olm::{test::get_account_and_session, InboundGroupSession, OlmMessageHash},\n\n store::{memorystore::MemoryStore, Changes, CryptoStore},\n\n };\n", "file_path": "matrix_sdk_crypto/src/store/memorystore.rs", "rank": 90, "score": 11.58812065581981 }, { "content": " /// # Arguments\n\n ///\n\n /// * `filter_name` - The name of the filter that was previously used to\n\n /// persist the filter.\n\n ///\n\n /// [`receive_filter_upload`]: #method.receive_filter_upload\n\n pub async fn get_filter(&self, filter_name: &str) -> StoreResult<Option<String>> {\n\n self.store.get_filter(filter_name).await\n\n }\n\n\n\n /// Get the outgoing requests that need to be sent out.\n\n ///\n\n /// This returns a list of `OutGoingRequest`, those requests need to be sent\n\n /// out to the server and the responses need to be passed back to the state\n\n /// machine using [`mark_request_as_sent`].\n\n ///\n\n /// [`mark_request_as_sent`]: #method.mark_request_as_sent\n\n #[cfg(feature = \"encryption\")]\n\n #[cfg_attr(feature = \"docs\", doc(cfg(encryption)))]\n\n pub async fn outgoing_requests(&self) -> Result<Vec<OutgoingRequest>, CryptoStoreError> {\n", "file_path": "matrix_sdk_base/src/client.rs", "rank": 91, "score": 11.477538588262565 }, { "content": " self.0.lock().await.push(\"call answer\".to_string())\n\n }\n\n async fn on_room_call_candidates(\n\n &self,\n\n _: Room,\n\n _: &SyncMessageEvent<CandidatesEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"call candidates\".to_string())\n\n }\n\n async fn on_room_call_hangup(&self, _: Room, _: &SyncMessageEvent<HangupEventContent>) {\n\n self.0.lock().await.push(\"call hangup\".to_string())\n\n }\n\n async fn on_room_redaction(&self, _: Room, _: &SyncRedactionEvent) {\n\n self.0.lock().await.push(\"redaction\".to_string())\n\n }\n\n async fn on_room_power_levels(&self, _: Room, _: &SyncStateEvent<PowerLevelsEventContent>) {\n\n self.0.lock().await.push(\"power\".to_string())\n\n }\n\n async fn on_room_tombstone(&self, _: Room, _: &SyncStateEvent<TombstoneEventContent>) {\n\n self.0.lock().await.push(\"tombstone\".to_string())\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 92, "score": 11.467751205097425 }, { "content": " room_id: &RoomId,\n\n event_type: EventType,\n\n state_key: &str,\n\n ) -> Result<Option<Raw<AnySyncStateEvent>>>;\n\n\n\n /// Get the current profile for the given user in the given room.\n\n ///\n\n /// # Arguments\n\n ///\n\n /// * `room_id` - The room id the profile is used in.\n\n ///\n\n /// * `user_id` - The id of the user the profile belongs to.\n\n async fn get_profile(\n\n &self,\n\n room_id: &RoomId,\n\n user_id: &UserId,\n\n ) -> Result<Option<MemberEventContent>>;\n\n\n\n /// Get a raw `MemberEvent` for the given state key in the given room id.\n\n ///\n", "file_path": "matrix_sdk_base/src/store/mod.rs", "rank": 93, "score": 11.42427534244942 }, { "content": " async fn on_room_aliases(&self, _: Room, _: &SyncStateEvent<AliasesEventContent>) {\n\n self.0.lock().await.push(\"aliases\".to_string())\n\n }\n\n async fn on_room_avatar(&self, _: Room, _: &SyncStateEvent<AvatarEventContent>) {\n\n self.0.lock().await.push(\"avatar\".to_string())\n\n }\n\n async fn on_room_message(&self, _: Room, _: &SyncMessageEvent<MsgEventContent>) {\n\n self.0.lock().await.push(\"message\".to_string())\n\n }\n\n async fn on_room_message_feedback(\n\n &self,\n\n _: Room,\n\n _: &SyncMessageEvent<FeedbackEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"feedback\".to_string())\n\n }\n\n async fn on_room_call_invite(&self, _: Room, _: &SyncMessageEvent<InviteEventContent>) {\n\n self.0.lock().await.push(\"call invite\".to_string())\n\n }\n\n async fn on_room_call_answer(&self, _: Room, _: &SyncMessageEvent<AnswerEventContent>) {\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 94, "score": 11.350229918692722 }, { "content": " .unwrap();\n\n\n\n room.typing_notice(true).await.unwrap();\n\n }\n\n\n\n #[tokio::test]\n\n async fn room_state_event_send() {\n\n use crate::events::{\n\n room::member::{MemberEventContent, MembershipState},\n\n AnyStateEventContent,\n\n };\n\n\n\n let client = logged_in_client().await;\n\n\n\n let _m = mock(\n\n \"PUT\",\n\n Matcher::Regex(r\"^/_matrix/client/r0/rooms/.*/state/.*\".to_string()),\n\n )\n\n .with_status(200)\n\n .match_header(\"authorization\", \"Bearer 1234\")\n", "file_path": "matrix_sdk/src/client.rs", "rank": 95, "score": 11.295385789751938 }, { "content": " }\n\n\n\n async fn on_state_member(&self, _: Room, _: &SyncStateEvent<MemberEventContent>) {\n\n self.0.lock().await.push(\"state member\".to_string())\n\n }\n\n async fn on_state_name(&self, _: Room, _: &SyncStateEvent<NameEventContent>) {\n\n self.0.lock().await.push(\"state name\".to_string())\n\n }\n\n async fn on_state_canonical_alias(\n\n &self,\n\n _: Room,\n\n _: &SyncStateEvent<CanonicalAliasEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"state canonical\".to_string())\n\n }\n\n async fn on_state_aliases(&self, _: Room, _: &SyncStateEvent<AliasesEventContent>) {\n\n self.0.lock().await.push(\"state aliases\".to_string())\n\n }\n\n async fn on_state_avatar(&self, _: Room, _: &SyncStateEvent<AvatarEventContent>) {\n\n self.0.lock().await.push(\"state avatar\".to_string())\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 96, "score": 11.294715091938023 }, { "content": " Json(#[from] SerdeError),\n\n /// The key export string isn't valid base64.\n\n #[error(transparent)]\n\n Decode(#[from] DecodeError),\n\n /// The key export doesn't all the required fields.\n\n #[error(transparent)]\n\n Io(#[from] std::io::Error),\n\n}\n\n\n\n/// Try to decrypt a reader into a list of exported room keys.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `passphrase` - The passphrase that was used to encrypt the exported keys.\n\n///\n\n/// # Examples\n\n/// ```no_run\n\n/// # use std::io::Cursor;\n\n/// # use matrix_sdk_crypto::{OlmMachine, decrypt_key_export};\n\n/// # use matrix_sdk_common::identifiers::user_id;\n\n/// # use futures::executor::block_on;\n\n/// # let alice = user_id!(\"@alice:example.org\");\n\n/// # let machine = OlmMachine::new(&alice, \"DEVICEID\".into());\n\n/// # block_on(async {\n\n/// # let export = Cursor::new(\"\".to_owned());\n\n/// let exported_keys = decrypt_key_export(export, \"1234\").unwrap();\n\n/// machine.import_keys(exported_keys, |_, _| {}).await.unwrap();\n\n/// # });\n\n/// ```\n", "file_path": "matrix_sdk_crypto/src/file_encryption/key_export.rs", "rank": 97, "score": 11.176961066249621 }, { "content": "use http::{HeaderValue, Response as HttpResponse};\n\nuse reqwest::{Client, Response};\n\n#[cfg(all(not(target_arch = \"wasm32\")))]\n\nuse std::sync::atomic::{AtomicU64, Ordering};\n\nuse tracing::trace;\n\nuse url::Url;\n\n\n\nuse matrix_sdk_common::{\n\n api::r0::media::create_content, async_trait, locks::RwLock, AsyncTraitDeps, AuthScheme,\n\n FromHttpResponseError, IncomingResponse, SendAccessToken,\n\n};\n\n\n\nuse crate::{\n\n error::HttpError, Bytes, BytesMut, ClientConfig, OutgoingRequest, RequestConfig, Session,\n\n};\n\n\n\n/// Abstraction around the http layer. The allows implementors to use different\n\n/// http libraries.\n\n#[cfg_attr(target_arch = \"wasm32\", async_trait(?Send))]\n\n#[cfg_attr(not(target_arch = \"wasm32\"), async_trait)]\n", "file_path": "matrix_sdk/src/http_client.rs", "rank": 98, "score": 11.156198619692798 }, { "content": " self.0.lock().await.push(\"presence\".to_string())\n\n }\n\n async fn on_non_room_ignored_users(\n\n &self,\n\n _: Room,\n\n _: &BasicEvent<IgnoredUserListEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"account ignore\".to_string())\n\n }\n\n async fn on_non_room_push_rules(&self, _: Room, _: &BasicEvent<PushRulesEventContent>) {\n\n self.0.lock().await.push(\"account push rules\".to_string())\n\n }\n\n async fn on_non_room_fully_read(\n\n &self,\n\n _: Room,\n\n _: &SyncEphemeralRoomEvent<FullyReadEventContent>,\n\n ) {\n\n self.0.lock().await.push(\"account read\".to_string())\n\n }\n\n async fn on_non_room_typing(\n", "file_path": "matrix_sdk/src/event_handler/mod.rs", "rank": 99, "score": 11.12343895233293 } ]
Rust
old/server/src/main.rs
icefoxen/WorldDocCode
45cb146ebdceca077bb910ca2af40c16232848a4
#[macro_use] extern crate rouille; extern crate lazy_static; extern crate serde; extern crate rustc_serialize; extern crate ring; extern crate untrusted; extern crate base64; use std::collections::HashMap; use std::sync::RwLock; use rouille::Response; extern crate protocol; use protocol::*; use ring::{signature, rand}; #[derive(Debug, Default, Clone)] struct ServerData { names: HashMap<String, UpdateMessage>, keys: HashMap<String, Vec<u8>>, } impl ServerData { fn get_name(&self, name: &str) -> Option<&UpdateMessage> { self.names.get(name) } fn get_id_key(&self, id: &str) -> Option<&[u8]> { self.keys.get(id).map(|x| x.as_ref()) } fn add_id(&mut self, id: &str, key: &[u8]) { self.keys.insert(id.into(), key.into()); } fn validate_update(&self, msg: &UpdateMessage) -> Result<(), ValidationError> { match self.keys.get(&msg.user) { Some(key) => msg.verify_signature(key), None => Err(ValidationError::UnknownUser(msg.user.clone())) } } fn update_name(&mut self, name: &str, contents: &UpdateMessage) { self.names.insert(name.to_string(), contents.clone()); } fn apply_update_if_valid(&mut self, dest: &str, msg: &UpdateMessage) -> Result<(), ValidationError> { let _ = self.validate_update(msg)?; self.update_name(dest, &msg); Ok(()) } fn add_user(&mut self, username: &str) { let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); let keypair = signature::Ed25519KeyPair::from_pkcs8( untrusted::Input::from(&pkcs8_bytes) ).unwrap(); let encoded_privkey = base64::encode(&pkcs8_bytes[..]); println!("Private key for {} is: {}", username, encoded_privkey); let pubkey_bytes = keypair.public_key_bytes(); self.add_id(username, pubkey_bytes); } fn run(server: ServerData, addr: &str) { let server = RwLock::new(server); server.write().unwrap().add_user("icefox"); rouille::start_server(addr, move |request| { router!( request, (GET) (/id/{name:String}) => { if let Some(n) = server.read().unwrap().get_id_key(&name) { Response::text(base64::encode(n)) } else { Response::empty_404() } }, (GET) (/name/{name:String}) => { println!("Got get to {}", &name); if let Some(n) = server.read().unwrap().get_name(&name) { Response::json(n) } else { Response::empty_404() } }, (POST) (/name/{name:String}) => { println!("Got post to {}", &name); let rename_request: UpdateMessage = try_or_400!(rouille::input::json_input(request)); println!("Got post to {}: {:?}", &name, rename_request); match server.write().unwrap().apply_update_if_valid(&name, &rename_request) { Ok(_) => Response::text("ok"), Err(v) => Response::text(format!("{:?}", v)).with_status_code(403), } }, _ => Response::text("hello world") ) }); } } fn main() { let s = ServerData::default(); ServerData::run(s, "127.0.0.1:8888"); } #[cfg(test)] mod tests { extern crate reqwest; use lazy_static; use std::thread; use std::io::Read; use serde::Serialize; use ring::{rand, signature}; use untrusted; use base64; const UNITTEST_USER: &str = "unittest_user"; const UNITTEST_NAME: &str = "unittest_name"; const UNITTEST_NAME_VALUE: &str = "unittest_name_value"; fn start_test_server() { use super::ServerData; let mut s = ServerData::default(); let pubkey_bytes = KEYPAIR.public_key_bytes(); s.add_id(UNITTEST_USER, pubkey_bytes); s.update_name(UNITTEST_NAME, UNITTEST_NAME_VALUE); ServerData::run(s, "127.0.0.1:8888"); } fn generate_keypair() -> signature::Ed25519KeyPair { let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); let keypair = signature::Ed25519KeyPair::from_pkcs8( untrusted::Input::from(&pkcs8_bytes) ).unwrap(); keypair } lazy_static! { static ref SERVER_THREAD: thread::JoinHandle<()> = thread::spawn(start_test_server); static ref KEYPAIR: signature::Ed25519KeyPair = generate_keypair(); } fn spawn_server_and_get(path: &str) -> reqwest::Response { lazy_static::initialize(&SERVER_THREAD); let new_path = String::from("http://localhost:8888") + path; reqwest::get(&new_path).unwrap() } fn spawn_server_and_post<T: Serialize>(path: &str, json: &T) -> reqwest::Response { lazy_static::initialize(&SERVER_THREAD); let client = reqwest::Client::new().unwrap(); let new_path = String::from("http://localhost:8888") + path; client.post(&new_path).unwrap() .json(json).unwrap() .send().unwrap() } #[test] fn test_basic() { let mut resp = spawn_server_and_get("/"); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, "hello world"); } #[test] fn test_id() { let mut resp = spawn_server_and_get((String::from("/id/") + UNITTEST_USER).as_str()); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); let pubkey_bytes = KEYPAIR.public_key_bytes(); let pubkey_string = base64::encode(pubkey_bytes); assert_eq!(content, pubkey_string); } #[test] fn test_get_name() { let resp = spawn_server_and_get("/name/test_no_name"); assert_eq!(resp.status(), reqwest::StatusCode::NotFound); let mut resp = spawn_server_and_get((String::from("/name/") + UNITTEST_NAME).as_str()); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, UNITTEST_NAME_VALUE); } #[test] fn test_post_name() { const NEWNAME: &str = "/name/test_post_name"; let resp = spawn_server_and_get(NEWNAME); assert!(!resp.status().is_success()); let changed_name = "foo!"; let data = super::UpdateMessage::signed_message(&KEYPAIR, UNITTEST_USER, changed_name); let mut resp = spawn_server_and_post(NEWNAME, &data); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, "ok"); let mut resp = spawn_server_and_get(NEWNAME); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, changed_name); let baddata = super::UpdateMessage { user: UNITTEST_USER.into(), signature: "".into(), new_contents: "aieeee!".into(), }; let resp = spawn_server_and_post(NEWNAME, &baddata); assert!(!resp.status().is_success()); let mut resp = spawn_server_and_get(NEWNAME); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, changed_name); } }
#[macro_use] extern crate rouille; extern crate lazy_static; extern crate serde; extern crate rustc_serialize; extern crate ring; extern crate untrusted; extern crate base64; use std::collections::HashMap; use std::sync::RwLock; use rouille::Response; extern crate protocol; use protocol::*; use ring::{signature, rand}; #[derive(Debug, Default, Clone)] struct ServerData { names: HashMap<String, UpdateMessage>, keys: HashMap<String, Vec<u8>>, } impl ServerData { fn get_name(&self, name: &str) -> Option<&UpdateMessage> { self.names.get(name) } fn get_id_key(&self, id: &str) -> Option<&[u8]> { self.keys.get(id).map(|x| x.as_ref()) } fn add_id(&mut self, id: &str, key: &[u8]) { self.keys.insert(id.into(), key.into()); } fn validate_update(&self, msg: &UpdateMessage) -> Result<(), ValidationError> { match self.keys.get(&msg.user) { Some(key) => msg.verify_signature(key), None => Err(ValidationError::UnknownUser(msg.user.clone())) } } fn update_name(&mut self, name: &str, contents: &UpdateMessage) { self.names.insert(name.to_string(), contents.clone()); } fn apply_update_if_valid(&mut self, dest: &str, msg: &UpdateMessage) -> Result<(), ValidationError> { let _ = self.validate_update(msg)?; self.update_name(dest, &msg); Ok(()) } fn add_user(&mut self, username: &str) { let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); let keypair = signature::Ed25519KeyPair::from_pkcs8( untrusted::Input::from(&pkcs8_bytes) ).unwrap(); let encoded_privkey = base64::encode(&pkcs8_bytes[..]); println!("Private key for {} is: {}", username, encoded_privkey); let pubkey_bytes = keypair.public_key_bytes(); self.add_id(username, pubkey_bytes); } fn run(server: ServerData, addr: &str) { let server = RwLock::new(server); server.write().unwrap().add_user("icefox"); rouille::start_server(addr, move |request| { router!( request, (GET) (/id/{name:String}) => { if let Some(n) = server.read().unwrap().get_id_key(&name) { Response::text(base64::encode(n)) } else { Response::empty_404() } }, (GET) (/name/{name:String}) => { println!("Got get to {}", &name); if let Some(n) = server.read().unwrap().get_name(&name) { Response::json(n) } else { Response::empty_404() } }, (POST) (/name/{name:String}) => { println!("Got post to {}", &name); let rename_request: UpdateMessage = try_or_400!(rouille::input::json_input(request)); println!("Got post to {}: {:?}", &name, rename_request); match server.write().unwrap().apply_update_if_valid(&name, &rename_request) { Ok(_) => Response::text("ok"), Err(v) => Response::text(format!("{:?}", v)).with_status_code(403), } }, _ => Response::text("hello world") ) }); } } fn main() { let s = ServerData::default(); ServerData::run(s, "127.0.0.1:8888"); } #[cfg(test)] mod tests { extern crate reqwest; use lazy_static; use std::thread; use std::io::Read; use serde::Serialize; use ring::{rand, signature}; use untrusted; use base64; const UNITTEST_USER: &str = "unittest_user"; const UNITTEST_NAME: &str = "unittest_name"; const UNITTEST_NAME_VALUE: &str = "unittest_name_value"; fn start_test_server() { use super::ServerData; let mut s = ServerData::default(); let pubkey_bytes = KEYPAIR.public_key_bytes(); s.add_id(UNITTEST_USER, pubkey_bytes); s.update_name(UNITTEST_NAME, UNITTEST_NAME_VALUE); ServerData::run(s, "127.0.0.1:8888"); }
lazy_static! { static ref SERVER_THREAD: thread::JoinHandle<()> = thread::spawn(start_test_server); static ref KEYPAIR: signature::Ed25519KeyPair = generate_keypair(); } fn spawn_server_and_get(path: &str) -> reqwest::Response { lazy_static::initialize(&SERVER_THREAD); let new_path = String::from("http://localhost:8888") + path; reqwest::get(&new_path).unwrap() } fn spawn_server_and_post<T: Serialize>(path: &str, json: &T) -> reqwest::Response { lazy_static::initialize(&SERVER_THREAD); let client = reqwest::Client::new().unwrap(); let new_path = String::from("http://localhost:8888") + path; client.post(&new_path).unwrap() .json(json).unwrap() .send().unwrap() } #[test] fn test_basic() { let mut resp = spawn_server_and_get("/"); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, "hello world"); } #[test] fn test_id() { let mut resp = spawn_server_and_get((String::from("/id/") + UNITTEST_USER).as_str()); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); let pubkey_bytes = KEYPAIR.public_key_bytes(); let pubkey_string = base64::encode(pubkey_bytes); assert_eq!(content, pubkey_string); } #[test] fn test_get_name() { let resp = spawn_server_and_get("/name/test_no_name"); assert_eq!(resp.status(), reqwest::StatusCode::NotFound); let mut resp = spawn_server_and_get((String::from("/name/") + UNITTEST_NAME).as_str()); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, UNITTEST_NAME_VALUE); } #[test] fn test_post_name() { const NEWNAME: &str = "/name/test_post_name"; let resp = spawn_server_and_get(NEWNAME); assert!(!resp.status().is_success()); let changed_name = "foo!"; let data = super::UpdateMessage::signed_message(&KEYPAIR, UNITTEST_USER, changed_name); let mut resp = spawn_server_and_post(NEWNAME, &data); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, "ok"); let mut resp = spawn_server_and_get(NEWNAME); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, changed_name); let baddata = super::UpdateMessage { user: UNITTEST_USER.into(), signature: "".into(), new_contents: "aieeee!".into(), }; let resp = spawn_server_and_post(NEWNAME, &baddata); assert!(!resp.status().is_success()); let mut resp = spawn_server_and_get(NEWNAME); assert!(resp.status().is_success()); let mut content = String::new(); resp.read_to_string(&mut content).unwrap(); assert_eq!(content, changed_name); } }
fn generate_keypair() -> signature::Ed25519KeyPair { let rng = rand::SystemRandom::new(); let pkcs8_bytes = signature::Ed25519KeyPair::generate_pkcs8(&rng).unwrap(); let keypair = signature::Ed25519KeyPair::from_pkcs8( untrusted::Input::from(&pkcs8_bytes) ).unwrap(); keypair }
function_block-full_function
[ { "content": "fn get_ipfs_doc(name: &str) {\n\n // Using 'get' here \n\n let url = format!(\"http://localhost:5001/api/v0/cat?arg={}\", name);\n\n let mut resp = reqwest::get(&url).expect(\"Could not get IPFS doc?\");\n\n let mut content = String::new();\n\n resp.read_to_string(&mut content).unwrap();\n\n println!(\"{}\", content);\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 0, "score": 99469.26488686385 }, { "content": "fn do_server(args: &mut str::SplitWhitespace) -> ClientState {\n\n if let (Some(servername), Some(username), Some(keystring)) = (args.next(), args.next(), args.next()) {\n\n let target_server = String::from(servername);\n\n let username = String::from(username);\n\n let pkcs8_bytes = base64::decode(keystring).unwrap();\n\n let keypair = signature::Ed25519KeyPair::from_pkcs8(\n\n untrusted::Input::from(&pkcs8_bytes)\n\n ).unwrap();\n\n Some(Connection {\n\n target_server: target_server,\n\n username: username,\n\n key: keypair,\n\n })\n\n } else {\n\n println!(\"Syntax: server <domain> <username> <private key>\");\n\n None\n\n }\n\n}\n\n\n\nconst CONVERSATION: &str = \"/name/conversation\";\n\n\n", "file_path": "old/client/src/main.rs", "rank": 1, "score": 81768.52400058089 }, { "content": "fn do_post(client: &ClientState, args: &mut str::SplitWhitespace) {\n\n if let Some(ref s) = *client {\n\n let url = String::from(\"http://\") + s.target_server.as_ref() + CONVERSATION;\n\n let mut rl = Editor::<()>::new();\n\n let dataline = rl.readline(\"Enter data to post: \").unwrap();\n\n let ipfs_hash = add_data_to_ipfs(&dataline);\n\n let data = UpdateMessage::signed_message(&s.key, &s.username, &ipfs_hash);\n\n // let data = UpdateMessage {\n\n // user: \"rawr\".into(),\n\n // signature: \"\".into(),\n\n // new_contents: \"aieeee!\".into(),\n\n // };\n\n let client = reqwest::Client::new();\n\n let mut resp = client.post(&url)\n\n .json(&data)\n\n .send().expect(\"Could not send?\");\n\n let mut content = String::new();\n\n resp.read_to_string(&mut content).unwrap();\n\n println!(\"Got {}\", content);\n\n } else {\n\n println!(\"Not connected to a server!\");\n\n }\n\n\n\n}\n\n\n\n\n", "file_path": "old/client/src/main.rs", "rank": 3, "score": 78979.57501856078 }, { "content": "fn do_get(client: &ClientState, args: &mut str::SplitWhitespace) {\n\n if let Some(ref state) = *client {\n\n let url = String::from(\"http://\") + state.target_server.as_ref() + CONVERSATION;\n\n let mut resp = reqwest::get(&url).expect(\"Error getting URL?\");\n\n let msg: UpdateMessage = resp.json().expect(\"Error parsing json response?\");\n\n println!(\"Message set by {} on {} to document {}\", &msg.user, &msg.utc, &msg.new_contents);\n\n // let mut content = String::new();\n\n // resp.read_to_string(&mut content).unwrap();\n\n // println!(\"Got {}\", content);\n\n println!(\"Fetching IPFS document...\");\n\n get_ipfs_doc(&msg.new_contents);\n\n } else {\n\n println!(\"Not connected to a server!\");\n\n }\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 4, "score": 78889.66479091468 }, { "content": "fn parse_and_do_command(client: &mut ClientState, cmd: &str) {\n\n let mut tokens = cmd.split_whitespace();\n\n if let Some(token) = tokens.next() {\n\n match token {\n\n \"help\" => do_help(),\n\n \"server\" => {\n\n let s = do_server(&mut tokens);\n\n *client = s;\n\n },\n\n \"get\" => do_get(client, &mut tokens),\n\n \"post\" => do_post(client, &mut tokens),\n\n other => println!(\"Unknown command: {}\", other),\n\n }\n\n } else {\n\n // Do nothing.\n\n }\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 6, "score": 70050.69586369237 }, { "content": "fn main() {\n\n let mut rl = Editor::<()>::new();\n\n println!(\"Type 'help' for help.\");\n\n let mut s: ClientState = None;\n\n loop {\n\n let mut prompt = match s {\n\n Some(ref state) => String::from(state.target_server.as_ref()),\n\n None => String::from(\"(not connected)\"),\n\n };\n\n // let mut prompt = String::from(server);\n\n prompt += \" > \";\n\n let readline = rl.readline(&prompt);\n\n match readline {\n\n Ok(line) => {\n\n rl.add_history_entry(&line);\n\n parse_and_do_command(&mut s, &line);\n\n },\n\n Err(ReadlineError::Interrupted) => {\n\n println!(\"EOF\");\n\n break\n", "file_path": "old/client/src/main.rs", "rank": 7, "score": 61152.5724938396 }, { "content": "/// Adds a chunk of data to IPFS\n\n/// horrifically writing it out to a temp file and posting that\n\n/// and returns a string containing the IPFS hash of the new data.\n\nfn add_data_to_ipfs(data: &str) -> String {\n\n let url = format!(\"http://localhost:5001/api/v0/add\");\n\n let client = reqwest::Client::new();\n\n {\n\n // Write the stupid stuff out to a file\n\n use std::fs;\n\n use std::io::Write;\n\n let mut f = fs::File::create(\"tempfile.txt\").unwrap();\n\n f.write(data.as_bytes()).unwrap();\n\n }\n\n // use reqwest::header::ContentType;\n\n // use reqwest::mime;\n\n // let form = reqwest::multipart::Form::new()\n\n // .file(\"foo\", \"tempfile.txt\").unwrap()\n\n // .text(\"path\", \"bar\");\n\n // let req = client.post(&url)\n\n // .multipart(form)\n\n // .body(\"rawr\")\n\n // .build().unwrap();\n\n // println!(\"Request is: {:?}\\nBody is: {:?}\", req, req.body());\n", "file_path": "old/client/src/main.rs", "rank": 8, "score": 54603.88341453392 }, { "content": "struct UpdateRequest {\n\n username: Identity,\n\n timestamp: DateTime,\n\n target: Location,\n\n new_target: CID,\n\n signature: Signature,\n\n}\n\n*/", "file_path": "pallasite/src/document.rs", "rank": 9, "score": 49391.48765038129 }, { "content": "struct Connection {\n\n target_server: String,\n\n username: String,\n\n key: signature::Ed25519KeyPair,\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 10, "score": 45055.945217820845 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct IpfsAddResponse {\n\n Hash: String,\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 11, "score": 42016.114139847916 }, { "content": "fn do_help() {\n\n println!(\"Help!\");\n\n println!(\"Ok, first thing you do is connect to a server with the 'server' command, like this:\");\n\n println!(\"server localhost:8888 icefox MFMCAQEwBQYDK2VwBCIEICFMtBQqf3puaJMwdOIHTDfuE5jpTKwaSSSqQKquI5lYoSMDIQC3VOwaNbCzRzRXDPnSyMqgMAREGco+J0oLhDQ0cTj9yg==\");\n\n println!(\"Obviously you need to be running the server on localhost. You also need to be running an IPFS node.\");\n\n println!(\"You can then type 'post', which will ask you for some input, then publish it as an IPFS document and send a request to the server to update the name to that document.\")\n\n println!(\"You can then type 'get' which will ask the server what the latest document is, and retrieve that from IPFS.\")\n\n println!(\"Exciting, huh?\")\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 12, "score": 41334.30939715559 }, { "content": "extern crate ring;\n\n#[macro_use]\n\nextern crate serde_derive;\n\nextern crate serde;\n\nextern crate rustc_serialize;\n\nextern crate untrusted;\n\nextern crate base64;\n\nextern crate chrono;\n\n\n\nuse ring::{signature};\n\n\n\n\n\n#[derive(Clone, PartialEq, Eq, Debug)]\n\npub enum ValidationError {\n\n UnknownUser(String),\n\n MalformedSignature,\n\n InvalidSignature,\n\n}\n\n\n\nuse chrono::prelude::*;\n", "file_path": "old/protocol/src/lib.rs", "rank": 23, "score": 18596.653152686373 }, { "content": " utc: Utc::now(),\n\n signature: base64_sig,\n\n new_contents: msg.to_string(),\n\n }\n\n }\n\n\n\n pub fn verify_signature(&self, pubkey_bytes: &[u8]) -> Result<(), ValidationError> {\n\n let aggregated_message = String::from(self.user.as_str()) + \" \" + self.new_contents.as_ref();\n\n let message_bytes = aggregated_message.as_bytes();\n\n let sig_bytes = base64::decode(&self.signature)\n\n .map_err(|_decode_error| ValidationError::MalformedSignature)?;\n\n let pubkey = untrusted::Input::from(pubkey_bytes);\n\n let msg = untrusted::Input::from(message_bytes);\n\n let sig = untrusted::Input::from(&sig_bytes);\n\n signature::verify(&signature::ED25519, pubkey, msg, sig)\n\n .map_err(|_err| ValidationError::InvalidSignature)\n\n }\n\n}", "file_path": "old/protocol/src/lib.rs", "rank": 24, "score": 18591.59126548414 }, { "content": "\n\n#[derive(Debug, Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Serialize, Deserialize)]\n\npub struct UpdateMessage {\n\n pub user: String,\n\n pub utc: DateTime<Utc>,\n\n pub signature: String,\n\n pub new_contents: String,\n\n}\n\n\n\nimpl UpdateMessage {\n\n pub fn signed_message(keypair: &signature::Ed25519KeyPair, user: &str, msg: &str) -> UpdateMessage {\n\n // TODO: Sign the digest of the contents rather than the contents itself,\n\n // apparently: https://en.wikipedia.org/wiki/Digital_signature#How_they_work\n\n // Also include timestamp and target server in the signature to prevent replay attacks.\n\n let aggregated_message = String::from(user) + \" \" + msg;\n\n let message_bytes = aggregated_message.as_bytes();\n\n let sig = keypair.sign(message_bytes);\n\n let base64_sig = base64::encode(sig.as_ref());\n\n UpdateMessage {\n\n user: user.to_string(),\n", "file_path": "old/protocol/src/lib.rs", "rank": 25, "score": 18591.250709220836 }, { "content": "extern crate reqwest;\n\nextern crate rustyline;\n\nextern crate protocol;\n\nextern crate base64;\n\nextern crate ring;\n\nextern crate untrusted;\n\nextern crate serde;\n\n#[macro_use]\n\nextern crate serde_derive;\n\n\n\nuse protocol::*;\n\n\n\nuse rustyline::error::ReadlineError;\n\nuse rustyline::Editor;\n\nuse std::str;\n\nuse std::io::Read;\n\nuse ring::{signature, rand};\n\n\n", "file_path": "old/client/src/main.rs", "rank": 26, "score": 14282.53258152203 }, { "content": "\n\n let form = reqwest::multipart::Form::new()\n\n .file(\"foo\", \"tempfile.txt\").unwrap()\n\n .text(\"path\", \"bar\");\n\n let mut resp = client.post(&url)\n\n .multipart(form)\n\n // .body(\"file\")\n\n // .header(ContentType(mime::MULTIPART_FORM_DATA))\n\n // .body(data.to_owned())\n\n .send().unwrap();\n\n\n\n let ipfs_response: IpfsAddResponse = resp.json().unwrap();\n\n\n\n // let mut content = String::new();\n\n // resp.read_to_string(&mut content).unwrap();\n\n // println!(\"Got response: {:?}\\n'{:?}'\", resp, ipfs_response);\n\n ipfs_response.Hash\n\n}\n\n\n", "file_path": "old/client/src/main.rs", "rank": 27, "score": 14270.037431629733 }, { "content": " },\n\n Err(ReadlineError::Eof) => {\n\n println!(\"Interrupted\");\n\n break\n\n },\n\n Err(err) => {\n\n println!(\"Error: {:?}\", err);\n\n break\n\n }\n\n }\n\n }\n\n}", "file_path": "old/client/src/main.rs", "rank": 28, "score": 14262.373591772879 }, { "content": "Assume the client is running their own IPFS system so we don’t have to worry about that.\n\n\n\n Identity server: This can be just an HTTP server that returns a user’s GPG public key as a document. As a testbed this\n\ndoesn’t need anything to be dynamic.\n\n\n\n Name server: This will also be an HTTP server with a little REST interface. You either GET a name to get the content\n\naddress associated with the name, or POST to an existing name to update it with a new content address. Your POST request will\n\ncontain: a user id, a datetime, an IPFS address to update to, and a signature of the other elements composed. Errors will\n\noccur if: the user is not authorized, the signature does not match. Errors should occur (but won’t for the prototype) if the\n\nIPFS address does not exist or points to some invalid sort of data.\n\n\n\n Client: Minimum possible thing, probably just a command-line thing like curl. Will take a server name and either fetch the\n\nlatest message or post a new message. Once that works it will be configurable to fetch the last N messages.\n\n\n\n\n", "file_path": "README.md", "rank": 29, "score": 11880.670145145656 }, { "content": "type ClientState = Option<Connection>;\n\n\n", "file_path": "old/client/src/main.rs", "rank": 30, "score": 11590.166792422124 }, { "content": "# pallasite\n\n\n", "file_path": "pallasite/README.md", "rank": 31, "score": 11455.304330611474 }, { "content": "extern crate chrono;\n\nextern crate cid;\n\nextern crate serde;\n\n#[macro_use]\n\nextern crate serde_derive;\n\n\n\npub mod document;\n\npub mod identity;\n\n\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n #[test]\n\n fn it_works() {\n\n }\n\n}\n", "file_path": "pallasite/src/lib.rs", "rank": 32, "score": 13.649097672745068 }, { "content": " username: String,\n\n authority: String,\n\n}\n\n\n\n/// A base64 encoded string of a key\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Key(String);\n\n\n\n/// A base64 encoded signature for the message\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Signature(String);\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum Algorithm {\n\n Ed25519,\n\n // Maybe others later\n\n}\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct PubkeyRequest {\n", "file_path": "pallasite/src/identity.rs", "rank": 33, "score": 9.415152096160774 }, { "content": "use std::time::Duration;\n\nuse chrono::prelude::*;\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Pubkey {\n\n username: Identity,\n\n algorithm: Algorithm,\n\n public_key: Key,\n\n created: DateTime<Utc>,\n\n expires: Option<DateTime<Utc>>,\n\n ttl: Option<Duration>,\n\n // An optional signature, so you can sign a new key with the previous one.\n\n // TODO: Specify a bit better exactly what goes into this and how it is connected.\n\n // Do we want a specific reference to the previous key as well?\n\n signature: Option<Signature>,\n\n}\n\n\n\n/// A user identity, such as [email protected]\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Identity {\n", "file_path": "pallasite/src/identity.rs", "rank": 34, "score": 7.3863239131561675 }, { "content": "use chrono::prelude::*;\n\nuse cid::Cid;\n\n\n\nuse identity::Identity;\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub struct Document {\n\n contents: Vec<Part>,\n\n character_encoding: Encoding,\n\n title: Option<String>,\n\n date: Option<DateTime<Utc>>, // Must be in UTC\n\n local_date: Option<FixedOffset>, // Offset of author's timezone from UTC\n\n author: Option<String>,\n\n author_id: Option<Identity>,\n\n previous_revisions: Option<Vec<Cid>>,\n\n subject: Option<String>, // Like an email subject... is this the same as \"title\"?\n\n // categories/tags (with vocabularies?)\n\n in_response_to: Option<Cid>,\n\n reply_to: Option<Identity>,\n\n language: Option<String>,\n", "file_path": "pallasite/src/document.rs", "rank": 35, "score": 4.343479390765938 }, { "content": " username: String,\n\n query: Option<Query>\n\n}\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum Query {\n\n Before(DateTime<Utc>),\n\n After(DateTime<Utc>),\n\n}\n\n\n\n\n", "file_path": "pallasite/src/identity.rs", "rank": 36, "score": 3.400419717444956 }, { "content": "}\n\n\n\n/// Possible character encodings.\n\n/// Just UTF-8 for now.\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum Encoding {\n\n Utf8,\n\n}\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum Part {\n\n Body(Vec<Segment>),\n\n Section {\n\n level: u32, \n\n contents: Vec<Segment>\n\n },\n\n}\n\n\n\n/// Describe structure of the contained text\n\n#[derive(Clone, PartialEq, Eq)]\n", "file_path": "pallasite/src/document.rs", "rank": 37, "score": 3.1851636916622112 }, { "content": "pub enum Segment {\n\n Para(Elements),\n\n Abstract(Elements),\n\n Table {\n\n header: Vec<Elements>,\n\n body: Vec<Vec<Segment>>,\n\n footer: Vec<Elements>,\n\n },\n\n Figure {\n\n caption: Vec<Elements>,\n\n source: Cid, // May get fancier someday\n\n },\n\n List {\n\n type_: ListType,\n\n elements: Vec<Segment>,\n\n },\n\n Code {\n\n language: Option<String>,\n\n contents: String,\n\n },\n", "file_path": "pallasite/src/document.rs", "rank": 38, "score": 2.4079312579404633 }, { "content": " Quote(Box<Segment>),\n\n}\n\n\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum ListType {\n\n Bulleted,\n\n Numbered,\n\n}\n\n\n\n// #[derive(Clone, PartialEq, Eq)]\n\npub type Elements = Vec<Element>;\n\n\n\n/// Describe properties of the contained text\n\n#[derive(Clone, PartialEq, Eq)]\n\npub enum Element {\n\n Text(String),\n\n Strong(Elements),\n\n Emphasized(Elements),\n\n Footnote(Elements),\n\n Xref {\n", "file_path": "pallasite/src/document.rs", "rank": 39, "score": 1.977842306029786 }, { "content": " contents: Elements, \n\n target: Cid,\n\n },\n\n Subscript(Elements),\n\n Superscript(Elements),\n\n Insertion(Elements),\n\n Deletion(Elements),\n\n Preformatted(Elements),\n\n Comment(String),\n\n Anchor(String),\n\n}\n\n\n\n\n\n\n\n/*\n", "file_path": "pallasite/src/document.rs", "rank": 40, "score": 1.578834493030201 } ]
Rust
src/search/old.rs
KevinWMatthews/mindbase
ab70ffd27c35acec0a0ecedf787234e8980d6e73
use crate::{ allegation::{ Allegation, Body, }, mbql::{ ast, error::{ MBQLError, MBQLErrorKind, }, query::BindResult, Query, }, symbol::Atom, AgentId, AllegationId, Analogy, ArtifactId, MBError, MindBase, Symbol, }; use std::convert::TryInto; use std::rc::Rc; pub struct GSContext<'a> { scan_min: [u8; 64], scan_max: [u8; 64], gs_agents: Vec<AgentId>, mb: &'a MindBase, } impl<'a> GSContext<'a> { pub fn symbolize(&mut self, symbolizable: &Rc<ast::GSymbolizable>, vivify: bool, query: &Query) -> Result<Symbol, MBQLError> { let node = self.symbolize_recurse(symbolizable, vivify, query)?; Ok(node.take_symbol()) } fn symbolize_recurse(&mut self, gsym: &Rc<ast::GSymbolizable>, vivify: bool, query: &Query) -> Result<GSNode, MBQLError> { let symbol = match &**gsym { ast::GSymbolizable::Artifact(a) => GSNode::artifact(self, vivify, query, a)?, ast::GSymbolizable::GroundPair(a) => GSNode::pair(self, vivify, query, a)?, ast::GSymbolizable::SymbolVar(sv) => GSNode::symbolvar(self, vivify, query, sv)?, ast::GSymbolizable::Ground(_) => { unreachable!() }, }; Ok(symbol) } fn find_matching_analogy_symbol(&self, left: &GSNode, right: &GSNode, query: &Query) -> Result<Option<Symbol>, MBError> { let left = left.symbol(); let right = right.symbol(); let comp_merged: Vec<SidedMergeItem<Atom>> = SidedMerge::new(left.atoms.iter(), right.atoms.iter()).map(|a| a.to_owned()) .collect(); let output_left: Vec<Atom> = Vec::new(); let output_right: Vec<Atom> = Vec::new(); let output_analogy: Vec<Atom> = Vec::new(); let iter = query.mb.allegation_iter().filter_map(|allegation| { match allegation { Ok((_, Allegation { body: Body::Analogy(analogy), agent_id, .. })) if self.gs_agents.contains(&agent_id) => { Some(Ok(analogy)) }, Ok(_) => None, Err(e) => Some(Err(e)), } }); for analogy in iter { let analogy = analogy?; let analogy_merged = SidedMerge::new(analogy.left.atoms.iter(), analogy.right.atoms.iter()); let si = SortedIntersect::new(analogy_merged, comp_merged.iter()); for item in si { match (item.left.side, item.right.side) { (Left, Left) => ll_hit = true, (Right, Right) => rr_hit = true, (Left, Right) => lr_hit = true, (Right, Left) => rl_hit = true, } } if (ll_hit && rr_hit) || (lr_hit && rl_hit) { output_analogy.push(analogy.id) } } return Ok(Symbol::new_option(output_analogy)); } } use std::{ cmp::Ordering, iter::Peekable, }; struct SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator { left: Peekable<L>, right: Peekable<R>, } impl<L, R> SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator { fn new(left: L, right: R) -> Self { SidedMerge { left: left.peekable(), right: right.peekable(), } } } pub struct SidedMergeItem<T> { pub item: T, side: ItemSide, } enum ItemSide { Left, Right, } impl<T: Clone> SidedMergeItem<&T> { pub fn to_owned(self) -> SidedMergeItem<T> { SidedMergeItem { item: self.item.clone(), side: self.side, } } } impl<L, R> Iterator for SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator, L::Item: Ord { type Item = SidedMergeItem<L::Item>; fn next(&mut self) -> Option<Self::Item> { let which = match (self.left.peek(), self.right.peek()) { (Some(l), Some(r)) => Some(l.cmp(r)), (Some(_), None) => Some(Ordering::Less), (None, Some(_)) => Some(Ordering::Greater), (None, None) => None, }; match which { Some(Ordering::Less) => { Some(SidedMergeItem { item: self.left.next().unwrap(), side: ItemSide::Left, }) }, Some(Ordering::Equal) => { Some(SidedMergeItem { item: self.left.next().unwrap(), side: ItemSide::Left, }) }, Some(Ordering::Greater) => { Some(SidedMergeItem { item: self.right.next().unwrap(), side: ItemSide::Right, }) }, None => None, } } } struct SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { left: Peekable<L>, right: Peekable<R>, } impl<L, R> SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { fn new(left: L, right: R) -> Self { SortedIntersect { left: left.peekable(), right: right.peekable(), } } } impl<L, R> Iterator for SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator, L::Item: Ord { type Item = L::Item; fn next(&mut self) -> Option<Self::Item> { let mut left = match self.left.next() { None => return None, Some(i) => i, }; let mut right = match self.right.next() { None => return None, Some(i) => i, }; use std::cmp::Ordering::*; loop { match left.cmp(&right) { Less => { left = match self.left.next() { Some(x) => x, None => return None, }; }, Greater => { right = match self.right.next() { Some(x) => x, None => return None, }; }, Equal => return Some(left), } } } } fn analogy_compare(analogy: &Analogy, left: &Symbol, right: &Symbol, atoms: &mut Vec<Atom>) { unimplemented!() } fn intersect_symbols(symbol_a: &Symbol, symbol_b: &Symbol) -> bool { let mut a_iter = symbol_a.atoms.iter(); let mut b_iter = symbol_b.atoms.iter(); let mut a = match a_iter.next() { Some(v) => v, None => { return false; }, }; let mut b = match b_iter.next() { Some(v) => v, None => { return false; }, }; use std::cmp::Ordering::*; loop { match a.cmp(b) { Less => { a = match a_iter.next() { Some(x) => x, None => return false, }; }, Greater => { b = match b_iter.next() { Some(x) => x, None => return false, }; }, Equal => return true, } } }
use crate::{ allegation::{ Allegation, Body, }, mbql::{ ast, error::{ MBQLError, MBQLErrorKind, }, query::BindResult, Query, }, symbol::Atom, AgentId, AllegationId, Analogy, ArtifactId, MBError, MindBase, Symbol, }; use std::convert::TryInto; use std::rc::Rc; pub struct GSContext<'a> { scan_min: [u8; 64], scan_max: [u8; 64], gs_agents: Vec<AgentId>, mb: &'a MindBase, } impl<'a> GSContext<'a> { pub fn symbolize(&mut self, symbolizable: &Rc<ast::GSymbolizable>, vivify: bool, query: &Query) -> Result<Symbol, MBQLError> { let node = self.symbolize_recurse(symbolizable, vivify, query)?; Ok(node.take_symbol()) } fn symbolize_recurse(&mut self, gsym: &Rc<ast::GSymbolizable>, vivify: bool, query: &Query) -> Result<GSNode, MBQLError> { let symbol = match &**gsym { ast::GSymbolizable::Artifact(a) => GSNode::artifact(self, vivify, query, a)?, ast::GSymbolizable::GroundPair(a) => GSNode::pair(self, vivify, query, a)?, ast::GSymbolizable::SymbolVar(sv) => GSNode::symbolvar(self, vivify, query, sv)?, ast::GSymbolizable::Ground(_) => { unreachable!() }, }; Ok(symbol) } fn find_matching_analogy_symbol(&self, left: &GSNode, right: &GSNode, query: &Query) -> Result<Option<Symbol>, MBError> { let left = left.symbol(); let right = right.symbol(); let comp_merged: Vec<SidedMergeItem<Atom>> = SidedMerge::new(left.atoms.iter(), right.atoms.iter()).map(|a| a.to_owned()) .collect(); let output_left: Vec<Atom> = Vec::new(); let output_right: Vec<Atom> = Vec::new(); let output_analogy: Vec<Atom> = Vec::new(); let iter = query.mb.allegation_iter().filter_map(|allegation| { match allegation { Ok((_, Allegation { body: Body::Analogy(analogy), agent_id, .. })) if self.gs_agents.contains(&agent_id) => { Some(Ok(analogy)) }, Ok(_) => None, Err(e) => Some(Err(e)), } }); for analogy in iter { let analogy = analogy?; let analogy_merged = SidedMerge::new(analogy.left.atoms.iter(), analogy.right.atoms.iter()); let si = SortedIntersect::new(analogy_merged, comp_merged.iter()); for item in si { match (item.left.side, item.right.side) { (Left, Left) => ll_hit = true, (Right, Right) => rr_hit = true, (Left, Right) => lr_hit = true, (Right, Left) => rl_hit = true, } } if (ll_hit && rr_hit) || (lr_hit && rl_hit) { output_analogy.push(analogy.id) } } return Ok(Symbol::new_option(output_analogy)); } } use std::{ cmp::Ordering, iter::Peekable, }; struct SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator { left: Peekable<L>, right: Peekable<R>, } impl<L, R> SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator { fn new(left: L, right: R) -> Self { SidedMerge { left: left.peekable(), right: right.peekable(), } } } pub struct SidedMergeItem<T> { pub item: T, side: ItemSide, } enum ItemSide { Left, Right, } impl<T: Clone> SidedMergeItem<&T> { pub fn to_owned(self) -> SidedMergeItem<T> { SidedMergeItem { item: self.item.clone(), side: self.side, } } } impl<L, R> Iterator for SidedMerge<L, R> where L: Iterator<Item = R::Item>, R: Iterator, L::Item: Ord { type Item = SidedMergeItem<L::Item>; fn next(&mut self) -> Option<Self::Item> { let which = match (self.left.peek(), self.right.peek()) { (Some(l), Some(r)) => Some(l.cmp(r)), (Some(_), None) => Some(Ordering::Less), (None, Some(_)) => Some(Ordering::Greater), (None, None) => None, }; match which { Some(Ordering::Less) => { Some(SidedMergeItem { item: self.left.next().unwrap(), side: ItemSide::Left, }) }, Some(Ordering::Equal) => { Some(SidedMergeItem { item: self.left.next().unwrap(), side: ItemSide::Left, }) }, Some(Ordering::Greater) => { Some(SidedMergeItem { item: self.right.next().unwra
} struct SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { left: Peekable<L>, right: Peekable<R>, } impl<L, R> SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator { fn new(left: L, right: R) -> Self { SortedIntersect { left: left.peekable(), right: right.peekable(), } } } impl<L, R> Iterator for SortedIntersect<L, R> where L: Iterator<Item = R::Item>, R: Iterator, L::Item: Ord { type Item = L::Item; fn next(&mut self) -> Option<Self::Item> { let mut left = match self.left.next() { None => return None, Some(i) => i, }; let mut right = match self.right.next() { None => return None, Some(i) => i, }; use std::cmp::Ordering::*; loop { match left.cmp(&right) { Less => { left = match self.left.next() { Some(x) => x, None => return None, }; }, Greater => { right = match self.right.next() { Some(x) => x, None => return None, }; }, Equal => return Some(left), } } } } fn analogy_compare(analogy: &Analogy, left: &Symbol, right: &Symbol, atoms: &mut Vec<Atom>) { unimplemented!() } fn intersect_symbols(symbol_a: &Symbol, symbol_b: &Symbol) -> bool { let mut a_iter = symbol_a.atoms.iter(); let mut b_iter = symbol_b.atoms.iter(); let mut a = match a_iter.next() { Some(v) => v, None => { return false; }, }; let mut b = match b_iter.next() { Some(v) => v, None => { return false; }, }; use std::cmp::Ordering::*; loop { match a.cmp(b) { Less => { a = match a_iter.next() { Some(x) => x, None => return false, }; }, Greater => { b = match b_iter.next() { Some(x) => x, None => return false, }; }, Equal => return true, } } }
p(), side: ItemSide::Right, }) }, None => None, } }
function_block-function_prefixed
[ { "content": "pub fn parse<T: std::io::BufRead>(reader: T, query: &mut super::Query) -> Result<(), MBQLError> {\n\n for (line_number, line) in reader.lines().enumerate() {\n\n let line_str: String = line.map_err(|error| {\n\n MBQLError { position: Position { row: line_number },\n\n kind: MBQLErrorKind::IOError { error }, }\n\n })?;\n\n\n\n parse_line(line_number + 1, &line_str, query)?;\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/mbql/parse.rs", "rank": 2, "score": 175351.57727340126 }, { "content": "struct SymbolVarMapItem {\n\n offset: usize,\n\n symbol: Option<Symbol>,\n\n is_bound: bool,\n\n}\n\n\n\nuse std::rc::Rc;\n\n\n\n// #[derive(Debug, Clone)]\n\n// pub enum Bindable {\n\n// Symbolizable(Rc<ast::Symbolizable>),\n\n// GSymbolizable(Rc<ast::GSymbolizable>),\n\n// }\n\n\n\n// impl Bindable {\n\n// pub fn position(&self) -> &Position {\n\n// match self {\n\n// Bindable::Symbolizable(s) => s.position(),\n\n// Bindable::GSymbolizable(s) => s.position(),\n\n// }\n", "file_path": "src/mbql/query.rs", "rank": 3, "score": 164765.75978290613 }, { "content": "#[allow(unused)]\n\npub fn dump_json<T: std::io::Write>(mb: &MindBase, mut writer: T) -> Result<(), MBError> {\n\n for result in mb.artifact_iter() {\n\n let (id, artifact) = result?; // we may have failed to retrieve/decode one of them\n\n let string = serde_json::to_writer(&mut writer, &JSONLine::Artifact((id, artifact)))?;\n\n writer.write(b\"\\n\");\n\n }\n\n\n\n for result in mb.allegation_iter() {\n\n let (id, allegation) = result?; // we may have failed to retrieve/decode one of them\n\n let string = serde_json::to_writer(&mut writer, &JSONLine::Allegation((id, allegation)))?;\n\n writer.write(b\"\\n\");\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "src/xport.rs", "rank": 4, "score": 162755.83843663544 }, { "content": "#[allow(unused)]\n\npub fn load_json<T: std::io::BufRead>(mb: &MindBase, mut reader: T) -> Result<(), MBError> {\n\n for line in reader.lines() {\n\n let line: JSONLine = serde_json::from_str(&line?[..])?;\n\n\n\n match line {\n\n JSONLine::Allegation((_id, allegation)) => {\n\n mb.put_allegation(&allegation)?;\n\n },\n\n JSONLine::Artifact((_id, artifact)) => {\n\n mb.put_artifact(artifact)?;\n\n },\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n", "file_path": "src/xport.rs", "rank": 5, "score": 160069.6380756803 }, { "content": "fn get_ground_symbol(mb: &MindBase) -> Result<(), MBError> {\n\n unimplemented!()\n\n // let _symbol1: Symbol = mb.get_ground_symbol(vec![\"A\", \"B\", \"C\", \"D\"])?;\n\n // let _symbol2: Symbol = mb.get_ground_symbol(vec![\"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\"])?;\n\n // Ok(())\n\n}\n\n\n", "file_path": "benches/basic.rs", "rank": 6, "score": 154723.91236166286 }, { "content": "pub fn sym(id: &'static str) -> Symbol {\n\n Symbol::simple(id)\n\n}\n", "file_path": "experiments/analogy_compare/src/symbol.rs", "rank": 7, "score": 152230.83937232845 }, { "content": "// TODO 2 - move this to MBQL, and load it up with lots of stuffs\n\npub fn genesis(_mb: &MindBase) -> Result<(), MBError> {\n\n // let _words = mb.put_artifact(Text::new(\"English words\"))?;\n\n\n\n Ok(())\n\n}\n", "file_path": "src/genesis/language_en.rs", "rank": 8, "score": 148263.86347965387 }, { "content": "pub fn from_base64<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>\n\n where D: Deserializer<'de>\n\n{\n\n use serde::de::Error;\n\n use std::convert::TryInto;\n\n String::deserialize(deserializer).and_then(|string| base64::decode(&string).map_err(|err| D::Error::custom(err.to_string())))\n\n .map(|bytes| bytes[..].try_into())\n\n .and_then(|opt| opt.map_err(|_| D::Error::custom(\"failed to deserialize\")))\n\n}\n\n\n\nimpl fmt::Display for ArtifactId {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use base64::STANDARD_NO_PAD;\n\n write!(f, \"{}\", base64::encode_config(&self.0, STANDARD_NO_PAD))\n\n }\n\n}\n\nimpl fmt::Debug for ArtifactId {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"ArtifactId:{}\", base64::encode(&self.0))\n\n }\n", "file_path": "src/artifact.rs", "rank": 11, "score": 141984.4324988083 }, { "content": "struct ArtifactVarMapItem {\n\n offset: usize,\n\n id: Option<ArtifactId>,\n\n}\n\n\n", "file_path": "src/mbql/query.rs", "rank": 12, "score": 136436.85714212462 }, { "content": "fn overwrite_vec(vec: &mut Option<Vec<u8>>, atom: &AllegationId) {\n\n match vec {\n\n None => {\n\n let mut v = Vec::new();\n\n v.extend(atom.as_ref());\n\n *vec = Some(v);\n\n },\n\n Some(v) => {\n\n v.truncate(0);\n\n v.extend(atom.as_bytes());\n\n },\n\n }\n\n}\n\n// At each stage, I am searching for a set of\n\n// * Instantiated artifacts (ID)\n\n// * Associative Analogies (ID)\n\n// * Catagorical Analogies (ID)\n\n// Lets ignore Given symbols for now\n\n//\n\n// so what are our cardinalities here?\n\n// If I were to start at the root of a given GSymz tree, It would initially encompass all the data in the system\n\n// Lets assume this for a moment. What do you do next?\n\n// you iterate over each record, then recursively check its contents for matching\n\n// Lets just fucking do this, but do it as a module!\n\n// Make it work, make it correct, make it fast. Not the reverse :facepalm:\n", "file_path": "src/search/node.rs", "rank": 13, "score": 132994.66641583163 }, { "content": "#[test]\n\nfn dialog_1() -> Result<(), std::io::Error> {\n\n let tmpdir = tempfile::tempdir()?;\n\n let tmpdirpath = tmpdir.path();\n\n let mb = MindBase::open(&tmpdirpath)?;\n\n\n\n let alice = mb.default_agent()?;\n\n let bob = mb.create_agent()?;\n\n\n\n // Alice and bob were going about their day, when they bumped into each other on the sidewalk.\n\n // They each have a perspective about what was happening which differ slightly, but they generally agree.\n\n // They exchange some pleasantries and then go about their day.\n\n // The goal is to explain, categorize, and correlate each of these things from their own perspectives\n\n\n\n // They haven't yet bumped into each other. What are they doing?\n\n unimplemented!();\n\n // let _a_things_imdoing = mb.get_ground_symbol(vec![\"Things I'm doing\", \"Alice\"])?;\n\n // let _b_things_imdoing = mb.get_ground_symbol(vec![\"Things I'm doing\", \"Bob\"])?;\n\n\n\n // Alice is going to describe an event, and so we need a unique symbol for that. (each Allegation is a universally unique\n\n // Symbol) We are alledging/creating a symbol for this event against text artifact, but it could easily be an\n", "file_path": "tests/dialog.rs", "rank": 14, "score": 132685.94279383548 }, { "content": "#[test]\n\nfn saturday() -> Result<(), std::io::Error> {\n\n let tmpdir = tempfile::tempdir()?;\n\n let tmpdirpath = tmpdir.path();\n\n let _mb = MindBase::open(&tmpdirpath)?;\n\n\n\n // Lets find a grounding symbol for \"Saturday\"\n\n // This needs to be a symbol which we regognize from our authorities.\n\n // * Our own agent, plus some known set of other agents.\n\n\n\n // Could be this Saturday\n\n // Could be last Saturday\n\n // Could be the the abstract *idea* of Saturday\n\n // Could refer to one specific square on a paper calendar on your wall\n\n // Could refer to the column on a paper calendar\n\n // Could be a person's name...\n\n // let saturday = mb.ground_symbol(FlatText::new(\"Saturday\"));\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "tests/dialog.rs", "rank": 15, "score": 132685.94279383548 }, { "content": "fn insert_test_dataset(mb: &MindBase) -> Result<(), MBError> {\n\n for _i in 0..50 {\n\n let mut last_symbol: Option<Symbol> = None;\n\n // println!(\"Loop {}\", _i);\n\n for letter in (b'A'..=b'Z').map(|v| String::from_utf8(vec![v]).unwrap()) {\n\n let symbol = mb.alledge(text(&letter))?.subjective();\n\n\n\n if let Some(parent) = last_symbol.take() {\n\n mb.alledge(Analogy::declarative(symbol.clone(), parent))?;\n\n }\n\n\n\n last_symbol = Some(symbol);\n\n }\n\n }\n\n\n\n Ok(())\n\n}\n\n\n", "file_path": "benches/basic.rs", "rank": 16, "score": 130170.90866496369 }, { "content": "#[test]\n\nfn apple() -> Result<(), MBError> {\n\n let tmpdir = tempfile::tempdir()?;\n\n let tmpdirpath = tmpdir.path();\n\n let mb = MindBase::open(&tmpdirpath)?;\n\n\n\n let apple_computers = mb.alledge(Text::new(\"Apple\"))?;\n\n let apple_the_fruit = mb.alledge(Text::new(\"Apple\"))?;\n\n let apple_of_my_eye = mb.alledge(Text::new(\"Apple\"))?;\n\n\n\n // Look up the \"ground symbol\" for \"Apple\" without any additional specificity\n\n let query = mb.query_str(r#\"$a = Ground(\"Apple\")\"#)?;\n\n query.apply()?;\n\n\n\n let apple_ground_symbol = query.get_symbol_for_var(\"a\")?.unwrap();\n\n\n\n // It's... all of them. Why? Because meaning is contextual/intersectional.\n\n // We don't have enough information to narrow it down yet and we should not assume what they meant\n\n assert_eq!(apple_ground_symbol.count(), 3);\n\n\n\n let _statement = mb.alledge(Text::new(\"I love Apple\"))?;\n", "file_path": "tests/other.rs", "rank": 17, "score": 125770.25419982307 }, { "content": "#[test]\n\nfn fridays() -> Result<(), MBError> {\n\n let tmpdir = tempfile::tempdir()?;\n\n let tmpdirpath = tmpdir.path();\n\n let mb = MindBase::open(&tmpdirpath)?;\n\n\n\n // Next Friday\n\n let f1 = mb.alledge(\"Friday\")?.subjective();\n\n\n\n // The abstract symbol of Friday\n\n let f2 = mb.alledge(\"Friday\")?.subjective();\n\n\n\n // The person named Friday\n\n let f3 = mb.alledge(\"Friday\")?.subjective();\n\n\n\n let fut = mb.alledge(\"Days which are in the near future\")?.subjective();\n\n let dow = mb.alledge(\"Abstract day of the week\")?.subjective();\n\n let per = mb.alledge(\"Names for a person\")?.subjective();\n\n\n\n mb.alledge(Analogy::declarative(f1, fut))?;\n\n mb.alledge(Analogy::declarative(f2, dow))?;\n", "file_path": "tests/other.rs", "rank": 18, "score": 125770.25419982307 }, { "content": "#[test]\n\nfn alice() -> Result<(), MBError> {\n\n // The question is: how do we represent predicates? Things like \"was just like\", and \"in that we were\", etc\n\n //\n\n // Depending on how you want to look at it, you could say that:\n\n // * Mindbase has exactly one predicate \"is a member of\", which is simply implicit in every Analogy\n\n // or\n\n // * Mindbase has an infinite number of predicates which you can define – Buttt, they're fused to the object\n\n //\n\n // So, we get \"is in the category of\" for free with each analogy.\n\n // For a statement like \"The pan is hot\" we would think of this as:\n\n // [the pan] (is in the category of) [things that are hot]\n\n // Connecting words like \"things that are\" can generally be discarded, provided they are referring to the subject.\n\n // If the connecting words _do_ in fact change the meaning, then either the subject or the object should be recursively\n\n // expanded to reflect that meaning.\n\n //\n\n // # Why not subject-predicate-object triples?\n\n // * Because they converge poorly - (speculation)\n\n // * Because it externalizes the semantics of the predicate to the user\n\n // * Because the event of jumping into the lake is itself a discrete constituent of the\n\n // [Alice [jumped into] [the lake]]\n", "file_path": "tests/other.rs", "rank": 19, "score": 125770.25419982307 }, { "content": "fn parse_line(row: usize, input: &str, query: &mut super::Query) -> Result<(), MBQLError> {\n\n let mut line =\n\n MBQLParser::parse(Rule::statement, &input).map_err(|pest_err| {\n\n MBQLError { position: Position { row },\n\n kind: MBQLErrorKind::ParseRow { input: input.to_string(),\n\n pest_err }, }\n\n })?;\n\n\n\n let inner = match line.next() {\n\n None => return Ok(()), // Comment or blank line\n\n Some(s) => s,\n\n };\n\n\n\n let position = Position { row };\n\n ast::Statement::parse(inner, query, &position)?;\n\n\n\n Ok(())\n\n}\n\n\n\n// trait Parse {\n", "file_path": "src/mbql/parse.rs", "rank": 20, "score": 124267.39698197327 }, { "content": "#[test]\n\nfn apple_ii() -> Result<(), MBError> {\n\n // // Lets suppose that Alice makes a statement about apples. Lets record that having happened.\n\n // let alice_statement = mb.alledge(text(\"I love apples\"))?;\n\n\n\n // // Now, lets also use NLP to parse this statement:\n\n // // NP[I] VP[love apples]\n\n // // PRP[I] VBP[love] NP [apples]\n\n // //\n\n // // Note: these derrived Artifacts are related to the original artifact of alice's statement.\n\n // // TODO 2 - How should the system alledge that these are related, and that it wasn't actually alice who broke them\n\n // down // this way?\n\n // let _np_i = mb.alledge(text(\"I\"))?;\n\n // let _vp_love_apples = mb.alledge(text(\"love apples\"))?;\n\n // let prp_i = mb.alledge(text(\"I\"))?;\n\n\n\n // // vbp = Verb non-3rd person singular present form\n\n // let vbp_love = mb.alledge(text(\"love\"))?;\n\n // // np = Proper Noun\n\n // let np_apples = mb.alledge(text(\"apples\"))?;\n\n\n", "file_path": "tests/other.rs", "rank": 21, "score": 122081.58937256769 }, { "content": "#[test]\n\nfn apple() -> Result<(), MBError> {\n\n let tmpdir = tempfile::tempdir()?;\n\n let tmpdirpath = tmpdir.path();\n\n let mb = MindBase::open(&tmpdirpath)?;\n\n\n\n // Questions / notes:\n\n // - Where precisely is the taxonomy?\n\n // – How do we navigate this?\n\n // - What *exactly* do $d, $k, $p etc represent? -- How do we bind to the desired subsymbol in a grounding? (No really: ?)\n\n // - Something need to make the Token \"weightier\" when it comes time to render this, but why? -- Adding emphasis or schematic\n\n // annotation to this effect is clearly wrong, tantamount to putting one's thumb on the scale\n\n // - How do we do N dimensional analogical grounding rather than 1 dimensional?\n\n // - It seems we need some way to break associativity, and refer to the symbol itself -- .left creates a new composite symbol\n\n // of left-handed branch sub-symbols (abbreviated as <) -- .right creates a new composite symbol left-handed branch\n\n // sub-symbols (abbreviated as >) -- Thus $7.right.right (abbreviated as $7>>) should yield the unique symbol which is\n\n // tagged with \"Malus Domestica\" (and which may be queried by Ground(\"Token\":\"Type\") to yeild the unique symbol tagged with\n\n // \"Species\" )\n\n\n\n // TODO 1 - determine if subsymbol binding is compatible with resymbolizion in ground.rs - It should be\n\n // TODO 1 - determine how we might be able to ground in multiple dimensions. Maybe Symbolvars need to perform lazy\n", "file_path": "tests/apple.rs", "rank": 22, "score": 122081.5893725677 }, { "content": "// TODO 1 - Rename this to Symbolize\n\npub trait Alledgable: std::fmt::Debug {\n\n fn alledge(self, mb: &MindBase, agent: &Agent) -> Result<Allegation, MBError>;\n\n}\n", "file_path": "src/allegation.rs", "rank": 23, "score": 119756.36487397927 }, { "content": "struct Diag {\n\n elements: Vec<DiagElement>,\n\n}\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 24, "score": 117918.41254658937 }, { "content": "enum DiagElement {\n\n ArtifactVar(ArtifactVar),\n\n SymbolVar(SymbolVar, usize),\n\n}\n\n\n\nimpl DiagStatement {\n\n pub fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::diagstatement);\n\n\n\n let mut items = pair.into_inner();\n\n let mut elements = Vec::new();\n\n\n\n while let Some(d) = items.next() {\n\n assert_eq!(d.as_rule(), Rule::diagelement);\n\n\n\n let mut de_inner = d.into_inner();\n\n let var = de_inner.next().unwrap();\n\n let e = match var.as_rule() {\n\n Rule::artifactvar => DiagElement::ArtifactVar(ArtifactVar::parse(var, position)?),\n\n Rule::symbolvar => {\n", "file_path": "src/mbql/ast.rs", "rank": 26, "score": 114510.82008913253 }, { "content": "pub fn atom(id: &'static str) -> Atom {\n\n Atom { id: AtomId(id),\n\n side: Side::Left,\n\n spin: Spin::Up, }\n\n}\n\n\n\n#[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)]\n\npub struct Atom {\n\n pub id: AtomId,\n\n pub spin: Spin,\n\n pub side: Side,\n\n}\n\n\n\nimpl Atom {\n\n pub fn new(id: AtomId) -> Self {\n\n Atom { id,\n\n side: Side::Middle,\n\n spin: Spin::Up }\n\n }\n\n\n", "file_path": "experiments/analogy_compare/src/atom.rs", "rank": 27, "score": 101524.09842277796 }, { "content": "fn _default_agent(my_agents: &sled::Tree) -> Result<Agent, MBError> {\n\n match my_agents.get(b\"latest\")? {\n\n None => _create_agent(my_agents),\n\n Some(pubkey) => {\n\n match my_agents.get(pubkey)? {\n\n None => Err(MBError::AgentHandleNotFound),\n\n Some(v) => {\n\n let agenthandle = bincode::deserialize(&v)?;\n\n Ok(agenthandle)\n\n },\n\n }\n\n },\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 28, "score": 99630.47572815919 }, { "content": "fn _create_agent(my_agents: &sled::Tree) -> Result<Agent, MBError> {\n\n let agent = Agent::new();\n\n\n\n let encoded: Vec<u8> = bincode::serialize(&agent).unwrap();\n\n my_agents.insert(agent.pubkey().as_bytes(), encoded)?;\n\n my_agents.insert(b\"latest\", agent.pubkey().as_bytes())?;\n\n my_agents.flush()?;\n\n\n\n Ok(agent)\n\n}\n\n\n\npub struct Iter<K, V> {\n\n iter: sled::Iter,\n\n phantomkey: std::marker::PhantomData<K>,\n\n phantomvalue: std::marker::PhantomData<V>,\n\n}\n\n\n\nimpl<K, V> Iterator for Iter<K, V>\n\n where K: std::convert::TryFrom<IVec>,\n\n V: DeserializeOwned\n", "file_path": "src/lib.rs", "rank": 29, "score": 99630.47572815919 }, { "content": "pub fn as_base64<T, S>(v: &T, serializer: S) -> Result<S::Ok, S::Error>\n\n where T: AsRef<[u8]>,\n\n S: Serializer\n\n{\n\n use base64::STANDARD_NO_PAD;\n\n serializer.serialize_str(&base64::encode_config(v.as_ref(), STANDARD_NO_PAD))\n\n}\n\n\n", "file_path": "src/artifact.rs", "rank": 30, "score": 98017.04756356427 }, { "content": "\n", "file_path": "src/mbql/ast/symbol.rs", "rank": 31, "score": 94264.57754787208 }, { "content": "pub fn text(text: &str) -> Text {\n\n Text::new(text)\n\n}\n\n\n\n/// Text of nonspecific structure, origin, and language\n\n#[derive(Serialize, Deserialize, PartialEq, Debug)]\n\npub struct Text {\n\n text: String,\n\n}\n\n\n\nimpl Text {\n\n pub fn new(text: &str) -> Self {\n\n Text { text: text.to_string() }\n\n }\n\n\n\n pub fn string(text: String) -> Self {\n\n Text { text }\n\n }\n\n}\n\n\n", "file_path": "src/artifact.rs", "rank": 32, "score": 86312.63748909938 }, { "content": "fn merge_16byte_list(_key: &[u8], // the key being merged\n\n last_bytes: Option<&[u8]>, // the previous value, if one existed\n\n op_bytes: &[u8] /* the new bytes being merged in */)\n\n -> Option<Vec<u8>> {\n\n // set the new value, return None to delete\n\n\n\n use inverted_index_util::entity_list::{\n\n insert_entity_immut,\n\n ImmutResult,\n\n };\n\n use typenum::consts::U16;\n\n\n\n Some(match last_bytes {\n\n Some(prior) => {\n\n match insert_entity_immut::<U16>(prior, op_bytes) {\n\n ImmutResult::Changed(newvec) => newvec,\n\n ImmutResult::Unchanged => prior.to_vec(),\n\n }\n\n },\n\n None => op_bytes.to_vec(),\n", "file_path": "src/lib.rs", "rank": 33, "score": 79749.7573927049 }, { "content": "fn main() {\n\n experiment1()\n\n}\n\n\n", "file_path": "experiments/analogy_compare/src/main.rs", "rank": 34, "score": 76075.4404853278 }, { "content": "fn experiment1() {\n\n // In this experiment, we are approxmiating the following MBQL\n\n // $x = Bind(\"Hot\")\n\n // $y = Ground($x : \"Cold\")\n\n\n\n let mut x = Symbol::null();\n\n let mut y = Symbol::null();\n\n\n\n // For simplicity, lets say these are all the analogies in the system\n\n let candidates = [Analogy::new(AtomId(\"a1\"), sym(\"Hot1\"), sym(\"Cold1\")),\n\n Analogy::new(AtomId(\"a2\"), sym(\"Hot2\"), sym(\"Cold2\")),\n\n Analogy::new(AtomId(\"a3\"), sym(\"Cold3\"), sym(\"Hot3\"))];\n\n\n\n // NOTE - this should have an unassigned Spin, because it's a match pair\n\n let search_pair = AtomVec::from_left_right(\"Hot\", \"Cold\");\n\n println!(\"Searching for {}\", search_pair.diag_lr());\n\n\n\n for candidate in &candidates {\n\n let v = candidate.intersect(&search_pair).expect(\"All of the above should match\");\n\n x.atoms.extend(v.left());\n", "file_path": "experiments/analogy_compare/src/main.rs", "rank": 35, "score": 76075.4404853278 }, { "content": "fn experiment2() {\n\n // $x = Bind(\"Hot\")\n\n // $y = Ground(($x : \"Cold\") : (\"Spicy\" : \"Mild\"))\n\n let a1 = Analogy::new(AtomId(\"a1\"), sym(\"Hot1\"), sym(\"Cold1\"));\n\n let a2 = Analogy::new(AtomId(\"a2\"), sym(\"Cold1\"), sym(\"Hot1\"));\n\n\n\n // NOTE - this should have an unassigned Spin, because it's a match pair\n\n let search_pair = AtomVec::from_left_right(\"Hot1\", \"Cold1\");\n\n // pair.insert(atom(\"Cold2\").left());\n\n // pair.insert(atom(\"Hot2\").right());\n\n\n\n // println!(\"{:?}\", a1);\n\n println!(\"{:?}\", search_pair);\n\n\n\n // This compares the analogy to a SymbolPair\n\n let p1 = a1.intersect(&search_pair).unwrap();\n\n // THIS is what we actually want to use for the bound symbol\n\n\n\n println!(\"p1: {:?}\", p1.diag_lr());\n\n\n\n let p2 = a2.intersect(&search_pair).unwrap();\n\n println!(\"p2: {:?}\", p2.diag_lr());\n\n}\n", "file_path": "experiments/analogy_compare/src/main.rs", "rank": 36, "score": 76075.4404853278 }, { "content": "\n\n pub fn stash_symbol_for_var(&self, var: &ast::SymbolVar, symbol: Symbol) -> Result<(), MBQLError> {\n\n match self.symbol_var_map.lock().unwrap().get_mut(&var.var) {\n\n None => {\n\n return Err(MBQLError { position: var.position.clone(),\n\n kind: MBQLErrorKind::SymbolVarNotFound { var: var.var.clone() }, })\n\n },\n\n Some(v) => v.symbol = Some(symbol),\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn get_symbol_for_var(&self, var: &str) -> Result<Option<Symbol>, MBError> {\n\n match self.symbol_var_map.lock().unwrap().get(var) {\n\n None => return Ok(None),\n\n Some(SymbolVarMapItem { symbol, .. }) => {\n\n if let Some(symbol) = symbol {\n\n // This could be a SymbolStatement or a BindStatement. Either way it must already be symbolized\n\n return Ok(Some(symbol.clone()));\n\n }\n", "file_path": "src/mbql/query.rs", "rank": 37, "score": 65939.18972061102 }, { "content": " symbol_var_map: Mutex::new(BTreeMap::new()),\n\n search_context: Mutex::new(SearchContext::new(mb)),\n\n mb };\n\n super::parse::parse(reader, &mut query)?;\n\n\n\n Ok(query)\n\n }\n\n\n\n pub fn from_str(mb: &'a MindBase, mbql_string: &str) -> Result<Self, MBQLError> {\n\n let cur = Cursor::new(mbql_string);\n\n Self::new(mb, cur)\n\n }\n\n\n\n pub fn add_statement(&mut self, statement: ast::Statement) {\n\n let offset = self.statements.len();\n\n\n\n match &statement {\n\n ast::Statement::Artifact(s) => {\n\n let mut avm = self.artifact_var_map.lock().unwrap();\n\n avm.insert(s.var.var.clone(), ArtifactVarMapItem { offset, id: None });\n", "file_path": "src/mbql/query.rs", "rank": 38, "score": 65937.66528344539 }, { "content": "// }\n\n// }\n\n\n\npub struct Query<'a> {\n\n pub statements: Vec<ast::Statement>,\n\n artifact_var_map: Mutex<BTreeMap<String, ArtifactVarMapItem>>,\n\n symbol_var_map: Mutex<BTreeMap<String, SymbolVarMapItem>>,\n\n pub search_context: Mutex<SearchContext<'a>>,\n\n pub mb: &'a MindBase,\n\n}\n\n\n\npub enum BindResult {\n\n Bound(Rc<ast::GSymbolizable>),\n\n Symbol(Symbol),\n\n}\n\n\n\nimpl<'a> Query<'a> {\n\n pub fn new<T: std::io::BufRead>(mb: &'a MindBase, reader: T) -> Result<Self, MBQLError> {\n\n let mut query = Query { statements: Vec::new(),\n\n artifact_var_map: Mutex::new(BTreeMap::new()),\n", "file_path": "src/mbql/query.rs", "rank": 39, "score": 65936.24890631145 }, { "content": "use super::{\n\n ast,\n\n error::{\n\n MBQLError,\n\n MBQLErrorKind,\n\n },\n\n Position,\n\n};\n\nuse crate::{\n\n search::SearchContext,\n\n ArtifactId,\n\n MBError,\n\n MindBase,\n\n Symbol,\n\n};\n\nuse std::{\n\n collections::BTreeMap,\n\n io::Cursor,\n\n sync::Mutex,\n\n};\n\n\n", "file_path": "src/mbql/query.rs", "rank": 40, "score": 65935.4588365189 }, { "content": " None => Err(MBError::SymbolVarNotFound),\n\n }\n\n },\n\n _ => {\n\n panic!(\"Sanity error\");\n\n },\n\n }\n\n },\n\n }\n\n }\n\n\n\n pub fn dump<T: std::io::Write>(&self, mut writer: T) -> Result<(), std::io::Error> {\n\n for statement in self.statements.iter() {\n\n statement.write(&mut writer)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn apply(&self) -> Result<(), MBQLError> {\n", "file_path": "src/mbql/query.rs", "rank": 41, "score": 65934.0176952042 }, { "content": " },\n\n Some(SymbolVarMapItem { offset,\n\n symbol,\n\n is_bound, }) => {\n\n // It should be unbound, otherwise throw an error\n\n\n\n if *is_bound {\n\n return Err(MBError::SymbolVarAlreadyBound);\n\n }\n\n\n\n match self.statements.get(*offset).unwrap() {\n\n ast::Statement::Bind(ast::BindStatement { gsymz, .. }) => {\n\n // for now we're only supporting binding to other ground statements\n\n *is_bound = true;\n\n let foo = gsymz.clone();\n\n Ok(BindResult::Bound(foo))\n\n },\n\n ast::Statement::Symbol(_) => {\n\n match symbol {\n\n Some(symbol) => Ok(BindResult::Symbol(symbol.clone())),\n", "file_path": "src/mbql/query.rs", "rank": 42, "score": 65933.50611158858 }, { "content": " };\n\n\n\n self.statements.push(statement);\n\n }\n\n\n\n // Have to be able to write independently, as Artifact variables may be evaluated recursively\n\n pub fn stash_artifact_for_var(&self, var: &ast::ArtifactVar, artifact_id: ArtifactId) -> Result<(), MBQLError> {\n\n match self.artifact_var_map.lock().unwrap().get_mut(&var.var) {\n\n None => {\n\n return Err(MBQLError { position: var.position.clone(),\n\n kind: MBQLErrorKind::ArtifactVarNotFound { var: var.var.clone() }, })\n\n },\n\n Some(v) => v.id = Some(artifact_id),\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn get_artifact_var(&self, var: &str) -> Result<Option<ArtifactId>, MBError> {\n\n let offset = match self.artifact_var_map.lock().unwrap().get(var) {\n\n None => return Ok(None),\n", "file_path": "src/mbql/query.rs", "rank": 43, "score": 65932.32440953018 }, { "content": " },\n\n };\n\n\n\n // We see it, but it's not set\n\n // Was previously doing lazy/out of order execution, but that's hard for the user to reason about\n\n // So we are insisting that they refer only to symbol vars which were previously set by their execution\n\n\n\n Err(MBError::SymbolVarNotFound)\n\n }\n\n\n\n // Bind to a `BindStatement` or return the Symbol from a SymbolStatement\n\n pub fn bind_symbolvar(&self, var: &str) -> Result<BindResult, MBError> {\n\n // Look up the symbolvar by string\n\n\n\n match self.symbol_var_map.lock().unwrap().get_mut(var) {\n\n None => {\n\n // TODO change this to MBError?\n\n // Why the distinction?\n\n // because it's strange to send in the bind_to only for its position?\n\n Err(MBError::SymbolVarNotFound)\n", "file_path": "src/mbql/query.rs", "rank": 44, "score": 65927.43577561517 }, { "content": " Some(ArtifactVarMapItem { offset, id }) => {\n\n if let Some(artifact_id) = id {\n\n return Ok(Some(artifact_id.clone()));\n\n }\n\n offset.clone()\n\n },\n\n };\n\n\n\n // Didn't have it yet. gotta calculate it\n\n match self.statements.get(offset).unwrap() {\n\n ast::Statement::Artifact(statement) => {\n\n return Ok(Some(statement.apply(self)?));\n\n },\n\n _ => {\n\n panic!(\"Sanity error\");\n\n },\n\n }\n\n }\n\n\n\n // pub fn get_symbolizable_for_var{}\n", "file_path": "src/mbql/query.rs", "rank": 45, "score": 65926.21127548307 }, { "content": " // TODO 2 - Validate all possible MBQLErrors at query creation time so that all remaining errors are MBErrors\n\n // and then change this to return Result<(),MBError>\n\n\n\n // iterate over all artifact statements and store\n\n // iterate over all symbol statements and recurse\n\n\n\n // gotta start somewhere\n\n // could be a cyclic graph\n\n // even artifacts must be able to recurse symbols\n\n\n\n for statement in self.statements.iter() {\n\n statement.apply(self)?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n", "file_path": "src/mbql/query.rs", "rank": 46, "score": 65926.12700703814 }, { "content": " },\n\n\n\n ast::Statement::Bind(s) => {\n\n let mut svm = self.symbol_var_map.lock().unwrap();\n\n svm.insert(s.sv.var.to_string(),\n\n SymbolVarMapItem { offset,\n\n symbol: None,\n\n is_bound: false });\n\n },\n\n ast::Statement::Symbol(s) => {\n\n if let Some(var) = &s.var {\n\n let mut svm = self.symbol_var_map.lock().unwrap();\n\n svm.insert(var.to_string(),\n\n SymbolVarMapItem { offset,\n\n symbol: None,\n\n is_bound: false });\n\n }\n\n },\n\n\n\n ast::Statement::Diag(_) => {},\n", "file_path": "src/mbql/query.rs", "rank": 47, "score": 65923.86535873965 }, { "content": " var: String,\n\n },\n\n SymbolVarBindingFailed {\n\n bound_to: std::rc::Rc<ast::SymbolStatement>,\n\n },\n\n\n\n // TODO 2 - Move this to MBError\n\n GSymNotFound,\n\n\n\n MBError(Box<MBError>),\n\n}\n\n\n\nimpl std::convert::From<MBError> for MBQLError {\n\n fn from(error: MBError) -> Self {\n\n MBQLError { position: Position::none(),\n\n kind: MBQLErrorKind::MBError(Box::new(error)), }\n\n }\n\n}\n\nimpl std::convert::From<MBQLError> for std::io::Error {\n\n fn from(error: MBQLError) -> Self {\n", "file_path": "src/mbql/error.rs", "rank": 48, "score": 65703.85627775635 }, { "content": "#[derive(Debug)]\n\npub struct MBQLError {\n\n pub position: Position,\n\n pub kind: MBQLErrorKind,\n\n}\n\n\n\nuse crate::{\n\n error::MBError,\n\n mbql::{\n\n ast,\n\n Position,\n\n },\n\n};\n\n\n\n#[derive(Debug)]\n\npub enum MBQLErrorKind {\n\n IOError {\n\n error: std::io::Error,\n\n },\n\n ParseRow {\n", "file_path": "src/mbql/error.rs", "rank": 49, "score": 65702.92688496834 }, { "content": " std::io::Error::new(std::io::ErrorKind::Other, format!(\"{}\", error))\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for MBQLError {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n match &self.kind {\n\n MBQLErrorKind::IOError { error } => f.write_fmt(format_args!(\"IO Error: {}\", error)),\n\n MBQLErrorKind::InvalidLine { input } => f.write_fmt(format_args!(\"Invalid row at {}: {}\", self.position.row, input)),\n\n MBQLErrorKind::ParseRow { pest_err, .. } => {\n\n // TODO - fix line numbers\n\n f.write_fmt(format_args!(\"Failed to parse row {}: {}\", self.position.row, pest_err))\n\n },\n\n MBQLErrorKind::InvalidCommand { .. } => f.write_str(\"meow\"),\n\n MBQLErrorKind::UnknownCommand { .. } => f.write_str(\"meow\"),\n\n MBQLErrorKind::CommandParse { .. } => f.write_str(\"meow\"),\n\n MBQLErrorKind::MBError(e) => write!(f, \"{:?}\", e),\n\n MBQLErrorKind::ArtifactVarNotFound { var } => {\n\n write!(f, \"Artifact Variable `{}` not found at row {}\", var, self.position.row)\n\n },\n", "file_path": "src/mbql/error.rs", "rank": 50, "score": 65693.93808933957 }, { "content": " input: String,\n\n pest_err: pest::error::Error<super::parse::Rule>,\n\n },\n\n InvalidLine {\n\n input: String,\n\n },\n\n InvalidCommand {\n\n command: String,\n\n },\n\n UnknownCommand {\n\n command: String,\n\n },\n\n CommandParse {\n\n body: String,\n\n // ron: ron::de::Error,\n\n },\n\n ArtifactVarNotFound {\n\n var: String,\n\n },\n\n SymbolVarNotFound {\n", "file_path": "src/mbql/error.rs", "rank": 51, "score": 65687.72759946495 }, { "content": " MBQLErrorKind::SymbolVarNotFound { var } => {\n\n write!(f, \"Symbol Variable `{}` not found at row {}\", var, self.position.row)\n\n },\n\n MBQLErrorKind::GSymNotFound => write!(f, \"Ground Symbol not found at row {}\", self.position.row),\n\n\n\n MBQLErrorKind::SymbolVarBindingFailed { bound_to } => {\n\n write!(f,\n\n \"Symbol binding failed at row {}. Already bound to row {}\",\n\n self.position.row,\n\n bound_to.position().row)\n\n },\n\n }\n\n }\n\n}\n", "file_path": "src/mbql/error.rs", "rank": 52, "score": 65687.06387253338 }, { "content": "\n\n pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n let left = self.left.apply(query)?;\n\n let right = self.right.apply(query)?;\n\n\n\n let symbol = query.mb.symbolize(Analogy::declarative(left, right))?;\n\n Ok(symbol)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Symbolize {\n\n symbolizable: Rc<Symbolizable>,\n\n position: Position,\n\n}\n\nimpl Symbolize {\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::symbolize);\n\n Ok(Symbolize { symbolizable: Rc::new(Symbolizable::parse(pair.into_inner().next().unwrap(), position)?),\n\n position: position.clone(), })\n", "file_path": "src/mbql/ast.rs", "rank": 53, "score": 65108.59394212406 }, { "content": " }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<ArtifactId, MBQLError> {\n\n let artifact_id = match self {\n\n Artifact::Agent(agent) => query.mb.put_artifact(agent.get_agent_id(query.mb)?)?,\n\n Artifact::Url(url) => query.mb.put_artifact(crate::artifact::Url { url: url.url.clone() })?,\n\n Artifact::Text(text) => query.mb.put_artifact(crate::artifact::Text::new(&text.text))?,\n\n Artifact::DataNode(node) => {\n\n let data_type = node.data_type.apply(query)?;\n\n query.mb.put_artifact(crate::artifact::DataNode { data_type,\n\n data: node.data.clone() })?\n\n },\n\n // Artifact::DataRelation(relation) => relation.write(writer)?,\n\n Artifact::ArtifactVar(var) => {\n\n match query.get_artifact_var(&var.var)? {\n\n None => {\n\n return Err(MBQLError { position: var.position.clone(),\n\n kind: MBQLErrorKind::ArtifactVarNotFound { var: var.var.clone() }, })\n\n },\n\n Some(a) => a,\n", "file_path": "src/mbql/ast.rs", "rank": 54, "score": 65107.02298495406 }, { "content": " GSymbolizable::GroundPair(x) => &x.position,\n\n }\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool, nest: bool) -> Result<(), std::io::Error> {\n\n match self {\n\n GSymbolizable::Artifact(a) => a.write(writer, verbose)?,\n\n GSymbolizable::GroundPair(p) => p.write(writer, nest)?,\n\n GSymbolizable::SymbolVar(sv) => sv.write(writer)?,\n\n GSymbolizable::Ground(g) => g.write(writer, verbose)?,\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n // pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n // let symbol = match self {\n\n // GroundSymbolizable::Artifact(a) => query.mb.get_ground_symbol(a)?,\n\n // GroundSymbolizable::GroundPair(a) => a.apply(query),\n\n // // GroundSymbolizable::SymbolVar(sv) => sv.apply(query),\n", "file_path": "src/mbql/ast.rs", "rank": 55, "score": 65105.342522083345 }, { "content": "\n\n match search_node.symbol() {\n\n None => {\n\n if self.vivify {\n\n search_node.vivify_symbols(query)?;\n\n search_node.stash_bindings(query)?;\n\n Ok(search_node.symbol().unwrap())\n\n } else {\n\n Err(MBQLError { position: self.position.clone(),\n\n kind: MBQLErrorKind::GSymNotFound, })\n\n }\n\n },\n\n Some(symbol) => {\n\n search_node.stash_bindings(query)?;\n\n Ok(symbol)\n\n },\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 56, "score": 65104.87986838369 }, { "content": "\n\n pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n let symbol = match self {\n\n Symbolizable::Artifact(a) => {\n\n let artifact_id = a.apply(query)?;\n\n println!(\"SYMBOLIZE: {}\", artifact_id);\n\n query.mb.symbolize(artifact_id)?\n\n },\n\n Symbolizable::Allege(a) => a.apply(query)?,\n\n // Symbolizable::SymbolVar(sv) => sv.apply(query),\n\n Symbolizable::Ground(g) => g.apply(query)?,\n\n Symbolizable::Symbolize(s) => s.apply(query)?,\n\n Symbolizable::SymbolVar(sv) => sv.apply(query)?,\n\n };\n\n\n\n Ok(symbol)\n\n }\n\n\n\n pub fn position(&self) -> &Position {\n\n match self {\n", "file_path": "src/mbql/ast.rs", "rank": 57, "score": 65104.07080098083 }, { "content": " pub right: Rc<GSymbolizable>,\n\n position: Position,\n\n}\n\n\n\nimpl GPair {\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::allege);\n\n\n\n let mut ground_symbol_pair = pair.into_inner().next().unwrap().into_inner();\n\n\n\n // According to the grammar, Allege may only contain symbol_pair\n\n let left = GSymbolizable::parse(ground_symbol_pair.next().unwrap(), position)?;\n\n let right = GSymbolizable::parse(ground_symbol_pair.next().unwrap(), position)?;\n\n\n\n Ok(GPair { left: Rc::new(left),\n\n right: Rc::new(right),\n\n position: position.clone(), })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, nest: bool) -> Result<(), std::io::Error> {\n", "file_path": "src/mbql/ast.rs", "rank": 58, "score": 65103.817746614564 }, { "content": " use std::fmt::Write;\n\n\n\n let mut out = String::new();\n\n let mut seen = false;\n\n for item in self.diag.elements.iter() {\n\n if seen {\n\n out.push_str(\", \");\n\n }\n\n seen = true;\n\n\n\n match item {\n\n DiagElement::ArtifactVar(var) => {\n\n if let Some(artifact_id) = query.get_artifact_var(&var.var)? {\n\n out.push_str(&format!(\"{} = {}\", var, artifact_id));\n\n } else {\n\n return Err(MBQLError { position: var.position.clone(),\n\n kind: MBQLErrorKind::ArtifactVarNotFound { var: var.var.clone() }, });\n\n }\n\n },\n\n DiagElement::SymbolVar(v, depth) => {\n", "file_path": "src/mbql/ast.rs", "rank": 59, "score": 65103.665212381355 }, { "content": "pub mod artifact;\n\n\n\nuse crate::{\n\n mbql::{\n\n error::MBQLError,\n\n parse::{\n\n self,\n\n Rule,\n\n },\n\n Position,\n\n Query,\n\n },\n\n search::SearchNode,\n\n AgentId,\n\n Analogy,\n\n ArtifactId,\n\n MBError,\n\n MindBase,\n\n Symbol,\n\n};\n", "file_path": "src/mbql/ast.rs", "rank": 60, "score": 65102.759670168336 }, { "content": " _ => unreachable!(),\n\n }\n\n },\n\n _ => unreachable!(),\n\n };\n\n\n\n Ok(s)\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool, nest: bool) -> Result<(), std::io::Error> {\n\n match self {\n\n Symbolizable::Artifact(a) => a.write(writer, verbose)?,\n\n Symbolizable::Allege(a) => a.write(writer, verbose, nest)?,\n\n Symbolizable::SymbolVar(sv) => sv.write(writer)?,\n\n Symbolizable::Ground(g) => g.write(writer, verbose)?,\n\n Symbolizable::Symbolize(s) => s.write(writer, verbose)?,\n\n }\n\n\n\n Ok(())\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 61, "score": 65102.19566782318 }, { "content": "#[derive(Debug)]\n\npub struct Allege {\n\n position: Position,\n\n left: Rc<Symbolizable>,\n\n right: Rc<Symbolizable>,\n\n}\n\n\n\nimpl Allege {\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::allege);\n\n\n\n let mut symbol_pair = pair.into_inner().next().unwrap().into_inner();\n\n\n\n // According to the grammar, Allege may only contain symbol_pair\n\n let left = Symbolizable::parse(symbol_pair.next().unwrap(), position)?;\n\n let right = Symbolizable::parse(symbol_pair.next().unwrap(), position)?;\n\n\n\n Ok(Allege { left: Rc::new(left),\n\n right: Rc::new(right),\n\n position: position.clone(), })\n", "file_path": "src/mbql/ast.rs", "rank": 62, "score": 65101.16053680677 }, { "content": " pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::symbolvar);\n\n Ok(Self { var: pair.into_inner().next().unwrap().as_str().to_string(),\n\n position: position.clone(), })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n writer.write(format!(\"${}\", self.var).as_bytes())?;\n\n Ok(())\n\n }\n\n\n\n pub fn to_string(&self) -> String {\n\n self.var.clone()\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n if let Some(symbol) = query.get_symbol_for_var(&self.var)? {\n\n Ok(symbol)\n\n } else {\n\n return Err(MBQLError { position: self.position.clone(),\n", "file_path": "src/mbql/ast.rs", "rank": 63, "score": 65100.70443522475 }, { "content": " if let Some(symbol) = query.get_symbol_for_var(&v.var)? {\n\n write!(out, \"{} = \", v).unwrap();\n\n symbol.contents_buf(query.mb, &mut out, *depth)?;\n\n } else {\n\n return Err(MBQLError { position: v.position.clone(),\n\n kind: MBQLErrorKind::SymbolVarNotFound { var: v.var.clone() }, });\n\n }\n\n },\n\n }\n\n }\n\n println!(\"DIAG: {}\", out);\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl DiagElement {\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n match self {\n\n DiagElement::ArtifactVar(v) => v.write(writer)?,\n\n DiagElement::SymbolVar(v, depth) => {\n", "file_path": "src/mbql/ast.rs", "rank": 64, "score": 65100.52024529009 }, { "content": "#[derive(Debug)]\n\npub enum Symbolizable {\n\n Artifact(Artifact),\n\n Allege(Allege),\n\n SymbolVar(SymbolVar),\n\n Ground(Ground),\n\n Symbolize(Symbolize),\n\n}\n\n\n\nimpl Symbolizable {\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n // because of left-recursion issues, we had to construct symbolizable in a slightly odd way\n\n // which necessitates allege and ground to support symbol_pair AND symbolizable as potential child elements\n\n // So we are handling symbol_pair if they were symbolizable\n\n let s = match pair.as_rule() {\n\n Rule::symbol_pair => {\n\n let mut inner = pair.into_inner();\n\n let left = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n let right = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n Symbolizable::Allege(Allege { left: Rc::new(left),\n", "file_path": "src/mbql/ast.rs", "rank": 65, "score": 65099.6763922445 }, { "content": " // // GroundSymbolizable::Ground(g) => g.apply(query),\n\n // _ => unimplemented!(),\n\n // };\n\n // Ok(symbol)\n\n // }\n\n}\n\n\n\n// impl GroundSymbolize for GroundSymbolizable {\n\n// fn symbol(&self) -> Option<Symbol> {\n\n// None\n\n// }\n\n\n\n// fn symbolize(&self, context: &mut crate::GSContext) -> Result<Symbol, crate::MBError> {\n\n// unimplemented!()\n\n// }\n\n// }\n\n\n\n#[derive(Debug)]\n\npub struct GPair {\n\n pub left: Rc<GSymbolizable>,\n", "file_path": "src/mbql/ast.rs", "rank": 66, "score": 65099.65645623379 }, { "content": "\n\nuse super::error::MBQLErrorKind;\n\nuse pest::iterators::Pair;\n\n\n\nuse std::rc::Rc;\n\n\n\npub enum Statement {\n\n Bind(BindStatement),\n\n Diag(DiagStatement),\n\n Symbol(SymbolStatement),\n\n Artifact(ArtifactStatement),\n\n}\n\n\n\nimpl Statement {\n\n pub fn parse(element: Pair<Rule>, query: &mut crate::mbql::Query, position: &Position) -> Result<(), MBQLError> {\n\n let me = match element.as_rule() {\n\n Rule::EOI => return Ok(()), // Comment or blank line\n\n Rule::artifactstatement => Statement::Artifact(ArtifactStatement::parse(element, position)?),\n\n Rule::bindstatement => Statement::Bind(BindStatement::parse(element, position)?),\n\n Rule::symbolstatement => Statement::Symbol(SymbolStatement::parse(element, position)?),\n", "file_path": "src/mbql/ast.rs", "rank": 67, "score": 65098.332274353816 }, { "content": "\n\nimpl DataNode {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n let mut inner = pair.into_inner();\n\n let data_type = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n\n\n let data = match inner.next() {\n\n Some(next) => {\n\n match next.as_rule() {\n\n Rule::base64 => Some(base64::decode(next.as_str()).unwrap()),\n\n Rule::quoted_string => Some(next.as_str().replace(\"\\\\\\\"\", \"\\\"\").as_bytes().to_owned()),\n\n _ => unreachable!(),\n\n }\n\n },\n\n None => None,\n\n };\n\n\n\n Ok(DataNode { data_type: Rc::new(data_type),\n\n data,\n\n position: position.clone() })\n", "file_path": "src/mbql/ast.rs", "rank": 68, "score": 65098.1807961102 }, { "content": " Ok(DiagStatement { position: position.clone(),\n\n diag: Diag { elements }, })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n writer.write(b\"Diag(\")?;\n\n let mut seen = false;\n\n for item in self.diag.elements.iter() {\n\n if seen {\n\n writer.write(b\", \")?;\n\n }\n\n seen = true;\n\n\n\n item.write(writer)?;\n\n }\n\n writer.write(b\")\\n\")?;\n\n Ok(())\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<(), MBQLError> {\n", "file_path": "src/mbql/ast.rs", "rank": 69, "score": 65097.84085287528 }, { "content": " }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool) -> Result<(), std::io::Error> {\n\n if verbose {\n\n writer.write(b\"Symbolize(\")?;\n\n }\n\n\n\n self.symbolizable.write(writer, false, false)?;\n\n\n\n if verbose {\n\n writer.write(b\")\")?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n self.symbolizable.apply(query)\n\n }\n\n}\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 70, "score": 65097.7440343053 }, { "content": " symz: symbol,\n\n position: position.clone() })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n if let Some(var) = &self.var {\n\n var.write(writer)?;\n\n writer.write(b\" = \")?;\n\n }\n\n self.symz.write(writer, true, false)?;\n\n writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<(), MBQLError> {\n\n let symbol = self.symz.apply(query)?;\n\n\n\n if let Some(var) = &self.var {\n\n query.stash_symbol_for_var(var, symbol.clone())?;\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 71, "score": 65097.39801518098 }, { "content": " if nest {\n\n writer.write(b\"(\")?;\n\n }\n\n\n\n self.left.write(writer, false, true)?;\n\n writer.write(b\" : \")?;\n\n self.right.write(writer, false, true)?;\n\n\n\n if nest {\n\n writer.write(b\")\")?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn position(&self) -> &Position {\n\n &self.position\n\n }\n\n // pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n // unimplemented!()\n\n // }\n", "file_path": "src/mbql/ast.rs", "rank": 72, "score": 65096.08882210894 }, { "content": " position: position.clone(), })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool) -> Result<(), std::io::Error> {\n\n if verbose {\n\n writer.write(format!(\"Text(\\\"{}\\\")\", self.text.replace(\"\\\"\", \"\\\\\\\"\")).as_bytes())?;\n\n } else {\n\n writer.write(format!(\"\\\"{}\\\"\", self.text.replace(\"\\\"\", \"\\\\\\\"\")).as_bytes())?;\n\n }\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct DataNode {\n\n pub data_type: Rc<Symbolizable>,\n\n pub data: Option<Vec<u8>>,\n\n pub position: Position,\n\n}\n", "file_path": "src/mbql/ast.rs", "rank": 73, "score": 65096.0240378306 }, { "content": " } else {\n\n writer.write(b\"Ground!(\")?;\n\n }\n\n self.symbolizable.write(writer, false, false)?;\n\n writer.write(b\")\")?;\n\n } else {\n\n if self.vivify {\n\n writer.write(b\"{\")?;\n\n } else {\n\n writer.write(b\"!{\")?;\n\n }\n\n\n\n self.symbolizable.write(writer, false, false)?;\n\n writer.write(b\"}\")?;\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<Symbol, MBQLError> {\n\n let mut search_node = SearchNode::search(query, &self.symbolizable)?;\n", "file_path": "src/mbql/ast.rs", "rank": 74, "score": 65095.908671310724 }, { "content": " Ok(())\n\n }\n\n\n\n pub fn apply(&self, query: &Query) -> Result<ArtifactId, MBQLError> {\n\n let artifact_id = self.artifact.apply(query)?;\n\n query.stash_artifact_for_var(&self.var, artifact_id.clone())?;\n\n Ok(artifact_id)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SymbolStatement {\n\n pub var: Option<SymbolVar>,\n\n pub position: Position,\n\n pub symz: Symbolizable,\n\n}\n\n\n\nimpl SymbolStatement {\n\n pub fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::symbolstatement);\n", "file_path": "src/mbql/ast.rs", "rank": 75, "score": 65095.63670711551 }, { "content": " GSymbolizable::GroundPair(GPair { left: Rc::new(left),\n\n right: Rc::new(right),\n\n position: position.clone(), })\n\n },\n\n _ => unreachable!(),\n\n }\n\n },\n\n _ => {\n\n panic!(\"Invalid parse element {}\", pair);\n\n },\n\n };\n\n\n\n Ok(s)\n\n }\n\n\n\n pub fn position(&self) -> &Position {\n\n match self {\n\n GSymbolizable::Artifact(x) => x.position(),\n\n GSymbolizable::SymbolVar(x) => &x.position,\n\n GSymbolizable::Ground(x) => &x.position,\n", "file_path": "src/mbql/ast.rs", "rank": 76, "score": 65095.55380802862 }, { "content": " let mut inner = pair.into_inner();\n\n let next = inner.next().unwrap();\n\n\n\n let (next, vivify) = if next.as_rule() == Rule::bang {\n\n // Ground!(..) means don't vivify any ground symbols\n\n (inner.next().unwrap(), false)\n\n } else {\n\n // Ground(..) means default behavior, vivification is ok\n\n (next, true)\n\n };\n\n\n\n Ok(Ground { symbolizable: Rc::new(GSymbolizable::parse(next, position)?),\n\n position: position.clone(),\n\n vivify })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool) -> Result<(), std::io::Error> {\n\n if verbose {\n\n if self.vivify {\n\n writer.write(b\"Ground(\")?;\n", "file_path": "src/mbql/ast.rs", "rank": 77, "score": 65094.66245702139 }, { "content": " right: Rc::new(right),\n\n position: position.clone(), })\n\n },\n\n Rule::symbolizable => {\n\n let element = pair.into_inner().next().unwrap();\n\n\n\n match element.as_rule() {\n\n Rule::artifact => Symbolizable::Artifact(Artifact::parse(element, position)?),\n\n Rule::symbolvar => Symbolizable::SymbolVar(SymbolVar::parse(element, position)?),\n\n Rule::ground => Symbolizable::Ground(Ground::parse(element, position)?),\n\n Rule::symbolize => Symbolizable::Symbolize(Symbolize::parse(element, position)?),\n\n Rule::allege => Symbolizable::Allege(Allege::parse(element, position)?),\n\n Rule::symbol_pair => {\n\n let mut inner = element.into_inner();\n\n let left = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n let right = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n Symbolizable::Allege(Allege { left: Rc::new(left),\n\n right: Rc::new(right),\n\n position: position.clone(), })\n\n },\n", "file_path": "src/mbql/ast.rs", "rank": 78, "score": 65094.644527774624 }, { "content": " }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool, nest: bool) -> Result<(), std::io::Error> {\n\n if verbose {\n\n writer.write(b\"Allege(\")?;\n\n } else if nest {\n\n writer.write(b\"(\")?;\n\n }\n\n\n\n self.left.write(writer, false, true)?;\n\n writer.write(b\" : \")?;\n\n self.right.write(writer, false, true)?;\n\n\n\n if verbose {\n\n writer.write(b\")\")?;\n\n } else if nest {\n\n writer.write(b\")\")?;\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 79, "score": 65094.589336491066 }, { "content": " Symbolizable::Artifact(x) => x.position(),\n\n Symbolizable::SymbolVar(x) => &x.position,\n\n Symbolizable::Ground(x) => &x.position,\n\n Symbolizable::Allege(x) => &x.position,\n\n Symbolizable::Symbolize(x) => &x.position,\n\n }\n\n }\n\n}\n\n\n\n// TODO 2 - remove Clone and wrap in an Rc\n\n#[derive(Debug)]\n\npub enum GSymbolizable {\n\n Artifact(Artifact),\n\n SymbolVar(Rc<SymbolVar>),\n\n Ground(Ground),\n\n GroundPair(GPair),\n\n}\n\n\n\nimpl GSymbolizable {\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n", "file_path": "src/mbql/ast.rs", "rank": 80, "score": 65094.23774235236 }, { "content": "\n\n Ok(())\n\n }\n\n\n\n pub fn position(&self) -> &Position {\n\n &self.position\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Ground {\n\n vivify: bool,\n\n symbolizable: Rc<GSymbolizable>,\n\n position: Position,\n\n}\n\n\n\nimpl Ground {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::ground);\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 81, "score": 65092.18409404229 }, { "content": "#[derive(Debug)]\n\npub struct Agent {\n\n pub(crate) ident: String,\n\n position: Position,\n\n}\n\n\n\nimpl Agent {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::agent);\n\n Ok(Agent { ident: pair.into_inner().next().unwrap().as_str().to_string(),\n\n position: position.clone(), })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, mut writer: T) -> Result<(), std::io::Error> {\n\n writer.write(format!(\"Agent({})\", self.ident).as_bytes())?;\n\n Ok(())\n\n }\n\n\n\n pub fn get_agent_id(&self, mb: &MindBase) -> Result<AgentId, MBError> {\n\n let agent_id = if self.ident == \"default\" {\n", "file_path": "src/mbql/ast.rs", "rank": 82, "score": 65091.967494629615 }, { "content": "\n\n let mut inner = pair.into_inner();\n\n let sv = SymbolVar::parse(inner.next().unwrap(), position)?;\n\n\n\n let next = inner.next().unwrap();\n\n\n\n let gsymz = Rc::new(GSymbolizable::parse(next, position)?);\n\n\n\n Ok(BindStatement { position: position.clone(),\n\n sv,\n\n gsymz })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n self.sv.write(writer)?;\n\n writer.write(b\" = \")?;\n\n self.gsymz.write(writer, true, false)?;\n\n writer.write(b\"\\n\")?;\n\n Ok(())\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 83, "score": 65091.823624724915 }, { "content": " pub relation_type: Rc<Symbolizable>,\n\n pub from: Rc<Symbolizable>,\n\n pub to: Rc<Symbolizable>,\n\n pub position: Position,\n\n}\n\n\n\nimpl DataRelation {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n let mut inner = pair.into_inner();\n\n\n\n let relation_type = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n let from = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n let to = Symbolizable::parse(inner.next().unwrap(), position)?;\n\n\n\n Ok(DataRelation { relation_type: Rc::new(relation_type),\n\n from: Rc::new(from),\n\n to: Rc::new(to),\n\n position: position.clone(), })\n\n }\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 84, "score": 65091.67777937823 }, { "content": "\n\n pub fn apply(&self, query: &Query) -> Result<(), MBQLError> {\n\n match self {\n\n Statement::Artifact(s) => {\n\n // Ignore this artifact_id because it's being stored inside the apply.\n\n // We have to do this because it's possible to have artifacts/symbols that recursively reference artifact\n\n // variables\n\n s.apply(query)?;\n\n },\n\n Statement::Symbol(s) => {\n\n // Ignore this symbol because it's being stored inside the apply.\n\n // We have to do this because it's possible to have artifacts/symbols that recursively reference symbol variables\n\n s.apply(query)?;\n\n },\n\n Statement::Diag(s) => s.apply(query)?,\n\n Statement::Bind(_) => {\n\n // BindStatements are only used indirectly\n\n },\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\npub struct DiagStatement {\n\n #[allow(unused)]\n\n position: Position,\n\n diag: Diag,\n\n}\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 85, "score": 65090.8059718522 }, { "content": " v.write(writer)?;\n\n\n\n if *depth > 0usize {\n\n write!(writer, \"~{}\", depth)?;\n\n }\n\n },\n\n }\n\n Ok(())\n\n }\n\n}\n\n\n\npub struct BindStatement {\n\n position: Position,\n\n pub sv: SymbolVar,\n\n pub gsymz: Rc<GSymbolizable>,\n\n}\n\n\n\nimpl BindStatement {\n\n pub fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::bindstatement);\n", "file_path": "src/mbql/ast.rs", "rank": 86, "score": 65090.47341507173 }, { "content": " kind: MBQLErrorKind::SymbolVarNotFound { var: self.var.clone() }, });\n\n }\n\n }\n\n\n\n pub fn position(&self) -> &Position {\n\n &self.position\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for SymbolVar {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"${}\", self.var)\n\n }\n\n}\n\n#[derive(Debug)]\n\npub struct ArtifactStatement {\n\n pub var: ArtifactVar,\n\n pub artifact: Artifact,\n\n pub position: Position,\n\n}\n", "file_path": "src/mbql/ast.rs", "rank": 87, "score": 65089.84233927135 }, { "content": " let s = match pair.as_rule() {\n\n Rule::ground_symbol_pair => {\n\n let mut inner = pair.into_inner();\n\n let left = GSymbolizable::parse(inner.next().unwrap(), position)?;\n\n let right = GSymbolizable::parse(inner.next().unwrap(), position)?;\n\n GSymbolizable::GroundPair(GPair { left: Rc::new(left),\n\n right: Rc::new(right),\n\n position: position.clone(), })\n\n },\n\n Rule::ground_symbolizable => {\n\n let element = pair.into_inner().next().unwrap();\n\n\n\n match element.as_rule() {\n\n Rule::artifact => GSymbolizable::Artifact(Artifact::parse(element, position)?),\n\n Rule::symbolvar => GSymbolizable::SymbolVar(Rc::new(SymbolVar::parse(element, position)?)),\n\n Rule::ground => GSymbolizable::Ground(Ground::parse(element, position)?),\n\n Rule::ground_symbol_pair => {\n\n let mut inner = element.into_inner();\n\n let left = GSymbolizable::parse(inner.next().unwrap(), position)?;\n\n let right = GSymbolizable::parse(inner.next().unwrap(), position)?;\n", "file_path": "src/mbql/ast.rs", "rank": 88, "score": 65089.606360611964 }, { "content": "\n\n let mut pairs = pair.into_inner();\n\n\n\n let next = pairs.next().unwrap();\n\n\n\n let (var, next) = if let Rule::symbolvar = next.as_rule() {\n\n (Some(SymbolVar::parse(next, position)?), pairs.next().unwrap())\n\n } else {\n\n (None, next)\n\n };\n\n\n\n // based on the grammar, we are guaranteed to have allege | ground | symbolize\n\n let symbol = match next.as_rule() {\n\n Rule::allege => Symbolizable::Allege(Allege::parse(next, position)?),\n\n Rule::ground => Symbolizable::Ground(Ground::parse(next, position)?),\n\n Rule::symbolize => Symbolizable::Symbolize(Symbolize::parse(next, position)?),\n\n _ => unreachable!(),\n\n };\n\n\n\n Ok(SymbolStatement { var,\n", "file_path": "src/mbql/ast.rs", "rank": 89, "score": 65089.48492541066 }, { "content": "\n\nimpl ArtifactStatement {\n\n pub fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::artifactstatement);\n\n\n\n let mut pairs = pair.into_inner();\n\n let var = ArtifactVar::parse(pairs.next().unwrap(), position)?;\n\n\n\n let artifact = Artifact::parse(pairs.next().unwrap(), position)?;\n\n\n\n Ok(ArtifactStatement { var,\n\n artifact,\n\n position: position.clone() })\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n self.var.write(writer)?;\n\n writer.write(b\" = \")?;\n\n self.artifact.write(writer, true)?;\n\n writer.write(b\"\\n\")?;\n", "file_path": "src/mbql/ast.rs", "rank": 90, "score": 65088.61544528008 }, { "content": " mb.default_agent()?.id()\n\n } else {\n\n AgentId::from_base64(&self.ident)?\n\n };\n\n\n\n Ok(agent_id)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Url {\n\n pub url: String,\n\n pub position: Position,\n\n}\n\n\n\nimpl Url {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n let pair = pair.into_inner().next().unwrap();\n\n Ok(Self { url: pair.as_str().replace(\"\\\\\\\"\", \"\\\"\"),\n\n position: position.clone(), })\n", "file_path": "src/mbql/ast.rs", "rank": 91, "score": 65087.763632545786 }, { "content": " }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n writer.write(b\"DataNode(\")?;\n\n self.data_type.write(writer, false, false)?;\n\n\n\n if let Some(data) = &self.data {\n\n writer.write(b\";\")?;\n\n let mut enc = base64::write::EncoderWriter::new(writer, base64::STANDARD);\n\n use std::io::Write;\n\n enc.write_all(data)?;\n\n }\n\n writer.write(b\")\")?;\n\n\n\n Ok(())\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct DataRelation {\n", "file_path": "src/mbql/ast.rs", "rank": 92, "score": 65087.46023078507 }, { "content": " }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, _verbose: bool) -> Result<(), std::io::Error> {\n\n writer.write(format!(\"Url(\\\"{}\\\")\", self.url.replace(\"\\\"\", \"\\\\\\\"\")).as_bytes())?;\n\n Ok(())\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Text {\n\n text: String,\n\n position: Position,\n\n}\n\n\n\nimpl Text {\n\n fn parse(pair: Pair<Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n let qs = pair.into_inner().next().unwrap();\n\n let s = qs.into_inner().next().unwrap();\n\n\n\n Ok(Text { text: s.as_str().to_string().replace(\"\\\\\\\"\", \"\\\"\"),\n", "file_path": "src/mbql/ast.rs", "rank": 93, "score": 65087.22120099703 }, { "content": "}\n\n\n\n#[derive(Debug)]\n\npub enum Artifact {\n\n Agent(Agent),\n\n Url(Url),\n\n Text(Text),\n\n DataNode(DataNode),\n\n DataRelation(DataRelation),\n\n ArtifactVar(ArtifactVar),\n\n}\n\n\n\nimpl Artifact {\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T, verbose: bool) -> Result<(), std::io::Error> {\n\n match self {\n\n Artifact::Agent(agent) => agent.write(writer)?,\n\n Artifact::Url(url) => url.write(writer, false)?,\n\n Artifact::Text(text) => text.write(writer, verbose)?,\n\n Artifact::DataNode(node) => node.write(writer)?,\n\n Artifact::DataRelation(relation) => relation.write(writer)?,\n", "file_path": "src/mbql/ast.rs", "rank": 94, "score": 65086.97757669744 }, { "content": " Rule::diagstatement => Statement::Diag(DiagStatement::parse(element, position)?),\n\n _ => {\n\n panic!(\"Invalid parse element {}\", element);\n\n },\n\n };\n\n\n\n query.add_statement(me);\n\n\n\n Ok(())\n\n }\n\n\n\n pub fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n match self {\n\n Statement::Artifact(s) => s.write(writer)?,\n\n Statement::Symbol(s) => s.write(writer)?,\n\n Statement::Diag(s) => s.write(writer)?,\n\n Statement::Bind(s) => s.write(writer)?,\n\n }\n\n Ok(())\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 95, "score": 65086.111562821825 }, { "content": " Artifact::ArtifactVar(var) => var.write(writer)?,\n\n }\n\n Ok(())\n\n }\n\n\n\n pub fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::artifact);\n\n let child = pair.into_inner().next().unwrap();\n\n\n\n let a = match child.as_rule() {\n\n Rule::artifactvar => Artifact::ArtifactVar(ArtifactVar::parse(child, position)?),\n\n Rule::agent => Artifact::Agent(Agent::parse(child, position)?),\n\n Rule::datanode => Artifact::DataNode(DataNode::parse(child, position)?),\n\n Rule::datarelation => Artifact::DataRelation(DataRelation::parse(child, position)?),\n\n Rule::text => Artifact::Text(Text::parse(child, position)?),\n\n Rule::url => Artifact::Url(Url::parse(child, position)?),\n\n _ => unreachable!(),\n\n };\n\n\n\n Ok(a)\n", "file_path": "src/mbql/ast.rs", "rank": 96, "score": 65085.17495897672 }, { "content": "\n\n // You can't apply a BindStatement - Not directly anyway\n\n\n\n pub fn position(&self) -> &Position {\n\n &self.position\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct ArtifactVar {\n\n pub var: String,\n\n pub position: Position,\n\n}\n\n\n\nimpl ArtifactVar {\n\n fn parse(pair: Pair<parse::Rule>, position: &Position) -> Result<Self, MBQLError> {\n\n assert_eq!(pair.as_rule(), Rule::artifactvar);\n\n Ok(Self { var: pair.into_inner().next().unwrap().as_str().to_string(),\n\n position: position.clone(), })\n\n }\n", "file_path": "src/mbql/ast.rs", "rank": 97, "score": 65085.11523326273 }, { "content": "\n\n fn write<T: std::io::Write>(&self, writer: &mut T) -> Result<(), std::io::Error> {\n\n writer.write(format!(\"@{}\", self.var).as_bytes())?;\n\n Ok(())\n\n }\n\n}\n\n\n\nimpl std::fmt::Display for ArtifactVar {\n\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\n write!(f, \"@{}\", self.var)\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct SymbolVar {\n\n pub var: String,\n\n pub position: Position,\n\n}\n\n\n\nimpl SymbolVar {\n", "file_path": "src/mbql/ast.rs", "rank": 98, "score": 65084.04864463204 }, { "content": " let depth = match de_inner.next() {\n\n None => 0,\n\n Some(n) => {\n\n println!(\"{}\", n.as_str());\n\n n.as_str().parse().unwrap()\n\n },\n\n };\n\n\n\n DiagElement::SymbolVar(SymbolVar::parse(var, position)?, depth)\n\n //\n\n },\n\n _ => {\n\n println!(\"{:?}\", var);\n\n unreachable!()\n\n },\n\n };\n\n\n\n elements.push(e)\n\n }\n\n\n", "file_path": "src/mbql/ast.rs", "rank": 99, "score": 65083.55724515738 } ]
Rust
src/liberty.rs
marlls1989/liberty-parse
efd8bbe621f4a8a612910c47608c0665993a77a8
use std::{ collections::BTreeMap, fmt, ops::{Deref, DerefMut}, }; use crate::ast::{GroupItem, LibertyAst, Value}; #[derive(Debug, PartialEq, Clone)] pub struct Liberty(pub Vec<Library>); impl Liberty { pub fn to_ast(self) -> LibertyAst { LibertyAst( self.0 .into_iter() .map(|g| g.into_group().into_group_item()) .collect(), ) } pub fn from_ast(ast: LibertyAst) -> Self { Liberty( ast.0 .into_iter() .map(|g| Library::from_group(Group::from_group_item(g))) .collect(), ) } } impl Deref for Liberty { type Target = [Library]; fn deref(&self) -> &Self::Target { self.0.deref() } } impl DerefMut for Liberty { fn deref_mut(&mut self) -> &mut Self::Target { self.0.deref_mut() } } impl From<LibertyAst> for Liberty { fn from(ast: LibertyAst) -> Self { Liberty::from_ast(ast) } } impl fmt::Display for Liberty { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.clone().to_ast().fmt(f) } } impl IntoIterator for Liberty { type Item = Library; type IntoIter = ::std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } #[derive(Debug, PartialEq, Clone)] pub struct Library { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, pub cells: BTreeMap<String, Cell>, } impl Library { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], cells: BTreeMap::new(), } } } #[derive(Debug, PartialEq, Clone)] pub struct Group { pub type_: String, pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, } impl Group { pub fn new(type_: &str, name: &str) -> Self { Self { type_: type_.to_string(), name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], } } pub fn from_group_item(group_item: GroupItem) -> Self { let (type_, name, items) = group_item.group(); let mut simple_attributes: BTreeMap<String, Value> = BTreeMap::new(); let mut complex_attributes: BTreeMap<String, Vec<Value>> = BTreeMap::new(); let mut groups: Vec<Self> = vec![]; for item in items { match item { GroupItem::SimpleAttr(name, value) => { simple_attributes.insert(name, value); } GroupItem::ComplexAttr(name, value) => { complex_attributes.insert(name, value); } GroupItem::Group(type_, name, items) => { groups.push(Group::from_group_item(GroupItem::Group(type_, name, items))); } _ => {} } } Self { name, type_, simple_attributes, complex_attributes, groups, } } pub fn into_group_item(self) -> GroupItem { let mut items: Vec<GroupItem> = Vec::with_capacity( self.simple_attributes.len() + self.complex_attributes.len() + self.groups.len(), ); items.extend( self.simple_attributes .into_iter() .map(|(name, value)| GroupItem::SimpleAttr(name, value)), ); items.extend( self.complex_attributes .into_iter() .map(|(name, value)| GroupItem::ComplexAttr(name, value)), ); items.extend(self.groups.into_iter().map(|g| g.into_group_item())); GroupItem::Group(self.type_, self.name, items) } } #[derive(Debug, PartialEq, Clone)] pub struct Cell { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, pub pins: BTreeMap<String, Pin>, } impl Cell { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], pins: BTreeMap::new(), } } } #[derive(Debug, PartialEq, Clone)] pub struct Pin { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, } impl Pin { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], } } } pub trait FromGroup { type Item; fn from_group(group: Group) -> Self::Item; } pub trait ToGroup { type Item; fn into_group(self) -> Group; } impl FromGroup for Library { type Item = Library; fn from_group(group: Group) -> Self::Item { let (cells, groups) = group.groups.into_iter().partition(|g| g.type_ == "cell"); Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups, cells: cells.into_iter().fold(BTreeMap::new(), |mut acc, cell| { acc.insert(cell.name.clone(), Cell::from_group(cell)); acc }), } } } impl ToGroup for Library { type Item = Library; fn into_group(self) -> Group { let mut groups: Vec<Group> = Vec::with_capacity(self.groups.len() + self.cells.len()); groups.extend(self.groups); groups.extend(self.cells.into_iter().map(|(_, cell)| cell.into_group())); Group { name: self.name, type_: String::from("library"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups, } } } impl FromGroup for Cell { type Item = Cell; fn from_group(group: Group) -> Self::Item { let (pins, groups) = group.groups.into_iter().partition(|g| g.type_ == "pin"); Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups, pins: pins.into_iter().fold(BTreeMap::new(), |mut acc, pin| { acc.insert(pin.name.clone(), Pin::from_group(pin)); acc }), } } } impl ToGroup for Cell { type Item = Cell; fn into_group(self) -> Group { let mut groups: Vec<Group> = Vec::with_capacity(self.groups.len() + self.pins.len()); groups.extend(self.pins.into_iter().map(|(_, pin)| pin.into_group())); groups.extend(self.groups); Group { name: self.name, type_: String::from("cell"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups, } } } impl FromGroup for Pin { type Item = Pin; fn from_group(group: Group) -> Self::Item { Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups: group.groups, } } } impl ToGroup for Pin { type Item = Pin; fn into_group(self) -> Group { Group { name: self.name, type_: String::from("pin"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups: self.groups, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_iter() { let lib = Liberty(vec![Library::new("mylib")]); let mut iter = lib.into_iter(); assert_eq!(iter.next(), Some(Library::new("mylib"))); assert_eq!(iter.next(), None); } #[test] fn test_pin_into_group() { let mut pin = Pin::new("my_pin"); pin.groups.push(Group::new("gtype", "gname")); let group = pin.into_group(); assert_eq!(group.type_, "pin"); assert_eq!(group.name, "my_pin"); assert_eq!(group.groups.len(), 1); } #[test] fn test_pin_from_group() { let mut group = Group::new("pin", "a"); group.groups.push(Group::new("gtype", "gname")); let pin = Pin::from_group(group); assert_eq!(pin.name, "a"); assert_eq!(pin.groups.len(), 1); } #[test] fn test_cell_into_group() { let mut cell = Cell::new("my_cell"); cell.groups.push(Group::new("gtype", "gname")); cell.pins.insert("a".to_string(), Pin::new("a")); cell.pins.insert("b".to_string(), Pin::new("b")); let group = cell.into_group(); assert_eq!(group.type_, "cell"); assert_eq!(group.name, "my_cell"); assert_eq!(group.groups.len(), 3); } #[test] fn test_cell_from_group() { let mut group = Group::new("cell", "AND2"); group.groups.push(Group::new("gtype", "gname")); group.groups.push(Group::new("pin", "a")); group.groups.push(Group::new("pin", "b")); let cell = Cell::from_group(group); assert_eq!(cell.name, "AND2"); assert_eq!(cell.groups.len(), 1); assert_eq!(cell.pins.len(), 2); } #[test] fn test_library_into_group() { let mut lib = Library::new("my_lib"); lib.groups.push(Group::new("gtype", "gname")); lib.cells.insert("AND2".to_string(), Cell::new("AND2")); lib.cells.insert("NAND2".to_string(), Cell::new("NAND2")); let group = lib.into_group(); assert_eq!(group.type_, "library"); assert_eq!(group.name, "my_lib"); assert_eq!(group.groups.len(), 3); } #[test] fn test_lib_from_group() { let mut group = Group::new("library", "mylib"); group.groups.push(Group::new("gtype", "gname")); let mut cell = Group::new("cell", "AND2"); cell.groups.push(Group::new("pin", "a")); cell.groups.push(Group::new("pin", "b")); group.groups.push(cell); let lib = Library::from_group(group); assert_eq!(lib.name, "mylib"); assert_eq!(lib.groups.len(), 1); assert_eq!(lib.cells.len(), 1); let converted_cell = lib.cells.get("AND2").unwrap(); assert_eq!(converted_cell.name, "AND2"); assert_eq!(converted_cell.groups.len(), 0); assert_eq!(converted_cell.pins.len(), 2); } }
use std::{ collections::BTreeMap, fmt, ops::{Deref, DerefMut}, }; use crate::ast::{GroupItem, LibertyAst, Value}; #[derive(Debug, PartialEq, Clone)] pub struct Liberty(pub Vec<Library>); impl Liberty { pub fn to_ast(self) -> LibertyAst { LibertyAst( self.0 .into_iter() .map(|g| g.into_group().into_group_item()) .collect(), ) } pub fn from_ast(ast: LibertyAst) -> Self { Liberty( ast.0 .into_iter() .map(|g| Library::from_group(Group::from_group_item(g))) .collect(), ) } } impl Deref for Liberty { type Target = [Library]; fn deref(&self) -> &Self::Target { self.0.deref() } } impl DerefMut for Liberty { fn deref_mut(&mut self) -> &mut Self::Target { self.0.deref_mut() } } impl From<LibertyAst> for Liberty { fn from(ast: LibertyAst) -> Self { Liberty::from_ast(ast) } } impl fmt::Display for Liberty { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.clone().to_ast().fmt(f) } } impl IntoIterator for Liberty { type Item = Library; type IntoIter = ::std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } #[derive(Debug, PartialEq, Clone)] pub struct Library { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, pub cells: BTreeMap<String, Cell>, } impl Library { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], cells: BTreeMap::new(), } } } #[derive(Debug, PartialEq, Clone)] pub struct Group { pub type_: String, pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, } impl Group { pub fn new(type_: &str, name: &str) -> Self { Self { type_: type_.to_string(), name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], } } pub fn from_group_item(group_item: GroupItem) -> Self { let (type_, name, items) = group_item.group(); let mut simple_attributes: BTreeMap<String, Value> = BTreeMap::new(); let mut complex_attributes: BTreeMap<String, Vec<Value>> = BTreeMap::new(); let mut groups: Vec<Self> = vec![]; for item in items {
} Self { name, type_, simple_attributes, complex_attributes, groups, } } pub fn into_group_item(self) -> GroupItem { let mut items: Vec<GroupItem> = Vec::with_capacity( self.simple_attributes.len() + self.complex_attributes.len() + self.groups.len(), ); items.extend( self.simple_attributes .into_iter() .map(|(name, value)| GroupItem::SimpleAttr(name, value)), ); items.extend( self.complex_attributes .into_iter() .map(|(name, value)| GroupItem::ComplexAttr(name, value)), ); items.extend(self.groups.into_iter().map(|g| g.into_group_item())); GroupItem::Group(self.type_, self.name, items) } } #[derive(Debug, PartialEq, Clone)] pub struct Cell { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, pub pins: BTreeMap<String, Pin>, } impl Cell { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], pins: BTreeMap::new(), } } } #[derive(Debug, PartialEq, Clone)] pub struct Pin { pub name: String, pub simple_attributes: BTreeMap<String, Value>, pub complex_attributes: BTreeMap<String, Vec<Value>>, pub groups: Vec<Group>, } impl Pin { pub fn new(name: &str) -> Self { Self { name: name.to_string(), simple_attributes: BTreeMap::new(), complex_attributes: BTreeMap::new(), groups: vec![], } } } pub trait FromGroup { type Item; fn from_group(group: Group) -> Self::Item; } pub trait ToGroup { type Item; fn into_group(self) -> Group; } impl FromGroup for Library { type Item = Library; fn from_group(group: Group) -> Self::Item { let (cells, groups) = group.groups.into_iter().partition(|g| g.type_ == "cell"); Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups, cells: cells.into_iter().fold(BTreeMap::new(), |mut acc, cell| { acc.insert(cell.name.clone(), Cell::from_group(cell)); acc }), } } } impl ToGroup for Library { type Item = Library; fn into_group(self) -> Group { let mut groups: Vec<Group> = Vec::with_capacity(self.groups.len() + self.cells.len()); groups.extend(self.groups); groups.extend(self.cells.into_iter().map(|(_, cell)| cell.into_group())); Group { name: self.name, type_: String::from("library"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups, } } } impl FromGroup for Cell { type Item = Cell; fn from_group(group: Group) -> Self::Item { let (pins, groups) = group.groups.into_iter().partition(|g| g.type_ == "pin"); Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups, pins: pins.into_iter().fold(BTreeMap::new(), |mut acc, pin| { acc.insert(pin.name.clone(), Pin::from_group(pin)); acc }), } } } impl ToGroup for Cell { type Item = Cell; fn into_group(self) -> Group { let mut groups: Vec<Group> = Vec::with_capacity(self.groups.len() + self.pins.len()); groups.extend(self.pins.into_iter().map(|(_, pin)| pin.into_group())); groups.extend(self.groups); Group { name: self.name, type_: String::from("cell"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups, } } } impl FromGroup for Pin { type Item = Pin; fn from_group(group: Group) -> Self::Item { Self { name: group.name, simple_attributes: group.simple_attributes, complex_attributes: group.complex_attributes, groups: group.groups, } } } impl ToGroup for Pin { type Item = Pin; fn into_group(self) -> Group { Group { name: self.name, type_: String::from("pin"), simple_attributes: self.simple_attributes, complex_attributes: self.complex_attributes, groups: self.groups, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_iter() { let lib = Liberty(vec![Library::new("mylib")]); let mut iter = lib.into_iter(); assert_eq!(iter.next(), Some(Library::new("mylib"))); assert_eq!(iter.next(), None); } #[test] fn test_pin_into_group() { let mut pin = Pin::new("my_pin"); pin.groups.push(Group::new("gtype", "gname")); let group = pin.into_group(); assert_eq!(group.type_, "pin"); assert_eq!(group.name, "my_pin"); assert_eq!(group.groups.len(), 1); } #[test] fn test_pin_from_group() { let mut group = Group::new("pin", "a"); group.groups.push(Group::new("gtype", "gname")); let pin = Pin::from_group(group); assert_eq!(pin.name, "a"); assert_eq!(pin.groups.len(), 1); } #[test] fn test_cell_into_group() { let mut cell = Cell::new("my_cell"); cell.groups.push(Group::new("gtype", "gname")); cell.pins.insert("a".to_string(), Pin::new("a")); cell.pins.insert("b".to_string(), Pin::new("b")); let group = cell.into_group(); assert_eq!(group.type_, "cell"); assert_eq!(group.name, "my_cell"); assert_eq!(group.groups.len(), 3); } #[test] fn test_cell_from_group() { let mut group = Group::new("cell", "AND2"); group.groups.push(Group::new("gtype", "gname")); group.groups.push(Group::new("pin", "a")); group.groups.push(Group::new("pin", "b")); let cell = Cell::from_group(group); assert_eq!(cell.name, "AND2"); assert_eq!(cell.groups.len(), 1); assert_eq!(cell.pins.len(), 2); } #[test] fn test_library_into_group() { let mut lib = Library::new("my_lib"); lib.groups.push(Group::new("gtype", "gname")); lib.cells.insert("AND2".to_string(), Cell::new("AND2")); lib.cells.insert("NAND2".to_string(), Cell::new("NAND2")); let group = lib.into_group(); assert_eq!(group.type_, "library"); assert_eq!(group.name, "my_lib"); assert_eq!(group.groups.len(), 3); } #[test] fn test_lib_from_group() { let mut group = Group::new("library", "mylib"); group.groups.push(Group::new("gtype", "gname")); let mut cell = Group::new("cell", "AND2"); cell.groups.push(Group::new("pin", "a")); cell.groups.push(Group::new("pin", "b")); group.groups.push(cell); let lib = Library::from_group(group); assert_eq!(lib.name, "mylib"); assert_eq!(lib.groups.len(), 1); assert_eq!(lib.cells.len(), 1); let converted_cell = lib.cells.get("AND2").unwrap(); assert_eq!(converted_cell.name, "AND2"); assert_eq!(converted_cell.groups.len(), 0); assert_eq!(converted_cell.pins.len(), 2); } }
match item { GroupItem::SimpleAttr(name, value) => { simple_attributes.insert(name, value); } GroupItem::ComplexAttr(name, value) => { complex_attributes.insert(name, value); } GroupItem::Group(type_, name, items) => { groups.push(Group::from_group_item(GroupItem::Group(type_, name, items))); } _ => {} }
if_condition
[ { "content": "pub fn parse_libs<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, Vec<GroupItem>, E> {\n\n context(\n\n \"parse_libs\",\n\n all_consuming(terminated(\n\n fold_many0(\n\n alt((\n\n context(\n\n \"outer comment\",\n\n map(\n\n map(delimited(multispace0, comment, multispace0), String::from),\n\n GroupItem::Comment,\n\n ),\n\n ),\n\n preceded(multispace0, context(\"parse_lib\", parse_group)),\n\n )),\n\n Vec::new(),\n\n |mut acc: Vec<_>, item| {\n\n match &item {\n\n GroupItem::Group(_, _, _) => acc.push(item),\n\n GroupItem::Comment(_) => {}\n", "file_path": "src/parser.rs", "rank": 0, "score": 124947.77313404923 }, { "content": "// Recursively convert a vector of [`GroupItem`]s into a single `String`\n\nfn items_to_string(items: &[GroupItem], level: usize) -> String {\n\n let indent = \" \".repeat(level);\n\n items\n\n .iter()\n\n .map(|item| match item {\n\n GroupItem::SimpleAttr(name, value) => {\n\n format!(\"{}{} : {};\", indent, name, value.to_string())\n\n }\n\n GroupItem::ComplexAttr(name, values) => format!(\n\n \"{}{} ({});\",\n\n indent,\n\n name,\n\n values.iter().map(|v| v.to_string()).join(\", \")\n\n ),\n\n GroupItem::Comment(v) => format!(\"/*\\n{}\\n*/\", v),\n\n GroupItem::Group(type_, name, group_items) => format!(\n\n \"{}{} ({}) {{\\n{}\\n{}}}\",\n\n indent,\n\n type_,\n\n name,\n", "file_path": "src/ast.rs", "rank": 1, "score": 115689.24797409985 }, { "content": "fn parse_group<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, GroupItem, E> {\n\n context(\n\n \"parsing group\",\n\n map(\n\n tuple((\n\n preceded(multispace0, underscore_tag),\n\n preceded(\n\n preceded(multispace0, char('(')),\n\n terminated(\n\n map(\n\n separated_list(\n\n preceded(multispace0, char(',')),\n\n preceded(\n\n multispace0,\n\n alt((\n\n map(quoted_string, |s| format!(\"\\\"{}\\\"\", s)),\n\n map(underscore_tag, |s| format!(\"{}\", s)),\n\n )),\n\n ),\n\n ),\n", "file_path": "src/parser.rs", "rank": 2, "score": 95120.65294090688 }, { "content": "/// Parse a string slice into a [liberty::Liberty] struct\n\npub fn parse_lib(contents: &str) -> ParseResult<liberty::Liberty> {\n\n Ok(liberty::Liberty::from_ast(ast::LibertyAst::from_string(\n\n contents,\n\n )?))\n\n}\n", "file_path": "src/lib.rs", "rank": 3, "score": 93395.9945755059 }, { "content": "fn simple_attribute<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, GroupItem, E> {\n\n context(\n\n \"simple attr\",\n\n map(\n\n tuple((\n\n preceded(multispace0, underscore_tag),\n\n preceded(multispace0, char(':')),\n\n cut(preceded(multispace0, simple_attr_value)),\n\n preceded(multispace0, char(';')),\n\n )),\n\n |(name, _, value, _)| GroupItem::SimpleAttr(name.to_string(), value),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 4, "score": 88094.03156933133 }, { "content": "fn complex_attribute<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, GroupItem, E> {\n\n context(\n\n \"complex attr\",\n\n map(\n\n tuple((\n\n preceded(multispace0, underscore_tag),\n\n preceded(multispace0, complex_attribute_values),\n\n preceded(multispace0, char(';')),\n\n )),\n\n |(name, value, _)| GroupItem::ComplexAttr(name.to_string(), value),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 5, "score": 88094.03156933133 }, { "content": "fn parse<'a>(contents: &'a str) -> result::Result<(), Error<'a>> {\n\n for lib in parse_lib(contents)? {\n\n println!(\"Parsed library '{}'\", lib.name);\n\n for (name, cell) in lib.cells {\n\n println!(\"Cell: {}\", name);\n\n if let Some(area) = cell.simple_attributes.get(\"area\") {\n\n println!(\"Cell has area: {:?}\", area.float());\n\n }\n\n }\n\n }\n\n Ok(())\n\n}\n\n\n", "file_path": "examples/list_library_cells.rs", "rank": 8, "score": 75889.75325599777 }, { "content": "fn quoted_floats<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, Vec<f64>, E> {\n\n context(\n\n \"quoted floats\",\n\n preceded(\n\n char('\\\"'),\n\n terminated(\n\n separated_list(\n\n preceded(multispace0, char(',')),\n\n preceded(multispace0, double),\n\n ),\n\n char('\\\"'),\n\n ),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 9, "score": 74971.93709504744 }, { "content": "fn simple_attr_value<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, Value, E> {\n\n context(\n\n \"simple attr value\",\n\n preceded(\n\n multispace0,\n\n alt((\n\n map(quoted_floats, Value::FloatGroup),\n\n map(quoted_string, |s| Value::String(s.to_string())),\n\n map(terminated(double, peek(one_of(\",; \\t)\"))), Value::Float),\n\n map(boolean, Value::Bool),\n\n map(map(expression, String::from), Value::Expression),\n\n )),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 10, "score": 73175.15324168277 }, { "content": "fn quoted_string<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, &str, E> {\n\n context(\n\n \"quoted string\",\n\n preceded(char('\\\"'), cut(terminated(is_not(\"\\\"\"), char('\\\"')))),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 11, "score": 71910.99416135294 }, { "content": "fn main() {\n\n let args: Vec<String> = env::args().collect();\n\n if args.len() < 2 {\n\n panic!(\"Missing LIB file argument\");\n\n }\n\n let contents = fs::read_to_string(&args[1]).expect(\"Unable to read LIB file\");\n\n parse(&contents).unwrap();\n\n}\n", "file_path": "examples/list_library_cells.rs", "rank": 12, "score": 69486.3204314955 }, { "content": "fn complex_attribute_values<'a, E: ParseError<&'a str>>(\n\n input: &'a str,\n\n) -> IResult<&str, Vec<Value>, E> {\n\n context(\n\n \"complex values\",\n\n delimited(\n\n preceded(multispace0, tag(\"(\")),\n\n delimited(\n\n opt(tuple((multispace0, tag(\"\\\\\"), line_ending))),\n\n separated_list(\n\n alt((\n\n map(\n\n tuple((multispace0, tag(\",\"), multispace0, tag(\"\\\\\"), line_ending)),\n\n |_| Some(1),\n\n ),\n\n map(tuple((multispace0, tag(\",\"))), |_| Some(1)),\n\n map(\n\n tuple((multispace0, tag(\"\\\\\"), line_ending, multispace0, tag(\",\"))),\n\n |_| Some(1),\n\n ),\n\n )),\n\n preceded(multispace0, simple_attr_value),\n\n ),\n\n opt(tuple((multispace0, tag(\"\\\\\"), line_ending))),\n\n ),\n\n preceded(multispace0, tag(\")\")),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 13, "score": 64511.62256773645 }, { "content": "fn parse_group_body<'a, E: ParseError<&'a str>>(\n\n input: &'a str,\n\n) -> IResult<&str, Vec<GroupItem>, E> {\n\n context(\n\n \"group body\",\n\n fold_many0(\n\n context(\n\n \"folding items\",\n\n alt((\n\n map(\n\n map(preceded(multispace0, comment), String::from),\n\n GroupItem::Comment,\n\n ),\n\n preceded(multispace0, parse_group),\n\n preceded(multispace0, simple_attribute),\n\n preceded(multispace0, complex_attribute),\n\n )),\n\n ),\n\n Vec::new(),\n\n |mut acc: Vec<_>, item| {\n\n acc.push(item);\n\n acc\n\n },\n\n ),\n\n )(input)\n\n}\n", "file_path": "src/parser.rs", "rank": 14, "score": 64234.06487533037 }, { "content": "fn expression<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, &str, E> {\n\n context(\"expression\", move |input| {\n\n recognize(separated_list(\n\n // operator\n\n preceded(multispace0, is_a(\"+-*/\")),\n\n // operand\n\n preceded(\n\n multispace0,\n\n preceded(\n\n opt(is_a(\"-\")),\n\n alt((\n\n // sub expression\n\n preceded(char('('), cut(terminated(expression, char(')')))),\n\n // identifier\n\n underscore_tag,\n\n // constant\n\n recognize(double),\n\n )),\n\n ),\n\n ),\n\n ))(input)\n\n })(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 15, "score": 59388.70769241388 }, { "content": "fn comment<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, &str, E> {\n\n context(\n\n \"comment\",\n\n recognize(delimited(tag(\"/*\"), take_until(\"*/\"), tag(\"*/\"))),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 16, "score": 59388.70769241388 }, { "content": "fn underscore_tag<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, &str, E> {\n\n context(\n\n \"underscore_tag\",\n\n recognize(preceded(\n\n alpha1,\n\n take_while(|c: char| c.is_alphanumeric() || c.eq_ignore_ascii_case(&'_')),\n\n )),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 17, "score": 58333.01714492787 }, { "content": "fn boolean<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, bool, E> {\n\n map_res(alpha1, |s: &str| s.parse::<bool>())(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 18, "score": 55065.01865146088 }, { "content": "use liberty_parse::{parse_lib, Error};\n\nuse std::{env, fs, result};\n\n\n", "file_path": "examples/list_library_cells.rs", "rank": 19, "score": 43508.19462235959 }, { "content": "fn main() {\n\n let mut buf = String::new();\n\n stdin().read_to_string(&mut buf).unwrap();\n\n\n\n let lib = parse_lib(&buf).unwrap();\n\n println!(\"{}\", lib);\n\n}\n", "file_path": "examples/reformat_lib.rs", "rank": 20, "score": 29657.369882678493 }, { "content": "fn main() {\n\n let lib_str = r#\"\n\nlibrary(sample) {\n\n cell(AND2) {\n\n area: 1;\n\n pin(o) {\n\n timing() {\n\n cell_rise(delay_temp_3x3) {\n\n index_1 (\"0.5, 1.0, 1.5\");\n\n index_2 (\"10.0, 20.0, 30.0\");\n\n values ( \"0.1, 0.2, 0.3\", \\\n\n \"0.11, 0.21, 0.31\", \\\n\n \"0.12, 0.22, 0.32\" );\n\n }\n\n }\n\n }\n\n }\n\n}\n\n\"#;\n\n\n", "file_path": "examples/get_area.rs", "rank": 21, "score": 29657.369882678493 }, { "content": "# liberty-parse\n\n\n\nLiberty file format parser for Rust\n\n\n\n## Example usage\n\n\n\nParse libraries from a Liberty file\n\n\n\n```rust\n\nuse liberty_parse::parse_lib;\n\n\n\nlet lib_str = r#\"\n\nlibrary(sample) {\n\n cell(AND2) {\n\n area: 1;\n\n }\n\n}\n\n\"#;\n\n\n\nfor lib in parse_lib(lib_str).unwrap() {\n\n println!(\"Library '{}' has {} cells\", lib.name, lib.cells.len());\n\n if let Some(cell) = lib.cells.get(\"AND2\") {\n\n let area = cell.simple_attributes.get(\"area\").map_or(0.0, |v| v.float());\n\n println!(\"Cell AND2 has area: {}\", area);\n\n } else {\n\n println!(\"Cell AND2 doesn't exist!\");\n\n }\n\n}\n\n```\n\n\n\n## Limitations\n\n\n\n- Doesn't automatically parse files from `include` statements\n\n- Doesn't parse bus syntax in pin names. For example:\n\n\n\n ```\n\n pin (X[0:3]){\n\n }\n\n ```\n\n\n", "file_path": "README.md", "rank": 41, "score": 13230.923107053455 }, { "content": " items_to_string(group_items, level + 1),\n\n indent\n\n ),\n\n })\n\n .join(\"\\n\")\n\n}\n\n\n\n/// Intermediate representation\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum GroupItem {\n\n // type, name, values\n\n Group(String, String, Vec<GroupItem>),\n\n // name, value\n\n SimpleAttr(String, Value),\n\n ComplexAttr(String, Vec<Value>),\n\n // contents\n\n Comment(String),\n\n}\n\n\n\nimpl GroupItem {\n", "file_path": "src/ast.rs", "rank": 42, "score": 18.6542084448852 }, { "content": " }\n\n\n\n /// Convert a [`Liberty`] struct into an AST\n\n pub fn from_liberty(lib: Liberty) -> Self {\n\n lib.to_ast()\n\n }\n\n}\n\n\n\nimpl fmt::Display for LibertyAst {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n write!(f, \"{}\", items_to_string(&self.0, 0))\n\n }\n\n}\n\n\n\nimpl From<Liberty> for LibertyAst {\n\n fn from(liberty: Liberty) -> Self {\n\n LibertyAst::from_liberty(liberty)\n\n }\n\n}\n\n\n\n// Recursively convert a vector of [`GroupItem`]s into a single `String`\n", "file_path": "src/ast.rs", "rank": 43, "score": 18.45017088278809 }, { "content": "/// [`GroupItem::Group`] variant.\n\n#[derive(Debug)]\n\npub struct LibertyAst(pub Vec<GroupItem>);\n\n\n\nimpl LibertyAst {\n\n /// Create a new AST from a vector of `GroupItem`s\n\n pub fn new(libs: Vec<GroupItem>) -> Self {\n\n Self(libs)\n\n }\n\n\n\n /// Parse a Liberty file's string representation into the AST\n\n pub fn from_string(input: &str) -> ParseResult<Self> {\n\n parse_libs::<VerboseError<&str>>(input)\n\n .map_err(|e| Error::new(input, e))\n\n .map(|(_, libs)| LibertyAst::new(libs))\n\n }\n\n\n\n /// Convert an AST into a [`Liberty`] struct\n\n pub fn into_liberty(self) -> Liberty {\n\n Liberty::from_ast(self)\n", "file_path": "src/ast.rs", "rank": 44, "score": 17.708934398335753 }, { "content": " /// Convert [`Value::Float`] to `f64` or panic\n\n pub fn group(&self) -> (String, String, Vec<GroupItem>) {\n\n if let GroupItem::Group(type_, name, items) = self {\n\n (String::from(type_), String::from(name), items.clone())\n\n } else {\n\n panic!(\"Not variant GroupItem::Group\");\n\n }\n\n }\n\n}\n\n\n\n/// Liberty value type\n\n///\n\n/// A wide range of types are defined for the Liberty syntax. Because there is little to no way\n\n/// to parse enumerated types from the syntax alone, enumerated types are parsed as the\n\n/// [`Value::Expression`] variant.\n\n#[derive(Debug, PartialEq, Clone)]\n\npub enum Value {\n\n /// Boolean value, parsed from the keywords `true` and `false`\n\n Bool(bool),\n\n /// Floating point value.\n", "file_path": "src/ast.rs", "rank": 45, "score": 17.564615388196362 }, { "content": "use nom::{\n\n error::{convert_error, VerboseError},\n\n Err,\n\n};\n\nuse std::{error, fmt};\n\n\n\n#[derive(Debug)]\n\npub struct Error<'a>(pub &'a str, pub Err<VerboseError<&'a str>>);\n\n\n\nimpl<'a> Error<'a> {\n\n pub fn new(input: &'a str, err: Err<VerboseError<&'a str>>) -> Self {\n\n Error(input, err)\n\n }\n\n}\n\n\n\nimpl<'a> fmt::Display for Error<'a> {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n match self {\n\n Error(input, Err::Error(err)) => write!(f, \"{}\", convert_error(input, err.clone())),\n\n Error(input, Err::Failure(err)) => write!(f, \"{}\", convert_error(input, err.clone())),\n", "file_path": "src/error.rs", "rank": 46, "score": 15.812831347870175 }, { "content": " } else {\n\n panic!(\"Not a bool\")\n\n }\n\n }\n\n\n\n /// Convert [`Value::FloatGroup`] to `Vec<f64>` or panic\n\n pub fn float_group(&self) -> Vec<f64> {\n\n if let Value::FloatGroup(v) = self {\n\n v.clone()\n\n } else {\n\n panic!(\"Not a float group\")\n\n }\n\n }\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n use super::{LibertyAst, Value};\n\n\n\n macro_rules! parse_file {\n", "file_path": "src/ast.rs", "rank": 47, "score": 13.42057906367804 }, { "content": " \"library\".to_string(),\n\n \"foo\".to_string(),\n\n vec![\n\n GroupItem::SimpleAttr(\n\n \"delay_model\".to_string(),\n\n Value::Expression(\"table_lookup\".to_string())\n\n ),\n\n GroupItem::Comment(\"/* unit attributes */\".to_string()),\n\n GroupItem::SimpleAttr(\n\n \"time_unit\".to_string(),\n\n Value::String(\"1ns\".to_string())\n\n ),\n\n GroupItem::ComplexAttr(\n\n \"capacitive_load_unit\".to_string(),\n\n vec![Value::Float(1.0), Value::Expression(\"pf\".to_string()),],\n\n ),\n\n GroupItem::SimpleAttr(\n\n \"function\".to_string(),\n\n Value::String(\"A & B\".to_string()),\n\n ),\n", "file_path": "src/parser.rs", "rank": 48, "score": 12.936784550837272 }, { "content": " fn test_simple_attribute_int() {\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : 345 ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Float(345.0),)\n\n ))\n\n );\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : -345 ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Float(-345.0),)\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_expression() {\n\n let expressions = vec![\n", "file_path": "src/parser.rs", "rank": 49, "score": 12.906322995633754 }, { "content": " abc ( 1, 2, 3 );\n\n }\n\n }\"#\n\n ),\n\n Ok((\n\n \"\",\n\n GroupItem::Group(\n\n \"outer\".to_string(),\n\n \"outer\".to_string(),\n\n vec![\n\n GroupItem::Group(\n\n \"inner\".to_string(),\n\n \"inner\".to_string(),\n\n vec![GroupItem::ComplexAttr(\n\n \"abc\".to_string(),\n\n vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0),],\n\n ),],\n\n ),\n\n GroupItem::Group(\n\n \"inner\".to_string(),\n", "file_path": "src/parser.rs", "rank": 50, "score": 12.765245705342034 }, { "content": " for lib in parse_lib(lib_str).unwrap() {\n\n println!(\"Library '{}' has {} cells\", lib.name, lib.cells.len());\n\n let area = lib\n\n .cells\n\n .get(\"AND2\")\n\n .and_then(|c| c.simple_attributes.get(\"area\"))\n\n .map_or(0.0, |v| v.float());\n\n println!(\"Cell AND2 has area: {}\", area);\n\n\n\n let values = lib\n\n .cells\n\n .get(\"AND2\")\n\n .and_then(|c| c.pins.get(\"o\"))\n\n .and_then(|p| p.groups.iter().find(|g| g.type_ == \"timing\"))\n\n .and_then(|t| t.groups.iter().find(|g| g.type_ == \"cell_rise\"))\n\n .and_then(|rise| rise.complex_attributes.get(\"values\"))\n\n .map_or(vec![], |values| {\n\n values.iter().map(|v| v.float_group()).collect()\n\n });\n\n println!(\"Pin AND2/o has cell_rise values: {:?}\", values);\n\n }\n\n}\n", "file_path": "examples/get_area.rs", "rank": 51, "score": 12.502071514187314 }, { "content": "//! .cells\n\n//! .get(\"AND2\")\n\n//! .and_then(|c| c.simple_attributes.get(\"area\"))\n\n//! .map_or(-1.0, |v| v.float());\n\n//! println!(\"Cell AND2 has area: {}\", area);\n\n//! }\n\n//! ```\n\n\n\npub mod ast;\n\nmod error;\n\npub mod liberty;\n\nmod parser;\n\n\n\npub use ast::{ParseResult, Value};\n\n\n\npub use error::Error;\n\n\n\n/// Parse a string slice into a [liberty::Liberty] struct\n", "file_path": "src/lib.rs", "rank": 52, "score": 12.464768425359445 }, { "content": " GroupItem::SimpleAttr(\n\n String::from(\"attr_name\"),\n\n Value::Expression(String::from(\"A + 1.2\")),\n\n )\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_simple_attribute_string() {\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : \\\"table_lookup\\\"; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(\n\n String::from(\"attr_name\"),\n\n Value::String(String::from(\"table_lookup\"))\n\n )\n\n ))\n\n );\n", "file_path": "src/parser.rs", "rank": 53, "score": 12.31722193571244 }, { "content": " ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_complex_attr_multi_line() {\n\n assert_eq!(\n\n complex_attribute::<(&str, ErrorKind)>(\n\n r#\"values ( \\\n\n \"0, 0.18, 0.33\", \\\n\n \"-0.555, -0.45, -0.225\");\"#\n\n ),\n\n Ok((\n\n \"\",\n\n GroupItem::ComplexAttr(\n\n \"values\".to_string(),\n\n vec![\n\n Value::FloatGroup(vec![0.0, 0.18, 0.33]),\n\n Value::FloatGroup(vec![-0.555, -0.45, -0.225]),\n\n ],\n", "file_path": "src/parser.rs", "rank": 54, "score": 12.157550257153993 }, { "content": "//! This crate reads Liberty format files, commonly used by\n\n//! [EDA](https://en.wikipedia.org/wiki/Electronic_design_automation) tools to describe library\n\n//! cells (including standard cells, hard IP, etc.).\n\n//!\n\n//! # Example\n\n//!\n\n//! ```\n\n//! use liberty_parse::parse_lib;\n\n//!\n\n//! let lib_str = r#\"\n\n//! library(sample) {\n\n//! cell(AND2) {\n\n//! area: 1;\n\n//! }\n\n//! }\n\n//! \"#;\n\n//!\n\n//! for lib in parse_lib(lib_str).unwrap() {\n\n//! println!(\"Library '{}' has {} cells\", lib.name, lib.cells.len());\n\n//! let area = lib\n", "file_path": "src/lib.rs", "rank": 55, "score": 11.90782356671439 }, { "content": " );\n\n }\n\n #[test]\n\n fn test_simple_attribute_float() {\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : 345.123 ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Float(345.123),)\n\n ))\n\n );\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : -345.123 ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Float(-345.123),)\n\n ))\n\n );\n\n }\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 56, "score": 11.89244589833936 }, { "content": " ///\n\n /// Enumerated values, such as the `delay_model` simple attribute, are parsed as a\n\n /// [`Value::Expression`].\n\n Expression(String),\n\n}\n\n\n\nimpl fmt::Display for Value {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n match self {\n\n Value::Expression(v) => v.fmt(f),\n\n Value::String(v) => write!(f, \"\\\"{}\\\"\", v),\n\n Value::Bool(v) => {\n\n if *v {\n\n write!(f, \"true\")\n\n } else {\n\n write!(f, \"false\")\n\n }\n\n }\n\n Value::Float(v) => write!(f, \"{}\", PrettyPrintFloat(*v)),\n\n Value::FloatGroup(v) => write!(\n", "file_path": "src/ast.rs", "rank": 57, "score": 11.825079241477093 }, { "content": " \"foo\".to_string(),\n\n vec![GroupItem::ComplexAttr(\n\n \"abc\".to_string(),\n\n vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0),],\n\n ),],\n\n ),\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_nested_group() {\n\n assert_eq!(\n\n parse_group::<(&str, ErrorKind)>(\n\n r#\"\n\n outer( outer ) {\n\n inner ( inner) {\n\n abc ( 1, 2, 3 );\n\n }\n\n inner(inner2 ) {\n", "file_path": "src/parser.rs", "rank": 58, "score": 11.709959002163428 }, { "content": " ($fname:ident) => {{\n\n let data = include_str!(concat!(\"../data/\", stringify!($fname), \".lib\"));\n\n LibertyAst::from_string(data).unwrap()\n\n }};\n\n }\n\n\n\n #[test]\n\n fn test_files() {\n\n parse_file!(small);\n\n parse_file!(cells);\n\n parse_file!(cells_timing);\n\n }\n\n\n\n #[test]\n\n fn test_values() {\n\n assert_eq!(Value::Bool(false).bool(), false);\n\n assert_eq!(Value::Float(-3.45).float(), -3.45f64);\n\n assert_eq!(Value::Expression(\"A & B\".to_string()).expr(), \"A & B\");\n\n assert_eq!(\n\n Value::FloatGroup(vec![1.2, 3.4]).float_group(),\n\n vec![1.2, 3.4]\n\n );\n\n assert_eq!(Value::String(\"abc def\".to_string()).string(), \"abc def\");\n\n }\n\n}\n", "file_path": "src/ast.rs", "rank": 59, "score": 11.5580906904312 }, { "content": " )\"#\n\n ),\n\n Ok((\"\", vec![Value::String(\"a string(b)\".to_string())]))\n\n );\n\n assert_eq!(\n\n complex_attribute_values::<VerboseError<&str>>(\"(123,-456)\"),\n\n Ok((\"\", vec![Value::Float(123.0), Value::Float(-456.0),]))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_complex_attr() {\n\n assert_eq!(\n\n complex_attribute::<(&str, ErrorKind)>(\"capacitive_load_unit (1,pf);\"),\n\n Ok((\n\n \"\",\n\n GroupItem::ComplexAttr(\n\n \"capacitive_load_unit\".to_string(),\n\n vec![Value::Float(1.0), Value::Expression(\"pf\".to_string()),],\n\n )\n", "file_path": "src/parser.rs", "rank": 60, "score": 11.49899787404134 }, { "content": " \"inner2\".to_string(),\n\n vec![GroupItem::ComplexAttr(\n\n \"abc\".to_string(),\n\n vec![Value::Float(1.0), Value::Float(2.0), Value::Float(3.0),],\n\n ),],\n\n ),\n\n ]\n\n )\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_lib_simple() {\n\n assert_eq!(\n\n parse_libs::<(&str, ErrorKind)>(\n\n r#\"\n\n/*\n\n delay model : typ\n\n check model : typ\n", "file_path": "src/parser.rs", "rank": 61, "score": 11.019643931486467 }, { "content": " fn test_complex_attr_values() {\n\n assert_eq!(\n\n complex_attribute_values::<VerboseError<&str>>(\n\n r#\"( \\\n\n \"0, 0.18, 0.33\", \\\n\n \"-0.555, -0.45, -0.225\" \\\n\n )\"#\n\n ),\n\n Ok((\n\n \"\",\n\n vec![\n\n Value::FloatGroup(vec![0.0, 0.18, 0.33]),\n\n Value::FloatGroup(vec![-0.555, -0.45, -0.225]),\n\n ]\n\n ))\n\n );\n\n assert_eq!(\n\n complex_attribute_values::<VerboseError<&str>>(\n\n r#\"( \\\n\n \"a string(b)\" \\\n", "file_path": "src/parser.rs", "rank": 62, "score": 10.994745696082655 }, { "content": " assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : a b ; \"),\n\n Err(Err::Error((\"b ; \", ErrorKind::Char))),\n\n );\n\n }\n\n #[test]\n\n fn test_simple_attribute_bool() {\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : true ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Bool(true),)\n\n ))\n\n );\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : false ; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(String::from(\"attr_name\"), Value::Bool(false),)\n\n ))\n", "file_path": "src/parser.rs", "rank": 63, "score": 10.943300308380486 }, { "content": " if let Value::String(v) = self {\n\n v.clone()\n\n } else {\n\n panic!(\"Not a string\")\n\n }\n\n }\n\n\n\n /// Convert [`Value::Expression`] to `String` or panic\n\n pub fn expr(&self) -> String {\n\n if let Value::Expression(v) = self {\n\n v.clone()\n\n } else {\n\n panic!(\"Not a string\")\n\n }\n\n }\n\n\n\n /// Convert [`Value::Bool`] to `bool` or panic\n\n pub fn bool(&self) -> bool {\n\n if let Value::Bool(v) = self {\n\n *v\n", "file_path": "src/ast.rs", "rank": 64, "score": 10.59679142303822 }, { "content": "//! Defines the types and parser for the Abstract Syntax Tree (AST) representation of a Liberty\n\n//! file.\n\n//!\n\n\n\nuse std::{fmt, result};\n\n\n\nuse crate::error::Error;\n\nuse crate::liberty::Liberty;\n\nuse crate::parser::parse_libs;\n\n\n\nuse float_pretty_print::PrettyPrintFloat;\n\nuse itertools::Itertools;\n\nuse nom::error::VerboseError;\n\n\n\n/// Result type for parsing\n\npub type ParseResult<'a, T> = result::Result<T, Error<'a>>;\n\n\n\n/// Liberty file AST representation\n\n///\n\n/// Each liberty file can have one or more `library`s defined in it, which are represented as a\n", "file_path": "src/ast.rs", "rank": 65, "score": 10.461311589894464 }, { "content": " ///\n\n /// All numbers are parsed into `f64`. While the Liberty specification differentiates between\n\n /// integers and floating point values on a per-field basis, all are parsed into an `f64`.\n\n Float(f64),\n\n /// Group of floating point values in quotation marks\n\n ///\n\n /// For example, this complex attribute\n\n ///\n\n /// ```text\n\n /// values ( \\\n\n /// \"1.0, 2.0, 3.0\", \\\n\n /// \"4.0, 5.0, 6.0\" \\\n\n /// );\n\n /// ```\n\n ///\n\n /// will be parsed into a `Vec<Value::FloatGroup>`.\n\n FloatGroup(Vec<f64>),\n\n /// String enclosed in quotation marks\n\n String(String),\n\n /// Expression\n", "file_path": "src/ast.rs", "rank": 66, "score": 9.893932194066464 }, { "content": " ];\n\n for expr in expressions {\n\n assert_eq!(expression::<(&str, ErrorKind)>(expr), Ok((\"\", expr)));\n\n }\n\n }\n\n\n\n #[test]\n\n fn test_simple_attribute_expression() {\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : nand2; \"),\n\n Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(\n\n String::from(\"attr_name\"),\n\n Value::Expression(String::from(\"nand2\")),\n\n )\n\n ))\n\n );\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : table_lookup; \"),\n", "file_path": "src/parser.rs", "rank": 67, "score": 9.827465040397069 }, { "content": " |vals: Vec<String>| vals.join(\", \"),\n\n ),\n\n preceded(multispace0, char(')')),\n\n ),\n\n ),\n\n preceded(\n\n preceded(multispace0, char('{')),\n\n cut(terminated(\n\n parse_group_body,\n\n preceded(multispace0, char('}')),\n\n )),\n\n ),\n\n )),\n\n |(gtype, name, body)| GroupItem::Group(gtype.to_string(), name, body),\n\n ),\n\n )(input)\n\n}\n\n\n", "file_path": "src/parser.rs", "rank": 68, "score": 9.555801512971778 }, { "content": " f,\n\n \"\\\"{}\\\"\",\n\n format!(\"{}\", v.iter().map(|x| PrettyPrintFloat(*x)).format(\", \"))\n\n ),\n\n }\n\n }\n\n}\n\n\n\nimpl Value {\n\n /// Convert [`Value::Float`] to `f64` or panic\n\n pub fn float(&self) -> f64 {\n\n if let Value::Float(v) = self {\n\n *v\n\n } else {\n\n panic!(\"Not a float\")\n\n }\n\n }\n\n\n\n /// Convert [`Value::String`] to `String` or panic\n\n pub fn string(&self) -> String {\n", "file_path": "src/ast.rs", "rank": 69, "score": 9.493191278605162 }, { "content": " Ok((\n\n \" \",\n\n GroupItem::SimpleAttr(\n\n String::from(\"attr_name\"),\n\n Value::Expression(String::from(\"table_lookup\")),\n\n )\n\n ))\n\n );\n\n let data = \"attr_name : A +B; \";\n\n match simple_attribute::<VerboseError<&str>>(data) {\n\n Err(Err::Error(err)) | Err(Err::Failure(err)) => {\n\n println!(\"Error: {}\", convert_error(data, err));\n\n assert_eq!(true, false);\n\n }\n\n _ => {}\n\n }\n\n assert_eq!(\n\n simple_attribute::<(&str, ErrorKind)>(\"attr_name : A + 1.2; \"),\n\n Ok((\n\n \" \",\n", "file_path": "src/parser.rs", "rank": 70, "score": 9.201398563331113 }, { "content": " GroupItem::SimpleAttr(\n\n \"slew_upper_threshold_pct_rise\".to_string(),\n\n Value::Float(80.0)\n\n ),\n\n GroupItem::SimpleAttr(\"nom_temperature\".to_string(), Value::Float(25.0)),\n\n ],\n\n ),]\n\n ))\n\n );\n\n }\n\n}\n", "file_path": "src/parser.rs", "rank": 71, "score": 9.137460738589422 }, { "content": "#[macro_use]\n\nextern crate criterion;\n\n\n\nuse liberty_parse::ast::LibertyAst;\n\nuse liberty_parse::parse_lib;\n\n\n\nuse criterion::Criterion;\n\n\n\nmacro_rules! my_bench_file_ast {\n\n ($benchname:ident, $fname:ident) => {\n\n fn $benchname(c: &mut Criterion) {\n\n let data = include_str!(concat!(\"../data/\", stringify!($fname), \".lib\"));\n\n c.bench_function(stringify!($benchname), move |b| {\n\n b.iter(|| match LibertyAst::from_string(data).unwrap() {\n\n _ => {}\n\n })\n\n });\n\n }\n\n };\n\n}\n", "file_path": "benches/bench.rs", "rank": 72, "score": 9.001765266696905 }, { "content": " }\n\n\n\n #[test]\n\n fn test_parse_group() {\n\n let data = \"library ( foo ) {\n\n abc ( 1, 2, 3 );\n\n }\";\n\n match parse_group::<VerboseError<&str>>(data) {\n\n Err(Err::Error(err)) | Err(Err::Failure(err)) => {\n\n println!(\"Error: {}\", convert_error(data, err));\n\n assert_eq!(true, false);\n\n }\n\n _ => {}\n\n };\n\n assert_eq!(\n\n parse_group::<(&str, ErrorKind)>(data),\n\n Ok((\n\n \"\",\n\n GroupItem::Group(\n\n \"library\".to_string(),\n", "file_path": "src/parser.rs", "rank": 73, "score": 8.654344137138144 }, { "content": "use liberty_parse::parse_lib;\n\nuse std::io::{stdin, Read};\n\n\n", "file_path": "examples/reformat_lib.rs", "rank": 74, "score": 7.9921997695253 }, { "content": " GroupItem::SimpleAttr(_, _) => {}\n\n GroupItem::ComplexAttr(_, _) => {}\n\n }\n\n acc\n\n },\n\n ),\n\n multispace0,\n\n )),\n\n )(input)\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use nom::{\n\n error::{convert_error, ErrorKind, VerboseError},\n\n Err,\n\n };\n\n\n\n #[test]\n", "file_path": "src/parser.rs", "rank": 75, "score": 6.613731971008361 }, { "content": " power model : typ\n\n capacitance model : typ\n\n other model : typ\n\n*/\n\nlibrary(foo) {\n\n\n\n delay_model : table_lookup;\n\n /* unit attributes */\n\n time_unit : \"1ns\";\n\n capacitive_load_unit (1, pf );\n\n function: \"A & B\";\n\n\n\n slew_upper_threshold_pct_rise : 80;\n\n nom_temperature : 25.0;\n\n}\n\n\"#\n\n ),\n\n Ok((\n\n \"\",\n\n vec![GroupItem::Group(\n", "file_path": "src/parser.rs", "rank": 76, "score": 6.176279658180012 }, { "content": "use crate::ast::{GroupItem, Value};\n\n\n\nuse nom::{\n\n branch::alt,\n\n bytes::complete::{is_a, is_not, tag, take_until, take_while},\n\n character::complete::{alpha1, char, line_ending, multispace0, one_of},\n\n combinator::{all_consuming, cut, map, map_res, opt, peek, recognize},\n\n error::{context, ParseError},\n\n multi::{fold_many0, separated_list},\n\n number::complete::double,\n\n sequence::{delimited, preceded, terminated, tuple},\n\n IResult,\n\n};\n\n\n", "file_path": "src/parser.rs", "rank": 77, "score": 5.508904704197967 }, { "content": "use liberty_parse::parse_lib;\n\n\n", "file_path": "examples/get_area.rs", "rank": 78, "score": 5.400785266693857 }, { "content": "\n\nmacro_rules! my_bench_file {\n\n ($fname:ident) => {\n\n fn $fname(c: &mut Criterion) {\n\n let data = include_str!(concat!(\"../data/\", stringify!($fname), \".lib\"));\n\n c.bench_function(stringify!($fname), move |b| {\n\n b.iter(|| match parse_lib(data).unwrap() {\n\n _ => {}\n\n })\n\n });\n\n }\n\n };\n\n}\n\n\n\nmy_bench_file_ast!(ast_small, small);\n\nmy_bench_file_ast!(ast_cells, cells);\n\nmy_bench_file_ast!(ast_cells_timing, cells_timing);\n\n\n\nmy_bench_file!(small);\n\nmy_bench_file!(cells);\n", "file_path": "benches/bench.rs", "rank": 79, "score": 5.256531611370914 }, { "content": "my_bench_file!(cells_timing);\n\n\n\ncriterion_group!(\n\n benches,\n\n small,\n\n cells,\n\n cells_timing,\n\n ast_small,\n\n ast_cells,\n\n ast_cells_timing\n\n);\n\ncriterion_main!(benches);\n", "file_path": "benches/bench.rs", "rank": 80, "score": 4.785861428413542 }, { "content": " )\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_comment() {\n\n assert_eq!(\n\n comment::<(&str, ErrorKind)>(\"/*** abc **/def\"),\n\n Ok((\"def\", \"/*** abc **/\"))\n\n );\n\n assert_eq!(\n\n comment::<(&str, ErrorKind)>(\n\n \"/* multi\n\nline\n\n**\n\n**/\n\n**/rest\"\n\n ),\n\n Ok((\n", "file_path": "src/parser.rs", "rank": 81, "score": 2.482117292112007 }, { "content": " assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\"nand2\"),\n\n Ok((\"\", \"nand2\"))\n\n );\n\n assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\"_\"),\n\n Err(Err::Error((\"_\", ErrorKind::Alpha)))\n\n );\n\n assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\" a_b\"),\n\n Err(Err::Error((\" a_b\", ErrorKind::Alpha)))\n\n );\n\n assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\",,\"),\n\n Err(Err::Error((\",,\", ErrorKind::Alpha)))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_simple_attribute_malformed() {\n", "file_path": "src/parser.rs", "rank": 82, "score": 2.4689767865225605 }, { "content": " \"\n\n**/rest\",\n\n \"/* multi\n\nline\n\n**\n\n**/\"\n\n ))\n\n );\n\n }\n\n\n\n #[test]\n\n fn test_underscore_tag() {\n\n assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\"a_b__c\"),\n\n Ok((\"\", \"a_b__c\"))\n\n );\n\n assert_eq!(\n\n underscore_tag::<(&str, ErrorKind)>(\"abc other\"),\n\n Ok((\" other\", \"abc\"))\n\n );\n", "file_path": "src/parser.rs", "rank": 83, "score": 2.4030876141791957 }, { "content": " Error(_, Err::Incomplete(_)) => write!(f, \"Input data is incomplete\"),\n\n }\n\n }\n\n}\n\n\n\nimpl<'a> error::Error for Error<'a> {\n\n fn source(&self) -> Option<&(dyn error::Error + 'static)> {\n\n None\n\n }\n\n}\n", "file_path": "src/error.rs", "rank": 84, "score": 2.0819860948248476 } ]
Rust
src/libpcp/term/constant.rs
ptal/pcp
5775dd8523a35ff521daf3cfa709794829d75955
use term::ops::*; use model::*; use kernel::*; use propagation::events::*; use gcollections::ops::*; use gcollections::*; use std::fmt::Debug; #[derive(Clone, Debug)] pub struct Constant<V> { value: V } impl<V> Constant<V> { pub fn new(value: V) -> Constant<V> { Constant { value: value } } } impl<V> DisplayStateful<Model> for Constant<V> where V: Debug { fn display(&self, _model: &Model) { print!("{:?}", self.value); } } impl<V, Domain, VStore> StoreMonotonicUpdate<VStore> for Constant<V> where VStore: Collection<Item=Domain>, Domain: Collection<Item=V> + Cardinality + Contains { fn update(&mut self, _store: &mut VStore, value: VStore::Item) -> bool { !value.is_empty() && value.contains(&self.value) } } impl<V, Domain, VStore> StoreRead<VStore> for Constant<V> where VStore: Collection<Item=Domain>, Domain: Collection<Item=V> + Singleton, V: Clone { fn read(&self, _store: &VStore) -> Domain { Domain::singleton(self.value.clone()) } } impl<V> ViewDependencies<FDEvent> for Constant<V> { fn dependencies(&self, _event: FDEvent) -> Vec<(usize, FDEvent)> { vec![] } } #[cfg(test)] mod test { use super::*; use trilean::SKleene; use trilean::SKleene::*; use propagation::*; use propagation::events::FDEvent; use propagation::events::FDEvent::*; use concept::*; use variable::VStoreFD; use propagators::test::*; use propagators::cmp::*; use interval::interval::*; type VStore = VStoreFD; #[test] fn x_less_constant() { let dom0_10 = (0,10).to_interval(); let dom0_4 = (0,4).to_interval(); let mut store = VStore::empty(); let x = Box::new(store.alloc(dom0_10)) as Var<VStore>; let c = Box::new(Constant::new(5 as i32)) as Var<VStore>; let x_less_c = XLessY::new(x.bclone(), c); test_propagation(1, x_less_c, &mut store, Unknown, True, vec![(0, Bound)], true); assert_eq!(x.read(&store), dom0_4); } #[test] fn unary_propagator_test() { let dom0_10 = (0,10).to_interval(); let dom0_0 = (0,0).to_interval(); unary_propagator_test_one(1, dom0_10, 0, XLessY::new, False, False, vec![], false); unary_propagator_test_one(2, dom0_10, 11, XLessY::new, True, True, vec![], true); unary_propagator_test_one(3, dom0_10, 10, XLessY::new, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(4, dom0_10, -1, x_leq_y, False, False, vec![], false); unary_propagator_test_one(5, dom0_10, 10, x_leq_y, True, True, vec![], true); unary_propagator_test_one(6, dom0_10, 9, x_leq_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(7, dom0_10, 10, x_greater_y, False, False, vec![], false); unary_propagator_test_one(8, dom0_10, -1, x_greater_y, True, True, vec![], true); unary_propagator_test_one(9, dom0_10, 0, x_greater_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(10, dom0_10, 11, x_geq_y, False, False, vec![], false); unary_propagator_test_one(11, dom0_10, 0, x_geq_y, True, True, vec![], true); unary_propagator_test_one(12, dom0_10, 1, x_geq_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(13, dom0_0, 0, XNeqY::new, False, False, vec![], false); unary_propagator_test_one(14, dom0_10, 5, XNeqY::new, Unknown, Unknown, vec![], true); unary_propagator_test_one(15, dom0_10, 0, XNeqY::new, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(16, dom0_10, 10, XNeqY::new, Unknown, True, vec![(0, Bound)], true); } fn unary_propagator_test_one<P, R>(id: u32, x: Interval<i32>, c: i32, make_prop: P, before: SKleene, after: SKleene, expected: Vec<(usize, FDEvent)>, propagate_success: bool) where P: FnOnce(FDVar, FDVar) -> R, R: PropagatorConcept<VStoreFD, FDEvent> { let mut store = VStore::empty(); let x = Box::new(store.alloc(x)) as Var<VStore>; let propagator = make_prop(x, Box::new(Constant::new(c)) as Var<VStore>); test_propagation(id, propagator, &mut store, before, after, expected, propagate_success); } }
use term::ops::*; use model::*; use kernel::*; use propagation::events::*; use gcollections::ops::*; use gcollections::*; use std::fmt::Debug; #[derive(Clone, Debug)] pub struct Constant<V> { value: V } impl<V> Constant<V> { pub fn new(value: V) -> Constant<V> { Constant { value: value } } } impl<V> DisplayStateful<Model> for Constant<V> where V: Debug { fn display(&self, _model: &Model) { print!("{:?}", self.value); } } impl<V, Domain, VStore> StoreMonotonicUpdate<VStore> for Constant<V> where VStore: Collection<Item=Domain>, Domain: Collection<Item=V> + Cardinality + Contains { fn update(&mut self, _store: &mut VStore, value: VStore::Item) -> bool { !value.is_empty() && value.contains(&self.value) } } impl<V, Domain, VStore> StoreRead<VStore> for Constant<V> where VStore: Collection<Item=Domain>, Domain: Collection<Item=V> + Singleton, V: Clone { fn read(&self, _store: &VStore) -> Domain { Domain::singleton(self.value.clone()) } } impl<V> ViewDependencies<FDEvent> for Constant<V> { fn dependencies(&self, _event: FDEvent) -> Vec<(usize, FDEvent)> { vec![] } } #[cfg(test)] mod test { use super::*; use trilean::SKleene; use trilean::SKleene::*; use propagation::*; use propagation::events::FDEvent; use propagation::events::FDEvent::*; use concept::*; use variable::VStoreFD; use propagators::test::*; use propagators::cmp::*; use interval::interval::*; type VStore = VStoreFD; #[test] fn x_less_constant() { let dom0_10 = (0,10).to_interval(); let dom0_4 = (0,4).to_interval(); let mut store = VStore::empty(); let x = Box::new(store.alloc(dom0_10)) as Var<VStore>; let c = Box::new(Constant::new(5 as i32)) as Var<VStore>; let x_less_c = XLessY::new(x.bclone(), c); test_propagation(1, x_less_c, &mut store, Unknown, True, vec![(0, Bound)], true); assert_eq!(x.read(&store), dom0_4); } #[test] fn unary_propagator_test() { let dom0_10 = (0,10).to_interval(); let dom0_0 = (0,0).to_interval(); unary_propagator_test_one(1, dom0_10, 0, XLessY::new, False, False, vec![], false); unary_propagator_test_one(2, dom0_10, 11, XLessY::new, True, True, vec![], true); unary_propagator_test_one(3, dom0_10, 10, XLessY::new, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(4, dom0_10, -1, x_leq_y, False, False, vec![], false); unary_propagator_test_one(5, dom0_10, 10, x_leq_y, True, True, vec![], true); unary_propagator_test_one(6, dom0_10, 9, x_leq_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(7, dom0_10, 10, x_greater_y, False, False, vec![], false); unary_propagator_test_one(8, dom0_10, -1, x_greater_y, True, True, vec![], true); unary_propagator_test_one(9, dom0_10, 0, x_greater_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(10, dom0_10, 11, x_geq_y, False, False, vec![], false); unary_propagator_test_one(11, dom0_10, 0, x_geq_y, True, True, vec![], true); unary_propagator_test_one(12, dom0_10, 1, x_geq_y, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(13, dom0_0, 0, XNeqY::new, False, False, vec![], false); unary_propagator_test_one(14, dom0_10, 5, XNeqY::new, Unknown, Unknown, vec![], true); unary_propagator_test_one(15, dom0_10, 0, XNeqY::new, Unknown, True, vec![(0, Bound)], true); unary_propagator_test_one(16, dom0_10, 10, XNeqY::new, Unknown, True, vec![(0, Bound)], true); }
}
fn unary_propagator_test_one<P, R>(id: u32, x: Interval<i32>, c: i32, make_prop: P, before: SKleene, after: SKleene, expected: Vec<(usize, FDEvent)>, propagate_success: bool) where P: FnOnce(FDVar, FDVar) -> R, R: PropagatorConcept<VStoreFD, FDEvent> { let mut store = VStore::empty(); let x = Box::new(store.alloc(x)) as Var<VStore>; let propagator = make_prop(x, Box::new(Constant::new(c)) as Var<VStore>); test_propagation(id, propagator, &mut store, before, after, expected, propagate_success); }
function_block-full_function
[ { "content": "pub fn x_leq_y<VStore, Domain, Bound>(x: Var<VStore>, y: Var<VStore>) -> XLessEqY<VStore> where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: Collection<Item=Bound> + IntDomain,\n\n Bound: IntBound\n\n{\n\n XLessY::new(x, Box::new(Addition::new(y, Bound::one())))\n\n}\n\n\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 0, "score": 371901.6133793747 }, { "content": "pub fn x_geq_y<VStore, Domain, Bound>(x: Var<VStore>, y: Var<VStore>) -> XGreaterEqY<VStore> where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: Collection<Item=Bound> + IntDomain,\n\n Bound: IntBound\n\n{\n\n x_greater_y(Box::new(Addition::new(x, Bound::one())), y)\n\n}\n\n\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 1, "score": 371901.6133793747 }, { "content": "/// Precondition: `vars.len() > 1`.\n\npub fn join_distinct<VStore, CStore, Domain, Bound>(\n\n _vstore: &mut VStore, cstore: &mut CStore, vars: Vec<Var<VStore>>) where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: IntDomain<Item=Bound> + 'static,\n\n Bound: IntBound + 'static,\n\n CStore: IntCStore<VStore> + 'static\n\n{\n\n assert!(vars.len() > 0,\n\n \"Variable array in `Distinct` must be non-empty.\");\n\n for i in 0..vars.len()-1 {\n\n for j in i+1..vars.len() {\n\n cstore.alloc(Box::new(XNeqY::new(vars[i].bclone(), vars[j].bclone())));\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug)]\n\npub struct Distinct<VStore>\n\n{\n\n conj: Conjunction<VStore>,\n", "file_path": "src/libpcp/propagators/distinct.rs", "rank": 2, "score": 359378.6891607802 }, { "content": "pub fn x_geq_y_plus_z<VStore, Domain, Bound>(x: Var<VStore>, y: Var<VStore>, z: Var<VStore>)\n\n -> XGreaterEqYPlusZ<VStore> where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: Collection<Item=Bound> + IntDomain,\n\n Bound: IntBound\n\n{\n\n XGreaterYPlusZ::new(Box::new(Addition::new(x, Bound::one())), y, z)\n\n}\n\n\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 3, "score": 351794.2496208517 }, { "content": "pub fn x_leq_y_plus_z<VStore, Domain, Bound>(x: Var<VStore>, y: Var<VStore>, z: Var<VStore>)\n\n -> XLessEqYPlusZ<VStore> where\n\n VStore: VStoreConcept<Item=Domain> + 'static,\n\n Domain: Collection<Item=Bound> + IntDomain,\n\n Bound: IntBound\n\n{\n\n XLessYPlusZ::new(Box::new(Addition::new(x, -Bound::one())), y, z)\n\n}\n\n\n\n// #[cfg(test)]\n\n// mod test {\n\n// use super::*;\n\n// use kernel::*;\n\n// use trilean::SKleene::*;\n\n// use propagation::events::*;\n\n// use propagation::events::FDEvent::*;\n\n// use interval::interval::*;\n\n// use propagators::test::*;\n\n\n\n// #[test]\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 4, "score": 351794.2496208517 }, { "content": "pub fn x_greater_y<VStore>(x: Var<VStore>, y: Var<VStore>) -> XGreaterY<VStore> {\n\n XLessY::new(y, x)\n\n}\n\n\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 5, "score": 304697.75966437696 }, { "content": "type CStore = CStoreFD<VStore>;\n\npub type FDSpace = Space<VStore, CStore, NoRecomputation<VStore, CStore>>;\n\n\n", "file_path": "src/libpcp/search/mod.rs", "rank": 6, "score": 241413.2840519652 }, { "content": "pub fn equivalence<VStore>(f: Formula<VStore>, g: Formula<VStore>) -> Formula<VStore> where\n\n VStore: Collection + 'static\n\n{\n\n Box::new(Conjunction::new(vec![\n\n implication(f.bclone(), g.bclone()),\n\n implication(g, f)\n\n ]))\n\n}\n", "file_path": "src/libpcp/logic/mod.rs", "rank": 7, "score": 238473.3543498911 }, { "content": "pub fn implication<VStore>(f: Formula<VStore>, g: Formula<VStore>) -> Formula<VStore> where\n\n VStore: Collection + 'static\n\n{\n\n Box::new(Disjunction::new(vec![f, g.not()]))\n\n}\n\n\n", "file_path": "src/libpcp/logic/mod.rs", "rank": 8, "score": 238473.3543498911 }, { "content": "pub trait PropagatorConcept_<VStore, Event> :\n\n Propagator<VStore>\n\n + Subsumption<VStore>\n\n + PropagatorDependencies<Event>\n\n + DisplayStateful<Model> + Debug\n\n + NotFormula<VStore>\n\n{}\n\n\n\nimpl<VStore, Event, R> PropagatorConcept_<VStore, Event> for R where\n\n R: Propagator<VStore>,\n\n R: Subsumption<VStore>,\n\n R: PropagatorDependencies<Event>,\n\n R: DisplayStateful<Model> + Debug,\n\n R: NotFormula<VStore>\n\n{}\n\n\n", "file_path": "src/libpcp/propagation/concept.rs", "rank": 9, "score": 225995.03848672548 }, { "content": "pub trait PropagatorConcept<VStore, Event>:\n\n PropagatorConcept_<VStore, Event>\n\n{\n\n fn bclone(&self) -> Box<dyn PropagatorConcept<VStore, Event>>;\n\n}\n\n\n\nimpl<VStore, Event, R> PropagatorConcept<VStore, Event> for R where\n\n R: PropagatorConcept_<VStore, Event>,\n\n R: Clone + NotFormula<VStore> + 'static,\n\n{\n\n fn bclone(&self) -> Box<dyn PropagatorConcept<VStore, Event>> {\n\n Box::new(self.clone())\n\n }\n\n}\n", "file_path": "src/libpcp/propagation/concept.rs", "rank": 10, "score": 225995.03848672548 }, { "content": "pub trait IntCStore<VStore>:\n\n Alloc + Empty + Clone + Freeze + DisplayStateful<Model> + DisplayStateful<(Model, VStore)> +\n\n Collection<Item=Box<dyn PropagatorConcept<VStore, FDEvent>>> +\n\n Consistency<VStore>\n\n{}\n\n\n\nimpl<R, VStore> IntCStore<VStore> for R where\n\n R: Alloc + Empty + Clone + Freeze + DisplayStateful<Model> + DisplayStateful<(Model, VStore)>,\n\n R: Collection<Item=Box<dyn PropagatorConcept<VStore, FDEvent>>>,\n\n R: Consistency<VStore>\n\n{}\n\n\n\npub type Formula<VStore> = Box<dyn PropagatorConcept<VStore, FDEvent>>;\n", "file_path": "src/libpcp/concept.rs", "rank": 11, "score": 224362.7401959427 }, { "content": "fn undo_delta_from_trail<Domain>(node: &Rc<Trail<Domain>>, delta: &mut VecMap<Domain>) where\n\n Domain: DomainConcept\n\n{\n\n for cell in node.trail.iter() {\n\n delta.insert(cell.location, cell.value.clone());\n\n }\n\n}\n\n\n", "file_path": "src/libpcp/variable/memory/trailed.rs", "rank": 12, "score": 192045.76687403172 }, { "content": "fn redo_delta_from_trail<Domain>(node: &Rc<Trail<Domain>>, delta: &mut VecMap<Domain>) where\n\n Domain: DomainConcept\n\n{\n\n for cell in node.trail.iter() {\n\n delta.entry(cell.location).or_insert(cell.value.clone());\n\n }\n\n}\n\n\n", "file_path": "src/libpcp/variable/memory/trailed.rs", "rank": 13, "score": 192045.76687403172 }, { "content": "pub trait IntVariable<VStore>: IntVariable_<VStore>\n\n where VStore: Collection\n\n{\n\n fn bclone(&self) -> Box<dyn IntVariable<VStore>>;\n\n}\n\n\n\nimpl<VStore, R> IntVariable<VStore> for R where\n\n R: IntVariable_<VStore>,\n\n R: Clone + 'static,\n\n VStore: Collection\n\n{\n\n fn bclone(&self) -> Box<dyn IntVariable<VStore>> {\n\n Box::new(self.clone())\n\n }\n\n}\n\n\n", "file_path": "src/libpcp/concept.rs", "rank": 14, "score": 191901.0982032708 }, { "content": "pub trait Propagator<VStore>\n\n{\n\n /// Returns `false` if it failed to propagate (a variable has an empty domain after propagation).\n\n fn propagate(&mut self, store: &mut VStore) -> bool;\n\n}\n\n\n", "file_path": "src/libpcp/propagation/ops.rs", "rank": 15, "score": 189181.97766695273 }, { "content": "pub trait Consistency<VStore> {\n\n fn consistency(&mut self, store: &mut VStore) -> SKleene;\n\n}\n", "file_path": "src/libpcp/kernel/consistency.rs", "rank": 16, "score": 182144.91143400033 }, { "content": "pub trait IntVariable_<VStore>:\n\n ViewDependencies<FDEvent> +\n\n StoreMonotonicUpdate<VStore> +\n\n StoreRead<VStore> +\n\n Debug + DisplayStateful<Model>\n\n where VStore: Collection\n\n{}\n\n\n\nimpl<R, VStore> IntVariable_<VStore> for R where\n\n R: ViewDependencies<FDEvent>,\n\n R: StoreMonotonicUpdate<VStore>,\n\n R: StoreRead<VStore>,\n\n R: Debug + DisplayStateful<Model>,\n\n VStore: Collection\n\n{}\n\n\n\npub type Var<VStore> = Box<dyn IntVariable<VStore>>;\n\n\n", "file_path": "src/libpcp/concept.rs", "rank": 17, "score": 182122.0260412107 }, { "content": "pub trait FreezeSpace<VStore, CStore> {\n\n fn freeze_space(vstore: VStore, cstore: CStore) -> Self;\n\n}\n", "file_path": "src/libpcp/search/recomputation/ops.rs", "rank": 18, "score": 177630.51194857934 }, { "content": "fn undo_redo_node<Domain>(node: &mut CopyMemory<Domain>,\n\n undo_delta: VecMap<Domain>, redo_delta: VecMap<Domain>)\n\n{\n\n for (loc, value) in undo_delta {\n\n debug_assert!(loc <= node.size(), \"All variables must be recorded.\");\n\n if loc == node.size() { break; }\n\n node.deref_mut()[loc] = value;\n\n }\n\n let mut redo_delta = redo_delta.into_iter();\n\n while let Some((loc, value)) = redo_delta.next() {\n\n debug_assert!(loc <= node.size(), \"All variables must be recorded.\");\n\n if loc == node.size() {\n\n node.push(value);\n\n break;\n\n }\n\n node.deref_mut()[loc] = value;\n\n }\n\n\n\n for (loc, value) in redo_delta {\n\n node.push(value);\n\n debug_assert!(node.size() == loc,\n\n \"From a node A (with n variables) to a node B (with m variables), some variables between n to m-1 were not recorded.\");\n\n }\n\n}\n\n\n", "file_path": "src/libpcp/variable/memory/trailed.rs", "rank": 19, "score": 171571.2672010169 }, { "content": "pub trait VStoreConcept:\n\n ImmutableMemoryConcept\n\n + AssociativeCollection<Location=Identity<<Self as Collection>::Item>>\n\n + Alloc\n\n + MonotonicUpdate\n\n + DisplayStateful<Model>\n\n{\n\n}\n", "file_path": "src/libpcp/variable/concept.rs", "rank": 20, "score": 170558.02469907762 }, { "content": "#[plugin_registrar]\n\npub fn plugin_registrar(reg: &mut Registry) {\n\n reg.register_syntax_extension(\n\n rust::token::intern(\"pcp\"),\n\n rust::SyntaxExtension::NormalTT(Box::new(expand), None, true));\n\n}\n\n\n", "file_path": "lang/src/lib.rs", "rank": 21, "score": 160813.42334620946 }, { "content": "pub trait EventConcept<Domain>:\n\n MonotonicEvent<Domain> + Merge + Clone + Debug\n\n{}\n\n\n\nimpl<Domain, R> EventConcept<Domain> for R where\n\n R: MonotonicEvent<Domain> + Merge + Clone + Debug\n\n{}\n\n\n", "file_path": "src/libpcp/variable/concept.rs", "rank": 22, "score": 156319.78911724366 }, { "content": "pub trait ValSelection<Domain> where Domain: Collection\n\n{\n\n fn select(&mut self, dom: Domain) -> Domain::Item;\n\n}\n\n\n", "file_path": "src/libpcp/search/branching/mod.rs", "rank": 23, "score": 149980.88941166794 }, { "content": "pub trait Subsumption<Store>\n\n{\n\n fn is_subsumed(&self, store: &Store) -> SKleene;\n\n}\n\n\n", "file_path": "src/libpcp/propagation/ops.rs", "rank": 24, "score": 147816.86981211678 }, { "content": "pub trait NotFormula<VStore>\n\n{\n\n fn not(&self) -> Formula<VStore>;\n\n}\n", "file_path": "src/libpcp/logic/ops.rs", "rank": 25, "score": 145338.86511430796 }, { "content": "pub trait MonotonicEvent<Domain> : Sized {\n\n // precondition: `little` is a subset of `big`.\n\n // returns `None` if no event occurred.\n\n fn new(little: &Domain, big: &Domain) -> Option<Self>;\n\n}\n", "file_path": "src/libpcp/kernel/event.rs", "rank": 26, "score": 142258.70241169032 }, { "content": "pub trait Distributor<Space, Bound> where Space: Freeze {\n\n // Postcondition: The union of the solutions of the child spaces must be equal to the solutions of the root space.\n\n fn distribute(&mut self, space: Space, var_idx: usize, val: Bound) -> (Space::FrozenState, Vec<Branch<Space>>);\n\n}\n", "file_path": "src/libpcp/search/branching/mod.rs", "rank": 27, "score": 132617.7854261138 }, { "content": "pub trait IntDomain:\n\n Bounded + Cardinality + Empty + IsEmpty + Singleton + IsSingleton + Range + Contains +\n\n ShrinkLeft + ShrinkRight + StrictShrinkLeft + StrictShrinkRight +\n\n Difference<<Self as Collection>::Item, Output=Self> +\n\n Intersection<Output=Self> + Difference<Output=Self> + Overlap + Subset + Disjoint +\n\n Add<<Self as Collection>::Item, Output=Self> + Sub<<Self as Collection>::Item, Output=Self> +\n\n Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> +\n\n Clone + Debug\n\nwhere\n\n <Self as Collection>::Item: IntBound\n\n{}\n\n\n\nimpl<R> IntDomain for R where\n\n R: Bounded + Cardinality + Empty + IsEmpty + Singleton + IsSingleton + Range + Contains,\n\n R: ShrinkLeft + ShrinkRight + StrictShrinkLeft + StrictShrinkRight,\n\n R: Difference<<R as Collection>::Item, Output=R>,\n\n R: Intersection<Output=R> + Difference<Output=R> + Overlap + Subset + Disjoint,\n\n R: Add<<R as Collection>::Item, Output=R> + Sub<<R as Collection>::Item, Output=R>,\n\n R: Add<Output=R> + Sub<Output=R> + Mul<Output=R>,\n\n R: Clone + Debug,\n\n <R as Collection>::Item: IntBound\n\n{}\n\n\n", "file_path": "src/libpcp/concept.rs", "rank": 28, "score": 130350.60533014109 }, { "content": "pub trait IntBound:\n\n Integer + Clone + Debug\n\n + Signed // Due to the lack of Subtraction in term/\n\n{}\n\n\n\nimpl<R> IntBound for R where\n\n R: Integer + Clone + Debug\n\n + Signed\n\n{}\n\n\n", "file_path": "src/libpcp/concept.rs", "rank": 29, "score": 130350.60533014109 }, { "content": "pub fn one_solution_engine() -> Box<dyn SearchTreeVisitor<FDSpace>> {\n\n let search =\n\n OneSolution::<_, VectorStack<_>, FDSpace>::new(\n\n Propagation::new(\n\n Brancher::new(FirstSmallestVar, MiddleVal, BinarySplit)));\n\n Box::new(search)\n\n}\n\n\n\n#[cfg(test)]\n\nmod test {\n\n pub use super::*;\n\n use propagators::cmp::*;\n\n use propagators::distinct::*;\n\n use term::*;\n\n use gcollections::ops::*;\n\n use interval::interval_set::*;\n\n use concept::*;\n\n\n\n pub fn nqueens(n: usize, space: &mut FDSpace) {\n\n let mut queens: Vec<Var<VStore>> = vec![];\n", "file_path": "src/libpcp/search/mod.rs", "rank": 30, "score": 124603.67775509885 }, { "content": "struct MemoryCell<Domain>\n\n{\n\n location: usize,\n\n value: Domain\n\n}\n\n\n\nimpl<Domain> MemoryCell<Domain>\n\n{\n\n fn new(location: usize, value: Domain) -> MemoryCell<Domain> {\n\n MemoryCell {\n\n location: location,\n\n value: value\n\n }\n\n }\n\n}\n\n\n\nimpl<Domain> Display for MemoryCell<Domain> where\n\n Domain: Display\n\n{\n\n fn fmt(&self, formatter: &mut Formatter) -> Result<(), Error> {\n", "file_path": "src/libpcp/variable/memory/trailed.rs", "rank": 31, "score": 123417.6682252143 }, { "content": "pub trait StoreRead<Store: Collection>\n\n{\n\n fn read(&self, store: &Store) -> Store::Item;\n\n}\n\n\n", "file_path": "src/libpcp/term/ops.rs", "rank": 32, "score": 116154.06674532901 }, { "content": "pub trait StoreMonotonicUpdate<Store: Collection>\n\n{\n\n fn update(&mut self, store: &mut Store, value: Store::Item) -> bool;\n\n}\n\n\n", "file_path": "src/libpcp/term/ops.rs", "rank": 33, "score": 114716.53549575707 }, { "content": "pub fn nqueens(n: usize) {\n\n let mut space = FDSpace::empty();\n\n\n\n let mut queens = vec![];\n\n // 2 queens can't share the same line.\n\n for _ in 0..n {\n\n queens.push(Box::new(space.vstore.alloc(IntervalSet::new(1, n as i32))) as Var<VStore>);\n\n }\n\n for i in 0..n-1 {\n\n for j in i + 1..n {\n\n // 2 queens can't share the same diagonal.\n\n let q1 = (i + 1) as i32;\n\n let q2 = (j + 1) as i32;\n\n // Xi + i != Xj + j reformulated as: Xi != Xj + j - i\n\n space.cstore.alloc(Box::new(XNeqY::new(\n\n queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), q2 - q1)) as Var<VStore>)));\n\n // Xi - i != Xj - j reformulated as: Xi != Xj - j + i\n\n space.cstore.alloc(Box::new(XNeqY::new(\n\n queens[i].bclone(), Box::new(Addition::new(queens[j].bclone(), -q2 + q1)) as Var<VStore>)));\n\n }\n", "file_path": "example/src/nqueens.rs", "rank": 34, "score": 110764.44090848503 }, { "content": "fn rc_eq<T>(a: &Rc<T>, b: &Rc<T>) -> bool\n\n{\n\n a.deref() as *const T == b.deref() as *const T\n\n}\n\n\n\n\n", "file_path": "src/libpcp/variable/memory/trailed.rs", "rank": 35, "score": 99890.8580290566 }, { "content": "pub trait MemoryConcept:\n\n ImmutableMemoryConcept\n\n + AssociativeCollection<Location=usize>\n\n + Push<Back>\n\n + Replace\n\n{}\n", "file_path": "src/libpcp/variable/memory/concept.rs", "rank": 36, "score": 97652.28238231772 }, { "content": "fn expand<'cx>(cx: &'cx mut rust::ExtCtxt, _sp: rust::Span,\n\n tts: &[rust::TokenTree]) -> Box<rust::MacResult + 'cx>\n\n{\n\n parse(cx, tts.iter().cloned().collect())\n\n}\n\n\n", "file_path": "lang/src/lib.rs", "rank": 37, "score": 96768.56560623158 }, { "content": "pub trait ImmutableMemoryConcept:\n\n Collection\n\n + AssociativeCollection\n\n + Cardinality<Size=usize>\n\n + Iterable\n\n + Empty\n\n + Index<usize, Output=<Self as Collection>::Item>\n\n + Freeze\n\n + Debug\n\n{}\n\n\n", "file_path": "src/libpcp/variable/memory/concept.rs", "rank": 38, "score": 96147.33350097708 }, { "content": "pub trait PropagatorDependencies<Event>\n\n{\n\n /// Each event on a variable that can change the result of the `is_subsumed` method should be listed here.\n\n fn dependencies(&self) -> Vec<(usize, Event)>;\n\n}\n", "file_path": "src/libpcp/propagation/ops.rs", "rank": 39, "score": 94315.51864436628 }, { "content": "pub trait Merge {\n\n fn merge(x: Self, y: Self) -> Self;\n\n}\n", "file_path": "src/libpcp/kernel/merge.rs", "rank": 40, "score": 91759.82758090406 }, { "content": "pub trait Scheduler {\n\n fn new(capacity: usize) -> Self;\n\n fn schedule(&mut self, idx: usize);\n\n fn unschedule(&mut self, idx: usize);\n\n fn pop(&mut self) -> Option<usize>;\n\n fn is_empty(&self) -> bool;\n\n}\n", "file_path": "src/libpcp/propagation/scheduler.rs", "rank": 41, "score": 89691.90339322705 }, { "content": "pub trait Reactor {\n\n fn new(num_vars: usize, num_events: usize) -> Self;\n\n fn subscribe<E>(&mut self, var: usize, ev: E, prop: usize) where E: EventIndex;\n\n fn unsubscribe<E>(&mut self, var: usize, ev: E, prop: usize) where E: EventIndex;\n\n fn react<E>(&self, var: usize, ev: E) -> Vec<usize> where E: EventIndex;\n\n}\n", "file_path": "src/libpcp/propagation/reactor.rs", "rank": 42, "score": 89691.90339322705 }, { "content": "pub trait Snapshot : Sized\n\n{\n\n type Label;\n\n type State : Freeze<FrozenState=Self>;\n\n\n\n fn label(&mut self) -> Self::Label;\n\n fn restore(self, label: Self::Label) -> Self::State;\n\n fn unfreeze(mut self) -> Self::State {\n\n let label = self.label();\n\n self.restore(label)\n\n }\n\n}\n", "file_path": "src/libpcp/kernel/restoration.rs", "rank": 43, "score": 89033.61313686354 }, { "content": "pub trait Freeze : Sized\n\n{\n\n type FrozenState : Snapshot<State=Self>;\n\n fn freeze(self) -> Self::FrozenState;\n\n}\n\n\n", "file_path": "src/libpcp/kernel/restoration.rs", "rank": 44, "score": 89033.61313686354 }, { "content": "pub trait EventIndex : Copy {\n\n fn to_index(self) -> usize;\n\n fn size() -> usize;\n\n}\n\n\n", "file_path": "src/libpcp/kernel/event.rs", "rank": 45, "score": 87278.45241141388 }, { "content": "pub trait DisplayStateful<State> {\n\n fn display(&self, state: &State);\n\n}\n\n\n\nimpl<State, R> DisplayStateful<State> for Box<R> where\n\n R: DisplayStateful<State>\n\n{\n\n fn display(&self, state: &State) {\n\n self.deref().display(state);\n\n }\n\n}", "file_path": "src/libpcp/kernel/display_stateful.rs", "rank": 46, "score": 85603.62315317689 }, { "content": "pub trait VarSelection<Space> {\n\n // Precondition: `space` must have variables not assigned.\n\n // Returns the index of the variable selected in `space`.\n\n fn select(&mut self, space: &Space) -> usize;\n\n}\n\n\n", "file_path": "src/libpcp/search/branching/mod.rs", "rank": 47, "score": 85066.94764165251 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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//! The kernel is a set of reusable traits shared among the different modules. It does not provide specific implementations.\n\n\n\npub mod consistency;\n\npub mod merge;\n\npub mod event;\n\npub mod restoration;\n\npub mod display_stateful;\n\n\n\npub use kernel::consistency::*;\n\npub use kernel::merge::*;\n\npub use kernel::event::*;\n\npub use kernel::restoration::*;\n\npub use kernel::display_stateful::*;\n", "file_path": "src/libpcp/kernel/mod.rs", "rank": 48, "score": 80634.73847487486 }, { "content": "// Copyright 2016 Pierre Talbot (IRCAM)\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 kernel::DisplayStateful;\n\nuse logic::ops::*;\n\nuse propagation::ops::*;\n\nuse model::*;\n\nuse std::fmt::Debug;\n\n\n", "file_path": "src/libpcp/propagation/concept.rs", "rank": 49, "score": 79038.25765855906 }, { "content": " before: SKleene, after: SKleene,\n\n delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool) where\n\n P: PropagatorConcept<VStoreFD, FDEvent>,\n\n FnProp: FnOnce(FDVar, FDVar, FDVar) -> P\n\n {\n\n let mut vstore = VStoreFD::empty();\n\n let x = Box::new(vstore.alloc(x)) as Var<VStoreFD>;\n\n let y = Box::new(vstore.alloc(y)) as Var<VStoreFD>;\n\n let z = Box::new(vstore.alloc(z)) as Var<VStoreFD>;\n\n let propagator = make_prop(x, y, z);\n\n test_propagation(test_num, propagator, &mut vstore, before, after, delta_expected, propagate_success);\n\n }\n\n\n\n pub fn nary_propagator_test<P, FnProp>(test_num: u32, make_prop: FnProp, doms: Vec<Interval<i32>>,\n\n before: SKleene, after: SKleene,\n\n delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool) where\n\n P: PropagatorConcept<VStoreFD, FDEvent>,\n\n FnProp: FnOnce(Vec<FDVar>) -> P\n\n {\n\n let mut vstore = VStoreFD::empty();\n\n let vars = doms.into_iter()\n\n .map(|d| Box::new(vstore.alloc(d)) as Var<VStoreFD>)\n\n .collect();\n\n let propagator = make_prop(vars);\n\n test_propagation(test_num, propagator, &mut vstore, before, after, delta_expected, propagate_success);\n\n }\n\n}\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 50, "score": 78487.9768337926 }, { "content": " consume_delta(vstore, delta_expected);\n\n }\n\n assert_eq!(prop.is_subsumed(vstore), after);\n\n }\n\n\n\n pub fn binary_propagator_test<P, FnProp>(test_num: u32, make_prop: FnProp, x: Interval<i32>, y: Interval<i32>,\n\n before: SKleene, after: SKleene,\n\n delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool) where\n\n P: PropagatorConcept<VStoreFD, FDEvent>,\n\n FnProp: FnOnce(FDVar, FDVar) -> P\n\n {\n\n let mut vstore = VStoreFD::empty();\n\n let x = Box::new(vstore.alloc(x)) as Var<VStoreFD>;\n\n let y = Box::new(vstore.alloc(y)) as Var<VStoreFD>;\n\n let propagator = make_prop(x, y);\n\n test_propagation(test_num, propagator, &mut vstore, before, after, delta_expected, propagate_success);\n\n }\n\n\n\n pub fn trinary_propagator_test<P, FnProp>(test_num: u32, make_prop: FnProp,\n\n x: Interval<i32>, y: Interval<i32>, z: Interval<i32>,\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 51, "score": 78487.85635471188 }, { "content": "\n\n // pub fn test_properties<VStore>(test_num: u32, vstore: &mut VStore, mut propagator: Formula<VStore>) where\n\n // VStore: VStoreConcept + Clone\n\n // {\n\n // contracting(test_num, &mut vstore.clone(), propagator.bclone());\n\n // idempotent(test_num, &mut vstore.clone(), propagator.bclone());\n\n // }\n\n\n\n pub type FDVar = Var<VStoreFD>;\n\n\n\n pub fn test_propagation<P>(test_num: u32, mut prop: P, vstore: &mut VStoreFD,\n\n before: SKleene, after: SKleene,\n\n delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool) where\n\n P: PropagatorConcept<VStoreFD, FDEvent>\n\n {\n\n // test_properties(test_num, vstore, prop.bclone());\n\n println!(\"Test number {}\", test_num);\n\n assert_eq!(prop.is_subsumed(vstore), before);\n\n assert_eq!(prop.propagate(vstore), propagate_success);\n\n if propagate_success {\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 52, "score": 78486.86276746984 }, { "content": " // prop: &Formula<VStore>, before: &T, after: &T) -> String\n\n // {\n\n // format!(\"Test {}: {}\\n\\\n\n // \\tPropagator {:?}\\n\\\n\n // \\tBefore: {:?}\\n\\\n\n // \\tAfter: {:?}\",\n\n // test_num, msg, prop, before, after)\n\n // }\n\n\n\n // fn status_inclusion(s1: SKleene, s2: SKleene) -> bool {\n\n // match s1 {\n\n // True => s2 == True,\n\n // False => s2 == False,\n\n // Unknown => true\n\n // }\n\n // }\n\n\n\n // /// contracting: p(d) ⊆ d for any domain d\n\n // fn contracting<VStore>(test_num: u32, vstore: &mut VStore, mut propagator: Formula<VStore>) where\n\n // VStore: VStoreConcept + Clone + Subset\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 53, "score": 78483.96451747653 }, { "content": "pub mod cumulative;\n\npub mod all_equal;\n\n\n\npub use propagators::cmp::*;\n\npub use propagators::distinct::*;\n\npub use propagators::all_equal::*;\n\n\n\n#[cfg(test)]\n\npub mod test\n\n{\n\n use trilean::SKleene;\n\n use propagation::*;\n\n use gcollections::ops::*;\n\n use concept::*;\n\n use variable::VStoreFD;\n\n use propagation::events::*;\n\n use interval::interval::*;\n\n use variable::store::test::consume_delta;\n\n\n\n // fn error_msg<T: Debug, VStore>(test_num: u32, msg: &str,\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 54, "score": 78482.90911992763 }, { "content": " // let prop_status = propagator.propagate(vstore);\n\n // let d1 = vstore.clone();\n\n // let d1_status = propagator.is_subsumed(vstore);\n\n // let prop_status2 = propagator.propagate(vstore);\n\n // let d2_status = propagator.is_subsumed(vstore);\n\n // let err1 = error_msg(test_num, \"Propagator is not idempotent.\", &propagator, &d1, &vstore);\n\n // assert!(d1 == vstore.clone() && prop_status == prop_status2 && d1_status == d2_status, err1);\n\n // }\n\n\n\n // // /// It is monotonic if and only if for any two domains d1 and d2, d1 ⊆ d2 implies p(d1) ⊆ p(d2).\n\n // // fn monotonic<VStore>(test_num: u32, vstore1: &mut VStore, vstore2: &mut VStore,\n\n // // mut propagator: Formula<VStore>) where\n\n // // VStore: VStoreConcept + Clone\n\n // // {}\n\n\n\n // // /// sound: for any domain d ∈ Dom and any assignment a ∈ Asn, if {a} ⊆ d, then p({a}) ⊆ p(d)\n\n // // fn sound<VStore>(test_num: u32, assignment: &mut VStore, vstore: &mut VStore,\n\n // // mut propagator: Formula<VStore>) where\n\n // // VStore: VStoreConcept + Clone\n\n // // {}\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 55, "score": 78477.38737236295 }, { "content": "pub mod reactors;\n\npub mod scheduler;\n\npub mod schedulers;\n\npub mod events;\n\npub mod store;\n\npub mod ops;\n\npub mod concept;\n\n\n\npub use propagation::reactor::Reactor;\n\npub use propagation::scheduler::Scheduler;\n\npub use propagation::ops::*;\n\npub use propagation::concept::*;\n\n\n\npub type CStoreFD<VStore> =\n\n store::Store<VStore, events::FDEvent, reactors::IndexedDeps, schedulers::RelaxedFifo>;\n", "file_path": "src/libpcp/propagation/mod.rs", "rank": 56, "score": 78476.96251467642 }, { "content": " // {\n\n // let d1 = vstore.clone();\n\n // let d1_status = propagator.is_subsumed(vstore);\n\n // let prop_status = propagator.propagate(vstore);\n\n // let d2_status = propagator.is_subsumed(vstore);\n\n // let err1 = error_msg(test_num, \"Propagator is not contracting.\", &propagator, &d1, &vstore);\n\n // assert!(vstore.is_subset(&d1), err1);\n\n // let err2 = error_msg(test_num, \"Propagator status is not monotonic.\", &propagator, &d1_status, &d2_status);\n\n // assert!(status_inclusion(d1_status, d2_status), err2);\n\n // if prop_status == false {\n\n // let err3 = error_msg(test_num, \"Propagator is not monotonic: the propagation failed but the status is not `False`.\",\n\n // &propagator, &d1_status, &d2_status);\n\n // assert!(d2_status == False, err3);\n\n // }\n\n // }\n\n\n\n // /// A propagator p is idempotent if and only if for all domains d, p(p(d)) = p(d).\n\n // fn idempotent<VStore>(test_num: u32, vstore: &mut VStore, mut propagator: Formula<VStore>) where\n\n // VStore: VStoreConcept + Clone + Eq\n\n // {\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 57, "score": 78473.87796004635 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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//! Propagation is a set of algorithmic components to verify the consistency of a constraint conjunction, called the *constraints store*.\n\n//!\n\n//! The constraints store is parametrized by the type of the variables store to keep both concrete implementation independents. Stores are stacked in a hierarchical manner and they communicate only from top to bottom; the variables store is not aware of the constraints store.\n\n\n\n\n\npub mod reactor;\n", "file_path": "src/libpcp/propagation/mod.rs", "rank": 58, "score": 78456.05057670208 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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//! Propagators are implementations of constraints, a single constraint can be realized by different propagators.\n\n//!\n\n//! We keep the propagator implementations generic over domains implementing specific operations (e.g. intersection or union). Propagators are also implemented to work on variable views, you can always obtain a view from a variable by using the `Identity` view.\n\n\n\npub mod cmp;\n\npub mod distinct;\n", "file_path": "src/libpcp/propagators/mod.rs", "rank": 59, "score": 78455.87910794937 }, { "content": " self.propagators[indexes[idx]].display(model);\n\n if idx < indexes.len() - 1 {\n\n print!(\" /\\\\ \\n{:>width$} \", \"\", width=header_width);\n\n }\n\n idx += 1;\n\n }\n\n println!();\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> DisplayStateful<(Model, VStore)> for Store<VStore, Event, R, S>\n\n{\n\n fn display(&self, &(ref model, ref vstore): &(Model, VStore)) {\n\n let mut subsumed = vec![];\n\n let mut unknown = vec![];\n\n let mut unsatisfiable = vec![];\n\n for (i, p) in self.propagators.iter().enumerate() {\n\n match p.is_subsumed(&vstore) {\n\n False => unsatisfiable.push(i),\n\n True => subsumed.push(i),\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 60, "score": 78384.0896871646 }, { "content": "use propagation::Reactor;\n\nuse propagation::Scheduler;\n\nuse propagation::concept::*;\n\nuse propagation::ops::*;\n\nuse variable::ops::*;\n\nuse gcollections::kind::*;\n\nuse gcollections::ops::*;\n\nuse std::ops::{Index, IndexMut};\n\nuse bit_set::BitSet;\n\n\n\n#[derive(Debug)]\n\npub struct Store<VStore, Event, Reactor, Scheduler>\n\n{\n\n propagators: Vec<Box<dyn PropagatorConcept<VStore, Event> + 'static>>,\n\n active: BitSet,\n\n reactor: Reactor,\n\n scheduler: Scheduler\n\n}\n\n\n\nimpl<VStore, Event, R, S> Empty for Store<VStore, Event, R, S> where\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 61, "score": 78382.38011997839 }, { "content": "\n\n fn restore(mut self, label: Self::Label) -> Self::State {\n\n self.cstore.propagators.truncate(label.0);\n\n self.cstore.active = label.1;\n\n self.cstore\n\n }\n\n}\n\n\n\n// #[cfg(test)]\n\n// mod test {\n\n// use kernel::*;\n\n// use trilean::SKleene::*;\n\n// use variable::VStoreFD;\n\n// use propagation::*;\n\n// use propagators::cmp::*;\n\n// use propagators::distinct::*;\n\n// use term::addition::Addition;\n\n// use interval::interval::*;\n\n// use interval::ops::*;\n\n// use gcollections::ops::*;\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 62, "score": 78381.294101438 }, { "content": "\n\n// type VStore = VStoreFD;\n\n// type CStore = CStoreFD<VStore>;\n\n\n\n// #[test]\n\n// fn basic_test() {\n\n// let variables: &mut VStore = &mut VStore::empty();\n\n// let mut constraints: CStore = CStore::empty();\n\n\n\n// assert_eq!(constraints.consistency(variables), True);\n\n\n\n// let var1 = variables.alloc(Interval::new(1,4));\n\n// let var2 = variables.alloc(Interval::new(1,4));\n\n// let var3 = variables.alloc(Interval::new(1,1));\n\n\n\n// assert_eq!(constraints.consistency(variables), True);\n\n\n\n// constraints.alloc(Box::new(XLessY::new(var1.clone(), var2)));\n\n// assert_eq!(constraints.consistency(variables), Unknown);\n\n\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 63, "score": 78379.3374369244 }, { "content": "// constraints.alloc(Box::new(XEqY::new(var1, var3)));\n\n// assert_eq!(constraints.consistency(variables), True);\n\n// }\n\n\n\n// fn chained_lt(n: usize, expect: SKleene) {\n\n// // X1 < X2 < X3 < ... < XN, all in dom [1, 10]\n\n// let variables: &mut VStore = &mut VStore::empty();\n\n// let mut constraints: CStore = CStore::empty();\n\n// let mut vars = vec![];\n\n// for _ in 0..n {\n\n// vars.push(variables.alloc(Interval::new(1,10)));\n\n// }\n\n// for i in 0..n-1 {\n\n// constraints.alloc(Box::new(XLessY::new(vars[i].clone(), vars[i+1].clone())));\n\n// }\n\n// assert_eq!(constraints.consistency(variables), expect);\n\n// }\n\n\n\n// #[test]\n\n// fn chained_lt_tests() {\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 64, "score": 78378.52055232278 }, { "content": "// chained_lt(1, True);\n\n// chained_lt(2, Unknown);\n\n// chained_lt(5, Unknown);\n\n// chained_lt(9, Unknown);\n\n// chained_lt(10, True);\n\n// chained_lt(11, False);\n\n// }\n\n\n\n// #[test]\n\n// fn example_nqueens() {\n\n// nqueens(1, True);\n\n// nqueens(2, Unknown);\n\n// nqueens(3, Unknown);\n\n// nqueens(4, Unknown);\n\n// }\n\n\n\n// fn nqueens(n: usize, expect: SKleene) {\n\n// let variables: &mut VStore = &mut VStore::empty();\n\n// let mut constraints: CStore = CStore::empty();\n\n// let mut queens = vec![];\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 65, "score": 78377.37843459817 }, { "content": "{\n\n fn is_subsumed(&self, vstore: &VStore) -> SKleene {\n\n self.propagators.iter()\n\n .fold(True, |x,p| x.and(p.is_subsumed(vstore)))\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Consistency<VStore> for Store<VStore, Event, R, S> where\n\n VStore: Cardinality<Size=usize> + DrainDelta<Event>,\n\n Event: EventIndex,\n\n R: Reactor + Cardinality<Size=usize>,\n\n S: Scheduler\n\n{\n\n fn consistency(&mut self, vstore: &mut VStore) -> SKleene {\n\n self.prepare(vstore);\n\n let consistent = self.propagation_loop(vstore);\n\n if !consistent { False }\n\n else if self.reactor.is_empty() { True }\n\n else { Unknown }\n\n }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 66, "score": 78377.33001050842 }, { "content": " consistent = false;\n\n break;\n\n }\n\n self.react(vstore);\n\n }\n\n // self.react(vstore); // For bulk reaction.\n\n }\n\n consistent\n\n }\n\n\n\n fn propagate_one(&mut self, p_idx: usize, vstore: &mut VStore) -> bool {\n\n vstore.reset_changed();\n\n let subsumed = self.propagator_consistency(p_idx, vstore);\n\n match subsumed {\n\n False => return false,\n\n True => self.unlink_prop(p_idx),\n\n Unknown => self.reschedule_prop(p_idx, vstore)\n\n };\n\n true\n\n }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 67, "score": 78375.09143868226 }, { "content": " \"The propagator {:?} has a dependency to the variable {} which is not in the vstore (of size {}).\\n\\\n\n Hint: you should not manually create `Identity` struct, if you do make sure they contain relevant index to the variable vstore.\",\n\n self[p_idx], v, vstore.size()));\n\n self.reactor.subscribe(v, ev, p_idx);\n\n }\n\n }\n\n }\n\n\n\n fn init_scheduler(&mut self) {\n\n self.scheduler = Scheduler::new(self.propagators.len());\n\n for p_idx in self.active.iter() {\n\n self.scheduler.schedule(p_idx);\n\n }\n\n }\n\n\n\n fn propagation_loop(&mut self, vstore: &mut VStore) -> bool {\n\n let mut consistent = true;\n\n while !self.scheduler.is_empty() && consistent {\n\n while let Some(p_idx) = self.scheduler.pop() {\n\n if !self.propagate_one(p_idx, vstore) {\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 68, "score": 78373.64456515163 }, { "content": " Unknown => unknown.push(i)\n\n };\n\n }\n\n self.display_constraints(&model, unsatisfiable, \"unsatisfiable:\");\n\n self.display_constraints(&model, subsumed, \"subsumed:\");\n\n self.display_constraints(&model, unknown, \"unknown:\");\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> DisplayStateful<Model> for Store<VStore, Event, R, S>\n\n{\n\n fn display(&self, model: &Model) {\n\n let mut i = 0;\n\n while i < self.propagators.len() {\n\n self.propagators[i].display(model);\n\n if i < self.propagators.len() - 1 {\n\n print!(\" /\\\\ \");\n\n }\n\n i += 1;\n\n }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 69, "score": 78373.64320026744 }, { "content": "{\n\n type Location = usize;\n\n}\n\n\n\nimpl<VStore, Event, R, S> Cardinality for Store<VStore, Event, R, S>\n\n{\n\n type Size = usize;\n\n\n\n fn size(&self) -> usize {\n\n self.propagators.len()\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Store<VStore, Event, R, S>\n\n{\n\n fn display_constraints(&self, model: &Model, indexes: Vec<usize>, header: &str) {\n\n let header_width = 15;\n\n print!(\"{:>width$} \", header, width=header_width);\n\n let mut idx = 0;\n\n while idx < indexes.len() {\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 70, "score": 78373.07226490919 }, { "content": " }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Store<VStore, Event, R, S> where\n\n VStore: Cardinality<Size=usize> + DrainDelta<Event>,\n\n Event: EventIndex,\n\n R: Reactor + Cardinality<Size=usize>,\n\n S: Scheduler\n\n{\n\n fn prepare(&mut self, vstore: &VStore) {\n\n self.init_reactor(vstore);\n\n self.init_scheduler();\n\n }\n\n\n\n fn init_reactor(&mut self, vstore: &VStore) {\n\n self.reactor = Reactor::new(vstore.size(), Event::size());\n\n for p_idx in self.active.iter() {\n\n let p_deps = self[p_idx].dependencies();\n\n for (v, ev) in p_deps {\n\n debug_assert!(v < vstore.size(), format!(\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 71, "score": 78368.90069269836 }, { "content": "}\n\n\n\nimpl<VStore, Event, R, S> Clone for Store<VStore, Event, R, S> where\n\n Event: EventIndex,\n\n R: Reactor,\n\n S: Scheduler\n\n{\n\n fn clone(&self) -> Self {\n\n let mut cstore = Store::empty();\n\n cstore.propagators = self.propagators.iter()\n\n .map(|p| p.bclone())\n\n .collect();\n\n cstore.active = self.active.clone();\n\n cstore\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Freeze for Store<VStore, Event, R, S> where\n\n Event: EventIndex,\n\n R: Reactor + Clone,\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 72, "score": 78367.97736614465 }, { "content": " S: Scheduler\n\n{\n\n fn new(cstore: Store<VStore, Event, R, S>) -> Self {\n\n FrozenStore {\n\n cstore: cstore\n\n }\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Snapshot for FrozenStore<VStore, Event, R, S> where\n\n Event: EventIndex,\n\n R: Reactor + Clone,\n\n S: Scheduler\n\n{\n\n type Label = (usize, BitSet);\n\n type State = Store<VStore, Event, R, S>;\n\n\n\n fn label(&mut self) -> Self::Label {\n\n (self.cstore.propagators.len(), self.cstore.active.clone())\n\n }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 73, "score": 78367.27990121445 }, { "content": "\n\n fn propagator_consistency(&mut self, p_idx: usize, vstore: &mut VStore) -> SKleene {\n\n if self[p_idx].propagate(vstore) {\n\n self[p_idx].is_subsumed(vstore)\n\n } else {\n\n False\n\n }\n\n }\n\n\n\n fn reschedule_prop(&mut self, p_idx: usize, vstore: &mut VStore) {\n\n if vstore.has_changed() {\n\n self.scheduler.schedule(p_idx);\n\n }\n\n }\n\n\n\n fn react(&mut self, vstore: &mut VStore) {\n\n for (v, ev) in vstore.drain_delta() {\n\n let reactions = self.reactor.react(v, ev);\n\n for p in reactions.into_iter() {\n\n self.scheduler.schedule(p);\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 74, "score": 78366.50262033909 }, { "content": "}\n\n\n\nimpl<VStore, Event, R, S> IndexMut<usize> for Store<VStore, Event, R, S>\n\n{\n\n fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut Self::Output {\n\n &mut self.propagators[index]\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Alloc for Store<VStore, Event, R, S>\n\n{\n\n fn alloc(&mut self, p: Self::Item) -> usize {\n\n let idx = self.propagators.len();\n\n self.propagators.push(p);\n\n self.active.insert(idx);\n\n idx\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Subsumption<VStore> for Store<VStore, Event, R, S>\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 75, "score": 78366.40465222436 }, { "content": " }\n\n }\n\n }\n\n\n\n fn unlink_prop(&mut self, p_idx: usize) {\n\n self.active.remove(p_idx);\n\n self.scheduler.unschedule(p_idx);\n\n let deps = self[p_idx].dependencies();\n\n for &(var, ev) in deps.iter() {\n\n self.reactor.unsubscribe(var, ev, p_idx)\n\n }\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Index<usize> for Store<VStore, Event, R, S>\n\n{\n\n type Output = Box<dyn PropagatorConcept<VStore, Event> + 'static>;\n\n fn index<'a>(&'a self, index: usize) -> &'a Self::Output {\n\n &self.propagators[index]\n\n }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 76, "score": 78366.17732137548 }, { "content": " S: Scheduler\n\n{\n\n type FrozenState = FrozenStore<VStore, Event, R, S>;\n\n fn freeze(self) -> Self::FrozenState\n\n {\n\n FrozenStore::new(self)\n\n }\n\n}\n\n\n\npub struct FrozenStore<VStore, Event, R, S> where\n\n Event: EventIndex,\n\n R: Reactor + Clone,\n\n S: Scheduler\n\n{\n\n cstore: Store<VStore, Event, R, S>\n\n}\n\n\n\nimpl<VStore, Event, R, S> FrozenStore<VStore, Event, R, S> where\n\n Event: EventIndex,\n\n R: Reactor + Clone,\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 77, "score": 78363.44596227455 }, { "content": " Event: EventIndex,\n\n R: Reactor,\n\n S: Scheduler\n\n{\n\n fn empty() -> Store<VStore, Event, R, S> {\n\n Store {\n\n propagators: vec![],\n\n active: BitSet::new(),\n\n reactor: Reactor::new(0,0),\n\n scheduler: Scheduler::new(0)\n\n }\n\n }\n\n}\n\n\n\nimpl<VStore, Event, R, S> Collection for Store<VStore, Event, R, S>\n\n{\n\n type Item = Box<dyn PropagatorConcept<VStore, Event>>;\n\n}\n\n\n\nimpl<VStore, Event, R, S> AssociativeCollection for Store<VStore, Event, R, S>\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 78, "score": 78363.29518365793 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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//! Represents the *constraint store* which is a conjunction of constraints, it also comes with an algorithm checking the consistency of the store. It is not a complete method for solving a constraint problem because the output can be `Unknown`. A complete solver is obtained using a search algorithm on top of the consistency algorithm.\n\n\n\nuse kernel::*;\n\nuse trilean::SKleene;\n\nuse trilean::SKleene::*;\n\nuse model::*;\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 79, "score": 78359.57570442048 }, { "content": "// // 2 queens can't share the same line.\n\n// for _ in 0..n {\n\n// queens.push(variables.alloc((1, n as i32).to_interval()));\n\n// }\n\n// for i in 0..n-1 {\n\n// for j in i + 1..n {\n\n// // 2 queens can't share the same diagonal.\n\n// let q1 = (i + 1) as i32;\n\n// let q2 = (j + 1) as i32;\n\n// // Xi + i != Xj + j\n\n// constraints.alloc(Box::new(XNeqY::new(Addition::new(queens[i], q1), Addition::new(queens[j], q2))));\n\n// // constraints.alloc(XNeqY::new(queens[i].clone(), Addition::new(queens[j].clone(), q2 - q1)));\n\n// // Xi - i != Xj - j\n\n// constraints.alloc(Box::new(XNeqY::new(queens[i].clone(), Addition::new(queens[j].clone(), -q2 + q1))));\n\n// }\n\n// }\n\n// // 2 queens can't share the same column.\n\n// constraints.alloc(Box::new(Distinct::new(queens)));\n\n// assert_eq!(constraints.consistency(variables), expect);\n\n// }\n\n// }\n", "file_path": "src/libpcp/propagation/store.rs", "rank": 80, "score": 78356.35045177056 }, { "content": "pub mod x_eq_y_mul_z;\n\n\n\nuse term::*;\n\nuse gcollections::*;\n\nuse concept::*;\n\npub use propagators::cmp::x_eq_y_plus_z::XEqYPlusZ;\n\npub use propagators::cmp::x_less_y_plus_z::XLessYPlusZ;\n\npub use propagators::cmp::x_greater_y_plus_z::XGreaterYPlusZ;\n\npub use propagators::cmp::x_eq_y_mul_z::XEqYMulZ;\n\npub use propagators::cmp::x_less_y::XLessY;\n\npub use propagators::cmp::x_eq_y::XEqY;\n\npub use propagators::cmp::x_neq_y::XNeqY;\n\n\n\npub type XGreaterY<VStore> = XLessY<VStore>;\n\npub type XGreaterEqY<VStore> = XLessY<VStore>;\n\npub type XLessEqY<VStore> = XLessY<VStore>;\n\npub type XGreaterEqYPlusZ<VStore> = XGreaterYPlusZ<VStore>;\n\npub type XLessEqYPlusZ<VStore> = XLessYPlusZ<VStore>;\n\n\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 81, "score": 76501.03681366726 }, { "content": "// x_geq_y_test_one(6, dom11_20, dom0_10, True, True, vec![], true);\n\n// x_geq_y_test_one(7, dom9_9, dom0_10, Unknown, True, vec![(1, Bound)], true);\n\n// }\n\n\n\n// fn x_geq_y_test_one(test_num: u32, x: Interval<i32>, y: Interval<i32>,\n\n// before: SKleene, after: SKleene,\n\n// delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool)\n\n// {\n\n// binary_propagator_test(test_num, x_geq_y::<_,_,i32>, x, y, before, after, delta_expected, propagate_success);\n\n// }\n\n// }\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 82, "score": 76498.67361383697 }, { "content": "// before: SKleene, after: SKleene,\n\n// delta_expected: Vec<(usize, FDEvent)>, propagate_success: bool)\n\n// {\n\n// binary_propagator_test(test_num, x_greater_y, x, y, before, after, delta_expected, propagate_success);\n\n// }\n\n\n\n// #[test]\n\n// fn x_geq_y_test() {\n\n// let dom0_10 = (0,10).to_interval();\n\n// let dom10_20 = (10,20).to_interval();\n\n// let dom10_11 = (10,11).to_interval();\n\n// let dom5_15 = (5,15).to_interval();\n\n// let dom11_20 = (11,20).to_interval();\n\n// let dom9_9 = (9,9).to_interval();\n\n\n\n// x_geq_y_test_one(1, dom0_10, dom0_10, Unknown, Unknown, vec![], true);\n\n// x_geq_y_test_one(2, dom0_10, dom10_20, Unknown, True, vec![(0, Assignment), (1, Assignment)], true);\n\n// x_geq_y_test_one(3, dom5_15, dom10_20, Unknown, Unknown, vec![(0, Bound), (1, Bound)], true);\n\n// x_geq_y_test_one(4, dom10_11, dom10_11, Unknown, Unknown, vec![], true);\n\n// x_geq_y_test_one(5, dom5_15, dom0_10, Unknown, Unknown, vec![], true);\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 83, "score": 76495.77719373611 }, { "content": "// fn x_greater_y_test() {\n\n// let dom0_10 = (0,10).to_interval();\n\n// let dom10_20 = (10,20).to_interval();\n\n// let dom10_11 = (10,11).to_interval();\n\n// let dom5_15 = (5,15).to_interval();\n\n// let dom5_11 = (5,11).to_interval();\n\n// let dom11_20 = (11,20).to_interval();\n\n// let dom9_9 = (9,9).to_interval();\n\n\n\n// x_greater_y_test_one(1, dom0_10, dom0_10, Unknown, Unknown, vec![(0, Bound), (1, Bound)], true);\n\n// x_greater_y_test_one(2, dom0_10, dom10_20, False, False, vec![], false);\n\n// x_greater_y_test_one(3, dom5_15, dom10_20, Unknown, Unknown, vec![(0, Bound), (1, Bound)], true);\n\n// x_greater_y_test_one(4, dom5_11, dom10_20, Unknown, True, vec![(0, Assignment), (1, Assignment)], true);\n\n// x_greater_y_test_one(5, dom10_11, dom10_11, Unknown, True, vec![(0, Assignment), (1, Assignment)], true);\n\n// x_greater_y_test_one(6, dom5_15, dom0_10, Unknown, Unknown, vec![], true);\n\n// x_greater_y_test_one(7, dom11_20, dom0_10, True, True, vec![], true);\n\n// x_greater_y_test_one(8, dom9_9, dom0_10, Unknown, True, vec![(1, Bound)], true);\n\n// }\n\n\n\n// fn x_greater_y_test_one(test_num: u32, x: Interval<i32>, y: Interval<i32>,\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 84, "score": 76493.61641805118 }, { "content": " fn size() -> usize {\n\n Inner.to_index() + 1\n\n }\n\n}\n\n\n\nimpl<Domain, Bound> MonotonicEvent<Domain> for FDEvent where\n\n Domain: Subset + Cardinality + Bounded + Collection<Item=Bound>,\n\n Bound: PartialEq + Eq\n\n{\n\n fn new(little: &Domain, big: &Domain) -> Option<Self>\n\n {\n\n assert!(little.is_subset(big),\n\n \"Events are computed on the difference between `little` and `big`.\\\n\n So `little` must be a subset of `big`.\");\n\n if little.size() != big.size() {\n\n let ev =\n\n if little.is_singleton() { Assignment }\n\n else if little.lower() != big.lower() ||\n\n little.upper() != big.upper() { Bound }\n\n else { Inner };\n\n Some(ev)\n\n } else {\n\n None\n\n }\n\n }\n\n}\n", "file_path": "src/libpcp/propagation/events/mod.rs", "rank": 85, "score": 76484.01092355348 }, { "content": "\n\n/// Failure or Nothing events are absents on purpose because they are not events that propagators should subscribe to. If a failure occurs, it's over. If nothing occurs, we don't care.\n\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]\n\npub enum FDEvent {\n\n Assignment = 0,\n\n Bound = 1,\n\n Inner = 2\n\n}\n\n\n\nimpl Merge for FDEvent {\n\n fn merge(e: FDEvent, f: FDEvent) -> FDEvent {\n\n min(e, f)\n\n }\n\n}\n\n\n\nimpl EventIndex for FDEvent {\n\n fn to_index(self) -> usize {\n\n self as usize\n\n }\n\n\n", "file_path": "src/libpcp/propagation/events/mod.rs", "rank": 86, "score": 76481.12584511282 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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 kernel::Merge;\n\nuse kernel::event::*;\n\nuse propagation::events::FDEvent::*;\n\nuse gcollections::kind::*;\n\nuse gcollections::ops::*;\n\nuse std::cmp::min;\n", "file_path": "src/libpcp/propagation/events/mod.rs", "rank": 87, "score": 76480.27920104006 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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\npub mod relaxed_fifo;\n\npub use propagation::schedulers::relaxed_fifo::RelaxedFifo;\n", "file_path": "src/libpcp/propagation/schedulers/mod.rs", "rank": 88, "score": 76478.50035436443 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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\npub mod indexed_deps;\n\n\n\npub use propagation::reactors::indexed_deps::IndexedDeps;\n", "file_path": "src/libpcp/propagation/reactors/mod.rs", "rank": 89, "score": 76478.50035436443 }, { "content": "// Copyright 2015 Pierre Talbot (IRCAM)\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\npub mod x_less_y;\n\npub mod x_eq_y;\n\npub mod x_neq_y;\n\npub mod x_greater_y_plus_z;\n\npub mod x_less_y_plus_z;\n\npub mod x_eq_y_plus_z;\n", "file_path": "src/libpcp/propagators/cmp/mod.rs", "rank": 90, "score": 76477.34241112562 }, { "content": "fn main() {\n\n nqueens(8);\n\n// let robot = robot::RobotScheduling::new(3, 500).solve();\n\n// println!(\"{}\", robot);\n\n\n\n// !!! Ok with 2 robot. doesn't stop with 3 robot.\n\n println!(\"Solve robot2 domaine 400\");\n\n let test1 = robot2::RobotScheduling::new_test1(2, 400, 10, 25, 240, 25).solve();\n\n println!(\"{}\", test1);\n\n\n\n// //ok bonne réponses. Le wait est bien intercallé\n\n println!(\"Solve robot2 domaine 400\");\n\n let test2 = robot2::RobotScheduling::new_test2(2, 400, 10, 25, 240, 25, 5).solve();\n\n println!(\"{}\", test2);\n\n\n\n// Non satisfi\n\n println!(\"Solve robot1 domaine 36\");\n\n let test1 = robot2::RobotScheduling::new_test1(2, 37, 1, 3, 24, 3).solve(); //non satisfauisable\n\n println!(\"{}\", test1);\n\n\n", "file_path": "example/src/main.rs", "rank": 91, "score": 65450.42149253573 }, { "content": "fn parse<'cx>(cx: &'cx rust::ExtCtxt,\n\n tts: Vec<rust::TokenTree>) -> Box<rust::MacResult + 'cx>\n\n{\n\n let mut compiler = code_gen::CodeGenerator::new(cx);\n\n ama::compile_anonymous_macro(cx, tts, &mut compiler)\n\n}\n", "file_path": "lang/src/lib.rs", "rank": 92, "score": 53758.843635464524 }, { "content": "pub trait Iterable: Collection\n\n{\n\n fn iter<'a>(&'a self) -> slice::Iter<'a, Self::Item>;\n\n}\n\n\n", "file_path": "src/libpcp/variable/ops.rs", "rank": 93, "score": 51344.884690435596 }, { "content": "pub trait ViewDependencies<Event>\n\n{\n\n fn dependencies(&self, event: Event) -> Vec<(usize, Event)>;\n\n}\n\n\n\nimpl<Store, R> StoreMonotonicUpdate<Store> for Box<R> where\n\n R: StoreMonotonicUpdate<Store>,\n\n Store: Collection\n\n{\n\n fn update(&mut self, store: &mut Store, value: Store::Item) -> bool {\n\n self.deref_mut().update(store, value)\n\n }\n\n}\n\n\n\nimpl<Store, R> StoreRead<Store> for Box<R> where\n\n R: StoreRead<Store>,\n\n Store: Collection\n\n{\n\n fn read(&self, store: &Store) -> Store::Item {\n\n self.deref().read(store)\n", "file_path": "src/libpcp/term/ops.rs", "rank": 94, "score": 50472.4060917215 }, { "content": "pub trait DrainDelta<Event>\n\n{\n\n fn drain_delta<'a>(&'a mut self) -> Drain<'a, Event>;\n\n fn has_changed(&self) -> bool;\n\n fn reset_changed(&mut self);\n\n}\n\n\n", "file_path": "src/libpcp/variable/ops.rs", "rank": 95, "score": 50472.4060917215 }, { "content": "pub trait TrailRestoration : Collection\n\n{\n\n type Mark;\n\n fn commit(&mut self) {}\n\n fn mark(&mut self) -> Self::Mark;\n\n fn undo(&mut self, mark: Self::Mark, memory: &mut Vec<Self::Item>);\n\n}\n", "file_path": "src/libpcp/variable/memory/ops.rs", "rank": 96, "score": 49639.85972538369 }, { "content": "pub trait MonotonicUpdate: AssociativeCollection\n\n{\n\n fn update(&mut self, loc: &Self::Location, value: Self::Item) -> bool;\n\n}\n", "file_path": "src/libpcp/variable/ops.rs", "rank": 97, "score": 49639.85972538369 }, { "content": "pub trait SearchMonitor<Space: Freeze> {\n\n fn on_node(&mut self, space: &Space, status: &Status<Space>) {\n\n self.dispatch_node(space, status)\n\n }\n\n\n\n fn dispatch_node(&mut self, space: &Space, status: &Status<Space>)\n\n {\n\n match status {\n\n &Satisfiable => self.on_solution(space),\n\n &Unsatisfiable => self.on_failure(space),\n\n &EndOfSearch => self.on_end_of_search(space),\n\n &Unknown(ref b) if b.is_empty() => self.on_prune(space),\n\n &Unknown(_) => self.on_unknown(space)\n\n }\n\n }\n\n\n\n fn on_solution(&mut self, _space: &Space) {}\n\n fn on_failure(&mut self, _space: &Space) {}\n\n fn on_end_of_search(&mut self, _space: &Space) {}\n\n fn on_prune(&mut self, _space: &Space) {}\n", "file_path": "src/libpcp/search/monitor.rs", "rank": 98, "score": 48853.77298726454 }, { "content": "pub trait TrailVariable : AssociativeCollection\n\n{\n\n fn trail_variable(&mut self, loc: Self::Location, value: Self::Item);\n\n}\n\n\n", "file_path": "src/libpcp/variable/memory/ops.rs", "rank": 99, "score": 48844.56545366809 } ]
Rust
src/state.rs
macfadyen/sailfish
44752a6769a2a7566a90dd9c8df21d4e2c49d720
use crate::cmdline::CommandLine; use crate::error; use crate::{Mesh, Patch, PointMass, Setup}; use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::io::Write; #[derive(Debug, Clone, Copy)] pub enum Recurrence { Linear(f64), Log(f64), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RecurringTask { pub number: u64, pub last_time: Option<f64>, } impl Default for RecurringTask { fn default() -> Self { Self::new() } } impl RecurringTask { pub fn new() -> Self { Self { number: 0, last_time: None, } } pub fn next(&mut self, current_time: f64, recurrence: Recurrence) { self.last_time = Some(self.next_time(current_time, recurrence)); self.number += 1; } pub fn next_time(&self, current_time: f64, recurrence: Recurrence) -> f64 { if let Some(last_time) = self.last_time { match recurrence { Recurrence::Linear(interval) => last_time + interval, Recurrence::Log(multiplier) => last_time * (1.0 + multiplier), } } else { current_time } } pub fn is_due(&self, current_time: f64, recurrence: Recurrence) -> bool { current_time >= self.next_time(current_time, recurrence) } } #[derive(Clone, serde::Serialize, serde::Deserialize)] pub struct State { pub command_line: CommandLine, pub restart_file: Option<String>, pub mesh: Mesh, pub setup_name: String, pub parameters: String, pub primitive: Vec<f64>, pub primitive_patches: Vec<Patch>, pub time: f64, pub iteration: u64, pub checkpoint: RecurringTask, #[serde(default)] pub time_series: RecurringTask, #[serde(default)] pub masses: Vec<PointMass>, #[serde(default)] pub time_series_data: Vec<Vec<f64>>, #[serde(default)] pub version: String, } impl State { pub fn from_checkpoint( filename: &str, new_parameters: &str, command_line: &CommandLine, ) -> Result<State, error::Error> { println!("read {}", filename); let mut f = File::open(filename).map_err(error::Error::IOError)?; let mut bytes = Vec::new(); f.read_to_end(&mut bytes).map_err(error::Error::IOError)?; let mut state: State = rmp_serde::from_read_ref(&bytes) .map_err(|e| error::Error::InvalidCheckpoint(format!("{}", e)))?; if !state.parameters.is_empty() && !new_parameters.is_empty() { state.parameters += ":"; } state.parameters += new_parameters; state.restart_file = Some(filename.to_string()); state.command_line.update(&command_line)?; state.version = crate::sailfish_version(); Ok(state) } pub fn set_primitive(&mut self, primitive: Vec<f64>) { assert!( primitive.len() == self.primitive.len(), "new and old primitive array sizes must match" ); self.primitive = primitive; } pub fn write_checkpoint( &mut self, setup: &dyn Setup, outdir: &str, ) -> Result<(), error::Error> { let filename = format!("{}/chkpt.{:04}.sf", outdir, self.checkpoint.number); println!("write {}", filename); self.masses = setup.masses(self.time).to_vec(); self.parameters = setup.model_parameter_string(); self.checkpoint .next(self.time, self.command_line.checkpoint_rule(setup)); create_dir_all(outdir).map_err(error::Error::IOError)?; let bytes = rmp_serde::to_vec_named(self).unwrap(); let mut file = File::create(&filename).map_err(error::Error::IOError)?; file.write_all(&bytes).map_err(error::Error::IOError)?; Ok(()) } pub fn upsample(mut self) -> Self { println!("upsample grid resolution"); let mut mesh = match self.mesh { Mesh::Structured(ref mut mesh) => mesh, _ => panic!("can only upsample structured mesh"), }; for patch in &mut self.primitive_patches { patch.upsample_mut() } mesh.ni *= 2; mesh.nj *= 2; mesh.dx *= 0.5; mesh.dy *= 0.5; self } }
use crate::cmdline::CommandLine; use crate::error; use crate::{Mesh, Patch, PointMass, Setup}; use std::fs::{create_dir_all, File}; use std::io::prelude::*; use std::io::Write; #[derive(Debug, Clone, Copy)] pub enum Recurrence { Linear(f64), Log(f64), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RecurringTask { pub number: u64, pub last_time: Option<f64>, } impl Default for RecurringTask { fn default() -> Self { Self::new() } } impl RecurringTask { pub fn new() -> Self { Self { number: 0, last_time: None, } } pub fn next(&mut self, current_time: f64, recurrence: Recurrence) { self.last_time = Some(self.next_time(current_time, recurrence)); self.number += 1; } pub fn next_time(&self, current_time: f64, recurrence: Recurrence) -> f64 { if let Some(last_time) = self.last_time { match recurrence { Recurrence::Linear(interval) => last_time + interval, Recurrence::Log(multiplier) => last_time * (1.0 + multiplier), } } else { current_time } } pub fn is_due(&self, current_time: f64, recurrence: Recurrence) -> bool { current_time >= self.next_time(current_time, recurrence) } } #[derive(Clone, serde::Serialize, serde::Deserialize)] pub struct State { pub command_line: CommandLine, pub restart_file: Option<String>, pub mesh: Mesh, pub setup_name: String, pub parameters: String, pub primitive: Vec<f64>, pub primitive_patches: Vec<Patch>, pub time: f64, pub iteration: u64, pub checkpoint: RecurringTask, #[serde(default)] pub time_series: RecurringTask, #[serde(default)] pub masses: Vec<PointMass>, #[serde(default)] pub time_series_data: Vec<Vec<f64>>, #[serde(default)] pub version: String, } impl State { pub fn from_checkpoint( filename: &str, new_parameters: &str, command_line: &CommandLine, ) -> Result<State, error::Error> { println!("read {}", filename); let mut f = File::open(filename).map_err(error::Error::IOError)?; let mut bytes = Vec::new(); f.read_to_end(&mut bytes).map_err(error::Error::IOErr
pub fn set_primitive(&mut self, primitive: Vec<f64>) { assert!( primitive.len() == self.primitive.len(), "new and old primitive array sizes must match" ); self.primitive = primitive; } pub fn write_checkpoint( &mut self, setup: &dyn Setup, outdir: &str, ) -> Result<(), error::Error> { let filename = format!("{}/chkpt.{:04}.sf", outdir, self.checkpoint.number); println!("write {}", filename); self.masses = setup.masses(self.time).to_vec(); self.parameters = setup.model_parameter_string(); self.checkpoint .next(self.time, self.command_line.checkpoint_rule(setup)); create_dir_all(outdir).map_err(error::Error::IOError)?; let bytes = rmp_serde::to_vec_named(self).unwrap(); let mut file = File::create(&filename).map_err(error::Error::IOError)?; file.write_all(&bytes).map_err(error::Error::IOError)?; Ok(()) } pub fn upsample(mut self) -> Self { println!("upsample grid resolution"); let mut mesh = match self.mesh { Mesh::Structured(ref mut mesh) => mesh, _ => panic!("can only upsample structured mesh"), }; for patch in &mut self.primitive_patches { patch.upsample_mut() } mesh.ni *= 2; mesh.nj *= 2; mesh.dx *= 0.5; mesh.dy *= 0.5; self } }
or)?; let mut state: State = rmp_serde::from_read_ref(&bytes) .map_err(|e| error::Error::InvalidCheckpoint(format!("{}", e)))?; if !state.parameters.is_empty() && !new_parameters.is_empty() { state.parameters += ":"; } state.parameters += new_parameters; state.restart_file = Some(filename.to_string()); state.command_line.update(&command_line)?; state.version = crate::sailfish_version(); Ok(state) }
function_block-function_prefixed
[ { "content": "/// Tries to construct a dynamic setup from a string key and model parameter\n\n/// string.\n\n///\n\n/// The result is put under `Arc` so it can be attached to solver instances\n\n/// and shared safely between threads. If no setup matches the given name, a\n\n/// `PrintUserInformation` error is returned listing the available setups. If\n\n/// a setup is found, but has an invalid configuration, the `InvalidSetup`\n\n/// error is returned here.\n\npub fn make_setup(setup_name: &str, parameters: &str) -> Result<Arc<dyn Setup>, error::Error> {\n\n setups()\n\n .into_iter()\n\n .find(|&(n, _)| n == setup_name)\n\n .map(|(_, f)| f(parameters))\n\n .ok_or_else(possible_setups_info)?\n\n}\n\n\n\n/// Classic 1D shocktube problem for the energy-conserving Euler equation\n\npub struct Shocktube;\n\n\n\nimpl FromStr for Shocktube {\n\n type Err = error::Error;\n\n fn from_str(parameters: &str) -> Result<Self, Self::Err> {\n\n if parameters.is_empty() {\n\n Ok(Self)\n\n } else {\n\n Err(InvalidSetup(\"setup does not take any parameters\".into()))\n\n }\n\n }\n", "file_path": "src/setups.rs", "rank": 0, "score": 217271.81840880762 }, { "content": "/// Returns the current version number (should be consistent with Cargo\n\n/// meta-data).\n\npub fn sailfish_version() -> String {\n\n \"sailfish version 0.3.5\".to_owned()\n\n}\n\n\n\n/// Execution modes. These modes are referenced by Rust driver code, and by\n\n/// solver code written in C.\n\n#[repr(C)]\n\n#[derive(Debug, Clone, Copy)]\n\npub enum ExecutionMode {\n\n /// Execution is either single core, or parallelized using thread-pool\n\n /// over a patch-based domain, without the help of OpenMP.\n\n CPU,\n\n /// Execution is parallelized in C code via OpenMP. If the domain is\n\n /// decomposed into patches, the patches are processed sequentially.\n\n OMP,\n\n /// Solver execution is performed on a GPU device, if available.\n\n GPU,\n\n}\n\n\n\n/// Description of sink model to model accretion onto a gravitating object.\n", "file_path": "src/lib.rs", "rank": 1, "score": 214750.41967198806 }, { "content": "/// Returns an iterator over all the devices on this system.\n\npub fn all_devices() -> impl Iterator<Item = Device> + Clone {\n\n cfg_if! {\n\n if #[cfg(feature = \"gpu\")] {\n\n (0..unsafe { gpu_get_device_count() }).map(Device)\n\n } else {\n\n (0..0).map(Device)\n\n }\n\n }\n\n}\n\n\n", "file_path": "gpu_core/src/lib.rs", "rank": 2, "score": 214356.52790591866 }, { "content": "fn time_exec<F>(device: Option<i32>, mut f: F) -> std::time::Duration\n\nwhere\n\n F: FnMut(),\n\n{\n\n let start = std::time::Instant::now();\n\n f();\n\n\n\n cfg_if! {\n\n if #[cfg(feature = \"gpu\")] {\n\n gpu_core::Device::with_id(device.unwrap_or(0)).unwrap().synchronize();\n\n } else {\n\n std::convert::identity(device); // black-box\n\n }\n\n }\n\n start.elapsed()\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 3, "score": 196528.07921260167 }, { "content": "/// Takes a string, and splits it into two parts, separated by the first\n\n/// instance of the given character. The first item in the pair is `Some`\n\n/// unless the input string is empty. The second item in the pair is `None` if\n\n/// `separator` is not found in the string.\n\npub fn split_pair(string: &str, separator: char) -> (Option<&str>, Option<&str>) {\n\n let mut a = string.splitn(2, separator);\n\n let n = a.next();\n\n let p = a.next();\n\n (n, p)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 4, "score": 194025.84651756042 }, { "content": "/// Attempts to interpret the given string as a directory and read its\n\n/// contents. If that succeeds, then returns the last entry in the directory,\n\n/// sorted alphabetically, which ends with `extension`. If no matching files\n\n/// are found or if `dir` was not a directory, then returns `None`.\n\npub fn last_in_dir_ending_with(dir: &str, extension: &str) -> Option<String> {\n\n if let Ok(entries) = std::fs::read_dir(dir) {\n\n return if let Ok(mut entries) = entries.collect::<Result<Vec<DirEntry>, _>>() {\n\n entries.retain(|e| e.file_name().to_str().unwrap().ends_with(extension));\n\n entries.sort_by_key(DirEntry::file_name);\n\n entries\n\n .last()\n\n .map(DirEntry::file_name)\n\n .map(OsString::into_string)\n\n .map(Result::ok)\n\n .flatten()\n\n } else {\n\n None\n\n }\n\n }\n\n None\n\n}\n", "file_path": "src/parse.rs", "rank": 5, "score": 193166.36938861746 }, { "content": "/// Executes the given closure on a GPU device if `device` is `Some`.\n\n/// Otherwise, the closure is just executed.\n\npub fn scope<T, F: FnMut() -> T>(device: Option<Device>, mut f: F) -> T {\n\n if let Some(device) = device {\n\n cfg_if! {\n\n if #[cfg(feature = \"gpu\")] {\n\n on_device(device.0, f)\n\n } else {\n\n panic!(\"gpu feature not enabled, requested device {:?}\", device)\n\n }\n\n }\n\n } else {\n\n f()\n\n }\n\n}\n\n\n", "file_path": "gpu_core/src/lib.rs", "rank": 6, "score": 190632.89328823244 }, { "content": "/// Returns whether the code has been compiled with GPU support\n\n/// (`feature=gpu`) either via CUDA or HIP.\n\npub fn compiled_with_gpu() -> bool {\n\n cfg_if! {\n\n if #[cfg(feature = \"gpu\")] {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n}\n", "file_path": "src/lib.rs", "rank": 7, "score": 175951.47663358419 }, { "content": "/// Returns whether the code has been compiled with OpenMP support,\n\n/// `feature=omp`.\n\npub fn compiled_with_omp() -> bool {\n\n cfg_if! {\n\n if #[cfg(feature = \"omp\")] {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/lib.rs", "rank": 8, "score": 175951.47663358419 }, { "content": "fn use_omp() -> bool {\n\n cfg_if! {\n\n if #[cfg(feature = \"omp\")] {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n}\n\n\n", "file_path": "build.rs", "rank": 9, "score": 172008.63894272846 }, { "content": "fn use_gpu() -> bool {\n\n cfg_if! {\n\n if #[cfg(feature = \"gpu\")] {\n\n true\n\n } else {\n\n false\n\n }\n\n }\n\n}\n\n\n", "file_path": "build.rs", "rank": 10, "score": 172008.63894272846 }, { "content": "/// Returns the parent directory for an absolute path string, or `None` if no\n\n/// parent directory exists. If the path is relative this function returns\n\n/// `Some(\".\")`.\n\npub fn parent_dir(path: &str) -> Option<&str> {\n\n Path::new(path)\n\n .parent()\n\n .and_then(Path::to_str)\n\n .map(|s| if s.is_empty() { \".\" } else { s })\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 11, "score": 166744.8279256693 }, { "content": "#[cfg(feature = \"gpu\")]\n\nfn on_device<T, F: FnMut() -> T>(device: i32, mut f: F) -> T {\n\n use std::ffi::CStr;\n\n let (result, error_str) = unsafe {\n\n let orig = gpu_get_device();\n\n gpu_set_device(device);\n\n let result = f();\n\n let error_str = gpu_get_last_error();\n\n let error_str = if error_str != std::ptr::null() {\n\n Some(CStr::from_ptr(error_str).to_str().unwrap().to_owned())\n\n } else {\n\n None\n\n };\n\n gpu_set_device(orig);\n\n (result, error_str)\n\n };\n\n if let Some(error_str) = error_str {\n\n panic!(\"{}\", error_str)\n\n } else {\n\n result\n\n }\n\n}\n", "file_path": "gpu_core/src/lib.rs", "rank": 12, "score": 163561.44406951044 }, { "content": "fn sorted_field(filename: &str, field: usize) -> Result<Vec<f64>> {\n\n let state = State::load(filename)?;\n\n let mut data = vec![];\n\n for patch in &state.primitive_patches {\n\n for b in patch.data.chunks_exact(8 * state.num_fields()?) {\n\n let b = &b[field * 8..(field + 1) * 8];\n\n let bytes = [b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]];\n\n let x = f64::from_le_bytes(bytes);\n\n if !x.is_finite() {\n\n anyhow::bail!(\"field contains nan or inf\")\n\n }\n\n data.push(x)\n\n }\n\n }\n\n data.sort_by(|a, b| a.partial_cmp(b).unwrap());\n\n Ok(data)\n\n}\n\n\n", "file_path": "sf_png/src/main.rs", "rank": 13, "score": 158317.46088252758 }, { "content": "fn setups() -> Vec<(&'static str, SetupFunction)> {\n\n vec![\n\n (\"binary\", setup_builder!(Binary)),\n\n (\"binary-therm\", setup_builder!(BinaryWithThermodynamics)),\n\n (\"envelope-shock\", setup_builder!(EnvelopeShock)),\n\n (\"explosion\", setup_builder!(Explosion)),\n\n (\"fast-shell\", setup_builder!(FastShell)),\n\n (\"pulse-collision\", setup_builder!(PulseCollision)),\n\n (\"sedov\", setup_builder!(Sedov)),\n\n (\"shocktube\", setup_builder!(Shocktube)),\n\n (\"wind\", setup_builder!(Wind)),\n\n ]\n\n}\n\n\n", "file_path": "src/setups.rs", "rank": 14, "score": 155211.62983447954 }, { "content": "/// Generates an error message of type `PrintUserInformation` listing known\n\n/// problem setups.\n\npub fn possible_setups_info() -> error::Error {\n\n let mut message = String::new();\n\n writeln!(message, \"specify setup:\").unwrap();\n\n for (setup_name, _) in setups() {\n\n writeln!(message, \" {}\", setup_name).unwrap();\n\n }\n\n PrintUserInformation(message)\n\n}\n\n\n", "file_path": "src/setups.rs", "rank": 15, "score": 153647.62445225776 }, { "content": "fn new_state(\n\n command_line: CommandLine,\n\n setup_name: &str,\n\n parameters: &str,\n\n) -> Result<State, error::Error> {\n\n let setup = setups::make_setup(setup_name, parameters)?;\n\n let mesh = setup.mesh(command_line.resolution.unwrap_or(1024));\n\n let num_patches = match command_line.execution_mode() {\n\n ExecutionMode::CPU => 512, // TODO: get patch count from command line\n\n ExecutionMode::OMP => 1,\n\n ExecutionMode::GPU => gpu_core::all_devices().count(),\n\n };\n\n\n\n let primitive_patches = match mesh {\n\n Mesh::Structured(_) => mesh\n\n .index_space()\n\n .tile(num_patches)\n\n .into_iter()\n\n .map(|s| setup.initial_primitive_patch(&s, &mesh))\n\n .collect(),\n", "file_path": "src/main.rs", "rank": 16, "score": 153438.2049644938 }, { "content": "/// Takes a string, and splits it into two parts, separated by the first\n\n/// instance of the given character. Each part is then parsed, and the whole\n\n/// call fails if either one fails.\n\npub fn parse_pair<T: std::str::FromStr<Err = E>, E>(\n\n string: &str,\n\n separator: char,\n\n) -> Result<(Option<T>, Option<T>), E> {\n\n let (sr1, sr2) = split_pair(&string, separator);\n\n let sr1 = sr1.map(|s| s.parse()).transpose()?;\n\n let sr2 = sr2.map(|s| s.parse()).transpose()?;\n\n Ok((sr1, sr2))\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 17, "score": 139020.4221857885 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct State {\n\n primitive_patches: Vec<Patch>,\n\n mesh: StructuredMesh,\n\n}\n\n\n\nimpl State {\n\n fn load(filename: &str) -> Result<Self> {\n\n let mut file = File::open(filename)?;\n\n let mut bytes = Vec::new();\n\n file.read_to_end(&mut bytes)?;\n\n Ok(rmp_serde::from_read_ref(&bytes)?)\n\n }\n\n fn num_fields(&self) -> Result<usize> {\n\n Ok(self\n\n .primitive_patches\n\n .first()\n\n .ok_or(anyhow::anyhow!(\"empty patch list\"))?\n\n .num_fields)\n\n }\n\n}\n\n\n", "file_path": "sf_png/src/main.rs", "rank": 18, "score": 137870.48357351264 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct Patch {\n\n #[serde(with = \"serde_bytes\")]\n\n data: Vec<u8>,\n\n rect: Rectangle<i64>,\n\n num_fields: usize,\n\n}\n\n\n", "file_path": "sf_png/src/main.rs", "rank": 19, "score": 137681.4833682918 }, { "content": "type SetupFunction = Box<dyn Fn(&str) -> Result<Arc<dyn Setup>, error::Error>>;\n\n\n", "file_path": "src/setups.rs", "rank": 20, "score": 135124.04464613512 }, { "content": "pub fn solver(\n\n mode: ExecutionMode,\n\n device: Option<i32>,\n\n faces: &[f64],\n\n primitive: &[f64],\n\n boundary_condition: BoundaryCondition,\n\n coords: Coordinates,\n\n) -> Result<Box<dyn Solve>, Error> {\n\n match mode {\n\n ExecutionMode::CPU => Ok(Box::new(cpu::Solver::new(\n\n faces,\n\n primitive,\n\n boundary_condition,\n\n coords,\n\n ))),\n\n ExecutionMode::OMP => {\n\n cfg_if! {\n\n if #[cfg(feature = \"omp\")] {\n\n Ok(Box::new(omp::Solver::new(faces, primitive, boundary_condition, coords)))\n\n } else {\n", "file_path": "src/euler1d/mod.rs", "rank": 21, "score": 127148.02137369156 }, { "content": "pub fn solver(\n\n mode: ExecutionMode,\n\n device: Option<i32>,\n\n faces: &[f64],\n\n primitive: &[f64],\n\n homologous_expansion: Option<(f64, f64)>,\n\n boundary_condition: BoundaryCondition,\n\n coords: Coordinates,\n\n scale_factor: f64,\n\n) -> Result<Box<dyn Solve>, Error> {\n\n let homologous_expansion = homologous_expansion.unwrap_or((1.0, 0.0));\n\n match mode {\n\n ExecutionMode::CPU => Ok(Box::new(cpu::Solver::new(\n\n faces,\n\n primitive,\n\n homologous_expansion,\n\n boundary_condition,\n\n coords,\n\n scale_factor,\n\n ))),\n", "file_path": "src/sr1d/mod.rs", "rank": 22, "score": 127148.02137369156 }, { "content": "fn print_quantiles(filename: &str, field: usize) -> Result<()> {\n\n let data = sorted_field(filename, field)?;\n\n println!(\"quantiles for {}:\", filename);\n\n println!(\" max {:+.03e}\", data.last().unwrap());\n\n for x in (1..5).rev() {\n\n let y = libm::erf(x as f64 / f64::sqrt(2.0));\n\n let i = (data.len() as f64 * y).floor() as usize;\n\n println!(\" +{} sigma ({:>6.3}%) {:+.03e}\", x, y * 100.0, data[i]);\n\n }\n\n for x in 1..5 {\n\n let y = 1.0 - libm::erf(x as f64 / f64::sqrt(2.0));\n\n let i = (data.len() as f64 * y).ceil() as usize;\n\n println!(\" -{} sigma ({:>6.3}%) {:+.03e}\", x, y * 100.0, data[i]);\n\n }\n\n println!(\" min {:+.03e}\", data.first().unwrap());\n\n Ok(())\n\n}\n\n\n", "file_path": "sf_png/src/main.rs", "rank": 23, "score": 126137.51958571105 }, { "content": "fn global_reduction<Solver: PatchBasedSolve>(solvers: &[Solver]) -> Vec<f64> {\n\n let patch_reductions: Vec<_> = solvers.iter().map(Solver::reductions).collect();\n\n let start = vec![0.0; patch_reductions[0].len()];\n\n\n\n patch_reductions.iter().fold(start, |a, b| {\n\n a.into_iter().zip(b).map(|(a, b)| a + b).collect()\n\n })\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 24, "score": 120563.65960763083 }, { "content": " def mesh(self, resolution: int):\n\n \"\"\"\n\n Return a mesh instance describing the problem domain.\n\n\n\n This method must be overridden, and the domain type must be supported\n\n by the solver. A resolution parameter is passed here from the driver.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 25, "score": 113393.83427547771 }, { "content": "/// A trait describing a simulation model setup.\n\n///\n\n/// This trait is used by the driver to define initial and boundary\n\n/// conditions, select a hydrodynamics solver and parameters, and describe\n\n/// physics conditions such as gravity and thermodynamics. Basic setups only\n\n/// need to implement a subset of the possible methods; most of the methods\n\n/// below have stub default implementations.\n\npub trait Setup: Send + Sync {\n\n /// Invoked by the solver to determine an equation of state (EOS), if that\n\n /// solver supports different types.\n\n ///\n\n /// Not all solvers support all EOS's, and the solver is not expected to\n\n /// produce an error if an incompatible EOS is returned from this method.\n\n fn equation_of_state(&self) -> EquationOfState;\n\n\n\n /// Invoked by the driver to build a mesh on which to run this problem.\n\n ///\n\n /// The mesh type must be compatible with the requested solver.\n\n ///\n\n /// The resolution parameter will be collected from the command line or\n\n /// restart file and provided to this method. The problem setup is then\n\n /// free to interpret the resolution parameter as it sees fit to generate\n\n /// a `Mesh` instance. For example, the resolution parameter may be\n\n /// interpreted by the setup as \"number of zones per side in a 2D square\n\n /// grid\", \"number of zones per decade\" in a 1D spherical polar grid, or\n\n /// \"number of polar zones\" in a 2D spherical polar grid.\n\n fn mesh(&self, resolution: u32) -> Mesh;\n", "file_path": "src/traits.rs", "rank": 26, "score": 111408.53220952206 }, { "content": " def mesh(self, num_zones_per_decade):\n", "file_path": "sailfish/setups/simple1d.py", "rank": 27, "score": 110790.15886049415 }, { "content": " def mesh(self, num_zones_per_decade):\n", "file_path": "sailfish/setups/simple2d.py", "rank": 28, "score": 110790.15886049415 }, { "content": "enum SolverState {\n\n NotReady,\n\n RungeKuttaStage(usize),\n\n}\n\n\n\npub struct Solver {\n\n time: f64,\n\n time0: f64,\n\n state: SolverState,\n\n dt: Option<f64>,\n\n rk_order: usize,\n\n primitive1: Patch,\n\n primitive2: Patch,\n\n conserved0: Patch,\n\n source_buf: Arc<Mutex<Patch>>,\n\n wavespeeds: Arc<Mutex<Patch>>,\n\n index_space: IndexSpace,\n\n incoming_count: usize,\n\n received_count: usize,\n\n outgoing_edges: Vec<Rectangle<i64>>,\n", "file_path": "src/euler2d/solver.rs", "rank": 29, "score": 109094.54977900366 }, { "content": "enum SolverState {\n\n NotReady,\n\n RungeKuttaStage(usize),\n\n}\n\n\n\npub struct Solver {\n\n time: f64,\n\n time0: f64,\n\n state: SolverState,\n\n dt: Option<f64>,\n\n rk_order: usize,\n\n primitive1: Patch,\n\n primitive2: Patch,\n\n conserved0: Patch,\n\n source_buf: Arc<Mutex<Patch>>,\n\n wavespeeds: Arc<Mutex<Patch>>,\n\n index_space: IndexSpace,\n\n incoming_count: usize,\n\n received_count: usize,\n\n outgoing_edges: Vec<Rectangle<i64>>,\n", "file_path": "src/iso2d/solver.rs", "rank": 30, "score": 109094.54977900366 }, { "content": "fn launch_single_patch(\n\n mut state: State,\n\n setup: Arc<dyn Setup>,\n\n cline: CommandLine,\n\n) -> Result<(), error::Error> {\n\n let (cfl, fold, rk_order, checkpoint_rule, dt_each_iter, end_time, outdir) = (\n\n cline.cfl_number(),\n\n cline.fold(),\n\n cline.rk_order(),\n\n cline.checkpoint_rule(setup.as_ref()),\n\n cline.recompute_dt_each_iteration(),\n\n cline.simulation_end_time(setup.as_ref()),\n\n cline.output_directory(&state.restart_file),\n\n );\n\n let mut solver = match &state.mesh {\n\n Mesh::FacePositions1D(faces) => match setup.solver_name().as_str() {\n\n \"euler1d\" => euler1d::solver(\n\n cline.execution_mode(),\n\n cline.device,\n\n faces,\n", "file_path": "src/main.rs", "rank": 31, "score": 108601.50284619724 }, { "content": " def mesh(self, num_zones_per_decade):\n\n return LogSphericalMesh(\n\n r0=self.r_inner,\n\n r1=self.r_outer,\n\n num_zones_per_decade=num_zones_per_decade,\n\n scale_factor_derivative=(1.0 / self.t_start) if self.expand else None,\n\n polar_grid=self.polar,\n\n polar_extent=self.polar_extent * pi,\n", "file_path": "sailfish/setups/envelope_shock.py", "rank": 32, "score": 108363.61061718184 }, { "content": " def mesh(self, num_zones_per_decade):\n\n return LogSphericalMesh(\n\n r0=self.r_inner,\n\n r1=self.r_outer,\n\n num_zones_per_decade=num_zones_per_decade,\n", "file_path": "sailfish/setups/exploding_star.py", "rank": 33, "score": 108363.61061718184 }, { "content": "fn sample_rgba(colormap: &[[f64; 3]; 256], y: f64) -> [u8; 4] {\n\n let k = (y.clamp(0.0, 1.0 - 1e-16) * 256.0) as usize;\n\n let l = colormap[k];\n\n let t = [\n\n (l[0] * 256.0) as u8,\n\n (l[1] * 256.0) as u8,\n\n (l[2] * 256.0) as u8,\n\n 255,\n\n ];\n\n t\n\n}\n\n\n", "file_path": "sf_png/src/main.rs", "rank": 34, "score": 108113.55228253709 }, { "content": " def default_model_parameters(cls):\n\n \"\"\"\n\n Return an iterator over the default model parameters for this class.\n\n \"\"\"\n\n for key, val in vars(cls).items():\n\n if type(val) == Parameter:\n\n yield key, val.default, val.about\n\n elif hasattr(cls, \"__annotations__\"):\n", "file_path": "sailfish/setup.py", "rank": 35, "score": 107905.05960580731 }, { "content": " def default_end_time(self):\n\n \"\"\"\n\n Provide a default end-time to the simulation driven.\n\n\n\n This value will be superceded if a non-None end time was provided to\n\n the driver. If neither the driver nor the setup has an end time, then\n\n the simulation runs until it's killed.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 36, "score": 107859.23762126421 }, { "content": " def default_end_time(self):\n", "file_path": "sailfish/setups/simple1d.py", "rank": 37, "score": 104418.9500851807 }, { "content": " def default_end_time(self):\n", "file_path": "sailfish/setups/simple2d.py", "rank": 38, "score": 104418.9500851807 }, { "content": "fn make_state(cline: &CommandLine) -> Result<State, error::Error> {\n\n let state = if let Some(ref setup_string) = cline.setup {\n\n let (name, parameters) = sailfish::parse::split_pair(setup_string, ':');\n\n let (name, parameters) = (name.unwrap_or(\"\"), parameters.unwrap_or(\"\"));\n\n\n\n if name.ends_with(\".sf\") {\n\n State::from_checkpoint(name, &parameters, cline)?\n\n } else if let Some(ref file) = sailfish::parse::last_in_dir_ending_with(name, \".sf\") {\n\n let chkpt = std::path::Path::new(name).join(file);\n\n State::from_checkpoint(chkpt.to_str().unwrap(), &parameters, cline)?\n\n } else {\n\n new_state(cline.clone(), name, &parameters)?\n\n }\n\n } else {\n\n return Err(setups::possible_setups_info());\n\n };\n\n if cline.upsample.unwrap_or(false) {\n\n Ok(state.upsample())\n\n } else {\n\n Ok(state)\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 39, "score": 102406.77046925096 }, { "content": " def default_end_time(self):\n", "file_path": "sailfish/setups/envelope_shock.py", "rank": 40, "score": 101203.57628438293 }, { "content": " def default_end_time(self):\n", "file_path": "sailfish/setups/exploding_star.py", "rank": 41, "score": 101203.57628438294 }, { "content": "/// A trait to build patch-based solver instances.\n\n///\n\n/// With domain-decomposed grids, the driver needs to construct one solver\n\n/// instance for each grid patch. So, rather than supplying the driver with\n\n/// the solver instance(s), the top-level driver invocation provides a sovler\n\n/// builder, which the driver then uses to build as many solvers as there are\n\n/// patches.\n\npub trait PatchBasedBuild {\n\n type Solver: PatchBasedSolve;\n\n\n\n #[allow(clippy::too_many_arguments)]\n\n fn build(\n\n &self,\n\n time: f64,\n\n primitive: Patch,\n\n global_structured_mesh: StructuredMesh,\n\n edge_list: &AdjacencyList<Rectangle<i64>>,\n\n rk_order: usize,\n\n mode: ExecutionMode,\n\n device: Option<Device>,\n\n setup: Arc<dyn Setup>,\n\n ) -> Self::Solver;\n\n}\n\n\n", "file_path": "src/traits.rs", "rank": 42, "score": 100818.50051154492 }, { "content": "/// A trait for 2D solvers which operate on grid patches.\n\n///\n\n/// These solvers implement message passing and task-based parallelism via the\n\n/// `Automaton` trait.\n\npub trait PatchBasedSolve:\n\n Automaton<Key = Rectangle<i64>, Value = Self, Message = Patch> + Send + Sync\n\n{\n\n /// Returns the primitive variable array for this solver.\n\n ///\n\n /// The data is row-major with contiguous primitive variable components.\n\n /// The array does not include guard zones.\n\n fn primitive(&self) -> Patch;\n\n\n\n /// Sets the time step size to be used in subsequent advance stages.\n\n fn set_timestep(&mut self, dt: f64);\n\n\n\n /// Returns the largest wavespeed among the zones in the solver's current\n\n /// primitive array.\n\n ///\n\n /// This function should be as performant as possible, although if the\n\n /// reduction required to obtain the maximum wavespeed is slow, the effect\n\n /// might be mitigated by living on the edge and re-computing the timestep\n\n /// less frequently than every time step.\n\n fn max_wavespeed(&self) -> f64;\n", "file_path": "src/traits.rs", "rank": 43, "score": 100815.0730264145 }, { "content": "fn launch_patch_based<Builder, Solver>(\n\n mut state: State,\n\n setup: Arc<dyn Setup>,\n\n cline: CommandLine,\n\n builder: Builder,\n\n) -> Result<(), error::Error>\n\nwhere\n\n Builder: PatchBasedBuild<Solver = Solver>,\n\n Solver: PatchBasedSolve,\n\n{\n\n let (cfl, fold, rk_order, checkpoint_rule, time_series_rule, dt_each_iter, end_time, outdir) = (\n\n cline.cfl_number(),\n\n cline.fold(),\n\n cline.rk_order(),\n\n cline.checkpoint_rule(setup.as_ref()),\n\n cline.time_series_rule(setup.as_ref()),\n\n cline.recompute_dt_each_iteration(),\n\n cline.simulation_end_time(setup.as_ref()),\n\n cline.output_directory(&state.restart_file),\n\n );\n", "file_path": "src/main.rs", "rank": 44, "score": 94449.59714679373 }, { "content": "fn max_wavespeed<Solver: PatchBasedSolve>(\n\n solvers: &[Solver],\n\n pool: &Option<rayon::ThreadPool>,\n\n) -> f64 {\n\n if let Some(pool) = pool {\n\n pool.install(|| {\n\n solvers\n\n .par_iter()\n\n .map(|s| s.max_wavespeed())\n\n .reduce(|| 0.0, f64::max)\n\n })\n\n } else {\n\n solvers\n\n .iter()\n\n .map(|s| s.max_wavespeed())\n\n .fold(0.0, f64::max)\n\n }\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 45, "score": 92003.2784125416 }, { "content": "class Setup(ABC):\n\n \"\"\"\n\n Abstract base class to describe a simulation model setup.\n\n\n\n Subclasses are used by the driver to define initial and boundary\n\n conditions, select a hydrodynamics solver and parameters, and describe\n\n physics conditions such as gravity and thermodynamics. Basic setups only\n\n need to implement a subset of the possible methods; most of the methods\n\n below have stub default implementations.\n\n \"\"\"\n\n\n\n def __init__(self, **kwargs):\n\n for key, val, about in type(self).default_model_parameters():\n\n if key in kwargs:\n\n if type(kwargs[key]) != type(val):\n\n raise SetupError(\n\n f\"parameter '{key}' has type {type(val).__name__} \"\n\n f\"(got {type(kwargs[key]).__name__})\"\n\n )\n\n setattr(self, key, kwargs[key])\n\n else:\n\n setattr(self, key, val)\n\n\n\n for key, val in kwargs.items():\n\n if not hasattr(self, key):\n\n raise SetupError(\n\n f\"'{self.dash_case_class_name()}' has no parameter '{key}'\"\n\n )\n\n\n\n self.validate()\n\n\n\n @classmethod\n\n def default_model_parameters(cls):\n\n \"\"\"\n\n Return an iterator over the default model parameters for this class.\n\n \"\"\"\n\n for key, val in vars(cls).items():\n\n if type(val) == Parameter:\n\n yield key, val.default, val.about\n\n elif hasattr(cls, \"__annotations__\"):\n\n print(cls.__annotations__)\n\n\n\n @classmethod\n\n def immutable_parameter_keys(cls):\n\n \"\"\"\n\n Return an iterator over the immutable model parameter keys.\n\n \"\"\"\n\n for key, val in vars(cls).items():\n\n if type(val) == Parameter and not val.mutable:\n\n yield key\n\n\n\n @classmethod\n\n def describe_class(cls):\n\n \"\"\"\n\n Print formatted text describing the setup.\n\n\n\n The output will include a normlized version of the class doc string,\n\n and the model parameter names, default values, and about message.\n\n \"\"\"\n\n print(f\"setup: {cls.dash_case_class_name()}\")\n\n print(dedent(cls.__doc__))\n\n cls().print_model_parameters()\n\n\n\n @classmethod\n\n def dash_case_class_name(cls):\n\n \"\"\"\n\n Return a `dash-case` name of this setup class.\n\n\n\n Dash case is used in configuration, including the setup name passed to\n\n the driver, and written in checkpoint files.\n\n \"\"\"\n\n return \"\".join(\n\n [\"-\" + c.lower() if c.isupper() else c for c in cls.__name__]\n\n ).lstrip(\"-\")\n\n\n\n @classmethod\n\n def find_setup_class(cls, name):\n\n \"\"\"\n\n Finds a setup class with the given name.\n\n\n\n The class name is expected in dash-case format. If no setup is found,\n\n a `SetupError` exception is raised.\n\n \"\"\"\n\n match = lambda s: s.dash_case_class_name() == name\n\n try:\n\n return next(filter(match, cls.__subclasses__()))\n\n except StopIteration:\n\n raise SetupError(f\"no setup named {name}\")\n\n\n\n @classmethod\n\n def has_model_parameters(cls):\n\n \"\"\"\n\n Determine if this class has any model parameters.\n\n \"\"\"\n\n for _ in cls.default_model_parameters():\n\n return True\n\n return False\n\n\n\n def print_model_parameters(self, logger=None, newlines=False):\n\n \"\"\"\n\n Print parameter names, values, and about messages to `stdout`.\n\n \"\"\"\n\n\n\n def _p(m):\n\n if logger is not None:\n\n logger.info(m)\n\n else:\n\n print(m)\n\n\n\n if newlines:\n\n _p(\"\")\n\n if self.has_model_parameters():\n\n _p(\"model parameters:\\n\")\n\n for name, val, about in self.model_parameters():\n\n _p(f\"{name:.<16s} {str(val):<8} {about}\")\n\n else:\n\n _p(\"setup has no model parameters\")\n\n if newlines:\n\n _p(\"\")\n\n\n\n def model_parameters(self):\n\n \"\"\"\n\n Return an iterator over the model parameters chosen for this setup.\n\n \"\"\"\n\n for key, val, about in self.default_model_parameters():\n\n yield key, getattr(self, key), about\n\n\n\n def model_parameter_dict(self):\n\n \"\"\"\n\n Return a dictionary of the model parameters.\n\n \"\"\"\n\n return {key: val for key, val, _ in self.model_parameters()}\n\n\n\n @abstractmethod\n\n def primitive(self, time, coordinate, primitive):\n\n \"\"\"\n\n Set initial or boundary data at a point.\n\n\n\n This method must be overridden to set the primitive hydrodynamic\n\n variables at a single point (given by `coordinate`) and time. The\n\n meaning of the coordinate is influenced by the type of mesh being\n\n used. Data is written to the output variable `primitive` for\n\n efficiency, since otherwise a tiny allocation is made for each zone in\n\n the simulation grid.\n\n\n\n The time coordinate enables the use of a time-dependent boundary\n\n condition.\n\n \"\"\"\n\n pass\n\n\n\n @abstractmethod\n\n def mesh(self, resolution: int):\n\n \"\"\"\n\n Return a mesh instance describing the problem domain.\n\n\n\n This method must be overridden, and the domain type must be supported\n\n by the solver. A resolution parameter is passed here from the driver.\n\n \"\"\"\n\n pass\n\n\n\n @property\n\n @abstractmethod\n\n def solver(self):\n\n \"\"\"\n\n Return the name of the setup class.\n\n \"\"\"\n\n pass\n\n\n\n @property\n\n def physics(self):\n\n \"\"\"\n\n Return physics parameters used by the solver: EOS, gravity, etc.\n\n\n\n Physics parameters should be distinct from the solver options, such as\n\n PLM theta value, RK integration type, or DG order.\n\n \"\"\"\n\n return dict()\n\n\n\n @property\n\n @abstractmethod\n\n def boundary_condition(self):\n\n \"\"\"\n\n Return a boundary condition mode.\n\n\n\n This method must be overridden, and the mode must be supported by the\n\n solver. 1D solvers should accept either a single return value\n\n specifying the BC mode at both the domain edges, or a pair of modes,\n\n one for each edge.\n\n \"\"\"\n\n pass\n\n\n\n @property\n\n def start_time(self):\n\n \"\"\"\n\n Provide a start time for the simulation. This is 0.0 by default.\n\n \"\"\"\n\n return 0.0\n\n\n\n @property\n\n def default_end_time(self):\n\n \"\"\"\n\n Provide a default end-time to the simulation driven.\n\n\n\n This value will be superceded if a non-None end time was provided to\n\n the driver. If neither the driver nor the setup has an end time, then\n\n the simulation runs until it's killed.\n\n \"\"\"\n\n return None\n\n\n\n @property\n\n def default_resolution(self):\n\n \"\"\"\n\n Provide a default grid resolution.\n\n \"\"\"\n\n return 10000\n\n\n\n def validate(self):\n\n \"\"\"\n\n Confirm that the model parameters are physically valid.\n\n\n\n This method should be overridden to indicate a failure by throwing a\n\n `SetupError` exception.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 46, "score": 85836.45394862373 }, { "content": " def __str__(self):\n", "file_path": "sailfish/mesh.py", "rank": 47, "score": 77255.77781840038 }, { "content": " real mass;\n", "file_path": "src/sailfish.h", "rank": 48, "score": 77020.5231752002 }, { "content": "struct Mesh\n\n{\n\n int64_t ni, nj;\n\n real x0, y0;\n\n real dx, dy;\n", "file_path": "src/sailfish.h", "rank": 49, "score": 76784.77382426962 }, { "content": "class Parameter(NamedTuple):\n\n \"\"\"\n\n A model parameter: enables runtime configuring of a setup.\n\n\n\n `Parameter` instances are assigned as class variables to `Setup`\n\n sub-classes. The `mutable` flag should be set to to `True` if the\n\n parameter is logically adjustable either during the run, or can be\n\n superseded when a run is restarted.\n\n \"\"\"\n\n\n\n default: Any\n\n about: str\n", "file_path": "sailfish/setup.py", "rank": 50, "score": 76753.84876528343 }, { "content": " def primitive(self, time, coordinate, primitive):\n\n \"\"\"\n\n Set initial or boundary data at a point.\n\n\n\n This method must be overridden to set the primitive hydrodynamic\n\n variables at a single point (given by `coordinate`) and time. The\n\n meaning of the coordinate is influenced by the type of mesh being\n\n used. Data is written to the output variable `primitive` for\n\n efficiency, since otherwise a tiny allocation is made for each zone in\n\n the simulation grid.\n\n\n\n The time coordinate enables the use of a time-dependent boundary\n\n condition.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 51, "score": 76378.82676809077 }, { "content": "struct PointMass\n\n{\n\n real x;\n\n real y;\n\n real vx;\n\n real vy;\n\n real mass;\n\n real rate;\n\n real radius;\n\n enum SinkModel model;\n", "file_path": "src/sailfish.h", "rank": 52, "score": 75603.83474964078 }, { "content": " def time(self):\n\n \"\"\"\n\n Return the simulation time.\n\n \"\"\"\n", "file_path": "sailfish/solver.py", "rank": 53, "score": 75563.8822727887 }, { "content": "struct Patch\n\n{\n\n int start;\n\n int count;\n\n int jumps;\n\n int num_fields;\n\n real *data;\n", "file_path": "src/euler1d/mod.c", "rank": 54, "score": 75388.55610724508 }, { "content": "static struct Patch patch(struct Mesh mesh, int num_fields, int num_guard, real *data)\n\n{\n\n struct Patch patch;\n\n patch.start[0] = -num_guard;\n\n patch.start[1] = -num_guard;\n\n patch.count[0] = mesh.ni + 2 * num_guard;\n\n patch.count[1] = mesh.nj + 2 * num_guard;\n\n patch.jumps[0] = num_fields * patch.count[1];\n\n patch.jumps[1] = num_fields;\n\n patch.num_fields = num_fields;\n\n patch.data = data;\n\n return patch;\n", "file_path": "src/iso2d/mod.c", "rank": 55, "score": 75388.55610724508 }, { "content": "static struct Patch patch(int num_elements, int num_fields, real *data)\n\n{\n\n struct Patch patch;\n\n patch.start = 0;\n\n patch.count = num_elements;\n\n patch.jumps = num_fields;\n\n patch.num_fields = num_fields;\n\n patch.data = data;\n\n return patch;\n", "file_path": "src/sr1d/mod.c", "rank": 56, "score": 75388.55610724508 }, { "content": "struct Patch\n\n{\n\n int start;\n\n int count;\n\n int jumps;\n\n int num_fields;\n\n real *data;\n", "file_path": "src/sr1d/mod.c", "rank": 57, "score": 75388.55610724508 }, { "content": "static struct Patch patch(struct Mesh mesh, int num_fields, int num_guard, real *data)\n\n{\n\n struct Patch patch;\n\n patch.start[0] = -num_guard;\n\n patch.start[1] = -num_guard;\n\n patch.count[0] = mesh.ni + 2 * num_guard;\n\n patch.count[1] = mesh.nj + 2 * num_guard;\n\n patch.jumps[0] = num_fields * patch.count[1];\n\n patch.jumps[1] = num_fields;\n\n patch.num_fields = num_fields;\n\n patch.data = data;\n\n return patch;\n", "file_path": "src/euler2d/mod.c", "rank": 58, "score": 75388.55610724508 }, { "content": "static struct Patch patch(int num_elements, int num_fields, real *data)\n\n{\n\n struct Patch patch;\n\n patch.start = 0;\n\n patch.count = num_elements;\n\n patch.jumps = num_fields;\n\n patch.num_fields = num_fields;\n\n patch.data = data;\n\n return patch;\n", "file_path": "src/euler1d/mod.c", "rank": 59, "score": 75388.55610724508 }, { "content": "struct Patch\n\n{\n\n int start[2];\n\n int count[2];\n\n int jumps[2];\n\n int num_fields;\n\n real *data;\n", "file_path": "src/euler2d/mod.c", "rank": 60, "score": 75388.55610724508 }, { "content": "struct Patch\n\n{\n\n int start[2];\n\n int count[2];\n\n int jumps[2];\n\n int num_fields;\n\n real *data;\n", "file_path": "src/iso2d/mod.c", "rank": 61, "score": 75388.55610724508 }, { "content": " def time(self):\n", "file_path": "sailfish/solvers/srhd_2d.py", "rank": 62, "score": 74246.97346255527 }, { "content": " def time(self):\n", "file_path": "sailfish/solvers/cbdgam_2d.py", "rank": 63, "score": 74246.97346255527 }, { "content": " def time(self):\n", "file_path": "sailfish/solvers/srhd_1d.py", "rank": 64, "score": 74246.97346255527 }, { "content": " def time(self):\n", "file_path": "sailfish/solvers/scdg_1d.py", "rank": 65, "score": 74246.97346255527 }, { "content": " def model_parameters(self):\n\n \"\"\"\n\n Return an iterator over the model parameters chosen for this setup.\n\n \"\"\"\n\n for key, val, about in self.default_model_parameters():\n", "file_path": "sailfish/setup.py", "rank": 66, "score": 74154.01801976109 }, { "content": " def has_model_parameters(cls):\n\n \"\"\"\n\n Determine if this class has any model parameters.\n\n \"\"\"\n\n for _ in cls.default_model_parameters():\n\n return True\n", "file_path": "sailfish/setup.py", "rank": 67, "score": 74146.00721840968 }, { "content": " def default_resolution(self):\n\n \"\"\"\n\n Provide a default grid resolution.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 68, "score": 74131.42830554224 }, { "content": " def start_time(self):\n\n \"\"\"\n\n Provide a start time for the simulation. This is 0.0 by default.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 69, "score": 74101.2166541799 }, { "content": "class Patch:\n\n \"\"\"\n\n Holds the array buffer state for the solution on a subset of the\n\n solution domain.\n\n \"\"\"\n\n\n\n def __init__(\n\n self,\n\n time,\n\n primitive,\n\n mesh,\n\n index_range,\n\n physics,\n\n options,\n\n lib,\n\n xp,\n\n ):\n\n i0, i1 = index_range\n\n self.lib = lib\n\n self.xp = xp\n\n self.time = self.time0 = time\n\n self.shape = (i1 - i0, mesh.shape[1]) # not including guard zones\n\n self.physics = physics\n\n self.options = options\n\n\n\n with self.execution_context():\n\n self.wavespeeds = self.xp.zeros(primitive.shape[:2])\n\n self.primitive1 = self.xp.array(primitive)\n\n self.primitive2 = self.xp.array(primitive)\n\n self.conserved0 = self.primitive_to_conserved(self.primitive1)\n\n\n\n def execution_context(self):\n\n \"\"\"TODO: return a CUDA context for execution on the assigned device\"\"\"\n\n return nullcontext()\n\n\n\n def maximum_wavespeed(self):\n\n with self.execution_context():\n\n self.lib.cbdgam_2d_wavespeed[self.shape](\n\n self.primitive1,\n\n self.wavespeeds,\n\n self.physics.gamma_law_index,\n\n )\n\n return self.xp.max(self.wavespeeds[ng:-ng, ng:-ng])\n\n\n\n def primitive_to_conserved(self, primitive):\n\n with self.execution_context():\n\n pass\n\n\n\n def recompute_conserved(self):\n\n with self.execution_context():\n\n pass\n\n\n\n def advance_rk(self, rk_param, dt):\n\n with self.execution_context():\n\n pass\n\n\n\n self.time = self.time0 * rk_param + (self.time + dt) * (1.0 - rk_param)\n\n self.primitive1, self.primitive2 = self.primitive2, self.primitive1\n\n\n\n def new_iteration(self):\n\n self.time0 = self.time\n\n self.recompute_conserved()\n\n\n\n @property\n\n def primitive(self):\n", "file_path": "sailfish/solvers/cbdgam_2d.py", "rank": 70, "score": 74084.19184940733 }, { "content": "class Patch:\n\n \"\"\"\n\n Holds the array buffer state for the solution on a subset of the\n\n solution domain.\n\n \"\"\"\n\n\n\n def __init__(\n\n self,\n\n time,\n\n conserved,\n\n mesh,\n\n index_range,\n\n lib,\n\n xp,\n\n ):\n\n i0, i1 = index_range\n\n self.lib = lib\n\n self.xp = xp\n\n self.shape = shape = (i1 - i0, mesh.shape[1]) # not including guard zones\n\n self.faces = xp.array(mesh.faces(*index_range))\n\n self.polar_extent = mesh.polar_extent\n\n\n\n try:\n\n adot = float(mesh.scale_factor_derivative)\n\n self.scale_factor_initial = 0.0\n\n self.scale_factor_derivative = adot\n\n except (TypeError, AttributeError):\n\n self.scale_factor_initial = 1.0\n\n self.scale_factor_derivative = 0.0\n\n\n\n self.time = self.time0 = time\n\n\n\n with self.execution_context():\n\n self.wavespeeds = xp.zeros(shape)\n\n self.primitive1 = xp.zeros_like(conserved)\n\n self.conserved0 = conserved\n\n self.conserved1 = self.conserved0.copy()\n\n self.conserved2 = self.conserved0.copy()\n\n\n\n def execution_context(self):\n\n \"\"\"TODO: return a CUDA context for execution on the assigned device\"\"\"\n\n return nullcontext()\n\n\n\n def recompute_primitive(self):\n\n with self.execution_context():\n\n self.lib.srhd_2d_conserved_to_primitive[self.shape](\n\n self.faces,\n\n self.conserved1,\n\n self.primitive1,\n\n self.polar_extent,\n\n self.scale_factor,\n\n )\n\n\n\n def advance_rk(self, rk_param, dt):\n\n with self.execution_context():\n\n self.lib.srhd_2d_advance_rk[self.shape](\n\n self.faces,\n\n self.conserved0,\n\n self.primitive1,\n\n self.conserved1,\n\n self.conserved2,\n\n self.polar_extent,\n\n self.scale_factor_initial,\n\n self.scale_factor_derivative,\n\n self.time,\n\n rk_param,\n\n dt,\n\n )\n\n self.time = self.time0 * rk_param + (self.time + dt) * (1.0 - rk_param)\n\n self.conserved1, self.conserved2 = self.conserved2, self.conserved1\n\n\n\n @property\n\n def maximum_wavespeed(self):\n\n self.recompute_primitive()\n\n with self.execution_context():\n\n self.lib.srhd_2d_max_wavespeeds[self.shape](\n\n self.faces,\n\n self.primitive1,\n\n self.wavespeeds,\n\n self.scale_factor_derivative,\n\n )\n\n return self.wavespeeds.max()\n\n\n\n @property\n\n def scale_factor(self):\n\n return self.scale_factor_initial + self.scale_factor_derivative * self.time\n\n\n\n def new_iteration(self):\n\n self.time0 = self.time\n\n self.conserved0[...] = self.conserved1[...]\n\n\n\n @property\n\n def conserved(self):\n\n return self.conserved1\n\n\n\n @property\n\n def primitive(self):\n\n self.recompute_primitive()\n", "file_path": "sailfish/solvers/srhd_2d.py", "rank": 71, "score": 74084.19184940733 }, { "content": "class Patch:\n\n \"\"\"\n\n Holds the array buffer state for the solution on a subset of the\n\n solution domain.\n\n \"\"\"\n\n\n\n def __init__(\n\n self,\n\n time,\n\n conserved,\n\n mesh,\n\n index_range,\n\n lib,\n\n xp,\n\n ):\n\n i0, i1 = index_range\n\n self.lib = lib\n\n self.xp = xp\n\n self.num_zones = num_zones = index_range[1] - index_range[0]\n\n self.faces = xp.array(mesh.faces(*index_range))\n\n self.coordinates = COORDINATES_DICT[type(mesh)]\n\n\n\n try:\n\n adot = float(mesh.scale_factor_derivative)\n\n self.scale_factor_initial = 0.0\n\n self.scale_factor_derivative = adot\n\n except (TypeError, AttributeError):\n\n self.scale_factor_initial = 1.0\n\n self.scale_factor_derivative = 0.0\n\n\n\n self.time = self.time0 = time\n\n\n\n with self.execution_context():\n\n self.wavespeeds = xp.zeros(num_zones)\n\n self.primitive1 = xp.zeros_like(conserved)\n\n self.conserved0 = conserved\n\n self.conserved1 = self.conserved0.copy()\n\n self.conserved2 = self.conserved0.copy()\n\n\n\n def execution_context(self):\n\n \"\"\"TODO: return a CUDA context for execution on the assigned device\"\"\"\n\n return nullcontext()\n\n\n\n def recompute_primitive(self):\n\n with self.execution_context():\n\n self.lib.srhd_1d_conserved_to_primitive[self.num_zones](\n\n self.faces,\n\n self.conserved1,\n\n self.primitive1,\n\n self.scale_factor,\n\n self.coordinates,\n\n )\n\n\n\n def advance_rk(self, rk_param, dt):\n\n with self.execution_context():\n\n self.lib.srhd_1d_advance_rk[self.num_zones](\n\n self.faces,\n\n self.conserved0,\n\n self.primitive1,\n\n self.conserved1,\n\n self.conserved2,\n\n self.scale_factor_initial,\n\n self.scale_factor_derivative,\n\n self.time,\n\n rk_param,\n\n dt,\n\n self.coordinates,\n\n )\n\n self.time = self.time0 * rk_param + (self.time + dt) * (1.0 - rk_param)\n\n self.conserved1, self.conserved2 = self.conserved2, self.conserved1\n\n\n\n @property\n\n def maximum_wavespeed(self):\n\n self.recompute_primitive()\n\n with self.execution_context():\n\n self.lib.srhd_1d_max_wavespeeds[self.num_zones](\n\n self.faces,\n\n self.primitive1,\n\n self.wavespeeds,\n\n self.scale_factor_derivative,\n\n )\n\n return self.wavespeeds.max()\n\n\n\n @property\n\n def scale_factor(self):\n\n return self.scale_factor_initial + self.scale_factor_derivative * self.time\n\n\n\n def new_iteration(self):\n\n self.time0 = self.time\n\n self.conserved0[...] = self.conserved1[...]\n\n\n\n @property\n\n def conserved(self):\n\n return self.conserved1\n\n\n\n @property\n\n def primitive(self):\n\n self.recompute_primitive()\n", "file_path": "sailfish/solvers/srhd_1d.py", "rank": 72, "score": 74084.19184940733 }, { "content": " def primitive(self, t, r, primitive):\n\n primitive[0] = 1.0 / r ** 2\n\n primitive[1] = self.velocity\n", "file_path": "sailfish/setups/simple1d.py", "rank": 73, "score": 73774.92934660647 }, { "content": " def primitive(self, t, _, primitive):\n\n primitive[0] = 1.0\n\n primitive[1] = 0.0\n\n primitive[2] = 0.0\n", "file_path": "sailfish/setups/simple2d.py", "rank": 74, "score": 73774.92934660647 }, { "content": "fn main() {\n\n let plat = sf_build::Platform::discover(use_gpu());\n\n plat.build_src(\"src/iso2d/mod\", use_omp())\n\n .compile(\"iso2d_mod\");\n\n plat.build_src(\"src/euler1d/mod\", use_omp())\n\n .compile(\"euler1d_mod\");\n\n plat.build_src(\"src/euler2d/mod\", use_omp())\n\n .compile(\"euler2d_mod\");\n\n plat.build_src(\"src/sr1d/mod\", use_omp())\n\n .compile(\"sr1d_mod\");\n\n plat.emit_link_flags();\n\n}\n", "file_path": "build.rs", "rank": 75, "score": 73541.11157963578 }, { "content": "class PointMass(NamedTuple):\n\n \"\"\"\n\n The mass, 2D position, and 2D velocity of a point-like particle\n\n \"\"\"\n\n\n\n mass: float\n\n position_x: float\n\n position_y: float\n\n velocity_x: float\n\n velocity_y: float\n\n\n\n @property\n\n def kinetic_energy(self) -> float:\n\n \"\"\"\n\n The kinetic energy of a point mass\n\n \"\"\"\n\n vx = p.velocity_x\n\n vy = p.velocity_y\n\n return 0.5 * p.mass * (vx * vx + vy * vy)\n\n\n\n @property\n\n def angular_momentum(self) -> float:\n\n \"\"\"\n\n The angular momentum of a point mass\n\n \"\"\"\n\n x = p.position_x\n\n y = p.position_y\n\n vx = p.velocity_x\n\n vy = p.velocity_y\n\n return p.mass * (x * vy - y * vx)\n\n\n\n def gravitational_potential(\n\n self, x: float, y: float, softening_length: float\n\n ) -> float:\n\n \"\"\"\n\n Return the gravitational potential of a point mass, with softening.\n\n \"\"\"\n\n dx = x - p.position_x\n\n dy = y - p.position_y\n\n r2 = dx * dx + dy * dy\n\n s2 = softening_length.powi(2)\n\n return -NEWTON_G * p.mass / sqrt(r2 + s2)\n\n\n\n def gravitational_acceleration(\n\n p, x: float, y: float, softening_length: float\n\n ) -> (float, float):\n\n \"\"\"\n\n Return the gravitational acceleration due to a point mass.\n\n \"\"\"\n\n dx = x - p.position_x\n\n dy = y - p.position_y\n\n r2 = dx * dx + dy * dy\n\n s2 = softening_length ** 2.0\n\n ax = -NEWTON_G * p.mass / (r2 + s2) ** 1.5 * dx\n\n ay = -NEWTON_G * p.mass / (r2 + s2) ** 1.5 * dy\n\n return (ax, ay)\n\n\n\n def perturb(\n\n self, dm: float = 0.0, dpx: float = 0.0, dpy: float = 0.0\n\n ) -> \"PointMass\":\n\n \"\"\"\n\n Perturb the mass and momentum of a point mass.\n\n\n\n Since the point mass maintains a velocity rather than momentum,\n\n the velocity is changed according to\n\n\n\n dv = (dp - v dm) / m\n\n \"\"\"\n\n return p._replace(\n\n mass=p.mass + dm,\n\n velocity_x=velocity_x + (dpx - p.velocity_x * dm) / p.mass,\n\n velocity_y=velocity_y + (dpy - p.velocity_y * dm) / p.mass,\n", "file_path": "sailfish/physics/kepler.py", "rank": 76, "score": 73067.6760241843 }, { "content": " def new_iteration(self):\n\n for patch in self.patches:\n", "file_path": "sailfish/solvers/srhd_1d.py", "rank": 77, "score": 72414.73747571772 }, { "content": " def new_iteration(self):\n\n for patch in self.patches:\n", "file_path": "sailfish/solvers/srhd_2d.py", "rank": 78, "score": 72414.73747571772 }, { "content": " def new_iteration(self):\n\n for patch in self.patches:\n", "file_path": "sailfish/solvers/cbdgam_2d.py", "rank": 79, "score": 72414.73747571772 }, { "content": "fn main() {\n\n if let Err(e) = run() {\n\n print!(\"{}\", e)\n\n }\n\n}\n", "file_path": "src/main.rs", "rank": 80, "score": 71777.89380811017 }, { "content": " def immutable_parameter_keys(cls):\n\n \"\"\"\n\n Return an iterator over the immutable model parameter keys.\n\n \"\"\"\n\n for key, val in vars(cls).items():\n\n if type(val) == Parameter and not val.mutable:\n", "file_path": "sailfish/setup.py", "rank": 81, "score": 71717.12419127874 }, { "content": " def model_parameter_dict(self):\n\n \"\"\"\n\n Return a dictionary of the model parameters.\n\n \"\"\"\n", "file_path": "sailfish/setup.py", "rank": 82, "score": 71713.1286292177 }, { "content": " Mesh::FacePositions1D(_) => vec![],\n\n };\n\n\n\n let primitive = match mesh {\n\n Mesh::Structured(_) => vec![],\n\n Mesh::FacePositions1D(_) => setup.initial_primitive_vec(&mesh),\n\n };\n\n\n\n let state = State {\n\n command_line,\n\n mesh,\n\n restart_file: None,\n\n iteration: 0,\n\n time: setup.initial_time(),\n\n primitive,\n\n primitive_patches,\n\n checkpoint: RecurringTask::new(),\n\n time_series: RecurringTask::new(),\n\n time_series_data: vec![],\n\n setup_name: setup_name.to_string(),\n\n parameters: parameters.to_string(),\n\n masses: setup.masses(setup.initial_time()).to_vec(),\n\n version: sailfish::sailfish_version(),\n\n };\n\n Ok(state)\n\n}\n\n\n", "file_path": "src/main.rs", "rank": 83, "score": 45.83324874112619 }, { "content": " })\n\n .unwrap_or_else(|| String::from(\".\"))\n\n }\n\n}\n\n\n\nimpl Default for CommandLine {\n\n fn default() -> Self {\n\n Self {\n\n use_omp: None,\n\n use_gpu: None,\n\n device: None,\n\n upsample: None,\n\n resolution: None,\n\n fold: None,\n\n checkpoint_interval: None,\n\n checkpoint_logspace: None,\n\n time_series_interval: None,\n\n time_series_logspace: None,\n\n setup: None,\n\n outdir: None,\n\n end_time: None,\n\n rk_order: None,\n\n cfl_number: None,\n\n recompute_timestep: None,\n\n }\n\n }\n\n}\n", "file_path": "src/cmdline.rs", "rank": 90, "score": 33.124059447209085 }, { "content": " let dx_min = state.mesh.min_spacing();\n\n\n\n if std::matches!(checkpoint_rule, Recurrence::Log(_)) && setup.initial_time() <= 0.0 {\n\n return Err(InvalidSetup(\n\n \"checkpoints can only be log-spaced if the initial time is > 0.0\".to_string(),\n\n ));\n\n }\n\n setup.print_parameters();\n\n\n\n while state.time < end_time {\n\n if state.checkpoint.is_due(state.time, checkpoint_rule) {\n\n state.set_primitive(solver.primitive(state.time));\n\n state.write_checkpoint(setup.as_ref(), &outdir)?;\n\n }\n\n\n\n if !dt_each_iter {\n\n dt = cfl * dx_min / solver.max_wavespeed(state.time, setup.as_ref())\n\n * setup.mesh_scale_factor(state.time);\n\n }\n\n\n", "file_path": "src/main.rs", "rank": 91, "score": 33.08498239475679 }, { "content": "use crate::error::Error;\n\nuse crate::{ExecutionMode, Setup, Recurrence};\n\nuse std::fmt::Write;\n\n\n\n#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n\npub struct CommandLine {\n\n pub use_omp: Option<bool>,\n\n pub use_gpu: Option<bool>,\n\n pub device: Option<i32>,\n\n pub upsample: Option<bool>,\n\n pub setup: Option<String>,\n\n pub resolution: Option<u32>,\n\n pub fold: Option<usize>,\n\n pub checkpoint_interval: Option<f64>,\n\n pub checkpoint_logspace: Option<bool>,\n\n pub time_series_interval: Option<f64>,\n\n pub time_series_logspace: Option<bool>,\n\n pub outdir: Option<String>,\n\n pub end_time: Option<f64>,\n\n pub rk_order: Option<usize>,\n", "file_path": "src/cmdline.rs", "rank": 92, "score": 32.47860389743156 }, { "content": " fn max_wavespeed(&self, _time: f64, _setup: &dyn Setup) -> f64 {\n\n 1.0\n\n }\n\n }\n\n}\n\n\n\npub mod omp {\n\n use super::*;\n\n pub struct Solver(cpu::Solver);\n\n\n\n impl Solver {\n\n pub fn new(\n\n faces: &[f64],\n\n primitive: &[f64],\n\n homologous_parameters: (f64, f64),\n\n boundary_condition: BoundaryCondition,\n\n coords: Coordinates,\n\n scale_factor: f64,\n\n ) -> Self {\n\n let mut solver = cpu::Solver::new(\n", "file_path": "src/sr1d/mod.rs", "rank": 93, "score": 32.22353957242787 }, { "content": " pub cfl_number: Option<f64>,\n\n pub recompute_timestep: Option<String>,\n\n}\n\n\n\nimpl CommandLine {\n\n pub fn parse() -> Result<Self, Error> {\n\n use Error::*;\n\n let mut c = Self::default();\n\n\n\n enum State {\n\n Ready,\n\n Device,\n\n GridResolution,\n\n Fold,\n\n Checkpoint,\n\n TimeSeries,\n\n EndTime,\n\n RkOrder,\n\n Cfl,\n\n Outdir,\n", "file_path": "src/cmdline.rs", "rank": 94, "score": 31.702830955701376 }, { "content": " type Err = error::Error;\n\n fn from_str(parameters: &str) -> Result<Self, Self::Err> {\n\n if parameters.is_empty() {\n\n Ok(Self)\n\n } else {\n\n Err(InvalidSetup(\"setup does not take any parameters\".into()))\n\n }\n\n }\n\n}\n\n\n\nimpl Setup for FastShell {\n\n fn num_primitives(&self) -> usize {\n\n 3\n\n }\n\n\n\n fn solver_name(&self) -> String {\n\n \"euler1d\".to_owned()\n\n }\n\n\n\n fn initial_primitive(&self, r: f64, _y: f64, primitive: &mut [f64]) {\n", "file_path": "src/setups.rs", "rank": 95, "score": 31.33692804530801 }, { "content": " faces,\n\n primitive,\n\n homologous_parameters,\n\n boundary_condition,\n\n coords,\n\n scale_factor,\n\n );\n\n solver.mode = ExecutionMode::OMP;\n\n Self(solver)\n\n }\n\n }\n\n\n\n impl Solve for Solver {\n\n fn primitive(&self, time: f64) -> Vec<f64> {\n\n self.0.primitive(time)\n\n }\n\n fn new_timestep(&mut self, time: f64) {\n\n self.0.new_timestep(time)\n\n }\n\n fn advance_rk(&mut self, setup: &dyn Setup, time: f64, a: f64, dt: f64) {\n", "file_path": "src/sr1d/mod.rs", "rank": 96, "score": 30.318084547314903 }, { "content": " } else {\n\n Recurrence::Linear(self.time_series_interval() * setup.unit_time())\n\n }\n\n }\n\n\n\n pub fn simulation_end_time(&self, setup: &dyn Setup) -> f64 {\n\n self.end_time\n\n .or_else(|| setup.end_time())\n\n .map(|t| t * setup.unit_time())\n\n .unwrap_or(f64::MAX)\n\n }\n\n\n\n pub fn output_directory(&self, restart_file: &Option<String>) -> String {\n\n self.outdir\n\n .clone()\n\n .or_else(|| {\n\n restart_file\n\n .as_deref()\n\n .and_then(crate::parse::parent_dir)\n\n .map(String::from)\n", "file_path": "src/cmdline.rs", "rank": 98, "score": 30.176792230564427 }, { "content": " let structured_mesh = match state.mesh {\n\n Mesh::Structured(mesh) => mesh,\n\n Mesh::FacePositions1D(_) => panic!(\"the patch-based solver requires a StructuredMesh\"),\n\n };\n\n\n\n for (_, patch) in patch_map.into_iter() {\n\n let solver = builder.build(\n\n state.time,\n\n patch,\n\n structured_mesh,\n\n &edge_list,\n\n rk_order,\n\n cline.execution_mode(),\n\n devices.next().flatten(),\n\n setup.clone(),\n\n );\n\n solvers.push(solver)\n\n }\n\n\n\n if std::matches!(checkpoint_rule, Recurrence::Log(_)) && setup.initial_time() <= 0.0 {\n", "file_path": "src/main.rs", "rank": 99, "score": 30.11375502074511 } ]
Rust
tests/mixins.rs
redzic/grass
37c1ada66418fdbb87968ede91efb9be83a80afa
#![cfg(test)] #[macro_use] mod macros; test!( basic_mixin, "@mixin a {\n color: red;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n}\n" ); test!(empty_mixin, "@mixin a {}\n\nb {\n @include a;\n}\n", ""); test!( just_a_comment, "@mixin foo() {\n /* begin foo */\n}\n\na {\n @include foo();\n}\n", "a {\n /* begin foo */\n}\n" ); test!( mixin_two_styles, "@mixin a {\n color: red;\n color: blue;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n color: blue;\n}\n" ); test!( mixin_ruleset, "@mixin a {\n b {\n color: red;\n }\n}\nb {\n @include a;\n}\n", "b b {\n color: red;\n}\n" ); test!( mixin_two_rulesets, "@mixin a {\n b {\n color: red;\n }\n c {\n color: blue;\n }\n}\nd {\n @include a;\n}\n", "d b {\n color: red;\n}\nd c {\n color: blue;\n}\n" ); test!( mixin_ruleset_and_style, "@mixin a {\n b {\n color: red;\n }\n color: blue;\n}\nd {\n @include a;\n}\n", "d {\n color: blue;\n}\nd b {\n color: red;\n}\n" ); test!( mixin_style_and_ruleset, "@mixin a {\n color: blue;\n b {\n color: red;\n}\n}\nd {\n @include a;\n}\n", "d {\n color: blue;\n}\nd b {\n color: red;\n}\n" ); test!( mixin_nested_rulesets, "@mixin a {\n b {\n c {\n color: red;\n}\n}\n}\nd {\n @include a;\n}\n", "d b c {\n color: red;\n}\n" ); test!( mixin_removes_empty_ruleset, "@mixin a {\n color: red; b {\n}\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_variable_scope_one_ruleset, "@mixin a {\n $a: blue;\nb {\n $a: red;\n} color: $a\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_no_args, "@mixin a {\n color: red;\n}\nd {\n @include a();\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_single_arg, "@mixin a($b) {\n color: $b;\n}\nd {\n @include a(red);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_two_args, "@mixin a($b, $c) {\n color: $b;\n color: $c\n}\nd {\n @include a(red, blue);\n}\n", "d {\n color: red;\n color: blue;\n}\n" ); test!( mixin_arg_trailing_comma, "@mixin a($b, $c,) {\n color: $b;\n color: $c\n}\nd {\n @include a(red, blue);\n}\n", "d {\n color: red;\n color: blue;\n}\n" ); test!( mixin_property_interpolation, "@mixin a($b) {\n #{$b}: red;\n}\nd {\n @include a(color);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_style_interpolation, "@mixin a($b) {\n color: #{$b};\n}\nd {\n @include a(red);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_simple_default_value, "@mixin a($b: red) {\n color: $b;\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_second_value_default, "@mixin a($a, $b: blue) {\n color: $a $b;\n}\nd {\n @include a(red);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_default_values, "@mixin a($a: red, $b: blue) {\n color: $a $b;\n}\nd {\n @include a;\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_override_default_value_positionally, "@mixin a($a: red) {\n color: $a;\n}\nd {\n @include a(blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_arg_override_default, "@mixin a($a: red) {\n color: $a;\n}\nd {\n @include a($a: blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_applies_to_second_arg, "@mixin a($a: red, $b) {\n color: $a $b;\n}\nd {\n @include a($b: blue);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_keywords, "@mixin a($a, $b) {\n color: $a $b;\n}\nd {\n @include a($a: red, $b: blue);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_keywords_wrong_direction, "@mixin a($a, $b) {\n color: $a $b;\n}\nd {\n @include a($b: blue, $a: red);\n}\n", "d {\n color: red blue;\n}\n" ); test!( variable_in_call_args, "@mixin a($a) {\n color: $a;\n}\nd {\n $c: red;\n @include a($c);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_positional_call_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(/*foo*/red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_positional_call_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(red/*foo*/);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_keyword_call_arg_val, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: /*foo*/red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_keyword_call_arg_val, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: red/*foo*/);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_keyword_call_arg_name, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(/*foo*/$a: red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_keyword_call_arg_name, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a/*foo*/: red);\n}\n", "d {\n color: red;\n}\n" ); test!( toplevel_include, "@mixin a {\n a {\n color: red;\n }\n}\n\n@include a;\n", "a {\n color: red;\n}\n" ); test!( include_list, "@mixin foo($x) {\n color: $x;\n}\na {\n @include foo(0px 0px 0px 0px #ef8086 inset !important);\n}\n", "a {\n color: 0px 0px 0px 0px #ef8086 inset !important;\n}\n" ); test!( content_without_variable, "@mixin foo {\n @content;\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( content_with_variable, "@mixin foo($a) {\n @content;\n}\n\na {\n @include foo(red) {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( mixin_style_does_not_end_with_semicolon, "@mixin foo {\n color: red\n}\n\na {\n @include foo;\n}\n", "a {\n color: red;\n}\n" ); test!( args_hyphen_arg_allows_underscore, "@mixin foo($a-b) {\n color: $a-b;\n color: $a_b;\n}\na {\n @include foo($a_b: a);\n @include foo($a-b: a);\n}\n", "a {\n color: a;\n color: a;\n color: a;\n color: a;\n}\n" ); test!( args_underscore_arg_allows_hyphen, "@mixin foo($a_b) {\n color: $a-b;\n color: $a_b;\n}\na {\n @include foo($a_b: a);\n @include foo($a-b: a);\n}\n", "a {\n color: a;\n color: a;\n color: a;\n color: a;\n}\n" ); test!( control_flow_in_content, "@mixin foo {\n @content;\n}\n\na {\n @include foo {@if true {color: red;}}\n}\n", "a {\n color: red;\n}\n" ); test!( content_in_control_flow, "@mixin foo() {\n @if true {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( content_inside_unknown_at_rule, "@mixin foo() {\n @foo (max-width: max) {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "@foo (max-width: max) {\n a {\n color: red;\n }\n}\n" ); test!( content_inside_media, "@mixin foo() {\n @media (max-width: max) {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "@media (max-width: max) {\n a {\n color: red;\n }\n}\n" ); error!( function_inside_mixin, "@mixin foo() {\n @function bar() {\n @return foo;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "Error: Mixins may not contain function declarations." ); error!( content_inside_control_flow_outside_mixin, "a {\n @if true {\n @content;\n }\n}\n", "Error: @content is only allowed within mixin declarations." ); error!( undefined_mixin, "a {@include foo;}", "Error: Undefined mixin." ); error!( body_missing_closing_curly_brace, "@mixin foo() {", "Error: expected \"}\"." ); test!( include_empty_args_no_semicolon, "@mixin c {}\n\na {\n @include c()\n}\n", "" ); test!( local_variable_declared_before_mixin_is_still_in_scope, "@mixin foo {}\n\na {\n $a: red;\n @include foo;\n color: $a;\n}\n", "a {\n color: red;\n}\n" ); test!( empty_content_args, "@mixin foo { @content() } a { @include foo { color: red; }; }", "a {\n color: red;\n}\n" ); test!( empty_content_args_using_empty_args, "@mixin foo { @content() } a { @include foo using () { color: red; }; }", "a {\n color: red;\n}\n" ); test!( content_using_one_arg, "@mixin foo { @content(red) } a { @include foo using ($a) { color: $a; } }", "a {\n color: red;\n}\n" ); test!( multiple_content_using_different_args, "@mixin foo { @content(1); @content(2); } @mixin bar { @include foo using ($a) { color: $a } } a { @include bar; }", "a {\n color: 1;\n color: 2;\n}\n" ); test!( chained_content, "@mixin foo { @content; } @mixin bar { @include foo { @content; } } a { @include bar { color: red; } }", "a {\n color: red;\n}\n" ); test!( content_can_access_local_variables, "@mixin foo { @content; } a { $bar: red; @include foo { color: $bar; } }", "a {\n color: red;\n}\n" ); error!( content_using_too_many_args, "@mixin foo { @content(red, blue) } a { @include foo using ($a) { color: $a; } }", "Error: Only 1 argument allowed, but 2 were passed." ); error!( content_using_too_few_args, "@mixin foo { @content() } a { @include foo using ($a) { color: $a; } }", "Error: Missing argument $a." );
#![cfg(test)] #[macro_use] mod macros; test!( basic_mixin, "@mixin a {\n color: red;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n}\n" ); test!(empty_mixin, "@mixin a {}\n\nb {\n @include a;\n}\n", ""); test!( just_a_comment, "@mixin foo() {\n /* begin
color: red;\n }\n}\n\n@include a;\n", "a {\n color: red;\n}\n" ); test!( include_list, "@mixin foo($x) {\n color: $x;\n}\na {\n @include foo(0px 0px 0px 0px #ef8086 inset !important);\n}\n", "a {\n color: 0px 0px 0px 0px #ef8086 inset !important;\n}\n" ); test!( content_without_variable, "@mixin foo {\n @content;\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( content_with_variable, "@mixin foo($a) {\n @content;\n}\n\na {\n @include foo(red) {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( mixin_style_does_not_end_with_semicolon, "@mixin foo {\n color: red\n}\n\na {\n @include foo;\n}\n", "a {\n color: red;\n}\n" ); test!( args_hyphen_arg_allows_underscore, "@mixin foo($a-b) {\n color: $a-b;\n color: $a_b;\n}\na {\n @include foo($a_b: a);\n @include foo($a-b: a);\n}\n", "a {\n color: a;\n color: a;\n color: a;\n color: a;\n}\n" ); test!( args_underscore_arg_allows_hyphen, "@mixin foo($a_b) {\n color: $a-b;\n color: $a_b;\n}\na {\n @include foo($a_b: a);\n @include foo($a-b: a);\n}\n", "a {\n color: a;\n color: a;\n color: a;\n color: a;\n}\n" ); test!( control_flow_in_content, "@mixin foo {\n @content;\n}\n\na {\n @include foo {@if true {color: red;}}\n}\n", "a {\n color: red;\n}\n" ); test!( content_in_control_flow, "@mixin foo() {\n @if true {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "a {\n color: red;\n}\n" ); test!( content_inside_unknown_at_rule, "@mixin foo() {\n @foo (max-width: max) {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "@foo (max-width: max) {\n a {\n color: red;\n }\n}\n" ); test!( content_inside_media, "@mixin foo() {\n @media (max-width: max) {\n @content;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "@media (max-width: max) {\n a {\n color: red;\n }\n}\n" ); error!( function_inside_mixin, "@mixin foo() {\n @function bar() {\n @return foo;\n }\n}\n\na {\n @include foo {\n color: red;\n }\n}\n", "Error: Mixins may not contain function declarations." ); error!( content_inside_control_flow_outside_mixin, "a {\n @if true {\n @content;\n }\n}\n", "Error: @content is only allowed within mixin declarations." ); error!( undefined_mixin, "a {@include foo;}", "Error: Undefined mixin." ); error!( body_missing_closing_curly_brace, "@mixin foo() {", "Error: expected \"}\"." ); test!( include_empty_args_no_semicolon, "@mixin c {}\n\na {\n @include c()\n}\n", "" ); test!( local_variable_declared_before_mixin_is_still_in_scope, "@mixin foo {}\n\na {\n $a: red;\n @include foo;\n color: $a;\n}\n", "a {\n color: red;\n}\n" ); test!( empty_content_args, "@mixin foo { @content() } a { @include foo { color: red; }; }", "a {\n color: red;\n}\n" ); test!( empty_content_args_using_empty_args, "@mixin foo { @content() } a { @include foo using () { color: red; }; }", "a {\n color: red;\n}\n" ); test!( content_using_one_arg, "@mixin foo { @content(red) } a { @include foo using ($a) { color: $a; } }", "a {\n color: red;\n}\n" ); test!( multiple_content_using_different_args, "@mixin foo { @content(1); @content(2); } @mixin bar { @include foo using ($a) { color: $a } } a { @include bar; }", "a {\n color: 1;\n color: 2;\n}\n" ); test!( chained_content, "@mixin foo { @content; } @mixin bar { @include foo { @content; } } a { @include bar { color: red; } }", "a {\n color: red;\n}\n" ); test!( content_can_access_local_variables, "@mixin foo { @content; } a { $bar: red; @include foo { color: $bar; } }", "a {\n color: red;\n}\n" ); error!( content_using_too_many_args, "@mixin foo { @content(red, blue) } a { @include foo using ($a) { color: $a; } }", "Error: Only 1 argument allowed, but 2 were passed." ); error!( content_using_too_few_args, "@mixin foo { @content() } a { @include foo using ($a) { color: $a; } }", "Error: Missing argument $a." );
foo */\n}\n\na {\n @include foo();\n}\n", "a {\n /* begin foo */\n}\n" ); test!( mixin_two_styles, "@mixin a {\n color: red;\n color: blue;\n}\n\nb {\n @include a;\n}\n", "b {\n color: red;\n color: blue;\n}\n" ); test!( mixin_ruleset, "@mixin a {\n b {\n color: red;\n }\n}\nb {\n @include a;\n}\n", "b b {\n color: red;\n}\n" ); test!( mixin_two_rulesets, "@mixin a {\n b {\n color: red;\n }\n c {\n color: blue;\n }\n}\nd {\n @include a;\n}\n", "d b {\n color: red;\n}\nd c {\n color: blue;\n}\n" ); test!( mixin_ruleset_and_style, "@mixin a {\n b {\n color: red;\n }\n color: blue;\n}\nd {\n @include a;\n}\n", "d {\n color: blue;\n}\nd b {\n color: red;\n}\n" ); test!( mixin_style_and_ruleset, "@mixin a {\n color: blue;\n b {\n color: red;\n}\n}\nd {\n @include a;\n}\n", "d {\n color: blue;\n}\nd b {\n color: red;\n}\n" ); test!( mixin_nested_rulesets, "@mixin a {\n b {\n c {\n color: red;\n}\n}\n}\nd {\n @include a;\n}\n", "d b c {\n color: red;\n}\n" ); test!( mixin_removes_empty_ruleset, "@mixin a {\n color: red; b {\n}\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_variable_scope_one_ruleset, "@mixin a {\n $a: blue;\nb {\n $a: red;\n} color: $a\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_no_args, "@mixin a {\n color: red;\n}\nd {\n @include a();\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_single_arg, "@mixin a($b) {\n color: $b;\n}\nd {\n @include a(red);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_two_args, "@mixin a($b, $c) {\n color: $b;\n color: $c\n}\nd {\n @include a(red, blue);\n}\n", "d {\n color: red;\n color: blue;\n}\n" ); test!( mixin_arg_trailing_comma, "@mixin a($b, $c,) {\n color: $b;\n color: $c\n}\nd {\n @include a(red, blue);\n}\n", "d {\n color: red;\n color: blue;\n}\n" ); test!( mixin_property_interpolation, "@mixin a($b) {\n #{$b}: red;\n}\nd {\n @include a(color);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_style_interpolation, "@mixin a($b) {\n color: #{$b};\n}\nd {\n @include a(red);\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_simple_default_value, "@mixin a($b: red) {\n color: $b;\n}\nd {\n @include a;\n}\n", "d {\n color: red;\n}\n" ); test!( mixin_second_value_default, "@mixin a($a, $b: blue) {\n color: $a $b;\n}\nd {\n @include a(red);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_default_values, "@mixin a($a: red, $b: blue) {\n color: $a $b;\n}\nd {\n @include a;\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_override_default_value_positionally, "@mixin a($a: red) {\n color: $a;\n}\nd {\n @include a(blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_arg_override_default, "@mixin a($a: red) {\n color: $a;\n}\nd {\n @include a($a: blue);\n}\n", "d {\n color: blue;\n}\n" ); test!( mixin_keyword_applies_to_second_arg, "@mixin a($a: red, $b) {\n color: $a $b;\n}\nd {\n @include a($b: blue);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_keywords, "@mixin a($a, $b) {\n color: $a $b;\n}\nd {\n @include a($a: red, $b: blue);\n}\n", "d {\n color: red blue;\n}\n" ); test!( mixin_two_keywords_wrong_direction, "@mixin a($a, $b) {\n color: $a $b;\n}\nd {\n @include a($b: blue, $a: red);\n}\n", "d {\n color: red blue;\n}\n" ); test!( variable_in_call_args, "@mixin a($a) {\n color: $a;\n}\nd {\n $c: red;\n @include a($c);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_positional_call_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(/*foo*/red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_positional_call_arg, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(red/*foo*/);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_keyword_call_arg_val, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: /*foo*/red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_keyword_call_arg_val, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a: red/*foo*/);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_before_keyword_call_arg_name, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a(/*foo*/$a: red);\n}\n", "d {\n color: red;\n}\n" ); test!( comment_after_keyword_call_arg_name, "@mixin a($a) {\n color: $a;\n}\nd {\n @include a($a/*foo*/: red);\n}\n", "d {\n color: red;\n}\n" ); test!( toplevel_include, "@mixin a {\n a {\n
random
[ { "content": "#![cfg(test)]\n\n\n\n#[macro_export]\n\nmacro_rules! test {\n\n ($( #[$attr:meta] ),*$func:ident, $input:expr) => {\n\n $(#[$attr])*\n\n #[test]\n\n #[allow(non_snake_case)]\n\n fn $func() {\n\n let sass = grass::from_string($input.to_string())\n\n .expect(concat!(\"failed to parse on \", $input));\n\n assert_eq!(\n\n String::from($input),\n\n sass\n\n );\n\n }\n\n };\n\n ($( #[$attr:meta] ),*$func:ident, $input:expr, $output:expr) => {\n\n $(#[$attr])*\n\n #[test]\n", "file_path": "tests/macros.rs", "rank": 0, "score": 95297.34189461524 }, { "content": " #[allow(non_snake_case)]\n\n fn $func() {\n\n let sass = grass::from_string($input.to_string())\n\n .expect(concat!(\"failed to parse on \", $input));\n\n assert_eq!(\n\n String::from($output),\n\n sass\n\n );\n\n }\n\n };\n\n}\n\n\n\n/// Verify the error *message*\n\n/// Span and scope information are not yet tested\n\n#[macro_export]\n\nmacro_rules! error {\n\n ($( #[$attr:meta] ),*$func:ident, $input:expr, $err:expr) => {\n\n $(#[$attr])*\n\n #[test]\n\n #[allow(non_snake_case)]\n", "file_path": "tests/macros.rs", "rank": 1, "score": 95296.32550770204 }, { "content": " fn $func() {\n\n match grass::from_string($input.to_string()) {\n\n Ok(..) => panic!(\"did not fail\"),\n\n Err(e) => assert_eq!($err, e.to_string()\n\n .chars()\n\n .take_while(|c| *c != '\\n')\n\n .collect::<String>()\n\n .as_str()\n\n ),\n\n }\n\n }\n\n };\n\n}\n", "file_path": "tests/macros.rs", "rank": 2, "score": 95286.84070901299 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(preserves_named_color_case, \"a {\\n color: OrAnGe;\\n}\\n\");\n\ntest!(\n\n named_color_casing_is_color,\n\n \"a {\\n color: hue(RED);\\n}\\n\",\n\n \"a {\\n color: 0deg;\\n}\\n\"\n\n);\n\ntest!(preserves_hex_color_case, \"a {\\n color: #FfFfFf;\\n}\\n\");\n\ntest!(\n\n preserves_hex_8_val_10000000,\n\n \"a {\\n color: #10000000;\\n}\\n\"\n\n);\n\ntest!(\n\n preserves_hex_8_val_12312312,\n\n \"a {\\n color: #12312312;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 21, "score": 94677.63513002843 }, { "content": " ident_plus_color,\n\n \"a {\\n color: foo + red;\\n}\\n\",\n\n \"a {\\n color: foored;\\n}\\n\"\n\n);\n\ntest!(\n\n color_minus_ident,\n\n \"a {\\n color: red - foo;\\n}\\n\",\n\n \"a {\\n color: red-foo;\\n}\\n\"\n\n);\n\ntest!(\n\n color_minus_dbl_quote_ident,\n\n \"a {\\n color: red - \\\"foo\\\";\\n}\\n\",\n\n \"a {\\n color: red-\\\"foo\\\";\\n}\\n\"\n\n);\n\ntest!(\n\n color_minus_sgl_quote_ident,\n\n \"a {\\n color: red - 'foo';\\n}\\n\",\n\n \"a {\\n color: red-\\\"foo\\\";\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 22, "score": 94674.86875862977 }, { "content": ");\n\ntest!(\n\n rgba_1_arg,\n\n \"a {\\n color: rgba(74.7% 173 93%);\\n}\\n\",\n\n \"a {\\n color: #beaded;\\n}\\n\"\n\n);\n\ntest!(\n\n hsla_1_arg,\n\n \"a {\\n color: hsla(60 60% 50%);\\n}\\n\",\n\n \"a {\\n color: #cccc33;\\n}\\n\"\n\n);\n\ntest!(\n\n hsla_1_arg_weird_units,\n\n \"a {\\n color: hsla(60foo 60foo 50foo);\\n}\\n\",\n\n \"a {\\n color: #cccc33;\\n}\\n\"\n\n);\n\ntest!(\n\n sass_spec__spec_colors_basic,\n\n \"p {\n\n color: rgb(255, 128, 0);\n", "file_path": "tests/color.rs", "rank": 23, "score": 94674.23114843032 }, { "content": " color_minus_important,\n\n \"a {\\n color: red - !important;\\n}\\n\",\n\n \"a {\\n color: red-!important;\\n}\\n\"\n\n);\n\ntest!(\n\n color_minus_null,\n\n \"a {\\n color: red - null;\\n}\\n\",\n\n \"a {\\n color: red-;\\n}\\n\"\n\n);\n\ntest!(\n\n ident_minus_color,\n\n \"a {\\n color: foo - red;\\n}\\n\",\n\n \"a {\\n color: foo-red;\\n}\\n\"\n\n);\n\ntest!(\n\n hue,\n\n \"a {\\n color: hue(hsl(193, 67%, 28%));\\n}\\n\",\n\n \"a {\\n color: 193deg;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 24, "score": 94673.75173827937 }, { "content": " hsl_hue_above_max,\n\n \"a {\\n color: hsl(540, 100%, 50%);\\n}\\n\",\n\n \"a {\\n color: aqua;\\n}\\n\"\n\n);\n\ntest!(\n\n hsl_hue_below_min,\n\n \"a {\\n color: hsl(-540, 100%, 50%);\\n}\\n\",\n\n \"a {\\n color: aqua;\\n}\\n\"\n\n);\n\ntest!(\n\n hsla_named,\n\n \"a {\\n color: hsla($hue: 193, $saturation: 67%, $lightness: 99, $alpha: .6);\\n}\\n\",\n\n \"a {\\n color: rgba(251, 253, 254, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n\n color_plus_ident,\n\n \"a {\\n color: red + foo;\\n}\\n\",\n\n \"a {\\n color: redfoo;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 25, "score": 94672.51499613325 }, { "content": " hsl_doesnt_care_about_units,\n\n \"a {\\n color: hsl(193deg, 67foo, 99%);\\n}\\n\",\n\n \"a {\\n color: #fbfdfe;\\n}\\n\"\n\n);\n\ntest!(\n\n hsl_named,\n\n \"a {\\n color: hsl($hue: 193, $saturation: 67%, $lightness: 99);\\n}\\n\",\n\n \"a {\\n color: #fbfdfe;\\n}\\n\"\n\n);\n\ntest!(\n\n hsl_four_args,\n\n \"a {\\n color: hsl(0, 0, 0, 0.456);\\n}\\n\",\n\n \"a {\\n color: rgba(0, 0, 0, 0.456);\\n}\\n\"\n\n);\n\ntest!(\n\n hsl_negative_hue,\n\n \"a {\\n color: hsl(-60deg, 100%, 50%);\\n}\\n\",\n\n \"a {\\n color: fuchsia;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 26, "score": 94672.33294866879 }, { "content": " color: red green blue;\n\n color: (red) (green) (blue);\n\n color: red + hux;\n\n color: unquote(\\\"red\\\") + green;\n\n foo: rgb(200, 150%, 170%);\n\n}\n\n\",\n\n \"p {\\n color: #ff8000;\\n color: red green blue;\\n color: red green blue;\\n color: redhux;\\n color: redgreen;\\n foo: #c8ffff;\\n}\\n\"\n\n);\n\ntest!(\n\n sass_spec__spec_colors_change_color,\n\n \"p {\n\n color: change-color(#102030, $blue: 5);\n\n color: change-color(#102030, $alpha: .325);\n\n color: change-color(#102030, $red: 120, $blue: 5);\n\n color: change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8);\n\n}\n\n\",\n\n \"p {\\n color: #102005;\\n color: rgba(16, 32, 48, 0.325);\\n color: #782005;\\n color: rgba(204, 85, 0, 0.8);\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 27, "score": 94670.59320946888 }, { "content": "test!(\n\n preserves_hex_8_val_ab234cff,\n\n \"a {\\n color: #ab234cff;\\n}\\n\"\n\n);\n\ntest!(preserves_hex_6_val_000000, \"a {\\n color: #000000;\\n}\\n\");\n\ntest!(preserves_hex_6_val_123123, \"a {\\n color: #123123;\\n}\\n\");\n\ntest!(preserves_hex_6_val_ab234c, \"a {\\n color: #ab234c;\\n}\\n\");\n\ntest!(preserves_hex_4_val_0000, \"a {\\n color: #0000;\\n}\\n\");\n\ntest!(preserves_hex_4_val_123a, \"a {\\n color: #123a;\\n}\\n\");\n\ntest!(preserves_hex_4_val_ab2f, \"a {\\n color: #ab2f;\\n}\\n\");\n\ntest!(preserves_hex_3_val_000, \"a {\\n color: #000;\\n}\\n\");\n\ntest!(preserves_hex_3_val_123, \"a {\\n color: #123;\\n}\\n\");\n\ntest!(preserves_hex_3_val_ab2, \"a {\\n color: #ab2;\\n}\\n\");\n\ntest!(\n\n converts_rgb_to_named_color,\n\n \"a {\\n color: rgb(0, 0, 0);\\n}\\n\",\n\n \"a {\\n color: black;\\n}\\n\"\n\n);\n\ntest!(\n\n converts_rgba_to_named_color_red,\n", "file_path": "tests/color.rs", "rank": 28, "score": 94669.0722786397 }, { "content": " \"a {\\n color: rgb(255, 0, 0, 255);\\n}\\n\",\n\n \"a {\\n color: red;\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_negative,\n\n \"a {\\n color: rgb(-1, 1, 1);\\n}\\n\",\n\n \"a {\\n color: #000101;\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_binop,\n\n \"a {\\n color: rgb(1, 2, 1+2);\\n}\\n\",\n\n \"a {\\n color: #010203;\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_pads_0,\n\n \"a {\\n color: rgb(1, 2, 3);\\n}\\n\",\n\n \"a {\\n color: #010203;\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_percent,\n", "file_path": "tests/color.rs", "rank": 29, "score": 94668.88247579022 }, { "content": "test!(\n\n fade_out,\n\n \"a {\\n color: fade-out(rgba(0, 0, 0, 0.8), 0.2);\\n}\\n\",\n\n \"a {\\n color: rgba(0, 0, 0, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n\n opacify,\n\n \"a {\\n color: opacify(rgba(0, 0, 0, 0.5), 0.1);\\n}\\n\",\n\n \"a {\\n color: rgba(0, 0, 0, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n\n fade_in,\n\n \"a {\\n color: opacify(rgba(0, 0, 17, 0.8), 0.2);\\n}\\n\",\n\n \"a {\\n color: #000011;\\n}\\n\"\n\n);\n\ntest!(\n\n grayscale_1,\n\n \"a {\\n color: grayscale(plum);\\n}\\n\",\n\n \"a {\\n color: #bfbfbf;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 30, "score": 94668.82435683062 }, { "content": " \"a {\\n color: alpha(#0123);\\n}\\n\",\n\n \"a {\\n color: 0.2;\\n}\\n\"\n\n);\n\ntest!(\n\n alpha_function_named_color,\n\n \"a {\\n color: alpha(red);\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(opacity_function_number, \"a {\\n color: opacity(1);\\n}\\n\");\n\ntest!(\n\n opacity_function_number_unit,\n\n \"a {\\n color: opacity(1px);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_one_arg,\n\n \"a {\\n color: rgba(1 2 3);\\n}\\n\",\n\n \"a {\\n color: #010203;\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_two_args,\n", "file_path": "tests/color.rs", "rank": 31, "score": 94668.81264210385 }, { "content": " hue_rgb_all_equal,\n\n \"a {\\n color: hue(rgb(1, 1, 1));\\n}\\n\",\n\n \"a {\\n color: 0deg;\\n}\\n\"\n\n);\n\ntest!(\n\n saturation,\n\n \"a {\\n color: saturation(hsl(193, 67%, 28%));\\n}\\n\",\n\n \"a {\\n color: 67%;\\n}\\n\"\n\n);\n\ntest!(\n\n saturation_2,\n\n \"$a: hsl(1, 1, 10);\\n\\na {\\n color: saturation($a);\\n}\\n\",\n\n \"a {\\n color: 1%;\\n}\\n\"\n\n);\n\ntest!(\n\n lightness,\n\n \"a {\\n color: lightness(hsl(193, 67%, 28%));\\n}\\n\",\n\n \"a {\\n color: 28%;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 32, "score": 94668.79552399376 }, { "content": ");\n\ntest!(\n\n mix_weight_25,\n\n \"a {\\n color: mix(#f00, #00f, 25%);\\n}\\n\",\n\n \"a {\\n color: #4000bf;\\n}\\n\"\n\n);\n\ntest!(\n\n mix_opacity,\n\n \"a {\\n color: mix(rgba(255, 0, 0, 0.5), #00f);\\n}\\n\",\n\n \"a {\\n color: rgba(64, 0, 191, 0.75);\\n}\\n\"\n\n);\n\ntest!(\n\n mix_sanity_check,\n\n \"a {\\n color: mix(black, white);\\n}\\n\",\n\n \"a {\\n color: gray;\\n}\\n\"\n\n);\n\ntest!(\n\n change_color_blue,\n\n \"a {\\n color: change-color(#102030, $blue: 5);\\n}\\n\",\n\n \"a {\\n color: #102005;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 33, "score": 94668.7151471591 }, { "content": "test!(\n\n transparent_from_function,\n\n \"a {\\n color: rgb(transparent, 0);\\n}\\n\",\n\n \"a {\\n color: rgba(0, 0, 0, 0);\\n}\\n\"\n\n);\n\ntest!(\n\n named_color_transparent_opacity,\n\n \"a {\\n color: opacity(transparent);\\n}\\n\",\n\n \"a {\\n color: 0;\\n}\\n\"\n\n);\n\ntest!(\n\n negative_values_in_rgb,\n\n \"a {\\n color: rgb(-1 -1 -1);\\n}\\n\",\n\n \"a {\\n color: black;\\n}\\n\"\n\n);\n\ntest!(\n\n negative_values_in_hsl,\n\n \"a {\\n color: hsl(-1 -1 -1);\\n}\\n\",\n\n \"a {\\n color: black;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 34, "score": 94668.7162832238 }, { "content": " \"a {\\n color: rgb(#123, 0);\\n}\\n\",\n\n \"a {\\n color: rgba(17, 34, 51, 0);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_two_args,\n\n \"a {\\n color: rgba(red, 0.5);\\n}\\n\",\n\n \"a {\\n color: rgba(255, 0, 0, 0.5);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_opacity_over_1,\n\n \"a {\\n color: rgba(1, 2, 3, 3);\\n}\\n\",\n\n \"a {\\n color: #010203;\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_negative_alpha,\n\n \"a {\\n color: rgba(1, 2, 3, -10%);\\n}\\n\",\n\n \"a {\\n color: rgba(1, 2, 3, 0);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_opacity_decimal,\n", "file_path": "tests/color.rs", "rank": 35, "score": 94668.7099170392 }, { "content": ");\n\ntest!(\n\n change_color_red_blue,\n\n \"a {\\n color: change-color(#102030, $red: 120, $blue: 5);\\n}\\n\",\n\n \"a {\\n color: #782005;\\n}\\n\"\n\n);\n\ntest!(\n\n change_color_lum_alpha,\n\n \"a {\\n color: change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8);\\n}\\n\",\n\n \"a {\\n color: rgba(204, 85, 0, 0.8);\\n}\\n\"\n\n);\n\ntest!(\n\n adjust_color_blue,\n\n \"a {\\n color: adjust-color(#102030, $blue: 5);\\n}\\n\",\n\n \"a {\\n color: #102035;\\n}\\n\"\n\n);\n\ntest!(\n\n adjust_color_negative,\n\n \"a {\\n color: adjust-color(#102030, $red: -5, $blue: 5);\\n}\\n\",\n\n \"a {\\n color: #0b2035;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 36, "score": 94668.69678221308 }, { "content": "test!(\n\n grayscale_2,\n\n \"a {\\n color: grayscale(red);\\n}\\n\",\n\n \"a {\\n color: gray;\\n}\\n\"\n\n);\n\ntest!(grayscale_number, \"a {\\n color: grayscale(15%);\\n}\\n\");\n\n// handle special functions better!\n\n// test!(\n\n// grayscale_number_casing,\n\n// \"a {\\n color: grAyscaLe(15%);\\n}\\n\"\n\n// );\n\ntest!(\n\n complement,\n\n \"a {\\n color: complement(red);\\n}\\n\",\n\n \"a {\\n color: aqua;\\n}\\n\"\n\n);\n\ntest!(\n\n mix_no_weight,\n\n \"a {\\n color: mix(#f00, #00f);\\n}\\n\",\n\n \"a {\\n color: purple;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 37, "score": 94668.69620787964 }, { "content": "test!(\n\n desaturate_basic,\n\n \"a {\\n color: desaturate(hsl(120, 30%, 90%), 20%);\\n}\\n\",\n\n \"a {\\n color: #e3e8e3;\\n}\\n\"\n\n);\n\ntest!(\n\n desaturate_3_hex,\n\n \"a {\\n color: desaturate(#855, 20%);\\n}\\n\",\n\n \"a {\\n color: #726b6b;\\n}\\n\"\n\n);\n\ntest!(\n\n desaturate_correctly_calculates_hue,\n\n \"a {\\n color: desaturate(plum, 14%);\\n}\\n\",\n\n \"a {\\n color: #d4a9d4;\\n}\\n\"\n\n);\n\ntest!(\n\n transparentize,\n\n \"a {\\n color: transparentize(rgba(0, 0, 0, 0.5), 0.1);\\n}\\n\",\n\n \"a {\\n color: rgba(0, 0, 0, 0.4);\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 38, "score": 94668.68167448616 }, { "content": "test!(\n\n saturate_one_arg,\n\n \"a {\\n color: saturate($amount: 50%);\\n}\\n\",\n\n \"a {\\n color: saturate(50%);\\n}\\n\"\n\n);\n\ntest!(\n\n saturate_basic,\n\n \"a {\\n color: saturate(hsl(120, 30%, 90%), 20%);\\n}\\n\",\n\n \"a {\\n color: #d9f2d9;\\n}\\n\"\n\n);\n\ntest!(\n\n saturate_3_hex,\n\n \"a {\\n color: saturate(#855, 20%);\\n}\\n\",\n\n \"a {\\n color: #9e3f3f;\\n}\\n\"\n\n);\n\ntest!(\n\n desaturate_named_args,\n\n \"a {\\n color: desaturate($color: hsl(25, 100%, 80%), $amount: 30%);\\n}\\n\",\n\n \"a {\\n color: #f0c6a8;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 39, "score": 94668.66245490435 }, { "content": " \"a {\\n color: rgba(159%, 169, 169%, 50%);\\n}\\n\",\n\n \"a {\\n color: rgba(255, 169, 255, 0.5);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_percent_round_up,\n\n \"a {\\n color: rgba(59%, 169, 69%, 50%);\\n}\\n\",\n\n \"a {\\n color: rgba(150, 169, 176, 0.5);\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_double_digits,\n\n \"a {\\n color: rgb(254, 255, 255);\\n}\\n\",\n\n \"a {\\n color: #feffff;\\n}\\n\"\n\n);\n\ntest!(\n\n rgb_double_digits_white,\n\n \"a {\\n color: rgb(255, 255, 255);\\n}\\n\",\n\n \"a {\\n color: white;\\n}\\n\"\n\n);\n\ntest!(\n\n alpha_function_4_hex,\n", "file_path": "tests/color.rs", "rank": 40, "score": 94668.65357647417 }, { "content": " invert_no_weight,\n\n \"a {\\n color: invert(white);\\n}\\n\",\n\n \"a {\\n color: black;\\n}\\n\"\n\n);\n\ntest!(invert_number, \"a {\\n color: invert(10%);\\n}\\n\");\n\ntest!(invert_number_casing, \"a {\\n color: iNveRt(10%);\\n}\\n\");\n\ntest!(\n\n invert_weight_percent,\n\n \"a {\\n color: invert(white, 20%);\\n}\\n\",\n\n \"a {\\n color: #cccccc;\\n}\\n\"\n\n);\n\ntest!(\n\n invert_weight_percent_turquoise,\n\n \"a {\\n color: invert(turquoise, 23%);\\n}\\n\",\n\n \"a {\\n color: #5db4ab;\\n}\\n\"\n\n);\n\ntest!(\n\n invert_weight_no_unit,\n\n \"a {\\n color: invert(white, 20);\\n}\\n\",\n\n \"a {\\n color: #cccccc;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 41, "score": 94668.63865843255 }, { "content": ");\n\ntest!(\n\n adjust_color_lum_alpha,\n\n \"a {\\n color: adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4);\\n}\\n\",\n\n \"a {\\n color: rgba(255, 106, 0, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n\n scale_color_lightness,\n\n \"a {\\n color: scale-color(hsl(120, 70%, 80%), $lightness: 50%);\\n}\\n\",\n\n \"a {\\n color: #d4f7d4;\\n}\\n\"\n\n);\n\ntest!(\n\n scale_color_negative,\n\n \"a {\\n color: scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%);\\n}\\n\",\n\n \"a {\\n color: #c899ff;\\n}\\n\"\n\n);\n\ntest!(\n\n scale_color_alpha,\n\n \"a {\\n color: scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%);\\n}\\n\",\n\n \"a {\\n color: rgba(200, 205, 208, 0.7);\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 42, "score": 94668.60943760017 }, { "content": "test!(\n\n interpolation_after_hash_containing_only_hex_chars,\n\n \"a {\\n color: ##{123};\\n color: type-of(##{123});\\n}\\n\",\n\n \"a {\\n color: #123;\\n color: string;\\n}\\n\"\n\n);\n\ntest!(\n\n non_hex_chars_after_hash_are_still_touching_hash,\n\n \"a {\\n color: #ooobar;\\n}\\n\",\n\n \"a {\\n color: #ooobar;\\n}\\n\"\n\n);\n\ntest!(\n\n more_than_8_hex_chars_after_hash_starts_with_letter,\n\n \"a {\\n color: #ffffffffff;\\n}\\n\",\n\n \"a {\\n color: #ffffffffff;\\n}\\n\"\n\n);\n\ntest!(\n\n more_than_8_hex_chars_after_hash_starts_with_number,\n\n \"a {\\n color: #0000000000;\\n}\\n\",\n\n \"a {\\n color: #00000000 0;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 43, "score": 94668.56157926795 }, { "content": "test!(\n\n more_than_8_hex_chars_after_hash_starts_with_number_contains_hex_char,\n\n \"a {\\n color: #00000000f00;\\n}\\n\",\n\n \"a {\\n color: #00000000 f00;\\n}\\n\"\n\n);\n\ntest!(\n\n all_three_rgb_channels_have_decimal,\n\n \"a {\\n color: rgba(1.5, 1.5, 1.5, 1);\\n}\\n\",\n\n \"a {\\n color: #020202;\\n}\\n\"\n\n);\n\ntest!(\n\n builtin_fn_red_rounds_channel,\n\n \"a {\\n color: red(rgba(1.5, 1.5, 1.5, 1));\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n builtin_fn_green_rounds_channel,\n\n \"a {\\n color: green(rgba(1.5, 1.5, 1.5, 1));\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n builtin_fn_blue_rounds_channel,\n\n \"a {\\n color: blue(rgba(1.5, 1.5, 1.5, 1));\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 44, "score": 94668.54994321895 }, { "content": " hue_maintains_value_when_created_through_hsl,\n\n \"a {\\n color: hue(hsl(0.544, 100%, 100%));\\n}\\n\",\n\n \"a {\\n color: 0.544deg;\\n}\\n\"\n\n);\n\ntest!(\n\n hue_red_equals_blue,\n\n \"a {\\n color: hue(rgb(1, 0, 1));\\n}\\n\",\n\n \"a {\\n color: 300deg;\\n}\\n\"\n\n);\n\ntest!(\n\n hue_green_equals_blue,\n\n \"a {\\n color: hue(rgb(0, 1, 1));\\n}\\n\",\n\n \"a {\\n color: 180deg;\\n}\\n\"\n\n);\n\ntest!(\n\n hue_green_is_1,\n\n \"a {\\n color: hue(rgb(0, 1, 0));\\n}\\n\",\n\n \"a {\\n color: 120deg;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 45, "score": 94668.48795838468 }, { "content": ");\n\ntest!(\n\n lighten_named_args,\n\n \"a {\\n color: lighten($color: hsl(0, 0%, 0%), $amount: 30%);\\n}\\n\",\n\n \"a {\\n color: #4d4d4d;\\n}\\n\"\n\n);\n\ntest!(\n\n lighten_basic,\n\n \"a {\\n color: lighten(hsl(0, 0%, 0%), 30%);\\n}\\n\",\n\n \"a {\\n color: #4d4d4d;\\n}\\n\"\n\n);\n\ntest!(\n\n lighten_3_hex,\n\n \"a {\\n color: lighten(#800, 20%);\\n}\\n\",\n\n // eventually, this should become `#e00`\n\n // blocked on recognizing when to use 3-hex over 6-hex\n\n \"a {\\n color: #ee0000;\\n}\\n\"\n\n);\n\ntest!(\n\n darken_named_args,\n", "file_path": "tests/color.rs", "rank": 46, "score": 94668.43053234176 }, { "content": ");\n\ntest!(\n\n scale_color_alpha_over_1,\n\n \"a {\\n color: scale-color(sienna, $alpha: -70%);\\n}\\n\",\n\n \"a {\\n color: rgba(160, 82, 45, 0.3);\\n}\\n\"\n\n);\n\ntest!(\n\n ie_hex_str_hex_3,\n\n \"a {\\n color: ie-hex-str(#abc);\\n}\\n\",\n\n \"a {\\n color: #FFAABBCC;\\n}\\n\"\n\n);\n\ntest!(\n\n ie_hex_str_hex_6,\n\n \"a {\\n color: ie-hex-str(#3322BB);\\n}\\n\",\n\n \"a {\\n color: #FF3322BB;\\n}\\n\"\n\n);\n\ntest!(\n\n ie_hex_str_rgb,\n\n \"a {\\n color: ie-hex-str(rgba(0, 255, 0, 0.5));\\n}\\n\",\n\n \"a {\\n color: #8000FF00;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 47, "score": 94668.41246076014 }, { "content": ");\n\ntest!(\n\n adjust_hue_positive,\n\n \"a {\\n color: adjust-hue(hsl(120, 30%, 90%), 60deg);\\n}\\n\",\n\n \"a {\\n color: #deeded;\\n}\\n\"\n\n);\n\ntest!(\n\n adjust_hue_negative,\n\n \"a {\\n color: adjust-hue(hsl(120, 30%, 90%), -60deg);\\n}\\n\",\n\n \"a {\\n color: #ededde;\\n}\\n\"\n\n);\n\ntest!(\n\n adjust_hue_3_hex,\n\n \"a {\\n color: adjust-hue(#811, 45deg);\\n}\\n\",\n\n \"a {\\n color: #886a11;\\n}\\n\"\n\n);\n\ntest!(\n\n adjust_hue_named_args,\n\n \"a {\\n color: adjust-hue($color: hsl(120, 30%, 90%), $degrees: 60deg);\\n}\\n\",\n\n \"a {\\n color: #deeded;\\n}\\n\"\n", "file_path": "tests/color.rs", "rank": 48, "score": 94668.37579279573 }, { "content": " \"a {\\n color: darken($color: hsl(25, 100%, 80%), $amount: 30%);\\n}\\n\",\n\n \"a {\\n color: #ff6a00;\\n}\\n\"\n\n);\n\ntest!(\n\n darken_basic,\n\n \"a {\\n color: darken(hsl(25, 100%, 80%), 30%);\\n}\\n\",\n\n \"a {\\n color: #ff6a00;\\n}\\n\"\n\n);\n\ntest!(\n\n darken_3_hex,\n\n \"a {\\n color: darken(#800, 20%);\\n}\\n\",\n\n // eventually, this should become `#200`\n\n // blocked on recognizing when to use 3-hex over 6-hex\n\n \"a {\\n color: #220000;\\n}\\n\"\n\n);\n\ntest!(\n\n saturate_named_args,\n\n \"a {\\n color: saturate($color: hsl(25, 100%, 80%), $amount: 30%);\\n}\\n\",\n\n \"a {\\n color: #ffc499;\\n}\\n\"\n\n);\n", "file_path": "tests/color.rs", "rank": 49, "score": 94668.2965404661 }, { "content": ");\n\nerror!(\n\n hsl_no_args,\n\n \"a {\\n color: hsl();\\n}\\n\", \"Error: Missing argument $channels.\"\n\n);\n\nerror!(\n\n hsla_no_args,\n\n \"a {\\n color: hsla();\\n}\\n\", \"Error: Missing argument $channels.\"\n\n);\n\ntest!(\n\n hsl_basic,\n\n \"a {\\n color: hsl(193, 67%, 99);\\n}\\n\",\n\n \"a {\\n color: #fbfdfe;\\n}\\n\"\n\n);\n\ntest!(\n\n hsla_basic,\n\n \"a {\\n color: hsla(193, 67%, 99, .6);\\n}\\n\",\n\n \"a {\\n color: rgba(251, 253, 254, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/color.rs", "rank": 50, "score": 94668.17692510886 }, { "content": " \"a {\\n color: rgba(1, 2, 3, .6);\\n}\\n\",\n\n \"a {\\n color: rgba(1, 2, 3, 0.6);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_opacity_percent,\n\n \"a {\\n color: rgba(1, 2, 3, 50%);\\n}\\n\",\n\n \"a {\\n color: rgba(1, 2, 3, 0.5);\\n}\\n\"\n\n);\n\ntest!(\n\n rgba_3_args,\n\n \"a {\\n color: rgba(7.1%, 20.4%, 33.9%);\\n}\\n\",\n\n \"a {\\n color: #123456;\\n}\\n\"\n\n);\n\nerror!(\n\n rgb_no_args,\n\n \"a {\\n color: rgb();\\n}\\n\", \"Error: Missing argument $channels.\"\n\n);\n\nerror!(\n\n rgba_no_args,\n\n \"a {\\n color: rgba();\\n}\\n\", \"Error: Missing argument $channels.\"\n", "file_path": "tests/color.rs", "rank": 51, "score": 94667.74196593263 }, { "content": "};\n\n\n\nuse crate::value::Number;\n\npub(crate) use name::NAMED_COLORS;\n\n\n\nuse num_traits::{One, Signed, ToPrimitive, Zero};\n\n\n\nmod name;\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n\npub(crate) struct Color {\n\n rgba: Rgba,\n\n hsla: Option<Hsla>,\n\n repr: String,\n\n}\n\n\n\nimpl Color {\n\n pub const fn new_rgba(\n\n red: Number,\n\n green: Number,\n", "file_path": "src/color/mod.rs", "rank": 52, "score": 93606.1930187257 }, { "content": " /// Change `alpha` to value given\n\n pub fn with_alpha(self, alpha: Number) -> Self {\n\n Color::from_rgba(self.red(), self.green(), self.blue(), alpha)\n\n }\n\n\n\n /// Makes a color more opaque.\n\n /// Takes a color and a number between 0 and 1,\n\n /// and returns a color with the opacity increased by that amount.\n\n pub fn fade_in(self, amount: Number) -> Self {\n\n Color::from_rgba(self.red(), self.green(), self.blue(), self.alpha() + amount)\n\n }\n\n\n\n /// Makes a color more transparent.\n\n /// Takes a color and a number between 0 and 1,\n\n /// and returns a color with the opacity decreased by that amount.\n\n pub fn fade_out(self, amount: Number) -> Self {\n\n Color::from_rgba(self.red(), self.green(), self.blue(), self.alpha() - amount)\n\n }\n\n}\n\n\n", "file_path": "src/color/mod.rs", "rank": 53, "score": 93603.33847633148 }, { "content": "//! A color is internally represented as either RGBA or HSLA.\n\n//!\n\n//! Colors can be constructed in Sass through names (e.g. red, blue, aqua)\n\n//! or the builtin functions `rgb()`, `rgba()`, `hsl()`, and `hsla()`,\n\n//! all of which can accept 1-4 arguments.\n\n//!\n\n//! It is necessary to retain the original values with which the\n\n//! color was constructed.\n\n//! E.g. `hsla(.999999999999, 100, 100, 1)` should retain its full HSLA\n\n//! values to an arbitrary precision.\n\n//!\n\n//! Color values matching named colors are implicitly converted to named colors\n\n//! E.g. `rgba(255, 0, 0, 1)` => `red`\n\n//!\n\n//! Named colors retain their original casing,\n\n//! so `rEd` should be emitted as `rEd`.\n\n\n\nuse std::{\n\n cmp::{max, min},\n\n fmt::{self, Display},\n", "file_path": "src/color/mod.rs", "rank": 54, "score": 93603.09288203486 }, { "content": " let hue = if hue > Number::from(180) {\n\n Number::from(360) - hue\n\n } else {\n\n hue + Number::from(180)\n\n };\n\n Color::from_hsla(hue, saturation, luminance, alpha)\n\n }\n\n}\n\n\n\n/// Opacity color functions\n\nimpl Color {\n\n pub fn alpha(&self) -> Number {\n\n let a = self.rgba.alpha();\n\n if a > Number::one() {\n\n a / Number::from(255)\n\n } else {\n\n a\n\n }\n\n }\n\n\n", "file_path": "src/color/mod.rs", "rank": 55, "score": 93602.85536647272 }, { "content": " blue: Number,\n\n alpha: Number,\n\n repr: String,\n\n ) -> Color {\n\n Color {\n\n rgba: Rgba::new(red, green, blue, alpha),\n\n hsla: None,\n\n repr,\n\n }\n\n }\n\n\n\n const fn new_hsla(\n\n red: Number,\n\n green: Number,\n\n blue: Number,\n\n alpha: Number,\n\n hsla: Hsla,\n\n repr: String,\n\n ) -> Color {\n\n Color {\n\n rgba: Rgba::new(red, green, blue, alpha),\n\n hsla: Some(hsla),\n\n repr,\n\n }\n\n }\n\n}\n\n\n\n#[derive(Debug, Clone, Eq, PartialEq)]\n", "file_path": "src/color/mod.rs", "rank": 56, "score": 93602.71552896788 }, { "content": "\n\n pub fn saturation(&self) -> Number {\n\n self.saturation.clone()\n\n }\n\n\n\n pub fn luminance(&self) -> Number {\n\n self.luminance.clone()\n\n }\n\n\n\n pub fn alpha(&self) -> Number {\n\n self.alpha.clone()\n\n }\n\n}\n\n\n\n// RGBA color functions\n\nimpl Color {\n\n pub fn new(red: u8, green: u8, blue: u8, alpha: u8, repr: String) -> Self {\n\n Color {\n\n rgba: Rgba::new(red.into(), green.into(), blue.into(), alpha.into()),\n\n hsla: None,\n", "file_path": "src/color/mod.rs", "rank": 57, "score": 93602.49956884235 }, { "content": " Color::from_hsla(hue + degrees, saturation, luminance, alpha)\n\n }\n\n\n\n pub fn lighten(&self, amount: Number) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n\n Color::from_hsla(hue, saturation, luminance + amount, alpha)\n\n }\n\n\n\n pub fn darken(&self, amount: Number) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n\n Color::from_hsla(hue, saturation, luminance - amount, alpha)\n\n }\n\n\n\n pub fn saturate(&self, amount: Number) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n\n Color::from_hsla(hue, saturation + amount, luminance, alpha)\n\n }\n\n\n\n pub fn desaturate(&self, amount: Number) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n", "file_path": "src/color/mod.rs", "rank": 58, "score": 93602.44304232311 }, { "content": "/// Other color functions\n\nimpl Color {\n\n pub fn to_ie_hex_str(&self) -> String {\n\n format!(\n\n \"#{:X}{:X}{:X}{:X}\",\n\n (self.alpha() * Number::from(255)).round().to_integer(),\n\n self.red().to_integer(),\n\n self.green().to_integer(),\n\n self.blue().to_integer()\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/color/mod.rs", "rank": 59, "score": 93602.4382306081 }, { "content": " repr,\n\n }\n\n }\n\n\n\n /// Create a new `Color` with just RGBA values.\n\n /// Color representation is created automatically.\n\n pub fn from_rgba(\n\n mut red: Number,\n\n mut green: Number,\n\n mut blue: Number,\n\n mut alpha: Number,\n\n ) -> Self {\n\n red = red.clamp(0, 255);\n\n green = green.clamp(0, 255);\n\n blue = blue.clamp(0, 255);\n\n alpha = alpha.clamp(0, 1);\n\n\n\n let repr = repr(&red, &green, &blue, &alpha);\n\n Color::new_rgba(red, green, blue, alpha, repr)\n\n }\n", "file_path": "src/color/mod.rs", "rank": 60, "score": 93602.32897010521 }, { "content": "\n\n pub fn red(&self) -> Number {\n\n self.rgba.red.clone().round()\n\n }\n\n\n\n pub fn blue(&self) -> Number {\n\n self.rgba.blue.clone().round()\n\n }\n\n\n\n pub fn green(&self) -> Number {\n\n self.rgba.green.clone().round()\n\n }\n\n\n\n /// Mix two colors together with weight\n\n /// Algorithm adapted from\n\n /// <https://github.com/sass/dart-sass/blob/0d0270cb12a9ac5cce73a4d0785fecb00735feee/lib/src/functions/color.dart#L718>\n\n pub fn mix(self, other: &Color, weight: Number) -> Self {\n\n let weight = weight.clamp(0, 100);\n\n let normalized_weight = weight.clone() * Number::from(2) - Number::one();\n\n let alpha_distance = self.alpha() - other.alpha();\n", "file_path": "src/color/mod.rs", "rank": 61, "score": 93602.15202263468 }, { "content": "/// HSLA color functions\n\n/// Algorithms adapted from <http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/>\n\nimpl Color {\n\n /// Calculate hue from RGBA values\n\n pub fn hue(&self) -> Number {\n\n if let Some(h) = &self.hsla {\n\n return h.hue();\n\n }\n\n\n\n let red = self.red() / Number::from(255);\n\n let green = self.green() / Number::from(255);\n\n let blue = self.blue() / Number::from(255);\n\n let min = min(&red, min(&green, &blue)).clone();\n\n let max = max(&red, max(&green, &blue)).clone();\n\n if min == max {\n\n return Number::zero();\n\n }\n\n\n\n let mut hue = if blue == max {\n\n Number::from(4) + (red - green) / (max - min)\n", "file_path": "src/color/mod.rs", "rank": 62, "score": 93601.53761076456 }, { "content": " let blue = channel(temporary_b, &temporary_1, &temporary_2);\n\n\n\n let repr = repr(&red, &green, &blue, &alpha);\n\n Color::new_hsla(red, green, blue, alpha, hsla, repr)\n\n }\n\n\n\n pub fn invert(&self, weight: Number) -> Self {\n\n if weight.is_zero() {\n\n return self.clone();\n\n }\n\n let red = Number::from(u8::max_value()) - self.red();\n\n let green = Number::from(u8::max_value()) - self.green();\n\n let blue = Number::from(u8::max_value()) - self.blue();\n\n let repr = repr(&red, &green, &blue, &self.alpha());\n\n let inverse = Color::new_rgba(red, green, blue, self.alpha(), repr);\n\n inverse.mix(self, weight)\n\n }\n\n\n\n pub fn complement(&self) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n", "file_path": "src/color/mod.rs", "rank": 63, "score": 93601.35052304073 }, { "content": " hue.clone(),\n\n saturation.clone(),\n\n luminance.clone(),\n\n alpha.clone(),\n\n );\n\n\n\n if saturation.is_zero() {\n\n let luminance = if luminance > Number::from(100) {\n\n Number::from(100)\n\n } else {\n\n luminance\n\n };\n\n let val = luminance * Number::from(255);\n\n let repr = repr(&val, &val, &val, &alpha);\n\n return Color::new_hsla(val.clone(), val.clone(), val, alpha, hsla, repr);\n\n }\n\n\n\n let temporary_1 = if luminance < Number::small_ratio(1, 2) {\n\n luminance.clone() * (Number::one() + saturation)\n\n } else {\n", "file_path": "src/color/mod.rs", "rank": 64, "score": 93600.76353067381 }, { "content": " luminance.clone() + saturation.clone() - luminance.clone() * saturation\n\n };\n\n let temporary_2 = Number::from(2) * luminance - temporary_1.clone();\n\n hue /= Number::from(360);\n\n let mut temporary_r = hue.clone() + Number::small_ratio(1, 3);\n\n let mut temporary_g = hue.clone();\n\n let mut temporary_b = hue - Number::small_ratio(1, 3);\n\n\n\n macro_rules! clamp_temp {\n\n ($temp:ident) => {\n\n if $temp > Number::one() {\n\n $temp -= Number::one();\n\n } else if $temp.is_negative() {\n\n $temp += Number::one();\n\n }\n\n };\n\n }\n\n\n\n clamp_temp!(temporary_r);\n\n clamp_temp!(temporary_g);\n", "file_path": "src/color/mod.rs", "rank": 65, "score": 93600.72762823774 }, { "content": " Color::from_hsla(hue, saturation - amount, luminance, alpha)\n\n }\n\n\n\n /// Create RGBA representation from HSLA values\n\n pub fn from_hsla(hue: Number, saturation: Number, luminance: Number, alpha: Number) -> Self {\n\n let mut hue = if hue > Number::from(360) {\n\n hue % Number::from(360)\n\n } else if hue < Number::from(-360) {\n\n Number::from(360) + hue % Number::from(360)\n\n } else if hue.is_negative() {\n\n Number::from(360) + hue.clamp(-360, 360)\n\n } else {\n\n hue\n\n };\n\n\n\n let saturation = saturation.clamp(0, 1);\n\n let luminance = luminance.clamp(0, 1);\n\n let alpha = alpha.clamp(0, 1);\n\n\n\n let hsla = Hsla::new(\n", "file_path": "src/color/mod.rs", "rank": 66, "score": 93600.58919415477 }, { "content": "\n\n let combined_weight1 =\n\n if normalized_weight.clone() * alpha_distance.clone() == Number::from(-1) {\n\n normalized_weight\n\n } else {\n\n (normalized_weight.clone() + alpha_distance.clone())\n\n / (Number::one() + normalized_weight * alpha_distance)\n\n };\n\n let weight1 = (combined_weight1 + Number::one()) / Number::from(2);\n\n let weight2 = Number::one() - weight1.clone();\n\n\n\n Color::from_rgba(\n\n self.red() * weight1.clone() + other.red() * weight2.clone(),\n\n self.green() * weight1.clone() + other.green() * weight2.clone(),\n\n self.blue() * weight1 + other.blue() * weight2,\n\n self.alpha() * weight.clone() + other.alpha() * (Number::one() - weight),\n\n )\n\n }\n\n}\n\n\n", "file_path": "src/color/mod.rs", "rank": 67, "score": 93600.43144779767 }, { "content": " Number::zero()\n\n } else if blue == max {\n\n Number::from(4) + (red - green) / (max - min)\n\n } else if green == max {\n\n Number::from(2) + (blue - red) / (max - min)\n\n } else {\n\n (green - blue) / (max - min)\n\n };\n\n\n\n if hue.is_negative() {\n\n hue += Number::from(360);\n\n }\n\n\n\n hue *= Number::from(60);\n\n\n\n (hue, saturation, lightness, self.alpha())\n\n }\n\n\n\n pub fn adjust_hue(&self, degrees: Number) -> Self {\n\n let (hue, saturation, luminance, alpha) = self.as_hsla();\n", "file_path": "src/color/mod.rs", "rank": 68, "score": 93597.2738617411 }, { "content": " /// Calculate luminance from RGBA values\n\n pub fn lightness(&self) -> Number {\n\n if let Some(h) = &self.hsla {\n\n return h.luminance() * Number::from(100);\n\n }\n\n\n\n let red = self.red() / Number::from(255);\n\n let green = self.green() / Number::from(255);\n\n let blue = self.blue() / Number::from(255);\n\n let min = min(&red, min(&green, &blue)).clone();\n\n let max = red.max(green.max(blue));\n\n (((min + max) / Number::from(2)) * Number::from(100)).round()\n\n }\n\n\n\n pub fn as_hsla(&self) -> (Number, Number, Number, Number) {\n\n if let Some(h) = &self.hsla {\n\n return (h.hue(), h.saturation(), h.luminance(), h.alpha());\n\n }\n\n\n\n let red = self.red() / Number::from(255);\n", "file_path": "src/color/mod.rs", "rank": 69, "score": 93597.2738617411 }, { "content": " let green = self.green() / Number::from(255);\n\n let blue = self.blue() / Number::from(255);\n\n\n\n let min = min(&red, min(&green, &blue)).clone();\n\n let max = red.max(green.max(blue));\n\n\n\n if min == max {\n\n return Number::zero();\n\n }\n\n\n\n let d = max.clone() - min.clone();\n\n let mm = max + min;\n\n let s = d / if mm > Number::one() {\n\n Number::from(2) - mm\n\n } else {\n\n mm\n\n };\n\n (s * Number::from(100)).round()\n\n }\n\n\n", "file_path": "src/color/mod.rs", "rank": 70, "score": 93597.2738617411 }, { "content": " let green = self.green() / Number::from(255);\n\n let blue = self.blue() / Number::from(255);\n\n let min = min(&red, min(&green, &blue)).clone();\n\n let max = max(&red, max(&green, &blue)).clone();\n\n\n\n let lightness = (min.clone() + max.clone()) / Number::from(2);\n\n\n\n let saturation = if min == max {\n\n Number::zero()\n\n } else {\n\n let d = max.clone() - min.clone();\n\n let mm = max.clone() + min.clone();\n\n d / if mm > Number::one() {\n\n Number::from(2) - mm\n\n } else {\n\n mm\n\n }\n\n };\n\n\n\n let mut hue = if min == max {\n", "file_path": "src/color/mod.rs", "rank": 71, "score": 93597.2738617411 }, { "content": " } else if green == max {\n\n Number::from(2) + (blue - red) / (max - min)\n\n } else {\n\n (green - blue) / (max - min)\n\n };\n\n\n\n if hue.is_negative() {\n\n hue += Number::from(360);\n\n }\n\n\n\n (hue * Number::from(60)).round()\n\n }\n\n\n\n /// Calculate saturation from RGBA values\n\n pub fn saturation(&self) -> Number {\n\n if let Some(h) = &self.hsla {\n\n return h.saturation() * Number::from(100);\n\n }\n\n\n\n let red = self.red() / Number::from(255);\n", "file_path": "src/color/mod.rs", "rank": 72, "score": 93597.2738617411 }, { "content": " clamp_temp!(temporary_b);\n\n\n\n fn channel(temp: Number, temp1: &Number, temp2: &Number) -> Number {\n\n Number::from(255)\n\n * if Number::from(6) * temp.clone() < Number::one() {\n\n temp2.clone() + (temp1.clone() - temp2.clone()) * Number::from(6) * temp\n\n } else if Number::from(2) * temp.clone() < Number::one() {\n\n temp1.clone()\n\n } else if Number::from(3) * temp.clone() < Number::from(2) {\n\n temp2.clone()\n\n + (temp1.clone() - temp2.clone())\n\n * (Number::small_ratio(2, 3) - temp)\n\n * Number::from(6)\n\n } else {\n\n temp2.clone()\n\n }\n\n }\n\n\n\n let red = channel(temporary_r, &temporary_1, &temporary_2);\n\n let green = channel(temporary_g, &temporary_1, &temporary_2);\n", "file_path": "src/color/mod.rs", "rank": 73, "score": 93597.2738617411 }, { "content": "use super::{Builtin, GlobalFunctionMap};\n\n\n\nmod hsl;\n\nmod opacity;\n\nmod other;\n\nmod rgb;\n\n\n\npub(crate) fn declare(f: &mut GlobalFunctionMap) {\n\n hsl::declare(f);\n\n opacity::declare(f);\n\n other::declare(f);\n\n rgb::declare(f);\n\n}\n", "file_path": "src/builtin/color/mod.rs", "rank": 74, "score": 90723.18087915007 }, { "content": "#[derive(Debug, Clone, Eq, PartialEq)]\n\nstruct Hsla {\n\n hue: Number,\n\n saturation: Number,\n\n luminance: Number,\n\n alpha: Number,\n\n}\n\n\n\nimpl Hsla {\n\n pub const fn new(hue: Number, saturation: Number, luminance: Number, alpha: Number) -> Self {\n\n Hsla {\n\n hue,\n\n saturation,\n\n luminance,\n\n alpha,\n\n }\n\n }\n\n\n\n pub fn hue(&self) -> Number {\n\n self.hue.clone()\n\n }\n", "file_path": "src/color/mod.rs", "rank": 75, "score": 90717.01948638566 }, { "content": "#[derive(Debug, Clone, Eq, PartialEq)]\n\nstruct Rgba {\n\n red: Number,\n\n green: Number,\n\n blue: Number,\n\n alpha: Number,\n\n}\n\n\n\nimpl Rgba {\n\n pub const fn new(red: Number, green: Number, blue: Number, alpha: Number) -> Self {\n\n Rgba {\n\n red,\n\n green,\n\n blue,\n\n alpha,\n\n }\n\n }\n\n\n\n pub fn alpha(&self) -> Number {\n\n self.alpha.clone()\n\n }\n\n}\n\n\n", "file_path": "src/color/mod.rs", "rank": 76, "score": 90717.01948638566 }, { "content": "/// Get the proper representation from RGBA values\n\nfn repr(red: &Number, green: &Number, blue: &Number, alpha: &Number) -> String {\n\n fn into_u8(channel: &Number) -> u8 {\n\n if channel > &Number::from(255) {\n\n 255_u8\n\n } else if channel.is_negative() {\n\n 0_u8\n\n } else {\n\n channel.round().to_integer().to_u8().unwrap_or(255)\n\n }\n\n }\n\n\n\n let red_u8 = into_u8(red);\n\n let green_u8 = into_u8(green);\n\n let blue_u8 = into_u8(blue);\n\n\n\n if alpha < &Number::one() {\n\n format!(\"rgba({}, {}, {}, {})\", red_u8, green_u8, blue_u8, alpha)\n\n } else if let Some(c) = NAMED_COLORS.get_by_rgba([red_u8, green_u8, blue_u8, 0xFF]) {\n\n (*c).to_string()\n\n } else {\n\n format!(\"#{:0>2x}{:0>2x}{:0>2x}\", red_u8, green_u8, blue_u8)\n\n }\n\n}\n\n\n\nimpl Display for Color {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n write!(f, \"{}\", self.repr)\n\n }\n\n}\n", "file_path": "src/color/mod.rs", "rank": 77, "score": 71041.63943221924 }, { "content": "pub fn many_named_colors(c: &mut Criterion) {\n\n c.bench_function(\"many_named_colors\", |b| {\n\n b.iter(|| {\n\n StyleSheet::new(black_box(\n\n include_str!(\"many_named_colors.scss\").to_string(),\n\n ))\n\n })\n\n });\n\n}\n\n\n\ncriterion_group!(benches, many_hsla, many_named_colors,);\n\ncriterion_main!(benches);\n", "file_path": "benches/colors.rs", "rank": 78, "score": 52055.01668103491 }, { "content": "use criterion::{black_box, criterion_group, criterion_main, Criterion};\n\nuse grass::StyleSheet;\n\n\n", "file_path": "benches/colors.rs", "rank": 79, "score": 48543.42043684495 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n if_toplevel_true,\n\n \"@if true {\\n a {\\n color: foo;\\n}\\n}\\n\",\n\n \"a {\\n color: foo;\\n}\\n\"\n\n);\n\ntest!(\n\n if_inner_true,\n\n \"a {\\n @if true {\\n color: foo;\\n}\\n}\\n\",\n\n \"a {\\n color: foo;\\n}\\n\"\n\n);\n\ntest!(\n\n if_toplevel_false,\n\n \"@if false {\\n a {\\n color: foo;\\n}\\n}\\n\",\n\n \"\"\n\n);\n", "file_path": "tests/if.rs", "rank": 80, "score": 47704.22493639405 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n inner_increment_var,\n\n \"$a: 4;\\n$b: 1;\\na {\\n @while $a > $b {\\n color: $b;\\n $b: $b + 1;\\n }\\n}\",\n\n \"a {\\n color: 1;\\n color: 2;\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n outer_increment_var,\n\n \"$a: 4;\\n$b: 1;\\n@while $a > $b {\\na {\\n color: $b;\\n }\\n $b: $b + 1;\\n}\",\n\n \"a {\\n color: 1;\\n}\\n\\na {\\n color: 2;\\n}\\n\\na {\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n inner_while_false,\n\n \"a {\\n @while false {\\n color: foo;\\n }\\n}\",\n\n \"\"\n\n);\n", "file_path": "tests/while.rs", "rank": 81, "score": 47702.00473622183 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n for_1_through_3,\n\n \"@for $i from 1 through 3 {\\n a {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\\na {\\n color: 2;\\n}\\n\\na {\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n for_1_to_3,\n\n \"@for $i from 1 to 3 {\\n a {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\\na {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n for_3_through_1,\n\n \"@for $i from 3 through 1 {\\n a {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 3;\\n}\\n\\na {\\n color: 2;\\n}\\n\\na {\\n color: 1;\\n}\\n\"\n\n);\n", "file_path": "tests/for.rs", "rank": 82, "score": 47698.72619843958 }, { "content": ");\n\nerror!(no_condition, \"@if{}\", \"Error: Expected expression.\");\n\nerror!(\n\n nothing_after_open_curly,\n\n \"@if foo {\", \"Error: expected \\\"}\\\".\"\n\n);\n\nerror!(\n\n first_condition_error,\n\n \"@if 1 + 1 =s {\\n}\", \"Error: expected \\\"=\\\".\"\n\n);\n\ntest!(\n\n conditions_evaluated_lazily,\n\n \"$p: null;\n\n @if $p==null {}\n\n @else if not comparable($p, 0) {}\",\n\n \"\"\n\n);\n\ntest!(\n\n at_rule_inside_ruleset,\n\n \"@mixin foo {\\n color: red;\\n}\\n\\n@if true {\\n a {\\n @include foo;\\n }\\n}\\n\",\n", "file_path": "tests/if.rs", "rank": 83, "score": 47698.70881613309 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n not_number,\n\n \"a {\\n color: not 1;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n not_true,\n\n \"a {\\n color: not true;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n not_false,\n\n \"a {\\n color: not false;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n", "file_path": "tests/not.rs", "rank": 84, "score": 47698.63493975581 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n one_or_two,\n\n \"a {\\n color: 1 or 2;\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(\n\n two_or_one,\n\n \"a {\\n color: 2 or 1;\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n true_or_true,\n\n \"a {\\n color: true or true;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n", "file_path": "tests/or.rs", "rank": 85, "score": 47698.5327064623 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n one_and_two,\n\n \"a {\\n color: 1 and 2;\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n two_and_one,\n\n \"a {\\n color: 2 and 1;\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(\n\n true_and_true,\n\n \"a {\\n color: true and true;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n", "file_path": "tests/and.rs", "rank": 86, "score": 47698.5327064623 }, { "content": "#![cfg(test)]\n\n\n\n#[macro_use]\n\nmod macros;\n\n\n\ntest!(\n\n each_space_separated_inner,\n\n \"a {\\n @each $i in 1 2 3 {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n color: 2;\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n each_comma_separated_inner,\n\n \"a {\\n @each $i in 1, 2, 3 {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n color: 2;\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n each_space_separated_outer,\n\n \"@each $i in 1 2 3 {\\n a {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\\na {\\n color: 2;\\n}\\n\\na {\\n color: 3;\\n}\\n\"\n\n);\n", "file_path": "tests/each.rs", "rank": 87, "score": 47698.12348851919 }, { "content": "test!(\n\n if_inner_false,\n\n \"a {\\n @if false {\\n color: foo;\\n}\\n}\\n\",\n\n \"\"\n\n);\n\ntest!(\n\n if_else_toplevel_true,\n\n \"@if true {\\n a {\\n color: foo;\\n}\\n} @else {\\n b {\\n color: bar;\\n}\\n}\\n\",\n\n \"a {\\n color: foo;\\n}\\n\"\n\n);\n\ntest!(\n\n if_else_inner_true,\n\n \"a {\\n @if true {\\n color: foo;\\n} @else {\\n color: bar;\\n}\\n}\\n\",\n\n \"a {\\n color: foo;\\n}\\n\"\n\n);\n\ntest!(\n\n if_else_toplevel_false,\n\n \"@if false {\\n a {\\n color: foo;\\n}\\n} @else {\\n a {\\n color: bar;\\n}\\n}\\n\",\n\n \"a {\\n color: bar;\\n}\\n\"\n\n);\n", "file_path": "tests/if.rs", "rank": 88, "score": 47694.75571754746 }, { "content": "test!(\n\n scope,\n\n \"a {\\n $a: red;\\n @for $i from 1 to 3 {\\n $a: blue;\\n }\\n color: $a;\\n}\\n\",\n\n \"a {\\n color: blue;\\n}\\n\"\n\n);\n\ntest!(\n\n simple_return_in_function,\n\n \"@function foo() {\\n @for $i from 1 to 2 {\\n @return $i;\\n }\\n}\\na {\\n color: foo();\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(\n\n return_gated_by_if_in_function,\n\n \"@function foo() {\\n @for $i from 1 through 2 {\\n @if $i==2 {\\n @return $i;\\n }\\n }\\n}\\na {\\n color: foo();\\n}\\n\",\n\n \"a {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n inner_if,\n\n \"a {\\n @for $i from 1 to 3 {\\n @if $i==2 {\\n color: red;\\n }\\n }\\n}\\n\",\n\n \"a {\\n color: red;\\n}\\n\"\n\n);\n", "file_path": "tests/for.rs", "rank": 89, "score": 47694.58024471848 }, { "content": "test!(\n\n not_null,\n\n \"a {\\n color: not null;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n\ntest!(\n\n not_unquoted,\n\n \"a {\\n color: not foo;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n not_not_true,\n\n \"a {\\n color: not not true;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n\ntest!(\n\n not_not_false,\n\n \"a {\\n color: not not false;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n", "file_path": "tests/not.rs", "rank": 90, "score": 47693.150733103124 }, { "content": "test!(\n\n short_circuits_when_lhs_is_true,\n\n \"a {\\n color: true or red % foo;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n\nerror!(\n\n does_not_short_circuit_when_lhs_is_false,\n\n \"a {\\n color: false or red % foo;\\n}\\n\", \"Error: Undefined operation \\\"red % foo\\\".\"\n\n);\n\ntest!(\n\n short_circuiting_in_comma_separated_list,\n\n \"a {\\n color: true or red % foo, red;\\n}\\n\",\n\n \"a {\\n color: true, red;\\n}\\n\"\n\n);\n\nerror!(\n\n properly_bubbles_error_when_invalid_char_after_or,\n\n \"a {\\n color: true or? foo;\\n}\\n\", \"Error: expected \\\";\\\".\"\n\n);\n", "file_path": "tests/or.rs", "rank": 91, "score": 47692.827943965676 }, { "content": " if_false_else_if_true_else,\n\n \"a {\\n @if false {\\n color: red;\\n} @else if true {\\n color: blue;\\n} @else {\\n color: green;\\n}\\n}\\n\",\n\n \"a {\\n color: blue;\\n}\\n\"\n\n);\n\ntest!(\n\n if_inner_style_missing_semicolon,\n\n \"a {\\n @if true {\\n color: red\\n }\\n}\\n\",\n\n \"a {\\n color: red;\\n}\\n\"\n\n);\n\ntest!(\n\n atrule_other_than_else_immediately_following,\n\n \"a {\\n @if true {\\n b {\\n background: gray;\\n }\\n }\\n\\n @if true {\\n b {\\n background: gray;\\n }\\n }\\n}\\n\",\n\n \"a b {\\n background: gray;\\n}\\na b {\\n background: gray;\\n}\\n\"\n\n);\n\ntest!(\n\n nested_if_in_function,\n\n \"@function foo($value) {\\n @if true {\\n @if false {\\n @error foo;\\n }\\n\\n @else {\\n @return $value;\\n }\\n }\\n}\n\n a { color: foo(bar); }\",\n\n \"a {\\n color: bar;\\n}\\n\"\n\n);\n", "file_path": "tests/if.rs", "rank": 92, "score": 47692.79093971929 }, { "content": "test!(\n\n if_else_inner_false,\n\n \"a {\\n @if false {\\n color: foo;\\n} @else {\\n color: bar;\\n}\\n}\\n\",\n\n \"a {\\n color: bar;\\n}\\n\"\n\n);\n\nerror!(\n\n no_brace_after_else,\n\n \"@if false {} @else -}\", \"Error: expected \\\"{\\\".\"\n\n);\n\ntest!(\n\n if_else_if_no_else,\n\n \"a {\\n @if false {\\n color: red;\\n} @else if true {\\n color: blue;\\n}\\n}\\n\",\n\n \"a {\\n color: blue;\\n}\\n\"\n\n);\n\ntest!(\n\n if_false_else_if_false_else,\n\n \"a {\\n @if false {\\n color: red;\\n} @else if false {\\n color: blue;\\n} @else {\\n color: green;\\n}\\n}\\n\",\n\n \"a {\\n color: green;\\n}\\n\"\n\n);\n\ntest!(\n", "file_path": "tests/if.rs", "rank": 93, "score": 47692.07535275581 }, { "content": " \"a {\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n part_of_binop,\n\n \"a {\\n color: 1 - and;\\n}\\n\",\n\n \"a {\\n color: 1-and;\\n}\\n\"\n\n);\n\ntest!(\n\n part_of_binop_casing,\n\n \"a {\\n color: 1 - AND;\\n}\\n\",\n\n \"a {\\n color: 1-AND;\\n}\\n\"\n\n);\n\ntest!(\n\n short_circuits_when_lhs_is_false,\n\n \"a {\\n color: false and comparable(\\\"a\\\", \\\"b\\\");\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\nerror!(\n\n #[ignore = \"blocked on a rewrite of value eval\"]\n\n properly_bubbles_error_when_invalid_char_after_and,\n\n \"a {\\n color: false and? foo;\\n}\\n\", \"Error: expected \\\";\\\".\"\n\n);\n", "file_path": "tests/and.rs", "rank": 94, "score": 47691.964933649935 }, { "content": "test!(\n\n for_3_to_1,\n\n \"@for $i from 3 to 1 {\\n a {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 3;\\n}\\n\\na {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n for_var_through_var,\n\n \"$a: 1;\\n$b: 3;\\n@for $x from $a through $b {\\n div {\\n color: $x;\\n }\\n}\\n\",\n\n \"div {\\n color: 1;\\n}\\n\\ndiv {\\n color: 2;\\n}\\n\\ndiv {\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n for_var_decl,\n\n \"@for $x from 1 to 3 {\\n $limit: $x;\\n\\n a {\\n color: $limit;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\\na {\\n color: 2;\\n}\\n\"\n\n);\n\ntest!(\n\n for_styles,\n\n \"a {\\n @for $i from 1 to 3 {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n color: 2;\\n}\\n\"\n\n);\n", "file_path": "tests/for.rs", "rank": 95, "score": 47688.894616067206 }, { "content": "test!(\n\n one_or_null,\n\n \"a {\\n color: 1 or null;\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(\n\n one_or_two_or_three,\n\n \"a {\\n color: 1 or 2 or 3;\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n\ntest!(\n\n part_of_binop,\n\n \"a {\\n color: 1 - or;\\n}\\n\",\n\n \"a {\\n color: 1-or;\\n}\\n\"\n\n);\n\ntest!(\n\n part_of_binop_casing,\n\n \"a {\\n color: 1 - OR;\\n}\\n\",\n\n \"a {\\n color: 1-OR;\\n}\\n\"\n\n);\n", "file_path": "tests/or.rs", "rank": 96, "score": 47688.885726508466 }, { "content": "test!(\n\n true_and_false,\n\n \"a {\\n color: true and false;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n false_and_true,\n\n \"a {\\n color: false and true;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n false_and_false,\n\n \"a {\\n color: false and false;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(null_and_one, \"a {\\n color: null and 1;\\n}\\n\", \"\");\n\ntest!(one_and_null, \"a {\\n color: 1 and null;\\n}\\n\", \"\");\n\ntest!(\n\n one_and_two_and_three,\n\n \"a {\\n color: 1 and 2 and 3;\\n}\\n\",\n", "file_path": "tests/and.rs", "rank": 97, "score": 47688.85684398381 }, { "content": "test!(\n\n each_two_variables_one_null,\n\n \"a {\\n @each $i, $c in 1 2 3 {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: 1;\\n color: 2;\\n color: 3;\\n}\\n\"\n\n);\n\ntest!(\n\n each_one_var_in_one_map,\n\n \"a {\\n @each $i in (a: b) {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: a b;\\n}\\n\"\n\n);\n\ntest!(\n\n each_two_vars_in_one_map,\n\n \"a {\\n @each $i, $c in (a: b) {\\n color: $i;\\n }\\n}\\n\",\n\n \"a {\\n color: a;\\n}\\n\"\n\n);\n\ntest!(\n\n each_two_vars_in_3_2_list,\n\n \"a {\\n @each $i, $c in (1 2 3, 4 5) {\\n color: $i, $c;\\n }\\n}\\n\",\n\n \"a {\\n color: 1, 2;\\n color: 4, 5;\\n}\\n\"\n\n);\n", "file_path": "tests/each.rs", "rank": 98, "score": 47688.83154277085 }, { "content": "test!(\n\n true_or_false,\n\n \"a {\\n color: true or false;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n\ntest!(\n\n false_or_true,\n\n \"a {\\n color: false or true;\\n}\\n\",\n\n \"a {\\n color: true;\\n}\\n\"\n\n);\n\ntest!(\n\n false_or_false,\n\n \"a {\\n color: false or false;\\n}\\n\",\n\n \"a {\\n color: false;\\n}\\n\"\n\n);\n\ntest!(\n\n null_or_one,\n\n \"a {\\n color: null or 1;\\n}\\n\",\n\n \"a {\\n color: 1;\\n}\\n\"\n\n);\n", "file_path": "tests/or.rs", "rank": 99, "score": 47688.68282416868 } ]
Rust
examples/custom-source.rs
Re3Studios/assets_manager
f6a0390aae4072f7d9e7084433f5fb585bc5fe8f
use assets_manager::{ hot_reloading::{DynUpdateSender, EventSender, FsWatcherBuilder}, source::{DirEntry, FileSystem, Source}, AssetCache, BoxedError, }; use std::{ borrow::Cow, io, path::{Path, PathBuf}, }; #[derive(Debug, Clone)] pub struct FsWithOverride { default_dir: FileSystem, override_dir: Option<FileSystem>, } impl FsWithOverride { pub fn new<P: AsRef<Path>>(default_path: P) -> io::Result<Self> { let default_dir = FileSystem::new(default_path)?; let override_dir = std::env::var_os("ASSETS_OVERRIDE").and_then(|path| { FileSystem::new(path) .map_err(|err| { log::error!("Error setting override assets directory: {}", err); }) .ok() }); Ok(Self { default_dir, override_dir, }) } pub fn path_of(&self, specifier: &str, ext: &str) -> PathBuf { self.default_dir.path_of(DirEntry::File(specifier, ext)) } } impl Source for FsWithOverride { fn read(&self, id: &str, ext: &str) -> io::Result<Cow<[u8]>> { if let Some(dir) = &self.override_dir { match dir.read(id, ext) { Ok(content) => return Ok(content), Err(err) => { if err.kind() != io::ErrorKind::NotFound { let path = dir.path_of(DirEntry::File(id, ext)); log::warn!("Error reading \"{}\": {}", path.display(), err); } } } } self.default_dir.read(id, ext) } fn read_dir(&self, id: &str, f: &mut dyn FnMut(DirEntry)) -> io::Result<()> { if let Some(dir) = &self.override_dir { match dir.read_dir(id, f) { Ok(()) => return Ok(()), Err(err) => { if err.kind() != io::ErrorKind::NotFound { let path = dir.path_of(DirEntry::Directory(id)); log::warn!("Error reading \"{}\": {}", path.display(), err); } } } } self.default_dir.read_dir(id, f) } fn exists(&self, entry: DirEntry) -> bool { self.override_dir .as_ref() .map_or(false, |dir| dir.exists(entry)) || self.default_dir.exists(entry) } fn configure_hot_reloading(&self, events: EventSender) -> Result<DynUpdateSender, BoxedError> { let mut builder = FsWatcherBuilder::new()?; if let Some(dir) = &self.override_dir { builder.watch(dir.root().to_owned())?; } builder.watch(self.default_dir.root().to_owned())?; Ok(builder.build(events)) } fn make_source(&self) -> Option<Box<dyn Source + Send>> { Some(Box::new(self.clone())) } } fn main() -> Result<(), BoxedError> { env_logger::builder() .filter_level(log::LevelFilter::Info) .init(); let source = FsWithOverride::new("assets")?; let cache = AssetCache::with_source(source); let msg = cache.load::<String>("example.hello")?; loop { #[cfg(feature = "hot-reloading")] cache.hot_reload(); println!("{}", msg.read()); std::thread::sleep(std::time::Duration::from_secs(1)) } }
use assets_manager::{ hot_reloading::{DynUpdateSender, EventSender, FsWatcherBuilder}, source::{DirEntry, FileSystem, Source}, AssetCache, BoxedError, }; use std::{ borrow::Cow, io, path::{Path, PathBuf}, }; #[derive(Debug, Clone)] pub struct FsWithOverride { default_dir: FileSystem, override_dir: Option<FileSystem>, } impl FsWithOverride { pub fn new<P: AsRef<Path>>(default_path: P) -> io::Result<Self> { let default_dir = FileSystem::new(default_path)?; let override_dir = std::env::var_os("ASSETS_OVERRIDE").and_then(|path| { FileSystem::new(path) .map_err(|err| { log::error!("Error setting override assets directory: {}", err); }) .ok() }); Ok(Self { default_dir, override_dir, }) } pub fn path_of(&self, specifier: &str, ext: &str) -> PathBuf { self.default_dir.path_of(DirEntry::File(specifier, ext)) } } impl Source for FsWithOverride { fn read(&self, id: &str, ext: &str) -> io::Result<Cow<[u8]>> { if let Some(dir) = &self.override_dir { match dir.read(id, ext) { Ok(content) => return Ok(content), Err(err) => { if err.kind() != io::ErrorKind::NotFound { let path = dir.path_of(DirEntry::File(id, ext)); log::warn!("Error reading \"{}\": {}", path.display(), err); } } } } self.default_dir.read(id, ext) } fn read_dir(&self, id: &str, f: &mut dyn FnMut(DirEntry)) -> io::Result<()> { if let Some(dir) = &self.override_dir { match dir.read_dir(id, f) { Ok(()) => return Ok(()), Err(err) => { if err.kind() != io::ErrorKind::NotFound { let path = dir.path_of(DirEntry::Directory(id)); log::warn!("Error reading \"{}\": {}", path.display(), err); } } } } self.default_dir.read_dir(id, f) } fn exists(&self, en
|| self.default_dir.exists(entry) } fn configure_hot_reloading(&self, events: EventSender) -> Result<DynUpdateSender, BoxedError> { let mut builder = FsWatcherBuilder::new()?; if let Some(dir) = &self.override_dir { builder.watch(dir.root().to_owned())?; } builder.watch(self.default_dir.root().to_owned())?; Ok(builder.build(events)) } fn make_source(&self) -> Option<Box<dyn Source + Send>> { Some(Box::new(self.clone())) } } fn main() -> Result<(), BoxedError> { env_logger::builder() .filter_level(log::LevelFilter::Info) .init(); let source = FsWithOverride::new("assets")?; let cache = AssetCache::with_source(source); let msg = cache.load::<String>("example.hello")?; loop { #[cfg(feature = "hot-reloading")] cache.hot_reload(); println!("{}", msg.read()); std::thread::sleep(std::time::Duration::from_secs(1)) } }
try: DirEntry) -> bool { self.override_dir .as_ref() .map_or(false, |dir| dir.exists(entry))
function_block-random_span
[ { "content": "fn load<A: Asset>(source: &dyn Source, id: &str) -> Result<Box<dyn AnyAsset>, Error> {\n\n let asset = load_from_source::<A, _>(source, id)?;\n\n Ok(Box::new(asset))\n\n}\n\n\n", "file_path": "src/key.rs", "rank": 0, "score": 240843.7802783121 }, { "content": "fn read_dir(path: &Path, content: &mut Content, id: Id, errors: &mut Vec<syn::Error>) {\n\n let dir = match path.read_dir() {\n\n Ok(dir) => dir,\n\n Err(e) => {\n\n push_error(errors, format!(\"{}: {}\", path.display(), e));\n\n return;\n\n }\n\n };\n\n\n\n for elem in dir {\n\n let path = match elem {\n\n Ok(e) => e.path(),\n\n Err(e) => {\n\n push_error(errors, format!(\"{}: {}\", path.display(), e));\n\n continue;\n\n }\n\n };\n\n\n\n if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {\n\n let this_id = id.clone().push(stem);\n", "file_path": "macros/src/embedded.rs", "rank": 1, "score": 209668.09291443357 }, { "content": "#[inline]\n\nfn load_single<A, S>(source: &S, id: &str, ext: &str) -> Result<A, ErrorKind>\n\nwhere\n\n A: Asset,\n\n S: Source + ?Sized,\n\n{\n\n let content = source.read(id, ext)?;\n\n let asset = A::Loader::load(content, ext)?;\n\n Ok(asset)\n\n}\n\n\n\npub(crate) fn load_from_source<A, S>(source: &S, id: &str) -> Result<A, Error>\n\nwhere\n\n A: Asset,\n\n S: Source + ?Sized,\n\n{\n\n let mut error = ErrorKind::NoDefaultValue;\n\n\n\n for ext in A::EXTENSIONS {\n\n match load_single(source, id, ext) {\n\n Err(err) => error = err.or(error),\n\n Ok(asset) => return Ok(asset),\n\n }\n\n }\n\n\n\n A::default_value(id, Error::from_kind(id.into(), error))\n\n}\n", "file_path": "src/cache.rs", "rank": 2, "score": 187131.3543026043 }, { "content": "fn extension_of(path: &Path) -> Option<&str> {\n\n match path.extension() {\n\n Some(ext) => ext.to_str(),\n\n None => Some(\"\"),\n\n }\n\n}\n\n\n", "file_path": "macros/src/embedded.rs", "rank": 3, "score": 161928.53769080242 }, { "content": "pub fn path_of_entry(root: &Path, entry: DirEntry) -> PathBuf {\n\n let (id, ext) = match entry {\n\n DirEntry::File(id, ext) => (id, Some(ext)),\n\n DirEntry::Directory(id) => (id, None),\n\n };\n\n\n\n let capacity = root.as_os_str().len() + id.len() + ext.map_or(0, |ext| ext.len()) + 2;\n\n let mut path = PathBuf::with_capacity(capacity);\n\n\n\n path.push(root);\n\n path.extend(id.split('.'));\n\n if let Some(ext) = ext {\n\n path.set_extension(ext);\n\n }\n\n\n\n path\n\n}\n\n\n\n#[inline]\n\npub(crate) fn extension_of(path: &Path) -> Option<&str> {\n", "file_path": "src/utils/private.rs", "rank": 4, "score": 156584.6595466092 }, { "content": "fn write_i32(path: &Path, n: i32) -> io::Result<()> {\n\n let mut file = File::create(path)?;\n\n write!(file, \"{}\", n)\n\n}\n\n\n\nmacro_rules! test_scenario {\n\n (@leak $cache:ident true) => { let $cache = Box::leak(Box::new($cache)); };\n\n (@leak $cache:ident false) => {};\n\n\n\n (@enhance $cache:ident true) => { $cache.enhance_hot_reloading(); };\n\n (@enhance $cache:ident false) => {};\n\n\n\n (@reload $cache:ident true) => {};\n\n (@reload $cache:ident false) => { $cache.hot_reload(); };\n\n\n\n (\n\n name: $name:ident,\n\n is_static: $is_static:tt,\n\n type: $load:ty,\n\n id: $id:literal,\n", "file_path": "src/hot_reloading/tests.rs", "rank": 5, "score": 146550.98599728593 }, { "content": "struct FileDesc(Id, String, PathBuf);\n\n\n", "file_path": "macros/src/embedded.rs", "rank": 6, "score": 146532.7794287495 }, { "content": "#[cfg(feature = \"gltf\")]\n\n#[test]\n\npub fn gltf() {\n\n let cache = AssetCache::new(\"assets\").unwrap();\n\n cache.load::<asset::Gltf>(\"test.gltf.box\").unwrap();\n\n}\n\n\n", "file_path": "src/asset/tests.rs", "rank": 7, "score": 143461.34638535042 }, { "content": "#[allow(clippy::redundant_closure)]\n\nfn reload<T: Compound>(cache: AnyCache, id: &str) -> Option<Dependencies> {\n\n let handle = cache.get_cached::<T>(id)?;\n\n\n\n match cache.record_load::<T>(id) {\n\n Ok((asset, deps)) => {\n\n handle.as_dynamic().write(asset);\n\n log::info!(\"Reloading \\\"{}\\\"\", id);\n\n Some(deps)\n\n }\n\n Err(err) => {\n\n log::warn!(\"Error reloading \\\"{}\\\": {}\", id, err);\n\n None\n\n }\n\n }\n\n}\n\n\n\npub(crate) struct CompoundReloadInfos(OwnedKey, Dependencies, ReloadFn);\n\n\n\nimpl CompoundReloadInfos {\n\n #[inline]\n", "file_path": "src/hot_reloading/paths.rs", "rank": 8, "score": 142121.1260497605 }, { "content": "fn push_error<T: std::fmt::Display>(errors: &mut Vec<syn::Error>, err: T) {\n\n errors.push(syn::Error::new(Span::call_site(), err));\n\n}\n\n\n", "file_path": "macros/src/embedded.rs", "rank": 9, "score": 141461.30337866629 }, { "content": "#[cfg(feature = \"gltf\")]\n\n#[test]\n\npub fn gltf_embedded() {\n\n let cache = AssetCache::new(\"assets\").unwrap();\n\n cache.load::<asset::Gltf>(\"test.gltf.box-embedded\").unwrap();\n\n}\n\n\n", "file_path": "src/asset/tests.rs", "rank": 10, "score": 139534.11093106773 }, { "content": "#[cfg(feature = \"gltf\")]\n\n#[test]\n\npub fn gltf_bin() {\n\n let cache = AssetCache::new(\"assets\").unwrap();\n\n cache.load::<asset::Gltf>(\"test.gltf.box-bin\").unwrap();\n\n}\n\n\n", "file_path": "src/asset/tests.rs", "rank": 11, "score": 139534.11093106773 }, { "content": "#[cfg(feature = \"gltf\")]\n\n#[test]\n\npub fn gltf_dir() {\n\n let cache = AssetCache::new(\"assets\").unwrap();\n\n let dir = cache.load_dir::<asset::Gltf>(\"test.gltf\", false).unwrap();\n\n\n\n let mut ids: Vec<_> = dir.iter().map(|gltf| gltf.unwrap().id()).collect();\n\n ids.sort_unstable();\n\n assert_eq!(\n\n ids,\n\n [\n\n \"test.gltf.box\",\n\n \"test.gltf.box-bin\",\n\n \"test.gltf.box-embedded\"\n\n ]\n\n )\n\n}\n", "file_path": "src/asset/tests.rs", "rank": 12, "score": 139534.11093106773 }, { "content": "#[derive(Default)]\n\nstruct IdBuilder {\n\n segments: Vec<String>,\n\n len: usize,\n\n}\n\n\n\nimpl IdBuilder {\n\n /// Pushs a segment in the builder.\n\n #[inline]\n\n fn push(&mut self, s: &str) {\n\n match self.segments.get_mut(self.len) {\n\n Some(seg) => {\n\n seg.clear();\n\n seg.push_str(s);\n\n }\n\n None => self.segments.push(s.to_owned()),\n\n }\n\n self.len += 1;\n\n }\n\n\n\n /// Pops a segment from the builder.\n", "file_path": "src/source/zip.rs", "rank": 13, "score": 122588.24066596536 }, { "content": "#[derive(Clone, Debug, Hash, PartialEq, Eq)]\n\nstruct Id(String);\n\n\n\nimpl Id {\n\n fn new() -> Id {\n\n Id(String::new())\n\n }\n\n\n\n fn push(mut self, id: &str) -> Id {\n\n if !self.0.is_empty() {\n\n self.0.push('.');\n\n }\n\n self.0.push_str(id);\n\n self\n\n }\n\n}\n\n\n", "file_path": "macros/src/embedded.rs", "rank": 14, "score": 113829.09327049152 }, { "content": "/// An asset is a type loadable from raw bytes.\n\n///\n\n/// `Asset`s can be loaded and retrieved by an [`AssetCache`].\n\n///\n\n/// This trait should only perform a conversion from raw bytes to the concrete\n\n/// type. If you need to load other assets, please use the [`Compound`] trait.\n\n///\n\n/// # Extension\n\n///\n\n/// You can provide several extensions that will be used to search and load\n\n/// assets. When loaded, each extension is tried in order until a file is\n\n/// correctly loaded or no extension remains. The empty string `\"\"` means a file\n\n/// without extension. You cannot use character `.`.\n\n///\n\n/// The `EXTENSION` field is a convenient shortcut if your asset uses only one\n\n/// extension. If you set a value for `EXTENSIONS` too, this field is ignored.\n\n///\n\n/// If neither `EXTENSION` nor `EXTENSIONS` is set, the default is no extension.\n\n///\n\n/// If you use hot-reloading, the asset will be reloaded each time one of the\n\n/// file with the given extension is touched.\n\n///\n\n/// # Example\n\n///\n\n/// Suppose you make a physics simulation, and you store positions and speeds\n\n/// in a Bincode-encoded file, with extension \".data\".\n\n///\n\n/// ```no_run\n\n/// # cfg_if::cfg_if! { if #[cfg(feature = \"bincode\")] {\n\n/// use assets_manager::{Asset, loader};\n\n/// use serde::Deserialize;\n\n///\n\n/// #[derive(Deserialize)]\n\n/// struct Vector {\n\n/// x: f32,\n\n/// y: f32,\n\n/// z: f32,\n\n/// }\n\n///\n\n/// #[derive(Deserialize)]\n\n/// struct World {\n\n/// pos: Vec<Vector>,\n\n/// speed: Vec<Vector>,\n\n/// }\n\n///\n\n/// impl Asset for World {\n\n/// const EXTENSION: &'static str = \"data\";\n\n/// type Loader = loader::BincodeLoader;\n\n/// }\n\n/// # }}\n\n/// ```\n\npub trait Asset: Sized + Send + Sync + 'static {\n\n /// Use this field if your asset only uses one extension.\n\n ///\n\n /// This value is ignored if you set `EXTENSIONS` too.\n\n const EXTENSION: &'static str = \"\";\n\n\n\n /// This field enables you to specify multiple extension for an asset.\n\n ///\n\n /// If `EXTENSION` is provided, you don't have to set this constant.\n\n ///\n\n /// If this array is empty, loading an asset of this type returns an error\n\n /// unless a default value is provided with the `default_value` method.\n\n const EXTENSIONS: &'static [&'static str] = &[Self::EXTENSION];\n\n\n\n /// Specifies a way to convert raw bytes into the asset.\n\n ///\n\n /// See module [`loader`] for implementations of common conversions.\n\n type Loader: loader::Loader<Self>;\n\n\n\n /// Specifies a eventual default value to use if an asset fails to load. If\n", "file_path": "src/asset.rs", "rank": 15, "score": 103978.88685930065 }, { "content": "/// Bytes sources to load assets from.\n\n///\n\n/// This trait provides an abstraction over a basic filesystem, which is used to\n\n/// load assets independantly from the actual storage kind.\n\n///\n\n/// As a consumer of this library, you generally don't need to use this trait,\n\n/// exept when implementing [`DirLoadable`].\n\n///\n\n/// See [module-level documentation](super::source) for more informations.\n\npub trait Source {\n\n /// Try reading the source given an id and an extension.\n\n ///\n\n /// If no error occurs, this function returns an `Cow`, which can be useful\n\n /// to avoid allocations.\n\n ///\n\n /// Most of the time, you won't need to use this method, directly, as it is\n\n /// done for you by an [`AssetCache`] when you load [`Asset`]s.\n\n ///\n\n /// [`Asset`]: crate::Asset\n\n fn read(&self, id: &str, ext: &str) -> io::Result<Cow<[u8]>>;\n\n\n\n /// Reads the content of a directory.\n\n ///\n\n /// If no error occurs, this function executes the given closure for each\n\n /// entry in the directory.\n\n ///\n\n /// # Example\n\n ///\n\n /// ```\n", "file_path": "src/source/mod.rs", "rank": 17, "score": 98163.72432707583 }, { "content": "fn raw(s: &str) -> Cow<[u8]> {\n\n s.as_bytes().into()\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 18, "score": 97606.40561158696 }, { "content": "#[derive(Clone, Copy)]\n\nstruct AnySource<'a> {\n\n cache: &'a dyn CacheWithSource,\n\n}\n\n\n\nimpl Source for AnySource<'_> {\n\n #[inline]\n\n fn read(&self, id: &str, ext: &str) -> io::Result<Cow<[u8]>> {\n\n self.cache.read(id, ext)\n\n }\n\n\n\n #[inline]\n\n fn read_dir(&self, id: &str, f: &mut dyn FnMut(DirEntry)) -> io::Result<()> {\n\n self.cache.read_dir(id, f)\n\n }\n\n\n\n #[inline]\n\n fn exists(&self, entry: DirEntry) -> bool {\n\n self.cache.exists(entry)\n\n }\n\n}\n", "file_path": "src/anycache.rs", "rank": 19, "score": 93776.1308323213 }, { "content": "#[proc_macro]\n\npub fn embed(input: TokenStream) -> TokenStream {\n\n let input = syn::parse_macro_input!(input as embedded::Input);\n\n input.expand_dir().unwrap_or_else(to_compile_errors).into()\n\n}\n\n\n", "file_path": "macros/src/lib.rs", "rank": 20, "score": 90599.0207627985 }, { "content": "fn load_buffer(\n\n cache: AnyCache,\n\n base_id: &str,\n\n buffer: _gltf::Buffer,\n\n blob: &mut Option<Vec<u8>>,\n\n) -> Result<Vec<u8>, BoxedError> {\n\n Ok(match buffer.source() {\n\n _gltf::buffer::Source::Bin => blob.take().ok_or(\"missing binary portion of binary glTF\")?,\n\n _gltf::buffer::Source::Uri(uri) => match UriContent::parse_uri(base_id, uri, None)? {\n\n UriContent::Bin { content: data, .. } => data,\n\n UriContent::File { id, .. } => cache.load::<Bin>(&id)?.cloned().0,\n\n },\n\n })\n\n}\n\n\n", "file_path": "src/asset/gltf.rs", "rank": 21, "score": 88702.65943256934 }, { "content": "fn load_image(\n\n cache: AnyCache,\n\n base_id: &str,\n\n buffers: &[Vec<u8>],\n\n image: _gltf::Image,\n\n) -> Result<image::DynamicImage, BoxedError> {\n\n match image.source() {\n\n _gltf::image::Source::Uri { uri, mime_type } => {\n\n match UriContent::parse_uri(base_id, uri, mime_type)? {\n\n UriContent::Bin { content, mime_type } => {\n\n load_image_from_buffer(&content, mime_type)\n\n }\n\n UriContent::File { id, ext } => match ext {\n\n \"png\" => Ok(cache.load::<super::Png>(&id)?.cloned().0),\n\n \"jpeg\" | \"jpg\" => Ok(cache.load::<super::Jpeg>(&id)?.cloned().0),\n\n _ => Err(\"Unknown image type\".into()),\n\n },\n\n }\n\n }\n\n _gltf::image::Source::View { view, mime_type } => {\n", "file_path": "src/asset/gltf.rs", "rank": 22, "score": 88702.65943256934 }, { "content": "/// Register a file of an archive in maps.\n\nfn register_file(\n\n file: ZipFile,\n\n index: usize,\n\n files: &mut HashMap<FileDesc, usize>,\n\n dirs: &mut HashMap<String, Vec<OwnedEntry>>,\n\n id_builder: &mut IdBuilder,\n\n) {\n\n id_builder.reset();\n\n\n\n // Check the path.\n\n let path = match file.enclosed_name() {\n\n Some(path) => path,\n\n None => {\n\n log::warn!(\"Suspicious path in zip archive: {:?}\", file.name());\n\n return;\n\n }\n\n };\n\n\n\n // Parse the path and register it.\n\n // The closure is used as a cheap `try` block.\n", "file_path": "src/source/zip.rs", "rank": 23, "score": 88672.47893413481 }, { "content": "struct WatchedPaths {\n\n roots: Vec<PathBuf>,\n\n paths: HashMap<PathBuf, SmallSet<super::AssetKey>>,\n\n}\n\n\n\nimpl WatchedPaths {\n\n fn new(roots: Vec<PathBuf>) -> WatchedPaths {\n\n WatchedPaths {\n\n roots,\n\n paths: HashMap::new(),\n\n }\n\n }\n\n\n\n fn add_asset(&mut self, asset: super::AssetKey) {\n\n for root in &self.roots {\n\n for ext in asset.typ.extensions() {\n\n let path = path_of_entry(root, DirEntry::File(&asset.id, ext));\n\n self.paths\n\n .entry(path)\n\n .or_insert_with(SmallSet::new)\n", "file_path": "src/hot_reloading/watcher.rs", "rank": 24, "score": 88067.94636829177 }, { "content": "struct AssetDeps {\n\n reload: Option<ReloadFn>,\n\n rdeps: HashSet<OwnedKey>,\n\n deps: Dependencies,\n\n}\n\n\n\nimpl Default for AssetDeps {\n\n fn default() -> Self {\n\n AssetDeps {\n\n reload: None,\n\n deps: Dependencies::empty(),\n\n rdeps: HashSet::new(),\n\n }\n\n }\n\n}\n\n\n\nimpl AssetDeps {\n\n fn new(reload: Option<ReloadFn>, deps: Dependencies) -> Self {\n\n AssetDeps {\n\n reload,\n", "file_path": "src/hot_reloading/dependencies.rs", "rank": 25, "score": 87507.388572081 }, { "content": "type Res = Result<(), Box<dyn std::error::Error>>;\n\n\n", "file_path": "src/hot_reloading/tests.rs", "rank": 26, "score": 87458.8277253981 }, { "content": "#[test]\n\nfn string_loader_ok() {\n\n let raw = raw(\"Hello World!\");\n\n\n\n let loaded: String = StringLoader::load(raw.clone(), \"\").unwrap();\n\n assert_eq!(loaded, \"Hello World!\");\n\n\n\n let loaded: Box<str> = StringLoader::load(raw, \"\").unwrap();\n\n assert_eq!(&*loaded, \"Hello World!\");\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 27, "score": 86836.80755934176 }, { "content": "#[test]\n\nfn bytes_loader_ok() {\n\n let raw = raw(\"Hello World!\");\n\n\n\n let loaded: Vec<u8> = BytesLoader::load(raw.clone(), \"\").unwrap();\n\n assert_eq!(loaded, b\"Hello World!\");\n\n\n\n let loaded: Box<[u8]> = BytesLoader::load(raw, \"\").unwrap();\n\n assert_eq!(&*loaded, b\"Hello World!\");\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 28, "score": 86836.80755934176 }, { "content": "#[test]\n\nfn parse_loader_ok() {\n\n let n = rand::random::<i32>();\n\n let s = &format!(\"{}\", n);\n\n let raw = raw(s);\n\n\n\n let loaded: i32 = ParseLoader::load(raw, \"\").unwrap();\n\n assert_eq!(loaded, n);\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 29, "score": 86836.80755934176 }, { "content": "#[test]\n\nfn parse_loader_err() {\n\n let raw = raw(\"x\");\n\n let loaded: Result<i32, _> = ParseLoader::load(raw, \"\");\n\n assert!(loaded.is_err());\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 30, "score": 86836.80755934176 }, { "content": "fn load_image_from_buffer(\n\n buffer: &[u8],\n\n mime_type: Option<&str>,\n\n) -> Result<image::DynamicImage, BoxedError> {\n\n let format = match mime_type {\n\n Some(\"image/png\") => Some(image::ImageFormat::Png),\n\n Some(\"image/jpeg\") => Some(image::ImageFormat::Jpeg),\n\n _ => None,\n\n };\n\n\n\n Ok(match format {\n\n Some(format) => image::load_from_memory_with_format(buffer, format),\n\n None => image::load_from_memory(buffer),\n\n }?)\n\n}\n\n\n", "file_path": "src/asset/gltf.rs", "rank": 31, "score": 86096.59004035962 }, { "content": "#[derive(Clone, Copy)]\n\nstruct BorrowedCache<'a> {\n\n assets: &'a AssetMap,\n\n source: &'a (dyn Source + 'static),\n\n reloader: &'a super::HotReloader,\n\n}\n\n\n\nimpl<'a> crate::anycache::RawCache for BorrowedCache<'a> {\n\n fn assets(&self) -> &AssetMap {\n\n self.assets\n\n }\n\n\n\n fn reloader(&self) -> Option<&super::HotReloader> {\n\n Some(self.reloader)\n\n }\n\n}\n\n\n\nimpl<'a> crate::anycache::RawCacheWithSource for BorrowedCache<'a> {\n\n type Source = &'a dyn Source;\n\n\n\n fn get_source(&self) -> &&'a (dyn Source + 'static) {\n", "file_path": "src/hot_reloading/paths.rs", "rank": 32, "score": 85801.94626080987 }, { "content": "#[test]\n\nfn string_loader_utf8_err() {\n\n let raw = b\"e\\xa2\"[..].into();\n\n let result: Result<String, _> = StringLoader::load(raw, \"\");\n\n assert!(result.is_err());\n\n}\n\n\n", "file_path": "src/loader/tests.rs", "rank": 33, "score": 84406.05988295643 }, { "content": "/// Mark a type as not being hot-reloaded.\n\n///\n\n/// At the moment, the only use of this trait is to enable `Handle::get` for\n\n/// types that implement it.\n\n///\n\n/// If you implement this trait on a type that also implement [`Asset`] or\n\n/// [`Compound`], you MUST set [`Asset::HOT_RELOADED`] (or\n\n/// [`Compound::HOT_RELOADED`] to `true` or you will get compile-error at best\n\n/// and panics at worst.\n\n///\n\n/// On a type that implements [`Storable`] directly, you can implement this\n\n/// trait wihout issues.\n\n///\n\n/// This trait is a workaround about Rust's type system current limitations.\n\npub trait NotHotReloaded: Storable {}\n\n\n", "file_path": "src/asset.rs", "rank": 34, "score": 84125.80547555881 }, { "content": "#[derive(Clone)]\n\nstruct Bin(Vec<u8>);\n\n\n\nimpl Asset for Bin {\n\n const EXTENSION: &'static str = \"bin\";\n\n type Loader = loader::LoadFrom<Vec<u8>, loader::BytesLoader>;\n\n}\n\n\n\nimpl From<Vec<u8>> for Bin {\n\n fn from(bytes: Vec<u8>) -> Self {\n\n Self(bytes)\n\n }\n\n}\n\n\n", "file_path": "src/asset/gltf.rs", "rank": 35, "score": 83334.71518795732 }, { "content": "/// Trait marker to store values in a cache.\n\n///\n\n/// Implementing this trait is necessary to use [`AssetCache::get_cached`]. This\n\n/// trait is already implemented for all `Compound` types.\n\n///\n\n/// This trait is a workaround about Rust's current lack of specialization.\n\npub trait Storable: Send + Sync + 'static {\n\n #[doc(hidden)]\n\n const HOT_RELOADED: bool = false;\n\n\n\n #[doc(hidden)]\n\n /// Compile-time check that HOT_RELOADED is false when `NotHotReloaded` is\n\n /// implemented.\n\n /// ```compile_fail\n\n /// use assets_manager::{Asset, asset::NotHotReloaded, AssetCache, loader};\n\n ///\n\n /// struct A(i32);\n\n /// impl From<i32> for A {\n\n /// fn from(x: i32) -> A { A(x) }\n\n /// }\n\n ///\n\n /// impl Asset for A {\n\n /// type Loader = loader::LoadFrom<i32, loader::ParseLoader>;\n\n /// }\n\n /// impl NotHotReloaded for A {}\n\n ///\n", "file_path": "src/asset.rs", "rank": 36, "score": 78594.56988505769 }, { "content": "#[derive(Clone, Hash, PartialEq, Eq)]\n\nstruct FileDesc(Arc<(String, String)>);\n\n\n\nimpl fmt::Debug for FileDesc {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"FileDesc\")\n\n .field(\"id\", &self.0 .0)\n\n .field(\"ext\", &self.0 .1)\n\n .finish()\n\n }\n\n}\n\n\n", "file_path": "src/source/zip.rs", "rank": 37, "score": 77049.30633621747 }, { "content": "/// An asset type that can load other kinds of assets.\n\n///\n\n/// `Compound`s can be loaded and retrieved by an [`AssetCache`].\n\n///\n\n/// A `Compound` often needs to reference other assets, but `Compound` requires\n\n/// `'static` and a `Handle` is borrowed. See [top-level documentation] for\n\n/// workarounds.\n\n///\n\n/// [top-level documentation]: crate#getting-owned-data\n\n///\n\n/// Note that all [`Asset`]s implement `Compound`.\n\n///\n\n/// # Hot-reloading\n\n///\n\n/// Any asset loaded from the given cache is registered as a dependency of the\n\n/// Compound. When the former is reloaded, the latter will be reloaded too. An\n\n/// asset cannot depend on itself, or it may cause deadlocks to happen.\n\n///\n\n/// To opt out of dependencies recording, use [`AssetCache::no_record`].\n\npub trait Compound: Sized + Send + Sync + 'static {\n\n /// Loads an asset from the cache.\n\n ///\n\n /// This function should not perform any kind of I/O: such concern should be\n\n /// delegated to [`Asset`]s.\n\n fn load(cache: AnyCache, id: &str) -> Result<Self, BoxedError>;\n\n\n\n /// Loads an asset and registers it for hot-reloading if necessary.\n\n ///\n\n /// This method is a internal implementation detail.\n\n #[doc(hidden)]\n\n fn _load_and_record<P: PrivateMarker>(\n\n cache: AnyCache,\n\n id: &SharedString,\n\n ) -> Result<Self, Error> {\n\n #[cfg(feature = \"hot-reloading\")]\n\n let res = if Self::HOT_RELOADED {\n\n cache.record_load(id).map(|(asset, deps)| {\n\n if let Some(reloader) = cache.reloader() {\n\n reloader.add_compound::<Self>(id.clone(), deps);\n", "file_path": "src/asset.rs", "rank": 38, "score": 75108.0194022433 }, { "content": "fn main() -> Result<(), BoxedError> {\n\n // The cache used to load assets\n\n // Its root is directory `assets`\n\n let cache = AssetCache::new(\"assets\")?;\n\n\n\n // Load an asset with type `Vec<MonsterStats>`\n\n // The result is a lock on the stats\n\n let goblin = cache.load::<Monster>(\"example.monsters.goblin\")?;\n\n\n\n // Lock the asset for reading. This is necessary because we might want to\n\n // reload it from disk (eg with hot-reloading)\n\n let goblin = goblin.read();\n\n\n\n // Use it\n\n println!(\n\n \"A {} ({}) has {} HP\",\n\n goblin.name, goblin.description, goblin.health\n\n );\n\n\n\n Ok(())\n\n}\n", "file_path": "examples/basic.rs", "rank": 39, "score": 74994.76467599449 }, { "content": "fn main() -> Result<(), BoxedError> {\n\n env_logger::builder()\n\n .filter_level(log::LevelFilter::Info)\n\n .init();\n\n\n\n let cache = AssetCache::new(\"assets\")?;\n\n\n\n // Load the Level from the cache\n\n let level = cache.load::<Level>(\"example.levels.forest\")?;\n\n let mut watcher = level.reload_watcher();\n\n\n\n println!(\"{:#?}\", level);\n\n\n\n loop {\n\n cache.hot_reload();\n\n\n\n // Touching one of these files will cause `level` to be reloaded:\n\n // - assets/example/levels/forest.ron\n\n // - assets/example/monsters/goblin.ron\n\n // - assets/example/monsters/giant_bat.ron\n\n if watcher.reloaded() {\n\n println!(\"{:#?}\", level);\n\n }\n\n\n\n std::thread::sleep(std::time::Duration::from_millis(100));\n\n }\n\n}\n", "file_path": "examples/compound.rs", "rank": 40, "score": 74994.76467599449 }, { "content": "fn main() -> Result<(), BoxedError> {\n\n env_logger::builder()\n\n .filter_level(log::LevelFilter::Info)\n\n .init();\n\n\n\n let cache = AssetCache::new(\"assets\")?;\n\n\n\n // The asset reference is obtained outside the loop\n\n let text = cache.load::<String>(\"example.hello\")?;\n\n\n\n // Indefinitly reload assets if they changed and print `text`\n\n loop {\n\n cache.hot_reload();\n\n\n\n println!(\"{}\", text.read());\n\n\n\n sleep(Duration::from_millis(200));\n\n }\n\n}\n", "file_path": "examples/hot_reloading.rs", "rank": 41, "score": 73788.12593258233 }, { "content": " /// Returns the path that the directory entry would have if it exists.\n\n #[inline]\n\n pub fn path_of(&self, entry: DirEntry) -> PathBuf {\n\n crate::utils::path_of_entry(&self.path, entry)\n\n }\n\n}\n\n\n\nimpl Source for FileSystem {\n\n fn read(&self, id: &str, ext: &str) -> io::Result<Cow<[u8]>> {\n\n let path = self.path_of(DirEntry::File(id, ext));\n\n fs::read(path).map(Into::into)\n\n }\n\n\n\n fn read_dir(&self, id: &str, f: &mut dyn FnMut(DirEntry)) -> io::Result<()> {\n\n let dir_path = self.path_of(DirEntry::Directory(id));\n\n let entries = fs::read_dir(dir_path)?;\n\n\n\n let mut entry_id = id.to_owned();\n\n\n\n // Ignore entries that return an error\n", "file_path": "src/source/filesystem.rs", "rank": 42, "score": 70266.43090738165 }, { "content": "use crate::{\n\n hot_reloading::{DynUpdateSender, EventSender, FsWatcherBuilder},\n\n utils::extension_of,\n\n BoxedError,\n\n};\n\n\n\n#[cfg(doc)]\n\nuse crate::AssetCache;\n\n\n\nuse std::{\n\n borrow::Cow,\n\n fmt, fs, io,\n\n path::{Path, PathBuf},\n\n};\n\n\n\nuse super::{DirEntry, Source};\n\n\n\n/// A [`Source`] to load assets from a directory in the file system.\n\n///\n\n/// This is the default `Source` of [`AssetCache`].\n", "file_path": "src/source/filesystem.rs", "rank": 43, "score": 70250.19100588578 }, { "content": " /// reading from the filesystem.\n\n ///\n\n /// # Errors\n\n ///\n\n /// An error can occur if `path` is not a valid readable directory.\n\n pub fn new<P: AsRef<Path>>(path: P) -> io::Result<FileSystem> {\n\n let path = path.as_ref().canonicalize()?;\n\n let _ = path.read_dir()?;\n\n\n\n Ok(FileSystem { path })\n\n }\n\n\n\n /// Gets the path of the source's root.\n\n ///\n\n /// The path is currently given as absolute, but this may change in the future.\n\n #[inline]\n\n pub fn root(&self) -> &Path {\n\n &self.path\n\n }\n\n\n", "file_path": "src/source/filesystem.rs", "rank": 44, "score": 70249.69062737147 }, { "content": " } else if path.is_dir() {\n\n f(DirEntry::Directory(this_id));\n\n }\n\n }\n\n\n\n Ok(())\n\n }\n\n\n\n fn exists(&self, entry: DirEntry) -> bool {\n\n self.path_of(entry).exists()\n\n }\n\n\n\n fn make_source(&self) -> Option<Box<dyn Source + Send>> {\n\n Some(Box::new(self.clone()))\n\n }\n\n\n\n fn configure_hot_reloading(&self, events: EventSender) -> Result<DynUpdateSender, BoxedError> {\n\n let mut watcher = FsWatcherBuilder::new()?;\n\n watcher.watch(self.path.clone())?;\n\n let reloader = watcher.build(events);\n", "file_path": "src/source/filesystem.rs", "rank": 45, "score": 70248.21270070848 }, { "content": "///\n\n/// ## Hot-reloading\n\n///\n\n/// This source supports hot-reloading: when a file is edited, the corresponding\n\n/// assets are reloaded when [`AssetCache::hot_reload`] is called.\n\n///\n\n/// ## WebAssembly\n\n///\n\n/// This source does not work in WebAssembly, because there is no file system.\n\n/// When called, it always returns an error.\n\n#[derive(Clone)]\n\npub struct FileSystem {\n\n path: PathBuf,\n\n}\n\n\n\nimpl FileSystem {\n\n /// Creates a new `FileSystem` from a directory.\n\n ///\n\n /// Generally you do not need to call this function directly, as the\n\n /// [`AssetCache::new`] method provides a shortcut to create a cache\n", "file_path": "src/source/filesystem.rs", "rank": 46, "score": 70243.10114936986 }, { "content": " for entry in entries.flatten() {\n\n let path = entry.path();\n\n\n\n let name = match path.file_stem().and_then(|n| n.to_str()) {\n\n Some(name) => name,\n\n None => continue,\n\n };\n\n\n\n let this_id: &str = if !id.is_empty() {\n\n entry_id.truncate(id.len());\n\n entry_id.extend([\".\", name].iter().copied());\n\n &entry_id\n\n } else {\n\n name\n\n };\n\n\n\n if path.is_file() {\n\n if let Some(ext) = extension_of(&path) {\n\n f(DirEntry::File(this_id, ext));\n\n }\n", "file_path": "src/source/filesystem.rs", "rank": 47, "score": 70242.31315134757 }, { "content": " Ok(reloader)\n\n }\n\n}\n\n\n\nimpl fmt::Debug for FileSystem {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.debug_struct(\"FileSystem\")\n\n .field(\"root\", &self.path)\n\n .finish()\n\n }\n\n}\n", "file_path": "src/source/filesystem.rs", "rank": 48, "score": 70239.60284559659 }, { "content": "fn visit(dep_graph: &DepsGraph, sort: &mut TopologicalSortData, key: &OwnedKey, add_self: bool) {\n\n if sort.visited.contains(key) {\n\n return;\n\n }\n\n\n\n let deps = match dep_graph.0.get(key) {\n\n Some(deps) => deps,\n\n None => return,\n\n };\n\n\n\n for rdep in deps.rdeps.iter() {\n\n visit(dep_graph, sort, rdep, true);\n\n }\n\n\n\n sort.visited.insert(key.clone());\n\n if add_self {\n\n sort.list.push(key.clone());\n\n }\n\n}\n\n\n", "file_path": "src/hot_reloading/dependencies.rs", "rank": 49, "score": 67834.91748749473 }, { "content": "#[derive(Deserialize, Clone, Debug)]\n\n#[allow(dead_code)]\n\nstruct Monster {\n\n name: String,\n\n description: String,\n\n health: u32,\n\n}\n\n\n\n/// Monsters are stored in RON\n\nimpl Asset for Monster {\n\n const EXTENSION: &'static str = \"ron\";\n\n type Loader = loader::RonLoader;\n\n}\n\n\n\n/// The format of a level description.\n\n///\n\n/// Compound assets should not do filesytem operations, so we do this with\n\n/// another asset.\n", "file_path": "examples/compound.rs", "rank": 50, "score": 61344.03555226125 }, { "content": "struct Inner {\n\n extensions: &'static [&'static str],\n\n #[allow(clippy::type_complexity)]\n\n load: fn(&dyn Source, id: &str) -> Result<Box<dyn AnyAsset>, Error>,\n\n}\n\n\n\nimpl Inner {\n\n fn of<A: Asset>() -> &'static Self {\n\n &Inner {\n\n extensions: A::EXTENSIONS,\n\n load: load::<A>,\n\n }\n\n }\n\n}\n\n\n\n/// A structure to represent the type on an [`Asset`]\n\n#[derive(Clone, Copy)]\n\npub struct AssetType {\n\n // TODO: move this into `inner` when `TypeId::of` is const-stable\n\n type_id: TypeId,\n", "file_path": "src/key.rs", "rank": 51, "score": 61339.98002546241 }, { "content": "#[derive(Debug)]\n\n#[allow(dead_code)]\n\nstruct Level {\n\n id: String,\n\n name: String,\n\n\n\n /// A list of (Monster, spawn chance)\n\n spawn_table: Vec<(Arc<Monster>, f32)>,\n\n}\n\n\n\n/// Specify how to load a Level.\n\n///\n\n/// It will load the the corresponding manifest, and the necessary monsters.\n\n/// Note that when hot-reloading is enabled, `assets_manager` records the assets\n\n/// a Compound depends on. When a dependency is reloading, the Coumpound is also\n\n/// reloaded. You don't have to write hot-reloading-specific code.\n\nimpl Compound for Level {\n\n fn load(cache: AnyCache, id: &str) -> Result<Self, BoxedError> {\n\n // Load the manifest\n\n let raw_level = cache.load::<LevelManifest>(id)?.read();\n\n\n\n // Prepare the spawn table\n", "file_path": "examples/compound.rs", "rank": 52, "score": 61339.98002546241 }, { "content": "#[derive(serde::Deserialize)]\n\nstruct Monster {\n\n name: String,\n\n description: String,\n\n health: u32,\n\n}\n\n\n\nimpl Asset for Monster {\n\n // The extension used by our type\n\n const EXTENSION: &'static str = \"ron\";\n\n\n\n // The way we load our data: here we use RON format\n\n type Loader = loader::RonLoader;\n\n}\n\n\n", "file_path": "examples/basic.rs", "rank": 53, "score": 61339.98002546241 }, { "content": "#[test]\n\nfn from_other() {\n\n let n = rand::random::<i32>();\n\n let s = &format!(\"{}\", n);\n\n let raw = raw(s);\n\n\n\n let loaded: X = LoadFrom::<i32, ParseLoader>::load(raw, \"\").unwrap();\n\n\n\n assert_eq!(loaded, X(n));\n\n}\n\n\n\ncfg_if::cfg_if! { if #[cfg(feature = \"serde\")] {\n\n use serde::{Serialize, Deserialize};\n\n use rand::{\n\n Rng,\n\n distributions::{Distribution, Standard},\n\n };\n\n\n\n #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)]\n\n struct Point {\n\n x: i32,\n", "file_path": "src/loader/tests.rs", "rank": 54, "score": 59906.700569573484 }, { "content": "#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nstruct Raw {\n\n zero: usize,\n\n ptr: *const Vec<u8>,\n\n}\n\n\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\nunion Inner {\n\n slice: *const [u8],\n\n vec: Raw,\n\n}\n\n\n\n/// Bytes that can easily be shared.\n\n///\n\n/// This structure is essentially a better alternative to an `Arc<Vec<u8>>`\n\n/// when created from a slice.\n\npub struct SharedBytes(Inner);\n\n\n\nunsafe impl Send for SharedBytes {}\n\nunsafe impl Sync for SharedBytes {}\n", "file_path": "src/utils/bytes.rs", "rank": 55, "score": 59777.74964736613 }, { "content": "struct ErrorRepr {\n\n id: SharedString,\n\n kind: ErrorKind,\n\n}\n\n\n\n/// The error type which is used when loading an asset.\n\npub struct Error(Box<ErrorRepr>);\n\n\n\nimpl Error {\n\n #[cold]\n\n pub(crate) fn from_io(id: SharedString, err: io::Error) -> Self {\n\n Self::from_kind(id, ErrorKind::Io(err))\n\n }\n\n\n\n pub(crate) fn from_kind(id: SharedString, kind: ErrorKind) -> Self {\n\n Self(Box::new(ErrorRepr { id, kind }))\n\n }\n\n\n\n #[cold]\n\n pub(crate) fn new(id: SharedString, err: BoxedError) -> Self {\n", "file_path": "src/error.rs", "rank": 56, "score": 59773.597467826155 }, { "content": "#[derive(Deserialize, Debug)]\n\nstruct LevelManifest {\n\n name: String,\n\n spawn_table: Vec<(String, u32)>,\n\n}\n\n\n\nimpl Asset for LevelManifest {\n\n const EXTENSION: &'static str = \"ron\";\n\n type Loader = loader::RonLoader;\n\n}\n\n\n\n/// The structure we use to store an in-game level\n", "file_path": "examples/compound.rs", "rank": 57, "score": 59773.597467826155 }, { "content": "struct Content {\n\n files: Vec<FileDesc>,\n\n dirs: HashMap<Id, Vec<DirEntry>>,\n\n}\n\n\n\nimpl Content {\n\n fn new() -> Content {\n\n Content {\n\n files: Vec::new(),\n\n dirs: HashMap::new(),\n\n }\n\n }\n\n\n\n fn push_file(&mut self, desc: FileDesc, dir_id: &Id) {\n\n let entry = DirEntry::File(desc.0.clone(), desc.1.clone());\n\n self.dirs\n\n .get_mut(dir_id)\n\n .expect(\"File without directory\")\n\n .push(entry);\n\n self.files.push(desc);\n", "file_path": "macros/src/embedded.rs", "rank": 58, "score": 59773.597467826155 }, { "content": "#[derive(Debug)]\n\nstruct NoDefaultValueError;\n\n\n\nimpl fmt::Display for NoDefaultValueError {\n\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n\n f.write_str(\"the asset has neither extension nor default value\")\n\n }\n\n}\n\n\n\nimpl StdError for NoDefaultValueError {}\n\n\n", "file_path": "src/error.rs", "rank": 59, "score": 58340.4846817111 }, { "content": "struct Record {\n\n reloader: *const HotReloader,\n\n records: Dependencies,\n\n}\n\n\n\nimpl Record {\n\n fn new(reloader: &HotReloader) -> Record {\n\n Record {\n\n reloader,\n\n records: Dependencies::empty(),\n\n }\n\n }\n\n\n\n fn insert(&mut self, reloader: &HotReloader, key: OwnedKey) {\n\n if self.reloader == reloader {\n\n self.records.0.insert(key);\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/hot_reloading/records.rs", "rank": 60, "score": 58340.4846817111 }, { "content": "#[derive(Default)]\n\nstruct Answers {\n\n next_token: AtomicUsize,\n\n current_token: Mutex<Option<usize>>,\n\n condvar: Condvar,\n\n}\n\n\n\nimpl Answers {\n\n fn get_unique_token(&self) -> usize {\n\n self.next_token.fetch_add(1, Ordering::Relaxed)\n\n }\n\n\n\n fn notify(&self, token: usize) {\n\n let guard = self.current_token.lock();\n\n // Make sure everyone consumed its answer token\n\n let mut guard = self.condvar.wait_while(guard, |t| t.is_some());\n\n *guard = Some(token);\n\n self.condvar.notify_all();\n\n }\n\n\n\n fn wait_for_answer(&self, token: usize) {\n", "file_path": "src/hot_reloading/mod.rs", "rank": 61, "score": 58340.4846817111 }, { "content": "#[test]\n\nfn messages() {\n\n use super::*;\n\n use crate::utils::Mutex;\n\n\n\n struct MessageChecker(Mutex<Vec<UpdateMessage>>);\n\n\n\n impl UpdateSender for MessageChecker {\n\n fn send_update(&self, message: UpdateMessage) {\n\n match self.0.lock().pop() {\n\n Some(expected) => assert_eq!(message, expected),\n\n None => panic!(\"Unexpected message {:?}\", message),\n\n }\n\n }\n\n }\n\n\n\n impl Drop for MessageChecker {\n\n fn drop(&mut self) {\n\n if !std::thread::panicking() {\n\n assert!(self.0.lock().is_empty());\n\n }\n", "file_path": "src/hot_reloading/tests.rs", "rank": 62, "score": 56922.8300769078 }, { "content": "#[cold]\n\n#[track_caller]\n\nfn wrong_handle_type() -> ! {\n\n panic!(\"wrong handle type\");\n\n}\n", "file_path": "src/entry.rs", "rank": 63, "score": 56922.8300769078 }, { "content": "fn sleep() {\n\n std::thread::sleep(std::time::Duration::from_millis(100));\n\n}\n\n\n", "file_path": "src/hot_reloading/tests.rs", "rank": 64, "score": 56922.8300769078 }, { "content": "#[cfg(feature = \"hot-reloading\")]\n\n#[derive(Debug, Clone, Copy)]\n\nstruct ReloadWatcherInner<'a> {\n\n reload_id: &'a AtomicReloadId,\n\n last_reload_id: ReloadId,\n\n}\n\n\n\n#[cfg(feature = \"hot-reloading\")]\n\nimpl<'a> ReloadWatcherInner<'a> {\n\n #[inline]\n\n fn new(reload_id: &'a AtomicReloadId) -> Self {\n\n Self {\n\n reload_id,\n\n last_reload_id: reload_id.load(),\n\n }\n\n }\n\n}\n\n\n\n/// A watcher that can tell when an asset is reloaded.\n\n///\n\n/// Each `ReloadWatcher` is associated to a single asset in a cache.\n\n///\n", "file_path": "src/entry.rs", "rank": 65, "score": 56074.239890946905 }, { "content": "struct TopologicalSortData {\n\n visited: HashSet<OwnedKey>,\n\n list: Vec<OwnedKey>,\n\n}\n\n\n", "file_path": "src/hot_reloading/dependencies.rs", "rank": 66, "score": 55811.370312095576 }, { "content": "fn translation_thread(\n\n _watcher: notify::RecommendedWatcher,\n\n roots: Vec<PathBuf>,\n\n notify: mpsc::Receiver<notify::DebouncedEvent>,\n\n updates: crossbeam_channel::Receiver<super::UpdateMessage>,\n\n events: super::EventSender,\n\n) {\n\n log::trace!(\"Starting hot-reloading translation thread\");\n\n\n\n let mut watched_paths = WatchedPaths::new(roots);\n\n\n\n while let Ok(event) = notify.recv() {\n\n loop {\n\n match updates.try_recv() {\n\n Ok(super::UpdateMessage::AddAsset(key)) => watched_paths.add_asset(key),\n\n Ok(super::UpdateMessage::RemoveAsset(key)) => watched_paths.remove_asset(key),\n\n Ok(super::UpdateMessage::Clear) => watched_paths.clear(),\n\n Err(crossbeam_channel::TryRecvError::Empty) => break,\n\n Err(crossbeam_channel::TryRecvError::Disconnected) => return,\n\n }\n", "file_path": "src/hot_reloading/watcher.rs", "rank": 67, "score": 55613.529012047264 }, { "content": " pub trait PrivateMarker {}\n\n pub(crate) enum Private {}\n\n impl PrivateMarker for Private {}\n\n}\n\n\n\npub(crate) use private_marker::{Private, PrivateMarker};\n\n\n\n#[cfg(feature = \"ahash\")]\n\npub(crate) use ahash::RandomState;\n\n\n\n#[cfg(not(feature = \"ahash\"))]\n\npub(crate) use std::collections::hash_map::RandomState;\n\n\n\npub(crate) struct HashMap<K, V>(StdHashMap<K, V, RandomState>);\n\n\n\nimpl<K, V> HashMap<K, V> {\n\n #[inline]\n\n #[allow(unused)]\n\n pub fn new() -> Self {\n\n Self(StdHashMap::with_hasher(RandomState::new()))\n", "file_path": "src/utils/private.rs", "rank": 68, "score": 55599.017389219785 }, { "content": "fn hot_reloading_thread(\n\n source: Box<dyn Source>,\n\n events: Receiver<Events>,\n\n cache_msg: Receiver<CacheMessage>,\n\n answers: Arc<Answers>,\n\n) {\n\n log::info!(\"Starting hot-reloading\");\n\n\n\n let mut cache = HotReloadingData::new(source);\n\n\n\n let mut select = channel::Select::new();\n\n select.recv(&cache_msg);\n\n select.recv(&events);\n\n\n\n loop {\n\n let ready = select.select();\n\n match ready.index() {\n\n 0 => match ready.recv(&cache_msg) {\n\n Ok(CacheMessage::Ptr(ptr, reloader, token)) => {\n\n // Safety: The received pointer is guaranteed to\n", "file_path": "src/hot_reloading/mod.rs", "rank": 69, "score": 54406.89026863509 }, { "content": "/// Defines how to handle updates.\n\n///\n\n/// Cache updates are sent to the hot-reloading subsystem through this trait.\n\npub trait UpdateSender {\n\n /// Sends an update to the hot-reloading subsystem. This function should be\n\n /// quick and should not block.\n\n fn send_update(&self, message: UpdateMessage);\n\n}\n\n\n\n/// A type-erased `UpdateSender`.\n\npub type DynUpdateSender = Box<dyn UpdateSender + Send + Sync>;\n\n\n\nimpl<T> UpdateSender for Box<T>\n\nwhere\n\n T: UpdateSender + ?Sized,\n\n{\n\n fn send_update(&self, message: UpdateMessage) {\n\n (**self).send_update(message)\n\n }\n\n}\n\n\n\nimpl<T> UpdateSender for std::sync::Arc<T>\n\nwhere\n", "file_path": "src/hot_reloading/mod.rs", "rank": 70, "score": 54381.44398325271 }, { "content": "pub trait UpdateSender {\n\n fn send_update(&self, update: UpdateMessage);\n\n}\n\n\n\npub type DynUpdateSender = Box<dyn UpdateSender + Send + Sync>;\n\n\n\nimpl<T> UpdateSender for Box<T>\n\nwhere\n\n T: UpdateSender + ?Sized,\n\n{\n\n fn send_update(&self, message: UpdateMessage) {\n\n (**self).send_update(message)\n\n }\n\n}\n\n\n\nimpl<T> UpdateSender for std::sync::Arc<T>\n\nwhere\n\n T: UpdateSender + ?Sized,\n\n{\n\n fn send_update(&self, message: UpdateMessage) {\n", "file_path": "src/hot_reloading/disabled.rs", "rank": 71, "score": 54381.44398325271 }, { "content": "/// Assets that are loadable from directories\n\n///\n\n/// Types that implement this trait can be used with [`AssetCache::load_dir`] to\n\n/// load all available assets in a directory (eventually recursively).\n\n///\n\n/// This trait is automatically implemented for all types that implement\n\n/// [`Asset`], and you can implement it to extend your own `Compound`s.\n\n///\n\n/// # Exemple implementation\n\n///\n\n/// Imagine you have several playlists with a JSON manifest to specify the ids\n\n/// of the musics to include.\n\n///\n\n/// ```no_run\n\n/// # cfg_if::cfg_if! { if #[cfg(all(feature = \"json\", feature = \"flac\"))] {\n\n/// use assets_manager::{\n\n/// Compound, BoxedError, AnyCache, SharedString,\n\n/// asset::{DirLoadable, Json, Flac},\n\n/// source::{DirEntry, Source},\n\n/// };\n\n///\n\n/// /// A simple playlist, a mere ordered list of musics\n\n/// struct Playlist {\n\n/// sounds: Vec<Flac>\n\n/// }\n\n///\n\n/// // Specify how to load a playlist\n\n/// impl Compound for Playlist {\n\n/// fn load(cache: AnyCache, id: &str) -> Result<Self, BoxedError> {\n\n/// // Read the manifest (a list of ids)\n\n/// let manifest = cache.load::<Json<Vec<String>>>(id)?.read();\n\n///\n\n/// // Load each sound\n\n/// let sounds = manifest.0.iter()\n\n/// .map(|id| Ok(cache.load::<Flac>(id)?.cloned()))\n\n/// .collect::<Result<_, BoxedError>>()?;\n\n///\n\n/// Ok(Playlist { sounds })\n\n/// }\n\n/// }\n\n///\n\n/// // Specify how to get ids of playlists in a directory\n\n/// impl DirLoadable for Playlist {\n\n/// fn select_ids<S: Source + ?Sized>(source: &S, id: &str) -> std::io::Result<Vec<SharedString>> {\n\n/// let mut ids = Vec::new();\n\n///\n\n/// // Select all files with \"json\" extension (manifest files)\n\n/// source.read_dir(id, &mut |entry| {\n\n/// if let DirEntry::File(id, ext) = entry {\n\n/// if ext == \"json\" {\n\n/// ids.push(id.into());\n\n/// }\n\n/// }\n\n/// })?;\n\n///\n\n/// Ok(ids)\n\n/// }\n\n/// }\n\n/// # }}\n\n/// ```\n\npub trait DirLoadable: Compound {\n\n /// Returns the ids of the assets contained in the directory given by `id`.\n\n ///\n\n /// Note that the order of the returned ids is not kept, and that redundant\n\n /// ids are removed.\n\n fn select_ids<S: Source + ?Sized>(source: &S, id: &str) -> io::Result<Vec<SharedString>>;\n\n}\n\n\n\nimpl<A> DirLoadable for A\n\nwhere\n\n A: Asset,\n\n{\n\n #[inline]\n\n fn select_ids<S: Source + ?Sized>(source: &S, id: &str) -> io::Result<Vec<SharedString>> {\n\n fn inner<S: Source + ?Sized>(\n\n source: &S,\n\n id: &str,\n\n extensions: &[&str],\n\n ) -> io::Result<Vec<SharedString>> {\n\n let mut ids = Vec::new();\n", "file_path": "src/dirs.rs", "rank": 72, "score": 53677.750589789175 }, { "content": "pub trait Loader<T> {\n\n /// Loads an asset from its raw bytes representation.\n\n ///\n\n /// The extension used to load the asset is also passed as parameter, which can\n\n /// be useful to guess the format if an asset type uses several extensions.\n\n fn load(content: Cow<[u8]>, ext: &str) -> Result<T, BoxedError>;\n\n}\n\n\n\n/// Loads assets from another type.\n\n///\n\n/// An example case for this is to easily load wrapper types, which are needed\n\n/// when the wrapped type is defined in another crate.\n\n///\n\n/// # Example\n\n///\n\n/// ```\n\n/// use assets_manager::{Asset, loader::{LoadFrom, ParseLoader}};\n\n/// use std::net::IpAddr;\n\n///\n\n/// struct Ip(IpAddr);\n", "file_path": "src/loader/mod.rs", "rank": 73, "score": 53634.069624604825 }, { "content": "/// Makes sure the value in a cell is reset when scope ends.\n\nstruct CellGuard<'a, T: Copy> {\n\n cell: &'a Cell<T>,\n\n val: T,\n\n}\n\n\n\nimpl<'a, T: Copy> CellGuard<'a, T> {\n\n fn replace(cell: &'a Cell<T>, new_value: T) -> Self {\n\n let val = cell.replace(new_value);\n\n Self { cell, val }\n\n }\n\n}\n\n\n\nimpl<T: Copy> Drop for CellGuard<'_, T> {\n\n fn drop(&mut self) {\n\n self.cell.set(self.val);\n\n }\n\n}\n\n\n\nthread_local! {\n\n static RECORDING: Cell<Option<NonNull<Record>>> = Cell::new(None);\n", "file_path": "src/hot_reloading/records.rs", "rank": 74, "score": 48888.91240981807 }, { "content": "#[cfg(feature = \"parking_lot\")]\n\n#[inline]\n\nfn wrap<T>(param: T) -> T {\n\n param\n\n}\n\n\n", "file_path": "src/utils/private.rs", "rank": 75, "score": 46435.35270846296 }, { "content": "#[repr(align(64))]\n\nstruct Shard(RwLock<HashMap<OwnedKey, CacheEntry>>);\n\n\n\n/// A map to store assets, optimized for concurrency.\n\n///\n\n/// This type has several uses:\n\n/// - Provide a safe wrapper to ensure that no issue with lifetimes happen.\n\n/// - Make a sharded lock map to reduce contention on the `RwLock` that guard\n\n/// inner `HashMap`s.\n\n/// - Provide an interface with the minimum of generics to reduce compile times.\n\npub(crate) struct AssetMap {\n\n hash_builder: RandomState,\n\n shards: Box<[Shard]>,\n\n}\n\n\n\nimpl AssetMap {\n\n fn new(min_shards: usize) -> AssetMap {\n\n let shards = min_shards.next_power_of_two();\n\n\n\n let hash_builder = RandomState::new();\n\n let shards = (0..shards)\n", "file_path": "src/cache.rs", "rank": 76, "score": 44580.78833157757 }, { "content": "struct UpdateSender(crossbeam_channel::Sender<super::UpdateMessage>);\n\n\n\nimpl super::UpdateSender for UpdateSender {\n\n fn send_update(&self, message: super::UpdateMessage) {\n\n let _ = self.0.send(message);\n\n }\n\n}\n\n\n\n/// Built-in reloader based on filesystem events.\n\n///\n\n/// You can use it to quickly set up hot-reloading for a custom [`Source`].\n\npub struct FsWatcherBuilder {\n\n roots: Vec<PathBuf>,\n\n watcher: notify::RecommendedWatcher,\n\n notify: mpsc::Receiver<notify::DebouncedEvent>,\n\n}\n\n\n\nimpl FsWatcherBuilder {\n\n /// Creates a new builder.\n\n pub fn new() -> Result<Self, BoxedError> {\n", "file_path": "src/hot_reloading/watcher.rs", "rank": 77, "score": 43738.481854183075 }, { "content": "#[cfg(not(feature = \"parking_lot\"))]\n\n#[inline]\n\nfn wrap<T>(param: sync::LockResult<T>) -> T {\n\n // Just ignore poison errors\n\n param.unwrap_or_else(sync::PoisonError::into_inner)\n\n}\n\n\n\n/// `RwLock` from `parking_lot` and `std` have different APIs, so we use this\n\n/// simple wrapper to easily permit both.\n\npub(crate) struct RwLock<T: ?Sized>(sync::RwLock<T>);\n\n\n\n#[allow(unused)]\n\nimpl<T> RwLock<T> {\n\n #[inline]\n\n pub fn new(inner: T) -> Self {\n\n Self(sync::RwLock::new(inner))\n\n }\n\n\n\n #[inline]\n\n pub fn into_inner(self) -> T {\n\n wrap(self.0.into_inner())\n\n }\n", "file_path": "src/utils/private.rs", "rank": 78, "score": 41361.5713907062 }, { "content": "fn to_compile_errors(errors: Vec<syn::Error>) -> proc_macro2::TokenStream {\n\n let errors = errors.iter().map(|e| e.to_compile_error());\n\n\n\n quote::quote! { #(#errors)* }\n\n}\n", "file_path": "macros/src/lib.rs", "rank": 79, "score": 39738.92331985182 }, { "content": " }\n\n\n\n /// If `false`, disable hot-reloading for assets of this type (`true` by\n\n /// default). If so, you may want to implement [`NotHotReloaded`] for this\n\n /// type to enable additional functions.\n\n const HOT_RELOADED: bool = true;\n\n\n\n #[doc(hidden)]\n\n fn get_key<P: PrivateMarker>() -> Option<crate::key::AssetType> {\n\n None\n\n }\n\n}\n\n\n\nimpl<A> Compound for A\n\nwhere\n\n A: Asset,\n\n{\n\n #[inline]\n\n fn load(cache: AnyCache, id: &str) -> Result<Self, BoxedError> {\n\n Ok(load_from_source(&cache.source(), id)?)\n", "file_path": "src/asset.rs", "rank": 80, "score": 36450.457592868755 }, { "content": " }\n\n asset\n\n })\n\n } else {\n\n cache.no_record(|| Self::load(cache, id))\n\n };\n\n\n\n #[cfg(not(feature = \"hot-reloading\"))]\n\n let res = Self::load(cache, id);\n\n\n\n res.map_err(|err| Error::new(id.clone(), err))\n\n }\n\n\n\n #[doc(hidden)]\n\n fn _load_and_record_entry<P: PrivateMarker>(\n\n cache: AnyCache,\n\n id: SharedString,\n\n ) -> Result<CacheEntry, Error> {\n\n let asset = Self::_load_and_record::<P>(cache, &id)?;\n\n Ok(CacheEntry::new(asset, id))\n", "file_path": "src/asset.rs", "rank": 81, "score": 36450.33092020185 }, { "content": " /// kind: String,\n\n /// }\n\n ///\n\n /// impl Asset for Item {\n\n /// const EXTENSION: &'static str = \"json\";\n\n /// type Loader = loader::JsonLoader;\n\n ///\n\n /// fn default_value(id: &str, error: Error) -> Result<Item, Error> {\n\n /// eprintln!(\"Error loading {}: {}. Using default value\", id, error);\n\n /// Ok(Item::default())\n\n /// }\n\n /// }\n\n /// # }}\n\n /// ```\n\n #[inline]\n\n #[allow(unused_variables)]\n\n fn default_value(id: &str, error: Error) -> Result<Self, Error> {\n\n Err(error)\n\n }\n\n\n", "file_path": "src/asset.rs", "rank": 82, "score": 36450.27052853085 }, { "content": " }\n\n\n\n #[doc(hidden)]\n\n fn _load_and_record<P: PrivateMarker>(\n\n cache: AnyCache,\n\n id: &SharedString,\n\n ) -> Result<Self, Error> {\n\n let asset = load_from_source(&cache.source(), id)?;\n\n\n\n #[cfg(feature = \"hot-reloading\")]\n\n if A::HOT_RELOADED {\n\n if let Some(reloader) = cache.reloader() {\n\n reloader.add_asset::<Self>(id.clone());\n\n }\n\n }\n\n\n\n Ok(asset)\n\n }\n\n\n\n const HOT_RELOADED: bool = Self::HOT_RELOADED;\n", "file_path": "src/asset.rs", "rank": 83, "score": 36449.32126088671 }, { "content": " Ok($name::new(bytes)?)\n\n }\n\n }\n\n\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n impl Asset for $name {\n\n const EXTENSIONS: &'static [&'static str] = &[$( $ext ),*];\n\n type Loader = loader::SoundLoader;\n\n }\n\n\n\n #[cfg(feature = $feature)]\n\n impl $name {\n\n /// Creates a new sound from raw bytes.\n\n #[inline]\n\n pub fn new(bytes: SharedBytes) -> Result<$name, DecoderError> {\n\n let _ = $decoder(io::Cursor::new(&bytes))?;\n\n Ok($name(bytes))\n\n }\n\n\n", "file_path": "src/asset.rs", "rank": 84, "score": 36448.739365807705 }, { "content": "\n\n #[doc(hidden)]\n\n fn get_key<P: PrivateMarker>() -> Option<crate::key::AssetType> {\n\n Some(crate::key::AssetType::of::<Self>())\n\n }\n\n}\n\n\n\nimpl<A> Compound for Arc<A>\n\nwhere\n\n A: Compound,\n\n{\n\n fn load(cache: AnyCache, id: &str) -> Result<Self, BoxedError> {\n\n let asset = cache.load_owned::<A>(id)?;\n\n Ok(Arc::new(asset))\n\n }\n\n\n\n const HOT_RELOADED: bool = A::HOT_RELOADED;\n\n}\n\n\n\nimpl<A> NotHotReloaded for Arc<A> where A: Compound + NotHotReloaded {}\n\n\n", "file_path": "src/asset.rs", "rank": 85, "score": 36448.0331428689 }, { "content": " #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n #[derive(Clone, Debug)]\n\n #[repr(transparent)]\n\n pub struct $name(pub image::DynamicImage);\n\n\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n impl loader::Loader<$name> for loader::ImageLoader {\n\n #[inline]\n\n fn load(content: Cow<[u8]>, _: &str) -> Result<$name, BoxedError> {\n\n let img = image::load_from_memory_with_format(&content, $format)?;\n\n Ok($name(img))\n\n }\n\n }\n\n\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n impl Asset for $name {\n\n const EXTENSIONS: &'static [&'static str] = &[$( $ext ),*];\n", "file_path": "src/asset.rs", "rank": 86, "score": 36447.2838503692 }, { "content": "use std::{borrow::Cow, io, sync::Arc};\n\n\n\n#[cfg(feature = \"gltf\")]\n\npub use gltf::Gltf;\n\n\n\n/// An asset is a type loadable from raw bytes.\n\n///\n\n/// `Asset`s can be loaded and retrieved by an [`AssetCache`].\n\n///\n\n/// This trait should only perform a conversion from raw bytes to the concrete\n\n/// type. If you need to load other assets, please use the [`Compound`] trait.\n\n///\n\n/// # Extension\n\n///\n\n/// You can provide several extensions that will be used to search and load\n\n/// assets. When loaded, each extension is tried in order until a file is\n\n/// correctly loaded or no extension remains. The empty string `\"\"` means a file\n\n/// without extension. You cannot use character `.`.\n\n///\n\n/// The `EXTENSION` field is a convenient shortcut if your asset uses only one\n", "file_path": "src/asset.rs", "rank": 87, "score": 36444.520172585755 }, { "content": " #[cfg(feature = $feature:literal)]\n\n struct $name:ident => (\n\n $decoder:path,\n\n [$($ext:literal),*],\n\n );\n\n )*\n\n ) => {\n\n $(\n\n #[doc = $doc]\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n #[derive(Clone, Debug)]\n\n pub struct $name(SharedBytes);\n\n\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n\n impl loader::Loader<$name> for loader::SoundLoader {\n\n #[inline]\n\n fn load(content: Cow<[u8]>, _: &str) -> Result<$name, BoxedError> {\n\n let bytes = content.into();\n", "file_path": "src/asset.rs", "rank": 88, "score": 36444.36188632592 }, { "content": " fn get_key<P: PrivateMarker>() -> Option<crate::key::AssetType> {\n\n Self::get_key::<P>()\n\n }\n\n}\n\n\n\nmacro_rules! string_assets {\n\n ( $( $typ:ty, )* ) => {\n\n $(\n\n impl Asset for $typ {\n\n const EXTENSION: &'static str = \"txt\";\n\n type Loader = loader::StringLoader;\n\n }\n\n )*\n\n }\n\n}\n\n\n\nstring_assets! {\n\n String, Box<str>, SharedString,\n\n}\n\n\n", "file_path": "src/asset.rs", "rank": 89, "score": 36443.810690999315 }, { "content": " /// this method returns `Ok`, the returned value is used as an asset. In\n\n /// particular, if this method always returns `Ok`, `AssetCache::load` is\n\n /// guaranteed not to fail.\n\n ///\n\n /// The `id` parameter is given to easily report the error.\n\n ///\n\n /// By default, this method always returns an error.\n\n ///\n\n /// # Example\n\n ///\n\n /// On error, log it and return a default value:\n\n ///\n\n /// ```no_run\n\n /// # cfg_if::cfg_if! { if #[cfg(feature = \"json\")] {\n\n /// use assets_manager::{Asset, Error, loader};\n\n /// use serde::Deserialize;\n\n ///\n\n /// #[derive(Deserialize, Default)]\n\n /// struct Item {\n\n /// name: String,\n", "file_path": "src/asset.rs", "rank": 90, "score": 36443.22971892693 }, { "content": " #[derive(Debug, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]\n\n #[serde(transparent)]\n\n #[repr(transparent)]\n\n pub struct $name<T>(pub T);\n\n\n\n #[cfg(feature = $feature)]\n\n impl<T> Clone for $name<T>\n\n where\n\n T: Clone\n\n {\n\n fn clone(&self) -> Self {\n\n Self(self.0.clone())\n\n }\n\n\n\n fn clone_from(&mut self, other: &Self) {\n\n self.0.clone_from(&other.0)\n\n }\n\n }\n\n\n\n #[cfg(feature = $feature)]\n", "file_path": "src/asset.rs", "rank": 91, "score": 36443.05289147705 }, { "content": " /// If `false`, disable hot-reloading for assets of this type (`true` by\n\n /// default). If so, you may want to implement [`NotHotReloaded`] for this\n\n /// type to enable additional functions.\n\n const HOT_RELOADED: bool = true;\n\n}\n\n\n\nimpl<A> Asset for Box<A>\n\nwhere\n\n A: Asset,\n\n{\n\n const EXTENSIONS: &'static [&'static str] = A::EXTENSIONS;\n\n type Loader = loader::LoadFromAsset<A>;\n\n\n\n #[inline]\n\n fn default_value(id: &str, error: Error) -> Result<Box<A>, Error> {\n\n A::default_value(id, error).map(Box::new)\n\n }\n\n\n\n const HOT_RELOADED: bool = A::HOT_RELOADED;\n\n}\n\n\n\nimpl<A> NotHotReloaded for Box<A> where A: Asset + NotHotReloaded {}\n\n\n", "file_path": "src/asset.rs", "rank": 92, "score": 36443.00221489467 }, { "content": "\n\nmacro_rules! serde_assets {\n\n (\n\n $(\n\n #[doc = $doc:literal]\n\n #[cfg(feature = $feature:literal)]\n\n struct $name:ident => (\n\n $loader:path,\n\n [$($ext:literal),*],\n\n );\n\n )*\n\n ) => {\n\n $(\n\n #[doc = $doc]\n\n ///\n\n /// This type can directly be used as an [`Asset`] to load values\n\n /// from an [`AssetCache`]. This is useful to load assets external\n\n /// types without a newtype wrapper (eg [`Vec`]).\n\n #[cfg(feature = $feature)]\n\n #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]\n", "file_path": "src/asset.rs", "rank": 93, "score": 36442.767036063386 }, { "content": " /// let cache = AssetCache::new(\"assets\")?;\n\n /// let handle = cache.load::<A>(\"tests\")?;\n\n /// let _ = handle.get();\n\n /// # Ok::<(), assets_manager::BoxedError>(())\n\n /// ```\n\n const _CHECK_NOT_HOT_RELOADED: () = [()][Self::HOT_RELOADED as usize];\n\n\n\n #[doc(hidden)]\n\n fn get_key<P: PrivateMarker>() -> Option<crate::key::AssetType> {\n\n None\n\n }\n\n}\n\n\n\nimpl<A> Storable for A\n\nwhere\n\n A: Compound,\n\n{\n\n #[doc(hidden)]\n\n const HOT_RELOADED: bool = A::HOT_RELOADED;\n\n\n", "file_path": "src/asset.rs", "rank": 94, "score": 36441.48262147494 }, { "content": "//! # Hot-reloading\n\n//!\n\n//! Different asset kinds have different interactions with hot-reloading:\n\n//! - `Asset`s are reloaded when the file they were loaded from is edited.\n\n//! - `Compound`s are reloaded when any asset they depend on to build themselves\n\n//! is reloaded.\n\n//! - Directories are never reloaded (note that individual assets in a directory\n\n//! are still reloaded).\n\n//!\n\n//! Additionally, one can explicitly disable hot-reloading for a type.\n\n\n\n#[cfg(feature = \"ab_glyph\")]\n\nmod fonts;\n\n#[cfg(feature = \"gltf\")]\n\nmod gltf;\n\n\n\n#[cfg(test)]\n\nmod tests;\n\n\n\npub use crate::dirs::DirLoadable;\n", "file_path": "src/asset.rs", "rank": 95, "score": 36441.458936952746 }, { "content": "//! Values loadable from a cache.\n\n//!\n\n//! # Asset kinds\n\n//!\n\n//! In `assets_manager`, assets are stored in an [`AssetCache`], and are usually\n\n//! loaded from a [`Source`], a file system abstraction. Most of the I/O with\n\n//! the source is handled by `assets_manager`, so you can focus on the rest.\n\n//!\n\n//! This crate defines several kinds of assets, that have different use cases:\n\n//! - The most common, [`Asset`]s, that are loaded from a single file. An\n\n//! `Asset` gives a way to get a Rust value from raw bytes.\n\n//! - [`Compound`] are created by loading other assets and composing them.\n\n//! - [`Storable`] is the widest category: everything `'static` type can fit in\n\n//! it. Values of types that implement `Storable` can be inserted in a cache,\n\n//! but provide no way to construct them.\n\n//!\n\n//! Additionnally, [`DirLoadable`] assets can be loaded by directory, eventually\n\n//! recursively. All `Asset` types implement this trait out of the box, but it\n\n//! can be extended to work with `Compound`s.\n\n//!\n", "file_path": "src/asset.rs", "rank": 96, "score": 36440.83046424614 }, { "content": "/// extension. If you set a value for `EXTENSIONS` too, this field is ignored.\n\n///\n\n/// If neither `EXTENSION` nor `EXTENSIONS` is set, the default is no extension.\n\n///\n\n/// If you use hot-reloading, the asset will be reloaded each time one of the\n\n/// file with the given extension is touched.\n\n///\n\n/// # Example\n\n///\n\n/// Suppose you make a physics simulation, and you store positions and speeds\n\n/// in a Bincode-encoded file, with extension \".data\".\n\n///\n\n/// ```no_run\n\n/// # cfg_if::cfg_if! { if #[cfg(feature = \"bincode\")] {\n\n/// use assets_manager::{Asset, loader};\n\n/// use serde::Deserialize;\n\n///\n\n/// #[derive(Deserialize)]\n\n/// struct Vector {\n\n/// x: f32,\n", "file_path": "src/asset.rs", "rank": 97, "score": 36440.37758898466 }, { "content": " T: for<'de> serde::Deserialize<'de> + Send + Sync + 'static,\n\n {\n\n const EXTENSIONS: &'static [&'static str] = &[$( $ext ),*];\n\n type Loader = loader::LoadFrom<T, $loader>;\n\n }\n\n\n\n #[cfg(feature = $feature)]\n\n impl<T> AsRef<T> for $name<T> {\n\n #[inline]\n\n fn as_ref(&self) -> &T {\n\n &self.0\n\n }\n\n }\n\n )*\n\n }\n\n}\n\n\n\nserde_assets! {\n\n /// Loads a value from a RON file.\n\n #[cfg(feature = \"json\")]\n", "file_path": "src/asset.rs", "rank": 98, "score": 36440.25420939025 }, { "content": " /// Creates a [`Decoder`] that can be send to `rodio` to play\n\n /// sounds.\n\n #[inline]\n\n pub fn decoder(self) -> Decoder<io::Cursor<SharedBytes>> {\n\n $decoder(io::Cursor::new(self.0)).unwrap()\n\n }\n\n\n\n #[inline]\n\n /// Returns a bytes slice of the sound content.\n\n pub fn as_bytes(&self) -> &[u8] {\n\n &self.0\n\n }\n\n\n\n /// Convert the sound back to raw bytes.\n\n #[inline]\n\n pub fn into_bytes(self) -> SharedBytes {\n\n self.0\n\n }\n\n }\n\n\n", "file_path": "src/asset.rs", "rank": 99, "score": 36440.07993200729 } ]
Rust
src/geom.rs
H2CO3/quirs
44b75e71d5578dd605bd12d88d45eb2763d3e071
use std::fmt; use util::int_to_usize; use info::Info; use quirc_sys::{ quirc_point, quirc_code, quirc_data }; use quirc_sys::{ quirc_decode, quirc_decode_error_t }; use error::{ Error, Result }; use self::quirc_decode_error_t::QUIRC_SUCCESS; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct Vec2D { pub x: usize, pub y: usize, } impl Vec2D { pub fn from_raw(p: quirc_point) -> Result<Self> { let (x, y) = (int_to_usize(p.x)?, int_to_usize(p.y)?); Ok(Vec2D { x, y }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Image<'a> { data: &'a [u8], size: Vec2D, } impl<'a> Image<'a> { pub fn new(data: &'a [u8], size: Vec2D) -> Result<Self> { if data.len() == size.x * size.y { Ok(Image { data, size }) } else { Err(Error::SizeMismatch) } } pub fn data(&self) -> &[u8] { self.data } pub fn width(&self) -> usize { self.size.x } pub fn height(&self) -> usize { self.size.y } } #[derive(Clone, Copy)] pub struct QrCode(quirc_code); impl QrCode { #[doc(hidden)] pub fn from_raw(raw: quirc_code) -> Result<Self> { let _ = int_to_usize(raw.size)?; for i in 0..4 { let _ = Vec2D::from_raw(raw.corners[i])?; } Ok(QrCode(raw)) } fn corner_at(&self, i: usize) -> Vec2D { Vec2D::from_raw(self.0.corners[i]).expect("invalid corner coordinates") } pub fn top_left_corner(&self) -> Vec2D { self.corner_at(0) } pub fn top_right_corner(&self) -> Vec2D { self.corner_at(1) } pub fn bottom_right_corner(&self) -> Vec2D { self.corner_at(2) } pub fn bottom_left_corner(&self) -> Vec2D { self.corner_at(3) } pub fn size(&self) -> usize { int_to_usize(self.0.size).expect("code size under- or overflows usize") } pub fn bitmap(&self) -> &[u8] { let size = self.size(); let num_bits = size * size; let num_bytes = (num_bits + 7) / 8; &self.0.cell_bitmap[..num_bytes] } pub fn get(&self, coord: Vec2D) -> Option<bool> { let size = self.size(); let Vec2D { x, y } = coord; if x < size && y < size { let i = y * size + x; let bit = self.0.cell_bitmap[i / 8] >> (i % 8) & 1; Some(bit != 0) } else { None } } pub fn bit_at(&self, coord: Vec2D) -> bool { self.get(coord).unwrap_or_else( || panic!("{:?} out of bounds for bitmap of size {}", coord, self.size()) ) } pub fn decode(&self) -> Result<Info> { let mut raw = quirc_data::default(); let error_code = unsafe { quirc_decode(&self.0, &mut raw) }; if error_code == QUIRC_SUCCESS { Ok(Info::from_raw(raw)) } else { Err(error_code.into()) } } } impl fmt::Debug for QrCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("QrCode") .field("top_left_corner", &self.top_left_corner()) .field("top_right_corner", &self.top_right_corner()) .field("bottom_right_corner", &self.bottom_right_corner()) .field("bottom_left_corner", &self.bottom_left_corner()) .field("size", &self.size()) .field("bitmap", &self.bitmap()) .finish() } }
use std::fmt; use util::int_to_usize; use info::Info; use quirc_sys::{ quirc_point, quirc_code, quirc_data }; use quirc_sys::{ quirc_decode, quirc_decode_error_t }; use error::{ Error, Result }; use self::quirc_decode_error_t::QUIRC_SUCCESS; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] pub struct Vec2D { pub x: usize, pub y: usize, } impl Vec2D { pub fn from_raw(p: quirc_point) -> Result<Self> { let (x, y) = (int_to_usize(p.x)?, int_to_usize(p.y)?); Ok(Vec2D { x, y }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Image<'a> {
a } pub fn width(&self) -> usize { self.size.x } pub fn height(&self) -> usize { self.size.y } } #[derive(Clone, Copy)] pub struct QrCode(quirc_code); impl QrCode { #[doc(hidden)] pub fn from_raw(raw: quirc_code) -> Result<Self> { let _ = int_to_usize(raw.size)?; for i in 0..4 { let _ = Vec2D::from_raw(raw.corners[i])?; } Ok(QrCode(raw)) } fn corner_at(&self, i: usize) -> Vec2D { Vec2D::from_raw(self.0.corners[i]).expect("invalid corner coordinates") } pub fn top_left_corner(&self) -> Vec2D { self.corner_at(0) } pub fn top_right_corner(&self) -> Vec2D { self.corner_at(1) } pub fn bottom_right_corner(&self) -> Vec2D { self.corner_at(2) } pub fn bottom_left_corner(&self) -> Vec2D { self.corner_at(3) } pub fn size(&self) -> usize { int_to_usize(self.0.size).expect("code size under- or overflows usize") } pub fn bitmap(&self) -> &[u8] { let size = self.size(); let num_bits = size * size; let num_bytes = (num_bits + 7) / 8; &self.0.cell_bitmap[..num_bytes] } pub fn get(&self, coord: Vec2D) -> Option<bool> { let size = self.size(); let Vec2D { x, y } = coord; if x < size && y < size { let i = y * size + x; let bit = self.0.cell_bitmap[i / 8] >> (i % 8) & 1; Some(bit != 0) } else { None } } pub fn bit_at(&self, coord: Vec2D) -> bool { self.get(coord).unwrap_or_else( || panic!("{:?} out of bounds for bitmap of size {}", coord, self.size()) ) } pub fn decode(&self) -> Result<Info> { let mut raw = quirc_data::default(); let error_code = unsafe { quirc_decode(&self.0, &mut raw) }; if error_code == QUIRC_SUCCESS { Ok(Info::from_raw(raw)) } else { Err(error_code.into()) } } } impl fmt::Debug for QrCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("QrCode") .field("top_left_corner", &self.top_left_corner()) .field("top_right_corner", &self.top_right_corner()) .field("bottom_right_corner", &self.bottom_right_corner()) .field("bottom_left_corner", &self.bottom_left_corner()) .field("size", &self.size()) .field("bitmap", &self.bitmap()) .finish() } }
data: &'a [u8], size: Vec2D, } impl<'a> Image<'a> { pub fn new(data: &'a [u8], size: Vec2D) -> Result<Self> { if data.len() == size.x * size.y { Ok(Image { data, size }) } else { Err(Error::SizeMismatch) } } pub fn data(&self) -> &[u8] { self.dat
random
[ { "content": "#[cfg_attr(feature = \"cargo-clippy\", allow(if_same_then_else, cast_possible_truncation, cast_possible_wrap))]\n\npub fn usize_to_int(n: usize) -> Result<c_int> {\n\n if size_of::<usize>() < size_of::<c_int>() {\n\n Ok(n as c_int)\n\n } else if n <= INT_MAX as usize {\n\n Ok(n as c_int)\n\n } else {\n\n Err(Error::IntOverflow)\n\n }\n\n}\n\n\n\n/// Attempts to convert an `int` to a `usize` without under- or overflow.\n", "file_path": "src/util.rs", "rank": 0, "score": 84221.09817921257 }, { "content": "#[cfg_attr(feature = \"cargo-clippy\", allow(if_same_then_else, cast_possible_truncation, cast_possible_wrap))]\n\npub fn int_to_usize(n: c_int) -> Result<usize> {\n\n if n < 0 {\n\n Err(Error::IntOverflow)\n\n } else if size_of::<c_int>() <= size_of::<usize>() {\n\n Ok(n as usize)\n\n } else if n <= usize::MAX as c_int {\n\n Ok(n as usize)\n\n } else {\n\n Err(Error::IntOverflow)\n\n }\n\n}\n", "file_path": "src/util.rs", "rank": 1, "score": 84221.09817921257 }, { "content": "fn main() {\n\n\n\n Command::new(\"make\")\n\n .args(&[\"libquirc.a\", \"-C\", \"quirc/\"])\n\n .status()\n\n .expect(\"couldn't build quirc C library\");\n\n\n\n let out_dir = env::var(\"OUT_DIR\")\n\n .expect(\"missing OUT_DIR env var\");\n\n\n\n fs::copy(\"quirc/libquirc.a\", out_dir.clone() + \"/libquirc.a\")\n\n .expect(\"couldn't copy libquirc.a to OUT_DIR\");\n\n\n\n Command::new(\"make\")\n\n .args(&[\"clean\", \"-C\", \"quirc/\"])\n\n .status()\n\n .expect(\"couldn't make clean\");\n\n\n\n println!(\"cargo:rustc-link-lib=static=quirc\");\n\n println!(\"cargo:rustc-link-search=native={}\", out_dir);\n\n}\n", "file_path": "build.rs", "rank": 2, "score": 26482.691633914503 }, { "content": "fn main() {\n\n let filename = args().nth(1).expect(\"please specify a PNG filename\");\n\n let image = lodepng::decode_file(\n\n &filename,\n\n lodepng::ColorType::GREY,\n\n 8,\n\n ).expect(\n\n \"error decoding PNG file\"\n\n );\n\n let bitmap = match image {\n\n lodepng::Image::Grey(buf) => buf,\n\n _ => panic!(\"PNG couldn't be decoded as 8-bit grayscale\"),\n\n };\n\n let bytes: Vec<u8> = bitmap.buffer.into_iter().map(|px| px.0).collect();\n\n\n\n let mut decoder = Decoder::new().expect(\"can't create Qui-RS decoder\");\n\n let image = Image::new(\n\n &bytes,\n\n Vec2D { x: bitmap.width, y: bitmap.height }\n\n ).expect(\n", "file_path": "examples/basic.rs", "rank": 3, "score": 25111.235131248188 }, { "content": "impl From<quirc_decode_error_t> for Error {\n\n fn from(error: quirc_decode_error_t) -> Self {\n\n Error::DecodingFailed(error.into())\n\n }\n\n}\n\n\n\n/// A decoding error.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum DecodingErrorKind {\n\n /// An unknown error happened.\n\n Unknown,\n\n /// The version was invalid.\n\n InvalidGridSize,\n\n /// The version was invalid.\n\n InvalidVersion,\n\n /// The format failed ECC check.\n\n FormatEcc,\n\n /// The data failed ECC check.\n\n DataEcc,\n\n /// The data type was not recognized.\n", "file_path": "src/error.rs", "rank": 4, "score": 21754.83096345183 }, { "content": "//! Errors that can happen during QR code detection and decoding.\n\n\n\nuse std::fmt;\n\nuse std::error;\n\nuse std::result;\n\nuse quirc_sys::quirc_decode_error_t;\n\n\n\n/// An error that could happen while using the `quirc` library.\n\n#[derive(Debug, Clone, Copy)]\n\npub enum Error {\n\n /// Memory could not be allocated.\n\n AllocFailed,\n\n /// The length of the data buffer doesn't match the dimensions of the image.\n\n SizeMismatch,\n\n /// The size specified as a Rust `usize` can't be expressed in a C `int`\n\n /// or vice versa.\n\n IntOverflow,\n\n /// A decoding error occurred.\n\n DecodingFailed(DecodingErrorKind),\n\n}\n", "file_path": "src/error.rs", "rank": 5, "score": 21754.466270475135 }, { "content": "\n\nimpl fmt::Display for Error {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n use std::error::Error;\n\n\n\n self.description().fmt(f)\n\n }\n\n}\n\n\n\nimpl error::Error for Error {\n\n fn description(&self) -> &str {\n\n match *self {\n\n Error::AllocFailed => \"memory allocation failed\",\n\n Error::SizeMismatch => \"buffer size doesn't match image dimensions\",\n\n Error::IntOverflow => \"usize <-> int conversion would overflow\",\n\n Error::DecodingFailed(reason) => reason.to_str(),\n\n }\n\n }\n\n}\n\n\n", "file_path": "src/error.rs", "rank": 6, "score": 21752.207833983837 }, { "content": " }\n\n}\n\n\n\nimpl fmt::Display for DecodingErrorKind {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.write_str(self.to_str())\n\n }\n\n}\n\n\n\n/// A `Result` which may hold a Qui-RS `Error`.\n\npub type Result<T> = result::Result<T, Error>;\n", "file_path": "src/error.rs", "rank": 7, "score": 21751.595853719005 }, { "content": " DataUnderflow => \"decoding failed because the data payload was too short\",\n\n }\n\n }\n\n}\n\n\n\nimpl From<quirc_decode_error_t> for DecodingErrorKind {\n\n fn from(code: quirc_decode_error_t) -> Self {\n\n use self::quirc_decode_error_t::*;\n\n use self::DecodingErrorKind::*;\n\n\n\n match code {\n\n QUIRC_ERROR_INVALID_GRID_SIZE => InvalidGridSize,\n\n\t QUIRC_ERROR_INVALID_VERSION => InvalidVersion,\n\n\t QUIRC_ERROR_FORMAT_ECC => FormatEcc,\n\n\t QUIRC_ERROR_DATA_ECC => DataEcc,\n\n\t QUIRC_ERROR_UNKNOWN_DATA_TYPE => UnknownDataType,\n\n\t QUIRC_ERROR_DATA_OVERFLOW => DataOverflow,\n\n\t QUIRC_ERROR_DATA_UNDERFLOW => DataUnderflow,\n\n _ => Unknown,\n\n }\n", "file_path": "src/error.rs", "rank": 8, "score": 21748.56569049862 }, { "content": " UnknownDataType,\n\n /// The data payload was too long.\n\n DataOverflow,\n\n /// The data payload was too short.\n\n DataUnderflow,\n\n}\n\n\n\nimpl DecodingErrorKind {\n\n /// Returns a human-readable error message.\n\n pub fn to_str(self) -> &'static str {\n\n use self::DecodingErrorKind::*;\n\n\n\n match self {\n\n Unknown => \"decoding failed because an unknown error happened\",\n\n InvalidGridSize => \"decoding failed beacuse the grid size was invalid\",\n\n InvalidVersion => \"decoding failed because the version was invalid\",\n\n FormatEcc => \"decoding failed because the format failed ECC check\",\n\n DataEcc => \"decoding failed because the data failed ECC check\",\n\n UnknownDataType => \"decoding failed because the data type was not recognized\",\n\n DataOverflow => \"decoding failed because the data payload was too long\",\n", "file_path": "src/error.rs", "rank": 9, "score": 21748.168072358163 }, { "content": "#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum QuircDataType {\n\n /// Numeric (digits only).\n\n QUIRC_DATA_TYPE_NUMERIC = 1,\n\n /// Alphanumeric.\n\n QUIRC_DATA_TYPE_ALPHA = 2,\n\n /// Bytes.\n\n QUIRC_DATA_TYPE_BYTE = 4,\n\n /// Kanji characters.\n\n QUIRC_DATA_TYPE_KANJI = 8,\n\n}\n\n\n\n/// This enum describes the various decoder errors which may occur.\n\n#[repr(C)]\n\n#[allow(non_camel_case_types)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum quirc_decode_error_t {\n\n /// No error.\n", "file_path": "src/quirc_sys.rs", "rank": 12, "score": 12.323953601847117 }, { "content": "//! High-level representation of the information contained in a QR code.\n\n\n\nuse std::str::{ self, Utf8Error };\n\nuse std::cmp::{ min, max };\n\nuse std::hash::{ Hash, Hasher };\n\nuse quirc_sys::{ quirc_data, QUIRC_MAX_PAYLOAD };\n\nuse quirc_sys::QuircEccLevel::*;\n\nuse quirc_sys::QuircDataType::*;\n\n\n\n/// High-level representation of the information contained in a QR code.\n\n#[derive(Debug, Clone, Copy)]\n\npub struct Info(quirc_data);\n\n\n\nimpl Info {\n\n /// Attempts to extract high-level information from the raw FFI `quirc_data`.\n\n #[doc(hidden)]\n\n pub fn from_raw(raw: quirc_data) -> Self {\n\n Info(raw)\n\n }\n\n\n", "file_path": "src/info.rs", "rank": 13, "score": 10.960304934168672 }, { "content": "//! Raw FFI bindings for the `quirc` C API.\n\n\n\nuse std::fmt;\n\nuse libc::{ c_int, c_char };\n\n\n\n/// Opaque type manipulated by the `quirc` C API.\n\n#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Debug)]\n\npub struct quirc {\n\n /// Just a zero-sized, `#[repr(C)]`-compatible private field serving as a\n\n /// guard against instantiating the opaque type from the outside world.\n\n _dummy: [u8; 0],\n\n}\n\n\n\n/// This structure describes a location in the input image buffer.\n\n#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]\n\npub struct quirc_point {\n", "file_path": "src/quirc_sys.rs", "rank": 14, "score": 10.88884177129323 }, { "content": "}\n\n\n\nimpl Hash for Info {\n\n fn hash<H: Hasher>(&self, state: &mut H) {\n\n self.version().hash(state);\n\n self.mask_id().hash(state);\n\n self.eci().hash(state);\n\n self.ecc_level().hash(state);\n\n self.data_type().hash(state);\n\n self.payload().hash(state);\n\n }\n\n}\n\n\n\n/// The ECC level used for the QR code.\n\n///\n\n/// NB: deriving `PartialOrd` and `Ord` produces the correct ordering even\n\n/// though the numerical values of the variants aren't in monotonic order.\n\n/// This is because `derive` takes into account the order in which the\n\n/// variants have been declared, and not their raw integer value.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n", "file_path": "src/info.rs", "rank": 15, "score": 10.28685877204113 }, { "content": "\t/// where i = (y * size) + x.\n\n\tpub size: c_int,\n\n /// The actual bitmap data.\n\n\tpub cell_bitmap: [u8; QUIRC_MAX_BITMAP],\n\n}\n\n\n\nimpl Default for quirc_code {\n\n fn default() -> Self {\n\n quirc_code {\n\n corners: Default::default(),\n\n size: 0,\n\n cell_bitmap: [0; QUIRC_MAX_BITMAP],\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Debug for quirc_code {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"quirc_code\")\n\n .field(\"corners\", &self.corners)\n", "file_path": "src/quirc_sys.rs", "rank": 17, "score": 9.353482163920278 }, { "content": "//! The actual QR code decoder.\n\n\n\nuse std::ptr;\n\nuse std::usize;\n\nuse std::ffi::CStr;\n\nuse libc::c_int;\n\nuse geom::{ Image, QrCode };\n\nuse quirc_sys::{ quirc, quirc_version, quirc_new, quirc_destroy };\n\nuse quirc_sys::{ quirc_resize, quirc_begin, quirc_end };\n\nuse quirc_sys::{ quirc_code, quirc_count, quirc_extract };\n\nuse util::{ usize_to_int, int_to_usize };\n\nuse error::{ Error, Result };\n\n\n\n/// A QR code decoder.\n\n#[derive(Debug)]\n\npub struct Decoder {\n\n /// Opaque handle to the `quirc` decoder object.\n\n inner: *mut quirc,\n\n}\n\n\n", "file_path": "src/decoder.rs", "rank": 18, "score": 9.213256091241309 }, { "content": "//! Various utility functions and types.\n\n\n\nuse std::usize;\n\nuse std::mem::size_of;\n\nuse libc::{ c_int, INT_MAX };\n\nuse error::{ Error, Result };\n\n\n\n/// Attempts to convert a `usize` to an `int` without overflow.\n\n#[cfg_attr(feature = \"cargo-clippy\", allow(if_same_then_else, cast_possible_truncation, cast_possible_wrap))]\n", "file_path": "src/util.rs", "rank": 19, "score": 9.000676896089056 }, { "content": "pub enum EccLevel {\n\n /// Low error correction: ~7% loss recoverable.\n\n L = QUIRC_ECC_LEVEL_L as _,\n\n /// Medium error correction: ~15% loss recoverable.\n\n M = QUIRC_ECC_LEVEL_M as _,\n\n /// Quartile error correction: ~25% loss recoverable.\n\n Q = QUIRC_ECC_LEVEL_Q as _,\n\n /// High error correction: ~30% loss recoverable.\n\n H = QUIRC_ECC_LEVEL_H as _,\n\n}\n\n\n\n/// The highest-valued (most complex) data type found in the QR code.\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n\npub enum DataType {\n\n /// Numeric (digits only).\n\n Numeric = QUIRC_DATA_TYPE_NUMERIC as _,\n\n /// Alphanumeric.\n\n Alphanumeric = QUIRC_DATA_TYPE_ALPHA as _,\n\n /// Bytes.\n\n Byte = QUIRC_DATA_TYPE_BYTE as _,\n\n /// Kanji characters.\n\n Kanji = QUIRC_DATA_TYPE_KANJI as _,\n\n}\n", "file_path": "src/info.rs", "rank": 20, "score": 8.870542501138589 }, { "content": " // the result is still bounded by `[0, QUIRC_MAX_PAYLOAD]`.\n\n let len = max(0, min(self.0.payload_len as _, QUIRC_MAX_PAYLOAD));\n\n &self.0.payload[..len]\n\n }\n\n\n\n /// Returns the payload as UTF-8 text if possible.\n\n pub fn as_str(&self) -> Result<&str, Utf8Error> {\n\n str::from_utf8(self.payload())\n\n }\n\n}\n\n\n\nimpl PartialEq<Info> for Info {\n\n fn eq(&self, other: &Info) -> bool {\n\n self.version() == other.version() &&\n\n self.mask_id() == other.mask_id() &&\n\n self.eci() == other.eci() &&\n\n self.ecc_level() == other.ecc_level() &&\n\n self.data_type() == other.data_type() &&\n\n self.payload() == other.payload()\n\n }\n", "file_path": "src/info.rs", "rank": 21, "score": 8.187753724943558 }, { "content": " .finish()\n\n }\n\n}\n\n\n\n/// QR-code ECC types.\n\n#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n\npub enum QuircEccLevel {\n\n /// Medium ECC: correct at most 15% damage.\n\n QUIRC_ECC_LEVEL_M = 0,\n\n /// Low ECC: correct at most 7% damage.\n\n QUIRC_ECC_LEVEL_L = 1,\n\n /// High ECC: correct at most 30% damage.\n\n QUIRC_ECC_LEVEL_H = 2,\n\n /// Quartile ECC: correct at most 25% damage.\n\n QUIRC_ECC_LEVEL_Q = 3,\n\n}\n\n\n\n/// QR-code data types.\n", "file_path": "src/quirc_sys.rs", "rank": 22, "score": 7.699605835162875 }, { "content": " /// X coordinate (column) of the point.\n\n\tpub x: c_int,\n\n /// Y coordinate (row) of the point.\n\n\tpub y: c_int,\n\n}\n\n\n\n/// This structure is used to return information about detected QR codes\n\n/// in the input image.\n\n#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\npub struct quirc_code {\n\n\t/// The four corners of the QR-code, from top left, clockwise */\n\n\tpub corners: [quirc_point; 4],\n\n\t/// The number of cells across in the QR-code. The cell bitmap\n\n\t/// is a bitmask giving the actual values of cells. If the cell\n\n\t/// at (x, y) is black, then the following bit is set:\n\n ///\n\n\t/// cell_bitmap[i >> 3] & (1 << (i & 7))\n\n ///\n", "file_path": "src/quirc_sys.rs", "rank": 23, "score": 7.680743968117264 }, { "content": " CStr::from_ptr(version_ptr).to_str().unwrap_or_default()\n\n }\n\n }\n\n }\n\n\n\n /// Feeds image data to the decoder and returns the QR codes.\n\n pub fn decode_image(&mut self, image: &Image) -> Result<Iter> {\n\n let width = usize_to_int(image.width())?;\n\n let height = usize_to_int(image.height())?;\n\n let image_data = image.data();\n\n\n\n unsafe {\n\n if quirc_resize(self.inner, width, height) != 0 {\n\n return Err(Error::AllocFailed);\n\n }\n\n\n\n let buf_ptr = quirc_begin(\n\n self.inner,\n\n ptr::null_mut(),\n\n ptr::null_mut(),\n", "file_path": "src/decoder.rs", "rank": 24, "score": 7.5905953054087805 }, { "content": " invalid_upcast_comparisons,\n\n cast_precision_loss, cast_lossless,\n\n cast_possible_wrap, cast_possible_truncation,\n\n mutex_integer, mut_mut, items_after_statements,\n\n print_stdout, mem_forget, maybe_infinite_iter))]\n\n\n\nextern crate libc;\n\n\n\nmod quirc_sys;\n\nmod util;\n\n\n\npub mod decoder;\n\npub mod info;\n\npub mod geom;\n\npub mod error;\n\n\n\npub use decoder::Decoder;\n\npub use error::Error;\n\npub use geom::{ Image, Vec2D, QrCode };\n\npub use info::Info;\n", "file_path": "src/lib.rs", "rank": 25, "score": 6.9827801982429785 }, { "content": "impl Decoder {\n\n /// Attempts to create a `Decoder`.\n\n pub fn new() -> Result<Self> {\n\n let inner = unsafe { quirc_new() };\n\n\n\n if inner.is_null() {\n\n Err(Error::AllocFailed)\n\n } else {\n\n Ok(Decoder { inner })\n\n }\n\n }\n\n\n\n /// Return the version number of the `quirc` library, if possible.\n\n pub fn version() -> &'static str {\n\n let version_ptr = unsafe { quirc_version() };\n\n\n\n if version_ptr.is_null() {\n\n \"\"\n\n } else {\n\n unsafe {\n", "file_path": "src/decoder.rs", "rank": 26, "score": 6.662845791442221 }, { "content": " .field(\"size\", &self.size)\n\n .field(\"cell_bitmap\", &self.cell_bitmap.as_ref())\n\n .finish()\n\n }\n\n}\n\n\n\n/// This structure holds the decoded QR-code data.\n\n#[allow(non_camel_case_types)]\n\n#[repr(C)]\n\n#[derive(Clone, Copy)]\n\npub struct quirc_data {\n\n\t/// Various parameters of the QR-code. These can mostly be\n\n\t/// ignored if you only care about the data.\n\n /// Version number.\n\n\tpub version: c_int,\n\n /// Error-correction level.\n\n\tpub ecc_level: c_int,\n\n /// Mask.\n\n\tpub mask: c_int,\n\n\t/// This field is the highest-valued data type found in the QR code.\n", "file_path": "src/quirc_sys.rs", "rank": 27, "score": 6.202391992402234 }, { "content": "//! Wrapper around the `quirc` QR code decoder library.\n\n\n\n#![crate_name=\"quirs\"]\n\n#![doc(html_root_url = \"https://docs.rs/quirs/0.1.1\")]\n\n#![deny(missing_debug_implementations, missing_copy_implementations,\n\n trivial_casts, trivial_numeric_casts,\n\n unstable_features,\n\n unused_import_braces, unused_qualifications, missing_docs)]\n\n#![cfg_attr(feature = \"cargo-clippy\",\n\n allow(single_match, match_same_arms, match_ref_pats,\n\n clone_on_ref_ptr, needless_pass_by_value))]\n\n#![cfg_attr(feature = \"cargo-clippy\",\n\n deny(wrong_pub_self_convention, used_underscore_binding,\n\n stutter, similar_names, pub_enum_variant_names,\n\n missing_docs_in_private_items,\n\n non_ascii_literal, unicode_not_nfc,\n\n result_unwrap_used, option_unwrap_used,\n\n option_map_unwrap_or_else, option_map_unwrap_or, filter_map,\n\n shadow_unrelated, shadow_reuse, shadow_same,\n\n int_plus_one, string_add_assign, if_not_else,\n", "file_path": "src/lib.rs", "rank": 28, "score": 6.084704180960867 }, { "content": "\tpub data_type: c_int,\n\n\t/// Data payload. For the Kanji datatype, payload is encoded as\n\n\t/// Shift-JIS. For all other datatypes, payload is ASCII text.\n\n\tpub payload: [u8; QUIRC_MAX_PAYLOAD],\n\n /// Valid (initialized) portion of `payload`.\n\n\tpub payload_len: c_int,\n\n\t/// ECI assignment number.\n\n\tpub eci: u32,\n\n}\n\n\n\nimpl Default for quirc_data {\n\n /// I don't particularly care that these default values don't make much sense.\n\n /// They won't be used outside the library anyway since this module is private,\n\n /// and the values are checked before conversion to a public type, so no UB\n\n /// can occur even if e.g. the value 0 is invalid for a certain `enum`.\n\n /// But I want to ensure I have initialized memory when working with a C library,\n\n /// and providing zeroed memory is standard practice for that.\n\n fn default() -> Self {\n\n quirc_data {\n\n version: 0,\n", "file_path": "src/quirc_sys.rs", "rank": 30, "score": 5.623351219947935 }, { "content": "\tQUIRC_SUCCESS = 0,\n\n /// Invalid grid size.\n\n\tQUIRC_ERROR_INVALID_GRID_SIZE,\n\n /// Invalid version.\n\n\tQUIRC_ERROR_INVALID_VERSION,\n\n /// Invalid ECC format.\n\n\tQUIRC_ERROR_FORMAT_ECC,\n\n /// ECC data error.\n\n\tQUIRC_ERROR_DATA_ECC,\n\n /// Invalid data type.\n\n\tQUIRC_ERROR_UNKNOWN_DATA_TYPE,\n\n /// Data overflow.\n\n\tQUIRC_ERROR_DATA_OVERFLOW,\n\n /// Data underflow.\n\n\tQUIRC_ERROR_DATA_UNDERFLOW,\n\n}\n\n\n\n/// Limits on the maximum size of QR-codes and their content.\n\npub const QUIRC_MAX_BITMAP: usize = 3917;\n\n/// Limits on the maximum size of QR-codes and their content.\n", "file_path": "src/quirc_sys.rs", "rank": 32, "score": 5.232721676082964 }, { "content": " ecc_level: 0,\n\n mask: 0,\n\n data_type: 0,\n\n payload: [0; QUIRC_MAX_PAYLOAD],\n\n payload_len: 0,\n\n eci: 0,\n\n }\n\n }\n\n}\n\n\n\nimpl fmt::Debug for quirc_data {\n\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n\n f.debug_struct(\"quirc_data\")\n\n .field(\"version\", &self.version)\n\n .field(\"ecc_level\", &self.ecc_level)\n\n .field(\"mask\", &self.mask)\n\n .field(\"data_type\", &self.data_type)\n\n .field(\"payload\", &self.payload.as_ref())\n\n .field(\"payload_len\", &self.payload_len)\n\n .field(\"eci\", &self.eci)\n", "file_path": "src/quirc_sys.rs", "rank": 34, "score": 4.491980137332783 }, { "content": " /// These functions are used to process images for QR-code recognition.\n\n /// `quirc_begin()` must first be called to obtain access to a buffer into\n\n /// which the input image should be placed. Optionally, the current\n\n /// width and height may be returned.\n\n pub fn quirc_begin(q: *mut quirc, q: *mut c_int, h: *mut c_int) -> *mut u8;\n\n\n\n /// After filling the buffer, `quirc_end()` should be called to process\n\n /// the image for QR-code recognition. The locations and content of each\n\n /// code may be obtained using accessor functions described below.\n\n pub fn quirc_end(q: *mut quirc);\n\n\n\n /// Return the number of QR-codes identified in the last processed image.\n\n pub fn quirc_count(q: *const quirc) -> c_int;\n\n\n\n /// Extract the QR-code specified by the given index.\n\n pub fn quirc_extract(q: *const quirc, index: c_int, code: *mut quirc_code);\n\n\n\n /// Decode a QR-code, returning the payload data.\n\n pub fn quirc_decode(code: *const quirc_code,\n\n data: *mut quirc_data) -> quirc_decode_error_t;\n\n}\n", "file_path": "src/quirc_sys.rs", "rank": 36, "score": 4.4255518178400175 }, { "content": " // returns without writing anything to the `quirc_code` out argument\n\n // if the index is OOB. Although we have a bounds check, I have\n\n // trust issues with underlying C libraries, so this remains a 0.\n\n let mut raw = quirc_code::default();\n\n\n\n unsafe {\n\n quirc_extract(self.decoder.inner, index, &mut raw);\n\n }\n\n\n\n self.index += 1;\n\n\n\n Some(QrCode::from_raw(raw))\n\n } else {\n\n None\n\n }\n\n }\n\n\n\n fn size_hint(&self) -> (usize, Option<usize>) {\n\n let (count, index) = self.count_and_index();\n\n\n\n int_to_usize(count - index)\n\n .map(|n| (n, Some(n)))\n\n .unwrap_or_default() // we don't know if it under- or overflowed\n\n }\n\n}\n", "file_path": "src/decoder.rs", "rank": 37, "score": 4.05060556963988 }, { "content": " );\n\n assert!(!buf_ptr.is_null(), \"quirc_begin() returned null pointer\");\n\n\n\n ptr::copy_nonoverlapping(\n\n image_data.as_ptr(),\n\n buf_ptr,\n\n image_data.len(),\n\n );\n\n\n\n quirc_end(self.inner);\n\n }\n\n\n\n Ok(Iter {\n\n decoder: self,\n\n index: 0,\n\n })\n\n }\n\n}\n\n\n\nimpl Drop for Decoder {\n", "file_path": "src/decoder.rs", "rank": 39, "score": 3.690470296835062 }, { "content": "pub const QUIRC_MAX_PAYLOAD: usize = 8896;\n\n\n\nextern {\n\n /// Obtain the library version string.\n\n pub fn quirc_version() -> *const c_char;\n\n\n\n /// Construct a new QR-code recognizer. This function will return NULL\n\n /// if sufficient memory could not be allocated.\n\n pub fn quirc_new() -> *mut quirc;\n\n\n\n /// Destroy a QR-code recognizer.\n\n pub fn quirc_destroy(q: *mut quirc);\n\n\n\n /// Resize the QR-code recognizer. The size of an image must be\n\n /// specified before codes can be analyzed.\n\n ///\n\n /// This function returns 0 on success, or -1 if sufficient memory could\n\n /// not be allocated.\n\n pub fn quirc_resize(q: *mut quirc, w: c_int, h: c_int) -> c_int;\n\n\n", "file_path": "src/quirc_sys.rs", "rank": 40, "score": 3.5515524086270824 }, { "content": " let count = unsafe {\n\n quirc_count(self.decoder.inner)\n\n };\n\n let index = self.index;\n\n\n\n assert!(count >= 0, \"quirc_count() was negative\");\n\n assert!(index >= 0, \"current index was negative\");\n\n\n\n (count, index)\n\n }\n\n}\n\n\n\nimpl<'a> Iterator for Iter<'a> {\n\n type Item = Result<QrCode>;\n\n\n\n fn next(&mut self) -> Option<Self::Item> {\n\n let (count, index) = self.count_and_index();\n\n\n\n if index < count {\n\n // This is not `mem::uninitialized` because `quirc_extract()`\n", "file_path": "src/decoder.rs", "rank": 41, "score": 3.2456296474165103 }, { "content": " /// Returns the version number of the code, in the range `1...40`.\n\n #[cfg_attr(feature = \"cargo-clippy\", allow(cast_possible_truncation, cast_possible_wrap))]\n\n pub fn version(&self) -> u8 {\n\n max(1, min(self.0.version, 40)) as _\n\n }\n\n\n\n /// Returns the mask ID of the code, in the range `0...7`.\n\n #[cfg_attr(feature = \"cargo-clippy\", allow(cast_possible_truncation, cast_possible_wrap))]\n\n pub fn mask_id(&self) -> u8 {\n\n max(0, min(self.0.mask, 7)) as _\n\n }\n\n\n\n /// Returns the ECI assignment number, in the range `0...30`.\n\n #[cfg_attr(feature = \"cargo-clippy\", allow(cast_possible_truncation, cast_possible_wrap))]\n\n pub fn eci(&self) -> u8 {\n\n max(0, min(self.0.eci, 30)) as _\n\n }\n\n\n\n /// Returns the error correction level of the code.\n\n pub fn ecc_level(&self) -> EccLevel {\n", "file_path": "src/info.rs", "rank": 42, "score": 3.062460037677424 }, { "content": "use std::fs;\n\nuse std::env;\n\nuse std::process::Command;\n\n\n", "file_path": "build.rs", "rank": 43, "score": 2.9946897053135264 }, { "content": " fn drop(&mut self) {\n\n unsafe {\n\n quirc_destroy(self.inner);\n\n }\n\n }\n\n}\n\n\n\n/// An iterator over QR codes in an image.\n\n#[derive(Debug)]\n\npub struct Iter<'a> {\n\n /// A reference to the decoder where this iterator's contents come from.\n\n decoder: &'a mut Decoder,\n\n /// The index of the next image to process.\n\n index: c_int,\n\n}\n\n\n\nimpl<'a> Iter<'a> {\n\n /// Returns the total count and the current index,\n\n /// ensuring that both are non-negative.\n\n fn count_and_index(&self) -> (c_int, c_int) {\n", "file_path": "src/decoder.rs", "rank": 44, "score": 2.9239619288223717 }, { "content": "extern crate quirs;\n\nextern crate lodepng;\n\n\n\nuse quirs::*;\n\nuse std::env::args;\n\n\n", "file_path": "examples/basic.rs", "rank": 45, "score": 2.7492180996889255 }, { "content": " let ecc = self.0.ecc_level;\n\n\n\n // Casting an `int` with a value that isn't valid for a Rust `enum` is\n\n // Undefined Behavior, so we must perform the conversion in the opposite\n\n // direction. Therefore, we can't use `match`.\n\n if ecc == QUIRC_ECC_LEVEL_L as _ {\n\n EccLevel::L\n\n } else if ecc == QUIRC_ECC_LEVEL_M as _ {\n\n EccLevel::M\n\n } else if ecc == QUIRC_ECC_LEVEL_Q as _ {\n\n EccLevel::Q\n\n } else if ecc == QUIRC_ECC_LEVEL_H as _ {\n\n EccLevel::H\n\n } else {\n\n EccLevel::L // assume only the lowest level of ECC for robustness\n\n }\n\n }\n\n\n\n /// Returns the highest-valued data type found in the code.\n\n pub fn data_type(&self) -> DataType {\n", "file_path": "src/info.rs", "rank": 46, "score": 2.3064780286496758 }, { "content": " // For the rationale behind this implementation,\n\n // see the comment in `ecc_level()` above.\n\n let dtype = self.0.data_type;\n\n\n\n if dtype == QUIRC_DATA_TYPE_NUMERIC as _ {\n\n DataType::Numeric\n\n } else if dtype == QUIRC_DATA_TYPE_ALPHA as _ {\n\n DataType::Alphanumeric\n\n } else if dtype == QUIRC_DATA_TYPE_BYTE as _ {\n\n DataType::Byte\n\n } else if dtype == QUIRC_DATA_TYPE_KANJI as _ {\n\n DataType::Kanji\n\n } else {\n\n DataType::Byte // assume uninterpreted raw bytes if type is unknown\n\n }\n\n }\n\n\n\n /// Returns the raw payload of the QR code.\n\n pub fn payload(&self) -> &[u8] {\n\n // This cast is safe because even if it over- or underflows,\n", "file_path": "src/info.rs", "rank": 48, "score": 1.1062476936591317 } ]