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
contracts/tests/sim/test_storage.rs
alexkeating/moloch
bf11f8e03de63a000706bb1c711cec16410dbe09
use crate::utils::init_moloch; use near_sdk_sim::{call, to_yocto}; use std::convert::TryInto; #[test] fn simulate_storage_deposit_exact() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = bob.account().unwrap().amount; let min_deposit = to_yocto("7"); println!("Here {:?} 23", start_amount); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(false) ), min_deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( start_amount - end_amount >= to_yocto("7"), "Did not take all of the registration" ); } #[test] fn simulate_storage_deposit_transfer_back() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = &bob.account().unwrap().amount; let deposit = 828593677552200000000; println!("Here {:?} 23", start_amount); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( (start_amount - end_amount) < deposit, "Not receieve correct excess amount" ); assert!( (start_amount - end_amount) > 1000000, "Not receieve correct excess amount" ); } #[test] fn simulate_storage_deposit_already_registered() { let (_, moloch, _, _, bob, _) = init_moloch(); let deposit = to_yocto("9"); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(false) ), deposit, near_sdk_sim::DEFAULT_GAS ); let start_amount = &bob.account().unwrap().amount; call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( (start_amount - end_amount) < 800000000000000000000, "Not receieve correct excess amount" ); } #[test] fn simulate_storage_deposit_below_min_amount() { let (_, moloch, _, alice, _, _) = init_moloch(); let deposit = 0; let res = call!( alice, moloch.storage_deposit( Some(alice.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); assert!( format!("{:?}", res.status()) .contains("The attached deposit is less than the minimum storage balance bounds"), "Corrrect error was not raised" ) } #[test] fn simulate_storage_withdraw_and_unregister() { let (_, moloch, _, alice, _, _) = init_moloch(); let deposit = to_yocto("10"); let start_amount = &alice.account().unwrap().amount; call!( alice, moloch.storage_deposit( Some(alice.account_id.to_string().try_into().unwrap()), Some(false) ), deposit, near_sdk_sim::DEFAULT_GAS ); let res = call!( alice, moloch.storage_withdraw(Some(to_yocto("9").into())), 1, near_sdk_sim::DEFAULT_GAS ); let end_amount = &alice.account().unwrap().amount; println!("Resp {:?}", res); println!("Diff {}", (start_amount - end_amount)); println!("yocto {}", to_yocto("1.1")); assert!((start_amount - end_amount) < to_yocto("1.1")); let res = call!( alice, moloch.storage_unregister(Some(true)), 1, near_sdk_sim::DEFAULT_GAS ); let end_amount = &alice.account().unwrap().amount; println!("Resp {:?}", res); println!("Diff {}", (start_amount - end_amount)); println!("yocto {}", 6000000000000000000000u128); assert!((start_amount - end_amount) < 6000000000000000000000); }
use crate::utils::init_moloch; use near_sdk_sim::{call, to_yocto}; use std::convert::TryInto; #[test] fn simulate_storage_deposit_exact() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = bob.account().unwrap().amount; let min_deposit = to_yocto("7"); println!("Here {:?} 23", start_amount); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(false) ), min_deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( start_amount - end_amount >= to_yocto("7"), "Did not take all of the registration" ); } #[test]
#[test] fn simulate_storage_deposit_already_registered() { let (_, moloch, _, _, bob, _) = init_moloch(); let deposit = to_yocto("9"); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(false) ), deposit, near_sdk_sim::DEFAULT_GAS ); let start_amount = &bob.account().unwrap().amount; call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( (start_amount - end_amount) < 800000000000000000000, "Not receieve correct excess amount" ); } #[test] fn simulate_storage_deposit_below_min_amount() { let (_, moloch, _, alice, _, _) = init_moloch(); let deposit = 0; let res = call!( alice, moloch.storage_deposit( Some(alice.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); assert!( format!("{:?}", res.status()) .contains("The attached deposit is less than the minimum storage balance bounds"), "Corrrect error was not raised" ) } #[test] fn simulate_storage_withdraw_and_unregister() { let (_, moloch, _, alice, _, _) = init_moloch(); let deposit = to_yocto("10"); let start_amount = &alice.account().unwrap().amount; call!( alice, moloch.storage_deposit( Some(alice.account_id.to_string().try_into().unwrap()), Some(false) ), deposit, near_sdk_sim::DEFAULT_GAS ); let res = call!( alice, moloch.storage_withdraw(Some(to_yocto("9").into())), 1, near_sdk_sim::DEFAULT_GAS ); let end_amount = &alice.account().unwrap().amount; println!("Resp {:?}", res); println!("Diff {}", (start_amount - end_amount)); println!("yocto {}", to_yocto("1.1")); assert!((start_amount - end_amount) < to_yocto("1.1")); let res = call!( alice, moloch.storage_unregister(Some(true)), 1, near_sdk_sim::DEFAULT_GAS ); let end_amount = &alice.account().unwrap().amount; println!("Resp {:?}", res); println!("Diff {}", (start_amount - end_amount)); println!("yocto {}", 6000000000000000000000u128); assert!((start_amount - end_amount) < 6000000000000000000000); }
fn simulate_storage_deposit_transfer_back() { let (_, moloch, _fdai, _alice, bob, _deposit_amount) = init_moloch(); let start_amount = &bob.account().unwrap().amount; let deposit = 828593677552200000000; println!("Here {:?} 23", start_amount); call!( bob, moloch.storage_deposit( Some(bob.account_id.to_string().try_into().unwrap()), Some(true) ), deposit, near_sdk_sim::DEFAULT_GAS ); let end_amount = bob.account().unwrap().amount; assert!( (start_amount - end_amount) < deposit, "Not receieve correct excess amount" ); assert!( (start_amount - end_amount) > 1000000, "Not receieve correct excess amount" ); }
function_block-full_function
[ { "content": "#[test]\n\nfn simulate_submit_proposal() {\n\n let (_root, moloch, fdai, alice, bob, deposit_amount) = init_moloch();\n\n register_user_moloch(&alice, &moloch);\n\n register_user_moloch(&bob, &moloch);\n\n call!(\n\n bob,\n\n fdai.ft_transfer_call(\n\n moloch.u...
Rust
src/uucore/src/lib/macros.rs
E3uka/coreutils
c7f7a222b9a2e86a68b204b417fbe23e7df01e3f
use std::sync::atomic::AtomicBool; pub static UTILITY_IS_SECOND_ARG: AtomicBool = AtomicBool::new(false); #[macro_export] macro_rules! show( ($err:expr) => ({ let e = $err; $crate::error::set_exit_code(e.code()); eprintln!("{}: {}", $crate::util_name(), e); }) ); #[macro_export] macro_rules! show_if_err( ($res:expr) => ({ if let Err(e) = $res { show!(e); } }) ); #[macro_export] macro_rules! show_error( ($($args:tt)+) => ({ eprint!("{}: ", $crate::util_name()); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_error_custom_description ( ($err:expr,$($args:tt)+) => ({ eprint!("{}: {}: ", $crate::util_name(), $err); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_warning( ($($args:tt)+) => ({ eprint!("{}: warning: ", $crate::util_name()); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_usage_error( ($($args:tt)+) => ({ eprint!("{}: ", $crate::util_name()); eprintln!($($args)+); eprintln!("Try '{} --help' for more information.", $crate::execution_phrase()); }) ); #[macro_export] macro_rules! exit( ($exit_code:expr) => ({ ::std::process::exit($exit_code) }) ); #[macro_export] macro_rules! crash( ($exit_code:expr, $($args:tt)+) => ({ $crate::show_error!($($args)+); $crate::exit!($exit_code) }) ); #[macro_export] macro_rules! crash_if_err( ($exit_code:expr, $exp:expr) => ( match $exp { Ok(m) => m, Err(f) => $crate::crash!($exit_code, "{}", f), } ) ); #[macro_export] macro_rules! safe_unwrap( ($exp:expr) => ( match $exp { Ok(m) => m, Err(f) => $crate::crash!(1, "{}", f.to_string()) } ) ); #[macro_export] macro_rules! return_if_err( ($exit_code:expr, $exp:expr) => ( match $exp { Ok(m) => m, Err(f) => { $crate::show_error!("{}", f); return $exit_code; } } ) ); #[macro_export] macro_rules! safe_writeln( ($fd:expr, $($args:tt)+) => ( match writeln!($fd, $($args)+) { Ok(_) => {} Err(f) => panic!("{}", f) } ) ); #[macro_export] macro_rules! snippet_list_join_oxford_comma { ($conjunction:expr, $valOne:expr, $valTwo:expr) => ( format!("{}, {} {}", $valOne, $conjunction, $valTwo) ); ($conjunction:expr, $valOne:expr, $valTwo:expr $(, $remaining_values:expr)*) => ( format!("{}, {}", $valOne, $crate::snippet_list_join_oxford_comma!($conjunction, $valTwo $(, $remaining_values)*)) ); } #[macro_export] macro_rules! snippet_list_join { ($conjunction:expr, $valOne:expr, $valTwo:expr) => ( format!("{} {} {}", $valOne, $conjunction, $valTwo) ); ($conjunction:expr, $valOne:expr, $valTwo:expr $(, $remaining_values:expr)*) => ( format!("{}, {}", $valOne, $crate::snippet_list_join_oxford_comma!($conjunction, $valTwo $(, $remaining_values)*)) ); } #[macro_export] macro_rules! msg_invalid_input { ($reason: expr) => { format!("invalid input: {}", $reason) }; } #[macro_export] macro_rules! msg_invalid_opt_use { ($about:expr, $flag:expr) => { $crate::msg_invalid_input!(format!("The '{}' option {}", $flag, $about)) }; ($about:expr, $long_flag:expr, $short_flag:expr) => { $crate::msg_invalid_input!(format!( "The '{}' ('{}') option {}", $long_flag, $short_flag, $about )) }; } #[macro_export] macro_rules! msg_opt_only_usable_if { ($clause:expr, $flag:expr) => { $crate::msg_invalid_opt_use!(format!("only usable if {}", $clause), $flag) }; ($clause:expr, $long_flag:expr, $short_flag:expr) => { $crate::msg_invalid_opt_use!( format!("only usable if {}", $clause), $long_flag, $short_flag ) }; } #[macro_export] macro_rules! msg_opt_invalid_should_be { ($expects:expr, $received:expr, $flag:expr) => { $crate::msg_invalid_opt_use!( format!("expects {}, but was provided {}", $expects, $received), $flag ) }; ($expects:expr, $received:expr, $long_flag:expr, $short_flag:expr) => { $crate::msg_invalid_opt_use!( format!("expects {}, but was provided {}", $expects, $received), $long_flag, $short_flag ) }; } #[macro_export] macro_rules! msg_expects_one_of { ($valOne:expr $(, $remaining_values:expr)*) => ( $crate::msg_invalid_input!(format!("expects one of {}", $crate::snippet_list_join!("or", $valOne $(, $remaining_values)*))) ); } #[macro_export] macro_rules! msg_expects_no_more_than_one_of { ($valOne:expr $(, $remaining_values:expr)*) => ( $crate::msg_invalid_input!(format!("expects no more than one of {}", $crate::snippet_list_join!("or", $valOne $(, $remaining_values)*))) ; ); }
use std::sync::atomic::AtomicBool; pub static UTILITY_IS_SECOND_ARG: AtomicBool = AtomicBool::new(false); #[macro_export] macro_rules! show( ($err:expr) => ({ let e = $err; $crate::error::set_exit_code(e.code()); eprintln!("{}: {}", $crate::util_name(), e); }) ); #[macro_export] macro_rules! show_if_err( ($res:expr) => ({ if let Err(e) = $res { show!(e); } }) ); #[macro_export] macro_rules! show_error( ($($args:tt)+) => ({ eprint!("{}: ", $crate::util_name()); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_error_custom_description ( ($err:expr,$($args:tt)+) => ({ eprint!("{}: {}: ", $crate::util_name(), $err); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_warning( ($($args:tt)+) => ({ eprint!("{}: warning: ", $crate::util_name()); eprintln!($($args)+); }) ); #[macro_export] macro_rules! show_usage_error( ($($args:tt)+) => ({ eprint!("{}: ", $crate::util_name()); eprintln!($($args)+); eprintln!("Try '{} --help' for more information.", $crate::execution_phrase()); }) ); #[macro_export] macro_rules! exit( ($exit_code:expr) => ({ ::std::process::exit($exit_code) }) ); #[macro_export] macro_rules! crash( ($exit_code:expr, $($args:tt)+) => ({ $crate::show_error!($($args)+); $crate::exit!($exit_code) }) ); #[macro_export] macro_rules! crash_if_err( ($exit_code:expr, $exp:expr) => ( match $exp { Ok(m) => m, Err(f) => $crate::crash!($exit_code, "{}", f), } ) ); #[macro_export] macro_rules! safe_unwrap( ($exp:expr) => ( match $exp { Ok(m) => m, Err(f) => $crate::crash!(1, "{}", f.to_string()) } ) ); #[macro_export] macro_rules! return_if_err( ($exit_code:expr, $exp:expr) => ( match $exp { Ok
expr, $short_flag:expr) => { $crate::msg_invalid_opt_use!( format!("only usable if {}", $clause), $long_flag, $short_flag ) }; } #[macro_export] macro_rules! msg_opt_invalid_should_be { ($expects:expr, $received:expr, $flag:expr) => { $crate::msg_invalid_opt_use!( format!("expects {}, but was provided {}", $expects, $received), $flag ) }; ($expects:expr, $received:expr, $long_flag:expr, $short_flag:expr) => { $crate::msg_invalid_opt_use!( format!("expects {}, but was provided {}", $expects, $received), $long_flag, $short_flag ) }; } #[macro_export] macro_rules! msg_expects_one_of { ($valOne:expr $(, $remaining_values:expr)*) => ( $crate::msg_invalid_input!(format!("expects one of {}", $crate::snippet_list_join!("or", $valOne $(, $remaining_values)*))) ); } #[macro_export] macro_rules! msg_expects_no_more_than_one_of { ($valOne:expr $(, $remaining_values:expr)*) => ( $crate::msg_invalid_input!(format!("expects no more than one of {}", $crate::snippet_list_join!("or", $valOne $(, $remaining_values)*))) ; ); }
(m) => m, Err(f) => { $crate::show_error!("{}", f); return $exit_code; } } ) ); #[macro_export] macro_rules! safe_writeln( ($fd:expr, $($args:tt)+) => ( match writeln!($fd, $($args)+) { Ok(_) => {} Err(f) => panic!("{}", f) } ) ); #[macro_export] macro_rules! snippet_list_join_oxford_comma { ($conjunction:expr, $valOne:expr, $valTwo:expr) => ( format!("{}, {} {}", $valOne, $conjunction, $valTwo) ); ($conjunction:expr, $valOne:expr, $valTwo:expr $(, $remaining_values:expr)*) => ( format!("{}, {}", $valOne, $crate::snippet_list_join_oxford_comma!($conjunction, $valTwo $(, $remaining_values)*)) ); } #[macro_export] macro_rules! snippet_list_join { ($conjunction:expr, $valOne:expr, $valTwo:expr) => ( format!("{} {} {}", $valOne, $conjunction, $valTwo) ); ($conjunction:expr, $valOne:expr, $valTwo:expr $(, $remaining_values:expr)*) => ( format!("{}, {}", $valOne, $crate::snippet_list_join_oxford_comma!($conjunction, $valTwo $(, $remaining_values)*)) ); } #[macro_export] macro_rules! msg_invalid_input { ($reason: expr) => { format!("invalid input: {}", $reason) }; } #[macro_export] macro_rules! msg_invalid_opt_use { ($about:expr, $flag:expr) => { $crate::msg_invalid_input!(format!("The '{}' option {}", $flag, $about)) }; ($about:expr, $long_flag:expr, $short_flag:expr) => { $crate::msg_invalid_input!(format!( "The '{}' ('{}') option {}", $long_flag, $short_flag, $about )) }; } #[macro_export] macro_rules! msg_opt_only_usable_if { ($clause:expr, $flag:expr) => { $crate::msg_invalid_opt_use!(format!("only usable if {}", $clause), $flag) }; ($clause:expr, $long_flag:
random
[ { "content": "pub fn uu_app() -> App<'static, 'static> {\n\n App::new(uucore::util_name())\n\n .about(\"A file perusal filter for CRT viewing.\")\n\n .version(crate_version!())\n\n .arg(\n\n Arg::with_name(options::SILENT)\n\n .short(\"d\")\n\n .l...
Rust
src/io.rs
finalfusion/finalfusion-utils
d37a5d7f17515bcd0d6ba56a2e4dcec5914bf07a
use std::convert::TryFrom; use std::fmt; use std::fs::File; use std::io::{BufReader, BufWriter}; use anyhow::{anyhow, bail, Context, Error, Result}; use finalfusion::compat::floret::ReadFloretText; use finalfusion::compat::text::{WriteText, WriteTextDims}; use finalfusion::compat::word2vec::WriteWord2Vec; use finalfusion::io::WriteEmbeddings; use finalfusion::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EmbeddingFormat { FastText, FinalFusion, FinalFusionMmap, Floret, Word2Vec, Text, TextDims, } impl TryFrom<&str> for EmbeddingFormat { type Error = Error; fn try_from(format: &str) -> Result<Self> { use self::EmbeddingFormat::*; match format { "fasttext" => Ok(FastText), "finalfusion" => Ok(FinalFusion), "finalfusion_mmap" => Ok(FinalFusionMmap), "floret" => Ok(Floret), "word2vec" => Ok(Word2Vec), "text" => Ok(Text), "textdims" => Ok(TextDims), unknown => Err(anyhow!("Unknown embedding format: {}", unknown)), } } } impl fmt::Display for EmbeddingFormat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use EmbeddingFormat::*; let s = match self { FastText => "fasttext", FinalFusion => "finalfusion", FinalFusionMmap => "finalfusion_mmap", Floret => "floret", Word2Vec => "word2vec", Text => "text", TextDims => "textdims", }; f.write_str(s) } } pub fn read_embeddings( filename: &str, embedding_format: EmbeddingFormat, ) -> Result<Embeddings<VocabWrap, StorageWrap>> { let f = File::open(filename).context("Cannot open embeddings file")?; let mut reader = BufReader::new(f); use self::EmbeddingFormat::*; let embeds = match embedding_format { FastText => ReadFastText::read_fasttext(&mut reader).map(Embeddings::into), FinalFusion => ReadEmbeddings::read_embeddings(&mut reader), FinalFusionMmap => MmapEmbeddings::mmap_embeddings(&mut reader), Floret => ReadFloretText::read_floret_text(&mut reader).map(Embeddings::into), Word2Vec => ReadWord2Vec::read_word2vec_binary(&mut reader).map(Embeddings::into), Text => ReadText::read_text(&mut reader).map(Embeddings::into), TextDims => ReadTextDims::read_text_dims(&mut reader).map(Embeddings::into), }; Ok(embeds?) } pub fn read_embeddings_view( filename: &str, embedding_format: EmbeddingFormat, ) -> Result<Embeddings<VocabWrap, StorageViewWrap>> { let f = File::open(filename).context("Cannot open embeddings file")?; let mut reader = BufReader::new(f); use self::EmbeddingFormat::*; let embeds = match embedding_format { FastText => ReadFastText::read_fasttext(&mut reader).map(Embeddings::into), FinalFusion => ReadEmbeddings::read_embeddings(&mut reader), FinalFusionMmap => MmapEmbeddings::mmap_embeddings(&mut reader), Floret => ReadFloretText::read_floret_text(&mut reader).map(Embeddings::into), Word2Vec => ReadWord2Vec::read_word2vec_binary(&mut reader).map(Embeddings::into), Text => ReadText::read_text(&mut reader).map(Embeddings::into), TextDims => ReadTextDims::read_text_dims(&mut reader).map(Embeddings::into), }; Ok(embeds?) } pub fn write_embeddings( embeddings: &Embeddings<VocabWrap, StorageWrap>, filename: &str, format: EmbeddingFormat, unnormalize: bool, ) -> Result<()> { let f = File::create(filename).context(format!("Cannot create embeddings file: {}", filename))?; let mut writer = BufWriter::new(f); use self::EmbeddingFormat::*; match format { FastText => bail!("Writing to the fastText format is not supported"), FinalFusion => embeddings.write_embeddings(&mut writer)?, FinalFusionMmap => bail!("Writing to memory-mapped finalfusion file is not supported"), Floret => bail!("Writing to the floret format is not supported"), Word2Vec => embeddings.write_word2vec_binary(&mut writer, unnormalize)?, Text => embeddings.write_text(&mut writer, unnormalize)?, TextDims => embeddings.write_text_dims(&mut writer, unnormalize)?, }; Ok(()) }
use std::convert::TryFrom; use std::fmt; use std::fs::File; use std::io::{BufReader, BufWriter}; use anyhow::{anyhow, bail, Context, Error, Result}; use finalfusion::compat::floret::ReadFloretText; use finalfusion::compat::text::{WriteText, WriteTextDims}; use finalfusion::compat::word2vec::WriteWord2Vec; use finalfusion::io::WriteEmbeddings; use finalfusion::prelude::*; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EmbeddingFormat { FastText, FinalFusion, FinalFusionMmap, Floret, Word2Vec, Text, TextDims, } impl TryFrom<&str> for EmbeddingFormat { type Error = Error; fn try_from(format: &str) -> Result<Self> { use self::EmbeddingFormat::*; match
} impl fmt::Display for EmbeddingFormat { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use EmbeddingFormat::*; let s = match self { FastText => "fasttext", FinalFusion => "finalfusion", FinalFusionMmap => "finalfusion_mmap", Floret => "floret", Word2Vec => "word2vec", Text => "text", TextDims => "textdims", }; f.write_str(s) } } pub fn read_embeddings( filename: &str, embedding_format: EmbeddingFormat, ) -> Result<Embeddings<VocabWrap, StorageWrap>> { let f = File::open(filename).context("Cannot open embeddings file")?; let mut reader = BufReader::new(f); use self::EmbeddingFormat::*; let embeds = match embedding_format { FastText => ReadFastText::read_fasttext(&mut reader).map(Embeddings::into), FinalFusion => ReadEmbeddings::read_embeddings(&mut reader), FinalFusionMmap => MmapEmbeddings::mmap_embeddings(&mut reader), Floret => ReadFloretText::read_floret_text(&mut reader).map(Embeddings::into), Word2Vec => ReadWord2Vec::read_word2vec_binary(&mut reader).map(Embeddings::into), Text => ReadText::read_text(&mut reader).map(Embeddings::into), TextDims => ReadTextDims::read_text_dims(&mut reader).map(Embeddings::into), }; Ok(embeds?) } pub fn read_embeddings_view( filename: &str, embedding_format: EmbeddingFormat, ) -> Result<Embeddings<VocabWrap, StorageViewWrap>> { let f = File::open(filename).context("Cannot open embeddings file")?; let mut reader = BufReader::new(f); use self::EmbeddingFormat::*; let embeds = match embedding_format { FastText => ReadFastText::read_fasttext(&mut reader).map(Embeddings::into), FinalFusion => ReadEmbeddings::read_embeddings(&mut reader), FinalFusionMmap => MmapEmbeddings::mmap_embeddings(&mut reader), Floret => ReadFloretText::read_floret_text(&mut reader).map(Embeddings::into), Word2Vec => ReadWord2Vec::read_word2vec_binary(&mut reader).map(Embeddings::into), Text => ReadText::read_text(&mut reader).map(Embeddings::into), TextDims => ReadTextDims::read_text_dims(&mut reader).map(Embeddings::into), }; Ok(embeds?) } pub fn write_embeddings( embeddings: &Embeddings<VocabWrap, StorageWrap>, filename: &str, format: EmbeddingFormat, unnormalize: bool, ) -> Result<()> { let f = File::create(filename).context(format!("Cannot create embeddings file: {}", filename))?; let mut writer = BufWriter::new(f); use self::EmbeddingFormat::*; match format { FastText => bail!("Writing to the fastText format is not supported"), FinalFusion => embeddings.write_embeddings(&mut writer)?, FinalFusionMmap => bail!("Writing to memory-mapped finalfusion file is not supported"), Floret => bail!("Writing to the floret format is not supported"), Word2Vec => embeddings.write_word2vec_binary(&mut writer, unnormalize)?, Text => embeddings.write_text(&mut writer, unnormalize)?, TextDims => embeddings.write_text_dims(&mut writer, unnormalize)?, }; Ok(()) }
format { "fasttext" => Ok(FastText), "finalfusion" => Ok(FinalFusion), "finalfusion_mmap" => Ok(FinalFusionMmap), "floret" => Ok(Floret), "word2vec" => Ok(Word2Vec), "text" => Ok(Text), "textdims" => Ok(TextDims), unknown => Err(anyhow!("Unknown embedding format: {}", unknown)), } }
function_block-function_prefixed
[ { "content": "fn read_metadata(filename: impl AsRef<str>) -> Result<Value> {\n\n let f = File::open(filename.as_ref())\n\n .context(format!(\"Cannot open metadata file: {}\", filename.as_ref()))?;\n\n let mut reader = BufReader::new(f);\n\n let mut buf = String::new();\n\n reader\n\n ....
Rust
src/agent/coverage/src/cobertura.rs
tonybaloney/onefuzz
e0f2e9ed5aae006e0054387de7a0ff8c83c8f722
use crate::source::SourceCoverage; use crate::source::SourceCoverageLocation; use crate::source::SourceFileCoverage; use anyhow::Context; use anyhow::Error; use anyhow::Result; use std::time::{SystemTime, UNIX_EPOCH}; use xml::writer::{EmitterConfig, XmlEvent}; pub fn cobertura(source_coverage: SourceCoverage) -> Result<String, Error> { let mut backing: Vec<u8> = Vec::new(); let mut emitter = EmitterConfig::new() .perform_indent(true) .create_writer(&mut backing); let unixtime = SystemTime::now() .duration_since(UNIX_EPOCH) .context("system time before unix epoch")? .as_secs(); emitter.write( XmlEvent::start_element("coverage") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("lines-covered", "0") .attr("lines-valid", "0") .attr("branches-covered", "0") .attr("branches-valid", "0") .attr("complexity", "0") .attr("version", "0.1") .attr("timestamp", &format!("{}", unixtime)), )?; emitter.write(XmlEvent::start_element("packages"))?; emitter.write( XmlEvent::start_element("package") .attr("name", "0") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; emitter.write(XmlEvent::start_element("classes"))?; let files: Vec<SourceFileCoverage> = source_coverage.files; for file in files { emitter.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", &file.file) .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; let locations: Vec<SourceCoverageLocation> = file.locations; emitter.write(XmlEvent::start_element("lines"))?; for location in locations { emitter.write( XmlEvent::start_element("line") .attr("number", &location.line.to_string()) .attr("hits", &location.count.to_string()) .attr("branch", "false"), )?; emitter.write(XmlEvent::end_element())?; } emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; } emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; Ok(String::from_utf8(backing)?) } #[cfg(test)] mod tests { use super::*; use anyhow::Result; #[test] fn test_source_to_cobertura() -> Result<()> { let mut coverage_locations_vec1: Vec<SourceCoverageLocation> = Vec::new(); coverage_locations_vec1.push(SourceCoverageLocation { line: 5, column: None, count: 3, }); coverage_locations_vec1.push(SourceCoverageLocation { line: 10, column: None, count: 0, }); let mut coverage_locations_vec2: Vec<SourceCoverageLocation> = Vec::new(); coverage_locations_vec2.push(SourceCoverageLocation { line: 0, column: None, count: 0, }); let mut file_coverage_vec1: Vec<SourceFileCoverage> = Vec::new(); file_coverage_vec1.push(SourceFileCoverage { locations: coverage_locations_vec1, file: "C:/Users/file1.txt".to_string(), }); file_coverage_vec1.push(SourceFileCoverage { locations: coverage_locations_vec2, file: "C:/Users/file2.txt".to_string(), }); let source_coverage_result = cobertura(SourceCoverage { files: file_coverage_vec1, }); let mut backing_test: Vec<u8> = Vec::new(); let mut _emitter_test = EmitterConfig::new() .perform_indent(true) .create_writer(&mut backing_test); let unixtime = SystemTime::now() .duration_since(UNIX_EPOCH) .context("system time before unix epoch")? .as_secs(); _emitter_test.write( XmlEvent::start_element("coverage") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("lines-covered", "0") .attr("lines-valid", "0") .attr("branches-covered", "0") .attr("branches-valid", "0") .attr("complexity", "0") .attr("version", "0.1") .attr("timestamp", &format!("{}", unixtime)), )?; _emitter_test.write(XmlEvent::start_element("packages"))?; _emitter_test.write( XmlEvent::start_element("package") .attr("name", "0") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("classes"))?; _emitter_test.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", "C:/Users/file1.txt") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("lines"))?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "5") .attr("hits", "3") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "10") .attr("hits", "0") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", "C:/Users/file2.txt") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("lines"))?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "0") .attr("hits", "0") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; assert_eq!(source_coverage_result?, String::from_utf8(backing_test)?); Ok(()) } }
use crate::source::SourceCoverage; use crate::source::SourceCoverageLocation; use crate::source::SourceFileCoverage; use anyhow::Context; use anyhow::Error; use anyhow::Result; use std::time::{SystemTime, UNIX_EPOCH}; use xml::writer::{EmitterConfig, XmlEvent};
#[cfg(test)] mod tests { use super::*; use anyhow::Result; #[test] fn test_source_to_cobertura() -> Result<()> { let mut coverage_locations_vec1: Vec<SourceCoverageLocation> = Vec::new(); coverage_locations_vec1.push(SourceCoverageLocation { line: 5, column: None, count: 3, }); coverage_locations_vec1.push(SourceCoverageLocation { line: 10, column: None, count: 0, }); let mut coverage_locations_vec2: Vec<SourceCoverageLocation> = Vec::new(); coverage_locations_vec2.push(SourceCoverageLocation { line: 0, column: None, count: 0, }); let mut file_coverage_vec1: Vec<SourceFileCoverage> = Vec::new(); file_coverage_vec1.push(SourceFileCoverage { locations: coverage_locations_vec1, file: "C:/Users/file1.txt".to_string(), }); file_coverage_vec1.push(SourceFileCoverage { locations: coverage_locations_vec2, file: "C:/Users/file2.txt".to_string(), }); let source_coverage_result = cobertura(SourceCoverage { files: file_coverage_vec1, }); let mut backing_test: Vec<u8> = Vec::new(); let mut _emitter_test = EmitterConfig::new() .perform_indent(true) .create_writer(&mut backing_test); let unixtime = SystemTime::now() .duration_since(UNIX_EPOCH) .context("system time before unix epoch")? .as_secs(); _emitter_test.write( XmlEvent::start_element("coverage") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("lines-covered", "0") .attr("lines-valid", "0") .attr("branches-covered", "0") .attr("branches-valid", "0") .attr("complexity", "0") .attr("version", "0.1") .attr("timestamp", &format!("{}", unixtime)), )?; _emitter_test.write(XmlEvent::start_element("packages"))?; _emitter_test.write( XmlEvent::start_element("package") .attr("name", "0") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("classes"))?; _emitter_test.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", "C:/Users/file1.txt") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("lines"))?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "5") .attr("hits", "3") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "10") .attr("hits", "0") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", "C:/Users/file2.txt") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; _emitter_test.write(XmlEvent::start_element("lines"))?; _emitter_test.write( XmlEvent::start_element("line") .attr("number", "0") .attr("hits", "0") .attr("branch", "false"), )?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; _emitter_test.write(XmlEvent::end_element())?; assert_eq!(source_coverage_result?, String::from_utf8(backing_test)?); Ok(()) } }
pub fn cobertura(source_coverage: SourceCoverage) -> Result<String, Error> { let mut backing: Vec<u8> = Vec::new(); let mut emitter = EmitterConfig::new() .perform_indent(true) .create_writer(&mut backing); let unixtime = SystemTime::now() .duration_since(UNIX_EPOCH) .context("system time before unix epoch")? .as_secs(); emitter.write( XmlEvent::start_element("coverage") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("lines-covered", "0") .attr("lines-valid", "0") .attr("branches-covered", "0") .attr("branches-valid", "0") .attr("complexity", "0") .attr("version", "0.1") .attr("timestamp", &format!("{}", unixtime)), )?; emitter.write(XmlEvent::start_element("packages"))?; emitter.write( XmlEvent::start_element("package") .attr("name", "0") .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; emitter.write(XmlEvent::start_element("classes"))?; let files: Vec<SourceFileCoverage> = source_coverage.files; for file in files { emitter.write( XmlEvent::start_element("class") .attr("name", "0") .attr("filename", &file.file) .attr("line-rate", "0") .attr("branch-rate", "0") .attr("complexity", "0"), )?; let locations: Vec<SourceCoverageLocation> = file.locations; emitter.write(XmlEvent::start_element("lines"))?; for location in locations { emitter.write( XmlEvent::start_element("line") .attr("number", &location.line.to_string()) .attr("hits", &location.count.to_string()) .attr("branch", "false"), )?; emitter.write(XmlEvent::end_element())?; } emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; } emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; emitter.write(XmlEvent::end_element())?; Ok(String::from_utf8(backing)?) }
function_block-full_function
[ { "content": " def is_used(self) -> bool:\n\n if len(self.get_forwards()) == 0:\n\n logging.info(PROXY_LOG_PREFIX + \"no forwards: %s\", self.region)\n\n return False\n", "file_path": "src/api-service/__app__/onefuzzlib/proxy.py", "rank": 0, "score": 51893.43127703405...
Rust
gui/src/app/root_stack/oc_page/stats_grid.rs
ashleysmithgpu/LACT
0bfc6c5acdd800d33ce92527328a9477c215b180
use daemon::gpu_controller::GpuStats; use gtk::*; #[derive(Clone)] pub struct StatsGrid { pub container: Grid, vram_usage_bar: LevelBar, vram_usage_label: Label, gpu_clock_label: Label, vram_clock_label: Label, gpu_voltage_label: Label, power_usage_label: Label, gpu_temperature_label: Label, gpu_usage_label: Label, } impl StatsGrid { pub fn new() -> Self { let container = Grid::new(); container.set_column_homogeneous(true); container.set_row_spacing(7); container.attach(&Label::new(Some("VRAM Usage")), 0, 0, 1, 1); let vram_usage_overlay = Overlay::new(); let vram_usage_bar = LevelBar::new(); let vram_usage_label = Label::new(None); { vram_usage_bar.set_orientation(Orientation::Horizontal); vram_usage_bar.set_value(1.0); vram_usage_label.set_text("0/0 MiB"); vram_usage_overlay.add(&vram_usage_bar); vram_usage_overlay.add_overlay(&vram_usage_label); container.attach(&vram_usage_overlay, 1, 0, 2, 1); } let gpu_clock_label = Label::new(None); { let gpu_clock_box = Box::new(Orientation::Horizontal, 5); gpu_clock_box.pack_start(&Label::new(Some("GPU Clock:")), false, false, 2); gpu_clock_label.set_markup("<b>0MHz</b>"); gpu_clock_box.pack_start(&gpu_clock_label, false, false, 2); gpu_clock_box.set_halign(Align::Center); container.attach(&gpu_clock_box, 0, 1, 1, 1); } let vram_clock_label = Label::new(None); { let vram_clock_box = Box::new(Orientation::Horizontal, 5); vram_clock_box.pack_start(&Label::new(Some("VRAM Clock:")), false, false, 2); vram_clock_label.set_markup("<b>0MHz</b>"); vram_clock_box.pack_start(&vram_clock_label, false, false, 2); vram_clock_box.set_halign(Align::Center); container.attach(&vram_clock_box, 1, 1, 1, 1); } let gpu_voltage_label = Label::new(None); { let gpu_voltage_box = Box::new(Orientation::Horizontal, 5); gpu_voltage_box.pack_start(&Label::new(Some("GPU Voltage:")), false, false, 2); gpu_voltage_label.set_markup("<b>0.000V</b>"); gpu_voltage_box.pack_start(&gpu_voltage_label, false, false, 2); gpu_voltage_box.set_halign(Align::Center); container.attach(&gpu_voltage_box, 2, 1, 1, 1); } let power_usage_label = Label::new(None); { let power_usage_box = Box::new(Orientation::Horizontal, 5); power_usage_box.pack_start(&Label::new(Some("Power Usage:")), false, false, 2); power_usage_label.set_markup("<b>00/000W</b>"); power_usage_box.pack_start(&power_usage_label, false, false, 2); power_usage_box.set_halign(Align::Center); container.attach(&power_usage_box, 0, 2, 1, 1); } let gpu_temperature_label = Label::new(None); { let gpu_temperature_box = Box::new(Orientation::Horizontal, 5); gpu_temperature_box.pack_start(&Label::new(Some("GPU Temperature:")), false, false, 2); gpu_temperature_box.pack_start(&gpu_temperature_label, false, false, 2); gpu_temperature_box.set_halign(Align::Center); container.attach(&gpu_temperature_box, 1, 2, 1, 1); } let gpu_usage_label = Label::new(None); { let gpu_usage_box = Box::new(Orientation::Horizontal, 5); gpu_usage_box.pack_start(&Label::new(Some("GPU Usage:")), false, false, 2); gpu_usage_box.pack_start(&gpu_usage_label, false, false, 2); gpu_usage_box.set_halign(Align::Center); container.attach(&gpu_usage_box, 2, 2, 1, 1); } Self { container, vram_usage_bar, vram_usage_label, gpu_clock_label, vram_clock_label, gpu_voltage_label, power_usage_label, gpu_temperature_label, gpu_usage_label, } } pub fn set_stats(&self, stats: &GpuStats) { self.vram_usage_bar.set_value( stats.mem_used.unwrap_or_else(|| 0) as f64 / stats.mem_total.unwrap_or_else(|| 0) as f64, ); self.vram_usage_label.set_text(&format!( "{}/{} MiB", stats.mem_used.unwrap_or_else(|| 0), stats.mem_total.unwrap_or_else(|| 0) )); self.gpu_clock_label.set_markup(&format!( "<b>{}MHz</b>", stats.gpu_freq.unwrap_or_else(|| 0) )); self.vram_clock_label.set_markup(&format!( "<b>{}MHz</b>", stats.mem_freq.unwrap_or_else(|| 0) )); self.gpu_voltage_label.set_markup(&format!( "<b>{}V</b>", stats.voltage.unwrap_or_else(|| 0) as f64 / 1000f64 )); self.power_usage_label.set_markup(&format!( "<b>{}/{}W</b>", stats.power_avg.unwrap_or_else(|| 0), stats.power_cap.unwrap_or_else(|| 0) )); self.gpu_temperature_label .set_markup(&format!("<b>{}°C</b>", stats.gpu_temp.unwrap_or_default())); self.gpu_usage_label .set_markup(&format!("<b>{}%</b>", stats.gpu_usage.unwrap_or_default())); } }
use daemon::gpu_controller::GpuStats; use gtk::*; #[derive(Clone)] pub struct StatsGrid { pub container: Grid, vram_usage_bar: LevelBar, vram_usage_label: Label, gpu_clock_label: Label, vram_clock_label: Label, gpu_voltage_label: Label, power_usage_label: Label, gpu_temperature_label: Label, gpu_usage_label: Label, } impl StatsGrid { pub fn new() -> Self { let container = Grid::new(); container.set_column_homogeneous(true); container.set_row_spacing(7); container.attach(&Label::new(Some("VRAM Usage")), 0, 0, 1, 1); let vram_usage_overlay = Overlay::new(); let vram_usage_bar = LevelBar::new(); let vram_usage_label = Label::new(None); { vram_usage_bar.set_orientation(Orientation::Horizontal); vram_usage_bar.set_value(1.0); vram_usage_label.set_text("0/0 MiB"); vram_usage_overlay.add(&vram_usage_bar); vram_usage_overlay.add_overlay(&vram_usage_label); container.attach(&vram_usage_overlay, 1, 0, 2, 1); } let gpu_clock_label = Label::new(None); { let gpu_clock_box = Box::new(Orientation::Horizontal, 5); gpu_clock_box.pack_start(&Label::new(Some("GPU Clock:")), false, false, 2); gpu_clock_label.set_markup("<b>0MHz</b>"); gpu_clock_box.pack_start(&gpu_clock_label, false, false, 2); gpu_clock_box.set_halign(Align::Center); container.attach(&gpu_clock_box, 0, 1, 1, 1); } let vram_clock_label = Label::new(None); { let vram_clock_box = Box::new(Orientation::Horizontal, 5); vram_clock_box.pack_start(&Label::new(Some("VRAM Clock:")), false, false, 2); vram_clock_label.set_markup("<b>0MHz</b>"); vram_clock_box.pack_start(&vram_clock_label, false, false, 2); vram_clock_box.set_halign(Align::Center); container.attach(&vram_clock_box, 1, 1, 1, 1); } let gpu_voltage_label = Label::new(None); { let gpu_voltage_box = Box::new(Orientation::Horizontal, 5); gpu_voltage_box.pack_start(&Label::new(Some("GPU Voltage:")), false, false, 2); gpu_voltage_label.set_markup("<b>0.000V</b>"); gpu_voltage_box.pack_start(&gpu_voltage_label, false, false, 2); gpu_voltage_box.set_halign(Align::Center); container.attach(&gpu_voltage_box, 2, 1, 1, 1); } let power_usage_label = Label::new(None); { let power_usage_box = Box::new(Orientation::Horizontal, 5); power_usage_box.pack_start(&Label::new(Some("Power Usage:")), false, false, 2); power_usage_label.set_markup("<b>00/000W</b>"); power_usage_box.pack_start(&power_usage_label, false, false, 2); power_usage_box.set_halign(Align::Center); container.attach(&power_usage_box, 0, 2, 1, 1); } let gpu_temperature_label = Label::new(None); { let gpu_temperature_box = Box::new(Orientation::Horizontal, 5); gpu_temperature_box.pack_start(&Label::new(Some("GPU Temperature:")), false, false, 2); gpu_temperature_box.pack_start(&gpu_temperature_label, false, false, 2); gpu_temperature_box.set_halign(Align::Center); container.attach(&gpu_temperature_box, 1, 2, 1, 1); } let gpu_usage_label = Label::new(None); { let gpu_usage_box = Box::new(Orientation::Horizontal, 5); gpu_usage_box.pack_start(&Label::new(Some("GPU Usage:")), false, false, 2); gpu_usage_box.pack_start(&gpu_usage_label, false, false, 2); gpu_usage_box.set_halign(Align::Center); container.attach(&gpu_usage_box, 2, 2, 1, 1); } Self { container, vram_usage_bar, vram_usage_label, gpu_clock_label, vram_clock_label, gpu_voltage_label, power_usage_label, gpu_temperature_label, gpu_usage_label, } } pub fn set_stats(&self, stats: &GpuStats) { self.vram_usage_bar.set_value( stats.mem_used.unwrap_or_else(|| 0) as f64 / stats.mem_total.unwrap_or_else(|| 0) as f64, ); self.vram_usage_label.set_text(&format!( "{}/{} MiB", stats.mem_used.unwrap_or_else(|| 0), stats.mem_total.unwrap_or_else(|| 0) )); self.gpu_clock_label.set_markup(&format!( "<b>{}MHz</b>", stats.gpu_freq.unwrap_or_else(|| 0) )); self.vram_clock_label.set_markup(&format!( "<b>{}MHz</b>", stats.mem_freq.unwrap_or_else(|| 0) )); self.gpu_voltage_label.set_markup(&format!( "<b>{}V</b>", stats.voltage.unwrap_or_else(|| 0) as f64 / 1000f64 )); self.power_usage_label.set_markup(&format!( "<b>{}/{}W</b>", stats.power_avg.unwrap_or_else(|| 0),
}
stats.power_cap.unwrap_or_else(|| 0) )); self.gpu_temperature_label .set_markup(&format!("<b>{}°C</b>", stats.gpu_temp.unwrap_or_default())); self.gpu_usage_label .set_markup(&format!("<b>{}%</b>", stats.gpu_usage.unwrap_or_default())); }
function_block-function_prefix_line
[ { "content": "fn print_stats(d: &DaemonConnection, gpu_id: u32) {\n\n let gpu_stats = d.get_gpu_stats(gpu_id).unwrap();\n\n println!(\n\n \"{} {}/{}{}\",\n\n \"VRAM Usage:\".green(),\n\n gpu_stats.mem_used.unwrap_or_default().to_string().bold(),\n\n gpu_stats.mem_total.unwrap_o...
Rust
src/lib.rs
aldanor/pod-typeinfo
9118046ce2a8e9b4e6cc523d18d7eace8fdaf0f1
#![cfg_attr(feature = "unstable", feature(plugin))] #![cfg_attr(feature = "unstable", plugin(clippy))] #[derive(Clone, PartialEq, Debug)] pub enum Type { Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, Char, Bool, Array(Box<Type>, usize), Compound(Vec<Field>, usize), } impl Type { pub fn size(&self) -> usize { match *self { Type::Int8 | Type::UInt8 | Type::Bool => 1, Type::Int16 | Type::UInt16 => 2, Type::Int32 | Type::UInt32 | Type::Float32 | Type::Char => 4, Type::Int64 | Type::UInt64 | Type::Float64 => 8, Type::Array(ref ty, num) => ty.size() * num, Type::Compound(_, size) => size, } } pub fn is_scalar(&self) -> bool { !self.is_array() && !self.is_compound() } pub fn is_array(&self) -> bool { if let Type::Array(_, _) = *self { true } else { false } } pub fn is_compound(&self) -> bool { if let Type::Compound(_, _) = *self { true } else { false } } } #[derive(Clone, PartialEq, Debug)] pub struct Field { pub ty: Type, pub name: String, pub offset: usize, } impl Field { pub fn new<S: Into<String>>(ty: &Type, name: S, offset: usize) -> Field { Field { ty: ty.clone(), name: name.into(), offset: offset } } } pub trait TypeInfo: Copy { fn type_info() -> Type; } macro_rules! impl_scalar { ($t:ty, $i:ident) => ( impl $crate::TypeInfo for $t { #[inline(always)] fn type_info() -> $crate::Type { $crate::Type::$i } } ) } impl_scalar!(i8, Int8); impl_scalar!(i16, Int16); impl_scalar!(i32, Int32); impl_scalar!(i64, Int64); impl_scalar!(u8, UInt8); impl_scalar!(u16, UInt16); impl_scalar!(u32, UInt32); impl_scalar!(u64, UInt64); impl_scalar!(f32, Float32); impl_scalar!(f64, Float64); impl_scalar!(char, Char); impl_scalar!(bool, Bool); #[cfg(target_pointer_width = "32")] impl_scalar!(isize, Int32); #[cfg(target_pointer_width = "64")] impl_scalar!(isize, Int64); #[cfg(target_pointer_width = "32")] impl_scalar!(usize, UInt32); #[cfg(target_pointer_width = "64")] impl_scalar!(usize, UInt64); macro_rules! impl_array { ($($n:expr),*$(,)*) => { $( impl<T: $crate::TypeInfo> $crate::TypeInfo for [T; $n] { #[inline(always)] fn type_info() -> $crate::Type { $crate::Type::Array( Box::new(<T as $crate::TypeInfo>::type_info()), $n ) } } )* }; } impl_array!( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, ); #[macro_export] macro_rules! def { ($($(#[$attr:meta])* struct $s:ident { $($i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* struct $s { $($i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); ($($(#[$attr:meta])* pub struct $s:ident { $($i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* pub struct $s { $($i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); ($($(#[$attr:meta])* pub struct $s:ident { $(pub $i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* pub struct $s { $(pub $i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); (@impl $s:ident { $($i:ident: $t:ty),+ }) => ( impl $crate::TypeInfo for $s { fn type_info() -> $crate::Type { let base = 0usize as *const $s; $crate::Type::Compound(vec![$( $crate::Field::new( &<$t as $crate::TypeInfo>::type_info(), stringify!($i), unsafe { &((*base).$i) as *const $t as usize} ) ),+], ::std::mem::size_of::<$s>()) } } ); }
#![cfg_attr(feature = "unstable", feature(plugin))] #![cfg_attr(feature = "unstable", plugin(clippy))] #[derive(Clone, PartialEq, Debug)] pub enum Type { Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64, Char, Bool, Array(Box<Type>, usize), Compound(Vec<Field>, usize), } impl Type { pub fn size(&self) -> usize { match *self { Type::Int8 | Type::UInt8 | Type::Bool => 1, Type::Int16 | Type::UInt16 => 2, Type::Int32 | Type::UInt32 | Type::Float32 | Type::Char => 4, Type::Int64 | Type::UInt64 | Type::Float64 => 8, Type::Array(ref ty, num) => ty.size() * num, Type::Compound(_, size) => size, } } pub fn is_scalar(&self) -> bool { !self.is_array() && !self.is_compound() } pub fn is_array(&self) -> bool { if let Type::Array(_, _) = *self { true } else { false } } pub fn is_compound(&self) -> bool { if let Type::Compound(_, _) = *self { true } else { false } } } #[derive(Clone, PartialEq, Debug)] pub struct Field { pub ty: Type, pub name: String, pub offset: usize, } impl Field {
} pub trait TypeInfo: Copy { fn type_info() -> Type; } macro_rules! impl_scalar { ($t:ty, $i:ident) => ( impl $crate::TypeInfo for $t { #[inline(always)] fn type_info() -> $crate::Type { $crate::Type::$i } } ) } impl_scalar!(i8, Int8); impl_scalar!(i16, Int16); impl_scalar!(i32, Int32); impl_scalar!(i64, Int64); impl_scalar!(u8, UInt8); impl_scalar!(u16, UInt16); impl_scalar!(u32, UInt32); impl_scalar!(u64, UInt64); impl_scalar!(f32, Float32); impl_scalar!(f64, Float64); impl_scalar!(char, Char); impl_scalar!(bool, Bool); #[cfg(target_pointer_width = "32")] impl_scalar!(isize, Int32); #[cfg(target_pointer_width = "64")] impl_scalar!(isize, Int64); #[cfg(target_pointer_width = "32")] impl_scalar!(usize, UInt32); #[cfg(target_pointer_width = "64")] impl_scalar!(usize, UInt64); macro_rules! impl_array { ($($n:expr),*$(,)*) => { $( impl<T: $crate::TypeInfo> $crate::TypeInfo for [T; $n] { #[inline(always)] fn type_info() -> $crate::Type { $crate::Type::Array( Box::new(<T as $crate::TypeInfo>::type_info()), $n ) } } )* }; } impl_array!( 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, ); #[macro_export] macro_rules! def { ($($(#[$attr:meta])* struct $s:ident { $($i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* struct $s { $($i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); ($($(#[$attr:meta])* pub struct $s:ident { $($i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* pub struct $s { $($i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); ($($(#[$attr:meta])* pub struct $s:ident { $(pub $i:ident: $t:ty),+$(,)* })*) => ( $( #[allow(dead_code)] #[derive(Clone, Copy)] $(#[$attr])* pub struct $s { $(pub $i: $t),+ } def!(@impl $s { $($i: $t),+ } ); )* ); (@impl $s:ident { $($i:ident: $t:ty),+ }) => ( impl $crate::TypeInfo for $s { fn type_info() -> $crate::Type { let base = 0usize as *const $s; $crate::Type::Compound(vec![$( $crate::Field::new( &<$t as $crate::TypeInfo>::type_info(), stringify!($i), unsafe { &((*base).$i) as *const $t as usize} ) ),+], ::std::mem::size_of::<$s>()) } } ); }
pub fn new<S: Into<String>>(ty: &Type, name: S, offset: usize) -> Field { Field { ty: ty.clone(), name: name.into(), offset: offset } }
function_block-full_function
[ { "content": "#[test]\n\n#[allow(unused_variables, unused_imports)]\n\nfn test_pub_structs_fields() {\n\n use module::{A, B};\n\n use module::multiple::{E, F, G, H};\n\n let b = B { x: 1, y: 2 };\n\n}\n", "file_path": "tests/test.rs", "rank": 0, "score": 65230.86850490266 }, { "cont...
Rust
src/main.rs
sonald/redis-cli-rs
5de760421f4d052d4a28001d1274ab90688d0fd3
use structopt::StructOpt; use tokio::prelude::*; use tokio::net::TcpStream; use rustyline::{Editor, error::ReadlineError}; use std::error::Error; use log::*; use std::io::Write; mod redis; use self::redis::*; #[derive(Debug, StructOpt)] struct Opt { #[structopt(short, long)] pub debug: bool, #[structopt(short, long, default_value = "127.0.0.1")] pub hostname: String, #[structopt(short("P"), long, default_value = "6379")] pub port: u16, #[structopt(short, long)] pub pipe: bool, pub cmds: Vec<String>, } type Result<T> = std::result::Result<T, Box<dyn Error>>; async fn read_redis_output(cli: &mut TcpStream) -> Result<Vec<u8>> { let mut res = vec![]; let mut buf = [0u8; 64]; loop { let n = cli.read(&mut buf[..]).await?; res.extend(&buf[..n]); if n < 64 { break } } Ok(res) } async fn consume_all_output(cli: &mut TcpStream) -> Result<()> { let res = read_redis_output(cli).await?; let mut start = 0; while let Some((value, left)) = RedisValue::deserialize(&res[start..]) { info!("{}", value); start += left; } Ok(()) } async fn stream(args: Vec<String>, pipe: bool, cli: &mut TcpStream) -> Result<()> { let cmd = args[0].clone(); let data = if pipe { args.into_iter().map(|a| a + "\r\n").collect::<String>().into_bytes() } else { let value = RedisValue::from_vec(args); value.to_wire()? }; cli.write(data.as_slice()).await?; match cmd.as_str() { "monitor" | "subscribe" => loop { consume_all_output(cli).await? }, _ => consume_all_output(cli).await } } async fn interactive<S: AsRef<str>>(prompt: S, cli: &mut TcpStream) -> Result<()> { let mut rl = Editor::<()>::new(); loop { let readline = rl.readline(prompt.as_ref()); match readline { Ok(line) => { rl.add_history_entry(line.as_str()); let args = line.split_whitespace().map(|s| s.to_owned()).collect::<Vec<String>>(); let cmd = args[0].clone(); let value = RedisValue::from_vec(args); cli.write(value.to_wire()?.as_slice()).await?; match cmd.as_str() { "monitor" | "subscribe" => loop { consume_all_output(cli).await? }, _ => { let res = read_redis_output(cli).await?; print!("{}", RedisValue::deserialize(&res).expect("").0); } } }, Err(ReadlineError::Interrupted) => { info!("CTRL-C"); break }, Err(ReadlineError::Eof) => { info!("CTRL-D"); break }, Err(err) => { return Err(Box::new(err)) } } } Ok(()) } async fn run(args: Opt) -> Result<()> { let mut cli = TcpStream::connect((args.hostname.as_str(), args.port)).await?; let prompt = format!("{}:{}> ", args.hostname,args.port); if args.cmds.len() == 0 && !args.pipe { interactive(prompt, &mut cli).await } else { let cmds = if args.pipe { let mut buf = String::new(); tokio::io::stdin().read_to_string(&mut buf).await?; buf.split('\n').map(|s| s.to_owned()).collect::<Vec<String>>() } else { args.cmds }; stream(cmds, args.pipe, &mut cli).await } } #[tokio::main] async fn main() { unsafe { signal_hook::register(signal_hook::SIGINT, || { println!("quit"); std::process::exit(0); }).expect("hook sigint failed"); } let start = std::time::Instant::now(); env_logger::builder().format(move |buf, log| { let current = start.elapsed().as_secs_f32(); writeln!(buf, "{:.04} {} - {}", current, log.level(), log.args()) }).init(); let args = Opt::from_args(); info!("start"); if let Err(err) = run(args).await { error!("error: {}", err); } }
use structopt::StructOpt; use tokio::prelude::*; use tokio::net::TcpStream; use rustyline::{Editor, error::ReadlineError}; use std::error::Error; use log::*; use std::io::Write; mod redis; use self::redis::*; #[derive(Debug, StructOpt)] struct Opt { #[structopt(short, long)] pub debug: bool, #[structopt(short, long, default_value = "127.0.0.1")] pub hostname: String, #[structopt(short("P"), long, default_value = "6379")] pub port: u16, #[structopt(short, long)] pub pipe: bool, pub cmds: Vec<String>, } type Result<T> = std::result::Result<T, Box<dyn Error>>; async fn read_redis_output(cli: &mut TcpStream) -> Result<Vec<u8>> { let mut res = vec![]; let mut buf = [0u8; 64]; loop { let n = cli.read(&mut buf[..]).await?; res.extend(&buf[..n]); if n < 64 { break } } Ok(res) } async fn consume_all_output(cli: &mut TcpStream) -> Result<()> { let res = read_redis_output(cli).await?; let mut start = 0; while let Some((value, left)) = RedisValue::deserialize(&res[start..]) { info!("{}", value); start += left; } Ok(()) } async fn stream(args: Vec<String>, pipe: bool, cli: &mut TcpStream) -> Result<()> { let cmd = args[0].clone(); let data = if pipe { args.into_iter().map(|a| a + "\r\n").collect::<String>().into_bytes() } else { let value = RedisValue::from_vec(args); value.to_wire()? }; cli.write(data.as_slice()).await?; match cmd.as_str() { "monitor" | "subscribe" => loop { consume_all_output(cli).await? }, _ => consume_all_output(cli).await } } async fn interactive<S: AsRef<str>>(prompt: S, cli: &mut TcpStream) -> Result<()> { let mut rl = Editor::<()>::new(); loop { let readline = rl.readline(prompt.as_ref()); match readline { Ok(line) => { rl.add_history_entry(line.as_str()); let args = line.split_whitespace().map(|s| s.to_owned()).collect::<Vec<String>>(); let cmd = args[0].clone(); let value = RedisValue::from_vec(args); cli.write(value.to_wire()?.as_slice()).await?; match cmd.as_str() {
_ => { let res = read_redis_output(cli).await?; print!("{}", RedisValue::deserialize(&res).expect("").0); } } }, Err(ReadlineError::Interrupted) => { info!("CTRL-C"); break }, Err(ReadlineError::Eof) => { info!("CTRL-D"); break }, Err(err) => { return Err(Box::new(err)) } } } Ok(()) } async fn run(args: Opt) -> Result<()> { let mut cli = TcpStream::connect((args.hostname.as_str(), args.port)).await?; let prompt = format!("{}:{}> ", args.hostname,args.port); if args.cmds.len() == 0 && !args.pipe { interactive(prompt, &mut cli).await } else { let cmds = if args.pipe { let mut buf = String::new(); tokio::io::stdin().read_to_string(&mut buf).await?; buf.split('\n').map(|s| s.to_owned()).collect::<Vec<String>>() } else { args.cmds }; stream(cmds, args.pipe, &mut cli).await } } #[tokio::main] async fn main() { unsafe { signal_hook::register(signal_hook::SIGINT, || { println!("quit"); std::process::exit(0); }).expect("hook sigint failed"); } let start = std::time::Instant::now(); env_logger::builder().format(move |buf, log| { let current = start.elapsed().as_secs_f32(); writeln!(buf, "{:.04} {} - {}", current, log.level(), log.args()) }).init(); let args = Opt::from_args(); info!("start"); if let Err(err) = run(args).await { error!("error: {}", err); } }
"monitor" | "subscribe" => loop { consume_all_output(cli).await? },
function_block-random_span
[ { "content": "# cedis\n\n\n\na simple redis-cli replacement written in pure rust\n", "file_path": "README.md", "rank": 2, "score": 13893.999718397194 }, { "content": "use std::fmt;\n\nuse std::error::Error;\n\nuse bytes::Bytes;\n\n\n\n#[derive(Debug)]\n\npub enum RedisValue {\n\n Str(Stri...
Rust
runtime_v4/src/runtime.rs
MatchaChoco010/game_loop_async_runtime
4ccd2e4c642cdf793f83c8764d8b408fbfe17b05
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::hash::Hash; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use futures::task::ArcWake; struct Task { future: Pin<Box<dyn Future<Output = ()> + 'static>>, } impl Task { fn new(f: impl Future<Output = ()> + 'static) -> Self { Self { future: Box::pin(f), } } fn poll(&mut self, mut ctx: Context) -> Poll<()> { match Future::poll(self.future.as_mut(), &mut ctx) { Poll::Pending => Poll::Pending, Poll::Ready(()) => Poll::Ready(()), } } } #[derive(Clone)] struct WakeFlag { waked: Arc<Mutex<bool>>, } impl WakeFlag { fn new() -> Self { Self { waked: Arc::new(Mutex::new(false)), } } fn wake(&self) { *self.waked.lock().unwrap() = true; } fn is_waked(&self) -> bool { *self.waked.lock().unwrap() } } #[derive(Clone)] struct WakeFlagWaker { flag: WakeFlag, } impl WakeFlagWaker { fn waker(flag: WakeFlag) -> Waker { futures::task::waker(Arc::new(Self { flag })) } } impl ArcWake for WakeFlagWaker { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.flag.wake(); } } pub enum RuntimeIsDone { Done, NotDone, } #[derive(Clone)] pub struct Runtime<T: Eq + Hash + Clone + Debug> { frame_counter: u64, tasks: Rc<RefCell<HashMap<T, Vec<Task>>>>, wait_tasks: Rc<RefCell<HashMap<T, Vec<Task>>>>, activated_phase: Rc<RefCell<HashMap<u16, T>>>, } impl<T: Eq + Hash + Clone + Debug> Runtime<T> { pub fn new() -> Self { Self { frame_counter: 0, tasks: Rc::new(RefCell::new(HashMap::new())), wait_tasks: Rc::new(RefCell::new(HashMap::new())), activated_phase: Rc::new(RefCell::new(HashMap::new())), } } pub fn spawn(&self, phase: T, f: impl Future<Output = ()> + 'static) { let mut tasks = self.tasks.borrow_mut(); let ts = tasks.entry(phase).or_insert(vec![]); ts.push(Task::new(f)); } pub fn update(&mut self) -> RuntimeIsDone { let activated_phase = self.activated_phase.borrow(); let mut phases = activated_phase.iter().collect::<Vec<_>>(); phases.sort_by_key(|(&order, _phase)| order); let phases = phases.into_iter().map(|(_order, phase)| phase); for phase in phases { 'current_frame: loop { let task = self .tasks .borrow_mut() .entry(phase.clone()) .or_insert(vec![]) .pop(); match task { None => break 'current_frame, Some(mut task) => { let flag = WakeFlag::new(); let waker = WakeFlagWaker::waker(flag.clone()); match task.poll(Context::from_waker(&waker)) { Poll::Ready(()) => (), Poll::Pending => { if flag.is_waked() { let mut tasks = self.tasks.borrow_mut(); let ts = tasks.entry(phase.clone()).or_insert(vec![]); ts.push(task); } else { let mut wait_tasks = self.wait_tasks.borrow_mut(); let wts = wait_tasks.entry(phase.clone()).or_insert(vec![]); wts.push(task); } } } } } } } { let mut done_flag = true; let wait_tasks = self.wait_tasks.borrow(); for (_p, tasks) in wait_tasks.iter() { if !tasks.is_empty() { done_flag = false; } } if done_flag { return RuntimeIsDone::Done; } } self.frame_counter += 1; std::mem::swap(&mut self.wait_tasks, &mut self.tasks); RuntimeIsDone::NotDone } pub fn frame_counter(&self) -> u64 { self.frame_counter } pub fn activate_phase(&mut self, phase: T, order: u16) { let mut activated_phase = self.activated_phase.borrow_mut(); if let Some(p) = activated_phase.get(&order) { panic!(format!( "Another PHASE has already been registered in this order: {:?}", p )); } activated_phase.insert(order, phase); } }
use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Debug; use std::future::Future; use std::hash::Hash; use std::pin::Pin; use std::rc::Rc; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll, Waker}; use futures::task::ArcWake; struct Task { future: Pin<Box<dyn Future<Output = ()> + 'static>>, } impl Task { fn new(f: impl Future<Output = ()> + 'static) -> Self { Self { future: Box::pin(f), } } fn poll(&mut self, mut ctx: Context) -> Poll<()> { match Future::poll(self.future.as_mut(), &mut ctx) { Poll::Pending => Poll::Pending, Poll::Ready(()) => Poll::Ready(()), } } } #[derive(Clone)] struct WakeFlag { waked: Arc<Mutex<bool>>, } impl WakeFlag { fn new() -> Self { Self { waked: Arc::new(Mutex::new(false)), } } fn wake(&self) { *self.waked.lock().unwrap() = true; } fn is_waked(&self) -> bool { *self.waked.lock().unwrap() } } #[derive(Clone)] struct WakeFlagWaker { flag: WakeFlag, } impl WakeFlagWaker { fn waker(flag: WakeFlag) -> Waker { futures::task::waker(Arc::new(Self { flag })) } } impl ArcWake for WakeFlagWaker { fn wake_by_ref(arc_self: &Arc<Self>) { arc_self.flag.wake(); } } pub enum RuntimeIsDone { Done,
c<RefCell<HashMap<T, Vec<Task>>>>, activated_phase: Rc<RefCell<HashMap<u16, T>>>, } impl<T: Eq + Hash + Clone + Debug> Runtime<T> { pub fn new() -> Self { Self { frame_counter: 0, tasks: Rc::new(RefCell::new(HashMap::new())), wait_tasks: Rc::new(RefCell::new(HashMap::new())), activated_phase: Rc::new(RefCell::new(HashMap::new())), } } pub fn spawn(&self, phase: T, f: impl Future<Output = ()> + 'static) { let mut tasks = self.tasks.borrow_mut(); let ts = tasks.entry(phase).or_insert(vec![]); ts.push(Task::new(f)); } pub fn update(&mut self) -> RuntimeIsDone { let activated_phase = self.activated_phase.borrow(); let mut phases = activated_phase.iter().collect::<Vec<_>>(); phases.sort_by_key(|(&order, _phase)| order); let phases = phases.into_iter().map(|(_order, phase)| phase); for phase in phases { 'current_frame: loop { let task = self .tasks .borrow_mut() .entry(phase.clone()) .or_insert(vec![]) .pop(); match task { None => break 'current_frame, Some(mut task) => { let flag = WakeFlag::new(); let waker = WakeFlagWaker::waker(flag.clone()); match task.poll(Context::from_waker(&waker)) { Poll::Ready(()) => (), Poll::Pending => { if flag.is_waked() { let mut tasks = self.tasks.borrow_mut(); let ts = tasks.entry(phase.clone()).or_insert(vec![]); ts.push(task); } else { let mut wait_tasks = self.wait_tasks.borrow_mut(); let wts = wait_tasks.entry(phase.clone()).or_insert(vec![]); wts.push(task); } } } } } } } { let mut done_flag = true; let wait_tasks = self.wait_tasks.borrow(); for (_p, tasks) in wait_tasks.iter() { if !tasks.is_empty() { done_flag = false; } } if done_flag { return RuntimeIsDone::Done; } } self.frame_counter += 1; std::mem::swap(&mut self.wait_tasks, &mut self.tasks); RuntimeIsDone::NotDone } pub fn frame_counter(&self) -> u64 { self.frame_counter } pub fn activate_phase(&mut self, phase: T, order: u16) { let mut activated_phase = self.activated_phase.borrow_mut(); if let Some(p) = activated_phase.get(&order) { panic!(format!( "Another PHASE has already been registered in this order: {:?}", p )); } activated_phase.insert(order, phase); } }
NotDone, } #[derive(Clone)] pub struct Runtime<T: Eq + Hash + Clone + Debug> { frame_counter: u64, tasks: Rc<RefCell<HashMap<T, Vec<Task>>>>, wait_tasks: R
random
[ { "content": "#[derive(Clone)]\n\nstruct WakeFlagWaker {\n\n flag: WakeFlag,\n\n}\n\nimpl WakeFlagWaker {\n\n fn waker(flag: WakeFlag) -> Waker {\n\n futures::task::waker(Arc::new(Self { flag }))\n\n }\n\n}\n\nimpl ArcWake for WakeFlagWaker {\n\n fn wake_by_ref(arc_self: &Arc<Self>) {\n\n ...
Rust
src/prng/chacha.rs
TheIronBorn/rand
e1b60350d0936e6f17c7fd017ed18f3151006f43
use core::fmt; use rand_core::{BlockRngCore, CryptoRng, RngCore, SeedableRng, Error, le}; use rand_core::impls::BlockRng; const SEED_WORDS: usize = 8; const STATE_WORDS: usize = 16; #[derive(Clone, Debug)] pub struct ChaChaRng(BlockRng<ChaChaCore>); impl RngCore for ChaChaRng { #[inline] fn next_u32(&mut self) -> u32 { self.0.next_u32() } #[inline] fn next_u64(&mut self) -> u64 { self.0.next_u64() } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { self.0.fill_bytes(dest) } #[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.0.try_fill_bytes(dest) } } impl SeedableRng for ChaChaRng { type Seed = <ChaChaCore as SeedableRng>::Seed; fn from_seed(seed: Self::Seed) -> Self { ChaChaRng(BlockRng::<ChaChaCore>::from_seed(seed)) } fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { BlockRng::<ChaChaCore>::from_rng(rng).map(ChaChaRng) } } impl CryptoRng for ChaChaRng {} impl ChaChaRng { #[deprecated(since="0.5.0", note="use the NewRng or SeedableRng trait")] pub fn new_unseeded() -> ChaChaRng { ChaChaRng::from_seed([0; SEED_WORDS*4]) } pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.0.inner_mut().set_counter(counter_low, counter_high); self.0.reset(); } pub fn set_rounds(&mut self, rounds: usize) { self.0.inner_mut().set_rounds(rounds); self.0.reset(); } } #[derive(Clone)] pub struct ChaChaCore { state: [u32; STATE_WORDS], rounds: usize, } impl fmt::Debug for ChaChaCore { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ChaChaCore {{}}") } } macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16); $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12); $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8); $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } impl BlockRngCore for ChaChaCore { type Item = u32; type Results = [u32; STATE_WORDS]; fn generate(&mut self, results: &mut Self::Results) { fn core(results: &mut [u32; STATE_WORDS], state: &[u32; STATE_WORDS], rounds: usize) { let mut tmp = *state; for _ in 0..rounds / 2 { double_round!(tmp); } for i in 0..STATE_WORDS { results[i] = tmp[i].wrapping_add(state[i]); } } core(results, &self.state, self.rounds); self.state[12] = self.state[12].wrapping_add(1); if self.state[12] != 0 { return; }; self.state[13] = self.state[13].wrapping_add(1); if self.state[13] != 0 { return; }; self.state[14] = self.state[14].wrapping_add(1); if self.state[14] != 0 { return; }; self.state[15] = self.state[15].wrapping_add(1); } } impl ChaChaCore { pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = counter_low as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = counter_high as u32; self.state[15] = (counter_high >> 32) as u32; } pub fn set_rounds(&mut self, rounds: usize) { assert!([4usize, 8, 12, 16, 20].iter().any(|x| *x == rounds)); self.rounds = rounds; } } impl SeedableRng for ChaChaCore { type Seed = [u8; SEED_WORDS*4]; fn from_seed(seed: Self::Seed) -> Self { let mut seed_le = [0u32; SEED_WORDS]; le::read_u32_into(&seed, &mut seed_le); Self { state: [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574, seed_le[0], seed_le[1], seed_le[2], seed_le[3], seed_le[4], seed_le[5], seed_le[6], seed_le[7], 0, 0, 0, 0], rounds: 20, } } } impl CryptoRng for ChaChaCore {} #[cfg(test)] mod test { use {RngCore, SeedableRng}; use super::ChaChaRng; #[test] fn test_chacha_construction() { let seed = [0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0]; let mut rng1 = ChaChaRng::from_seed(seed); assert_eq!(rng1.next_u32(), 137206642); let mut rng2 = ChaChaRng::from_rng(rng1).unwrap(); assert_eq!(rng2.next_u32(), 1325750369); } #[test] fn test_chacha_true_values_a() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2]; assert_eq!(results, expected); for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b]; assert_eq!(results, expected); } #[test] fn test_chacha_true_values_b() { let seed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; let mut rng = ChaChaRng::from_seed(seed); for _ in 0..16 { rng.next_u32(); } let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8, 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8, 0xebdd4aa6, 0xa0136c00]; assert_eq!(results, expected); } #[test] fn test_chacha_true_values_c() { let seed = [0, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let expected = [0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1, 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5, 0x87f47473, 0x96f0992e]; let mut results = [0u32; 16]; let mut rng1 = ChaChaRng::from_seed(seed); for _ in 0..32 { rng1.next_u32(); } for i in results.iter_mut() { *i = rng1.next_u32(); } assert_eq!(results, expected); let mut rng2 = ChaChaRng::from_seed(seed); rng2.set_counter(2, 0); for i in results.iter_mut() { *i = rng2.next_u32(); } assert_eq!(results, expected); } #[test] fn test_chacha_multiple_blocks() { let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); for _ in 0..16 { rng.next_u32(); } } let expected = [0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4]; assert_eq!(results, expected); } #[test] fn test_chacha_true_bytes() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u8; 32]; rng.fill_bytes(&mut results); let expected = [118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 83, 134, 189, 40, 189, 210, 25, 184, 160, 141, 237, 26, 168, 54, 239, 204, 139, 119, 13, 199]; assert_eq!(results, expected); } #[test] fn test_chacha_set_counter() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); rng.set_counter(0, 2u64 << 56); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72, 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8, 0x398a19fa, 0x6ded1b53]; assert_eq!(results, expected); } #[test] fn test_chacha_set_rounds() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); rng.set_rounds(8); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x2fef003e, 0xd6405f89, 0xe8b85b7f, 0xa1a5091f, 0xc30e842c, 0x3b7f9ace, 0x88e11b18, 0x1e1a71ef, 0x72e14c98, 0x416f21b9, 0x6753449f, 0x19566d45, 0xa3424a31, 0x01b086da, 0xb8fd7b38, 0x42fe0c0e]; assert_eq!(results, expected); } #[test] fn test_chacha_clone() { let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; let mut rng = ChaChaRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } } }
use core::fmt; use rand_core::{BlockRngCore, CryptoRng, RngCore, SeedableRng, Error, le}; use rand_core::impls::BlockRng; const SEED_WORDS: usize = 8; const STATE_WORDS: usize = 16; #[derive(Clone, Debug)] pub struct ChaChaRng(BlockRng<ChaChaCore>); impl RngCore for ChaChaRng { #[inline] fn next_u32(&mut self) -> u32 { self.0.next_u32() } #[inline] fn next_u64(&mut self) -> u64 { self.0.next_u64() } #[inline] fn fill_bytes(&mut self, dest: &mut [u8]) { self.0.fill_bytes(dest) } #[inline] fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> { self.0.try_fill_bytes(dest) } } impl SeedableRng for ChaChaRng { type Seed = <ChaChaCore as SeedableRng>::Seed; fn from_seed(seed: Self::Seed) -> Self { ChaChaRng(BlockRng::<ChaChaCore>::from_seed(seed)) } fn from_rng<R: RngCore>(rng: R) -> Result<Self, Error> { BlockRng::<ChaChaCore>::from_rng(rng).map(ChaChaRng) } } impl CryptoRng for ChaChaRng {} impl ChaChaRng { #[deprecated(since="0.5.0", note="use the NewRng or SeedableRng trait")] pub fn new_unseeded() -> ChaChaRng { ChaChaRng::from_seed([0; SEED_WORDS*4]) } pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.0.inner_mut().set_counter(counter_low, counter_high); self.0.reset(); } pub fn set_rounds(&mut self, rounds: usize) { self.0.inner_mut().set_rounds(rounds); self.0.reset(); } } #[derive(Clone)] pub struct ChaChaCore { state: [u32; STATE_WORDS], rounds: usize, } impl fmt::Debug for ChaChaCore { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ChaChaCore {{}}") } } macro_rules! quarter_round{ ($a: expr, $b: expr, $c: expr, $d: expr) => {{ $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16); $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12); $a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8); $c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7); }} } macro_rules! double_round{ ($x: expr) => {{ quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]); quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]); quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]); quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]); quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]); quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]); quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]); quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]); }} } impl BlockRngCore for ChaChaCore { type Item = u32; type Results = [u32; STATE_WORDS]; fn generate(&mut self, results: &mut Self::Results) { fn core(results: &mut [u32; STATE_WORDS], state: &[u32; STATE_WORDS], rounds: usize) { let mut tmp = *state; for _ in 0..rounds / 2 { double_round!(tmp); } for i in 0..STATE_WORDS { results[i] = tmp[i].wrapping_add(state[i]); } } core(results, &self.state, self.rounds); self.state[12] = self.state[12].wrapping_add(1); if self.state[12] != 0 { return; }; self.state[13] = self.state[13].wrapping_add(1); if self.state[13] != 0 { return; }; self.state[14] = self.state[14].wrapping_add(1); if self.state[14] != 0 { return; }; self.state[15] = self.state[15].wrapping_add(1); } } impl ChaChaCore { pub fn set_counter(&mut self, counter_low: u64, counter_high: u64) { self.state[12] = counter_low as u32; self.state[13] = (counter_low >> 32) as u32; self.state[14] = counter_high as u32; self.state[15] = (counter_high >> 32) as u32; } pub fn set_rounds(&mut self, rounds: usize) { assert!([4usize, 8, 12, 16, 20].iter().any(|x| *x == rounds)); self.rounds = rounds; } } impl SeedableRng for ChaChaCore { type Seed = [u8; SEED_WORDS*4]; fn from_seed(seed: Self::Seed) -> Self { let mut seed_le = [0u32; SEED_WORDS]; le::read_u32_into(&seed, &mut seed_le); Self { state: [0x61707865, 0x3320646E, 0x79622D32, 0x6B206574, seed_le[0], seed_le[1], seed_le[2], seed_le[3], seed_le[4], seed_le[5], seed_le[6], seed_le[7], 0, 0, 0, 0], rounds: 20, } } } impl CryptoRng for ChaChaCore {} #[cfg(test)] mod test { use {RngCore, SeedableRng}; use super::ChaChaRng; #[test] fn test_chacha_construction() { let seed = [0,0,0,0,0,0,0,0, 1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 3,0,0,0,0,0,0,0]; let mut rng1 = ChaChaRng::from_seed(seed); assert_eq!(rng1.next_u32(), 137206642); let mut rng2 = ChaChaRng::from_rng(rng1).unwrap(); assert_eq!(rng2.next_u32(), 1325750369); } #[test] fn test_chacha_true_values_a() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8, 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815, 0x69b687c3, 0x8665eeb2]; assert_eq!(results, expected); for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612, 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51, 0x1f0ae1ac, 0x6f4d794b]; assert_eq!(results, expected); } #[test] fn test_chacha_true_values_b() { let seed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; let mut rng = ChaChaRng::from_seed(seed); for _ in 0..16 { rng.next_u32(); } let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8, 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8, 0xebdd4aa6, 0xa0136c00]; assert_eq!(results, expected); } #[test] fn test_chacha_true_values_c() { let seed = [0, 0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; let expected = [0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1, 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5, 0x87f47473, 0x96f0992e]; let mut results = [0u32; 16]; let mut rng1 = ChaChaRng::from_seed(seed); for _ in 0..32 { rng1.next_u32(); } for i in results.iter_mut() { *i = rng1.next_u32(); } assert_eq!(results, expected); let mut rng2 = ChaChaRng::from_seed(seed); rng2.set_counter(2, 0); for i in results.iter_mut() { *i = rng2.next_u32(); } assert_eq!(results, expected); } #[test] fn test_chacha_multiple_blocks() { let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); for _ in 0..16 { rng.next_u32(); } } let expected = [0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186, 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc, 0x5f1c86d9, 0xc1f8e7f4]; assert_eq!(results, expected); } #[test]
#[test] fn test_chacha_set_counter() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); rng.set_counter(0, 2u64 << 56); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72, 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8, 0x398a19fa, 0x6ded1b53]; assert_eq!(results, expected); } #[test] fn test_chacha_set_rounds() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); rng.set_rounds(8); let mut results = [0u32; 16]; for i in results.iter_mut() { *i = rng.next_u32(); } let expected = [0x2fef003e, 0xd6405f89, 0xe8b85b7f, 0xa1a5091f, 0xc30e842c, 0x3b7f9ace, 0x88e11b18, 0x1e1a71ef, 0x72e14c98, 0x416f21b9, 0x6753449f, 0x19566d45, 0xa3424a31, 0x01b086da, 0xb8fd7b38, 0x42fe0c0e]; assert_eq!(results, expected); } #[test] fn test_chacha_clone() { let seed = [0,0,0,0, 1,0,0,0, 2,0,0,0, 3,0,0,0, 4,0,0,0, 5,0,0,0, 6,0,0,0, 7,0,0,0]; let mut rng = ChaChaRng::from_seed(seed); let mut clone = rng.clone(); for _ in 0..16 { assert_eq!(rng.next_u64(), clone.next_u64()); } } }
fn test_chacha_true_bytes() { let seed = [0u8; 32]; let mut rng = ChaChaRng::from_seed(seed); let mut results = [0u8; 32]; rng.fill_bytes(&mut results); let expected = [118, 184, 224, 173, 160, 241, 61, 144, 64, 93, 106, 229, 83, 134, 189, 40, 189, 210, 25, 184, 160, 141, 237, 26, 168, 54, 239, 204, 139, 119, 13, 199]; assert_eq!(results, expected); }
function_block-full_function
[ { "content": "/// Implement `fill_bytes` via `next_u64`, little-endian order.\n\npub fn fill_bytes_via_u64<R: RngCore + ?Sized>(rng: &mut R, dest: &mut [u8]) {\n\n fill_bytes_via!(rng, next_u64, 8, dest)\n\n}\n\n\n\nmacro_rules! impl_uint_from_fill {\n\n ($rng:expr, $ty:ty, $N:expr) => ({\n\n debug...
Rust
src/main.rs
harksin/noria-mysql
7ece4f4107d453c922b452cbf0d824be7625a8e4
#![feature(box_syntax, box_patterns)] #![feature(nll)] #![feature(try_from)] extern crate arccstr; extern crate chrono; #[macro_use] extern crate clap; extern crate noria; extern crate msql_srv; extern crate nom_sql; #[macro_use] extern crate lazy_static; #[macro_use] extern crate slog; extern crate slog_term; extern crate regex; mod convert; mod rewrite; mod schema; mod backend; mod utils; use msql_srv::MysqlIntermediary; use nom_sql::SelectStatement; use std::collections::HashMap; use std::io::{self, BufReader, BufWriter}; use std::net; use std::sync::atomic::AtomicUsize; use std::sync::{Arc, RwLock}; use std::thread; use schema::Schema; use backend::NoriaBackend; pub fn logger_pls() -> slog::Logger { use slog::Drain; use slog::Logger; use slog_term::term_full; use std::sync::Mutex; Logger::root(Mutex::new(term_full()).fuse(), o!()) } fn main() { use clap::{App, Arg}; let matches = App::new("distributary-mysql") .version("0.0.1") .about("MySQL shim for Noria.") .arg( Arg::with_name("deployment") .long("deployment") .takes_value(true) .required(true) .help("Noria deployment ID to attach to."), ).arg( Arg::with_name("zk_addr") .long("zookeeper-address") .short("z") .default_value("127.0.0.1:2181") .help("IP:PORT for Zookeeper."), ).arg( Arg::with_name("port") .long("port") .short("p") .default_value("3306") .takes_value(true) .help("Port to listen on."), ).arg( Arg::with_name("slowlog") .long("log-slow") .help("Log slow queries (> 5ms)"), ).arg( Arg::with_name("no-static-responses") .long("no-static-responses") .takes_value(false) .help("Disable checking for queries requiring static responses. Improves latency."), ).arg( Arg::with_name("no-sanitize") .long("no-sanitize") .takes_value(false) .help("Disable query sanitization. Improves latency."), ).arg(Arg::with_name("verbose").long("verbose").short("v")) .get_matches(); let deployment = matches.value_of("deployment").unwrap().to_owned(); let port = value_t_or_exit!(matches, "port", u16); let slowlog = matches.is_present("slowlog"); let zk_addr = matches.value_of("zk_addr").unwrap().to_owned(); let sanitize = !matches.is_present("no-sanitize"); let static_responses = !matches.is_present("no-static-responses"); let listener = net::TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap(); let log = logger_pls(); info!(log, "listening on port {}", port); let query_counter = Arc::new(AtomicUsize::new(0)); let schemas: Arc<RwLock<HashMap<String, Schema>>> = Arc::default(); let auto_increments: Arc<RwLock<HashMap<String, AtomicUsize>>> = Arc::default(); let query_cache: Arc<RwLock<HashMap<SelectStatement, String>>> = Arc::default(); let mut threads = Vec::new(); let mut i = 0; while let Ok((s, _)) = listener.accept() { s.set_nodelay(true).unwrap(); let builder = thread::Builder::new().name(format!("handler{}", i)); let (schemas, auto_increments, query_cache, query_counter, log) = ( schemas.clone(), auto_increments.clone(), query_cache.clone(), query_counter.clone(), log.clone(), ); let zk_addr = zk_addr.clone(); let deployment = deployment.clone(); let jh = builder .spawn(move || { let b = NoriaBackend::new( &zk_addr, &deployment, schemas, auto_increments, query_cache, query_counter, slowlog, static_responses, sanitize, log, ); let rs = s.try_clone().unwrap(); if let Err(e) = MysqlIntermediary::run_on(b, BufReader::new(rs), BufWriter::new(s)) { match e.kind() { io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe => {} _ => { panic!("{:?}", e); } } } }).unwrap(); threads.push(jh); i += 1; } for t in threads.drain(..) { t.join() .map_err(|e| e.downcast::<io::Error>().unwrap()) .unwrap(); } }
#![feature(box_syntax, box_patterns)] #![feature(nll)] #![feature(try_from)] extern crate arccstr; extern crate chrono; #[macro_use] extern crate clap; extern crate noria; extern crate msql_srv; extern crate nom_sql; #[macro_use] extern crate lazy_static; #[macro_use] extern crate slog; extern crate slog_term; extern crate regex; mod convert; mod rewrite; mod schema; mod backend; mod utils; use msql_srv::MysqlIntermediary; use nom_sql::SelectStatement; use std::collections::HashMap; use std::io::{self, BufReader, BufWriter}; use std::net; use std::sync::atomic::AtomicUsize; use std::sync::{Arc, RwLock}; use std::thread; use schema::Schema; use backend::NoriaBackend; pub fn logger_pls() -> slog::Logger { use slog::Drain; use slog::Logger; use slog_term::term_full; use std::sync::Mutex; Logger::root(Mutex::new(term_full()).fuse(), o!()) } fn main() { use clap::{App, Arg}; let matches = App::new("distributary-mysql") .version("0.0.1") .about("MySQL shim for Noria.") .arg( Arg::with_name("deployment") .long("deployment") .takes_value(true) .required(true) .help("Noria deployment ID to attach to."), ).arg( Arg::with_name("zk_addr") .long("zookeeper-address") .short("z") .default_value("127.0.0.1:2181") .help("IP:PORT for Zookeeper."), ).arg( Arg::with_name("port") .long("port") .short("p") .default_value("3306") .takes_value(true) .help("Port to listen on."), ).arg( Arg::with_name("slowlog") .long("log-slow") .help("Log slow queries (> 5ms)"), ).arg( Arg::with_name("no-static-responses") .long("no-static-responses") .takes_value(false) .help("Disable checking for queries requiring static responses. Improves latency."), ).arg( Arg::with_name("no-sanitize") .long("no-sanitize") .takes_value(false) .help("Disable query sanitization. Improves latency."), ).arg(Arg::with_name("verbose").long("verbose").short("v")) .get_matches(); let deployment = matches.value_of("deployment").unwrap().to_owned(); let port = value_t_or_exit!(matches, "port", u16); let slowlog = matches.is_present("slowlog"); let zk_addr = matches.value_of("zk_addr").unwrap().to_owned(); let sanitize = !matches.is_present("no-sanitiz
e"); let static_responses = !matches.is_present("no-static-responses"); let listener = net::TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap(); let log = logger_pls(); info!(log, "listening on port {}", port); let query_counter = Arc::new(AtomicUsize::new(0)); let schemas: Arc<RwLock<HashMap<String, Schema>>> = Arc::default(); let auto_increments: Arc<RwLock<HashMap<String, AtomicUsize>>> = Arc::default(); let query_cache: Arc<RwLock<HashMap<SelectStatement, String>>> = Arc::default(); let mut threads = Vec::new(); let mut i = 0; while let Ok((s, _)) = listener.accept() { s.set_nodelay(true).unwrap(); let builder = thread::Builder::new().name(format!("handler{}", i)); let (schemas, auto_increments, query_cache, query_counter, log) = ( schemas.clone(), auto_increments.clone(), query_cache.clone(), query_counter.clone(), log.clone(), ); let zk_addr = zk_addr.clone(); let deployment = deployment.clone(); let jh = builder .spawn(move || { let b = NoriaBackend::new( &zk_addr, &deployment, schemas, auto_increments, query_cache, query_counter, slowlog, static_responses, sanitize, log, ); let rs = s.try_clone().unwrap(); if let Err(e) = MysqlIntermediary::run_on(b, BufReader::new(rs), BufWriter::new(s)) { match e.kind() { io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe => {} _ => { panic!("{:?}", e); } } } }).unwrap(); threads.push(jh); i += 1; } for t in threads.drain(..) { t.join() .map_err(|e| e.downcast::<io::Error>().unwrap()) .unwrap(); } }
function_block-function_prefixed
[ { "content": "fn collapse_where_in_recursive(\n\n leftmost_param_index: &mut usize,\n\n expr: &mut ConditionExpression,\n\n rewrite_literals: bool,\n\n) -> Option<(usize, Vec<Literal>)> {\n\n match *expr {\n\n ConditionExpression::Base(ConditionBase::Literal(Literal::Placeholder)) => {\n\n ...
Rust
crates/tako/benches/benchmarks/worker.rs
User3574/hyperqueue
d4dea5a805925cb624eb81da65840d5a8226d4a9
use std::time::Duration; use criterion::measurement::WallTime; use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion}; use tako::common::index::{AsIdVec, ItemId}; use tako::common::resources::descriptor::GenericResourceKindIndices; use tako::common::resources::map::ResourceMap; use tako::common::resources::{ CpuRequest, GenericResourceDescriptor, GenericResourceDescriptorKind, GenericResourceRequest, ResourceDescriptor, ResourceRequest, TimeRequest, }; use tokio::sync::mpsc::unbounded_channel; use tokio::sync::oneshot::Receiver; use tako::messages::worker::ComputeTaskMsg; use tako::worker::launcher::{TaskLaunchData, TaskLauncher}; use tako::worker::rqueue::ResourceWaitQueue; use tako::worker::state::{TaskMap, WorkerState, WorkerStateRef}; use tako::worker::task::Task; use tako::worker::taskenv::{StopReason, TaskResult}; use tako::TaskId; use crate::create_worker; struct BenchmarkTaskLauncher; impl TaskLauncher for BenchmarkTaskLauncher { fn build_task( &self, _state: &WorkerState, _task_id: TaskId, _stop_receiver: Receiver<StopReason>, ) -> tako::Result<TaskLaunchData> { Ok(TaskLaunchData::from_future(Box::pin(async move { Ok(TaskResult::Finished) }))) } } fn create_worker_state() -> WorkerStateRef { let worker = create_worker(1); let (tx, _) = unbounded_channel(); let (tx2, _) = unbounded_channel(); WorkerStateRef::new( worker.id, worker.configuration, None, tx, tx2, Default::default(), Default::default(), Box::new(BenchmarkTaskLauncher), ) } fn create_worker_task(id: u64) -> Task { Task::new(ComputeTaskMsg { id: TaskId::new(id as <TaskId as ItemId>::IdType), instance_id: Default::default(), dep_info: vec![], user_priority: 0, scheduler_priority: 0, resources: Default::default(), time_limit: None, n_outputs: 0, body: vec![], }) } macro_rules! measure_time { ($body: block) => {{ let start = ::std::time::Instant::now(); $body start.elapsed() }} } fn bench_add_task(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("add task", task_count), &task_count, |b, &task_count| { b.iter_custom(|iters| { let mut total = Duration::new(0, 0); for _ in 0..iters { let state = create_worker_state(); let mut state = state.get_mut(); for id in 0..task_count { state.add_task(create_worker_task(id)); } let task = create_worker_task(task_count); let duration = measure_time!({ state.add_task(task); }); total += duration; } total }); }, ); } } fn bench_add_tasks(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("add tasks", task_count), &task_count, |b, &task_count| { b.iter_batched( || { let state = create_worker_state(); let tasks: Vec<_> = (0..task_count).map(|id| create_worker_task(id)).collect(); (state, tasks) }, |(state, tasks)| { let mut state = state.get_mut(); for task in tasks { state.add_task(task); } }, BatchSize::SmallInput, ); }, ); } } fn bench_cancel_waiting_task(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("cancel waiting task", task_count), &task_count, |b, &task_count| { b.iter_batched_ref( || { let state = create_worker_state(); { let mut state = state.get_mut(); for id in 0..task_count { state.add_task(create_worker_task(id)); } } (state, TaskId::new(0)) }, |(state, task_id)| { let mut state = state.get_mut(); state.cancel_task(*task_id); }, BatchSize::SmallInput, ); }, ); } } fn create_resource_queue(num_cpus: u32) -> ResourceWaitQueue { ResourceWaitQueue::new( &ResourceDescriptor { cpus: vec![(0..num_cpus).collect::<Vec<_>>().to_ids()], generic: vec![GenericResourceDescriptor { name: "GPU".to_string(), kind: GenericResourceDescriptorKind::Indices(GenericResourceKindIndices { start: 0.into(), end: 8.into(), }), }], }, &ResourceMap::from_vec(vec!["GPU".to_string()]), ) } fn bench_resource_queue_add_task(c: &mut BenchmarkGroup<WallTime>) { c.bench_function("add task to resource queue", |b| { b.iter_batched_ref( || (create_resource_queue(64), create_worker_task(0)), |(queue, task)| queue.add_task(task), BatchSize::SmallInput, ); }); } fn bench_resource_queue_release_allocation(c: &mut BenchmarkGroup<WallTime>) { c.bench_function("release allocation from resource queue", |b| { b.iter_batched_ref( || { let mut queue = create_resource_queue(64); let mut task = create_worker_task(0); task.resources = ResourceRequest::new( CpuRequest::Compact(64), TimeRequest::new(0, 0), vec![GenericResourceRequest { resource: 0.into(), amount: 2, }] .into(), ); queue.add_task(&task); let mut map = TaskMap::default(); map.insert(task); let mut started = queue.try_start_tasks(&map, None); (queue, Some(started.pop().unwrap().1)) }, |(queue, allocation)| queue.release_allocation(allocation.take().unwrap()), BatchSize::SmallInput, ); }); } fn bench_resource_queue_start_tasks(c: &mut BenchmarkGroup<WallTime>) { for task_count in [1, 10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("start tasks in resource queue", task_count), &task_count, |b, &task_count| { b.iter_batched_ref( || { let mut queue = create_resource_queue(64); let mut map = TaskMap::default(); for id in 0..task_count { let mut task = create_worker_task(id); task.resources = ResourceRequest::new( CpuRequest::Compact(64), TimeRequest::new(0, 0), vec![GenericResourceRequest { resource: 0.into(), amount: 2, }] .into(), ); queue.add_task(&task); map.insert(task); } (queue, map) }, |(queue, map)| queue.try_start_tasks(&map, None), BatchSize::SmallInput, ); }, ); } } pub fn benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("worker"); bench_add_task(&mut group); bench_add_tasks(&mut group); bench_cancel_waiting_task(&mut group); bench_resource_queue_add_task(&mut group); bench_resource_queue_release_allocation(&mut group); bench_resource_queue_start_tasks(&mut group); }
use std::time::Duration; use criterion::measurement::WallTime; use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion}; use tako::common::index::{AsIdVec, ItemId}; use tako::common::resources::descriptor::GenericResourceKindIndices; use tako::common::resources::map::ResourceMap; use tako::common::resources::{ CpuRequest, GenericResourceDescriptor, GenericResourceDescriptorKind, GenericResourceRequest, ResourceDescriptor, ResourceRequest, TimeRequest, }; use tokio::sync::mpsc::unbounded_channel; use tokio::sync::oneshot::Receiver; use tako::messages::worker::ComputeTaskMsg; use tako::worker::launcher::{TaskLaunchData, TaskLauncher}; use tako::worker::rqueue::ResourceWaitQueue; use tako::worker::state::{TaskMap, WorkerState, WorkerStateRef}; use tako::worker::task::Task; use tako::worker::taskenv::{StopReason, TaskResult}; use tako::TaskId; use crate::create_worker; struct BenchmarkTaskLauncher; impl TaskLauncher for BenchmarkTaskLauncher { fn build_task( &self, _state: &WorkerState, _task_id: TaskId, _stop_receiver: Receiver<StopReason>, ) -> tako::Result<TaskLaunchData> { Ok(TaskLaunchData::from_future(Box::pin(async move { Ok(TaskResult::Finished) }))) } } fn create_worker_state() -> WorkerStateRef { let worker = create_worker(1); let (tx, _) = unbounded_channel(); let (tx2, _) = unbounded_channel(); WorkerStateRef::new( worker.id, worker.configuration, None, tx, tx2, Default::default(), Default::default(), Box::new(BenchmarkTaskLauncher), ) } fn create_worker_task(id: u64) -> Task { Task::new(ComputeTaskMsg { id: TaskId::new(id as <TaskId as ItemId>::IdType), instance_id: Default::default(), dep_info: vec![], user_priority: 0, scheduler_priority: 0, resources: Default::default(), time_limit: None, n_outputs: 0, body: vec![], }) } macro_rules! measure_time { ($body: block) => {{ let start = ::std::time::Instant::now(); $body start.elapsed() }} } fn bench_add_task(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("add task", task_count), &task_count, |b, &task_count| { b.iter_custom(|iters| { let mut total = Duration::new(0, 0); for _ in 0..iters { let state = create_worker_state(); let mut state = state.get_mut(); for id in 0..task_count { state.add_task(create_worker_task(id));
}, &ResourceMap::from_vec(vec!["GPU".to_string()]), ) } fn bench_resource_queue_add_task(c: &mut BenchmarkGroup<WallTime>) { c.bench_function("add task to resource queue", |b| { b.iter_batched_ref( || (create_resource_queue(64), create_worker_task(0)), |(queue, task)| queue.add_task(task), BatchSize::SmallInput, ); }); } fn bench_resource_queue_release_allocation(c: &mut BenchmarkGroup<WallTime>) { c.bench_function("release allocation from resource queue", |b| { b.iter_batched_ref( || { let mut queue = create_resource_queue(64); let mut task = create_worker_task(0); task.resources = ResourceRequest::new( CpuRequest::Compact(64), TimeRequest::new(0, 0), vec![GenericResourceRequest { resource: 0.into(), amount: 2, }] .into(), ); queue.add_task(&task); let mut map = TaskMap::default(); map.insert(task); let mut started = queue.try_start_tasks(&map, None); (queue, Some(started.pop().unwrap().1)) }, |(queue, allocation)| queue.release_allocation(allocation.take().unwrap()), BatchSize::SmallInput, ); }); } fn bench_resource_queue_start_tasks(c: &mut BenchmarkGroup<WallTime>) { for task_count in [1, 10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("start tasks in resource queue", task_count), &task_count, |b, &task_count| { b.iter_batched_ref( || { let mut queue = create_resource_queue(64); let mut map = TaskMap::default(); for id in 0..task_count { let mut task = create_worker_task(id); task.resources = ResourceRequest::new( CpuRequest::Compact(64), TimeRequest::new(0, 0), vec![GenericResourceRequest { resource: 0.into(), amount: 2, }] .into(), ); queue.add_task(&task); map.insert(task); } (queue, map) }, |(queue, map)| queue.try_start_tasks(&map, None), BatchSize::SmallInput, ); }, ); } } pub fn benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("worker"); bench_add_task(&mut group); bench_add_tasks(&mut group); bench_cancel_waiting_task(&mut group); bench_resource_queue_add_task(&mut group); bench_resource_queue_release_allocation(&mut group); bench_resource_queue_start_tasks(&mut group); }
} let task = create_worker_task(task_count); let duration = measure_time!({ state.add_task(task); }); total += duration; } total }); }, ); } } fn bench_add_tasks(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("add tasks", task_count), &task_count, |b, &task_count| { b.iter_batched( || { let state = create_worker_state(); let tasks: Vec<_> = (0..task_count).map(|id| create_worker_task(id)).collect(); (state, tasks) }, |(state, tasks)| { let mut state = state.get_mut(); for task in tasks { state.add_task(task); } }, BatchSize::SmallInput, ); }, ); } } fn bench_cancel_waiting_task(c: &mut BenchmarkGroup<WallTime>) { for task_count in [10, 1_000, 100_000] { c.bench_with_input( BenchmarkId::new("cancel waiting task", task_count), &task_count, |b, &task_count| { b.iter_batched_ref( || { let state = create_worker_state(); { let mut state = state.get_mut(); for id in 0..task_count { state.add_task(create_worker_task(id)); } } (state, TaskId::new(0)) }, |(state, task_id)| { let mut state = state.get_mut(); state.cancel_task(*task_id); }, BatchSize::SmallInput, ); }, ); } } fn create_resource_queue(num_cpus: u32) -> ResourceWaitQueue { ResourceWaitQueue::new( &ResourceDescriptor { cpus: vec![(0..num_cpus).collect::<Vec<_>>().to_ids()], generic: vec![GenericResourceDescriptor { name: "GPU".to_string(), kind: GenericResourceDescriptorKind::Indices(GenericResourceKindIndices { start: 0.into(), end: 8.into(), }), }],
random
[ { "content": "pub fn task_transfer_cost(taskmap: &TaskMap, task: &Task, worker_id: WorkerId) -> u64 {\n\n // TODO: For large number of inputs, only sample inputs\n\n task.inputs\n\n .iter()\n\n .take(512)\n\n .map(|ti| {\n\n let t = taskmap.get_task(ti.task());\n\n ...
Rust
src/ops/list.rs
wellinthatcase/fast-redis
b8b806989290d7c658884379975f59bfecaa84a5
use crate::*; #[pymethods] impl RedisClient { #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn rpush(&mut self, key: String, elements: Vec<&PyAny>, no_overwrite: Option<&PyDict>) -> PyResult<usize> { let command = nx_x_decider("RPUSH", "X", no_overwrite); let mut args = construct_vector(elements.len() + 1, Cow::from(&elements))?; args.insert(0, key); Ok(route_command(self, &command, Some(args))?) } #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn lpush(&mut self, key: String, elements: Vec<&PyAny>, no_overwrite: Option<&PyDict>) -> PyResult<usize> { let command = nx_x_decider("LPUSH", "X", no_overwrite); let mut args = construct_vector(elements.len() + 1, Cow::from(&elements))?; args.insert(0, key); Ok(route_command(self, &command, Some(args))?) } #[text_signature = "($self, key, index, /)"] pub fn lindex(&mut self, key: &str, index: isize) -> PyResult<String> { let ind = index.to_string(); Ok(route_command(self, "LINDEX", Some(&[key, &ind]))?) } #[text_signature = "($self, key, element, /)"] pub fn linsert(&mut self, key: &str, element: &str) -> PyResult<isize> { Ok(route_command(self, "LINSERT", Some(&[key, element]))?) } #[text_signature = "($self, key, /)"] pub fn llen(&mut self, key: &str) -> PyResult<isize> { Ok(route_command(self, "LLEN", Some(key))?) } #[text_signature = "($self, key, /)"] pub fn lpop(&mut self, key: &str) -> PyResult<String> { Ok(route_command(self, "LPOP", Some(key))?) } #[text_signature = "($self, key, index, element, /)"] pub fn lset(&mut self, key: &str, index: usize, element: &PyAny) -> PyResult<String> { let ind = index.to_string(); let elem = element.to_string(); Ok(route_command(self, "LSET", Some(&[key, &ind, &elem]))?) } #[text_signature = "($self, key, beginning, end, /)"] pub fn lrange(&mut self, key: &str, beginning: usize, end: usize) -> PyResult<Vec<String>> { let start = beginning.to_string(); let stop = end.to_string(); Ok(route_command(self, "LRANGE", Some(&[key, &start, &stop]))?) } #[args(elems="*")] #[text_signature = "($self, key, amt, elems, /)"] pub fn lrem(&mut self, key: String, amt: usize, elems: Vec<&PyAny>) -> PyResult<usize> { let mut arguments = construct_vector(elems.len() + 2, Cow::from(&elems))?; arguments.insert(0, amt.to_string()); arguments.insert(0, key); Ok(route_command(self, "LREM", Some(arguments))?) } #[text_signature = "($self, key, beginning, end, /)"] pub fn ltrim(&mut self, key: &str, beginning: isize, end: isize) -> PyResult<usize> { let stop = end.to_string(); let start = beginning.to_string(); Ok(route_command(self, "LTRIM", Some(&[key, &start, &stop]))?) } #[text_signature = "($self, key, /)"] pub fn rpop(&mut self, key: &str) -> PyResult<String> { Ok(route_command(self, "RPOP", Some(key))?) } #[text_signature = "($self, key, /)"] pub fn lelements(&mut self, key: &str) -> PyResult<Vec<String>> { let stop = self.llen(key)?.to_string(); Ok(route_command(self, "LRANGE", Some(&[key, "0", &stop]))?) } #[text_signature = "($self, source, destination, /)"] pub fn rpoplpush(&mut self, source: &str, destination: &str) -> PyResult<String> { Ok(route_command(self, "RPOPLPUSH", Some(&[source, destination]))?) } }
use crate::*; #[pymethods] impl RedisClient { #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn rpush(&mut self, key: String, elements: Vec<&PyAny>, no_overwrite: Option<&PyDict>) -> PyResult<usize> { let command = nx_x_decider("RPUSH", "X", no_overwrite); let mut args = construct_vector(elements.len() + 1, Cow::from(&elements))?; args.insert(0, key); Ok(route_command(self, &command, Some(args))?) } #[args(elements="*", no_overwrite="**")] #[text_signature = "($self, key, elements, *, no_overwrite)"] pub fn lpush(&mut self, key: String, elements: Vec<&PyAny>, no_overwrite: Option<&PyDict>) -> PyResult<usize> { let command = nx_x_decider("LPUSH", "
#[text_signature = "($self, key, index, /)"] pub fn lindex(&mut self, key: &str, index: isize) -> PyResult<String> { let ind = index.to_string(); Ok(route_command(self, "LINDEX", Some(&[key, &ind]))?) } #[text_signature = "($self, key, element, /)"] pub fn linsert(&mut self, key: &str, element: &str) -> PyResult<isize> { Ok(route_command(self, "LINSERT", Some(&[key, element]))?) } #[text_signature = "($self, key, /)"] pub fn llen(&mut self, key: &str) -> PyResult<isize> { Ok(route_command(self, "LLEN", Some(key))?) } #[text_signature = "($self, key, /)"] pub fn lpop(&mut self, key: &str) -> PyResult<String> { Ok(route_command(self, "LPOP", Some(key))?) } #[text_signature = "($self, key, index, element, /)"] pub fn lset(&mut self, key: &str, index: usize, element: &PyAny) -> PyResult<String> { let ind = index.to_string(); let elem = element.to_string(); Ok(route_command(self, "LSET", Some(&[key, &ind, &elem]))?) } #[text_signature = "($self, key, beginning, end, /)"] pub fn lrange(&mut self, key: &str, beginning: usize, end: usize) -> PyResult<Vec<String>> { let start = beginning.to_string(); let stop = end.to_string(); Ok(route_command(self, "LRANGE", Some(&[key, &start, &stop]))?) } #[args(elems="*")] #[text_signature = "($self, key, amt, elems, /)"] pub fn lrem(&mut self, key: String, amt: usize, elems: Vec<&PyAny>) -> PyResult<usize> { let mut arguments = construct_vector(elems.len() + 2, Cow::from(&elems))?; arguments.insert(0, amt.to_string()); arguments.insert(0, key); Ok(route_command(self, "LREM", Some(arguments))?) } #[text_signature = "($self, key, beginning, end, /)"] pub fn ltrim(&mut self, key: &str, beginning: isize, end: isize) -> PyResult<usize> { let stop = end.to_string(); let start = beginning.to_string(); Ok(route_command(self, "LTRIM", Some(&[key, &start, &stop]))?) } #[text_signature = "($self, key, /)"] pub fn rpop(&mut self, key: &str) -> PyResult<String> { Ok(route_command(self, "RPOP", Some(key))?) } #[text_signature = "($self, key, /)"] pub fn lelements(&mut self, key: &str) -> PyResult<Vec<String>> { let stop = self.llen(key)?.to_string(); Ok(route_command(self, "LRANGE", Some(&[key, "0", &stop]))?) } #[text_signature = "($self, source, destination, /)"] pub fn rpoplpush(&mut self, source: &str, destination: &str) -> PyResult<String> { Ok(route_command(self, "RPOPLPUSH", Some(&[source, destination]))?) } }
X", no_overwrite); let mut args = construct_vector(elements.len() + 1, Cow::from(&elements))?; args.insert(0, key); Ok(route_command(self, &command, Some(args))?) }
function_block-function_prefixed
[ { "content": "#[inline]\n\nfn route_command<Args, ReturnType>(inst: &mut RedisClient, cmd: &str, args: Option<Args>) -> PyResult<ReturnType>\n\nwhere \n\n Args: ToRedisArgs,\n\n ReturnType: FromRedisValue\n\n{\n\n let mut call = redis::cmd(cmd);\n\n call.arg(args);\n\n\n\n match call.query(&mut i...
Rust
actions/balance-notification-registration/src/lib.rs
HugoByte/aurras
fcc03684f4ed56ce949c5a1db8764508e0feb3f9
extern crate serde_json; use actions_common::Context; use chesterfield::sync::{Client, Database}; use serde_derive::{Deserialize, Serialize}; use serde_json::{Error, Value}; mod types; use std::collections::HashMap; use types::{Address, Response, Topic}; #[cfg(test)] use actions_common::Config; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] struct Input { __ow_method: String, #[serde(default = "empty_string")] __ow_query: String, #[serde(default = "empty_string")] address: String, balance_filter_db: String, db_name: String, db_url: String, event_registration_db: String, #[serde(default = "empty_string")] token: String, #[serde(default = "empty_string")] topic: String, } fn empty_string() -> String { String::new() } struct Action { params: Input, context: Option<Context>, } impl Action { pub fn new(params: Input) -> Self { Action { params, context: None, } } #[cfg(test)] pub fn init(&mut self, config: &Config) { let db = self.connect_db(&self.params.db_url, &self.params.db_name); self.context = Some(Context::new(db, Some(config))); } #[cfg(not(test))] pub fn init(&mut self) { let db = self.connect_db(&self.params.db_url, &self.params.db_name); self.context = Some(Context::new(db, None)); } fn connect_db(&self, db_url: &String, db_name: &String) -> Database { let client = Client::new(db_url).unwrap(); let db = client.database(db_name).unwrap(); if !db.exists().unwrap() { db.create().unwrap(); } db } pub fn get_context(&mut self) -> &Context { self.context.as_mut().expect("Action not Initialized!") } pub fn method(&self) -> String { self.params.__ow_method.clone() } pub fn get_event_sources(&self) -> Result<Value, Error> { let db = self.connect_db(&self.params.db_url, &self.params.event_registration_db); let context = Context::new(db, None); let list: Response = serde_json::from_value( context.get_list(&self.params.db_url, &self.params.event_registration_db)?, )?; Ok(serde_json::json!({ "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": list.rows })) } pub fn get_address(&mut self, id: &String) -> Result<Value, Error> { self.get_context().get_document(id) } pub fn add_address(&self, token: &str, topic: &str, address: &str) -> Result<String, Error> { let db = self.connect_db(&self.params.db_url, &self.params.balance_filter_db); let context = Context::new(db, None); if context.get_document(topic).is_err() { context.insert_document( &serde_json::json!({ "filters": {} }), Some(topic.to_string()), )?; } let mut doc: Topic = serde_json::from_value(context.get_document(topic)?)?; doc.filters.insert( address.to_string(), Address { token: token.to_string(), }, ); context.update_document(&topic, &doc.rev, &serde_json::to_value(doc.clone())?) } } pub fn main(args: Value) -> Result<Value, Error> { let input = serde_json::from_value::<Input>(args)?; let mut action = Action::new(input); #[cfg(not(test))] action.init(); match action.method().as_ref() { "post" => { let id = action.add_address( &action.params.token, &action.params.topic, &action.params.address, )?; return Ok(serde_json::json!({ "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "success": true } })) } "get" => return action.get_event_sources(), method => { return Err(format!("method not supported document {}", method)) .map_err(serde::de::Error::custom) } } } #[cfg(test)] mod tests { use super::*; use actions_common::mock_containers::CouchDB; use tokio; use tokio::time::{sleep, Duration}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Source { name: String, trigger: String, } impl Source { pub fn new(name: String, trigger: String) -> Self { Source { name, trigger } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Row<T> { rows: Vec<View<T>>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct View<T> { doc: T, } #[tokio::test] async fn add_address_pass() { let config = Config::new(); let couchdb = CouchDB::new("admin".to_string(), "password".to_string()) .await .unwrap(); sleep(Duration::from_millis(5000)).await; let url = format!("http://admin:password@localhost:{}", couchdb.port()); let topic = "1234".to_string(); let address = "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(); let token = "1".to_string(); let mut action = Action::new(Input { db_url: url, db_name: "test".to_string(), __ow_method: "post".to_string(), __ow_query: "".to_string(), address: "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(), balance_filter_db: "balance_filter_db".to_string(), event_registration_db: "".to_string(), token: "1".to_string(), topic: "418a8b8c-02b8-11ec-9a03-0242ac130003".to_string(), }); action.init(&config); let db = action.connect_db(&action.params.db_url, &action.params.balance_filter_db); let context = Context::new(db, None); action.add_address(&token, &topic, &address).unwrap(); let doc: Topic = serde_json::from_value(context.get_document(&topic).unwrap()).unwrap(); let mut filters = HashMap::new(); filters.insert( address.clone(), Address { token: "1".to_string(), }, ); let expected = Topic { id: doc.id.clone(), rev: doc.rev.clone(), filters, }; assert_eq!(doc, expected); couchdb.delete().await.expect("Stopping Container Failed"); } #[ignore] #[should_panic] #[tokio::test] async fn get_event_sources_pass() { let config = Config::new(); let couchdb = CouchDB::new("admin".to_string(), "password".to_string()) .await .unwrap(); sleep(Duration::from_millis(5000)).await; let url = format!("http://admin:password@localhost:{}", couchdb.port()); let topic = "1234".to_string(); let address = "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(); let token = "1".to_string(); let mut action = Action::new(Input { db_url: url.clone(), db_name: "test".to_string(), __ow_method: "post".to_string(), __ow_query: "".to_string(), address: "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(), balance_filter_db: "balance_filter_db".to_string(), event_registration_db: "event_registration_db".to_string(), token: "1".to_string(), topic: "418a8b8c-02b8-11ec-9a03-0242ac130003".to_string(), }); action.init(&config); let event_registration_db = action.connect_db(&action.params.db_url, &action.params.event_registration_db); let event_registration_db_context = Context::new(event_registration_db, None); event_registration_db_context .insert_document( &serde_json::json!({ "name": "polkadot", "trigger": "trigger" }), Some("event_id".to_string()), ) .unwrap(); let doc: Source = serde_json::from_value( event_registration_db_context .get_document(&"event_id".to_string()) .unwrap(), ) .unwrap(); let sources: Row<Source> = serde_json::from_value( event_registration_db_context .get_list(&url.clone(), &action.params.event_registration_db) .unwrap(), ) .unwrap(); let expected: View<Source> = View { doc: Source { ..doc }, }; assert_eq!(sources.rows, vec![expected]); couchdb.delete().await.expect("Stopping Container Failed"); } }
extern crate serde_json; use actions_common::Context; use chesterfield::sync::{Client, Database}; use serde_derive::{Deserialize, Serialize}; use serde_json::{Error, Value}; mod types; use std::collections::HashMap; use types::{Address, Response, Topic}; #[cfg(test)] use actions_common::Config; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] struct Input { __ow_method: String, #[serde(default = "empty_string")] __ow_query: String, #[serde(default = "empty_string")] address: String, balance_filter_db: String, db_name: String, db_url: String, event_registration_db: String, #[serde(default = "empty_string")] token: String, #[serde(default = "empty_string")] topic: String, } fn empty_string() -> String { String::new() } struct Action { params: Input, context: Option<Context>, } impl Action { pub fn new(params: Input) -> Self { Action { params, context: None, } } #[cfg(test)] pub fn init(&mut self, config: &Config) { let db = self.connect_db(&self.params.db_url, &self.params.db_name); self.context = Some(Context::new(db, Some(config))); } #[cfg(not(test))] pub fn init(&mut self) { let db = self.connect_db(&self.params.db_url, &self.params.db_name); self.context = Some(Context::new(db, None)); } fn connect_db(&self, db_url: &String, db_name: &String) -> Database { let client = Client::new(db_url).unwrap(); let db = client.database(db_name).unwrap(); if !db.exists().unwrap() { db.create().unwrap(); } db } pub fn get_context(&mut self) -> &Context { self.context.as_mut().expect("Action not Initialized!") } pub fn method(&self) -> String { self.params.__ow_method.clone() } pub fn get_event_sources(&self) -> Result<Value, Error> { let db = self.connect_db(&self.params.db_url, &self.params.event_registration_db); let context = Context::new(db, None); let list: Response = serde_json::from_value( context.get_list(&self.params.db_url, &self.params.event_registration_db)?, )?; Ok(serde_json::json!({ "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": list.rows })) } pub fn get_address(&mut self, id: &String) -> Result<Value, Error> { self.get_context().get_document(id) } pub fn add_address(&self, token: &str, topic: &str, address: &str) -> Result<String, Error> { let db = self.connect_db(&self.params.db_url, &self.params.balance_filter_db); let context = Context::new(db, None); if context.get_document(topic).is_err() { context.insert_document( &serde_json::json!({ "filters": {} }), Some(topic.to_string()), )?; } let mut doc: Topic = serde_json::from_value(context.get_document(topic)?)?; doc.filters.insert( address.to_string(), Address { token: token.to_string(), }, ); context.update_document(&topic, &doc.rev, &serde_json::to_value(doc.clone())?) } } pub fn main(args: Val
#[cfg(test)] mod tests { use super::*; use actions_common::mock_containers::CouchDB; use tokio; use tokio::time::{sleep, Duration}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Source { name: String, trigger: String, } impl Source { pub fn new(name: String, trigger: String) -> Self { Source { name, trigger } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Row<T> { rows: Vec<View<T>>, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct View<T> { doc: T, } #[tokio::test] async fn add_address_pass() { let config = Config::new(); let couchdb = CouchDB::new("admin".to_string(), "password".to_string()) .await .unwrap(); sleep(Duration::from_millis(5000)).await; let url = format!("http://admin:password@localhost:{}", couchdb.port()); let topic = "1234".to_string(); let address = "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(); let token = "1".to_string(); let mut action = Action::new(Input { db_url: url, db_name: "test".to_string(), __ow_method: "post".to_string(), __ow_query: "".to_string(), address: "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(), balance_filter_db: "balance_filter_db".to_string(), event_registration_db: "".to_string(), token: "1".to_string(), topic: "418a8b8c-02b8-11ec-9a03-0242ac130003".to_string(), }); action.init(&config); let db = action.connect_db(&action.params.db_url, &action.params.balance_filter_db); let context = Context::new(db, None); action.add_address(&token, &topic, &address).unwrap(); let doc: Topic = serde_json::from_value(context.get_document(&topic).unwrap()).unwrap(); let mut filters = HashMap::new(); filters.insert( address.clone(), Address { token: "1".to_string(), }, ); let expected = Topic { id: doc.id.clone(), rev: doc.rev.clone(), filters, }; assert_eq!(doc, expected); couchdb.delete().await.expect("Stopping Container Failed"); } #[ignore] #[should_panic] #[tokio::test] async fn get_event_sources_pass() { let config = Config::new(); let couchdb = CouchDB::new("admin".to_string(), "password".to_string()) .await .unwrap(); sleep(Duration::from_millis(5000)).await; let url = format!("http://admin:password@localhost:{}", couchdb.port()); let topic = "1234".to_string(); let address = "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(); let token = "1".to_string(); let mut action = Action::new(Input { db_url: url.clone(), db_name: "test".to_string(), __ow_method: "post".to_string(), __ow_query: "".to_string(), address: "15ss3TDX2NLG31ugk6QN5zHhq2MUfiaPhePSjWwht6Dr9RUw".to_string(), balance_filter_db: "balance_filter_db".to_string(), event_registration_db: "event_registration_db".to_string(), token: "1".to_string(), topic: "418a8b8c-02b8-11ec-9a03-0242ac130003".to_string(), }); action.init(&config); let event_registration_db = action.connect_db(&action.params.db_url, &action.params.event_registration_db); let event_registration_db_context = Context::new(event_registration_db, None); event_registration_db_context .insert_document( &serde_json::json!({ "name": "polkadot", "trigger": "trigger" }), Some("event_id".to_string()), ) .unwrap(); let doc: Source = serde_json::from_value( event_registration_db_context .get_document(&"event_id".to_string()) .unwrap(), ) .unwrap(); let sources: Row<Source> = serde_json::from_value( event_registration_db_context .get_list(&url.clone(), &action.params.event_registration_db) .unwrap(), ) .unwrap(); let expected: View<Source> = View { doc: Source { ..doc }, }; assert_eq!(sources.rows, vec![expected]); couchdb.delete().await.expect("Stopping Container Failed"); } }
ue) -> Result<Value, Error> { let input = serde_json::from_value::<Input>(args)?; let mut action = Action::new(input); #[cfg(not(test))] action.init(); match action.method().as_ref() { "post" => { let id = action.add_address( &action.params.token, &action.params.topic, &action.params.address, )?; return Ok(serde_json::json!({ "statusCode": 200, "headers": { "Content-Type": "application/json" }, "body": { "success": true } })) } "get" => return action.get_event_sources(), method => { return Err(format!("method not supported document {}", method)) .map_err(serde::de::Error::custom) } } }
function_block-function_prefixed
[ { "content": "pub fn main(args: Value) -> Result<Value, Error> {\n\n let input = serde_json::from_value::<Input>(args)?;\n\n let mut action = Action::new(input);\n\n\n\n // TODO: Fix\n\n #[cfg(not(test))]\n\n action.init();\n\n\n\n let filtered_topics = action.filter_topics();\n\n let filte...
Rust
src/async/bufwriter.rs
kimhyunkang/rssh
046275ccdee7962230d5598b175e8f9815db605c
use super::buf::AsyncBuf; use super::DEFAULT_BUFSIZE; use std::{cmp, io}; use std::io::Write; use futures::{Async, Poll}; #[derive(Debug)] pub struct AsyncBufWriter<W: Write> { inner: Option<W>, buf: AsyncBuf, panicked: bool } #[derive(Debug)] pub struct IntoInnerError<W>(W, io::Error); impl <W: Write> AsyncBufWriter<W> { pub fn new(inner: W) -> AsyncBufWriter<W> { AsyncBufWriter::with_capacity(DEFAULT_BUFSIZE, inner) } pub fn with_capacity(capacity: usize, inner: W) -> AsyncBufWriter<W> { AsyncBufWriter { inner: Some(inner), buf: AsyncBuf::with_capacity(capacity), panicked: false } } pub fn nb_into_inner(mut self) -> Poll<W, IntoInnerError<AsyncBufWriter<W>>> { match self.nb_flush() { Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::Ready(())) => Ok(Async::Ready(self.inner.take().unwrap())), Err(e) => Err(IntoInnerError(self, e)) } } #[inline] fn write_inner(&mut self, buf: &[u8]) -> io::Result<usize> { self.panicked = true; let res = self.inner.as_mut().expect("attempted to write after into_inner called").write(buf); self.panicked = false; res } #[inline] fn flush_inner(&mut self) -> io::Result<()> { self.panicked = true; let res = self.inner.as_mut().expect("attempted to flush after into_inner called").flush(); self.panicked = false; res } pub fn nb_flush_buf(&mut self) -> Poll<(), io::Error> { self.panicked = true; let amt = try_nb!(self.inner.as_mut().expect("attempted to flush after into_inner called").write(self.buf.get_ref())); self.panicked = false; self.buf.consume(amt); if self.buf.is_empty() { Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } pub fn nb_flush(&mut self) -> Poll<(), io::Error> { if !self.buf.is_empty() { if let Async::NotReady = try!(self.nb_flush_buf()) { return Ok(Async::NotReady); } } if self.buf.is_empty() { try_nb!(self.flush_inner()); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } pub fn nb_write_exact(&mut self, buf: &[u8]) -> Poll<(), io::Error> { if buf.len() > self.buf.capacity() { if !self.buf.is_empty() { if let Async::NotReady = try!(self.nb_flush_buf()) { return Ok(Async::NotReady); } } match self.write_inner(buf) { Ok(amt) => { self.buf.write_all(&buf[amt ..]); Ok(Async::Ready(())) } Err(e) => match e.kind() { io::ErrorKind::WouldBlock => Ok(Async::NotReady), _ => Err(e) } } } else { if self.buf.try_write_all(buf) { Ok(Async::Ready(())) } else { match try!(self.nb_flush_buf()) { Async::NotReady => Ok(Async::NotReady), Async::Ready(()) => if self.buf.try_write_all(buf) { Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } } } pub fn nb_write<F>(&mut self, len: usize, mut f: F) -> Poll<(), io::Error> where F: FnMut(&mut [u8]) -> () { if !self.buf.try_reserve(len) { match try!(self.nb_flush_buf()) { Async::NotReady => return Ok(Async::NotReady), Async::Ready(()) => self.buf.reserve(len) } } f(&mut self.buf.get_mut()[.. len]); self.buf.fill(len); Ok(Async::Ready(())) } } impl <W: Write> Write for AsyncBufWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if buf.len() > self.buf.reserve_size() { try!(self.nb_flush_buf()); } if self.buf.is_empty() && self.buf.capacity() < buf.len() { self.write_inner(buf) } else { let datasize = cmp::min(self.buf.reserve_size(), buf.len()); self.buf.get_mut()[.. datasize].copy_from_slice(&buf[.. datasize]); self.buf.fill(datasize); Ok(datasize) } } fn flush(&mut self) -> io::Result<()> { while let Async::NotReady = try!(self.nb_flush_buf()) { () } self.flush_inner() } } impl <W: Write> Drop for AsyncBufWriter<W> { fn drop(&mut self) { if self.inner.is_some() && !self.panicked { let _r = self.nb_flush_buf(); } } } #[cfg(test)] mod test { use super::*; use std::io::{Cursor, Write}; use futures::Async; #[test] fn nb_write_exact() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hell").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"o, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"wor").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"ld!").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_flush().expect("error!")); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } #[test] fn nb_write_exact_larger_than_buf() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hello, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"world!").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_flush().expect("error!")); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } #[test] fn nb_write_exact_then_flush() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hello, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"world!").expect("error!")); bufwriter.flush().expect("error!"); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } #[test] fn nb_write_then_flush() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write(7, |buf| buf.copy_from_slice(b"Hello, ")).expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write(6, |buf| buf.copy_from_slice(b"world!")).expect("error!")); bufwriter.flush().expect("error!"); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } }
use super::buf::AsyncBuf; use super::DEFAULT_BUFSIZE; use std::{cmp, io}; use std::io::Write; use futures::{Async, Poll}; #[derive(Debug)] pub struct AsyncBufWriter<W: Write> { inner: Option<W>, buf: AsyncBuf, panicked: bool } #[derive(Debug)] pub struct IntoInnerError<W>(W, io::Error); impl <W: Write> AsyncBufWriter<W> { pub fn new(inner: W) -> AsyncBufWriter<W> { AsyncBufWriter::with_capacity(DEFAULT_BUFSIZE, inner) } pub fn with_capacity(capacity: usize, inner: W) -> AsyncBufWriter<W> { AsyncBufWriter { inner: Some(inner), buf: AsyncBuf::with_capacity(capacity), panicked: false } } pub fn nb_into_inner(mut self) -> Poll<W, IntoInnerError<AsyncBufWriter<W>>> { match self.nb_flush() { Ok(Async::NotReady) => Ok(Async::NotReady), Ok(Async::Ready(())) => Ok(Async::Ready(self.inner.take().unwrap())), Err(e) => Err(IntoInnerError(self, e)) } } #[inline] fn write_inner(&mut self, buf: &[u8]) -> io::Result<usize> { self.panicked = true; let res = self.inner.as_mut().expect("attempted to write after into_inner called").write(buf); self.panicked = false; res } #[inline] fn flush_inner(&mut self) -> io::Result<()> { self.panicked = true; let res = self.inner.as_mut().expect("attempted to flush after into_inner called").flush(); self.panicked = false; res } pub fn nb_flush_buf(&mut self) -> Poll<(), io::Error> { self.panicked = true; let amt = try_nb!(self.inner.as_mut().expect("attempted to flush after into_inner called").write(self.buf.get_ref())); self.panicked = false; self.buf.consume(amt); if self.buf.is_empty() { Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } pub fn nb_flush(&mut self) -> Poll<(), io::Error> { if !self.buf.is_empty() { if let Async::NotReady = try!(self.nb_flush_buf()) { return Ok(Async::NotReady); } } if self.buf.is_empty() { try_nb!(self.flush_inner()); Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } pub fn nb_write_exact(&mut self, buf: &[u8]) -> Poll<(), io::Error> { if buf.len() > self.buf.capacity() { if !self.buf.is_empty() { if let Async::NotReady = try!(self.nb_flush_buf()) { return Ok(Async::NotReady); } } match self.write_inner(buf) { Ok(amt) => { self.buf.write_all(&buf[amt ..]); Ok(Async::Ready(())) } Err(e) => match e.kind() { io::ErrorKind::WouldBlock => Ok(Async::NotReady), _ => Err(e) } } } else { if self.buf.try_write_all(buf) { Ok(Async::Ready(())) } else { match try!(self.nb_flush_buf()) { Async::NotReady => Ok(Async::NotReady), Async::Ready(()) => if self.buf.try_write_all(buf) { Ok(Async::Ready(())) } else { Ok(Async::NotReady) } } } } } pub fn nb_write<F>(&mut self, len: usize, mut f: F) -> Poll<(), io::Error> where F: FnMut(&mut [u8]) -> () { if !self.buf.try_reserve(len) { match try!(self.nb_flush_buf()) { Async::NotReady => return Ok(Async::NotReady), Async::Ready(()) => self.buf.reserve(len) } } f(&mut self.buf.get_mut()[.. len]); self.buf.fill(len); Ok(Async::Ready(())) } } impl <W: Write> Write for AsyncBufWriter<W> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if buf.len() > self.buf.reserve_size() { try!(self.nb_flush_buf()); } if self.buf.is_empty() && self.buf.capacity() < buf.len() { self.write_inner(buf) } else { let datasize = cmp::min(self.buf.reserve_size(), buf.len()); self.buf.get_mut()[.. datasize].copy_from_slice(&buf[.. datasize]); self.buf.fill(datasize); Ok(datasize) } } fn flush(&mut self) -> io::Result<()> { while let Async::NotReady = try!(self.nb_flush_buf()) { () } self.flush_inner() } } impl <W: Write> Drop for AsyncBufWriter<W> { fn drop(&mut self) { if self.inner.is_some() && !self.panicked { let _r = self.nb_flush_buf(); } } } #[cfg(test)] mod test { use super::*; use std::io::{Cursor, Write}; use futures::Async; #[test] fn nb_write_exact() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut buf
#[test] fn nb_write_exact_larger_than_buf() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hello, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"world!").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_flush().expect("error!")); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } #[test] fn nb_write_exact_then_flush() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hello, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"world!").expect("error!")); bufwriter.flush().expect("error!"); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } #[test] fn nb_write_then_flush() { let writer = { let buf = vec![0u8; 16]; let writer = Cursor::new(buf); let mut bufwriter = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write(7, |buf| buf.copy_from_slice(b"Hello, ")).expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write(6, |buf| buf.copy_from_slice(b"world!")).expect("error!")); bufwriter.flush().expect("error!"); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); } }
writer = AsyncBufWriter::with_capacity(4, writer); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"Hell").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"o, ").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"wor").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_write_exact(b"ld!").expect("error!")); assert_eq!(Async::Ready(()), bufwriter.nb_flush().expect("error!")); if let Async::Ready(w) = bufwriter.nb_into_inner().expect("error!") { w } else { panic!("not ready"); } }; let wsize = writer.position() as usize; assert_eq!(b"Hello, world!".len(), wsize); let buf = writer.into_inner(); assert_eq!(b"Hello, world!".as_ref(), &buf[.. wsize]); }
function_block-function_prefixed
[ { "content": "pub fn ntoh(buf: &[u8]) -> u32 {\n\n ((buf[0] as u32) << 24) + ((buf[1] as u32) << 16) + ((buf[2] as u32) << 8) + (buf[3] as u32)\n\n}\n\n\n", "file_path": "src/transport.rs", "rank": 0, "score": 151752.52172682478 }, { "content": "pub fn compute_pad_len<R: Rng>(payload_len:...
Rust
src/tokenizer.rs
crowlKats/rust-urlpattern
1dc0054b693ec652c8e4702a0edffc243ef5cd2c
use derive_more::Display; use crate::error::TokenizerError; use crate::Error; #[derive(Debug, Display, Clone, Eq, PartialEq)] pub enum TokenType { Open, Close, Regexp, Name, Char, EscapedChar, OtherModifier, Asterisk, End, InvalidChar, } #[derive(Debug, Clone)] pub struct Token { pub kind: TokenType, pub index: usize, pub value: String, } #[derive(Debug, Eq, PartialEq)] pub enum TokenizePolicy { Strict, Lenient, } struct Tokenizer { input: Vec<char>, policy: TokenizePolicy, token_list: Vec<Token>, index: usize, next_index: usize, code_point: Option<char>, } impl Tokenizer { #[inline] fn get_next_codepoint(&mut self) { self.code_point = Some(self.input[self.next_index]); self.next_index += 1; } #[inline] fn add_token_with_default_pos_and_len(&mut self, kind: TokenType) { self.add_token_with_default_len(kind, self.next_index, self.index); } #[inline] fn add_token_with_default_len( &mut self, kind: TokenType, next_pos: usize, value_pos: usize, ) { self.add_token(kind, next_pos, value_pos, next_pos - value_pos); } #[inline] fn add_token( &mut self, kind: TokenType, next_pos: usize, value_pos: usize, value_len: usize, ) { let range = value_pos..(value_pos + value_len); let value = self.input[range].iter().collect::<String>(); self.token_list.push(Token { kind, index: self.index, value, }); self.index = next_pos; } fn process_tokenizing_error( &mut self, next_pos: usize, value_pos: usize, error: TokenizerError, ) -> Result<(), Error> { if self.policy == TokenizePolicy::Strict { Err(Error::Tokenizer(error, value_pos)) } else { self.add_token_with_default_len( TokenType::InvalidChar, next_pos, value_pos, ); Ok(()) } } #[inline] fn seek_and_get_next_codepoint(&mut self, index: usize) { self.next_index = index; self.get_next_codepoint(); } } pub fn tokenize( input: &str, policy: TokenizePolicy, ) -> Result<Vec<Token>, Error> { let mut tokenizer = Tokenizer { input: input.chars().collect::<Vec<char>>(), policy, token_list: vec![], index: 0, next_index: 0, code_point: None, }; while tokenizer.index < tokenizer.input.len() { tokenizer.next_index = tokenizer.index; tokenizer.get_next_codepoint(); if tokenizer.code_point == Some('*') { tokenizer.add_token_with_default_pos_and_len(TokenType::Asterisk); continue; } if matches!(tokenizer.code_point, Some('+') | Some('?')) { tokenizer.add_token_with_default_pos_and_len(TokenType::OtherModifier); continue; } if tokenizer.code_point == Some('\\') { if tokenizer.index == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( tokenizer.next_index, tokenizer.index, TokenizerError::IncompleteEscapeCode, )?; continue; } let escaped_index = tokenizer.next_index; tokenizer.get_next_codepoint(); tokenizer.add_token_with_default_len( TokenType::EscapedChar, tokenizer.next_index, escaped_index, ); continue; } if tokenizer.code_point == Some('{') { tokenizer.add_token_with_default_pos_and_len(TokenType::Open); continue; } if tokenizer.code_point == Some('}') { tokenizer.add_token_with_default_pos_and_len(TokenType::Close); continue; } if tokenizer.code_point == Some(':') { let mut name_pos = tokenizer.next_index; let name_start = name_pos; while name_pos < tokenizer.input.len() { tokenizer.seek_and_get_next_codepoint(name_pos); let first_code_point = name_pos == name_start; let valid_codepoint = is_valid_name_codepoint( tokenizer.code_point.unwrap(), first_code_point, ); if !valid_codepoint { break; } name_pos = tokenizer.next_index; } if name_pos <= name_start { tokenizer.process_tokenizing_error( name_start, tokenizer.index, TokenizerError::InvalidName, )?; continue; } tokenizer.add_token_with_default_len( TokenType::Name, name_pos, name_start, ); continue; } if tokenizer.code_point == Some('(') { let mut depth = 1; let mut regexp_pos = tokenizer.next_index; let regexp_start = regexp_pos; let mut error = false; while regexp_pos < tokenizer.input.len() { tokenizer.seek_and_get_next_codepoint(regexp_pos); if !tokenizer.code_point.unwrap().is_ascii() || (regexp_pos == regexp_start && tokenizer.code_point == Some('?')) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex( "must not start with ?, and may only contain ascii", ), )?; error = true; break; } if tokenizer.code_point == Some('\\') { if regexp_pos == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::IncompleteEscapeCode, )?; error = true; break; } tokenizer.get_next_codepoint(); if !tokenizer.code_point.unwrap().is_ascii() { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("non ascii character was escaped"), )?; error = true; break; } regexp_pos = tokenizer.next_index; continue; } if tokenizer.code_point == Some(')') { depth -= 1; if depth == 0 { regexp_pos = tokenizer.next_index; break; } } else if tokenizer.code_point == Some('(') { depth += 1; if regexp_pos == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("nested groups not closed"), )?; error = true; break; } let temp_pos = tokenizer.next_index; tokenizer.get_next_codepoint(); if tokenizer.code_point != Some('?') { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("nested groups must start with ?"), )?; error = true; break; } tokenizer.next_index = temp_pos; } regexp_pos = tokenizer.next_index; } if error { continue; } if depth != 0 { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("missing closing )"), )?; continue; } let regexp_len = regexp_pos - regexp_start - 1; if regexp_len == 0 { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("length must be > 0"), )?; continue; } tokenizer.add_token( TokenType::Regexp, regexp_pos, regexp_start, regexp_len, ); continue; } tokenizer.add_token_with_default_pos_and_len(TokenType::Char); } tokenizer.add_token_with_default_len( TokenType::End, tokenizer.index, tokenizer.index, ); Ok(tokenizer.token_list) } #[inline] pub(crate) fn is_valid_name_codepoint(code_point: char, first: bool) -> bool { if first { unic_ucd_ident::is_id_start(code_point) || matches!(code_point, '$' | '_') } else { unic_ucd_ident::is_id_continue(code_point) || matches!(code_point, '$' | '\u{200C}' | '\u{200D}') } }
use derive_more::Display; use crate::error::TokenizerError; use crate::Error; #[derive(Debug, Display, Clone, Eq, PartialEq)] pub enum TokenType { Open, Close, Regexp, Name, Char, EscapedChar, OtherModifier, Asterisk, End, InvalidChar, } #[derive(Debug, Clone)] pub struct Token { pub kind: TokenType, pub index: usize, pub value: String, } #[derive(Debug, Eq, PartialEq)] pub enum TokenizePolicy { Strict, Lenient, } struct Tokenizer { input: Vec<char>, policy: TokenizePolicy, token_list: Vec<Token>, index: usize, next_index: usize, code_point: Option<char>, } impl Tokenizer { #[inline] fn get_next_codepoint(&mut self) { self.code_point = Some(self.input[self.next_index]); self.next_index += 1; } #[inline] fn add_token_with_default_pos_and_len(&mut self, kind: TokenType) { self.add_token_with_default_len(kind, self.next_index, self.index); } #[inline] fn add_token_with_default_len( &mut self, kind: TokenType, next_pos: usize, value_pos: usize, ) { self.add_token(kind, next_pos, value_pos, next_pos - value_pos); } #[inline]
fn process_tokenizing_error( &mut self, next_pos: usize, value_pos: usize, error: TokenizerError, ) -> Result<(), Error> { if self.policy == TokenizePolicy::Strict { Err(Error::Tokenizer(error, value_pos)) } else { self.add_token_with_default_len( TokenType::InvalidChar, next_pos, value_pos, ); Ok(()) } } #[inline] fn seek_and_get_next_codepoint(&mut self, index: usize) { self.next_index = index; self.get_next_codepoint(); } } pub fn tokenize( input: &str, policy: TokenizePolicy, ) -> Result<Vec<Token>, Error> { let mut tokenizer = Tokenizer { input: input.chars().collect::<Vec<char>>(), policy, token_list: vec![], index: 0, next_index: 0, code_point: None, }; while tokenizer.index < tokenizer.input.len() { tokenizer.next_index = tokenizer.index; tokenizer.get_next_codepoint(); if tokenizer.code_point == Some('*') { tokenizer.add_token_with_default_pos_and_len(TokenType::Asterisk); continue; } if matches!(tokenizer.code_point, Some('+') | Some('?')) { tokenizer.add_token_with_default_pos_and_len(TokenType::OtherModifier); continue; } if tokenizer.code_point == Some('\\') { if tokenizer.index == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( tokenizer.next_index, tokenizer.index, TokenizerError::IncompleteEscapeCode, )?; continue; } let escaped_index = tokenizer.next_index; tokenizer.get_next_codepoint(); tokenizer.add_token_with_default_len( TokenType::EscapedChar, tokenizer.next_index, escaped_index, ); continue; } if tokenizer.code_point == Some('{') { tokenizer.add_token_with_default_pos_and_len(TokenType::Open); continue; } if tokenizer.code_point == Some('}') { tokenizer.add_token_with_default_pos_and_len(TokenType::Close); continue; } if tokenizer.code_point == Some(':') { let mut name_pos = tokenizer.next_index; let name_start = name_pos; while name_pos < tokenizer.input.len() { tokenizer.seek_and_get_next_codepoint(name_pos); let first_code_point = name_pos == name_start; let valid_codepoint = is_valid_name_codepoint( tokenizer.code_point.unwrap(), first_code_point, ); if !valid_codepoint { break; } name_pos = tokenizer.next_index; } if name_pos <= name_start { tokenizer.process_tokenizing_error( name_start, tokenizer.index, TokenizerError::InvalidName, )?; continue; } tokenizer.add_token_with_default_len( TokenType::Name, name_pos, name_start, ); continue; } if tokenizer.code_point == Some('(') { let mut depth = 1; let mut regexp_pos = tokenizer.next_index; let regexp_start = regexp_pos; let mut error = false; while regexp_pos < tokenizer.input.len() { tokenizer.seek_and_get_next_codepoint(regexp_pos); if !tokenizer.code_point.unwrap().is_ascii() || (regexp_pos == regexp_start && tokenizer.code_point == Some('?')) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex( "must not start with ?, and may only contain ascii", ), )?; error = true; break; } if tokenizer.code_point == Some('\\') { if regexp_pos == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::IncompleteEscapeCode, )?; error = true; break; } tokenizer.get_next_codepoint(); if !tokenizer.code_point.unwrap().is_ascii() { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("non ascii character was escaped"), )?; error = true; break; } regexp_pos = tokenizer.next_index; continue; } if tokenizer.code_point == Some(')') { depth -= 1; if depth == 0 { regexp_pos = tokenizer.next_index; break; } } else if tokenizer.code_point == Some('(') { depth += 1; if regexp_pos == (tokenizer.input.len() - 1) { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("nested groups not closed"), )?; error = true; break; } let temp_pos = tokenizer.next_index; tokenizer.get_next_codepoint(); if tokenizer.code_point != Some('?') { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("nested groups must start with ?"), )?; error = true; break; } tokenizer.next_index = temp_pos; } regexp_pos = tokenizer.next_index; } if error { continue; } if depth != 0 { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("missing closing )"), )?; continue; } let regexp_len = regexp_pos - regexp_start - 1; if regexp_len == 0 { tokenizer.process_tokenizing_error( regexp_start, tokenizer.index, TokenizerError::InvalidRegex("length must be > 0"), )?; continue; } tokenizer.add_token( TokenType::Regexp, regexp_pos, regexp_start, regexp_len, ); continue; } tokenizer.add_token_with_default_pos_and_len(TokenType::Char); } tokenizer.add_token_with_default_len( TokenType::End, tokenizer.index, tokenizer.index, ); Ok(tokenizer.token_list) } #[inline] pub(crate) fn is_valid_name_codepoint(code_point: char, first: bool) -> bool { if first { unic_ucd_ident::is_id_start(code_point) || matches!(code_point, '$' | '_') } else { unic_ucd_ident::is_id_continue(code_point) || matches!(code_point, '$' | '\u{200C}' | '\u{200D}') } }
fn add_token( &mut self, kind: TokenType, next_pos: usize, value_pos: usize, value_len: usize, ) { let range = value_pos..(value_pos + value_len); let value = self.input[range].iter().collect::<String>(); self.token_list.push(Token { kind, index: self.index, value, }); self.index = next_pos; }
function_block-full_function
[ { "content": "// Ref: https://wicg.github.io/urlpattern/#escape-a-pattern-string\n\nfn escape_pattern_string(input: &str) -> String {\n\n assert!(input.is_ascii());\n\n let mut result = String::new();\n\n for char in input.chars() {\n\n if matches!(char, '+' | '*' | '?' | ':' | '{' | '}' | '(' | ')' | '\\...
Rust
src/main.rs
Cxarli/minecrab
ddff0ab35c234c4413b2638c2615a2767c37c9ff
mod aabb; mod camera; mod geometry; mod geometry_buffers; mod hud; mod player; mod render_context; mod state; mod text_renderer; mod texture; mod time; mod utils; mod vertex; mod view; mod world; use std::time::{Duration, Instant}; use winit::{ dpi::{PhysicalSize, Size}, event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; use crate::state::State; fn handle_window_event( event: &WindowEvent, state: &mut State, window: &Window, ) -> Option<ControlFlow> { match event { WindowEvent::CloseRequested => Some(ControlFlow::Exit), WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => { let _ = window.set_cursor_grab(false); window.set_cursor_visible(true); state.mouse_grabbed = false; None } WindowEvent::Resized(physical_size) => { state.resize(*physical_size); None } WindowEvent::ScaleFactorChanged { new_inner_size, .. } => { state.resize(**new_inner_size); None } WindowEvent::MouseInput { state: mouse_state, button, .. } => { if !state.mouse_grabbed && *button == MouseButton::Left && *mouse_state == ElementState::Pressed { let _ = window.set_cursor_grab(true); window.set_cursor_visible(false); state.mouse_grabbed = true; } else { state.window_event(event); } None } WindowEvent::Focused(false) => { let _ = window.set_cursor_grab(false); window.set_cursor_visible(true); state.mouse_grabbed = false; None } event => { state.window_event(event); None } } } fn main() { env_logger::init(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("minecrab") .with_inner_size(Size::Physical(PhysicalSize { width: 1280, height: 720, })) .build(&event_loop) .unwrap(); let mut state = futures::executor::block_on(State::new(&window)); let mut frames = 0; let mut frame_instant = Instant::now(); let mut elapsed = Duration::from_secs(0); let mut frametime_min = Duration::from_secs(1000); let mut frametime_max = Duration::from_secs(0); let mut last_render_time = Instant::now(); let mut triangle_count = 0; event_loop.run(move |event, _, control_flow| { match event { Event::DeviceEvent { ref event, .. } => state.device_event(event), Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { if let Some(cf) = handle_window_event(event, &mut state, &window) { *control_flow = cf } } Event::RedrawRequested(_) => { let frame_elapsed = frame_instant.elapsed(); frame_instant = Instant::now(); frametime_min = frametime_min.min(frame_elapsed); frametime_max = frametime_max.max(frame_elapsed); elapsed += frame_elapsed; frames += 1; if elapsed.as_secs() >= 1 { let frametime = elapsed / frames; let fps = 1_000_000 / frametime.as_micros(); let fps_max = 1_000_000 / frametime_min.as_micros(); let fps_min = 1_000_000 / frametime_max.as_micros(); print!("{:>4} frames | ", frames); print!( "frametime avg={:>5.2}ms min={:>5.2}ms max={:>5.2}ms | ", frametime.as_secs_f32() * 1000.0, frametime_min.as_secs_f32() * 1000.0, frametime_max.as_secs_f32() * 1000.0, ); print!( "fps avg={:>5} min={:>5} max={:>5} | ", fps, fps_min, fps_max ); println!( "{:>8} tris | {:>5} chunks", triangle_count, state.world.chunks.len() ); elapsed = Duration::from_secs(0); frames = 0; frametime_min = Duration::from_secs(1000); frametime_max = Duration::from_secs(0); } let dt = last_render_time.elapsed(); let now = Instant::now(); last_render_time = now; let render_time = match state.render() { Err(root_cause) => { match root_cause.downcast_ref::<wgpu::SurfaceError>() { Some(wgpu::SurfaceError::Lost) => { state.resize(state.window_size); } Some(wgpu::SurfaceError::OutOfMemory) => { *control_flow = ControlFlow::Exit; } Some(wgpu::SurfaceError::Timeout) => { eprintln!("TIMEOUT"); } Some(wgpu::SurfaceError::Outdated) => { eprintln!("OUTDATED"); } None => {} } return; } Ok((triangle_count_, render_time)) => { triangle_count = triangle_count_; render_time } }; state.update(dt, render_time); } Event::MainEventsCleared => { window.request_redraw(); } _ => {} } }); }
mod aabb; mod camera; mod geometry; mod geometry_buffers; mod hud; mod player; mod render_context; mod state; mod text_renderer; mod texture; mod time; mod utils; mod vertex; mod view; mod world; use std::time::{Duration, Instant}; use winit::{ dpi::{PhysicalSize, Size}, event::{ElementState, Event, KeyboardInput, MouseButton, VirtualKeyCode, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; use crate::state::State; fn handle_window_event( event: &WindowEvent, state: &mut State, window: &Window, ) -> Option<ControlFlow> { match event { WindowEvent::CloseRequested => Some(ControlFlow::Exit), WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => { let _ = window.set_cursor_grab(false); window.set_cursor_visible(true); state.mouse_grabbed = false; None } WindowEvent::Resized(physical_size) => { state.resize(*physical_size); None } WindowEvent::ScaleFactorChanged { new_inner_size, .. } => { state.resize(**new_inner_size); None } WindowEvent::MouseInput { state: mouse_state, button, .. } => { if !state.mouse_grabbed && *button == MouseButton::Left && *mouse_state == ElementState::Pressed { let _ = window.set_cursor_grab(true); window.set_cursor_visible(false); state.mouse_grabbed = true; } else { state.window_event(event); } None } WindowEvent::Focused(false) => { let _ = window.set_cursor_grab(false); window.set_cursor_visible(true); state.mouse_grabbed = false; None } event => { state.window_event(event); None } } } fn main() { env_logger::init(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("minecrab") .with_inner_size(Size::Physical(PhysicalSize { width: 1280, height: 720, })) .build(&event_loop) .unwrap(); let mut state = futures::executor::block_on(State::new(&window)); let mut frames = 0; let mut frame_instant = Instant::now(); let mut elapsed = Duration::from_secs(0); let mut frametime_min = Duration::from_secs(1000); let mut frametime_max = Duration::from_secs(0); let mut last_render_time = Instant::now(); let mut triangle_count = 0; event_loop.run(move |event, _, control_flow| { match event { Event::DeviceEvent { ref event, .. } => state.device_event(event), Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { if let Some(cf) = handle_window_event(event, &mut state, &window) { *control_flow = cf } } Event::RedrawRequested(_) => { let frame_elapsed = frame_instant.elapsed(); frame_instant = Instant::now(); frametime_min = frametime_min.min(frame_elapsed); frametime_max = frametime_max.max(frame_elapsed); elapsed += frame_elapsed; frames += 1; if elapsed.as_secs() >= 1 { let frametime = elapsed / frames; let fps = 1_000_000 / frametime.as_micros(); let fps_max = 1_000_000 / frametime_min.as_micros(); let fps_min = 1_000_000 / frametime_max.as_micros(); print!("{:>4} frames | ", frames); print!( "frametime avg={:>5.2}ms min={:>5.2}ms max={:>5.2}ms | ", frametime.as_secs_f32() * 1000.0, frametime_min.as_secs_f32() * 1000.0, frametime_max.as_secs_f32() * 1000.0, );
print!( "fps avg={:>5} min={:>5} max={:>5} | ", fps, fps_min, fps_max ); println!( "{:>8} tris | {:>5} chunks", triangle_count, state.world.chunks.len() ); elapsed = Duration::from_secs(0); frames = 0; frametime_min = Duration::from_secs(1000); frametime_max = Duration::from_secs(0); } let dt = last_render_time.elapsed(); let now = Instant::now(); last_render_time = now; let render_time = match state.render() { Err(root_cause) => { match root_cause.downcast_ref::<wgpu::SurfaceError>() { Some(wgpu::SurfaceError::Lost) => { state.resize(state.window_size); } Some(wgpu::SurfaceError::OutOfMemory) => { *control_flow = ControlFlow::Exit; } Some(wgpu::SurfaceError::Timeout) => { eprintln!("TIMEOUT"); } Some(wgpu::SurfaceError::Outdated) => { eprintln!("OUTDATED"); } None => {} } return; } Ok((triangle_count_, render_time)) => { triangle_count = triangle_count_; render_time } }; state.update(dt, render_time); } Event::MainEventsCleared => { window.request_redraw(); } _ => {} } }); }
function_block-function_prefix_line
[ { "content": "use wgpu::{CommandEncoder, RenderPipeline};\n\n\n\nuse crate::{\n\n render_context::RenderContext,\n\n vertex::{HudVertex, Vertex},\n\n world::block::BlockType,\n\n};\n\n\n\nuse self::{debug_hud::DebugHud, hotbar_hud::HotbarHud, widgets_hud::WidgetsHud};\n\n\n\nuse std::borrow::Cow;\n\n\n...
Rust
src/serial.rs
IamfromSpace/stm32f3xx-hal
c68c36c03e0e33699b3b0c9acc3f8d80f5a25cd4
use crate::{ gpio::{gpioa, gpiob, gpioc, AF7}, hal::{blocking, serial}, pac::{USART1, USART2, USART3}, rcc::{Clocks, APB1, APB2}, time::Bps, }; use cfg_if::cfg_if; use core::{convert::Infallible, marker::PhantomData, ptr}; cfg_if! { if #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] { use crate::dma; use cortex_m::interrupt; } } pub enum Event { Rxne, Txe, } #[derive(Debug)] #[non_exhaustive] pub enum Error { Framing, Noise, Overrun, Parity, } pub unsafe trait TxPin<USART> {} pub unsafe trait RxPin<USART> {} unsafe impl TxPin<USART1> for gpioa::PA9<AF7> {} unsafe impl TxPin<USART1> for gpiob::PB6<AF7> {} unsafe impl TxPin<USART1> for gpioc::PC4<AF7> {} unsafe impl RxPin<USART1> for gpioa::PA10<AF7> {} unsafe impl RxPin<USART1> for gpiob::PB7<AF7> {} unsafe impl RxPin<USART1> for gpioc::PC5<AF7> {} unsafe impl TxPin<USART2> for gpioa::PA2<AF7> {} unsafe impl TxPin<USART2> for gpiob::PB3<AF7> {} unsafe impl RxPin<USART2> for gpioa::PA3<AF7> {} unsafe impl RxPin<USART2> for gpiob::PB4<AF7> {} unsafe impl TxPin<USART3> for gpiob::PB10<AF7> {} unsafe impl TxPin<USART3> for gpioc::PC10<AF7> {} unsafe impl RxPin<USART3> for gpioc::PC11<AF7> {} cfg_if! { if #[cfg(any(feature = "gpio-f303", feature = "gpio-f303e", feature = "gpio-f373"))] { use crate::gpio::{gpiod, gpioe}; unsafe impl TxPin<USART1> for gpioe::PE0<AF7> {} unsafe impl RxPin<USART1> for gpioe::PE1<AF7> {} unsafe impl TxPin<USART2> for gpiod::PD5<AF7> {} unsafe impl RxPin<USART2> for gpiod::PD6<AF7> {} unsafe impl TxPin<USART3> for gpiod::PD8<AF7> {} unsafe impl RxPin<USART3> for gpiod::PD9<AF7> {} unsafe impl RxPin<USART3> for gpioe::PE15<AF7> {} } } cfg_if! { if #[cfg(not(feature = "gpio-f373"))] { unsafe impl TxPin<USART2> for gpioa::PA14<AF7> {} unsafe impl RxPin<USART2> for gpioa::PA15<AF7> {} unsafe impl RxPin<USART3> for gpiob::PB11<AF7> {} } } pub struct Serial<USART, PINS> { usart: USART, pins: PINS, } pub struct Rx<USART> { _usart: PhantomData<USART>, } pub struct Tx<USART> { _usart: PhantomData<USART>, } macro_rules! hal { ($( $USARTX:ident: ($usartX:ident, $APB:ident, $usartXen:ident, $usartXrst:ident, $pclkX:ident), )+) => { $( impl<TX, RX> Serial<$USARTX, (TX, RX)> { pub fn $usartX( usart: $USARTX, pins: (TX, RX), baud_rate: Bps, clocks: Clocks, apb: &mut $APB, ) -> Self where TX: TxPin<$USARTX>, RX: RxPin<$USARTX>, { apb.enr().modify(|_, w| w.$usartXen().set_bit()); apb.rstr().modify(|_, w| w.$usartXrst().set_bit()); apb.rstr().modify(|_, w| w.$usartXrst().clear_bit()); let brr = clocks.$pclkX().0 / baud_rate.0; crate::assert!(brr >= 16, "impossible baud rate"); usart.brr.write(|w| unsafe { w.bits(brr) }); usart.cr1.modify(|_, w| { w.ue().enabled(); w.re().enabled(); w.te().enabled() }); Serial { usart, pins } } pub fn listen(&mut self, event: Event) { match event { Event::Rxne => { self.usart.cr1.modify(|_, w| w.rxneie().set_bit()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().set_bit()) }, } } pub fn unlisten(&mut self, event: Event) { match event { Event::Rxne => { self.usart.cr1.modify(|_, w| w.rxneie().clear_bit()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().clear_bit()) }, } } pub fn split(self) -> (Tx<$USARTX>, Rx<$USARTX>) { ( Tx { _usart: PhantomData, }, Rx { _usart: PhantomData, }, ) } pub fn free(self) -> ($USARTX, (TX, RX)) { (self.usart, self.pins) } } impl serial::Read<u8> for Rx<$USARTX> { type Error = Error; fn read(&mut self) -> nb::Result<u8, Error> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; let icr = unsafe { &(*$USARTX::ptr()).icr }; Err(if isr.pe().bit_is_set() { icr.write(|w| w.pecf().clear()); nb::Error::Other(Error::Parity) } else if isr.fe().bit_is_set() { icr.write(|w| w.fecf().clear()); nb::Error::Other(Error::Framing) } else if isr.nf().bit_is_set() { icr.write(|w| w.ncf().clear()); nb::Error::Other(Error::Noise) } else if isr.ore().bit_is_set() { icr.write(|w| w.orecf().clear()); nb::Error::Other(Error::Overrun) } else if isr.rxne().bit_is_set() { return Ok(unsafe { ptr::read_volatile(&(*$USARTX::ptr()).rdr as *const _ as *const _) }); } else { nb::Error::WouldBlock }) } } impl serial::Write<u8> for Tx<$USARTX> { type Error = Infallible; fn flush(&mut self) -> nb::Result<(), Infallible> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.tc().bit_is_set() { Ok(()) } else { Err(nb::Error::WouldBlock) } } fn write(&mut self, byte: u8) -> nb::Result<(), Infallible> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.txe().bit_is_set() { unsafe { ptr::write_volatile(&(*$USARTX::ptr()).tdr as *const _ as *mut _, byte) } Ok(()) } else { Err(nb::Error::WouldBlock) } } } impl blocking::serial::write::Default<u8> for Tx<$USARTX> {} #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl Rx<$USARTX> { pub fn read_exact<B, C>( self, buffer: B, mut channel: C ) -> dma::Transfer<B, C, Self> where Self: dma::OnChannel<C>, B: dma::WriteBuffer<Word = u8> + 'static, C: dma::Channel, { let pa = unsafe { &(*$USARTX::ptr()).rdr } as *const _ as u32; unsafe { channel.set_peripheral_address(pa, dma::Increment::Disable) }; dma::Transfer::start_write(buffer, channel, self) } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl Tx<$USARTX> { pub fn write_all<B, C>( self, buffer: B, mut channel: C ) -> dma::Transfer<B, C, Self> where Self: dma::OnChannel<C>, B: dma::ReadBuffer<Word = u8> + 'static, C: dma::Channel, { let pa = unsafe { &(*$USARTX::ptr()).tdr } as *const _ as u32; unsafe { channel.set_peripheral_address(pa, dma::Increment::Disable) }; dma::Transfer::start_read(buffer, channel, self) } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl dma::Target for Rx<$USARTX> { fn enable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmar().enabled()); }); } fn disable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmar().disabled()); }); } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl dma::Target for Tx<$USARTX> { fn enable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmat().enabled()); }); } fn disable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmat().disabled()); }); } } )+ } } hal! { USART1: (usart1, APB2, usart1en, usart1rst, pclk2), USART2: (usart2, APB1, usart2en, usart2rst, pclk1), USART3: (usart3, APB1, usart3en, usart3rst, pclk1), }
use crate::{ gpio::{gpioa, gpiob, gpioc, AF7}, hal::{blocking, serial}, pac::{USART1, USART2, USART3}, rcc::{Clocks, APB1, APB2}, time::Bps, }; use cfg_if::cfg_if; use core::{convert::Infallible, marker::PhantomData, ptr}; cfg_if! { if #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] { use crate::dma; use cortex_m::interrupt; } } pub enum Event { Rxne, Txe, } #[derive(Debug)] #[non_exhaustive] pub enum Error { Framing, Noise, Overrun, Parity, } pub unsafe trait TxPin<USART> {} pub unsafe trait RxPin<USART> {} unsafe impl TxPin<USART1> for gpioa::PA9<AF7> {} unsafe impl TxPin<USART1> for gpiob::PB6<AF7> {} unsafe impl TxPin<USART1> for gpioc::PC4<AF7> {} unsafe impl RxPin<USART1> for gpioa::PA10<AF7> {} unsafe impl RxPin<USART1> for gpiob::PB7<AF7> {} unsafe impl RxPin<USART1> for gpioc::PC5<AF7> {} unsafe impl TxPin<USART2> for gpioa::PA2<AF7> {} unsafe impl TxPin<USART2> for gpiob::PB3<AF7> {} unsafe impl RxPin<USART2> for gpioa::PA3<AF7> {} unsafe impl RxPin<USART2> for gpiob::PB4<AF7> {} unsafe impl TxPin<USART3> for gpiob::PB10<AF7> {} unsafe impl TxPin<USART3> for gpioc::PC10<AF7> {} unsafe impl RxPin<USART3> for gpioc::PC11<AF7> {} cfg_if! { if #[cfg(any(feature = "gpio-f303", feature = "gpio-f303e", feature = "gpio-f373"))] { use crate::gpio::{gpiod, gpioe}; unsafe impl TxPin<USART1> for gpioe::PE0<AF7> {} unsafe impl RxPin<USART1> for gpioe::PE1<AF7> {} unsafe impl TxPin<USART2> for gpiod::PD5<AF7> {} unsafe impl RxPin<USART2> for gpiod::PD6<AF7> {} unsafe impl TxPin<USART3> for gpiod::PD8<AF7> {} unsafe impl RxPin<USART3> for gpiod::PD9<AF7> {} unsafe impl RxPin<USART3> for gpioe::PE15<AF7> {} } } cfg_if! { if #[cfg(not(feature = "gpio-f373"))] { unsafe impl TxPin<USART2> for gpioa::PA14<AF7> {} unsafe impl RxPin<USART2> for gpioa::PA15<AF7> {} unsafe impl RxPin<USART3> for gpiob::PB11<AF7> {} } } pub struct Serial<USART, PINS> { usart: USART, pins: PINS, } pub struct Rx<USART> { _usart: PhantomData<USART>, } pub struct Tx<USART> { _usart: PhantomData<USART>, } macro_rules! hal { ($( $USARTX:ident: ($usartX:ident, $APB:ident, $usartXen:ident, $usartXrst:ident, $pclkX:ident), )+) => { $( impl<TX, RX> Serial<$USARTX, (TX, RX)> { pub fn $usartX( usart: $USARTX, pins: (TX, RX), baud_rate: Bps, clocks: Clocks, apb: &mut $APB, ) -> Self where TX: TxPin<$USARTX>, RX: RxPin<$USARTX>, { apb.enr().modify(|_, w| w.$usartXen().set_bit()); apb.rstr().modify(|_, w| w.$usartXrst().set_bit()); apb.rstr().modify(|_, w| w.$usartXrst().clear_bit()); let brr = clocks.$pclkX().0 / baud_rate.0; crate::assert!(brr >= 16, "impossible baud rate"); usart.brr.write(|w| unsafe { w.bits(brr) }); usart.cr1.modify(|_, w| { w.ue().enabled(); w.re().enabled(); w.te().enabled() }); Serial { usart, pins }
self.usart.cr1.modify(|_, w| w.rxneie().set_bit()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().set_bit()) }, } } pub fn unlisten(&mut self, event: Event) { match event { Event::Rxne => { self.usart.cr1.modify(|_, w| w.rxneie().clear_bit()) }, Event::Txe => { self.usart.cr1.modify(|_, w| w.txeie().clear_bit()) }, } } pub fn split(self) -> (Tx<$USARTX>, Rx<$USARTX>) { ( Tx { _usart: PhantomData, }, Rx { _usart: PhantomData, }, ) } pub fn free(self) -> ($USARTX, (TX, RX)) { (self.usart, self.pins) } } impl serial::Read<u8> for Rx<$USARTX> { type Error = Error; fn read(&mut self) -> nb::Result<u8, Error> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; let icr = unsafe { &(*$USARTX::ptr()).icr }; Err(if isr.pe().bit_is_set() { icr.write(|w| w.pecf().clear()); nb::Error::Other(Error::Parity) } else if isr.fe().bit_is_set() { icr.write(|w| w.fecf().clear()); nb::Error::Other(Error::Framing) } else if isr.nf().bit_is_set() { icr.write(|w| w.ncf().clear()); nb::Error::Other(Error::Noise) } else if isr.ore().bit_is_set() { icr.write(|w| w.orecf().clear()); nb::Error::Other(Error::Overrun) } else if isr.rxne().bit_is_set() { return Ok(unsafe { ptr::read_volatile(&(*$USARTX::ptr()).rdr as *const _ as *const _) }); } else { nb::Error::WouldBlock }) } } impl serial::Write<u8> for Tx<$USARTX> { type Error = Infallible; fn flush(&mut self) -> nb::Result<(), Infallible> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.tc().bit_is_set() { Ok(()) } else { Err(nb::Error::WouldBlock) } } fn write(&mut self, byte: u8) -> nb::Result<(), Infallible> { let isr = unsafe { (*$USARTX::ptr()).isr.read() }; if isr.txe().bit_is_set() { unsafe { ptr::write_volatile(&(*$USARTX::ptr()).tdr as *const _ as *mut _, byte) } Ok(()) } else { Err(nb::Error::WouldBlock) } } } impl blocking::serial::write::Default<u8> for Tx<$USARTX> {} #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl Rx<$USARTX> { pub fn read_exact<B, C>( self, buffer: B, mut channel: C ) -> dma::Transfer<B, C, Self> where Self: dma::OnChannel<C>, B: dma::WriteBuffer<Word = u8> + 'static, C: dma::Channel, { let pa = unsafe { &(*$USARTX::ptr()).rdr } as *const _ as u32; unsafe { channel.set_peripheral_address(pa, dma::Increment::Disable) }; dma::Transfer::start_write(buffer, channel, self) } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl Tx<$USARTX> { pub fn write_all<B, C>( self, buffer: B, mut channel: C ) -> dma::Transfer<B, C, Self> where Self: dma::OnChannel<C>, B: dma::ReadBuffer<Word = u8> + 'static, C: dma::Channel, { let pa = unsafe { &(*$USARTX::ptr()).tdr } as *const _ as u32; unsafe { channel.set_peripheral_address(pa, dma::Increment::Disable) }; dma::Transfer::start_read(buffer, channel, self) } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl dma::Target for Rx<$USARTX> { fn enable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmar().enabled()); }); } fn disable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmar().disabled()); }); } } #[cfg(any(feature = "stm32f302", feature = "stm32f303"))] impl dma::Target for Tx<$USARTX> { fn enable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmat().enabled()); }); } fn disable_dma(&mut self) { interrupt::free(|_| unsafe { let cr3 = &(*$USARTX::ptr()).cr3; cr3.modify(|_, w| w.dmat().disabled()); }); } } )+ } } hal! { USART1: (usart1, APB2, usart1en, usart1rst, pclk2), USART2: (usart2, APB1, usart2en, usart2rst, pclk1), USART3: (usart3, APB1, usart3en, usart3rst, pclk1), }
} pub fn listen(&mut self, event: Event) { match event { Event::Rxne => {
random
[ { "content": "fn unlock(apb1: &mut APB1, pwr: &mut PWR) {\n\n apb1.enr().modify(|_, w| {\n\n w\n\n // Enable the backup interface by setting PWREN\n\n .pwren()\n\n .set_bit()\n\n });\n\n pwr.cr.modify(|_, w| {\n\n w\n\n // Enable access to the b...
Rust
src/processor/mod.rs
gluwa/Sawtooth-SDK-Rust
8a3d99fa2c82eb3131148931a819ffca46d78c66
/* * Copyright 2017 Bitwise IO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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. * ----------------------------------------------------------------------------- */ #![allow(unknown_lints)] extern crate ctrlc; extern crate protobuf; extern crate rand; extern crate zmq; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::RecvTimeoutError; use std::sync::Arc; use std::time::Duration; use self::rand::Rng; pub mod handler; mod zmq_context; use crate::messages::network::PingResponse; use crate::messages::processor::TpProcessRequest; use crate::messages::processor::TpProcessResponse; use crate::messages::processor::TpProcessResponse_Status; use crate::messages::processor::TpRegisterRequest; use crate::messages::processor::TpUnregisterRequest; use crate::messages::validator::Message_MessageType; use crate::messaging::stream::MessageSender; use crate::messaging::stream::ReceiveError; use crate::messaging::stream::SendError; use crate::messaging::stream::{MessageConnection, MessageReceiver}; use crate::messaging::zmq_stream::ZmqMessageConnection; use crate::messaging::zmq_stream::ZmqMessageSender; use protobuf::Message as M; use protobuf::RepeatedField; use rand::distributions::Alphanumeric; use self::handler::TransactionHandler; use self::handler::{ApplyError, TransactionContext}; use self::zmq_context::ZmqTransactionContext; fn generate_correlation_id() -> String { const LENGTH: usize = 16; rand::thread_rng() .sample_iter(Alphanumeric) .take(LENGTH) .map(char::from) .collect() } pub struct EmptyTransactionContext { inner: Arc<InnerEmptyContext>, } impl Clone for EmptyTransactionContext { fn clone(&self) -> Self { Self { inner: Arc::clone(&self.inner), } } } struct InnerEmptyContext { context: Box<dyn TransactionContext + Send + Sync>, _sender: ZmqMessageSender, _receiver: std::sync::Mutex<MessageReceiver>, } impl EmptyTransactionContext { fn new(conn: &ZmqMessageConnection, timeout: Option<Duration>) -> Self { let (_sender, _receiver) = conn.create(); Self { inner: Arc::new(InnerEmptyContext { context: Box::new(ZmqTransactionContext::with_timeout( "", _sender.clone(), timeout, )), _receiver: std::sync::Mutex::new(_receiver), _sender, }), } } pub fn flush(&self) { if let Ok(rx) = self.inner._receiver.try_lock() { if let Ok(Ok(msg)) = rx.recv_timeout(Duration::from_millis(100)) { log::info!("Empty context received message : {:?}", msg); } } } } impl TransactionContext for EmptyTransactionContext { fn get_state_entries( &self, _addresses: &[String], ) -> Result<Vec<(String, Vec<u8>)>, handler::ContextError> { panic!("unsupported for an empty context") } fn set_state_entries( &self, _entries: Vec<(String, Vec<u8>)>, ) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn delete_state_entries( &self, _addresses: &[String], ) -> Result<Vec<String>, handler::ContextError> { panic!("unsupported for an empty context") } fn add_receipt_data(&self, _data: &[u8]) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn add_event( &self, _event_type: String, _attributes: Vec<(String, String)>, _data: &[u8], ) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn get_sig_by_num(&self, block_num: u64) -> Result<String, handler::ContextError> { self.inner.context.get_sig_by_num(block_num) } fn get_reward_block_signatures( &self, block_id: &str, first_pred: u64, last_pred: u64, ) -> Result<Vec<String>, handler::ContextError> { self.inner .context .get_reward_block_signatures(block_id, first_pred, last_pred) } fn get_state_entries_by_prefix( &self, tip_id: &str, address: &str, ) -> Result<Vec<(String, Vec<u8>)>, handler::ContextError> { self.inner .context .get_state_entries_by_prefix(tip_id, address) } } pub struct TransactionProcessor<'a> { endpoint: String, conn: ZmqMessageConnection, handlers: Vec<&'a dyn TransactionHandler>, empty_contexts: Vec<EmptyTransactionContext>, } impl<'a> TransactionProcessor<'a> { pub fn new(endpoint: &str) -> TransactionProcessor { TransactionProcessor { endpoint: String::from(endpoint), conn: ZmqMessageConnection::new(endpoint), handlers: Vec::new(), empty_contexts: Vec::new(), } } pub fn add_handler(&mut self, handler: &'a dyn TransactionHandler) { self.handlers.push(handler); } pub fn empty_context(&mut self, timeout: Option<Duration>) -> EmptyTransactionContext { let context = EmptyTransactionContext::new(&self.conn, timeout); let context_cp = context.clone(); self.empty_contexts.push(context); context_cp } fn register(&mut self, sender: &ZmqMessageSender, unregister: &Arc<AtomicBool>) -> bool { for handler in &self.handlers { for version in handler.family_versions() { let mut request = TpRegisterRequest::new(); request.set_family(handler.family_name().clone()); request.set_version(version.clone()); request.set_namespaces(RepeatedField::from_vec(handler.namespaces().clone())); info!( "sending TpRegisterRequest: {} {}", &handler.family_name(), &version ); let serialized = match request.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); return false; } }; let x: &[u8] = &serialized; let mut future = match sender.send( Message_MessageType::TP_REGISTER_REQUEST, &generate_correlation_id(), x, ) { Ok(fut) => fut, Err(err) => { error!("Registration failed: {}", err); return false; } }; loop { match future.get_timeout(Duration::from_millis(10000)) { Ok(_) => break, Err(_) => { if unregister.load(Ordering::SeqCst) { return false; } } }; } } } true } fn unregister(&mut self, sender: &ZmqMessageSender) { let request = TpUnregisterRequest::new(); info!("sending TpUnregisterRequest"); let serialized = match request.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); return; } }; let x: &[u8] = &serialized; let mut future = match sender.send( Message_MessageType::TP_UNREGISTER_REQUEST, &generate_correlation_id(), x, ) { Ok(fut) => fut, Err(err) => { error!("Unregistration failed: {}", err); return; } }; match future.get_timeout(Duration::from_millis(1000)) { Ok(_) => (), Err(err) => { info!("Unregistration failed: {}", err); } }; } #[allow(clippy::cognitive_complexity)] pub fn start(&mut self) { let unregister = Arc::new(AtomicBool::new(false)); let r = unregister.clone(); ctrlc::set_handler(move || { r.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); let mut first_time = true; let mut restart = true; while restart { info!("connecting to endpoint: {}", self.endpoint); if first_time { first_time = false; } else { self.conn = ZmqMessageConnection::new(&self.endpoint); } let (mut sender, receiver) = self.conn.create(); if unregister.load(Ordering::SeqCst) { self.unregister(&sender); restart = false; continue; } if !self.register(&sender, &unregister.clone()) { continue; } loop { if unregister.load(Ordering::SeqCst) { self.unregister(&sender); restart = false; break; } match receiver.recv_timeout(Duration::from_millis(1000)) { Ok(r) => { let message = match r { Ok(message) => message, Err(ReceiveError::DisconnectedError) => { info!("Trying to Reconnect"); break; } Err(err) => { error!("Error: {}", err); continue; } }; trace!("Message: {}", message.get_correlation_id()); match message.get_message_type() { Message_MessageType::TP_PROCESS_REQUEST => { let request = match TpProcessRequest::parse_from_bytes( &message.get_content(), ) { Ok(request) => request, Err(err) => { error!("Cannot parse TpProcessRequest: {}", err); continue; } }; let mut context = ZmqTransactionContext::new( request.get_context_id(), sender.clone(), ); let mut response = TpProcessResponse::new(); match self.handlers[0].apply(&request, &mut context) { Ok(()) => { info!("TP_PROCESS_REQUEST sending TpProcessResponse: OK"); response.set_status(TpProcessResponse_Status::OK); } Err(ApplyError::InvalidTransaction(msg)) => { info!( "TP_PROCESS_REQUEST sending TpProcessResponse: {}", &msg ); response.set_status( TpProcessResponse_Status::INVALID_TRANSACTION, ); response.set_message(msg); } Err(err) => { info!( "TP_PROCESS_REQUEST sending TpProcessResponse: {}", err ); response .set_status(TpProcessResponse_Status::INTERNAL_ERROR); response.set_message(err.to_string()); } }; let serialized = match response.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); continue; } }; match sender.reply( Message_MessageType::TP_PROCESS_RESPONSE, message.get_correlation_id(), &serialized, ) { Ok(_) => (), Err(SendError::DisconnectedError) => { error!("DisconnectedError"); break; } Err(SendError::TimeoutError) => error!("TimeoutError"), Err(SendError::UnknownError(e)) => { restart = false; error!("UnknownError: {}", e); break; } }; } Message_MessageType::PING_REQUEST => { trace!("sending PingResponse"); let response = PingResponse::new(); let serialized = match response.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); continue; } }; match sender.reply( Message_MessageType::PING_RESPONSE, message.get_correlation_id(), &serialized, ) { Ok(_) => (), Err(SendError::DisconnectedError) => { error!("DisconnectedError"); break; } Err(SendError::TimeoutError) => error!("TimeoutError"), Err(SendError::UnknownError(e)) => { restart = false; error!("UnknownError: {}", e); break; } }; } _ => { info!( "Transaction Processor recieved invalid message type: {:?}", message.get_message_type() ); } } } Err(RecvTimeoutError::Timeout) => (), Err(err) => { error!("Error: {}", err); } } } sender.close(); } } }
/* * Copyright 2017 Bitwise IO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * 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. * ----------------------------------------------------------------------------- */ #![allow(unknown_lints)] extern crate ctrlc; extern crate protobuf; extern crate rand; extern crate zmq; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::RecvTimeoutError; use std::sync::Arc; use std::time::Duration; use self::rand::Rng; pub mod handler; mod zmq_context; use crate::messages::network::PingResponse; use crate::messages::processor::TpProcessRequest; use crate::messages::processor::TpProcessResponse; use crate::messages::processor::TpProcessResponse_Status; use crate::messages::processor::TpRegisterRequest; use crate::messages::processor::TpUnregisterRequest; use crate::messages::validator::Message_MessageType; use crate::messaging::stream::MessageSender; use crate::messaging::stream::ReceiveError; use crate::messaging::stream::SendError; use crate::messaging::stream::{MessageConnection, MessageReceiver}; use crate::messaging::zmq_stream::ZmqMessageConnection; use crate::messaging::zmq_stream::ZmqMessageSender; use protobuf::Message as M; use protobuf::RepeatedField; use rand::distributions::Alphanumeric; use self::handler::TransactionHandler; use self::handler::{ApplyError, TransactionContext}; use self::zmq_context::ZmqTransactionContext; fn generate_correlation_id() -> String { const LENGTH: usize = 16; rand::thread_rng() .sample_iter(Alphanumeric) .take(LENGTH) .map(char::from) .collect() } pub struct EmptyTransactionContext { inner: Arc<InnerEmptyContext>, } impl Clone for EmptyTransactionContext { fn clone(&self) -> Self { Self { inner: Arc::clone(&self.inner), } } } struct InnerEmptyContext { context: Box<dyn TransactionContext + Send + Sync>, _sender: ZmqMessageSender, _receiver: std::sync::Mutex<MessageReceiver>, } impl EmptyTransactionContext { fn new(conn: &ZmqMessageConnection, timeout: Option<Duration>) -> Self { let (_sender, _receiver) = conn.create(); Self { inner: Arc::new(InnerEmptyContext { context: Box::new(ZmqTransactionContext::with_timeout( "", _sender.clone(), timeout, )), _receiver: std::sync::Mutex::new(_receiver), _sender, }), } } pub fn flush(&self) { if let Ok(rx) = self.inner._receiver.try_lock() { if let Ok(Ok(msg)) = rx.recv_timeout(Duration::from_millis(100)) { log::info!("Empty context received message : {:?}", msg); } } } } impl TransactionContext for EmptyTransactionContext { fn get_state_entries( &self, _addresses: &[String], ) -> Result<Vec<(String, Vec<u8>)>, handler::ContextError> { panic!("unsupported for an empty context") } fn set_state_entries( &self, _entries: Vec<(String, Vec<u8>)>, ) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn delete_state_entries( &self, _addresses: &[String], ) -> Result<Vec<String>, handler::ContextError> { panic!("unsupported for an empty context") } fn add_receipt_data(&self, _data: &[u8]) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn add_event( &self, _event_type: String, _attributes: Vec<(String, String)>, _data: &[u8], ) -> Result<(), handler::ContextError> { panic!("unsupported for an empty context") } fn get_sig_by_num(&self, block_num: u64) -> Result<String, handler::ContextError> { self.inner.context.get_sig_by_num(block_num) } fn get_reward_block_signatures( &self, block_id: &str, first_pred: u64, last_pred: u64, ) -> Result<Vec<String>, handler::ContextError> { self.inner .context .get_reward_block_signatures(block_id, first_pred, last_pred) } fn get_state_entries_by_prefix( &self, tip_id: &str, address: &str, ) -> Result<Vec<(String, Vec<u8>)>, handler::ContextError> { self.inner .context .get_state_entries_by_prefix(tip_id, address) } } pub struct TransactionProcessor<'a> { endpoint: String, conn: ZmqMessageConnection, handlers: Vec<&'a dyn TransactionHandler>, empty_contexts: Vec<EmptyTransactionContext>, } impl<'a> TransactionProcessor<'a> { pub fn new(endpoint: &str) -> TransactionProcessor { TransactionProcessor { endpoint: String::from(endpoint), conn: ZmqMessageConnection::new(endpoint), handlers: Vec::new(), empty_contexts: Vec::new(), } } pub fn add_handler(&mut self, handler: &'a dyn TransactionHandler) { self.handlers.push(handler); } pub fn empty_context(&mut self, timeout: Option<Duration>) -> EmptyTransactionContext { let context = EmptyTransactionContext::new(&self.conn, timeout); let context_cp = context.clone(); self.empty_contexts.push(context); context_cp }
fn unregister(&mut self, sender: &ZmqMessageSender) { let request = TpUnregisterRequest::new(); info!("sending TpUnregisterRequest"); let serialized = match request.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); return; } }; let x: &[u8] = &serialized; let mut future = match sender.send( Message_MessageType::TP_UNREGISTER_REQUEST, &generate_correlation_id(), x, ) { Ok(fut) => fut, Err(err) => { error!("Unregistration failed: {}", err); return; } }; match future.get_timeout(Duration::from_millis(1000)) { Ok(_) => (), Err(err) => { info!("Unregistration failed: {}", err); } }; } #[allow(clippy::cognitive_complexity)] pub fn start(&mut self) { let unregister = Arc::new(AtomicBool::new(false)); let r = unregister.clone(); ctrlc::set_handler(move || { r.store(true, Ordering::SeqCst); }) .expect("Error setting Ctrl-C handler"); let mut first_time = true; let mut restart = true; while restart { info!("connecting to endpoint: {}", self.endpoint); if first_time { first_time = false; } else { self.conn = ZmqMessageConnection::new(&self.endpoint); } let (mut sender, receiver) = self.conn.create(); if unregister.load(Ordering::SeqCst) { self.unregister(&sender); restart = false; continue; } if !self.register(&sender, &unregister.clone()) { continue; } loop { if unregister.load(Ordering::SeqCst) { self.unregister(&sender); restart = false; break; } match receiver.recv_timeout(Duration::from_millis(1000)) { Ok(r) => { let message = match r { Ok(message) => message, Err(ReceiveError::DisconnectedError) => { info!("Trying to Reconnect"); break; } Err(err) => { error!("Error: {}", err); continue; } }; trace!("Message: {}", message.get_correlation_id()); match message.get_message_type() { Message_MessageType::TP_PROCESS_REQUEST => { let request = match TpProcessRequest::parse_from_bytes( &message.get_content(), ) { Ok(request) => request, Err(err) => { error!("Cannot parse TpProcessRequest: {}", err); continue; } }; let mut context = ZmqTransactionContext::new( request.get_context_id(), sender.clone(), ); let mut response = TpProcessResponse::new(); match self.handlers[0].apply(&request, &mut context) { Ok(()) => { info!("TP_PROCESS_REQUEST sending TpProcessResponse: OK"); response.set_status(TpProcessResponse_Status::OK); } Err(ApplyError::InvalidTransaction(msg)) => { info!( "TP_PROCESS_REQUEST sending TpProcessResponse: {}", &msg ); response.set_status( TpProcessResponse_Status::INVALID_TRANSACTION, ); response.set_message(msg); } Err(err) => { info!( "TP_PROCESS_REQUEST sending TpProcessResponse: {}", err ); response .set_status(TpProcessResponse_Status::INTERNAL_ERROR); response.set_message(err.to_string()); } }; let serialized = match response.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); continue; } }; match sender.reply( Message_MessageType::TP_PROCESS_RESPONSE, message.get_correlation_id(), &serialized, ) { Ok(_) => (), Err(SendError::DisconnectedError) => { error!("DisconnectedError"); break; } Err(SendError::TimeoutError) => error!("TimeoutError"), Err(SendError::UnknownError(e)) => { restart = false; error!("UnknownError: {}", e); break; } }; } Message_MessageType::PING_REQUEST => { trace!("sending PingResponse"); let response = PingResponse::new(); let serialized = match response.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); continue; } }; match sender.reply( Message_MessageType::PING_RESPONSE, message.get_correlation_id(), &serialized, ) { Ok(_) => (), Err(SendError::DisconnectedError) => { error!("DisconnectedError"); break; } Err(SendError::TimeoutError) => error!("TimeoutError"), Err(SendError::UnknownError(e)) => { restart = false; error!("UnknownError: {}", e); break; } }; } _ => { info!( "Transaction Processor recieved invalid message type: {:?}", message.get_message_type() ); } } } Err(RecvTimeoutError::Timeout) => (), Err(err) => { error!("Error: {}", err); } } } sender.close(); } } }
fn register(&mut self, sender: &ZmqMessageSender, unregister: &Arc<AtomicBool>) -> bool { for handler in &self.handlers { for version in handler.family_versions() { let mut request = TpRegisterRequest::new(); request.set_family(handler.family_name().clone()); request.set_version(version.clone()); request.set_namespaces(RepeatedField::from_vec(handler.namespaces().clone())); info!( "sending TpRegisterRequest: {} {}", &handler.family_name(), &version ); let serialized = match request.write_to_bytes() { Ok(serialized) => serialized, Err(err) => { error!("Serialization failed: {}", err); return false; } }; let x: &[u8] = &serialized; let mut future = match sender.send( Message_MessageType::TP_REGISTER_REQUEST, &generate_correlation_id(), x, ) { Ok(fut) => fut, Err(err) => { error!("Registration failed: {}", err); return false; } }; loop { match future.get_timeout(Duration::from_millis(10000)) { Ok(_) => break, Err(_) => { if unregister.load(Ordering::SeqCst) { return false; } } }; } } } true }
function_block-full_function
[ { "content": "pub fn create_context(algorithm_name: &str) -> Result<Box<dyn Context>, Error> {\n\n match algorithm_name {\n\n \"secp256k1\" => Ok(Box::new(secp256k1::Secp256k1Context::new())),\n\n _ => Err(Error::NoSuchAlgorithm(format!(\n\n \"no such algorithm: {}\",\n\n ...
Rust
client/telemetry/src/transport.rs
cruz101-hub/substrate
6e45ffaa4d2a2aa62405194890477985b94747cd
use futures::{ executor::block_on, prelude::*, ready, task::{Context, Poll}, }; use libp2p::{ core::transport::{timeout::TransportTimeout, OptionalTransport}, wasm_ext, Transport, }; use std::io; use std::pin::Pin; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); pub(crate) fn initialize_transport( wasm_external_transport: Option<wasm_ext::ExtTransport>, ) -> Result<WsTrans, io::Error> { let transport = match wasm_external_transport.clone() { Some(t) => OptionalTransport::some(t), None => OptionalTransport::none(), } .map((|inner, _| StreamSink::from(inner)) as fn(_, _) -> _); #[cfg(not(target_os = "unknown"))] let transport = transport.or_transport({ let inner = block_on(libp2p::dns::DnsConfig::system(libp2p::tcp::TcpConfig::new()))?; libp2p::websocket::framed::WsConfig::new(inner).and_then(|connec, _| { let connec = connec .with(|item| { let item = libp2p::websocket::framed::OutgoingData::Binary(item); future::ready(Ok::<_, io::Error>(item)) }) .try_filter(|item| future::ready(item.is_data())) .map_ok(|data| data.into_bytes()); future::ready(Ok::<_, io::Error>(connec)) }) }); Ok(TransportTimeout::new( transport.map(|out, _| { let out = out .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) .sink_map_err(|err| io::Error::new(io::ErrorKind::Other, err)); Box::pin(out) as Pin<Box<_>> }), CONNECT_TIMEOUT, ) .boxed()) } pub(crate) trait StreamAndSink<I>: Stream + Sink<I> {} impl<T: ?Sized + Stream + Sink<I>, I> StreamAndSink<I> for T {} pub(crate) type WsTrans = libp2p::core::transport::Boxed< Pin< Box< dyn StreamAndSink<Vec<u8>, Item = Result<Vec<u8>, io::Error>, Error = io::Error> + Send, >, >, >; #[pin_project::pin_project] pub(crate) struct StreamSink<T>(#[pin] T, Option<Vec<u8>>); impl<T> From<T> for StreamSink<T> { fn from(inner: T) -> StreamSink<T> { StreamSink(inner, None) } } impl<T: AsyncRead> Stream for StreamSink<T> { type Item = Result<Vec<u8>, io::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let this = self.project(); let mut buf = vec![0; 128]; match ready!(AsyncRead::poll_read(this.0, cx, &mut buf)) { Ok(0) => Poll::Ready(None), Ok(n) => { buf.truncate(n); Poll::Ready(Some(Ok(buf))) } Err(err) => Poll::Ready(Some(Err(err))), } } } impl<T: AsyncWrite> StreamSink<T> { fn poll_flush_buffer(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { let this = self.project(); if let Some(buffer) = this.1 { if ready!(this.0.poll_write(cx, &buffer[..]))? != buffer.len() { log::error!(target: "telemetry", "Detected some internal buffering happening in the telemetry"); let err = io::Error::new(io::ErrorKind::Other, "Internal buffering detected"); return Poll::Ready(Err(err)); } } *this.1 = None; Poll::Ready(Ok(())) } } impl<T: AsyncWrite> Sink<Vec<u8>> for StreamSink<T> { type Error = io::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(StreamSink::poll_flush_buffer(self, cx))?; Poll::Ready(Ok(())) } fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> { let this = self.project(); debug_assert!(this.1.is_none()); *this.1 = Some(item); Ok(()) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(self.as_mut().poll_flush_buffer(cx))?; let this = self.project(); AsyncWrite::poll_flush(this.0, cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(self.as_mut().poll_flush_buffer(cx))?; let this = self.project(); AsyncWrite::poll_close(this.0, cx) } }
use futures::{ executor::block_on, prelude::*, ready, task::{Context, Poll}, }; use libp2p::{ core::transport::{timeout::TransportTimeout, OptionalTransport}, wasm_ext, Transport, }; use std::io; use std::pin::Pin; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); pub(crate) fn initialize_transport( wasm_external_transport: Option<wasm_ext::ExtTransport>, ) -> Result<WsTrans, io::Error> { let transport = match wasm_external_transport.clone() { Some(t) => OptionalTransport::some(t), None => OptionalTransport::none(), } .map((|inner, _| StreamSink::from(inner)) as fn(_, _) -> _); #[cfg(not(target_os = "unknown"))] let transport = transport.or_transport({ let inner = block_on(libp2p::dns::DnsConfig::system(libp2p::tcp::TcpConfig::new()))?; libp2p::websocket::framed::WsConfig::new(inner).and_then(|connec, _| { let connec = connec .with(|item| { let item = libp2p::websocket::framed::OutgoingData::Binary(item); future::ready(Ok::<_, io::Error>(item)) }) .try_filter(|item| future::ready(item.is_data())) .map_ok(|data| data.into_bytes()); future::ready(Ok::<_, io::Error>(connec)) }) });
} pub(crate) trait StreamAndSink<I>: Stream + Sink<I> {} impl<T: ?Sized + Stream + Sink<I>, I> StreamAndSink<I> for T {} pub(crate) type WsTrans = libp2p::core::transport::Boxed< Pin< Box< dyn StreamAndSink<Vec<u8>, Item = Result<Vec<u8>, io::Error>, Error = io::Error> + Send, >, >, >; #[pin_project::pin_project] pub(crate) struct StreamSink<T>(#[pin] T, Option<Vec<u8>>); impl<T> From<T> for StreamSink<T> { fn from(inner: T) -> StreamSink<T> { StreamSink(inner, None) } } impl<T: AsyncRead> Stream for StreamSink<T> { type Item = Result<Vec<u8>, io::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> { let this = self.project(); let mut buf = vec![0; 128]; match ready!(AsyncRead::poll_read(this.0, cx, &mut buf)) { Ok(0) => Poll::Ready(None), Ok(n) => { buf.truncate(n); Poll::Ready(Some(Ok(buf))) } Err(err) => Poll::Ready(Some(Err(err))), } } } impl<T: AsyncWrite> StreamSink<T> { fn poll_flush_buffer(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), io::Error>> { let this = self.project(); if let Some(buffer) = this.1 { if ready!(this.0.poll_write(cx, &buffer[..]))? != buffer.len() { log::error!(target: "telemetry", "Detected some internal buffering happening in the telemetry"); let err = io::Error::new(io::ErrorKind::Other, "Internal buffering detected"); return Poll::Ready(Err(err)); } } *this.1 = None; Poll::Ready(Ok(())) } } impl<T: AsyncWrite> Sink<Vec<u8>> for StreamSink<T> { type Error = io::Error; fn poll_ready(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(StreamSink::poll_flush_buffer(self, cx))?; Poll::Ready(Ok(())) } fn start_send(self: Pin<&mut Self>, item: Vec<u8>) -> Result<(), Self::Error> { let this = self.project(); debug_assert!(this.1.is_none()); *this.1 = Some(item); Ok(()) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(self.as_mut().poll_flush_buffer(cx))?; let this = self.project(); AsyncWrite::poll_flush(this.0, cx) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Result<(), Self::Error>> { ready!(self.as_mut().poll_flush_buffer(cx))?; let this = self.project(); AsyncWrite::poll_close(this.0, cx) } }
Ok(TransportTimeout::new( transport.map(|out, _| { let out = out .map_err(|err| io::Error::new(io::ErrorKind::Other, err)) .sink_map_err(|err| io::Error::new(io::ErrorKind::Other, err)); Box::pin(out) as Pin<Box<_>> }), CONNECT_TIMEOUT, ) .boxed())
call_expression
[ { "content": "fn decl_runtime_version_impl_inner(item: ItemConst) -> Result<TokenStream> {\n\n\tlet runtime_version = ParseRuntimeVersion::parse_expr(&*item.expr)?.build(item.expr.span())?;\n\n\tlet link_section =\n\n\t\tgenerate_emit_link_section_decl(&runtime_version.encode(), \"runtime_version\");\n\n\n\n\tO...
Rust
tests/baking_mod/macros_baking/macro_choice.rs
julien-lange/mpst_rust_github
ca10d860f06d3bc4b6d1a9df290d2812235b456f
use either::Either; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::role::end::RoleEnd; use mpstthree::role::Role; use std::error::Error; use rand::{thread_rng, Rng}; use mpstthree::bundle_impl; bundle_impl!(MeshedChannels, A, B, C); type OfferMpst<S0, S1, S2, S3, R0, R1, N0> = Recv<Either<MeshedChannels<S0, S1, R0, N0>, MeshedChannels<S2, S3, R1, N0>>, End>; type ChooseMpst<S0, S1, S2, S3, R0, R1, N0> = Send< Either< MeshedChannels< <S0 as Session>::Dual, <S1 as Session>::Dual, <R0 as Role>::Dual, <N0 as Role>::Dual, >, MeshedChannels< <S2 as Session>::Dual, <S3 as Session>::Dual, <R1 as Role>::Dual, <N0 as Role>::Dual, >, >, End, >; type AtoCClose = End; type AtoBClose = End; type AtoCVideo<N> = Recv<N, Send<N, End>>; type AtoBVideo<N> = Send<N, Recv<N, End>>; type BtoAClose = <AtoBClose as Session>::Dual; type BtoCClose = End; type BtoAVideo<N> = <AtoBVideo<N> as Session>::Dual; type CtoBClose = <BtoCClose as Session>::Dual; type CtoAClose = <AtoCClose as Session>::Dual; type CtoAVideo<N> = <AtoCVideo<N> as Session>::Dual; type StackAEnd = RoleEnd; type StackAVideo = RoleC<RoleB<RoleB<RoleC<RoleEnd>>>>; type StackAVideoDual = <StackAVideo as Role>::Dual; type StackAFull = RoleC<RoleC<RoleAlltoC<RoleEnd, RoleEnd>>>; type StackBEnd = RoleEnd; type StackBVideo = RoleA<RoleA<RoleEnd>>; type StackBVideoDual = <StackBVideo as Role>::Dual; type StackBFull = RoleAlltoC<RoleEnd, RoleEnd>; type StackCEnd = RoleEnd; type StackCVideo = RoleA<RoleA<RoleEnd>>; type StackCChoice = RoleCtoAll<StackCVideo, StackCEnd>; type StackCFull = RoleA<RoleA<StackCChoice>>; type ChooseCtoA<N> = ChooseMpst< BtoAVideo<N>, CtoAVideo<N>, BtoAClose, CtoAClose, StackAVideoDual, StackAEnd, RoleADual<RoleEnd>, >; type ChooseCtoB<N> = ChooseMpst< AtoBVideo<N>, CtoBClose, AtoBClose, CtoBClose, StackBVideoDual, StackBEnd, RoleBDual<RoleEnd>, >; type InitC<N> = Send<N, Recv<N, ChooseCtoA<N>>>; type EndpointCFull<N> = MeshedChannels<InitC<N>, ChooseCtoB<N>, StackCFull, RoleC<RoleEnd>>; type EndpointAVideo<N> = MeshedChannels<AtoBVideo<N>, AtoCVideo<N>, StackAVideo, RoleA<RoleEnd>>; type EndpointAEnd = MeshedChannels<AtoBClose, AtoCClose, StackAEnd, RoleA<RoleEnd>>; type OfferA<N> = OfferMpst< AtoBVideo<N>, AtoCVideo<N>, AtoBClose, AtoCClose, StackAVideo, StackAEnd, RoleA<RoleEnd>, >; type InitA<N> = Recv<N, Send<N, OfferA<N>>>; type EndpointAFull<N> = MeshedChannels<End, InitA<N>, StackAFull, RoleA<RoleEnd>>; type EndpointBVideo<N> = MeshedChannels<BtoAVideo<N>, BtoCClose, StackBVideo, RoleB<RoleEnd>>; type EndpointBEnd = MeshedChannels<BtoAClose, BtoCClose, StackBEnd, RoleB<RoleEnd>>; type OfferB<N> = OfferMpst< BtoAVideo<N>, BtoCClose, BtoAClose, BtoCClose, StackBVideo, StackBEnd, RoleB<RoleEnd>, >; type EndpointBFull<N> = MeshedChannels<End, OfferB<N>, StackBFull, RoleB<RoleEnd>>; fn server(s: EndpointBFull<i32>) -> Result<(), Box<dyn Error>> { s.offer( |s: EndpointBVideo<i32>| { let (request, s) = s.recv()?; s.send(request + 1).close() }, |s: EndpointBEnd| s.close(), ) } fn authenticator(s: EndpointAFull<i32>) -> Result<(), Box<dyn Error>> { let (id, s) = s.recv()?; s.send(id + 1).offer( |s: EndpointAVideo<i32>| { let (request, s) = s.recv()?; let (video, s) = s.send(request + 1).recv()?; assert_eq!(request, id + 1); assert_eq!(video, id + 3); s.send(video + 1).close() }, |s: EndpointAEnd| s.close(), ) } fn client_video(s: EndpointCFull<i32>) -> Result<(), Box<dyn Error>> { let mut rng = thread_rng(); let id: i32 = rng.gen(); let (accept, s) = s.send(id).recv()?; assert_eq!(accept, id + 1); let (result, s) = s.choose_left().send(accept).recv()?; assert_eq!(result, accept + 3); s.close() } fn client_close(s: EndpointCFull<i32>) -> Result<(), Box<dyn Error>> { let mut rng = thread_rng(); let id: i32 = rng.gen(); let (accept, s) = s.send(id).recv()?; assert_eq!(accept, id + 1); s.choose_right().close() } pub fn run_usecase_right() { assert!(|| -> Result<(), Box<dyn Error>> { { let (thread_a, thread_b, thread_c) = fork_mpst(authenticator, server, client_close); assert!(thread_a.join().is_ok()); assert!(thread_b.join().is_ok()); assert!(thread_c.join().is_ok()); } Ok(()) }() .is_ok()); } pub fn run_usecase_left() { assert!(|| -> Result<(), Box<dyn Error>> { { let (thread_a, thread_b, thread_c) = fork_mpst(authenticator, server, client_video); assert!(thread_a.join().is_ok()); assert!(thread_b.join().is_ok()); assert!(thread_c.join().is_ok()); } Ok(()) }() .is_ok()); }
use either::Either; use mpstthree::binary::struct_trait::{end::End, recv::Recv, send::Send, session::Session}; use mpstthree::role::end::RoleEnd; use mpstthree::role::Role; use std::error::Error; use rand::{thread_rng, Rng}; use mpstthree::bundle_impl; bundle_impl!(MeshedChannels, A, B, C); type OfferMpst<S0, S1, S2, S3, R0, R1, N0> = Recv<Either<MeshedChannels<S0, S1, R0, N0>, MeshedChannels<S2, S3, R1, N0>>, End>; type ChooseMpst<S0, S1, S2, S3, R0, R1, N0> = Send< Either< MeshedChannels< <S0 as Session>::Dual, <S1 as Session>::Dual, <R0 as Role>::Dual, <N0 as Role>::Dual, >, MeshedChannels< <S2 as Session>::Dual, <S3 as Session>::Dual, <R1 as Role>::Dual, <N0 as Role>::Dual, >, >, End, >; type AtoCClose = End; type AtoBClose = End; type AtoCVideo<N> = Recv<N, Send<N, End>>; type AtoBVideo<N> = Send<N, Recv<N, End>>; type BtoAClose = <AtoBClose as Session>::Dual; type BtoCClose = End; type BtoAVideo<N> = <AtoBVideo<N> as Session>::Dual; type CtoBClose = <BtoCClose as Session>::Dual; type CtoAClose = <AtoCClose as Session>::Dual; type CtoAVideo<N> = <AtoCVideo<N> as Session>::Dual; type StackAEnd = RoleEnd; t
tackAEnd, RoleA<RoleEnd>>; type OfferA<N> = OfferMpst< AtoBVideo<N>, AtoCVideo<N>, AtoBClose, AtoCClose, StackAVideo, StackAEnd, RoleA<RoleEnd>, >; type InitA<N> = Recv<N, Send<N, OfferA<N>>>; type EndpointAFull<N> = MeshedChannels<End, InitA<N>, StackAFull, RoleA<RoleEnd>>; type EndpointBVideo<N> = MeshedChannels<BtoAVideo<N>, BtoCClose, StackBVideo, RoleB<RoleEnd>>; type EndpointBEnd = MeshedChannels<BtoAClose, BtoCClose, StackBEnd, RoleB<RoleEnd>>; type OfferB<N> = OfferMpst< BtoAVideo<N>, BtoCClose, BtoAClose, BtoCClose, StackBVideo, StackBEnd, RoleB<RoleEnd>, >; type EndpointBFull<N> = MeshedChannels<End, OfferB<N>, StackBFull, RoleB<RoleEnd>>; fn server(s: EndpointBFull<i32>) -> Result<(), Box<dyn Error>> { s.offer( |s: EndpointBVideo<i32>| { let (request, s) = s.recv()?; s.send(request + 1).close() }, |s: EndpointBEnd| s.close(), ) } fn authenticator(s: EndpointAFull<i32>) -> Result<(), Box<dyn Error>> { let (id, s) = s.recv()?; s.send(id + 1).offer( |s: EndpointAVideo<i32>| { let (request, s) = s.recv()?; let (video, s) = s.send(request + 1).recv()?; assert_eq!(request, id + 1); assert_eq!(video, id + 3); s.send(video + 1).close() }, |s: EndpointAEnd| s.close(), ) } fn client_video(s: EndpointCFull<i32>) -> Result<(), Box<dyn Error>> { let mut rng = thread_rng(); let id: i32 = rng.gen(); let (accept, s) = s.send(id).recv()?; assert_eq!(accept, id + 1); let (result, s) = s.choose_left().send(accept).recv()?; assert_eq!(result, accept + 3); s.close() } fn client_close(s: EndpointCFull<i32>) -> Result<(), Box<dyn Error>> { let mut rng = thread_rng(); let id: i32 = rng.gen(); let (accept, s) = s.send(id).recv()?; assert_eq!(accept, id + 1); s.choose_right().close() } pub fn run_usecase_right() { assert!(|| -> Result<(), Box<dyn Error>> { { let (thread_a, thread_b, thread_c) = fork_mpst(authenticator, server, client_close); assert!(thread_a.join().is_ok()); assert!(thread_b.join().is_ok()); assert!(thread_c.join().is_ok()); } Ok(()) }() .is_ok()); } pub fn run_usecase_left() { assert!(|| -> Result<(), Box<dyn Error>> { { let (thread_a, thread_b, thread_c) = fork_mpst(authenticator, server, client_video); assert!(thread_a.join().is_ok()); assert!(thread_b.join().is_ok()); assert!(thread_c.join().is_ok()); } Ok(()) }() .is_ok()); }
ype StackAVideo = RoleC<RoleB<RoleB<RoleC<RoleEnd>>>>; type StackAVideoDual = <StackAVideo as Role>::Dual; type StackAFull = RoleC<RoleC<RoleAlltoC<RoleEnd, RoleEnd>>>; type StackBEnd = RoleEnd; type StackBVideo = RoleA<RoleA<RoleEnd>>; type StackBVideoDual = <StackBVideo as Role>::Dual; type StackBFull = RoleAlltoC<RoleEnd, RoleEnd>; type StackCEnd = RoleEnd; type StackCVideo = RoleA<RoleA<RoleEnd>>; type StackCChoice = RoleCtoAll<StackCVideo, StackCEnd>; type StackCFull = RoleA<RoleA<StackCChoice>>; type ChooseCtoA<N> = ChooseMpst< BtoAVideo<N>, CtoAVideo<N>, BtoAClose, CtoAClose, StackAVideoDual, StackAEnd, RoleADual<RoleEnd>, >; type ChooseCtoB<N> = ChooseMpst< AtoBVideo<N>, CtoBClose, AtoBClose, CtoBClose, StackBVideoDual, StackBEnd, RoleBDual<RoleEnd>, >; type InitC<N> = Send<N, Recv<N, ChooseCtoA<N>>>; type EndpointCFull<N> = MeshedChannels<InitC<N>, ChooseCtoB<N>, StackCFull, RoleC<RoleEnd>>; type EndpointAVideo<N> = MeshedChannels<AtoBVideo<N>, AtoCVideo<N>, StackAVideo, RoleA<RoleEnd>>; type EndpointAEnd = MeshedChannels<AtoBClose, AtoCClose, S
random
[ { "content": "type ChooseMpstThree<S0, S1, S2, S3, R0, R1, N0> = Send<\n\n Either<\n\n MeshedChannels<\n\n <S0 as Session>::Dual,\n\n <S1 as Session>::Dual,\n\n <R0 as Role>::Dual,\n\n <N0 as Role>::Dual,\n\n >,\n\n MeshedChannels<\n\n ...
Rust
src/managers/memory.rs
aajtodd/riam
2b72f7d2eb5bac184631c2926f41629a44de6fd5
use crate::{Policy, PolicyManager, Result, RiamError}; use std::collections::HashMap; use std::collections::HashSet; use uuid::Uuid; pub struct MemoryManager { by_principal: HashMap<String, HashSet<Uuid>>, by_id: HashMap<Uuid, Policy>, } impl MemoryManager { pub fn new() -> Self { MemoryManager { by_principal: HashMap::new(), by_id: HashMap::new(), } } } impl PolicyManager for MemoryManager { fn create(&mut self, mut policy: Policy) -> Result<Uuid> { if !policy.is_valid() { return Err(RiamError::InvalidPolicy); } let id = Uuid::new_v4(); policy.id = Some(id); self.by_id.insert(id, policy); Ok(id) } fn update(&mut self, policy: &Policy) -> Result<()> { match policy.id { Some(id) => match self.by_id.get_mut(&id) { Some(p) => { *p = policy.clone(); } None => return Err(RiamError::UnknownPolicy), }, None => return Err(RiamError::InvalidPolicy), } Ok(()) } fn get(&self, id: &Uuid) -> Result<&Policy> { if let Some(p) = self.by_id.get(&id) { return Ok(p); } Err(RiamError::UnknownPolicy) } fn delete(&mut self, id: &Uuid) -> Result<()> { if let Some(_) = self.by_id.remove(&id) { self.by_principal.retain(|_principal, pset| { pset.remove(&id); return pset.len() > 0; }) } else { return Err(RiamError::UnknownPolicy); } Ok(()) } fn list(&self) -> Result<Vec<Policy>> { Ok(Vec::new()) } fn get_policies_for_principal(&self, principal: &str) -> Result<Option<Vec<Policy>>> { if let Some(policy_ids) = self.by_principal.get(principal) { let mut policies: Vec<Policy> = Vec::with_capacity(policy_ids.len()); for id in policy_ids { let p = self.by_id.get(id).unwrap(); policies.push(p.clone()); } return Ok(Some(policies)); } Ok(None) } fn attach(&mut self, principal: &str, id: &Uuid) -> Result<()> { self.by_principal .entry(principal.to_owned()) .or_insert(HashSet::new()) .insert(*id); Ok(()) } fn detach(&mut self, principal: &str, id: &Uuid) -> Result<()> { if let Some(pset) = self.by_principal.get_mut(principal) { pset.remove(id); if pset.len() == 0 { self.by_principal.remove(principal); } } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_memory_manager_attach_detach() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let policy: Policy = serde_json::from_str(jsp).unwrap(); let id = mgr.create(policy).unwrap(); let principal = "user:test-user"; mgr.attach(principal, &id).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 1); mgr.detach(principal, &id).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap(); assert_eq!(actual.is_none(), true); } #[test] fn test_memory_manager_update() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let policy: Policy = serde_json::from_str(jsp).unwrap(); let id = mgr.create(policy).unwrap(); let mut policy = mgr.get(&id).unwrap().clone(); assert_eq!(policy.name, Some("Account policy".to_owned())); policy.name = Some("Modified Name".to_owned()); mgr.update(&policy).unwrap(); let policy = mgr.get(&id).unwrap().clone(); assert_eq!(policy.name, Some("Modified Name".to_owned())); } #[test] fn test_memory_manager_delete() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let p1: Policy = serde_json::from_str(jsp).unwrap(); let id1 = mgr.create(p1).unwrap(); let jsp = r#" { "name": "Blog policy", "statements": [ { "sid": "Deny blog access", "effect": "deny", "actions": ["blog:list"], "resources": ["resource:blog:*"] } ] } "#; let p2: Policy = serde_json::from_str(jsp).unwrap(); let id2 = mgr.create(p2).unwrap(); let principal = "users:test-user"; mgr.attach(principal, &id1).unwrap(); mgr.attach(principal, &id2).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 2); mgr.delete(&id1).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 1); } }
use crate::{Policy, PolicyManager, Result, RiamError}; use std::collections::HashMap; use std::collections::HashSet; use uuid::Uuid; pub struct MemoryManager { by_principal: HashMap<String, HashSet<Uuid>>, by_id: HashMap<Uuid, Policy>, } impl MemoryManager { pub fn new() -> Self { MemoryManager { by_principal: HashMap::new(), by_id: HashMap::new(), } } } impl PolicyManager for MemoryManager { fn create(&mut self, mut policy: Policy) -> Result<Uuid> { if !policy.is_valid() { return Err(RiamError::InvalidPolicy); } let id = Uuid::new_v4(); policy.id = Some(id); self.by_id.insert(id, policy); Ok(id) } fn update(&mut self, policy: &Policy) -> Result<()> { match policy.id { Some(id) => match self.by_id.get_mut(&id) { Some(p) => { *p = policy.clone(); } None => return Err(RiamError::UnknownPolicy), }, None => return Err(RiamError::InvalidPolicy), } Ok(()) } fn get(&self, id: &Uuid) -> Result<&Policy> { if let Some(p) = self.by_id.get(&id) { return Ok(p); } Err(RiamError::UnknownPolicy) } fn delete(&mut self, id: &Uuid) -> Result<()> { if let Some(_) = self.by_id.rem
fn list(&self) -> Result<Vec<Policy>> { Ok(Vec::new()) } fn get_policies_for_principal(&self, principal: &str) -> Result<Option<Vec<Policy>>> { if let Some(policy_ids) = self.by_principal.get(principal) { let mut policies: Vec<Policy> = Vec::with_capacity(policy_ids.len()); for id in policy_ids { let p = self.by_id.get(id).unwrap(); policies.push(p.clone()); } return Ok(Some(policies)); } Ok(None) } fn attach(&mut self, principal: &str, id: &Uuid) -> Result<()> { self.by_principal .entry(principal.to_owned()) .or_insert(HashSet::new()) .insert(*id); Ok(()) } fn detach(&mut self, principal: &str, id: &Uuid) -> Result<()> { if let Some(pset) = self.by_principal.get_mut(principal) { pset.remove(id); if pset.len() == 0 { self.by_principal.remove(principal); } } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_memory_manager_attach_detach() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let policy: Policy = serde_json::from_str(jsp).unwrap(); let id = mgr.create(policy).unwrap(); let principal = "user:test-user"; mgr.attach(principal, &id).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 1); mgr.detach(principal, &id).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap(); assert_eq!(actual.is_none(), true); } #[test] fn test_memory_manager_update() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let policy: Policy = serde_json::from_str(jsp).unwrap(); let id = mgr.create(policy).unwrap(); let mut policy = mgr.get(&id).unwrap().clone(); assert_eq!(policy.name, Some("Account policy".to_owned())); policy.name = Some("Modified Name".to_owned()); mgr.update(&policy).unwrap(); let policy = mgr.get(&id).unwrap().clone(); assert_eq!(policy.name, Some("Modified Name".to_owned())); } #[test] fn test_memory_manager_delete() { let mut mgr = MemoryManager::new(); let jsp = r#" { "name": "Account policy", "statements": [ { "sid": "Grant account access", "effect": "allow", "actions": ["account:list", "account:get"], "resources": ["resource:account:1235"] } ] } "#; let p1: Policy = serde_json::from_str(jsp).unwrap(); let id1 = mgr.create(p1).unwrap(); let jsp = r#" { "name": "Blog policy", "statements": [ { "sid": "Deny blog access", "effect": "deny", "actions": ["blog:list"], "resources": ["resource:blog:*"] } ] } "#; let p2: Policy = serde_json::from_str(jsp).unwrap(); let id2 = mgr.create(p2).unwrap(); let principal = "users:test-user"; mgr.attach(principal, &id1).unwrap(); mgr.attach(principal, &id2).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 2); mgr.delete(&id1).unwrap(); let actual = mgr.get_policies_for_principal(principal).unwrap().unwrap(); assert_eq!(actual.len(), 1); } }
ove(&id) { self.by_principal.retain(|_principal, pset| { pset.remove(&id); return pset.len() > 0; }) } else { return Err(RiamError::UnknownPolicy); } Ok(()) }
function_block-function_prefixed
[ { "content": "// custom serialize for Vec<String> for policy statements. If the vec length is\n\n// 1 the output will be flattened to just that single string. Otherwise it will\n\n// serialize normally to a sequence\n\n// e.g.\n\n// vec![\"actions:list\"] -> \"actions:list\"\n\n// vec![\"actions:list\", \"actio...
Rust
src/hir/constructor2enum.rs
KeenS/webml
60f4d899d623d5872c325412054bd0d77e37c4aa
use crate::config::Config; use crate::hir::util::Transform; use crate::hir::*; use crate::pass::Pass; use std::collections::{HashMap, HashSet}; pub struct ConstructorToEnumPass { enum_likes: HashSet<Symbol>, symbol_table: SymbolTable, } fn rewrite_ty(enum_likes: &HashSet<Symbol>, ty: HTy) -> HTy { use HTy::*; match ty { Datatype(name) if enum_likes.contains(&name) => HTy::Int, Fun(arg, ret) => Fun( Box::new(rewrite_ty(enum_likes, *arg)), Box::new(rewrite_ty(enum_likes, *ret)), ), Tuple(tuple) => Tuple( tuple .into_iter() .map(|t| rewrite_ty(enum_likes, t)) .collect(), ), ty => ty, } } impl ConstructorToEnumPass { fn new(symbol_table: SymbolTable) -> Self { let (enum_likes, types) = symbol_table .types .into_iter() .partition::<HashMap<Symbol, TypeInfo>, _>(|(_, type_info)| { type_info.constructors.iter().all(|(_, arg)| arg.is_none()) }); let enum_likes = enum_likes.into_iter().map(|(name, _)| name).collect(); let types = types .into_iter() .map(|(name, mut type_info)| { type_info.constructors = type_info .constructors .into_iter() .map(|(descriminant, argty)| match argty { Some(ty) => (descriminant, Some(rewrite_ty(&enum_likes, ty))), argty @ None => (descriminant, argty), }) .collect(); (name, type_info) }) .collect(); let symbol_table = SymbolTable { types }; let mut this = Self { enum_likes, symbol_table, }; this.rewrite_table(); this } fn rewrite_table(&mut self) {} fn is_enum_like(&self, name: &Symbol) -> bool { self.enum_likes.contains(name) } fn rewrite_ty(&self, ty: HTy) -> HTy { rewrite_ty(&self.enum_likes, ty) } } impl Transform for ConstructorToEnumPass { fn transform_val(&mut self, mut val: Val) -> Val { val.ty = self.rewrite_ty(val.ty); val.expr = self.transform_expr(val.expr); val } fn transform_binds(&mut self, ty: HTy, bind: Box<Val>, ret: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::Let { ty, bind: Box::new(self.transform_val(*bind)), ret: Box::new(self.transform_expr(*ret)), } } fn transform_fun( &mut self, param: (HTy, Symbol), body_ty: HTy, body: Box<Expr>, captures: Vec<(HTy, Symbol)>, ) -> Expr { let (param_ty, param) = param; let param_ty = self.rewrite_ty(param_ty); let param = (param_ty, param); let body_ty = self.rewrite_ty(body_ty); let captures = captures .into_iter() .map(|(ty, name)| (self.rewrite_ty(ty), name)) .collect(); Expr::Fun { param, body_ty, captures, body: Box::new(self.transform_expr(*body)), } } fn transform_closure( &mut self, envs: Vec<(HTy, Symbol)>, param_ty: HTy, body_ty: HTy, fname: Symbol, ) -> Expr { let envs = envs .into_iter() .map(|(ty, name)| (self.rewrite_ty(ty), name)) .collect(); let param_ty = self.rewrite_ty(param_ty); let body_ty = self.rewrite_ty(body_ty); Expr::Closure { envs, param_ty, body_ty, fname, } } fn transform_builtin_call(&mut self, ty: HTy, fun: BIF, args: Vec<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::BuiltinCall { ty, fun, args: args .into_iter() .map(|arg| self.transform_expr(arg)) .collect(), } } fn transform_extern_call( &mut self, ty: HTy, module: String, fun: String, args: Vec<Expr>, ) -> Expr { let ty = self.rewrite_ty(ty); Expr::ExternCall { ty, module, fun, args: args .into_iter() .map(|arg| self.transform_expr(arg)) .collect(), } } fn transform_app(&mut self, ty: HTy, fun: Box<Expr>, arg: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::App { ty, fun: Box::new(self.transform_expr(*fun)), arg: Box::new(self.transform_expr(*arg)), } } fn transform_case(&mut self, ty: HTy, cond: Box<Expr>, arms: Vec<(Pattern, Expr)>) -> Expr { let ty = self.rewrite_ty(ty); let mut arms = arms; arms = arms .into_iter() .map(|(pat, expr)| { use Pattern::*; let pat = match pat { Constant { value, ty } => { let ty = self.rewrite_ty(ty); Constant { value, ty } } Char { value, ty } => { let ty = self.rewrite_ty(ty); Char { value, ty } } Tuple { tys, tuple } => { let tys = tys.into_iter().map(|ty| self.rewrite_ty(ty)).collect(); Tuple { tys, tuple } } Constructor { descriminant, ty, arg, } => match ty { HTy::Datatype(name) if self.is_enum_like(&name) => Constant { ty: HTy::Int, value: descriminant as i64, }, ty => Constructor { descriminant, ty, arg, }, }, Var { name, ty } => Var { name, ty: self.rewrite_ty(ty), }, }; (pat, expr) }) .collect(); Expr::Case { ty, expr: Box::new(self.transform_expr(*cond)), arms: arms .into_iter() .map(|(pat, expr)| (pat, self.transform_expr(expr))) .collect(), } } fn transform_tuple(&mut self, tys: Vec<HTy>, tuple: Vec<Expr>) -> Expr { let tys = tys.into_iter().map(|ty| self.rewrite_ty(ty)).collect(); Expr::Tuple { tys, tuple: tuple.into_iter().map(|e| self.transform_expr(e)).collect(), } } fn transform_proj(&mut self, ty: HTy, index: u32, tuple: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::Proj { ty, index, tuple: Box::new(self.transform_expr(*tuple)), } } fn transform_constructor( &mut self, ty: HTy, arg: Option<Box<Expr>>, descriminant: u32, ) -> Expr { let name = match &ty { HTy::Datatype(name) => name, _ => unreachable!(), }; if self.is_enum_like(name) { Expr::Lit { ty: HTy::Int, value: Literal::Int(descriminant as i64), } } else { Expr::Constructor { ty, arg, descriminant, } } } fn transform_sym(&mut self, ty: HTy, name: Symbol) -> Expr { let ty = self.rewrite_ty(ty); Expr::Sym { ty, name } } fn transform_lit(&mut self, ty: HTy, value: Literal) -> Expr { let ty = self.rewrite_ty(ty); Expr::Lit { ty, value } } } pub struct ConstructorToEnum {} impl ConstructorToEnum { pub fn new() -> Self { Self {} } } impl<E> Pass<Context, E> for ConstructorToEnum { type Target = Context; fn trans( &mut self, Context(symbol_table, hir): Context, _: &Config, ) -> ::std::result::Result<Self::Target, E> { let mut pass = ConstructorToEnumPass::new(symbol_table); let hir = pass.transform_hir(hir); let symbol_table = pass.symbol_table; Ok(Context(symbol_table, hir)) } }
use crate::config::Config; use crate::hir::util::Transform; use crate::hir::*; use crate::pass::Pass; use std::collections::{HashMap, HashSet}; pub struct ConstructorToEnumPass { enum_likes: HashSet<Symbol>, symbol_table: SymbolTable, } fn rewrite_ty(enum_likes: &HashSet<Symbol>, ty: HTy) -> HTy { use HTy::*; match ty { Datatype(name) if enum_likes.contains(&name) => HTy::Int, Fun(arg, ret) => Fun( Box::new(rewrite_ty(enum_likes, *arg)), Box::new(rewrite_ty(enum_likes, *ret)), ), Tuple(tuple) => Tuple( tuple .into_iter() .map(|t| rewrite_ty(enum_likes, t)) .collect(), ), ty => ty, } } impl ConstructorToEnumPass { fn new(symbol_table: SymbolTable) -> Self { let (enum_likes, types) = symbol_table .types .into_iter() .partition::<HashMap<Symbol, TypeInfo>, _>(|(_, type_info)| { type_info.constructors.iter().all(|(_, arg)| arg.is_none()) }); let enum_likes = enum_likes.into_iter().map(|(name, _)| name).collect(); let types = types .into_iter() .map(|(name, mut type_info)| { type_info.constructors = type_info .constructors .into_iter() .map(|(descriminant, argty)| match argty { Some(ty) => (descriminant, Some(rewrite_ty(&enum_likes, ty))), argty @ None => (descriminant, argty), }) .collect(); (name, type_info) }) .collect(); let symbol_table = SymbolTable { types }; let mut this = Self { enum_likes, symbol_table, }; this.rewrite_table(); this } fn rewrite_table(&mut self) {} fn is_enum_like(&self, name: &Symbol) -> bool { self.enum_likes.contains(name) } fn rewrite_ty(&self, ty: HTy) -> HTy { rewrite_ty(&self.enum_likes, ty) } } impl Transform for ConstructorToEnumPass { fn transform_val(&mut self, mut val: Val) -> Val { val.ty = self.rewrite_ty(val.ty); val.expr = self.transform_expr(val.expr); val } fn transform_binds(&mut self, ty: HTy, bind: Box<Val>, ret: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::Let { ty, bind: Box::new(self.transform_val(*bind)), ret: Box::new(self.transform_expr(*ret)), } } fn transform_fun( &mut self, param: (HTy, Symbol), body_ty: HTy, body: Box<Expr>, captures: Vec<(HTy, Symbol)>, ) -> Expr { let (param_ty, param) = param; let param_ty = self.rewrite_ty(param_ty); let param = (param_ty, param); let body_ty = self.rewrite_ty(body_ty); let captures = captures .into_iter() .map(|(ty, name)| (self.rewrite_ty(ty), name)) .collect(); Expr::Fun { param, body_ty, captures, body: Box::new(self.transform_expr(*body)), } } fn transform_closure( &mut self, envs: Vec<(HTy, Symbol)>, param_ty: HTy, body_ty: HTy, fname: Symbol, ) -> Expr { let envs = envs .into_iter() .map(|(ty, name)| (self.rewrite_ty(ty), name)) .collect(); let param_ty = self.rewrite_ty(param_ty); let body_ty = self.rewrite_ty(body_ty); Expr::Closure { envs, param_ty, body_ty, fname, } } fn transform_builtin_call(&mut self, ty: HTy, fun: BIF, args: Vec<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::BuiltinCall { ty, fun, args: args .into_iter() .map(|arg| self.transform_expr(arg)) .collect(), } } fn transform_extern_call( &mut self, ty: HTy, module: String, fun: String, args: Vec<Expr>, ) -> Expr { let ty = self.rewrite_ty(ty); Expr::ExternCall { ty, module, fun, args: args .into_iter() .map(|arg| self.transform_expr(arg)) .collect(), } } fn transform_app(&mut self, ty: HTy, fun: Box<Expr>, arg: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::App { ty, fun: Box::new(self.transform_expr(*fun)), arg: Box::new(self.transform_expr(*arg)), } } fn transform_case(&mut self, ty: HTy, cond: Box<Expr>, arms: Vec<(Pattern, Expr)>) -> Expr { let ty = self.rewrite_ty(ty); let mut arms = arms; arms = arms .into_iter() .map(|(pat, expr)| { use Pattern::*; let pat = match pat { Constant { value, ty } => { let ty = self.rewrite_ty(ty); Constant { value, ty } } Char { value, ty } => { let ty = self.rewrite_ty(ty); Char { value, ty } } Tuple { tys, tuple } => { let tys = tys.into_iter().map(|ty| self.rewrite_ty(ty)).collect(); Tuple { tys, tuple } } Constructor { descriminant, ty, arg, } =>
, Var { name, ty } => Var { name, ty: self.rewrite_ty(ty), }, }; (pat, expr) }) .collect(); Expr::Case { ty, expr: Box::new(self.transform_expr(*cond)), arms: arms .into_iter() .map(|(pat, expr)| (pat, self.transform_expr(expr))) .collect(), } } fn transform_tuple(&mut self, tys: Vec<HTy>, tuple: Vec<Expr>) -> Expr { let tys = tys.into_iter().map(|ty| self.rewrite_ty(ty)).collect(); Expr::Tuple { tys, tuple: tuple.into_iter().map(|e| self.transform_expr(e)).collect(), } } fn transform_proj(&mut self, ty: HTy, index: u32, tuple: Box<Expr>) -> Expr { let ty = self.rewrite_ty(ty); Expr::Proj { ty, index, tuple: Box::new(self.transform_expr(*tuple)), } } fn transform_constructor( &mut self, ty: HTy, arg: Option<Box<Expr>>, descriminant: u32, ) -> Expr { let name = match &ty { HTy::Datatype(name) => name, _ => unreachable!(), }; if self.is_enum_like(name) { Expr::Lit { ty: HTy::Int, value: Literal::Int(descriminant as i64), } } else { Expr::Constructor { ty, arg, descriminant, } } } fn transform_sym(&mut self, ty: HTy, name: Symbol) -> Expr { let ty = self.rewrite_ty(ty); Expr::Sym { ty, name } } fn transform_lit(&mut self, ty: HTy, value: Literal) -> Expr { let ty = self.rewrite_ty(ty); Expr::Lit { ty, value } } } pub struct ConstructorToEnum {} impl ConstructorToEnum { pub fn new() -> Self { Self {} } } impl<E> Pass<Context, E> for ConstructorToEnum { type Target = Context; fn trans( &mut self, Context(symbol_table, hir): Context, _: &Config, ) -> ::std::result::Result<Self::Target, E> { let mut pass = ConstructorToEnumPass::new(symbol_table); let hir = pass.transform_hir(hir); let symbol_table = pass.symbol_table; Ok(Context(symbol_table, hir)) } }
match ty { HTy::Datatype(name) if self.is_enum_like(&name) => Constant { ty: HTy::Int, value: descriminant as i64, }, ty => Constructor { descriminant, ty, arg, }, }
if_condition
[ { "content": "fn take_binds(expr: Expr) -> (Expr, Vec<Val>) {\n\n use crate::hir::Expr::*;\n\n match expr {\n\n Let { bind, ret, .. } => {\n\n let (expr, mut binds) = take_binds(*ret);\n\n binds.insert(0, *bind);\n\n (expr, binds)\n\n }\n\n BuiltinCall...
Rust
tests/delete_component.rs
colelawrence/shipyard
bd535706a4ec53f5162e4aae6b8c9480e5f8bc75
use core::any::type_name; use shipyard::error; use shipyard::internal::iterators; use shipyard::prelude::*; #[test] fn no_pack() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); usizes.delete(entity1); assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); } #[test] fn tight() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); (&mut usizes, &mut u32s).tight_pack(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); Delete::<(usize,)>::delete((&mut usizes, &mut u32s), entity1); assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); let iter = (&usizes, &u32s).iter(); if let iterators::Iter2::Tight(mut iter) = iter { assert_eq!(iter.next(), Some((&2, &3))); assert_eq!(iter.next(), None); } else { panic!("not packed"); } } #[test] fn loose() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); (&mut usizes, &mut u32s).loose_pack(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); Delete::<(usize,)>::delete((&mut usizes, &mut u32s), entity1); assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); let mut iter = (&usizes, &u32s).iter(); assert_eq!(iter.next(), Some((&2, &3))); assert_eq!(iter.next(), None); } #[test] fn tight_loose() { let world = World::new(); let (mut entities, mut usizes, mut u64s, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u64, &mut u32)>(); (&mut usizes, &mut u64s).tight_pack(); LoosePack::<(u32,)>::loose_pack((&mut u32s, &mut usizes, &mut u64s)); let entity1 = entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (0, 1, 2)); let entity2 = entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (3, 4, 5)); entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (6, 7, 8)); Delete::<(u32,)>::delete((&mut u32s, &mut usizes, &mut u64s), entity1); let mut iter = (&usizes, &u64s).iter(); assert_eq!(iter.next(), Some((&0, &1))); assert_eq!(iter.next(), Some((&3, &4))); assert_eq!(iter.next(), Some((&6, &7))); assert_eq!(iter.next(), None); let iter = (&usizes, &u64s, &u32s).iter(); if let iterators::Iter3::Loose(mut iter) = iter { assert_eq!(iter.next(), Some((&6, &7, &8))); assert_eq!(iter.next(), Some((&3, &4, &5))); assert_eq!(iter.next(), None); } let component = Remove::<(usize,)>::remove((&mut usizes, &mut u32s, &mut u64s), entity2); assert_eq!(component, (Some(3),)); let mut iter = (&usizes, &u64s).iter(); assert_eq!(iter.next(), Some((&0, &1))); assert_eq!(iter.next(), Some((&6, &7))); assert_eq!(iter.next(), None); let mut iter = (&usizes, &u64s, &u32s).iter(); assert_eq!(iter.next(), Some((&6, &7, &8))); assert_eq!(iter.next(), None); } #[test] fn update() { let world = World::new(); let (mut entities, mut usizes) = world.borrow::<(EntitiesMut, &mut usize)>(); usizes.update_pack(); let entity1 = entities.add_entity(&mut usizes, 0); let entity2 = entities.add_entity(&mut usizes, 2); usizes.delete(entity1); assert_eq!( usizes.get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(usizes.len(), 1); assert_eq!(usizes.inserted().len(), 1); assert_eq!(usizes.modified().len(), 0); assert_eq!(usizes.deleted().len(), 1); assert_eq!(usizes.take_deleted(), vec![(entity1, 0)]); } #[test] fn strip() { let world = World::new(); let (entity1, entity2) = world.run::<(EntitiesMut, &mut usize, &mut u32), _, _>( |(mut entities, mut usizes, mut u32s)| { ( entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)), entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)), ) }, ); world.run::<AllStorages, _, _>(|mut all_storages| { all_storages.strip(entity1); }); world.run::<(&mut usize, &mut u32), _, _>(|(mut usizes, mut u32s)| { assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!( (&mut u32s).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<u32>(), }) ); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); }); world.run::<AllStorages, _, _>(|mut all_storages| { assert!(all_storages.delete(entity1)); }); }
use core::any::type_name; use shipyard::error; use shipyard::internal::iterators; use shipyard::prelude::*; #[test] fn no_pack() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); usizes.delete(entity1); assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); } #[test] fn tight() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); (&mut usizes, &mut u32s).tight_pack(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); Delete::<(usize,)>::delete((&mut usizes, &mut u32s), entity1);
#[test] fn loose() { let world = World::new(); let (mut entities, mut usizes, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u32)>(); (&mut usizes, &mut u32s).loose_pack(); let entity1 = entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)); let entity2 = entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)); Delete::<(usize,)>::delete((&mut usizes, &mut u32s), entity1); assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); let mut iter = (&usizes, &u32s).iter(); assert_eq!(iter.next(), Some((&2, &3))); assert_eq!(iter.next(), None); } #[test] fn tight_loose() { let world = World::new(); let (mut entities, mut usizes, mut u64s, mut u32s) = world.borrow::<(EntitiesMut, &mut usize, &mut u64, &mut u32)>(); (&mut usizes, &mut u64s).tight_pack(); LoosePack::<(u32,)>::loose_pack((&mut u32s, &mut usizes, &mut u64s)); let entity1 = entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (0, 1, 2)); let entity2 = entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (3, 4, 5)); entities.add_entity((&mut usizes, &mut u64s, &mut u32s), (6, 7, 8)); Delete::<(u32,)>::delete((&mut u32s, &mut usizes, &mut u64s), entity1); let mut iter = (&usizes, &u64s).iter(); assert_eq!(iter.next(), Some((&0, &1))); assert_eq!(iter.next(), Some((&3, &4))); assert_eq!(iter.next(), Some((&6, &7))); assert_eq!(iter.next(), None); let iter = (&usizes, &u64s, &u32s).iter(); if let iterators::Iter3::Loose(mut iter) = iter { assert_eq!(iter.next(), Some((&6, &7, &8))); assert_eq!(iter.next(), Some((&3, &4, &5))); assert_eq!(iter.next(), None); } let component = Remove::<(usize,)>::remove((&mut usizes, &mut u32s, &mut u64s), entity2); assert_eq!(component, (Some(3),)); let mut iter = (&usizes, &u64s).iter(); assert_eq!(iter.next(), Some((&0, &1))); assert_eq!(iter.next(), Some((&6, &7))); assert_eq!(iter.next(), None); let mut iter = (&usizes, &u64s, &u32s).iter(); assert_eq!(iter.next(), Some((&6, &7, &8))); assert_eq!(iter.next(), None); } #[test] fn update() { let world = World::new(); let (mut entities, mut usizes) = world.borrow::<(EntitiesMut, &mut usize)>(); usizes.update_pack(); let entity1 = entities.add_entity(&mut usizes, 0); let entity2 = entities.add_entity(&mut usizes, 2); usizes.delete(entity1); assert_eq!( usizes.get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(usizes.len(), 1); assert_eq!(usizes.inserted().len(), 1); assert_eq!(usizes.modified().len(), 0); assert_eq!(usizes.deleted().len(), 1); assert_eq!(usizes.take_deleted(), vec![(entity1, 0)]); } #[test] fn strip() { let world = World::new(); let (entity1, entity2) = world.run::<(EntitiesMut, &mut usize, &mut u32), _, _>( |(mut entities, mut usizes, mut u32s)| { ( entities.add_entity((&mut usizes, &mut u32s), (0usize, 1u32)), entities.add_entity((&mut usizes, &mut u32s), (2usize, 3u32)), ) }, ); world.run::<AllStorages, _, _>(|mut all_storages| { all_storages.strip(entity1); }); world.run::<(&mut usize, &mut u32), _, _>(|(mut usizes, mut u32s)| { assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!( (&mut u32s).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<u32>(), }) ); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); }); world.run::<AllStorages, _, _>(|mut all_storages| { assert!(all_storages.delete(entity1)); }); }
assert_eq!( (&mut usizes).get(entity1), Err(error::MissingComponent { id: entity1, name: type_name::<usize>(), }) ); assert_eq!((&mut u32s).get(entity1), Ok(&mut 1)); assert_eq!(usizes.get(entity2), Ok(&2)); assert_eq!(u32s.get(entity2), Ok(&3)); let iter = (&usizes, &u32s).iter(); if let iterators::Iter2::Tight(mut iter) = iter { assert_eq!(iter.next(), Some((&2, &3))); assert_eq!(iter.next(), None); } else { panic!("not packed"); } }
function_block-function_prefix_line
[ { "content": "#[system(Test3)]\n\nfn run(_: &mut Entities, _: &mut u32) {}\n\n\n", "file_path": "tests/derive/good.rs", "rank": 0, "score": 274503.01059633156 }, { "content": "#[system(Test1)]\n\nfn run(_: &usize, _: &mut i32, _: &Entities, _: Unique<&u32>, _: Entities) {}\n\n\n", "file_...
Rust
solo-machine/src/server/ibc.rs
devashishdxt/ibc-solo-machine
76cb11d81e4777e96d4babbfb81381e50a48d57e
tonic::include_proto!("ibc"); use std::time::SystemTime; use k256::ecdsa::VerifyingKey; use solo_machine_core::{ cosmos::crypto::{PublicKey, PublicKeyAlgo}, ibc::core::ics24_host::identifier::ChainId, service::IbcService as CoreIbcService, DbPool, Event, Signer, }; use tokio::sync::mpsc::UnboundedSender; use tonic::{Request, Response, Status}; use self::ibc_server::Ibc; const DEFAULT_MEMO: &str = "solo-machine-memo"; pub struct IbcService<S> { core_service: CoreIbcService, signer: S, } impl<S> IbcService<S> { pub fn new(db_pool: DbPool, notifier: UnboundedSender<Event>, signer: S) -> Self { let core_service = CoreIbcService::new_with_notifier(db_pool, notifier); Self { core_service, signer, } } } #[tonic::async_trait] impl<S> Ibc for IbcService<S> where S: Signer + Send + Sync + 'static, { async fn connect( &self, request: Request<ConnectRequest>, ) -> Result<Response<ConnectResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let request_id = request.request_id; let force = request.force; self.core_service .connect(&self.signer, chain_id, request_id, memo, force) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(ConnectResponse {})) } async fn mint(&self, request: Request<MintRequest>) -> Result<Response<MintResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let amount = request.amount; let denom = request .denom .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let receiver = request.receiver_address; let transaction_hash = self .core_service .mint( &self.signer, chain_id, request_id, amount, denom, receiver, memo, ) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(MintResponse { transaction_hash })) } async fn burn(&self, request: Request<BurnRequest>) -> Result<Response<BurnResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let amount = request.amount; let denom = request .denom .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let transaction_hash = self .core_service .burn(&self.signer, chain_id, request_id, amount, denom, memo) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(BurnResponse { transaction_hash })) } async fn update_signer( &self, request: Request<UpdateSignerRequest>, ) -> Result<Response<UpdateSignerResponse>, Status> { let request = request.into_inner(); let chain_id: ChainId = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let new_public_key_bytes = hex::decode(&request.new_public_key) .map_err(|err| Status::invalid_argument(err.to_string()))?; let new_verifying_key = VerifyingKey::from_sec1_bytes(&new_public_key_bytes) .map_err(|err| Status::invalid_argument(err.to_string()))?; let public_key_algo = request .public_key_algo .map(|s| s.parse()) .transpose() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))? .unwrap_or(PublicKeyAlgo::Secp256k1); let new_public_key = match public_key_algo { PublicKeyAlgo::Secp256k1 => PublicKey::Secp256k1(new_verifying_key), #[cfg(feature = "ethermint")] PublicKeyAlgo::EthSecp256k1 => PublicKey::EthSecp256k1(new_verifying_key), }; self.core_service .update_signer(&self.signer, chain_id, request_id, new_public_key, memo) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(UpdateSignerResponse {})) } async fn query_history( &self, request: Request<QueryHistoryRequest>, ) -> Result<Response<QueryHistoryResponse>, Status> { let request = request.into_inner(); let limit = request.limit.unwrap_or(10); let offset = request.offset.unwrap_or(0); let history = self .core_service .history(&self.signer, limit, offset) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; let response = QueryHistoryResponse { operations: history .into_iter() .map(|op| Operation { id: op.id, request_id: op.request_id, address: op.address, denom: op.denom.to_string(), amount: op.amount, operation_type: op.operation_type.to_string(), transaction_hash: op.transaction_hash, created_at: Some(SystemTime::from(op.created_at).into()), }) .collect(), }; Ok(Response::new(response)) } }
tonic::include_proto!("ibc"); use std::time::SystemTime; use k256::ecdsa::VerifyingKey; use solo_machine_core::{ cosmos::crypto::{PublicKey, PublicKeyAlgo}, ibc::core::ics24_host::identifier::ChainId, service::IbcService as CoreIbcService, DbPool, Event, Signer, }; use tokio::sync::mpsc::UnboundedSender; use tonic::{Request, Response, Status}; use self::ibc_server::Ibc; const DEFAULT_MEMO: &str = "solo-machine-memo"; pub struct IbcService<S> { core_service: CoreIbcService, signer: S, } impl<S> IbcService<S> { pub fn new(db_pool: DbPool, notifier: UnboundedSender<Event>, signer: S) -> Self { let core_service = CoreIbcService::new_with_notifier(db_pool, notifier); Self { core_service, signer, } } } #[tonic::async_trait] impl<S> Ibc for IbcService<S> where S: Signer + Send + Sync + 'static, { async fn connect( &self, request: Request<ConnectRequest>, ) -> Result<Response<ConnectResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned());
async fn mint(&self, request: Request<MintRequest>) -> Result<Response<MintResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let amount = request.amount; let denom = request .denom .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let receiver = request.receiver_address; let transaction_hash = self .core_service .mint( &self.signer, chain_id, request_id, amount, denom, receiver, memo, ) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(MintResponse { transaction_hash })) } async fn burn(&self, request: Request<BurnRequest>) -> Result<Response<BurnResponse>, Status> { let request = request.into_inner(); let chain_id = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let amount = request.amount; let denom = request .denom .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let transaction_hash = self .core_service .burn(&self.signer, chain_id, request_id, amount, denom, memo) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(BurnResponse { transaction_hash })) } async fn update_signer( &self, request: Request<UpdateSignerRequest>, ) -> Result<Response<UpdateSignerResponse>, Status> { let request = request.into_inner(); let chain_id: ChainId = request .chain_id .parse() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))?; let request_id = request.request_id; let memo = request.memo.unwrap_or_else(|| DEFAULT_MEMO.to_owned()); let new_public_key_bytes = hex::decode(&request.new_public_key) .map_err(|err| Status::invalid_argument(err.to_string()))?; let new_verifying_key = VerifyingKey::from_sec1_bytes(&new_public_key_bytes) .map_err(|err| Status::invalid_argument(err.to_string()))?; let public_key_algo = request .public_key_algo .map(|s| s.parse()) .transpose() .map_err(|err: anyhow::Error| Status::invalid_argument(err.to_string()))? .unwrap_or(PublicKeyAlgo::Secp256k1); let new_public_key = match public_key_algo { PublicKeyAlgo::Secp256k1 => PublicKey::Secp256k1(new_verifying_key), #[cfg(feature = "ethermint")] PublicKeyAlgo::EthSecp256k1 => PublicKey::EthSecp256k1(new_verifying_key), }; self.core_service .update_signer(&self.signer, chain_id, request_id, new_public_key, memo) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(UpdateSignerResponse {})) } async fn query_history( &self, request: Request<QueryHistoryRequest>, ) -> Result<Response<QueryHistoryResponse>, Status> { let request = request.into_inner(); let limit = request.limit.unwrap_or(10); let offset = request.offset.unwrap_or(0); let history = self .core_service .history(&self.signer, limit, offset) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; let response = QueryHistoryResponse { operations: history .into_iter() .map(|op| Operation { id: op.id, request_id: op.request_id, address: op.address, denom: op.denom.to_string(), amount: op.amount, operation_type: op.operation_type.to_string(), transaction_hash: op.transaction_hash, created_at: Some(SystemTime::from(op.created_at).into()), }) .collect(), }; Ok(Response::new(response)) } }
let request_id = request.request_id; let force = request.force; self.core_service .connect(&self.signer, chain_id, request_id, memo, force) .await .map_err(|err| { log::error!("{}", err); Status::internal(err.to_string()) })?; Ok(Response::new(ConnectResponse {})) }
function_block-function_prefix_line
[ { "content": "#[async_trait]\n\npub trait Signer: ToPublicKey + Send + Sync {\n\n /// Signs the given message\n\n async fn sign(&self, request_id: Option<&str>, message: Message<'_>) -> Result<Vec<u8>>;\n\n}\n\n\n\n#[async_trait]\n\nimpl<T: Signer> Signer for &T {\n\n async fn sign(&self, request_id: O...
Rust
src/kernel/src/syscall/sync.rs
ariadiamond/twizzler-Rust
5f5d01bac9127ca1d64bb8aa472a04f6634fc3a9
use core::time::Duration; use alloc::{collections::BTreeMap, vec::Vec}; use twizzler_abi::syscall::{ ThreadSync, ThreadSyncError, ThreadSyncReference, ThreadSyncSleep, ThreadSyncWake, }; use x86_64::VirtAddr; use crate::{ obj::{LookupFlags, ObjectRef}, once::Once, spinlock::Spinlock, thread::{current_memory_context, current_thread_ref, CriticalGuard, ThreadRef, ThreadState}, }; struct Requeue { list: Spinlock<BTreeMap<u64, ThreadRef>>, } /* TODO: make this thread-local */ static mut REQUEUE: Once<Requeue> = Once::new(); fn get_requeue_list() -> &'static Requeue { unsafe { REQUEUE.call_once(|| Requeue { list: Spinlock::new(BTreeMap::new()), }) } } pub fn requeue_all() { let requeue = get_requeue_list(); let mut list = requeue.list.lock(); for (_, thread) in list.drain_filter(|_, v| v.reset_sync_sleep_done()) { crate::sched::schedule_thread(thread); } } pub fn add_to_requeue(thread: ThreadRef) { let requeue = get_requeue_list(); requeue.list.lock().insert(thread.id(), thread); } fn finish_blocking(guard: CriticalGuard) { let thread = current_thread_ref().unwrap(); crate::interrupt::with_disabled(|| { thread.set_state(ThreadState::Blocked); drop(guard); crate::sched::schedule(false); thread.set_state(ThreadState::Running); }); } fn get_obj_and_offset(addr: VirtAddr) -> Result<(ObjectRef, usize), ThreadSyncError> { let vmc = current_memory_context().ok_or(ThreadSyncError::Unknown)?; let mapping = { vmc.inner().lookup_object(addr) }.ok_or(ThreadSyncError::InvalidReference)?; let offset = (addr.as_u64() as usize) % (1024 * 1024 * 1024); Ok((mapping.obj.clone(), offset)) } fn get_obj(reference: ThreadSyncReference) -> Result<(ObjectRef, usize), ThreadSyncError> { Ok(match reference { ThreadSyncReference::ObjectRef(id, offset) => { let obj = match crate::obj::lookup_object(id, LookupFlags::empty()) { crate::obj::LookupResult::Found(o) => o, _ => return Err(ThreadSyncError::InvalidReference), }; (obj, offset) } ThreadSyncReference::Virtual(addr) => get_obj_and_offset(VirtAddr::new(addr as u64))?, }) } struct SleepEvent { obj: ObjectRef, offset: usize, did_sleep: bool, } fn prep_sleep(sleep: &ThreadSyncSleep, first_sleep: bool) -> Result<SleepEvent, ThreadSyncError> { let (obj, offset) = get_obj(sleep.reference)?; /* logln!( "{} sleep {} {:x}", current_thread_ref().unwrap().id(), obj.id(), offset ); if let ThreadSyncReference::Virtual(p) = &sleep.reference { logln!(" => {:p} {}", *p, unsafe { (**p).load(core::sync::atomic::Ordering::SeqCst) }); } */ let did_sleep = obj.setup_sleep_word(offset, sleep.op, sleep.value, first_sleep); Ok(SleepEvent { obj, offset, did_sleep, }) } fn undo_sleep(sleep: SleepEvent) { sleep.obj.remove_from_sleep_word(sleep.offset); } fn wakeup(wake: &ThreadSyncWake) -> Result<usize, ThreadSyncError> { let (obj, offset) = get_obj(wake.reference)?; Ok(obj.wakeup_word(offset, wake.count)) } fn thread_sync_cb_timeout(thread: ThreadRef) { if thread.reset_sync_sleep() { add_to_requeue(thread); } requeue_all(); } pub fn sys_thread_sync( ops: &mut [ThreadSync], timeout: Option<&mut Duration>, ) -> Result<usize, ThreadSyncError> { let mut ready_count = 0; let mut unsleeps = Vec::new(); for op in ops { match op { ThreadSync::Sleep(sleep, result) => match prep_sleep(sleep, unsleeps.is_empty()) { Ok(se) => { *result = Ok(if se.did_sleep { 0 } else { 1 }); if se.did_sleep { unsleeps.push(se); } else { ready_count += 1; } } Err(x) => *result = Err(x), }, ThreadSync::Wake(wake, result) => { /* if let ThreadSyncReference::Virtual(p) = &wake.reference { logln!(" wake => {:p} {}", *p, unsafe { (**p).load(core::sync::atomic::Ordering::SeqCst) }); } */ match wakeup(wake) { Ok(count) => { *result = Ok(count); if count > 0 { ready_count += 1; } } Err(x) => { *result = Err(x); } } } } } let thread = current_thread_ref().unwrap(); { let guard = thread.enter_critical(); if !unsleeps.is_empty() { if let Some(timeout) = timeout { crate::clock::register_timeout_callback( timeout.as_nanos() as u64, thread_sync_cb_timeout, thread.clone(), ); } thread.set_sync_sleep_done(); } requeue_all(); if !unsleeps.is_empty() { finish_blocking(guard); } else { drop(guard); } } for op in unsleeps { undo_sleep(op); } Ok(ready_count) }
use core::time::Duration; use alloc::{collections::BTreeMap, vec::Vec}; use twizzler_abi::syscall::{ ThreadSync, ThreadSyncError, ThreadSyncReference, ThreadSyncSleep, ThreadSyncWake, }; use x86_64::VirtAddr; use crate::{ obj::{LookupFlags, ObjectRef}, once::Once, spinlock::Spinlock, thread::{current_memory_context, current_thread_ref, CriticalGuard, ThreadRef, ThreadState}, }; struct Requeue { list: Spinlock<BTreeMap<u64, ThreadRef>>, } /* TODO: make this thread-local */ static mut REQUEUE: Once<Requeue> = Once::new(); fn get_requeue_list() -> &'static Requeue { unsafe { REQUEUE.call_once(|| Requeue { list: Spinlock::new(BTreeMap::new()), }) } } pub fn requeue_all() { let requeue = get_requeue_list(); let mut list = requeue.list.lock(); for (_, thread) in list.drain_filter(|_, v| v.reset_sync_sleep_done()) { crate::sched::schedule_thread(thread); } } pub fn add_to_requeue(thread: ThreadRef) { let requeue = get_requeue_list(); requeue.list.lock().insert(thread.id(), thread); } fn finish_blocking(guard: CriticalGuard) { let thread = current_thread_ref().unwrap(); crate::interrupt::with_disabled(|| { thread.set_state(ThreadState::Blocked); drop(guard); crate::sched::schedule(false); thread.set_state(ThreadState::Running); }); } fn get_obj_and_offset(addr: VirtAddr) -> Result<(ObjectRef, usize), ThreadSyncError> { let vmc = current_memory_context().ok_or(ThreadSyncError::Unknown)?; let mapping = { vmc.inner().lookup_object(addr) }.ok_or(ThreadSyncError::InvalidReference)?; let offset = (addr.as_u64() as usize) % (1024 * 1024 * 1024); Ok((mapping.obj.clone(), offset)) } fn get_obj(reference: ThreadSyncReference) -> Result<(ObjectRef, usize), ThreadSyncError> { Ok(match reference { ThreadSyncReference::ObjectRef(id, offset) => { let obj = match crate::obj::lookup_object(id, LookupFlags::empty()) { crate::obj::LookupResult::Found(o) => o, _ => return Err(ThreadSyncError::InvalidReference), }; (obj, offset) } ThreadSyncReference::Virtual(addr) => get_obj_and_offset(VirtAddr::new(addr as u64))?, }) } struct SleepEvent { obj: ObjectRef, offset: usize, did_sleep: bool, } fn prep_sleep(sleep: &ThreadSyncSleep, first_sleep: bool) -> Result<SleepEvent, ThreadSyncError> { let (obj, offset) = get_obj(sleep.referenc
fn undo_sleep(sleep: SleepEvent) { sleep.obj.remove_from_sleep_word(sleep.offset); } fn wakeup(wake: &ThreadSyncWake) -> Result<usize, ThreadSyncError> { let (obj, offset) = get_obj(wake.reference)?; Ok(obj.wakeup_word(offset, wake.count)) } fn thread_sync_cb_timeout(thread: ThreadRef) { if thread.reset_sync_sleep() { add_to_requeue(thread); } requeue_all(); } pub fn sys_thread_sync( ops: &mut [ThreadSync], timeout: Option<&mut Duration>, ) -> Result<usize, ThreadSyncError> { let mut ready_count = 0; let mut unsleeps = Vec::new(); for op in ops { match op { ThreadSync::Sleep(sleep, result) => match prep_sleep(sleep, unsleeps.is_empty()) { Ok(se) => { *result = Ok(if se.did_sleep { 0 } else { 1 }); if se.did_sleep { unsleeps.push(se); } else { ready_count += 1; } } Err(x) => *result = Err(x), }, ThreadSync::Wake(wake, result) => { /* if let ThreadSyncReference::Virtual(p) = &wake.reference { logln!(" wake => {:p} {}", *p, unsafe { (**p).load(core::sync::atomic::Ordering::SeqCst) }); } */ match wakeup(wake) { Ok(count) => { *result = Ok(count); if count > 0 { ready_count += 1; } } Err(x) => { *result = Err(x); } } } } } let thread = current_thread_ref().unwrap(); { let guard = thread.enter_critical(); if !unsleeps.is_empty() { if let Some(timeout) = timeout { crate::clock::register_timeout_callback( timeout.as_nanos() as u64, thread_sync_cb_timeout, thread.clone(), ); } thread.set_sync_sleep_done(); } requeue_all(); if !unsleeps.is_empty() { finish_blocking(guard); } else { drop(guard); } } for op in unsleeps { undo_sleep(op); } Ok(ready_count) }
e)?; /* logln!( "{} sleep {} {:x}", current_thread_ref().unwrap().id(), obj.id(), offset ); if let ThreadSyncReference::Virtual(p) = &sleep.reference { logln!(" => {:p} {}", *p, unsafe { (**p).load(core::sync::atomic::Ordering::SeqCst) }); } */ let did_sleep = obj.setup_sleep_word(offset, sleep.op, sleep.value, first_sleep); Ok(SleepEvent { obj, offset, did_sleep, }) }
function_block-function_prefixed
[]
Rust
src/render.rs
JorgenPo/rust-text-rpg
5e8f489741628062503ff1814535384b1692929f
use termion::terminal_size; use termion::{color, cursor, clear, style}; use std::io::{Error, Write, Stdout, StdoutLock}; use termion::raw::{IntoRawMode, RawTerminal}; use std::cmp::max; #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; std::io::stdout().write_fmt(args).expect("Failed to write"); } #[macro_export] macro_rules! render { ($($arg:tt)*) => ( _print(format_args!($($arg)*)); std::io::stdout().flush().unwrap(); ); } pub struct TermSize { pub width: u16, pub height: u16 } impl Default for TermSize { fn default() -> Self { TermSize{ width: 80, height: 120, } } } pub enum Coordinate { Absolute(u16), Centered, Percent(u8), FromBorder(u16), } pub struct Position { pub x: Coordinate, pub y: Coordinate, } impl Position { pub fn from(x: u16, y: u16) -> Self { Position { x: Coordinate::Absolute(x), y: Coordinate::Absolute(y) } } } pub struct Render { pub term_size: TermSize, pub clear_color: Box<dyn color::Color>, pub hide_cursor: bool } pub trait Drawable { fn draw(&self) -> String; fn get_width(&self) -> u16; fn get_height(&self) -> u16; fn get_position(&self) -> &Position; fn set_position(&mut self, pos: Position); } impl Render { pub fn new() -> Self { let mut term_size = match terminal_size() { Ok((width, height)) => TermSize{width, height}, Err(err) => TermSize::default(), }; if term_size.width == 0 || term_size.height == 0 { term_size = TermSize::default(); } Render { term_size, clear_color: Box::new(color::Black), hide_cursor: true } } pub fn clear_screen(&mut self) { render!("{}{}{}", color::Bg(self.clear_color.as_ref()), clear::All, cursor::Goto(1, 1)); if self.hide_cursor { render!("{}", cursor::Hide); } } fn get_middle_x<T: Drawable> (&self, drawable: &T) -> u16 { let half_width = drawable.get_width() / 2; let center_x = self.term_size.width / 2; center_x - half_width + 1 } fn get_middle_y<T: Drawable> (&self, drawable: &T) -> u16 { let half_height = drawable.get_height() / 2; let center_y = self.term_size.height / 2; center_y - half_height + 1 } pub fn set_cursor_position(&mut self, coord: (u16, u16)) { render!("{}", cursor::Goto(coord.0, coord.1)); } pub fn set_pixel_color(&mut self, coord: (u16, u16), color: Box<dyn color::Color>) { print!("{}{} ", cursor::Goto(coord.0, coord.1), color::Bg(color.as_ref())); } pub fn draw<T: Drawable>(&mut self, drawable: &T) { let position = drawable.get_position(); let x = match position.x { Coordinate::Absolute(x) => max(x, 1), Coordinate::Centered => self.get_middle_x(drawable), Coordinate::Percent(percent) => max(self.term_size.width, self.term_size.width * percent as u16 / 100), Coordinate::FromBorder(x) => max(1, self.term_size.width - x) }; let y = match position.y { Coordinate::Absolute(y) => max(y, 1), Coordinate::Centered => self.get_middle_y(drawable), Coordinate::Percent(percent) => max(self.term_size.height, self.term_size.height * percent as u16 / 100), Coordinate::FromBorder(y) => max(1, self.term_size.height - y) }; render!("{}{}", cursor::Goto(x, y), drawable.draw()); } pub fn draw_raw(&mut self, string: &str) { render!("{}", string); } pub fn flash(&self) { std::io::stdout().flush().unwrap(); } } impl Drop for Render { fn drop(&mut self) { print!("{}{}{}{}", clear::All, style::Reset, cursor::Show, cursor::Goto(1, 1)); } }
use termion::terminal_size; use termion::{color, cursor, clear, style}; use std::io::{Error, Write, Stdout, StdoutLock}; use termion::raw::{IntoRawMode, RawTerminal}; use std::cmp::max; #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; std::io::stdout().write_fmt(args).expect("Failed to write"); } #[macro_export] macro_rules! render { ($($arg:tt)*) => ( _print(format_args!($($arg)*)); std::io::stdout().flush().unwrap(); ); } pub struct TermSize { pub width: u16, pub height: u16 } impl Default for TermSize { fn default() -> Self { TermSize{ width: 80, height: 120, } } } pub enum Coordinate { Absolute(u16), Centered, Percent(u8), FromBorder(u16), } pub struct Position { pub x: Coordinate, pub y: Coordinate, } impl Position { pub fn from(x: u16, y: u16) -> Self { Position { x: Coordinate::Absolute(x), y: Coordinate::Absolute(y) } } } pub struct Render { pub term_size: TermSize, pub clear_color: Box<dyn color::Color>, pub hide_cursor: bool } pub trait Drawable { fn draw(&self) -> String; fn get_width(&self) -> u16; fn get_height(&self) -> u16; fn get_position(&self) -> &Position; fn set_position(&mut self, pos: Position); } impl Render { pub fn new() -> Self { let mut term_size = match terminal_size() { Ok((width, height)) => TermSize{width, height}, Err(err) => TermSize::default(), }; if term_size.width == 0 || term_size.height == 0 { term_size = TermSize::default(); } Render { term_size, clear_color: Box::new(color::Black), hide_cursor: true } } pub fn clear_screen(&mut self) { render!("{}{}{}", color::Bg(self.clear_color.as_ref()), clear::All, cursor::Goto(1, 1)); if self.hide_cursor { render!("{}", cursor::Hide); } } fn get_middle_x<T: Drawable> (&self, drawable: &T) -> u16 { let half_width = drawable.get_width() / 2; let center_x = self.term_size.width / 2; center_x - half_width + 1 } fn get_middle_y<T: Drawable> (&self, drawable: &T) -> u16 { let half_height = drawable.get_height() / 2; let center_y = self.term_size.height / 2; center_y - half_height + 1 } pub fn set_cursor_position(&mut self, coord: (u16, u16)) { render!("{}", cursor::Goto(coord.0, coord.1)); } pub fn set_pixel_color(&mut self, coord: (u16, u16), color: Box<dyn color::Color>) { print!("{}{} ", cursor::Goto(coord.0, coord.1), color::Bg(color.as_ref())); }
pub fn draw_raw(&mut self, string: &str) { render!("{}", string); } pub fn flash(&self) { std::io::stdout().flush().unwrap(); } } impl Drop for Render { fn drop(&mut self) { print!("{}{}{}{}", clear::All, style::Reset, cursor::Show, cursor::Goto(1, 1)); } }
pub fn draw<T: Drawable>(&mut self, drawable: &T) { let position = drawable.get_position(); let x = match position.x { Coordinate::Absolute(x) => max(x, 1), Coordinate::Centered => self.get_middle_x(drawable), Coordinate::Percent(percent) => max(self.term_size.width, self.term_size.width * percent as u16 / 100), Coordinate::FromBorder(x) => max(1, self.term_size.width - x) }; let y = match position.y { Coordinate::Absolute(y) => max(y, 1), Coordinate::Centered => self.get_middle_y(drawable), Coordinate::Percent(percent) => max(self.term_size.height, self.term_size.height * percent as u16 / 100), Coordinate::FromBorder(y) => max(1, self.term_size.height - y) }; render!("{}{}", cursor::Goto(x, y), drawable.draw()); }
function_block-full_function
[ { "content": "pub trait Logger {\n\n fn info(&mut self, message: &str);\n\n fn warn(&mut self, message: &str);\n\n}", "file_path": "src/game/loggers.rs", "rank": 2, "score": 61792.36740350007 }, { "content": "fn lerp_color(start: color::Rgb, end: color::Rgb, k: f32) -> color::Rgb {\n\n...
Rust
scheduler/crates/api/src/calendar/update_calendar.rs
omid/nettu-scheduler
27a2728882842222085ee4e17c952ec215fd683e
use crate::shared::{ auth::{ account_can_modify_calendar, account_can_modify_user, protect_account_route, Permission, }, usecase::{execute, execute_with_policy, PermissionBoundary, UseCase}, }; use crate::{error::NettuError, shared::auth::protect_route}; use actix_web::{web, HttpResponse}; use nettu_scheduler_api_structs::update_calendar::{APIResponse, PathParams, RequestBody}; use nettu_scheduler_domain::{Calendar, Metadata, User, ID}; use nettu_scheduler_infra::NettuContext; pub async fn update_calendar_admin_controller( http_req: web::HttpRequest, ctx: web::Data<NettuContext>, path: web::Path<PathParams>, body: web::Json<RequestBody>, ) -> Result<HttpResponse, NettuError> { let account = protect_account_route(&http_req, &ctx).await?; let cal = account_can_modify_calendar(&account, &path.calendar_id, &ctx).await?; let user = account_can_modify_user(&account, &cal.user_id, &ctx).await?; let usecase = UpdateCalendarUseCase { user, calendar_id: cal.id, week_start: body.0.settings.week_start, timezone: body.0.settings.timezone, metadata: body.0.metadata, }; execute(usecase, &ctx) .await .map(|calendar| HttpResponse::Ok().json(APIResponse::new(calendar))) .map_err(NettuError::from) } pub async fn update_calendar_controller( http_req: web::HttpRequest, ctx: web::Data<NettuContext>, mut path: web::Path<PathParams>, body: web::Json<RequestBody>, ) -> Result<HttpResponse, NettuError> { let (user, policy) = protect_route(&http_req, &ctx).await?; let usecase = UpdateCalendarUseCase { user, calendar_id: std::mem::take(&mut path.calendar_id), week_start: body.0.settings.week_start, timezone: body.0.settings.timezone, metadata: body.0.metadata, }; execute_with_policy(usecase, &policy, &ctx) .await .map(|calendar| HttpResponse::Ok().json(APIResponse::new(calendar))) .map_err(NettuError::from) } #[derive(Debug)] struct UpdateCalendarUseCase { pub user: User, pub calendar_id: ID, pub week_start: Option<isize>, pub timezone: Option<String>, pub metadata: Option<Metadata>, } #[derive(Debug)] enum UseCaseError { CalendarNotFound, StorageError, InvalidSettings(String), } impl From<UseCaseError> for NettuError { fn from(e: UseCaseError) -> Self { match e { UseCaseError::StorageError => Self::InternalError, UseCaseError::CalendarNotFound => Self::NotFound("The calendar was not found.".into()), UseCaseError::InvalidSettings(err) => Self::BadClientData(format!( "Bad calendar settings provided. Error message: {}", err )), } } } #[async_trait::async_trait(?Send)] impl UseCase for UpdateCalendarUseCase { type Response = Calendar; type Error = UseCaseError; const NAME: &'static str = "UpdateCalendar"; async fn execute(&mut self, ctx: &NettuContext) -> Result<Self::Response, Self::Error> { let mut calendar = match ctx.repos.calendars.find(&self.calendar_id).await { Some(cal) if cal.user_id == self.user.id => cal, _ => return Err(UseCaseError::CalendarNotFound), }; if let Some(wkst) = self.week_start { if !calendar.settings.set_week_start(wkst) { return Err(UseCaseError::InvalidSettings(format!( "Invalid week start: {}, must be between 0 and 6", wkst ))); } } if let Some(timezone) = &self.timezone { if !calendar.settings.set_timezone(timezone) { return Err(UseCaseError::InvalidSettings(format!( "Invalid timezone: {}, must be a valid IANA Timezone string", timezone ))); } } if let Some(metadata) = &self.metadata { calendar.metadata = metadata.clone(); } ctx.repos .calendars .save(&calendar) .await .map(|_| calendar) .map_err(|_| UseCaseError::StorageError) } } impl PermissionBoundary for UpdateCalendarUseCase { fn permissions(&self) -> Vec<Permission> { vec![Permission::UpdateCalendar] } } #[cfg(test)] mod test { use nettu_scheduler_domain::{Account, Calendar, User}; use nettu_scheduler_infra::setup_context; use super::*; #[actix_web::main] #[test] async fn it_rejects_invalid_wkst() { let ctx = setup_context().await; let account = Account::default(); ctx.repos.accounts.insert(&account).await.unwrap(); let user = User::new(account.id.clone()); ctx.repos.users.insert(&user).await.unwrap(); let calendar = Calendar::new(&user.id, &account.id); ctx.repos.calendars.insert(&calendar).await.unwrap(); let mut usecase = UpdateCalendarUseCase { user, calendar_id: calendar.id.into(), week_start: Some(20), timezone: None, metadata: None, }; let res = usecase.execute(&ctx).await; assert!(res.is_err()); } #[actix_web::main] #[test] async fn it_update_settings_with_valid_wkst() { let ctx = setup_context().await; let account = Account::default(); ctx.repos.accounts.insert(&account).await.unwrap(); let user = User::new(account.id.clone()); ctx.repos.users.insert(&user).await.unwrap(); let calendar = Calendar::new(&user.id, &account.id); ctx.repos.calendars.insert(&calendar).await.unwrap(); assert_eq!(calendar.settings.week_start, 0); let new_wkst = 3; let mut usecase = UpdateCalendarUseCase { user, calendar_id: calendar.id.clone(), week_start: Some(new_wkst), timezone: None, metadata: Some(Metadata::new()), }; let res = usecase.execute(&ctx).await; assert!(res.is_ok()); let calendar = ctx.repos.calendars.find(&calendar.id).await.unwrap(); assert_eq!(calendar.settings.week_start, new_wkst); } }
use crate::shared::{ auth::{ account_can_modify_calendar, account_can_modify_user, protect_account_route, Permission, }, usecase::{execute, execute_with_policy, PermissionBoundary, UseCase}, }; use crate::{error::NettuError, shared::auth::protect_route}; use actix_web::{web, HttpResponse}; use nettu_scheduler_api_structs::update_calendar::{APIResponse, PathParams, RequestBody}; use nettu_scheduler_domain::{Calendar, Metadata, User, ID}; use nettu_scheduler_infra::NettuContext; pub async fn update_calendar_admin_controller( http_req: web::HttpRequest, ctx: web::Data<NettuContext>, path: web::Path<PathParams>, body: web::Json<RequestBody>, ) -> Result<HttpResponse, NettuError> { let account = protect_account_route(&http_req, &ctx).await?; let cal = account_can_modify_calendar(&account, &path.calendar_id, &ctx).await?; let user = account_can_modify_user(&account, &cal.user_id, &ctx).await?; let usecase = UpdateCalendarUseCase { user, calendar_id: cal.id, week_start: body.0.settings.week_start, timezone: body.0.settings.timezone, metadata: body.0.metadata, }; execute(usecase, &ctx) .await .map(|calendar| HttpResponse::Ok().json(APIResponse::new(calendar))) .map_err(NettuError::from) } pub async fn update_calendar_controller( http_req: web::HttpRequest, ctx: web::Data<NettuContext>, mut path: web::Path<PathParams>, body: web::Json<RequestBody>, ) -> Result<HttpResponse, NettuError> { let (user, policy) = protect_route(&http_req, &ctx).await?; let usecase = UpdateCalendarUseCase { user, calendar_id: std::mem::take(&mut path.calendar_id), week_start: body.0.settings.week_start, timezone: body.0.settings.timezone, metadata: body.0.metadata, }; execute_with_policy(usecase, &policy, &ctx) .await .map(|calendar| HttpResponse::Ok().json(APIResponse::new(calendar))) .map_err(NettuError::from) } #[derive(Debug)] struct UpdateCalendarUseCase { pub user: User, pub calendar_id: ID, pub week_start: Option<isize>, pub timezone: Option<String>, pub metadata: Option<Metadata>, } #[derive(Debug)] enum UseCaseError { CalendarNotFound, StorageError, InvalidSettings(String), } impl From<UseCaseError> for NettuError { fn from(e: UseCaseError) -> Self { match e { UseCaseError::StorageError => Self::InternalError, UseCaseError::CalendarNotFound => Self::NotFound("The calendar was not found.".into()), UseCaseError::InvalidSettings(err) => Self::BadClientData(format!( "Bad calendar settings provided. Error message: {}", err )), } } } #[async_trait::async_trait(?Send)] impl UseCase for UpdateCalendarUseCase { type Response = Calendar; type Error = UseCaseError; const NAME: &'static str = "UpdateCalendar"; async fn execute(&mut self, ctx: &NettuContext) -> Result<Self::Response, Self::Error> { let mut calendar = match ctx.repos.calendars.find(&self.calendar_id).await { Some(cal) if cal.user_id == self.user.id => cal, _ => return Err(UseCaseError::CalendarNotFound), }; if let Some(wkst) = self.week_start { if !calendar.settings.set_week_start(wkst) { return Err(UseCaseError::InvalidSettings(format!( "Invalid week start: {}, must be between 0 and 6", wkst ))); } } if let Some(timezone) = &self.timezone { if !calendar.settings.set_timezone(timezone) { return
; } } if let Some(metadata) = &self.metadata { calendar.metadata = metadata.clone(); } ctx.repos .calendars .save(&calendar) .await .map(|_| calendar) .map_err(|_| UseCaseError::StorageError) } } impl PermissionBoundary for UpdateCalendarUseCase { fn permissions(&self) -> Vec<Permission> { vec![Permission::UpdateCalendar] } } #[cfg(test)] mod test { use nettu_scheduler_domain::{Account, Calendar, User}; use nettu_scheduler_infra::setup_context; use super::*; #[actix_web::main] #[test] async fn it_rejects_invalid_wkst() { let ctx = setup_context().await; let account = Account::default(); ctx.repos.accounts.insert(&account).await.unwrap(); let user = User::new(account.id.clone()); ctx.repos.users.insert(&user).await.unwrap(); let calendar = Calendar::new(&user.id, &account.id); ctx.repos.calendars.insert(&calendar).await.unwrap(); let mut usecase = UpdateCalendarUseCase { user, calendar_id: calendar.id.into(), week_start: Some(20), timezone: None, metadata: None, }; let res = usecase.execute(&ctx).await; assert!(res.is_err()); } #[actix_web::main] #[test] async fn it_update_settings_with_valid_wkst() { let ctx = setup_context().await; let account = Account::default(); ctx.repos.accounts.insert(&account).await.unwrap(); let user = User::new(account.id.clone()); ctx.repos.users.insert(&user).await.unwrap(); let calendar = Calendar::new(&user.id, &account.id); ctx.repos.calendars.insert(&calendar).await.unwrap(); assert_eq!(calendar.settings.week_start, 0); let new_wkst = 3; let mut usecase = UpdateCalendarUseCase { user, calendar_id: calendar.id.clone(), week_start: Some(new_wkst), timezone: None, metadata: Some(Metadata::new()), }; let res = usecase.execute(&ctx).await; assert!(res.is_ok()); let calendar = ctx.repos.calendars.find(&calendar.id).await.unwrap(); assert_eq!(calendar.settings.week_start, new_wkst); } }
Err(UseCaseError::InvalidSettings(format!( "Invalid timezone: {}, must be a valid IANA Timezone string", timezone )))
call_expression
[]
Rust
tower-balance/src/p2c/service.rs
JeanMertz/tower
7e55b7fa0b2db4ff36fd90f3700bd628c89951b6
use crate::error; use futures::{future, Async, Future, Poll}; use rand::{rngs::SmallRng, SeedableRng}; use tower_discover::{Change, Discover}; use tower_load::Load; use tower_ready_cache::{error::Failed, ReadyCache}; use tower_service::Service; use tracing::{debug, trace}; #[derive(Debug)] pub struct Balance<D: Discover, Req> { discover: D, services: ReadyCache<D::Key, D::Service, Req>, ready_index: Option<usize>, rng: SmallRng, } impl<D, Req> Balance<D, Req> where D: Discover, D::Service: Service<Req>, <D::Service as Service<Req>>::Error: Into<error::Error>, { pub fn new(discover: D, rng: SmallRng) -> Self { Self { rng, discover, ready_index: None, services: ReadyCache::default(), } } pub fn from_entropy(discover: D) -> Self { Self::new(discover, SmallRng::from_entropy()) } pub fn len(&self) -> usize { self.services.len() } pub(crate) fn discover_mut(&mut self) -> &mut D { &mut self.discover } } impl<D, Req> Balance<D, Req> where D: Discover, D::Key: Clone, D::Error: Into<error::Error>, D::Service: Service<Req> + Load, <D::Service as Load>::Metric: std::fmt::Debug, <D::Service as Service<Req>>::Error: Into<error::Error>, { fn update_pending_from_discover(&mut self) -> Result<(), error::Discover> { debug!("updating from discover"); loop { match self .discover .poll() .map_err(|e| error::Discover(e.into()))? { Async::NotReady => return Ok(()), Async::Ready(Change::Remove(key)) => { trace!("remove"); self.services.evict(&key); } Async::Ready(Change::Insert(key, svc)) => { trace!("insert"); self.services.push(key, svc); } } } } fn promote_pending_to_ready(&mut self) { loop { match self.services.poll_pending() { Ok(Async::Ready(())) => { debug_assert_eq!(self.services.pending_len(), 0); break; } Ok(Async::NotReady) => { debug_assert!(self.services.pending_len() > 0); break; } Err(error) => { debug!(%error, "dropping failed endpoint"); } } } trace!( ready = %self.services.ready_len(), pending = %self.services.pending_len(), "poll_unready" ); } fn p2c_ready_index(&mut self) -> Option<usize> { match self.services.ready_len() { 0 => None, 1 => Some(0), len => { let idxs = rand::seq::index::sample(&mut self.rng, len, 2); let aidx = idxs.index(0); let bidx = idxs.index(1); debug_assert_ne!(aidx, bidx, "random indices must be distinct"); let aload = self.ready_index_load(aidx); let bload = self.ready_index_load(bidx); let chosen = if aload <= bload { aidx } else { bidx }; trace!( a.index = aidx, a.load = ?aload, b.index = bidx, b.load = ?bload, chosen = if chosen == aidx { "a" } else { "b" }, "p2c", ); Some(chosen) } } } fn ready_index_load(&self, index: usize) -> <D::Service as Load>::Metric { let (_, svc) = self.services.get_ready_index(index).expect("invalid index"); svc.load() } } impl<D, Req> Service<Req> for Balance<D, Req> where D: Discover, D::Key: Clone, D::Error: Into<error::Error>, D::Service: Service<Req> + Load, <D::Service as Load>::Metric: std::fmt::Debug, <D::Service as Service<Req>>::Error: Into<error::Error>, { type Response = <D::Service as Service<Req>>::Response; type Error = error::Error; type Future = future::MapErr< <D::Service as Service<Req>>::Future, fn(<D::Service as Service<Req>>::Error) -> error::Error, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.update_pending_from_discover()?; self.promote_pending_to_ready(); loop { if let Some(index) = self.ready_index.take() { match self.services.check_ready_index(index) { Ok(true) => { self.ready_index = Some(index); return Ok(Async::Ready(())); } Ok(false) => { trace!("ready service became unavailable"); } Err(Failed(_, error)) => { debug!(%error, "endpoint failed"); } } } self.ready_index = self.p2c_ready_index(); if self.ready_index.is_none() { debug_assert_eq!(self.services.ready_len(), 0); return Ok(Async::NotReady); } } } fn call(&mut self, request: Req) -> Self::Future { let index = self.ready_index.take().expect("called before ready"); self.services .call_ready_index(index, request) .map_err(Into::into) } }
use crate::error; use futures::{future, Async, Future, Poll}; use rand::{rngs::SmallRng, SeedableRng}; use tower_discover::{Change, Discover}; use tower_load::Load; use tower_ready_cache::{error::Failed, ReadyCache}; use tower_service::Service; use tracing::{debug, trace}; #[derive(Debug)] pub struct Balance<D: Discover, Req> { discover: D, services: ReadyCache<D::Key, D::Service, Req>, ready_index: Option<usize>, rng: SmallRng, } impl<D, Req> Balance<D, Req> where D: Discover, D::Service: Service<Req>, <D::Service as Service<Req>>::Error: Into<error::Error>, { pub fn new(discover: D, rng: SmallRng) -> Self { Self { rng, discover, ready_index: None, services: ReadyCache::default(), } } pub fn from_entropy(discover: D) -> Self { Self::new(discover, SmallRng::from_entropy()) } pub fn len(&self) -> usize { self.services.len() } pub(crate) fn discover_mut(&mut self) -> &mut D { &mut self.discover } } impl<D, Req> Balance<D, Req> where D: Discover, D::Key: Clone, D::Error: Into<error::Error>, D::Service: Service<Req> + Load, <D::Service as Load>::Metric: std::fmt::Debug, <D::Service as Service<Req>>::Error: Into<error::Error>, { fn update_pending_from_discover(&mut self) -> Result<(), error::Discover> { debug!("updating from discover"); loop { match self .discover .poll() .map_err(|e| error::Discover(e.into()))? { Async::NotReady => return Ok(()), Async::Ready(Change::Remove(key)) => { trace!("remove"); self.services.evict(&key); } Async::Ready(Change::Insert(key, svc)) => { trace!("insert"); self.services.push(key, svc); } } } } fn promote_pending_to_ready(&mut self) { loop { match self.services.poll_pending() { Ok(Async::Ready(())) => { debug_assert_eq!(self.services.pending_len(), 0); break; } Ok(Async::NotReady) => { debug_assert!(self.services.pending_len() > 0); break; } Err(error) => { debug!(%error, "dropping failed endpoint"); } } } trace!( ready = %self.services.ready_len(), pending = %self.services.pending_len(), "poll_unready" ); } fn p2c_ready_index(&mut self) -> Option<usize> { match self.services.ready_len() { 0 => None, 1 => Some(0), len => { let idxs = rand::seq::index::sample(&mut self.rng, len, 2); let aidx = idxs.index(0); let bidx = idxs.index(1); debug_assert_ne!(aidx, bidx, "random indices must be distinct"); let aload = self.ready_index_load(aidx); let bload = self.ready_index_load(bidx); let chosen = if aload <= bload { aidx } else { bidx }; trace!( a.index = aidx, a.load = ?aload, b.index = bidx, b.load = ?bload, chosen = if chosen == aidx { "a" } else { "b" }, "p2c", ); Some(chosen) } } } fn ready_index_load(&self, index: usize) -> <D::Service as Load>::Metric { let (_, svc) = self.services.get_ready_index(index).expect("invalid index"); svc.load() } } impl<D, Req> Service<Req> for Balance<D, Req> where D: Discover, D::Key: Clone, D::Error: Into<error::Error>, D::Service: Service<Req> + Load, <D::Service as Load>::Metric: std::fmt::Debug, <D::Service as Service<Req>>::Error: Into<error::Error>, { type Response = <D::Service as Service<Req>>::Response; type Error = error::Error; type Future = future::MapErr< <D::Service as Service<Req>>::Future, fn(<D::Service as Service<Req>>::Error) -> error::Error, >; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.update_pending_from_discover()?; self.promote_pending_to_ready(); loop { if let Some(index) = self.ready_index.take() { match self.services.check_ready_index(index) { Ok(true) => {
} } self.ready_index = self.p2c_ready_index(); if self.ready_index.is_none() { debug_assert_eq!(self.services.ready_len(), 0); return Ok(Async::NotReady); } } } fn call(&mut self, request: Req) -> Self::Future { let index = self.ready_index.take().expect("called before ready"); self.services .call_ready_index(index, request) .map_err(Into::into) } }
self.ready_index = Some(index); return Ok(Async::Ready(())); } Ok(false) => { trace!("ready service became unavailable"); } Err(Failed(_, error)) => { debug!(%error, "endpoint failed"); }
function_block-random_span
[ { "content": "fn new_service<P: Policy<Req, Res, Error> + Clone>(\n\n policy: P,\n\n) -> (tower_retry::Retry<P, Mock>, Handle) {\n\n let (service, handle) = mock::pair();\n\n let service = tower_retry::Retry::new(policy, service);\n\n (service, handle)\n\n}\n\n\n", "file_path": "tower-retry/test...
Rust
src/views/krate_publish.rs
vignesh-sankaran/crates.io
387ae4f2e9f6e653804bb063ae30cadd8c3382be
use std::collections::HashMap; use semver; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use models::krate::MAX_NAME_LENGTH; use models::Crate; use models::DependencyKind; use models::Keyword as CrateKeyword; #[derive(Deserialize, Serialize, Debug)] pub struct EncodableCrateUpload { pub name: EncodableCrateName, pub vers: EncodableCrateVersion, pub deps: Vec<EncodableCrateDependency>, pub features: HashMap<EncodableFeatureName, Vec<EncodableFeature>>, pub authors: Vec<String>, pub description: Option<String>, pub homepage: Option<String>, pub documentation: Option<String>, pub readme: Option<String>, pub readme_file: Option<String>, pub keywords: Option<EncodableKeywordList>, pub categories: Option<EncodableCategoryList>, pub license: Option<String>, pub license_file: Option<String>, pub repository: Option<String>, pub badges: Option<HashMap<String, HashMap<String, String>>>, #[serde(default)] pub links: Option<String>, } #[derive(PartialEq, Eq, Hash, Serialize, Debug, Deref)] pub struct EncodableCrateName(pub String); #[derive(Debug, Deref)] pub struct EncodableCrateVersion(pub semver::Version); #[derive(Debug, Deref)] pub struct EncodableCrateVersionReq(pub semver::VersionReq); #[derive(Serialize, Debug, Deref)] pub struct EncodableKeywordList(pub Vec<EncodableKeyword>); #[derive(Serialize, Debug, Deref)] pub struct EncodableKeyword(pub String); #[derive(Serialize, Debug, Deref)] pub struct EncodableCategoryList(pub Vec<EncodableCategory>); #[derive(Serialize, Deserialize, Debug, Deref)] pub struct EncodableCategory(pub String); #[derive(Serialize, Debug, Deref)] pub struct EncodableFeature(pub String); #[derive(PartialEq, Eq, Hash, Serialize, Debug, Deref)] pub struct EncodableFeatureName(pub String); #[derive(Serialize, Deserialize, Debug)] pub struct EncodableCrateDependency { pub optional: bool, pub default_features: bool, pub name: EncodableCrateName, pub features: Vec<EncodableFeature>, pub version_req: EncodableCrateVersionReq, pub target: Option<String>, pub kind: Option<DependencyKind>, pub explicit_name_in_toml: Option<EncodableCrateName>, } impl<'de> Deserialize<'de> for EncodableCrateName { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateName, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_name(&s) { let value = de::Unexpected::Str(&s); let expected = format!( "a valid crate name to start with a letter, contain only letters, \ numbers, hyphens, or underscores and have at most {} characters", MAX_NAME_LENGTH ); Err(de::Error::invalid_value(value, &expected.as_ref())) } else { Ok(EncodableCrateName(s)) } } } impl<T: ?Sized> PartialEq<T> for EncodableCrateName where String: PartialEq<T>, { fn eq(&self, rhs: &T) -> bool { self.0 == *rhs } } impl<'de> Deserialize<'de> for EncodableKeyword { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeyword, D::Error> { let s = String::deserialize(d)?; if !CrateKeyword::valid_name(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid keyword specifier"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableKeyword(s)) } } } impl<'de> Deserialize<'de> for EncodableFeatureName { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_feature_name(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid feature name containing only letters, \ numbers, hyphens, or underscores"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableFeatureName(s)) } } } impl<'de> Deserialize<'de> for EncodableFeature { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableFeature, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_feature(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid feature name"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableFeature(s)) } } } impl<'de> Deserialize<'de> for EncodableCrateVersion { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersion, D::Error> { let s = String::deserialize(d)?; match semver::Version::parse(&s) { Ok(v) => Ok(EncodableCrateVersion(v)), Err(..) => { let value = de::Unexpected::Str(&s); let expected = "a valid semver"; Err(de::Error::invalid_value(value, &expected)) } } } } impl<'de> Deserialize<'de> for EncodableCrateVersionReq { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersionReq, D::Error> { let s = String::deserialize(d)?; match semver::VersionReq::parse(&s) { Ok(v) => Ok(EncodableCrateVersionReq(v)), Err(..) => { let value = de::Unexpected::Str(&s); let expected = "a valid version req"; Err(de::Error::invalid_value(value, &expected)) } } } } impl<T: ?Sized> PartialEq<T> for EncodableCrateVersionReq where semver::VersionReq: PartialEq<T>, { fn eq(&self, rhs: &T) -> bool { self.0 == *rhs } } impl<'de> Deserialize<'de> for EncodableKeywordList { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeywordList, D::Error> { let inner = <Vec<EncodableKeyword> as Deserialize<'de>>::deserialize(d)?; if inner.len() > 5 { let expected = "at most 5 keywords per crate"; return Err(de::Error::invalid_length(inner.len(), &expected)); } for val in &inner { if val.len() > 20 { let expected = "a keyword with less than 20 characters"; return Err(de::Error::invalid_length(val.len(), &expected)); } } Ok(EncodableKeywordList(inner)) } } impl<'de> Deserialize<'de> for EncodableCategoryList { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCategoryList, D::Error> { let inner = <Vec<EncodableCategory> as Deserialize<'de>>::deserialize(d)?; if inner.len() > 5 { let expected = "at most 5 categories per crate"; Err(de::Error::invalid_length(inner.len(), &expected)) } else { Ok(EncodableCategoryList(inner)) } } } impl Serialize for EncodableCrateVersion { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&(**self).to_string()) } } impl Serialize for EncodableCrateVersionReq { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&(**self).to_string()) } } use diesel::pg::Pg; use diesel::serialize::{self, Output, ToSql}; use diesel::sql_types::Text; use std::io::Write; impl ToSql<Text, Pg> for EncodableFeature { fn to_sql<W: Write>(&self, out: &mut Output<'_, W, Pg>) -> serialize::Result { ToSql::<Text, Pg>::to_sql(&**self, out) } } #[test] fn feature_deserializes_for_valid_features() { use serde_json as json; assert!(json::from_str::<EncodableFeature>("\"foo\"").is_ok()); assert!(json::from_str::<EncodableFeature>("\"\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"/\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"%/%\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"a/a\"").is_ok()); assert!(json::from_str::<EncodableFeature>("\"32-column-tables\"").is_ok()); }
use std::collections::HashMap; use semver; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use models::krate::MAX_NAME_LENGTH; use models::Crate; use models::DependencyKind; use models::Keyword as CrateKeyword; #[derive(Deserialize, Serialize, Debug)] pub struct EncodableCrateUpload { pub name: EncodableCrateName, pub vers: EncodableCrateVersion, pub deps: Vec<EncodableCrateDependency>, pub features: HashMap<EncodableFeatureName, Vec<EncodableFeature>>, pub authors: Vec<String>, pub description: Option<String>, pub homepage: Option<String>, pub documentation: Option<String>, pub readme: Option<String>, pub readme_file: Option<String>, pub keywords: Option<EncodableKeywordList>, pub categories: Option<EncodableCategoryList>, pub license: Option<String>, pub license_file: Option<String>, pub repository: Option<String>, pub badges: Option<HashMap<String, HashMap<String, String>>>, #[serde(default)] pub links: Option<String>, } #[derive(PartialEq, Eq, Hash, Serialize, Debug, Deref)] pub struct EncodableCrateName(pub String); #[derive(Debug, Deref)] pub struct EncodableCrateVersion(pub semver::Version); #[derive(Debug, Deref)] pub struct EncodableCrateVersionReq(pub semver::VersionReq); #[derive(Serialize, Debug, Deref)] pub struct EncodableKeywordList(pub Vec<EncodableKeyword>); #[derive(Serialize, Debug, Deref)] pub struct EncodableKeyword(pub String); #[derive(Serialize, Debug, Deref)] pub struct EncodableCategoryList(pub Vec<EncodableCategory>); #[derive(Serialize, Deserialize, Debug, Deref)] pub struct EncodableCategory(pub String); #[derive(Serialize, Debug, Deref)] pub struct EncodableFeature(pub String); #[derive(PartialEq, Eq, Hash, Serialize, Debug, Deref)] pub struct EncodableFeatureName(pub String); #[derive(Serialize, Deserialize, Debug)] pub struct EncodableCrateDependency { pub optional: bool, pub default_features: bool, pub name: EncodableCrateName, pub features: Vec<EncodableFeature>, pub version_req: EncodableCrateVersionReq, pub target: Option<String>, pub kind: Option<DependencyKind>, pub explicit_name_in_toml: Option<EncodableCrateName>, } impl<'de> Deserialize<'de> for EncodableCrateName { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateName, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_name(&s) { let value = de::Unexpected::Str(&s); let expected = format!( "a valid crate name to start with a letter, contain only letters, \ numbers, hyphens, or underscores and have at most {} characters", MAX_NAME_LENGTH ); Err(de::Error::invalid_value(value, &expected.as_ref())) } else { Ok(EncodableCrateName(s)) } } } impl<T: ?Sized> PartialEq<T> for EncodableCrateName where String: PartialEq<T>, { fn eq(&self, rhs: &T) -> bool { self.0 == *rhs } } impl<'de> Deserialize<'de> for EncodableKeyword { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeyword, D::Error> { let s = String::deserialize(d)?; if !CrateKeyword::valid_name(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid keyword specifier"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableKeyword(s)) } } } impl<'de> Deserialize<'de> for EncodableFeatureName { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_feature_name(&s) { let value = de::Unexpected::Str(&s);
} impl<'de> Deserialize<'de> for EncodableFeature { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableFeature, D::Error> { let s = String::deserialize(d)?; if !Crate::valid_feature(&s) { let value = de::Unexpected::Str(&s); let expected = "a valid feature name"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableFeature(s)) } } } impl<'de> Deserialize<'de> for EncodableCrateVersion { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersion, D::Error> { let s = String::deserialize(d)?; match semver::Version::parse(&s) { Ok(v) => Ok(EncodableCrateVersion(v)), Err(..) => { let value = de::Unexpected::Str(&s); let expected = "a valid semver"; Err(de::Error::invalid_value(value, &expected)) } } } } impl<'de> Deserialize<'de> for EncodableCrateVersionReq { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCrateVersionReq, D::Error> { let s = String::deserialize(d)?; match semver::VersionReq::parse(&s) { Ok(v) => Ok(EncodableCrateVersionReq(v)), Err(..) => { let value = de::Unexpected::Str(&s); let expected = "a valid version req"; Err(de::Error::invalid_value(value, &expected)) } } } } impl<T: ?Sized> PartialEq<T> for EncodableCrateVersionReq where semver::VersionReq: PartialEq<T>, { fn eq(&self, rhs: &T) -> bool { self.0 == *rhs } } impl<'de> Deserialize<'de> for EncodableKeywordList { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableKeywordList, D::Error> { let inner = <Vec<EncodableKeyword> as Deserialize<'de>>::deserialize(d)?; if inner.len() > 5 { let expected = "at most 5 keywords per crate"; return Err(de::Error::invalid_length(inner.len(), &expected)); } for val in &inner { if val.len() > 20 { let expected = "a keyword with less than 20 characters"; return Err(de::Error::invalid_length(val.len(), &expected)); } } Ok(EncodableKeywordList(inner)) } } impl<'de> Deserialize<'de> for EncodableCategoryList { fn deserialize<D: Deserializer<'de>>(d: D) -> Result<EncodableCategoryList, D::Error> { let inner = <Vec<EncodableCategory> as Deserialize<'de>>::deserialize(d)?; if inner.len() > 5 { let expected = "at most 5 categories per crate"; Err(de::Error::invalid_length(inner.len(), &expected)) } else { Ok(EncodableCategoryList(inner)) } } } impl Serialize for EncodableCrateVersion { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&(**self).to_string()) } } impl Serialize for EncodableCrateVersionReq { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&(**self).to_string()) } } use diesel::pg::Pg; use diesel::serialize::{self, Output, ToSql}; use diesel::sql_types::Text; use std::io::Write; impl ToSql<Text, Pg> for EncodableFeature { fn to_sql<W: Write>(&self, out: &mut Output<'_, W, Pg>) -> serialize::Result { ToSql::<Text, Pg>::to_sql(&**self, out) } } #[test] fn feature_deserializes_for_valid_features() { use serde_json as json; assert!(json::from_str::<EncodableFeature>("\"foo\"").is_ok()); assert!(json::from_str::<EncodableFeature>("\"\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"/\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"%/%\"").is_err()); assert!(json::from_str::<EncodableFeature>("\"a/a\"").is_ok()); assert!(json::from_str::<EncodableFeature>("\"32-column-tables\"").is_ok()); }
let expected = "a valid feature name containing only letters, \ numbers, hyphens, or underscores"; Err(de::Error::invalid_value(value, &expected)) } else { Ok(EncodableFeatureName(s)) } }
function_block-function_prefix_line
[]
Rust
programs/vote/src/vote_processor.rs
Flawm/solana
551c24da5792f4452c3c555e562809e8c9e742e5
use { crate::{id, vote_instruction::VoteInstruction, vote_state}, log::*, solana_metrics::inc_new_counter_info, solana_program_runtime::{ invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check, }, solana_sdk::{ feature_set, instruction::InstructionError, keyed_account::{get_signers, keyed_account_at_index, KeyedAccount}, program_utils::limited_deserialize, pubkey::Pubkey, sysvar::rent::Rent, }, std::collections::HashSet, }; pub fn process_instruction( first_instruction_account: usize, data: &[u8], invoke_context: &mut InvokeContext, ) -> Result<(), InstructionError> { let keyed_accounts = invoke_context.get_keyed_accounts()?; trace!("process_instruction: {:?}", data); trace!("keyed_accounts: {:?}", keyed_accounts); let me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; if me.owner()? != id() { return Err(InstructionError::InvalidAccountOwner); } let signers: HashSet<Pubkey> = get_signers(&keyed_accounts[first_instruction_account..]); match limited_deserialize(data)? { VoteInstruction::InitializeAccount(vote_init) => { let rent = get_sysvar_with_account_check::rent( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; verify_rent_exemption(me, &rent)?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 2)?, invoke_context, )?; vote_state::initialize_account(me, &vote_init, &signers, &clock) } VoteInstruction::Authorize(voter_pubkey, vote_authorize) => { let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; vote_state::authorize( me, &voter_pubkey, vote_authorize, &signers, &clock, &invoke_context.feature_set, ) } VoteInstruction::UpdateValidatorIdentity => vote_state::update_validator_identity( me, keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?.unsigned_key(), &signers, ), VoteInstruction::UpdateCommission(commission) => { vote_state::update_commission(me, commission, &signers) } VoteInstruction::Vote(vote) | VoteInstruction::VoteSwitch(vote, _) => { inc_new_counter_info!("vote-native", 1); let slot_hashes = get_sysvar_with_account_check::slot_hashes( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 2)?, invoke_context, )?; vote_state::process_vote( me, &slot_hashes, &clock, &vote, &signers, &invoke_context.feature_set, ) } VoteInstruction::UpdateVoteState(vote_state_update) | VoteInstruction::UpdateVoteStateSwitch(vote_state_update, _) => { if invoke_context .feature_set .is_active(&feature_set::allow_votes_to_directly_update_vote_state::id()) { inc_new_counter_info!("vote-state-native", 1); let sysvar_cache = invoke_context.get_sysvar_cache(); let slot_hashes = sysvar_cache.get_slot_hashes()?; let clock = sysvar_cache.get_clock()?; vote_state::process_vote_state_update( me, slot_hashes.slot_hashes(), &clock, vote_state_update, &signers, ) } else { Err(InstructionError::InvalidInstructionData) } } VoteInstruction::Withdraw(lamports) => { let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?; let rent_sysvar = if invoke_context .feature_set .is_active(&feature_set::reject_non_rent_exempt_vote_withdraws::id()) { Some(invoke_context.get_sysvar_cache().get_rent()?) } else { None }; vote_state::withdraw(me, lamports, to, &signers, rent_sysvar.as_deref()) } VoteInstruction::AuthorizeChecked(vote_authorize) => { if invoke_context .feature_set .is_active(&feature_set::vote_stake_checked_instructions::id()) { let voter_pubkey = &keyed_account_at_index(keyed_accounts, first_instruction_account + 3)? .signer_key() .ok_or(InstructionError::MissingRequiredSignature)?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; vote_state::authorize( me, voter_pubkey, vote_authorize, &signers, &clock, &invoke_context.feature_set, ) } else { Err(InstructionError::InvalidInstructionData) } } } } fn verify_rent_exemption( keyed_account: &KeyedAccount, rent: &Rent, ) -> Result<(), InstructionError> { if !rent.is_exempt(keyed_account.lamports()?, keyed_account.data_len()?) { Err(InstructionError::InsufficientFunds) } else { Ok(()) } } #[cfg(test)] mod tests { use { super::*, crate::{ vote_instruction::{ authorize, authorize_checked, create_account, update_commission, update_validator_identity, update_vote_state, update_vote_state_switch, vote, vote_switch, withdraw, VoteInstruction, }, vote_state::{Vote, VoteAuthorize, VoteInit, VoteState, VoteStateUpdate}, }, bincode::serialize, solana_program_runtime::invoke_context::mock_process_instruction, solana_sdk::{ account::{self, Account, AccountSharedData}, hash::Hash, instruction::{AccountMeta, Instruction}, sysvar::{self, clock::Clock, slot_hashes::SlotHashes}, }, std::str::FromStr, }; fn create_default_account() -> AccountSharedData { AccountSharedData::new(0, 0, &Pubkey::new_unique()) } fn process_instruction( instruction_data: &[u8], transaction_accounts: Vec<(Pubkey, AccountSharedData)>, instruction_accounts: Vec<AccountMeta>, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { mock_process_instruction( &id(), Vec::new(), instruction_data, transaction_accounts, instruction_accounts, expected_result, super::process_instruction, ) } fn process_instruction_as_one_arg( instruction: &Instruction, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { let mut pubkeys: HashSet<Pubkey> = instruction .accounts .iter() .map(|meta| meta.pubkey) .collect(); pubkeys.insert(sysvar::clock::id()); pubkeys.insert(sysvar::rent::id()); pubkeys.insert(sysvar::slot_hashes::id()); let transaction_accounts: Vec<_> = pubkeys .iter() .map(|pubkey| { ( *pubkey, if sysvar::clock::check_id(pubkey) { account::create_account_shared_data_for_test(&Clock::default()) } else if sysvar::slot_hashes::check_id(pubkey) { account::create_account_shared_data_for_test(&SlotHashes::default()) } else if sysvar::rent::check_id(pubkey) { account::create_account_shared_data_for_test(&Rent::free()) } else if *pubkey == invalid_vote_state_pubkey() { AccountSharedData::from(Account { owner: invalid_vote_state_pubkey(), ..Account::default() }) } else { AccountSharedData::from(Account { owner: id(), ..Account::default() }) }, ) }) .collect(); process_instruction( &instruction.data, transaction_accounts, instruction.accounts.clone(), expected_result, ) } fn invalid_vote_state_pubkey() -> Pubkey { Pubkey::from_str("BadVote111111111111111111111111111111111111").unwrap() } #[test] fn test_vote_process_instruction_decode_bail() { process_instruction( &[], Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); } #[test] fn test_spoofed_vote() { process_instruction_as_one_arg( &vote( &invalid_vote_state_pubkey(), &Pubkey::new_unique(), Vote::default(), ), Err(InstructionError::InvalidAccountOwner), ); process_instruction_as_one_arg( &update_vote_state( &invalid_vote_state_pubkey(), &Pubkey::default(), VoteStateUpdate::default(), ), Err(InstructionError::InvalidAccountOwner), ); } #[test] fn test_vote_process_instruction() { solana_logger::setup(); let instructions = create_account( &Pubkey::new_unique(), &Pubkey::new_unique(), &VoteInit::default(), 101, ); process_instruction_as_one_arg(&instructions[1], Err(InstructionError::InvalidAccountData)); process_instruction_as_one_arg( &vote( &Pubkey::new_unique(), &Pubkey::new_unique(), Vote::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &vote_switch( &Pubkey::new_unique(), &Pubkey::new_unique(), Vote::default(), Hash::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &authorize( &Pubkey::new_unique(), &Pubkey::new_unique(), &Pubkey::new_unique(), VoteAuthorize::Voter, ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_vote_state( &Pubkey::default(), &Pubkey::default(), VoteStateUpdate::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_vote_state_switch( &Pubkey::default(), &Pubkey::default(), VoteStateUpdate::default(), Hash::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_validator_identity( &Pubkey::new_unique(), &Pubkey::new_unique(), &Pubkey::new_unique(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_commission(&Pubkey::new_unique(), &Pubkey::new_unique(), 0), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &withdraw( &Pubkey::new_unique(), &Pubkey::new_unique(), 0, &Pubkey::new_unique(), ), Err(InstructionError::InvalidAccountData), ); } #[test] fn test_vote_authorize_checked() { let vote_pubkey = Pubkey::new_unique(); let authorized_pubkey = Pubkey::new_unique(); let new_authorized_pubkey = Pubkey::new_unique(); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Voter, ); instruction.accounts = instruction.accounts[0..2].to_vec(); process_instruction_as_one_arg(&instruction, Err(InstructionError::NotEnoughAccountKeys)); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Withdrawer, ); instruction.accounts = instruction.accounts[0..2].to_vec(); process_instruction_as_one_arg(&instruction, Err(InstructionError::NotEnoughAccountKeys)); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Voter, ); instruction.accounts[3] = AccountMeta::new_readonly(new_authorized_pubkey, false); process_instruction_as_one_arg( &instruction, Err(InstructionError::MissingRequiredSignature), ); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Withdrawer, ); instruction.accounts[3] = AccountMeta::new_readonly(new_authorized_pubkey, false); process_instruction_as_one_arg( &instruction, Err(InstructionError::MissingRequiredSignature), ); let vote_account = AccountSharedData::new(100, VoteState::size_of(), &id()); let clock_address = sysvar::clock::id(); let clock_account = account::create_account_shared_data_for_test(&Clock::default()); let default_authorized_pubkey = Pubkey::default(); let authorized_account = create_default_account(); let new_authorized_account = create_default_account(); let transaction_accounts = vec![ (vote_pubkey, vote_account), (clock_address, clock_account), (default_authorized_pubkey, authorized_account), (new_authorized_pubkey, new_authorized_account), ]; let instruction_accounts = vec![ AccountMeta { pubkey: vote_pubkey, is_signer: false, is_writable: false, }, AccountMeta { pubkey: clock_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: default_authorized_pubkey, is_signer: true, is_writable: false, }, AccountMeta { pubkey: new_authorized_pubkey, is_signer: true, is_writable: false, }, ]; process_instruction( &serialize(&VoteInstruction::AuthorizeChecked(VoteAuthorize::Voter)).unwrap(), transaction_accounts.clone(), instruction_accounts.clone(), Ok(()), ); process_instruction( &serialize(&VoteInstruction::AuthorizeChecked( VoteAuthorize::Withdrawer, )) .unwrap(), transaction_accounts, instruction_accounts, Ok(()), ); } }
use { crate::{id, vote_instruction::VoteInstruction, vote_state}, log::*, solana_metrics::inc_new_counter_info, solana_program_runtime::{ invoke_context::InvokeContext, sysvar_cache::get_sysvar_with_account_check, }, solana_sdk::{ feature_set, instruction::InstructionError, keyed_account::{get_signers, keyed_account_at_index, KeyedAccount}, program_utils::limited_deserialize, pubkey::Pubkey, sysvar::rent::Rent, }, std::collections::HashSet, }; pub fn process_instruction( first_instruction_account: usize, data: &[u8], invoke_context: &mut InvokeContext, ) -> Result<(), InstructionError> { let keyed_accounts = invoke_context.get_keyed_accounts()?; trace!("process_instruction: {:?}", data); trace!("keyed_accounts: {:?}", keyed_accounts); let me = &mut keyed_account_at_index(keyed_accounts, first_instruction_account)?; if me.owner()? != id() { return Err(InstructionError::InvalidAccountOwner); } let signers: HashSet<Pubkey> = get_signers(&keyed_accounts[first_instruction_account..]); match limited_deserialize(data)? { VoteInstruction::InitializeAccount(vote_init) => { let rent = get_sysvar_with_account_check::rent( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; verify_rent_exemption(me, &rent)?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 2)?, invoke_context, )?; vote_state::initialize_account(me, &vote_init, &signers, &clock) } VoteInstruction::Authorize(voter_pubkey, vote_authorize) => { let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; vote_state::authorize( me, &voter_pubkey, vote_authorize, &signers, &clock, &invoke_context.feature_set, ) } VoteInstruction::UpdateValidatorIdentity => vote_state::update_validator_identity( me, keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?.unsigned_key(), &signers, ), VoteInstruction::UpdateCommission(commission) => { vote_state::update_commission(me, commission, &signers) } VoteInstruction::Vote(vote) | VoteInstruction::VoteSwitch(vote, _) => { inc_new_counter_info!("vote-native", 1); let slot_hashes = get_sysvar_with_account_check::slot_hashes( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 2)?, invoke_context, )?; vote_state::process_vote( me, &slot_hashes, &clock, &vote, &signers, &invoke_context.feature_set, ) } VoteInstruction::UpdateVoteState(vote_state_update) | VoteInstruction::UpdateVoteStateSwitch(vote_state_update, _) => { if invoke_context .feature_set .is_active(&feature_set::allow_votes_to_directly_update_vote_state::id()) { inc_new_counter_info!("vote-state-native", 1); let sysvar_cache = invoke_context.get_sysvar_cache(); let slot_hashes = sysvar_cache.get_slot_hashes()?; let clock = sysvar_cache.get_clock()?; vote_state::process_vote_state_update( me, slot_hashes.slot_hashes(), &clock, vote_state_update, &signers, ) } else { Err(InstructionError::InvalidInstructionData) } } VoteInstruction::Withdraw(lamports) => { let to = keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?; let rent_sysvar = if invoke_context .feature_set .is_active(&feature_set::reject_non_rent_exempt_vote_withdraws::id()) { Some(invoke_context.get_sysvar_cache().get_rent()?) } else { None }; vote_state::withdraw(me, lamports, to, &signers, rent_sysvar.as_deref()) } VoteInstruction::AuthorizeChecked(vote_authorize) => { if invoke_context .feature_set .is_active(&feature_set::vote_stake_checked_instructions::id()) { let voter_pubkey = &keyed_account_at_index(keyed_accounts, first_instruction_account + 3)? .signer_key() .ok_or(InstructionError::MissingRequiredSignature)?; let clock = get_sysvar_with_account_check::clock( keyed_account_at_index(keyed_accounts, first_instruction_account + 1)?, invoke_context, )?; vote_state::authorize( me, voter_pubkey, vote_authorize, &signers, &clock, &invoke_context.feature_set, ) } else { Err(InstructionError::InvalidInstructionData) } } } } fn verify_rent_exemption( keyed_account: &KeyedAccount, rent: &Rent, ) -> Result<(), InstructionError> { if !rent.is_exempt(keyed_account.lamports()?, keyed_account.data_len()?) { Err(InstructionError::InsufficientFunds) } else { Ok(()) } } #[cfg(test)] mod tests { use { super::*, crate::{ vote_instruction::{ authorize, authorize_checked, create_account, update_commission, update_validator_identity, update_vote_state, update_vote_state_switch, vote, vote_switch, withdraw, VoteInstruction, }, vote_state::{Vote, VoteAuthorize, VoteInit, VoteState, VoteStateUpdate}, }, bincode::serialize, solana_program_runtime::invoke_context::mock_process_instruction, solana_sdk::{ account::{self, Account, AccountSharedData}, hash::Hash, instruction::{AccountMeta, Instruction}, sysvar::{self, clock::Clock, slot_hashes::SlotHashes}, }, std::str::FromStr, }; fn create_default_account() -> AccountSharedData { AccountSharedData::new(0, 0, &Pubkey::new_unique()) } fn process_instruction( instruction_data: &[u8], transaction_accounts: Vec<(Pubkey, AccountSharedData)>, instruction_accounts: Vec<AccountMeta>, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { mock_process_instruction( &id(), Vec::new(), instruction_data, transaction_accounts, instruction_accounts, expected_result, super::process_instruction, ) } fn process_instruction_as_one_arg( instruction: &Instruction, expected_result: Result<(), InstructionError>, ) -> Vec<AccountSharedData> { let mut pubkeys: HashSet<Pubkey> = instruction .accounts .iter() .map(|meta| meta.pubkey) .collect(); pubkeys.insert(sysvar::clock::id()); pubkeys.insert(sysvar::rent::id()); pubkeys.insert(sysvar::slot_hashes::id()); let transaction_accounts: Vec<_> = pubkeys .iter() .map(|pubkey| { ( *pubkey, if sysvar::clock::check_id(pubkey) { account::create_account_shared_data_for_test(&Clock::default()) } else if sysvar::slot_hashes::check_id(pubkey) { account::create_account_shared_data_for_test(&SlotHashes::default()) } else if sysvar::rent::check_id(pubkey) { account::create_account_shared_data_for_test(&Rent::free()) } else if *pubkey == invalid_vote_state_pubkey() { AccountSharedData::from(Account { owner: invalid_vote_state_pubkey(), ..Account::default() }) } else { AccountSharedData::from(Account { owner: id(), ..Account::default() }) }, ) }) .collect(); process_instruction( &instruction.data, transaction_accounts, instruction.accounts.clone(), expected_result, ) } fn invalid_vote_state_pubkey() -> Pubkey { Pubkey::from_str("BadVote111111111111111111111111111111111111").unwrap() } #[test]
#[test] fn test_spoofed_vote() { process_instruction_as_one_arg( &vote( &invalid_vote_state_pubkey(), &Pubkey::new_unique(), Vote::default(), ), Err(InstructionError::InvalidAccountOwner), ); process_instruction_as_one_arg( &update_vote_state( &invalid_vote_state_pubkey(), &Pubkey::default(), VoteStateUpdate::default(), ), Err(InstructionError::InvalidAccountOwner), ); } #[test] fn test_vote_process_instruction() { solana_logger::setup(); let instructions = create_account( &Pubkey::new_unique(), &Pubkey::new_unique(), &VoteInit::default(), 101, ); process_instruction_as_one_arg(&instructions[1], Err(InstructionError::InvalidAccountData)); process_instruction_as_one_arg( &vote( &Pubkey::new_unique(), &Pubkey::new_unique(), Vote::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &vote_switch( &Pubkey::new_unique(), &Pubkey::new_unique(), Vote::default(), Hash::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &authorize( &Pubkey::new_unique(), &Pubkey::new_unique(), &Pubkey::new_unique(), VoteAuthorize::Voter, ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_vote_state( &Pubkey::default(), &Pubkey::default(), VoteStateUpdate::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_vote_state_switch( &Pubkey::default(), &Pubkey::default(), VoteStateUpdate::default(), Hash::default(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_validator_identity( &Pubkey::new_unique(), &Pubkey::new_unique(), &Pubkey::new_unique(), ), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &update_commission(&Pubkey::new_unique(), &Pubkey::new_unique(), 0), Err(InstructionError::InvalidAccountData), ); process_instruction_as_one_arg( &withdraw( &Pubkey::new_unique(), &Pubkey::new_unique(), 0, &Pubkey::new_unique(), ), Err(InstructionError::InvalidAccountData), ); } #[test] fn test_vote_authorize_checked() { let vote_pubkey = Pubkey::new_unique(); let authorized_pubkey = Pubkey::new_unique(); let new_authorized_pubkey = Pubkey::new_unique(); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Voter, ); instruction.accounts = instruction.accounts[0..2].to_vec(); process_instruction_as_one_arg(&instruction, Err(InstructionError::NotEnoughAccountKeys)); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Withdrawer, ); instruction.accounts = instruction.accounts[0..2].to_vec(); process_instruction_as_one_arg(&instruction, Err(InstructionError::NotEnoughAccountKeys)); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Voter, ); instruction.accounts[3] = AccountMeta::new_readonly(new_authorized_pubkey, false); process_instruction_as_one_arg( &instruction, Err(InstructionError::MissingRequiredSignature), ); let mut instruction = authorize_checked( &vote_pubkey, &authorized_pubkey, &new_authorized_pubkey, VoteAuthorize::Withdrawer, ); instruction.accounts[3] = AccountMeta::new_readonly(new_authorized_pubkey, false); process_instruction_as_one_arg( &instruction, Err(InstructionError::MissingRequiredSignature), ); let vote_account = AccountSharedData::new(100, VoteState::size_of(), &id()); let clock_address = sysvar::clock::id(); let clock_account = account::create_account_shared_data_for_test(&Clock::default()); let default_authorized_pubkey = Pubkey::default(); let authorized_account = create_default_account(); let new_authorized_account = create_default_account(); let transaction_accounts = vec![ (vote_pubkey, vote_account), (clock_address, clock_account), (default_authorized_pubkey, authorized_account), (new_authorized_pubkey, new_authorized_account), ]; let instruction_accounts = vec![ AccountMeta { pubkey: vote_pubkey, is_signer: false, is_writable: false, }, AccountMeta { pubkey: clock_address, is_signer: false, is_writable: false, }, AccountMeta { pubkey: default_authorized_pubkey, is_signer: true, is_writable: false, }, AccountMeta { pubkey: new_authorized_pubkey, is_signer: true, is_writable: false, }, ]; process_instruction( &serialize(&VoteInstruction::AuthorizeChecked(VoteAuthorize::Voter)).unwrap(), transaction_accounts.clone(), instruction_accounts.clone(), Ok(()), ); process_instruction( &serialize(&VoteInstruction::AuthorizeChecked( VoteAuthorize::Withdrawer, )) .unwrap(), transaction_accounts, instruction_accounts, Ok(()), ); } }
fn test_vote_process_instruction_decode_bail() { process_instruction( &[], Vec::new(), Vec::new(), Err(InstructionError::NotEnoughAccountKeys), ); }
function_block-full_function
[ { "content": "pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result<Pubkey, SanitizeError> {\n\n let len = std::mem::size_of::<Pubkey>();\n\n if data.len() < *current + len {\n\n return Err(SanitizeError::IndexOutOfBounds);\n\n }\n\n let e = Pubkey::new(&data[*current..*current + len...
Rust
src/widgets/image_widget.rs
alexislozano/rust-pushrod
57f4129861a2e22608cbc9cb0aa151b5fb424c62
use crate::render::callbacks::CallbackRegistry; use crate::render::widget::*; use crate::render::widget_cache::WidgetContainer; use crate::render::widget_config::{ CompassPosition, Config, WidgetConfig, CONFIG_COLOR_BASE, CONFIG_IMAGE_POSITION, CONFIG_SIZE, }; use crate::render::Points; use sdl2::image::LoadTexture; use sdl2::rect::Rect; use sdl2::render::{Canvas, TextureQuery}; use sdl2::video::Window; use std::collections::HashMap; use std::path::Path; pub struct ImageWidget { config: WidgetConfig, system_properties: HashMap<i32, String>, callback_registry: CallbackRegistry, image_name: String, scaled: bool, } impl ImageWidget { pub fn new(image_name: String, x: i32, y: i32, w: u32, h: u32, scaled: bool) -> Self { Self { config: WidgetConfig::new(x, y, w, h), system_properties: HashMap::new(), callback_registry: CallbackRegistry::new(), image_name, scaled, } } } impl Widget for ImageWidget { fn draw(&mut self, c: &mut Canvas<Window>) { let base_color = self.get_color(CONFIG_COLOR_BASE); c.set_draw_color(base_color); c.fill_rect(self.get_drawing_area()).unwrap(); let texture_creator = c.texture_creator(); let texture = texture_creator .load_texture(Path::new(&self.image_name)) .unwrap(); let widget_w = self.get_size(CONFIG_SIZE)[0] as i32; let widget_h = self.get_size(CONFIG_SIZE)[1] as i32; let TextureQuery { width, height, .. } = texture.query(); let texture_x = match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::W | CompassPosition::SW => { self.get_config().to_x(0) } CompassPosition::N | CompassPosition::Center | CompassPosition::S => { self.get_config().to_x((widget_w - width as i32) / 2) } CompassPosition::NE | CompassPosition::E | CompassPosition::SE => { self.get_config().to_x(widget_w - width as i32) } }; let texture_y = match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::N | CompassPosition::NE => { self.get_config().to_y(0) } CompassPosition::W | CompassPosition::Center | CompassPosition::E => { self.get_config().to_y((widget_h - height as i32) / 2) } CompassPosition::SW | CompassPosition::S | CompassPosition::SE => { self.get_config().to_y(widget_h - height as i32) } }; if !self.scaled { c.copy( &texture, None, Rect::new(texture_x, texture_y, width, height), ) .unwrap(); } else { c.copy( &texture, None, Rect::new( self.get_config().to_x(0), self.get_config().to_y(0), widget_w as u32, widget_h as u32, ), ) .unwrap(); } } fn on_config_changed(&mut self, _k: u8, _v: Config) { if _k == CONFIG_IMAGE_POSITION { self.get_config().set_invalidate(true); } } default_widget_properties!(); default_widget_callbacks!(); }
use crate::render::callbacks::CallbackRegistry; use crate::render::widget::*; use crate::render::widget_cache::WidgetContainer; use crate::render::widget_config::{ CompassPosition, Config, WidgetConfig, CONFIG_COLOR_BASE, CONFIG_IMAGE_POSITION, CONFIG_SIZE, }; use crate::render::Points; use sdl2::image::LoadTexture; use sdl2::rect::Rect; use sdl2::render::{Canvas, TextureQuery}; use sdl2::video::Window; use std::collections::HashMap; use std::path::Path; pub struct ImageWidget { config: WidgetConfig, system_properties: HashMap<i32, String>, callback_registry: CallbackRegistry, image_name: String, scaled: bool, } impl ImageWidget { pub fn new(image_name: String, x: i32, y: i32, w: u32, h: u32, scaled: bool) -> Self { Self { config: WidgetConfig::new(x, y, w, h), system_properties: HashMap::new(), callback_registry: CallbackRegistry::new(), image_name, scaled, } } } impl Widget for ImageWidget { fn draw(&mut self, c: &mut Canvas<Window>) { let base_color = self.get_color(CONFIG_COLOR_BASE); c.set_draw_color(base_color); c.fill_rect(self.get_drawing_area()).unwrap(); let texture_creator = c.texture_creator(); let texture = texture_creator .load_texture(Path::new(&self.image_name)) .unwrap(); let widget_w = self.get_size(CONFIG_SIZE)[0] as i32; let widget_h = self.get_size(CONFIG_SIZE)[1] as i32; let TextureQuery { width, height, .. } = texture.query(); let texture_x =
; let texture_y = match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::N | CompassPosition::NE => { self.get_config().to_y(0) } CompassPosition::W | CompassPosition::Center | CompassPosition::E => { self.get_config().to_y((widget_h - height as i32) / 2) } CompassPosition::SW | CompassPosition::S | CompassPosition::SE => { self.get_config().to_y(widget_h - height as i32) } }; if !self.scaled { c.copy( &texture, None, Rect::new(texture_x, texture_y, width, height), ) .unwrap(); } else { c.copy( &texture, None, Rect::new( self.get_config().to_x(0), self.get_config().to_y(0), widget_w as u32, widget_h as u32, ), ) .unwrap(); } } fn on_config_changed(&mut self, _k: u8, _v: Config) { if _k == CONFIG_IMAGE_POSITION { self.get_config().set_invalidate(true); } } default_widget_properties!(); default_widget_callbacks!(); }
match self.get_compass(CONFIG_IMAGE_POSITION) { CompassPosition::NW | CompassPosition::W | CompassPosition::SW => { self.get_config().to_x(0) } CompassPosition::N | CompassPosition::Center | CompassPosition::S => { self.get_config().to_x((widget_w - width as i32) / 2) } CompassPosition::NE | CompassPosition::E | CompassPosition::SE => { self.get_config().to_x(widget_w - width as i32) } }
if_condition
[ { "content": "pub fn widget_id_for_name(widgets: &[WidgetContainer], name: String) -> usize {\n\n match widgets.iter().find(|x| x.get_widget_name() == name.clone()) {\n\n Some(x) => x.get_widget_id() as usize,\n\n None => 0 as usize,\n\n }\n\n}\n", "file_path": "src/render/callbacks.rs",...
Rust
src/nfa.rs
MarioJim/finite-automata-tui
c22e9c0de28a199efbdfcabda7e8184fecaf1a20
use multimap::MultiMap; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fmt; #[derive(Debug)] pub struct NFA { pub alphabet: HashSet<String>, initial_state: String, states: HashMap<String, NFAState>, } #[derive(Debug)] struct NFAState { is_final: bool, transitions: MultiMap<String, String>, } impl NFA { fn transition(&self, from_state: &str, symbol: &str) -> Option<&Vec<String>> { self.states .get(from_state) .unwrap() .transitions .get_vec(symbol) } pub fn resolve_transitions(&self, symbols: Vec<&str>) -> Result<Vec<String>, String> { let mut current_states: HashSet<&str> = [self.initial_state.as_ref()].iter().cloned().collect(); for symbol in symbols { if !self.alphabet.contains(symbol) { return Err(format!("Symbol {} isn't the in alphabet", symbol)); } let mut next_states: HashSet<&str> = HashSet::with_capacity(self.states.len()); for current_state in current_states { if let Some(v) = self.transition(current_state, &symbol) { for state_to_transition in v { next_states.insert(state_to_transition.as_str()); } } } current_states = next_states; } Ok(current_states.iter().map(|&s| s.to_string()).collect()) } pub fn is_any_state_final(&self, states: Vec<String>) -> bool { for state in states { if self.states.get(state.as_str()).unwrap().is_final { return true; } } false } } impl TryFrom<String> for NFA { type Error = &'static str; fn try_from(file: String) -> Result<Self, Self::Error> { let mut lines = file.lines(); let mut states: HashMap<String, NFAState> = HashMap::new(); for state_name in lines.next().unwrap().split(',') { states.insert( state_name.to_string(), NFAState { is_final: false, transitions: MultiMap::new(), }, ); } let mut alphabet: HashSet<String> = HashSet::new(); match lines.next() { Some(s) => { let symbols: Vec<&str> = s.split(',').collect(); for symbol in symbols { alphabet.insert(symbol.to_string()); } } None => return Err("Couldn't find the alphabet definition"), }; let initial_state = match lines.next() { Some(s) => match states.contains_key(s) { true => s.to_string(), false => return Err("Couldn't find initial state"), }, None => return Err("Couldn't find the initial state definition"), }; let final_states: Vec<&str> = match lines.next() { Some(s) => s.split(',').collect(), None => return Err("Couldn't find the final states definition"), }; for final_state in final_states { match states.get_mut(final_state) { Some(state) => state.is_final = true, None => return Err("Couldn't find final state"), } } for line in lines { let mut line_iter = line.split("=>"); let from_symbol: Vec<&str> = match line_iter.next() { Some(s) => s.split(',').collect(), None => return Err("Transition line is empty"), }; let from_state = match from_symbol.get(0) { Some(&s) => match states.contains_key(s) { true => s, false => { return Err("Couldn't find a transition's starting state in defined states") } }, None => return Err("Couldn't find starting state in a transition"), }; let symbol = match from_symbol.get(1) { Some(&s) => match alphabet.contains(s) { true => s, false => return Err("Symbol doesn't belong to alphabet definition"), }, None => return Err("Couldn't find symbol in transition definition"), }; let next_states: Vec<&str> = match line_iter.next() { Some(s) => s.split(',').collect(), None => return Err("Transition couldn't be split correctly"), }; for next_state in next_states { if states.contains_key(next_state) { states .get_mut(from_state) .unwrap() .transitions .insert(symbol.to_string(), next_state.to_string()); } else { return Err("Couldn't find ending state in transition in defined states"); } } } Ok(NFA { states, initial_state, alphabet, }) } } impl fmt::Display for NFA { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Automata {{\n")?; write!(f, " Language: {:?},\n", self.alphabet)?; write!(f, " States: [\n")?; for (state_name, state) in &self.states { write!(f, " {}: {:?}\n", state_name, state)?; } write!(f, " ],\n")?; write!(f, " Initial State: {},\n", self.initial_state)?; write!(f, "}}") } }
use multimap::MultiMap; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::fmt; #[derive(Debug)] pub struct NFA { pub alphabet: HashSet<String>, initial_state: String, states: HashMap<String, NFAState>, } #[derive(Debug)] struct NFAState { is_final: bool, transitions: MultiMap<String, String>, } impl NFA { fn transition(&self, from_state: &str, symbol: &str) -> Option<&Vec<String>> { self.states .get(from_state) .unwrap() .transitions .get_vec(symbol) } pub fn resolve_transitions(&self, symbols: Vec<&str>) -> Result<Vec<String>, String> { let mut current_states: HashSet<&str> = [self.initial_state.as_ref()].iter().cloned().collect(); for symbol in symbols { if !self.alphabet.contains(symbol) { return Err(format!("Symbol {} isn't the in alphabet", symbol)); } let mut next_states: HashSet<&str> = HashSet::with_capacity(self.states.len()); for current_state in current_states { if let Some(v) = self.transition(current_state, &symbol) { for state_to_transition in v { next_states.insert(state_to_transition.as_str()); } } } current_states = next_states; } Ok(current_states.iter().map(|&s| s.to_string()).collect()) } pub fn is_any_state_final(&self, states: Vec<String>) -> bool { for state in states { if self.states.get(state.as_str()).unwrap().is_final { return true; } } false } } impl TryFrom<String> for NFA { type Error = &'static str; fn try_from(file: String) -> Result<Self, Self::Error> { let mut lines = file.lines(); let mut states: HashMap<String, NFAState> = HashMap::new(); for state_name in lines.next().unwrap().split(',') { states.insert( state_name.to_string(), NFAState { is_final: false, transitions: MultiMap::new(), }, ); } let mut alphabet: HashSet<String> = HashSet::new(); match lines.next() { Some(s) => { let symbols: Vec<&str> = s.split(',').collect(); for symbol in symbols { alphabet.insert(symbol.to_string()); } } None => return Err("Couldn't find the alphabet definition"), }; let initial_state = match lines.next() { Some(s) => match states.contains_key(s) { true => s.to_string(), false => return Err("Couldn't find initial state"), }, None => return Err("Couldn't find the initial state definition"), }; let final_states: Vec<&str> = match lines.next() { Some(s) => s.split(',').collect(), None => return Err("Couldn't find the final states definition"), }; for final_state in final_states { match states.get_mut(final_state) { Some(state) => state.is_final = true, None => return Err("Couldn't find final state"), } } for line in lines { let mut line_iter = line.split("=>"); let from_symbol: Vec<&str> =
; let from_state = match from_symbol.get(0) { Some(&s) => match states.contains_key(s) { true => s, false => { return Err("Couldn't find a transition's starting state in defined states") } }, None => return Err("Couldn't find starting state in a transition"), }; let symbol = match from_symbol.get(1) { Some(&s) => match alphabet.contains(s) { true => s, false => return Err("Symbol doesn't belong to alphabet definition"), }, None => return Err("Couldn't find symbol in transition definition"), }; let next_states: Vec<&str> = match line_iter.next() { Some(s) => s.split(',').collect(), None => return Err("Transition couldn't be split correctly"), }; for next_state in next_states { if states.contains_key(next_state) { states .get_mut(from_state) .unwrap() .transitions .insert(symbol.to_string(), next_state.to_string()); } else { return Err("Couldn't find ending state in transition in defined states"); } } } Ok(NFA { states, initial_state, alphabet, }) } } impl fmt::Display for NFA { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Automata {{\n")?; write!(f, " Language: {:?},\n", self.alphabet)?; write!(f, " States: [\n")?; for (state_name, state) in &self.states { write!(f, " {}: {:?}\n", state_name, state)?; } write!(f, " ],\n")?; write!(f, " Initial State: {},\n", self.initial_state)?; write!(f, "}}") } }
match line_iter.next() { Some(s) => s.split(',').collect(), None => return Err("Transition line is empty"), }
if_condition
[ { "content": "pub fn show_tui(automata_struct: nfa::NFA) {\n\n let instructions = \"Write the symbols separated by a space, press Esc or Ctrl+C to quit\";\n\n let mut input_f = input_field::InputField::new();\n\n let term = Term::with_height(TermHeight::Fixed(4)).unwrap();\n\n while let Ok(ev) = ter...
Rust
src/middle/builder.rs
reitermarkus/libffi-rs
693182bf1fb16da2c00ace0cc13920a98845c9a3
use std::any::Any; use super::types::Type; #[derive(Clone, Debug)] pub struct Builder { args: Vec<Type>, res: Type, abi: super::FfiAbi, } impl Default for Builder { fn default() -> Self { Builder::new() } } impl Builder { pub fn new() -> Self { Builder { args: vec![], res: Type::void(), abi: super::ffi_abi_FFI_DEFAULT_ABI, } } pub fn arg(mut self, type_: Type) -> Self { self.args.push(type_); self } pub fn args<I>(mut self, types: I) -> Self where I: IntoIterator<Item=Type> { self.args.extend(types.into_iter()); self } pub fn res(mut self, type_: Type) -> Self { self.res = type_; self } pub fn abi(mut self, abi: super::FfiAbi) -> Self { self.abi = abi; self } pub fn into_cif(self) -> super::Cif { let mut result = super::Cif::new(self.args, self.res); result.set_abi(self.abi); result } pub fn into_closure<U, R>( self, callback: super::Callback<U, R>, userdata: &U) -> super::Closure { super::Closure::new(self.into_cif(), callback, userdata) } pub fn into_closure_mut<U, R>( self, callback: super::CallbackMut<U, R>, userdata: &mut U) -> super::Closure { super::Closure::new_mut(self.into_cif(), callback, userdata) } pub fn into_closure_once<U: Any, R>( self, callback: super::CallbackOnce<U, R>, userdata: U) -> super::ClosureOnce { super::ClosureOnce::new(self.into_cif(), callback, userdata) } }
use std::any::Any; use super::types::Type; #[derive(Clone, Debug)] pub struct Builder { args: Vec<Type>, res: Type, abi: super::FfiAbi, } impl Default for Builder { fn default() -> Self { Builder::new() } } impl Builder { pub fn new() -> Self { Builder { args: vec![], res: Type::void(), abi: super::ffi_abi_FFI_DEFAULT_ABI, } } pub fn arg(mut self, type_: Type) -> Self { self.args.push(type_); self }
pub fn res(mut self, type_: Type) -> Self { self.res = type_; self } pub fn abi(mut self, abi: super::FfiAbi) -> Self { self.abi = abi; self } pub fn into_cif(self) -> super::Cif { let mut result = super::Cif::new(self.args, self.res); result.set_abi(self.abi); result } pub fn into_closure<U, R>( self, callback: super::Callback<U, R>, userdata: &U) -> super::Closure { super::Closure::new(self.into_cif(), callback, userdata) } pub fn into_closure_mut<U, R>( self, callback: super::CallbackMut<U, R>, userdata: &mut U) -> super::Closure { super::Closure::new_mut(self.into_cif(), callback, userdata) } pub fn into_closure_once<U: Any, R>( self, callback: super::CallbackOnce<U, R>, userdata: U) -> super::ClosureOnce { super::ClosureOnce::new(self.into_cif(), callback, userdata) } }
pub fn args<I>(mut self, types: I) -> Self where I: IntoIterator<Item=Type> { self.args.extend(types.into_iter()); self }
function_block-full_function
[ { "content": "/// Constructs an [`Arg`](struct.Arg.html) for passing to\n\n/// [`call`](fn.call.html).\n\npub fn arg<T: super::CType>(arg: &T) -> Arg {\n\n Arg::new(arg)\n\n}\n\n\n\n/// Performs a dynamic call to a C function.\n\n///\n\n/// To reduce boilerplate, see [`ffi_call!`](../../macro.ffi_call!.html)...
Rust
baustelle/src/containerfile.rs
akhramov/knast
8c9f5f481a467a22c7cc47f11a28fe52536f9950
use std::{convert::TryFrom, fs, io::Read, path::PathBuf}; use anyhow::{Context, Error}; use dockerfile_parser::{ Dockerfile as Containerfile, FromInstruction, Instruction::{self, *}, }; use futures::{ channel::mpsc::{unbounded, SendError, UnboundedSender}, future::{self, Future}, stream::Stream, SinkExt, TryFutureExt, }; use uuid::Uuid; use registratur::v2::{ client::Client, domain::{config::Config, manifest::Manifest}, }; use crate::{ fetcher::{Fetcher, LayerDownloadStatus}, runtime_config::RuntimeConfig, storage::{Storage, StorageEngine, BLOBS_STORAGE_KEY}, unpacker::Unpacker, }; #[derive(Clone, Debug)] pub enum EvaluationUpdate { From(LayerDownloadStatus), } pub struct Builder<'a, T: StorageEngine> { fetcher: Fetcher<'a, T>, storage: &'a Storage<T>, container_folder: PathBuf, } impl<'a, T: StorageEngine> Builder<'a, T> { #[fehler::throws] pub fn new( registry_url: &'a str, architecture: String, os: Vec<String>, storage: &'a Storage<T>, ) -> Self { let client = Client::build(registry_url)?; let fetcher = Fetcher::new(storage, client, architecture, os); let container_uuid = format!("{}", Uuid::new_v4()); let container_folder = storage.folder().join("containers").join(&container_uuid); fs::create_dir_all(&container_folder)?; Self { fetcher, container_folder, storage, } } #[fehler::throws] pub fn interpret( &self, file: impl Read, ) -> ( impl Stream<Item = EvaluationUpdate>, impl Future<Output = Result<PathBuf, Error>> + '_, ) { let (sender, receiver) = unbounded(); let containerfile = Containerfile::from_reader(file)?; let result = containerfile.iter_stages().flat_map(|stage| { stage.instructions.into_iter().map(|instruction| { self.execute_instruction(instruction.clone(), sender.clone()) }) }); let folder = self.container_folder.clone(); let completion_future = future::try_join_all(result).and_then(|_| future::ok(folder)); (receiver, completion_future) } #[fehler::throws] async fn execute_instruction( &self, instruction: Instruction, sender: UnboundedSender<EvaluationUpdate>, ) { match instruction { From(instruction) => { self.execute_from_instruction(instruction, sender).await?; } _ => { log::warn!( "Unhandled containerfile instruction {:?}", instruction ) } } } #[fehler::throws] async fn execute_from_instruction( &self, instruction: FromInstruction, sender: UnboundedSender<EvaluationUpdate>, ) { let image = &instruction.image_parsed; let sender = sender.with(|val| { future::ok::<_, SendError>(EvaluationUpdate::From(val)) }); let default_tag = String::from("latest"); let tag = image.tag.as_ref().unwrap_or(&default_tag); let digest = self.fetcher.fetch(&image.image, &tag, sender).await?; let manifest: Manifest = self.storage.get(BLOBS_STORAGE_KEY, &digest)?.context( "Fetched manifest was not found. Possible storage corruption", )?; let config: Config = self .storage .get(BLOBS_STORAGE_KEY, manifest.config.digest)? .context( "Fetched config was not found. Possible storage corruption", )?; let destination = self.container_folder.join("rootfs"); let unpacker = Unpacker::new(&self.storage, &destination); unpacker.unpack(digest)?; let runtime_config = RuntimeConfig::try_from((config, destination.as_path()))?; serde_json::to_writer( fs::File::create(&self.container_folder.join("config.json"))?, &runtime_config, )?; } } #[cfg(test)] mod tests { use futures::StreamExt; use super::*; use crate::storage::TestStorage as Storage; #[tokio::test] async fn test_interpretation() { #[cfg(feature = "integration_testing")] let (url, _mocks) = ("https://registry-1.docker.io", ()); #[cfg(not(feature = "integration_testing"))] let (url, _mocks) = test_helpers::mock_server!("unix.yml"); let tempdir = tempfile::tempdir().expect("Failed to create a tempdir"); let storage = Storage::new(tempdir.path()).expect("Unable to initialize cache"); let builder = Builder::new(&url, "amd64".into(), vec!["linux".into()], &storage) .expect("failed to initialize the builder"); let containerfile = test_helpers::fixture!("containerfile"); let (updates, complete_future) = builder.interpret(containerfile.as_bytes()).unwrap(); let (_, result) = future::join(updates.collect::<Vec<_>>(), complete_future).await; let container_folder = result.expect("Unable to enterpret containerfile"); assert!(container_folder.join("rootfs/etc/passwd").exists()); let file = fs::File::open(container_folder.join("config.json")) .expect("Failed to open OCI runtime config file"); let config: RuntimeConfig = serde_json::from_reader(file) .expect("Failed to parse OCI runtime config file"); let command = config.process.unwrap().args.unwrap().join(" "); assert_eq!(command, "nginx -g daemon off;"); } }
use std::{convert::TryFrom, fs, io::Read, path::PathBuf}; use anyhow::{Context, Error}; use dockerfile_parser::{ Dockerfile as Containerfile, FromInstruction, Instruction::{self, *}, }; use futures::{ channel::mpsc::{unbounded, SendError, UnboundedSender}, future::{self, Future}, stream::Stream, SinkExt, TryFutureExt, }; use uuid::Uuid; use registratur::v2::{ client::Client, domain::{config::Config, manifest::Manifest}, }; use crate::{ fetcher::{Fetcher, LayerDownloadStatus}, runtime_config::RuntimeConfig, storage::{Storage, StorageEngine, BLOBS_STORAGE_KEY}, unpacker::Unpacker, }; #[derive(Clone, Debug)] pub enum EvaluationUpdate { From(LayerDownloadStatus), } pub struct Builder<'a, T: StorageEngine> { fetcher: Fetcher<'a, T>, storage: &'a Storage<T>, container_folder: PathBuf, } impl<'a, T: StorageEngine> Builder<'a, T> { #[fehler::throws] pub fn new( registry_url: &'a str, architecture: String, os: Vec<String>, storage: &'a Storage<T>, ) -> Self { let client = Client::build(registry_url)?; let fetcher = Fetcher::new(storage, client, architecture, os); let container_uuid = format!("{}", Uuid::new_v4()); let container_folder = storage.folder().join("containers").join(&container_uuid); fs::create_dir_all(&container_folder)?; Self { fetcher, container_folder, storage, } } #[fehler::throws] pub fn interpret( &self, file: impl Read, ) -> ( impl Stream<Item = EvaluationUpdate>, impl Future<Output = Result<PathBuf, Error>> + '_, ) { let (sender, receiver) = unbounded(); let containerfile = Containerfile::from_reader(file)?; let result = containerfile.iter_stages().flat_map(|stage| { stage.instructions.into_iter().map(|instruction| { self.execute_instruction(instruction.clone(), sender.clone()) }) }); let folder = self.container_folder.clone(); let completion_future = future::try_join_all(result).and_then(|_| future::ok(folder)); (receiver, completion_future) } #[fehler::throws] async fn execute_instruction( &self, instruction: Instruction, se
#[fehler::throws] async fn execute_from_instruction( &self, instruction: FromInstruction, sender: UnboundedSender<EvaluationUpdate>, ) { let image = &instruction.image_parsed; let sender = sender.with(|val| { future::ok::<_, SendError>(EvaluationUpdate::From(val)) }); let default_tag = String::from("latest"); let tag = image.tag.as_ref().unwrap_or(&default_tag); let digest = self.fetcher.fetch(&image.image, &tag, sender).await?; let manifest: Manifest = self.storage.get(BLOBS_STORAGE_KEY, &digest)?.context( "Fetched manifest was not found. Possible storage corruption", )?; let config: Config = self .storage .get(BLOBS_STORAGE_KEY, manifest.config.digest)? .context( "Fetched config was not found. Possible storage corruption", )?; let destination = self.container_folder.join("rootfs"); let unpacker = Unpacker::new(&self.storage, &destination); unpacker.unpack(digest)?; let runtime_config = RuntimeConfig::try_from((config, destination.as_path()))?; serde_json::to_writer( fs::File::create(&self.container_folder.join("config.json"))?, &runtime_config, )?; } } #[cfg(test)] mod tests { use futures::StreamExt; use super::*; use crate::storage::TestStorage as Storage; #[tokio::test] async fn test_interpretation() { #[cfg(feature = "integration_testing")] let (url, _mocks) = ("https://registry-1.docker.io", ()); #[cfg(not(feature = "integration_testing"))] let (url, _mocks) = test_helpers::mock_server!("unix.yml"); let tempdir = tempfile::tempdir().expect("Failed to create a tempdir"); let storage = Storage::new(tempdir.path()).expect("Unable to initialize cache"); let builder = Builder::new(&url, "amd64".into(), vec!["linux".into()], &storage) .expect("failed to initialize the builder"); let containerfile = test_helpers::fixture!("containerfile"); let (updates, complete_future) = builder.interpret(containerfile.as_bytes()).unwrap(); let (_, result) = future::join(updates.collect::<Vec<_>>(), complete_future).await; let container_folder = result.expect("Unable to enterpret containerfile"); assert!(container_folder.join("rootfs/etc/passwd").exists()); let file = fs::File::open(container_folder.join("config.json")) .expect("Failed to open OCI runtime config file"); let config: RuntimeConfig = serde_json::from_reader(file) .expect("Failed to parse OCI runtime config file"); let command = config.process.unwrap().args.unwrap().join(" "); assert_eq!(command, "nginx -g daemon off;"); } }
nder: UnboundedSender<EvaluationUpdate>, ) { match instruction { From(instruction) => { self.execute_from_instruction(instruction, sender).await?; } _ => { log::warn!( "Unhandled containerfile instruction {:?}", instruction ) } } }
function_block-function_prefixed
[ { "content": "#[fehler::throws]\n\npub fn teardown(storage: &Storage<impl StorageEngine>, key: impl AsRef<str>) {\n\n let cache: ContainerAddressStorage = storage\n\n .get(NETWORK_STATE_STORAGE_KEY, CONTAINER_ADDRESS_STORAGE_KEY)?\n\n .ok_or_else(|| anyhow::anyhow!(\"Failed to read network stat...
Rust
src/room.rs
neosam/sprite-game
5d261eb538824ebb133833a4f4fe4f162aa3445c
use rand::Rng; #[derive(Copy, Clone)] pub enum DestRoom { Relative(isize, isize, i32, i32,), Absolute(isize, isize, i32, i32,), } impl DestRoom { pub fn to_absolute_coordinates(&self, (x, y): (i32, i32)) -> (i32, i32) { match self { DestRoom::Relative(rel_x, rel_y, _, _) => (x + *rel_x as i32, y + *rel_y as i32), DestRoom::Absolute(abs_x, abs_y, _, _) => (*abs_x as i32, *abs_y as i32), } } pub fn spawn_point(&self) -> (i32, i32) { match self { DestRoom::Relative(_, _, x, y) => (*x, *y), DestRoom::Absolute(_, _, x, y) => (*x, *y), } } } #[derive(Copy, Clone)] pub enum RoomField { Nothing, Wall, Stone, Bush, Player, Exit(DestRoom), } #[derive(Clone)] pub struct Room { pub width: usize, pub height: usize, pub fields: Vec<RoomField>, } impl Room { pub fn new(width: usize, height: usize) -> Room { let fields = (0..(width * height)).map(|_| RoomField::Nothing).collect(); Room { width, height, fields, } } pub fn set_field(&mut self, x: usize, y: usize, field: RoomField) { if x < self.width && y < self.height { let index = x + y * self.width; self.fields[index] = field; } } pub fn get_field(&self, x: usize, y: usize) -> Option<RoomField> { if x < self.width && y < self.height { let index = x + y * self.width; Some(self.fields[index]) } else { None } } pub fn room_field_iterator(&self) -> RoomFieldIterator { RoomFieldIterator { x: 0, y: 0, room: self } } } #[derive(Default)] pub struct RoomGeneration { pub width: usize, pub height: usize, pub exit_north: bool, pub exit_south: bool, pub exit_east: bool, pub exit_west: bool, } impl RoomGeneration { pub fn generate_room(&self, rng: &mut impl Rng) -> Room { let mut room = Room::new(self.width, self.height); /* Draw borders */ let wall_borders = RoomField::Wall; for x in 0..self.width { room.set_field(x, 0, wall_borders); room.set_field(x, self.height - 1, wall_borders); } for y in 0..self.height { room.set_field(0, y, wall_borders); room.set_field(self.width - 1, y, wall_borders); } /* Open exits */ if self.exit_north { room.set_field(self.width / 2, self.height - 1, RoomField::Exit(DestRoom::Relative(0, -1, self.width as i32 / 2, 1))); } if self.exit_south { room.set_field(self.width / 2, 0, RoomField::Exit(DestRoom::Relative(0, 1, self.width as i32 / 2, self.height as i32 - 2))); } if self.exit_east { room.set_field(self.width - 1, self.height / 2, RoomField::Exit(DestRoom::Relative(1, 0, 1, self.height as i32 / 2))); } if self.exit_west { room.set_field(0, self.height / 2, RoomField::Exit(DestRoom::Relative(-1, 0, self.width as i32 - 2, self.height as i32 / 2))); } /* Draw 5-7 random stones */ for _ in 0..rng.gen_range(5, 8) { let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Stone); } /* Draw 5-7 bushes */ for _ in 0..rng.gen_range(5, 8) { let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Bush); } /* Add the player somewhere */ let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Player); room } } pub struct RoomFieldIterator<'a> { room: &'a Room, x: usize, y: usize, } impl<'a> Iterator for RoomFieldIterator<'a> { type Item = (usize, usize, RoomField); fn next(&mut self) -> Option<Self::Item> { let result = self.room.get_field(self.x, self.y).map(|field| (self.x, self.y, field)); self.x += 1; if self.x >= self.room.width { self.x = 0; self.y += 1; } if self.y >= self.room.height { return None; } result } }
use rand::Rng; #[derive(Copy, Clone)] pub enum DestRoom { Relative(isize, isize, i32, i32,), Absolute(isize, isize, i32, i32,), } impl DestRoom { pub fn to_absolute_coordinates(&self, (x, y): (i32, i32)) -> (i32, i32) { match self { DestRoom::Relative(rel_x, rel_y, _, _) => (x + *rel_x as i32, y + *rel_y as i32), DestRoom::Absolute(abs_x, abs_y, _, _) => (*abs_x as i32, *abs_y as i32), } } pub fn spawn_point(&self) -> (i32, i32) { match self { DestRoom::Relative(_, _, x, y) => (*x, *y), DestRoom::Absolute(_, _, x, y) => (*x, *y), } } } #[derive(Copy, Clone)] pub enum RoomField { Nothing, Wall, Stone, Bush, Player, Exit(DestRoom), } #[derive(Clone)] pub struct Room { pub width: usize, pub height: usize, pub fields: Vec<RoomField>, } impl Room { pub fn new(width: usize, height: usize) -> Room { let fields = (0..(width * height)).map(|_| RoomField::Nothing).collect(); Room { width, height, fields, } } pub fn set_field(&mut self, x: usize, y: usize, field: RoomField) { if x < self.width && y < self.height { let index = x + y * self.width; self.fields[index] = field; } } pub fn get_field(&self, x: usize, y: usize) -> Option<RoomField> { if x < self.width && y < self.height { let index = x + y * self.width; Some(self.fields[index]) } else { None } } pub fn room_field_iterator(&self) -> RoomFieldIterator { RoomFieldIterator { x: 0, y: 0, room: self } } } #[derive(Default)] pub struct RoomGeneration { pub width: usize, pub height: usize, pub exit_north: bool, pub exit_south: bool, pub exit_east: bool, pub exit_west: bool, } impl RoomGeneration { pub fn generate_room(&self, rng: &mut impl Rng) -> Room { let mut room = Room::new(self.width, self.height); /* Draw borders */ let wall_borders = RoomField::Wall; for x in 0..self.width { room.set_field(x, 0, wall_borders); room.set_field(x, self.height - 1, wall_borders); } for y in 0..self.height { room.set_field(0, y, wall_borders); room.set_field(self.width - 1, y, wall_borders); } /* Open exits */ if self.exit_north { room.set_field(self.width / 2, self.height - 1, RoomField::Exit(DestRoom::Relative(0, -1, self.width as i32 / 2, 1))); } if self.exit_south { room.set_field(self.width / 2, 0, RoomField::Exit(DestRoom::Relative(0, 1, self.width as i32 / 2, self.height as i32 - 2))); }
if self.exit_west { room.set_field(0, self.height / 2, RoomField::Exit(DestRoom::Relative(-1, 0, self.width as i32 - 2, self.height as i32 / 2))); } /* Draw 5-7 random stones */ for _ in 0..rng.gen_range(5, 8) { let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Stone); } /* Draw 5-7 bushes */ for _ in 0..rng.gen_range(5, 8) { let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Bush); } /* Add the player somewhere */ let x = rng.gen_range(2, self.width - 3); let y = rng.gen_range(2, self.height - 3); room.set_field(x, y, RoomField::Player); room } } pub struct RoomFieldIterator<'a> { room: &'a Room, x: usize, y: usize, } impl<'a> Iterator for RoomFieldIterator<'a> { type Item = (usize, usize, RoomField); fn next(&mut self) -> Option<Self::Item> { let result = self.room.get_field(self.x, self.y).map(|field| (self.x, self.y, field)); self.x += 1; if self.x >= self.room.width { self.x = 0; self.y += 1; } if self.y >= self.room.height { return None; } result } }
if self.exit_east { room.set_field(self.width - 1, self.height / 2, RoomField::Exit(DestRoom::Relative(1, 0, 1, self.height as i32 / 2))); }
if_condition
[ { "content": "fn generate_corridor(map: &mut Map<RoomGeneration>, rng: &mut impl Rng, width: usize, height: usize, corridor_length: u32, mut coordinate: (i32, i32)) -> Vec<(i32,i32)> {\n\n let mut coordinate_stack = Vec::new();\n\n for _ in 0..corridor_length {\n\n let choice = {\n\n let...
Rust
part_8/src/render.rs
CroPo/roguelike-tutorial-2018
6ceceb445087ef42ed988574ef5ac04e341d9889
use tcod::console::{Console, Root, blit, Offscreen}; use map_objects::map::GameMap; use tcod::Map; use ecs::Ecs; use ecs::component::Position; use ecs::component::Render; use ecs::id::EntityId; use tcod::Color; use tcod::colors; use tcod::BackgroundFlag; use tcod::TextAlignment; use ecs::component::Actor; use message::MessageLog; use std::rc::Rc; use textwrap::wrap; use ecs::component::Name; use ecs::component::Inventory; use game_states::GameState; #[derive(PartialEq, Eq, PartialOrd, Ord)] pub enum RenderOrder { Corpse = 1, Item = 2, Actor = 3, } pub fn render_all(ecs: &Ecs, map: &mut GameMap, fov_map: &Map, game_state: &GameState, console: &mut Offscreen, panel: &mut Offscreen, root_console: &mut Root, bar_width: i32, panel_y: i32, log_panel: &MessagePanel, mouse_pos: (i32, i32)) { map.draw(console, fov_map); let component_ids = ecs.get_all_ids::<Render>(); let mut ids_filtered: Vec<&EntityId> = component_ids.iter().filter(|id| { if let Some(p) = ecs.get_component::<Position>(**id) { fov_map.is_in_fov(p.position.0, p.position.1) } else { false } }).collect(); ids_filtered.sort_by(|id_a, id_b| { let comp_a = ecs.get_component::<Render>(**id_a).unwrap(); let comp_b = ecs.get_component::<Render>(**id_b).unwrap(); comp_a.order.cmp(&comp_b.order) }); ids_filtered.iter().for_each(|id| { let c = ecs.get_component::<Render>(**id).unwrap(); c.draw(ecs, console) }); blit(console, (0, 0), (console.width(), console.height()), root_console, (0, 0), 1.0, 1.0); panel.set_default_foreground(colors::LIGHT_GREY); panel.set_default_background(colors::BLACK); panel.clear(); panel.print_ex(1, 0, BackgroundFlag::None, TextAlignment::Left, get_names_under_mouse(ecs, fov_map, mouse_pos)); if let Some(p) = ecs.get_component::<Actor>(ecs.player_entity_id) { panel.set_default_background(colors::BLACK); render_bar(panel, (1, 1), bar_width, "HP", p.hp, p.max_hp, colors::RED, colors::DARK_RED); } log_panel.render(panel); blit(panel, (0, 0), (panel.width(), panel.height()), root_console, (0, panel_y), 1.0, 1.0); if *game_state == GameState::ShowInventory || *game_state == GameState::ShowInventoryDrop { inventory_menu(root_console, ecs, "Inventory", 50, console.width(), console.height()); } root_console.flush() } pub fn clear_all(ecs: &Ecs, console: &mut Console) { ecs.get_all::<Position>().iter().for_each(|(e, _)| { let render_component = ecs.get_component::<Render>(*e); match render_component { Some(r) => { r.clear(ecs, console) } None => () } }); } pub fn render_bar(panel: &mut Offscreen, pos: (i32, i32), width: i32, name: &str, value: i32, max: i32, bar_color: Color, back_color: Color) { let filled_width = (value as f64 / max as f64 * width as f64).round() as i32; panel.set_default_background(back_color); panel.rect(pos.0, pos.1, width, 1, false, BackgroundFlag::Screen); if filled_width > 0 { panel.set_default_background(bar_color); panel.rect(pos.0, pos.1, filled_width, 1, false, BackgroundFlag::Screen) } panel.set_default_foreground(colors::WHITE); panel.print_ex(pos.0 + width / 2, pos.1, BackgroundFlag::None, TextAlignment::Center, format!("{}: {}/{}", name, value, max)); } fn get_names_under_mouse(ecs: &Ecs, fov_map: &Map, mouse_pos: (i32, i32)) -> String { let mut names = vec![]; ecs.get_all::<Position>().iter().filter(|(_, p)| { p.position.0 == mouse_pos.0 && p.position.1 == mouse_pos.1 && fov_map.is_in_fov(mouse_pos.0, mouse_pos.1) }).for_each(|(id, _)| { if let Some(n) = ecs.get_component::<Name>(*id) { names.push(n.name.clone()); } }); names.join(",") } pub fn selection_menu(console: &mut Root, title: &str, options: Vec<String>, width: i32, screen_width: i32, screen_height: i32) { let header_height = console.get_height_rect(0, 0, width, screen_height, title); let height = header_height + options.len() as i32; let mut menu_panel = Offscreen::new(width, height); menu_panel.set_default_foreground(colors::WHITE); menu_panel.print_rect_ex(0, 0, width, height, BackgroundFlag::None, TextAlignment::Left, title); let mut y = header_height; let mut letter_index = 'a' as u8; for option in options { let text = format!("({}) {}", letter_index as char, option); menu_panel.print_ex(0, y, BackgroundFlag::None, TextAlignment::Left, text); y+=1; letter_index+=1; } let x = screen_width / 2 - width / 2; let y = screen_height / 2 - height / 2; blit(&menu_panel, (0, 0), (width, height), console, (x, y), 1.0, 1.0); } pub fn inventory_menu(console: &mut Root, ecs: &Ecs, title: &str, width: i32, screen_width: i32, screen_height: i32) { if let Some(inventory) = ecs.get_component::<Inventory>(ecs.player_entity_id) { let items = if inventory.items.len() == 0 { vec!["Inventory is empty".to_string()] } else { inventory.items.iter().filter(|item_id|{ ecs.has_component::<Name>(**item_id) }).map(|item_id| { ecs.get_component::<Name>(*item_id).unwrap().name.clone() }).collect() }; selection_menu(console, title, items, width, screen_width, screen_height); } } pub struct MessagePanel { pos: (i32, i32), dimensions: (i32, i32), log: Rc<MessageLog>, } impl MessagePanel { pub fn new(pos: (i32, i32), dimensions: (i32, i32), log: Rc<MessageLog>) -> MessagePanel { MessagePanel { pos, dimensions, log, } } pub fn render(&self, panel: &mut Offscreen) { let mut total_lines = 0; 'l: for m in self.log.messages().iter().rev() { let lines = wrap(&m.text, self.dimensions.0 as usize); panel.set_default_foreground(m.color); for l in lines { panel.print_ex(self.pos.0, self.pos.1 + total_lines, BackgroundFlag::None, TextAlignment::Left, l.to_string()); total_lines += 1; if self.pos.1 + total_lines > self.dimensions.1 { break 'l; } } }; } }
use tcod::console::{Console, Root, blit, Offscreen}; use map_objects::map::GameMap; use tcod::Map; use ecs::Ecs; use ecs::component::Position; use ecs::component::Render; use ecs::id::EntityId; use tcod::Color; use tcod::colors; use tcod::BackgroundFlag; use tcod::TextAlignment; use ecs::component::Actor; use message::MessageLog; use std::rc::Rc; use textwrap::wrap; use ecs::component::Name; use ecs::component::Inventory; use game_states::GameState; #[derive(PartialEq, Eq, PartialOrd, Ord)] pub enum RenderOrder { Corpse = 1, Item = 2, Actor = 3, } pub fn render_all(ecs: &Ecs, map: &mut GameMap, fov_map: &Map, game_state: &GameState, console: &mut Offscreen, panel: &mut Offscreen, root_console: &mut Root, bar_width: i32, panel_y: i32, log_panel: &MessagePanel, mouse_pos: (i32, i32)) { map.draw(console, fov_map); let component_ids = ecs.get_all_ids::<Render>(); let mut ids_filtered: Vec<&EntityId> = component_ids.iter().filter(|id| { if let Some(p) = ecs.get_component::<Position>(**id) { fov_map.is_in_fov(p.position.0, p.position.1) } else { false } }).collect(); ids_filtered.sort_by(|id_a, id_b| { let comp_a = ecs.get_component::<Render>(**id_a).unwrap(); let comp_b = ecs.get_component::<Render>(**id_b).unwrap(); comp_a.order.cmp(&comp_b.order) }); ids_filtered.iter().for_each(|id| { let c = ecs.get_component::<Render>(**id).unwrap(); c.draw(ecs, console) }); blit(console, (0, 0), (console.width(), console.height()), root_console, (0, 0), 1.0, 1.0); panel.set_default_foreground(colors::LIGHT_GREY); panel.set_default_background(colors::BLACK); panel.clear(); panel.print_ex(1, 0, BackgroundFlag::None, TextAlignment::Left, get_names_under_mouse(ecs, fov_map, mouse_pos)); if let Some(p) = ecs.get_component::<Actor>(ecs.player_entity_id) { panel.set_default_background(colors::BLACK); render_bar(panel, (1, 1), bar_width, "HP", p.hp, p.max_hp, colors::RED, colors::DARK_RED); } log_panel.render(panel); blit(panel, (0, 0), (panel.width(), panel.height()), root_console, (0, panel_y), 1.0, 1.0); if *game_state == GameState::ShowInventory || *game_state == GameState::ShowInventoryDrop { inventory_menu(root_console, ecs, "Inventory", 50, console.width(), console.height()); } root_console.flush() } pub fn clear_all(ecs: &Ecs, console: &mut Console) { ecs.get_all::<Position>().iter().for_each(|(e, _)| { let render_component = ecs.get_component::<Render>(*e); match render_component { Some(r) => { r.clear(ecs, console) } None => () } }); } pub fn render_bar(panel: &mut Offscreen, pos: (i32, i32), width: i32, name: &str, value: i32, max: i32, bar_color: Color, back_color: Color) { let filled_width = (value as f64 / max as f64 * width as f64).round() as i32; panel.set_default_background(back_color); panel.rect(pos.0, pos.1, width, 1, false, BackgroundFlag::Screen); if filled_width > 0 { panel.set_default_background(bar_color); panel.rect(pos.0, pos.1, filled_width, 1, false, BackgroundFlag::Screen) } panel.set_default_foreground(colors::WHITE); panel.print_ex(pos.0 + width / 2, pos.1, BackgroundFlag::None, TextAlignment::Center, format!("{}: {}/{}", name, value, max)); } fn get_names_under_mouse(ecs: &Ecs, fov_map: &Map, mouse_pos: (i32, i32)) -> String { let mut names = vec![]; ecs.get_all::<Position>().iter().filter(|(_, p)| { p.position.0 == mouse_pos.0 && p.position.1 == mouse_pos.1 && fov_map.is_in_fov(mouse_pos.0, mouse_pos.1) }).for_each(|(id, _)| { if let Some(n) = ecs.get_component::<Name>(*id) { names.push(n.name.clone()); } }); names.join(",") } pub fn selection_menu(console: &mut Root, title: &str, options: Vec<String>, width: i32, screen_width: i32, screen_height: i32) { let header_height = console.get_height_rect(0, 0, width, screen_height, title); let height = header_height + options.len() as i32; let mut menu_panel = Offscreen::new(width, height); menu_panel.set_default_foreground(colors::WHITE); menu_panel.print_rect_ex(0, 0, width, height, BackgroundFlag::None, TextAlignment::Left, title); let mut y = header_height; let mut letter_index = 'a' as u8; for option in options { let text = forma
pub fn inventory_menu(console: &mut Root, ecs: &Ecs, title: &str, width: i32, screen_width: i32, screen_height: i32) { if let Some(inventory) = ecs.get_component::<Inventory>(ecs.player_entity_id) { let items = if inventory.items.len() == 0 { vec!["Inventory is empty".to_string()] } else { inventory.items.iter().filter(|item_id|{ ecs.has_component::<Name>(**item_id) }).map(|item_id| { ecs.get_component::<Name>(*item_id).unwrap().name.clone() }).collect() }; selection_menu(console, title, items, width, screen_width, screen_height); } } pub struct MessagePanel { pos: (i32, i32), dimensions: (i32, i32), log: Rc<MessageLog>, } impl MessagePanel { pub fn new(pos: (i32, i32), dimensions: (i32, i32), log: Rc<MessageLog>) -> MessagePanel { MessagePanel { pos, dimensions, log, } } pub fn render(&self, panel: &mut Offscreen) { let mut total_lines = 0; 'l: for m in self.log.messages().iter().rev() { let lines = wrap(&m.text, self.dimensions.0 as usize); panel.set_default_foreground(m.color); for l in lines { panel.print_ex(self.pos.0, self.pos.1 + total_lines, BackgroundFlag::None, TextAlignment::Left, l.to_string()); total_lines += 1; if self.pos.1 + total_lines > self.dimensions.1 { break 'l; } } }; } }
t!("({}) {}", letter_index as char, option); menu_panel.print_ex(0, y, BackgroundFlag::None, TextAlignment::Left, text); y+=1; letter_index+=1; } let x = screen_width / 2 - width / 2; let y = screen_height / 2 - height / 2; blit(&menu_panel, (0, 0), (width, height), console, (x, y), 1.0, 1.0); }
function_block-function_prefixed
[ { "content": "/// Display a selection menu of various options\n\npub fn selection_menu(console: &mut Root, title: &str, options: Vec<String>, width: i32, screen_width: i32, screen_height: i32) {\n\n let header_height = console.get_height_rect(0, 0, width, screen_height, title);\n\n let height = header_hei...
Rust
clinkv2/src/kzg10/prover.rs
sunhuachuang/ckb-zkp
4031a458a301a87cfdea9f6c662cc8a837d6ae51
use ark_ec::PairingEngine; use ark_ff::{Field, One, ToBytes, UniformRand, Zero}; use ark_poly::polynomial::univariate::DensePolynomial; use ark_poly::{EvaluationDomain, GeneralEvaluationDomain, Polynomial, UVPolynomial}; use ark_std::{cfg_iter, cfg_iter_mut}; use merlin::Transcript; use rand::Rng; #[cfg(feature = "parallel")] use rayon::prelude::*; use crate::{ kzg10::{Proof, ProveAssignment, ProveKey, KZG10}, r1cs::{Index, SynthesisError}, }; pub fn create_random_proof<E: PairingEngine, R: Rng>( circuit: &ProveAssignment<E>, kzg10_ck: &ProveKey<'_, E>, rng: &mut R, ) -> Result<Proof<E>, SynthesisError> { let m_io = circuit.input_assignment.len(); let m_mid = circuit.aux_assignment.len(); let n = circuit.input_assignment[0].len(); let mut transcript = Transcript::new(b"CLINKv2"); let domain: GeneralEvaluationDomain<E::Fr> = EvaluationDomain::<E::Fr>::new(n).ok_or(SynthesisError::PolynomialDegreeTooLarge)?; let domain_size = domain.size(); let mut r_q_polys = vec![]; let mut r_mid_comms = vec![]; let mut r_mid_q_values = vec![]; let mut r_mid_q_rands = vec![]; let zero = E::Fr::zero(); let one = E::Fr::one(); let hiding_bound = Some(2); for j in 0..m_io { let rj_coeffs = domain.ifft(&circuit.input_assignment[j]); let rj_poly = DensePolynomial::from_coefficients_vec(rj_coeffs); r_q_polys.push(rj_poly); } for j in 0..m_mid { let rj_coeffs = domain.ifft(&circuit.aux_assignment[j]); let mut rj_poly = DensePolynomial::from_coefficients_vec(rj_coeffs); let rho = zero; let rho_poly = DensePolynomial::from_coefficients_vec(vec![rho; 1]); let vanishing_poly = domain.vanishing_polynomial(); rj_poly += &(&rho_poly * &vanishing_poly.into()); let (rj_comm, rj_rand) = KZG10::<E>::commit(&kzg10_ck, &rj_poly, hiding_bound, Some(rng))?; r_q_polys.push(rj_poly); r_mid_comms.push(rj_comm); r_mid_q_rands.push(rj_rand); } let mut r_mid_comms_bytes = vec![]; r_mid_comms.write(&mut r_mid_comms_bytes)?; transcript.append_message(b"witness polynomial commitments", &r_mid_comms_bytes); let mut c = [0u8; 31]; transcript.challenge_bytes(b"batching challenge", &mut c); let eta = E::Fr::from_random_bytes(&c).unwrap(); let m_abc = circuit.at.len(); let mut sum_coset_ab = vec![zero; domain_size]; let mut sum_c = vec![zero; domain_size]; let mut eta_i = one; for i in 0..m_abc { let mut ai_coeffs = vec![zero; domain_size]; for (coeff, index) in (&circuit.at[i]).into_iter() { let id = match index { Index::Input(j) => *j, Index::Aux(j) => m_io + *j, }; for k in 0..r_q_polys[id].coeffs.len() { ai_coeffs[k] += &(r_q_polys[id].coeffs[k] * coeff); } } let mut ai = DensePolynomial::from_coefficients_vec(ai_coeffs); let mut bi_coeffs = vec![zero; domain_size]; for (coeff, index) in (&circuit.bt[i]).into_iter() { let id = match index { Index::Input(j) => *j, Index::Aux(j) => m_io + *j, }; for k in 0..r_q_polys[id].coeffs.len() { bi_coeffs[k] += &(r_q_polys[id].coeffs[k] * coeff); } } let mut bi = DensePolynomial::from_coefficients_vec(bi_coeffs); domain.coset_fft_in_place(&mut ai.coeffs); domain.coset_fft_in_place(&mut bi.coeffs); let coset_ab_values = domain.mul_polynomials_in_evaluation_domain(&ai, &bi); drop(ai); drop(bi); cfg_iter!(coset_ab_values) .zip(&mut sum_coset_ab) .for_each(|(coset_abij, sum_coset_ab_j)| *sum_coset_ab_j += &(eta_i * (*coset_abij))); let mut ci_values = vec![zero; domain_size]; for (coeff, index) in (&circuit.ct[i]).into_iter() { match index { Index::Input(j) => { cfg_iter_mut!(&mut ci_values) .zip(&circuit.input_assignment[*j]) .for_each(|(cij, rij)| *cij += &(*rij * coeff)); } Index::Aux(j) => { cfg_iter_mut!(&mut ci_values) .zip(&circuit.aux_assignment[*j]) .for_each(|(cij, rij)| *cij += &(*rij * coeff)); } }; } cfg_iter!(ci_values) .zip(&mut sum_c) .for_each(|(cij, sum_c_j)| *sum_c_j += &(eta_i * (*cij))); eta_i = eta_i * &eta; } domain.ifft_in_place(&mut sum_c); domain.coset_fft_in_place(&mut sum_c); cfg_iter_mut!(sum_coset_ab) .zip(sum_c) .for_each(|(sum_coset_ab_j, sum_coset_c_j)| *sum_coset_ab_j -= &sum_coset_c_j); domain.divide_by_vanishing_poly_on_coset_in_place(&mut sum_coset_ab); domain.coset_ifft_in_place(&mut sum_coset_ab); let q_poly = DensePolynomial::from_coefficients_vec(sum_coset_ab); let (q_comm, q_rand) = KZG10::<E>::commit(&kzg10_ck, &q_poly, hiding_bound, Some(rng))?; let mut q_comm_bytes = vec![]; q_comm.write(&mut q_comm_bytes)?; transcript.append_message(b"quotient polynomial commitments", &q_comm_bytes); let mut c = [0u8; 31]; transcript.challenge_bytes(b"random point", &mut c); let zeta = E::Fr::from_random_bytes(&c).unwrap(); r_q_polys.push(q_poly); r_mid_q_rands.push(q_rand); for j in 0..(m_mid + 1) { let value = r_q_polys[j + m_io].evaluate(&zeta); r_mid_q_values.push(value); } let opening_challenge = E::Fr::rand(rng); let r_mid_q_proof = KZG10::<E>::batch_open( &kzg10_ck, &r_q_polys[m_io..], zeta, opening_challenge, &r_mid_q_rands, )?; let proof = Proof { r_mid_comms, q_comm, r_mid_q_values, r_mid_q_proof, opening_challenge, }; Ok(proof) }
use ark_ec::PairingEngine; use ark_ff::{Field, One, ToBytes, UniformRand, Zero}; use ark_poly::polynomial::univariate::DensePolynomial; use ark_poly::{EvaluationDomain, GeneralEvaluationDomain, Polynomial, UVPolynomial}; use ark_std::{cfg_iter, cfg_iter_mut}; use merlin::Transcript; use rand::Rng; #[cfg(feature = "parallel")] use rayon::prelude::*; use crate::{ kzg10::{Proof, ProveAssignment, ProveKey, KZG10}, r1cs::{Index, SynthesisError}, };
pub fn create_random_proof<E: PairingEngine, R: Rng>( circuit: &ProveAssignment<E>, kzg10_ck: &ProveKey<'_, E>, rng: &mut R, ) -> Result<Proof<E>, SynthesisError> { let m_io = circuit.input_assignment.len(); let m_mid = circuit.aux_assignment.len(); let n = circuit.input_assignment[0].len(); let mut transcript = Transcript::new(b"CLINKv2"); let domain: GeneralEvaluationDomain<E::Fr> = EvaluationDomain::<E::Fr>::new(n).ok_or(SynthesisError::PolynomialDegreeTooLarge)?; let domain_size = domain.size(); let mut r_q_polys = vec![]; let mut r_mid_comms = vec![]; let mut r_mid_q_values = vec![]; let mut r_mid_q_rands = vec![]; let zero = E::Fr::zero(); let one = E::Fr::one(); let hiding_bound = Some(2); for j in 0..m_io { let rj_coeffs = domain.ifft(&circuit.input_assignment[j]); let rj_poly = DensePolynomial::from_coefficients_vec(rj_coeffs); r_q_polys.push(rj_poly); } for j in 0..m_mid { let rj_coeffs = domain.ifft(&circuit.aux_assignment[j]); let mut rj_poly = DensePolynomial::from_coefficients_vec(rj_coeffs); let rho = zero; let rho_poly = DensePolynomial::from_coefficients_vec(vec![rho; 1]); let vanishing_poly = domain.vanishing_polynomial(); rj_poly += &(&rho_poly * &vanishing_poly.into()); let (rj_comm, rj_rand) = KZG10::<E>::commit(&kzg10_ck, &rj_poly, hiding_bound, Some(rng))?; r_q_polys.push(rj_poly); r_mid_comms.push(rj_comm); r_mid_q_rands.push(rj_rand); } let mut r_mid_comms_bytes = vec![]; r_mid_comms.write(&mut r_mid_comms_bytes)?; transcript.append_message(b"witness polynomial commitments", &r_mid_comms_bytes); let mut c = [0u8; 31]; transcript.challenge_bytes(b"batching challenge", &mut c); let eta = E::Fr::from_random_bytes(&c).unwrap(); let m_abc = circuit.at.len(); let mut sum_coset_ab = vec![zero; domain_size]; let mut sum_c = vec![zero; domain_size]; let mut eta_i = one; for i in 0..m_abc { let mut ai_coeffs = vec![zero; domain_size]; for (coeff, index) in (&circuit.at[i]).into_iter() { let id = match index { Index::Input(j) => *j, Index::Aux(j) => m_io + *j, }; for k in 0..r_q_polys[id].coeffs.len() { ai_coeffs[k] += &(r_q_polys[id].coeffs[k] * coeff); } } let mut ai = DensePolynomial::from_coefficients_vec(ai_coeffs); let mut bi_coeffs = vec![zero; domain_size]; for (coeff, index) in (&circuit.bt[i]).into_iter() { let id = match index { Index::Input(j) => *j, Index::Aux(j) => m_io + *j, }; for k in 0..r_q_polys[id].coeffs.len() { bi_coeffs[k] += &(r_q_polys[id].coeffs[k] * coeff); } } let mut bi = DensePolynomial::from_coefficients_vec(bi_coeffs); domain.coset_fft_in_place(&mut ai.coeffs); domain.coset_fft_in_place(&mut bi.coeffs); let coset_ab_values = domain.mul_polynomials_in_evaluation_domain(&ai, &bi); drop(ai); drop(bi); cfg_iter!(coset_ab_values) .zip(&mut sum_coset_ab) .for_each(|(coset_abij, sum_coset_ab_j)| *sum_coset_ab_j += &(eta_i * (*coset_abij))); let mut ci_values = vec![zero; domain_size]; for (coeff, index) in (&circuit.ct[i]).into_iter() { match index { Index::Input(j) => { cfg_iter_mut!(&mut ci_values) .zip(&circuit.input_assignment[*j]) .for_each(|(cij, rij)| *cij += &(*rij * coeff)); } Index::Aux(j) => { cfg_iter_mut!(&mut ci_values) .zip(&circuit.aux_assignment[*j]) .for_each(|(cij, rij)| *cij += &(*rij * coeff)); } }; } cfg_iter!(ci_values) .zip(&mut sum_c) .for_each(|(cij, sum_c_j)| *sum_c_j += &(eta_i * (*cij))); eta_i = eta_i * &eta; } domain.ifft_in_place(&mut sum_c); domain.coset_fft_in_place(&mut sum_c); cfg_iter_mut!(sum_coset_ab) .zip(sum_c) .for_each(|(sum_coset_ab_j, sum_coset_c_j)| *sum_coset_ab_j -= &sum_coset_c_j); domain.divide_by_vanishing_poly_on_coset_in_place(&mut sum_coset_ab); domain.coset_ifft_in_place(&mut sum_coset_ab); let q_poly = DensePolynomial::from_coefficients_vec(sum_coset_ab); let (q_comm, q_rand) = KZG10::<E>::commit(&kzg10_ck, &q_poly, hiding_bound, Some(rng))?; let mut q_comm_bytes = vec![]; q_comm.write(&mut q_comm_bytes)?; transcript.append_message(b"quotient polynomial commitments", &q_comm_bytes); let mut c = [0u8; 31]; transcript.challenge_bytes(b"random point", &mut c); let zeta = E::Fr::from_random_bytes(&c).unwrap(); r_q_polys.push(q_poly); r_mid_q_rands.push(q_rand); for j in 0..(m_mid + 1) { let value = r_q_polys[j + m_io].evaluate(&zeta); r_mid_q_values.push(value); } let opening_challenge = E::Fr::rand(rng); let r_mid_q_proof = KZG10::<E>::batch_open( &kzg10_ck, &r_q_polys[m_io..], zeta, opening_challenge, &r_mid_q_rands, )?; let proof = Proof { r_mid_comms, q_comm, r_mid_q_values, r_mid_q_proof, opening_challenge, }; Ok(proof) }
function_block-full_function
[ { "content": "type Kzg10Proof<E> = kzg10::Proof<E>;\n", "file_path": "clinkv2/src/kzg10/mod.rs", "rank": 0, "score": 123476.63471316447 }, { "content": "fn skip_leading_zeros_and_convert_to_bigints<F: PrimeField>(\n\n p: &DensePolynomial<F>,\n\n) -> (usize, Vec<F::BigInt>) {\n\n let mu...
Rust
examples/simple/main.rs
Vollkornaffe/VRV
8e71b9c728dbe91d41d563e32bcbf432952fe828
use std::{ collections::HashSet, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Instant, }; use ash::vk::{DynamicState, Extent2D}; use cgmath::{perspective, Deg, EuclideanSpace, Matrix4, Point3, SquareMatrix, Vector3}; use openxr::{EventDataBuffer, SessionState, ViewConfigurationType}; use per_frame::PerFrameWindow; use simplelog::{Config, SimpleLogger}; use vk_shader_macros::include_glsl; use vrv::{ wrap_vulkan::{create_pipeline, create_pipeline_layout, pipeline::create_shader_module}, State, }; use winit::{ event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use crate::{ camera::{fov_to_projection, pose_to_matrix_inverse, KeyMap, SphereCoords}, per_frame::{PerFrameHMD, UniformMatricesHMD, UniformMatricesWindow}, }; mod camera; mod per_frame; fn main() { let _ = SimpleLogger::init(log::LevelFilter::Warn, Config::default()); let event_loop = EventLoop::new(); let window = WindowBuilder::new().build(&event_loop).unwrap(); let mut state = State::new(&window).unwrap(); let (hmd_per_frame_buffers, hmd_descriptor_related) = PerFrameHMD::new_vec(&state.vulkan, state.get_image_count_hmd()).unwrap(); let (window_per_frame_buffers, window_descriptor_related) = PerFrameWindow::new_vec(&state.vulkan, state.get_image_count_window()).unwrap(); const HMD_VERT: &[u32] = include_glsl!("shaders/example_hmd.vert"); const HMD_FRAG: &[u32] = include_glsl!("shaders/example_hmd.frag"); const WINDOW_VERT: &[u32] = include_glsl!("shaders/example_window.vert"); const WINDOW_FRAG: &[u32] = include_glsl!("shaders/example_window.frag"); let hmd_module_vert = create_shader_module(&state.vulkan, HMD_VERT, "HMDShaderVert".to_string()).unwrap(); let hmd_module_frag = create_shader_module(&state.vulkan, HMD_FRAG, "HMDShaderFrag".to_string()).unwrap(); let window_module_vert = create_shader_module(&state.vulkan, WINDOW_VERT, "WindowShaderVert".to_string()).unwrap(); let window_module_frag = create_shader_module(&state.vulkan, WINDOW_FRAG, "WindowShaderFrag".to_string()).unwrap(); let hmd_pipeline_layout = create_pipeline_layout( &state.vulkan, hmd_descriptor_related.layout, "HMDPipelineLayout".to_string(), ) .unwrap(); let hmd_pipeline = create_pipeline( &state.vulkan, state.hmd_render_pass, hmd_pipeline_layout, hmd_module_vert, hmd_module_frag, state.openxr.get_resolution().unwrap(), &[], "HMDPipeline".to_string(), ) .unwrap(); let window_pipeline_layout = create_pipeline_layout( &state.vulkan, window_descriptor_related.layout, "WindowPipelineLayout".to_string(), ) .unwrap(); let window_pipeline = create_pipeline( &state.vulkan, state.window_render_pass, window_pipeline_layout, window_module_vert, window_module_frag, Extent2D { width: window.inner_size().width, height: window.inner_size().height, }, &[DynamicState::VIEWPORT, DynamicState::SCISSOR], "WindowPipeline".to_string(), ) .unwrap(); unsafe { state .vulkan .device .destroy_shader_module(hmd_module_vert, None); state .vulkan .device .destroy_shader_module(hmd_module_frag, None); state .vulkan .device .destroy_shader_module(window_module_vert, None); state .vulkan .device .destroy_shader_module(window_module_frag, None); } let mut spherical_coords = SphereCoords::new(); let mut pressed_keys: HashSet<VirtualKeyCode> = HashSet::new(); let ctrlc = Arc::new(AtomicBool::new(false)); { let r = ctrlc.clone(); ctrlc::set_handler(move || { r.store(true, Ordering::Relaxed); }) .expect("setting Ctrl-C handler"); } let mut xr_event_storage = EventDataBuffer::new(); let mut xr_session_running = false; let mut xr_focused = false; event_loop.run(move |event, _, control_flow| match event { Event::MainEventsCleared => { if ctrlc.load(Ordering::Relaxed) { log::warn!("Exiting through Ctrl-C"); *control_flow = ControlFlow::Exit; match state.session.request_exit() { Ok(()) => {} Err(openxr::sys::Result::ERROR_SESSION_NOT_RUNNING) => {} Err(e) => panic!("{}", e), } return; } while let Some(event) = state .openxr .instance .poll_event(&mut xr_event_storage) .unwrap() { use openxr::Event::*; match event { SessionStateChanged(e) => { log::warn!("entered state {:?}", e.state()); xr_focused = false; match e.state() { SessionState::READY => { state .session .begin(ViewConfigurationType::PRIMARY_STEREO) .unwrap(); xr_session_running = true; } SessionState::STOPPING => { state.session.end().unwrap(); xr_session_running = false; } SessionState::FOCUSED => { xr_focused = true; } SessionState::EXITING | SessionState::LOSS_PENDING => { *control_flow = ControlFlow::Exit; return; } _ => {} } } InstanceLossPending(_) => { *control_flow = ControlFlow::Exit; return; } EventsLost(e) => { log::error!("lost {} events", e.lost_event_count()); } _ => {} } } let hmd_pre_render_info = state.pre_render_hmd().unwrap(); if hmd_pre_render_info.image_index.is_some() { let image_index = hmd_pre_render_info.image_index.unwrap(); let hmd_current_frame = &hmd_per_frame_buffers[image_index as usize]; state .record_hmd( hmd_pre_render_info, hmd_pipeline_layout, hmd_pipeline, &hmd_current_frame.mesh_buffers, hmd_current_frame.descriptor_set, ) .unwrap(); let views = state .get_views(hmd_pre_render_info.frame_state.predicted_display_time) .unwrap(); hmd_current_frame.matrix_buffer.write(&[UniformMatricesHMD { model: Matrix4::identity(), view_left: pose_to_matrix_inverse(views[0].pose), view_right: pose_to_matrix_inverse(views[1].pose), proj_left: fov_to_projection(views[0].fov), proj_right: fov_to_projection(views[1].fov), }]); state.submit_hmd(hmd_pre_render_info, &views).unwrap(); } let window_pre_render_info = state.pre_render_window().unwrap(); let window_current_frame = &window_per_frame_buffers[window_pre_render_info.image_index as usize]; spherical_coords.update( &pressed_keys .iter() .map(|&k| k.into()) .collect::<Vec<KeyMap>>(), ); window_current_frame .matrix_buffer .write(&[UniformMatricesWindow { model: Matrix4::identity(), view: Matrix4::look_at_rh( spherical_coords.to_coords(), Point3::origin(), Vector3::unit_y(), ), proj: { let mut tmp = perspective( Deg(45.0), window.inner_size().width as f32 / window.inner_size().height as f32, 0.1, 100.0, ); tmp[1][1] *= -1.0; tmp }, }]); state .render_window( window_pre_render_info, window_pipeline_layout, window_pipeline, &window_current_frame.mesh_buffers, window_current_frame.descriptor_set, ) .unwrap(); window.request_redraw(); } Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { match event { WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(new_inner_size) => { log::info!("Resizing to {:?}", new_inner_size); state.resize(&window).unwrap(); } WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size, } => { log::info!("Changing scale to {}", scale_factor); log::info!("Resizing to {:?}", new_inner_size); state.resize(&window).unwrap(); } WindowEvent::KeyboardInput { input: KeyboardInput { state, virtual_keycode: Some(code), .. }, .. } => { _ = match state { ElementState::Pressed => pressed_keys.insert(*code), ElementState::Released => pressed_keys.remove(code), } } _ => {} } } _ => {} }) }
use std::{ collections::HashSet, sync::{ atomic::{AtomicBool, Ordering}, Arc, }, time::Instant, }; use ash::vk::{DynamicState, Extent2D}; use cgmath::{perspective, Deg, EuclideanSpace, Matrix4, Point3, SquareMatrix, Vector3}; use openxr::{EventDataBuffer, SessionState, ViewConfigurationType}; use per_frame::PerFrameWindow; use simplelog::{Config, SimpleLogger}; use vk_shader_macros::include_glsl; use vrv::{ wrap_vulkan::{create_pipeline, create_pipeline_layout, pipeline::create_shader_module}, State, }; use winit::{ event::{ElementState, Event, KeyboardInput, VirtualKeyCode, WindowEvent}, event_loop::{ControlFlow, EventLoop}, window::WindowBuilder, }; use crate::{ camera::{fov_to_projection, pose_to_matrix_inverse, KeyMap, SphereCoords}, per_frame::{PerFrameHMD, UniformMatricesHMD, UniformMatricesWindow}, }; mod camera; mod per_frame; fn main() { let _ = SimpleLogger::init(log::LevelFilter::Warn, Config::default()); let event_loop = EventLoop::new(); let window = WindowBuilder::new().build(&event_loop).unwrap(); let mut state = State::new(&window).unwrap(); let (hmd_per_frame_buffers, hmd_descriptor_related) = PerFrameHMD::new_vec(&state.vulkan, state.get_image_count_hmd()).unwrap(); let (window_per_frame_buffers, window_descriptor_related) = PerFrameWindow::new_vec(&state.vulkan, state.get_image_count_window()).unwrap(); const HMD_VERT: &[u32] = include_glsl!("shaders/example_hmd.vert"); const HMD_FRAG: &[u32] = include_glsl!("shaders/example_hmd.frag"); const WINDOW_VERT: &[u32] = include_glsl!("shaders/example_window.vert"); const WINDOW_FRAG: &[u32] = include_glsl!("shaders/example_window.frag"); let hmd_module_vert = create_shader_module(&state.vulkan, HMD_VERT, "HMDShaderVert".to_string()).unwrap(); let hmd_module_frag = create_shader_module(&state.vulkan, HMD_FRAG, "HMDShaderFrag".to_string()).unwrap(); let window_module_vert = create_shader_module(&state.vulkan, WINDOW_VERT, "WindowShaderVert".to_string()).unwrap(); let window_module_frag = create_shader_module(&state.vulkan, WINDOW_FRAG, "WindowShaderFrag".to_string()).unwrap(); let hmd_pipeline_layout = create_pipeline_layout( &state.vulkan, hmd_descriptor_related.layout, "HMDPipelineLayout".to_string(), ) .unwrap(); let hmd_pipeline = create_pipeline( &state.vulkan, state.hmd_render_pass, hmd_pipeline_layout, hmd_module_vert, hmd_module_frag, state.openxr.get_resolution().unwrap(), &[], "HMDPipeline".to_string(), ) .unwrap(); let window_pipeline_layout = create_pipeline_layout( &state.vulkan, window_descriptor_related.layout, "WindowPipelineLayout".to_string(), ) .unwrap(); let window_pipeline = create_pipeline( &state.vulkan, state.window_render_pass, window_pipeline_layout, window_module_vert, window_module_frag, Extent2D { width: window.inner_size().width, height: window.inner_size().height, }, &[DynamicState::VIEWPORT, DynamicState::SCISSOR], "WindowPipeline".to_string(), ) .unwrap(); unsafe { state .vulkan .device .destroy_shader_module(hmd_module_vert, None); state .vulkan .device .destroy_shader_module(hmd_module_frag, None); state .vulkan .device .destroy_shader_module(window_module_vert, None); state .vulkan .device .destroy_shader_module(window_module_frag, None); } let mut spherical_coords = SphereCoords::new(); let mut pressed_keys: HashSet<VirtualKeyCode> = HashSet::new(); let ctrlc = Arc::new(AtomicBool::new(false)); { let r = ctrlc.clone(); ctrlc::set_handler(move || { r.store(true, Ordering::Relaxed); }) .expect("setting Ctrl-C handler"); } let mut xr_event_storage = EventDataBuffer::new(); let mut xr_session_running = false; let mut xr_focused = false; event_loop.run(move |event, _, control_flow| match event { Event::MainEventsCleared => { if ctrlc.load(Ordering::Relaxed) { log::warn!("Exiting through Ctrl-C"); *control_flow = ControlFlow::Exit; match state.session.request_exit() { Ok(()) => {} Err(openxr::sys::Result::ERROR_SESSION_NOT_RUNNING) => {} Err(e) => panic!("{}", e), } return; } while let Some(event) = state .openxr .instance .poll_event(&mut xr_event_storage) .unwrap() {
use openxr::Event::*; match event { SessionStateChanged(e) => { log::warn!("entered state {:?}", e.state()); xr_focused = false; match e.state() { SessionState::READY => { state .session .begin(ViewConfigurationType::PRIMARY_STEREO) .unwrap(); xr_session_running = true; } SessionState::STOPPING => { state.session.end().unwrap(); xr_session_running = false; } SessionState::FOCUSED => { xr_focused = true; } SessionState::EXITING | SessionState::LOSS_PENDING => { *control_flow = ControlFlow::Exit; return; } _ => {} } } InstanceLossPending(_) => { *control_flow = ControlFlow::Exit; return; } EventsLost(e) => { log::error!("lost {} events", e.lost_event_count()); } _ => {} } } let hmd_pre_render_info = state.pre_render_hmd().unwrap(); if hmd_pre_render_info.image_index.is_some() { let image_index = hmd_pre_render_info.image_index.unwrap(); let hmd_current_frame = &hmd_per_frame_buffers[image_index as usize]; state .record_hmd( hmd_pre_render_info, hmd_pipeline_layout, hmd_pipeline, &hmd_current_frame.mesh_buffers, hmd_current_frame.descriptor_set, ) .unwrap(); let views = state .get_views(hmd_pre_render_info.frame_state.predicted_display_time) .unwrap(); hmd_current_frame.matrix_buffer.write(&[UniformMatricesHMD { model: Matrix4::identity(), view_left: pose_to_matrix_inverse(views[0].pose), view_right: pose_to_matrix_inverse(views[1].pose), proj_left: fov_to_projection(views[0].fov), proj_right: fov_to_projection(views[1].fov), }]); state.submit_hmd(hmd_pre_render_info, &views).unwrap(); } let window_pre_render_info = state.pre_render_window().unwrap(); let window_current_frame = &window_per_frame_buffers[window_pre_render_info.image_index as usize]; spherical_coords.update( &pressed_keys .iter() .map(|&k| k.into()) .collect::<Vec<KeyMap>>(), ); window_current_frame .matrix_buffer .write(&[UniformMatricesWindow { model: Matrix4::identity(), view: Matrix4::look_at_rh( spherical_coords.to_coords(), Point3::origin(), Vector3::unit_y(), ), proj: { let mut tmp = perspective( Deg(45.0), window.inner_size().width as f32 / window.inner_size().height as f32, 0.1, 100.0, ); tmp[1][1] *= -1.0; tmp }, }]); state .render_window( window_pre_render_info, window_pipeline_layout, window_pipeline, &window_current_frame.mesh_buffers, window_current_frame.descriptor_set, ) .unwrap(); window.request_redraw(); } Event::WindowEvent { ref event, window_id, } if window_id == window.id() => { match event { WindowEvent::CloseRequested | WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } => *control_flow = ControlFlow::Exit, WindowEvent::Resized(new_inner_size) => { log::info!("Resizing to {:?}", new_inner_size); state.resize(&window).unwrap(); } WindowEvent::ScaleFactorChanged { scale_factor, new_inner_size, } => { log::info!("Changing scale to {}", scale_factor); log::info!("Resizing to {:?}", new_inner_size); state.resize(&window).unwrap(); } WindowEvent::KeyboardInput { input: KeyboardInput { state, virtual_keycode: Some(code), .. }, .. } => { _ = match state { ElementState::Pressed => pressed_keys.insert(*code), ElementState::Released => pressed_keys.remove(code), } } _ => {} } } _ => {} }) }
function_block-function_prefixed
[ { "content": "// there are 4 angles to consider instead of one\n\npub fn fov_to_projection(fov: Fovf) -> Matrix4<f32> {\n\n let tan_left = fov.angle_left.tan();\n\n let tan_right = fov.angle_right.tan();\n\n let tan_down = fov.angle_down.tan();\n\n let tan_up = fov.angle_up.tan();\n\n let near = ...
Rust
crates/nu-parser/src/hir.rs
jkatzmewing/nushell
7061af712e3eec7e2bb68bf7ca31e67d6b8b3ae8
pub(crate) mod baseline_parse; pub(crate) mod binary; pub(crate) mod expand_external_tokens; pub(crate) mod external_command; pub(crate) mod named; pub(crate) mod path; pub(crate) mod range; pub mod syntax_shape; pub(crate) mod tokens_iterator; use crate::hir::syntax_shape::Member; use crate::parse::operator::CompareOperator; use crate::parse::parser::Number; use crate::parse::unit::Unit; use derive_new::new; use getset::Getters; use nu_protocol::{PathMember, ShellTypeName}; use nu_source::{ b, DebugDocBuilder, HasSpan, IntoSpanned, PrettyDebug, PrettyDebugRefineKind, PrettyDebugWithSource, Span, Spanned, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use crate::parse::number::RawNumber; pub(crate) use self::binary::Binary; pub(crate) use self::path::Path; pub(crate) use self::range::Range; pub(crate) use self::tokens_iterator::TokensIterator; pub use self::external_command::ExternalCommand; pub use self::named::{NamedArguments, NamedValue}; #[derive(Debug, Clone)] pub struct Signature { unspanned: nu_protocol::Signature, span: Span, } impl Signature { pub fn new(unspanned: nu_protocol::Signature, span: impl Into<Span>) -> Signature { Signature { unspanned, span: span.into(), } } } impl HasSpan for Signature { fn span(&self) -> Span { self.span } } impl PrettyDebugWithSource for Signature { fn pretty_debug(&self, source: &str) -> DebugDocBuilder { self.unspanned.pretty_debug(source) } } #[derive(Debug, Clone, Eq, PartialEq, Getters, Serialize, Deserialize, new)] pub struct Call { #[get = "pub(crate)"] pub head: Box<SpannedExpression>, #[get = "pub(crate)"] pub positional: Option<Vec<SpannedExpression>>, #[get = "pub(crate)"] pub named: Option<NamedArguments>, pub span: Span, } impl Call { pub fn switch_preset(&self, switch: &str) -> bool { self.named .as_ref() .and_then(|n| n.get(switch)) .map(|t| match t { NamedValue::PresentSwitch(_) => true, _ => false, }) .unwrap_or(false) } } impl PrettyDebugWithSource for Call { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.pretty_debug(source), PrettyDebugRefineKind::WithContext => { self.head .refined_pretty_debug(PrettyDebugRefineKind::WithContext, source) + b::preceded_option( Some(b::space()), self.positional.as_ref().map(|pos| { b::intersperse( pos.iter().map(|expr| { expr.refined_pretty_debug( PrettyDebugRefineKind::WithContext, source, ) }), b::space(), ) }), ) + b::preceded_option( Some(b::space()), self.named.as_ref().map(|named| { named.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source) }), ) } } } fn pretty_debug(&self, source: &str) -> DebugDocBuilder { b::typed( "call", self.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source), ) } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Expression { Literal(Literal), ExternalWord, Synthetic(Synthetic), Variable(Variable), Binary(Box<Binary>), Range(Box<Range>), Block(Vec<SpannedExpression>), List(Vec<SpannedExpression>), Path(Box<Path>), FilePath(PathBuf), ExternalCommand(ExternalCommand), Command(Span), Boolean(bool), } impl ShellTypeName for Expression { fn type_name(&self) -> &'static str { match self { Expression::Literal(literal) => literal.type_name(), Expression::Synthetic(synthetic) => synthetic.type_name(), Expression::Command(..) => "command", Expression::ExternalWord => "external word", Expression::FilePath(..) => "file path", Expression::Variable(..) => "variable", Expression::List(..) => "list", Expression::Binary(..) => "binary", Expression::Range(..) => "range", Expression::Block(..) => "block", Expression::Path(..) => "variable path", Expression::Boolean(..) => "boolean", Expression::ExternalCommand(..) => "external", } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Synthetic { String(String), } impl ShellTypeName for Synthetic { fn type_name(&self) -> &'static str { match self { Synthetic::String(_) => "string", } } } impl IntoSpanned for Expression { type Output = SpannedExpression; fn into_spanned(self, span: impl Into<Span>) -> Self::Output { SpannedExpression { expr: self, span: span.into(), } } } impl Expression { pub fn into_expr(self, span: impl Into<Span>) -> SpannedExpression { self.into_spanned(span) } pub fn into_unspanned_expr(self) -> SpannedExpression { SpannedExpression { expr: self, span: Span::unknown(), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub struct SpannedExpression { pub expr: Expression, pub span: Span, } impl std::ops::Deref for SpannedExpression { type Target = Expression; fn deref(&self) -> &Expression { &self.expr } } impl HasSpan for SpannedExpression { fn span(&self) -> Span { self.span } } impl ShellTypeName for SpannedExpression { fn type_name(&self) -> &'static str { self.expr.type_name() } } impl PrettyDebugWithSource for SpannedExpression { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.refined_pretty_debug(refine, source), PrettyDebugRefineKind::WithContext => match &self.expr { Expression::Literal(literal) => literal .clone() .into_spanned(self.span) .refined_pretty_debug(refine, source), Expression::ExternalWord => { b::delimit("e\"", b::primitive(self.span.slice(source)), "\"").group() } Expression::Synthetic(s) => match s { Synthetic::String(_) => { b::delimit("s\"", b::primitive(self.span.slice(source)), "\"").group() } }, Expression::Variable(Variable::Other(_)) => b::keyword(self.span.slice(source)), Expression::Variable(Variable::It(_)) => b::keyword("$it"), Expression::Binary(binary) => binary.pretty_debug(source), Expression::Range(range) => range.pretty_debug(source), Expression::Block(_) => b::opaque("block"), Expression::List(list) => b::delimit( "[", b::intersperse( list.iter() .map(|item| item.refined_pretty_debug(refine, source)), b::space(), ), "]", ), Expression::Path(path) => path.pretty_debug(source), Expression::FilePath(path) => b::typed("path", b::primitive(path.display())), Expression::ExternalCommand(external) => { b::keyword("^") + b::keyword(external.name.slice(source)) } Expression::Command(command) => b::keyword(command.slice(source)), Expression::Boolean(boolean) => match boolean { true => b::primitive("$yes"), false => b::primitive("$no"), }, }, } } fn pretty_debug(&self, source: &str) -> DebugDocBuilder { match &self.expr { Expression::Literal(literal) => { literal.clone().into_spanned(self.span).pretty_debug(source) } Expression::ExternalWord => { b::typed("external word", b::primitive(self.span.slice(source))) } Expression::Synthetic(s) => match s { Synthetic::String(s) => b::typed("synthetic", b::primitive(format!("{:?}", s))), }, Expression::Variable(Variable::Other(_)) => b::keyword(self.span.slice(source)), Expression::Variable(Variable::It(_)) => b::keyword("$it"), Expression::Binary(binary) => binary.pretty_debug(source), Expression::Range(range) => range.pretty_debug(source), Expression::Block(_) => b::opaque("block"), Expression::List(list) => b::delimit( "[", b::intersperse( list.iter().map(|item| item.pretty_debug(source)), b::space(), ), "]", ), Expression::Path(path) => path.pretty_debug(source), Expression::FilePath(path) => b::typed("path", b::primitive(path.display())), Expression::ExternalCommand(external) => b::typed( "command", b::keyword("^") + b::primitive(external.name.slice(source)), ), Expression::Command(command) => { b::typed("command", b::primitive(command.slice(source))) } Expression::Boolean(boolean) => match boolean { true => b::primitive("$yes"), false => b::primitive("$no"), }, } } } impl Expression { pub fn number(i: impl Into<Number>) -> Expression { Expression::Literal(Literal::Number(i.into())) } pub fn size(i: impl Into<Number>, unit: impl Into<Unit>) -> Expression { Expression::Literal(Literal::Size(i.into(), unit.into())) } pub fn string(inner: impl Into<Span>) -> Expression { Expression::Literal(Literal::String(inner.into())) } pub fn synthetic_string(string: impl Into<String>) -> Expression { Expression::Synthetic(Synthetic::String(string.into())) } pub fn column_path(members: Vec<Member>) -> Expression { Expression::Literal(Literal::ColumnPath(members)) } pub fn path(head: SpannedExpression, tail: Vec<impl Into<PathMember>>) -> Expression { let tail = tail.into_iter().map(|t| t.into()).collect(); Expression::Path(Box::new(Path::new(head, tail))) } pub fn dot_member(head: SpannedExpression, next: impl Into<PathMember>) -> Expression { let SpannedExpression { expr: item, span } = head; let next = next.into(); match item { Expression::Path(path) => { let (head, mut tail) = path.parts(); tail.push(next); Expression::path(head, tail) } other => Expression::path(other.into_expr(span), vec![next]), } } pub fn infix( left: SpannedExpression, op: Spanned<impl Into<CompareOperator>>, right: SpannedExpression, ) -> Expression { Expression::Binary(Box::new(Binary::new(left, op.map(|o| o.into()), right))) } pub fn range(left: SpannedExpression, op: Span, right: SpannedExpression) -> Expression { Expression::Range(Box::new(Range::new(left, op, right))) } pub fn file_path(path: impl Into<PathBuf>) -> Expression { Expression::FilePath(path.into()) } pub fn list(list: Vec<SpannedExpression>) -> Expression { Expression::List(list) } pub fn bare() -> Expression { Expression::Literal(Literal::Bare) } pub fn pattern(inner: impl Into<String>) -> Expression { Expression::Literal(Literal::GlobPattern(inner.into())) } pub fn variable(inner: impl Into<Span>) -> Expression { Expression::Variable(Variable::Other(inner.into())) } pub fn external_command(inner: impl Into<Span>) -> Expression { Expression::ExternalCommand(ExternalCommand::new(inner.into())) } pub fn it_variable(inner: impl Into<Span>) -> Expression { Expression::Variable(Variable::It(inner.into())) } } impl From<Spanned<Path>> for SpannedExpression { fn from(path: Spanned<Path>) -> SpannedExpression { Expression::Path(Box::new(path.item)).into_expr(path.span) } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Literal { Number(Number), Size(Number, Unit), String(Span), GlobPattern(String), ColumnPath(Vec<Member>), Bare, } impl Literal { pub fn into_spanned(self, span: impl Into<Span>) -> SpannedLiteral { SpannedLiteral { literal: self, span: span.into(), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub struct SpannedLiteral { pub literal: Literal, pub span: Span, } impl ShellTypeName for Literal { fn type_name(&self) -> &'static str { match &self { Literal::Number(..) => "number", Literal::Size(..) => "size", Literal::String(..) => "string", Literal::ColumnPath(..) => "column path", Literal::Bare => "string", Literal::GlobPattern(_) => "pattern", } } } impl PrettyDebugWithSource for SpannedLiteral { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.pretty_debug(source), PrettyDebugRefineKind::WithContext => match &self.literal { Literal::Number(number) => number.pretty(), Literal::Size(number, unit) => (number.pretty() + unit.pretty()).group(), Literal::String(string) => b::primitive(format!("{:?}", string.slice(source))), Literal::GlobPattern(pattern) => b::primitive(pattern), Literal::ColumnPath(path) => { b::intersperse_with_source(path.iter(), b::space(), source) } Literal::Bare => b::delimit("b\"", b::primitive(self.span.slice(source)), "\""), }, } } fn pretty_debug(&self, source: &str) -> DebugDocBuilder { match &self.literal { Literal::Number(number) => number.pretty(), Literal::Size(number, unit) => { b::typed("size", (number.pretty() + unit.pretty()).group()) } Literal::String(string) => b::typed( "string", b::primitive(format!("{:?}", string.slice(source))), ), Literal::GlobPattern(pattern) => b::typed("pattern", b::primitive(pattern)), Literal::ColumnPath(path) => b::typed( "column path", b::intersperse_with_source(path.iter(), b::space(), source), ), Literal::Bare => b::typed("bare", b::primitive(self.span.slice(source))), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Variable { It(Span), Other(Span), }
pub(crate) mod baseline_parse; pub(crate) mod binary; pub(crate) mod expand_external_tokens; pub(crate) mod external_command; pub(crate) mod named; pub(crate) mod path; pub(crate) mod range; pub mod syntax_shape; pub(crate) mod tokens_iterator; use crate::hir::syntax_shape::Member; use crate::parse::operator::CompareOperator; use crate::parse::parser::Number; use crate::parse::unit::Unit; use derive_new::new; use getset::Getters; use nu_protocol::{PathMember, ShellTypeName}; use nu_source::{ b, DebugDocBuilder, HasSpan, IntoSpanned, PrettyDebug, PrettyDebugRefineKind, PrettyDebugWithSource, Span, Spanned, }; use serde::{Deserialize, Serialize}; use std::path::PathBuf; use crate::parse::number::RawNumber; pub(crate) use self::binary::Binary; pub(crate) use self::path::Path; pub(crate) use self::range::Range; pub(crate) use self::tokens_iterator::TokensIterator; pub use self::external_command::ExternalCommand; pub use self::named::{NamedArguments, NamedValue}; #[derive(Debug, Clone)] pub struct Signature { unspanned: nu_protocol::Signature, span: Span, } impl Signature { pub fn new(unspanned: nu_protocol::Signature, span: impl Into<Span>) -> Signature { Signature { unspanned, span: span.into(), } } } impl HasSpan for Signature { fn span(&self) -> Span { self.span } } impl PrettyDebugWithSource for Signature { fn pretty_debug(&self, source: &str) -> DebugDocBuilder { self.unspanned.pretty_debug(source) } } #[derive(Debug, Clone, Eq, PartialEq, Getters, Serialize, Deserialize, new)] pub struct Call { #[get = "pub(crate)"] pub head: Box<SpannedExpression>, #[get = "pub(crate)"] pub positional: Option<Vec<SpannedExpression>>, #[get = "pub(crate)"] pub named: Option<NamedArguments>, pub span: Span, } impl Call { pub fn switch_preset(&self, switch: &str) -> bool { self.named .as_ref() .and_then(|n| n.get(switch)) .map(|t| match t { NamedValue::PresentSwitch(_) => true, _ => false, }) .unwrap_or(false) } } impl PrettyDebugWithSource for Call { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.pretty_debug(source), PrettyDebugRefineKind::WithContext => { self.head .refined_pretty_debug(PrettyDebugRefineKind::WithContext, source) + b::preceded_option( Some(b::space()), self.positional.as_ref().map(|pos| { b::intersperse( pos.iter().map(|expr| { expr.refined_pretty_debug( PrettyDebugRefineKind::WithContext, source, ) }), b::spac
fn pretty_debug(&self, source: &str) -> DebugDocBuilder { b::typed( "call", self.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source), ) } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Expression { Literal(Literal), ExternalWord, Synthetic(Synthetic), Variable(Variable), Binary(Box<Binary>), Range(Box<Range>), Block(Vec<SpannedExpression>), List(Vec<SpannedExpression>), Path(Box<Path>), FilePath(PathBuf), ExternalCommand(ExternalCommand), Command(Span), Boolean(bool), } impl ShellTypeName for Expression { fn type_name(&self) -> &'static str { match self { Expression::Literal(literal) => literal.type_name(), Expression::Synthetic(synthetic) => synthetic.type_name(), Expression::Command(..) => "command", Expression::ExternalWord => "external word", Expression::FilePath(..) => "file path", Expression::Variable(..) => "variable", Expression::List(..) => "list", Expression::Binary(..) => "binary", Expression::Range(..) => "range", Expression::Block(..) => "block", Expression::Path(..) => "variable path", Expression::Boolean(..) => "boolean", Expression::ExternalCommand(..) => "external", } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Synthetic { String(String), } impl ShellTypeName for Synthetic { fn type_name(&self) -> &'static str { match self { Synthetic::String(_) => "string", } } } impl IntoSpanned for Expression { type Output = SpannedExpression; fn into_spanned(self, span: impl Into<Span>) -> Self::Output { SpannedExpression { expr: self, span: span.into(), } } } impl Expression { pub fn into_expr(self, span: impl Into<Span>) -> SpannedExpression { self.into_spanned(span) } pub fn into_unspanned_expr(self) -> SpannedExpression { SpannedExpression { expr: self, span: Span::unknown(), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub struct SpannedExpression { pub expr: Expression, pub span: Span, } impl std::ops::Deref for SpannedExpression { type Target = Expression; fn deref(&self) -> &Expression { &self.expr } } impl HasSpan for SpannedExpression { fn span(&self) -> Span { self.span } } impl ShellTypeName for SpannedExpression { fn type_name(&self) -> &'static str { self.expr.type_name() } } impl PrettyDebugWithSource for SpannedExpression { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.refined_pretty_debug(refine, source), PrettyDebugRefineKind::WithContext => match &self.expr { Expression::Literal(literal) => literal .clone() .into_spanned(self.span) .refined_pretty_debug(refine, source), Expression::ExternalWord => { b::delimit("e\"", b::primitive(self.span.slice(source)), "\"").group() } Expression::Synthetic(s) => match s { Synthetic::String(_) => { b::delimit("s\"", b::primitive(self.span.slice(source)), "\"").group() } }, Expression::Variable(Variable::Other(_)) => b::keyword(self.span.slice(source)), Expression::Variable(Variable::It(_)) => b::keyword("$it"), Expression::Binary(binary) => binary.pretty_debug(source), Expression::Range(range) => range.pretty_debug(source), Expression::Block(_) => b::opaque("block"), Expression::List(list) => b::delimit( "[", b::intersperse( list.iter() .map(|item| item.refined_pretty_debug(refine, source)), b::space(), ), "]", ), Expression::Path(path) => path.pretty_debug(source), Expression::FilePath(path) => b::typed("path", b::primitive(path.display())), Expression::ExternalCommand(external) => { b::keyword("^") + b::keyword(external.name.slice(source)) } Expression::Command(command) => b::keyword(command.slice(source)), Expression::Boolean(boolean) => match boolean { true => b::primitive("$yes"), false => b::primitive("$no"), }, }, } } fn pretty_debug(&self, source: &str) -> DebugDocBuilder { match &self.expr { Expression::Literal(literal) => { literal.clone().into_spanned(self.span).pretty_debug(source) } Expression::ExternalWord => { b::typed("external word", b::primitive(self.span.slice(source))) } Expression::Synthetic(s) => match s { Synthetic::String(s) => b::typed("synthetic", b::primitive(format!("{:?}", s))), }, Expression::Variable(Variable::Other(_)) => b::keyword(self.span.slice(source)), Expression::Variable(Variable::It(_)) => b::keyword("$it"), Expression::Binary(binary) => binary.pretty_debug(source), Expression::Range(range) => range.pretty_debug(source), Expression::Block(_) => b::opaque("block"), Expression::List(list) => b::delimit( "[", b::intersperse( list.iter().map(|item| item.pretty_debug(source)), b::space(), ), "]", ), Expression::Path(path) => path.pretty_debug(source), Expression::FilePath(path) => b::typed("path", b::primitive(path.display())), Expression::ExternalCommand(external) => b::typed( "command", b::keyword("^") + b::primitive(external.name.slice(source)), ), Expression::Command(command) => { b::typed("command", b::primitive(command.slice(source))) } Expression::Boolean(boolean) => match boolean { true => b::primitive("$yes"), false => b::primitive("$no"), }, } } } impl Expression { pub fn number(i: impl Into<Number>) -> Expression { Expression::Literal(Literal::Number(i.into())) } pub fn size(i: impl Into<Number>, unit: impl Into<Unit>) -> Expression { Expression::Literal(Literal::Size(i.into(), unit.into())) } pub fn string(inner: impl Into<Span>) -> Expression { Expression::Literal(Literal::String(inner.into())) } pub fn synthetic_string(string: impl Into<String>) -> Expression { Expression::Synthetic(Synthetic::String(string.into())) } pub fn column_path(members: Vec<Member>) -> Expression { Expression::Literal(Literal::ColumnPath(members)) } pub fn path(head: SpannedExpression, tail: Vec<impl Into<PathMember>>) -> Expression { let tail = tail.into_iter().map(|t| t.into()).collect(); Expression::Path(Box::new(Path::new(head, tail))) } pub fn dot_member(head: SpannedExpression, next: impl Into<PathMember>) -> Expression { let SpannedExpression { expr: item, span } = head; let next = next.into(); match item { Expression::Path(path) => { let (head, mut tail) = path.parts(); tail.push(next); Expression::path(head, tail) } other => Expression::path(other.into_expr(span), vec![next]), } } pub fn infix( left: SpannedExpression, op: Spanned<impl Into<CompareOperator>>, right: SpannedExpression, ) -> Expression { Expression::Binary(Box::new(Binary::new(left, op.map(|o| o.into()), right))) } pub fn range(left: SpannedExpression, op: Span, right: SpannedExpression) -> Expression { Expression::Range(Box::new(Range::new(left, op, right))) } pub fn file_path(path: impl Into<PathBuf>) -> Expression { Expression::FilePath(path.into()) } pub fn list(list: Vec<SpannedExpression>) -> Expression { Expression::List(list) } pub fn bare() -> Expression { Expression::Literal(Literal::Bare) } pub fn pattern(inner: impl Into<String>) -> Expression { Expression::Literal(Literal::GlobPattern(inner.into())) } pub fn variable(inner: impl Into<Span>) -> Expression { Expression::Variable(Variable::Other(inner.into())) } pub fn external_command(inner: impl Into<Span>) -> Expression { Expression::ExternalCommand(ExternalCommand::new(inner.into())) } pub fn it_variable(inner: impl Into<Span>) -> Expression { Expression::Variable(Variable::It(inner.into())) } } impl From<Spanned<Path>> for SpannedExpression { fn from(path: Spanned<Path>) -> SpannedExpression { Expression::Path(Box::new(path.item)).into_expr(path.span) } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Literal { Number(Number), Size(Number, Unit), String(Span), GlobPattern(String), ColumnPath(Vec<Member>), Bare, } impl Literal { pub fn into_spanned(self, span: impl Into<Span>) -> SpannedLiteral { SpannedLiteral { literal: self, span: span.into(), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub struct SpannedLiteral { pub literal: Literal, pub span: Span, } impl ShellTypeName for Literal { fn type_name(&self) -> &'static str { match &self { Literal::Number(..) => "number", Literal::Size(..) => "size", Literal::String(..) => "string", Literal::ColumnPath(..) => "column path", Literal::Bare => "string", Literal::GlobPattern(_) => "pattern", } } } impl PrettyDebugWithSource for SpannedLiteral { fn refined_pretty_debug(&self, refine: PrettyDebugRefineKind, source: &str) -> DebugDocBuilder { match refine { PrettyDebugRefineKind::ContextFree => self.pretty_debug(source), PrettyDebugRefineKind::WithContext => match &self.literal { Literal::Number(number) => number.pretty(), Literal::Size(number, unit) => (number.pretty() + unit.pretty()).group(), Literal::String(string) => b::primitive(format!("{:?}", string.slice(source))), Literal::GlobPattern(pattern) => b::primitive(pattern), Literal::ColumnPath(path) => { b::intersperse_with_source(path.iter(), b::space(), source) } Literal::Bare => b::delimit("b\"", b::primitive(self.span.slice(source)), "\""), }, } } fn pretty_debug(&self, source: &str) -> DebugDocBuilder { match &self.literal { Literal::Number(number) => number.pretty(), Literal::Size(number, unit) => { b::typed("size", (number.pretty() + unit.pretty()).group()) } Literal::String(string) => b::typed( "string", b::primitive(format!("{:?}", string.slice(source))), ), Literal::GlobPattern(pattern) => b::typed("pattern", b::primitive(pattern)), Literal::ColumnPath(path) => b::typed( "column path", b::intersperse_with_source(path.iter(), b::space(), source), ), Literal::Bare => b::typed("bare", b::primitive(self.span.slice(source))), } } } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum Variable { It(Span), Other(Span), }
e(), ) }), ) + b::preceded_option( Some(b::space()), self.named.as_ref().map(|named| { named.refined_pretty_debug(PrettyDebugRefineKind::WithContext, source) }), ) } } }
function_block-function_prefixed
[ { "content": "pub fn files_exist_at(files: Vec<impl AsRef<Path>>, path: impl AsRef<Path>) -> bool {\n\n files.iter().all(|f| {\n\n let mut loc = PathBuf::from(path.as_ref());\n\n loc.push(f);\n\n loc.exists()\n\n })\n\n}\n\n\n", "file_path": "crates/nu-test-support/src/fs.rs", ...
Rust
src/token.rs
illumination-k/rs9cc
6c2570e5d250435267a331b0a4d66ca052cb477d
use std::iter::Peekable; use std::collections::HashSet; #[derive(Debug, Clone)] struct OpWords { op_words: HashSet<String>, max_length: usize, } impl OpWords { fn new(op_words: Vec<&str>) -> Self { let max_length = op_words.iter().map(|x| x.len()).max().unwrap(); Self { op_words: op_words.into_iter().map(|x| x.to_string()).collect(), max_length: max_length, } } fn contains(&self, x: &str) -> bool { self.op_words.contains(x) } fn contains_u8(&self, x: &[u8]) -> bool { unsafe { self.contains(String::from_utf8_unchecked(x.to_vec()).as_ref()) } } fn ops(&self, len: usize) -> Vec<String> { self.op_words.iter().filter(|x| x.len() == len).map(|x| x.clone()).collect() } } impl Default for OpWords { fn default() -> Self { let op_words = vec!["+", "-", "/", "*", "==", "=!", ">=", "<=", "<", ">", "(", ")"]; OpWords::new(op_words) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TokenKind { TkReserved, TkNum, } #[derive(Debug, Clone)] pub struct Token { pub token_kind: TokenKind, pub val: String, } impl Token { pub fn new(token_kind: TokenKind, val: String) -> Self { Self { token_kind, val } } } pub struct TokenIter { s: String, op_words: OpWords, } impl Iterator for TokenIter { type Item = Token; fn next(&mut self) -> Option<Self::Item> { self.s = self.s.trim().to_string(); if self.s.is_empty() { return None } let mut bytes = std::collections::VecDeque::from(self.s.to_owned().as_bytes().to_vec()); let mut val = vec![]; let token_kind = if bytes[0].is_ascii_digit() { TokenKind::TkNum } else { TokenKind::TkReserved }; match token_kind { TokenKind::TkNum => { while let Some(byte) = bytes.pop_front() { if byte.is_ascii_digit() { val.push(byte) } else { bytes.push_front(byte); break; } } }, TokenKind::TkReserved => { while let Some(byte) = bytes.pop_front() { if !byte.is_ascii_digit() && byte != b' ' { val.push(byte); } else { bytes.push_front(byte); break; } } let mut now_length = self.op_words.max_length; while now_length > 0 { if now_length <= val.len() { if self.op_words.contains_u8(&val[..now_length]) { for &v in val[now_length..].iter().rev() { bytes.push_front(v) } val = val[..now_length].to_vec(); break; } } now_length -= 1; } } } unsafe { self.s = String::from_utf8_unchecked(bytes.into_iter().collect()); Some(Token::new(token_kind, String::from_utf8_unchecked(val))) } } } pub trait TokenExt { fn tokenize(&self) -> TokenIter; } impl TokenExt for String { fn tokenize(&self) -> TokenIter { TokenIter { s: self.to_owned(), op_words: Default::default(), } } } pub fn consume(op: &str, iter: &mut Peekable<TokenIter>) -> bool { match iter.peek() { Some(t) => { if t.token_kind == TokenKind::TkReserved && &t.val == op { iter.next(); true } else { false } }, None => false } } #[cfg(test)] mod test { use super::*; #[test] fn test_op_words() { let mut op_words: OpWords = Default::default(); assert!(op_words.contains("*")); assert!(op_words.contains("(")); assert!(op_words.contains_u8(b"(")); assert!(!op_words.contains_u8(b"!=)")); } #[test] fn test_tokenizer() { let s = "13 + 2 - 3".to_string(); let vals = vec!["13", "+", "2", "-", "3"].iter().map(|x| x.to_string()).collect::<Vec<String>>(); let kinds = vec![TokenKind::TkNum, TokenKind::TkReserved, TokenKind::TkNum, TokenKind::TkReserved, TokenKind::TkNum]; let mut dvals = vec![]; let mut dkinds = vec![]; for t in s.tokenize() { dvals.push(t.val); dkinds.push(t.token_kind) } assert_eq!(vals, dvals); assert_eq!(kinds, dkinds); } }
use std::iter::Peekable; use std::collections::HashSet; #[derive(Debug, Clone)] struct OpWords { op_words: HashSet<String>, max_length: usize, } impl OpWords { fn new(op_words: Vec<&str>) -> Self { let max_length = op_words.iter().map(|x| x.len()).max().unwrap(); Self { op_words: op_words.into_iter().map(|x| x.to_string()).collect(), max_length: max_length, } } fn contains(&self, x: &str) -> bool { self.op_words.contains(x) } fn contains_u8(&self, x: &[u8]) -> bool { unsafe { self.contains(String::from_utf8_unchecked(x.to_vec()).as_ref()) } } fn ops(&self, len: usize) -> Vec<String> { self.op_words.iter().filter(|x| x.len() == len).map(|x| x.clone()).collect() } } impl Default for OpWords { fn default() -> Self { let op_words = vec!["+", "-", "/", "*", "==", "=!", ">=", "<=", "<", ">", "(", ")"]; OpWords::new(op_words) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TokenKind { TkReserved, TkNum, } #[derive(Debug, Clone)] pub struct Token { pub token_kind: TokenKind, pub val: String, } impl Token { pub fn new(token_kind: TokenKind, val: String) -> Self { Self { token_kind, val } } } pub struct TokenIter { s: String, op_words: OpWords, } impl Iterator for TokenIter { type Item = Token; fn next(&mut self) -> Option<Self::Item> { self.s = self.s.trim().to_string(); if self.s.is_empty() { return None } let mut bytes = std::collections::VecDeque::from(self.s.to_owned().as_bytes().to_vec()); let mut val = vec![]; let token_kind =
&v in val[now_length..].iter().rev() { bytes.push_front(v) } val = val[..now_length].to_vec(); break; } } now_length -= 1; } } } unsafe { self.s = String::from_utf8_unchecked(bytes.into_iter().collect()); Some(Token::new(token_kind, String::from_utf8_unchecked(val))) } } } pub trait TokenExt { fn tokenize(&self) -> TokenIter; } impl TokenExt for String { fn tokenize(&self) -> TokenIter { TokenIter { s: self.to_owned(), op_words: Default::default(), } } } pub fn consume(op: &str, iter: &mut Peekable<TokenIter>) -> bool { match iter.peek() { Some(t) => { if t.token_kind == TokenKind::TkReserved && &t.val == op { iter.next(); true } else { false } }, None => false } } #[cfg(test)] mod test { use super::*; #[test] fn test_op_words() { let mut op_words: OpWords = Default::default(); assert!(op_words.contains("*")); assert!(op_words.contains("(")); assert!(op_words.contains_u8(b"(")); assert!(!op_words.contains_u8(b"!=)")); } #[test] fn test_tokenizer() { let s = "13 + 2 - 3".to_string(); let vals = vec!["13", "+", "2", "-", "3"].iter().map(|x| x.to_string()).collect::<Vec<String>>(); let kinds = vec![TokenKind::TkNum, TokenKind::TkReserved, TokenKind::TkNum, TokenKind::TkReserved, TokenKind::TkNum]; let mut dvals = vec![]; let mut dkinds = vec![]; for t in s.tokenize() { dvals.push(t.val); dkinds.push(t.token_kind) } assert_eq!(vals, dvals); assert_eq!(kinds, dkinds); } }
if bytes[0].is_ascii_digit() { TokenKind::TkNum } else { TokenKind::TkReserved }; match token_kind { TokenKind::TkNum => { while let Some(byte) = bytes.pop_front() { if byte.is_ascii_digit() { val.push(byte) } else { bytes.push_front(byte); break; } } }, TokenKind::TkReserved => { while let Some(byte) = bytes.pop_front() { if !byte.is_ascii_digit() && byte != b' ' { val.push(byte); } else { bytes.push_front(byte); break; } } let mut now_length = self.op_words.max_length; while now_length > 0 { if now_length <= val.len() { if self.op_words.contains_u8(&val[..now_length]) { for
function_block-random_span
[ { "content": "pub fn primary(tokenizer: &mut Peekable<TokenIter>) -> Box<Node> {\n\n if consume(\"(\", tokenizer) {\n\n let node = expr(tokenizer);\n\n let _expect = consume(\")\", tokenizer);\n\n return node \n\n }\n\n\n\n match tokenizer.peek() {\n\n Some(t) => {\n\n ...
Rust
beacon_node/store/src/block_at_slot.rs
JustinDrake/lighthouse
0694d1d0ec488d2d9f448a2bf5c6f742e1c5a5ed
use super::*; use ssz::{Decode, DecodeError}; fn get_block_bytes<T: Store<E>, E: EthSpec>( store: &T, root: Hash256, ) -> Result<Option<Vec<u8>>, Error> { store.get_bytes(BeaconBlock::<E>::db_column().into(), &root[..]) } fn read_slot_from_block_bytes(bytes: &[u8]) -> Result<Slot, DecodeError> { let end = std::cmp::min(Slot::ssz_fixed_len(), bytes.len()); Slot::from_ssz_bytes(&bytes[0..end]) } fn read_parent_root_from_block_bytes(bytes: &[u8]) -> Result<Hash256, DecodeError> { let previous_bytes = Slot::ssz_fixed_len(); let slice = bytes .get(previous_bytes..previous_bytes + Hash256::ssz_fixed_len()) .ok_or_else(|| DecodeError::BytesInvalid("Not enough bytes.".to_string()))?; Hash256::from_ssz_bytes(slice) } pub fn get_block_at_preceeding_slot<T: Store<E>, E: EthSpec>( store: &T, slot: Slot, start_root: Hash256, ) -> Result<Option<(Hash256, BeaconBlock<E>)>, Error> { Ok( match get_at_preceeding_slot::<_, E>(store, slot, start_root)? { Some((hash, bytes)) => Some((hash, BeaconBlock::<E>::from_ssz_bytes(&bytes)?)), None => None, }, ) } fn get_at_preceeding_slot<T: Store<E>, E: EthSpec>( store: &T, slot: Slot, mut root: Hash256, ) -> Result<Option<(Hash256, Vec<u8>)>, Error> { loop { if let Some(bytes) = get_block_bytes::<_, E>(store, root)? { let this_slot = read_slot_from_block_bytes(&bytes)?; if this_slot == slot { break Ok(Some((root, bytes))); } else if this_slot < slot { break Ok(None); } else { root = read_parent_root_from_block_bytes(&bytes)?; } } else { break Ok(None); } } } #[cfg(test)] mod tests { use super::*; use ssz::Encode; use tree_hash::TreeHash; type BeaconBlock = types::BeaconBlock<MinimalEthSpec>; #[test] fn read_slot() { let spec = MinimalEthSpec::default_spec(); let test_slot = |slot: Slot| { let mut block = BeaconBlock::empty(&spec); block.slot = slot; let bytes = block.as_ssz_bytes(); assert_eq!(read_slot_from_block_bytes(&bytes).unwrap(), slot); }; test_slot(Slot::new(0)); test_slot(Slot::new(1)); test_slot(Slot::new(42)); test_slot(Slot::new(u64::max_value())); } #[test] fn bad_slot() { for i in 0..8 { assert!(read_slot_from_block_bytes(&vec![0; i]).is_err()); } } #[test] fn read_parent_root() { let spec = MinimalEthSpec::default_spec(); let test_root = |root: Hash256| { let mut block = BeaconBlock::empty(&spec); block.parent_root = root; let bytes = block.as_ssz_bytes(); assert_eq!(read_parent_root_from_block_bytes(&bytes).unwrap(), root); }; test_root(Hash256::random()); test_root(Hash256::random()); test_root(Hash256::random()); } fn build_chain( store: &impl Store<MinimalEthSpec>, slots: &[usize], spec: &ChainSpec, ) -> Vec<(Hash256, BeaconBlock)> { let mut blocks_and_roots: Vec<(Hash256, BeaconBlock)> = vec![]; for (i, slot) in slots.iter().enumerate() { let mut block = BeaconBlock::empty(spec); block.slot = Slot::from(*slot); if i > 0 { block.parent_root = blocks_and_roots[i - 1].0; } let root = Hash256::from_slice(&block.tree_hash_root()); store.put(&root, &block).unwrap(); blocks_and_roots.push((root, block)); } blocks_and_roots } #[test] fn chain_without_skips() { let n: usize = 10; let store = MemoryStore::open(); let spec = MinimalEthSpec::default_spec(); let slots: Vec<usize> = (0..n).collect(); let blocks_and_roots = build_chain(&store, &slots, &spec); for source in 1..n { for target in 0..=source { let (source_root, _source_block) = &blocks_and_roots[source]; let (target_root, target_block) = &blocks_and_roots[target]; let (found_root, found_block) = store .get_block_at_preceeding_slot(*source_root, target_block.slot) .unwrap() .unwrap(); assert_eq!(found_root, *target_root); assert_eq!(found_block, *target_block); } } } #[test] fn chain_with_skips() { let store = MemoryStore::<MinimalEthSpec>::open(); let spec = MinimalEthSpec::default_spec(); let slots = vec![0, 1, 2, 5]; let blocks_and_roots = build_chain(&store, &slots, &spec); for target in 0..3 { let (source_root, _source_block) = &blocks_and_roots[3]; let (target_root, target_block) = &blocks_and_roots[target]; let (found_root, found_block) = store .get_block_at_preceeding_slot(*source_root, target_block.slot) .unwrap() .unwrap(); assert_eq!(found_root, *target_root); assert_eq!(found_block, *target_block); } let (source_root, _source_block) = &blocks_and_roots[3]; assert!(store .get_block_at_preceeding_slot(*source_root, Slot::new(3)) .unwrap() .is_none()); let (source_root, _source_block) = &blocks_and_roots[3]; assert!(store .get_block_at_preceeding_slot(*source_root, Slot::new(3)) .unwrap() .is_none()); } }
use super::*; use ssz::{Decode, DecodeError}; fn get_block_bytes<T: Store<E>, E: EthSpec>( store: &T, root: Hash256, ) -> Result<Option<Vec<u8>>, Error> { store.get_bytes(BeaconBlock::<E>::db_column().into(), &root[..]) } fn read_slot_from_block_bytes(bytes: &[u8]) -> Result<Slot, DecodeError> { let end = std::cmp::min(Slot::ssz_fixed_len(), bytes.len()); Slot::from_ssz_bytes(&bytes[0..end]) } fn read_parent_root_from_block_byte
pub fn get_block_at_preceeding_slot<T: Store<E>, E: EthSpec>( store: &T, slot: Slot, start_root: Hash256, ) -> Result<Option<(Hash256, BeaconBlock<E>)>, Error> { Ok( match get_at_preceeding_slot::<_, E>(store, slot, start_root)? { Some((hash, bytes)) => Some((hash, BeaconBlock::<E>::from_ssz_bytes(&bytes)?)), None => None, }, ) } fn get_at_preceeding_slot<T: Store<E>, E: EthSpec>( store: &T, slot: Slot, mut root: Hash256, ) -> Result<Option<(Hash256, Vec<u8>)>, Error> { loop { if let Some(bytes) = get_block_bytes::<_, E>(store, root)? { let this_slot = read_slot_from_block_bytes(&bytes)?; if this_slot == slot { break Ok(Some((root, bytes))); } else if this_slot < slot { break Ok(None); } else { root = read_parent_root_from_block_bytes(&bytes)?; } } else { break Ok(None); } } } #[cfg(test)] mod tests { use super::*; use ssz::Encode; use tree_hash::TreeHash; type BeaconBlock = types::BeaconBlock<MinimalEthSpec>; #[test] fn read_slot() { let spec = MinimalEthSpec::default_spec(); let test_slot = |slot: Slot| { let mut block = BeaconBlock::empty(&spec); block.slot = slot; let bytes = block.as_ssz_bytes(); assert_eq!(read_slot_from_block_bytes(&bytes).unwrap(), slot); }; test_slot(Slot::new(0)); test_slot(Slot::new(1)); test_slot(Slot::new(42)); test_slot(Slot::new(u64::max_value())); } #[test] fn bad_slot() { for i in 0..8 { assert!(read_slot_from_block_bytes(&vec![0; i]).is_err()); } } #[test] fn read_parent_root() { let spec = MinimalEthSpec::default_spec(); let test_root = |root: Hash256| { let mut block = BeaconBlock::empty(&spec); block.parent_root = root; let bytes = block.as_ssz_bytes(); assert_eq!(read_parent_root_from_block_bytes(&bytes).unwrap(), root); }; test_root(Hash256::random()); test_root(Hash256::random()); test_root(Hash256::random()); } fn build_chain( store: &impl Store<MinimalEthSpec>, slots: &[usize], spec: &ChainSpec, ) -> Vec<(Hash256, BeaconBlock)> { let mut blocks_and_roots: Vec<(Hash256, BeaconBlock)> = vec![]; for (i, slot) in slots.iter().enumerate() { let mut block = BeaconBlock::empty(spec); block.slot = Slot::from(*slot); if i > 0 { block.parent_root = blocks_and_roots[i - 1].0; } let root = Hash256::from_slice(&block.tree_hash_root()); store.put(&root, &block).unwrap(); blocks_and_roots.push((root, block)); } blocks_and_roots } #[test] fn chain_without_skips() { let n: usize = 10; let store = MemoryStore::open(); let spec = MinimalEthSpec::default_spec(); let slots: Vec<usize> = (0..n).collect(); let blocks_and_roots = build_chain(&store, &slots, &spec); for source in 1..n { for target in 0..=source { let (source_root, _source_block) = &blocks_and_roots[source]; let (target_root, target_block) = &blocks_and_roots[target]; let (found_root, found_block) = store .get_block_at_preceeding_slot(*source_root, target_block.slot) .unwrap() .unwrap(); assert_eq!(found_root, *target_root); assert_eq!(found_block, *target_block); } } } #[test] fn chain_with_skips() { let store = MemoryStore::<MinimalEthSpec>::open(); let spec = MinimalEthSpec::default_spec(); let slots = vec![0, 1, 2, 5]; let blocks_and_roots = build_chain(&store, &slots, &spec); for target in 0..3 { let (source_root, _source_block) = &blocks_and_roots[3]; let (target_root, target_block) = &blocks_and_roots[target]; let (found_root, found_block) = store .get_block_at_preceeding_slot(*source_root, target_block.slot) .unwrap() .unwrap(); assert_eq!(found_root, *target_root); assert_eq!(found_block, *target_block); } let (source_root, _source_block) = &blocks_and_roots[3]; assert!(store .get_block_at_preceeding_slot(*source_root, Slot::new(3)) .unwrap() .is_none()); let (source_root, _source_block) = &blocks_and_roots[3]; assert!(store .get_block_at_preceeding_slot(*source_root, Slot::new(3)) .unwrap() .is_none()); } }
s(bytes: &[u8]) -> Result<Hash256, DecodeError> { let previous_bytes = Slot::ssz_fixed_len(); let slice = bytes .get(previous_bytes..previous_bytes + Hash256::ssz_fixed_len()) .ok_or_else(|| DecodeError::BytesInvalid("Not enough bytes.".to_string()))?; Hash256::from_ssz_bytes(slice) }
function_block-function_prefixed
[ { "content": "/// Fetch the next state to use whilst backtracking in `*RootsIterator`.\n\nfn next_historical_root_backtrack_state<E: EthSpec, S: Store<E>>(\n\n store: &S,\n\n current_state: &BeaconState<E>,\n\n) -> Option<BeaconState<E>> {\n\n // For compatibility with the freezer database's restore po...
Rust
src/protocol/spdm/get_caps.rs
capoferro/manticore
64a4fb3089133d1543849bfdc44ccb8855ba0b7e
use core::mem; use core::time::Duration; use enumflags2::bitflags; use enumflags2::BitFlags; use crate::io::ReadInt as _; use crate::protocol::spdm; use crate::protocol::spdm::CommandType; protocol_struct! { type GetCaps; const TYPE: CommandType = GetCaps; #![fuzz_derives_if = any()] struct Request { pub crypto_timeout: Duration, #[cfg_attr(feature = "serde", serde(with = "crate::serde::bitflags"))] pub caps: BitFlags<Caps>, pub max_packet_size: u32, pub max_message_size: u32, } fn Request::from_wire(r, a) { spdm::expect_zeros(r, 3)?; let ct_exp = r.read_le::<u8>()?; let crypto_timeout = Duration::from_micros(1u64 << ct_exp); spdm::expect_zeros(r, 2)?; let caps = BitFlags::<Caps>::from_wire(r, a)?; let max_packet_size = r.read_le::<u32>()?; let max_message_size = r.read_le::<u32>()?; Ok(Self { crypto_timeout, caps, max_packet_size, max_message_size }) } fn Request::to_wire(&self, w) { spdm::write_zeros(&mut w, 3)?; let ct_micros = self.crypto_timeout.as_micros(); if !ct_micros.is_power_of_two() { return Err(wire::Error::OutOfRange); } let ct_exp = 8 * mem::size_of_val(&ct_micros) as u32 - ct_micros.leading_zeros() - 1; w.write_le(ct_exp as u8)?; spdm::write_zeros(&mut w, 2)?; self.caps.to_wire(&mut w)?; w.write_le(self.max_packet_size)?; w.write_le(self.max_message_size)?; Ok(()) } #![fuzz_derives_if = any()] struct Response { pub crypto_timeout: Duration, #[cfg_attr(feature = "serde", serde(with = "crate::serde::bitflags"))] pub caps: BitFlags<Caps>, pub max_packet_size: u32, pub max_message_size: u32, } fn Response::from_wire(r, a) { spdm::expect_zeros(r, 3)?; let ct_exp = r.read_le::<u8>()?; let crypto_timeout = Duration::from_micros(1u64 << ct_exp); spdm::expect_zeros(r, 2)?; let caps = BitFlags::<Caps>::from_wire(r, a)?; let max_packet_size = r.read_le::<u32>()?; let max_message_size = r.read_le::<u32>()?; Ok(Self { crypto_timeout, caps, max_packet_size, max_message_size }) } fn Response::to_wire(&self, w) { spdm::write_zeros(&mut w, 3)?; let ct_micros = self.crypto_timeout.as_micros(); if !ct_micros.is_power_of_two() { return Err(wire::Error::OutOfRange); } let ct_exp = 8 * mem::size_of_val(&ct_micros) as u32 - ct_micros.leading_zeros() - 1; w.write_le(ct_exp as u8)?; spdm::write_zeros(&mut w, 2)?; self.caps.to_wire(&mut w)?; w.write_le(self.max_packet_size)?; w.write_le(self.max_message_size)?; Ok(()) } } #[cfg(feature = "arbitrary-derive")] use { crate::protocol::arbitrary_bitflags, libfuzzer_sys::arbitrary::{self, Arbitrary, Unstructured}, }; #[cfg(feature = "arbitrary-derive")] impl Arbitrary for GetCapsRequest { fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { Ok(Self { crypto_timeout: u.arbitrary()?, caps: arbitrary_bitflags(u)?, max_packet_size: u.arbitrary()?, max_message_size: u.arbitrary()?, }) } fn size_hint(_depth: usize) -> (usize, Option<usize>) { let size = mem::size_of::<Duration>() + mem::size_of::<BitFlags<Caps>>() + mem::size_of::<u32>() * 2; (size, Some(size)) } } #[cfg(feature = "arbitrary-derive")] impl Arbitrary for GetCapsResponse { fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { Ok(Self { crypto_timeout: u.arbitrary()?, caps: arbitrary_bitflags(u)?, max_packet_size: u.arbitrary()?, max_message_size: u.arbitrary()?, }) } fn size_hint(_depth: usize) -> (usize, Option<usize>) { let size = mem::size_of::<Duration>() + mem::size_of::<BitFlags<Caps>>() + mem::size_of::<u32>() * 2; (size, Some(size)) } } #[bitflags] #[repr(u32)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Caps { Cache = 1 << 0, Certs = 1 << 1, Challenge = 1 << 2, UnsignedMeasurements = 1 << 3, SignedMeasurements = 1 << 4, FreshMeasurements = 1 << 5, SessionEncryption = 1 << 6, SessionAuth = 1 << 7, MutualAuth = 1 << 8, KeyExchange = 1 << 9, PskWithoutContext = 1 << 10, PskWithContext = 1 << 11, Heartbeat = 1 << 13, KeyUpdate = 1 << 14, HandshakeInTheClear = 1 << 15, PubKeyProvisioned = 1 << 16, Chunking = 1 << 17, AliasCert = 1 << 18, } impl Caps { pub fn manticore() -> enumflags2::BitFlags<Self> { Self::Certs | Self::Challenge | Self::SignedMeasurements | Self::FreshMeasurements | Self::SessionEncryption | Self::KeyExchange | Self::Heartbeat | Self::AliasCert } } #[cfg(test)] mod test { use super::*; round_trip_test! { request_round_trip: { bytes: &[ 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0b01110110, 0b00100010, 0b00000100, 0b00000000, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, ], json: r#"{ "crypto_timeout": { "nanos": 4096000, "secs": 0 }, "caps": [ "Certs", "Challenge", "SignedMeasurements", "FreshMeasurements", "SessionEncryption", "KeyExchange", "Heartbeat", "AliasCert" ], "max_packet_size": 256, "max_message_size": 1024 }"#, value: GetCapsRequest { crypto_timeout: Duration::from_micros(4096), caps: Caps::manticore(), max_packet_size: 256, max_message_size: 1024, }, }, response_round_trip: { bytes: &[ 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0b01110110, 0b00100010, 0b00000100, 0b00000000, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, ], json: r#"{ "crypto_timeout": { "nanos": 4096000, "secs": 0 }, "caps": [ "Certs", "Challenge", "SignedMeasurements", "FreshMeasurements", "SessionEncryption", "KeyExchange", "Heartbeat", "AliasCert" ], "max_packet_size": 256, "max_message_size": 1024 }"#, value: GetCapsResponse { crypto_timeout: Duration::from_micros(4096), caps: Caps::manticore(), max_packet_size: 256, max_message_size: 1024, }, }, } }
use core::mem; use core::time::Duration; use enumflags2::bitflags; use enumflags2::BitFlags; use crate::io::ReadInt as _; use crate::protocol::spdm; use crate::protocol::spdm::CommandType; protocol_struct! { type GetCaps; const TYPE: CommandType = GetCaps; #![fuzz_derives_if = any()] struct Request { pub crypto_timeout: Duration, #[cfg_attr(feature = "serde", serde(with = "crate::serde::bitflags"))] pub caps: BitFlags<Caps>, pub max_packet_size: u32, pub max_message_size: u32, } fn Request::from_wire(r, a) { spdm::expect_zeros(r, 3)?; let ct_exp = r.read_le::<u8>()?; let crypto_timeout = Duration::from_micros(1u64 << ct_exp); spdm::expect_zeros(r, 2)?; let caps = BitFlags::<Caps>::from_wire(r, a)?; let max_packet_size = r.read_le::<u32>()?; let max_message_size = r.read_le::<u32>()?; Ok(Self { crypto_timeout, caps, max_packet_size, max_message_size }) } fn Request::to_wire(&self, w) { spdm::write_zeros(&mut w, 3)?; let ct_micros = self.crypto_timeout.as_micros(); if !ct_micros.is_power_of_two() { return Err(wire::Error::OutOfRange); } let ct_exp = 8 * mem::size_of_val(&ct_micros) as u32 - ct_micros.leading_zeros() - 1; w.write_le(ct_exp as u8)?; spdm::write_zeros(&mut w, 2)?; self.caps.to_wire(&mut w)?; w.write_le(self.max_packet_size)?; w.write_le(self.max_message_size)?; Ok(()) } #![fuzz_derives_if = any()] struct Response { pub crypto_timeout: Duration, #[cfg_attr(feature = "serde", serde(with = "crate::serde::bitflags"))] pub caps: BitFlags<Caps>, pub max_packet_size: u32, pub max_message_size: u32, } fn Response::from_wire(r, a) { spdm::expect_zeros(r, 3)?; let ct_exp = r.read_le::<u8>()?; let crypto_timeout = Duration::from_micros(1u64 << ct_exp); spdm::expect_zeros(r, 2)?; let caps = BitFlags::<Caps>::from_wire(r, a)?; let max_packet_size = r.read_le::<u32>()?; let max_message_size = r.read_le::<u32>()?; Ok(Self { crypto_timeout, caps, max_packet_size, max_message_size }) } fn Response::to_wire(&self, w) { spdm::write_zeros(&mut w, 3)?; let ct_micros = self.crypto_timeout.as_micros(); if !ct_micros.is_power_of_two() { return Err(wire::Error::OutOfRange); } let ct_exp = 8 * mem::size_of_val(&ct_micros) as u32 - ct_micros.leading_zeros() - 1; w.write_le(ct_exp as u8)?; spdm::write_zeros(&mut w, 2)?; self.caps.to_wire(&mut w)?; w.write_le(self.max_packet_size)?; w.write_le(self.max_message_size)?; Ok(()) } } #[cfg(feature = "arbitrary-derive")] use { crate::protocol::arbitrary_bitflags, libfuzzer_sys::arbitrary::{self, Arbitrary, Unstructured}, }; #[cfg(feature = "arbitrary-derive")] impl Arbitrary for GetCapsRequest { fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { Ok(Self { crypto_timeout: u.arbitrary()?, caps: arbitrary_bitflags(u)?, max_packet_size: u.arbitrary()?, max_message_size: u.arbitrary()?, }) } fn size_hint(_depth: usize) -> (usize, Option<usize>) {
(size, Some(size)) } } #[cfg(feature = "arbitrary-derive")] impl Arbitrary for GetCapsResponse { fn arbitrary(u: &mut Unstructured) -> arbitrary::Result<Self> { Ok(Self { crypto_timeout: u.arbitrary()?, caps: arbitrary_bitflags(u)?, max_packet_size: u.arbitrary()?, max_message_size: u.arbitrary()?, }) } fn size_hint(_depth: usize) -> (usize, Option<usize>) { let size = mem::size_of::<Duration>() + mem::size_of::<BitFlags<Caps>>() + mem::size_of::<u32>() * 2; (size, Some(size)) } } #[bitflags] #[repr(u32)] #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Caps { Cache = 1 << 0, Certs = 1 << 1, Challenge = 1 << 2, UnsignedMeasurements = 1 << 3, SignedMeasurements = 1 << 4, FreshMeasurements = 1 << 5, SessionEncryption = 1 << 6, SessionAuth = 1 << 7, MutualAuth = 1 << 8, KeyExchange = 1 << 9, PskWithoutContext = 1 << 10, PskWithContext = 1 << 11, Heartbeat = 1 << 13, KeyUpdate = 1 << 14, HandshakeInTheClear = 1 << 15, PubKeyProvisioned = 1 << 16, Chunking = 1 << 17, AliasCert = 1 << 18, } impl Caps { pub fn manticore() -> enumflags2::BitFlags<Self> { Self::Certs | Self::Challenge | Self::SignedMeasurements | Self::FreshMeasurements | Self::SessionEncryption | Self::KeyExchange | Self::Heartbeat | Self::AliasCert } } #[cfg(test)] mod test { use super::*; round_trip_test! { request_round_trip: { bytes: &[ 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0b01110110, 0b00100010, 0b00000100, 0b00000000, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, ], json: r#"{ "crypto_timeout": { "nanos": 4096000, "secs": 0 }, "caps": [ "Certs", "Challenge", "SignedMeasurements", "FreshMeasurements", "SessionEncryption", "KeyExchange", "Heartbeat", "AliasCert" ], "max_packet_size": 256, "max_message_size": 1024 }"#, value: GetCapsRequest { crypto_timeout: Duration::from_micros(4096), caps: Caps::manticore(), max_packet_size: 256, max_message_size: 1024, }, }, response_round_trip: { bytes: &[ 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0b01110110, 0b00100010, 0b00000100, 0b00000000, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, ], json: r#"{ "crypto_timeout": { "nanos": 4096000, "secs": 0 }, "caps": [ "Certs", "Challenge", "SignedMeasurements", "FreshMeasurements", "SessionEncryption", "KeyExchange", "Heartbeat", "AliasCert" ], "max_packet_size": 256, "max_message_size": 1024 }"#, value: GetCapsResponse { crypto_timeout: Duration::from_micros(4096), caps: Caps::manticore(), max_packet_size: 256, max_message_size: 1024, }, }, } }
let size = mem::size_of::<Duration>() + mem::size_of::<BitFlags<Caps>>() + mem::size_of::<u32>() * 2;
assignment_statement
[ { "content": "/// No-std helper for using as a `write!()` target.\n\nstruct ArrayBuf<const N: usize>([u8; N], usize);\n\n\n\nimpl<const N: usize> AsRef<str> for ArrayBuf<N> {\n\n fn as_ref(&self) -> &str {\n\n core::str::from_utf8(&self.0[..self.1]).unwrap()\n\n }\n\n}\n\n\n\nimpl<const N: usize> D...
Rust
kernel/src/allocator/tests.rs
rrybarczyk/osy
3328c26343d47c31e615df080d4769821567df15
mod align_util { use allocator::util::{align_up, align_down}; #[test] fn test_align_down() { assert_eq!(align_down(0, 2), 0); assert_eq!(align_down(0, 8), 0); assert_eq!(align_down(0, 1 << 5), 0); assert_eq!(align_down(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_down(1 << 20, 1 << 10), 1 << 20); assert_eq!(align_down(1 << 23, 1 << 4), 1 << 23); assert_eq!(align_down(1, 1 << 4), 0); assert_eq!(align_down(10, 1 << 4), 0); assert_eq!(align_down(0xFFFF, 1 << 2), 0xFFFC); assert_eq!(align_down(0xFFFF, 1 << 3), 0xFFF8); assert_eq!(align_down(0xFFFF, 1 << 4), 0xFFF0); assert_eq!(align_down(0xFFFF, 1 << 5), 0xFFE0); assert_eq!(align_down(0xAFFFF, 1 << 8), 0xAFF00); assert_eq!(align_down(0xAFFFF, 1 << 12), 0xAF000); assert_eq!(align_down(0xAFFFF, 1 << 16), 0xA0000); } #[test] fn test_align_up() { assert_eq!(align_up(0, 2), 0); assert_eq!(align_up(0, 8), 0); assert_eq!(align_up(0, 1 << 5), 0); assert_eq!(align_up(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_up(1 << 20, 1 << 10), 1 << 20); assert_eq!(align_up(1 << 23, 1 << 4), 1 << 23); assert_eq!(align_up(1, 1 << 4), 1 << 4); assert_eq!(align_up(10, 1 << 4), 1 << 4); assert_eq!(align_up(0xFFFF, 1 << 2), 0x10000); assert_eq!(align_up(0xFFFF, 1 << 3), 0x10000); assert_eq!(align_up(0xFFFF, 1 << 4), 0x10000); assert_eq!(align_up(0xAFFFF, 1 << 12), 0xB0000); assert_eq!(align_up(0xABCDAB, 1 << 2), 0xABCDAC); assert_eq!(align_up(0xABCDAB, 1 << 4), 0xABCDB0); assert_eq!(align_up(0xABCDAB, 1 << 8), 0xABCE00); assert_eq!(align_up(0xABCDAB, 1 << 12), 0xABD000); assert_eq!(align_up(0xABCDAB, 1 << 16), 0xAC0000); } #[test] #[should_panic] fn test_panics_1() { align_down(0xFFFF0000, 7); } #[test] #[should_panic] fn test_panics_2() { align_down(0xFFFF0000, 123); } #[test] #[should_panic] fn test_panics_3() { align_up(0xFFFF0000, 7); } #[test] #[should_panic] fn test_panics_4() { align_up(0xFFFF0000, 456); } } #[path = ""] mod allocator { #[allow(dead_code)] mod bump; #[allow(dead_code)] mod bin; use alloc::allocator::{AllocErr, Layout}; use alloc::raw_vec::RawVec; macro test_allocators { (@$kind:ident, $name:ident, $mem:expr, |$info:pat| $block:expr) => { #[test] fn $name() { let mem: RawVec<u8> = RawVec::with_capacity($mem); let start = mem.ptr() as usize; let end = start + $mem; let allocator = $kind::Allocator::new(start, end); let $info = (start, end, allocator); $block } }, ($bin:ident, $bump:ident, $mem:expr, |$info:pat| $block:expr) => ( test_allocators!(@bin, $bin, $mem, |$info| $block); test_allocators!(@bump, $bump, $mem, |$info| $block); ) } macro layout($size:expr, $align:expr) { Layout::from_size_align($size, $align).unwrap() } macro test_layouts($layouts:expr, $start:expr, $end:expr, $a:expr) { let (layouts, start, end, mut a) = ($layouts, $start, $end, $a); let mut pointers: Vec<(usize, Layout)> = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).unwrap() as usize; pointers.push((ptr, layout.clone())); } for &(ptr, ref layout) in &pointers { assert!(ptr >= start, "allocated {:x} after start ({:x})", ptr, start); assert!(ptr + layout.size() <= end, "{:x} + {:x} exceeds the bounds of {:x}", ptr, layout.size(), end); } pointers.sort_by_key(|&(ptr, _)| ptr); for window in pointers.windows(2) { let (&(ptr_a, ref layout_a), &(ptr_b, _)) = (&window[0], &window[1]); assert!(ptr_b - ptr_a >= layout_a.size(), "memory region {:x} - {:x} does not fit {}", ptr_a, ptr_b, layout_a.size()); } for &(ptr, ref layout) in &pointers { assert!(ptr % layout.align() == 0, "{:x} is not aligned to {}", ptr, layout.align()); } } test_allocators!(bin_exhausted, bump_exhausted, 128, |(_, _, mut a)| { let e = a.alloc(layout!(1024, 128)).unwrap_err(); assert_eq!(e, AllocErr::Exhausted { request: layout!(1024, 128) }) }); test_allocators!(bin_alloc, bump_alloc, 8 * (1 << 20), |(start, end, a)| { let layouts = [ layout!(16, 16), layout!(16, 128), layout!(16, 256), layout!(4, 256), layout!(1024, 16), layout!(1024, 4), layout!(1024, 128), layout!(2048, 8), layout!(2049, 8), layout!(2050, 8), layout!(4095, 4), layout!(4096, 4), layout!(4096, 4), layout!(4096, 4096), layout!(16, 4096), layout!(8192, 4096), layout!(8192, 8), layout!(8192, 8), ]; test_layouts!(layouts, start, end, a); }); test_allocators!(bin_alloc_2, bump_alloc_2, 16 * (1 << 20), |(start, end, a)| { let mut layouts = vec![]; for i in 1..1024 { layouts.push(layout!(i * 8, 16)); } test_layouts!(layouts, start, end, a); }); fn scribble(ptr: *mut u8, size: usize) { unsafe { ::std::ptr::write_bytes(ptr, 0xAF, size); } } test_allocators!(bin_dealloc_s, bump_dealloc_s, 4096, |(_, _, mut a)| { let layouts = [ layout!(16, 16), layout!(16, 128), layout!(16, 256), ]; let mut pointers: Vec<(usize, Layout)> = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).unwrap(); scribble(ptr, layout.size()); pointers.push((ptr as usize, layout.clone())); } for (ptr, layout) in pointers { scribble(ptr as *mut u8, layout.size()); a.dealloc(ptr as *mut u8, layout); } }); test_allocators!(@bin, bin_dealloc_1, 65536, |(_, _, mut a)| { let layouts = [ layout!(16, 16), layout!(16, 256), layout!(32, 4), layout!(32, 1024), layout!(4, 1024), layout!(4, 32), ]; for (i, layout) in layouts.iter().enumerate() { let mut ptrs = vec![]; for _ in 0..(25 + i * 2) { let ptr = a.alloc(layout.clone()).expect("allocation"); assert!(ptr as usize % layout.align() == 0, "{:x} is not aligned to {}", ptr as usize, layout.align()); scribble(ptr, layout.size()); ptrs.push((ptr, layout.clone())); } for (ptr, layout) in ptrs { a.dealloc(ptr, layout); } } for _ in 0..500 { for layout in &layouts { let ptr = a.alloc(layout.clone()).expect("allocation"); scribble(ptr, layout.size()); assert!(ptr as usize % layout.align() == 0, "{:x} is not aligned to {}", ptr as usize, layout.align()); a.dealloc(ptr, layout.clone()); } } }); test_allocators!(@bin, bin_dealloc_2, 8192, |(_, _, mut a)| { let layouts = [ layout!(3072, 16), layout!(512, 32), ]; for _ in 0..1000 { let mut ptrs = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).expect("allocation"); scribble(ptr, layout.size()); ptrs.push(ptr as usize); } for (layout, ptr) in layouts.iter().zip(ptrs.into_iter()) { scribble(ptr as *mut u8, layout.size()); a.dealloc(ptr as *mut u8, layout.clone()); } } }); } mod linked_list { use allocator::linked_list::LinkedList; #[test] fn example_1() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); } assert_eq!(list.peek(), Some(address_2)); assert_eq!(list.pop(), Some(address_2)); assert_eq!(list.pop(), Some(address_1)); assert_eq!(list.pop(), None); } #[test] fn example_2() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let address_3 = (&mut (3 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); list.push(address_3); } for node in list.iter_mut() { if node.value() == address_2 { node.pop(); } } assert_eq!(list.pop(), Some(address_3)); assert_eq!(list.pop(), Some(address_1)); assert_eq!(list.pop(), None); } #[test] fn example_3() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let address_3 = (&mut (3 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); list.push(address_3); } for node in list.iter_mut() { if node.value() == address_2 { node.pop(); } } { let mut iter = list.iter(); assert_eq!(iter.next(), Some(address_3)); assert_eq!(iter.next(), Some(address_1)); assert_eq!(iter.next(), None); } for node in list.iter_mut() { if node.value() == address_1 { node.pop(); } } { let mut iter = list.iter(); assert_eq!(iter.next(), Some(address_3)); assert_eq!(iter.next(), None); } for node in list.iter_mut() { if node.value() == address_3 { node.pop(); } } let mut iter = list.iter(); assert_eq!(iter.next(), None); } }
mod align_util { use allocator::util::{align_up, align_down}; #[test] fn test_align_down() { a
12), 0xAF000); assert_eq!(align_down(0xAFFFF, 1 << 16), 0xA0000); } #[test] fn test_align_up() { assert_eq!(align_up(0, 2), 0); assert_eq!(align_up(0, 8), 0); assert_eq!(align_up(0, 1 << 5), 0); assert_eq!(align_up(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_up(1 << 20, 1 << 10), 1 << 20); assert_eq!(align_up(1 << 23, 1 << 4), 1 << 23); assert_eq!(align_up(1, 1 << 4), 1 << 4); assert_eq!(align_up(10, 1 << 4), 1 << 4); assert_eq!(align_up(0xFFFF, 1 << 2), 0x10000); assert_eq!(align_up(0xFFFF, 1 << 3), 0x10000); assert_eq!(align_up(0xFFFF, 1 << 4), 0x10000); assert_eq!(align_up(0xAFFFF, 1 << 12), 0xB0000); assert_eq!(align_up(0xABCDAB, 1 << 2), 0xABCDAC); assert_eq!(align_up(0xABCDAB, 1 << 4), 0xABCDB0); assert_eq!(align_up(0xABCDAB, 1 << 8), 0xABCE00); assert_eq!(align_up(0xABCDAB, 1 << 12), 0xABD000); assert_eq!(align_up(0xABCDAB, 1 << 16), 0xAC0000); } #[test] #[should_panic] fn test_panics_1() { align_down(0xFFFF0000, 7); } #[test] #[should_panic] fn test_panics_2() { align_down(0xFFFF0000, 123); } #[test] #[should_panic] fn test_panics_3() { align_up(0xFFFF0000, 7); } #[test] #[should_panic] fn test_panics_4() { align_up(0xFFFF0000, 456); } } #[path = ""] mod allocator { #[allow(dead_code)] mod bump; #[allow(dead_code)] mod bin; use alloc::allocator::{AllocErr, Layout}; use alloc::raw_vec::RawVec; macro test_allocators { (@$kind:ident, $name:ident, $mem:expr, |$info:pat| $block:expr) => { #[test] fn $name() { let mem: RawVec<u8> = RawVec::with_capacity($mem); let start = mem.ptr() as usize; let end = start + $mem; let allocator = $kind::Allocator::new(start, end); let $info = (start, end, allocator); $block } }, ($bin:ident, $bump:ident, $mem:expr, |$info:pat| $block:expr) => ( test_allocators!(@bin, $bin, $mem, |$info| $block); test_allocators!(@bump, $bump, $mem, |$info| $block); ) } macro layout($size:expr, $align:expr) { Layout::from_size_align($size, $align).unwrap() } macro test_layouts($layouts:expr, $start:expr, $end:expr, $a:expr) { let (layouts, start, end, mut a) = ($layouts, $start, $end, $a); let mut pointers: Vec<(usize, Layout)> = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).unwrap() as usize; pointers.push((ptr, layout.clone())); } for &(ptr, ref layout) in &pointers { assert!(ptr >= start, "allocated {:x} after start ({:x})", ptr, start); assert!(ptr + layout.size() <= end, "{:x} + {:x} exceeds the bounds of {:x}", ptr, layout.size(), end); } pointers.sort_by_key(|&(ptr, _)| ptr); for window in pointers.windows(2) { let (&(ptr_a, ref layout_a), &(ptr_b, _)) = (&window[0], &window[1]); assert!(ptr_b - ptr_a >= layout_a.size(), "memory region {:x} - {:x} does not fit {}", ptr_a, ptr_b, layout_a.size()); } for &(ptr, ref layout) in &pointers { assert!(ptr % layout.align() == 0, "{:x} is not aligned to {}", ptr, layout.align()); } } test_allocators!(bin_exhausted, bump_exhausted, 128, |(_, _, mut a)| { let e = a.alloc(layout!(1024, 128)).unwrap_err(); assert_eq!(e, AllocErr::Exhausted { request: layout!(1024, 128) }) }); test_allocators!(bin_alloc, bump_alloc, 8 * (1 << 20), |(start, end, a)| { let layouts = [ layout!(16, 16), layout!(16, 128), layout!(16, 256), layout!(4, 256), layout!(1024, 16), layout!(1024, 4), layout!(1024, 128), layout!(2048, 8), layout!(2049, 8), layout!(2050, 8), layout!(4095, 4), layout!(4096, 4), layout!(4096, 4), layout!(4096, 4096), layout!(16, 4096), layout!(8192, 4096), layout!(8192, 8), layout!(8192, 8), ]; test_layouts!(layouts, start, end, a); }); test_allocators!(bin_alloc_2, bump_alloc_2, 16 * (1 << 20), |(start, end, a)| { let mut layouts = vec![]; for i in 1..1024 { layouts.push(layout!(i * 8, 16)); } test_layouts!(layouts, start, end, a); }); fn scribble(ptr: *mut u8, size: usize) { unsafe { ::std::ptr::write_bytes(ptr, 0xAF, size); } } test_allocators!(bin_dealloc_s, bump_dealloc_s, 4096, |(_, _, mut a)| { let layouts = [ layout!(16, 16), layout!(16, 128), layout!(16, 256), ]; let mut pointers: Vec<(usize, Layout)> = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).unwrap(); scribble(ptr, layout.size()); pointers.push((ptr as usize, layout.clone())); } for (ptr, layout) in pointers { scribble(ptr as *mut u8, layout.size()); a.dealloc(ptr as *mut u8, layout); } }); test_allocators!(@bin, bin_dealloc_1, 65536, |(_, _, mut a)| { let layouts = [ layout!(16, 16), layout!(16, 256), layout!(32, 4), layout!(32, 1024), layout!(4, 1024), layout!(4, 32), ]; for (i, layout) in layouts.iter().enumerate() { let mut ptrs = vec![]; for _ in 0..(25 + i * 2) { let ptr = a.alloc(layout.clone()).expect("allocation"); assert!(ptr as usize % layout.align() == 0, "{:x} is not aligned to {}", ptr as usize, layout.align()); scribble(ptr, layout.size()); ptrs.push((ptr, layout.clone())); } for (ptr, layout) in ptrs { a.dealloc(ptr, layout); } } for _ in 0..500 { for layout in &layouts { let ptr = a.alloc(layout.clone()).expect("allocation"); scribble(ptr, layout.size()); assert!(ptr as usize % layout.align() == 0, "{:x} is not aligned to {}", ptr as usize, layout.align()); a.dealloc(ptr, layout.clone()); } } }); test_allocators!(@bin, bin_dealloc_2, 8192, |(_, _, mut a)| { let layouts = [ layout!(3072, 16), layout!(512, 32), ]; for _ in 0..1000 { let mut ptrs = vec![]; for layout in &layouts { let ptr = a.alloc(layout.clone()).expect("allocation"); scribble(ptr, layout.size()); ptrs.push(ptr as usize); } for (layout, ptr) in layouts.iter().zip(ptrs.into_iter()) { scribble(ptr as *mut u8, layout.size()); a.dealloc(ptr as *mut u8, layout.clone()); } } }); } mod linked_list { use allocator::linked_list::LinkedList; #[test] fn example_1() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); } assert_eq!(list.peek(), Some(address_2)); assert_eq!(list.pop(), Some(address_2)); assert_eq!(list.pop(), Some(address_1)); assert_eq!(list.pop(), None); } #[test] fn example_2() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let address_3 = (&mut (3 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); list.push(address_3); } for node in list.iter_mut() { if node.value() == address_2 { node.pop(); } } assert_eq!(list.pop(), Some(address_3)); assert_eq!(list.pop(), Some(address_1)); assert_eq!(list.pop(), None); } #[test] fn example_3() { let address_1 = (&mut (1 as usize)) as *mut usize; let address_2 = (&mut (2 as usize)) as *mut usize; let address_3 = (&mut (3 as usize)) as *mut usize; let mut list = LinkedList::new(); unsafe { list.push(address_1); list.push(address_2); list.push(address_3); } for node in list.iter_mut() { if node.value() == address_2 { node.pop(); } } { let mut iter = list.iter(); assert_eq!(iter.next(), Some(address_3)); assert_eq!(iter.next(), Some(address_1)); assert_eq!(iter.next(), None); } for node in list.iter_mut() { if node.value() == address_1 { node.pop(); } } { let mut iter = list.iter(); assert_eq!(iter.next(), Some(address_3)); assert_eq!(iter.next(), None); } for node in list.iter_mut() { if node.value() == address_3 { node.pop(); } } let mut iter = list.iter(); assert_eq!(iter.next(), None); } }
ssert_eq!(align_down(0, 2), 0); assert_eq!(align_down(0, 8), 0); assert_eq!(align_down(0, 1 << 5), 0); assert_eq!(align_down(1 << 10, 1 << 10), 1 << 10); assert_eq!(align_down(1 << 20, 1 << 10), 1 << 20); assert_eq!(align_down(1 << 23, 1 << 4), 1 << 23); assert_eq!(align_down(1, 1 << 4), 0); assert_eq!(align_down(10, 1 << 4), 0); assert_eq!(align_down(0xFFFF, 1 << 2), 0xFFFC); assert_eq!(align_down(0xFFFF, 1 << 3), 0xFFF8); assert_eq!(align_down(0xFFFF, 1 << 4), 0xFFF0); assert_eq!(align_down(0xFFFF, 1 << 5), 0xFFE0); assert_eq!(align_down(0xAFFFF, 1 << 8), 0xAFF00); assert_eq!(align_down(0xAFFFF, 1 <<
function_block-random_span
[ { "content": "pub fn next_test_ip4() -> SocketAddr {\n\n let port = PORT.fetch_add(1, Ordering::SeqCst) as u16 + base_port();\n\n SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))\n\n}\n\n\n", "file_path": "std/src/net/test.rs", "rank": 0, "score": 132764.1280292329 }, {...
Rust
src/types/fetch_attributes.rs
FelixPodint/imap-codec
48019304520dcaade13fc94a5f359d0a450b7a79
use std::num::NonZeroU32; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::types::{ body::BodyStructure, core::NString, datetime::MyDateTime, envelope::Envelope, flag::Flag, section::Section, }; #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Macro { All, Fast, Full, } impl Macro { pub fn expand(&self) -> Vec<FetchAttribute> { use FetchAttribute::*; match self { Self::All => vec![Flags, InternalDate, Rfc822Size, Envelope], Self::Fast => vec![Flags, InternalDate, Rfc822Size], Self::Full => vec![Flags, InternalDate, Rfc822Size, Envelope, Body], } } } #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MacroOrFetchAttributes { Macro(Macro), FetchAttributes(Vec<FetchAttribute>), } impl From<Macro> for MacroOrFetchAttributes { fn from(m: Macro) -> Self { MacroOrFetchAttributes::Macro(m) } } impl From<Vec<FetchAttribute>> for MacroOrFetchAttributes { fn from(attributes: Vec<FetchAttribute>) -> Self { MacroOrFetchAttributes::FetchAttributes(attributes) } } #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum FetchAttribute { Body, BodyExt { section: Option<Section>, partial: Option<(u32, NonZeroU32)>, peek: bool, }, BodyStructure, Envelope, Flags, InternalDate, Rfc822, Rfc822Header, Rfc822Size, Rfc822Text, Uid, } #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum FetchAttributeValue { Body(BodyStructure), BodyExt { section: Option<Section>, origin: Option<u32>, data: NString, }, BodyStructure(BodyStructure), Envelope(Envelope), Flags(Vec<Flag>), InternalDate(MyDateTime), Rfc822(NString), Rfc822Header(NString), Rfc822Size(u32), Rfc822Text(NString), Uid(NonZeroU32), }
use std::num::NonZeroU32; #[cfg(feature = "arbitrary")] use arbitrary::Arbitrary; #[cfg(feature = "serdex")] use serde::{Deserialize, Serialize}; use crate::types::{ body::BodyStructure, core::NString, datetime::MyDateTime, envelope::Envelope, flag::Flag, section::Section, }; #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Macro { All, Fast, Full, } impl Macro { pub fn expand(&self) -> Vec<FetchAttribute> { use FetchAttribut
} #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MacroOrFetchAttributes { Macro(Macro), FetchAttributes(Vec<FetchAttribute>), } impl From<Macro> for MacroOrFetchAttributes { fn from(m: Macro) -> Self { MacroOrFetchAttributes::Macro(m) } } impl From<Vec<FetchAttribute>> for MacroOrFetchAttributes { fn from(attributes: Vec<FetchAttribute>) -> Self { MacroOrFetchAttributes::FetchAttributes(attributes) } } #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum FetchAttribute { Body, BodyExt { section: Option<Section>, partial: Option<(u32, NonZeroU32)>, peek: bool, }, BodyStructure, Envelope, Flags, InternalDate, Rfc822, Rfc822Header, Rfc822Size, Rfc822Text, Uid, } #[cfg_attr(feature = "arbitrary", derive(Arbitrary))] #[cfg_attr(feature = "serdex", derive(Serialize, Deserialize))] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum FetchAttributeValue { Body(BodyStructure), BodyExt { section: Option<Section>, origin: Option<u32>, data: NString, }, BodyStructure(BodyStructure), Envelope(Envelope), Flags(Vec<Flag>), InternalDate(MyDateTime), Rfc822(NString), Rfc822Header(NString), Rfc822Size(u32), Rfc822Text(NString), Uid(NonZeroU32), }
e::*; match self { Self::All => vec![Flags, InternalDate, Rfc822Size, Envelope], Self::Fast => vec![Flags, InternalDate, Rfc822Size], Self::Full => vec![Flags, InternalDate, Rfc822Size, Envelope, Body], } }
function_block-function_prefixed
[ { "content": "/// body = \"(\" (body-type-1part / body-type-mpart) \")\"\n\n///\n\n/// Note: This parser is recursively defined. Thus, in order to not overflow the stack,\n\n/// it is needed to limit how may recursions are allowed. (8 should suffice).\n\npub fn body(remaining_recursions: usize) -> impl Fn(&[u8]...
Rust
rsocket/src/frame/setup.rs
sofkyle/rsocket-rust
136fbc70c006c53ee3e3839aa16e97eb7cf845da
use super::{Body, Frame, PayloadSupport, Version, FLAG_METADATA, FLAG_RESUME}; use crate::utils::{RSocketResult, Writeable, DEFAULT_MIME_TYPE}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::time::Duration; #[derive(Debug, PartialEq)] pub struct Setup { version: Version, keepalive: u32, lifetime: u32, token: Option<Bytes>, mime_metadata: String, mime_data: String, metadata: Option<Bytes>, data: Option<Bytes>, } impl Writeable for Setup { fn len(&self) -> usize { let mut n: usize = 12; n += match &self.token { Some(v) => 2 + v.len(), None => 0, }; n += 2 + self.mime_metadata.len() + self.mime_data.len(); n += PayloadSupport::len(&self.metadata, &self.data); n } fn write_to(&self, bf: &mut BytesMut) { self.version.write_to(bf); bf.put_u32(self.keepalive); bf.put_u32(self.lifetime); if let Some(b) = &self.token { bf.put_u16(b.len() as u16); bf.put(b.bytes()); } bf.put_u8(self.mime_metadata.len() as u8); bf.put(Bytes::from(self.mime_metadata.clone())); bf.put_u8(self.mime_data.len() as u8); bf.put(Bytes::from(self.mime_data.clone())); PayloadSupport::write(bf, self.get_metadata(), self.get_data()); } } impl Setup { pub fn decode(flag: u16, b: &mut BytesMut) -> RSocketResult<Setup> { let major = b.get_u16(); let minor = b.get_u16(); let keepalive = b.get_u32(); let lifetime = b.get_u32(); let token: Option<Bytes> = if flag & FLAG_RESUME != 0 { let l = b.get_u16(); Some(b.split_to(l as usize).to_bytes()) } else { None }; let mut len_mime: usize = b[0] as usize; b.advance(1); let mime_metadata = b.split_to(len_mime); len_mime = b[0] as usize; b.advance(1); let mime_data = b.split_to(len_mime); let (metadata, data) = PayloadSupport::read(flag, b); Ok(Setup { version: Version::new(major, minor), keepalive, lifetime, token, mime_metadata: String::from_utf8(mime_metadata.to_vec()).unwrap(), mime_data: String::from_utf8(mime_data.to_vec()).unwrap(), metadata, data, }) } pub fn builder(stream_id: u32, flag: u16) -> SetupBuilder { SetupBuilder::new(stream_id, flag) } pub fn get_version(&self) -> Version { self.version } pub fn get_keepalive(&self) -> Duration { Duration::from_millis(u64::from(self.keepalive)) } pub fn get_lifetime(&self) -> Duration { Duration::from_millis(u64::from(self.lifetime)) } pub fn get_token(&self) -> Option<Bytes> { self.token.clone() } pub fn get_mime_metadata(&self) -> &String { &self.mime_metadata } pub fn get_mime_data(&self) -> &String { &self.mime_data } pub fn get_metadata(&self) -> &Option<Bytes> { &self.metadata } pub fn get_data(&self) -> &Option<Bytes> { &self.data } pub fn split(self) -> (Option<Bytes>, Option<Bytes>) { (self.data, self.metadata) } } pub struct SetupBuilder { stream_id: u32, flag: u16, value: Setup, } impl SetupBuilder { fn new(stream_id: u32, flag: u16) -> SetupBuilder { SetupBuilder { stream_id, flag, value: Setup { version: Version::default(), keepalive: 30_000, lifetime: 90_000, token: None, mime_metadata: String::from(DEFAULT_MIME_TYPE), mime_data: String::from(DEFAULT_MIME_TYPE), metadata: None, data: None, }, } } pub fn build(self) -> Frame { Frame::new(self.stream_id, Body::Setup(self.value), self.flag) } pub fn set_data(mut self, bs: Bytes) -> Self { self.value.data = Some(bs); self } pub fn set_metadata(mut self, bs: Bytes) -> Self { self.flag |= FLAG_METADATA; self.value.metadata = Some(bs); self } pub fn set_version(mut self, major: u16, minor: u16) -> Self { self.value.version = Version::new(major, minor); self } pub fn set_keepalive(mut self, duration: Duration) -> Self { self.value.keepalive = duration.as_millis() as u32; self } pub fn set_lifetime(mut self, duration: Duration) -> Self { self.value.lifetime = duration.as_millis() as u32; self } pub fn set_token(mut self, token: Bytes) -> Self { self.value.token = Some(token); self.flag |= FLAG_RESUME; self } pub fn set_mime_metadata(mut self, mime: &str) -> Self { if mime.len() > 256 { panic!("maximum mime length is 256"); } self.value.mime_metadata = String::from(mime); self } pub fn set_mime_data(mut self, mime: &str) -> Self { if mime.len() > 256 { panic!("maximum mime length is 256"); } self.value.mime_data = String::from(mime); self } }
use super::{Body, Frame, PayloadSupport, Version, FLAG_METADATA, FLAG_RESUME}; use crate::utils::{RSocketResult, Writeable, DEFAULT_MIME_TYPE}; use bytes::{Buf, BufMut, Bytes, BytesMut}; use std::time::Duration; #[derive(Debug, PartialEq)] pub struct Setup { version: Version, keepalive: u32, lifetime: u32, token: Option<Bytes>, mime_metadata: String, mime_data: String, metadata: Option<Bytes>, data: Option<Bytes>, } impl Writeable for Setup { fn len(&self) -> usize { let mut n: usize = 12; n += match &self.token { Some(v) => 2 + v.len(), None => 0, }; n += 2 + self.mime_metadata.len() + self.mime_data.len(); n += PayloadSupport::len(&self.metadata, &self.data); n } fn write_to(&self, bf: &mut BytesMut) { self.version.write_to(bf); bf.put_u32(self.keepalive); bf.put_u32(self.lifetime); if let Some(b) = &self.token { bf.put_u16(b.len() as u16); bf.put(b.bytes()); } bf.put_u8(self.mime_metadata.len() as u8); bf.put(Bytes::from(self.mime_metadata.clone())); bf.put_u8(self.mime_data.len() as u8); bf.put(Bytes::from(self.mime_data.clone())); PayloadSupport::write(bf, self.get_metadata(), self.get_data()); } } impl Setup { pub fn decode(flag: u16, b: &mut BytesMut) -> RSocketResult<Setup> { let major = b.get_u16(); let minor = b.get_u16(); let keepalive = b.get_u32(); let lifetime = b.get_u32(); let token: Option<Bytes> = if flag & FLAG_RESUME != 0 { let l = b.get_u16(); Some(b.split_to(l as usize).to_bytes()) } else { None }; let mut len_mime: usize = b[0] as usize; b.advance(1); let mime_metadata = b.split_to(len_mime); len_mime = b[0] as usize; b.advance(1); let mime_data = b.split_to(len_mime); let (metadata, data) = PayloadSupport::read(flag, b);
} pub fn builder(stream_id: u32, flag: u16) -> SetupBuilder { SetupBuilder::new(stream_id, flag) } pub fn get_version(&self) -> Version { self.version } pub fn get_keepalive(&self) -> Duration { Duration::from_millis(u64::from(self.keepalive)) } pub fn get_lifetime(&self) -> Duration { Duration::from_millis(u64::from(self.lifetime)) } pub fn get_token(&self) -> Option<Bytes> { self.token.clone() } pub fn get_mime_metadata(&self) -> &String { &self.mime_metadata } pub fn get_mime_data(&self) -> &String { &self.mime_data } pub fn get_metadata(&self) -> &Option<Bytes> { &self.metadata } pub fn get_data(&self) -> &Option<Bytes> { &self.data } pub fn split(self) -> (Option<Bytes>, Option<Bytes>) { (self.data, self.metadata) } } pub struct SetupBuilder { stream_id: u32, flag: u16, value: Setup, } impl SetupBuilder { fn new(stream_id: u32, flag: u16) -> SetupBuilder { SetupBuilder { stream_id, flag, value: Setup { version: Version::default(), keepalive: 30_000, lifetime: 90_000, token: None, mime_metadata: String::from(DEFAULT_MIME_TYPE), mime_data: String::from(DEFAULT_MIME_TYPE), metadata: None, data: None, }, } } pub fn build(self) -> Frame { Frame::new(self.stream_id, Body::Setup(self.value), self.flag) } pub fn set_data(mut self, bs: Bytes) -> Self { self.value.data = Some(bs); self } pub fn set_metadata(mut self, bs: Bytes) -> Self { self.flag |= FLAG_METADATA; self.value.metadata = Some(bs); self } pub fn set_version(mut self, major: u16, minor: u16) -> Self { self.value.version = Version::new(major, minor); self } pub fn set_keepalive(mut self, duration: Duration) -> Self { self.value.keepalive = duration.as_millis() as u32; self } pub fn set_lifetime(mut self, duration: Duration) -> Self { self.value.lifetime = duration.as_millis() as u32; self } pub fn set_token(mut self, token: Bytes) -> Self { self.value.token = Some(token); self.flag |= FLAG_RESUME; self } pub fn set_mime_metadata(mut self, mime: &str) -> Self { if mime.len() > 256 { panic!("maximum mime length is 256"); } self.value.mime_metadata = String::from(mime); self } pub fn set_mime_data(mut self, mime: &str) -> Self { if mime.len() > 256 { panic!("maximum mime length is 256"); } self.value.mime_data = String::from(mime); self } }
Ok(Setup { version: Version::new(major, minor), keepalive, lifetime, token, mime_metadata: String::from_utf8(mime_metadata.to_vec()).unwrap(), mime_data: String::from_utf8(mime_data.to_vec()).unwrap(), metadata, data, })
call_expression
[ { "content": "#[inline]\n\nfn to_frame_type(body: &Body) -> u16 {\n\n match body {\n\n Body::Setup(_) => TYPE_SETUP,\n\n Body::Lease(_) => TYPE_LEASE,\n\n Body::Keepalive(_) => TYPE_KEEPALIVE,\n\n Body::RequestResponse(_) => TYPE_REQUEST_RESPONSE,\n\n Body::RequestFNF(_) =>...
Rust
src/pka/compare.rs
jeandudey/cc13x2-rs
215918099301ec75e9dfad531f5cf46e13077a39
#[doc = "Reader of register COMPARE"] pub type R = crate::R<u32, super::COMPARE>; #[doc = "Writer for register COMPARE"] pub type W = crate::W<u32, super::COMPARE>; #[doc = "Register COMPARE `reset()`'s with value 0x01"] impl crate::ResetValue for super::COMPARE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x01 } } #[doc = "Reader of field `RESERVED3`"] pub type RESERVED3_R = crate::R<u32, u32>; #[doc = "Write proxy for field `RESERVED3`"] pub struct RESERVED3_W<'a> { w: &'a mut W, } impl<'a> RESERVED3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1fff_ffff << 3)) | (((value as u32) & 0x1fff_ffff) << 3); self.w } } #[doc = "Reader of field `A_GREATER_THAN_B`"] pub type A_GREATER_THAN_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_GREATER_THAN_B`"] pub struct A_GREATER_THAN_B_W<'a> { w: &'a mut W, } impl<'a> A_GREATER_THAN_B_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `A_LESS_THAN_B`"] pub type A_LESS_THAN_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_LESS_THAN_B`"] pub struct A_LESS_THAN_B_W<'a> { w: &'a mut W, } impl<'a> A_LESS_THAN_B_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `A_EQUALS_B`"] pub type A_EQUALS_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_EQUALS_B`"] pub struct A_EQUALS_B_W<'a> { w: &'a mut W, } impl<'a> A_EQUALS_B_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 3:31 - 31:3\\] Ignore on read"] #[inline(always)] pub fn reserved3(&self) -> RESERVED3_R { RESERVED3_R::new(((self.bits >> 3) & 0x1fff_ffff) as u32) } #[doc = "Bit 2 - 2:2\\] Vector_A is greater than Vector_B"] #[inline(always)] pub fn a_greater_than_b(&self) -> A_GREATER_THAN_B_R { A_GREATER_THAN_B_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - 1:1\\] Vector_A is less than Vector_B"] #[inline(always)] pub fn a_less_than_b(&self) -> A_LESS_THAN_B_R { A_LESS_THAN_B_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - 0:0\\] Vector_A is equal to Vector_B"] #[inline(always)] pub fn a_equals_b(&self) -> A_EQUALS_B_R { A_EQUALS_B_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bits 3:31 - 31:3\\] Ignore on read"] #[inline(always)] pub fn reserved3(&mut self) -> RESERVED3_W { RESERVED3_W { w: self } } #[doc = "Bit 2 - 2:2\\] Vector_A is greater than Vector_B"] #[inline(always)] pub fn a_greater_than_b(&mut self) -> A_GREATER_THAN_B_W { A_GREATER_THAN_B_W { w: self } } #[doc = "Bit 1 - 1:1\\] Vector_A is less than Vector_B"] #[inline(always)] pub fn a_less_than_b(&mut self) -> A_LESS_THAN_B_W { A_LESS_THAN_B_W { w: self } } #[doc = "Bit 0 - 0:0\\] Vector_A is equal to Vector_B"] #[inline(always)] pub fn a_equals_b(&mut self) -> A_EQUALS_B_W { A_EQUALS_B_W { w: self } } }
#[doc = "Reader of register COMPARE"] pub type R = crate::R<u32, super::COMPARE>; #[doc = "Writer for register COMPARE"] pub type W = crate::W<u32, super::COMPARE>; #[doc = "Register COMPARE `reset()`'s with value 0x01"] impl crate::ResetValue for super::COMPARE { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x01 } } #[doc = "Reader of field `RESERVED3`"] pub type RESERVED3_R = crate::R<u32, u32>; #[doc = "Write proxy for field `RESERVED3`"] pub struct RESERVED3_W<'a> { w: &'a mut W, } impl<'a> RESERVED3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1fff_ffff << 3)) | (((value as u32) & 0x1fff_ffff) << 3); self.w } } #[doc = "Reader of field `A_GREATER_THAN_B`"] pub type A_GREATER_THAN_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_GREATER_THAN_B`"] pub struct A_GREATER_THAN_B_W<'a> { w: &'a mut W, } impl<'a> A_GREATER_THAN_B_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Reader of field `A_LESS_THAN_B`"] pub type A_LESS_THAN_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_LESS_THAN_B`"] pub struct A_LESS_THAN_B_W<'a> { w: &'a mut W, } impl<'a> A_LESS_THAN_B_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `A_EQUALS_B`"] pub type A_EQUALS_B_R = crate::R<bool, bool>; #[doc = "Write proxy for field `A_EQUALS_B`"] pub struct A_EQUALS_B_W<'a> { w: &'a mut W, } impl<'a> A_EQUALS_B_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
ls_b(&mut self) -> A_EQUALS_B_W { A_EQUALS_B_W { w: self } } }
mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bits 3:31 - 31:3\\] Ignore on read"] #[inline(always)] pub fn reserved3(&self) -> RESERVED3_R { RESERVED3_R::new(((self.bits >> 3) & 0x1fff_ffff) as u32) } #[doc = "Bit 2 - 2:2\\] Vector_A is greater than Vector_B"] #[inline(always)] pub fn a_greater_than_b(&self) -> A_GREATER_THAN_B_R { A_GREATER_THAN_B_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - 1:1\\] Vector_A is less than Vector_B"] #[inline(always)] pub fn a_less_than_b(&self) -> A_LESS_THAN_B_R { A_LESS_THAN_B_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - 0:0\\] Vector_A is equal to Vector_B"] #[inline(always)] pub fn a_equals_b(&self) -> A_EQUALS_B_R { A_EQUALS_B_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bits 3:31 - 31:3\\] Ignore on read"] #[inline(always)] pub fn reserved3(&mut self) -> RESERVED3_W { RESERVED3_W { w: self } } #[doc = "Bit 2 - 2:2\\] Vector_A is greater than Vector_B"] #[inline(always)] pub fn a_greater_than_b(&mut self) -> A_GREATER_THAN_B_W { A_GREATER_THAN_B_W { w: self } } #[doc = "Bit 1 - 1:1\\] Vector_A is less than Vector_B"] #[inline(always)] pub fn a_less_than_b(&mut self) -> A_LESS_THAN_B_W { A_LESS_THAN_B_W { w: self } } #[doc = "Bit 0 - 0:0\\] Vector_A is equal to Vector_B"] #[inline(always)] pub fn a_equa
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 = \"Res...
Rust
src/p2p/session.rs
placefortea/teatree
7a56755a428fe63ee753df67a7c71d8f668e17ec
use bytes::{BufMut, BytesMut}; use futures::stream::SplitSink; use futures::Sink; use std::collections::HashMap; use std::net::SocketAddr; use tokio::codec::BytesCodec; use tokio::net::UdpFramed; use crate::actor::prelude::*; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::traits::actor::P2PBridgeActor; use super::codec::{P2PBody, P2PHead, HEAD_LENGTH}; use super::content::P2PContent; use super::p2p::P2PActor; #[derive(Clone)] pub struct P2PMessage(pub P2PHead, pub P2PContent, pub SocketAddr); impl Message for P2PMessage { type Result = (); } #[derive(Clone)] pub struct CodecMessage(pub BytesMut, pub SocketAddr); impl Message for CodecMessage { type Result = (); } #[derive(Clone)] pub(crate) struct P2PAddrMessage<A: P2PBridgeActor>(pub Addr<P2PActor<A>>); impl<A: P2PBridgeActor> Message for P2PAddrMessage<A> { type Result = (); } pub struct P2PSessionActor<A: P2PBridgeActor> { pub sinks: Vec<SplitSink<UdpFramed<BytesCodec>>>, pub p2p_addr: Option<Addr<P2PActor<A>>>, pub waitings: Vec<(P2PHead, P2PBody, SocketAddr)>, pub receivings: HashMap<[u8; 8], Vec<u8>>, } impl<A: P2PBridgeActor> P2PSessionActor<A> { fn send_udp( &mut self, mut bytes: Vec<u8>, mut prev_sign: [u8; 8], self_sign: [u8; 8], socket: SocketAddr, ctx: &mut Context<Self>, ) { let mut send_bytes = vec![]; let (mut now, next, next_sign) = if bytes.len() > 65400 { let now = bytes.drain(0..65400).as_slice().into(); (now, bytes, rand::random()) } else { (bytes, vec![], self_sign.clone()) }; send_bytes.extend_from_slice(&mut prev_sign); send_bytes.extend_from_slice(&mut self_sign.clone()); send_bytes.extend_from_slice(&mut next_sign.clone()); send_bytes.append(&mut now); let mut dst = BytesMut::new(); dst.reserve(send_bytes.len()); dst.put(send_bytes); self.sinks.pop().and_then(|sink| { let _ = sink .send((dst.into(), socket.clone())) .into_actor(self) .then(move |res, act, ctx| { match res { Ok(sink) => { act.sinks.push(sink); if !next.is_empty() { act.send_udp(next, self_sign, next_sign, socket, ctx); } } Err(_) => panic!("DEBUG: NETWORK HAVE ERROR"), } actor_ok(()) }) .wait(ctx); Some(()) }); } } impl<A: P2PBridgeActor> Actor for P2PSessionActor<A> { type Context = Context<Self>; } impl<A: P2PBridgeActor> Handler<P2PAddrMessage<A>> for P2PSessionActor<A> { type Result = (); fn handle(&mut self, msg: P2PAddrMessage<A>, _ctx: &mut Context<Self>) { self.p2p_addr = Some(msg.0); } } impl<A: P2PBridgeActor> StreamHandler<CodecMessage, std::io::Error> for P2PSessionActor<A> { fn handle(&mut self, msg: CodecMessage, _ctx: &mut Context<Self>) { let (mut src, socket) = (msg.0, msg.1); if src.len() < 16 { return; } let (head_sign, new_data) = src.split_at_mut(24); let (prev, me_next) = head_sign.split_at_mut(8); let (me, next) = me_next.split_at_mut(8); let mut prev_sign = [0u8; 8]; prev_sign.copy_from_slice(prev); let mut sign = [0u8; 8]; sign.copy_from_slice(me); let mut next_sign = [0u8; 8]; next_sign.copy_from_slice(next); let mut data = vec![]; if let Some(mut prev_data) = self.receivings.remove(&prev_sign) { prev_sign = sign; data.append(&mut prev_data); } data.extend_from_slice(new_data); if let Some(mut next_data) = self.receivings.remove(&next_sign) { data.append(&mut next_data); } let head = { if data.len() < HEAD_LENGTH || prev_sign != sign { self.receivings.insert(sign, data); return; } P2PHead::decode(data.as_ref()) }; let size = head.len as usize; if data.len() >= size + HEAD_LENGTH { let (_, data) = data.split_at_mut(HEAD_LENGTH); let (buf, _) = data.split_at_mut(size); let content = bincode::deserialize(buf).unwrap_or(P2PContent::None); if self.p2p_addr.is_some() { let _ = try_resend_times( self.p2p_addr.clone().unwrap(), P2PMessage(head, content, socket), DEFAULT_TIMES, ) .map_err(|_| { println!("Send Message to p2p fail"); }); } } else { self.receivings.insert(sign, data); } } } impl<A: P2PBridgeActor> Handler<P2PMessage> for P2PSessionActor<A> { type Result = (); fn handle(&mut self, msg: P2PMessage, ctx: &mut Context<Self>) { self.waitings.push((msg.0, P2PBody(msg.1), msg.2)); if self.sinks.is_empty() { return; } while !self.waitings.is_empty() { let w = self.waitings.remove(0); if self.sinks.is_empty() { self.waitings.push(w); break; } let (mut head, body, socket) = (w.0, w.1, w.2); let mut body_bytes: Vec<u8> = bincode::serialize(&body).unwrap_or(vec![]); head.update_len(body_bytes.len() as u32); let mut head_bytes = head.encode().to_vec(); let mut bytes = vec![]; bytes.append(&mut head_bytes); bytes.append(&mut body_bytes); let sign: [u8; 8] = rand::random(); self.send_udp(bytes, sign.clone(), sign, socket, ctx); } } }
use bytes::{BufMut, BytesMut}; use futures::stream::SplitSink; use futures::Sink; use std::collections::HashMap; use std::net::SocketAddr; use tokio::codec::BytesCodec; use tokio::net::UdpFramed; use crate::actor::prelude::*; use crate::primitives::functions::{try_resend_times, DEFAULT_TIMES}; use crate::traits::actor::P2PBridgeActor; use super::codec::{P2PBody, P2PHead, HEAD_LENGTH}; use super::content::P2PContent; use super::p2p::P2PActor; #[derive(Clone)] pub struct P2PMessage(pub P2PHead, pub P2PContent, pub SocketAddr); impl Message for P2PMessage { type Result = (); } #[derive(Clone)] pub struct CodecMessage(pub BytesMut, pub SocketAddr); impl Message for CodecMessage { type Result = (); } #[derive(Clone)] pub(crate) struct P2PAddrMessage<A: P2PBridgeActor>(pub Addr<P2PActor<A>>); impl<A: P2PBridgeActor> Message for P2PAddrMessage<A> { type Result = (); } pub struct P2PSessionActor<A: P2PBridgeActor> { pub sinks: Vec<SplitSink<UdpFramed<BytesCodec>>>, pub p2p_addr: Option<Addr<P2PActor<A>>>, pub waitings: Vec<(P2PHead, P2PBody, SocketAddr)>, pub receivings: HashMap<[u8; 8], Vec<u8>>, } impl<A: P2PBridgeActor> P2PSessionActor<A> { fn send_udp( &mut self, mut bytes: Vec<u8>, mut prev_sign: [u8; 8], self_sign: [u8; 8], socket: SocketAddr, ctx: &mut Context<Self>, ) { let mut send_bytes = vec![]; let (mut now, next, next_sign) = if bytes.len() > 65400 { let now = bytes.drain(0..65400).as_slice().into(); (now, bytes, rand::random()) } else { (bytes, vec![], self_sign.clone()) }; send_bytes.extend_from_slice(&mut prev_sign); send_bytes.extend_from_slice(&mut self_sign.clone()); send_bytes.extend_from_slice(&mut next_sign.clone()); send_bytes.append(&mut now); let mut dst = BytesMut::new(); dst.reserve(send_bytes.len()); dst.put(send_bytes); self.sinks.pop().and_then(|sink| { let _ = sink .send((dst.into(), socket.clone())) .into_actor(self) .then(move |res, act, ctx| { match res { Ok(sink) => { act.sinks.push(sink);
} Err(_) => panic!("DEBUG: NETWORK HAVE ERROR"), } actor_ok(()) }) .wait(ctx); Some(()) }); } } impl<A: P2PBridgeActor> Actor for P2PSessionActor<A> { type Context = Context<Self>; } impl<A: P2PBridgeActor> Handler<P2PAddrMessage<A>> for P2PSessionActor<A> { type Result = (); fn handle(&mut self, msg: P2PAddrMessage<A>, _ctx: &mut Context<Self>) { self.p2p_addr = Some(msg.0); } } impl<A: P2PBridgeActor> StreamHandler<CodecMessage, std::io::Error> for P2PSessionActor<A> { fn handle(&mut self, msg: CodecMessage, _ctx: &mut Context<Self>) { let (mut src, socket) = (msg.0, msg.1); if src.len() < 16 { return; } let (head_sign, new_data) = src.split_at_mut(24); let (prev, me_next) = head_sign.split_at_mut(8); let (me, next) = me_next.split_at_mut(8); let mut prev_sign = [0u8; 8]; prev_sign.copy_from_slice(prev); let mut sign = [0u8; 8]; sign.copy_from_slice(me); let mut next_sign = [0u8; 8]; next_sign.copy_from_slice(next); let mut data = vec![]; if let Some(mut prev_data) = self.receivings.remove(&prev_sign) { prev_sign = sign; data.append(&mut prev_data); } data.extend_from_slice(new_data); if let Some(mut next_data) = self.receivings.remove(&next_sign) { data.append(&mut next_data); } let head = { if data.len() < HEAD_LENGTH || prev_sign != sign { self.receivings.insert(sign, data); return; } P2PHead::decode(data.as_ref()) }; let size = head.len as usize; if data.len() >= size + HEAD_LENGTH { let (_, data) = data.split_at_mut(HEAD_LENGTH); let (buf, _) = data.split_at_mut(size); let content = bincode::deserialize(buf).unwrap_or(P2PContent::None); if self.p2p_addr.is_some() { let _ = try_resend_times( self.p2p_addr.clone().unwrap(), P2PMessage(head, content, socket), DEFAULT_TIMES, ) .map_err(|_| { println!("Send Message to p2p fail"); }); } } else { self.receivings.insert(sign, data); } } } impl<A: P2PBridgeActor> Handler<P2PMessage> for P2PSessionActor<A> { type Result = (); fn handle(&mut self, msg: P2PMessage, ctx: &mut Context<Self>) { self.waitings.push((msg.0, P2PBody(msg.1), msg.2)); if self.sinks.is_empty() { return; } while !self.waitings.is_empty() { let w = self.waitings.remove(0); if self.sinks.is_empty() { self.waitings.push(w); break; } let (mut head, body, socket) = (w.0, w.1, w.2); let mut body_bytes: Vec<u8> = bincode::serialize(&body).unwrap_or(vec![]); head.update_len(body_bytes.len() as u32); let mut head_bytes = head.encode().to_vec(); let mut bytes = vec![]; bytes.append(&mut head_bytes); bytes.append(&mut body_bytes); let sign: [u8; 8] = rand::random(); self.send_udp(bytes, sign.clone(), sign, socket, ctx); } } }
if !next.is_empty() { act.send_udp(next, self_sign, next_sign, socket, ctx); }
if_condition
[ { "content": "pub fn parse_http_body_json(bytes: &mut BytesMut) -> Result<Value, ()> {\n\n let mut vec: Vec<u8> = Vec::new();\n\n\n\n for (i, v) in (&bytes).iter().enumerate() {\n\n if v == &13 || v == &10 {\n\n vec.push(v.clone())\n\n } else {\n\n if vec == [13, 10, 13...
Rust
src/connector/mysql/conversion.rs
kyle-mccarthy/quaint
12b6d22014f4e1218e32760a91b7985205e02453
use crate::{ ast::Value, connector::{queryable::TakeRow, TypeIdentifier}, error::{Error, ErrorKind}, }; #[cfg(feature = "chrono")] use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc}; use mysql_async::{ self as my, consts::{ColumnFlags, ColumnType}, }; use std::convert::TryFrom; #[tracing::instrument(skip(params))] pub fn conv_params<'a>(params: &[Value<'a>]) -> crate::Result<my::Params> { if params.is_empty() { Ok(my::Params::Empty) } else { let mut values = Vec::with_capacity(params.len()); for pv in params { let res = match pv { Value::Integer(i) => i.map(my::Value::Int), Value::Float(f) => f.map(my::Value::Float), Value::Double(f) => f.map(my::Value::Double), Value::Text(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())), Value::Bytes(bytes) => bytes.clone().map(|bytes| my::Value::Bytes(bytes.into_owned())), Value::Enum(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())), Value::Boolean(b) => b.map(|b| my::Value::Int(b as i64)), Value::Char(c) => c.map(|c| my::Value::Bytes(vec![c as u8])), Value::Xml(s) => s.as_ref().map(|s| my::Value::Bytes((s).as_bytes().to_vec())), Value::Array(_) => { let msg = "Arrays are not supported in MySQL."; let kind = ErrorKind::conversion(msg); let mut builder = Error::builder(kind); builder.set_original_message(msg); return Err(builder.build()); } #[cfg(feature = "bigdecimal")] Value::Numeric(f) => f.as_ref().map(|f| my::Value::Bytes(f.to_string().as_bytes().to_vec())), #[cfg(feature = "json")] Value::Json(s) => match s { Some(ref s) => { let json = serde_json::to_string(s)?; let bytes = json.into_bytes(); Some(my::Value::Bytes(bytes)) } None => None, }, #[cfg(feature = "uuid")] Value::Uuid(u) => u.map(|u| my::Value::Bytes(u.to_hyphenated().to_string().into_bytes())), #[cfg(feature = "chrono")] Value::Date(d) => { d.map(|d| my::Value::Date(d.year() as u16, d.month() as u8, d.day() as u8, 0, 0, 0, 0)) } #[cfg(feature = "chrono")] Value::Time(t) => { t.map(|t| my::Value::Time(false, 0, t.hour() as u8, t.minute() as u8, t.second() as u8, 0)) } #[cfg(feature = "chrono")] Value::DateTime(dt) => dt.map(|dt| { my::Value::Date( dt.year() as u16, dt.month() as u8, dt.day() as u8, dt.hour() as u8, dt.minute() as u8, dt.second() as u8, dt.timestamp_subsec_micros(), ) }), }; match res { Some(val) => values.push(val), None => values.push(my::Value::NULL), } } Ok(my::Params::Positional(values)) } } impl TypeIdentifier for my::Column { fn is_real(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DECIMAL | MYSQL_TYPE_NEWDECIMAL) } fn is_float(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_FLOAT) } fn is_double(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DOUBLE) } fn is_integer(&self) -> bool { use ColumnType::*; matches!( self.column_type(), MYSQL_TYPE_TINY | MYSQL_TYPE_SHORT | MYSQL_TYPE_LONG | MYSQL_TYPE_LONGLONG | MYSQL_TYPE_YEAR | MYSQL_TYPE_INT24 ) } fn is_datetime(&self) -> bool { use ColumnType::*; matches!( self.column_type(), MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_DATETIME | MYSQL_TYPE_TIMESTAMP2 | MYSQL_TYPE_DATETIME2 ) } fn is_time(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_TIME | MYSQL_TYPE_TIME2) } fn is_date(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DATE | MYSQL_TYPE_NEWDATE) } fn is_text(&self) -> bool { use ColumnType::*; let is_defined_text = matches!( self.column_type(), MYSQL_TYPE_VARCHAR | MYSQL_TYPE_VAR_STRING | MYSQL_TYPE_STRING ); let is_bytes_but_text = matches!( self.column_type(), MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB ) && self.character_set() != 63; is_defined_text || is_bytes_but_text } fn is_bytes(&self) -> bool { use ColumnType::*; let is_a_blob = matches!( self.column_type(), MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB ) && self.character_set() == 63; let is_bits = self.column_type() == MYSQL_TYPE_BIT && self.column_length() > 1; is_a_blob || is_bits } fn is_bool(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_BIT && self.column_length() == 1 } fn is_json(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_JSON } fn is_enum(&self) -> bool { self.flags() == ColumnFlags::ENUM_FLAG || self.column_type() == ColumnType::MYSQL_TYPE_ENUM } fn is_null(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_NULL } } impl TakeRow for my::Row { fn take_result_row(&mut self) -> crate::Result<Vec<Value<'static>>> { fn convert(row: &mut my::Row, i: usize) -> crate::Result<Value<'static>> { let value = row.take(i).ok_or_else(|| { let msg = "Index out of bounds"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let column = row.columns_ref().get(i).ok_or_else(|| { let msg = "Index out of bounds"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let res = match value { #[cfg(feature = "json")] my::Value::Bytes(b) if column.is_json() => { serde_json::from_slice(&b).map(Value::json).map_err(|_| { let msg = "Unable to convert bytes to JSON"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })? } my::Value::Bytes(b) if column.is_enum() => { let s = String::from_utf8(b)?; Value::enum_variant(s) } #[cfg(feature = "bigdecimal")] my::Value::Bytes(b) if column.is_real() => { let s = String::from_utf8(b).map_err(|_| { let msg = "Could not convert NEWDECIMAL from bytes to String."; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let dec = s.parse().map_err(|_| { let msg = "Could not convert NEWDECIMAL string to a BigDecimal."; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; Value::numeric(dec) } my::Value::Bytes(b) if column.is_bool() => match b.as_slice() { [0] => Value::boolean(false), _ => Value::boolean(true), }, my::Value::Bytes(b) if column.character_set() == 63 => Value::bytes(b), my::Value::Bytes(s) => Value::text(String::from_utf8(s)?), my::Value::Int(i) => Value::integer(i), my::Value::UInt(i) => Value::integer(i64::try_from(i).map_err(|_| { let msg = "Unsigned integers larger than 9_223_372_036_854_775_807 are currently not handled."; let kind = ErrorKind::value_out_of_range(msg); Error::builder(kind).build() })?), my::Value::Float(f) => Value::from(f), my::Value::Double(f) => Value::from(f), #[cfg(feature = "chrono")] my::Value::Date(year, month, day, hour, min, sec, micro) => { if day == 0 || month == 0 { let msg = format!( "The column `{}` contained an invalid datetime value with either day or month set to zero.", column.name_str() ); let kind = ErrorKind::value_out_of_range(msg); return Err(Error::builder(kind).build()); } let time = NaiveTime::from_hms_micro(hour.into(), min.into(), sec.into(), micro); let date = NaiveDate::from_ymd(year.into(), month.into(), day.into()); let dt = NaiveDateTime::new(date, time); Value::datetime(DateTime::<Utc>::from_utc(dt, Utc)) } #[cfg(feature = "chrono")] my::Value::Time(is_neg, days, hours, minutes, seconds, micros) => { if is_neg { let kind = ErrorKind::conversion("Failed to convert a negative time"); return Err(Error::builder(kind).build()); } if days != 0 { let kind = ErrorKind::conversion("Failed to read a MySQL `time` as duration"); return Err(Error::builder(kind).build()); } let time = NaiveTime::from_hms_micro(hours.into(), minutes.into(), seconds.into(), micros); Value::time(time) } my::Value::NULL => match column { t if t.is_bool() => Value::Boolean(None), t if t.is_enum() => Value::Enum(None), t if t.is_null() => Value::Integer(None), t if t.is_integer() => Value::Integer(None), t if t.is_float() => Value::Float(None), t if t.is_double() => Value::Double(None), t if t.is_text() => Value::Text(None), t if t.is_bytes() => Value::Bytes(None), #[cfg(feature = "bigdecimal")] t if t.is_real() => Value::Numeric(None), #[cfg(feature = "chrono")] t if t.is_datetime() => Value::DateTime(None), #[cfg(feature = "chrono")] t if t.is_time() => Value::Time(None), #[cfg(feature = "chrono")] t if t.is_date() => Value::Date(None), #[cfg(feature = "json")] t if t.is_json() => Value::Json(None), typ => { let msg = format!( "Value of type {:?} is not supported with the current configuration", typ ); let kind = ErrorKind::conversion(msg); return Err(Error::builder(kind).build()); } }, #[cfg(not(feature = "chrono"))] typ => { let msg = format!( "Value of type {:?} is not supported with the current configuration", typ ); let kind = ErrorKind::conversion(msg); Err(Error::builder(kind).build())? } }; Ok(res) } let mut row = Vec::with_capacity(self.len()); for i in 0..self.len() { row.push(convert(self, i)?); } Ok(row) } }
use crate::{ ast::Value, connector::{queryable::TakeRow, TypeIdentifier}, error::{Error, ErrorKind}, }; #[cfg(feature = "chrono")] use chrono::{DateTime, Datelike, NaiveDate, NaiveDateTime, NaiveTime, Timelike, Utc}; use mysql_async::{ self as my, consts::{ColumnFlags, ColumnType}, }; use std::convert::TryFrom; #[tracing::instrument(skip(params))] pub fn conv_params<'a>(params: &[Value<'a>]) -> crate::Result<my::Params> { if params.is_empty() { Ok(my::Params::Empty) } else { let mut values = Vec::with_capacity(params.len()); for pv in params { let res = match pv { Value::Integer(i) => i.map(my::Value::Int), Value::Float(f) => f.map(my::Value::Float), Value::Double(f) => f.map(my::Value::Double), Value::Text(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())), Value::Bytes(bytes) => bytes.clone().map(|bytes| my::Value::Bytes(bytes.into_owned())), Value::Enum(s) => s.clone().map(|s| my::Value::Bytes((&*s).as_bytes().to_vec())), Value::Boolean(b) => b.map(|b| my::Value::Int(b as i64)), Value::Char(c) => c.map(|c| my::Value::Bytes(vec![c as u8])), Value::Xml(s) => s.as_ref().map(|s| my::Value::Bytes((s).as_bytes().to_vec())), Value::Array(_) => { let msg = "Arrays are not supported in MySQL."; let kind = ErrorKind::conversion(msg); let mut builder = Error::builder(kind); builder.set_original_message(msg); return Err(builder.build()); } #[cfg(feature = "bigdecimal")] Value::Numeric(f) => f.as_ref().map(|f| my::Value::Bytes(f.to_string().as_bytes().to_vec())), #[cfg(feature = "json")] Value::Json(s) => match s { Some(ref s) => { let json = serde_json::to_string(s)?; let bytes = json.into_bytes(); Some(my::Value::Bytes(bytes)) } None => None, }, #[cfg(feature = "uuid")] Value::Uuid(u) => u.map(|u| my::Value::Bytes(u.to_hyphenated().to_string().into_bytes())), #[cfg(feature = "chrono")] Value::Date(d) => { d.map(|d| my::Value::Date(d.year() as u16, d.month() as u8, d.day() as u8, 0, 0, 0, 0)) } #[cfg(feature = "chrono")] Value::Time(t) => { t.map(|t| my::Value::Time(false, 0, t.hour() as u8, t.minute() as u8, t.second() as u8, 0)) } #[cfg(feature = "chrono")] Value::DateTime(dt) => dt.map(|dt| { my::Value::Date( dt.year() as u16, dt.month() as u8, dt.day() as u8, dt.hour() as u8, dt.minute() as u8, dt.second() as u8, dt.timestamp_subsec_micros(), ) }), }; match res { Some(val) => values.push(val), None => values.push(my::Value::NULL), } } Ok(my::Params::Positional(values)) } } impl TypeIdentifier for my::Column { fn is_real(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DECIMAL | MYSQL_TYPE_NEWDECIMAL) } fn is_float(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_FLOAT) } fn is_double(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DOUBLE) } fn is_integer(&self) -> bool { use ColumnType::*; matches!( self.column_type(), MYSQL_TYPE_TINY | MYSQL_TYPE_SHORT | MYSQL_TYPE_LONG | MYSQL_TYPE_LONGLONG | MYSQL_TYPE_YEAR | MYSQL_TYPE_INT24 ) } fn is_datetime(&self) -> bool { use ColumnType::*; matches!( self.column_type(), MYSQL_TYPE_TIMESTAMP | MYSQL_TYPE_DATETIME | MYSQL_TYPE_TIMESTAMP2 | MYSQL_TYPE_DATETIME2 ) } fn is_time(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_TIME | MYSQL_TYPE_TIME2) } fn is_date(&self) -> bool { use ColumnType::*; matches!(self.column_type(), MYSQL_TYPE_DATE | MYSQL_TYPE_NEWDATE) } fn is_text(&self) -> bool { use ColumnType::*; let is_defined_text = matches!( self.column_type(), MYSQL_TYPE_VARCHAR | MYSQL_TYPE_VAR_STRING | MYSQL_TYPE_STRING ); let is_bytes_but_text = matches!( self.column_type(), MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB ) && self.character_set() != 63; is_defined_text || is_bytes_but_text } fn is_bytes(&self) -> bool { use ColumnType::*; let is_a_blob = matches!( self.column_type(), MYSQL_TYPE_TINY_BLOB | MYSQL_TYPE_MEDIUM_BLOB | MYSQL_TYPE_LONG_BLOB | MYSQL_TYPE_BLOB ) && self.character_set() == 63; let is_bits = self.column_type() == MYSQL_TYPE_BIT && self.column_length() > 1; is_a_blob || is_bits } fn is_bool(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_BIT && self.column_length() == 1 } fn is_json(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_JSON } fn is_enum(&self) -> bool { self.flags() == ColumnFlags::ENUM_FLAG || self.column_type() == ColumnType::MYSQL_TYPE_ENUM } fn is_null(&self) -> bool { self.column_type() == ColumnType::MYSQL_TYPE_NULL } } impl TakeRow for my::Row { fn take_result_row(&mut self) -> crate::Result<Vec<Value<'static>>> {
let mut row = Vec::with_capacity(self.len()); for i in 0..self.len() { row.push(convert(self, i)?); } Ok(row) } }
fn convert(row: &mut my::Row, i: usize) -> crate::Result<Value<'static>> { let value = row.take(i).ok_or_else(|| { let msg = "Index out of bounds"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let column = row.columns_ref().get(i).ok_or_else(|| { let msg = "Index out of bounds"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let res = match value { #[cfg(feature = "json")] my::Value::Bytes(b) if column.is_json() => { serde_json::from_slice(&b).map(Value::json).map_err(|_| { let msg = "Unable to convert bytes to JSON"; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })? } my::Value::Bytes(b) if column.is_enum() => { let s = String::from_utf8(b)?; Value::enum_variant(s) } #[cfg(feature = "bigdecimal")] my::Value::Bytes(b) if column.is_real() => { let s = String::from_utf8(b).map_err(|_| { let msg = "Could not convert NEWDECIMAL from bytes to String."; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; let dec = s.parse().map_err(|_| { let msg = "Could not convert NEWDECIMAL string to a BigDecimal."; let kind = ErrorKind::conversion(msg); Error::builder(kind).build() })?; Value::numeric(dec) } my::Value::Bytes(b) if column.is_bool() => match b.as_slice() { [0] => Value::boolean(false), _ => Value::boolean(true), }, my::Value::Bytes(b) if column.character_set() == 63 => Value::bytes(b), my::Value::Bytes(s) => Value::text(String::from_utf8(s)?), my::Value::Int(i) => Value::integer(i), my::Value::UInt(i) => Value::integer(i64::try_from(i).map_err(|_| { let msg = "Unsigned integers larger than 9_223_372_036_854_775_807 are currently not handled."; let kind = ErrorKind::value_out_of_range(msg); Error::builder(kind).build() })?), my::Value::Float(f) => Value::from(f), my::Value::Double(f) => Value::from(f), #[cfg(feature = "chrono")] my::Value::Date(year, month, day, hour, min, sec, micro) => { if day == 0 || month == 0 { let msg = format!( "The column `{}` contained an invalid datetime value with either day or month set to zero.", column.name_str() ); let kind = ErrorKind::value_out_of_range(msg); return Err(Error::builder(kind).build()); } let time = NaiveTime::from_hms_micro(hour.into(), min.into(), sec.into(), micro); let date = NaiveDate::from_ymd(year.into(), month.into(), day.into()); let dt = NaiveDateTime::new(date, time); Value::datetime(DateTime::<Utc>::from_utc(dt, Utc)) } #[cfg(feature = "chrono")] my::Value::Time(is_neg, days, hours, minutes, seconds, micros) => { if is_neg { let kind = ErrorKind::conversion("Failed to convert a negative time"); return Err(Error::builder(kind).build()); } if days != 0 { let kind = ErrorKind::conversion("Failed to read a MySQL `time` as duration"); return Err(Error::builder(kind).build()); } let time = NaiveTime::from_hms_micro(hours.into(), minutes.into(), seconds.into(), micros); Value::time(time) } my::Value::NULL => match column { t if t.is_bool() => Value::Boolean(None), t if t.is_enum() => Value::Enum(None), t if t.is_null() => Value::Integer(None), t if t.is_integer() => Value::Integer(None), t if t.is_float() => Value::Float(None), t if t.is_double() => Value::Double(None), t if t.is_text() => Value::Text(None), t if t.is_bytes() => Value::Bytes(None), #[cfg(feature = "bigdecimal")] t if t.is_real() => Value::Numeric(None), #[cfg(feature = "chrono")] t if t.is_datetime() => Value::DateTime(None), #[cfg(feature = "chrono")] t if t.is_time() => Value::Time(None), #[cfg(feature = "chrono")] t if t.is_date() => Value::Date(None), #[cfg(feature = "json")] t if t.is_json() => Value::Json(None), typ => { let msg = format!( "Value of type {:?} is not supported with the current configuration", typ ); let kind = ErrorKind::conversion(msg); return Err(Error::builder(kind).build()); } }, #[cfg(not(feature = "chrono"))] typ => { let msg = format!( "Value of type {:?} is not supported with the current configuration", typ ); let kind = ErrorKind::conversion(msg); Err(Error::builder(kind).build())? } }; Ok(res) }
function_block-full_function
[ { "content": "#[tracing::instrument(skip(params))]\n\npub fn conv_params<'a>(params: &'a [Value<'a>]) -> crate::Result<Vec<&'a dyn ToSql>> {\n\n let mut converted = Vec::with_capacity(params.len());\n\n\n\n for param in params.iter() {\n\n converted.push(param as &dyn ToSql)\n\n }\n\n\n\n Ok(...
Rust
src/services/filler/processor.rs
Emulator000/pdfiller
89df98bbdb95147269ba9161f619ae59a30a43ce
use std::collections::BTreeMap; use std::str; use async_std::sync::Arc; use log::error; use lopdf::{Dictionary, Document as PdfDocument, Object, ObjectId}; use crate::file::FileProvider; use crate::mongo::models::document::Document; const PDF_VERSION: &str = "1.5"; pub struct DocumentObjects { pub objects: BTreeMap<ObjectId, Object>, pub pages: BTreeMap<ObjectId, Object>, } pub fn get_documents_containers<F: FileProvider + ?Sized>( file_type: Arc<Box<F>>, documents: Vec<Document>, compiled: bool, ) -> DocumentObjects { let mut max_id = 1; let mut documents_pages = BTreeMap::new(); let mut documents_objects = BTreeMap::new(); for document in documents { if let Some(ref file_name) = if compiled { file_type.generate_compiled_filepath(&document.file) } else { Some(document.file) } { match PdfDocument::load(file_name) { Ok(mut document) => { document.renumber_objects_with(max_id); max_id = document.max_id + 1; documents_pages.extend( document .get_pages() .into_iter() .map(|(_, object_id)| { ( object_id, document.get_object(object_id).unwrap().to_owned(), ) }) .collect::<BTreeMap<ObjectId, Object>>(), ); documents_objects.extend(document.objects); } Err(e) => { sentry::capture_error(&e); error!("Error loading the PDF: {:#?}", e); } } } } DocumentObjects { pages: documents_pages, objects: documents_objects, } } pub fn process_documents(documents_objects: DocumentObjects) -> Option<PdfDocument> { let mut document = PdfDocument::with_version(PDF_VERSION); let mut catalog_object: Option<(ObjectId, Object)> = None; let mut pages_object: Option<(ObjectId, Object)> = None; for (object_id, object) in documents_objects.objects.iter() { match object.type_name().unwrap_or("") { "Catalog" => { catalog_object = Some(( if let Some((id, _)) = catalog_object { id } else { *object_id }, object.clone(), )); } "Pages" => { if let Some(dictionary) = upsert_dictionary(&object, pages_object.as_ref().map(|(_, object)| object)) { pages_object = Some(( if let Some((id, _)) = pages_object { id } else { *object_id }, Object::Dictionary(dictionary), )); } } "Page" => {} "Outlines" => {} "Outline" => {} _ => { document.objects.insert(*object_id, object.clone()); } } } pages_object.as_ref()?; for (object_id, object) in documents_objects.pages.iter() { if let Ok(dictionary) = object.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Parent", pages_object.as_ref().unwrap().0); document .objects .insert(*object_id, Object::Dictionary(dictionary)); } } catalog_object.as_ref()?; let catalog_object = catalog_object.unwrap(); let pages_object = pages_object.unwrap(); if let Ok(dictionary) = pages_object.1.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Count", documents_objects.pages.len() as u32); document .objects .insert(pages_object.0, Object::Dictionary(dictionary)); } if let Ok(dictionary) = catalog_object.1.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Pages", pages_object.0); dictionary.remove(b"Outlines"); document .objects .insert(catalog_object.0, Object::Dictionary(dictionary)); } document.trailer.set("Root", catalog_object.0); document.max_id = document.objects.len() as u32; document.renumber_objects(); document.compress(); Some(document) } fn upsert_dictionary(object: &Object, other_object: Option<&Object>) -> Option<Dictionary> { if let Ok(dictionary) = object.as_dict() { let mut dictionary = dictionary.clone(); if let Some(object) = other_object { if let Ok(old_dictionary) = object.as_dict() { dictionary.extend(old_dictionary); } } Some(dictionary) } else { None } }
use std::collections::BTreeMap; use std::str; use async_std::sync::Arc; use log::error; use lopdf::{Dictionary, Document as PdfDocument, Object, ObjectId}; use crate::file::FileProvider; use crate::mongo::models::document::Document; const PDF_VERSION: &str = "1.5"; pub struct DocumentObjects { pub objects: BTreeMap<ObjectId, Object>, pub pages: BTreeMap<ObjectId, Object>, } pub fn get_documents_containers<F: FileProvider + ?Sized>( file_type: Arc<Box<F>>, documents: Vec<Document>, compiled: bool, ) -> DocumentObjects { let mut max_id = 1; let mut documents_pages = BTreeMap::new(); let mut documents_objects = BTreeMap::new(); for document in documents { if let Some(ref file_name) = if compiled { file_type.generate_compiled_filepath(&document.file) } else { Some(document.file) } { match PdfDocument::load(file_name) { Ok(mut document) => { document.renumber_objects_with(max_id); max_id = document.max_id + 1; documents_pages.extend( document .get_pages() .into_iter() .map(|(_, object_id)| { ( object_id, document.get_object(object_id).unwrap().to_owned(), ) }) .collect::<BTreeMap<ObjectId, Object>>(), ); documents_objects.extend(document.objects); } Err(e) => { sentry::capture_error(&e); error!("Error loading the PDF: {:#?}", e); } } } } DocumentObjects { pages: documents_pages, objects: documents_objects, } } pub fn process_documents(documents_objects: DocumentObjects) -> Option<PdfDocument> { let mut document = PdfDocument::with_version(PDF_VERSION); let mut catalog_object: Option<(ObjectId, Object)> = None; let mut pages_object: Option<(ObjectId, Object)> = None; for (object_id, object) in documents_objects.objects.iter() { match object.type_name().unwrap_or("") { "Catalog" => { catalog_object =
; } "Pages" => { if let Some(dictionary) = upsert_dictionary(&object, pages_object.as_ref().map(|(_, object)| object)) { pages_object = Some(( if let Some((id, _)) = pages_object { id } else { *object_id }, Object::Dictionary(dictionary), )); } } "Page" => {} "Outlines" => {} "Outline" => {} _ => { document.objects.insert(*object_id, object.clone()); } } } pages_object.as_ref()?; for (object_id, object) in documents_objects.pages.iter() { if let Ok(dictionary) = object.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Parent", pages_object.as_ref().unwrap().0); document .objects .insert(*object_id, Object::Dictionary(dictionary)); } } catalog_object.as_ref()?; let catalog_object = catalog_object.unwrap(); let pages_object = pages_object.unwrap(); if let Ok(dictionary) = pages_object.1.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Count", documents_objects.pages.len() as u32); document .objects .insert(pages_object.0, Object::Dictionary(dictionary)); } if let Ok(dictionary) = catalog_object.1.as_dict() { let mut dictionary = dictionary.clone(); dictionary.set("Pages", pages_object.0); dictionary.remove(b"Outlines"); document .objects .insert(catalog_object.0, Object::Dictionary(dictionary)); } document.trailer.set("Root", catalog_object.0); document.max_id = document.objects.len() as u32; document.renumber_objects(); document.compress(); Some(document) } fn upsert_dictionary(object: &Object, other_object: Option<&Object>) -> Option<Dictionary> { if let Ok(dictionary) = object.as_dict() { let mut dictionary = dictionary.clone(); if let Some(object) = other_object { if let Ok(old_dictionary) = object.as_dict() { dictionary.extend(old_dictionary); } } Some(dictionary) } else { None } }
Some(( if let Some((id, _)) = catalog_object { id } else { *object_id }, object.clone(), ))
call_expression
[ { "content": "fn get_document_buffer(document: &mut PdfDocument) -> ExportCompilerResult<Vec<u8>> {\n\n let buf = Vec::<u8>::new();\n\n let mut cursor = Cursor::new(buf);\n\n\n\n match document.save_to(&mut cursor) {\n\n Ok(_) => {\n\n let _ = cursor.seek(SeekFrom::Start(0));\n\n\n\n ...
Rust
openethereum/rpc/src/v1/helpers/subscribers.rs
snuspl/fluffy
d17e1fb3cda259d6f2c244ef67ee3a4bdf83261b
use std::{ops, str}; use std::collections::HashMap; use jsonrpc_pubsub::{typed::{Subscriber, Sink}, SubscriptionId}; use ethereum_types::H64; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Id(H64); impl str::FromStr for Id { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.starts_with("0x") { Ok(Id(s[2..].parse().map_err(|e| format!("{}", e))?)) } else { Err("The id must start with 0x".into()) } } } impl Id { pub fn as_string(&self) -> String { format!("{:?}", self.0) } } #[cfg(not(test))] mod random { use rand::rngs::OsRng; pub type Rng = rand::rngs::OsRng; pub fn new() -> Rng { OsRng } } #[cfg(test)] mod random { use rand::SeedableRng; use rand_xorshift::XorShiftRng; const RNG_SEED: [u8; 16] = [0u8; 16]; pub type Rng = XorShiftRng; pub fn new() -> Rng { Rng::from_seed(RNG_SEED) } } pub struct Subscribers<T> { rand: random::Rng, subscriptions: HashMap<Id, T>, } impl<T> Default for Subscribers<T> { fn default() -> Self { Subscribers { rand: random::new(), subscriptions: HashMap::new(), } } } impl<T> Subscribers<T> { fn next_id(&mut self) -> Id { let data = H64::random_using(&mut self.rand); Id(data) } pub fn insert(&mut self, val: T) -> SubscriptionId { let id = self.next_id(); debug!(target: "pubsub", "Adding subscription id={:?}", id); let s = id.as_string(); self.subscriptions.insert(id, val); SubscriptionId::String(s) } pub fn remove(&mut self, id: &SubscriptionId) -> Option<T> { trace!(target: "pubsub", "Removing subscription id={:?}", id); match *id { SubscriptionId::String(ref id) => match id.parse() { Ok(id) => self.subscriptions.remove(&id), Err(_) => None, }, _ => None, } } } impl<T> Subscribers<Sink<T>> { pub fn push(&mut self, sub: Subscriber<T>) { let id = self.next_id(); if let Ok(sink) = sub.assign_id(SubscriptionId::String(id.as_string())) { debug!(target: "pubsub", "Adding subscription id={:?}", id); self.subscriptions.insert(id, sink); } } } impl<T, V> Subscribers<(Sink<T>, V)> { pub fn push(&mut self, sub: Subscriber<T>, val: V) { let id = self.next_id(); if let Ok(sink) = sub.assign_id(SubscriptionId::String(id.as_string())) { debug!(target: "pubsub", "Adding subscription id={:?}", id); self.subscriptions.insert(id, (sink, val)); } } } impl<T> ops::Deref for Subscribers<T> { type Target = HashMap<Id, T>; fn deref(&self) -> &Self::Target { &self.subscriptions } }
use std::{ops, str}; use std::collections::HashMap; use jsonrpc_pubsub::{typed::{Subscriber, Sink}, SubscriptionId}; use ethereum_types::H64; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub struct Id(H64); impl str::FromStr for Id { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.starts_with("0x") { Ok(Id(s[2..].parse().map_err(|e| format!("{}", e))?)) } else { Err("The id must start with 0x".into()) } } } impl Id { pub fn as_string(&self) -> String { format!("{:?}", self.0) } } #[cfg(not(test))] mod random { use rand::rngs::OsRng; pub type Rng = rand::rngs::OsRng; pub fn new() -> Rng { OsRng } } #[cfg(test)] mod random { use rand::SeedableRng; use rand_xorshift::XorShiftRng; const RNG_SEED: [u8; 16] = [0u8; 16]; pub type Rng = XorShiftRng; pub fn new() -> Rng { Rng::from_seed(RNG_SEED) } } pub struct Subscribers<T> { rand: random::Rng, subscriptions: HashMap<Id, T>, } impl<T> Default for Subscribers<T> { fn default() -> Self { Subscribers { rand: random::new(), subscriptions: HashMap::new(), } } } impl<T> Subscribers<T> { fn next_id(&mut self) -> Id { let data = H64::random_using(&mut self.rand); Id(data) } pub fn insert(&mut self, val: T) -> SubscriptionId { let id = self.next_id(); debug!(target: "pubsub", "Adding subscription id={:?}", id); let s = id.as_string(); self.subscriptions.insert(id, val); SubscriptionId::String(s) }
} impl<T> Subscribers<Sink<T>> { pub fn push(&mut self, sub: Subscriber<T>) { let id = self.next_id(); if let Ok(sink) = sub.assign_id(SubscriptionId::String(id.as_string())) { debug!(target: "pubsub", "Adding subscription id={:?}", id); self.subscriptions.insert(id, sink); } } } impl<T, V> Subscribers<(Sink<T>, V)> { pub fn push(&mut self, sub: Subscriber<T>, val: V) { let id = self.next_id(); if let Ok(sink) = sub.assign_id(SubscriptionId::String(id.as_string())) { debug!(target: "pubsub", "Adding subscription id={:?}", id); self.subscriptions.insert(id, (sink, val)); } } } impl<T> ops::Deref for Subscribers<T> { type Target = HashMap<Id, T>; fn deref(&self) -> &Self::Target { &self.subscriptions } }
pub fn remove(&mut self, id: &SubscriptionId) -> Option<T> { trace!(target: "pubsub", "Removing subscription id={:?}", id); match *id { SubscriptionId::String(ref id) => match id.parse() { Ok(id) => self.subscriptions.remove(&id), Err(_) => None, }, _ => None, } }
function_block-full_function
[ { "content": "#[allow(dead_code)]\n\npub fn json_chain_test<H: FnMut(&str, HookType)>(path: &Path, json_data: &[u8], start_stop_hook: &mut H) -> Vec<String> {\n\n\tlet _ = ::env_logger::try_init();\n\n\tlet tests = ethjson::test_helpers::state::Test::load(json_data)\n\n\t\t.expect(&format!(\"Could not parse JSO...
Rust
src/refmanager.rs
WilsonGramer/ref_thread_local.rs
52cd3d9641d1b776ebd1586bdc914dd889a9f9de
extern crate std; use super::RefThreadLocal; use std::cell::Cell; use std::fmt::{Debug, Display, Formatter}; use std::ops::{Deref, DerefMut}; use std::ptr::{null, null_mut}; use std::thread::LocalKey; struct RefManagerInnerData<T> { borrow_count: Cell<isize>, value: T, } pub struct RefManagerPeekData<T> { ptr_inner_data: *mut RefManagerInnerData<T>, ptr_borrow_count: *const Cell<isize>, ptr_value: *mut T, } impl<T> Clone for RefManagerPeekData<T> { fn clone(&self) -> Self { return Self { ptr_inner_data: self.ptr_inner_data, ptr_borrow_count: self.ptr_borrow_count, ptr_value: self.ptr_value, }; } } impl<T> Copy for RefManagerPeekData<T> {} pub struct RefManagerDataGuard<T> { peek_data: Cell<RefManagerPeekData<T>>, } pub struct Ref<'a, T: ?Sized + 'a> { borrow_count: &'a Cell<isize>, value: &'a T, } pub struct RefMut<'a, T: ?Sized + 'a> { borrow_count: &'a Cell<isize>, value: &'a mut T, } #[derive(Debug)] pub struct RefManager<T: 'static> { local_key: &'static LocalKey<RefManagerDataGuard<T>>, init_func: fn() -> T, } #[derive(Debug)] pub struct BorrowError { _private: (), } #[derive(Debug)] pub struct BorrowMutError { _private: (), } #[macro_export] #[doc(hidden)] macro_rules! _create_refmanager_data { ($NAME:ident, $T:ty) => { thread_local! { static $NAME: $crate::RefManagerDataGuard<$T> = $crate::RefManagerDataGuard::INIT_SELF; } }; } impl<T> RefManager<T> { pub fn new(local_key: &'static LocalKey<RefManagerDataGuard<T>>, init_func: fn() -> T) -> Self { RefManager { local_key, init_func, } } fn get_initialized_peek(&self) -> RefManagerPeekData<T> { self.local_key.with(|guard| { if guard.peek_data.get().ptr_inner_data.is_null() { self.initialize().expect("failed to initialize"); } guard.peek_data.get() }) } } impl<T> RefThreadLocal<T> for RefManager<T> { fn initialize(&self) -> Result<(), ()> { self.local_key.with(|guard| { if guard.peek_data.get().ptr_inner_data.is_null() { let mut box_inner_data = Box::new(RefManagerInnerData { borrow_count: Cell::new(0), value: (self.init_func)(), }); let ptr_borrow_count = &box_inner_data.borrow_count as *const Cell<isize>; let ptr_value = &mut box_inner_data.value as *mut T; let ptr_inner_data = Box::into_raw(box_inner_data); guard.peek_data.set(RefManagerPeekData { ptr_inner_data, ptr_borrow_count, ptr_value, }); Ok(()) } else { Err(()) } }) } fn destroy(&self) -> Result<(), ()> { self.local_key.with(|guard| guard.destroy()) } fn is_initialized(&self) -> bool { self.local_key .with(|guard| !guard.peek_data.get().ptr_inner_data.is_null()) } fn borrow<'a>(&self) -> Ref<'a, T> { self.try_borrow().expect("already mutably borrowed") } fn borrow_mut<'a>(&self) -> RefMut<'a, T> { self.try_borrow_mut().expect("already borrowed") } fn try_borrow<'a>(&self) -> Result<Ref<'a, T>, BorrowError> { let peek_data = self.get_initialized_peek(); let (ptr_borrow_count, ptr_value) = (peek_data.ptr_borrow_count, peek_data.ptr_value); let cell_borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap(); let borrow_count = cell_borrow_count.get(); if borrow_count < 0 { return Err(BorrowError { _private: () }); } cell_borrow_count.set(borrow_count + 1); Ok(Ref { borrow_count: cell_borrow_count, value: unsafe { ptr_value.as_ref() }.unwrap(), }) } fn try_borrow_mut<'a>(&self) -> Result<RefMut<'a, T>, BorrowMutError> { let peek_data = self.get_initialized_peek(); let (ptr_borrow_count, ptr_value) = (peek_data.ptr_borrow_count, peek_data.ptr_value); let cell_borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap(); let borrow_count = cell_borrow_count.get(); if borrow_count != 0 { return Err(BorrowMutError { _private: () }); } cell_borrow_count.set(-1); Ok(RefMut { borrow_count: cell_borrow_count, value: unsafe { ptr_value.as_mut() }.unwrap(), }) } } impl<'a, T: ?Sized> Drop for Ref<'a, T> { fn drop(&mut self) { self.borrow_count.set(self.borrow_count.get() - 1); } } impl<'a, T: ?Sized> Deref for Ref<'a, T> { type Target = T; fn deref(&self) -> &T { self.value } } impl<'a, T: ?Sized> Ref<'a, T> { pub fn map<U, F>(orig: Ref<'a, T>, f: F) -> Ref<'a, U> where F: FnOnce(&T) -> &U, { let borrow_count = orig.borrow_count; let value = orig.value; std::mem::forget(orig); Ref { borrow_count: borrow_count, value: f(value), } } pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'a, T>, f: F) -> (Ref<'a, U>, Ref<'a, V>) where F: FnOnce(&T) -> (&U, &V), { let borrow_count = orig.borrow_count; let value = orig.value; std::mem::forget(orig); let (a, b) = f(value); borrow_count.set(borrow_count.get() + 1); ( Ref { borrow_count: borrow_count, value: a, }, Ref { borrow_count: borrow_count, value: b, }, ) } } impl<'a, T: Debug> Debug for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl<'a, T: Display> Display for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { self.value.fmt(f) } } impl<'a, T: ?Sized> Drop for RefMut<'a, T> { fn drop(&mut self) { self.borrow_count.set(self.borrow_count.get() + 1); } } impl<'a, T: ?Sized> Deref for RefMut<'a, T> { type Target = T; fn deref(&self) -> &T { self.value } } impl<'a, T: ?Sized> DerefMut for RefMut<'a, T> { fn deref_mut(&mut self) -> &mut T { self.value } } impl<'a, T: Debug> Debug for RefMut<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl<'a, T: Display> Display for RefMut<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { self.value.fmt(f) } } impl<'a, T: ?Sized> RefMut<'a, T> { pub fn map<U, F>(orig: RefMut<'a, T>, f: F) -> RefMut<'a, U> where F: FnOnce(&mut T) -> &mut U, { let borrow_count = orig.borrow_count; let value = orig.value as *mut T; std::mem::forget(orig); RefMut { borrow_count: borrow_count, value: f(unsafe { value.as_mut().unwrap() }), } } pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: RefMut<'a, T>, f: F) -> (RefMut<'a, U>, RefMut<'a, V>) where F: FnOnce(&mut T) -> (&mut U, &mut V), { let borrow_count = orig.borrow_count; let value = orig.value as *mut T; std::mem::forget(orig); let (a, b) = f(unsafe { value.as_mut().unwrap() }); borrow_count.set(borrow_count.get() - 1); ( RefMut { borrow_count: borrow_count, value: a, }, RefMut { borrow_count: borrow_count, value: b, }, ) } } impl<T> RefManagerDataGuard<T> { pub const INIT_PEEK_DATA: RefManagerPeekData<T> = RefManagerPeekData { ptr_inner_data: null_mut(), ptr_borrow_count: null(), ptr_value: null_mut(), }; pub const INIT_SELF: Self = RefManagerDataGuard { peek_data: Cell::new(Self::INIT_PEEK_DATA), }; pub fn destroy(&self) -> Result<(), ()> { let peek_data = self.peek_data.get(); let (ptr_inner_data, ptr_borrow_count) = (peek_data.ptr_inner_data, peek_data.ptr_borrow_count); if ptr_inner_data.is_null() { Err(()) } else { let borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap().get(); if borrow_count != 0 { panic!("cannot destroy before all references are dropped"); } unsafe { Box::from_raw(ptr_inner_data) }; self.peek_data.set(Self::INIT_PEEK_DATA); Ok(()) } } } impl<T> Drop for RefManagerDataGuard<T> { fn drop(&mut self) { let _ = self.destroy(); } }
extern crate std; use super::RefThreadLocal; use std::cell::Cell; use std::fmt::{Debug, Display, Formatter}; use std::ops::{Deref, DerefMut}; use std::ptr::{null, null_mut}; use std::thread::LocalKey; struct RefManagerInnerData<T> { borrow_count: Cell<isize>, value: T, } pub struct RefManagerPeekData<T> { ptr_inner_data: *mut RefManagerInnerData<T>, ptr_borrow_count: *const Cell<isize>, ptr_value: *mut T, } impl<T> Clone for RefManagerPeekData<T> { fn clone(&self) -> Self { return Self { ptr_inner_data: self.ptr_inner_data, ptr_borrow_count: self.ptr_borrow_count, ptr_value: self.ptr_value, }; } } impl<T> Copy for RefManagerPeekData<T> {} pub struct RefManagerDataGuard<T> { peek_data: Cell<RefManagerPeekData<T>>, } pub struct Ref<'a, T: ?Sized + 'a> { borrow_count: &'a Cell<isize>, value: &'a T, } pub struct RefMut<'a, T: ?Sized + 'a> { borrow_count: &'a Cell<isize>, value: &'a mut T, } #[derive(Debug)] pub struct RefManager<T: 'static> { local_key: &'static LocalKey<RefManagerDataGuard<T>>, init_func: fn() -> T, } #[derive(Debug)] pub struct BorrowError { _private: (), } #[derive(Debug)] pub struct BorrowMutError { _private: (), } #[macro_export] #[doc(hidden)] macro_rules! _create_refmanager_data { ($NAME:ident, $T:ty) => { thread_local! { static $NAME: $crate::RefManagerDataGuard<$T> = $crate::RefManagerDataGuard::INIT_SELF; } }; } impl<T> RefManager<T> { pub fn new(local_key: &'static LocalKey<RefManagerDataGuard<T>>, init_func: fn() -> T) -> Self { RefManager { local_key, init_func, } } fn get_initialized_peek(&self) -> RefManagerPeekData<T> { self.local_key.with(|guard| { if guard.peek_data.get().ptr_inner_data.is_null() { self.initialize().expect("failed to initialize"); } guard.peek_data.get() }) } } impl<T> RefThreadLocal<T> for RefManager<T> { fn initialize(&self) -> Result<(), ()> { self.local_key.with(|guard| { if guard.peek_data.get().ptr_inner_data.is_null() { let mut box_inner_data = Box::new(RefManagerInnerData { borrow_count: Cell::new(0), value: (self.init_func)(), }); let ptr_borrow_count = &box_inner_data.borrow_count as *const Cell<isize>; let ptr_value = &mut box_inner_data.value as *mut T; let ptr_inner_data = Box::into_raw(box_inner_data); guard.peek_data.set(RefManagerPeekData { ptr_inner_data, ptr_borrow_count, ptr_value, }); Ok(()) } else { Err(()) } }) } fn destroy(&self) -> Result<(), ()> { self.local_key.with(|guard| guard.destroy()) } fn is_initialized(&self) -> bool { self.local_key .with(|guard| !guard.peek_data.get().ptr_inner_data.is_null()) } fn borrow<'a>(&self) -> Ref<'a, T> { self.try_borrow().expect("already mutably borrowed") } fn borrow_mut<'a>(&self) -> RefMut<'a, T> { self.try_borrow_mut().expect("already borrowed") } fn try_borrow<'a>(&self) -> Result<Ref<'a, T>, BorrowError> { let peek_data = self.get_initialized_peek(); let (ptr_borrow_count, ptr_value) = (peek_data.ptr_borrow_count, peek_data.ptr_value); let cell_borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap(); let borrow_count = cell_borrow_count.get(); if borrow_count < 0 { return Err(BorrowError { _private: () }); } cell_borrow_count.set(borrow_count + 1); Ok(Ref { borrow_count: cell_borrow_count, value: unsafe { ptr_value.as_ref() }.unwrap(), }) } fn try_borrow_mut<'a>(&self) -> Result<RefMut<'a, T>, BorrowMutError> { let peek_data = self.get_initialized_peek(); let (ptr_borrow_count, ptr_value) = (peek_data.ptr_borrow_count, peek_data.ptr_value); let cell_borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap(); let borrow_count = cell_borrow_count.get(); if borrow_count != 0 { return Err(BorrowMutError { _private: () }); } cell_borrow_count.set(-1); Ok(RefMut { borrow_count: cell_borrow_count, value: unsafe { ptr_value.as_mut() }.unwrap(), }) } } impl<'a, T: ?Sized> Drop for Ref<'a, T> { fn drop(&mut self) { self.borrow_count.set(self.borrow_count.get() - 1); } } impl<'a, T: ?Sized> Deref for Ref<'a, T> { type Target = T; fn deref(&self) -> &T { self.value } } impl<'a, T: ?Sized> Ref<'a, T> { pub fn map<U, F>(orig: Ref<'a, T>, f: F) -> Ref<'a, U> where F: FnOnce(&T) -> &U, { let borrow_count = orig.borrow_count; let value = orig.value; std::mem::forget(orig); Ref { borrow_count: borrow_count, value: f(value), } }
} impl<'a, T: Debug> Debug for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl<'a, T: Display> Display for Ref<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { self.value.fmt(f) } } impl<'a, T: ?Sized> Drop for RefMut<'a, T> { fn drop(&mut self) { self.borrow_count.set(self.borrow_count.get() + 1); } } impl<'a, T: ?Sized> Deref for RefMut<'a, T> { type Target = T; fn deref(&self) -> &T { self.value } } impl<'a, T: ?Sized> DerefMut for RefMut<'a, T> { fn deref_mut(&mut self) -> &mut T { self.value } } impl<'a, T: Debug> Debug for RefMut<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Debug::fmt(&**self, f) } } impl<'a, T: Display> Display for RefMut<'a, T> { fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { self.value.fmt(f) } } impl<'a, T: ?Sized> RefMut<'a, T> { pub fn map<U, F>(orig: RefMut<'a, T>, f: F) -> RefMut<'a, U> where F: FnOnce(&mut T) -> &mut U, { let borrow_count = orig.borrow_count; let value = orig.value as *mut T; std::mem::forget(orig); RefMut { borrow_count: borrow_count, value: f(unsafe { value.as_mut().unwrap() }), } } pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: RefMut<'a, T>, f: F) -> (RefMut<'a, U>, RefMut<'a, V>) where F: FnOnce(&mut T) -> (&mut U, &mut V), { let borrow_count = orig.borrow_count; let value = orig.value as *mut T; std::mem::forget(orig); let (a, b) = f(unsafe { value.as_mut().unwrap() }); borrow_count.set(borrow_count.get() - 1); ( RefMut { borrow_count: borrow_count, value: a, }, RefMut { borrow_count: borrow_count, value: b, }, ) } } impl<T> RefManagerDataGuard<T> { pub const INIT_PEEK_DATA: RefManagerPeekData<T> = RefManagerPeekData { ptr_inner_data: null_mut(), ptr_borrow_count: null(), ptr_value: null_mut(), }; pub const INIT_SELF: Self = RefManagerDataGuard { peek_data: Cell::new(Self::INIT_PEEK_DATA), }; pub fn destroy(&self) -> Result<(), ()> { let peek_data = self.peek_data.get(); let (ptr_inner_data, ptr_borrow_count) = (peek_data.ptr_inner_data, peek_data.ptr_borrow_count); if ptr_inner_data.is_null() { Err(()) } else { let borrow_count = unsafe { ptr_borrow_count.as_ref() }.unwrap().get(); if borrow_count != 0 { panic!("cannot destroy before all references are dropped"); } unsafe { Box::from_raw(ptr_inner_data) }; self.peek_data.set(Self::INIT_PEEK_DATA); Ok(()) } } } impl<T> Drop for RefManagerDataGuard<T> { fn drop(&mut self) { let _ = self.destroy(); } }
pub fn map_split<U: ?Sized, V: ?Sized, F>(orig: Ref<'a, T>, f: F) -> (Ref<'a, U>, Ref<'a, V>) where F: FnOnce(&T) -> (&U, &V), { let borrow_count = orig.borrow_count; let value = orig.value; std::mem::forget(orig); let (a, b) = f(value); borrow_count.set(borrow_count.get() + 1); ( Ref { borrow_count: borrow_count, value: a, }, Ref { borrow_count: borrow_count, value: b, }, ) }
function_block-full_function
[ { "content": "fn __static_ref_initialize() -> X {\n\n X\n\n}\n", "file_path": "tests/test.rs", "rank": 0, "score": 76498.62253932712 }, { "content": "#[test]\n\nfn test_borrow_mut_after_borrow() {\n\n let _a = NUMBER.try_borrow();\n\n let _b = NUMBER.try_borrow_mut();\n\n _a.expe...
Rust
src/parser/combinators.rs
ireina7/abyss.rs
2c374996d68a6940a6100ff41e1912d3daca9db9
use super::core::*; #[allow(dead_code)] pub fn wrap<P: Parser>(p: P) -> Wrapper<P> { Wrapper::new(p) } #[allow(dead_code)] pub fn pure<A: Clone>(x: A) -> Pure<A> { Pure::new(x) } #[allow(dead_code)] pub fn satisfy<F>(f: F) -> Satisfy<F> where F: Fn(&char) -> bool { Satisfy::new(f) } #[allow(dead_code)] pub fn fix<'a, A, F>(fix: F) -> Fix<'a, A> where F: for<'f> Fn(&'f Fix<'a, A>) -> Box<dyn Parser<Output=A> + 'f> + 'a { Fix::new(fix) } #[allow(dead_code)] pub fn many<P: Parser>(p: P) -> Many<P> { Many::new(p) } #[allow(dead_code)] pub fn at_least_1<P: Parser>(p: P) -> Many1<P> { Many1::new(p) } #[allow(dead_code)] pub fn many1<P: Parser>(p: P) -> Many1<P> { at_least_1(p) } #[allow(dead_code)] pub fn char(ch: char) -> Char { Char { ch } } #[allow(dead_code)] pub fn digit() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|&c| c.is_digit(10)).info("Parsing single digit") } #[allow(dead_code)] pub fn digits() -> Wrapper<impl Parser<Output=Vec<char>> + Clone> { many(digit()).info("Parsing many digits") } #[allow(dead_code)] pub fn letter() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|&c| c.is_alphabetic()).info("Parsing single letter") } #[allow(dead_code)] pub fn letters() -> Wrapper<impl Parser<Output=Vec<char>> + Clone> { many(letter()).info("Parsing many letters") } #[allow(dead_code)] pub fn blank() -> Wrapper<impl Parser<Output=String> + Clone> { many(char(' ') | char('\t') | char('\n')).map(|xs| xs.into_iter().collect()) .info("Parsing blanks") } #[allow(dead_code)] pub fn identifier() -> Wrapper<impl Parser<Output=String> + Clone> { (letter() >> move |x_| many(letter().or(digit()).or(char('_'))) >> move |xs| pure(vec![x_].into_iter().chain(xs.into_iter()).collect::<String>())) .info("Parsing identifier") } #[allow(dead_code)] pub fn any() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|_| true).info("Parsing any char") } #[allow(dead_code)] pub fn one_of(cs: &str) -> Wrapper<impl Parser<Output=char> + Clone> { let ss = cs.to_string(); satisfy(move |&c| ss.chars().any(|x| x == c)) .info(&format!("Parsing char of one of {}", cs)) } #[allow(dead_code)] pub fn except(cs: &str) -> Wrapper<impl Parser<Output=char> + Clone> { let ss = cs.to_string(); satisfy(move |&c| !ss.chars().any(|x| x == c)) .info(&format!("Parsing char except one of {}", cs)) } #[allow(dead_code)] pub fn identifiers_sep_by_blank() -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { many( identifier() >> move |x| blank() >> move |_| pure(x.clone())) .info("Parsing identifiers") } #[allow(dead_code)] pub fn list_of_identifiers_sep_by_blank() -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { (char('(') >> move |_| identifiers_sep_by_blank() >> move |s| char(')') >> move |_| pure(s.clone())) .info("Parsing list of identifiers") } /* pub fn list<P: Parser<Output=Vec<String>> + Clone>(p: Wrapper<P>) -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { wrap( char('(') >> move |__| many(identifier()) >> move |xs| char(')') >> move |__| pure(xs.clone()) ) } */ #[cfg(test)] mod tests { use super::*; #[test] fn test_parser_monad() { let mut src = ParseState::new("a0bcdefghijklmn"); let ans = char('a') .and_then(|_| digit()) .and_then(|_| char('b')); assert_eq!(ans.parse(&mut src), Ok('b')); } /* #[test] fn test_parser_monad_do_notation() { let mut src = ParseState::new("a0bcdefghijklmn"); let parser = do_parse! { a =o char('a'), _ =o digit() , b =o char('b'), =o satisfy(move |&c| c == a || c == b || c == 'c') }; assert_eq!(parser.parse(&mut src), Ok('c')); }*/ #[test] fn test_parser_many() { let mut src = ParseState::new("aa0bcdefghijklmn"); let parser = many(char('a')); assert_eq!(parser.parse(&mut src), Ok(vec!['a', 'a'])); } #[test] fn test_parser_many1() { let mut src = ParseState::new("aa01bcdefghijklmn"); let parser0 = at_least_1(char('a')); let parser1 = digits(); let parser2 = many1(char('a')); assert_eq!(parser0.parse(&mut src), Ok(vec!['a', 'a'])); assert_eq!(parser1.parse(&mut src), Ok(vec!['0', '1'])); assert_eq!(parser2.parse(&mut src).ok(), None); } #[test] fn test_parser_identifier() { let mut src = ParseState::new("hello0)"); let parser = identifier(); assert_eq!(parser.parse(&mut src), Ok("hello0".into())); } /* #[test] fn test_parser_string() { let mut src = ParseState::new("hello0%"); let parser = string("hell"); assert_eq!(parser.parse(&mut src).ok(), Some("hell".into())); //assert_eq!(src.next(), Some('o')); }*/ #[test] fn test_parser_map() { let mut src = ParseState::new("hello0%"); let parser = letters().map(|cs| cs.into_iter().map(|c| if c == 'l' { 'x' } else { c }).collect::<String>()); assert_eq!(parser.parse(&mut src).ok(), Some("hexxo".into())); } #[test] fn test_parse_list() { let mut src = ParseState::new("(Hello world)"); let parser = list_of_identifiers_sep_by_blank(); assert_eq!(parser.parse(&mut src), Ok(vec!["Hello", "world"].into_iter().map(|s| s.into()).collect())); } #[test] fn test_parser_blank() { let mut src = ParseState::new("( )"); let parser = char('(').and(blank()); assert_eq!(parser.parse(&mut src).ok(), Some(" ".into())); } #[test] fn test_parser_fix() { let mut src = ParseState::new("....@"); let parser = fix(|f| Box::new( char('.') >> move |_| f.clone().or(char('@')) >> move |xs| pure(xs.clone()) )); assert_eq!(parser.parse(&mut src).ok(), Some('@')); } }
use super::core::*; #[allow(dead_code)] pub fn wrap<P: Parser>(p: P) -> Wrapper<P> { Wrapper::new(p) } #[allow(dead_code)] pub fn pure<A: Clone>(x: A) -> Pure<A> { Pure::new(x) } #[allow(dead_code)] pub fn satisfy<F>(f: F) -> Satisfy<F> where F: Fn(&char) -> bool { Satisfy::new(f) } #[allow(dead_code)] pub fn fix<'a, A, F>(fix: F) -> Fix<'a, A> where F: for<'f> Fn(&'f Fix<'a, A>) -> Box<dyn Parser<Output=A> + 'f> + 'a { Fix::new(fix) } #[allow(dead_code)] pub fn many<P: Parser>(p: P) -> Many<P> { Many::new(p) } #[allow(dead_code)] pub fn at_least_1<P: Parser>(p: P) -> Many1<P> { Many1::new(p) } #[allow(dead_code)] pub fn many1<P: Parser>(p: P) -> Many1<P> { at_least_1(p) } #[allow(dead_code)] pub fn char(ch: char) -> Char { Char { ch } } #[allow(dead_code)] pub fn digit() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|&c| c.is_digit(10)).info("Parsing single digit") } #[allow(dead_code)] pub fn digits() -> Wrapper<impl Parser<Output=Vec<char>> + Clone> { many(digit()).info("Parsing many digits") } #[allow(dead_code)] pub fn letter() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|&c| c.is_alphabetic()).info("Parsing single letter") } #[allow(dead_code)] pub fn letters() -> Wrapper<impl Parser<Output=Vec<char>> + Clone> { many(letter()).info("Parsing many letters") } #[allow(dead_code)] pub fn blank() -> Wrapper<impl Parser<Output=String> + Clone> { many(char(' ') | char('\t') | char('\n')).map(|xs| xs.into_iter().collect()) .info("Parsing blanks") } #[allow(dead_code)] pub fn identifier() -> Wrapper<impl Parser<Output=String> + Clone> { (letter() >> move |x_| many(letter().or(digit()).or(char('_'))) >> move |xs| pure(vec![x_].into_iter().chain(xs.into_iter()).collect::<String>())) .info("Parsing identifier") } #[allow(dead_code)] pub fn any() -> Wrapper<impl Parser<Output=char> + Clone> { satisfy(|_| true).info("Parsing any char") } #[allow(dead_code)] pub fn one_of(cs: &str) -> Wrapper<impl Parser<Output=char> + Clone> { let ss = cs.to_string(); satisfy(move |&c| ss.chars().any(|x| x == c))
.parse(&mut src), Ok('c')); }*/ #[test] fn test_parser_many() { let mut src = ParseState::new("aa0bcdefghijklmn"); let parser = many(char('a')); assert_eq!(parser.parse(&mut src), Ok(vec!['a', 'a'])); } #[test] fn test_parser_many1() { let mut src = ParseState::new("aa01bcdefghijklmn"); let parser0 = at_least_1(char('a')); let parser1 = digits(); let parser2 = many1(char('a')); assert_eq!(parser0.parse(&mut src), Ok(vec!['a', 'a'])); assert_eq!(parser1.parse(&mut src), Ok(vec!['0', '1'])); assert_eq!(parser2.parse(&mut src).ok(), None); } #[test] fn test_parser_identifier() { let mut src = ParseState::new("hello0)"); let parser = identifier(); assert_eq!(parser.parse(&mut src), Ok("hello0".into())); } /* #[test] fn test_parser_string() { let mut src = ParseState::new("hello0%"); let parser = string("hell"); assert_eq!(parser.parse(&mut src).ok(), Some("hell".into())); //assert_eq!(src.next(), Some('o')); }*/ #[test] fn test_parser_map() { let mut src = ParseState::new("hello0%"); let parser = letters().map(|cs| cs.into_iter().map(|c| if c == 'l' { 'x' } else { c }).collect::<String>()); assert_eq!(parser.parse(&mut src).ok(), Some("hexxo".into())); } #[test] fn test_parse_list() { let mut src = ParseState::new("(Hello world)"); let parser = list_of_identifiers_sep_by_blank(); assert_eq!(parser.parse(&mut src), Ok(vec!["Hello", "world"].into_iter().map(|s| s.into()).collect())); } #[test] fn test_parser_blank() { let mut src = ParseState::new("( )"); let parser = char('(').and(blank()); assert_eq!(parser.parse(&mut src).ok(), Some(" ".into())); } #[test] fn test_parser_fix() { let mut src = ParseState::new("....@"); let parser = fix(|f| Box::new( char('.') >> move |_| f.clone().or(char('@')) >> move |xs| pure(xs.clone()) )); assert_eq!(parser.parse(&mut src).ok(), Some('@')); } }
.info(&format!("Parsing char of one of {}", cs)) } #[allow(dead_code)] pub fn except(cs: &str) -> Wrapper<impl Parser<Output=char> + Clone> { let ss = cs.to_string(); satisfy(move |&c| !ss.chars().any(|x| x == c)) .info(&format!("Parsing char except one of {}", cs)) } #[allow(dead_code)] pub fn identifiers_sep_by_blank() -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { many( identifier() >> move |x| blank() >> move |_| pure(x.clone())) .info("Parsing identifiers") } #[allow(dead_code)] pub fn list_of_identifiers_sep_by_blank() -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { (char('(') >> move |_| identifiers_sep_by_blank() >> move |s| char(')') >> move |_| pure(s.clone())) .info("Parsing list of identifiers") } /* pub fn list<P: Parser<Output=Vec<String>> + Clone>(p: Wrapper<P>) -> Wrapper<impl Parser<Output=Vec<String>> + Clone> { wrap( char('(') >> move |__| many(identifier()) >> move |xs| char(')') >> move |__| pure(xs.clone()) ) } */ #[cfg(test)] mod tests { use super::*; #[test] fn test_parser_monad() { let mut src = ParseState::new("a0bcdefghijklmn"); let ans = char('a') .and_then(|_| digit()) .and_then(|_| char('b')); assert_eq!(ans.parse(&mut src), Ok('b')); } /* #[test] fn test_parser_monad_do_notation() { let mut src = ParseState::new("a0bcdefghijklmn"); let parser = do_parse! { a =o char('a'), _ =o digit() , b =o char('b'), =o satisfy(move |&c| c == a || c == b || c == 'c') }; assert_eq!(parser
random
[ { "content": "/// Check if variable is atom (normal form)\n\nfn is_atom(s: &str) -> bool {\n\n let atoms = [\"True\", \"False\"];\n\n atoms.iter().any(|&x| x == s)\n\n}\n\n\n", "file_path": "src/abyss/eval/strict.rs", "rank": 18, "score": 143964.6489613122 }, { "content": "/// Test if ...
Rust
src/entities.rs
JoshMcguigan/amethyst-2d-platformer-demo
fa4c53621e4af22e6e7f0657e83bfa13f50bf341
use amethyst::{ assets::{AssetStorage, Loader}, core::{Transform}, ecs::{Entity}, prelude::*, renderer::{ Camera, PngFormat, Projection, Sprite, SpriteRender, SpriteSheet, SpriteSheetHandle, Texture, TextureMetadata, SpriteSheetFormat, Transparent }, }; use crate::{ DISPLAY_WIDTH, PLAYER_W, PLAYER_H, CRATE_SIZE, GROUND_Y, TOTAL_PLAYER_SPRITE_HEIGHT, components::{Player, TwoDimObject} }; pub struct InitialState; impl SimpleState for InitialState { fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let world = data.world; let background_sprite_sheet_handle = load_sprite_sheet(world, "./texture/BG.png", "./texture/BG.ron"); init_background_sprite(world, &background_sprite_sheet_handle); let ground_sprite_sheet_handle = load_sprite_sheet(world, "./texture/ground.png", "./texture/ground.ron"); init_ground_sprite(world, &ground_sprite_sheet_handle); let crate_sprite_sheet_handle = load_sprite_sheet(world, "./texture/Crate.png", "./texture/Crate.ron"); init_crate_sprite(world, &crate_sprite_sheet_handle, 0., GROUND_Y); init_crate_sprite(world, &crate_sprite_sheet_handle, CRATE_SIZE, GROUND_Y); init_crate_sprite(world, &crate_sprite_sheet_handle, 0., GROUND_Y + CRATE_SIZE); let floating_crate_height = (PLAYER_H + 10) as f32 + GROUND_Y; init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - CRATE_SIZE, floating_crate_height); init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - 2. * CRATE_SIZE, floating_crate_height); init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - 3. * CRATE_SIZE, floating_crate_height); world.register::<Player>(); let sprite_sheet_handle = load_player_sprite_sheet(world); init_player(world, &sprite_sheet_handle); init_camera(world); } } fn init_camera(world: &mut World) { let mut transform = Transform::default(); transform.set_xyz(0.0, 0.0, 1.0); world .create_entity() .with(Camera::from(Projection::orthographic( 0.0, DISPLAY_WIDTH, 0.0, 1000., ))) .with(transform) .build(); } fn init_player(world: &mut World, sprite_sheet_handle: &SpriteSheetHandle) -> Entity { let scale = 1.; let mut transform = Transform::default(); transform.set_scale(scale, scale, scale); let sprite_render = SpriteRender { sprite_sheet: sprite_sheet_handle.clone(), sprite_number: 60, }; let mut two_dim_object = TwoDimObject::new(PLAYER_W as f32, PLAYER_H as f32); two_dim_object.set_position(500., 500.); two_dim_object.update_transform_position(&mut transform); world .create_entity() .with(transform) .with(Player::new(two_dim_object)) .with(sprite_render) .with(Transparent) .build() } fn init_background_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity { let mut transform = Transform::default(); transform.set_xyz(500., 500., -10.); transform.set_scale(1., 1.5, 1.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; world.create_entity() .with(transform) .with(sprite) .with(Transparent) .build() } fn init_ground_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity { let mut transform = Transform::default(); transform.set_z(-9.); transform.set_scale(10., 1., 1.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; let mut two_dim_object = TwoDimObject::new(1280., 128.); two_dim_object.set_left(0.); two_dim_object.set_top(GROUND_Y); two_dim_object.update_transform_position(&mut transform); world.create_entity() .with(transform) .with(two_dim_object) .with(sprite) .with(Transparent) .build() } fn init_crate_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle, left: f32, bottom: f32) -> Entity { let mut transform = Transform::default(); transform.set_z(-9.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; let mut two_dim_object = TwoDimObject::new(CRATE_SIZE, CRATE_SIZE); two_dim_object.set_left(left); two_dim_object.set_bottom(bottom); two_dim_object.update_transform_position(&mut transform); world.create_entity() .with(transform) .with(two_dim_object) .with(sprite) .with(Transparent) .build() } fn load_sprite_sheet(world: &mut World, png_path: &str, ron_path: &str) -> SpriteSheetHandle { let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( png_path, PngFormat, TextureMetadata::srgb_scale(), (), &texture_storage, ) }; let loader = world.read_resource::<Loader>(); let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>(); loader.load( ron_path, SpriteSheetFormat, texture_handle, (), &sprite_sheet_store, ) } fn load_player_sprite_sheet(world: &mut World) -> SpriteSheetHandle { let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( "./texture/spritesheet.png", PngFormat, TextureMetadata::srgb_scale(), (), &texture_storage, ) }; let loader = world.read_resource::<Loader>(); let sprite_count = 75; let mut sprites = Vec::with_capacity(sprite_count); let image_w = 200; let image_h = 13980; for i in 0..(sprite_count as u32) { let offset_x = 0; let offset_y = TOTAL_PLAYER_SPRITE_HEIGHT * i; let offsets = [0.; 2]; let sprite = Sprite::from_pixel_values( image_w, image_h, PLAYER_W, PLAYER_H, offset_x, offset_y, offsets, ); sprites.push(sprite); } let sprite_sheet = SpriteSheet { texture: texture_handle, sprites, }; loader.load_from_data( sprite_sheet, (), &world.read_resource::<AssetStorage<SpriteSheet>>(), ) }
use amethyst::{ assets::{AssetStorage, Loader}, core::{Transform}, ecs::{Entity}, prelude::*, renderer::{ Camera, PngFormat, Projection, Sprite, SpriteRender, SpriteSheet, SpriteSheetHandle, Texture, TextureMetadata, SpriteSheetFormat, Transparent }, }; use crate::{ DISPLAY_WIDTH, PLAYER_W, PLAYER_H, CRATE_SIZE, GROUND_Y, TOTAL_PLAYER_SPRITE_HEIGHT, components::{Player, TwoDimObject} }; pub struct InitialState; impl SimpleState for InitialState { fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) { let world = data.world; let background_sprite_sheet_handle = load_sprite_sheet(world, "./texture/BG.png", "./texture/BG.ron"); init_background_sprite(world, &background_sprite_sheet_handle); let ground_sprite_sheet_handle = load_sprite_sheet(world, "./texture/ground.png", "./texture/ground.ron"); init_ground_sprite(world, &ground_sprite_sheet_handle); let crate_sprite_sheet_handle = load_sprite_sheet(world, "./texture/Crate.png", "./texture/Crate.ron"); init_crate_sprite(world, &crate_sprite_sheet_handle, 0., GROUND_Y); init_crate_sprite(world, &crate_sprite_sheet_handle, CRATE_SIZE, GROUND_Y); init_crate_sprite(world, &crate_sprite_sheet_handle, 0., GROUND_Y + CRATE_SIZE); let floating_crate_height = (PLAYER_H + 10) as f32 + GROUND_Y; init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - CRATE_SIZE, floating_crate_height); init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - 2. * CRATE_SIZE, floating_crate_height); init_crate_sprite(world, &crate_sprite_sheet_handle, DISPLAY_WIDTH - 3. * CRATE_SIZE, floating_crate_height); world.register::<Player>(); let sprite_sheet_handle = load_player_sprite_sheet(world); init_player(world, &sprite_sheet_handle); init_camera(world); } } fn init_camera(world: &mut World) { let mut transform = Transform::default(); transform.set_xyz(0.0, 0.0, 1.0); world .create_entity() .with(Camera::from(Projection::orthographic( 0.0, DISPLAY_WIDTH, 0.0, 1000., ))) .with(transform) .build(); } fn init_player(world: &mut World, sprite_sheet_handle: &SpriteSheetHandle) -> Entity { let scale = 1.; let mut transform = Transform::default(); transform.set_scale(scale, scale, scale); let sprite_render = SpriteRender { sprite_sheet: sprite_sheet_handle.clone(), sprite_number: 60, }; let mut two_dim_object = TwoDimObject::new(PLAYER_W as f32, PLAYER_H as f32); two_dim_object.set_position(500., 500.); two_dim_object.update_transform_position(&mut transform); world .create_entity() .with(transform) .with(Player::new(two_dim_object)) .with(sprite_render) .with(Transparent) .build() } fn init_background_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity { let mut transform = Transform::default(); transform.set_xyz(500., 500., -10.); transform.set_scale(1., 1.5, 1.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; world.create_entity() .with(transform) .with(sprite) .with(Transparent) .build() } fn init_ground_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle) -> Entity { let mut transform = Transform::default(); transform.set_z(-9.); transform.set_scale(10., 1., 1.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; let mut two_dim_object = TwoDimObject::new(1280., 128.); two_dim_object.set_left(0.); two_dim_object.set_top(GROUND_Y); two_dim_object.update_transform_position(&mut transform);
fn init_crate_sprite(world: &mut World, sprite_sheet: &SpriteSheetHandle, left: f32, bottom: f32) -> Entity { let mut transform = Transform::default(); transform.set_z(-9.); let sprite = SpriteRender { sprite_sheet: sprite_sheet.clone(), sprite_number: 0, }; let mut two_dim_object = TwoDimObject::new(CRATE_SIZE, CRATE_SIZE); two_dim_object.set_left(left); two_dim_object.set_bottom(bottom); two_dim_object.update_transform_position(&mut transform); world.create_entity() .with(transform) .with(two_dim_object) .with(sprite) .with(Transparent) .build() } fn load_sprite_sheet(world: &mut World, png_path: &str, ron_path: &str) -> SpriteSheetHandle { let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( png_path, PngFormat, TextureMetadata::srgb_scale(), (), &texture_storage, ) }; let loader = world.read_resource::<Loader>(); let sprite_sheet_store = world.read_resource::<AssetStorage<SpriteSheet>>(); loader.load( ron_path, SpriteSheetFormat, texture_handle, (), &sprite_sheet_store, ) } fn load_player_sprite_sheet(world: &mut World) -> SpriteSheetHandle { let texture_handle = { let loader = world.read_resource::<Loader>(); let texture_storage = world.read_resource::<AssetStorage<Texture>>(); loader.load( "./texture/spritesheet.png", PngFormat, TextureMetadata::srgb_scale(), (), &texture_storage, ) }; let loader = world.read_resource::<Loader>(); let sprite_count = 75; let mut sprites = Vec::with_capacity(sprite_count); let image_w = 200; let image_h = 13980; for i in 0..(sprite_count as u32) { let offset_x = 0; let offset_y = TOTAL_PLAYER_SPRITE_HEIGHT * i; let offsets = [0.; 2]; let sprite = Sprite::from_pixel_values( image_w, image_h, PLAYER_W, PLAYER_H, offset_x, offset_y, offsets, ); sprites.push(sprite); } let sprite_sheet = SpriteSheet { texture: texture_handle, sprites, }; loader.load_from_data( sprite_sheet, (), &world.read_resource::<AssetStorage<SpriteSheet>>(), ) }
world.create_entity() .with(transform) .with(two_dim_object) .with(sprite) .with(Transparent) .build() }
function_block-function_prefix_line
[ { "content": "fn main() -> amethyst::Result<()> {\n\n amethyst::start_logger(Default::default());\n\n let config = DisplayConfig::load(\"./resources/display_config.ron\");\n\n let pipe = Pipeline::build().with_stage(\n\n Stage::with_backbuffer()\n\n .clear_target([0.1, 0.1, 0.2, 1.0],...
Rust
src/lib.rs
psFried/pgen
008a4c680cd3651da5442780076523df1e8df86e
#[macro_use] extern crate failure; #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; extern crate itertools; extern crate lalrpop_util; extern crate rand; extern crate regex; extern crate rustyline; extern crate string_cache; mod arguments; pub(crate) mod builtins; mod context; pub mod interpreter; pub mod program; pub mod repl; mod types; pub mod verbosity; mod writer; #[cfg(test)] mod fun_test; pub use self::arguments::Arguments; pub use self::context::ProgramContext; pub use self::interpreter::ast::GenType; pub use self::interpreter::prototype::{ BoundArgument, BuiltinFunctionCreator, BuiltinFunctionPrototype, CreateFunctionResult, FunctionPrototype, InterpretedFunctionPrototype, }; pub use self::interpreter::{Interpreter, Source}; pub use self::types::{ ConstBin, ConstBoolean, ConstDecimal, ConstInt, ConstString, ConstUint, OutputType, }; pub use self::writer::DataGenOutput; use failure::Error; use std::fmt::Debug; use std::rc::Rc; pub type IString = string_cache::DefaultAtom; pub trait RunnableFunction<T>: Debug { fn gen_value(&self, context: &mut ProgramContext) -> Result<T, Error>; fn write_value( &self, context: &mut ProgramContext, output: &mut DataGenOutput, ) -> Result<(), Error>; } pub type DynFun<T> = Rc<RunnableFunction<T>>; pub type DynStringFun = DynFun<IString>; pub type DynUintFun = DynFun<u64>; pub type DynIntFun = DynFun<i64>; pub type DynDecimalFun = DynFun<f64>; pub type DynBooleanFun = DynFun<bool>; pub type DynBinFun = DynFun<Vec<u8>>; #[derive(Debug, Clone)] pub enum AnyFunction { String(DynStringFun), Uint(DynUintFun), Int(DynIntFun), Decimal(DynDecimalFun), Boolean(DynBooleanFun), Bin(DynBinFun), } impl AnyFunction { pub fn get_type(&self) -> GenType { match *self { AnyFunction::String(_) => GenType::String, AnyFunction::Uint(_) => GenType::Uint, AnyFunction::Int(_) => GenType::Int, AnyFunction::Decimal(_) => GenType::Decimal, AnyFunction::Boolean(_) => GenType::Boolean, AnyFunction::Bin(_) => GenType::Bin, } } pub fn write_value( &self, context: &mut ProgramContext, output: &mut DataGenOutput, ) -> Result<(), Error> { match *self { AnyFunction::String(ref fun) => fun.write_value(context, output), AnyFunction::Uint(ref fun) => fun.write_value(context, output), AnyFunction::Int(ref fun) => fun.write_value(context, output), AnyFunction::Decimal(ref fun) => fun.write_value(context, output), AnyFunction::Boolean(ref fun) => fun.write_value(context, output), AnyFunction::Bin(ref fun) => fun.write_value(context, output), } } } macro_rules! type_conversions { ($([$as_fn_name:ident, $req_fn_name:ident, $return_type:ty, $do_match:path]),*) => { impl AnyFunction { $( pub fn $as_fn_name(self) -> Result<$return_type, AnyFunction> { match self { $do_match(fun) => Ok(fun), other @ _ => Err(other) } } pub fn $req_fn_name(self) -> Result<$return_type, Error> { self.$as_fn_name().map_err(|fun| { format_err!("Invalid argument type, expected: {}, actual: {}", stringify!($return_type), fun.get_type()) }) } )* } } } type_conversions!{ [as_string, require_string, DynStringFun, AnyFunction::String], [as_int, require_int, DynIntFun, AnyFunction::Int], [as_uint, require_uint, DynUintFun, AnyFunction::Uint], [as_decimal, require_decimal, DynDecimalFun, AnyFunction::Decimal], [as_boolean, require_boolean, DynBooleanFun, AnyFunction::Boolean], [as_bin, require_bin, DynBinFun, AnyFunction::Bin] }
#[macro_use] extern crate failure; #[macro_use] extern crate lazy_static; extern crate byteorder; extern crate encoding; extern crate itertools; extern crate lalrpop_util; extern crate rand; extern crate regex; extern crate rustyline; extern crate string_cache; mod arguments; pub(crate) mod builtins; mod context; pub mod interpreter; pub mod program; pub mod repl; mod types; pub mod verbosity; mod writer; #[cfg(test)] mod fun_test; pub use self::arguments::Arguments; pub use self::context::ProgramContext; pub use self::interpreter::ast::GenType; pub use self::interpreter::prototype::{ BoundArgument, BuiltinFunctionCreator, BuiltinFunctionPrototype, CreateFunctionResult, FunctionPrototype, InterpretedFunctionPrototype, }; pub use self::interpreter::{Interpreter, Source}; pub use self::types::{ ConstBin, ConstBoolean, ConstDecimal, ConstInt, ConstString, ConstUint, OutputType, }; pub use self::writer::DataGenOutput; use failure::Error; use std::fmt::Debug; use std::rc::Rc; pub type IString = string_cache::DefaultAtom; pub trait RunnableFunction<T>: Debug { fn gen_value(&self, context: &mut ProgramContext) -> Result<T, Error>; fn write_value( &self, context: &mut ProgramContext, output: &mut DataGenOutput, ) -> Result<(), Error>; } pub type DynFun<T> = Rc<RunnableFunction<T>>; pub type DynStringFun = DynFun<IString>; pub type DynUintFun = DynFun<u64>; pub type DynIntFun = DynFun<i64>; pub type DynDecimalFun = DynFun<f64>; pub type DynBooleanFun = DynFun<bool>; pub type DynBinFun = DynFun<Vec<u8>>; #[derive(Debug, Clone)] pub enum AnyFunction { String(DynStringFun), Uint(DynUintFun), Int(DynIntFun), Decimal(DynDecimalFun), Boolean(DynBooleanFun), Bin(DynBinFun), } impl AnyFunction {
pub fn write_value( &self, context: &mut ProgramContext, output: &mut DataGenOutput, ) -> Result<(), Error> { match *self { AnyFunction::String(ref fun) => fun.write_value(context, output), AnyFunction::Uint(ref fun) => fun.write_value(context, output), AnyFunction::Int(ref fun) => fun.write_value(context, output), AnyFunction::Decimal(ref fun) => fun.write_value(context, output), AnyFunction::Boolean(ref fun) => fun.write_value(context, output), AnyFunction::Bin(ref fun) => fun.write_value(context, output), } } } macro_rules! type_conversions { ($([$as_fn_name:ident, $req_fn_name:ident, $return_type:ty, $do_match:path]),*) => { impl AnyFunction { $( pub fn $as_fn_name(self) -> Result<$return_type, AnyFunction> { match self { $do_match(fun) => Ok(fun), other @ _ => Err(other) } } pub fn $req_fn_name(self) -> Result<$return_type, Error> { self.$as_fn_name().map_err(|fun| { format_err!("Invalid argument type, expected: {}, actual: {}", stringify!($return_type), fun.get_type()) }) } )* } } } type_conversions!{ [as_string, require_string, DynStringFun, AnyFunction::String], [as_int, require_int, DynIntFun, AnyFunction::Int], [as_uint, require_uint, DynUintFun, AnyFunction::Uint], [as_decimal, require_decimal, DynDecimalFun, AnyFunction::Decimal], [as_boolean, require_boolean, DynBooleanFun, AnyFunction::Boolean], [as_bin, require_bin, DynBinFun, AnyFunction::Bin] }
pub fn get_type(&self) -> GenType { match *self { AnyFunction::String(_) => GenType::String, AnyFunction::Uint(_) => GenType::Uint, AnyFunction::Int(_) => GenType::Int, AnyFunction::Decimal(_) => GenType::Decimal, AnyFunction::Boolean(_) => GenType::Boolean, AnyFunction::Bin(_) => GenType::Bin, } }
function_block-full_function
[ { "content": "fn execute_fn(function: AnyFunction, context: &mut ProgramContext) -> Result<(), Error> {\n\n let out = io::stdout();\n\n let mut lock = out.lock();\n\n\n\n let result = {\n\n let mut dgen_out = DataGenOutput::new(&mut lock);\n\n function.write_value(context, &mut dgen_out)....
Rust
src/resolution/constraint/contact_equation.rs
BenBergman/nphysics
11ca4d6f967c35e7f51e65295174c5b0395cbd93
use na::Bounded; use na; use num::Float; use ncollide::geometry::Contact; use volumetric::InertiaTensor; use resolution::constraint::velocity_constraint::VelocityConstraint; use object::RigidBody; use math::{Scalar, Point, Vect, Orientation}; pub enum CorrectionMode { Velocity(Scalar), VelocityAndPosition(Scalar, Scalar, Scalar), VelocityAndPositionThresold(Scalar, Scalar, Scalar) } impl CorrectionMode { #[inline] pub fn vel_corr_factor(&self) -> Scalar { match *self { CorrectionMode::Velocity(ref v) => v.clone(), CorrectionMode::VelocityAndPosition(ref v, _, _) => v.clone(), CorrectionMode::VelocityAndPositionThresold(ref v, _, _) => v.clone() } } #[inline] pub fn pos_corr_factor(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, ref p, _) => p.clone(), CorrectionMode::VelocityAndPositionThresold(_, ref p, _) => p.clone(), CorrectionMode::Velocity(_) => na::zero() } } #[inline] pub fn min_depth_for_pos_corr(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, _, ref t) => t.clone(), CorrectionMode::VelocityAndPositionThresold(_, _, ref t) => t.clone(), CorrectionMode::Velocity(_) => Bounded::max_value() } } #[inline] pub fn max_depth_for_vel_corr(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, _, _) => Bounded::max_value(), CorrectionMode::VelocityAndPositionThresold(_, _, ref t) => t.clone(), CorrectionMode::Velocity(_) => Bounded::max_value() } } } pub struct CorrectionParameters { pub corr_mode: CorrectionMode, pub joint_corr: Scalar, pub rest_eps: Scalar } pub fn reinit_to_first_order_equation(dt: Scalar, coll: &Contact<Point>, constraint: &mut VelocityConstraint, correction: &CorrectionParameters) { /* * Fill b */ if coll.depth >= correction.corr_mode.min_depth_for_pos_corr() { constraint.objective = correction.corr_mode.pos_corr_factor() * coll.depth.max(na::zero()) / dt; } else { constraint.objective = na::zero(); } /* * Reset forces */ constraint.impulse = na::zero(); } pub fn fill_second_order_equation(dt: Scalar, coll: &Contact<Point>, rb1: &RigidBody, rb2: &RigidBody, rconstraint: &mut VelocityConstraint, idr: usize, fconstraints: &mut [VelocityConstraint], idf: usize, cache: &[Scalar], correction: &CorrectionParameters) { let restitution = rb1.restitution() * rb2.restitution(); let center = na::center(&coll.world1, &coll.world2); fill_velocity_constraint(dt.clone(), coll.normal.clone(), center.clone(), restitution, coll.depth.clone(), cache[0].clone(), na::zero(), Bounded::max_value(), rb1, rb2, rconstraint, correction); let friction = rb1.friction() * rb2.friction(); let mut i = 0; na::orthonormal_subspace_basis(&coll.normal, |friction_axis| { let constraint = &mut fconstraints[idf + i]; fill_velocity_constraint(dt.clone(), friction_axis, center.clone(), na::zero(), na::zero(), cache[i + 1].clone(), na::zero(), na::zero(), rb1, rb2, constraint, correction); constraint.friction_coeff = friction.clone(); constraint.friction_limit_id = idr; i = i + 1; true }) } pub fn fill_constraint_geometry(normal: Vect, rot_axis1: Orientation, rot_axis2: Orientation, rb1: &Option<&RigidBody>, rb2: &Option<&RigidBody>, constraint: &mut VelocityConstraint) { constraint.normal = normal; constraint.inv_projected_mass = na::zero(); match *rb1 { Some(ref rb) => { constraint.weighted_normal1 = constraint.normal * rb.inv_mass(); constraint.rot_axis1 = rot_axis1; constraint.weighted_rot_axis1 = rb.inv_inertia().apply(&constraint.rot_axis1); constraint.inv_projected_mass = constraint.inv_projected_mass + na::dot(&constraint.normal, &constraint.weighted_normal1) + na::dot(&constraint.rot_axis1, &constraint.weighted_rot_axis1); }, None => { } } match *rb2 { Some(ref rb) => { constraint.weighted_normal2 = constraint.normal * rb.inv_mass(); constraint.rot_axis2 = rot_axis2; constraint.weighted_rot_axis2 = rb.inv_inertia().apply(&constraint.rot_axis2); constraint.inv_projected_mass = constraint.inv_projected_mass + na::dot(&constraint.normal, &constraint.weighted_normal2) + na::dot(&constraint.rot_axis2, &constraint.weighted_rot_axis2); }, None => { } } let _1: Scalar = na::one(); constraint.inv_projected_mass = _1 / constraint.inv_projected_mass; } fn fill_velocity_constraint(dt: Scalar, normal: Vect, center: Point, restitution: Scalar, depth: Scalar, initial_impulse: Scalar, lobound: Scalar, hibound: Scalar, rb1: &RigidBody, rb2: &RigidBody, constraint: &mut VelocityConstraint, correction: &CorrectionParameters) { let rot_axis1 = na::cross(&(center - *rb1.center_of_mass()), &-normal); let rot_axis2 = na::cross(&(center - *rb2.center_of_mass()), &normal); let opt_rb1 = if rb1.can_move() { Some(rb1) } else { None }; let opt_rb2 = if rb2.can_move() { Some(rb2) } else { None }; fill_constraint_geometry(normal, rot_axis1, rot_axis2, &opt_rb1, &opt_rb2, constraint); /* * Fill indice */ constraint.id1 = rb1.index(); constraint.id2 = rb2.index(); /* * correction amount */ constraint.objective = relative_velocity( &opt_rb1, &opt_rb2, &constraint.normal, &constraint.rot_axis1, &constraint.rot_axis2, &dt); if constraint.objective < -correction.rest_eps { constraint.objective = constraint.objective + restitution * constraint.objective } constraint.objective = -constraint.objective; if depth < na::zero() { constraint.objective = constraint.objective + depth / dt } else if depth < correction.corr_mode.max_depth_for_vel_corr() { constraint.objective = constraint.objective + depth * correction.corr_mode.vel_corr_factor() / dt } constraint.impulse = if depth < na::zero() { na::zero() } else { initial_impulse }; /* * constraint bounds */ constraint.lobound = lobound; constraint.hibound = hibound; } pub fn relative_velocity(rb1: &Option<&RigidBody>, rb2: &Option<&RigidBody>, normal: &Vect, rot_axis1: &Orientation, rot_axis2: &Orientation, dt: &Scalar) -> Scalar { let mut dvel: Scalar = na::zero(); match *rb1 { Some(ref rb) => { dvel = dvel - na::dot(&(rb.lin_vel() + rb.lin_acc() * *dt), normal) + na::dot(&(rb.ang_vel() + rb.ang_acc() * *dt), rot_axis1); }, None => { } } match *rb2 { Some(ref rb) => { dvel = dvel + na::dot(&(rb.lin_vel() + rb.lin_acc() * *dt), normal) + na::dot(&(rb.ang_vel() + rb.ang_acc() * *dt), rot_axis2); }, None => { } } dvel }
use na::Bounded; use na; use num::Float; use ncollide::geometry::Contact; use volumetric::InertiaTensor; use resolution::constraint::velocity_constraint::VelocityConstraint; use object::RigidBody; use math::{Scalar, Point, Vect, Orientation}; pub enum CorrectionMode { Velocity(Scalar), VelocityAndPosition(Scalar, Scalar, Scalar), VelocityAndPositionThresold(Scalar, Scalar, Scalar) } impl CorrectionMode { #[inline] pub fn vel_corr_factor(&self) -> Scalar { match *self { CorrectionMode::Velocity(ref v) => v.clone(), CorrectionMode::VelocityAndPosition(ref v, _, _) => v.clone(), CorrectionMode::VelocityAndPositionThresold(ref v, _, _) => v.clone() } } #[inline] pub fn pos_c
e::VelocityAndPositionThresold(_, ref p, _) => p.clone(), CorrectionMode::Velocity(_) => na::zero() } } #[inline] pub fn min_depth_for_pos_corr(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, _, ref t) => t.clone(), CorrectionMode::VelocityAndPositionThresold(_, _, ref t) => t.clone(), CorrectionMode::Velocity(_) => Bounded::max_value() } } #[inline] pub fn max_depth_for_vel_corr(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, _, _) => Bounded::max_value(), CorrectionMode::VelocityAndPositionThresold(_, _, ref t) => t.clone(), CorrectionMode::Velocity(_) => Bounded::max_value() } } } pub struct CorrectionParameters { pub corr_mode: CorrectionMode, pub joint_corr: Scalar, pub rest_eps: Scalar } pub fn reinit_to_first_order_equation(dt: Scalar, coll: &Contact<Point>, constraint: &mut VelocityConstraint, correction: &CorrectionParameters) { /* * Fill b */ if coll.depth >= correction.corr_mode.min_depth_for_pos_corr() { constraint.objective = correction.corr_mode.pos_corr_factor() * coll.depth.max(na::zero()) / dt; } else { constraint.objective = na::zero(); } /* * Reset forces */ constraint.impulse = na::zero(); } pub fn fill_second_order_equation(dt: Scalar, coll: &Contact<Point>, rb1: &RigidBody, rb2: &RigidBody, rconstraint: &mut VelocityConstraint, idr: usize, fconstraints: &mut [VelocityConstraint], idf: usize, cache: &[Scalar], correction: &CorrectionParameters) { let restitution = rb1.restitution() * rb2.restitution(); let center = na::center(&coll.world1, &coll.world2); fill_velocity_constraint(dt.clone(), coll.normal.clone(), center.clone(), restitution, coll.depth.clone(), cache[0].clone(), na::zero(), Bounded::max_value(), rb1, rb2, rconstraint, correction); let friction = rb1.friction() * rb2.friction(); let mut i = 0; na::orthonormal_subspace_basis(&coll.normal, |friction_axis| { let constraint = &mut fconstraints[idf + i]; fill_velocity_constraint(dt.clone(), friction_axis, center.clone(), na::zero(), na::zero(), cache[i + 1].clone(), na::zero(), na::zero(), rb1, rb2, constraint, correction); constraint.friction_coeff = friction.clone(); constraint.friction_limit_id = idr; i = i + 1; true }) } pub fn fill_constraint_geometry(normal: Vect, rot_axis1: Orientation, rot_axis2: Orientation, rb1: &Option<&RigidBody>, rb2: &Option<&RigidBody>, constraint: &mut VelocityConstraint) { constraint.normal = normal; constraint.inv_projected_mass = na::zero(); match *rb1 { Some(ref rb) => { constraint.weighted_normal1 = constraint.normal * rb.inv_mass(); constraint.rot_axis1 = rot_axis1; constraint.weighted_rot_axis1 = rb.inv_inertia().apply(&constraint.rot_axis1); constraint.inv_projected_mass = constraint.inv_projected_mass + na::dot(&constraint.normal, &constraint.weighted_normal1) + na::dot(&constraint.rot_axis1, &constraint.weighted_rot_axis1); }, None => { } } match *rb2 { Some(ref rb) => { constraint.weighted_normal2 = constraint.normal * rb.inv_mass(); constraint.rot_axis2 = rot_axis2; constraint.weighted_rot_axis2 = rb.inv_inertia().apply(&constraint.rot_axis2); constraint.inv_projected_mass = constraint.inv_projected_mass + na::dot(&constraint.normal, &constraint.weighted_normal2) + na::dot(&constraint.rot_axis2, &constraint.weighted_rot_axis2); }, None => { } } let _1: Scalar = na::one(); constraint.inv_projected_mass = _1 / constraint.inv_projected_mass; } fn fill_velocity_constraint(dt: Scalar, normal: Vect, center: Point, restitution: Scalar, depth: Scalar, initial_impulse: Scalar, lobound: Scalar, hibound: Scalar, rb1: &RigidBody, rb2: &RigidBody, constraint: &mut VelocityConstraint, correction: &CorrectionParameters) { let rot_axis1 = na::cross(&(center - *rb1.center_of_mass()), &-normal); let rot_axis2 = na::cross(&(center - *rb2.center_of_mass()), &normal); let opt_rb1 = if rb1.can_move() { Some(rb1) } else { None }; let opt_rb2 = if rb2.can_move() { Some(rb2) } else { None }; fill_constraint_geometry(normal, rot_axis1, rot_axis2, &opt_rb1, &opt_rb2, constraint); /* * Fill indice */ constraint.id1 = rb1.index(); constraint.id2 = rb2.index(); /* * correction amount */ constraint.objective = relative_velocity( &opt_rb1, &opt_rb2, &constraint.normal, &constraint.rot_axis1, &constraint.rot_axis2, &dt); if constraint.objective < -correction.rest_eps { constraint.objective = constraint.objective + restitution * constraint.objective } constraint.objective = -constraint.objective; if depth < na::zero() { constraint.objective = constraint.objective + depth / dt } else if depth < correction.corr_mode.max_depth_for_vel_corr() { constraint.objective = constraint.objective + depth * correction.corr_mode.vel_corr_factor() / dt } constraint.impulse = if depth < na::zero() { na::zero() } else { initial_impulse }; /* * constraint bounds */ constraint.lobound = lobound; constraint.hibound = hibound; } pub fn relative_velocity(rb1: &Option<&RigidBody>, rb2: &Option<&RigidBody>, normal: &Vect, rot_axis1: &Orientation, rot_axis2: &Orientation, dt: &Scalar) -> Scalar { let mut dvel: Scalar = na::zero(); match *rb1 { Some(ref rb) => { dvel = dvel - na::dot(&(rb.lin_vel() + rb.lin_acc() * *dt), normal) + na::dot(&(rb.ang_vel() + rb.ang_acc() * *dt), rot_axis1); }, None => { } } match *rb2 { Some(ref rb) => { dvel = dvel + na::dot(&(rb.lin_vel() + rb.lin_acc() * *dt), normal) + na::dot(&(rb.ang_vel() + rb.ang_acc() * *dt), rot_axis2); }, None => { } } dvel }
orr_factor(&self) -> Scalar { match *self { CorrectionMode::VelocityAndPosition(_, ref p, _) => p.clone(), CorrectionMod
function_block-random_span
[]
Rust
src/hs_types.rs
a-mackay/raystack
26837f3c148f0e21ba529f40925828e3f291c333
use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::{FromHaysonError, Hayson}; use serde_json::{json, Value}; use std::convert::From; const KIND: &str = "_kind"; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Date(NaiveDate); impl Date { pub fn new(naive_date: NaiveDate) -> Self { Date(naive_date) } pub fn naive_date(&self) -> &NaiveDate { &self.0 } pub fn into_naive_date(self) -> NaiveDate { self.0 } } impl Hayson for Date { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { match &value { Value::Object(obj) => { if let Some(kind_err) = hayson_check_kind("date", value) { return Err(kind_err); } let val = obj.get("val"); if val.is_none() { return hayson_error("Date val is missing"); } let val = val.unwrap().as_str(); if val.is_none() { return hayson_error("Date val is not a string"); } let val = val.unwrap(); match val.parse() { Ok(naive_date) => Ok(Date::new(naive_date)), Err(_) => hayson_error( "Date val string could not be parsed as a NaiveDate", ), } } _ => hayson_error("Date JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "date", "val": self.naive_date().to_string(), }) } } impl From<NaiveDate> for Date { fn from(d: NaiveDate) -> Self { Self::new(d) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Time(NaiveTime); impl Time { pub fn new(naive_time: NaiveTime) -> Self { Time(naive_time) } pub fn naive_time(&self) -> &NaiveTime { &self.0 } pub fn into_naive_time(self) -> NaiveTime { self.0 } } impl Hayson for Time { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { match &value { Value::Object(obj) => { if let Some(kind_err) = hayson_check_kind("time", value) { return Err(kind_err); } let val = obj.get("val"); if val.is_none() { return hayson_error("Time val is missing"); } let val = val.unwrap().as_str(); if val.is_none() { return hayson_error("Time val is not a string"); } let val = val.unwrap(); match val.parse() { Ok(naive_time) => Ok(Time::new(naive_time)), Err(_) => hayson_error( "Time val string could not be parsed as a NaiveTime", ), } } _ => hayson_error("Time JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "time", "val": self.naive_time().to_string(), }) } } impl From<NaiveTime> for Time { fn from(t: NaiveTime) -> Self { Self::new(t) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct DateTime { date_time: chrono::DateTime<Tz>, } impl DateTime { pub fn new(date_time: chrono::DateTime<Tz>) -> Self { Self { date_time } } pub fn date_time(&self) -> &chrono::DateTime<Tz> { &self.date_time } pub fn into_date_time(self) -> chrono::DateTime<Tz> { self.date_time } pub fn time_zone(&self) -> &str { self.date_time.timezone().name() } pub fn short_time_zone(&self) -> &str { crate::tz::time_zone_name_to_short_name(self.time_zone()) } } impl Hayson for DateTime { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { let default_tz = "GMT"; match &value { Value::Object(obj) => { if let Some(kind_err) = hayson_check_kind("dateTime", value) { return Err(kind_err); } let tz_value = obj.get("tz"); let mut tz_str = default_tz.to_owned(); if let Some(value) = tz_value { match value { Value::Null => { tz_str = default_tz.to_owned(); } Value::String(tz_string) => { tz_str = tz_string.clone(); } _ => { return hayson_error( "DateTime tz is not a null or a string", ) } } } let dt = obj.get("val"); if dt.is_none() { return hayson_error("DateTime val is missing"); } let dt = dt.unwrap().as_str(); if dt.is_none() { return hayson_error("DateTime val is not a string"); } let dt = dt.unwrap(); match chrono::DateTime::parse_from_rfc3339(dt) { Ok(dt) => { let tz = crate::skyspark_tz_string_to_tz(&tz_str); if let Some(tz) = tz { let dt = dt.with_timezone(&tz); Ok(DateTime::new(dt)) } else { hayson_error(format!("DateTime tz '{}' has no matching chrono_tz time zone", tz_str)) } } Err(_) => hayson_error( "Time val string could not be parsed as a NaiveTime", ), } } _ => hayson_error("Time JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "dateTime", "val": self.date_time().to_rfc3339(), "tz": self.short_time_zone(), }) } } impl From<chrono::DateTime<Tz>> for DateTime { fn from(dt: chrono::DateTime<Tz>) -> Self { Self::new(dt) } } fn hayson_error<T, M>(message: M) -> Result<T, FromHaysonError> where M: AsRef<str>, { Err(FromHaysonError::new(message.as_ref().to_owned())) } fn hayson_error_opt<M>(message: M) -> Option<FromHaysonError> where M: AsRef<str>, { Some(FromHaysonError::new(message.as_ref().to_owned())) } fn hayson_check_kind( target_kind: &str, value: &Value, ) -> Option<FromHaysonError> { match value.get(KIND) { Some(kind) => match kind { Value::String(kind) => { if kind == target_kind { None } else { hayson_error_opt(format!( "Expected '{}' = {} but found {}", KIND, kind, kind )) } } _ => hayson_error_opt(format!("'{}' key is not a string", KIND)), }, None => hayson_error_opt(format!("Missing '{}' key", KIND)), } } #[cfg(test)] mod test { use crate::{Date, DateTime, Time}; use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::Hayson; #[test] fn serde_date_works() { let naive_date = NaiveDate::from_ymd(2021, 1, 1); let x = Date::new(naive_date); let value = x.to_hayson(); let deserialized = Date::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_time_works() { let naive_time = NaiveTime::from_hms(2, 15, 59); let x = Time::new(naive_time); let value = x.to_hayson(); let deserialized = Time::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::GMT); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_with_one_slash_tz_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::Australia__Sydney); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_with_multiple_slashes_tz_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::America__North_Dakota__Beulah); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn short_time_zone_works() { let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::America__North_Dakota__Beulah) .into(); assert_eq!(dt.short_time_zone(), "Beulah"); let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::GMT) .into(); assert_eq!(dt.short_time_zone(), "GMT"); let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::Australia__Sydney) .into(); assert_eq!(dt.short_time_zone(), "Sydney"); } }
use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::{FromHaysonError, Hayson}; use serde_json::{json, Value}; use std::convert::From; const KIND: &str = "_kind"; #[derive(Clone, Debug, Eq, PartialEq)] pub struct Date(NaiveDate); impl Date { pub fn new(naive_date: NaiveDate) -> Self { Date(naive_date) } pub fn naive_date(&self) -> &NaiveDate { &self.0 } pub fn into_naive_date(self) -> NaiveDate { self.0 } } impl Hayson for Date { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { match &value { Value::Object(obj) => { if let Some(kind_err) = hayson_check_kind("date", value) { return Err(kind_err); } let val = obj.get("val"); if val.is_none() { return hayson_error("Date val is missing"); } let val = val.unwrap().as_str(); if val.is_none() { return hayson_error("Date val is not a string"); } let val = val.unwrap(); match val.parse() { Ok(naive_date) => Ok(Date::new(naive_date)), Err(_) => hayson_error( "Date val string could not be parsed as a NaiveDate", ), } } _ => hayson_error("Date JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "date", "val": self.naive_date().to_string(), }) } } impl From<NaiveDate> for Date { fn from(d: NaiveDate) -> Self { Self::new(d) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct Time(NaiveTime); impl Time { pub fn new(naive_time: NaiveTime) -> Self { Time(naive_time) } pub fn naive_time(&self) -> &NaiveTime { &self.0 } pub fn into_naive_time(self) -> NaiveTime { self.0 } } impl Hayson for Time { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { match &value { Value::Object(obj) => { if let Some(kind_err) = hayson_check_kind("time", value) { return Err(kind_err); } let val = obj.get("val"); if val.is_none() { return hayson_error("Time val is missing"); } let val = val.unwrap().as_str(); if val.is_none() { return hayson_error("Time val is not a string"); } let val = val.unwrap(); match val.parse() { Ok(naive_time) => Ok(Time::new(naive_time)), Err(_) => hayson_error( "Time val string could not be parsed as a NaiveTime", ), } } _ => hayson_error("Time JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "time", "val": self.naive_time().to_string(), }) } } impl From<NaiveTime> for Time { fn from(t: NaiveTime) -> Self { Self::new(t) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct DateTime { date_time: chrono::DateTime<Tz>, } impl DateTime { pub fn new(date_time: chrono::DateTime<Tz>) -> Self { Self { date_time } } pub fn date_time(&self) -> &chrono::DateTime<Tz> { &self.date_time } pub fn into_date_time(self) -> chrono::DateTime<Tz> { self.date_time } pub fn time_zone(&self) -> &str { self.date_time.timezone().name() } pub fn short_time_zone(&self) -> &str { crate::tz::time_zone_name_to_short_name(self.time_zone()) } } impl Hayson for DateTime { fn from_hayson(value: &Value) -> Result<Self, FromHaysonError> { let default_tz = "GMT"; match &value { Value::Object(obj) => {
let tz_value = obj.get("tz"); let mut tz_str = default_tz.to_owned(); if let Some(value) = tz_value { match value { Value::Null => { tz_str = default_tz.to_owned(); } Value::String(tz_string) => { tz_str = tz_string.clone(); } _ => { return hayson_error( "DateTime tz is not a null or a string", ) } } } let dt = obj.get("val"); if dt.is_none() { return hayson_error("DateTime val is missing"); } let dt = dt.unwrap().as_str(); if dt.is_none() { return hayson_error("DateTime val is not a string"); } let dt = dt.unwrap(); match chrono::DateTime::parse_from_rfc3339(dt) { Ok(dt) => { let tz = crate::skyspark_tz_string_to_tz(&tz_str); if let Some(tz) = tz { let dt = dt.with_timezone(&tz); Ok(DateTime::new(dt)) } else { hayson_error(format!("DateTime tz '{}' has no matching chrono_tz time zone", tz_str)) } } Err(_) => hayson_error( "Time val string could not be parsed as a NaiveTime", ), } } _ => hayson_error("Time JSON value must be an object"), } } fn to_hayson(&self) -> Value { json!({ KIND: "dateTime", "val": self.date_time().to_rfc3339(), "tz": self.short_time_zone(), }) } } impl From<chrono::DateTime<Tz>> for DateTime { fn from(dt: chrono::DateTime<Tz>) -> Self { Self::new(dt) } } fn hayson_error<T, M>(message: M) -> Result<T, FromHaysonError> where M: AsRef<str>, { Err(FromHaysonError::new(message.as_ref().to_owned())) } fn hayson_error_opt<M>(message: M) -> Option<FromHaysonError> where M: AsRef<str>, { Some(FromHaysonError::new(message.as_ref().to_owned())) } fn hayson_check_kind( target_kind: &str, value: &Value, ) -> Option<FromHaysonError> { match value.get(KIND) { Some(kind) => match kind { Value::String(kind) => { if kind == target_kind { None } else { hayson_error_opt(format!( "Expected '{}' = {} but found {}", KIND, kind, kind )) } } _ => hayson_error_opt(format!("'{}' key is not a string", KIND)), }, None => hayson_error_opt(format!("Missing '{}' key", KIND)), } } #[cfg(test)] mod test { use crate::{Date, DateTime, Time}; use chrono::{NaiveDate, NaiveTime}; use chrono_tz::Tz; use raystack_core::Hayson; #[test] fn serde_date_works() { let naive_date = NaiveDate::from_ymd(2021, 1, 1); let x = Date::new(naive_date); let value = x.to_hayson(); let deserialized = Date::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_time_works() { let naive_time = NaiveTime::from_hms(2, 15, 59); let x = Time::new(naive_time); let value = x.to_hayson(); let deserialized = Time::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::GMT); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_with_one_slash_tz_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::Australia__Sydney); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn serde_date_time_with_multiple_slashes_tz_works() { let dt = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::America__North_Dakota__Beulah); let x = DateTime::new(dt); let value = x.to_hayson(); let deserialized = DateTime::from_hayson(&value).unwrap(); assert_eq!(x, deserialized); } #[test] fn short_time_zone_works() { let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::America__North_Dakota__Beulah) .into(); assert_eq!(dt.short_time_zone(), "Beulah"); let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::GMT) .into(); assert_eq!(dt.short_time_zone(), "GMT"); let dt: DateTime = chrono::DateTime::parse_from_rfc3339("2021-01-01T18:30:09.453Z") .unwrap() .with_timezone(&Tz::Australia__Sydney) .into(); assert_eq!(dt.short_time_zone(), "Sydney"); } }
if let Some(kind_err) = hayson_check_kind("dateTime", value) { return Err(kind_err); }
if_condition
[ { "content": "/// Convert a `DateTime` into a string which can be used in ZINC files.\n\nfn to_zinc_encoded_string(date_time: &DateTime) -> String {\n\n let time_zone_name = date_time.short_time_zone();\n\n format!(\n\n \"{} {}\",\n\n date_time\n\n .date_time()\n\n .to_...
Rust
src/timestamp.rs
Cognoscan/fog_pack
7b3af246faa851bfc2aa09cc186ff2332124e791
use std::cmp; use std::convert::TryFrom; use std::fmt; use std::ops; use std::time; use byteorder::{LittleEndian, ReadBytesExt}; use fog_crypto::serde::{ CryptoEnum, FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX, FOG_TYPE_ENUM_TIME_NAME, }; use serde::{ de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected, VariantAccess}, ser::{Serialize, SerializeStructVariant, Serializer}, }; use serde_bytes::ByteBuf; const MAX_NANOSEC: u32 = 1_999_999_999; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct Timestamp { sec: i64, nano: u32, standard: u8, } impl Timestamp { pub fn from_utc(sec: i64, nano: u32) -> Option<Timestamp> { if nano > MAX_NANOSEC { None } else { Some(Timestamp { sec, nano, standard: 0, }) } } pub fn from_sec(sec: i64) -> Timestamp { Timestamp { sec, nano: 0, standard: 0, } } pub const fn zero() -> Timestamp { Timestamp { sec: 0, nano: 0, standard: 0, } } pub const fn min_value() -> Timestamp { Timestamp { sec: i64::MIN, nano: 0, standard: 0, } } pub const fn max_value() -> Timestamp { Timestamp { sec: i64::MAX, nano: MAX_NANOSEC, standard: 0, } } pub fn min(self, other: Timestamp) -> Timestamp { if self < other { self } else { other } } pub fn max(self, other: Timestamp) -> Timestamp { if self > other { self } else { other } } pub fn next(mut self) -> Timestamp { if self.nano < MAX_NANOSEC { self.nano += 1; } else { self.nano = 0; self.sec += 1; } self } pub fn prev(mut self) -> Timestamp { if self.nano > 0 { self.nano -= 1; } else { self.nano = MAX_NANOSEC; self.sec -= 1; } self } pub fn timestamp_utc(&self) -> i64 { self.sec } pub fn timestamp_subsec_nanos(&self) -> u32 { self.nano } pub fn as_vec(&self) -> Vec<u8> { let mut v = Vec::new(); self.encode_vec(&mut v); v } pub fn encode_vec(&self, vec: &mut Vec<u8>) { if self.nano != 0 { vec.reserve(1 + 8 + 4); vec.push(self.standard); vec.extend_from_slice(&self.sec.to_le_bytes()); vec.extend_from_slice(&self.nano.to_le_bytes()); } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { vec.reserve(1 + 4); vec.push(self.standard); vec.extend_from_slice(&(self.sec as u32).to_le_bytes()); } else { vec.reserve(1 + 8); vec.push(self.standard); vec.extend_from_slice(&self.sec.to_le_bytes()); } } pub fn size(&self) -> usize { if self.nano != 0 { 1 + 8 + 4 } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { 1 + 4 } else { 1 + 8 } } pub fn now() -> Option<Timestamp> { match time::SystemTime::now().duration_since(time::SystemTime::UNIX_EPOCH) { Ok(t) => Timestamp::from_utc(t.as_secs() as i64, t.subsec_nanos()), Err(_) => None, } } } impl ops::Add<i64> for Timestamp { type Output = Timestamp; fn add(self, rhs: i64) -> Self { Timestamp { sec: self.sec + rhs, nano: self.nano, standard: self.standard, } } } impl ops::Sub<i64> for Timestamp { type Output = Timestamp; fn sub(self, rhs: i64) -> Self { Timestamp { sec: self.sec - rhs, nano: self.nano, standard: self.standard, } } } impl cmp::Ord for Timestamp { fn cmp(&self, other: &Timestamp) -> cmp::Ordering { match self.sec.cmp(&other.sec) { cmp::Ordering::Equal => self.nano.cmp(&other.nano), other => other, } } } impl cmp::PartialOrd for Timestamp { fn partial_cmp(&self, other: &Timestamp) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl fmt::Display for Timestamp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UTC: {} sec + {} ns", self.sec, self.nano) } } impl TryFrom<&[u8]> for Timestamp { type Error = String; fn try_from(value: &[u8]) -> Result<Self, Self::Error> { let mut raw = value; let standard = raw .read_u8() .map_err(|_| String::from("missing time standard byte"))?; let (sec, nano) = match value.len() { 13 => { let sec = raw.read_i64::<LittleEndian>().unwrap(); let nano = raw.read_u32::<LittleEndian>().unwrap(); (sec, nano) } 9 => { let sec = raw.read_i64::<LittleEndian>().unwrap(); (sec, 0) } 5 => { let sec = raw.read_u32::<LittleEndian>().unwrap() as i64; (sec, 0) } _ => { return Err(format!( "not a recognized Timestamp length ({} bytes)", value.len() )) } }; Ok(Timestamp { sec, nano, standard, }) } } impl Serialize for Timestamp { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_human_readable() { let mut sv = serializer.serialize_struct_variant( FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX as u32, FOG_TYPE_ENUM_TIME_NAME, 2, )?; sv.serialize_field("std", &self.standard)?; sv.serialize_field("secs", &self.sec)?; sv.serialize_field("nanos", &self.sec)?; sv.end() } else { let value = ByteBuf::from(self.as_vec()); serializer.serialize_newtype_variant( FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX as u32, FOG_TYPE_ENUM_TIME_NAME, &value, ) } } } impl<'de> Deserialize<'de> for Timestamp { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct TimeVisitor { is_human_readable: bool, } impl<'de> serde::de::Visitor<'de> for TimeVisitor { type Value = Timestamp; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!( fmt, "{} enum with variant {} (id {})", FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_NAME, FOG_TYPE_ENUM_TIME_INDEX ) } fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> where A: EnumAccess<'de>, { let variant = match data.variant()? { (CryptoEnum::Time, variant) => variant, (e, _) => { return Err(A::Error::invalid_type( Unexpected::Other(e.as_str()), &"Time", )) } }; if self.is_human_readable { use serde::de::MapAccess; struct TimeStructVisitor; impl<'de> serde::de::Visitor<'de> for TimeStructVisitor { type Value = Timestamp; fn expecting( &self, fmt: &mut fmt::Formatter<'_>, ) -> Result<(), fmt::Error> { write!(fmt, "timestamp struct") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut secs: Option<i64> = None; let mut nanos: u32 = 0; while let Some(key) = map.next_key::<String>()? { match key.as_ref() { "std" => { let v: u8 = map.next_value()?; if v != 0 { return Err(A::Error::invalid_value( Unexpected::Unsigned(v as u64), &"0", )); } } "secs" => { secs = Some(map.next_value()?); } "nanos" => { nanos = map.next_value()?; } _ => { return Err(A::Error::unknown_field( key.as_ref(), &["std", "secs", "nanos"], )) } } } let secs = secs.ok_or_else(|| A::Error::missing_field("secs"))?; Timestamp::from_utc(secs, nanos) .ok_or_else(|| A::Error::custom("Invalid timestamp")) } } variant.struct_variant(&["std", "secs", "nanos"], TimeStructVisitor) } else { let bytes: ByteBuf = variant.newtype_variant()?; Timestamp::try_from(bytes.as_ref()).map_err(A::Error::custom) } } } let is_human_readable = deserializer.is_human_readable(); deserializer.deserialize_enum( FOG_TYPE_ENUM, &[FOG_TYPE_ENUM_TIME_NAME], TimeVisitor { is_human_readable }, ) } } #[cfg(test)] mod test { use super::*; fn edge_cases() -> Vec<(usize, Timestamp)> { let mut test_cases = Vec::new(); test_cases.push((5, Timestamp::from_utc(0, 0).unwrap())); test_cases.push((5, Timestamp::from_utc(1, 0).unwrap())); test_cases.push((13, Timestamp::from_utc(1, 1).unwrap())); test_cases.push((5, Timestamp::from_utc(u32::MAX as i64 - 1, 0).unwrap())); test_cases.push((5, Timestamp::from_utc(u32::MAX as i64 - 0, 0).unwrap())); test_cases.push((9, Timestamp::from_utc(u32::MAX as i64 + 1, 0).unwrap())); test_cases.push((9, Timestamp::from_utc(i64::MIN, 0).unwrap())); test_cases.push((13, Timestamp::from_utc(i64::MIN, 1).unwrap())); test_cases } #[test] fn roundtrip() { for (index, case) in edge_cases().iter().enumerate() { println!( "Test #{}: '{}' with expected length = {}", index, case.1, case.0 ); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); assert_eq!(enc.len(), case.0); let decoded = Timestamp::try_from(enc.as_ref()).unwrap(); assert_eq!(decoded, case.1); } } #[test] fn too_long() { for case in edge_cases() { println!("Test with Timestamp = {}", case.1); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); enc.push(0u8); assert!(Timestamp::try_from(enc.as_ref()).is_err()); } } #[test] fn too_short() { for case in edge_cases() { println!("Test with Timestamp = {}", case.1); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); enc.pop(); assert!(Timestamp::try_from(enc.as_ref()).is_err()); } } }
use std::cmp; use std::convert::TryFrom; use std::fmt; use std::ops; use std::time; use byteorder::{LittleEndian, ReadBytesExt}; use fog_crypto::serde::{ CryptoEnum, FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX, FOG_TYPE_ENUM_TIME_NAME, }; use serde::{ de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected, VariantAccess}, ser::{Serialize, SerializeStructVariant, Serializer}, }; use serde_bytes::ByteBuf; const MAX_NANOSEC: u32 = 1_999_999_999; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct Timestamp { sec: i64, nano: u32, standard: u8, } impl Timestamp { pub fn from_utc(sec: i64, nano: u32) -> Option<Timestamp> { if nano > MAX_NANOSEC { None } else { Some(Timestamp { sec, nano, standard: 0, }) } } pub fn from_sec(sec: i64) -> Timestamp { Timestamp { sec, nano: 0, standard: 0, } } pub const fn zero() -> Timestamp { Timestamp { sec: 0, nano: 0, standard: 0, } } pub const fn min_value() -> Timestamp { Timestamp { sec: i64::MIN, nano: 0, standard: 0, } } pub const fn max_value() -> Timestamp { Timestamp { sec: i64::MAX, nano: MAX_NANOSEC, standard: 0, } } pub fn min(self, other: Timestamp) -> Timestamp { if self < other { self } else { other } } pub fn max(self, other: Timestamp) -> Timestamp { if self > other { self } else { other } } pub fn next(mut self) -> Timestamp { if self.nano < MAX_NANOSEC { self.nano += 1; } else { self.nano = 0; self.sec += 1; } self } pub fn prev(mut self) -> Timestamp { if self.nano > 0 { self.nano -= 1; } else { self.nano = MAX_NANOSEC; self.sec -= 1; } self } pub fn timestamp_utc(&self) -> i64 { self.sec } pub fn timestamp_subsec_nanos(&self) -> u32 { self.nano } pub fn as_vec(&self) -> Vec<u8> { let mut v = Vec::new(); self.encode_vec(&mut v); v } pub fn encode_vec(&self, vec: &mut Vec<u8>) { if self.nano != 0 { vec.reserve(1 + 8 + 4);
pub fn size(&self) -> usize { if self.nano != 0 { 1 + 8 + 4 } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { 1 + 4 } else { 1 + 8 } } pub fn now() -> Option<Timestamp> { match time::SystemTime::now().duration_since(time::SystemTime::UNIX_EPOCH) { Ok(t) => Timestamp::from_utc(t.as_secs() as i64, t.subsec_nanos()), Err(_) => None, } } } impl ops::Add<i64> for Timestamp { type Output = Timestamp; fn add(self, rhs: i64) -> Self { Timestamp { sec: self.sec + rhs, nano: self.nano, standard: self.standard, } } } impl ops::Sub<i64> for Timestamp { type Output = Timestamp; fn sub(self, rhs: i64) -> Self { Timestamp { sec: self.sec - rhs, nano: self.nano, standard: self.standard, } } } impl cmp::Ord for Timestamp { fn cmp(&self, other: &Timestamp) -> cmp::Ordering { match self.sec.cmp(&other.sec) { cmp::Ordering::Equal => self.nano.cmp(&other.nano), other => other, } } } impl cmp::PartialOrd for Timestamp { fn partial_cmp(&self, other: &Timestamp) -> Option<cmp::Ordering> { Some(self.cmp(other)) } } impl fmt::Display for Timestamp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UTC: {} sec + {} ns", self.sec, self.nano) } } impl TryFrom<&[u8]> for Timestamp { type Error = String; fn try_from(value: &[u8]) -> Result<Self, Self::Error> { let mut raw = value; let standard = raw .read_u8() .map_err(|_| String::from("missing time standard byte"))?; let (sec, nano) = match value.len() { 13 => { let sec = raw.read_i64::<LittleEndian>().unwrap(); let nano = raw.read_u32::<LittleEndian>().unwrap(); (sec, nano) } 9 => { let sec = raw.read_i64::<LittleEndian>().unwrap(); (sec, 0) } 5 => { let sec = raw.read_u32::<LittleEndian>().unwrap() as i64; (sec, 0) } _ => { return Err(format!( "not a recognized Timestamp length ({} bytes)", value.len() )) } }; Ok(Timestamp { sec, nano, standard, }) } } impl Serialize for Timestamp { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if serializer.is_human_readable() { let mut sv = serializer.serialize_struct_variant( FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX as u32, FOG_TYPE_ENUM_TIME_NAME, 2, )?; sv.serialize_field("std", &self.standard)?; sv.serialize_field("secs", &self.sec)?; sv.serialize_field("nanos", &self.sec)?; sv.end() } else { let value = ByteBuf::from(self.as_vec()); serializer.serialize_newtype_variant( FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_INDEX as u32, FOG_TYPE_ENUM_TIME_NAME, &value, ) } } } impl<'de> Deserialize<'de> for Timestamp { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct TimeVisitor { is_human_readable: bool, } impl<'de> serde::de::Visitor<'de> for TimeVisitor { type Value = Timestamp; fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { write!( fmt, "{} enum with variant {} (id {})", FOG_TYPE_ENUM, FOG_TYPE_ENUM_TIME_NAME, FOG_TYPE_ENUM_TIME_INDEX ) } fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> where A: EnumAccess<'de>, { let variant = match data.variant()? { (CryptoEnum::Time, variant) => variant, (e, _) => { return Err(A::Error::invalid_type( Unexpected::Other(e.as_str()), &"Time", )) } }; if self.is_human_readable { use serde::de::MapAccess; struct TimeStructVisitor; impl<'de> serde::de::Visitor<'de> for TimeStructVisitor { type Value = Timestamp; fn expecting( &self, fmt: &mut fmt::Formatter<'_>, ) -> Result<(), fmt::Error> { write!(fmt, "timestamp struct") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut secs: Option<i64> = None; let mut nanos: u32 = 0; while let Some(key) = map.next_key::<String>()? { match key.as_ref() { "std" => { let v: u8 = map.next_value()?; if v != 0 { return Err(A::Error::invalid_value( Unexpected::Unsigned(v as u64), &"0", )); } } "secs" => { secs = Some(map.next_value()?); } "nanos" => { nanos = map.next_value()?; } _ => { return Err(A::Error::unknown_field( key.as_ref(), &["std", "secs", "nanos"], )) } } } let secs = secs.ok_or_else(|| A::Error::missing_field("secs"))?; Timestamp::from_utc(secs, nanos) .ok_or_else(|| A::Error::custom("Invalid timestamp")) } } variant.struct_variant(&["std", "secs", "nanos"], TimeStructVisitor) } else { let bytes: ByteBuf = variant.newtype_variant()?; Timestamp::try_from(bytes.as_ref()).map_err(A::Error::custom) } } } let is_human_readable = deserializer.is_human_readable(); deserializer.deserialize_enum( FOG_TYPE_ENUM, &[FOG_TYPE_ENUM_TIME_NAME], TimeVisitor { is_human_readable }, ) } } #[cfg(test)] mod test { use super::*; fn edge_cases() -> Vec<(usize, Timestamp)> { let mut test_cases = Vec::new(); test_cases.push((5, Timestamp::from_utc(0, 0).unwrap())); test_cases.push((5, Timestamp::from_utc(1, 0).unwrap())); test_cases.push((13, Timestamp::from_utc(1, 1).unwrap())); test_cases.push((5, Timestamp::from_utc(u32::MAX as i64 - 1, 0).unwrap())); test_cases.push((5, Timestamp::from_utc(u32::MAX as i64 - 0, 0).unwrap())); test_cases.push((9, Timestamp::from_utc(u32::MAX as i64 + 1, 0).unwrap())); test_cases.push((9, Timestamp::from_utc(i64::MIN, 0).unwrap())); test_cases.push((13, Timestamp::from_utc(i64::MIN, 1).unwrap())); test_cases } #[test] fn roundtrip() { for (index, case) in edge_cases().iter().enumerate() { println!( "Test #{}: '{}' with expected length = {}", index, case.1, case.0 ); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); assert_eq!(enc.len(), case.0); let decoded = Timestamp::try_from(enc.as_ref()).unwrap(); assert_eq!(decoded, case.1); } } #[test] fn too_long() { for case in edge_cases() { println!("Test with Timestamp = {}", case.1); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); enc.push(0u8); assert!(Timestamp::try_from(enc.as_ref()).is_err()); } } #[test] fn too_short() { for case in edge_cases() { println!("Test with Timestamp = {}", case.1); let mut enc = Vec::new(); case.1.encode_vec(&mut enc); enc.pop(); assert!(Timestamp::try_from(enc.as_ref()).is_err()); } } }
vec.push(self.standard); vec.extend_from_slice(&self.sec.to_le_bytes()); vec.extend_from_slice(&self.nano.to_le_bytes()); } else if (self.sec <= u32::MAX as i64) && (self.sec >= 0) { vec.reserve(1 + 4); vec.push(self.standard); vec.extend_from_slice(&(self.sec as u32).to_le_bytes()); } else { vec.reserve(1 + 8); vec.push(self.standard); vec.extend_from_slice(&self.sec.to_le_bytes()); } }
function_block-function_prefix_line
[ { "content": "/// Serialize an element onto a byte vector. Doesn't check if Array & Map structures make\n\n/// sense, just writes elements out.\n\npub fn serialize_elem(buf: &mut Vec<u8>, elem: Element) {\n\n use self::Element::*;\n\n match elem {\n\n Null => buf.push(Marker::Null.into()),\n\n ...
Rust
src/main.rs
thehamsterjam/better_aws_sso
4a2fbee508c549dbba65fe17e7557fdb844581d3
use clap::{App, Arg}; use ini::Ini; use serde::Deserialize; use std::{thread, time}; use ureq::Response; use webbrowser; extern crate dirs; use std::time::{SystemTime, UNIX_EPOCH}; const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code"; #[derive(Debug)] #[allow(non_snake_case)] struct SsoProfile { sso_profile_name : String, sso_start_url: String, sso_region : String, sso_account_id : String, sso_role_name : String } impl SsoProfile { fn new( sso_profile_name : String, sso_start_url: String, sso_region : String, sso_account_id : String, sso_role_name : String) -> SsoProfile { SsoProfile{ sso_profile_name, sso_start_url, sso_region, sso_account_id, sso_role_name } } } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct RegisterClientResponse { clientId: String, clientIdIssuedAt: i32, clientSecret: String, clientSecretExpiresAt: i32, authorizationEndpoint: Option<String>, tokenEndpoint: Option<String>, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct StartDeviceAuthorizationResponse { deviceCode: String, expiresIn: i32, interval: i32, userCode: String, verificationUri: Option<String>, verificationUriComplete: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct CreateTokenResponse { accessToken: String, expiresIn: i32, idToken: Option<String>, refreshToken: Option<String>, tokenType: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct RoleCreds { accessKeyId: String, expiration: i64, secretAccessKey: String, sessionToken: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct GetRoleCredsResponse { roleCredentials: RoleCreds, } fn main() { static VERSION: &'static str = include_str!(concat!("", "version")); let matches = App::new("AWS SSO, but better") .version(VERSION) .author("Damien Maier") .author("Saves your SSO login credentials into the credentials file, so it can be used with things like terraform") .arg(Arg::with_name("profile") .short("p") .long("profile") .takes_value(true) .required(true) .help("AWS profile set up for SSO")) .arg(Arg::with_name("save_as_profile_name") .short("s") .long("save_as_profile_name") .help("Whether to save the credentials under the profile name with an _ at the end or under <account_id>_<role_name>")) .arg(Arg::with_name("all") .short("a") .long("all") .help("Get credentials for all profiles with the same start url as the specified profile")) .arg(Arg::with_name("verbose") .short("v") .long("verbose") .help("Print verbose logging")) .get_matches(); let profile = matches.value_of("profile").unwrap().to_owned(); let verbose = matches.is_present("verbose"); let save_as_profile_name = matches.is_present("save_as_profile_name"); let all = matches.is_present("all"); let home = dirs::home_dir().unwrap().to_str().unwrap().to_owned(); let sso_profiles = get_sso_profiles(profile, &home, all); let oidc_url = format!("https://oidc.{}.amazonaws.com", sso_profiles[0].sso_region); let sso_url = format!("https://portal.sso.{}.amazonaws.com", sso_profiles[0].sso_region); let register_client_resp = register_client(&oidc_url, verbose); let device_auth_resp = device_auth(&oidc_url, &sso_profiles[0].sso_start_url, &register_client_resp, verbose); let create_token_resp = create_token(&oidc_url, &register_client_resp, &device_auth_resp, verbose); for sso_profile in sso_profiles { let get_role_creds_resp = get_role_credentials( &sso_url, &sso_profile.sso_account_id, &sso_profile.sso_role_name, &create_token_resp, verbose, ); save_sso( &sso_profile.sso_profile_name, &sso_profile.sso_account_id, &sso_profile.sso_role_name, &get_role_creds_resp, &home, save_as_profile_name, verbose, ); } } fn get_sso_profiles(profile_name : String, home : &String, all : bool) -> Vec<SsoProfile> { let aws_conf = Ini::load_from_file(format!("{}{}", home, "/.aws/config")).unwrap(); let sso_start_url = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_start_url") .unwrap().to_owned(); let sso_region = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_region") .unwrap().to_owned(); let sso_account_id = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_account_id") .unwrap().to_owned(); let sso_role_name = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_role_name") .unwrap().to_owned(); if !all { return vec![SsoProfile::new(profile_name, sso_start_url, sso_region, sso_account_id, sso_role_name)] } else { let mut profiles = Vec::new(); for (section, properties) in aws_conf.iter() { if properties.contains_key("sso_start_url") { if properties.get("sso_start_url").unwrap() == sso_start_url { profiles.push(SsoProfile::new( section.unwrap().to_owned(), properties.get("sso_start_url").unwrap().to_owned(), properties.get("sso_region").unwrap().to_owned(), properties.get("sso_account_id").unwrap().to_owned(), properties.get("sso_role_name").unwrap().to_owned(), )) } } } return profiles; } } fn register_client(oidc_url: &String, verbose: bool) -> RegisterClientResponse { let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs(); let register_resp = ureq::post(format!("{}{}", oidc_url, "/client/register").as_str()) .set("Content-type", "application/json") .set("Action", "RegisterClient") .set("Version", "2019-06-10") .send_json(serde_json::json!({ "clientName" : format!("rustSSO-{}", since_the_epoch).as_str(), "clientType" : "public" })) .into_json_deserialize::<RegisterClientResponse>(); if verbose { println!("{:#?}", register_resp); } let register_resp_un = register_resp.unwrap(); if verbose { println!("{:#?}", register_resp_un); } register_resp_un } fn device_auth( oidc_url: &String, start_url: &String, register_resp: &RegisterClientResponse, verbose: bool, ) -> StartDeviceAuthorizationResponse { let device_auth_resp = ureq::post(format!("{}{}", oidc_url, "/device_authorization").as_str()) .set("Content-type", "application/json") .set("Action", "StartDeviceAuthorization") .set("Version", "2019-06-10") .send_json(serde_json::json!( { "clientId" : register_resp.clientId, "clientSecret" : register_resp.clientSecret, "startUrl" : start_url })) .into_json_deserialize::<StartDeviceAuthorizationResponse>(); if verbose { println!("{:#?}", device_auth_resp); } let device_auth_resp_un = device_auth_resp.unwrap(); if verbose { println!("{:#?}", device_auth_resp_un); } device_auth_resp_un } fn create_token( oidc_url: &String, register_resp: &RegisterClientResponse, device_auth_resp: &StartDeviceAuthorizationResponse, verbose: bool, ) -> CreateTokenResponse { if webbrowser::open(device_auth_resp.verificationUriComplete.as_str()).is_err() { println!( "Go to {}", device_auth_resp.verificationUriComplete.as_str() ); } let sec = time::Duration::from_secs(1); let create_tok_resp_un = loop { thread::sleep(sec); let create_tok_resp = ureq::post(format!("{}{}", oidc_url, "/token").as_str()) .set("Content-type", "application/json") .set("Action", "CreateToken") .set("Version", "2019-06-10") .send_json(serde_json::json!({ "clientId": register_resp.clientId, "clientSecret": register_resp.clientSecret, "deviceCode": device_auth_resp.deviceCode, "grantType": GRANT_TYPE, })); if verbose { println!("{:#?}", create_tok_resp); } if create_tok_resp.ok() { break create_tok_resp .into_json_deserialize::<CreateTokenResponse>() .unwrap(); } else { if verbose { println!("{:#?}", create_tok_resp.into_json()); } } }; if verbose { println!("{:#?}", create_tok_resp_un); } create_tok_resp_un } fn get_role_credentials( sso_url: &String, sso_account_id: &String, sso_role_name: &String, create_token_resp: &CreateTokenResponse, verbose: bool, ) -> GetRoleCredsResponse { let get_role_creds = ureq::get(format!("{}{}", sso_url, "/federation/credentials").as_str()) .query("account_id", sso_account_id) .query("role_name", sso_role_name) .set( "x-amz-sso_bearer_token", format!("{}", create_token_resp.accessToken).as_str(), ) .call() .into_json_deserialize::<GetRoleCredsResponse>(); if verbose { println!("{:#?}", get_role_creds); } let get_role_creds_un = get_role_creds.unwrap(); if verbose { println!("{:#?}", get_role_creds_un); } get_role_creds_un } fn save_sso( profile: &str, sso_account_id: &String, sso_role_name: &String, get_role_creds: &GetRoleCredsResponse, home_dir: &String, save_as_profile_name: bool, verbose: bool, ) { let section_name = if save_as_profile_name { format!("{}_", profile) } else { format!("{}_{}", sso_account_id, sso_role_name) }; let mut aws_creds = Ini::load_from_file(format!("{}{}", home_dir, "/.aws/credentials")).unwrap(); if verbose { println!("Section name : {}", section_name); } aws_creds .with_section(Some(section_name)) .set( "aws_access_key_id", get_role_creds.roleCredentials.accessKeyId.to_owned(), ) .set( "aws_secret_access_key", get_role_creds.roleCredentials.secretAccessKey.to_owned(), ) .set( "aws_session_token", get_role_creds.roleCredentials.sessionToken.to_owned(), ); aws_creds .write_to_file(format!("{}{}", home_dir, "/.aws/credentials")) .unwrap(); } fn _list_accounts(sso_url: String, access_token: String) -> Response { ureq::get(format!("{}{}", sso_url, "/assignment/accounts").as_str()) .query("max_result", "100") .set( "x-amz-sso_bearer_token", format!("{}", access_token).as_str(), ) .call() }
use clap::{App, Arg}; use ini::Ini; use serde::Deserialize; use std::{thread, time}; use ureq::Response; use webbrowser; extern crate dirs; use std::time::{SystemTime, UNIX_EPOCH}; const GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code"; #[derive(Debug)] #[allow(non_snake_case)] struct SsoProfile { sso_profile_name : String, sso_start_url: String, sso_region : String, sso_account_id : String, sso_role_name : String } impl SsoProfile { fn new( sso_profile_name : String, sso_start_url: String, sso_region : String, sso_account_id : String, sso_role_name : String) -> SsoProfile { SsoProfile{ sso_profile_name, sso_start_url, sso_region, sso_account_id, sso_role_name } } } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct RegisterClientResponse { clientId: String, clientIdIssuedAt: i32, clientSecret: String, clientSecretExpiresAt: i32, authorizationEndpoint: Option<String>, tokenEndpoint: Option<String>, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct StartDeviceAuthorizationResponse { deviceCode: String, expiresIn: i32, interval: i32, userCode: String, verificationUri: Option<String>, verificationUriComplete: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct CreateTokenResponse { accessToken: String, expiresIn: i32, idToken: Option<String>, refreshToken: Option<String>, tokenType: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct RoleCreds { accessKeyId: String, expiration: i64, secretAccessKey: String, sessionToken: String, } #[derive(Debug, Deserialize)] #[allow(non_snake_case)] struct GetRoleCredsResponse { roleCredentials: RoleCreds, } fn main() { static VERSION: &'static str = include_str!(concat!("", "version")); let matches = App::new("AWS SSO, but better") .version(VERSION) .author("Damien Maier") .author("Saves your SSO login credentials into the credentials file, so it can be used with things like terraform") .arg(Arg::with_name("profile") .short("p") .long("profile") .takes_value(true) .required(true) .help("AWS profile set up for SSO")) .arg(Arg::with_name("save_as_profile_name") .short("s") .long("save_as_profile_name") .help("Whether to save the credentials under the profile name with an _ at the end or under <account_id>_<role_name>")) .arg(Arg::with_name("all") .short("a") .long("all") .help("Get credentials for all profiles with the same start url as the specified profile")) .arg(Arg::with_name("verbose") .short("v") .long("verbose") .help("Print verbose logging")) .get_matches(); let profile = matches.value_of("profile").unwrap().to_owned(); let verbose = matches.is_present("verbose"); let save_as_profile_name = matches.is_present("save_as_profile_name"); let all = matches.is_present("all"); let home = dirs::home_dir().unwrap().to_str().unwrap().to_owned(); let sso_profiles = get_sso_profiles(profile, &home, all); let oidc_url = format!("https://oidc.{}.amazonaws.com", sso_profiles[0].sso_region); let sso_url = format!("https://portal.sso.{}.amazonaws.com", sso_profiles[0].sso_region); let register_client_resp = register_client(&oidc_url, verbose); let device_auth_resp = device_auth(&oidc_url, &sso_profiles[0].sso_start_url, &register_client_resp, verbose); let create_token_resp = create_token(&oidc_url, &register_client_resp, &device_auth_resp, verbose); for sso_profile in sso_profiles { let get_role_creds_resp = get_role_credentials( &sso_url, &sso_profile.sso_account_id, &sso_profile.sso_role_name, &create_token_resp, verbose, ); save_sso( &sso_profile.sso_profile_name, &sso_profile.sso_account_id, &sso_profile.sso_role_name, &get_role_creds_resp, &home, save_as_profile_name, verbose, ); } } fn get_sso_profiles(profile_name : String, home : &String, all : bool) -> Vec<SsoProfile> { let aws_conf = Ini::load_from_file(format!("{}{}", home, "/.aws/config")).unwrap(); let sso_start_url = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_start_url") .unwrap().to_owned(); let sso_region = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_region") .unwrap().to_owned(); let sso_account_id = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_account_id") .unwrap().to_owned(); let sso_role_name = aws_conf .get_from(Some(format!("{}", profile_name)), "sso_role_name") .unwrap().to_owned(); if !all { return vec![SsoProfile::new(profile_name, sso_start_url, sso_region, sso_account_id, sso_role_name)] } else { let mut profiles = Vec::new(); for (section, properties) in aws_conf.iter() { if properties.contains_key("sso_start_url") { if properties.get("sso_start_url").unwrap() == sso_start_url { profiles.push(SsoProfile::new( section.unwrap().to_owned(), properties.get("sso_start_url").unwrap().to_owned(), properties.get("sso_region").unwrap().to_owned(), properties.get("sso_account_id").unwrap().to_owned(), properties.get("sso_role_name").unwrap().to_owned(), )) } } } return profiles; } } fn register_client(oidc_url: &String, verbose: bool) -> RegisterClientResponse { let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs(); let register_resp = ureq::post(format!("{}{}", oidc_url, "/client/register").as_str()) .set("Content-type", "application/json") .set("Action", "RegisterClient") .set("Version", "2019-06-10") .send_json(serde_json::json!({ "clientName" : format!("rustSSO-{}", since_the_epoch).as_str(), "clientType" : "public" })) .into_json_deserialize::<RegisterClientResponse>(); if verbose { println!("{:#?}", register_resp); } let register_resp_un = register_resp.unwrap(); if verbose { println!("{:#?}", register_resp_un); } register_resp_un } fn device_auth( oidc_url: &String, start_url: &String, register_resp: &RegisterClientResponse, verbose: bool, ) -> StartDeviceAuthorizationResponse { let device_auth_resp = ureq::post(format!("{}{}", oidc_url, "/device_authorization").as_str()) .set("Content-type", "application/json") .set("Action", "StartDeviceAuthorization") .set("Version", "2019-06-10") .send_json(serde_json::json!( { "clientId" : register_resp.clientId, "clientSecret" : register_resp.clientSecret, "startUrl" : start_url })) .into_json_deserialize::<StartDeviceAuthorizationResponse>(); if verbose { println!("{:#?}", device_auth_resp); } let device_auth_resp_un = device_auth_resp.unwrap(); if verbose { println!("{:#?}", device_auth_resp_un); } device_auth_resp_un } fn create_token( oidc_url: &String, register_resp: &RegisterClientResponse, device_auth_resp: &StartDeviceAuthorizationResponse, verbose: bool, ) -> CreateTokenResponse { if webbrowser::open(device_auth_resp.verificationUriComplete.as_str()).is_err() { println!( "Go to {}", device_auth_resp.verificationUriComplete.as_str() ); } let sec = time::Duration::from_secs(1); let create_tok_resp_un = loop { thread::sleep(sec); let create_tok_resp = ureq::post(format!("{}{}", oidc_url, "/token").as_str()) .set("Content-type", "application/json") .set("Action", "CreateToken") .set("Version", "2019-06-10") .send_json(serde_json::json!({ "clientId": register_resp.clientId, "clientSecret": register_resp.clientSecret, "deviceCode": device_auth_resp.deviceCode, "grantType": GRANT_TYPE, })); if verbose { println!("{:#?}", create_tok_resp); } if create_tok_resp.ok() { break create_tok_resp .into_json_deserialize::<CreateTokenResponse>() .unwrap(); } else { if verbose { println!("{:#?}", create_tok_resp.into_json()); } } }; if verbose { println!("{:#?}", create_tok_resp_un); } create_tok_resp_un } fn get_role_credentials( sso_url: &String, sso_account_id: &String, sso_role_name: &String, create_token_resp: &CreateTokenResponse, verbose: bool, ) -> GetRoleCredsResponse { let get_role_creds = ureq::get(format!("{}{}", sso_url, "/federation/credentials").as_str()) .query("account_id", sso_account_id) .query("role_name", sso_role_name) .set( "x-amz-sso_bearer_token", format!("{}", create_token_resp.accessToken).as_str(), ) .call() .into_json_deserialize::<GetRoleCredsResponse>(); if verbose { println!("{:#?}", get_role_creds); } let get_role_creds_un = get_role_creds.unwrap(); if verbose { println!("{:#?}", get_role_creds_un); } get_role_creds_un } fn save_sso( profile: &str, sso_account_id: &String, sso_role_name: &String, get_role_creds: &GetRoleCredsResponse, home_dir: &String, save_as_profile_name: bool, verbose: bool, ) { let section_name = i
fn _list_accounts(sso_url: String, access_token: String) -> Response { ureq::get(format!("{}{}", sso_url, "/assignment/accounts").as_str()) .query("max_result", "100") .set( "x-amz-sso_bearer_token", format!("{}", access_token).as_str(), ) .call() }
f save_as_profile_name { format!("{}_", profile) } else { format!("{}_{}", sso_account_id, sso_role_name) }; let mut aws_creds = Ini::load_from_file(format!("{}{}", home_dir, "/.aws/credentials")).unwrap(); if verbose { println!("Section name : {}", section_name); } aws_creds .with_section(Some(section_name)) .set( "aws_access_key_id", get_role_creds.roleCredentials.accessKeyId.to_owned(), ) .set( "aws_secret_access_key", get_role_creds.roleCredentials.secretAccessKey.to_owned(), ) .set( "aws_session_token", get_role_creds.roleCredentials.sessionToken.to_owned(), ); aws_creds .write_to_file(format!("{}{}", home_dir, "/.aws/credentials")) .unwrap(); }
function_block-function_prefixed
[ { "content": "fn get_latest_version() -> String {\n\n let api_url = \"https://api.github.com/repos/thehamsterjam/better_aws_sso/releases/latest\";\n\n let resp = ureq::get(api_url)\n\n .call()\n\n .into_json()\n\n .unwrap();\n\n resp[\"tag_name\"].to_string()\n\n}", "file_path"...
Rust
src/sol.rs
Aehmlo/sudoku
d2cb746ff47d427128f53f593efc555212cf32b5
use crate::sudoku::Grid; use crate::Element; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; use std::ops::{Index, IndexMut}; #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum Difficulty { #[doc(hidden)] Unplayable, Beginner, Easy, Intermediate, Difficult, Advanced, } impl From<usize> for Difficulty { fn from(score: usize) -> Self { use crate::Difficulty::*; match score { 0...49 => Unplayable, 50...150 => Beginner, 151...250 => Easy, 251...400 => Intermediate, 401...550 => Difficult, _ => Advanced, } } } #[derive(Clone, Debug)] #[allow(missing_copy_implementations)] pub enum Error { Unknown, #[doc(hidden)] __TestOther, } pub trait Solve: Sized { fn solution(&self) -> Result<Self, Error>; fn is_uniquely_solvable(&self) -> bool { self.solution().is_ok() } } pub trait Score: Solve { fn score(&self) -> Option<usize>; fn difficulty(&self) -> Option<Difficulty> { self.score().map(Into::into) } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct PossibilitySet { pub values: u64, } impl PossibilitySet { pub fn new(order: u8) -> Self { let mut values = 0; for i in 1..=order.pow(2) as usize { values |= 1 << (i - 1); } Self { values } } pub fn eliminate(self, value: usize) -> Option<Self> { let values = self.values & !(1 << (value - 1)); match values { 0 => None, _ => Some(Self { values }), } } pub fn freedom(self) -> usize { let mut x = self.values; let mut n = 0; while x > 0 { x &= x - 1; n += 1; } n } pub fn contains(self, value: usize) -> bool { self.values | (1 << (value - 1)) == self.values } } #[derive(Debug)] pub struct PossibilityMap { possibilities: Vec<Option<PossibilitySet>>, order: u8, parent: Option<Sudoku>, } impl PossibilityMap { pub fn new(order: u8) -> Self { Self { possibilities: vec![ Some(PossibilitySet::new(order)); (order as usize).pow(2 + DIMENSIONS as u32) ], order, parent: None, } } pub fn eliminate(&mut self, index: Point, value: usize) { self[index] = self[index].and_then(|e| e.eliminate(value)); } pub fn next(&self) -> (Option<Point>, Option<PossibilitySet>) { let mut best = None; let mut best_index = None; let mut best_score = None; for index in self.points() { if let Some(element) = self[index] { if best_score.is_none() || best_score.unwrap() > element.freedom() { best = Some(element); best_index = Some(index); best_score = Some(element.freedom()); } } else if let Some(ref parent) = self.parent { if parent[index].is_none() { return (None, None); } } } (best_index, best) } } impl Index<Point> for PossibilityMap { type Output = Option<PossibilitySet>; fn index(&self, index: Point) -> &Self::Output { let index = index.fold(self.order); &self.possibilities[index] } } impl IndexMut<Point> for PossibilityMap { fn index_mut(&mut self, index: Point) -> &mut Option<PossibilitySet> { let index = index.fold(self.order); &mut self.possibilities[index] } } impl Grid for PossibilityMap { fn points(&self) -> Vec<Point> { (0..(self.order as usize).pow(2 + DIMENSIONS as u32)) .map(|p| Point::unfold(p, self.order)) .collect() } } impl From<Sudoku> for PossibilityMap { fn from(sudoku: Sudoku) -> Self { let order = sudoku.order; let mut map = PossibilityMap::new(order); for i in 0..(sudoku.order as usize).pow(2 + DIMENSIONS as u32) { let point = Point::unfold(i, order); if sudoku[point].is_some() { map[point] = None; } else { let groups = sudoku.groups(point); for group in &groups { let elements = group.elements(); for element in elements { if let Some(Element(value)) = element { map.eliminate(point, value as usize); } } } } } map.parent = Some(sudoku); map } } pub fn solve(puzzle: &Sudoku) -> Result<Sudoku, Error> { solve_and_score(puzzle).map(|(sol, _)| sol) } pub fn solve_and_score(puzzle: &Sudoku) -> Result<(Sudoku, usize), Error> { let mut context = Context { problem: puzzle.clone(), count: 0, solution: None, branch_score: 0, }; recurse(&mut context, 0); let s = context.branch_score; let c = calculate_c(puzzle) as isize; let e = count_empty(puzzle) as isize; context .solution .ok_or(Error::Unknown) .map(|sol| (sol, (s * c + e) as usize)) } struct Context { problem: Sudoku, count: usize, solution: Option<Sudoku>, branch_score: isize, } fn recurse(mut context: &mut Context, difficulty: isize) { let problem = context.problem.clone(); let map: PossibilityMap = problem.into(); match map.next() { (None, _) => { if context.problem.is_complete() { if context.count == 0 { context.branch_score = difficulty; context.solution = Some(context.problem.clone()); } context.count += 1; } return; } (Some(index), Some(set)) => { let branch_factor = set.freedom() as isize - 1; let possible = (1..=(context.problem.order as usize).pow(2)) .filter(|v| set.contains(*v)) .collect::<Vec<_>>(); let difficulty = difficulty + branch_factor.pow(DIMENSIONS as u32); for value in possible { context .problem .substitute(index, Some(Element(value as u8))); recurse(&mut context, difficulty); if context.count > 1 { return; } } context.problem.substitute(index, None); } _ => unreachable!(), } } fn count_empty(sudoku: &Sudoku) -> usize { sudoku.elements.iter().filter(|e| e.is_none()).count() } fn calculate_c(sudoku: &Sudoku) -> usize { let order = sudoku.order; 10.0_f64.powf(f64::from(order).powf(4.0).log10().ceil()) as usize } pub fn score(sudoku: &Sudoku) -> Option<usize> { solve_and_score(&sudoku).ok().map(|(_, s)| s) } #[cfg(test)] mod tests { use crate::sol::{calculate_c, Error, PossibilityMap, PossibilitySet, Solve}; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; struct DummyPuzzle(bool); impl DummyPuzzle { fn new(solvable: bool) -> Self { Self { 0: solvable } } } impl Solve for DummyPuzzle { fn solution(&self) -> Result<Self, Error> { if self.0 { Ok(Self { 0: true }) } else { Err(Error::__TestOther) } } } #[test] fn test_is_uniquely_solvable() { let solvable = DummyPuzzle::new(true); assert_eq!(solvable.is_uniquely_solvable(), true); let unsolvable = DummyPuzzle::new(false); assert_eq!(unsolvable.is_uniquely_solvable(), false); } #[test] fn test_calculate_c() { let sudoku = Sudoku::new(3); assert_eq!(calculate_c(&sudoku), 100); let sudoku = Sudoku::new(4); assert_eq!(calculate_c(&sudoku), 1_000); let sudoku = Sudoku::new(5); assert_eq!(calculate_c(&sudoku), 1_000); let sudoku = Sudoku::new(6); assert_eq!(calculate_c(&sudoku), 10_000); } #[test] fn test_map_new() { for order in 1..6 { let map = PossibilityMap::new(order); for i in 0..(order as usize).pow(DIMENSIONS as u32 + 2) { let index = Point::unfold(i, order); let set = PossibilitySet::new(order); assert_eq!(map[index], Some(set)); } } } #[test] fn test_map_from_sudoku() { let sudoku = Sudoku::new(3); let map: PossibilityMap = sudoku.into(); for p in map.possibilities { assert_eq!(p, Some(PossibilitySet::new(3))); } } #[test] fn test_set_new() { let set = PossibilitySet::new(3); for i in 1..10 { assert!(set.contains(i)); } } #[test] fn test_set_eliminate() { let mut set = PossibilitySet::new(3); for i in 1..9 { set = set.eliminate(i).unwrap(); assert!(!set.contains(i)); } assert_eq!(set.eliminate(9), None); } #[test] fn test_set_freedom() { let mut set = PossibilitySet::new(3); for i in 1..9 { set = set.eliminate(i).unwrap(); assert_eq!(set.freedom(), 9 - i); } } }
use crate::sudoku::Grid; use crate::Element; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; use std::ops::{Index, IndexMut}; #[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] pub enum Difficulty { #[doc(hidden)] Unplayable, Beginner, Easy, Intermediate, Difficult, Advanced, } impl From<usize> for Difficulty { fn from(score: usize) -> Self { use crate::Difficulty::*; match score { 0...49 => Unplayable, 50...150 => Beginner, 151...250 => Easy, 251...400 => Intermediate, 401...550 => Difficult, _ => Advanced, } } } #[derive(Clone, Debug)] #[allow(missing_copy_implementations)] pub enum Error { Unknown, #[doc(hidden)] __TestOther, } pub trait Solve: Sized { fn solution(&self) -> Result<Self, Error>; fn is_uniquely_solvable(&self) -> bool { self.solution().is_ok() } } pub trait Score: Solve { fn score(&self) -> Option<usize>; fn difficulty(&self) -> Option<Difficulty> { self.score().map(Into::into) } } #[derive(Clone, Copy, Debug, PartialEq)] pub struct PossibilitySet { pub values: u64, } impl PossibilitySet { pub fn new(order: u8) -> Self { let mut values = 0; for i in 1..=order.pow(2) as usize { values |= 1 << (i - 1); } Self { values } } pub fn eliminate(self, value: usize) -> Option<Self> { let values = self.values & !(1 << (value - 1)); match values { 0 => None, _ => Some(Self { values }), } } pub fn freedom(self) -> usize { let mut x = self.values; let mut n = 0; while x > 0 { x &= x - 1; n += 1; } n } pub fn contains(self, value: usize) -> bool { self.values | (1 << (value - 1)) == self.values } } #[derive(Debug)] pub struct PossibilityMap { possibilities: Vec<Option<PossibilitySet>>, order: u8, parent: Option<Sudoku>, } impl PossibilityMap { pub fn new(order: u8) -> Sel
pub fn eliminate(&mut self, index: Point, value: usize) { self[index] = self[index].and_then(|e| e.eliminate(value)); } pub fn next(&self) -> (Option<Point>, Option<PossibilitySet>) { let mut best = None; let mut best_index = None; let mut best_score = None; for index in self.points() { if let Some(element) = self[index] { if best_score.is_none() || best_score.unwrap() > element.freedom() { best = Some(element); best_index = Some(index); best_score = Some(element.freedom()); } } else if let Some(ref parent) = self.parent { if parent[index].is_none() { return (None, None); } } } (best_index, best) } } impl Index<Point> for PossibilityMap { type Output = Option<PossibilitySet>; fn index(&self, index: Point) -> &Self::Output { let index = index.fold(self.order); &self.possibilities[index] } } impl IndexMut<Point> for PossibilityMap { fn index_mut(&mut self, index: Point) -> &mut Option<PossibilitySet> { let index = index.fold(self.order); &mut self.possibilities[index] } } impl Grid for PossibilityMap { fn points(&self) -> Vec<Point> { (0..(self.order as usize).pow(2 + DIMENSIONS as u32)) .map(|p| Point::unfold(p, self.order)) .collect() } } impl From<Sudoku> for PossibilityMap { fn from(sudoku: Sudoku) -> Self { let order = sudoku.order; let mut map = PossibilityMap::new(order); for i in 0..(sudoku.order as usize).pow(2 + DIMENSIONS as u32) { let point = Point::unfold(i, order); if sudoku[point].is_some() { map[point] = None; } else { let groups = sudoku.groups(point); for group in &groups { let elements = group.elements(); for element in elements { if let Some(Element(value)) = element { map.eliminate(point, value as usize); } } } } } map.parent = Some(sudoku); map } } pub fn solve(puzzle: &Sudoku) -> Result<Sudoku, Error> { solve_and_score(puzzle).map(|(sol, _)| sol) } pub fn solve_and_score(puzzle: &Sudoku) -> Result<(Sudoku, usize), Error> { let mut context = Context { problem: puzzle.clone(), count: 0, solution: None, branch_score: 0, }; recurse(&mut context, 0); let s = context.branch_score; let c = calculate_c(puzzle) as isize; let e = count_empty(puzzle) as isize; context .solution .ok_or(Error::Unknown) .map(|sol| (sol, (s * c + e) as usize)) } struct Context { problem: Sudoku, count: usize, solution: Option<Sudoku>, branch_score: isize, } fn recurse(mut context: &mut Context, difficulty: isize) { let problem = context.problem.clone(); let map: PossibilityMap = problem.into(); match map.next() { (None, _) => { if context.problem.is_complete() { if context.count == 0 { context.branch_score = difficulty; context.solution = Some(context.problem.clone()); } context.count += 1; } return; } (Some(index), Some(set)) => { let branch_factor = set.freedom() as isize - 1; let possible = (1..=(context.problem.order as usize).pow(2)) .filter(|v| set.contains(*v)) .collect::<Vec<_>>(); let difficulty = difficulty + branch_factor.pow(DIMENSIONS as u32); for value in possible { context .problem .substitute(index, Some(Element(value as u8))); recurse(&mut context, difficulty); if context.count > 1 { return; } } context.problem.substitute(index, None); } _ => unreachable!(), } } fn count_empty(sudoku: &Sudoku) -> usize { sudoku.elements.iter().filter(|e| e.is_none()).count() } fn calculate_c(sudoku: &Sudoku) -> usize { let order = sudoku.order; 10.0_f64.powf(f64::from(order).powf(4.0).log10().ceil()) as usize } pub fn score(sudoku: &Sudoku) -> Option<usize> { solve_and_score(&sudoku).ok().map(|(_, s)| s) } #[cfg(test)] mod tests { use crate::sol::{calculate_c, Error, PossibilityMap, PossibilitySet, Solve}; use crate::Point; use crate::Sudoku; use crate::DIMENSIONS; struct DummyPuzzle(bool); impl DummyPuzzle { fn new(solvable: bool) -> Self { Self { 0: solvable } } } impl Solve for DummyPuzzle { fn solution(&self) -> Result<Self, Error> { if self.0 { Ok(Self { 0: true }) } else { Err(Error::__TestOther) } } } #[test] fn test_is_uniquely_solvable() { let solvable = DummyPuzzle::new(true); assert_eq!(solvable.is_uniquely_solvable(), true); let unsolvable = DummyPuzzle::new(false); assert_eq!(unsolvable.is_uniquely_solvable(), false); } #[test] fn test_calculate_c() { let sudoku = Sudoku::new(3); assert_eq!(calculate_c(&sudoku), 100); let sudoku = Sudoku::new(4); assert_eq!(calculate_c(&sudoku), 1_000); let sudoku = Sudoku::new(5); assert_eq!(calculate_c(&sudoku), 1_000); let sudoku = Sudoku::new(6); assert_eq!(calculate_c(&sudoku), 10_000); } #[test] fn test_map_new() { for order in 1..6 { let map = PossibilityMap::new(order); for i in 0..(order as usize).pow(DIMENSIONS as u32 + 2) { let index = Point::unfold(i, order); let set = PossibilitySet::new(order); assert_eq!(map[index], Some(set)); } } } #[test] fn test_map_from_sudoku() { let sudoku = Sudoku::new(3); let map: PossibilityMap = sudoku.into(); for p in map.possibilities { assert_eq!(p, Some(PossibilitySet::new(3))); } } #[test] fn test_set_new() { let set = PossibilitySet::new(3); for i in 1..10 { assert!(set.contains(i)); } } #[test] fn test_set_eliminate() { let mut set = PossibilitySet::new(3); for i in 1..9 { set = set.eliminate(i).unwrap(); assert!(!set.contains(i)); } assert_eq!(set.eliminate(9), None); } #[test] fn test_set_freedom() { let mut set = PossibilitySet::new(3); for i in 1..9 { set = set.eliminate(i).unwrap(); assert_eq!(set.freedom(), 9 - i); } } }
f { Self { possibilities: vec![ Some(PossibilitySet::new(order)); (order as usize).pow(2 + DIMENSIONS as u32) ], order, parent: None, } }
function_block-function_prefixed
[ { "content": "/// Trait to generate a puzzle.\n\n///\n\n/// Requires that the puzzle be solvable (to ensure the desired difficulty is\n\n/// attained).\n\npub trait Generate: Score + Sized {\n\n /// Generates a puzzle of the desired order and difficulty.\n\n fn generate(order: u8, difficulty: Difficulty) ...
Rust
flow-rs/src/channel/storage.rs
ysh329/MegFlow
778a4361a88af43f499528f4509f6523515ce0ee
/** * \file flow-rs/src/channel/storage.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use super::{inner, ChannelBase, Receiver, Sender, SenderRecord}; use crate::envelope::SealedEnvelope; use crate::rt::sync::Mutex; use std::collections::HashMap; use std::process; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; #[derive(Clone)] pub struct ChannelStorage { storage: Arc<inner::Channel<SealedEnvelope>>, receiver_epoch: Arc<AtomicUsize>, sender_epoch: Arc<AtomicUsize>, sender_record: SenderRecord, rx_counter: Arc<AtomicUsize>, tx_counter: Arc<AtomicUsize>, } impl ChannelBase for ChannelStorage { fn is_closed(&self) -> bool { self.storage.queue.is_closed() } fn is_none(&self) -> bool { false } } impl ChannelStorage { pub fn bound(cap: usize) -> ChannelStorage { ChannelStorage { storage: inner::bounded(cap), receiver_epoch: Arc::new(AtomicUsize::new(0)), sender_epoch: Arc::new(AtomicUsize::new(0)), sender_record: Arc::new(Mutex::new(HashMap::new())), rx_counter: Arc::new(AtomicUsize::new(0)), tx_counter: Arc::new(AtomicUsize::new(0)), } } pub fn unbound() -> ChannelStorage { ChannelStorage { storage: inner::unbounded(), receiver_epoch: Arc::new(AtomicUsize::new(0)), sender_epoch: Arc::new(AtomicUsize::new(0)), sender_record: Arc::new(Mutex::new(HashMap::new())), rx_counter: Arc::new(AtomicUsize::new(0)), tx_counter: Arc::new(AtomicUsize::new(0)), } } pub fn sender(&self) -> Sender { let count = self.storage.sender_count.fetch_add(1, Ordering::Relaxed); if count > usize::MAX / 2 { process::abort(); } Sender::new( inner::Sender { channel: self.storage.clone(), }, self.sender_epoch.clone(), self.sender_record.clone(), self.tx_counter.clone(), ) } pub fn receiver(&self) -> Receiver { let count = self.storage.receiver_count.fetch_add(1, Ordering::Relaxed); if count > usize::MAX / 2 { process::abort(); } Receiver::new( inner::Receiver { channel: self.storage.clone(), listener: None, }, self.receiver_epoch.clone(), self.rx_counter.clone(), ) } pub fn len(&self) -> usize { self.storage.queue.len() } pub fn is_almost_full(&self) -> bool { match self.storage.queue.capacity() { Some(capacity) => (0.9 * capacity as f64) <= self.len() as f64, None => false, } } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn close(&self) { self.storage.close(); } pub fn sender_count(&self) -> usize { self.storage.sender_count.load(Ordering::Relaxed) } pub fn receiver_count(&self) -> usize { self.storage.receiver_count.load(Ordering::Relaxed) } pub fn swap_tx_counter(&self) -> usize { self.tx_counter.swap(0, Ordering::Relaxed) } pub fn swap_rx_counter(&self) -> usize { self.rx_counter.swap(0, Ordering::Relaxed) } }
/** * \file flow-rs/src/channel/storage.rs * MegFlow is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2019-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ use super::{inner, ChannelBase, Receiver, Sender, SenderRecord}; use crate::envelope::SealedEnvelope; use crate::rt::sync::Mutex; use std::collections::HashMap; use std::process; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; #[derive(Clone)] pub struct ChannelStorage { storage: Arc<inner::Channel<SealedEnvelope>>, receiver_epoch: Arc<AtomicUsize>, sender_epoch: Arc<AtomicUsize>, sender_record: SenderRecord, rx_counter: Arc<AtomicUsize>, tx_counter: Arc<AtomicUsize>, } impl ChannelBase for ChannelStorage { fn is_closed(&self) -> bool { self.storage.
> ChannelStorage { ChannelStorage { storage: inner::bounded(cap), receiver_epoch: Arc::new(AtomicUsize::new(0)), sender_epoch: Arc::new(AtomicUsize::new(0)), sender_record: Arc::new(Mutex::new(HashMap::new())), rx_counter: Arc::new(AtomicUsize::new(0)), tx_counter: Arc::new(AtomicUsize::new(0)), } } pub fn unbound() -> ChannelStorage { ChannelStorage { storage: inner::unbounded(), receiver_epoch: Arc::new(AtomicUsize::new(0)), sender_epoch: Arc::new(AtomicUsize::new(0)), sender_record: Arc::new(Mutex::new(HashMap::new())), rx_counter: Arc::new(AtomicUsize::new(0)), tx_counter: Arc::new(AtomicUsize::new(0)), } } pub fn sender(&self) -> Sender { let count = self.storage.sender_count.fetch_add(1, Ordering::Relaxed); if count > usize::MAX / 2 { process::abort(); } Sender::new( inner::Sender { channel: self.storage.clone(), }, self.sender_epoch.clone(), self.sender_record.clone(), self.tx_counter.clone(), ) } pub fn receiver(&self) -> Receiver { let count = self.storage.receiver_count.fetch_add(1, Ordering::Relaxed); if count > usize::MAX / 2 { process::abort(); } Receiver::new( inner::Receiver { channel: self.storage.clone(), listener: None, }, self.receiver_epoch.clone(), self.rx_counter.clone(), ) } pub fn len(&self) -> usize { self.storage.queue.len() } pub fn is_almost_full(&self) -> bool { match self.storage.queue.capacity() { Some(capacity) => (0.9 * capacity as f64) <= self.len() as f64, None => false, } } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn close(&self) { self.storage.close(); } pub fn sender_count(&self) -> usize { self.storage.sender_count.load(Ordering::Relaxed) } pub fn receiver_count(&self) -> usize { self.storage.receiver_count.load(Ordering::Relaxed) } pub fn swap_tx_counter(&self) -> usize { self.tx_counter.swap(0, Ordering::Relaxed) } pub fn swap_rx_counter(&self) -> usize { self.rx_counter.swap(0, Ordering::Relaxed) } }
queue.is_closed() } fn is_none(&self) -> bool { false } } impl ChannelStorage { pub fn bound(cap: usize) -
random
[ { "content": "pub fn ident(lit: impl AsRef<str>) -> Ident {\n\n Ident::new(lit.as_ref(), Span::call_site())\n\n}\n", "file_path": "flow-derive/src/lit.rs", "rank": 0, "score": 153767.02012632263 }, { "content": "pub fn match_last_ty(ty: &syn::Type, wrapper: &str) -> bool {\n\n match ty...
Rust
src/external_service/spread_sheet/token_manager.rs
tacogips/api-everywhere
02224c875afee72dc0ad82707e1ef1a0d7eff51a
use arc_swap::ArcSwap; use chrono::{Duration, Local}; use hyper; use log; use once_cell::sync::OnceCell; use std::path::PathBuf; use std::sync::Arc; use thiserror::Error; use tokio::sync::broadcast; use tokio::task::{JoinError, JoinHandle}; use tokio::time::timeout; use yup_oauth2::{ self as oauth, authenticator::{Authenticator, DefaultHyperClient, HyperClientBuilder}, AccessToken, Error as OauthError, }; type Result<T> = std::result::Result<T, GoogleTokenManagerError>; #[derive(Error, Debug)] pub enum GoogleTokenManagerError { #[error("oauth error:{0}")] OauthError(#[from] OauthError), #[error("failed to load service account file:{0}, {1}")] ServiceAccountFileLoadError(PathBuf, std::io::Error), #[error("invalid service account file:{0}, {1}")] InvalidServiceAccountFileError(PathBuf, std::io::Error), #[error("async task join error:{0}")] JoinError(#[from] JoinError), } static TOKEN_BUFFER_DURATION_TO_EXPIRE: OnceCell<Duration> = OnceCell::new(); fn get_token_buffer_duraiton_to_expire() -> &'static Duration { TOKEN_BUFFER_DURATION_TO_EXPIRE.get_or_init(|| Duration::minutes(2)) } #[allow(dead_code)] pub struct TokenManager<HttpConnector> { authenticator: Arc<Authenticator<HttpConnector>>, scopes: &'static [&'static str], inner_current_token: Arc<ArcSwap<AccessToken>>, token_refreshing_loop_jh: JoinHandle<()>, } impl<HttpConnector> TokenManager<HttpConnector> where HttpConnector: hyper::client::connect::Connect + Clone + Send + Sync + 'static, { pub async fn start( authenticator: Authenticator<HttpConnector>, scopes: &'static [&'static str], stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> Result<Self> { let access_token = authenticator.token(scopes.as_ref()).await?; let current_token = Arc::new(ArcSwap::from(Arc::new(access_token))); let authenticator = Arc::new(authenticator); let token_refreshing_loop_jh = Self::periodically_refreshing_token( authenticator.clone(), current_token.clone(), scopes, stop_refreshing_notifyer_rx, token_refresh_period, ) .await; let result = Self { authenticator, scopes, inner_current_token: current_token, token_refreshing_loop_jh, }; Ok(result) } async fn periodically_refreshing_token( authenticator: Arc<Authenticator<HttpConnector>>, shared_token: Arc<ArcSwap<AccessToken>>, scopes: &'static [&'static str], mut stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> JoinHandle<()> { let shared_token_current = shared_token.clone(); let refresh_token_loop_jh = tokio::spawn(async move { let refresh_period = token_refresh_period .map(|p| p.to_std().unwrap()) .unwrap_or_else(|| std::time::Duration::from_secs(30)); loop { let has_stop_notified = timeout(refresh_period, stop_refreshing_notifyer_rx.recv()).await; if has_stop_notified.is_ok() { log::info!("exiting from auth token refreshing loop"); break; } let current_token = shared_token_current.load(); let need_refresh = (**current_token) .expiration_time() .map(|expiration_time| { expiration_time - *get_token_buffer_duraiton_to_expire() <= Local::now() }) .unwrap_or(false); if need_refresh { let new_token = Self::get_new_token(&authenticator, &scopes).await; match new_token { Ok(access_token) => shared_token.store(Arc::new(access_token)), Err(e) => { log::error!("failed to refresh token :{}", e); } } } } log::info!("exit from refreshing token loop") }); refresh_token_loop_jh } #[allow(dead_code)] pub fn authenticator(&self) -> Arc<Authenticator<HttpConnector>> { Arc::clone(&self.authenticator) } #[allow(dead_code)] pub async fn force_refresh_token(&mut self) -> Result<()> { let new_token = Self::get_new_token(&self.authenticator, &self.scopes).await; match new_token { Ok(access_token) => { self.current_token().store(Arc::new(access_token)); Ok(()) } Err(e) => { log::error!("failed to refresh token :{}", e); return Err(e); } } } async fn get_new_token( authenticator: &Authenticator<HttpConnector>, scopes: &'static [&'static str], ) -> Result<AccessToken> { let new_token = authenticator.force_refreshed_token(scopes).await?; Ok(new_token) } pub async fn wait_until_refreshing_finished(self: Self) -> Result<()> { self.token_refreshing_loop_jh.await?; Ok(()) } } impl<ANY> TokenManager<ANY> { pub fn current_token(&self) -> Arc<ArcSwap<AccessToken>> { Arc::clone(&self.inner_current_token) } } pub async fn token_manager_from_service_account_file( scopes: &'static [&'static str], service_account_cred_file: PathBuf, stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> Result<TokenManager<<DefaultHyperClient as HyperClientBuilder>::Connector>> { let sa_key = oauth::read_service_account_key(&service_account_cred_file) .await .map_err(|e| { GoogleTokenManagerError::ServiceAccountFileLoadError( service_account_cred_file.clone(), e, ) })?; let authenticator = oauth::ServiceAccountAuthenticator::builder(sa_key) .build() .await .map_err(|e| { GoogleTokenManagerError::InvalidServiceAccountFileError(service_account_cred_file, e) })?; TokenManager::start( authenticator, scopes, stop_refreshing_notifyer_rx, token_refresh_period, ) .await } #[cfg(all(test, feature = "test-using-sa"))] mod test { use super::super::scopes; use super::super::test::load_test_sa_file_path; use super::token_manager_from_service_account_file; use tokio::sync::broadcast; #[tokio::test] async fn load_token_manager_test() { let (_, rx) = broadcast::channel(1); let token_manager = token_manager_from_service_account_file( scopes::SHEET_READ_ONLY, load_test_sa_file_path(), rx, None, ) .await; assert!(token_manager.is_ok()); let token_manager = token_manager.unwrap(); let token = token_manager.current_token(); assert_ne!("", token.load().as_str()); } }
use arc_swap::ArcSwap; use chrono::{Duration, Local}; use hyper; use log; use once_cell::sync::OnceCell; use std::path::PathBuf; use std::sync::Arc; use thiserror::Error; use tokio::sync::broadcast; use tokio::task::{JoinError, JoinHandle}; use tokio::time::timeout; use yup_oauth2::{ self as oauth, authenticator::{Authenticator, DefaultHyperClient, HyperClientBuilder}, AccessToken, Error as OauthError, }; type Result<T> = std::result::Result<T, GoogleTokenManagerError>; #[derive(Error, Debug)] pub enum GoogleTokenManagerError { #[error("oauth error:{0}")] OauthError(#[from] OauthError), #[error("failed to load service account file:{0}, {1}")] ServiceAccountFileLoadError(PathBuf, std::io::Error), #[error("invalid service account file:{0}, {1}")] InvalidServiceAccountFileError(PathBuf, std::io::Error), #[error("async task join error:{0}")] JoinError(#[from] JoinError), } static TOKEN_BUFFER_DURATION_TO_EXPIRE: OnceCell<Duration> = OnceCell::new(); fn get_token_buffer_duraiton_to_expire() -> &'static Duration { TOKEN_BUFFER_DURATION_TO_EXPIRE.get_or_init(|| Duration::minutes(2)) } #[allow(dead_code)] pub struct TokenManager<HttpConnector> { authenticator: Arc<Authenticator<HttpConnector>>, scopes: &'static [&'static str], inner_current_token: Arc<ArcSwap<AccessToken>>, token_refreshing_loop_jh: JoinHandle<()>, } impl<HttpConnector> TokenManager<HttpConnector> where HttpConnector: hyper::client::connect::Connect + Clone + Send + Sync + 'static, { pub async fn start( authenticator: Authenticator<HttpConnector>, scopes: &'static [&'static str], stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> Result<Self> { let access_token = authenticator.token(scopes.as_ref()).await?; let current_token = Arc::new(ArcSwap::from(Arc::new(access_token))); let authenticator = Arc::new(authenticator); let token_refreshing_loop_jh = Self::periodically_refreshing_token( authenticator.clone(), current_token.clone(), scopes, stop_refreshing_notifyer_rx, token_refresh_period, ) .await; let result = Self { authenticator, scopes, inner_current_token: curre
})?; let authenticator = oauth::ServiceAccountAuthenticator::builder(sa_key) .build() .await .map_err(|e| { GoogleTokenManagerError::InvalidServiceAccountFileError(service_account_cred_file, e) })?; TokenManager::start( authenticator, scopes, stop_refreshing_notifyer_rx, token_refresh_period, ) .await } #[cfg(all(test, feature = "test-using-sa"))] mod test { use super::super::scopes; use super::super::test::load_test_sa_file_path; use super::token_manager_from_service_account_file; use tokio::sync::broadcast; #[tokio::test] async fn load_token_manager_test() { let (_, rx) = broadcast::channel(1); let token_manager = token_manager_from_service_account_file( scopes::SHEET_READ_ONLY, load_test_sa_file_path(), rx, None, ) .await; assert!(token_manager.is_ok()); let token_manager = token_manager.unwrap(); let token = token_manager.current_token(); assert_ne!("", token.load().as_str()); } }
nt_token, token_refreshing_loop_jh, }; Ok(result) } async fn periodically_refreshing_token( authenticator: Arc<Authenticator<HttpConnector>>, shared_token: Arc<ArcSwap<AccessToken>>, scopes: &'static [&'static str], mut stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> JoinHandle<()> { let shared_token_current = shared_token.clone(); let refresh_token_loop_jh = tokio::spawn(async move { let refresh_period = token_refresh_period .map(|p| p.to_std().unwrap()) .unwrap_or_else(|| std::time::Duration::from_secs(30)); loop { let has_stop_notified = timeout(refresh_period, stop_refreshing_notifyer_rx.recv()).await; if has_stop_notified.is_ok() { log::info!("exiting from auth token refreshing loop"); break; } let current_token = shared_token_current.load(); let need_refresh = (**current_token) .expiration_time() .map(|expiration_time| { expiration_time - *get_token_buffer_duraiton_to_expire() <= Local::now() }) .unwrap_or(false); if need_refresh { let new_token = Self::get_new_token(&authenticator, &scopes).await; match new_token { Ok(access_token) => shared_token.store(Arc::new(access_token)), Err(e) => { log::error!("failed to refresh token :{}", e); } } } } log::info!("exit from refreshing token loop") }); refresh_token_loop_jh } #[allow(dead_code)] pub fn authenticator(&self) -> Arc<Authenticator<HttpConnector>> { Arc::clone(&self.authenticator) } #[allow(dead_code)] pub async fn force_refresh_token(&mut self) -> Result<()> { let new_token = Self::get_new_token(&self.authenticator, &self.scopes).await; match new_token { Ok(access_token) => { self.current_token().store(Arc::new(access_token)); Ok(()) } Err(e) => { log::error!("failed to refresh token :{}", e); return Err(e); } } } async fn get_new_token( authenticator: &Authenticator<HttpConnector>, scopes: &'static [&'static str], ) -> Result<AccessToken> { let new_token = authenticator.force_refreshed_token(scopes).await?; Ok(new_token) } pub async fn wait_until_refreshing_finished(self: Self) -> Result<()> { self.token_refreshing_loop_jh.await?; Ok(()) } } impl<ANY> TokenManager<ANY> { pub fn current_token(&self) -> Arc<ArcSwap<AccessToken>> { Arc::clone(&self.inner_current_token) } } pub async fn token_manager_from_service_account_file( scopes: &'static [&'static str], service_account_cred_file: PathBuf, stop_refreshing_notifyer_rx: broadcast::Receiver<()>, token_refresh_period: Option<Duration>, ) -> Result<TokenManager<<DefaultHyperClient as HyperClientBuilder>::Connector>> { let sa_key = oauth::read_service_account_key(&service_account_cred_file) .await .map_err(|e| { GoogleTokenManagerError::ServiceAccountFileLoadError( service_account_cred_file.clone(), e, )
random
[ { "content": "/// \"A\" -> 0\n\n/// \"Z\" -> 25\n\n/// \"AA\"-> 26\n\npub fn col_alphabet_to_num(n: &str) -> Result<usize> {\n\n let chars: Vec<char> = n.chars().into_iter().collect();\n\n let mut digit = chars.len();\n\n let mut result = 0usize;\n\n for each in chars {\n\n let num_at_digi...
Rust
2d-games/match-three/src/mgfw/ecs/entity.rs
Syn-Nine/rust-mini-games
b80fa60d524c8fb6749731cbc078a1a2526861ed
use super::*; use crate::mgfw::log; pub const ENTITY_SZ: usize = 256; #[derive(Copy, Clone)] pub struct EntityIdSpan { pub first: usize, pub last: usize, } struct Entity { components: u32, } pub struct EntityRegistry { data: *mut Entity, cursor: usize, span: EntityIdSpan, } #[allow(dead_code)] impl EntityRegistry { pub fn new(mgr: &mut CacheManager) -> EntityRegistry { log(format!("Constructing EntityRegistry")); let sz_bytes = std::mem::size_of::<Entity>() * ENTITY_SZ; EntityRegistry { data: mgr.allocate(sz_bytes) as *mut Entity, cursor: 0, span: EntityIdSpan { first: ENTITY_SZ - 1, last: 0, }, } } pub fn add(&mut self) -> usize { for _i in 0..ENTITY_SZ { if !self.has_component(self.cursor, COMPONENT_ACTIVE) { break; } self.cursor = (self.cursor + 1) % ENTITY_SZ; } if self.has_component(self.cursor, COMPONENT_ACTIVE) { log(format!( "WARNING: EntityRegistry: Ran out of available entity slots!" )); assert!(false); } self.add_component(self.cursor, COMPONENT_ACTIVE); self.cursor } pub fn add_component(&mut self, idx: usize, component: u32) { let entity = self.get_data_ref_mut(idx); entity.components |= component; if idx < self.span.first { self.span.first = idx; } if idx > self.span.last { self.span.last = idx; } } pub fn has_component(&self, idx: usize, component: u32) -> bool { let entity = self.get_data_ref(idx); (entity.components & component) == component } pub fn set_active(&mut self, idx: usize, val: bool) { self.overwrite_component(idx, COMPONENT_VISIBLE, val); } pub fn is_active(&self, idx: usize) -> bool { return self.has_component(idx, COMPONENT_ACTIVE); } pub fn set_visibility(&mut self, idx: usize, val: bool) { self.overwrite_component(idx, COMPONENT_VISIBLE, val); } pub fn is_visible(&self, idx: usize) -> bool { return self.has_component(idx, COMPONENT_VISIBLE); } pub fn clear_component(&mut self, idx: usize, component: u32) { let entity = self.get_data_ref_mut(idx); entity.components &= !component; if COMPONENT_ACTIVE == component && (idx == self.span.first || idx == self.span.last) { self.update_span(); } } pub fn overwrite_component(&mut self, idx: usize, component: u32, val: bool) { self.clear_component(idx, component); if val { self.add_component(idx, component); } } pub fn get_id_span(&self) -> EntityIdSpan { self.span } fn update_span(&mut self) { self.span = EntityIdSpan { first: ENTITY_SZ - 1, last: 0, }; for idx in 0..ENTITY_SZ { if self.has_component(idx, COMPONENT_ACTIVE) { if idx < self.span.first { self.span.first = idx; } if idx > self.span.last { self.span.last = idx; } } } } fn get_data_ref_mut(&self, idx: usize) -> &mut Entity { assert!(idx < ENTITY_SZ); unsafe { &mut *(self.data.offset(idx as isize)) } } fn get_data_ref(&self, idx: usize) -> &Entity { assert!(idx < ENTITY_SZ); unsafe { &*(self.data.offset(idx as isize)) } } }
use super::*; use crate::mgfw::log; pub const ENTITY_SZ: usize = 256; #[derive(Copy, Clone)] pub struct EntityIdSpan { pub first: usize, pub last: usize, } struct Entity { components: u32, } pub struct EntityRegistry { data: *mut Entity, cursor: usize, span: EntityIdSpan, } #[allow(dead_code)] impl EntityRegistry { pub fn new(mgr: &mut CacheManager) -> EntityRegistry { log(format!("Constructing EntityRegistry")); let sz_bytes = std::mem::size_of::<Entity>() * ENTITY_SZ; EntityRegistry { data: mgr.allocate(sz_bytes) as *mut Entity, cursor: 0, span: EntityIdSpan { first: ENTITY_SZ - 1, last: 0, }, } } pub fn add(&mut self) -> usize { for _i in 0..ENTITY_SZ { if !self.has_component(self.cursor, COMPONENT_ACTIVE) { break; } self.cursor = (self.cursor + 1) % ENTITY_SZ; } if self.has_component(self.cursor, COMPONENT_ACTIVE) { log(format!( "WARNING: EntityRegistry: Ran out of available entity slots!" )); assert!(false); } self.add_component(self.cursor, COMPONENT_ACTIVE); self.cursor } pub fn add_component(&mut self, idx: usize, component: u32) { let entity = self.get_data_ref_mut(idx); entity.components |= component; if idx < self.span.first { self.span.first = idx; } if idx > self.span.last { self.span.last = idx; } } pub fn has_component(&self, idx: usize, component: u32) -> bool { let entity = self.get_data_ref(idx); (entity.components & component) == component } pub fn set_active(&mut self, idx: usize, val: bool) { self.overwrite_component(idx, COMPONENT_VISIBLE, val); } pub fn is_active(&self, idx: usize) -> bool { return self.has_component(idx, COMPONENT_ACTIVE); } pub fn set_visibility(&mut self, idx: usize, val: bool) { self.overwrite_component(idx, COMPONENT_VISIBLE, val); } pub fn is_visible(&self, idx: usize) -> bool { return self.has_component(idx, COMPONENT_VISIBLE); } pub fn clear_component(&mut self, idx: usize, component: u32) { let entity = self.get_data_ref_mut(idx); entity.components &= !component; if COMPONENT_ACTIVE == component && (idx == self.span.first || idx == self.span.last) { self.update_span(); } } pub fn overwrite_component(&mut self, idx: usize, component: u32, val: bool) { self.clear_component(idx, component); if val { self.add_component(idx, component); } } pub fn get_id_span(&self) -> EntityIdSpan { self.span } fn update_span(&mut self) { self.span = EntityIdSpan { first: ENTITY_SZ - 1, last: 0, }; for idx in 0..ENTITY_SZ {
} } fn get_data_ref_mut(&self, idx: usize) -> &mut Entity { assert!(idx < ENTITY_SZ); unsafe { &mut *(self.data.offset(idx as isize)) } } fn get_data_ref(&self, idx: usize) -> &Entity { assert!(idx < ENTITY_SZ); unsafe { &*(self.data.offset(idx as isize)) } } }
if self.has_component(idx, COMPONENT_ACTIVE) { if idx < self.span.first { self.span.first = idx; } if idx > self.span.last { self.span.last = idx; } }
if_condition
[ { "content": "// update the entities for the cursor\n\npub fn update_cursor_entities(cache: &mut GameData, world: &mut mgfw::ecs::World) {\n\n let mut j: usize = 0;\n\n let loc = get_cursor_location(cache);\n\n let cx: f32 = loc.0 as f32 * 16.0 + 8.0;\n\n let cy: f32 = loc.1 as f32 * 16.0 + 56.0;\n\...
Rust
src/window/glutin.rs
jutuon/space-boss-battles
407d3fa1f057ea0ce9b05b6f695349be1f3a141f
use std::os::raw::c_void; use glutin::{EventsLoop, GlContext, WindowBuilder, ContextBuilder, GlWindow, GlRequest, Api, VirtualKeyCode}; use input::{InputManager, Key, Input}; use renderer::{Renderer, DEFAULT_SCREEN_HEIGHT, DEFAULT_SCREEN_WIDTH}; use settings::Settings; use gui::GUI; use logic::Logic; use utils::{TimeManager, TimeMilliseconds}; use audio::{Audio, Volume, AudioPlayer}; use super::{Window, RenderingContext, WINDOW_TITLE}; pub struct GlutinWindow { rendering_context: RenderingContext, events_loop: EventsLoop, window: GlWindow, mouse_x: i32, mouse_y: i32, } impl Window for GlutinWindow { type AudioPlayer = AudioPlayerRodio; fn new(rendering_context: RenderingContext) -> Result<Self, ()> { let events_loop = EventsLoop::new(); let window_builder = WindowBuilder::new() .with_title(WINDOW_TITLE) .with_dimensions(DEFAULT_SCREEN_WIDTH as u32, DEFAULT_SCREEN_HEIGHT as u32) .with_min_dimensions(DEFAULT_SCREEN_WIDTH as u32, DEFAULT_SCREEN_HEIGHT as u32); let gl_request = match rendering_context { RenderingContext::OpenGL => GlRequest::Specific(Api::OpenGl, (3,3)), RenderingContext::OpenGLES => GlRequest::Specific(Api::OpenGlEs, (2,0)), }; let context_builder = ContextBuilder::new() .with_gl(gl_request) .with_vsync(true); let gl_window = match GlWindow::new(window_builder, context_builder, &events_loop) { Ok(window) => window, Err(error) => { println!("couldn't create window: {}", error); return Err(()); } }; unsafe { if let Err(error) = gl_window.make_current() { println!("couldn't make OpenGL context current: {}", error); return Err(()); } } let window = Self { rendering_context, window: gl_window, events_loop, mouse_x: 0, mouse_y: 0, }; Ok(window) } fn handle_events<R: Renderer>( &mut self, input_manager: &mut InputManager, renderer: &mut R, settings: &mut Settings, gui: &mut GUI, logic: &mut Logic, quit_flag: &mut bool, time_manager: &TimeManager, ) { use glutin::{Event, WindowEvent, KeyboardInput, ElementState}; let mouse_x = &mut self.mouse_x; let mouse_y = &mut self.mouse_y; self.events_loop.poll_events(|event| { match event { Event::WindowEvent { event: window_event, ..} => { match window_event { WindowEvent::Resized(width, height) => { renderer.update_screen_size(width as i32, height as i32); gui.update_position_from_half_screen_width(renderer.half_screen_width_world_coordinates()); logic.update_half_screen_width(renderer.half_screen_width_world_coordinates()); }, WindowEvent::Closed => *quit_flag = true, WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(keycode), .. }, .. } => { if let Some(key) = virtual_keycode_to_key(keycode) { input_manager.update_key_down(key, time_manager.current_time()); } } WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Released, virtual_keycode: Some(keycode), .. }, .. } => { if let Some(key) = virtual_keycode_to_key(keycode) { input_manager.update_key_up(key, time_manager.current_time()); } } WindowEvent::MouseInput { state: ElementState::Released, ..} => { input_manager.update_mouse_button_up(renderer.screen_coordinates_to_world_coordinates(*mouse_x, *mouse_y)); }, WindowEvent::CursorMoved { position: (x, y), ..} => { *mouse_x = x as i32; *mouse_y = y as i32; input_manager.update_mouse_motion(renderer.screen_coordinates_to_world_coordinates(*mouse_x, *mouse_y)); }, _ => (), } }, _ => (), } }) } fn swap_buffers(&mut self) -> Result<(), ()> { self.window.swap_buffers().map_err(|error| { println!("couldn't swap buffers: {}", error); }) } fn set_fullscreen(&mut self, value: bool) { if value { let current_monitor = self.window.get_current_monitor(); self.window.set_fullscreen(Some(current_monitor)); } else { self.window.set_fullscreen(None); } } fn set_v_sync(&mut self, value: bool) { } fn rendering_context(&self) -> RenderingContext { self.rendering_context } fn gl_get_proc_address(&self, function_name: &str) -> *const c_void { self.window.get_proc_address(function_name) as *const c_void } fn add_game_controller_mappings(&mut self, game_controller_mappings: &Vec<String>) { } fn audio_player(&mut self) -> Option<Self::AudioPlayer> { None } } pub struct AudioPlayerRodio { } impl AudioPlayer for AudioPlayerRodio { type Music = AudioRodio; type Effect = AudioRodio; } pub struct AudioRodio { } impl Audio for AudioRodio { type Volume = VolumeRodio; fn load(file_path: &str) -> Result<Self, String> { unimplemented!() } fn play(&mut self) { unimplemented!() } fn change_volume(&mut self, volume: Self::Volume) { unimplemented!() } } #[derive(Debug, Clone, Copy)] pub struct VolumeRodio { } impl Volume for VolumeRodio { type Value = i32; const MAX_VOLUME: Self::Value = 0; const DEFAULT_VOLUME_PERCENTAGE: i32 = 0; fn new(volume: Self::Value) -> Self { unimplemented!() } fn value(&self) -> Self::Value { unimplemented!() } fn from_percentage(percentage: i32) -> Self { let percentage = if percentage < 0 { 0 } else if 100 < percentage { 100 } else { percentage }; VolumeRodio {} } } fn virtual_keycode_to_key(keycode: VirtualKeyCode) -> Option<Key> { let key = match keycode { VirtualKeyCode::Up | VirtualKeyCode::W => Key::Up, VirtualKeyCode::Down | VirtualKeyCode::S => Key::Down, VirtualKeyCode::Left | VirtualKeyCode::A => Key::Left, VirtualKeyCode::Right | VirtualKeyCode::D => Key::Right, VirtualKeyCode::Space | VirtualKeyCode::LControl | VirtualKeyCode::RControl => Key::Shoot, VirtualKeyCode::Return => Key::Select, VirtualKeyCode::Escape => Key::Back, _ => return None, }; Some(key) }
use std::os::raw::c_void; use glutin::{EventsLoop, GlContext, WindowBuilder, ContextBuilder, GlWindow, GlRequest, Api, VirtualKeyCode}; use input::{InputManager, Key, Input}; use renderer::{Renderer, DEFAULT_SCREEN_HEIGHT, DEFAULT_SCREEN_WIDTH}; use settings::Settings; use gui::GUI; use logic::Logic; use utils::{TimeManager, TimeMilliseconds}; use audio::{Audio, Volume, AudioPlayer}; use super::{Window, RenderingContext, WINDOW_TITLE}; pub struct GlutinWindow { rendering_context: RenderingContext, events_loop: EventsLoop, window: GlWindow, mouse_x: i32, mouse_y: i32, } impl Window for GlutinWindow { type AudioPlayer = AudioPlayerRodio; fn new(rendering_context: RenderingContext) -> Result<Self, ()> { let events_loop = EventsLoop::new(); let window_builder = WindowBuilder::new() .with_title(WINDOW_TITLE) .with_dimensions(DEFAULT_SCREEN_WIDTH as u32, DEFAULT_SCREEN_HEIGHT as u32) .with_min_dimensions(DEFAULT_SCREEN_WIDTH as u32, DEFAULT_SCREEN_HEIGHT as u32); let gl_request = match rendering_context { RenderingContext::OpenGL => GlRequest::Specific(Api::OpenGl, (3,3)), RenderingContext::OpenGLES => GlRequest::Specific(Api::OpenGlEs, (2,0)), }; let context_builder = ContextBuilder::new() .with_gl(gl_request) .with_vsync(true); let gl_window = match GlWindow::new(window_builder, context_builder, &events_loop) { Ok(window) => window, Err(error) => { println!("couldn't create window: {}", error); return Err(()); } }; unsafe { if let Err(error) = gl_window.make_current() { println!("couldn't make OpenGL context current: {}", error); return Err(()); } } let window = Self { rendering_context, window: gl_window, events_loop, mouse_x: 0, mouse_y: 0, }; Ok(window) } fn handle_events<R: Renderer>( &mut self, input_manager: &mut InputManager, renderer: &mut R, settings: &mut Settings, gui: &mut GUI, logic: &mut Logic, quit_flag: &mut bool, time_manager: &TimeManager, ) { use glutin::{Event, WindowEvent, KeyboardInput, ElementState}; let mouse_x = &mut self.mouse_x; let mouse_y = &mut self.mouse_y; self.events_loop.poll_events(|event| { match event { Event::WindowEvent { event: window_event, ..} => { match window_event { WindowEvent::Resized(width, height) => { renderer.update_screen_size(width as i32, height as i32); gui.update_position_from_half_screen_width(renderer.half_screen_width_world_coordinates()); logic.update_half_screen_width(renderer.half_screen_width_world_coordinates()); }, WindowEvent::Closed => *quit_flag = true, WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Pressed, virtual_keycode: Some(keycode), .. }, .. } => {
} WindowEvent::KeyboardInput { input: KeyboardInput { state: ElementState::Released, virtual_keycode: Some(keycode), .. }, .. } => { if let Some(key) = virtual_keycode_to_key(keycode) { input_manager.update_key_up(key, time_manager.current_time()); } } WindowEvent::MouseInput { state: ElementState::Released, ..} => { input_manager.update_mouse_button_up(renderer.screen_coordinates_to_world_coordinates(*mouse_x, *mouse_y)); }, WindowEvent::CursorMoved { position: (x, y), ..} => { *mouse_x = x as i32; *mouse_y = y as i32; input_manager.update_mouse_motion(renderer.screen_coordinates_to_world_coordinates(*mouse_x, *mouse_y)); }, _ => (), } }, _ => (), } }) } fn swap_buffers(&mut self) -> Result<(), ()> { self.window.swap_buffers().map_err(|error| { println!("couldn't swap buffers: {}", error); }) } fn set_fullscreen(&mut self, value: bool) { if value { let current_monitor = self.window.get_current_monitor(); self.window.set_fullscreen(Some(current_monitor)); } else { self.window.set_fullscreen(None); } } fn set_v_sync(&mut self, value: bool) { } fn rendering_context(&self) -> RenderingContext { self.rendering_context } fn gl_get_proc_address(&self, function_name: &str) -> *const c_void { self.window.get_proc_address(function_name) as *const c_void } fn add_game_controller_mappings(&mut self, game_controller_mappings: &Vec<String>) { } fn audio_player(&mut self) -> Option<Self::AudioPlayer> { None } } pub struct AudioPlayerRodio { } impl AudioPlayer for AudioPlayerRodio { type Music = AudioRodio; type Effect = AudioRodio; } pub struct AudioRodio { } impl Audio for AudioRodio { type Volume = VolumeRodio; fn load(file_path: &str) -> Result<Self, String> { unimplemented!() } fn play(&mut self) { unimplemented!() } fn change_volume(&mut self, volume: Self::Volume) { unimplemented!() } } #[derive(Debug, Clone, Copy)] pub struct VolumeRodio { } impl Volume for VolumeRodio { type Value = i32; const MAX_VOLUME: Self::Value = 0; const DEFAULT_VOLUME_PERCENTAGE: i32 = 0; fn new(volume: Self::Value) -> Self { unimplemented!() } fn value(&self) -> Self::Value { unimplemented!() } fn from_percentage(percentage: i32) -> Self { let percentage = if percentage < 0 { 0 } else if 100 < percentage { 100 } else { percentage }; VolumeRodio {} } } fn virtual_keycode_to_key(keycode: VirtualKeyCode) -> Option<Key> { let key = match keycode { VirtualKeyCode::Up | VirtualKeyCode::W => Key::Up, VirtualKeyCode::Down | VirtualKeyCode::S => Key::Down, VirtualKeyCode::Left | VirtualKeyCode::A => Key::Left, VirtualKeyCode::Right | VirtualKeyCode::D => Key::Right, VirtualKeyCode::Space | VirtualKeyCode::LControl | VirtualKeyCode::RControl => Key::Shoot, VirtualKeyCode::Return => Key::Select, VirtualKeyCode::Escape => Key::Back, _ => return None, }; Some(key) }
if let Some(key) = virtual_keycode_to_key(keycode) { input_manager.update_key_down(key, time_manager.current_time()); }
if_condition
[ { "content": "/// Returns the value of boolean reference and sets\n\n/// references value to false.\n\nfn return_and_reset(value: &mut bool) -> bool {\n\n let original_value: bool = *value;\n\n *value = false;\n\n original_value\n\n}\n\n\n\nimpl Input for InputManager {\n\n fn up(&self) -> bool {...
Rust
crates/fluvio-test/src/tests/longevity/mod.rs
bohlmannc/fluvio
b5a3105600b6886c55d76707d369fa59f5d9673b
pub mod producer; pub mod consumer; use core::panic; use std::any::Any; use std::num::ParseIntError; use std::time::Duration; use structopt::StructOpt; use fluvio_test_derive::fluvio_test; use fluvio_test_util::test_meta::environment::EnvironmentSetup; use fluvio_test_util::test_meta::{TestOption, TestCase}; use fluvio_test_util::async_process; #[derive(Debug, Clone)] pub struct LongevityTestCase { pub environment: EnvironmentSetup, pub option: LongevityTestOption, } impl From<TestCase> for LongevityTestCase { fn from(test_case: TestCase) -> Self { let longevity_option = test_case .option .as_any() .downcast_ref::<LongevityTestOption>() .expect("LongevityTestOption") .to_owned(); LongevityTestCase { environment: test_case.environment, option: longevity_option, } } } #[derive(Debug, Clone, StructOpt, Default, PartialEq)] #[structopt(name = "Fluvio Longevity Test")] pub struct LongevityTestOption { #[structopt(long, parse(try_from_str = parse_seconds), default_value = "3600")] runtime_seconds: Duration, #[structopt(long, default_value = "1000")] record_size: usize, #[structopt(long, default_value = "1")] pub producers: u32, #[structopt(long, default_value = "1")] pub consumers: u32, #[structopt(long, short)] verbose: bool, } fn parse_seconds(s: &str) -> Result<Duration, ParseIntError> { let seconds = s.parse::<u64>()?; Ok(Duration::from_secs(seconds)) } impl TestOption for LongevityTestOption { fn as_any(&self) -> &dyn Any { self } } #[fluvio_test(topic = "longevity")] pub fn longevity(mut test_driver: FluvioTestDriver, mut test_case: TestCase) { let option: LongevityTestCase = test_case.into(); println!("Starting Longevity Test"); println!("Expected runtime: {:?}", option.option.runtime_seconds); println!("# Consumers: {}", option.option.consumers); println!("# Producers: {}", option.option.producers); if !option.option.verbose { println!("Run with `--verbose` flag for more test output"); } let mut consumer_wait = Vec::new(); for i in 0..option.option.consumers { println!("Starting Consumer #{}", i); let consumer = async_process!(async { test_driver .connect() .await .expect("Connecting to cluster failed"); consumer::consumer_stream(test_driver.clone(), option.clone(), i).await }); consumer_wait.push(consumer); } let mut producer_wait = Vec::new(); for i in 0..option.option.producers { println!("Starting Producer #{}", i); let producer = async_process!(async { test_driver .connect() .await .expect("Connecting to cluster failed"); producer::producer(test_driver, option, i).await }); producer_wait.push(producer); } let _: Vec<_> = consumer_wait .into_iter() .map(|c| c.join().expect("Consumer thread fail")) .collect(); let _: Vec<_> = producer_wait .into_iter() .map(|p| p.join().expect("Producer thread fail")) .collect(); }
pub mod producer; pub mod consumer; use core::panic; use std::any::Any; use std::num::ParseIntError; use std::time::Duration; use structopt::StructOpt; use fluvio_test_derive::fluvio_test; use fluvio_test_util::test_meta::environment::EnvironmentSetup; use fluvio_test_util::test_meta::{TestOption, TestCase}; use fluvio_test_util::async_process; #[derive(Debug, Clone)] pub struct LongevityTestCase { pub environment: EnvironmentSetup, pub option: LongevityTestOption, } impl From<TestCase> for LongevityTestCase { fn from(test_case: TestCase) -> Self { let longevity_option = test_cas
} #[derive(Debug, Clone, StructOpt, Default, PartialEq)] #[structopt(name = "Fluvio Longevity Test")] pub struct LongevityTestOption { #[structopt(long, parse(try_from_str = parse_seconds), default_value = "3600")] runtime_seconds: Duration, #[structopt(long, default_value = "1000")] record_size: usize, #[structopt(long, default_value = "1")] pub producers: u32, #[structopt(long, default_value = "1")] pub consumers: u32, #[structopt(long, short)] verbose: bool, } fn parse_seconds(s: &str) -> Result<Duration, ParseIntError> { let seconds = s.parse::<u64>()?; Ok(Duration::from_secs(seconds)) } impl TestOption for LongevityTestOption { fn as_any(&self) -> &dyn Any { self } } #[fluvio_test(topic = "longevity")] pub fn longevity(mut test_driver: FluvioTestDriver, mut test_case: TestCase) { let option: LongevityTestCase = test_case.into(); println!("Starting Longevity Test"); println!("Expected runtime: {:?}", option.option.runtime_seconds); println!("# Consumers: {}", option.option.consumers); println!("# Producers: {}", option.option.producers); if !option.option.verbose { println!("Run with `--verbose` flag for more test output"); } let mut consumer_wait = Vec::new(); for i in 0..option.option.consumers { println!("Starting Consumer #{}", i); let consumer = async_process!(async { test_driver .connect() .await .expect("Connecting to cluster failed"); consumer::consumer_stream(test_driver.clone(), option.clone(), i).await }); consumer_wait.push(consumer); } let mut producer_wait = Vec::new(); for i in 0..option.option.producers { println!("Starting Producer #{}", i); let producer = async_process!(async { test_driver .connect() .await .expect("Connecting to cluster failed"); producer::producer(test_driver, option, i).await }); producer_wait.push(producer); } let _: Vec<_> = consumer_wait .into_iter() .map(|c| c.join().expect("Consumer thread fail")) .collect(); let _: Vec<_> = producer_wait .into_iter() .map(|p| p.join().expect("Producer thread fail")) .collect(); }
e .option .as_any() .downcast_ref::<LongevityTestOption>() .expect("LongevityTestOption") .to_owned(); LongevityTestCase { environment: test_case.environment, option: longevity_option, } }
function_block-function_prefixed
[ { "content": "fn cluster_cleanup(option: EnvironmentSetup) {\n\n if option.cluster_delete() {\n\n let mut setup = TestCluster::new(option);\n\n\n\n let cluster_cleanup_wait = async_process!(async {\n\n setup.remove_cluster().await;\n\n });\n\n let _ = cluster_cleanup_wa...
Rust
src/octez/node.rs
tzConnectBerlin/que-pasa
c79769fbe7aa8d0ef3e1d104bb45f68bf63a7c7d
use crate::octez::block::{Block, LevelMeta}; use anyhow::{anyhow, Context, Result}; use backoff::{retry, Error, ExponentialBackoff}; use chrono::{DateTime, Utc}; use curl::easy::Easy; use serde::Deserialize; use std::str::FromStr; use std::time::Duration; #[derive(Clone)] pub struct NodeClient { node_url: String, chain: String, timeout: Duration, } impl NodeClient { pub fn new(node_url: String, chain: String) -> Self { Self { node_url, chain, timeout: Duration::from_secs(20), } } pub(crate) fn head(&self) -> Result<LevelMeta> { let (meta, _) = self.level_json_internal("head")?; Ok(meta) } pub(crate) fn level_json(&self, level: u32) -> Result<(LevelMeta, Block)> { self.level_json_internal(&format!("{}", level)) } fn level_json_internal(&self, level: &str) -> Result<(LevelMeta, Block)> { let (body, _) = self .load_retry_on_nonjson(&format!("blocks/{}", level)) .with_context(|| { format!("failed to get level_json for level={}", level) })?; let mut deserializer = serde_json::Deserializer::from_str(&body); deserializer.disable_recursion_limit(); let block: Block = Block::deserialize(&mut deserializer) .with_context(|| anyhow!("failed to deserialize block json"))?; let meta = LevelMeta { level: block.header.level as u32, hash: Some(block.hash.clone()), prev_hash: Some(block.header.predecessor.clone()), baked_at: Some(Self::timestamp_from_block(&block)?), }; Ok((meta, block)) } pub(crate) fn get_contract_storage_definition( &self, contract_id: &str, level: Option<u32>, ) -> Result<serde_json::Value> { let level = match level { Some(x) => format!("{}", x), None => "head".to_string(), }; let (_, json) = self .load_retry_on_nonjson(&format!( "blocks/{}/context/contracts/{}/script", level, contract_id )) .with_context(|| { format!( "failed to get script data for contract='{}', level={}", contract_id, level ) })?; for entry in json["code"].as_array().ok_or_else(|| { anyhow!("malformed script response (missing 'code' field)") })? { if let Some(prim) = entry.as_object().ok_or_else(|| anyhow!("malformed script response ('code' array element is not an object)"))?.get("prim") { if prim == &serde_json::Value::String("storage".to_string()) { return Ok(entry["args"].as_array().ok_or_else(|| anyhow!("malformed script response ('storage' entry does not have 'args' field)"))?[0].clone()); } } else { return Err(anyhow!("malformed script response ('code' array element does not have a field 'prim')")); } } Err(anyhow!("malformed script response ('code' array does not have 'storage' entry)")) } fn parse_rfc3339(rfc3339: &str) -> Result<DateTime<Utc>> { let fixedoffset = chrono::DateTime::parse_from_rfc3339(rfc3339)?; Ok(fixedoffset.with_timezone(&Utc)) } fn timestamp_from_block(block: &Block) -> Result<DateTime<Utc>> { Self::parse_rfc3339(block.header.timestamp.as_str()) } fn load_retry_on_nonjson( &self, endpoint: &str, ) -> Result<(String, serde_json::Value)> { fn transient_err(e: anyhow::Error) -> Error<anyhow::Error> { if e.is::<curl::Error>() { let curl_err = e.downcast::<curl::Error>(); if curl_err.is_err() { let downcast_err = curl_err.err().unwrap(); error!("unexpected err on possibly transcient err downcast: {}", downcast_err); return Error::Permanent(downcast_err); } match curl_err.as_ref().ok().unwrap().code() { 7 | 28 => { warn!("transient node communication error, retrying.. err={:?}", curl_err); return Error::Transient(anyhow!("{:?}", curl_err)); } _ => {} }; let curl_err_val = curl_err.ok().unwrap(); return Error::Permanent(anyhow!( "{} {} (curl status code: {})", curl_err_val.description(), curl_err_val .extra_description() .map(|descr| format!("(verbose: {})", descr)) .unwrap_or_else(|| "".to_string()), curl_err_val.code(), )); } warn!("transient node communication error, retrying.. err={:?}", e); Error::Transient(e) } let op = || -> Result<(String, serde_json::Value)> { let body = self.load(endpoint)?; let mut deserializer = serde_json::Deserializer::from_str(&body); deserializer.disable_recursion_limit(); let deserializer = serde_stacker::Deserializer::new(&mut deserializer); let json = serde_json::Value::deserialize(deserializer)?; Ok((body, json)) }; retry(ExponentialBackoff::default(), || { op().map_err(transient_err) }) .map_err(|e| anyhow!(e)) } fn load(&self, endpoint: &str) -> Result<String> { let uri = format!("{}/chains/{}/{}", self.node_url, self.chain, endpoint); debug!("loading: {}", uri); let mut resp_data = Vec::new(); let mut handle = Easy::new(); handle .timeout(self.timeout) .with_context(|| { format!( "failed to set timeout to curl handle for uri='{}'", uri ) })?; handle.url(&uri).with_context(|| { format!("failed to call endpoint, uri='{}'", uri) })?; { let mut transfer = handle.transfer(); transfer.write_function(|new_data| { resp_data.extend_from_slice(new_data); Ok(new_data.len()) })?; transfer.perform().with_context(|| { format!("failed load response for uri='{}'", uri) })?; } let body = std::str::from_utf8(&resp_data).with_context(|| { format!("failed to parse response as utf8 for uri='{}'", uri) })?; Ok(body.to_string()) } } pub(crate) trait StorageGetter { fn get_contract_storage( &self, contract_id: &str, level: u32, ) -> Result<serde_json::Value>; fn get_bigmap_value( &self, level: u32, bigmap_id: i32, keyhash: &str, ) -> Result<Option<serde_json::Value>>; } impl StorageGetter for NodeClient { fn get_contract_storage( &self, contract_id: &str, level: u32, ) -> Result<serde_json::Value> { self.load_retry_on_nonjson(&format!( "blocks/{}/context/contracts/{}/storage", level, contract_id )) .map(|(_, json)| json) .with_context(|| { format!( "failed to get storage for contract='{}', level={}", contract_id, level ) }) } fn get_bigmap_value( &self, level: u32, bigmap_id: i32, keyhash: &str, ) -> Result<Option<serde_json::Value>> { let body = self.load(&format!( "blocks/{}/context/big_maps/{}/{}", level, bigmap_id, keyhash, )) .with_context(|| { format!( "failed to get value for bigmap (level={}, bigmap_id={}, keyhash={})", level, bigmap_id, keyhash, ) })?; Ok(serde_json::Value::from_str(&body).ok()) } }
use crate::octez::block::{Block, LevelMeta}; use anyhow::{anyhow, Context, Result}; use backoff::{retry, Error, ExponentialBackoff}; use chrono::{DateTime, Utc}; use curl::easy::Easy; use serde::Deserialize; use std::str::FromStr; use std::time::Duration; #[derive(Clone)] pub struct NodeClient { node_url: String, chain: String, timeout: Duration, } impl NodeClient { pub fn new(node_url: String, chain: String) -> Self { Self { node_url, chain, timeout: Duration::from_secs(20), } } pub(crate) fn head(&self) -> Result<LevelMeta> { let (meta, _) = self.level_json_internal("head")?; Ok(meta) } pub(crate) fn level_json(&self, level: u32) -> Result<(LevelMeta, Block)> { self.level_json_internal(&format!("{}", level)) }
pub(crate) fn get_contract_storage_definition( &self, contract_id: &str, level: Option<u32>, ) -> Result<serde_json::Value> { let level = match level { Some(x) => format!("{}", x), None => "head".to_string(), }; let (_, json) = self .load_retry_on_nonjson(&format!( "blocks/{}/context/contracts/{}/script", level, contract_id )) .with_context(|| { format!( "failed to get script data for contract='{}', level={}", contract_id, level ) })?; for entry in json["code"].as_array().ok_or_else(|| { anyhow!("malformed script response (missing 'code' field)") })? { if let Some(prim) = entry.as_object().ok_or_else(|| anyhow!("malformed script response ('code' array element is not an object)"))?.get("prim") { if prim == &serde_json::Value::String("storage".to_string()) { return Ok(entry["args"].as_array().ok_or_else(|| anyhow!("malformed script response ('storage' entry does not have 'args' field)"))?[0].clone()); } } else { return Err(anyhow!("malformed script response ('code' array element does not have a field 'prim')")); } } Err(anyhow!("malformed script response ('code' array does not have 'storage' entry)")) } fn parse_rfc3339(rfc3339: &str) -> Result<DateTime<Utc>> { let fixedoffset = chrono::DateTime::parse_from_rfc3339(rfc3339)?; Ok(fixedoffset.with_timezone(&Utc)) } fn timestamp_from_block(block: &Block) -> Result<DateTime<Utc>> { Self::parse_rfc3339(block.header.timestamp.as_str()) } fn load_retry_on_nonjson( &self, endpoint: &str, ) -> Result<(String, serde_json::Value)> { fn transient_err(e: anyhow::Error) -> Error<anyhow::Error> { if e.is::<curl::Error>() { let curl_err = e.downcast::<curl::Error>(); if curl_err.is_err() { let downcast_err = curl_err.err().unwrap(); error!("unexpected err on possibly transcient err downcast: {}", downcast_err); return Error::Permanent(downcast_err); } match curl_err.as_ref().ok().unwrap().code() { 7 | 28 => { warn!("transient node communication error, retrying.. err={:?}", curl_err); return Error::Transient(anyhow!("{:?}", curl_err)); } _ => {} }; let curl_err_val = curl_err.ok().unwrap(); return Error::Permanent(anyhow!( "{} {} (curl status code: {})", curl_err_val.description(), curl_err_val .extra_description() .map(|descr| format!("(verbose: {})", descr)) .unwrap_or_else(|| "".to_string()), curl_err_val.code(), )); } warn!("transient node communication error, retrying.. err={:?}", e); Error::Transient(e) } let op = || -> Result<(String, serde_json::Value)> { let body = self.load(endpoint)?; let mut deserializer = serde_json::Deserializer::from_str(&body); deserializer.disable_recursion_limit(); let deserializer = serde_stacker::Deserializer::new(&mut deserializer); let json = serde_json::Value::deserialize(deserializer)?; Ok((body, json)) }; retry(ExponentialBackoff::default(), || { op().map_err(transient_err) }) .map_err(|e| anyhow!(e)) } fn load(&self, endpoint: &str) -> Result<String> { let uri = format!("{}/chains/{}/{}", self.node_url, self.chain, endpoint); debug!("loading: {}", uri); let mut resp_data = Vec::new(); let mut handle = Easy::new(); handle .timeout(self.timeout) .with_context(|| { format!( "failed to set timeout to curl handle for uri='{}'", uri ) })?; handle.url(&uri).with_context(|| { format!("failed to call endpoint, uri='{}'", uri) })?; { let mut transfer = handle.transfer(); transfer.write_function(|new_data| { resp_data.extend_from_slice(new_data); Ok(new_data.len()) })?; transfer.perform().with_context(|| { format!("failed load response for uri='{}'", uri) })?; } let body = std::str::from_utf8(&resp_data).with_context(|| { format!("failed to parse response as utf8 for uri='{}'", uri) })?; Ok(body.to_string()) } } pub(crate) trait StorageGetter { fn get_contract_storage( &self, contract_id: &str, level: u32, ) -> Result<serde_json::Value>; fn get_bigmap_value( &self, level: u32, bigmap_id: i32, keyhash: &str, ) -> Result<Option<serde_json::Value>>; } impl StorageGetter for NodeClient { fn get_contract_storage( &self, contract_id: &str, level: u32, ) -> Result<serde_json::Value> { self.load_retry_on_nonjson(&format!( "blocks/{}/context/contracts/{}/storage", level, contract_id )) .map(|(_, json)| json) .with_context(|| { format!( "failed to get storage for contract='{}', level={}", contract_id, level ) }) } fn get_bigmap_value( &self, level: u32, bigmap_id: i32, keyhash: &str, ) -> Result<Option<serde_json::Value>> { let body = self.load(&format!( "blocks/{}/context/big_maps/{}/{}", level, bigmap_id, keyhash, )) .with_context(|| { format!( "failed to get value for bigmap (level={}, bigmap_id={}, keyhash={})", level, bigmap_id, keyhash, ) })?; Ok(serde_json::Value::from_str(&body).ok()) } }
fn level_json_internal(&self, level: &str) -> Result<(LevelMeta, Block)> { let (body, _) = self .load_retry_on_nonjson(&format!("blocks/{}", level)) .with_context(|| { format!("failed to get level_json for level={}", level) })?; let mut deserializer = serde_json::Deserializer::from_str(&body); deserializer.disable_recursion_limit(); let block: Block = Block::deserialize(&mut deserializer) .with_context(|| anyhow!("failed to deserialize block json"))?; let meta = LevelMeta { level: block.header.level as u32, hash: Some(block.hash.clone()), prev_hash: Some(block.header.predecessor.clone()), baked_at: Some(Self::timestamp_from_block(&block)?), }; Ok((meta, block)) }
function_block-full_function
[ { "content": "fn is_implicit_active(level: u32, contract_address: &str) -> bool {\n\n // liquidity baking has 2 implicit contract creation events in the block prior to Granada's activation block\n\n level == LIQUIDITY_BAKING_LEVEL\n\n && (contract_address == LIQUIDITY_BAKING\n\n || contr...
Rust
benches/custom_benches.rs
IzumiRaine/libdeflater
3a90be5798fc9949e9a416efeaba4663ac7d4e25
extern crate flate2; extern crate libdeflater; use std::io::prelude::*; use std::fs; use std::fs::{File}; use std::path::Path; use criterion::{Criterion, black_box}; use flate2::{Compression, Compress, Decompress, FlushCompress, FlushDecompress}; use libdeflater::{Compressor, CompressionLvl, Decompressor}; struct Flate2Encoder { compress: Compress, } impl Flate2Encoder { fn new() -> Flate2Encoder { Flate2Encoder{ compress: Compress::new(Compression::default(), true) } } fn encode(&mut self, data: &[u8], out: &mut Vec<u8>) { self.compress.compress_vec(data, out, FlushCompress::Finish).unwrap(); self.compress.reset(); } } struct Flate2Decoder { decompress: Decompress, } impl Flate2Decoder { fn new() -> Flate2Decoder { Flate2Decoder { decompress: Decompress::new(true) } } fn decode(&mut self, compressed_data: &[u8], _decomp_sz: usize, out: &mut Vec<u8>) { self.decompress.decompress_vec(compressed_data, out, FlushDecompress::Finish).unwrap(); self.decompress.reset(true); } } struct LibdeflateEncoder { compressor: Compressor, } impl LibdeflateEncoder { fn new() -> LibdeflateEncoder { LibdeflateEncoder { compressor: Compressor::new(CompressionLvl::default()), } } fn encode(&mut self, data: &[u8], out: &mut Vec<u8>) { unsafe { out.set_len(self.compressor.zlib_compress_bound(data.len())); let actual = self.compressor.zlib_compress(data, out).unwrap(); out.set_len(actual); } } } struct LibdeflateDecoder { st: Decompressor, } impl LibdeflateDecoder { fn new() -> LibdeflateDecoder { LibdeflateDecoder { st: Decompressor::new() } } fn decode(&mut self, zlib_data: &[u8], decomp_sz: usize, out: &mut Vec<u8>) { unsafe { out.set_len(decomp_sz); let sz = self.st.zlib_decompress(zlib_data, out).unwrap(); out.set_len(sz); } } } pub fn run_custom_benches(b: &mut Criterion) { let (entries, biggest_entry) = { let mut biggest: u64 = 0; let mut entries = Vec::new(); let path = Path::new("bench_data"); for entry in fs::read_dir(path).unwrap() { let entry = entry.unwrap(); let pth = entry.path(); let sz = entry.metadata().unwrap().len(); let filename = pth.file_name().unwrap().to_str().unwrap(); if entry.metadata().unwrap().is_file() && !filename.contains("README.md") { entries.push(pth); biggest = if sz > biggest { sz } else { biggest } } } (entries, biggest as usize) }; let buf_big_enough_to_fit_data = biggest_entry + 100; let mut buf: Vec<u8> = Vec::with_capacity(buf_big_enough_to_fit_data); let mut flate2_encoder = Flate2Encoder::new(); let mut libdeflate_encoder = LibdeflateEncoder::new(); let mut flate2_decoder = Flate2Decoder::new(); let mut libdeflate_decoder = LibdeflateDecoder::new(); for pth in entries { let k = pth.file_name().unwrap().to_str().unwrap(); let mut grp = b.benchmark_group(k); grp.sample_size(20); let raw_data = { let mut file = File::open(&pth).unwrap(); let mut data = Vec::new(); file.read_to_end(&mut data).unwrap(); data }; grp.bench_function("flate2_encode", |b| b.iter(|| { buf.clear(); flate2_encoder.encode(black_box(&raw_data), black_box(&mut buf)); })); grp.bench_function("libdeflate_encode", |b| b.iter(|| { buf.clear(); libdeflate_encoder.encode(black_box(&raw_data), black_box(&mut buf)); })); let compressed_data = { let mut buf = Vec::with_capacity(buf_big_enough_to_fit_data); Flate2Encoder::new().encode(&raw_data, &mut buf); buf }; grp.bench_function("flate2_decode", |b| b.iter(|| { buf.clear(); flate2_decoder.decode(black_box(&compressed_data), black_box(raw_data.len()), black_box(&mut buf)); })); grp.bench_function("libdeflate_decode", |b| b.iter(|| { buf.clear(); libdeflate_decoder.decode(black_box(&compressed_data), black_box(raw_data.len()), black_box(&mut buf)); })); grp.finish(); } }
extern crate flate2; extern crate libdeflater; use std::io::prelude::*; use std::fs; use std::fs::{File}; use std::path::Path; use crit
inish(); } }
erion::{Criterion, black_box}; use flate2::{Compression, Compress, Decompress, FlushCompress, FlushDecompress}; use libdeflater::{Compressor, CompressionLvl, Decompressor}; struct Flate2Encoder { compress: Compress, } impl Flate2Encoder { fn new() -> Flate2Encoder { Flate2Encoder{ compress: Compress::new(Compression::default(), true) } } fn encode(&mut self, data: &[u8], out: &mut Vec<u8>) { self.compress.compress_vec(data, out, FlushCompress::Finish).unwrap(); self.compress.reset(); } } struct Flate2Decoder { decompress: Decompress, } impl Flate2Decoder { fn new() -> Flate2Decoder { Flate2Decoder { decompress: Decompress::new(true) } } fn decode(&mut self, compressed_data: &[u8], _decomp_sz: usize, out: &mut Vec<u8>) { self.decompress.decompress_vec(compressed_data, out, FlushDecompress::Finish).unwrap(); self.decompress.reset(true); } } struct LibdeflateEncoder { compressor: Compressor, } impl LibdeflateEncoder { fn new() -> LibdeflateEncoder { LibdeflateEncoder { compressor: Compressor::new(CompressionLvl::default()), } } fn encode(&mut self, data: &[u8], out: &mut Vec<u8>) { unsafe { out.set_len(self.compressor.zlib_compress_bound(data.len())); let actual = self.compressor.zlib_compress(data, out).unwrap(); out.set_len(actual); } } } struct LibdeflateDecoder { st: Decompressor, } impl LibdeflateDecoder { fn new() -> LibdeflateDecoder { LibdeflateDecoder { st: Decompressor::new() } } fn decode(&mut self, zlib_data: &[u8], decomp_sz: usize, out: &mut Vec<u8>) { unsafe { out.set_len(decomp_sz); let sz = self.st.zlib_decompress(zlib_data, out).unwrap(); out.set_len(sz); } } } pub fn run_custom_benches(b: &mut Criterion) { let (entries, biggest_entry) = { let mut biggest: u64 = 0; let mut entries = Vec::new(); let path = Path::new("bench_data"); for entry in fs::read_dir(path).unwrap() { let entry = entry.unwrap(); let pth = entry.path(); let sz = entry.metadata().unwrap().len(); let filename = pth.file_name().unwrap().to_str().unwrap(); if entry.metadata().unwrap().is_file() && !filename.contains("README.md") { entries.push(pth); biggest = if sz > biggest { sz } else { biggest } } } (entries, biggest as usize) }; let buf_big_enough_to_fit_data = biggest_entry + 100; let mut buf: Vec<u8> = Vec::with_capacity(buf_big_enough_to_fit_data); let mut flate2_encoder = Flate2Encoder::new(); let mut libdeflate_encoder = LibdeflateEncoder::new(); let mut flate2_decoder = Flate2Decoder::new(); let mut libdeflate_decoder = LibdeflateDecoder::new(); for pth in entries { let k = pth.file_name().unwrap().to_str().unwrap(); let mut grp = b.benchmark_group(k); grp.sample_size(20); let raw_data = { let mut file = File::open(&pth).unwrap(); let mut data = Vec::new(); file.read_to_end(&mut data).unwrap(); data }; grp.bench_function("flate2_encode", |b| b.iter(|| { buf.clear(); flate2_encoder.encode(black_box(&raw_data), black_box(&mut buf)); })); grp.bench_function("libdeflate_encode", |b| b.iter(|| { buf.clear(); libdeflate_encoder.encode(black_box(&raw_data), black_box(&mut buf)); })); let compressed_data = { let mut buf = Vec::with_capacity(buf_big_enough_to_fit_data); Flate2Encoder::new().encode(&raw_data, &mut buf); buf }; grp.bench_function("flate2_decode", |b| b.iter(|| { buf.clear(); flate2_decoder.decode(black_box(&compressed_data), black_box(raw_data.len()), black_box(&mut buf)); })); grp.bench_function("libdeflate_decode", |b| b.iter(|| { buf.clear(); libdeflate_decoder.decode(black_box(&compressed_data), black_box(raw_data.len()), black_box(&mut buf)); })); grp.f
random
[ { "content": "#[test]\n\nfn test_use_crc32_convenience_method_returns_same_crc32_as_flate2() {\n\n // This assumes that flate2's crc32 implementation returns a\n\n // correct value, which is a pretty safe assumption.\n\n\n\n let input_data = read_fixture_content();\n\n\n\n let flate2_crc32 = {\n\n ...
Rust
aoc13/src/main.rs
jadeaffenjaeger/rust_aoc19
4f3f4160377cbfdb76207ab942afc8306b201b2d
use intcomputer::*; use display::*; use std::env; use std::fs; use num_enum::TryFromPrimitive; use std::convert::TryFrom; const WIDTH: usize = 44; const HEIGHT: usize = 20; const SCALE: usize = 25; #[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)] #[repr(i64)] enum Tile { Empty = 0, Wall = 1, Block = 2, Paddle = 3, Ball = 4, } struct Arcade<'a> { screen: [Tile; WIDTH * HEIGHT], display: &'a mut Display, computer: IntComputer, score: u32, } impl<'a> Arcade<'a> { pub fn new(program: Vec<i64>, display: &'a mut Display) -> Self { Self { display: display, screen: [Tile::Empty; WIDTH * HEIGHT], computer: IntComputer::new(program), score: 0, } } pub fn run(&mut self) { loop { self.computer.run(); match self.computer.state { ProgramState::Finished => break, ProgramState::Running => continue, ProgramState::WaitingForInput => { self.consume_output(); break; } } } } pub fn left(&mut self) { self.computer.input.push_back(-1); } pub fn right(&mut self) { self.computer.input.push_back(1); } pub fn neutral(&mut self) { self.computer.input.push_back(0); } pub fn consume_output(&mut self) { while self.computer.output.len() > 0 { let x = self.computer.output.pop_front().unwrap(); let y = self.computer.output.pop_front().unwrap(); if x == -1 && y == 0 { let score = self.computer.output.pop_front().unwrap() as u32; self.score = score; } else { let tile = Tile::try_from(self.computer.output.pop_front().unwrap()).unwrap(); self.screen[(x as usize) + (y as usize) * WIDTH] = tile; self.display.set_pixel(x as usize, y as usize, tile as u32); } } } } fn main() -> Result<(), String> { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename).unwrap(); let mut display= Display::new(WIDTH, HEIGHT, SCALE, "Aoc Day 13"); let mut program: Vec<i64> = contents .trim() .split(',') .map(|x| x.parse().unwrap()) .collect(); let mut arcade = Arcade::new(program.clone(), &mut display); arcade.run(); arcade.consume_output(); let blocktiles = arcade.screen.iter().filter(|&&t| t == Tile::Block).count(); println!("Solution Part 1: {:?}", blocktiles); program[0] = 2; let mut arcade = Arcade::new(program, &mut display); loop { arcade.run(); if arcade.computer.state == ProgramState::Finished || arcade.display.update() == false { break; } let get_pos = |tiletype| { arcade .screen .iter() .enumerate() .filter(|(_, &t)| t == tiletype) .next() .unwrap() }; let ball_x = get_pos(Tile::Ball).0 % WIDTH; let paddle_x = get_pos(Tile::Paddle).0 % WIDTH; if ball_x < paddle_x { arcade.left() } if ball_x > paddle_x { arcade.right() } if ball_x == paddle_x { arcade.neutral() } } arcade.consume_output(); println!("Solution Part 2: {}", arcade.score); Ok(()) }
use intcomputer::*; use display::*; use std::env; use std::fs; use num_enum::TryFromPrimitive; use std::convert::TryFrom; const WIDTH: usize = 44; const HEIGHT: usize = 20; const SCALE: usize = 25; #[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)] #[repr(i64)] enum Tile { Empty = 0, Wall = 1, Block = 2, Paddle = 3, Ball = 4, } struct Arcade<'a> { screen: [Tile; WIDTH * HEIGHT], display: &'a mut Display, computer: IntComputer, score: u32, } impl<'a> Arcade<'a> { pub fn new(program: Vec<i64>, display: &'a mut Display) -> Self { Self { display: display, screen: [Tile::Empty; WIDTH * HEIGHT], computer: IntComputer::new(program), score: 0, } } pub fn run(&mut self) { loo
pub fn left(&mut self) { self.computer.input.push_back(-1); } pub fn right(&mut self) { self.computer.input.push_back(1); } pub fn neutral(&mut self) { self.computer.input.push_back(0); } pub fn consume_output(&mut self) { while self.computer.output.len() > 0 { let x = self.computer.output.pop_front().unwrap(); let y = self.computer.output.pop_front().unwrap(); if x == -1 && y == 0 { let score = self.computer.output.pop_front().unwrap() as u32; self.score = score; } else { let tile = Tile::try_from(self.computer.output.pop_front().unwrap()).unwrap(); self.screen[(x as usize) + (y as usize) * WIDTH] = tile; self.display.set_pixel(x as usize, y as usize, tile as u32); } } } } fn main() -> Result<(), String> { let args: Vec<String> = env::args().collect(); let filename = &args[1]; let contents = fs::read_to_string(filename).unwrap(); let mut display= Display::new(WIDTH, HEIGHT, SCALE, "Aoc Day 13"); let mut program: Vec<i64> = contents .trim() .split(',') .map(|x| x.parse().unwrap()) .collect(); let mut arcade = Arcade::new(program.clone(), &mut display); arcade.run(); arcade.consume_output(); let blocktiles = arcade.screen.iter().filter(|&&t| t == Tile::Block).count(); println!("Solution Part 1: {:?}", blocktiles); program[0] = 2; let mut arcade = Arcade::new(program, &mut display); loop { arcade.run(); if arcade.computer.state == ProgramState::Finished || arcade.display.update() == false { break; } let get_pos = |tiletype| { arcade .screen .iter() .enumerate() .filter(|(_, &t)| t == tiletype) .next() .unwrap() }; let ball_x = get_pos(Tile::Ball).0 % WIDTH; let paddle_x = get_pos(Tile::Paddle).0 % WIDTH; if ball_x < paddle_x { arcade.left() } if ball_x > paddle_x { arcade.right() } if ball_x == paddle_x { arcade.neutral() } } arcade.consume_output(); println!("Solution Part 2: {}", arcade.score); Ok(()) }
p { self.computer.run(); match self.computer.state { ProgramState::Finished => break, ProgramState::Running => continue, ProgramState::WaitingForInput => { self.consume_output(); break; } } } }
function_block-function_prefixed
[ { "content": "fn combine_layers(layer: &[u32], image: &mut [u32]) {\n\n let combine_pixels = |top, bottom| match top {\n\n 2 => bottom,\n\n _ => top,\n\n };\n\n\n\n for (p1, p2) in image.iter_mut().zip(layer.iter()) {\n\n *p1 = combine_pixels(*p1, *p2);\n\n }\n\n}\n\n\n", "f...
Rust
textures/src/imagemap.rs
hackmad/pbr_rust
b7ae75564bf71c4dfea8b20f49d05ac1b89e6734
use super::*; use core::geometry::*; use core::interaction::*; use core::mipmap::*; use core::pbrt::*; use core::spectrum::*; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign}; #[derive(Clone)] pub struct ImageTexture<Tmemory> where Tmemory: Copy + Default + Mul<Float, Output = Tmemory> + MulAssign<Float> + Div<Float, Output = Tmemory> + DivAssign<Float> + Add<Tmemory, Output = Tmemory> + AddAssign + Clamp<Float>, Spectrum: ConvertIn<Tmemory>, { mapping: ArcTextureMapping2D, mipmap: ArcMIPMap<Tmemory>, } macro_rules! new_image_texture { ($t: ty) => { impl ImageTexture<$t> { pub fn new( mapping: ArcTextureMapping2D, path: &str, filtering_method: FilteringMethod, wrap_mode: ImageWrap, scale: Float, gamma: bool, max_anisotropy: Float, ) -> Self { let tex_info = TexInfo::new( path, filtering_method, wrap_mode, scale, gamma, max_anisotropy, ); let mipmap = match MIPMapCache::get(tex_info) { Ok(mipmap) => mipmap, Err(err) => panic!("Unable to load MIPMap: {}", err), }; Self { mapping, mipmap } } } }; } new_image_texture!(RGBSpectrum); new_image_texture!(Float); impl Texture<Spectrum> for ImageTexture<RGBSpectrum> { fn evaluate(&self, hit: &Hit, uv: &Point2f, der: &Derivatives) -> Spectrum { let TextureMap2DResult { p: st, dstdx, dstdy, } = self.mapping.map(hit, uv, der); let mem = self.mipmap.lookup(&st, &dstdx, &dstdy); let rgb = mem.to_rgb(); Spectrum::from_rgb(&rgb, None) } } impl Texture<Float> for ImageTexture<Float> { fn evaluate(&self, hit: &Hit, uv: &Point2f, der: &Derivatives) -> Float { let TextureMap2DResult { p: st, dstdx, dstdy, } = self.mapping.map(hit, uv, der); self.mipmap.lookup(&st, &dstdx, &dstdy) } } macro_rules! from_params { ($t: ty) => { impl From<(&TextureParams, ArcTransform, &str)> for ImageTexture<$t> { fn from(p: (&TextureParams, ArcTransform, &str)) -> Self { let (tp, tex2world, cwd) = p; let map = get_texture_mapping(tp, tex2world); let max_anisotropy = tp.find_float("maxanisotropy", 8.0); let filtering_method = if tp.find_bool("trilinear", false) { FilteringMethod::Trilinear } else { FilteringMethod::Ewa }; let wrap = tp.find_string("wrap", String::from("repeat")); let wrap_mode = match &wrap[..] { "black" => ImageWrap::Black, "clamp" => ImageWrap::Clamp, _ => ImageWrap::Repeat, }; let scale = tp.find_float("scale", 1.0); let path = tp.find_filename("filename", String::from(""), cwd); let gamma = tp.find_bool("gamma", path.ends_with(".tga") || path.ends_with(".png")); Self::new( map, &path, filtering_method, wrap_mode, scale, gamma, max_anisotropy, ) } } }; } from_params!(RGBSpectrum); from_params!(Float);
use super::*; use core::geometry::*; use core::interaction::*; use core::mipmap::*; use core::pbrt::*; use core::spectrum::*; use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign}; #[derive(Clone)] pub struct ImageTexture<Tmemory> where Tmemory: Copy + Default + Mul<Float, Output = Tmemory> + MulAssign<Float> + Div<Float, Output = Tmemory> + DivAssign<Float> + Add<Tmemory, Output = Tmemory> + AddAssign + Clamp<Float>, Spectrum: ConvertIn<Tmemory>, { mapping: ArcTextureMapping2D, mipmap: ArcMIPMap<Tmemory>, } macro_rules! new_image_texture { ($t: ty) => { impl ImageTexture<$t> { pub fn new( mapping: ArcTextureMapping2D, path: &str, filtering_method: FilteringMethod, wrap_mode: ImageWrap, scale: Float, gamma: bool, max_anisotropy: Float, ) -> Self { let tex_info = TexInfo::new( path, filtering_method, wrap_mode, scale, gamma, max_anisotropy, ); let mipmap = match MIPMapCache::get(tex_info) { Ok(mipmap) => mipmap, Err(err) => panic!("Unable to load MIPMap: {}", err), }; Self { mapping, mipmap } } } }; } new_image_texture!(RGBSpectrum); new_image_texture!(Float); impl Texture<Spectrum> for ImageTexture<RGBSpectrum> { fn evaluate(&self, hit: &Hit, uv: &Point2f, der: &Derivatives) -> Spectrum {
let mem = self.mipmap.lookup(&st, &dstdx, &dstdy); let rgb = mem.to_rgb(); Spectrum::from_rgb(&rgb, None) } } impl Texture<Float> for ImageTexture<Float> { fn evaluate(&self, hit: &Hit, uv: &Point2f, der: &Derivatives) -> Float { let TextureMap2DResult { p: st, dstdx, dstdy, } = self.mapping.map(hit, uv, der); self.mipmap.lookup(&st, &dstdx, &dstdy) } } macro_rules! from_params { ($t: ty) => { impl From<(&TextureParams, ArcTransform, &str)> for ImageTexture<$t> { fn from(p: (&TextureParams, ArcTransform, &str)) -> Self { let (tp, tex2world, cwd) = p; let map = get_texture_mapping(tp, tex2world); let max_anisotropy = tp.find_float("maxanisotropy", 8.0); let filtering_method = if tp.find_bool("trilinear", false) { FilteringMethod::Trilinear } else { FilteringMethod::Ewa }; let wrap = tp.find_string("wrap", String::from("repeat")); let wrap_mode = match &wrap[..] { "black" => ImageWrap::Black, "clamp" => ImageWrap::Clamp, _ => ImageWrap::Repeat, }; let scale = tp.find_float("scale", 1.0); let path = tp.find_filename("filename", String::from(""), cwd); let gamma = tp.find_bool("gamma", path.ends_with(".tga") || path.ends_with(".png")); Self::new( map, &path, filtering_method, wrap_mode, scale, gamma, max_anisotropy, ) } } }; } from_params!(RGBSpectrum); from_params!(Float);
let TextureMap2DResult { p: st, dstdx, dstdy, } = self.mapping.map(hit, uv, der);
assignment_statement
[]
Rust
imxrt1062-pac/imxrt1062-ocotp/src/crc_addr.rs
Shock-1/teensy4-rs
effc3b290f1be3c7aef62a78e82dbfbc27aa6370
#[doc = "Reader of register CRC_ADDR"] pub type R = crate::R<u32, super::CRC_ADDR>; #[doc = "Writer for register CRC_ADDR"] pub type W = crate::W<u32, super::CRC_ADDR>; #[doc = "Register CRC_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::CRC_ADDR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DATA_START_ADDR`"] pub type DATA_START_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DATA_START_ADDR`"] pub struct DATA_START_ADDR_W<'a> { w: &'a mut W, } impl<'a> DATA_START_ADDR_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 & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `DATA_END_ADDR`"] pub type DATA_END_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DATA_END_ADDR`"] pub struct DATA_END_ADDR_W<'a> { w: &'a mut W, } impl<'a> DATA_END_ADDR_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 & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of field `CRC_ADDR`"] pub type CRC_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CRC_ADDR`"] pub struct CRC_ADDR_W<'a> { w: &'a mut W, } impl<'a> CRC_ADDR_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 & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `OTPMK_CRC`"] pub type OTPMK_CRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OTPMK_CRC`"] pub struct OTPMK_CRC_W<'a> { w: &'a mut W, } impl<'a> OTPMK_CRC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `RSVD0`"] pub type RSVD0_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - DATA_START_ADDR"] #[inline(always)] pub fn data_start_addr(&self) -> DATA_START_ADDR_R { DATA_START_ADDR_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - DATA_END_ADDR"] #[inline(always)] pub fn data_end_addr(&self) -> DATA_END_ADDR_R { DATA_END_ADDR_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - CRC_ADDR"] #[inline(always)] pub fn crc_addr(&self) -> CRC_ADDR_R { CRC_ADDR_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bit 24 - OTPMK_CRC"] #[inline(always)] pub fn otpmk_crc(&self) -> OTPMK_CRC_R { OTPMK_CRC_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 25:31 - RSVD0"] #[inline(always)] pub fn rsvd0(&self) -> RSVD0_R { RSVD0_R::new(((self.bits >> 25) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:7 - DATA_START_ADDR"] #[inline(always)] pub fn data_start_addr(&mut self) -> DATA_START_ADDR_W { DATA_START_ADDR_W { w: self } } #[doc = "Bits 8:15 - DATA_END_ADDR"] #[inline(always)] pub fn data_end_addr(&mut self) -> DATA_END_ADDR_W { DATA_END_ADDR_W { w: self } } #[doc = "Bits 16:23 - CRC_ADDR"] #[inline(always)] pub fn crc_addr(&mut self) -> CRC_ADDR_W { CRC_ADDR_W { w: self } } #[doc = "Bit 24 - OTPMK_CRC"] #[inline(always)] pub fn otpmk_crc(&mut self) -> OTPMK_CRC_W { OTPMK_CRC_W { w: self } } }
#[doc = "Reader of register CRC_ADDR"] pub type R = crate::R<u32, super::CRC_ADDR>; #[doc = "Writer for register CRC_ADDR"] pub type W = crate::W<u32, super::CRC_ADDR>; #[doc = "Register CRC_ADDR `reset()`'s with value 0"] impl crate::ResetValue for super::CRC_ADDR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DATA_START_ADDR`"] pub type DATA_START_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DATA_START_ADDR`"] pub struct DATA_START_ADDR_W<'a> { w: &'a mut W, } impl<'a> DATA_START_ADDR_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 & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `DATA_END_ADDR`"] pub type DATA_END_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DATA_END_ADDR`"] pub struct DATA_END_ADDR_W<'a> { w: &'a mut W, } impl<'a> DATA_END_ADDR_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 & !(0xff << 8)) | (((value as u32) & 0xff) << 8); self.w } } #[doc = "Reader of
{ OTPMK_CRC_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bits 25:31 - RSVD0"] #[inline(always)] pub fn rsvd0(&self) -> RSVD0_R { RSVD0_R::new(((self.bits >> 25) & 0x7f) as u8) } } impl W { #[doc = "Bits 0:7 - DATA_START_ADDR"] #[inline(always)] pub fn data_start_addr(&mut self) -> DATA_START_ADDR_W { DATA_START_ADDR_W { w: self } } #[doc = "Bits 8:15 - DATA_END_ADDR"] #[inline(always)] pub fn data_end_addr(&mut self) -> DATA_END_ADDR_W { DATA_END_ADDR_W { w: self } } #[doc = "Bits 16:23 - CRC_ADDR"] #[inline(always)] pub fn crc_addr(&mut self) -> CRC_ADDR_W { CRC_ADDR_W { w: self } } #[doc = "Bit 24 - OTPMK_CRC"] #[inline(always)] pub fn otpmk_crc(&mut self) -> OTPMK_CRC_W { OTPMK_CRC_W { w: self } } }
field `CRC_ADDR`"] pub type CRC_ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CRC_ADDR`"] pub struct CRC_ADDR_W<'a> { w: &'a mut W, } impl<'a> CRC_ADDR_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 & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } #[doc = "Reader of field `OTPMK_CRC`"] pub type OTPMK_CRC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OTPMK_CRC`"] pub struct OTPMK_CRC_W<'a> { w: &'a mut W, } impl<'a> OTPMK_CRC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "Reader of field `RSVD0`"] pub type RSVD0_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:7 - DATA_START_ADDR"] #[inline(always)] pub fn data_start_addr(&self) -> DATA_START_ADDR_R { DATA_START_ADDR_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - DATA_END_ADDR"] #[inline(always)] pub fn data_end_addr(&self) -> DATA_END_ADDR_R { DATA_END_ADDR_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:23 - CRC_ADDR"] #[inline(always)] pub fn crc_addr(&self) -> CRC_ADDR_R { CRC_ADDR_R::new(((self.bits >> 16) & 0xff) as u8) } #[doc = "Bit 24 - OTPMK_CRC"] #[inline(always)] pub fn otpmk_crc(&self) -> OTPMK_CRC_R
random
[]
Rust
src/transaction.rs
tiagolobocastro/heath
4faedf8f37acba0ac183273cfc0cd00286526ded
use crate::{ client::ClientId, csv::transaction::{TransactionId, TransactionLogCsv, TransactionType}, transactions::TransactionInfo, }; use serde::{Deserialize, Serialize}; impl TransactionInfo for TransactionLog { fn transaction_type(&self) -> TransactionType { match self { Self::Deposit { .. } => TransactionType::Deposit, Self::Withdrawal { .. } => TransactionType::Withdrawal, Self::Dispute { .. } => TransactionType::Dispute, Self::Resolve { .. } => TransactionType::Resolve, Self::Chargeback { .. } => TransactionType::Chargeback, } } fn client_id(&self) -> ClientId { match self { Self::Deposit { common, .. } => common.client_id, Self::Withdrawal { common, .. } => common.client_id, Self::Dispute { common } => common.client_id, Self::Resolve { common } => common.client_id, Self::Chargeback { common } => common.client_id, } } fn transaction_id(&self) -> TransactionId { match self { Self::Deposit { common, .. } => common.tx_id, Self::Withdrawal { common, .. } => common.tx_id, Self::Dispute { common } => common.tx_id, Self::Resolve { common } => common.tx_id, Self::Chargeback { common } => common.tx_id, } } fn amount(&self) -> Option<rust_decimal::Decimal> { match self { Self::Deposit { amount, .. } => Some(*amount), Self::Withdrawal { amount, .. } => Some(*amount), Self::Dispute { .. } => None, Self::Resolve { .. } => None, Self::Chargeback { .. } => None, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub(crate) enum TransactionLog { Deposit { #[serde(flatten)] common: TransactionLogCommon, #[serde(rename = "amount")] amount: rust_decimal::Decimal, }, Withdrawal { common: TransactionLogCommon, #[serde(rename = "amount")] amount: rust_decimal::Decimal, }, Dispute { #[serde(flatten)] common: TransactionLogCommon, }, Resolve { #[serde(flatten)] common: TransactionLogCommon, }, Chargeback { #[serde(flatten)] common: TransactionLogCommon, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) enum DisputeSate { Undisputed, Disputed(rust_decimal::Decimal), Chargeback, } impl Default for DisputeSate { fn default() -> Self { Self::Undisputed } } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct TransactionLogCommon { #[serde(rename = "client")] client_id: ClientId, #[serde(rename = "tx")] tx_id: TransactionId, } impl From<TransactionLogCsv> for TransactionLog { fn from(tx: TransactionLogCsv) -> Self { let common = TransactionLogCommon { client_id: tx.client_id(), tx_id: tx.transaction_id(), }; match tx.transaction_type() { TransactionType::Deposit => Self::Deposit { common, amount: tx.amount().expect("Deposit should contain the amount"), }, TransactionType::Withdrawal => Self::Withdrawal { common, amount: tx.amount().expect("Withdrawal should contain the amount"), }, TransactionType::Dispute => Self::Dispute { common }, TransactionType::Resolve => Self::Resolve { common }, TransactionType::Chargeback => Self::Chargeback { common }, } } } impl TransactionLog { #[allow(dead_code)] pub(crate) fn log_info(&self) { tracing::info!(type_=?self.transaction_type(), client=self.client_id(), tx=%self.transaction_id(), amount=?self.amount()); } }
use crate::{ client::ClientId, csv::transaction::{TransactionId, TransactionLogCsv, TransactionType}, transactions::TransactionInfo, }; use serde::{Deserialize, Serialize}; impl TransactionInfo for TransactionLog { fn transaction_type(&self) -> TransactionType { match self { Self::Deposit { .. } => TransactionType::Deposit, Self::Withdrawal { .. } => TransactionType::Withdrawal, Self::Dispute { .. } => TransactionType::Dispute, Self::Resolve { .. } => TransactionType::Resolve, Self::Chargeback { .. } => TransactionType::Chargeback, } } fn client_id(&self) -> ClientId { match self { Self::Deposit { common, .. } => common.client_id, Self::Withdrawal { common, .. } => common.client_id, Self::Dispute { common } => common.client_id, Self::Resolve { common } => common.client_id, Self::Chargeback { common } => common.client_id, } } fn transaction_id(&self) -> TransactionId { match self { Self::Deposit { common, .. } => common.tx_id, Self::Withdrawal { common, .. } => common.tx_id, Self::Dispute { common } => common.tx_id, Self::Resolve { common } => common.tx_id, Self::Chargeback { common } => common.tx_id, } } fn amount(&self) -> Option<rust_decimal::Decimal> { match self { Self::Deposit { amount, .. } => Some(*amount), Self::Withdrawal { amount, .. } => Some(*amount), Self::Dispute { .. } => None, Self::Resolve { .. } => None, Self::Chargeback { .. } => None, } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type")] pub(crate) enum TransactionLog { Deposit { #[serde(flatten)] common: TransactionLogCommon, #[serde(rename = "amount")] amount: rust_decimal::Decimal, }, Withdrawal { common: TransactionLogCommon, #[serde(rename = "amount")] amount: rust_decimal::Decimal, }, Dispute { #[serde(flatten)] common: TransactionLogCommon, }, Resolve { #[serde(flatten)] common: TransactionLogCommon, }, Chargeback { #[serde(flatten)] common: TransactionLogCommon, }, } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) enum DisputeSate { Undisputed, Disputed(rust_decimal::Decimal), Chargeback, } impl Default for DisputeSate { fn default() -> Self { Self::Undisputed } } #[derive(Debug, Clone, Serialize, Deserialize)] pub(crate) struct TransactionLogCommon { #[serde(rename = "client")] client_id: ClientId, #[serde(rename = "tx")] tx_id: TransactionId, } impl From<TransactionLogCsv> for TransactionLog { fn from(tx: TransactionLogCsv) -> Self {
match tx.transaction_type() { TransactionType::Deposit => Self::Deposit { common, amount: tx.amount().expect("Deposit should contain the amount"), }, TransactionType::Withdrawal => Self::Withdrawal { common, amount: tx.amount().expect("Withdrawal should contain the amount"), }, TransactionType::Dispute => Self::Dispute { common }, TransactionType::Resolve => Self::Resolve { common }, TransactionType::Chargeback => Self::Chargeback { common }, } } } impl TransactionLog { #[allow(dead_code)] pub(crate) fn log_info(&self) { tracing::info!(type_=?self.transaction_type(), client=self.client_id(), tx=%self.transaction_id(), amount=?self.amount()); } }
let common = TransactionLogCommon { client_id: tx.client_id(), tx_id: tx.transaction_id(), };
assignment_statement
[ { "content": " account: BankAccount,\n\n disputed_tx: Option<TransactionLog>,\n\n}\n\nimpl Dispute {\n\n pub(crate) fn new(account: BankAccount, disputed_tx: Option<TransactionLog>) -> Self {\n\n Self {\n\n account,\n\n disputed_tx,\n\n }\n\n }\n\n}\n\nimpl Transa...
Rust
src/terminal/winapi_terminal.rs
Rukenshia/crossterm
caa7579ef6102f966a7436f55c2dfda2e30efb5a
use {Construct}; use cursor::cursor; use super::{ClearType, ITerminal}; use winapi::um::wincon::{SMALL_RECT, COORD, CONSOLE_SCREEN_BUFFER_INFO,}; use kernel::windows_kernel::{kernel, terminal}; pub struct WinApiTerminal; impl Construct for WinApiTerminal { fn new() -> Box<WinApiTerminal> { Box::from(WinApiTerminal {}) } } impl ITerminal for WinApiTerminal { fn clear(&self, clear_type: ClearType) { let csbi = kernel::get_console_screen_buffer_info(); let pos = cursor().pos(); match clear_type { ClearType::All => clear_entire_screen(csbi), ClearType::FromCursorDown => clear_after_cursor(pos,csbi), ClearType::FromCursorUp => clear_before_cursor(pos, csbi), ClearType::CurrentLine => clear_current_line(pos, csbi), ClearType::UntilNewLine => clear_until_line(pos, csbi), }; } fn terminal_size(&self) -> (u16, u16) { terminal::terminal_size() } fn scroll_up(&self, count: i16) { } fn scroll_down(&self, count: i16) { let csbi = kernel::get_console_screen_buffer_info(); let mut srct_window; srct_window = csbi.srWindow; if srct_window.Bottom < csbi.dwSize.Y - count { srct_window.Top += count; srct_window.Bottom += count; let success = kernel::set_console_info(true, &mut srct_window); if success { panic!("Something went wrong when scrolling down"); } } } fn set_size(&self, width: i16, height: i16) { if width <= 0 { panic!("Cannot set the terminal width lower than 1"); } if height <= 0 { panic!("Cannot set the terminal height lower then 1") } let csbi = kernel::get_console_screen_buffer_info(); let mut success = false; let mut resize_buffer = false; let mut size = COORD { X: csbi.dwSize.X, Y: csbi.dwSize.Y }; if csbi.dwSize.X < csbi.srWindow.Left + width { if csbi.srWindow.Left >= i16::max_value() - width { panic!("Argument out of range when setting terminal width."); } size.X = csbi.srWindow.Left + width; resize_buffer = true; } if csbi.dwSize.Y < csbi.srWindow.Top + height { if csbi.srWindow.Top >= i16::max_value() - height { panic!("Argument out of range when setting terminal height"); } size.Y = csbi.srWindow.Top + height; resize_buffer = true; } if resize_buffer { success = kernel::set_console_screen_buffer_size(size); if !success { panic!("Something went wrong when setting screen buffer size."); } } let mut fsr_window: SMALL_RECT = csbi.srWindow; fsr_window.Bottom = fsr_window.Top + height; fsr_window.Right = fsr_window.Left + width; let success = kernel::set_console_info(true, &fsr_window); if success { if resize_buffer { kernel::set_console_screen_buffer_size(csbi.dwSize); } let bounds = kernel::get_largest_console_window_size(); if width > bounds.X { panic!("Argument width: {} out of range when setting terminal width.", width); } if height > bounds.Y { panic!("Argument height: {} out of range when setting terminal height", height); } } } } pub fn clear_after_cursor(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (mut x,mut y) = pos; if x as i16 > csbi.dwSize.X { y += 1; x = 0; } let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; clear(start_location,cells_to_write); } pub fn clear_before_cursor(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (xpos,ypos) = pos; let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = (csbi.dwSize.X as u32 * ypos as u32) + (xpos as u32 + 1); clear(start_location, cells_to_write); } pub fn clear_entire_screen(csbi: CONSOLE_SCREEN_BUFFER_INFO) { let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; clear( start_location, cells_to_write); cursor().goto(0, 0); } pub fn clear_current_line(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let x = 0; let y = pos.1; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32; clear(start_location, cells_to_write); cursor().goto(0, y); } pub fn clear_until_line(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (x,y) = pos; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = (csbi.dwSize.X - x as i16) as u32; clear(start_location, cells_to_write); cursor().goto(x,y); } fn clear( start_loaction: COORD, cells_to_write: u32 ) { let mut cells_written = 0; let mut success = false; success = kernel::fill_console_output_character(&mut cells_written, start_loaction, cells_to_write); if !success { panic!("Could not clear screen after cursor"); } cells_written = 0; success = kernel::fill_console_output_attribute(&mut cells_written, start_loaction, cells_to_write); if !success { panic!("Couldnot reset attributes after cursor"); } }
use {Construct}; use cursor::cursor; use super::{ClearType, ITerminal}; use winapi::um::wincon::{SMALL_RECT, COORD, CONSOLE_SCREEN_BUFFER_INFO,}; use kernel::windows_kernel::{kernel, terminal}; pub struct WinApiTerminal; impl Construct for WinApiTerminal { fn new() -> Box<WinApiTerminal> { Box::from(WinApiTerminal {}) } } impl ITerminal for WinApiTerminal { fn clear(&self, clear_type: ClearType) { let csbi = kernel::get_console_screen_buffer_info(); let pos = cursor().pos(); match clear_type { ClearType::All => clear_entire_screen(csbi), ClearType::FromCursorDown => clear_after_cursor(pos,csbi), ClearType::FromCursorUp => clear_before_cursor(pos, csbi), ClearType::CurrentLine => clear_current_line(pos, csbi), ClearType::UntilNewLine => clear_until_line(pos, csbi), }; } fn terminal_size(&self) -> (u16, u16) { terminal::terminal_size() } fn scroll_up(&self, count: i16) { } fn scroll_down(&self, count: i16) { let csbi = kernel::get_console_screen_buffer_info(); let mut srct_window; srct_window = csbi.srWindow; if srct_window.Bottom < csbi.dwSize.Y - count { srct_window.Top += count; srct_window.Bottom += count; let success = kernel::set_console_info(true, &mut srct_window); if success { panic!("Something went wrong when scrolling down"); } } } fn set_size(&self, width: i16, height: i16) { if width <= 0 { panic!("Cannot set the terminal width lower than 1"); } if height <= 0 { panic!("Cannot set the terminal height lower then 1") } let csbi = kernel::get_console_screen_buffer_info(); let mut success = false; let mut resize_buffer = false; let mut size = COORD { X: csbi.dwSize.X, Y: csbi.dwSize.Y }; if csbi.dwSize.X < csbi.srWindow.Left + width { if csbi.srWindow.Left >= i16::max_value() - width { panic!("Argument out of range when setting terminal width."); } size.X = csbi.srWindow.Left + width; resize_buffer = true; } if csbi.dwSize.Y < csbi.srWindow.Top + height { if csbi.srWindow.Top >= i16::max_value() - height { panic!("Argument out of range when setting terminal height"); } size.Y = csbi.srWindow.Top + height; resize_buffer = true; } if resize_buffer { success = kernel::set_console_screen_buffer_size(size); if !success { panic!("Something went wrong when setting screen buffer size."); } } let mut fsr_window: SMALL_RECT = csbi.srWindow; fsr_window.Bottom = fsr_window.Top + height; fsr_window.Right = fsr_window.Left + width; let success = kernel::set_console_info(true, &fsr_window); if success { if resize_buffer { kernel::set_console_screen_buffer_size(csbi.dwSize); } let bounds = kernel::get_largest_console_window_size(); if width > bounds.X { panic!("Argument width: {} out of range when setting terminal width.", width); } if height > bounds.Y { panic!("Argument height: {} out of range when setting terminal height", height); } } } } pub fn clear_after_cursor(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (mut x,mut y) = pos; if x as i16 > csbi.dwSize.X { y += 1; x = 0; } let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; clear(start_location,cells_to_write); }
pub fn clear_entire_screen(csbi: CONSOLE_SCREEN_BUFFER_INFO) { let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32 * csbi.dwSize.Y as u32; clear( start_location, cells_to_write); cursor().goto(0, 0); } pub fn clear_current_line(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let x = 0; let y = pos.1; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = csbi.dwSize.X as u32; clear(start_location, cells_to_write); cursor().goto(0, y); } pub fn clear_until_line(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (x,y) = pos; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = (csbi.dwSize.X - x as i16) as u32; clear(start_location, cells_to_write); cursor().goto(x,y); } fn clear( start_loaction: COORD, cells_to_write: u32 ) { let mut cells_written = 0; let mut success = false; success = kernel::fill_console_output_character(&mut cells_written, start_loaction, cells_to_write); if !success { panic!("Could not clear screen after cursor"); } cells_written = 0; success = kernel::fill_console_output_attribute(&mut cells_written, start_loaction, cells_to_write); if !success { panic!("Couldnot reset attributes after cursor"); } }
pub fn clear_before_cursor(pos: (u16,u16), csbi: CONSOLE_SCREEN_BUFFER_INFO) { let (xpos,ypos) = pos; let x = 0; let y = 0; let start_location = COORD { X: x as i16, Y: y as i16}; let cells_to_write = (csbi.dwSize.X as u32 * ypos as u32) + (xpos as u32 + 1); clear(start_location, cells_to_write); }
function_block-full_function
[ { "content": "pub fn set_console_screen_buffer_size( size: COORD) -> bool\n\n{\n\n let output_handle = get_output_handle();\n\n\n\n unsafe\n\n {\n\n let success = SetConsoleScreenBufferSize(output_handle, size);\n\n is_true(success)\n\n }\n\n}\n\n\n", "file_path": ...
Rust
src/skelly.rs
lain-dono/skelly
f161e4d3641c22fb764936bf441dac8434c3f9d1
use na::{Isometry3, Point3, RealField, Scalar, Translation3, UnitQuaternion}; pub struct Skelly<T: Scalar, D = ()> { bones: Vec<Bone<T, D>>, } struct Bone<T: Scalar, D> { isometry: Isometry3<T>, parent: Option<usize>, userdata: D, } impl<T> Skelly<T> where T: Scalar, { pub fn add_root(&mut self, position: Point3<T>) -> usize where T: RealField, { self.add_root_with(position, ()) } pub fn attach(&mut self, relative_position: Point3<T>, parent: usize) -> usize where T: RealField, { self.attach_with(relative_position, parent, ()) } } impl<T, D> Skelly<T, D> where T: Scalar, { pub fn new() -> Self { Skelly { bones: Vec::new() } } pub fn add_root_with(&mut self, position: Point3<T>, userdata: D) -> usize where T: RealField, { self.bones.push(Bone { isometry: Isometry3 { rotation: UnitQuaternion::identity(), translation: position.coords.into(), }, parent: None, userdata, }); self.bones.len() - 1 } pub fn attach_with(&mut self, relative_position: Point3<T>, parent: usize, userdata: D) -> usize where T: RealField, { assert!(parent < self.bones.len(), "Parent index is ouf of bounds"); self.bones.push(Bone { isometry: Isometry3 { rotation: UnitQuaternion::identity(), translation: relative_position.coords.into(), }, parent: Some(parent), userdata, }); self.bones.len() - 1 } pub fn rotate(&mut self, bone: usize, rotation: UnitQuaternion<T>) where T: RealField, { let bone = &mut self.bones[bone]; bone.isometry.rotation = bone.isometry.rotation * rotation; } pub fn translate_bone(&mut self, bone: usize, translation: Translation3<T>) where T: RealField, { let bone = &mut self.bones[bone]; bone.isometry.translation = bone.isometry.translation * translation; } pub fn set_bone_position(&mut self, bone: usize, position: Point3<T>) { self.bones[bone].isometry.translation = position.coords.into(); } pub fn get_userdata(&self, bone: usize) -> &D { &self.bones[bone].userdata } pub fn get_userdata_mut(&mut self, bone: usize) -> &mut D { &mut self.bones[bone].userdata } pub fn get_parent(&self, bone: usize) -> Option<usize> { self.bones[bone].parent } pub fn len(&self) -> usize { self.bones.len() } pub fn write_globals(&self, globals: &mut [Isometry3<T>]) where T: RealField, { self.bones .iter() .take(globals.len()) .enumerate() .for_each(|(index, bone)| match bone.parent { Some(parent) => { debug_assert!(parent < index); globals[index] = globals[parent] * bone.isometry; } None => { globals[index] = bone.isometry; } }) } pub fn write_globals_for_posture(&self, posture: &Posture<T>, globals: &mut [Isometry3<T>]) where T: RealField, { self.bones .iter() .zip(&posture.joints) .take(globals.len()) .enumerate() .for_each(|(index, (bone, isometry))| match bone.parent { Some(parent) => { debug_assert!(parent < index); globals[index] = globals[parent] * *isometry; } None => { globals[index] = *isometry; } }) } pub fn assume_posture(&mut self, posture: &Posture<T>) where T: Copy, { assert_eq!(self.bones.len(), posture.joints.len()); self.bones .iter_mut() .zip(&posture.joints) .for_each(|(bone, isometry)| bone.isometry = *isometry); } pub fn make_posture(&self) -> Posture<T> where T: Copy, { Posture { joints: self.bones.iter().map(|bone| bone.isometry).collect(), } } pub fn make_chain(&self, mut bone: usize, chain: &mut Vec<usize>) { while let Some(parent) = self.bones[bone].parent { chain.push(parent); bone = parent; } } } pub struct Posture<T: Scalar> { joints: Vec<Isometry3<T>>, } impl<T> Posture<T> where T: Scalar, { pub fn new(len: usize) -> Self where T: RealField, { Posture { joints: vec![Isometry3::identity(); len], } } pub fn len(&self) -> usize { self.joints.len() } pub fn get_joint(&self, bone: usize) -> &Isometry3<T> { &self.joints[bone] } pub fn get_joint_mut(&mut self, bone: usize) -> &mut Isometry3<T> { &mut self.joints[bone] } }
use na::{Isometry3, Point3, RealField, Scalar, Translation3, UnitQuaternion}; pub struct Skelly<T: Scalar, D = ()> { bones: Vec<Bone<T, D>>, } struct Bone<T: Scalar, D> { isometry: Isometry3<T>, parent: Option<usize>, userdata: D, } impl<T> Skelly<T> where T: Scalar, { pub fn add_root(&mut self, position: Point3<T>) -> usize where T: RealField, { self.add_root_with(position, ()) } pub fn a
mut self, bone: usize) -> &mut D { &mut self.bones[bone].userdata } pub fn get_parent(&self, bone: usize) -> Option<usize> { self.bones[bone].parent } pub fn len(&self) -> usize { self.bones.len() } pub fn write_globals(&self, globals: &mut [Isometry3<T>]) where T: RealField, { self.bones .iter() .take(globals.len()) .enumerate() .for_each(|(index, bone)| match bone.parent { Some(parent) => { debug_assert!(parent < index); globals[index] = globals[parent] * bone.isometry; } None => { globals[index] = bone.isometry; } }) } pub fn write_globals_for_posture(&self, posture: &Posture<T>, globals: &mut [Isometry3<T>]) where T: RealField, { self.bones .iter() .zip(&posture.joints) .take(globals.len()) .enumerate() .for_each(|(index, (bone, isometry))| match bone.parent { Some(parent) => { debug_assert!(parent < index); globals[index] = globals[parent] * *isometry; } None => { globals[index] = *isometry; } }) } pub fn assume_posture(&mut self, posture: &Posture<T>) where T: Copy, { assert_eq!(self.bones.len(), posture.joints.len()); self.bones .iter_mut() .zip(&posture.joints) .for_each(|(bone, isometry)| bone.isometry = *isometry); } pub fn make_posture(&self) -> Posture<T> where T: Copy, { Posture { joints: self.bones.iter().map(|bone| bone.isometry).collect(), } } pub fn make_chain(&self, mut bone: usize, chain: &mut Vec<usize>) { while let Some(parent) = self.bones[bone].parent { chain.push(parent); bone = parent; } } } pub struct Posture<T: Scalar> { joints: Vec<Isometry3<T>>, } impl<T> Posture<T> where T: Scalar, { pub fn new(len: usize) -> Self where T: RealField, { Posture { joints: vec![Isometry3::identity(); len], } } pub fn len(&self) -> usize { self.joints.len() } pub fn get_joint(&self, bone: usize) -> &Isometry3<T> { &self.joints[bone] } pub fn get_joint_mut(&mut self, bone: usize) -> &mut Isometry3<T> { &mut self.joints[bone] } }
ttach(&mut self, relative_position: Point3<T>, parent: usize) -> usize where T: RealField, { self.attach_with(relative_position, parent, ()) } } impl<T, D> Skelly<T, D> where T: Scalar, { pub fn new() -> Self { Skelly { bones: Vec::new() } } pub fn add_root_with(&mut self, position: Point3<T>, userdata: D) -> usize where T: RealField, { self.bones.push(Bone { isometry: Isometry3 { rotation: UnitQuaternion::identity(), translation: position.coords.into(), }, parent: None, userdata, }); self.bones.len() - 1 } pub fn attach_with(&mut self, relative_position: Point3<T>, parent: usize, userdata: D) -> usize where T: RealField, { assert!(parent < self.bones.len(), "Parent index is ouf of bounds"); self.bones.push(Bone { isometry: Isometry3 { rotation: UnitQuaternion::identity(), translation: relative_position.coords.into(), }, parent: Some(parent), userdata, }); self.bones.len() - 1 } pub fn rotate(&mut self, bone: usize, rotation: UnitQuaternion<T>) where T: RealField, { let bone = &mut self.bones[bone]; bone.isometry.rotation = bone.isometry.rotation * rotation; } pub fn translate_bone(&mut self, bone: usize, translation: Translation3<T>) where T: RealField, { let bone = &mut self.bones[bone]; bone.isometry.translation = bone.isometry.translation * translation; } pub fn set_bone_position(&mut self, bone: usize, position: Point3<T>) { self.bones[bone].isometry.translation = position.coords.into(); } pub fn get_userdata(&self, bone: usize) -> &D { &self.bones[bone].userdata } pub fn get_userdata_mut(&
random
[ { "content": "fn enque<T>(queue: &mut Vec<QueueItem<T>>, bone: usize, tip: Point3<T>, goal: Point3<T>)\n\nwhere\n\n T: Scalar,\n\n{\n\n let index = queue\n\n .binary_search_by(|item| item.bone.cmp(&bone))\n\n .unwrap_or_else(|x| x);\n\n\n\n queue.insert(index, QueueItem { bone, tip, goal ...
Rust
benches/spmc_mt_read_write_bench.rs
tower120/lockless_event_queue
aa55039161736c88b103a520f83ce8f8ab66288f
use rc_event_queue::spmc::{EventQueue, EventReader, Settings}; use criterion::{Criterion, black_box, criterion_main, criterion_group, BenchmarkId}; use std::time::{Duration, Instant}; use std::thread; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::pin::Pin; use rc_event_queue::{CleanupMode, LendingIterator}; const QUEUE_SIZE: usize = 100000; struct S{} impl Settings for S{ const MIN_CHUNK_SIZE: u32 = 512; const MAX_CHUNK_SIZE: u32 = 512; const CLEANUP: CleanupMode = CleanupMode::Never; } type Event = EventQueue<usize, S>; fn bench_event_read_write<F>(iters: u64, writer_fn: F) -> Duration where F: Fn(&mut Event, usize, usize) -> () + Send + 'static + Clone { let mut total = Duration::ZERO; let readers_thread_count = 4; for _ in 0..iters { let mut event = Event::new(); let mut readers = Vec::new(); for _ in 0..readers_thread_count{ readers.push(EventReader::new(&mut event)); } let writer_thread = { let writer_fn = writer_fn.clone(); Box::new(thread::spawn(move || { writer_fn(&mut event, 0, QUEUE_SIZE); })) }; let readers_stop = Arc::new(AtomicBool::new(false)); let mut reader_threads = Vec::new(); for mut reader in readers{ let readers_stop = readers_stop.clone(); let thread = Box::new(thread::spawn(move || { let mut local_sum0: usize = 0; loop{ let stop = readers_stop.load(Ordering::Acquire); let mut iter = reader.iter(); while let Some(i) = iter.next(){ local_sum0 += i; } if stop{ break; } } black_box(local_sum0); })); reader_threads.push(thread); } let start = Instant::now(); writer_thread.join().unwrap(); readers_stop.store(true, Ordering::Release); for thread in reader_threads { thread.join().unwrap(); } total += start.elapsed(); } total } pub fn mt_read_write_event_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("spmc mt read write"); for session_size in [4, 8, 16, 32, 128, 512 as usize]{ group.bench_with_input( BenchmarkId::new("spmc::EventQueue extend", session_size), &session_size, |b, input| b.iter_custom(|iters| { let session_len = *input; let f = move |event: &mut Event, from: usize, to: usize|{ write_extend(session_len, event, from, to); }; bench_event_read_write(iters, f) })); } #[inline(always)] fn write_push(event: &mut Event, from: usize, to: usize){ for i in from..to{ event.push(black_box(i)); } } #[inline(always)] fn write_extend(session_len: usize, event: &mut Event, from: usize, to: usize){ let mut i = from; loop{ let session_from = i; let session_to = session_from + session_len; if session_to>=to{ return; } event.extend(black_box(session_from..session_to)); i = session_to; } } group.bench_function("spmc::EventQueue push", |b|b.iter_custom(|iters| bench_event_read_write(iters, write_push))); } criterion_group!(benches, mt_read_write_event_benchmark); criterion_main!(benches);
use rc_event_queue::spmc::{EventQueue, EventReader, Settings}; use criterion::{Criterion, black_box, criterion_main, criterion_group, BenchmarkId}; use std::time::{Duration, Instant}; use std::thread; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::pin::Pin; use rc_event_queue::{CleanupMode, LendingIterator}; const QUEUE_SIZE: usize = 100000; struct S{} impl Settings for S{ const MIN_CHUNK_SIZE: u32 = 512; const MAX_CHUNK_SIZE: u32 = 512; const CLEANUP: CleanupMode = CleanupMode::Never; } type Event = EventQueue<usize, S>; fn bench_event_read_write<F>(iters: u64, writer_fn: F) -> Duration where F: Fn(&mut Event, usize, usize) -> ()
let thread = Box::new(thread::spawn(move || { let mut local_sum0: usize = 0; loop{ let stop = readers_stop.load(Ordering::Acquire); let mut iter = reader.iter(); while let Some(i) = iter.next(){ local_sum0 += i; } if stop{ break; } } black_box(local_sum0); })); reader_threads.push(thread); } let start = Instant::now(); writer_thread.join().unwrap(); readers_stop.store(true, Ordering::Release); for thread in reader_threads { thread.join().unwrap(); } total += start.elapsed(); } total } pub fn mt_read_write_event_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("spmc mt read write"); for session_size in [4, 8, 16, 32, 128, 512 as usize]{ group.bench_with_input( BenchmarkId::new("spmc::EventQueue extend", session_size), &session_size, |b, input| b.iter_custom(|iters| { let session_len = *input; let f = move |event: &mut Event, from: usize, to: usize|{ write_extend(session_len, event, from, to); }; bench_event_read_write(iters, f) })); } #[inline(always)] fn write_push(event: &mut Event, from: usize, to: usize){ for i in from..to{ event.push(black_box(i)); } } #[inline(always)] fn write_extend(session_len: usize, event: &mut Event, from: usize, to: usize){ let mut i = from; loop{ let session_from = i; let session_to = session_from + session_len; if session_to>=to{ return; } event.extend(black_box(session_from..session_to)); i = session_to; } } group.bench_function("spmc::EventQueue push", |b|b.iter_custom(|iters| bench_event_read_write(iters, write_push))); } criterion_group!(benches, mt_read_write_event_benchmark); criterion_main!(benches);
+ Send + 'static + Clone { let mut total = Duration::ZERO; let readers_thread_count = 4; for _ in 0..iters { let mut event = Event::new(); let mut readers = Vec::new(); for _ in 0..readers_thread_count{ readers.push(EventReader::new(&mut event)); } let writer_thread = { let writer_fn = writer_fn.clone(); Box::new(thread::spawn(move || { writer_fn(&mut event, 0, QUEUE_SIZE); })) }; let readers_stop = Arc::new(AtomicBool::new(false)); let mut reader_threads = Vec::new(); for mut reader in readers{ let readers_stop = readers_stop.clone();
function_block-random_span
[ { "content": "/// We test high-contention read-write case.\n\nfn bench_event_read_write<F>(iters: u64, writer_fn: F) -> Duration\n\n where F: Fn(&ArcEvent, usize, usize) -> () + Send + 'static + Clone\n\n{\n\n let mut total = Duration::ZERO;\n\n\n\n let writers_thread_count = 2;\n\n let readers_thre...
Rust
eval/src/values/mod.rs
slowli/arithmetic-parser
3e01a6069ddea36740126c40386deea0b6dfaee7
use hashbrown::HashMap; use core::{ any::{type_name, Any}, fmt, }; use crate::{ alloc::{vec, Rc, String, Vec}, fns, }; use arithmetic_parser::{MaybeSpanned, StripCode}; mod env; mod function; mod ops; mod variable_map; pub use self::{ env::Environment, function::{CallContext, Function, InterpretedFn, NativeFn}, variable_map::{Assertions, Comparisons, Prelude, VariableMap}, }; #[derive(Debug, Clone, Copy, PartialEq)] #[non_exhaustive] pub enum ValueType { Prim, Bool, Function, Tuple(usize), Object, Array, Ref, } impl fmt::Display for ValueType { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Prim => formatter.write_str("primitive value"), Self::Bool => formatter.write_str("boolean value"), Self::Function => formatter.write_str("function"), Self::Tuple(1) => formatter.write_str("tuple with 1 element"), Self::Object => formatter.write_str("object"), Self::Tuple(size) => write!(formatter, "tuple with {} elements", size), Self::Array => formatter.write_str("array"), Self::Ref => formatter.write_str("reference"), } } } pub struct OpaqueRef { value: Rc<dyn Any>, type_name: &'static str, dyn_eq: fn(&dyn Any, &dyn Any) -> bool, dyn_fmt: fn(&dyn Any, &mut fmt::Formatter<'_>) -> fmt::Result, } #[allow(renamed_and_removed_lints, clippy::unknown_clippy_lints)] impl OpaqueRef { #[allow(clippy::missing_panics_doc)] pub fn new<T>(value: T) -> Self where T: Any + fmt::Debug + PartialEq, { Self { value: Rc::new(value), type_name: type_name::<T>(), dyn_eq: |this, other| { let this_cast = this.downcast_ref::<T>().unwrap(); other .downcast_ref::<T>() .map_or(false, |other_cast| other_cast == this_cast) }, dyn_fmt: |this, formatter| { let this_cast = this.downcast_ref::<T>().unwrap(); fmt::Debug::fmt(this_cast, formatter) }, } } #[allow(clippy::missing_panics_doc)] pub fn with_identity_eq<T>(value: T) -> Self where T: Any + fmt::Debug, { Self { value: Rc::new(value), type_name: type_name::<T>(), dyn_eq: |this, other| { let this_data = (this as *const dyn Any).cast::<()>(); let other_data = (other as *const dyn Any).cast::<()>(); this_data == other_data }, dyn_fmt: |this, formatter| { let this_cast = this.downcast_ref::<T>().unwrap(); fmt::Debug::fmt(this_cast, formatter) }, } } pub fn downcast_ref<T: Any>(&self) -> Option<&T> { self.value.downcast_ref() } } impl Clone for OpaqueRef { fn clone(&self) -> Self { Self { value: Rc::clone(&self.value), type_name: self.type_name, dyn_eq: self.dyn_eq, dyn_fmt: self.dyn_fmt, } } } impl PartialEq for OpaqueRef { fn eq(&self, other: &Self) -> bool { (self.dyn_eq)(self.value.as_ref(), other.value.as_ref()) } } impl fmt::Debug for OpaqueRef { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_tuple("OpaqueRef") .field(&self.value.as_ref()) .finish() } } impl fmt::Display for OpaqueRef { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "{}::", self.type_name)?; (self.dyn_fmt)(self.value.as_ref(), formatter) } } #[derive(Debug)] #[non_exhaustive] pub enum Value<'a, T> { Prim(T), Bool(bool), Function(Function<'a, T>), Tuple(Vec<Value<'a, T>>), Object(HashMap<String, Value<'a, T>>), Ref(OpaqueRef), } pub type SpannedValue<'a, T> = MaybeSpanned<'a, Value<'a, T>>; impl<'a, T> Value<'a, T> { pub fn native_fn(function: impl NativeFn<T> + 'static) -> Self { Self::Function(Function::Native(Rc::new(function))) } pub fn wrapped_fn<Args, F>(fn_to_wrap: F) -> Self where fns::FnWrapper<Args, F>: NativeFn<T> + 'static, { let wrapped = fns::wrap::<Args, _>(fn_to_wrap); Self::native_fn(wrapped) } pub(crate) fn interpreted_fn(function: InterpretedFn<'a, T>) -> Self { Self::Function(Function::Interpreted(Rc::new(function))) } pub fn void() -> Self { Self::Tuple(vec![]) } pub fn opaque_ref(value: impl Any + fmt::Debug + PartialEq) -> Self { Self::Ref(OpaqueRef::new(value)) } pub fn value_type(&self) -> ValueType { match self { Self::Prim(_) => ValueType::Prim, Self::Bool(_) => ValueType::Bool, Self::Function(_) => ValueType::Function, Self::Tuple(elements) => ValueType::Tuple(elements.len()), Self::Object(_) => ValueType::Object, Self::Ref(_) => ValueType::Ref, } } pub fn is_void(&self) -> bool { matches!(self, Self::Tuple(tuple) if tuple.is_empty()) } pub fn is_function(&self) -> bool { matches!(self, Self::Function(_)) } } impl<T: Clone> Clone for Value<'_, T> { fn clone(&self) -> Self { match self { Self::Prim(lit) => Self::Prim(lit.clone()), Self::Bool(bool) => Self::Bool(*bool), Self::Function(function) => Self::Function(function.clone()), Self::Tuple(tuple) => Self::Tuple(tuple.clone()), Self::Object(fields) => Self::Object(fields.clone()), Self::Ref(reference) => Self::Ref(reference.clone()), } } } impl<T: 'static + Clone> StripCode for Value<'_, T> { type Stripped = Value<'static, T>; fn strip_code(self) -> Self::Stripped { match self { Self::Prim(lit) => Value::Prim(lit), Self::Bool(bool) => Value::Bool(bool), Self::Function(function) => Value::Function(function.strip_code()), Self::Tuple(tuple) => { Value::Tuple(tuple.into_iter().map(StripCode::strip_code).collect()) } Self::Object(fields) => Value::Object( fields .into_iter() .map(|(name, value)| (name, value.strip_code())) .collect(), ), Self::Ref(reference) => Value::Ref(reference), } } } impl<'a, T: Clone> From<&Value<'a, T>> for Value<'a, T> { fn from(reference: &Value<'a, T>) -> Self { reference.clone() } } impl<T: PartialEq> PartialEq for Value<'_, T> { fn eq(&self, rhs: &Self) -> bool { match (self, rhs) { (Self::Prim(this), Self::Prim(other)) => this == other, (Self::Bool(this), Self::Bool(other)) => this == other, (Self::Tuple(this), Self::Tuple(other)) => this == other, (Self::Object(this), Self::Object(other)) => this == other, (Self::Function(this), Self::Function(other)) => this.is_same_function(other), (Self::Ref(this), Self::Ref(other)) => this == other, _ => false, } } } impl<T: fmt::Display> fmt::Display for Value<'_, T> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Prim(value) => fmt::Display::fmt(value, formatter), Self::Bool(true) => formatter.write_str("true"), Self::Bool(false) => formatter.write_str("false"), Self::Ref(opaque_ref) => fmt::Display::fmt(opaque_ref, formatter), Self::Function(_) => formatter.write_str("[function]"), Self::Object(fields) => { formatter.write_str("#{ ")?; for (name, value) in fields.iter() { write!(formatter, "{} = {}; ", name, value)?; } formatter.write_str("}") } Self::Tuple(elements) => { formatter.write_str("(")?; for (i, element) in elements.iter().enumerate() { fmt::Display::fmt(element, formatter)?; if i + 1 < elements.len() { formatter.write_str(", ")?; } } formatter.write_str(")") } } } } #[cfg(test)] mod tests { use super::*; use core::cmp::Ordering; #[test] fn opaque_ref_equality() { let value = Value::<f32>::opaque_ref(Ordering::Less); let same_value = Value::<f32>::opaque_ref(Ordering::Less); assert_eq!(value, same_value); assert_eq!(value, value.clone()); let other_value = Value::<f32>::opaque_ref(Ordering::Greater); assert_ne!(value, other_value); } #[test] fn opaque_ref_formatting() { let value = OpaqueRef::new(Ordering::Less); assert_eq!(value.to_string(), "core::cmp::Ordering::Less"); } }
use hashbrown::HashMap; use core::{ any::{type_name, Any}, fmt, }; use crate::{ alloc::{vec, Rc, String, Vec}, fns, }; use arithmetic_parser::{MaybeSpanned, StripCode}; mod env; mod function; mod ops; mod variable_map; pub use self::{ env::Environment, function::{CallContext, Function, InterpretedFn, NativeFn}, variable_map::{Assertions, Comparisons, Prelude, VariableMap}, }; #[derive(Debug, Clone, Copy, PartialEq)] #[non_exhaustive] pub enum ValueType { Prim, Bool, Function, Tuple(usize), Object, Array, Ref, } impl fmt::Display for ValueType { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Prim => formatter.write_str("primitive value"), Self::Bool => formatter.write_str("boolean value"), Self::Function => formatter.write_str("function"), Self::Tuple(1) => formatter.write_str("tuple with 1 element"), Self::Object => formatter.write_str("object"), Self::Tuple(size) => write!(formatter, "tuple with {} elements", size), Self::Array => formatter.write_str("array"), Self::Ref => formatter.write_str("reference"), } } } pub struct OpaqueRef { value: Rc<dyn Any>, type_name: &'static str, dyn_eq: fn(&dyn Any, &dyn Any) -> bool, dyn_fmt: fn(&dyn Any, &mut fmt::Formatter<'_>) -> fmt::Result, } #[allow(renamed_and_removed_lints, clippy::unknown_clippy_lints)] impl OpaqueRef { #[allow(clippy::missing_panics_doc)] pub fn new<T>(value: T) -> Self where T: Any + fmt::Debug + PartialEq, { Self { value: Rc::new(value), type_name: type_name::<T>(), dyn_eq: |this, other| { let this_cast = this.downcast_ref::<T>().unwrap(); other .downcast_ref::<T>() .map_or(false, |other_cast| other_cast == this_cast) }, dyn_fmt: |this, formatter| { let this_cast = this.downcast_ref::<T>().unwrap(); fmt::Debug::fmt(this_cast, formatter) }, } } #[allow(clippy::missing_panics_doc)] pub fn with_identity_eq<T>(value: T) -> Self where T: Any + fmt::Debug, { Self { value: Rc::new(value), type_name: type_name::<T>(), dyn_eq: |this, other| { let this_data = (this as *const dyn Any).cast::<()>(); let other_data = (other as *const dyn Any).cast::<()>(); this_data == other_data }, dyn_fmt: |this, formatter| { let this_cast = this.downcast_ref::<T>().unwrap(); fmt::Debug::fmt(this_cast, formatter) }, } } pub fn downcast_ref<T: Any>(&self) -> Option<&T> { self.value.downcast_ref() } } impl Clone for OpaqueRef { fn clone(&self) -> Self { Self { value: Rc::clone(&self.value), type_name: self.type_name, dyn_eq: self.dyn_eq, dyn_fmt: self.dyn_fmt, } } } impl PartialEq for OpaqueRef { fn eq(&self, other: &Self) -> bool { (self.dyn_eq)(self.value.as_ref(), other.value.as_ref()) } } impl fmt::Debug for OpaqueRef { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_tuple("OpaqueRef") .field(&self.value.as_ref()) .finish() } } impl fmt::Display for OpaqueRef { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "{}::", self.type_name)?; (self.dyn_fmt)(self.value.as_ref(), formatter) } } #[derive(Debug)] #[non_exhaustive] pub enum Value<'a, T> { Prim(T), Bool(bool), Function(Function<'a, T>), Tuple(Vec<Value<'a, T>>), Object(HashMap<String, Value<'a, T>>), Ref(OpaqueRef), } pub type SpannedValue<'a, T> = MaybeSpanned<'a, Value<'a, T>>; impl<'a, T> Value<'a, T> { pub fn native_fn(function: impl NativeFn<T> + 'static) -> Self { Self::Function(Function::Native(Rc::new(function))) } pub fn wrapped_fn<Args, F>(fn_to_wrap: F) -> Self where fns::FnWrapper<Args, F>: NativeFn<T> + 'static, { let wrapped = fns::wrap::<Args, _>(fn_to_wrap); Self::native_fn(wrapped) } pub(crate) fn interpreted_fn(function: InterpretedFn<'a, T>) -> Self { Self::Function(Function::Interpreted(Rc::new(function))) } pub fn void() -> Self { Self::Tuple(vec![]) } pub fn opaque_ref(value: impl Any + fmt::Debug + PartialEq) -> Self { Self::Ref(OpaqueRef::new(value)) } pub fn value_type(&self) -> ValueType { match self { Self::Prim(_) => ValueType::Prim, Self::Bool(_) => ValueType::Bool, Self::Function(_) => ValueType::Function, Self::Tuple(elements) => ValueType::Tuple(elements.len()), Self::Object(_) => ValueType::Object, Self::Ref(_) => ValueType::Ref, } } pub fn is_void(&self) -> bool { matches!(self, Self::Tuple(tuple) if tuple.is_empty()) } pub fn is_function(&self) -> bool { matches!(self, Self::Function(_)) } } impl<T: Clone> Clone for Value<'_, T> { fn clone(&self) -> Self { match self { Self::Prim(lit) => Self::Prim(lit.clone()), Self::Bool(bool) => Self::Bool(*bool), Self::Function(function) => Self::Function(function.clone()), Self::Tuple(tuple) => Self::Tuple(tuple.clone()), Self::Object(fields) => Self::Object(fields.clone()), Self::Ref(reference) => Self::Ref(reference.clone()), } } } impl<T: 'static + Clone> StripCode for Value<'_, T> { type Stripped = Value<'static, T>; fn strip_code(self) -> Self::Stripped { match self { Self::Prim(lit) => Value::Prim(lit), Self::Bool(bool) => Value::Bool(bool), Self::Function(function) => Value::Function(function.strip_code()), Self::Tuple(tuple) => { Value::Tuple(tuple.into_iter().map(StripCode::strip_code).collect()) } Self::Object(fields) => Value::Object( fields .into_iter() .map(|(name, value)| (name, value.strip_code())) .collect(), ), Self::Ref(reference) => Value::Ref(reference), } } } impl<'a, T: Clone> From<&Value<'a, T>> for Value<'a, T> { fn from(reference: &Value<'a, T>) -> Self { reference.clone() } } impl<T: PartialEq> PartialEq for Value<'_, T> { fn eq(&self, rhs: &Self) -> bool { match (self, rhs) { (Self::Prim(this), Self::Prim(other)) => this == other, (Self::Bool(this), Self::Bool(other)) => this ==
his == other, _ => false, } } } impl<T: fmt::Display> fmt::Display for Value<'_, T> { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Prim(value) => fmt::Display::fmt(value, formatter), Self::Bool(true) => formatter.write_str("true"), Self::Bool(false) => formatter.write_str("false"), Self::Ref(opaque_ref) => fmt::Display::fmt(opaque_ref, formatter), Self::Function(_) => formatter.write_str("[function]"), Self::Object(fields) => { formatter.write_str("#{ ")?; for (name, value) in fields.iter() { write!(formatter, "{} = {}; ", name, value)?; } formatter.write_str("}") } Self::Tuple(elements) => { formatter.write_str("(")?; for (i, element) in elements.iter().enumerate() { fmt::Display::fmt(element, formatter)?; if i + 1 < elements.len() { formatter.write_str(", ")?; } } formatter.write_str(")") } } } } #[cfg(test)] mod tests { use super::*; use core::cmp::Ordering; #[test] fn opaque_ref_equality() { let value = Value::<f32>::opaque_ref(Ordering::Less); let same_value = Value::<f32>::opaque_ref(Ordering::Less); assert_eq!(value, same_value); assert_eq!(value, value.clone()); let other_value = Value::<f32>::opaque_ref(Ordering::Greater); assert_ne!(value, other_value); } #[test] fn opaque_ref_formatting() { let value = OpaqueRef::new(Ordering::Less); assert_eq!(value.to_string(), "core::cmp::Ordering::Less"); } }
other, (Self::Tuple(this), Self::Tuple(other)) => this == other, (Self::Object(this), Self::Object(other)) => this == other, (Self::Function(this), Self::Function(other)) => this.is_same_function(other), (Self::Ref(this), Self::Ref(other)) => t
function_block-random_span
[ { "content": "/// Default implementation of [`VisitMut::visit_function_mut()`].\n\npub fn visit_function_mut<Prim, V>(visitor: &mut V, function: &mut Function<Prim>)\n\nwhere\n\n Prim: PrimitiveType,\n\n V: VisitMut<Prim> + ?Sized,\n\n{\n\n visitor.visit_tuple_mut(&mut function.args);\n\n visitor.vi...
Rust
starlark/src/syntax/validate.rs
creativemindplus/starlark-rust
4fc26687df9a975eeb26f6b3d6f995d188fd00ba
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashSet; use gazebo::prelude::*; use thiserror::Error; use crate::{ codemap::{CodeMap, Spanned}, errors::Diagnostic, syntax::{ ast::{ Argument, Assign, AssignIdentP, AssignOp, AstArgument, AstAssign, AstAssignIdent, AstExpr, AstParameter, AstStmt, AstString, Expr, Parameter, Stmt, }, Dialect, }, }; #[derive(Error, Debug)] enum ValidateError { #[error("`break` cannot be used outside of a `for` loop")] BreakOutsideLoop, #[error("`continue` cannot be used outside of a `for` loop")] ContinueOutsideLoop, #[error("`return` cannot be used outside of a `def` function")] ReturnOutsideDef, #[error("`load` must only occur at the top of a module")] LoadNotTop, #[error("`if` cannot be used outside `def` in this dialect")] NoTopLevelIf, #[error("`for` cannot be used outside `def` in this dialect")] NoTopLevelFor, #[error("left-hand-side of assignment must take the form `a`, `a.b` or `a[b]`")] InvalidLhs, #[error("left-hand-side of modifying assignment cannot be a list or tuple")] InvalidModifyLhs, } #[derive(Eq, PartialEq, Ord, PartialOrd)] enum ArgsStage { Positional, Named, Args, Kwargs, } #[derive(Error, Debug)] enum ArgumentDefinitionOrderError { #[error("positional argument after non positional")] PositionalThenNonPositional, #[error("named argument after *args or **kwargs")] NamedArgumentAfterStars, #[error("repeated named argument")] RepeatedNamed, #[error("Args array after another args or kwargs")] ArgsArrayAfterArgsOrKwargs, #[error("Multiple kwargs dictionary in arguments")] MultipleKwargs, } impl Expr { pub fn check_call( f: AstExpr, args: Vec<AstArgument>, codemap: &CodeMap, ) -> anyhow::Result<Expr> { let err = |span, msg| Err(Diagnostic::new(msg, span, codemap.dupe())); let mut stage = ArgsStage::Positional; let mut named_args = HashSet::new(); for arg in &args { match &arg.node { Argument::Positional(_) => { if stage != ArgsStage::Positional { return err( arg.span, ArgumentDefinitionOrderError::PositionalThenNonPositional, ); } } Argument::Named(n, _) => { if stage > ArgsStage::Named { return err( arg.span, ArgumentDefinitionOrderError::NamedArgumentAfterStars, ); } else if !named_args.insert(&n.node) { return err(n.span, ArgumentDefinitionOrderError::RepeatedNamed); } else { stage = ArgsStage::Named; } } Argument::Args(_) => { if stage > ArgsStage::Named { return err( arg.span, ArgumentDefinitionOrderError::ArgsArrayAfterArgsOrKwargs, ); } else { stage = ArgsStage::Args; } } Argument::KwArgs(_) => { if stage == ArgsStage::Kwargs { return err(arg.span, ArgumentDefinitionOrderError::MultipleKwargs); } else { stage = ArgsStage::Kwargs; } } } } Ok(Expr::Call(box f, args)) } } fn test_param_name<'a, T>( argset: &mut HashSet<&'a str>, n: &'a AstAssignIdent, arg: &Spanned<T>, codemap: &CodeMap, ) -> anyhow::Result<()> { if argset.contains(n.node.0.as_str()) { return Err(Diagnostic::new( ArgumentUseOrderError::DuplicateParameterName, arg.span, codemap.dupe(), )); } argset.insert(&n.node.0); Ok(()) } #[derive(Error, Debug)] enum ArgumentUseOrderError { #[error("duplicated parameter name")] DuplicateParameterName, #[error("positional parameter after non positional")] PositionalThenNonPositional, #[error("Default parameter after args array or kwargs dictionary")] DefaultParameterAfterStars, #[error("Args parameter after another args or kwargs parameter")] ArgsParameterAfterStars, #[error("Multiple kwargs dictionary in parameters")] MultipleKwargs, } fn check_parameters(parameters: &[AstParameter], codemap: &CodeMap) -> anyhow::Result<()> { let err = |span, msg| Err(Diagnostic::new(msg, span, codemap.dupe())); let mut argset = HashSet::new(); let mut seen_args = false; let mut seen_kwargs = false; let mut seen_optional = false; for arg in parameters.iter() { match &arg.node { Parameter::Normal(n, ..) => { if seen_kwargs || seen_optional { return err(arg.span, ArgumentUseOrderError::PositionalThenNonPositional); } test_param_name(&mut argset, n, arg, codemap)?; } Parameter::WithDefaultValue(n, ..) => { if seen_kwargs { return err(arg.span, ArgumentUseOrderError::DefaultParameterAfterStars); } seen_optional = true; test_param_name(&mut argset, n, arg, codemap)?; } Parameter::NoArgs => { if seen_args || seen_kwargs { return err(arg.span, ArgumentUseOrderError::ArgsParameterAfterStars); } seen_args = true; } Parameter::Args(n, ..) => { if seen_args || seen_kwargs { return err(arg.span, ArgumentUseOrderError::ArgsParameterAfterStars); } seen_args = true; test_param_name(&mut argset, n, arg, codemap)?; } Parameter::KwArgs(n, ..) => { if seen_kwargs { return err(arg.span, ArgumentUseOrderError::MultipleKwargs); } seen_kwargs = true; test_param_name(&mut argset, n, arg, codemap)?; } } } Ok(()) } impl Expr { pub fn check_lambda( parameters: Vec<AstParameter>, body: AstExpr, codemap: &CodeMap, ) -> anyhow::Result<Expr> { check_parameters(&parameters, codemap)?; Ok(Expr::Lambda(parameters, box body, ())) } } impl Stmt { pub fn check_def( name: AstString, parameters: Vec<AstParameter>, return_type: Option<Box<AstExpr>>, stmts: AstStmt, codemap: &CodeMap, ) -> anyhow::Result<Stmt> { check_parameters(&parameters, codemap)?; let name = name.into_map(|s| AssignIdentP(s, ())); Ok(Stmt::Def(name, parameters, return_type, box stmts, ())) } pub fn check_assign(codemap: &CodeMap, x: AstExpr) -> anyhow::Result<AstAssign> { Ok(Spanned { span: x.span, node: match x.node { Expr::Tuple(xs) | Expr::List(xs) => { Assign::Tuple(xs.into_try_map(|x| Self::check_assign(codemap, x))?) } Expr::Dot(a, b) => Assign::Dot(a, b), Expr::ArrayIndirection(box (a, b)) => Assign::ArrayIndirection(box (a, b)), Expr::Identifier(x, ()) => Assign::Identifier(x.into_map(|s| AssignIdentP(s, ()))), _ => { return Err(Diagnostic::new( ValidateError::InvalidLhs, x.span, codemap.dupe(), )); } }, }) } pub fn check_assignment( codemap: &CodeMap, lhs: AstExpr, op: Option<AssignOp>, rhs: AstExpr, ) -> anyhow::Result<Stmt> { if op.is_some() { match &lhs.node { Expr::Tuple(_) | Expr::List(_) => { return Err(Diagnostic::new( ValidateError::InvalidModifyLhs, lhs.span, codemap.dupe(), )); } _ => {} } } let lhs = Self::check_assign(codemap, lhs)?; Ok(match op { None => Stmt::Assign(lhs, box rhs), Some(op) => Stmt::AssignModify(lhs, op, box rhs), }) } pub fn validate(codemap: &CodeMap, stmt: &AstStmt, dialect: &Dialect) -> anyhow::Result<()> { fn f( codemap: &CodeMap, dialect: &Dialect, stmt: &AstStmt, top_level: bool, inside_for: bool, inside_def: bool, ) -> anyhow::Result<()> { let err = |x| Err(Diagnostic::new(x, stmt.span, codemap.dupe())); match &stmt.node { Stmt::Def(_, _, _, body, _payload) => f(codemap, dialect, body, false, false, true), Stmt::For(_, box (_, body)) => { if top_level && !dialect.enable_top_level_stmt { err(ValidateError::NoTopLevelFor) } else { f(codemap, dialect, body, false, true, inside_def) } } Stmt::If(..) | Stmt::IfElse(..) => { if top_level && !dialect.enable_top_level_stmt { err(ValidateError::NoTopLevelIf) } else { stmt.node.visit_stmt_result(|x| { f(codemap, dialect, x, false, inside_for, inside_def) }) } } Stmt::Break if !inside_for => err(ValidateError::BreakOutsideLoop), Stmt::Continue if !inside_for => err(ValidateError::ContinueOutsideLoop), Stmt::Return(_) if !inside_def => err(ValidateError::ReturnOutsideDef), Stmt::Load(..) if !top_level => err(ValidateError::LoadNotTop), _ => stmt.node.visit_stmt_result(|x| { f(codemap, dialect, x, top_level, inside_for, inside_def) }), } } f(codemap, dialect, stmt, true, false, false) } }
/* * Copyright 2018 The Starlark in Rust Authors. * Copyright (c) Facebook, Inc. and its affiliates. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use std::collections::HashSet; use gazebo::prelude::*; use thiserror::Error; use crate::{ codemap::{CodeMap, Spanned}, errors::Diagnostic, syntax::{ ast::{ Argument, Assign, AssignIdentP, AssignOp, AstArgument, AstAssign, AstAssignIdent, AstExpr, AstParameter, AstStmt, AstString, Expr, Parameter, Stmt, }, Dialect, }, }; #[derive(Error, Debug)] enum ValidateError { #[error("`break` cannot be used outside of a `for` loop")] BreakOutsideLoop, #[error("`continue` cannot be used outside of a `for` loop")] ContinueOutsideLoop, #[error("`return` cannot be used outside of a `def` function")] ReturnOutsideDef, #[error("`load` must only occur at the top of a module")] LoadNotTop, #[error("`if` cannot be used outside `def` in this dialect")] NoTopLevelIf, #[error("`for` cannot be used outside `def` in this dialect")] NoTopLevelFor, #[error("left-hand-side of assignment must take the form `a`, `a.b` or `a[b]`")] InvalidLhs, #[error("left-hand-side of modifying assignment cannot be a list or tuple")] InvalidModifyLhs, } #[derive(Eq, PartialEq, Ord, PartialOrd)] enum ArgsStage { Positional, Named, Args, Kwargs, } #[derive(Error, Debug)] enum ArgumentDefinitionOrderError { #[error("positional argument after non positional")] PositionalThenNonPositional, #[error("named argument after *args or **kwargs")] NamedArgumentAfterStars, #[error("repeated named argument")] RepeatedNamed, #[error("Args array after another args or kwargs")] ArgsArrayAfterArgsOrKwargs, #[error("Multiple kwargs dictionary in arguments")] MultipleKwargs, } impl Expr { pub fn check_call( f: AstExpr, args: Vec<AstArgument>, codemap: &CodeMap, ) -> anyhow::Result<Expr> { let err = |span, msg| Err(Diagnostic::new(msg, span, codemap.dupe())); let mut stage = ArgsStage::Positional; let mut named_args = HashSet::new(); for arg in &args { match &arg.node { Argument::Positional(_) => { if stage != ArgsStage::Positional { return err( arg.span, ArgumentDefinitionOrderError::PositionalThenNonPositional, ); } } Argument::Named(n, _) => { if stage > ArgsStage::Named { return err( arg.span, ArgumentDefinitionOrderError::NamedArgumentAfterStars, ); } else if !named_args.insert(&n.node) { return err(n.span, ArgumentDefinitionOrderError::RepeatedNamed); } else { stage = ArgsStage::Named; } } Argument::Args(_) => { if stage > ArgsStage::Named { return err( arg.span, ArgumentDefinitionOrderError::ArgsArrayAfterArgsOrKwargs, ); } else { stage = ArgsStage::Args; } } Argument::KwArgs(_) => { if stage == ArgsStage::Kwargs { return err(arg.span, ArgumentDefinitionOrderError::MultipleKwargs); } else { stage = ArgsStage::Kwargs; } } } } Ok(Expr::Call(box f, args)) } } fn test_param_name<'a, T>( argset: &mut HashSet<&'a str>, n: &'a AstAssignIdent, arg: &Spanned<T>, codemap: &CodeMap, ) -> anyhow::Result<()> { if argset.contains(n.node.0.as_str()) { return Err(Diagnostic::new( ArgumentUseOrderError::DuplicateParameterName, arg.span, codemap.dupe(), )); } argset.insert(&n.node.0); Ok(()) } #[derive(Error, Debug)] enum ArgumentUseOrderError { #[error("duplicated parameter name")] DuplicateParameterName, #[error("positional parameter after non positional")] PositionalThenNonPositional, #[error("Default parameter after args array or kwargs dictionary")] DefaultParameterAfterStars, #[error("Args parameter after another args or kwargs parameter")] ArgsParameterAfterStars, #[error("Multiple kwargs dictionary in parameters")] MultipleKwargs, } fn check_parameters(parameters: &[AstParameter], codemap: &CodeMap) -> anyhow::Result<()> { let err = |span, msg| Err(Diagnostic::new(msg, span, codemap.dupe())); let mut argset = HashSet::new(); let mut seen_args = false; let mut seen_kwargs = false; let mut seen_optional = false; for arg in parameters.iter() { match &arg.node { Parameter::Normal(n, ..) => { if seen_kwargs || seen_optional { return err(arg.span, ArgumentUseOrderError::PositionalThenNonPositional); } test_param_name(&mut argset, n, arg, codemap)?; } Parameter::WithDefaultValue(n, ..) => { if seen_kwargs { return err(arg.span, ArgumentUseOrderError::DefaultParameterAfterStars); } seen_optional = true; test_param_name(&mut argset, n, arg, codemap)?; } Parameter::NoArgs => { if seen_args || seen_kwargs { return err(arg.span, ArgumentUseOrderError::ArgsParameterAfterStars); } seen_args = true; } Parameter::Args(n, ..) => { if seen_args || seen_kwargs { return err(arg.span, ArgumentUseOrderError::ArgsParameterAfterStars); } seen_args = true; test_param_name(&mut argset, n, arg, codemap)?; } Parameter::KwArgs(n, ..) => { if seen_kwargs { return err(arg.span, ArgumentUseOrderError::MultipleKwargs); } seen_kwargs = true; test_param_name(&mut argset, n, arg, codemap)?; } } } Ok(()) } impl Expr { pub fn check_lambda( parameters: Vec<AstParameter>, body: AstExpr, codemap: &CodeMap, ) -> anyhow::Result<Expr> { check_parameters(&parameters, codemap)?; Ok(Expr::Lambda(parameters, box body, ())) } } impl Stmt {
pub fn check_assign(codemap: &CodeMap, x: AstExpr) -> anyhow::Result<AstAssign> { Ok(Spanned { span: x.span, node: match x.node { Expr::Tuple(xs) | Expr::List(xs) => { Assign::Tuple(xs.into_try_map(|x| Self::check_assign(codemap, x))?) } Expr::Dot(a, b) => Assign::Dot(a, b), Expr::ArrayIndirection(box (a, b)) => Assign::ArrayIndirection(box (a, b)), Expr::Identifier(x, ()) => Assign::Identifier(x.into_map(|s| AssignIdentP(s, ()))), _ => { return Err(Diagnostic::new( ValidateError::InvalidLhs, x.span, codemap.dupe(), )); } }, }) } pub fn check_assignment( codemap: &CodeMap, lhs: AstExpr, op: Option<AssignOp>, rhs: AstExpr, ) -> anyhow::Result<Stmt> { if op.is_some() { match &lhs.node { Expr::Tuple(_) | Expr::List(_) => { return Err(Diagnostic::new( ValidateError::InvalidModifyLhs, lhs.span, codemap.dupe(), )); } _ => {} } } let lhs = Self::check_assign(codemap, lhs)?; Ok(match op { None => Stmt::Assign(lhs, box rhs), Some(op) => Stmt::AssignModify(lhs, op, box rhs), }) } pub fn validate(codemap: &CodeMap, stmt: &AstStmt, dialect: &Dialect) -> anyhow::Result<()> { fn f( codemap: &CodeMap, dialect: &Dialect, stmt: &AstStmt, top_level: bool, inside_for: bool, inside_def: bool, ) -> anyhow::Result<()> { let err = |x| Err(Diagnostic::new(x, stmt.span, codemap.dupe())); match &stmt.node { Stmt::Def(_, _, _, body, _payload) => f(codemap, dialect, body, false, false, true), Stmt::For(_, box (_, body)) => { if top_level && !dialect.enable_top_level_stmt { err(ValidateError::NoTopLevelFor) } else { f(codemap, dialect, body, false, true, inside_def) } } Stmt::If(..) | Stmt::IfElse(..) => { if top_level && !dialect.enable_top_level_stmt { err(ValidateError::NoTopLevelIf) } else { stmt.node.visit_stmt_result(|x| { f(codemap, dialect, x, false, inside_for, inside_def) }) } } Stmt::Break if !inside_for => err(ValidateError::BreakOutsideLoop), Stmt::Continue if !inside_for => err(ValidateError::ContinueOutsideLoop), Stmt::Return(_) if !inside_def => err(ValidateError::ReturnOutsideDef), Stmt::Load(..) if !top_level => err(ValidateError::LoadNotTop), _ => stmt.node.visit_stmt_result(|x| { f(codemap, dialect, x, top_level, inside_for, inside_def) }), } } f(codemap, dialect, stmt, true, false, false) } }
pub fn check_def( name: AstString, parameters: Vec<AstParameter>, return_type: Option<Box<AstExpr>>, stmts: AstStmt, codemap: &CodeMap, ) -> anyhow::Result<Stmt> { check_parameters(&parameters, codemap)?; let name = name.into_map(|s| AssignIdentP(s, ())); Ok(Stmt::Def(name, parameters, return_type, box stmts, ())) }
function_block-full_function
[ { "content": "fn require_return_expression(ret_type: &Option<Box<AstExpr>>) -> Option<Span> {\n\n match ret_type {\n\n None => None,\n\n Some(x) => match &***x {\n\n Expr::Identifier(x, _) if x.node == \"None\" => None,\n\n _ => Some(x.span),\n\n },\n\n }\n\n}\n\...
Rust
src/utils.rs
rustbunker/youki
2f3d8062ec006057e04b13c6697ebabf7cd5f9bd
use std::env; use std::ffi::CString; use std::fs; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::Context; use anyhow::{bail, Result}; use nix::unistd; pub trait PathBufExt { fn as_in_container(&self) -> Result<PathBuf>; fn join_absolute_path(&self, p: &Path) -> Result<PathBuf>; } impl PathBufExt for PathBuf { fn as_in_container(&self) -> Result<PathBuf> { if self.is_relative() { bail!("Relative path cannot be converted to the path in the container.") } else { let path_string = self.to_string_lossy().into_owned(); Ok(PathBuf::from(path_string[1..].to_string())) } } fn join_absolute_path(&self, p: &Path) -> Result<PathBuf> { if !p.is_absolute() && !p.as_os_str().is_empty() { bail!( "cannot join {:?} because it is not the absolute path.", p.display() ) } Ok(PathBuf::from(format!("{}{}", self.display(), p.display()))) } } pub fn do_exec(path: impl AsRef<Path>, args: &[String], envs: &[String]) -> Result<()> { let p = CString::new(path.as_ref().to_string_lossy().to_string())?; let a: Vec<CString> = args .iter() .map(|s| CString::new(s.to_string()).unwrap_or_default()) .collect(); env::vars().for_each(|(key, _value)| std::env::remove_var(key)); envs.iter().for_each(|e| { let mut split = e.split('='); if let Some(key) = split.next() { let value: String = split.collect::<Vec<&str>>().join("="); env::set_var(key, value) }; }); unistd::execvp(&p, &a)?; Ok(()) } pub fn set_name(_name: &str) -> Result<()> { Ok(()) } pub fn get_cgroup_path(cgroups_path: &Option<PathBuf>, container_id: &str) -> PathBuf { match cgroups_path { Some(cpath) => cpath.clone(), None => PathBuf::from(format!("/youki/{}", container_id)), } } pub fn delete_with_retry<P: AsRef<Path>>(path: P) -> Result<()> { let mut attempts = 0; let mut delay = Duration::from_millis(10); let path = path.as_ref(); while attempts < 5 { if fs::remove_dir(path).is_ok() { return Ok(()); } std::thread::sleep(delay); attempts += attempts; delay *= attempts; } bail!("could not delete {:?}", path) } pub fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> { let path = path.as_ref(); fs::write(path, contents).with_context(|| format!("failed to write to {:?}", path))?; Ok(()) } pub struct TempDir { path: Option<PathBuf>, } impl TempDir { pub fn new<P: Into<PathBuf>>(path: P) -> Result<Self> { let p = path.into(); std::fs::create_dir_all(&p)?; Ok(Self { path: Some(p) }) } pub fn path(&self) -> &Path { self.path .as_ref() .expect("temp dir has already been removed") } pub fn remove(&mut self) { if let Some(p) = &self.path { let _ = fs::remove_dir_all(p); self.path = None; } } } impl Drop for TempDir { fn drop(&mut self) { self.remove(); } } impl AsRef<Path> for TempDir { fn as_ref(&self) -> &Path { self.path() } } impl Deref for TempDir { type Target = Path; fn deref(&self) -> &Self::Target { self.path() } } pub fn create_temp_dir(test_name: &str) -> Result<TempDir> { let dir = TempDir::new(std::env::temp_dir().join(test_name))?; Ok(dir) } #[cfg(test)] mod tests { use super::*; #[test] fn test_join_absolute_path() { assert_eq!( PathBuf::from("sample/a/") .join_absolute_path(&PathBuf::from("/b")) .unwrap(), PathBuf::from("sample/a/b") ); } #[test] fn test_join_absolute_path_error() { assert_eq!( PathBuf::from("sample/a/") .join_absolute_path(&PathBuf::from("b/c")) .is_err(), true ); } #[test] fn test_get_cgroup_path() { let cid = "sample_container_id"; assert_eq!( get_cgroup_path(&None, cid), PathBuf::from("/youki/sample_container_id") ); assert_eq!( get_cgroup_path(&Some(PathBuf::from("/youki")), cid), PathBuf::from("/youki") ); } }
use std::env; use std::ffi::CString; use std::fs; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::time::Duration; use anyhow::Context; use anyhow::{bail, Result}; use nix::unistd; pub trait PathBufExt { fn as_in_container(&self) -> Result<PathBuf>; fn join_absolute_path(&self, p: &Path) -> Result<PathBuf>; } impl PathBufExt for PathBuf { fn as_in_conta
.unwrap(), PathBuf::from("sample/a/b") ); } #[test] fn test_join_absolute_path_error() { assert_eq!( PathBuf::from("sample/a/") .join_absolute_path(&PathBuf::from("b/c")) .is_err(), true ); } #[test] fn test_get_cgroup_path() { let cid = "sample_container_id"; assert_eq!( get_cgroup_path(&None, cid), PathBuf::from("/youki/sample_container_id") ); assert_eq!( get_cgroup_path(&Some(PathBuf::from("/youki")), cid), PathBuf::from("/youki") ); } }
iner(&self) -> Result<PathBuf> { if self.is_relative() { bail!("Relative path cannot be converted to the path in the container.") } else { let path_string = self.to_string_lossy().into_owned(); Ok(PathBuf::from(path_string[1..].to_string())) } } fn join_absolute_path(&self, p: &Path) -> Result<PathBuf> { if !p.is_absolute() && !p.as_os_str().is_empty() { bail!( "cannot join {:?} because it is not the absolute path.", p.display() ) } Ok(PathBuf::from(format!("{}{}", self.display(), p.display()))) } } pub fn do_exec(path: impl AsRef<Path>, args: &[String], envs: &[String]) -> Result<()> { let p = CString::new(path.as_ref().to_string_lossy().to_string())?; let a: Vec<CString> = args .iter() .map(|s| CString::new(s.to_string()).unwrap_or_default()) .collect(); env::vars().for_each(|(key, _value)| std::env::remove_var(key)); envs.iter().for_each(|e| { let mut split = e.split('='); if let Some(key) = split.next() { let value: String = split.collect::<Vec<&str>>().join("="); env::set_var(key, value) }; }); unistd::execvp(&p, &a)?; Ok(()) } pub fn set_name(_name: &str) -> Result<()> { Ok(()) } pub fn get_cgroup_path(cgroups_path: &Option<PathBuf>, container_id: &str) -> PathBuf { match cgroups_path { Some(cpath) => cpath.clone(), None => PathBuf::from(format!("/youki/{}", container_id)), } } pub fn delete_with_retry<P: AsRef<Path>>(path: P) -> Result<()> { let mut attempts = 0; let mut delay = Duration::from_millis(10); let path = path.as_ref(); while attempts < 5 { if fs::remove_dir(path).is_ok() { return Ok(()); } std::thread::sleep(delay); attempts += attempts; delay *= attempts; } bail!("could not delete {:?}", path) } pub fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> { let path = path.as_ref(); fs::write(path, contents).with_context(|| format!("failed to write to {:?}", path))?; Ok(()) } pub struct TempDir { path: Option<PathBuf>, } impl TempDir { pub fn new<P: Into<PathBuf>>(path: P) -> Result<Self> { let p = path.into(); std::fs::create_dir_all(&p)?; Ok(Self { path: Some(p) }) } pub fn path(&self) -> &Path { self.path .as_ref() .expect("temp dir has already been removed") } pub fn remove(&mut self) { if let Some(p) = &self.path { let _ = fs::remove_dir_all(p); self.path = None; } } } impl Drop for TempDir { fn drop(&mut self) { self.remove(); } } impl AsRef<Path> for TempDir { fn as_ref(&self) -> &Path { self.path() } } impl Deref for TempDir { type Target = Path; fn deref(&self) -> &Self::Target { self.path() } } pub fn create_temp_dir(test_name: &str) -> Result<TempDir> { let dir = TempDir::new(std::env::temp_dir().join(test_name))?; Ok(dir) } #[cfg(test)] mod tests { use super::*; #[test] fn test_join_absolute_path() { assert_eq!( PathBuf::from("sample/a/") .join_absolute_path(&PathBuf::from("/b"))
random
[ { "content": "#[inline]\n\npub fn write_cgroup_file_str<P: AsRef<Path>>(path: P, data: &str) -> Result<()> {\n\n fs::OpenOptions::new()\n\n .create(false)\n\n .write(true)\n\n .truncate(false)\n\n .open(path.as_ref())\n\n .with_context(|| format!(\"failed to open {:?}\", pa...
Rust
cli/src/command/export/export.rs
bennyboer/worklog
bce3c3954c3a14cca7c029caf2641ec1f5af4478
use crate::command::command::Command; use crate::command::list; use cmd_args::{arg, option, Group}; use persistence::calc::event::EventType; use persistence::calc::WorkItem; use std::collections::HashMap; use std::fs; pub struct ExportCommand {} impl Command for ExportCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "Export work log entries", ) .add_argument(arg::Descriptor::new( arg::Type::Str, "Export type (e. g. 'markdown')", )) .add_option(option::Descriptor::new( "path", option::Type::Str { default: String::from("log_export.md"), }, "Path of the file to export to", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd))", )) } fn aliases(&self) -> Option<Vec<&str>> { None } fn name(&self) -> &str { "export" } } fn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let export_type = args[0].str().unwrap(); if export_type.trim().to_lowercase() == "markdown" { export_to_markdown( options.get("path").unwrap().str().unwrap(), options .get("filter") .unwrap() .str() .map_or(String::from("today"), |v| v.to_owned()), ); } else { panic!("Export type '{}' currently not supported", export_type); } } fn export_to_markdown(file_path: &str, filter: String) { let (from_timestamp, to_timestamp) = list::filter_keyword_to_time_range(&filter[..]); let items = persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap(); let first_item = items.first().unwrap(); let date_time = shared::time::get_local_date_time(first_item.created_timestamp()); let mut data = String::new(); data.push_str(&format!( "# Report for {} the {}\n\n", date_time.format("%A").to_string(), date_time.format("%Y-%m-%d").to_string() )); data.push_str("## Statistics\n\n"); let total_work_time = { let item_refs: Vec<&WorkItem> = items.iter().collect(); let total_work_time_ms = list::calculate_total_work_time(&item_refs); shared::time::format_duration((total_work_time_ms / 1000) as u32) }; let start_time = shared::time::get_local_date_time(find_earliest_work_item(&items).created_timestamp()) .format("%H:%M") .to_string(); let end_time = shared::time::get_local_date_time(find_latest_work_item(&items).created_timestamp()) .format("%H:%M") .to_string(); data.push_str(&format!( "\ | Total time worked | Started working | Finished working | | ----------------- | --------------- | ---------------- | | {} | {} | {} |\n\n", total_work_time, start_time, end_time )); data.push_str("## Work items\n\n"); for item in &items { data.push_str(&format!( "- {}. Took `{}` ({}). Tags: *{}*.\n", item.description(), shared::time::format_duration((item.time_taken() / 1000) as u32), format_event_timeline(item), item.tags().join(", ") )); } fs::write(file_path, data).expect("Unable to write export file"); } fn format_event_timeline(item: &WorkItem) -> String { let mut result = Vec::new(); let mut start_time = None; for event in item.events() { match event.event_type() { EventType::Started | EventType::Continued => { start_time = Some(shared::time::get_local_date_time(event.timestamp())) } EventType::Finished | EventType::Paused => result.push(format!( "{} - {}", start_time.unwrap().format("%H:%M"), shared::time::get_local_date_time(event.timestamp()).format("%H:%M") )), }; } result.join(", ") } fn find_latest_work_item(items: &[WorkItem]) -> &WorkItem { let mut lastest_ts: i64 = items.first().unwrap().events().last().unwrap().timestamp(); let mut latest_item = items.first().unwrap(); for item in &items[1..] { if item.events().last().unwrap().timestamp() > lastest_ts { lastest_ts = item.events().last().unwrap().timestamp(); latest_item = item; } } latest_item } fn find_earliest_work_item(items: &[WorkItem]) -> &WorkItem { let mut earliest_ts: i64 = items.first().unwrap().created_timestamp(); let mut earliest_item = items.first().unwrap(); for item in &items[1..] { if item.created_timestamp() < earliest_ts { earliest_ts = item.created_timestamp(); earliest_item = item; } } earliest_item }
use crate::command::command::Command; use crate::command::list; use cmd_args::{arg, option, Group}; use persistence::calc::event::EventType; use persistence::calc::WorkItem; use std::collections::HashMap; use std::fs; pub struct ExportCommand {} impl Command for ExportCommand { fn build(&self) -> Group { Group::new( Box::new(|args, options| execute(args, options)), "Export work log entries", ) .add_argument(arg::Descriptor::new( arg::Type::Str, "Export type (e. g. 'markdown')", )) .add_option(option::Descriptor::new( "path", option::Type::Str { default: String::from("log_export.md"), }, "Path of the file to export to", )) .add_option(option::Descriptor::new( "filter", option::Type::Str { default: String::from("today"), }, "Filter by a date ('today' (default), 'yesterday', '2020-02-20' (yyyy-MM-dd))", )) } fn aliases(&self
::time::format_duration((total_work_time_ms / 1000) as u32) }; let start_time = shared::time::get_local_date_time(find_earliest_work_item(&items).created_timestamp()) .format("%H:%M") .to_string(); let end_time = shared::time::get_local_date_time(find_latest_work_item(&items).created_timestamp()) .format("%H:%M") .to_string(); data.push_str(&format!( "\ | Total time worked | Started working | Finished working | | ----------------- | --------------- | ---------------- | | {} | {} | {} |\n\n", total_work_time, start_time, end_time )); data.push_str("## Work items\n\n"); for item in &items { data.push_str(&format!( "- {}. Took `{}` ({}). Tags: *{}*.\n", item.description(), shared::time::format_duration((item.time_taken() / 1000) as u32), format_event_timeline(item), item.tags().join(", ") )); } fs::write(file_path, data).expect("Unable to write export file"); } fn format_event_timeline(item: &WorkItem) -> String { let mut result = Vec::new(); let mut start_time = None; for event in item.events() { match event.event_type() { EventType::Started | EventType::Continued => { start_time = Some(shared::time::get_local_date_time(event.timestamp())) } EventType::Finished | EventType::Paused => result.push(format!( "{} - {}", start_time.unwrap().format("%H:%M"), shared::time::get_local_date_time(event.timestamp()).format("%H:%M") )), }; } result.join(", ") } fn find_latest_work_item(items: &[WorkItem]) -> &WorkItem { let mut lastest_ts: i64 = items.first().unwrap().events().last().unwrap().timestamp(); let mut latest_item = items.first().unwrap(); for item in &items[1..] { if item.events().last().unwrap().timestamp() > lastest_ts { lastest_ts = item.events().last().unwrap().timestamp(); latest_item = item; } } latest_item } fn find_earliest_work_item(items: &[WorkItem]) -> &WorkItem { let mut earliest_ts: i64 = items.first().unwrap().created_timestamp(); let mut earliest_item = items.first().unwrap(); for item in &items[1..] { if item.created_timestamp() < earliest_ts { earliest_ts = item.created_timestamp(); earliest_item = item; } } earliest_item }
) -> Option<Vec<&str>> { None } fn name(&self) -> &str { "export" } } fn execute(args: &Vec<arg::Value>, options: &HashMap<&str, option::Value>) { let export_type = args[0].str().unwrap(); if export_type.trim().to_lowercase() == "markdown" { export_to_markdown( options.get("path").unwrap().str().unwrap(), options .get("filter") .unwrap() .str() .map_or(String::from("today"), |v| v.to_owned()), ); } else { panic!("Export type '{}' currently not supported", export_type); } } fn export_to_markdown(file_path: &str, filter: String) { let (from_timestamp, to_timestamp) = list::filter_keyword_to_time_range(&filter[..]); let items = persistence::find_items_by_timerange(from_timestamp, to_timestamp).unwrap(); let first_item = items.first().unwrap(); let date_time = shared::time::get_local_date_time(first_item.created_timestamp()); let mut data = String::new(); data.push_str(&format!( "# Report for {} the {}\n\n", date_time.format("%A").to_string(), date_time.format("%Y-%m-%d").to_string() )); data.push_str("## Statistics\n\n"); let total_work_time = { let item_refs: Vec<&WorkItem> = items.iter().collect(); let total_work_time_ms = list::calculate_total_work_time(&item_refs); shared
random
[ { "content": "/// Execute the log command.\n\nfn execute(args: &Vec<arg::Value>, _options: &HashMap<&str, option::Value>) {\n\n let description = args[0].str().unwrap();\n\n let tags_str = args[1].str().unwrap();\n\n let time_taken_str = args[2].str().unwrap();\n\n\n\n let tags: Vec<String> = tags_s...
Rust
src/client/general.rs
stuck-overflow/obws
6b71ed39bfacb66bbb3050b300e97ac2be2efa44
use serde::Serialize; use super::Client; use crate::requests::{KeyModifier, Projector, ProjectorInternal, QtGeometry, RequestType}; use crate::responses; use crate::{Error, Result}; pub struct General<'a> { pub(super) client: &'a Client, } impl<'a> General<'a> { pub async fn get_version(&self) -> Result<responses::Version> { self.client.send_message(RequestType::GetVersion).await } pub async fn get_auth_required(&self) -> Result<responses::AuthRequired> { self.client.send_message(RequestType::GetAuthRequired).await } pub async fn authenticate(&self, auth: &str) -> Result<()> { self.client .send_message(RequestType::Authenticate { auth }) .await } pub async fn set_filename_formatting(&self, filename_formatting: &str) -> Result<()> { self.client .send_message(RequestType::SetFilenameFormatting { filename_formatting, }) .await } pub async fn get_filename_formatting(&self) -> Result<String> { self.client .send_message::<responses::FilenameFormatting>(RequestType::GetFilenameFormatting) .await .map(|ff| ff.filename_formatting) } pub async fn get_stats(&self) -> Result<responses::ObsStats> { self.client .send_message::<responses::Stats>(RequestType::GetStats) .await .map(|s| s.stats) } pub async fn broadcast_custom_message<T>(&self, realm: &str, data: &T) -> Result<()> where T: Serialize, { self.client .send_message(RequestType::BroadcastCustomMessage { realm, data: &serde_json::to_value(data).map_err(Error::SerializeCustomData)?, }) .await } pub async fn get_video_info(&self) -> Result<responses::VideoInfo> { self.client.send_message(RequestType::GetVideoInfo).await } pub async fn open_projector(&self, projector: Projector<'_>) -> Result<()> { self.client .send_message(RequestType::OpenProjector(ProjectorInternal { ty: projector.ty, monitor: projector.monitor, geometry: projector.geometry.map(QtGeometry::serialize).as_deref(), name: projector.name, })) .await } pub async fn trigger_hotkey_by_name(&self, hotkey_name: &str) -> Result<()> { self.client .send_message(RequestType::TriggerHotkeyByName { hotkey_name }) .await } pub async fn trigger_hotkey_by_sequence( &self, key_id: &str, key_modifiers: &[KeyModifier], ) -> Result<()> { self.client .send_message(RequestType::TriggerHotkeyBySequence { key_id, key_modifiers, }) .await } }
use serde::Serialize; use super::Client; use crate::requests::{KeyModifier, Projector, ProjectorInternal, QtGeometry, RequestType}; use crate::responses; use crate::{Error, Result}; pub struct General<'a> { pub(super) client: &'a Client, } impl<'a> General<'a> { pub async fn get_version(&self) -> Result<responses::Version> { self.client.send_message(RequestType::GetVersion).await } pub async fn get_auth_required(&self) -> Result<responses::AuthRequired> { self.client.send_message(RequestType::GetAuthRequired).await } pub async fn authenticate(&self, auth: &str) -> Result<()> { self.client .send_message(RequestType::Authenticate { auth }) .await } pub async fn set_filename_formatting(&self, filename_formatting: &str) -> Result<()> { self.client .send_message(RequestType::SetFilenameFormatting { filename_formatting, }) .await } pub async fn get_filename_formatting(&self) -> Result<String> { self.client .send_message::<responses::FilenameFormatting>(RequestType::GetFilenameFormatting) .await .map(|ff| ff.filename_formatting) }
pub async fn broadcast_custom_message<T>(&self, realm: &str, data: &T) -> Result<()> where T: Serialize, { self.client .send_message(RequestType::BroadcastCustomMessage { realm, data: &serde_json::to_value(data).map_err(Error::SerializeCustomData)?, }) .await } pub async fn get_video_info(&self) -> Result<responses::VideoInfo> { self.client.send_message(RequestType::GetVideoInfo).await } pub async fn open_projector(&self, projector: Projector<'_>) -> Result<()> { self.client .send_message(RequestType::OpenProjector(ProjectorInternal { ty: projector.ty, monitor: projector.monitor, geometry: projector.geometry.map(QtGeometry::serialize).as_deref(), name: projector.name, })) .await } pub async fn trigger_hotkey_by_name(&self, hotkey_name: &str) -> Result<()> { self.client .send_message(RequestType::TriggerHotkeyByName { hotkey_name }) .await } pub async fn trigger_hotkey_by_sequence( &self, key_id: &str, key_modifiers: &[KeyModifier], ) -> Result<()> { self.client .send_message(RequestType::TriggerHotkeyBySequence { key_id, key_modifiers, }) .await } }
pub async fn get_stats(&self) -> Result<responses::ObsStats> { self.client .send_message::<responses::Stats>(RequestType::GetStats) .await .map(|s| s.stats) }
function_block-full_function
[ { "content": "pub fn duration_millis<'de, D>(deserializer: D) -> Result<Duration, D::Error>\n\nwhere\n\n D: Deserializer<'de>,\n\n{\n\n deserializer.deserialize_i64(DurationMillisVisitor)\n\n}\n\n\n", "file_path": "src/de.rs", "rank": 0, "score": 109560.20084211772 }, { "content": "pub...
Rust
src/liboak/back/context.rs
ptal/oak
667c625096540600b6c6ac0943126ca092a9f80e
pub use back::continuation::*; use back::name_factory::*; use back::compiler::ExprCompilerFn; use back::compiler::rtype::*; use back::compiler::{recognizer_compiler, parser_compiler}; use back::compiler::value::*; use quote::quote; use syn::parse_quote; pub struct Context<'a> { grammar: &'a TGrammar, closures: Vec<syn::Stmt>, name_factory: NameFactory, free_variables: Vec<Ident>, mark_variables: Vec<Ident>, mut_ref_free_variables: Vec<(Ident, syn::Type)>, num_combinators_compiled: usize } impl<'a> Context<'a> { pub fn new(grammar: &'a TGrammar) -> Self { Context { grammar: grammar, closures: vec![], name_factory: NameFactory::new(), free_variables: vec![], mark_variables: vec![], mut_ref_free_variables: vec![], num_combinators_compiled: 0 } } pub fn into_recognizer_function(self, body: syn::Expr, rule: Rule) -> syn::Item { let recognizer_fn = recognizer_id(rule.ident()); self.function(recognizer_fn, true, body, parse_quote!(())) } pub fn into_parser_alias(self, rule: Rule) -> syn::Item { let id = rule.ident(); let recognizer_fn = recognizer_name(parse_quote!(#id)); let parser_fn = parser_id(id); self.function(parser_fn, false, parse_quote!(#recognizer_fn(state)), parse_quote!(())) } pub fn into_parser_function(self, body: syn::Expr, rule: Rule) -> syn::Item { let parser_fn = parser_id(rule.ident()); let ty = TypeCompiler::compile(self.grammar, rule.expr_idx); self.function(parser_fn, true, body, ty) } fn function(self, name: Ident, state_mut: bool, body: syn::Expr, ty: syn::Type) -> syn::Item { let state_param = self.state_param(state_mut); let stream_ty = self.grammar.stream_type(); let generics = self.grammar.stream_generics(); let closures = self.closures; parse_quote!( #[inline] pub fn #name #generics (#state_param) -> oak_runtime::ParseState<#stream_ty, #ty> { #(#closures)* #body } ) } fn state_param(&self, state_mut: bool) -> syn::FnArg { let mut_kw = if state_mut { Some(quote!(mut)) } else { None }; let ps_ty = self.parse_state_ty(); parse_quote!(#mut_kw state: #ps_ty) } fn parse_state_ty(&self) -> syn::Type { let stream_ty = self.grammar.stream_type(); parse_quote!(oak_runtime::ParseState<#stream_ty, ()>) } pub fn compile(&mut self, compiler: ExprCompilerFn, idx: usize, success: syn::Expr, failure: syn::Expr) -> syn::Expr { let compiler = compiler(&self.grammar, idx); compiler.compile_expr(self, Continuation::new(success, failure)) } pub fn compile_success(&mut self, compiler: ExprCompilerFn, idx: usize, success: syn::Expr, failure: syn::Expr) -> syn::Expr { let expr = self.compile(compiler, idx, success, failure); self.num_combinators_compiled += 1; expr } pub fn compile_recognizer_expr(&mut self, idx: usize) -> syn::Expr { Continuation::new( parse_quote!(state), parse_quote!(state.failure()) ) .compile_success(self, recognizer_compiler, idx) .unwrap_success() } pub fn value_constructor<F>(&mut self, expr_idx: usize, value_ty: syn::Type, value_constructor: F) -> (syn::Expr, Ident) where F: FnOnce(Ident, syn::Expr) -> syn::Expr, { let result_var = self.next_free_var(); let scope = self.open_scope(expr_idx); self.push_mut_ref_fv(result_var.clone(), value_ty); let result_value = tuple_value(self.free_variables()); let body = Continuation::new( value_constructor(result_var.clone(), result_value), parse_quote!(state.failure()) ) .compile_success(self, parser_compiler, expr_idx) .unwrap_success(); self.close_scope(scope); (body, result_var) } pub fn do_not_duplicate_success(&self) -> bool { self.num_combinators_compiled > 0 } pub fn success_as_closure(&mut self, continuation: Continuation) -> Continuation { if self.do_not_duplicate_success() { self.num_combinators_compiled = 0; let closure_name = self.name_factory.next_closure_name(); let args = self.closure_args(); let params = self.closure_params(); continuation.map_success(|success, _| { self.closures.push(parse_quote!(let #closure_name = |#(#params),*| #success;)); parse_quote!(#closure_name(#(#args),*)) }) } else { continuation } } fn closure_params(&self) -> Vec<syn::FnArg> { let stream_ty = self.grammar.stream_type(); vec![self.state_param(true)] .into_iter() .chain(self.mut_ref_free_variables .iter().cloned() .map(|(var, ty)| parse_quote!(#var: &mut #ty))) .chain(self.free_variables .iter() .map(|var| parse_quote!(#var:_))) .chain(self.mark_variables .iter() .map(|var| parse_quote!(#var: #stream_ty))) .collect() } fn closure_args(&self) -> Vec<syn::Expr> { vec![parse_quote!(state)] .into_iter() .chain(self.mut_ref_free_variables .iter().cloned() .map(|(var, _)| parse_quote!(&mut #var))) .chain(self.free_variables .iter() .map(|var| parse_quote!(#var))) .chain(self.mark_variables .iter() .map(|var| parse_quote!(#var.clone()))) .collect() } pub fn next_mark_name(&mut self) -> Ident { self.name_factory.next_mark_name() } pub fn next_counter_name(&mut self) -> Ident { self.name_factory.next_counter_name() } pub fn next_branch_failed_name(&mut self) -> Ident { self.name_factory.next_branch_failed_name() } pub fn next_free_var(&mut self) -> Ident { self.free_variables.pop().expect("Free variables are all bound.") } pub fn next_free_var_skip(&mut self, expr_idx: usize) -> Ident { let card = self.expr_cardinality(expr_idx); let len_fv = self.free_variables.len(); self.free_variables.remove(len_fv-1-card) } pub fn push_mark(&mut self, mark: Ident) { self.mark_variables.push(mark); } pub fn pop_mark(&mut self) { self.mark_variables.pop(); } pub fn free_variables(&self) -> Vec<Ident> { self.free_variables.clone() } pub fn push_mut_ref_fv(&mut self, mut_ref_var: Ident, mut_ref_ty: syn::Type) { self.mut_ref_free_variables.push((mut_ref_var,mut_ref_ty)); } pub fn pop_mut_ref_fv(&mut self) { self.mut_ref_free_variables.pop() .expect("There is no mut ref free variables."); } pub fn expr_cardinality(&self, expr_idx: usize) -> usize { self.grammar[expr_idx].type_cardinality() } pub fn has_unit_type(&self, expr_idx: usize) -> bool { self.grammar[expr_idx].ty == crate::middle::typing::ast::Type::Unit } pub fn open_scope(&mut self, expr_idx: usize) -> Scope { let scope = self.save_scope(); self.num_combinators_compiled = 0; self.mut_ref_free_variables = vec![]; let cardinality = self.expr_cardinality(expr_idx); let free_vars = self.name_factory.fresh_vars(cardinality); self.free_variables = free_vars; scope } pub fn close_scope(&mut self, scope: Scope) { assert!(self.free_variables.is_empty(), "Try to close the scope but all free variables have not been bounded."); self.restore_scope(scope); } pub fn save_scope(&self) -> Scope { Scope::new( self.num_combinators_compiled, self.free_variables.clone(), self.mut_ref_free_variables.clone() ) } pub fn restore_scope(&mut self, scope: Scope) { self.num_combinators_compiled = scope.num_combinators_compiled; self.mut_ref_free_variables = scope.mut_ref_free_variables; self.free_variables = scope.free_variables; } } #[derive(Clone)] pub struct Scope { num_combinators_compiled: usize, free_variables: Vec<Ident>, mut_ref_free_variables: Vec<(Ident, syn::Type)> } impl Scope { fn new(n: usize, fv: Vec<Ident>, mfv: Vec<(Ident, syn::Type)>) -> Self { Scope { num_combinators_compiled: n, free_variables: fv, mut_ref_free_variables: mfv } } }
pub use back::continuation::*; use back::name_factory::*; use back::compiler::ExprCompilerFn; use back::compiler::rtype::*; use back::compiler::{recognizer_compiler, parser_compiler}; use back::compiler::value::*; use quote::quote; use syn::parse_quote; pub struct Context<'a> { grammar: &'a TGrammar, closures: Vec<syn::Stmt>, name_factory: NameFactory, free_variables: Vec<Ident>, mark_variables: Vec<Ident>, mut_ref_free_variables: Vec<(Ident, syn::Type)>, num_combinators_compiled: usize } impl<'a> Context<'a> { pub fn new(grammar: &'a TGrammar) -> Self { Context { grammar: grammar, closures: vec![], name_factory: NameFactory::new(), free_variables: vec![], mark_variables: vec![], mut_ref_free_variables: vec![], num_combinators_compiled: 0 } } pub fn into_recognizer_function(self, body: syn::Expr, rule: Rule) -> syn::Item { let recognizer_fn = recognizer_id(rule.ident()); self.function(recognizer_fn, true, body, parse_quote!(())) } pub fn into_parser_alias(self, rule: Rule) -> syn::Item { let id = rule.ident(); let recognizer_fn = recognizer_name(parse_quote!(#id)); let parser_fn = parser_id(id); self.function(parser_fn, false, parse_quote!(#recognizer_fn(state)), parse_quote!(())) } pub fn into_parser_function(self, body: syn::Expr, rule: Rule) -> syn::Item { let parser_fn = parser_id(rule.ident()); let ty = TypeCompiler::compile(self.grammar, rule.expr_idx); self.function(parser_fn, true, body, ty) } fn function(self, name: Ident, state_mut: bool, body: syn::Expr, ty: syn::Type) -> syn::Item { let state_param = self.state_param(state_mut); let stream_ty = self.grammar.stream_type(); let generics = self.grammar.stream_generics(); let closures = self.closures; parse_quote!( #[inline] pub fn #name #generics (#state_param) -> oak_runtime::ParseState<#stream_ty, #ty> { #(#closures)* #body } ) } fn state_param(&self, state_mut: bool) -> syn::FnArg { let mut_kw = if state_mut { Some(quote!(mut)) } else { None }; let ps_ty = self.parse_state_ty(); parse_quote!(#mut_kw state: #ps_ty) } fn parse_state_ty(&self) -> syn::Type { let stream_ty = self.grammar.stream_type(); parse_quote!(oak_runtime::ParseState<#stream_ty, ()>) } pub fn compile(&mut self, compiler: ExprCompilerFn, idx: usize, success: syn::Expr, failure: syn::Expr) -> syn::Expr { let compiler = compiler(&self.grammar, idx); compiler.compile_expr(self, Continuation::new(success, failure)) } pub fn compile_success(&mut self, compiler: ExprCompilerFn, idx: usize, success: syn::Expr, failure: syn::Expr) -> syn::Expr { let expr = self.compile(compiler, idx, success, failure); self.num_combinators_compiled += 1; expr } pub fn compile_recognizer_expr(&mut self, idx: usize) -> syn::Expr { Continuation::new( parse_quote!(state), parse_quote!(state.failure()) ) .compile_success(self, recognizer_compiler, idx) .unwrap_success() } pub fn value_constructor<F>(&mut self, expr_idx: usize, value_ty: syn::Type, value_constructor: F) -> (syn::Expr, Ident) where F: FnOnce(Ident, syn::Expr) -> syn::Expr, { let result_var = self.next_free_var(); let scope = self.open_scope(expr_idx);
pub fn do_not_duplicate_success(&self) -> bool { self.num_combinators_compiled > 0 } pub fn success_as_closure(&mut self, continuation: Continuation) -> Continuation { if self.do_not_duplicate_success() { self.num_combinators_compiled = 0; let closure_name = self.name_factory.next_closure_name(); let args = self.closure_args(); let params = self.closure_params(); continuation.map_success(|success, _| { self.closures.push(parse_quote!(let #closure_name = |#(#params),*| #success;)); parse_quote!(#closure_name(#(#args),*)) }) } else { continuation } } fn closure_params(&self) -> Vec<syn::FnArg> { let stream_ty = self.grammar.stream_type(); vec![self.state_param(true)] .into_iter() .chain(self.mut_ref_free_variables .iter().cloned() .map(|(var, ty)| parse_quote!(#var: &mut #ty))) .chain(self.free_variables .iter() .map(|var| parse_quote!(#var:_))) .chain(self.mark_variables .iter() .map(|var| parse_quote!(#var: #stream_ty))) .collect() } fn closure_args(&self) -> Vec<syn::Expr> { vec![parse_quote!(state)] .into_iter() .chain(self.mut_ref_free_variables .iter().cloned() .map(|(var, _)| parse_quote!(&mut #var))) .chain(self.free_variables .iter() .map(|var| parse_quote!(#var))) .chain(self.mark_variables .iter() .map(|var| parse_quote!(#var.clone()))) .collect() } pub fn next_mark_name(&mut self) -> Ident { self.name_factory.next_mark_name() } pub fn next_counter_name(&mut self) -> Ident { self.name_factory.next_counter_name() } pub fn next_branch_failed_name(&mut self) -> Ident { self.name_factory.next_branch_failed_name() } pub fn next_free_var(&mut self) -> Ident { self.free_variables.pop().expect("Free variables are all bound.") } pub fn next_free_var_skip(&mut self, expr_idx: usize) -> Ident { let card = self.expr_cardinality(expr_idx); let len_fv = self.free_variables.len(); self.free_variables.remove(len_fv-1-card) } pub fn push_mark(&mut self, mark: Ident) { self.mark_variables.push(mark); } pub fn pop_mark(&mut self) { self.mark_variables.pop(); } pub fn free_variables(&self) -> Vec<Ident> { self.free_variables.clone() } pub fn push_mut_ref_fv(&mut self, mut_ref_var: Ident, mut_ref_ty: syn::Type) { self.mut_ref_free_variables.push((mut_ref_var,mut_ref_ty)); } pub fn pop_mut_ref_fv(&mut self) { self.mut_ref_free_variables.pop() .expect("There is no mut ref free variables."); } pub fn expr_cardinality(&self, expr_idx: usize) -> usize { self.grammar[expr_idx].type_cardinality() } pub fn has_unit_type(&self, expr_idx: usize) -> bool { self.grammar[expr_idx].ty == crate::middle::typing::ast::Type::Unit } pub fn open_scope(&mut self, expr_idx: usize) -> Scope { let scope = self.save_scope(); self.num_combinators_compiled = 0; self.mut_ref_free_variables = vec![]; let cardinality = self.expr_cardinality(expr_idx); let free_vars = self.name_factory.fresh_vars(cardinality); self.free_variables = free_vars; scope } pub fn close_scope(&mut self, scope: Scope) { assert!(self.free_variables.is_empty(), "Try to close the scope but all free variables have not been bounded."); self.restore_scope(scope); } pub fn save_scope(&self) -> Scope { Scope::new( self.num_combinators_compiled, self.free_variables.clone(), self.mut_ref_free_variables.clone() ) } pub fn restore_scope(&mut self, scope: Scope) { self.num_combinators_compiled = scope.num_combinators_compiled; self.mut_ref_free_variables = scope.mut_ref_free_variables; self.free_variables = scope.free_variables; } } #[derive(Clone)] pub struct Scope { num_combinators_compiled: usize, free_variables: Vec<Ident>, mut_ref_free_variables: Vec<(Ident, syn::Type)> } impl Scope { fn new(n: usize, fv: Vec<Ident>, mfv: Vec<(Ident, syn::Type)>) -> Self { Scope { num_combinators_compiled: n, free_variables: fv, mut_ref_free_variables: mfv } } }
self.push_mut_ref_fv(result_var.clone(), value_ty); let result_value = tuple_value(self.free_variables()); let body = Continuation::new( value_constructor(result_var.clone(), result_value), parse_quote!(state.failure()) ) .compile_success(self, parser_compiler, expr_idx) .unwrap_success(); self.close_scope(scope); (body, result_var) }
function_block-function_prefix_line
[ { "content": "pub fn recognizer_compiler(grammar: &TGrammar, idx: usize) -> Box<dyn CompileExpr> {\n\n match grammar.expr_by_index(idx) {\n\n StrLiteral(lit) => Box::new(StrLiteralCompiler::recognizer(lit)),\n\n CharacterClass(classes) => Box::new(CharacterClassCompiler::recognizer(classes)),\n\n AnyS...
Rust
dpx/src/dpx_dpxconf.rs
mulimoen/tectonic
bea4516e2c7b253bc92dbd0b744a233635db7b0b
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #![allow( mutable_transmutes, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_mut )] use crate::streq_ptr; pub type __off_t = i64; pub type __off64_t = i64; pub type size_t = u64; #[derive(Copy, Clone)] #[repr(C)] pub struct paper { pub name: *const i8, pub pswidth: f64, pub psheight: f64, } #[no_mangle] pub static mut paperspecs: [paper; 22] = [ { let mut init = paper { name: b"letter\x00" as *const u8 as *const i8, pswidth: 612.00f64, psheight: 792.00f64, }; init }, { let mut init = paper { name: b"legal\x00" as *const u8 as *const i8, pswidth: 612.00f64, psheight: 1008.00f64, }; init }, { let mut init = paper { name: b"ledger\x00" as *const u8 as *const i8, pswidth: 1224.00f64, psheight: 792.00f64, }; init }, { let mut init = paper { name: b"tabloid\x00" as *const u8 as *const i8, pswidth: 792.00f64, psheight: 1224.00f64, }; init }, { let mut init = paper { name: b"a6\x00" as *const u8 as *const i8, pswidth: 297.638f64, psheight: 419.528f64, }; init }, { let mut init = paper { name: b"a5\x00" as *const u8 as *const i8, pswidth: 419.528f64, psheight: 595.276f64, }; init }, { let mut init = paper { name: b"a4\x00" as *const u8 as *const i8, pswidth: 595.276f64, psheight: 841.890f64, }; init }, { let mut init = paper { name: b"a3\x00" as *const u8 as *const i8, pswidth: 841.890f64, psheight: 1190.550f64, }; init }, { let mut init = paper { name: b"b6\x00" as *const u8 as *const i8, pswidth: 364.25f64, psheight: 515.91f64, }; init }, { let mut init = paper { name: b"b5\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 728.50f64, }; init }, { let mut init = paper { name: b"b4\x00" as *const u8 as *const i8, pswidth: 728.50f64, psheight: 1031.81f64, }; init }, { let mut init = paper { name: b"b3\x00" as *const u8 as *const i8, pswidth: 1031.81f64, psheight: 1457.00f64, }; init }, { let mut init = paper { name: b"b5var\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 651.97f64, }; init }, { let mut init = paper { name: b"jisb6\x00" as *const u8 as *const i8, pswidth: 364.25f64, psheight: 515.91f64, }; init }, { let mut init = paper { name: b"jisb5\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 728.50f64, }; init }, { let mut init = paper { name: b"jisb4\x00" as *const u8 as *const i8, pswidth: 728.50f64, psheight: 1031.81f64, }; init }, { let mut init = paper { name: b"jisb3\x00" as *const u8 as *const i8, pswidth: 1031.81f64, psheight: 1457.00f64, }; init }, { let mut init = paper { name: b"isob6\x00" as *const u8 as *const i8, pswidth: 354.331f64, psheight: 498.898f64, }; init }, { let mut init = paper { name: b"isob5\x00" as *const u8 as *const i8, pswidth: 498.898f64, psheight: 708.661f64, }; init }, { let mut init = paper { name: b"isob4\x00" as *const u8 as *const i8, pswidth: 708.661f64, psheight: 1000.630f64, }; init }, { let mut init = paper { name: b"isob3\x00" as *const u8 as *const i8, pswidth: 1000.630f64, psheight: 1417.320f64, }; init }, { let mut init = paper { name: 0 as *const i8, pswidth: 0i32 as f64, psheight: 0i32 as f64, }; init }, ]; #[no_mangle] pub unsafe extern "C" fn paperinfo(mut ppformat: *const i8) -> *const paper { if ppformat.is_null() { return 0 as *const paper; } let mut ppinfo = &*paperspecs.as_ptr().offset(0) as *const paper; while !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 }) .is_null() { if streq_ptr(ppformat, (*ppinfo).name) { break; } ppinfo = if !ppinfo.offset(1).is_null() && !(*ppinfo.offset(1)).name.is_null() { ppinfo.offset(1) } else { 0 as *const paper } } return if !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 }) .is_null() { ppinfo } else { 0 as *const paper }; } /* HAVE_LIBPAPER */ /* HAVE_LIBPAPER */ #[no_mangle] pub unsafe extern "C" fn dumppaperinfo() { let mut ppinfo = &*paperspecs.as_ptr().offset(0) as *const paper; while !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 }) .is_null() { let wd = if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).pswidth } else { 0.0f64 }; let ht = if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).psheight } else { 0.0f64 }; println!( "{}: {:.2} {:.2} ({:.2}mm {:.2}mm)", if !ppinfo.is_null() && !(*ppinfo).name.is_null() { use std::ffi::CStr; let name = CStr::from_ptr((*ppinfo).name); name.to_string_lossy() } else { use std::borrow::Cow; Cow::Borrowed("(null)") }, wd, ht, 25.4f64 * wd / 72.0f64, 25.4f64 * ht / 72.0f64, ); ppinfo = if !ppinfo.offset(1).is_null() && !(*ppinfo.offset(1)).name.is_null() { ppinfo.offset(1) } else { 0 as *const paper } } }
/* This is dvipdfmx, an eXtended version of dvipdfm by Mark A. Wicks. Copyright (C) 2002-2016 by Jin-Hwan Cho and Shunsaku Hirata, the dvipdfmx project team. Copyright (C) 1998, 1999 by Mark A. Wicks <mwicks@kettering.edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #![allow( mutable_transmutes, non_camel_case_types, non_snake_case, non_upper_case_globals, unused_mut )] use crate::streq_ptr; pub type __off_t = i64; pub type __off64_t = i64; pub type size_t = u64; #[derive(Copy, Clone)] #[repr(C)] pub struct paper { pub name: *const i8, pub pswidth: f64, pub psheight: f64, } #[no_mangle] pub static mut paperspecs: [paper; 22] = [ { let mut init = paper { name: b"letter\x00" as *const u8 as *const i8, pswidth: 612.00f64, psheight: 792.00f64, }; init }, { let mut init = paper { name: b"legal\x00" as *const u8 as *const i8, pswidth: 612.00f64, psheight: 1008.00f64, }; init }, { let mut init = paper { name: b"ledger\x00" as *const u8 as *const i8, pswidth: 1224.00f64, psheight: 792.00f64, }; init }, { let mut init = paper { name: b"tabloid\x00" as *const u8 as *const i8, pswidth: 792.00f64, psheight: 1224.00f64, }; init }, { let mut init = paper { name: b"a6\x00" as *const u8 as *const i8, pswidth: 297.638f64, psheight: 419.528f64, }; init }, { let mut init = paper { name: b"a5\x00" as *const u8 as *const i8, pswidth: 419.528f64, psheight: 595.276f64, }; init }, { let mut init = paper { name: b"a4\x00" as *const u8 as
.is_null() { if streq_ptr(ppformat, (*ppinfo).name) { break; } ppinfo = if !ppinfo.offset(1).is_null() && !(*ppinfo.offset(1)).name.is_null() { ppinfo.offset(1) } else { 0 as *const paper } } return if !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 }) .is_null() { ppinfo } else { 0 as *const paper }; } /* HAVE_LIBPAPER */ /* HAVE_LIBPAPER */ #[no_mangle] pub unsafe extern "C" fn dumppaperinfo() { let mut ppinfo = &*paperspecs.as_ptr().offset(0) as *const paper; while !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 }) .is_null() { let wd = if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).pswidth } else { 0.0f64 }; let ht = if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).psheight } else { 0.0f64 }; println!( "{}: {:.2} {:.2} ({:.2}mm {:.2}mm)", if !ppinfo.is_null() && !(*ppinfo).name.is_null() { use std::ffi::CStr; let name = CStr::from_ptr((*ppinfo).name); name.to_string_lossy() } else { use std::borrow::Cow; Cow::Borrowed("(null)") }, wd, ht, 25.4f64 * wd / 72.0f64, 25.4f64 * ht / 72.0f64, ); ppinfo = if !ppinfo.offset(1).is_null() && !(*ppinfo.offset(1)).name.is_null() { ppinfo.offset(1) } else { 0 as *const paper } } }
*const i8, pswidth: 595.276f64, psheight: 841.890f64, }; init }, { let mut init = paper { name: b"a3\x00" as *const u8 as *const i8, pswidth: 841.890f64, psheight: 1190.550f64, }; init }, { let mut init = paper { name: b"b6\x00" as *const u8 as *const i8, pswidth: 364.25f64, psheight: 515.91f64, }; init }, { let mut init = paper { name: b"b5\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 728.50f64, }; init }, { let mut init = paper { name: b"b4\x00" as *const u8 as *const i8, pswidth: 728.50f64, psheight: 1031.81f64, }; init }, { let mut init = paper { name: b"b3\x00" as *const u8 as *const i8, pswidth: 1031.81f64, psheight: 1457.00f64, }; init }, { let mut init = paper { name: b"b5var\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 651.97f64, }; init }, { let mut init = paper { name: b"jisb6\x00" as *const u8 as *const i8, pswidth: 364.25f64, psheight: 515.91f64, }; init }, { let mut init = paper { name: b"jisb5\x00" as *const u8 as *const i8, pswidth: 515.91f64, psheight: 728.50f64, }; init }, { let mut init = paper { name: b"jisb4\x00" as *const u8 as *const i8, pswidth: 728.50f64, psheight: 1031.81f64, }; init }, { let mut init = paper { name: b"jisb3\x00" as *const u8 as *const i8, pswidth: 1031.81f64, psheight: 1457.00f64, }; init }, { let mut init = paper { name: b"isob6\x00" as *const u8 as *const i8, pswidth: 354.331f64, psheight: 498.898f64, }; init }, { let mut init = paper { name: b"isob5\x00" as *const u8 as *const i8, pswidth: 498.898f64, psheight: 708.661f64, }; init }, { let mut init = paper { name: b"isob4\x00" as *const u8 as *const i8, pswidth: 708.661f64, psheight: 1000.630f64, }; init }, { let mut init = paper { name: b"isob3\x00" as *const u8 as *const i8, pswidth: 1000.630f64, psheight: 1417.320f64, }; init }, { let mut init = paper { name: 0 as *const i8, pswidth: 0i32 as f64, psheight: 0i32 as f64, }; init }, ]; #[no_mangle] pub unsafe extern "C" fn paperinfo(mut ppformat: *const i8) -> *const paper { if ppformat.is_null() { return 0 as *const paper; } let mut ppinfo = &*paperspecs.as_ptr().offset(0) as *const paper; while !ppinfo.is_null() && !(if !ppinfo.is_null() && !(*ppinfo).name.is_null() { (*ppinfo).name } else { 0 as *const i8 })
random
[ { "content": "pub fn hex_to_bytes(text: &str, dest: &mut [u8]) -> Result<()> {\n\n let n = dest.len();\n\n let text_len = text.len();\n\n\n\n if text_len != 2 * n {\n\n return Err(ErrorKind::BadLength(2 * n, text_len).into());\n\n }\n\n\n\n for i in 0..n {\n\n dest[i] = u8::from_str...
Rust
src/nal/sei/buffering_period.rs
fkaa/h264-reader
24bc61f62599ee3d3fe4df7f725a00002ac8d484
use super::SeiCompletePayloadReader; use std::marker; use crate::nal::{sps, pps}; use crate::rbsp::RbspBitReader; use crate::Context; use crate::nal::sei::HeaderType; use crate::rbsp::RbspBitReaderError; use log::*; #[derive(Debug)] enum BufferingPeriodError { ReaderError(RbspBitReaderError), UndefinedSeqParamSetId(pps::ParamSetId), InvalidSeqParamSetId(pps::ParamSetIdError), } impl From<RbspBitReaderError> for BufferingPeriodError { fn from(e: RbspBitReaderError) -> Self { BufferingPeriodError::ReaderError(e) } } impl From<pps::ParamSetIdError> for BufferingPeriodError { fn from(e: pps::ParamSetIdError) -> Self { BufferingPeriodError::InvalidSeqParamSetId(e) } } #[derive(Debug, Eq, PartialEq)] struct InitialCpbRemoval { initial_cpb_removal_delay: u32, initial_cpb_removal_delay_offset: u32, } fn read_cpb_removal_delay_list(r: &mut RbspBitReader<'_>, count: usize, length: u8) -> Result<Vec<InitialCpbRemoval>,RbspBitReaderError> { let mut res = vec!(); for _ in 0..count { res.push(InitialCpbRemoval { initial_cpb_removal_delay: r.read_u32(length)?, initial_cpb_removal_delay_offset: r.read_u32(length)?, }); } Ok(res) } #[derive(Debug, Eq, PartialEq)] struct BufferingPeriod { nal_hrd_bp: Option<Vec<InitialCpbRemoval>>, vcl_hrd_bp: Option<Vec<InitialCpbRemoval>>, } impl BufferingPeriod { fn read<Ctx>(ctx: &Context<Ctx>, buf: &[u8]) -> Result<BufferingPeriod,BufferingPeriodError> { let mut r = RbspBitReader::new(buf); let seq_parameter_set_id = pps::ParamSetId::from_u32(r.read_ue_named("seq_parameter_set_id")?)?; let sps = ctx.sps_by_id(seq_parameter_set_id) .ok_or_else(|| BufferingPeriodError::UndefinedSeqParamSetId(seq_parameter_set_id))?; let vui = sps.vui_parameters.as_ref(); let mut read = |p: &sps::HrdParameters| read_cpb_removal_delay_list( &mut r, p.cpb_specs.len(), p.initial_cpb_removal_delay_length_minus1 + 1, ); let nal_hrd_bp = vui.and_then(|v| v.nal_hrd_parameters.as_ref()).map(&mut read).transpose()?; let vcl_hrd_bp = vui.and_then(|v| v.vcl_hrd_parameters.as_ref()).map(&mut read).transpose()?; Ok(BufferingPeriod { nal_hrd_bp, vcl_hrd_bp, }) } } pub struct BufferingPeriodPayloadReader<Ctx> { phantom: marker::PhantomData<Ctx>, } impl<Ctx> Default for BufferingPeriodPayloadReader<Ctx> { fn default() -> Self { BufferingPeriodPayloadReader { phantom: marker::PhantomData } } } impl<Ctx> SeiCompletePayloadReader for BufferingPeriodPayloadReader<Ctx> { type Ctx = Ctx; fn header(&mut self, ctx: &mut Context<Ctx>, payload_type: HeaderType, buf: &[u8]) { assert_eq!(payload_type, HeaderType::BufferingPeriod); match BufferingPeriod::read(ctx, buf) { Err(e) => error!("Failure reading buffering_period: {:?}", e), Ok(buffering_period) => { info!("TODO: expose buffering_period {:#?}", buffering_period); } } } } #[cfg(test)] mod test { use hex_literal::hex; use super::*; #[test] fn parse() { let mut ctx = Context::default(); let sps_rbsp = hex!(" 4d 60 15 8d 8d 28 58 9d 08 00 00 0f a0 00 07 53 07 00 00 00 92 7c 00 00 12 4f 80 fb dc 18 00 00 0f 42 40 00 07 a1 20 7d ee 07 c6 0c 62 60 "); ctx.put_seq_param_set(sps::SeqParameterSet::from_bytes(&sps_rbsp[..]).unwrap()); let payload = &hex!("d7 e4 00 00 57 e4 00 00 40")[..]; assert_eq!(BufferingPeriod::read(&ctx, payload).unwrap(), BufferingPeriod { nal_hrd_bp: Some(vec![ InitialCpbRemoval { initial_cpb_removal_delay: 45_000, initial_cpb_removal_delay_offset: 0, }, ]), vcl_hrd_bp: Some(vec![ InitialCpbRemoval { initial_cpb_removal_delay: 45_000, initial_cpb_removal_delay_offset: 0, }, ]), }); } }
use super::SeiCompletePayloadReader; use std::marker; use crate::nal::{sps, pps}; use crate::rbsp::RbspBitReader; use crate::Context; use crate::nal::sei::HeaderType; use crate::rbsp::RbspBitReaderError; use log::*; #[derive(Debug)] enum BufferingPeriodError { ReaderError(RbspBitReaderError), UndefinedSeqParamSetId(pps::ParamSetId), InvalidSeqParamSetId(pps::ParamSetIdError), } impl From<RbspBitReaderError> for BufferingPeriodError { fn from(e: RbspBitReaderError) -> Self { BufferingPeriodError::ReaderError(e) } } impl From<pps::ParamSetIdError> for BufferingPeriodError { fn from(e: pps::ParamSetIdError) -> Self { BufferingPeriodError::InvalidSeqParamSetId(e) } } #[derive(Debug, Eq, PartialEq)] struct InitialCpbRemoval { initial_cpb_removal_delay: u32, initial_cpb_removal_delay_offset: u32, } fn read_cpb_removal_delay_list(r: &mut RbspBitReader<'_>, count: usize, length: u8) -> Result<Vec<InitialCpbRemoval>,RbspBitReaderError> { let mut res = vec!(); for _ in 0..count { res.push(InitialCpbRemoval { initial_cpb_removal_delay: r.read_u32(length)?, initial_cpb_removal_delay_offset: r.read_u32(length)?, }); } Ok(res) } #[derive(Debug, Eq, PartialEq)] struct BufferingPeriod { nal_hrd_bp: Option<Vec<InitialCpbRemoval>>, vcl_hrd_bp: Option<Vec<InitialCpbRemoval>>, } impl BufferingPeriod { fn read<Ctx>(ctx: &Context<Ctx>, buf: &[u8]) -> Result<BufferingPeriod,BufferingPeriodError> { let mut r = RbspBitReader::new(buf); let seq_parameter_set_id = pps::ParamSetId::from_u32(r.read_ue_named("seq_parameter_set_id")?)?; let sps = ctx.sps_by_id(seq_parameter_set_id) .ok_or_else(|| BufferingPeriodError::UndefinedSeqParamSetId(seq_parameter_set_id))?; let vui = sps.vui_parameters.as_ref(); let mut read = |p: &sps::HrdParameters| read_cpb_removal_delay_list( &mut r, p.cpb_specs.len(), p.initial_cpb_removal_delay_length_minus1 + 1, ); let nal_hrd_bp = vui.and_then(|v| v.nal_hrd_parameters.as_ref()).map(&mut read).transpose()?; let vcl_hrd_bp = vui.and_then(|v| v.vcl_hrd_parameters.as_ref()).map(&mut read).transpose()?; Ok(BufferingPeriod { nal_hrd_bp, vcl_hrd_bp, }) } } pub struct BufferingPeriodPayloadReader<Ctx> { phantom: marker::PhantomData<Ctx>, } impl<Ctx> Default for BufferingPeriodPayloadReader<Ctx> { fn default() -> Self { BufferingPeriodPayloadReader { phantom: marker::PhantomData } } } impl<Ctx> SeiCompletePayloadReader for BufferingPeriodPayloadReader<Ctx> { type Ctx = Ctx; fn header(&mut self, ctx: &mut Context<Ctx>, payload_type: HeaderType, buf: &[u8]) { assert_eq!(payload_type, HeaderType::BufferingPeriod);
} } #[cfg(test)] mod test { use hex_literal::hex; use super::*; #[test] fn parse() { let mut ctx = Context::default(); let sps_rbsp = hex!(" 4d 60 15 8d 8d 28 58 9d 08 00 00 0f a0 00 07 53 07 00 00 00 92 7c 00 00 12 4f 80 fb dc 18 00 00 0f 42 40 00 07 a1 20 7d ee 07 c6 0c 62 60 "); ctx.put_seq_param_set(sps::SeqParameterSet::from_bytes(&sps_rbsp[..]).unwrap()); let payload = &hex!("d7 e4 00 00 57 e4 00 00 40")[..]; assert_eq!(BufferingPeriod::read(&ctx, payload).unwrap(), BufferingPeriod { nal_hrd_bp: Some(vec![ InitialCpbRemoval { initial_cpb_removal_delay: 45_000, initial_cpb_removal_delay_offset: 0, }, ]), vcl_hrd_bp: Some(vec![ InitialCpbRemoval { initial_cpb_removal_delay: 45_000, initial_cpb_removal_delay_offset: 0, }, ]), }); } }
match BufferingPeriod::read(ctx, buf) { Err(e) => error!("Failure reading buffering_period: {:?}", e), Ok(buffering_period) => { info!("TODO: expose buffering_period {:#?}", buffering_period); } }
if_condition
[ { "content": "fn count_zero_bits<R: BitRead>(r: &mut R, name: &'static str) -> Result<u8, RbspBitReaderError> {\n\n let mut count = 0;\n\n while !r.read_bit()? {\n\n count += 1;\n\n if count > 31 {\n\n return Err(RbspBitReaderError::ExpGolombTooLarge(name));\n\n }\n\n }\...
Rust
src/main.rs
gfarrell/netctl-tray
58b7ad1684bc9f949839fb2dd08cd9ef2ad0bc74
#![feature(exclusive_range_pattern)] mod state; use notify_rust::{Notification, Timeout}; use qt_gui::QIcon; use qt_widgets::cpp_utils::{CppBox, MutPtr}; use qt_widgets::qt_core::{QString, QTimer, Slot}; use qt_widgets::{QActionGroup, QApplication, QMenu, QSystemTrayIcon, SlotOfActivationReason}; use state::{inotify_watch, scan_profiles, update_state, State}; use std::ffi::OsStr; use std::net::SocketAddr; use std::process::Command; use std::sync::{Arc, Mutex}; use structopt::StructOpt; use users::{get_current_gid, get_current_username, get_user_groups}; #[derive(Debug, StructOpt)] #[structopt( name = "netctl-tray", about = "A lightweight netctl tray app with notifications." )] pub struct Opt { #[structopt(short, long, default_value = "2")] pub interval: f32, #[structopt(long, default_value = "1.1.1.1:53")] pub host: SocketAddr, #[structopt(short)] pub disable_notifications: bool, } fn main() { let args = Opt::from_args(); let (in_wheel, in_network) = is_user_in_wheel_and_network(); if !in_wheel { eprintln!("Warning! You are not in group 'wheel', netctl-tray might not work or work only partially."); } if !in_network { eprintln!("Warning! You are not in group 'network', netctl-tray might not work or work only partially."); } let mut state = State { link_quality: 0, ping: 0.0, all_profiles: Arc::new(Mutex::new(Vec::new())), active_profile: None, }; if let Err(e) = scan_profiles(&mut *state.all_profiles.lock().unwrap()) { eprintln!("Error while scanning profiles: {:?}", e); return; } let all_profiles_clone = state.all_profiles.clone(); if let Err(e) = inotify_watch(all_profiles_clone, "/etc/netctl") { eprintln!("Error watching /etc/netctl: {:?}", e); return; } if let Err(e) = update_state(&mut state, &args) { eprintln!("Can't update tray state: {:?}", e); } let state_ptr: *mut State = &mut state; QApplication::init(|_app| { unsafe { let mut tray = QSystemTrayIcon::from_q_icon(get_status_icon(&mut state).as_ref()); let tray_click = SlotOfActivationReason::new(|reason| { let reason = reason.to_int(); if reason == 3 || reason == 4 { if let Err(e) = Notification::new() .summary("netctl") .body(&format!( "Profile: <b>{}</b>, Ping: <b>{} ms</b>, Quality: <b>{}/70</b>", (*state_ptr) .active_profile .as_ref() .unwrap_or(&"<i>{none}</i>".to_string()), if (*state_ptr).ping == f32::INFINITY { "∞".to_string() } else { (*state_ptr).ping.round().to_string() }, (*state_ptr).link_quality )) .icon("network-wireless") .timeout(Timeout::Milliseconds(5000)) .show() { eprintln!("Error sending desktop notification: {:?}", e); } } }); tray.activated().connect(&tray_click); let mut menu = QMenu::new(); tray.set_context_menu(menu.as_mut_ptr()); let profiles_submenu = menu.add_menu_q_string(QString::from_std_str("Profiles").as_mut_ref()); let mut profile_actions_group = QActionGroup::new(profiles_submenu); let group_ptr = profile_actions_group.as_mut_ptr(); let click = Slot::new(|| { #[cfg(not(feature = "auto"))] { if let Some(current_active_profile) = &(*state_ptr).active_profile { if let Err(e) = Command::new("netctl") .arg("stop") .arg(current_active_profile) .spawn() { eprintln!("Couldn't run netctl stop command: {:?}", e); } } if let Err(e) = Command::new("netctl") .arg("start") .arg((*group_ptr).checked_action().text().to_std_string()) .spawn() { eprintln!("Couldn't run netctl start command: {:?}", e); } } #[cfg(feature = "auto")] { if let Err(e) = Command::new("netctl-auto") .arg("switch-to") .arg((*group_ptr).checked_action().text().to_std_string()) .spawn() { eprintln!("Couldn't run netctl-auto switch-to command: {:?}", e); } } }); let generate_profiles_submenu = Slot::new(|| { gen_profile_submenu( state_ptr, profiles_submenu, &mut profile_actions_group, &click, ); }); profiles_submenu .about_to_show() .connect(&generate_profiles_submenu); let exit_app = Slot::new(|| { std::process::exit(0); }); menu.add_action_q_icon_q_string( QIcon::from_q_string( QString::from_std_str("/usr/share/netctl-tray/exit.svg").as_mut_ref(), ) .as_mut_ref(), QString::from_std_str("Exit").as_mut_ref(), ) .triggered() .connect(&exit_app); tray.show(); let update_state = Slot::new(|| { let old_active_profile = (*state_ptr).active_profile.clone(); if let Err(e) = update_state(&mut (*state_ptr), &args) { eprintln!("Can't update tray state: {:?}", e); } if !args.disable_notifications { if let Err(e) = profile_notification(&mut (*state_ptr), old_active_profile) { eprintln!("Error sending desktop notification: {:?}", e); } } tray.set_icon(get_status_icon(&mut (*state_ptr)).as_ref()); }); let mut update_timer = QTimer::new_0a(); update_timer.set_interval((args.interval * 1000.0) as i32); update_timer.timeout().connect(&update_state); update_timer.start_0a(); QApplication::exec() } }); } unsafe fn gen_profile_submenu( state_ptr: *mut State, mut profiles_submenu: MutPtr<QMenu>, profile_actions_group: &mut CppBox<QActionGroup>, click: &Slot, ) { profiles_submenu.clear(); for profile in &(*(*state_ptr).all_profiles.lock().unwrap()) { let mut item = profiles_submenu.add_action_q_string(QString::from_std_str(profile).as_mut_ref()); item.set_checkable(true); item.set_checked(false); if let Some(active_profile) = &(*state_ptr).active_profile { if active_profile == profile { item.set_checked(true); } } item.set_action_group(profile_actions_group.as_mut_ptr()); item.triggered().connect(click); } } fn profile_notification( state: &mut State, old_active_profile: Option<String>, ) -> Result<(), notify_rust::error::Error> { let text = match (&old_active_profile, &state.active_profile) { (None, Some(new)) => { format!("Profile <b>{}</b> started.", new) } (Some(old), None) => { format!("Profile <b>{}</b> stopped.", old) } (Some(old), Some(new)) => { if old != new { format!("Profile switched: from <b>{}</b> to <b>{}</b>.", old, new) } else { return Ok(()); } } _ => { return Ok(()); } }; Notification::new() .summary("netctl") .body(&text) .icon("network-wireless") .timeout(Timeout::Milliseconds(5000)) .show()?; Ok(()) } fn is_user_in_wheel_and_network() -> (bool, bool) { let username = match get_current_username() { Some(s) => s, None => { eprintln!("Can't get current user!"); return (false, false); } }; let groups = match get_user_groups(&username, get_current_gid()) { Some(g) => g, None => { eprintln!("Couldn't get the list of groups the user is in."); return (false, false); } }; let mut in_wheel = false; let mut in_network = false; for group in groups { if group.name() == OsStr::new("network") { in_network = true; } else if group.name() == OsStr::new("wheel") { in_wheel = true; } } (in_wheel, in_network) } fn get_status_icon(state: &mut State) -> CppBox<QIcon> { let icon_path = if state.active_profile.is_none() { "/usr/share/netctl-tray/no_profile.svg" } else { if state.ping == f32::INFINITY { match state.link_quality { 0 => "/usr/share/netctl-tray/no_signal_no_internet.svg", 1..23 => "/usr/share/netctl-tray/bad_no_internet.svg", 23..47 => "/usr/share/netctl-tray/medium_no_internet.svg", _ => "/usr/share/netctl-tray/good_no_internet.svg", } } else { match state.link_quality { 0 => "/usr/share/netctl-tray/no_signal.svg", 1..23 => "/usr/share/netctl-tray/bad.svg", 23..47 => "/usr/share/netctl-tray/medium.svg", _ => "/usr/share/netctl-tray/good.svg", } } }; unsafe { QIcon::from_q_string(QString::from_std_str(&icon_path).as_mut_ref()) } }
#![feature(exclusive_range_pattern)] mod state; use notify_rust::{Notification, Timeout}; use qt_gui::QIcon; use qt_widgets::cpp_utils::{CppBox, MutPtr}; use qt_widgets::qt_core::{QString, QTimer, Slot}; use qt_widgets::{QActionGroup, QApplication, QMenu, QSystemTrayIcon, SlotOfActivationReason}; use state::{inotify_watch, scan_profiles, update_state, State}; use std::ffi::OsStr; use std::net::SocketAddr; use std::process::Command; use std::sync::{Arc, Mutex}; use structopt::StructOpt; use users::{get_current_gid, get_current_username, get_user_groups}; #[derive(Debug, StructOpt)] #[structopt( name = "netctl-tray", about = "A lightweight netctl tray app with notifications." )] pub struct Opt { #[structopt(short, long, default_value = "2")] pub interval: f32, #[structopt(long, default_value = "1.1.1.1:53")] pub host: SocketAddr, #[structopt(short)] pub disable_notifications: bool, } fn main() { let args = Opt::from_args(); let (in_wheel, in_network) = is_user_in_wheel_and_network(); if !in_wheel { eprintln!("Warning! You are not in group 'wheel', netctl-tray might not work or work only partially."); } if !in_network { eprintln!("Warning! You are not in group 'network', netctl-tray might not work or work only partially."); } let mut state = State { link_quality: 0, ping: 0.0, all_profiles: Arc::new(Mutex::new(Vec::new())), active_profile: None, }; if let Err(e) = scan_profiles(&mut *state.all_profiles.lock().unwrap()) { eprintln!("Error while scanning profiles: {:?}", e); return; } let all_profiles_clone = state.all_profiles.clone(); if let Err(e) = inotify_watch(all_profiles_clone, "/etc/netctl") { eprintln!("Error watching /etc/netctl: {:?}", e); return; } if let Err(e) = update_state(&mut state, &args) { eprintln!("Can't update tray state: {:?}", e); } let state_ptr: *mut State = &mut state; QApplication::init(|_app| { unsafe { let mut tray = QSystemTrayIcon::from_q_icon(get_status_icon(&mut state).as_ref()); let tray_click = SlotOfActivationReason::new(|reason| { let reason = reason.to_int(); if reason == 3 || reason == 4 { if let Err(e) = Notification::new() .summary("netctl") .body(&format!( "Profile: <b>{}</b>, Ping: <b>{} ms</b>, Quality: <b>{}/70</b>", (*state_ptr) .active_profile .as_ref() .unwrap_or(&"<i>{none}</i>".to_string()), if (*state_ptr).ping == f32::INFINITY { "∞".to_string() } else { (*state_ptr).ping.round().to_string() }, (*state_ptr).link_quality )) .icon("network-wireless") .timeout(Timeout::Milliseconds(5000)) .show() { eprintln!("Error sending desktop notification: {:?}", e); } } }); tray.activated().connect(&tray_click); let mut menu = QMenu::new(); tray.set_context_menu(menu.as_mut_ptr()); let profiles_submenu = menu.add_menu_q_string(QString::from_std_str("Profiles").as_mut_ref()); let mut profile_actions_group = QActionGroup::new(profiles_submenu); let group_ptr = profile_actions_group.as_mut_ptr(); let click = Slot::new(|| { #[cfg(not(feature = "auto"))] { if let Some(current_active_profile) = &(*state_ptr).active_profile { if let Err(e) = Command::new("netctl") .arg("stop") .arg(current_active_profile) .spawn() { eprintln!("Couldn't run netctl stop command: {:?}", e); } } if let Err(e) = Command::new("netctl") .arg("start") .arg((*group_ptr).checked_action().text().to_std_string()) .spawn() { eprintln!("Couldn't run netctl start command: {:?}", e); } } #[cfg(feature = "auto")] { if let Err(e) = Command::new("netctl-auto") .arg("switch-to") .arg((*group_ptr).checked_action().text().to_std_string()) .spawn() { eprintln!("Couldn't run netctl-auto switch-to command: {:?}", e); } } }); let generate_profiles_submenu = Slot::new(|| { gen_profile_submenu( state_ptr, profiles_submenu, &mut profile_actions_group, &click, ); }); profiles_submenu .about_to_show() .connect(&generate_profiles_submenu); let exit_app = Slot::new(|| { std::process::exit(0); }); menu.add_action_q_icon_q_string( QIcon::from_q_string( QString::from_std_str("/usr/share/netctl-tray/exit.svg").as_mut_ref(), ) .as_mut_ref(), QString::from_std_str("Exit").as_mut_ref(), ) .triggered() .connect(&exit_app); tray.show(); let update_state = Slot::new(|| { let old_active_profile = (*state_ptr).active_profile.clone(); if let Err(e) = update_state(&mut (*state_ptr), &args) { eprintln!("Can't update tray state: {:?}", e); } if !args.disable_notifications { if let Err(e) = profile_notification(&mut (*state_ptr), old_active_profile) { eprintln!("Error sending desktop notification: {:?}", e); } } tray.set_icon(get_status_icon(&mut (*state_ptr)).as_ref()); }); let mut update_timer = QTimer::new_0a(); update_timer.set_interval((args.interval * 1000.0) as i32); update_timer.timeout().connect(&update_state); update_timer.start_0a(); QApplication::exec() } }); }
fn profile_notification( state: &mut State, old_active_profile: Option<String>, ) -> Result<(), notify_rust::error::Error> { let text = match (&old_active_profile, &state.active_profile) { (None, Some(new)) => { format!("Profile <b>{}</b> started.", new) } (Some(old), None) => { format!("Profile <b>{}</b> stopped.", old) } (Some(old), Some(new)) => { if old != new { format!("Profile switched: from <b>{}</b> to <b>{}</b>.", old, new) } else { return Ok(()); } } _ => { return Ok(()); } }; Notification::new() .summary("netctl") .body(&text) .icon("network-wireless") .timeout(Timeout::Milliseconds(5000)) .show()?; Ok(()) } fn is_user_in_wheel_and_network() -> (bool, bool) { let username = match get_current_username() { Some(s) => s, None => { eprintln!("Can't get current user!"); return (false, false); } }; let groups = match get_user_groups(&username, get_current_gid()) { Some(g) => g, None => { eprintln!("Couldn't get the list of groups the user is in."); return (false, false); } }; let mut in_wheel = false; let mut in_network = false; for group in groups { if group.name() == OsStr::new("network") { in_network = true; } else if group.name() == OsStr::new("wheel") { in_wheel = true; } } (in_wheel, in_network) } fn get_status_icon(state: &mut State) -> CppBox<QIcon> { let icon_path = if state.active_profile.is_none() { "/usr/share/netctl-tray/no_profile.svg" } else { if state.ping == f32::INFINITY { match state.link_quality { 0 => "/usr/share/netctl-tray/no_signal_no_internet.svg", 1..23 => "/usr/share/netctl-tray/bad_no_internet.svg", 23..47 => "/usr/share/netctl-tray/medium_no_internet.svg", _ => "/usr/share/netctl-tray/good_no_internet.svg", } } else { match state.link_quality { 0 => "/usr/share/netctl-tray/no_signal.svg", 1..23 => "/usr/share/netctl-tray/bad.svg", 23..47 => "/usr/share/netctl-tray/medium.svg", _ => "/usr/share/netctl-tray/good.svg", } } }; unsafe { QIcon::from_q_string(QString::from_std_str(&icon_path).as_mut_ref()) } }
unsafe fn gen_profile_submenu( state_ptr: *mut State, mut profiles_submenu: MutPtr<QMenu>, profile_actions_group: &mut CppBox<QActionGroup>, click: &Slot, ) { profiles_submenu.clear(); for profile in &(*(*state_ptr).all_profiles.lock().unwrap()) { let mut item = profiles_submenu.add_action_q_string(QString::from_std_str(profile).as_mut_ref()); item.set_checkable(true); item.set_checked(false); if let Some(active_profile) = &(*state_ptr).active_profile { if active_profile == profile { item.set_checked(true); } } item.set_action_group(profile_actions_group.as_mut_ptr()); item.triggered().connect(click); } }
function_block-full_function
[ { "content": "// Updates the netctl-tray state: ping, quality and current active profile\n\npub fn update_state(state: &mut State, args: &Opt) -> Result<(), std::io::Error> {\n\n // get the current active profile\n\n #[cfg(not(feature = \"auto\"))]\n\n let raw_profiles = Command::new(\"netctl\").arg(\"...
Rust
examples/rpg_engine/src/character.rs
arn-the-long-beard/ntnu_rust_lecture
1c7d6aba84e9e5ea99f18a5e46a11a674a08aa34
use crate::dice::SkillDice; use crate::item::Weapon; use crate::item::*; use crate::stuff::{Stuff, StuffConfig}; use colored::*; #[derive(Clone)] pub struct Character { name: String, health: f32, max_health: f32, stuff: Stuff, } #[allow(unused)] impl Character { pub fn name(&self) -> &str { &self.name } pub fn health(&self) -> f32 { self.health } pub fn set_health(&mut self, health: f32) { self.health = health; } } #[allow(unused)] impl Character { pub fn new(name: &str, health: f32) -> Self { Character { name: name.to_string(), health, max_health: health, stuff: Default::default(), } } pub fn roll_dice(&self, skill: SkillDice) -> u8 { skill.dices_roll_result(&self.name) } #[must_use] pub fn grab_weapon<W: Weapon + Send + Sync + 'static>(mut self, new_weapon: W) -> Self { self.stuff = self.stuff.equip_weapon(new_weapon); self } #[must_use] pub fn drop_first_weapon(mut self) -> Self { self.stuff.unset_first_weapon(); self } #[must_use] pub fn drop_second_weapon(mut self) -> Self { self.stuff.unset_second_weapon(); self } #[must_use] pub fn grab_armor<A: Armor + Send + Sync + 'static>(mut self, armor: A) -> Self { self.stuff = self.stuff.equip_armor(armor); self } fn check_blocking_damages(&self) -> Option<BlockedDamages> { match self.stuff.get_weapon_settings() { StuffConfig::DualWeapons => { None } StuffConfig::ShieldAndWeapon => self.stuff.get_second_weapon_blocking_damage(), StuffConfig::TwoHandsWeapon => self.stuff.get_first_weapon_blocking_damage(), StuffConfig::OnlyShied => self.stuff.get_second_weapon_blocking_damage(), StuffConfig::OneSingleHandWeapon => self.stuff.get_first_weapon_blocking_damage(), StuffConfig::OneWeaponAsSecondary => None, } } pub fn can_block(&self) -> Option<BlockedDamages> { self.check_blocking_damages() } pub fn gets_hit(&mut self, raw_damages: RawDamages) -> RawDamages { let mut damage_taken = raw_damages - self.get_armor(); if damage_taken < 0.0 { damage_taken = raw_damages * 0.1; } self.update_health_from_taken_damage(&damage_taken); damage_taken } fn update_health_from_taken_damage(&mut self, damages: &RawDamages) { self.health -= *damages; if self.health < 0.0 { self.health = 0.0 } } #[deprecated] pub fn get_attacked_by(&mut self, damages: RawDamages, attack_dice: u8, def_dice: Option<u8>) { let mut receive_damage = damages - self.get_armor(); if let Some(def_result) = def_dice { if def_result > attack_dice { let blocking_damage = self.can_block().unwrap_or(0.0); receive_damage -= blocking_damage; println!( "{} {} {} with its weapon", self.name().bold(), "blocked".blue(), blocking_damage.to_string().red() ) } else { println!( "{} {} {} the attack ", self.name().bold(), "failed".red(), "blocking".underline() ); } } else { println!("{} Will not block the attack", self.name.bold()); } if receive_damage < 0.0 { receive_damage = damages * 0.1; } println!( "{} received {} damages", self.name.bold(), receive_damage.to_string().red().bold() ); self.health -= receive_damage; if self.health < 0.0 { self.health = 0.0 } } fn get_armor(&self) -> BlockedDamages { self.stuff.get_armor_rating() } pub fn get_health_status(&self) -> HealthStatus { let percentage: u8 = ((self.health / self.max_health) * 100.0) as u8; match percentage { 0 => HealthStatus::Dead, 1..=10 => HealthStatus::AlmostDead, 11..=30 => HealthStatus::SeriouslyHurt, 31..=50 => HealthStatus::VeryHurt, 51..=75 => HealthStatus::LightlyHurt, 76..=99 => HealthStatus::SlightlyHurt, 100 => HealthStatus::Healthy, _ => { println!( "{} % of maximum health, Did you get some magic ?", percentage ); HealthStatus::Healthy } } } pub fn deal_damages(&self) -> RawDamages { self.stuff.calculate_damages() } } #[derive(PartialEq, Debug)] pub enum HealthStatus { Dead, AlmostDead, SeriouslyHurt, VeryHurt, LightlyHurt, SlightlyHurt, Healthy, } #[cfg(test)] mod test { use super::*; fn get_test_player() -> Character { Character::new("test character", 1000.0) } fn get_long_iron_sword() -> RegularWeapon { RegularWeapon::new("Long Iron Sword", 25.0, HandheldType::SingleHand) } fn get_long_steel_sword() -> RegularWeapon { RegularWeapon::new("Long Steel Sword", 30.0, HandheldType::SingleHand) } fn get_steel_battle_axe() -> RegularWeapon { RegularWeapon::new("Steal battle Axe", 65.0, HandheldType::TwoHands) } fn get_iron_shield() -> Shield { Shield::new("Iron Shield", 25.0, 5.0) } fn get_steel_shield() -> Shield { Shield::new("Steel Shield", 35.0, 7.0) } fn get_daedric_mail() -> BodyArmor { BodyArmor::new("Daedric Shield", 45.0) } #[test] fn test_blocking_for_weapon_config() { let mut guard = get_test_player().grab_weapon(get_steel_battle_axe()); assert_eq!( guard.check_blocking_damages().unwrap(), get_steel_battle_axe().damages() * 0.5 ); guard = guard.grab_weapon(get_iron_shield()); assert_eq!( guard.check_blocking_damages().unwrap(), get_iron_shield().can_block_if_possible().unwrap() ); guard = guard.grab_weapon(get_long_iron_sword()); assert_eq!( guard.check_blocking_damages().unwrap(), get_iron_shield().can_block_if_possible().unwrap() ); guard = guard.grab_weapon(get_long_iron_sword()); assert!(guard.check_blocking_damages().is_none()); guard = guard.drop_second_weapon(); assert_eq!( guard.check_blocking_damages().unwrap(), get_long_iron_sword().damages() * 0.3 ); } #[test] fn check_status() { let mut guard_test = get_test_player(); assert_eq!(&guard_test.get_health_status(), &HealthStatus::Healthy); guard_test.set_health(850.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::SlightlyHurt); guard_test.set_health(550.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::LightlyHurt); guard_test.set_health(350.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::VeryHurt); guard_test.set_health(250.00); assert_eq!( &guard_test.get_health_status(), &HealthStatus::SeriouslyHurt ); guard_test.set_health(50.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::AlmostDead); guard_test.set_health(0.0); assert_eq!(&guard_test.get_health_status(), &HealthStatus::Dead); } #[test] fn kill_naked_character() { let mut guard = get_test_player(); guard.get_attacked_by(1800.2, 3, None); assert_eq!(&guard.get_health_status(), &HealthStatus::Dead); } #[test] fn defense_armored_character() { let mut guard = get_test_player().grab_armor(get_daedric_mail()); guard.get_attacked_by(100.0, 3, None); assert_eq!(guard.health, 945.0); } #[test] fn defense_armored_character_with_block() { let mut guard = get_test_player() .grab_armor(get_daedric_mail()) .grab_weapon(get_iron_shield()); guard.get_attacked_by(100.0, 3, Some(5)); assert_eq!(guard.health, 970.0); } }
use crate::dice::SkillDice; use crate::item::Weapon; use crate::item::*; use crate::stuff::{Stuff, StuffConfig}; use colored::*; #[derive(Clone)] pub struct Character { name: String, health: f32, max_health: f32, stuff: Stuff, } #[allow(unused)] impl Character { pub fn name(&self) -> &str { &self.name } pub fn health(&self) -> f32 { self.health } pub fn set_health(&mut self, health: f32) { self.health = health; } } #[allow(unused)] impl Character { pub fn new(name: &str, health: f32) -> Self { Character { name: name.to_string(), health, max_health: health, stuff: Default::default(), } } pub fn roll_dice(&self, skill: SkillDice) -> u8 { skill.dices_roll_result(&self.name) } #[must_use] pub fn grab_weapon<W: Weapon + Send + Sync + 'static>(mut self, new_weapon: W) -> Self { self.stuff = self.stuff.equip_weapon(new_weapon); self } #[must_use] pub fn drop_first_weapon(mut self) -> Self { self.stuff.unset_first_weapon(); self } #[must_use] pub fn drop_second_weapon(mut self) -> Self { self.stuff.unset_second_weapon(); self } #[must_use] pub fn grab_armor<A: Armor + Send + Sync + 'static>(mut self, armor: A) -> Self { self.stuff = self.stuff.equip_armor(armor); self } fn check_blocking_damages(&self) -> Option<BlockedDamages> { match self.stuff.get_weapon_settings() { StuffConfig::DualWeapons => { None } StuffConfig::ShieldAndWeapon => self.stuff.get_second_weapon_blocking_damage(), StuffConfig::TwoHandsWeapon => self.stuff.get_first_weapon_blocking_damage(), StuffConfig::OnlyShied => self.stuff.get_second_weapon_blocking_damage(), StuffConfig::OneSingleHandWeapon => self.stuff.get_first_weapon_blocking_damage(), StuffConfig::OneWeaponAsSecondary => None, } } pub fn can_block(&self) -> Option<BlockedDamages> { self.check_blocking_damages() } pub fn gets_hit(&mut s
fn update_health_from_taken_damage(&mut self, damages: &RawDamages) { self.health -= *damages; if self.health < 0.0 { self.health = 0.0 } } #[deprecated] pub fn get_attacked_by(&mut self, damages: RawDamages, attack_dice: u8, def_dice: Option<u8>) { let mut receive_damage = damages - self.get_armor(); if let Some(def_result) = def_dice { if def_result > attack_dice { let blocking_damage = self.can_block().unwrap_or(0.0); receive_damage -= blocking_damage; println!( "{} {} {} with its weapon", self.name().bold(), "blocked".blue(), blocking_damage.to_string().red() ) } else { println!( "{} {} {} the attack ", self.name().bold(), "failed".red(), "blocking".underline() ); } } else { println!("{} Will not block the attack", self.name.bold()); } if receive_damage < 0.0 { receive_damage = damages * 0.1; } println!( "{} received {} damages", self.name.bold(), receive_damage.to_string().red().bold() ); self.health -= receive_damage; if self.health < 0.0 { self.health = 0.0 } } fn get_armor(&self) -> BlockedDamages { self.stuff.get_armor_rating() } pub fn get_health_status(&self) -> HealthStatus { let percentage: u8 = ((self.health / self.max_health) * 100.0) as u8; match percentage { 0 => HealthStatus::Dead, 1..=10 => HealthStatus::AlmostDead, 11..=30 => HealthStatus::SeriouslyHurt, 31..=50 => HealthStatus::VeryHurt, 51..=75 => HealthStatus::LightlyHurt, 76..=99 => HealthStatus::SlightlyHurt, 100 => HealthStatus::Healthy, _ => { println!( "{} % of maximum health, Did you get some magic ?", percentage ); HealthStatus::Healthy } } } pub fn deal_damages(&self) -> RawDamages { self.stuff.calculate_damages() } } #[derive(PartialEq, Debug)] pub enum HealthStatus { Dead, AlmostDead, SeriouslyHurt, VeryHurt, LightlyHurt, SlightlyHurt, Healthy, } #[cfg(test)] mod test { use super::*; fn get_test_player() -> Character { Character::new("test character", 1000.0) } fn get_long_iron_sword() -> RegularWeapon { RegularWeapon::new("Long Iron Sword", 25.0, HandheldType::SingleHand) } fn get_long_steel_sword() -> RegularWeapon { RegularWeapon::new("Long Steel Sword", 30.0, HandheldType::SingleHand) } fn get_steel_battle_axe() -> RegularWeapon { RegularWeapon::new("Steal battle Axe", 65.0, HandheldType::TwoHands) } fn get_iron_shield() -> Shield { Shield::new("Iron Shield", 25.0, 5.0) } fn get_steel_shield() -> Shield { Shield::new("Steel Shield", 35.0, 7.0) } fn get_daedric_mail() -> BodyArmor { BodyArmor::new("Daedric Shield", 45.0) } #[test] fn test_blocking_for_weapon_config() { let mut guard = get_test_player().grab_weapon(get_steel_battle_axe()); assert_eq!( guard.check_blocking_damages().unwrap(), get_steel_battle_axe().damages() * 0.5 ); guard = guard.grab_weapon(get_iron_shield()); assert_eq!( guard.check_blocking_damages().unwrap(), get_iron_shield().can_block_if_possible().unwrap() ); guard = guard.grab_weapon(get_long_iron_sword()); assert_eq!( guard.check_blocking_damages().unwrap(), get_iron_shield().can_block_if_possible().unwrap() ); guard = guard.grab_weapon(get_long_iron_sword()); assert!(guard.check_blocking_damages().is_none()); guard = guard.drop_second_weapon(); assert_eq!( guard.check_blocking_damages().unwrap(), get_long_iron_sword().damages() * 0.3 ); } #[test] fn check_status() { let mut guard_test = get_test_player(); assert_eq!(&guard_test.get_health_status(), &HealthStatus::Healthy); guard_test.set_health(850.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::SlightlyHurt); guard_test.set_health(550.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::LightlyHurt); guard_test.set_health(350.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::VeryHurt); guard_test.set_health(250.00); assert_eq!( &guard_test.get_health_status(), &HealthStatus::SeriouslyHurt ); guard_test.set_health(50.00); assert_eq!(&guard_test.get_health_status(), &HealthStatus::AlmostDead); guard_test.set_health(0.0); assert_eq!(&guard_test.get_health_status(), &HealthStatus::Dead); } #[test] fn kill_naked_character() { let mut guard = get_test_player(); guard.get_attacked_by(1800.2, 3, None); assert_eq!(&guard.get_health_status(), &HealthStatus::Dead); } #[test] fn defense_armored_character() { let mut guard = get_test_player().grab_armor(get_daedric_mail()); guard.get_attacked_by(100.0, 3, None); assert_eq!(guard.health, 945.0); } #[test] fn defense_armored_character_with_block() { let mut guard = get_test_player() .grab_armor(get_daedric_mail()) .grab_weapon(get_iron_shield()); guard.get_attacked_by(100.0, 3, Some(5)); assert_eq!(guard.health, 970.0); } }
elf, raw_damages: RawDamages) -> RawDamages { let mut damage_taken = raw_damages - self.get_armor(); if damage_taken < 0.0 { damage_taken = raw_damages * 0.1; } self.update_health_from_taken_damage(&damage_taken); damage_taken }
function_block-function_prefixed
[ { "content": "pub fn roll_dice(actor: &str, dices: &str, action: &str) -> i64 {\n\n let result = Roller::new(&format!(\"{} : {} \", dices, action))\n\n .unwrap()\n\n .roll()\n\n .unwrap();\n\n println!(\n\n \"{} rolls {} for {} \",\n\n actor.bold(),\n\n dices.unde...
Rust
src/bin/roughenough-kms.rs
lachesis/roughenough
a5e29a47646cc57bdd8e3603818cc9bd46f81bfc
#[macro_use] extern crate log; use clap::{App, Arg}; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use log::LevelFilter; use simple_logger::SimpleLogger; #[allow(unused_imports)] use roughenough::kms::{EnvelopeEncryption, KmsProvider}; use roughenough::roughenough_version; const HEX: Encoding = HEXLOWER_PERMISSIVE; #[cfg(not(any(feature = "awskms", feature = "gcpkms")))] fn encrypt_seed(_: &str, _: &str) { unreachable!() } #[cfg(any(feature = "awskms", feature = "gcpkms"))] fn encrypt_seed(kms_key: &str, hex_seed: &str) { let kms_client = get_kms(kms_key); let plaintext_seed = HEX.decode(hex_seed.as_ref()).expect("Error decoding hex seed value"); if plaintext_seed.len() != 32 { panic!( "Seed must be 32 bytes long; provided seed is {}", plaintext_seed.len() ); } match EnvelopeEncryption::encrypt_seed(&kms_client, &plaintext_seed) { Ok(encrypted_blob) => { println!("kms_protection: \"{}\"", kms_key); println!("seed: {}", HEX.encode(&encrypted_blob)); } Err(e) => { error!("Error: {:?}", e); } } } #[cfg(not(any(feature = "awskms", feature = "gcpkms")))] fn decrypt_blob(_: &str, _: &str) { unreachable!() } #[cfg(any(feature = "awskms", feature = "gcpkms"))] fn decrypt_blob(kms_key: &str, hex_blob: &str) { let kms_client = get_kms(kms_key); let ciphertext = HEX.decode(hex_blob.as_ref()).expect("Error decoding hex blob value"); match EnvelopeEncryption::decrypt_seed(&kms_client, ciphertext.as_ref()) { Ok(plaintext) => { println!("{}", HEX.encode(&plaintext)); } Err(e) => { error!("Error: {:?}", e); } } } #[cfg(feature = "awskms")] fn get_kms(kms_key: &str) -> impl KmsProvider { use roughenough::kms::AwsKms; AwsKms::from_arn(kms_key).unwrap() } #[cfg(feature = "gcpkms")] fn get_kms(kms_key: &str) -> impl KmsProvider { use roughenough::kms::GcpKms; GcpKms::from_resource_id(kms_key).unwrap() } #[allow(unused_variables)] pub fn main() { SimpleLogger::new() .with_level(LevelFilter::Info) .init() .unwrap(); if !(cfg!(feature = "gcpkms") || cfg!(feature = "awskms")) { warn!("KMS support was not compiled into this build; nothing to do."); warn!("See the Roughenough documentation for information on KMS support."); warn!(" https://github.com/int08h/roughenough/blob/master/doc/OPTIONAL-FEATURES.md"); return; } let matches = App::new("roughenough-kms") .version(roughenough_version().as_ref()) .long_about("Encrypt and decrypt Roughenough long-term server seeds using a KMS") .arg( Arg::with_name("KEY_ID") .short("k") .long("kms-key") .takes_value(true) .required(true) .help("Identity of the KMS key to be used"), ) .arg( Arg::with_name("DECRYPT") .short("d") .long("decrypt") .takes_value(true) .required(false) .help("Previously encrypted blob to decrypt to plaintext"), ) .arg( Arg::with_name("SEED") .short("s") .long("seed") .takes_value(true) .required(false) .help("32 byte hex seed for the server's long-term identity"), ) .get_matches(); let kms_key = matches.value_of("KEY_ID").expect("Invalid KMS key id"); if matches.is_present("SEED") { let hex_seed = matches.value_of("SEED").expect("Invalid seed value"); encrypt_seed(kms_key, hex_seed); } else if matches.is_present("DECRYPT") { let hex_blob = matches.value_of("DECRYPT").expect("Invalid blob value"); decrypt_blob(kms_key, hex_blob); } else { error!("Neither seed encryption (-s) or blob decryption (-d) was specified."); error!("One of them is required."); } }
#[macro_use] extern crate log; use clap::{App, Arg}; use data_encoding::{Encoding, HEXLOWER_PERMISSIVE}; use log::LevelFilter; use simple_logger::SimpleLogger; #[allow(unused_imports)] use roughenough::kms::{EnvelopeEncryption, KmsProvider}; use roughenough::roughenough_version; const HEX: Encoding = HEXLOWER_PERMISSIVE; #[cfg(not(any(feature = "awskms", feature = "gcpkms")))] fn encrypt_seed(_: &str, _: &str) { unreachable!() } #[cfg(any(feature = "awskms", feature = "gcpkms"))] fn encrypt_seed(kms_key: &str, hex_seed: &str) { let kms_client = get_kms(kms_key); let plaintext_seed = HEX.decode(hex_seed.as_ref()).expect("Error decoding hex seed value"); if plaintext_seed.len() != 32 { panic!( "Seed must be 32 bytes long; provided seed is {}", plaintext_seed.len() ); } match EnvelopeEncryption::encrypt_seed(&kms_client, &plaintext_seed) { Ok(encrypted_blob) => { println!("kms_protection: \"{}\"", kms_key); println!("seed: {}", HEX.encode(&encrypted_blob)); } Err(e) => { error!("Error: {:?}", e); } } } #[cfg(not(any(feature = "awskms", feature = "gcpkms")))] fn decrypt_blob(_: &str, _: &str) { unreachable!() } #[cfg(any(feature = "awskms", feature = "gcpkms"))] fn decrypt_blob(kms_key: &str, hex_blob: &str) { let kms_client = get_kms(kms_key); let ciphertext = HEX.decode(hex_blob.as_ref()).expect("Error decoding hex blob value"); match EnvelopeEncryption::decrypt_seed(&kms_client, ciphertext.as_ref()) { Ok(plaintext) => { println!("{}", HEX.encode(&plaintext)); } Err(e) => { error!("Error: {:?}", e); } } } #[cfg(feature = "awskms")] fn get_kms(kms_key: &str) -> impl KmsProvider { use roughenough::kms::AwsKms; AwsKms::from_arn(kms_key).unwrap() } #[cfg(feature = "gcpkms")] fn get_kms(kms_key: &str) -> impl KmsProvider { use roughenough::kms::GcpKms; GcpKms::from_resource_id(kms_key).unwrap() } #[allow(unused_variables)] pub fn main() { SimpleLogger::new() .with_level(LevelFilter::Info) .init() .unwrap(); if !(cfg!(feature = "gcpkms") || cfg!(feature = "awskms")) { warn!("KMS support was not compiled into this build; nothing to do."); warn!("See the Roughenough documentation for information on KMS support."); warn!(" https://github.com/int08h/roughenough/blob/master/doc/OPTIONAL-FEATURES.md"); return; }
let kms_key = matches.value_of("KEY_ID").expect("Invalid KMS key id"); if matches.is_present("SEED") { let hex_seed = matches.value_of("SEED").expect("Invalid seed value"); encrypt_seed(kms_key, hex_seed); } else if matches.is_present("DECRYPT") { let hex_blob = matches.value_of("DECRYPT").expect("Invalid blob value"); decrypt_blob(kms_key, hex_blob); } else { error!("Neither seed encryption (-s) or blob decryption (-d) was specified."); error!("One of them is required."); } }
let matches = App::new("roughenough-kms") .version(roughenough_version().as_ref()) .long_about("Encrypt and decrypt Roughenough long-term server seeds using a KMS") .arg( Arg::with_name("KEY_ID") .short("k") .long("kms-key") .takes_value(true) .required(true) .help("Identity of the KMS key to be used"), ) .arg( Arg::with_name("DECRYPT") .short("d") .long("decrypt") .takes_value(true) .required(false) .help("Previously encrypted blob to decrypt to plaintext"), ) .arg( Arg::with_name("SEED") .short("s") .long("seed") .takes_value(true) .required(false) .help("32 byte hex seed for the server's long-term identity"), ) .get_matches();
assignment_statement
[ { "content": "/// Factory function to create a `ServerConfig` _trait object_ based on the value\n\n/// of the provided `arg`.\n\n///\n\n/// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html)\n\n/// * any other value returns a [`FileConfig`](struct.FileConfig.html)\n\n///\n\npub fn m...
Rust
src/read/elf/hash.rs
sunfishcode/object
aaf312e51fc6e4511e19a32c05d4b2ddf248b5b6
use core::mem; use crate::elf; use crate::read::{ReadError, ReadRef, Result}; use crate::{U32, U64}; use super::{FileHeader, Sym, SymbolTable, Version, VersionTable}; #[derive(Debug)] pub struct HashTable<'data, Elf: FileHeader> { buckets: &'data [U32<Elf::Endian>], chains: &'data [U32<Elf::Endian>], } impl<'data, Elf: FileHeader> HashTable<'data, Elf> { pub fn parse(endian: Elf::Endian, data: &'data [u8]) -> Result<Self> { let mut offset = 0; let header = data .read::<elf::HashHeader<Elf::Endian>>(&mut offset) .read_error("Invalid hash header")?; let buckets = data .read_slice(&mut offset, header.bucket_count.get(endian) as usize) .read_error("Invalid hash buckets")?; let chains = data .read_slice(&mut offset, header.chain_count.get(endian) as usize) .read_error("Invalid hash chains")?; Ok(HashTable { buckets, chains }) } pub fn symbol_table_length(&self) -> u32 { self.chains.len() as u32 } pub fn find<R: ReadRef<'data>>( &self, endian: Elf::Endian, name: &[u8], hash: u32, version: Option<&Version>, symbols: &SymbolTable<'data, Elf, R>, versions: &VersionTable<'data, Elf>, ) -> Option<(usize, &'data Elf::Sym)> { let mut index = self.buckets[(hash as usize) % self.buckets.len()].get(endian) as usize; let mut i = 0; let strings = symbols.strings(); while index != 0 && i < self.chains.len() { if let Ok(symbol) = symbols.symbol(index) { if symbol.name(endian, strings) == Ok(name) && versions.matches(endian, index, version) { return Some((index, symbol)); } } index = self.chains.get(index)?.get(endian) as usize; i += 1; } None } } #[derive(Debug)] pub struct GnuHashTable<'data, Elf: FileHeader> { symbol_base: u32, bloom_shift: u32, bloom_filters: &'data [u8], buckets: &'data [U32<Elf::Endian>], values: &'data [U32<Elf::Endian>], } impl<'data, Elf: FileHeader> GnuHashTable<'data, Elf> { pub fn parse(endian: Elf::Endian, data: &'data [u8]) -> Result<Self> { let mut offset = 0; let header = data .read::<elf::GnuHashHeader<Elf::Endian>>(&mut offset) .read_error("Invalid GNU hash header")?; let bloom_len = u64::from(header.bloom_count.get(endian)) * mem::size_of::<Elf::Word>() as u64; let bloom_filters = data .read_bytes(&mut offset, bloom_len) .read_error("Invalid GNU hash bloom filters")?; let buckets = data .read_slice(&mut offset, header.bucket_count.get(endian) as usize) .read_error("Invalid GNU hash buckets")?; let chain_count = (data.len() - offset as usize) / 4; let values = data .read_slice(&mut offset, chain_count) .read_error("Invalid GNU hash values")?; Ok(GnuHashTable { symbol_base: header.symbol_base.get(endian), bloom_shift: header.bloom_shift.get(endian), bloom_filters, buckets, values, }) } pub fn symbol_base(&self) -> u32 { self.symbol_base } pub fn symbol_table_length(&self, endian: Elf::Endian) -> Option<u32> { if self.symbol_base == 0 { return None; } let mut max_symbol = 0; for bucket in self.buckets { let bucket = bucket.get(endian); if max_symbol < bucket { max_symbol = bucket; } } for value in self .values .get(max_symbol.checked_sub(self.symbol_base)? as usize..)? { max_symbol += 1; if value.get(endian) & 1 != 0 { return Some(max_symbol); } } None } pub fn find<R: ReadRef<'data>>( &self, endian: Elf::Endian, name: &[u8], hash: u32, version: Option<&Version>, symbols: &SymbolTable<'data, Elf, R>, versions: &VersionTable<'data, Elf>, ) -> Option<(usize, &'data Elf::Sym)> { let word_bits = mem::size_of::<Elf::Word>() as u32 * 8; let bloom_count = self.bloom_filters.len() / mem::size_of::<Elf::Word>(); let offset = ((hash / word_bits) & (bloom_count as u32 - 1)) * mem::size_of::<Elf::Word>() as u32; let filter = if word_bits == 64 { self.bloom_filters .read_at::<U64<Elf::Endian>>(offset.into()) .ok()? .get(endian) } else { self.bloom_filters .read_at::<U32<Elf::Endian>>(offset.into()) .ok()? .get(endian) .into() }; if filter & (1 << (hash % word_bits)) == 0 { return None; } if filter & (1 << ((hash >> self.bloom_shift) % word_bits)) == 0 { return None; } let mut index = self.buckets[(hash as usize) % self.buckets.len()].get(endian) as usize; if index == 0 { return None; } let strings = symbols.strings(); let symbols = symbols.symbols().get(index..)?; let values = self .values .get(index.checked_sub(self.symbol_base as usize)?..)?; for (symbol, value) in symbols.iter().zip(values.iter()) { let value = value.get(endian); if value | 1 == hash | 1 { if symbol.name(endian, strings) == Ok(name) && versions.matches(endian, index, version) { return Some((index, symbol)); } } if value & 1 != 0 { break; } index += 1; } None } }
use core::mem; use crate::elf; use crate::read::{ReadError, ReadRef, Result}; use crate::{U32, U64}; use super::{FileHeader, Sym, SymbolTable, Version, VersionTable}; #[derive(Debug)] pub struct HashTable<'data, Elf: FileHeader> { buckets: &'data [U32<Elf::Endian>], chains: &'data [U32<Elf::Endian>], } impl<'data, Elf: FileHeader> HashTable<'data, Elf> { pub fn parse(endian: Elf::Endian, data: &'data [u8]) -> Result<Self> { let mut offset = 0; let header = data .read::<elf::HashHeader<Elf::Endian>>(&mut offset) .read_error("Invalid hash header")?; let buckets = data .read_slice(&mut offset, header.bucket_count.get(endian) as usize) .read_error("Invalid hash buckets")?; let chains = data .read_slice(&mut offset, header.chain_count.get(endian) as usize) .read_error("Invalid hash chains")?; Ok(HashTable { buckets, chains }) } pub fn symbol_table_length(&self) -> u32 { self.chains.len() as u32 } pub fn find<R: ReadRef<'data>>( &self, endian: Elf::Endian, name: &[u8], hash: u32, version: Option<&Version>, symbols: &SymbolTable<'data, Elf, R>, versions: &VersionTable<'data, Elf>, ) -> Option<(usize, &'data Elf::Sym)> { let mut index = self.buckets[(hash as usize) % self.buckets.len()].get(endian) as usize; let mut i = 0; let strings = symbols.strings(); while index != 0 && i < self.chains.len() { if let Ok(symbol) = symbols.symbol(index) { if symbol.name(endian, strings) == Ok(name) && versions.matches(endian, index, version) { return Some((index, symbol)); } } index = self.chains.get(index)?.get(endian) as usize; i += 1; } None } } #[derive(Debug)] pub struct GnuHashTable<'data, Elf: FileHeader> { symbol_base: u32, bloom_shift: u32, bloom_filters: &'data [u8], buckets: &'data [U32<Elf::Endian>], values: &'data [U32<Elf::Endian>], } impl<'data, Elf: FileHeader> GnuHashTable<'data, Elf> { pub fn parse(endian: Elf::Endian, data: &'data [u8]) -> Result<Self> { let mut offset = 0; let header = data .read::<elf::GnuHashHeader<Elf::Endian>>(&mut offset) .read_error("Invalid GNU hash header")?; let bloom_len = u64::from(header.bloom_count.get(endian)) * mem::size_of::<Elf::Word>() as u64; let bloom_filters = data .read_bytes(&mut offset, bloom_len) .read_error("Invalid GNU hash bloom filters")?; let buckets = data .read_slice(&mut offset, header.bucket_count.get(endian) as usize) .read_error("Invalid GNU hash buckets")?; let chain_count = (data.len() - offset as usize) / 4; let values = data .read_slice(&mut offset, chain_count) .read_error("Invalid GNU hash values")?; Ok(GnuHashTable { symbol_base: header.symbol_base.get(endian), bloom_shift: header.bloom_shift.get(endian), bloom_filters, buckets, values, }) } pub fn symbol_base(&self) -> u32 { self.symbol_base } pub fn symbol_table_length(&self, endian: Elf::Endian) -> Option<u32> { if self.symbol_base == 0 { return None; } let mut max_symbol = 0; for bucket in self.buckets { let bucket = bucket.get(endian); if max_symbol <
l); } } None } pub fn find<R: ReadRef<'data>>( &self, endian: Elf::Endian, name: &[u8], hash: u32, version: Option<&Version>, symbols: &SymbolTable<'data, Elf, R>, versions: &VersionTable<'data, Elf>, ) -> Option<(usize, &'data Elf::Sym)> { let word_bits = mem::size_of::<Elf::Word>() as u32 * 8; let bloom_count = self.bloom_filters.len() / mem::size_of::<Elf::Word>(); let offset = ((hash / word_bits) & (bloom_count as u32 - 1)) * mem::size_of::<Elf::Word>() as u32; let filter = if word_bits == 64 { self.bloom_filters .read_at::<U64<Elf::Endian>>(offset.into()) .ok()? .get(endian) } else { self.bloom_filters .read_at::<U32<Elf::Endian>>(offset.into()) .ok()? .get(endian) .into() }; if filter & (1 << (hash % word_bits)) == 0 { return None; } if filter & (1 << ((hash >> self.bloom_shift) % word_bits)) == 0 { return None; } let mut index = self.buckets[(hash as usize) % self.buckets.len()].get(endian) as usize; if index == 0 { return None; } let strings = symbols.strings(); let symbols = symbols.symbols().get(index..)?; let values = self .values .get(index.checked_sub(self.symbol_base as usize)?..)?; for (symbol, value) in symbols.iter().zip(values.iter()) { let value = value.get(endian); if value | 1 == hash | 1 { if symbol.name(endian, strings) == Ok(name) && versions.matches(endian, index, version) { return Some((index, symbol)); } } if value & 1 != 0 { break; } index += 1; } None } }
bucket { max_symbol = bucket; } } for value in self .values .get(max_symbol.checked_sub(self.symbol_base)? as usize..)? { max_symbol += 1; if value.get(endian) & 1 != 0 { return Some(max_symbo
function_block-random_span
[ { "content": "/// Calculate the GNU hash for a symbol name.\n\n///\n\n/// Used for `SHT_GNU_HASH`.\n\npub fn gnu_hash(name: &[u8]) -> u32 {\n\n let mut hash = 5381u32;\n\n for byte in name {\n\n hash = hash.wrapping_mul(33).wrapping_add(u32::from(*byte));\n\n }\n\n hash\n\n}\n\n\n\n// Motorol...
Rust
gstreamer/src/buffer_pool.rs
heftig/gstreamer-rs
03c3580c224a10c86e89b34380215a551e1f7bff
use BufferPool; use Structure; use glib; use glib::translate::{from_glib, from_glib_full, from_glib_none, ToGlib, ToGlibPtr, ToGlibPtrMut}; use glib::IsA; use ffi; use std::mem; use std::ops; use std::ptr; #[derive(Debug, PartialEq, Eq)] pub struct BufferPoolConfig(Structure); impl ops::Deref for BufferPoolConfig { type Target = ::StructureRef; fn deref(&self) -> &::StructureRef { self.0.deref() } } impl ops::DerefMut for BufferPoolConfig { fn deref_mut(&mut self) -> &mut ::StructureRef { self.0.deref_mut() } } impl AsRef<::StructureRef> for BufferPoolConfig { fn as_ref(&self) -> &::StructureRef { self.0.as_ref() } } impl AsMut<::StructureRef> for BufferPoolConfig { fn as_mut(&mut self) -> &mut ::StructureRef { self.0.as_mut() } } impl BufferPoolConfig { pub fn add_option(&mut self, option: &str) { unsafe { ffi::gst_buffer_pool_config_add_option( self.0.to_glib_none_mut().0, option.to_glib_none().0, ); } } pub fn has_option(&self, option: &str) -> bool { unsafe { from_glib(ffi::gst_buffer_pool_config_has_option( self.0.to_glib_none().0, option.to_glib_none().0, )) } } pub fn get_options(&self) -> Vec<String> { unsafe { let n = ffi::gst_buffer_pool_config_n_options(self.0.to_glib_none().0) as usize; let mut options = Vec::with_capacity(n); for i in 0..n { options.push(from_glib_none(ffi::gst_buffer_pool_config_get_option( self.0.to_glib_none().0, i as u32, ))); } options } } pub fn set_params<'a, T: Into<Option<&'a ::Caps>>>( &mut self, caps: T, size: u32, min_buffers: u32, max_buffers: u32, ) { let caps = caps.into(); unsafe { ffi::gst_buffer_pool_config_set_params( self.0.to_glib_none_mut().0, caps.to_glib_none().0, size, min_buffers, max_buffers, ); } } pub fn get_params(&self) -> Option<(Option<::Caps>, u32, u32, u32)> { unsafe { let mut caps = ptr::null_mut(); let mut size = mem::uninitialized(); let mut min_buffers = mem::uninitialized(); let mut max_buffers = mem::uninitialized(); let ret: bool = from_glib(ffi::gst_buffer_pool_config_get_params( self.0.to_glib_none().0, &mut caps, &mut size, &mut min_buffers, &mut max_buffers, )); if !ret { return None; } Some((from_glib_none(caps), size, min_buffers, max_buffers)) } } pub fn validate_params<'a, T: Into<Option<&'a ::Caps>>>( &self, caps: T, size: u32, min_buffers: u32, max_buffers: u32, ) -> bool { let caps = caps.into(); unsafe { from_glib(ffi::gst_buffer_pool_config_validate_params( self.0.to_glib_none().0, caps.to_glib_none().0, size, min_buffers, max_buffers, )) } } } #[derive(Debug)] pub struct BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams); impl BufferPoolAcquireParams { pub fn with_flags(flags: ::BufferPoolAcquireFlags) -> Self { BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams { format: ffi::GST_FORMAT_UNDEFINED, start: -1, stop: -1, flags: flags.to_glib(), _gst_reserved: [ptr::null_mut(); 4], }) } pub fn with_start_stop<T: ::SpecificFormattedValue>( start: T, stop: T, flags: ::BufferPoolAcquireFlags, ) -> Self { unsafe { BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams { format: start.get_format().to_glib(), start: start.to_raw_value(), stop: stop.to_raw_value(), flags: flags.to_glib(), _gst_reserved: [ptr::null_mut(); 4], }) } } pub fn flags(&self) -> ::BufferPoolAcquireFlags { from_glib(self.0.flags) } pub fn format(&self) -> ::Format { from_glib(self.0.format) } pub fn start(&self) -> ::GenericFormattedValue { ::GenericFormattedValue::new(from_glib(self.0.format), self.0.start) } pub fn stop(&self) -> ::GenericFormattedValue { ::GenericFormattedValue::new(from_glib(self.0.format), self.0.stop) } } impl PartialEq for BufferPoolAcquireParams { fn eq(&self, other: &Self) -> bool { self.format() == other.format() && self.start() == other.start() && self.stop() == other.stop() } } impl Eq for BufferPoolAcquireParams {} impl BufferPool { pub fn new() -> BufferPool { assert_initialized_main_thread!(); let (major, minor, _, _) = ::version(); if (major, minor) > (1, 12) { unsafe { from_glib_full(ffi::gst_buffer_pool_new()) } } else { unsafe { from_glib_none(ffi::gst_buffer_pool_new()) } } } } impl Default for BufferPool { fn default() -> Self { Self::new() } } pub trait BufferPoolExtManual { fn get_config(&self) -> BufferPoolConfig; fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError>; fn is_flushing(&self) -> bool; fn acquire_buffer<'a, P: Into<Option<&'a BufferPoolAcquireParams>>>( &self, params: P, ) -> Result<::Buffer, ::FlowReturn>; fn release_buffer(&self, buffer: ::Buffer); } impl<O: IsA<BufferPool>> BufferPoolExtManual for O { fn get_config(&self) -> BufferPoolConfig { unsafe { let ptr = ffi::gst_buffer_pool_get_config(self.to_glib_none().0); BufferPoolConfig(from_glib_full(ptr)) } } fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError> { unsafe { glib::error::BoolError::from_glib( ffi::gst_buffer_pool_set_config(self.to_glib_none().0, config.0.into_ptr()), "Failed to set config", ) } } fn is_flushing(&self) -> bool { unsafe { let stash = self.to_glib_none(); let ptr: *mut ffi::GstBufferPool = stash.0; from_glib((*ptr).flushing) } } fn acquire_buffer<'a, P: Into<Option<&'a BufferPoolAcquireParams>>>( &self, params: P, ) -> Result<::Buffer, ::FlowReturn> { let params = params.into(); let params_ptr = match params { Some(params) => &params.0 as *const _ as *mut _, None => ptr::null_mut(), }; unsafe { let mut buffer = ptr::null_mut(); let ret = from_glib(ffi::gst_buffer_pool_acquire_buffer( self.to_glib_none().0, &mut buffer, params_ptr, )); if ret == ::FlowReturn::Ok { Ok(from_glib_full(buffer)) } else { Err(ret) } } } fn release_buffer(&self, buffer: ::Buffer) { unsafe { ffi::gst_buffer_pool_release_buffer(self.to_glib_none().0, buffer.into_ptr()); } } } #[cfg(test)] mod tests { use super::*; use prelude::*; #[test] fn test_pool() { ::init().unwrap(); let pool = ::BufferPool::new(); let mut config = pool.get_config(); config.set_params(Some(&::Caps::new_simple("foo/bar", &[])), 1024, 0, 2); pool.set_config(config).unwrap(); pool.set_active(true).unwrap(); let params = ::BufferPoolAcquireParams::with_flags(::BufferPoolAcquireFlags::DONTWAIT); let _buf1 = pool.acquire_buffer(&params).unwrap(); let buf2 = pool.acquire_buffer(&params).unwrap(); assert!(pool.acquire_buffer(&params).is_err()); drop(buf2); let _buf2 = pool.acquire_buffer(&params).unwrap(); pool.set_active(false).unwrap(); } }
use BufferPool; use Structure; use glib; use glib::translate::{from_glib, from_glib_full, from_glib_none, ToGlib, ToGlibPtr, ToGlibPtrMut}; use glib::IsA; use ffi; use std::mem; use std::ops; use std::ptr; #[derive(Debug, PartialEq, Eq)] pub struct BufferPoolConfig(Structure); impl ops::Deref for BufferPoolConfig { type Target = ::StructureRef; fn deref(&self) -> &::StructureRef { self.0.deref() } } impl ops::DerefMut for BufferPoolConfig { fn deref_mut(&mut self) -> &mut ::StructureRef { self.0.deref_mut() } } impl AsRef<::StructureRef> for BufferPoolConfig { fn as_ref(&self) -> &::StructureRef { self.0.as_ref() } } impl AsMut<::StructureRef> for BufferPoolConfig { fn as_mut(&mut self) -> &mut ::StructureRef { self.0.as_mut() } } impl BufferPoolConfig { pub fn add_option(&mut self, option: &str) { unsafe { ffi::gst_buffer_pool_config_add_option( self.0.to_glib_none_mut().0, option.to_glib_none().0, ); } } pub fn has_option(&self, option: &str) -> bool { unsafe { from_glib(ffi::gst_buffer_pool_config_has_option( self.0.to_glib_none().0, option.to_glib_none().0, )) } } pub fn get_options(&self) -> Vec<String> { unsafe { let n = ffi::gst_buffer_pool_config_n_options(self.0.to_glib_none().0) as usize; let mut options = Vec::with_capacity(n); for i in 0..n { options.push(from_glib_none(ffi::gst_buffer_pool_config_get_option( self.0.to_glib_none().0, i as u32, ))); } options } } pub fn set_params<'a, T: Into<Option<&'a ::Caps>>>( &mut self, caps: T, size: u32, min_buffers: u32, max_buffers: u32, ) { let caps = caps.into(); unsafe { ffi::gst_buffer_pool_config_set_params( self.0.to_glib_none_mut().0, caps.to_glib_none().0, size, min_buffers, max_buffers, ); } } pub fn get_params(&self) -> Option<(Option<::Caps>, u32, u32, u32)> { unsafe { let mut caps = ptr::null_mut(); let mut size = mem::uninitialized(); let mut min_buffers = mem::uninitialized(); let mut max_buffers = mem::uninitialized(); let ret: bool = from_glib(ffi::gst_buffer_pool_config_get_params( self.0.to_glib_none().0, &mut caps, &mut size, &mut min_buffers, &mut max_buffers, )); if !ret { return None; } Some((from_glib_none(caps), size, min_buffers, max_buffers)) } } pub fn validate_params<'a, T: Into<Option<&'a ::Caps>>>( &self, caps: T, size: u32, min_buffers: u32, max_buffers: u32, ) -> bool { let caps = caps.into(); unsafe { from_glib(ffi::gst_buffer_pool_config_validate_params( self.0.to_glib_none().0, caps.to_glib_none().0, size, min_buffers, max_buffers, )) } } } #[derive(Debug)] pub struct BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams); impl BufferPoolAcquireParams { pub fn with_flags(flags: ::BufferPoolAcquireFlags) -> Self { BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams { format: ffi::GST_FORMAT_UNDEFINED, start: -1, stop: -1, flags: flags.to_glib(), _gst_reserved: [ptr::null_mut(); 4], }) } pub fn with_start_stop<T: ::SpecificFormattedValue>( start: T, stop: T, flags: ::BufferPoolAcquireFlags, ) -> Self { unsafe { BufferPoolAcquireParams(ffi::GstBufferPoolAcquireParams { format: start.get_format().to_glib(), start: start.to_raw_value(), stop: stop.to_raw_value(), flags: flags.to_glib(), _gst_reserved: [ptr::null_mut(); 4], }) } } pub fn flags(&self) -> ::BufferPoolAcquireFlags { from_glib(self.0.flags) } pub fn format(&self) -> ::Format { from_glib(self.0.format) } pub fn start(&self) -> ::GenericFormattedValue { ::GenericFormattedValue::new(from_glib(self.0.format), self.0.start) } pub fn stop(&self) -> ::GenericFormattedValue { ::GenericFormattedValue::new(from_glib(self.0.format), self.0.stop) } } impl PartialEq for BufferPoolAcquireParams { fn eq(&self, other: &Self) -> bool { self.format() == other.format() && self.start() == other.start() && self.stop() == other.stop() } } impl Eq for BufferPoolAcquireParams {} impl BufferPool { pub fn new() -> BufferPool { assert_initialized_main_thread!(); let (major, minor, _, _) = ::version(); if (major, minor) > (1, 12) { unsafe { from_glib_full(ffi::gst_buffer_pool_new()) } } else { unsafe { from_glib_none(ffi::gst_buffer_pool_new()) } } } } impl Default for BufferPool { fn default() -> Self { Self::new() } } pub trait BufferPoolExtManual { fn get_config(&self) -> BufferPoolConfig; fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError>; fn is_flushing(&self) -> bool; fn acquire_buffer<'a, P: Into<Option<&'a BufferPoolAcquireParams>>>( &self, params: P, ) -> Result<::Buffer, ::FlowReturn>; fn release_buffer(&self, buffer: ::Buffer); } impl<O: IsA<BufferPool>> BufferPoolExtManual for O { fn get_config(&self) -> BufferPoolConfig { unsafe { let ptr = ffi::gst_buffer_pool_get_config(self.to_glib_none().0); BufferPoolConfig(from_glib_full(ptr)) } } fn set_config(&self, config: BufferPoolConfig) -> Result<(), glib::error::BoolError> { unsafe { glib::error::BoolError::from_glib( ffi::gst_buffer_pool_set_config(self.to_glib_none().0, config.0.into_ptr()), "Failed to set config", ) } } fn is_flushing(&self) -> bool { unsafe { let stash = self.to_glib_none(); let ptr: *mut ffi::GstBufferPool = stash.0; from_glib((*ptr).flushing) } }
fn release_buffer(&self, buffer: ::Buffer) { unsafe { ffi::gst_buffer_pool_release_buffer(self.to_glib_none().0, buffer.into_ptr()); } } } #[cfg(test)] mod tests { use super::*; use prelude::*; #[test] fn test_pool() { ::init().unwrap(); let pool = ::BufferPool::new(); let mut config = pool.get_config(); config.set_params(Some(&::Caps::new_simple("foo/bar", &[])), 1024, 0, 2); pool.set_config(config).unwrap(); pool.set_active(true).unwrap(); let params = ::BufferPoolAcquireParams::with_flags(::BufferPoolAcquireFlags::DONTWAIT); let _buf1 = pool.acquire_buffer(&params).unwrap(); let buf2 = pool.acquire_buffer(&params).unwrap(); assert!(pool.acquire_buffer(&params).is_err()); drop(buf2); let _buf2 = pool.acquire_buffer(&params).unwrap(); pool.set_active(false).unwrap(); } }
fn acquire_buffer<'a, P: Into<Option<&'a BufferPoolAcquireParams>>>( &self, params: P, ) -> Result<::Buffer, ::FlowReturn> { let params = params.into(); let params_ptr = match params { Some(params) => &params.0 as *const _ as *mut _, None => ptr::null_mut(), }; unsafe { let mut buffer = ptr::null_mut(); let ret = from_glib(ffi::gst_buffer_pool_acquire_buffer( self.to_glib_none().0, &mut buffer, params_ptr, )); if ret == ::FlowReturn::Ok { Ok(from_glib_full(buffer)) } else { Err(ret) } } }
function_block-full_function
[ { "content": "pub fn type_find_helper<P: IsA<gst::Pad>>(src: &P, size: u64) -> Option<gst::Caps> {\n\n assert_initialized_main_thread!();\n\n unsafe {\n\n from_glib_full(ffi::gst_type_find_helper(src.to_glib_none().0, size))\n\n }\n\n}\n\n\n", "file_path": "gstreamer-base/src/auto/functions....
Rust
src/io/obj.rs
cpheinrich/web-geo-viewer
e835b0667e57697e0b8005c08c9dcd36222811ee
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use log::*; use rust_3d::*; use std::{ fmt, io::{BufRead, Error as ioError}, }; use super::utils::*; use super::{MaterialInfo, MaterialSurface}; pub fn load_obj_mesh<EM, P, R>( read: &mut R, mesh: &mut EM, material_info: &mut MaterialInfo, ) -> ObjResult<()> where EM: IsFaceEditableMesh<P, Face3> + IsVertexEditableMesh<P, Face3>, P: IsBuildable3D + Clone, R: BufRead, { let mut line_buffer = Vec::new(); let mut i_line = 0; let mut mtl_name = "NotSpecified".to_string(); material_info .surfaces .insert(mtl_name.clone(), MaterialSurface::new()); while let Ok(line) = fetch_line(read, &mut line_buffer) { i_line += 1; if line.starts_with(b"usemtl ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; mtl_name = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; material_info .surfaces .insert(mtl_name.clone(), MaterialSurface::new()); } if line.starts_with(b"mtllib ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let lib_name: String = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; material_info.material_libs.insert(lib_name.clone()); } if line.starts_with(b"v ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let z = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; mesh.add_vertex(P::new(x, y, z)); } else if line.starts_with(b"vt ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .or(Some(0f64)) .unwrap(); let z = words .next() .and_then(|w| from_ascii(w)) .or(Some(0f64)) .unwrap(); material_info.uv.push_d(Point3D::new(x, y, z)); } else if line.starts_with(b"f ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let mut tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let a: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_at: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_at = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let b: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_bt: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_bt = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let c: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_ct: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_ct = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } let mut maybe_d: Option<usize> = None; let mut maybe_dt: Option<usize> = None; match words.next() { Some(tmp) => { let tmp_str = until_bytes(tmp, b'/'); if tmp_str.len() > 0 { maybe_d = from_ascii(until_bytes(&tmp_str, b'/')).or(None); } if tmp_str.len() + 1 < tmp.len() { maybe_dt = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } if let Some(d) = maybe_d { let face = Face3 { a: VId { val: a - 1 }, b: VId { val: c - 1 }, c: VId { val: d - 1 }, }; material_info .surfaces .get_mut(&mtl_name) .unwrap() .faces .insert(face); } if let (Some(at), Some(ct), Some(d), Some(dt)) = (maybe_at, maybe_ct, maybe_d, maybe_dt) { material_info .surfaces .get_mut(&mtl_name) .unwrap() .uvs .insert( Face3 { a: VId { val: a - 1 }, b: VId { val: c - 1 }, c: VId { val: d - 1 }, }, Face3 { a: VId { val: at - 1 }, b: VId { val: ct - 1 }, c: VId { val: dt - 1 }, }, ); } } None => {} }; material_info .surfaces .get_mut(&mtl_name) .unwrap() .faces .insert(Face3 { a: VId { val: a - 1 }, b: VId { val: b - 1 }, c: VId { val: c - 1 }, }); if let (Some(at), Some(bt), Some(ct)) = (maybe_at, maybe_bt, maybe_ct) { material_info .surfaces .get_mut(&mtl_name) .unwrap() .uvs .insert( Face3 { a: VId { val: a - 1 }, b: VId { val: b - 1 }, c: VId { val: c - 1 }, }, Face3 { a: VId { val: at - 1 }, b: VId { val: bt - 1 }, c: VId { val: ct - 1 }, }, ); } if let Some(_next) = words.next() { return Err(ObjError::NotTriangularMesh(i_line)); } } } for surface in &material_info.surfaces { for face in &surface.1.faces { match mesh.try_add_connection(face.a, face.b, face.c).or(Err( ObjError::InvalidMeshIndices(face.a.val, face.b.val, face.c.val), )) { Ok(_) => {} Err(_) => { info!( "Warning, face {},{},{} could not be added.", face.a.val, face.b.val, face.c.val ); } } } } Ok(()) } pub fn load_obj_points<IP, P, R>(read: &mut R, ip: &mut IP) -> ObjResult<()> where IP: IsPushable<P>, P: IsBuildable3D, R: BufRead, { let mut line_buffer = Vec::new(); let mut i_line = 0; while let Ok(line) = fetch_line(read, &mut line_buffer) { i_line += 1; if line.starts_with(b"v ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let z = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; ip.push(P::new(x, y, z)); } } Ok(()) } pub enum ObjError { AccessFile, InvalidMeshIndices(usize, usize, usize), LineParse(usize), NotTriangularMesh(usize), } pub type ObjResult<T> = std::result::Result<T, ObjError>; impl fmt::Debug for ObjError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::AccessFile => write!(f, "Unable to access file"), Self::LineParse(x) => write!(f, "Unable to parse line {}", x), Self::InvalidMeshIndices(x, y, z) => { write!(f, "File contains invalid mesh indices: {}, {}, {}", x, y, z) } Self::NotTriangularMesh(x) => write!( f, "File contains face with more than 3 sets of indices on line {}", x ), } } } impl From<ioError> for ObjError { fn from(_error: ioError) -> Self { ObjError::AccessFile } }
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use log::*; use rust_3d::*; use std::{ fmt, io::{BufRead, Error as ioError}, }; use super::utils::*; use super::{MaterialInfo, MaterialSurface}; pub fn load_obj_mesh<EM, P, R>( read: &mut R, mesh: &mut EM, material_info: &mut MaterialInfo, ) -> ObjResult<()> where EM: IsFaceEditableMesh<P, Face3> + IsVertexEditableMesh<P, Face3>, P: IsBuildable3D + Clone, R: BufRead, { let mut line_buffer = Vec::new(); let mut i_line = 0; let mut mtl_name = "NotSpecified".to_string(); material_info .surfaces .insert(mtl_name.clone(), MaterialSurface::new()); while let Ok(line) = fetch_line(read, &mut line_buffer) { i_line += 1; if line.starts_with(b"usemtl ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; mtl_name = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; material_info .surfaces .insert(mtl_name.clone(), MaterialSurface::new()); } if line.starts_with(b"mtllib ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let lib_name: String = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; material_info.material_libs.insert(lib_name.clone()); } if line.starts_with(b"v ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let z = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; mesh.add_vertex(P::new(x, y, z)); } else if line.starts_with(b"vt ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .or(Some(0f64)) .unwrap(); let z = words .next() .and_then(|w| from_ascii(w)) .or(Some(0f64)) .unwrap(); material_info.uv.push_d(Point3D::new(x, y, z)); } else if line.starts_with(b"f ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let mut tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let a: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_at: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_at = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let b: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_bt: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_bt = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } tmp = words.next().ok_or(ObjError::LineParse(i_line))?; let tmp_str = until_bytes(tmp, b'/'); let c: usize = from_ascii(tmp_str).ok_or(ObjError::LineParse(i_line))?; let mut maybe_ct: Option<usize> = None; if tmp_str.len() + 1 < tmp.len() { maybe_ct = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); } let mut maybe_d: Option<usize> = None; let mut maybe_dt: Option<usize> = None; match words.next() { Some(tmp) => { let tmp_str = until_bytes(tmp, b'/'); if tmp_str.len() > 0 { maybe_d = from_ascii(until_bytes(&tmp_str, b'/')).or(None); } if tmp_str.len() + 1 < tmp.len() { maybe_dt = from_ascii(until_bytes(&tmp[(tmp_str.len() + 1)..], b'/')).or(None); }
} } } } Ok(()) } pub fn load_obj_points<IP, P, R>(read: &mut R, ip: &mut IP) -> ObjResult<()> where IP: IsPushable<P>, P: IsBuildable3D, R: BufRead, { let mut line_buffer = Vec::new(); let mut i_line = 0; while let Ok(line) = fetch_line(read, &mut line_buffer) { i_line += 1; if line.starts_with(b"v ") { let mut words = to_words_skip_empty(line); words.next().ok_or(ObjError::LineParse(i_line))?; let x = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let y = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; let z = words .next() .and_then(|w| from_ascii(w)) .ok_or(ObjError::LineParse(i_line))?; ip.push(P::new(x, y, z)); } } Ok(()) } pub enum ObjError { AccessFile, InvalidMeshIndices(usize, usize, usize), LineParse(usize), NotTriangularMesh(usize), } pub type ObjResult<T> = std::result::Result<T, ObjError>; impl fmt::Debug for ObjError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::AccessFile => write!(f, "Unable to access file"), Self::LineParse(x) => write!(f, "Unable to parse line {}", x), Self::InvalidMeshIndices(x, y, z) => { write!(f, "File contains invalid mesh indices: {}, {}, {}", x, y, z) } Self::NotTriangularMesh(x) => write!( f, "File contains face with more than 3 sets of indices on line {}", x ), } } } impl From<ioError> for ObjError { fn from(_error: ioError) -> Self { ObjError::AccessFile } }
if let Some(d) = maybe_d { let face = Face3 { a: VId { val: a - 1 }, b: VId { val: c - 1 }, c: VId { val: d - 1 }, }; material_info .surfaces .get_mut(&mtl_name) .unwrap() .faces .insert(face); } if let (Some(at), Some(ct), Some(d), Some(dt)) = (maybe_at, maybe_ct, maybe_d, maybe_dt) { material_info .surfaces .get_mut(&mtl_name) .unwrap() .uvs .insert( Face3 { a: VId { val: a - 1 }, b: VId { val: c - 1 }, c: VId { val: d - 1 }, }, Face3 { a: VId { val: at - 1 }, b: VId { val: ct - 1 }, c: VId { val: dt - 1 }, }, ); } } None => {} }; material_info .surfaces .get_mut(&mtl_name) .unwrap() .faces .insert(Face3 { a: VId { val: a - 1 }, b: VId { val: b - 1 }, c: VId { val: c - 1 }, }); if let (Some(at), Some(bt), Some(ct)) = (maybe_at, maybe_bt, maybe_ct) { material_info .surfaces .get_mut(&mtl_name) .unwrap() .uvs .insert( Face3 { a: VId { val: a - 1 }, b: VId { val: b - 1 }, c: VId { val: c - 1 }, }, Face3 { a: VId { val: at - 1 }, b: VId { val: bt - 1 }, c: VId { val: ct - 1 }, }, ); } if let Some(_next) = words.next() { return Err(ObjError::NotTriangularMesh(i_line)); } } } for surface in &material_info.surfaces { for face in &surface.1.faces { match mesh.try_add_connection(face.a, face.b, face.c).or(Err( ObjError::InvalidMeshIndices(face.a.val, face.b.val, face.c.val), )) { Ok(_) => {} Err(_) => { info!( "Warning, face {},{},{} could not be added.", face.a.val, face.b.val, face.c.val );
random
[ { "content": "/// Loads an IsMesh3D from the off file format\n\npub fn load_off_mesh<EM, P, R>(read: &mut R, mesh: &mut EM) -> OffResult<()>\n\nwhere\n\n EM: IsFaceEditableMesh<P, Face3> + IsVertexEditableMesh<P, Face3>,\n\n P: IsBuildable3D + Clone,\n\n R: BufRead,\n\n{\n\n let mut line_buffer = Ve...
Rust
step09/src/virtio.rs
13696652781/RSCV
f07db4aad2a5758ceae92fd41cd6e8520d117ace
use crate::bus::*; use crate::cpu::*; use crate::trap::*; pub const VIRTIO_IRQ: u64 = 1; const VRING_DESC_SIZE: u64 = 16; const DESC_NUM: u64 = 8; pub const VIRTIO_MAGIC: u64 = VIRTIO_BASE + 0x000; pub const VIRTIO_VERSION: u64 = VIRTIO_BASE + 0x004; pub const VIRTIO_DEVICE_ID: u64 = VIRTIO_BASE + 0x008; pub const VIRTIO_VENDOR_ID: u64 = VIRTIO_BASE + 0x00c; pub const VIRTIO_DEVICE_FEATURES: u64 = VIRTIO_BASE + 0x010; pub const VIRTIO_DRIVER_FEATURES: u64 = VIRTIO_BASE + 0x020; pub const VIRTIO_GUEST_PAGE_SIZE: u64 = VIRTIO_BASE + 0x028; pub const VIRTIO_QUEUE_SEL: u64 = VIRTIO_BASE + 0x030; pub const VIRTIO_QUEUE_NUM_MAX: u64 = VIRTIO_BASE + 0x034; pub const VIRTIO_QUEUE_NUM: u64 = VIRTIO_BASE + 0x038; pub const VIRTIO_QUEUE_PFN: u64 = VIRTIO_BASE + 0x040; pub const VIRTIO_QUEUE_NOTIFY: u64 = VIRTIO_BASE + 0x050; pub const VIRTIO_STATUS: u64 = VIRTIO_BASE + 0x070; pub struct Virtio { id: u64, driver_features: u32, page_size: u32, queue_sel: u32, queue_num: u32, queue_pfn: u32, queue_notify: u32, status: u32, disk: Vec<u8>, } impl Device for Virtio { fn load(&mut self, addr: u64, size: u64) -> Result<u64, Exception> { match size { 32 => Ok(self.load32(addr)), _ => Err(Exception::LoadAccessFault), } } fn store(&mut self, addr: u64, size: u64, value: u64) -> Result<(), Exception> { match size { 32 => Ok(self.store32(addr, value)), _ => Err(Exception::StoreAMOAccessFault), } } } impl Virtio { pub fn new(disk_image: Vec<u8>) -> Self { let mut disk = Vec::new(); disk.extend(disk_image.iter().cloned()); Self { id: 0, driver_features: 0, page_size: 0, queue_sel: 0, queue_num: 0, queue_pfn: 0, queue_notify: 9999, status: 0, disk, } } pub fn is_interrupting(&mut self) -> bool { if self.queue_notify != 9999 { self.queue_notify = 9999; return true; } false } pub fn load32(&self, addr: u64) -> u64 { match addr { VIRTIO_MAGIC => 0x74726976, VIRTIO_VERSION => 0x1, VIRTIO_DEVICE_ID => 0x2, VIRTIO_VENDOR_ID => 0x554d4551, VIRTIO_DEVICE_FEATURES => 0, VIRTIO_DRIVER_FEATURES => self.driver_features as u64, VIRTIO_QUEUE_NUM_MAX => 8, VIRTIO_QUEUE_PFN => self.queue_pfn as u64, VIRTIO_STATUS => self.status as u64, _ => 0, } } pub fn store32(&mut self, addr: u64, value: u64) { let val = value as u32; match addr { VIRTIO_DEVICE_FEATURES => self.driver_features = val, VIRTIO_GUEST_PAGE_SIZE => self.page_size = val, VIRTIO_QUEUE_SEL => self.queue_sel = val, VIRTIO_QUEUE_NUM => self.queue_num = val, VIRTIO_QUEUE_PFN => self.queue_pfn = val, VIRTIO_QUEUE_NOTIFY => self.queue_notify = val, VIRTIO_STATUS => self.status = val, _ => {} } } fn get_new_id(&mut self) -> u64 { self.id = self.id.wrapping_add(1); self.id } fn desc_addr(&self) -> u64 { self.queue_pfn as u64 * self.page_size as u64 } fn read_disk(&self, addr: u64) -> u64 { self.disk[addr as usize] as u64 } fn write_disk(&mut self, addr: u64, value: u64) { self.disk[addr as usize] = value as u8 } pub fn disk_access(cpu: &mut Cpu) { let desc_addr = cpu.bus.virtio.desc_addr(); let avail_addr = cpu.bus.virtio.desc_addr() + 0x40; let used_addr = cpu.bus.virtio.desc_addr() + 4096; let offset = cpu .bus .load(avail_addr.wrapping_add(1), 16) .expect("failed to read offset"); let index = cpu .bus .load( avail_addr.wrapping_add(offset % DESC_NUM).wrapping_add(2), 16, ) .expect("failed to read index"); let desc_addr0 = desc_addr + VRING_DESC_SIZE * index; let addr0 = cpu .bus .load(desc_addr0, 64) .expect("failed to read an address field in a descriptor"); let next0 = cpu .bus .load(desc_addr0.wrapping_add(14), 16) .expect("failed to read a next field in a descripor"); let desc_addr1 = desc_addr + VRING_DESC_SIZE * next0; let addr1 = cpu .bus .load(desc_addr1, 64) .expect("failed to read an address field in a descriptor"); let len1 = cpu .bus .load(desc_addr1.wrapping_add(8), 32) .expect("failed to read a length field in a descriptor"); let flags1 = cpu .bus .load(desc_addr1.wrapping_add(12), 16) .expect("failed to read a flags field in a descriptor"); let blk_sector = cpu .bus .load(addr0.wrapping_add(8), 64) .expect("failed to read a sector field in a virtio_blk_outhdr"); match (flags1 & 2) == 0 { true => { for i in 0..len1 as u64 { let data = cpu .bus .load(addr1 + i, 8) .expect("failed to read from memory"); cpu.bus.virtio.write_disk(blk_sector * 512 + i, data); } } false => { for i in 0..len1 as u64 { let data = cpu.bus.virtio.read_disk(blk_sector * 512 + i); cpu.bus .store(addr1 + i, 8, data) .expect("failed to write to memory"); } } }; let new_id = cpu.bus.virtio.get_new_id(); cpu.bus .store(used_addr.wrapping_add(2), 16, new_id % 8) .expect("failed to write to memory"); } }
use crate::bus::*; use crate::cpu::*; use crate::trap::*; pub const VIRTIO_IRQ: u64 = 1; const VRING_DESC_SIZE: u64 = 16; const DESC_NUM: u64 = 8; pub const VIRTIO_MAGIC: u64 = VIRTIO_BASE + 0x000; pub const VIRTIO_VERSION: u64 = VIRTIO_BASE + 0x004; pub const VIRTIO_DEVICE_ID: u64 = VIRTIO_BASE + 0x008; pub const VIRTIO_VENDOR_ID: u64 = VIRTIO_BASE + 0x00c; pub const VIRTIO_DEVICE_FEATURES: u64 = VIRTIO_BASE + 0x010; pub const VIRTIO_DRIVER_FEATURES: u64 = VIRTIO_BASE + 0x020; pub const VIRTIO_GUEST_PAGE_SIZE: u64 = VIRTIO_BASE + 0x028; pub const VIRTIO_QUEUE_SEL: u64 = VIRTIO_BASE + 0x030; pub const VIRTIO_QUEUE_NUM_MAX: u64 = VIRTIO_BASE + 0x034; pub const VIRTIO_QUEUE_NUM: u64 = VIRTIO_BASE + 0x038; pub const VIRTIO_QUEUE_PFN: u64 = VIRTIO_BASE + 0x040; pub const VIRTIO_QUEUE_NOTIFY: u64 = VIRTIO_BASE + 0x050; pub const VIRTIO_STATUS: u64 = VIRTIO_BASE + 0x070; pub struct Virtio { id: u64, driver_features: u32, page_size: u32, queue_sel: u32, queue_num: u32, queue_pfn: u32, queue_notify: u32, status: u32, disk: Vec<u8>, } impl Device for Virtio { fn load(&mut self, addr: u64, size: u64) -> Result<u64, Exception> { match size { 32 => Ok(self.load32(addr)), _ => Err(Exception::LoadAccessFault), } } fn store(&mut self, addr: u64, size: u64, value: u64) -> Result<(), Exception> {
} } impl Virtio { pub fn new(disk_image: Vec<u8>) -> Self { let mut disk = Vec::new(); disk.extend(disk_image.iter().cloned()); Self { id: 0, driver_features: 0, page_size: 0, queue_sel: 0, queue_num: 0, queue_pfn: 0, queue_notify: 9999, status: 0, disk, } } pub fn is_interrupting(&mut self) -> bool { if self.queue_notify != 9999 { self.queue_notify = 9999; return true; } false } pub fn load32(&self, addr: u64) -> u64 { match addr { VIRTIO_MAGIC => 0x74726976, VIRTIO_VERSION => 0x1, VIRTIO_DEVICE_ID => 0x2, VIRTIO_VENDOR_ID => 0x554d4551, VIRTIO_DEVICE_FEATURES => 0, VIRTIO_DRIVER_FEATURES => self.driver_features as u64, VIRTIO_QUEUE_NUM_MAX => 8, VIRTIO_QUEUE_PFN => self.queue_pfn as u64, VIRTIO_STATUS => self.status as u64, _ => 0, } } pub fn store32(&mut self, addr: u64, value: u64) { let val = value as u32; match addr { VIRTIO_DEVICE_FEATURES => self.driver_features = val, VIRTIO_GUEST_PAGE_SIZE => self.page_size = val, VIRTIO_QUEUE_SEL => self.queue_sel = val, VIRTIO_QUEUE_NUM => self.queue_num = val, VIRTIO_QUEUE_PFN => self.queue_pfn = val, VIRTIO_QUEUE_NOTIFY => self.queue_notify = val, VIRTIO_STATUS => self.status = val, _ => {} } } fn get_new_id(&mut self) -> u64 { self.id = self.id.wrapping_add(1); self.id } fn desc_addr(&self) -> u64 { self.queue_pfn as u64 * self.page_size as u64 } fn read_disk(&self, addr: u64) -> u64 { self.disk[addr as usize] as u64 } fn write_disk(&mut self, addr: u64, value: u64) { self.disk[addr as usize] = value as u8 } pub fn disk_access(cpu: &mut Cpu) { let desc_addr = cpu.bus.virtio.desc_addr(); let avail_addr = cpu.bus.virtio.desc_addr() + 0x40; let used_addr = cpu.bus.virtio.desc_addr() + 4096; let offset = cpu .bus .load(avail_addr.wrapping_add(1), 16) .expect("failed to read offset"); let index = cpu .bus .load( avail_addr.wrapping_add(offset % DESC_NUM).wrapping_add(2), 16, ) .expect("failed to read index"); let desc_addr0 = desc_addr + VRING_DESC_SIZE * index; let addr0 = cpu .bus .load(desc_addr0, 64) .expect("failed to read an address field in a descriptor"); let next0 = cpu .bus .load(desc_addr0.wrapping_add(14), 16) .expect("failed to read a next field in a descripor"); let desc_addr1 = desc_addr + VRING_DESC_SIZE * next0; let addr1 = cpu .bus .load(desc_addr1, 64) .expect("failed to read an address field in a descriptor"); let len1 = cpu .bus .load(desc_addr1.wrapping_add(8), 32) .expect("failed to read a length field in a descriptor"); let flags1 = cpu .bus .load(desc_addr1.wrapping_add(12), 16) .expect("failed to read a flags field in a descriptor"); let blk_sector = cpu .bus .load(addr0.wrapping_add(8), 64) .expect("failed to read a sector field in a virtio_blk_outhdr"); match (flags1 & 2) == 0 { true => { for i in 0..len1 as u64 { let data = cpu .bus .load(addr1 + i, 8) .expect("failed to read from memory"); cpu.bus.virtio.write_disk(blk_sector * 512 + i, data); } } false => { for i in 0..len1 as u64 { let data = cpu.bus.virtio.read_disk(blk_sector * 512 + i); cpu.bus .store(addr1 + i, 8, data) .expect("failed to write to memory"); } } }; let new_id = cpu.bus.virtio.get_new_id(); cpu.bus .store(used_addr.wrapping_add(2), 16, new_id % 8) .expect("failed to write to memory"); } }
match size { 32 => Ok(self.store32(addr, value)), _ => Err(Exception::StoreAMOAccessFault), }
if_condition
[ { "content": "fn main() -> io::Result<()> {\n\n let args: Vec<String> = env::args().collect();\n\n\n\n if args.len() != 2 {\n\n panic!(\"Usage: rvemu-for-book <filename>\");\n\n }\n\n let mut file = File::open(&args[1])?;\n\n let mut binary = Vec::new();\n\n file.read_to_end(&mut binary...
Rust
descriptor/src/ranges.rs
Moxinilian/rendy
c521b6d97d8154042bcc2215c7d7906cc70d7282
use std::{ cmp::Ordering, ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}, }; pub use gfx_hal::pso::{DescriptorRangeDesc, DescriptorSetLayoutBinding, DescriptorType}; const DESCPTOR_TYPES_COUNT: usize = 11; const DESCRIPTOR_TYPES: [DescriptorType; DESCPTOR_TYPES_COUNT] = [ DescriptorType::Sampler, DescriptorType::CombinedImageSampler, DescriptorType::SampledImage, DescriptorType::StorageImage, DescriptorType::UniformTexelBuffer, DescriptorType::StorageTexelBuffer, DescriptorType::UniformBuffer, DescriptorType::StorageBuffer, DescriptorType::UniformBufferDynamic, DescriptorType::StorageBufferDynamic, DescriptorType::InputAttachment, ]; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct DescriptorRanges { counts: [u32; DESCPTOR_TYPES_COUNT], } impl DescriptorRanges { pub fn zero() -> Self { DescriptorRanges { counts: [0; DESCPTOR_TYPES_COUNT], } } pub fn add_binding(&mut self, binding: DescriptorSetLayoutBinding) { self.counts[binding.ty as usize] += binding.count as u32; } pub fn iter(&self) -> DescriptorRangesIter<'_> { DescriptorRangesIter { counts: &self.counts, index: 0, } } pub fn counts(&self) -> &[u32] { &self.counts } pub fn counts_mut(&mut self) -> &mut [u32] { &mut self.counts } pub fn from_bindings(bindings: &[DescriptorSetLayoutBinding]) -> Self { let mut descs = Self::zero(); for binding in bindings { descs.counts[binding.ty as usize] += binding.count as u32; } descs } pub fn from_binding_iter<I>(bindings: I) -> Self where I: Iterator<Item = DescriptorSetLayoutBinding> { let mut descs = Self::zero(); for binding in bindings { descs.counts[binding.ty as usize] += binding.count as u32; } descs } } impl PartialOrd for DescriptorRanges { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { let mut ord = self.counts[0].partial_cmp(&other.counts[0])?; for i in 1..DESCPTOR_TYPES_COUNT { match (ord, self.counts[i].partial_cmp(&other.counts[i])?) { (Ordering::Less, Ordering::Greater) | (Ordering::Greater, Ordering::Less) => { return None; } (Ordering::Equal, new) => ord = new, _ => (), } } Some(ord) } } impl Add for DescriptorRanges { type Output = Self; fn add(mut self, rhs: Self) -> Self { self += rhs; self } } impl AddAssign for DescriptorRanges { fn add_assign(&mut self, rhs: Self) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] += rhs.counts[i]; } } } impl Sub for DescriptorRanges { type Output = Self; fn sub(mut self, rhs: Self) -> Self { self -= rhs; self } } impl SubAssign for DescriptorRanges { fn sub_assign(&mut self, rhs: Self) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] -= rhs.counts[i]; } } } impl Mul<u32> for DescriptorRanges { type Output = Self; fn mul(mut self, rhs: u32) -> Self { self *= rhs; self } } impl MulAssign<u32> for DescriptorRanges { fn mul_assign(&mut self, rhs: u32) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] *= rhs; } } } impl<'a> IntoIterator for &'a DescriptorRanges { type Item = DescriptorRangeDesc; type IntoIter = DescriptorRangesIter<'a>; fn into_iter(self) -> DescriptorRangesIter<'a> { self.iter() } } pub struct DescriptorRangesIter<'a> { counts: &'a [u32; DESCPTOR_TYPES_COUNT], index: u8, } impl<'a> Iterator for DescriptorRangesIter<'a> { type Item = DescriptorRangeDesc; fn next(&mut self) -> Option<DescriptorRangeDesc> { loop { let index = self.index as usize; if index >= DESCPTOR_TYPES_COUNT { return None; } else { self.index += 1; if self.counts[index] > 0 { return Some(DescriptorRangeDesc { count: self.counts[index] as usize, ty: DESCRIPTOR_TYPES[index], }); } } } } }
use std::{ cmp::Ordering, ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}, }; pub use gfx_hal::pso::{DescriptorRangeDesc, DescriptorSetLayoutBinding, DescriptorType}; const DESCPTOR_TYPES_COUNT: usize = 11; const DESCRIPTOR_TYPES: [DescriptorType; DESCPTOR_TYPES_COUNT] = [ DescriptorType::Sampler, DescriptorType::CombinedImageSampler, DescriptorType::SampledImage, DescriptorType::StorageImage, DescriptorType::UniformTexelBuffer, DescriptorType::StorageTexelBuffer, DescriptorType::UniformBuffer, DescriptorType::StorageBuffer, DescriptorType::UniformBufferDynamic, DescriptorType::StorageBufferDynamic, DescriptorType::InputAttachment, ]; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct DescriptorRanges { counts: [u32; DESCPTOR_TYPES_COUNT], } impl DescriptorRanges { pub fn zero() -> Self { DescriptorRanges { counts: [0; DESCPTOR_TYPES_COUNT], } } pub fn add_binding(&mut self, binding: DescriptorSetLayoutBinding) { self.counts[binding.ty as usize] += binding.count as u32; } pub fn iter(&self) -> DescriptorRangesIter<'_> { DescriptorRangesIter { counts: &self.counts, index: 0, } } pub fn counts(&self) -> &[u32] { &self.counts } pub fn counts_mut(&mut self) -> &mut [u32] { &mut self.counts } pub fn from_bindings(bindings: &[DescriptorSetLayoutBinding]) -> Self { let mut descs = Self::zero(); for binding in bindings { descs.counts[binding.ty as usize] += binding.count as u32; } descs } pub fn from_binding_iter<I>(bindings: I) -> Self where I: Iterator<Item = DescriptorSetLayoutBinding> { let mut descs = Self::zero(); for binding in bindings { descs.counts[binding.ty as usize] += binding.count as u32; } descs } } impl PartialOrd for DescriptorRanges { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { let mut ord = self.counts[0].partial_cmp(&other.counts[0])?; for i in 1..DESCPTOR_TYPES_COUNT { match (ord, self.counts[i].partial_cmp(&other.counts[i])?) { (Ordering::Less, Ordering::Greater) | (Ordering::Greater, Ordering::Less) => { return None; } (Ordering::Equal, new) => ord = new, _ => (), } } Some(ord) } } impl Add for DescriptorRanges { type Output = Self; fn add(mut self, rhs: Self) -> Self { self += rhs; self } } impl AddAssign for DescriptorRanges { fn add_assign(&mut self, rhs: Self) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] += rhs.counts[i]; } } } impl Sub for DescriptorRanges { type Output = Self; fn sub(mut self, rhs: Self) -> Self { self -= rhs; self } } impl SubAssign for DescriptorRanges { fn sub_assign(&mut self, rhs: Self) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] -= rhs.counts[i]; } } } impl Mul<u32> for DescriptorRanges { type Output = Self; fn mul(mut self, rhs: u32) -> Self { self *= rhs; self } } impl MulAssign<u32> for DescriptorRanges { fn mul_assign(&mut self, rhs: u32) { for i in 0..DESCPTOR_TYPES_COUNT { self.counts[i] *= rhs; } } } impl<'a> IntoIterator for &'a DescriptorRanges { type Item = DescriptorRangeDesc; type IntoIter = DescriptorRangesIter<'a>; fn into_iter(self) -> DescriptorRangesIter<'a> { self.iter() } } pub struct DescriptorRangesIter<'a> { counts: &'a [u32; DESCPTOR_TYPES_COUNT], index: u8, } impl<'a> Iterator for DescriptorRangesIter<'a> { type Item = DescriptorRangeDesc; fn next(&mut self) -> Option<DescriptorRangeDesc> { loop { let index = self.index as usize; if index >= DESCPTOR_TYPES_COUNT { return None; } else { self.index += 1; if self.counts[index] > 0 { return
; } } } } }
Some(DescriptorRangeDesc { count: self.counts[index] as usize, ty: DESCRIPTOR_TYPES[index], })
call_expression
[ { "content": "/// Trait for vertex attributes to implement\n\npub trait AsAttribute: Debug + PartialEq + PartialOrd + Copy + Send + Sync + 'static {\n\n /// Name of the attribute\n\n const NAME: &'static str;\n\n /// Attribute format.\n\n const FORMAT: Format;\n\n}\n\n\n\n/// A unique identifier for...
Rust
src/rust/storage/seg/src/ttl_buckets/ttl_bucket.rs
wandaitzuchen/pelikan
7421cdedbd5cf5c9814d244ae02eef5ec05904bf
use super::{SEGMENT_CLEAR, SEGMENT_EXPIRE}; use crate::*; use core::num::NonZeroU32; pub struct TtlBucket { head: Option<NonZeroU32>, tail: Option<NonZeroU32>, ttl: i32, nseg: i32, next_to_merge: Option<NonZeroU32>, _pad: [u8; 44], } impl TtlBucket { pub(super) fn new(ttl: i32) -> Self { Self { head: None, tail: None, ttl, nseg: 0, next_to_merge: None, _pad: [0; 44], } } pub fn head(&self) -> Option<NonZeroU32> { self.head } pub fn set_head(&mut self, id: Option<NonZeroU32>) { self.head = id; } pub fn next_to_merge(&self) -> Option<NonZeroU32> { self.next_to_merge } pub fn set_next_to_merge(&mut self, next: Option<NonZeroU32>) { self.next_to_merge = next; } pub(super) fn expire(&mut self, hashtable: &mut HashTable, segments: &mut Segments) -> usize { if self.head.is_none() { return 0; } let mut expired = 0; loop { let seg_id = self.head; if let Some(seg_id) = seg_id { let flush_at = segments.flush_at(); let mut segment = segments.get_mut(seg_id).unwrap(); if segment.create_at() + segment.ttl() <= Instant::recent() || segment.create_at() < flush_at { if let Some(next) = segment.next_seg() { self.head = Some(next); } else { self.head = None; self.tail = None; } let _ = segment.clear(hashtable, true); segments.push_free(seg_id); SEGMENT_EXPIRE.increment(); expired += 1; } else { return expired; } } else { return expired; } } } pub(super) fn clear(&mut self, hashtable: &mut HashTable, segments: &mut Segments) -> usize { if self.head.is_none() { return 0; } let mut cleared = 0; loop { let seg_id = self.head; if let Some(seg_id) = seg_id { let mut segment = segments.get_mut(seg_id).unwrap(); if let Some(next) = segment.next_seg() { self.head = Some(next); } else { self.head = None; self.tail = None; } let _ = segment.clear(hashtable, true); segments.push_free(seg_id); SEGMENT_CLEAR.increment(); cleared += 1; } else { return cleared; } } } fn try_expand(&mut self, segments: &mut Segments) -> Result<(), TtlBucketsError> { if let Some(id) = segments.pop_free() { { if let Some(tail_id) = self.tail { let mut tail = segments.get_mut(tail_id).unwrap(); tail.set_next_seg(Some(id)); } } let mut segment = segments.get_mut(id).unwrap(); segment.set_prev_seg(self.tail); segment.set_next_seg(None); segment.set_ttl(Duration::from_secs(self.ttl as u32)); if self.head.is_none() { debug_assert!(self.tail.is_none()); self.head = Some(id); } self.tail = Some(id); self.nseg += 1; debug_assert!(!segment.evictable(), "segment should not be evictable"); segment.set_evictable(true); segment.set_accessible(true); Ok(()) } else { Err(TtlBucketsError::NoFreeSegments) } } pub(crate) fn reserve( &mut self, size: usize, segments: &mut Segments, ) -> Result<ReservedItem, TtlBucketsError> { trace!("reserving: {} bytes for ttl: {}", size, self.ttl); let seg_size = segments.segment_size() as usize; if size > seg_size { debug!("item is oversized"); return Err(TtlBucketsError::ItemOversized { size }); } loop { if let Some(id) = self.tail { if let Ok(mut segment) = segments.get_mut(id) { if !segment.accessible() { continue; } let offset = segment.write_offset() as usize; trace!("offset: {}", offset); if offset + size <= seg_size { let size = size as i32; let item = segment.alloc_item(size); return Ok(ReservedItem::new(item, segment.id(), offset)); } } } self.try_expand(segments)?; } } }
use super::{SEGMENT_CLEAR, SEGMENT_EXPIRE}; use crate::*; use core::num::NonZeroU32; pub struct TtlBucket { head: Option<NonZeroU32>, tail: Option<NonZeroU32>, ttl: i32, nseg: i32, next_to_merge: Option<NonZeroU32>, _pad: [u8; 44], } impl TtlBucket { pub(super) fn new(ttl: i32) -> Self { Self { head: None, tail: None, ttl, nseg: 0, next_to_merge: None, _pad: [0; 44], } } pub fn head(&self) -> Option<NonZeroU32> { self.head } pub fn set_head(&mut self, id: Option<NonZeroU32>) { self.head = id; } pub fn next_to_merge(&self) -> Option<NonZeroU32> { self.next_to_merge } pub fn set_next_to_merge(&mut self, next: Option<NonZeroU32>) { self.next_to_merge = next; } pub(super) fn expire(&mut self, hashtable: &mut HashTable, segments: &mut Segments) -> usize { if self.head.is_none() { return 0; } let mut expired = 0; loop { let seg_id = self.head; if let Some(seg_id) = seg_id { let flush_at = segments.flush_at(); let mut segment = segments.get_mut(seg_id).unwrap(); if segment.create_at() + segment.ttl() <= Instant::recent() || segment.create_at() < flush_at { if let Some(next) = segment.next_seg() { self.head = Some(next); } else {
ired += 1; } else { return expired; } } else { return expired; } } } pub(super) fn clear(&mut self, hashtable: &mut HashTable, segments: &mut Segments) -> usize { if self.head.is_none() { return 0; } let mut cleared = 0; loop { let seg_id = self.head; if let Some(seg_id) = seg_id { let mut segment = segments.get_mut(seg_id).unwrap(); if let Some(next) = segment.next_seg() { self.head = Some(next); } else { self.head = None; self.tail = None; } let _ = segment.clear(hashtable, true); segments.push_free(seg_id); SEGMENT_CLEAR.increment(); cleared += 1; } else { return cleared; } } } fn try_expand(&mut self, segments: &mut Segments) -> Result<(), TtlBucketsError> { if let Some(id) = segments.pop_free() { { if let Some(tail_id) = self.tail { let mut tail = segments.get_mut(tail_id).unwrap(); tail.set_next_seg(Some(id)); } } let mut segment = segments.get_mut(id).unwrap(); segment.set_prev_seg(self.tail); segment.set_next_seg(None); segment.set_ttl(Duration::from_secs(self.ttl as u32)); if self.head.is_none() { debug_assert!(self.tail.is_none()); self.head = Some(id); } self.tail = Some(id); self.nseg += 1; debug_assert!(!segment.evictable(), "segment should not be evictable"); segment.set_evictable(true); segment.set_accessible(true); Ok(()) } else { Err(TtlBucketsError::NoFreeSegments) } } pub(crate) fn reserve( &mut self, size: usize, segments: &mut Segments, ) -> Result<ReservedItem, TtlBucketsError> { trace!("reserving: {} bytes for ttl: {}", size, self.ttl); let seg_size = segments.segment_size() as usize; if size > seg_size { debug!("item is oversized"); return Err(TtlBucketsError::ItemOversized { size }); } loop { if let Some(id) = self.tail { if let Ok(mut segment) = segments.get_mut(id) { if !segment.accessible() { continue; } let offset = segment.write_offset() as usize; trace!("offset: {}", offset); if offset + size <= seg_size { let size = size as i32; let item = segment.alloc_item(size); return Ok(ReservedItem::new(item, segment.id(), offset)); } } } self.try_expand(segments)?; } } }
self.head = None; self.tail = None; } let _ = segment.clear(hashtable, true); segments.push_free(seg_id); SEGMENT_EXPIRE.increment(); exp
random
[ { "content": "#[inline]\n\nfn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {\n\n let n = cmp::min(dst.len(), src.len());\n\n dst[0..n].copy_from_slice(&src[0..n]);\n\n n\n\n}\n\n\n\n#[cfg(test)]\n\nmod tests {\n\n use super::*;\n\n use tempfile::NamedTempFile;\n\n\n\n fn kvs() -> Vec<(Strin...
Rust
oxide-7/src/video/mod.rs
coopersimon/oxide-7
538a2946fc32eef922749dcfe86490c1f09ca12e
mod ram; mod render; use std::sync::{ Arc, Mutex }; use bitflags::bitflags; use crate::{ common::Interrupt, constants::{ timing, screen }, }; use ram::VideoMem; pub use render::RenderTarget; type VRamRef = Arc<Mutex<VideoMem>>; bitflags! { #[derive(Default)] struct IntEnable: u8 { const ENABLE_NMI = bit!(7); const ENABLE_IRQ_Y = bit!(5); const ENABLE_IRQ_X = bit!(4); const AUTO_JOYPAD = bit!(0); } } impl IntEnable { fn all_irq() -> IntEnable { IntEnable::ENABLE_IRQ_X | IntEnable::ENABLE_IRQ_Y } } bitflags! { #[derive(Default)] struct PPUStatus: u8 { const V_BLANK = bit!(7); const H_BLANK = bit!(6); } } #[derive(PartialEq)] pub enum PPUSignal { None, Int(Interrupt), HBlank, Delay, FrameStart, } #[derive(Debug, PartialEq)] enum PPUState { HBlankLeft, DrawingBeforePause, DrawingAfterPause, HBlankRight, VBlank } #[derive(Clone, Copy)] pub enum BG { _1, _2, _3, _4 } impl BG { fn all() -> &'static [BG; 4] { const BGS: [BG; 4] = [BG::_1, BG::_2, BG::_3, BG::_4]; &BGS } } pub struct PPU { state: PPUState, mem: VRamRef, cycle_count: usize, scanline: usize, int_enable: IntEnable, status: PPUStatus, nmi_flag: u8, irq_flag: u8, h_timer: u16, h_cycle: usize, v_timer: u16, h_irq_latch: bool, renderer: render::RenderThread, } impl PPU { pub fn new() -> Self { let mem = Arc::new(Mutex::new(VideoMem::new())); PPU { state: PPUState::VBlank, mem: mem.clone(), cycle_count: 0, scanline: 0, int_enable: IntEnable::default(), status: PPUStatus::default(), nmi_flag: 0, irq_flag: 0, h_timer: 0, h_cycle: 0, v_timer: 0, h_irq_latch: false, renderer: render::RenderThread::new(mem), } } pub fn start_frame(&mut self, frame: RenderTarget) { self.renderer.start_frame(frame); } pub fn read_mem(&mut self, addr: u8) -> u8 { self.mem.lock().unwrap().read(addr) } pub fn write_mem(&mut self, addr: u8, data: u8) { self.mem.lock().unwrap().write(addr, data); } pub fn get_status(&mut self) -> u8 { self.status.bits() } pub fn latch_hv(&mut self) -> u8 { self.mem.lock().unwrap().set_latched_hv( (self.cycle_count / timing::DOT_TIME) as u16, self.scanline as u16 ); 0 } pub fn clock(&mut self, cycles: usize) -> PPUSignal { use PPUState::*; self.cycle_count += cycles; let transition = match self.state { VBlank if self.scanline == 0 => Some(PPUTransition::ExitVBlank), DrawingBeforePause if self.cycle_count >= timing::PAUSE_START => Some(PPUTransition::CPUPause), DrawingAfterPause if self.cycle_count >= timing::H_BLANK_TIME => Some(PPUTransition::EnterHBlank), HBlankRight if self.cycle_count >= timing::SCANLINE => Some(PPUTransition::NextLine), HBlankLeft if self.scanline > screen::V_RES => Some(PPUTransition::EnterVBlank), HBlankLeft if (self.cycle_count >= timing::SCANLINE_OFFSET) && (self.scanline <= screen::V_RES) => Some(PPUTransition::ExitHBlank), VBlank if self.cycle_count >= timing::SCANLINE => Some(PPUTransition::NextLine), _ => None }; let signal = if let Some(transition) = transition { self.transition_state(transition) } else { PPUSignal::None }; if signal == PPUSignal::None { if self.check_x_irq() { self.h_irq_latch = true; self.trigger_irq() } else { PPUSignal::None } } else { signal } } pub fn set_int_enable(&mut self, data: u8) { self.int_enable = IntEnable::from_bits_truncate(data); } pub fn set_h_timer_lo(&mut self, data: u8) { self.h_timer = set_lo!(self.h_timer, data); self.h_cycle = (self.h_timer as usize) * timing::DOT_TIME; self.h_irq_latch = false; } pub fn set_h_timer_hi(&mut self, data: u8) { self.h_timer = set_hi!(self.h_timer, data); self.h_cycle = (self.h_timer as usize) * timing::DOT_TIME; self.h_irq_latch = false; } pub fn set_v_timer_lo(&mut self, data: u8) { self.v_timer = set_lo!(self.v_timer, data); } pub fn set_v_timer_hi(&mut self, data: u8) { self.v_timer = set_hi!(self.v_timer, data); } pub fn get_nmi_flag(&mut self) -> u8 { std::mem::replace(&mut self.nmi_flag, 0) } pub fn get_irq_flag(&mut self) -> u8 { std::mem::replace(&mut self.irq_flag, 0) } } enum PPUTransition { ExitVBlank, CPUPause, EnterHBlank, NextLine, ExitHBlank, EnterVBlank, } impl PPU { fn transition_state(&mut self, transition: PPUTransition) -> PPUSignal { use PPUTransition::*; match transition { ExitVBlank => { self.nmi_flag = 0; self.irq_flag = 0; self.toggle_vblank(false); self.toggle_hblank(false); self.state = PPUState::DrawingBeforePause; PPUSignal::FrameStart }, CPUPause => { self.state = PPUState::DrawingAfterPause; PPUSignal::Delay }, EnterHBlank => { self.toggle_hblank(true); self.state = PPUState::HBlankRight; PPUSignal::HBlank }, NextLine => { self.cycle_count -= timing::SCANLINE; self.h_irq_latch = false; self.scanline += 1; if self.scanline >= screen::NUM_SCANLINES { self.scanline -= screen::NUM_SCANLINES; } if self.state == PPUState::HBlankRight { self.state = PPUState::HBlankLeft; } if self.check_y_irq() { self.trigger_irq() } else { PPUSignal::None } }, ExitHBlank => { self.toggle_hblank(false); self.renderer.draw_line((self.scanline - 1) as usize); self.state = PPUState::DrawingBeforePause; PPUSignal::None }, EnterVBlank => { self.toggle_vblank(true); self.toggle_hblank(false); { let mut mem = self.mem.lock().unwrap(); mem.oam_reset(); } self.state = PPUState::VBlank; self.trigger_nmi() }, } } fn check_y_irq(&self) -> bool { let enabled = (self.int_enable & IntEnable::all_irq()) == IntEnable::ENABLE_IRQ_Y; enabled && (self.scanline == (self.v_timer as usize)) } fn check_x_irq(&self) -> bool { let irq = self.int_enable & IntEnable::all_irq(); if !self.h_irq_latch { if irq == IntEnable::all_irq() { (self.scanline == (self.v_timer as usize)) && (self.cycle_count >= self.h_cycle) } else if irq == IntEnable::ENABLE_IRQ_X { self.cycle_count >= self.h_cycle } else { false } } else { false } } fn trigger_nmi(&mut self) -> PPUSignal { self.nmi_flag |= bit!(7); if self.int_enable.contains(IntEnable::ENABLE_NMI) { PPUSignal::Int(Interrupt::NMI) } else { PPUSignal::Int(Interrupt::VBLANK) } } fn trigger_irq(&mut self) -> PPUSignal { self.irq_flag |= bit!(7); PPUSignal::Int(Interrupt::IRQ) } fn toggle_vblank(&mut self, vblank: bool) { self.status.set(PPUStatus::V_BLANK, vblank); } fn toggle_hblank(&mut self, hblank: bool) { self.status.set(PPUStatus::H_BLANK, hblank); } }
mod ram; mod render; use std::sync::{ Arc, Mutex }; use bitflags::bitflags; use crate::{ common::Interrupt, constants::{ timing, screen }, }; use ram::VideoMem; pub use render::RenderTarget; type VRamRef = Arc<Mutex<VideoMem>>; bitflags! { #[derive(Default)] struct IntEnable: u8 { const ENABLE_NMI = bit!(7); const ENABLE_IRQ_Y = bit!(5); const ENABLE_IRQ_X = bit!(4); const AUTO_JOYPAD = bit!(0); } } impl IntEnable { fn all_irq() -> IntEnable { IntEnable::ENABLE_IRQ_X | IntEnable::ENABLE_IRQ_Y } } bitflags! { #[derive(Default)] struct PPUStatus: u8 { const V_BLANK = bit!(7); const H_BLANK = bit!(6); } } #[derive(PartialEq)] pub enum PPUSignal { None, Int(Interrupt), HBlank, Delay, FrameStart, } #[derive(Debug, PartialEq)] enum PPUState { HBlankLeft, DrawingBeforePause, DrawingAfterPause, HBlankRight, VBlank } #[derive(Clone, Copy)] pub enum BG { _1, _2, _3, _4 } impl BG { fn all() -> &'static [BG; 4] { const BGS: [BG; 4] = [BG::_1, BG::_2, BG::_3, BG::_4]; &BGS } } pub struct PPU { state: PPUState, mem: VRamRef, cycle_count: usize, scanline: usize, int_enable: IntEnable, status: PPUStatus, nmi_flag: u8, irq_flag: u8, h_timer: u16, h_cycle: usize, v_timer: u16, h_irq_latch: bool, renderer: render::RenderThread, } impl PPU { pub fn new() -> Self { let mem = Arc::new(Mut
= PPUState::VBlank; self.trigger_nmi() }, } } fn check_y_irq(&self) -> bool { let enabled = (self.int_enable & IntEnable::all_irq()) == IntEnable::ENABLE_IRQ_Y; enabled && (self.scanline == (self.v_timer as usize)) } fn check_x_irq(&self) -> bool { let irq = self.int_enable & IntEnable::all_irq(); if !self.h_irq_latch { if irq == IntEnable::all_irq() { (self.scanline == (self.v_timer as usize)) && (self.cycle_count >= self.h_cycle) } else if irq == IntEnable::ENABLE_IRQ_X { self.cycle_count >= self.h_cycle } else { false } } else { false } } fn trigger_nmi(&mut self) -> PPUSignal { self.nmi_flag |= bit!(7); if self.int_enable.contains(IntEnable::ENABLE_NMI) { PPUSignal::Int(Interrupt::NMI) } else { PPUSignal::Int(Interrupt::VBLANK) } } fn trigger_irq(&mut self) -> PPUSignal { self.irq_flag |= bit!(7); PPUSignal::Int(Interrupt::IRQ) } fn toggle_vblank(&mut self, vblank: bool) { self.status.set(PPUStatus::V_BLANK, vblank); } fn toggle_hblank(&mut self, hblank: bool) { self.status.set(PPUStatus::H_BLANK, hblank); } }
ex::new(VideoMem::new())); PPU { state: PPUState::VBlank, mem: mem.clone(), cycle_count: 0, scanline: 0, int_enable: IntEnable::default(), status: PPUStatus::default(), nmi_flag: 0, irq_flag: 0, h_timer: 0, h_cycle: 0, v_timer: 0, h_irq_latch: false, renderer: render::RenderThread::new(mem), } } pub fn start_frame(&mut self, frame: RenderTarget) { self.renderer.start_frame(frame); } pub fn read_mem(&mut self, addr: u8) -> u8 { self.mem.lock().unwrap().read(addr) } pub fn write_mem(&mut self, addr: u8, data: u8) { self.mem.lock().unwrap().write(addr, data); } pub fn get_status(&mut self) -> u8 { self.status.bits() } pub fn latch_hv(&mut self) -> u8 { self.mem.lock().unwrap().set_latched_hv( (self.cycle_count / timing::DOT_TIME) as u16, self.scanline as u16 ); 0 } pub fn clock(&mut self, cycles: usize) -> PPUSignal { use PPUState::*; self.cycle_count += cycles; let transition = match self.state { VBlank if self.scanline == 0 => Some(PPUTransition::ExitVBlank), DrawingBeforePause if self.cycle_count >= timing::PAUSE_START => Some(PPUTransition::CPUPause), DrawingAfterPause if self.cycle_count >= timing::H_BLANK_TIME => Some(PPUTransition::EnterHBlank), HBlankRight if self.cycle_count >= timing::SCANLINE => Some(PPUTransition::NextLine), HBlankLeft if self.scanline > screen::V_RES => Some(PPUTransition::EnterVBlank), HBlankLeft if (self.cycle_count >= timing::SCANLINE_OFFSET) && (self.scanline <= screen::V_RES) => Some(PPUTransition::ExitHBlank), VBlank if self.cycle_count >= timing::SCANLINE => Some(PPUTransition::NextLine), _ => None }; let signal = if let Some(transition) = transition { self.transition_state(transition) } else { PPUSignal::None }; if signal == PPUSignal::None { if self.check_x_irq() { self.h_irq_latch = true; self.trigger_irq() } else { PPUSignal::None } } else { signal } } pub fn set_int_enable(&mut self, data: u8) { self.int_enable = IntEnable::from_bits_truncate(data); } pub fn set_h_timer_lo(&mut self, data: u8) { self.h_timer = set_lo!(self.h_timer, data); self.h_cycle = (self.h_timer as usize) * timing::DOT_TIME; self.h_irq_latch = false; } pub fn set_h_timer_hi(&mut self, data: u8) { self.h_timer = set_hi!(self.h_timer, data); self.h_cycle = (self.h_timer as usize) * timing::DOT_TIME; self.h_irq_latch = false; } pub fn set_v_timer_lo(&mut self, data: u8) { self.v_timer = set_lo!(self.v_timer, data); } pub fn set_v_timer_hi(&mut self, data: u8) { self.v_timer = set_hi!(self.v_timer, data); } pub fn get_nmi_flag(&mut self) -> u8 { std::mem::replace(&mut self.nmi_flag, 0) } pub fn get_irq_flag(&mut self) -> u8 { std::mem::replace(&mut self.irq_flag, 0) } } enum PPUTransition { ExitVBlank, CPUPause, EnterHBlank, NextLine, ExitHBlank, EnterVBlank, } impl PPU { fn transition_state(&mut self, transition: PPUTransition) -> PPUSignal { use PPUTransition::*; match transition { ExitVBlank => { self.nmi_flag = 0; self.irq_flag = 0; self.toggle_vblank(false); self.toggle_hblank(false); self.state = PPUState::DrawingBeforePause; PPUSignal::FrameStart }, CPUPause => { self.state = PPUState::DrawingAfterPause; PPUSignal::Delay }, EnterHBlank => { self.toggle_hblank(true); self.state = PPUState::HBlankRight; PPUSignal::HBlank }, NextLine => { self.cycle_count -= timing::SCANLINE; self.h_irq_latch = false; self.scanline += 1; if self.scanline >= screen::NUM_SCANLINES { self.scanline -= screen::NUM_SCANLINES; } if self.state == PPUState::HBlankRight { self.state = PPUState::HBlankLeft; } if self.check_y_irq() { self.trigger_irq() } else { PPUSignal::None } }, ExitHBlank => { self.toggle_hblank(false); self.renderer.draw_line((self.scanline - 1) as usize); self.state = PPUState::DrawingBeforePause; PPUSignal::None }, EnterVBlank => { self.toggle_vblank(true); self.toggle_hblank(false); { let mut mem = self.mem.lock().unwrap(); mem.oam_reset(); } self.state
random
[ { "content": "type CartMappingFn = fn(u8, u16) -> CartDevice;\n\n\n", "file_path": "oxide-7/src/mem/rom/mod.rs", "rank": 1, "score": 252137.86479187425 }, { "content": "fn map_hirom_bank(in_bank: u8, mapping: u8, lo_rom: bool, bank_addr: u16) -> u8 {\n\n let mapped_bank = map_bank(in_bank...
Rust
src/limit.rs
phip1611/spectrum-analyzer
8f8eb2cd91768222a7ede072c2c5353788238256
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #[derive(Debug, Copy, Clone)] pub enum FrequencyLimit { All, Min(f32), Max(f32), Range(f32, f32), } impl FrequencyLimit { #[inline(always)] pub const fn maybe_min(&self) -> Option<f32> { match self { FrequencyLimit::Min(min) => Some(*min), FrequencyLimit::Range(min, _) => Some(*min), _ => None, } } #[inline(always)] pub const fn maybe_max(&self) -> Option<f32> { match self { FrequencyLimit::Max(max) => Some(*max), FrequencyLimit::Range(_, max) => Some(*max), _ => None, } } #[inline(always)] pub fn min(&self) -> f32 { self.maybe_min().expect("Must contain a value!") } #[inline(always)] pub fn max(&self) -> f32 { self.maybe_max().expect("Must contain a value!") } pub fn verify(&self, max_detectable_frequency: f32) -> Result<(), FrequencyLimitError> { match self { Self::All => Ok(()), Self::Min(x) | Self::Max(x) => { if *x < 0.0 { Err(FrequencyLimitError::ValueBelowMinimum(*x)) } else if *x > max_detectable_frequency { Err(FrequencyLimitError::ValueAboveNyquist(*x)) } else { Ok(()) } } FrequencyLimit::Range(min, max) => { let _ = Self::Min(*min).verify(max_detectable_frequency)?; let _ = Self::Max(*max).verify(max_detectable_frequency)?; if min > max { Err(FrequencyLimitError::InvalidRange(*min, *max)) } else { Ok(()) } } } } } #[derive(Debug)] pub enum FrequencyLimitError { ValueBelowMinimum(f32), ValueAboveNyquist(f32), InvalidRange(f32, f32), } #[cfg(test)] mod tests { use crate::FrequencyLimit; #[test] fn test_panic_min_below_minimum() { let _ = FrequencyLimit::Min(-1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_min_above_nyquist() { let _ = FrequencyLimit::Min(1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_max_below_minimum() { let _ = FrequencyLimit::Max(-1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_max_above_nyquist() { let _ = FrequencyLimit::Max(1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_min() { let _ = FrequencyLimit::Range(-1.0, 0.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_max() { let _ = FrequencyLimit::Range(0.0, 1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_order() { let _ = FrequencyLimit::Range(0.0, -1.0).verify(0.0).unwrap_err(); } #[test] fn test_ok() { let _ = FrequencyLimit::Min(50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Max(50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Range(50.0, 50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Range(50.0, 70.0).verify(100.0).unwrap(); } }
/* MIT License Copyright (c) 2021 Philipp Schuster Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #[derive(Debug, Copy, Clone)] pub enum FrequencyLimit { All, Min(f32), Max(f32), Range(f32, f32), } impl FrequencyLimit { #[inline(always)] pub const fn maybe_min(&self) -> Option<f32> { match self { FrequencyLimit::Min(min) => Some(*min), FrequencyLimit::Range(min, _) => Some(*min), _ => None, } } #[inline(always)] pub const fn maybe_max(&self) -> Option<f32> { match self { FrequencyLimit::Max(max) => Some(*max), FrequencyLimit::Range(_, max) => Some(*max), _ => None, } } #[inline(always)] pub fn min(&self) -> f32 { self.maybe_min().expect("Must contain a value!") } #[inline(always)] pub fn max(&self) -> f32 { self.maybe_max().expect("Must contain a value!") } pub fn verify(&self, max_detectable_frequency: f32) -> Result<(), FrequencyLimitError> { match self { Self::All => Ok(()), Self::Min(x) | Self::Max(x) => { if *x < 0.0 {
} #[derive(Debug)] pub enum FrequencyLimitError { ValueBelowMinimum(f32), ValueAboveNyquist(f32), InvalidRange(f32, f32), } #[cfg(test)] mod tests { use crate::FrequencyLimit; #[test] fn test_panic_min_below_minimum() { let _ = FrequencyLimit::Min(-1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_min_above_nyquist() { let _ = FrequencyLimit::Min(1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_max_below_minimum() { let _ = FrequencyLimit::Max(-1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_max_above_nyquist() { let _ = FrequencyLimit::Max(1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_min() { let _ = FrequencyLimit::Range(-1.0, 0.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_max() { let _ = FrequencyLimit::Range(0.0, 1.0).verify(0.0).unwrap_err(); } #[test] fn test_panic_range_order() { let _ = FrequencyLimit::Range(0.0, -1.0).verify(0.0).unwrap_err(); } #[test] fn test_ok() { let _ = FrequencyLimit::Min(50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Max(50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Range(50.0, 50.0).verify(100.0).unwrap(); let _ = FrequencyLimit::Range(50.0, 70.0).verify(100.0).unwrap(); } }
Err(FrequencyLimitError::ValueBelowMinimum(*x)) } else if *x > max_detectable_frequency { Err(FrequencyLimitError::ValueAboveNyquist(*x)) } else { Ok(()) } } FrequencyLimit::Range(min, max) => { let _ = Self::Min(*min).verify(max_detectable_frequency)?; let _ = Self::Max(*max).verify(max_detectable_frequency)?; if min > max { Err(FrequencyLimitError::InvalidRange(*min, *max)) } else { Ok(()) } } } }
function_block-function_prefix_line
[ { "content": "/// Creates a sine (sinus) wave function for a given frequency.\n\n/// Don't forget to scale up the value to the audio resolution.\n\n/// So far, amplitude is in interval `[-1; 1]`. The parameter\n\n/// of the returned function is the point in time in seconds.\n\n///\n\n/// * `frequency` is in Her...
Rust
predict/src/bin/build_driving_model.rs
ehsanul/brick
291c0783f3b062cf73887cb3581dd92342891165
extern crate bincode; extern crate flate2; extern crate predict; extern crate state; use bincode::serialize_into; use flate2::write::GzEncoder; use flate2::Compression; use predict::driving_model::{DrivingModel, PlayerTransformation, TransformationMap}; use predict::sample; use state::*; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::error::Error; use std::fs::{create_dir_all, File}; use std::io::BufWriter; use std::path::Path; fn build_model_for(control_branch: &str) -> DrivingModel { let all_samples = sample::load_all_samples(&format!("./data/samples/flat_ground/{}/", control_branch)); let mut model = DrivingModel::default(); index_all_samples(&mut model.tick2, &all_samples, 2); index_all_samples(&mut model.tick16, &all_samples, 16); model } fn write_model(path: &Path, model: DrivingModel) -> Result<(), Box<dyn Error>> { let f = BufWriter::new(File::create(path)?); let mut e = GzEncoder::new(f, Compression::default()); Ok(serialize_into(&mut e, &model)?) } fn index_all_samples(indexed: &mut TransformationMap, all_samples: &[Vec<PlayerState>], num_ticks: usize) { for sample in all_samples { if sample.len() < sample::MIN_SAMPLE_LENGTH { println!("bad sample: {:?}", sample[0]); } let mut j = 0; let ratio = FPS as usize / sample::RECORD_FPS; while sample[j..].len() > num_ticks / ratio { let key = sample::normalized_player_rounded(&sample[j]); match indexed.entry(key) { Vacant(e) => { e.insert(PlayerTransformation::from_samples(&sample[j..], num_ticks)); } Occupied(mut e) => { let should_replace = { let existing_transformation = e.get(); let existing_delta_x = (existing_transformation.start_local_vx as f32 - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vx as f32) .abs(); let existing_delta_y = (existing_transformation.start_local_vy as f32 - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vy as f32) .abs(); let existing_delta = (existing_delta_x.powf(2.0) + existing_delta_y.powf(2.0)).sqrt(); let new_lv = sample[j].local_velocity(); let new_delta_x = (new_lv.x - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vx as f32).abs(); let new_delta_y = (new_lv.y - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vy as f32).abs(); let new_delta = (new_delta_x.powf(2.0) + new_delta_y.powf(2.0)).sqrt(); new_delta < existing_delta }; if should_replace { e.insert(PlayerTransformation::from_samples(&sample[j..], num_ticks)); } } }; j += 1; } } } fn main() -> Result<(), Box<dyn Error>> { let control_branches = [ "throttle_straight", "throttle_right", "throttle_left", "boost_straight", "boost_right", "boost_left", ]; let base_path = Path::new("./models/flat_ground"); create_dir_all(&base_path)?; for control_branch in control_branches.iter() { let model = build_model_for(control_branch); let filename = format!("{}.bincode.gz", control_branch); write_model(&base_path.join(filename), model)?; } Ok(()) }
extern crate bincode; extern crate flate2; extern crate predict; extern crate state; use bincode::serialize_into; use flate2::write::GzEncoder; use flate2::Compression; use predict::driving_model::{DrivingModel, PlayerTransformation, TransformationMap}; use predict::sample; use state::*; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::error::Error; use std::fs::{create_dir_all, File}; use std::io::BufWriter; use std::path::Path; fn build_model_for(control_branch: &str) -> DrivingModel { let all_samples = sample::load_all_samples(&format!("./data/samples/flat_ground/{}/", control_branch)); let mut model = DrivingModel::default(); index_all_samples(&mut model.tick2, &all_samples, 2); index_all_samples(&mut model.tick16, &all_samples, 16); model } fn write_model(path: &Path, model: DrivingModel) -> Result<(), Box<dyn Error>> { let f = BufWriter::new(File::create(path)?); let mut e = GzEncoder::new(f, Compression::default()); Ok(serialize_into(&mut e, &model)?) } fn index_all_samples(indexed: &mut TransformationMap, all_samples: &[Vec<PlayerState>], num_ticks: usize) { for sample in all_samples { if sample.len() < sample::MIN_SAMPLE_LENGTH { println!("bad sample: {:?}", sample[0]); } let mut j = 0; let ratio = FPS as usize / sample::RECORD_FPS; while sample[j..].len() > num_ticks / ratio { let key = sample::normalized_player_rounded(&sample[j]); match indexed.entry(key) { Vacant(e) => { e.insert(PlayerTransformation::from_samples(&sample[j..], num_ticks)); } Occupied(mut e) => { let should_replace = { let existing_transformation = e.get(); let existing_delta_x = (existing_transformation.start_local_vx as f32 - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vx as f32) .abs();
let existing_delta = (existing_delta_x.powf(2.0) + existing_delta_y.powf(2.0)).sqrt(); let new_lv = sample[j].local_velocity(); let new_delta_x = (new_lv.x - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vx as f32).abs(); let new_delta_y = (new_lv.y - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vy as f32).abs(); let new_delta = (new_delta_x.powf(2.0) + new_delta_y.powf(2.0)).sqrt(); new_delta < existing_delta }; if should_replace { e.insert(PlayerTransformation::from_samples(&sample[j..], num_ticks)); } } }; j += 1; } } } fn main() -> Result<(), Box<dyn Error>> { let control_branches = [ "throttle_straight", "throttle_right", "throttle_left", "boost_straight", "boost_right", "boost_left", ]; let base_path = Path::new("./models/flat_ground"); create_dir_all(&base_path)?; for control_branch in control_branches.iter() { let model = build_model_for(control_branch); let filename = format!("{}.bincode.gz", control_branch); write_model(&base_path.join(filename), model)?; } Ok(()) }
let existing_delta_y = (existing_transformation.start_local_vy as f32 - sample::GROUND_SPEED_GRID_FACTOR * e.key().local_vy as f32) .abs();
assignment_statement
[ { "content": "fn percentile_value(numbers: &mut Vec<f32>, percentile: f32) -> f32 {\n\n numbers.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Less));\n\n let i = (percentile * numbers.len() as f32) as usize / 100;\n\n numbers[i]\n\n}\n\n\n", "file_path": "predict/tests/compare_with_sample_fil...
Rust
utoipa-gen/src/openapi.rs
juhaku/utoipa
070b00c13b41040e9605c62a0d7c3b5fcf04899c
use proc_macro2::Ident; use proc_macro_error::ResultExt; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{And, Comma}, Attribute, Error, ExprPath, GenericParam, Generics, Token, }; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned, ToTokens}; use crate::{ parse_utils, path::PATH_STRUCT_PREFIX, security_requirement::SecurityRequirementAttr, Array, ExternalDocs, }; mod info; #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct OpenApiAttr { handlers: Punctuated<ExprPath, Comma>, components: Punctuated<Component, Comma>, modifiers: Punctuated<Modifier, Comma>, security: Option<Array<SecurityRequirementAttr>>, tags: Option<Array<Tag>>, external_docs: Option<ExternalDocs>, } pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Option<OpenApiAttr> { attrs .iter() .find(|attribute| attribute.path.is_ident("openapi")) .map(|attribute| attribute.parse_args::<OpenApiAttr>().unwrap_or_abort()) } impl Parse for OpenApiAttr { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE: &str = "unexpected attribute, expected any of: handlers, components, modifiers, security, tags, external_docs"; let mut openapi = OpenApiAttr::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new(error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE, error)) })?; let attribute = &*ident.to_string(); match attribute { "handlers" => { openapi.handlers = parse_utils::parse_punctuated_within_parenthesis(input)?; } "components" => { openapi.components = parse_utils::parse_punctuated_within_parenthesis(input)? } "modifiers" => { openapi.modifiers = parse_utils::parse_punctuated_within_parenthesis(input)?; } "security" => { let security; parenthesized!(security in input); openapi.security = Some(parse_utils::parse_groups(&security)?) } "tags" => { let tags; parenthesized!(tags in input); openapi.tags = Some(parse_utils::parse_groups(&tags)?); } "external_docs" => { let external_docs; parenthesized!(external_docs in input); openapi.external_docs = Some(external_docs.parse()?); } _ => { return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE)); } } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(openapi) } } #[cfg_attr(feature = "debug", derive(Debug))] struct Component { ty: Ident, generics: Generics, } impl Component { fn has_lifetime_generics(&self) -> bool { self.generics .params .iter() .any(|generic| matches!(generic, GenericParam::Lifetime(_))) } } impl Parse for Component { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Component { ty: input.parse()?, generics: input.parse()?, }) } } #[cfg_attr(feature = "debug", derive(Debug))] struct Modifier { and: And, ident: Ident, } impl ToTokens for Modifier { fn to_tokens(&self, tokens: &mut TokenStream) { let and = &self.and; let ident = &self.ident; tokens.extend(quote! { #and #ident }) } } impl Parse for Modifier { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self { and: input.parse()?, ident: input.parse()?, }) } } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] struct Tag { name: String, description: Option<String>, external_docs: Option<ExternalDocs>, } impl Parse for Tag { fn parse(input: ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE: &str = "unexpected token, expected any of: name, description, external_docs"; let mut tag = Tag::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { syn::Error::new(error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE, error)) })?; let attribute_name = &*ident.to_string(); match attribute_name { "name" => tag.name = parse_utils::parse_next_literal_str(input)?, "description" => { tag.description = Some(parse_utils::parse_next_literal_str(input)?) } "external_docs" => { let content; parenthesized!(content in input); tag.external_docs = Some(content.parse::<ExternalDocs>()?); } _ => return Err(syn::Error::new(ident.span(), EXPECTED_ATTRIBUTE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(tag) } } impl ToTokens for Tag { fn to_tokens(&self, tokens: &mut TokenStream) { let name = &self.name; tokens.extend(quote! { utoipa::openapi::tag::TagBuilder::new().name(#name) }); if let Some(ref description) = self.description { tokens.extend(quote! { .description(Some(#description)) }); } if let Some(ref external_docs) = self.external_docs { tokens.extend(quote! { .external_docs(Some(#external_docs)) }); } tokens.extend(quote! { .build() }) } } pub(crate) struct OpenApi(pub OpenApiAttr, pub Ident); impl ToTokens for OpenApi { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let OpenApi(attributes, ident) = self; let info = info::impl_info(); let components = impl_components(&attributes.components, tokens).map(|components| { quote! { .components(Some(#components)) } }); let modifiers = &attributes.modifiers; let modifiers_len = modifiers.len(); modifiers.iter().for_each(|modifier| { let assert_modifier = format_ident!("_Assert{}", modifier.ident); let ident = &modifier.ident; quote_spanned! {modifier.ident.span()=> struct #assert_modifier where #ident : utoipa::Modify; }; }); let path_items = impl_paths(&attributes.handlers); let securities = attributes.security.as_ref().map(|securities| { quote! { .security(Some(#securities)) } }); let tags = attributes.tags.as_ref().map(|tags| { quote! { .tags(Some(#tags)) } }); let external_docs = attributes.external_docs.as_ref().map(|external_docs| { quote! { .external_docs(Some(#external_docs)) } }); tokens.extend(quote! { impl utoipa::OpenApi for #ident { fn openapi() -> utoipa::openapi::OpenApi { use utoipa::{Component, Path}; let mut openapi = utoipa::openapi::OpenApiBuilder::new() .info(#info) .paths(#path_items) #components #securities #tags #external_docs.build(); let _mods: [&dyn utoipa::Modify; #modifiers_len] = [#modifiers]; _mods.iter().for_each(|modifier| modifier.modify(&mut openapi)); openapi } } }); } } fn impl_components( components: &Punctuated<Component, Comma>, tokens: &mut TokenStream, ) -> Option<TokenStream> { if !components.is_empty() { let mut components_tokens = components.iter().fold( quote! { utoipa::openapi::ComponentsBuilder::new() }, |mut schema, component| { let ident = &component.ty; let span = ident.span(); let component_name = &*ident.to_string(); let (_, ty_generics, _) = component.generics.split_for_impl(); let assert_ty_generics = if component.has_lifetime_generics() { Some(quote! {<'static>}) } else { Some(ty_generics.to_token_stream()) }; let assert_component = format_ident!("_AssertComponent{}", component_name); tokens.extend(quote_spanned! {span=> struct #assert_component where #ident #assert_ty_generics: utoipa::Component; }); let ty_generics = if component.has_lifetime_generics() { None } else { Some(ty_generics) }; schema.extend(quote! { .component(#component_name, <#ident #ty_generics>::component()) }); schema }, ); components_tokens.extend(quote! { .build() }); Some(components_tokens) } else { None } } fn impl_paths(handler_paths: &Punctuated<ExprPath, Comma>) -> TokenStream { handler_paths.iter().fold( quote! { utoipa::openapi::path::PathsBuilder::new() }, |mut paths, handler| { let segments = handler.path.segments.iter().collect::<Vec<_>>(); let handler_fn_name = &*segments.last().unwrap().ident.to_string(); let tag = &*segments .iter() .take(segments.len() - 1) .map(|part| part.ident.to_string()) .collect::<Vec<_>>() .join("::"); let handler_ident = format_ident!("{}{}", PATH_STRUCT_PREFIX, handler_fn_name); let handler_ident_name = &*handler_ident.to_string(); let usage = syn::parse_str::<ExprPath>( &vec![ if tag.is_empty() { None } else { Some(tag) }, Some(handler_ident_name), ] .into_iter() .flatten() .collect::<Vec<_>>() .join("::"), ) .unwrap(); paths.extend(quote! { .path(#usage::path(), #usage::path_item(Some(#tag))) }); paths }, ) }
use proc_macro2::Ident; use proc_macro_error::ResultExt; use syn::{ parenthesized, parse::{Parse, ParseStream}, punctuated::Punctuated, token::{And, Comma}, Attribute, Error, ExprPath, GenericParam, Generics, Token, }; use proc_macro2::TokenStream; use quote::{format_ident, quote, quote_spanned, ToTokens}; use crate::{ parse_utils, path::PATH_STRUCT_PREFIX, security_requirement::SecurityRequirementAttr, Array, ExternalDocs, }; mod info; #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] pub struct OpenApiAttr { handlers: Punctuated<ExprPath, Comma>, components: Punctuated<Component, Comma>, modifiers: Punctuated<Modifier, Comma>, security: Option<Array<SecurityRequirementAttr>>, tags: Option<Array<Tag>>, external_docs: Option<ExternalDocs>, } pub fn parse_openapi_attrs(attrs: &[Attribute]) -> Option<OpenApiAttr> { attrs .iter() .find(|attribute| attribute.path.is_ident("openapi")) .map(|attribute| attribute.parse_args::<OpenApiAttr>().unwrap_or_abort()) } impl Parse for OpenApiAttr { fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE: &str = "unexpected attribute, expected any of: handlers, components, modifiers, security, tags, external_docs"; let mut openapi = OpenApiAttr::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { Error::new(error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE, error)) })?; let attribute = &*ident.to_string(); match attribute { "handlers" => { openapi.handlers = parse_utils::parse_punctuated_within_parenthesis(input)?; } "components" => { openapi.components = parse_utils::parse_punctuated_within_parenthesis(input)? } "modifiers" => { openapi.modifiers = parse_utils::parse_punctuated_within_parenthesis(input)?; } "security" => { let security; parenthesized!(security in input); openapi.security = Some(parse_utils::parse_groups(&security)?) } "tags" => { let tags; parenthesized!(tags in input); openapi.tags = Some(parse_utils::parse_groups(&tags)?); } "external_docs" => { let external_docs; parenthesized!(external_docs in input); openapi.external_docs = Some(external_docs.parse()?); } _ => { return Err(Error::new(ident.span(), EXPECTED_ATTRIBUTE)); } } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(openapi) } } #[cfg_attr(feature = "debug", derive(Debug))] struct Component { ty: Ident, generics: Generics, } impl Component {
} impl Parse for Component { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Component { ty: input.parse()?, generics: input.parse()?, }) } } #[cfg_attr(feature = "debug", derive(Debug))] struct Modifier { and: And, ident: Ident, } impl ToTokens for Modifier { fn to_tokens(&self, tokens: &mut TokenStream) { let and = &self.and; let ident = &self.ident; tokens.extend(quote! { #and #ident }) } } impl Parse for Modifier { fn parse(input: ParseStream) -> syn::Result<Self> { Ok(Self { and: input.parse()?, ident: input.parse()?, }) } } #[derive(Default)] #[cfg_attr(feature = "debug", derive(Debug))] struct Tag { name: String, description: Option<String>, external_docs: Option<ExternalDocs>, } impl Parse for Tag { fn parse(input: ParseStream) -> syn::Result<Self> { const EXPECTED_ATTRIBUTE: &str = "unexpected token, expected any of: name, description, external_docs"; let mut tag = Tag::default(); while !input.is_empty() { let ident = input.parse::<Ident>().map_err(|error| { syn::Error::new(error.span(), &format!("{}, {}", EXPECTED_ATTRIBUTE, error)) })?; let attribute_name = &*ident.to_string(); match attribute_name { "name" => tag.name = parse_utils::parse_next_literal_str(input)?, "description" => { tag.description = Some(parse_utils::parse_next_literal_str(input)?) } "external_docs" => { let content; parenthesized!(content in input); tag.external_docs = Some(content.parse::<ExternalDocs>()?); } _ => return Err(syn::Error::new(ident.span(), EXPECTED_ATTRIBUTE)), } if !input.is_empty() { input.parse::<Token![,]>()?; } } Ok(tag) } } impl ToTokens for Tag { fn to_tokens(&self, tokens: &mut TokenStream) { let name = &self.name; tokens.extend(quote! { utoipa::openapi::tag::TagBuilder::new().name(#name) }); if let Some(ref description) = self.description { tokens.extend(quote! { .description(Some(#description)) }); } if let Some(ref external_docs) = self.external_docs { tokens.extend(quote! { .external_docs(Some(#external_docs)) }); } tokens.extend(quote! { .build() }) } } pub(crate) struct OpenApi(pub OpenApiAttr, pub Ident); impl ToTokens for OpenApi { fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) { let OpenApi(attributes, ident) = self; let info = info::impl_info(); let components = impl_components(&attributes.components, tokens).map(|components| { quote! { .components(Some(#components)) } }); let modifiers = &attributes.modifiers; let modifiers_len = modifiers.len(); modifiers.iter().for_each(|modifier| { let assert_modifier = format_ident!("_Assert{}", modifier.ident); let ident = &modifier.ident; quote_spanned! {modifier.ident.span()=> struct #assert_modifier where #ident : utoipa::Modify; }; }); let path_items = impl_paths(&attributes.handlers); let securities = attributes.security.as_ref().map(|securities| { quote! { .security(Some(#securities)) } }); let tags = attributes.tags.as_ref().map(|tags| { quote! { .tags(Some(#tags)) } }); let external_docs = attributes.external_docs.as_ref().map(|external_docs| { quote! { .external_docs(Some(#external_docs)) } }); tokens.extend(quote! { impl utoipa::OpenApi for #ident { fn openapi() -> utoipa::openapi::OpenApi { use utoipa::{Component, Path}; let mut openapi = utoipa::openapi::OpenApiBuilder::new() .info(#info) .paths(#path_items) #components #securities #tags #external_docs.build(); let _mods: [&dyn utoipa::Modify; #modifiers_len] = [#modifiers]; _mods.iter().for_each(|modifier| modifier.modify(&mut openapi)); openapi } } }); } } fn impl_components( components: &Punctuated<Component, Comma>, tokens: &mut TokenStream, ) -> Option<TokenStream> { if !components.is_empty() { let mut components_tokens = components.iter().fold( quote! { utoipa::openapi::ComponentsBuilder::new() }, |mut schema, component| { let ident = &component.ty; let span = ident.span(); let component_name = &*ident.to_string(); let (_, ty_generics, _) = component.generics.split_for_impl(); let assert_ty_generics = if component.has_lifetime_generics() { Some(quote! {<'static>}) } else { Some(ty_generics.to_token_stream()) }; let assert_component = format_ident!("_AssertComponent{}", component_name); tokens.extend(quote_spanned! {span=> struct #assert_component where #ident #assert_ty_generics: utoipa::Component; }); let ty_generics = if component.has_lifetime_generics() { None } else { Some(ty_generics) }; schema.extend(quote! { .component(#component_name, <#ident #ty_generics>::component()) }); schema }, ); components_tokens.extend(quote! { .build() }); Some(components_tokens) } else { None } } fn impl_paths(handler_paths: &Punctuated<ExprPath, Comma>) -> TokenStream { handler_paths.iter().fold( quote! { utoipa::openapi::path::PathsBuilder::new() }, |mut paths, handler| { let segments = handler.path.segments.iter().collect::<Vec<_>>(); let handler_fn_name = &*segments.last().unwrap().ident.to_string(); let tag = &*segments .iter() .take(segments.len() - 1) .map(|part| part.ident.to_string()) .collect::<Vec<_>>() .join("::"); let handler_ident = format_ident!("{}{}", PATH_STRUCT_PREFIX, handler_fn_name); let handler_ident_name = &*handler_ident.to_string(); let usage = syn::parse_str::<ExprPath>( &vec![ if tag.is_empty() { None } else { Some(tag) }, Some(handler_ident_name), ] .into_iter() .flatten() .collect::<Vec<_>>() .join("::"), ) .unwrap(); paths.extend(quote! { .path(#usage::path(), #usage::path_item(Some(#tag))) }); paths }, ) }
fn has_lifetime_generics(&self) -> bool { self.generics .params .iter() .any(|generic| matches!(generic, GenericParam::Lifetime(_))) }
function_block-full_function
[]
Rust
src/main.rs
Drarig29/crypto-balance
b9f57923b4eb0c145ff7908c6d82425093225413
#[macro_use] extern crate rocket; extern crate chrono; extern crate dotenv; extern crate hex; extern crate hmac; extern crate mongodb; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate sha2; mod aggregate; mod database; mod model; mod requests; mod utils; use chrono::{DateTime, Utc}; use dotenv::dotenv; use env::VarError; use rocket::fs::NamedFile; use rocket::http::{ContentType, Status}; use rocket::request::Request; use rocket::response::{self, Responder}; use rocket::serde::json::Json; use rocket::Response; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::path::{Path, PathBuf}; use std::{env, vec}; #[derive(Clone)] pub struct Environment { app_password: String, binance_key: String, binance_secret: String, nomics_key: String, mongodb_host: String, mongodb_port: String, mongodb_username: String, mongodb_password: String, } #[derive(Serialize, Deserialize)] pub struct AuthBody { password: String, } #[derive(Serialize, Deserialize)] pub struct RequestBody { password: String, conversion: String, start: String, end: String, } #[derive(Debug)] struct ApiResponse { status: Status, json: Value, } #[derive(Debug)] pub struct TimeSpan { start: DateTime<Utc>, end: DateTime<Utc>, } pub const BINANCE_API_BASE_URL: &str = "https://api.binance.com/sapi/v1/accountSnapshot"; pub const NOMICS_API_BASE_URL: &str = "https://api.nomics.com/v1/currencies/sparkline"; pub const ACCOUNT_TYPE: &str = "SPOT"; fn get_env_vars() -> Result<Environment, VarError> { let app_password = env::var("APPLICATION_PASSWORD")?; let binance_key = env::var("BINANCE_API_KEY")?; let binance_secret = env::var("BINANCE_API_SECRET")?; let nomics_key = env::var("NOMICS_API_KEY")?; let mongodb_host = env::var("MONGODB_HOST")?; let mongodb_port = env::var("MONGODB_PORT")?; let mongodb_username = env::var("MONGODB_USERNAME")?; let mongodb_password = env::var("MONGODB_PASSWORD")?; Ok(Environment { app_password, binance_key, binance_secret, nomics_key, mongodb_host, mongodb_port, mongodb_username, mongodb_password, }) } #[get("/")] async fn index() -> Option<NamedFile> { NamedFile::open("static/index.html").await.ok() } #[get("/<file..>")] async fn files(file: PathBuf) -> Option<NamedFile> { NamedFile::open(Path::new("static/").join(file)).await.ok() } impl<'r> Responder<'r, 'r> for ApiResponse { fn respond_to(self, req: &Request) -> response::Result<'r> { Response::build_from(self.json.respond_to(req).unwrap()) .status(self.status) .header(ContentType::JSON) .ok() } } #[post("/auth", format = "json", data = "<body>")] async fn auth(body: Json<AuthBody>) -> ApiResponse { let env_variables = match get_env_vars() { Ok(res) => res, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; if body.password != env_variables.app_password { return ApiResponse { status: Status::Forbidden, json: json!("Incorrect password".to_string()), }; } ApiResponse { status: Status::Ok, json: json!("Success".to_string()), } } #[post("/api", format = "json", data = "<body>")] async fn api(body: Json<RequestBody>) -> ApiResponse { let env_variables = match get_env_vars() { Ok(res) => res, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; if body.password != env_variables.app_password { return ApiResponse { status: Status::Forbidden, json: json!("Incorrect password".to_string()), }; } println!("Start: {}\nEnd: {}", body.start, body.end); let start = DateTime::parse_from_rfc3339(&body.start) .unwrap() .with_timezone(&Utc); let end = DateTime::parse_from_rfc3339(&body.end) .unwrap() .with_timezone(&Utc); let mongodb_url = format!( "mongodb://{}:{}@{}:{}", env_variables.mongodb_username, env_variables.mongodb_password, env_variables.mongodb_host, env_variables.mongodb_port, ); let client = mongodb::Client::with_uri_str(&mongodb_url).await.unwrap(); let database = client.database("crypto-balance"); let available_snapshots = database::get_snapshots(&database, start, end).await; let needed_timespans = utils::get_timespans_to_retrieve(available_snapshots, start, end); if needed_timespans.is_empty() { let computed_snapshots = database::get_computed_snapshots(&database, start, end).await; let result = serde_json::to_value(&computed_snapshots).unwrap(); return ApiResponse { status: Status::Ok, json: result, }; } let split_by_30_days = utils::split_all_timespans_max_days(&needed_timespans, 30); let snapshots = match requests::get_all_snapshots( &env_variables, ACCOUNT_TYPE, 30, &split_by_30_days, ) .await { Ok(snapshots) => snapshots, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; database::push_snapshots(&database, snapshots).await; let assets = database::get_possessed_assets(&database).await; let split_by_45_days = utils::split_all_timespans_max_days(&needed_timespans, 45); let price_history = match requests::get_all_history( &env_variables, &assets, &body.conversion, &split_by_45_days, ) .await { Ok(price_history) => price_history, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; database::push_history(&database, price_history).await; let computed_snapshots = database::get_computed_snapshots(&database, start, end).await; let result = serde_json::to_value(&computed_snapshots).unwrap(); ApiResponse { status: Status::Ok, json: result, } } #[rocket::main] async fn main() { dotenv().ok(); let res = rocket::build() .mount("/", routes![index, auth, api, files]) .launch() .await; res.expect("An error occured while launching the rocket.") }
#[macro_use] extern crate rocket; extern crate chrono; extern crate dotenv; extern crate hex; extern crate hmac; extern crate mongodb; extern crate reqwest; extern crate serde; extern crate serde_json; extern crate sha2; mod aggregate; mod database; mod model; mod requests; mod utils; use chrono::{DateTime, Utc}; use dotenv::dotenv; use env::VarError; use rocket::fs::NamedFile; use rocket::http::{ContentType, Status}; use rocket::request::Request; use rocket::response::{self, Responder}; use rocket::serde::json::Json; use rocket::Response; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::path::{Path, PathBuf}; use std::{env, vec}; #[derive(Clone)] pub struct Environment { app_password: String, binance_key: String, binance_secret: String, nomics_key: String, mongodb_host: String, mongodb_port: String, mongodb_username: String, mongodb_password: String, } #[derive(Serialize, Deserialize)] pub struct AuthBody { password: String, } #[derive(Serialize, Deserialize)] pub struct RequestBody { password: String, conversion: String, start: String, end: String, } #[derive(Debug)] struct ApiResponse { status: Status, json: Value, } #[derive(Debug)] pub struct TimeSpan { start: DateTime<Utc>, end: DateTime<Utc>, } pub const BINANCE_API_BASE_URL: &str = "https://api.binance.com/sapi/v1/accountSnapshot"; pub const NOMICS_API_BASE_URL: &str = "https://api.nomics.com/v1/currencies/sparkline"; pub const ACCOUNT_TYPE: &str = "SPOT"; fn get_env_vars() -> Result<Environment, VarError> { let app_password = env::var("APPLICATION_PASSWORD")?; let binance_key = env::var("BINANCE_API_KEY")?; let binance_secret = env::var("BINANCE_API_SECRET")?; let nomics_key = env::var("NOMICS_API_KEY")?; let mongodb_host = env::var("MONGODB_HOST")?; let mongodb_port = env::var("MONGODB_PORT")?; let mongodb_username = env::var("MONGODB_USERNAME")?; let mongodb_password = env::var("MONGODB_PASSWORD")?;
} #[get("/")] async fn index() -> Option<NamedFile> { NamedFile::open("static/index.html").await.ok() } #[get("/<file..>")] async fn files(file: PathBuf) -> Option<NamedFile> { NamedFile::open(Path::new("static/").join(file)).await.ok() } impl<'r> Responder<'r, 'r> for ApiResponse { fn respond_to(self, req: &Request) -> response::Result<'r> { Response::build_from(self.json.respond_to(req).unwrap()) .status(self.status) .header(ContentType::JSON) .ok() } } #[post("/auth", format = "json", data = "<body>")] async fn auth(body: Json<AuthBody>) -> ApiResponse { let env_variables = match get_env_vars() { Ok(res) => res, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; if body.password != env_variables.app_password { return ApiResponse { status: Status::Forbidden, json: json!("Incorrect password".to_string()), }; } ApiResponse { status: Status::Ok, json: json!("Success".to_string()), } } #[post("/api", format = "json", data = "<body>")] async fn api(body: Json<RequestBody>) -> ApiResponse { let env_variables = match get_env_vars() { Ok(res) => res, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; if body.password != env_variables.app_password { return ApiResponse { status: Status::Forbidden, json: json!("Incorrect password".to_string()), }; } println!("Start: {}\nEnd: {}", body.start, body.end); let start = DateTime::parse_from_rfc3339(&body.start) .unwrap() .with_timezone(&Utc); let end = DateTime::parse_from_rfc3339(&body.end) .unwrap() .with_timezone(&Utc); let mongodb_url = format!( "mongodb://{}:{}@{}:{}", env_variables.mongodb_username, env_variables.mongodb_password, env_variables.mongodb_host, env_variables.mongodb_port, ); let client = mongodb::Client::with_uri_str(&mongodb_url).await.unwrap(); let database = client.database("crypto-balance"); let available_snapshots = database::get_snapshots(&database, start, end).await; let needed_timespans = utils::get_timespans_to_retrieve(available_snapshots, start, end); if needed_timespans.is_empty() { let computed_snapshots = database::get_computed_snapshots(&database, start, end).await; let result = serde_json::to_value(&computed_snapshots).unwrap(); return ApiResponse { status: Status::Ok, json: result, }; } let split_by_30_days = utils::split_all_timespans_max_days(&needed_timespans, 30); let snapshots = match requests::get_all_snapshots( &env_variables, ACCOUNT_TYPE, 30, &split_by_30_days, ) .await { Ok(snapshots) => snapshots, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; database::push_snapshots(&database, snapshots).await; let assets = database::get_possessed_assets(&database).await; let split_by_45_days = utils::split_all_timespans_max_days(&needed_timespans, 45); let price_history = match requests::get_all_history( &env_variables, &assets, &body.conversion, &split_by_45_days, ) .await { Ok(price_history) => price_history, Err(e) => { return ApiResponse { status: Status::InternalServerError, json: json!(e.to_string()), } } }; database::push_history(&database, price_history).await; let computed_snapshots = database::get_computed_snapshots(&database, start, end).await; let result = serde_json::to_value(&computed_snapshots).unwrap(); ApiResponse { status: Status::Ok, json: result, } } #[rocket::main] async fn main() { dotenv().ok(); let res = rocket::build() .mount("/", routes![index, auth, api, files]) .launch() .await; res.expect("An error occured while launching the rocket.") }
Ok(Environment { app_password, binance_key, binance_secret, nomics_key, mongodb_host, mongodb_port, mongodb_username, mongodb_password, })
call_expression
[ { "content": "pub fn make_aggregate_query(start: DateTime<Utc>, end: DateTime<Utc>) -> Vec<bson::Document> {\n\n vec![\n\n doc! {\n\n \"$match\": {\n\n \"time\": {\n\n \"$gte\": start,\n\n \"$lte\": end\n\n }\n\n }\n\n },\n\n ...
Rust
src/tests/unit.rs
asomers/async-weighted-semaphore
2085026ab5f4a5b9b6bc8a724e7cdca75a212c32
use std::sync::{Arc, Barrier, Mutex}; use rand::{thread_rng, Rng, SeedableRng}; use std::sync::atomic::{AtomicIsize, AtomicBool}; use std::sync::atomic::Ordering::Relaxed; use std::task::{Context, Waker, Poll}; use std::future::Future; use std::{mem, thread, fmt}; use futures_test::task::{AwokenCount, new_count_waker}; use std::pin::Pin; use futures_test::std_reexport::panic::catch_unwind; use futures_test::std_reexport::collections::BTreeMap; use rand_xorshift::XorShiftRng; use std::fmt::Debug; use futures_test::futures_core_reexport::core_reexport::fmt::Formatter; use crate::{Semaphore, AcquireFuture, PoisonError, SemaphoreGuard}; struct TestFuture<'a> { waker: Waker, count: AwokenCount, old_count: usize, inner: Pin<Box<AcquireFuture<'a>>>, amount: usize, } impl<'a> Debug for TestFuture<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("TF") .field("w", &(self.count.get() != self.old_count)) .field("p", &(self.inner.as_ref().get_ref() as *const AcquireFuture)) .field("i", &self.inner) .finish() } } impl<'a> TestFuture<'a> { fn new(sem: &'a Semaphore, amount: usize) -> Self { let (waker, count) = new_count_waker(); TestFuture { waker, count, old_count: 0, inner: Box::pin(sem.acquire(amount)), amount } } fn count(&self) -> usize { self.count.get() } fn poll(&mut self) -> Option<Result<SemaphoreGuard<'a>, PoisonError>> { match self.inner.as_mut().poll(&mut Context::from_waker(&self.waker)) { Poll::Pending => None, Poll::Ready(x) => Some(x) } } fn poll_if_woken(&mut self) -> Option<Result<SemaphoreGuard<'a>, PoisonError>> { let count = self.count.get(); if self.old_count != count { self.old_count = count; self.poll() } else { None } } fn into_inner(self) -> Pin<Box<AcquireFuture<'a>>> { self.inner } } #[test] fn test_simple() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 1); let g1 = a1.poll().unwrap().unwrap(); let mut a2 = TestFuture::new(&semaphore, 1); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); assert!(a2.poll().is_none()); mem::drop(g1); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_zero_now() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 0); let g1 = a1.poll().unwrap().unwrap(); assert_eq!(a1.count(), 0); mem::drop(g1); } #[test] fn test_zero_pending() { let semaphore = Semaphore::new(0); println!("A {:?}", semaphore); let mut a1 = TestFuture::new(&semaphore, 1); println!("B {:?}", semaphore); assert!(a1.poll().is_none()); println!("C {:?}", semaphore); let mut a2 = TestFuture::new(&semaphore, 0); let _g2 = a2.poll(); assert!(a2.poll().is_none()); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); mem::drop(a1); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_cancel() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 2); assert!(a1.poll().is_none()); let mut a2 = TestFuture::new(&semaphore, 1); assert!(a2.poll().is_none()); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); mem::drop(a1); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_leak() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 2); assert!(a1.poll().is_none()); lazy_static! { static ref SUPPRESS: Mutex<usize> = Mutex::new(0); } unsafe { *SUPPRESS.lock().unwrap() = Box::into_raw(Pin::into_inner_unchecked(a1.into_inner())) as usize; } mem::drop(semaphore); } #[test] fn test_poison_panic() { let semaphore = Semaphore::new(1); assert!(catch_unwind( || { let _guard = TestFuture::new(&semaphore, 1).poll().unwrap().unwrap(); panic!("Expected panic"); } ).is_err()); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_new() { let semaphore = Semaphore::new(usize::MAX); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_immediate() { let semaphore = Semaphore::new(0); semaphore.release(usize::MAX); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_add() { let semaphore = Semaphore::new(0); semaphore.release(Semaphore::MAX_AVAILABLE / 2); semaphore.release(Semaphore::MAX_AVAILABLE / 2 + 2); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_concurrent() { let semaphore = Semaphore::new(0); let mut future = TestFuture::new(&semaphore, 2); assert!(future.poll().is_none()); semaphore.release(usize::MAX); future.poll_if_woken().expect("done").err().expect("AcquireError"); } #[test] fn test_sequential() { let semaphore = Semaphore::new(0); let mut time = 0; let mut available = 0usize; let mut futures = BTreeMap::<usize, TestFuture>::new(); let mut rng = XorShiftRng::seed_from_u64(954360855); for _ in 0..100000 { if rng.gen_bool(0.1) && futures.len() < 5 { let amount = rng.gen_range(0, 10); let mut fut = TestFuture::new(&semaphore, amount); if let Some(guard) = fut.poll() { guard.unwrap().forget(); available = available.checked_sub(amount).unwrap(); } else { futures.insert(time, fut); } time += 1; } else if rng.gen_bool(0.1) { let mut blocked = false; let mut ready = vec![]; for (time, fut) in futures.iter_mut() { if rng.gen_bool(0.5) { if let Some(guard) = fut.poll_if_woken() { assert!(!blocked); guard.unwrap().forget(); available = available.checked_sub(fut.amount).unwrap(); ready.push(*time); } else { blocked = true; } } } for time in ready { futures.remove(&time); } } else if rng.gen_bool(0.1) && available < 30 { let amount = rng.gen_range(0, 10); available = available.checked_add(amount).unwrap(); semaphore.release(amount); } } } #[test] fn test_parallel() { for i in 0..1000 { println!("iteration {:?}", i); test_parallel_impl(); } } fn test_parallel_impl() { let threads = 10; let semaphore = Arc::new(Semaphore::new(0)); let resource = Arc::new(AtomicIsize::new(0)); let barrier = Arc::new(Barrier::new(threads)); let poisoned = Arc::new(AtomicBool::new(false)); let pending_max = Arc::new(AtomicIsize::new(-1)); (0..threads).map(|index| thread::Builder::new().name(format!("test_parallel_impl_{}", index)).spawn({ let semaphore = semaphore.clone(); let resource = resource.clone(); let barrier = barrier.clone(); let poisoned = poisoned.clone(); let pending_max = pending_max.clone(); move || { let mut time = 0; let mut futures = BTreeMap::<usize, TestFuture>::new(); let on_guard = |guard: Result<SemaphoreGuard, PoisonError>| { match guard { Err(PoisonError) => {} Ok(guard) => { let amount = guard.forget() as isize; resource.fetch_sub(amount, Relaxed).checked_sub(amount).unwrap(); } } }; for _ in 0.. { if thread_rng().gen_bool(0.1) { if futures.len() < 5 { let amount = thread_rng().gen_range(0, 10); let mut fut = TestFuture::new(&semaphore, amount); match fut.poll() { None => { futures.insert(time, fut); } Some(guard) => on_guard(guard), } time += 1; } } if thread_rng().gen_bool(0.001) { if barrier.wait().is_leader() { pending_max.store(-1, Relaxed); } let was_poisoned = poisoned.load(Relaxed); let mut ready = vec![]; for (time, fut) in futures.iter_mut() { if let Some(guard) = fut.poll_if_woken() { on_guard(guard); ready.push(*time); } } for time in ready { futures.remove(&time); } barrier.wait(); print!("{:?} ", futures.len()); if let Some(front) = futures.values_mut().next() { pending_max.fetch_max(front.amount as isize, Relaxed); } let leader = barrier.wait(); let pending_amount = pending_max.load(Relaxed); if pending_amount >= 0 && pending_amount <= resource.load(Relaxed) { for (time, fut) in futures.iter_mut() { println!("{:?} {:?}", time, fut); } if leader.is_leader() { println!("{:?}", semaphore); panic!("Should have acquired. {:?} of {:?}", pending_amount, resource.load(Relaxed)); } } if barrier.wait().is_leader() { println!(); } if was_poisoned { return; } } if thread_rng().gen_bool(0.1) { let mut ready = vec![]; for (time, fut) in futures.iter_mut().rev() { if thread_rng().gen_bool(0.5) { let guard = if time & 1 == 1 && thread_rng().gen_bool(0.5) { fut.poll() } else { fut.poll_if_woken() }; if let Some(guard) = guard { on_guard(guard); ready.push(*time); } else if !ready.is_empty() { println!("{:?}", semaphore); for (time, fut) in futures.iter_mut() { println!("{:?} {:?}", time, fut); } panic!(); } } } for time in ready { futures.remove(&time); } } if thread_rng().gen_bool(0.1) { let mut cancelled = vec![]; for (time, _) in futures.iter_mut().rev() { if time & 2 == 2 && thread_rng().gen_bool(0.5) { cancelled.push(*time); } } for time in cancelled { futures.remove(&time); } } if thread_rng().gen_bool(0.1) && resource.load(Relaxed) < 20 { let amount = thread_rng().gen_range(0, 20); resource.fetch_add(amount as isize, Relaxed); semaphore.release(amount); } if thread_rng().gen_bool(0.1) { if let Ok(guard) = semaphore.try_acquire(thread_rng().gen_range(0, 10)) { on_guard(Ok(guard)); } } if thread_rng().gen_bool(0.0001) { poisoned.store(true, Relaxed); semaphore.poison(); } } } }).unwrap()).collect::<Vec<_>>().into_iter().for_each(|x| x.join().unwrap()); }
use std::sync::{Arc, Barrier, Mutex}; use rand::{thread_rng, Rng, SeedableRng}; use std::sync::atomic::{AtomicIsize, AtomicBool}; use std::sync::atomic::Ordering::Relaxed; use std::task::{Context, Waker, Poll}; use std::future::Future; use std::{mem, thread, fmt}; use futures_test::task::{AwokenCount, new_count_waker}; use std::pin::Pin; use futures_test::std_reexport::panic::catch_unwind; use futures_test::std_reexport::collections::BTreeMap; use rand_xorshift::XorShiftRng; use std::fmt::Debug; use futures_test::futures_core_reexport::core_reexport::fmt::Formatter; use crate::{Semaphore, AcquireFuture, PoisonError, SemaphoreGuard}; struct TestFuture<'a> { waker: Waker, count: AwokenCount, old_count: usize, inner: Pin<Box<AcquireFuture<'a>>>, amount: usize, } impl<'a> Debug for TestFuture<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("TF") .field("w", &(self.count.get() != self.old_count)) .field("p", &(self.inner.as_ref().get_ref() as *const AcquireFuture)) .field("i", &self.inner) .finish() } } impl<'a> TestFuture<'a> { fn new(sem: &'a Semaphore, amount: usize) -> Self { let (waker, count) = new_count_waker(); TestFuture { waker, count, old_count: 0, inner: Box::pin(sem.acquire(amount)), amount } } fn count(&self) -> usize { self.count.get() } fn poll(&mut self) -> Option<Result<SemaphoreGuard<'a>, PoisonError>> { match self.inner.as_mut().poll(&mut Context::from_waker(&self.waker)) { Poll::Pending => None, Poll::Ready(x) => Some(x) } } fn poll_if_woken(&mut self) -> Option<Result<SemaphoreGuard<'a>, PoisonError>> { let count = self.count.get(); if self.old_count != count { self.old_count = count; self.poll() } else { None } } fn into_inner(self) -> Pin<Box<AcquireFuture<'a>>> { self.inner } } #[test] fn test_simple() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 1); let g1 = a1.poll().unwrap().unwrap(); let mut a2 = TestFuture::new(&semaphore, 1); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); assert!(a2.poll().is_none()); mem::drop(g1); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_zero_now() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 0); let g1 = a1.poll().unwrap().unwrap(); assert_eq!(a1.count(), 0); mem::drop(g1); } #[test] fn test_zero_pending() { let semaphore = Semaphore::new(0); println!("A {:?}", semaphore); let mut a1 = TestFuture::new(&semaphore, 1); println!("B {:?}", semaphore); assert!(a1.poll().is_none()); println!("C {:?}", semaphore); let mut a2 = TestFuture::new(&semaphore, 0); let _g2 = a2.poll(); assert!(a2.poll().is_none()); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); mem::drop(a1); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_cancel() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 2); assert!(a1.poll().is_none()); let mut a2 = TestFuture::new(&semaphore, 1); assert!(a2.poll().is_none()); assert_eq!(a1.count(), 0); assert_eq!(a2.count(), 0); mem::drop(a1); assert_eq!(a2.count(), 1); assert!(a2.poll().is_some()); } #[test] fn test_leak() { let semaphore = Semaphore::new(1); let mut a1 = TestFuture::new(&semaphore, 2); assert!(a1.poll().is_none()); lazy_static! { static ref SUPPRESS: Mutex<usize> = Mutex::new(0); } unsafe { *SUPPRESS.lock().unwrap() = Box::into_raw(Pin::into_inner_unchecked(a1.into_inner())) as usize; } mem::drop(semaphore); } #[test] fn test_poison_panic() { let semaphore = Semaphore::new(1); assert!(catch_unwind( || { let _guard = TestFuture::new(&semaphore, 1).poll().unwrap().unwrap(); panic!("Expected panic"); } ).is_err()); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_new() { let semaphore = Semaphore::new(usize::MAX); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_immediate() { let semaphore = Semaphore::new(0); semaphore.release(usize::MAX); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_add() { let semaphore = Semaphore::new(0); semaphore.release(Semaphore::MAX_AVAILABLE / 2); semaphore.release(Semaphore::MAX_AVAILABLE / 2 + 2); TestFuture::new(&semaphore, 2).poll().unwrap().err().unwrap(); } #[test] fn test_poison_release_concurrent() { let semaphore = Semaphore::new(0); let mut future = TestFuture::new(&semaphore, 2); assert!(future.poll().is_none()); semaphore.release(usize::MAX); future.poll_if_woken().expect("done").err().expect("AcquireError"); } #[test] fn test_sequential() { let semaphore = Semaphore::new(0); let mut time = 0; let mut available = 0usize; let mut futures = BTreeMap::<usi
#[test] fn test_parallel() { for i in 0..1000 { println!("iteration {:?}", i); test_parallel_impl(); } } fn test_parallel_impl() { let threads = 10; let semaphore = Arc::new(Semaphore::new(0)); let resource = Arc::new(AtomicIsize::new(0)); let barrier = Arc::new(Barrier::new(threads)); let poisoned = Arc::new(AtomicBool::new(false)); let pending_max = Arc::new(AtomicIsize::new(-1)); (0..threads).map(|index| thread::Builder::new().name(format!("test_parallel_impl_{}", index)).spawn({ let semaphore = semaphore.clone(); let resource = resource.clone(); let barrier = barrier.clone(); let poisoned = poisoned.clone(); let pending_max = pending_max.clone(); move || { let mut time = 0; let mut futures = BTreeMap::<usize, TestFuture>::new(); let on_guard = |guard: Result<SemaphoreGuard, PoisonError>| { match guard { Err(PoisonError) => {} Ok(guard) => { let amount = guard.forget() as isize; resource.fetch_sub(amount, Relaxed).checked_sub(amount).unwrap(); } } }; for _ in 0.. { if thread_rng().gen_bool(0.1) { if futures.len() < 5 { let amount = thread_rng().gen_range(0, 10); let mut fut = TestFuture::new(&semaphore, amount); match fut.poll() { None => { futures.insert(time, fut); } Some(guard) => on_guard(guard), } time += 1; } } if thread_rng().gen_bool(0.001) { if barrier.wait().is_leader() { pending_max.store(-1, Relaxed); } let was_poisoned = poisoned.load(Relaxed); let mut ready = vec![]; for (time, fut) in futures.iter_mut() { if let Some(guard) = fut.poll_if_woken() { on_guard(guard); ready.push(*time); } } for time in ready { futures.remove(&time); } barrier.wait(); print!("{:?} ", futures.len()); if let Some(front) = futures.values_mut().next() { pending_max.fetch_max(front.amount as isize, Relaxed); } let leader = barrier.wait(); let pending_amount = pending_max.load(Relaxed); if pending_amount >= 0 && pending_amount <= resource.load(Relaxed) { for (time, fut) in futures.iter_mut() { println!("{:?} {:?}", time, fut); } if leader.is_leader() { println!("{:?}", semaphore); panic!("Should have acquired. {:?} of {:?}", pending_amount, resource.load(Relaxed)); } } if barrier.wait().is_leader() { println!(); } if was_poisoned { return; } } if thread_rng().gen_bool(0.1) { let mut ready = vec![]; for (time, fut) in futures.iter_mut().rev() { if thread_rng().gen_bool(0.5) { let guard = if time & 1 == 1 && thread_rng().gen_bool(0.5) { fut.poll() } else { fut.poll_if_woken() }; if let Some(guard) = guard { on_guard(guard); ready.push(*time); } else if !ready.is_empty() { println!("{:?}", semaphore); for (time, fut) in futures.iter_mut() { println!("{:?} {:?}", time, fut); } panic!(); } } } for time in ready { futures.remove(&time); } } if thread_rng().gen_bool(0.1) { let mut cancelled = vec![]; for (time, _) in futures.iter_mut().rev() { if time & 2 == 2 && thread_rng().gen_bool(0.5) { cancelled.push(*time); } } for time in cancelled { futures.remove(&time); } } if thread_rng().gen_bool(0.1) && resource.load(Relaxed) < 20 { let amount = thread_rng().gen_range(0, 20); resource.fetch_add(amount as isize, Relaxed); semaphore.release(amount); } if thread_rng().gen_bool(0.1) { if let Ok(guard) = semaphore.try_acquire(thread_rng().gen_range(0, 10)) { on_guard(Ok(guard)); } } if thread_rng().gen_bool(0.0001) { poisoned.store(true, Relaxed); semaphore.poison(); } } } }).unwrap()).collect::<Vec<_>>().into_iter().for_each(|x| x.join().unwrap()); }
ze, TestFuture>::new(); let mut rng = XorShiftRng::seed_from_u64(954360855); for _ in 0..100000 { if rng.gen_bool(0.1) && futures.len() < 5 { let amount = rng.gen_range(0, 10); let mut fut = TestFuture::new(&semaphore, amount); if let Some(guard) = fut.poll() { guard.unwrap().forget(); available = available.checked_sub(amount).unwrap(); } else { futures.insert(time, fut); } time += 1; } else if rng.gen_bool(0.1) { let mut blocked = false; let mut ready = vec![]; for (time, fut) in futures.iter_mut() { if rng.gen_bool(0.5) { if let Some(guard) = fut.poll_if_woken() { assert!(!blocked); guard.unwrap().forget(); available = available.checked_sub(fut.amount).unwrap(); ready.push(*time); } else { blocked = true; } } } for time in ready { futures.remove(&time); } } else if rng.gen_bool(0.1) && available < 30 { let amount = rng.gen_range(0, 10); available = available.checked_add(amount).unwrap(); semaphore.release(amount); } } }
function_block-function_prefixed
[ { "content": "struct SemMutex(Semaphore, UnsafeCell<usize>);\n\n\n\nunsafe impl Send for SemMutex {}\n\n\n\nunsafe impl Sync for SemMutex {}\n\n\n\nimpl Default for SemMutex {\n\n fn default() -> Self {\n\n SemMutex(Semaphore::new(1), UnsafeCell::new(0))\n\n }\n\n}\n\n\n\nimpl AtomicCounter for Sem...
Rust
src/indexer/mod.rs
sinhrks/brassfibre
86028eaf7271b2cd560ef064969ef1cbf47396d4
use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; use std::iter::FromIterator; use std::slice; use std::vec; use nullvec::prelude::dev::algos::Indexing; use traits::{Slicer, IndexerIndex, Append}; mod convert; mod formatting; mod indexing; mod ops; mod sort; #[derive(Clone)] pub struct Indexer<U: Clone + Hash> { pub values: Vec<U>, htable: RefCell<HashMap<U, usize>>, } impl<U> Indexer<U> where U: Clone + Eq + Hash, { pub fn from_len(len: usize) -> Indexer<usize> { (0..len).collect() } pub fn new(values: Vec<U>) -> Self { Indexer { values: values, htable: RefCell::new(HashMap::new()), } } } impl<U> Slicer for Indexer<U> where U: Clone + Eq + Hash, { type Scalar = U; fn len(&self) -> usize { self.values.len() } fn iloc(&self, location: &usize) -> Self::Scalar { self.values[*location].clone() } unsafe fn iloc_unchecked(&self, location: &usize) -> Self::Scalar { self.values.get_unchecked(*location).clone() } fn ilocs(&self, locations: &[usize]) -> Self { let new_values = Indexing::reindex(&self.values, locations); Indexer::new(new_values) } unsafe fn ilocs_unchecked(&self, locations: &[usize]) -> Self { let new_values = Indexing::reindex_unchecked(&self.values, locations); Indexer::new(new_values) } fn ilocs_forced(&self, _locations: &[usize]) -> Self { unimplemented!() } fn blocs(&self, flags: &[bool]) -> Self { let new_values: Vec<U> = Indexing::blocs(&self.values, flags); Indexer::new(new_values) } } impl<U> IndexerIndex for Indexer<U> where U: Clone + Eq + Hash, { type Key = U; fn contains(&self, label: &U) -> bool { self.init_state(); self.htable.borrow().contains_key(label) } fn push(&mut self, label: U) { let loc = self.len(); let mut htable = self.htable.borrow_mut(); match htable.entry(label.clone()) { Entry::Occupied(_) => panic!("duplicates are not allowed"), Entry::Vacant(e) => e.insert(loc), }; self.values.push(label); } fn get_loc(&self, label: &U) -> usize { self.init_state(); *self.htable.borrow().get(label).unwrap() } fn get_locs(&self, labels: &[U]) -> Vec<usize> { labels.iter().map(|label| self.get_loc(label)).collect() } fn init_state(&self) { let mut htable = self.htable.borrow_mut(); if htable.len() != 0 { return; } for (loc, label) in self.values.iter().enumerate() { match htable.entry(label.clone()) { Entry::Occupied(_) => panic!("duplicates are not allowed"), Entry::Vacant(e) => e.insert(loc), }; } } } impl<'a, T> Append<'a> for Indexer<T> where T: Clone + Eq + Hash, { fn append(&self, other: &Self) -> Self { let mut new_values: Vec<T> = self.values.clone(); new_values.append(&mut other.values.clone()); Indexer::new(new_values) } } impl<U> PartialEq for Indexer<U> where U: Clone + Eq + Hash, { fn eq(&self, other: &Indexer<U>) -> bool { self.values == other.values } } impl<U> IntoIterator for Indexer<U> where U: Clone + Eq + Hash, { type Item = U; type IntoIter = vec::IntoIter<U>; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() } } impl<U> Indexer<U> where U: Clone + Eq + Hash, { pub fn iter(&self) -> slice::Iter<U> { self.values.iter() } } impl<U> FromIterator<U> for Indexer<U> where U: Clone + Eq + Hash, { fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = U>, { let values: Vec<U> = iter.into_iter().collect(); Indexer::new(values) } }
use std::cell::RefCell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; use std::iter::FromIterator; use std::slice; use std::vec; use nullvec::prelude::dev::algos::Indexing; use traits::{Slicer, IndexerIndex, Append}; mod convert; mod formatting; mod indexing; mod ops; mod sort; #[derive(Clone)] pub struct Indexer<U: Clone + Hash> { pub values: Vec<U>, htable: RefCell<HashMap<U, usize>>, } impl<U> Indexer<U> where U: Clone + Eq + Hash, { pub fn from_len(len: usize) -> Indexer<usize> { (0..len).collect() } pub fn new(values: Vec<U>) -> Self { Indexer { values: values, htable: RefCell::new(HashMap::new()), } } } impl<U> Slicer for Indexer<U> where U: Clone + Eq + Hash, { type Scalar = U; fn len(&self) -> usize { self.values.len() } fn iloc(&self, location: &usize) -> Self::Scalar { self.values[*location].clone() } unsafe fn iloc_unchecked(&self, location: &usize) -> Self::Scalar { self.values.get_unchecked(*location).clone() } fn ilocs(&self, locations: &[usize]) -> Self { let new_values = Indexing::reindex(&self.values, locations); Indexer::new(new_values) } unsafe fn ilocs_unchecked(&self, locations: &[usize]) -> Self { let new_values = Indexing::reindex_unchecked(&self.values, locations); Indexer::new(new_values) } fn ilocs_forced(&self, _locations: &[usize]) -> Self { unimplemented!() } fn blocs(&self, flags: &[bool]) -> Self { let new_values: Vec<U> = Indexing::blocs(&self.values, flags); Indexer::new(new_values) } } impl<U> IndexerIndex for Indexer<U> where U: Clone + Eq + Hash, { type Key = U; fn contains(&self, label: &U) -> bool { self.init_state(); self.htable.borrow().contains_key(label) } fn push(&mut self, label: U) { let loc = self.len(); let mut htable = self.htable.borrow_mut(); match htable.entry(label.clone()) { Entry::Occupied(_) => panic!("duplicates are not allowed"), Entry::Vacant(e) => e.insert(loc), }; self.values.push(label); } fn get_loc(&self, label: &U) -> usize { self.init_state(); *self.htable.borrow().get(label).unwrap() } fn get_locs(&self, labels: &[U]) -> Vec<usize> { labels.iter().map(|label| self.get_loc(label)).collect() } fn init_state(&self) { let mut htable = self.htable.borrow_mut(); if htable.len() != 0 { return; } for (loc, label) in self.values.iter().enumerate() { match htable.entry(label.clone()) { Entry::Occupied(_) => panic!("duplicates are not allowed"), Entry::Vacant(e) => e.insert(loc), }; } } } impl<'a, T> Append<'a> for Indexer<T> where T: Clone + Eq + Hash, { fn append(&self, other: &Self) -> Self { let mut new_values: Vec<T> = self.values.clone(); new_values.append(&mut other.values.clone()); Indexer::new(new_values) } } impl<U> PartialEq for Indexer<U> where U: Clone + Eq + Hash, { fn eq(&self, other: &Indexer<U>) -> bool { self.values == other.values } } impl<U> IntoIterator for Indexer<U> where U: Clone + Eq + Hash, { type Item = U; type IntoIter = vec::IntoIter<U>; fn into_iter(self) -> Self::IntoIter { self.values.into_iter() } } impl<U> Indexer<U> where U: Clone + Eq + Hash, { pub fn iter(&self) -> slice::Iter<U> { self.values.iter() } } impl<U> FromIterator<U> for Indexer<U> where U: Clone + Eq + Hash, {
}
fn from_iter<T>(iter: T) -> Self where T: IntoIterator<Item = U>, { let values: Vec<U> = iter.into_iter().collect(); Indexer::new(values) }
function_block-full_function
[ { "content": "/// Indexing methods for Indexer\n\npub trait IndexerIndex: Slicer {\n\n type Key;\n\n\n\n fn contains(&self, label: &Self::Key) -> bool;\n\n fn push(&mut self, label: Self::Key);\n\n fn get_loc(&self, label: &Self::Key) -> usize;\n\n fn get_locs(&self, labels: &[Self::Key]) -> Vec<...
Rust
src/overlay.rs
penumbra-zone/jellyfish-merkle
0f216e2dcd3219c58f1bc4a584c373416cbef5cd
use std::collections::HashMap; use anyhow::Result; use tracing::instrument; use crate::{ storage::{TreeReader, TreeWriter}, JellyfishMerkleTree, KeyHash, MissingRootError, OwnedValue, RootHash, Version, }; pub struct WriteOverlay<R> { reader: R, overlay: HashMap<KeyHash, OwnedValue>, version: Version, } impl<R> WriteOverlay<R> { pub const PRE_GENESIS_VERSION: Version = u64::MAX; } impl<R> WriteOverlay<R> where R: TreeReader + Sync, { pub fn new(reader: R, version: Version) -> Self { Self { reader, version, overlay: Default::default(), } } fn tree(&self) -> JellyfishMerkleTree<'_, R> { JellyfishMerkleTree::new(&self.reader) } #[instrument(name = "WriteOverlay::get", skip(self, key))] pub async fn get(&self, key: KeyHash) -> Result<Option<OwnedValue>> { if let Some(value) = self.overlay.get(&key) { tracing::trace!(?key, value = ?hex::encode(&value), "read from cache"); Ok(Some(value.clone())) } else { match self.tree().get(key, self.version).await { Ok(Some(value)) => { tracing::trace!(version = ?self.version, ?key, value = ?hex::encode(&value), "read from tree"); Ok(Some(value)) } Ok(None) => { tracing::trace!(version = ?self.version, ?key, "key not found in tree"); Ok(None) } Err(e) if e.downcast_ref::<MissingRootError>().is_some() => { tracing::trace!(version = ?self.version, "no data available at this version"); Ok(None) } Err(e) => Err(e), } } } #[instrument(name = "WriteOverlay::get_with_proof", skip(self, key))] pub async fn get_with_proof( &self, key: Vec<u8>, ) -> Result<(OwnedValue, ics23::ExistenceProof)> { if self.overlay.contains_key(&key.clone().into()) { return Err(anyhow::anyhow!("key is not yet committed to tree")); } let proof = self.tree().get_with_ics23_proof(key, self.version).await?; Ok((proof.value.clone(), proof)) } #[instrument(name = "WriteOverlay::put", skip(self, key, value))] pub fn put(&mut self, key: KeyHash, value: OwnedValue) { tracing::trace!(?key, value = ?hex::encode(&value)); *self.overlay.entry(key).or_default() = value; } #[instrument(name = "WriteOverlay::commit", skip(self, writer))] pub async fn commit<W>(&mut self, mut writer: W) -> Result<(RootHash, Version)> where W: TreeWriter + Sync, { let overlay = std::mem::replace(&mut self.overlay, Default::default()); let new_version = self.version.wrapping_add(1); tracing::trace!(old_version = ?self.version, new_version, ?overlay); let (root_hash, batch) = self .tree() .put_value_set(overlay.into_iter().collect(), new_version) .await?; writer.write_node_batch(&batch.node_batch).await?; tracing::trace!(?root_hash, "wrote node batch to backing store"); self.version = new_version; Ok((root_hash, new_version)) } }
use std::collections::HashMap; use anyhow::Result; use tracing::instrument; use crate::{ storage::{TreeReader, TreeWriter}, JellyfishMerkleTree, KeyHash, MissingRootError, OwnedValue, RootHash, Version, }; pub struct WriteOverlay<R> { reader: R, overlay: HashMap<KeyHash, OwnedValue>, version: Version, } impl<R> WriteOverlay<R> { pub const PRE_GENESIS_VERSION: Version = u64::MAX; } impl<R> WriteOverlay<R> where R: TreeReader + Sync, { pub fn new(reader: R, version: Version) -> Self { Self { reader, version, overlay: Default::default(), } } fn tree(&self) -> JellyfishMerkleTree<'_, R> { JellyfishMerkleTree::new(&self.reader) } #[instrument(name = "WriteOverlay::get", skip(self, key))] pub async fn get(&self, key: KeyHash) -> Result<Option<OwnedValue>> { if let Some(value) = self.overlay.get(&key) { tracing::trace!(?key, value = ?hex::encode(&value), "read from cache"); Ok(Some(value.clone())) } else {
} } #[instrument(name = "WriteOverlay::get_with_proof", skip(self, key))] pub async fn get_with_proof( &self, key: Vec<u8>, ) -> Result<(OwnedValue, ics23::ExistenceProof)> { if self.overlay.contains_key(&key.clone().into()) { return Err(anyhow::anyhow!("key is not yet committed to tree")); } let proof = self.tree().get_with_ics23_proof(key, self.version).await?; Ok((proof.value.clone(), proof)) } #[instrument(name = "WriteOverlay::put", skip(self, key, value))] pub fn put(&mut self, key: KeyHash, value: OwnedValue) { tracing::trace!(?key, value = ?hex::encode(&value)); *self.overlay.entry(key).or_default() = value; } #[instrument(name = "WriteOverlay::commit", skip(self, writer))] pub async fn commit<W>(&mut self, mut writer: W) -> Result<(RootHash, Version)> where W: TreeWriter + Sync, { let overlay = std::mem::replace(&mut self.overlay, Default::default()); let new_version = self.version.wrapping_add(1); tracing::trace!(old_version = ?self.version, new_version, ?overlay); let (root_hash, batch) = self .tree() .put_value_set(overlay.into_iter().collect(), new_version) .await?; writer.write_node_batch(&batch.node_batch).await?; tracing::trace!(?root_hash, "wrote node batch to backing store"); self.version = new_version; Ok((root_hash, new_version)) } }
match self.tree().get(key, self.version).await { Ok(Some(value)) => { tracing::trace!(version = ?self.version, ?key, value = ?hex::encode(&value), "read from tree"); Ok(Some(value)) } Ok(None) => { tracing::trace!(version = ?self.version, ?key, "key not found in tree"); Ok(None) } Err(e) if e.downcast_ref::<MissingRootError>().is_some() => { tracing::trace!(version = ?self.version, "no data available at this version"); Ok(None) } Err(e) => Err(e), }
if_condition
[ { "content": "/// Computes the key immediately after `key`.\n\npub fn plus_one(key: KeyHash) -> KeyHash {\n\n assert_ne!(key, KeyHash([0xff; 32]));\n\n\n\n let mut buf = key.0;\n\n for i in (0..32).rev() {\n\n if buf[i] == 255 {\n\n buf[i] = 0;\n\n } else {\n\n buf[i...
Rust
engine/src/types.rs
ivankabestwill/wirefilter
294292f53db18a5a3261118e93fad30bd9498b09
use lex::{expect, skip_space, Lex, LexResult, LexWith}; use rhs_types::{Bytes, IpRange, UninhabitedBool}; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, fmt::{self, Debug, Formatter}, net::IpAddr, ops::RangeInclusive, }; use strict_partial_ord::StrictPartialOrd; fn lex_rhs_values<'i, T: Lex<'i>>(input: &'i str) -> LexResult<'i, Vec<T>> { let mut input = expect(input, "{")?; let mut res = Vec::new(); loop { input = skip_space(input); if let Ok(rest) = expect(input, "}") { input = rest; return Ok((res, input)); } else { let (item, rest) = T::lex(input)?; res.push(item); input = rest; } } } macro_rules! declare_types { ($(# $attrs:tt)* enum $name:ident $(<$lt:tt>)* { $($(# $vattrs:tt)* $variant:ident ( $ty:ty ) , )* }) => { $(# $attrs)* #[repr(u8)] pub enum $name $(<$lt>)* { $($(# $vattrs)* $variant($ty),)* } impl $(<$lt>)* GetType for $name $(<$lt>)* { fn get_type(&self) -> Type { match self { $($name::$variant(_) => Type::$variant,)* } } } impl $(<$lt>)* Debug for $name $(<$lt>)* { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { $($name::$variant(inner) => Debug::fmt(inner, f),)* } } } }; ($($(# $attrs:tt)* $name:ident ( $lhs_ty:ty | $rhs_ty:ty | $multi_rhs_ty:ty ) , )*) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[repr(u8)] pub enum Type { $($(# $attrs)* $name,)* } pub trait GetType { fn get_type(&self) -> Type; } impl GetType for Type { fn get_type(&self) -> Type { *self } } declare_types! { #[derive(PartialEq, Eq, Clone, Deserialize)] #[serde(untagged)] enum LhsValue<'a> { $($(# $attrs)* $name($lhs_ty),)* } } $(impl<'a> From<$lhs_ty> for LhsValue<'a> { fn from(value: $lhs_ty) -> Self { LhsValue::$name(value) } })* declare_types! { #[derive(PartialEq, Eq, Clone, Serialize)] #[serde(untagged)] enum RhsValue { $($(# $attrs)* $name($rhs_ty),)* } } impl<'i> LexWith<'i, Type> for RhsValue { fn lex_with(input: &str, ty: Type) -> LexResult<'_, Self> { Ok(match ty { $(Type::$name => { let (value, input) = <$rhs_ty>::lex(input)?; (RhsValue::$name(value), input) })* }) } } impl<'a> PartialOrd<RhsValue> for LhsValue<'a> { fn partial_cmp(&self, other: &RhsValue) -> Option<Ordering> { match (self, other) { $((LhsValue::$name(lhs), RhsValue::$name(rhs)) => { lhs.strict_partial_cmp(rhs) },)* _ => None, } } } impl<'a> StrictPartialOrd<RhsValue> for LhsValue<'a> {} impl<'a> PartialEq<RhsValue> for LhsValue<'a> { fn eq(&self, other: &RhsValue) -> bool { self.strict_partial_cmp(other) == Some(Ordering::Equal) } } declare_types! { #[derive(PartialEq, Eq, Clone, Serialize)] #[serde(untagged)] enum RhsValues { $($(# $attrs)* $name(Vec<$multi_rhs_ty>),)* } } impl<'i> LexWith<'i, Type> for RhsValues { fn lex_with(input: &str, ty: Type) -> LexResult<'_, Self> { Ok(match ty { $(Type::$name => { let (value, input) = lex_rhs_values(input)?; (RhsValues::$name(value), input) })* }) } } }; } impl<'a> From<&'a str> for LhsValue<'a> { fn from(s: &'a str) -> Self { s.as_bytes().into() } } declare_types!( Ip(IpAddr | IpAddr | IpRange), Bytes(&'a [u8] | Bytes | Bytes), Int(i32 | i32 | RangeInclusive<i32>), Bool(bool | UninhabitedBool | UninhabitedBool), ); #[test] fn test_lhs_value_deserialize() { use std::str::FromStr; let ipv4: LhsValue<'_> = serde_json::from_str("\"127.0.0.1\"").unwrap(); assert_eq!(ipv4, LhsValue::Ip(IpAddr::from_str("127.0.0.1").unwrap())); let ipv6: LhsValue<'_> = serde_json::from_str("\"::1\"").unwrap(); assert_eq!(ipv6, LhsValue::Ip(IpAddr::from_str("::1").unwrap())); let bytes: LhsValue<'_> = serde_json::from_str("\"a JSON string with unicode ❤\"").unwrap(); assert_eq!( bytes, LhsValue::Bytes(b"a JSON string with unicode \xE2\x9D\xA4") ); assert!( serde_json::from_str::<LhsValue<'_>>("\"a JSON string with escaped-unicode \\u2764\"") .is_err(), "LhsValue can only handle borrowed bytes" ); let bytes: LhsValue<'_> = serde_json::from_str("\"1337\"").unwrap(); assert_eq!(bytes, LhsValue::Bytes(b"1337")); let integer: LhsValue<'_> = serde_json::from_str("1337").unwrap(); assert_eq!(integer, LhsValue::Int(1337)); let b: LhsValue<'_> = serde_json::from_str("false").unwrap(); assert_eq!(b, LhsValue::Bool(false)); }
use lex::{expect, skip_space, Lex, LexResult, LexWith}; use rhs_types::{Bytes, IpRange, UninhabitedBool}; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, fmt::{self, Debug, Formatter}, net::IpAddr, ops::RangeInclusive, }; use strict_partial_ord::StrictPartialOrd; fn lex_rhs_values<'i, T: Lex<'i>>(input: &'i str) -> LexResult<'i, Vec<T>> { let mut input = expect(input, "{")?; let mut res = Vec::new(); loop { input = skip_space(input);
} } macro_rules! declare_types { ($(# $attrs:tt)* enum $name:ident $(<$lt:tt>)* { $($(# $vattrs:tt)* $variant:ident ( $ty:ty ) , )* }) => { $(# $attrs)* #[repr(u8)] pub enum $name $(<$lt>)* { $($(# $vattrs)* $variant($ty),)* } impl $(<$lt>)* GetType for $name $(<$lt>)* { fn get_type(&self) -> Type { match self { $($name::$variant(_) => Type::$variant,)* } } } impl $(<$lt>)* Debug for $name $(<$lt>)* { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { $($name::$variant(inner) => Debug::fmt(inner, f),)* } } } }; ($($(# $attrs:tt)* $name:ident ( $lhs_ty:ty | $rhs_ty:ty | $multi_rhs_ty:ty ) , )*) => { #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[repr(u8)] pub enum Type { $($(# $attrs)* $name,)* } pub trait GetType { fn get_type(&self) -> Type; } impl GetType for Type { fn get_type(&self) -> Type { *self } } declare_types! { #[derive(PartialEq, Eq, Clone, Deserialize)] #[serde(untagged)] enum LhsValue<'a> { $($(# $attrs)* $name($lhs_ty),)* } } $(impl<'a> From<$lhs_ty> for LhsValue<'a> { fn from(value: $lhs_ty) -> Self { LhsValue::$name(value) } })* declare_types! { #[derive(PartialEq, Eq, Clone, Serialize)] #[serde(untagged)] enum RhsValue { $($(# $attrs)* $name($rhs_ty),)* } } impl<'i> LexWith<'i, Type> for RhsValue { fn lex_with(input: &str, ty: Type) -> LexResult<'_, Self> { Ok(match ty { $(Type::$name => { let (value, input) = <$rhs_ty>::lex(input)?; (RhsValue::$name(value), input) })* }) } } impl<'a> PartialOrd<RhsValue> for LhsValue<'a> { fn partial_cmp(&self, other: &RhsValue) -> Option<Ordering> { match (self, other) { $((LhsValue::$name(lhs), RhsValue::$name(rhs)) => { lhs.strict_partial_cmp(rhs) },)* _ => None, } } } impl<'a> StrictPartialOrd<RhsValue> for LhsValue<'a> {} impl<'a> PartialEq<RhsValue> for LhsValue<'a> { fn eq(&self, other: &RhsValue) -> bool { self.strict_partial_cmp(other) == Some(Ordering::Equal) } } declare_types! { #[derive(PartialEq, Eq, Clone, Serialize)] #[serde(untagged)] enum RhsValues { $($(# $attrs)* $name(Vec<$multi_rhs_ty>),)* } } impl<'i> LexWith<'i, Type> for RhsValues { fn lex_with(input: &str, ty: Type) -> LexResult<'_, Self> { Ok(match ty { $(Type::$name => { let (value, input) = lex_rhs_values(input)?; (RhsValues::$name(value), input) })* }) } } }; } impl<'a> From<&'a str> for LhsValue<'a> { fn from(s: &'a str) -> Self { s.as_bytes().into() } } declare_types!( Ip(IpAddr | IpAddr | IpRange), Bytes(&'a [u8] | Bytes | Bytes), Int(i32 | i32 | RangeInclusive<i32>), Bool(bool | UninhabitedBool | UninhabitedBool), ); #[test] fn test_lhs_value_deserialize() { use std::str::FromStr; let ipv4: LhsValue<'_> = serde_json::from_str("\"127.0.0.1\"").unwrap(); assert_eq!(ipv4, LhsValue::Ip(IpAddr::from_str("127.0.0.1").unwrap())); let ipv6: LhsValue<'_> = serde_json::from_str("\"::1\"").unwrap(); assert_eq!(ipv6, LhsValue::Ip(IpAddr::from_str("::1").unwrap())); let bytes: LhsValue<'_> = serde_json::from_str("\"a JSON string with unicode ❤\"").unwrap(); assert_eq!( bytes, LhsValue::Bytes(b"a JSON string with unicode \xE2\x9D\xA4") ); assert!( serde_json::from_str::<LhsValue<'_>>("\"a JSON string with escaped-unicode \\u2764\"") .is_err(), "LhsValue can only handle borrowed bytes" ); let bytes: LhsValue<'_> = serde_json::from_str("\"1337\"").unwrap(); assert_eq!(bytes, LhsValue::Bytes(b"1337")); let integer: LhsValue<'_> = serde_json::from_str("1337").unwrap(); assert_eq!(integer, LhsValue::Int(1337)); let b: LhsValue<'_> = serde_json::from_str("false").unwrap(); assert_eq!(b, LhsValue::Bool(false)); }
if let Ok(rest) = expect(input, "}") { input = rest; return Ok((res, input)); } else { let (item, rest) = T::lex(input)?; res.push(item); input = rest; }
if_condition
[ { "content": "fn lex_digits(input: &str) -> LexResult<'_, &str> {\n\n // Lex any supported digits (up to radix 16) for better error locations.\n\n take_while(input, \"digit\", |c| c.is_digit(16))\n\n}\n\n\n", "file_path": "engine/src/rhs_types/int.rs", "rank": 0, "score": 184976.2941145299 }...
Rust
src/main.rs
jmccrae/simple-rust-web
88ac2fc0c0d5ca91c05d8b3543a9cc00a0e43bcd
extern crate clap; extern crate iron; extern crate handlebars; extern crate params; extern crate percent_encoding; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod renderer; mod templates; use clap::{Arg, App}; use handlebars::Handlebars; use iron::middleware::Handler; use iron::prelude::*; use params::Params; use percent_encoding::percent_decode; use renderer::*; use serde::Serialize; use templates::*; use std::collections::HashMap; use std::str::from_utf8; struct Server { hbars : Handlebars, renderers : Vec<(&'static str, Box<Renderer>)> } impl Server { fn new() -> Server { let mut hb = Handlebars::new(); hb.register_template_string("layout", from_utf8(LAYOUT).expect("Layout is not valid utf-8")). expect("Layout is not valid template"); for &(name, template) in TEMPLATES.iter() { hb.register_template_string(name, from_utf8(template).expect( &format!("{} is not valid UTF-8", name))). expect(&format!("{} is not a valid template", name)); } Server { hbars : hb, renderers : Vec::new() } } #[allow(dead_code)] fn add_static(&mut self, path : &'static str, name : &str, content : &'static [u8]) { self.renderers.push((path, Box::new(StaticRenderer::new(name.to_string(), content)))) } #[allow(dead_code)] fn add_renderer(&mut self, path: &'static str, renderer : Box<Renderer>) { self.renderers.push((path, renderer)); } #[allow(dead_code)] fn add_translator<A>(&mut self, path: &'static str, name: &str, template : &'static str, translator : Box<Translator<A>>) where A : Serialize + 'static { self.renderers.push((path, Box::new(TranslatorRenderer(name.to_string(), template.to_string(), translator)))) } } impl Handler for Server { fn handle(&self, req : &mut Request) -> IronResult<Response> { for &(ref path, ref renderer) in self.renderers.iter() { match match_path(path, &req.url.path()) { Some(args) => { let depth = req.url.path().len(); let params = req.get_ref::<Params>().unwrap(); return renderer.render(args, params, &self.hbars, depth); }, None => {} } } return render_error(&self.hbars, from_utf8(templates::NOT_FOUND). expect("Invalid UTF-8 in 404").to_string(), iron::status::NotFound); } } fn match_path(pattern : &str, path : &Vec<&str>) -> Option<HashMap<String,String>> { let mut captures = HashMap::new(); let p : Vec<&str> = pattern.split("/").collect(); if p.len() != path.len() { None } else { for (p1,p2) in p.iter().zip(path.iter()) { if p1.starts_with(":") { captures.insert(p1[1..].to_string(), urldecode(p2)); } else if p1 != p2 { return None; } } Some(captures) } } fn urldecode(s : &str) -> String { percent_decode(s.as_bytes()).decode_utf8().unwrap().into_owned() } fn main() { let matches = App::new(APP_TITLE). version(VERSION). author(AUTHOR). about(ABOUT). arg(Arg::with_name("port") .short("p") .long("port") .value_name("PORT") .help("The port to run the server on") .takes_value(true)). get_matches(); let port : u16 = matches.value_of("port").and_then(|pstr| { pstr.parse::<u16>().ok() }).unwrap_or(3000); let mut server = Server::new(); init(&mut server); let iron = Iron::new(server); iron.http(("localhost",port)).unwrap(); } static APP_TITLE : &'static str = "My App"; static VERSION : &'static str = "0.1"; static AUTHOR : &'static str = "John McCrae <john@mccr.ae>"; static ABOUT : &'static str = "Simple framework for making Rust Webapps"; struct TestTranslator; impl Translator<String> for TestTranslator { fn convert(&self, v : HashMap<String, String>) -> Result<String,TranslatorError> { Ok(v["test"].clone()) } } fn init(server : &mut Server) { server.add_static("", "Index", INDEX); server.add_translator("foo", "bar", "template", Box::new(TestTranslator)); }
extern crate clap; extern crate iron; extern crate handlebars; extern crate params; extern crate percent_encoding; #[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; mod renderer; mod templates; use clap::{Arg, App}; use handlebars::Handlebars; use iron::middleware::Handler; use iron::prelude::*; use params::Params; use percent_encoding::percent_decode; use renderer::*; use serde::Serialize; use templates::*; use std::collections::HashMap; use std::str::from_utf8; struct Server { hbars : Handlebars, renderers : Vec<(&'static str, Box<Renderer>)> } impl Server { fn new() -> Server { let mut hb = Handlebars::new(); hb.register_template_string("layout", from_utf8(LAYOUT).expect("Layout is not valid utf-8")). expect("Layout is not valid template"); for &(name, template) in TEMPLATES.iter() { hb.register_template_string(name, from_utf8(template).expect( &format!("{} is not valid UTF-8", name))). expect(&format!("{} is not a valid template", name)); } Server { hbars : hb, renderers : Vec::new() } } #[allow(dead_code)] fn add_static(&mut self, path : &'static str, name : &str, content : &'static [u8]) { self.renderers.push((path, Box::new(StaticRenderer::new(name.to_string(), content)))) } #[allow(dead_code)] fn add_renderer(&mut self, path: &'static str, renderer : Box<Renderer>) { self.renderers.push((path, renderer)); } #[allow(dead_code)] fn add_translator<A>(&mut self, path: &'static str, name: &str, template : &'static str, translator : Box<Translator<A>>) where A : Serialize + 'static { self.renderers.push((path, Box::new(TranslatorRenderer(name.to_string(), template.to_string(), translator)))) } } impl Handler for Server { fn handle(&self, req : &mut Request) -> IronResult<Response> { for &(ref path, ref renderer) in self.renderers.iter() { match match_path(path, &req.url.path()) { Some(args) => { let depth = req.url.path().len(); let params = req.get_ref::<Params>().unwrap(); return renderer.render(args, params, &self.hbars, depth); }, None => {} } } return render_error(&self.hbars, from_utf8(templates::NOT_FOUND). expect("Invalid UTF-8 in 404").to_string(), iron::status::NotFound); } } fn match_path(pattern : &str, path : &Vec<&str>) -> Option<HashMap<String,String>> { let mut captures = HashMap::new(); let p : Vec<&str> = pattern.split("/").collect(); if p.len() != path.len() { None } else { for (p1,p2) in p.iter().zip(path.iter()) { if p1.starts_with(":") { captures.insert(p1[1..].to_string(), urldecode(p2)); } else if p1 != p2 { return None; } } Some(captures) } } fn urldecode(s : &str) -> String { percent_decode(s.as_bytes()).decode_utf8().unwrap().into_owned() } fn main() { let matches = App::new(APP_TITLE). version(VERSION). author(AUTHOR). about(ABOUT). arg(Arg::with_name("port") .short("p") .long("port") .value_name("PORT") .help("The port to run the server on") .takes_value(true)). get_matches(); let port : u16 = matches.value_of("port").and_then(|pstr| { pstr.parse::<u16>().ok() }).unwrap_or(3000);
static APP_TITLE : &'static str = "My App"; static VERSION : &'static str = "0.1"; static AUTHOR : &'static str = "John McCrae <john@mccr.ae>"; static ABOUT : &'static str = "Simple framework for making Rust Webapps"; struct TestTranslator; impl Translator<String> for TestTranslator { fn convert(&self, v : HashMap<String, String>) -> Result<String,TranslatorError> { Ok(v["test"].clone()) } } fn init(server : &mut Server) { server.add_static("", "Index", INDEX); server.add_translator("foo", "bar", "template", Box::new(TestTranslator)); }
let mut server = Server::new(); init(&mut server); let iron = Iron::new(server); iron.http(("localhost",port)).unwrap(); }
function_block-function_prefix_line
[ { "content": "/// Render using `layout.hbs`\n\npub fn render_ok(hbars : &Handlebars, title : String, body : String) -> IronResult<Response> {\n\n Ok(Response::with(\n\n (iron::status::Ok,\n\n Header(ContentType::html()),\n\n hbars.render(\"layout\", &LayoutPage {\n\n ...