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
tests/rsa_tests.rs
NikVolf/ring
0c0f7c47112f9ff3e1b8d8d4427d8246fcdc0794
#![forbid( anonymous_parameters, box_pointers, legacy_directory_ownership, missing_copy_implementations, missing_debug_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences, warnings, )] extern crate ring; extern crate untrusted; use ring::{der, error, signature, test}; #[cfg(feature = "rsa_signing")] use ring::rand; #[cfg(feature = "rsa_signing")] #[test] fn rsa_from_pkcs8_test() { test::from_file("tests/rsa_from_pkcs8_tests.txt", |section, test_case| { assert_eq!(section, ""); let input = test_case.consume_bytes("Input"); let input = untrusted::Input::from(&input); let error = test_case.consume_optional_string("Error"); assert_eq!(signature::RSAKeyPair::from_pkcs8(input).is_ok(), error.is_none()); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_signature_rsa_pkcs1_sign() { let rng = rand::SystemRandom::new(); test::from_file("tests/rsa_pkcs1_sign_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PKCS1_SHA256, "SHA384" => &signature::RSA_PKCS1_SHA384, "SHA512" => &signature::RSA_PKCS1_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let private_key = test_case.consume_bytes("Key"); let msg = test_case.consume_bytes("Msg"); let expected = test_case.consume_bytes("Sig"); let result = test_case.consume_string("Result"); let private_key = untrusted::Input::from(&private_key); let key_pair = signature::RSAKeyPair::from_der(private_key); if result == "Fail-Invalid-Key" { assert!(key_pair.is_err()); return Ok(()); } let key_pair = key_pair.unwrap(); let key_pair = std::sync::Arc::new(key_pair); let mut signing_state = signature::RSASigningState::new(key_pair).unwrap(); let mut actual = vec![0u8; signing_state.key_pair().public_modulus_len()]; signing_state.sign(alg, &rng, &msg, actual.as_mut_slice()).unwrap(); assert_eq!(actual.as_slice() == &expected[..], result == "Pass"); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_signature_rsa_pss_sign() { struct DeterministicSalt<'a> { salt: &'a [u8], rng: &'a rand::SecureRandom } impl<'a> rand::SecureRandom for DeterministicSalt<'a> { fn fill(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> { let dest_len = dest.len(); if dest_len != self.salt.len() { self.rng.fill(dest)?; } else { dest.copy_from_slice(&self.salt); } Ok(()) } } let rng = rand::SystemRandom::new(); test::from_file("tests/rsa_pss_sign_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PSS_SHA256, "SHA384" => &signature::RSA_PSS_SHA384, "SHA512" => &signature::RSA_PSS_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let result = test_case.consume_string("Result"); let private_key = test_case.consume_bytes("Key"); let private_key = untrusted::Input::from(&private_key); let key_pair = signature::RSAKeyPair::from_der(private_key); if key_pair.is_err() && result == "Fail-Invalid-Key" { return Ok(()); } let key_pair = key_pair.unwrap(); let key_pair = std::sync::Arc::new(key_pair); let msg = test_case.consume_bytes("Msg"); let salt = test_case.consume_bytes("Salt"); let expected = test_case.consume_bytes("Sig"); let new_rng = DeterministicSalt { salt: &salt, rng: &rng }; let mut signing_state = signature::RSASigningState::new(key_pair).unwrap(); let mut actual = vec![0u8; signing_state.key_pair().public_modulus_len()]; signing_state.sign(alg, &new_rng, &msg, actual.as_mut_slice())?; assert_eq!(actual.as_slice() == &expected[..], result == "Pass"); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_rsa_key_pair_traits() { test::compile_time_assert_send::<signature::RSAKeyPair>(); test::compile_time_assert_sync::<signature::RSAKeyPair>(); test::compile_time_assert_debug::<signature::RSAKeyPair>(); test::compile_time_assert_send::<signature::RSASigningState>(); } #[test] fn test_signature_rsa_pkcs1_verify() { test::from_file("tests/rsa_pkcs1_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA1" => &signature::RSA_PKCS1_2048_8192_SHA1, "SHA256" => &signature::RSA_PKCS1_2048_8192_SHA256, "SHA384" => &signature::RSA_PKCS1_2048_8192_SHA384, "SHA512" => &signature::RSA_PKCS1_2048_8192_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let public_key = test_case.consume_bytes("Key"); let public_key = untrusted::Input::from(&public_key); assert!(public_key.read_all(error::Unspecified, |input| { der::nested(input, der::Tag::Sequence, error::Unspecified, |input| { let _ = der::positive_integer(input)?; let _ = der::positive_integer(input)?; Ok(()) }) }).is_ok()); let msg = test_case.consume_bytes("Msg"); let msg = untrusted::Input::from(&msg); let sig = test_case.consume_bytes("Sig"); let sig = untrusted::Input::from(&sig); let expected_result = test_case.consume_string("Result"); let actual_result = signature::verify(alg, public_key, msg, sig); assert_eq!(actual_result.is_ok(), expected_result == "P"); Ok(()) }); } #[test] fn test_signature_rsa_pss_verify() { test::from_file("tests/rsa_pss_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PSS_2048_8192_SHA256, "SHA384" => &signature::RSA_PSS_2048_8192_SHA384, "SHA512" => &signature::RSA_PSS_2048_8192_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let public_key = test_case.consume_bytes("Key"); let public_key = untrusted::Input::from(&public_key); assert!(public_key.read_all(error::Unspecified, |input| { der::nested(input, der::Tag::Sequence, error::Unspecified, |input| { let _ = der::positive_integer(input)?; let _ = der::positive_integer(input)?; Ok(()) }) }).is_ok()); let msg = test_case.consume_bytes("Msg"); let msg = untrusted::Input::from(&msg); let sig = test_case.consume_bytes("Sig"); let sig = untrusted::Input::from(&sig); let expected_result = test_case.consume_string("Result"); let actual_result = signature::verify(alg, public_key, msg, sig); assert_eq!(actual_result.is_ok(), expected_result == "P"); Ok(()) }); } #[test] fn test_signature_rsa_primitive_verification() { test::from_file("tests/rsa_primitive_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let n = test_case.consume_bytes("n"); let e = test_case.consume_bytes("e"); let msg = test_case.consume_bytes("Msg"); let sig = test_case.consume_bytes("Sig"); let expected = test_case.consume_string("Result"); let result = signature::primitive::verify_rsa( &signature::RSA_PKCS1_2048_8192_SHA256, (untrusted::Input::from(&n), untrusted::Input::from(&e)), untrusted::Input::from(&msg), untrusted::Input::from(&sig)); assert_eq!(result.is_ok(), expected == "Pass"); Ok(()) }) }
#![forbid( anonymous_parameters, box_pointers, legacy_directory_ownership, missing_copy_implementations, missing_debug_implementations, missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results, variant_size_differences, warnings, )] extern crate ring; extern crate untrusted; use ring::{der, error, signature, test}; #[cfg(feature = "rsa_signing")] use ring::rand; #[cfg(feature = "rsa_signing")] #[test] fn rsa_from_pkcs8_test() { test::from_file("tests/rsa_from_pkcs8_tests.txt", |section, test_case| { assert_eq!(section, ""); let input = test_case.consume_bytes("Input"); let input = untrusted::Input::from(&input); let error = test_case.consume_optional_string("Error"); assert_eq!(signature::RSAKeyPair::from_pkcs8(input).is_ok(), error.is_none()); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_signature_rsa_pkcs1_sign() { let rng = rand::SystemRandom::new(); test::from_file("tests/rsa_pkcs1_sign_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PKCS1_SHA256, "SHA384" => &signature::RSA_PKCS1_SHA384, "SHA512" => &signature::RSA_PKCS1_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let private_key = test_case.consume_bytes("Key"); let msg = test_case.consume_bytes("Msg"); let expected = test_case.consume_bytes("Sig"); let result = test_case.consume_string("Result"); let private_key = untrusted::Input::from(&private_key); let key_pair = signature::RSAKeyPair::from_der(private_key); if result == "Fail-Invalid-Key" { assert!(key_pair.is_err()); return Ok(()); } let key_pair = key_pair.unwrap(); let key_pair = std::sync::Arc::new(key_pair); let mut signing_state = signature::RSASigningState::new(key_pair).unwrap(); let mut actual = vec![0u8; signing_state.key_pair().public_modulus_len()]; signing_state.sign(alg, &rng, &msg, actual.as_mut_slice()).unwrap(); assert_eq!(actual.as_slice() == &expected[..], result == "Pass"); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_signature_rsa_pss_sign() { struct DeterministicSalt<'a> { salt: &'a [u8], rng: &'a rand::SecureRandom } impl<'a> rand::SecureRandom for DeterministicSalt<'a> { fn fill(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> { let dest_len = dest.len(); if dest_len != self.salt.len() { self.rng.fill(dest)?; } else { dest.copy_from_slice(&self.salt); } Ok(()) } } let rng = rand::SystemRandom::new(); test::from_file("tests/rsa_pss_sign_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest");
let result = test_case.consume_string("Result"); let private_key = test_case.consume_bytes("Key"); let private_key = untrusted::Input::from(&private_key); let key_pair = signature::RSAKeyPair::from_der(private_key); if key_pair.is_err() && result == "Fail-Invalid-Key" { return Ok(()); } let key_pair = key_pair.unwrap(); let key_pair = std::sync::Arc::new(key_pair); let msg = test_case.consume_bytes("Msg"); let salt = test_case.consume_bytes("Salt"); let expected = test_case.consume_bytes("Sig"); let new_rng = DeterministicSalt { salt: &salt, rng: &rng }; let mut signing_state = signature::RSASigningState::new(key_pair).unwrap(); let mut actual = vec![0u8; signing_state.key_pair().public_modulus_len()]; signing_state.sign(alg, &new_rng, &msg, actual.as_mut_slice())?; assert_eq!(actual.as_slice() == &expected[..], result == "Pass"); Ok(()) }); } #[cfg(feature = "rsa_signing")] #[test] fn test_rsa_key_pair_traits() { test::compile_time_assert_send::<signature::RSAKeyPair>(); test::compile_time_assert_sync::<signature::RSAKeyPair>(); test::compile_time_assert_debug::<signature::RSAKeyPair>(); test::compile_time_assert_send::<signature::RSASigningState>(); } #[test] fn test_signature_rsa_pkcs1_verify() { test::from_file("tests/rsa_pkcs1_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA1" => &signature::RSA_PKCS1_2048_8192_SHA1, "SHA256" => &signature::RSA_PKCS1_2048_8192_SHA256, "SHA384" => &signature::RSA_PKCS1_2048_8192_SHA384, "SHA512" => &signature::RSA_PKCS1_2048_8192_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let public_key = test_case.consume_bytes("Key"); let public_key = untrusted::Input::from(&public_key); assert!(public_key.read_all(error::Unspecified, |input| { der::nested(input, der::Tag::Sequence, error::Unspecified, |input| { let _ = der::positive_integer(input)?; let _ = der::positive_integer(input)?; Ok(()) }) }).is_ok()); let msg = test_case.consume_bytes("Msg"); let msg = untrusted::Input::from(&msg); let sig = test_case.consume_bytes("Sig"); let sig = untrusted::Input::from(&sig); let expected_result = test_case.consume_string("Result"); let actual_result = signature::verify(alg, public_key, msg, sig); assert_eq!(actual_result.is_ok(), expected_result == "P"); Ok(()) }); } #[test] fn test_signature_rsa_pss_verify() { test::from_file("tests/rsa_pss_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let digest_name = test_case.consume_string("Digest"); let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PSS_2048_8192_SHA256, "SHA384" => &signature::RSA_PSS_2048_8192_SHA384, "SHA512" => &signature::RSA_PSS_2048_8192_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } }; let public_key = test_case.consume_bytes("Key"); let public_key = untrusted::Input::from(&public_key); assert!(public_key.read_all(error::Unspecified, |input| { der::nested(input, der::Tag::Sequence, error::Unspecified, |input| { let _ = der::positive_integer(input)?; let _ = der::positive_integer(input)?; Ok(()) }) }).is_ok()); let msg = test_case.consume_bytes("Msg"); let msg = untrusted::Input::from(&msg); let sig = test_case.consume_bytes("Sig"); let sig = untrusted::Input::from(&sig); let expected_result = test_case.consume_string("Result"); let actual_result = signature::verify(alg, public_key, msg, sig); assert_eq!(actual_result.is_ok(), expected_result == "P"); Ok(()) }); } #[test] fn test_signature_rsa_primitive_verification() { test::from_file("tests/rsa_primitive_verify_tests.txt", |section, test_case| { assert_eq!(section, ""); let n = test_case.consume_bytes("n"); let e = test_case.consume_bytes("e"); let msg = test_case.consume_bytes("Msg"); let sig = test_case.consume_bytes("Sig"); let expected = test_case.consume_string("Result"); let result = signature::primitive::verify_rsa( &signature::RSA_PKCS1_2048_8192_SHA256, (untrusted::Input::from(&n), untrusted::Input::from(&e)), untrusted::Input::from(&msg), untrusted::Input::from(&sig)); assert_eq!(result.is_ok(), expected == "Pass"); Ok(()) }) }
let alg = match digest_name.as_ref() { "SHA256" => &signature::RSA_PSS_SHA256, "SHA384" => &signature::RSA_PSS_SHA384, "SHA512" => &signature::RSA_PSS_SHA512, _ => { panic!("Unsupported digest: {}", digest_name) } };
assignment_statement
[ { "content": "#[inline]\n\npub fn sign(key_pair: &KeyPair, rng: &rand::SecureRandom, msg: untrusted::Input)\n\n -> Result<Signature, error::Unspecified> {\n\n key_pair.inner.sign(rng, msg)\n\n}\n\n\n", "file_path": "src/signature.rs", "rank": 0, "score": 364956.10236816294 }, { ...
Rust
src/error.rs
braunse/isahc
df395edf481221d7d1fbfef020d813e604aa28e3
#![allow(deprecated)] use std::error::Error as StdError; use std::fmt; use std::io; #[derive(Debug)] pub enum Error { Aborted, BadClientCertificate(Option<String>), BadServerCertificate(Option<String>), ConnectFailed, CouldntResolveHost, CouldntResolveProxy, Curl(String), InvalidContentEncoding(Option<String>), InvalidCredentials, InvalidHttpFormat(http::Error), InvalidUtf8, Io(io::Error), NoResponse, RangeRequestUnsupported, RequestBodyError(Option<String>), ResponseBodyError(Option<String>), SSLConnectFailed(Option<String>), SSLEngineError(Option<String>), Timeout, TooManyRedirects, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", self, Error::description(self)) } } impl StdError for Error { fn description(&self) -> &str { match self { Error::Aborted => "request aborted unexpectedly", Error::BadClientCertificate(Some(ref e)) => e, Error::BadServerCertificate(Some(ref e)) => e, Error::ConnectFailed => "failed to connect to the server", Error::CouldntResolveHost => "couldn't resolve host name", Error::CouldntResolveProxy => "couldn't resolve proxy host name", Error::Curl(ref e) => e, Error::InvalidContentEncoding(Some(ref e)) => e, Error::InvalidCredentials => "credentials were rejected by the server", Error::InvalidHttpFormat(ref e) => e.description(), Error::InvalidUtf8 => "bytes are not valid UTF-8", Error::Io(ref e) => e.description(), Error::NoResponse => "server did not send a response", Error::RangeRequestUnsupported => "server does not support or accept range requests", Error::RequestBodyError(Some(ref e)) => e, Error::ResponseBodyError(Some(ref e)) => e, Error::SSLConnectFailed(Some(ref e)) => e, Error::SSLEngineError(Some(ref e)) => e, Error::Timeout => "request took longer than the configured timeout", Error::TooManyRedirects => "max redirect limit exceeded", _ => "unknown error", } } fn cause(&self) -> Option<&dyn StdError> { match self { Error::InvalidHttpFormat(e) => Some(e), Error::Io(e) => Some(e), _ => None, } } } #[doc(hidden)] impl From<curl::Error> for Error { fn from(error: curl::Error) -> Error { if error.is_ssl_certproblem() || error.is_ssl_cacert_badfile() { Error::BadClientCertificate(error.extra_description().map(str::to_owned)) } else if error.is_peer_failed_verification() || error.is_ssl_cacert() { Error::BadServerCertificate(error.extra_description().map(str::to_owned)) } else if error.is_couldnt_connect() { Error::ConnectFailed } else if error.is_couldnt_resolve_host() { Error::CouldntResolveHost } else if error.is_couldnt_resolve_proxy() { Error::CouldntResolveProxy } else if error.is_bad_content_encoding() || error.is_conv_failed() { Error::InvalidContentEncoding(error.extra_description().map(str::to_owned)) } else if error.is_login_denied() { Error::InvalidCredentials } else if error.is_got_nothing() { Error::NoResponse } else if error.is_range_error() { Error::RangeRequestUnsupported } else if error.is_read_error() || error.is_aborted_by_callback() { Error::RequestBodyError(error.extra_description().map(str::to_owned)) } else if error.is_write_error() || error.is_partial_file() { Error::ResponseBodyError(error.extra_description().map(str::to_owned)) } else if error.is_ssl_connect_error() { Error::SSLConnectFailed(error.extra_description().map(str::to_owned)) } else if error.is_ssl_engine_initfailed() || error.is_ssl_engine_notfound() || error.is_ssl_engine_setfailed() { Error::SSLEngineError(error.extra_description().map(str::to_owned)) } else if error.is_operation_timedout() { Error::Timeout } else if error.is_too_many_redirects() { Error::TooManyRedirects } else { Error::Curl(error.description().to_owned()) } } } #[doc(hidden)] impl From<curl::MultiError> for Error { fn from(error: curl::MultiError) -> Error { Error::Curl(error.description().to_owned()) } } #[doc(hidden)] impl From<http::Error> for Error { fn from(error: http::Error) -> Error { Error::InvalidHttpFormat(error) } } #[doc(hidden)] impl From<io::Error> for Error { fn from(error: io::Error) -> Error { match error.kind() { io::ErrorKind::ConnectionRefused => Error::ConnectFailed, io::ErrorKind::TimedOut => Error::Timeout, _ => Error::Io(error), } } } #[doc(hidden)] impl From<Error> for io::Error { fn from(error: Error) -> io::Error { match error { Error::ConnectFailed => io::ErrorKind::ConnectionRefused.into(), Error::Io(e) => e, Error::Timeout => io::ErrorKind::TimedOut.into(), _ => io::ErrorKind::Other.into(), } } } #[doc(hidden)] impl From<std::string::FromUtf8Error> for Error { fn from(_: std::string::FromUtf8Error) -> Error { Error::InvalidUtf8 } } #[doc(hidden)] impl From<std::str::Utf8Error> for Error { fn from(_: std::str::Utf8Error) -> Error { Error::InvalidUtf8 } }
#![allow(deprecated)] use std::error::Error as StdError; use std::fmt; use std::io; #[derive(Debug)] pub enum Error { Aborted, BadClientCertificate(Option<String>), BadServerCertificate(Option<String>), ConnectFailed, CouldntResolveHost, CouldntResolveProxy, Curl(String), InvalidContentEncoding(Option<String>), InvalidCredentials, InvalidHttpFormat(http::Error), InvalidUtf8, Io(io::Error), NoResponse, RangeRequestUnsupported, RequestBodyError(Option<String>), ResponseBodyError(Option<String>), SSLConnectFailed(Option<String>), SSLEngineError(Option<String>), Timeout, TooManyRedirects, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}: {}", self, Error::description(self)) } } impl StdError for Error { fn description(&self) -> &str { match self { Error::Aborted => "request aborted unexpectedly", Error::BadClientCertificate(Some(ref e)) => e, Error::BadServerCertificate(Some(ref e)) => e, Error::ConnectFailed => "failed to connect to the server", Error::CouldntResolveHost => "couldn't resolve host name", Error::CouldntResolveProxy => "couldn't resolve proxy host name", Error::Curl(ref e) => e, Error::InvalidContentEncoding(Some(ref e)) => e, Error::InvalidCredentials => "credentials were rejected by the server", Error::InvalidHttpFormat(ref e) => e.description(), Error::InvalidUtf8 => "bytes are not valid UTF-8", Error::Io(ref e) => e.description(), Error::NoResponse => "server did not send a response", Error::RangeRequestUnsupported => "server does not support or accept range requests", Error::RequestBodyError(Some(ref e)) => e, Error::ResponseBodyError(Some(ref e)) => e, Error::SSLConnectFailed(Some(ref e)) => e, Error::SSLEngineError(Some(ref e)) => e, Error::Timeout => "request took longer than the configured timeout", Error::TooManyRedirects => "max redirect limit exceeded", _ => "unknown error", } } fn cause(&self) -> Option<&dyn StdError> { match self { Error::InvalidHttpFormat(e) => Some(e), Error::Io(e) => Some(e), _ => None, } } } #[doc(hidden)] impl From<curl::Error> for Error { fn from(error: curl::Error) -> Error { if error.is_ssl_certproblem() || error.is_ssl_cacert_badfile() { Error::BadClientCertificate(error.extra_description().map(str::to_owned)) } else if error.is_peer_failed_verification() || error.is_ssl_cacert() { Error::BadServerCertificate(error.extra_description().map(str::to_owned)) } else if error.is_couldnt_connect() { Error::ConnectFailed } else if error.is_couldnt_resolve_host() { Error::CouldntResolveHost } else if error.is_couldnt_resolve_proxy() { Error::CouldntResolveProxy } else if error.is_bad_content_encoding() || error.is_conv_failed() { Error::InvalidContentEncoding(error.extra_description().map(str::to_owned)) } else if error.is_login_denied() { Error::InvalidCredentials } else if error.is_got_nothing() { Error::NoResponse } else if error.is_range_error() { Error::RangeRequestUnsupported } else if error.is_read_error() || error.is_aborted_by_callback() { Error::RequestBodyError(error.extra_description().map(str::to_owned)) } else if error.is_write_error() || error.is_partial_file() { Error::ResponseBodyError(error.extra_description().map(str::to_owned)) } else if error.is_ssl_connect_error() { Error::SSLConnectFailed(error.extra_description().map(str::to_owned)) } else if error.is_ssl_engine_initfailed() || error.is_ssl_engine_notfound() || error.is_ssl_engine_setfailed() { Error::SSLEngineError(error.extra_description().map(str::to_owned)) } else if error.is_operation_timedout() { Error::Timeout } else if error.is_too_many_redirects() { Error::TooManyRedirects } else { Error::Curl(error.description().to_owned()) } } } #[doc(hidden)] impl From<curl::MultiError> for Error { fn from(error: curl::MultiError) -> Error { Error::Curl(error.description().to_owned()) } } #[doc(hidden)] impl From<http::Error> for Error { fn from(error: http::Error) -> Error { Error::InvalidHttpFormat(error) } } #[doc(hidden)] impl From<io::Error> for Error { fn from(error: io::Error) -> Error { match error.kind() { io::ErrorKind::ConnectionRefused => Error::ConnectFailed, io::ErrorKind::TimedOut => Error::Timeout, _ => Error::Io(error), } } } #[doc(hidden)] impl From<Error> for io::Error {
} #[doc(hidden)] impl From<std::string::FromUtf8Error> for Error { fn from(_: std::string::FromUtf8Error) -> Error { Error::InvalidUtf8 } } #[doc(hidden)] impl From<std::str::Utf8Error> for Error { fn from(_: std::str::Utf8Error) -> Error { Error::InvalidUtf8 } }
fn from(error: Error) -> io::Error { match error { Error::ConnectFailed => io::ErrorKind::ConnectionRefused.into(), Error::Io(e) => e, Error::Timeout => io::ErrorKind::TimedOut.into(), _ => io::ErrorKind::Other.into(), } }
function_block-full_function
[ { "content": "/// Creates an interceptor from an arbitrary closure or function.\n\npub fn from_fn<F, E>(f: F) -> InterceptorFn<F>\n\nwhere\n\n F: for<'a> private::AsyncFn2<Request<Body>, Context<'a>, Output = Result<Response<Body>, E>> + Send + Sync + 'static,\n\n E: Into<Box<dyn Error>>,\n\n{\n\n Inte...
Rust
src/objects/module.rs
mloebel/rust-cpython
2e243f7622a8d33bca3fb321db25d4be4c26397d
use libc::c_char; use std::ffi::{CStr, CString}; use crate::conversion::ToPyObject; use crate::err::{self, PyErr, PyResult}; use crate::ffi; use crate::objectprotocol::ObjectProtocol; use crate::objects::{exc, PyDict, PyObject, PyTuple}; use crate::py_class::PythonObjectFromPyClassMacro; use crate::python::{PyDrop, Python, PythonObject}; pub struct PyModule(PyObject); pyobject_newtype!(PyModule, PyModule_Check, PyModule_Type); impl PyModule { pub fn new(py: Python, name: &str) -> PyResult<PyModule> { let name = CString::new(name).unwrap(); unsafe { err::result_cast_from_owned_ptr(py, ffi::PyModule_New(name.as_ptr())) } } pub fn import(py: Python, name: &str) -> PyResult<PyModule> { let name = CString::new(name).unwrap(); unsafe { err::result_cast_from_owned_ptr(py, ffi::PyImport_ImportModule(name.as_ptr())) } } pub fn dict(&self, py: Python) -> PyDict { unsafe { let r = PyObject::from_borrowed_ptr(py, ffi::PyModule_GetDict(self.0.as_ptr())); r.unchecked_cast_into::<PyDict>() } } unsafe fn str_from_ptr<'a>(&'a self, py: Python, ptr: *const c_char) -> PyResult<&'a str> { if ptr.is_null() { Err(PyErr::fetch(py)) } else { let slice = CStr::from_ptr(ptr).to_bytes(); match std::str::from_utf8(slice) { Ok(s) => Ok(s), Err(e) => Err(PyErr::from_instance( py, exc::UnicodeDecodeError::new_utf8(py, slice, e)?, )), } } } pub fn name<'a>(&'a self, py: Python) -> PyResult<&'a str> { unsafe { self.str_from_ptr(py, ffi::PyModule_GetName(self.0.as_ptr())) } } #[allow(deprecated)] pub fn filename<'a>(&'a self, py: Python) -> PyResult<&'a str> { unsafe { self.str_from_ptr(py, ffi::PyModule_GetFilename(self.0.as_ptr())) } } #[cfg(feature = "python3-sys")] pub fn filename_object<'a>(&'a self, py: Python) -> PyResult<PyObject> { let ptr = unsafe { ffi::PyModule_GetFilenameObject(self.0.as_ptr()) }; if ptr.is_null() { Err(PyErr::fetch(py)) } else { Ok(unsafe { PyObject::from_borrowed_ptr(py, ptr) }) } } pub fn get(&self, py: Python, name: &str) -> PyResult<PyObject> { self.as_object().getattr(py, name) } pub fn call<A>( &self, py: Python, name: &str, args: A, kwargs: Option<&PyDict>, ) -> PyResult<PyObject> where A: ToPyObject<ObjectType = PyTuple>, { self.as_object().getattr(py, name)?.call(py, args, kwargs) } pub fn add<V>(&self, py: Python, name: &str, value: V) -> PyResult<()> where V: ToPyObject, { self.as_object().setattr(py, name, value) } pub fn add_class<'p, T>(&self, py: Python<'p>) -> PyResult<()> where T: PythonObjectFromPyClassMacro, { T::add_to_module(py, self) } }
use libc::c_char; use std::ffi::{CStr, CString}; use crate::conversion::ToPyObject; use crate::err::{self, PyErr, PyResult}; use crate::ffi; use crate::objectprotocol::ObjectProtocol; use crate::objects::{exc, PyDict, PyObject, PyTuple}; use crate::py_class::PythonObjectFromPyClassMacro; use crate::python::{PyDrop, Python, PythonObject}; pub struct PyModule(PyObject); pyobject_newtype!(PyModule, PyModule_Check, PyModule_Type); impl PyModule { pub fn new(py: Python, name: &str) -> PyResult<PyModule> { let name = CString::new(name).unwrap(); unsafe { err::result_cast_from_owned_ptr(py, ffi::PyModule_New(name.as_ptr())) } } pub fn import(py: Python, name: &str) -> PyResult<PyModule> { let name = CString::new(name).unwrap(); unsafe { err::result_cast_from_owned_ptr(py, ffi::PyImport_ImportModule(name.as_ptr())) } } pub fn dict(&self, py: Python) -> PyDict { unsafe { let r = PyObject::from_borrowed_ptr(py, ffi::PyModule_GetDict(self.0.as_ptr())); r.unchecked_cast_into::<PyDict>() } } unsafe fn str_from_ptr<'a>(&'a self, py: Python, ptr: *const c_char) -> PyResult<&'a str> { if ptr.is_null() { Err(PyErr::fetch(py)) } else { let slice = CStr::from_ptr(ptr).to_bytes(); match std::str::from_utf8(slice) { Ok(s) => Ok(s), Err(e) =>
, } } } pub fn name<'a>(&'a self, py: Python) -> PyResult<&'a str> { unsafe { self.str_from_ptr(py, ffi::PyModule_GetName(self.0.as_ptr())) } } #[allow(deprecated)] pub fn filename<'a>(&'a self, py: Python) -> PyResult<&'a str> { unsafe { self.str_from_ptr(py, ffi::PyModule_GetFilename(self.0.as_ptr())) } } #[cfg(feature = "python3-sys")] pub fn filename_object<'a>(&'a self, py: Python) -> PyResult<PyObject> { let ptr = unsafe { ffi::PyModule_GetFilenameObject(self.0.as_ptr()) }; if ptr.is_null() { Err(PyErr::fetch(py)) } else { Ok(unsafe { PyObject::from_borrowed_ptr(py, ptr) }) } } pub fn get(&self, py: Python, name: &str) -> PyResult<PyObject> { self.as_object().getattr(py, name) } pub fn call<A>( &self, py: Python, name: &str, args: A, kwargs: Option<&PyDict>, ) -> PyResult<PyObject> where A: ToPyObject<ObjectType = PyTuple>, { self.as_object().getattr(py, name)?.call(py, args, kwargs) } pub fn add<V>(&self, py: Python, name: &str, value: V) -> PyResult<()> where V: ToPyObject, { self.as_object().setattr(py, name, value) } pub fn add_class<'p, T>(&self, py: Python<'p>) -> PyResult<()> where T: PythonObjectFromPyClassMacro, { T::add_to_module(py, self) } }
Err(PyErr::from_instance( py, exc::UnicodeDecodeError::new_utf8(py, slice, e)?, ))
call_expression
[ { "content": "pub fn type_error_to_false(py: Python, e: PyErr) -> PyResult<bool> {\n\n if e.matches(py, py.get_type::<exc::TypeError>()) {\n\n Ok(false)\n\n } else {\n\n Err(e)\n\n }\n\n}\n\n\n\n#[macro_export]\n\n#[doc(hidden)]\n\nmacro_rules! py_class_binary_numeric_slot {\n\n ($clas...
Rust
clients/client-core/src/client/real_messages_control/acknowledgement_control/retransmission_request_listener.rs
confio/nym
495ca35c1f46e7244d89fdf73402021d70df625d
use super::action_controller::{Action, ActionSender}; use super::PendingAcknowledgement; use super::RetransmissionRequestReceiver; use crate::client::{ real_messages_control::real_traffic_stream::{BatchRealMessageSender, RealMessage}, topology_control::TopologyAccessor, }; use futures::StreamExt; use log::*; use nymsphinx::preparer::MessagePreparer; use nymsphinx::{acknowledgements::AckKey, addressing::clients::Recipient}; use rand::{CryptoRng, Rng}; use std::sync::{Arc, Weak}; pub(super) struct RetransmissionRequestListener<R> where R: CryptoRng + Rng, { ack_key: Arc<AckKey>, ack_recipient: Recipient, message_preparer: MessagePreparer<R>, action_sender: ActionSender, real_message_sender: BatchRealMessageSender, request_receiver: RetransmissionRequestReceiver, topology_access: TopologyAccessor, } impl<R> RetransmissionRequestListener<R> where R: CryptoRng + Rng, { pub(super) fn new( ack_key: Arc<AckKey>, ack_recipient: Recipient, message_preparer: MessagePreparer<R>, action_sender: ActionSender, real_message_sender: BatchRealMessageSender, request_receiver: RetransmissionRequestReceiver, topology_access: TopologyAccessor, ) -> Self { RetransmissionRequestListener { ack_key, ack_recipient, message_preparer, action_sender, real_message_sender, request_receiver, topology_access, } } async fn on_retransmission_request(&mut self, timed_out_ack: Weak<PendingAcknowledgement>) { let timed_out_ack = match timed_out_ack.upgrade() { Some(timed_out_ack) => timed_out_ack, None => { debug!("We received an ack JUST as we were about to retransmit [1]"); return; } }; let packet_recipient = &timed_out_ack.recipient; let chunk_clone = timed_out_ack.message_chunk.clone(); let frag_id = chunk_clone.fragment_identifier(); let topology_permit = self.topology_access.get_read_permit().await; let topology_ref = match topology_permit .try_get_valid_topology_ref(&self.ack_recipient, Some(packet_recipient)) { Some(topology_ref) => topology_ref, None => { warn!("Could not retransmit the packet - the network topology is invalid"); self.action_sender .unbounded_send(Action::new_start_timer(frag_id)) .unwrap(); return; } }; let prepared_fragment = self .message_preparer .prepare_chunk_for_sending(chunk_clone, topology_ref, &self.ack_key, packet_recipient) .await .unwrap(); if Arc::strong_count(&timed_out_ack) == 1 { debug!("We received an ack JUST as we were about to retransmit [2]"); return; } drop(timed_out_ack); let new_delay = prepared_fragment.total_delay; self.action_sender .unbounded_send(Action::new_update_delay(frag_id, new_delay)) .unwrap(); self.real_message_sender .unbounded_send(vec![RealMessage::new( prepared_fragment.mix_packet, frag_id, )]) .unwrap(); } pub(super) async fn run(&mut self) { debug!("Started RetransmissionRequestListener"); while let Some(timed_out_ack) = self.request_receiver.next().await { self.on_retransmission_request(timed_out_ack).await; } error!("TODO: error msg. Or maybe panic?") } }
use super::action_controller::{Action, ActionSender}; use super::PendingAcknowledgement; use super::RetransmissionRequestReceiver; use crate::client::{ real_messages_control::real_traffic_stream::{BatchRealMessageSender, RealMessage}, topology_control::TopologyAccessor, }; use futures::StreamExt; use log::*; use nymsphinx::preparer::MessagePreparer; use nymsphinx::{acknowledgements::AckKey, addressing::clients::Recipient}; use rand::{CryptoRng, Rng}; use std::sync::{Arc, Weak}; pub(super) struct RetransmissionRequestListener<R> where R: CryptoRng + Rng, { ack_key: Arc<AckKey>, ack_recipient: Recipient, message_preparer: MessagePreparer<R>, action_sender: ActionSender, real_message_sender: BatchRealMessageSender, request_receiver: RetransmissionRequestReceiver, topology_access: TopologyAccessor, } impl<R> RetransmissionRequestListener<R> where R: CryptoRng + Rng, { pub(super) fn new( ack_key: Arc<AckKey>, ack_recipient: Recipient, message_preparer: MessagePreparer<R>, action_sender: ActionSender, real_message_sender: BatchRealMessageSender, request_receiver: RetransmissionRequestReceiver, topology_access: TopologyAccessor, ) -> Self { RetransmissionRequestListener { ack_key, ack_recipient, message_preparer, action_sender, real_message_sender, request_receiver, topology_access, } }
pub(super) async fn run(&mut self) { debug!("Started RetransmissionRequestListener"); while let Some(timed_out_ack) = self.request_receiver.next().await { self.on_retransmission_request(timed_out_ack).await; } error!("TODO: error msg. Or maybe panic?") } }
async fn on_retransmission_request(&mut self, timed_out_ack: Weak<PendingAcknowledgement>) { let timed_out_ack = match timed_out_ack.upgrade() { Some(timed_out_ack) => timed_out_ack, None => { debug!("We received an ack JUST as we were about to retransmit [1]"); return; } }; let packet_recipient = &timed_out_ack.recipient; let chunk_clone = timed_out_ack.message_chunk.clone(); let frag_id = chunk_clone.fragment_identifier(); let topology_permit = self.topology_access.get_read_permit().await; let topology_ref = match topology_permit .try_get_valid_topology_ref(&self.ack_recipient, Some(packet_recipient)) { Some(topology_ref) => topology_ref, None => { warn!("Could not retransmit the packet - the network topology is invalid"); self.action_sender .unbounded_send(Action::new_start_timer(frag_id)) .unwrap(); return; } }; let prepared_fragment = self .message_preparer .prepare_chunk_for_sending(chunk_clone, topology_ref, &self.ack_key, packet_recipient) .await .unwrap(); if Arc::strong_count(&timed_out_ack) == 1 { debug!("We received an ack JUST as we were about to retransmit [2]"); return; } drop(timed_out_ack); let new_delay = prepared_fragment.total_delay; self.action_sender .unbounded_send(Action::new_update_delay(frag_id, new_delay)) .unwrap(); self.real_message_sender .unbounded_send(vec![RealMessage::new( prepared_fragment.mix_packet, frag_id, )]) .unwrap(); }
function_block-full_function
[ { "content": "/// Entry point for splitting whole message into possibly multiple [`Set`]s.\n\n// TODO: make it take message: Vec<u8> instead\n\npub fn split_into_sets<R: Rng>(\n\n rng: &mut R,\n\n message: &[u8],\n\n max_plaintext_size: usize,\n\n) -> Vec<FragmentSet> {\n\n let num_of_sets = total_n...
Rust
src/lib.rs
aesteve/vertx-eventbus-client-rs
2a8391d48f177d8ec9daaf9e2e973cb9d3502634
use std::io; pub mod listener; pub mod message; pub mod publisher; mod utils; use crate::listener::EventBusListener; use crate::publisher::EventBusPublisher; use std::net::{TcpStream, ToSocketAddrs}; pub fn eventbus<A: ToSocketAddrs>(address: A) -> io::Result<(EventBusPublisher, EventBusListener)> { let socket = TcpStream::connect(&address)?; socket.set_nonblocking(true)?; let control_socket = socket .try_clone()?; let w_socket = socket .try_clone()?; Ok(( EventBusPublisher::new(w_socket)?, EventBusListener::new(control_socket)?, )) } #[cfg(test)] mod tests { use crate::eventbus; use crate::message::{Message, SendMessage}; use serde_json::json; use testcontainers::images::generic::{GenericImage, WaitFor}; use testcontainers::*; fn mock_eventbus_server() -> GenericImage { GenericImage::new("aesteve/tests:mock-eventbus-server") .with_wait_for(WaitFor::message_on_stdout("TCP bridge connected")) } #[test] fn test_ping() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, _) = eventbus(addr).expect("Event bus creation must not fail"); publisher .ping() .expect("Should be able to send ping to the server"); } #[test] fn consumer_test() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (_, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let mut consumer = listener.consumer("out-address".to_string()).unwrap(); let mut received_msgs = Vec::new(); while received_msgs.len() < 3 { if let Some(Ok(msg)) = consumer.next() { assert!(received_msgs .iter() .find(|m: &&Message| m.body == msg.body) .is_none()); received_msgs.push(msg); } } listener .unregister_consumer("out-address".to_string()) .expect("Unregistering consumer must not fail"); } #[test] fn send_reply_pattern() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let reply_address = "the-reply-address"; let mut consumer = listener.consumer(reply_address.to_string()).unwrap(); let payload = json!({"test": "value"}); let expected_payload = payload.clone(); publisher .send(SendMessage { address: "echo-address".to_string(), reply_address: Some(reply_address.to_string()), body: Some(payload), headers: None, }) .expect("Sending a message to the event bus must work fine"); let mut received_msgs = 0; while received_msgs == 0 { if let Some(Ok(msg)) = consumer.next() { assert_eq!(reply_address, msg.address); assert_eq!( expected_payload, msg.body.expect("Body should be extracted") ); received_msgs += 1; } } } #[test] fn pub_sub_pattern() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, _) = eventbus(addr).expect("Event bus creation must not fail"); let payload = json!({"test": "value"}); publisher .publish(Message { address: "in-address".to_string(), body: Some(payload), headers: None, }) .expect("Publishing a message to the event bus must work fine"); } #[test] fn test_errors() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let payload = json!({"test": "value"}); publisher .send(SendMessage { address: "error-address".to_string(), reply_address: Some("the-reply-address".to_string()), body: Some(payload), headers: None, }) .expect("Publishing a message to the event bus must work fine"); let mut errors_received = 0; let mut errors = listener.errors().expect("Can listen to errors"); while errors_received == 0 { if let Some(Ok(error_msg)) = errors.next() { assert_eq!(error_msg.message, "FORBIDDEN".to_string(),); errors_received += 1; } } } #[test] fn connect_to_an_unexisting_address_should_fail() { let eb = eventbus("127.0.0.1::1111"); assert!(eb.is_err()); } #[test] fn should_be_notified_of_errors() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (_, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let mut error_listener = listener .errors() .expect("Can ask for an iterator over error messages"); listener .consumer("something_we_dont_have_access_to".to_string()) .expect("Can subscribe to any address"); let mut errors_received = 0; while errors_received < 1 { if let Some(Ok(error_msg)) = error_listener.next() { errors_received += 1; assert!(error_msg.message.contains("denied")) } } } }
use std::io; pub mod listener; pub mod message; pub mod publisher; mod utils; use crate::listener::EventBusListener; use crate::publisher::EventBusPublisher; use std::net::{TcpStream, ToSocketAddrs}; pub fn eventbus<A: ToSocketAddrs>(address: A) -> io::Result<(EventBusPublisher, EventBusListener)> { let socket = TcpStream::connect(&address)?; socket.set_nonblocking(true)?; let control_socket = socket .try_clone()?; let w_socket = socket .try_clone()?; Ok(( EventBusPublisher::new(w_socket)?, EventBusListener::new(control_socket)?, )) } #[cfg(test)] mod tests { use crate::eventbus; use crate::message::{Message, SendMessage}; use serde_json::json; use testcontainers::images::generic::{GenericImage, WaitFor}; use testcontainers::*; fn mock_eventbus_server() -> GenericImage { GenericImage::new("aesteve/tests:mock-eventbus-server") .with_wait_for(WaitFor::message_on_stdout("TCP bridge connected")) } #[test] fn test_ping() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, _) = eventbus(addr).expect("Event bus creation must not fail"); publisher .ping() .expect("Should be able to send ping to the server"); } #[test] fn consumer_test() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (_, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let mut consumer = listener.consumer("out-address".to_string()).unwrap(); let mut received_msgs = Vec::new(); while received_msgs.len() < 3 { if let Some(Ok(msg)) = consumer.next() { assert!(received_msgs .iter() .find(|m: &&Message| m.body == msg.body) .is_none()); received_msgs.push(msg); } } listener .unregister_consumer("out-address".to_string()) .expect("Unregistering consumer must not fail"); } #[test] fn send_reply_pattern() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let reply_address = "the-reply-address"; let mut consumer = listener.consumer(reply_address.to_string()).unwrap(); let payload = json!({"test": "value"}); let expected_payload = payload.clone(); publisher .send(SendMessage { address: "echo-address".to_string(), reply_address: Some(reply_address.to_string()), body: Some(payload), headers: None, }) .expect("Sending a message to the event bus must work fine"); let mut received_msgs = 0; while received_msgs == 0 { if let Some(Ok(msg)) = consumer.next() { assert_eq!(reply_address, msg.address); assert_eq!( expected_payload, msg.body.expect("Body should be extracted") ); received_msgs += 1; } } } #[test] fn pub_sub_pattern() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, _) = eventbus(addr).expect("Event bus creation must not fail"); let payload = json!({"test": "value"}); publisher .publish(Message { address: "in-address".to_string(), body: Some(payload), headers: None, }) .expect("Publishing a message to the event bus must work fine"); } #[test] fn test_errors() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (mut publisher, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let payload = json!({"test": "value"}); publisher .send(SendMessage { address: "error-address".to_string(), reply_address: Some("the-reply-address".to_string()), body: Some(payload), headers: None, }) .expect("Publishing a message to the event bus must work fine"); let mut errors_received = 0; let mut errors = listener.errors().expect("Can listen to errors"); while errors_received == 0 { if let Some(Ok(error_msg)) = errors.next() { assert_eq!(error_msg.message, "FORBIDDEN".to_string(),); errors_received += 1; } } } #[test] fn connect_to_an_unexisting_address_should_fail() { let eb = eventbus("127.0.0.1::1111"); assert!(eb.is_err()); } #[test] fn should_be_notified_of_errors() { let docker = clients::Cli::default(); let node = docker.run(mock_eventbus_server()); let host_port = node .get_host_port(7542) .expect("Mock event bus server implementation needs to be up before running tests"); let addr = format!("localhost:{}", host_port); println!("Mock server running on {}", addr); let (_, mut listener) = eventbus(addr).expect("Event bus creation must not fail"); let mut error_listener = listener .errors() .expect("Can ask for an iterator over error messages"); listener .consumer("something_we_dont_have_access_to".to_string()) .expect("Can subscribe to any address"); let mut errors_received = 0; while errors_received < 1 {
} } }
if let Some(Ok(error_msg)) = error_listener.next() { errors_received += 1; assert!(error_msg.message.contains("denied")) }
if_condition
[ { "content": "type ErrorNotifier = Mutex<Option<Sender<UserMessage<ErrorMessage>>>>;\n\n\n\npub struct EventBusListener {\n\n socket: TcpStream,\n\n handlers: MessageHandlersByAddress,\n\n error_handler: Arc<ErrorNotifier>,\n\n}\n\n\n\nimpl EventBusListener {\n\n pub fn new(socket: TcpStream) -> io:...
Rust
pallets/stake-nft/src/mock.rs
SubGame-Network/subgame-network
d9906befc41e972e11fa1a669d47eddb15dabdd8
use crate as pallet_stake_nft; use pallet_timestamp; use balances; use frame_support::parameter_types; use frame_system as system; use pallet_nft; use pallet_lease; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event<T>}, SubgameNFT: pallet_nft::{Module, Call, Storage, Event<T>}, SubgameStakeNft: pallet_stake_nft::{Module, Call, Storage, Event<T>}, Lease: pallet_lease::{Module, Call, Storage, Event<T>}, Balances: balances::{Module, Call, Storage, Config<T>, Event<T>}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, } ); parameter_types! { pub const ExistentialDeposit: u64 = 500; pub const MaxLocks: u32 = 50; } impl balances::Config for Test { type MaxLocks = (); type Balance = u64; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); } parameter_types! { pub const BlockHashCount: u64 = 250; } impl system::Config for Test { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type DbWeight = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type AccountData = balances::AccountData<u64>; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); } parameter_types! { pub const BridgeOwner: u32 = 3; } parameter_types! { pub const CommodityLimit: u128 = 1000000000000000000000; pub const UserCommodityLimit: u64 = 10000000000000000000; } impl pallet_nft::Config for Test { type CommodityAdmin = frame_system::EnsureRoot<Self::AccountId>; type CommodityLimit = CommodityLimit; type UserCommodityLimit = UserCommodityLimit; type Event = Event; } impl pallet_lease::Config for Test { type Event = Event; type PalletId = u64; type UniqueAssets = SubgameNFT; type OwnerAddress = BridgeOwner; } impl pallet_stake_nft::Config for Test { type ProgramId = u64; type PalletId = u64; type Balances = Balances; type UniqueAssets = SubgameNFT; type Lease = Lease; type OwnerAddress = BridgeOwner; type Event = Event; } impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = (); type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); balances::GenesisConfig::<Test> { balances: vec![ (1, 1000000), (2, 1000000), (3, 1000000), (4, 1000000), (5, 1000000), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternalities = t.into(); ext.execute_with(|| System::set_block_number(1)); ext }
use crate as pallet_stake_nft; use pallet_timestamp; use balances; use frame_support::parameter_types; use frame_system as system; use pallet_nft; use pallet_lease; use sp_core::H256; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; type Block = frame_system::mocking::MockBlock<Test>; frame_support::construct_runtime!( pub enum Test where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event<T>}, SubgameNFT: pallet_nft::{Module, Call, Storage, Event<T>}, SubgameStakeNft: pallet_stake_nft::{Module, Call, Storage, Event<T>}, Lease: pallet_lease::{Module, Call, Storage, Event<T>}, Balances: balances::{Module, Call, Storage, Config<T>, Event<T>}, Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent}, } ); parameter_types! { pub const ExistentialDeposit: u64 = 500; pub const MaxLocks: u32 = 50; } impl balances::Config for Test { type MaxLocks = (); type Balance = u64; type Event = Event; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); } parameter_types! { pub const BlockHashCount: u64 = 250; } impl system::Config for Test { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type DbWeight = (); type Origin = Origin; type Call = Call; type Index = u64; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type AccountData = balances::AccountData<u64>; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = Event; type BlockHashCount = BlockHashCount; type Version = (); type PalletInfo = PalletInfo; type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); } parameter_types! { pub const BridgeOwner: u32 = 3; } parameter_types! { pub const CommodityLimit: u128 = 1000000000000000000000; pub const UserCommodityLimit: u64 = 10000000000000000000; } impl pallet_nft::Config for Test { type CommodityAdmin = frame_system::EnsureRoot<Self::AccountId>; type CommodityLimit = CommodityLimit; type UserCommodityLimit = UserCommodityLimit; type Event = Event; } impl pallet_lease::Config for Test { type Event = Event; type PalletId = u64; type UniqueAssets = SubgameNFT; type OwnerAddress = BridgeOwner; } impl pallet_stake_nft::Config for Test { type ProgramId = u64; type PalletId = u64; type Balances = Balances; type UniqueAssets = SubgameNFT; type Lease = Lease; type OwnerAddress = BridgeOwner; type Event = Event; } impl pallet_timestamp::Config for Test { type Moment = u64; type OnTimestampSet = (); type MinimumPeriod = (); type WeightInfo = (); } pub fn new_test_ext() -> sp_io::TestExternalities { let mut t = system::GenesisConfig::default() .build_storage::<Test>() .unwrap(); balances::GenesisConfig::<Test> { balances: vec![ (1, 1000000), (2, 100000
0), (3, 1000000), (4, 1000000), (5, 1000000), ], } .assimilate_storage(&mut t) .unwrap(); let mut ext: sp_io::TestExternalities = t.into(); ext.execute_with(|| System::set_block_number(1)); ext }
function_block-function_prefixed
[ { "content": "type Block = frame_system::mocking::MockBlock<Test>;\n\n\n\n// Configure a mock runtime to test the pallet.\n\nframe_support::construct_runtime!(\n\n pub enum Test where\n\n Block = Block,\n\n NodeBlock = Block,\n\n UncheckedExtrinsic = UncheckedExtrinsic,\n\n {\n\n ...
Rust
core/codegen/tests/route.rs
Compro-Prasad/Rocket
198b6f0e9726f7e53c61d365b797df630c876c59
#![deny(non_snake_case)] #[macro_use] extern crate rocket; use std::path::PathBuf; use rocket::http::ext::Normalize; use rocket::local::blocking::Client; use rocket::data::{self, Data, FromData, ToByteUnit}; use rocket::request::{Request, Form}; use rocket::http::{Status, RawStr, ContentType}; #[derive(FromForm, UriDisplayQuery)] struct Inner<'r> { field: &'r RawStr } struct Simple(String); #[async_trait] impl FromData for Simple { type Error = (); async fn from_data(_: &Request<'_>, data: Data) -> data::Outcome<Self, ()> { let string = data.open(64.bytes()).stream_to_string().await.unwrap(); data::Outcome::Success(Simple(string)) } } #[post("/<a>/<name>/name/<path..>?sky=blue&<sky>&<query..>", format = "json", data = "<simple>", rank = 138)] fn post1( sky: usize, name: &RawStr, a: String, query: Form<Inner<'_>>, path: PathBuf, simple: Simple, ) -> String { let string = format!("{}, {}, {}, {}, {}, {}", sky, name, a, query.field, path.normalized_str(), simple.0); let uri = uri!(post2: a, name.url_decode_lossy(), path, sky, query.into_inner()); format!("({}) ({})", string, uri.to_string()) } #[route(POST, path = "/<a>/<name>/name/<path..>?sky=blue&<sky>&<query..>", format = "json", data = "<simple>", rank = 138)] fn post2( sky: usize, name: &RawStr, a: String, query: Form<Inner<'_>>, path: PathBuf, simple: Simple, ) -> String { let string = format!("{}, {}, {}, {}, {}, {}", sky, name, a, query.field, path.normalized_str(), simple.0); let uri = uri!(post2: a, name.url_decode_lossy(), path, sky, query.into_inner()); format!("({}) ({})", string, uri.to_string()) } #[allow(dead_code)] #[post("/<_unused_param>?<_unused_query>", data="<_unused_data>")] fn test_unused_params(_unused_param: String, _unused_query: String, _unused_data: Data) { } #[test] fn test_full_route() { let rocket = rocket::ignite() .mount("/1", routes![post1]) .mount("/2", routes![post2]); let client = Client::tracked(rocket).unwrap(); let a = "A%20A"; let name = "Bob%20McDonald"; let path = "this/path/here"; let sky = 777; let query = "field=inside"; let simple = "data internals"; let path_part = format!("/{}/{}/name/{}", a, name, path); let query_part = format!("?sky={}&sky=blue&{}", sky, query); let uri = format!("{}{}", path_part, query_part); let expected_uri = format!("{}?sky=blue&sky={}&{}", path_part, sky, query); let response = client.post(&uri).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client.post(format!("/1{}", uri)).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client .post(format!("/1{}", uri)) .header(ContentType::JSON) .body(simple) .dispatch(); assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})", sky, name, "A A", "inside", path, simple, expected_uri)); let response = client.post(format!("/2{}", uri)).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client .post(format!("/2{}", uri)) .header(ContentType::JSON) .body(simple) .dispatch(); assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})", sky, name, "A A", "inside", path, simple, expected_uri)); } mod scopes { mod other { #[get("/world")] pub fn world() -> &'static str { "Hello, world!" } } #[get("/hello")] pub fn hello() -> &'static str { "Hello, outside world!" } use other::world; fn _rocket() -> rocket::Rocket { rocket::ignite().mount("/", rocket::routes![hello, world]) } }
#![deny(non_snake_case)] #[macro_use] extern crate rocket; use std::path::PathBuf; use rocket::http::ext::Normalize; use rocket::local::blocking::Client; use rocket::data::{self, Data, FromData, ToByteUnit}; use rocket::request::{Request, Form}; use rocket::http::{Status, RawStr, ContentType}; #[derive(FromForm, UriDisplayQuery)] struct Inner<'r> { field: &'r RawStr } struct Simple(String); #[async_trait] impl FromData for Simple { type Error = (); async fn from_data(_: &Request<'_>, data: Data) -> data::Outcome<Self, ()> { let string = data.open(64.bytes()).stream_to_string().await.unwrap(); data::Outcome::Success(Simple(string)) } } #[post("/<a>/<name>/name/<path..>?sky=blue&<sky>&<query..>", format = "json", data = "<simple>", rank = 138)] fn post1( sky: usize, name: &RawStr, a: String, query: Form<Inner<'_>>, path: PathBuf, simple: Simple, ) -> String { let string = format!("{}, {}, {}, {}, {}, {}", sky, name, a, query.field, path.normalized_str(), simple.0); let uri = uri!(post2: a, name.url_decode_lossy(), path, sky, query.into_inner()); format!("({}) ({})", string, uri.to_string()) } #[route(POST, path = "/<a>/<name>/name/<path..>?sky=blue&<sky>&<query..>", format = "json", data = "<simple>", rank = 138)] fn post2( sky: usize, name: &RawStr, a: String, query: Form<Inner<'_>>, path: PathBuf, simple: Simple, ) -> String { let string = format!("{}, {}, {}, {}, {}, {}", sky, name, a, query.field, path.normalized_str(), simple.0); let uri = uri!(post2: a, name.url_decode_lossy(), path, sky, query.into_inner()); format!("({}) ({})", string, uri.to_string()) } #[allow(dead_code)] #[post("/<_unused_param>?<_unused_query>", data="<_unused_data>")] fn test_unused_params(_unused_param: String, _unused_query: String, _unused_data: Data) { } #[test] fn test_full_route() { let rocket = rocket::ignite() .mount("/1", routes![post1]) .mount("/2", routes![post2]); let client = Client::tracked(rocket).unwrap(); let a = "A%20A"; let name = "Bob%20McDonald"; let path = "this/path/here"; let sky = 777; let query = "field=inside"; let simple = "data internals"; let path_part = format!("/{}/{}/name/{}", a, name, path); let query_part = format!("?sky={}&sky=blue&{}", sky, query); let uri = format!("{}{}", path_part, query_part); let expected_uri = format!("{}?sky=blue&sky={}&{}", path_part, sky, query); let response = client.post(&uri).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client.post(format!("/1{}", uri)).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client .post(format!("/1{}", uri)) .header(ContentType::JSON) .body(simple) .dispatch(); assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})", sky, name, "A A", "inside", path, simple, expected_uri)); let response = client.post(format!("/2{}", uri)).body(simple).dispatch(); assert_eq!(response.status(), Status::NotFound); let response = client .post(format!("/2{}", uri)) .header(ContentType::JSON) .body(simple) .
mod scopes { mod other { #[get("/world")] pub fn world() -> &'static str { "Hello, world!" } } #[get("/hello")] pub fn hello() -> &'static str { "Hello, outside world!" } use other::world; fn _rocket() -> rocket::Rocket { rocket::ignite().mount("/", rocket::routes![hello, world]) } }
dispatch(); assert_eq!(response.into_string().unwrap(), format!("({}, {}, {}, {}, {}, {}) ({})", sky, name, "A A", "inside", path, simple, expected_uri)); }
function_block-function_prefix_line
[ { "content": "fn test(uri: String, expected: String) {\n\n let client = Client::tracked(super::rocket()).unwrap();\n\n let response = client.get(&uri).dispatch();\n\n assert_eq!(response.into_string(), Some(expected));\n\n}\n\n\n", "file_path": "examples/ranking/src/tests.rs", "rank": 0, "s...
Rust
services/src/util/parsing.rs
2younis/geoengine
253eb7ff2c980511fecdec6ff8fb176d5365bc11
use geoengine_datatypes::primitives::SpatialResolution; use serde::de; use serde::de::Error; use serde::Deserialize; use std::fmt; use std::marker::PhantomData; use std::str::FromStr; use url::Url; pub fn parse_spatial_resolution<'de, D>(deserializer: D) -> Result<SpatialResolution, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; let split: Result<Vec<f64>, <f64 as FromStr>::Err> = s.split(',').map(f64::from_str).collect(); match split.as_ref().map(Vec::as_slice) { Ok(&[x, y]) => SpatialResolution::new(x, y).map_err(D::Error::custom), Err(error) => Err(D::Error::custom(error)), Ok(..) => Err(D::Error::custom("Invalid spatial resolution")), } } pub fn string_or_string_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> where D: serde::Deserializer<'de>, { struct StringOrVec(PhantomData<Vec<String>>); impl<'de> de::Visitor<'de> for StringOrVec { type Value = Vec<String>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("string or array of strings") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![value.to_owned()]) } fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error> where S: de::SeqAccess<'de>, { Deserialize::deserialize(de::value::SeqAccessDeserializer::new(visitor)) } } deserializer.deserialize_any(StringOrVec(PhantomData)) } pub fn deserialize_base_url<'de, D>(deserializer: D) -> Result<Url, D::Error> where D: serde::Deserializer<'de>, { let mut url_string = String::deserialize(deserializer)?; if !url_string.ends_with('/') { url_string.push('/'); } Url::parse(&url_string).map_err(D::Error::custom) } pub fn deserialize_base_url_option<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error> where D: serde::Deserializer<'de>, { let mut url_string = if let Some(url_string) = Option::<String>::deserialize(deserializer)? { url_string } else { return Ok(None); }; if !url_string.ends_with('/') { url_string.push('/'); } Url::parse(&url_string) .map(Option::Some) .map_err(D::Error::custom) } #[cfg(test)] mod tests { use std::fmt::Display; use super::*; #[test] fn test_deserialize_base_url() { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_base_url")] base_url: Url, } impl Display for Test { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.base_url.to_string()) } } assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de/"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert!(serde_json::from_str::<Test>(r#"{"base_url": "foo"}"#).is_err()); } #[test] fn test_deserialize_base_url_option() { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_base_url_option")] base_url: Option<Url>, } impl Display for Test { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.base_url { Some(base_url) => f.write_str(&base_url.to_string()), None => f.write_str(""), } } } assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de/"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert!(serde_json::from_str::<Test>(r#"{"base_url": "foo"}"#).is_err()); assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": null}"#) .unwrap() .to_string(), "" ); } }
use geoengine_datatypes::primitives::SpatialResolution; use serde::de; use serde::de::Error; use serde::Deserialize; use std::fmt; use std::marker::PhantomData; use std::str::FromStr; use url::Url; pub fn parse_spatial_resolution<'de, D>(deserializer: D) -> Result<SpatialResolution, D::Error> where D: serde::Deserializer<'de>, { let s = String::deserialize(deserializer)?; let split: Result<Vec<f64>, <f64 as FromStr>::Err> = s.split(',').map(f64::from_str).collect(); match split.as_ref().map(Vec::as_slice) { Ok(&[x, y]) => SpatialResolution::new(x, y).map_err(D::Error::custom), Err(error) => Err(D::Error::custom(error)), Ok(..) => Err(D::Error::custom("Invalid spatial resolution")), } } pub fn string_or_string_array<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> where D: serde::Deserializer<'de>, { struct StringOrVec(PhantomData<Vec<String>>); impl<'de> de::Visitor<'de> for StringOrVec { type Value = Vec<String>; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("string or array of strings") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { Ok(vec![value.to_owned()]) } fn visit_seq<S>(self, visitor: S) -> Result<Self::Value, S::Error> where S: de::SeqAccess<'de>, { Deserialize::deserialize(de::value::SeqAccessDeserializer::new(visitor)) } } deserializer.deserialize_any(StringOrVec(PhantomData)) } pub fn deserialize_base_url<'de, D>(deserializer: D) -> Result<Url, D::Error> where D: serde::Deserializer<'de>, { let mut url_string = String::deserialize(deserializer)?; if !url_string.ends_with('/') { url_string.push('/'); } Url::parse(&url_string).map_err(D::Error::custom) } pub fn deserialize_base_url_option<'de, D>(deserializer: D) -> Result<Option<Url>, D::Error> where D: serde::Deserializer<'de>, { let mut url_string = if let Some(url_string) = Option::<String>::deserialize(deserializer)? { url_string } else { return Ok(None); }; if !url_string.ends_with('/') { url_string.push('/'); } Url::parse(&url_string) .map(Option::Some) .map_err(D::Error::custom) } #[cfg(test)] mod tests { use std::fmt::Display; use super::*; #[test] fn test_deserialize_base_url() { #[derive(Deserialize)]
ert_eq!( serde_json::from_str::<Test>(r#"{"base_url": null}"#) .unwrap() .to_string(), "" ); } }
struct Test { #[serde(deserialize_with = "deserialize_base_url")] base_url: Url, } impl Display for Test { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.base_url.to_string()) } } assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de/"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert!(serde_json::from_str::<Test>(r#"{"base_url": "foo"}"#).is_err()); } #[test] fn test_deserialize_base_url_option() { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_base_url_option")] base_url: Option<Url>, } impl Display for Test { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.base_url { Some(base_url) => f.write_str(&base_url.to_string()), None => f.write_str(""), } } } assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de/"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert_eq!( serde_json::from_str::<Test>(r#"{"base_url": "https://www.endpoint.de"}"#) .unwrap() .to_string(), "https://www.endpoint.de/" ); assert!(serde_json::from_str::<Test>(r#"{"base_url": "foo"}"#).is_err()); ass
random
[ { "content": "pub fn spatial_reference_specification(srs_string: &str) -> Result<SpatialReferenceSpecification> {\n\n if let Some(sref) = custom_spatial_reference_specification(srs_string) {\n\n return Ok(sref);\n\n }\n\n\n\n let spatial_reference = SpatialReference::from_str(srs_string).context...
Rust
capstone-rs/examples/cstool.rs
froydnj/capstone-rs
5044ace8022b1651d1b7c93d41ad56993e0225f5
extern crate capstone; extern crate clap; #[macro_use] extern crate log; extern crate stderrlog; use capstone::prelude::*; use capstone::{Arch, Endian, EnumList, ExtraMode, Mode}; use clap::{App, Arg, ArgGroup}; use std::fmt::Display; use std::fs::File; use std::io::prelude::*; use std::io; use std::process::exit; use std::str::FromStr; const DEFAULT_CAPACITY: usize = 1024; trait ExpectExit<T> { fn expect_exit(self) -> T; } impl<T, E> ExpectExit<T> for Result<T, E> where E: Display, { fn expect_exit(self) -> T { match self { Ok(t) => t, Err(e) => { eprintln!("error: {}", e); exit(1); } } } } fn reg_names<T, I>(cs: &Capstone, regs: T) -> String where T: Iterator<Item = I>, I: Into<RegId>, { let names: Vec<String> = regs.map(|x| cs.reg_name(x.into()).unwrap()).collect(); names.join(", ") } fn group_names<T, I>(cs: &Capstone, regs: T) -> String where T: Iterator<Item = I>, I: Into<InsnGroupId>, { let names: Vec<String> = regs.map(|x| cs.group_name(x.into()).unwrap()).collect(); names.join(", ") } fn unhexed_bytes(input: Vec<u8>) -> Vec<u8> { let mut output: Vec<u8> = Vec::new(); let mut curr_byte_str = String::with_capacity(2); for b_u8 in input { let b = char::from(b_u8); if ('0' <= b && b <= '9') || ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') { curr_byte_str.push(b); } if curr_byte_str.len() == 2 { debug!(" curr_byte_str={:?}", curr_byte_str); let byte = u8::from_str_radix(&curr_byte_str, 16).expect("Unexpect hex parse error"); output.push(byte); curr_byte_str.clear(); } } if log::max_level() >= log::LevelFilter::Info { let output_hex: Vec<String> = output.iter().map(|x| format!("{:02x}", x)).collect(); info!("unhexed_output = {:?}", output_hex); } output } fn disasm<T: Iterator<Item = ExtraMode>>( arch: Arch, mode: Mode, extra_mode: T, endian: Option<Endian>, code: &[u8], addr: u64, show_detail: bool, ) { info!("Got {} bytes", code.len()); let mut cs = Capstone::new_raw(arch, mode, extra_mode, endian).expect_exit(); if show_detail { cs.set_detail(true).expect("Failed to set detail"); } let stdout = io::stdout(); let mut handle = stdout.lock(); for i in cs.disasm_all(code, addr).expect_exit().iter() { let bytes: Vec<_> = i.bytes().iter().map(|x| format!("{:02x}", x)).collect(); let bytes = bytes.join(" "); writeln!( &mut handle, "{:-10x}: {:35} {:7} {}", i.address(), bytes, i.mnemonic().unwrap(), i.op_str().unwrap_or("") ).is_ok(); if show_detail { let detail = cs.insn_detail(&i).expect("Failed to get insn detail"); let output: &[(&str, String)] = &[ ("insn id:", format!("{:?}", i.id().0)), ("read regs:", reg_names(&cs, detail.regs_read())), ("write regs:", reg_names(&cs, detail.regs_write())), ("insn groups:", group_names(&cs, detail.groups())), ]; for &(ref name, ref message) in output.iter() { writeln!(&mut handle, "{:13}{:12} {}", "", name, message).is_ok(); } } } } fn main() { let _arches: Vec<String> = Arch::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let arches: Vec<&str> = _arches.iter().map(|x| x.as_str()).collect(); let _modes: Vec<String> = Mode::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let modes: Vec<&str> = _modes.iter().map(|x| x.as_str()).collect(); let _extra_modes: Vec<String> = ExtraMode::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let extra_modes: Vec<&str> = _extra_modes.iter().map(|x| x.as_str()).collect(); let matches = App::new("capstone-rs disassembler tool") .about("Disassembles binary file") .arg( Arg::with_name("file") .short("f") .long("file") .help("input file with binary instructions") .takes_value(true), ) .arg( Arg::with_name("stdin") .short("s") .long("stdin") .help("read binary instructions from stdin") .takes_value(false), ) .arg( Arg::with_name("code") .short("c") .long("code") .help("instruction bytes (implies --hex)") .takes_value(true), ) .arg( Arg::with_name("address") .short("r") .long("addr") .help("address of code") .takes_value(true), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity"), ) .arg( Arg::with_name("hex") .short("x") .long("hex") .help("Treat input has hex; only select characters that are [a-fA-F0-9]") .takes_value(false), ) .arg( Arg::with_name("DETAIL") .short("d") .long("detail") .help("Print details about instructions") .takes_value(false), ) .arg( Arg::with_name("ARCH") .short("a") .long("arch") .help("Architecture") .takes_value(true) .required(true) .possible_values(arches.as_slice()) .case_insensitive(true), ) .arg( Arg::with_name("MODE") .short("m") .long("mode") .help("Mode") .takes_value(true) .required(true) .possible_values(modes.as_slice()) .case_insensitive(true), ) .arg( Arg::with_name("EXTRA_MODE") .short("e") .long("extra") .help("Extra Mode") .takes_value(true) .required(false) .possible_values(extra_modes.as_slice()) .case_insensitive(true) .multiple(true), ) .arg( Arg::with_name("ENDIAN") .short("n") .long("endian") .help("Endianness") .takes_value(true) .required(false) .possible_values(&["little", "big"]) .case_insensitive(true), ) .group( ArgGroup::with_name("INPUT") .arg("file") .arg("stdin") .arg("code") .required(true), ) .get_matches(); let direct_input_bytes: Vec<u8> = if let Some(file_path) = matches.value_of("file") { let mut file = File::open(file_path).expect_exit(); let capacity = match file.metadata() { Err(_) => DEFAULT_CAPACITY, Ok(metadata) => metadata.len() as usize, }; let mut buf = Vec::with_capacity(capacity as usize); file.read_to_end(&mut buf).expect_exit(); buf } else if let Some(code) = matches.value_of("code") { code.as_bytes().iter().map(|x| *x).collect() } else { let mut buf = Vec::with_capacity(DEFAULT_CAPACITY); let stdin = std::io::stdin(); stdin.lock().read_to_end(&mut buf).expect_exit(); buf }; stderrlog::new() .verbosity(matches.occurrences_of("v") as usize) .init() .unwrap(); let is_hex = matches.is_present("hex") || matches.is_present("code"); info!("is_hex = {:?}", is_hex); let show_detail = matches.is_present("DETAIL"); info!("show_detail = {:?}", show_detail); let arch: Arch = Arch::from_str(matches.value_of("ARCH").unwrap()) .unwrap() .into(); info!("Arch = {:?}", arch); let mode: Mode = Mode::from_str(matches.value_of("MODE").unwrap()) .unwrap() .into(); info!("Mode = {:?}", mode); let extra_mode: Vec<_> = match matches.values_of("EXTRA_MODE") { None => Vec::with_capacity(0), Some(x) => x .map(|x| ExtraMode::from(ExtraMode::from_str(x).unwrap())) .collect(), }; info!("ExtraMode = {:?}", extra_mode); let endian: Option<Endian> = matches .value_of("ENDIAN") .map(|x| Endian::from_str(x).expect_exit()); info!("Endian = {:?}", endian); let address = u64::from_str_radix(matches.value_of("address").unwrap_or("1000"), 16).expect_exit(); info!("Address = 0x{:x}", address); let input_bytes = if is_hex { unhexed_bytes(direct_input_bytes) } else { direct_input_bytes }; disasm( arch, mode, extra_mode.iter().map(|x| *x), endian, input_bytes.as_slice(), address, show_detail, ); }
extern crate capstone; extern crate clap; #[macro_use] extern crate log; extern crate stderrlog; use capstone::prelude::*; use capstone::{Arch, Endian, EnumList, ExtraMode, Mode}; use clap::{App, Arg, ArgGroup}; use std::fmt::Display; use std::fs::File; use std::io::prelude::*; use std::io; use std::process::exit; use std::str::FromStr; const DEFAULT_CAPACITY: usize = 1024; trait ExpectExit<T> { fn expect_exit(self) -> T; } impl<T, E> ExpectExit<T> for Result<T, E> where E: Display, { fn expect_exit(self) -> T { match self { Ok(t) => t, Err(e) => { eprintln!("error: {}", e); exit(1); } } } } fn reg_names<T, I>(cs: &Capstone, regs: T) -> String where T: Iterator<Item = I>, I: Into<RegId>, { let names: Vec<String> = regs.map(|x| cs.reg_name(x.into()).unwrap()).collect(); names.join(", ") } fn group_names<T, I>(cs: &Capstone, regs: T) -> String where T: Iterator<Item = I>, I: Into<InsnGroupId>, { let names: Vec<String> = regs.map(|x| cs.group_name(x.into()).unwrap()).collect(); names.join(", ") } fn unhexed_bytes(input: Vec<u8>) -> Vec<u8> { let mut output: Vec<u8> = Vec::new(); let mut curr_byte_str = String::with_capacity(2); for b_u8 in input { let b = char::from(b_u8); if ('0' <= b && b <= '9') || ('a' <= b && b <= 'f') || ('A' <= b && b <= 'F') { curr_byte_str.push(b); } if curr_byte_str.len() == 2 { debug!(" curr_byte_str={:?}", curr_byte_str); let byte = u8::from_str_radix(&curr_byte_str, 16).expect("Unexpect hex parse error"); output.push(byte); curr_byte_str.clear(); } } if log::max_level() >= log::LevelFilter::Info { let output_hex: Vec<String> = output.iter().map(|x| format!("{:02x}", x)).collect(); info!("unhexed_output = {:?}", output_hex); } output } fn disasm<T: Iterator<Item = ExtraMode>>( arch: Arch, mode: Mode, extra_mode: T, endian: Option<Endian>, code: &[u8], addr: u64, show_detail: bool, ) { info!("Got {} bytes", code.len()); let mut cs = Capstone::new_raw(arch, mode, extra_mode, endian).expect_exit(); if show_detail { cs.set_detail(true).expect("Failed to set detail"); } let stdout = io::stdout(); let mut handle = stdout.lock(); for i in cs.disasm_all(code, addr).expect_exit().iter() { let bytes: Vec<_> = i.bytes().iter().map(|x| format!("{:02x}", x)).collect(); let bytes = bytes.join(" "); writeln!( &mut handle, "{:-10x}: {:35} {:7} {}", i.address(), bytes, i.mnemonic().unwrap(), i.op_str().
("code") .required(true), ) .get_matches(); let direct_input_bytes: Vec<u8> = if let Some(file_path) = matches.value_of("file") { let mut file = File::open(file_path).expect_exit(); let capacity = match file.metadata() { Err(_) => DEFAULT_CAPACITY, Ok(metadata) => metadata.len() as usize, }; let mut buf = Vec::with_capacity(capacity as usize); file.read_to_end(&mut buf).expect_exit(); buf } else if let Some(code) = matches.value_of("code") { code.as_bytes().iter().map(|x| *x).collect() } else { let mut buf = Vec::with_capacity(DEFAULT_CAPACITY); let stdin = std::io::stdin(); stdin.lock().read_to_end(&mut buf).expect_exit(); buf }; stderrlog::new() .verbosity(matches.occurrences_of("v") as usize) .init() .unwrap(); let is_hex = matches.is_present("hex") || matches.is_present("code"); info!("is_hex = {:?}", is_hex); let show_detail = matches.is_present("DETAIL"); info!("show_detail = {:?}", show_detail); let arch: Arch = Arch::from_str(matches.value_of("ARCH").unwrap()) .unwrap() .into(); info!("Arch = {:?}", arch); let mode: Mode = Mode::from_str(matches.value_of("MODE").unwrap()) .unwrap() .into(); info!("Mode = {:?}", mode); let extra_mode: Vec<_> = match matches.values_of("EXTRA_MODE") { None => Vec::with_capacity(0), Some(x) => x .map(|x| ExtraMode::from(ExtraMode::from_str(x).unwrap())) .collect(), }; info!("ExtraMode = {:?}", extra_mode); let endian: Option<Endian> = matches .value_of("ENDIAN") .map(|x| Endian::from_str(x).expect_exit()); info!("Endian = {:?}", endian); let address = u64::from_str_radix(matches.value_of("address").unwrap_or("1000"), 16).expect_exit(); info!("Address = 0x{:x}", address); let input_bytes = if is_hex { unhexed_bytes(direct_input_bytes) } else { direct_input_bytes }; disasm( arch, mode, extra_mode.iter().map(|x| *x), endian, input_bytes.as_slice(), address, show_detail, ); }
unwrap_or("") ).is_ok(); if show_detail { let detail = cs.insn_detail(&i).expect("Failed to get insn detail"); let output: &[(&str, String)] = &[ ("insn id:", format!("{:?}", i.id().0)), ("read regs:", reg_names(&cs, detail.regs_read())), ("write regs:", reg_names(&cs, detail.regs_write())), ("insn groups:", group_names(&cs, detail.groups())), ]; for &(ref name, ref message) in output.iter() { writeln!(&mut handle, "{:13}{:12} {}", "", name, message).is_ok(); } } } } fn main() { let _arches: Vec<String> = Arch::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let arches: Vec<&str> = _arches.iter().map(|x| x.as_str()).collect(); let _modes: Vec<String> = Mode::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let modes: Vec<&str> = _modes.iter().map(|x| x.as_str()).collect(); let _extra_modes: Vec<String> = ExtraMode::variants() .iter() .map(|x| format!("{}", x).to_lowercase()) .collect(); let extra_modes: Vec<&str> = _extra_modes.iter().map(|x| x.as_str()).collect(); let matches = App::new("capstone-rs disassembler tool") .about("Disassembles binary file") .arg( Arg::with_name("file") .short("f") .long("file") .help("input file with binary instructions") .takes_value(true), ) .arg( Arg::with_name("stdin") .short("s") .long("stdin") .help("read binary instructions from stdin") .takes_value(false), ) .arg( Arg::with_name("code") .short("c") .long("code") .help("instruction bytes (implies --hex)") .takes_value(true), ) .arg( Arg::with_name("address") .short("r") .long("addr") .help("address of code") .takes_value(true), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity"), ) .arg( Arg::with_name("hex") .short("x") .long("hex") .help("Treat input has hex; only select characters that are [a-fA-F0-9]") .takes_value(false), ) .arg( Arg::with_name("DETAIL") .short("d") .long("detail") .help("Print details about instructions") .takes_value(false), ) .arg( Arg::with_name("ARCH") .short("a") .long("arch") .help("Architecture") .takes_value(true) .required(true) .possible_values(arches.as_slice()) .case_insensitive(true), ) .arg( Arg::with_name("MODE") .short("m") .long("mode") .help("Mode") .takes_value(true) .required(true) .possible_values(modes.as_slice()) .case_insensitive(true), ) .arg( Arg::with_name("EXTRA_MODE") .short("e") .long("extra") .help("Extra Mode") .takes_value(true) .required(false) .possible_values(extra_modes.as_slice()) .case_insensitive(true) .multiple(true), ) .arg( Arg::with_name("ENDIAN") .short("n") .long("endian") .help("Endianness") .takes_value(true) .required(false) .possible_values(&["little", "big"]) .case_insensitive(true), ) .group( ArgGroup::with_name("INPUT") .arg("file") .arg("stdin") .arg
random
[ { "content": "/// Disassemble code and print information\n\nfn arch_example(cs: &mut Capstone, code: &[u8]) -> CsResult<()> {\n\n let insns = cs.disasm_all(code, 0x1000)?;\n\n println!(\"Found {} instructions\", insns.len());\n\n for i in insns.iter() {\n\n println!();\n\n println!(\"{}\"...
Rust
compiler/context.rs
mwatts/arret
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
use crate::hir::PackagePaths; use crate::rfi; use crate::source::SourceLoader; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::{hash, path}; use codespan_reporting::diagnostic::Diagnostic; use arret_syntax::datum::Datum; use arret_syntax::span::{FileId, Span}; use crate::hir; use crate::hir::exports::Exports; use crate::hir::import; use crate::hir::loader::{LoadedModule, ModuleName}; use crate::hir::lowering::LoweredModule; use crate::promise::PromiseMap; use crate::reporting::diagnostic_for_syntax_error; use crate::reporting::errors_to_diagnostics; use crate::source::SourceFile; use crate::ty; use crate::typeck::infer; new_global_id_type!( ModuleId, u32, std::sync::atomic::AtomicU32, std::num::NonZeroU32 ); pub(crate) type ModuleImports = HashMap<ModuleName, Arc<Module>>; pub struct LinkedLibrary { _loaded: libloading::Library, target_path: Box<path::Path>, } impl LinkedLibrary { pub fn target_path(&self) -> &path::Path { &self.target_path } } pub(crate) struct Module { pub module_id: ModuleId, pub imports: ModuleImports, pub defs: Vec<hir::Def<hir::Inferred>>, pub inferred_locals: Arc<HashMap<hir::LocalId, ty::Ref<ty::Poly>>>, pub exports: Exports, pub main_local_id: Option<hir::LocalId>, pub linked_library: Option<Arc<LinkedLibrary>>, } impl PartialEq for Module { fn eq(&self, other: &Self) -> bool { self.module_id == other.module_id } } impl Eq for Module {} impl hash::Hash for Module { fn hash<H: hash::Hasher>(&self, state: &mut H) { state.write_u32(self.module_id.get()); } } type CachedModule = Result<Arc<Module>, Vec<Diagnostic<FileId>>>; type UncachedModule = Result<Module, Vec<Diagnostic<FileId>>>; fn transitive_deps(imports: &ModuleImports) -> HashSet<Arc<Module>> { let mut all_deps: HashSet<Arc<Module>> = imports.values().cloned().collect(); for import in imports.values() { all_deps.extend(transitive_deps(&import.imports).into_iter()); } all_deps } pub(crate) fn prims_to_module(exports: Exports) -> Module { Module { module_id: ModuleId::alloc(), imports: HashMap::new(), defs: vec![], inferred_locals: Arc::new(HashMap::new()), exports, main_local_id: None, linked_library: None, } } fn rfi_library_to_module(span: Span, rfi_library: rfi::Library) -> Module { use crate::hir::var_id::LocalIdAlloc; use crate::ty::Ty; use arret_syntax::datum::DataStr; let rfi::Library { loaded, target_path, exported_funs, } = rfi_library; let mut lia = LocalIdAlloc::new(); let mut exports = HashMap::with_capacity(exported_funs.len()); let mut defs = Vec::with_capacity(exported_funs.len()); let mut inferred_locals = HashMap::with_capacity(exported_funs.len()); for (fun_name, rust_fun) in exported_funs.into_vec().into_iter() { let local_id = lia.alloc_mut(); let arret_type: ty::Ref<ty::Poly> = Ty::Fun(Box::new(rust_fun.arret_fun_type().clone())).into(); let fun_name_data_str: DataStr = fun_name.into(); let def = hir::Def::<hir::Inferred> { span, macro_invocation_span: None, destruc: hir::destruc::Destruc::Scalar( span, hir::destruc::Scalar::new( Some(local_id), fun_name_data_str.clone(), arret_type.clone(), ), ), value_expr: hir::Expr { result_ty: arret_type.clone(), kind: hir::ExprKind::RustFun(rust_fun), }, }; defs.push(def); inferred_locals.insert(local_id, arret_type); exports.insert(fun_name_data_str, hir::scope::Binding::Var(None, local_id)); } Module { module_id: ModuleId::alloc(), imports: HashMap::new(), defs, inferred_locals: Arc::new(inferred_locals), exports, main_local_id: None, linked_library: Some(Arc::new(LinkedLibrary { _loaded: loaded, target_path, })), } } pub struct CompileCtx { package_paths: PackagePaths, enable_optimisations: bool, source_loader: SourceLoader, rfi_loader: rfi::Loader, modules_by_name: PromiseMap<ModuleName, CachedModule>, } impl CompileCtx { pub fn new(package_paths: PackagePaths, enable_optimisations: bool) -> Self { use crate::hir::exports; use std::iter; let initial_modules = iter::once(("primitives", exports::prims_exports())) .chain(iter::once(("types", exports::tys_exports()))) .map(|(terminal_name, exports)| { let prims_module = prims_to_module(exports); ( ModuleName::new( "arret".into(), vec!["internal".into()], (*terminal_name).into(), ), Ok(Arc::new(prims_module)), ) }); Self { package_paths, enable_optimisations, source_loader: SourceLoader::new(), rfi_loader: rfi::Loader::new(), modules_by_name: PromiseMap::new(initial_modules), } } pub fn package_paths(&self) -> &PackagePaths { &self.package_paths } pub fn enable_optimisations(&self) -> bool { self.enable_optimisations } pub fn source_loader(&self) -> &SourceLoader { &self.source_loader } pub(crate) fn rfi_loader(&self) -> &rfi::Loader { &self.rfi_loader } fn get_module_by_name(&self, span: Span, module_name: ModuleName) -> CachedModule { self.modules_by_name .get_or_insert_with( module_name.clone(), move || match hir::loader::load_module_by_name(self, span, &module_name) { Ok(LoadedModule::Source(source_file)) => { self.source_file_to_module(&source_file).map(Arc::new) } Ok(LoadedModule::Rust(rfi_library)) => { Ok(Arc::new(rfi_library_to_module(span, rfi_library))) } Err(err) => Err(vec![err.into()]), }, ) } pub(crate) fn source_file_to_module(&self, source_file: &SourceFile) -> UncachedModule { let data = source_file .parsed() .map_err(|err| vec![diagnostic_for_syntax_error(&err)])?; self.data_to_module(data) } pub(crate) fn imports_for_data<'a>( &self, data: impl Iterator<Item = &'a Datum>, ) -> Result<ModuleImports, Vec<Diagnostic<FileId>>> { let imported_module_names = import::collect_imported_module_names(data).map_err(errors_to_diagnostics)?; let import_count = imported_module_names.len(); let loaded_module_results: Vec<(ModuleName, CachedModule)> = imported_module_names .into_iter() .map(|(module_name, span)| { let module = self.get_module_by_name(span, module_name.clone()); (module_name, module) }) .collect(); let mut diagnostics = Vec::<Diagnostic<FileId>>::new(); let mut imports = HashMap::<ModuleName, Arc<Module>>::with_capacity(import_count); for (module_name, loaded_module_result) in loaded_module_results { match loaded_module_result { Ok(module) => { imports.insert(module_name, module); } Err(mut new_diagnostics) => diagnostics.append(&mut new_diagnostics), } } if !diagnostics.is_empty() { return Err(diagnostics); } Ok(imports) } fn data_to_module(&self, data: &[Datum]) -> UncachedModule { let imports = self.imports_for_data(data.iter())?; let lowered_module = hir::lowering::lower_data(&imports, data).map_err(errors_to_diagnostics)?; let LoweredModule { defs: lowered_defs, exports, main_local_id, } = lowered_module; let imported_inferred_vars = transitive_deps(&imports) .into_iter() .map(|module| (module.module_id, module.inferred_locals.clone())) .collect(); let inferred_module = infer::infer_module(&imported_inferred_vars, lowered_defs) .map_err(errors_to_diagnostics)?; let infer::InferredModule { defs: inferred_defs, inferred_locals, } = inferred_module; Ok(Module { module_id: ModuleId::alloc(), imports, defs: inferred_defs, inferred_locals: Arc::new(inferred_locals), exports, main_local_id, linked_library: None, }) } }
use crate::hir::PackagePaths; use crate::rfi; use crate::source::SourceLoader; use std::collections::{HashMap, HashSet}; use std::sync::Arc; use std::{hash, path}; use codespan_reporting::diagnostic::Diagnostic; use arret_syntax::datum::Datum; use arret_syntax::span::{FileId, Span}; use crate::hir; use crate::hir::exports::Exports; use crate::hir::import; use crate::hir::loader::{LoadedModule, ModuleName}; use crate::hir::lowering::LoweredModule; use crate::promise::PromiseMap; use crate::reporting::diagnostic_for_syntax_error; use crate::reporting::errors_to_diagnostics; use crate::source::SourceFile; use crate::ty; use crate::typeck::infer; new_global_id_type!( ModuleId, u32, std::sync::atomic::AtomicU32, std::num::NonZeroU32 ); pub(crate) type ModuleImports = HashMap<ModuleName, Arc<Module>>; pub struct LinkedLibrary { _loaded: libloading::Library, target_path: Box<path::Path>, } impl LinkedLibrary { pub fn target_path(&self) -> &path::Path { &self.target_path } } pub(crate) struct Module { pub module_id: ModuleId, pub imports: ModuleImports, pub defs: Vec<hir::Def<hir::Inferred>>, pub inferred_locals: Arc<HashMap<hir::LocalId, ty::Ref<ty::Poly>>>, pub exports: Exports, pub main_local_id: Option<hir::LocalId>, pub linked_library: Option<Arc<LinkedLibrary>>, } impl PartialEq for Module { fn eq(&self, other: &Self) -> bool { self.module_id == other.module_id } } impl Eq for Module {} impl hash::Hash for Module { fn hash<H: hash::Hasher>(&self, state: &mut H) { state.write_u32(self.module_id.get()); } } type CachedModule = Result<Arc<Module>, Vec<Diagnostic<FileId>>>; type UncachedModule = Result<Module, Vec<Diagnostic<FileId>>>; fn transitive_deps(imports: &ModuleImports) -> HashSet<Arc<Module>> { let mut all_deps: HashSet<Arc<Module>> = imports.values().cloned().collect(); for import in imports.values() { all_deps.extend(transitive_deps(&import.imports).into_iter()); } all_deps } pub(crate) fn prims_to_module(exports: Exports) -> Module { Module { module_id: ModuleId::alloc(), imports: HashMap::new(), defs: vec![], inferred_locals: Arc::new(HashMap::new()), exports, main_local_id: None, linked_library: None, } } fn rfi_library_to_module(span: Span, rfi_library: rfi::Library) -> Module { use crate::hir::var_id::LocalIdAlloc; use crate::ty::Ty; use arret_syntax::datum::DataStr; let rfi::Library { loaded, target_path, exported_funs, } = rfi_library; let mut lia = LocalIdAlloc::new(); let mut exports = HashMap::with_capacity(exported_funs.len()); let mut defs = Vec::with_capacity(exported_funs.len()); let mut inferred_locals = HashMap::with_capacity(exported_funs.len()); for (fun_name, rust_fun) in exported_funs.into_vec().into_iter() { let local_id = lia.alloc_mut(); let arret_type: ty::Ref<ty::Poly> = Ty::Fun(Box::new(rust_fun.arret_fun_type().clone())).into(); let fun_name_data_str: DataStr = fun_name.into();
defs.push(def); inferred_locals.insert(local_id, arret_type); exports.insert(fun_name_data_str, hir::scope::Binding::Var(None, local_id)); } Module { module_id: ModuleId::alloc(), imports: HashMap::new(), defs, inferred_locals: Arc::new(inferred_locals), exports, main_local_id: None, linked_library: Some(Arc::new(LinkedLibrary { _loaded: loaded, target_path, })), } } pub struct CompileCtx { package_paths: PackagePaths, enable_optimisations: bool, source_loader: SourceLoader, rfi_loader: rfi::Loader, modules_by_name: PromiseMap<ModuleName, CachedModule>, } impl CompileCtx { pub fn new(package_paths: PackagePaths, enable_optimisations: bool) -> Self { use crate::hir::exports; use std::iter; let initial_modules = iter::once(("primitives", exports::prims_exports())) .chain(iter::once(("types", exports::tys_exports()))) .map(|(terminal_name, exports)| { let prims_module = prims_to_module(exports); ( ModuleName::new( "arret".into(), vec!["internal".into()], (*terminal_name).into(), ), Ok(Arc::new(prims_module)), ) }); Self { package_paths, enable_optimisations, source_loader: SourceLoader::new(), rfi_loader: rfi::Loader::new(), modules_by_name: PromiseMap::new(initial_modules), } } pub fn package_paths(&self) -> &PackagePaths { &self.package_paths } pub fn enable_optimisations(&self) -> bool { self.enable_optimisations } pub fn source_loader(&self) -> &SourceLoader { &self.source_loader } pub(crate) fn rfi_loader(&self) -> &rfi::Loader { &self.rfi_loader } fn get_module_by_name(&self, span: Span, module_name: ModuleName) -> CachedModule { self.modules_by_name .get_or_insert_with( module_name.clone(), move || match hir::loader::load_module_by_name(self, span, &module_name) { Ok(LoadedModule::Source(source_file)) => { self.source_file_to_module(&source_file).map(Arc::new) } Ok(LoadedModule::Rust(rfi_library)) => { Ok(Arc::new(rfi_library_to_module(span, rfi_library))) } Err(err) => Err(vec![err.into()]), }, ) } pub(crate) fn source_file_to_module(&self, source_file: &SourceFile) -> UncachedModule { let data = source_file .parsed() .map_err(|err| vec![diagnostic_for_syntax_error(&err)])?; self.data_to_module(data) } pub(crate) fn imports_for_data<'a>( &self, data: impl Iterator<Item = &'a Datum>, ) -> Result<ModuleImports, Vec<Diagnostic<FileId>>> { let imported_module_names = import::collect_imported_module_names(data).map_err(errors_to_diagnostics)?; let import_count = imported_module_names.len(); let loaded_module_results: Vec<(ModuleName, CachedModule)> = imported_module_names .into_iter() .map(|(module_name, span)| { let module = self.get_module_by_name(span, module_name.clone()); (module_name, module) }) .collect(); let mut diagnostics = Vec::<Diagnostic<FileId>>::new(); let mut imports = HashMap::<ModuleName, Arc<Module>>::with_capacity(import_count); for (module_name, loaded_module_result) in loaded_module_results { match loaded_module_result { Ok(module) => { imports.insert(module_name, module); } Err(mut new_diagnostics) => diagnostics.append(&mut new_diagnostics), } } if !diagnostics.is_empty() { return Err(diagnostics); } Ok(imports) } fn data_to_module(&self, data: &[Datum]) -> UncachedModule { let imports = self.imports_for_data(data.iter())?; let lowered_module = hir::lowering::lower_data(&imports, data).map_err(errors_to_diagnostics)?; let LoweredModule { defs: lowered_defs, exports, main_local_id, } = lowered_module; let imported_inferred_vars = transitive_deps(&imports) .into_iter() .map(|module| (module.module_id, module.inferred_locals.clone())) .collect(); let inferred_module = infer::infer_module(&imported_inferred_vars, lowered_defs) .map_err(errors_to_diagnostics)?; let infer::InferredModule { defs: inferred_defs, inferred_locals, } = inferred_module; Ok(Module { module_id: ModuleId::alloc(), imports, defs: inferred_defs, inferred_locals: Arc::new(inferred_locals), exports, main_local_id, linked_library: None, }) } }
let def = hir::Def::<hir::Inferred> { span, macro_invocation_span: None, destruc: hir::destruc::Destruc::Scalar( span, hir::destruc::Scalar::new( Some(local_id), fun_name_data_str.clone(), arret_type.clone(), ), ), value_expr: hir::Expr { result_ty: arret_type.clone(), kind: hir::ExprKind::RustFun(rust_fun), }, };
assignment_statement
[ { "content": "/// Adds internal member fields common to all inline and external records\n\npub fn append_common_internal_members(tcx: &mut TargetCtx, members: &mut Vec<LLVMTypeRef>) {\n\n unsafe {\n\n members.extend_from_slice(&[\n\n // is_inline\n\n LLVMInt8TypeInContext(tcx.llx...
Rust
tests/category_dist_sums.rs
bostontrader/bookwerx-core-rust
35f8ac82b22399ffb1ae0eabc4dcd186395d9fc3
use bookwerx_core_rust::db as D; use rocket::http::Status; use rocket::local::Client; use bookwerx_core_rust::dfp::dfp::{DFP, Sign, dfp_abs, dfp_add}; pub fn category_dist_sums(client: &Client, apikey: &String, categories: &Vec<D::Category>) -> () { let mut response = client .get(format!( "/category_dist_sums?apikey={}&category_id=666", &apikey )) .dispatch(); let mut r: D::Sums = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 0); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![2, 1], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_start=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![9], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![7], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_start=2020-12&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![4], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![2, 1], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_start=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![9], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![7], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_start=2020-12&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![4], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&decorate=false", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); let r: D::Sums = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&decorate=true", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); let r: D::SumsDecorated = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); }
use bookwerx_core_rust::db as D; use rocket::http::Status; use rocket::local::Client; use bookwerx_core_rust::dfp::dfp::{DFP, Sign, dfp_abs, dfp_add};
pub fn category_dist_sums(client: &Client, apikey: &String, categories: &Vec<D::Category>) -> () { let mut response = client .get(format!( "/category_dist_sums?apikey={}&category_id=666", &apikey )) .dispatch(); let mut r: D::Sums = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 0); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![2, 1], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_start=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![9], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![7], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={},{}&time_start=2020-12&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id, (categories.get(3).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 1); assert_eq!(r.sums[0].sum, DFP { amount: vec![4], exp: 0, sign: Sign::Positive }); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![2, 1], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_start=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![9], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![7], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&time_start=2020-12&time_stop=2020-12", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); r = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); assert_eq!(dfp_abs(&(r.sums[0].sum) ), DFP { amount: vec![4], exp: 0, sign: Sign::Positive }); assert_eq!( dfp_add( r.sums[0].sum.clone(), r.sums[1].sum.clone()), DFP { amount: vec![], exp: 0, sign: Sign::Zero } ); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&decorate=false", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); let r: D::Sums = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); response = client .get(format!( "/category_dist_sums?apikey={}&category_id={}&decorate=true", &apikey, (categories.get(0).unwrap()).id )) .dispatch(); let r: D::SumsDecorated = serde_json::from_str(&(response.body_string().unwrap())[..]).unwrap(); assert_eq!(response.status(), Status::Ok); assert_eq!(r.sums.len(), 2); }
function_block-full_function
[ { "content": "use bookwerx_core_rust::db as D;\n\nuse rocket::http::Status;\n\nuse rocket::local::Client;\n\nuse bookwerx_core_rust::dfp::dfp::{DFP, Sign};\n\n\n", "file_path": "tests/account_dist_sum.rs", "rank": 0, "score": 8.044035556254066 }, { "content": "use bookwerx_core_rust::dfp::df...
Rust
src/vdac0/opa2_cal.rs
timokroeger/efm32pg12-pac
bbe43a716047334a3cd51de8e0e3d51280497689
#[doc = "Reader of register OPA2_CAL"] pub type R = crate::R<u32, super::OPA2_CAL>; #[doc = "Writer for register OPA2_CAL"] pub type W = crate::W<u32, super::OPA2_CAL>; #[doc = "Register OPA2_CAL `reset()`'s with value 0x80e7"] impl crate::ResetValue for super::OPA2_CAL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x80e7 } } #[doc = "Reader of field `CM1`"] pub type CM1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM1`"] pub struct CM1_W<'a> { w: &'a mut W, } impl<'a> CM1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `CM2`"] pub type CM2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM2`"] pub struct CM2_W<'a> { w: &'a mut W, } impl<'a> CM2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 5)) | (((value as u32) & 0x0f) << 5); self.w } } #[doc = "Reader of field `CM3`"] pub type CM3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM3`"] pub struct CM3_W<'a> { w: &'a mut W, } impl<'a> CM3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10); self.w } } #[doc = "Reader of field `GM`"] pub type GM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `GM`"] pub struct GM_W<'a> { w: &'a mut W, } impl<'a> GM_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 & !(0x07 << 13)) | (((value as u32) & 0x07) << 13); self.w } } #[doc = "Reader of field `GM3`"] pub type GM3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `GM3`"] pub struct GM3_W<'a> { w: &'a mut W, } impl<'a> GM3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 17)) | (((value as u32) & 0x03) << 17); self.w } } #[doc = "Reader of field `OFFSETP`"] pub type OFFSETP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OFFSETP`"] pub struct OFFSETP_W<'a> { w: &'a mut W, } impl<'a> OFFSETP_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 & !(0x1f << 20)) | (((value as u32) & 0x1f) << 20); self.w } } #[doc = "Reader of field `OFFSETN`"] pub type OFFSETN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OFFSETN`"] pub struct OFFSETN_W<'a> { w: &'a mut W, } impl<'a> OFFSETN_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 & !(0x1f << 26)) | (((value as u32) & 0x1f) << 26); self.w } } impl R { #[doc = "Bits 0:3 - Compensation Cap Cm1 Trim Value"] #[inline(always)] pub fn cm1(&self) -> CM1_R { CM1_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 5:8 - Compensation Cap Cm2 Trim Value"] #[inline(always)] pub fn cm2(&self) -> CM2_R { CM2_R::new(((self.bits >> 5) & 0x0f) as u8) } #[doc = "Bits 10:11 - Compensation Cap Cm3 Trim Value"] #[inline(always)] pub fn cm3(&self) -> CM3_R { CM3_R::new(((self.bits >> 10) & 0x03) as u8) } #[doc = "Bits 13:15 - Gm Trim Value"] #[inline(always)] pub fn gm(&self) -> GM_R { GM_R::new(((self.bits >> 13) & 0x07) as u8) } #[doc = "Bits 17:18 - Gm3 Trim Value"] #[inline(always)] pub fn gm3(&self) -> GM3_R { GM3_R::new(((self.bits >> 17) & 0x03) as u8) } #[doc = "Bits 20:24 - OPAx Non-Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetp(&self) -> OFFSETP_R { OFFSETP_R::new(((self.bits >> 20) & 0x1f) as u8) } #[doc = "Bits 26:30 - OPAx Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetn(&self) -> OFFSETN_R { OFFSETN_R::new(((self.bits >> 26) & 0x1f) as u8) } } impl W { #[doc = "Bits 0:3 - Compensation Cap Cm1 Trim Value"] #[inline(always)] pub fn cm1(&mut self) -> CM1_W { CM1_W { w: self } } #[doc = "Bits 5:8 - Compensation Cap Cm2 Trim Value"] #[inline(always)] pub fn cm2(&mut self) -> CM2_W { CM2_W { w: self } } #[doc = "Bits 10:11 - Compensation Cap Cm3 Trim Value"] #[inline(always)] pub fn cm3(&mut self) -> CM3_W { CM3_W { w: self } } #[doc = "Bits 13:15 - Gm Trim Value"] #[inline(always)] pub fn gm(&mut self) -> GM_W { GM_W { w: self } } #[doc = "Bits 17:18 - Gm3 Trim Value"] #[inline(always)] pub fn gm3(&mut self) -> GM3_W { GM3_W { w: self } } #[doc = "Bits 20:24 - OPAx Non-Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetp(&mut self) -> OFFSETP_W { OFFSETP_W { w: self } } #[doc = "Bits 26:30 - OPAx Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetn(&mut self) -> OFFSETN_W { OFFSETN_W { w: self } } }
#[doc = "Reader of register OPA2_CAL"] pub type R = crate::R<u32, super::OPA2_CAL>; #[doc = "Writer for register OPA2_CAL"] pub type W = crate::W<u32, super::OPA2_CAL>; #[doc = "Register OPA2_CAL `reset()`'s with value 0x80e7"] impl crate::ResetValue for super::OPA2_CAL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x80e7 } } #[doc = "Reader of field `CM1`"] pub type CM1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM1`"] pub struct CM1_W<'a> { w: &'a mut W, } impl<'a> CM1_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `CM2`"] pub type CM2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM2`"] pub struct CM2_W<'a> { w: &'a mut W, } impl<'a> CM2_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 5)) | (((value as u32) & 0x0f) << 5); self.w } } #[doc = "Reader of field `CM3`"] pub type CM3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CM3`"] pub struct CM3_W<'a> { w: &'a mut W, } impl<'a> CM3_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10); self.w } } #[doc = "Reader of field `GM`"] pub type GM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `GM`"] pub struct GM_W<'a> { w: &'a mut W, } impl<'a> GM_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 & !(0x07 << 13)) | (((value as u32) & 0x07) << 13); self.w } } #[doc = "Reader of field `GM3`"] pub type GM3_R = crate::R<u8, u8>; #[doc = "Write proxy for field `GM3`"] pub struct GM3_W<'a> { w: &'a mut W, } impl<'a> GM3_W<'a> { #[doc = r"Writes raw bits to the field"] #
self } } #[doc = "Bits 17:18 - Gm3 Trim Value"] #[inline(always)] pub fn gm3(&mut self) -> GM3_W { GM3_W { w: self } } #[doc = "Bits 20:24 - OPAx Non-Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetp(&mut self) -> OFFSETP_W { OFFSETP_W { w: self } } #[doc = "Bits 26:30 - OPAx Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetn(&mut self) -> OFFSETN_W { OFFSETN_W { w: self } } }
[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 17)) | (((value as u32) & 0x03) << 17); self.w } } #[doc = "Reader of field `OFFSETP`"] pub type OFFSETP_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OFFSETP`"] pub struct OFFSETP_W<'a> { w: &'a mut W, } impl<'a> OFFSETP_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 & !(0x1f << 20)) | (((value as u32) & 0x1f) << 20); self.w } } #[doc = "Reader of field `OFFSETN`"] pub type OFFSETN_R = crate::R<u8, u8>; #[doc = "Write proxy for field `OFFSETN`"] pub struct OFFSETN_W<'a> { w: &'a mut W, } impl<'a> OFFSETN_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 & !(0x1f << 26)) | (((value as u32) & 0x1f) << 26); self.w } } impl R { #[doc = "Bits 0:3 - Compensation Cap Cm1 Trim Value"] #[inline(always)] pub fn cm1(&self) -> CM1_R { CM1_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 5:8 - Compensation Cap Cm2 Trim Value"] #[inline(always)] pub fn cm2(&self) -> CM2_R { CM2_R::new(((self.bits >> 5) & 0x0f) as u8) } #[doc = "Bits 10:11 - Compensation Cap Cm3 Trim Value"] #[inline(always)] pub fn cm3(&self) -> CM3_R { CM3_R::new(((self.bits >> 10) & 0x03) as u8) } #[doc = "Bits 13:15 - Gm Trim Value"] #[inline(always)] pub fn gm(&self) -> GM_R { GM_R::new(((self.bits >> 13) & 0x07) as u8) } #[doc = "Bits 17:18 - Gm3 Trim Value"] #[inline(always)] pub fn gm3(&self) -> GM3_R { GM3_R::new(((self.bits >> 17) & 0x03) as u8) } #[doc = "Bits 20:24 - OPAx Non-Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetp(&self) -> OFFSETP_R { OFFSETP_R::new(((self.bits >> 20) & 0x1f) as u8) } #[doc = "Bits 26:30 - OPAx Inverting Input Offset Configuration Value"] #[inline(always)] pub fn offsetn(&self) -> OFFSETN_R { OFFSETN_R::new(((self.bits >> 26) & 0x1f) as u8) } } impl W { #[doc = "Bits 0:3 - Compensation Cap Cm1 Trim Value"] #[inline(always)] pub fn cm1(&mut self) -> CM1_W { CM1_W { w: self } } #[doc = "Bits 5:8 - Compensation Cap Cm2 Trim Value"] #[inline(always)] pub fn cm2(&mut self) -> CM2_W { CM2_W { w: self } } #[doc = "Bits 10:11 - Compensation Cap Cm3 Trim Value"] #[inline(always)] pub fn cm3(&mut self) -> CM3_W { CM3_W { w: self } } #[doc = "Bits 13:15 - Gm Trim Value"] #[inline(always)] pub fn gm(&mut self) -> GM_W { GM_W { w:
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/uu/sort/src/merge.rs
oconnor663/coreutils
c7930a63f7221a6b0e3791c15529e6b10de07ef2
use std::{ cmp::Ordering, ffi::OsStr, io::{Read, Write}, iter, rc::Rc, sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}, thread, }; use compare::Compare; use crate::{ chunks::{self, Chunk}, compare_by, open, GlobalSettings, }; pub fn merge<'a>(files: &[impl AsRef<OsStr>], settings: &'a GlobalSettings) -> FileMerger<'a> { let (request_sender, request_receiver) = channel(); let mut reader_files = Vec::with_capacity(files.len()); let mut loaded_receivers = Vec::with_capacity(files.len()); for (file_number, file) in files.iter().filter_map(open).enumerate() { let (sender, receiver) = sync_channel(2); loaded_receivers.push(receiver); reader_files.push(ReaderFile { file, sender: Some(sender), carry_over: vec![], }); request_sender .send((file_number, Chunk::new(vec![0; 8 * 1024], |_| Vec::new()))) .unwrap(); } for file_number in 0..reader_files.len() { request_sender .send((file_number, Chunk::new(vec![0; 8 * 1024], |_| Vec::new()))) .unwrap(); } thread::spawn({ let settings = settings.clone(); move || { reader( request_receiver, &mut reader_files, &settings, if settings.zero_terminated { b'\0' } else { b'\n' }, ) } }); let mut mergeable_files = vec![]; for (file_number, receiver) in loaded_receivers.into_iter().enumerate() { mergeable_files.push(MergeableFile { current_chunk: Rc::new(receiver.recv().unwrap()), file_number, line_idx: 0, receiver, }) } FileMerger { heap: binary_heap_plus::BinaryHeap::from_vec_cmp( mergeable_files, FileComparator { settings }, ), request_sender, prev: None, } } struct ReaderFile { file: Box<dyn Read + Send>, sender: Option<SyncSender<Chunk>>, carry_over: Vec<u8>, } fn reader( recycled_receiver: Receiver<(usize, Chunk)>, files: &mut [ReaderFile], settings: &GlobalSettings, separator: u8, ) { for (file_idx, chunk) in recycled_receiver.iter() { let (recycled_lines, recycled_buffer) = chunk.recycle(); let ReaderFile { file, sender, carry_over, } = &mut files[file_idx]; chunks::read( sender, recycled_buffer, None, carry_over, file, &mut iter::empty(), separator, recycled_lines, settings, ); } } pub struct MergeableFile { current_chunk: Rc<Chunk>, line_idx: usize, receiver: Receiver<Chunk>, file_number: usize, } struct PreviousLine { chunk: Rc<Chunk>, line_idx: usize, file_number: usize, } pub struct FileMerger<'a> { heap: binary_heap_plus::BinaryHeap<MergeableFile, FileComparator<'a>>, request_sender: Sender<(usize, Chunk)>, prev: Option<PreviousLine>, } impl<'a> FileMerger<'a> { pub fn write_all(&mut self, settings: &GlobalSettings) { let mut out = settings.out_writer(); while self.write_next(settings, &mut out) {} } fn write_next(&mut self, settings: &GlobalSettings, out: &mut impl Write) -> bool { if let Some(file) = self.heap.peek() { let prev = self.prev.replace(PreviousLine { chunk: file.current_chunk.clone(), line_idx: file.line_idx, file_number: file.file_number, }); file.current_chunk.with_lines(|lines| { let current_line = &lines[file.line_idx]; if settings.unique { if let Some(prev) = &prev { let cmp = compare_by( &prev.chunk.borrow_lines()[prev.line_idx], current_line, settings, ); if cmp == Ordering::Equal { return; } } } current_line.print(out, settings); }); let was_last_line_for_file = file.current_chunk.borrow_lines().len() == file.line_idx + 1; if was_last_line_for_file { if let Ok(next_chunk) = file.receiver.recv() { let mut file = self.heap.peek_mut().unwrap(); file.current_chunk = Rc::new(next_chunk); file.line_idx = 0; } else { self.heap.pop(); } } else { self.heap.peek_mut().unwrap().line_idx += 1; } if let Some(prev) = prev { if let Ok(prev_chunk) = Rc::try_unwrap(prev.chunk) { self.request_sender .send((prev.file_number, prev_chunk)) .ok(); } } } !self.heap.is_empty() } } struct FileComparator<'a> { settings: &'a GlobalSettings, } impl<'a> Compare<MergeableFile> for FileComparator<'a> { fn compare(&self, a: &MergeableFile, b: &MergeableFile) -> Ordering { let mut cmp = compare_by( &a.current_chunk.borrow_lines()[a.line_idx], &b.current_chunk.borrow_lines()[b.line_idx], self.settings, ); if cmp == Ordering::Equal { cmp = a.file_number.cmp(&b.file_number); } cmp.reverse() } }
use std::{ cmp::Ordering, ffi::OsStr, io::{Read, Write}, iter, rc::Rc, sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}, thread, }; use compare::Compare; use crate::{ chunks::{self, Chunk}, compare_by, open, GlobalSettings, }; pub fn merge<'a>(files: &[impl AsRef<OsStr>], settings: &'a GlobalSettings) -> FileMerger<'a> { let (request_sender, request_receiver) = channel(); let mut reader_files = Vec::with_capacity(files.len()); let mut loaded_receivers = Vec::with_capacity(files.len()); for (file_number, file) in files.iter().filter_map(open).enumerate() { let (sender, receiver) = sync_channel(2); loaded_receivers.push(receiver); reader_files.push(ReaderFile { file, sender: Some(sender), carry_over: vec![], }); request_sender .send((file_number, Chunk::new(vec![0; 8 * 1024], |_| Vec::new()))) .unwrap(); } for file_number in 0..reader_files.len() { request_sender .send((file_number, Chunk::new(vec![0; 8 * 1024], |_| Vec::new()))) .unwrap(); } thread::spawn({ let settings = settings.clone(); move || { reader( request_receiver, &mut reader_files, &settings, if settings.zero_terminated { b'\0' } else { b'\n' }, ) } }); let mut mergeable_files = vec![]; for (file_number, receiver) in loaded_receivers.into_iter().enumerate() { mergeable_files.push(MergeableFile { current_chunk: Rc::new(receiver.recv().unwrap()), file_number, line_idx: 0, receiver, }) } FileMerger { heap: binary_heap_plus::BinaryHeap::from_vec_cmp( mergeable_files, FileComparator { settings }, ), request_sender, prev: None, } } struct ReaderFile { file: Box<dyn Read + Send>, sender: Option<SyncSender<Chunk>>, carry_over: Vec<u8>, } fn reader( recycled_receiver: Receiver<(usize, Chunk)>, files: &mut [ReaderFile], settings: &GlobalSettings, separator: u8, ) { for (file_idx, chunk) in recycled_receiver.iter() { let (recycled_lines, recycled_buffer) = chunk.recycle(); let ReaderFile { file, sender, carry_over, } = &mut files[file_idx]; chunks::read( sender, recycled_buffer, None, carry_over, file, &mut iter::empty(), separator, recycled_lines, settings, ); } } pub struct MergeableFile { current_chunk: Rc<Chunk>, line_idx: usize, receiver: Receiver<Chunk>, file_number: usize, } struct PreviousLine { chunk: Rc<Chunk>, line_idx: usize, file_number: usize, } pub struct FileMerger<'a> { heap: binary_heap_plus::BinaryHeap<MergeableFile, FileComparator<'a>>, request_sender: Sender<(usize, Chunk)>, prev: Option<PreviousLine>, } impl<'a> FileMerger<'a> { pub fn write_all(&mut self, settings: &GlobalSettings) { let mut out = settings.out_writer(); while self.write_next(settings, &mut out) {} } fn write_next(&mut self, settings: &GlobalSettings, out: &mut impl Write) -> bool { if let Some(file) = self.heap.peek() { let prev = self.prev.replace(PreviousLine { chunk: file.current_chunk.clone(), line_idx: file.line_idx, file_number: file.file_number, }); file.current_chunk.with_lines(|lines| { let current_line = &lines[file.line_idx]; if settings.unique { if let Some(prev) = &prev { let cmp = compare_by( &prev.chunk.borrow_lines()[prev.line_idx], current_line, settings, ); if cmp == Ordering::Equal { return; } } } current_line.print(out, settings); }); let was_last_line_for_file = file.current_chunk.borrow_lines().len() == file.line_idx + 1; if was_last_line_for_file { if let Ok(next_chunk) = file.receiver.recv() { let mut file = self.heap.peek_mut().unwrap(); file.current_chunk = Rc::new(next_chunk); file.line_idx = 0; } else { self.heap.pop(); } } else { self.heap.peek_mut().unwrap().line_idx += 1; } if let Some(prev) = prev { if let Ok(prev_chunk) = Rc::try_unwrap(prev.chunk) { self.request_sender .send((prev.file_number, prev_chunk)) .ok(); } } } !self.heap.is_empty() } } struct FileComparator<'a> { settings: &'a GlobalSettings, } impl<'a> Compare<MergeableFile> for FileComparator<'a> { fn compare(&self, a: &MergeableFile, b: &MergeableFile) -> Ordering { let mut cmp =
; if cmp == Ordering::Equal { cmp = a.file_number.cmp(&b.file_number); } cmp.reverse() } }
compare_by( &a.current_chunk.borrow_lines()[a.line_idx], &b.current_chunk.borrow_lines()[b.line_idx], self.settings, )
call_expression
[ { "content": "/// Write the lines in `chunk` to `file`, separated by `separator`.\n\nfn write(chunk: &mut Chunk, file: &Path, separator: u8) {\n\n chunk.with_lines_mut(|lines| {\n\n // Write the lines to the file\n\n let file = crash_if_err!(1, OpenOptions::new().create(true).write(true).open(f...
Rust
router/src/dml_handlers/partitioner.rs
r4ntix/influxdb_iox
5ff874925101e2afbafa6853385260a2ba044394
use super::DmlHandler; use async_trait::async_trait; use data_types::{DatabaseName, DeletePredicate, PartitionTemplate}; use hashbrown::HashMap; use mutable_batch::{MutableBatch, PartitionWrite, WritePayload}; use observability_deps::tracing::*; use thiserror::Error; use trace::ctx::SpanContext; #[derive(Debug, Error)] pub enum PartitionError { #[error("error batching into partitioned write: {0}")] BatchWrite(#[from] mutable_batch::Error), } #[derive(Debug, PartialEq, Clone)] pub struct Partitioned<T> { key: String, payload: T, } impl<T> Partitioned<T> { pub fn new(key: String, payload: T) -> Self { Self { key, payload } } pub fn payload(&self) -> &T { &self.payload } pub fn into_parts(self) -> (String, T) { (self.key, self.payload) } } #[derive(Debug)] pub struct Partitioner { partition_template: PartitionTemplate, } impl Partitioner { pub fn new(partition_template: PartitionTemplate) -> Self { Self { partition_template } } } #[async_trait] impl DmlHandler for Partitioner { type WriteError = PartitionError; type DeleteError = PartitionError; type WriteInput = HashMap<String, MutableBatch>; type WriteOutput = Vec<Partitioned<Self::WriteInput>>; async fn write( &self, _namespace: &DatabaseName<'static>, batch: Self::WriteInput, _span_ctx: Option<SpanContext>, ) -> Result<Self::WriteOutput, Self::WriteError> { let mut partitions: HashMap<_, HashMap<_, MutableBatch>> = HashMap::default(); for (table_name, batch) in batch { for (partition_key, partition_payload) in PartitionWrite::partition(&table_name, &batch, &self.partition_template) { let partition = partitions.entry(partition_key).or_default(); let table_batch = partition .raw_entry_mut() .from_key(&table_name) .or_insert_with(|| (table_name.to_owned(), MutableBatch::default())); partition_payload.write_to_batch(table_batch.1)?; } } Ok(partitions .into_iter() .map(|(key, batch)| Partitioned { key, payload: batch, }) .collect::<Vec<_>>()) } async fn delete( &self, _namespace: &DatabaseName<'static>, _table_name: &str, _predicate: &DeletePredicate, _span_ctx: Option<SpanContext>, ) -> Result<(), Self::DeleteError> { Ok(()) } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use data_types::TemplatePart; const DEFAULT_TIMESTAMP_NANOS: i64 = 42000000000000000; macro_rules! test_write { ( $name:ident, lp = $lp:expr, want_writes = [$($want_writes:tt)*], want_handler_ret = $($want_handler_ret:tt)+ ) => { paste::paste! { #[tokio::test] async fn [<test_write_ $name>]() { let partition_template = PartitionTemplate { parts: vec![TemplatePart::TimeFormat("%Y-%m-%d".to_owned())], }; let partitioner = Partitioner::new(partition_template); let ns = DatabaseName::new("bananas").expect("valid db name"); let (writes, _) = mutable_batch_lp::lines_to_batches_stats($lp, DEFAULT_TIMESTAMP_NANOS).expect("failed to parse test LP"); let handler_ret = partitioner.write(&ns, writes, None).await; assert_matches!(handler_ret, $($want_handler_ret)+); let got = handler_ret.unwrap_or_default() .into_iter() .map(|partition| { let mut tables = partition .payload .keys() .cloned() .collect::<Vec<String>>(); tables.sort(); (partition.key.clone(), tables) }) .collect::<HashMap<_, _>>(); test_write!(@assert_writes, got, $($want_writes)*); } } }; (@assert_writes, $got:ident, unchecked) => { let _x = $got; }; (@assert_writes, $got:ident, $($partition_key:expr => $want_tables:expr, )*) => { #[allow(unused_mut)] let mut want_writes: HashMap<String, _> = Default::default(); $( let mut want: Vec<String> = $want_tables.into_iter().map(|t| t.to_string()).collect(); want.sort(); want_writes.insert($partition_key.to_string(), want); )* pretty_assertions::assert_eq!(want_writes, $got); }; } test_write!( single_partition, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 2\n\ another,tag1=A,tag2=B value=42i 3\n\ bananas,tag1=A,tag2=B val=42i 2\n\ table,tag1=A,tag2=B val=42i 1\n\ ", want_writes = [ "1970-01-01" => ["bananas", "platanos", "another", "table"], ], want_handler_ret = Ok(_) ); test_write!( multiple_partitions, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 1465839830100400200\n\ another,tag1=A,tag2=B value=42i 1465839830100400200\n\ bananas,tag1=A,tag2=B val=42i 2\n\ table,tag1=A,tag2=B val=42i 1644347270670952000\n\ ", want_writes = [ "1970-01-01" => ["bananas"], "2016-06-13" => ["platanos", "another"], "2022-02-08" => ["table"], ], want_handler_ret = Ok(_) ); test_write!( multiple_partitions_upserted, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 1465839830100400200\n\ platanos,tag1=A,tag2=B value=42i 1\n\ bananas,tag1=A,tag2=B value=42i 1465839830100400200\n\ bananas,tag1=A,tag2=B value=42i 1465839830100400200\n\ ", want_writes = [ "1970-01-01" => ["bananas", "platanos"], "2016-06-13" => ["bananas", "platanos"], ], want_handler_ret = Ok(_) ); }
use super::DmlHandler; use async_trait::async_trait; use data_types::{DatabaseName, DeletePredicate, PartitionTemplate}; use hashbrown::HashMap; use mutable_batch::{MutableBatch, PartitionWrite, WritePayload}; use observability_deps::tracing::*; use thiserror::Error; use trace::ctx::SpanContext; #[derive(Debug, Error)] pub enum PartitionError { #[error("error batching into partitioned write: {0}")] BatchWrite(#[from] mutable_batch::Error), } #[derive(Debug, PartialEq, Clone)] pub struct Partitioned<T> { key: String, payload: T, } impl<T> Partitioned<T> { pub fn new(key: String, payload: T) -> Self { Self { key, payload } } pub fn payload(&self) -> &T { &self.payload } pub fn into_parts(self) -> (String, T) { (self.key, self.payload) } } #[derive(Debug)] pub struct Partitioner { partition_template: PartitionTemplate, } impl Partitioner { pub fn new(partition_template: PartitionTemplate) -> Self { Self { partition_template } } } #[async_trait] impl DmlHandler for Partitioner { type WriteError = PartitionError; type DeleteError = PartitionError; type WriteInput = HashMap<String, MutableBatch>; type WriteOutput = Vec<Partitioned<Self::WriteInput>>; async fn write( &self, _namespace: &DatabaseName<'static>, batch: Self::WriteInput, _span_ctx: Option<SpanContext>, ) -> Result<Self::WriteOutput, Self::WriteError> { let mut partitions: HashMap<_, HashMap<_, MutableBatch>> = Hash
; let table_batch = partition .raw_entry_mut() .from_key(&table_name) .or_insert_with(|| (table_name.to_owned(), MutableBatch::default())); partition_payload.write_to_batch(table_batch.1)?; } } Ok(partitions .into_iter() .map(|(key, batch)| Partitioned { key, payload: batch, }) .collect::<Vec<_>>()) } async fn delete( &self, _namespace: &DatabaseName<'static>, _table_name: &str, _predicate: &DeletePredicate, _span_ctx: Option<SpanContext>, ) -> Result<(), Self::DeleteError> { Ok(()) } } #[cfg(test)] mod tests { use super::*; use assert_matches::assert_matches; use data_types::TemplatePart; const DEFAULT_TIMESTAMP_NANOS: i64 = 42000000000000000; macro_rules! test_write { ( $name:ident, lp = $lp:expr, want_writes = [$($want_writes:tt)*], want_handler_ret = $($want_handler_ret:tt)+ ) => { paste::paste! { #[tokio::test] async fn [<test_write_ $name>]() { let partition_template = PartitionTemplate { parts: vec![TemplatePart::TimeFormat("%Y-%m-%d".to_owned())], }; let partitioner = Partitioner::new(partition_template); let ns = DatabaseName::new("bananas").expect("valid db name"); let (writes, _) = mutable_batch_lp::lines_to_batches_stats($lp, DEFAULT_TIMESTAMP_NANOS).expect("failed to parse test LP"); let handler_ret = partitioner.write(&ns, writes, None).await; assert_matches!(handler_ret, $($want_handler_ret)+); let got = handler_ret.unwrap_or_default() .into_iter() .map(|partition| { let mut tables = partition .payload .keys() .cloned() .collect::<Vec<String>>(); tables.sort(); (partition.key.clone(), tables) }) .collect::<HashMap<_, _>>(); test_write!(@assert_writes, got, $($want_writes)*); } } }; (@assert_writes, $got:ident, unchecked) => { let _x = $got; }; (@assert_writes, $got:ident, $($partition_key:expr => $want_tables:expr, )*) => { #[allow(unused_mut)] let mut want_writes: HashMap<String, _> = Default::default(); $( let mut want: Vec<String> = $want_tables.into_iter().map(|t| t.to_string()).collect(); want.sort(); want_writes.insert($partition_key.to_string(), want); )* pretty_assertions::assert_eq!(want_writes, $got); }; } test_write!( single_partition, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 2\n\ another,tag1=A,tag2=B value=42i 3\n\ bananas,tag1=A,tag2=B val=42i 2\n\ table,tag1=A,tag2=B val=42i 1\n\ ", want_writes = [ "1970-01-01" => ["bananas", "platanos", "another", "table"], ], want_handler_ret = Ok(_) ); test_write!( multiple_partitions, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 1465839830100400200\n\ another,tag1=A,tag2=B value=42i 1465839830100400200\n\ bananas,tag1=A,tag2=B val=42i 2\n\ table,tag1=A,tag2=B val=42i 1644347270670952000\n\ ", want_writes = [ "1970-01-01" => ["bananas"], "2016-06-13" => ["platanos", "another"], "2022-02-08" => ["table"], ], want_handler_ret = Ok(_) ); test_write!( multiple_partitions_upserted, lp = "\ bananas,tag1=A,tag2=B val=42i 1\n\ platanos,tag1=A,tag2=B value=42i 1465839830100400200\n\ platanos,tag1=A,tag2=B value=42i 1\n\ bananas,tag1=A,tag2=B value=42i 1465839830100400200\n\ bananas,tag1=A,tag2=B value=42i 1465839830100400200\n\ ", want_writes = [ "1970-01-01" => ["bananas", "platanos"], "2016-06-13" => ["bananas", "platanos"], ], want_handler_ret = Ok(_) ); }
Map::default(); for (table_name, batch) in batch { for (partition_key, partition_payload) in PartitionWrite::partition(&table_name, &batch, &self.partition_template) { let partition = partitions.entry(partition_key).or_default()
function_block-random_span
[]
Rust
07-rust/stm32f446/stm32f446_pac/src/rcc/cr.rs
aaronhktan/stm32-exploration
dcd7674424cd17b02b85c6b3ce533456d5037d65
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x83"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x83 } } #[doc = "Reader of field `PLLI2SRDY`"] pub type PLLI2SRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `PLLI2SON`"] pub type PLLI2SON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLI2SON`"] pub struct PLLI2SON_W<'a> { w: &'a mut W, } impl<'a> PLLI2SON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `PLLRDY`"] pub type PLLRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `PLLON`"] pub type PLLON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLON`"] pub struct PLLON_W<'a> { w: &'a mut W, } impl<'a> PLLON_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 `CSSON`"] pub type CSSON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSSON`"] pub struct CSSON_W<'a> { w: &'a mut W, } impl<'a> CSSON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `HSEBYP`"] pub type HSEBYP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSEBYP`"] pub struct HSEBYP_W<'a> { w: &'a mut W, } impl<'a> HSEBYP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `HSERDY`"] pub type HSERDY_R = crate::R<bool, bool>; #[doc = "Reader of field `HSEON`"] pub type HSEON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSEON`"] pub struct HSEON_W<'a> { w: &'a mut W, } impl<'a> HSEON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `HSICAL`"] pub type HSICAL_R = crate::R<u8, u8>; #[doc = "Reader of field `HSITRIM`"] pub type HSITRIM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HSITRIM`"] pub struct HSITRIM_W<'a> { w: &'a mut W, } impl<'a> HSITRIM_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 & !(0x1f << 3)) | (((value as u32) & 0x1f) << 3); self.w } } #[doc = "Reader of field `HSIRDY`"] pub type HSIRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `HSION`"] pub type HSION_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSION`"] pub struct HSION_W<'a> { w: &'a mut W, } impl<'a> HSION_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 27 - PLLI2S clock ready flag"] #[inline(always)] pub fn plli2srdy(&self) -> PLLI2SRDY_R { PLLI2SRDY_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - PLLI2S enable"] #[inline(always)] pub fn plli2son(&self) -> PLLI2SON_R { PLLI2SON_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - Main PLL (PLL) clock ready flag"] #[inline(always)] pub fn pllrdy(&self) -> PLLRDY_R { PLLRDY_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - Main PLL (PLL) enable"] #[inline(always)] pub fn pllon(&self) -> PLLON_R { PLLON_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 19 - Clock security system enable"] #[inline(always)] pub fn csson(&self) -> CSSON_R { CSSON_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bits 8:15 - Internal high-speed clock calibration"] #[inline(always)] pub fn hsical(&self) -> HSICAL_R { HSICAL_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 3:7 - Internal high-speed clock trimming"] #[inline(always)] pub fn hsitrim(&self) -> HSITRIM_R { HSITRIM_R::new(((self.bits >> 3) & 0x1f) as u8) } #[doc = "Bit 1 - Internal high-speed clock ready flag"] #[inline(always)] pub fn hsirdy(&self) -> HSIRDY_R { HSIRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&self) -> HSION_R { HSION_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 26 - PLLI2S enable"] #[inline(always)] pub fn plli2son(&mut self) -> PLLI2SON_W { PLLI2SON_W { w: self } } #[doc = "Bit 24 - Main PLL (PLL) enable"] #[inline(always)] pub fn pllon(&mut self) -> PLLON_W { PLLON_W { w: self } } #[doc = "Bit 19 - Clock security system enable"] #[inline(always)] pub fn csson(&mut self) -> CSSON_W { CSSON_W { w: self } } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&mut self) -> HSEBYP_W { HSEBYP_W { w: self } } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&mut self) -> HSEON_W { HSEON_W { w: self } } #[doc = "Bits 3:7 - Internal high-speed clock trimming"] #[inline(always)] pub fn hsitrim(&mut self) -> HSITRIM_W { HSITRIM_W { w: self } } #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&mut self) -> HSION_W { HSION_W { w: self } } }
#[doc = "Reader of register CR"] pub type R = crate::R<u32, super::CR>; #[doc = "Writer for register CR"] pub type W = crate::W<u32, super::CR>; #[doc = "Register CR `reset()`'s with value 0x83"] impl crate::ResetValue for super::CR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x83 } } #[doc = "Reader of field `PLLI2SRDY`"] pub type PLLI2SRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `PLLI2SON`"] pub type PLLI2SON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLI2SON`"] pub struct PLLI2SON_W<'a> { w: &'a mut W, } impl<'a> PLLI2SON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "Reader of field `PLLRDY`"] pub type PLLRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `PLLON`"] pub type PLLON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLON`"] pub struct PLLON_W<'a> { w: &'a mut W, } impl<'a> PLLON_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 `CSSON`"] pub type CSSON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CSSON`"] pub struct CSSON_W<'a> { w: &'a mut W, } impl<'a> CSSON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `HSEBYP`"] pub type HSEBYP_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSEBYP`"] pub struct HSEBYP_W<'a> { w: &'a mut W, } impl<'a> HSEBYP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `HSERDY`"] pub type HSERDY_R = crate::R<bool, bool>; #[doc = "Reader of field `HSEON`"] pub type HSEON_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSEON`"] pub struct HSEON_W<'a> { w: &'a mut W, } impl<'a> HSEON_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `HSICAL`"] pub type HSICAL_R = crate::R<u8, u8>; #[doc = "Reader of field `HSITRIM`"] pub type HSITRIM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `HSITRIM`"] pub struct HSITRIM_W<'a> { w: &'a mut W, } impl<'a> HSITRIM_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 & !(0x1f << 3)) | (((value as u32) & 0x1f) << 3); self.w
18) & 0x01) != 0) } #[doc = "Bit 17 - HSE clock ready flag"] #[inline(always)] pub fn hserdy(&self) -> HSERDY_R { HSERDY_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&self) -> HSEON_R { HSEON_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bits 8:15 - Internal high-speed clock calibration"] #[inline(always)] pub fn hsical(&self) -> HSICAL_R { HSICAL_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 3:7 - Internal high-speed clock trimming"] #[inline(always)] pub fn hsitrim(&self) -> HSITRIM_R { HSITRIM_R::new(((self.bits >> 3) & 0x1f) as u8) } #[doc = "Bit 1 - Internal high-speed clock ready flag"] #[inline(always)] pub fn hsirdy(&self) -> HSIRDY_R { HSIRDY_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&self) -> HSION_R { HSION_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 26 - PLLI2S enable"] #[inline(always)] pub fn plli2son(&mut self) -> PLLI2SON_W { PLLI2SON_W { w: self } } #[doc = "Bit 24 - Main PLL (PLL) enable"] #[inline(always)] pub fn pllon(&mut self) -> PLLON_W { PLLON_W { w: self } } #[doc = "Bit 19 - Clock security system enable"] #[inline(always)] pub fn csson(&mut self) -> CSSON_W { CSSON_W { w: self } } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&mut self) -> HSEBYP_W { HSEBYP_W { w: self } } #[doc = "Bit 16 - HSE clock enable"] #[inline(always)] pub fn hseon(&mut self) -> HSEON_W { HSEON_W { w: self } } #[doc = "Bits 3:7 - Internal high-speed clock trimming"] #[inline(always)] pub fn hsitrim(&mut self) -> HSITRIM_W { HSITRIM_W { w: self } } #[doc = "Bit 0 - Internal high-speed clock enable"] #[inline(always)] pub fn hsion(&mut self) -> HSION_W { HSION_W { w: self } } }
} } #[doc = "Reader of field `HSIRDY`"] pub type HSIRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `HSION`"] pub type HSION_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HSION`"] pub struct HSION_W<'a> { w: &'a mut W, } impl<'a> HSION_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } impl R { #[doc = "Bit 27 - PLLI2S clock ready flag"] #[inline(always)] pub fn plli2srdy(&self) -> PLLI2SRDY_R { PLLI2SRDY_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 26 - PLLI2S enable"] #[inline(always)] pub fn plli2son(&self) -> PLLI2SON_R { PLLI2SON_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 25 - Main PLL (PLL) clock ready flag"] #[inline(always)] pub fn pllrdy(&self) -> PLLRDY_R { PLLRDY_R::new(((self.bits >> 25) & 0x01) != 0) } #[doc = "Bit 24 - Main PLL (PLL) enable"] #[inline(always)] pub fn pllon(&self) -> PLLON_R { PLLON_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 19 - Clock security system enable"] #[inline(always)] pub fn csson(&self) -> CSSON_R { CSSON_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - HSE clock bypass"] #[inline(always)] pub fn hsebyp(&self) -> HSEBYP_R { HSEBYP_R::new(((self.bits >>
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
06/chronal-manhattan/src/main.rs
mnem/advent-of-code-2018
f2f5821d29fcf111ef4c1ff963bc4636626781f6
extern crate regex; use std::fs; use std::cmp; use regex::Regex; fn main() { let input = read_input(); let result = process(&input); println!("Result: {}\n", result); } fn read_input() -> String { let input_filename = String::from("input.txt"); fs::read_to_string(input_filename) .expect("Failed to read file") } fn process(input: &str) -> i32 { let points = Point::from_lines(&input); let (max_x, max_y) = extent(&points); let mut scored_grids = Vec::new(); for point in points { let scored_grid = scored_grid_from(point, max_x, max_y); scored_grids.push(scored_grid); } let cell_count = (max_x * max_y) as usize; for cell_index in 0..cell_count { let mut min_score = i32::max_value(); for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; min_score = cmp::min(min_score, grid_cell_score); } let mut min_cells_seen = 0; for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; if min_score == grid_cell_score { min_cells_seen += 1; } } if min_cells_seen > 1 { for grid_index in 0..scored_grids.len() { scored_grids[grid_index][cell_index] = -1; } } else { for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; if grid_cell_score == min_score { continue; } scored_grids[grid_index][cell_index] = -1; } } } let mut areas = Vec::new(); for grid in &scored_grids { if grid_is_infinite(grid, max_x, max_y) { areas.push(0); continue; } let area = grid.iter().fold(0, |acc, value| { if *value >= 0 { return acc + 1; } else { return acc; } }); areas.push(area); } areas.sort(); return *areas.last().unwrap() as i32; } fn grid_is_infinite(grid: &Vec<i32>, extent_x: usize, extent_y: usize) -> bool { let max = extent_x * extent_y; let top_range = 0..extent_x; let bottom_range = (extent_x * (extent_y - 1))..max; for (top, bottom) in top_range.zip(bottom_range) { if grid[top] >= 0 || grid[bottom] >= 0 { return true; } } let left_range = (0 ..max).step_by(extent_x); let right_range = ((extent_x - 1)..max).step_by(extent_x); for (left, right) in left_range.zip(right_range) { if grid[left] >= 0 || grid[right] >= 0 { return true; } } return false; } fn scored_grid_from(point: Point, extent_x: usize, extend_y: usize) -> Vec<i32> { let mut scores = Vec::new(); for y in 0..extend_y { for x in 0..extent_x { let score = ((y as i32) - point.y).abs() + ((x as i32) - point.x).abs(); scores.push(score); } } return scores; } fn extent(points: &Vec<Point>) -> (usize, usize) { let mut max_x = 0; let mut max_y = 0; for point in points { max_x = cmp::max(max_x, point.x); max_y = cmp::max(max_y, point.y); } max_x += 1; max_y += 1; (max_x as usize, max_y as usize) } #[derive(Debug,PartialEq)] struct Point { x: i32, y: i32, } impl Point { fn from_string(string: &str) -> Point { let re = Regex::new(r"(?P<x>\d*)\D*(?P<y>\d*)").unwrap(); let captures = re.captures(string).unwrap(); return Point { x: captures["x"].parse().unwrap(), y: captures["y"].parse().unwrap() }; } fn from_lines(lines: &str) -> Vec<Point> { let mut points = Vec::new(); for line in lines.lines() { let line = line.trim(); if line.len() == 0 { continue; } points.push(Point::from_string(line)); } return points; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_point_from_string() { let subject = Point::from_string("1, 2"); assert_eq!(Point { x: 1, y: 2 }, subject); let subject = Point::from_string("100 , 25699"); assert_eq!(Point { x: 100, y: 25699 }, subject); } #[test] fn test_point_from_lines_trailing_newline() { let subject = Point::from_lines("1, 2\n3, 4\n5, 6\n"); let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},]; assert_eq!(expected, subject); } #[test] fn test_point_from_lines_trailing() { let subject = Point::from_lines("1, 2\n3, 4\n5, 6"); let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},]; assert_eq!(expected, subject); } #[test] fn test_extent() { let input = vec![Point {x: 0, y: 10}, Point {x: 20, y: 0}, Point {x: 19, y: 10},]; let (max_x, max_y) = extent(&input); assert_eq!(21, max_x); assert_eq!(11, max_y); } #[test] fn test_scored_grid_1() { let in_point = Point { x: 1, y: 1}; let extent_x = 3; let extent_y = 3; let result = scored_grid_from(in_point, extent_x, extent_y); let expected = vec![ 2, 1, 2, 1, 0, 1, 2, 1, 2, ]; assert_eq!(expected, result); } #[test] fn test_scored_grid_2() { let in_point = Point { x: 1, y: 1}; let extent_x = 5; let extent_y = 7; let result = scored_grid_from(in_point, extent_x, extent_y); let expected = vec![ 2, 1, 2, 3, 4, 1, 0, 1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 3, 4, 5, 4, 3, 4, 5, 6, 5, 4, 5, 6, 7, 6, 5, 6, 7, 8, ]; assert_eq!(expected, result); } #[test] fn test_grid_is_infinite_top() { let extent_x = 3; let extent_y = 3; let grid = vec![ 0, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, 0, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, 0, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_grid_is_infinite_centre() { let extent_x = 3; let extent_y = 3; let grid = vec![ -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(false, result); let grid = vec![ -1, -1, -1, -1, 0, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(false, result); } #[test] fn test_grid_is_infinite_bottom() { let extent_x = 3; let extent_y = 3; let grid = vec![ -1, -1, -1, -1, -1, -1, 0, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, -1, -1, -1, -1, 0, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, -1, -1, -1, -1, -1, 0, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_grid_is_infinite_left() { let extent_x = 3; let extent_y = 3; let grid = vec![ 0, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, 0, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, 0, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_example() { let input = "1, 1\n1, 6\n8, 3\n3, 4\n5, 5\n8, 9"; let result = process(input); assert_eq!(17, result); } }
extern crate regex; use std::fs; use std::cmp; use regex::Regex; fn main() { let input = read_input(); let result = process(&input); println!("Result: {}\n", result); } fn read_input() -> String { let input_filename = String::from("input.txt"); fs::read_to_string(input_filename) .expect("Failed to read file") } fn process(input: &str) -> i32 { let points = Point::from_lines(&input); let (max_x, max_y) = extent(&points); let mut scored_grids = Vec::new(); for point in points { let scored_grid = scored_grid_from(point, max_x, max_y); scored_grids.push(scored_grid); } let cell_count = (max_x * max_y) as usize; for cell_index in 0..cell_count { let mut min_score = i32::max_value(); for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; min_score = cmp::min(min_score, grid_cell_score); } let mut min_cells_seen = 0; for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; if min_score == grid_cell_score { min_cells_seen += 1; } } if min_cells_seen > 1 { for grid_index in 0..scored_grids.len() { scored_grids[grid_index][cell_index] = -1; } } else { for grid_index in 0..scored_grids.len() { let grid_cell_score = scored_grids[grid_index][cell_index]; if grid_cell_score == min_score { continue; } scored_grids[grid_index][cell_index] = -1; } } } let mut areas = Vec::new(); for grid in &scored_grids { if grid_is_infinite(grid, max_x, max_y) { areas.push(0); continue; } let area = grid.iter().fold(0, |acc, value| { if *value >= 0 { return acc + 1; } else { return acc; } }); areas.push(area); } areas.sort(); return *areas.last().unwrap() as i32; } fn grid_is_infinite(grid: &Vec<i32>, extent_x: usize, extent_y: usize) -> bool { let max = extent_x * extent_y; let top_range = 0..extent_x; let bottom_range = (extent_x * (extent_y - 1))..max; for (top, bottom) in top_range.zip(bottom_range) { if grid[top] >= 0 || grid[bottom] >= 0 { return true; } } let left_range = (0 ..max).step_by(extent_x); let right_range = ((extent_x - 1)..max).step_by(extent_x); for (left, right) in left_range.zip(right_range) { if grid[left] >= 0 || grid[right] >= 0 { return true; } } return false; } fn scored_grid_from(point: Point, extent_x: usize, extend_y: usize) -> Vec<i32> { let mut scores = Vec::new(); for y in 0..extend_y { for x in 0..extent_x { let score = ((y as i32) - point.y).abs() + ((x as i32) - point.x).abs(); scores.push(score); } } return scores; } fn extent(points: &Vec<Point>) -> (usize, usize) { let mut max_x = 0; let mut max_y = 0; for point in points { max_x = cmp::max(max_x, point.x); max_y = cmp::max(max_y, point.y); } max_x += 1; max_y += 1; (max_x as usize, max_y as usize) } #[derive(Debug,PartialEq)] struct Point { x: i32, y: i32, } impl Point { fn from_string(string: &str) -> Point { let re = Regex::new(r"(?P<x>\d*)\D*(?P<y>\d*)").unwrap(); let captures = re.captures(string).unwrap(); return Point { x: captures["x"].parse().unwrap(), y: captures["y"].parse().unwrap() };
te(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, 0, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, 0, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_grid_is_infinite_centre() { let extent_x = 3; let extent_y = 3; let grid = vec![ -1, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(false, result); let grid = vec![ -1, -1, -1, -1, 0, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(false, result); } #[test] fn test_grid_is_infinite_bottom() { let extent_x = 3; let extent_y = 3; let grid = vec![ -1, -1, -1, -1, -1, -1, 0, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, -1, -1, -1, -1, 0, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, -1, -1, -1, -1, -1, 0, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_grid_is_infinite_left() { let extent_x = 3; let extent_y = 3; let grid = vec![ 0, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, 0, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); let grid = vec![ -1, -1, -1, 0, -1, -1, -1, -1, -1, ]; let result = grid_is_infinite(&grid, extent_x, extent_y); assert_eq!(true, result); } #[test] fn test_example() { let input = "1, 1\n1, 6\n8, 3\n3, 4\n5, 5\n8, 9"; let result = process(input); assert_eq!(17, result); } }
} fn from_lines(lines: &str) -> Vec<Point> { let mut points = Vec::new(); for line in lines.lines() { let line = line.trim(); if line.len() == 0 { continue; } points.push(Point::from_string(line)); } return points; } } #[cfg(test)] mod tests { use super::*; #[test] fn test_point_from_string() { let subject = Point::from_string("1, 2"); assert_eq!(Point { x: 1, y: 2 }, subject); let subject = Point::from_string("100 , 25699"); assert_eq!(Point { x: 100, y: 25699 }, subject); } #[test] fn test_point_from_lines_trailing_newline() { let subject = Point::from_lines("1, 2\n3, 4\n5, 6\n"); let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},]; assert_eq!(expected, subject); } #[test] fn test_point_from_lines_trailing() { let subject = Point::from_lines("1, 2\n3, 4\n5, 6"); let expected = vec![Point {x: 1, y: 2},Point {x: 3, y: 4},Point {x: 5, y: 6},]; assert_eq!(expected, subject); } #[test] fn test_extent() { let input = vec![Point {x: 0, y: 10}, Point {x: 20, y: 0}, Point {x: 19, y: 10},]; let (max_x, max_y) = extent(&input); assert_eq!(21, max_x); assert_eq!(11, max_y); } #[test] fn test_scored_grid_1() { let in_point = Point { x: 1, y: 1}; let extent_x = 3; let extent_y = 3; let result = scored_grid_from(in_point, extent_x, extent_y); let expected = vec![ 2, 1, 2, 1, 0, 1, 2, 1, 2, ]; assert_eq!(expected, result); } #[test] fn test_scored_grid_2() { let in_point = Point { x: 1, y: 1}; let extent_x = 5; let extent_y = 7; let result = scored_grid_from(in_point, extent_x, extent_y); let expected = vec![ 2, 1, 2, 3, 4, 1, 0, 1, 2, 3, 2, 1, 2, 3, 4, 3, 2, 3, 4, 5, 4, 3, 4, 5, 6, 5, 4, 5, 6, 7, 6, 5, 6, 7, 8, ]; assert_eq!(expected, result); } #[test] fn test_grid_is_infinite_top() { let extent_x = 3; let extent_y = 3; let grid = vec![ 0, -1, -1, -1, -1, -1, -1, -1, -1, ]; let result = grid_is_infini
random
[ { "content": "fn scored_grid_from(point: Point, extent_x: usize, extend_y: usize) -> Vec<i32> {\n\n let mut scores = Vec::new();\n\n for y in 0..extend_y {\n\n for x in 0..extent_x {\n\n let score = ((y as i32) - point.y).abs() + ((x as i32) - point.x).abs();\n\n scores.push(s...
Rust
src/commands/kv/bucket/sync.rs
aleclarson/wrangler
37d0506a845d6122190b0a43865a59e839347c1b
use std::collections::HashSet; use std::fs::metadata; use std::iter::FromIterator; use std::path::Path; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; use crate::commands::kv; use crate::commands::kv::bucket::directory_keys_only; use crate::commands::kv::bucket::directory_keys_values; use crate::commands::kv::key::KeyList; use crate::settings::global_user::GlobalUser; use crate::settings::toml::Target; use crate::terminal::message; use super::manifest::AssetManifest; pub fn sync( target: &Target, user: &GlobalUser, namespace_id: &str, path: &Path, verbose: bool, ) -> Result<(Vec<KeyValuePair>, Vec<String>, AssetManifest), failure::Error> { kv::validate_target(target)?; let remote_keys_iter = KeyList::new(target, &user, namespace_id, None)?; let mut remote_keys: HashSet<String> = HashSet::new(); for remote_key in remote_keys_iter { match remote_key { Ok(remote_key) => { remote_keys.insert(remote_key.name); } Err(e) => failure::bail!(kv::format_error(e)), } } let (pairs, asset_manifest): (Vec<KeyValuePair>, AssetManifest) = directory_keys_values(target, path, verbose)?; let to_upload = filter_files(pairs, &remote_keys); let local_keys_vec: Vec<String> = match &metadata(path) { Ok(file_type) if file_type.is_dir() => directory_keys_only(target, path), Ok(_) => failure::bail!("{} should be a directory", path.display()), Err(e) => failure::bail!("{}", e), }?; let local_keys: HashSet<_> = HashSet::from_iter(local_keys_vec.into_iter()); let to_delete: Vec<_> = remote_keys .difference(&local_keys) .map(|key| key.to_owned()) .collect(); message::success("Success"); Ok((to_upload, to_delete, asset_manifest)) } fn filter_files(pairs: Vec<KeyValuePair>, already_uploaded: &HashSet<String>) -> Vec<KeyValuePair> { let mut filtered_pairs: Vec<KeyValuePair> = Vec::new(); for pair in pairs { if !already_uploaded.contains(&pair.key) { filtered_pairs.push(pair); } } filtered_pairs } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::path::Path; use crate::commands::kv::bucket::generate_path_and_key; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; #[test] fn it_can_filter_preexisting_files() { let (_, key_a_old) = generate_path_and_key(Path::new("/a"), Path::new("/"), Some("old".to_string())) .unwrap(); let (_, key_b_old) = generate_path_and_key(Path::new("/b"), Path::new("/"), Some("old".to_string())) .unwrap(); let (_, key_b_new) = generate_path_and_key(Path::new("/b"), Path::new("/"), Some("new".to_string())) .unwrap(); let mut exclude_keys = HashSet::new(); exclude_keys.insert(key_a_old.clone()); exclude_keys.insert(key_b_old); let pairs_to_upload = vec![ KeyValuePair { key: key_a_old, value: "old".to_string(), expiration_ttl: None, expiration: None, base64: None, }, KeyValuePair { key: key_b_new.clone(), value: "new".to_string(), expiration_ttl: None, expiration: None, base64: None, }, ]; let expected = vec![KeyValuePair { key: key_b_new, value: "new".to_string(), expiration_ttl: None, expiration: None, base64: None, }]; let actual = filter_files(pairs_to_upload, &exclude_keys); check_kv_pairs_equality(expected, actual); } fn check_kv_pairs_equality(expected: Vec<KeyValuePair>, actual: Vec<KeyValuePair>) { assert!(expected.len() == actual.len()); for (idx, pair) in expected.into_iter().enumerate() { assert!(pair.key == actual[idx].key); assert!(pair.value == actual[idx].value); } } }
use std::collections::HashSet; use std::fs::metadata; use std::iter::FromIterator; use std::path::Path; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; use crate::commands::kv; use crate::commands::kv::bucket::directory_keys_only; use crate::commands::kv::bucket::directory_keys_values; use crate::commands::kv::key::KeyList; use crate::settings::global_user::GlobalUser; use crate::settings::toml::Target; use crate::terminal::message; use super::manifest::AssetManifest; pub fn sync( target: &Target, user: &GlobalUser, namespace_id: &str, path: &Path, verbose: bool, ) -> Result<(Vec<KeyValuePair>, Vec<String>, AssetManifest), failure::Error> { kv::validate_target(target)?; let remote_keys_iter = KeyList::new(target, &user, namespace_id, None)?; let mut remote_keys: HashSet<String> = HashSet::new(); for remote_key in remote_keys_iter { match remote_key { Ok(remote_key) => { remote_keys.insert(remote_key.name); } Err(e) => failure::bail!(kv::format_error(e)), } } let (pairs, asset_manifest): (Vec<KeyValuePair>, AssetManifest) = directory_keys_values(target, path, verbose)?; let to_upload = filter_files(pairs, &remote_keys); let local_keys_vec: Vec<String> = match &metadata(path) { Ok(file_type) if file_type.is_dir() => directory_keys_only(target, path), Ok(_) => failure::bail!("{} should be a directory", path.display()), Err(e) => failure::bail!("{}", e), }?; let local_keys: HashSet<_> = HashSet::from_iter(local_keys_vec.into_iter()); let to_delete: Vec<_> = remote_keys .difference(&local_keys) .map(|key| key.to_owned()) .collect(); message::success("Success"); Ok((to_upload, to_delete, asset_manifest)) } fn filter_files(pairs: Vec<KeyValuePair>, already_uploaded: &HashSet<String>) -> Vec<KeyValuePair> { let mut filtered_pairs: Vec<KeyValuePair> = Vec::new(); for pair in pairs { if !already_uploaded.contains(&pair.key) { filtered_pairs.push(pair); } } filtered_pairs } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; use std::path::Path; use crate::commands::kv::bucket::generate_path_and_key; use cloudflare::endpoints::workerskv::write_bulk::KeyValuePair; #[test] fn it_can_filter_preexisting_files() { let (_, key_a_old) = generate_path_and_key(Path::new("/a"), Path::new("/"), Some("old".to_string())) .unwrap(); let (_, key_b_old) = generate_path_and_key(Path::new("/b"), Path::new("/"), Some("old".to_string())) .unwrap(); let (_, key_b_new) = generate_path_and_key(Path::new("/b"), Path::new("/"), Some("new".to_string())) .unwrap(); let mut exclude_ke
fn check_kv_pairs_equality(expected: Vec<KeyValuePair>, actual: Vec<KeyValuePair>) { assert!(expected.len() == actual.len()); for (idx, pair) in expected.into_iter().enumerate() { assert!(pair.key == actual[idx].key); assert!(pair.value == actual[idx].value); } } }
ys = HashSet::new(); exclude_keys.insert(key_a_old.clone()); exclude_keys.insert(key_b_old); let pairs_to_upload = vec![ KeyValuePair { key: key_a_old, value: "old".to_string(), expiration_ttl: None, expiration: None, base64: None, }, KeyValuePair { key: key_b_new.clone(), value: "new".to_string(), expiration_ttl: None, expiration: None, base64: None, }, ]; let expected = vec![KeyValuePair { key: key_b_new, value: "new".to_string(), expiration_ttl: None, expiration: None, base64: None, }]; let actual = filter_files(pairs_to_upload, &exclude_keys); check_kv_pairs_equality(expected, actual); }
function_block-function_prefixed
[ { "content": "pub fn create_secret(name: &str, user: &GlobalUser, target: &Target) -> Result<(), failure::Error> {\n\n validate_target(target)?;\n\n\n\n let secret_value = interactive::get_user_input(&format!(\n\n \"Enter the secret text you'd like assigned to the variable {} on the script named {}...
Rust
rust/src/cosmos/crypto/multisig.rs
PFC-Validator/terra.proto
4939cca497ba641046d18546dd234fd33a3f61c6
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(unused_results)] #[derive(PartialEq,Clone,Default)] pub struct MultiSignature { pub signatures: ::protobuf::RepeatedField<::std::vec::Vec<u8>>, pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a MultiSignature { fn default() -> &'a MultiSignature { <MultiSignature as ::protobuf::Message>::default_instance() } } impl MultiSignature { pub fn new() -> MultiSignature { ::std::default::Default::default() } pub fn get_signatures(&self) -> &[::std::vec::Vec<u8>] { &self.signatures } pub fn clear_signatures(&mut self) { self.signatures.clear(); } pub fn set_signatures(&mut self, v: ::protobuf::RepeatedField<::std::vec::Vec<u8>>) { self.signatures = v; } pub fn mut_signatures(&mut self) -> &mut ::protobuf::RepeatedField<::std::vec::Vec<u8>> { &mut self.signatures } pub fn take_signatures(&mut self) -> ::protobuf::RepeatedField<::std::vec::Vec<u8>> { ::std::mem::replace(&mut self.signatures, ::protobuf::RepeatedField::new()) } } impl ::protobuf::Message for MultiSignature { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_bytes_into(wire_type, is, &mut self.signatures)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.signatures { my_size += ::protobuf::rt::bytes_size(1, &value); }; my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.signatures { os.write_bytes(1, &v)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> MultiSignature { MultiSignature::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "signatures", |m: &MultiSignature| { &m.signatures }, |m: &mut MultiSignature| { &mut m.signatures }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<MultiSignature>( "MultiSignature", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static MultiSignature { static instance: ::protobuf::rt::LazyV2<MultiSignature> = ::protobuf::rt::LazyV2::INIT; instance.get(MultiSignature::new) } } impl ::protobuf::Clear for MultiSignature { fn clear(&mut self) { self.signatures.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for MultiSignature { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for MultiSignature { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct CompactBitArray { pub extra_bits_stored: u32, pub elems: ::std::vec::Vec<u8>, pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a CompactBitArray { fn default() -> &'a CompactBitArray { <CompactBitArray as ::protobuf::Message>::default_instance() } } impl CompactBitArray { pub fn new() -> CompactBitArray { ::std::default::Default::default() } pub fn get_extra_bits_stored(&self) -> u32 { self.extra_bits_stored } pub fn clear_extra_bits_stored(&mut self) { self.extra_bits_stored = 0; } pub fn set_extra_bits_stored(&mut self, v: u32) { self.extra_bits_stored = v; } pub fn get_elems(&self) -> &[u8] { &self.elems } pub fn clear_elems(&mut self) { self.elems.clear(); } pub fn set_elems(&mut self, v: ::std::vec::Vec<u8>) { self.elems = v; } pub fn mut_elems(&mut self) -> &mut ::std::vec::Vec<u8> { &mut self.elems } pub fn take_elems(&mut self) -> ::std::vec::Vec<u8> { ::std::mem::replace(&mut self.elems, ::std::vec::Vec::new()) } } impl ::protobuf::Message for CompactBitArray { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.extra_bits_stored = tmp; }, 2 => { ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.elems)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.extra_bits_stored != 0 { my_size += ::protobuf::rt::value_size(1, self.extra_bits_stored, ::protobuf::wire_format::WireTypeVarint); } if !self.elems.is_empty() { my_size += ::protobuf::rt::bytes_size(2, &self.elems); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if self.extra_bits_stored != 0 { os.write_uint32(1, self.extra_bits_stored)?; } if !self.elems.is_empty() { os.write_bytes(2, &self.elems)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> CompactBitArray { CompactBitArray::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "extra_bits_stored", |m: &CompactBitArray| { &m.extra_bits_stored }, |m: &mut CompactBitArray| { &mut m.extra_bits_stored }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "elems", |m: &CompactBitArray| { &m.elems }, |m: &mut CompactBitArray| { &mut m.elems }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<CompactBitArray>( "CompactBitArray", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static CompactBitArray { static instance: ::protobuf::rt::LazyV2<CompactBitArray> = ::protobuf::rt::LazyV2::INIT; instance.get(CompactBitArray::new) } } impl ::protobuf::Clear for CompactBitArray { fn clear(&mut self) { self.extra_bits_stored = 0; self.elems.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for CompactBitArray { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for CompactBitArray { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n-cosmos/crypto/multisig/v1beta1/multisig.proto\x12\x1ecosmos.crypto.mu\ ltisig.v1beta1\x1a\x14gogoproto/gogo.proto\"6\n\x0eMultiSignature\x12\ \x1e\n\nsignatures\x18\x01\x20\x03(\x0cR\nsignatures:\x04\xd0\xa1\x1f\ \x01\"Y\n\x0fCompactBitArray\x12*\n\x11extra_bits_stored\x18\x01\x20\x01\ (\rR\x0fextraBitsStored\x12\x14\n\x05elems\x18\x02\x20\x01(\x0cR\x05elem\ s:\x04\x98\xa0\x1f\0B+Z)github.com/cosmos/cosmos-sdk/crypto/typesb\x06pr\ oto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }
#![allow(unknown_lints)] #![allow(clippy::all)] #![allow(unused_attributes)] #![cfg_attr(rustfmt, rustfmt::skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] #![allow(unused_imports)] #![allow(unused_results)] #[derive(PartialEq,Clone,Default)] pub struct MultiSignature { pub signatures: ::protobuf::RepeatedField<::std::vec::Vec<u8>>, pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a MultiSignature { fn default() -> &'a MultiSignature { <MultiSignature as ::protobuf::Message>::default_instance() } } impl MultiSignature { pub fn new() -> MultiSignature { ::std::default::Default::default() } pub fn get_signatures(&self) -> &[::std::vec::Vec<u8>] { &self.signatures } pub fn clear_signatures(&mut self) { self.signatures.clear(); } pub fn set_signatures(&mut self, v: ::protobuf::RepeatedField<::std::vec::Vec<u8>>) { self.signatures = v; } pub fn mut_signatures(&mut self) -> &mut ::protobuf::RepeatedField<::std::vec::Vec<u8>> { &mut self.signatures } pub fn take_signatures(&mut self) -> ::protobuf::RepeatedField<::std::vec::Vec<u8>> { ::std::mem::replace(&mut self.signatures, ::protobuf::RepeatedField::new()) } } impl ::protobuf::Message for MultiSignature { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { ::protobuf::rt::read_repeated_bytes_into(wire_type, is, &mut self.signatures)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; for value in &self.signatures { my_size += ::protobuf::rt::bytes_size(1, &value); }; my_si
d }, |m: &mut CompactBitArray| { &mut m.extra_bits_stored }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "elems", |m: &CompactBitArray| { &m.elems }, |m: &mut CompactBitArray| { &mut m.elems }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<CompactBitArray>( "CompactBitArray", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static CompactBitArray { static instance: ::protobuf::rt::LazyV2<CompactBitArray> = ::protobuf::rt::LazyV2::INIT; instance.get(CompactBitArray::new) } } impl ::protobuf::Clear for CompactBitArray { fn clear(&mut self) { self.extra_bits_stored = 0; self.elems.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for CompactBitArray { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for CompactBitArray { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n-cosmos/crypto/multisig/v1beta1/multisig.proto\x12\x1ecosmos.crypto.mu\ ltisig.v1beta1\x1a\x14gogoproto/gogo.proto\"6\n\x0eMultiSignature\x12\ \x1e\n\nsignatures\x18\x01\x20\x03(\x0cR\nsignatures:\x04\xd0\xa1\x1f\ \x01\"Y\n\x0fCompactBitArray\x12*\n\x11extra_bits_stored\x18\x01\x20\x01\ (\rR\x0fextraBitsStored\x12\x14\n\x05elems\x18\x02\x20\x01(\x0cR\x05elem\ s:\x04\x98\xa0\x1f\0B+Z)github.com/cosmos/cosmos-sdk/crypto/typesb\x06pr\ oto3\ "; static file_descriptor_proto_lazy: ::protobuf::rt::LazyV2<::protobuf::descriptor::FileDescriptorProto> = ::protobuf::rt::LazyV2::INIT; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { file_descriptor_proto_lazy.get(|| { parse_descriptor_proto() }) }
ze += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { for v in &self.signatures { os.write_bytes(1, &v)?; }; os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> MultiSignature { MultiSignature::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_repeated_field_accessor::<_, ::protobuf::types::ProtobufTypeBytes>( "signatures", |m: &MultiSignature| { &m.signatures }, |m: &mut MultiSignature| { &mut m.signatures }, )); ::protobuf::reflect::MessageDescriptor::new_pb_name::<MultiSignature>( "MultiSignature", fields, file_descriptor_proto() ) }) } fn default_instance() -> &'static MultiSignature { static instance: ::protobuf::rt::LazyV2<MultiSignature> = ::protobuf::rt::LazyV2::INIT; instance.get(MultiSignature::new) } } impl ::protobuf::Clear for MultiSignature { fn clear(&mut self) { self.signatures.clear(); self.unknown_fields.clear(); } } impl ::std::fmt::Debug for MultiSignature { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for MultiSignature { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } #[derive(PartialEq,Clone,Default)] pub struct CompactBitArray { pub extra_bits_stored: u32, pub elems: ::std::vec::Vec<u8>, pub unknown_fields: ::protobuf::UnknownFields, pub cached_size: ::protobuf::CachedSize, } impl<'a> ::std::default::Default for &'a CompactBitArray { fn default() -> &'a CompactBitArray { <CompactBitArray as ::protobuf::Message>::default_instance() } } impl CompactBitArray { pub fn new() -> CompactBitArray { ::std::default::Default::default() } pub fn get_extra_bits_stored(&self) -> u32 { self.extra_bits_stored } pub fn clear_extra_bits_stored(&mut self) { self.extra_bits_stored = 0; } pub fn set_extra_bits_stored(&mut self, v: u32) { self.extra_bits_stored = v; } pub fn get_elems(&self) -> &[u8] { &self.elems } pub fn clear_elems(&mut self) { self.elems.clear(); } pub fn set_elems(&mut self, v: ::std::vec::Vec<u8>) { self.elems = v; } pub fn mut_elems(&mut self) -> &mut ::std::vec::Vec<u8> { &mut self.elems } pub fn take_elems(&mut self) -> ::std::vec::Vec<u8> { ::std::mem::replace(&mut self.elems, ::std::vec::Vec::new()) } } impl ::protobuf::Message for CompactBitArray { fn is_initialized(&self) -> bool { true } fn merge_from(&mut self, is: &mut ::protobuf::CodedInputStream<'_>) -> ::protobuf::ProtobufResult<()> { while !is.eof()? { let (field_number, wire_type) = is.read_tag_unpack()?; match field_number { 1 => { if wire_type != ::protobuf::wire_format::WireTypeVarint { return ::std::result::Result::Err(::protobuf::rt::unexpected_wire_type(wire_type)); } let tmp = is.read_uint32()?; self.extra_bits_stored = tmp; }, 2 => { ::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.elems)?; }, _ => { ::protobuf::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; }, }; } ::std::result::Result::Ok(()) } #[allow(unused_variables)] fn compute_size(&self) -> u32 { let mut my_size = 0; if self.extra_bits_stored != 0 { my_size += ::protobuf::rt::value_size(1, self.extra_bits_stored, ::protobuf::wire_format::WireTypeVarint); } if !self.elems.is_empty() { my_size += ::protobuf::rt::bytes_size(2, &self.elems); } my_size += ::protobuf::rt::unknown_fields_size(self.get_unknown_fields()); self.cached_size.set(my_size); my_size } fn write_to_with_cached_sizes(&self, os: &mut ::protobuf::CodedOutputStream<'_>) -> ::protobuf::ProtobufResult<()> { if self.extra_bits_stored != 0 { os.write_uint32(1, self.extra_bits_stored)?; } if !self.elems.is_empty() { os.write_bytes(2, &self.elems)?; } os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &dyn (::std::any::Any) { self as &dyn (::std::any::Any) } fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { self as &mut dyn (::std::any::Any) } fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { self } fn descriptor(&self) -> &'static ::protobuf::reflect::MessageDescriptor { Self::descriptor_static() } fn new() -> CompactBitArray { CompactBitArray::new() } fn descriptor_static() -> &'static ::protobuf::reflect::MessageDescriptor { static descriptor: ::protobuf::rt::LazyV2<::protobuf::reflect::MessageDescriptor> = ::protobuf::rt::LazyV2::INIT; descriptor.get(|| { let mut fields = ::std::vec::Vec::new(); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeUint32>( "extra_bits_stored", |m: &CompactBitArray| { &m.extra_bits_store
random
[ { "content": "pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto {\n\n file_descriptor_proto_lazy.get(|| {\n\n parse_descriptor_proto()\n\n })\n\n}\n", "file_path": "rust/src/tendermint/crypto/proof.rs", "rank": 0, "score": 222119.91363063856 }, {...
Rust
tss-esapi/tests/integration_tests/context_tests/tpm_commands/non_volatile_storage_tests.rs
Superhepper/rust-tss-esapi
a6ae84793e73b10dd672b613ada820566c84fe85
mod test_nv_define_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_define_space_failures() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500015).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .unwrap(); let platform_nv_index_attributes = NvIndexAttributesBuilder::new() .with_pp_write(true) .with_pp_read(true) .with_platform_create(true) .build() .expect("Failed to create platform nv index attributes"); let platform_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(platform_nv_index_attributes) .with_data_area_size(32) .build() .unwrap(); let _ = context .nv_define_space(Provision::Platform, None, &owner_nv_public) .unwrap_err(); let _ = context .nv_define_space(Provision::Owner, None, &platform_nv_public) .unwrap_err(); } #[test] fn test_nv_define_space() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500016).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let platform_nv_index_attributes = NvIndexAttributesBuilder::new() .with_pp_write(true) .with_pp_read(true) .with_platform_create(true) .build() .expect("Failed to create platform nv index attributes"); let platform_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(platform_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for platform"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); let platform_nv_index_handle = context .nv_define_space(Provision::Platform, None, &platform_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Platform, platform_nv_index_handle) .expect("Call to nv_undefine_space failed"); } } mod test_nv_undefine_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_undefine_space() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500017).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); } } mod test_nv_read_public { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_read_public() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500019).unwrap(); let nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let expected_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build the expected NvPublic"); let nv_index_handle = context .nv_define_space(Provision::Owner, None, &expected_nv_public) .expect("Call to nv_define_space failed"); let read_public_result = context.nv_read_public(nv_index_handle); let _ = context .nv_undefine_space(Provision::Owner, nv_index_handle) .unwrap(); if let Err(e) = read_public_result { panic!("Failed to read public of nv index: {}", e); } let (actual_nv_public, _name) = read_public_result.unwrap(); assert_eq!(expected_nv_public, actual_nv_public); } } mod test_nv_write { use crate::common::create_ctx_with_session; use std::convert::TryFrom; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{ algorithm::HashingAlgorithm, resource_handles::{NvAuth, Provision}, }, nv::storage::NvPublicBuilder, structures::MaxNvBuffer, }; #[test] fn test_nv_write() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500018).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let write_result = context.nv_write( NvAuth::Owner, owner_nv_index_handle, &MaxNvBuffer::try_from([1, 2, 3, 4, 5, 6, 7].to_vec()).unwrap(), 0, ); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); if let Err(e) = write_result { panic!("Failed to perform nv write: {}", e); } } } mod test_nv_read { use crate::common::create_ctx_with_session; use std::convert::TryFrom; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{ algorithm::HashingAlgorithm, resource_handles::{NvAuth, Provision}, }, nv::storage::NvPublicBuilder, structures::MaxNvBuffer, }; #[test] fn test_nv_read() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500020).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let value = [1, 2, 3, 4, 5, 6, 7]; let expected_data = MaxNvBuffer::try_from(value.to_vec()).expect("Failed to create MaxBuffer from data"); let write_result = context.nv_write(NvAuth::Owner, owner_nv_index_handle, &expected_data, 0); let read_result = context.nv_read(NvAuth::Owner, owner_nv_index_handle, value.len() as u16, 0); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); if let Err(e) = write_result { panic!("Failed to perform nv write: {}", e); } if let Err(e) = read_result { panic!("Failed to read public of nv index: {}", e); } let actual_data = read_result.unwrap(); assert_eq!(expected_data, actual_data); } }
mod test_nv_define_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_define_space_failures() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500015).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .unwrap(); let platform_nv_index_attributes = NvIndexAttributesBuilder::new() .with_pp_write(true) .with_pp_read(true) .with_platform_create(true) .build() .expect("Failed to create platform nv index attributes"); let platform_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(platform_nv_index_attributes) .with_data_area_size(32) .build() .unwrap(); let _ = context .nv_define_space(Provision::Platform, None, &owner_nv_public) .unwrap_err(); let _ = context .nv_define_space(Provision::Owner, None, &platform_nv_public) .unwrap_err(); } #[test] fn test_nv_define_space() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500016).unwrap(); le
} mod test_nv_undefine_space { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_undefine_space() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500017).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); } } mod test_nv_read_public { use crate::common::create_ctx_with_session; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{algorithm::HashingAlgorithm, resource_handles::Provision}, nv::storage::NvPublicBuilder, }; #[test] fn test_nv_read_public() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500019).unwrap(); let nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let expected_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build the expected NvPublic"); let nv_index_handle = context .nv_define_space(Provision::Owner, None, &expected_nv_public) .expect("Call to nv_define_space failed"); let read_public_result = context.nv_read_public(nv_index_handle); let _ = context .nv_undefine_space(Provision::Owner, nv_index_handle) .unwrap(); if let Err(e) = read_public_result { panic!("Failed to read public of nv index: {}", e); } let (actual_nv_public, _name) = read_public_result.unwrap(); assert_eq!(expected_nv_public, actual_nv_public); } } mod test_nv_write { use crate::common::create_ctx_with_session; use std::convert::TryFrom; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{ algorithm::HashingAlgorithm, resource_handles::{NvAuth, Provision}, }, nv::storage::NvPublicBuilder, structures::MaxNvBuffer, }; #[test] fn test_nv_write() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500018).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let write_result = context.nv_write( NvAuth::Owner, owner_nv_index_handle, &MaxNvBuffer::try_from([1, 2, 3, 4, 5, 6, 7].to_vec()).unwrap(), 0, ); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); if let Err(e) = write_result { panic!("Failed to perform nv write: {}", e); } } } mod test_nv_read { use crate::common::create_ctx_with_session; use std::convert::TryFrom; use tss_esapi::{ attributes::NvIndexAttributesBuilder, handles::NvIndexTpmHandle, interface_types::{ algorithm::HashingAlgorithm, resource_handles::{NvAuth, Provision}, }, nv::storage::NvPublicBuilder, structures::MaxNvBuffer, }; #[test] fn test_nv_read() { let mut context = create_ctx_with_session(); let nv_index = NvIndexTpmHandle::new(0x01500020).unwrap(); let owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let value = [1, 2, 3, 4, 5, 6, 7]; let expected_data = MaxNvBuffer::try_from(value.to_vec()).expect("Failed to create MaxBuffer from data"); let write_result = context.nv_write(NvAuth::Owner, owner_nv_index_handle, &expected_data, 0); let read_result = context.nv_read(NvAuth::Owner, owner_nv_index_handle, value.len() as u16, 0); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); if let Err(e) = write_result { panic!("Failed to perform nv write: {}", e); } if let Err(e) = read_result { panic!("Failed to read public of nv index: {}", e); } let actual_data = read_result.unwrap(); assert_eq!(expected_data, actual_data); } }
t owner_nv_index_attributes = NvIndexAttributesBuilder::new() .with_owner_write(true) .with_owner_read(true) .build() .expect("Failed to create owner nv index attributes"); let owner_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(owner_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for owner"); let platform_nv_index_attributes = NvIndexAttributesBuilder::new() .with_pp_write(true) .with_pp_read(true) .with_platform_create(true) .build() .expect("Failed to create platform nv index attributes"); let platform_nv_public = NvPublicBuilder::new() .with_nv_index(nv_index) .with_index_name_algorithm(HashingAlgorithm::Sha256) .with_index_attributes(platform_nv_index_attributes) .with_data_area_size(32) .build() .expect("Failed to build NvPublic for platform"); let owner_nv_index_handle = context .nv_define_space(Provision::Owner, None, &owner_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Owner, owner_nv_index_handle) .expect("Call to nv_undefine_space failed"); let platform_nv_index_handle = context .nv_define_space(Provision::Platform, None, &platform_nv_public) .expect("Call to nv_define_space failed"); let _ = context .nv_undefine_space(Provision::Platform, platform_nv_index_handle) .expect("Call to nv_undefine_space failed"); }
function_block-function_prefixed
[ { "content": "fn write_nv_index(context: &mut Context, nv_index: NvIndexTpmHandle) -> NvIndexHandle {\n\n // Create owner nv public.\n\n let owner_nv_index_attributes = NvIndexAttributesBuilder::new()\n\n .with_owner_write(true)\n\n .with_owner_read(true)\n\n .with_pp_read(true)\n\n ...
Rust
src/syntax/src/statement.rs
isaacazuelos/kurt
f86c3230d9d0cd54b307eda27e3ddbb4c145d1f0
use parser::Parse; use crate::lexer::{Reserved, TokenKind}; use super::*; #[derive(Debug)] pub enum Statement<'a> { Binding(Binding<'a>), Empty(Span), Expression(Expression<'a>), If(IfOnly<'a>), } impl<'a> Syntax for Statement<'a> { fn span(&self) -> Span { match self { Statement::Binding(b) => b.span(), Statement::Empty(s) => *s, Statement::Expression(s) => s.span(), Statement::If(i) => i.span(), } } } impl<'a> Parse<'a> for Statement<'a> { type SyntaxError = SyntaxError; fn parse_with(parser: &mut Parser<'a>) -> SyntaxResult<Statement<'a>> { match parser.peek_kind() { Some(TokenKind::Semicolon) => { Ok(Statement::Empty(parser.next_span())) } Some(TokenKind::Reserved(Reserved::Var | Reserved::Let)) => { Ok(Statement::Binding(parser.parse()?)) } Some(TokenKind::Reserved(Reserved::If)) => { let if_only: IfOnly = parser.parse()?; if parser.peek_kind() == Some(TokenKind::Reserved(Reserved::Else)) { let if_else = if_only.expand_with_else(parser)?; Ok(Statement::Expression(Expression::If(if_else))) } else { Ok(Statement::If(if_only)) } } Some(_) => Ok(Statement::Expression(parser.parse()?)), None => Err(Error::EOF(parser.eof_span())), } } } #[cfg(test)] mod parser_tests { use super::*; #[test] fn parse_expression_literal() { let mut parser = Parser::new("0").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!( literal, Ok(Statement::Expression(Expression::Literal(_))) )); assert!(parser.is_empty()); } #[test] fn parse_empty() { let mut parser = Parser::new(";").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!(literal, Ok(Statement::Empty(_)))); assert!(!parser.is_empty()); } #[test] fn parse_binding() { let mut parser = Parser::new("let x = 1;").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!(literal, Ok(Statement::Binding(_)))); assert!(!parser.is_empty()); } #[test] fn parse_expression_with_semicolon() { let mut parser = Parser::new("0;").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!( literal, Ok(Statement::Expression(Expression::Literal(_))) )); assert!(!parser.is_empty()); } #[test] fn parse_if_only() { let mut parser = Parser::new("if true { }").unwrap(); let syntax = parser.parse::<Statement>(); assert!( matches!(syntax, Ok(Statement::If(_))), "expected If statement, but got {:#?}", syntax ); assert!(parser.is_empty()); } #[test] fn parse_if_else() { let mut parser = Parser::new("if true { } else { }").unwrap(); let syntax = parser.parse::<Statement>(); assert!( matches!(syntax, Ok(Statement::Expression(Expression::If(_)))), "expected If expression, but got {:#?}", syntax ); assert!(parser.is_empty()); } }
use parser::Parse; use crate::lexer::{Reserved, TokenKind}; use super::*; #[derive(Debug)] pub enum Statement<'a> { Binding(Binding<'a>), Empty(Span), Expression(Expression<'a>), If(IfOnly<'a>), } impl<'a> Syntax for Statement<'a> {
} impl<'a> Parse<'a> for Statement<'a> { type SyntaxError = SyntaxError; fn parse_with(parser: &mut Parser<'a>) -> SyntaxResult<Statement<'a>> { match parser.peek_kind() { Some(TokenKind::Semicolon) => { Ok(Statement::Empty(parser.next_span())) } Some(TokenKind::Reserved(Reserved::Var | Reserved::Let)) => { Ok(Statement::Binding(parser.parse()?)) } Some(TokenKind::Reserved(Reserved::If)) => { let if_only: IfOnly = parser.parse()?; if parser.peek_kind() == Some(TokenKind::Reserved(Reserved::Else)) { let if_else = if_only.expand_with_else(parser)?; Ok(Statement::Expression(Expression::If(if_else))) } else { Ok(Statement::If(if_only)) } } Some(_) => Ok(Statement::Expression(parser.parse()?)), None => Err(Error::EOF(parser.eof_span())), } } } #[cfg(test)] mod parser_tests { use super::*; #[test] fn parse_expression_literal() { let mut parser = Parser::new("0").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!( literal, Ok(Statement::Expression(Expression::Literal(_))) )); assert!(parser.is_empty()); } #[test] fn parse_empty() { let mut parser = Parser::new(";").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!(literal, Ok(Statement::Empty(_)))); assert!(!parser.is_empty()); } #[test] fn parse_binding() { let mut parser = Parser::new("let x = 1;").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!(literal, Ok(Statement::Binding(_)))); assert!(!parser.is_empty()); } #[test] fn parse_expression_with_semicolon() { let mut parser = Parser::new("0;").unwrap(); let literal = parser.parse::<Statement>(); assert!(matches!( literal, Ok(Statement::Expression(Expression::Literal(_))) )); assert!(!parser.is_empty()); } #[test] fn parse_if_only() { let mut parser = Parser::new("if true { }").unwrap(); let syntax = parser.parse::<Statement>(); assert!( matches!(syntax, Ok(Statement::If(_))), "expected If statement, but got {:#?}", syntax ); assert!(parser.is_empty()); } #[test] fn parse_if_else() { let mut parser = Parser::new("if true { } else { }").unwrap(); let syntax = parser.parse::<Statement>(); assert!( matches!(syntax, Ok(Statement::Expression(Expression::If(_)))), "expected If expression, but got {:#?}", syntax ); assert!(parser.is_empty()); } }
fn span(&self) -> Span { match self { Statement::Binding(b) => b.span(), Statement::Empty(s) => *s, Statement::Expression(s) => s.span(), Statement::If(i) => i.span(), } }
function_block-full_function
[]
Rust
component/src/desktop_window.rs
rohankumardubey/makepad
2248d20bd8e1431616acc89846a841abc36dffb7
use makepad_render::*; use crate::desktop_button::*; use crate::window_menu::*; use crate::button_logic::*; live_register!{ use crate::theme::*; DesktopWindow: {{DesktopWindow}} { clear_color: (COLOR_WINDOW_BG) caption_bg: {color: (COLOR_WINDOW_CAPTION)} caption: "Desktop Window", main_view:{}, border_fill: {color: (COLOR_WINDOW_CAPTION)}, inner_view:{ }, caption_layout:{ padding:{t:2.0} align: {fx: 0.5, fy: 0.5}, walk: { width: Width::Filled, height: Height::Fixed(26.), } } caption_view: { layout: { walk: { width: Width::Filled, height: Height::Computed }, } } } } #[derive(Live, LiveHook)] pub struct DesktopWindow { #[rust] pub caption_size: Vec2, pass: Pass, color_texture: Texture, depth_texture: Texture, window: Window, main_view: View, caption_view: View, inner_view: View, caption_layout: Layout, clear_color: Vec4, min_btn: DesktopButton, max_btn: DesktopButton, close_btn: DesktopButton, xr_btn: DesktopButton, fullscreen_btn: DesktopButton, caption_text: DrawText, caption_bg: DrawColor, caption: String, border_fill: DrawColor, #[rust(WindowMenu::new(cx))] pub window_menu: WindowMenu, #[rust(Menu::main(vec![ Menu::sub("App", vec![ ]), ]))] default_menu: Menu, #[rust] pub last_menu: Option<Menu>, #[rust] pub inner_over_chrome: bool, } #[derive(Clone, PartialEq)] pub enum DesktopWindowEvent { EventForOtherWindow, WindowClosed, WindowGeomChange(WindowGeomChangeEvent), None } impl DesktopWindow { pub fn handle_event(&mut self, cx: &mut Cx, event: &mut Event) -> DesktopWindowEvent { if let ButtonAction::WasClicked = self.xr_btn.handle_desktop_button(cx, event) { if self.window.xr_is_presenting(cx) { self.window.xr_stop_presenting(cx); } else { self.window.xr_start_presenting(cx); } } if let ButtonAction::WasClicked = self.fullscreen_btn.handle_desktop_button(cx, event) { if self.window.is_fullscreen(cx) { self.window.normal(cx); } else { self.window.fullscreen(cx); } } if let ButtonAction::WasClicked = self.min_btn.handle_desktop_button(cx, event) { self.window.minimize(cx); } if let ButtonAction::WasClicked = self.max_btn.handle_desktop_button(cx, event) { if self.window.is_fullscreen(cx) { self.window.restore(cx); } else { self.window.maximize(cx); } } if let ButtonAction::WasClicked = self.close_btn.handle_desktop_button(cx, event) { self.window.close(cx); } let is_for_other_window = match event { Event::WindowCloseRequested(ev) => ev.window_id != self.window.window_id, Event::WindowClosed(ev) => { if ev.window_id == self.window.window_id { return DesktopWindowEvent::WindowClosed } true } Event::WindowGeomChange(ev) => { if ev.window_id == self.window.window_id { return DesktopWindowEvent::WindowGeomChange(ev.clone()) } true }, Event::WindowDragQuery(dq) => { if dq.window_id == self.window.window_id { if dq.abs.x < self.caption_size.x && dq.abs.y < self.caption_size.y { if dq.abs.x < 50. { dq.response = WindowDragQueryResponse::SysMenu; } else { dq.response = WindowDragQueryResponse::Caption; } } } true } Event::FingerDown(ev) => ev.window_id != self.window.window_id, Event::FingerMove(ev) => ev.window_id != self.window.window_id, Event::FingerHover(ev) => ev.window_id != self.window.window_id, Event::FingerUp(ev) => ev.window_id != self.window.window_id, Event::FingerScroll(ev) => ev.window_id != self.window.window_id, _ => false }; if is_for_other_window { DesktopWindowEvent::EventForOtherWindow } else { DesktopWindowEvent::None } } pub fn begin(&mut self, cx: &mut Cx, menu: Option<&Menu>) -> ViewRedraw { if !self.main_view.view_will_redraw(cx) { return Err(()) } self.window.begin(cx); self.pass.begin(cx); self.pass.add_color_texture(cx, &self.color_texture, PassClearColor::ClearWith(self.clear_color)); self.pass.set_depth_texture(cx, &self.depth_texture, PassClearDepth::ClearWith(1.0)); self.main_view.begin(cx).unwrap(); /*self.caption_view.set_layout(cx, Layout { walk: Walk::wh(Width::Filled, Height::Computed), ..Layout::default() });*/ if self.caption_view.begin(cx).is_ok() { let process_chrome = match cx.platform_type { PlatformType::Linux {custom_window_chrome} => custom_window_chrome, _ => true }; if process_chrome { match cx.platform_type { PlatformType::MsWindows | PlatformType::Unknown | PlatformType::Linux {..} => { self.caption_bg.begin(cx, Layout { align: Align {fx: 1.0, fy: 0.0}, walk: Walk::wh(Width::Filled, Height::Computed), ..Default::default() }); if let Some(_menu) = menu { } self.min_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMin); if self.window.is_fullscreen(cx) { self.max_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMaxToggled); } else { self.max_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMax); } self.close_btn.draw_desktop_button(cx, DesktopButtonType::WindowsClose); cx.change_turtle_align_x_cab(0.5); cx.compute_turtle_height(); cx.change_turtle_align_y_cab(0.5); cx.reset_turtle_pos(); cx.move_turtle(50., 0.); self.caption_size = Vec2 {x: cx.get_width_left(), y: cx.get_height_left()}; self.caption_text.draw_walk(cx, &self.caption); self.caption_bg.end(cx); cx.turtle_new_line(); }, PlatformType::OSX => { if let Some(menu) = menu { cx.update_menu(menu); } else { cx.update_menu(&self.default_menu); } self.caption_bg.begin(cx, self.caption_layout); self.caption_size = Vec2 {x: cx.get_width_left(), y: cx.get_height_left()}; self.caption_text.draw_walk(cx, &self.caption); self.caption_bg.end(cx); cx.turtle_new_line(); }, PlatformType::WebBrowser {..} => { if self.window.is_fullscreen(cx) { self.caption_bg.begin(cx, Layout { align: Align {fx: 0.5, fy: 0.5}, walk: Walk::wh(Width::Filled, Height::Fixed(22.)), ..Default::default() }); self.caption_bg.end(cx); cx.turtle_new_line(); } } } } self.caption_view.end(cx); } cx.turtle_new_line(); if self.inner_view.begin(cx).is_ok(){ return Ok(()) } self.end_inner(cx, true); Err(()) } pub fn end(&mut self, cx: &mut Cx) { self.end_inner(cx, false); } fn end_inner(&mut self, cx: &mut Cx, no_inner:bool) { if !no_inner{ self.inner_view.end(cx); } if !cx.platform_type.is_desktop() && !self.window.is_fullscreen(cx) { cx.reset_turtle_pos(); cx.move_turtle(cx.get_width_total() - 50.0, 0.); self.fullscreen_btn.draw_desktop_button(cx, DesktopButtonType::Fullscreen); } if self.window.xr_can_present(cx) { cx.reset_turtle_pos(); cx.move_turtle(cx.get_width_total() - 100.0, 0.); self.xr_btn.draw_desktop_button(cx, DesktopButtonType::XRMode); } self.main_view.end(cx); self.pass.end(cx); self.window.end(cx); } }
use makepad_render::*; use crate::desktop_button::*; use crate::window_menu::*; use crate::button_logic::*; live_register!{ use crate::theme::*; DesktopWindow: {{DesktopWindow}} { clear_color: (COLOR_WINDOW_BG) caption_bg: {color: (COLOR_WINDOW_CAPTION)} caption: "Desktop Window", main_view:{}, border_fill: {color: (COLOR_WINDOW_CAPTION)}, inner_view:{ }, caption_layout:{ padding:{t:2.0} align: {fx: 0.5, fy: 0.5}, walk: { width: Width::Filled, height: Height::Fixed(26.), } } caption_view: { layout: { walk: { width: Width::Filled, height: Height::Computed }, } } } } #[derive(Live, LiveHook)] pub struct DesktopWindow { #[rust] pub caption_size: Vec2, pass: Pass, color_texture: Texture, depth_texture: Texture, window: Window, main_view: View, caption_view: View, inner_view: View, caption_layout: Layout, clear_color: Vec4, min_btn: DesktopButton, max_btn: DesktopButton, close_btn: DesktopButton, xr_btn: DesktopButton, fullscreen_btn: DesktopButton, caption_text: DrawText, caption_bg: DrawColor, caption: String, border_fill: DrawColor, #[rust(WindowMenu::new(cx))] pub window_menu: WindowMenu, #[rust(Menu::main(vec![ Menu::sub("App", vec![ ]), ]))] default_menu: Menu, #[rust] pub last_menu: Option<Menu>, #[rust] pub inner_over_chrome: bool, } #[derive(Clone, PartialEq)] pub enum DesktopWindowEvent { EventForOtherWindow, WindowClosed, WindowGeomChange(WindowGeomChangeEvent), None } impl DesktopWindow { pub fn handle_event(&mut self, cx: &mut Cx, event: &mut Event) -> DesktopWindowEvent { if let ButtonAction::WasClicked = self.xr_btn.handle_desktop_button(cx, event) { if self.window.xr_is_presenting(cx) { self.window.xr_stop_presenting(cx); } else { self.window.xr_start_presenting(cx); } } if let ButtonAction::WasClicked = self.fullscreen_btn.handle_desktop_button(cx, event) { if self.window.is_fullscreen(cx) { self.window.normal(cx); } else { self.window.fullscreen(cx); } } if let ButtonAction::WasClicked = self.min_btn.handle_desktop_button(cx, event) { self.window.minimize(cx); } if let ButtonAction::WasClicked = self.max_btn.handle_desktop_button(cx, event) { if self.window.is_fullscreen(cx) { self.window.restore(cx); } else { self.window.maximize(cx); } } if let ButtonAction::WasClicked = self.close_btn.handle_desktop_button(cx, event) { self.window.close(cx); } let is_for_other_window = match event { Event::WindowCloseRequested(ev) => ev.window_id != self.window.window_id, Event::WindowClosed(ev) => { if ev.window_id == self.window.window_id { return DesktopWindowEvent::WindowClosed } true } Event::WindowGeomChange(ev) => { if ev.window_id == self.window.window_id { return DesktopWindowEvent::WindowGeomChange(ev.clone()) } true }, Event::WindowDragQuery(dq) => { if dq.window_id == self.window.window_id { if dq.abs.x < self.caption_size.x && dq.abs.y < self.caption_size.y { if dq.abs.x < 50. { dq.response = WindowDragQueryResponse::SysMenu; } else { dq.response = WindowDragQueryResponse::Caption; } } } true } Event::FingerDown(ev) => ev.window_id != self.window.window_id, Event::FingerMove(ev) => ev.window_id != self.window.window_id, Event::FingerHover(ev) => ev.window_id != self.window.window_id, Event::FingerUp(ev) => ev.window_id != self.window.window_id, Event::FingerScroll(ev) => ev.window_id != self.window.window_id, _ => false }; if is_for_other_window { DesktopWindowEvent::EventForOtherWindow } else { DesktopWindowEvent::None } } pub fn begin(&mut self, cx: &mut Cx, menu: Option<&Menu>) -> ViewRedraw { if !self.main_view.view_will_redraw(cx) { return Err(()) } self.window.begin(cx); self.pass.begin(cx); self.pass.add_color_texture(cx, &self.color_texture, PassClearColor::ClearWith(self.clear_color)); self.pass.set_depth_texture(cx, &self.depth_texture, PassClearDepth::ClearWith(1.0)); self.main_view.begin(cx).unwrap(); /*self.caption_view.set_layout(cx, Layout { walk: Walk::wh(Width::Filled, Height::Computed), ..Layout::default() });*/ if self.caption_view.begin(cx).is_ok() { let process_chrome = match cx.platform_type { PlatformType::Linux {custom_window_chrome} => custom_window_chrome, _ => true }; if process_chrome { match cx.platform_type { PlatformType::MsWindows | PlatformType::Unknown | PlatformType::Linux {..} => { self.caption_bg.begin(cx, Layout { align: Align {fx: 1.0, fy: 0.0}, walk: Walk::wh(Width::Filled, Height::Computed), ..Default::default() }); if let Some(_menu) = menu { } self.min_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMin); if self.window.is_fullscreen(cx) { self.max_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMaxToggled); } else { self.max_btn.draw_desktop_button(cx, DesktopButtonType::WindowsMax); } self.close_btn.draw_desktop_button(cx, DesktopButtonType::WindowsClose); cx.change_turtle_align_x_cab(0.5); cx.compute_turtle_height(); cx.change_turtle_align_y_cab(0.5); cx.reset_turtle_pos(); cx.move_turtle(50., 0.); self.caption_size = Vec2 {x: cx.get_width_left(), y: cx.get_height_left()}; self.caption_text.draw_walk(cx, &self.caption); self.caption_bg.end(cx); cx.turtle_new_line(); }, PlatformType::OSX => { if let Some(menu) = menu { cx.update_menu(menu); } else { cx.update_menu(&self.default_menu); } self.caption_bg.begin(cx, self.caption_layout); self.caption_size = Vec2 {x: cx.get_width_left(), y: cx.get_height_left()}; self.caption_text.draw_walk(cx, &self.caption); self.caption_bg.end(cx); cx.turtle_new_line(); }, PlatformType::WebBrowser {..} => { if self.window.is_fullscreen(cx) { self.caption_bg.begin(cx, Layout { align: Align {fx: 0.5, fy: 0.5}, walk: Walk::wh(Width::Filled, Height::Fixed(22.)), ..Default::default() }); self.caption_bg.end(cx); cx.turtle_new_line(); } } } } self.caption_view.end(cx); } cx.turtle_new_line(); if self.inner_view.begin(cx).is_ok(){ return Ok(()) } self.end_inner(cx, true); Err(()) } pub fn end(&mut self, cx: &mut Cx) { self.end_inner(cx, false); } fn end_inner(&mut self, cx: &mut Cx, no_inner:bool) { if !no_inner{ self.inner_view.end(cx); } if !cx.platform_type.is_desktop() && !self.window.is_fullscreen(cx) { cx.reset_turtle_pos(); cx.move_turtle(cx.get_width_total() - 50.0, 0.); self.fullscreen_btn.draw_desktop_button(cx, DesktopButtonType::Fullscreen); } if self.window.xr_can_present(cx) { cx.reset_turtle_pos(); cx.move_turtle(cx.get_width_total() - 100.0, 0.); self.xr_btn.draw_deskto
}
p_button(cx, DesktopButtonType::XRMode); } self.main_view.end(cx); self.pass.end(cx); self.window.end(cx); }
function_block-function_prefixed
[ { "content": "pub fn new_cxthread(&mut self) -> CxThread {\n\n CxThread {cx: self as *mut _ as u64}\n\n }\n\n \n\n pub fn get_mapped_texture_user_data(&mut self, texture: &Texture) -> Option<usize> {\n\n if let Some(texture_id) = texture.texture_id {\n\n let cxtexture = &self.t...
Rust
src/main.rs
jeff-lund/Molecule
c37aeffce87abea007a56b82ed0d1cd474cb8530
#![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] mod utility; use utility::*; mod atoms; use atoms::*; use std::env::args; use std::fs::File; use std::io::prelude::*; const DEBUG: bool = false; const MAX_GENERATIONS: u32 = 200; fn pprint (molecule: &Molecule, atoms: &Vec<&str>, peaks: &Vec<f32>) { for a in atoms { print!("|{} ", a); } println!("|"); for row in molecule.structure.genrows() { println!("{}", row); } println!(""); println!("Fitness: {}", molecule.fitness); print!("Carbon Assignments: {:?}", molecule.kind[0]); for entry in molecule.kind.iter().skip(1) { print!(", {:?}", entry); } println!(""); print!("Chemical Shifts: {}", molecule.chemical_shifts[0]); for entry in molecule.chemical_shifts.iter().skip(1) { print!(", {}", entry); } println!(""); print!("Experimental Chemical Shifts: {}", peaks[0]); for entry in peaks.iter().skip(1) { print!(", {}", entry); } println!(""); } fn main() -> std::io::Result<()> { let f = args().nth(1).expect("No file argument given"); let mut file = File::open(f)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let mut b = buffer.lines(); let chemical_formula = parse_elemental_analysis(b.next().expect("invalid file")); let peaks = parse_peaks(b.next().expect("invalid file")); let ihd = compute_ihd(&chemical_formula); let bonds = get_bonds(&chemical_formula); let atoms = get_atoms(&chemical_formula); if symmetrical_carbons(&chemical_formula, &peaks) { eprintln!("There must be a chemical shift for each carbon atom in the chemical formula"); std::process::exit(0); } if DEBUG == false { let mut population: Vec<Molecule> = Vec::new(); let mut pop = 0; while pop < POPULATION { let molecule = create_test_molecule(&atoms, bonds); if connected(&molecule.structure) && check_bonds(&molecule.structure, &atoms) { population.push(molecule); pop += 1; } } let mut best_molecule: Molecule = Molecule::new(Structure::zeros((1,1))); for gen in 0..MAX_GENERATIONS { println!("Generation {}", gen); for molecule in population.iter_mut() { molecule.assign_carbons(&atoms); molecule.compute_shifts(&atoms); molecule.fitness(&peaks); } best_molecule = best(&population); if best_molecule.fitness == 0.0 { break; } population = generate_children(population, &atoms, bonds) } println!("Best fit found"); pprint(&best_molecule, &atoms, &peaks); } if DEBUG == true { println!("********************DEBUG*************************************"); println!("{:?}", atoms); println!("IHD {}", ihd); println!("{:?}", chemical_formula); println!("{:?}", peaks); if symmetrical_carbons(&chemical_formula, &peaks) { println!("Symmetric carbons present"); } println!("Bonds Assigned: {}", bonds); println!("********************END DEBUG*********************************"); let mut tot = 0; let mut fcon = 0; let mut fbond = 0; let mut failed_both = 0; let mut pop = 0; let mut population = Vec::new(); while pop < POPULATION { let m = create_test_molecule(&atoms, bonds); let mut bond_flag = 0; let mut con_flag = 0; tot += 1; if !connected(&m.structure) { fcon += 1; con_flag = 1; } if !check_bonds(&m.structure, &atoms) { fbond += 1; bond_flag = 1; } if con_flag == 0 && bond_flag == 0 { population.push(m); pop += 1; } if con_flag == 1 && bond_flag == 1 { failed_both += 1; } } println!("Added {} molecules to population. Total molecules created: {}", pop, tot); println!("Failed bond check: {}", fbond); println!("Failed connected: {}", fcon); println!("Failed both: {}", failed_both); for i in 0..10 { population[i].assign_carbons(&atoms); println!("{:?}", population[i].kind); } } Ok(()) }
#![allow(dead_code)] #![allow(unused_assignments)] #![allow(unused_variables)] mod utility; use utility::*; mod atoms; use atoms::*; use std::env::args; use std::fs::File; use std::io::prelude::*; const DEBUG: bool = false; const MAX_GENERATIONS: u32 = 200; fn pprint (molecule: &Molecule, atoms: &Vec<&str>, peaks: &Vec<f32>) { for a in atoms { print!("|{} ", a); } println!("|"); for row in molecule.structure.genrows() { println!("{}", row); } println!(""); println!("Fitness: {}", molecule.fitness); print!("Carbon Assignments: {:?}", molecule.kind[0]); for entry in molecule.kind.iter().skip(1) { print!(", {:?}", entry); } println!(""); print!("Chemical Shifts: {}", molecule.chemical_shifts[0]); for entry in molecule.chemical_shifts.iter().skip(1) { print!(", {}", entry); } println!("");
fn main() -> std::io::Result<()> { let f = args().nth(1).expect("No file argument given"); let mut file = File::open(f)?; let mut buffer = String::new(); file.read_to_string(&mut buffer)?; let mut b = buffer.lines(); let chemical_formula = parse_elemental_analysis(b.next().expect("invalid file")); let peaks = parse_peaks(b.next().expect("invalid file")); let ihd = compute_ihd(&chemical_formula); let bonds = get_bonds(&chemical_formula); let atoms = get_atoms(&chemical_formula); if symmetrical_carbons(&chemical_formula, &peaks) { eprintln!("There must be a chemical shift for each carbon atom in the chemical formula"); std::process::exit(0); } if DEBUG == false { let mut population: Vec<Molecule> = Vec::new(); let mut pop = 0; while pop < POPULATION { let molecule = create_test_molecule(&atoms, bonds); if connected(&molecule.structure) && check_bonds(&molecule.structure, &atoms) { population.push(molecule); pop += 1; } } let mut best_molecule: Molecule = Molecule::new(Structure::zeros((1,1))); for gen in 0..MAX_GENERATIONS { println!("Generation {}", gen); for molecule in population.iter_mut() { molecule.assign_carbons(&atoms); molecule.compute_shifts(&atoms); molecule.fitness(&peaks); } best_molecule = best(&population); if best_molecule.fitness == 0.0 { break; } population = generate_children(population, &atoms, bonds) } println!("Best fit found"); pprint(&best_molecule, &atoms, &peaks); } if DEBUG == true { println!("********************DEBUG*************************************"); println!("{:?}", atoms); println!("IHD {}", ihd); println!("{:?}", chemical_formula); println!("{:?}", peaks); if symmetrical_carbons(&chemical_formula, &peaks) { println!("Symmetric carbons present"); } println!("Bonds Assigned: {}", bonds); println!("********************END DEBUG*********************************"); let mut tot = 0; let mut fcon = 0; let mut fbond = 0; let mut failed_both = 0; let mut pop = 0; let mut population = Vec::new(); while pop < POPULATION { let m = create_test_molecule(&atoms, bonds); let mut bond_flag = 0; let mut con_flag = 0; tot += 1; if !connected(&m.structure) { fcon += 1; con_flag = 1; } if !check_bonds(&m.structure, &atoms) { fbond += 1; bond_flag = 1; } if con_flag == 0 && bond_flag == 0 { population.push(m); pop += 1; } if con_flag == 1 && bond_flag == 1 { failed_both += 1; } } println!("Added {} molecules to population. Total molecules created: {}", pop, tot); println!("Failed bond check: {}", fbond); println!("Failed connected: {}", fcon); println!("Failed both: {}", failed_both); for i in 0..10 { population[i].assign_carbons(&atoms); println!("{:?}", population[i].kind); } } Ok(()) }
print!("Experimental Chemical Shifts: {}", peaks[0]); for entry in peaks.iter().skip(1) { print!(", {}", entry); } println!(""); }
function_block-function_prefix_line
[ { "content": "/// Validate the overall correctness of a chromosome\n\nfn validate_chromosome(chromosome: &Chromosome, atoms: &Vec<&str>, num_bonds: u32) -> bool {\n\n // check proper number of bonds exist\n\n let bonds: u32 = chromosome.iter().sum();\n\n if bonds != num_bonds {\n\n return false;...
Rust
src/hotkey_config.rs
Ynscription/livesplit-core
1027a92faaf8eeb14ce8be8a32ce8d3f202bc664
#![allow(clippy::trivially_copy_pass_by_ref)] use crate::hotkey::KeyCode; use crate::platform::prelude::*; use crate::settings::{Field, SettingsDescription, Value}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(default)] pub struct HotkeyConfig { pub split: Option<KeyCode>, pub reset: Option<KeyCode>, pub undo: Option<KeyCode>, pub skip: Option<KeyCode>, pub pause: Option<KeyCode>, pub undo_all_pauses: Option<KeyCode>, pub previous_comparison: Option<KeyCode>, pub next_comparison: Option<KeyCode>, pub toggle_timing_method: Option<KeyCode>, } #[cfg(any(windows, target_os = "linux"))] impl Default for HotkeyConfig { fn default() -> Self { use crate::hotkey::KeyCode::*; Self { split: Some(NumPad1), reset: Some(NumPad3), undo: Some(NumPad8), skip: Some(NumPad2), pause: Some(NumPad5), undo_all_pauses: None, previous_comparison: Some(NumPad4), next_comparison: Some(NumPad6), toggle_timing_method: None, } } } #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] impl Default for HotkeyConfig { fn default() -> Self { use crate::hotkey::KeyCode::*; Self { split: Some(Numpad1), reset: Some(Numpad3), undo: Some(Numpad8), skip: Some(Numpad2), pause: Some(Numpad5), undo_all_pauses: None, previous_comparison: Some(Numpad4), next_comparison: Some(Numpad6), toggle_timing_method: None, } } } #[cfg(not(any( windows, target_os = "linux", all(target_arch = "wasm32", target_os = "unknown"), )))] impl Default for HotkeyConfig { fn default() -> Self { Self { split: Some(KeyCode), reset: Some(KeyCode), undo: Some(KeyCode), skip: Some(KeyCode), pause: Some(KeyCode), undo_all_pauses: None, previous_comparison: Some(KeyCode), next_comparison: Some(KeyCode), toggle_timing_method: None, } } } impl HotkeyConfig { pub fn settings_description(&self) -> SettingsDescription { SettingsDescription::with_fields(vec![ Field::new("Start / Split".into(), self.split.into()), Field::new("Reset".into(), self.reset.into()), Field::new("Undo Split".into(), self.undo.into()), Field::new("Skip Split".into(), self.skip.into()), Field::new("Pause".into(), self.pause.into()), Field::new("Undo All Pauses".into(), self.undo_all_pauses.into()), Field::new( "Previous Comparison".into(), self.previous_comparison.into(), ), Field::new("Next Comparison".into(), self.next_comparison.into()), Field::new( "Toggle Timing Method".into(), self.toggle_timing_method.into(), ), ]) } pub fn set_value(&mut self, index: usize, value: Value) -> Result<(), ()> { let value: Option<KeyCode> = value.into(); if value.is_some() { let any = [ self.split, self.reset, self.undo, self.skip, self.pause, self.undo_all_pauses, self.previous_comparison, self.next_comparison, self.toggle_timing_method, ] .iter() .enumerate() .filter(|&(i, _)| i != index) .any(|(_, &v)| v == value); if any { return Err(()); } } match index { 0 => self.split = value, 1 => self.reset = value, 2 => self.undo = value, 3 => self.skip = value, 4 => self.pause = value, 5 => self.undo_all_pauses = value, 6 => self.previous_comparison = value, 7 => self.next_comparison = value, 8 => self.toggle_timing_method = value, _ => panic!("Unsupported Setting Index"), } Ok(()) } #[cfg(feature = "std")] pub fn from_json<R>(reader: R) -> serde_json::Result<Self> where R: std::io::Read, { serde_json::from_reader(reader) } #[cfg(feature = "std")] pub fn write_json<W>(&self, writer: W) -> serde_json::Result<()> where W: std::io::Write, { serde_json::to_writer(writer, self) } }
#![allow(clippy::trivially_copy_pass_by_ref)] use crate::hotkey::KeyCode; use crate::platform::prelude::*; use crate::settings::{Field, SettingsDescription, Value}; use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(default)] pub struct HotkeyConfig { pub split: Option<KeyCode>, pub reset: Option<KeyCode>, pub undo: Option<KeyCode>, pub skip: Option<KeyCode>, pub pause: Option<KeyCode>, pub undo_all_pauses: Option<KeyCode>, pub previous_comparison: Option<KeyCode>, pub next_comparison: Option<KeyCode>, pub toggle_timing_method: Option<KeyCode>, } #[cfg(any(windows, target_os = "linux"))] impl Default for HotkeyConfig { fn default() -> Self { use crate::hotkey::KeyCode::*; Self { split: Some(NumPad1), reset: Some(NumPad3), undo: Some(NumPad8), skip: Some
on = value, 8 => self.toggle_timing_method = value, _ => panic!("Unsupported Setting Index"), } Ok(()) } #[cfg(feature = "std")] pub fn from_json<R>(reader: R) -> serde_json::Result<Self> where R: std::io::Read, { serde_json::from_reader(reader) } #[cfg(feature = "std")] pub fn write_json<W>(&self, writer: W) -> serde_json::Result<()> where W: std::io::Write, { serde_json::to_writer(writer, self) } }
(NumPad2), pause: Some(NumPad5), undo_all_pauses: None, previous_comparison: Some(NumPad4), next_comparison: Some(NumPad6), toggle_timing_method: None, } } } #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] impl Default for HotkeyConfig { fn default() -> Self { use crate::hotkey::KeyCode::*; Self { split: Some(Numpad1), reset: Some(Numpad3), undo: Some(Numpad8), skip: Some(Numpad2), pause: Some(Numpad5), undo_all_pauses: None, previous_comparison: Some(Numpad4), next_comparison: Some(Numpad6), toggle_timing_method: None, } } } #[cfg(not(any( windows, target_os = "linux", all(target_arch = "wasm32", target_os = "unknown"), )))] impl Default for HotkeyConfig { fn default() -> Self { Self { split: Some(KeyCode), reset: Some(KeyCode), undo: Some(KeyCode), skip: Some(KeyCode), pause: Some(KeyCode), undo_all_pauses: None, previous_comparison: Some(KeyCode), next_comparison: Some(KeyCode), toggle_timing_method: None, } } } impl HotkeyConfig { pub fn settings_description(&self) -> SettingsDescription { SettingsDescription::with_fields(vec![ Field::new("Start / Split".into(), self.split.into()), Field::new("Reset".into(), self.reset.into()), Field::new("Undo Split".into(), self.undo.into()), Field::new("Skip Split".into(), self.skip.into()), Field::new("Pause".into(), self.pause.into()), Field::new("Undo All Pauses".into(), self.undo_all_pauses.into()), Field::new( "Previous Comparison".into(), self.previous_comparison.into(), ), Field::new("Next Comparison".into(), self.next_comparison.into()), Field::new( "Toggle Timing Method".into(), self.toggle_timing_method.into(), ), ]) } pub fn set_value(&mut self, index: usize, value: Value) -> Result<(), ()> { let value: Option<KeyCode> = value.into(); if value.is_some() { let any = [ self.split, self.reset, self.undo, self.skip, self.pause, self.undo_all_pauses, self.previous_comparison, self.next_comparison, self.toggle_timing_method, ] .iter() .enumerate() .filter(|&(i, _)| i != index) .any(|(_, &v)| v == value); if any { return Err(()); } } match index { 0 => self.split = value, 1 => self.reset = value, 2 => self.undo = value, 3 => self.skip = value, 4 => self.pause = value, 5 => self.undo_all_pauses = value, 6 => self.previous_comparison = value, 7 => self.next_comparis
random
[ { "content": "/// Registers a clock as the global handler for providing the high precision\n\n/// time stamps on a `no_std` target.\n\npub fn register_clock(clock: impl Clock) {\n\n let clock: Box<dyn Clock> = Box::new(clock);\n\n let clock = Box::new(clock);\n\n // FIXME: This isn't entirely clean as ...
Rust
sqldb/rust/src/sqldb.rs
thomastaylor312/interfaces
621d0d88772db85591d8625cca82264799e6ef64
#![allow(unused_imports, clippy::ptr_arg, clippy::needless_lifetimes)] use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, io::Write, string::ToString}; use wasmbus_rpc::{ deserialize, serialize, Context, Message, MessageDispatch, RpcError, RpcResult, SendOpts, Timestamp, Transport, }; pub const SMITHY_VERSION: &str = "1.0"; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct Column { pub ordinal: u32, #[serde(default)] pub name: String, #[serde(rename = "dbType")] #[serde(default)] pub db_type: String, } pub type Columns = Vec<Column>; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct ExecuteResult { #[serde(rename = "rowsAffected")] pub rows_affected: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<SqlDbError>, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct FetchResult { #[serde(rename = "numRows")] pub num_rows: u64, pub columns: Columns, #[serde(with = "serde_bytes")] #[serde(default)] pub rows: Vec<u8>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<SqlDbError>, } pub type Query = String; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct SqlDbError { #[serde(default)] pub code: String, #[serde(default)] pub message: String, } #[async_trait] pub trait SqlDb { fn contract_id() -> &'static str { "wasmcloud:sqldb" } async fn execute(&self, ctx: &Context, arg: &Query) -> RpcResult<ExecuteResult>; async fn fetch(&self, ctx: &Context, arg: &Query) -> RpcResult<FetchResult>; } #[doc(hidden)] #[async_trait] pub trait SqlDbReceiver: MessageDispatch + SqlDb { async fn dispatch(&self, ctx: &Context, message: &Message<'_>) -> RpcResult<Message<'_>> { match message.method { "Execute" => { let value: Query = deserialize(message.arg.as_ref()) .map_err(|e| RpcError::Deser(format!("message '{}': {}", message.method, e)))?; let resp = SqlDb::execute(self, ctx, &value).await?; let buf = serialize(&resp)?; Ok(Message { method: "SqlDb.Execute", arg: Cow::Owned(buf), }) } "Fetch" => { let value: Query = deserialize(message.arg.as_ref()) .map_err(|e| RpcError::Deser(format!("message '{}': {}", message.method, e)))?; let resp = SqlDb::fetch(self, ctx, &value).await?; let buf = serialize(&resp)?; Ok(Message { method: "SqlDb.Fetch", arg: Cow::Owned(buf), }) } _ => Err(RpcError::MethodNotHandled(format!( "SqlDb::{}", message.method ))), } } } #[derive(Debug)] pub struct SqlDbSender<T: Transport> { transport: T, } impl<T: Transport> SqlDbSender<T> { pub fn via(transport: T) -> Self { Self { transport } } pub fn set_timeout(&self, interval: std::time::Duration) { self.transport.set_timeout(interval); } } #[cfg(target_arch = "wasm32")] impl SqlDbSender<wasmbus_rpc::actor::prelude::WasmHost> { pub fn new() -> Self { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", "default") .unwrap(); Self { transport } } pub fn new_with_link(link_name: &str) -> wasmbus_rpc::RpcResult<Self> { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", link_name)?; Ok(Self { transport }) } } #[async_trait] impl<T: Transport + std::marker::Sync + std::marker::Send> SqlDb for SqlDbSender<T> { #[allow(unused)] async fn execute(&self, ctx: &Context, arg: &Query) -> RpcResult<ExecuteResult> { let buf = serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "SqlDb.Execute", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value = deserialize(&resp) .map_err(|e| RpcError::Deser(format!("response to {}: {}", "Execute", e)))?; Ok(value) } #[allow(unused)] async fn fetch(&self, ctx: &Context, arg: &Query) -> RpcResult<FetchResult> { let buf = serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "SqlDb.Fetch", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value = deserialize(&resp) .map_err(|e| RpcError::Deser(format!("response to {}: {}", "Fetch", e)))?; Ok(value) } }
#![allow(unused_imports, clippy::ptr_arg, clippy::needless_lifetimes)] use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::{borrow::Cow, io::Write, string::ToString}; use wasmbus_rpc::{ deserialize, serialize, Context, Message, MessageDispatch, RpcError, RpcResult, SendOpts, Timestamp, Transport, }; pub const SMITHY_VERSION: &str = "1.0"; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct Column { pub ordinal: u32, #[serde(default)] pub name: String, #[serde(rename = "dbType")] #[serde(default)] pub db_type: String, } pub type Columns = Vec<Column>; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct ExecuteResult { #[serde(rename = "rowsAffected")] pub rows_affected: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<SqlDbError>, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct FetchResult { #[serde(rename = "numRows")] pub num_rows: u64, pub columns: Columns, #[serde(with = "serde_bytes")] #[serde(default)] pub rows: Vec<u8>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<SqlDbError>, } pub type Query = String; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct SqlDbError { #[serde(default)] pub code: String, #[serde(default)] pub message: String, } #[async_trait] pub trait SqlDb { fn contract_id() -> &'static str { "wasmcloud:sqldb" } async fn execute(&self, ctx: &Context, arg: &Query) -> RpcResult<ExecuteResult>; async fn fetch(&self, ctx: &Context, arg: &Query) -> RpcResult<FetchResult>; } #[doc(hidden)] #[async_trait] pub trait SqlDbReceiver: MessageDispatch + SqlDb { async fn dispatch(&self, ctx: &Context, message: &Message<'_>) -> RpcResult<Message<'_>> { match message.method { "Execute" => { let value: Query = deserialize(message.arg.as_ref()) .map_err(|e| RpcError::Deser(format!("message '{}': {}", message.method, e)))?; let resp = SqlDb::execute(self, ctx, &value).await?; let buf = serialize(&resp)?; Ok(Message { method: "SqlDb.Execute", arg: Cow::Owned(buf), }) } "Fetch" => { let value: Query = deserialize(message.arg.as_ref()) .
} #[derive(Debug)] pub struct SqlDbSender<T: Transport> { transport: T, } impl<T: Transport> SqlDbSender<T> { pub fn via(transport: T) -> Self { Self { transport } } pub fn set_timeout(&self, interval: std::time::Duration) { self.transport.set_timeout(interval); } } #[cfg(target_arch = "wasm32")] impl SqlDbSender<wasmbus_rpc::actor::prelude::WasmHost> { pub fn new() -> Self { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", "default") .unwrap(); Self { transport } } pub fn new_with_link(link_name: &str) -> wasmbus_rpc::RpcResult<Self> { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider("wasmcloud:sqldb", link_name)?; Ok(Self { transport }) } } #[async_trait] impl<T: Transport + std::marker::Sync + std::marker::Send> SqlDb for SqlDbSender<T> { #[allow(unused)] async fn execute(&self, ctx: &Context, arg: &Query) -> RpcResult<ExecuteResult> { let buf = serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "SqlDb.Execute", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value = deserialize(&resp) .map_err(|e| RpcError::Deser(format!("response to {}: {}", "Execute", e)))?; Ok(value) } #[allow(unused)] async fn fetch(&self, ctx: &Context, arg: &Query) -> RpcResult<FetchResult> { let buf = serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "SqlDb.Fetch", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value = deserialize(&resp) .map_err(|e| RpcError::Deser(format!("response to {}: {}", "Fetch", e)))?; Ok(value) } }
map_err(|e| RpcError::Deser(format!("message '{}': {}", message.method, e)))?; let resp = SqlDb::fetch(self, ctx, &value).await?; let buf = serialize(&resp)?; Ok(Message { method: "SqlDb.Fetch", arg: Cow::Owned(buf), }) } _ => Err(RpcError::MethodNotHandled(format!( "SqlDb::{}", message.method ))), } }
function_block-function_prefix_line
[ { "content": "#[doc(hidden)]\n\n#[async_trait]\n\npub trait KeyValueReceiver: MessageDispatch + KeyValue {\n\n async fn dispatch(&self, ctx: &Context, message: &Message<'_>) -> RpcResult<Message<'_>> {\n\n match message.method {\n\n \"Increment\" => {\n\n let value: Increment...
Rust
src/usbdcd/control/mod.rs
Meptl/mk20d7
c7cd01cf55214b0b53fae7c7672607e739b64663
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONTROL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `IF`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IFR { #[doc = "No interrupt is pending."] _0, #[doc = "An interrupt is pending."] _1, } impl IFR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { IFR::_0 => false, IFR::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IFR { match value { false => IFR::_0, true => IFR::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == IFR::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == IFR::_1 } } #[doc = "Possible values of the field `IE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IER { #[doc = "Disable interrupts to the system."] _0, #[doc = "Enable interrupts to the system."] _1, } impl IER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { IER::_0 => false, IER::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IER { match value { false => IER::_0, true => IER::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == IER::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == IER::_1 } } #[doc = "Values that can be written to the field `IACK`"] pub enum IACKW { #[doc = "Do not clear the interrupt."] _0, #[doc = "Clear the IF bit (interrupt flag)."] _1, } impl IACKW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { IACKW::_0 => false, IACKW::_1 => true, } } } #[doc = r" Proxy"] pub struct _IACKW<'a> { w: &'a mut W, } impl<'a> _IACKW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IACKW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not clear the interrupt."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(IACKW::_0) } #[doc = "Clear the IF bit (interrupt flag)."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(IACKW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `IE`"] pub enum IEW { #[doc = "Disable interrupts to the system."] _0, #[doc = "Enable interrupts to the system."] _1, } impl IEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { IEW::_0 => false, IEW::_1 => true, } } } #[doc = r" Proxy"] pub struct _IEW<'a> { w: &'a mut W, } impl<'a> _IEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable interrupts to the system."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(IEW::_0) } #[doc = "Enable interrupts to the system."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(IEW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `START`"] pub enum STARTW { #[doc = "Do not start the sequence. Writes of this value have no effect."] _0, #[doc = "Initiate the charger detection sequence. If the sequence is already running, writes of this value have no effect."] _1, } impl STARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { STARTW::_0 => false, STARTW::_1 => true, } } } #[doc = r" Proxy"] pub struct _STARTW<'a> { w: &'a mut W, } impl<'a> _STARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: STARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not start the sequence. Writes of this value have no effect."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(STARTW::_0) } #[doc = "Initiate the charger detection sequence. If the sequence is already running, writes of this value have no effect."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(STARTW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SR`"] pub enum SRW { #[doc = "Do not perform a software reset."] _0, #[doc = "Perform a software reset."] _1, } impl SRW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SRW::_0 => false, SRW::_1 => true, } } } #[doc = r" Proxy"] pub struct _SRW<'a> { w: &'a mut W, } impl<'a> _SRW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SRW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not perform a software reset."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(SRW::_0) } #[doc = "Perform a software reset."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(SRW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 8 - Interrupt Flag"] #[inline] pub fn if_(&self) -> IFR { IFR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 16 - Interrupt Enable"] #[inline] pub fn ie(&self) -> IER { IER::_from({ const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 65536 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Interrupt Acknowledge"] #[inline] pub fn iack(&mut self) -> _IACKW { _IACKW { w: self } } #[doc = "Bit 16 - Interrupt Enable"] #[inline] pub fn ie(&mut self) -> _IEW { _IEW { w: self } } #[doc = "Bit 24 - Start Change Detection Sequence"] #[inline] pub fn start(&mut self) -> _STARTW { _STARTW { w: self } } #[doc = "Bit 25 - Software Reset"] #[inline] pub fn sr(&mut self) -> _SRW { _SRW { w: self } } }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CONTROL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = "Possible values of the field `IF`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IFR { #[doc = "No interrupt is pending."] _0, #[doc = "An interrupt is pending."] _1, } impl IFR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline]
#[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IFR { match value { false => IFR::_0, true => IFR::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == IFR::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == IFR::_1 } } #[doc = "Possible values of the field `IE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IER { #[doc = "Disable interrupts to the system."] _0, #[doc = "Enable interrupts to the system."] _1, } impl IER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { IER::_0 => false, IER::_1 => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> IER { match value { false => IER::_0, true => IER::_1, } } #[doc = "Checks if the value of the field is `_0`"] #[inline] pub fn is_0(&self) -> bool { *self == IER::_0 } #[doc = "Checks if the value of the field is `_1`"] #[inline] pub fn is_1(&self) -> bool { *self == IER::_1 } } #[doc = "Values that can be written to the field `IACK`"] pub enum IACKW { #[doc = "Do not clear the interrupt."] _0, #[doc = "Clear the IF bit (interrupt flag)."] _1, } impl IACKW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { IACKW::_0 => false, IACKW::_1 => true, } } } #[doc = r" Proxy"] pub struct _IACKW<'a> { w: &'a mut W, } impl<'a> _IACKW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IACKW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not clear the interrupt."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(IACKW::_0) } #[doc = "Clear the IF bit (interrupt flag)."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(IACKW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `IE`"] pub enum IEW { #[doc = "Disable interrupts to the system."] _0, #[doc = "Enable interrupts to the system."] _1, } impl IEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { IEW::_0 => false, IEW::_1 => true, } } } #[doc = r" Proxy"] pub struct _IEW<'a> { w: &'a mut W, } impl<'a> _IEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: IEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable interrupts to the system."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(IEW::_0) } #[doc = "Enable interrupts to the system."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(IEW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 16; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `START`"] pub enum STARTW { #[doc = "Do not start the sequence. Writes of this value have no effect."] _0, #[doc = "Initiate the charger detection sequence. If the sequence is already running, writes of this value have no effect."] _1, } impl STARTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { STARTW::_0 => false, STARTW::_1 => true, } } } #[doc = r" Proxy"] pub struct _STARTW<'a> { w: &'a mut W, } impl<'a> _STARTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: STARTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not start the sequence. Writes of this value have no effect."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(STARTW::_0) } #[doc = "Initiate the charger detection sequence. If the sequence is already running, writes of this value have no effect."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(STARTW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 24; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SR`"] pub enum SRW { #[doc = "Do not perform a software reset."] _0, #[doc = "Perform a software reset."] _1, } impl SRW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SRW::_0 => false, SRW::_1 => true, } } } #[doc = r" Proxy"] pub struct _SRW<'a> { w: &'a mut W, } impl<'a> _SRW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SRW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Do not perform a software reset."] #[inline] pub fn _0(self) -> &'a mut W { self.variant(SRW::_0) } #[doc = "Perform a software reset."] #[inline] pub fn _1(self) -> &'a mut W { self.variant(SRW::_1) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 25; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 8 - Interrupt Flag"] #[inline] pub fn if_(&self) -> IFR { IFR::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 16 - Interrupt Enable"] #[inline] pub fn ie(&self) -> IER { IER::_from({ const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 65536 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Interrupt Acknowledge"] #[inline] pub fn iack(&mut self) -> _IACKW { _IACKW { w: self } } #[doc = "Bit 16 - Interrupt Enable"] #[inline] pub fn ie(&mut self) -> _IEW { _IEW { w: self } } #[doc = "Bit 24 - Start Change Detection Sequence"] #[inline] pub fn start(&mut self) -> _STARTW { _STARTW { w: self } } #[doc = "Bit 25 - Software Reset"] #[inline] pub fn sr(&mut self) -> _SRW { _SRW { w: self } } }
pub fn bit(&self) -> bool { match *self { IFR::_0 => false, IFR::_1 => true, } }
function_block-full_function
[ { "content": "fn main() {\n\n if env::var_os(\"CARGO_FEATURE_RT\").is_some() {\n\n let out = &PathBuf::from(env::var_os(\"OUT_DIR\").unwrap());\n\n File::create(out.join(\"device.x\"))\n\n .unwrap()\n\n .write_all(include_bytes!(\"device.x\"))\n\n .unwrap();\n\n...
Rust
src/utils/redis/pubsub.rs
greglearns/portier-broker
935fcce0405fd0e3ac70ee8922c0f62bf0823a75
use futures_util::future::poll_fn; use redis::{ConnectionAddr, ConnectionInfo, ErrorKind, RedisError, RedisResult, Value}; use std::collections::hash_map::{Entry, HashMap}; use std::future::Future; use std::io::Result as IoResult; use std::net::ToSocketAddrs; use std::pin::Pin; use std::task::Poll; use tokio::io::{self, AsyncWriteExt}; use tokio::net::TcpStream; use tokio::stream::Stream; use tokio::sync::{broadcast, mpsc, oneshot}; #[cfg(unix)] use tokio::net::UnixStream; struct ReadHalf(io::BufReader<Box<dyn io::AsyncRead + Unpin + Send>>); impl ReadHalf { async fn read(&mut self) -> RedisResult<Value> { redis::parse_redis_value_async(&mut self.0).await } } struct WriteHalf(Box<dyn io::AsyncWrite + Unpin + Send>); impl WriteHalf { async fn write(&mut self, cmd: &[&[u8]]) -> IoResult<()> { let mut data = format!("*{}\r\n", cmd.len()).into_bytes(); for part in cmd { data.append(&mut format!("${}\r\n", part.len()).into_bytes()); data.extend_from_slice(part); data.extend_from_slice(b"\r\n"); } self.0.write_all(&data).await } } pub type RecvChan = broadcast::Receiver<Vec<u8>>; type ReplyChan = oneshot::Sender<RecvChan>; struct Cmd { chan: Vec<u8>, reply: ReplyChan, } struct Sub { tx: broadcast::Sender<Vec<u8>>, pending: Option<Vec<ReplyChan>>, } enum LoopEvent { Cmd(Cmd), CmdClosed, Interval, Read((RedisResult<Value>, ReadHalf)), } async fn conn_loop(mut rx: ReadHalf, mut tx: WriteHalf, mut cmd: mpsc::Receiver<Cmd>) { let interval = tokio::time::interval(tokio::time::Duration::from_secs(20)); tokio::pin!(interval); interval.as_mut().tick().await; let mut read_fut: Pin<Box<dyn Future<Output = _> + Send>> = Box::pin(async move { let res = rx.read().await; (res, rx) }); let mut subs: HashMap<Vec<u8>, Sub> = HashMap::new(); loop { match poll_fn(|cx| { if let Poll::Ready(res) = cmd.poll_recv(cx) { match res { Some(cmd) => Poll::Ready(LoopEvent::Cmd(cmd)), None => Poll::Ready(LoopEvent::CmdClosed), } } else if let Poll::Ready(_) = interval.as_mut().poll_next(cx) { Poll::Ready(LoopEvent::Interval) } else if let Poll::Ready(res) = read_fut.as_mut().poll(cx) { Poll::Ready(LoopEvent::Read(res)) } else { Poll::Pending } }) .await { LoopEvent::Cmd(Cmd { chan, reply }) => match subs.entry(chan.clone()) { Entry::Occupied(mut entry) => { let sub = entry.get_mut(); if let Some(ref mut pending) = sub.pending { pending.push(reply); } else { let _ = reply.send(sub.tx.subscribe()); } } Entry::Vacant(entry) => { entry.insert(Sub { tx: broadcast::channel(8).0, pending: Some(vec![reply]), }); tx.write(&[b"SUBSCRIBE", &chan]) .await .expect("Failed to send subscribe command to Redis"); } }, LoopEvent::CmdClosed => { unimplemented!(); } LoopEvent::Interval => { let to_unsub: Vec<Vec<u8>> = subs .iter() .filter_map(|(chan, sub)| { if sub.pending.is_none() && sub.tx.receiver_count() == 0 { Some(chan.clone()) } else { None } }) .collect(); if to_unsub.is_empty() { tx.write(&[b"PING"]) .await .expect("Failed to send ping command to Redis"); } else { for chan in &to_unsub { subs.remove(chan); } let mut unsub_cmd: Vec<&[u8]> = vec![b"UNSUBSCRIBE"]; unsub_cmd.extend(to_unsub.iter().map(|chan| &chan[..])); tx.write(&unsub_cmd) .await .expect("Failed to send unsubscribe command to Redis"); } } LoopEvent::Read((res, mut rx)) => { read_fut = Box::pin(async move { let res = rx.read().await; (res, rx) }); let value = res.expect("Failed to read from Redis"); let vec = match value { Value::Status(status) if status == "PONG" => continue, Value::Bulk(ref vec) if vec.len() >= 2 => vec, _ => panic!("Unexpected value from Redis: {:?}", value), }; match (&vec[0], &vec[1], vec.get(2)) { ( &Value::Data(ref ev), &Value::Data(ref chan), Some(&Value::Data(ref data)), ) if ev == b"message" => { if let Some(ref sub) = subs.get(&chan[..]) { let _ = sub.tx.send(data.to_vec()); } } (&Value::Data(ref ev), &Value::Data(ref chan), _) if ev == b"subscribe" => { if let Some(ref mut sub) = subs.get_mut(&chan[..]) { if let Some(pending) = sub.pending.take() { for reply in pending { let _ = reply.send(sub.tx.subscribe()); } } } } (&Value::Data(ref ev), _, _) if ev == b"unsubscribe" || ev == b"pong" => {} _ => panic!("Unexpected value from Redis: {:?}", value), } } } } } #[derive(Clone)] pub struct Subscriber { cmd: mpsc::Sender<Cmd>, } impl Subscriber { pub async fn subscribe(&mut self, chan: Vec<u8>) -> broadcast::Receiver<Vec<u8>> { let (reply_tx, reply_rx) = oneshot::channel(); let cmd = Cmd { chan, reply: reply_tx, }; if self.cmd.send(cmd).await.is_ok() { if let Ok(rx) = reply_rx.await { return rx; } } panic!("Tried to subscribe on closed pubsub connection"); } } pub async fn connect(info: &ConnectionInfo) -> RedisResult<Subscriber> { let (rx, tx): ( Box<dyn io::AsyncRead + Unpin + Send>, Box<dyn io::AsyncWrite + Unpin + Send>, ) = match *info.addr { ConnectionAddr::Tcp(ref host, port) => { let socket_addr = { let mut socket_addrs = (&host[..], port).to_socket_addrs()?; match socket_addrs.next() { Some(socket_addr) => socket_addr, None => { return Err(RedisError::from(( ErrorKind::InvalidClientConfig, "No address found for host", ))); } } }; let (rx, tx) = io::split(TcpStream::connect(&socket_addr).await?); (Box::new(rx), Box::new(tx)) } #[cfg(unix)] ConnectionAddr::Unix(ref path) => { let (rx, tx) = io::split(UnixStream::connect(path).await?); (Box::new(rx), Box::new(tx)) } #[cfg(not(unix))] ConnectionAddr::Unix(_) => { return Err(RedisError::from(( ErrorKind::InvalidClientConfig, "Cannot connect to unix sockets \ on this platform", ))) } }; let mut rx = ReadHalf(io::BufReader::new(rx)); let mut tx = WriteHalf(tx); if let Some(ref passwd) = info.passwd { tx.write(&[b"AUTH", passwd.as_bytes()]).await?; match rx.read().await { Ok(Value::Okay) => (), _ => { return Err(( ErrorKind::AuthenticationFailed, "Password authentication failed", ) .into()); } } } let (cmd_tx, cmd_rx) = mpsc::channel(8); tokio::spawn(conn_loop(rx, tx, cmd_rx)); Ok(Subscriber { cmd: cmd_tx }) }
use futures_util::future::poll_fn; use redis::{ConnectionAddr, ConnectionInfo, ErrorKind, RedisError, RedisResult, Value}; use std::collections::hash_map::{Entry, HashMap}; use std::future::Future; use std::io::Result as IoResult; use std::net::ToSocketAddrs; use std::pin::Pin; use std::task::Poll; use tokio::io::{self, AsyncWriteExt}; use tokio::net::TcpStream; use tokio::stream::Stream; use tokio::sync::{broadcast, mpsc, oneshot}; #[cfg(unix)] use tokio::net::UnixStream; struct ReadHalf(io::BufReader<Box<dyn io::AsyncRead + Unpin + Send>>); impl ReadHalf { async fn read(&mut self) -> RedisResult<Value> { redis::parse_redis_value_async(&mut self.0).await } } struct WriteHalf(Box<dyn io::AsyncWrite + Unpin + Send>); impl WriteHalf { async fn write(&mut self, cmd: &[&[u8]]) -> IoResult<()> { let mut data = format!("*{}\r\n", cmd.len()).into_bytes(); for part in cmd { data.append(&mut format!("${}\r\n", part.len()).into_bytes()); data.extend_from_slice(part); data.extend_from_slice(b"\r\n"); } self.0.write_all(&data).await } } pub type RecvChan = broadcast::Receiver<Vec<u8>>; type ReplyChan = oneshot::Sender<RecvChan>; struct Cmd { chan: Vec<u8>, reply: ReplyChan, } struct Sub { tx: broadcast::Sender<Vec<u8>>, pending: Option<Vec<ReplyChan>>, } enum LoopEvent { Cmd(Cmd), CmdClosed, Interval, Read((RedisResult<Value>, ReadHalf)), } async fn conn_loop(mut rx: ReadHalf, mut tx: WriteHalf, mut cmd: mpsc::Receiver<Cmd>) { let interval = tokio::time::interval(tokio::time::Duration::from_secs(20)); tokio::pin!(interval); interval.as_mut().tick().await; let mut read_fut: Pin<Box<dyn Future<Output = _> + Send>> = Box::pin(async move { let res = rx.read().await; (res, rx) }); let mut subs: HashMap<Vec<u8>, Sub> = HashMap::new(); loop { match poll_fn(|cx| { if let Poll::Ready(res) = cmd.poll_recv(cx) { match res { Some(cmd) => Poll::Ready(LoopEvent::Cmd(cmd)), None => Poll::Ready(LoopEvent::CmdClosed), } } else if let Poll::Ready(_) = interval.as_mut().poll_next(cx) { Poll::Ready(LoopEvent::Interval) } else if let Poll::Ready(res) = read_fut.as_mut().poll(cx) { Poll::Ready(LoopEvent::Read(res)) } else { Poll::Pending } }) .await { LoopEvent::Cmd(Cmd { chan, reply }) => match subs.entry(chan.clone()) { Entry::Occupied(mut entry) => { let sub = entry.get_mut(); if let Some(ref mut pending) = sub.pending { pending.push(reply); } else { let _ = reply.send(sub.tx.subscribe()); } } Entry::Vacant(entry) => { entry.insert(Sub { tx: broadcast::channel(8).0, pending: Some(vec![reply]), }); tx.write(&[b"SUBSCRIBE", &chan]) .await .expect("Failed to send subscribe command to Redis"); } }, LoopEvent::CmdClosed => { unimplemented!(); } LoopEvent::Interval => { let to_unsub: Vec<Vec<u8>> = subs .iter() .filter_map(|(chan, sub)| { if sub.pending.is_none() && sub.tx.receiver_count() == 0 { Some(chan.clone()) } else { None } }) .collect(); if to_unsub.is_empty() { tx.write(&[b"PING"]) .await .expect("Failed to send ping command to Redis"); } else { for chan in &to_unsub { subs.remove(chan); } let mut unsub_cmd: Vec<&[u8]> = vec![b"UNSUBSCRIBE"]; unsub_cmd.extend(to_unsub.iter().map(|chan| &chan[..])); tx.write(&unsub_cmd) .await .expect("Failed to send unsubscribe command to Redis"); } } LoopEvent::Read((res, mut rx)) => { read_fut = Box::pin(async move { let res = rx.read().await; (res, rx) }); let value = res.expect("Failed to read from Redis"); let vec = match value { Value::Status(status) if status == "PONG" => continue, Value::Bulk(ref vec) if vec.len() >= 2 => vec, _ => panic!("Unexpected value from Redis: {:?}", value), }; match (&vec[0], &vec[1], vec.get(2)) { ( &Value::Data(ref ev), &Value::Data(ref chan), Some(&Value::Data(ref data)), ) if ev == b"message" => { if let Some(ref sub) = subs.get(&chan[..]) { let _ = sub.tx.send(data.to_vec()); } } (&Value::Data(ref ev), &Value::Data(ref chan), _) if ev == b"subscribe" => { if let Some(ref mut sub) = subs.get_mut(&chan[..]) { if let Some(pending) = sub.pending.take() { for reply in pending { let _ = reply.send(sub.tx.subscribe()); } } } } (&Value::Data(ref ev), _, _) if ev == b"unsubscribe" || ev == b"pong" => {} _ => panic!("Unexpected value from Redis: {:?}", value), } } } } } #[derive(Clone)] pub struct Subscriber { cmd: mpsc::Sender<Cmd>, } impl Subscriber { pub async fn subscribe(&mut self, chan: Vec<u8>) -> broadcast::Receiver<Vec<u8>> { let (reply_tx, reply_rx) = oneshot::channel(); let cmd = Cmd { chan,
} panic!("Tried to subscribe on closed pubsub connection"); } } pub async fn connect(info: &ConnectionInfo) -> RedisResult<Subscriber> { let (rx, tx): ( Box<dyn io::AsyncRead + Unpin + Send>, Box<dyn io::AsyncWrite + Unpin + Send>, ) = match *info.addr { ConnectionAddr::Tcp(ref host, port) => { let socket_addr = { let mut socket_addrs = (&host[..], port).to_socket_addrs()?; match socket_addrs.next() { Some(socket_addr) => socket_addr, None => { return Err(RedisError::from(( ErrorKind::InvalidClientConfig, "No address found for host", ))); } } }; let (rx, tx) = io::split(TcpStream::connect(&socket_addr).await?); (Box::new(rx), Box::new(tx)) } #[cfg(unix)] ConnectionAddr::Unix(ref path) => { let (rx, tx) = io::split(UnixStream::connect(path).await?); (Box::new(rx), Box::new(tx)) } #[cfg(not(unix))] ConnectionAddr::Unix(_) => { return Err(RedisError::from(( ErrorKind::InvalidClientConfig, "Cannot connect to unix sockets \ on this platform", ))) } }; let mut rx = ReadHalf(io::BufReader::new(rx)); let mut tx = WriteHalf(tx); if let Some(ref passwd) = info.passwd { tx.write(&[b"AUTH", passwd.as_bytes()]).await?; match rx.read().await { Ok(Value::Okay) => (), _ => { return Err(( ErrorKind::AuthenticationFailed, "Password authentication failed", ) .into()); } } } let (cmd_tx, cmd_rx) = mpsc::channel(8); tokio::spawn(conn_loop(rx, tx, cmd_rx)); Ok(Subscriber { cmd: cmd_tx }) }
reply: reply_tx, }; if self.cmd.send(cmd).await.is_ok() { if let Ok(rx) = reply_rx.await { return rx; }
function_block-random_span
[ { "content": "#[inline]\n\npub fn decode<T: ?Sized + AsRef<[u8]>>(data: &T) -> Result<Vec<u8>, ()> {\n\n base64::decode_config(data, base64::URL_SAFE_NO_PAD).map_err(|_| ())\n\n}\n", "file_path": "src/utils/base64url.rs", "rank": 2, "score": 202123.42041081307 }, { "content": "/// Parse a...
Rust
src/util.rs
HEnquist/flexi_logger
5a89eb567d35a7821b682e95e9328859b133c042
use crate::{deferred_now::DeferredNow, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::Write; #[cfg(test)] use std::io::Cursor; #[cfg(test)] use std::sync::{Arc, Mutex}; #[cfg(feature = "async")] pub(crate) const ASYNC_FLUSH: &[u8] = b"F"; #[cfg(feature = "async")] pub(crate) const ASYNC_SHUTDOWN: &[u8] = b"S"; #[derive(Copy, Clone, Debug)] pub(crate) enum ERRCODE { Write, Flush, Format, Poison, LogFile, #[cfg(feature = "specfile_without_notification")] LogSpecFile, #[cfg(target_os = "linux")] Symlink, } impl ERRCODE { fn as_index(self) -> &'static str { match self { Self::Write => "write", Self::Flush => "flush", Self::Format => "format", Self::Poison => "poison", Self::LogFile => "logfile", #[cfg(feature = "specfile_without_notification")] Self::LogSpecFile => "logspecfile", #[cfg(target_os = "linux")] Self::Symlink => "symlink", } } } pub(crate) fn eprint_err(errcode: ERRCODE, msg: &str, err: &dyn std::error::Error) { eprintln!( "[flexi_logger][ERRCODE::{code:?}] {msg}, caused by {err}\n\ See https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html#{code_lc}", msg = msg, err = err, code = errcode, code_lc = errcode.as_index(), ); } pub(crate) fn io_err(s: &'static str) -> std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, s) } pub(crate) fn buffer_with<F>(f: F) where F: FnOnce(&RefCell<Vec<u8>>), { thread_local! { static BUFFER: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(200)); } BUFFER.with(f); } pub(crate) fn write_buffered( format_function: FormatFunction, now: &mut DeferredNow, record: &Record, w: &mut dyn Write, #[cfg(test)] o_validation_buffer: Option<&Arc<Mutex<Cursor<Vec<u8>>>>>, ) -> Result<(), std::io::Error> { let mut result: Result<(), std::io::Error> = Ok(()); buffer_with(|tl_buf| match tl_buf.try_borrow_mut() { Ok(mut buffer) => { (format_function)(&mut *buffer, now, record) .unwrap_or_else(|e| eprint_err(ERRCODE::Format, "formatting failed", &e)); buffer .write_all(b"\n") .unwrap_or_else(|e| eprint_err(ERRCODE::Write, "writing failed", &e)); result = w.write_all(&*buffer).map_err(|e| { eprint_err(ERRCODE::Write, "writing failed", &e); e }); #[cfg(test)] if let Some(valbuf) = o_validation_buffer { valbuf.lock().unwrap().write_all(&*buffer).ok(); } buffer.clear(); } Err(_e) => { let mut tmp_buf = Vec::<u8>::with_capacity(200); (format_function)(&mut tmp_buf, now, record) .unwrap_or_else(|e| eprint_err(ERRCODE::Format, "formatting failed", &e)); tmp_buf .write_all(b"\n") .unwrap_or_else(|e| eprint_err(ERRCODE::Write, "writing failed", &e)); result = w.write_all(&tmp_buf).map_err(|e| { eprint_err(ERRCODE::Write, "writing failed", &e); e }); #[cfg(test)] if let Some(valbuf) = o_validation_buffer { valbuf.lock().unwrap().write_all(&tmp_buf).ok(); } } }); result }
use crate::{deferred_now::DeferredNow, FormatFunction}; use log::Record; use std::cell::RefCell; use std::io::Write; #[cfg(test)] use std::io::Cursor; #[cfg(test)] use std::sync::{Arc, Mutex}; #[cfg(feature = "async")] pub(crate) const ASYNC_FLUSH: &[u8] = b"F"; #[cfg(feature = "async")] pub(crate) const ASYNC_SHUTDOWN: &[u8] = b"S"; #[derive(Copy, Clone, Debug)] pub(crate) enum ERRCODE { Write, Flush, Format, Poison, LogFile, #[cfg(feature = "specfile_without_notification")] LogSpecFile, #[cfg(target_os = "linux")] Symlink, } impl ERRCODE { fn as_index(self) -> &'static str { match self { Self::Write => "write", Self::Flush => "flush", Self::Format => "format", Self::Poison => "poison", Self::LogFile => "logfile", #[cfg(feature = "specfile_without_notification")] Self::LogSpecFile => "logspecfile", #[cfg(target_os = "linux")] Self::Symlink => "symlink", } } } pub(crate) fn eprint_err(errcode: ERRCODE, msg: &str, err: &dyn std::error::Error) { eprintln!( "[flexi_logger][ERRCODE::{code:?}] {msg}, caused by {err}\n\ See https://docs.rs/flexi_logger/latest/flexi_logger/error_info/index.html#{code_lc}", msg = msg, err = err, code = errcode, code_lc = errcode.as_index(), ); } pub(crate) fn io_err(s: &'static str) -> std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, s) } pub(crate) fn buffer_with<F>(f: F) where F: FnOnce(&RefCell<Vec<u8>>), { thread_local! { static BUFFER: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(200)); } BUFFER.with(f); } pub(crate) fn write_buffered( format_function: FormatFunction, now: &mut DeferredNow, record: &Record, w: &mut dyn Write, #[cfg(test)] o_validation_buffer: Option<&Arc<Mutex<Cursor<Vec<u8>>>>>, ) -> Result<(), std::io::Error> { let mut result: Result<(), std::io::Error> = Ok(());
; result }
buffer_with(|tl_buf| match tl_buf.try_borrow_mut() { Ok(mut buffer) => { (format_function)(&mut *buffer, now, record) .unwrap_or_else(|e| eprint_err(ERRCODE::Format, "formatting failed", &e)); buffer .write_all(b"\n") .unwrap_or_else(|e| eprint_err(ERRCODE::Write, "writing failed", &e)); result = w.write_all(&*buffer).map_err(|e| { eprint_err(ERRCODE::Write, "writing failed", &e); e }); #[cfg(test)] if let Some(valbuf) = o_validation_buffer { valbuf.lock().unwrap().write_all(&*buffer).ok(); } buffer.clear(); } Err(_e) => { let mut tmp_buf = Vec::<u8>::with_capacity(200); (format_function)(&mut tmp_buf, now, record) .unwrap_or_else(|e| eprint_err(ERRCODE::Format, "formatting failed", &e)); tmp_buf .write_all(b"\n") .unwrap_or_else(|e| eprint_err(ERRCODE::Write, "writing failed", &e)); result = w.write_all(&tmp_buf).map_err(|e| { eprint_err(ERRCODE::Write, "writing failed", &e); e }); #[cfg(test)] if let Some(valbuf) = o_validation_buffer { valbuf.lock().unwrap().write_all(&tmp_buf).ok(); } } })
call_expression
[ { "content": "fn push_err(s: &str, parse_errs: &mut String) {\n\n if !parse_errs.is_empty() {\n\n parse_errs.push_str(\"; \");\n\n }\n\n parse_errs.push_str(s);\n\n}\n\n\n", "file_path": "src/log_specification.rs", "rank": 0, "score": 184303.19247900957 }, { "content": "fn co...
Rust
src/tools/clippy/clippy_lints/src/needless_arbitrary_self_type.rs
ohno418/rust
395a09c3dafe0c7838c9ca41d2b47bb5e79a5b6d
use clippy_utils::diagnostics::span_lint_and_sugg; use if_chain::if_chain; use rustc_ast::ast::{BindingMode, Lifetime, Mutability, Param, PatKind, Path, TyKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::kw; use rustc_span::Span; declare_clippy_lint! { #[clippy::version = "1.47.0"] pub NEEDLESS_ARBITRARY_SELF_TYPE, complexity, "type of `self` parameter is already by default `Self`" } declare_lint_pass!(NeedlessArbitrarySelfType => [NEEDLESS_ARBITRARY_SELF_TYPE]); enum Mode { Ref(Option<Lifetime>), Value, } fn check_param_inner(cx: &EarlyContext<'_>, path: &Path, span: Span, binding_mode: &Mode, mutbl: Mutability) { if_chain! { if let [segment] = &path.segments[..]; if segment.ident.name == kw::SelfUpper; then { let mut applicability = Applicability::MachineApplicable; let self_param = match (binding_mode, mutbl) { (Mode::Ref(None), Mutability::Mut) => "&mut self".to_string(), (Mode::Ref(Some(lifetime)), Mutability::Mut) => { if lifetime.ident.span.from_expansion() { applicability = Applicability::HasPlaceholders; "&'_ mut self".to_string() } else { format!("&{} mut self", &lifetime.ident.name) } }, (Mode::Ref(None), Mutability::Not) => "&self".to_string(), (Mode::Ref(Some(lifetime)), Mutability::Not) => { if lifetime.ident.span.from_expansion() { applicability = Applicability::HasPlaceholders; "&'_ self".to_string() } else { format!("&{} self", &lifetime.ident.name) } }, (Mode::Value, Mutability::Mut) => "mut self".to_string(), (Mode::Value, Mutability::Not) => "self".to_string(), }; span_lint_and_sugg( cx, NEEDLESS_ARBITRARY_SELF_TYPE, span, "the type of the `self` parameter does not need to be arbitrary", "consider to change this parameter to", self_param, applicability, ) } } } impl EarlyLintPass for NeedlessArbitrarySelfType { fn check_param(&mut self, cx: &EarlyContext<'_>, p: &Param) { if !p.is_self() || p.span.from_expansion() { return; } match &p.ty.kind { TyKind::Path(None, path) => { if let PatKind::Ident(BindingMode::ByValue(mutbl), _, _) = p.pat.kind { check_param_inner(cx, path, p.span.to(p.ty.span), &Mode::Value, mutbl); } }, TyKind::Rptr(lifetime, mut_ty) => { if_chain! { if let TyKind::Path(None, path) = &mut_ty.ty.kind; if let PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, _) = p.pat.kind; then { check_param_inner(cx, path, p.span.to(p.ty.span), &Mode::Ref(*lifetime), mut_ty.mutbl); } } }, _ => {}, } } }
use clippy_utils::diagnostics::span_lint_and_sugg; use if_chain::if_chain; use rustc_ast::ast::{BindingMode, Lifetime, Mutability, Param, PatKind, Path, TyKind}; use rustc_errors::Applicability; use rustc_lint::{EarlyContext, EarlyLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::kw; use rustc_span::Span; declare_clippy_lint! { #[clippy::version = "1.47.0"] pub NEEDLESS_ARBITRARY_SELF_TYPE, complexity, "type of `self` parameter is already by default `Self`" } declare_lint_pass!(NeedlessArbitrarySelfType => [NEEDLESS_ARBITRARY_SELF_TYPE]); enum Mode { Ref(Option<Lifetime>), Value, } fn check_param_inner(cx: &EarlyContext<'_>, path: &Path, span: Span, binding_mode: &Mode, mutbl: Mutability) { if_chain! { if let [segment] = &path.segments[..]; if segment.ident.name == kw::SelfUpper; then { let mut applicability = Applicability::MachineApplicable; let self_param = match (binding_mode, mutbl) { (Mode::Ref(None), Mutability::Mut) => "&mut self".to_string(), (Mode::Ref(Some(lifetime)), Mutability::Mut) => { if lifetime.ident.span.from_expansion() { applicability = Applicability::HasPlaceholders; "&'_ mut self".to_string() } else { format!("&{} mut self", &lifetime.ident.name) } }, (Mode::Ref(None), Mutability::Not) => "&self".to_string(), (Mode::Ref(Some(lifetime)), Mutability::Not) => { if lifetime.ident.span.from_expansion() { applicability = Applicability::HasPlaceholders; "&'_ self".to_string() } else { format!("&{} self", &lifetime.ident.name) } }, (Mode::Value, Mutability::Mut) => "mut self".to_string(), (Mode::Value, Mutability::Not) => "self
e of the `self` parameter does not need to be arbitrary", "consider to change this parameter to", self_param, applicability, ) } } } impl EarlyLintPass for NeedlessArbitrarySelfType { fn check_param(&mut self, cx: &EarlyContext<'_>, p: &Param) { if !p.is_self() || p.span.from_expansion() { return; } match &p.ty.kind { TyKind::Path(None, path) => { if let PatKind::Ident(BindingMode::ByValue(mutbl), _, _) = p.pat.kind { check_param_inner(cx, path, p.span.to(p.ty.span), &Mode::Value, mutbl); } }, TyKind::Rptr(lifetime, mut_ty) => { if_chain! { if let TyKind::Path(None, path) = &mut_ty.ty.kind; if let PatKind::Ident(BindingMode::ByValue(Mutability::Not), _, _) = p.pat.kind; then { check_param_inner(cx, path, p.span.to(p.ty.span), &Mode::Ref(*lifetime), mut_ty.mutbl); } } }, _ => {}, } } }
".to_string(), }; span_lint_and_sugg( cx, NEEDLESS_ARBITRARY_SELF_TYPE, span, "the typ
random
[]
Rust
storage/aptosdb/src/pruner/mod.rs
JoshLind/aptos-core
a58a87106bde10eccb8954128cd31700b76e95c1
mod db_pruner; pub(crate) mod db_sub_pruner; pub(crate) mod event_store; mod ledger_store; pub(crate) mod state_store; pub(crate) mod transaction_store; pub mod utils; pub(crate) mod worker; use crate::metrics::APTOS_STORAGE_PRUNE_WINDOW; use aptos_config::config::StoragePrunerConfig; use aptos_infallible::Mutex; use crate::{EventStore, LedgerStore, TransactionStore}; use aptos_types::transaction::Version; use schemadb::DB; use std::{ sync::{ mpsc::{channel, Sender}, Arc, }, thread::JoinHandle, }; use worker::{Command, Worker}; #[derive(Debug)] pub(crate) struct Pruner { state_store_prune_window: Version, ledger_prune_window: Version, worker_thread: Option<JoinHandle<()>>, command_sender: Mutex<Sender<Command>>, #[allow(dead_code)] least_readable_version: Arc<Mutex<Vec<Version>>>, last_version_sent_to_pruners: Arc<Mutex<Version>>, pruning_batch_size: usize, latest_version: Arc<Mutex<Version>>, } #[cfg(test)] pub enum PrunerIndex { StateStorePrunerIndex, LedgerPrunerIndex, } impl Pruner { pub fn new( db: Arc<DB>, storage_pruner_config: StoragePrunerConfig, transaction_store: Arc<TransactionStore>, ledger_store: Arc<LedgerStore>, event_store: Arc<EventStore>, ) -> Self { let (command_sender, command_receiver) = channel(); let least_readable_version = Arc::new(Mutex::new(vec![0, 0, 0, 0, 0])); let worker_progress_clone = Arc::clone(&least_readable_version); APTOS_STORAGE_PRUNE_WINDOW.set( storage_pruner_config .state_store_prune_window .expect("State store pruner window is required") as i64, ); let worker = Worker::new( db, transaction_store, ledger_store, event_store, command_receiver, least_readable_version, storage_pruner_config.pruning_batch_size as u64, ); let worker_thread = std::thread::Builder::new() .name("aptosdb_pruner".into()) .spawn(move || worker.work()) .expect("Creating pruner thread should succeed."); Self { state_store_prune_window: storage_pruner_config .state_store_prune_window .expect("State store prune window must be specified"), ledger_prune_window: storage_pruner_config .ledger_prune_window .expect("Default prune window must be specified"), worker_thread: Some(worker_thread), command_sender: Mutex::new(command_sender), least_readable_version: worker_progress_clone, last_version_sent_to_pruners: Arc::new(Mutex::new(0)), pruning_batch_size: storage_pruner_config.pruning_batch_size, latest_version: Arc::new(Mutex::new(0)), } } pub fn get_state_store_pruner_window(&self) -> Version { self.state_store_prune_window } pub fn maybe_wake_pruner(&self, latest_version: Version) { *self.latest_version.lock() = latest_version; if latest_version >= *self.last_version_sent_to_pruners.lock() + self.pruning_batch_size as u64 { self.wake_pruner(latest_version) } } fn wake_pruner(&self, latest_version: Version) { let least_readable_state_store_version = latest_version.saturating_sub(self.state_store_prune_window); let least_readable_ledger_version = latest_version.saturating_sub(self.ledger_prune_window); self.command_sender .lock() .send(Command::Prune { target_db_versions: vec![ least_readable_state_store_version, least_readable_ledger_version, ], }) .expect("Receiver should not destruct prematurely."); } #[cfg(test)] pub fn wake_and_wait( &self, latest_version: Version, pruner_index: usize, ) -> anyhow::Result<()> { use std::{ thread::sleep, time::{Duration, Instant}, }; self.maybe_wake_pruner(latest_version); if latest_version > self.state_store_prune_window || latest_version > self.ledger_prune_window { let least_readable_state_store_version = latest_version - self.state_store_prune_window; const TIMEOUT: Duration = Duration::from_secs(10); let end = Instant::now() + TIMEOUT; while Instant::now() < end { if *self .least_readable_version .lock() .get(pruner_index) .unwrap() >= least_readable_state_store_version { return Ok(()); } sleep(Duration::from_millis(1)); } anyhow::bail!("Timeout waiting for pruner worker."); } Ok(()) } } impl Drop for Pruner { fn drop(&mut self) { self.command_sender .lock() .send(Command::Quit) .expect("Receiver should not destruct."); self.worker_thread .take() .expect("Worker thread must exist.") .join() .expect("Worker thread should join peacefully."); } }
mod db_pruner; pub(crate) mod db_sub_pruner; pub(crate) mod event_store; mod ledger_store; pub(crate) mod state_store; pub(crate) mod transaction_store; pub mod utils; pub(crate) mod worker; use crate::metrics::APTOS_STORAGE_PRUNE_WINDOW; use aptos_config::config::StoragePrunerConfig; use aptos_infallible::Mutex; use crate::{EventStore, LedgerStore, TransactionStore}; use aptos_types::transaction::Version; use schemadb::DB; use std::{ sync::{ mpsc::{channel, Sender}, Arc, }, thread::JoinHandle, }; use worker::{Command, Worker}; #[derive(Debug)] pub(crate) struct Pruner { state_store_prune_window: Version, ledger_prune_window: Version, worker_thread: Option<JoinHandle<()>>, command_sender: Mutex<Sender<Command>>, #[allow(dead_code)] least_readable_version: Arc<Mutex<Vec<Version>>>, last_version_sent_to_pruners: Arc<Mutex<Version>>, pruning_batch_size: usize, latest_version: Arc<Mutex<Version>>, } #[cfg(test)] pub enum PrunerIndex { StateStorePrunerIndex, LedgerPrunerIndex, } impl Pruner { pub fn new( db: Arc<DB>, storage_pruner_config: StoragePrunerConfig, transaction_store: Arc<TransactionStore>, ledger_store: Arc<LedgerStore>, event_store: Arc<EventStore>, ) -> Self { let (command_sender, command_receiver) = channel(); let least_readable_version = Arc::new(Mutex::new(vec![0, 0, 0, 0, 0])); let worker_progress_clone = Arc::clone(&least_readable_version); APTOS_STORAGE_PRUNE_WINDOW.set( storage_pruner_config .state_store_prune_window .expect("State store pruner window is required") as i64, ); let worker = Worker::new( db, transaction_store, ledger_store, event_store, command_receiver, least_readable_version, storage_pruner_config.pruning_batch_size as u64, ); let worker_thread = std::thread::Builder::new() .name("aptosdb_pruner".into()) .spawn(move || worker.work()) .expect("Creating pruner thread should succeed."); Self { state_store_prune_window: storage_pruner_config .state_store_prune_window .expect("State store prune window must be specified"), ledger_prune_window: storage_pruner_config .ledger_prune_window .expect("Default prune window must be specified"), worker_thread: Some(worker_thread), command_sender: Mutex::new(command_sender), least_readable_version: worker_progress_clone, last_version_sent_to_pruners: Arc::new(Mutex::new(0)), pruning_batch_size: storage_pruner_config.pruning_batch_size, latest_version: Arc::new(Mutex::new(0)), } } pub fn get_state_store_pruner_window(&self) -> Version { self.state_store_prune_window } pub fn maybe_wake_pruner(&self, latest_version: Version) { *self.latest_version.lock() = latest_version; if latest_version >= *self.last_version_sent_to_pruners.lock() + self.pruning_batch_size as u64 { self.wake_pruner(latest_version) } } fn wake_pruner(&self, latest_version: Version) { let least_readable_state_store_version = latest_version.saturating_sub(self.state_store_prune_window); let least_readable_ledger_version = latest_version.saturating_sub(self.ledger_prune_window); self.command_sender .lock() .send(Command::Prune { target_db_versions: vec![ least_readable_state_store_version, least_readable_ledger_version, ], }) .expect("Receiver should not destruct prematurely."); } #[cfg(test)] pub fn wake_and_wait( &self, latest_version: Version, pruner_index: usize, ) -> anyhow::Result<()> { use std::{ thread::sleep, time::{Duration, Instant}, }; self.maybe_wake_pruner(latest_version); if latest_version > self.state_store_prune_window || latest_version > self.ledger_prune_window {
} impl Drop for Pruner { fn drop(&mut self) { self.command_sender .lock() .send(Command::Quit) .expect("Receiver should not destruct."); self.worker_thread .take() .expect("Worker thread must exist.") .join() .expect("Worker thread should join peacefully."); } }
let least_readable_state_store_version = latest_version - self.state_store_prune_window; const TIMEOUT: Duration = Duration::from_secs(10); let end = Instant::now() + TIMEOUT; while Instant::now() < end { if *self .least_readable_version .lock() .get(pruner_index) .unwrap() >= least_readable_state_store_version { return Ok(()); } sleep(Duration::from_millis(1)); } anyhow::bail!("Timeout waiting for pruner worker."); } Ok(()) }
function_block-function_prefix_line
[ { "content": "/// Fetches the latest synced version from the specified storage\n\npub fn fetch_latest_synced_version(storage: Arc<dyn DbReader>) -> Result<Version, Error> {\n\n let latest_transaction_info =\n\n storage\n\n .get_latest_transaction_info_option()\n\n .map_err(|error...
Rust
src/basic/constpool.rs
orasunis/jbcrs
723185189c8422b1a1d1eb3a0bacb59ed00cf00a
use std::hash::{Hash, Hasher}; use std::collections::HashMap; use std::cmp::{Eq, PartialEq}; use std::rc::Rc; use std::slice::Iter; use result::*; #[derive(Debug, Clone)] pub enum Item { UTF8(String), Integer(i32), Float(f32), Long(i64), Double(f64), Class(u16), String(u16), FieldRef { class: u16, name_and_type: u16, }, MethodRef { class: u16, name_and_type: u16, }, InterfaceMethodRef { class: u16, name_and_type: u16, }, NameAndType { name: u16, desc: u16, }, MethodHandle { kind: ReferenceKind, index: u16, }, MethodType(u16), InvokeDynamic { bootstrap_method_attribute: u16, name_and_type: u16, }, Module(u16), Package(u16), } impl Item { fn is_double(&self) -> bool { match *self { Item::Long(_) | Item::Double(_) => true, _ => false, } } } impl Hash for Item { fn hash<H: Hasher>(&self, state: &mut H) { match *self { Item::UTF8(ref s) => { state.write_u8(1); s.hash(state); } Item::Integer(i) => { state.write_u8(3); i.hash(state); } Item::Float(f) => { state.write_u8(4); f.to_bits().hash(state); } Item::Long(i) => { state.write_u8(5); i.hash(state); } Item::Double(f) => { state.write_u8(6); f.to_bits().hash(state); } Item::Class(ptr) => { state.write_u8(7); ptr.hash(state); } Item::String(ptr) => { state.write_u8(8); ptr.hash(state); } Item::FieldRef { class, name_and_type, } => { state.write_u8(9); class.hash(state); name_and_type.hash(state); } Item::MethodRef { class, name_and_type, } => { state.write_u8(10); class.hash(state); name_and_type.hash(state); } Item::InterfaceMethodRef { class, name_and_type, } => { state.write_u8(11); class.hash(state); name_and_type.hash(state); } Item::NameAndType { name, desc } => { state.write_u8(12); name.hash(state); desc.hash(state); } Item::MethodHandle { ref kind, index } => { state.write_u8(15); kind.hash(state); index.hash(state); } Item::MethodType(ptr) => { state.write_u8(16); ptr.hash(state); } Item::InvokeDynamic { bootstrap_method_attribute, name_and_type, } => { state.write_u8(18); bootstrap_method_attribute.hash(state); name_and_type.hash(state); } Item::Module(ptr) => { state.write_u8(19); ptr.hash(state); } Item::Package(ptr) => { state.write_u8(20); ptr.hash(state); } } } } impl PartialEq for Item { fn eq(&self, other: &Item) -> bool { match (self, other) { (&Item::UTF8(ref str1), &Item::UTF8(ref str2)) => *str1 == *str2, (&Item::Integer(i1), &Item::Integer(i2)) => i1 == i2, (&Item::Float(f1), &Item::Float(f2)) => f1.to_bits() == f2.to_bits(), (&Item::Long(i1), &Item::Long(i2)) => i1 == i2, (&Item::Double(f1), &Item::Double(f2)) => f1.to_bits() == f2.to_bits(), (&Item::Class(i1), &Item::Class(i2)) | (&Item::String(i1), &Item::String(i2)) => { i1 == i2 } ( &Item::FieldRef { class: class1, name_and_type: nat1, }, &Item::FieldRef { class: class2, name_and_type: nat2, }, ) | ( &Item::MethodRef { class: class1, name_and_type: nat1, }, &Item::MethodRef { class: class2, name_and_type: nat2, }, ) | ( &Item::InterfaceMethodRef { class: class1, name_and_type: nat1, }, &Item::InterfaceMethodRef { class: class2, name_and_type: nat2, }, ) => class1 == class2 && nat1 == nat2, ( &Item::NameAndType { name: name1, desc: desc1, }, &Item::NameAndType { name: name2, desc: desc2, }, ) => name1 == name2 && desc1 == desc2, ( &Item::MethodHandle { kind: ref kind1, index: index1, }, &Item::MethodHandle { kind: ref kind2, index: index2, }, ) => kind1 == kind2 && index1 == index2, ( &Item::InvokeDynamic { bootstrap_method_attribute: bma1, name_and_type: nat1, }, &Item::InvokeDynamic { bootstrap_method_attribute: bma2, name_and_type: nat2, }, ) => bma1 == bma2 && nat1 == nat2, (&Item::Package(index1), &Item::Package(index2)) | (&Item::Module(index1), &Item::Module(index2)) | (&Item::MethodType(index1), &Item::MethodType(index2)) => index1 == index2, _ => false, } } } impl Eq for Item {} #[derive(Eq, PartialEq, Hash, Debug, Clone)] pub enum ReferenceKind { GetField, GetStatic, PutField, PutStatic, InvokeVirtual, InvokeStatic, InvokeSpecial, NewInvokeSpecial, InvokeInterface, } #[derive(Default)] pub struct Pool { length: u16, by_index: Vec<Option<Rc<Item>>>, by_entry: HashMap<Rc<Item>, u16>, } impl Pool { pub fn new() -> Self { Pool { length: 1, by_index: Vec::new(), by_entry: HashMap::new(), } } pub fn with_capacity(cap: u16) -> Self { Pool { length: 1, by_index: Vec::with_capacity(cap as usize), by_entry: HashMap::with_capacity(cap as usize), } } #[inline] pub fn len(&self) -> u16 { self.length } #[inline] pub fn is_empty(&self) -> bool { self.len() == 1 } pub fn get(&self, index: u16) -> Result<&Item> { if index != 0 && index <= self.len() { if let Some(ref item) = self.by_index[index as usize - 1] { return Ok(item); } } Err(Error::InvalidCPItem(index)) } pub fn get_utf8(&self, index: u16) -> Result<String> { if let Item::UTF8(ref s) = *self.get(index)? { Ok(s.clone()) } else { Err(Error::InvalidCPItem(index)) } } pub fn get_class_name_opt(&self, index: u16) -> Result<Option<String>> { if let Item::Class(utf_index) = *self.get(index)? { if utf_index == 0 { Ok(None) } else { Ok(Some(self.get_utf8(utf_index)?)) } } else { Err(Error::InvalidCPItem(index)) } } pub fn get_class_name(&self, index: u16) -> Result<String> { if let Item::Class(utf_index) = *self.get(index)? { self.get_utf8(utf_index) } else { Err(Error::InvalidCPItem(index)) } } pub fn push(&mut self, item: Item) -> Result<u16> { if self.len() == u16::max_value() { return Err(Error::CPTooLarge); } let double = item.is_double(); let length = &mut self.length; let rc_item = Rc::new(item); let rc_item1 = Rc::clone(&rc_item); let by_index = &mut self.by_index; Ok(*self.by_entry.entry(rc_item).or_insert_with(move || { by_index.push(Some(Rc::clone(&rc_item1))); let prev_length = *length; if double { by_index.push(None); *length += 2; } else { *length += 1; } prev_length })) } pub fn iter(&self) -> PoolIter { PoolIter { iter: self.by_index.iter(), index: 0, } } } pub struct PoolIter<'a> { iter: Iter<'a, Option<Rc<Item>>>, index: u16, } impl<'a> Iterator for PoolIter<'a> { type Item = (u16, &'a Item); fn next(&mut self) -> Option<Self::Item> { self.index += 1; if let Some(rc_item) = self.iter.next() { if let Some(ref item) = *rc_item { Some((self.index + 1, item)) } else { self.next() } } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn constpool() { let mut pool = Pool::new(); assert_eq!(pool.push(Item::Integer(123)).unwrap(), 1); assert_eq!(pool.push(Item::Long(32767)).unwrap(), 2); assert_eq!(pool.push(Item::Long(65535)).unwrap(), 4); assert_eq!(pool.push(Item::Float(3.8)).unwrap(), 6); assert_eq!(pool.push(Item::Integer(123)).unwrap(), 1); assert_eq!(pool.get(1).unwrap(), &Item::Integer(123)); assert_eq!(pool.get(2).unwrap(), &Item::Long(32767)); assert_eq!(pool.get(4).unwrap(), &Item::Long(65535)); assert_eq!(pool.get(6).unwrap(), &Item::Float(3.8)); } }
use std::hash::{Hash, Hasher}; use std::collections::HashMap; use std::cmp::{Eq, PartialEq}; use std::rc::Rc; use std::slice::Iter; use result::*; #[derive(Debug, Clone)] pub enum Item { UTF8(String), Integer(i32), Float(f32), Long(i64), Double(f64), Class(u16), String(u16), FieldRef { class: u16, name_and_type: u16, }, MethodRef { class: u16, name_and_type: u16, }, InterfaceMethodRef { class: u16, name_and_type: u16, }, NameAndType { name: u16, desc: u16, }, MethodHandle { kind: ReferenceKind, index: u16, }, MethodType(u16), InvokeDynamic { bootstrap_method_attribute: u16, name_and_type: u16, }, Module(u16), Package(u16), } impl Item { fn is_double(&self) -> bool { match *self { Item::Long(_) | Item::Double(_) => true, _ => false, } } } impl Hash for Item { fn hash<H: Hasher>(&self, state: &mut H) { match *self { Item::UTF8(ref s) => { state.write_u8(1); s.hash(state); } Item::Integer(i) => { state.write_u8(3); i.hash(state); } Item::Float(f) => { state.write_u8(4); f.to_bits().hash(state); } Item::Long(i) => { state.write_u8(5); i.hash(state); } Item::Double(f) => { state.write_u8(6); f.to_bits().hash(state); } Item::Class(ptr) => { state.write_u8(7); ptr.hash(state); } Item::String(ptr) => { state.write_u8(8); ptr.hash(state); } Item::FieldRef { class, name_and_type, } => { state.write_u8(9); class.hash(state); name_and_type.hash(state); } Item::MethodRef { class, name_and_type, } => { state.write_u8(10); class.hash(state); name_and_type.hash(state); } Item::InterfaceMethodRef { class, name_and_type, } => { state.write_u8(11); class.hash(state); name_and_type.hash(state); } Item::NameAndType { name, desc } => { state.write_u8(12); name.hash(state); desc.hash(state); } Item::MethodHandle { ref kind, index } => { state.write_u8(15); kind.hash(state); index.hash(state); } Item::MethodType(ptr) => { state.write_u8(16); ptr.hash(state); } Item::InvokeDynamic { bootstrap_method_attribute, name_and_type, } => { state.write_u8(18); bootstrap_method_attribute.hash(state); name_and_type.hash(state); } Item::Module(ptr) => { state.write_u8(19); ptr.hash(state); } Item::Package(ptr) => { state.write_u8(20); ptr.hash(state); } } } } impl PartialEq for Item { fn eq(&self, other: &Item) -> bool { match (self, other) { (&Item::UTF8(ref str1), &Item::UTF8(ref str2)) => *str1 == *str2, (&Item::Integer(i1), &Item::Integer(i2)) => i1 == i2, (&Item::Float(f1), &Item::Float(f2)) => f1.to_bits() == f2.to_bits(), (&Item::Long(i1), &Item::Long(i2)) => i1 == i2, (&Item::Double(f1), &Item::Double(f2)) => f1.to_bits() == f2.to_bits(), (&Item::Class(i1), &Item::Class(i2)) | (&Item::String(i1), &Item::String(i2)) => { i1 == i2 } ( &Item::FieldRef { class: class1, name_and_type: nat1, }, &Item::FieldRef { class: class2, name_and_type: nat2, }, ) | ( &Item::MethodRef { class: class1, name_and_type: nat1, }, &Item::MethodRef { class: class2, name_and_type: nat2, }, ) | ( &Item::InterfaceMethodRef { class: class1, name_and_type: nat1, }, &Item::InterfaceMethodRef { class: class2, name_and_type: nat2, }, ) => class1 == class2 && nat1 == nat2, ( &Item::NameAndType { name: name1, desc: desc1, }, &Item::NameAndType { name: name2, desc: desc2, }, ) => name1 == name2 && desc1 == desc2, ( &Item::MethodHandle { kind: ref kind1, index: index1, }, &Item::MethodHandle { kind: ref kind2, index: index2, }, ) => kind1 == kind2 && index1 == index2, ( &Item::InvokeDynamic { bootstrap_method_attribute: bma1, name_and_type: nat1, }, &Item::InvokeDynamic { bootstrap_method_attribute: bma2, name_and_type: nat2, }, ) => bma1 == bma2 && nat1 == nat2, (&Item::Package(index1), &Item::Package(index2)) | (&Item::Module(index1), &Item::Module(index2)) | (&Item::MethodType(index1), &Item::MethodType(index2)) => index1 == index2, _ => false, } } } impl Eq for Item {} #[derive(Eq, PartialEq, Hash, Debug, Clone)] pub enum ReferenceKind { GetField, GetStatic, PutField, PutStatic, InvokeVirtual, InvokeStatic, InvokeSpecial, NewInvokeSpecial, InvokeInterface, } #[derive(Default)] pub struct Pool { length: u16, by_index: Vec<Option<Rc<Item>>>, by_entry: HashMap<Rc<Item>, u16>, } impl Pool { pub fn new() -> Self { Pool { length: 1, by_index: Vec::new(), by_entry: HashMap::new(), } } pub fn with_capacity(cap: u16) -> Self { Pool { length: 1, by_index: Vec::with_capacity(cap as usize), by_entry: HashMap::with_capacity(cap as usize), } } #[inline] pub fn len(&self) -> u16 { self.length } #[inline] pub fn is_empty(&self) -> bool { self.len() == 1 } pub fn get(&self, index: u16) -> Result<&Item> { if index != 0 && index <= self.len() { if let Some(ref item) = self.by_index[index as usize - 1] { return Ok(item); } } Err(Error::InvalidCPItem(index)) } pub fn get_utf8(&self, index: u16) -> Result<String> { if let Item::UTF8(ref s) = *self.get(index)? { Ok(s.clone()) } else { Err(Error::InvalidCPItem(index)) } } pub fn get_class_name_opt(&self, index: u16) -> Result<Option<String>> { if let Item::Class(utf_index) = *self.get(index)? { if utf_index == 0 { Ok(None) } else { Ok(Some(self.get_utf8(utf_index)?)) } } else { Err(Error::InvalidCPItem(index)) } } pub fn get_class_name(&self, index: u16) -> Result<String> { if let Item::Class(utf_index) = *self.get(index)? { self.get_utf8(utf_index) } else { Err(Error::InvalidCPItem(index)) } }
pub fn iter(&self) -> PoolIter { PoolIter { iter: self.by_index.iter(), index: 0, } } } pub struct PoolIter<'a> { iter: Iter<'a, Option<Rc<Item>>>, index: u16, } impl<'a> Iterator for PoolIter<'a> { type Item = (u16, &'a Item); fn next(&mut self) -> Option<Self::Item> { self.index += 1; if let Some(rc_item) = self.iter.next() { if let Some(ref item) = *rc_item { Some((self.index + 1, item)) } else { self.next() } } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn constpool() { let mut pool = Pool::new(); assert_eq!(pool.push(Item::Integer(123)).unwrap(), 1); assert_eq!(pool.push(Item::Long(32767)).unwrap(), 2); assert_eq!(pool.push(Item::Long(65535)).unwrap(), 4); assert_eq!(pool.push(Item::Float(3.8)).unwrap(), 6); assert_eq!(pool.push(Item::Integer(123)).unwrap(), 1); assert_eq!(pool.get(1).unwrap(), &Item::Integer(123)); assert_eq!(pool.get(2).unwrap(), &Item::Long(32767)); assert_eq!(pool.get(4).unwrap(), &Item::Long(65535)); assert_eq!(pool.get(6).unwrap(), &Item::Float(3.8)); } }
pub fn push(&mut self, item: Item) -> Result<u16> { if self.len() == u16::max_value() { return Err(Error::CPTooLarge); } let double = item.is_double(); let length = &mut self.length; let rc_item = Rc::new(item); let rc_item1 = Rc::clone(&rc_item); let by_index = &mut self.by_index; Ok(*self.by_entry.entry(rc_item).or_insert_with(move || { by_index.push(Some(Rc::clone(&rc_item1))); let prev_length = *length; if double { by_index.push(None); *length += 2; } else { *length += 1; } prev_length })) }
function_block-full_function
[ { "content": "/// Parses the class file, which is represented as a byte array.\n\n/// The constant pool and the class is returned, if no error occurred.\n\npub fn parse(input: &[u8]) -> Result<(Pool, Class)> {\n\n // create a new decoder from the byte array\n\n let mut cursor = 0;\n\n let mut decoder =...
Rust
tests/builder.rs
denzp/rust-ptx-builder
4b5bb6845674417d04f3cba48ba0cda6f5c4772a
use std::env; use std::env::current_dir; use std::fs::{remove_dir_all, File}; use std::io::prelude::*; use std::path::PathBuf; use antidote::Mutex; use lazy_static::*; use ptx_builder::error::*; use ptx_builder::prelude::*; lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn should_provide_output_path() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { assert!(output.get_assembly_path().starts_with( env::temp_dir() .join("ptx-builder-0.5") .join("sample_ptx_crate"), )); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_write_assembly() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_application_crate() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/app-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_mixed_crate_lib() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/mixed-crate").unwrap(); match builder .set_crate_type(CrateType::Library) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); println!("{}", output.get_assembly_path().display()); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_mixed_crate_bin() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/mixed-crate").unwrap(); match builder .set_crate_type(CrateType::Binary) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); println!("{}", output.get_assembly_path().display()); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_handle_rebuild_without_changes() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = { Builder::new("tests/fixtures/app-crate") .unwrap() .disable_colors() }; builder.build().unwrap(); match builder.build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_write_assembly_in_debug_mode() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder .set_profile(Profile::Debug) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("debug")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_report_about_build_failure() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/faulty-crate") .unwrap() .disable_colors(); let output = builder.build(); let crate_absoulte_path = current_dir() .unwrap() .join("tests") .join("fixtures") .join("faulty-crate"); let lib_path = PathBuf::from("src").join("lib.rs"); let crate_absoulte_path_str = crate_absoulte_path.display().to_string(); match output.unwrap_err().kind() { BuildErrorKind::BuildFailed(diagnostics) => { assert_eq!( diagnostics .into_iter() .filter(|item| !item.contains("Blocking waiting") && !item.contains("Compiling core") && !item.contains("Compiling compiler_builtins") && !item.contains("Finished release [optimized] target(s)")) .collect::<Vec<_>>(), &[ format!( " Compiling faulty-ptx_crate v0.1.0 ({})", crate_absoulte_path_str ), String::from("error[E0425]: cannot find function `external_fn` in this scope"), format!(" --> {}:6:20", lib_path.display()), String::from(" |"), String::from("6 | *y.offset(0) = external_fn(*x.offset(0)) * a;"), String::from(" | ^^^^^^^^^^^ not found in this scope"), String::from(""), String::from("error: aborting due to previous error"), String::from(""), String::from( "For more information about this error, try `rustc --explain E0425`.", ), String::from("error: could not compile `faulty-ptx_crate`."), String::from(""), ] ); } _ => unreachable!("it should fail with proper error"), } } #[test] fn should_provide_crate_source_files() { let _lock = ENV_MUTEX.lock(); let crate_path = { current_dir() .unwrap() .join("tests") .join("fixtures") .join("sample-crate") }; let builder = Builder::new(&crate_path.display().to_string()).unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut sources = output.dependencies().unwrap(); let mut expectations = vec![ crate_path.join("src").join("lib.rs"), crate_path.join("src").join("mod1.rs"), crate_path.join("src").join("mod2.rs"), crate_path.join("Cargo.toml"), crate_path.join("Cargo.lock"), ]; sources.sort(); expectations.sort(); assert_eq!(sources, expectations); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_provide_application_crate_source_files() { let _lock = ENV_MUTEX.lock(); let crate_path = { current_dir() .unwrap() .join("tests") .join("fixtures") .join("app-crate") }; let builder = Builder::new(&crate_path.display().to_string()).unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut sources = output.dependencies().unwrap(); let mut expectations = vec![ crate_path.join("src").join("main.rs"), crate_path.join("src").join("mod1.rs"), crate_path.join("src").join("mod2.rs"), crate_path.join("Cargo.toml"), crate_path.join("Cargo.lock"), ]; sources.sort(); expectations.sort(); assert_eq!(sources, expectations); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_not_get_built_from_rls() { let _lock = ENV_MUTEX.lock(); env::set_var("CARGO", "some/path/to/rls"); assert_eq!(Builder::is_build_needed(), false); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::NotNeeded => {} BuildStatus::Success(_) => unreachable!(), } env::set_var("CARGO", ""); } #[test] fn should_not_get_built_recursively() { let _lock = ENV_MUTEX.lock(); env::set_var("PTX_CRATE_BUILDING", "1"); assert_eq!(Builder::is_build_needed(), false); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::NotNeeded => {} BuildStatus::Success(_) => unreachable!(), } env::set_var("PTX_CRATE_BUILDING", ""); } fn cleanup_temp_location() { let crate_names = &[ "faulty_ptx_crate", "sample_app_ptx_crate", "sample_ptx_crate", "mixed_crate", ]; for name in crate_names { remove_dir_all(env::temp_dir().join("ptx-builder-0.5").join(name)).unwrap_or_default(); } }
use std::env; use std::env::current_dir; use std::fs::{remove_dir_all, File}; use std::io::prelude::*; use std::path::PathBuf; use antidote::Mutex; use lazy_static::*; use ptx_builder::error::*; use ptx_builder::prelude::*; lazy_static! { static ref ENV_MUTEX: Mutex<()> = Mutex::new(()); } #[test] fn should_provide_output_path() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { assert!(output.get_assembly_path().starts_with( env::temp_dir() .join("ptx-builder-0.5") .join("sample_ptx_crate"), )); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_write_assembly() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_application_crate() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/app-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_mixed_crate_lib() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/mixed-crate").unwrap(); match builder .set_crate_type(CrateType::Library) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); println!("{}", output.get_assembly_path().display()); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_build_mixed_crate_bin() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/mixed-crate").unwrap(); match builder .set_crate_type(CrateType::Binary) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); println!("{}", output.get_assembly_path().display()); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_handle_rebuild_without_changes() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = { Builder::new("tests/fixtures/app-crate") .unwrap() .disable_colors() }; builder.build().unwrap(); match builder.build().unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("release")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_write_assembly_in_debug_mode() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder .set_profile(Profile::Debug) .disable_colors() .build() .unwrap() { BuildStatus::Success(output) => { let mut assembly_contents = String::new(); File::open(output.get_assembly_path()) .unwrap() .read_to_string(&mut assembly_contents) .unwrap(); assert!(output .get_assembly_path() .to_string_lossy() .contains("debug")); assert!(assembly_contents.contains(".visible .entry the_kernel(")); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_report_about_build_failure() { cleanup_temp_location(); let _lock = ENV_MUTEX.lock(); let builder = Builder::new("tests/fixtures/faulty-crate") .unwrap() .disable_colors(); let output = builder.build(); let crate_absoulte_path = current_dir() .unwrap() .join("tests") .join("fixtures") .join("faulty-crate"); let lib_path = PathBuf::from("src").join("lib.rs"); let crate_absoulte_path_str = crate_absoulte_path.display().to_string(); match output.unwrap_err().kind() { BuildErrorKind::BuildFailed(diagnostics) => { assert_eq!( diagnostics .into_iter() .filter(|item| !item.contains("Blocking waiting") && !item.contains("Compiling core") && !item.contains("Compiling compiler_builtins") && !item.contains("Finished release [optimized] target(s)")) .collect::<Vec<_>>(), &[ format!( " Compiling faulty-ptx_crate v0.1.0 ({})", crate_absoulte_path_str ), String::from("error[E0425]: cannot find function `external_fn` in this scope"), format!(" --> {}:6:20", lib_path.display()), String::from(" |"), String::from("6 | *y.offset(0) = external_fn(*x.offset(0)) * a;"), String::from(" | ^^^^^^^^^^^ not found in this scope"), String::from(""), String::from("error: aborting due to previous error"), String::from(""), String::from( "For more information about this error, try `rustc --explain E0425`.", ), String::from("error: could not compile `faulty-ptx_crate`."), String::from(""), ] ); } _ => unreachable!("it should fail with proper error"), } } #[test] fn should_provide_crate_source_files() { let _lock = ENV_MUTEX.lock(); let crate_path = { current_dir() .unwrap() .join("tests") .join("fixtures") .join("sample-crate") }; let builder = Builder::new(&crate_path.display().to_string()).unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut sources = output.dependencies().unwrap(); let mut expectations = vec![ crate_path.join("src").join("lib.rs"), crate_path.join("src").join("mod1.rs"), crate_path.join("src").join("mod2.rs"), crate_path.join("Cargo.toml"), crate_path.join("Cargo.lock"), ]; sources.sort(); expectations.sort(); assert_eq!(sources, expectations); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_provide_application_crate_source_files() { let _lock = ENV_MUTEX.lock(); let crate_path = { current_dir() .unwrap() .join("tests") .join("fixtures") .join("app-crate") }; let builder = Builder::new(&crate_path.display().to_string()).unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::Success(output) => { let mut sources = output.dependencies().unwrap(); let mut expectations = vec![ crate_path.join("src").join("main.rs"), crate_path.join("src").join("mod1.rs"), crate_path.join("src").join("mod2.rs"), crate_path.join("Cargo.toml"), crate_path.join("Cargo.lock"), ]; sources.sort(); expectations.sort(); assert_eq!(sources, expectations); } BuildStatus::NotNeeded => unreachable!(), } } #[test] fn should_not_get_built_from_rls() { let _lock = ENV_MUTEX.lock(); env::set_var("CARGO", "some/path/to/rls"); assert_eq!(Builder::is_build_needed(), false); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::NotNeeded => {} BuildStatus::Success(_) => unreachable!(), } env::set_var("CARGO", ""); } #[test] fn should_not_get_built_recursively() { let _lock = ENV_MUTEX.lock(); env::set_var("PTX_CRATE_BUILDING", "1"); assert_eq!(Builder::is_build_needed(), false); let builder = Builder::new("tests/fixtures/sample-crate").unwrap(); match builder.disable_colors().build().unwrap() { BuildStatus::NotNeeded => {} BuildStatus::Success(_) => unreachable!(), } env::set_var("PTX_CRATE_BUILDING", ""); } f
n cleanup_temp_location() { let crate_names = &[ "faulty_ptx_crate", "sample_app_ptx_crate", "sample_ptx_crate", "mixed_crate", ]; for name in crate_names { remove_dir_all(env::temp_dir().join("ptx-builder-0.5").join(name)).unwrap_or_default(); } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn should_provide_output_path() {\n\n let source_crate = Crate::analyse(\"tests/fixtures/sample-crate\").unwrap();\n\n\n\n assert!(source_crate.get_output_path().unwrap().starts_with(\n\n env::temp_dir()\n\n .join(\"ptx-builder-0.5\")\n\n .join(\"sampl...
Rust
src/collector.rs
playXE/test
50fae1922ef116908d09cdf81b301c153e980416
use super::{allocation::ImmixSpace, block::ImmixBlock, constants::*, CollectionType}; use crate::{large_object_space::LargeObjectSpace, object::*, util::*}; use alloc::collections::VecDeque; use core::ptr::NonNull; use vec_map::VecMap; pub struct ImmixCollector; pub struct Visitor<'a> { immix_space: &'a mut ImmixSpace, queue: &'a mut VecDeque<*mut RawGc>, defrag: bool, next_live_mark: bool, } impl<'a> Tracer for Visitor<'a> { fn trace(&mut self, reference: &mut NonNull<RawGc>) { unsafe { let mut child = &mut *reference.as_ptr(); if child.is_forwarded() { debug!("Child {:p} is forwarded to 0x{:x}", child, child.vtable()); *reference = NonNull::new_unchecked(child.vtable() as *mut _); } else if (&*child).get_mark() != self.next_live_mark { if self.defrag && self.immix_space.filter_fast(Address::from_ptr(child)) { if let Some(new_child) = self.immix_space.maybe_evacuate(child) { *reference = NonNull::new_unchecked(new_child.to_mut_ptr()); debug!("Evacuated child {:p} to {}", child, new_child); child = &mut *new_child.to_mut_ptr::<RawGc>(); } } debug!("Push child {:p} into object queue", child); self.queue.push_back(child); } } } } impl ImmixCollector { pub fn collect( collection_type: &CollectionType, roots: &[*mut RawGc], precise_roots: &[*mut *mut RawGc], immix_space: &mut ImmixSpace, next_live_mark: bool, ) -> usize { let mut object_queue: VecDeque<*mut RawGc> = roots.iter().copied().collect(); for root in precise_roots.iter() { unsafe { let root = &mut **root; let mut raw = &mut **root; if immix_space.filter_fast(Address::from_ptr(raw)) { if raw.is_forwarded() { raw = &mut *(raw.vtable() as *mut RawGc); } else if *collection_type == CollectionType::ImmixEvacCollection { if let Some(new_object) = immix_space.maybe_evacuate(raw) { *root = new_object.to_mut_ptr::<RawGc>(); raw.set_forwarded(new_object.to_usize()); raw = &mut *new_object.to_mut_ptr::<RawGc>(); } } } object_queue.push_back(raw); } } let mut visited = 0; while let Some(object) = object_queue.pop_front() { unsafe { let object_addr = Address::from_ptr(object); if !(&mut *object).mark(next_live_mark) { if immix_space.filter_fast(object_addr) { let block = ImmixBlock::get_block_ptr(object_addr); immix_space.set_gc_object(object_addr); (&mut *block).line_object_mark(object_addr); } debug!("Object {:p} was unmarked: visit their children", object); visited += (&*object).object_size(); let visitor_fn = (&*object).rtti().visit_references; { let mut visitor = core::mem::transmute::<_, Visitor<'static>>(Visitor { immix_space, next_live_mark, queue: &mut object_queue, defrag: *collection_type == CollectionType::ImmixEvacCollection, }); visitor_fn( object as *mut u8, TracerPtr { tracer: core::mem::transmute(&mut visitor as &mut dyn Tracer), }, ); } } } } debug!("Completed collection with {} bytes visited", visited); visited } } use alloc::vec::Vec; pub struct Collector { all_blocks: Vec<*mut ImmixBlock>, mark_histogram: VecMap<usize>, } impl Default for Collector { fn default() -> Self { Self::new() } } impl Collector { pub fn new() -> Self { Self { all_blocks: Vec::new(), mark_histogram: VecMap::with_capacity(NUM_LINES_PER_BLOCK), } } pub fn extend_all_blocks(&mut self, blocks: Vec<*mut ImmixBlock>) { self.all_blocks.extend(blocks); } pub fn prepare_collection( &mut self, evacuation: bool, _cycle_collect: bool, available_blocks: usize, evac_headroom: usize, total_blocks: usize, emergency: bool, ) -> CollectionType { if emergency && USE_EVACUATION { for block in &mut self.all_blocks { unsafe { (**block).evacuation_candidate = true; } } return CollectionType::ImmixEvacCollection; } let mut perform_evac = evacuation; let evac_threshhold = (total_blocks as f64 * EVAC_TRIGGER_THRESHHOLD) as usize; let available_evac_blocks = available_blocks + evac_headroom; debug!( "total blocks={},evac threshold={}, available evac blocks={}", total_blocks, evac_threshhold, available_evac_blocks ); if evacuation || available_evac_blocks < evac_threshhold { let hole_threshhold = self.establish_hole_threshhold(evac_headroom); debug!("evac threshold={}", hole_threshhold); perform_evac = USE_EVACUATION && hole_threshhold > 0; if perform_evac { for block in &mut self.all_blocks { unsafe { (**block).evacuation_candidate = (**block).hole_count as usize >= hole_threshhold; } } } } match (false, perform_evac, true) { (true, false, true) => CollectionType::ImmixCollection, (true, true, true) => CollectionType::ImmixEvacCollection, (false, false, _) => CollectionType::ImmixCollection, (false, true, _) => CollectionType::ImmixEvacCollection, _ => CollectionType::ImmixCollection, } } pub fn collect( &mut self, collection_type: &CollectionType, roots: &[*mut RawGc], precise_roots: &[*mut *mut RawGc], immix_space: &mut ImmixSpace, large_object_space: &mut LargeObjectSpace, next_live_mark: bool, ) -> usize { for block in &mut self.all_blocks { unsafe { immix_space .bitmap .clear_range((*block) as usize, (*block) as usize + BLOCK_SIZE); (**block).line_map.clear_all(); } } let visited = ImmixCollector::collect( collection_type, roots, precise_roots, immix_space, next_live_mark, ); self.mark_histogram.clear(); let (recyclable_blocks, free_blocks) = self.sweep_all_blocks(); immix_space.set_recyclable_blocks(recyclable_blocks); let evac_headroom = if USE_EVACUATION { EVAC_HEADROOM - immix_space.evac_headroom() } else { 0 }; immix_space.extend_evac_headroom(free_blocks.iter().take(evac_headroom).copied()); immix_space.return_blocks(free_blocks.iter().skip(evac_headroom).copied()); large_object_space.sweep(); visited } fn sweep_all_blocks(&mut self) -> (Vec<*mut ImmixBlock>, Vec<*mut ImmixBlock>) { let mut unavailable_blocks = Vec::new(); let mut recyclable_blocks = Vec::new(); let mut free_blocks = Vec::new(); for block in self.all_blocks.drain(..) { if unsafe { (*block).is_empty() } { unsafe { (*block).reset(); } debug!("Push block {:p} into free_blocks", block); free_blocks.push(block); } else { unsafe { (*block).count_holes(); } let (holes, marked_lines) = unsafe { (*block).count_holes_and_marked_lines() }; if self.mark_histogram.contains_key(holes) { if let Some(val) = self.mark_histogram.get_mut(holes) { *val += marked_lines; } } else { self.mark_histogram.insert(holes, marked_lines); } debug!( "Found {} holes and {} marked lines in block {:p}", holes, marked_lines, block ); match holes { 0 => { debug!("Push block {:p} into unavailable_blocks", block); unavailable_blocks.push(block); } _ => { debug!("Push block {:p} into recyclable_blocks", block); recyclable_blocks.push(block); } } } } self.all_blocks = unavailable_blocks; (recyclable_blocks, free_blocks) } fn establish_hole_threshhold(&self, evac_headroom: usize) -> usize { let mut available_histogram: VecMap<usize> = VecMap::with_capacity(NUM_LINES_PER_BLOCK); for &block in &self.all_blocks { let (holes, free_lines) = unsafe { (*block).count_holes_and_available_lines() }; if available_histogram.contains_key(holes) { if let Some(val) = available_histogram.get_mut(holes) { *val += free_lines; } } else { available_histogram.insert(holes, free_lines); } } let mut required_lines = 0; let mut available_lines = evac_headroom * (NUM_LINES_PER_BLOCK - 1); for threshold in 0..NUM_LINES_PER_BLOCK { required_lines += *self.mark_histogram.get(threshold).unwrap_or(&0); available_lines = available_lines.saturating_sub(*available_histogram.get(threshold).unwrap_or(&0)); if available_lines <= required_lines { return threshold; } } NUM_LINES_PER_BLOCK } }
use super::{allocation::ImmixSpace, block::ImmixBlock, constants::*, CollectionType}; use crate::{large_object_space::LargeObjectSpace, object::*, util::*}; use alloc::collections::VecDeque; use core::ptr::NonNull; use vec_map::VecMap; pub struct ImmixCollector; pub struct Visitor<'a> { immix_space: &'a mut ImmixSpace, queue: &'a mut VecDeque<*mut RawGc>, defrag: bool, next_live_mark: bool, } impl<'a> Tracer for Visitor<'a> { fn trace(&mut self, reference: &mut NonNull<RawGc>) { unsafe { let mut child = &mut *reference.as_ptr(); if child.is_forwarded() { debug!("Child {:p} is forwarded to 0x{:x}", child, child.vtable()); *reference = NonNull::new_unchecked(child.vtable() as *mut _); } else if (&*child).get_mark() != self.next_live_mark { if self.defrag && self.immix_space.filter_fast(Address::from_ptr(child)) { if let Some(new_child) = self.immix_space.maybe_evacuate(child) { *reference = NonNull::new_unchecked(new_child.to_mut_ptr()); debug!("Evacuated child {:p} to {}", child, new_child); child = &mut *new_child.to_mut_ptr::<RawGc>(); } } debug!("Push child {:p} into object queue", child); self.queue.push_back(child); } } } } impl ImmixCollector { pub fn collect( collection_type: &CollectionType, roots: &[*mut RawGc], precise_roots: &[*mut *mut RawGc], immix_space: &mut ImmixSpace, next_live_mark: bool, ) -> usize { let mut object_queue: VecDeque<*mut RawGc> = roots.iter().copied().collect(); for root in precise_roots.iter() { unsafe { let root = &mut **root; let mut raw = &mut **root; if immix_space.filter_fast(Address::from_ptr(raw)) { if raw.is_forwarded() { raw = &mut *(raw.vtable() as *mut RawGc); } else if *collection_type == CollectionType::ImmixEvacCollection { if let Some(new_object) = immix_space.maybe_evacuate(raw) { *root = new_object.to_mut_ptr::<RawGc>(); raw.set_forwarded(new_object.to_usize()); raw = &mut *new_object.to_mut_ptr::<RawGc>(); } } } object_queue.push_back(raw); } } let mut visited = 0; while let Some(object) = object_queue.pop_front() { unsafe { let object_addr = Address::from_ptr(object); if !(&mut *object).mark(next_live_mark) { if immix_space.filter_fast(object_addr) { let block = ImmixBlock::get_block_ptr(object_addr); immix_space.set_gc_object(object_addr); (&mut *block).line_object_mark(object_addr); } debug!("Object {:p} was unmarked: visit their children", object); visited += (&*object).object_size(); let visitor_fn = (&*object).rtti().visit_references; { let mut visitor = core::mem::transmute::<_, Visitor<'static>>(Visitor { immix_space, next_live_mark, queue: &mut object_queue, defrag: *collection_type == CollectionType::ImmixEvacCollection, }); visitor_fn( object as *mut u8, TracerPtr { tracer: core::mem::transmute(&mut visitor as &mut dyn Tracer), }, ); } } } } debug!("Completed collection with {} bytes visited", visited); visited } } use alloc::vec::Vec; pub struct Collector { all_blocks: Vec<*mut ImmixBlock>, mark_histogram: VecMap<usize>, } impl Default for Collector { fn default() -> Self { Self::new() } } impl Collector { pub fn new() -> Self { Self { all_blocks: Vec::new(), mark_histogram: VecMap::with_capacity(NUM_LINES_PER_BLOCK), } } pub fn extend_all_blocks(&mut self, blocks: Vec<*mut ImmixBlock>) { self.all_blocks.extend(blocks); } pub fn prepare_collection( &mut self, evacuation: bool, _cycle_collect: bool, available_blocks: usize, evac_headroom: usize, total_blocks: usize, emergency: bool, ) -> CollectionType { if emergency && USE_EVACUATION { for block in &mut self.all_blocks { unsafe { (**block).evacuation_candidate = true; } } return CollectionType::ImmixEvacCollection; } let mut perform_evac = evacuation; let evac_threshhold = (total_blocks as f64 * EVAC_TRIGGER_THRESHHOLD) as usize; let available_evac_blocks = available_blocks + evac_headroom; debug!( "total blocks={},evac threshold={}, available evac blocks={}", total_blocks, evac_threshhold, available_evac_blocks ); if evacuation || available_evac_blocks < evac_threshhold { let hole_threshhold = self.establish_hole_threshhold(evac_headroom); debug!("evac threshold={}", hole_threshhold); perform_evac = USE_EVACUATION && hole_threshhold > 0; if perform_evac { for block in &mut self.all_blocks { unsafe { (**block).evacuation_candidate = (**block).hole_count as usize >= hole_threshhold; } } } } match (false, perform_evac, true) { (true, false, true) => CollectionType::ImmixCollection, (true, true, true) => CollectionType::ImmixEvacCollection, (false, false, _) => CollectionType::ImmixCollection, (false, true, _) => CollectionType::ImmixEvacCollection, _ => CollectionType::ImmixCollection, } }
fn sweep_all_blocks(&mut self) -> (Vec<*mut ImmixBlock>, Vec<*mut ImmixBlock>) { let mut unavailable_blocks = Vec::new(); let mut recyclable_blocks = Vec::new(); let mut free_blocks = Vec::new(); for block in self.all_blocks.drain(..) { if unsafe { (*block).is_empty() } { unsafe { (*block).reset(); } debug!("Push block {:p} into free_blocks", block); free_blocks.push(block); } else { unsafe { (*block).count_holes(); } let (holes, marked_lines) = unsafe { (*block).count_holes_and_marked_lines() }; if self.mark_histogram.contains_key(holes) { if let Some(val) = self.mark_histogram.get_mut(holes) { *val += marked_lines; } } else { self.mark_histogram.insert(holes, marked_lines); } debug!( "Found {} holes and {} marked lines in block {:p}", holes, marked_lines, block ); match holes { 0 => { debug!("Push block {:p} into unavailable_blocks", block); unavailable_blocks.push(block); } _ => { debug!("Push block {:p} into recyclable_blocks", block); recyclable_blocks.push(block); } } } } self.all_blocks = unavailable_blocks; (recyclable_blocks, free_blocks) } fn establish_hole_threshhold(&self, evac_headroom: usize) -> usize { let mut available_histogram: VecMap<usize> = VecMap::with_capacity(NUM_LINES_PER_BLOCK); for &block in &self.all_blocks { let (holes, free_lines) = unsafe { (*block).count_holes_and_available_lines() }; if available_histogram.contains_key(holes) { if let Some(val) = available_histogram.get_mut(holes) { *val += free_lines; } } else { available_histogram.insert(holes, free_lines); } } let mut required_lines = 0; let mut available_lines = evac_headroom * (NUM_LINES_PER_BLOCK - 1); for threshold in 0..NUM_LINES_PER_BLOCK { required_lines += *self.mark_histogram.get(threshold).unwrap_or(&0); available_lines = available_lines.saturating_sub(*available_histogram.get(threshold).unwrap_or(&0)); if available_lines <= required_lines { return threshold; } } NUM_LINES_PER_BLOCK } }
pub fn collect( &mut self, collection_type: &CollectionType, roots: &[*mut RawGc], precise_roots: &[*mut *mut RawGc], immix_space: &mut ImmixSpace, large_object_space: &mut LargeObjectSpace, next_live_mark: bool, ) -> usize { for block in &mut self.all_blocks { unsafe { immix_space .bitmap .clear_range((*block) as usize, (*block) as usize + BLOCK_SIZE); (**block).line_map.clear_all(); } } let visited = ImmixCollector::collect( collection_type, roots, precise_roots, immix_space, next_live_mark, ); self.mark_histogram.clear(); let (recyclable_blocks, free_blocks) = self.sweep_all_blocks(); immix_space.set_recyclable_blocks(recyclable_blocks); let evac_headroom = if USE_EVACUATION { EVAC_HEADROOM - immix_space.evac_headroom() } else { 0 }; immix_space.extend_evac_headroom(free_blocks.iter().take(evac_headroom).copied()); immix_space.return_blocks(free_blocks.iter().skip(evac_headroom).copied()); large_object_space.sweep(); visited }
function_block-full_function
[ { "content": "/// Check if `mem` is aligned for precise allocation\n\npub fn is_aligned_for_precise_allocation(mem: *mut u8) -> bool {\n\n let allocable_ptr = mem as usize;\n\n (allocable_ptr & (PreciseAllocation::ALIGNMENT - 1)) == 0\n\n}\n\n/// This space contains objects which are larger than the size ...
Rust
frontend/apps/crates/utils/src/components/module_page.rs
Sheng-Long/ji-cloud
d12741467eb5d0ae15e3cece9d3428ef9d0050e3
/* There are a few fundamental concepts going on here... * 1. The serialized data does _not_ need to be Clone. * rather, it's passed completely to the child * and then the child is free to split it up for Mutable/etc. * (here it is held and taken from an Option) * 2. The loader will be skipped if the url has ?iframe_data=true * in this case, iframe communication is setup and the parent * is expected to post a message with the data (via IframeInit) */ use std::rc::Rc; use std::cell::RefCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use futures_signals::{ map_ref, signal::{Mutable,ReadOnlyMutable, SignalExt, Signal}, signal_vec::{MutableVec, SignalVec, SignalVecExt}, CancelableFutureHandle, }; use web_sys::{Url, HtmlElement, Element, HtmlInputElement}; use dominator::{DomBuilder, Dom, html, events, with_node, clone, apply_methods}; use dominator_helpers::{elem,dynamic_class_signal ,with_data_id, spawn_future, AsyncLoader}; use crate::templates; use wasm_bindgen_futures::{JsFuture, spawn_local, future_to_promise}; use serde::de::DeserializeOwned; use crate::{ iframe::*, resize::*, }; use std::future::Future; use async_trait::async_trait; #[async_trait(?Send)] pub trait ModuleRenderer { type Data: DeserializeOwned; async fn load(_self:Rc<Self>) -> Self::Data; fn render(_self: Rc<Self>, data: Self::Data) -> Dom; } pub struct ModulePage<T, R> where T: DeserializeOwned, R: ModuleRenderer<Data = T>, { renderer: Rc<R>, loaded_data: RefCell<Option<T>>, has_loaded_data: Mutable<bool>, wait_iframe_data: bool, loader: AsyncLoader, } impl <T, R> ModulePage <T, R> where T: DeserializeOwned + 'static, R: ModuleRenderer<Data = T> + 'static, { pub fn new(renderer:Rc<R>) -> Rc<Self> { let wait_iframe_data = should_get_iframe_data(); let _self = Rc::new(Self { renderer, loaded_data: RefCell::new(None), has_loaded_data: Mutable::new(false), loader: AsyncLoader::new(), wait_iframe_data, }); let _self_clone = _self.clone(); _self_clone.loader.load(async move { if !wait_iframe_data { let data:T = ModuleRenderer::load(_self.renderer.clone()).await; *_self.loaded_data.borrow_mut() = Some(data); _self.has_loaded_data.set(true); } }); _self_clone } pub fn render(_self: Rc<Self>) -> Dom { elem!(templates::module_page(), { .with_data_id!("module-outer", { .with_data_id!("module-content", { .child_signal(_self.has_loaded_data.signal().map(clone!(_self => move |ready| { if ready { let data = _self.loaded_data.borrow_mut().take().unwrap_throw(); Some(ModuleRenderer::render(_self.renderer.clone(),data)) } else { None } }))) }) .with_node!(elem => { .global_event(clone!(_self => move |evt:events::Resize| { ModuleBounds::set( elem.client_width(), elem.client_height() ); })) }) .after_inserted(clone!(_self => move |elem| { ModuleBounds::set( elem.client_width(), elem.client_height() ); })) }) .global_event(clone!(_self => move |evt:dominator_helpers::events::Message| { if let Ok(msg) = evt.try_serde_data::<IframeInit<T>>() { if !_self.wait_iframe_data { log::warn!("weird... shouldn't have gotten iframe data!"); } *_self.loaded_data.borrow_mut() = Some(msg.data.unwrap_throw()); _self.has_loaded_data.set(true); } else { log::info!("hmmm got other iframe message..."); } })) .after_inserted(clone!(_self => move |elem| { if _self.wait_iframe_data { let target = web_sys::window().unwrap_throw().parent().unwrap_throw().unwrap_throw(); let msg = IframeInit::empty(); target.post_message(&msg.into(), "*"); } })) }) } }
/* There are a few fundamental concepts going on here... * 1. The serialized data does _not_ need to be Clone. * rather, it's passed completely to the child * and then the child is free to split it up for Mutable/etc. * (here it is held and taken from an Option) * 2. The loader will be skipped if the url has ?iframe_data=true * in this case, iframe communication is setup and the parent * is expected to post a message with the data (via IframeInit) */ use std::rc::Rc; use std::cell::RefCell; use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use futures_signals::{ map_ref, signal::{Mutable,ReadOnlyMutable, SignalExt, Signal}, signal_vec::{MutableVec, SignalVec, SignalVecExt}, CancelableFutureHandle, }; use web_sys::{Url, HtmlElement, Element, HtmlInputElement}; use dominator::{DomBuilder, Dom, html, events, with_node, clone, apply_methods}; use dominator_helpers::{elem,dynamic_class_signal ,with_data_id, spawn_future, AsyncLoader}; use crate::templates; use wasm_bindgen_futures::{JsFuture, spawn_local, future_to_promise}; use serde::de::DeserializeOwned; use crate::{ iframe::*, resize::*, }; use std::future::Future; use async_trait::async_trait; #[async_trait(?Send)] pub trait ModuleRenderer { type Data: DeserializeOwned; async fn load(_self
data)) } else { None } }))) }) .with_node!(elem => { .global_event(clone!(_self => move |evt:events::Resize| { ModuleBounds::set( elem.client_width(), elem.client_height() ); })) }) .after_inserted(clone!(_self => move |elem| { ModuleBounds::set( elem.client_width(), elem.client_height() ); })) }) .global_event(clone!(_self => move |evt:dominator_helpers::events::Message| { if let Ok(msg) = evt.try_serde_data::<IframeInit<T>>() { if !_self.wait_iframe_data { log::warn!("weird... shouldn't have gotten iframe data!"); } *_self.loaded_data.borrow_mut() = Some(msg.data.unwrap_throw()); _self.has_loaded_data.set(true); } else { log::info!("hmmm got other iframe message..."); } })) .after_inserted(clone!(_self => move |elem| { if _self.wait_iframe_data { let target = web_sys::window().unwrap_throw().parent().unwrap_throw().unwrap_throw(); let msg = IframeInit::empty(); target.post_message(&msg.into(), "*"); } })) }) } }
:Rc<Self>) -> Self::Data; fn render(_self: Rc<Self>, data: Self::Data) -> Dom; } pub struct ModulePage<T, R> where T: DeserializeOwned, R: ModuleRenderer<Data = T>, { renderer: Rc<R>, loaded_data: RefCell<Option<T>>, has_loaded_data: Mutable<bool>, wait_iframe_data: bool, loader: AsyncLoader, } impl <T, R> ModulePage <T, R> where T: DeserializeOwned + 'static, R: ModuleRenderer<Data = T> + 'static, { pub fn new(renderer:Rc<R>) -> Rc<Self> { let wait_iframe_data = should_get_iframe_data(); let _self = Rc::new(Self { renderer, loaded_data: RefCell::new(None), has_loaded_data: Mutable::new(false), loader: AsyncLoader::new(), wait_iframe_data, }); let _self_clone = _self.clone(); _self_clone.loader.load(async move { if !wait_iframe_data { let data:T = ModuleRenderer::load(_self.renderer.clone()).await; *_self.loaded_data.borrow_mut() = Some(data); _self.has_loaded_data.set(true); } }); _self_clone } pub fn render(_self: Rc<Self>) -> Dom { elem!(templates::module_page(), { .with_data_id!("module-outer", { .with_data_id!("module-content", { .child_signal(_self.has_loaded_data.signal().map(clone!(_self => move |ready| { if ready { let data = _self.loaded_data.borrow_mut().take().unwrap_throw(); Some(ModuleRenderer::render(_self.renderer.clone(),
random
[ { "content": "pub fn image_edit_category_child(name:&str) -> HtmlElement {\n\n TEMPLATES.with(|t| t.cache.render_elem(IMAGE_EDIT_CATEGORIES_CHILD, &html_map!{\n\n \"name\" => name\n\n }).unwrap_throw())\n\n}\n", "file_path": "frontend/apps/crates/entry/admin/src/templates.rs", "rank": 0, ...
Rust
crates/augmented/application/audio-processor-standalone/src/options.rs
yamadapc/augmented-audio
2f662cd8aa1a0ba46445f8f41c8483ae2dc552d3
use std::ffi::OsString; use clap::ArgMatches; pub enum RenderingOptions { Online { input_file: Option<String>, }, Offline { input_file: String, output_file: String, }, } pub struct MidiOptions { pub input_file: Option<String>, } pub struct Options { midi: MidiOptions, rendering: RenderingOptions, } impl Options { pub fn rendering(&self) -> &RenderingOptions { &self.rendering } pub fn midi(&self) -> &MidiOptions { &self.midi } } pub fn parse_options(supports_midi: bool) -> Options { parse_options_from(supports_midi, &mut std::env::args_os()) } fn parse_options_from<I, T>(supports_midi: bool, args: I) -> Options where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let app = clap::App::new("audio-processor-standalone"); let mut app = app .arg(clap::Arg::from_usage( "-i, --input-file=[INPUT_PATH] 'An input audio file to process'", )) .arg(clap::Arg::from_usage( "-o, --output-file=[OUTPUT_PATH] 'If specified, will render offline into this file (WAV)'", )); if supports_midi { app = app .arg(clap::Arg::from_usage( "--midi-input-file=[MIDI_INPUT_FILE] 'If specified, this MIDI file will be passed through the processor'", )); } let matches = app.get_matches_from(args); let midi_options = parse_midi_options(&matches); let rendering = parse_rendering_options(&matches); Options { midi: midi_options, rendering, } } fn parse_midi_options(matches: &ArgMatches) -> MidiOptions { MidiOptions { input_file: matches.value_of("midi-input-file").map(|s| s.into()), } } fn parse_rendering_options(matches: &ArgMatches) -> RenderingOptions { if matches.is_present("output-file") { if !matches.is_present("input-file") { log::error!("Please specify `--input-file`"); std::process::exit(1); } let input_path = matches.value_of("input-file").map(|s| s.into()).unwrap(); let output_path = matches.value_of("output-file").map(|s| s.into()).unwrap(); RenderingOptions::Offline { input_file: input_path, output_file: output_path, } } else { RenderingOptions::Online { input_file: matches.value_of("input-file").map(|s| s.into()), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_empty_options() { let options = parse_options_from::<Vec<String>, String>(false, vec![]); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Online { .. } )); } #[test] fn test_parse_online_options() { let options = parse_options_from::<Vec<String>, String>( false, vec!["program".into(), "--input-file".into(), "test.mp3".into()], ); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Online { .. } )); match options.rendering() { RenderingOptions::Online { input_file } => { assert_eq!(input_file.as_ref().unwrap(), "test.mp3"); } _ => {} } } #[test] fn test_parse_midi_options() { let options = parse_options_from::<Vec<String>, String>( true, vec![ "program".into(), "--midi-input-file".into(), "bach.mid".into(), ], ); assert!(options.midi().input_file.is_some()); assert_eq!(options.midi().input_file.as_ref().unwrap(), "bach.mid") } #[test] fn test_parse_offline_options() { let options = parse_options_from::<Vec<String>, String>( false, vec![ "program".into(), "--input-file".into(), "test.mp3".into(), "--output-file".into(), "test.wav".into(), ], ); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Offline { .. } )); match options.rendering() { RenderingOptions::Offline { input_file, output_file, } => { assert_eq!(input_file, "test.mp3"); assert_eq!(output_file, "test.wav"); } _ => {} } } }
use std::ffi::OsString; use clap::ArgMatches; pub enum RenderingOptions { Online { input_file: Option<String>, }, Offline { input_file: String, output_file: String, }, } pub struct MidiOptions { pub input_file: Option<String>, } pub struct Options { midi: MidiOptions, rendering: RenderingOptions, } impl Options { pub fn rendering(&self) -> &RenderingOptions { &self.rendering } pub fn midi(&self) -> &MidiOptions { &self.midi } } pub fn parse_options(supports_midi: bool) -> Options { parse_options_from(supports_midi, &mut std::env::args_os()) }
fn parse_midi_options(matches: &ArgMatches) -> MidiOptions { MidiOptions { input_file: matches.value_of("midi-input-file").map(|s| s.into()), } } fn parse_rendering_options(matches: &ArgMatches) -> RenderingOptions { if matches.is_present("output-file") { if !matches.is_present("input-file") { log::error!("Please specify `--input-file`"); std::process::exit(1); } let input_path = matches.value_of("input-file").map(|s| s.into()).unwrap(); let output_path = matches.value_of("output-file").map(|s| s.into()).unwrap(); RenderingOptions::Offline { input_file: input_path, output_file: output_path, } } else { RenderingOptions::Online { input_file: matches.value_of("input-file").map(|s| s.into()), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_parse_empty_options() { let options = parse_options_from::<Vec<String>, String>(false, vec![]); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Online { .. } )); } #[test] fn test_parse_online_options() { let options = parse_options_from::<Vec<String>, String>( false, vec!["program".into(), "--input-file".into(), "test.mp3".into()], ); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Online { .. } )); match options.rendering() { RenderingOptions::Online { input_file } => { assert_eq!(input_file.as_ref().unwrap(), "test.mp3"); } _ => {} } } #[test] fn test_parse_midi_options() { let options = parse_options_from::<Vec<String>, String>( true, vec![ "program".into(), "--midi-input-file".into(), "bach.mid".into(), ], ); assert!(options.midi().input_file.is_some()); assert_eq!(options.midi().input_file.as_ref().unwrap(), "bach.mid") } #[test] fn test_parse_offline_options() { let options = parse_options_from::<Vec<String>, String>( false, vec![ "program".into(), "--input-file".into(), "test.mp3".into(), "--output-file".into(), "test.wav".into(), ], ); assert!(options.midi().input_file.is_none()); assert!(matches!( options.rendering(), RenderingOptions::Offline { .. } )); match options.rendering() { RenderingOptions::Offline { input_file, output_file, } => { assert_eq!(input_file, "test.mp3"); assert_eq!(output_file, "test.wav"); } _ => {} } } }
fn parse_options_from<I, T>(supports_midi: bool, args: I) -> Options where I: IntoIterator<Item = T>, T: Into<OsString> + Clone, { let app = clap::App::new("audio-processor-standalone"); let mut app = app .arg(clap::Arg::from_usage( "-i, --input-file=[INPUT_PATH] 'An input audio file to process'", )) .arg(clap::Arg::from_usage( "-o, --output-file=[OUTPUT_PATH] 'If specified, will render offline into this file (WAV)'", )); if supports_midi { app = app .arg(clap::Arg::from_usage( "--midi-input-file=[MIDI_INPUT_FILE] 'If specified, this MIDI file will be passed through the processor'", )); } let matches = app.get_matches_from(args); let midi_options = parse_midi_options(&matches); let rendering = parse_rendering_options(&matches); Options { midi: midi_options, rendering, } }
function_block-function_prefix_line
[ { "content": "pub fn render_to_xml<C: Component>(mut root: C) -> String {\n\n use xml::writer::{EmitterConfig, EventWriter, XmlEvent};\n\n\n\n let bytes = Vec::new();\n\n let buf_sink = BufWriter::new(bytes);\n\n let mut writer = EmitterConfig::new()\n\n .perform_indent(true)\n\n .crea...
Rust
stm32-gen-features/src/lib.rs
topisani/embassy
43a7226d8b8e5a2dabae8afbaf9e81651b59ca6e
use std::{iter::FilterMap, path::Path, slice::Iter}; const SUPPORTED_FAMILIES: [&str; 10] = [ "stm32f0", "stm32f1", "stm32f4", "stm32g0", "stm32l0", "stm32l1", "stm32l4", "stm32h7", "stm32wb55", "stm32wl55", ]; const SEPARATOR_START: &str = "# BEGIN GENERATED FEATURES\n"; const SEPARATOR_END: &str = "# END GENERATED FEATURES\n"; const HELP: &str = "# Generated by stm32-gen-features. DO NOT EDIT.\n"; fn is_supported(name: &str) -> bool { SUPPORTED_FAMILIES .iter() .any(|family| name.starts_with(family)) } type SupportedIter<'a> = FilterMap< Iter<'a, (String, Vec<String>)>, fn(&(String, Vec<String>)) -> Option<(&String, &Vec<String>)>, >; trait FilterSupported { fn supported(&self) -> SupportedIter; } impl FilterSupported for &[(String, Vec<String>)] { fn supported(&self) -> SupportedIter { self.iter() .filter_map(|(name, cores)| is_supported(name).then(|| (name, cores))) } } pub fn chip_names_and_cores() -> Vec<(String, Vec<String>)> { glob::glob("../stm32-data/data/chips/*.yaml") .unwrap() .filter_map(|entry| entry.map_err(|e| eprintln!("{:?}", e)).ok()) .filter_map(|entry| { if let Some(name) = entry.file_stem().and_then(|stem| stem.to_str()) { Some((name.to_lowercase(), chip_cores(&entry))) } else { eprintln!("{:?} is not a regular file", entry); None } }) .collect() } fn chip_cores(path: &Path) -> Vec<String> { let file_contents = std::fs::read_to_string(path).unwrap(); let doc = &yaml_rust::YamlLoader::load_from_str(&file_contents).unwrap()[0]; doc["cores"] .as_vec() .unwrap_or_else(|| panic!("{:?}:[cores] is not an array", path)) .iter() .enumerate() .map(|(i, core)| { core["name"] .as_str() .unwrap_or_else(|| panic!("{:?}:[cores][{}][name] is not a string", path, i)) .to_owned() }) .collect() } pub fn embassy_stm32_needed_data(names_and_cores: &[(String, Vec<String>)]) -> String { let mut result = String::new(); for (chip_name, cores) in names_and_cores.supported() { if cores.len() > 1 { for core_name in cores.iter() { result += &format!( "{chip}_{core} = [ \"stm32-metapac/{chip}_{core}\" ]\n", chip = chip_name, core = core_name ); } } else { result += &format!("{chip} = [ \"stm32-metapac/{chip}\" ]\n", chip = chip_name); } } result } pub fn stm32_metapac_needed_data(names_and_cores: &[(String, Vec<String>)]) -> String { let mut result = String::new(); for (chip_name, cores) in names_and_cores { if cores.len() > 1 { for core_name in cores { result += &format!("{}_{} = []\n", chip_name, core_name); } } else { result += &format!("{} = []\n", chip_name); } } result } fn split_cargo_toml_contents(contents: &str) -> (&str, &str) { let (before, remainder) = contents .split_once(SEPARATOR_START) .unwrap_or_else(|| panic!("missing \"{}\" tag", SEPARATOR_START)); let (_, after) = remainder .split_once(SEPARATOR_END) .unwrap_or_else(|| panic!("missing \"{}\" tag", SEPARATOR_END)); (before, after) } pub fn generate_cargo_toml_file(previous_text: &str, new_contents: &str) -> String { let (before, after) = split_cargo_toml_contents(previous_text); before.to_owned() + SEPARATOR_START + HELP + new_contents + SEPARATOR_END + after } #[cfg(test)] mod tests { use super::*; #[test] fn stm32f407vg_is_supported() { assert!(is_supported("stm32f407vg")) } #[test] fn abcdef_is_not_supported() { assert!(!is_supported("abcdef")) } #[test] #[ignore] fn stm32f407vg_yaml_file_exists_and_is_supported() { assert!(chip_names_and_cores() .as_slice() .supported() .into_iter() .any(|(name, _)| { name == "stm32f407vg" })) } #[test] fn keeps_text_around_separators() { let initial = "\ before # BEGIN GENERATED FEATURES # END GENERATED FEATURES after "; let expected = "\ before # BEGIN GENERATED FEATURES # Generated by stm32-gen-features. DO NOT EDIT. a = [\"b\"] # END GENERATED FEATURES after "; let new_contents = String::from("a = [\"b\"]\n"); assert_eq!(generate_cargo_toml_file(initial, &new_contents), expected); } #[test] #[should_panic] fn does_not_generate_if_separators_are_missing() { let initial = "\ before # END GENERATED FEATURES after "; let new_contents = String::from("a = [\"b\"]\n"); generate_cargo_toml_file(initial, &new_contents); } }
use std::{iter::FilterMap, path::Path, slice::Iter}; const SUPPORTED_FAMILIES: [&str; 10] = [ "stm32f0", "stm32f1", "stm32f4", "stm32g0", "stm32l0", "stm32l1", "stm32l4", "stm32h7", "stm32wb55", "stm32wl55", ]; const SEPARATOR_START: &str = "# BEGIN GENERATED FEATURES\n"; const SEPARATOR_END: &str = "# END GENERATED FEATURES\n"; const HELP: &str = "# Generated by stm32-gen-features. DO NOT EDIT.\n"; fn is_supported(name: &str) -> bool { SUPPORTED_FAMILIES .iter() .any(|family| name.starts_with(family)) } type SupportedIter<'a> = FilterMap< Iter<'a, (String, Vec<String>)>, fn(&(String, Vec<String>)) -> Option<(&String, &Vec<String>)>, >; trait FilterSupported { fn supported(&self) -> SupportedIter; } impl FilterSupported for &[(String, Vec<String>)] { fn supported(&self) -> SupportedIter { self.iter() .filter_map(|(name, cores)| is_supported(name).then(|| (name, cores))) } } pub fn chip_names_and_cores() -> Vec<(String, Vec<String>)> { glob::glob("../stm32-data/data/chips/*.yaml") .unwrap() .filter_map(|entry| entry.map_err(|e| eprintln!("{:?}", e)).ok()) .filter_map(|entry| { if let Some(name) = entry.file_stem().and_then(|stem| stem.to_str()) { Some((name.to_lowercase(), chip_cores(&entry))) } else { eprintln!("{:?} is not a regular file", entry); None } }) .collect() } fn chip_cores(path: &Path) -> Vec<String> { let file_contents = std::fs::read_to_string(path).unwrap(); let doc = &yaml_rust::YamlLoader::load_from_str(&file_contents).unwrap()[0]; doc["cores"] .as_vec() .unwrap_or_else(|| panic!("{:?}:[cores] is not an array", path)) .iter() .enumerate() .map(|(i, core)| { core["name"] .as_str() .unwrap_or_else(|| panic!("{:?}:[cores][{}][name] is not a string", path, i)) .to_owned() }) .collect() } pub fn embassy_stm32_needed_data(names_and_cores: &[(String, Vec<String>)]) -> String { let mut result = String::new(); for (chip_name, cores) in names_and_cores.supported() { if cores.len() > 1 { for core_name in cores.iter() { result += &format!( "{chip}_{core} = [ \"stm32-metapac/{chip}_{core}\" ]\n", chip = chip_name, core = core_name ); } } else { result += &format!("{chip} = [ \"stm32-metapac/{chip}\" ]\n", chip = chip_name); } } result } pub fn stm32_metapac_needed_data(names_and_cores: &[(String, Vec<String>)]) -> String { let mut result = String::new(); for (chip_name, cores) in names_and_cores { if cores.len() > 1 { for core_name in cores { result += &format!("{}_{} = []\n", chip_name, core_name); } } else { result += &format!("{} = []\n", chip_name); } } result } fn split_cargo_toml_contents(contents: &str) -> (&str, &str) { let (before, remainder) = contents .split_once(SEPARATOR_START) .unwrap_or_else(|| panic!("missing \"{}\" tag", SEPARATOR_START)); let (_, after) = remainder .split_once(SEPARATOR_END) .unwrap_or_else(|| panic!("missing \"{}\" tag", SEPARATOR_END)); (before, after) } pub fn generate_cargo_toml_file(previous_text: &str, new_contents: &str) -> String { let (before, after) = split_cargo_toml_contents(previous_text); before.to_owned() + SEPARATOR_START + HELP + new_contents + SEPARATOR_END + after } #[cfg(test)] mod tests { use super::*; #[test] fn stm32f407vg_is_supported() { assert!(is_supported("stm32f407vg")) } #[test] fn abcdef_is_not_supported() { assert!(!is_supported("abcdef")) } #[test] #[ignore] fn stm32f407vg_yaml_file_exists_and_is_supported() { assert!(chip_names_and_cores() .as_slice() .supported() .into_iter() .any(|(name, _)| { name == "stm32f407vg" })) } #[test] fn keeps_text_around_separators() { let initial = "\ before # BEGIN GENERATED FEATURES # END GENERATED FEATURES after "; let expected = "\ before # BEGIN GENERATED FEATURES # Generated by stm32-gen-features. DO NOT EDIT. a = [\"b\"] # END GENERATED FEATURES after "; let new_contents = String::from("a = [\"b\"]\n"); assert_eq!(generate_cargo_toml_file(initial, &new_contents), expected); } #[test] #[should_panic]
}
fn does_not_generate_if_separators_are_missing() { let initial = "\ before # END GENERATED FEATURES after "; let new_contents = String::from("a = [\"b\"]\n"); generate_cargo_toml_file(initial, &new_contents); }
function_block-full_function
[ { "content": "/// Update a Cargo.toml file\n\n///\n\n/// Update the content between \"# BEGIN GENERATED FEATURES\" and \"# END GENERATED FEATURES\"\n\n/// with the given content\n\nfn update_cargo_file(path: &str, new_contents: &str) {\n\n let previous_text = std::fs::read_to_string(path).unwrap();\n\n le...
Rust
identity-account/src/account/builder.rs
charlesthompson3/identity.rs
713140734e86a4b11f85921009b491ff28b5cd10
#[cfg(feature = "stronghold")] use std::path::PathBuf; use std::sync::Arc; #[cfg(feature = "stronghold")] use zeroize::Zeroize; use identity_account_storage::storage::MemStore; use identity_account_storage::storage::Storage; #[cfg(feature = "stronghold")] use identity_account_storage::storage::Stronghold; use identity_iota::tangle::Client; use identity_iota::tangle::ClientBuilder; use identity_iota_core::did::IotaDID; use super::config::AccountConfig; use super::config::AccountSetup; use super::config::AutoSave; use crate::account::Account; use crate::error::Result; use crate::identity::IdentitySetup; #[derive(Debug)] pub enum AccountStorage { Memory, #[cfg(feature = "stronghold")] Stronghold(PathBuf, Option<String>, Option<bool>), Custom(Arc<dyn Storage>), } #[derive(Debug)] pub struct AccountBuilder { config: AccountConfig, storage_template: Option<AccountStorage>, storage: Option<Arc<dyn Storage>>, client_builder: Option<ClientBuilder>, client: Option<Arc<Client>>, } impl AccountBuilder { pub fn new() -> Self { Self { config: AccountConfig::new(), storage_template: Some(AccountStorage::Memory), storage: Some(Arc::new(MemStore::new())), client_builder: None, client: None, } } #[must_use] pub fn autosave(mut self, value: AutoSave) -> Self { self.config = self.config.autosave(value); self } #[must_use] pub fn autopublish(mut self, value: bool) -> Self { self.config = self.config.autopublish(value); self } #[cfg(test)] #[must_use] pub(crate) fn testmode(mut self, value: bool) -> Self { self.config = self.config.testmode(value); self } #[must_use] pub fn storage(mut self, value: AccountStorage) -> Self { self.storage_template = Some(value); self } async fn get_storage(&mut self) -> Result<Arc<dyn Storage>> { match self.storage_template.take() { Some(AccountStorage::Memory) => { let storage = Arc::new(MemStore::new()); self.storage = Some(storage); } #[cfg(feature = "stronghold")] Some(AccountStorage::Stronghold(snapshot, password, dropsave)) => { let passref: Option<&str> = password.as_deref(); let adapter: Stronghold = Stronghold::new(&snapshot, passref, dropsave).await?; if let Some(mut password) = password { password.zeroize(); } let storage = Arc::new(adapter); self.storage = Some(storage); } Some(AccountStorage::Custom(storage)) => { self.storage = Some(storage); } None => (), }; Ok(Arc::clone(self.storage.as_ref().unwrap())) } #[must_use] pub fn client(mut self, client: Arc<Client>) -> Self { self.client = Some(client); self.client_builder = None; self } #[must_use] pub fn client_builder(mut self, client_builder: ClientBuilder) -> Self { self.client = None; self.client_builder = Some(client_builder); self } async fn get_or_build_client(&mut self) -> Result<Arc<Client>> { if let Some(client) = &self.client { Ok(Arc::clone(client)) } else if let Some(client_builder) = self.client_builder.take() { let client: Arc<Client> = Arc::new(client_builder.build().await?); self.client = Some(Arc::clone(&client)); Ok(client) } else { let client: Arc<Client> = Arc::new(Client::new().await?); self.client = Some(Arc::clone(&client)); Ok(client) } } async fn build_setup(&mut self) -> Result<AccountSetup> { let client: Arc<Client> = self.get_or_build_client().await?; Ok(AccountSetup::new( self.get_storage().await?, client, self.config.clone(), )) } pub async fn create_identity(&mut self, input: IdentitySetup) -> Result<Account> { let setup: AccountSetup = self.build_setup().await?; Account::create_identity(setup, input).await } pub async fn load_identity(&mut self, did: IotaDID) -> Result<Account> { let setup: AccountSetup = self.build_setup().await?; Account::load_identity(setup, did).await } } impl Default for AccountBuilder { fn default() -> Self { Self::new() } }
#[cfg(feature = "stronghold")] use std::path::PathBuf; use std::sync::Arc; #[cfg(feature = "stronghold")] use zeroize::Zeroize; use identity_account_storage::storage::MemStore; use identity_account_storage::storage::Storage; #[cfg(feature = "stronghold")] use identity_account_storage::storage::Stronghold; use identity_iota::tangle::Client; use identity_iota::tangle::ClientBuilder; use identity_iota_core::did::IotaDID; use super::config::AccountConfig; use super::config::AccountSetup; use super::config::AutoSave; use crate::account::Account; use crate::error::Result; use crate::identity::IdentitySetup; #[derive(Debug)] pub enum AccountStorage { Memory, #[cfg(feature = "stronghold")] Stronghold(PathBuf, Option<String>, Option<bool>), Custom(Arc<dyn Storage>), } #[derive(Debug)] pub struct AccountBuilder { config: AccountConfig, storage_template: Option<AccountStorage>, storage: Option<Arc<dyn Storage>>, client_builder: Option<ClientBuilder>, client: Option<Arc<Client>>, } impl AccountBuilder { pub fn new() -> Self { Self { config: A
#[must_use] pub fn autosave(mut self, value: AutoSave) -> Self { self.config = self.config.autosave(value); self } #[must_use] pub fn autopublish(mut self, value: bool) -> Self { self.config = self.config.autopublish(value); self } #[cfg(test)] #[must_use] pub(crate) fn testmode(mut self, value: bool) -> Self { self.config = self.config.testmode(value); self } #[must_use] pub fn storage(mut self, value: AccountStorage) -> Self { self.storage_template = Some(value); self } async fn get_storage(&mut self) -> Result<Arc<dyn Storage>> { match self.storage_template.take() { Some(AccountStorage::Memory) => { let storage = Arc::new(MemStore::new()); self.storage = Some(storage); } #[cfg(feature = "stronghold")] Some(AccountStorage::Stronghold(snapshot, password, dropsave)) => { let passref: Option<&str> = password.as_deref(); let adapter: Stronghold = Stronghold::new(&snapshot, passref, dropsave).await?; if let Some(mut password) = password { password.zeroize(); } let storage = Arc::new(adapter); self.storage = Some(storage); } Some(AccountStorage::Custom(storage)) => { self.storage = Some(storage); } None => (), }; Ok(Arc::clone(self.storage.as_ref().unwrap())) } #[must_use] pub fn client(mut self, client: Arc<Client>) -> Self { self.client = Some(client); self.client_builder = None; self } #[must_use] pub fn client_builder(mut self, client_builder: ClientBuilder) -> Self { self.client = None; self.client_builder = Some(client_builder); self } async fn get_or_build_client(&mut self) -> Result<Arc<Client>> { if let Some(client) = &self.client { Ok(Arc::clone(client)) } else if let Some(client_builder) = self.client_builder.take() { let client: Arc<Client> = Arc::new(client_builder.build().await?); self.client = Some(Arc::clone(&client)); Ok(client) } else { let client: Arc<Client> = Arc::new(Client::new().await?); self.client = Some(Arc::clone(&client)); Ok(client) } } async fn build_setup(&mut self) -> Result<AccountSetup> { let client: Arc<Client> = self.get_or_build_client().await?; Ok(AccountSetup::new( self.get_storage().await?, client, self.config.clone(), )) } pub async fn create_identity(&mut self, input: IdentitySetup) -> Result<Account> { let setup: AccountSetup = self.build_setup().await?; Account::create_identity(setup, input).await } pub async fn load_identity(&mut self, did: IotaDID) -> Result<Account> { let setup: AccountSetup = self.build_setup().await?; Account::load_identity(setup, did).await } } impl Default for AccountBuilder { fn default() -> Self { Self::new() } }
ccountConfig::new(), storage_template: Some(AccountStorage::Memory), storage: Some(Arc::new(MemStore::new())), client_builder: None, client: None, } }
function_block-function_prefixed
[ { "content": "// implement Debug on the Enum from the `InputModel`.\n\npub fn impl_debug_enum(input: &InputModel) -> TokenStream {\n\n // collect appropriate data and generate param declarations.\n\n let diff: &Ident = input.diff();\n\n let evariants: &Vec<EVariant> = input.e_variants();\n\n\n\n let param_d...
Rust
integration_test/src/transactional_event_stream_writer_tests.rs
claudiofahey/pravega-client-rust
efaccc1ba896588ffb125cd72378b07f714609e5
use pravega_client::event_stream_writer::EventStreamWriter; use pravega_client_config::{ClientConfigBuilder, MOCK_CONTROLLER_URI}; use pravega_client_shared::*; use pravega_connection_pool::connection_pool::ConnectionPool; use pravega_controller_client::{ControllerClient, ControllerClientImpl}; use pravega_wire_protocol::connection_factory::{ConnectionFactory, SegmentConnectionManager}; use pravega_wire_protocol::wire_commands::{Replies, Requests}; use std::net::SocketAddr; use pravega_client::client_factory::ClientFactory; use pravega_client::raw_client::RawClient; use pravega_client::segment_reader::AsyncSegmentReader; use pravega_client::transaction::transactional_event_stream_writer::TransactionalEventStreamWriter; use pravega_client::transaction::Transaction; use tracing::{error, info}; use crate::pravega_service::PravegaStandaloneServiceConfig; use pravega_wire_protocol::client_connection::{ClientConnection, ClientConnectionImpl}; use pravega_wire_protocol::commands::{ Command, EventCommand, GetStreamSegmentInfoCommand, StreamSegmentInfoCommand, }; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Handle; use tokio::time::sleep; pub fn test_transactional_event_stream_writer(config: PravegaStandaloneServiceConfig) { info!("test TransactionalEventStreamWriter"); let scope_name = Scope::from("testScopeTxnWriter".to_owned()); let stream_name = Stream::from("testStreamTxnWriter".to_owned()); let scoped_stream = ScopedStream { scope: scope_name.clone(), stream: stream_name.clone(), }; let config = ClientConfigBuilder::default() .controller_uri(MOCK_CONTROLLER_URI) .is_auth_enabled(config.auth) .is_tls_enabled(config.tls) .build() .expect("creating config"); let client_factory = ClientFactory::new(config); let handle = client_factory.get_runtime(); handle.block_on(setup_test( &scope_name, &stream_name, client_factory.get_controller_client(), )); let mut writer = handle.block_on(client_factory.create_transactional_event_stream_writer(scoped_stream, WriterId(0))); handle.block_on(test_commit_transaction(&mut writer)); handle.block_on(test_abort_transaction(&mut writer)); handle.block_on(test_write_and_read_transaction(&mut writer, &client_factory)); info!("test TransactionalEventStreamWriter passed"); } async fn test_commit_transaction(writer: &mut TransactionalEventStreamWriter) { info!("test commit transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); transaction .commit(Timestamp(0u64)) .await .expect("commit transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Committed, 10).await; info!("test commit transaction passed"); } async fn test_abort_transaction(writer: &mut TransactionalEventStreamWriter) { info!("test abort transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); transaction.abort().await.expect("abort transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Aborted, 10).await; info!("test abort transaction passed"); } async fn test_write_and_read_transaction( writer: &mut TransactionalEventStreamWriter, factory: &ClientFactory, ) { info!("test write transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); let num_events: i32 = 100; for _ in 0..num_events { transaction .write_event(None, String::from("hello").into_bytes()) .await .expect("write to transaction"); } let segments = factory .get_controller_client() .get_current_segments(&transaction.get_stream()) .await .expect("get segments"); for segment in segments.get_segments() { let segment_info = get_segment_info(&segment, factory).await; assert_eq!(segment_info.write_offset, 0); } transaction .commit(Timestamp(0u64)) .await .expect("commit transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Committed, 10).await; let mut count: i32 = 0; let data: &str = "hello"; for segment in segments.get_segments() { info!("creating reader for segment {:?}", segment); let reader = factory.create_async_event_reader(segment.clone()).await; let segment_info = get_segment_info(&segment, factory).await; let mut offset = 0; let end_offset = segment_info.write_offset; loop { if offset >= end_offset { break; } match reader.read(offset, data.len() as i32 + 8).await { Ok(reply) => { count += 1; offset += data.len() as i64 + 8; let expected = EventCommand { data: String::from("hello").into_bytes(), } .write_fields() .expect("serialize cmd"); assert_eq!(reply.data, expected); } Err(e) => { error!("error {:?} when reading from segment", e); panic!("failed to read data from segmentstore"); } } } } assert_eq!(count, num_events); info!("test write transaction passed"); } async fn setup_test(scope_name: &Scope, stream_name: &Stream, controller_client: &dyn ControllerClient) { controller_client .create_scope(scope_name) .await .expect("create scope"); info!("Scope created"); let request = StreamConfiguration { scoped_stream: ScopedStream { scope: scope_name.clone(), stream: stream_name.clone(), }, scaling: Scaling { scale_type: ScaleType::FixedNumSegments, target_rate: 0, scale_factor: 0, min_num_segments: 2, }, retention: Retention { retention_type: RetentionType::None, retention_param: 0, }, }; controller_client .create_stream(&request) .await .expect("create stream"); info!("Stream created"); } async fn get_segment_info(segment: &ScopedSegment, factory: &ClientFactory) -> StreamSegmentInfoCommand { let delegation_toke_provider = factory .create_delegation_token_provider(ScopedStream::from(segment)) .await; let cmd = GetStreamSegmentInfoCommand { request_id: 0, segment_name: segment.to_string(), delegation_token: delegation_toke_provider .retrieve_token(factory.get_controller_client()) .await, }; let request = Requests::GetStreamSegmentInfo(cmd); let rawclient = factory.create_raw_client(segment).await; let reply = rawclient .send_request(&request) .await .expect("send get segment info cmd"); if let Replies::StreamSegmentInfo(r) = reply { r } else { panic!("wrong reply from segment {:?}", reply); } } async fn wait_for_transaction_with_timeout( transaction: &Transaction, expected_status: TransactionStatus, timeout_second: i32, ) { for _i in 0..timeout_second { if expected_status == transaction.check_status().await.expect("get transaction status") { return; } sleep(Duration::from_secs(1)).await; } panic!( "timeout {:?} exceeded, Transaction is not {:?}", timeout_second, expected_status ); }
use pravega_client::event_stream_writer::EventStreamWriter; use pravega_client_config::{ClientConfigBuilder, MOCK_CONTROLLER_URI}; use pravega_client_shared::*; use pravega_connection_pool::connection_pool::ConnectionPool; use pravega_controller_client::{ControllerClient, ControllerClientImpl}; use pravega_wire_protocol::connection_factory::{ConnectionFactory, SegmentConnectionManager}; use pravega_wire_protocol::wire_commands::{Replies, Requests}; use std::net::SocketAddr; use pravega_client::client_factory::ClientFactory; use pravega_client::raw_client::RawClient; use pravega_client::segment_reader::AsyncSegmentReader; use pravega_client::transaction::transactional_event_stream_writer::TransactionalEventStreamWriter; use pravega_client::transaction::Transaction; use tracing::{error, info}; use crate::pravega_service::PravegaStandaloneServiceConfig; use pravega_wire_protocol::client_connection::{ClientConnection, ClientConnectionImpl}; use pravega_wire_protocol::commands::{ Command, EventCommand, GetStreamSegmentInfoCommand, StreamSegmentInfoCommand, }; use std::sync::Arc; use std::time::Duration; use tokio::runtime::Handle; use tokio::time::sleep; pub fn test_transactional_event_stream_writer(config: PravegaStandaloneServiceConfig) { info!("test TransactionalEventStreamWriter"); let scope_name = Scope::from("testScopeTxnWriter".to_owned()); let stream_name = Stream::from("testStreamTxnWriter".to_owned()); let scoped_stream = ScopedStream { scope: scope_name.clone(), stream: stream_name.clone(), }; let config = ClientConfigBuilder::default() .controller_uri(MOCK_CONTROLLER_URI) .is_auth_enabled(config.auth) .is_tls_enabled(config.tls) .build() .expect("creating config"); let client_factory = ClientFactory::new(config); let handle = client_factory.get_runtime(); handle.block_on(setup_test( &scope_name, &stream_name, client_factory.get_controller_client(), )); let mut writer = handle.block_on(client_factory.create_transactional_event_stream_writer(scoped_stream, WriterId(0))); handle.block_on(test_commit_transaction(&mut writer)); handle.block_on(test_abort_transaction(&mut writer)); handle.block_on(test_write_and_read_transaction(&mut writer, &client_factory)); info!("test TransactionalEventStreamWriter passed"); } async fn test_commit_transaction(writer: &mut TransactionalEventStreamWriter) { info!("test commit transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); transaction .commit(Timestamp(0u64)) .await .expect("commit transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Committed, 10).await; info!("test commit transaction passed"); } async fn test_abort_transaction(writer: &mut TransactionalEventStreamWriter) { info!("test abort transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); transaction.abort().await.expect("abort transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Aborted, 10).await; info!("test abort transaction passed"); } async fn test_write_and_read_transaction( writer: &mut TransactionalEventStreamWriter, factory: &ClientFactory, ) { info!("test write transaction"); let mut transaction = writer.begin().await.expect("begin transaction"); assert_eq!( transaction.check_status().await.expect("get transaction status"), TransactionStatus::Open ); let num_events: i32 = 100; for _ in 0..num_events { transaction .write_event(None, String::from("hello").into_bytes()) .await .expect("write to transaction"); } let segments = factory .get_controller_client() .get_current_segments(&transaction.get_stream()) .await .expect("get segments"); for segment in segments.get_segments() { let segment_info = get_segment_info(&segment, factory).await; assert_eq!(segment_info.write_offset, 0); } transaction .commit(Timestamp(0u64)) .await .expect("commit transaction"); wait_for_transaction_with_timeout(&transaction, TransactionStatus::Committed, 10).await; let mut count: i32 = 0; let data: &str = "hello"; for segment in segments.get_segments() { info!("creating reader for segment {:?}", segment); let reader = factory.create_async_event_reader(segment.clone()).await; let segment_info = get_segment_info(&segment, factory).await; let mut offset = 0; let end_offset = segment_info.write_offset; loop { if offset >= end_offset { break; } match reader.read(offset, data.len() as i32 + 8).await { Ok(reply) => { count += 1; offset += data.len() as i64 + 8; let expected = EventCommand { data: String::from("hello").into_bytes(), } .write_fields() .expect("serialize cmd"); assert_eq!(reply.data, expected); } Err(e) => { error!("error {:?} when reading from segment", e); panic!("failed to read data from segmentstore"); } } } } assert_eq!(count, num_events); info!("test write transaction passed"); } async fn setup_test(scope_name: &Scope, stream_name: &Stream, controller_client: &dyn ControllerClient) { controller_client .create_scope(scope_name) .await .expect("create scope"); info!("Scope created"); let request = StreamConfiguration { scoped_stream: ScopedStream { scope: scope_name.clone(), stream: stream_name.clone(), }, scaling: Scaling { scale_type: ScaleType::FixedNumSegments, target_rate: 0, scale_factor: 0, min_num_segments: 2, }, retention: Retention { retention_type: RetentionType::None, retention_param: 0, }, }; controller_client .create_stream(&request) .await .expect("create stream"); info!("Stream created"); } async fn get_segment_info(segment: &ScopedSegment, factory: &ClientFactory) -> StreamSegmentInfoCommand {
let cmd = GetStreamSegmentInfoCommand { request_id: 0, segment_name: segment.to_string(), delegation_token: delegation_toke_provider .retrieve_token(factory.get_controller_client()) .await, }; let request = Requests::GetStreamSegmentInfo(cmd); let rawclient = factory.create_raw_client(segment).await; let reply = rawclient .send_request(&request) .await .expect("send get segment info cmd"); if let Replies::StreamSegmentInfo(r) = reply { r } else { panic!("wrong reply from segment {:?}", reply); } } async fn wait_for_transaction_with_timeout( transaction: &Transaction, expected_status: TransactionStatus, timeout_second: i32, ) { for _i in 0..timeout_second { if expected_status == transaction.check_status().await.expect("get transaction status") { return; } sleep(Duration::from_secs(1)).await; } panic!( "timeout {:?} exceeded, Transaction is not {:?}", timeout_second, expected_status ); }
let delegation_toke_provider = factory .create_delegation_token_provider(ScopedStream::from(segment)) .await;
assignment_statement
[ { "content": "fn test_simple_write_and_read(writer: &mut ByteStreamWriter, reader: &mut ByteStreamReader) {\n\n info!(\"test byte stream write and read\");\n\n let payload1 = vec![1; 4];\n\n let payload2 = vec![2; 4];\n\n\n\n let size1 = writer.write(&payload1).expect(\"write payload1 to byte stream...
Rust
cs39/src/size_test.rs
gretchenfrage/CS639S20_Demos
d75a16cf66b6b95eb74fc8f101020672b62e5a90
use crate::{ cap_parse, navigate::{ DemoLookup, find_demo, }, compile::{ cpp_files, modify_compile, Compiled, }, output::{ INFO_INDENT, TableWriter, }, quant::{ subproc, demo_min_time, }, }; use std::{ path::Path, process::Command, mem::replace, collections::HashMap, fs::read_to_string, ffi::OsString, }; use regex::{self, Regex}; use byte_unit::Byte; use serde::Serialize; #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] #[repr(usize)] pub enum Dim { X, Y } pub fn parse_dim_line(dim: Dim, line: &str) -> Option<u128> { let pat = format!( r#"^{}[[:space:]]+(?P<n>\d+)[[:space:]]*$"#, regex::escape(&format!( r##"#define {}DIM"##, match dim { Dim::X => 'X', Dim::Y => 'Y', }, )), ); let pat = Regex::new(&pat).unwrap(); pat.captures(line) .map(|caps| cap_parse::<u128>(&caps, "n").unwrap()) } pub fn format_dim_line(dim: Dim, val: u128) -> String { format!( r##"#define {}DIM {}"##, match dim { Dim::X => 'X', Dim::Y => 'Y', }, val, ) } pub fn find_dims( lookup: &DemoLookup, major: u32, minor: u32 ) -> Result<(u128, u128), ()> { let path = find_demo(lookup, major, minor)?; let mut found: [Option<u128>; 2] = [None, None]; for file in cpp_files(&path) { let code = read_to_string(path.join(file)).unwrap(); for line in code.lines() { for &dim in &[Dim::X, Dim::Y] { if let Some(val) = parse_dim_line(dim, line) { if found[dim as usize].is_some() { println!("[ERROR] dimension {:?} defined twice in code", dim); return Err(()); } else { found[dim as usize] = Some(val); } } } } } for &dim in &[Dim::X, Dim::Y] { if found[dim as usize].is_none() { println!("[ERROR] dimension {:?} not found in code", dim); return Err(()); } } Ok((found[0].unwrap(), found[1].unwrap())) } #[derive(Clone, Debug, Serialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SizeTestRow { x_size: u128, y_size: u128, product_size: u128, data_size_bytes: u128, data_size_string: String, best_time_ms: f64, } pub fn run<P>( repo: P, lookup: &DemoLookup, major: u32, minor: u32, mut table: TableWriter<SizeTestRow>, ) -> Result<(), ()> where P: AsRef<Path> { let (base_x, base_y) = find_dims(lookup, major, minor)?; println!("[INFO] default dimensions are {:?}", (base_x, base_y)); let dim_seq: Vec<(u128, u128)> = { let mut vec = Vec::new(); let base = base_x * base_y; let mut curr = base; let incr = 1; for _ in 0..10 { if (curr >> incr) >= (1 << 12) { curr >>= incr; } else { break; } } loop { vec.push(curr); if (curr << incr) > (base << 12) { break; } else if (curr << incr) > ((1 << 30) * 4 / 4) { break; } else { curr <<= incr; } } fn u128sqrt(n: u128) -> u128 { (n as f64).sqrt() as u128 } vec .into_iter() .map(|s| { let y = u128sqrt(base_y * s / base_x); let mut x = s / y; x += s % (x * y); (x, y) }) .collect() }; println!("[INFO] testing with dimensions:"); let mut dim_pretty = Vec::new(); for &(x, y) in &dim_seq { let data_size = x * y * 4; let data_size_str = Byte::from_bytes(data_size) .get_appropriate_unit(true) .format(0); let dim_pretty_curr = format!("{}×{} = {}", x, y, data_size_str); println!("{} • {}", INFO_INDENT, dim_pretty_curr); dim_pretty.push(dim_pretty_curr); } for (i, &(x, y)) in dim_seq.iter().enumerate() { println!("[INFO] benchmarking dimension {}", &dim_pretty[i]); let Compiled { workdir, binary } = modify_compile( &repo, lookup, major, minor, |code: &mut HashMap<OsString, String>| { for (file, content) in replace(code, HashMap::new()) { let rewritten: String = content.lines() .map(|line: &str| { let mut line = line.to_owned(); if parse_dim_line(Dim::X, &line).is_some() { line = format_dim_line(Dim::X, x); } else if parse_dim_line(Dim::Y, &line).is_some() { line = format_dim_line(Dim::Y, y); } line.push('\n'); line }) .collect(); code.insert(file, rewritten); } })?; let (status, lines) = subproc( Command::new(&binary) .current_dir(&workdir), false); let min_time = demo_min_time(&lines); println!("[INFO] best time = {:.2}ms", min_time.as_secs_f64() / 1000.0); table.write(SizeTestRow { x_size: x, y_size: y, product_size: x * y, data_size_bytes: x * y * 4, data_size_string: dim_pretty[i].clone(), best_time_ms: min_time.as_secs_f64() / 1000.0 }); println!(); if !status.success() { println!("[ERROR] exit code {}", status.code().unwrap()); return Err(()); } } println!("[INFO] done"); Ok(()) }
use crate::{ cap_parse, navigate::{ DemoLookup, find_demo, }, compile::{ cpp_files, modify_compile, Compiled, }, output::{ INFO_INDENT, TableWriter, }, quant::{ subproc, demo_min_time,
lone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] #[repr(usize)] pub enum Dim { X, Y } pub fn parse_dim_line(dim: Dim, line: &str) -> Option<u128> { let pat = format!( r#"^{}[[:space:]]+(?P<n>\d+)[[:space:]]*$"#, regex::escape(&format!( r##"#define {}DIM"##, match dim { Dim::X => 'X', Dim::Y => 'Y', }, )), ); let pat = Regex::new(&pat).unwrap(); pat.captures(line) .map(|caps| cap_parse::<u128>(&caps, "n").unwrap()) } pub fn format_dim_line(dim: Dim, val: u128) -> String { format!( r##"#define {}DIM {}"##, match dim { Dim::X => 'X', Dim::Y => 'Y', }, val, ) } pub fn find_dims( lookup: &DemoLookup, major: u32, minor: u32 ) -> Result<(u128, u128), ()> { let path = find_demo(lookup, major, minor)?; let mut found: [Option<u128>; 2] = [None, None]; for file in cpp_files(&path) { let code = read_to_string(path.join(file)).unwrap(); for line in code.lines() { for &dim in &[Dim::X, Dim::Y] { if let Some(val) = parse_dim_line(dim, line) { if found[dim as usize].is_some() { println!("[ERROR] dimension {:?} defined twice in code", dim); return Err(()); } else { found[dim as usize] = Some(val); } } } } } for &dim in &[Dim::X, Dim::Y] { if found[dim as usize].is_none() { println!("[ERROR] dimension {:?} not found in code", dim); return Err(()); } } Ok((found[0].unwrap(), found[1].unwrap())) } #[derive(Clone, Debug, Serialize, PartialEq)] #[serde(rename_all = "PascalCase")] pub struct SizeTestRow { x_size: u128, y_size: u128, product_size: u128, data_size_bytes: u128, data_size_string: String, best_time_ms: f64, } pub fn run<P>( repo: P, lookup: &DemoLookup, major: u32, minor: u32, mut table: TableWriter<SizeTestRow>, ) -> Result<(), ()> where P: AsRef<Path> { let (base_x, base_y) = find_dims(lookup, major, minor)?; println!("[INFO] default dimensions are {:?}", (base_x, base_y)); let dim_seq: Vec<(u128, u128)> = { let mut vec = Vec::new(); let base = base_x * base_y; let mut curr = base; let incr = 1; for _ in 0..10 { if (curr >> incr) >= (1 << 12) { curr >>= incr; } else { break; } } loop { vec.push(curr); if (curr << incr) > (base << 12) { break; } else if (curr << incr) > ((1 << 30) * 4 / 4) { break; } else { curr <<= incr; } } fn u128sqrt(n: u128) -> u128 { (n as f64).sqrt() as u128 } vec .into_iter() .map(|s| { let y = u128sqrt(base_y * s / base_x); let mut x = s / y; x += s % (x * y); (x, y) }) .collect() }; println!("[INFO] testing with dimensions:"); let mut dim_pretty = Vec::new(); for &(x, y) in &dim_seq { let data_size = x * y * 4; let data_size_str = Byte::from_bytes(data_size) .get_appropriate_unit(true) .format(0); let dim_pretty_curr = format!("{}×{} = {}", x, y, data_size_str); println!("{} • {}", INFO_INDENT, dim_pretty_curr); dim_pretty.push(dim_pretty_curr); } for (i, &(x, y)) in dim_seq.iter().enumerate() { println!("[INFO] benchmarking dimension {}", &dim_pretty[i]); let Compiled { workdir, binary } = modify_compile( &repo, lookup, major, minor, |code: &mut HashMap<OsString, String>| { for (file, content) in replace(code, HashMap::new()) { let rewritten: String = content.lines() .map(|line: &str| { let mut line = line.to_owned(); if parse_dim_line(Dim::X, &line).is_some() { line = format_dim_line(Dim::X, x); } else if parse_dim_line(Dim::Y, &line).is_some() { line = format_dim_line(Dim::Y, y); } line.push('\n'); line }) .collect(); code.insert(file, rewritten); } })?; let (status, lines) = subproc( Command::new(&binary) .current_dir(&workdir), false); let min_time = demo_min_time(&lines); println!("[INFO] best time = {:.2}ms", min_time.as_secs_f64() / 1000.0); table.write(SizeTestRow { x_size: x, y_size: y, product_size: x * y, data_size_bytes: x * y * 4, data_size_string: dim_pretty[i].clone(), best_time_ms: min_time.as_secs_f64() / 1000.0 }); println!(); if !status.success() { println!("[ERROR] exit code {}", status.code().unwrap()); return Err(()); } } println!("[INFO] done"); Ok(()) }
}, }; use std::{ path::Path, process::Command, mem::replace, collections::HashMap, fs::read_to_string, ffi::OsString, }; use regex::{self, Regex}; use byte_unit::Byte; use serde::Serialize; #[derive(Copy, C
random
[ { "content": "/// Spawn a sub-process, and by the power of threads,\n\n/// elevate its stdout and stderr to the parent while\n\n/// also merging them together into a line stream,\n\n/// then collecting them.\n\npub fn subproc<B>(mut command: B, quiet: bool) -> (ExitStatus, Vec<String>) \n\nwhere\n\n B: Borro...
Rust
rs/registry/canister/tests/tests/add_node_operator.rs
contropist/ic
9240bea7dc0239fcbc5d43ad11f3ca803ee9bb11
use candid::Encode; use dfn_candid::candid; use dfn_core::api::PrincipalId; use ic_nervous_system_common_test_keys::TEST_NEURON_1_OWNER_PRINCIPAL; use ic_nns_test_utils::registry::invariant_compliant_mutation_as_atomic_req; use ic_nns_test_utils::{ itest_helpers::{ forward_call_via_universal_canister, local_test_on_nns_subnet, set_up_registry_canister, set_up_universal_canister, }, registry::get_value, }; use ic_protobuf::registry::node_operator::v1::NodeOperatorRecord; use ic_registry_keys::make_node_operator_record_key; use registry_canister::{ init::{RegistryCanisterInitPayload, RegistryCanisterInitPayloadBuilder}, mutations::do_add_node_operator::AddNodeOperatorPayload, }; use assert_matches::assert_matches; use std::collections::BTreeMap; #[test] fn test_the_anonymous_user_cannot_add_a_node_operator() { local_test_on_nns_subnet(|runtime| async move { let registry = set_up_registry_canister(&runtime, RegistryCanisterInitPayload::default()).await; let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; let response: Result<(), String> = registry .update_("add_node_operator", candid, (payload.clone(),)) .await; assert_matches!(response, Err(s) if s.contains("is not authorized to call this method: add_node_operator")); let key = make_node_operator_record_key(PrincipalId::new_anonymous()).into_bytes(); assert_eq!( get_value::<NodeOperatorRecord>(&registry, &key).await, NodeOperatorRecord::default() ); Ok(()) }); } #[test] fn test_a_canister_other_than_the_governance_canister_cannot_add_a_node_operator() { local_test_on_nns_subnet(|runtime| async move { let attacker_canister = set_up_universal_canister(&runtime).await; assert_ne!( attacker_canister.canister_id(), ic_nns_constants::GOVERNANCE_CANISTER_ID ); let registry = set_up_registry_canister(&runtime, RegistryCanisterInitPayload::default()).await; let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( !forward_call_via_universal_canister( &attacker_canister, &registry, "add_node_operator", Encode!(&payload).unwrap() ) .await ); let key = make_node_operator_record_key(PrincipalId::new_anonymous()).into_bytes(); assert_eq!( get_value::<NodeOperatorRecord>(&registry, &key).await, NodeOperatorRecord::default() ); Ok(()) }); } #[test] fn test_accepted_proposal_mutates_the_registry() { local_test_on_nns_subnet(|runtime| async move { let registry = set_up_registry_canister( &runtime, RegistryCanisterInitPayloadBuilder::new() .push_init_mutate_request(invariant_compliant_mutation_as_atomic_req()) .build(), ) .await; let fake_proposal_canister = set_up_universal_canister(&runtime).await; assert_eq!( fake_proposal_canister.canister_id(), ic_nns_constants::GOVERNANCE_CANISTER_ID ); let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload).unwrap() ) .await ); assert_eq!( get_value::<NodeOperatorRecord>( &registry, make_node_operator_record_key(PrincipalId::new_anonymous()).as_bytes() ) .await, NodeOperatorRecord { node_operator_principal_id: PrincipalId::new_anonymous().to_vec(), node_allowance: 5, node_provider_principal_id: PrincipalId::new_anonymous().to_vec(), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, } ); let payload2 = AddNodeOperatorPayload { node_operator_principal_id: Some(*TEST_NEURON_1_OWNER_PRINCIPAL), node_allowance: 120, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "BC1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload2).unwrap() ) .await ); assert_eq!( get_value::<NodeOperatorRecord>( &registry, make_node_operator_record_key(*TEST_NEURON_1_OWNER_PRINCIPAL).as_bytes() ) .await, NodeOperatorRecord { node_operator_principal_id: TEST_NEURON_1_OWNER_PRINCIPAL.to_vec(), node_allowance: 120, node_provider_principal_id: PrincipalId::new_anonymous().to_vec(), dc_id: "BC1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, } ); let payload3 = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 567, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "CA1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( !forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload3).unwrap() ) .await ); Ok(()) }); }
use candid::Encode; use dfn_candid::candid; use dfn_core::api::PrincipalId; use ic_nervous_system_common_test_keys::TEST_NEURON_1_OWNER_PRINCIPAL; use ic_nns_test_utils::registry::invariant_compliant_mutation_as_atomic_req; use ic_nns_test_utils::{ itest_helpers::{ forward_call_via_universal_canister, local_test_on_nns_subnet, set_up_registry_canister, set_up_universal_canister, }, registry::get_value, }; use ic_protobuf::registry::node_operator::v1::NodeOperatorRecord; use ic_registry_keys::make_node_operator_record_key; use registry_canister::{ init::{RegistryCanisterInitPayload, RegistryCanisterInitPayloadBuilder}, mutations::do_add_node_operator::AddNodeOperatorPayload, }; use assert_matches::assert_matches; use std::collections::BTreeMap; #[test] fn test_the_anonymous_user_cannot_add_a_node_operator() { local_test_on_nns_subnet(|runtime| async move { let registry = set_up_registry_canister(&runtime, RegistryCanisterInitPayload::default()).await; let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; let response: Result<(), String> = registry .update_("add_node_operator", candid, (payload.clone(),)) .await; assert_matches!(response, Err(s) if s.contain
#[test] fn test_a_canister_other_than_the_governance_canister_cannot_add_a_node_operator() { local_test_on_nns_subnet(|runtime| async move { let attacker_canister = set_up_universal_canister(&runtime).await; assert_ne!( attacker_canister.canister_id(), ic_nns_constants::GOVERNANCE_CANISTER_ID ); let registry = set_up_registry_canister(&runtime, RegistryCanisterInitPayload::default()).await; let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( !forward_call_via_universal_canister( &attacker_canister, &registry, "add_node_operator", Encode!(&payload).unwrap() ) .await ); let key = make_node_operator_record_key(PrincipalId::new_anonymous()).into_bytes(); assert_eq!( get_value::<NodeOperatorRecord>(&registry, &key).await, NodeOperatorRecord::default() ); Ok(()) }); } #[test] fn test_accepted_proposal_mutates_the_registry() { local_test_on_nns_subnet(|runtime| async move { let registry = set_up_registry_canister( &runtime, RegistryCanisterInitPayloadBuilder::new() .push_init_mutate_request(invariant_compliant_mutation_as_atomic_req()) .build(), ) .await; let fake_proposal_canister = set_up_universal_canister(&runtime).await; assert_eq!( fake_proposal_canister.canister_id(), ic_nns_constants::GOVERNANCE_CANISTER_ID ); let payload = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 5, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload).unwrap() ) .await ); assert_eq!( get_value::<NodeOperatorRecord>( &registry, make_node_operator_record_key(PrincipalId::new_anonymous()).as_bytes() ) .await, NodeOperatorRecord { node_operator_principal_id: PrincipalId::new_anonymous().to_vec(), node_allowance: 5, node_provider_principal_id: PrincipalId::new_anonymous().to_vec(), dc_id: "AN1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, } ); let payload2 = AddNodeOperatorPayload { node_operator_principal_id: Some(*TEST_NEURON_1_OWNER_PRINCIPAL), node_allowance: 120, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "BC1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload2).unwrap() ) .await ); assert_eq!( get_value::<NodeOperatorRecord>( &registry, make_node_operator_record_key(*TEST_NEURON_1_OWNER_PRINCIPAL).as_bytes() ) .await, NodeOperatorRecord { node_operator_principal_id: TEST_NEURON_1_OWNER_PRINCIPAL.to_vec(), node_allowance: 120, node_provider_principal_id: PrincipalId::new_anonymous().to_vec(), dc_id: "BC1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, } ); let payload3 = AddNodeOperatorPayload { node_operator_principal_id: Some(PrincipalId::new_anonymous()), node_allowance: 567, node_provider_principal_id: Some(PrincipalId::new_anonymous()), dc_id: "CA1".into(), rewardable_nodes: BTreeMap::new(), ipv6: None, }; assert!( !forward_call_via_universal_canister( &fake_proposal_canister, &registry, "add_node_operator", Encode!(&payload3).unwrap() ) .await ); Ok(()) }); }
s("is not authorized to call this method: add_node_operator")); let key = make_node_operator_record_key(PrincipalId::new_anonymous()).into_bytes(); assert_eq!( get_value::<NodeOperatorRecord>(&registry, &key).await, NodeOperatorRecord::default() ); Ok(()) }); }
function_block-function_prefixed
[ { "content": "fn test_dapp_method_validate_(payload: i64) -> Result<String, String> {\n\n if payload > 10 {\n\n Ok(format!(\"Value is {}. Valid!\", payload))\n\n } else {\n\n Err(\"Value < 10. Invalid!\".to_string())\n\n }\n\n}\n\n\n", "file_path": "rs/sns/integration_tests/test_canis...
Rust
src/banner.rs
nirsarkar/feroxbuster
6921ac03a9a3e08a931bfe160cd4854d76ba6a02
use crate::{config::Configuration, utils::status_colorizer, VERSION}; macro_rules! format_banner_entry_helper { ($rune:expr, $name:expr, $value:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}", $rune, $name, $value, indent = $indent, col_w = $col_width ) }; ($rune:expr, $name:expr, $value:expr, $value2:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}:\u{0020}{}", $rune, $name, $value, $value2, indent = $indent, col_w = $col_width ) }; } macro_rules! format_banner_entry { ($rune:expr, $name:expr, $value:expr) => { format_banner_entry_helper!($rune, $name, $value, 3, 22) }; ($rune:expr, $name:expr, $value1:expr, $value2:expr) => { format_banner_entry_helper!($rune, $name, $value1, $value2, 3, 22) }; } pub fn initialize(targets: &[String], config: &Configuration) { let artwork = format!( r#" ___ ___ __ __ __ __ __ ___ |__ |__ |__) |__) | / ` / \ \_/ | | \ |__ | |___ | \ | \ | \__, \__/ / \ | |__/ |___ by Ben "epi" Risher {} ver: {}"#, '\u{1F913}', VERSION ); let top = "───────────────────────────┬──────────────────────"; let bottom = "───────────────────────────┴──────────────────────"; eprintln!("{}", artwork); eprintln!("{}", top); for target in targets { eprintln!( "{}", format_banner_entry!("\u{1F3af}", "Target Url", target) ); } let mut codes = vec![]; for code in &config.statuscodes { codes.push(status_colorizer(&code.to_string())) } eprintln!( "{}", format_banner_entry!("\u{1F680}", "Threads", config.threads) ); eprintln!( "{}", format_banner_entry!("\u{1f4d6}", "Wordlist", config.wordlist) ); eprintln!( "{}", format_banner_entry!( "\u{1F197}", "Status Codes", format!("[{}]", codes.join(", ")) ) ); eprintln!( "{}", format_banner_entry!("\u{1f4a5}", "Timeout (secs)", config.timeout) ); eprintln!( "{}", format_banner_entry!("\u{1F9a1}", "User-Agent", config.useragent) ); if !config.config.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f489}", "Config File", config.config) ); } if !config.proxy.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f48e}", "Proxy", config.proxy) ); } if !config.headers.is_empty() { for (name, value) in &config.headers { eprintln!( "{}", format_banner_entry!("\u{1f92f}", "Header", name, value) ); } } if !config.sizefilters.is_empty() { for filter in &config.sizefilters { eprintln!( "{}", format_banner_entry!("\u{1f4a2}", "Size Filter", filter) ); } } if config.extract_links { eprintln!( "{}", format_banner_entry!("\u{1F50E}", "Extract Links", config.extract_links) ); } if !config.queries.is_empty() { for query in &config.queries { eprintln!( "{}", format_banner_entry!( "\u{1f914}", "Query Parameter", format!("{}={}", query.0, query.1) ) ); } } if !config.output.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f4be}", "Output File", config.output) ); } if !config.extensions.is_empty() { eprintln!( "{}", format_banner_entry!( "\u{1f4b2}", "Extensions", format!("[{}]", config.extensions.join(", ")) ) ); } if config.insecure { eprintln!( "{}", format_banner_entry!("\u{1f513}", "Insecure", config.insecure) ); } if config.redirects { eprintln!( "{}", format_banner_entry!("\u{1f4cd}", "Follow Redirects", config.redirects) ); } if config.dontfilter { eprintln!( "{}", format_banner_entry!("\u{1f92a}", "Filter Wildcards", !config.dontfilter) ); } match config.verbosity { 1 => { eprintln!( "{}", format_banner_entry!("\u{1f508}", "Verbosity", config.verbosity) ); } 2 => { eprintln!( "{}", format_banner_entry!("\u{1f509}", "Verbosity", config.verbosity) ); } 3 => { eprintln!( "{}", format_banner_entry!("\u{1f50a}", "Verbosity", config.verbosity) ); } 4 => { eprintln!( "{}", format_banner_entry!("\u{1f4e2}", "Verbosity", config.verbosity) ); } _ => {} } if config.addslash { eprintln!( "{}", format_banner_entry!("\u{1fa93}", "Add Slash", config.addslash) ); } if !config.norecursion { if config.depth == 0 { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion Depth", "INFINITE") ); } else { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion Depth", config.depth) ); } } else { eprintln!( "{}", format_banner_entry!("\u{1f6ab}", "Do Not Recurse", config.norecursion) ); } eprintln!("{}", bottom); } #[cfg(test)] mod tests { use super::*; #[test] fn banner_without_targets() { let config = Configuration::default(); initialize(&[], &config); } #[test] fn banner_without_status_codes() { let mut config = Configuration::default(); config.statuscodes = vec![]; initialize(&[String::from("http://localhost")], &config); } #[test] fn banner_without_config_file() { let mut config = Configuration::default(); config.config = String::new(); initialize(&[String::from("http://localhost")], &config); } #[test] fn banner_without_queries() { let mut config = Configuration::default(); config.queries = vec![(String::new(), String::new())]; initialize(&[String::from("http://localhost")], &config); } }
use crate::{config::Configuration, utils::status_colorizer, VERSION}; macro_rules! format_banner_entry_helper { ($rune:expr, $name:expr, $value:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}", $rune, $name, $value, indent = $indent, col_w = $col_width ) }; ($rune:expr, $name:expr, $value:expr, $value2:expr, $indent:expr, $col_width:expr) => { format!( "\u{0020}{:\u{0020}<indent$}{:\u{0020}<col_w$}\u{2502}\u{0020}{}:\u{0020}{}", $rune, $name, $value, $value2, indent = $indent, col_w = $col_width ) }; } macro_rules! format_banner_entry { ($rune:expr, $name:expr, $value:expr) => { format_banner_entry_helper!($rune, $name, $value, 3, 22) }; ($rune:expr, $name:expr, $value1:expr, $value2:expr) => { format_banner_entry_helper!($rune, $name, $value1, $value2, 3, 22) }; } pub fn initialize(targets: &[String], config: &Configuration) { let artwork = format!( r#" ___ ___ __ __ __ __ __ ___ |__ |__ |__) |__) | / ` / \ \_/ | | \ |__ | |___ | \ | \ | \__, \__/ / \ | |__/ |___ by Ben "epi" Risher {} ver: {}"#, '\u{1F913}', VERSION ); let top = "───────────────────────────┬──────────────────────"; let bottom = "───────────────────────────┴──────────────────────"; eprintln!("{}", artwork); eprintln!("{}", top); for target in targets { eprintln!( "{}", format_banner_entry!("\u{1F3af}", "Target Url", target) ); } let mut codes = vec![]; for code in &config.statuscodes { codes.push(status_colorizer(&code.to_string())) } eprintln!( "{}", format_banner_entry!("\u{1F680}", "Threads", config.threads) ); eprintln!( "{}", format_banner_entry!("\u{1f4d6}", "Wordlist", config.wordlist) ); eprintln!( "{}", format_banner_entry!( "\u{1F197}", "Status Codes", format!("[{}]", codes.join(", ")) ) ); eprintln!( "{}", format_banner_entry!("\u{1f4a5}", "Timeout (secs)", config.timeout) ); eprintln!( "{}", format_banner_entry!("\u{1F9a1}", "User-Agent", config.useragent) ); if !config.config.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f489}", "Config File", config.config) ); } if !config.proxy.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f48e}", "Proxy", config.proxy) ); } if !config.headers.is_empty() { for (name, value) in &config.headers { eprintln!( "{}", format_banner_entry!("\u{1f92f}", "Header", name, value) ); } } if !config.sizefilters.is_empty() { for filter in &config.sizefilters { eprintln!( "{}", format_banner_entry!("\u{1f4a2}", "Size Filter", filter) ); } } if config.extract_links { eprintln!( "{}", format_banner_entry!("\u{1F50E}", "Extract Links", config.extract_links) ); } if !config.queries.is_empty() { for query in &config.queries { eprintln!( "{}", format_banner_entry!( "\u{1f914}", "Query Parameter", format!("{}={}", query.0, query.1) ) ); } } if !config.output.is_empty() { eprintln!( "{}", format_banner_entry!("\u{1f4be}", "Output File", config.output) ); } if !config.extensions.is_empty() { eprintln!( "{}", format_banner_entry!( "\u{1f4b2}", "Extensions", format!("[{}]", config.extensions.join(", ")) ) ); } if config.insecure { eprintln!( "{}", format_banner_entry!("\u{1f513}", "Insecure", config.insecure) ); } if config.redirects { eprintln!( "{}", format_banner_entry!("\u{1f4cd}", "Follow Redirects", config.redirects) ); } if config.dontfilter { eprintln!( "{}", format_banner_entry!("\u{1f92a}", "Filter Wildcards", !config.dontfilter) ); } match config.verbosity { 1 => { eprintln!( "{}", format_banner_entry!("\u{1f508}", "Verbosity", config.verbosity) ); } 2 => { eprintln!( "{}", format_banner_entry!("\u{1f509}", "Verbosity", config.verbosity) ); } 3 => { eprintln!( "{}", format_banner_entry!("\u{1f50a}", "Verbosity", config.verbosity) ); } 4 => { eprintln!( "{}", format_banner_entry!("\u{1f4e2}", "Verbosity", config.verbosity) ); } _ => {} } if config.addslash { eprintln!( "{}", format_banner_entry!("\u{1fa93}", "Add Slash", config.addslash) ); }
eprintln!("{}", bottom); } #[cfg(test)] mod tests { use super::*; #[test] fn banner_without_targets() { let config = Configuration::default(); initialize(&[], &config); } #[test] fn banner_without_status_codes() { let mut config = Configuration::default(); config.statuscodes = vec![]; initialize(&[String::from("http://localhost")], &config); } #[test] fn banner_without_config_file() { let mut config = Configuration::default(); config.config = String::new(); initialize(&[String::from("http://localhost")], &config); } #[test] fn banner_without_queries() { let mut config = Configuration::default(); config.queries = vec![(String::new(), String::new())]; initialize(&[String::from("http://localhost")], &config); } }
if !config.norecursion { if config.depth == 0 { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion Depth", "INFINITE") ); } else { eprintln!( "{}", format_banner_entry!("\u{1f503}", "Recursion Depth", config.depth) ); } } else { eprintln!( "{}", format_banner_entry!("\u{1f6ab}", "Do Not Recurse", config.norecursion) ); }
if_condition
[ { "content": "/// simple helper to stay DRY, trys to join a url + fragment and add it to the `links` HashSet\n\nfn add_link_to_set_of_links(link: &str, url: &Url, links: &mut HashSet<String>) {\n\n log::trace!(\n\n \"enter: add_link_to_set_of_links({}, {}, {:?})\",\n\n link,\n\n url.to_s...
Rust
src/cheat.rs
ruabmbua/navi
dc4fe98f5611f40af9f232aaae4b3cfe6058bef5
use crate::display; use crate::filesystem; use crate::option::Config; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; pub struct SuggestionOpts { pub header_lines: u8, pub column: Option<u8>, pub multi: bool, } pub type Value = (String, Option<SuggestionOpts>); fn gen_snippet(snippet: &str, line: &str) -> String { if snippet.is_empty() { line.to_string() } else { format!("{}{}", &snippet[..snippet.len() - 2], line) } } fn parse_opts(text: &str) -> SuggestionOpts { let mut header_lines: u8 = 0; let mut column: Option<u8> = None; let mut multi = false; let mut parts = text.split(' '); while let Some(p) = parts.next() { match p { "--multi" => multi = true, "--header" | "--header-lines" => { header_lines = parts.next().unwrap().parse::<u8>().unwrap() } "--column" => column = Some(parts.next().unwrap().parse::<u8>().unwrap()), _ => (), } } SuggestionOpts { header_lines, column, multi, } } fn parse_variable_line(line: &str) -> (&str, &str, Option<SuggestionOpts>) { let re = Regex::new(r"^\$\s*([^:]+):(.*)").unwrap(); let caps = re.captures(line).unwrap(); let variable = caps.get(1).unwrap().as_str().trim(); let mut command_plus_opts = caps.get(2).unwrap().as_str().split("---"); let command = command_plus_opts.next().unwrap(); let opts = match command_plus_opts.next() { Some(o) => Some(parse_opts(o)), None => None, }; (variable, command, opts) } fn read_file( path: &str, variables: &mut HashMap<String, Value>, stdin: &mut std::process::ChildStdin, ) { let mut tags = String::from(""); let mut comment = String::from(""); let mut snippet = String::from(""); let (tag_width, comment_width) = display::widths(); if let Ok(lines) = filesystem::read_lines(path) { for l in lines { let line = l.unwrap(); if line.starts_with('%') { tags = String::from(&line[2..]); } else if line.starts_with('#') { comment = String::from(&line[2..]); } else if line.starts_with('$') { let (variable, command, opts) = parse_variable_line(&line[..]); variables.insert( format!("{};{}", tags, variable), (String::from(command), opts), ); } else if line.ends_with('\\') { snippet = if !snippet.is_empty() { format!("{}{}", &snippet[..snippet.len() - 2], line) } else { line } } else if line.is_empty() { } else { let full_snippet = gen_snippet(&snippet, &line); match stdin.write( display::format_line( &tags[..], &comment[..], &full_snippet[..], tag_width, comment_width, ) .as_bytes(), ) { Ok(_) => snippet = String::from(""), Err(_) => break, } } } } } pub fn read_all(config: &Config, stdin: &mut std::process::ChildStdin) -> HashMap<String, Value> { let mut variables: HashMap<String, Value> = HashMap::new(); let fallback = format!("{}/cheats", filesystem::exe_path_string()); let folders_str = config.path.as_ref().unwrap_or(&fallback); let folders = folders_str.split(':'); for folder in folders { if let Ok(paths) = fs::read_dir(folder) { for path in paths { read_file( path.unwrap().path().into_os_string().to_str().unwrap(), &mut variables, stdin, ); } } } variables }
use crate::display; use crate::filesystem; use crate::option::Config; use regex::Regex; use std::collections::HashMap; use std::fs; use std::io::Write; pub struct SuggestionOpts { pub header_lines: u8, pub column: Option<u8>, pub multi: bool, } pub type Value = (String, Option<SuggestionOpts>); fn gen_snippet(snippet: &str, line: &str) -> String { if snippet.is_empty() { line.to_string() } else { format!("{}{}", &snippet[..snippet.len() - 2], line) } } fn parse_opts(text: &str) -> SuggestionOpts {
fn parse_variable_line(line: &str) -> (&str, &str, Option<SuggestionOpts>) { let re = Regex::new(r"^\$\s*([^:]+):(.*)").unwrap(); let caps = re.captures(line).unwrap(); let variable = caps.get(1).unwrap().as_str().trim(); let mut command_plus_opts = caps.get(2).unwrap().as_str().split("---"); let command = command_plus_opts.next().unwrap(); let opts = match command_plus_opts.next() { Some(o) => Some(parse_opts(o)), None => None, }; (variable, command, opts) } fn read_file( path: &str, variables: &mut HashMap<String, Value>, stdin: &mut std::process::ChildStdin, ) { let mut tags = String::from(""); let mut comment = String::from(""); let mut snippet = String::from(""); let (tag_width, comment_width) = display::widths(); if let Ok(lines) = filesystem::read_lines(path) { for l in lines { let line = l.unwrap(); if line.starts_with('%') { tags = String::from(&line[2..]); } else if line.starts_with('#') { comment = String::from(&line[2..]); } else if line.starts_with('$') { let (variable, command, opts) = parse_variable_line(&line[..]); variables.insert( format!("{};{}", tags, variable), (String::from(command), opts), ); } else if line.ends_with('\\') { snippet = if !snippet.is_empty() { format!("{}{}", &snippet[..snippet.len() - 2], line) } else { line } } else if line.is_empty() { } else { let full_snippet = gen_snippet(&snippet, &line); match stdin.write( display::format_line( &tags[..], &comment[..], &full_snippet[..], tag_width, comment_width, ) .as_bytes(), ) { Ok(_) => snippet = String::from(""), Err(_) => break, } } } } } pub fn read_all(config: &Config, stdin: &mut std::process::ChildStdin) -> HashMap<String, Value> { let mut variables: HashMap<String, Value> = HashMap::new(); let fallback = format!("{}/cheats", filesystem::exe_path_string()); let folders_str = config.path.as_ref().unwrap_or(&fallback); let folders = folders_str.split(':'); for folder in folders { if let Ok(paths) = fs::read_dir(folder) { for path in paths { read_file( path.unwrap().path().into_os_string().to_str().unwrap(), &mut variables, stdin, ); } } } variables }
let mut header_lines: u8 = 0; let mut column: Option<u8> = None; let mut multi = false; let mut parts = text.split(' '); while let Some(p) = parts.next() { match p { "--multi" => multi = true, "--header" | "--header-lines" => { header_lines = parts.next().unwrap().parse::<u8>().unwrap() } "--column" => column = Some(parts.next().unwrap().parse::<u8>().unwrap()), _ => (), } } SuggestionOpts { header_lines, column, multi, } }
function_block-function_prefix_line
[ { "content": "pub fn variable_prompt(varname: &str) -> String {\n\n format!(\"{}: \", varname)\n\n}\n\n\n", "file_path": "src/display.rs", "rank": 1, "score": 147276.47230093126 }, { "content": "fn gen_replacement(value: &str) -> String {\n\n if value.contains(' ') {\n\n format!...
Rust
iroha/src/queue.rs
EmelianPiker/iroha
d6097b81572554444b2e9a9a560c581006fc895a
use self::config::QueueConfiguration; use crate::prelude::*; use std::time::Duration; #[derive(Debug)] pub struct Queue { pending_tx: Vec<AcceptedTransaction>, maximum_transactions_in_block: usize, transaction_time_to_live: Duration, } impl Queue { pub fn from_configuration(config: &QueueConfiguration) -> Queue { Queue { pending_tx: Vec::new(), maximum_transactions_in_block: config.maximum_transactions_in_block as usize, transaction_time_to_live: Duration::from_millis(config.transaction_time_to_live_ms), } } pub fn push_pending_transaction(&mut self, tx: AcceptedTransaction) { self.pending_tx.push(tx); } pub fn pop_pending_transactions(&mut self) -> Vec<AcceptedTransaction> { self.pending_tx = self .pending_tx .iter() .cloned() .filter(|transaction| !transaction.is_expired(self.transaction_time_to_live)) .collect(); let pending_transactions_length = self.pending_tx.len(); let amount_to_drain = if self.maximum_transactions_in_block > pending_transactions_length { pending_transactions_length } else { self.maximum_transactions_in_block }; self.pending_tx.drain(..amount_to_drain).collect() } } pub mod config { use serde::Deserialize; use std::env; const MAXIMUM_TRANSACTIONS_IN_BLOCK: &str = "MAXIMUM_TRANSACTIONS_IN_BLOCK"; const DEFAULT_MAXIMUM_TRANSACTIONS_IN_BLOCK: u32 = 10; const TRANSACTION_TIME_TO_LIVE_MS: &str = "TRANSACTION_TIME_TO_LIVE_MS"; const DEFAULT_TRANSACTION_TIME_TO_LIVE_MS: u64 = 100_000; #[derive(Clone, Deserialize, Debug)] #[serde(rename_all = "UPPERCASE")] pub struct QueueConfiguration { #[serde(default = "default_maximum_transactions_in_block")] pub maximum_transactions_in_block: u32, #[serde(default = "default_transaction_time_to_live_ms")] pub transaction_time_to_live_ms: u64, } impl QueueConfiguration { pub fn load_environment(&mut self) -> Result<(), String> { if let Ok(max_block_tx) = env::var(MAXIMUM_TRANSACTIONS_IN_BLOCK) { self.maximum_transactions_in_block = serde_json::from_str(&max_block_tx).map_err(|e| { format!( "Failed to parse maximum number of transactions per block: {}", e ) })?; } if let Ok(transaction_ttl_ms) = env::var(TRANSACTION_TIME_TO_LIVE_MS) { self.transaction_time_to_live_ms = serde_json::from_str(&transaction_ttl_ms) .map_err(|e| format!("Failed to parse transaction's ttl: {}", e))?; } Ok(()) } } fn default_maximum_transactions_in_block() -> u32 { DEFAULT_MAXIMUM_TRANSACTIONS_IN_BLOCK } fn default_transaction_time_to_live_ms() -> u64 { DEFAULT_TRANSACTION_TIME_TO_LIVE_MS } } #[cfg(test)] mod tests { use super::*; #[test] fn push_pending_transaction() { let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: 2, transaction_time_to_live_ms: 100000, }); queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100000, ) .accept() .expect("Failed to create Transaction."), ); } #[test] fn pop_pending_transactions() { let max_block_tx = 2; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 100000, }); for _ in 0..5 { queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100000, ) .accept() .expect("Failed to create Transaction."), ); } assert_eq!( queue.pop_pending_transactions().len(), max_block_tx as usize ) } #[test] fn pop_pending_transactions_with_timeout() { let max_block_tx = 6; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 200, }); for _ in 0..(max_block_tx - 1) { queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100, ) .accept() .expect("Failed to create Transaction."), ); } queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 200, ) .accept() .expect("Failed to create Transaction."), ); std::thread::sleep(Duration::from_millis(101)); assert_eq!(queue.pop_pending_transactions().len(), 1); queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 300, ) .accept() .expect("Failed to create Transaction."), ); std::thread::sleep(Duration::from_millis(201)); assert_eq!(queue.pop_pending_transactions().len(), 0); } }
use self::config::QueueConfiguration; use crate::prelude::*; use std::time::Duration; #[derive(Debug)] pub struct Queue { pending_tx: Vec<AcceptedTransaction>, maximum_transactions_in_block: usize, transaction_time_to_live: Duration, } impl Queue { pub fn from_configuration(config: &QueueConfiguration) -> Queue { Queue { pending_tx: Vec::new(), maximum_transactions_in_block: config.maximum_transactions_in_block as usize, transaction_time_to_live: Duration::from_millis(config.transaction_time_to_live_ms), } } pub fn push_pending_transaction(&mut self, tx: AcceptedTransaction) { self.pending_tx.push(tx); } pub fn pop_pending_transactions(&mut self) -> Vec<AcceptedTransaction> { self.pending_tx = self .pending_tx .iter() .cloned() .filter(|transaction| !transaction.is_expired(self.transaction_time_to_live)) .collect(); let pending_transactions_length = self.pending_tx.len(); let amount_to_drain = if self.maximum_transactions_in_block > pending_transactions_length { pending_transactions_length } else { self.maximum_transactions_in_block }; self.pending_tx.drain(..amount_to_drain).collect() } } pub mod config { use serde::Deserialize; use std::env; const MAXIMUM_TRANSACTIONS_IN_BLOCK: &str = "MAXIMUM_TRANSACTIONS_IN_BLOCK"; const DEFAULT_MAXIMUM_TRANSACTIONS_IN_BLOCK: u32 = 10; const TRANSACTION_TIME_TO_LIVE_MS: &str = "TRANSACTION_TIME_TO_LIVE_MS"; const DEFAULT_TRANSACTION_TIME_TO_LIVE_MS: u64 = 100_000; #[derive(Clone, Deserialize, Debug)] #[serde(rename_all = "UPPERCASE")] pub struct QueueConfiguration { #[serde(default = "default_maximum_transactions_in_block")] pub maximum_transactions_in_block: u32, #[serde(default = "default_transaction_time_to_live_ms")] pub transaction_time_to_live_ms: u64, } impl QueueConfiguration { pub fn load_environment(&mut self) -> Result<(), String> { if let Ok(max_block_tx) = env::var(MAXIMUM_TRANSACTIONS_IN_BLOCK) { self.maximum_transactions_in_block = serde_json::from_str(&max_block_tx).map_err(|e| { format!( "Failed to parse maximum number of transactions per block: {}", e ) })?; } if let Ok(transaction_ttl_ms) = env::var(TRANSACTION_TIME_TO_LIVE_MS) { self.transaction_time_to_live_ms = serde_json::from_str(&transaction_ttl_ms) .map_err(|e| format!("Failed to parse transaction's ttl: {}", e))?; } Ok(()) } } fn default_maximum_transactions_in_block() -> u32 { DEFAULT_MAXIMUM_TRANSACTIONS_IN_BLOCK } fn default_transaction_time_to_live_ms() -> u64 { DEFAULT_TRANSACTION_TIME_TO_LIVE_MS } } #[cfg(test)] mod tests { use super::*; #[test] fn push_pending_transaction() { let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: 2, transaction_time_to_live_ms: 100000, }); queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100000, ) .accept() .expect("Failed to create Transaction."), ); } #[test]
#[test] fn pop_pending_transactions_with_timeout() { let max_block_tx = 6; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 200, }); for _ in 0..(max_block_tx - 1) { queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100, ) .accept() .expect("Failed to create Transaction."), ); } queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 200, ) .accept() .expect("Failed to create Transaction."), ); std::thread::sleep(Duration::from_millis(101)); assert_eq!(queue.pop_pending_transactions().len(), 1); queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 300, ) .accept() .expect("Failed to create Transaction."), ); std::thread::sleep(Duration::from_millis(201)); assert_eq!(queue.pop_pending_transactions().len(), 0); } }
fn pop_pending_transactions() { let max_block_tx = 2; let mut queue = Queue::from_configuration(&QueueConfiguration { maximum_transactions_in_block: max_block_tx, transaction_time_to_live_ms: 100000, }); for _ in 0..5 { queue.push_pending_transaction( RequestedTransaction::new( Vec::new(), <Account as Identifiable>::Id::new("account", "domain"), 100000, ) .accept() .expect("Failed to create Transaction."), ); } assert_eq!( queue.pop_pending_transactions().len(), max_block_tx as usize ) }
function_block-full_function
[ { "content": "/// Initializes `Logger` with given `LoggerConfiguration`.\n\n/// After the initialization `log` macros will print with the use of this `Logger`.\n\n/// For more information see [log crate](https://docs.rs/log/0.4.8/log/).\n\npub fn init(configuration: &config::LoggerConfiguration) -> Result<(), S...
Rust
Distributed systems/dsassignment1/solution/lib.rs
rzetelskik/MIMUW
6d193bd6f252a617a275acb1c697bfc983589c0c
use std::time::Duration; use async_channel::{unbounded, Sender, Receiver}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; pub trait Message: Send + 'static {} impl<T: Send + 'static> Message for T {} #[async_trait::async_trait] pub trait Handler<M: Message> where M: Message, { async fn handle(&mut self, msg: M); } #[async_trait::async_trait] trait Handlee<T>: Send + 'static where T: Send, { async fn get_handled(self: Box<Self>, module: &mut T); } #[async_trait::async_trait] impl<M, T> Handlee<T> for M where T: Handler<M> + Send, M: Message, { async fn get_handled(self: Box<Self>, module: &mut T) { module.handle(*self).await } } #[async_trait::async_trait] trait Closeable { fn close(&self) -> bool; } #[async_trait::async_trait] impl<T> Closeable for Receiver<T> { fn close(&self) -> bool { self.close() } } #[derive(Debug, Clone)] pub struct Tick {} pub struct System { finish: Arc<AtomicBool>, handles: Vec<tokio::task::JoinHandle<()>>, tick_handles: Vec<tokio::task::JoinHandle<()>>, rxs: Vec<Box<dyn Closeable>> } impl System { pub async fn request_tick<T: Handler<Tick> + Send>( &mut self, requester: &ModuleRef<T>, delay: Duration, ) { if self.finish.load(Ordering::Relaxed) { panic!(); } let requester_cloned = requester.clone(); let finish_cloned = self.finish.clone(); let handle = tokio::spawn(async move { let mut interval = tokio::time::interval(delay); loop { interval.tick().await; if finish_cloned.load(Ordering::Relaxed) { break; } requester_cloned.send(Tick{}).await; }; }); self.tick_handles.push(handle); } pub async fn register_module<T: Send + 'static>(&mut self, module: T) -> ModuleRef<T> { if self.finish.load(Ordering::Relaxed) { panic!(); } let (tx, rx): (Sender<Box<dyn Handlee<T>>>, Receiver<Box<dyn Handlee<T>>>) = unbounded(); let rx_cloned = rx.clone(); let finish_cloned = self.finish.clone(); let mut mut_module = module; let handle = tokio::spawn(async move { while !finish_cloned.load(Ordering::Relaxed) { match rx_cloned.recv().await { Ok(msg) => { if finish_cloned.load(Ordering::Relaxed) { break; } msg.get_handled(&mut mut_module).await; } Err(_) => { break; } } } }); self.handles.push(handle); self.rxs.push(Box::new(rx)); ModuleRef{ tx } } pub async fn new() -> Self { System{ finish: Arc::new(AtomicBool::new(false)), handles: Vec::new(), tick_handles: Vec::new(), rxs: Vec::new(), } } pub async fn shutdown(&mut self) { if self.finish.load(Ordering::Relaxed) { panic!(); } self.finish.store(true, Ordering::Relaxed); for rx in self.rxs.iter_mut() { rx.close(); } for handle in self.tick_handles.iter_mut() { let _ = handle.await; } for handle in self.handles.iter_mut() { let _ = handle.await; } } } pub struct ModuleRef<T: Send + 'static> { tx: Sender<Box<dyn Handlee<T>>>, } impl<T: Send> ModuleRef<T> { pub async fn send<M: Message>(&self, msg: M) where T: Handler<M>, { let _ = self.tx.send(Box::new(msg)).await; } } impl<T: Send> Clone for ModuleRef<T> { fn clone(&self) -> Self { ModuleRef{ tx: self.tx.clone(), } } }
use std::time::Duration; use async_channel::{unbounded, Sender, Receiver}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; pub trait Message: Send + 'static {} impl<T: Send + 'static> Message for T {} #[async_trait::async_trait] pub trait Handler<M: Message> where M: Message, { async fn handle(&mut self, msg: M); } #[async_trait::async_trait] trait Handlee<T>: Send + 'static where T: Send, { async fn get_handled(self: Box<Self>, module: &mut T); } #[async_trait::async_trait] impl<M, T> Handlee<T> for M where T: Handler<M> + Send, M: Message, { async fn get_handled(self: Box<Self>, module: &mut T) { module.handle(*self).await } } #[async_trait::async_trait] trait Closeable { fn close(&self) -> bool; } #[async_trait::async_trait] impl<T> Closeable for Receiver<T> { fn close(&self) -> bool { self.close() } } #[derive(Debug, Clone)] pub struct Tick {} pub struct System { finish: Arc<AtomicBool>, handles: Vec<tokio::task::JoinHandle<()>>, tick_handles: Vec<tokio::task::JoinHandle<()>>, rxs: Vec<Box<dyn Closeable>> } impl System { pub async fn request_tick<T: Handler<Tick> + Send>( &mut self, requester: &ModuleRef<T>, delay: Duration, ) { if self.finish.load(Ordering::Relaxed) { panic!(); } let requester_cloned = requester.clone(); let finish_cloned = self.finish.clone(); let handle = tokio::spawn(async move { let mut interval = tokio::time::interval(delay); loop { interval.tick().await; if finish_cloned.load(Ordering::Relaxed) { break; } requester_cloned.send(Tick{}).await; }; }); self.tick_handles.push(handle); } pub async fn register_module<T: Send + 'static>(&mut self, module: T) -> ModuleRef<T> { if self.finish.load(Ordering::Relaxed) { panic!(); } let (tx, rx): (Sender<Box<dyn Handlee<T>>>, Receiver<Box<dyn Handlee<T>>>) = unbounded(); let rx_cloned = rx.clone(); let finish_cloned = self.finish.clone(); let mut mut_module = module; let handle = tokio::spawn(async move { while !finish_cloned.load(Ordering::Relaxed) { match rx_cloned.recv().await { Ok(msg) => { if finish_cloned.load(Ordering::Relaxed) { break; } msg.get_handled(&mut mut_module).await; }
pub async fn new() -> Self { System{ finish: Arc::new(AtomicBool::new(false)), handles: Vec::new(), tick_handles: Vec::new(), rxs: Vec::new(), } } pub async fn shutdown(&mut self) { if self.finish.load(Ordering::Relaxed) { panic!(); } self.finish.store(true, Ordering::Relaxed); for rx in self.rxs.iter_mut() { rx.close(); } for handle in self.tick_handles.iter_mut() { let _ = handle.await; } for handle in self.handles.iter_mut() { let _ = handle.await; } } } pub struct ModuleRef<T: Send + 'static> { tx: Sender<Box<dyn Handlee<T>>>, } impl<T: Send> ModuleRef<T> { pub async fn send<M: Message>(&self, msg: M) where T: Handler<M>, { let _ = self.tx.send(Box::new(msg)).await; } } impl<T: Send> Clone for ModuleRef<T> { fn clone(&self) -> Self { ModuleRef{ tx: self.tx.clone(), } } }
Err(_) => { break; } } } }); self.handles.push(handle); self.rxs.push(Box::new(rx)); ModuleRef{ tx } }
function_block-function_prefix_line
[ { "content": "/// Run the executor.\n\nfn run_executor(rx: Receiver<FibonacciSystemMessage>) -> JoinHandle<()> {\n\n let mut modules: HashMap<Ident, FibonacciModule> = HashMap::new();\n\n\n\n thread::spawn(move || {\n\n while let Ok(msg) = rx.recv() {\n\n match msg {\n\n F...
Rust
src/main.rs
belltoy/raindrop
8e26118026d41da74e899dd1d9af0000301253f5
use std::io::BufRead; use std::path::PathBuf; use glob::glob; use structopt::StructOpt; use log::{debug, info, error}; use pretty_env_logger::env_logger as logger; mod exhaust; mod db; #[derive(StructOpt, Debug)] struct Args { #[structopt(short, long, help = "DONOT execute SQL statements")] check: bool, #[structopt(short, long, help = "Input paths", required(true))] inputs: Vec<String>, #[structopt(short, long, help = "Execute or not")] execute: bool, #[structopt(short, long, help = "MySQL URL, example: `mysql://user:password@host:port/db_name`", required_if("execute", "true"))] mysql: Option<String>, } fn main() -> Result<(), String> { logger::from_env(logger::Env::default().default_filter_or("info")).init(); let args = Args::from_args(); if args.execute && args.mysql.is_none() { return Err("Require mysql URL".into()); } let inputs = read_files(&args.inputs)?; let filtered: Vec<_> = inputs.iter() .filter(|(file, p)| { if p.len() == 0 { info!("Filter out empty file: {:?}", file); false } else { true } }) .enumerate() .map(|(no, (file, p))| { (no, file, p) }).collect(); let input_contents: Vec<_> = filtered.iter().map(|(no, _file, p)| { p.iter().map(|s| (no, s.as_str())).collect::<Vec<_>>() }).collect(); let input_files: Vec<_> = filtered.iter().map(|(_no, file, _p)| file).collect(); debug!("input files: {:?}", input_files); assert_eq!(input_files.len(), input_contents.len()); let input_contents: Vec<_> = (&input_contents[..]).iter().map(|p| &p[..]).collect(); let outputs = exhaust::shuffle(&input_contents[..]); outputs.iter().enumerate().for_each(|(i, case)| { debug!("-- Case: {}", i); case.iter().for_each(|(idx, line)| { let idx = **idx; debug!(" {} -- [client: {}] [from file: {:?}]", line, idx, input_files[idx]); }); }); if args.execute { execute_sqls(args.mysql.as_ref().unwrap(), &input_files, &outputs)?; } Ok(()) } fn read_files(inputs: &Vec<String>) -> Result<Vec<(PathBuf, Vec<String>)>, String> { let inputs_paths = inputs.iter().flat_map(|p| { let mut result = glob(p).unwrap().peekable(); if result.peek().is_none() { error!("Invalid input argument: {}", p); } result }); let mut unique_inputs = Vec::new(); inputs_paths .flat_map(|p| { p.map_err(|e| format!("glob pattern error: {}", e)) .and_then(|p| { if p.is_dir() { p.read_dir().map_err(|e| format!("read_dir error: {}", e)) .map(|op: std::fs::ReadDir| { op.map(|p| { p .map(|dir_entry| dir_entry.path()) .map_err(|e| format!("IO error during read dir iteration: {}", e)) }) .filter(|p| { if let Ok(p) = p { !p.is_dir() } else { true } }).collect::<Vec<_>>() }) } else { Ok(vec![Ok(p)]) } }) }) .flat_map(|p| p) .for_each(|p| { if !unique_inputs.contains(&p) { unique_inputs.push(p); } }); let (inputs, errors): (Vec<Result<_, _>>, _) = unique_inputs.into_iter().partition(Result::is_ok); info!("inputs files: {:?}", inputs); if errors.len() > 0 { return Err(format!("{:?}", errors)); } let inputs = inputs.into_iter().map(Result::unwrap); let (inputs_contents, io_errors): (Vec<_>, _) = inputs.map(|input_file| -> Result<_, String> { debug!("Open file: {:?}", input_file); let f = std::fs::File::open(&input_file).map_err(|e| { format!("open file {} error: {}", input_file.to_str().unwrap_or("unknown path"), e) })?; let reader = std::io::BufReader::new(f); let lines: Vec<_> = reader.lines().map(|line| { let line = line.map_err(|e| format!("IO Error when reading lines: {}", e)); line }).collect(); Ok((input_file, lines)) }).partition(Result::is_ok); let inputs_contents = inputs_contents.into_iter().map(Result::unwrap); let io_errors: Vec<_> = io_errors.into_iter().map(Result::unwrap_err).collect(); if io_errors.len() > 0 { let e = &io_errors[0]; return Err(e.into()); } let inputs = inputs_contents.map(|(file_name, lines_result)| { let lines: Vec<_> = lines_result.into_iter() .map(Result::unwrap) .map(|line| line.trim().to_owned()) .filter(|line| line.len() > 0) .collect(); (file_name, lines) }).collect::<Vec<_>>(); Ok(inputs) } fn execute_sqls<I: std::fmt::Debug>(url: &str, input_files: &[I], outputs: &[Vec<(&usize, &str)>]) -> Result<(), String> { let pool = db::init_clients(&url, input_files.len()).map_err(|e| { format!("db error: {:?}", e) })?; let (clients, errors): (Vec<_>, _) = input_files.iter().map(|file| { let file_path = format!("{:?}", file); pool.get_conn().map(|p| (p, file_path)) }) .partition(Result::is_ok); let mut clients: Vec<_> = clients.into_iter().map(Result::unwrap).collect(); let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect(); if errors.len() > 0 { return Err(format!("get connection error: {:?}", errors[0])); } db::execute_sqls(&mut clients[..], &outputs[..]).map_err(|e| { format!("mysql error: {:?}", e) })?; Ok(()) }
use std::io::BufRead; use std::path::PathBuf; use glob::glob; use structopt::StructOpt; use log::{debug, info, error}; use pretty_env_logger::env_logger as logger; mod exhaust; mod db; #[derive(StructOpt, Debug)] struct Args { #[structopt(short, long, help = "DONOT execute SQL statements")] check: bool, #[structopt(short, long, help = "Input paths", required(true))] inputs: Vec<String>, #[structopt(short, long, help = "Execute or not")] execute: bool, #[structopt(short, long, help = "MySQL URL, example: `mysql://user:password@host:port/db_name`", required_if("execute", "true"))] mysql: Option<String>, } fn main() -> Result<(), String> { logger::from_env(logger::Env::default().default_filter_or("info")).init(); let args = Args::from_args(); if args.execute && args.mysql.is_none() { return Err("Require mysql URL".into()); } let inputs = read_files(&args.inputs)?; let filtered: Vec<_> = inputs.iter() .filter(|(file, p)| { if p.len() == 0 { info!("Filter out empty file: {:?}", file); false } else { true } }) .enumerate() .map(|(no, (file, p))| { (no, file, p) }).collect(); let input_contents: Vec<_> = filtered.iter().map(|(no, _file, p)| { p.iter().map(|s| (no, s.as_str())).collect::<Vec<_>>() }).collect(); let input_files: Vec<_> = filtered.iter().map(|(_no, file, _p)| file).collect(); debug!("input files: {:
e(); if result.peek().is_none() { error!("Invalid input argument: {}", p); } result }); let mut unique_inputs = Vec::new(); inputs_paths .flat_map(|p| { p.map_err(|e| format!("glob pattern error: {}", e)) .and_then(|p| { if p.is_dir() { p.read_dir().map_err(|e| format!("read_dir error: {}", e)) .map(|op: std::fs::ReadDir| { op.map(|p| { p .map(|dir_entry| dir_entry.path()) .map_err(|e| format!("IO error during read dir iteration: {}", e)) }) .filter(|p| { if let Ok(p) = p { !p.is_dir() } else { true } }).collect::<Vec<_>>() }) } else { Ok(vec![Ok(p)]) } }) }) .flat_map(|p| p) .for_each(|p| { if !unique_inputs.contains(&p) { unique_inputs.push(p); } }); let (inputs, errors): (Vec<Result<_, _>>, _) = unique_inputs.into_iter().partition(Result::is_ok); info!("inputs files: {:?}", inputs); if errors.len() > 0 { return Err(format!("{:?}", errors)); } let inputs = inputs.into_iter().map(Result::unwrap); let (inputs_contents, io_errors): (Vec<_>, _) = inputs.map(|input_file| -> Result<_, String> { debug!("Open file: {:?}", input_file); let f = std::fs::File::open(&input_file).map_err(|e| { format!("open file {} error: {}", input_file.to_str().unwrap_or("unknown path"), e) })?; let reader = std::io::BufReader::new(f); let lines: Vec<_> = reader.lines().map(|line| { let line = line.map_err(|e| format!("IO Error when reading lines: {}", e)); line }).collect(); Ok((input_file, lines)) }).partition(Result::is_ok); let inputs_contents = inputs_contents.into_iter().map(Result::unwrap); let io_errors: Vec<_> = io_errors.into_iter().map(Result::unwrap_err).collect(); if io_errors.len() > 0 { let e = &io_errors[0]; return Err(e.into()); } let inputs = inputs_contents.map(|(file_name, lines_result)| { let lines: Vec<_> = lines_result.into_iter() .map(Result::unwrap) .map(|line| line.trim().to_owned()) .filter(|line| line.len() > 0) .collect(); (file_name, lines) }).collect::<Vec<_>>(); Ok(inputs) } fn execute_sqls<I: std::fmt::Debug>(url: &str, input_files: &[I], outputs: &[Vec<(&usize, &str)>]) -> Result<(), String> { let pool = db::init_clients(&url, input_files.len()).map_err(|e| { format!("db error: {:?}", e) })?; let (clients, errors): (Vec<_>, _) = input_files.iter().map(|file| { let file_path = format!("{:?}", file); pool.get_conn().map(|p| (p, file_path)) }) .partition(Result::is_ok); let mut clients: Vec<_> = clients.into_iter().map(Result::unwrap).collect(); let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect(); if errors.len() > 0 { return Err(format!("get connection error: {:?}", errors[0])); } db::execute_sqls(&mut clients[..], &outputs[..]).map_err(|e| { format!("mysql error: {:?}", e) })?; Ok(()) }
?}", input_files); assert_eq!(input_files.len(), input_contents.len()); let input_contents: Vec<_> = (&input_contents[..]).iter().map(|p| &p[..]).collect(); let outputs = exhaust::shuffle(&input_contents[..]); outputs.iter().enumerate().for_each(|(i, case)| { debug!("-- Case: {}", i); case.iter().for_each(|(idx, line)| { let idx = **idx; debug!(" {} -- [client: {}] [from file: {:?}]", line, idx, input_files[idx]); }); }); if args.execute { execute_sqls(args.mysql.as_ref().unwrap(), &input_files, &outputs)?; } Ok(()) } fn read_files(inputs: &Vec<String>) -> Result<Vec<(PathBuf, Vec<String>)>, String> { let inputs_paths = inputs.iter().flat_map(|p| { let mut result = glob(p).unwrap().peekabl
random
[ { "content": "pub fn init_clients(url: &str, size: usize) -> MySQLResult<Pool> {\n\n let opts = Opts::from_url(url)?;\n\n let pool = Pool::new_manual(size, size, opts)?;\n\n Ok(pool)\n\n}\n\n\n", "file_path": "src/db.rs", "rank": 3, "score": 74685.11859225594 }, { "content": "/// He...
Rust
alvr/experiments/client/src/xr/openxr/interaction.rs
AndresGroselj/ALVR
679f3a1cdaeff99322fb94560208949d75edef83
use super::{convert, SceneButtons, XrContext, XrHandPoseInput}; use crate::{ xr::{XrActionType, XrActionValue, XrHandTrackingInput, XrProfileDesc}, ViewConfig, }; use alvr_common::{prelude::*, MotionData}; use alvr_session::TrackingSpace; use openxr as xr; use std::collections::HashMap; const OCULUS_PROFILE: &str = "/interaction_profiles/oculus/touch_controller"; const SELECT_ACTION_NAME: &str = "alvr_scene_select"; const OCULUS_SELECT_PATHS: &[&str] = &[ "/user/hand/left/input/x/click", "/user/hand/right/input/a/click", "/user/hand/left/input/trigger", "/user/hand/right/input/trigger", ]; const MENU_ACTION_NAME: &str = "alvr_scene_menu"; const OCULUS_MENU_PATHS: &[&str] = &["/user/hand/left/input/menu/click"]; enum OpenxrButtonAction { Binary(xr::Action<bool>), Scalar(xr::Action<f32>), } struct HandTrackingContext { tracker: xr::HandTracker, target_ray_action: xr::Action<xr::Posef>, target_ray_space: xr::Space, } pub struct HandInteractionContext { grip_action: xr::Action<xr::Posef>, grip_space: xr::Space, hand_tracking_context: Option<HandTrackingContext>, vibration_action: xr::Action<xr::Haptic>, } pub struct OpenxrInteractionContext { session: xr::Session<xr::Vulkan>, action_set: xr::ActionSet, scene_select_action: xr::Action<bool>, scene_menu_action: xr::Action<bool>, streaming_button_actions: HashMap<String, OpenxrButtonAction>, pub reference_space: xr::Space, pub left_hand_interaction: HandInteractionContext, pub right_hand_interaction: HandInteractionContext, } impl OpenxrInteractionContext { fn get_hand_interaction( xr_context: &XrContext, session: xr::Session<xr::Vulkan>, action_set: &xr::ActionSet, hand: xr::Hand, ) -> StrResult<HandInteractionContext> { let hand_str = if hand == xr::Hand::LEFT { "alvr_left" } else { "alvr_right" }; let grip_action_name = format!("{}_grip", hand_str); let grip_action = trace_err!(action_set.create_action(&grip_action_name, &grip_action_name, &[]))?; let grip_space = trace_err!(grip_action.create_space( session.clone(), xr::Path::NULL, xr::Posef::IDENTITY ))?; let hand_tracking_context = if trace_err!(xr_context .instance .supports_hand_tracking(xr_context.system))? { let tracker = trace_err!(session.create_hand_tracker(hand))?; let target_ray_action_name = format!("{}_aim", hand_str); let target_ray_action = trace_err!(action_set.create_action( &target_ray_action_name, &target_ray_action_name, &[] ))?; let target_ray_space = trace_err!(target_ray_action.create_space( session, xr::Path::NULL, xr::Posef::IDENTITY ))?; Some(HandTrackingContext { tracker, target_ray_action, target_ray_space, }) } else { None }; let vibration_action_name = format!("{}_haptics", hand_str); let vibration_action = trace_err!(action_set.create_action( &vibration_action_name, &vibration_action_name, &[] ))?; Ok(HandInteractionContext { grip_action, grip_space, hand_tracking_context, vibration_action, }) } pub fn new( xr_context: &XrContext, session: xr::Session<xr::Vulkan>, stream_action_types: &[(String, XrActionType)], stream_profile_descs: Vec<XrProfileDesc>, ) -> StrResult<Self> { let action_set = trace_err!(xr_context .instance .create_action_set("alvr_bindings", "ALVR bindings", 0))?; let mut button_actions = HashMap::new(); button_actions.insert( SELECT_ACTION_NAME.to_owned(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( SELECT_ACTION_NAME, SELECT_ACTION_NAME, &[] ))?), ); button_actions.insert( MENU_ACTION_NAME.to_owned(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( MENU_ACTION_NAME, MENU_ACTION_NAME, &[] ))?), ); for (name, action_type) in stream_action_types { match action_type { XrActionType::Binary => button_actions.insert( name.clone(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( name, name, &[] ))?), ), XrActionType::Scalar => button_actions.insert( name.clone(), OpenxrButtonAction::Scalar(trace_err!(action_set.create_action( name, name, &[] ))?), ), }; } let left_hand_interaction = Self::get_hand_interaction(xr_context, session.clone(), &action_set, xr::Hand::LEFT)?; let right_hand_interaction = Self::get_hand_interaction(xr_context, session.clone(), &action_set, xr::Hand::RIGHT)?; let mut profile_descs = vec![]; for mut profile in stream_profile_descs { if profile.profile == OCULUS_PROFILE { profile.tracked = true; profile.has_haptics = true; for path in OCULUS_SELECT_PATHS { profile .button_bindings .push((SELECT_ACTION_NAME.to_owned(), (*path).to_owned())); } for path in OCULUS_MENU_PATHS { profile .button_bindings .push((MENU_ACTION_NAME.to_owned(), (*path).to_owned())); } } profile_descs.push(profile); } if profile_descs .iter() .any(|profile| profile.profile == OCULUS_PROFILE) { let mut button_bindings = vec![]; for path in OCULUS_SELECT_PATHS { button_bindings.push((SELECT_ACTION_NAME.to_owned(), (*path).to_owned())); } for path in OCULUS_MENU_PATHS { button_bindings.push((MENU_ACTION_NAME.to_owned(), (*path).to_owned())); } profile_descs.push(XrProfileDesc { profile: OCULUS_PROFILE.to_owned(), button_bindings, tracked: true, has_haptics: true, }) } for profile in profile_descs { let profile_path = trace_err!(xr_context.instance.string_to_path(&profile.profile))?; let mut bindings = vec![]; for (action_name, path_string) in &profile.button_bindings { let action = if let Some(res) = button_actions.get(action_name) { res } else { return fmt_e!("Action {} not defined", action_name); }; let path = trace_err!(xr_context.instance.string_to_path(path_string))?; match action { OpenxrButtonAction::Binary(action) => { bindings.push(xr::Binding::new(action, path)) } OpenxrButtonAction::Scalar(action) => { bindings.push(xr::Binding::new(action, path)) } } } if profile.tracked { bindings.push(xr::Binding::new( &left_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/input/grip/pose"))?, )); if let Some(hand_tracking_context) = &left_hand_interaction.hand_tracking_context { bindings.push(xr::Binding::new( &hand_tracking_context.target_ray_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/input/aim/pose"))?, )); } bindings.push(xr::Binding::new( &right_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/input/grip/pose"))?, )); if let Some(hand_tracking_context) = &right_hand_interaction.hand_tracking_context { bindings.push(xr::Binding::new( &hand_tracking_context.target_ray_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/input/aim/pose"))?, )); } } if profile.has_haptics { bindings.push(xr::Binding::new( &left_hand_interaction.vibration_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/output/haptic"))?, )); bindings.push(xr::Binding::new( &right_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/output/haptic"))?, )); } xr_context .instance .suggest_interaction_profile_bindings(profile_path, &bindings) .ok(); } trace_err!(session.attach_action_sets(&[&action_set]))?; let reference_space = trace_err!(session .create_reference_space(xr::ReferenceSpaceType::STAGE, xr::Posef::IDENTITY) .or_else(|_| { session.create_reference_space( xr::ReferenceSpaceType::LOCAL, xr::Posef { orientation: xr::Quaternionf::IDENTITY, position: xr::Vector3f { x: 0.0, y: -1.5, z: 0.0, }, }, ) }))?; let scene_select_action = match button_actions.remove(SELECT_ACTION_NAME).unwrap() { OpenxrButtonAction::Binary(action) => action, _ => unreachable!(), }; let scene_menu_action = match button_actions.remove(MENU_ACTION_NAME).unwrap() { OpenxrButtonAction::Binary(action) => action, _ => unreachable!(), }; Ok(Self { session, action_set, scene_select_action, scene_menu_action, streaming_button_actions: button_actions, reference_space, left_hand_interaction, right_hand_interaction, }) } pub fn sync_input(&self) -> StrResult { trace_err!(self.session.sync_actions(&[(&self.action_set).into()])) } pub fn get_views( &self, view_configuration_type: xr::ViewConfigurationType, display_time: xr::Time, ) -> StrResult<Vec<ViewConfig>> { let (_, views) = trace_err!(self.session.locate_views( view_configuration_type, display_time, &self.reference_space ))?; Ok(views .into_iter() .map(|view| ViewConfig { orientation: convert::from_xr_orientation(view.pose.orientation), position: convert::from_xr_vec3(view.pose.position), fov: convert::from_xr_fov(view.fov), }) .collect()) } fn get_motion(location: xr::SpaceLocation, velocity: xr::SpaceVelocity) -> MotionData { MotionData { orientation: convert::from_xr_orientation(location.pose.orientation), position: convert::from_xr_vec3(location.pose.position), linear_velocity: velocity.linear_velocity.map(convert::from_xr_vec3), angular_velocity: velocity.angular_velocity.map(convert::from_xr_vec3), } } pub fn get_poses( &self, hand_interaction: &HandInteractionContext, display_time: xr::Time, ) -> StrResult<XrHandPoseInput> { let (grip_location, grip_velocity) = trace_err!(hand_interaction .grip_space .relate(&self.reference_space, display_time))?; let grip_motion = Self::get_motion(grip_location, grip_velocity); let hand_tracking_input = if let Some(ctx) = &hand_interaction.hand_tracking_context { let (target_ray_location, target_ray_velocity) = trace_err!(ctx .target_ray_space .relate(&self.reference_space, display_time))?; let target_ray_motion = Self::get_motion(target_ray_location, target_ray_velocity); if let Some((joint_locations, joint_velocities)) = trace_err!(self .reference_space .relate_hand_joints(&ctx.tracker, display_time))? { let skeleton_motion = joint_locations .iter() .zip(joint_velocities.iter()) .map(|(joint_location, joint_velocity)| MotionData { orientation: convert::from_xr_orientation(joint_location.pose.orientation), position: convert::from_xr_vec3(joint_location.pose.position), linear_velocity: joint_velocity .velocity_flags .contains(xr::SpaceVelocityFlags::LINEAR_VALID) .then(|| convert::from_xr_vec3(joint_velocity.linear_velocity)), angular_velocity: joint_velocity .velocity_flags .contains(xr::SpaceVelocityFlags::ANGULAR_VALID) .then(|| convert::from_xr_vec3(joint_velocity.angular_velocity)), }) .collect(); Some(XrHandTrackingInput { target_ray_motion, skeleton_motion, }) } else { None } } else { None }; Ok(XrHandPoseInput { grip_motion, hand_tracking_input, }) } pub fn get_scene_buttons(&self) -> StrResult<SceneButtons> { let select_state = trace_err!(self .scene_select_action .state(&self.session, xr::Path::NULL))?; let menu_state = trace_err!(self.scene_menu_action.state(&self.session, xr::Path::NULL))?; Ok(SceneButtons { select: select_state.current_state, menu: menu_state.current_state, }) } pub fn get_streming_buttons(&self) -> StrResult<HashMap<String, XrActionValue>> { let mut values = HashMap::new(); for (name, action) in &self.streaming_button_actions { match action { OpenxrButtonAction::Binary(action) => { values.insert( name.clone(), XrActionValue::Boolean( trace_err!(action.state(&self.session, xr::Path::NULL))?.current_state, ), ); } OpenxrButtonAction::Scalar(action) => { values.insert( name.clone(), XrActionValue::Scalar( trace_err!(action.state(&self.session, xr::Path::NULL))?.current_state, ), ); } } } Ok(values) } }
use super::{convert, SceneButtons, XrContext, XrHandPoseInput}; use crate::{ xr::{XrActionType, XrActionValue, XrHandTrackingInput, XrProfileDesc}, ViewConfig, }; use alvr_common::{prelude::*, MotionData}; use alvr_session::TrackingSpace; use openxr as xr; use std::collections::HashMap; const OCULUS_PROFILE: &str = "/interaction_profiles/oculus/touch_controller"; const SELECT_ACTION_NAME: &str = "alvr_scene_select"; const OCULUS_SELECT_PATHS: &[&str] = &[ "/user/hand/left/input/x/click", "/user/hand/right/input/a/click", "/user/hand/left/input/trigger", "/user/hand/right/input/trigger", ]; const MENU_ACTION_NAME: &str = "alvr_scene_menu"; const OCULUS_MENU_PATHS: &[&str] = &["/user/hand/left/input/menu/click"]; enum OpenxrButtonAction { Binary(xr::Action<bool>), Scalar(xr::Action<f32>), } struct HandTrackingContext { tracker: xr::HandTracker, target_ray_action: xr::Action<xr::Posef>, target_ray_space: xr::Space, } pub struct HandInteractionContext { grip_action: xr::Action<xr::Posef>, grip_space: xr::Space, hand_tracking_context: Option<HandTrackingContext>, vibration_action: xr::Action<xr::Haptic>, } pub struct OpenxrInteractionContext { session: xr::Session<xr::Vulkan>, action_set: xr::ActionSet, scene_select_action: xr::Action<bool>, scene_menu_action: xr::Action<bool>, streaming_button_actions: HashMap<String, OpenxrButtonAction>, pub reference_space: xr::Space, pub left_hand_interaction: HandInteractionContext, pub right_hand_interaction: HandInteractionContext, } impl OpenxrInteractionContext { fn get_hand_interaction( xr_context: &XrContext, session: xr::Session<xr::Vulkan>, action_set: &xr::ActionSet, hand: xr::Hand, ) -> StrResult<HandInteractionContext> { let hand_str = if hand == xr::Hand::LEFT { "alvr_left" } else { "alvr_right" }; let grip_action_name = format!("{}_grip", hand_str); let grip_action = trace_err!(action_set.create_action(&grip_action_name, &grip_action_name, &[]))?; let grip_space = trace_err!(grip_action.create_space( session.clone(), xr::Path::NULL, xr::Posef::IDENTITY ))?; let hand_tracking_context = if trace_err!(xr_context .instance .supports_hand_tracking(xr_context.system))? { let tracker = trace_err!(session.create_hand_tracker(hand))?; let target_ray_action_name = format!("{}_aim", hand_str);
let target_ray_space = trace_err!(target_ray_action.create_space( session, xr::Path::NULL, xr::Posef::IDENTITY ))?; Some(HandTrackingContext { tracker, target_ray_action, target_ray_space, }) } else { None }; let vibration_action_name = format!("{}_haptics", hand_str); let vibration_action = trace_err!(action_set.create_action( &vibration_action_name, &vibration_action_name, &[] ))?; Ok(HandInteractionContext { grip_action, grip_space, hand_tracking_context, vibration_action, }) } pub fn new( xr_context: &XrContext, session: xr::Session<xr::Vulkan>, stream_action_types: &[(String, XrActionType)], stream_profile_descs: Vec<XrProfileDesc>, ) -> StrResult<Self> { let action_set = trace_err!(xr_context .instance .create_action_set("alvr_bindings", "ALVR bindings", 0))?; let mut button_actions = HashMap::new(); button_actions.insert( SELECT_ACTION_NAME.to_owned(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( SELECT_ACTION_NAME, SELECT_ACTION_NAME, &[] ))?), ); button_actions.insert( MENU_ACTION_NAME.to_owned(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( MENU_ACTION_NAME, MENU_ACTION_NAME, &[] ))?), ); for (name, action_type) in stream_action_types { match action_type { XrActionType::Binary => button_actions.insert( name.clone(), OpenxrButtonAction::Binary(trace_err!(action_set.create_action( name, name, &[] ))?), ), XrActionType::Scalar => button_actions.insert( name.clone(), OpenxrButtonAction::Scalar(trace_err!(action_set.create_action( name, name, &[] ))?), ), }; } let left_hand_interaction = Self::get_hand_interaction(xr_context, session.clone(), &action_set, xr::Hand::LEFT)?; let right_hand_interaction = Self::get_hand_interaction(xr_context, session.clone(), &action_set, xr::Hand::RIGHT)?; let mut profile_descs = vec![]; for mut profile in stream_profile_descs { if profile.profile == OCULUS_PROFILE { profile.tracked = true; profile.has_haptics = true; for path in OCULUS_SELECT_PATHS { profile .button_bindings .push((SELECT_ACTION_NAME.to_owned(), (*path).to_owned())); } for path in OCULUS_MENU_PATHS { profile .button_bindings .push((MENU_ACTION_NAME.to_owned(), (*path).to_owned())); } } profile_descs.push(profile); } if profile_descs .iter() .any(|profile| profile.profile == OCULUS_PROFILE) { let mut button_bindings = vec![]; for path in OCULUS_SELECT_PATHS { button_bindings.push((SELECT_ACTION_NAME.to_owned(), (*path).to_owned())); } for path in OCULUS_MENU_PATHS { button_bindings.push((MENU_ACTION_NAME.to_owned(), (*path).to_owned())); } profile_descs.push(XrProfileDesc { profile: OCULUS_PROFILE.to_owned(), button_bindings, tracked: true, has_haptics: true, }) } for profile in profile_descs { let profile_path = trace_err!(xr_context.instance.string_to_path(&profile.profile))?; let mut bindings = vec![]; for (action_name, path_string) in &profile.button_bindings { let action = if let Some(res) = button_actions.get(action_name) { res } else { return fmt_e!("Action {} not defined", action_name); }; let path = trace_err!(xr_context.instance.string_to_path(path_string))?; match action { OpenxrButtonAction::Binary(action) => { bindings.push(xr::Binding::new(action, path)) } OpenxrButtonAction::Scalar(action) => { bindings.push(xr::Binding::new(action, path)) } } } if profile.tracked { bindings.push(xr::Binding::new( &left_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/input/grip/pose"))?, )); if let Some(hand_tracking_context) = &left_hand_interaction.hand_tracking_context { bindings.push(xr::Binding::new( &hand_tracking_context.target_ray_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/input/aim/pose"))?, )); } bindings.push(xr::Binding::new( &right_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/input/grip/pose"))?, )); if let Some(hand_tracking_context) = &right_hand_interaction.hand_tracking_context { bindings.push(xr::Binding::new( &hand_tracking_context.target_ray_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/input/aim/pose"))?, )); } } if profile.has_haptics { bindings.push(xr::Binding::new( &left_hand_interaction.vibration_action, trace_err!(xr_context .instance .string_to_path("/user/hand/left/output/haptic"))?, )); bindings.push(xr::Binding::new( &right_hand_interaction.grip_action, trace_err!(xr_context .instance .string_to_path("/user/hand/right/output/haptic"))?, )); } xr_context .instance .suggest_interaction_profile_bindings(profile_path, &bindings) .ok(); } trace_err!(session.attach_action_sets(&[&action_set]))?; let reference_space = trace_err!(session .create_reference_space(xr::ReferenceSpaceType::STAGE, xr::Posef::IDENTITY) .or_else(|_| { session.create_reference_space( xr::ReferenceSpaceType::LOCAL, xr::Posef { orientation: xr::Quaternionf::IDENTITY, position: xr::Vector3f { x: 0.0, y: -1.5, z: 0.0, }, }, ) }))?; let scene_select_action = match button_actions.remove(SELECT_ACTION_NAME).unwrap() { OpenxrButtonAction::Binary(action) => action, _ => unreachable!(), }; let scene_menu_action = match button_actions.remove(MENU_ACTION_NAME).unwrap() { OpenxrButtonAction::Binary(action) => action, _ => unreachable!(), }; Ok(Self { session, action_set, scene_select_action, scene_menu_action, streaming_button_actions: button_actions, reference_space, left_hand_interaction, right_hand_interaction, }) } pub fn sync_input(&self) -> StrResult { trace_err!(self.session.sync_actions(&[(&self.action_set).into()])) } pub fn get_views( &self, view_configuration_type: xr::ViewConfigurationType, display_time: xr::Time, ) -> StrResult<Vec<ViewConfig>> { let (_, views) = trace_err!(self.session.locate_views( view_configuration_type, display_time, &self.reference_space ))?; Ok(views .into_iter() .map(|view| ViewConfig { orientation: convert::from_xr_orientation(view.pose.orientation), position: convert::from_xr_vec3(view.pose.position), fov: convert::from_xr_fov(view.fov), }) .collect()) } fn get_motion(location: xr::SpaceLocation, velocity: xr::SpaceVelocity) -> MotionData { MotionData { orientation: convert::from_xr_orientation(location.pose.orientation), position: convert::from_xr_vec3(location.pose.position), linear_velocity: velocity.linear_velocity.map(convert::from_xr_vec3), angular_velocity: velocity.angular_velocity.map(convert::from_xr_vec3), } } pub fn get_poses( &self, hand_interaction: &HandInteractionContext, display_time: xr::Time, ) -> StrResult<XrHandPoseInput> { let (grip_location, grip_velocity) = trace_err!(hand_interaction .grip_space .relate(&self.reference_space, display_time))?; let grip_motion = Self::get_motion(grip_location, grip_velocity); let hand_tracking_input = if let Some(ctx) = &hand_interaction.hand_tracking_context { let (target_ray_location, target_ray_velocity) = trace_err!(ctx .target_ray_space .relate(&self.reference_space, display_time))?; let target_ray_motion = Self::get_motion(target_ray_location, target_ray_velocity); if let Some((joint_locations, joint_velocities)) = trace_err!(self .reference_space .relate_hand_joints(&ctx.tracker, display_time))? { let skeleton_motion = joint_locations .iter() .zip(joint_velocities.iter()) .map(|(joint_location, joint_velocity)| MotionData { orientation: convert::from_xr_orientation(joint_location.pose.orientation), position: convert::from_xr_vec3(joint_location.pose.position), linear_velocity: joint_velocity .velocity_flags .contains(xr::SpaceVelocityFlags::LINEAR_VALID) .then(|| convert::from_xr_vec3(joint_velocity.linear_velocity)), angular_velocity: joint_velocity .velocity_flags .contains(xr::SpaceVelocityFlags::ANGULAR_VALID) .then(|| convert::from_xr_vec3(joint_velocity.angular_velocity)), }) .collect(); Some(XrHandTrackingInput { target_ray_motion, skeleton_motion, }) } else { None } } else { None }; Ok(XrHandPoseInput { grip_motion, hand_tracking_input, }) } pub fn get_scene_buttons(&self) -> StrResult<SceneButtons> { let select_state = trace_err!(self .scene_select_action .state(&self.session, xr::Path::NULL))?; let menu_state = trace_err!(self.scene_menu_action.state(&self.session, xr::Path::NULL))?; Ok(SceneButtons { select: select_state.current_state, menu: menu_state.current_state, }) } pub fn get_streming_buttons(&self) -> StrResult<HashMap<String, XrActionValue>> { let mut values = HashMap::new(); for (name, action) in &self.streaming_button_actions { match action { OpenxrButtonAction::Binary(action) => { values.insert( name.clone(), XrActionValue::Boolean( trace_err!(action.state(&self.session, xr::Path::NULL))?.current_state, ), ); } OpenxrButtonAction::Scalar(action) => { values.insert( name.clone(), XrActionValue::Scalar( trace_err!(action.state(&self.session, xr::Path::NULL))?.current_state, ), ); } } } Ok(values) } }
let target_ray_action = trace_err!(action_set.create_action( &target_ray_action_name, &target_ray_action_name, &[] ))?;
assignment_statement
[ { "content": "pub fn create_graphics_context(xr_context: &XrContext) -> StrResult<GraphicsContext> {\n\n let entry = unsafe { ash::Entry::load().unwrap() };\n\n\n\n let raw_instance = unsafe {\n\n let extensions_ptrs =\n\n convert::get_vulkan_instance_extensions(&entry, TARGET_VULKAN_VER...
Rust
src/message/commands/clearchat.rs
Chronophylos/twitch-irc-rs
bf9792ebc085c08bb2e7e49e158ef2ae3e4412c6
use crate::message::commands::IRCMessageParseExt; use crate::message::{IRCMessage, ServerMessageParseError}; use chrono::{DateTime, Utc}; use std::convert::TryFrom; use std::str::FromStr; use std::time::Duration; #[derive(Debug, Clone, PartialEq)] pub struct ClearChatMessage { pub channel_login: String, pub channel_id: String, pub action: ClearChatAction, pub server_timestamp: DateTime<Utc>, pub source: IRCMessage, } #[derive(Debug, Clone, PartialEq)] pub enum ClearChatAction { ChatCleared, UserBanned { user_login: String, user_id: String, }, UserTimedOut { user_login: String, user_id: String, timeout_length: Duration, }, } impl TryFrom<IRCMessage> for ClearChatMessage { type Error = ServerMessageParseError; fn try_from(source: IRCMessage) -> Result<ClearChatMessage, ServerMessageParseError> { if source.command != "CLEARCHAT" { return Err(ServerMessageParseError::MismatchedCommand(source)); } let action = match source.params.get(1) { Some(user_login) => { let user_id = source.try_get_nonempty_tag_value("target-user-id")?; let ban_duration = source.try_get_optional_nonempty_tag_value("ban-duration")?; match ban_duration { Some(ban_duration) => { let ban_duration = u64::from_str(ban_duration).map_err(|_| { ServerMessageParseError::MalformedTagValue( source.to_owned(), "ban-duration", ban_duration.to_owned(), ) })?; ClearChatAction::UserTimedOut { user_login: user_login.to_owned(), user_id: user_id.to_owned(), timeout_length: Duration::from_secs(ban_duration), } } None => ClearChatAction::UserBanned { user_login: user_login.to_owned(), user_id: user_id.to_owned(), }, } } None => ClearChatAction::ChatCleared, }; Ok(ClearChatMessage { channel_login: source.try_get_channel_login()?.to_owned(), channel_id: source.try_get_nonempty_tag_value("room-id")?.to_owned(), action, server_timestamp: source.try_get_timestamp("tmi-sent-ts")?, source, }) } } impl From<ClearChatMessage> for IRCMessage { fn from(msg: ClearChatMessage) -> IRCMessage { msg.source } } #[cfg(test)] mod tests { use crate::message::commands::clearchat::ClearChatAction; use crate::message::{ClearChatMessage, IRCMessage}; use chrono::{TimeZone, Utc}; use std::convert::TryFrom; use std::time::Duration; #[test] pub fn test_timeout() { let src = "@ban-duration=1;room-id=11148817;target-user-id=148973258;tmi-sent-ts=1594553828245 :tmi.twitch.tv CLEARCHAT #pajlada :fabzeef"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "pajlada".to_owned(), channel_id: "11148817".to_owned(), action: ClearChatAction::UserTimedOut { user_login: "fabzeef".to_owned(), user_id: "148973258".to_owned(), timeout_length: Duration::from_secs(1) }, server_timestamp: Utc.timestamp_millis(1594553828245), source: irc_message } ) } #[test] pub fn test_permaban() { let src = "@room-id=11148817;target-user-id=70948394;tmi-sent-ts=1594561360331 :tmi.twitch.tv CLEARCHAT #pajlada :weeb123"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "pajlada".to_owned(), channel_id: "11148817".to_owned(), action: ClearChatAction::UserBanned { user_login: "weeb123".to_owned(), user_id: "70948394".to_owned(), }, server_timestamp: Utc.timestamp_millis(1594561360331), source: irc_message } ) } #[test] pub fn test_chat_clear() { let src = "@room-id=40286300;tmi-sent-ts=1594561392337 :tmi.twitch.tv CLEARCHAT #randers"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "randers".to_owned(), channel_id: "40286300".to_owned(), action: ClearChatAction::ChatCleared, server_timestamp: Utc.timestamp_millis(1594561392337), source: irc_message } ) } }
use crate::message::commands::IRCMessageParseExt; use crate::message::{IRCMessage, ServerMessageParseError}; use chrono::{DateTime, Utc}; use std::convert::TryFrom; use std::str::FromStr; use std::time::Duration; #[derive(Debug, Clone, PartialEq)] pub struct ClearChatMessage { pub channel_login: String, pub channel_id: String, pub action: ClearChatAction, pub server_timestamp: DateTime<Utc>, pub source: IRCMessage, } #[derive(Debug, Clone, PartialEq)] pub enum ClearChatAction { ChatCleared, UserBanned { user_login: String, user_id: String, }, UserTimedOut { user_login: String, user_id: String, timeout_length: Duration, }, } impl TryFrom<IRCMessage> for ClearChatMessage { type Error = ServerMessageParseError; fn try_from(source: IRCMessage) -> Result<ClearChatMessage, ServerMessageParseError> { if source.command != "CLEARCHAT" { return Err(ServerMessageParseError::MismatchedCommand(source)); } let action = match source.params.get(1) { Some(user_login) => { let user_id = source.try_get_nonempty_tag_value("target-user-id")?; let ban_duration = source.try_get_optional_nonempty_tag_value("ban-duration")?; match ban_duration { Some(ban_duration) => { let ban_duration = u64::from_str(ban_duration).map_err(|_| { ServerMessageParseError::MalformedTagValue( source.to_owned(), "ban-duration", ban_duration.to_owned(), ) })?; ClearChatAction::UserTimedOut { user_login: user_login.to_owned(), user_id: user_id.to_owned(), timeout_length: Duration::from_secs(ban_duration), } } None => ClearChatAction::UserBanned { user_login: user_login.to_owned(), user_id: user_id.to_owned(), }, } } None => ClearChatAction::ChatCleared, }; Ok(ClearChatMessage { channel_login: source.try_get_channel_login()?.to_owned(), channel_id: source.try_get_nonempty_tag_value("room-id")?.to_owned(), action, server_timestamp: source.try_get_timestamp("tmi-sent-ts")?, source, }) } } impl From<ClearChatMessage> for IRCMessage { fn from(msg: ClearChatMessage) -> IRCMessage { msg.source } } #[cfg(test)] mod tests { use crate::message::commands::clearchat::ClearChatAction; use crate::message::{ClearChatMessage, IRCMessage}; use chrono::{TimeZone, Utc}; use std::convert::TryFrom; use std::time::Duration; #[test]
#[test] pub fn test_permaban() { let src = "@room-id=11148817;target-user-id=70948394;tmi-sent-ts=1594561360331 :tmi.twitch.tv CLEARCHAT #pajlada :weeb123"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "pajlada".to_owned(), channel_id: "11148817".to_owned(), action: ClearChatAction::UserBanned { user_login: "weeb123".to_owned(), user_id: "70948394".to_owned(), }, server_timestamp: Utc.timestamp_millis(1594561360331), source: irc_message } ) } #[test] pub fn test_chat_clear() { let src = "@room-id=40286300;tmi-sent-ts=1594561392337 :tmi.twitch.tv CLEARCHAT #randers"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "randers".to_owned(), channel_id: "40286300".to_owned(), action: ClearChatAction::ChatCleared, server_timestamp: Utc.timestamp_millis(1594561392337), source: irc_message } ) } }
pub fn test_timeout() { let src = "@ban-duration=1;room-id=11148817;target-user-id=148973258;tmi-sent-ts=1594553828245 :tmi.twitch.tv CLEARCHAT #pajlada :fabzeef"; let irc_message = IRCMessage::parse(src).unwrap(); let msg = ClearChatMessage::try_from(irc_message.clone()).unwrap(); assert_eq!( msg, ClearChatMessage { channel_login: "pajlada".to_owned(), channel_id: "11148817".to_owned(), action: ClearChatAction::UserTimedOut { user_login: "fabzeef".to_owned(), user_id: "148973258".to_owned(), timeout_length: Duration::from_secs(1) }, server_timestamp: Utc.timestamp_millis(1594553828245), source: irc_message } ) }
function_block-full_function
[ { "content": "fn encode_tag_value(raw: &str) -> String {\n\n let mut output = String::with_capacity((raw.len() as f64 * 1.2) as usize);\n\n\n\n for c in raw.chars() {\n\n match c {\n\n ';' => output.push_str(\"\\\\:\"),\n\n ' ' => output.push_str(\"\\\\s\"),\n\n '\\...
Rust
src/test_framework/incremental_interface.rs
vlmutolo/orion
e2af271cc3b7ce763591e02a5e6808579c1e3504
use crate::errors::UnknownCryptoError; use core::marker::PhantomData; pub trait TestableStreamingContext<T: PartialEq> { fn reset(&mut self) -> Result<(), UnknownCryptoError>; fn update(&mut self, input: &[u8]) -> Result<(), UnknownCryptoError>; fn finalize(&mut self) -> Result<T, UnknownCryptoError>; fn one_shot(input: &[u8]) -> Result<T, UnknownCryptoError>; fn verify_result(expected: &T, input: &[u8]) -> Result<(), UnknownCryptoError>; fn compare_states(state_1: &Self, state_2: &Self); } #[allow(dead_code)] pub struct StreamingContextConsistencyTester<R, T> { _return_type: PhantomData<R>, _initial_context: T, blocksize: usize, } impl<R, T> StreamingContextConsistencyTester<R, T> where R: PartialEq + core::fmt::Debug, T: TestableStreamingContext<R> + Clone, { pub fn new(streaming_context: T, blocksize: usize) -> Self { Self { _return_type: PhantomData, _initial_context: streaming_context, blocksize, } } const DEFAULT_INPUT: [u8; 37] = [255u8; 37]; #[cfg(feature = "safe_api")] pub fn run_all_tests_property(&self, data: &[u8]) { self.consistency(data); self.consistency(&[0u8; 0]); self.produces_same_state(data); self.incremental_and_one_shot(data); self.double_finalize_with_reset_no_update_ok(data); self.double_finalize_with_reset_ok(data); self.double_finalize_err(data); self.update_after_finalize_with_reset_ok(data); self.update_after_finalize_err(data); self.double_reset_ok(data); self.immediate_finalize(); Self::verify_same_input_ok(data); Self::verify_diff_input_err(data); } #[cfg(feature = "safe_api")] pub fn run_all_tests(&self) { self.consistency(&Self::DEFAULT_INPUT); self.consistency(&[0u8; 0]); self.produces_same_state(&Self::DEFAULT_INPUT); self.incremental_processing_with_leftover(); self.incremental_and_one_shot(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_no_update_ok(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.double_finalize_err(&Self::DEFAULT_INPUT); self.update_after_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.update_after_finalize_err(&Self::DEFAULT_INPUT); self.double_reset_ok(&Self::DEFAULT_INPUT); self.immediate_finalize(); Self::verify_same_input_ok(&Self::DEFAULT_INPUT); Self::verify_diff_input_err(&Self::DEFAULT_INPUT); } #[cfg(not(feature = "safe_api"))] pub fn run_all_tests(&self) { self.consistency(&Self::DEFAULT_INPUT); self.consistency(&[0u8; 0]); self.produces_same_state(&Self::DEFAULT_INPUT); self.incremental_and_one_shot(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_no_update_ok(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.double_finalize_err(&Self::DEFAULT_INPUT); self.update_after_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.update_after_finalize_err(&Self::DEFAULT_INPUT); self.double_reset_ok(&Self::DEFAULT_INPUT); self.immediate_finalize(); Self::verify_same_input_ok(&Self::DEFAULT_INPUT); Self::verify_diff_input_err(&Self::DEFAULT_INPUT); } fn consistency(&self, data: &[u8]) { let mut state_1 = self._initial_context.clone(); state_1.update(data).unwrap(); let res_1 = state_1.finalize().unwrap(); let mut state_2 = self._initial_context.clone(); state_2.reset().unwrap(); state_2.update(data).unwrap(); let res_2 = state_2.finalize().unwrap(); let mut state_3 = self._initial_context.clone(); state_3.update(data).unwrap(); state_3.reset().unwrap(); state_3.update(data).unwrap(); let res_3 = state_3.finalize().unwrap(); let mut state_4 = self._initial_context.clone(); state_4.update(data).unwrap(); let _ = state_4.finalize().unwrap(); state_4.reset().unwrap(); state_4.update(data).unwrap(); let res_4 = state_4.finalize().unwrap(); assert_eq!(res_1, res_2); assert_eq!(res_2, res_3); assert_eq!(res_3, res_4); if data.is_empty() { let mut state_5 = self._initial_context.clone(); let res_5 = state_5.finalize().unwrap(); let mut state_6 = self._initial_context.clone(); state_6.reset().unwrap(); let res_6 = state_6.finalize().unwrap(); let mut state_7 = self._initial_context.clone(); state_7.update(b"WRONG DATA").unwrap(); state_7.reset().unwrap(); let res_7 = state_7.finalize().unwrap(); assert_eq!(res_4, res_5); assert_eq!(res_5, res_6); assert_eq!(res_6, res_7); } } fn produces_same_state(&self, data: &[u8]) { let state_1 = self._initial_context.clone(); let mut state_2 = self._initial_context.clone(); state_2.reset().unwrap(); let mut state_3 = self._initial_context.clone(); state_3.update(data).unwrap(); state_3.reset().unwrap(); let mut state_4 = self._initial_context.clone(); state_4.update(data).unwrap(); let _ = state_4.finalize().unwrap(); state_4.reset().unwrap(); T::compare_states(&state_1, &state_2); T::compare_states(&state_2, &state_3); T::compare_states(&state_3, &state_4); } #[cfg(feature = "safe_api")] fn incremental_processing_with_leftover(&self) { for len in 0..self.blocksize * 4 { let data = vec![0u8; len]; let mut state = self._initial_context.clone(); let mut other_data: Vec<u8> = Vec::new(); other_data.extend_from_slice(&data); state.update(&data).unwrap(); if data.len() > self.blocksize { other_data.extend_from_slice(b""); state.update(b"").unwrap(); } if data.len() > self.blocksize * 2 { other_data.extend_from_slice(b"Extra"); state.update(b"Extra").unwrap(); } if data.len() > self.blocksize * 3 { other_data.extend_from_slice(&[0u8; 256]); state.update(&[0u8; 256]).unwrap(); } let streaming_result = state.finalize().unwrap(); let one_shot_result = T::one_shot(&other_data).unwrap(); assert_eq!(streaming_result, one_shot_result); } } fn incremental_and_one_shot(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let streaming_result = state.finalize().unwrap(); let one_shot_result = T::one_shot(data).unwrap(); assert_eq!(streaming_result, one_shot_result); } fn double_finalize_with_reset_no_update_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.finalize().is_ok()); } fn double_finalize_with_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); state.update(data).unwrap(); assert!(state.finalize().is_ok()); } fn double_finalize_err(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); assert!(state.finalize().is_err()); } fn update_after_finalize_with_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.update(data).is_ok()); } fn update_after_finalize_err(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); assert!(state.update(data).is_err()); } fn double_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.reset().is_ok()); } fn immediate_finalize(&self) { let mut state = self._initial_context.clone(); assert!(state.finalize().is_ok()); } pub fn verify_same_input_ok(data: &[u8]) { let expected = T::one_shot(data).unwrap(); assert!(T::verify_result(&expected, data).is_ok()); } pub fn verify_diff_input_err(data: &[u8]) { let expected = T::one_shot(data).unwrap(); assert!(T::verify_result(&expected, b"Bad data").is_err()); } }
use crate::errors::UnknownCryptoError; use core::marker::PhantomData; pub trait TestableStreamingContext<T: PartialEq> { fn reset(&mut self) -> Result<(), UnknownCryptoError>; fn update(&mut self, input: &[u8]) -> Result<(), UnknownCryptoError>; fn finalize(&mut self) -> Result<T, UnknownCryptoError>; fn one_shot(input: &[u8]) -> Result<T, UnknownCryptoError>; fn verify_result(expected: &T, input: &[u8]) -> Result<(), UnknownCryptoError>; fn compare_states(state_1: &Self, state_2: &Self); } #[allow(dead_code)] pub struct StreamingContextConsistencyTester<R, T> { _return_type: PhantomData<R>, _initial_context: T, blocksize: usize, } impl<R, T> StreamingContextConsistencyTester<R, T> where R: PartialEq + core::fmt::Debug, T: TestableStreamingContext<R> + Clone, { pub fn new(streaming_context: T, blocksize: usize) -> Self { Self { _return_type: PhantomData, _initial_context: streaming_context, blocksize, } } const DEFAULT_INPUT: [u8; 37] = [255u8; 37]; #[cfg(feature = "safe_api")] pub fn run_all_tests_property(&self, data: &[u8]) { self.consistency(data); self.consistency(&[0u8; 0]); self.produces_same_state(data); self.incremental_and_one_shot(data); self.double_finalize_with_reset_no_update_ok(data); self.double_finalize_with_reset_ok(data); self.double_finalize_err(data); self.update_after_finalize_with_reset_ok(data); self.update_after_finalize_err(data); self.double_reset_ok(data); self.immediate_finalize(); Self::verify_same_input_ok(data); Self::verify_diff_input_err(data); } #[cfg(feature = "safe_api")] pub fn run_all_tests(&self) { self.consistency(&Self::DEFAULT_INPUT); self.consistency(&[0u8; 0]); self.produces_same_state(&Self::DEFAULT_INPUT); self.incremental_processing_with_leftover(); self.incremental_and_one_shot(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_no_update_ok(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.double_finalize_err(&Self::DEFAULT_INPUT); self.update_after_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.update_after_finalize_err(&Self::DEFAULT_INPUT); self.double_reset_ok(&Self::DEFAULT_INPUT); self.immediate_finalize(); Self::verify_same_input_ok(&Self::DEFAULT_INPUT); Self::verify_diff_input_err(&Self::DEFAULT_INPUT); } #[cfg(not(feature = "safe_api"))] pub fn run_all_tests(&self) { self.consistency(&Self::DEFAULT_INPUT); self.consistency(&[0u8; 0]); self.produces_same_state(&Self::DEFAULT_INPUT); self.incremental_and_one_shot(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_no_update_ok(&Self::DEFAULT_INPUT); self.double_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.double_finalize_err(&Self::DEFAULT_INPUT); self.update_after_finalize_with_reset_ok(&Self::DEFAULT_INPUT); self.update_after_finalize_err(&Self::DEFAULT_INPUT); self.double_reset_ok(&Self::DEFAULT_INPUT); self.immediate_finalize(); Self::verify_same_input_ok(&Self::DEFAULT_INPUT); Self::verify_diff_input_err(&Self::DEFAULT_INPUT); } fn consistency(&self, data: &[u8]) { let mut state_1 = self._initial_context.clone(); state_1.update(data).unwrap(); let res_1 = state_1.finalize().unwrap(); let mut state_2 = self._initial_context.clone(); state_2.reset().unwrap(); state_2.update(data).unwrap(); let res_2 = state_2.finalize().unwrap(); let mut state_3 = self._initial_context.clone(); state_3.update(data).unwrap(); state_3.reset().unwrap(); state_3.update(data).unwrap(); let res_3 = state_3.finalize().unwrap(); let mut state_4 = self._initial_context.clone(); state_4.update(data).unwrap(); let _ = state_4.finalize().unwrap(); state_4.reset().unwrap(); state_4.update(data).unwrap(); let res_4 = state_4.finalize().unwrap(); assert_eq!(res_1, res_2); assert_eq!(res_2, res_3); assert_eq!(res_3, res_4); if data.is_empty() { let mut state_5 = self._initial_context.clone(); let res_5 = state_5.finalize().unwrap(); let mut state_6 = self._initial_context.clone(); state_6.reset().unwrap(); let res_6 = state_6.finalize().unwrap(); let mut state_7 = self._initial_context.clone(); state_7.update(b"WRONG DATA").unwrap(); state_7.reset().unwrap(); let res_7 = state_7.finalize().unwrap(); assert_eq!(res_4, res_5); assert_eq!(res_5, res_6); assert_eq!(res_6, res_7); } } fn produces_same_state(&self, data: &[u8]) { let state_1 = self._initial_context.clone(); let mut state_2 = self._initial_context.clone(); state_2.reset().unwrap(); let mut state_3 = self._initial_context.clone(); state_3.update(data).unwrap(); state_3.reset().unwrap(); let mut state_4 = self._initial_context.clone(); state_4.update(data).unwrap(); let _ = state_4.finalize().unwrap(); state_4.reset().unwrap(); T::compare_states(&state_1, &state_2); T::compare_states(&state_2, &state_3); T::compare_states(&state_3, &state_4); } #[cfg(feature = "safe_api")] fn incremental_processing_with_leftover(&self) { for len in 0..self.blocksize * 4 { let data = vec![0u8; len]; let mut state = self._initial_context.clone(); let mut other_data: Vec<u8> = Vec::new(); other_data.extend_from_slice(&data); state.update(&data).unwrap(); if data.len() > self.blocksize { other_data.extend_from_slice(b""); state.update(b"").unwrap(); } if data.len() > self.blocksize * 2 { other_data.extend_from_slice(b"Extra"); state.update(b"Extra").unwrap(); } if data.len() > self.blocksize * 3 { other_data.extend_from_slice(&[0u8; 256]); state.update(&[0u8; 256]).unwrap(); } let streaming_result = state.finalize().unwrap(); let one_shot_result = T::one_shot(&other_data).unwrap(); assert_eq!(streaming_result, one_shot_result); } } fn incremental_and_one_shot(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let streaming_result = state.finalize().unwrap(); let one_shot_result = T::one_shot(data).unwrap(); assert_eq!(streaming_result, one_shot_result); } fn double_finalize_with_reset_no_update_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.finalize().is_ok()); } fn double_finalize_with_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); state.update(data).unwrap(); assert!(state.finalize().is_ok()); } fn double_finalize_err(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); assert!(state.finalize().is_err()); }
fn update_after_finalize_err(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); assert!(state.update(data).is_err()); } fn double_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.reset().is_ok()); } fn immediate_finalize(&self) { let mut state = self._initial_context.clone(); assert!(state.finalize().is_ok()); } pub fn verify_same_input_ok(data: &[u8]) { let expected = T::one_shot(data).unwrap(); assert!(T::verify_result(&expected, data).is_ok()); } pub fn verify_diff_input_err(data: &[u8]) { let expected = T::one_shot(data).unwrap(); assert!(T::verify_result(&expected, b"Bad data").is_err()); } }
fn update_after_finalize_with_reset_ok(&self, data: &[u8]) { let mut state = self._initial_context.clone(); state.update(data).unwrap(); let _ = state.finalize().unwrap(); state.reset().unwrap(); assert!(state.update(data).is_ok()); }
function_block-full_function
[ { "content": "/// H' as defined in the specification.\n\nfn extended_hash(input: &[u8], dst: &mut [u8]) -> Result<(), UnknownCryptoError> {\n\n if dst.is_empty() {\n\n return Err(UnknownCryptoError);\n\n }\n\n\n\n let outlen = dst.len() as u32;\n\n\n\n if dst.len() <= BLAKE2B_OUTSIZE {\n\n ...
Rust
examples/example1.rs
evetion/startin
88ad5557cbd954ec8996f99d9afb74fd1ec174ec
#![allow(dead_code)] extern crate csv; extern crate serde; extern crate startin; #[macro_use] extern crate serde_derive; use std::error::Error; use std::io; #[derive(Debug, Deserialize)] pub struct CSVPoint { pub x: f64, pub y: f64, pub z: f64, } fn main() { let re = read_xyz_file(); let vec = match re { Ok(vec) => vec, Err(error) => panic!("Problem with the file {:?}", error), }; let mut dt = startin::Triangulation::new(); dt.set_jump_and_walk(false); dt.use_robust_predicates(true); let mut duplicates = 0; for p in vec.into_iter() { let re = dt.insert_one_pt(p.x, p.y, p.z); match re { Ok(_x) => continue, Err(_e) => duplicates = duplicates + 1, }; } if duplicates > 0 { println!("Duplicates? {} of them.\n", duplicates); } else { println!("Duplicates? none.\n"); } println!("{}", dt); let pts = dt.all_vertices(); println!("Size pts: {}", pts.len()); println!("Vertex CH: {}", dt.is_vertex_convex_hull(0)); let re = dt.adjacent_vertices_to_vertex(66); if re.is_some() == true { for each in re.unwrap() { println!("Adjacent vertex {}", each); } } else { println!("Vertex does not exists."); } let trs = dt.incident_triangles_to_vertex(6).unwrap(); let re = dt.adjacent_triangles_to_triangle(&trs[0]); if re.is_some() == true { println!("Adjacent to: {}", &trs[0]); for tr in re.unwrap().iter() { println!("adj: {}", tr); } } let pathout = "/Users/hugo/temp/out.obj"; println!("Writing OBJ file..."); let re = dt.write_obj(pathout.to_string(), false); match re { Ok(_x) => println!("--> OBJ output saved to: {}", pathout), Err(_x) => println!("ERROR: path {} doesn't exist, abort.", pathout), } } fn read_xyz_file() -> Result<Vec<CSVPoint>, Box<dyn Error>> { let mut rdr = csv::ReaderBuilder::new() .delimiter(b' ') .from_reader(io::stdin()); let mut vpts: Vec<CSVPoint> = Vec::new(); for result in rdr.deserialize() { let record: CSVPoint = result?; vpts.push(record); } Ok(vpts) }
#![allow(dead_code)] extern crate csv; extern crate serde; extern crate startin; #[macro_use] extern crate serde_derive; use std::error::Error; use std::io; #[derive(Debug, Deserialize)] pub struct CSVPoint { pub x: f64, pub y: f64, pub z: f64, } fn main() { let re = read_xyz_file(); let vec = match re { Ok(vec) => vec, Err(error) => panic!("Problem with the file {:?}", error), }; let mut dt = startin::Triangulation::new(); dt.set_jump_and_walk(false); dt.use_robust_predicates(true); let mut duplicates = 0; for p in vec.into_iter() { let re = dt.insert_one_pt(p.x, p.y, p.z); match re { Ok(_x) => continue, Err(_e) => duplicates = duplicates + 1, }; } if duplicates > 0 { println!("Duplicates? {} of them.\n", duplicates); } else { println!("Duplicates? none.\n"); } println!("{}", dt); let pts = dt.all_vertices(); println!("Size pts: {}", pts.len()); println!("Vertex CH: {}", dt.is_vertex_convex_hull(0)); let re = dt.adja
fn read_xyz_file() -> Result<Vec<CSVPoint>, Box<dyn Error>> { let mut rdr = csv::ReaderBuilder::new() .delimiter(b' ') .from_reader(io::stdin()); let mut vpts: Vec<CSVPoint> = Vec::new(); for result in rdr.deserialize() { let record: CSVPoint = result?; vpts.push(record); } Ok(vpts) }
cent_vertices_to_vertex(66); if re.is_some() == true { for each in re.unwrap() { println!("Adjacent vertex {}", each); } } else { println!("Vertex does not exists."); } let trs = dt.incident_triangles_to_vertex(6).unwrap(); let re = dt.adjacent_triangles_to_triangle(&trs[0]); if re.is_some() == true { println!("Adjacent to: {}", &trs[0]); for tr in re.unwrap().iter() { println!("adj: {}", tr); } } let pathout = "/Users/hugo/temp/out.obj"; println!("Writing OBJ file..."); let re = dt.write_obj(pathout.to_string(), false); match re { Ok(_x) => println!("--> OBJ output saved to: {}", pathout), Err(_x) => println!("ERROR: path {} doesn't exist, abort.", pathout), } }
function_block-function_prefixed
[ { "content": "fn read_xyz_file() -> Vec<Vec<f64>> {\n\n let tmpf = File::open(\"/Users/hugo/Dropbox/data/ahn3/o3.txt\").unwrap();\n\n // let tmpf = File::open(\"/Users/hugo/Dropbox/data/ahn3/test.txt\").unwrap();\n\n let file = BufReader::new(&tmpf);\n\n\n\n let mut pts: Vec<Vec<f64>> = Vec::new();\...
Rust
src/input/json.rs
PassFort/rouille
c3f06096afab039b88076d3d613f9a29e7a5f1dd
use serde; use serde_json; use serde_json::Value; use std::error; use std::fmt; use std::io::Error as IoError; use Request; #[derive(Debug)] pub enum JsonError { BodyAlreadyExtracted, WrongContentType, NullPresent, IoError(IoError), ParseError(serde_json::Error), } impl From<IoError> for JsonError { fn from(err: IoError) -> JsonError { JsonError::IoError(err) } } impl From<serde_json::Error> for JsonError { fn from(err: serde_json::Error) -> JsonError { JsonError::ParseError(err) } } impl error::Error for JsonError { #[inline] fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { JsonError::IoError(ref e) => Some(e), JsonError::ParseError(ref e) => Some(e), _ => None, } } } impl fmt::Display for JsonError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { let description = match *self { JsonError::BodyAlreadyExtracted => "the body of the request was already extracted", JsonError::WrongContentType => "the request didn't have a JSON content type", JsonError::NullPresent => "the JSON body contained an escaped null byte", JsonError::IoError(_) => { "could not read the body from the request, or could not execute the CGI program" } JsonError::ParseError(_) => "error while parsing the JSON body", }; write!(fmt, "{}", description) } } fn check_null(value: &Value) -> Result<&Value, JsonError> { match &value { Value::String(s) => { if s.find("\0").is_some() { return Err(JsonError::NullPresent); } } Value::Array(a) => { for element in a { check_null(element)?; } } Value::Object(o) => { for (k, v) in o { if k.find("\0").is_some() { return Err(JsonError::NullPresent); } check_null(v)?; } } _ => (), }; Ok(value) } pub fn json_input<O>(request: &Request) -> Result<O, JsonError> where O: serde::de::DeserializeOwned, { if let Some(header) = request.header("Content-Type") { if !header.starts_with("application/json") { return Err(JsonError::WrongContentType); } } else { return Err(JsonError::WrongContentType); } if let Some(b) = request.data() { let v: Value = serde_json::from_reader(b)?; check_null(&v)?; serde_json::from_value::<O>(v).map_err(From::from) } else { Err(JsonError::BodyAlreadyExtracted) } } #[cfg(test)] mod test { use super::*; #[test] fn test_check_nulls() { let data = r#" { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ], "children": [ { "name": "Sarah\u0000" }, { "name": "Bill\u0000" } ] }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_err()); } #[test] fn test_key_nulls() { let data = r#" { "name\u0000": "John Doe", "age": 43 }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_err()); } #[test] fn test_check_not_null() { let data = r#" { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ], "children": [ { "name": "Sarah" }, { "name": "Bill" } ] }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_ok()); } }
use serde; use serde_json; use serde_json::Value; use std::error; use std::fmt; use std::io::Error as IoError; use Request; #[derive(Debug)] pub enum JsonError { BodyAlreadyExtracted, WrongContentType, NullPresent, IoError(IoError), ParseError(serde_json::Error), } impl From<IoError> for JsonError { fn from(err: IoError) -> JsonError { JsonError::IoError(err) } } impl From<serde_json::Error> for JsonError { fn from(err: serde_json::Error) -> JsonError { JsonError::ParseError(err) } } impl error::Error for JsonError { #[inline] fn source(&self) -> Option<&(dyn error::Error + 'static)> { match *self { JsonError::IoError(ref e) => Some(e), JsonError::ParseError(ref e) => Some(e), _ => None, } } } impl fmt::Display for JsonError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { let description = match *self { JsonError::BodyAlreadyExtracted => "the body of the request was already extracted", JsonError::WrongContentType => "the request didn't have a JSON content type", JsonError::NullPresent => "the JSON body contained an escaped null byte", JsonError::IoError(_) => { "could not read the body from the request, or could not execute the CGI program" } JsonError::ParseError(_) => "error while parsing the JSON body", }; write!(fmt, "{}", description) } } fn check_null(value: &Value) -> Result<&Value, JsonError> { match &value { Value::String(
pub fn json_input<O>(request: &Request) -> Result<O, JsonError> where O: serde::de::DeserializeOwned, { if let Some(header) = request.header("Content-Type") { if !header.starts_with("application/json") { return Err(JsonError::WrongContentType); } } else { return Err(JsonError::WrongContentType); } if let Some(b) = request.data() { let v: Value = serde_json::from_reader(b)?; check_null(&v)?; serde_json::from_value::<O>(v).map_err(From::from) } else { Err(JsonError::BodyAlreadyExtracted) } } #[cfg(test)] mod test { use super::*; #[test] fn test_check_nulls() { let data = r#" { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ], "children": [ { "name": "Sarah\u0000" }, { "name": "Bill\u0000" } ] }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_err()); } #[test] fn test_key_nulls() { let data = r#" { "name\u0000": "John Doe", "age": 43 }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_err()); } #[test] fn test_check_not_null() { let data = r#" { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ], "children": [ { "name": "Sarah" }, { "name": "Bill" } ] }"#; let v: Value = serde_json::from_str(data).unwrap(); assert!(check_null(&v).is_ok()); } }
s) => { if s.find("\0").is_some() { return Err(JsonError::NullPresent); } } Value::Array(a) => { for element in a { check_null(element)?; } } Value::Object(o) => { for (k, v) in o { if k.find("\0").is_some() { return Err(JsonError::NullPresent); } check_null(v)?; } } _ => (), }; Ok(value) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn plain_text_body(request: &Request) -> Result<String, PlainTextError> {\n\n plain_text_body_with_limit(request, 1024 * 1024)\n\n}\n\n\n", "file_path": "src/input/plain.rs", "rank": 2, "score": 213355.85341939444 }, { "content": "/// Applies content encodin...
Rust
src/commands/commands/math.rs
Chronophylos/chb4
8754dbeb16eb36b79118f676fbf1897b582d67ed
use super::prelude::*; use evalexpr::*; use std::f64::consts; static PHI: f64 = 1.61803398874989484820; pub fn command() -> Arc<Command> { Command::with_name("math") .alias("quickmafs") .command(move |_context, args, _msg, _user| { let context = context_map! { "e" => consts::E, "π" => consts::PI, "pi" => consts::PI, "phi" => PHI, "φ" => PHI, "sqrt" => Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Float((int as f64).sqrt())) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.sqrt())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "abs" => Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int.abs())) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.abs())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "floor"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.floor())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "ceil"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.ceil())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "round"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.round())) } else { Err(EvalexprError::expected_number(argument.clone())) } })) } .unwrap(); let expr = args.join(" "); Ok(match eval_with_context(&expr, &context) { Ok(s) => MessageResult::Message(format!("{}", s)), Err(err) => MessageResult::Error(err.to_string()), }) }) .about("Do some math") .description( " This command uses the `evalexpr` crate. This crate allows the definition of constants and functions. .Constants |=== | Name | Value | Description | e | 2.71828182845904523536028747135266250f64 | Euler's number (e) | pi, π | 3.14159265358979323846264338327950288f64 | Archimedes' constant (π) |=== .Functions |=== | Name | Description | sqrt(x) | Square root of x | abs(x) | Absolute value of x | floor(x) | Returns the largest integer less than or equal to a number. | ceil(x) | Returns the smallest integer greater than or equal to a number. | round(x) | Returns the nearest integer to a number. Round half-way cases away from `0.0`. |=== ==== USAGE ``` math <expr> ``` Where <expr> is a valid mathematical expression. ", ) .done() }
use super::prelude::*; use evalexpr::*; use std::f64::consts; static PHI: f64 = 1.61803398874989484820; pub fn command() -> Arc<Command> { Command::with_name("math") .alias("quickmafs") .command(move |_context, args, _msg, _user| { let context = context_map! { "e" => consts::E, "π" => consts::PI, "pi" => consts::PI, "phi" => PHI, "φ" => PHI, "sqrt" => Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Float((int as f64).sqrt())) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.sqrt())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "abs" => Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int.abs())) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.abs())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "floor"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.floor())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "ceil"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.ceil())) } else { Err(EvalexprError::expected_number(argument.clone())) } })), "round"=> Function::new(Box::new(|argument| { if let Ok(int) = argument.as_int() { Ok(Value::Int(int)) } else if let Ok(float) = argument.as_float() { Ok(Value::Float(float.round())) } else { Err(EvalexprError::expected_number(argument.clone())) } })) } .unwrap(); let expr = args.join(" ");
}) .about("Do some math") .description( " This command uses the `evalexpr` crate. This crate allows the definition of constants and functions. .Constants |=== | Name | Value | Description | e | 2.71828182845904523536028747135266250f64 | Euler's number (e) | pi, π | 3.14159265358979323846264338327950288f64 | Archimedes' constant (π) |=== .Functions |=== | Name | Description | sqrt(x) | Square root of x | abs(x) | Absolute value of x | floor(x) | Returns the largest integer less than or equal to a number. | ceil(x) | Returns the smallest integer greater than or equal to a number. | round(x) | Returns the nearest integer to a number. Round half-way cases away from `0.0`. |=== ==== USAGE ``` math <expr> ``` Where <expr> is a valid mathematical expression. ", ) .done() }
Ok(match eval_with_context(&expr, &context) { Ok(s) => MessageResult::Message(format!("{}", s)), Err(err) => MessageResult::Error(err.to_string()), })
call_expression
[ { "content": "pub fn command() -> Arc<Command> {\n\n Command::with_name(\"system\")\n\n .alias(\"sysstat\")\n\n .command(|context, _args, _msg, _user| {\n\n let sys = System::new();\n\n\n\n let (mem_proc, mem_used, mem_total) =\n\n mem(&sys).context(\"Could ...
Rust
src/layout/gpos1.rs
daltonmaag/fonttools-rs
f6bbfa93cfb0b963432b87b30e4f5dfdfe9db923
use crate::layout::coverage::Coverage; use crate::layout::valuerecord::{coerce_to_same_format, ValueRecord, ValueRecordFlags}; use crate::utils::is_all_the_same; use otspec::types::*; use otspec::Serialize; use otspec::{DeserializationError, Deserialize, Deserializer, ReaderContext, SerializationError}; use otspec_macros::Serialize; use std::collections::BTreeMap; #[derive(Debug, PartialEq, Clone, Serialize)] #[allow(missing_docs, non_snake_case, non_camel_case_types)] pub struct SinglePosFormat1 { #[serde(offset_base)] pub posFormat: uint16, pub coverage: Offset16<Coverage>, pub valueFormat: ValueRecordFlags, pub valueRecord: ValueRecord, } #[derive(Debug, PartialEq, Clone, Serialize)] #[allow(missing_docs, non_snake_case, non_camel_case_types)] pub struct SinglePosFormat2 { #[serde(offset_base)] pub posFormat: uint16, pub coverage: Offset16<Coverage>, pub valueFormat: ValueRecordFlags, #[serde(with = "Counted")] pub valueRecords: Vec<ValueRecord>, } #[derive(Debug, Clone, PartialEq)] pub enum SinglePosInternal { Format1(SinglePosFormat1), Format2(SinglePosFormat2), } impl Serialize for SinglePosInternal { fn to_bytes(&self, data: &mut Vec<u8>) -> Result<(), SerializationError> { match self { SinglePosInternal::Format1(s) => s.to_bytes(data), SinglePosInternal::Format2(s) => s.to_bytes(data), } } } #[derive(Debug, PartialEq, Clone)] pub struct SinglePos { pub mapping: BTreeMap<uint16, ValueRecord>, } impl Deserialize for SinglePos { fn from_bytes(c: &mut ReaderContext) -> Result<Self, DeserializationError> { let mut mapping = BTreeMap::new(); let format: uint16 = c.de()?; let coverage: Offset16<Coverage> = c.de()?; let value_format: ValueRecordFlags = c.de()?; match format { 1 => { let mut vr: ValueRecord = ValueRecord::from_bytes(c, value_format)?; vr.simplify(); for glyph_id in &coverage.as_ref().unwrap().glyphs { mapping.insert(*glyph_id, vr); } } 2 => { let _count: uint16 = c.de()?; for glyph_id in coverage.as_ref().unwrap().glyphs.iter() { let mut vr: ValueRecord = ValueRecord::from_bytes(c, value_format)?; vr.simplify(); mapping.insert(*glyph_id, vr); } } _ => panic!("Bad single pos format {:?}", format), } Ok(SinglePos { mapping }) } } impl From<&SinglePos> for SinglePosInternal { fn from(val: &SinglePos) -> Self { let mut mapping = val.mapping.clone(); for (_, val) in mapping.iter_mut() { (*val).simplify() } let coverage = Coverage { glyphs: mapping.keys().copied().collect(), }; if is_all_the_same(mapping.values()) { let vr = mapping.values().next().unwrap(); SinglePosInternal::Format1(SinglePosFormat1 { posFormat: 1, coverage: Offset16::to(coverage), valueFormat: vr.flags(), valueRecord: *vr, }) } else { let vrs: Vec<ValueRecord> = mapping.values().copied().collect(); let vrs = coerce_to_same_format(vrs); SinglePosInternal::Format2(SinglePosFormat2 { posFormat: 2, coverage: Offset16::to(coverage), valueFormat: vrs[0].flags(), valueRecords: vrs, }) } } } impl Serialize for SinglePos { fn to_bytes(&self, data: &mut Vec<u8>) -> Result<(), SerializationError> { let ssi: SinglePosInternal = self.into(); ssi.to_bytes(data) } } #[cfg(test)] mod tests { use super::*; use crate::{btreemap, valuerecord}; use std::iter::FromIterator; #[test] fn test_single_pos_1_1_serde() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10)), }; let binary_pos = vec![ 0x00, 0x01, 0x00, 0x08, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x01, 0x00, 66, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); } #[test] fn test_single_pos_1_1_serde2() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=10, yPlacement=0), ), }; let binary_pos = vec![ 0x00, 0x01, 0x00, 0x08, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!( de, SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=10), ), } ); } #[test] fn test_single_pos_1_2_serde() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=-20), ), }; let binary_pos = vec![ 0x00, 0x02, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x02, 0x00, 0x0a, 0xff, 0xec, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); } #[test] fn test_single_pos_1_2_serde2() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xPlacement=-20), ), }; let binary_pos = vec![ 0x00, 0x02, 0x00, 0x10, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0a, 0xff, 0xec, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); } }
use crate::layout::coverage::Coverage; use crate::layout::valuerecord::{coerce_to_same_format, ValueRecord, ValueRecordFlags}; use crate::utils::is_all_the_same; use otspec::types::*; use otspec::Serialize; use otspec::{DeserializationError, Deserialize, Deserializer, ReaderContext, SerializationError}; use otspec_macros::Serialize; use std::collections::BTreeMap; #[derive(Debug, PartialEq, Clone, Serialize)] #[allow(missing_docs, non_snake_case, non_camel_case_types)] pub struct SinglePosFormat1 { #[serde(offset_base)] pub posFormat: uint16, pub coverage: Offset16<Coverage>, pub valueFormat: ValueRecordFlags, pub valueRecord: ValueRecord, } #[derive(Debug, PartialEq, Clone, Serialize)] #[allow(missing_docs, non_snake_case, non_camel_case_types)] pub struct SinglePosFormat2 { #[serde(offset_base)] pub posFormat: uint16, pub coverage: Offset16<Coverage>, pub valueFormat: ValueRecordFlags, #[serde(with = "Counted")] pub valueRecords: Vec<ValueRecord>, } #[derive(Debug, Clone, PartialEq)] pub enum SinglePosInternal { Format1(SinglePosFormat1), Format2(SinglePosFormat2), } impl Serialize for SinglePosInternal { fn to_bytes(&self, data: &mut Vec<u8>) -> Result<(), SerializationError> { match self { SinglePosInternal::Format1(s) => s.to_bytes(data), SinglePosInternal::Format2(s) => s.to_bytes(data), } } } #[derive(Debug, PartialEq, Clone)] pub struct SinglePos { pub mapping: BTreeMap<uint16, ValueRecord>, } impl Deserialize for SinglePos { fn from_bytes(c: &mut ReaderContext) -> Result<Self, DeserializationError> { let mut mapping = BTreeMap::new(); let format: uint16 = c.de()?; let coverage: Offset16<Coverage> = c.de()?; let value_format: ValueRecordFlags = c.de()?; match format { 1 => { let mut vr: ValueRecord = ValueRecord::from_bytes(c, value_format)?; vr.simplify(); for glyph_id in &coverage.as_ref().unwrap().glyphs { mapping.insert(*glyph_id, vr); } } 2 => { let _count: uint16 = c.de()?; for glyph_id in coverage.as_ref().unwrap().glyphs.iter() { let mut vr: ValueRecord = ValueRecord::from_bytes(c, value_format)?; vr.simplify(); mapping.insert(*glyph_id, vr); } } _ => panic!("Bad single pos format {:?}", format), } Ok(SinglePos { mapping }) } } impl From<&SinglePos> for SinglePosInternal { fn from(val: &SinglePos) -> Self { let mut mapping = val.mapping.clone(); for (_, val) in mapping.iter_mut() { (*val).simplify() } let coverage = Coverage { glyphs: mapping.keys().copied().collect(), }; if is_all_the_same(mapping.values()) { let vr = mapping.values().next().unwrap(); SinglePosInternal::Format1(SinglePosFormat1 { posFormat: 1, coverage: Offset16::to(coverage), valueFormat: vr.flags(), valueRecord: *vr, }) } else { let vrs: Vec<ValueRecord> = mapping.values().copied().collect(); let vrs = coerce_to_same_format(vrs); SinglePosInternal::Format2(SinglePosFormat2 { posFormat: 2, coverage: Offset16::to(coverage), valueFormat: vrs[0].flags(), valueRecords: vrs, }) } } } impl Serialize for SinglePos { fn to_bytes(&self, data: &mut Vec<u8>) -> Result<(), SerializationError> { let ssi: SinglePosInternal = self.into(); ssi.to_bytes(data) } } #[cfg(test)] mod tests { use super::*; use crate::{btreemap, valuerecord}; use std::iter::FromIterator; #[test] fn test_single_pos_1_1_serde() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10)), }; let binary_pos = vec![ 0x00, 0x01, 0x00, 0x08, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x01, 0x00, 66, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); } #[test] fn test_single_pos_1_1_serde2() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=10, yPlacement=0), ), }; let binary_pos = vec![ 0x00, 0x01, 0x00, 0x08, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!( de, SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=10), ), } ); } #[test] fn test_single_pos_1_2_serde() { let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xAdvance=-20), ), }; let binary_pos = vec![ 0x00, 0x02, 0x00, 0x0c, 0x00, 0x04, 0x00, 0x02, 0x00, 0x0a, 0xff, 0xec, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); } #[test] fn test_single_pos_1_2_serde2() {
}
let pos = SinglePos { mapping: btreemap!(66 => valuerecord!(xAdvance=10), 67 => valuerecord!(xPlacement=-20), ), }; let binary_pos = vec![ 0x00, 0x02, 0x00, 0x10, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0a, 0xff, 0xec, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 66, 0x00, 67, ]; let serialized = otspec::ser::to_bytes(&pos).unwrap(); assert_eq!(serialized, binary_pos); let de: SinglePos = otspec::de::from_bytes(&binary_pos).unwrap(); assert_eq!(de, pos); }
function_block-function_prefix_line
[ { "content": "fn consecutive_slices(data: &[uint16]) -> Vec<&[uint16]> {\n\n let mut slice_start = 0;\n\n let mut result = Vec::new();\n\n for i in 1..data.len() {\n\n if data[i - 1] + 1 != data[i] {\n\n result.push(&data[slice_start..i]);\n\n slice_start = i;\n\n }\...
Rust
src/bytecode/src/loader.rs
ales-tsurko/koto
040c255d2170ac44e6743f6b381c7fb639e492a2
use { crate::{Chunk, Compiler, CompilerError, CompilerSettings}, koto_parser::{format_error_with_excerpt, Parser, ParserError}, std::{collections::HashMap, error, fmt, path::PathBuf, sync::Arc}, }; #[derive(Clone, Debug)] pub enum LoaderErrorType { ParserError(ParserError), CompilerError(CompilerError), IoError(String), } #[derive(Clone, Debug)] pub struct LoaderError { error: LoaderErrorType, source: String, source_path: Option<PathBuf>, } impl LoaderError { pub fn from_parser_error( error: ParserError, source: &str, source_path: Option<PathBuf>, ) -> Self { Self { error: LoaderErrorType::ParserError(error), source: source.into(), source_path, } } pub fn from_compiler_error( error: CompilerError, source: &str, source_path: Option<PathBuf>, ) -> Self { Self { error: LoaderErrorType::CompilerError(error), source: source.into(), source_path, } } pub fn io_error(error: String) -> Self { Self { error: LoaderErrorType::IoError(error), source: "".into(), source_path: None, } } pub fn is_indentation_error(&self) -> bool { match &self.error { LoaderErrorType::ParserError(e) => e.is_indentation_error(), _ => false, } } } impl fmt::Display for LoaderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use LoaderErrorType::*; if f.alternate() { match &self.error { ParserError(koto_parser::ParserError { error, .. }) => { f.write_str(&error.to_string()) } CompilerError(crate::CompilerError { message, .. }) => f.write_str(message), IoError(e) => f.write_str(&e), } } else { match &self.error { ParserError(koto_parser::ParserError { error, span }) => { f.write_str(&format_error_with_excerpt( Some(&error.to_string()), &self.source_path, &self.source, span.start, span.end, )) } CompilerError(crate::CompilerError { message, span }) => { f.write_str(&format_error_with_excerpt( Some(&message), &self.source_path, &self.source, span.start, span.end, )) } IoError(e) => f.write_str(&e), } } } } impl error::Error for LoaderError {} #[derive(Clone, Default)] pub struct Loader { chunks: HashMap<PathBuf, Arc<Chunk>>, } impl Loader { fn compile( &mut self, script: &str, script_path: Option<PathBuf>, compiler_settings: CompilerSettings, ) -> Result<Arc<Chunk>, LoaderError> { match Parser::parse(&script) { Ok((ast, constants)) => { let (bytes, mut debug_info) = match Compiler::compile(&ast, compiler_settings) { Ok((bytes, debug_info)) => (bytes, debug_info), Err(e) => return Err(LoaderError::from_compiler_error(e, script, script_path)), }; debug_info.source = script.to_string(); Ok(Arc::new(Chunk::new( bytes, constants, script_path, debug_info, ))) } Err(e) => Err(LoaderError::from_parser_error(e, script, script_path)), } } pub fn compile_repl(&mut self, script: &str) -> Result<Arc<Chunk>, LoaderError> { self.compile(script, None, CompilerSettings { repl_mode: true }) } pub fn compile_script( &mut self, script: &str, script_path: &Option<PathBuf>, ) -> Result<Arc<Chunk>, LoaderError> { self.compile(script, script_path.clone(), CompilerSettings::default()) } pub fn compile_module( &mut self, name: &str, load_from_path: Option<PathBuf>, ) -> Result<(Arc<Chunk>, PathBuf), LoaderError> { let path = match &load_from_path { Some(path) => match path.canonicalize() { Ok(canonicalized) if canonicalized.is_file() => match canonicalized.parent() { Some(parent_dir) => parent_dir.to_path_buf(), None => { return Err(LoaderError::io_error( "Failed to get parent of provided path".to_string(), )) } }, Ok(canonicalized) => canonicalized, Err(e) => return Err(LoaderError::io_error(e.to_string())), }, None => match std::env::current_dir() { Ok(path) => path, Err(e) => return Err(LoaderError::io_error(e.to_string())), }, }; let mut load_module_from_path = |module_path: PathBuf| match self.chunks.get(&module_path) { Some(chunk) => Ok((chunk.clone(), module_path.clone())), None => match std::fs::read_to_string(&module_path) { Ok(script) => { let chunk = self.compile( &script, Some(module_path.clone()), CompilerSettings::default(), )?; self.chunks.insert(module_path.clone(), chunk.clone()); Ok((chunk, module_path)) } Err(_) => Err(LoaderError::io_error(format!( "File not found: {}", module_path.to_string_lossy() ))), }, }; let extension = "koto"; let named_path = path.join(name); let module_path = named_path.with_extension(extension); if module_path.exists() { load_module_from_path(module_path) } else { let module_path = named_path.join("main").with_extension(extension); if module_path.exists() { load_module_from_path(module_path) } else { Err(LoaderError::io_error(format!( "Unable to find module '{}'", name ))) } } } }
use { crate::{Chunk, Compiler, CompilerError, CompilerSettings}, koto_parser::{format_error_with_excerpt, Parser, ParserError}, std::{collections::HashMap, error, fmt, path::PathBuf, sync::Arc}, }; #[derive(Clone, Debug)] pub enum LoaderErrorType { ParserError(ParserError), CompilerError(CompilerError), IoError(String), } #[derive(Clone, Debug)] pub struct LoaderError { error: LoaderErrorType, source: String, source_path: Option<PathBuf>, } impl LoaderError { pub fn from_parser_error( error: ParserError, source: &str, source_path: Option<PathBuf>, ) -> Self { Self { error: LoaderErrorType::ParserError(error), source: source.into(), source_path, } }
pub fn io_error(error: String) -> Self { Self { error: LoaderErrorType::IoError(error), source: "".into(), source_path: None, } } pub fn is_indentation_error(&self) -> bool { match &self.error { LoaderErrorType::ParserError(e) => e.is_indentation_error(), _ => false, } } } impl fmt::Display for LoaderError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use LoaderErrorType::*; if f.alternate() { match &self.error { ParserError(koto_parser::ParserError { error, .. }) => { f.write_str(&error.to_string()) } CompilerError(crate::CompilerError { message, .. }) => f.write_str(message), IoError(e) => f.write_str(&e), } } else { match &self.error { ParserError(koto_parser::ParserError { error, span }) => { f.write_str(&format_error_with_excerpt( Some(&error.to_string()), &self.source_path, &self.source, span.start, span.end, )) } CompilerError(crate::CompilerError { message, span }) => { f.write_str(&format_error_with_excerpt( Some(&message), &self.source_path, &self.source, span.start, span.end, )) } IoError(e) => f.write_str(&e), } } } } impl error::Error for LoaderError {} #[derive(Clone, Default)] pub struct Loader { chunks: HashMap<PathBuf, Arc<Chunk>>, } impl Loader { fn compile( &mut self, script: &str, script_path: Option<PathBuf>, compiler_settings: CompilerSettings, ) -> Result<Arc<Chunk>, LoaderError> { match Parser::parse(&script) { Ok((ast, constants)) => { let (bytes, mut debug_info) = match Compiler::compile(&ast, compiler_settings) { Ok((bytes, debug_info)) => (bytes, debug_info), Err(e) => return Err(LoaderError::from_compiler_error(e, script, script_path)), }; debug_info.source = script.to_string(); Ok(Arc::new(Chunk::new( bytes, constants, script_path, debug_info, ))) } Err(e) => Err(LoaderError::from_parser_error(e, script, script_path)), } } pub fn compile_repl(&mut self, script: &str) -> Result<Arc<Chunk>, LoaderError> { self.compile(script, None, CompilerSettings { repl_mode: true }) } pub fn compile_script( &mut self, script: &str, script_path: &Option<PathBuf>, ) -> Result<Arc<Chunk>, LoaderError> { self.compile(script, script_path.clone(), CompilerSettings::default()) } pub fn compile_module( &mut self, name: &str, load_from_path: Option<PathBuf>, ) -> Result<(Arc<Chunk>, PathBuf), LoaderError> { let path = match &load_from_path { Some(path) => match path.canonicalize() { Ok(canonicalized) if canonicalized.is_file() => match canonicalized.parent() { Some(parent_dir) => parent_dir.to_path_buf(), None => { return Err(LoaderError::io_error( "Failed to get parent of provided path".to_string(), )) } }, Ok(canonicalized) => canonicalized, Err(e) => return Err(LoaderError::io_error(e.to_string())), }, None => match std::env::current_dir() { Ok(path) => path, Err(e) => return Err(LoaderError::io_error(e.to_string())), }, }; let mut load_module_from_path = |module_path: PathBuf| match self.chunks.get(&module_path) { Some(chunk) => Ok((chunk.clone(), module_path.clone())), None => match std::fs::read_to_string(&module_path) { Ok(script) => { let chunk = self.compile( &script, Some(module_path.clone()), CompilerSettings::default(), )?; self.chunks.insert(module_path.clone(), chunk.clone()); Ok((chunk, module_path)) } Err(_) => Err(LoaderError::io_error(format!( "File not found: {}", module_path.to_string_lossy() ))), }, }; let extension = "koto"; let named_path = path.join(name); let module_path = named_path.with_extension(extension); if module_path.exists() { load_module_from_path(module_path) } else { let module_path = named_path.join("main").with_extension(extension); if module_path.exists() { load_module_from_path(module_path) } else { Err(LoaderError::io_error(format!( "Unable to find module '{}'", name ))) } } } }
pub fn from_compiler_error( error: CompilerError, source: &str, source_path: Option<PathBuf>, ) -> Self { Self { error: LoaderErrorType::CompilerError(error), source: source.into(), source_path, } }
function_block-full_function
[ { "content": "/// Returns a [String] displaying the annotated instructions contained in the compiled [Chunk]\n\npub fn chunk_to_string_annotated(chunk: Arc<Chunk>, source_lines: &[&str]) -> String {\n\n let mut result = String::new();\n\n let mut reader = InstructionReader::new(chunk);\n\n let mut ip =...
Rust
quic/s2n-quic-transport/src/transmission/application.rs
nsdyoshi/s2n-quic
0635e62cdc58fb968de0a0d576822e09c96cba99
use crate::{ ack::AckManager, connection, contexts::WriteContext, endpoint, path, path::mtu, recovery, space::{datagram, HandshakeStatus}, stream::{AbstractStreamManager, StreamTrait as Stream}, sync::{flag, flag::Ping}, transmission::{self, Mode}, }; use core::ops::RangeInclusive; use s2n_quic_core::packet::number::PacketNumberSpace; pub enum Payload<'a, Config: endpoint::Config> { Normal(Normal<'a, Config::Stream, Config>), MtuProbe(MtuProbe<'a>), PathValidationOnly(PathValidationOnly<'a, Config>), } impl<'a, Config: endpoint::Config> Payload<'a, Config> { #[allow(clippy::too_many_arguments)] pub fn new( path_id: path::Id, path_manager: &'a mut path::Manager<Config>, local_id_registry: &'a mut connection::LocalIdRegistry, transmission_mode: transmission::Mode, ack_manager: &'a mut AckManager, handshake_status: &'a mut HandshakeStatus, ping: &'a mut flag::Ping, stream_manager: &'a mut AbstractStreamManager<Config::Stream>, recovery_manager: &'a mut recovery::Manager<Config>, datagram_manager: &'a mut datagram::Manager<Config>, ) -> Self { if transmission_mode != Mode::PathValidationOnly { debug_assert_eq!(path_id, path_manager.active_path_id()); } match transmission_mode { Mode::LossRecoveryProbing | Mode::Normal => { transmission::application::Payload::Normal(Normal { ack_manager, handshake_status, ping, stream_manager, local_id_registry, path_manager, recovery_manager, datagram_manager, }) } Mode::MtuProbing => transmission::application::Payload::MtuProbe(MtuProbe { mtu_controller: &mut path_manager[path_id].mtu_controller, }), Mode::PathValidationOnly => { transmission::application::Payload::PathValidationOnly(PathValidationOnly { path: &mut path_manager[path_id], }) } } } } impl<'a, Config: endpoint::Config> super::Payload for Payload<'a, Config> { fn size_hint(&self, range: RangeInclusive<usize>) -> usize { (*range.start()).max(1) } fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { match self { Payload::Normal(inner) => inner.on_transmit(context), Payload::MtuProbe(inner) => inner.on_transmit(context), Payload::PathValidationOnly(inner) => inner.on_transmit(context), } } fn packet_number_space(&self) -> PacketNumberSpace { PacketNumberSpace::ApplicationData } } impl<'a, Config: endpoint::Config> transmission::interest::Provider for Payload<'a, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { match self { Payload::Normal(inner) => inner.transmission_interest(query), Payload::MtuProbe(inner) => inner.transmission_interest(query), Payload::PathValidationOnly(inner) => inner.transmission_interest(query), } } } pub struct Normal<'a, S: Stream, Config: endpoint::Config> { ack_manager: &'a mut AckManager, handshake_status: &'a mut HandshakeStatus, ping: &'a mut Ping, stream_manager: &'a mut AbstractStreamManager<S>, local_id_registry: &'a mut connection::LocalIdRegistry, path_manager: &'a mut path::Manager<Config>, recovery_manager: &'a mut recovery::Manager<Config>, datagram_manager: &'a mut datagram::Manager<Config>, } impl<'a, S: Stream, Config: endpoint::Config> Normal<'a, S, Config> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { let did_send_ack = self.ack_manager.on_transmit(context); if context.transmission_constraint().can_transmit() || context.transmission_constraint().can_retransmit() { self.handshake_status.on_transmit(context); self.path_manager.active_path_mut().on_transmit(context); self.local_id_registry.on_transmit(context); self.path_manager.on_transmit(context); self.datagram_manager .on_transmit(context, self.stream_manager); let _ = self.stream_manager.on_transmit(context); self.recovery_manager.on_transmit(context); let _ = self.ping.on_transmit(context); } if did_send_ack { self.ack_manager.on_transmit_complete(context); } } } impl<'a, S: Stream, Config: endpoint::Config> transmission::interest::Provider for Normal<'a, S, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.ack_manager.transmission_interest(query)?; self.handshake_status.transmission_interest(query)?; self.stream_manager.transmission_interest(query)?; self.datagram_manager.transmission_interest(query)?; self.local_id_registry.transmission_interest(query)?; self.path_manager.transmission_interest(query)?; self.recovery_manager.transmission_interest(query)?; self.path_manager .active_path() .transmission_interest(query)?; self.ping.transmission_interest(query)?; Ok(()) } } pub struct MtuProbe<'a> { mtu_controller: &'a mut mtu::Controller, } impl<'a> MtuProbe<'a> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { if context.transmission_constraint().can_transmit() { self.mtu_controller.on_transmit(context) } } } impl<'a> transmission::interest::Provider for MtuProbe<'a> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.mtu_controller.transmission_interest(query) } } pub struct PathValidationOnly<'a, Config: endpoint::Config> { path: &'a mut path::Path<Config>, } impl<'a, Config: endpoint::Config> PathValidationOnly<'a, Config> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { if context.transmission_constraint().can_transmit() { self.path.on_transmit(context) } } } impl<'a, Config: endpoint::Config> transmission::interest::Provider for PathValidationOnly<'a, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.path.transmission_interest(query) } }
use crate::{ ack::AckManager, connection, contexts::WriteContext, endpoint, path, path::mtu, recovery, space::{datagram, HandshakeStatus}, stream::{AbstractStreamManager, StreamTrait as Stream}, sync::{flag, flag::Ping}, transmission::{self, Mode}, }; use core::ops::RangeInclusive; use s2n_quic_core::packet::number::PacketNumberSpace; pub enum Payload<'a, Config: endpoint::Config> { Normal(Normal<'a, Config::Stream, Config>), MtuProbe(MtuProbe<'a>), PathValidationOnly(PathValidationOnly<'a, Config>), } impl<'a, Config: endpoint::Config> Payload<'a, Config> { #[allow(clippy::too_many_arguments)] pub fn new( path_id: path::Id, path_manager: &'a mut path::Manager<Config>, local_id_registry: &'a mut connection::LocalIdRegistry, transmission_mode: transmission::Mode, ack_manager: &'a mut AckManager, handshake_status: &'a mut HandshakeStatus, ping: &'a mut flag::Ping, stream_manager: &'a mut AbstractStreamManager<Config::Stream>, recovery_manager: &'a mut recovery::Manager<Config>, datagram_manager: &'a mut datagram::Manager<Config>, ) -> Self { if transmission_mode != Mode::PathValidationOnly { debug_assert_eq!(path_id, path_manager.active_path_id()); } match transmission_mode { Mode::LossRecoveryProbing | Mode::Normal => { transmission::application::Payload::Normal(Normal { ack_manager, handshake_status, ping, stream_manager, local_id_registry, path_manager, recovery_manager, datagram_manager, }) } Mode::MtuProbing => transmission::application::Payload::MtuProbe(MtuProbe { mtu_controller: &mut path_manager[path_id].mtu_controller, }), Mode::PathValidationOnly => { transmission::application::Payload::PathValidationOnly(PathValidationOnly { path: &mut path_manager[path_id], }) } } } } impl<'a, Config: endpoint::Config> super::Payload for Payload<'a, Config> { fn size_hint(&self, range: RangeInclusive<usize>) -> usize { (*range.start()).max(1) } fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { match self { Payload::Normal(inner) => inner.on_transmit(context), Payload::MtuProbe(inner) => inner.on_transmit(context), Payload::PathValidationOnly(inner) => inner.on_transmit(context), } } fn packet_number_space(&self) -> PacketNumberSpace { PacketNumberSpace::ApplicationData } } impl<'a, Config: endpoint::Config> transmission::interest::Provider for Payload<'a, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { match self { Payload::Normal(inner) => inner.transmission_interest(query), Payload::MtuProbe(inner) => inner.transmission_interest(query), Payload::PathValidationOnly(inner) => inner.transmission_interest(query), } } } pub struct Normal<'a, S: Stream, Config: endpoint::Config> { ack_manager: &'a mut AckManager, handshake_status: &'a mut HandshakeStatus, ping: &'a mut Ping, stream_manager: &'a mut AbstractStreamManager<S>, local_id_registry: &'a mut connection::LocalIdRegistry, path_manager: &'a mut path::Manager<Config>, recovery_manager: &'a mut recovery::Manager<Config>, datagram_manager: &'a mut datagram::Manager<Config>, } impl<'a, S: Stream, Config: endpoint::Config> Normal<'a, S, Config> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { let did_send_ack = self.ack_manager.on_transmit(context); if context.transmission_constraint().can_transmit() || context.transmission_constraint().can_retransmit() { self.handshake_status.on_transmit(context); self.path_manager.active_path_mut().on_transmit(context); self.local_id_registry.on_transmit(contex
} impl<'a, S: Stream, Config: endpoint::Config> transmission::interest::Provider for Normal<'a, S, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.ack_manager.transmission_interest(query)?; self.handshake_status.transmission_interest(query)?; self.stream_manager.transmission_interest(query)?; self.datagram_manager.transmission_interest(query)?; self.local_id_registry.transmission_interest(query)?; self.path_manager.transmission_interest(query)?; self.recovery_manager.transmission_interest(query)?; self.path_manager .active_path() .transmission_interest(query)?; self.ping.transmission_interest(query)?; Ok(()) } } pub struct MtuProbe<'a> { mtu_controller: &'a mut mtu::Controller, } impl<'a> MtuProbe<'a> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { if context.transmission_constraint().can_transmit() { self.mtu_controller.on_transmit(context) } } } impl<'a> transmission::interest::Provider for MtuProbe<'a> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.mtu_controller.transmission_interest(query) } } pub struct PathValidationOnly<'a, Config: endpoint::Config> { path: &'a mut path::Path<Config>, } impl<'a, Config: endpoint::Config> PathValidationOnly<'a, Config> { fn on_transmit<W: WriteContext>(&mut self, context: &mut W) { if context.transmission_constraint().can_transmit() { self.path.on_transmit(context) } } } impl<'a, Config: endpoint::Config> transmission::interest::Provider for PathValidationOnly<'a, Config> { fn transmission_interest<Q: transmission::interest::Query>( &self, query: &mut Q, ) -> transmission::interest::Result { self.path.transmission_interest(query) } }
t); self.path_manager.on_transmit(context); self.datagram_manager .on_transmit(context, self.stream_manager); let _ = self.stream_manager.on_transmit(context); self.recovery_manager.on_transmit(context); let _ = self.ping.on_transmit(context); } if did_send_ack { self.ack_manager.on_transmit_complete(context); } }
function_block-function_prefixed
[ { "content": "pub trait Context<Config: endpoint::Config> {\n\n const ENDPOINT_TYPE: endpoint::Type;\n\n\n\n fn is_handshake_confirmed(&self) -> bool;\n\n\n\n fn path(&self) -> &Path<Config>;\n\n\n\n fn path_mut(&mut self) -> &mut Path<Config>;\n\n\n\n fn path_by_id(&self, path_id: path::Id) -> &...
Rust
src/util.rs
anderejd/meshlite
2a3b1f06b0dae801b55b10ee8f78c11c9cee5ebb
use cgmath::Point3; use cgmath::Vector3; use cgmath::prelude::*; use cgmath::Deg; use cgmath::Rad; /* Range of the Dot Product of Two Unit Vectors Dot Angle 1.000 0 degrees 0.966 15 degrees 0.866 30 degrees 0.707 45 degrees 0.500 60 degrees 0.259 75 degrees 0.000 90 degrees -0.259 105 by degrees -0.500 120 degrees -0.707 135 degrees -0.866 150 degrees -0.966 165 degrees -1.000 180 degrees Source: http://chortle.ccsu.edu/vectorlessons/vch09/vch09_6.html */ pub fn norm(p1: Point3<f32>, p2: Point3<f32>, p3: Point3<f32>) -> Vector3<f32> { let side1 = p2 - p1; let side2 = p3 - p1; let perp = side1.cross(side2); perp.normalize() } pub fn almost_eq(v1: Vector3<f32>, v2: Vector3<f32>) -> bool { (v1.x - v2.x).abs() <= 0.01 && (v1.y - v2.y).abs() <= 0.01 && (v1.z - v2.z).abs() <= 0.01 } pub fn point_in_triangle(a: Point3<f32>, b: Point3<f32>, c: Point3<f32>, p: Point3<f32>) -> bool { let u = b - a; let v = c - a; let w = p - a; let v_cross_w = v.cross(w); let v_cross_u = v.cross(u); if v_cross_w.dot(v_cross_u) < 0.0 { return false; } let u_cross_w = u.cross(w); let u_cross_v = u.cross(v); if u_cross_w.dot(u_cross_v) < 0.0 { return false; } let denom = u_cross_v.magnitude(); let r = v_cross_w.magnitude() / denom; let t = u_cross_w.magnitude() / denom; r + t <= 1.0 } pub fn angle360(a: Vector3<f32>, b: Vector3<f32>, direct: Vector3<f32>) -> f32 { let angle = Rad::acos(a.dot(b)); let c = a.cross(b); if c.dot(direct) < 0.0 { 180.0 + Deg::from(angle).0 } else { Deg::from(angle).0 } } #[derive(PartialEq)] #[derive(Debug)] pub enum PointSide { Front, Back, Coincident } pub fn point_side_on_plane(pt: Point3<f32>, pt_on_plane: Point3<f32>, norm: Vector3<f32>) -> PointSide { let line = pt - pt_on_plane; let dot = line.dot(norm); if dot > 0.0 { PointSide::Front } else if dot < 0.0 { PointSide::Back } else { PointSide::Coincident } } #[derive(PartialEq)] #[derive(Debug)] pub enum SegmentPlaneIntersect { NoIntersection, Parallel, LiesIn, Intersection(Point3<f32>), } pub const SMALL_NUM : f32 = 0.00000001; pub fn intersect_of_segment_and_plane(p0: Point3<f32>, p1: Point3<f32>, pt_on_plane: Point3<f32>, norm: Vector3<f32>) -> SegmentPlaneIntersect { let u = p1 - p0; let w = p0 - pt_on_plane; let d = norm.dot(u); let n = -norm.dot(w); if d.abs() < SMALL_NUM { if n == 0.0 { return SegmentPlaneIntersect::LiesIn; } return SegmentPlaneIntersect::Parallel; } let s_i = n / d; if s_i < 0.0 || s_i > 1.0 || s_i.is_nan() || s_i.is_infinite() { return SegmentPlaneIntersect::NoIntersection; } SegmentPlaneIntersect::Intersection(p0 + (s_i * u)) } pub fn is_segment_and_quad_intersect(p0: Point3<f32>, p1: Point3<f32>, quad: &Vec<Point3<f32>>) -> bool { let r1 = p0; let r2 = p1; let s1 = quad[0]; let s2 = quad[1]; let s3 = quad[2]; let ds21 = s2 - s1; let ds31 = s3 - s1; let n = ds21.cross(ds31); let dr = r1 - r2; let ndotdr = n.dot(dr); if ndotdr.abs() < SMALL_NUM { return false; } let t = -n.dot(r1 - s1) / ndotdr; let m = r1 + (dr * t); let dms1 = m - s1; let u = dms1.dot(ds21); let v = dms1.dot(ds31); u >= 0.0 && u <= ds21.dot(ds21) && v >= 0.0 && v <= ds31.dot(ds31) } pub fn is_two_quads_intersect(first_quad: &Vec<Point3<f32>>, second_quad: &Vec<Point3<f32>>) -> bool { for i in 0..second_quad.len() { if is_segment_and_quad_intersect(second_quad[i], second_quad[(i + 1) % second_quad.len()], first_quad) { return true; } } for i in 0..first_quad.len() { if is_segment_and_quad_intersect(first_quad[i], first_quad[(i + 1) % first_quad.len()], second_quad) { return true; } } false } pub fn is_point_on_segment(point: Point3<f32>, seg_begin: Point3<f32>, seg_end: Point3<f32>) -> bool { let v = seg_end - seg_begin; let w = point - seg_begin; let w_dot_v = w.dot(v); if w_dot_v <= 0.0 { return false; } let v_dot_v = v.dot(v); if v_dot_v <= w_dot_v { return false; } let t = seg_begin + (v * (w_dot_v / v_dot_v)); let dist = t.distance(point); dist <= 0.00001 } pub fn is_valid_norm(norm: Vector3<f32>) -> bool { !norm.x.is_nan() && !norm.y.is_nan() && !norm.z.is_nan() } pub fn pick_base_plane_norm(directs: Vec<Vector3<f32>>, positions: Vec<Point3<f32>>, weights: Vec<f32>) -> Option<Vector3<f32>> { if directs.len() <= 1 { None } else if directs.len() <= 2 { if directs[0].dot(directs[1]).abs() < 0.966 { return Some(directs[0].cross(directs[1]).normalize()) } None } else if directs.len() <= 3 { let norm = norm(positions[0], positions[1], positions[2]); if is_valid_norm(norm) { return Some(norm.normalize()); } if directs[0].dot(directs[1]).abs() < 0.966 { return Some(directs[0].cross(directs[1]).normalize()) } else if directs[1].dot(directs[2]).abs() < 0.966 { return Some(directs[1].cross(directs[2]).normalize()) } else if directs[2].dot(directs[0]).abs() < 0.966 { return Some(directs[2].cross(directs[0]).normalize()) } else { None } } else { let mut weighted_indices : Vec<(usize, usize)> = Vec::new(); for i in 0..weights.len() { weighted_indices.push((i, (weights[i] * 100.0) as usize)); } weighted_indices.sort_by(|a, b| b.1.cmp(&a.1)); let i0 = weighted_indices[0].0; let i1 = weighted_indices[1].0; let i2 = weighted_indices[2].0; let norm = norm(positions[i0], positions[i1], positions[i2]); if is_valid_norm(norm) { return Some(norm.normalize()); } if directs[i0].dot(directs[i1]).abs() < 0.966 { return Some(directs[i0].cross(directs[i1]).normalize()) } else if directs[i1].dot(directs[i2]).abs() < 0.966 { return Some(directs[i1].cross(directs[i2]).normalize()) } else if directs[i2].dot(directs[i0]).abs() < 0.966 { return Some(directs[i2].cross(directs[i0]).normalize()) } else { None } } } pub fn world_perp(direct: Vector3<f32>) -> Vector3<f32> { const WORLD_Y_AXIS : Vector3<f32> = Vector3 {x: 0.0, y: 1.0, z: 0.0}; const WORLD_X_AXIS : Vector3<f32> = Vector3 {x: 1.0, y: 0.0, z: 0.0}; if direct.dot(WORLD_X_AXIS).abs() > 0.707 { direct.cross(WORLD_Y_AXIS) } else { direct.cross(WORLD_X_AXIS) } } pub fn calculate_deform_position(vert_position: Point3<f32>, vert_ray: Vector3<f32>, deform_norm: Vector3<f32>, deform_factor: f32) -> Point3<f32> { let revised_norm = if vert_ray.dot(deform_norm) < 0.0 { -deform_norm } else { deform_norm }; let proj = vert_ray.project_on(revised_norm); let scaled_proj = proj * deform_factor; let scaled_vert_ray = Vector3 {x:vert_position.x, y:vert_position.y, z:vert_position.z} + (scaled_proj - proj); Point3 {x: scaled_vert_ray.x, y: scaled_vert_ray.y, z: scaled_vert_ray.z} } pub fn make_quad(position: Point3<f32>, direct: Vector3<f32>, radius: f32, base_norm: Vector3<f32>) -> Vec<Point3<f32>> { let direct_normalized = direct.normalize(); let base_norm_normalized = base_norm.normalize(); let dot = direct_normalized.dot(base_norm); let oriented_base_norm = { if dot > 0.0 { base_norm_normalized } else { -base_norm_normalized } }; let u = { if direct_normalized.dot(oriented_base_norm).abs() > 0.707 { let switched_base_norm = world_perp(oriented_base_norm); direct_normalized.cross(switched_base_norm) } else { direct_normalized.cross(oriented_base_norm) } }; let v = u.cross(direct); let u = u.normalize() * radius; let v = v.normalize() * radius; let origin = position + direct * radius; let f = vec![origin - u - v, origin + u - v, origin + u + v, origin - u + v]; f } pub fn pick_most_not_obvious_vertex(vertices: Vec<Point3<f32>>) -> usize { if vertices.len() <= 1 { return 0; } let mut choosen_index = 0; let mut choosen_x = vertices[0].x; let pick_max = choosen_x < 0.0; for i in 1..vertices.len() { let x = vertices[i].x; if pick_max { if x > choosen_x { choosen_index = i; choosen_x = x; } } else { if x < choosen_x { choosen_index = i; choosen_x = x; } } } choosen_index }
use cgmath::Point3; use cgmath::Vector3; use cgmath::prelude::*; use cgmath::Deg; use cgmath::Rad; /* Range of the Dot Product of Two Unit Vectors Dot Angle 1.000 0 degrees 0.966 15 degrees 0.866 30 degrees 0.707 45 degrees 0.500 60 degrees 0.259 75 degrees 0.000 90 degrees -0.259 105 by degrees -0.500 120 degrees -0.707 135 degrees -0.866 150 degrees -0.966 165 degrees -1.000 180 degrees Source: http://chortle.ccsu.edu/vectorlessons/vch09/vch09_6.html */ pub fn norm(p1: Point3<f32>, p2: Point3<f32>, p3: Point3<f32>) -> Vector3<f32> { let side1 = p2 - p1; let side2 = p3 - p1; let perp = side1.cross(side2); perp.normalize() } pub fn almost_eq(v1: Vector3<f32>, v2: Vector3<f32>) -> bool { (v1.x - v2.x).abs() <= 0.01 && (v1.y - v2.y).abs() <= 0.01 && (v1.z - v2.z).abs() <= 0.01 } pub fn point_in_triangle(a: Point3<f32>, b: Point3<f32>, c: Point3<f32>, p: Point3<f32>) -> bool { let u = b - a; let v = c - a; let w = p - a; let v_cross_w = v.cross(w); let v_cross_u = v.cross(u); if v_cross_w.dot(v_cross_u) < 0.0 { return false; } let u_cross_w = u.cross(w); let u_cross_v = u.cross(v); if u_cross_w.dot(u_cross_v) < 0.0 { return false; } let denom = u_cross_v.magnitude(); let r = v_cross_w.magnitude() / denom; let t = u_cross_w.magnitude() / denom; r + t <= 1.0 } pub fn angle360(a: Vector3<f32>, b: Vector3<f32>, direct: Vector3<f32>) -> f32 { let angle = Rad::acos(a.dot(b)); let c = a.cross(b); if c.dot(direct) < 0.0 { 180.0 + Deg::from(angle).0 } else { Deg::from(angle).0 } } #[derive(PartialEq)] #[derive(Debug)] pub enum PointSide { Front, Back, Coincident } pub fn point_side_on_plane(pt: Point3<f32>, pt_on_plane: Point3<f32>, norm: Vector3<f32>) -> PointSide { let line = pt - pt_on_plane; let dot = line.dot(norm); if dot > 0.0 { PointSide::Front } else if dot < 0.0 { PointSide::Back } else { PointSide::Coincident } } #[derive(PartialEq)] #[derive(Debug)] pub enum SegmentPlaneIntersect { NoIntersection, Parallel, LiesIn, Intersection(Point3<f32>), } pub const SMALL_NUM : f32 = 0.00000001; pub fn intersect_of_segment_and_plane(p0: Point3<f32>, p1: Point3<f32>, pt_on_plane: Point3<f32>, norm: Vector3<f32>) -> SegmentPlaneIntersect { let u = p1 - p0; let w = p0 - pt_on_plane; let d = norm.dot(u); let n = -norm.dot(w); if d.abs() < SMALL_NUM { if n == 0.0 { return SegmentPlaneIntersect::LiesIn; } return SegmentPlaneIntersect::Parallel; } let s_i = n / d; if s_i < 0.0 || s_i > 1.0 || s_i.is_nan() || s_i.is_infinite() { return SegmentPlaneIntersect::NoIntersection; } SegmentPlaneIntersect::Intersection(p0 + (s_i * u)) } pub fn is_segment_and_quad_intersect(p0: Point3<f32>, p1: Point3<f32>, quad: &Vec<Point3<f32>>) -> bool { let r1 = p0; let r2 = p1; let s1 = quad[0]; let s2 = quad[1]; let s3 = quad[2]; let ds21 = s2 - s1; let ds31 = s3 - s1; let n = ds21.cross(ds31); let dr = r1 - r2; let ndotdr = n.dot(dr); if ndotdr.abs() < SMALL_NUM { return false; } let t = -n.dot(r1 - s1) / ndotdr; let m = r1 + (dr * t); let dms1 = m - s1; let u = dms1.dot(ds21); let v = dms1.dot(ds31); u >= 0.0 && u <= ds21.dot(ds21) && v >= 0.0 && v <= ds31.dot(ds31) } pub fn is_two_quads_intersect(first_quad: &Vec<Point3<f32>>, second_quad: &Vec<Point3<f32>>) -> bool { for i in 0..second_quad.len() { if is_segment_and_quad_intersect(second_quad[i], second_quad[(i + 1) % second_quad.len()], first_quad) { return true; } } for i in 0..first_quad.len() { if is_segment_and_quad_intersect(first_quad[i], first_quad[(i + 1) % first_quad.len()], second_quad) { return true; } } false } pub fn is_point_on_segment(point: Point3<f32>, seg_begin: Point3<f32>, seg_end: Point3<f32>) -> bool { let v = seg_end - seg_begin; let w = point - seg_begin; let w_dot_v = w.dot(v); if w_dot_v <= 0.0 { return false; } let v_dot_v = v.dot(v); if v_dot_v <= w_dot_v { return false; } let t = seg_begin + (v * (w_dot_v / v_dot_v)); let dist = t.distance(point); dist <= 0.00001 } pub fn is_valid_norm(norm: Vector3<f32>) -> bool { !norm.x.is_nan() && !norm.y.is_nan() && !norm.z.is_nan() } pub fn pick_base_plane_norm(directs: Vec<Vector3<f32>>, positions: Vec<Point3<f32>>, weights: Vec<f32>) -> Option<Vector3<f32>> { if directs.len() <= 1 { None } else if directs.len() <= 2 { if directs[0].dot(directs[1]).abs() < 0.966 { return Some(directs[0].cross(directs[1]).normalize()) } None } else if directs.len() <= 3 { let norm = norm(positions[0], positions[1], positions[2]); if is_valid_norm(norm) { return Some(norm.normalize()); } if directs[0].dot(directs[1]).abs() < 0.966 { return Some(directs[0].cross(directs[1]).normalize()) } else if directs[1].dot(directs[2]).abs() < 0.966 { return Some(directs[1].cross(directs[2]).normalize()) } else if directs[2].dot(directs[0]).abs() < 0.966 { return Some(directs[2].cross(directs[0]).normalize()) } else { None } } else { let mut weighted_indices : Vec<(usize, usize)> = Vec::new(); for i in 0..weights.len() { weighted_indices.push((i, (weights[i] * 100.0) as usize)); } weighted_indices.sort_by(|a, b| b.1.cmp(&a.1)); let i0 = weighted_indices[0].0; let i1 = weighted_indices[1].0; let i2 = weighted_indices[2].0; let norm = norm(positions[i0], positions[i1], positions[i2]); if is_valid_norm(norm) { return Some(norm.normalize()); } if directs[i0].dot(directs[i1]).abs() < 0.966 { return Some(directs[i0].cross(directs[i1]).normalize()) } else if directs[i1].dot(directs[i2]).abs() < 0.966 { return Some(directs[i1].cross(directs[i2]).normalize()) } else if directs[i2].dot(directs[i0]).abs() < 0.966 { return Some(directs[i2].cross(directs[i0]).normalize()) } else { None } } } pub fn world_perp(direct: Vector3<f32>) -> Vector3<f32> { const WORLD_Y_AXIS : Vector3<f32> = Vector3 {x: 0.0, y: 1.0, z: 0.0}; const WORLD_X_AXIS : Vector3<f32> = Vector3 {x: 1.0, y: 0.0, z: 0.0}; if direct.dot(WORLD_X_AXIS).abs() > 0.707 { direct.cross(WORLD_Y_AXIS) } else { direct.cross(WORLD_X_AXIS) } } pub fn calculate_deform_position(vert_position: Point3<f32>, vert_ray: Vector3<f32>, deform_norm: Vector3<f32>, deform_factor: f32) -> Point3<f32> { let revised_norm = if vert_ray.dot(deform_norm) < 0.0 { -deform_norm } else { deform_norm }; let proj = vert_ray.project_on(revised_norm); let scaled_proj = proj * deform_factor; let scaled_vert_ray = Vector3 {x:vert_position.x, y:vert_position.y, z:vert_position.z} + (scaled_proj - proj); Point3 {x: scaled_vert_ray.x, y: scaled_vert_ray.y, z: scaled_vert_ray.z} } pub fn make_quad(position: Point3<f32>, direct: Vector3<f32>, radius: f32, base_norm: Vector3<f32>) -> Vec<Point3<f32>> { let direct_normalized = direct.normalize(); let base_norm_normalized = base_norm.normalize(); let dot = direct_normalized.dot(base_norm); let oriented_base_norm = { if dot > 0.0 { base_norm_normalized } else { -base_norm_normalized } };
let v = u.cross(direct); let u = u.normalize() * radius; let v = v.normalize() * radius; let origin = position + direct * radius; let f = vec![origin - u - v, origin + u - v, origin + u + v, origin - u + v]; f } pub fn pick_most_not_obvious_vertex(vertices: Vec<Point3<f32>>) -> usize { if vertices.len() <= 1 { return 0; } let mut choosen_index = 0; let mut choosen_x = vertices[0].x; let pick_max = choosen_x < 0.0; for i in 1..vertices.len() { let x = vertices[i].x; if pick_max { if x > choosen_x { choosen_index = i; choosen_x = x; } } else { if x < choosen_x { choosen_index = i; choosen_x = x; } } } choosen_index }
let u = { if direct_normalized.dot(oriented_base_norm).abs() > 0.707 { let switched_base_norm = world_perp(oriented_base_norm); direct_normalized.cross(switched_base_norm) } else { direct_normalized.cross(oriented_base_norm) } };
assignment_statement
[ { "content": "pub fn cube() -> Mesh {\n\n let mut m = Mesh::new();\n\n let face_id = m.add_plane(1.0, 1.0);\n\n let normal = m.face_norm(face_id);\n\n m.extrude_face(face_id, normal, 1.0).translate(0.0, 0.0, -0.5);\n\n m\n\n}\n\n\n", "file_path": "src/primitives.rs", "rank": 15, "scor...
Rust
main/src/vocab/sentence_piece_bpe_model.rs
sftse/rust-tokenizers
d869924622e40ea525d8244d1716517751c7743a
use crate::error::TokenizerError; use crate::tokenizer::base_tokenizer::{Token, TokenRef}; use crate::tokenizer::tokenization_utils::{is_punctuation, is_whitespace}; use crate::vocab::sentencepiece_proto::sentencepiece_model::ModelProto; use crate::{Mask, Offset, OffsetSize}; use hashbrown::HashMap; use protobuf::Message; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fs::File; use std::io::Read; use std::ops::Index; #[derive(Debug, Clone)] pub struct BpeMergeVocab { pub values: HashMap<String, i64>, } pub struct SentencePieceBpeModel { bpe_ranks: BpeMergeVocab, } impl SentencePieceBpeModel { pub fn from_file(path: &str) -> Result<SentencePieceBpeModel, TokenizerError> { let mut f = File::open(path).map_err(|e| { TokenizerError::FileNotFound(format!("{} vocabulary file not found :{}", path, e)) })?; let mut contents = Vec::new(); let proto = match f.read_to_end(&mut contents) { Ok(_) => match ModelProto::parse_from_bytes(contents.as_slice()) { Ok(proto_value) => proto_value, Err(e) => { return Err(TokenizerError::VocabularyParsingError(e.to_string())); } }, Err(e) => { return Err(TokenizerError::VocabularyParsingError(e.to_string())); } }; let mut values = HashMap::new(); for (idx, piece) in proto.get_pieces().iter().enumerate() { values.insert(piece.get_piece().to_owned(), idx as i64); } let bpe_ranks = BpeMergeVocab { values }; Ok(SentencePieceBpeModel { bpe_ranks }) } pub fn tokenize_to_tokens(&self, initial_token: TokenRef) -> Vec<Token> { let mut sub_tokens = Vec::new(); if initial_token.mask != Mask::Special && initial_token.mask != Mask::Unknown { let mut agenda: BinaryHeap<SymbolPair> = BinaryHeap::new(); let mut symbols = SymbolList::from(initial_token); for symbol_index in 1..symbols.len() { self.maybe_add_pair( symbol_index as isize - 1, symbol_index as isize, initial_token.text, &symbols, &mut agenda, ); } while let Some(symbol_pair) = agenda.pop() { let left_symbol_index = symbol_pair.left; let right_symbol_index = symbol_pair.right; if left_symbol_index != -1 && right_symbol_index != -1 { let new_symbol = symbols.merge_symbols( left_symbol_index as usize, right_symbol_index as usize, symbol_pair.pair_size, ); if let Some(new_symbol) = new_symbol { self.maybe_add_pair( new_symbol.prev, left_symbol_index, initial_token.text, &symbols, &mut agenda, ); self.maybe_add_pair( left_symbol_index, new_symbol.next, initial_token.text, &symbols, &mut agenda, ); } } } for symbol in symbols.into_iter().flatten() { sub_tokens.push(Token { text: initial_token.text[symbol.start_byte..symbol.end_byte].to_string(), offset: Offset { begin: symbol.start_offset as OffsetSize + initial_token.offset.begin, end: symbol.end_offset as OffsetSize + initial_token.offset.begin, }, reference_offsets: initial_token.reference_offsets [symbol.start_offset..symbol.end_offset] .to_vec(), mask: Default::default(), }) } } else { sub_tokens.push(initial_token.to_owned()); } self.populate_masks(sub_tokens.as_mut_slice(), '\u{2581}'); sub_tokens } fn maybe_add_pair( &self, left_symbol_index: isize, right_symbol_index: isize, input_text: &str, symbols: &SymbolList, agenda: &mut BinaryHeap<SymbolPair>, ) { if left_symbol_index != -1 && right_symbol_index != -1 { if let (Some(left_symbol), Some(right_symbol)) = ( symbols[left_symbol_index as usize], symbols[right_symbol_index as usize], ) { let merged_text = &input_text[left_symbol.start_byte..right_symbol.end_byte]; if let Some(&score) = self.bpe_ranks.values.get(merged_text) { agenda.push(SymbolPair { left: left_symbol_index, right: right_symbol_index, score, pair_size: left_symbol.size + right_symbol.size, }) } } } } pub fn populate_masks(&self, tokens: &mut [Token], whitespace_token: char) { let mut previous_mask = Mask::None; for token in tokens { if token.text.chars().count() == 1 { let first_char = match token.text.chars().last() { Some(value) => value, None => { token.mask = Mask::Unknown; previous_mask = Mask::Unknown; continue; } }; if is_punctuation(&first_char) { token.mask = Mask::Punctuation; previous_mask = Mask::Punctuation; continue; } if is_whitespace(&first_char) { token.mask = Mask::Whitespace; previous_mask = Mask::Punctuation; continue; } } if !token.text.starts_with(whitespace_token) & !(previous_mask == Mask::Punctuation) & !(previous_mask == Mask::Whitespace) { token.mask = Mask::Continuation; previous_mask = Mask::Continuation; } else { previous_mask = Mask::None; } } } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] struct Symbol { start_byte: usize, end_byte: usize, start_offset: usize, end_offset: usize, prev: isize, next: isize, size: usize, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] struct SymbolPair { left: isize, right: isize, score: i64, pair_size: usize, } impl Ord for SymbolPair { fn cmp(&self, other: &Self) -> Ordering { other .score .cmp(&self.score) .then_with(|| other.left.cmp(&self.left)) } } impl PartialOrd for SymbolPair { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } struct SymbolList { symbols: Vec<Option<Symbol>>, } impl Index<usize> for SymbolList { type Output = Option<Symbol>; fn index(&self, index: usize) -> &Option<Symbol> { self.symbols.index(index) } } impl IntoIterator for SymbolList { type Item = Option<Symbol>; type IntoIter = <Vec<Option<Symbol>> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.symbols.into_iter() } } impl From<TokenRef<'_>> for SymbolList { fn from(token: TokenRef) -> Self { let mut symbols = Vec::with_capacity(token.text.len()); for (index, (character_start, character)) in token.text.char_indices().enumerate() { let next = if index == token.text.char_indices().count() - 1 { -1 } else { (index + 1) as isize }; symbols.push(Some(Symbol { start_byte: character_start, end_byte: character_start + character.len_utf8(), start_offset: index, end_offset: index + 1, prev: index as isize - 1, next, size: 1, })); } Self { symbols } } } impl SymbolList { pub fn len(&self) -> usize { self.symbols.len() } pub fn merge_symbols( &mut self, symbol_1_index: usize, symbol_2_index: usize, size_validation: usize, ) -> Option<Symbol> { if let (Some(left_symbol), Some(right_symbol)) = (self[symbol_1_index], self[symbol_2_index]) { if left_symbol.size + right_symbol.size != size_validation { return None; } if right_symbol.next != -1 { if let Some(next_next) = self.symbols.get_mut(right_symbol.next as usize).unwrap() { next_next.prev = symbol_1_index as isize; } } let new_symbol = Symbol { start_byte: left_symbol.start_byte, end_byte: right_symbol.end_byte, start_offset: left_symbol.start_offset, end_offset: right_symbol.end_offset, prev: left_symbol.prev, next: right_symbol.next, size: left_symbol.size + right_symbol.size, }; self.symbols[symbol_2_index] = None; self.symbols[symbol_1_index] = Some(new_symbol); Some(new_symbol) } else { None } } }
use crate::error::TokenizerError; use crate::tokenizer::base_tokenizer::{Token, TokenRef}; use crate::tokenizer::tokenization_utils::{is_punctuation, is_whitespace}; use crate::vocab::sentencepiece_proto::sentencepiece_model::ModelProto; use crate::{Mask, Offset, OffsetSize}; use hashbrown::HashMap; use protobuf::Message; use std::cmp::Ordering; use std::collections::BinaryHeap; use std::fs::File; use std::io::Read; use std::ops::Index; #[derive(Debug, Clone)] pub struct BpeMergeVocab { pub values: HashMap<String, i64>, } pub struct SentencePieceBpeModel { bpe_ranks: BpeMergeVocab, } impl SentencePieceBpeModel { pub fn from_file(path: &str) -> Result<SentencePieceBpeModel, TokenizerError> { let mut f = File::open(path).map_err(|e| { TokenizerError::FileNotFound(format!("{} vocabulary file not found :{}", path, e)) })?; let mut contents = Vec::new(); let proto = match f.read_to_end(&mut contents) { Ok(_) => match ModelProto::parse_from_bytes(contents.as_slice()) { Ok(proto_value) => proto_value, Err(e) => { return Err(TokenizerError::VocabularyParsingError(e.to_string())); } }, Err(e) => { return Err(TokenizerError::VocabularyParsingError(e.to_string())); } }; let mut values = HashMap::new(); for (idx, piece) in proto.get_pieces().iter().enumerate() { values.insert(piece.get_piece().to_owned(), idx as i64); } let bpe_ranks = BpeMergeVocab { values }; Ok(SentencePieceBpeModel { bpe_ranks }) } pub fn tokenize_to_tokens(&self, initial_token: TokenRef) -> Vec<Token> { let mut sub_tokens = Vec::new(); if initial_token.mask != Mask::Special && initial_token.mask != Mask::Unknown { let mut agenda: BinaryHeap<SymbolPair> = BinaryHeap::new(); let mut symbols = SymbolList::from(initial_token); for symbol_index in 1..symbols.len() { self.maybe_add_pair( symbol_index as isize - 1, symbol_index as isize, initial_token.text, &symbols, &mut agenda, ); } while let Some(symbol_pair) = agenda.pop() { let left_symbol_index = symbol_pair.left; let right_symbol_index = symbol_pair.right; if left_symbol_index != -1 && right_symbol_index != -1 { let new_symbol = symbols.merge_symbols( left_symbol_index as usize, right_symbol_index as usize, symbol_pair.pair_size, ); if let Some(new_symbol) = new_symbol { self.maybe_add_pair( new_symbol.prev, left_symbol_index, initial_token.text, &symbols, &mut agenda, ); self.maybe_add_pair( left_symbol_index, new_symbol.next, initial_token.text, &symbols, &mut agenda, ); } } } for symbol in symbols.into_iter().flatten() { sub_tokens.push(Token { text: initial_token.text[symbol.start_byte..symbol.end_byte].to_string(), offset: Offset { begin: symbol.start_offset as OffsetSize + initial_token.offset.begin, end: symbol.end_offset as OffsetSize + initial_token.offset.begin, }, reference_offsets: initial_token.reference_offsets [symbol.start_offset..symbol.end_offset] .to_vec(), mask: Default::default(), }) } } else { sub_tokens.push(initial_token.to_owned()); } self.populate_masks(sub_tokens.as_mut_slice(), '\u{2581}'); sub_tokens } fn maybe_add_pair( &self, left_symbol_index: isize, right_symbol_index: isize, input_text: &str, symbols: &SymbolList, agenda: &mut BinaryHeap<SymbolPair>, ) { if left_symbol_index != -1 && right_symbol_index != -1 { if let (Some(left_symbol), Some(right_symbol)) = ( symbols[left_symbol_index as usize], symbols[right_symbol_index as usize], ) { let merged_text = &input_text[left_symbol.start_byte..right_symbol.end_byte]; if let Some(&score) = self.bpe_ranks.values.get(merged_text) { agenda.push(SymbolPair { left: left_symbol_index, right: right_symbol_index, score, pair_size: left_symbol.size + right_symbol.size, }) } } } } pub fn populate_masks(&self, tokens: &mut [Token], whitespace_token: char) { let mut previous_mask = Mask::None; for token in tokens { if token.text.chars().count() == 1 { let first_char = match token.text.chars().last() { Some(value) => value, None => { token.mask = Mask::Unknown; previous_mask = Mask::Unknown; continue; } }; if is_punctuation(&first_char) { token.mask = Mask::Punctuation; previous_mask = Mask::Punctuation; continue; } if is_whitespace(&first_char) { token.mask = Mask::Whitespace; previous_mask = Mask::Punctuation; continue; } } if !token.text.starts_with(whitespace_token) & !(previous_mask == Mask::Punctuation) & !(previous_mask == Mask::Whitespace) { token.mask = Mask::Continuation; previous_mask = Mask::Continuation; } else { previous_mask = Mask::None; } } } } #[derive(Debug, Copy, Clone, Eq, PartialEq)] struct Symbol { start_byte: usize, end_byte: usize, start_offset: usize, end_offset: usize, prev: isize, next: isize, size: usize, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] struct SymbolPair { left: isize, right: isize, score: i64, pair_size: usize, } impl Ord for SymbolPair { fn cmp(&self, other: &Self) -> Ordering { other .score .cmp(&self.score) .then_with(|| other.left.cmp(&self.left)) } } impl PartialOrd for SymbolPair { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } struct SymbolList { symbols: Vec<Option<Symbol>>, } impl Index<usize> for SymbolList { type Output = Option<Symbol>; fn index(&self, index: usize) -> &Option<Symbol> { self.symbols.index(index) } } impl IntoIterator for SymbolList { type Item = Option<Symbol>; type IntoIter = <Vec<Option<Symbol>> as IntoIterator>::IntoIter; fn into_iter(self) -> Self::IntoIter { self.symbols.into_iter() } } impl From<TokenRef<'_>> for SymbolList { fn from(token: TokenRef) -> Self { let mut symbols = Vec::with_capacity(token.text.len()); for (index, (character_start, character)) in token.text.char_indices().enumerate() { let next = if index == token.text.char_indices().count() - 1 { -1 } else { (index + 1) as isize }; symbols.push(
); } Self { symbols } } } impl SymbolList { pub fn len(&self) -> usize { self.symbols.len() } pub fn merge_symbols( &mut self, symbol_1_index: usize, symbol_2_index: usize, size_validation: usize, ) -> Option<Symbol> { if let (Some(left_symbol), Some(right_symbol)) = (self[symbol_1_index], self[symbol_2_index]) { if left_symbol.size + right_symbol.size != size_validation { return None; } if right_symbol.next != -1 { if let Some(next_next) = self.symbols.get_mut(right_symbol.next as usize).unwrap() { next_next.prev = symbol_1_index as isize; } } let new_symbol = Symbol { start_byte: left_symbol.start_byte, end_byte: right_symbol.end_byte, start_offset: left_symbol.start_offset, end_offset: right_symbol.end_offset, prev: left_symbol.prev, next: right_symbol.next, size: left_symbol.size + right_symbol.size, }; self.symbols[symbol_2_index] = None; self.symbols[symbol_1_index] = Some(new_symbol); Some(new_symbol) } else { None } } }
Some(Symbol { start_byte: character_start, end_byte: character_start + character.len_utf8(), start_offset: index, end_offset: index + 1, prev: index as isize - 1, next, size: 1, })
call_expression
[ { "content": "fn bytes_offsets(text: &str) -> Vec<usize> {\n\n let mut offsets = Vec::with_capacity(text.len());\n\n for (char_idx, character) in text.chars().enumerate() {\n\n for _ in 0..character.len_utf8() {\n\n offsets.push(char_idx)\n\n }\n\n }\n\n offsets\n\n}\n\n\n",...
Rust
storage/libradb/src/metrics.rs
chouette254/libra
1eaefa60d29e1df72ba6c4f9cf1867964821b586
use libra_metrics::{ register_histogram_vec, register_int_counter, register_int_gauge, register_int_gauge_vec, HistogramVec, IntCounter, IntGauge, IntGaugeVec, }; use once_cell::sync::Lazy; pub static LIBRA_STORAGE_LEDGER: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libra_storage_ledger", "Libra storage ledger counters", &["type"] ) .unwrap() }); pub static LIBRA_STORAGE_CF_SIZE_BYTES: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libra_storage_cf_size_bytes", "Libra storage Column Family size in bytes", &["cf_name"] ) .unwrap() }); pub static LIBRA_STORAGE_COMMITTED_TXNS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "libra_storage_committed_txns", "Libra storage committed transactions" ) .unwrap() }); pub static LIBRA_STORAGE_LATEST_TXN_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_latest_transaction_version", "Libra storage latest transaction version" ) .unwrap() }); pub static LIBRA_STORAGE_LEDGER_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_ledger_version", "Version in the latest saved ledger info." ) .unwrap() }); pub static LIBRA_STORAGE_NEXT_BLOCK_EPOCH: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_next_block_epoch", "ledger_info.next_block_epoch() for the latest saved ledger info." ) .unwrap() }); pub static LIBRA_STORAGE_PRUNE_WINDOW: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!("libra_storage_prune_window", "Libra storage prune window").unwrap() }); pub static LIBRA_STORAGE_PRUNER_LEAST_READABLE_STATE_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_pruner_least_readable_state_version", "Libra storage pruner least readable state version" ) .unwrap() }); pub static LIBRA_STORAGE_API_LATENCY_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "libra_storage_api_latency_seconds", "Libra storage api latency in seconds", &["api_name"] ) .unwrap() }); pub static LIBRA_STORAGE_OTHER_TIMERS_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "libra_storage_other_timers_seconds", "Various timers below public API level.", &["name"] ) .unwrap() }); pub(crate) static BACKUP_EPOCH_ENDING_EPOCH: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_epoch_ending_epoch", "Current epoch returned in an epoch ending backup." ) .unwrap() }); pub(crate) static BACKUP_TXN_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_transaction_version", "Current version returned in a transaction backup." ) .unwrap() }); pub(crate) static BACKUP_STATE_SNAPSHOT_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_state_snapshot_version", "Version of requested state snapshot backup." ) .unwrap() }); pub(crate) static BACKUP_STATE_SNAPSHOT_LEAF_IDX: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_state_snapshot_leaf_index", "Index of current leaf index returned in a state snapshot backup." ) .unwrap() });
use libra_metrics::{ register_histogram_vec, register_int_counter, register_int_gauge,
in bytes", &["cf_name"] ) .unwrap() }); pub static LIBRA_STORAGE_COMMITTED_TXNS: Lazy<IntCounter> = Lazy::new(|| { register_int_counter!( "libra_storage_committed_txns", "Libra storage committed transactions" ) .unwrap() }); pub static LIBRA_STORAGE_LATEST_TXN_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_latest_transaction_version", "Libra storage latest transaction version" ) .unwrap() }); pub static LIBRA_STORAGE_LEDGER_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_ledger_version", "Version in the latest saved ledger info." ) .unwrap() }); pub static LIBRA_STORAGE_NEXT_BLOCK_EPOCH: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_next_block_epoch", "ledger_info.next_block_epoch() for the latest saved ledger info." ) .unwrap() }); pub static LIBRA_STORAGE_PRUNE_WINDOW: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!("libra_storage_prune_window", "Libra storage prune window").unwrap() }); pub static LIBRA_STORAGE_PRUNER_LEAST_READABLE_STATE_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_storage_pruner_least_readable_state_version", "Libra storage pruner least readable state version" ) .unwrap() }); pub static LIBRA_STORAGE_API_LATENCY_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "libra_storage_api_latency_seconds", "Libra storage api latency in seconds", &["api_name"] ) .unwrap() }); pub static LIBRA_STORAGE_OTHER_TIMERS_SECONDS: Lazy<HistogramVec> = Lazy::new(|| { register_histogram_vec!( "libra_storage_other_timers_seconds", "Various timers below public API level.", &["name"] ) .unwrap() }); pub(crate) static BACKUP_EPOCH_ENDING_EPOCH: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_epoch_ending_epoch", "Current epoch returned in an epoch ending backup." ) .unwrap() }); pub(crate) static BACKUP_TXN_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_transaction_version", "Current version returned in a transaction backup." ) .unwrap() }); pub(crate) static BACKUP_STATE_SNAPSHOT_VERSION: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_state_snapshot_version", "Version of requested state snapshot backup." ) .unwrap() }); pub(crate) static BACKUP_STATE_SNAPSHOT_LEAF_IDX: Lazy<IntGauge> = Lazy::new(|| { register_int_gauge!( "libra_backup_handler_state_snapshot_leaf_index", "Index of current leaf index returned in a state snapshot backup." ) .unwrap() });
register_int_gauge_vec, HistogramVec, IntCounter, IntGauge, IntGaugeVec, }; use once_cell::sync::Lazy; pub static LIBRA_STORAGE_LEDGER: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libra_storage_ledger", "Libra storage ledger counters", &["type"] ) .unwrap() }); pub static LIBRA_STORAGE_CF_SIZE_BYTES: Lazy<IntGaugeVec> = Lazy::new(|| { register_int_gauge_vec!( "libra_storage_cf_size_bytes", "Libra storage Column Family size
random
[ { "content": "// Parse a use declaration:\n\n// UseDecl =\n\n// \"use\" <ModuleIdent> <UseAlias> \";\" |\n\n// \"use\" <ModuleIdent> :: <UseMember> \";\" |\n\n// \"use\" <ModuleIdent> :: \"{\" Comma<UseMember> \"}\" \";\"\n\nfn parse_use_decl<'input>(tokens: &mut Lexer<'input>) -...
Rust
src/bin/delete-reaction.rs
netguru/commentable-rs
be95c83cfc2ff65d6175cc0a979461cc235512c5
use lambda_http::{lambda, Request, Response, Body, RequestExt}; use rusoto_core::Region; use rusoto_dynamodb::{DynamoDbClient}; use serde::Deserialize; use commentable_rs::utils::db::{DynamoDbModel, CommentableId}; use commentable_rs::utils::http::{ok, bad_request, internal_server_error, HttpError}; use commentable_rs::utils::current_user::CurrentUser; use commentable_rs::utils::current_comment::CurrentComment; use commentable_rs::models::{ user::{AuthToken, User, UserId}, comment::{CommentId, Comment}, reaction::{reaction_id, Reaction, ReactionType}, }; #[derive(Deserialize)] struct Params { auth_token: AuthToken, comment_id: CommentId, reaction_type: ReactionType, } struct DeleteReaction { db: DynamoDbClient, commentable_id: CommentableId, params: Params, current_user: Option<User>, current_comment: Option<Comment>, reaction: Option<Reaction>, } impl CurrentUser for DeleteReaction { fn db(&self) -> &DynamoDbClient { &self.db } fn auth_token(&self) -> Option<AuthToken> { Some(self.params.auth_token.clone()) } fn set_current_user(&mut self, user: Option<User>) { self.current_user = user; } } impl CurrentComment for DeleteReaction { fn db(&self) -> &DynamoDbClient { &self.db } fn commentable_id(&self) -> CommentableId { self.commentable_id.clone() } fn comment_id(&self) -> CommentId { self.params.comment_id.clone() } fn set_current_comment(&mut self, comment: Comment) { self.current_comment = Some(comment); } } impl DeleteReaction { pub fn respond_to(request: Request) -> Result<Response<Body>, HttpError> { if let Some(commentable_id) = request.path_parameters().get("id") { Self::new(request, commentable_id.to_string())? .validate_params()? .fetch_current_user()? .fetch_current_comment()? .fetch_reaction()? .delete()? .serialize() } else { Err(bad_request("Invalid path parameters: 'id' is required.")) } } pub fn new(request: Request, commentable_id: CommentableId) -> Result<Self, HttpError> { if let Ok(Some(params)) = request.payload::<Params>() { Ok(Self { db: DynamoDbClient::new(Region::default()), commentable_id, current_comment: None, current_user: None, reaction: None, params, }) } else { Err(bad_request("Invalid parameters")) } } fn current_user_id(&self) -> &UserId { &self.current_user.as_ref().unwrap().id } fn current_comment_id(&self) -> &CommentId { &self.current_comment.as_ref().unwrap().id } pub fn validate_params(&mut self) -> Result<&mut Self, HttpError> { if self.params.auth_token.trim().len() == 0 { Err(bad_request("Invalid request parameters: auth_token is required")) } else if self.params.comment_id.trim().len() == 0 { Err(bad_request("Invalid request parameters: comment_id is required")) } else if self.params.reaction_type.trim().len() == 0 { Err(bad_request("Invalid request parameters: reaction_type is required")) } else { Ok(self) } } pub fn fetch_reaction(&mut self) -> Result<&mut Self, HttpError> { let id = reaction_id(self.current_comment_id(), self.current_user_id(), &self.params.reaction_type); match Reaction::find(&self.db, self.commentable_id.clone(), id) { Ok(Some(reaction)) => self.reaction = Some(reaction), Ok(None) => return Err(bad_request("Could not delete reaction.")), Err(err) => return Err(internal_server_error(err)), } Ok(self) } pub fn delete(&mut self) -> Result<&mut Self, HttpError> { let id = reaction_id(self.current_comment_id(), self.current_user_id(), &self.params.reaction_type); Reaction::delete(&self.db, self.commentable_id.clone(), id) .map_err(|err| internal_server_error(err))?; Ok(self) } pub fn serialize(&self) -> Result<Response<Body>, HttpError> { Ok(ok("")) } } fn main() { lambda!(|request, _| DeleteReaction::respond_to(request) .or_else(|error_response| Ok(error_response)) ); }
use lambda_http::{lambda, Request, Response, Body, RequestExt}; use rusoto_core::Region; use rusoto_dynamodb::{DynamoDbClient}; use serde::Deserialize; use commentable_rs::utils::db::{DynamoDbModel, CommentableId}; use commentable_rs::utils::http::{ok, bad_request, internal_server_error, HttpError}; use commentable_rs::utils::current_user::CurrentUser; use commentable_rs::utils::current_comment::CurrentComment; use commentable_rs::models::{ user::{AuthToken, User, UserId}, comment::{CommentId, Comment}, reaction::{reaction_id, Reaction, ReactionType}, }; #[derive(Deserialize)] struct Params { auth_token: AuthToken, comment_id: CommentId, reaction_type: ReactionType, } struct DeleteReaction { db: DynamoDbClient, commentable_id: CommentableId, params: Params, current_user: Option<User>, current_comment: Option<Comment>, reaction: Option<Reaction>, } impl CurrentUser for DeleteReaction { fn db(&self) -> &DynamoDbClient { &self.db } fn auth_token(&self) -> Option<AuthToken> { Some(self.params.auth_token.clone()) } fn set_current_user(&mut self, user: Option<User>) { self.current_user = user; } } impl CurrentComment for DeleteReaction { fn db(&self) -> &DynamoDbClient { &self.db } fn commentable_id(&self) -> CommentableId { self.commentable_id.clone() } fn comment_id(&self) -> CommentId { self.params.comment_id.clone() } fn set_current_comment(&mut self, comment: Comment) { self.current_comment = Some(comment); } } impl DeleteReaction { pub fn respond_to(request: Request) -> Result<Response<Body>, HttpError> { if let Some(commentable_id) = request.path_parameters().get("id") { Self::new(request, commentable_id.to_string())? .validate_params()? .fetch_current_user()? .fetch_current_comment()? .fetch_reaction()? .delete()? .serialize() } else { Err(bad_request("Invalid path parameters: 'id' is required.")) } } pub fn new(request: Request, commentable_id: CommentableId) -> Result<Self, HttpError> { if let Ok(Some(params)) = request.payload::<Params>() {
} else { Err(bad_request("Invalid parameters")) } } fn current_user_id(&self) -> &UserId { &self.current_user.as_ref().unwrap().id } fn current_comment_id(&self) -> &CommentId { &self.current_comment.as_ref().unwrap().id } pub fn validate_params(&mut self) -> Result<&mut Self, HttpError> { if self.params.auth_token.trim().len() == 0 { Err(bad_request("Invalid request parameters: auth_token is required")) } else if self.params.comment_id.trim().len() == 0 { Err(bad_request("Invalid request parameters: comment_id is required")) } else if self.params.reaction_type.trim().len() == 0 { Err(bad_request("Invalid request parameters: reaction_type is required")) } else { Ok(self) } } pub fn fetch_reaction(&mut self) -> Result<&mut Self, HttpError> { let id = reaction_id(self.current_comment_id(), self.current_user_id(), &self.params.reaction_type); match Reaction::find(&self.db, self.commentable_id.clone(), id) { Ok(Some(reaction)) => self.reaction = Some(reaction), Ok(None) => return Err(bad_request("Could not delete reaction.")), Err(err) => return Err(internal_server_error(err)), } Ok(self) } pub fn delete(&mut self) -> Result<&mut Self, HttpError> { let id = reaction_id(self.current_comment_id(), self.current_user_id(), &self.params.reaction_type); Reaction::delete(&self.db, self.commentable_id.clone(), id) .map_err(|err| internal_server_error(err))?; Ok(self) } pub fn serialize(&self) -> Result<Response<Body>, HttpError> { Ok(ok("")) } } fn main() { lambda!(|request, _| DeleteReaction::respond_to(request) .or_else(|error_response| Ok(error_response)) ); }
Ok(Self { db: DynamoDbClient::new(Region::default()), commentable_id, current_comment: None, current_user: None, reaction: None, params, })
call_expression
[ { "content": "pub fn comment_id(commentable_id: &CommentableId, user_id: &UserId) -> String {\n\n let id = hash(&format!(\"{}{}{}\", commentable_id, user_id, Utc::now().to_string()));\n\n format!(\"{}{}{}\", COMMENT_ID_PREFIX, Utc::now().timestamp_millis(), id)\n\n}\n", "file_path": "src/models/comment.rs...
Rust
src/u32x8_.rs
nathanvoglsam/wide
00de1af88cced28b9fb64fbe393261f203573c96
use super::*; pick! { if #[cfg(target_feature="avx2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { avx2: m256i } } else if #[cfg(target_feature="ssse3")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { sse0: m128i, sse1: m128i } } else { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { arr: [u32;8] } } } unsafe impl Zeroable for u32x8 {} unsafe impl Pod for u32x8 {} impl Add for u32x8 { type Output = Self; #[inline] #[must_use] fn add(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: add_i32_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: add_i32_m128i(self.sse0, rhs.sse0) , sse1: add_i32_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].wrapping_add(rhs.arr[0]), self.arr[1].wrapping_add(rhs.arr[1]), self.arr[2].wrapping_add(rhs.arr[2]), self.arr[3].wrapping_add(rhs.arr[3]), self.arr[4].wrapping_add(rhs.arr[4]), self.arr[5].wrapping_add(rhs.arr[5]), self.arr[6].wrapping_add(rhs.arr[6]), self.arr[7].wrapping_add(rhs.arr[7]), ]} } } } } impl Sub for u32x8 { type Output = Self; #[inline] #[must_use] fn sub(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: sub_i32_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: sub_i32_m128i(self.sse0, rhs.sse0) , sse1: sub_i32_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].wrapping_sub(rhs.arr[0]), self.arr[1].wrapping_sub(rhs.arr[1]), self.arr[2].wrapping_sub(rhs.arr[2]), self.arr[3].wrapping_sub(rhs.arr[3]), self.arr[4].wrapping_sub(rhs.arr[4]), self.arr[5].wrapping_sub(rhs.arr[5]), self.arr[6].wrapping_sub(rhs.arr[6]), self.arr[7].wrapping_sub(rhs.arr[7]), ]} } } } } impl Mul for u32x8 { type Output = Self; #[inline] #[must_use] fn mul(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: mul_i32_keep_low_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: mul_i32_keep_low_m128i(self.sse0, rhs.sse0) , sse1: mul_i32_keep_low_m128i(self.sse1, rhs.sse1)} } else { let arr1: [u32; 8] = cast(self); let arr2: [u32; 8] = cast(rhs); cast([ arr1[0].wrapping_mul(arr2[0]), arr1[1].wrapping_mul(arr2[1]), arr1[2].wrapping_mul(arr2[2]), arr1[3].wrapping_mul(arr2[3]), arr1[4].wrapping_mul(arr2[4]), arr1[5].wrapping_mul(arr2[5]), arr1[6].wrapping_mul(arr2[6]), arr1[7].wrapping_mul(arr2[7]), ]) } } } } impl BitAnd for u32x8 { type Output = Self; #[inline] #[must_use] fn bitand(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitand_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitand_m128i(self.sse0, rhs.sse0) , sse1: bitand_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitand(rhs.arr[0]), self.arr[1].bitand(rhs.arr[1]), self.arr[2].bitand(rhs.arr[2]), self.arr[3].bitand(rhs.arr[3]), self.arr[4].bitand(rhs.arr[4]), self.arr[5].bitand(rhs.arr[5]), self.arr[6].bitand(rhs.arr[6]), self.arr[7].bitand(rhs.arr[7]), ]} } } } } impl BitOr for u32x8 { type Output = Self; #[inline] #[must_use] fn bitor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitor_m128i(self.sse0, rhs.sse0) , sse1: bitor_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitor(rhs.arr[0]), self.arr[1].bitor(rhs.arr[1]), self.arr[2].bitor(rhs.arr[2]), self.arr[3].bitor(rhs.arr[3]), self.arr[4].bitor(rhs.arr[4]), self.arr[5].bitor(rhs.arr[5]), self.arr[6].bitor(rhs.arr[6]), self.arr[7].bitor(rhs.arr[7]), ]} } } } } impl BitXor for u32x8 { type Output = Self; #[inline] #[must_use] fn bitxor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitxor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitxor_m128i(self.sse0, rhs.sse0) , sse1: bitxor_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitxor(rhs.arr[0]), self.arr[1].bitxor(rhs.arr[1]), self.arr[2].bitxor(rhs.arr[2]), self.arr[3].bitxor(rhs.arr[3]), self.arr[4].bitxor(rhs.arr[4]), self.arr[5].bitxor(rhs.arr[5]), self.arr[6].bitxor(rhs.arr[6]), self.arr[7].bitxor(rhs.arr[7]), ]} } } } } macro_rules! impl_shl_t_for_u32x8 { ($($shift_type:ty),+ $(,)?) => { $(impl Shl<$shift_type> for u32x8 { type Output = Self; #[inline] #[must_use] fn shl(self, rhs: $shift_type) -> Self::Output { let u = rhs as u64; pick! { if #[cfg(target_feature="avx2")] { let shift = cast([u, 0]); Self { avx2: shl_all_u32_m256i(self.avx2, shift) } } else if #[cfg(target_feature="ssse3")] { let shift = cast([u, 0]); Self { sse0: shl_all_u32_m128i(self.sse0, shift) , sse1: shl_all_u32_m128i(self.sse1, shift)} } else { Self { arr: [ self.arr[0] << u, self.arr[1] << u, self.arr[2] << u, self.arr[3] << u, self.arr[4] << u, self.arr[5] << u, self.arr[6] << u, self.arr[7] << u, ]} } } } })+ }; } impl_shl_t_for_u32x8!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); macro_rules! impl_shr_t_for_u32x8 { ($($shift_type:ty),+ $(,)?) => { $(impl Shr<$shift_type> for u32x8 { type Output = Self; #[inline] #[must_use] fn shr(self, rhs: $shift_type) -> Self::Output { let u = rhs as u64; pick! { if #[cfg(target_feature="avx2")] { let shift = cast([u, 0]); Self { avx2: shr_all_u32_m256i(self.avx2, shift) } } else if #[cfg(target_feature="ssse3")] { let shift = cast([u, 0]); Self { sse0: shr_all_u32_m128i(self.sse0, shift) , sse1: shr_all_u32_m128i(self.sse1, shift)} } else { Self { arr: [ self.arr[0] >> u, self.arr[1] >> u, self.arr[2] >> u, self.arr[3] >> u, self.arr[4] >> u, self.arr[5] >> u, self.arr[6] >> u, self.arr[7] >> u, ]} } } } })+ }; } impl_shr_t_for_u32x8!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); impl u32x8 { #[inline] #[must_use] pub fn cmp_eq(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_eq_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_eq_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_eq_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] == rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] == rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] == rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] == rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] == rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] == rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] == rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] == rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn cmp_gt(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_gt_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_gt_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_gt_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] > rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] > rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] > rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] > rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] > rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] > rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] > rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] > rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn cmp_lt(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_eq_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_lt_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_lt_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] < rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] < rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] < rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] < rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] < rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] < rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] < rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] < rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn blend(self, t: Self, f: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: blend_varying_i8_m256i(f.avx2, t.avx2, self.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: blend_varying_i8_m128i(f.sse0, t.sse0, self.sse0) , sse1: blend_varying_i8_m128i(f.sse1, t.sse1, self.sse1)} } else { generic_bit_blend(self, t, f) } } } #[inline] #[must_use] pub fn max(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: max_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: max_i32_m128i(self.sse0, rhs.sse0), sse1: max_i32_m128i(self.sse1, rhs.sse1) } } else { self.cmp_lt(rhs).blend(rhs, self) } } } #[inline] #[must_use] pub fn min(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: max_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: max_i32_m128i(self.sse0, rhs.sse0), sse1: max_i32_m128i(self.sse1, rhs.sse1) } } else { self.cmp_lt(rhs).blend(self, rhs) } } } } impl Not for u32x8 { type Output = Self; fn not(self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: self.avx2.not() } } else if #[cfg(target_feature="ssse3")] { Self { sse0: self.sse0.not() , sse1: self.sse1.not() } } else { Self { arr: [ !self.arr[0], !self.arr[1], !self.arr[2], !self.arr[3], !self.arr[4], !self.arr[5], !self.arr[6], !self.arr[7], ]} } } } }
use super::*; pick! { if #[cfg(target_feature="avx2")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { avx2: m256i } } else if #[cfg(target_feature="ssse3")] { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { sse0: m128i, sse1: m128i } } else { #[derive(Default, Clone, Copy, PartialEq, Eq)] #[repr(C, align(32))] pub struct u32x8 { arr: [u32;8] } } } unsafe impl Zeroable for u32x8 {} unsafe impl Pod for u32x8 {} impl Add for u32x8 { type Output = Self; #[inline] #[must_use] fn add(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: add_i32_m256i(
} impl Sub for u32x8 { type Output = Self; #[inline] #[must_use] fn sub(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: sub_i32_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: sub_i32_m128i(self.sse0, rhs.sse0) , sse1: sub_i32_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].wrapping_sub(rhs.arr[0]), self.arr[1].wrapping_sub(rhs.arr[1]), self.arr[2].wrapping_sub(rhs.arr[2]), self.arr[3].wrapping_sub(rhs.arr[3]), self.arr[4].wrapping_sub(rhs.arr[4]), self.arr[5].wrapping_sub(rhs.arr[5]), self.arr[6].wrapping_sub(rhs.arr[6]), self.arr[7].wrapping_sub(rhs.arr[7]), ]} } } } } impl Mul for u32x8 { type Output = Self; #[inline] #[must_use] fn mul(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: mul_i32_keep_low_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: mul_i32_keep_low_m128i(self.sse0, rhs.sse0) , sse1: mul_i32_keep_low_m128i(self.sse1, rhs.sse1)} } else { let arr1: [u32; 8] = cast(self); let arr2: [u32; 8] = cast(rhs); cast([ arr1[0].wrapping_mul(arr2[0]), arr1[1].wrapping_mul(arr2[1]), arr1[2].wrapping_mul(arr2[2]), arr1[3].wrapping_mul(arr2[3]), arr1[4].wrapping_mul(arr2[4]), arr1[5].wrapping_mul(arr2[5]), arr1[6].wrapping_mul(arr2[6]), arr1[7].wrapping_mul(arr2[7]), ]) } } } } impl BitAnd for u32x8 { type Output = Self; #[inline] #[must_use] fn bitand(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitand_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitand_m128i(self.sse0, rhs.sse0) , sse1: bitand_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitand(rhs.arr[0]), self.arr[1].bitand(rhs.arr[1]), self.arr[2].bitand(rhs.arr[2]), self.arr[3].bitand(rhs.arr[3]), self.arr[4].bitand(rhs.arr[4]), self.arr[5].bitand(rhs.arr[5]), self.arr[6].bitand(rhs.arr[6]), self.arr[7].bitand(rhs.arr[7]), ]} } } } } impl BitOr for u32x8 { type Output = Self; #[inline] #[must_use] fn bitor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitor_m128i(self.sse0, rhs.sse0) , sse1: bitor_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitor(rhs.arr[0]), self.arr[1].bitor(rhs.arr[1]), self.arr[2].bitor(rhs.arr[2]), self.arr[3].bitor(rhs.arr[3]), self.arr[4].bitor(rhs.arr[4]), self.arr[5].bitor(rhs.arr[5]), self.arr[6].bitor(rhs.arr[6]), self.arr[7].bitor(rhs.arr[7]), ]} } } } } impl BitXor for u32x8 { type Output = Self; #[inline] #[must_use] fn bitxor(self, rhs: Self) -> Self::Output { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: bitxor_m256i(self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: bitxor_m128i(self.sse0, rhs.sse0) , sse1: bitxor_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].bitxor(rhs.arr[0]), self.arr[1].bitxor(rhs.arr[1]), self.arr[2].bitxor(rhs.arr[2]), self.arr[3].bitxor(rhs.arr[3]), self.arr[4].bitxor(rhs.arr[4]), self.arr[5].bitxor(rhs.arr[5]), self.arr[6].bitxor(rhs.arr[6]), self.arr[7].bitxor(rhs.arr[7]), ]} } } } } macro_rules! impl_shl_t_for_u32x8 { ($($shift_type:ty),+ $(,)?) => { $(impl Shl<$shift_type> for u32x8 { type Output = Self; #[inline] #[must_use] fn shl(self, rhs: $shift_type) -> Self::Output { let u = rhs as u64; pick! { if #[cfg(target_feature="avx2")] { let shift = cast([u, 0]); Self { avx2: shl_all_u32_m256i(self.avx2, shift) } } else if #[cfg(target_feature="ssse3")] { let shift = cast([u, 0]); Self { sse0: shl_all_u32_m128i(self.sse0, shift) , sse1: shl_all_u32_m128i(self.sse1, shift)} } else { Self { arr: [ self.arr[0] << u, self.arr[1] << u, self.arr[2] << u, self.arr[3] << u, self.arr[4] << u, self.arr[5] << u, self.arr[6] << u, self.arr[7] << u, ]} } } } })+ }; } impl_shl_t_for_u32x8!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); macro_rules! impl_shr_t_for_u32x8 { ($($shift_type:ty),+ $(,)?) => { $(impl Shr<$shift_type> for u32x8 { type Output = Self; #[inline] #[must_use] fn shr(self, rhs: $shift_type) -> Self::Output { let u = rhs as u64; pick! { if #[cfg(target_feature="avx2")] { let shift = cast([u, 0]); Self { avx2: shr_all_u32_m256i(self.avx2, shift) } } else if #[cfg(target_feature="ssse3")] { let shift = cast([u, 0]); Self { sse0: shr_all_u32_m128i(self.sse0, shift) , sse1: shr_all_u32_m128i(self.sse1, shift)} } else { Self { arr: [ self.arr[0] >> u, self.arr[1] >> u, self.arr[2] >> u, self.arr[3] >> u, self.arr[4] >> u, self.arr[5] >> u, self.arr[6] >> u, self.arr[7] >> u, ]} } } } })+ }; } impl_shr_t_for_u32x8!(i8, u8, i16, u16, i32, u32, i64, u64, i128, u128); impl u32x8 { #[inline] #[must_use] pub fn cmp_eq(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_eq_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_eq_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_eq_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] == rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] == rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] == rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] == rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] == rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] == rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] == rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] == rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn cmp_gt(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_gt_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_gt_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_gt_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] > rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] > rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] > rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] > rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] > rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] > rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] > rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] > rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn cmp_lt(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: cmp_eq_mask_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: cmp_lt_mask_i32_m128i(self.sse0,rhs.sse0), sse1: cmp_lt_mask_i32_m128i(self.sse1,rhs.sse1), } } else { Self { arr: [ if self.arr[0] < rhs.arr[0] { u32::MAX } else { 0 }, if self.arr[1] < rhs.arr[1] { u32::MAX } else { 0 }, if self.arr[2] < rhs.arr[2] { u32::MAX } else { 0 }, if self.arr[3] < rhs.arr[3] { u32::MAX } else { 0 }, if self.arr[4] < rhs.arr[4] { u32::MAX } else { 0 }, if self.arr[5] < rhs.arr[5] { u32::MAX } else { 0 }, if self.arr[6] < rhs.arr[6] { u32::MAX } else { 0 }, if self.arr[7] < rhs.arr[7] { u32::MAX } else { 0 }, ]} } } } #[inline] #[must_use] pub fn blend(self, t: Self, f: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: blend_varying_i8_m256i(f.avx2, t.avx2, self.avx2) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: blend_varying_i8_m128i(f.sse0, t.sse0, self.sse0) , sse1: blend_varying_i8_m128i(f.sse1, t.sse1, self.sse1)} } else { generic_bit_blend(self, t, f) } } } #[inline] #[must_use] pub fn max(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: max_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: max_i32_m128i(self.sse0, rhs.sse0), sse1: max_i32_m128i(self.sse1, rhs.sse1) } } else { self.cmp_lt(rhs).blend(rhs, self) } } } #[inline] #[must_use] pub fn min(self, rhs: Self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: max_i32_m256i(self.avx2, rhs.avx2 ) } } else if #[cfg(target_feature="sse4.1")] { Self { sse0: max_i32_m128i(self.sse0, rhs.sse0), sse1: max_i32_m128i(self.sse1, rhs.sse1) } } else { self.cmp_lt(rhs).blend(self, rhs) } } } } impl Not for u32x8 { type Output = Self; fn not(self) -> Self { pick! { if #[cfg(target_feature="avx2")] { Self { avx2: self.avx2.not() } } else if #[cfg(target_feature="ssse3")] { Self { sse0: self.sse0.not() , sse1: self.sse1.not() } } else { Self { arr: [ !self.arr[0], !self.arr[1], !self.arr[2], !self.arr[3], !self.arr[4], !self.arr[5], !self.arr[6], !self.arr[7], ]} } } } }
self.avx2, rhs.avx2) } } else if #[cfg(target_feature="ssse3")] { Self { sse0: add_i32_m128i(self.sse0, rhs.sse0) , sse1: add_i32_m128i(self.sse1, rhs.sse1)} } else { Self { arr: [ self.arr[0].wrapping_add(rhs.arr[0]), self.arr[1].wrapping_add(rhs.arr[1]), self.arr[2].wrapping_add(rhs.arr[2]), self.arr[3].wrapping_add(rhs.arr[3]), self.arr[4].wrapping_add(rhs.arr[4]), self.arr[5].wrapping_add(rhs.arr[5]), self.arr[6].wrapping_add(rhs.arr[6]), self.arr[7].wrapping_add(rhs.arr[7]), ]} } } }
function_block-function_prefixed
[ { "content": "#[test]\n\nfn impl_add_for_u32x8() {\n\n let a = u32x8::from([1, 2, u32::MAX - 1, u32::MAX - 1, 31, 72, 13, 53]);\n\n let b = u32x8::from([17, 18, 1, 2, 12, 12, 634, 15]);\n\n let expected = u32x8::from([18, 20, u32::MAX, u32::MIN, 43, 84, 647, 68]);\n\n let actual = a + b;\n\n assert_eq!(exp...
Rust
src/async/session.rs
reachkrr/serverless-wasm
0e521adc782a002aa1beae56d3661a88322d75e3
use mio::unix::UnixReady; use mio::net::TcpStream; use mio::{Poll, Ready}; use std::collections::HashMap; use std::iter::repeat; use std::rc::Rc; use std::io::{ErrorKind, Read, Write}; use std::cell::RefCell; use std::net::{SocketAddr, Shutdown}; use slab::Slab; use interpreter::WasmInstance; use super::host; use config::ApplicationState; use httparse; use wasmi::{ExternVal, ImportsBuilder, ModuleInstance, TrapKind, RuntimeValue}; #[derive(Debug, Clone, PartialEq)] pub enum ExecutionResult { WouldBlock, Close(Vec<usize>), Continue, ConnectBackend(SocketAddr), } #[derive(Debug)] pub struct Stream { pub readiness: UnixReady, pub interest: UnixReady, pub stream: TcpStream, pub index: usize, } pub struct Buf { buf: Vec<u8>, offset: usize, len: usize, } #[derive(Debug,Clone,PartialEq)] pub enum SessionState { WaitingForRequest, WaitingForBackendConnect(usize), TcpRead(i32, u32, usize), TcpWrite(i32, Vec<u8>, usize), Executing, Done, } pub struct Session { client: Stream, backends: HashMap<usize, Stream>, instance: Option<WasmInstance<host::State, host::AsyncHost>>, config: Rc<RefCell<ApplicationState>>, buffer: Buf, pub state: Option<SessionState>, method: Option<String>, path: Option<String>, env: Option<Rc<RefCell<host::State>>>, } impl Session { pub fn new(config: Rc<RefCell<ApplicationState>>, stream: TcpStream, index: usize) -> Session { let client = Stream { readiness: UnixReady::from(Ready::empty()), interest: UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error(), stream, index, }; let capacity = 8192; let mut v = Vec::with_capacity(capacity); v.extend(repeat(0).take(capacity)); let buffer = Buf { buf: v, offset: 0, len: 0, }; Session { client, backends: HashMap::new(), instance: None, config, buffer, state: Some(SessionState::WaitingForRequest), method: None, path: None, env: None, } } pub fn add_backend(&mut self, stream: TcpStream, index: usize) { let s = Stream { readiness: UnixReady::from(Ready::empty()), interest: UnixReady::from(Ready::writable()) | UnixReady::hup() | UnixReady::error(), stream, index, }; self.backends.insert(index, s); self.state = Some(SessionState::WaitingForBackendConnect(index)); } pub fn resume(&mut self) -> ExecutionResult { let res = self.instance.as_mut().map(|instance| instance.resume()).unwrap(); println!("resume result: {:?}", res); match res { Err(t) => match t.kind() { TrapKind::Host(ref err) => { match err.as_ref().downcast_ref() { Some(host::AsyncHostError::Connecting(address)) => { println!("returning connect to backend server: {}", address); return ExecutionResult::ConnectBackend(address.clone()); }, Some(host::AsyncHostError::TcpWrite(fd, ptr, sz, written)) => { self.backends.get_mut(&(*fd as usize)).map(|backend| backend.interest.insert(UnixReady::from(Ready::writable()))); let buf = self.env.as_mut().and_then(|env| env.borrow_mut().get_buf(*ptr, *sz as usize)).unwrap(); self.state = Some(SessionState::TcpWrite(*fd, buf, *written)); return ExecutionResult::Continue; }, Some(host::AsyncHostError::TcpRead(fd, ptr, sz)) => { self.backends.get_mut(&(*fd as usize)).map(|backend| backend.interest.insert(UnixReady::from(Ready::readable()))); self.state = Some(SessionState::TcpRead(*fd, *ptr, *sz as usize)); return ExecutionResult::Continue; }, _ => { panic!("got host error: {:?}", err) } } }, _ => { panic!("got trap: {:?}", t); } }, Ok(_) => if self .instance .as_mut() .map(|instance| { println!( "set up response: {:?}", instance.state.borrow().prepared_response ); instance .state .borrow() .prepared_response .status_code .is_some() && instance.state.borrow().prepared_response.body.is_some() }) .unwrap_or(false) { self.client.interest.insert(Ready::writable()); return ExecutionResult::Continue } } ExecutionResult::Continue } pub fn create_instance(&mut self) -> ExecutionResult { let method = self.method.as_ref().unwrap(); let path = self.path.as_ref().unwrap(); if let Some((func_name, module, ref opt_env)) = self.config.borrow().route(method, path) { let mut env = host::State::new(); if let Some(h) = opt_env { env.db.extend( h.iter() .map(|(ref k, ref v)| (k.to_string(), v.to_string())), ); } let env = Rc::new(RefCell::new(env)); self.env = Some(env.clone()); let resolver = host::StateResolver { inner: env.clone() }; let main = ModuleInstance::new(&module, &ImportsBuilder::new().with_resolver("env", &resolver)) .expect("Failed to instantiate module") .assert_no_start(); if let Some(ExternVal::Func(func_ref)) = main.export_by_name(func_name) { let instance = WasmInstance::new(env, &func_ref, &[]); self.instance = Some(instance); ExecutionResult::Continue } else { println!("function not found"); self .client .stream .write(b"HTTP/1.1 404 Not Found\r\nContent-length: 19\r\n\r\nFunction not found\n"); self.client.stream.shutdown(Shutdown::Both); self.client.interest = UnixReady::from(Ready::empty()); ExecutionResult::Close(vec![self.client.index]) } } else { println!("route not found"); self .client .stream .write(b"HTTP/1.1 404 Not Found\r\nContent-length: 16\r\n\r\nRoute not found\n"); self.client.stream.shutdown(Shutdown::Both); self.client.interest = UnixReady::from(Ready::empty()); ExecutionResult::Close(vec![self.client.index]) } } pub fn process_events(&mut self, token: usize, events: Ready) -> bool { println!("client[{}]: token {} got events {:?}", self.client.index, token, events); if token == self.client.index { self.client.readiness = self.client.readiness | UnixReady::from(events); self.client.readiness & self.client.interest != UnixReady::from(Ready::empty()) } else { if let Some(ref mut stream) = self.backends.get_mut(&token) { println!("state: {:?}", self.state); if self.state == Some(SessionState::WaitingForBackendConnect(token)) { self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I32(token as i32))); self.state = Some(SessionState::Executing); } stream.readiness.insert(UnixReady::from(events)); stream.readiness & stream.interest != UnixReady::from(Ready::empty()) } else { println!("non existing backend {} got events {:?}", token, events); false } } } pub fn execute(&mut self) -> ExecutionResult { loop { let front_readiness = self.client.readiness & self.client.interest; if front_readiness.is_readable() { let res = self.front_readable(); if res != ExecutionResult::Continue { return res; } } if front_readiness.is_writable() { let res = self.front_writable(); if res != ExecutionResult::Continue { return res; } } let res = self.process(); if res != ExecutionResult::Continue { return res; } } } fn front_readable(&mut self) -> ExecutionResult { if self.state == Some(SessionState::WaitingForRequest) { loop { if self.buffer.offset + self.buffer.len == self.buffer.buf.len() { break; } match self .client .stream .read(&mut self.buffer.buf[self.buffer.offset + self.buffer.len..]) { Ok(0) => { return ExecutionResult::Close(vec![self.client.index]); } Ok(sz) => { self.buffer.len += sz; } Err(e) => { if e.kind() == ErrorKind::WouldBlock { self.client.readiness.remove(Ready::readable()); break; } } } } ExecutionResult::Continue } else { ExecutionResult::Close(vec![self.client.index]) } } fn process(&mut self) -> ExecutionResult { println!("[{}] process", self.client.index); let state = self.state.take().unwrap(); match state { SessionState::WaitingForRequest => { let (method, path) = { let mut headers = [httparse::Header { name: "", value: &[], }; 16]; let mut req = httparse::Request::new(&mut headers); match req.parse(&self.buffer.buf[self.buffer.offset..self.buffer.len]) { Err(e) => { println!("http parsing error: {:?}", e); self.state = Some(SessionState::WaitingForRequest); return ExecutionResult::Close(vec![self.client.index]); } Ok(httparse::Status::Partial) => { self.state = Some(SessionState::WaitingForRequest); return ExecutionResult::Continue; } Ok(httparse::Status::Complete(sz)) => { self.buffer.offset += sz; println!("got request: {:?}", req); ( req.method.unwrap().to_string(), req.path.unwrap().to_string(), ) } } }; self.client.interest.remove(Ready::readable()); self.method = Some(method); self.path = Some(path); self.state = Some(SessionState::Executing); ExecutionResult::Continue }, SessionState::Executing => { if self.instance.is_none() { let res = self.create_instance(); if res != ExecutionResult::Continue { self.state = Some(SessionState::Executing); return res; } } println!("resuming"); self.state = Some(SessionState::Executing); self.resume() }, SessionState::TcpRead(fd, ptr, sz) => { let readiness = self.backends[&(fd as usize)].readiness & self.backends[&(fd as usize)].interest; println!("tcpread({}): readiness: {:?}", fd, readiness); if readiness.is_readable() { let mut buffer = Vec::with_capacity(sz as usize); buffer.extend(repeat(0).take(sz as usize)); let mut read = 0usize; loop { match self.backends.get_mut(&(fd as usize)).unwrap().stream.read(&mut buffer[read..]) { Ok(0) => { println!("read 0"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::readable())); self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, Ok(sz) => { read += sz; println!("read {} bytes", read); if read == sz { self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } }, Err(e) => match e.kind() { ErrorKind::WouldBlock => { println!("wouldblock"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::readable())); self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, e => { println!("backend socket error: {:?}", e); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(-1))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } } } } } else { self.state = Some(SessionState::TcpRead(fd, ptr, sz)); ExecutionResult::WouldBlock } }, SessionState::TcpWrite(fd, buffer, mut written) => { let readiness = self.backends[&(fd as usize)].readiness & self.backends[&(fd as usize)].interest; if readiness.is_writable() { loop { match self.backends.get_mut(&(fd as usize)).unwrap().stream.write(&buffer[written..]) { Ok(0) => { self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::writable())); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(written as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, Ok(sz) => { written += sz; println!("wrote {} bytes", sz); if written == buffer.len() { self.state = Some(SessionState::Executing); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(written as i64))); return ExecutionResult::Continue; } }, Err(e) => match e.kind() { ErrorKind::WouldBlock => { println!("wouldblock"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::writable())); self.state = Some(SessionState::TcpWrite(fd, buffer, written)); return ExecutionResult::Continue; }, e => { println!("backend socket error: {:?}", e); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(-1))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } } } } } else { self.state = Some(SessionState::TcpWrite(fd, buffer, written)); ExecutionResult::WouldBlock } }, SessionState::WaitingForBackendConnect(_) => { panic!("should not have called execute() in WaitingForBackendConnect"); }, SessionState::Done => { panic!("done"); } } } fn front_writable(&mut self) -> ExecutionResult { println!("[{}] front writable", self.client.index); let response = self .instance .as_mut() .map(|instance| instance.state.borrow().prepared_response.clone()) .unwrap(); self .client .stream .write_fmt(format_args!("HTTP/1.1 {} {}\r\n", response.status_code.unwrap(), response.reason.unwrap())); for header in response.headers.iter() { self .client .stream .write_fmt(format_args!("{}: {}\r\n", header.0, header.1)); } self.client.stream.write(b"\r\n"); self.client.stream.write(&response.body.unwrap()[..]); ExecutionResult::Close(vec![self.client.index]) } }
use mio::unix::UnixReady; use mio::net::TcpStream; use mio::{Poll, Ready}; use std::collections::HashMap; use std::iter::repeat; use std::rc::Rc; use std::io::{ErrorKind, Read, Write}; use std::cell::RefCell; use std::net::{SocketAddr, Shutdown}; use slab::Slab; use interpreter::WasmInstance; use super::host; use config::ApplicationState; use httparse; use wasmi::{ExternVal, ImportsBuilder, ModuleInstance, TrapKind, RuntimeValue}; #[derive(Debug, Clone, PartialEq)] pub enum ExecutionResult { WouldBlock, Close(Vec<usize>), Continue, ConnectBackend(SocketAddr), } #[derive(Debug)] pub struct Stream { pub readiness: UnixReady, pub interest: UnixReady, pub stream: TcpStream, pub index: usize, } pub struct Buf { buf: Vec<u8>, offset: usize, len: usize, } #[derive(Debug,Clone,PartialEq)] pub enum SessionState { WaitingForRequest, WaitingForBackendConnect(usize), TcpRead(i32, u32, usize), TcpWrite(i32, Vec<u8>, usize), Executing, Done, } pub struct Session { client: Stream, backends: HashMap<usize, Stream>, instance: Option<WasmInstance<host::State, host::AsyncHost>>, config: Rc<RefCell<ApplicationState>>, buffer: Buf, pub state: Option<SessionState>, method: Option<String>, path: Option<String>, env: Option<Rc<RefCell<host::State>>>, } impl Session { pub fn new(config: Rc<RefCell<ApplicationState>>, stream: TcpStream, index: usize) -> Session { let client = Stream { readiness: UnixReady::from(Ready::empty()), interest: UnixReady::from(Ready::readable()) | UnixReady::hup() | UnixReady::error(), stream, index, }; let capacity = 8192; let mut v = Vec::with_capacity(capacity); v.extend(repeat(0).take(capacity)); let buffer = Buf { buf: v, offset: 0, len: 0, }; Session { client, b
pub fn add_backend(&mut self, stream: TcpStream, index: usize) { let s = Stream { readiness: UnixReady::from(Ready::empty()), interest: UnixReady::from(Ready::writable()) | UnixReady::hup() | UnixReady::error(), stream, index, }; self.backends.insert(index, s); self.state = Some(SessionState::WaitingForBackendConnect(index)); } pub fn resume(&mut self) -> ExecutionResult { let res = self.instance.as_mut().map(|instance| instance.resume()).unwrap(); println!("resume result: {:?}", res); match res { Err(t) => match t.kind() { TrapKind::Host(ref err) => { match err.as_ref().downcast_ref() { Some(host::AsyncHostError::Connecting(address)) => { println!("returning connect to backend server: {}", address); return ExecutionResult::ConnectBackend(address.clone()); }, Some(host::AsyncHostError::TcpWrite(fd, ptr, sz, written)) => { self.backends.get_mut(&(*fd as usize)).map(|backend| backend.interest.insert(UnixReady::from(Ready::writable()))); let buf = self.env.as_mut().and_then(|env| env.borrow_mut().get_buf(*ptr, *sz as usize)).unwrap(); self.state = Some(SessionState::TcpWrite(*fd, buf, *written)); return ExecutionResult::Continue; }, Some(host::AsyncHostError::TcpRead(fd, ptr, sz)) => { self.backends.get_mut(&(*fd as usize)).map(|backend| backend.interest.insert(UnixReady::from(Ready::readable()))); self.state = Some(SessionState::TcpRead(*fd, *ptr, *sz as usize)); return ExecutionResult::Continue; }, _ => { panic!("got host error: {:?}", err) } } }, _ => { panic!("got trap: {:?}", t); } }, Ok(_) => if self .instance .as_mut() .map(|instance| { println!( "set up response: {:?}", instance.state.borrow().prepared_response ); instance .state .borrow() .prepared_response .status_code .is_some() && instance.state.borrow().prepared_response.body.is_some() }) .unwrap_or(false) { self.client.interest.insert(Ready::writable()); return ExecutionResult::Continue } } ExecutionResult::Continue } pub fn create_instance(&mut self) -> ExecutionResult { let method = self.method.as_ref().unwrap(); let path = self.path.as_ref().unwrap(); if let Some((func_name, module, ref opt_env)) = self.config.borrow().route(method, path) { let mut env = host::State::new(); if let Some(h) = opt_env { env.db.extend( h.iter() .map(|(ref k, ref v)| (k.to_string(), v.to_string())), ); } let env = Rc::new(RefCell::new(env)); self.env = Some(env.clone()); let resolver = host::StateResolver { inner: env.clone() }; let main = ModuleInstance::new(&module, &ImportsBuilder::new().with_resolver("env", &resolver)) .expect("Failed to instantiate module") .assert_no_start(); if let Some(ExternVal::Func(func_ref)) = main.export_by_name(func_name) { let instance = WasmInstance::new(env, &func_ref, &[]); self.instance = Some(instance); ExecutionResult::Continue } else { println!("function not found"); self .client .stream .write(b"HTTP/1.1 404 Not Found\r\nContent-length: 19\r\n\r\nFunction not found\n"); self.client.stream.shutdown(Shutdown::Both); self.client.interest = UnixReady::from(Ready::empty()); ExecutionResult::Close(vec![self.client.index]) } } else { println!("route not found"); self .client .stream .write(b"HTTP/1.1 404 Not Found\r\nContent-length: 16\r\n\r\nRoute not found\n"); self.client.stream.shutdown(Shutdown::Both); self.client.interest = UnixReady::from(Ready::empty()); ExecutionResult::Close(vec![self.client.index]) } } pub fn process_events(&mut self, token: usize, events: Ready) -> bool { println!("client[{}]: token {} got events {:?}", self.client.index, token, events); if token == self.client.index { self.client.readiness = self.client.readiness | UnixReady::from(events); self.client.readiness & self.client.interest != UnixReady::from(Ready::empty()) } else { if let Some(ref mut stream) = self.backends.get_mut(&token) { println!("state: {:?}", self.state); if self.state == Some(SessionState::WaitingForBackendConnect(token)) { self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I32(token as i32))); self.state = Some(SessionState::Executing); } stream.readiness.insert(UnixReady::from(events)); stream.readiness & stream.interest != UnixReady::from(Ready::empty()) } else { println!("non existing backend {} got events {:?}", token, events); false } } } pub fn execute(&mut self) -> ExecutionResult { loop { let front_readiness = self.client.readiness & self.client.interest; if front_readiness.is_readable() { let res = self.front_readable(); if res != ExecutionResult::Continue { return res; } } if front_readiness.is_writable() { let res = self.front_writable(); if res != ExecutionResult::Continue { return res; } } let res = self.process(); if res != ExecutionResult::Continue { return res; } } } fn front_readable(&mut self) -> ExecutionResult { if self.state == Some(SessionState::WaitingForRequest) { loop { if self.buffer.offset + self.buffer.len == self.buffer.buf.len() { break; } match self .client .stream .read(&mut self.buffer.buf[self.buffer.offset + self.buffer.len..]) { Ok(0) => { return ExecutionResult::Close(vec![self.client.index]); } Ok(sz) => { self.buffer.len += sz; } Err(e) => { if e.kind() == ErrorKind::WouldBlock { self.client.readiness.remove(Ready::readable()); break; } } } } ExecutionResult::Continue } else { ExecutionResult::Close(vec![self.client.index]) } } fn process(&mut self) -> ExecutionResult { println!("[{}] process", self.client.index); let state = self.state.take().unwrap(); match state { SessionState::WaitingForRequest => { let (method, path) = { let mut headers = [httparse::Header { name: "", value: &[], }; 16]; let mut req = httparse::Request::new(&mut headers); match req.parse(&self.buffer.buf[self.buffer.offset..self.buffer.len]) { Err(e) => { println!("http parsing error: {:?}", e); self.state = Some(SessionState::WaitingForRequest); return ExecutionResult::Close(vec![self.client.index]); } Ok(httparse::Status::Partial) => { self.state = Some(SessionState::WaitingForRequest); return ExecutionResult::Continue; } Ok(httparse::Status::Complete(sz)) => { self.buffer.offset += sz; println!("got request: {:?}", req); ( req.method.unwrap().to_string(), req.path.unwrap().to_string(), ) } } }; self.client.interest.remove(Ready::readable()); self.method = Some(method); self.path = Some(path); self.state = Some(SessionState::Executing); ExecutionResult::Continue }, SessionState::Executing => { if self.instance.is_none() { let res = self.create_instance(); if res != ExecutionResult::Continue { self.state = Some(SessionState::Executing); return res; } } println!("resuming"); self.state = Some(SessionState::Executing); self.resume() }, SessionState::TcpRead(fd, ptr, sz) => { let readiness = self.backends[&(fd as usize)].readiness & self.backends[&(fd as usize)].interest; println!("tcpread({}): readiness: {:?}", fd, readiness); if readiness.is_readable() { let mut buffer = Vec::with_capacity(sz as usize); buffer.extend(repeat(0).take(sz as usize)); let mut read = 0usize; loop { match self.backends.get_mut(&(fd as usize)).unwrap().stream.read(&mut buffer[read..]) { Ok(0) => { println!("read 0"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::readable())); self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, Ok(sz) => { read += sz; println!("read {} bytes", read); if read == sz { self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } }, Err(e) => match e.kind() { ErrorKind::WouldBlock => { println!("wouldblock"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::readable())); self.env.as_mut().map(|env| env.borrow_mut().write_buf(ptr, &buffer[..read])); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(read as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, e => { println!("backend socket error: {:?}", e); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(-1))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } } } } } else { self.state = Some(SessionState::TcpRead(fd, ptr, sz)); ExecutionResult::WouldBlock } }, SessionState::TcpWrite(fd, buffer, mut written) => { let readiness = self.backends[&(fd as usize)].readiness & self.backends[&(fd as usize)].interest; if readiness.is_writable() { loop { match self.backends.get_mut(&(fd as usize)).unwrap().stream.write(&buffer[written..]) { Ok(0) => { self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::writable())); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(written as i64))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; }, Ok(sz) => { written += sz; println!("wrote {} bytes", sz); if written == buffer.len() { self.state = Some(SessionState::Executing); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(written as i64))); return ExecutionResult::Continue; } }, Err(e) => match e.kind() { ErrorKind::WouldBlock => { println!("wouldblock"); self.backends.get_mut(&(fd as usize)).map(|backend| backend.readiness.remove(Ready::writable())); self.state = Some(SessionState::TcpWrite(fd, buffer, written)); return ExecutionResult::Continue; }, e => { println!("backend socket error: {:?}", e); self.instance.as_mut().map(|instance| instance.add_function_result(RuntimeValue::I64(-1))); self.state = Some(SessionState::Executing); return ExecutionResult::Continue; } } } } } else { self.state = Some(SessionState::TcpWrite(fd, buffer, written)); ExecutionResult::WouldBlock } }, SessionState::WaitingForBackendConnect(_) => { panic!("should not have called execute() in WaitingForBackendConnect"); }, SessionState::Done => { panic!("done"); } } } fn front_writable(&mut self) -> ExecutionResult { println!("[{}] front writable", self.client.index); let response = self .instance .as_mut() .map(|instance| instance.state.borrow().prepared_response.clone()) .unwrap(); self .client .stream .write_fmt(format_args!("HTTP/1.1 {} {}\r\n", response.status_code.unwrap(), response.reason.unwrap())); for header in response.headers.iter() { self .client .stream .write_fmt(format_args!("{}: {}\r\n", header.0, header.1)); } self.client.stream.write(b"\r\n"); self.client.stream.write(&response.body.unwrap()[..]); ExecutionResult::Close(vec![self.client.index]) } }
ackends: HashMap::new(), instance: None, config, buffer, state: Some(SessionState::WaitingForRequest), method: None, path: None, env: None, } }
function_block-function_prefixed
[ { "content": "pub fn server(config: Config) {\n\n let state = ApplicationState::new(&config);\n\n\n\n let addr = (&config.listen_address).parse().unwrap();\n\n let server = TcpListener::bind(&addr).unwrap();\n\n\n\n let mut poll = Poll::new().unwrap();\n\n\n\n poll\n\n .register(&server, SERVER, Ready::...
Rust
modules/world/tests/graph.rs
drunkenme/lemon3d-rs
48d4e879996e2502e0faaf36e4dbcebfca9961b0
extern crate crayon; extern crate crayon_world; extern crate rand; use crayon::prelude::*; use crayon::*; use crayon_world::prelude::*; use crayon_world::renderable::headless::HeadlessRenderer; #[test] pub fn hierachy() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e2, e1, false).unwrap(); assert!(scene.is_ancestor(e2, e1)); assert!(scene.is_ancestor(e3, e1)); assert!(scene.is_ancestor(e4, e1)); assert!(scene.is_ancestor(e4, e3)); assert!(!scene.is_ancestor(e1, e1)); assert!(!scene.is_ancestor(e1, e2)); assert!(!scene.is_ancestor(e1, e3)); assert!(!scene.is_ancestor(e1, e4)); assert!(!scene.is_ancestor(e2, e4)); assert!(scene.is_root(e1)); assert!(!scene.is_root(e2)); assert!(!scene.is_root(e3)); assert!(!scene.is_root(e4)); assert!(!scene.is_leaf(e1)); assert!(scene.is_leaf(e2)); assert!(!scene.is_leaf(e3)); assert!(scene.is_leaf(e4)); let point = [1.0, 0.0, 0.0]; scene.set_position(e3, point); assert_ulps_eq!(scene.position(e4).unwrap(), point.into()); let point = [1.0, 0.0, 2.0]; scene.set_position(e1, point); assert_ulps_eq!(scene.position(e4).unwrap(), [2.0, 0.0, 2.0].into()); assert_ulps_eq!(scene.local_position(e4).unwrap(), [0.0, 0.0, 0.0].into()); scene.set_parent(e4, Some(e2), false).unwrap(); assert_ulps_eq!(scene.position(e4).unwrap(), [1.0, 0.0, 2.0].into()); assert_ulps_eq!(scene.local_position(e4).unwrap(), [0.0, 0.0, 0.0].into()); scene.set_local_position(e2, [1.0, 0.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(90.0), Deg(0.0)); scene.set_rotation(e1, euler); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 0.0, 1.0].into()); } #[test] fn remove() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); let e5 = scene.create("e5"); let e6 = scene.create("e6"); scene.set_parent(e2, e1, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e5, e3, false).unwrap(); scene.set_parent(e6, e5, false).unwrap(); assert!(scene.len() == 6); scene.delete(e3); assert!(scene.contains(e1)); assert!(scene.contains(e2)); assert!(!scene.contains(e3)); assert!(!scene.contains(e4)); assert!(!scene.contains(e5)); assert!(!scene.contains(e6)); assert!(scene.len() == 2); } #[test] fn transform() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); scene.set_scale(e1, 2.0); scene.set_position(e1, [1.0, 0.0, 2.0]); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(90.0)); let rotation = Quaternion::from(euler); scene.set_rotation(e1, rotation); let v = [1.0, 0.0, 0.0]; let transform = scene.transform(e1).unwrap(); assert_ulps_eq!(transform.transform_direction(v), [0.0, 1.0, 0.0].into()); assert_ulps_eq!(transform.transform_vector(v), [0.0, 2.0, 0.0].into()); assert_ulps_eq!(transform.transform_point(v), [1.0, 2.0, 2.0].into()); } #[test] fn keep_world_pose() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); scene.set_position(e1, [0.0, 1.0, 0.0]); assert_ulps_eq!(scene.position(e1).unwrap(), [0.0, 1.0, 0.0].into()); assert_ulps_eq!(scene.local_position(e1).unwrap(), [0.0, 1.0, 0.0].into()); scene.set_position(e2, [1.0, 0.0, 0.0]); scene.set_position(e3, [0.0, 0.0, 1.0]); scene.set_parent(e2, e1, false).unwrap(); assert_ulps_eq!(scene.local_position(e2).unwrap(), [1.0, 0.0, 0.0].into()); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 1.0, 0.0].into()); scene.remove_from_parent(e2, true).unwrap(); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 1.0, 0.0].into()); scene.set_parent(e3, e1, true).unwrap(); assert_ulps_eq!(scene.local_position(e3).unwrap(), [0.0, -1.0, 1.0].into()); assert_ulps_eq!(scene.position(e3).unwrap(), [0.0, 0.0, 1.0].into()); scene.remove_from_parent(e3, false).unwrap(); assert_ulps_eq!(scene.position(e3).unwrap(), [0.0, -1.0, 1.0].into()); } #[test] fn look_at() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [0.0, 0.0, -5.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [0.0, 0.0, 5.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(180.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [1.0, 0.0, 1.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(225.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); } #[test] fn iteration() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); let e5 = scene.create("e5"); let e6 = scene.create("e6"); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e2, e1, false).unwrap(); scene.set_parent(e6, e4, false).unwrap(); scene.set_parent(e5, e4, false).unwrap(); assert_eq!( scene.descendants(e1).collect::<Vec<_>>(), [e2, e3, e4, e5, e6] ); assert_eq!(scene.children(e1).collect::<Vec<_>>(), [e2, e3]); assert_eq!(scene.ancestors(e1).collect::<Vec<_>>(), []); assert_eq!(scene.ancestors(e2).collect::<Vec<_>>(), [e1]); assert_eq!(scene.ancestors(e4).collect::<Vec<_>>(), [e3, e1]); assert_eq!(scene.ancestors(e6).collect::<Vec<_>>(), [e4, e3, e1]); } #[test] fn random_iteration() { let mut scene = Scene::new(HeadlessRenderer::new()); let mut nodes = vec![]; for _ in 0..255 { nodes.push(scene.create("")); } let mut constructed = vec![]; constructed.push(nodes.pop().unwrap()); let mut count = 0; for i in 0..254 { let idx = rand::random::<usize>() % nodes.len(); let pidx = rand::random::<usize>() % constructed.len(); if pidx == 0 { count += 1; } scene .set_parent(nodes[idx], constructed[pidx], false) .unwrap(); let len = scene.descendants(constructed[0]).count(); assert_eq!(len, i + 1); constructed.push(nodes[idx]); nodes.remove(idx); } let len = scene.children(constructed[0]).count(); assert_eq!(len, count); let len = scene.descendants(constructed[0]).count(); assert_eq!(len, 254); }
extern crate crayon; extern crate crayon_world; extern crate rand; use crayon::prelude::*; use crayon::*; use crayon_world::prelude::*; use crayon_world::renderable::headless::HeadlessRenderer; #[test] pub fn hierachy() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e2, e1, false).unwrap(); assert!(scene.is_ancestor(e2, e1)); assert!(scene.is_ancestor(e3, e1)); assert!(scene.is_ancestor(e4, e1)); assert!(scene.is_ancestor(e4, e3)); assert!(!scene.is_ancestor(e1, e1)); assert!(!scene.is_ancestor(e1, e2)); assert!(!scene.is_ancestor(e1, e3)); assert!(!scene.is_ancestor(e1, e4)); assert!(!scene.is_ancestor(e2, e4)); assert!(scene.is_root(e1)); assert!(!scene.is_root(e2)); assert!(!scene.is_root(e3)); assert!(!scene.is_root(e4)); assert!(!scene.is_leaf(e1)); assert!(scene.is_leaf(e2)); assert!(!scene.is_leaf(e3)); assert!(scene.is_leaf(e4)); let point = [1.0, 0.0, 0.0]; scene.set_position(e3, point); assert_ulps_eq!(scene.position(e4).unwrap(), point.into()); let point = [1.0, 0.0, 2.0]; scene.set_position(e1, point); assert_ulps_eq!(scene.position(e4).unwrap(), [2.0, 0.0, 2.0].into()); assert_ulps_eq!(scene.local_position(e4).unwrap(), [0.0, 0.0, 0.0].into()); scene.set_parent(e4, Some(e2), false).unwrap(); assert_ulps_eq!(scene.position(e4).unwrap(), [1.0, 0.0, 2.0].into()); assert_ulps_eq!(scene.local_position(e4).unwrap(), [0.0, 0.0, 0.0].into()); scene.set_local_position(e2, [1.0, 0.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(90.0), Deg(0.0)); scene.set_rotation(e1, euler); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 0.0, 1.0].into()); } #[test] fn remove() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); let e5 = scene.create("e5"); let e6 = scene.create("e6"); scene.set_parent(e2, e1, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e5, e3, false).unwrap(); scene.set_parent(e6, e5, false).unwrap(); assert!(scene.len() == 6); scene.delete(e3); assert!(scene.contains(e1)); assert!(scene.contains(e2)); assert!(!scene.contains(e3)); assert!(!scene.contains(e4)); assert!(!scene.contains(e5)); assert!(!scene.contains(e6)); assert!(scene.len() == 2); } #[test] fn transform() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); scene.set_scale(e1, 2.0); scene.set_position(e1, [1.0, 0.0, 2.0]); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(90.0)); let rotation = Quaternion::from(euler); scene.set_rotation(e1, rotation); let v = [1.0, 0.0, 0.0]; let transform = scene.transform(e1).unwrap(); assert_ulps_eq!(transform.transform_direction(v), [0.0, 1.0, 0.0].into()); assert_ulps_eq!(transform.transform_vector(v), [0.0, 2.0, 0.0].into()); assert_ulps_eq!(transform.transform_point(v), [1.0, 2.0, 2.0].into()); } #[test] fn keep_world_pose() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); scene.set_position(e1, [0.0, 1.0, 0.0]); assert_ulps_eq!(scene.position(e1).unwrap(), [0.0, 1.0, 0.0].into()); assert_ulps_eq!(scene.local_position(e1).unwrap(), [0.0, 1.0, 0.0].into()); scene.set_position(e2, [1.0, 0.0, 0.0]); scene.set_position(e3, [0.0, 0.0, 1.0]); scene.set_parent(e2, e1, false).unwrap(); assert_ulps_eq!(scene.local_position(e2).unwrap(), [1.0, 0.0, 0.0].into()); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 1.0, 0.0].into()); scene.remove_from_parent(e2, true).unwrap(); assert_ulps_eq!(scene.position(e2).unwrap(), [1.0, 1.0, 0.0].into()); scene.set_parent(e3, e1, true).unwrap(); assert_ulps_eq!(scene.local_position(e3).unwrap(), [0.0, -1.0, 1.0].into()); assert_ulps_eq!(scene.position(e3).unwrap(), [0.0, 0.0, 1.0].into()); scene.remove_from_parent(e3, false).unwrap(); assert_ulps_eq!(scene.position(e3).unwrap(), [0.0, -1.0, 1.0].into()); } #[test] fn look_at() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [0.0, 0.0, -5.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [0.0, 0.0, 5.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(180.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); scene.set_position(e1, [1.0, 0.0, 1.0]); scene.look_at(e1, [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]); let euler = Euler::new(Deg(0.0), Deg(225.0), Deg(0.0)); assert_ulps_eq!(scene.rotation(e1).unwrap(), euler.into()); } #[test] fn iteration() { let mut scene = Scene::new(HeadlessRenderer::new()); let e1 = scene.create("e1"); let e2 = scene.create("e2"); let e3 = scene.create("e3"); let e4 = scene.create("e4"); let e5 = scene.create("e5"); let e6 = scene.create("e6"); scene.set_parent(e4, e3, false).unwrap(); scene.set_parent(e3, e1, false).unwrap(); scene.set_parent(e2, e1, false).unwrap(); scene.set_parent(e6, e4, false).unwrap(); scene.set_parent(e5, e4, false).unwrap(); assert_eq!( scene.descendants(e1).collect::<Vec<_>>(), [e2, e3, e4, e5, e6] ); assert_eq!(scene.children(e1).collect::<Vec<_>>(), [e2, e3]); assert_eq!(scene.ancestors(e1).collect::<Vec<_>>(), []); assert_eq!(scene.ancestors(e2).collect::<Vec<_>>(), [e1]); assert_eq!(scene.ancestors(e4).collect::<Vec<_>>(), [e3, e1]); assert_eq!(scene.ancestors(e6).collect::<Vec<_>>(), [e4, e3, e1]); } #[test] fn random_iteration() { let mut scene = Scene::new(HeadlessRenderer::new()); let mut nodes = vec![]; for _ in 0..255 { nodes.push(scene.create("")); } let mut constructed = vec![]; constructed.push(nodes.pop().unwrap()); let mut count = 0; for i in 0..254 { let idx = rand::random::<usize>() % nodes.len(); let pidx = rand::random::<usize>() % constructed.len(); if pidx == 0 { count += 1; } scene .set_parent(nodes[idx], constructed[pidx], false) .unwrap(); let len = scene.descendants(constructed[0]).count(); assert_eq!(len, i + 1); constructed.push(nodes[idx]); nodes.remove(idx); }
let len = scene.children(constructed[0]).count(); assert_eq!(len, count); let len = scene.descendants(constructed[0]).count(); assert_eq!(len, 254); }
function_block-function_prefix_line
[ { "content": "#[test]\n\nfn transform() {\n\n let mut e1 = Transform::default();\n\n let euler = Euler::new(Deg(0.0), Deg(0.0), Deg(90.0));\n\n e1.scale = 2.0;\n\n e1.position = [1.0, 0.0, 2.0].into();\n\n e1.rotation = euler.into();\n\n\n\n let v = [1.0, 0.0, 0.0];\n\n assert_ulps_eq!(e1.t...
Rust
day-11/src/main.rs
mmehrten/advent-of-code-2021
f04ac08718f4bda3d24ecf255083dac7b6b2cf8a
use std::collections::HashSet; use std::fs::File; use std::io::Error; use std::io::{BufRead, BufReader}; fn parse_file_path(args: &[String]) -> &str { if args.len() != 2 { panic!( "Expected one file path and an optional window size to run against, got: {} arguments", args.len() - 1 ); } let input_path = &args[1]; input_path.as_str() } #[cfg(test)] mod test_parse_file_path { use crate::parse_file_path; #[test] fn one_arg_ok() { assert_eq!( parse_file_path(&vec!["script_path".to_string(), "arg_text".to_string()][..]), "arg_text" ); } #[test] #[should_panic] fn no_arg_fail() { parse_file_path(&Vec::new()); } #[test] #[should_panic] fn many_arg_fail() { parse_file_path( &vec![ "script_path".to_string(), "arg_text".to_string(), "extra_arg".to_string(), ][..], ); } } fn get_buf_reader(input_path: &str) -> BufReader<File> { let contents = File::open(input_path).expect(format!("Error reading file: {}", input_path).as_str()); let reader = BufReader::new(contents); reader } #[cfg(test)] mod test_get_buf_reader { use crate::get_buf_reader; #[test] #[should_panic] fn error_file_handled() { get_buf_reader("inputs/noexist.txt"); } #[test] fn example_file_handled() { get_buf_reader("inputs/example.txt"); } } struct Field { spaces: Vec<usize>, width: usize, } static ACTIVATION_ENERGY: usize = 9; impl Field { fn len(&self) -> usize { self.spaces.len() } fn neighbors(&self, idx: usize) -> Vec<usize> { let mut neighbors = Vec::new(); let has_above = idx >= self.width; let has_left = idx % self.width != 0; let has_right = idx % self.width != self.width - 1; let has_below = idx < self.spaces.len() - self.width; if has_above { neighbors.push(idx - self.width); } if has_left { neighbors.push(idx - 1); } if has_right { neighbors.push(idx + 1); } if has_below { neighbors.push(idx + self.width); } if has_above && has_left { neighbors.push(idx - 1 - self.width) } if has_above && has_right { neighbors.push(idx + 1 - self.width) } if has_below && has_left { neighbors.push(idx - 1 + self.width) } if has_below && has_right { neighbors.push(idx + 1 + self.width) } neighbors } fn parse_line(line: Result<String, Error>) -> Vec<usize> { line.expect("Failed to parse line from file.") .split("") .filter(|s| s != &"") .map(|s| { s.parse::<usize>() .expect("Failed to parse integer from inputs.") }) .collect::<Vec<usize>>() } fn parse_line_into(&mut self, line: Result<String, Error>) { self.spaces.extend(Field::parse_line(line)); } fn increase_total_energy(&mut self) { for idx in 0..self.len() { self.spaces[idx] += 1; } } fn try_activate_node(&mut self, idx: usize, activations: &mut HashSet<usize>) { if self.spaces[idx] <= ACTIVATION_ENERGY || activations.contains(&idx) { return; } activations.insert(idx); for neighbor in self.neighbors(idx) { self.spaces[neighbor] += 1; self.try_activate_node(neighbor, activations); } } fn try_activate_all(&mut self, activations: &mut HashSet<usize>) { for idx in 0..self.len() { self.try_activate_node(idx, activations); } } fn deactivate_node(&mut self, idx: usize) { self.spaces[idx] = 0; } } fn solution(input_path: &str, num_iterations: usize) -> (usize, usize) { let reader = get_buf_reader(input_path); let mut lines = reader.lines(); let mut inputs = Vec::new(); inputs.extend(Field::parse_line(lines.next().expect(""))); let array_width = inputs.len(); let mut field = Field { width: array_width, spaces: inputs, }; while let Some(line) = lines.next() { field.parse_line_into(line); } let mut activation_count = 0; let mut step_num = 0; loop { step_num += 1; let mut activations = HashSet::new(); field.increase_total_energy(); field.try_activate_all(&mut activations); if step_num <= num_iterations { activation_count += activations.len(); } if activations.len() == field.len() { return (activation_count, step_num); } for idx in activations { field.deactivate_node(idx); } } } fn main() { let args: Vec<String> = std::env::args().collect(); let input_path = parse_file_path(&args); let (activation_count, sync_step_count) = solution(input_path, 100); println!( "Total activation count after 100 steps: {:?}", activation_count ); println!("Steps to flash synchronization: {:?}", sync_step_count); } #[cfg(test)] mod test_solution { use crate::solution; #[test] fn example_correct() { assert_eq!(solution("inputs/example.txt", 100), (1656, 195)); } #[test] fn question_correct() { assert_eq!(solution("inputs/challenge.txt", 100), (1613, 510)); } }
use std::collections::HashSet; use std::fs::File; use std::io::Error; use std::io::{BufRead, BufReader}; fn parse_file_path(args: &[String]) -> &str { if args.len() != 2 { panic!( "Expected one file path and an optional window size to run against, got: {} arguments
("inputs/challenge.txt", 100), (1613, 510)); } }
", args.len() - 1 ); } let input_path = &args[1]; input_path.as_str() } #[cfg(test)] mod test_parse_file_path { use crate::parse_file_path; #[test] fn one_arg_ok() { assert_eq!( parse_file_path(&vec!["script_path".to_string(), "arg_text".to_string()][..]), "arg_text" ); } #[test] #[should_panic] fn no_arg_fail() { parse_file_path(&Vec::new()); } #[test] #[should_panic] fn many_arg_fail() { parse_file_path( &vec![ "script_path".to_string(), "arg_text".to_string(), "extra_arg".to_string(), ][..], ); } } fn get_buf_reader(input_path: &str) -> BufReader<File> { let contents = File::open(input_path).expect(format!("Error reading file: {}", input_path).as_str()); let reader = BufReader::new(contents); reader } #[cfg(test)] mod test_get_buf_reader { use crate::get_buf_reader; #[test] #[should_panic] fn error_file_handled() { get_buf_reader("inputs/noexist.txt"); } #[test] fn example_file_handled() { get_buf_reader("inputs/example.txt"); } } struct Field { spaces: Vec<usize>, width: usize, } static ACTIVATION_ENERGY: usize = 9; impl Field { fn len(&self) -> usize { self.spaces.len() } fn neighbors(&self, idx: usize) -> Vec<usize> { let mut neighbors = Vec::new(); let has_above = idx >= self.width; let has_left = idx % self.width != 0; let has_right = idx % self.width != self.width - 1; let has_below = idx < self.spaces.len() - self.width; if has_above { neighbors.push(idx - self.width); } if has_left { neighbors.push(idx - 1); } if has_right { neighbors.push(idx + 1); } if has_below { neighbors.push(idx + self.width); } if has_above && has_left { neighbors.push(idx - 1 - self.width) } if has_above && has_right { neighbors.push(idx + 1 - self.width) } if has_below && has_left { neighbors.push(idx - 1 + self.width) } if has_below && has_right { neighbors.push(idx + 1 + self.width) } neighbors } fn parse_line(line: Result<String, Error>) -> Vec<usize> { line.expect("Failed to parse line from file.") .split("") .filter(|s| s != &"") .map(|s| { s.parse::<usize>() .expect("Failed to parse integer from inputs.") }) .collect::<Vec<usize>>() } fn parse_line_into(&mut self, line: Result<String, Error>) { self.spaces.extend(Field::parse_line(line)); } fn increase_total_energy(&mut self) { for idx in 0..self.len() { self.spaces[idx] += 1; } } fn try_activate_node(&mut self, idx: usize, activations: &mut HashSet<usize>) { if self.spaces[idx] <= ACTIVATION_ENERGY || activations.contains(&idx) { return; } activations.insert(idx); for neighbor in self.neighbors(idx) { self.spaces[neighbor] += 1; self.try_activate_node(neighbor, activations); } } fn try_activate_all(&mut self, activations: &mut HashSet<usize>) { for idx in 0..self.len() { self.try_activate_node(idx, activations); } } fn deactivate_node(&mut self, idx: usize) { self.spaces[idx] = 0; } } fn solution(input_path: &str, num_iterations: usize) -> (usize, usize) { let reader = get_buf_reader(input_path); let mut lines = reader.lines(); let mut inputs = Vec::new(); inputs.extend(Field::parse_line(lines.next().expect(""))); let array_width = inputs.len(); let mut field = Field { width: array_width, spaces: inputs, }; while let Some(line) = lines.next() { field.parse_line_into(line); } let mut activation_count = 0; let mut step_num = 0; loop { step_num += 1; let mut activations = HashSet::new(); field.increase_total_energy(); field.try_activate_all(&mut activations); if step_num <= num_iterations { activation_count += activations.len(); } if activations.len() == field.len() { return (activation_count, step_num); } for idx in activations { field.deactivate_node(idx); } } } fn main() { let args: Vec<String> = std::env::args().collect(); let input_path = parse_file_path(&args); let (activation_count, sync_step_count) = solution(input_path, 100); println!( "Total activation count after 100 steps: {:?}", activation_count ); println!("Steps to flash synchronization: {:?}", sync_step_count); } #[cfg(test)] mod test_solution { use crate::solution; #[test] fn example_correct() { assert_eq!(solution("inputs/example.txt", 100), (1656, 195)); } #[test] fn question_correct() { assert_eq!(solution
random
[ { "content": "/// Parse the file path from command line arguments.\n\n///\n\n/// # Arguments\n\n///\n\n/// * `args` - the command line arguments\n\n///\n\n/// # Returns\n\n///\n\n/// A single command line argument - panics if zero or more than one argument are passed.\n\nfn parse_file_path(args: &[String]) -> &...
Rust
src/server/snap.rs
Caoming/tikv
7c25c38965692ccfc17d175fbd529d64c6695e13
use std::fmt::{self, Formatter, Display}; use std::io; use std::fs::File; use std::net::{SocketAddr, TcpStream}; use std::io::Read; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::boxed::FnBox; use std::time::{Instant, Duration}; use threadpool::ThreadPool; use mio::Token; use super::metrics::*; use super::{Result, ConnData, Msg}; use super::transport::RaftStoreRouter; use raftstore::store::{SnapFile, SnapManager, SnapKey, SnapEntry}; use util::worker::Runnable; use util::codec::rpc; use util::buf::PipeBuffer; use util::HandyRwLock; use util::transport::SendCh; use kvproto::raft_serverpb::RaftMessage; pub type Callback = Box<FnBox(Result<()>) + Send>; const DEFAULT_SENDER_POOL_SIZE: usize = 3; const DEFAULT_READ_TIMEOUT: u64 = 30; const DEFAULT_WRITE_TIMEOUT: u64 = 30; pub enum Task { Register(Token, RaftMessage), Write(Token, PipeBuffer), Close(Token), Discard(Token), SendTo { addr: SocketAddr, data: ConnData, cb: Callback, }, } impl Display for Task { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { Task::Register(token, ref meta) => write!(f, "Register {:?} token: {:?}", meta, token), Task::Write(token, _) => write!(f, "Write snap for {:?}", token), Task::Close(token) => write!(f, "Close file {:?}", token), Task::Discard(token) => write!(f, "Discard file {:?}", token), Task::SendTo { ref addr, ref data, .. } => { write!(f, "SendTo Snap[to: {}, snap: {:?}]", addr, data.msg) } } } } fn send_snap(mgr: SnapManager, addr: SocketAddr, data: ConnData) -> Result<()> { assert!(data.is_snapshot()); let timer = Instant::now(); let send_timer = SEND_SNAP_HISTOGRAM.start_timer(); let snap = data.msg.get_raft().get_message().get_snapshot(); let key = try!(SnapKey::from_snap(&snap)); mgr.wl().register(key.clone(), SnapEntry::Sending); let snap_file = box_try!(mgr.rl().get_snap_file(&key, true)); defer!({ snap_file.delete(); mgr.wl().deregister(&key, &SnapEntry::Sending); }); if !snap_file.exists() { return Err(box_err!("missing snap file: {:?}", snap_file.path())); } let mut f = try!(File::open(snap_file.path())); let mut conn = try!(TcpStream::connect(&addr)); try!(conn.set_nodelay(true)); try!(conn.set_read_timeout(Some(Duration::from_secs(DEFAULT_READ_TIMEOUT)))); try!(conn.set_write_timeout(Some(Duration::from_secs(DEFAULT_WRITE_TIMEOUT)))); let res = rpc::encode_msg(&mut conn, data.msg_id, &data.msg) .and_then(|_| io::copy(&mut f, &mut conn).map_err(From::from)) .and_then(|_| conn.read(&mut [0]).map_err(From::from)) .map(|_| ()) .map_err(From::from); let size = snap_file.meta().map(|m| m.len()).unwrap_or(0); info!("[region {}] sent snapshot {} [size: {}, dur: {:?}]", key.region_id, key, size, timer.elapsed()); send_timer.observe_duration(); res } pub struct Runner<R: RaftStoreRouter + 'static> { snap_mgr: SnapManager, files: HashMap<Token, (SnapFile, RaftMessage)>, pool: ThreadPool, ch: SendCh<Msg>, raft_router: R, } impl<R: RaftStoreRouter + 'static> Runner<R> { pub fn new(snap_mgr: SnapManager, r: R, ch: SendCh<Msg>) -> Runner<R> { Runner { snap_mgr: snap_mgr, files: map![], pool: ThreadPool::new_with_name(thd_name!("snap sender"), DEFAULT_SENDER_POOL_SIZE), raft_router: r, ch: ch, } } pub fn close(&self, token: Token) { if let Err(e) = self.ch.send(Msg::CloseConn { token: token }) { error!("failed to close connection {:?}: {:?}", token, e); } } } impl<R: RaftStoreRouter + 'static> Runnable<Task> for Runner<R> { fn run(&mut self, task: Task) { match task { Task::Register(token, meta) => { SNAP_TASK_COUNTER.with_label_values(&["register"]).inc(); let mgr = self.snap_mgr.clone(); match SnapKey::from_snap(meta.get_message().get_snapshot()) .and_then(|key| mgr.rl().get_snap_file(&key, false).map(|r| (r, key))) { Ok((f, k)) => { if f.exists() { info!("file {} already exists, skip receiving.", f.path().display()); if let Err(e) = self.raft_router.send_raft_msg(meta) { error!("send snapshot for token {:?} err {:?}", token, e); } self.close(token); return; } debug!("begin to receive snap {:?}", meta); mgr.wl().register(k.clone(), SnapEntry::Receiving); self.files.insert(token, (f, meta)); } Err(e) => error!("failed to create snap file for {:?}: {:?}", token, e), } } Task::Write(token, mut data) => { SNAP_TASK_COUNTER.with_label_values(&["write"]).inc(); let mut should_close = false; match self.files.entry(token) { Entry::Occupied(mut e) => { if let Err(err) = data.write_all_to(&mut e.get_mut().0) { error!("failed to write data to {:?}: {:?}", token, err); let (_, msg) = e.remove(); let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); should_close = true; } } Entry::Vacant(_) => error!("invalid snap token {:?}", token), } if should_close { self.close(token); } } Task::Close(token) => { SNAP_TASK_COUNTER.with_label_values(&["close"]).inc(); match self.files.remove(&token) { Some((mut writer, msg)) => { let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); info!("saving snapshot to {}", writer.path().display()); defer!({ self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); self.close(token); }); if let Err(e) = writer.save() { error!("failed to save file {:?}: {:?}", token, e); return; } if let Err(e) = self.raft_router.send_raft_msg(msg) { error!("send snapshot for token {:?} err {:?}", token, e); } } None => error!("invalid snap token {:?}", token), } } Task::Discard(token) => { SNAP_TASK_COUNTER.with_label_values(&["discard"]).inc(); if let Some((_, msg)) = self.files.remove(&token) { debug!("discard snapshot: {:?}", msg); let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); } } Task::SendTo { addr, data, cb } => { SNAP_TASK_COUNTER.with_label_values(&["send"]).inc(); let mgr = self.snap_mgr.clone(); self.pool.execute(move || { let res = send_snap(mgr, addr, data); if res.is_err() { error!("failed to send snap to {}: {:?}", addr, res); } cb(res) }); } } } }
use std::fmt::{self, Formatter, Display}; use std::io; use std::fs::File; use std::net::{SocketAddr, TcpStream}; use std::io::Read; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::boxed::FnBox; use std::time::{Instant, Duration}; use threadpool::ThreadPool; use mio::Token; use super::metrics::*; use super::{Result, ConnData, Msg}; use super::transport::RaftStoreRouter; use raftstore::store::{SnapFile, SnapManager, SnapKey, SnapEntry}; use util::worker::Runnable; use util::codec::rpc; use util::buf::PipeBuffer; use util::HandyRwLock; use util::transport::SendCh; use kvproto::raft_serverpb::RaftMessage; pub type Callback = Box<FnBox(Result<()>) + Send>; const DEFAULT_SENDER_POOL_SIZE: usize = 3; const DEFAULT_READ_TIMEOUT: u64 = 30; const DEFAULT_WRITE_TIMEOUT: u64 = 30; pub enum Task { Register(Token, RaftMessage), Write(Token, PipeBuffer), Close(Token), Discard(Token), SendTo { addr: SocketAddr, data: ConnData, cb: Callback, }, } impl Display for Task {
} fn send_snap(mgr: SnapManager, addr: SocketAddr, data: ConnData) -> Result<()> { assert!(data.is_snapshot()); let timer = Instant::now(); let send_timer = SEND_SNAP_HISTOGRAM.start_timer(); let snap = data.msg.get_raft().get_message().get_snapshot(); let key = try!(SnapKey::from_snap(&snap)); mgr.wl().register(key.clone(), SnapEntry::Sending); let snap_file = box_try!(mgr.rl().get_snap_file(&key, true)); defer!({ snap_file.delete(); mgr.wl().deregister(&key, &SnapEntry::Sending); }); if !snap_file.exists() { return Err(box_err!("missing snap file: {:?}", snap_file.path())); } let mut f = try!(File::open(snap_file.path())); let mut conn = try!(TcpStream::connect(&addr)); try!(conn.set_nodelay(true)); try!(conn.set_read_timeout(Some(Duration::from_secs(DEFAULT_READ_TIMEOUT)))); try!(conn.set_write_timeout(Some(Duration::from_secs(DEFAULT_WRITE_TIMEOUT)))); let res = rpc::encode_msg(&mut conn, data.msg_id, &data.msg) .and_then(|_| io::copy(&mut f, &mut conn).map_err(From::from)) .and_then(|_| conn.read(&mut [0]).map_err(From::from)) .map(|_| ()) .map_err(From::from); let size = snap_file.meta().map(|m| m.len()).unwrap_or(0); info!("[region {}] sent snapshot {} [size: {}, dur: {:?}]", key.region_id, key, size, timer.elapsed()); send_timer.observe_duration(); res } pub struct Runner<R: RaftStoreRouter + 'static> { snap_mgr: SnapManager, files: HashMap<Token, (SnapFile, RaftMessage)>, pool: ThreadPool, ch: SendCh<Msg>, raft_router: R, } impl<R: RaftStoreRouter + 'static> Runner<R> { pub fn new(snap_mgr: SnapManager, r: R, ch: SendCh<Msg>) -> Runner<R> { Runner { snap_mgr: snap_mgr, files: map![], pool: ThreadPool::new_with_name(thd_name!("snap sender"), DEFAULT_SENDER_POOL_SIZE), raft_router: r, ch: ch, } } pub fn close(&self, token: Token) { if let Err(e) = self.ch.send(Msg::CloseConn { token: token }) { error!("failed to close connection {:?}: {:?}", token, e); } } } impl<R: RaftStoreRouter + 'static> Runnable<Task> for Runner<R> { fn run(&mut self, task: Task) { match task { Task::Register(token, meta) => { SNAP_TASK_COUNTER.with_label_values(&["register"]).inc(); let mgr = self.snap_mgr.clone(); match SnapKey::from_snap(meta.get_message().get_snapshot()) .and_then(|key| mgr.rl().get_snap_file(&key, false).map(|r| (r, key))) { Ok((f, k)) => { if f.exists() { info!("file {} already exists, skip receiving.", f.path().display()); if let Err(e) = self.raft_router.send_raft_msg(meta) { error!("send snapshot for token {:?} err {:?}", token, e); } self.close(token); return; } debug!("begin to receive snap {:?}", meta); mgr.wl().register(k.clone(), SnapEntry::Receiving); self.files.insert(token, (f, meta)); } Err(e) => error!("failed to create snap file for {:?}: {:?}", token, e), } } Task::Write(token, mut data) => { SNAP_TASK_COUNTER.with_label_values(&["write"]).inc(); let mut should_close = false; match self.files.entry(token) { Entry::Occupied(mut e) => { if let Err(err) = data.write_all_to(&mut e.get_mut().0) { error!("failed to write data to {:?}: {:?}", token, err); let (_, msg) = e.remove(); let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); should_close = true; } } Entry::Vacant(_) => error!("invalid snap token {:?}", token), } if should_close { self.close(token); } } Task::Close(token) => { SNAP_TASK_COUNTER.with_label_values(&["close"]).inc(); match self.files.remove(&token) { Some((mut writer, msg)) => { let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); info!("saving snapshot to {}", writer.path().display()); defer!({ self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); self.close(token); }); if let Err(e) = writer.save() { error!("failed to save file {:?}: {:?}", token, e); return; } if let Err(e) = self.raft_router.send_raft_msg(msg) { error!("send snapshot for token {:?} err {:?}", token, e); } } None => error!("invalid snap token {:?}", token), } } Task::Discard(token) => { SNAP_TASK_COUNTER.with_label_values(&["discard"]).inc(); if let Some((_, msg)) = self.files.remove(&token) { debug!("discard snapshot: {:?}", msg); let key = SnapKey::from_snap(msg.get_message().get_snapshot()).unwrap(); self.snap_mgr.wl().deregister(&key, &SnapEntry::Receiving); } } Task::SendTo { addr, data, cb } => { SNAP_TASK_COUNTER.with_label_values(&["send"]).inc(); let mgr = self.snap_mgr.clone(); self.pool.execute(move || { let res = send_snap(mgr, addr, data); if res.is_err() { error!("failed to send snap to {}: {:?}", addr, res); } cb(res) }); } } } }
fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { Task::Register(token, ref meta) => write!(f, "Register {:?} token: {:?}", meta, token), Task::Write(token, _) => write!(f, "Write snap for {:?}", token), Task::Close(token) => write!(f, "Close file {:?}", token), Task::Discard(token) => write!(f, "Discard file {:?}", token), Task::SendTo { ref addr, ref data, .. } => { write!(f, "SendTo Snap[to: {}, snap: {:?}]", addr, data.msg) } } }
function_block-full_function
[ { "content": "pub fn new_message(from: u64, to: u64, t: MessageType, n: usize) -> Message {\n\n let mut m = new_message_with_entries(from, to, t, vec![]);\n\n if n > 0 {\n\n let mut ents = Vec::with_capacity(n);\n\n for _ in 0..n {\n\n ents.push(new_entry(0, 0, SOME_DATA));\n\n ...
Rust
aml/src/test_utils.rs
Dentosal/acpi
2273964aef430a51afee8735526e7323f597d2ca
use crate::{parser::Propagate, AmlContext, AmlValue, Handler}; use alloc::boxed::Box; struct TestHandler; impl Handler for TestHandler { fn read_u8(&self, _address: usize) -> u8 { unimplemented!() } fn read_u16(&self, _address: usize) -> u16 { unimplemented!() } fn read_u32(&self, _address: usize) -> u32 { unimplemented!() } fn read_u64(&self, _address: usize) -> u64 { unimplemented!() } fn write_u8(&mut self, _address: usize, _value: u8) { unimplemented!() } fn write_u16(&mut self, _address: usize, _value: u16) { unimplemented!() } fn write_u32(&mut self, _address: usize, _value: u32) { unimplemented!() } fn write_u64(&mut self, _address: usize, _value: u64) { unimplemented!() } fn read_io_u8(&self, _port: u16) -> u8 { unimplemented!() } fn read_io_u16(&self, _port: u16) -> u16 { unimplemented!() } fn read_io_u32(&self, _port: u16) -> u32 { unimplemented!() } fn write_io_u8(&self, _port: u16, _value: u8) { unimplemented!() } fn write_io_u16(&self, _port: u16, _value: u16) { unimplemented!() } fn write_io_u32(&self, _port: u16, _value: u32) { unimplemented!() } fn read_pci_u8(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u8 { unimplemented!() } fn read_pci_u16(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u16 { unimplemented!() } fn read_pci_u32(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u32 { unimplemented!() } fn write_pci_u8(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u8) { unimplemented!() } fn write_pci_u16(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u16) { unimplemented!() } fn write_pci_u32(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u32) { unimplemented!() } } pub(crate) fn make_test_context() -> AmlContext { AmlContext::new(Box::new(TestHandler), crate::DebugVerbosity::None) } pub(crate) macro check_err($parse: expr, $error: pat, $remains: expr) { match $parse { Ok((remains, _, result)) => panic!("Expected Err, got {:#?}. Remaining = {:#x?}", result, remains), Err((remains, _, Propagate::Err($error))) if *remains == *$remains => (), Err((remains, _, Propagate::Err($error))) => { panic!("Correct error, incorrect stream returned: {:#x?}", remains) } Err((_, _, err)) => panic!("Got wrong error: {:?}", err), } } pub(crate) macro check_ok($parse: expr, $expected: expr, $remains: expr) { match $parse { Ok((remains, _, ref result)) if remains == *$remains && result == &$expected => (), Ok((remains, _, ref result)) if result == &$expected => { panic!("Correct result, incorrect slice returned: {:x?}", remains) } Ok((_, _, ref result)) => panic!("Successfully parsed Ok, but it was wrong: {:#?}", result), Err((_, _, err)) => panic!("Expected Ok, got {:#?}", err), } } pub(crate) macro check_ok_value($parse: expr, $expected: expr, $remains: expr) { match $parse { Ok((remains, _, ref result)) if remains == *$remains && crudely_cmp_values(result, &$expected) => (), Ok((remains, _, ref result)) if crudely_cmp_values(result, &$expected) => { panic!("Correct result, incorrect slice returned: {:x?}", remains) } Ok((_, _, ref result)) => panic!("Successfully parsed Ok, but it was wrong: {:#?}", result), Err((_, _, err)) => panic!("Expected Ok, got {:#?}", err), } } pub(crate) fn crudely_cmp_values(a: &AmlValue, b: &AmlValue) -> bool { use crate::value::MethodCode; match a { AmlValue::Boolean(a) => match b { AmlValue::Boolean(b) => a == b, _ => false, }, AmlValue::Integer(a) => match b { AmlValue::Integer(b) => a == b, _ => false, }, AmlValue::String(ref a) => match b { AmlValue::String(ref b) => a == b, _ => false, }, AmlValue::OpRegion { region, offset, length, parent_device } => match b { AmlValue::OpRegion { region: b_region, offset: b_offset, length: b_length, parent_device: b_parent_device, } => { region == b_region && offset == b_offset && length == b_length && parent_device == b_parent_device } _ => false, }, AmlValue::Field { region, flags, offset, length } => match b { AmlValue::Field { region: b_region, flags: b_flags, offset: b_offset, length: b_length } => { region == b_region && flags == b_flags && offset == b_offset && length == b_length } _ => false, }, AmlValue::Device => match b { AmlValue::Device => true, _ => false, }, AmlValue::Method { flags, code } => match b { AmlValue::Method { flags: b_flags, code: b_code } => { if flags != b_flags { return false; } match (code, b_code) { (MethodCode::Aml(a), MethodCode::Aml(b)) => a == b, (MethodCode::Aml(_), MethodCode::Native(_)) => false, (MethodCode::Native(_), MethodCode::Aml(_)) => false, (MethodCode::Native(_), MethodCode::Native(_)) => panic!("Can't compare two native methods"), } } _ => false, }, AmlValue::Buffer(a) => match b { AmlValue::Buffer(b) => *a.lock() == *b.lock(), _ => false, }, AmlValue::BufferField { buffer_data, offset, length } => match b { AmlValue::BufferField { buffer_data: b_buffer_data, offset: b_offset, length: b_length } => { alloc::sync::Arc::as_ptr(buffer_data) == alloc::sync::Arc::as_ptr(b_buffer_data) && offset == b_offset && length == b_length } _ => false, }, AmlValue::Processor { id, pblk_address, pblk_len } => match b { AmlValue::Processor { id: b_id, pblk_address: b_pblk_address, pblk_len: b_pblk_len } => { id == b_id && pblk_address == b_pblk_address && pblk_len == b_pblk_len } _ => false, }, AmlValue::Mutex { sync_level } => match b { AmlValue::Mutex { sync_level: b_sync_level } => sync_level == b_sync_level, _ => false, }, AmlValue::Package(a) => match b { AmlValue::Package(b) => { for (a, b) in a.iter().zip(b) { if crudely_cmp_values(a, b) == false { return false; } } true } _ => false, }, AmlValue::PowerResource { system_level, resource_order } => match b { AmlValue::PowerResource { system_level: b_system_level, resource_order: b_resource_order } => { system_level == b_system_level && resource_order == b_resource_order } _ => false, }, AmlValue::ThermalZone => match b { AmlValue::ThermalZone => true, _ => false, }, } }
use crate::{parser::Propagate, AmlContext, AmlValue, Handler}; use alloc::boxed::Box; struct TestHandler; impl Handler for TestHandler { fn read_u8(&self, _address: usize) -> u8 { unimplemented!() } fn read_u16(&self, _address: usize) -> u16 { unimplemented!() } fn read_u32(&self, _address: usize) -> u32 { unimplemented!() } fn read_u64(&self, _address: usize) -> u64 { unimplemented!() } fn write_u8(&mut self, _address: usize, _value: u8) { unimplemented!() } fn write_u16(&mut self, _address: usize, _value: u16) { unimplemented!() } fn write_u32(&mut self, _address: usize, _value: u32) { unimplemented!() } fn write_u64(&mut self, _address: usize, _value: u64) { unimplemented!() } fn read_io_u8(&self, _port: u16) -> u8 { unimplemented!() } fn read_io_u16(&self, _port: u16) -> u16 { unimplemented!() } fn read_io_u32(&self, _port: u16) -> u32 { unimplemented!() } fn write_io_u8(&self, _port: u16, _value: u8) { unimplemented!() } fn write_io_u16(&self, _port: u16, _value: u16) { unimplemented!() } fn write_io_u32(&self, _port: u16, _value: u32) { unimplemented!() } fn read_pci_u8(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u8 { unimplemented!() } fn read_pci_u16(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u16 { unimplemented!() } fn read_pci_u32(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16) -> u32 { unimplemented!() } fn write_pci_u8(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u8) { unimplemented!() } fn write_pci_u16(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u16) { unimplemented!() } fn write_pci_u32(&self, _segment: u16, _bus: u8, device: u8, _function: u8, _offset: u16, _value: u32) { unimplemented!() } } pub(crate) fn make_test_context() -> AmlContext { AmlContext::new(Box::new(TestHandler), crate::DebugVerbosity::None) } pub(crate) macro check_err($parse: expr, $error: pat, $remains: expr) { match $parse { Ok((remains, _, result)) => panic!("Expected Err, got {:#?}. Remaining = {:#x?}", result, remains), Err((remains, _, Propagate::Err($error))) if *remains == *$remains => (), Err((remains, _, Propagate::Err($error))) => { panic!("Correct error, incorrect stream returned: {:#x?}", remains) } Err((_, _, err)) => panic!("Got wrong error: {:?}", err), } } pub(crate) macro check_ok($parse: expr, $expected: expr, $remains: expr) { match $parse { Ok((remains, _, ref result)) if remains == *$remains && result == &$expected => (), Ok((remains, _, ref result)) if result == &$expected => { panic!("Correct result, incorrect slice returned: {:x?}", remains) } Ok((_, _, ref result)) => panic!("Successfully parsed Ok, but it was wrong: {:#?}", result), Err((_, _, err)) => panic!("Expected Ok, got {:#?}", err), } } pub(crate) macro check_ok_value($parse: expr, $expected: expr, $remains: expr) { match $parse { Ok((remains, _, ref result)) if remains == *$remains && crudely_cmp_values(result, &$expected) => (), Ok((remains, _, ref result)) if crudely_cmp_values(result, &$expected) => { panic!("Correct result, incorrect slice returned: {:x?}", remains) } Ok((_, _, ref result)) => panic!("Successfully parsed Ok, but it was wrong: {:#?}", result), Err((_, _, err)) => panic!("Expe
_parent_device } _ => false, }, AmlValue::Field { region, flags, offset, length } => match b { AmlValue::Field { region: b_region, flags: b_flags, offset: b_offset, length: b_length } => { region == b_region && flags == b_flags && offset == b_offset && length == b_length } _ => false, }, AmlValue::Device => match b { AmlValue::Device => true, _ => false, }, AmlValue::Method { flags, code } => match b { AmlValue::Method { flags: b_flags, code: b_code } => { if flags != b_flags { return false; } match (code, b_code) { (MethodCode::Aml(a), MethodCode::Aml(b)) => a == b, (MethodCode::Aml(_), MethodCode::Native(_)) => false, (MethodCode::Native(_), MethodCode::Aml(_)) => false, (MethodCode::Native(_), MethodCode::Native(_)) => panic!("Can't compare two native methods"), } } _ => false, }, AmlValue::Buffer(a) => match b { AmlValue::Buffer(b) => *a.lock() == *b.lock(), _ => false, }, AmlValue::BufferField { buffer_data, offset, length } => match b { AmlValue::BufferField { buffer_data: b_buffer_data, offset: b_offset, length: b_length } => { alloc::sync::Arc::as_ptr(buffer_data) == alloc::sync::Arc::as_ptr(b_buffer_data) && offset == b_offset && length == b_length } _ => false, }, AmlValue::Processor { id, pblk_address, pblk_len } => match b { AmlValue::Processor { id: b_id, pblk_address: b_pblk_address, pblk_len: b_pblk_len } => { id == b_id && pblk_address == b_pblk_address && pblk_len == b_pblk_len } _ => false, }, AmlValue::Mutex { sync_level } => match b { AmlValue::Mutex { sync_level: b_sync_level } => sync_level == b_sync_level, _ => false, }, AmlValue::Package(a) => match b { AmlValue::Package(b) => { for (a, b) in a.iter().zip(b) { if crudely_cmp_values(a, b) == false { return false; } } true } _ => false, }, AmlValue::PowerResource { system_level, resource_order } => match b { AmlValue::PowerResource { system_level: b_system_level, resource_order: b_resource_order } => { system_level == b_system_level && resource_order == b_resource_order } _ => false, }, AmlValue::ThermalZone => match b { AmlValue::ThermalZone => true, _ => false, }, } }
cted Ok, got {:#?}", err), } } pub(crate) fn crudely_cmp_values(a: &AmlValue, b: &AmlValue) -> bool { use crate::value::MethodCode; match a { AmlValue::Boolean(a) => match b { AmlValue::Boolean(b) => a == b, _ => false, }, AmlValue::Integer(a) => match b { AmlValue::Integer(b) => a == b, _ => false, }, AmlValue::String(ref a) => match b { AmlValue::String(ref b) => a == b, _ => false, }, AmlValue::OpRegion { region, offset, length, parent_device } => match b { AmlValue::OpRegion { region: b_region, offset: b_offset, length: b_length, parent_device: b_parent_device, } => { region == b_region && offset == b_offset && length == b_length && parent_device == b
random
[ { "content": "pub fn take_n<'a, 'c>(n: u32) -> impl Parser<'a, 'c, &'a [u8]>\n\nwhere\n\n 'c: 'a,\n\n{\n\n move |input: &'a [u8], context| {\n\n if (input.len() as u32) < n {\n\n return Err((input, context, Propagate::Err(AmlError::UnexpectedEndOfStream)));\n\n }\n\n\n\n le...
Rust
src/setting_serial.rs
opendoor-labs/libnm-rs
ddd1c6c4599fb9d4c62f44f5eb17a0286eeabe1a
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use Setting; use SettingSerialParity; glib_wrapper! { pub struct SettingSerial(Object<nm_sys::NMSettingSerial, nm_sys::NMSettingSerialClass, SettingSerialClass>) @extends Setting; match fn { get_type => || nm_sys::nm_setting_serial_get_type(), } } impl SettingSerial { pub fn new() -> SettingSerial { unsafe { Setting::from_glib_full(nm_sys::nm_setting_serial_new()).unsafe_cast() } } } impl Default for SettingSerial { fn default() -> Self { Self::new() } } pub const NONE_SETTING_SERIAL: Option<&SettingSerial> = None; pub trait SettingSerialExt: 'static { fn get_baud(&self) -> u32; fn get_bits(&self) -> u32; fn get_parity(&self) -> SettingSerialParity; fn get_send_delay(&self) -> u64; fn get_stopbits(&self) -> u32; fn set_property_baud(&self, baud: u32); fn set_property_bits(&self, bits: u32); fn set_property_parity(&self, parity: SettingSerialParity); fn set_property_send_delay(&self, send_delay: u64); fn set_property_stopbits(&self, stopbits: u32); fn connect_property_baud_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_bits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_parity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_send_delay_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_stopbits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<SettingSerial>> SettingSerialExt for O { fn get_baud(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_baud(self.as_ref().to_glib_none().0) } } fn get_bits(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_bits(self.as_ref().to_glib_none().0) } } fn get_parity(&self) -> SettingSerialParity { unsafe { from_glib(nm_sys::nm_setting_serial_get_parity( self.as_ref().to_glib_none().0, )) } } fn get_send_delay(&self) -> u64 { unsafe { nm_sys::nm_setting_serial_get_send_delay(self.as_ref().to_glib_none().0) } } fn get_stopbits(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_stopbits(self.as_ref().to_glib_none().0) } } fn set_property_baud(&self, baud: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"baud\0".as_ptr() as *const _, Value::from(&baud).to_glib_none().0, ); } } fn set_property_bits(&self, bits: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"bits\0".as_ptr() as *const _, Value::from(&bits).to_glib_none().0, ); } } fn set_property_parity(&self, parity: SettingSerialParity) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"parity\0".as_ptr() as *const _, Value::from(&parity).to_glib_none().0, ); } } fn set_property_send_delay(&self, send_delay: u64) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"send-delay\0".as_ptr() as *const _, Value::from(&send_delay).to_glib_none().0, ); } } fn set_property_stopbits(&self, stopbits: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"stopbits\0".as_ptr() as *const _, Value::from(&stopbits).to_glib_none().0, ); } } fn connect_property_baud_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_baud_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::baud\0".as_ptr() as *const _, Some(transmute(notify_baud_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_bits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_bits_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::bits\0".as_ptr() as *const _, Some(transmute(notify_bits_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_parity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_parity_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::parity\0".as_ptr() as *const _, Some(transmute(notify_parity_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_send_delay_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_send_delay_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::send-delay\0".as_ptr() as *const _, Some(transmute(notify_send_delay_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_stopbits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_stopbits_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::stopbits\0".as_ptr() as *const _, Some(transmute(notify_stopbits_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for SettingSerial { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SettingSerial") } }
use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::Value; use glib_sys; use gobject_sys; use nm_sys; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use Setting; use SettingSerialParity; glib_wrapper! { pub struct SettingSerial(Object<nm_sys::NMSettingSerial, nm_sys::NMSettingSerialClass, SettingSerialClass>) @extends Setting; match fn { get_type => || nm_sys::nm_setting_serial_get_type(), } } impl SettingSerial { pub fn new() -> SettingSerial { unsafe { Setting::from_glib_full(nm_sys::nm_setting_serial_new()).unsafe_cast() } } } impl Default for SettingSerial { fn default() -> Self { Self::new() } } pub const NONE_SETTING_SERIAL: Option<&SettingSerial> = None; pub trait SettingSerialExt: 'static { fn get_baud(&self) -> u32; fn get_bits(&self) -> u32; fn get_parity(&self) -> SettingSerialParity; fn get_send_delay(&self) -> u64; fn get_stopbits(&self) -> u32; fn set_property_baud(&self, baud: u32); fn set_property_bits(&self, bits: u32); fn set_property_parity(&self, parity: SettingSerialParity); fn set_property_send_delay(&self, send_delay: u64); fn set_property_stopbits(&self, stopbits: u32); fn connect_property_baud_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_bits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_parity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_send_delay_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_stopbits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<SettingSerial>> SettingSerialExt for O { fn get_baud(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_baud(self.as_ref().to_glib_none().0) } } fn get_bits(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_bits(self.as_ref().to_glib_none().0) } } fn get_parity(&self) -> SettingSerialParity { unsafe { from_glib(nm_sys::nm_setting_serial_get_parity( self.as_ref().to_glib_none().0, )) } } fn get_send_delay(&self) -> u64 { unsafe { nm_sys::nm_setting_serial_get_send_delay(self.as_ref().to_glib_none().0) } } fn get_stopbits(&self) -> u32 { unsafe { nm_sys::nm_setting_serial_get_stopbits(self.as_ref().to_glib_none().0) } } fn set_property_baud(&self, baud: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"baud\0".as_ptr() as *const _, Value::from(&baud).to_glib_none().0, ); } } fn set_property_bits(&self, bits: u32) { unsafe { gobject_sys::g_object_set_property(
fn set_property_parity(&self, parity: SettingSerialParity) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"parity\0".as_ptr() as *const _, Value::from(&parity).to_glib_none().0, ); } } fn set_property_send_delay(&self, send_delay: u64) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"send-delay\0".as_ptr() as *const _, Value::from(&send_delay).to_glib_none().0, ); } } fn set_property_stopbits(&self, stopbits: u32) { unsafe { gobject_sys::g_object_set_property( self.to_glib_none().0 as *mut gobject_sys::GObject, b"stopbits\0".as_ptr() as *const _, Value::from(&stopbits).to_glib_none().0, ); } } fn connect_property_baud_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_baud_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::baud\0".as_ptr() as *const _, Some(transmute(notify_baud_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_bits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_bits_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::bits\0".as_ptr() as *const _, Some(transmute(notify_bits_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_parity_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_parity_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::parity\0".as_ptr() as *const _, Some(transmute(notify_parity_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_send_delay_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_send_delay_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::send-delay\0".as_ptr() as *const _, Some(transmute(notify_send_delay_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_stopbits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_stopbits_trampoline<P, F: Fn(&P) + 'static>( this: *mut nm_sys::NMSettingSerial, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<SettingSerial>, { let f: &F = &*(f as *const F); f(&SettingSerial::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::stopbits\0".as_ptr() as *const _, Some(transmute(notify_stopbits_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for SettingSerial { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "SettingSerial") } }
self.to_glib_none().0 as *mut gobject_sys::GObject, b"bits\0".as_ptr() as *const _, Value::from(&bits).to_glib_none().0, ); } }
function_block-function_prefix_line
[ { "content": "pub trait SettingExt: 'static {\n\n fn compare<P: IsA<Setting>>(&self, b: &P, flags: SettingCompareFlags) -> bool;\n\n\n\n //fn diff<P: IsA<Setting>>(&self, b: &P, flags: SettingCompareFlags, invert_results: bool, results: /*Unknown conversion*//*Unimplemented*/HashTable TypeId { ns_id: 0, i...
Rust
src/lower.rs
1tgr/simplejit-demo
750a1f628452d42836d0da5fc415fcef7750c045
use crate::ast::*; use crate::intern::Intern; use crate::{InternExt, Parse, Result}; use std::collections::HashMap; use std::convert::Infallible; use std::num::NonZeroU32; use std::rc::Rc; use std::result; #[salsa::query_group(LowerDatabase)] pub trait Lower: Parse { fn lower_function(&self, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)>; } fn lower_function(db: &dyn Lower, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)> { let mut envs = HashMap::new(); let global_env = db.global_env()?; envs.insert(EnvId::GLOBAL, global_env.clone()); let mut index = 2; let env = EnvId::from(NonZeroU32::new(index).unwrap()); index += 1; let Env { mut bindings, ty_bindings } = global_env; let Function { signature, param_names, body } = db.function(name)?; let Signature { param_tys, return_ty: _ } = signature; for (index, (name, ty)) in param_names.into_iter().zip(param_tys).enumerate() { bindings.insert(name, (env, Binding::Param(Param { index, ty }))); } envs.insert(env, Env { bindings, ty_bindings }); let body = LowerExprTransform { db, env, envs: &mut envs, index: &mut index, } .transform_expr(body)?; Ok((Rc::new(envs), body)) } pub trait LowerExt: Lower { fn binding_pair(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<(EnvId, Binding)> { let (envs, _) = self.lower_function(function_name)?; let Env { bindings, ty_bindings: _ } = &envs[&env]; let binding = bindings .get(&name) .ok_or_else(|| error!("reading from undeclared variable {}", self.lookup_intern_ident(name)))?; Ok(binding.clone()) } fn binding_decl_env(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<EnvId> { let (decl_env, _) = self.binding_pair(function_name, env, name)?; Ok(decl_env) } fn binding(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<Binding> { let (_, binding) = self.binding_pair(function_name, env, name)?; Ok(binding) } } impl<T: Lower + ?Sized> LowerExt for T {} struct LowerExprTransform<'a, DB: ?Sized> { db: &'a DB, env: EnvId, envs: &'a mut HashMap<EnvId, Env>, index: &'a mut u32, } impl<'a, DB: Intern + ?Sized> LowerExprTransform<'a, DB> { fn make_scope(&mut self, mut env: Env, decl_name: IdentId, decl_expr: ExprId, mut stmts: Vec<ExprId>) -> result::Result<Scope, Infallible> { let scope_env = EnvId::from(NonZeroU32::new(*self.index).unwrap()); *self.index += 1; let decl_expr = self.transform_expr(decl_expr)?; env.bindings.insert(decl_name, (scope_env, Binding::Variable(Variable { decl_expr }))); self.envs.insert(scope_env, env); LowerExprTransform { db: self.db, env: scope_env, envs: self.envs, index: self.index, } .transform_stmts(&mut stmts)?; let body = self.db.intern_block(stmts); Ok(Scope { scope_env, decl_name, decl_expr, body, }) } fn transform_stmts(&mut self, stmts: &mut Vec<ExprId>) -> result::Result<(), Infallible> { for (index, expr_mut) in stmts.iter_mut().enumerate() { if let Expr::Assign(assign) = self.db.lookup_intern_expr(*expr_mut) { let Assign { lvalue, expr: decl_expr } = assign; if let Expr::Identifier(lvalue) = self.db.lookup_intern_expr(lvalue) { let Identifier { env: _, name } = lvalue; let env = self.envs[&self.env].clone(); if !env.bindings.contains_key(&name) { let body = stmts.split_off(index + 1); let scope = self.make_scope(env, name, decl_expr, body)?; stmts[index] = self.intern_expr(Expr::Scope(scope)); return Ok(()); } } } *expr_mut = self.transform_expr(*expr_mut)?; } Ok(()) } } impl<'a, DB: Intern + InternExt + ?Sized> ExprTransform for LowerExprTransform<'a, DB> { type Error = Infallible; fn lookup_expr(&self, expr: ExprId) -> Expr { self.db.lookup_intern_expr(expr) } fn intern_expr(&self, expr: Expr) -> ExprId { if let Expr::Block(expr) = expr { let Block { stmts } = expr; self.db.intern_block(stmts) } else { self.db.intern_expr(expr) } } fn transform_block(&mut self, _expr_id: ExprId, mut expr: Block) -> result::Result<Expr, Infallible> { self.transform_stmts(&mut expr.stmts)?; Ok(Expr::Block(expr)) } fn transform_call(&mut self, _expr_id: ExprId, mut expr: Call) -> result::Result<Expr, Infallible> { expr.env = Some(self.env); expr.transform(self) } fn transform_identifier(&mut self, _expr_id: ExprId, mut expr: Identifier) -> result::Result<Expr, Infallible> { expr.env = Some(self.env); expr.transform(self) } }
use crate::ast::*; use crate::intern::Intern; use crate::{InternExt, Parse, Result}; use std::collections::HashMap; use std::convert::Infallible; use std::num::NonZeroU32; use std::rc::Rc; use std::result; #[salsa::query_group(LowerDatabase)] pub trait Lower: Parse { fn lower_function(&self, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)>; } fn lower_function(db: &dyn Lower, name: IdentId) -> Result<(Rc<HashMap<EnvId, Env>>, ExprId)> { let mut envs = HashMap::new(); let global_env = db.global_env()?; envs.insert(EnvId::GLOBAL, global_env.clone()); let mut index = 2; let env = EnvId::from(NonZeroU32::new(index).unwrap()); index += 1; let Env { mut bindings, ty_bindings } = global_env; let Function { signature, param_names, body } = db.function(name)?; let Signature { param_tys, return_ty: _ } = signature; for (index, (name, ty)) in param_names.into_iter().zip(param_tys).enumerate() { bindings.insert(name, (env, Binding::Param(Param { index, ty }))); } envs.insert(env, Env { bindings, ty_bindings }); let body = LowerExprTransform { db, env, envs: &mut envs, index: &mut index, } .transform_expr(body)?; Ok((Rc::new(envs), body)) } pub trait LowerExt: Lower { fn binding_pair(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<(EnvId, Binding)> { let (envs, _) = self.lower_function(function_name)?; let Env { bindings, ty_bindings: _ } = &envs[&env]; let binding = bindings .get(&name) .ok_or_else(|| error!("reading from undeclared variable {}", self.lookup_intern_ident(name)))?; Ok(binding.clone()) } fn binding_decl_env(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<EnvId> { let (decl_env, _) = self.binding_pair(function_name, env, name)?; Ok(decl_env) } fn binding(&self, function_name: IdentId, env: EnvId, name: IdentId) -> Result<Binding> { let (_, binding) = self.binding_pair(function_name, env, name)?; Ok(binding) } } impl<T: Lower + ?Sized> LowerExt for T {} struct LowerExprTransform<'a, DB: ?Sized> { db: &'a DB, env: EnvId, envs: &'a mut HashMap<EnvId, Env>, index: &'a mut u32, } impl<'a, DB: Intern + ?Sized> LowerExprTransform<'a, DB> { fn make_scope(&mut self, mut env: Env, decl_name: IdentId, decl_expr: ExprId, mut stmts: Vec<ExprId>) -> result::Result<Scope, Infallible> { let scope_env = EnvId::from(NonZeroU32::new(*self.index).unwrap()); *self.index += 1; let decl_expr = self.transform_expr(decl_expr)?; env.bindings.insert(decl_name, (scope_env, Binding::Variable(Variable { decl_expr }))); self.envs.insert(scope_env, env); LowerExprTransform { db: self.db, env: scope_env, envs: self.envs, index: self.index, } .transform_stmts(&mut stmts)?; let body = self.db.intern_block(stmts); Ok(Scope { scope_env, decl_name, decl_expr, body, }) } fn transform_stmts(&mut self, stmts: &mut Vec<ExprId>) -> result::Result<(), Infallible> { for (index, expr_mut) in stmts.iter_mut().enumerate() { if let Expr::Assign(assign) = self.db.lookup_intern_expr(*expr_mut) { let Assign { lvalue, expr: decl_expr } = assign; if let Expr::Identifier(lvalue) = self.db.lookup_intern_expr(lvalue) { let Identifier { env: _, name } = lvalue; let env = self.envs[&self.env].clone(); if !env.bindings.contains_key(&name) { let body = stmts.split_off(index + 1); let scope = self.make_scope(env, name, decl_expr, body)?; stmts[index] = self.intern_expr(Expr::Scope(scope)); return Ok(()); } } } *expr_mut = self.transform_expr(*expr_mut)?; } Ok(()) } } impl<'a, DB: Intern + InternExt + ?Sized> ExprTransform for LowerExprTransform<'a, DB> { type Error = Infallible; fn lookup_expr(&self, expr: ExprId) -> Expr { self.db.lookup_intern_expr(expr) } fn intern_expr(&self, expr: Expr) -> ExprI
fn transform_block(&mut self, _expr_id: ExprId, mut expr: Block) -> result::Result<Expr, Infallible> { self.transform_stmts(&mut expr.stmts)?; Ok(Expr::Block(expr)) } fn transform_call(&mut self, _expr_id: ExprId, mut expr: Call) -> result::Result<Expr, Infallible> { expr.env = Some(self.env); expr.transform(self) } fn transform_identifier(&mut self, _expr_id: ExprId, mut expr: Identifier) -> result::Result<Expr, Infallible> { expr.env = Some(self.env); expr.transform(self) } }
d { if let Expr::Block(expr) = expr { let Block { stmts } = expr; self.db.intern_block(stmts) } else { self.db.intern_expr(expr) } }
function_block-function_prefixed
[ { "content": "fn function_body(db: &dyn Parse, name: IdentId) -> Result<ExprId> {\n\n let Function {\n\n signature: _,\n\n param_names: _,\n\n body,\n\n } = db.function(name)?;\n\n\n\n Ok(body)\n\n}\n\n\n", "file_path": "src/parse.rs", "rank": 1, "score": 259582.8352002...
Rust
tests/integrations/config/test_config_client.rs
amyangfei/tikv
5019e61d0c8e1966f6b649894ad17ba128068a1e
use std::cmp::Ordering; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use kvproto::configpb::*; use configuration::{ConfigChange, Configuration}; use pd_client::errors::Result; use pd_client::ConfigClient; use raftstore::store::Config as RaftstoreConfig; use tikv::config::*; use tikv_util::config::ReadableDuration; use tikv_util::worker::FutureWorker; struct MockPdClient { configs: Mutex<HashMap<String, Config>>, } #[derive(Clone)] struct Config { version: Version, content: String, update: Vec<ConfigEntry>, } impl Config { fn new(version: Version, content: String, update: Vec<ConfigEntry>) -> Self { Config { version, content, update, } } } impl MockPdClient { fn new() -> Self { MockPdClient { configs: Mutex::new(HashMap::new()), } } fn register(self: Arc<Self>, id: &str, cfg: TiKvConfig) -> ConfigHandler { let (version, cfg) = ConfigHandler::create(id.to_owned(), self, cfg).unwrap(); ConfigHandler::start( id.to_owned(), ConfigController::new(cfg, version), FutureWorker::new("test-pd-worker").scheduler(), ) .unwrap() } fn update_cfg<F>(&self, id: &str, f: F) where F: Fn(&mut TiKvConfig), { let mut configs = self.configs.lock().unwrap(); let cfg = configs.get_mut(id).unwrap(); let mut config: TiKvConfig = toml::from_str(&cfg.content).unwrap(); f(&mut config); cfg.content = toml::to_string(&config).unwrap(); cfg.version.local += 1; } fn update_raw<F>(&self, id: &str, f: F) where F: Fn(&mut String), { let mut configs = self.configs.lock().unwrap(); let cfg = configs.get_mut(id).unwrap(); f(&mut cfg.content); cfg.version.local += 1; } fn get(&self, id: &str) -> Config { self.configs.lock().unwrap().get(id).unwrap().clone() } } impl ConfigClient for MockPdClient { fn register_config(&self, id: String, v: Version, cfg: String) -> Result<CreateResponse> { let old = self .configs .lock() .unwrap() .insert(id.clone(), Config::new(v.clone(), cfg.clone(), Vec::new())); assert!(old.is_none(), format!("id {} already be registered", id)); let mut status = Status::default(); status.set_code(StatusCode::Ok); let mut resp = CreateResponse::default(); resp.set_status(status); resp.set_config(cfg); resp.set_version(v); Ok(resp) } fn get_config(&self, id: String, version: Version) -> Result<GetResponse> { let mut resp = GetResponse::default(); let mut status = Status::default(); let configs = self.configs.lock().unwrap(); if let Some(cfg) = configs.get(&id) { match cmp_version(&cfg.version, &version) { Ordering::Equal => status.set_code(StatusCode::Ok), _ => { resp.set_config(cfg.content.clone()); status.set_code(StatusCode::WrongVersion); } } resp.set_version(cfg.version.clone()); } else { status.set_code(StatusCode::Unknown); } resp.set_status(status); Ok(resp) } fn update_config( &self, id: String, version: Version, mut entries: Vec<ConfigEntry>, ) -> Result<UpdateResponse> { let mut resp = UpdateResponse::default(); let mut status = Status::default(); if let Some(cfg) = self.configs.lock().unwrap().get_mut(&id) { match cmp_version(&cfg.version, &version) { Ordering::Equal => { cfg.update.append(&mut entries); cfg.version.local += 1; status.set_code(StatusCode::Ok); } _ => status.set_code(StatusCode::WrongVersion), } resp.set_version(cfg.version.clone()); } else { status.set_code(StatusCode::Unknown); } resp.set_status(status); Ok(resp) } } #[test] fn test_update_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let mut cfg = cfg_handler.get_config().clone(); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!(cfg_handler.get_config(), &cfg); pd_client.update_cfg(id, |cfg| { cfg.refresh_config_interval = ReadableDuration::hours(12); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); cfg.refresh_config_interval = ReadableDuration::hours(12); assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_update_not_support_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let cfg = cfg_handler.get_config().clone(); pd_client.update_cfg(id, |cfg| { cfg.server.addr = "localhost:3000".to_owned(); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_update_to_invalid() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg = TiKvConfig::default(); cfg.raft_store.raft_log_gc_threshold = 2000; let mut cfg_handler = pd_client.clone().register(id, cfg); pd_client.update_cfg(id, |cfg| { cfg.raft_store.raft_log_gc_threshold = 0; }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!( cfg_handler.get_config().raft_store.raft_log_gc_threshold, 2000 ); let cfg = pd_client.get(id); assert_eq!(cfg.update.len(), 1); assert_eq!(cfg.update[0].name, "raftstore.raft-log-gc-threshold"); assert_eq!(cfg.update[0].value, toml::to_string(&2000).unwrap()); } #[test] fn test_compatible_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let mut cfg = cfg_handler.get_config().clone(); pd_client.update_raw(id, |cfg| { *cfg = " [new.config] xyz = 1 [raftstore] raft-log-gc-threshold = 2048 " .to_owned(); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); cfg.raft_store.raft_log_gc_threshold = 2048; assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_dispatch_change() { use configuration::ConfigManager; use std::error::Error; use std::result::Result; #[derive(Clone)] struct CfgManager(Arc<Mutex<RaftstoreConfig>>); impl ConfigManager for CfgManager { fn dispatch(&mut self, c: ConfigChange) -> Result<(), Box<dyn Error>> { self.0.lock().unwrap().update(c); Ok(()) } } let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let cfg = TiKvConfig::default(); let mgr = CfgManager(Arc::new(Mutex::new(Default::default()))); let mut cfg_handler = { let (version, cfg) = ConfigHandler::create(id.to_owned(), pd_client.clone(), cfg).unwrap(); *mgr.0.lock().unwrap() = cfg.raft_store.clone(); let mut controller = ConfigController::new(cfg, version); controller.register(Module::Raftstore, Box::new(mgr.clone())); ConfigHandler::start( id.to_owned(), controller, FutureWorker::new("test-pd-worker").scheduler(), ) .unwrap() }; pd_client.update_cfg(id, |cfg| { cfg.raft_store.raft_log_gc_threshold = 2000; }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!( cfg_handler.get_config().raft_store.raft_log_gc_threshold, 2000 ); assert_eq!(mgr.0.lock().unwrap().raft_log_gc_threshold, 2000); }
use std::cmp::Ordering; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use kvproto::configpb::*; use configuration::{ConfigChange, Configuration}; use pd_client::errors::Result; use pd_client::ConfigClient; use raftstore::store::Config as RaftstoreConfig; use tikv::config::*; use tikv_util::config::ReadableDuration; use tikv_util::worker::FutureWorker; struct MockPdClient { configs: Mutex<HashMap<String, Config>>, } #[derive(Clone)] struct Config { version: Version, content: String, update: Vec<ConfigEntry>, } impl Config { fn new(version: Version, content: String, update: Vec<ConfigEntry>) -> Self { Config { version, content, update, } } } impl MockPdClient { fn new() -> Self { MockPdClient { configs: Mutex::new(HashMap::new()), } } fn register(self: Arc<Self>, id: &str, cfg: TiKvConfig) -> ConfigHandler { let (version, cfg) = ConfigHandler::create(id.to_owned(), self, cfg).unwrap(); ConfigHandler::start( id.to_owned(), ConfigController::new(cfg, version), FutureWorker::new("test-pd-worker").scheduler(), ) .unwrap() } fn update_cfg<F>(&self, id: &str, f: F) where F: Fn(&mut TiKvConfig), { let mut configs = self.configs.lock().unwrap(); let cfg = configs.get_mut(id).unwrap(); let mut config: TiKvConfig = toml::from_str(&cfg.content).unwrap(); f(&mut config); cfg.content = toml::to_string(&config).unwrap(); cfg.version.local += 1; } fn update_raw<F>(&self, id: &str, f: F) where F: Fn(&mut String), { let mut configs = self.configs.lock().unwrap(); let cfg = configs.get_mut(id).unwrap(); f(&mut cfg.content); cfg.version.local += 1; } fn get(&self, id: &str) -> Config { self.configs.lock().unwrap().get(id).unwrap().clone() } } impl ConfigClient for MockPdClient { fn register_config(&self, id: String, v: Version, cfg: String) -> Result<CreateResponse> { let old = self .configs .lock() .unwrap() .insert(id.clone(), Config::new(v.clone(), cfg.clone(), Vec::new())); assert!(old.is_none(), format!("id {} already be registered", id)); let mut status = Status::default(); status.set_code(StatusCode::Ok); let mut resp = CreateResponse::default(); resp.set_status(status); resp.set_config(cfg); resp.set_version(v); Ok(resp) } fn get_config(&self, id: String, version: Version) -> Result<GetResponse> { let mut resp = GetResponse::default(); let mut status = Status::default(); let configs = self.configs.lock().unwrap();
resp.set_status(status); Ok(resp) } fn update_config( &self, id: String, version: Version, mut entries: Vec<ConfigEntry>, ) -> Result<UpdateResponse> { let mut resp = UpdateResponse::default(); let mut status = Status::default(); if let Some(cfg) = self.configs.lock().unwrap().get_mut(&id) { match cmp_version(&cfg.version, &version) { Ordering::Equal => { cfg.update.append(&mut entries); cfg.version.local += 1; status.set_code(StatusCode::Ok); } _ => status.set_code(StatusCode::WrongVersion), } resp.set_version(cfg.version.clone()); } else { status.set_code(StatusCode::Unknown); } resp.set_status(status); Ok(resp) } } #[test] fn test_update_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let mut cfg = cfg_handler.get_config().clone(); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!(cfg_handler.get_config(), &cfg); pd_client.update_cfg(id, |cfg| { cfg.refresh_config_interval = ReadableDuration::hours(12); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); cfg.refresh_config_interval = ReadableDuration::hours(12); assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_update_not_support_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let cfg = cfg_handler.get_config().clone(); pd_client.update_cfg(id, |cfg| { cfg.server.addr = "localhost:3000".to_owned(); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_update_to_invalid() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg = TiKvConfig::default(); cfg.raft_store.raft_log_gc_threshold = 2000; let mut cfg_handler = pd_client.clone().register(id, cfg); pd_client.update_cfg(id, |cfg| { cfg.raft_store.raft_log_gc_threshold = 0; }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!( cfg_handler.get_config().raft_store.raft_log_gc_threshold, 2000 ); let cfg = pd_client.get(id); assert_eq!(cfg.update.len(), 1); assert_eq!(cfg.update[0].name, "raftstore.raft-log-gc-threshold"); assert_eq!(cfg.update[0].value, toml::to_string(&2000).unwrap()); } #[test] fn test_compatible_config() { let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let mut cfg_handler = pd_client.clone().register(id, TiKvConfig::default()); let mut cfg = cfg_handler.get_config().clone(); pd_client.update_raw(id, |cfg| { *cfg = " [new.config] xyz = 1 [raftstore] raft-log-gc-threshold = 2048 " .to_owned(); }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); cfg.raft_store.raft_log_gc_threshold = 2048; assert_eq!(cfg_handler.get_config(), &cfg); } #[test] fn test_dispatch_change() { use configuration::ConfigManager; use std::error::Error; use std::result::Result; #[derive(Clone)] struct CfgManager(Arc<Mutex<RaftstoreConfig>>); impl ConfigManager for CfgManager { fn dispatch(&mut self, c: ConfigChange) -> Result<(), Box<dyn Error>> { self.0.lock().unwrap().update(c); Ok(()) } } let pd_client = Arc::new(MockPdClient::new()); let id = "localhost:1080"; let cfg = TiKvConfig::default(); let mgr = CfgManager(Arc::new(Mutex::new(Default::default()))); let mut cfg_handler = { let (version, cfg) = ConfigHandler::create(id.to_owned(), pd_client.clone(), cfg).unwrap(); *mgr.0.lock().unwrap() = cfg.raft_store.clone(); let mut controller = ConfigController::new(cfg, version); controller.register(Module::Raftstore, Box::new(mgr.clone())); ConfigHandler::start( id.to_owned(), controller, FutureWorker::new("test-pd-worker").scheduler(), ) .unwrap() }; pd_client.update_cfg(id, |cfg| { cfg.raft_store.raft_log_gc_threshold = 2000; }); cfg_handler.refresh_config(pd_client.as_ref()).unwrap(); assert_eq!( cfg_handler.get_config().raft_store.raft_log_gc_threshold, 2000 ); assert_eq!(mgr.0.lock().unwrap().raft_log_gc_threshold, 2000); }
if let Some(cfg) = configs.get(&id) { match cmp_version(&cfg.version, &version) { Ordering::Equal => status.set_code(StatusCode::Ok), _ => { resp.set_config(cfg.content.clone()); status.set_code(StatusCode::WrongVersion); } } resp.set_version(cfg.version.clone()); } else { status.set_code(StatusCode::Unknown); }
if_condition
[ { "content": "fn config_to_slice(config_change: &[(String, String)]) -> Vec<(&str, &str)> {\n\n config_change\n\n .iter()\n\n .map(|(name, value)| (name.as_str(), value.as_str()))\n\n .collect()\n\n}\n\n\n", "file_path": "src/config.rs", "rank": 0, "score": 391110.64508115995...
Rust
editor/src/settings/mod.rs
Libertus-Lab/Fyrox
c925304f42744659fd3a6be5c4a1a8609556033a
use crate::{ inspector::editors::make_property_editors_container, settings::{ debugging::DebuggingSettings, graphics::GraphicsSettings, move_mode::MoveInteractionModeSettings, rotate_mode::RotateInteractionModeSettings, selection::SelectionSettings, }, GameEngine, Message, MSG_SYNC_FLAG, }; use fyrox::{ core::{ inspect::{Inspect, PropertyInfo}, pool::Handle, scope_profile, }, gui::{ button::{ButtonBuilder, ButtonMessage}, grid::{Column, GridBuilder, Row}, inspector::{ editors::{ enumeration::EnumPropertyEditorDefinition, inspectable::InspectablePropertyEditorDefinition, PropertyEditorDefinitionContainer, }, FieldKind, InspectorBuilder, InspectorContext, InspectorMessage, PropertyChanged, }, message::{MessageDirection, UiMessage}, scroll_viewer::ScrollViewerBuilder, stack_panel::StackPanelBuilder, widget::WidgetBuilder, window::{WindowBuilder, WindowMessage, WindowTitle}, HorizontalAlignment, Orientation, Thickness, UiNode, UserInterface, }, renderer::{CsmSettings, QualitySettings, ShadowMapPrecision}, utils::log::Log, }; use ron::ser::PrettyConfig; use serde::{Deserialize, Serialize}; use std::{fs::File, path::PathBuf, rc::Rc, sync::mpsc::Sender}; pub mod debugging; pub mod graphics; pub mod move_mode; pub mod rotate_mode; pub mod selection; pub struct SettingsWindow { window: Handle<UiNode>, ok: Handle<UiNode>, default: Handle<UiNode>, inspector: Handle<UiNode>, } #[derive(Deserialize, Serialize, PartialEq, Clone, Default, Debug, Inspect)] pub struct Settings { pub selection: SelectionSettings, pub graphics: GraphicsSettings, pub debugging: DebuggingSettings, pub move_mode_settings: MoveInteractionModeSettings, pub rotate_mode_settings: RotateInteractionModeSettings, } #[derive(Debug)] pub enum SettingsError { Io(std::io::Error), Ron(ron::Error), } impl From<std::io::Error> for SettingsError { fn from(e: std::io::Error) -> Self { Self::Io(e) } } impl From<ron::Error> for SettingsError { fn from(e: ron::Error) -> Self { Self::Ron(e) } } impl Settings { const FILE_NAME: &'static str = "settings.ron"; fn full_path() -> PathBuf { Self::FILE_NAME.into() } pub fn load() -> Result<Self, SettingsError> { let file = File::open(Self::full_path())?; Ok(ron::de::from_reader(file)?) } pub fn save(&self) -> Result<(), SettingsError> { let file = File::create(Self::full_path())?; ron::ser::to_writer_pretty(file, self, PrettyConfig::default())?; Ok(()) } fn make_property_editors_container( sender: Sender<Message>, ) -> Rc<PropertyEditorDefinitionContainer> { let container = make_property_editors_container(sender); container.insert(InspectablePropertyEditorDefinition::<GraphicsSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<SelectionSettings>::new()); container.insert(EnumPropertyEditorDefinition::<ShadowMapPrecision>::new()); container.insert(InspectablePropertyEditorDefinition::<DebuggingSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<CsmSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<QualitySettings>::new()); container.insert(InspectablePropertyEditorDefinition::< MoveInteractionModeSettings, >::new()); container.insert(InspectablePropertyEditorDefinition::< RotateInteractionModeSettings, >::new()); Rc::new(container) } fn handle_property_changed(&mut self, property_changed: &PropertyChanged) -> bool { if let FieldKind::Inspectable(ref inner) = property_changed.value { return match property_changed.name.as_ref() { Self::SELECTION => self.selection.handle_property_changed(&**inner), Self::GRAPHICS => self.graphics.handle_property_changed(&**inner), Self::DEBUGGING => self.debugging.handle_property_changed(&**inner), Self::MOVE_MODE_SETTINGS => { self.move_mode_settings.handle_property_changed(&**inner) } Self::ROTATE_MODE_SETTINGS => { self.rotate_mode_settings.handle_property_changed(&**inner) } _ => false, }; } false } } impl SettingsWindow { pub fn new(engine: &mut GameEngine) -> Self { let ok; let default; let ctx = &mut engine.user_interface.build_ctx(); let inspector = InspectorBuilder::new(WidgetBuilder::new()).build(ctx); let window = WindowBuilder::new(WidgetBuilder::new().with_width(500.0).with_height(600.0)) .open(false) .with_title(WindowTitle::Text("Settings".to_owned())) .with_content( GridBuilder::new( WidgetBuilder::new() .with_child( ScrollViewerBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(2.0)) .on_row(0), ) .with_content(inspector) .build(ctx), ) .with_child( StackPanelBuilder::new( WidgetBuilder::new() .on_row(1) .with_horizontal_alignment(HorizontalAlignment::Right) .with_child({ default = ButtonBuilder::new( WidgetBuilder::new() .with_width(80.0) .with_margin(Thickness::uniform(1.0)), ) .with_text("Default") .build(ctx); default }) .with_child({ ok = ButtonBuilder::new( WidgetBuilder::new() .with_width(80.0) .with_margin(Thickness::uniform(1.0)), ) .with_text("OK") .build(ctx); ok }), ) .with_orientation(Orientation::Horizontal) .build(ctx), ), ) .add_row(Row::stretch()) .add_row(Row::strict(25.0)) .add_column(Column::stretch()) .build(ctx), ) .build(ctx); Self { window, ok, default, inspector, } } pub fn open(&self, ui: &mut UserInterface, settings: &Settings, sender: &Sender<Message>) { ui.send_message(WindowMessage::open( self.window, MessageDirection::ToWidget, true, )); self.sync_to_model(ui, settings, sender); } fn sync_to_model(&self, ui: &mut UserInterface, settings: &Settings, sender: &Sender<Message>) { let context = InspectorContext::from_object( settings, &mut ui.build_ctx(), Settings::make_property_editors_container(sender.clone()), None, MSG_SYNC_FLAG, 0, ); ui.send_message(InspectorMessage::context( self.inspector, MessageDirection::ToWidget, context, )); } pub fn handle_message( &mut self, message: &UiMessage, engine: &mut GameEngine, settings: &mut Settings, sender: &Sender<Message>, ) { scope_profile!(); let old_settings = settings.clone(); if let Some(ButtonMessage::Click) = message.data::<ButtonMessage>() { if message.destination() == self.ok { engine.user_interface.send_message(WindowMessage::close( self.window, MessageDirection::ToWidget, )); } else if message.destination() == self.default { *settings = Default::default(); self.sync_to_model(&mut engine.user_interface, settings, sender); } } else if let Some(InspectorMessage::PropertyChanged(property_changed)) = message.data() { if message.destination() == self.inspector && !settings.handle_property_changed(property_changed) { Log::err(format!( "Unhandled property change: {}", property_changed.path() )) } } if settings != &old_settings { if settings.graphics.quality != engine.renderer.get_quality_settings() { if let Err(e) = engine .renderer .set_quality_settings(&settings.graphics.quality) { Log::err(format!( "An error occurred at attempt to set new graphics settings: {:?}", e )); } else { Log::info("New graphics quality settings were successfully set!".to_owned()); } } match settings.save() { Ok(_) => { Log::info("Settings were successfully saved!".to_owned()); } Err(e) => { Log::err(format!("Unable to save settings! Reason: {:?}!", e)); } }; } } }
use crate::{ inspector::editors::make_property_editors_container, settings::{ debugging::DebuggingSettings, graphics::GraphicsSettings, move_mode::MoveInteractionModeSettings, rotate_mode::RotateInteractionModeSettings, selection::SelectionSettings, }, GameEngine, Message, MSG_SYNC_FLAG, }; use fyrox::{ core::{ inspect::{Inspect, PropertyInfo}, pool::Handle, scope_profile, }, gui::{ button::{ButtonBuilder, ButtonMessage}, grid::{Column, GridBuilder, Row}, inspector::{ editors::{ enumeration::EnumPropertyEditorDefinition, inspectable::InspectablePropertyEditorDefinition, PropertyEditorDefinitionContainer, }, FieldKind, InspectorBuilder, InspectorContext, InspectorMessage, PropertyChanged, }, message::{MessageDirection, UiMessage}, scroll_viewer::ScrollViewerBuilder, stack_panel::StackPanelBuilder, widget::WidgetBuilder, window::{WindowBuilder, WindowMessage, WindowTitle}, HorizontalAlignment, Orientation, Thickness, UiNode, UserInterface, }, renderer::{CsmSettings, QualitySettings, ShadowMapPrecision}, utils::log::Log, }; use ron::ser::PrettyConfig; use serde::{Deserialize, Serialize}; use std::{fs::File, path::PathBuf, rc::Rc, sync::mpsc::Sender}; pub mod debugging; pub mod graphics; pub mod move_mode; pub mod rotate_mode; pub mod selection; pub struct SettingsWindow { window: Handle<UiNode>, ok: Handle<UiNode>, default: Handle<UiNode>, inspector: Handle<UiNode>, } #[derive(Deserialize, Serialize, PartialEq, Clone, Default, Debug, Inspect)] pub struct Settings { pub selection: SelectionSettings, pub graphics: GraphicsSettings, pub debugging: DebuggingSettings, pub move_mode_settings: MoveInteractionModeSettings, pub rotate_mode_settings: RotateInteractionModeSettings, } #[derive(Debug)] pub enum SettingsError { Io(std::io::Error), Ron(ron::Error), } impl From<std::io::Error> for SettingsError { fn from(e: std::io::Error) -> Self { Self::Io(e) } } impl From<ron::Error> for SettingsError { fn from(e: ron::Error) -> Self { Self::Ron(e) } } impl Settings { const FILE_NAME: &'static str = "settings.ron"; fn full_path() -> PathBuf { Self::FILE_NAME.into() } pub fn load() -> Result<Self, SettingsError> { let file = File::open(Self::full_path())?; Ok(ron::de::from_reader(file)?) } pub fn save(&self) -> Result<(), SettingsError> { let file = File::create(Self::full_path())?; ron::ser::to_writer_pretty(file, self, PrettyConfig::default())?; Ok(()) } fn make_property_editors_container( sender: Sender<Message>, ) -> Rc<PropertyEditorDefinitionContainer> { let container = make_property_editors_container(sender); container.insert(InspectablePropertyEditorDefinition::<GraphicsSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<SelectionSettings>::new()); container.insert(EnumPropertyEditorDefinition::<ShadowMapPrecision>::new()); container.insert(InspectablePropertyEditorDefinition::<DebuggingSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<CsmSettings>::new()); container.insert(InspectablePropertyEditorDefinition::<QualitySettings>::new()); container.insert(InspectablePropertyEditorDefinition::< MoveInteractionModeSettings, >::new()); container.insert(InspectablePropertyEditorDefinition::< RotateInteractionModeSettings, >::new()); Rc::new(container) } fn handle_property_changed(&mut self, property_changed: &PropertyChanged) -> bool { if let FieldKind::Inspectable(ref inner) = property_changed.value { return match property_changed.name.as_ref() { Self::SELECTION => self.selection.handle_property_changed(&**inner), Self::GRAPHICS => self.graphics.handle_property_changed(&**inner), Self::DEBUGGING => self.debugging.handle_property_changed(&**inner), Self::MOVE_MODE_SETTINGS => { self.move_mode_settings.handle_property_changed(&**inner) } Self::ROTATE_MODE_SETTINGS => { self.rotate_mode_settings.handle_property_changed(&**inner) } _ => false, }; } false } } impl SettingsWindow { pub fn new(engine: &mut GameEngine) -> Self { let ok; let default; let ctx = &mut engine.user_interface.build_ctx(); let inspector = InspectorBuilder::new(WidgetBuilder::new()).build(ctx); let window = WindowBuilder::new(WidgetBuilder::new().with_width(500.0).with_height(600.0)) .open(false) .with_title(WindowTitle::Text("Settings".to_owned())) .with_content( GridBuilder::new( WidgetBuilder::new() .with_child( ScrollViewerBuilder::new( WidgetBuilder::new() .with_margin(Thickness::uniform(2.0)) .on_row(0), ) .with_content(inspector) .build(ctx), ) .with_child( StackPanelBuilder::new( WidgetBuilder::new() .on_row(1) .with_horizontal_alignment(HorizontalAlignment::Right) .with_child({ default = ButtonBuilder::new( WidgetBuilder::new() .with_width(80.0) .with_margin(Thickness::uniform(1.0)), ) .with_text("Default") .build(ctx); default }) .with_child({ ok = ButtonBuilder::new( WidgetBuilder::new() .with_width(80.0) .with_margin(Thickness::uniform(1.0)), ) .with_text("OK") .build(ctx); ok }), ) .with_orientation(Orientation::Horizontal) .build(ctx), ), ) .add_row(Row::stretch()) .add_row(Row::strict(25.0)) .add_column(Column::stretch()) .build(ctx), ) .build(ctx); Self { window, ok, default, inspector, } } pub fn open(&self, ui: &mut UserInterface, settings: &Settings, sender: &Sender<Message>) { ui.send_message(WindowMessage::open( self.window, MessageDirection::ToWidget, true, )); self.sync_to_model(ui, settings, sender); } fn sync_to_model(&self, ui: &mut UserInterface, settings: &Settings, sender: &Sender<Message>) { let context = InspectorContext::from_object( settings, &mut ui.build_ctx(), Settings::make_property_editors_container(sender.clone()), None, MSG_SYNC_FLAG, 0, ); ui.send_message(InspectorMessage::context( self.inspector, MessageDirection::ToWidget, context, )); } pub fn handle_message( &mut self, message: &UiMessage, engine: &mut GameEngine, settings: &mut Settings, sender: &Sender<Message>, ) { scope_profile!(); let old_settings = settings.clone(); if let Some(ButtonMessage::Click) = message.data::<ButtonMessage>() { if message.destination() == self.ok { engine.user_interface.send_message(WindowMessage::close( self.window, MessageDirection::ToWidget, )); } else if message.destination() == self.default { *settings = Default::default(); self.sync_to_model(&mut engine.user_interface, settings, sender); } } else if let Some(InspectorMessage::PropertyChanged(property_changed)) = message.data() { if message.destination() == self.inspector && !settings.handle_property_changed(property_changed) { Log::err(format!( "Unhandled property change: {}", property_changed.path() )) } } if settings != &old_settings {
match settings.save() { Ok(_) => { Log::info("Settings were successfully saved!".to_owned()); } Err(e) => { Log::err(format!("Unable to save settings! Reason: {:?}!", e)); } }; } } }
if settings.graphics.quality != engine.renderer.get_quality_settings() { if let Err(e) = engine .renderer .set_quality_settings(&settings.graphics.quality) { Log::err(format!( "An error occurred at attempt to set new graphics settings: {:?}", e )); } else { Log::info("New graphics quality settings were successfully set!".to_owned()); } }
if_condition
[ { "content": "pub trait InspectableEnum: Debug + Inspect + 'static {}\n\n\n\nimpl<T: Debug + Inspect + 'static> InspectableEnum for T {}\n\n\n\n#[derive(Debug, Clone, PartialEq)]\n\npub enum EnumPropertyEditorMessage {\n\n Variant(usize),\n\n PropertyChanged(PropertyChanged),\n\n}\n\n\n\nimpl EnumProperty...
Rust
crates/rome_js_parser/src/parse.rs
mrkldshv/tools
c173b0c01ee499fcb49d6ae328f1229daa183868
use crate::token_source::Trivia; use crate::*; use rome_diagnostics::Severity; use rome_js_syntax::{ JsAnyRoot, JsExpressionSnipped, JsLanguage, JsModule, JsScript, JsSyntaxNode, ModuleKind, SourceType, }; use rome_rowan::AstNode; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct Parse<T> { root: JsSyntaxNode, errors: Vec<ParseDiagnostic>, _ty: PhantomData<T>, } impl<T> Parse<T> { pub fn new_module(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Self::new(root, errors) } pub fn new_script(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Self::new(root, errors) } pub fn new(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Parse { root, errors, _ty: PhantomData, } } pub fn cast<N: AstNode<Language = JsLanguage>>(self) -> Option<Parse<N>> { if N::can_cast(self.syntax().kind()) { Some(Parse::new(self.root, self.errors)) } else { None } } pub fn syntax(&self) -> JsSyntaxNode { self.root.clone() } pub fn diagnostics(&self) -> &[Diagnostic] { self.errors.as_slice() } pub fn into_diagnostics(self) -> Vec<Diagnostic> { self.errors } pub fn has_errors(&self) -> bool { self.errors.iter().any(|diagnostic| diagnostic.is_error()) } } impl<T: AstNode<Language = JsLanguage>> Parse<T> { pub fn tree(&self) -> T { self.try_tree().unwrap_or_else(|| { panic!( "Expected tree to be a {} but root is:\n{:#?}", std::any::type_name::<T>(), self.syntax() ) }) } pub fn try_tree(&self) -> Option<T> { T::cast(self.syntax()) } pub fn ok(self) -> Result<T, Vec<ParseDiagnostic>> { if !self.errors.iter().any(|d| d.severity == Severity::Error) { Ok(self.tree()) } else { Err(self.errors) } } } pub fn parse_common( text: &str, file_id: usize, source_type: SourceType, ) -> (Vec<Event>, Vec<ParseDiagnostic>, Vec<Trivia>) { let mut parser = crate::Parser::new(text, file_id, source_type); crate::syntax::program::parse(&mut parser); let (events, trivia, errors) = parser.finish(); (events, errors, trivia) } pub fn parse_script(text: &str, file_id: usize) -> Parse<JsScript> { parse( text, file_id, SourceType::js_module().with_module_kind(ModuleKind::Script), ) .cast::<JsScript>() .unwrap() } pub fn parse_module(text: &str, file_id: usize) -> Parse<JsModule> { parse(text, file_id, SourceType::js_module()) .cast::<JsModule>() .unwrap() } pub fn parse(text: &str, file_id: usize, source_type: SourceType) -> Parse<JsAnyRoot> { tracing::debug_span!("parse", file_id = file_id).in_scope(move || { let (events, errors, tokens) = parse_common(text, file_id, source_type); let mut tree_sink = LosslessTreeSink::new(text, &tokens); crate::process(&mut tree_sink, events, errors); let (green, parse_errors) = tree_sink.finish(); Parse::new(green, parse_errors) }) } pub fn parse_expression(text: &str, file_id: usize) -> Parse<JsExpressionSnipped> { let mut parser = crate::Parser::new(text, file_id, SourceType::js_module()); crate::syntax::expr::parse_expression_snipped(&mut parser).unwrap(); let (events, tokens, errors) = parser.finish(); let mut tree_sink = LosslessTreeSink::new(text, &tokens); crate::process(&mut tree_sink, events, errors); let (green, parse_errors) = tree_sink.finish(); Parse::new_script(green, parse_errors) }
use crate::token_source::Trivia; use crate::*; use rome_diagnostics::Severity; use rome_js_syntax::{ JsAnyRoot, JsExpressionSnipped, JsLanguage, JsModule, JsScript, JsSyntaxNode, ModuleKind, SourceType, }; use rome_rowan::AstNode; use std::marker::PhantomData; #[derive(Debug, Clone)] pub struct Parse<T> { root: JsSyntaxNode, errors: Vec<ParseDiagnostic>, _ty: PhantomData<T>, } impl<T> Parse<T> { pub fn new_module(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Self::new(root, errors) } pub fn new_script(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Self::new(root, errors) } pub fn new(root: JsSyntaxNode, errors: Vec<ParseDiagnostic>) -> Parse<T> { Parse { root, errors, _ty: PhantomData, } } pub fn cast<N: AstNode<Language = JsLanguage>>(self) -> Option<Parse<N>> { if N::can_cast(self.syntax().kind()) { Some(Parse::new(self.root, self.errors)) } else { None } } pub fn syntax(&self) -> JsSyntaxNode { self.root.clone() } pub fn diagnostics(&self) -> &[Diagnostic] { self.errors.as_slice() } pub fn into_diagnostics(self) -> Vec<Diagnostic> { self.errors } pub fn has_errors(&self) -> bool { self.errors.iter().any(|diagnostic| diagnostic.is_error()) } } impl<T: AstNode<Language = JsLanguage>> Parse<T> { pub fn tree(&self) -> T { self.try_tree().unwrap_or_else(|| { panic!( "Expected tree to be a {} but root is:\n{:#?}", std::any::type_name::<T>(), self.syntax() ) }) } pub fn try_tree(&self) -> Option<T> { T::cast(self.syntax()) }
} pub fn parse_common( text: &str, file_id: usize, source_type: SourceType, ) -> (Vec<Event>, Vec<ParseDiagnostic>, Vec<Trivia>) { let mut parser = crate::Parser::new(text, file_id, source_type); crate::syntax::program::parse(&mut parser); let (events, trivia, errors) = parser.finish(); (events, errors, trivia) } pub fn parse_script(text: &str, file_id: usize) -> Parse<JsScript> { parse( text, file_id, SourceType::js_module().with_module_kind(ModuleKind::Script), ) .cast::<JsScript>() .unwrap() } pub fn parse_module(text: &str, file_id: usize) -> Parse<JsModule> { parse(text, file_id, SourceType::js_module()) .cast::<JsModule>() .unwrap() } pub fn parse(text: &str, file_id: usize, source_type: SourceType) -> Parse<JsAnyRoot> { tracing::debug_span!("parse", file_id = file_id).in_scope(move || { let (events, errors, tokens) = parse_common(text, file_id, source_type); let mut tree_sink = LosslessTreeSink::new(text, &tokens); crate::process(&mut tree_sink, events, errors); let (green, parse_errors) = tree_sink.finish(); Parse::new(green, parse_errors) }) } pub fn parse_expression(text: &str, file_id: usize) -> Parse<JsExpressionSnipped> { let mut parser = crate::Parser::new(text, file_id, SourceType::js_module()); crate::syntax::expr::parse_expression_snipped(&mut parser).unwrap(); let (events, tokens, errors) = parser.finish(); let mut tree_sink = LosslessTreeSink::new(text, &tokens); crate::process(&mut tree_sink, events, errors); let (green, parse_errors) = tree_sink.finish(); Parse::new_script(green, parse_errors) }
pub fn ok(self) -> Result<T, Vec<ParseDiagnostic>> { if !self.errors.iter().any(|d| d.severity == Severity::Error) { Ok(self.tree()) } else { Err(self.errors) } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn process(sink: &mut impl TreeSink, mut events: Vec<Event>, errors: Vec<ParseDiagnostic>) {\n\n sink.errors(errors);\n\n let mut forward_parents = Vec::new();\n\n\n\n for i in 0..events.len() {\n\n match &mut events[i] {\n\n Event::Start {\n\n ...
Rust
couchbase-lite/src/query.rs
adrien-jeser-doctolib/couchbase-lite-rust
49ef36b21aef1817314cf98f679587be55604a7d
use crate::{ error::{c4error_init, Error}, ffi::{ c4query_new, c4query_new2, c4query_release, c4query_run, c4query_setParameters, c4queryenum_next, c4queryenum_release, kC4DefaultQueryOptions, kC4N1QLQuery, C4Query, C4QueryEnumerator, FLArrayIterator_GetCount, FLArrayIterator_GetValueAt, c4query_columnCount, c4query_columnTitle }, fl_slice::{fl_slice_empty, AsFlSlice}, value::{FromValueRef, ValueRef}, Database, Result, }; use fallible_streaming_iterator::FallibleStreamingIterator; use serde::Serialize; use std::ptr::NonNull; use crate::fl_slice::fl_slice_to_str_unchecked; use std::convert::TryFrom; pub struct Query<'db> { _db: &'db Database, inner: NonNull<C4Query>, } impl Drop for Query<'_> { fn drop(&mut self) { unsafe { c4query_release(self.inner.as_ptr()) }; } } impl Query<'_> { pub(crate) fn new<'a, 'b>(db: &'a Database, query_json: &'b str) -> Result<Query<'a>> { let mut c4err = c4error_init(); let query = unsafe { c4query_new( db.inner.0.as_ptr(), query_json.as_bytes().as_flslice(), &mut c4err, ) }; NonNull::new(query) .map(|inner| Query { _db: db, inner }) .ok_or_else(|| c4err.into()) } pub(crate) fn new_n1ql<'a, 'b>(db: &'a Database, query_n1ql: &'b str) -> Result<Query<'a>> { let mut c4err = c4error_init(); let mut out_error_pos: std::os::raw::c_int = -1; let query = unsafe { c4query_new2( db.inner.0.as_ptr(), kC4N1QLQuery, query_n1ql.as_bytes().as_flslice(), &mut out_error_pos, &mut c4err, ) }; NonNull::new(query) .map(|inner| Query { _db: db, inner }) .ok_or_else(|| c4err.into()) } pub fn set_parameters<T>(&self, parameters: &T) -> Result<()> where T: Serialize, { let param_string = serde_json::to_string(parameters)?; let param_slice = param_string.as_bytes().as_flslice(); unsafe { c4query_setParameters(self.inner.as_ptr(), param_slice); } Ok(()) } pub fn run(&self) -> Result<Enumerator> { let mut c4err = c4error_init(); let it = unsafe { c4query_run( self.inner.as_ptr(), &kC4DefaultQueryOptions, fl_slice_empty(), &mut c4err, ) }; NonNull::new(it) .map(|inner| Enumerator { _query: self, reach_end: false, inner, }) .ok_or_else(|| c4err.into()) } pub fn column_names(&self) -> Result<Vec<String>> { let col_count = unsafe { c4query_columnCount(self.inner.as_ptr()) }; let column_count = match usize::try_from(col_count) { Ok(value) => value, Err(_) => return Err(Error::LogicError("column count doesn't fit".to_string())), }; let mut names = Vec::with_capacity(column_count); for col_index in 0..col_count { let title = unsafe { c4query_columnTitle(self.inner.as_ptr(), col_index) }; let name = unsafe { fl_slice_to_str_unchecked(title).to_owned() }; names.push(name); } Ok(names) } } pub struct Enumerator<'query> { _query: &'query Query<'query>, reach_end: bool, inner: NonNull<C4QueryEnumerator>, } impl Drop for Enumerator<'_> { fn drop(&mut self) { unsafe { c4queryenum_release(self.inner.as_ptr()) }; } } impl<'en> FallibleStreamingIterator for Enumerator<'en> { type Error = crate::error::Error; type Item = Enumerator<'en>; fn advance(&mut self) -> Result<()> { if self.reach_end { return Ok(()); } let mut c4err = c4error_init(); if unsafe { c4queryenum_next(self.inner.as_ptr(), &mut c4err) } { Ok(()) } else { if c4err.code == 0 { self.reach_end = true; Ok(()) } else { Err(c4err.into()) } } } fn get(&self) -> Option<&Enumerator<'en>> { if !self.reach_end { Some(self) } else { None } } } impl<'a> Enumerator<'a> { pub fn get_raw_checked(&self, i: u32) -> Result<ValueRef<'a>> { let n = unsafe { FLArrayIterator_GetCount(&self.inner.as_ref().columns) }; if i >= n { return Err(Error::LogicError(format!( "Enumerator::get_raw_checked: Index out of bounds {} / {}", i, n ))); } let val: ValueRef = unsafe { FLArrayIterator_GetValueAt(&self.inner.as_ref().columns, i) }.into(); Ok(val) } pub fn get_checked<T>(&self, i: u32) -> Result<T> where T: FromValueRef<'a>, { let value_ref = self.get_raw_checked(i)?; FromValueRef::column_result(value_ref) } pub fn col_count(&self) -> u32 { unsafe { FLArrayIterator_GetCount(&self.inner.as_ref().columns) } } }
use crate::{ error::{c4error_init, Error}, ffi::{ c4query_new, c4query_new2, c4query_release, c4query_run, c4query_setParameters, c4queryenum_next, c4queryenum_release, kC4DefaultQueryOptions, kC4N1QLQuery, C4Query, C4QueryEnumerator, FLArrayIterator_GetCount, FLArrayIterator_GetValueAt, c4query_columnCount, c4query_columnTitle }, fl_slice::{fl_slice_empty, AsFlSlice}, value::{FromValueRef, ValueRef}, Database, Result, }; use fallible_streaming_iterator::FallibleStreamingIterator; use serde::Serialize; use std::ptr::NonNull; use crate::fl_slice::fl_slice_to_str_unchecked; use std::convert::TryFrom; pub struct Query<'db> { _db: &'db Database, inner: NonNull<C4Query>, } impl Drop for Query<'_> { fn drop(&mut self) { unsafe { c4query_release(self.inner.as_ptr()) }; } } impl Query<'_> { pub(crate) fn new<'a, 'b>(db: &'a Database, query_json: &'b str) -> Result<Query<'a>> { let mut c4err = c4error_init(); let query = unsafe { c4query_new( db.inner.0.as_ptr(),
.ok_or_else(|| c4err.into()) } pub(crate) fn new_n1ql<'a, 'b>(db: &'a Database, query_n1ql: &'b str) -> Result<Query<'a>> { let mut c4err = c4error_init(); let mut out_error_pos: std::os::raw::c_int = -1; let query = unsafe { c4query_new2( db.inner.0.as_ptr(), kC4N1QLQuery, query_n1ql.as_bytes().as_flslice(), &mut out_error_pos, &mut c4err, ) }; NonNull::new(query) .map(|inner| Query { _db: db, inner }) .ok_or_else(|| c4err.into()) } pub fn set_parameters<T>(&self, parameters: &T) -> Result<()> where T: Serialize, { let param_string = serde_json::to_string(parameters)?; let param_slice = param_string.as_bytes().as_flslice(); unsafe { c4query_setParameters(self.inner.as_ptr(), param_slice); } Ok(()) } pub fn run(&self) -> Result<Enumerator> { let mut c4err = c4error_init(); let it = unsafe { c4query_run( self.inner.as_ptr(), &kC4DefaultQueryOptions, fl_slice_empty(), &mut c4err, ) }; NonNull::new(it) .map(|inner| Enumerator { _query: self, reach_end: false, inner, }) .ok_or_else(|| c4err.into()) } pub fn column_names(&self) -> Result<Vec<String>> { let col_count = unsafe { c4query_columnCount(self.inner.as_ptr()) }; let column_count = match usize::try_from(col_count) { Ok(value) => value, Err(_) => return Err(Error::LogicError("column count doesn't fit".to_string())), }; let mut names = Vec::with_capacity(column_count); for col_index in 0..col_count { let title = unsafe { c4query_columnTitle(self.inner.as_ptr(), col_index) }; let name = unsafe { fl_slice_to_str_unchecked(title).to_owned() }; names.push(name); } Ok(names) } } pub struct Enumerator<'query> { _query: &'query Query<'query>, reach_end: bool, inner: NonNull<C4QueryEnumerator>, } impl Drop for Enumerator<'_> { fn drop(&mut self) { unsafe { c4queryenum_release(self.inner.as_ptr()) }; } } impl<'en> FallibleStreamingIterator for Enumerator<'en> { type Error = crate::error::Error; type Item = Enumerator<'en>; fn advance(&mut self) -> Result<()> { if self.reach_end { return Ok(()); } let mut c4err = c4error_init(); if unsafe { c4queryenum_next(self.inner.as_ptr(), &mut c4err) } { Ok(()) } else { if c4err.code == 0 { self.reach_end = true; Ok(()) } else { Err(c4err.into()) } } } fn get(&self) -> Option<&Enumerator<'en>> { if !self.reach_end { Some(self) } else { None } } } impl<'a> Enumerator<'a> { pub fn get_raw_checked(&self, i: u32) -> Result<ValueRef<'a>> { let n = unsafe { FLArrayIterator_GetCount(&self.inner.as_ref().columns) }; if i >= n { return Err(Error::LogicError(format!( "Enumerator::get_raw_checked: Index out of bounds {} / {}", i, n ))); } let val: ValueRef = unsafe { FLArrayIterator_GetValueAt(&self.inner.as_ref().columns, i) }.into(); Ok(val) } pub fn get_checked<T>(&self, i: u32) -> Result<T> where T: FromValueRef<'a>, { let value_ref = self.get_raw_checked(i)?; FromValueRef::column_result(value_ref) } pub fn col_count(&self) -> u32 { unsafe { FLArrayIterator_GetCount(&self.inner.as_ref().columns) } } }
query_json.as_bytes().as_flslice(), &mut c4err, ) }; NonNull::new(query) .map(|inner| Query { _db: db, inner })
function_block-random_span
[ { "content": "fn print_external_changes(db: &mut Option<Database>) -> Result<(), Box<dyn std::error::Error>> {\n\n let db = db\n\n .as_mut()\n\n .ok_or_else(|| format!(\"print_external_changes: db not OPEN\"))?;\n\n let mut doc_ids = HashSet::<String>::new();\n\n for change in db.observed...
Rust
src/rust/iced-x86/src/formatter/fast/options.rs
darfink/iced
6371d812392a02bd9c37cbe4f19d2dcdf33aacd4
struct Flags1; impl Flags1 { const SPACE_AFTER_OPERAND_SEPARATOR: u32 = 0x0000_0001; const RIP_RELATIVE_ADDRESSES: u32 = 0x0000_0002; const USE_PSEUDO_OPS: u32 = 0x0000_0004; const SHOW_SYMBOL_ADDRESS: u32 = 0x0000_0008; const ALWAYS_SHOW_SEGMENT_REGISTER: u32 = 0x0000_0010; const ALWAYS_SHOW_MEMORY_SIZE: u32 = 0x0000_0020; const UPPERCASE_HEX: u32 = 0x0000_0040; const USE_HEX_PREFIX: u32 = 0x0000_0080; } #[derive(Debug, Clone, Eq, PartialEq, Hash)] #[allow(missing_copy_implementations)] pub struct FastFormatterOptions { options1: u32, } impl FastFormatterOptions { #[must_use] #[inline] pub(super) fn new() -> Self { Self { options1: Flags1::USE_PSEUDO_OPS | Flags1::UPPERCASE_HEX } } #[must_use] #[inline] pub fn space_after_operand_separator(&self) -> bool { (self.options1 & Flags1::SPACE_AFTER_OPERAND_SEPARATOR) != 0 } #[inline] pub fn set_space_after_operand_separator(&mut self, value: bool) { if value { self.options1 |= Flags1::SPACE_AFTER_OPERAND_SEPARATOR; } else { self.options1 &= !Flags1::SPACE_AFTER_OPERAND_SEPARATOR; } } #[must_use] #[inline] pub fn rip_relative_addresses(&self) -> bool { (self.options1 & Flags1::RIP_RELATIVE_ADDRESSES) != 0 } #[inline] pub fn set_rip_relative_addresses(&mut self, value: bool) { if value { self.options1 |= Flags1::RIP_RELATIVE_ADDRESSES; } else { self.options1 &= !Flags1::RIP_RELATIVE_ADDRESSES; } } #[must_use] #[inline] pub fn use_pseudo_ops(&self) -> bool { (self.options1 & Flags1::USE_PSEUDO_OPS) != 0 } #[inline] pub fn set_use_pseudo_ops(&mut self, value: bool) { if value { self.options1 |= Flags1::USE_PSEUDO_OPS; } else { self.options1 &= !Flags1::USE_PSEUDO_OPS; } } #[must_use] #[inline] pub fn show_symbol_address(&self) -> bool { (self.options1 & Flags1::SHOW_SYMBOL_ADDRESS) != 0 } #[inline] pub fn set_show_symbol_address(&mut self, value: bool) { if value { self.options1 |= Flags1::SHOW_SYMBOL_ADDRESS; } else { self.options1 &= !Flags1::SHOW_SYMBOL_ADDRESS; } } #[must_use] #[inline] pub fn always_show_segment_register(&self) -> bool { (self.options1 & Flags1::ALWAYS_SHOW_SEGMENT_REGISTER) != 0 } #[inline] pub fn set_always_show_segment_register(&mut self, value: bool) { if value { self.options1 |= Flags1::ALWAYS_SHOW_SEGMENT_REGISTER; } else { self.options1 &= !Flags1::ALWAYS_SHOW_SEGMENT_REGISTER; } } #[must_use] #[inline] pub fn always_show_memory_size(&self) -> bool { (self.options1 & Flags1::ALWAYS_SHOW_MEMORY_SIZE) != 0 } #[inline] pub fn set_always_show_memory_size(&mut self, value: bool) { if value { self.options1 |= Flags1::ALWAYS_SHOW_MEMORY_SIZE; } else { self.options1 &= !Flags1::ALWAYS_SHOW_MEMORY_SIZE; } } #[must_use] #[inline] pub fn uppercase_hex(&self) -> bool { (self.options1 & Flags1::UPPERCASE_HEX) != 0 } #[inline] pub fn set_uppercase_hex(&mut self, value: bool) { if value { self.options1 |= Flags1::UPPERCASE_HEX; } else { self.options1 &= !Flags1::UPPERCASE_HEX; } } #[must_use] #[inline] pub fn use_hex_prefix(&self) -> bool { (self.options1 & Flags1::USE_HEX_PREFIX) != 0 } #[inline] pub fn set_use_hex_prefix(&mut self, value: bool) { if value { self.options1 |= Flags1::USE_HEX_PREFIX; } else { self.options1 &= !Flags1::USE_HEX_PREFIX; } } }
struct Flags1; impl Flags1 { const SPACE_AFTER_OPERAND_SEPARATOR: u32 = 0x0000_0001; const RIP_RELATIVE_ADDRESSES: u32 = 0x0000_0002; const USE_PSEUDO_OPS: u32 = 0x0000_0004; const SHOW_SYMBOL_ADDRESS: u32 = 0x0000_0008; const ALWAYS_SHOW_SEGMENT_REGISTER: u32 = 0x0000_0010; const ALWAYS_SHOW_MEMORY_SIZE: u32 = 0x0000_0020; const UPPERCASE_HEX: u32 = 0x0000_0040; const USE_HEX_PREFIX: u32 = 0x0000_0080; } #[derive(Debug, Clone, Eq, PartialEq, Hash)] #[allow(missing_copy_implementations)] pub struct FastFormatterOptions { options1: u32, } impl FastFormatterOptions { #[must_use] #[inline] pub(super) fn new() -> Self { Self { options1: Flags1::USE_PSEUDO_OPS | Flags1::UPPERCASE_HEX } } #[must_use] #[inline] pub fn space_after_operand_separator(&self) -> bool { (self.options1 & Flags1::SPACE_AFTER_OPERAND_SEPARATOR) != 0 } #[inline] pub fn set_space_after_operand_separator(&mut self, value: bool) { if value { self.options1 |= Flags1::SPACE_AFTER_OPERAND_SEPARATOR; } else { self.options1 &= !Flags1::SPACE_AFTER_OPERAND_SEPARATOR; } } #[must_use] #[inline] pub fn rip_relative_addresses(&self) -> bool { (self.options1 & Flags1::RIP_RELATIVE_ADDRESSES) != 0 } #[inline] pub fn set_rip_relative_addresses(&mut self, value: bool) {
} #[must_use] #[inline] pub fn use_pseudo_ops(&self) -> bool { (self.options1 & Flags1::USE_PSEUDO_OPS) != 0 } #[inline] pub fn set_use_pseudo_ops(&mut self, value: bool) { if value { self.options1 |= Flags1::USE_PSEUDO_OPS; } else { self.options1 &= !Flags1::USE_PSEUDO_OPS; } } #[must_use] #[inline] pub fn show_symbol_address(&self) -> bool { (self.options1 & Flags1::SHOW_SYMBOL_ADDRESS) != 0 } #[inline] pub fn set_show_symbol_address(&mut self, value: bool) { if value { self.options1 |= Flags1::SHOW_SYMBOL_ADDRESS; } else { self.options1 &= !Flags1::SHOW_SYMBOL_ADDRESS; } } #[must_use] #[inline] pub fn always_show_segment_register(&self) -> bool { (self.options1 & Flags1::ALWAYS_SHOW_SEGMENT_REGISTER) != 0 } #[inline] pub fn set_always_show_segment_register(&mut self, value: bool) { if value { self.options1 |= Flags1::ALWAYS_SHOW_SEGMENT_REGISTER; } else { self.options1 &= !Flags1::ALWAYS_SHOW_SEGMENT_REGISTER; } } #[must_use] #[inline] pub fn always_show_memory_size(&self) -> bool { (self.options1 & Flags1::ALWAYS_SHOW_MEMORY_SIZE) != 0 } #[inline] pub fn set_always_show_memory_size(&mut self, value: bool) { if value { self.options1 |= Flags1::ALWAYS_SHOW_MEMORY_SIZE; } else { self.options1 &= !Flags1::ALWAYS_SHOW_MEMORY_SIZE; } } #[must_use] #[inline] pub fn uppercase_hex(&self) -> bool { (self.options1 & Flags1::UPPERCASE_HEX) != 0 } #[inline] pub fn set_uppercase_hex(&mut self, value: bool) { if value { self.options1 |= Flags1::UPPERCASE_HEX; } else { self.options1 &= !Flags1::UPPERCASE_HEX; } } #[must_use] #[inline] pub fn use_hex_prefix(&self) -> bool { (self.options1 & Flags1::USE_HEX_PREFIX) != 0 } #[inline] pub fn set_use_hex_prefix(&mut self, value: bool) { if value { self.options1 |= Flags1::USE_HEX_PREFIX; } else { self.options1 &= !Flags1::USE_HEX_PREFIX; } } }
if value { self.options1 |= Flags1::RIP_RELATIVE_ADDRESSES; } else { self.options1 &= !Flags1::RIP_RELATIVE_ADDRESSES; }
if_condition
[ { "content": "fn read_infos(bitness: u32, is_misc: bool) -> (Vec<InstructionInfo>, HashSet<u32>) {\n\n\tlet mut filename = get_formatter_unit_tests_dir();\n\n\tif is_misc {\n\n\t\tfilename.push(format!(\"InstructionInfos{}_Misc.txt\", bitness));\n\n\t} else {\n\n\t\tfilename.push(format!(\"InstructionInfos{}.tx...
Rust
src/num_traits.rs
icewind1991/bitbuffer-rs
96c37a0bc32cac5c44b77c5c0b05b053735c2942
use crate::Endianness; use num_traits::PrimInt; use std::array::TryFromSliceError; use std::convert::TryFrom; use std::fmt::Debug; use std::ops::{BitOrAssign, BitXor}; pub trait UncheckedPrimitiveFloat: Sized { type BYTES: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = TryFromSliceError>; type INT: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt + BitXor + Debug + SplitFitUsize; fn from_f32_unchecked(n: f32) -> Self; fn from_f64_unchecked(n: f64) -> Self; fn to_bytes<E: Endianness>(self) -> Self::BYTES; fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self; fn to_int(self) -> Self::INT; fn from_int(int: Self::INT) -> Self; } impl UncheckedPrimitiveFloat for f32 { type BYTES = [u8; 4]; type INT = u32; #[inline(always)] fn from_f32_unchecked(n: f32) -> Self { n } #[inline(always)] fn from_f64_unchecked(n: f64) -> Self { n as f32 } fn to_bytes<E: Endianness>(self) -> Self::BYTES { if E::is_le() { self.to_le_bytes() } else { self.to_be_bytes() } } fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self { if E::is_le() { Self::from_le_bytes(bytes) } else { Self::from_be_bytes(bytes) } } fn to_int(self) -> Self::INT { Self::INT::from_le_bytes(self.to_le_bytes()) } fn from_int(int: Self::INT) -> Self { Self::from_le_bytes(int.to_le_bytes()) } } impl UncheckedPrimitiveFloat for f64 { type BYTES = [u8; 8]; type INT = u64; #[inline(always)] fn from_f32_unchecked(n: f32) -> Self { n as f64 } #[inline(always)] fn from_f64_unchecked(n: f64) -> Self { n } fn to_bytes<E: Endianness>(self) -> Self::BYTES { if E::is_le() { self.to_le_bytes() } else { self.to_be_bytes() } } fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self { if E::is_le() { Self::from_le_bytes(bytes) } else { Self::from_be_bytes(bytes) } } fn to_int(self) -> Self::INT { Self::INT::from_le_bytes(self.to_le_bytes()) } fn from_int(int: Self::INT) -> Self { Self::from_le_bytes(int.to_le_bytes()) } } pub trait UncheckedPrimitiveInt: Sized { fn from_u8_unchecked(n: u8) -> Self; fn from_i8_unchecked(n: i8) -> Self; fn from_u16_unchecked(n: u16) -> Self; fn from_i16_unchecked(n: i16) -> Self; fn from_u32_unchecked(n: u32) -> Self; fn from_i32_unchecked(n: i32) -> Self; fn from_u64_unchecked(n: u64) -> Self; fn from_i64_unchecked(n: i64) -> Self; fn from_u128_unchecked(n: u128) -> Self; fn from_i128_unchecked(n: i128) -> Self; fn from_usize_unchecked(n: usize) -> Self; fn from_isize_unchecked(n: isize) -> Self; fn into_u8_unchecked(self) -> u8; fn into_i8_unchecked(self) -> i8; fn into_u16_unchecked(self) -> u16; fn into_i16_unchecked(self) -> i16; fn into_u32_unchecked(self) -> u32; fn into_i32_unchecked(self) -> i32; fn into_u64_unchecked(self) -> u64; fn into_i64_unchecked(self) -> i64; fn into_u128_unchecked(self) -> u128; fn into_i128_unchecked(self) -> i128; fn into_usize_unchecked(self) -> usize; fn into_isize_unchecked(self) -> isize; fn from_unchecked<N: UncheckedPrimitiveInt>(n: N) -> Self; } macro_rules! impl_unchecked_int { ($type:ty, $conv:ident) => { impl UncheckedPrimitiveInt for $type { #[inline(always)] fn from_u8_unchecked(n: u8) -> Self { n as $type } #[inline(always)] fn from_i8_unchecked(n: i8) -> Self { n as $type } #[inline(always)] fn from_u16_unchecked(n: u16) -> Self { n as $type } #[inline(always)] fn from_i16_unchecked(n: i16) -> Self { n as $type } #[inline(always)] fn from_u32_unchecked(n: u32) -> Self { n as $type } #[inline(always)] fn from_i32_unchecked(n: i32) -> Self { n as $type } #[inline(always)] fn from_u64_unchecked(n: u64) -> Self { n as $type } #[inline(always)] fn from_i64_unchecked(n: i64) -> Self { n as $type } #[inline(always)] fn from_u128_unchecked(n: u128) -> Self { n as $type } #[inline(always)] fn from_i128_unchecked(n: i128) -> Self { n as $type } #[inline(always)] fn from_usize_unchecked(n: usize) -> Self { n as $type } #[inline(always)] fn from_isize_unchecked(n: isize) -> Self { n as $type } fn into_u8_unchecked(self) -> u8 { self as u8 } #[inline(always)] fn into_i8_unchecked(self) -> i8 { self as i8 } #[inline(always)] fn into_u16_unchecked(self) -> u16 { self as u16 } #[inline(always)] fn into_i16_unchecked(self) -> i16 { self as i16 } #[inline(always)] fn into_u32_unchecked(self) -> u32 { self as u32 } #[inline(always)] fn into_i32_unchecked(self) -> i32 { self as i32 } #[inline(always)] fn into_u64_unchecked(self) -> u64 { self as u64 } #[inline(always)] fn into_i64_unchecked(self) -> i64 { self as i64 } #[inline(always)] fn into_u128_unchecked(self) -> u128 { self as u128 } #[inline(always)] fn into_i128_unchecked(self) -> i128 { self as i128 } #[inline(always)] fn into_usize_unchecked(self) -> usize { self as usize } #[inline(always)] fn into_isize_unchecked(self) -> isize { self as isize } #[inline(always)] fn from_unchecked<N: UncheckedPrimitiveInt>(n: N) -> Self { n.$conv() } } }; } impl_unchecked_int!(u8, into_u8_unchecked); impl_unchecked_int!(i8, into_i8_unchecked); impl_unchecked_int!(u16, into_u16_unchecked); impl_unchecked_int!(i16, into_i16_unchecked); impl_unchecked_int!(u32, into_u32_unchecked); impl_unchecked_int!(i32, into_i32_unchecked); impl_unchecked_int!(u64, into_u64_unchecked); impl_unchecked_int!(i64, into_i64_unchecked); impl_unchecked_int!(u128, into_u128_unchecked); impl_unchecked_int!(i128, into_i128_unchecked); impl_unchecked_int!(usize, into_usize_unchecked); impl_unchecked_int!(isize, into_isize_unchecked); pub trait IsSigned { fn is_signed() -> bool; } macro_rules! impl_is_signed { ($type:ty, $signed:expr) => { impl IsSigned for $type { #[inline(always)] fn is_signed() -> bool { $signed } } }; } impl_is_signed!(u8, false); impl_is_signed!(u16, false); impl_is_signed!(u32, false); impl_is_signed!(u64, false); impl_is_signed!(u128, false); impl_is_signed!(usize, false); impl_is_signed!(i8, true); impl_is_signed!(i16, true); impl_is_signed!(i32, true); impl_is_signed!(i64, true); impl_is_signed!(i128, true); impl_is_signed!(isize, true); pub trait SplitFitUsize { type Iter: Iterator<Item = (usize, u8)> + ExactSizeIterator + DoubleEndedIterator; fn split_fit_usize<E: Endianness>(self) -> Self::Iter; } use std::array; use std::mem::size_of; macro_rules! impl_split_fit { ($type:ty) => { impl SplitFitUsize for $type { type Iter = array::IntoIter<(usize, u8), 1>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { assert!(size_of::<Self>() < size_of::<usize>()); [(self as usize, size_of::<Self>() as u8 * 8)].into_iter() } } }; } macro_rules! impl_split_fit_signed { ($signed_type:ty, $unsigned_type:ty) => { impl SplitFitUsize for $signed_type { type Iter = <$unsigned_type as SplitFitUsize>::Iter; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { let unsigned = <$unsigned_type>::from_ne_bytes(self.to_ne_bytes()); unsigned.split_fit_usize::<E>() } } }; } impl_split_fit!(u8); impl_split_fit!(u16); impl_split_fit!(i8); impl_split_fit!(i16); #[cfg(target_pointer_width = "64")] impl_split_fit!(u32); #[cfg(target_pointer_width = "32")] impl SplitFitUsize for u32 { type Iter = array::IntoIter<(usize, u8), 2>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { Self::Iter::new(if E::is_le() { [ ((self & (Self::MAX >> 8)) as usize, 24), ((self >> 24) as usize, 8), ] } else { [ ((self >> 24) as usize, 8), ((self & (Self::MAX >> 8)) as usize, 24), ] }) } } impl_split_fit_signed!(i32, u32); impl SplitFitUsize for u64 { type Iter = array::IntoIter<(usize, u8), 3>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ((self & (Self::MAX >> 40)) as usize, 24), ((self >> 24 & (Self::MAX >> 16)) as usize, 24), ((self >> 48) as usize, 16), ] } else { [ ((self >> 48) as usize, 16), ((self >> 24 & (Self::MAX >> 16)) as usize, 24), ((self & (Self::MAX >> 40)) as usize, 24), ] }) .into_iter() } } impl_split_fit_signed!(i64, u64); impl SplitFitUsize for u128 { type Iter = array::IntoIter<(usize, u8), 6>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ((self & (Self::MAX >> 104)) as usize, 24), ((self >> 24 & (Self::MAX >> 80)) as usize, 24), ((self >> 48 & (Self::MAX >> 56)) as usize, 24), ((self >> 72 & (Self::MAX >> 32)) as usize, 24), ((self >> 96 & (Self::MAX >> 8)) as usize, 24), ((self >> 120) as usize, 8), ] } else { [ ((self >> 120) as usize, 8), ((self >> 96 & (Self::MAX >> 8)) as usize, 24), ((self >> 72 & (Self::MAX >> 32)) as usize, 24), ((self >> 48 & (Self::MAX >> 56)) as usize, 24), ((self >> 24 & (Self::MAX >> 80)) as usize, 24), ((self & (Self::MAX >> 104)) as usize, 24), ] }) .into_iter() } } impl_split_fit_signed!(i128, u128); impl SplitFitUsize for usize { type Iter = array::IntoIter<(usize, u8), 2>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ( (self & (Self::MAX >> (usize::BITS - 8))) as usize, usize::BITS as u8 - 8, ), ((self >> (usize::BITS - 8)) as usize, 8), ] } else { [ ((self >> (usize::BITS - 8)) as usize, 8), ( (self & (Self::MAX >> (usize::BITS - 8))) as usize, usize::BITS as u8 - 8, ), ] }) .into_iter() } } impl_split_fit_signed!(isize, usize);
use crate::Endianness; use num_traits::PrimInt; use std::array::TryFromSliceError; use std::convert::TryFrom; use std::fmt::Debug; use std::ops::{BitOrAssign, BitXor}; pub trait UncheckedPrimitiveFloat: Sized { type BYTES: AsRef<[u8]> + for<'a> TryFrom<&'a [u8], Error = TryFromSliceError>; type INT: PrimInt + BitOrAssign + IsSigned + UncheckedPrimitiveInt + BitXor + Debug + SplitFitUsize; fn from_f32_unchecked(n: f32) -> Self; fn from_f64_unchecked(n: f64) -> Self; fn to_bytes<E: Endianness>(self) -> Self::BYTES; fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self; fn to_int(self) -> Self::INT; fn from_int(int: Self::INT) -> Self; } impl UncheckedPrimitiveFloat for f32 { type BYTES = [u8; 4]; type INT = u32; #[inline(always)] fn from_f32_unchecked(n: f32) -> Self { n } #[inline(always)] fn from_f64_unchecked(n: f64) -> Self { n as f32 } fn to_bytes<E: Endianness>(self) -> Self::BYTES { if E::is_le() { self.to_le_bytes() } else { self.to_be_bytes() } } fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self { if E::is_le() { Self::from_le_bytes(bytes) } else { Self::from_be_bytes(bytes) } } fn to_int(self) -> Self::INT { Self::INT::from_le_bytes(self.to_le_bytes()) } fn from_int(int: Self::INT) -> Self { Self::from_le_bytes(int.to_le_bytes()) } } impl UncheckedPrimitiveFloat for f64 { type BYTES = [u8; 8]; type INT = u64; #[inline(always)] fn from_f32_unchecked(n: f32) -> Self { n as f64 } #[inline(always)] fn from_f64_unchecked(n: f64) -> Self { n } fn to_bytes<E: Endianness>(self) -> Self::BYTES { if E::is_le() { self.to_le_bytes() } else { self.to_be_bytes() } } fn from_bytes<E: Endianness>(bytes: Self::BYTES) -> Self { if E::is_le() { Self::from_le_bytes(bytes) } else { Self::from_be_bytes(bytes) } } fn to_int(self) -> Self::INT { Self::INT::from_le_bytes(self.to_le_bytes()) } fn from_int(int: Self::INT) -> Self { Self::from_le_bytes(int.to_le_bytes()) } } pub trait UncheckedPrimitiveInt: Sized { fn from_u8_unchecked(n: u8) -> Self; fn from_i8_unchecked(n: i8) -> Self; fn from_u16_unchecked(n: u16) -> Self; fn from_i16_unchecked(n: i16) -> Self; fn from_u32_unchecked(n: u32) -> Self; fn from_i32_unchecked(n: i32) -> Self; fn from_u64_unchecked(n: u64) -> Self; fn from_i64_unchecked(n: i64) -> Self; fn from_u128_unchecked(n: u128) -> Self; fn from_i128_unchecked(n: i128) -> Self; fn from_usize_unchecked(n: usize) -> Self; fn from_isize_unchecked(n: isize) -> Self; fn into_u8_unchecked(self) -> u8; fn into_i8_unchecked(self) -> i8; fn into_u16_unchecked(self) -> u16; fn into_i16_unchecked(self) -> i16; fn into_u32_unchecked(self) -> u32; fn into_i32_unchecked(self) -> i32; fn into_u64_unchecked(self) -> u64; fn into_i64_unchecked(self) -> i64; fn into_u128_unchecked(self) -> u128; fn into_i128_unchecked(self) -> i128; fn into_usize_unchecked(self) -> usize; fn into_isize_unchecked(self) -> isize; fn from_unchecked<N: UncheckedPrimitiveInt>(n: N) -> Self; } macro_rules! impl_unchecked_int { ($type:ty, $conv:ident) => { impl UncheckedPrimitiveInt for $type { #[inline(always)] fn from_u8_unchecked(n: u8) -> Self { n as $type } #[inline(always)] fn from_i8_unchecked(n: i8) -> Self { n as $type } #[inline(always)] fn from_u16_unchecked(n: u16) -> Self { n as $type } #[inline(always)] fn from_i16_unchecked(n: i16) -> Self { n as $type } #[inline(always)] fn from_u32_unchecked(n: u32) -> Self { n as $type } #[inline(always)] fn from_i32_unchecked(n: i32) -> Self { n as $type } #[inline(always)] fn from_u64_unchecked(n: u64) -> Self { n as $type } #[inline(always)] fn from_i64_unchecked(n: i64) -> Self { n as $type } #[inline(always)] fn from_u128_unchecked(n: u128) -> Self { n as $type } #[inline(always)] fn from_i128_unchecked(n: i128) -> Self { n as $type } #[inline(always)] fn from_usize_unchecked(n: usize) -> Self { n as $type } #[inline(always)] fn from_isize_unchecked(n: isize) -> Self { n as $type } fn into_u8_unchecked(self) -> u8 { self as u8 } #[inline(always)] fn into_i8_unchecked(self) -> i8 { self as i8 } #[inline(always)] fn into_u16_unchecked(self) -> u16 { self as u16 } #[inline(always)] fn into_i16_unchecked(self) -> i16 { self as i16 } #[inline(always)] fn into_u32_unchecked(self) -> u32 { self as u32 } #[inline(always)] fn into_i32_unchecked(self) -> i32 { self as i32 } #[inline(always)] fn into_u64_unchecked(self) -> u64 { self as u64 } #[inline(always)] fn into_i64_unchecked(self) -> i64 { self as i64 } #[inline(always)] fn into_u128_unchecked(self) -> u128 { self as u128 } #[inline(always)] fn into_i128_unchecked(self) -> i128 { self as i128 } #[inline(always)] fn into_usize_unchecked(self) -> usize { self as usize } #[inline(always)] fn into_isize_unchecked(self) -> isize { self as isize } #[inline(always)] fn from_unchecked<N: UncheckedPrimitiveInt>(n: N) -> Self { n.$conv() } } }; } impl_unchecked_int!(u8, into_u8_unchecked); impl_unchecked_int!(i8, into_i8_unchecked); impl_unchecked_int!(u16, into_u16_unchecked); impl_unchecked_int!(i16, into_i16_unchecked); impl_unchecked_int!(u32, into_u32_unchecked); impl_unchecked_int!(i32, into_i32_unchecked); impl_unchecked_int!(u64, into_u64_unchecked); impl_unchecked_int!(i64, into_i64_unchecked); impl_unchecked_int!(u128, into_u128_unchecked); impl_unchecked_int!(i128, into_i128_unchecked); impl_unchecked_int!(usize, into_usize_unchecked); impl_unchecked_int!(isize, into_isize_unchecked); pub trait IsSigned { fn is_signed() -> bool; } macro_rules! impl_is_signed { ($type:ty, $signed:expr) => { impl IsSigned for $type { #[inline(always)] fn is_signed() -> bool { $signed } } }; } impl_is_signed!(u8, false); impl_is_signed!(u16, false); impl_is_signed!(u32, false); impl_is_signed!(u64, false); impl_is_signed!(u128, false); impl_is_signed!(usize, false); impl_is_signed!(i8, true); impl_is_signed!(i16, true); impl_is_signed!(i32, true); impl_is_signed!(i64, true); impl_is_signed!(i128, true); impl_is_signed!(isize, true); pub trait SplitFitUsize { type Iter: Iterator<Item = (usize, u8)> + ExactSizeIterator + DoubleEndedIterator; fn split_fit_usize<E: Endianness>(self) -> Self::Iter; } use std::array; use std::mem::size_of; macro_rules! impl_split_fit { ($type:ty) => { impl SplitFitUsize for $type { type Iter = array::IntoIter<(usize, u8), 1>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { assert!(size_of::<Self>() < size_of::<usize>()); [(self as usize, size_of::<Self>() as u8 * 8)].into_iter() } } }; } macro_rules! impl_split_fit_signed { ($signed_type:ty, $unsigned_type:ty) => { impl SplitFitUsize for $signed_type { type Iter = <$unsigned_type as SplitFitUsize>::Iter; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { let unsigned = <$unsigned_type>::from_ne_bytes(self.to_ne_bytes()); unsigned.split_fit_usize::<E>() } } }; } impl_split_fit!(u8); impl_split_fit!(u16); impl_split_fit!(i8); impl_split_fit!(i16); #[cfg(target_pointer_width = "64")] impl_split_fit!(u32); #[cfg(target_pointer_width = "32")] impl SplitFitUsize for u32 { type Iter = array::IntoIter<(usize, u8), 2>;
} impl_split_fit_signed!(i32, u32); impl SplitFitUsize for u64 { type Iter = array::IntoIter<(usize, u8), 3>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ((self & (Self::MAX >> 40)) as usize, 24), ((self >> 24 & (Self::MAX >> 16)) as usize, 24), ((self >> 48) as usize, 16), ] } else { [ ((self >> 48) as usize, 16), ((self >> 24 & (Self::MAX >> 16)) as usize, 24), ((self & (Self::MAX >> 40)) as usize, 24), ] }) .into_iter() } } impl_split_fit_signed!(i64, u64); impl SplitFitUsize for u128 { type Iter = array::IntoIter<(usize, u8), 6>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ((self & (Self::MAX >> 104)) as usize, 24), ((self >> 24 & (Self::MAX >> 80)) as usize, 24), ((self >> 48 & (Self::MAX >> 56)) as usize, 24), ((self >> 72 & (Self::MAX >> 32)) as usize, 24), ((self >> 96 & (Self::MAX >> 8)) as usize, 24), ((self >> 120) as usize, 8), ] } else { [ ((self >> 120) as usize, 8), ((self >> 96 & (Self::MAX >> 8)) as usize, 24), ((self >> 72 & (Self::MAX >> 32)) as usize, 24), ((self >> 48 & (Self::MAX >> 56)) as usize, 24), ((self >> 24 & (Self::MAX >> 80)) as usize, 24), ((self & (Self::MAX >> 104)) as usize, 24), ] }) .into_iter() } } impl_split_fit_signed!(i128, u128); impl SplitFitUsize for usize { type Iter = array::IntoIter<(usize, u8), 2>; fn split_fit_usize<E: Endianness>(self) -> Self::Iter { (if E::is_le() { [ ( (self & (Self::MAX >> (usize::BITS - 8))) as usize, usize::BITS as u8 - 8, ), ((self >> (usize::BITS - 8)) as usize, 8), ] } else { [ ((self >> (usize::BITS - 8)) as usize, 8), ( (self & (Self::MAX >> (usize::BITS - 8))) as usize, usize::BITS as u8 - 8, ), ] }) .into_iter() } } impl_split_fit_signed!(isize, usize);
fn split_fit_usize<E: Endianness>(self) -> Self::Iter { Self::Iter::new(if E::is_le() { [ ((self & (Self::MAX >> 8)) as usize, 24), ((self >> 24) as usize, 8), ] } else { [ ((self >> 24) as usize, 8), ((self & (Self::MAX >> 8)) as usize, 24), ] }) }
function_block-full_function
[ { "content": "fn type_is_int(ty: &Type) -> bool {\n\n if let Type::Path(path) = ty {\n\n if let Some(ident) = path.path.get_ident() {\n\n let name = ident.to_string();\n\n matches!(\n\n name.as_str(),\n\n \"u8\" | \"u16\" | \"u32\" | \"u64\" | \"usiz...
Rust
quibitous/src/blockchain/bootstrap.rs
The-Blockchain-Company/quibitous
a93cedb5c9d833f6e82429286faaf4f15e9e15a0
use super::tip::TipUpdater; use crate::blockcfg::{Block, HeaderHash}; use crate::blockchain::{ chain::{CheckHeaderProof, StreamInfo, StreamReporter}, Blockchain, Ref, Tip, }; use crate::metrics::Metrics; use chain_core::property::Deserialize; use chain_network::data as net_data; use chain_network::error::Error as NetworkError; use futures::prelude::*; use tokio_util::sync::CancellationToken; use std::sync::Arc; #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] BlockchainError(Box<super::Error>), #[error("received block {0} is not connected to the block chain")] BlockMissingParent(HeaderHash), #[error("bootstrap pull stream failed")] PullStreamFailed(#[source] NetworkError), #[error("failures while deserializing block from stream")] BlockDeserialize(#[from] std::io::Error), #[error("the bootstrap process was interrupted")] Interrupted, } pub async fn bootstrap_from_stream<S>( blockchain: Blockchain, branch: Tip, stream: S, cancellation_token: CancellationToken, ) -> Result<Option<Arc<Ref>>, Error> where S: Stream<Item = Result<net_data::Block, NetworkError>> + Unpin, { let block0 = *blockchain.block0(); let mut tip_updater = TipUpdater::new( branch, blockchain.clone(), None, None, Metrics::builder().build(), ); let mut bootstrap_info = StreamReporter::new(report); let mut maybe_parent_tip = None; let cancel = cancellation_token.cancelled(); tokio::pin!(cancel); let mut stream = stream .map_err(Error::PullStreamFailed) .map(|maybe_block| maybe_block.and_then(|b| Ok(Block::deserialize(b.as_bytes())?))) .take_until(cancel); while let Some(block_result) = stream.next().await { let maybe_tip = match block_result { Ok(block) => { if block.header().hash() == block0 { continue; } bootstrap_info.append_block(&block); blockchain .handle_bootstrap_block(block, CheckHeaderProof::Enabled) .await .map_err(|e| Error::BlockchainError(Box::new(e))) } Err(err) => Err(err), }; match maybe_tip { Ok(parent_tip) => { maybe_parent_tip = Some(parent_tip); } Err(err) => { if let Some(bootstrap_tip) = maybe_parent_tip { tip_updater .process_new_ref(bootstrap_tip) .await .map_err(|e| Error::BlockchainError(Box::new(e)))?; } return Err(err); } } } if let Some(ref bootstrap_tip) = maybe_parent_tip { tip_updater .process_new_ref(bootstrap_tip.clone()) .await .map_err(|e| Error::BlockchainError(Box::new(e)))?; } else { tracing::info!("no new blocks received from the network"); } if stream.take_result().is_some() { return Err(Error::Interrupted); } Ok(maybe_parent_tip) } fn report(stream_info: &StreamInfo) { fn print_sz(n: f64) -> String { if n > 1_000_000.0 { format!("{:.2}mb", n / (1024 * 1024) as f64) } else if n > 1_000.0 { format!("{:.2}kb", n / 1024_f64) } else { format!("{:.2}b", n) } } let current = std::time::SystemTime::now(); let time_diff = current.duration_since(stream_info.last_reported); let bytes_diff = stream_info.bytes_received - stream_info.last_bytes_received; let bytes = print_sz(bytes_diff as f64); let kbs = time_diff .map(|td| { let v = (bytes_diff as f64) / td.as_secs_f64(); print_sz(v) }) .unwrap_or_else(|_| "N/A".to_string()); tracing::info!( "receiving from network bytes={} {}/s, blockchain {}", bytes, kbs, stream_info .last_block_description .as_ref() .map(|lbd| lbd.to_string()) .expect("append_block should always be called before report") ) }
use super::tip::TipUpdater; use crate::blockcfg::{Block, HeaderHash}; use crate::blockchain::{ chain::{CheckHeaderProof, StreamInfo, StreamReporter}, Blockchain, Ref, Tip, }; use crate::metrics::Metrics; use chain_core::property::Deserialize; use chain_network::data as net_data; use chain_network::error::Error as NetworkError; use futures::prelude::*; use tokio_util::sync::CancellationToken; use std::sync::Arc; #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] BlockchainError(Box<super::Error>), #[error("received block {0} is not connected to the block chain")] BlockMissingParent(HeaderHash),
map_err(|e| Error::BlockchainError(Box::new(e))) } Err(err) => Err(err), }; match maybe_tip { Ok(parent_tip) => { maybe_parent_tip = Some(parent_tip); } Err(err) => { if let Some(bootstrap_tip) = maybe_parent_tip { tip_updater .process_new_ref(bootstrap_tip) .await .map_err(|e| Error::BlockchainError(Box::new(e)))?; } return Err(err); } } } if let Some(ref bootstrap_tip) = maybe_parent_tip { tip_updater .process_new_ref(bootstrap_tip.clone()) .await .map_err(|e| Error::BlockchainError(Box::new(e)))?; } else { tracing::info!("no new blocks received from the network"); } if stream.take_result().is_some() { return Err(Error::Interrupted); } Ok(maybe_parent_tip) } fn report(stream_info: &StreamInfo) { fn print_sz(n: f64) -> String { if n > 1_000_000.0 { format!("{:.2}mb", n / (1024 * 1024) as f64) } else if n > 1_000.0 { format!("{:.2}kb", n / 1024_f64) } else { format!("{:.2}b", n) } } let current = std::time::SystemTime::now(); let time_diff = current.duration_since(stream_info.last_reported); let bytes_diff = stream_info.bytes_received - stream_info.last_bytes_received; let bytes = print_sz(bytes_diff as f64); let kbs = time_diff .map(|td| { let v = (bytes_diff as f64) / td.as_secs_f64(); print_sz(v) }) .unwrap_or_else(|_| "N/A".to_string()); tracing::info!( "receiving from network bytes={} {}/s, blockchain {}", bytes, kbs, stream_info .last_block_description .as_ref() .map(|lbd| lbd.to_string()) .expect("append_block should always be called before report") ) }
#[error("bootstrap pull stream failed")] PullStreamFailed(#[source] NetworkError), #[error("failures while deserializing block from stream")] BlockDeserialize(#[from] std::io::Error), #[error("the bootstrap process was interrupted")] Interrupted, } pub async fn bootstrap_from_stream<S>( blockchain: Blockchain, branch: Tip, stream: S, cancellation_token: CancellationToken, ) -> Result<Option<Arc<Ref>>, Error> where S: Stream<Item = Result<net_data::Block, NetworkError>> + Unpin, { let block0 = *blockchain.block0(); let mut tip_updater = TipUpdater::new( branch, blockchain.clone(), None, None, Metrics::builder().build(), ); let mut bootstrap_info = StreamReporter::new(report); let mut maybe_parent_tip = None; let cancel = cancellation_token.cancelled(); tokio::pin!(cancel); let mut stream = stream .map_err(Error::PullStreamFailed) .map(|maybe_block| maybe_block.and_then(|b| Ok(Block::deserialize(b.as_bytes())?))) .take_until(cancel); while let Some(block_result) = stream.next().await { let maybe_tip = match block_result { Ok(block) => { if block.header().hash() == block0 { continue; } bootstrap_info.append_block(&block); blockchain .handle_bootstrap_block(block, CheckHeaderProof::Enabled) .await .
random
[ { "content": "fn network_block_error_into_reply(err: chain::Error) -> intercom::Error {\n\n use super::chain::Error::*;\n\n\n\n match err {\n\n Storage(e) => intercom::Error::failed(e),\n\n Ledger(e) => intercom::Error::failed_precondition(e),\n\n Block0(e) => intercom::Error::failed(...
Rust
src/main.rs
azerupi/cube-parse
ee5af4aa48755449bab7d7afe01166e029791ffc
use std::{collections::HashMap, env, path::Path}; use alphanumeric_sort::compare_str; use clap::{App, Arg}; use lazy_static::lazy_static; use regex::Regex; mod family; mod internal_peripheral; mod mcu; mod utils; #[derive(Debug, PartialEq)] enum GenerateTarget { Features, PinMappings, EepromSizes, } lazy_static! { static ref GPIO_VERSION: Regex = Regex::new("^([^_]*)_gpio_v1_0$").unwrap(); } fn gpio_version_to_feature(version: &str) -> Result<String, String> { if let Some(captures) = GPIO_VERSION.captures(version) { Ok(format!("io-{}", captures.get(1).unwrap().as_str())) } else { Err(format!("Could not parse version {:?}", version)) } } fn eeprom_size_to_feature(size: u32) -> String { format!("eeprom-{}", size) } fn flash_size_to_feature(size: u32) -> String { format!("flash-{}", size) } fn ram_size_to_feature(size: u32) -> String { format!("ram-{}", size) } fn main() -> Result<(), String> { let args = App::new("cube-parse") .version(env!("CARGO_PKG_VERSION")) .about("Extract AF modes on MCU pins from the database files provided with STM32CubeMX") .author(&*env!("CARGO_PKG_AUTHORS").replace(":", ", ")) .arg( Arg::with_name("db_dir") .short("d") .help("Path to the CubeMX MCU database directory") .takes_value(true) .required(true), ) .arg( Arg::with_name("generate") .help("What to generate") .takes_value(true) .possible_values(&["features", "pin_mappings", "eeprom_sizes"]) .required(true), ) .arg( Arg::with_name("mcu_family") .help("The MCU family to extract, e.g. \"STM32L0\"") .takes_value(true) .required(true), ) .get_matches(); let db_dir = Path::new(args.value_of("db_dir").unwrap()); let mcu_family = args.value_of("mcu_family").unwrap(); let generate = match args.value_of("generate").unwrap() { "features" => GenerateTarget::Features, "pin_mappings" => GenerateTarget::PinMappings, "eeprom_sizes" => GenerateTarget::EepromSizes, _ => unreachable!(), }; let families = family::Families::load(&db_dir) .map_err(|e| format!("Could not load families XML: {}", e))?; let family = (&families) .into_iter() .find(|v| v.name == mcu_family) .ok_or_else(|| format!("Could not find family {}", mcu_family))?; let mut mcu_map: HashMap<String, (&family::Mcu, mcu::Mcu)> = HashMap::new(); let mut mcu_gpio_map: HashMap<String, Vec<String>> = HashMap::new(); let mut mcu_package_map: HashMap<String, String> = HashMap::new(); let mut mcu_eeprom_size_map: HashMap<u32, Vec<String>> = HashMap::new(); let mut mcu_flash_size_map: HashMap<u32, Vec<String>> = HashMap::new(); let mut mcu_ram_size_map: HashMap<u32, Vec<String>> = HashMap::new(); for sf in family { for mcu in sf { let mcu_dat = mcu::Mcu::load(&db_dir, &mcu.name) .map_err(|e| format!("Could not load MCU data for mcu {}: {}", &mcu.name, e))?; let gpio_version = mcu_dat.get_ip("GPIO").unwrap().get_version().to_string(); mcu_gpio_map .entry(gpio_version) .or_insert(vec![]) .push(mcu.ref_name.clone()); if mcu_family == "STM32L0" { mcu_package_map.insert(mcu.ref_name.clone(), mcu.package_name.clone()); } if let Some(size) = mcu_dat.get_eeprom_size() { mcu_eeprom_size_map .entry(size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } if let Some(flash_size) = mcu.flash_size() { mcu_flash_size_map .entry(flash_size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } if let Some(ram_size) = mcu.ram_size() { mcu_ram_size_map .entry(ram_size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } mcu_map.insert(mcu.ref_name.clone(), (mcu, mcu_dat)); } } match generate { GenerateTarget::Features => generate_features( &mcu_map, &mcu_gpio_map, &mcu_package_map, &mcu_eeprom_size_map, &mcu_flash_size_map, &mcu_ram_size_map, &mcu_family, )?, GenerateTarget::PinMappings => generate_pin_mappings(&mcu_gpio_map, &db_dir)?, GenerateTarget::EepromSizes => generate_eeprom_sizes(&mcu_eeprom_size_map)?, }; Ok(()) } lazy_static! { static ref FEATURE_DEPENDENCIES: HashMap<&'static str, HashMap<&'static str, &'static str>> = { let mut m = HashMap::new(); let mut l0 = HashMap::new(); l0.insert("^STM32L0.1", "stm32l0x1"); l0.insert("^STM32L0.2", "stm32l0x2"); l0.insert("^STM32L0.3", "stm32l0x3"); m.insert("STM32L0", l0); m }; } fn generate_features( mcu_map: &HashMap<String, (&family::Mcu, mcu::Mcu)>, mcu_gpio_map: &HashMap<String, Vec<String>>, mcu_package_map: &HashMap<String, String>, mcu_eeprom_size_map: &HashMap<u32, Vec<String>>, mcu_flash_size_map: &HashMap<u32, Vec<String>>, mcu_ram_size_map: &HashMap<u32, Vec<String>>, mcu_family: &str, ) -> Result<(), String> { let mut io_features = mcu_gpio_map .keys() .map(|gpio| gpio_version_to_feature(gpio)) .collect::<Result<Vec<String>, String>>()?; io_features.sort(); println!("# Features based on the GPIO peripheral version"); println!("# This determines the pin function mapping of the MCU"); for feature in io_features { println!("{} = []", feature); } println!(); let mut eeprom_sizes = mcu_eeprom_size_map.keys().collect::<Vec<_>>(); eeprom_sizes.sort(); println!("# Features based on EEPROM size (in bytes)"); for size in eeprom_sizes { println!("{} = []", eeprom_size_to_feature(*size)); } println!(); let mut flash_sizes = mcu_flash_size_map.keys().collect::<Vec<_>>(); flash_sizes.sort(); println!("# Features based on Flash size (in kbytes)"); for size in flash_sizes { println!("{} = []", flash_size_to_feature(*size)); } println!(); let mut ram_sizes = mcu_ram_size_map.keys().collect::<Vec<_>>(); ram_sizes.sort(); println!("# Features based on RAM size (in kbytes)"); for size in ram_sizes { println!("{} = []", ram_size_to_feature(*size)); } println!(); if !mcu_package_map.is_empty() { println!("# Physical packages"); let mut packages = mcu_package_map .values() .map(|v| v.to_lowercase()) .collect::<Vec<_>>(); packages.sort_by(|a, b| compare_str(a, b)); packages.dedup(); for pkg in packages { println!("{} = []", pkg); } println!(); } let mut mcu_aliases = vec![]; for (gpio, mcu_list) in mcu_gpio_map { let gpio_version_feature = gpio_version_to_feature(gpio).unwrap(); for mcu in mcu_list { let mut dependencies = vec![]; if let Some(family) = FEATURE_DEPENDENCIES.get(mcu_family) { for (pattern, feature) in family { if Regex::new(pattern).unwrap().is_match(&mcu) { dependencies.push(feature.to_string()); break; } } } if let Some(package) = mcu_package_map.get(mcu) { dependencies.push(package.to_lowercase()); } dependencies.push(gpio_version_feature.clone()); let (mcu_info, mcu_dat) = mcu_map.get(mcu).unwrap(); if let Some(size) = mcu_dat.get_eeprom_size() { dependencies.push(eeprom_size_to_feature(size)); } if let Some(flash_size) = mcu_info.flash_size() { dependencies.push(flash_size_to_feature(flash_size)); } if let Some(ram_size) = mcu_info.ram_size() { dependencies.push(ram_size_to_feature(ram_size)); } mcu_aliases.push(format!( "mcu-{} = [{}]", mcu, &dependencies.iter().map(|val| format!("\"{}\"", val)).fold( String::new(), |mut acc, x| { if !acc.is_empty() { acc.push_str(", "); } acc.push_str(&x); acc } ) )); } } mcu_aliases.sort(); println!("# MCU aliases"); println!("#"); println!("# Note: These are just aliases, they should not be used to directly feature gate"); println!( "# functionality in the HAL! However, user code should usually depend on a MCU alias." ); for alias in mcu_aliases { println!("{}", alias); } Ok(()) } fn generate_pin_mappings( mcu_gpio_map: &HashMap<String, Vec<String>>, db_dir: &Path, ) -> Result<(), String> { let mut gpio_versions = mcu_gpio_map.keys().collect::<Vec<_>>(); gpio_versions.sort(); for gpio in gpio_versions { let gpio_version_feature = gpio_version_to_feature(&gpio)?; println!("#[cfg(feature = \"{}\")]", gpio_version_feature); let gpio_data = internal_peripheral::IpGPIO::load(db_dir, &gpio) .map_err(|e| format!("Could not load IP GPIO file: {}", e))?; render_pin_modes(&gpio_data); println!("\n"); } Ok(()) } fn generate_eeprom_sizes(mcu_eeprom_size_map: &HashMap<u32, Vec<String>>) -> Result<(), String> { println!("// EEPROM sizes in bytes, generated with cube-parse"); for size in mcu_eeprom_size_map.keys() { println!("#[cfg(feature = \"{}\")]", eeprom_size_to_feature(*size)); println!("const EEPROM_SIZE_BYTES: u32 = {};", size); } Ok(()) } fn render_pin_modes(ip: &internal_peripheral::IpGPIO) { let mut pin_map: HashMap<String, Vec<String>> = HashMap::new(); for p in &ip.gpio_pin { let name = p.get_name(); if let Some(n) = name { pin_map.insert(n, p.get_af_modes()); } } let mut pin_map = pin_map .into_iter() .map(|(k, mut v)| { #[allow(clippy::redundant_closure)] v.sort_by(|a, b| compare_str(a, b)); (k, v) }) .collect::<Vec<_>>(); pin_map.sort_by(|a, b| compare_str(&a.0, &b.0)); println!("pins! {{"); for (n, af) in pin_map { if af.is_empty() { continue; } else if af.len() == 1 { println!(" {} => {{{}}},", n, af[0]); } else { println!(" {} => {{", n); for a in af { println!(" {},", a); } println!(" }},"); } } println!("}}"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_gpio_version_to_feature() { assert_eq!( gpio_version_to_feature("STM32L152x8_gpio_v1_0").unwrap(), "io-STM32L152x8" ); assert_eq!( gpio_version_to_feature("STM32F333_gpio_v1_0").unwrap(), "io-STM32F333" ); assert!(gpio_version_to_feature("STM32F333_gpio_v1_1").is_err()); assert!(gpio_version_to_feature("STM32F333_qqio_v1_0").is_err()); assert!(gpio_version_to_feature("STM32_STM32F333_gpio_v1_0").is_err()); } }
use std::{collections::HashMap, env, path::Path}; use alphanumeric_sort::compare_str; use clap::{App, Arg}; use lazy_static::lazy_static; use regex::Regex; mod family; mod internal_peripheral; mod mcu; mod utils; #[derive(Debug, PartialEq)] enum GenerateTarget { Features, PinMappings, EepromSizes, } lazy_static! { static ref GPIO_VERSION: Regex = Regex::new("^([^_]*)_gpio_v1_0$").unwrap(); } fn gpio_version_to_feature(version: &str) -> Result<String, String> { if let Some(captures) = GPIO_VERSION.captures(version) { Ok(format!("io-{}", captures.get(1).unwrap().as_str())) } else { Err(format!("Could not parse version {:?}", version)) } } fn eeprom_size_to_feature(size: u32) -> String { format!("eeprom-{}", size) } fn flash_size_to_feature(size: u32) -> String { format!("flash-{}", size) } fn ram_size_to_feature(size: u32) -> String { format!("ram-{}", size) } fn main() -> Result<(), String> { let args = App::new("cube-parse") .version(env!("CARGO_PKG_VERSION")) .about("Extract AF modes on MCU pins from the database files provided with STM32CubeMX") .author(&*env!("CARGO_PKG_AUTHORS").replace(":", ", ")) .arg( Arg::with_name("db_dir") .short("d") .help("Path to the CubeMX MCU database directory") .takes_value(true) .required(true), ) .arg( Arg::with_name("generate") .help("What to generate") .takes_value(true) .possible_values(&["features", "pin_mappings", "eeprom_sizes"]) .required(true), ) .arg( Arg::with_name("mcu_family") .help("The MCU family to extract, e.g. \"STM32L0\"") .takes_value(true) .required(true), ) .get_matches(); let db_dir = Path::new(args.value_of("db_dir").unwrap()); let mcu_family = args.value_of("mcu_family").unwrap(); let generate = match args.value_of("generate").unwrap() { "features" => GenerateTarget::Features, "pin_mappings" => Genera
} if let Some(ram_size) = mcu.ram_size() { mcu_ram_size_map .entry(ram_size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } mcu_map.insert(mcu.ref_name.clone(), (mcu, mcu_dat)); } } match generate { GenerateTarget::Features => generate_features( &mcu_map, &mcu_gpio_map, &mcu_package_map, &mcu_eeprom_size_map, &mcu_flash_size_map, &mcu_ram_size_map, &mcu_family, )?, GenerateTarget::PinMappings => generate_pin_mappings(&mcu_gpio_map, &db_dir)?, GenerateTarget::EepromSizes => generate_eeprom_sizes(&mcu_eeprom_size_map)?, }; Ok(()) } lazy_static! { static ref FEATURE_DEPENDENCIES: HashMap<&'static str, HashMap<&'static str, &'static str>> = { let mut m = HashMap::new(); let mut l0 = HashMap::new(); l0.insert("^STM32L0.1", "stm32l0x1"); l0.insert("^STM32L0.2", "stm32l0x2"); l0.insert("^STM32L0.3", "stm32l0x3"); m.insert("STM32L0", l0); m }; } fn generate_features( mcu_map: &HashMap<String, (&family::Mcu, mcu::Mcu)>, mcu_gpio_map: &HashMap<String, Vec<String>>, mcu_package_map: &HashMap<String, String>, mcu_eeprom_size_map: &HashMap<u32, Vec<String>>, mcu_flash_size_map: &HashMap<u32, Vec<String>>, mcu_ram_size_map: &HashMap<u32, Vec<String>>, mcu_family: &str, ) -> Result<(), String> { let mut io_features = mcu_gpio_map .keys() .map(|gpio| gpio_version_to_feature(gpio)) .collect::<Result<Vec<String>, String>>()?; io_features.sort(); println!("# Features based on the GPIO peripheral version"); println!("# This determines the pin function mapping of the MCU"); for feature in io_features { println!("{} = []", feature); } println!(); let mut eeprom_sizes = mcu_eeprom_size_map.keys().collect::<Vec<_>>(); eeprom_sizes.sort(); println!("# Features based on EEPROM size (in bytes)"); for size in eeprom_sizes { println!("{} = []", eeprom_size_to_feature(*size)); } println!(); let mut flash_sizes = mcu_flash_size_map.keys().collect::<Vec<_>>(); flash_sizes.sort(); println!("# Features based on Flash size (in kbytes)"); for size in flash_sizes { println!("{} = []", flash_size_to_feature(*size)); } println!(); let mut ram_sizes = mcu_ram_size_map.keys().collect::<Vec<_>>(); ram_sizes.sort(); println!("# Features based on RAM size (in kbytes)"); for size in ram_sizes { println!("{} = []", ram_size_to_feature(*size)); } println!(); if !mcu_package_map.is_empty() { println!("# Physical packages"); let mut packages = mcu_package_map .values() .map(|v| v.to_lowercase()) .collect::<Vec<_>>(); packages.sort_by(|a, b| compare_str(a, b)); packages.dedup(); for pkg in packages { println!("{} = []", pkg); } println!(); } let mut mcu_aliases = vec![]; for (gpio, mcu_list) in mcu_gpio_map { let gpio_version_feature = gpio_version_to_feature(gpio).unwrap(); for mcu in mcu_list { let mut dependencies = vec![]; if let Some(family) = FEATURE_DEPENDENCIES.get(mcu_family) { for (pattern, feature) in family { if Regex::new(pattern).unwrap().is_match(&mcu) { dependencies.push(feature.to_string()); break; } } } if let Some(package) = mcu_package_map.get(mcu) { dependencies.push(package.to_lowercase()); } dependencies.push(gpio_version_feature.clone()); let (mcu_info, mcu_dat) = mcu_map.get(mcu).unwrap(); if let Some(size) = mcu_dat.get_eeprom_size() { dependencies.push(eeprom_size_to_feature(size)); } if let Some(flash_size) = mcu_info.flash_size() { dependencies.push(flash_size_to_feature(flash_size)); } if let Some(ram_size) = mcu_info.ram_size() { dependencies.push(ram_size_to_feature(ram_size)); } mcu_aliases.push(format!( "mcu-{} = [{}]", mcu, &dependencies.iter().map(|val| format!("\"{}\"", val)).fold( String::new(), |mut acc, x| { if !acc.is_empty() { acc.push_str(", "); } acc.push_str(&x); acc } ) )); } } mcu_aliases.sort(); println!("# MCU aliases"); println!("#"); println!("# Note: These are just aliases, they should not be used to directly feature gate"); println!( "# functionality in the HAL! However, user code should usually depend on a MCU alias." ); for alias in mcu_aliases { println!("{}", alias); } Ok(()) } fn generate_pin_mappings( mcu_gpio_map: &HashMap<String, Vec<String>>, db_dir: &Path, ) -> Result<(), String> { let mut gpio_versions = mcu_gpio_map.keys().collect::<Vec<_>>(); gpio_versions.sort(); for gpio in gpio_versions { let gpio_version_feature = gpio_version_to_feature(&gpio)?; println!("#[cfg(feature = \"{}\")]", gpio_version_feature); let gpio_data = internal_peripheral::IpGPIO::load(db_dir, &gpio) .map_err(|e| format!("Could not load IP GPIO file: {}", e))?; render_pin_modes(&gpio_data); println!("\n"); } Ok(()) } fn generate_eeprom_sizes(mcu_eeprom_size_map: &HashMap<u32, Vec<String>>) -> Result<(), String> { println!("// EEPROM sizes in bytes, generated with cube-parse"); for size in mcu_eeprom_size_map.keys() { println!("#[cfg(feature = \"{}\")]", eeprom_size_to_feature(*size)); println!("const EEPROM_SIZE_BYTES: u32 = {};", size); } Ok(()) } fn render_pin_modes(ip: &internal_peripheral::IpGPIO) { let mut pin_map: HashMap<String, Vec<String>> = HashMap::new(); for p in &ip.gpio_pin { let name = p.get_name(); if let Some(n) = name { pin_map.insert(n, p.get_af_modes()); } } let mut pin_map = pin_map .into_iter() .map(|(k, mut v)| { #[allow(clippy::redundant_closure)] v.sort_by(|a, b| compare_str(a, b)); (k, v) }) .collect::<Vec<_>>(); pin_map.sort_by(|a, b| compare_str(&a.0, &b.0)); println!("pins! {{"); for (n, af) in pin_map { if af.is_empty() { continue; } else if af.len() == 1 { println!(" {} => {{{}}},", n, af[0]); } else { println!(" {} => {{", n); for a in af { println!(" {},", a); } println!(" }},"); } } println!("}}"); } #[cfg(test)] mod tests { use super::*; #[test] fn test_gpio_version_to_feature() { assert_eq!( gpio_version_to_feature("STM32L152x8_gpio_v1_0").unwrap(), "io-STM32L152x8" ); assert_eq!( gpio_version_to_feature("STM32F333_gpio_v1_0").unwrap(), "io-STM32F333" ); assert!(gpio_version_to_feature("STM32F333_gpio_v1_1").is_err()); assert!(gpio_version_to_feature("STM32F333_qqio_v1_0").is_err()); assert!(gpio_version_to_feature("STM32_STM32F333_gpio_v1_0").is_err()); } }
teTarget::PinMappings, "eeprom_sizes" => GenerateTarget::EepromSizes, _ => unreachable!(), }; let families = family::Families::load(&db_dir) .map_err(|e| format!("Could not load families XML: {}", e))?; let family = (&families) .into_iter() .find(|v| v.name == mcu_family) .ok_or_else(|| format!("Could not find family {}", mcu_family))?; let mut mcu_map: HashMap<String, (&family::Mcu, mcu::Mcu)> = HashMap::new(); let mut mcu_gpio_map: HashMap<String, Vec<String>> = HashMap::new(); let mut mcu_package_map: HashMap<String, String> = HashMap::new(); let mut mcu_eeprom_size_map: HashMap<u32, Vec<String>> = HashMap::new(); let mut mcu_flash_size_map: HashMap<u32, Vec<String>> = HashMap::new(); let mut mcu_ram_size_map: HashMap<u32, Vec<String>> = HashMap::new(); for sf in family { for mcu in sf { let mcu_dat = mcu::Mcu::load(&db_dir, &mcu.name) .map_err(|e| format!("Could not load MCU data for mcu {}: {}", &mcu.name, e))?; let gpio_version = mcu_dat.get_ip("GPIO").unwrap().get_version().to_string(); mcu_gpio_map .entry(gpio_version) .or_insert(vec![]) .push(mcu.ref_name.clone()); if mcu_family == "STM32L0" { mcu_package_map.insert(mcu.ref_name.clone(), mcu.package_name.clone()); } if let Some(size) = mcu_dat.get_eeprom_size() { mcu_eeprom_size_map .entry(size) .or_insert(vec![]) .push(mcu.ref_name.clone()); } if let Some(flash_size) = mcu.flash_size() { mcu_flash_size_map .entry(flash_size) .or_insert(vec![]) .push(mcu.ref_name.clone());
random
[ { "content": "pub fn load_file<'a, P: AsRef<Path>, Q: AsRef<Path>, R: Deserialize<'a>>(\n\n db_dir: P,\n\n file_path: Q,\n\n) -> Result<R, Box<dyn Error>> {\n\n let db_dir = db_dir.as_ref();\n\n let mut fin = BufReader::new(File::open(&db_dir.join(file_path.as_ref()))?);\n\n\n\n Ok(serde_xml_rs::...
Rust
grid/src/lib.rs
Daniel-del-Castillo/ia1
c11d768af415a8d117152b954cb9cf25bce48631
use crossterm::style::Colorize; use std::fmt; mod content; mod path_finding; use content::Content; use rand::{thread_rng, Rng}; pub struct Grid { grid: Vec<Vec<Content>>, goal: Option<(usize, usize)>, car: Option<(usize, usize)>, } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for _ in 0..self.grid[0].len() + 2 { write!(f, "{}", " ".on_dark_blue())?; } write!(f, "\n\r")?; for row in self.grid.iter() { write!(f, "{}", " ".on_dark_blue())?; for cell in row.iter() { write!(f, "{}", cell)? } write!(f, "{}", " \n\r".on_dark_blue())?; } for _ in 0..self.grid[0].len() + 2 { write!(f, "{}", " ".on_dark_blue())?; } write!(f, "\n\r")?; Ok(()) } } impl Grid { pub fn new(m: usize, n: usize) -> Self { assert!(m != 0 && n != 0); Grid { grid: vec![vec![Content::Empty; n]; m], goal: None, car: None, } } pub fn m(&self) -> usize { self.grid.len() } pub fn n(&self) -> usize { self.grid[0].len() } pub fn has_goal(&self) -> bool { match self.goal { None => false, Some(_) => true, } } pub fn has_car(&self) -> bool { match self.car { None => false, Some(_) => true, } } pub fn set_width(&mut self, n: usize) { assert!(n != 0); let width = self.grid[0].len(); if n == width { return; } else if n < width { self.grid.iter_mut().for_each(|row| row.truncate(n)); self.check_car_valididy(); self.check_goal_valididy(); } else { self.grid .iter_mut() .for_each(|row| (0..n - width).for_each(|_| row.push(Content::Empty))); } } pub fn set_height(&mut self, m: usize) { assert!(m != 0); let height = self.grid.len(); if m == height { return; } else if m < height { self.grid.truncate(m); self.check_car_valididy(); self.check_goal_valididy(); } else { let width = self.grid[0].len(); (0..m - height).for_each(|_| self.grid.push(vec![Content::Empty; width])); } } pub fn set_wall(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Car => self.car = None, Content::Goal => self.goal = None, _ => {} } self.grid[y][x] = Content::Wall; } pub fn set_goal(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Car => self.car = None, Content::Goal => return, _ => {} } self.grid[y][x] = Content::Goal; if let Some(old_goal_pos) = &mut self.goal { self.grid[old_goal_pos.1][old_goal_pos.0] = Content::Empty; } self.goal = Some((x, y)); } pub fn set_car(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.goal = None, Content::Car => return, _ => {} } self.grid[y][x] = Content::Car; if let Some(old_car_pos) = &mut self.car { self.grid[old_car_pos.1][old_car_pos.0] = Content::Empty; } self.car = Some((x, y)); } pub fn set_empty(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.goal = None, Content::Car => self.car = None, _ => {} } self.grid[y][x] = Content::Empty; } pub fn clear(&mut self) { self.grid = vec![vec![Content::Empty; self.grid[0].len()]; self.grid.len()]; } pub fn fill_random(&mut self, wall_percentage: usize) { assert!(wall_percentage <= 100); self.car = None; self.goal = None; self.fill_random_walls(wall_percentage); let car_pos = self.get_random_pos(); self.set_car(car_pos.0, car_pos.1); if self.m() * self.n() != 1 { let goal_pos = loop { let pos = self.get_random_pos(); if pos != car_pos { break pos; } }; self.set_goal(goal_pos.0, goal_pos.1); } } fn fill_random_walls(&mut self, wall_percentage: usize) { let mut rng = thread_rng(); for content in self.grid.iter_mut().map(|i| i.iter_mut()).flatten() { if rng.gen_range(1, 101) <= wall_percentage { *content = Content::Wall; } else { *content = Content::Empty; } } } fn get_random_pos(&mut self) -> (usize, usize) { let n_cells = self.m() * self.n(); let pos = thread_rng().gen_range(0, n_cells); let y = pos / self.n(); let x = pos % self.n(); (x, y) } fn check_car_valididy(&mut self) { if let Some(pos) = self.car { if pos.0 >= self.n() || pos.1 >= self.m() { self.car = None; } } } fn check_goal_valididy(&mut self) { if let Some(pos) = self.goal { if pos.0 >= self.n() || pos.1 >= self.m() { self.goal = None; } } } }
use crossterm::style::Colorize; use std::fmt; mod content; mod path_finding; use content::Content; use rand::{thread_rng, Rng}; pub struct Grid { grid: Vec<Vec<Content>>, goal: Option<(usize, usize)>, car: Option<(usize, usize)>, } impl fmt::Display for Grid { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for _ in 0..self.grid[0].len() + 2 { write!(f, "{}", " ".on_dark_blue())?; } write!(f, "\n\r")?; for row in self.grid.iter() { write!(f, "{}", " ".on_dark_blue())?; for cell in row.iter() { write!(f, "{}", cell)? } write!(f, "{}", " \n\r".on_dark_blue())?; } for _ in 0..self.grid[0].len() + 2 { write!(f, "{}", " ".on_dark_blue())?; } write!(f, "\n\r")?; Ok(()) } } impl Grid { pub fn new(m: usize, n: usize) -> Self { assert!(m != 0 && n != 0); Grid { grid: vec![vec![Content::Empty; n]; m], goal: None, car: None, } } pub fn m(&self) -> usize { self.grid.len() } pub fn n(&self) -> usize { self.grid[0].len() } pub fn has_goal(&self) -> bool { match self.goal { None => false, Some(_) => true, } } pub fn has_car(&self) -> bool { match self.car { None => false, Some(_) => true, } } pub fn set_width(&mut self, n: usize) { assert!(n != 0); let width = self.grid[0].len(); if n == width { return; } else if n < width { self.grid.iter_mut().for_each(|row| row.truncate(n)); self.check_car_valididy(); self.check_goal_valididy(); } else { self.grid .iter_mut() .for_each(|row| (0..n - width).for_each(|_| row.push(Content::Empty))); } } pub fn set_height(&mut self, m: usize) { assert!(m != 0); let height = self.grid.len(); if m == height { return; } else if m < height { self.grid.truncate(m); self.check_car_valididy(); self.check_goal_valididy(); } else { let width = self.grid[0].len(); (0..m - height).for_each(|_| self.grid.push(vec![Content::Empty; width])); } } pub fn set_wall(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Car => self.car = None, Content::Goal => self.goal = None, _ => {} } self.grid[y][x] = Content::Wall; } pub fn set_goal(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Car => self.car = None, Content::Goal => return, _ => {} } self.grid[y][x] = Content::Goal; if let Some(old_goal_pos) = &mut self.goal { se
y][x] = Content::Car; if let Some(old_car_pos) = &mut self.car { self.grid[old_car_pos.1][old_car_pos.0] = Content::Empty; } self.car = Some((x, y)); } pub fn set_empty(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.goal = None, Content::Car => self.car = None, _ => {} } self.grid[y][x] = Content::Empty; } pub fn clear(&mut self) { self.grid = vec![vec![Content::Empty; self.grid[0].len()]; self.grid.len()]; } pub fn fill_random(&mut self, wall_percentage: usize) { assert!(wall_percentage <= 100); self.car = None; self.goal = None; self.fill_random_walls(wall_percentage); let car_pos = self.get_random_pos(); self.set_car(car_pos.0, car_pos.1); if self.m() * self.n() != 1 { let goal_pos = loop { let pos = self.get_random_pos(); if pos != car_pos { break pos; } }; self.set_goal(goal_pos.0, goal_pos.1); } } fn fill_random_walls(&mut self, wall_percentage: usize) { let mut rng = thread_rng(); for content in self.grid.iter_mut().map(|i| i.iter_mut()).flatten() { if rng.gen_range(1, 101) <= wall_percentage { *content = Content::Wall; } else { *content = Content::Empty; } } } fn get_random_pos(&mut self) -> (usize, usize) { let n_cells = self.m() * self.n(); let pos = thread_rng().gen_range(0, n_cells); let y = pos / self.n(); let x = pos % self.n(); (x, y) } fn check_car_valididy(&mut self) { if let Some(pos) = self.car { if pos.0 >= self.n() || pos.1 >= self.m() { self.car = None; } } } fn check_goal_valididy(&mut self) { if let Some(pos) = self.goal { if pos.0 >= self.n() || pos.1 >= self.m() { self.goal = None; } } } }
lf.grid[old_goal_pos.1][old_goal_pos.0] = Content::Empty; } self.goal = Some((x, y)); } pub fn set_car(&mut self, x: usize, y: usize) { match &mut self.grid[y][x] { Content::Goal => self.goal = None, Content::Car => return, _ => {} } self.grid[
random
[ { "content": "fn get_grid_size(matches: &ArgMatches) -> (usize, usize) {\n\n let m = matches.value_of(\"m\").unwrap_or(\"10\");\n\n let n = matches.value_of(\"n\").unwrap_or(\"10\");\n\n let m = match m.parse() {\n\n Err(_) | Ok(0) => {\n\n eprintln!(\"The -m parameter must be a posit...
Rust
src/parser/rfc3501/body.rs
filtsin/rimap
21954bdd1a848fe4a17e4180552ab4e58027a100
use super::{core::*, grammar::envelope}; use crate::parser::types::{ Body, BodyEnc, BodyFields, BodyTypeBasic, BodyTypeMsg, BodyTypeText, MediaBasic, MediaType, }; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, value}, multi::separated_list1, sequence::{delimited, preceded, separated_pair, terminated, tuple}, IResult, }; pub(crate) fn body(i: &[u8]) -> IResult<&[u8], Body> { todo!() } pub(crate) fn body_type_1part(i: &[u8]) -> IResult<&[u8], Body<'_>> { todo!() } pub(crate) fn body_type_basic(i: &[u8]) -> IResult<&[u8], BodyTypeBasic<'_>> { map( separated_pair(media_basic, tag(" "), body_fields), |(media, fields)| BodyTypeBasic { media, fields }, )(i) } pub(crate) fn media_basic(i: &[u8]) -> IResult<&[u8], MediaBasic<'_>> { map( separated_pair( alt(( delimited( tag("\""), alt(( value(MediaType::Application, tag_no_case("APPLICATION")), value(MediaType::Audio, tag_no_case("AUDIO")), value(MediaType::Image, tag_no_case("IMAGE")), value(MediaType::Message, tag_no_case("MESSAGE")), value(MediaType::Video, tag_no_case("VIDEO")), )), tag("\""), ), map(string, MediaType::Custom), )), tag(" "), string, ), |(media_type, subtype)| MediaBasic { media_type, subtype, }, )(i) } pub(crate) fn body_fields(i: &[u8]) -> IResult<&[u8], BodyFields<'_>> { map( tuple(( body_fld_param, tag(" "), nstring, tag(" "), nstring, tag(" "), body_fld_enc, tag(" "), number, )), |(param, _, id, _, desc, _, enc, _, octets)| BodyFields { param, id, desc, enc, octets, }, )(i) } pub(crate) fn body_fld_param(i: &[u8]) -> IResult<&[u8], Option<Vec<(&str, &str)>>> { alt(( map( delimited( tag("("), separated_list1(tag(" "), separated_pair(string, tag(" "), string)), tag(")"), ), Some, ), nil, ))(i) } pub(crate) fn body_fld_enc(i: &[u8]) -> IResult<&[u8], BodyEnc<'_>> { alt(( delimited( tag("\""), alt(( value(BodyEnc::N7bit, tag_no_case("7BIT")), value(BodyEnc::N8bit, tag_no_case("8BIT")), value(BodyEnc::Binary, tag_no_case("BINARY")), value(BodyEnc::Base64, tag_no_case("BASE64")), value(BodyEnc::QuotedPrintable, tag_no_case("QUOTED-PRINTABLE")), )), tag("\""), ), map(string, BodyEnc::Custom), ))(i) } pub(crate) fn body_type_msg(i: &[u8]) -> IResult<&[u8], BodyTypeMsg<'_>> { map( tuple(( tag_no_case("\"MESSAGE\" \"RFC822\" "), body_fields, tag(" "), envelope, tag(" "), body, tag(" "), number, )), |(_, fields, _, envelope, _, body, _, lines)| BodyTypeMsg { fields, envelope, body: Box::new(body), lines, }, )(i) } pub(crate) fn body_type_text(i: &[u8]) -> IResult<&[u8], BodyTypeText<'_>> { map( tuple(( tag_no_case("\"TEXT\" "), string, tag(" "), body_fields, tag(" "), number, )), |(_, subtype, _, fields, _, lines)| BodyTypeText { subtype, fields, lines, }, )(i) } pub(crate) fn body_ext_1part(i: &[u8]) -> IResult<&[u8], ()> { todo!() }
use super::{core::*, grammar::envelope}; use crate::parser::types::{ Body, BodyEnc, BodyFields, BodyTypeBasic, BodyTypeMsg, BodyTypeText, MediaBasic, MediaType, }; use nom::{ branch::alt, bytes::streaming::{tag, tag_no_case}, combinator::{map, value}, multi::separated_list1, sequence::{delimited, preceded, separated_pair, terminated, tuple}, IResult, }; pub(crate) fn body(i: &[u8]) -> IResult<&[u8], Body> { todo!() } pub(crate) fn body_type_1part(i: &[u8]) -> IResult<&[u8], Body<'_>> { todo!() } pub(crate) fn body_type_basic(i: &[u8]) -> IResult<&[u8], BodyTypeBasic<'_>> { map( separated_pair(media_basic, tag(" "), body_fields), |(media, fields)| BodyTypeBasic { media, fields }, )(i) } pub(crate) fn media_basic(i: &[u8]) -> IResult<&[u8], MediaBasic<'_>> { map( separated_pair( alt(( delimited( tag("\""), alt(( value(MediaType::Application, tag_no_case("APPLICATION")), value(MediaType::Audio, tag_no_case("AUDIO")), value(MediaType::Image, tag_no_case("IMAGE")), value(MediaType::Message, tag_no_case("MESSAGE")), value(MediaType::Video, tag_no_case("VIDEO")), )), tag("\""), ), map(string, MediaType::Custom), )), tag(" "), string, ), |(media_type, subtype)| MediaBasic { media_type, subtype, }, )(i) } pub(crate) fn body_fields(i: &[u8]) ->
body: Box::new(body), lines, }, )(i) } pub(crate) fn body_type_text(i: &[u8]) -> IResult<&[u8], BodyTypeText<'_>> { map( tuple(( tag_no_case("\"TEXT\" "), string, tag(" "), body_fields, tag(" "), number, )), |(_, subtype, _, fields, _, lines)| BodyTypeText { subtype, fields, lines, }, )(i) } pub(crate) fn body_ext_1part(i: &[u8]) -> IResult<&[u8], ()> { todo!() }
IResult<&[u8], BodyFields<'_>> { map( tuple(( body_fld_param, tag(" "), nstring, tag(" "), nstring, tag(" "), body_fld_enc, tag(" "), number, )), |(param, _, id, _, desc, _, enc, _, octets)| BodyFields { param, id, desc, enc, octets, }, )(i) } pub(crate) fn body_fld_param(i: &[u8]) -> IResult<&[u8], Option<Vec<(&str, &str)>>> { alt(( map( delimited( tag("("), separated_list1(tag(" "), separated_pair(string, tag(" "), string)), tag(")"), ), Some, ), nil, ))(i) } pub(crate) fn body_fld_enc(i: &[u8]) -> IResult<&[u8], BodyEnc<'_>> { alt(( delimited( tag("\""), alt(( value(BodyEnc::N7bit, tag_no_case("7BIT")), value(BodyEnc::N8bit, tag_no_case("8BIT")), value(BodyEnc::Binary, tag_no_case("BINARY")), value(BodyEnc::Base64, tag_no_case("BASE64")), value(BodyEnc::QuotedPrintable, tag_no_case("QUOTED-PRINTABLE")), )), tag("\""), ), map(string, BodyEnc::Custom), ))(i) } pub(crate) fn body_type_msg(i: &[u8]) -> IResult<&[u8], BodyTypeMsg<'_>> { map( tuple(( tag_no_case("\"MESSAGE\" \"RFC822\" "), body_fields, tag(" "), envelope, tag(" "), body, tag(" "), number, )), |(_, fields, _, envelope, _, body, _, lines)| BodyTypeMsg { fields, envelope,
random
[ { "content": "fn vec_to_string(v: &Vec<u8>) -> String {\n\n std::string::String::from_utf8_lossy(&v[..]).into_owned()\n\n}\n", "file_path": "src/error.rs", "rank": 0, "score": 90814.00460926183 }, { "content": "pub fn create_custom_error(msg: String) -> Error {\n\n Error::Custom(msg)\n...
Rust
src/compaction/value.rs
timothee-haudebourg/json-ld
0b44aa736b681893e75ce282c67511480c992901
use super::{compact_iri, JsonSrc, Options}; use crate::{ context::{self, Inversible, Loader, Local}, syntax::{Container, ContainerType, Keyword, Term, Type}, util::{AsAnyJson, AsJson, JsonFrom}, ContextMut, Error, Id, Loc, Reference, Value, }; pub async fn compact_indexed_value_with< J: JsonSrc, K: JsonFrom<J>, T: Sync + Send + Id, C: ContextMut<T>, L: Loader, M, >( value: &Value<J, T>, index: Option<&str>, active_context: Inversible<T, &C>, active_property: Option<&str>, loader: &mut L, options: Options, meta: M, ) -> Result<K, Error> where C: Sync + Send, C::LocalContext: Send + Sync + From<L::Output>, L: Sync + Send, M: Send + Sync + Clone + Fn(Option<&J::MetaData>) -> K::MetaData, { let mut active_context = active_context.into_borrowed(); if let Some(active_property) = active_property { if let Some(active_property_definition) = active_context.get(active_property) { if let Some(local_context) = &active_property_definition.context { active_context = Inversible::new( local_context .process_with( *active_context.as_ref(), loader, active_property_definition.base_url(), context::ProcessingOptions::from(options).with_override(), ) .await .map_err(Loc::unwrap)? .into_inner(), ) .into_owned() } } } let mut result = K::Object::default(); let active_property_definition = match active_property { Some(active_property) => active_context.get(active_property), None => None, }; let language = match active_property_definition { Some(def) => match def.language.as_ref() { Some(lang) => lang.as_ref().map(|l| l.as_ref()).option(), None => active_context.default_language(), }, None => active_context.default_language(), }; let direction = match active_property_definition { Some(def) => match def.direction { Some(dir) => dir.option(), None => active_context.default_base_direction(), }, None => active_context.default_base_direction(), }; let type_mapping: Option<Type<&T>> = match active_property_definition { Some(def) => def.typ.as_ref().map(|t| t.into()), None => None, }; let container_mapping = match active_property_definition { Some(def) => def.container, None => Container::None, }; let remove_index = (index.is_some() && container_mapping.contains(ContainerType::Index)) || index.is_none(); match value { Value::Literal(lit, ty) => { use crate::object::value::Literal; if ty.as_ref().map(Type::Ref) == type_mapping && remove_index { match lit { Literal::Null => return Ok(K::null(meta(None))), Literal::Boolean(b) => return Ok(b.as_json_with(meta(None))), Literal::Number(n) => return Ok(K::number(n.clone().into(), meta(None))), Literal::String(s) => { if ty.is_some() || (language.is_none() && direction.is_none()) { return Ok(s.as_json_with(meta(None))); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), s.as_json_with(meta(None)), ); } } } } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; match lit { Literal::Null => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::null(meta(None)), ); } Literal::Boolean(b) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), b.as_json_with(meta(None)), ); } Literal::Number(n) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::number(n.clone().into(), meta(None)), ); } Literal::String(s) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), s.as_json_with(meta(None)), ); } } if let Some(ty) = ty { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Type), true, false, options, )?; let compact_ty = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Ref(Reference::Id(ty.clone())), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), match compact_ty { Some(s) => K::string(s.as_str().into(), meta(None)), None => K::null(meta(None)), }, ); } } } Value::LangString(ls) => { let ls_language = ls.language(); let ls_direction = ls.direction(); if remove_index && (ls_language.is_none() || language == ls_language) && (ls_direction.is_none() || direction == ls_direction) { return Ok(ls.as_str().as_json_with(meta(None))); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::string(ls.as_str().into(), meta(None)), ); if let Some(language) = ls.language() { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Language), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), language.as_json_with(meta(None)), ); } if let Some(direction) = ls.direction() { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Direction), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), direction.as_json_with(meta(None)), ); } } } Value::Json(value) => { if type_mapping == Some(Type::Json) && remove_index { return Ok(value.as_json_with(meta)); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), value.as_json_with(meta.clone()), ); let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Type), true, false, options, )?; let compact_ty = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Json), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), match compact_ty { Some(s) => K::string(s.as_str().into(), meta(None)), None => K::null(meta(None)), }, ); } } } if !remove_index { if let Some(index) = index { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Index), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), index.as_json_with(meta(None)), ); } } Ok(K::object(result, meta(None))) }
use super::{compact_iri, JsonSrc, Options}; use crate::{ context::{self, Inversible, Loader, Local}, syntax::{Container, ContainerType, Keyword, Term, Type}, util::{AsAnyJson, AsJson, JsonFrom}, ContextMut, Error, Id, Loc, Reference, Value, }; pub async fn compact_indexed_value_with< J: JsonSrc, K: JsonFrom<J>, T: Sync + Send + Id, C: ContextMut<T>, L: Loader, M, >( value: &Value<J, T>, index: Option<&str>, active_context: Inversible<T, &C>, active_property: Option<&str>, loader: &mut L, options: Options, meta: M, ) -> Result<K, Error> where C: Sync + Send, C::LocalContext: Send + Sync + From<L::Output>, L: Sync + Send, M: Send + Sync + Clone + Fn(Option<&J::MetaData>) -> K::MetaData, { let mut active_context = active_context.into_borrowed(); if let Some(active_property) = active_property { if let Some(active_property_definition) = active_context.get(active_property) { if let Some(local_context) = &active_property_definition.context { active_context = Inversible::new( local_context .process_with( *active_context.as_ref(), loader, active_property_definition.base_url(), context::ProcessingOptions::from(options).with_override(), ) .await .map_err(Loc::unwrap)? .into_inner(), ) .into_owned() } } } let mut result = K::Object::default(); let active_property_definition = match active_property { Some(active_property) => active_context.get(active_property), None => None, }; let language = match active_property_definition { Some(def) =>
, None => active_context.default_language(), }; let direction = match active_property_definition { Some(def) => match def.direction { Some(dir) => dir.option(), None => active_context.default_base_direction(), }, None => active_context.default_base_direction(), }; let type_mapping: Option<Type<&T>> = match active_property_definition { Some(def) => def.typ.as_ref().map(|t| t.into()), None => None, }; let container_mapping = match active_property_definition { Some(def) => def.container, None => Container::None, }; let remove_index = (index.is_some() && container_mapping.contains(ContainerType::Index)) || index.is_none(); match value { Value::Literal(lit, ty) => { use crate::object::value::Literal; if ty.as_ref().map(Type::Ref) == type_mapping && remove_index { match lit { Literal::Null => return Ok(K::null(meta(None))), Literal::Boolean(b) => return Ok(b.as_json_with(meta(None))), Literal::Number(n) => return Ok(K::number(n.clone().into(), meta(None))), Literal::String(s) => { if ty.is_some() || (language.is_none() && direction.is_none()) { return Ok(s.as_json_with(meta(None))); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), s.as_json_with(meta(None)), ); } } } } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; match lit { Literal::Null => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::null(meta(None)), ); } Literal::Boolean(b) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), b.as_json_with(meta(None)), ); } Literal::Number(n) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::number(n.clone().into(), meta(None)), ); } Literal::String(s) => { result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), s.as_json_with(meta(None)), ); } } if let Some(ty) = ty { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Type), true, false, options, )?; let compact_ty = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Ref(Reference::Id(ty.clone())), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), match compact_ty { Some(s) => K::string(s.as_str().into(), meta(None)), None => K::null(meta(None)), }, ); } } } Value::LangString(ls) => { let ls_language = ls.language(); let ls_direction = ls.direction(); if remove_index && (ls_language.is_none() || language == ls_language) && (ls_direction.is_none() || direction == ls_direction) { return Ok(ls.as_str().as_json_with(meta(None))); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), K::string(ls.as_str().into(), meta(None)), ); if let Some(language) = ls.language() { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Language), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), language.as_json_with(meta(None)), ); } if let Some(direction) = ls.direction() { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Direction), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), direction.as_json_with(meta(None)), ); } } } Value::Json(value) => { if type_mapping == Some(Type::Json) && remove_index { return Ok(value.as_json_with(meta)); } else { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Value), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), value.as_json_with(meta.clone()), ); let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Type), true, false, options, )?; let compact_ty = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Json), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), match compact_ty { Some(s) => K::string(s.as_str().into(), meta(None)), None => K::null(meta(None)), }, ); } } } if !remove_index { if let Some(index) = index { let compact_key = compact_iri::<J, _, _>( active_context.as_ref(), &Term::Keyword(Keyword::Index), true, false, options, )?; result.insert( K::new_key(compact_key.as_ref().unwrap().as_str(), meta(None)), index.as_json_with(meta(None)), ); } } Ok(K::object(result, meta(None))) }
match def.language.as_ref() { Some(lang) => lang.as_ref().map(|l| l.as_ref()).option(), None => active_context.default_language(), }
if_condition
[ { "content": "/// Get the `@value` field of a value object.\n\nfn value_value<J: JsonClone, K: JsonFrom<J>, T: Id, M>(value: &Value<J, T>, meta: M) -> K\n\nwhere\n\n\tM: Clone + Fn(Option<&J::MetaData>) -> K::MetaData,\n\n{\n\n\tuse crate::object::value::Literal;\n\n\tmatch value {\n\n\t\tValue::Literal(lit, _t...
Rust
whisper/src/aggregation.rs
GiantPlantsSociety/graphite-rs
d2657ae3ddf110023417ec255f5192ac8fa83bfc
use serde::*; use std::cmp; use std::convert::Into; use std::fmt; use std::str::FromStr; #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64(a: &f64, b: &f64) -> cmp::Ordering { a.partial_cmp(b).unwrap_or(::std::cmp::Ordering::Equal) } #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64_abs(a: &f64, b: &f64) -> cmp::Ordering { cmp_f64(&a.abs(), &b.abs()) } #[derive(Clone, Copy, Debug, PartialEq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AggregationMethod { Average, Sum, Last, Max, Min, AvgZero, AbsMax, AbsMin, } impl AggregationMethod { pub fn from_type(aggregation_type: u32) -> Option<Self> { match aggregation_type { 1 => Some(AggregationMethod::Average), 2 => Some(AggregationMethod::Sum), 3 => Some(AggregationMethod::Last), 4 => Some(AggregationMethod::Max), 5 => Some(AggregationMethod::Min), 6 => Some(AggregationMethod::AvgZero), 7 => Some(AggregationMethod::AbsMax), 8 => Some(AggregationMethod::AbsMin), _ => None, } } pub fn to_type(self) -> u32 { match self { AggregationMethod::Average => 1, AggregationMethod::Sum => 2, AggregationMethod::Last => 3, AggregationMethod::Max => 4, AggregationMethod::Min => 5, AggregationMethod::AvgZero => 6, AggregationMethod::AbsMax => 7, AggregationMethod::AbsMin => 8, } } pub fn aggregate(self, values: &[Option<f64>]) -> Result<f64, &'static str> { match self { AggregationMethod::Average => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); let count = values.iter().filter_map(|v| *v).count(); Ok(sum / count as f64) } AggregationMethod::Sum => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); Ok(sum) } AggregationMethod::Last => { if let Some(Some(v)) = values.iter().rev().find(|v| v.is_some()) { Ok(*v) } else { Err("Empty list of values") } } AggregationMethod::Max => values .iter() .filter_map(|v| *v) .max_by(cmp_f64) .ok_or("Empty list of values"), AggregationMethod::Min => values .iter() .filter_map(|v| *v) .min_by(cmp_f64) .ok_or("Empty list of values"), AggregationMethod::AvgZero => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); let len = values.len(); Ok(sum / len as f64) } AggregationMethod::AbsMax => values .iter() .filter_map(|v| *v) .max_by(cmp_f64_abs) .ok_or("Empty list of values"), AggregationMethod::AbsMin => values .iter() .filter_map(|v| *v) .min_by(cmp_f64_abs) .ok_or("Empty list of values"), } } } impl ::std::default::Default for AggregationMethod { fn default() -> Self { AggregationMethod::Average } } impl FromStr for AggregationMethod { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "average" => Ok(AggregationMethod::Average), "sum" => Ok(AggregationMethod::Sum), "last" => Ok(AggregationMethod::Last), "max" => Ok(AggregationMethod::Max), "min" => Ok(AggregationMethod::Min), "avg_zero" => Ok(AggregationMethod::AvgZero), "absmax" => Ok(AggregationMethod::AbsMax), "absmin" => Ok(AggregationMethod::AbsMin), _ => Err(format!("Unsupported aggregation method '{}'.", s)), } } } impl Into<&'static str> for AggregationMethod { fn into(self) -> &'static str { match self { AggregationMethod::Average => "average", AggregationMethod::Sum => "sum", AggregationMethod::Last => "last", AggregationMethod::Max => "max", AggregationMethod::Min => "min", AggregationMethod::AvgZero => "avg_zero", AggregationMethod::AbsMax => "absmax", AggregationMethod::AbsMin => "absmin", } } } impl fmt::Display for AggregationMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s: &str = (*self).into(); write!(f, "{}", s) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_display() { assert_eq!(AggregationMethod::Average.to_string(), "average"); assert_eq!(AggregationMethod::Sum.to_string(), "sum"); assert_eq!(AggregationMethod::Last.to_string(), "last"); assert_eq!(AggregationMethod::Max.to_string(), "max"); assert_eq!(AggregationMethod::Min.to_string(), "min"); assert_eq!(AggregationMethod::AvgZero.to_string(), "avg_zero"); assert_eq!(AggregationMethod::AbsMax.to_string(), "absmax"); assert_eq!(AggregationMethod::AbsMin.to_string(), "absmin"); assert_eq!(AggregationMethod::default().to_string(), "average"); } #[test] fn test_convert() { assert_eq!( AggregationMethod::from_str(&AggregationMethod::Average.to_string()), Ok(AggregationMethod::Average) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Sum.to_string()), Ok(AggregationMethod::Sum) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Last.to_string()), Ok(AggregationMethod::Last) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Max.to_string()), Ok(AggregationMethod::Max) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Min.to_string()), Ok(AggregationMethod::Min) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AvgZero.to_string()), Ok(AggregationMethod::AvgZero) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AbsMax.to_string()), Ok(AggregationMethod::AbsMax) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AbsMin.to_string()), Ok(AggregationMethod::AbsMin) ); assert!(AggregationMethod::from_str("test").is_err()); } #[test] fn test_aggregate() { assert_eq!( AggregationMethod::Average.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(2.5) ); assert_eq!( AggregationMethod::Min.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(1.0) ); assert_eq!( AggregationMethod::Max.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(4.0) ); assert_eq!( AggregationMethod::Last.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(4.0) ); assert_eq!( AggregationMethod::Last.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, Some(4.0), None ]), Ok(4.0) ); assert_eq!( AggregationMethod::Sum.aggregate(&[ Some(10.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(19.0) ); assert_eq!( AggregationMethod::AvgZero.aggregate(&[ Some(1.0), Some(2.0), Some(3.0), Some(4.0), None, None, None, None ]), Ok(1.25) ); assert_eq!( AggregationMethod::AbsMax.aggregate(&[Some(-3.0), Some(-2.0), Some(1.0), Some(2.0)]), Ok(-3.0) ); assert_eq!( AggregationMethod::AbsMax.aggregate(&[Some(-2.0), Some(-1.0), Some(2.0), Some(3.0)]), Ok(3.0) ); assert_eq!( AggregationMethod::AbsMin.aggregate(&[Some(-3.0), Some(-2.0), Some(1.0), Some(2.0)]), Ok(1.0) ); assert_eq!( AggregationMethod::AbsMin.aggregate(&[Some(-2.0), Some(-1.0), Some(2.0), Some(3.0)]), Ok(-1.0) ); assert!(AggregationMethod::Last.aggregate(&[]).is_err()); } #[test] fn test_from_to_type() { for i in 1..9 { let method = AggregationMethod::from_type(i).unwrap(); assert_eq!(AggregationMethod::to_type(method), i); } assert_eq!(AggregationMethod::from_type(9), None); } }
use serde::*; use std::cmp; use std::convert::Into; use std::fmt; use std::str::FromStr; #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64(a: &f64, b: &f64) -> cmp::Ordering { a.partial_cmp(b).unwrap_or(::std::cmp::Ordering::Equal) } #[allow(clippy::trivially_copy_pass_by_ref)] fn cmp_f64_abs(a: &f64, b: &f64) -> cmp::Ordering { cmp_f64(&a.abs(), &b.abs()) } #[derive(Clone, Copy, Debug, PartialEq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AggregationMethod { Average, Sum,
} } pub fn aggregate(self, values: &[Option<f64>]) -> Result<f64, &'static str> { match self { AggregationMethod::Average => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); let count = values.iter().filter_map(|v| *v).count(); Ok(sum / count as f64) } AggregationMethod::Sum => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); Ok(sum) } AggregationMethod::Last => { if let Some(Some(v)) = values.iter().rev().find(|v| v.is_some()) { Ok(*v) } else { Err("Empty list of values") } } AggregationMethod::Max => values .iter() .filter_map(|v| *v) .max_by(cmp_f64) .ok_or("Empty list of values"), AggregationMethod::Min => values .iter() .filter_map(|v| *v) .min_by(cmp_f64) .ok_or("Empty list of values"), AggregationMethod::AvgZero => { let sum: f64 = values.iter().filter_map(|v| *v).sum(); let len = values.len(); Ok(sum / len as f64) } AggregationMethod::AbsMax => values .iter() .filter_map(|v| *v) .max_by(cmp_f64_abs) .ok_or("Empty list of values"), AggregationMethod::AbsMin => values .iter() .filter_map(|v| *v) .min_by(cmp_f64_abs) .ok_or("Empty list of values"), } } } impl ::std::default::Default for AggregationMethod { fn default() -> Self { AggregationMethod::Average } } impl FromStr for AggregationMethod { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "average" => Ok(AggregationMethod::Average), "sum" => Ok(AggregationMethod::Sum), "last" => Ok(AggregationMethod::Last), "max" => Ok(AggregationMethod::Max), "min" => Ok(AggregationMethod::Min), "avg_zero" => Ok(AggregationMethod::AvgZero), "absmax" => Ok(AggregationMethod::AbsMax), "absmin" => Ok(AggregationMethod::AbsMin), _ => Err(format!("Unsupported aggregation method '{}'.", s)), } } } impl Into<&'static str> for AggregationMethod { fn into(self) -> &'static str { match self { AggregationMethod::Average => "average", AggregationMethod::Sum => "sum", AggregationMethod::Last => "last", AggregationMethod::Max => "max", AggregationMethod::Min => "min", AggregationMethod::AvgZero => "avg_zero", AggregationMethod::AbsMax => "absmax", AggregationMethod::AbsMin => "absmin", } } } impl fmt::Display for AggregationMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let s: &str = (*self).into(); write!(f, "{}", s) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_display() { assert_eq!(AggregationMethod::Average.to_string(), "average"); assert_eq!(AggregationMethod::Sum.to_string(), "sum"); assert_eq!(AggregationMethod::Last.to_string(), "last"); assert_eq!(AggregationMethod::Max.to_string(), "max"); assert_eq!(AggregationMethod::Min.to_string(), "min"); assert_eq!(AggregationMethod::AvgZero.to_string(), "avg_zero"); assert_eq!(AggregationMethod::AbsMax.to_string(), "absmax"); assert_eq!(AggregationMethod::AbsMin.to_string(), "absmin"); assert_eq!(AggregationMethod::default().to_string(), "average"); } #[test] fn test_convert() { assert_eq!( AggregationMethod::from_str(&AggregationMethod::Average.to_string()), Ok(AggregationMethod::Average) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Sum.to_string()), Ok(AggregationMethod::Sum) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Last.to_string()), Ok(AggregationMethod::Last) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Max.to_string()), Ok(AggregationMethod::Max) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::Min.to_string()), Ok(AggregationMethod::Min) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AvgZero.to_string()), Ok(AggregationMethod::AvgZero) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AbsMax.to_string()), Ok(AggregationMethod::AbsMax) ); assert_eq!( AggregationMethod::from_str(&AggregationMethod::AbsMin.to_string()), Ok(AggregationMethod::AbsMin) ); assert!(AggregationMethod::from_str("test").is_err()); } #[test] fn test_aggregate() { assert_eq!( AggregationMethod::Average.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(2.5) ); assert_eq!( AggregationMethod::Min.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(1.0) ); assert_eq!( AggregationMethod::Max.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(4.0) ); assert_eq!( AggregationMethod::Last.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(4.0) ); assert_eq!( AggregationMethod::Last.aggregate(&[ Some(1.0), None, Some(2.0), None, Some(3.0), None, Some(4.0), None ]), Ok(4.0) ); assert_eq!( AggregationMethod::Sum.aggregate(&[ Some(10.0), None, Some(2.0), None, Some(3.0), None, None, Some(4.0) ]), Ok(19.0) ); assert_eq!( AggregationMethod::AvgZero.aggregate(&[ Some(1.0), Some(2.0), Some(3.0), Some(4.0), None, None, None, None ]), Ok(1.25) ); assert_eq!( AggregationMethod::AbsMax.aggregate(&[Some(-3.0), Some(-2.0), Some(1.0), Some(2.0)]), Ok(-3.0) ); assert_eq!( AggregationMethod::AbsMax.aggregate(&[Some(-2.0), Some(-1.0), Some(2.0), Some(3.0)]), Ok(3.0) ); assert_eq!( AggregationMethod::AbsMin.aggregate(&[Some(-3.0), Some(-2.0), Some(1.0), Some(2.0)]), Ok(1.0) ); assert_eq!( AggregationMethod::AbsMin.aggregate(&[Some(-2.0), Some(-1.0), Some(2.0), Some(3.0)]), Ok(-1.0) ); assert!(AggregationMethod::Last.aggregate(&[]).is_err()); } #[test] fn test_from_to_type() { for i in 1..9 { let method = AggregationMethod::from_type(i).unwrap(); assert_eq!(AggregationMethod::to_type(method), i); } assert_eq!(AggregationMethod::from_type(9), None); } }
Last, Max, Min, AvgZero, AbsMax, AbsMin, } impl AggregationMethod { pub fn from_type(aggregation_type: u32) -> Option<Self> { match aggregation_type { 1 => Some(AggregationMethod::Average), 2 => Some(AggregationMethod::Sum), 3 => Some(AggregationMethod::Last), 4 => Some(AggregationMethod::Max), 5 => Some(AggregationMethod::Min), 6 => Some(AggregationMethod::AvgZero), 7 => Some(AggregationMethod::AbsMax), 8 => Some(AggregationMethod::AbsMin), _ => None, } } pub fn to_type(self) -> u32 { match self { AggregationMethod::Average => 1, AggregationMethod::Sum => 2, AggregationMethod::Last => 3, AggregationMethod::Max => 4, AggregationMethod::Min => 5, AggregationMethod::AvgZero => 6, AggregationMethod::AbsMax => 7, AggregationMethod::AbsMin => 8,
random
[ { "content": "pub fn diff(\n\n path1: &Path,\n\n path2: &Path,\n\n ignore_empty: bool,\n\n mut until_time: u32,\n\n now: u32,\n\n) -> Result<Vec<DiffArchive>, io::Error> {\n\n let mut file1 = WhisperFile::open(path1)?;\n\n let mut file2 = WhisperFile::open(path2)?;\n\n\n\n if file1.info(...
Rust
src/algorithms/leaky_bucket.rs
jbg/ratelimit_meter
df4d7a3f9b26dffe4468ad2b05a512589296dd64
use crate::lib::*; use crate::thread_safety::ThreadsafeWrapper; use crate::{ algorithms::{Algorithm, RateLimitState, RateLimitStateWithClock}, instant, InconsistentCapacity, NegativeMultiDecision, NonConformance, }; #[derive(Debug, Clone, Eq, PartialEq)] pub struct LeakyBucket<P: instant::Relative = instant::TimeSource> { full: Duration, token_interval: Duration, point: PhantomData<P>, } #[derive(Debug, Eq, PartialEq, Clone)] pub struct State<P: instant::Relative>(ThreadsafeWrapper<BucketState<P>>); impl<P: instant::Relative> Default for State<P> { fn default() -> Self { State(Default::default()) } } impl<P: instant::Relative> RateLimitState<LeakyBucket<P>, P> for State<P> {} impl<P: instant::Absolute> RateLimitStateWithClock<LeakyBucket<P>, P> for State<P> { fn last_touched(&self, _params: &LeakyBucket<P>) -> P { let data = self.0.snapshot(); data.last_update.unwrap_or_else(P::now) + data.level } } #[cfg(feature = "std")] mod std { use crate::instant::Relative; use evmap::ShallowCopy; impl<P: Relative> ShallowCopy for super::State<P> { unsafe fn shallow_copy(&mut self) -> Self { super::State(self.0.shallow_copy()) } } } #[derive(Debug, PartialEq)] pub struct TooEarly<P: instant::Relative>(P, Duration); impl<P: instant::Relative> fmt::Display for TooEarly<P> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "rate-limited until {:?}", self.0 + self.1) } } impl<P: instant::Relative> NonConformance<P> for TooEarly<P> { #[inline] fn earliest_possible(&self) -> P { self.0 + self.1 } } #[derive(Debug, Clone, PartialEq, Eq)] struct BucketState<P: instant::Relative> { level: Duration, last_update: Option<P>, } impl<P: instant::Relative> Default for BucketState<P> { fn default() -> Self { BucketState { level: Duration::new(0, 0), last_update: None, } } } impl<P: instant::Relative> Algorithm<P> for LeakyBucket<P> { type BucketState = State<P>; type NegativeDecision = TooEarly<P>; fn construct( capacity: NonZeroU32, cell_weight: NonZeroU32, per_time_unit: Duration, ) -> Result<Self, InconsistentCapacity> { if capacity < cell_weight { return Err(InconsistentCapacity::new(capacity, cell_weight)); } let token_interval = (per_time_unit * cell_weight.get()) / capacity.get(); Ok(LeakyBucket { full: per_time_unit, token_interval, point: PhantomData, }) } fn test_n_and_update( &self, state: &Self::BucketState, n: u32, t0: P, ) -> Result<(), NegativeMultiDecision<TooEarly<P>>> { let full = self.full; let weight = self.token_interval * n; if weight > self.full { return Err(NegativeMultiDecision::InsufficientCapacity(n)); } state.0.measure_and_replace(|state| { let mut new = BucketState { last_update: Some(t0), level: Duration::new(0, 0), }; let last = state.last_update.unwrap_or(t0); let t0 = cmp::max(t0, last); new.level = state.level - cmp::min(t0.duration_since(last), state.level); if weight + new.level <= full { new.level += weight; (Ok(()), Some(new)) } else { let wait_period = (weight + new.level) - full; ( Err(NegativeMultiDecision::BatchNonConforming( n, TooEarly(t0, wait_period), )), None, ) } }) } }
use crate::lib::*; use crate::thread_safety::ThreadsafeWrapper; use crate::{ algorithms::{Algorithm, RateLimitState, RateLimitStateWithClock}, instant, InconsistentCapacity, NegativeMultiDecision, NonConformance, }; #[derive(Debug, Clone, Eq, PartialEq)] pub struct LeakyBucket<P: instant::Relative = instant::TimeSource> { full: Duration, token_interval: Duration, point: PhantomData<P>, } #[derive(Debug, Eq, PartialEq, Clone)] pub struct State<P: instant::Relative>(ThreadsafeWrapper<BucketState<P>>); impl<P: instant::Relative> Default for State<P> { fn default() -> Self { State(Default::default()) } } impl<P: instant::Relative> RateLimitState<LeakyBucket<P>, P> for State<P> {} impl<P: instant::Absolute> RateLimitStateWithClock<LeakyBucket<P>, P> for State<P> { fn last_touched(&self, _params: &LeakyBucket<P>) -> P { let data = self.0.snapshot(); data.last_update.unwrap_or_else(P::now) + data.level } } #[cfg(feature = "std")] mod std { use crate::instant::Relative; use evmap::ShallowCopy; impl<P: Relative> ShallowCopy for super::State<P> { unsafe fn shallow_copy(&mut self) -> Self { super::State(self.0.shallow_copy()) } } } #[derive(Debug, PartialEq)] pub struct TooEarly<P: instant::Relative>(P, Duration); impl<P: instant::Relative> fmt::Display for TooEarly<P> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "rate-limited until {:?}", self.0 + self.1) } } impl<P: instant::Relative> NonConformance<P> for TooEarly<P> { #[inline] fn earliest_possible(&self) -> P { self.0 + self.1 } } #[derive(Debug, Clone, PartialEq, Eq)] struct BucketState<P: instant::Relative> { level: Duration, last_update: Option<P>, } impl<P: instant::R
(per_time_unit * cell_weight.get()) / capacity.get(); Ok(LeakyBucket { full: per_time_unit, token_interval, point: PhantomData, }) } fn test_n_and_update( &self, state: &Self::BucketState, n: u32, t0: P, ) -> Result<(), NegativeMultiDecision<TooEarly<P>>> { let full = self.full; let weight = self.token_interval * n; if weight > self.full { return Err(NegativeMultiDecision::InsufficientCapacity(n)); } state.0.measure_and_replace(|state| { let mut new = BucketState { last_update: Some(t0), level: Duration::new(0, 0), }; let last = state.last_update.unwrap_or(t0); let t0 = cmp::max(t0, last); new.level = state.level - cmp::min(t0.duration_since(last), state.level); if weight + new.level <= full { new.level += weight; (Ok(()), Some(new)) } else { let wait_period = (weight + new.level) - full; ( Err(NegativeMultiDecision::BatchNonConforming( n, TooEarly(t0, wait_period), )), None, ) } }) } }
elative> Default for BucketState<P> { fn default() -> Self { BucketState { level: Duration::new(0, 0), last_update: None, } } } impl<P: instant::Relative> Algorithm<P> for LeakyBucket<P> { type BucketState = State<P>; type NegativeDecision = TooEarly<P>; fn construct( capacity: NonZeroU32, cell_weight: NonZeroU32, per_time_unit: Duration, ) -> Result<Self, InconsistentCapacity> { if capacity < cell_weight { return Err(InconsistentCapacity::new(capacity, cell_weight)); } let token_interval =
random
[ { "content": "/// Trait that all rate limit states have to implement around\n\n/// housekeeping in keyed rate limiters.\n\npub trait RateLimitState<P, I: instant::Relative>: Default + Send + Sync + Eq + fmt::Debug {}\n\n\n", "file_path": "src/algorithms.rs", "rank": 0, "score": 139496.12516807122 ...
Rust
languages/idl_gen/src/rust/con_idl.rs
adrianos42/native_idl
688de924e1e2244719a33aba40aae8b9dd10ede9
use idl::idl_nodes::*; use proc_macro2::{self, TokenStream}; use quote::format_ident; pub(crate) fn get_rust_ty_ref(ty: &TypeName, references: bool) -> TokenStream { match ty { TypeName::Types(types) => match types { Types::NatInt => quote! { i64 }, Types::NatFloat => quote! { f64 }, Types::NatString => quote! { String }, Types::NatBytes => quote! { Vec<u8> }, Types::NatBool => quote! { bool }, Types::NatUUID => quote! { Uuid }, Types::NatNone => quote! { () }, }, TypeName::TypeFunction(value) => { let args = get_rust_ty_ref(&value.args, references); let ret = get_rust_ty_ref(&value.return_ty, references); quote! { #args -> #ret } } TypeName::TypeTuple(value) => { let mut fields_t = vec![]; for ty in &value.fields { let ident = format_ident!("{}", &ty.ident); let ty_ident = get_rust_ty_ref(&ty.ty, references); fields_t.push(quote! { #ident: #ty_ident }) } let fields = fields_t.into_iter(); quote! { ( #( #fields ),* ) } } TypeName::TypeArray(value) => { let ty = get_rust_ty_ref(&value.ty, references); quote! { Vec<#ty> } } TypeName::TypeMap(value) => { let ty = get_rust_ty_ref(&value.map_ty, references); let index_ty = get_rust_ty_ref(&value.index_ty, references); quote! { ::std::collections::HashMap<#index_ty, #ty> } } TypeName::TypeResult(value) => { let ok_ty = get_rust_ty_ref(&value.ok_ty, references); let err_ty = get_rust_ty_ref(&value.err_ty, references); quote! { Result<#ok_ty, #err_ty> } } TypeName::TypePair(value) => { let first_ty = get_rust_ty_ref(&value.first_ty, references); let second_ty = get_rust_ty_ref(&value.second_ty, references); quote! { (#first_ty, #second_ty) } } TypeName::TypeOption(value) => { let some_ty = get_rust_ty_ref(&value.some_ty, references); quote! { Option<#some_ty> } } TypeName::ListTypeName(value) | TypeName::EnumTypeName(value) | TypeName::StructTypeName(value) | TypeName::ConstTypeName(value) => { let ident = format_ident!("{}", &value); if references { quote! { super::#ident } } else { quote! { #ident } } } TypeName::TypeStream(_) => { quote! { Box<dyn StreamInstance + Send + Sync> } } TypeName::InterfaceTypeName(value) => { let ident = format_ident!("{}Instance", value); quote! { Box<dyn super::idl_impl::#ident> } } } } pub(crate) fn get_rust_ty_name(ty: &TypeName) -> String { match ty { TypeName::Types(types) => match types { Types::NatInt => "i64".to_owned(), Types::NatFloat => "f64".to_owned(), Types::NatString => "String".to_owned(), Types::NatBytes => "Vecu8".to_owned(), Types::NatBool => "bool".to_owned(), Types::NatUUID => "Uuid".to_owned(), Types::NatNone => "none".to_owned(), }, TypeName::TypeFunction(value) => { let args = get_rust_ty_name(&value.args); let ret = get_rust_ty_name(&value.return_ty); format!("Func{}Ret{}_", args, ret) } TypeName::TypeTuple(value) => { let mut fields_t = String::new(); for ty in &value.fields { let ty_ident = get_rust_ty_name(&ty.ty); fields_t.push_str(&ty_ident); } format!("Args{}_", fields_t) } TypeName::TypeArray(value) => { let ty = get_rust_ty_name(&value.ty); format!("Vec{}_", ty) } TypeName::TypeMap(value) => { let ty = get_rust_ty_name(&value.map_ty); let index_ty = get_rust_ty_name(&value.index_ty); format!("Map{}{}_", ty, index_ty) } TypeName::TypeResult(value) => { let ok_ty = get_rust_ty_name(&value.ok_ty); let err_ty = get_rust_ty_name(&value.err_ty); format!("Result{}{}_", ok_ty, err_ty) } TypeName::TypePair(value) => { let first_ty = get_rust_ty_name(&value.first_ty); let second_ty = get_rust_ty_name(&value.second_ty); format!("Pair{}{}_", first_ty, second_ty) } TypeName::TypeOption(value) => { let some_ty = get_rust_ty_name(&value.some_ty); format!("Option{}_", some_ty) } TypeName::ListTypeName(value) | TypeName::EnumTypeName(value) | TypeName::StructTypeName(value) | TypeName::ConstTypeName(value) => value.to_owned(), TypeName::TypeStream(value) => { let stream_ty = get_rust_ty_name(&value.s_ty); format!("Stream{}_", stream_ty) } TypeName::InterfaceTypeName(value) => value.to_owned(), } }
use idl::idl_nodes::*; use proc_macro2::{self, TokenStream}; use quote::format_ident; pub(crate) fn get_rust_ty_ref(ty: &TypeName, references: bool) -> TokenStream { match ty { TypeName::Types(types) => match types { Types::NatInt => quote! { i64 }, Types::NatFloat => quote! { f64 }, Types::NatString => quote! { String }, Types::NatBytes => quote! { Vec<u8> }, Types::NatBool => quote! { bool }, Types::NatUUID => quote! { Uuid }, Types::NatNone => quote! { () }, }, TypeName::TypeFunction(value) => { let args = get_rust_ty_ref(&value.args, references); let ret = get_rust_ty_ref(&value.return_ty, references); quote! { #args -> #ret } } TypeName::TypeTuple(value) => { let mut fields_t = vec![]; for ty in &value.fields { let ident = format_ident!("{}", &ty.ident); let ty_ident = get_rust_ty_ref(&ty.ty, references); fields_t.push(quote! { #ident: #ty_ident }) } let fields = fields_t.into_iter(); quote! { ( #( #fields ),* ) } } TypeName::TypeArray(value) => { let ty = get_rust_ty_ref(&value.ty, references); quote! { Vec<#ty> } } TypeName::TypeMap(value) => { let ty = get_rust_ty_ref(&value.map_ty, references); let index_ty = get_rust_ty_ref(&value.index_ty, references); quote! { ::std::collections::HashMap<#index_ty, #ty> } } TypeName::TypeResult(value) => { let ok_ty = get_rust_ty_ref(&value.ok_ty, references); let err_ty = get_rust_ty_ref(&value.err_ty, references); quote! { Result<#ok_ty, #err_ty> } } TypeName::TypePair(value) => { let first_ty = get_rust_ty_ref(&value.first_ty, references); let second_ty = get_rust_ty_ref(&value.second_ty, references); quote! { (#first_ty, #second_ty) } } TypeName::TypeOption(value) => { let some_ty = get_rust_ty_ref(&value.some_ty, references); quote! { Option<#some_ty> } } TypeName::ListTypeName(value) | TypeName::EnumTypeName(value) | TypeName::StructTypeName(value) | TypeName::ConstTypeName(
TypeName::InterfaceTypeName(value) => { let ident = format_ident!("{}Instance", value); quote! { Box<dyn super::idl_impl::#ident> } } } } pub(crate) fn get_rust_ty_name(ty: &TypeName) -> String { match ty { TypeName::Types(types) => match types { Types::NatInt => "i64".to_owned(), Types::NatFloat => "f64".to_owned(), Types::NatString => "String".to_owned(), Types::NatBytes => "Vecu8".to_owned(), Types::NatBool => "bool".to_owned(), Types::NatUUID => "Uuid".to_owned(), Types::NatNone => "none".to_owned(), }, TypeName::TypeFunction(value) => { let args = get_rust_ty_name(&value.args); let ret = get_rust_ty_name(&value.return_ty); format!("Func{}Ret{}_", args, ret) } TypeName::TypeTuple(value) => { let mut fields_t = String::new(); for ty in &value.fields { let ty_ident = get_rust_ty_name(&ty.ty); fields_t.push_str(&ty_ident); } format!("Args{}_", fields_t) } TypeName::TypeArray(value) => { let ty = get_rust_ty_name(&value.ty); format!("Vec{}_", ty) } TypeName::TypeMap(value) => { let ty = get_rust_ty_name(&value.map_ty); let index_ty = get_rust_ty_name(&value.index_ty); format!("Map{}{}_", ty, index_ty) } TypeName::TypeResult(value) => { let ok_ty = get_rust_ty_name(&value.ok_ty); let err_ty = get_rust_ty_name(&value.err_ty); format!("Result{}{}_", ok_ty, err_ty) } TypeName::TypePair(value) => { let first_ty = get_rust_ty_name(&value.first_ty); let second_ty = get_rust_ty_name(&value.second_ty); format!("Pair{}{}_", first_ty, second_ty) } TypeName::TypeOption(value) => { let some_ty = get_rust_ty_name(&value.some_ty); format!("Option{}_", some_ty) } TypeName::ListTypeName(value) | TypeName::EnumTypeName(value) | TypeName::StructTypeName(value) | TypeName::ConstTypeName(value) => value.to_owned(), TypeName::TypeStream(value) => { let stream_ty = get_rust_ty_name(&value.s_ty); format!("Stream{}_", stream_ty) } TypeName::InterfaceTypeName(value) => value.to_owned(), } }
value) => { let ident = format_ident!("{}", &value); if references { quote! { super::#ident } } else { quote! { #ident } } } TypeName::TypeStream(_) => { quote! { Box<dyn StreamInstance + Send + Sync> } }
function_block-random_span
[]
Rust
src/mqtt/listener.rs
Galhad/ratelmq
15395108681aa97b861d0364263ac7cd123d2b11
use crate::mqtt::events::{ClientEvent, ServerEvent}; use crate::mqtt::packets::ControlPacket; use crate::mqtt::transport::mqtt_bytes_stream::{MqttBytesReadStream, MqttBytesWriteStream}; use crate::mqtt::transport::packet_decoder::read_packet; use crate::mqtt::transport::packet_encoder::write_packet; use log::{debug, error, info, trace, warn}; use std::net::SocketAddr; use tokio::io::Error; use tokio::net::{TcpListener, TcpStream}; use tokio::select; use tokio::sync::mpsc::{Receiver, Sender}; use tokio::sync::{broadcast, mpsc}; pub struct MqttListener { listener: TcpListener, client_event_tx: mpsc::Sender<ClientEvent>, ctrl_c_rx: broadcast::Receiver<()>, } impl MqttListener { pub async fn bind( address: &str, client_event_tx: mpsc::Sender<ClientEvent>, ctrl_c_rx: broadcast::Receiver<()>, ) -> Result<MqttListener, Error> { debug!("Binding MQTT TCP to {}", &address); let listener = TcpListener::bind(address).await.unwrap(); info!("Listening for MQTT TCP connections on {}", &address); let mqtt_listener = MqttListener { listener, client_event_tx, ctrl_c_rx, }; Ok(mqtt_listener) } pub async fn start_accepting(mut self) { loop { select! { _ = self.ctrl_c_rx.recv() => { trace!("Stopping listener"); break; } _ = Self::accept(&self.listener, &self.client_event_tx) => {} } } } async fn accept(listener: &TcpListener, client_event_tx: &mpsc::Sender<ClientEvent>) { match listener.accept().await { Ok((socket, address)) => { let client_event_tx = client_event_tx.clone(); tokio::spawn(async move { Self::handle_connection(socket, client_event_tx, address).await; }); } Err(e) => { error!("Error while accepting connection: {:?}", e); } } } async fn handle_connection( socket: TcpStream, client_event_tx: Sender<ClientEvent>, address: SocketAddr, ) { let (tcp_read, tcp_write) = socket.into_split(); let (server_event_tx, server_event_rx) = mpsc::channel(32); let mut write_stream = MqttBytesWriteStream::new(4096, tcp_write); tokio::spawn(async move { Self::connection_write_loop(server_event_rx, &mut write_stream).await; }); let mut read_stream = MqttBytesReadStream::new(4096, tcp_read); tokio::spawn(async move { Self::connection_read_loop(client_event_tx, server_event_tx, &mut read_stream, address) .await; }); } async fn connection_read_loop( client_event_tx: Sender<ClientEvent>, server_event_tx: Sender<ServerEvent>, mut read_stream: &mut MqttBytesReadStream, address: SocketAddr, ) { let client_id; if let Ok(packet) = read_packet(&mut read_stream).await { trace!("Read the first packet: {:?}", &packet); if let ControlPacket::Connect(c) = packet { client_id = c.client_id.clone(); let event = ClientEvent::Connected(c, address, server_event_tx.clone()); if let Err(e) = client_event_tx.send(event).await { error!("Error while sending client event to be processed: {}", &e); } } else { warn!("The first received packet is not CONNECT"); return; } } else { return; } while let Ok(packet) = read_packet(&mut read_stream).await { trace!("Read packet: {:?}", &packet); let event = ClientEvent::ControlPacket(client_id.clone(), packet, server_event_tx.clone()); if let Err(e) = client_event_tx.send(event).await { error!("Error while sending client event to be processed: {}", &e); } } trace!("Client read task ended"); } async fn connection_write_loop( mut server_event_rx: Receiver<ServerEvent>, mut write_stream: &mut MqttBytesWriteStream, ) { while let Some(event) = server_event_rx.recv().await { trace!("Received server event: {:?}", &event); match event { ServerEvent::ControlPacket(packet) => { trace!("Writing packet: {:?}", &packet); if let Err(e) = write_packet(&mut write_stream, packet).await { error!("Error while writing packet: {:?}", &e); } } ServerEvent::Disconnect => { break; } } } trace!("Client write task ended"); } }
use crate::mqtt::events::{ClientEvent, ServerEvent}; use crate::mqtt::packets::ControlPacket; use crate::mqtt::transport::mqtt_bytes_stream::{MqttBytesReadStream, MqttBytesWriteStream}; use crate::mqtt::transport::packet_decoder::read_packet; use crate::mqtt::transport::packet_encoder::write_packet; use log::{debug, error, info, trace, warn}; use std::net::SocketAddr; use tokio::io::Error; use tokio::net::{TcpListener, TcpStream}; use tokio::select; use toki
_tx = client_event_tx.clone(); tokio::spawn(async move { Self::handle_connection(socket, client_event_tx, address).await; }); } Err(e) => { error!("Error while accepting connection: {:?}", e); } } } async fn handle_connection( socket: TcpStream, client_event_tx: Sender<ClientEvent>, address: SocketAddr, ) { let (tcp_read, tcp_write) = socket.into_split(); let (server_event_tx, server_event_rx) = mpsc::channel(32); let mut write_stream = MqttBytesWriteStream::new(4096, tcp_write); tokio::spawn(async move { Self::connection_write_loop(server_event_rx, &mut write_stream).await; }); let mut read_stream = MqttBytesReadStream::new(4096, tcp_read); tokio::spawn(async move { Self::connection_read_loop(client_event_tx, server_event_tx, &mut read_stream, address) .await; }); } async fn connection_read_loop( client_event_tx: Sender<ClientEvent>, server_event_tx: Sender<ServerEvent>, mut read_stream: &mut MqttBytesReadStream, address: SocketAddr, ) { let client_id; if let Ok(packet) = read_packet(&mut read_stream).await { trace!("Read the first packet: {:?}", &packet); if let ControlPacket::Connect(c) = packet { client_id = c.client_id.clone(); let event = ClientEvent::Connected(c, address, server_event_tx.clone()); if let Err(e) = client_event_tx.send(event).await { error!("Error while sending client event to be processed: {}", &e); } } else { warn!("The first received packet is not CONNECT"); return; } } else { return; } while let Ok(packet) = read_packet(&mut read_stream).await { trace!("Read packet: {:?}", &packet); let event = ClientEvent::ControlPacket(client_id.clone(), packet, server_event_tx.clone()); if let Err(e) = client_event_tx.send(event).await { error!("Error while sending client event to be processed: {}", &e); } } trace!("Client read task ended"); } async fn connection_write_loop( mut server_event_rx: Receiver<ServerEvent>, mut write_stream: &mut MqttBytesWriteStream, ) { while let Some(event) = server_event_rx.recv().await { trace!("Received server event: {:?}", &event); match event { ServerEvent::ControlPacket(packet) => { trace!("Writing packet: {:?}", &packet); if let Err(e) = write_packet(&mut write_stream, packet).await { error!("Error while writing packet: {:?}", &e); } } ServerEvent::Disconnect => { break; } } } trace!("Client write task ended"); } }
o::sync::mpsc::{Receiver, Sender}; use tokio::sync::{broadcast, mpsc}; pub struct MqttListener { listener: TcpListener, client_event_tx: mpsc::Sender<ClientEvent>, ctrl_c_rx: broadcast::Receiver<()>, } impl MqttListener { pub async fn bind( address: &str, client_event_tx: mpsc::Sender<ClientEvent>, ctrl_c_rx: broadcast::Receiver<()>, ) -> Result<MqttListener, Error> { debug!("Binding MQTT TCP to {}", &address); let listener = TcpListener::bind(address).await.unwrap(); info!("Listening for MQTT TCP connections on {}", &address); let mqtt_listener = MqttListener { listener, client_event_tx, ctrl_c_rx, }; Ok(mqtt_listener) } pub async fn start_accepting(mut self) { loop { select! { _ = self.ctrl_c_rx.recv() => { trace!("Stopping listener"); break; } _ = Self::accept(&self.listener, &self.client_event_tx) => {} } } } async fn accept(listener: &TcpListener, client_event_tx: &mpsc::Sender<ClientEvent>) { match listener.accept().await { Ok((socket, address)) => { let client_event
random
[ { "content": "#[derive(Debug)]\n\npub struct BuildInfo {\n\n pub version: &'static str,\n\n pub commit_hash: &'static str,\n\n}\n\n\n\npub const BUILD_INFO: BuildInfo = BuildInfo {\n\n version: env!(\"CARGO_PKG_VERSION\"),\n\n commit_hash: env!(\"BUILD_GIT_HASH\"),\n\n};\n", "file_path": "src/co...
Rust
src/utils.rs
KaiWitt/kalayo
5498ed501cb7799cacb709403ba8a6141dc3e2e4
use bitcoin::util::address::Address; use bitcoin::{AddressType, Network}; use std::str::FromStr; use warp::hyper::StatusCode; use warp::Rejection; use crate::error::ErrorMsg; pub fn validate_address(address: Address) -> Result<Address, Rejection> { if address.network != Network::Bitcoin { return Err(ErrorMsg::reject_new( StatusCode::BAD_REQUEST, format!("Address [{}] is not a Bitcoin mainnet address.", address), )); } if let Some(addr_type) = address.address_type() { if addr_type != AddressType::P2wpkh { let msg = format!("[{}] is not a P2WPKH Bitcoin mainnet address.", &address); return Err(ErrorMsg::reject_new(StatusCode::BAD_REQUEST, msg)); } return Ok(address); } log::warn!("Adress [{}] has no address type", address); Err(ErrorMsg::reject_new( StatusCode::BAD_REQUEST, format!("Address [{}] has no address type.", address), )) } pub fn validate_address_str(address: &str) -> Result<Address, Rejection> { match Address::from_str(address) { Ok(address) => validate_address(address), Err(_) => { let msg = format!("[{}] is not a valid Bitcoin address.", &address); Err(ErrorMsg::reject_new(StatusCode::BAD_REQUEST, msg)) } } } #[cfg(test)] mod test { use std::str::FromStr; use bitcoin::Address; use crate::utils::{validate_address, validate_address_str}; #[test] fn validate_address_returns_address_when_address_is_mainnet_p2wpkh() { let p2wpkh = Address::from_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); let p2wpkh_validated = validate_address(p2wpkh.clone()).unwrap(); assert_eq!(p2wpkh_validated, p2wpkh); } #[test] fn validate_address_returns_err_when_address_is_not_p2wpkh() { let p2pkh = Address::from_str("1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ").unwrap(); let p2sh = Address::from_str("34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo").unwrap(); let p2wsh = Address::from_str("bc1q8500kqh90vgkgsdnsw6a84mrzmgwwnhtxuu5wy347wuxk0g08e4smc3tl9") .unwrap(); let p2pkh_validated = validate_address(p2pkh.clone()); let p2sh_validated = validate_address(p2sh.clone()); let p2wsh_validated = validate_address(p2wsh.clone()); assert!(p2pkh_validated.is_err()); assert!(p2sh_validated.is_err()); assert!(p2wsh_validated.is_err()); } #[test] fn validate_address_returns_err_when_address_is_not_mainnet() { let testnet_addr = Address::from_str("tb1qt25c7aencjadsva2tkzmkc9juqslnn2e0kug4h").unwrap(); let validated = validate_address(testnet_addr.clone()); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_address_when_address_is_mainnet_p2wpkh() { let p2wpkh = Address::from_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); let p2wpkh_validated = validate_address_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); assert_eq!(p2wpkh_validated, p2wpkh); } #[test] fn validate_address_str_returns_err_when_address_is_not_p2wpkh() { let p2pkh = validate_address_str("1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ"); let p2sh = validate_address_str("34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo"); assert!(p2pkh.is_err()); assert!(p2sh.is_err()); } #[test] fn validate_address_str_returns_err_when_address_is_not_mainnet() { let validated = validate_address_str("tb1qt25c7aencjadsva2tkzmkc9juqslnn2e0kug4h"); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_err_when_input_is_not_an_address() { let validated = validate_address_str("notanaddress"); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_err_when_input_is_empty() { let validated = validate_address_str(""); assert!(validated.is_err()); } }
use bitcoin::util::address::Address; use bitcoin::{AddressType, Network}; use std::str::FromStr; use warp::hyper::StatusCode; use warp::Rejection; use crate::error::ErrorMsg; pub fn validate_address(address: Address) -> Result<Address, Rejection> { if address.network != Network::Bitcoin { return Err(ErrorMsg::reject_new( StatusCode::BAD_REQUEST, format!("Address [{}] is not a Bitcoin mainnet address.", address), )); }
pub fn validate_address_str(address: &str) -> Result<Address, Rejection> { match Address::from_str(address) { Ok(address) => validate_address(address), Err(_) => { let msg = format!("[{}] is not a valid Bitcoin address.", &address); Err(ErrorMsg::reject_new(StatusCode::BAD_REQUEST, msg)) } } } #[cfg(test)] mod test { use std::str::FromStr; use bitcoin::Address; use crate::utils::{validate_address, validate_address_str}; #[test] fn validate_address_returns_address_when_address_is_mainnet_p2wpkh() { let p2wpkh = Address::from_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); let p2wpkh_validated = validate_address(p2wpkh.clone()).unwrap(); assert_eq!(p2wpkh_validated, p2wpkh); } #[test] fn validate_address_returns_err_when_address_is_not_p2wpkh() { let p2pkh = Address::from_str("1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ").unwrap(); let p2sh = Address::from_str("34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo").unwrap(); let p2wsh = Address::from_str("bc1q8500kqh90vgkgsdnsw6a84mrzmgwwnhtxuu5wy347wuxk0g08e4smc3tl9") .unwrap(); let p2pkh_validated = validate_address(p2pkh.clone()); let p2sh_validated = validate_address(p2sh.clone()); let p2wsh_validated = validate_address(p2wsh.clone()); assert!(p2pkh_validated.is_err()); assert!(p2sh_validated.is_err()); assert!(p2wsh_validated.is_err()); } #[test] fn validate_address_returns_err_when_address_is_not_mainnet() { let testnet_addr = Address::from_str("tb1qt25c7aencjadsva2tkzmkc9juqslnn2e0kug4h").unwrap(); let validated = validate_address(testnet_addr.clone()); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_address_when_address_is_mainnet_p2wpkh() { let p2wpkh = Address::from_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); let p2wpkh_validated = validate_address_str("bc1qx46k3hyr7pu83vj3srapz0hdht3gzy8j3yplmp").unwrap(); assert_eq!(p2wpkh_validated, p2wpkh); } #[test] fn validate_address_str_returns_err_when_address_is_not_p2wpkh() { let p2pkh = validate_address_str("1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ"); let p2sh = validate_address_str("34xp4vRoCGJym3xR7yCVPFHoCNxv4Twseo"); assert!(p2pkh.is_err()); assert!(p2sh.is_err()); } #[test] fn validate_address_str_returns_err_when_address_is_not_mainnet() { let validated = validate_address_str("tb1qt25c7aencjadsva2tkzmkc9juqslnn2e0kug4h"); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_err_when_input_is_not_an_address() { let validated = validate_address_str("notanaddress"); assert!(validated.is_err()); } #[test] fn validate_address_str_returns_err_when_input_is_empty() { let validated = validate_address_str(""); assert!(validated.is_err()); } }
if let Some(addr_type) = address.address_type() { if addr_type != AddressType::P2wpkh { let msg = format!("[{}] is not a P2WPKH Bitcoin mainnet address.", &address); return Err(ErrorMsg::reject_new(StatusCode::BAD_REQUEST, msg)); } return Ok(address); } log::warn!("Adress [{}] has no address type", address); Err(ErrorMsg::reject_new( StatusCode::BAD_REQUEST, format!("Address [{}] has no address type.", address), )) }
function_block-function_prefix_line
[]
Rust
vendor/rust-cdk/src/ic_cdk_macros/src/import.rs
dfinity/bigmap-poc
177e3be92316064d62e6e31538f01dded65b9ccb
use crate::error::Errors; use quote::quote; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use std::path::PathBuf; use std::str::FromStr; #[derive(Default, Deserialize)] struct ImportAttributes { pub canister: Option<String>, pub canister_id: Option<String>, pub candid_path: Option<PathBuf>, } fn get_env_id_and_candid(canister_name: &str) -> Result<(String, PathBuf), Errors> { let canister_id_var_name = format!("CANISTER_ID_{}", canister_name); let candid_path_var_name = format!("CANISTER_CANDID_{}", canister_name); Ok(( std::env::var(canister_id_var_name).map_err(|_| { Errors::message(&format!( "Could not find DFX bindings for canister named '{}'. Did you build using DFX?", canister_name )) })?, std::env::var_os(candid_path_var_name) .ok_or_else(|| Errors::message("Could not find DFX bindings.")) .map(|p| PathBuf::from(p))?, )) } struct RustLanguageBinding { visibility: String, canister_id: String, } impl candid::codegen::rust::RustBindings for RustLanguageBinding { fn record( &self, id: &str, fields: &[(String, String)], ) -> Result<String, candid::error::Error> { let all_fields = fields .iter() .map(|(name, ty)| format!("pub {} : {}", name, ty)) .collect::<Vec<String>>() .join(" , "); Ok(format!( r#" #[derive(Clone, Debug, Default, CandidType, serde::Deserialize)] pub struct {} {{ {} }} "#, id, all_fields )) } fn actor(&self, name: &str, all_functions: &[String]) -> Result<String, candid::error::Error> { let mut all_functions_str = String::new(); for f in all_functions { all_functions_str += f; } Ok(format!( r#"{vis} struct {name} {{ }} impl {name} {{ {functions} }}"#, vis = self.visibility, name = name, functions = all_functions_str )) } fn actor_function_body( &self, name: &str, arguments: &[(String, String)], return_type: &str, _is_query: bool, ) -> Result<String, candid::error::Error> { let canister_id = &self.canister_id; let arguments = if arguments.is_empty() { "Option::<()>::None".to_string() } else if arguments.len() == 1 { format!("Some({})", arguments[0].0) } else { format!( "Some(({}))", arguments .iter() .map(|(name, _)| name.clone()) .collect::<Vec<String>>() .join(",") ) }; let call = if return_type.is_empty() { "ic_cdk::call_no_return" } else { "ic_cdk::call" }; Ok(format!( r#" {{ {call}( ic_cdk::CanisterId::from_str("{canister_id}").unwrap(), "{name}", {arguments} ) .await .unwrap() }} "#, call = call, canister_id = canister_id, name = name.escape_debug(), arguments = arguments, )) } fn actor_function( &self, name: &str, arguments: &[(String, String)], returns: &[String], is_query: bool, ) -> Result<String, candid::error::Error> { let id = candid::codegen::rust::candid_id_to_rust(name); let return_type = if returns.is_empty() { "".to_string() } else if returns.len() == 1 { returns[0].clone() } else { format!("( {} )", returns.join(" , ")) }; let arguments_list = arguments .iter() .map(|(name, ty)| format!("{} : {}", name, ty)) .collect::<Vec<String>>() .join(" , "); let body = self.actor_function_body(name, arguments, &return_type, is_query)?; Ok(format!( "async fn {id}( {arguments} ) {return_type} {body}", id = id, arguments = arguments_list, body = body, return_type = if return_type == "" { format!("") } else { format!(" -> {}", return_type) } )) } } pub(crate) fn ic_import( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> Result<proc_macro::TokenStream, Errors> { let config = match from_tokenstream::<ImportAttributes>(&proc_macro2::TokenStream::from(attr)) { Ok(c) => c, Err(err) => return Err(Errors::message(format!("{}", err.to_compile_error()))), }; let (canister_id, candid_path) = { if let Some(canister_name) = config.canister { get_env_id_and_candid(&canister_name)? } else if let Some(canister_id) = config.canister_id { if let Some(candid_path) = config.candid_path { (canister_id, candid_path) } else { return Err(Errors::message("Must specify both candid and canister_id.")); } } else { return Err(Errors::message("Must specify both candid and canister_id.")); } }; let item = syn::parse2::<syn::Item>(proc_macro2::TokenStream::from(item)).map_err(Errors::from)?; let item = match item { syn::Item::Struct(item) => item, _ => return Err(Errors::message("import must be used on a struct.")), }; let visibility = { let vis = item.vis; format!("{}", quote! { #vis }) }; let struct_name = item.ident.to_string(); let candid_str = std::fs::read_to_string(&candid_path).unwrap(); let prog = candid::IDLProg::from_str(&candid_str) .map_err(|e| Errors::message(format!("Could not parse the candid file: {}", e)))?; let bindings = Box::new(RustLanguageBinding { visibility, canister_id: canister_id.clone(), }); let config = candid::codegen::rust::Config::default() .with_actor_name(struct_name) .with_biguint_type("candid::Nat".to_string()) .with_bigint_type("candid::Int".to_string()) .with_bindings(bindings); let rust_str = candid::codegen::idl_to_rust(&prog, &config).map_err(|e| Errors::message(e.to_string()))?; let rust_str = format!("{} {}", "type principal = Vec<u8>;", rust_str); Ok(proc_macro::TokenStream::from_str(&rust_str).unwrap()) }
use crate::error::Errors; use quote::quote; use serde::Deserialize; use serde_tokenstream::from_tokenstream; use std::path::PathBuf; use std::str::FromStr; #[derive(Default, Deserialize)] struct ImportAttributes { pub canister: Option<String>, pub canister_id: Option<String>, pub candid_path: Option<PathBuf>, }
struct RustLanguageBinding { visibility: String, canister_id: String, } impl candid::codegen::rust::RustBindings for RustLanguageBinding { fn record( &self, id: &str, fields: &[(String, String)], ) -> Result<String, candid::error::Error> { let all_fields = fields .iter() .map(|(name, ty)| format!("pub {} : {}", name, ty)) .collect::<Vec<String>>() .join(" , "); Ok(format!( r#" #[derive(Clone, Debug, Default, CandidType, serde::Deserialize)] pub struct {} {{ {} }} "#, id, all_fields )) } fn actor(&self, name: &str, all_functions: &[String]) -> Result<String, candid::error::Error> { let mut all_functions_str = String::new(); for f in all_functions { all_functions_str += f; } Ok(format!( r#"{vis} struct {name} {{ }} impl {name} {{ {functions} }}"#, vis = self.visibility, name = name, functions = all_functions_str )) } fn actor_function_body( &self, name: &str, arguments: &[(String, String)], return_type: &str, _is_query: bool, ) -> Result<String, candid::error::Error> { let canister_id = &self.canister_id; let arguments = if arguments.is_empty() { "Option::<()>::None".to_string() } else if arguments.len() == 1 { format!("Some({})", arguments[0].0) } else { format!( "Some(({}))", arguments .iter() .map(|(name, _)| name.clone()) .collect::<Vec<String>>() .join(",") ) }; let call = if return_type.is_empty() { "ic_cdk::call_no_return" } else { "ic_cdk::call" }; Ok(format!( r#" {{ {call}( ic_cdk::CanisterId::from_str("{canister_id}").unwrap(), "{name}", {arguments} ) .await .unwrap() }} "#, call = call, canister_id = canister_id, name = name.escape_debug(), arguments = arguments, )) } fn actor_function( &self, name: &str, arguments: &[(String, String)], returns: &[String], is_query: bool, ) -> Result<String, candid::error::Error> { let id = candid::codegen::rust::candid_id_to_rust(name); let return_type = if returns.is_empty() { "".to_string() } else if returns.len() == 1 { returns[0].clone() } else { format!("( {} )", returns.join(" , ")) }; let arguments_list = arguments .iter() .map(|(name, ty)| format!("{} : {}", name, ty)) .collect::<Vec<String>>() .join(" , "); let body = self.actor_function_body(name, arguments, &return_type, is_query)?; Ok(format!( "async fn {id}( {arguments} ) {return_type} {body}", id = id, arguments = arguments_list, body = body, return_type = if return_type == "" { format!("") } else { format!(" -> {}", return_type) } )) } } pub(crate) fn ic_import( attr: proc_macro::TokenStream, item: proc_macro::TokenStream, ) -> Result<proc_macro::TokenStream, Errors> { let config = match from_tokenstream::<ImportAttributes>(&proc_macro2::TokenStream::from(attr)) { Ok(c) => c, Err(err) => return Err(Errors::message(format!("{}", err.to_compile_error()))), }; let (canister_id, candid_path) = { if let Some(canister_name) = config.canister { get_env_id_and_candid(&canister_name)? } else if let Some(canister_id) = config.canister_id { if let Some(candid_path) = config.candid_path { (canister_id, candid_path) } else { return Err(Errors::message("Must specify both candid and canister_id.")); } } else { return Err(Errors::message("Must specify both candid and canister_id.")); } }; let item = syn::parse2::<syn::Item>(proc_macro2::TokenStream::from(item)).map_err(Errors::from)?; let item = match item { syn::Item::Struct(item) => item, _ => return Err(Errors::message("import must be used on a struct.")), }; let visibility = { let vis = item.vis; format!("{}", quote! { #vis }) }; let struct_name = item.ident.to_string(); let candid_str = std::fs::read_to_string(&candid_path).unwrap(); let prog = candid::IDLProg::from_str(&candid_str) .map_err(|e| Errors::message(format!("Could not parse the candid file: {}", e)))?; let bindings = Box::new(RustLanguageBinding { visibility, canister_id: canister_id.clone(), }); let config = candid::codegen::rust::Config::default() .with_actor_name(struct_name) .with_biguint_type("candid::Nat".to_string()) .with_bigint_type("candid::Int".to_string()) .with_bindings(bindings); let rust_str = candid::codegen::idl_to_rust(&prog, &config).map_err(|e| Errors::message(e.to_string()))?; let rust_str = format!("{} {}", "type principal = Vec<u8>;", rust_str); Ok(proc_macro::TokenStream::from_str(&rust_str).unwrap()) }
fn get_env_id_and_candid(canister_name: &str) -> Result<(String, PathBuf), Errors> { let canister_id_var_name = format!("CANISTER_ID_{}", canister_name); let candid_path_var_name = format!("CANISTER_CANDID_{}", canister_name); Ok(( std::env::var(canister_id_var_name).map_err(|_| { Errors::message(&format!( "Could not find DFX bindings for canister named '{}'. Did you build using DFX?", canister_name )) })?, std::env::var_os(candid_path_var_name) .ok_or_else(|| Errors::message("Could not find DFX bindings.")) .map(|p| PathBuf::from(p))?, )) }
function_block-full_function
[ { "content": "#[derive(CandidType, serde::Deserialize, Debug)]\n\nstruct CanisterIdRecord {\n\n canister_id: candid::Principal,\n\n}\n\n\n\npub async fn subnet_create_new_canister() -> Result<CanisterId, String> {\n\n let management_canister = ic_cdk::CanisterId::from(Vec::new());\n\n let new_can_id_re...
Rust
src/k8-client/src/client/config_rustls.rs
simlay/k8-api
3a69671c469c46757e489f4ab6919f6601e0e514
use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::net::ToSocketAddrs; use std::path::Path; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures_util::future::Future; use futures_util::io::{AsyncRead as StdAsyncRead, AsyncWrite as StdAsyncWrite}; use http::Uri; use tracing::debug; use hyper::client::connect::{Connected, Connection}; use hyper::service::Service; use hyper::Body; use hyper::Client; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use fluvio_future::net::TcpStream; use fluvio_future::rust_tls::{ConnectorBuilder, DefaultClientTlsStream, TlsConnector}; use super::executor::FluvioHyperExecutor; use crate::cert::{ClientConfigBuilder, ConfigBuilder}; use crate::ClientError; pub type HyperClient = Client<TlsHyperConnector, Body>; pub type HyperConfigBuilder = ClientConfigBuilder<HyperClientBuilder>; pub struct HyperTlsStream(DefaultClientTlsStream); impl Connection for HyperTlsStream { fn connected(&self) -> Connected { Connected::new() } } impl AsyncRead for HyperTlsStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<IoResult<()>> { match Pin::new(&mut self.0).poll_read(cx, buf.initialize_unfilled())? { Poll::Ready(bytes_read) => { buf.advance(bytes_read); Poll::Ready(Ok(())) } Poll::Pending => Poll::Pending, } } } impl AsyncWrite for HyperTlsStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<IoResult<usize>> { Pin::new(&mut self.0).poll_write(cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { Pin::new(&mut self.0).poll_flush(cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { Pin::new(&mut self.0).poll_close(cx) } } #[derive(Clone)] pub struct TlsHyperConnector(Arc<TlsConnector>); impl TlsHyperConnector { fn new(connector: TlsConnector) -> Self { Self(Arc::new(connector)) } } impl Service<Uri> for TlsHyperConnector { type Response = HyperTlsStream; type Error = ClientError; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, uri: Uri) -> Self::Future { let connector = self.0.clone(); Box::pin(async move { let host = match uri.host() { Some(h) => h, None => return Err(ClientError::Other("no host".to_string())), }; match uri.scheme_str() { Some("http") => Err(ClientError::Other("http not supported".to_string())), Some("https") => { let socket_addr = { let host = host.to_string(); let port = uri.port_u16().unwrap_or(443); match (host.as_str(), port).to_socket_addrs()?.next() { Some(addr) => addr, None => { return Err(ClientError::Other(format!( "host resolution: {} failed", host ))) } } }; debug!("socket address to: {}", socket_addr); let tcp_stream = TcpStream::connect(&socket_addr).await?; let stream = connector.connect(host, tcp_stream).await.map_err(|err| { IoError::new(ErrorKind::Other, format!("tls handshake: {}", err)) })?; Ok(HyperTlsStream(stream)) } scheme => Err(ClientError::Other(format!("{:?}", scheme))), } }) } } pub struct HyperClientBuilder(ConnectorBuilder); impl ConfigBuilder for HyperClientBuilder { type Client = HyperClient; fn new() -> Self { Self(ConnectorBuilder::new()) } fn build(self) -> Result<Self::Client, ClientError> { let connector = self.0.build(); Ok(Client::builder() .executor(FluvioHyperExecutor) .build::<_, Body>(TlsHyperConnector::new(connector))) } fn load_ca_certificate(self, ca_path: impl AsRef<Path>) -> Result<Self, IoError> { Ok(Self(self.0.load_ca_cert(ca_path)?)) } fn load_client_certificate<P: AsRef<Path>>( self, client_crt_path: P, client_key_path: P, ) -> Result<Self, IoError> { Ok(Self( self.0.load_client_certs(client_crt_path, client_key_path)?, )) } }
use std::io::{Error as IoError, ErrorKind, Result as IoResult}; use std::net::ToSocketAddrs; use std::path::Path; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures_util::future::Future; use futures_util::io::{AsyncRead as StdAsyncRead, AsyncWrite as StdAsyncWrite}; use http::Uri; use tracing::debug; use hyper::client::connect::{Connected, Connection}; use hyper::service::Service; use hyper::Body; use hyper::Client; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use fluvio_future::net::TcpStream; use fluvio_future::rust_tls::{ConnectorBuilder, DefaultClientTlsStream, TlsConnector}; use super::executor::FluvioHyperExecutor; use crate::cert::{ClientConfigBuilder, ConfigBuilder}; use crate::ClientError; pub type HyperClient = Client<TlsHyperConnector, Body>; pub type HyperConfigBuilder = ClientConfigBuilder<HyperClientBuilder>; pub struct HyperTlsStream(DefaultClientTlsStream); impl Connection for HyperTlsStream { fn connected(&self) -> Connected { Connected::new() } } impl AsyncRead for HyperTlsStream { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<IoResult<()>> { match Pin::new(&mut self.0).poll_read(cx, buf.initialize_unfilled())? {
} impl AsyncWrite for HyperTlsStream { fn poll_write( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<IoResult<usize>> { Pin::new(&mut self.0).poll_write(cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { Pin::new(&mut self.0).poll_flush(cx) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<IoResult<()>> { Pin::new(&mut self.0).poll_close(cx) } } #[derive(Clone)] pub struct TlsHyperConnector(Arc<TlsConnector>); impl TlsHyperConnector { fn new(connector: TlsConnector) -> Self { Self(Arc::new(connector)) } } impl Service<Uri> for TlsHyperConnector { type Response = HyperTlsStream; type Error = ClientError; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, uri: Uri) -> Self::Future { let connector = self.0.clone(); Box::pin(async move { let host = match uri.host() { Some(h) => h, None => return Err(ClientError::Other("no host".to_string())), }; match uri.scheme_str() { Some("http") => Err(ClientError::Other("http not supported".to_string())), Some("https") => { let socket_addr = { let host = host.to_string(); let port = uri.port_u16().unwrap_or(443); match (host.as_str(), port).to_socket_addrs()?.next() { Some(addr) => addr, None => { return Err(ClientError::Other(format!( "host resolution: {} failed", host ))) } } }; debug!("socket address to: {}", socket_addr); let tcp_stream = TcpStream::connect(&socket_addr).await?; let stream = connector.connect(host, tcp_stream).await.map_err(|err| { IoError::new(ErrorKind::Other, format!("tls handshake: {}", err)) })?; Ok(HyperTlsStream(stream)) } scheme => Err(ClientError::Other(format!("{:?}", scheme))), } }) } } pub struct HyperClientBuilder(ConnectorBuilder); impl ConfigBuilder for HyperClientBuilder { type Client = HyperClient; fn new() -> Self { Self(ConnectorBuilder::new()) } fn build(self) -> Result<Self::Client, ClientError> { let connector = self.0.build(); Ok(Client::builder() .executor(FluvioHyperExecutor) .build::<_, Body>(TlsHyperConnector::new(connector))) } fn load_ca_certificate(self, ca_path: impl AsRef<Path>) -> Result<Self, IoError> { Ok(Self(self.0.load_ca_cert(ca_path)?)) } fn load_client_certificate<P: AsRef<Path>>( self, client_crt_path: P, client_key_path: P, ) -> Result<Self, IoError> { Ok(Self( self.0.load_client_certs(client_crt_path, client_key_path)?, )) } }
Poll::Ready(bytes_read) => { buf.advance(bytes_read); Poll::Ready(Ok(())) } Poll::Pending => Poll::Pending, } }
function_block-function_prefix_line
[ { "content": "pub fn create_topic_stream_result(\n\n ttw_list: &TestTopicWatchList,\n\n) -> TokenStreamResult<TopicSpec, TopicStatus,ClientError> {\n\n let mut topic_watch_list = vec![];\n\n for ttw in ttw_list {\n\n topic_watch_list.push(Ok(create_topic_watch(&ttw)));\n\n }\n\n Ok(topic_w...
Rust
samples/command_executer/src/lib.rs
costisin/aws-nitro-enclaves-cli
de77067677ef2287661063b4529e937b52115a60
pub mod command_parser; pub mod protocol_helpers; pub mod utils; use command_parser::{CommandOutput, FileArgs, ListenArgs, RunArgs}; use protocol_helpers::{recv_loop, recv_u64, send_loop, send_u64}; use nix::sys::socket::listen as listen_vsock; use nix::sys::socket::{accept, bind, connect, shutdown, socket}; use nix::sys::socket::{AddressFamily, Shutdown, SockAddr, SockFlag, SockType}; use nix::unistd::close; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::cmp::min; use std::convert::TryInto; use std::fs::File; use std::io::{Read, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::process::Command; pub const VMADDR_CID_ANY: u32 = 0xFFFFFFFF; pub const BUF_MAX_LEN: usize = 8192; pub const BACKLOG: usize = 128; const MAX_CONNECTION_ATTEMPTS: usize = 5; #[derive(Debug, Clone, FromPrimitive)] enum CmdId { RunCmd = 0, RecvFile, SendFile, RunCmdNoWait, } struct VsockSocket { socket_fd: RawFd, } impl VsockSocket { fn new(socket_fd: RawFd) -> Self { VsockSocket { socket_fd } } } impl Drop for VsockSocket { fn drop(&mut self) { shutdown(self.socket_fd, Shutdown::Both) .unwrap_or_else(|e| eprintln!("Failed to shut socket down: {:?}", e)); close(self.socket_fd).unwrap_or_else(|e| eprintln!("Failed to close socket: {:?}", e)); } } impl AsRawFd for VsockSocket { fn as_raw_fd(&self) -> RawFd { self.socket_fd } } fn vsock_connect(cid: u32, port: u32) -> Result<VsockSocket, String> { let sockaddr = SockAddr::new_vsock(cid, port); let mut err_msg = String::new(); for i in 0..MAX_CONNECTION_ATTEMPTS { let vsocket = VsockSocket::new( socket( AddressFamily::Vsock, SockType::Stream, SockFlag::empty(), None, ) .map_err(|err| format!("Failed to create the socket: {:?}", err))?, ); match connect(vsocket.as_raw_fd(), &sockaddr) { Ok(_) => return Ok(vsocket), Err(e) => err_msg = format!("Failed to connect: {}", e), } std::thread::sleep(std::time::Duration::from_secs(1 << i)); } Err(err_msg) } fn run_server(fd: RawFd, no_wait: bool) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let command = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let command_output = if no_wait { #[rustfmt::skip] let output = Command::new("sh") .arg("-c") .arg(command) .spawn(); if output.is_err() { CommandOutput::new( String::new(), format!("Could not execute the command {}", command), 1, ) } else { CommandOutput::new(String::new(), String::new(), 0) } } else { let output = Command::new("sh") .arg("-c") .arg(command) .output() .map_err(|err| format!("Could not execute the command {}: {:?}", command, err))?; CommandOutput::new_from(output)? }; let json_output = serde_json::to_string(&command_output) .map_err(|err| format!("Could not serialize the output: {:?}", err))?; let buf = json_output.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(fd, len)?; send_loop(fd, &buf, len)?; Ok(()) } fn recv_file_server(fd: RawFd) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let path = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let mut file = File::open(path).map_err(|err| format!("Could not open file {:?}", err))?; let filesize = file .metadata() .map_err(|err| format!("Could not get file metadata {:?}", err))? .len(); send_u64(fd, filesize)?; println!("Sending file {} - size {}", path, filesize); let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); file.read_exact(&mut buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not read {:?}", err))?; send_loop(fd, &buf, tmpsize)?; progress += tmpsize } Ok(()) } fn send_file_server(fd: RawFd) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let path = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let mut file = File::create(path).map_err(|err| format!("Could not open file {:?}", err))?; let filesize = recv_u64(fd)?; println!("Receiving file {} - size {}", path, filesize); let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); recv_loop(fd, &mut buf, tmpsize)?; file.write_all(&buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not write {:?}", err))?; progress += tmpsize } Ok(()) } pub fn listen(args: ListenArgs) -> Result<(), String> { let socket_fd = socket( AddressFamily::Vsock, SockType::Stream, SockFlag::empty(), None, ) .map_err(|err| format!("Create socket failed: {:?}", err))?; let sockaddr = SockAddr::new_vsock(VMADDR_CID_ANY, args.port); bind(socket_fd, &sockaddr).map_err(|err| format!("Bind failed: {:?}", err))?; listen_vsock(socket_fd, BACKLOG).map_err(|err| format!("Listen failed: {:?}", err))?; loop { let fd = accept(socket_fd).map_err(|err| format!("Accept failed: {:?}", err))?; let cmdid = match recv_u64(fd) { Ok(id_u64) => match CmdId::from_u64(id_u64) { Some(c) => c, _ => { eprintln!("Error no such command"); continue; } }, Err(e) => { eprintln!("Error {}", e); continue; } }; match cmdid { CmdId::RunCmd => { if let Err(e) = run_server(fd, false) { eprintln!("Error {}", e); } } CmdId::RecvFile => { if let Err(e) = recv_file_server(fd) { eprintln!("Error {}", e); } } CmdId::SendFile => { if let Err(e) = send_file_server(fd) { eprintln!("Error {}", e); } } CmdId::RunCmdNoWait => { if let Err(e) = run_server(fd, true) { eprintln!("Error {}", e); } } } } } pub fn run(args: RunArgs) -> Result<i32, String> { let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); if args.no_wait { send_u64(socket_fd, CmdId::RunCmdNoWait as u64)?; } else { send_u64(socket_fd, CmdId::RunCmd as u64)?; } let buf = args.command.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let mut buf = [0u8; BUF_MAX_LEN]; let len = recv_u64(socket_fd)?; let mut json_output = String::new(); let mut to_recv = len; while to_recv > 0 { let recv_len = min(BUF_MAX_LEN as u64, to_recv); recv_loop(socket_fd, &mut buf, recv_len)?; to_recv -= recv_len; let to_recv_usize: usize = recv_len.try_into().map_err(|err| format!("{:?}", err))?; json_output.push_str( std::str::from_utf8(&buf[0..to_recv_usize]).map_err(|err| format!("{:?}", err))?, ); } let output: CommandOutput = serde_json::from_str(json_output.as_str()) .map_err(|err| format!("Could not deserialize the output: {:?}", err))?; print!("{}", output.stdout); eprint!("{}", output.stderr); let rc = match output.rc { Some(code) => code, _ => 0, }; Ok(rc) } pub fn recv_file(args: FileArgs) -> Result<(), String> { let mut file = File::create(&args.localfile) .map_err(|err| format!("Could not open localfile {:?}", err))?; let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); send_u64(socket_fd, CmdId::RecvFile as u64)?; let buf = args.remotefile.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let filesize = recv_u64(socket_fd)?; println!( "Receiving file {}(saving to {}) - size {}", &args.remotefile, &args.localfile[..], filesize ); let mut progress: u64 = 0; let mut tmpsize: u64; let mut buf = [0u8; BUF_MAX_LEN]; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); recv_loop(socket_fd, &mut buf, tmpsize)?; file.write_all(&buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not write {:?}", err))?; progress += tmpsize } Ok(()) } pub fn send_file(args: FileArgs) -> Result<(), String> { let mut file = File::open(&args.localfile).map_err(|err| format!("Could not open localfile {:?}", err))?; let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); send_u64(socket_fd, CmdId::SendFile as u64)?; let buf = args.remotefile.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let filesize = file .metadata() .map_err(|err| format!("Could not get file metadate {:?}", err))? .len(); send_u64(socket_fd, filesize)?; println!( "Sending file {}(sending to {}) - size {}", &args.localfile, &args.remotefile[..], filesize ); let mut buf = [0u8; BUF_MAX_LEN]; let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); file.read_exact(&mut buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not read {:?}", err))?; send_loop(socket_fd, &buf, tmpsize)?; progress += tmpsize } Ok(()) }
pub mod command_parser; pub mod protocol_helpers; pub mod utils; use command_parser::{CommandOutput, FileArgs, ListenArgs, RunArgs}; use protocol_helpers::{recv_loop, recv_u64, send_loop, send_u64}; use nix::sys::socket::listen as listen_vsock; use nix::sys::socket::{accept, bind, connect, shutdown, socket}; use nix::sys::socket::{AddressFamily, Shutdown, SockAddr, SockFlag, SockType}; use nix::unistd::close; use num_derive::FromPrimitive; use num_traits::FromPrimitive; use std::cmp::min; use std::convert::TryInto; use std::fs::File; use std::io::{Read, Write}; use std::os::unix::io::{AsRawFd, RawFd}; use std::process::Command; pub const VMADDR_CID_ANY: u32 = 0xFFFFFFFF; pub const BUF_MAX_LEN: usize = 8192; pub const BACKLOG: usize = 128; const MAX_CONNECTION_ATTEMPTS: usize = 5; #[derive(Debug, Clone, FromPrimitive)] enum CmdId { RunCmd = 0, RecvFile, SendFile, RunCmdNoWait, } struct VsockSocket { socket_fd: RawFd, } impl VsockSocket { fn new(socket_fd: RawFd) -> Self { VsockSocket { socket_fd } } } impl Drop for VsockSocket { fn drop(&mut self) { shutdown(self.socket_fd, Shutdown::Both) .unwrap_or_else(|e| eprintln!("Failed to shut socket down: {:?}", e)); close(self.socket_fd).unwrap_or_else(|e| eprintln!("Failed to close socket: {:?}", e)); } } impl AsRawFd for VsockSocket { fn as_raw_fd(&self) -> RawFd { self.socket_fd } } fn vsock_connect(cid: u32, port: u32) -> Result<VsockSocket, String> { let sockaddr = SockAddr::new_vsock(cid, port); let mut err_msg = String::new(); for i in 0..MAX_CONNECTION_ATTEMPTS { let vsocket = VsockSocket::new( socket( AddressFamily::Vsock, SockType::Stream, SockFlag::empty(), None, ) .map_err(|err| format!("Failed to create the socket: {:?}", err))?, ); match connect(vsocket.as_raw_fd(), &sockaddr) { Ok(_) => return Ok(vsocket), Err(e) => err_msg = format!("Failed to connect: {}", e), } std::thread::sleep(std::time::Duration::from_secs(1 << i)); } Err(err_msg) } fn run_server(fd: RawFd, no_wait: bool) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let command = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let command_output = if no_wait { #[rustfmt::skip] let output = Command::new("sh") .arg("-c") .arg(command) .spawn(); if output.is_err() { CommandOutput::new( String::new(), format!("Could not execute the command {}", command), 1, ) } else { CommandOutput::new(String::new(), String::new(), 0) } } else { let output = Command::new("sh") .arg("-c") .arg(command) .output() .map_err(|err| format!("Could not execute the command {}: {:?}", command, err))?; CommandOutput::new_from(output)? }; let json_output = serde_json::to_string(&command_output) .map_err(|err| format!("Could not serialize the output: {:?}", err))?; let buf = json_output.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(fd, len)?; send_loop(fd, &buf, len)?; Ok(()) } fn recv_file_server(fd: RawFd) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let path = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let mut file = File::open(path).map_err(|err| format!("Could not open file {:?}", err))?; let filesize = file .metadata() .map_err(|err| format!("Could not get file metadata {:?}", err))? .len(); send_u64(fd, filesize)?; println!("Sending file {} - size {}", path, filesize); let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); file.read_exact(&mut buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not read {:?}", err))?; send_loop(fd, &buf, tmpsize)?; progress += tmpsize } Ok(()) } fn send_file_server(fd: RawFd) -> Result<(), String> { let len = recv_u64(fd)?; let mut buf = [0u8; BUF_MAX_LEN]; recv_loop(fd, &mut buf, len)?; let len_usize = len.try_into().map_err(|err| format!("{:?}", err))?; let path = std::str::from_utf8(&buf[0..len_usize]).map_err(|err| format!("{:?}", err))?; let mut file = File::create(path).map_err(|err| format!("Could not open file {:?}", err))?; let filesize = recv_u64(fd)?; println!("Receiving file {} - size {}", path, filesize); let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); recv_loop(fd, &mut buf, tmpsize)?; file.write_all(&buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not write {:?}", err))?; progress += tmpsize } Ok(()) } pub fn listen(args: ListenArgs) -> Result<(), String> { let socket_fd = socket( AddressFamily::Vsock, SockType::Stream, SockFlag::empty(), None, ) .map_err(|err| format!("Create socket failed: {:?}", err))?; let sockaddr = SockAddr::new_vsock(VMADDR_CID_ANY, args.port); bind(socket_fd, &sockaddr).map_err(|err| format!("Bind failed: {:?}", err))?; listen_vsock(socket_fd, BACKLOG).map_err(|err| format!("Listen failed: {:?}", err))?; loop { let fd = accept(socket_fd).map_err(|err| format!("Accept failed: {:?}", err))?; let cmdid = match recv_u64(fd) { Ok(id_u64) => match CmdId::from_u64(id_u64) { Some(c) => c, _ => { eprintln!("Error no such command"); continue; } }, Err(e) => { eprintln!("Error {}", e); continue; } }; match cmdid { CmdId::RunCmd => { if let Err(e) = run_server(fd, false) { eprintln!("Error {}", e); } } CmdId::RecvFile => { if let Err(e) = recv_file_server(fd) { eprintln!("Error {}", e); } } CmdId::SendFile => { if let Err(e) = send_file_server(fd) { eprintln!("Error {}", e); } } CmdId::RunCmdNoWait => { if let Err(e) = run_server(fd, true) { eprintln!("Error {}", e); } } } } } pub fn run(args: RunArgs) -> Result<i32, String> { let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); if args.no_wait { send_u64(socket_fd, CmdId::RunCmdNoWait as u64)?; } else { send_u64(socket_fd, CmdId::RunCmd as u64)?; } let buf = args.command.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let mut buf = [0u8; BUF_MAX_LEN]; let len = recv_u64(socket_fd)?; let mut json_output = String::new(); let mut to_recv = len; while to_recv > 0 { let recv_len = min(BUF_MAX_LEN as u64, to_recv); recv_loop(socket_fd, &mut buf, recv_len)?; to_recv -= recv_len; let to_recv_usize: usize = recv_len.try_into().map_err(|err| format!("{:?}", err))?; json_output.push_str( std::str::from_utf8(&buf[0..to_recv_usize]).map_err(|err| format!("{:?}", err))?, ); } let output: CommandOutput = serde_json::from_str(json_output.as_str()) .map_err(|err| format!("Could not deserialize the output: {:?}", err))?; print!("{}", output.stdout); eprint!("{}", output.stderr); let rc = match output.rc { Some(code) => code, _ => 0, }; Ok(rc) } pub fn recv_file(args: FileArgs) -> Result<(), String> { let mut file = File::create(&args.localfile) .map_err(|err| format!("Could not open localfile {:?}", err))?; let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); send_u64(socket_fd, CmdId::RecvFile as u64)?; let buf = args.remotefile.as_bytes(); let len: u64 = buf.len().try_into().map_err(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let filesize = recv_u64(socket_fd)?; println!( "Receiving file {}(saving to {}) - size {}", &args.remotefile, &args.localfile[..], filesize ); let mut progress: u64 = 0; let mut tmpsize: u64; let mut buf = [0u8; BUF_MAX_LEN]; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); recv_loop(socket_fd, &mut buf, tmpsize)?; file.write_all(&buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could n
r(|err| format!("{:?}", err))?; send_u64(socket_fd, len)?; send_loop(socket_fd, &buf, len)?; let filesize = file .metadata() .map_err(|err| format!("Could not get file metadate {:?}", err))? .len(); send_u64(socket_fd, filesize)?; println!( "Sending file {}(sending to {}) - size {}", &args.localfile, &args.remotefile[..], filesize ); let mut buf = [0u8; BUF_MAX_LEN]; let mut progress: u64 = 0; let mut tmpsize: u64; while progress < filesize { tmpsize = buf.len().try_into().map_err(|err| format!("{:?}", err))?; tmpsize = min(tmpsize, filesize - progress); file.read_exact(&mut buf[..tmpsize.try_into().map_err(|err| format!("{:?}", err))?]) .map_err(|err| format!("Could not read {:?}", err))?; send_loop(socket_fd, &buf, tmpsize)?; progress += tmpsize } Ok(()) }
ot write {:?}", err))?; progress += tmpsize } Ok(()) } pub fn send_file(args: FileArgs) -> Result<(), String> { let mut file = File::open(&args.localfile).map_err(|err| format!("Could not open localfile {:?}", err))?; let vsocket = vsock_connect(args.cid, args.port)?; let socket_fd = vsocket.as_raw_fd(); send_u64(socket_fd, CmdId::SendFile as u64)?; let buf = args.remotefile.as_bytes(); let len: u64 = buf.len().try_into().map_er
random
[ { "content": "pub fn recv_loop(fd: RawFd, buf: &mut [u8], len: u64) -> Result<(), String> {\n\n let len: usize = len.try_into().map_err(|err| format!(\"{:?}\", err))?;\n\n let mut recv_bytes = 0;\n\n\n\n while recv_bytes < len {\n\n let size = match recv(fd, &mut buf[recv_bytes..len], MsgFlags::...
Rust
src/test/spec/unified_runner/mod.rs
awitten1/mongo-rust-driver
5a0192cf1ba11d9e44c453e14f90d32231689166
mod entity; mod matcher; mod operation; mod test_event; mod test_file; mod test_runner; use std::{convert::TryFrom, ffi::OsStr, fs::read_dir, path::PathBuf, time::Duration}; use futures::{future::FutureExt, stream::TryStreamExt}; use semver::Version; use tokio::sync::RwLockWriteGuard; use crate::{ bson::{doc, Document}, options::{CollectionOptions, FindOptions, ReadConcern, ReadPreference, SelectionCriteria}, test::{run_single_test, run_spec_test, LOCK}, RUNTIME, }; pub use self::{ entity::{ClientEntity, Entity, FindCursor, SessionEntity}, matcher::{events_match, results_match}, operation::{Operation, OperationObject}, test_event::{ExpectedCmapEvent, ExpectedCommandEvent, ExpectedEvent, ObserveEvent}, test_file::{ merge_uri_options, CollectionData, ExpectError, ExpectedEventType, TestFile, TestFileEntity, Topology, }, test_runner::{EntityMap, TestRunner}, }; use self::operation::Expectation; static SPEC_VERSIONS: &[Version] = &[ Version::new(1, 0, 0), Version::new(1, 1, 0), Version::new(1, 4, 0), Version::new(1, 5, 0), ]; const SKIPPED_OPERATIONS: &[&str] = &[ "bulkWrite", "count", "download", "download_by_name", "listCollectionObjects", "listDatabaseObjects", "mapReduce", "watch", ]; pub async fn run_unified_format_test(test_file: TestFile) { let version_matches = SPEC_VERSIONS.iter().any(|req| { if req.major != test_file.schema_version.major { return false; } if req.minor < test_file.schema_version.minor { return false; } true }); if !version_matches { panic!( "Test runner not compatible with specification version {}", &test_file.schema_version ); } let mut test_runner = TestRunner::new().await; if let Some(requirements) = test_file.run_on_requirements { let mut can_run_on = false; for requirement in requirements { if requirement.can_run_on(&test_runner.internal_client).await { can_run_on = true; } } if !can_run_on { println!("Client topology not compatible with test"); return; } } for test_case in test_file.tests { if let Some(skip_reason) = test_case.skip_reason { println!("Skipping {}: {}", &test_case.description, skip_reason); continue; } if test_case .operations .iter() .any(|op| SKIPPED_OPERATIONS.contains(&op.name.as_str())) { println!("Skipping {}", &test_case.description); continue; } println!("Running {}", &test_case.description); if let Some(requirements) = test_case.run_on_requirements { let mut can_run_on = false; for requirement in requirements { if requirement.can_run_on(&test_runner.internal_client).await { can_run_on = true; } } if !can_run_on { println!( "{}: client topology not compatible with test", &test_case.description ); return; } } if let Some(ref initial_data) = test_file.initial_data { for data in initial_data { test_runner.insert_initial_data(data).await; } } if let Some(ref create_entities) = test_file.create_entities { test_runner.populate_entity_map(create_entities).await; } for operation in test_case.operations { match operation.object { OperationObject::TestRunner => { operation .execute_test_runner_operation(&mut test_runner) .await; } OperationObject::Entity(ref id) => { let result = operation .execute_entity_operation(id, &mut test_runner) .await; match &operation.expectation { Expectation::Result { expected_value, save_as_entity, } => { let opt_entity = result.unwrap_or_else(|e| { panic!( "{} should succeed, but failed with the following error: {}", operation.name, e ) }); if expected_value.is_some() || save_as_entity.is_some() { let entity = opt_entity.unwrap_or_else(|| { panic!("{} did not return an entity", operation.name) }); if let Some(expected_bson) = expected_value { if let Entity::Bson(actual) = &entity { assert!( results_match( Some(actual), expected_bson, operation.returns_root_documents(), Some(&test_runner.entities), ), "result mismatch, expected = {:#?} actual = {:#?}", expected_bson, actual, ); } else { panic!( "Incorrect entity type returned from {}, expected BSON", operation.name ); } } if let Some(id) = save_as_entity { if test_runner.entities.insert(id.clone(), entity).is_some() { panic!( "Entity with id {} already present in entity map", id ); } } } } Expectation::Error(expect_error) => { let error = result .expect_err(&format!("{} should return an error", operation.name)); expect_error.verify_result(error); } Expectation::Ignore => (), } } } if test_case.description == "Server supports implicit sessions" { RUNTIME.delay_for(Duration::from_secs(1)).await; } } test_runner.fail_point_guards.clear(); if let Some(ref events) = test_case.expect_events { for expected in events { let entity = test_runner.entities.get(&expected.client).unwrap(); let client = entity.as_client(); client.sync_workers().await; let event_type = expected .event_type .unwrap_or(test_file::ExpectedEventType::Command); let actual_events: Vec<ExpectedEvent> = client .get_filtered_events(event_type) .into_iter() .map(Into::into) .collect(); let expected_events = &expected.events; assert_eq!( actual_events.len(), expected_events.len(), "actual:\n{:#?}\nexpected:\n{:#?}", actual_events, expected_events ); for (actual, expected) in actual_events.iter().zip(expected_events) { assert!( events_match(actual, expected, Some(&test_runner.entities)), "event mismatch: expected = {:#?}, actual = {:#?}", expected, actual, ); } } } if let Some(ref outcome) = test_case.outcome { for expected_data in outcome { let db_name = &expected_data.database_name; let coll_name = &expected_data.collection_name; let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let read_concern = ReadConcern::local(); let options = CollectionOptions::builder() .selection_criteria(selection_criteria) .read_concern(read_concern) .build(); let collection = test_runner .internal_client .get_coll_with_options(db_name, coll_name, options); let options = FindOptions::builder().sort(doc! { "_id": 1 }).build(); let actual_data: Vec<Document> = collection .find(doc! {}, options) .await .unwrap() .try_collect() .await .unwrap(); assert_eq!(expected_data.documents, actual_data); } } println!("{} succeeded", &test_case.description); } } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn test_examples() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; run_spec_test( &["unified-test-format", "examples"], run_unified_format_test, ) .await; } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn valid_fail() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; let path: PathBuf = [ env!("CARGO_MANIFEST_DIR"), "src", "test", "spec", "json", "unified-test-format", "valid-fail", ] .iter() .collect(); for entry in read_dir(&path).unwrap() { let test_file_path = PathBuf::from(entry.unwrap().file_name()); let path = path.join(&test_file_path); let path_display = path.display().to_string(); std::panic::AssertUnwindSafe(run_single_test(path, &run_unified_format_test)) .catch_unwind() .await .expect_err(&format!("tests from {} should have failed", path_display)); } } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn valid_pass() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; run_spec_test( &["unified-test-format", "valid-pass"], run_unified_format_test, ) .await; } const SKIPPED_INVALID_TESTS: &[&str] = &[ "expectedEventsForClient-events_conflicts_with_cmap_eventType.json", "expectedEventsForClient-events_conflicts_with_command_eventType.json", "expectedEventsForClient-events_conflicts_with_default_eventType.json", ]; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn invalid() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; let path: PathBuf = [ env!("CARGO_MANIFEST_DIR"), "src", "test", "spec", "json", "unified-test-format", "invalid", ] .iter() .collect(); for entry in read_dir(&path).unwrap() { let test_file = entry.unwrap(); if !test_file.file_type().unwrap().is_file() { continue; } let test_file_path = PathBuf::from(test_file.file_name()); if test_file_path.extension().and_then(OsStr::to_str) != Some("json") { continue; } let test_file_str = test_file_path.as_os_str().to_str().unwrap(); if SKIPPED_INVALID_TESTS .iter() .any(|skip| *skip == test_file_str) { println!("Skipping {}", test_file_str); continue; } let path = path.join(&test_file_path); let path_display = path.display().to_string(); let json: serde_json::Value = serde_json::from_reader(std::fs::File::open(path.as_path()).unwrap()).unwrap(); let result: Result<TestFile, _> = bson::from_bson( bson::Bson::try_from(json).unwrap_or_else(|_| panic!("{}", path_display)), ); if let Ok(test_file) = result { panic!( "{}: should be invalid, parsed to:\n{:#?}", path_display, test_file ); } } }
mod entity; mod matcher; mod operation; mod test_event; mod test_file; mod test_runner; use std::{convert::TryFrom, ffi::OsStr, fs::read_dir, path::PathBuf, time::Duration}; use futures::{future::FutureExt, stream::TryStreamExt}; use semver::Version; use tokio::sync::RwLockWriteGuard; use crate::{ bson::{doc, Document}, options::{CollectionOptions, FindOptions, ReadConcern, ReadPreference, SelectionCriteria}, test::{run_single_test, run_spec_test, LOCK}, RUNTIME, }; pub use self::{ entity::{ClientEntity, Entity, FindCursor, SessionEntity}, matcher::{events_match, results_match}, operation::{Operation, OperationObject}, test_event::{ExpectedCmapEvent, ExpectedCommandEvent, ExpectedEvent, ObserveEvent}, test_file::{ merge_uri_options, CollectionData, ExpectError, ExpectedEventType, TestFile, TestFileEntity, Topology, }, test_runner::{EntityMap, TestRunner}, }; use self::operation::Expectation; static SPEC_VERSIONS: &[Version] = &[ Version::new(1, 0, 0), Version::new(1, 1, 0), Version::new(1, 4, 0), Version::new(1, 5, 0), ]; const SKIPPED_OPERATIONS: &[&str] = &[ "bulkWrite", "count", "download", "download_by_name", "listCollectionObjects", "listDatabaseObjects", "mapReduce", "watch", ]; pub async fn run_unified_format_test(test_file: TestFile) { let version_matches = SPEC_VERSIONS.iter().any(|req| { if req.major != test_file.schema_version.major { return false; } if req.minor < test_file.schema_version.minor { return false; } true }); if !version_matches { panic!( "Test runner not compatible with specification version {}", &test_file.schema_version ); } let mut test_runner = TestRunner::new().await; if let Some(requirements) = test_file.run_on_requirements { let mut can_run_on = false; for requirement in requirements { if requirement.can_run_on(&test_runner.internal_client).await { can_run_on = true; } } if !can_run_on { println!("Client topology not compatible with test"); return; } } for test_case in test_file.tests { if let Some(skip_reason) = test_case.skip_reason { println!("Skipping {}: {}", &test_case.description, skip_reason); continue; } if test_case .operations .iter() .any(|op| SKIPPED_OPERATIONS.contains(&op.name.as_str())) { println!("Skipping {}", &test_case.description); continue; } println!("Running {}", &test_case.description); if let Some(requirements) = test_case.run_on_requirements { let mut can_run_on = false; for requirement in requirements { if requirement.can_run_on(&test_runner.internal_client).await { can_run_on = true; } } if !can_run_on { println!( "{}: client topology not compatible with test", &test_case.description ); return; } } if let Some(ref initial_data) = test_file.initial_data { for data in initial_data { test_runner.insert_initial_data(data).await; } } if let Some(ref create_entities) = test_file.create_entities { test_runner.populate_entity_map(create_entities).await; } for operation in test_case.operations { match operation.object { OperationObject::TestRunner => { operation .execute_test_runner_operation(&mut test_runner) .await; } OperationObject::Entity(ref id) => { let result = operation .execute_entity_operation(id, &mut test_runner) .await; match &operation.expectation { Expectation::Result { expected_value, save_as_entity, } => { let opt_entity = result.unwrap_or_else(|e| { panic!( "{} should succeed, but failed with the following error: {}", operation.name, e ) }); if expected_value.is_some() || save_as_entity.is_some() { let entity = opt_entity.unwrap_or_else(|| { panic!("{} did not return an entity", operation.name) }); if let Some(expected_bson) = expected_value { if let Entity::Bson(actual) = &entity { assert!( results_match( Some(actual), expected_bson, operation.returns_root_documents(), Some(&test_runner.entities), ), "result mismatch, expected = {:#?} actual = {:#?}", expected_bson, actual, ); } else { panic!( "Incorrect entity type returned from {}, expected BSON", operation.name ); } } if let Some(id) = save_as_entity { if test_runner.entities.insert(id.clone(), entity).is_some() { panic!( "Entity with id {} already present in entity map", id ); } } } } Expectation::Error(expect_error) => { let error = result .expect_err(&format!("{} should return an error", operation.name)); expect_error.verify_result(error); } Expectation::Ignore => (), } } } if test_case.description == "Server supports implicit sessions" { RUNTIME.delay_for(Duration::from_secs(1)).await; } } test_runner.fail_point_guards.clear(); if let Some(ref events) = test_case.expect_events { for expected in events { let entity = test_runner.entities.get(&expected.client).unwrap(); let client = entity.as_client(); client.sync_workers().await; let event_type = expected .event_type .unwrap_or(test_file::ExpectedEventType::Command); let actual_events: Vec<ExpectedEvent> = client .get_filtered_events(event_type) .into_iter() .map(Into::into) .collect(); let expected_events = &expected.events; assert_eq!( actual_events.len(), expected_events.len(), "actual:\n{:#?}\nexpected:\n{:#?}", actual_events, expected_events ); for (actual, expected) in actual_events.iter().zip(expected_events) { assert!( events_match(actual, expected, Some(&test_runner.entities)), "event mismatch: expected = {:#?}, actual = {:#?}", expected, actual, ); } } } if let Some(ref outcome) = test_case.outcome { for expected_data in outcome { let db_name = &expected_data.database_name; let coll_name = &expected_data.collection_name; let selection_criteria = SelectionCriteria::ReadPreference(ReadPreference::Primary); let read_concern = ReadConcern::local(); let options = CollectionOptions::builder() .selection_criteria(selection_criteria) .read_concern(read_concern) .build(); let collection = test_runner .internal_client .get_coll_with_options(db_name, coll_name, options); let options = FindOptions::builder().sort(doc! { "_id": 1 }).build(); let actual_data: Vec<Document> = collection .find(doc! {}, options) .await .unwrap() .try_collect() .await .unwrap(); assert_eq!(expected_data.documents, actual_data); } } println!("{} succeeded", &test_case.description); } } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn test_examples() { let _guar
#[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn valid_fail() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; let path: PathBuf = [ env!("CARGO_MANIFEST_DIR"), "src", "test", "spec", "json", "unified-test-format", "valid-fail", ] .iter() .collect(); for entry in read_dir(&path).unwrap() { let test_file_path = PathBuf::from(entry.unwrap().file_name()); let path = path.join(&test_file_path); let path_display = path.display().to_string(); std::panic::AssertUnwindSafe(run_single_test(path, &run_unified_format_test)) .catch_unwind() .await .expect_err(&format!("tests from {} should have failed", path_display)); } } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn valid_pass() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; run_spec_test( &["unified-test-format", "valid-pass"], run_unified_format_test, ) .await; } const SKIPPED_INVALID_TESTS: &[&str] = &[ "expectedEventsForClient-events_conflicts_with_cmap_eventType.json", "expectedEventsForClient-events_conflicts_with_command_eventType.json", "expectedEventsForClient-events_conflicts_with_default_eventType.json", ]; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn invalid() { let _guard: RwLockWriteGuard<_> = LOCK.run_exclusively().await; let path: PathBuf = [ env!("CARGO_MANIFEST_DIR"), "src", "test", "spec", "json", "unified-test-format", "invalid", ] .iter() .collect(); for entry in read_dir(&path).unwrap() { let test_file = entry.unwrap(); if !test_file.file_type().unwrap().is_file() { continue; } let test_file_path = PathBuf::from(test_file.file_name()); if test_file_path.extension().and_then(OsStr::to_str) != Some("json") { continue; } let test_file_str = test_file_path.as_os_str().to_str().unwrap(); if SKIPPED_INVALID_TESTS .iter() .any(|skip| *skip == test_file_str) { println!("Skipping {}", test_file_str); continue; } let path = path.join(&test_file_path); let path_display = path.display().to_string(); let json: serde_json::Value = serde_json::from_reader(std::fs::File::open(path.as_path()).unwrap()).unwrap(); let result: Result<TestFile, _> = bson::from_bson( bson::Bson::try_from(json).unwrap_or_else(|_| panic!("{}", path_display)), ); if let Ok(test_file) = result { panic!( "{}: should be invalid, parsed to:\n{:#?}", path_display, test_file ); } } }
d: RwLockWriteGuard<_> = LOCK.run_exclusively().await; run_spec_test( &["unified-test-format", "examples"], run_unified_format_test, ) .await; }
function_block-function_prefixed
[ { "content": "fn entity_matches(id: &str, actual: Option<&Bson>, entities: &EntityMap) -> bool {\n\n let bson = entities.get(id).unwrap().as_bson();\n\n results_match_inner(actual, bson, false, false, Some(entities))\n\n}\n\n\n", "file_path": "src/test/spec/unified_runner/matcher.rs", "rank": 0, ...
Rust
src/cache/file_manager.rs
cloudfuse-io/cloud-readers-rs
498ae2e6bbcdc170659bb76d428e5135f8041724
use std::collections::BTreeMap; use std::fmt; use std::sync::{Arc, Condvar, Mutex}; use anyhow::{anyhow, bail, ensure, Result}; use itertools::Itertools; use tokio::sync::mpsc::UnboundedSender; use super::Range; #[derive(Clone)] pub(crate) enum Download { Pending(usize), Done(Arc<Vec<u8>>), Error(String), } impl fmt::Debug for Download { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Download::Pending(len) => write!(f, "Pending({} bytes)", len), Download::Done(data) => write!(f, "Done({} bytes)", data.len()), Download::Error(error) => write!(f, "Error({:?})", error), } } } pub(crate) struct RangeCursor { data: Arc<Vec<u8>>, offset: u64, } impl fmt::Debug for RangeCursor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RangeCursor") .field("data", &format!("vec![x;{}]", self.data.len())) .field("offset", &self.offset) .finish() } } impl RangeCursor { fn try_new(data: Arc<Vec<u8>>, offset: u64) -> Result<Self> { ensure!( data.len() > offset as usize, "Out of bound in RangeCursor: (offset={}) >= (length={})", offset, data.len(), ); Ok(Self { data, offset }) } pub(crate) fn read(self, buf: &mut [u8]) -> usize { let len = std::cmp::min(buf.len(), self.data.len() - self.offset as usize); buf[0..len] .clone_from_slice(&self.data[self.offset as usize..(self.offset as usize + len)]); len } } #[derive(Clone)] pub(crate) struct FileCache { ranges: Arc<Mutex<BTreeMap<u64, Download>>>, cv: Arc<Condvar>, file_size: u64, } fn fmt_debug(map: &BTreeMap<u64, Download>) -> String { map.iter() .map(|(pos, dl)| format!("-- Start={:0>10} Status={:?}", pos, dl)) .join("\n") } impl fmt::Debug for FileCache { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let range_guard = self.ranges.lock().unwrap(); write!(f, "{}", fmt_debug(&*range_guard)) } } impl FileCache { pub(crate) fn new(file_size: u64) -> Self { Self { ranges: Arc::new(Mutex::new(BTreeMap::new())), cv: Arc::new(Condvar::new()), file_size, } } pub(crate) fn insert(&self, start: u64, download: Download) { let mut range_guard = self.ranges.lock().unwrap(); range_guard.insert(start, download); self.cv.notify_all() } fn get_range(&self, start: u64) -> Result<RangeCursor> { use std::ops::Bound::{Included, Unbounded}; let mut ranges_guard = self.ranges.lock().unwrap(); ensure!(ranges_guard.len() > 0, "No download scheduled"); let mut before = ranges_guard .range((Unbounded, Included(start))) .next_back() .map(|(start, dl)| (*start, dl.clone())); while let Some((_, Download::Pending(_))) = before { ranges_guard = self.cv.wait(ranges_guard).unwrap(); before = ranges_guard .range((Unbounded, Included(start))) .next_back() .map(|(start, dl)| (*start, dl.clone())); } let before = before.ok_or_else(|| { anyhow!( "Download not scheduled at position {}, scheduled ranges are:\n{}", start, fmt_debug(&*ranges_guard), ) })?; match before.1 { Download::Done(bytes) => { ensure!( before.0 + bytes.len() as u64 > start, "Download not scheduled at position {}, scheduled ranges are:\n{}", start, fmt_debug(&*ranges_guard), ); RangeCursor::try_new(bytes, start - before.0) } Download::Error(err) => bail!(err), Download::Pending(_) => unreachable!(), } } } #[derive(Clone)] pub struct FileManager { cache: FileCache, tx: UnboundedSender<Range>, } impl FileManager { pub(crate) fn new(cache: FileCache, tx: UnboundedSender<Range>) -> Self { Self { cache, tx } } pub fn queue_download(&self, ranges: Vec<Range>) -> Result<()> { for range in ranges { self.cache .insert(range.start, Download::Pending(range.length)); self.tx.send(range).map_err(|e| anyhow!(e.to_string()))?; } Ok(()) } pub(crate) fn get_range(&self, start: u64) -> Result<RangeCursor> { self.cache.get_range(start) } pub fn get_file_size(&self) -> u64 { self.cache.file_size } } #[cfg(test)] mod tests { use super::super::mock::*; use super::super::DownloadCache; use super::*; #[tokio::test] async fn test_read_at_0() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); assert_cursor(file_manager, 0, pattern(0, 100)) .await .expect("Could not get range at 0 with download of [0:100["); } #[tokio::test] async fn test_read_with_offset() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); assert_cursor(file_manager, 50, pattern(50, 100)) .await .expect("Could not get range at 50 with download of [0:100["); } #[tokio::test] async fn test_read_uninited() { let file_manager = init_mock(1000).await; let err_msg = assert_cursor(file_manager, 0, pattern(0, 100)) .await .expect_err("Read file without queued downloads should fail") .to_string(); assert_eq!(err_msg, "No download scheduled"); } #[tokio::test] async fn test_read_outside_download() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); let err_msg = assert_cursor(file_manager, 120, pattern(120, 200)) .await .expect_err("Read file without scheduled downloads should fail") .to_string(); assert_eq!( err_msg, "\ Download not scheduled at position 120, scheduled ranges are: -- Start=0000000000 Status=Done(100 bytes)" ); } #[tokio::test] async fn test_read_error_downloader() { let mut download_cache = DownloadCache::new(1); let file_manager = download_cache .register(Box::new(ErrorFileDescription {})) .await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); let error = tokio::task::spawn_blocking(move || -> Result<RangeCursor> { file_manager.get_range(0) }) .await .unwrap() .unwrap_err(); assert_eq!( format!("{:?}", error), "Error in ErrorDownloader\n\nCaused by:\n Download Failed" ); } async fn init_mock(len: u64) -> FileManager { let mut download_cache = DownloadCache::new(1); let pattern_file_description = PatternFileDescription::new(len); download_cache .register(Box::new(pattern_file_description)) .await } async fn assert_cursor(file_manager: FileManager, start: u64, target: Vec<u8>) -> Result<()> { let target_length = target.len(); let cursor = tokio::task::spawn_blocking(move || -> Result<RangeCursor> { file_manager.get_range(start) }) .await .unwrap()?; let mut content = vec![0u8; target_length]; cursor.read(&mut content); assert_eq!(content, target); Ok(()) } }
use std::collections::BTreeMap; use std::fmt; use std::sync::{Arc, Condvar, Mutex}; use anyhow::{anyhow, bail, ensure, Result}; use itertools::Itertools; use tokio::sync::mpsc::UnboundedSender; use super::Range; #[derive(Clone)] pub(crate) enum Download { Pending(usize), Done(Arc<Vec<u8>>), Error(String), } impl fmt::Debug for Download { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Download::Pending(len) => write!(f, "Pending({} bytes)", len), Download::Done(data) => write!(f, "Done({} bytes)", data.len()), Download::Error(error) => write!(f, "Error({:?})", error), } } } pub(crate) struct RangeCursor { data: Arc<Vec<u8>>, offset: u64, } impl fmt::Debug for RangeCursor { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("RangeCursor") .field("data", &format!("vec![x;{}]", self.data.len())) .field("offset", &self.offset) .finish() } } impl RangeCursor { fn try_new(data: Arc<Vec<u8>>, offse
pub(crate) fn read(self, buf: &mut [u8]) -> usize { let len = std::cmp::min(buf.len(), self.data.len() - self.offset as usize); buf[0..len] .clone_from_slice(&self.data[self.offset as usize..(self.offset as usize + len)]); len } } #[derive(Clone)] pub(crate) struct FileCache { ranges: Arc<Mutex<BTreeMap<u64, Download>>>, cv: Arc<Condvar>, file_size: u64, } fn fmt_debug(map: &BTreeMap<u64, Download>) -> String { map.iter() .map(|(pos, dl)| format!("-- Start={:0>10} Status={:?}", pos, dl)) .join("\n") } impl fmt::Debug for FileCache { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let range_guard = self.ranges.lock().unwrap(); write!(f, "{}", fmt_debug(&*range_guard)) } } impl FileCache { pub(crate) fn new(file_size: u64) -> Self { Self { ranges: Arc::new(Mutex::new(BTreeMap::new())), cv: Arc::new(Condvar::new()), file_size, } } pub(crate) fn insert(&self, start: u64, download: Download) { let mut range_guard = self.ranges.lock().unwrap(); range_guard.insert(start, download); self.cv.notify_all() } fn get_range(&self, start: u64) -> Result<RangeCursor> { use std::ops::Bound::{Included, Unbounded}; let mut ranges_guard = self.ranges.lock().unwrap(); ensure!(ranges_guard.len() > 0, "No download scheduled"); let mut before = ranges_guard .range((Unbounded, Included(start))) .next_back() .map(|(start, dl)| (*start, dl.clone())); while let Some((_, Download::Pending(_))) = before { ranges_guard = self.cv.wait(ranges_guard).unwrap(); before = ranges_guard .range((Unbounded, Included(start))) .next_back() .map(|(start, dl)| (*start, dl.clone())); } let before = before.ok_or_else(|| { anyhow!( "Download not scheduled at position {}, scheduled ranges are:\n{}", start, fmt_debug(&*ranges_guard), ) })?; match before.1 { Download::Done(bytes) => { ensure!( before.0 + bytes.len() as u64 > start, "Download not scheduled at position {}, scheduled ranges are:\n{}", start, fmt_debug(&*ranges_guard), ); RangeCursor::try_new(bytes, start - before.0) } Download::Error(err) => bail!(err), Download::Pending(_) => unreachable!(), } } } #[derive(Clone)] pub struct FileManager { cache: FileCache, tx: UnboundedSender<Range>, } impl FileManager { pub(crate) fn new(cache: FileCache, tx: UnboundedSender<Range>) -> Self { Self { cache, tx } } pub fn queue_download(&self, ranges: Vec<Range>) -> Result<()> { for range in ranges { self.cache .insert(range.start, Download::Pending(range.length)); self.tx.send(range).map_err(|e| anyhow!(e.to_string()))?; } Ok(()) } pub(crate) fn get_range(&self, start: u64) -> Result<RangeCursor> { self.cache.get_range(start) } pub fn get_file_size(&self) -> u64 { self.cache.file_size } } #[cfg(test)] mod tests { use super::super::mock::*; use super::super::DownloadCache; use super::*; #[tokio::test] async fn test_read_at_0() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); assert_cursor(file_manager, 0, pattern(0, 100)) .await .expect("Could not get range at 0 with download of [0:100["); } #[tokio::test] async fn test_read_with_offset() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); assert_cursor(file_manager, 50, pattern(50, 100)) .await .expect("Could not get range at 50 with download of [0:100["); } #[tokio::test] async fn test_read_uninited() { let file_manager = init_mock(1000).await; let err_msg = assert_cursor(file_manager, 0, pattern(0, 100)) .await .expect_err("Read file without queued downloads should fail") .to_string(); assert_eq!(err_msg, "No download scheduled"); } #[tokio::test] async fn test_read_outside_download() { let file_manager = init_mock(1000).await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); let err_msg = assert_cursor(file_manager, 120, pattern(120, 200)) .await .expect_err("Read file without scheduled downloads should fail") .to_string(); assert_eq!( err_msg, "\ Download not scheduled at position 120, scheduled ranges are: -- Start=0000000000 Status=Done(100 bytes)" ); } #[tokio::test] async fn test_read_error_downloader() { let mut download_cache = DownloadCache::new(1); let file_manager = download_cache .register(Box::new(ErrorFileDescription {})) .await; file_manager .queue_download(vec![Range { start: 0, length: 100, }]) .expect("Could not queue Range on handle"); let error = tokio::task::spawn_blocking(move || -> Result<RangeCursor> { file_manager.get_range(0) }) .await .unwrap() .unwrap_err(); assert_eq!( format!("{:?}", error), "Error in ErrorDownloader\n\nCaused by:\n Download Failed" ); } async fn init_mock(len: u64) -> FileManager { let mut download_cache = DownloadCache::new(1); let pattern_file_description = PatternFileDescription::new(len); download_cache .register(Box::new(pattern_file_description)) .await } async fn assert_cursor(file_manager: FileManager, start: u64, target: Vec<u8>) -> Result<()> { let target_length = target.len(); let cursor = tokio::task::spawn_blocking(move || -> Result<RangeCursor> { file_manager.get_range(start) }) .await .unwrap()?; let mut content = vec![0u8; target_length]; cursor.read(&mut content); assert_eq!(content, target); Ok(()) } }
t: u64) -> Result<Self> { ensure!( data.len() > offset as usize, "Out of bound in RangeCursor: (offset={}) >= (length={})", offset, data.len(), ); Ok(Self { data, offset }) }
function_block-function_prefixed
[ { "content": "/// A downloader that always returns an error\n\nstruct ErrorDownloader;\n\n\n\n#[async_trait]\n\nimpl Downloader for ErrorDownloader {\n\n async fn download(&self, _file: String, _start: u64, _length: usize) -> Result<Vec<u8>> {\n\n Err(anyhow!(\"Download Failed\").context(\"Error in Er...
Rust
src/asset/tileset.rs
B-Reif/bevy_asefile
51d8abfc51aa9e406dad2e5cad4b93c22e7b3fc6
use asefile::{AsepriteFile, TilesetImageError}; use bevy::{ prelude::*, reflect::TypeUuid, render::texture::{Extent3d, TextureDimension, TextureFormat}, }; use std::fmt; pub(crate) type TilesetResult<T> = std::result::Result<T, TilesetError>; #[derive(Debug)] pub enum TilesetError { MissingId(asefile::TilesetId), NoPixels(asefile::TilesetId), } impl fmt::Display for TilesetError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TilesetError::MissingId(tileset_id) => { write!(f, "No tileset found with id: {}", tileset_id) } TilesetError::NoPixels(tileset_id) => { write!(f, "No pixel data for tileset with id: {}", tileset_id) } } } } impl From<&TilesetImageError> for TilesetError { fn from(e: &TilesetImageError) -> Self { match e { TilesetImageError::MissingTilesetId(id) => Self::MissingId(*id), TilesetImageError::NoPixelsInTileset(id) => Self::NoPixels(*id), } } } impl From<TilesetImageError> for TilesetError { fn from(e: TilesetImageError) -> Self { Self::from(&e) } } fn texture_from(ase: &AsepriteFile, tileset: &asefile::Tileset) -> TilesetResult<Texture> { let tileset_id = tileset.id(); let image = ase.tileset_image(&tileset_id)?; let size = Extent3d { width: image.width(), height: image.height(), depth: 1, }; Ok(Texture::new_fill( size, TextureDimension::D2, image.as_raw(), TextureFormat::Rgba8UnormSrgb, )) } #[derive(Debug)] pub struct TileSize { pub width: u16, pub height: u16, } impl TileSize { fn from_ase(ase_size: &asefile::TileSize) -> Self { Self { width: *ase_size.width(), height: *ase_size.height(), } } } #[derive(Debug, TypeUuid)] #[uuid = "0e2dbd05-dbad-46c9-a943-395f83dfa4ba"] pub struct Tileset { pub tile_count: u32, pub tile_size: TileSize, pub name: String, pub texture: Handle<Texture>, } impl Tileset { pub fn texture_size(&self) -> Vec2 { let TileSize { width, height } = self.tile_size; let tile_count = self.tile_count as f32; Vec2::new(width as f32, height as f32 * tile_count) } } #[derive(Debug)] pub(crate) struct TilesetData<T> { pub(crate) tile_count: u32, pub(crate) tile_size: TileSize, pub(crate) name: String, pub(crate) texture: T, } impl<T> TilesetData<T> { fn from_ase<F>(f: F, ase: &AsepriteFile, ase_tileset: &asefile::Tileset) -> TilesetResult<Self> where F: FnOnce(&AsepriteFile, &asefile::Tileset) -> TilesetResult<T>, { let texture = f(ase, ase_tileset)?; let ase_size = ase_tileset.tile_size(); Ok(Self { tile_count: *ase_tileset.tile_count(), tile_size: TileSize::from_ase(ase_size), name: ase_tileset.name().to_string(), texture, }) } } impl TilesetData<Texture> { pub(crate) fn from_ase_with_texture( ase: &AsepriteFile, ase_tileset: &asefile::Tileset, ) -> TilesetResult<Self> { TilesetData::<Texture>::from_ase(texture_from, ase, ase_tileset) } }
use asefile::{AsepriteFile, TilesetImageError}; use bevy::{ prelude::*, reflect::T
width, height } = self.tile_size; let tile_count = self.tile_count as f32; Vec2::new(width as f32, height as f32 * tile_count) } } #[derive(Debug)] pub(crate) struct TilesetData<T> { pub(crate) tile_count: u32, pub(crate) tile_size: TileSize, pub(crate) name: String, pub(crate) texture: T, } impl<T> TilesetData<T> { fn from_ase<F>(f: F, ase: &AsepriteFile, ase_tileset: &asefile::Tileset) -> TilesetResult<Self> where F: FnOnce(&AsepriteFile, &asefile::Tileset) -> TilesetResult<T>, { let texture = f(ase, ase_tileset)?; let ase_size = ase_tileset.tile_size(); Ok(Self { tile_count: *ase_tileset.tile_count(), tile_size: TileSize::from_ase(ase_size), name: ase_tileset.name().to_string(), texture, }) } } impl TilesetData<Texture> { pub(crate) fn from_ase_with_texture( ase: &AsepriteFile, ase_tileset: &asefile::Tileset, ) -> TilesetResult<Self> { TilesetData::<Texture>::from_ase(texture_from, ase, ase_tileset) } }
ypeUuid, render::texture::{Extent3d, TextureDimension, TextureFormat}, }; use std::fmt; pub(crate) type TilesetResult<T> = std::result::Result<T, TilesetError>; #[derive(Debug)] pub enum TilesetError { MissingId(asefile::TilesetId), NoPixels(asefile::TilesetId), } impl fmt::Display for TilesetError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TilesetError::MissingId(tileset_id) => { write!(f, "No tileset found with id: {}", tileset_id) } TilesetError::NoPixels(tileset_id) => { write!(f, "No pixel data for tileset with id: {}", tileset_id) } } } } impl From<&TilesetImageError> for TilesetError { fn from(e: &TilesetImageError) -> Self { match e { TilesetImageError::MissingTilesetId(id) => Self::MissingId(*id), TilesetImageError::NoPixelsInTileset(id) => Self::NoPixels(*id), } } } impl From<TilesetImageError> for TilesetError { fn from(e: TilesetImageError) -> Self { Self::from(&e) } } fn texture_from(ase: &AsepriteFile, tileset: &asefile::Tileset) -> TilesetResult<Texture> { let tileset_id = tileset.id(); let image = ase.tileset_image(&tileset_id)?; let size = Extent3d { width: image.width(), height: image.height(), depth: 1, }; Ok(Texture::new_fill( size, TextureDimension::D2, image.as_raw(), TextureFormat::Rgba8UnormSrgb, )) } #[derive(Debug)] pub struct TileSize { pub width: u16, pub height: u16, } impl TileSize { fn from_ase(ase_size: &asefile::TileSize) -> Self { Self { width: *ase_size.width(), height: *ase_size.height(), } } } #[derive(Debug, TypeUuid)] #[uuid = "0e2dbd05-dbad-46c9-a943-395f83dfa4ba"] pub struct Tileset { pub tile_count: u32, pub tile_size: TileSize, pub name: String, pub texture: Handle<Texture>, } impl Tileset { pub fn texture_size(&self) -> Vec2 { let TileSize {
random
[ { "content": "use crate::asset::{TileSize, Tileset};\n\nuse bevy::math::{UVec2, Vec2};\n\nuse bevy_ecs_tilemap::prelude::*;\n\n\n\nimpl From<TileSize> for Vec2 {\n\n fn from(tile_size: TileSize) -> Self {\n\n Vec2::new(tile_size.width as f32, tile_size.height as f32)\n\n }\n\n}\n\n\n\nimpl Tileset ...
Rust
src/lib.rs
justanotherdot/cargo-watch
ac0a403e0c6b64a60dd7f5f78c049301ce092b4f
#![forbid(unsafe_code, clippy::pedantic)] #![allow( clippy::non_ascii_literal, clippy::cast_sign_loss, clippy::cast_possible_truncation )] #[macro_use] extern crate clap; extern crate watchexec; use clap::{ArgMatches, Error, ErrorKind}; use std::{env::set_current_dir, path::MAIN_SEPARATOR}; use watchexec::{Args, ArgsBuilder}; pub mod args; pub mod cargo; pub mod watch; pub fn change_dir() { cargo::root() .and_then(|p| set_current_dir(p).ok()) .unwrap_or_else(|| { Error::with_description("Not a Cargo project, aborting.", ErrorKind::Io).exit(); }); } pub fn set_commands(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let mut commands: Vec<String> = Vec::new(); if matches.is_present("cmd:cargo") { for cargo in values_t!(matches, "cmd:cargo", String).unwrap_or_else(|e| e.exit()) { let mut cmd: String = "cargo ".into(); cmd.push_str(&cargo); commands.push(cmd); } } if matches.is_present("cmd:shell") { for shell in values_t!(matches, "cmd:shell", String).unwrap_or_else(|e| e.exit()) { commands.push(shell); } } if commands.is_empty() { commands.push("cargo check".into()); } if debug { println!(">>> Commands: {:?}", commands); } builder.cmd(commands); } pub fn set_ignores(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { if matches.is_present("ignore-nothing") { if debug { println!(">>> Ignoring nothing"); } builder.no_vcs_ignore(true); return; } let novcs = matches.is_present("no-gitignore"); builder.no_vcs_ignore(novcs); if debug { println!(">>> Load Git/VCS ignores: {:?}", !novcs); } let mut list = vec![ format!("*{}.DS_Store", MAIN_SEPARATOR), "*.sw?".into(), "*.sw?x".into(), "#*#".into(), ".#*".into(), ".*.kate-swp".into(), format!("*{s}.hg{s}**", s = MAIN_SEPARATOR), format!("*{s}.git{s}**", s = MAIN_SEPARATOR), format!("*{s}.svn{s}**", s = MAIN_SEPARATOR), "*.db".into(), "*.db-*".into(), format!("*{s}*.db-journal{s}**", s = MAIN_SEPARATOR), format!("*{s}target{s}**", s = MAIN_SEPARATOR), ]; if debug { println!(">>> Default ignores: {:?}", list); } if matches.is_present("ignore") { for ignore in values_t!(matches, "ignore", String).unwrap_or_else(|e| e.exit()) { #[cfg(windows)] let ignore = ignore.replace("/", &MAIN_SEPARATOR.to_string()); list.push(ignore); } } if debug { println!(">>> All ignores: {:?}", list); } builder.ignores(list); } pub fn set_debounce(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let d = if matches.is_present("delay") { let debounce = value_t!(matches, "delay", f32).unwrap_or_else(|e| e.exit()); if debug { println!(">>> File updates debounce: {} seconds", debounce); } (debounce * 1000.0) as u32 } else { 500 }; builder.poll_interval(d).debounce(d); } pub fn set_watches(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let mut opts = Vec::new(); if matches.is_present("watch") { for watch in values_t!(matches, "watch", String).unwrap_or_else(|e| e.exit()) { opts.push(watch.into()); } } if opts.is_empty() { opts.push(".".into()); } if debug { println!(">>> Watches: {:?}", opts); } builder.paths(opts); } pub fn get_options(debug: bool, matches: &ArgMatches) -> Args { let mut builder = ArgsBuilder::default(); builder .restart(!matches.is_present("no-restart")) .poll(matches.is_present("poll")) .clear_screen(matches.is_present("clear")) .debug(debug) .run_initially(!matches.is_present("postpone")); set_ignores(debug, &mut builder, &matches); set_debounce(debug, &mut builder, &matches); set_watches(debug, &mut builder, &matches); set_commands(debug, &mut builder, &matches); let mut args = builder.build().unwrap(); args.once = matches.is_present("once"); if debug { println!(">>> Watchexec arguments: {:?}", args); } args }
#![forbid(unsafe_code, clippy::pedantic)] #![allow( clippy::non_ascii_literal, clippy::cast_sign_loss, clippy::cast_possible_truncation )] #[macro_use] extern crate clap; extern crate watchexec; use clap::{ArgMatches, Error, ErrorKind}; use std::{env::set_current_dir, path::MAIN_SEPARATOR}; use watchexec::{Args, ArgsBuilder}; pub mod args; pub mod cargo; pub mod watch;
pub fn set_commands(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let mut commands: Vec<String> = Vec::new(); if matches.is_present("cmd:cargo") { for cargo in values_t!(matches, "cmd:cargo", String).unwrap_or_else(|e| e.exit()) { let mut cmd: String = "cargo ".into(); cmd.push_str(&cargo); commands.push(cmd); } } if matches.is_present("cmd:shell") { for shell in values_t!(matches, "cmd:shell", String).unwrap_or_else(|e| e.exit()) { commands.push(shell); } } if commands.is_empty() { commands.push("cargo check".into()); } if debug { println!(">>> Commands: {:?}", commands); } builder.cmd(commands); } pub fn set_ignores(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { if matches.is_present("ignore-nothing") { if debug { println!(">>> Ignoring nothing"); } builder.no_vcs_ignore(true); return; } let novcs = matches.is_present("no-gitignore"); builder.no_vcs_ignore(novcs); if debug { println!(">>> Load Git/VCS ignores: {:?}", !novcs); } let mut list = vec![ format!("*{}.DS_Store", MAIN_SEPARATOR), "*.sw?".into(), "*.sw?x".into(), "#*#".into(), ".#*".into(), ".*.kate-swp".into(), format!("*{s}.hg{s}**", s = MAIN_SEPARATOR), format!("*{s}.git{s}**", s = MAIN_SEPARATOR), format!("*{s}.svn{s}**", s = MAIN_SEPARATOR), "*.db".into(), "*.db-*".into(), format!("*{s}*.db-journal{s}**", s = MAIN_SEPARATOR), format!("*{s}target{s}**", s = MAIN_SEPARATOR), ]; if debug { println!(">>> Default ignores: {:?}", list); } if matches.is_present("ignore") { for ignore in values_t!(matches, "ignore", String).unwrap_or_else(|e| e.exit()) { #[cfg(windows)] let ignore = ignore.replace("/", &MAIN_SEPARATOR.to_string()); list.push(ignore); } } if debug { println!(">>> All ignores: {:?}", list); } builder.ignores(list); } pub fn set_debounce(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let d = if matches.is_present("delay") { let debounce = value_t!(matches, "delay", f32).unwrap_or_else(|e| e.exit()); if debug { println!(">>> File updates debounce: {} seconds", debounce); } (debounce * 1000.0) as u32 } else { 500 }; builder.poll_interval(d).debounce(d); } pub fn set_watches(debug: bool, builder: &mut ArgsBuilder, matches: &ArgMatches) { let mut opts = Vec::new(); if matches.is_present("watch") { for watch in values_t!(matches, "watch", String).unwrap_or_else(|e| e.exit()) { opts.push(watch.into()); } } if opts.is_empty() { opts.push(".".into()); } if debug { println!(">>> Watches: {:?}", opts); } builder.paths(opts); } pub fn get_options(debug: bool, matches: &ArgMatches) -> Args { let mut builder = ArgsBuilder::default(); builder .restart(!matches.is_present("no-restart")) .poll(matches.is_present("poll")) .clear_screen(matches.is_present("clear")) .debug(debug) .run_initially(!matches.is_present("postpone")); set_ignores(debug, &mut builder, &matches); set_debounce(debug, &mut builder, &matches); set_watches(debug, &mut builder, &matches); set_commands(debug, &mut builder, &matches); let mut args = builder.build().unwrap(); args.once = matches.is_present("once"); if debug { println!(">>> Watchexec arguments: {:?}", args); } args }
pub fn change_dir() { cargo::root() .and_then(|p| set_current_dir(p).ok()) .unwrap_or_else(|| { Error::with_description("Not a Cargo project, aborting.", ErrorKind::Io).exit(); }); }
function_block-full_function
[ { "content": "fn main() -> watchexec::error::Result<()> {\n\n let matches = cargo_watch::args::parse();\n\n\n\n cargo_watch::change_dir();\n\n\n\n let quiet = matches.is_present(\"quiet\");\n\n let debug = matches.is_present(\"debug\");\n\n let opts = cargo_watch::get_options(debug, &matches);\n\...
Rust
fastpay_core/src/authority.rs
mahimna-fb/fastpay
413826688d365ad597acb002213704378e9b2efc
use crate::{base_types::*, committee::Committee, error::FastPayError, messages::*}; use std::{collections::BTreeMap, convert::TryInto}; #[cfg(test)] #[path = "unit_tests/authority_tests.rs"] mod authority_tests; #[derive(Eq, PartialEq, Debug)] pub struct AccountOffchainState { pub balance: Balance, pub next_sequence_number: SequenceNumber, pub pending_confirmation: Option<SignedTransferOrder>, pub confirmed_log: Vec<CertifiedTransferOrder>, pub synchronization_log: Vec<PrimarySynchronizationOrder>, pub received_log: Vec<CertifiedTransferOrder>, } pub struct AuthorityState { pub name: AuthorityName, pub committee: Committee, pub secret: SecretKey, pub accounts: BTreeMap<FastPayAddress, AccountOffchainState>, pub last_transaction_index: VersionNumber, pub shard_id: ShardId, pub number_of_shards: u32, } pub trait Authority { fn handle_transfer_order( &mut self, order: TransferOrder, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_confirmation_order( &mut self, order: ConfirmationOrder, ) -> Result<(AccountInfoResponse, Option<CrossShardUpdate>), FastPayError>; fn handle_primary_synchronization_order( &mut self, order: PrimarySynchronizationOrder, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_account_info_request( &self, request: AccountInfoRequest, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_cross_shard_recipient_commit( &mut self, certificate: CertifiedTransferOrder, ) -> Result<(), FastPayError>; } impl Authority for AuthorityState { fn handle_transfer_order( &mut self, order: TransferOrder, ) -> Result<AccountInfoResponse, FastPayError> { fp_ensure!( self.in_shard(&order.transfer.sender), FastPayError::WrongShard ); order.check_signature()?; let transfer = &order.transfer; let sender = transfer.sender; fp_ensure!( transfer.sequence_number <= SequenceNumber::max(), FastPayError::InvalidSequenceNumber ); fp_ensure!( transfer.amount > Amount::zero(), FastPayError::IncorrectTransferAmount ); match self.accounts.get_mut(&sender) { None => fp_bail!(FastPayError::UnknownSenderAccount), Some(account) => { if let Some(pending_confirmation) = &account.pending_confirmation { fp_ensure!( &pending_confirmation.value.transfer == transfer, FastPayError::PreviousTransferMustBeConfirmedFirst { pending_confirmation: pending_confirmation.value.clone() } ); return Ok(account.make_account_info(sender)); } fp_ensure!( account.next_sequence_number == transfer.sequence_number, FastPayError::UnexpectedSequenceNumber ); fp_ensure!( account.balance >= transfer.amount.into(), FastPayError::InsufficientFunding { current_balance: account.balance } ); let signed_order = SignedTransferOrder::new(order, self.name, &self.secret); account.pending_confirmation = Some(signed_order); Ok(account.make_account_info(sender)) } } } fn handle_confirmation_order( &mut self, confirmation_order: ConfirmationOrder, ) -> Result<(AccountInfoResponse, Option<CrossShardUpdate>), FastPayError> { let certificate = confirmation_order.transfer_certificate; fp_ensure!( self.in_shard(&certificate.value.transfer.sender), FastPayError::WrongShard ); certificate.check(&self.committee)?; let transfer = certificate.value.transfer.clone(); let mut sender_account = self .accounts .entry(transfer.sender) .or_insert_with(AccountOffchainState::new); let mut sender_sequence_number = sender_account.next_sequence_number; let mut sender_balance = sender_account.balance; if sender_sequence_number < transfer.sequence_number { fp_bail!(FastPayError::MissingEalierConfirmations { current_sequence_number: sender_sequence_number }); } if sender_sequence_number > transfer.sequence_number { return Ok((sender_account.make_account_info(transfer.sender), None)); } sender_balance = sender_balance.try_sub(transfer.amount.into())?; sender_sequence_number = sender_sequence_number.increment()?; sender_account.balance = sender_balance; sender_account.next_sequence_number = sender_sequence_number; sender_account.pending_confirmation = None; sender_account.confirmed_log.push(certificate.clone()); let info = sender_account.make_account_info(transfer.sender); let recipient = match transfer.recipient { Address::FastPay(recipient) => recipient, Address::Primary(_) => { return Ok((info, None)); } }; if self.in_shard(&recipient) { let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); recipient_account.balance = recipient_account .balance .try_add(transfer.amount.into()) .unwrap_or_else(|_| Balance::max()); recipient_account.received_log.push(certificate); return Ok((info, None)); } let cross_shard = Some(CrossShardUpdate { shard_id: self.which_shard(&recipient), transfer_certificate: certificate, }); Ok((info, cross_shard)) } fn handle_cross_shard_recipient_commit( &mut self, certificate: CertifiedTransferOrder, ) -> Result<(), FastPayError> { let transfer = &certificate.value.transfer; let recipient = match transfer.recipient { Address::FastPay(recipient) => recipient, Address::Primary(_) => { fp_bail!(FastPayError::InvalidCrossShardUpdate); } }; fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); recipient_account.balance = recipient_account .balance .try_add(transfer.amount.into()) .unwrap_or_else(|_| Balance::max()); recipient_account.received_log.push(certificate); Ok(()) } fn handle_primary_synchronization_order( &mut self, order: PrimarySynchronizationOrder, ) -> Result<AccountInfoResponse, FastPayError> { let recipient = order.recipient; fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); if order.transaction_index <= self.last_transaction_index { return Ok(recipient_account.make_account_info(recipient)); } fp_ensure!( order.transaction_index == self.last_transaction_index.increment()?, FastPayError::UnexpectedTransactionIndex ); let recipient_balance = recipient_account.balance.try_add(order.amount.into())?; let last_transaction_index = self.last_transaction_index.increment()?; recipient_account.balance = recipient_balance; recipient_account.synchronization_log.push(order); self.last_transaction_index = last_transaction_index; Ok(recipient_account.make_account_info(recipient)) } fn handle_account_info_request( &self, request: AccountInfoRequest, ) -> Result<AccountInfoResponse, FastPayError> { fp_ensure!(self.in_shard(&request.sender), FastPayError::WrongShard); let account = self.account_state(&request.sender)?; let mut response = account.make_account_info(request.sender); if let Some(seq) = request.request_sequence_number { if let Some(cert) = account.confirmed_log.get(usize::from(seq)) { response.requested_certificate = Some(cert.clone()); } else { fp_bail!(FastPayError::CertificateNotfound) } } if let Some(idx) = request.request_received_transfers_excluding_first_nth { response.requested_received_transfers = account.received_log[idx..].to_vec(); } Ok(response) } } impl Default for AccountOffchainState { fn default() -> Self { Self { balance: Balance::zero(), next_sequence_number: SequenceNumber::new(), pending_confirmation: None, confirmed_log: Vec::new(), synchronization_log: Vec::new(), received_log: Vec::new(), } } } impl AccountOffchainState { pub fn new() -> Self { Self::default() } fn make_account_info(&self, sender: FastPayAddress) -> AccountInfoResponse { AccountInfoResponse { sender, balance: self.balance, next_sequence_number: self.next_sequence_number, pending_confirmation: self.pending_confirmation.clone(), requested_certificate: None, requested_received_transfers: Vec::new(), } } #[cfg(test)] pub fn new_with_balance(balance: Balance, received_log: Vec<CertifiedTransferOrder>) -> Self { Self { balance, next_sequence_number: SequenceNumber::new(), pending_confirmation: None, confirmed_log: Vec::new(), synchronization_log: Vec::new(), received_log, } } } impl AuthorityState { pub fn new(committee: Committee, name: AuthorityName, secret: SecretKey) -> Self { AuthorityState { committee, name, secret, accounts: BTreeMap::new(), last_transaction_index: VersionNumber::new(), shard_id: 0, number_of_shards: 1, } } pub fn new_shard( committee: Committee, name: AuthorityName, secret: SecretKey, shard_id: u32, number_of_shards: u32, ) -> Self { AuthorityState { committee, name, secret, accounts: BTreeMap::new(), last_transaction_index: VersionNumber::new(), shard_id, number_of_shards, } } pub fn in_shard(&self, address: &FastPayAddress) -> bool { self.which_shard(address) == self.shard_id } pub fn get_shard(num_shards: u32, address: &FastPayAddress) -> u32 { const LAST_INTEGER_INDEX: usize = std::mem::size_of::<FastPayAddress>() - 4; u32::from_le_bytes(address.0[LAST_INTEGER_INDEX..].try_into().expect("4 bytes")) % num_shards } pub fn which_shard(&self, address: &FastPayAddress) -> u32 { Self::get_shard(self.number_of_shards, address) } fn account_state( &self, address: &FastPayAddress, ) -> Result<&AccountOffchainState, FastPayError> { self.accounts .get(address) .ok_or(FastPayError::UnknownSenderAccount) } #[cfg(test)] pub fn accounts_mut(&mut self) -> &mut BTreeMap<FastPayAddress, AccountOffchainState> { &mut self.accounts } }
use crate::{base_types::*, committee::Committee, error::FastPayError, messages::*}; use std::{collections::BTreeMap, convert::TryInto}; #[cfg(test)] #[path = "unit_tests/authority_tests.rs"] mod authority_tests; #[derive(Eq, PartialEq, Debug)] pub struct AccountOffchainState { pub balance: Balance, pub next_sequence_number: SequenceNumber, pub pending_confirmation: Option<SignedTransferOrder>, pub confirmed_log: Vec<CertifiedTransferOrder>, pub synchronization_log: Vec<PrimarySynchronizationOrder>, pub received_log: Vec<CertifiedTransferOrder>, } pub struct AuthorityState { pub name: AuthorityName, pub committee: Committee, pub secret: SecretKey, pub accounts: BTreeMap<FastPayAddress, AccountOffchainState>, pub last_transaction_index: VersionNumber, pub shard_id: ShardId, pub number_of_shards: u32, } pub trait Authority { fn handle_transfer_order( &mut self, order: TransferOrder, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_confirmation_order( &mut self, order: ConfirmationOrder, ) -> Result<(AccountInfoResponse, Option<CrossShardUpdate>), FastPayError>; fn handle_primary_synchronization_order( &mut self, order: PrimarySynchronizationOrder, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_account_info_request( &self, request: AccountInfoRequest, ) -> Result<AccountInfoResponse, FastPayError>; fn handle_cross_shard_recipient_commit( &mut self, certificate: CertifiedTransferOrder, ) -> Result<(), FastPayError>; } impl Authority for AuthorityState { fn handle_transfer_order( &mut self, order: TransferOrder, ) -> Result<AccountInfoResponse, FastPayError> { fp_ensure!( self.in_shard(&order.transfer.sender), FastPayError::WrongShard ); order.check_signature()?; let transfer = &order.transfer; let sender = transfer.sender; fp_ensure!( transfer.sequence_number <= SequenceNumber::max(), FastPayError::InvalidSequenceNumber ); fp_ensure!( transfer.amount > Amount::zero(), FastPayError::IncorrectTransferAmount ); match self.accounts.get_mut(&sender) { None => fp_bail!(FastPayError::UnknownSenderAccount), Some(account) => { if let Some(pending_confirmation) = &account.pending_confirmation { fp_ensure!( &pending_confirmation.value.transfer == transfer, FastPayError::PreviousTransferMustBeConfirmedFirst { pending_confirmation: pending_confirmation.value.clone() } ); return Ok(account.make_account_info(sender)); } fp_ensure!( account.next_sequence_number == transfer.sequence_number, FastPayError::UnexpectedSequenceNumber ); fp_ensure!( account.balance >= transfer.amount.into(), FastPayError::InsufficientFunding { current_balance: account.balance } ); let signed_order = SignedTransferOrder::new(order, self.name, &self.secret); account.pending_confirmation = Some(signed_order); Ok(account.make_account_info(sender)) } } } fn handle_confirmation_order( &mut self, confirmation_order: ConfirmationOrder, ) -> Result<(AccountInfoResponse, Option<CrossShardUpdate>), FastPayError> { let certificate = confirmation_order.transfer_certificate; fp_ensure!( self.in_shard(&certificate.value.transfer.sender), FastPayError::WrongShard ); certificate.check(&self.committee)?; let transfer = certificate.value.transfer.clone(); let mut sender_account = self .accounts .entry(transfer.sender) .or_insert_with(AccountOffchainState::new); let mut sender_sequence_number = sender_account.next_sequence_number; let mut sender_balance = sender_account.balance; if sender_sequence_number < transfer.sequence_number { fp_bail!(FastPayError::MissingEalierConfirmations { current_sequence_number: sender_sequence_number }); } if sender_sequence_number > transfer.sequence_number { return Ok((sender_account.make_account_info(transfer.sender), None)); } sender_balance = sender_balance.try_sub(transfer.amount.into())?; sender_sequence_number = sender_sequence_number.increment()?; sender_account.balance = sender_balance; sender_account.next_sequence_number = sender_sequence_number; sender_account.pending_confirmation = None; sender_account.confirmed_log.push(certificate.clone()); let info = sender_account.make_account_info(transfer.sender); let recipient = match transfer.recipient { Address::FastPay(recipient) => recipient, Address::Primary(_) => { return Ok((info, None)); } }; if self.in_shard(&recipient) { let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); recipient_account.balance = recipient_account .balance .try_add(transfer.amount.into()) .unwrap_or_else(|_| Balance::max()); recipient_account.received_log.push(certificate); return Ok((info, None)); } let cross_shard = Some(CrossShardUpdate { shard_id: self.which_shard(&recipient), transfer_certificate: certificate, }); Ok((info, cross_shard)) } fn handle_cross_shard_recipient_commit( &mut self,
requested_certificate: None, requested_received_transfers: Vec::new(), } } #[cfg(test)] pub fn new_with_balance(balance: Balance, received_log: Vec<CertifiedTransferOrder>) -> Self { Self { balance, next_sequence_number: SequenceNumber::new(), pending_confirmation: None, confirmed_log: Vec::new(), synchronization_log: Vec::new(), received_log, } } } impl AuthorityState { pub fn new(committee: Committee, name: AuthorityName, secret: SecretKey) -> Self { AuthorityState { committee, name, secret, accounts: BTreeMap::new(), last_transaction_index: VersionNumber::new(), shard_id: 0, number_of_shards: 1, } } pub fn new_shard( committee: Committee, name: AuthorityName, secret: SecretKey, shard_id: u32, number_of_shards: u32, ) -> Self { AuthorityState { committee, name, secret, accounts: BTreeMap::new(), last_transaction_index: VersionNumber::new(), shard_id, number_of_shards, } } pub fn in_shard(&self, address: &FastPayAddress) -> bool { self.which_shard(address) == self.shard_id } pub fn get_shard(num_shards: u32, address: &FastPayAddress) -> u32 { const LAST_INTEGER_INDEX: usize = std::mem::size_of::<FastPayAddress>() - 4; u32::from_le_bytes(address.0[LAST_INTEGER_INDEX..].try_into().expect("4 bytes")) % num_shards } pub fn which_shard(&self, address: &FastPayAddress) -> u32 { Self::get_shard(self.number_of_shards, address) } fn account_state( &self, address: &FastPayAddress, ) -> Result<&AccountOffchainState, FastPayError> { self.accounts .get(address) .ok_or(FastPayError::UnknownSenderAccount) } #[cfg(test)] pub fn accounts_mut(&mut self) -> &mut BTreeMap<FastPayAddress, AccountOffchainState> { &mut self.accounts } }
certificate: CertifiedTransferOrder, ) -> Result<(), FastPayError> { let transfer = &certificate.value.transfer; let recipient = match transfer.recipient { Address::FastPay(recipient) => recipient, Address::Primary(_) => { fp_bail!(FastPayError::InvalidCrossShardUpdate); } }; fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); recipient_account.balance = recipient_account .balance .try_add(transfer.amount.into()) .unwrap_or_else(|_| Balance::max()); recipient_account.received_log.push(certificate); Ok(()) } fn handle_primary_synchronization_order( &mut self, order: PrimarySynchronizationOrder, ) -> Result<AccountInfoResponse, FastPayError> { let recipient = order.recipient; fp_ensure!(self.in_shard(&recipient), FastPayError::WrongShard); let recipient_account = self .accounts .entry(recipient) .or_insert_with(AccountOffchainState::new); if order.transaction_index <= self.last_transaction_index { return Ok(recipient_account.make_account_info(recipient)); } fp_ensure!( order.transaction_index == self.last_transaction_index.increment()?, FastPayError::UnexpectedTransactionIndex ); let recipient_balance = recipient_account.balance.try_add(order.amount.into())?; let last_transaction_index = self.last_transaction_index.increment()?; recipient_account.balance = recipient_balance; recipient_account.synchronization_log.push(order); self.last_transaction_index = last_transaction_index; Ok(recipient_account.make_account_info(recipient)) } fn handle_account_info_request( &self, request: AccountInfoRequest, ) -> Result<AccountInfoResponse, FastPayError> { fp_ensure!(self.in_shard(&request.sender), FastPayError::WrongShard); let account = self.account_state(&request.sender)?; let mut response = account.make_account_info(request.sender); if let Some(seq) = request.request_sequence_number { if let Some(cert) = account.confirmed_log.get(usize::from(seq)) { response.requested_certificate = Some(cert.clone()); } else { fp_bail!(FastPayError::CertificateNotfound) } } if let Some(idx) = request.request_received_transfers_excluding_first_nth { response.requested_received_transfers = account.received_log[idx..].to_vec(); } Ok(response) } } impl Default for AccountOffchainState { fn default() -> Self { Self { balance: Balance::zero(), next_sequence_number: SequenceNumber::new(), pending_confirmation: None, confirmed_log: Vec::new(), synchronization_log: Vec::new(), received_log: Vec::new(), } } } impl AccountOffchainState { pub fn new() -> Self { Self::default() } fn make_account_info(&self, sender: FastPayAddress) -> AccountInfoResponse { AccountInfoResponse { sender, balance: self.balance, next_sequence_number: self.next_sequence_number, pending_confirmation: self.pending_confirmation.clone(),
random
[ { "content": "pub fn serialize_info_request(value: &AccountInfoRequest) -> Vec<u8> {\n\n serialize(&ShallowSerializedMessage::InfoReq(value))\n\n}\n\n\n", "file_path": "fastpay_core/src/serialize.rs", "rank": 0, "score": 194362.98059485495 }, { "content": "pub fn serialize_transfer_order_...
Rust
crypto/bls/src/macros.rs
sean-sn/lighthouse
c6baa0eed131c5e8ecc5860778ffc7d4a4c18d2d
macro_rules! impl_tree_hash { ($byte_size: expr) => { fn tree_hash_type() -> tree_hash::TreeHashType { tree_hash::TreeHashType::Vector } fn tree_hash_packed_encoding(&self) -> Vec<u8> { unreachable!("Vector should never be packed.") } fn tree_hash_packing_factor() -> usize { unreachable!("Vector should never be packed.") } fn tree_hash_root(&self) -> tree_hash::Hash256 { let values_per_chunk = tree_hash::BYTES_PER_CHUNK; let minimum_chunk_count = ($byte_size + values_per_chunk - 1) / values_per_chunk; tree_hash::merkle_root(&self.serialize(), minimum_chunk_count) } }; } macro_rules! impl_ssz_encode { ($byte_size: expr) => { fn is_ssz_fixed_len() -> bool { true } fn ssz_fixed_len() -> usize { $byte_size } fn ssz_bytes_len(&self) -> usize { $byte_size } fn ssz_append(&self, buf: &mut Vec<u8>) { buf.extend_from_slice(&self.serialize()) } }; } macro_rules! impl_ssz_decode { ($byte_size: expr) => { fn is_ssz_fixed_len() -> bool { true } fn ssz_fixed_len() -> usize { $byte_size } fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> { let len = bytes.len(); let expected = <Self as ssz::Decode>::ssz_fixed_len(); if len != expected { Err(ssz::DecodeError::InvalidByteLength { len, expected }) } else { Self::deserialize(bytes) .map_err(|e| ssz::DecodeError::BytesInvalid(format!("{:?}", e))) } } }; } macro_rules! impl_display { () => { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", hex_encode(self.serialize().to_vec())) } }; } macro_rules! impl_from_str { () => { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.starts_with("0x") { let bytes = hex::decode(&s[2..]).map_err(|e| e.to_string())?; Self::deserialize(&bytes[..]).map_err(|e| format!("{:?}", e)) } else { Err("must start with 0x".to_string()) } } }; } macro_rules! impl_serde_serialize { () => { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&self.to_string()) } }; } macro_rules! impl_serde_deserialize { () => { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { pub struct StringVisitor; impl<'de> serde::de::Visitor<'de> for StringVisitor { type Value = String; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a hex string with 0x prefix") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(value.to_string()) } } let string = deserializer.deserialize_str(StringVisitor)?; <Self as std::str::FromStr>::from_str(&string).map_err(serde::de::Error::custom) } }; } macro_rules! impl_debug { () => { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", hex_encode(&self.serialize().to_vec())) } }; } #[cfg(feature = "arbitrary")] macro_rules! impl_arbitrary { ($byte_size: expr) => { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> { let mut bytes = [0u8; $byte_size]; u.fill_buffer(&mut bytes)?; Self::deserialize(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat) } }; }
macro_rules! impl_tree_hash { ($byte_size: expr) => { fn tree_hash_type() -> tree_hash::TreeHashType { tree_hash::TreeHashType::Vector } fn tree_hash_packed_encoding(&self) -> Vec<u8> { unreachable!("Vector should never be packed.") } fn tree_hash_packing_factor() -> usize { unreachable!("Vector should never be packed.") } fn tree_hash_root(&self) -> tree_hash::Hash256 { let values_per_chunk = tree_hash::BYTES_PER_CHUNK; let minimum_chunk_count = ($byte_size + values_per_chunk - 1) / values_per_chunk; tree_hash::merkle_root(&self.serialize(), minimum_chunk_count) } }; } macro_rules! impl_ssz_encode { ($byte_size: expr) => { fn is_ssz_fixed_len() -> bool { true } fn ssz_fixed_len() -> usize { $byte_size } fn ssz_bytes_len(&self) -> usize { $byte_size } fn ssz_append(&self, buf: &mut Vec<u8>) { buf.extend_from_slice(&self.serialize()) } }; } macro_rules! impl_ssz_decode { ($byte_size: expr) => { fn is_ssz_fixed_len() -> bool { true } fn ssz_fixed_len() -> usize { $byte_size } fn from_ssz_bytes(bytes: &[u8]) -> Result<Self, ssz::DecodeError> { let len = bytes.len(); let expected = <Self as ssz::Decode>::ssz_fixed_len(); if len != expected { Err(ssz::DecodeError::InvalidByteLength { len, expected }) } else { Self::deserialize(bytes) .map_err(|e| ssz::DecodeError::BytesInvalid(format!("{:?}", e))) } } }; } macro_rules! impl_display { () => { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", hex_encode(self.serialize().to_vec())) } }; } macro_rules! impl_from_str { () => { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.starts_with("0x") { let bytes = hex::decode(&s[2..]).map_err(|e| e.to_string())?; Self::deserialize(&bytes[..]).map_err(|e| format!("{:?}", e)) } else { Err("must start with 0x".to_string()) } } }; } macro_rules! impl_serde_serialize { () => { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&self.to_string()) } }; } macro_rules! impl_serde_deserialize { () => { fn deserialize<D>(deserializer: D) -> Result<Sel
Self::deserialize(&bytes).map_err(|_| arbitrary::Error::IncorrectFormat) } }; }
f, D::Error> where D: Deserializer<'de>, { pub struct StringVisitor; impl<'de> serde::de::Visitor<'de> for StringVisitor { type Value = String; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a hex string with 0x prefix") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(value.to_string()) } } let string = deserializer.deserialize_str(StringVisitor)?; <Self as std::str::FromStr>::from_str(&string).map_err(serde::de::Error::custom) } }; } macro_rules! impl_debug { () => { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", hex_encode(&self.serialize().to_vec())) } }; } #[cfg(feature = "arbitrary")] macro_rules! impl_arbitrary { ($byte_size: expr) => { fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> { let mut bytes = [0u8; $byte_size]; u.fill_buffer(&mut bytes)?;
random
[ { "content": "fn string_to_bytes(string: &str) -> Result<Vec<u8>, String> {\n\n let string = if string.starts_with(\"0x\") {\n\n &string[2..]\n\n } else {\n\n string\n\n };\n\n\n\n hex::decode(string).map_err(|e| format!(\"Unable to decode public or private key: {}\", e))\n\n}\n\n\n", ...
Rust
src/developer/ffx/plugins/setui/display/src/lib.rs
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
use anyhow::Result; use ffx_core::ffx_plugin; use ffx_setui_display_args::Display; use fidl_fuchsia_settings::{DisplayProxy, DisplaySettings}; use utils::handle_mixed_result; use utils::{self, Either, WatchOrSetResult}; #[ffx_plugin("setui", DisplayProxy = "core/setui_service:expose:fuchsia.settings.Display")] pub async fn run_command(display_proxy: DisplayProxy, display: Display) -> Result<()> { handle_mixed_result("Display", command(display_proxy, DisplaySettings::from(display)).await) .await } async fn command(proxy: DisplayProxy, settings: DisplaySettings) -> WatchOrSetResult { if settings == DisplaySettings::EMPTY { Ok(Either::Watch(utils::watch_to_stream(proxy, |p| p.watch()))) } else { Ok(Either::Set(if let Err(err) = proxy.set(settings.clone()).await? { format!("{:?}", err) } else { format!("Successfully set Display to {:?}", Display::from(settings)) })) } } #[cfg(test)] mod test { use super::*; use fidl_fuchsia_settings::{DisplayRequest, LowLightMode, Theme, ThemeMode, ThemeType}; use futures::prelude::*; use test_case::test_case; #[fuchsia_async::run_singlethreaded(test)] async fn test_run_command() { let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { responder, .. } => { let _ = responder.send(&mut Ok(())); } DisplayRequest::Watch { .. } => { panic!("Unexpected call to watch"); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let display = Display { brightness: None, auto_brightness_level: None, auto_brightness: Some(true), low_light_mode: None, theme: None, screen_enabled: None, }; let response = run_command(proxy, display).await; assert!(response.is_ok()); } #[test_case( Display { brightness: Some(0.5), auto_brightness_level: None, auto_brightness: Some(false), low_light_mode: None, theme: None, screen_enabled: None, }; "Test display set() output with non-empty input." )] #[test_case( Display { brightness: None, auto_brightness_level: Some(0.8), auto_brightness: Some(true), low_light_mode: Some(LowLightMode::Enable), theme: Some(Theme { theme_type: Some(ThemeType::Dark), theme_mode: Some(ThemeMode::AUTO), ..Theme::EMPTY }), screen_enabled: Some(true), }; "Test display set() output with a different non-empty input." )] #[fuchsia_async::run_singlethreaded(test)] async fn validate_display_set_output(expected_display: Display) -> Result<()> { let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { responder, .. } => { let _ = responder.send(&mut Ok(())); } DisplayRequest::Watch { .. } => { panic!("Unexpected call to watch"); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let output = utils::assert_set!(command(proxy, DisplaySettings::from(expected_display.clone()))); assert_eq!(output, format!("Successfully set Display to {:?}", expected_display)); Ok(()) } #[test_case( Display { brightness: None, auto_brightness_level: None, auto_brightness: None, low_light_mode: None, theme: None, screen_enabled: None, }; "Test display watch() output with empty input." )] #[test_case( Display { brightness: Some(0.5), auto_brightness_level: None, auto_brightness: Some(false), low_light_mode: None, theme: None, screen_enabled: None, }; "Test display watch() output with non-empty input." )] #[fuchsia_async::run_singlethreaded(test)] async fn validate_display_watch_output(expected_display: Display) -> Result<()> { let expected_display_clone = expected_display.clone(); let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { .. } => { panic!("Unexpected call to set"); } DisplayRequest::Watch { responder } => { let _ = responder.send(DisplaySettings::from(expected_display.clone())); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let output = utils::assert_watch!(command( proxy, DisplaySettings::from(Display { brightness: None, auto_brightness_level: None, auto_brightness: None, low_light_mode: None, theme: None, screen_enabled: None, }) )); assert_eq!(output, format!("{:#?}", DisplaySettings::from(expected_display_clone))); Ok(()) } }
use anyhow::Result; use ffx_core::ffx_plugin; use ffx_setui_display_args::Display; use fidl_fuchsia_settings::{DisplayProxy, DisplaySettings}; use utils::handle_mixed_result; use utils::{self, Either, WatchOrSetResult}; #[ffx_plugin("setui", DisplayProxy = "core/setui_service:expose:fuchsia.settings.Display")] pub async fn run_command(display_proxy: DisplayProxy, display: Display) -> Result<()> { handle_mixed_result("Display", command(display_proxy, DisplaySettings::from(display)).await) .await } async fn command(proxy: DisplayProxy, settings: DisplaySettings) -> WatchOrSetResult { if settings == DisplaySettings::EMPTY { Ok(Either::Watch(utils::watch_to_stream(proxy, |p| p.watch()))) } else { Ok(Either::Set(if let Err(err) = proxy.set(settings.clone()).await? { format!("{:?}", err) } else { format!("Successfully set Display to {:?}", Display::from(settings)) })) } } #[cfg(test)] mod test { use super::*; use fidl_fuchsia_settings::{DisplayRequest, LowLightMode, Theme, ThemeMode, ThemeType}; use futures::prelude::*; use test_case::test_case; #[fuchsia_async::run_singlethreaded(test)] async fn test_run_command() { let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { responder, .. } => { let _ = responder.send(&mut Ok(())); } DisplayRequest::Watch { .. } => { panic!("Unexpected call to watch"); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let display = Display { brightness: None, auto_brightness_level: None, auto_brightness: Some(true), low_light_mode: None, theme: None, screen_enabled: None, }; let response = run_command(proxy, display).await; assert!(response.is_ok()); } #[test_case( Display { brightness: Some(0.5), auto_brightness_level: None, auto_brightness: Some(false), low_light_mode: None, theme: None, screen_enabled: None, }; "Test display set() output with non-empty input." )] #[test_case( Display { brightness: None, auto_brightness_level: Some(0.8), auto_brightness: Some(true), low_light_mode: Some(LowLightMode::Enable), theme: Some(Theme { theme_type: Some(ThemeType::Dark), theme_mode: Some(ThemeMode::AUTO), ..Theme::EMPTY }), screen_enabled: Some(true), }; "Test display set() output with a different non-empty input." )] #[fuchsia_async::run_singlethreaded(test)]
#[test_case( Display { brightness: None, auto_brightness_level: None, auto_brightness: None, low_light_mode: None, theme: None, screen_enabled: None, }; "Test display watch() output with empty input." )] #[test_case( Display { brightness: Some(0.5), auto_brightness_level: None, auto_brightness: Some(false), low_light_mode: None, theme: None, screen_enabled: None, }; "Test display watch() output with non-empty input." )] #[fuchsia_async::run_singlethreaded(test)] async fn validate_display_watch_output(expected_display: Display) -> Result<()> { let expected_display_clone = expected_display.clone(); let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { .. } => { panic!("Unexpected call to set"); } DisplayRequest::Watch { responder } => { let _ = responder.send(DisplaySettings::from(expected_display.clone())); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let output = utils::assert_watch!(command( proxy, DisplaySettings::from(Display { brightness: None, auto_brightness_level: None, auto_brightness: None, low_light_mode: None, theme: None, screen_enabled: None, }) )); assert_eq!(output, format!("{:#?}", DisplaySettings::from(expected_display_clone))); Ok(()) } }
async fn validate_display_set_output(expected_display: Display) -> Result<()> { let proxy = setup_fake_display_proxy(move |req| match req { DisplayRequest::Set { responder, .. } => { let _ = responder.send(&mut Ok(())); } DisplayRequest::Watch { .. } => { panic!("Unexpected call to watch"); } DisplayRequest::WatchLightSensor { .. } => { panic!("Unexpected call to watch light sensor"); } }); let output = utils::assert_set!(command(proxy, DisplaySettings::from(expected_display.clone()))); assert_eq!(output, format!("Successfully set Display to {:?}", expected_display)); Ok(()) }
function_block-full_function
[]
Rust
src/setup_config.rs
amarant/msvc-helper
27821c5cdbfdebcae94342f8b6662791f1e78b02
#![allow(bad_style)] use std::ffi::OsString; use std::ptr::null_mut; use std::fmt; use winapi::Interface; use winapi::shared::minwindef::{LPFILETIME, ULONG}; use winapi::shared::winerror::S_FALSE; use winapi::shared::wtypes::BSTR; use winapi::shared::wtypesbase::LPCOLESTR; use winapi::um::combaseapi::{CoCreateInstance, CLSCTX_ALL}; use winapi::um::oaidl::LPSAFEARRAY; use winapi::um::unknwnbase::{IUnknown, IUnknownVtbl}; use winapi::um::winnt::{HRESULT, LCID, LPCWSTR, PULONGLONG}; use winapi::um::combaseapi::CoInitializeEx; use winapi::um::objbase::COINIT_MULTITHREADED; use utils::BStr; use wio::com::ComPtr; ENUM!{enum InstanceState { eNone = 0, eLocal = 1, eRegistered = 2, eNoRebootRequired = 4, eComplete = -1i32 as u32, }} RIDL!{#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)] interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) { fn GetInstanceId( pbstrInstanceId: *mut BSTR, ) -> HRESULT, fn GetInstallDate( pInstallDate: LPFILETIME, ) -> HRESULT, fn GetInstallationName( pbstrInstallationName: *mut BSTR, ) -> HRESULT, fn GetInstallationPath( pbstrInstallationPath: *mut BSTR, ) -> HRESULT, fn GetInstallationVersion( pbstrInstallationVersion: *mut BSTR, ) -> HRESULT, fn GetDisplayName( lcid: LCID, pbstrDisplayName: *mut BSTR, ) -> HRESULT, fn GetDescription( lcid: LCID, pbstrDescription: *mut BSTR, ) -> HRESULT, fn ResolvePath( pwszRelativePath: LPCOLESTR, pbstrAbsolutePath: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)] interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) { fn GetState( pState: *mut InstanceState, ) -> HRESULT, fn GetPackages( ppsaPackages: *mut LPSAFEARRAY, ) -> HRESULT, fn GetProduct( ppPackage: *mut *mut ISetupPackageReference, ) -> HRESULT, fn GetProductPath( pbstrProductPath: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)] interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) { fn Next( celt: ULONG, rgelt: *mut *mut ISetupInstance, pceltFetched: *mut ULONG, ) -> HRESULT, fn Skip( celt: ULONG, ) -> HRESULT, fn Reset() -> HRESULT, fn Clone( ppenum: *mut *mut IEnumSetupInstances, ) -> HRESULT, }} RIDL!{#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)] interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) { fn EnumInstances( ppEnumInstances: *mut *mut IEnumSetupInstances, ) -> HRESULT, fn GetInstanceForCurrentProcess( ppInstance: *mut *mut ISetupInstance, ) -> HRESULT, fn GetInstanceForPath( wzPath: LPCWSTR, ppInstance: *mut *mut ISetupInstance, ) -> HRESULT, }} RIDL!{#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)] interface ISetupConfiguration2(ISetupConfiguration2Vtbl): ISetupConfiguration(ISetupConfigurationVtbl) { fn EnumAllInstances( ppEnumInstances: *mut *mut IEnumSetupInstances, ) -> HRESULT, }} RIDL!{#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)] interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) { fn GetId( pbstrId: *mut BSTR, ) -> HRESULT, fn GetVersion( pbstrVersion: *mut BSTR, ) -> HRESULT, fn GetChip( pbstrChip: *mut BSTR, ) -> HRESULT, fn GetLanguage( pbstrLanguage: *mut BSTR, ) -> HRESULT, fn GetBranch( pbstrBranch: *mut BSTR, ) -> HRESULT, fn GetType( pbstrType: *mut BSTR, ) -> HRESULT, fn GetUniqueId( pbstrUniqueId: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)] interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) { fn ParseVersion( pwszVersion: LPCOLESTR, pullVersion: PULONGLONG, ) -> HRESULT, fn ParseVersionRange( pwszVersionRange: LPCOLESTR, pullMinVersion: PULONGLONG, pullMaxVersion: PULONGLONG, ) -> HRESULT, }} DEFINE_GUID!{CLSID_SetupConfiguration, 0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d} pub fn initialize_com() -> Result<i32, i32> { let err = unsafe { CoInitializeEx(null_mut(), COINIT_MULTITHREADED) }; if err < 0 { return Err(err); } Ok(err) } lazy_static! { static ref COM_INIT: Result<i32, i32> = { initialize_com() }; } pub struct SetupConfiguration(ComPtr<ISetupConfiguration>); impl SetupConfiguration { pub fn new() -> Result<SetupConfiguration, i32> { if let Err(i) = *COM_INIT { return Err(i); } let mut obj = null_mut(); let err = unsafe { CoCreateInstance( &CLSID_SetupConfiguration, null_mut(), CLSCTX_ALL, &ISetupConfiguration::uuidof(), &mut obj, ) }; if err < 0 { return Err(err); } let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; Ok(SetupConfiguration(obj)) } pub fn get_instance_for_current_process(&self) -> Result<SetupInstance, i32> { let mut obj = null_mut(); let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { SetupInstance::from_raw(obj) }) } pub fn enum_instances(&self) -> Result<EnumSetupInstances, i32> { let mut obj = null_mut(); let err = unsafe { self.0.EnumInstances(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { EnumSetupInstances::from_raw(obj) }) } pub fn enum_all_instances(&self) -> Result<EnumSetupInstances, i32> { let mut obj = null_mut(); let this = try!(self.0.cast::<ISetupConfiguration2>()); let err = unsafe { this.EnumAllInstances(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { EnumSetupInstances::from_raw(obj) }) } } pub struct SetupInstance(ComPtr<ISetupInstance>); impl SetupInstance { pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance { SetupInstance(ComPtr::from_raw(obj)) } pub fn instance_id(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstanceId(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_name(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationName(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_path(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationPath(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_version(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationVersion(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn product_path(&self) -> Result<OsString, i32> { let mut s = null_mut(); let this = try!(self.0.cast::<ISetupInstance2>()); let err = unsafe { this.GetProductPath(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } } impl fmt::Debug for SetupInstance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Setup Instance {{ instance_id: {:?}, installation_name: {:?}, installation_path: {:?}, installation_version: {:?}, product_path: {:?}}}", self.instance_id(), self.installation_name(), self.installation_path(), self.installation_version(), self.product_path(), ) } } fn displayRes(res: Result<OsString, i32>) -> String { match res { Ok(s) => match s.into_string() { Ok(s) => s, Err(_) => "Error".into(), }, Err(i) => format!("Error: {}", i), } } impl fmt::Display for SetupInstance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Instance id: {}, Installation name: {}, Installation path: {}, Installation version: {}, Product path: {}", displayRes(self.instance_id()), displayRes(self.installation_name()), displayRes(self.installation_path()), displayRes(self.installation_version()), displayRes(self.product_path()) ) } } pub struct EnumSetupInstances(ComPtr<IEnumSetupInstances>); impl EnumSetupInstances { pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances { EnumSetupInstances(ComPtr::from_raw(obj)) } } impl Iterator for EnumSetupInstances { type Item = Result<SetupInstance, i32>; fn next(&mut self) -> Option<Result<SetupInstance, i32>> { let mut obj = null_mut(); let err = unsafe { self.0.Next(1, &mut obj, null_mut()) }; if err < 0 { return Some(Err(err)); } if err == S_FALSE { return None; } Some(Ok(unsafe { SetupInstance::from_raw(obj) })) } }
#![allow(bad_style)] use std::ffi::OsString; use std::ptr::null_mut; use std::fmt; use winapi::Interface; use winapi::shared::minwindef::{LPFILETIME, ULONG}; use winapi::shared::winerror::S_FALSE; use winapi::shared::wtypes::BSTR; use winapi::shared::wtypesbase::LPCOLESTR; use winapi::um::combaseapi::{CoCreateInstance, CLSCTX_ALL}; use winapi::um::oaidl::LPSAFEARRAY; use winapi::um::unknwnbase::{IUnknown, IUnknownVtbl}; use winapi::um::winnt::{HRESULT, LCID, LPCWSTR, PULONGLONG}; use winapi::um::combaseapi::CoInitializeEx; use winapi::um::objbase::COINIT_MULTITHREADED; use utils::BStr; use wio::com::ComPtr; ENUM!{enum InstanceState { eNone = 0, eLocal = 1, eRegistered = 2, eNoRebootRequired = 4, eComplete = -1i32 as u32, }} RIDL!{#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)] interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) { fn GetInstanceId( pbstrInstanceId: *mut BSTR, ) -> HRESULT, fn GetInstallDate( pInstallDate: LPFILETIME, ) -> HRESULT, fn GetInstallationName( pbstrInstallationName: *mut BSTR, ) -> HRESULT, fn GetInstallationPath( pbstrInstallationPath: *mut BSTR, ) -> HRESULT, fn GetInstallationVersion( pbstrInstallationVersion: *mut BSTR, ) -> HRESULT, fn GetDisplayName( lcid: LCID, pbstrDisplayName: *mut BSTR, ) -> HRESULT, fn GetDescription( lcid: LCID, pbstrDescription: *mut BSTR, ) -> HRESULT, fn ResolvePath( pwszRelativePath: LPCOLESTR, pbstrAbsolutePath: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)] interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) { fn GetState( pState: *mut InstanceState, ) -> HRESULT, fn GetPackages( ppsaPackages: *mut LPSAFEARRAY, ) -> HRESULT, fn GetProduct( ppPackage: *mut *mut ISetupPackageReference, ) -> HRESULT, fn GetProductPath( pbstrProductPath: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)] interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) { fn Next( celt: ULONG, rgelt: *mut *mut ISetupInstance, pceltFetched: *mut ULONG, ) -> HRESULT, fn Skip( celt: ULONG, ) -> HRESULT, fn Reset() -> HRESULT, fn Clone( ppenum: *mut *mut IEnumSetupInstances, ) -> HRESULT, }} RIDL!{#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)] interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) { fn EnumInstances( ppEnumInstances: *mut *mut IEnumSetupInstances, ) -> HRESULT, fn GetInstanceForCurrentProcess( ppInstance: *mut *mut ISetupInstance, ) -> HRESULT, fn GetInstanceForPath( wzPath: LPCWSTR, ppInstance: *mut *mut ISetupInstance, ) -> HRESULT, }} RIDL!{#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)] interface ISetupConfiguration2(ISetupConfiguration2Vtbl): ISetupConfiguration(ISetupConfigurationVtbl) { fn EnumAllInstances( ppEnumInstances: *mut *mut IEnumSetupInstances, ) -> HRESULT, }} RIDL!{#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)] interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) { fn GetId( pbstrId: *mut BSTR, ) -> HRESULT, fn GetVersion( pbstrVersion: *mut BSTR, ) -> HRESULT, fn GetChip( pbstrChip: *mut BSTR, ) -> HRESULT, fn GetLanguage( pbstrLanguage: *mut BSTR, ) -> HRESULT, fn GetBranch( pbstrBranch: *mut BSTR, ) -> HRESULT, fn GetType( pbstrType: *mut BSTR, ) -> HRESULT, fn GetUniqueId( pbstrUniqueId: *mut BSTR, ) -> HRESULT, }} RIDL!{#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)] interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) { fn ParseVersion( pwszVersion: LPCOLESTR, pullVersion: PULONGLONG, ) -> HRESULT, fn ParseVersionRange( pwszVersionRange: LPCOLESTR, pullMinVersion: PULONGLONG, pullMaxVersion: PULONGLONG, ) -> HRESULT, }} DEFINE_GUID!{CLSID_SetupConfiguration, 0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d} pub fn initialize_com() -> Result<i32, i32> { let err = unsafe { CoInitializeEx(null_mut(), COINIT_MULTITHREADED) }; if err < 0 { return Err(err); } Ok(err) } lazy_static! { static ref COM_INIT: Result<i32, i32> = { initialize_com() }; } pub struct SetupConfiguration(ComPtr<ISetupConfiguration>); impl SetupConfiguration { pub fn new() -> Result<SetupConfiguration, i32> { if let Err(i) = *COM_INIT { return Err(i); } let mut obj = null_mut(); let err = unsafe {
}; if err < 0 { return Err(err); } let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; Ok(SetupConfiguration(obj)) } pub fn get_instance_for_current_process(&self) -> Result<SetupInstance, i32> { let mut obj = null_mut(); let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { SetupInstance::from_raw(obj) }) } pub fn enum_instances(&self) -> Result<EnumSetupInstances, i32> { let mut obj = null_mut(); let err = unsafe { self.0.EnumInstances(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { EnumSetupInstances::from_raw(obj) }) } pub fn enum_all_instances(&self) -> Result<EnumSetupInstances, i32> { let mut obj = null_mut(); let this = try!(self.0.cast::<ISetupConfiguration2>()); let err = unsafe { this.EnumAllInstances(&mut obj) }; if err < 0 { return Err(err); } Ok(unsafe { EnumSetupInstances::from_raw(obj) }) } } pub struct SetupInstance(ComPtr<ISetupInstance>); impl SetupInstance { pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance { SetupInstance(ComPtr::from_raw(obj)) } pub fn instance_id(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstanceId(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_name(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationName(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_path(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationPath(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn installation_version(&self) -> Result<OsString, i32> { let mut s = null_mut(); let err = unsafe { self.0.GetInstallationVersion(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } pub fn product_path(&self) -> Result<OsString, i32> { let mut s = null_mut(); let this = try!(self.0.cast::<ISetupInstance2>()); let err = unsafe { this.GetProductPath(&mut s) }; let bstr = unsafe { BStr::from_raw(s) }; if err < 0 { return Err(err); } Ok(bstr.to_osstring()) } } impl fmt::Debug for SetupInstance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Setup Instance {{ instance_id: {:?}, installation_name: {:?}, installation_path: {:?}, installation_version: {:?}, product_path: {:?}}}", self.instance_id(), self.installation_name(), self.installation_path(), self.installation_version(), self.product_path(), ) } } fn displayRes(res: Result<OsString, i32>) -> String { match res { Ok(s) => match s.into_string() { Ok(s) => s, Err(_) => "Error".into(), }, Err(i) => format!("Error: {}", i), } } impl fmt::Display for SetupInstance { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Instance id: {}, Installation name: {}, Installation path: {}, Installation version: {}, Product path: {}", displayRes(self.instance_id()), displayRes(self.installation_name()), displayRes(self.installation_path()), displayRes(self.installation_version()), displayRes(self.product_path()) ) } } pub struct EnumSetupInstances(ComPtr<IEnumSetupInstances>); impl EnumSetupInstances { pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances { EnumSetupInstances(ComPtr::from_raw(obj)) } } impl Iterator for EnumSetupInstances { type Item = Result<SetupInstance, i32>; fn next(&mut self) -> Option<Result<SetupInstance, i32>> { let mut obj = null_mut(); let err = unsafe { self.0.Next(1, &mut obj, null_mut()) }; if err < 0 { return Some(Err(err)); } if err == S_FALSE { return None; } Some(Ok(unsafe { SetupInstance::from_raw(obj) })) } }
CoCreateInstance( &CLSID_SetupConfiguration, null_mut(), CLSCTX_ALL, &ISetupConfiguration::uuidof(), &mut obj, )
call_expression
[ { "content": "pub fn get_lasted_platform_toolset() -> Option<String> {\n\n get_toolchains()\n\n .iter()\n\n .next()\n\n .map(|v| v.platform_toolset.clone())\n\n}\n", "file_path": "src/toolchain.rs", "rank": 1, "score": 59086.79993836931 }, { "content": "fn os_to_res_s...
Rust
proto-compiler/src/cmd/compile.rs
livelybug/ibc-rs
e83a2d0963fe6fa675b4125a4e8c18b13b792d88
use std::fs::remove_dir_all; use std::fs::{copy, create_dir_all}; use std::path::{Path, PathBuf}; use git2::Repository; use tempdir::TempDir; use walkdir::WalkDir; use argh::FromArgs; #[derive(Debug, FromArgs)] #[argh(subcommand, name = "compile")] pub struct CompileCmd { #[argh(option, short = 's')] sdk: PathBuf, #[argh(option, short = 'o')] out: PathBuf, } impl CompileCmd { pub fn run(&self) { let tmp = TempDir::new("ibc-proto").unwrap(); Self::output_sdk_version(&self.sdk, tmp.as_ref()); Self::compile_protos(&self.sdk, tmp.as_ref()); Self::compile_proto_services(&self.sdk, &tmp.as_ref()); Self::copy_generated_files(tmp.as_ref(), &self.out); } fn output_sdk_version(sdk_dir: &Path, out_dir: &Path) { let repo = Repository::open(sdk_dir).unwrap(); let commit = repo.head().unwrap(); let rev = commit.shorthand().unwrap(); let path = out_dir.join("COSMOS_SDK_COMMIT"); std::fs::write(path, rev).unwrap(); } fn compile_protos(sdk_dir: &Path, out_dir: &Path) { println!( "[info ] Compiling .proto files to Rust into '{}'...", out_dir.display() ); let root = env!("CARGO_MANIFEST_DIR"); let proto_paths = [ format!("{}/../proto/definitions/mock", root), format!("{}/proto/ibc", sdk_dir.display()), format!("{}/proto/cosmos/tx", sdk_dir.display()), format!("{}/proto/cosmos/base", sdk_dir.display()), format!("{}/proto/cosmos/staking", sdk_dir.display()), ]; let proto_includes_paths = [ format!("{}/../proto", root), format!("{}/proto", sdk_dir.display()), format!("{}/third_party/proto", sdk_dir.display()), ]; let mut protos: Vec<PathBuf> = vec![]; for proto_path in &proto_paths { protos.append( &mut WalkDir::new(proto_path) .into_iter() .filter_map(|e| e.ok()) .filter(|e| { e.file_type().is_file() && e.path().extension().is_some() && e.path().extension().unwrap() == "proto" }) .map(|e| e.into_path()) .collect(), ); } let includes: Vec<PathBuf> = proto_includes_paths.iter().map(PathBuf::from).collect(); let mut config = prost_build::Config::default(); config.out_dir(out_dir); config.extern_path(".tendermint", "::tendermint_proto"); config.compile_protos(&protos, &includes).unwrap(); } fn compile_proto_services(sdk_dir: impl AsRef<Path>, out_dir: impl AsRef<Path>) { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let sdk_dir = sdk_dir.as_ref().to_owned(); let proto_includes_paths = [ root.join("../proto"), sdk_dir.join("proto"), sdk_dir.join("third_party/proto"), ]; let includes = proto_includes_paths.iter().map(|p| p.as_os_str().to_os_string()).collect::<Vec<_>>(); let proto_services_path = [ sdk_dir.join("proto/cosmos/auth/v1beta1/query.proto"), sdk_dir.join("proto/cosmos/staking/v1beta1/query.proto"), ]; let services = proto_services_path.iter().map(|p| p.as_os_str().to_os_string()).collect::<Vec<_>>(); println!("[info ] Compiling proto clients for GRPC services!"); tonic_build::configure() .build_client(true) .build_server(false) .format(false) .out_dir(out_dir) .compile(&services, &includes).unwrap(); println!("[info ] => Done!"); } fn copy_generated_files(from_dir: &Path, to_dir: &Path) { println!( "[info ] Copying generated files into '{}'...", to_dir.display() ); remove_dir_all(&to_dir).unwrap_or_default(); create_dir_all(&to_dir).unwrap(); let errors = WalkDir::new(from_dir) .into_iter() .filter_map(|e| e.ok()) .filter(|e| e.file_type().is_file()) .map(|e| { copy( e.path(), format!( "{}/{}", to_dir.display(), &e.file_name().to_os_string().to_str().unwrap() ), ) }) .filter_map(|e| e.err()) .collect::<Vec<_>>(); if !errors.is_empty() { for e in errors { println!("[error] Error while copying compiled file: {}", e); } panic!("[error] Aborted."); } } }
use std::fs::remove_dir_all; use std::fs::{copy, create_dir_all}; use std::path::{Path, PathBuf}; use git2::Repository; use tempdir::TempDir; use walkdir::WalkDir; use argh::FromArgs; #[derive(Debug, FromArgs)] #[argh(subcommand, name = "compile")] pub struct CompileCmd { #[argh(option, short = 's')] sdk: PathBuf, #[argh(option, short = 'o')] out: PathBuf, } impl CompileCmd { pub fn run(&self) { let tmp = TempDir::new("ibc-proto").unwrap(); Self::output_sdk_version(&self.sdk, tmp.as_ref()); Self::compile_protos(&self.sdk, tmp.as_ref()); Self::compile_proto_services(&self.sdk, &tmp.as_ref()); Self::copy_generated_files(tmp.as_ref(), &self.out); } fn output_sdk_version(sdk_dir: &Path, out_dir: &Path) { let repo = Repository::open(sdk_dir).unwrap(); let commit = repo.head().unwrap(); let rev = commit.shorthand().unwrap(); let path = out_dir.join("COSMOS_SDK_COMMIT"); std::fs::write(path, rev).unwrap(); } fn compile_protos(sdk_dir: &Path, out_dir: &Path) { println!( "[info ] Compiling .proto files to Rust into '{}'...", out_dir.display() ); let root = env!("CARGO_MANIFEST_DIR"); let proto_paths = [ format!("{}/../proto/definitions/mock", root), format!("{}/proto/ibc", sdk_dir.display()), format!("{}/proto/cosmos/tx", sdk_dir.display()), format!("{}/proto/cosmos/base", sdk_dir.display()), format!("{}/proto/cosmos/staking", sdk_dir.display()), ]; let proto_includes_paths = [ format!("{}/../proto", root), format!("{}/proto", sdk_dir.display()), format!("{}/third_party/proto", sdk_dir.display()), ]; let mut protos: Vec<PathBuf> = vec![]; for proto_path in &proto_paths { protos.append( &mut WalkDir::new(proto_path) .into_iter() .filter_map(|e| e.ok()) .filter(|e| { e.file_type().is_file() && e.path().extension().is_some() && e.path().extension().unwrap() == "proto" }) .map(|e| e.into_path()) .collect(), ); } let includes: Vec<PathBuf> = proto_includes_paths.iter().map(PathBuf::from).collect(); let mut config = prost_build::Config::default(); config.out_dir(out_dir); config.extern_path(".tendermint", "::tendermint_proto"); config.compile_protos(&protos, &includes).unwrap(); } fn compile_proto_services(sdk_dir: impl AsRef<Path>, out_dir: impl AsRef<Path>) { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let sdk_dir = sdk_dir.as_ref().to_owned(); let proto_includes_paths = [ root.join("../proto"), sdk_dir.join("proto"), sdk_dir.join("third_party/proto"), ]; let includes = proto_includes_paths.iter().map(|p| p.as_os_str().to_os_string()).collect::<Vec<_>>(); let proto_services_path = [ sdk_dir.join("proto/cosmos/auth/v1beta1/query.proto"), sdk_dir.join("proto/cosmos/staking/v1beta1/query.proto"), ]; let services = proto_services_path.iter().map(|p| p.as_os_str().to_os_string()).collect::<Vec<_>>(); println!("[info ] Compiling proto clients for GRPC services!"); tonic_build::configure() .build_client(true) .build_server(false) .format(false) .out_dir(out_dir) .compile(&services, &includes).unwrap(); println!("[info ] => Done!"); } fn copy_generated_files(from_dir: &Path, to_dir: &Path) { println!( "[info ] Copying generated files into '{}'...", to_dir.display() ); remove_dir_all(&to_dir).unwrap_or_default(); create_dir_all(&to_dir).unwrap(); let errors = WalkDir::new(from_dir) .into_iter() .filter_map(|e| e.ok()) .filter(|e| e.file_type().is_file()) .map(|e| {
}) .filter_map(|e| e.err()) .collect::<Vec<_>>(); if !errors.is_empty() { for e in errors { println!("[error] Error while copying compiled file: {}", e); } panic!("[error] Aborted."); } } }
copy( e.path(), format!( "{}/{}", to_dir.display(), &e.file_name().to_os_string().to_str().unwrap() ), )
call_expression
[ { "content": "/// Serialize the given `Config` as TOML to the given config file.\n\npub fn store(config: &Config, path: impl AsRef<Path>) -> Result<(), Error> {\n\n let mut file = if path.as_ref().exists() {\n\n fs::OpenOptions::new().write(true).truncate(true).open(path)\n\n } else {\n\n Fi...
Rust
src/http_client/client_impl.rs
ngi-nix/etebase-rs
33447aa22a2d8d2a93863312d6f61e341682ebfe
use serde::Deserialize; use crate::error::{Error, Result}; pub trait ClientImplementation { fn get(&self, url: &str, auth_token: Option<&str>) -> Response; fn post(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn put(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn patch(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn delete(&self, url: &str, auth_token: Option<&str>) -> Response; } #[derive(Clone)] pub struct Response { bytes: Vec<u8>, status: u16, err: Option<Error>, } impl Response { pub fn new(bytes: Vec<u8>, status: u16) -> Self { Self { bytes, status, err: None, } } pub fn new_err(err: Error) -> Self { Self { bytes: vec![], status: 0, err: Some(err), } } pub fn reset_ok(&mut self, bytes: Vec<u8>, status: u16) { self.bytes = bytes; self.status = status; self.err = None; } pub fn reset_err(&mut self, err: Error) { self.err = Some(err); } pub fn bytes(&self) -> &[u8] { &self.bytes } pub fn status(&self) -> u16 { self.status } pub fn error_for_status(&self) -> Result<()> { if self.status >= 200 && self.status < 300 { return Ok(()); } #[derive(Deserialize)] struct ErrorResponse<'a> { pub code: Option<&'a str>, pub detail: Option<&'a str>, } let content: ErrorResponse = rmp_serde::from_read_ref(self.bytes()).unwrap_or(ErrorResponse { code: None, detail: None, }); Err(match self.status { 300..=399 => Error::NotFound("Got a redirect - should never happen".to_string()), 401 => Error::Unauthorized(content.detail.unwrap_or("Unauthorized").to_string()), 403 => { Error::PermissionDenied(content.detail.unwrap_or("PermissionDenied").to_string()) } 404 => Error::NotFound(content.detail.unwrap_or("NotFound").to_string()), 409 => Error::Conflict(content.detail.unwrap_or("Conflict").to_string()), 502..=504 => Error::TemporaryServerError( content .detail .unwrap_or("Temporary server error") .to_string(), ), 500..=501 | 505..=599 => { Error::ServerError(content.detail.unwrap_or("Server error").to_string()) } status => Error::Http(format!( "HTTP error {}! Code: '{}'. Detail: '{}'", status, content.code.unwrap_or("null"), content.detail.unwrap_or("null") )), }) } #[deprecated(since = "0.5.1", note = "please use `into_result` instead")] #[allow(clippy::wrong_self_convention)] pub fn as_result(self) -> Result<Self> { self.into_result() } pub fn into_result(self) -> Result<Self> { match self.err { Some(err) => Err(err), None => Ok(self), } } }
use serde::Deserialize; use crate::error::{Error, Result}; pub trait ClientImplementation { fn get(&self, url: &str, auth_token: Option<&str>) -> Response; fn post(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn put(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn patch(&self, url: &str, auth_token: Option<&str>, body: Vec<u8>) -> Response; fn delete(&self, url: &str, auth_token: Option<&str>) -> Response; } #[derive(Clone)] pub struct Response { bytes: Vec<u8>, status: u16, err: Option<Error>, } impl Response { pub fn new(bytes: Vec<u8>, status: u16) -> Self { Self { bytes, status, err: None, } } pub fn new_err(err: Error) -> Self { Self { bytes: vec![], status: 0, err: Some(err), } } pub fn reset_ok(&mut self, bytes: Vec<u8>, status: u16) { self.bytes = bytes; self.status = status; self.err = None; } pub fn reset_err(&mut self, err: Error) { self.err = Some(err); } pub fn bytes(&self) -> &[u8] { &self.bytes } pub fn status(&self) -> u16 { self.status } pub fn error_for_status(&self) -> Result<()> { if self.status >= 200 && self.status < 300 { return Ok(()); } #[derive(Deserialize)] struct ErrorResponse<'a> { pub code: Option<&'a str>, pub detail: Option<&'a str>, } let con
.detail .unwrap_or("Temporary server error") .to_string(), ), 500..=501 | 505..=599 => { Error::ServerError(content.detail.unwrap_or("Server error").to_string()) } status => Error::Http(format!( "HTTP error {}! Code: '{}'. Detail: '{}'", status, content.code.unwrap_or("null"), content.detail.unwrap_or("null") )), }) } #[deprecated(since = "0.5.1", note = "please use `into_result` instead")] #[allow(clippy::wrong_self_convention)] pub fn as_result(self) -> Result<Self> { self.into_result() } pub fn into_result(self) -> Result<Self> { match self.err { Some(err) => Err(err), None => Ok(self), } } }
tent: ErrorResponse = rmp_serde::from_read_ref(self.bytes()).unwrap_or(ErrorResponse { code: None, detail: None, }); Err(match self.status { 300..=399 => Error::NotFound("Got a redirect - should never happen".to_string()), 401 => Error::Unauthorized(content.detail.unwrap_or("Unauthorized").to_string()), 403 => { Error::PermissionDenied(content.detail.unwrap_or("PermissionDenied").to_string()) } 404 => Error::NotFound(content.detail.unwrap_or("NotFound").to_string()), 409 => Error::Conflict(content.detail.unwrap_or("Conflict").to_string()), 502..=504 => Error::TemporaryServerError( content
random
[ { "content": "pub fn derive_key(salt: &[u8], password: &str) -> Result<Vec<u8>> {\n\n let mut key = vec![0; 32];\n\n let salt = &salt[..argon2id13::SALTBYTES];\n\n let salt: &[u8; argon2id13::SALTBYTES] =\n\n to_enc_error!(salt.try_into(), \"Expect salt to be at least 16 bytes\")?;\n\n let pa...
Rust
src/http.rs
mdheller/monolith
625c529cf1409848aa3ce42a74991d0d69c75d88
use regex::Regex; use reqwest::header::{CONTENT_TYPE, USER_AGENT}; use reqwest::{Client, RedirectPolicy}; use std::time::Duration; use url::{ParseError, Url}; use utils::data_to_dataurl; lazy_static! { static ref REGEX_URL: Regex = Regex::new(r"^https?://").unwrap(); } pub fn is_data_url(url: &str) -> Result<bool, String> { match Url::parse(url) { Ok(parsed_url) => Ok(parsed_url.scheme() == "data"), Err(err) => Err(format!("{}", err)), } } pub fn is_valid_url(path: &str) -> bool { REGEX_URL.is_match(path) } pub fn resolve_url(from: &str, to: &str) -> Result<String, ParseError> { let result = if is_valid_url(to) { to.to_string() } else { Url::parse(from)?.join(to)?.to_string() }; Ok(result) } pub fn retrieve_asset( url: &str, as_dataurl: bool, as_mime: &str, opt_user_agent: &str, ) -> Result<String, reqwest::Error> { if is_data_url(&url).unwrap() { Ok(url.to_string()) } else { let client = Client::builder() .redirect(RedirectPolicy::limited(3)) .timeout(Duration::from_secs(10)) .build() .unwrap(); let mut response = client .get(url) .header(USER_AGENT, opt_user_agent) .send() .unwrap(); if as_dataurl { let mut data: Vec<u8> = vec![]; response.copy_to(&mut data)?; let mimetype = if as_mime == "" { response .headers() .get(CONTENT_TYPE) .and_then(|header| header.to_str().ok()) .unwrap_or(&as_mime) } else { as_mime }; Ok(data_to_dataurl(&mimetype, &data)) } else { Ok(response.text().unwrap()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_url() { assert!(is_valid_url("https://www.rust-lang.org/")); assert!(is_valid_url("http://kernel.org")); assert!(!is_valid_url("./index.html")); assert!(!is_valid_url("some-local-page.htm")); assert!(!is_valid_url("ftp://1.2.3.4/www/index.html")); assert!(!is_valid_url( "data:text/html;base64,V2VsY29tZSBUbyBUaGUgUGFydHksIDxiPlBhbDwvYj4h" )); } #[test] fn test_resolve_url() -> Result<(), ParseError> { let resolved_url = resolve_url( "https://www.kernel.org", "../category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" ); let resolved_url = resolve_url( "https://www.kernel.org", "category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" ); let resolved_url = resolve_url( "saved_page.htm", "https://www.kernel.org/category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" ); let resolved_url = resolve_url( "https://www.kernel.org", "//www.kernel.org/theme/images/logos/tux.png", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.kernel.org", "//another-host.org/theme/images/logos/tux.png", )?; assert_eq!( resolved_url.as_str(), "https://another-host.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.kernel.org/category/signatures.html", "/theme/images/logos/tux.png", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.w3schools.com/html/html_iframe.asp", "default.asp", )?; assert_eq!( resolved_url.as_str(), "https://www.w3schools.com/html/default.asp" ); Ok(()) } #[test] fn test_is_data_url() { assert!( is_data_url("data:text/html;base64,V2VsY29tZSBUbyBUaGUgUGFydHksIDxiPlBhbDwvYj4h") .unwrap_or(false) ); assert!(!is_data_url("https://kernel.org").unwrap_or(false)); assert!(!is_data_url("//kernel.org").unwrap_or(false)); } }
use regex::Regex; use reqwest::header::{CONTENT_TYPE, USER_AGENT}; use reqwest::{Client, RedirectPolicy}; use std::time::Duration; use url::{ParseError, Url}; use utils::data_to_dataurl; lazy_static! { static ref REGEX_URL: Regex = Regex::new(r"^https?://").unwrap(); } pub fn is_data_url(url: &str) -> Result<bool, String> { match Url::parse(url) { Ok(parsed_url) => Ok(parsed_url.scheme() == "data"), Err(err) => Err(format!("{}", err)), } } pub fn is_valid_url(path: &str) -> bool { REGEX_URL.is_match(path) } pub fn resolve_url(from: &str, to: &str) -> Result<String, ParseError> { let result = if is_valid_url(to) { to.to_string() } else { Url::parse(from)?.join(to)?.to_string() }; Ok(result) } pub fn retrieve_asset( url: &str, as_dataurl: bool, as_mime: &str, opt_user_agent: &str, ) -> Result<String, reqwest::Error> { if is_data_url(&url).unwrap() { Ok(url.to_string()) } else { let client = Client::builder() .redirect(RedirectPolicy::limited(3)) .timeout(Duration::from_secs(10)) .build() .unwrap(); let mut response = client .get(url) .header(USER_AGENT, opt_user_agent) .send() .unwrap(); if as_dataurl { let mut data: Vec<u8> = vec![]; response.copy_to(&mut data)?; let mimetype = if as_mime == "" { response .headers() .get(CONTENT_TYPE) .and_then(|header| header.to_str().ok()) .unwrap_or(&as_mime) } else { as_mime }; Ok(data_to_dataurl(&mimetype, &data)) } else { Ok(response.text().unwrap()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_url() { assert!(is_valid_url("https://www.rust-lang.org/")); assert!(is_valid_url("http://kernel.org")); assert!(!is_valid_url("./index.html")); assert!(!is_valid_url("some-local-page.htm")); assert!(!is_valid_url("ftp://1.2.3.4/www/index.html")); assert!(!is_valid_url( "data:text/html;base64,V2VsY29tZSBUbyBUaGUgUGFydHksIDxiPlBhbDwvYj4h" )); } #[test] fn test_resolve_url() -> Result<(), ParseError> { let resolved_url = resolve_url( "https://www.kernel.org", "../category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" ); let resolved_url = resolve_url( "https://www.kernel.org", "category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" ); let resolved_url = resolve_url( "saved_page.htm", "https://www.kernel.org/category/signatures.html", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/category/signatures.html" );
assert_eq!( resolved_url.as_str(), "https://www.kernel.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.kernel.org", "//another-host.org/theme/images/logos/tux.png", )?; assert_eq!( resolved_url.as_str(), "https://another-host.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.kernel.org/category/signatures.html", "/theme/images/logos/tux.png", )?; assert_eq!( resolved_url.as_str(), "https://www.kernel.org/theme/images/logos/tux.png" ); let resolved_url = resolve_url( "https://www.w3schools.com/html/html_iframe.asp", "default.asp", )?; assert_eq!( resolved_url.as_str(), "https://www.w3schools.com/html/default.asp" ); Ok(()) } #[test] fn test_is_data_url() { assert!( is_data_url("data:text/html;base64,V2VsY29tZSBUbyBUaGUgUGFydHksIDxiPlBhbDwvYj4h") .unwrap_or(false) ); assert!(!is_data_url("https://kernel.org").unwrap_or(false)); assert!(!is_data_url("//kernel.org").unwrap_or(false)); } }
let resolved_url = resolve_url( "https://www.kernel.org", "//www.kernel.org/theme/images/logos/tux.png", )?;
assignment_statement
[ { "content": "pub fn data_to_dataurl(mime: &str, data: &[u8]) -> String {\n\n let mimetype = if mime == \"\" {\n\n detect_mimetype(data)\n\n } else {\n\n mime.to_string()\n\n };\n\n format!(\"data:{};base64,{}\", mimetype, encode(data))\n\n}\n\n\n", "file_path": "src/utils.rs", ...
Rust
src/board/builder.rs
veeso/chess-engine-harmon
463474a593e10695281309293677f2d96a06ddd6
use super::{Board, Color, Piece, Square, BLACK, WHITE}; pub struct BoardBuilder { board: Board, } impl From<Board> for BoardBuilder { fn from(board: Board) -> Self { Self { board } } } impl Default for BoardBuilder { fn default() -> Self { let mut board = Board::empty(); board.white_castling_rights.disable_all(); board.black_castling_rights.disable_all(); Self { board } } } impl BoardBuilder { pub fn row(mut self, piece: Piece) -> Self { let mut pos = piece.get_pos(); while pos.get_col() > 0 { pos = pos.next_left() } for _ in 0..8 { *self.board.get_square(pos) = Square::from(piece.move_to(pos)); pos = pos.next_right(); } self } pub fn column(mut self, piece: Piece) -> Self { let mut pos = piece.get_pos(); while pos.get_row() > 0 { pos = pos.next_below() } for _ in 0..8 { *self.board.get_square(pos) = Square::from(piece.move_to(pos)); pos = pos.next_above(); } self } pub fn piece(mut self, piece: Piece) -> Self { let pos = piece.get_pos(); *self.board.get_square(pos) = Square::from(piece); self } pub fn enable_castling(mut self) -> Self { self.board.black_castling_rights.enable_all(); self.board.white_castling_rights.enable_all(); self } pub fn disable_castling(mut self) -> Self { self.board.black_castling_rights.disable_all(); self.board.white_castling_rights.disable_all(); self } pub fn enable_queenside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.enable_queenside(), BLACK => self.board.black_castling_rights.enable_queenside(), } self } pub fn disable_queenside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.disable_queenside(), BLACK => self.board.black_castling_rights.disable_queenside(), } self } pub fn enable_kingside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.enable_kingside(), BLACK => self.board.black_castling_rights.enable_kingside(), } self } pub fn disable_kingside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.disable_kingside(), BLACK => self.board.black_castling_rights.disable_kingside(), } self } pub fn player_moving(mut self, color: Color) -> Self { self.board.turn = color; self } pub fn build(self) -> Board { self.board } } #[cfg(test)] mod test { use super::*; use crate::position::*; use crate::{BLACK, WHITE}; use pretty_assertions::assert_eq; #[test] fn default() { let builder: BoardBuilder = BoardBuilder::default(); assert_eq!(builder.board.get_legal_moves(WHITE).is_empty(), true); assert_eq!(builder.board.get_legal_moves(BLACK).is_empty(), true); assert_eq!( builder.board.black_castling_rights.can_kingside_castle(), false ); assert_eq!( builder.board.black_castling_rights.can_queenside_castle(), false ); assert_eq!( builder.board.white_castling_rights.can_kingside_castle(), false ); assert_eq!( builder.board.white_castling_rights.can_queenside_castle(), false ); } #[test] fn from() { let builder: BoardBuilder = BoardBuilder::from(Board::default()); assert_eq!(builder.board.get_legal_moves(WHITE).len(), 20); assert_eq!(builder.board.get_legal_moves(BLACK).len(), 20); assert_eq!( builder.board.black_castling_rights.can_kingside_castle(), true ); assert_eq!( builder.board.black_castling_rights.can_queenside_castle(), true ); assert_eq!( builder.board.white_castling_rights.can_kingside_castle(), true ); assert_eq!( builder.board.white_castling_rights.can_queenside_castle(), true ); } #[test] fn row() { let board: Board = BoardBuilder::default().row(Piece::Queen(WHITE, A1)).build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Queen(WHITE, A1)); assert_eq!(board.get_piece(B1).unwrap(), Piece::Queen(WHITE, B1)); assert_eq!(board.get_piece(C1).unwrap(), Piece::Queen(WHITE, C1)); assert_eq!(board.get_piece(D1).unwrap(), Piece::Queen(WHITE, D1)); assert_eq!(board.get_piece(E1).unwrap(), Piece::Queen(WHITE, E1)); assert_eq!(board.get_piece(F1).unwrap(), Piece::Queen(WHITE, F1)); assert_eq!(board.get_piece(G1).unwrap(), Piece::Queen(WHITE, G1)); assert_eq!(board.get_piece(H1).unwrap(), Piece::Queen(WHITE, H1)); } #[test] fn col() { let board: Board = BoardBuilder::default() .column(Piece::Queen(WHITE, A1)) .build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Queen(WHITE, A1)); assert_eq!(board.get_piece(A2).unwrap(), Piece::Queen(WHITE, A2)); assert_eq!(board.get_piece(A3).unwrap(), Piece::Queen(WHITE, A3)); assert_eq!(board.get_piece(A4).unwrap(), Piece::Queen(WHITE, A4)); assert_eq!(board.get_piece(A5).unwrap(), Piece::Queen(WHITE, A5)); assert_eq!(board.get_piece(A6).unwrap(), Piece::Queen(WHITE, A6)); assert_eq!(board.get_piece(A7).unwrap(), Piece::Queen(WHITE, A7)); assert_eq!(board.get_piece(A8).unwrap(), Piece::Queen(WHITE, A8)); } #[test] fn piece() { let board: Board = BoardBuilder::default() .piece(Piece::Rook(WHITE, A1)) .piece(Piece::Rook(BLACK, H8)) .build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Rook(WHITE, A1)); assert_eq!(board.get_piece(H8).unwrap(), Piece::Rook(BLACK, H8)); } #[test] fn player_moving() { let board: Board = BoardBuilder::default().player_moving(BLACK).build(); assert_eq!(board.get_turn(), BLACK); } #[test] fn castling_rights() { let board: Board = BoardBuilder::default().enable_castling().build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_kingside_castle(WHITE) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_kingside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_queenside_castle(WHITE) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_queenside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default().disable_castling().build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_castling() .disable_queenside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_castling() .disable_kingside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); } }
use super::{Board, Color, Piece, Square, BLACK, WHITE}; pub struct BoardBuilder { board: Board, } impl From<Board> for BoardBuilder { fn from(board: Board) -> Self { Self { board } } } impl Default for BoardBuilder {
} impl BoardBuilder { pub fn row(mut self, piece: Piece) -> Self { let mut pos = piece.get_pos(); while pos.get_col() > 0 { pos = pos.next_left() } for _ in 0..8 { *self.board.get_square(pos) = Square::from(piece.move_to(pos)); pos = pos.next_right(); } self } pub fn column(mut self, piece: Piece) -> Self { let mut pos = piece.get_pos(); while pos.get_row() > 0 { pos = pos.next_below() } for _ in 0..8 { *self.board.get_square(pos) = Square::from(piece.move_to(pos)); pos = pos.next_above(); } self } pub fn piece(mut self, piece: Piece) -> Self { let pos = piece.get_pos(); *self.board.get_square(pos) = Square::from(piece); self } pub fn enable_castling(mut self) -> Self { self.board.black_castling_rights.enable_all(); self.board.white_castling_rights.enable_all(); self } pub fn disable_castling(mut self) -> Self { self.board.black_castling_rights.disable_all(); self.board.white_castling_rights.disable_all(); self } pub fn enable_queenside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.enable_queenside(), BLACK => self.board.black_castling_rights.enable_queenside(), } self } pub fn disable_queenside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.disable_queenside(), BLACK => self.board.black_castling_rights.disable_queenside(), } self } pub fn enable_kingside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.enable_kingside(), BLACK => self.board.black_castling_rights.enable_kingside(), } self } pub fn disable_kingside_castle(mut self, color: Color) -> Self { match color { WHITE => self.board.white_castling_rights.disable_kingside(), BLACK => self.board.black_castling_rights.disable_kingside(), } self } pub fn player_moving(mut self, color: Color) -> Self { self.board.turn = color; self } pub fn build(self) -> Board { self.board } } #[cfg(test)] mod test { use super::*; use crate::position::*; use crate::{BLACK, WHITE}; use pretty_assertions::assert_eq; #[test] fn default() { let builder: BoardBuilder = BoardBuilder::default(); assert_eq!(builder.board.get_legal_moves(WHITE).is_empty(), true); assert_eq!(builder.board.get_legal_moves(BLACK).is_empty(), true); assert_eq!( builder.board.black_castling_rights.can_kingside_castle(), false ); assert_eq!( builder.board.black_castling_rights.can_queenside_castle(), false ); assert_eq!( builder.board.white_castling_rights.can_kingside_castle(), false ); assert_eq!( builder.board.white_castling_rights.can_queenside_castle(), false ); } #[test] fn from() { let builder: BoardBuilder = BoardBuilder::from(Board::default()); assert_eq!(builder.board.get_legal_moves(WHITE).len(), 20); assert_eq!(builder.board.get_legal_moves(BLACK).len(), 20); assert_eq!( builder.board.black_castling_rights.can_kingside_castle(), true ); assert_eq!( builder.board.black_castling_rights.can_queenside_castle(), true ); assert_eq!( builder.board.white_castling_rights.can_kingside_castle(), true ); assert_eq!( builder.board.white_castling_rights.can_queenside_castle(), true ); } #[test] fn row() { let board: Board = BoardBuilder::default().row(Piece::Queen(WHITE, A1)).build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Queen(WHITE, A1)); assert_eq!(board.get_piece(B1).unwrap(), Piece::Queen(WHITE, B1)); assert_eq!(board.get_piece(C1).unwrap(), Piece::Queen(WHITE, C1)); assert_eq!(board.get_piece(D1).unwrap(), Piece::Queen(WHITE, D1)); assert_eq!(board.get_piece(E1).unwrap(), Piece::Queen(WHITE, E1)); assert_eq!(board.get_piece(F1).unwrap(), Piece::Queen(WHITE, F1)); assert_eq!(board.get_piece(G1).unwrap(), Piece::Queen(WHITE, G1)); assert_eq!(board.get_piece(H1).unwrap(), Piece::Queen(WHITE, H1)); } #[test] fn col() { let board: Board = BoardBuilder::default() .column(Piece::Queen(WHITE, A1)) .build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Queen(WHITE, A1)); assert_eq!(board.get_piece(A2).unwrap(), Piece::Queen(WHITE, A2)); assert_eq!(board.get_piece(A3).unwrap(), Piece::Queen(WHITE, A3)); assert_eq!(board.get_piece(A4).unwrap(), Piece::Queen(WHITE, A4)); assert_eq!(board.get_piece(A5).unwrap(), Piece::Queen(WHITE, A5)); assert_eq!(board.get_piece(A6).unwrap(), Piece::Queen(WHITE, A6)); assert_eq!(board.get_piece(A7).unwrap(), Piece::Queen(WHITE, A7)); assert_eq!(board.get_piece(A8).unwrap(), Piece::Queen(WHITE, A8)); } #[test] fn piece() { let board: Board = BoardBuilder::default() .piece(Piece::Rook(WHITE, A1)) .piece(Piece::Rook(BLACK, H8)) .build(); assert_eq!(board.get_piece(A1).unwrap(), Piece::Rook(WHITE, A1)); assert_eq!(board.get_piece(H8).unwrap(), Piece::Rook(BLACK, H8)); } #[test] fn player_moving() { let board: Board = BoardBuilder::default().player_moving(BLACK).build(); assert_eq!(board.get_turn(), BLACK); } #[test] fn castling_rights() { let board: Board = BoardBuilder::default().enable_castling().build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_kingside_castle(WHITE) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_kingside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_queenside_castle(WHITE) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_queenside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default().disable_castling().build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), false); assert_eq!(board.white_castling_rights.can_queenside_castle(), false); let board: Board = BoardBuilder::default() .enable_castling() .disable_queenside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), true); assert_eq!(board.black_castling_rights.can_queenside_castle(), false); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); let board: Board = BoardBuilder::default() .enable_castling() .disable_kingside_castle(BLACK) .build(); assert_eq!(board.black_castling_rights.can_kingside_castle(), false); assert_eq!(board.black_castling_rights.can_queenside_castle(), true); assert_eq!(board.white_castling_rights.can_kingside_castle(), true); assert_eq!(board.white_castling_rights.can_queenside_castle(), true); } }
fn default() -> Self { let mut board = Board::empty(); board.white_castling_rights.disable_all(); board.black_castling_rights.disable_all(); Self { board } }
function_block-function_prefix_line
[ { "content": "/// ### was_illegal_move\n\n///\n\n/// Returns whether game result was an illegal move\n\npub fn was_illegal_move(res: &GameResult) -> bool {\n\n matches!(res, Err(GameError::IllegalMove(_)))\n\n}\n\n\n", "file_path": "src/game/result.rs", "rank": 0, "score": 43371.68225817752 }, ...
Rust
src/direction.rs
jack-atack/Cursive
fc065e8e589c24dfa7906d9423c7b63fee095e23
use crate::vec::Vec2; use crate::XY; #[derive(Clone, Copy, Debug, PartialEq)] pub enum Orientation { Horizontal, Vertical, } impl Orientation { pub fn pair() -> XY<Orientation> { XY::new(Orientation::Horizontal, Orientation::Vertical) } pub fn get<T: Clone>(self, v: &XY<T>) -> T { v.get(self).clone() } pub fn swap(self) -> Self { match self { Orientation::Horizontal => Orientation::Vertical, Orientation::Vertical => Orientation::Horizontal, } } pub fn get_ref<T>(self, v: &mut XY<T>) -> &mut T { match self { Orientation::Horizontal => &mut v.x, Orientation::Vertical => &mut v.y, } } pub fn stack<'a, T: Iterator<Item = &'a Vec2>>(self, iter: T) -> Vec2 { match self { Orientation::Horizontal => { iter.fold(Vec2::zero(), |a, b| a.stack_horizontal(b)) } Orientation::Vertical => { iter.fold(Vec2::zero(), |a, b| a.stack_vertical(b)) } } } pub fn make_vec(self, main_axis: usize, second_axis: usize) -> Vec2 { let mut result = Vec2::zero(); *self.get_ref(&mut result) = main_axis; *self.swap().get_ref(&mut result) = second_axis; result } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Direction { Abs(Absolute), Rel(Relative), } impl Direction { pub fn relative(self, orientation: Orientation) -> Option<Relative> { match self { Direction::Abs(abs) => abs.relative(orientation), Direction::Rel(rel) => Some(rel), } } pub fn absolute(self, orientation: Orientation) -> Absolute { match self { Direction::Abs(abs) => abs, Direction::Rel(rel) => rel.absolute(orientation), } } pub fn back() -> Self { Direction::Rel(Relative::Back) } pub fn front() -> Self { Direction::Rel(Relative::Front) } pub fn left() -> Self { Direction::Abs(Absolute::Left) } pub fn right() -> Self { Direction::Abs(Absolute::Right) } pub fn up() -> Self { Direction::Abs(Absolute::Up) } pub fn down() -> Self { Direction::Abs(Absolute::Down) } pub fn none() -> Self { Direction::Abs(Absolute::None) } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Relative { Front, Back, } impl Relative { pub fn absolute(self, orientation: Orientation) -> Absolute { match (orientation, self) { (Orientation::Horizontal, Relative::Front) => Absolute::Left, (Orientation::Horizontal, Relative::Back) => Absolute::Right, (Orientation::Vertical, Relative::Front) => Absolute::Up, (Orientation::Vertical, Relative::Back) => Absolute::Down, } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Absolute { Left, Up, Right, Down, None, } impl Absolute { pub fn relative(self, orientation: Orientation) -> Option<Relative> { match (orientation, self) { (Orientation::Horizontal, Absolute::Left) | (Orientation::Vertical, Absolute::Up) => Some(Relative::Front), (Orientation::Horizontal, Absolute::Right) | (Orientation::Vertical, Absolute::Down) => Some(Relative::Back), _ => None, } } }
use crate::vec::Vec2; use crate::XY; #[derive(Clone, Copy, Debug, PartialEq)] pub enum Orientation { Horizontal, Vertical, } impl Orientation { pub fn pair() -> XY<Orientation> { XY::new(Orientation::Horizontal, Orientation::Vertical) } pub fn get<T: Clone>(self, v: &XY<T>) -> T { v.get(self).clone() } pub fn swap(self) -> Self { match self { Orientation::Horizontal => Orientation::Vertical, Orientation::Vertical => Orientation::Horizontal, } } pub fn get_ref<T>(self, v: &mut XY<T>) -> &mut T { match self { Orientation::Horizontal => &mut v.x, Orientation::Vertical => &mut v.y, } } pub fn stack<'a, T: Iterator<Item = &'a Vec2>>(self, iter: T) -> Vec2 { match self { Orientation::Horizontal => { iter.fold(Vec2::zero(), |a, b| a.stack_horizontal(b)) } Orientation::Vertical => { iter.fold(Vec2::zero(), |a, b| a.stack_vertical(b)) } } } pub fn make_vec(self, main_axis: usize, second_axis: usize) -> Vec2 { let mut result = Vec2::zero(); *self.get_ref(&mut result) = main_axis; *self.swap().get_ref(&mut result) = second_axis; result } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Direction { Abs(Absolute), Rel(Relative), } impl Direction { pub fn relative(self, orientation: Orientation) -> Option<Relative> { match self { Direction::Abs(abs) => abs.relative(orientation), Direction::Rel(rel) => Some(rel), } } pub fn absolute(self, orientation: Orientation) -> Absolute { match self { Direction::Abs(abs) => abs, Direction::Rel(rel) => rel.absolute(orientation), } } pub fn back() -> Self { Direction::Rel(Relative::Back) } pub fn front() -> Self { Direction::Rel(Relative::Front) } pub fn left() -> Self { Direction::Abs(Absolute::Left) } pub fn right() -> Self { Direction::Abs(Absolute::Right) } pub fn up() -> Self { Direction::Abs(Absolute::Up) } pub fn down() -> Self { Direction::Abs(Absolute::Down) } pub fn none() -> Self { Direction::Abs(Absolute::None) } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Relative { Front, Back, } impl Relative { pub fn absolute(self, orientation: Orientation) -> Absolute { match (orientation, self) { (Orientation::Horizontal, Relative::Front) => Absolute::Left, (Orientation::Horizontal, Relative::Back) => Absolute::Right, (Orientation::Vertical, Relative::Front) => Absolute::Up, (Orientation::Vertical, Relative::Back) => Absolute::Down, } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum Absolute { Left, Up, Right, Down, None, } impl Absolute { pub fn relative(self, orientation: O
n::Horizontal, Absolute::Right) | (Orientation::Vertical, Absolute::Down) => Some(Relative::Back), _ => None, } } }
rientation) -> Option<Relative> { match (orientation, self) { (Orientation::Horizontal, Absolute::Left) | (Orientation::Vertical, Absolute::Up) => Some(Relative::Front), (Orientatio
function_block-random_span
[ { "content": "fn cap<'a, I: Iterator<Item = &'a mut usize>>(iter: I, max: usize) {\n\n let mut available = max;\n\n for item in iter {\n\n if *item > available {\n\n *item = available;\n\n }\n\n\n\n available -= *item;\n\n }\n\n}\n\n\n\nimpl LinearLayout {\n\n /// Cre...
Rust
src/gui/layout.rs
lukexor/pix-engine
447b794d57fcb4e6c5631254857d210c430f0181
use crate::{ops::clamp_size, prelude::*}; impl PixState { #[inline] pub fn same_line<O>(&mut self, offset: O) where O: Into<Option<[i32; 2]>>, { let [x, y] = self.ui.pcursor().as_array(); let offset = offset.into().unwrap_or([0; 2]); let item_pad = self.theme.spacing.item_pad; self.ui .set_cursor([x + item_pad.x() + offset[0], y + offset[1]]); self.ui.line_height = self.ui.pline_height - offset[1]; } #[inline] pub fn next_width(&mut self, width: u32) { self.ui.next_width = Some(clamp_size(width)); } pub fn tab_bar<S, I, F>(&mut self, label: S, tabs: &[I], f: F) -> PixResult<()> where S: AsRef<str>, I: AsRef<str>, F: FnOnce(usize, &mut PixState) -> PixResult<()>, { let label = label.as_ref(); let s = self; let tab_id = s.ui.get_id(&label); let colors = s.theme.colors; let fpad = s.theme.spacing.frame_pad; let ipad = s.theme.spacing.item_pad; for (i, tab_label) in tabs.iter().enumerate() { if i > 0 { s.same_line(None); } let tab_label = tab_label.as_ref(); let id = s.ui.get_id(&tab_label); let tab_label = s.ui.get_label(tab_label); let pos = s.cursor_pos(); let colors = s.theme.colors; let (width, height) = s.text_size(tab_label)?; let tab = rect![pos + fpad.x(), width, height].offset_size(2 * ipad); let hovered = s.ui.try_hover(id, &tab); let focused = s.ui.try_focus(id); let disabled = s.ui.disabled; let active = s.ui.is_active(id); s.push(); s.ui.push_cursor(); s.rect_mode(RectMode::Corner); let clip = tab.offset_size([1, 0]); s.clip(clip)?; if hovered { s.frame_cursor(&Cursor::hand())?; } let [stroke, fg, bg] = s.widget_colors(id, ColorType::SecondaryVariant); if active || focused { s.stroke(stroke); } else { s.no_stroke(); } if hovered { s.fill(fg.blended(colors.background, 0.04)); } else { s.fill(colors.background); } if active { s.rect(tab.offset([1, 1]))?; } else { s.rect(tab)?; } s.no_clip()?; s.rect_mode(RectMode::Center); s.clip(tab)?; s.set_cursor_pos(tab.center()); s.no_stroke(); let is_active_tab = i == s.ui.current_tab(tab_id); if is_active_tab { s.fill(colors.secondary_variant); } else if hovered | focused { s.fill(fg); } else { s.fill(colors.secondary_variant.blended(bg, 0.60)); } s.text(tab_label)?; s.no_clip()?; s.ui.pop_cursor(); s.pop(); s.ui.handle_events(id); s.advance_cursor(tab.size()); if !disabled && s.ui.was_clicked(id) { s.ui.set_current_tab(tab_id, i); } } let pos = s.cursor_pos(); let fpad = s.theme.spacing.frame_pad; s.push(); s.stroke(colors.disabled()); let y = pos.y() + 1; let line_width = s.ui_width()? - fpad.x(); s.line(line_![fpad.x(), y, line_width, y])?; s.pop(); s.advance_cursor([line_width, fpad.y()]); s.push_id(tab_id); f(s.ui.current_tab(tab_id), s)?; s.pop_id(); Ok(()) } } impl PixState { pub fn spacing(&mut self) -> PixResult<()> { let s = self; let width = s.ui_width()?; let (_, height) = s.text_size(" ")?; s.advance_cursor([width, height]); Ok(()) } pub fn indent(&mut self) -> PixResult<()> { let s = self; let (width, height) = s.text_size(" ")?; s.advance_cursor([width, height]); s.same_line(None); Ok(()) } pub fn separator(&mut self) -> PixResult<()> { let s = self; let pos = s.cursor_pos(); let colors = s.theme.colors; let pad = s.theme.spacing.frame_pad; let height = clamp_size(s.theme.font_size); let y = pos.y() + height / 2; s.push(); s.stroke(colors.disabled()); let width = s.ui_width()?; s.line(line_![pad.x(), y, width, y])?; s.pop(); s.advance_cursor([width, height]); Ok(()) } }
use crate::{ops::clamp_size, prelude::*}; impl PixState { #[inline] pub fn same_line<O>(&mut self, offset: O) where O: Into<Option<[i32; 2]>>, { let [x, y] = self.ui.pcursor().as_array(); let offset = offset.into().unwrap_or([0; 2]); let item_pad = self.theme.spacing.item_pad; self.ui .set_cursor([x + item_pad.x() + offset[0], y + offset[1]]); self.ui.line_height = self.ui.pline_height - offset[1]; } #[inline] pub fn next_width(&mut self, width: u32) { self.ui.next_width = Some(clamp_size(width)); }
} impl PixState { pub fn spacing(&mut self) -> PixResult<()> { let s = self; let width = s.ui_width()?; let (_, height) = s.text_size(" ")?; s.advance_cursor([width, height]); Ok(()) } pub fn indent(&mut self) -> PixResult<()> { let s = self; let (width, height) = s.text_size(" ")?; s.advance_cursor([width, height]); s.same_line(None); Ok(()) } pub fn separator(&mut self) -> PixResult<()> { let s = self; let pos = s.cursor_pos(); let colors = s.theme.colors; let pad = s.theme.spacing.frame_pad; let height = clamp_size(s.theme.font_size); let y = pos.y() + height / 2; s.push(); s.stroke(colors.disabled()); let width = s.ui_width()?; s.line(line_![pad.x(), y, width, y])?; s.pop(); s.advance_cursor([width, height]); Ok(()) } }
pub fn tab_bar<S, I, F>(&mut self, label: S, tabs: &[I], f: F) -> PixResult<()> where S: AsRef<str>, I: AsRef<str>, F: FnOnce(usize, &mut PixState) -> PixResult<()>, { let label = label.as_ref(); let s = self; let tab_id = s.ui.get_id(&label); let colors = s.theme.colors; let fpad = s.theme.spacing.frame_pad; let ipad = s.theme.spacing.item_pad; for (i, tab_label) in tabs.iter().enumerate() { if i > 0 { s.same_line(None); } let tab_label = tab_label.as_ref(); let id = s.ui.get_id(&tab_label); let tab_label = s.ui.get_label(tab_label); let pos = s.cursor_pos(); let colors = s.theme.colors; let (width, height) = s.text_size(tab_label)?; let tab = rect![pos + fpad.x(), width, height].offset_size(2 * ipad); let hovered = s.ui.try_hover(id, &tab); let focused = s.ui.try_focus(id); let disabled = s.ui.disabled; let active = s.ui.is_active(id); s.push(); s.ui.push_cursor(); s.rect_mode(RectMode::Corner); let clip = tab.offset_size([1, 0]); s.clip(clip)?; if hovered { s.frame_cursor(&Cursor::hand())?; } let [stroke, fg, bg] = s.widget_colors(id, ColorType::SecondaryVariant); if active || focused { s.stroke(stroke); } else { s.no_stroke(); } if hovered { s.fill(fg.blended(colors.background, 0.04)); } else { s.fill(colors.background); } if active { s.rect(tab.offset([1, 1]))?; } else { s.rect(tab)?; } s.no_clip()?; s.rect_mode(RectMode::Center); s.clip(tab)?; s.set_cursor_pos(tab.center()); s.no_stroke(); let is_active_tab = i == s.ui.current_tab(tab_id); if is_active_tab { s.fill(colors.secondary_variant); } else if hovered | focused { s.fill(fg); } else { s.fill(colors.secondary_variant.blended(bg, 0.60)); } s.text(tab_label)?; s.no_clip()?; s.ui.pop_cursor(); s.pop(); s.ui.handle_events(id); s.advance_cursor(tab.size()); if !disabled && s.ui.was_clicked(id) { s.ui.set_current_tab(tab_id, i); } } let pos = s.cursor_pos(); let fpad = s.theme.spacing.frame_pad; s.push(); s.stroke(colors.disabled()); let y = pos.y() + 1; let line_width = s.ui_width()? - fpad.x(); s.line(line_![fpad.x(), y, line_width, y])?; s.pop(); s.advance_cursor([line_width, fpad.y()]); s.push_id(tab_id); f(s.ui.current_tab(tab_id), s)?; s.pop_id(); Ok(()) }
function_block-full_function
[ { "content": "pub fn main() -> PixResult<()> {\n\n let mut engine = PixEngine::builder()\n\n .with_dimensions(WIDTH, HEIGHT)\n\n .with_title(\"Colors\")\n\n .with_frame_rate()\n\n .build()?;\n\n let mut app = Colors::new();\n\n engine.run(&mut app)\n\n}\n", "file_path": ...
Rust
PLs/Rust/Slns/Simple-Windows-RS-Window/src/main.rs
QubitTooLate/How-To-Make-A-Win32-Window
2593bf0192bc361490a957eb3b6b5d2c23bed11b
use bindings::{ Windows::Win32::{ Foundation::*, UI::WindowsAndMessaging::*, System::LibraryLoader::{ GetModuleHandleA, }, }, }; use windows::*; fn main() -> Result<()> { let mut window = Win3Window::new()?; window.run() } struct Win3Window { handle: HWND } impl Win3Window { fn new() -> Result<Self> { Ok(Win3Window { handle: HWND(0) }) } fn procedure(&mut self, window_handle: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT { unsafe { match message { WM_CLOSE => { DestroyWindow(window_handle); LRESULT(0) } WM_DESTROY => { PostQuitMessage(0); LRESULT(0) } _ => DefWindowProcA(window_handle, message, w, l), } } } fn run(&mut self) -> Result<()> { unsafe { let instance = GetModuleHandleA(None); debug_assert!(instance.0 != 0); let wc = WNDCLASSA { hCursor: LoadCursorW(None, IDC_ARROW), hInstance: instance, lpszClassName: PSTR(b"window\0".as_ptr() as _), lpfnWndProc: Some(Self::window_procedure), ..Default::default() }; let atom = RegisterClassA(&wc); debug_assert!(atom != 0); let handle = CreateWindowExA( Default::default(), "window", "Sample Window", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, None, None, instance, self as *mut _ as _, ); debug_assert!(handle.0 != 0); debug_assert!(handle == self.handle); let mut msg = MSG::default(); /*while msg.message != WM_QUIT { if PeekMessageA(&mut msg, None, 0, 0, PM_REMOVE).into() { DispatchMessageA(&msg); } else { let result = self.no_message_handler(); if result.is_err() { return result; } } }*/ while GetMessageA(&mut msg, None, 0, 0).into() { DispatchMessageA(&msg); } Ok(()) } } /*fn no_message_handler(&mut self) -> Result<()> { Ok(()) }*/ extern "system" fn window_procedure( window_handle: HWND, message: u32, w: WPARAM, l: LPARAM, ) -> LRESULT { unsafe { let this : *mut Self; if message == WM_NCCREATE { let create_struct = l.0 as *const CREATESTRUCTA; this = (*create_struct).lpCreateParams as *mut Self; (*this).handle = window_handle; SetWindowLong(window_handle, GWLP_USERDATA, this as _); } else { this = GetWindowLong(window_handle, GWLP_USERDATA) as *mut Self; } if !this.is_null() { return (*this).procedure(window_handle, message, w, l); } DefWindowProcA(window_handle, message, w, l) } } } #[allow(non_snake_case)] #[cfg(target_pointer_width = "32")] unsafe fn SetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize { SetWindowLongA(window, index, value as _) as _ } #[allow(non_snake_case)] #[cfg(target_pointer_width = "64")] unsafe fn SetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize { SetWindowLongPtrA(window, index, value) } #[allow(non_snake_case)] #[cfg(target_pointer_width = "32")] unsafe fn GetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize { GetWindowLongA(window, index) as _ } #[allow(non_snake_case)] #[cfg(target_pointer_width = "64")] unsafe fn GetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize { GetWindowLongPtrA(window, index) }
use bindings::{ Windows::Win32::{ Foundation::*, UI::WindowsAndMessaging::*, System::LibraryLoader::{ GetModuleHandleA, }, }, }; use windows::*; fn main() -> Result<()> { let mut window = Win3Window::new()?; window.run() } struct Win3Window { handle: HWND } impl Win3Window { fn new() -> Result<Self> { Ok(Win3Window { handle: HWND(0) }) } fn procedure(&mut self, window_handle: HWND, message: u32, w: WPARAM, l: LPARAM) -> LRESULT { unsafe { match message { WM_CLOSE => { DestroyWindow(window_handle);
handle, message, w, l); } DefWindowProcA(window_handle, message, w, l) } } } #[allow(non_snake_case)] #[cfg(target_pointer_width = "32")] unsafe fn SetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize { SetWindowLongA(window, index, value as _) as _ } #[allow(non_snake_case)] #[cfg(target_pointer_width = "64")] unsafe fn SetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX, value: isize) -> isize { SetWindowLongPtrA(window, index, value) } #[allow(non_snake_case)] #[cfg(target_pointer_width = "32")] unsafe fn GetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize { GetWindowLongA(window, index) as _ } #[allow(non_snake_case)] #[cfg(target_pointer_width = "64")] unsafe fn GetWindowLong(window: HWND, index: WINDOW_LONG_PTR_INDEX) -> isize { GetWindowLongPtrA(window, index) }
LRESULT(0) } WM_DESTROY => { PostQuitMessage(0); LRESULT(0) } _ => DefWindowProcA(window_handle, message, w, l), } } } fn run(&mut self) -> Result<()> { unsafe { let instance = GetModuleHandleA(None); debug_assert!(instance.0 != 0); let wc = WNDCLASSA { hCursor: LoadCursorW(None, IDC_ARROW), hInstance: instance, lpszClassName: PSTR(b"window\0".as_ptr() as _), lpfnWndProc: Some(Self::window_procedure), ..Default::default() }; let atom = RegisterClassA(&wc); debug_assert!(atom != 0); let handle = CreateWindowExA( Default::default(), "window", "Sample Window", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, None, None, instance, self as *mut _ as _, ); debug_assert!(handle.0 != 0); debug_assert!(handle == self.handle); let mut msg = MSG::default(); /*while msg.message != WM_QUIT { if PeekMessageA(&mut msg, None, 0, 0, PM_REMOVE).into() { DispatchMessageA(&msg); } else { let result = self.no_message_handler(); if result.is_err() { return result; } } }*/ while GetMessageA(&mut msg, None, 0, 0).into() { DispatchMessageA(&msg); } Ok(()) } } /*fn no_message_handler(&mut self) -> Result<()> { Ok(()) }*/ extern "system" fn window_procedure( window_handle: HWND, message: u32, w: WPARAM, l: LPARAM, ) -> LRESULT { unsafe { let this : *mut Self; if message == WM_NCCREATE { let create_struct = l.0 as *const CREATESTRUCTA; this = (*create_struct).lpCreateParams as *mut Self; (*this).handle = window_handle; SetWindowLong(window_handle, GWLP_USERDATA, this as _); } else { this = GetWindowLong(window_handle, GWLP_USERDATA) as *mut Self; } if !this.is_null() { return (*this).procedure(window_
random
[]
Rust
lamp_asm_parser/src/lexer.rs
ElFamosoKilluaah/lamp
4a879129118a798de6d2ba05b5e39a0f0663649b
use lamp_common::op::{get_op, Opcode}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { Opcode(Opcode), Num8(u8), Ptr8(u8), } #[derive(Debug)] pub enum LexerError { UnexpectedToken(usize, String), InvalidMnemonic(usize, String), InvalidLine(usize), } impl std::fmt::Display for LexerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { /* at + 1 because at is an array/vec index */ Self::InvalidLine(at) => { write!(f, "Line {} contains one or more invalid tokens", at + 1) } Self::UnexpectedToken(at, tkn) => { write!(f, "Unexpected token at line {}: \'{}\'", at + 1, tkn) } Self::InvalidMnemonic(at, mnemonic) => { write!(f, "Invalid mnemonic at line {}: \'{}\'", at + 1, mnemonic) } } } } pub struct Lexer; #[derive(PartialEq, Debug)] pub struct TokenizedLine { pub opcode: Opcode, pub operands: Vec<TokenType>, } impl TokenizedLine { pub fn empty() -> Self { TokenizedLine { opcode: Opcode::NOP, operands: vec![], } } } impl Lexer { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self {} } #[allow(clippy::ptr_arg)] pub fn tokenize(&self, content: &Vec<String>) -> Result<Vec<TokenizedLine>, Vec<LexerError>> { let mut tokenized = Vec::<TokenizedLine>::new(); let mut errors = Vec::<LexerError>::new(); #[allow(clippy::needless_range_loop)] for i in 0..content.len() { if content[i].starts_with(lamp_common::constants::COMMENT_MARKER) { continue; } match self.tokenize_line(&content[i], i) { Ok(tkn) => { if errors.is_empty() { tokenized.push(tkn); } } Err(e) => errors.push(e), } } if errors.is_empty() { return Ok(tokenized); } Err(errors) } pub fn tokenize_line(&self, line: &str, line_num: usize) -> Result<TokenizedLine, LexerError> { if let Some(index) = line.find(' ') { let to_tokenize = line.split_at(index); let mut tokenized = TokenizedLine::empty(); if let Ok(opcode) = get_op(to_tokenize.0.to_owned()) { tokenized.opcode = opcode; match self.tokenize_operands(to_tokenize.1.to_owned(), line_num) { Ok(tkns) => { tokenized.operands = tkns; Ok(tokenized) } Err(e) => Err(e), } } else { Err(LexerError::InvalidMnemonic( line_num, to_tokenize.0.to_owned(), )) } } else { Err(LexerError::InvalidLine(line_num)) } } pub fn tokenize_operands( &self, line: String, line_num: usize, ) -> Result<Vec<TokenType>, LexerError> { let to_tokenize: Vec<&str> = line.split(',').collect(); let mut tokens = Vec::<TokenType>::new(); for tkn in to_tokenize { let tkn = tkn.split_whitespace().next(); match tkn { Some(tkn) => match self.from_number_to_token(tkn.to_string(), line_num) { Ok(tok) => tokens.push(tok), Err(e) => return Err(e), }, None => break, } } Ok(tokens) } pub fn from_number_to_token(&self, tkn: String, line: usize) -> Result<TokenType, LexerError> { let split = &tkn.split_at(1); match split.1.parse::<u8>() { Ok(number) => match split.0 { "#" => Ok(TokenType::Num8(number)), "$" => Ok(TokenType::Ptr8(number)), other => Err(LexerError::UnexpectedToken(line, other.to_owned())), }, Err(_) => Err(LexerError::UnexpectedToken(line, tkn)), } } }
use lamp_common::op::{get_op, Opcode}; #[derive(Debug, Copy, Clone, PartialEq)] pub enum TokenType { Opcode(Opcode), Num8(u8), Ptr8(u8), } #[derive(Debug)] pub enum LexerError { UnexpectedToken(usize, String), InvalidMnemonic(usize, String), InvalidLine(usize), } impl std::fmt::Display for LexerError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { /* at + 1 because at is an array/vec index */ Self::InvalidLine(at) => { write!(f, "Line {} contains one or more invalid tokens", at + 1) } Self::UnexpectedToken(at, tkn) => { write!(f, "Unexpected token at line {}: \'{}\
e>::new(); let mut errors = Vec::<LexerError>::new(); #[allow(clippy::needless_range_loop)] for i in 0..content.len() { if content[i].starts_with(lamp_common::constants::COMMENT_MARKER) { continue; } match self.tokenize_line(&content[i], i) { Ok(tkn) => { if errors.is_empty() { tokenized.push(tkn); } } Err(e) => errors.push(e), } } if errors.is_empty() { return Ok(tokenized); } Err(errors) } pub fn tokenize_line(&self, line: &str, line_num: usize) -> Result<TokenizedLine, LexerError> { if let Some(index) = line.find(' ') { let to_tokenize = line.split_at(index); let mut tokenized = TokenizedLine::empty(); if let Ok(opcode) = get_op(to_tokenize.0.to_owned()) { tokenized.opcode = opcode; match self.tokenize_operands(to_tokenize.1.to_owned(), line_num) { Ok(tkns) => { tokenized.operands = tkns; Ok(tokenized) } Err(e) => Err(e), } } else { Err(LexerError::InvalidMnemonic( line_num, to_tokenize.0.to_owned(), )) } } else { Err(LexerError::InvalidLine(line_num)) } } pub fn tokenize_operands( &self, line: String, line_num: usize, ) -> Result<Vec<TokenType>, LexerError> { let to_tokenize: Vec<&str> = line.split(',').collect(); let mut tokens = Vec::<TokenType>::new(); for tkn in to_tokenize { let tkn = tkn.split_whitespace().next(); match tkn { Some(tkn) => match self.from_number_to_token(tkn.to_string(), line_num) { Ok(tok) => tokens.push(tok), Err(e) => return Err(e), }, None => break, } } Ok(tokens) } pub fn from_number_to_token(&self, tkn: String, line: usize) -> Result<TokenType, LexerError> { let split = &tkn.split_at(1); match split.1.parse::<u8>() { Ok(number) => match split.0 { "#" => Ok(TokenType::Num8(number)), "$" => Ok(TokenType::Ptr8(number)), other => Err(LexerError::UnexpectedToken(line, other.to_owned())), }, Err(_) => Err(LexerError::UnexpectedToken(line, tkn)), } } }
'", at + 1, tkn) } Self::InvalidMnemonic(at, mnemonic) => { write!(f, "Invalid mnemonic at line {}: \'{}\'", at + 1, mnemonic) } } } } pub struct Lexer; #[derive(PartialEq, Debug)] pub struct TokenizedLine { pub opcode: Opcode, pub operands: Vec<TokenType>, } impl TokenizedLine { pub fn empty() -> Self { TokenizedLine { opcode: Opcode::NOP, operands: vec![], } } } impl Lexer { #[allow(clippy::new_without_default)] pub fn new() -> Self { Self {} } #[allow(clippy::ptr_arg)] pub fn tokenize(&self, content: &Vec<String>) -> Result<Vec<TokenizedLine>, Vec<LexerError>> { let mut tokenized = Vec::<TokenizedLin
random
[ { "content": "pub fn get_op<'a>(base: String) -> Result<Opcode, &'a str> {\n\n for (opcode, name) in OPCODES_STRINGS {\n\n if base.to_uppercase().contains(name) {\n\n return Ok(*opcode);\n\n }\n\n }\n\n\n\n Err(\"No opcode found.\")\n\n}\n", "file_path": "lamp_common/src/op...