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
src/lib.rs
ecies/rs
8acefe16f51de03b18fccb654d7b0d24f4548006
pub use libsecp256k1::{util::FULL_PUBLIC_KEY_SIZE, Error as SecpError, PublicKey, SecretKey}; pub mod consts; pub mod types; pub mod utils; #[cfg(feature = "openssl")] mod openssl_aes; #[cfg(feature = "pure")] mod pure_aes; use utils::{aes_decrypt, aes_encrypt, decapsulate, encapsulate, generate_keypair}; pub fn encrypt(receiver_pub: &[u8], msg: &[u8]) -> Result<Vec<u8>, SecpError> { let receiver_pk = PublicKey::parse_slice(receiver_pub, None)?; let (ephemeral_sk, ephemeral_pk) = generate_keypair(); let aes_key = encapsulate(&ephemeral_sk, &receiver_pk)?; let encrypted = aes_encrypt(&aes_key, msg).ok_or(SecpError::InvalidMessage)?; let mut cipher_text = Vec::with_capacity(FULL_PUBLIC_KEY_SIZE + encrypted.len()); cipher_text.extend(ephemeral_pk.serialize().iter()); cipher_text.extend(encrypted); Ok(cipher_text) } pub fn decrypt(receiver_sec: &[u8], msg: &[u8]) -> Result<Vec<u8>, SecpError> { let receiver_sk = SecretKey::parse_slice(receiver_sec)?; if msg.len() < FULL_PUBLIC_KEY_SIZE { return Err(SecpError::InvalidMessage); } let ephemeral_pk = PublicKey::parse_slice(&msg[..FULL_PUBLIC_KEY_SIZE], None)?; let encrypted = &msg[FULL_PUBLIC_KEY_SIZE..]; let aes_key = decapsulate(&ephemeral_pk, &receiver_sk)?; aes_decrypt(&aes_key, encrypted).ok_or(SecpError::InvalidMessage) } #[cfg(test)] mod tests { use super::*; use utils::generate_keypair; const MSG: &str = "helloworld"; const BIG_MSG_SIZE: usize = 2 * 1024 * 1024; const BIG_MSG: [u8; BIG_MSG_SIZE] = [1u8; BIG_MSG_SIZE]; pub(super) fn test_enc_dec(sk: &[u8], pk: &[u8]) { let msg = MSG.as_bytes(); assert_eq!(msg, decrypt(sk, &encrypt(pk, msg).unwrap()).unwrap().as_slice()); } pub(super) fn test_enc_dec_big(sk: &[u8], pk: &[u8]) { let msg = &BIG_MSG; assert_eq!(msg.to_vec(), decrypt(sk, &encrypt(pk, msg).unwrap()).unwrap()); } #[test] fn attempts_to_decrypt_with_another_key() { let (_, pk1) = generate_keypair(); let (sk2, _) = generate_keypair(); assert_eq!( decrypt( &sk2.serialize(), encrypt(&pk1.serialize_compressed(), b"text").unwrap().as_slice() ), Err(SecpError::InvalidMessage) ); } #[test] fn attempts_to_decrypt_incorrect_message() { let (sk, _) = generate_keypair(); assert_eq!(decrypt(&sk.serialize(), &[]), Err(SecpError::InvalidMessage)); assert_eq!(decrypt(&sk.serialize(), &[0u8; 65]), Err(SecpError::InvalidPublicKey)); } #[test] fn attempts_to_encrypt_with_invalid_key() { assert_eq!(encrypt(&[0u8; 33], b"text"), Err(SecpError::InvalidPublicKey)); } #[test] fn test_compressed_public() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize_compressed()); test_enc_dec(sk, pk); } #[test] fn test_uncompressed_public() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize()); test_enc_dec(sk, pk); } #[test] fn test_compressed_public_big_msg() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize_compressed()); test_enc_dec_big(sk, pk); } #[test] #[cfg(not(target_arch = "wasm32"))] fn test_against_python() { use futures_util::FutureExt; use hex::encode; use tokio::runtime::Runtime; use utils::tests::decode_hex; const PYTHON_BACKEND: &str = "https://eciespy.herokuapp.com/"; let (sk, pk) = generate_keypair(); let sk_hex = encode(&sk.serialize().to_vec()); let uncompressed_pk = &pk.serialize(); let pk_hex = encode(uncompressed_pk.to_vec()); let client = reqwest::Client::new(); let params = [("data", MSG), ("pub", pk_hex.as_str())]; let rt = Runtime::new().unwrap(); let res = rt .block_on( client .post(PYTHON_BACKEND) .form(&params) .send() .then(|r| r.unwrap().text()), ) .unwrap(); let server_encrypted = decode_hex(&res); let local_decrypted = decrypt(&sk.serialize(), server_encrypted.as_slice()).unwrap(); assert_eq!(local_decrypted, MSG.as_bytes()); let local_encrypted = encrypt(uncompressed_pk, MSG.as_bytes()).unwrap(); let params = [("data", encode(local_encrypted)), ("prv", sk_hex)]; let res = rt .block_on( client .post(PYTHON_BACKEND) .form(&params) .send() .then(|r| r.unwrap().text()), ) .unwrap(); assert_eq!(res, MSG); } } #[cfg(all(test, target_arch = "wasm32"))] mod wasm_tests { use super::generate_keypair; use super::tests::{test_enc_dec, test_enc_dec_big}; use wasm_bindgen_test::*; #[wasm_bindgen_test] fn test_wasm() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize()); test_enc_dec(sk, pk); test_enc_dec_big(sk, pk); } }
pub use libsecp256k1::{util::FULL_PUBLIC_KEY_SIZE, Error as SecpError, PublicKey, SecretKey}; pub mod consts; pub mod types; pub mod utils; #[cfg(feature = "openssl")] mod openssl_aes; #[cfg(feature = "pure")] mod pure_aes; use utils::{aes_decrypt, aes_encrypt, decapsulate, encapsulate, generate_keypair}; pub fn encrypt(receiver_pub: &[u8], msg: &[u8]) -> Result<Vec<u8>, SecpError> { let receiver_pk = PublicKey::parse_slice(receiver_pub, None)?; let (ephemeral_sk, ephemeral_pk) = generate_keypair(); let aes_key = encapsulate(&ephemeral_sk, &receiver_pk)?; let encrypted = aes_encrypt(&aes_key, msg).ok_or(SecpError::InvalidMessage)?; let mut cipher_text = Vec::with_capacity(FULL_PUBLIC_KEY_SIZE + encrypted.len()); cipher_text.extend(ephemeral_pk.serialize().iter()); cipher_text.extend(encrypted); Ok(cipher_text) } pub fn decrypt(receiver_sec: &[u8], msg: &[u8]) -> Result<Vec<u8>, SecpError> { let receiver_sk = SecretKey::parse_slice(receiver_sec)?; if msg.len() < FULL_PUBLIC_KEY_SIZE { return Err(SecpError::InvalidMessage); } let ephemeral_pk = PublicKey::parse_slice(&msg[..FULL_PUBLIC_KEY_SIZE], None)?; let encrypted = &msg[FULL_PUBLIC_KEY_SIZE..]; let aes_key = decapsulate(&ephemeral_pk,
alidMessage) ); } #[test] fn attempts_to_decrypt_incorrect_message() { let (sk, _) = generate_keypair(); assert_eq!(decrypt(&sk.serialize(), &[]), Err(SecpError::InvalidMessage)); assert_eq!(decrypt(&sk.serialize(), &[0u8; 65]), Err(SecpError::InvalidPublicKey)); } #[test] fn attempts_to_encrypt_with_invalid_key() { assert_eq!(encrypt(&[0u8; 33], b"text"), Err(SecpError::InvalidPublicKey)); } #[test] fn test_compressed_public() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize_compressed()); test_enc_dec(sk, pk); } #[test] fn test_uncompressed_public() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize()); test_enc_dec(sk, pk); } #[test] fn test_compressed_public_big_msg() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize_compressed()); test_enc_dec_big(sk, pk); } #[test] #[cfg(not(target_arch = "wasm32"))] fn test_against_python() { use futures_util::FutureExt; use hex::encode; use tokio::runtime::Runtime; use utils::tests::decode_hex; const PYTHON_BACKEND: &str = "https://eciespy.herokuapp.com/"; let (sk, pk) = generate_keypair(); let sk_hex = encode(&sk.serialize().to_vec()); let uncompressed_pk = &pk.serialize(); let pk_hex = encode(uncompressed_pk.to_vec()); let client = reqwest::Client::new(); let params = [("data", MSG), ("pub", pk_hex.as_str())]; let rt = Runtime::new().unwrap(); let res = rt .block_on( client .post(PYTHON_BACKEND) .form(&params) .send() .then(|r| r.unwrap().text()), ) .unwrap(); let server_encrypted = decode_hex(&res); let local_decrypted = decrypt(&sk.serialize(), server_encrypted.as_slice()).unwrap(); assert_eq!(local_decrypted, MSG.as_bytes()); let local_encrypted = encrypt(uncompressed_pk, MSG.as_bytes()).unwrap(); let params = [("data", encode(local_encrypted)), ("prv", sk_hex)]; let res = rt .block_on( client .post(PYTHON_BACKEND) .form(&params) .send() .then(|r| r.unwrap().text()), ) .unwrap(); assert_eq!(res, MSG); } } #[cfg(all(test, target_arch = "wasm32"))] mod wasm_tests { use super::generate_keypair; use super::tests::{test_enc_dec, test_enc_dec_big}; use wasm_bindgen_test::*; #[wasm_bindgen_test] fn test_wasm() { let (sk, pk) = generate_keypair(); let (sk, pk) = (&sk.serialize(), &pk.serialize()); test_enc_dec(sk, pk); test_enc_dec_big(sk, pk); } }
&receiver_sk)?; aes_decrypt(&aes_key, encrypted).ok_or(SecpError::InvalidMessage) } #[cfg(test)] mod tests { use super::*; use utils::generate_keypair; const MSG: &str = "helloworld"; const BIG_MSG_SIZE: usize = 2 * 1024 * 1024; const BIG_MSG: [u8; BIG_MSG_SIZE] = [1u8; BIG_MSG_SIZE]; pub(super) fn test_enc_dec(sk: &[u8], pk: &[u8]) { let msg = MSG.as_bytes(); assert_eq!(msg, decrypt(sk, &encrypt(pk, msg).unwrap()).unwrap().as_slice()); } pub(super) fn test_enc_dec_big(sk: &[u8], pk: &[u8]) { let msg = &BIG_MSG; assert_eq!(msg.to_vec(), decrypt(sk, &encrypt(pk, msg).unwrap()).unwrap()); } #[test] fn attempts_to_decrypt_with_another_key() { let (_, pk1) = generate_keypair(); let (sk2, _) = generate_keypair(); assert_eq!( decrypt( &sk2.serialize(), encrypt(&pk1.serialize_compressed(), b"text").unwrap().as_slice() ), Err(SecpError::Inv
random
[ { "content": "/// AES-256-GCM encryption wrapper\n\npub fn aes_encrypt(key: &[u8], msg: &[u8]) -> Option<Vec<u8>> {\n\n let key = GenericArray::from_slice(key);\n\n let aead = Aes256Gcm::new(key);\n\n\n\n let mut iv = [0u8; AES_IV_LENGTH];\n\n thread_rng().fill(&mut iv);\n\n\n\n let nonce = Gener...
Rust
hphp/hack/src/rupro/hackrs/shallow_decl_provider/store.rs
leikahing/hhvm
26617c88ca35c5e078c3aef12c061d7996925375
use anyhow::Result; use datastore::Store; use pos::{ConstName, FunName, MethodName, ModuleName, PropName, TypeName}; use std::sync::Arc; use ty::decl::{ shallow::Decl, shallow::ModuleDecl, ConstDecl, FunDecl, ShallowClass, Ty, TypedefDecl, }; use ty::reason::Reason; #[derive(Debug)] pub struct ShallowDeclStore<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, static_properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, static_methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, constructors: Arc<dyn Store<TypeName, Ty<R>>>, } impl<R: Reason> ShallowDeclStore<R> { pub fn new( classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, static_properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, static_methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, constructors: Arc<dyn Store<TypeName, Ty<R>>>, ) -> Self { Self { classes, typedefs, funs, consts, modules, properties, static_properties, methods, static_methods, constructors, } } pub fn with_no_member_stores( classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, ) -> Self { Self { properties: Arc::new(PropFinder { classes: Arc::clone(&classes), }), static_properties: Arc::new(StaticPropFinder { classes: Arc::clone(&classes), }), methods: Arc::new(MethodFinder { classes: Arc::clone(&classes), }), static_methods: Arc::new(StaticMethodFinder { classes: Arc::clone(&classes), }), constructors: Arc::new(ConstructorFinder { classes: Arc::clone(&classes), }), classes, typedefs, funs, consts, modules, } } pub fn add_decls(&self, decls: impl IntoIterator<Item = Decl<R>>) -> Result<()> { for decl in decls.into_iter() { match decl { Decl::Class(name, decl) => self.add_class(name, Arc::new(decl))?, Decl::Fun(name, decl) => self.funs.insert(name, Arc::new(decl))?, Decl::Typedef(name, decl) => self.typedefs.insert(name, Arc::new(decl))?, Decl::Const(name, decl) => self.consts.insert(name, Arc::new(decl))?, Decl::Module(name, decl) => self.modules.insert(name, Arc::new(decl))?, } } Ok(()) } pub fn get_fun(&self, name: FunName) -> Result<Option<Arc<FunDecl<R>>>> { self.funs.get(name) } pub fn get_const(&self, name: ConstName) -> Result<Option<Arc<ConstDecl<R>>>> { self.consts.get(name) } pub fn get_class(&self, name: TypeName) -> Result<Option<Arc<ShallowClass<R>>>> { self.classes.get(name) } pub fn get_typedef(&self, name: TypeName) -> Result<Option<Arc<TypedefDecl<R>>>> { self.typedefs.get(name) } pub fn get_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.properties.get((class_name, property_name)) } pub fn get_static_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.static_properties.get((class_name, property_name)) } pub fn get_method_type( &self, class_name: TypeName, method_name: MethodName, ) -> Result<Option<Ty<R>>> { self.methods.get((class_name, method_name)) } pub fn get_static_method_type( &self, class_name: TypeName, method_name: MethodName, ) -> Result<Option<Ty<R>>> { self.static_methods.get((class_name, method_name)) } pub fn get_constructor_type(&self, class_name: TypeName) -> Result<Option<Ty<R>>> { self.constructors.get(class_name) } fn add_class(&self, name: TypeName, cls: Arc<ShallowClass<R>>) -> Result<()> { let cid = cls.name.id(); for prop in cls.props.iter().rev() { if let Some(ty) = &prop.ty { self.properties.insert((cid, prop.name.id()), ty.clone())? } } for prop in cls.static_props.iter().rev() { if let Some(ty) = &prop.ty { self.static_properties .insert((cid, prop.name.id()), ty.clone())? } } for meth in cls.methods.iter().rev() { self.methods .insert((cid, meth.name.id()), meth.ty.clone())? } for meth in cls.static_methods.iter().rev() { self.static_methods .insert((cid, meth.name.id()), meth.ty.clone())? } if let Some(constructor) = &cls.constructor { self.constructors.insert(cid, constructor.ty.clone())? } self.classes.insert(name, cls)?; Ok(()) } } #[derive(Debug)] struct PropFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, PropName), Ty<R>> for PropFinder<R> { fn get(&self, (class_name, property_name): (TypeName, PropName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.props.iter().rev().find_map(|prop| { if prop.name.id() == property_name { prop.ty.clone() } else { None } }) })) } fn insert(&self, _: (TypeName, PropName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, PropName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct StaticPropFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, PropName), Ty<R>> for StaticPropFinder<R> { fn get(&self, (class_name, property_name): (TypeName, PropName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.static_props.iter().rev().find_map(|prop| { if prop.name.id() == property_name { prop.ty.clone() } else { None } }) })) } fn insert(&self, _: (TypeName, PropName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, PropName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct MethodFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, MethodName), Ty<R>> for MethodFinder<R> { fn get(&self, (class_name, method_name): (TypeName, MethodName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.methods.iter().rev().find_map(|meth| { if meth.name.id() == method_name { Some(meth.ty.clone()) } else { None } }) })) } fn insert(&self, _: (TypeName, MethodName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, MethodName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct StaticMethodFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, MethodName), Ty<R>> for StaticMethodFinder<R> { fn get(&self, (class_name, method_name): (TypeName, MethodName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.static_methods.iter().rev().find_map(|meth| { if meth.name.id() == method_name { Some(meth.ty.clone()) } else { None } }) })) } fn insert(&self, _: (TypeName, MethodName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, MethodName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct ConstructorFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<TypeName, Ty<R>> for ConstructorFinder<R> { fn get(&self, class_name: TypeName) -> Result<Option<Ty<R>>> { Ok(self .classes .get(class_name)? .and_then(|cls| cls.constructor.as_ref().map(|meth| meth.ty.clone()))) } fn insert(&self, _: TypeName, _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = TypeName>) -> Result<()> { Ok(()) } }
use anyhow::Result; use datastore::Store; use pos::{ConstName, FunName, MethodName, ModuleName, PropName, TypeName}; use std::sync::Arc; use ty::decl::{ shallow::Decl, shallow::ModuleDecl, ConstDecl, FunDecl, ShallowClass, Ty, TypedefDecl, }; use ty::reason::Reason; #[derive(Debug)] pub struct ShallowDeclStore<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, static_properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, static_methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, constructors: Arc<dyn Store<TypeName, Ty<R>>>, } impl<R: Reason> ShallowDeclStore<R> { pub fn new( classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, static_properties: Arc<dyn Store<(TypeName, PropName), Ty<R>>>, methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, static_methods: Arc<dyn Store<(TypeName, MethodName), Ty<R>>>, constructors: Arc<dyn Store<TypeName, Ty<R>>>, ) -> Self { Self { classes, typedefs, funs, consts, modules, properties, static_properties, methods, static_methods, constructors, } } pub fn with_no_member_stores( classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, typedefs: Arc<dyn Store<TypeName, Arc<TypedefDecl<R>>>>, funs: Arc<dyn Store<FunName, Arc<FunDecl<R>>>>, consts: Arc<dyn Store<ConstName, Arc<ConstDecl<R>>>>, modules: Arc<dyn Store<ModuleName, Arc<ModuleDecl<R>>>>, ) -> Self { Self { properties: Arc::new(PropFinder { classes: Arc::clone(&classes), }), static_properties: Arc::new(StaticPropFinder { classes: Arc::clone(&classes), }), methods: Arc::new(MethodFinder { classes: Arc::clone(&classes), }), static_methods: Arc::new(StaticMethodFinder { classes: Arc::clone(&classes), }), constructors: Arc::new(ConstructorFinder { classes: Arc::clone(&classes), }), classes, typedefs, funs, consts, modules, } } pub fn add_decls(&self, decls: impl IntoIterator<Item = Decl<R>>) -> Result<()> { for decl in decls.into_iter() { match decl { Decl::Class(name, decl) => self.add_class(name, Arc::new(decl))?, Decl::Fun(name, decl) => self.funs.insert(name, Arc::new(decl))?, Decl::Typedef(name, decl) => self.typedefs.insert(name, Arc::new(decl))?, Decl::Const(name, decl) => self.consts.insert(name, Arc::new(decl))?, Decl::Module(name, decl) => self.modules.insert(name, Arc::new(decl))?, } } Ok(()) } pub fn get_fun(&self, name: FunName) -> Result<Option<Arc<FunDecl<R>>>> { self.funs.get(name) } pub fn get_const(&self, name: ConstName) -> Result<Option<Arc<ConstDecl<R>>>> { self.consts.get(name) } pub fn get_class(&self, name: TypeName) -> Result<Option<Arc<ShallowClass<R>>>> { self.classes.get(name) } pub fn get_typedef(&self, name: TypeName) -> Result<Option<Arc<TypedefDecl<R>>>> { self.typedefs.get(name) }
pub fn get_static_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.static_properties.get((class_name, property_name)) } pub fn get_method_type( &self, class_name: TypeName, method_name: MethodName, ) -> Result<Option<Ty<R>>> { self.methods.get((class_name, method_name)) } pub fn get_static_method_type( &self, class_name: TypeName, method_name: MethodName, ) -> Result<Option<Ty<R>>> { self.static_methods.get((class_name, method_name)) } pub fn get_constructor_type(&self, class_name: TypeName) -> Result<Option<Ty<R>>> { self.constructors.get(class_name) } fn add_class(&self, name: TypeName, cls: Arc<ShallowClass<R>>) -> Result<()> { let cid = cls.name.id(); for prop in cls.props.iter().rev() { if let Some(ty) = &prop.ty { self.properties.insert((cid, prop.name.id()), ty.clone())? } } for prop in cls.static_props.iter().rev() { if let Some(ty) = &prop.ty { self.static_properties .insert((cid, prop.name.id()), ty.clone())? } } for meth in cls.methods.iter().rev() { self.methods .insert((cid, meth.name.id()), meth.ty.clone())? } for meth in cls.static_methods.iter().rev() { self.static_methods .insert((cid, meth.name.id()), meth.ty.clone())? } if let Some(constructor) = &cls.constructor { self.constructors.insert(cid, constructor.ty.clone())? } self.classes.insert(name, cls)?; Ok(()) } } #[derive(Debug)] struct PropFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, PropName), Ty<R>> for PropFinder<R> { fn get(&self, (class_name, property_name): (TypeName, PropName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.props.iter().rev().find_map(|prop| { if prop.name.id() == property_name { prop.ty.clone() } else { None } }) })) } fn insert(&self, _: (TypeName, PropName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, PropName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct StaticPropFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, PropName), Ty<R>> for StaticPropFinder<R> { fn get(&self, (class_name, property_name): (TypeName, PropName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.static_props.iter().rev().find_map(|prop| { if prop.name.id() == property_name { prop.ty.clone() } else { None } }) })) } fn insert(&self, _: (TypeName, PropName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, PropName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct MethodFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, MethodName), Ty<R>> for MethodFinder<R> { fn get(&self, (class_name, method_name): (TypeName, MethodName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.methods.iter().rev().find_map(|meth| { if meth.name.id() == method_name { Some(meth.ty.clone()) } else { None } }) })) } fn insert(&self, _: (TypeName, MethodName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, MethodName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct StaticMethodFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<(TypeName, MethodName), Ty<R>> for StaticMethodFinder<R> { fn get(&self, (class_name, method_name): (TypeName, MethodName)) -> Result<Option<Ty<R>>> { Ok(self.classes.get(class_name)?.and_then(|cls| { cls.static_methods.iter().rev().find_map(|meth| { if meth.name.id() == method_name { Some(meth.ty.clone()) } else { None } }) })) } fn insert(&self, _: (TypeName, MethodName), _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = (TypeName, MethodName)>) -> Result<()> { Ok(()) } } #[derive(Debug)] struct ConstructorFinder<R: Reason> { classes: Arc<dyn Store<TypeName, Arc<ShallowClass<R>>>>, } impl<R: Reason> Store<TypeName, Ty<R>> for ConstructorFinder<R> { fn get(&self, class_name: TypeName) -> Result<Option<Ty<R>>> { Ok(self .classes .get(class_name)? .and_then(|cls| cls.constructor.as_ref().map(|meth| meth.ty.clone()))) } fn insert(&self, _: TypeName, _: Ty<R>) -> Result<()> { Ok(()) } fn remove_batch(&self, _: &mut dyn Iterator<Item = TypeName>) -> Result<()> { Ok(()) } }
pub fn get_property_type( &self, class_name: TypeName, property_name: PropName, ) -> Result<Option<Ty<R>>> { self.properties.get((class_name, property_name)) }
function_block-full_function
[]
Rust
src/workers.rs
arthurprs/sucredb
c3cf1adddf74b7616aa6b6f10b334aba0e1b5a30
use crossbeam_channel as chan; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{thread, time}; pub trait ExitMsg { fn exit_msg() -> Self; fn is_exit(&self) -> bool; } pub struct WorkerSender<T: ExitMsg + Send + 'static> { cursor: AtomicUsize, alive_threads: Arc<AtomicUsize>, channels: Vec<chan::Sender<T>>, } impl<T: ExitMsg + Send + 'static> Clone for WorkerSender<T> { fn clone(&self) -> Self { WorkerSender { cursor: Default::default(), channels: self.channels.clone(), alive_threads: self.alive_threads.clone(), } } } pub struct WorkerManager<T: ExitMsg + Send + 'static> { thread_count: usize, threads: Vec<thread::JoinHandle<()>>, name: String, alive_threads: Arc<AtomicUsize>, channels: Vec<chan::Sender<T>>, } impl<T: ExitMsg + Send + 'static> WorkerManager<T> { pub fn new(name: String, thread_count: usize) -> Self { assert!(thread_count > 0); WorkerManager { thread_count: thread_count, threads: Default::default(), name: name, alive_threads: Default::default(), channels: Default::default(), } } pub fn start<F>(&mut self, mut worker_fn_gen: F) where F: FnMut() -> Box<FnMut(T) + Send>, { assert!(self.channels.is_empty()); for i in 0..self.thread_count { let mut worker_fn = worker_fn_gen(); let (tx, rx) = chan::unbounded(); let alive_handle = self.alive_threads.clone(); self.channels.push(tx); self.threads.push( thread::Builder::new() .name(format!("Worker:{}:{}", i, self.name)) .spawn(move || { alive_handle.fetch_add(1, Ordering::SeqCst); for m in rx { if m.is_exit() { break; } worker_fn(m); } alive_handle.fetch_sub(1, Ordering::SeqCst); info!("Exiting worker"); }).unwrap(), ); } } pub fn sender(&self) -> WorkerSender<T> { assert!(!self.channels.is_empty()); WorkerSender { cursor: Default::default(), channels: self.channels.clone(), alive_threads: self.alive_threads.clone(), } } } impl<T: ExitMsg + Send + 'static> WorkerSender<T> { pub fn send(&self, msg: T) -> bool { let cursor = self.cursor.fetch_add(1, Ordering::Relaxed); self.send_to(cursor, msg) } pub fn send_to(&self, seed: usize, msg: T) -> bool { self.channels[seed % self.channels.len()].send(msg); self.alive_threads.load(Ordering::SeqCst) > 0 } } impl<T: ExitMsg + Send + 'static> Drop for WorkerManager<T> { fn drop(&mut self) { for c in &*self.channels { let _ = c.send(T::exit_msg()); } for t in self.threads.drain(..) { let _ = t.join(); } } } pub fn timer_fn<F>( name: String, interval: time::Duration, mut callback: F, ) -> thread::JoinHandle<()> where F: FnMut(time::Instant) -> bool + Send + 'static, { thread::Builder::new() .name(format!("Timer:{}", name)) .spawn(move || loop { thread::sleep(interval); if !callback(time::Instant::now()) { break; } }).expect("Can't start timer") }
use crossbeam_channel as chan; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use std::{thread, time}; pub trait ExitMsg { fn exit_msg() -> Self; fn is_exit(&self) -> bool; } pub struct WorkerSender<
<T> { assert!(!self.channels.is_empty()); WorkerSender { cursor: Default::default(), channels: self.channels.clone(), alive_threads: self.alive_threads.clone(), } } } impl<T: ExitMsg + Send + 'static> WorkerSender<T> { pub fn send(&self, msg: T) -> bool { let cursor = self.cursor.fetch_add(1, Ordering::Relaxed); self.send_to(cursor, msg) } pub fn send_to(&self, seed: usize, msg: T) -> bool { self.channels[seed % self.channels.len()].send(msg); self.alive_threads.load(Ordering::SeqCst) > 0 } } impl<T: ExitMsg + Send + 'static> Drop for WorkerManager<T> { fn drop(&mut self) { for c in &*self.channels { let _ = c.send(T::exit_msg()); } for t in self.threads.drain(..) { let _ = t.join(); } } } pub fn timer_fn<F>( name: String, interval: time::Duration, mut callback: F, ) -> thread::JoinHandle<()> where F: FnMut(time::Instant) -> bool + Send + 'static, { thread::Builder::new() .name(format!("Timer:{}", name)) .spawn(move || loop { thread::sleep(interval); if !callback(time::Instant::now()) { break; } }).expect("Can't start timer") }
T: ExitMsg + Send + 'static> { cursor: AtomicUsize, alive_threads: Arc<AtomicUsize>, channels: Vec<chan::Sender<T>>, } impl<T: ExitMsg + Send + 'static> Clone for WorkerSender<T> { fn clone(&self) -> Self { WorkerSender { cursor: Default::default(), channels: self.channels.clone(), alive_threads: self.alive_threads.clone(), } } } pub struct WorkerManager<T: ExitMsg + Send + 'static> { thread_count: usize, threads: Vec<thread::JoinHandle<()>>, name: String, alive_threads: Arc<AtomicUsize>, channels: Vec<chan::Sender<T>>, } impl<T: ExitMsg + Send + 'static> WorkerManager<T> { pub fn new(name: String, thread_count: usize) -> Self { assert!(thread_count > 0); WorkerManager { thread_count: thread_count, threads: Default::default(), name: name, alive_threads: Default::default(), channels: Default::default(), } } pub fn start<F>(&mut self, mut worker_fn_gen: F) where F: FnMut() -> Box<FnMut(T) + Send>, { assert!(self.channels.is_empty()); for i in 0..self.thread_count { let mut worker_fn = worker_fn_gen(); let (tx, rx) = chan::unbounded(); let alive_handle = self.alive_threads.clone(); self.channels.push(tx); self.threads.push( thread::Builder::new() .name(format!("Worker:{}:{}", i, self.name)) .spawn(move || { alive_handle.fetch_add(1, Ordering::SeqCst); for m in rx { if m.is_exit() { break; } worker_fn(m); } alive_handle.fetch_sub(1, Ordering::SeqCst); info!("Exiting worker"); }).unwrap(), ); } } pub fn sender(&self) -> WorkerSender
random
[ { "content": "pub trait Metadata\n\n : Serialize + DeserializeOwned + Clone + PartialEq + Send + fmt::Debug + 'static\n\n {\n\n}\n\n\n\nimpl<T: Serialize + DeserializeOwned + Clone + PartialEq + Send + fmt::Debug + 'static> Metadata\n\n for T {\n\n}\n\n\n", "file_path": "src/gossip.rs", "rank":...
Rust
src/lib.rs
jonas-schievink/vmem
bc31326d5e202c34444243802cb6ffab07dcff02
#![doc(html_root_url = "https://docs.rs/vmem/0.1.0")] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "win.rs"] mod imp; use failure::{Backtrace, Fail}; use std::marker::PhantomData; use std::ops::Range; use std::sync::Mutex; use std::{fmt, io}; #[derive(Debug)] pub struct ReservedMemory { addr: usize, len: usize, allocations: Mutex<Allocations>, } impl ReservedMemory { pub fn reserve(bytes: usize) -> Self { Self::try_reserve(bytes).expect("failed to reserve address space") } pub fn try_reserve(bytes: usize) -> Result<Self, Error> { match imp::reserve(bytes) { Ok(ptr) => Ok(Self { addr: ptr as usize, len: bytes, allocations: Mutex::new(Allocations { list: Vec::new() }), }), Err(e) => Err(ErrorKind::Os(e).into()), } } pub fn addr(&self) -> usize { self.addr } pub fn page_size(&self) -> usize { page_size::get() } pub fn allocate(&self, offset: usize, bytes: usize) -> Result<AllocatedMemory, Error> { self.addr .checked_add(offset) .and_then(|sum| sum.checked_add(bytes)) .ok_or_else(|| ErrorKind::TooLarge)?; if offset + bytes > self.len { return Err(ErrorKind::TooLarge.into()); } if bytes == 0 { return Err(ErrorKind::ZeroSize.into()); } if offset & (self.page_size() - 1) != 0 { return Err(ErrorKind::NotAligned(offset).into()); } let bytes = bytes + self.page_size() - 1; let bytes = bytes & !(self.page_size() - 1); let mut allocs = self.allocations.lock().unwrap(); if allocs.find_allocation_overlapping(offset).is_ok() { return Err(ErrorKind::Overlap.into()); } let addr = self.addr + offset; imp::alloc(addr, bytes).map_err(ErrorKind::Os)?; allocs.register_allocation(offset, bytes); Ok(AllocatedMemory { addr, len: bytes, _p: PhantomData, }) } } impl Drop for ReservedMemory { fn drop(&mut self) { unsafe { imp::unreserve(self.addr, self.len).expect("failed to deallocate memory"); } } } #[derive(Debug)] struct Allocations { list: Vec<Range<usize>>, } impl Allocations { fn register_allocation(&mut self, offset: usize, size: usize) { let idx = match self.find_allocation_overlapping(offset) { Ok(_) => { panic!( "new allocation at offset {} and size {} overlaps existing one", offset, size ); } Err(idx) => idx, }; self.list.insert(idx, offset..offset + size); } fn find_allocation_overlapping(&self, offset: usize) -> Result<usize, usize> { use std::cmp::Ordering; self.list.binary_search_by(|alloc| { if alloc.end <= offset { Ordering::Less } else if alloc.start > offset { Ordering::Greater } else { assert!(alloc.start <= offset && alloc.end > offset); Ordering::Equal } }) } } #[derive(Debug)] pub struct AllocatedMemory<'a> { addr: usize, len: usize, _p: PhantomData<&'a ()>, } impl<'a> AllocatedMemory<'a> { pub fn addr(&self) -> usize { self.addr } pub fn len(&self) -> usize { self.len } pub fn set_protection(&mut self, prot: Protection) { imp::protect(self.addr, self.len, prot).expect("could not change protection") } } #[derive(Debug, Copy, Clone)] pub enum Protection { ReadOnly, ReadWrite, ReadExecute, } #[derive(Debug)] pub struct Error { inner: ErrorKind, } impl Fail for Error { fn cause(&self) -> Option<&Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt(f) } } impl From<ErrorKind> for Error { fn from(e: ErrorKind) -> Self { Self { inner: e } } } #[derive(Fail, Debug)] enum ErrorKind { #[fail(display = "operating system reported error: {}", _0)] Os(#[cause] io::Error), #[fail(display = "requested size is too large")] TooLarge, #[fail(display = "zero-sized allocation requested")] ZeroSize, #[fail(display = "requested allocation overlaps an existing one")] Overlap, #[fail(display = "requested location {:#X} is not page-aligned", _0)] NotAligned(usize), } /* Tests: * Test for leaks * `mem::forget` AllocatedMemory, then drop ReservedMemory normally - should not leak anything! */ #[cfg(test)] mod tests { use super::*; use std::ptr; #[test] fn reserve() { let mem = ReservedMemory::reserve(1024 * 1024); drop(mem); } #[test] fn alloc() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, 1).expect("failed to allocate page"); mem.allocate(0, 1).expect_err("allocated page twice"); mem.allocate(page_size::get() - 1, 1) .expect_err("allocated first page twice (at end)"); mem.allocate(page_size::get(), 1) .expect("failed to allocate second page"); mem.allocate(page_size::get(), 1) .expect_err("allocated second page twice"); mem.allocate(0, 1).expect_err("allocated page twice"); let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, page_size::get()) .expect("failed to allocate"); mem.allocate(page_size::get(), 1) .expect("failed to allocate second page"); } #[test] fn alloc_same_page_different_offset() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, 1).expect("failed to allocate page"); mem.allocate(1, 1).expect_err("allocated page twice"); mem.allocate(page_size::get() - 10, 1) .expect_err("allocated page twice"); } #[test] fn doesnt_fit() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(1024 * 1024 - page_size::get(), page_size::get() + 1) .expect_err("allocated more than last page"); mem.allocate(1024 * 1024, 1) .expect_err("allocated past last page"); mem.allocate(1024 * 1024 * 256, 1) .expect_err("allocated past last page"); mem.allocate(1024 * 1024 - page_size::get(), page_size::get()) .expect("couldn't allocate last page"); } #[test] fn page_boundary() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(1024 + 1, 1) .expect_err("allocation not on page boundary succeeded"); } #[test] fn absurdly_large() { ReservedMemory::try_reserve(1024 * 1024 * 1024 * 1024 * 500).unwrap_err(); } #[test] fn access() { let mem = ReservedMemory::reserve(1024 * 1024); let alloc = mem .allocate(0, page_size::get()) .expect("failed to allocate"); for addr in alloc.addr()..alloc.addr() + alloc.len() { unsafe { ptr::read(addr as *const u8); } } } }
#![doc(html_root_url = "https://docs.rs/vmem/0.1.0")] #![warn(missing_debug_implementations)] #![warn(missing_docs)] #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "win.rs"] mod imp; use failure::{Backtrace, Fail}; use std::marker::PhantomData; use std::ops::Range; use std::sync::Mutex; use std::{fmt, io}; #[derive(Debug)] pub struct ReservedMemory { addr: usize, len: usize, allocations: Mutex<Allocations>, } impl ReservedMemory { pub fn reserve(bytes: usize) -> Self { Self::try_reserve(bytes).expect("failed to reserve address space") } pub fn try_reserve(bytes: usize) -> Result<Self, Error> {
} pub fn addr(&self) -> usize { self.addr } pub fn page_size(&self) -> usize { page_size::get() } pub fn allocate(&self, offset: usize, bytes: usize) -> Result<AllocatedMemory, Error> { self.addr .checked_add(offset) .and_then(|sum| sum.checked_add(bytes)) .ok_or_else(|| ErrorKind::TooLarge)?; if offset + bytes > self.len { return Err(ErrorKind::TooLarge.into()); } if bytes == 0 { return Err(ErrorKind::ZeroSize.into()); } if offset & (self.page_size() - 1) != 0 { return Err(ErrorKind::NotAligned(offset).into()); } let bytes = bytes + self.page_size() - 1; let bytes = bytes & !(self.page_size() - 1); let mut allocs = self.allocations.lock().unwrap(); if allocs.find_allocation_overlapping(offset).is_ok() { return Err(ErrorKind::Overlap.into()); } let addr = self.addr + offset; imp::alloc(addr, bytes).map_err(ErrorKind::Os)?; allocs.register_allocation(offset, bytes); Ok(AllocatedMemory { addr, len: bytes, _p: PhantomData, }) } } impl Drop for ReservedMemory { fn drop(&mut self) { unsafe { imp::unreserve(self.addr, self.len).expect("failed to deallocate memory"); } } } #[derive(Debug)] struct Allocations { list: Vec<Range<usize>>, } impl Allocations { fn register_allocation(&mut self, offset: usize, size: usize) { let idx = match self.find_allocation_overlapping(offset) { Ok(_) => { panic!( "new allocation at offset {} and size {} overlaps existing one", offset, size ); } Err(idx) => idx, }; self.list.insert(idx, offset..offset + size); } fn find_allocation_overlapping(&self, offset: usize) -> Result<usize, usize> { use std::cmp::Ordering; self.list.binary_search_by(|alloc| { if alloc.end <= offset { Ordering::Less } else if alloc.start > offset { Ordering::Greater } else { assert!(alloc.start <= offset && alloc.end > offset); Ordering::Equal } }) } } #[derive(Debug)] pub struct AllocatedMemory<'a> { addr: usize, len: usize, _p: PhantomData<&'a ()>, } impl<'a> AllocatedMemory<'a> { pub fn addr(&self) -> usize { self.addr } pub fn len(&self) -> usize { self.len } pub fn set_protection(&mut self, prot: Protection) { imp::protect(self.addr, self.len, prot).expect("could not change protection") } } #[derive(Debug, Copy, Clone)] pub enum Protection { ReadOnly, ReadWrite, ReadExecute, } #[derive(Debug)] pub struct Error { inner: ErrorKind, } impl Fail for Error { fn cause(&self) -> Option<&Fail> { self.inner.cause() } fn backtrace(&self) -> Option<&Backtrace> { self.inner.backtrace() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.inner.fmt(f) } } impl From<ErrorKind> for Error { fn from(e: ErrorKind) -> Self { Self { inner: e } } } #[derive(Fail, Debug)] enum ErrorKind { #[fail(display = "operating system reported error: {}", _0)] Os(#[cause] io::Error), #[fail(display = "requested size is too large")] TooLarge, #[fail(display = "zero-sized allocation requested")] ZeroSize, #[fail(display = "requested allocation overlaps an existing one")] Overlap, #[fail(display = "requested location {:#X} is not page-aligned", _0)] NotAligned(usize), } /* Tests: * Test for leaks * `mem::forget` AllocatedMemory, then drop ReservedMemory normally - should not leak anything! */ #[cfg(test)] mod tests { use super::*; use std::ptr; #[test] fn reserve() { let mem = ReservedMemory::reserve(1024 * 1024); drop(mem); } #[test] fn alloc() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, 1).expect("failed to allocate page"); mem.allocate(0, 1).expect_err("allocated page twice"); mem.allocate(page_size::get() - 1, 1) .expect_err("allocated first page twice (at end)"); mem.allocate(page_size::get(), 1) .expect("failed to allocate second page"); mem.allocate(page_size::get(), 1) .expect_err("allocated second page twice"); mem.allocate(0, 1).expect_err("allocated page twice"); let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, page_size::get()) .expect("failed to allocate"); mem.allocate(page_size::get(), 1) .expect("failed to allocate second page"); } #[test] fn alloc_same_page_different_offset() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(0, 1).expect("failed to allocate page"); mem.allocate(1, 1).expect_err("allocated page twice"); mem.allocate(page_size::get() - 10, 1) .expect_err("allocated page twice"); } #[test] fn doesnt_fit() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(1024 * 1024 - page_size::get(), page_size::get() + 1) .expect_err("allocated more than last page"); mem.allocate(1024 * 1024, 1) .expect_err("allocated past last page"); mem.allocate(1024 * 1024 * 256, 1) .expect_err("allocated past last page"); mem.allocate(1024 * 1024 - page_size::get(), page_size::get()) .expect("couldn't allocate last page"); } #[test] fn page_boundary() { let mem = ReservedMemory::reserve(1024 * 1024); mem.allocate(1024 + 1, 1) .expect_err("allocation not on page boundary succeeded"); } #[test] fn absurdly_large() { ReservedMemory::try_reserve(1024 * 1024 * 1024 * 1024 * 500).unwrap_err(); } #[test] fn access() { let mem = ReservedMemory::reserve(1024 * 1024); let alloc = mem .allocate(0, page_size::get()) .expect("failed to allocate"); for addr in alloc.addr()..alloc.addr() + alloc.len() { unsafe { ptr::read(addr as *const u8); } } } }
match imp::reserve(bytes) { Ok(ptr) => Ok(Self { addr: ptr as usize, len: bytes, allocations: Mutex::new(Allocations { list: Vec::new() }), }), Err(e) => Err(ErrorKind::Os(e).into()), }
if_condition
[]
Rust
notedata/src/sm_parser.rs
martensm/rustmania
c5f40dcd5f8bf7a555cd8a7d470594409a7ccc8f
use crate::{ parser_generic::{beat_pair, comma_separated, stepmania_tag, ws_trimmed}, Chart, DisplayBpm, Measure, Note, NoteData, NoteRow, NoteType, }; use nom::{ branch::alt, bytes::complete::{tag, take_until}, character::complete::{char, multispace1, none_of, not_line_ending}, combinator::map, error::ErrorKind, multi::{count, fold_many0, fold_many1, many0, separated_nonempty_list}, number::complete::double, sequence::{preceded, separated_pair, terminated}, Err, IResult, }; use num_rational::Rational32; fn display_bpm(input: &str) -> IResult<&str, DisplayBpm> { alt(( map( separated_pair(double, ws_trimmed(char(':')), double), |(min, max)| DisplayBpm::Range(min, max), ), map(double, DisplayBpm::Static), map(char('*'), |_| DisplayBpm::Random), ))(input) } fn notetype(input: &str) -> IResult<&str, Option<NoteType>> { map(none_of("\r\n,"), into_sm_notetype)(input) } fn into_sm_notetype(sm_char: char) -> Option<NoteType> { match sm_char { '1' => Some(NoteType::Tap), '2' => Some(NoteType::Hold), '3' => Some(NoteType::HoldEnd), '4' => Some(NoteType::Roll), 'M' => Some(NoteType::Mine), 'L' => Some(NoteType::Lift), 'F' => Some(NoteType::Fake), _ => None, } } fn noterow(input: &str) -> IResult<&str, NoteRow> { map( fold_many1(notetype, (vec![], 0), |(mut noterow, mut index), item| { if let Some(item) = item { noterow.push(Note::new(item, index)) } index += 1; (noterow, index) }), |(noterow, _)| noterow, )(input) } fn measure(input: &str) -> IResult<&str, Measure> { map( fold_many0( terminated(noterow, multispace1), (vec![], 0), |(mut noterows, mut index), item| { if !item.is_empty() { noterows.push((item, index)) } index += 1; (noterows, index) }, ), |(noterows, total)| { noterows .into_iter() .map(|(item, index)| (item, Rational32::new(index, total))) .collect() }, )(input) } fn chart(input: &str) -> IResult<&str, Chart> { preceded( terminated( count(terminated(take_until(":"), char(':')), 5), many0(alt((comment, multispace1))), ), separated_nonempty_list( preceded( many0(alt((comment, multispace1))), terminated(char(','), many0(alt((comment, multispace1)))), ), measure, ), )(input) } fn comment(input: &str) -> IResult<&str, &str> { preceded(tag("//"), not_line_ending)(input) } fn notedata(input: &str) -> IResult<&str, NoteData> { let mut input = input; let mut nd = NoteData::new(); while let Ok((output, (tag, value))) = preceded(take_until("#"), stepmania_tag)(input) { input = output; if !value.trim().is_empty() { match tag { "TITLE" => nd.meta.title = Some(value.to_owned()), "SUBTITLE" => nd.meta.subtitle = Some(value.to_owned()), "ARTIST" => nd.meta.artist = Some(value.to_owned()), "TITLETRANSLIT" => nd.meta.title_translit = Some(value.to_owned()), "SUBTITLETRANSLIT" => nd.meta.subtitle_translit = Some(value.to_owned()), "ARTISTTRANSLIT" => nd.meta.artist_translit = Some(value.to_owned()), "GENRE" => nd.meta.genre = Some(value.to_owned()), "CREDIT" => nd.meta.credit = Some(value.to_owned()), "BANNER" => nd.meta.banner_path = Some(value.to_owned()), "BACKGROUND" => nd.meta.background_path = Some(value.to_owned()), "LYRICSPATH" => nd.meta.lyrics_path = Some(value.to_owned()), "CDTITLE" => nd.meta.cd_title = Some(value.to_owned()), "MUSIC" => nd.meta.music_path = Some(value.to_owned()), "SAMPLESTART" => nd.meta.sample_start = Some(ws_trimmed(double)(value)?.1), "SAMPLELENGTH" => nd.meta.sample_length = Some(ws_trimmed(double)(value)?.1), "OFFSET" => nd.structure.offset = Some(-ws_trimmed(double)(value)?.1), "DISPLAYBPM" => nd.meta.display_bpm = Some(ws_trimmed(display_bpm)(value)?.1), "BPMS" => { nd.structure.bpms = ws_trimmed(comma_separated(beat_pair(double, 4.0)))(value)?.1 } "STOPS" => { nd.structure.stops = Some(ws_trimmed(comma_separated(beat_pair(double, 4.0)))(value)?.1) } "NOTES" => nd.charts.push(chart(value)?.1), _ => {} } } } Ok((input, nd)) } pub fn parse(input: &str) -> Result<NoteData, Err<(&str, ErrorKind)>> { notedata(input).map(|notedata| notedata.1) } #[cfg(test)] mod tests { use super::*; use crate::{BeatPair, ChartMetadata, StructureData}; use nom::Err::Error; #[test] fn parse_display_bpm() { assert_eq!( display_bpm("1.2 : 3.4 foo"), Ok((" foo", DisplayBpm::Range(1.2, 3.4))) ); assert_eq!(display_bpm("1.2foo"), Ok(("foo", DisplayBpm::Static(1.2)))); assert_eq!(display_bpm("*"), Ok(("", DisplayBpm::Random))); } #[test] fn parse_notetype() { assert_eq!(notetype("1foo"), Ok(("foo", Some(NoteType::Tap)))); assert_eq!(notetype("2foo"), Ok(("foo", Some(NoteType::Hold)))); assert_eq!(notetype("3foo"), Ok(("foo", Some(NoteType::HoldEnd)))); assert_eq!(notetype("4foo"), Ok(("foo", Some(NoteType::Roll)))); assert_eq!(notetype("Mfoo"), Ok(("foo", Some(NoteType::Mine)))); assert_eq!(notetype("Lfoo"), Ok(("foo", Some(NoteType::Lift)))); assert_eq!(notetype("Ffoo"), Ok(("foo", Some(NoteType::Fake)))); assert_eq!(notetype("0foo"), Ok(("foo", None))); assert_eq!(notetype("\rfoo"), Err(Error(("\rfoo", ErrorKind::NoneOf)))); assert_eq!(notetype("\nfoo"), Err(Error(("\nfoo", ErrorKind::NoneOf)))); assert_eq!(notetype(",foo"), Err(Error((",foo", ErrorKind::NoneOf)))); } #[test] fn parse_noterow() { assert_eq!( noterow("0101\n"), Ok(( "\n", vec![Note::new(NoteType::Tap, 1), Note::new(NoteType::Tap, 3)] )) ); } #[test] fn parse_measure() { assert_eq!( measure( "0000\n \ 0100\n \ 0000\n \ 0010\n \ 0000\n" ), Ok(( "", vec![ (vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 5)), (vec![Note::new(NoteType::Tap, 2)], Rational32::new(3, 5)), ] )) ); } #[test] fn parse_comment() { assert_eq!(comment("// foo\nbar"), Ok(("\nbar", " foo"))); } #[test] fn parse_chart() { assert_eq!( chart( " foo:: bar :: 0.000,0.000 :\n\n \ 0000\n \ 0100\n \ 0000\n \ 0000\n \ , // baz\n 0000\n \ 0000\n \ 0010\n \ 0000\n" ), Ok(( "", vec![ vec![(vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 4))], vec![(vec![Note::new(NoteType::Tap, 2)], Rational32::new(1, 2))], ] )) ); } #[test] fn parse_notedata() { assert_eq!( notedata( "content that is #TITLE:bar1; not part of a tag is discarded #SUBTITLE:bar2;#ARTIST:bar3;#TITLETRANSLIT:bar4;#SUBTITLETRANSLIT:bar5; #ARTISTTRANSLIT:bar6;#GENRE:bar7;#CREDIT:bar8;#BANNER:bar9; #BACKGROUND:bar10;#LYRICSPATH:bar11;#CDTITLE:bar12;#MUSIC:bar13; #SAMPLESTART: 1.2 ;#SAMPLELENGTH: 3.4 ;#BPMS: 1.0=2 ; #STOPS: 3.0=4 ;#OFFSET: 1 ;#DISPLAYBPM: * ;#STOPS: ; #NOTES: ::::: \ 0000\n \ 0100\n \ 0000\n \ 0000\n \ ; #NOTES: ::::: \ 0000\n \ 0000\n \ 0010\n \ 0000\n \ ;" ), Ok(( "", NoteData { meta: ChartMetadata { title: Some("bar1".to_owned()), subtitle: Some("bar2".to_owned()), artist: Some("bar3".to_owned()), title_translit: Some("bar4".to_owned()), subtitle_translit: Some("bar5".to_owned()), artist_translit: Some("bar6".to_owned()), genre: Some("bar7".to_owned()), credit: Some("bar8".to_owned()), banner_path: Some("bar9".to_owned()), background_path: Some("bar10".to_owned()), lyrics_path: Some("bar11".to_owned()), cd_title: Some("bar12".to_owned()), music_path: Some("bar13".to_owned()), sample_start: Some(1.2), sample_length: Some(3.4), display_bpm: Some(DisplayBpm::Random), background_changes: None, foreground_changes: None, selectable: None, }, structure: StructureData { bpms: vec![BeatPair::from_pair(1. / 4.0, 2.0).unwrap()], stops: Some(vec![BeatPair::from_pair(3. / 4.0, 4.0).unwrap()]), offset: Some(-1.0), }, charts: vec![ vec![vec![( vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 4), )]], vec![vec![( vec![Note::new(NoteType::Tap, 2)], Rational32::new(2, 4), )]], ], } )) ); } }
use crate::{ parser_generic::{beat_pair, comma_separated, stepmania_tag, ws_trimmed}, Chart, DisplayBpm, Measure, Note, NoteData, NoteRow, NoteType, }; use nom::{ branch::alt, bytes::complete::{tag, take_until}, character::complete::{char, multispace1, none_of, not_line_ending}, combinator::map, error::ErrorKind, multi::{count, fold_many0, fold_many1, many0, separated_nonempty_list}, number::complete::double, sequence::{preceded, separat
IT" => nd.meta.subtitle_translit = Some(value.to_owned()), "ARTISTTRANSLIT" => nd.meta.artist_translit = Some(value.to_owned()), "GENRE" => nd.meta.genre = Some(value.to_owned()), "CREDIT" => nd.meta.credit = Some(value.to_owned()), "BANNER" => nd.meta.banner_path = Some(value.to_owned()), "BACKGROUND" => nd.meta.background_path = Some(value.to_owned()), "LYRICSPATH" => nd.meta.lyrics_path = Some(value.to_owned()), "CDTITLE" => nd.meta.cd_title = Some(value.to_owned()), "MUSIC" => nd.meta.music_path = Some(value.to_owned()), "SAMPLESTART" => nd.meta.sample_start = Some(ws_trimmed(double)(value)?.1), "SAMPLELENGTH" => nd.meta.sample_length = Some(ws_trimmed(double)(value)?.1), "OFFSET" => nd.structure.offset = Some(-ws_trimmed(double)(value)?.1), "DISPLAYBPM" => nd.meta.display_bpm = Some(ws_trimmed(display_bpm)(value)?.1), "BPMS" => { nd.structure.bpms = ws_trimmed(comma_separated(beat_pair(double, 4.0)))(value)?.1 } "STOPS" => { nd.structure.stops = Some(ws_trimmed(comma_separated(beat_pair(double, 4.0)))(value)?.1) } "NOTES" => nd.charts.push(chart(value)?.1), _ => {} } } } Ok((input, nd)) } pub fn parse(input: &str) -> Result<NoteData, Err<(&str, ErrorKind)>> { notedata(input).map(|notedata| notedata.1) } #[cfg(test)] mod tests { use super::*; use crate::{BeatPair, ChartMetadata, StructureData}; use nom::Err::Error; #[test] fn parse_display_bpm() { assert_eq!( display_bpm("1.2 : 3.4 foo"), Ok((" foo", DisplayBpm::Range(1.2, 3.4))) ); assert_eq!(display_bpm("1.2foo"), Ok(("foo", DisplayBpm::Static(1.2)))); assert_eq!(display_bpm("*"), Ok(("", DisplayBpm::Random))); } #[test] fn parse_notetype() { assert_eq!(notetype("1foo"), Ok(("foo", Some(NoteType::Tap)))); assert_eq!(notetype("2foo"), Ok(("foo", Some(NoteType::Hold)))); assert_eq!(notetype("3foo"), Ok(("foo", Some(NoteType::HoldEnd)))); assert_eq!(notetype("4foo"), Ok(("foo", Some(NoteType::Roll)))); assert_eq!(notetype("Mfoo"), Ok(("foo", Some(NoteType::Mine)))); assert_eq!(notetype("Lfoo"), Ok(("foo", Some(NoteType::Lift)))); assert_eq!(notetype("Ffoo"), Ok(("foo", Some(NoteType::Fake)))); assert_eq!(notetype("0foo"), Ok(("foo", None))); assert_eq!(notetype("\rfoo"), Err(Error(("\rfoo", ErrorKind::NoneOf)))); assert_eq!(notetype("\nfoo"), Err(Error(("\nfoo", ErrorKind::NoneOf)))); assert_eq!(notetype(",foo"), Err(Error((",foo", ErrorKind::NoneOf)))); } #[test] fn parse_noterow() { assert_eq!( noterow("0101\n"), Ok(( "\n", vec![Note::new(NoteType::Tap, 1), Note::new(NoteType::Tap, 3)] )) ); } #[test] fn parse_measure() { assert_eq!( measure( "0000\n \ 0100\n \ 0000\n \ 0010\n \ 0000\n" ), Ok(( "", vec![ (vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 5)), (vec![Note::new(NoteType::Tap, 2)], Rational32::new(3, 5)), ] )) ); } #[test] fn parse_comment() { assert_eq!(comment("// foo\nbar"), Ok(("\nbar", " foo"))); } #[test] fn parse_chart() { assert_eq!( chart( " foo:: bar :: 0.000,0.000 :\n\n \ 0000\n \ 0100\n \ 0000\n \ 0000\n \ , // baz\n 0000\n \ 0000\n \ 0010\n \ 0000\n" ), Ok(( "", vec![ vec![(vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 4))], vec![(vec![Note::new(NoteType::Tap, 2)], Rational32::new(1, 2))], ] )) ); } #[test] fn parse_notedata() { assert_eq!( notedata( "content that is #TITLE:bar1; not part of a tag is discarded #SUBTITLE:bar2;#ARTIST:bar3;#TITLETRANSLIT:bar4;#SUBTITLETRANSLIT:bar5; #ARTISTTRANSLIT:bar6;#GENRE:bar7;#CREDIT:bar8;#BANNER:bar9; #BACKGROUND:bar10;#LYRICSPATH:bar11;#CDTITLE:bar12;#MUSIC:bar13; #SAMPLESTART: 1.2 ;#SAMPLELENGTH: 3.4 ;#BPMS: 1.0=2 ; #STOPS: 3.0=4 ;#OFFSET: 1 ;#DISPLAYBPM: * ;#STOPS: ; #NOTES: ::::: \ 0000\n \ 0100\n \ 0000\n \ 0000\n \ ; #NOTES: ::::: \ 0000\n \ 0000\n \ 0010\n \ 0000\n \ ;" ), Ok(( "", NoteData { meta: ChartMetadata { title: Some("bar1".to_owned()), subtitle: Some("bar2".to_owned()), artist: Some("bar3".to_owned()), title_translit: Some("bar4".to_owned()), subtitle_translit: Some("bar5".to_owned()), artist_translit: Some("bar6".to_owned()), genre: Some("bar7".to_owned()), credit: Some("bar8".to_owned()), banner_path: Some("bar9".to_owned()), background_path: Some("bar10".to_owned()), lyrics_path: Some("bar11".to_owned()), cd_title: Some("bar12".to_owned()), music_path: Some("bar13".to_owned()), sample_start: Some(1.2), sample_length: Some(3.4), display_bpm: Some(DisplayBpm::Random), background_changes: None, foreground_changes: None, selectable: None, }, structure: StructureData { bpms: vec![BeatPair::from_pair(1. / 4.0, 2.0).unwrap()], stops: Some(vec![BeatPair::from_pair(3. / 4.0, 4.0).unwrap()]), offset: Some(-1.0), }, charts: vec![ vec![vec![( vec![Note::new(NoteType::Tap, 1)], Rational32::new(1, 4), )]], vec![vec![( vec![Note::new(NoteType::Tap, 2)], Rational32::new(2, 4), )]], ], } )) ); } }
ed_pair, terminated}, Err, IResult, }; use num_rational::Rational32; fn display_bpm(input: &str) -> IResult<&str, DisplayBpm> { alt(( map( separated_pair(double, ws_trimmed(char(':')), double), |(min, max)| DisplayBpm::Range(min, max), ), map(double, DisplayBpm::Static), map(char('*'), |_| DisplayBpm::Random), ))(input) } fn notetype(input: &str) -> IResult<&str, Option<NoteType>> { map(none_of("\r\n,"), into_sm_notetype)(input) } fn into_sm_notetype(sm_char: char) -> Option<NoteType> { match sm_char { '1' => Some(NoteType::Tap), '2' => Some(NoteType::Hold), '3' => Some(NoteType::HoldEnd), '4' => Some(NoteType::Roll), 'M' => Some(NoteType::Mine), 'L' => Some(NoteType::Lift), 'F' => Some(NoteType::Fake), _ => None, } } fn noterow(input: &str) -> IResult<&str, NoteRow> { map( fold_many1(notetype, (vec![], 0), |(mut noterow, mut index), item| { if let Some(item) = item { noterow.push(Note::new(item, index)) } index += 1; (noterow, index) }), |(noterow, _)| noterow, )(input) } fn measure(input: &str) -> IResult<&str, Measure> { map( fold_many0( terminated(noterow, multispace1), (vec![], 0), |(mut noterows, mut index), item| { if !item.is_empty() { noterows.push((item, index)) } index += 1; (noterows, index) }, ), |(noterows, total)| { noterows .into_iter() .map(|(item, index)| (item, Rational32::new(index, total))) .collect() }, )(input) } fn chart(input: &str) -> IResult<&str, Chart> { preceded( terminated( count(terminated(take_until(":"), char(':')), 5), many0(alt((comment, multispace1))), ), separated_nonempty_list( preceded( many0(alt((comment, multispace1))), terminated(char(','), many0(alt((comment, multispace1)))), ), measure, ), )(input) } fn comment(input: &str) -> IResult<&str, &str> { preceded(tag("//"), not_line_ending)(input) } fn notedata(input: &str) -> IResult<&str, NoteData> { let mut input = input; let mut nd = NoteData::new(); while let Ok((output, (tag, value))) = preceded(take_until("#"), stepmania_tag)(input) { input = output; if !value.trim().is_empty() { match tag { "TITLE" => nd.meta.title = Some(value.to_owned()), "SUBTITLE" => nd.meta.subtitle = Some(value.to_owned()), "ARTIST" => nd.meta.artist = Some(value.to_owned()), "TITLETRANSLIT" => nd.meta.title_translit = Some(value.to_owned()), "SUBTITLETRANSL
random
[]
Rust
src/client.rs
erikjohnston/matrix-hyper-federation-client
9939cf12f9bc8437a376370a135c2ee4eddb8c33
use std::convert::TryInto; use std::sync::Arc; use anyhow::{bail, format_err, Context, Error}; use ed25519_dalek::Keypair; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use http::request::{Builder, Parts}; use http::{HeaderValue, Uri}; use hyper::body::{to_bytes, HttpBody}; use hyper::client::connect::Connect; use hyper::{Body, Client, Request, Response}; use serde::Serialize; use serde_json::value::RawValue; use signed_json::{Canonical, Signed}; use crate::server_resolver::MatrixConnector; pub type FederationClient = hyper::Client<MatrixConnector>; pub async fn new_federation_client() -> Result<FederationClient, Error> { let connector = MatrixConnector::with_default_resolver().await?; Ok(Client::builder().build(connector)) } #[derive(Debug, Clone)] pub struct SigningFederationClient<C = MatrixConnector> { client: Client<C>, server_name: String, key_id: String, secret_key: Arc<Keypair>, } impl SigningFederationClient<MatrixConnector> { pub async fn new( server_name: impl ToString, key_id: impl ToString, secret_key: Keypair, ) -> Result<Self, Error> { let connector = MatrixConnector::with_default_resolver().await?; Ok(SigningFederationClient { client: Client::builder().build(connector), server_name: server_name.to_string(), key_id: key_id.to_string(), secret_key: Arc::new(secret_key), }) } } impl<C> SigningFederationClient<C> { pub fn with_client( client: Client<C>, server_name: String, key_name: String, secret_key: Keypair, ) -> Self { SigningFederationClient { client, server_name, key_id: key_name, secret_key: Arc::new(secret_key), } } } impl<C> SigningFederationClient<C> where C: Connect + Clone + Send + Sync + 'static, { pub async fn get(&self, uri: Uri) -> Result<Response<Body>, Error> { let body = Body::default(); let mut req = Request::new(body); *req.uri_mut() = uri; Ok(self.request(req).await?) } pub async fn request(&self, req: Request<Body>) -> Result<Response<Body>, Error> { if req.uri().scheme() != Some(&"matrix".parse()?) { return Ok(self.client.request(req).await?); } if !req.body().is_end_stream() && req.headers().get(CONTENT_TYPE) != Some(&HeaderValue::from_static("application/json")) { bail!("Request has a non-JSON body") } let (mut parts, body) = req.into_parts(); let content = if body.is_end_stream() { None } else { let bytes = to_bytes(body).await?; let json_string = String::from_utf8(bytes.to_vec())?; Some(RawValue::from_string(json_string)?) }; let auth_header = make_auth_header_from_parts( &self.server_name, &self.key_id, &self.secret_key, &parts, content.as_ref(), ) .context("Failed to sign request")?; parts.headers.insert(AUTHORIZATION, auth_header.parse()?); let new_body = if let Some(raw_value) = content { raw_value.to_string().into() } else { Body::default() }; let new_req = Request::from_parts(parts, new_body); Ok(self.client.request(new_req).await?) } } pub fn make_auth_header<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, method: &str, path: &str, destination: &str, content: Option<T>, ) -> Result<String, Error> { let request_json = RequestJson { method, uri: path, origin: server_name, destination, content, }; let signed: Signed<_> = Signed::wrap(request_json).context("Failed to serialize content")?; let sig = signed.sign_detached(secret_key); let b64_sig = base64::encode_config(&sig, base64::STANDARD_NO_PAD); Ok(format!( r#"X-Matrix origin={},key="{}",sig="{}""#, server_name, key_id, b64_sig, )) } pub fn make_auth_header_from_parts<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, parts: &Parts, content: Option<T>, ) -> Result<String, Error> { make_auth_header( server_name, key_id, secret_key, parts.method.as_str(), parts .uri .path_and_query() .ok_or_else(|| format_err!("Path is required"))? .as_str(), parts .uri .host() .ok_or_else(|| format_err!("Host is required"))?, content, ) } pub fn sign_and_build_json_request<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, mut request_builder: Builder, content: Option<T>, ) -> Result<Request<Body>, Error> { let uri = request_builder .uri_ref() .ok_or_else(|| format_err!("URI must be set"))?; let host = uri .host() .ok_or_else(|| format_err!("Host is required in URI"))?; let path = uri .path_and_query() .ok_or_else(|| format_err!("Path is required in URI"))? .as_str(); let method = request_builder .method_ref() .ok_or_else(|| format_err!("Method must be set"))?; let canonical_content = if let Some(content) = content { Some(Canonical::wrap(content).context("Failed to serialize content")?) } else { None }; let header_string = make_auth_header( server_name, key_id, secret_key, method.as_str(), path, host, canonical_content.as_ref(), )?; let header_value = header_string.try_into()?; let body = if let Some(c) = canonical_content { Body::from(c.into_canonical()) } else { Body::default() }; request_builder .headers_mut() .map(|header_map| header_map.insert(AUTHORIZATION, header_value)); let request = request_builder.body(body)?; Ok(request) } #[derive(Serialize)] pub struct RequestJson<'a, T> { method: &'a str, uri: &'a str, origin: &'a str, destination: &'a str, #[serde(skip_serializing_if = "Option::is_none")] content: Option<T>, } pub trait SignedRequestBuilderExt { fn signed( self, server_name: &str, key_id: &str, secret_key: &Keypair, ) -> Result<Request<Body>, Error>; fn signed_json<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: T, ) -> Result<Request<Body>, Error>; fn signed_json_opt<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: Option<T>, ) -> Result<Request<Body>, Error>; } impl SignedRequestBuilderExt for Builder { fn signed( self, server_name: &str, key_id: &str, secret_key: &Keypair, ) -> Result<Request<Body>, Error> { sign_and_build_json_request::<()>(server_name, key_id, secret_key, self, None) } fn signed_json<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: T, ) -> Result<Request<Body>, Error> { sign_and_build_json_request(server_name, key_id, secret_key, self, Some(content)) } fn signed_json_opt<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: Option<T>, ) -> Result<Request<Body>, Error> { if let Some(content) = content { self.signed_json(server_name, key_id, secret_key, content) } else { self.signed(server_name, key_id, secret_key) } } } pub struct AuthHeader<'a> { pub origin: &'a str, pub key_id: &'a str, pub signature: &'a str, } pub fn parse_auth_header(header: &str) -> Option<AuthHeader> { let header = header.strip_prefix("X-Matrix ")?; let mut origin = None; let mut key_id = None; let mut signature = None; for item in header.split(',') { let (key, value) = item.split_at(item.find('=')?); let value = value.trim_matches('='); let value = if value.starts_with('"') && value.ends_with('"') { &value[1..value.len() - 1] } else { value }; match key { "origin" => origin = Some(value), "key" => key_id = Some(value), "sig" => signature = Some(value), _ => {} } } Some(AuthHeader { origin: origin?, key_id: key_id?, signature: signature?, }) } #[cfg(test)] mod test { use std::collections::BTreeMap; use ed25519_dalek::{PublicKey, SecretKey}; use super::*; #[test] fn test_parse_auth_header() { let header = parse_auth_header(r#"X-Matrix origin=foo.com,key="key_id",sig="some_signature""#) .unwrap(); assert_eq!(header.origin, "foo.com"); assert_eq!(header.key_id, "key_id"); assert_eq!(header.signature, "some_signature"); } #[tokio::test] async fn auth_header_no_content() { let secret = SecretKey::from_bytes(&[0u8; 32]).unwrap(); let public = PublicKey::from(&secret); let secret_key = Keypair { secret, public }; let header = make_auth_header::<()>( "localhost", "ed25519:test", &secret_key, "GET", "/test", "matrix.org", None, ) .unwrap(); assert_eq!( header, r#"X-Matrix origin=localhost,key="ed25519:test",sig="aemgn56SKst12mSbh2X0l3pBuzyWmAkURVknrTqz/ev2p8KDnKHXnFw/UsLOfwbD6V/om4Lh+DzeyE0MlJ1GBA""# ); } #[tokio::test] async fn auth_header_content() { let secret = SecretKey::from_bytes(&[0u8; 32]).unwrap(); let public = PublicKey::from(&secret); let secret_key = Keypair { secret, public }; let mut map = BTreeMap::new(); map.insert("foo", "bar"); let header = make_auth_header( "localhost", "ed25519:test", &secret_key, "GET", "/test", "matrix.org", Some(map), ) .unwrap(); assert_eq!( header, r#"X-Matrix origin=localhost,key="ed25519:test",sig="JwOvw9q9rGU1FOX+nVqZkXL9P6WhsKE3aNV2Q+Ftj0urJHv8olv7r7gOMZM3nITm0gVwYBN8s0FBGJymeQt9DA""# ); } }
use std::convert::TryInto; use std::sync::Arc; use anyhow::{bail, format_err, Context, Error}; use ed25519_dalek::Keypair; use http::header::{AUTHORIZATION, CONTENT_TYPE}; use http::request::{Builder, Parts}; use http::{HeaderValue, Uri}; use hyper::body::{to_bytes, HttpBody}; use hyper::client::connect::Connect; use hyper::{Body, Client, Request, Response}; use serde::Serialize; use serde_json::value::RawValue; use signed_json::{Canonical, Signed}; use crate::server_resolver::MatrixConnector; pub type FederationClient = hyper::Client<MatrixConnector>; pub async fn new_federation_client() -> Result<FederationClient, Error> { let connector = MatrixConnector::with_default_resolver().await?; Ok(Client::builder().build(connector)) } #[derive(Debug, Clone)] pub struct SigningFederationClient<C = MatrixConnector> { client: Client<C>, server_name: String, key_id: String, secret_key: Arc<Keypair>, } impl SigningFederationClient<MatrixConnector> { pub async fn new( server_name: impl ToString, key_id: impl ToString, secret_key: Keypair, ) -> Result<Self, Error> { let connector = MatrixConnector::with_default_resolver().await?; Ok(SigningFederationClient { client: Client::builder().build(connector), server_name: server_name.to_string(), key_id: key_id.to_string(), secret_key: Arc::new(secret_key), }) } } impl<C> SigningFederationClient<C> { pub fn with_client( client: Client<C>, server_name: String, key_name: String, secret_key: Keypair, ) -> Self { SigningFederationClient { client, server_name, key_id: key_name, secret_key: Arc::new(secret_key), } } } impl<C> SigningFederationClient<C> where C: Connect + Clone + Send + Sync + 'static, { pub async fn get(&self, uri: Uri) -> Result<Response<Body>, Error> { let body = Body::default(); let mut req = Request::new(body); *req.uri_mut() = uri; Ok(self.request(req).await?) } pub async fn request(&self, req: Request<Body>) -> Result<Response<Body>, Error> { if req.uri().scheme() != Some(&"matrix".parse()?) { return Ok(self.client.request(req).await?); } if !req.body().is_end_stream() && req.headers().get(CONTENT_TYPE) != Some(&HeaderValue::from_static("application/json")) { bail!("Request has a non-JSON body") } let (mut parts, body) = req.into_parts(); let content = if body.is_end_stream() { None } else { let bytes = to_bytes(body).await?; let json_string = String::from_utf8(bytes.to_vec())?; Some(RawValue::from_string(json_string)?) }; let auth_header = make_auth_header_from_parts( &self.server_name, &self.key_id, &self.secret_key, &parts, content.as_ref(), ) .context("Failed to sign request")?; parts.headers.insert(AUTHORIZATION, auth_header.parse()?); let new_body = if let Some(raw_value) = content { raw_value.to_string().into() } else { Body::default() }; let new_req = Request::from_parts(parts, new_body); Ok(self.client.request(new_req).await?) } } pub fn make_auth_header<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, method: &str, path: &str, destination: &str, content: Option<T>, ) -> Result<String, Error> { let request_json = RequestJson { method, uri: path, origin: server_name, destination, content, }; let signed: Signed<_> = Signed::wrap(request_json).context("Failed to serialize content")?; let sig = signed.sign_detached(secret_key); let b64_sig = base64::encode_config(&sig, base64::STANDARD_NO_PAD); Ok(format!( r#"X-Matrix origin={},key="{}",sig="{}""#, server_name, key_id, b64_sig, )) } pub fn make_auth_header_from_parts<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, parts: &Parts, content: Option<T>, ) -> Result<String, Error> { make_auth_header( server_name, key_id, secret_key, parts.method.as_str(), parts .uri .path_and_query() .ok_or_else(|| format_err!("Path is required"))? .as_str(), parts .uri .host() .ok_or_else(|| format_err!("Host is required"))?, content, ) } pub fn sign_and_build_json_request<T: serde::Serialize>( server_name: &str, key_id: &str, secret_key: &Keypair, mut request_builder: Builder, content: Option<T>, ) -> Result<Request<Body>, Error> { let uri = request_builder .uri_ref() .ok_or_else(|| format_err!("URI must be set"))?; let host = uri .host() .ok_or_else(|| format_err!("Host is required in URI"))?; let path = uri .path_and_query() .ok_or_else(|| format_err!("Path is required in URI"))? .as_str(); let method = request_builder .method_ref() .ok_or_else(|| format_err!("Method must be set"))?; let canonical_content = if let Some(content) = content { Some(Canonical::wrap(content).context("Failed to serialize content")?) } else { None }; let header_string = make_auth_header( server_name, key_id, secret_key, method.as_str(), path, host, canonical_content.as_ref(), )?; let header_value = header_string.try_into()?; let body = if let Some(c) = canonical_content { Body::from(c.into_canonical()) } else { Body::default() }; request_builder .headers_mut() .map(|header_map| header_map.insert(AUTHORIZATION, header_value)); let request = request_builder.body(body)?; Ok(request) } #[derive(Serialize)] pub struct RequestJson<'a, T> { method: &'a str, uri: &'a str, origin: &'a str, destination: &'a str, #[serde(skip_serializing_if = "Option::is_none")] content: Option<T>, } pub trait SignedRequestBuilderExt { fn signed( self, server_name: &str, key_id: &str, secret_key: &Keypair, ) -> Result<Request<Body>, Error>; fn signed_json<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: T, ) -> Result<Request<Body>, Error>; fn signed_json_opt<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: Option<T>, ) -> Result<Request<Body>, Error>; } impl SignedRequestBuilderExt for Builder { fn signed( self, server_name: &str, key_id: &str, secret_key: &Keypair, ) -> Result<Request<Body>, Error> { sign_and_build_json_request::<()>(server_name, key_id, secret_key, self, None) } fn signed_json<T: Serialize>( self, server_name: &str, key_id: &str, secret_key: &Keypair, content: T, ) -> Result<Request<Body>, Error> { sign_and_build_json_request(server_name, key_id, secret_key, self, Some(content)) } fn signed_json_opt<T: Serialize>( self, server_name: &str, key_id: &str,
} pub struct AuthHeader<'a> { pub origin: &'a str, pub key_id: &'a str, pub signature: &'a str, } pub fn parse_auth_header(header: &str) -> Option<AuthHeader> { let header = header.strip_prefix("X-Matrix ")?; let mut origin = None; let mut key_id = None; let mut signature = None; for item in header.split(',') { let (key, value) = item.split_at(item.find('=')?); let value = value.trim_matches('='); let value = if value.starts_with('"') && value.ends_with('"') { &value[1..value.len() - 1] } else { value }; match key { "origin" => origin = Some(value), "key" => key_id = Some(value), "sig" => signature = Some(value), _ => {} } } Some(AuthHeader { origin: origin?, key_id: key_id?, signature: signature?, }) } #[cfg(test)] mod test { use std::collections::BTreeMap; use ed25519_dalek::{PublicKey, SecretKey}; use super::*; #[test] fn test_parse_auth_header() { let header = parse_auth_header(r#"X-Matrix origin=foo.com,key="key_id",sig="some_signature""#) .unwrap(); assert_eq!(header.origin, "foo.com"); assert_eq!(header.key_id, "key_id"); assert_eq!(header.signature, "some_signature"); } #[tokio::test] async fn auth_header_no_content() { let secret = SecretKey::from_bytes(&[0u8; 32]).unwrap(); let public = PublicKey::from(&secret); let secret_key = Keypair { secret, public }; let header = make_auth_header::<()>( "localhost", "ed25519:test", &secret_key, "GET", "/test", "matrix.org", None, ) .unwrap(); assert_eq!( header, r#"X-Matrix origin=localhost,key="ed25519:test",sig="aemgn56SKst12mSbh2X0l3pBuzyWmAkURVknrTqz/ev2p8KDnKHXnFw/UsLOfwbD6V/om4Lh+DzeyE0MlJ1GBA""# ); } #[tokio::test] async fn auth_header_content() { let secret = SecretKey::from_bytes(&[0u8; 32]).unwrap(); let public = PublicKey::from(&secret); let secret_key = Keypair { secret, public }; let mut map = BTreeMap::new(); map.insert("foo", "bar"); let header = make_auth_header( "localhost", "ed25519:test", &secret_key, "GET", "/test", "matrix.org", Some(map), ) .unwrap(); assert_eq!( header, r#"X-Matrix origin=localhost,key="ed25519:test",sig="JwOvw9q9rGU1FOX+nVqZkXL9P6WhsKE3aNV2Q+Ftj0urJHv8olv7r7gOMZM3nITm0gVwYBN8s0FBGJymeQt9DA""# ); } }
secret_key: &Keypair, content: Option<T>, ) -> Result<Request<Body>, Error> { if let Some(content) = content { self.signed_json(server_name, key_id, secret_key, content) } else { self.signed(server_name, key_id, secret_key) } }
function_block-function_prefix_line
[ { "content": "type ConnectorFuture =\n\n Pin<Box<dyn Future<Output = Result<MaybeHttpsStream<TcpStream>, Error>> + Send>>;\n\n\n\nimpl Service<Uri> for MatrixConnector {\n\n type Response = MaybeHttpsStream<TcpStream>;\n\n type Error = Error;\n\n type Future = ConnectorFuture;\n\n\n\n fn poll_rea...
Rust
src/terminal/config/input_filter.rs
ovnz/BearLibTerminal.rs
0a963d631125e20eae6f7d9a652ba4e278dc9df9
use std::fmt; use terminal::config::{ConfigPart, escape_config_string}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilter { Event{name: InputFilterEvent, both: bool}, Group{group: InputFilterGroup, both: bool}, Alnum{keys: String, both: bool}, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilterGroup { Arrow, Keypad, Keyboard, Mouse, System, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilterEvent { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Row0, Row1, Row2, Row3, Row4, Row5, Row6, Row7, Row8, Row9, Space, Minus, Equals, LBracket, RBracket, Backslash, Semicolon, Apostrophe, Grave, Comma, Period, Slash, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Return, Escape, Backspace, Tab, Pause, Insert, Home, Pageup, Delete, End, Pagedown, Right, Left, Down, Up, Shift, Control, Pad0, Pad1, Pad2, Pad3, Pad4, Pad5, Pad6, Pad7, Pad8, Pad9, PadDivide, PadMultiply, PadMinus, PadPlus, PadPeriod, PadEnter, MouseLeft, MouseRight, MouseMiddle, MouseX1, MouseX2, MouseMove, MouseScroll, MouseWheel, MouseX, MouseY, MousePixelX, MousePixelY, MouseClicks, Width, Height, CellWidth, CellHeight, Color, Bkcolor, Layer, Composition, Char, Wchar, Event, Fullscreen, Close, Resized, } impl ConfigPart for Vec<InputFilter> { fn to_config_str(&self) -> String { format!("input.filter = [{}];", { let mut elems = "".to_string(); for filter in self { elems = format!("{}{}, ", elems, escape_config_string(&match filter { &InputFilter::Event{ref name, both} => format!("{}{}", name, if both {"+"} else {""}), &InputFilter::Group{ref group, both} => format!("{}{}", group, if both {"+"} else {""}), &InputFilter::Alnum{ref keys, both} => format!("{}{}", keys, if both {"+"} else {""}), })); } elems.pop(); elems.pop(); elems }) } } impl fmt::Display for InputFilterGroup { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { &InputFilterGroup::Arrow => "arrow", &InputFilterGroup::Keypad => "keypad", &InputFilterGroup::Keyboard => "keyboard", &InputFilterGroup::Mouse => "mouse", &InputFilterGroup::System => "system", }) } } impl fmt::Display for InputFilterEvent { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { &InputFilterEvent::A => "A", &InputFilterEvent::B => "B", &InputFilterEvent::C => "C", &InputFilterEvent::D => "D", &InputFilterEvent::E => "E", &InputFilterEvent::F => "F", &InputFilterEvent::G => "G", &InputFilterEvent::H => "H", &InputFilterEvent::I => "I", &InputFilterEvent::J => "J", &InputFilterEvent::K => "K", &InputFilterEvent::L => "L", &InputFilterEvent::M => "M", &InputFilterEvent::N => "N", &InputFilterEvent::O => "O", &InputFilterEvent::P => "P", &InputFilterEvent::Q => "Q", &InputFilterEvent::R => "R", &InputFilterEvent::S => "S", &InputFilterEvent::T => "T", &InputFilterEvent::U => "U", &InputFilterEvent::V => "V", &InputFilterEvent::W => "W", &InputFilterEvent::X => "X", &InputFilterEvent::Y => "Y", &InputFilterEvent::Z => "Z", &InputFilterEvent::Row0 => "0", &InputFilterEvent::Row1 => "1", &InputFilterEvent::Row2 => "2", &InputFilterEvent::Row3 => "3", &InputFilterEvent::Row4 => "4", &InputFilterEvent::Row5 => "5", &InputFilterEvent::Row6 => "6", &InputFilterEvent::Row7 => "7", &InputFilterEvent::Row8 => "8", &InputFilterEvent::Row9 => "9", &InputFilterEvent::Space => "space", &InputFilterEvent::Minus => "minus", &InputFilterEvent::Equals => "equals", &InputFilterEvent::LBracket => "lbracket", &InputFilterEvent::RBracket => "rbracket", &InputFilterEvent::Backslash => "backslash", &InputFilterEvent::Semicolon => "semicolon", &InputFilterEvent::Apostrophe => "apostrophe", &InputFilterEvent::Grave => "grave", &InputFilterEvent::Comma => "comma", &InputFilterEvent::Period => "period", &InputFilterEvent::Slash => "slash", &InputFilterEvent::F1 => "F1", &InputFilterEvent::F2 => "F2", &InputFilterEvent::F3 => "F3", &InputFilterEvent::F4 => "F4", &InputFilterEvent::F5 => "F5", &InputFilterEvent::F6 => "F6", &InputFilterEvent::F7 => "F7", &InputFilterEvent::F8 => "F8", &InputFilterEvent::F9 => "F9", &InputFilterEvent::F10 => "F10", &InputFilterEvent::F11 => "F11", &InputFilterEvent::F12 => "F12", &InputFilterEvent::Return => "return", &InputFilterEvent::Escape => "escape", &InputFilterEvent::Backspace => "backspace", &InputFilterEvent::Tab => "tab", &InputFilterEvent::Pause => "pause", &InputFilterEvent::Insert => "insert", &InputFilterEvent::Home => "home", &InputFilterEvent::Pageup => "pageup", &InputFilterEvent::Delete => "delete", &InputFilterEvent::End => "end", &InputFilterEvent::Pagedown => "pagedown", &InputFilterEvent::Right => "right", &InputFilterEvent::Left => "left", &InputFilterEvent::Down => "down", &InputFilterEvent::Up => "up", &InputFilterEvent::Shift => "shift", &InputFilterEvent::Control => "control", &InputFilterEvent::Pad0 => "KP_0", &InputFilterEvent::Pad1 => "KP_1", &InputFilterEvent::Pad2 => "KP_2", &InputFilterEvent::Pad3 => "KP_3", &InputFilterEvent::Pad4 => "KP_4", &InputFilterEvent::Pad5 => "KP_5", &InputFilterEvent::Pad6 => "KP_6", &InputFilterEvent::Pad7 => "KP_7", &InputFilterEvent::Pad8 => "KP_8", &InputFilterEvent::Pad9 => "KP_9", &InputFilterEvent::PadDivide => "KP_divide", &InputFilterEvent::PadMultiply => "KP_multiply", &InputFilterEvent::PadMinus => "KP_minus", &InputFilterEvent::PadPlus => "KP_plus", &InputFilterEvent::PadPeriod => "KP_period", &InputFilterEvent::PadEnter => "KP_enter", &InputFilterEvent::MouseLeft => "mouse_left", &InputFilterEvent::MouseRight => "mouse_right", &InputFilterEvent::MouseMiddle => "mouse_middle", &InputFilterEvent::MouseX1 => "mouse_x1", &InputFilterEvent::MouseX2 => "mouse_x2", &InputFilterEvent::MouseMove => "mouse_move", &InputFilterEvent::MouseScroll => "mouse_scroll", &InputFilterEvent::MouseWheel => "mouse_wheel", &InputFilterEvent::MouseX => "mouse_x", &InputFilterEvent::MouseY => "mouse_y", &InputFilterEvent::MousePixelX => "mouse_pixelx", &InputFilterEvent::MousePixelY => "mouse_pixely", &InputFilterEvent::MouseClicks => "mouse_clicks", &InputFilterEvent::Width => "width", &InputFilterEvent::Height => "height", &InputFilterEvent::CellWidth => "cell_width", &InputFilterEvent::CellHeight => "cell_height", &InputFilterEvent::Color => "color", &InputFilterEvent::Bkcolor => "bkcolor", &InputFilterEvent::Layer => "layer", &InputFilterEvent::Composition => "composition", &InputFilterEvent::Char => "char", &InputFilterEvent::Wchar => "wchar", &InputFilterEvent::Event => "event", &InputFilterEvent::Fullscreen => "fullscreen", &InputFilterEvent::Close => "close", &InputFilterEvent::Resized => "resized", }) } }
use std::fmt; use terminal::config::{ConfigPart, escape_config_string}; #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilter { Event{name: InputFilterEvent, both: bool}, Group{group: InputFilterGroup, both: bool}, Alnum{keys: String, both: bool}, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilterGroup { Arrow, Keypad, Keyboard, Mouse, System, } #[derive(Clone, Debug, Eq, PartialEq, Hash)] pub enum InputFilterEvent { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Row0, Row1, Row2, Row3, Row4, Row5, Row6, Row7, Row8, Row9, Space, Minus, Equals, LBracket, RBracket, Backslash, Semicolon, Apostrophe, Grave, Comma, Period, Slash, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Return, Escape, Backspace, Tab, Pause, Insert, Home, Pageup, Delete, End, Pagedown, Right, Left, Down, Up, Shift, Control, Pad0, Pad1, Pad2, Pad3, Pad4, Pad5, Pad6, Pad7, Pad8, Pad9, PadDivide, PadMultiply, PadMinus, PadPlus, PadPeriod, PadEnter, MouseLeft, MouseRight, MouseMiddle, MouseX1, MouseX2, MouseMove, MouseScroll, MouseWheel, MouseX, MouseY, MousePixelX, MousePixelY, MouseClicks, Width, Height, CellWidth, CellHeight, Color, Bkcolor, Layer, Composition, Char, Wchar, Event, Fullscreen, Close, Resized, } impl ConfigPart for Vec<InputFilter> { fn to_config_str(&self) -> String { format!("input.filter = [{}];", { let mut elems = "".to_string(); for filter in self { elems = format!("{}{}, ", elems, escape_config_string(&match filter { &InputFilter::Event{ref name, both} => format!("{}{}", name, if both {"+"} else {""}), &InputFilter::Group{ref group, both} => format!("{}{}", group, if both {"+"} else {""}), &InputFilter::Alnum{ref keys, both} => format!("{}{}", keys, if both {"+"} else {""}), })); } elems.pop(); elems.pop(); elems }) } } impl fmt::Display for InputFilterGroup { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { &InputFilterGroup::Arrow => "arrow", &InputFilterGroup::Keypad => "keypad", &InputFilterGroup::Keyboard => "keyboard", &InputFilterGroup::Mouse => "mouse", &InputFilterGroup::System => "system", }) } } impl fmt::Display for InputFilterEvent {
}
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str(match self { &InputFilterEvent::A => "A", &InputFilterEvent::B => "B", &InputFilterEvent::C => "C", &InputFilterEvent::D => "D", &InputFilterEvent::E => "E", &InputFilterEvent::F => "F", &InputFilterEvent::G => "G", &InputFilterEvent::H => "H", &InputFilterEvent::I => "I", &InputFilterEvent::J => "J", &InputFilterEvent::K => "K", &InputFilterEvent::L => "L", &InputFilterEvent::M => "M", &InputFilterEvent::N => "N", &InputFilterEvent::O => "O", &InputFilterEvent::P => "P", &InputFilterEvent::Q => "Q", &InputFilterEvent::R => "R", &InputFilterEvent::S => "S", &InputFilterEvent::T => "T", &InputFilterEvent::U => "U", &InputFilterEvent::V => "V", &InputFilterEvent::W => "W", &InputFilterEvent::X => "X", &InputFilterEvent::Y => "Y", &InputFilterEvent::Z => "Z", &InputFilterEvent::Row0 => "0", &InputFilterEvent::Row1 => "1", &InputFilterEvent::Row2 => "2", &InputFilterEvent::Row3 => "3", &InputFilterEvent::Row4 => "4", &InputFilterEvent::Row5 => "5", &InputFilterEvent::Row6 => "6", &InputFilterEvent::Row7 => "7", &InputFilterEvent::Row8 => "8", &InputFilterEvent::Row9 => "9", &InputFilterEvent::Space => "space", &InputFilterEvent::Minus => "minus", &InputFilterEvent::Equals => "equals", &InputFilterEvent::LBracket => "lbracket", &InputFilterEvent::RBracket => "rbracket", &InputFilterEvent::Backslash => "backslash", &InputFilterEvent::Semicolon => "semicolon", &InputFilterEvent::Apostrophe => "apostrophe", &InputFilterEvent::Grave => "grave", &InputFilterEvent::Comma => "comma", &InputFilterEvent::Period => "period", &InputFilterEvent::Slash => "slash", &InputFilterEvent::F1 => "F1", &InputFilterEvent::F2 => "F2", &InputFilterEvent::F3 => "F3", &InputFilterEvent::F4 => "F4", &InputFilterEvent::F5 => "F5", &InputFilterEvent::F6 => "F6", &InputFilterEvent::F7 => "F7", &InputFilterEvent::F8 => "F8", &InputFilterEvent::F9 => "F9", &InputFilterEvent::F10 => "F10", &InputFilterEvent::F11 => "F11", &InputFilterEvent::F12 => "F12", &InputFilterEvent::Return => "return", &InputFilterEvent::Escape => "escape", &InputFilterEvent::Backspace => "backspace", &InputFilterEvent::Tab => "tab", &InputFilterEvent::Pause => "pause", &InputFilterEvent::Insert => "insert", &InputFilterEvent::Home => "home", &InputFilterEvent::Pageup => "pageup", &InputFilterEvent::Delete => "delete", &InputFilterEvent::End => "end", &InputFilterEvent::Pagedown => "pagedown", &InputFilterEvent::Right => "right", &InputFilterEvent::Left => "left", &InputFilterEvent::Down => "down", &InputFilterEvent::Up => "up", &InputFilterEvent::Shift => "shift", &InputFilterEvent::Control => "control", &InputFilterEvent::Pad0 => "KP_0", &InputFilterEvent::Pad1 => "KP_1", &InputFilterEvent::Pad2 => "KP_2", &InputFilterEvent::Pad3 => "KP_3", &InputFilterEvent::Pad4 => "KP_4", &InputFilterEvent::Pad5 => "KP_5", &InputFilterEvent::Pad6 => "KP_6", &InputFilterEvent::Pad7 => "KP_7", &InputFilterEvent::Pad8 => "KP_8", &InputFilterEvent::Pad9 => "KP_9", &InputFilterEvent::PadDivide => "KP_divide", &InputFilterEvent::PadMultiply => "KP_multiply", &InputFilterEvent::PadMinus => "KP_minus", &InputFilterEvent::PadPlus => "KP_plus", &InputFilterEvent::PadPeriod => "KP_period", &InputFilterEvent::PadEnter => "KP_enter", &InputFilterEvent::MouseLeft => "mouse_left", &InputFilterEvent::MouseRight => "mouse_right", &InputFilterEvent::MouseMiddle => "mouse_middle", &InputFilterEvent::MouseX1 => "mouse_x1", &InputFilterEvent::MouseX2 => "mouse_x2", &InputFilterEvent::MouseMove => "mouse_move", &InputFilterEvent::MouseScroll => "mouse_scroll", &InputFilterEvent::MouseWheel => "mouse_wheel", &InputFilterEvent::MouseX => "mouse_x", &InputFilterEvent::MouseY => "mouse_y", &InputFilterEvent::MousePixelX => "mouse_pixelx", &InputFilterEvent::MousePixelY => "mouse_pixely", &InputFilterEvent::MouseClicks => "mouse_clicks", &InputFilterEvent::Width => "width", &InputFilterEvent::Height => "height", &InputFilterEvent::CellWidth => "cell_width", &InputFilterEvent::CellHeight => "cell_height", &InputFilterEvent::Color => "color", &InputFilterEvent::Bkcolor => "bkcolor", &InputFilterEvent::Layer => "layer", &InputFilterEvent::Composition => "composition", &InputFilterEvent::Char => "char", &InputFilterEvent::Wchar => "wchar", &InputFilterEvent::Event => "event", &InputFilterEvent::Fullscreen => "fullscreen", &InputFilterEvent::Close => "close", &InputFilterEvent::Resized => "resized", }) }
function_block-full_function
[ { "content": "fn get_key(released: bool, key: KeyCode, ctrl: bool, shift: bool) -> Event {\n\n\tif released {\n\n\t\tEvent::KeyReleased{\n\n\t\t\tkey: key,\n\n\t\t\tctrl: ctrl,\n\n\t\t\tshift: shift,\n\n\t\t}\n\n\t} else {\n\n\t\tEvent::KeyPressed{\n\n\t\t\tkey: key,\n\n\t\t\tctrl: ctrl,\n\n\t\t\tshift: shift,\...
Rust
src/main.rs
mkb2091/msolve
7ccdda6626ada1cc3abdf0e1abb7cd32f3618e4c
#[cfg(feature = "cli")] mod cli { #[cfg(not(feature = "std"))] compile_error!("`std` feature is required for cli"); use std::io::BufRead; use std::io::Write; use clap::Clap; #[derive(Clap, Copy, Clone)] #[clap(version = "1.0")] struct Opts { #[clap(short, long)] verify_uniqueness: bool, #[clap(short, long)] count_steps: bool, #[clap(subcommand)] mode: Mode, } #[derive(Clap, Copy, Clone)] enum Mode { Solve(Solve), Select(Select), Difficulty, CountSolutions(CountSolutions), #[cfg(feature = "generate")] Generate(Generate), ListTechniques, Info, } #[derive(Clap, Copy, Clone)] struct Solve { #[clap(short, long, default_value = "1")] count: usize, } #[derive(Clap, Copy, Clone)] struct Select { #[clap(short, long)] invert: bool, } #[derive(Clap, Copy, Clone)] struct CountSolutions { n: usize, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct Generate { #[clap(subcommand)] mode: GenerateMode, #[clap(short, long)] display_score: bool, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] enum GenerateMode { Once(GenerateOnce), Continuous(GenerateContinuous), } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct GenerateOnce { cells_to_remove: usize, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct GenerateContinuous { #[clap(short, long)] n: Option<std::num::NonZeroUsize>, } fn score_sudoku(sudoku: &msolve::Sudoku, opts: &Opts) -> Option<i32> { sudoku.difficulty(opts.count_steps) } pub fn main() { let opts: Opts = Opts::parse(); let stdin = std::io::stdin(); let mut input = stdin.lock(); let mut buffer = String::with_capacity(82); let stdout = std::io::stdout(); let mut output_handle = stdout.lock(); let mut info = [0; 3]; #[cfg(feature = "rand")] let mut rng = rand::thread_rng(); #[cfg(feature = "generate")] if let Mode::Generate(generate) = opts.mode { if let GenerateMode::Continuous(continuous) = generate.mode { let n = continuous.n.map(|n| n.get()).unwrap_or(0); let mut counter = 0; for (sudoku, score) in msolve::Sudoku::generate(rand::thread_rng(), opts.count_steps) { if generate.display_score { let _ = output_handle.write_all(&score.to_string().as_bytes()); let _ = output_handle.write_all(b";"); } let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); if n != 0 { counter += 1; if counter >= n { return; } } } } } while let Ok(result) = input.read_line(&mut buffer) { if result == 0 { break; } let sudoku = buffer.parse::<msolve::Sudoku>().unwrap(); match opts.mode { Mode::Solve(solve) => { if opts.verify_uniqueness { if let Some(solution) = sudoku.solve_unique() { let _ = output_handle.write_all(&solution.to_bytes()); let _ = output_handle.write_all(b"\n"); } } else { for solution in sudoku.iter().take(solve.count) { let _ = output_handle.write_all(&solution.to_bytes()); let _ = output_handle.write_all(b"\n"); } } } Mode::Select(select) => { let mut does_match = if opts.verify_uniqueness { sudoku.has_single_solution() } else { sudoku.has_solution() }; if select.invert { does_match = !does_match; } if does_match { let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } } Mode::Difficulty => { if let Some(difficulty) = score_sudoku(&sudoku, &opts) { let _ = output_handle.write_all(&difficulty.to_string().as_bytes()); let _ = output_handle.write_all(b";"); let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } } Mode::CountSolutions(n) => { let count = sudoku.count_solutions(n.n); let _ = output_handle.write_all(&count.to_string().as_bytes()); let _ = output_handle.write_all(b";"); let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } #[cfg(feature = "generate")] Mode::Generate(generate) => { if let GenerateMode::Once(once) = generate.mode { let (sudoku, score) = sudoku.generate_from_seed( &mut rng, once.cells_to_remove, opts.count_steps, ); if generate.display_score { let _ = output_handle.write_all(&score.to_string().as_bytes()); let _ = output_handle.write_all(b";"); } let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } else { unimplemented!() } } Mode::ListTechniques => { for (explanation, state) in sudoku.list_techniques().iter() { let _ = output_handle.write_all(&explanation.as_bytes()); let _ = output_handle.write_all(b"\n"); let _ = output_handle.write_all(&state.to_pencilmark_bytes()); let _ = output_handle.write_all(b"\n"); std::thread::sleep(std::time::Duration::from_secs(1)); } } Mode::Info => { info[sudoku.count_solutions(2)] += 1; } } buffer.clear(); } if let Mode::Info = opts.mode { println!( "0 Solutions: {}, 1 Solution: {}, 2+ Solutions: {}", info[0], info[1], info[2] ); } } } fn main() { #[cfg(feature = "cli")] cli::main() }
#[cfg(feature = "cli")] mod cli { #[cfg(not(feature = "std"))] compile_error!("`std` feature is required for cli"); use std::io::BufRead; use std::io::Write; use clap::Clap; #[derive(Clap, Copy, Clone)] #[clap(version = "1.0")] struct Opts { #[clap(short, long)] verify_uniqueness: bool, #[clap(short, long)] count_steps: bool, #[clap(subcommand)] mode: Mode, } #[derive(Clap, Copy, Clone)] enum Mode { Solve(Solve), Select(Select), Difficulty, CountSolutions(CountSolutions), #[cfg(feature = "generate")] Generate(Generate), ListTechniques, Info, } #[derive(Clap, Copy, Clone)] struct Solve { #[clap(short, long, default_value = "1")] count: usize, } #[derive(Clap, Copy, Clone)] struct Select { #[clap(short, long)] invert: bool, } #[derive(Clap, Copy, Clone)] struct CountSolutions { n: usize, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct Generate { #[clap(subcommand)] mode: GenerateMode, #[clap(short, long)] display_score: bool, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] enum GenerateMode { Once(GenerateOnce), Continuous(GenerateContinuous), } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct GenerateOnce { cells_to_remove: usize, } #[cfg(feature = "generate")] #[derive(Clap, Copy, Clone)] struct GenerateContinuous { #[clap(short, long)] n: Option<std::num::NonZeroUsize>, } fn score_sudoku(sudoku: &msolve::Sudoku, opts: &Opts) -> Option<i32> { sudoku.difficulty(opts.count_steps) } pub fn main() { let opts: Opts = Opts::parse(); let stdin = std::io::stdin(); let mut input = stdin.lock(); let mut buffer = String::with_capacity(82); let stdout = std::io::stdout(); let mut output_handle = stdout.
} fn main() { #[cfg(feature = "cli")] cli::main() }
lock(); let mut info = [0; 3]; #[cfg(feature = "rand")] let mut rng = rand::thread_rng(); #[cfg(feature = "generate")] if let Mode::Generate(generate) = opts.mode { if let GenerateMode::Continuous(continuous) = generate.mode { let n = continuous.n.map(|n| n.get()).unwrap_or(0); let mut counter = 0; for (sudoku, score) in msolve::Sudoku::generate(rand::thread_rng(), opts.count_steps) { if generate.display_score { let _ = output_handle.write_all(&score.to_string().as_bytes()); let _ = output_handle.write_all(b";"); } let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); if n != 0 { counter += 1; if counter >= n { return; } } } } } while let Ok(result) = input.read_line(&mut buffer) { if result == 0 { break; } let sudoku = buffer.parse::<msolve::Sudoku>().unwrap(); match opts.mode { Mode::Solve(solve) => { if opts.verify_uniqueness { if let Some(solution) = sudoku.solve_unique() { let _ = output_handle.write_all(&solution.to_bytes()); let _ = output_handle.write_all(b"\n"); } } else { for solution in sudoku.iter().take(solve.count) { let _ = output_handle.write_all(&solution.to_bytes()); let _ = output_handle.write_all(b"\n"); } } } Mode::Select(select) => { let mut does_match = if opts.verify_uniqueness { sudoku.has_single_solution() } else { sudoku.has_solution() }; if select.invert { does_match = !does_match; } if does_match { let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } } Mode::Difficulty => { if let Some(difficulty) = score_sudoku(&sudoku, &opts) { let _ = output_handle.write_all(&difficulty.to_string().as_bytes()); let _ = output_handle.write_all(b";"); let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } } Mode::CountSolutions(n) => { let count = sudoku.count_solutions(n.n); let _ = output_handle.write_all(&count.to_string().as_bytes()); let _ = output_handle.write_all(b";"); let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } #[cfg(feature = "generate")] Mode::Generate(generate) => { if let GenerateMode::Once(once) = generate.mode { let (sudoku, score) = sudoku.generate_from_seed( &mut rng, once.cells_to_remove, opts.count_steps, ); if generate.display_score { let _ = output_handle.write_all(&score.to_string().as_bytes()); let _ = output_handle.write_all(b";"); } let _ = output_handle.write_all(&sudoku.to_bytes()); let _ = output_handle.write_all(b"\n"); } else { unimplemented!() } } Mode::ListTechniques => { for (explanation, state) in sudoku.list_techniques().iter() { let _ = output_handle.write_all(&explanation.as_bytes()); let _ = output_handle.write_all(b"\n"); let _ = output_handle.write_all(&state.to_pencilmark_bytes()); let _ = output_handle.write_all(b"\n"); std::thread::sleep(std::time::Duration::from_secs(1)); } } Mode::Info => { info[sudoku.count_solutions(2)] += 1; } } buffer.clear(); } if let Mode::Info = opts.mode { println!( "0 Solutions: {}, 1 Solution: {}, 2+ Solutions: {}", info[0], info[1], info[2] ); } }
function_block-function_prefixed
[ { "content": "fn bench_solving(sudoku: Option<&String>, solver: Solver, mode: Mode) -> usize {\n\n let solution_count = match mode {\n\n Mode::SolveOne => 1,\n\n Mode::SolveUnique => 2,\n\n };\n\n match solver {\n\n Solver::MSolve => {\n\n if let Ok(sudoku) = msolve::Sud...
Rust
src/lib.rs
ldm0/wasm_nn
da6149a8e1d4c22a1c1496058401ea44aeadfc4d
mod data; mod nn; use std::mem; use std::slice; use once_cell::sync::Lazy; use std::sync::Mutex; use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data; use nn::Network; #[derive(Default)] struct MetaData { fc_size: u32, num_classes: u32, descent_rate: f32, regular_rate: f32, } #[derive(Default)] struct CriticalSection(MetaData, Data, Network); extern "C" { fn log_u64(num: u32); fn draw_point(x: u32, y: u32, label_ratio: f32); } static DATA: Lazy<Mutex<CriticalSection>> = Lazy::new(|| Mutex::default()); #[no_mangle] pub fn alloc(size: u32) -> *mut u8 { let mut buffer: Vec<u8> = Vec::with_capacity(size as usize); let buffer_ptr = buffer.as_mut_ptr(); mem::forget(buffer); buffer_ptr } #[no_mangle] pub fn free(buffer_ptr: *mut u8, size: u32) { let _ = unsafe { Vec::from_raw_parts(buffer_ptr, 0, size as usize) }; } #[no_mangle] pub fn init( data_radius: f32, data_spin_span: f32, data_num: u32, num_classes: u32, data_gen_rand_max: f32, network_gen_rand_max: f32, fc_size: u32, descent_rate: f32, regular_rate: f32, ) { let ref mut tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, data, network) = tmp; metadata.fc_size = fc_size; metadata.num_classes = num_classes; metadata.descent_rate = descent_rate; metadata.regular_rate = regular_rate; data.init( num_classes, data_num / num_classes, data_radius, data_spin_span, data_gen_rand_max, ); const PLANE_DIMENSION: u32 = 2; network.init(PLANE_DIMENSION, fc_size, num_classes, network_gen_rand_max); } #[no_mangle] pub fn train() -> f32 { let ref mut tmp = *DATA.lock().unwrap(); let CriticalSection(ref metadata, ref data, ref mut network) = *tmp; let regular_rate = metadata.regular_rate; let descent_rate = metadata.descent_rate; let (fc_layer, softmax) = network.forward_propagation(&data.points); let (dw1, db1, dw2, db2) = network.back_propagation( &data.points, &fc_layer, &softmax, &data.labels, regular_rate, ); let loss = network.loss(&softmax, &data.labels, regular_rate); network.descent(&dw1, &db1, &dw2, &db2, descent_rate); let (data_loss, regular_loss) = loss; data_loss + regular_loss } #[no_mangle] pub fn draw_prediction(canvas: *mut u8, width: u32, height: u32, span_least: f32) { let width = width as usize; let height = height as usize; let ref tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, _, network) = tmp; let num_classes = metadata.num_classes as usize; let r: Array1<f32> = Array::linspace(0f32, 200f32, num_classes); let g: Array1<f32> = Array::linspace(0f32, 240f32, num_classes); let b: Array1<f32> = Array::linspace(0f32, 255f32, num_classes); let span_per_pixel = span_least / width.min(height) as f32; let span_height = height as f32 * span_per_pixel; let span_width = width as f32 * span_per_pixel; let width_max = span_width / 2f32; let width_min = -span_width / 2f32; let height_max = span_height / 2f32; let height_min = -span_height / 2f32; let x_axis: Array1<f32> = Array::linspace(width_min, width_max, width); let y_axis: Array1<f32> = Array::linspace(height_min, height_max, height); let mut grid: Array3<f32> = Array::zeros((height, width, 2)); for y in 0..height { for x in 0..width { let coord = array![x_axis[[x]], y_axis[[y]]]; let mut slice = grid.slice_mut(s![y, x, ..]); slice.assign(&coord); } } let xys = grid.into_shape((height * width, 2)).unwrap(); let (_, softmax) = network.forward_propagation(&xys); let mut labels: Array1<usize> = Array::zeros(height * width); for (y, row) in softmax.axis_iter(Axis(0)).enumerate() { let mut maxx = 0 as usize; let mut max = row[[0]]; for (x, col) in row.iter().enumerate() { if *col > max { maxx = x; max = *col; } } labels[[y]] = maxx; } let grid_label = labels.into_shape((height, width)).unwrap(); let canvas_size = width * height * 4; let canvas: &mut [u8] = unsafe { slice::from_raw_parts_mut(canvas, canvas_size) }; for y in 0..height { for x in 0..width { canvas[4 * (y * width + x) + 0] = r[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 1] = g[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 2] = b[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 3] = 0xFF as u8; } } } #[no_mangle] pub fn draw_points(width: u32, height: u32, span_least: f32) { let ref tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, data, _) = tmp; let num_classes = metadata.num_classes as f32; let pixel_per_span = width.min(height) as f32 / span_least; let labels = &data.labels; let points = &data.points; let points_x = points.index_axis(Axis(1), 0); let points_y = points.index_axis(Axis(1), 1); Zip::from(labels) .and(points_x) .and(points_y) .apply(|&label, &x, &y| { let x = (x * pixel_per_span) as i64 + width as i64 / 2; let y = (y * pixel_per_span) as i64 + height as i64 / 2; if !(x >= width as i64 || x < 0 || y >= height as i64 || y < 0) { let x = x as u32; let y = y as u32; let label_ratio = label as f32 / num_classes; unsafe { draw_point(x, y, label_ratio); } } }); } #[cfg(test)] mod kernel_test { use super::*; static POINT_DRAW_TIMES: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0)); #[no_mangle] extern "C" fn draw_point(_: u32, _: u32, _: f32) { *POINT_DRAW_TIMES.lock().unwrap() += 1; } use std::f32::consts::PI; const DATA_GEN_RADIUS: f32 = 1f32; const SPIN_SPAN: f32 = PI; const NUM_CLASSES: u32 = 3; const DATA_NUM: u32 = 300; const FC_SIZE: u32 = 100; const REGULAR_RATE: f32 = 0.001f32; const DESCENT_RATE: f32 = 1f32; const DATA_GEN_RAND_MAX: f32 = 0.25f32; const NETWORK_GEN_RAND_MAX: f32 = 0.1f32; #[test] fn test_all() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let loss_before: f32 = train(); for _ in 0..50 { let loss = train(); assert!(loss < loss_before * 1.1f32); } } #[test] fn test_buffer_allocation() { let buffer = alloc(114514); free(buffer, 114514); } #[test] fn test_draw_prediction() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let width = 100; let height = 100; let buffer = alloc(width * height * 4); draw_prediction(buffer, width, height, 2f32); free(buffer, width * height * 4); } #[test] fn test_draw_points() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 1, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(100, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(10000000, 1000000, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); } }
mod data; mod nn; use std::mem; use std::slice; use once_cell::sync::Lazy; use std::sync::Mutex; use ndarray::prelude::*; use ndarray::{array, Array, Array1, Array3, Axis, Zip}; use data::Data; use nn::Network; #[derive(Default)] struct MetaData { fc_size: u32, num_classes: u32, descent_rate: f32, regular_rate: f32, } #[derive(Default)] struct CriticalSection(MetaData, Data, Network); extern "C" { fn log_u64(num: u32); fn draw_point(x: u32, y: u32, label_ratio: f32); } static DATA: Lazy<Mutex<CriticalSection>> = Lazy::new(|| Mutex::default()); #[no_mangle] pub fn alloc(size: u32) -> *mut u8 { let mut buffer: Vec<u8> = Vec::with_capacity(size as usize); let buffer_ptr = buffer.as_mut_ptr(); mem::forget(buffer); buffer_ptr } #[no_mangle] pub fn free(buffer_ptr: *mut u8, size: u32) { let _ = unsafe { Vec::from_raw_parts(buffer_ptr, 0, size as usize) }; } #[no_mangle] pub fn init( data_radius: f32, data_spin_span: f32, data_num: u32, num_classes: u32, data_gen_rand_max: f32, network_gen_rand_max: f32, fc_size: u32, descent_rate: f32, regular_rate: f32, ) { let ref mut tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, data, network) = tmp; metadata.fc_size = fc_size; metadata.num_classes = num_classes; metadata.descent_rate = descent_rate; metadata.regular_rate = regular_rate; data.init( num_classes, data_num / num_classes, data_radius, data_spin_span, data_gen_rand_max, ); const PLANE_DIMENSION: u32 = 2; network.init(PLANE_DIMENSION, fc_size, num_classes, network_gen_rand_max); } #[no_mangle] pub fn train() -> f32 { let ref mut tmp = *DATA.lock().unwrap(); let CriticalSection(ref metadata, ref data, ref mut network) = *tmp; let regular_rate = metadata.regular_rate; let descent_rate = metadata.descent_rate; let (fc_layer, softmax) = network.forward_propagation(&data.points); let (dw1, db1, dw2, db2) = network.back_propagation( &data.points, &fc_layer, &softmax, &data.labels, regular_rate, ); let loss = network.loss(&softmax, &data.labels, regular_rate); network.descent(&dw1, &db1, &dw2, &db2, descent_rate); let (data_loss, regular_loss) = loss; data_loss + regular_loss } #[no_mangle] pub fn draw_prediction(canvas: *mut u8, width: u32, height: u32, span_least: f32) { let width = width as usize; let height = height as usize; let ref tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, _, network) = tmp; let num_classes = metadata.num_classes as usize; let r: Array1<f32> = Array::linspace(0f32, 200f32, num_classes); let g: Array1<f32> = Array::linspace(0f32, 240f32, num_classes); let b: Array1<f32> = Array::linspace(0f32, 255f32, num_classes); let span_per_pixel = span_least / width.min(height) as f32; let span_height = height as f32 * span_per_pixel; let span_width = width as f32 * span_per_pixel; let width_max = span_width / 2f32; let width_min = -span_width / 2f32; let height_max = span_height / 2f32; let height_min = -span_height / 2f32; let x_axis: Array1<f32> = Array::linspace(width_min, width_max, width); let y_axis: Array1<f32> = Array::linspace(height_min, height_max, height); let mut grid: Array3<f32> = Array::zeros((height, width, 2)); for y in 0..height { for x in 0..width { let coord = array![x_axis[[x]], y_axis[[y]]]; let mut slice = grid.slice_mut(s![y, x, ..]); slice.assign(&coord); } } let xys = grid.into_shape((height * width, 2)).unwrap(); let (_, softmax) = network.forward_propagation(&xys); let mut labels: Array1<usize> = Array::zeros(height * width); for (y, row) in softmax.axis_iter(Axis(0)).enumerate() { let mut maxx = 0 as usize; let mut max = row[[0]]; for (x, col) in row.iter().enumerate() { if *col > max { maxx = x; max = *col; } } labels[[y]] = maxx; } let grid_label = labels.into_shape((height, width)).unwrap(); let canvas_size = width * height * 4; let canvas: &mut [u8] = unsafe { slice::from_raw_parts_mut(canvas, canvas_size) }; for y in 0..height { for x in 0..width { canvas[4 * (y * width + x) + 0] = r[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 1] = g[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 2] = b[[grid_label[[y, x]]]] as u8; canvas[4 * (y * width + x) + 3] = 0xFF as u8; } } } #[no_mangle] pub fn draw_points(width: u32, height: u32, span_least: f32) { let ref tmp = *DATA.lock().unwrap(); let CriticalSection(metadata, data, _) = tmp; let num_classes = metadata.num_classes as f32; let pixel_per_span = width.min(height) as f32 / span_least; let labels = &data.labels; let points = &data.points; let points_x = points.index_axis(Axis(1), 0); let points_y = points.index_axis(Axis(1), 1); Zip::from(labels) .and(points_x) .and(points_y) .apply(|&label, &x, &y| { let x = (x * pixel_per_span) as i64 + width as i64 / 2; let y = (y * pixel_per_span) as i64 + height as i64 / 2; if !(x >= width as i64 || x < 0 || y >= height as i64 || y < 0) { let x = x as u32; let y = y as u32; let label_ratio = label as f32 / num_classes; unsafe { draw_point(x, y, label_ratio); } } }); } #[cfg(test)] mod kernel_test { use super::*; static POINT_DRAW_TIMES: Lazy<Mutex<u32>> = Lazy::new(|| Mutex::new(0)); #[no_mangle] extern "C" fn draw_point(_: u32, _: u32, _: f32) { *POINT_DRAW_TIMES.lock().unwrap() += 1; } use std::f32::consts::PI; const DATA_GEN_RADIUS: f32 = 1f32; const SPIN_SPAN: f32 = PI; const NUM_CLASSES: u32 = 3; const DATA_NUM: u32 = 300; const FC_SIZE: u32 = 100; const REGULAR_RATE: f32 = 0.001f32; const DESCENT_RATE: f32 = 1f32; const DATA_GEN_RAND_MAX: f32 = 0.25f32; const NETWORK_GEN_RAND_MAX: f32 = 0.1f32; #[test] fn test_all() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let loss_before: f32 = train(); for _ in 0..50 { let loss = train(); assert!(loss < loss_before * 1.1f32); }
ck().unwrap() = 0; draw_points(1, 1, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(1, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(100, 100, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); *POINT_DRAW_TIMES.lock().unwrap() = 0; draw_points(10000000, 1000000, DATA_GEN_RADIUS * 2f32 * 1.1f32); assert_eq!(DATA_NUM, *POINT_DRAW_TIMES.lock().unwrap()); } }
} #[test] fn test_buffer_allocation() { let buffer = alloc(114514); free(buffer, 114514); } #[test] fn test_draw_prediction() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); let width = 100; let height = 100; let buffer = alloc(width * height * 4); draw_prediction(buffer, width, height, 2f32); free(buffer, width * height * 4); } #[test] fn test_draw_points() { init( DATA_GEN_RADIUS, SPIN_SPAN, DATA_NUM, NUM_CLASSES, DATA_GEN_RAND_MAX, NETWORK_GEN_RAND_MAX, FC_SIZE, DESCENT_RATE, REGULAR_RATE, ); *POINT_DRAW_TIMES.lo
random
[ { "content": "use ndarray::prelude::*;\n\nuse ndarray::{stack, Array, Array1, Array2, Axis}; // for matrices\n\n\n\nuse ndarray_rand::rand_distr::StandardNormal; // for randomness\n\nuse ndarray_rand::RandomExt; // for randomness\n\nuse rand::rngs::SmallRng;\n\nuse rand::SeedableRng; // for from_seed // for ran...
Rust
rend3/src/renderer/shaders.rs
Noxime/rend3
8270d40cb7522a1212b1b99ab768cc525786f04f
use crate::{ datatypes::ShaderHandle, list::{ShaderSourceType, SourceShaderDescriptor}, registry::ResourceRegistry, ShaderError, }; use parking_lot::RwLock; use shaderc::{CompileOptions, Compiler, OptimizationLevel, ResolvedInclude, SourceLanguage, TargetEnv}; use std::{borrow::Cow, future::Future, path::Path, sync::Arc, thread, thread::JoinHandle}; use wgpu::{Device, ShaderFlags, ShaderModule, ShaderModuleDescriptor, ShaderSource}; pub type ShaderCompileResult = Result<Arc<ShaderModule>, ShaderError>; const BUILTIN_SHADERS: include_dir::Dir = include_dir::include_dir!("./shaders"); pub struct ShaderManager { shader_thread: Option<JoinHandle<()>>, sender: flume::Sender<CompileCommand>, registry: RwLock<ResourceRegistry<Arc<ShaderModule>>>, } impl ShaderManager { pub fn new(device: Arc<Device>) -> Arc<Self> { let (sender, receiver) = flume::unbounded(); let shader_thread = Some( thread::Builder::new() .name("rend3 shader-compilation".into()) .spawn(move || compile_shader_loop(device, receiver)) .unwrap(), ); let registry = RwLock::new(ResourceRegistry::new()); Arc::new(Self { shader_thread, sender, registry, }) } pub fn allocate(&self) -> ShaderHandle { ShaderHandle(self.registry.read().allocate()) } pub fn allocate_async_insert(self: &Arc<Self>, args: SourceShaderDescriptor) -> impl Future<Output = ShaderHandle> { let handle = ShaderHandle(self.registry.read().allocate()); let fut = self.compile_shader(args); let this = Arc::clone(self); async move { let res = fut.await.unwrap(); this.registry.write().insert(handle.0, res); handle } } pub fn insert(&self, handle: ShaderHandle, shader: Arc<ShaderModule>) { self.registry.write().insert(handle.0, shader); } pub fn remove(&self, handle: ShaderHandle) { self.registry.write().remove(handle.0); } pub fn get(&self, handle: ShaderHandle) -> Arc<ShaderModule> { self.registry.read().get(handle.0).clone() } pub fn compile_shader(&self, args: SourceShaderDescriptor) -> impl Future<Output = ShaderCompileResult> { let (sender, receiver) = flume::bounded(1); self.sender.send(CompileCommand::Compile(args, sender)).unwrap(); async move { receiver.recv_async().await.unwrap() } } } impl Drop for ShaderManager { fn drop(&mut self) { self.sender.send(CompileCommand::Stop).unwrap(); self.shader_thread.take().unwrap().join().unwrap(); } } #[derive(Debug, Clone)] enum CompileCommand { Compile(SourceShaderDescriptor, flume::Sender<ShaderCompileResult>), Stop, } fn compile_shader_loop(device: Arc<Device>, receiver: flume::Receiver<CompileCommand>) { let mut compiler = shaderc::Compiler::new().unwrap(); while let Ok(command) = receiver.recv() { match command { CompileCommand::Compile(args, sender) => { let result = compile_shader(&mut compiler, &device, &args); sender.send(result).unwrap(); } CompileCommand::Stop => return, } } } fn compile_shader(compiler: &mut Compiler, device: &Device, args: &SourceShaderDescriptor) -> ShaderCompileResult { span_transfer!(_ -> file_span, WARN, "Loading File"); tracing::debug!("Compiling shader {:?}", args); let contents = match args.source { ShaderSourceType::File(ref file) => { std::fs::read_to_string(file).map_err(|e| ShaderError::FileError(e, args.clone()))? } ShaderSourceType::Builtin(ref file) => BUILTIN_SHADERS .get_file(file) .ok_or_else(|| ShaderError::Builtin(args.clone()))? .contents_utf8() .unwrap() .to_string(), ShaderSourceType::Value(ref code) => code.clone(), }; let file_name = match args.source { ShaderSourceType::File(ref file) | ShaderSourceType::Builtin(ref file) => &**file, ShaderSourceType::Value(_) => "./file", }; let builtin = matches!(args.source, ShaderSourceType::Builtin(_)); span_transfer!(file_span -> compile_span, WARN, "Shader Compilation"); let mut options = CompileOptions::new().unwrap(); options.set_generate_debug_info(); options.set_source_language(SourceLanguage::GLSL); options.set_target_env(TargetEnv::Vulkan, 0); options.set_optimization_level(match cfg!(debug_assertions) { true => OptimizationLevel::Zero, false => OptimizationLevel::Performance, }); for (key, value) in &args.defines { options.add_macro_definition(&key, value.as_deref()); } options.set_include_callback(|include, _ty, src, _depth| { let joined = Path::new(src) .parent() .ok_or_else(|| { format!( "Cannot find include <{}> relative to file {} as there is no parent directory", include, src ) })? .join(Path::new(include)); let contents = if builtin { let dedot = path_dedot::ParseDot::parse_dot(&joined).unwrap(); BUILTIN_SHADERS .get_file(dedot) .ok_or_else(|| { format!( "Error while locating builtin include <{}> from file {} for path {}", include, src, joined.display() ) })? .contents_utf8() .unwrap() .to_string() } else { std::fs::read_to_string(&joined).map_err(|e| { format!( "Error while loading include <{}> from file {} for path {}: {}", include, src, joined.display(), e ) })? }; Ok(ResolvedInclude { resolved_name: joined.to_string_lossy().to_string(), content: contents, }) }); let binary = compiler .compile_into_spirv(&contents, args.stage.into(), &file_name, "main", Some(&options)) .map_err(|e| ShaderError::CompileError(e, args.clone()))?; let bytes = binary.as_binary(); span_transfer!(compile_span -> module_create_span, WARN, "Create Shader Module"); let module = Arc::new(device.create_shader_module(&ShaderModuleDescriptor { label: None, source: ShaderSource::SpirV(Cow::Borrowed(bytes)), flags: ShaderFlags::VALIDATION, })); Ok(module) }
use crate::{ datatypes::ShaderHandle, list::{ShaderSourceType, SourceShaderDescriptor}, registry::ResourceRegistry, ShaderError, }; use parking_lot::RwLock; use shaderc::{CompileOptions, Compiler, OptimizationLevel, ResolvedInclude, SourceLanguage, TargetEnv}; use std::{borrow::Cow, future::Future, path::Path, sync::Arc, thread, thread::JoinHandle}; use wgpu::{Device, ShaderFlags, ShaderModule, ShaderModuleDescriptor, ShaderSource}; pub type ShaderCompileResult = Result<Arc<ShaderModule>, ShaderError>; const BUILTIN_SHADERS: include_dir::Dir = include_dir::include_dir!("./shaders"); pub struct ShaderManager { shader_thread: Option<JoinHandle<()>>, sender: flume::Sender<CompileCommand>, registry: RwLock<ResourceRegistry<Arc<ShaderModule>>>, } impl ShaderManager { pub fn new(device: Arc<Device>) -> Arc<Self> { let (sender, receiver) = flume::unbounded(); let shader_thread = Some( thread::Builder::new() .name("rend3 shader-compilation".into()) .spawn(move || compile_shader_loop(device, receiver)) .unwrap(), ); let registry = RwLock::new(ResourceRegistry::new()); Arc::new(Self { shader_thread, sender, registry, }) } pub fn allocate(&self) -> ShaderHandle { ShaderHandle(self.registry.read().allocate()) } pub fn allocate_async_insert(self: &Arc<Self>, args: SourceShaderDescriptor) -> impl Future<Output = ShaderHandle> { let handle = ShaderHandle(self.registry.read().allocate()); let fut = self.compile_shader(args); let this = Arc::clone(self); async move { let res = fut.await.unwrap(); this.registry.write().insert(handle.0, res); handle } } pub fn insert(&self, handle: ShaderHandle, shader: Arc<ShaderModule>) { self.registry.write().insert(handle.0, shader); } pub fn remove(&self, handle: ShaderHandle) { self.registry.write().remove(handle.0); } pub fn get(&self, handle: ShaderHandle) -> Arc<ShaderModule> { self.registry.read().get(handle.0).clone() } pub fn compile_shader(&self, args: SourceShaderDescriptor) -> impl Future<Output = ShaderCompileResult> { let (sender, receiver) = flume::bounded(1); self.sender.send(CompileCommand::Compile(args, sender)).unwrap(); async move { receiver.recv_async().await.unwrap() } } } impl Drop for ShaderManager { fn drop(&mut self) { self.sender.send(CompileCommand::Stop).unwrap(); self.shader_thread.take().unwrap().join().unwrap(); } } #[derive(Debug, Clone)] enum CompileCommand { Compile(SourceShaderDescriptor, flume::Sender<ShaderCompileResult>), Stop, } fn compile_shader_loop(device: Arc<Device>, receiver: flume::Receiver<CompileCommand>) { let mut compiler = shaderc::Compiler::new().unwrap(); while let Ok(command) = receiver.recv() { match command { CompileCommand::Compile(args, sender) => { let result = compile_shader(&mut com
ltin(args.clone()))? .contents_utf8() .unwrap() .to_string(), ShaderSourceType::Value(ref code) => code.clone(), }; let file_name = match args.source { ShaderSourceType::File(ref file) | ShaderSourceType::Builtin(ref file) => &**file, ShaderSourceType::Value(_) => "./file", }; let builtin = matches!(args.source, ShaderSourceType::Builtin(_)); span_transfer!(file_span -> compile_span, WARN, "Shader Compilation"); let mut options = CompileOptions::new().unwrap(); options.set_generate_debug_info(); options.set_source_language(SourceLanguage::GLSL); options.set_target_env(TargetEnv::Vulkan, 0); options.set_optimization_level(match cfg!(debug_assertions) { true => OptimizationLevel::Zero, false => OptimizationLevel::Performance, }); for (key, value) in &args.defines { options.add_macro_definition(&key, value.as_deref()); } options.set_include_callback(|include, _ty, src, _depth| { let joined = Path::new(src) .parent() .ok_or_else(|| { format!( "Cannot find include <{}> relative to file {} as there is no parent directory", include, src ) })? .join(Path::new(include)); let contents = if builtin { let dedot = path_dedot::ParseDot::parse_dot(&joined).unwrap(); BUILTIN_SHADERS .get_file(dedot) .ok_or_else(|| { format!( "Error while locating builtin include <{}> from file {} for path {}", include, src, joined.display() ) })? .contents_utf8() .unwrap() .to_string() } else { std::fs::read_to_string(&joined).map_err(|e| { format!( "Error while loading include <{}> from file {} for path {}: {}", include, src, joined.display(), e ) })? }; Ok(ResolvedInclude { resolved_name: joined.to_string_lossy().to_string(), content: contents, }) }); let binary = compiler .compile_into_spirv(&contents, args.stage.into(), &file_name, "main", Some(&options)) .map_err(|e| ShaderError::CompileError(e, args.clone()))?; let bytes = binary.as_binary(); span_transfer!(compile_span -> module_create_span, WARN, "Create Shader Module"); let module = Arc::new(device.create_shader_module(&ShaderModuleDescriptor { label: None, source: ShaderSource::SpirV(Cow::Borrowed(bytes)), flags: ShaderFlags::VALIDATION, })); Ok(module) }
piler, &device, &args); sender.send(result).unwrap(); } CompileCommand::Stop => return, } } } fn compile_shader(compiler: &mut Compiler, device: &Device, args: &SourceShaderDescriptor) -> ShaderCompileResult { span_transfer!(_ -> file_span, WARN, "Loading File"); tracing::debug!("Compiling shader {:?}", args); let contents = match args.source { ShaderSourceType::File(ref file) => { std::fs::read_to_string(file).map_err(|e| ShaderError::FileError(e, args.clone()))? } ShaderSourceType::Builtin(ref file) => BUILTIN_SHADERS .get_file(file) .ok_or_else(|| ShaderError::Bui
random
[]
Rust
src/imp/scintilla/mod_cocoa.rs
plyhun/plygui-scintilla
6543238d109c7cf44a8883d65f5bb4d12df0bd90
use crate::sdk::*; use plygui_cocoa::common::*; use std::os::raw::{c_int, c_long, c_ulong, c_void}; lazy_static! { static ref WINDOW_CLASS: RefClass = unsafe { register_window_class("PlyguiConsole", BASE_CLASS, |decl| { decl.add_method(sel!(setFrameSize:), set_frame_size as extern "C" fn(&mut Object, Sel, NSSize)); }) }; } pub type Scintilla = AMember<AControl<AScintilla<CocoaScintilla>>>; const BASE_CLASS: &str = "ScintillaView"; #[repr(C)] pub struct CocoaScintilla { base: CocoaControlBase<Scintilla>, fn_ptr: Option<extern "C" fn(*mut c_void, c_int, c_ulong, c_long) -> *mut c_void>, self_ptr: Option<*mut c_void>, } impl<O: crate::Scintilla> NewScintillaInner<O> for CocoaScintilla { fn with_uninit(u: &mut mem::MaybeUninit<O>) -> Self { let sc = Self { base: CocoaControlBase::with_params(*WINDOW_CLASS, set_frame_size_inner::<O>), fn_ptr: None, self_ptr: None, }; unsafe { let selfptr = u as *mut _ as *mut ::std::os::raw::c_void; (&mut *sc.base.control).set_ivar(IVAR, selfptr); } sc } } impl ScintillaInner for CocoaScintilla { fn new() -> Box<dyn crate::Scintilla> { let mut b: Box<mem::MaybeUninit<Scintilla>> = Box::new_uninit(); let ab = AMember::with_inner( AControl::with_inner( AScintilla::with_inner( <Self as NewScintillaInner<Scintilla>>::with_uninit(b.as_mut()), ) ), ); unsafe { b.as_mut_ptr().write(ab); b.assume_init() } } fn set_margin_width(&mut self, index: usize, width: isize) { if let Some(fn_ptr) = self.fn_ptr { (fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETMARGINWIDTHN as i32, index as c_ulong, width as c_long); } } fn set_readonly(&mut self, readonly: bool) { if let Some(fn_ptr) = self.fn_ptr { (fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETREADONLY as i32, if readonly { 1 } else { 0 }, 0); } } fn is_readonly(&self) -> bool { if let Some(fn_ptr) = self.fn_ptr { !(fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_GETREADONLY as i32, 0, 0).is_null() } else { true } } fn set_codepage(&mut self, cp: crate::Codepage) { if let Some(fn_ptr) = self.fn_ptr { ((fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETCODEPAGE as i32, cp as c_ulong, 0) as isize); } } fn codepage(&self) -> crate::Codepage { if let Some(fn_ptr) = self.fn_ptr { ((fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_GETCODEPAGE as i32, 0, 0) as isize).into() } else { Default::default() } } fn append_text(&mut self, text: &str) { self.set_codepage(crate::Codepage::Utf8); if let Some(fn_ptr) = self.fn_ptr { let len = text.len(); let tptr = text.as_bytes().as_ptr(); (fn_ptr)(self.self_ptr.unwrap(), crate::scintilla_sys::SCI_APPENDTEXT as i32, len as c_ulong, tptr as c_long); } } } impl ControlInner for CocoaScintilla { fn on_added_to_container(&mut self, member: &mut MemberBase, control: &mut ControlBase, _parent: &dyn controls::Container, _x: i32, _y: i32, pw: u16, ph: u16) { unsafe { use scintilla_sys::{SCI_GETDIRECTFUNCTION, SCI_GETDIRECTPOINTER}; let fn_ptr: extern "C" fn(*mut c_void, c_int, c_ulong, c_long) -> *mut c_void = msg_send![self.base.control, message:SCI_GETDIRECTFUNCTION wParam:0 lParam:0]; let self_ptr: *mut c_void = msg_send![self.base.control, message:SCI_GETDIRECTPOINTER wParam:0 lParam:0]; self.fn_ptr = Some(fn_ptr); self.self_ptr = Some(self_ptr); } self.measure(member, control, pw, ph); } fn on_removed_from_container(&mut self, _: &mut MemberBase, _: &mut ControlBase, _: &dyn controls::Container) { self.fn_ptr = None; self.self_ptr = None; unsafe { self.base.on_removed_from_container(); } } fn parent(&self) -> Option<&dyn controls::Member> { self.base.parent() } fn parent_mut(&mut self) -> Option<&mut dyn controls::Member> { self.base.parent_mut() } fn root(&self) -> Option<&dyn controls::Member> { self.base.root() } fn root_mut(&mut self) -> Option<&mut dyn controls::Member> { self.base.root_mut() } #[cfg(feature = "markup")] fn fill_from_markup(&mut self, member: &mut MemberBase, control: &mut ControlBase, markup: &plygui_api::markup::Markup, registry: &mut plygui_api::markup::MarkupRegistry) { fill_from_markup_base!(self, base, markup, registry, Scintilla, ["Scintilla"]); } } impl HasLayoutInner for CocoaScintilla { fn on_layout_changed(&mut self, _: &mut MemberBase) { self.base.invalidate(); } } impl Drawable for CocoaScintilla { fn draw(&mut self, _member: &mut MemberBase, control: &mut ControlBase) { self.base.draw(control.coords, control.measured); } fn measure(&mut self, _: &mut MemberBase, control: &mut ControlBase, parent_width: u16, parent_height: u16) -> (u16, u16, bool) { let old_size = control.measured; control.measured = match control.visibility { types::Visibility::Gone => (0, 0), _ => { let w = match control.layout.width { layout::Size::MatchParent => parent_width, layout::Size::Exact(w) => w, layout::Size::WrapContent => { 42 as u16 } }; let h = match control.layout.height { layout::Size::MatchParent => parent_height, layout::Size::Exact(h) => h, layout::Size::WrapContent => { 42 as u16 } }; (w, h) } }; (control.measured.0, control.measured.1, control.measured != old_size) } fn invalidate(&mut self, _: &mut MemberBase, _: &mut ControlBase) { self.base.invalidate(); } } impl HasNativeIdInner for CocoaScintilla { type Id = CocoaId; fn native_id(&self) -> Self::Id { self.base.control.into() } } impl HasSizeInner for CocoaScintilla { fn on_size_set(&mut self, _: &mut MemberBase, _: (u16, u16)) -> bool { self.base.invalidate(); true } } impl Spawnable for CocoaScintilla { fn spawn() -> Box<dyn controls::Control> { Self::new().into_control() } } impl HasVisibilityInner for CocoaScintilla { fn on_visibility_set(&mut self, _base: &mut MemberBase, value: types::Visibility) -> bool { self.base.on_set_visibility(value) } } impl MemberInner for CocoaScintilla {} extern "C" fn set_frame_size(this: &mut Object, sel: Sel, param: NSSize) { unsafe { let b = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); let b2 = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); (b.inner().inner().inner().base.resize_handler)(b2, sel, param) } } extern "C" fn set_frame_size_inner<O: crate::Scintilla>(this: &mut Scintilla, _: Sel, param: NSSize) { unsafe { let () = msg_send![super(this.inner_mut().inner_mut().inner_mut().base.control, Class::get(BASE_CLASS).unwrap()), setFrameSize: param]; this.call_on_size::<O>(param.width as u16, param.height as u16) } }
use crate::sdk::*; use plygui_cocoa::common::*; use std::os::raw::{c_int, c_long, c_ulong, c_void}; lazy_static! { static ref WINDOW_CLASS: RefClass = unsafe { register_window_class("PlyguiConsole", BASE_CLASS, |decl| { decl.add_method(sel!(setFrameSize:), set_frame_size as extern "C" fn(&mut Object, Sel, NSSize)); }) }; } pub type Scintilla = AMember<AControl<AScintilla<CocoaScintilla>>>; const BASE_CLASS: &str = "ScintillaView"; #[repr(C)] pub struct CocoaScintilla { base: CocoaControlBase<Scintilla>, fn_ptr: Option<extern "C" fn(*mut c_void, c_int, c_ulong, c_long) -> *mut c_void>, self_ptr: Option<*mut c_void>, } impl<O: crate::Scintilla> NewScintillaInner<O> for CocoaScintilla { fn with_uninit(u: &mut mem::MaybeUninit<O>) -> Self { let sc = Self { base: CocoaControlBase::with_params(*WINDOW_CLASS, set_frame_size_inner::<O>), fn_ptr: None, self_ptr: None, }; unsafe { let selfptr = u as *mut _ as *mut ::std::os::raw::c_void; (&mut *sc.base.control).set_ivar(IVAR, selfptr); } sc } } impl ScintillaInner for CocoaScintilla { fn new() -> Box<dyn crate::Scintilla> { let mut b: Box<mem::MaybeUninit<Scintilla>> = Box::new_uninit(); let ab = AMember::with_inner( AControl::with_inner( AScintilla::with_inner( <Self as NewScintillaInner<Scintilla>>::with_uninit(b.as_mut()), ) ), ); unsafe { b.as_mut_ptr().write(ab); b.assume_init() } } fn set_margin_width(&mut self, index: usize, width: isize) { if let Some(fn_ptr) = self.fn_ptr { (fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETMARGINWIDTHN as i32, index as c_ulong, width as c_long); } } fn set_readonly(&mut self, readonly: bool) { if let Some(fn_ptr) = self.fn_ptr { (fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETREADONLY as i32, if readonly { 1 } else { 0 }, 0); } } fn is_readonly(&self) -> bool { if let Some(fn_ptr) = self.fn_ptr { !(fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_GETREADONLY as i32, 0, 0).is_null() } else { true } } fn set_codepage(&mut self, cp: crate::Codepage) { if let Some(fn_ptr) = self.fn_ptr { ((fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_SETCODEPAGE as i32, cp as c_ulong, 0) as isize); } } fn codepage(&self) -> crate::Codepage { if let Some(fn_ptr) = self.fn_ptr { ((
e.on_set_visibility(value) } } impl MemberInner for CocoaScintilla {} extern "C" fn set_frame_size(this: &mut Object, sel: Sel, param: NSSize) { unsafe { let b = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); let b2 = member_from_cocoa_id_mut::<Scintilla>(this).unwrap(); (b.inner().inner().inner().base.resize_handler)(b2, sel, param) } } extern "C" fn set_frame_size_inner<O: crate::Scintilla>(this: &mut Scintilla, _: Sel, param: NSSize) { unsafe { let () = msg_send![super(this.inner_mut().inner_mut().inner_mut().base.control, Class::get(BASE_CLASS).unwrap()), setFrameSize: param]; this.call_on_size::<O>(param.width as u16, param.height as u16) } }
fn_ptr)(self.self_ptr.unwrap(), scintilla_sys::SCI_GETCODEPAGE as i32, 0, 0) as isize).into() } else { Default::default() } } fn append_text(&mut self, text: &str) { self.set_codepage(crate::Codepage::Utf8); if let Some(fn_ptr) = self.fn_ptr { let len = text.len(); let tptr = text.as_bytes().as_ptr(); (fn_ptr)(self.self_ptr.unwrap(), crate::scintilla_sys::SCI_APPENDTEXT as i32, len as c_ulong, tptr as c_long); } } } impl ControlInner for CocoaScintilla { fn on_added_to_container(&mut self, member: &mut MemberBase, control: &mut ControlBase, _parent: &dyn controls::Container, _x: i32, _y: i32, pw: u16, ph: u16) { unsafe { use scintilla_sys::{SCI_GETDIRECTFUNCTION, SCI_GETDIRECTPOINTER}; let fn_ptr: extern "C" fn(*mut c_void, c_int, c_ulong, c_long) -> *mut c_void = msg_send![self.base.control, message:SCI_GETDIRECTFUNCTION wParam:0 lParam:0]; let self_ptr: *mut c_void = msg_send![self.base.control, message:SCI_GETDIRECTPOINTER wParam:0 lParam:0]; self.fn_ptr = Some(fn_ptr); self.self_ptr = Some(self_ptr); } self.measure(member, control, pw, ph); } fn on_removed_from_container(&mut self, _: &mut MemberBase, _: &mut ControlBase, _: &dyn controls::Container) { self.fn_ptr = None; self.self_ptr = None; unsafe { self.base.on_removed_from_container(); } } fn parent(&self) -> Option<&dyn controls::Member> { self.base.parent() } fn parent_mut(&mut self) -> Option<&mut dyn controls::Member> { self.base.parent_mut() } fn root(&self) -> Option<&dyn controls::Member> { self.base.root() } fn root_mut(&mut self) -> Option<&mut dyn controls::Member> { self.base.root_mut() } #[cfg(feature = "markup")] fn fill_from_markup(&mut self, member: &mut MemberBase, control: &mut ControlBase, markup: &plygui_api::markup::Markup, registry: &mut plygui_api::markup::MarkupRegistry) { fill_from_markup_base!(self, base, markup, registry, Scintilla, ["Scintilla"]); } } impl HasLayoutInner for CocoaScintilla { fn on_layout_changed(&mut self, _: &mut MemberBase) { self.base.invalidate(); } } impl Drawable for CocoaScintilla { fn draw(&mut self, _member: &mut MemberBase, control: &mut ControlBase) { self.base.draw(control.coords, control.measured); } fn measure(&mut self, _: &mut MemberBase, control: &mut ControlBase, parent_width: u16, parent_height: u16) -> (u16, u16, bool) { let old_size = control.measured; control.measured = match control.visibility { types::Visibility::Gone => (0, 0), _ => { let w = match control.layout.width { layout::Size::MatchParent => parent_width, layout::Size::Exact(w) => w, layout::Size::WrapContent => { 42 as u16 } }; let h = match control.layout.height { layout::Size::MatchParent => parent_height, layout::Size::Exact(h) => h, layout::Size::WrapContent => { 42 as u16 } }; (w, h) } }; (control.measured.0, control.measured.1, control.measured != old_size) } fn invalidate(&mut self, _: &mut MemberBase, _: &mut ControlBase) { self.base.invalidate(); } } impl HasNativeIdInner for CocoaScintilla { type Id = CocoaId; fn native_id(&self) -> Self::Id { self.base.control.into() } } impl HasSizeInner for CocoaScintilla { fn on_size_set(&mut self, _: &mut MemberBase, _: (u16, u16)) -> bool { self.base.invalidate(); true } } impl Spawnable for CocoaScintilla { fn spawn() -> Box<dyn controls::Control> { Self::new().into_control() } } impl HasVisibilityInner for CocoaScintilla { fn on_visibility_set(&mut self, _base: &mut MemberBase, value: types::Visibility) -> bool { self.bas
random
[ { "content": "fn event_handler<O: crate::Scintilla>(object: &mut QObject, event: &mut QEvent) -> bool {\n\n match unsafe { event.type_() } {\n\n QEventType::Resize => {\n\n if let Some(this) = cast_qobject_to_uimember_mut::<Scintilla>(object) {\n\n let size = unsafe { \n\n ...
Rust
core/http/src/unix.rs
pzmarzly/Rocket
a4677871796c7170cfbbf83d205a8758338762df
use std::io::{self, Read, Write}; use std::path::Path; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::time::Duration; #[cfg(unix)] use std::os::unix::net::{UnixListener, UnixStream}; #[cfg(windows)] use uds_windows::{UnixListener, UnixStream}; use crate::hyper; use crate::hyper::net::{NetworkStream, NetworkListener}; use crate::hyper::Server; pub struct UnixSocketStream(pub UnixStream); impl Clone for UnixSocketStream { #[inline] fn clone(&self) -> UnixSocketStream { UnixSocketStream(self.0.try_clone().unwrap()) } } impl NetworkStream for UnixSocketStream { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.0.peer_addr() .map(|_| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0))) } #[inline] fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { self.0.set_read_timeout(dur) } #[inline] fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { self.0.set_write_timeout(dur) } } impl Read for UnixSocketStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl Write for UnixSocketStream { #[inline] fn write(&mut self, msg: &[u8]) -> io::Result<usize> { self.0.write(msg) } #[inline] fn flush(&mut self) -> io::Result<()> { self.0.flush() } } #[derive(Debug)] pub struct UnixSocketListener(pub UnixListener); impl Clone for UnixSocketListener { #[inline] fn clone(&self) -> UnixSocketListener { UnixSocketListener(self.0.try_clone().unwrap()) } } impl UnixSocketListener { pub fn new<P: AsRef<Path>>(addr: P) -> hyper::Result<UnixSocketListener> { Ok(UnixSocketListener(UnixListener::bind(addr)?)) } } impl NetworkListener for UnixSocketListener { type Stream = UnixSocketStream; #[inline] fn accept(&mut self) -> hyper::Result<UnixSocketStream> { Ok(UnixSocketStream(self.0.accept()?.0)) } #[inline] fn local_addr(&mut self) -> io::Result<SocketAddr> { self.0.local_addr().map(|_| { SocketAddr::V4( SocketAddrV4::new( Ipv4Addr::new(0, 0, 0, 0), 0 ) ) }) } } pub struct UnixSocketServer; impl UnixSocketServer { pub fn http<P>(path: P) -> hyper::Result<Server<UnixSocketListener>> where P: AsRef<Path> { UnixSocketListener::new(path).map(Server::new) } } #[cfg(feature = "tls")] mod tls { use super::*; use crate::hyper::{self, net::SslServer}; use crate::tls::{TlsStream, ServerSession, TlsServer, WrappedStream}; use crate::unix::UnixSocketStream; pub type UnixHttpsStream = WrappedStream<ServerSession, UnixSocketStream>; impl UnixSocketServer { pub fn https<P, S>(path: P, ssl: S) -> hyper::Result<Server<HttpsListener<S>>> where P: AsRef<Path>, S: SslServer<UnixSocketStream> + Clone { HttpsListener::new(path, ssl).map(Server::new) } } #[derive(Clone)] pub struct HttpsListener<S: SslServer<UnixSocketStream>> { listener: UnixSocketListener, ssl: S, } impl<S: SslServer<UnixSocketStream>> HttpsListener<S> { pub fn new<P>(path: P, ssl: S) -> hyper::Result<HttpsListener<S>> where P: AsRef<Path> { UnixSocketListener::new(path) .map(|listener| HttpsListener { listener, ssl }) } } impl<S> NetworkListener for HttpsListener<S> where S: SslServer<UnixSocketStream> + Clone { type Stream = S::Stream; #[inline] fn accept(&mut self) -> hyper::Result<S::Stream> { self.listener.accept().and_then(|s| self.ssl.wrap_server(s)) } #[inline] fn local_addr(&mut self) -> io::Result<SocketAddr> { self.listener.local_addr() } fn set_read_timeout(&mut self, duration: Option<Duration>) { self.listener.set_read_timeout(duration) } fn set_write_timeout(&mut self, duration: Option<Duration>) { self.listener.set_write_timeout(duration) } } impl SslServer<UnixSocketStream> for TlsServer { type Stream = WrappedStream<ServerSession, UnixSocketStream>; fn wrap_server( &self, stream: UnixSocketStream ) -> hyper::Result<WrappedStream<ServerSession, UnixSocketStream>> { let tls = TlsStream::new(rustls::ServerSession::new(&self.cfg), stream); Ok(WrappedStream::new(tls)) } } } #[cfg(feature = "tls")] pub use self::tls::*;
use std::io::{self, Read, Write}; use std::path::Path; use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use std::time::Duration; #[cfg(unix)] use std::os::unix::net::{UnixListener, UnixStream}; #[cfg(windows)] use uds_windows::{UnixListener, UnixStream}; use crate::hyper; use crate::hyper::net::{NetworkStream, NetworkListener}; use crate::hyper::Server; pub struct UnixSocketStream(pub UnixStream); impl Clone for UnixSocketStream { #[inline] fn clone(&self) -> UnixSocketStream { UnixSocketStream(self.0.try_clone().unwrap()) } } impl NetworkStream for UnixSocketStream { #[inline] fn peer_addr(&mut self) -> io::Result<SocketAddr> { self.0.peer_addr() .map(|_| SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(0, 0, 0, 0), 0))) } #[inline] fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { self.0.set_read_timeout(dur) } #[inline] fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { self.0.set_write_timeout(dur) } } impl Read for UnixSocketStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl Write for UnixSocketStream { #[inline] fn write(&mut self, msg: &[u8]) -> io::Result<usize> { self.0.write(msg) } #[inline] fn flush(&mut self) -> io::Result<()> { self.0.flush() } } #[derive(Debug)] pub struct UnixSocketListener(pub UnixListener); impl Clone for UnixSocketListener { #[inline] fn clone(&self) -> UnixSocketListener { UnixSocketListener(self.0.try_clone().unwrap()) } } impl UnixSocketListener { pub fn new<P: AsRef<Path>>(addr: P) -> hyper::Result<UnixSocketListener> { Ok(UnixSocketListener(UnixListener::bind(addr)?)) } } impl NetworkListener for UnixSocketListener { type Stream = UnixSocketStream; #[inline] fn accept(&mut self) -> hyper::Result<UnixSocketStream> { Ok(UnixSocketStream(self.0.accept()?.0)) } #[inline] fn local_addr(&mut self) -> io::Result<SocketAddr> { self.0.local_addr().map(|_| { SocketAddr::V4( SocketAddrV4::new( Ipv4Addr::new(0, 0, 0, 0), 0 ) ) }) } } pub struct UnixSocketServer; impl UnixSocketServer { pub fn http<P>(path: P) -> hyper::Result<Server<UnixSocketListener>> where P: AsRef<Path> { UnixSocketListener::new(path).map(Server::new) } } #[cfg(feature = "tls")] mod tls { use super::*; use crate::hyper::{self, net::SslServer}; use crate::tls::{TlsStream, ServerSession, TlsServer, WrappedStream}; use crate::unix::UnixSocketStream; pub type UnixHttpsStream = WrappedStream<ServerSession, UnixSocketStream>; impl UnixSocketServer { pub fn https<P, S>(path: P, ssl: S) -> hyper::Result<Server<HttpsListener<S>>> where P: AsRef<Path>, S: SslServer<UnixSocketStream> + Clone { HttpsListener::new(path, ssl).map(Server::new) } } #[derive(Clone)] pub struct HttpsListener<S: SslServer<UnixSocketStream>> { listener: UnixSocketListener, ssl: S, } impl<S: SslServer<UnixSocketStream>> HttpsListener<S> {
} impl<S> NetworkListener for HttpsListener<S> where S: SslServer<UnixSocketStream> + Clone { type Stream = S::Stream; #[inline] fn accept(&mut self) -> hyper::Result<S::Stream> { self.listener.accept().and_then(|s| self.ssl.wrap_server(s)) } #[inline] fn local_addr(&mut self) -> io::Result<SocketAddr> { self.listener.local_addr() } fn set_read_timeout(&mut self, duration: Option<Duration>) { self.listener.set_read_timeout(duration) } fn set_write_timeout(&mut self, duration: Option<Duration>) { self.listener.set_write_timeout(duration) } } impl SslServer<UnixSocketStream> for TlsServer { type Stream = WrappedStream<ServerSession, UnixSocketStream>; fn wrap_server( &self, stream: UnixSocketStream ) -> hyper::Result<WrappedStream<ServerSession, UnixSocketStream>> { let tls = TlsStream::new(rustls::ServerSession::new(&self.cfg), stream); Ok(WrappedStream::new(tls)) } } } #[cfg(feature = "tls")] pub use self::tls::*;
pub fn new<P>(path: P, ssl: S) -> hyper::Result<HttpsListener<S>> where P: AsRef<Path> { UnixSocketListener::new(path) .map(|listener| HttpsListener { listener, ssl }) }
function_block-full_function
[ { "content": "pub fn kill_stream(stream: &mut BodyReader) {\n\n // Only do the expensive reading if we're not sure we're done.\n\n use self::HttpReader::*;\n\n match *stream {\n\n SizedReader(_, n) | ChunkedReader(_, Some(n)) if n > 0 => { /* continue */ },\n\n _ => return\n\n };\n\n\n...
Rust
src/platform/bluez/misc/thermometer.rs
OtaK/niter
e66b301b2469b7048e0ce254110a8e4df04cceba
#[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct ThermometerManager { object_path: String, } impl std::str::FromStr for ThermometerManager { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_path: s.into(), }) } } crate::to_proxy_impl!(ThermometerManager, ThermometerManagerProxy, "org.bluez"); crate::impl_tryfrom_zvariant!(ThermometerManager); #[zbus::dbus_proxy( interface = "org.bluez.ThermometerManager1", default_service = "org.bluez" )] pub trait ThermometerManager { fn register_watcher(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn unregister_watcher(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn enable_intermediate_measurement(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn disable_intermediate_measurement(&self, agent: ThermometerWatcher) -> zbus::Result<()>; } #[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct Thermometer { object_path: String, } impl std::str::FromStr for Thermometer { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_path: s.into(), }) } } crate::to_proxy_impl!(Thermometer, ThermometerProxy, "org.bluez"); crate::impl_tryfrom_zvariant!(Thermometer); #[zbus::dbus_proxy(interface = "org.bluez.Thermometer1", default_service = "org.bluez")] pub trait Thermometer { #[dbus_proxy(property)] fn intermediate(&self) -> zbus::fdo::Result<bool>; #[dbus_proxy(property)] fn interval(&self) -> zbus::fdo::Result<u16>; #[dbus_proxy(property)] fn set_interval(&self, interval_seconds: u16) -> zbus::fdo::Result<()>; #[dbus_proxy(property)] fn maximum(&self) -> zbus::fdo::Result<u16>; #[dbus_proxy(property)] fn minimum(&self) -> zbus::fdo::Result<u16>; } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct ThermometerWatcher { object_path: String, current_measurement: Option<ThermometerMeasurement>, } impl zvariant::Type for ThermometerWatcher { fn signature() -> zvariant::Signature<'static> { zvariant::Signature::from_str_unchecked("s") } } #[zbus::dbus_interface(name = "org.bluez.ThermometerWatcher1")] impl ThermometerWatcher { fn measurement_received( &mut self, measurement: ThermometerMeasurement, ) -> zbus::fdo::Result<()> { self.current_measurement = Some(measurement); Ok(()) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ThermometerMeasurement { #[serde(skip)] calculated_value: Option<f64>, exponent: i16, mantissa: i32, unit: ThermometerMeasurementUnit, time: Option<u64>, r#type: Option<ThermometerMeasurementType>, measurement: ThermometerMeasurementKind, } impl zvariant::Type for ThermometerMeasurement { fn signature() -> zvariant::Signature<'static> { zvariant::Signature::from_str_unchecked("a{sv}") } } const TWO_POW_23: i32 = 8388608; const MANTISSA_NAN: i32 = TWO_POW_23 - 1; const MANTISSA_PINF: i32 = TWO_POW_23 - 2; const MANTISSA_NINF: i32 = -(MANTISSA_PINF); const MANTISSA_NRES: i32 = -(TWO_POW_23); impl std::convert::TryFrom<zvariant::Dict<'_, '_>> for ThermometerMeasurement { type Error = crate::NiterError; fn try_from(dict: zvariant::Dict<'_, '_>) -> crate::NiterResult<Self> { use std::str::FromStr as _; let exponent: i16 = *dict .get("Exponent")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let mantissa: i32 = *dict .get("Mantissa")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let unit: &str = dict .get("Unit")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let time = dict.get("Time")?; let measurement_type: Option<&str> = dict.get("Type")?; let measurement_kind: &str = dict .get("Measurement")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let calculated_value: Option<f64> = if exponent == 0 { match mantissa { MANTISSA_NAN => Some(f64::NAN), MANTISSA_NRES => None, MANTISSA_PINF => Some(f64::INFINITY), MANTISSA_NINF => Some(-f64::INFINITY), _ => None, } } else { Some(mantissa as f64 * 10.0_f64.powi(exponent.into())) }; Ok(Self { calculated_value, exponent, mantissa, unit: ThermometerMeasurementUnit::from_str(&unit)?, time: time.copied(), r#type: measurement_type.and_then(|s| ThermometerMeasurementType::from_str(s).ok()), measurement: ThermometerMeasurementKind::from_str(measurement_kind)?, }) } } impl std::convert::TryFrom<zvariant::OwnedValue> for ThermometerMeasurement { type Error = crate::NiterError; fn try_from(v: zvariant::OwnedValue) -> Result<Self, Self::Error> { use std::convert::TryInto as _; let dict: zvariant::Dict = v.try_into()?; Self::try_from(dict) } } #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementUnit { Celsius, Farenheit, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementUnit); #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementType { Armpit, Body, Ear, Finger, Intestines, Mouth, Rectum, Toe, Tympanum, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementType); #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementKind { Final, Intermediate, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementKind);
#[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct ThermometerManager { object_path: String, } impl std::str::FromStr for ThermometerManager { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_path: s.into(), }) } } crate::to_proxy_impl!(ThermometerManager, ThermometerManagerProxy, "org.bluez"); crate::impl_tryfrom_zvariant!(ThermometerManager); #[zbus::dbus_proxy( interface = "org.bluez.ThermometerManager1", default_service = "org.bluez" )] pub trait ThermometerManager { fn register_watcher(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn unregister_watcher(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn enable_intermediate_measurement(&self, agent: ThermometerWatcher) -> zbus::Result<()>; fn disable_intermediate_measurement(&self, agent: ThermometerWatcher) -> zbus::Result<()>; } #[derive(Debug, Clone, zvariant_derive::Type, serde::Serialize, serde::Deserialize)] pub struct Thermometer { object_path: String, } impl std::str::FromStr for Thermometer { type Err = crate::NiterError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self { object_path: s.into(), }) } } crate::to_proxy_impl!(Thermometer, ThermometerProxy, "org.bluez"); crate::impl_tryfrom_zvariant!(Thermometer); #[zbus::dbus_proxy(interface = "org.bluez.Thermometer1", default_service = "org.bluez")] pub trait Thermometer { #[dbus_proxy(property)] fn intermediate(&self) -> zbus::fdo::Result<bool>; #[dbus_proxy(property)] fn interval(&self) -> zbus::fdo::Result<u16>; #[dbus_proxy(property)] fn set_interval(&self, interval_seconds: u16) -> zbus::fdo::Result<()>; #[dbus_proxy(property)] fn maximum(&self) -> zbus::fdo::Result<u16>; #[dbus_proxy(property)] fn minimum(&self) -> zbus::fdo::Result<u16>; } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct ThermometerWatcher { object_path: String, current_measurement: Option<ThermometerMeasurement>, } impl zvariant::Type for ThermometerWatcher { fn signature() -> zvariant::Signature<'static> { zvariant::Signature::from_str_unchecked("s") } } #[zbus::dbus_interface(name = "org.bluez.ThermometerWatcher1")] impl ThermometerWatcher { fn measurement_received( &mut self, measurement: ThermometerMeasurement, ) -> zbus::fdo::Result<()> { self.current_measurement = Some(measurement); Ok(()) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ThermometerMeasurement { #[serde(skip)] calculated_value: Option<f64>, exponent: i16, mantissa: i32, unit: ThermometerMeasurementUnit, time: Option<u64>, r#type: Option<ThermometerMeasurementType>, measurement: ThermometerMeasurementKind, } impl zvariant::Type for ThermometerMeasurement { fn signature() -> zvariant::Signature<'static> { zvariant::Signature::from_str_unchecked("a{sv}") } } const TWO_POW_23: i32 = 8388608; const MANTISSA_NAN: i32 = TWO_POW_23 - 1; const MANTISSA_PINF: i32 = TWO_POW_23 - 2; const MANTISSA_NINF: i32 = -(MANTISSA_PINF); const MANTISSA_NRES: i32 = -(TWO_POW_23); impl std::convert::TryFrom<zvariant::Dict<'_, '_>> for ThermometerMeasurement { type Error = crate::NiterError; fn try_from(dict: zvariant::Dict<'_, '_>) -> crate::NiterResult<Self> { use std::str::FromStr as _; let exponent: i16 = *dict .get("Exponent")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let mantissa: i32 = *dict .get("Mantissa")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let unit: &str = dict .get("Unit")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let time = dict.get("Time")?; let measurement_type: Option<&str> = dict.get("Type")?; let measurement_kind: &str = dict .get("Measurement")? .ok_or_else(|| zvariant::Error::IncorrectType)?; let calculated_value: Option<f64> = if exponent == 0 { match mantissa { MANTISSA_NAN => Some(f64::NAN), MANTISSA_NRES => None, MANTISSA_PINF => Some(f64::INFINITY), MANTISSA_NINF => Some(-f64::INFINITY), _ => None, } } else { Some(mantissa as f64 * 10.0_f64.powi(exponent.into())) };
} } impl std::convert::TryFrom<zvariant::OwnedValue> for ThermometerMeasurement { type Error = crate::NiterError; fn try_from(v: zvariant::OwnedValue) -> Result<Self, Self::Error> { use std::convert::TryInto as _; let dict: zvariant::Dict = v.try_into()?; Self::try_from(dict) } } #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementUnit { Celsius, Farenheit, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementUnit); #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementType { Armpit, Body, Ear, Finger, Intestines, Mouth, Rectum, Toe, Tympanum, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementType); #[derive( Debug, Clone, Copy, strum::EnumString, strum::Display, zvariant_derive::Type, serde::Serialize, serde::Deserialize, )] #[strum(serialize_all = "lowercase")] pub enum ThermometerMeasurementKind { Final, Intermediate, } crate::impl_tryfrom_zvariant!(ThermometerMeasurementKind);
Ok(Self { calculated_value, exponent, mantissa, unit: ThermometerMeasurementUnit::from_str(&unit)?, time: time.copied(), r#type: measurement_type.and_then(|s| ThermometerMeasurementType::from_str(s).ok()), measurement: ThermometerMeasurementKind::from_str(measurement_kind)?, })
call_expression
[ { "content": "pub trait MediaEndpointDelegate<E: std::error::Error>: zvariant::Type + 'static {\n\n fn set_configuration(&mut self, transport: MediaTransport, properties: MediaEndpointProperties) -> Result<(), E>;\n\n fn select_configuration(&mut self, capabilities: MediaEndpointCapabilities) -> Result<Me...
Rust
server/src/records/users/mod.rs
Deploy-Software/Blog
495868019becb4953ff8ba2a39a8fa936095c772
use async_graphql::{Error, Result, SimpleObject}; use bcrypt::{hash, verify, DEFAULT_COST}; use chrono::DateTime; use regex::Regex; use serde::{Deserialize, Serialize}; use sqlx::PgPool; pub mod session; #[derive(sqlx::FromRow, SimpleObject, Debug, Deserialize, Serialize, Clone)] pub struct SimpleUser { pub id: i32, pub email: String, pub name: String, pub password: String, pub date: DateTime<chrono::Utc>, } impl<'a> SimpleUser { pub fn unwrap_user_session(maybe_user: Option<SimpleUser>) -> Result<SimpleUser> { match maybe_user { Some(user) => Ok(user), None => Err(Error::from("The user session doesn't exist.")), } } pub async fn from_email(pg_pool: &PgPool, email: &'a str) -> Result<Self> { match sqlx::query_as!( Self, r#" SELECT users.id, users.email, users.name, users.password, users.date FROM users WHERE email = $1 "#, email ) .fetch_optional(pg_pool) .await { Ok(maybe_user) => match maybe_user { Some(user) => Ok(user), None => Err(Error::from("The email and password combination failed.")), }, Err(error) => { println!("{}", error.to_string()); Err(Error::from( "An error occured while retrieving the user from the database.", )) } } } pub async fn from_session_token( pg_pool: &PgPool, session_token: &'a str, ) -> Result<Option<Self>> { match sqlx::query_as!( Self, r#" SELECT users.id, users.email, users.name, users.password, users.date FROM users INNER JOIN user_sessions ON users.id = user_sessions.user_id WHERE user_sessions.token = $1 "#, session_token ) .fetch_optional(pg_pool) .await { Ok(maybe_user) => Ok(maybe_user), Err(error) => { println!("{}", error.to_string()); Err(Error::from( "An error occured while retrieving the user from the database.", )) } } } pub async fn password_matches(&self, password_to_test: &'a str) -> Result<bool> { match verify(password_to_test, &self.password) { Ok(matches) => Ok(matches), Err(error) => { println!("{}", error.to_string()); Err(Error::from( "We were unable compare the password with our saved password.", )) } } } } #[derive(sqlx::FromRow, Debug, Deserialize, Serialize)] pub struct NewUser<'a> { pub email: &'a str, pub name: &'a str, pub password: String, } impl<'a> NewUser<'a> { pub fn new(email: &'a str, name: &'a str, password: &'a str) -> Result<Self> { let re = match Regex::new(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") { Ok(re) => re, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Email regex could not be compiled.")); } }; if !re.is_match(email) { return Err(Error::from("Email is not valid.")); } let re = match Regex::new(r"(^[a-zA-Z0-9]{8,}$)") { Ok(re) => re, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Password regex could not be compiled.")); } }; if !re.is_match(password) { return Err(Error::from("Password is not secure enough.")); } let hashed_password = match hash(&password, DEFAULT_COST) { Ok(hashed) => hashed, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Could not hash password.")); } }; Ok(NewUser { email, name, password: hashed_password, }) } pub async fn insert(&self, pg_pool: &PgPool) -> Result<SimpleUser> { match sqlx::query_as!( SimpleUser, r#" INSERT INTO users (email, name, password) VALUES ($1, $2, $3) RETURNING id, email, name, password, date "#, &self.email, &self.name, &self.password ) .fetch_one(pg_pool) .await { Ok(user) => Ok(user), Err(error) => { println!("{}", error.to_string()); Err(Error::from("Unable to insert user in database.")) } } } }
use async_graphql::{Error, Result, SimpleObject}; use bcrypt::{hash, verify, DEFAULT_COST}; use chrono::DateTime; use regex::Regex; use serde::{Deserialize, Serialize}; use sqlx::PgPool; pub mod session; #[derive(sqlx::FromRow, SimpleObject, Debug, Deserialize, Serialize, Clone)] pub struct SimpleUser { pub id: i32, pub email: String, pub name: String, pub password: String, pub date: DateTime<chrono::Utc>, } impl<'a> SimpleUser { pub fn unwrap_user_session(maybe_user: Option<SimpleUser>) -> Result<SimpleUser> { match maybe_user { Some(user) => Ok(user), None => Err(Error::from("The user session doesn't exist.")), } } pub async fn from_email(pg_pool: &PgPool, email: &'a str) -> Result<Self> { match sqlx::query_as!( Self, r#" SELECT users.id, users.email, users.name, users.password, users.date FROM users WHERE email = $1 "#, email ) .fetch_optional(pg_pool) .await { Ok(maybe_user) => match maybe_user { Some(user) => Ok(user), None => Err(Error::from("The email and password combination failed.")), }, Err(error) => { println!("{}", error.to_string()); Err(Error::from( "An error occured while retrieving the user from the database.", )) } } }
pub async fn password_matches(&self, password_to_test: &'a str) -> Result<bool> { match verify(password_to_test, &self.password) { Ok(matches) => Ok(matches), Err(error) => { println!("{}", error.to_string()); Err(Error::from( "We were unable compare the password with our saved password.", )) } } } } #[derive(sqlx::FromRow, Debug, Deserialize, Serialize)] pub struct NewUser<'a> { pub email: &'a str, pub name: &'a str, pub password: String, } impl<'a> NewUser<'a> { pub fn new(email: &'a str, name: &'a str, password: &'a str) -> Result<Self> { let re = match Regex::new(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") { Ok(re) => re, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Email regex could not be compiled.")); } }; if !re.is_match(email) { return Err(Error::from("Email is not valid.")); } let re = match Regex::new(r"(^[a-zA-Z0-9]{8,}$)") { Ok(re) => re, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Password regex could not be compiled.")); } }; if !re.is_match(password) { return Err(Error::from("Password is not secure enough.")); } let hashed_password = match hash(&password, DEFAULT_COST) { Ok(hashed) => hashed, Err(error) => { println!("{}", error.to_string()); return Err(Error::from("Could not hash password.")); } }; Ok(NewUser { email, name, password: hashed_password, }) } pub async fn insert(&self, pg_pool: &PgPool) -> Result<SimpleUser> { match sqlx::query_as!( SimpleUser, r#" INSERT INTO users (email, name, password) VALUES ($1, $2, $3) RETURNING id, email, name, password, date "#, &self.email, &self.name, &self.password ) .fetch_one(pg_pool) .await { Ok(user) => Ok(user), Err(error) => { println!("{}", error.to_string()); Err(Error::from("Unable to insert user in database.")) } } } }
pub async fn from_session_token( pg_pool: &PgPool, session_token: &'a str, ) -> Result<Option<Self>> { match sqlx::query_as!( Self, r#" SELECT users.id, users.email, users.name, users.password, users.date FROM users INNER JOIN user_sessions ON users.id = user_sessions.user_id WHERE user_sessions.token = $1 "#, session_token ) .fetch_optional(pg_pool) .await { Ok(maybe_user) => Ok(maybe_user), Err(error) => { println!("{}", error.to_string()); Err(Error::from( "An error occured while retrieving the user from the database.", )) } } }
function_block-full_function
[ { "content": "type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;\n\n\n\npub struct AuthToken(String);\n", "file_path": "server/src/main.rs", "rank": 0, "score": 78968.49216649115 }, { "content": "#[wasm_bindgen(start)]\n\npub fn run_app() {\n\n App::<Model>...
Rust
src/hash_tree.rs
ChosunOne/binary_merkle_tree
c42d5c980030e28afcf5c2819ea3507a017b00cc
#[cfg(not(any(feature = "use_hashbrown")))] use std::collections::HashMap; use std::path::PathBuf; #[cfg(feature = "use_hashbrown")] use hashbrown::HashMap; use crate::merkle_bit::{BinaryMerkleTreeResult, MerkleBIT}; use crate::traits::{Array, Decode, Encode}; use crate::tree::tree_branch::TreeBranch; use crate::tree::tree_data::TreeData; use crate::tree::tree_leaf::TreeLeaf; use crate::tree::tree_node::TreeNode; use crate::tree_db::HashTreeDB; use crate::tree_hasher::TreeHasher; type Tree<ArrayType, ValueType> = MerkleBIT< HashTreeDB<ArrayType>, TreeBranch<ArrayType>, TreeLeaf<ArrayType>, TreeData, TreeNode<ArrayType>, TreeHasher, ValueType, ArrayType, >; pub struct HashTree<ArrayType = [u8; 32], ValueType = Vec<u8>> where ValueType: Encode + Decode, ArrayType: Array, { tree: Tree<ArrayType, ValueType>, } impl<ValueType, ArrayType> HashTree<ArrayType, ValueType> where ValueType: Encode + Decode, ArrayType: Array, { #[inline] pub fn new(depth: usize) -> BinaryMerkleTreeResult<Self> { let path = PathBuf::new(); let tree = MerkleBIT::new(&path, depth)?; Ok(Self { tree }) } #[inline] pub fn open(path: &PathBuf, depth: usize) -> BinaryMerkleTreeResult<Self> { let tree = MerkleBIT::new(path, depth)?; Ok(Self { tree }) } #[inline] pub fn get( &self, root_hash: &ArrayType, keys: &mut [ArrayType], ) -> BinaryMerkleTreeResult<HashMap<ArrayType, Option<ValueType>>> { self.tree.get(root_hash, keys) } #[inline] pub fn insert( &mut self, previous_root: Option<&ArrayType>, keys: &mut [ArrayType], values: &[ValueType], ) -> BinaryMerkleTreeResult<ArrayType> { self.tree.insert(previous_root, keys, values) } #[inline] pub fn remove(&mut self, root_hash: &ArrayType) -> BinaryMerkleTreeResult<()> { self.tree.remove(root_hash) } #[inline] pub fn generate_inclusion_proof( &self, root: &ArrayType, key: ArrayType, ) -> BinaryMerkleTreeResult<Vec<(ArrayType, bool)>> { self.tree.generate_inclusion_proof(root, key) } #[inline] pub fn verify_inclusion_proof( root: &ArrayType, key: ArrayType, value: &ValueType, proof: &[(ArrayType, bool)], ) -> BinaryMerkleTreeResult<()> { Tree::verify_inclusion_proof(root, key, value, proof) } #[inline] pub fn get_one( &self, root: &ArrayType, key: &ArrayType, ) -> BinaryMerkleTreeResult<Option<ValueType>> { self.tree.get_one(root, key) } #[inline] pub fn insert_one( &mut self, previous_root: Option<&ArrayType>, key: &ArrayType, value: &ValueType, ) -> BinaryMerkleTreeResult<ArrayType> { self.tree.insert_one(previous_root, key, value) } }
#[cfg(not(any(feature = "use_hashbrown")))] use std::collections::HashMap; use std::path::PathBuf; #[cfg(feature = "use_hashbrown")] use hashbrown::HashMap; use crate::merkle_bit::{BinaryMerkleTreeResult, MerkleBIT}; use crate::traits::{Array, Decode, Encode}; use crate::tree::tree_branch::TreeBranch; use crate::tree::tree_data::TreeData; use crate::tree::tree_leaf::TreeLeaf; use crate::tree::tree_node::TreeNode; use crate::tree_db::HashTreeDB; use crate::tree_hasher::TreeHasher; type Tree<ArrayType, ValueType> = MerkleBIT< HashTreeDB<ArrayType>, TreeBranch<ArrayType>, TreeLeaf<ArrayType>, TreeData, TreeNode<ArrayType>, TreeHasher, ValueType, ArrayType, >; pub struct HashTree<ArrayType = [u8; 32], ValueType = Vec<u8>> where ValueType: Encode + Decode, ArrayType: Array, { tree: Tree<ArrayType, ValueType>, } impl<ValueType, ArrayType> HashTree<ArrayType, ValueType> where ValueType: Encode + Decode, ArrayType: Array, { #[inline] pub fn new(depth: usize) -> BinaryMerkleTreeResult<Self> { let path = PathBuf::new(); let tree = MerkleBIT::new(&path, depth)?; Ok(Self { tree }) } #[inline] pub fn open(path: &PathBuf, depth: usize) -> BinaryMerkleTreeResult<Self> { let tree = MerkleBIT::new(path, depth)?; Ok(Self { tree }) } #[inline] pub fn ge
#[inline] pub fn insert( &mut self, previous_root: Option<&ArrayType>, keys: &mut [ArrayType], values: &[ValueType], ) -> BinaryMerkleTreeResult<ArrayType> { self.tree.insert(previous_root, keys, values) } #[inline] pub fn remove(&mut self, root_hash: &ArrayType) -> BinaryMerkleTreeResult<()> { self.tree.remove(root_hash) } #[inline] pub fn generate_inclusion_proof( &self, root: &ArrayType, key: ArrayType, ) -> BinaryMerkleTreeResult<Vec<(ArrayType, bool)>> { self.tree.generate_inclusion_proof(root, key) } #[inline] pub fn verify_inclusion_proof( root: &ArrayType, key: ArrayType, value: &ValueType, proof: &[(ArrayType, bool)], ) -> BinaryMerkleTreeResult<()> { Tree::verify_inclusion_proof(root, key, value, proof) } #[inline] pub fn get_one( &self, root: &ArrayType, key: &ArrayType, ) -> BinaryMerkleTreeResult<Option<ValueType>> { self.tree.get_one(root, key) } #[inline] pub fn insert_one( &mut self, previous_root: Option<&ArrayType>, key: &ArrayType, value: &ValueType, ) -> BinaryMerkleTreeResult<ArrayType> { self.tree.insert_one(previous_root, key, value) } }
t( &self, root_hash: &ArrayType, keys: &mut [ArrayType], ) -> BinaryMerkleTreeResult<HashMap<ArrayType, Option<ValueType>>> { self.tree.get(root_hash, keys) }
function_block-function_prefixed
[ { "content": "#[inline]\n\npub fn generate_tree_ref_queue<ArrayType: Array>(\n\n tree_refs: &mut Vec<TreeRef<ArrayType>>,\n\n tree_ref_queue: &mut HashMap<usize, Vec<(usize, usize, usize)>>,\n\n) -> BinaryMerkleTreeResult<HashSet<usize>> {\n\n let mut unique_split_bits = HashSet::new();\n\n for i in...
Rust
src/util/coalesce.rs
tikue/inverted_index
c912e7c982116591ebd88f2e146f8aa5f7814bd6
use std::collections::BTreeMap; use std::collections::btree_map::Entry::*; use std::iter::FromIterator; pub trait Merge: Ord + Copy { fn merge(self, other: Self) -> Option<Self>; } pub trait Coalesce: Sized + IntoIterator where Self::Item: Ord + Copy + Merge { fn coalesce(&mut self, index: usize, el: Self::Item); fn search_coalesce(&mut self, start: usize, el: Self::Item) -> usize; fn merge_coalesce<Iter>(&mut self, other: Iter) where Iter: IntoIterator<Item = Self::Item> { let mut idx = 0; for element in other { idx = self.search_coalesce(idx, element); } } } impl<T: Ord + Copy + Merge> Coalesce for Vec<T> { fn coalesce(&mut self, index: usize, el: T) { let merge = T::merge; if self.is_empty() { self.insert(index, el); } else if index == 0 { if let Some(coalesced) = merge(el, self[0]) { self[index] = coalesced; } else { self.insert(index, el); } } else if index == self.len() { if let Some(coalesced) = merge(self[index - 1], el) { self[index - 1] = coalesced; } else { self.insert(index, el); } } else { if let Some(coalesced) = merge(self[index - 1], el) { self[index - 1] = coalesced; if let Some(coalesced) = merge(self[index - 1], self[index]) { self[index - 1] = coalesced; self.remove(index); } } else if let Some(coalesced) = merge(el, self[index]) { self[index] = coalesced; } else { self.insert(index, el); } } } fn search_coalesce(&mut self, start: usize, el: T) -> usize { match self[start..].binary_search(&el) { Ok(idx) => start + idx, Err(idx) => { let idx = start + idx; self.coalesce(idx, el); idx } } } } pub struct MergeCoalesceMap<K, V>(pub BTreeMap<K, V>); impl<'a, 'b, K, V> FromIterator<(&'a K, &'b V)> for MergeCoalesceMap<K, V> where K: 'a + Ord + Clone, V: 'b + Coalesce + Clone, V::Item: Ord + Copy + Merge { fn from_iter<It>(iterator: It) -> Self where It: IntoIterator<Item = (&'a K, &'b V)> { let mut map = BTreeMap::new(); for (k, v) in iterator { match map.entry(k.clone()) { Vacant(entry) => { entry.insert(v.clone()); } Occupied(mut entry) => entry.get_mut().merge_coalesce(v.clone()), } } MergeCoalesceMap(map) } } impl<K, V> FromIterator<(K, V)> for MergeCoalesceMap<K, V> where K: Ord + Clone, V: Coalesce + Clone, V::Item: Ord + Copy + Merge { fn from_iter<It>(iterator: It) -> Self where It: IntoIterator<Item = (K, V)> { let mut map = BTreeMap::new(); for (k, v) in iterator { match map.entry(k) { Vacant(entry) => { entry.insert(v); } Occupied(mut entry) => entry.get_mut().merge_coalesce(v.into_iter()), } } MergeCoalesceMap(map) } } macro_rules! impl_merge_tuples { ($tp:ident) => ( impl Merge for ($tp, $tp) { fn merge(self, (begin2, end2): ($tp, $tp)) -> Option<($tp, $tp)> { let (begin1, end1) = self; assert!(begin2 >= begin1, "Input's begin must be >= self's begin"); if end1 >= begin2 { Some(if end1 < end2 { (begin1, end2) } else { (begin1, end1) }) } else { None } } } ) } impl_merge_tuples!(isize); impl_merge_tuples!(usize); impl_merge_tuples!(u32); impl_merge_tuples!(u16); impl_merge_tuples!(u8); impl_merge_tuples!(i32); impl_merge_tuples!(i16); impl_merge_tuples!(i8); #[test] fn test_coalesce_empty() { let mut v = vec![]; v.coalesce(0, (0, 1)); assert_eq!(v, [(0, 1)]); } #[test] fn test_coalesce_first() { let mut v = vec![(1, 1)]; v.coalesce(0, (0, 1)); assert_eq!(v, [(0, 1)]) } #[test] fn test_coalesce_last() { let mut v = vec![(1, 1)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(1, 2)]) } #[test] fn test_coalesce_both() { let mut v = vec![(1, 1), (2, 2)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(1, 2)]) } #[test] fn test_coalesce_none() { let mut v = vec![(1, 1), (3, 3)]; v.coalesce(1, (2, 2)); assert_eq!(v, [(1, 1), (2, 2), (3, 3)]) } #[test] fn test_coalesce_twice() { let mut v = vec![]; v.coalesce(0, (0, 1)); v.coalesce(0, (-2, -1)); v.coalesce(1, (-1, 0)); assert_eq!(v, [(-2, 1)]); } #[test] fn test_search_and_coalesce() { let mut v = vec![]; for el in vec![(0, 1), (-2, -1), (-1, 0)] { let index = v.binary_search(&el).err().unwrap(); v.coalesce(index, el); } assert_eq!(v, [(-2, 1)]); } #[test] fn test_coalesce_subrange() { let mut v = vec![(0, 3)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(0, 3)]); } #[test] fn test_search_coalesce() { let mut v = vec![(0, 1), (2, 3), (4, 5), (6, 7)]; assert_eq!(2, v.search_coalesce(1, (4, 5))); } #[test] fn test_search_coalesce_2() { let mut v = vec![(0, 1), (2, 3), (4, 5), (6, 7)]; assert_eq!(3, v.search_coalesce(1, (5, 6))); assert_eq!(v, [(0, 1), (2, 3), (4, 7)]); }
use std::collections::BTreeMap; use std::collections::btree_map::Entry::*; use std::iter::FromIterator; pub trait Merge: Ord + Copy { fn merge(self, other: Self) -> Option<Self>; } pub trait Coalesce: Sized + IntoIterator where Self::Item: Ord + Copy + Merge { fn coalesce(&mut self, index: usize, el: Self::Item); fn search_coalesce(&mut self, start: usize, el: Self::Item) -> usize; fn merge_coalesce<Iter>(&mut self, other: Iter) where Iter: IntoIterator<Item = Self::Item> { let mut idx = 0; for element in other { idx = self.search_coalesce(idx, element); } } } impl<T: Ord + Copy + Merge> Coalesce for Vec<T> { fn coalesce(&mut self, index: usize, el: T) { let merge = T::merge; if self.is_empty() { self.insert(index, el); } else if index == 0 { if let Some(coalesced) = merge(el, self[0]) { self[index] = coalesced; } else { self.insert(index, el); } } else if index == self.len() { if let Some(coalesced) = merge(self[index - 1], el) { self[index - 1] = coalesced; } else { self.insert(index, el); } } else { if let Some(coalesced) = merge(self[index - 1], el) { self[index - 1] = coalesced; if let Some(coalesced) = merge(self[index - 1], self[index]) { self[index - 1] = coalesced; self.remove(index); } } else if let Some(coalesced) = merge(el, self[index]) { self[index] = coalesced; } else { self.insert(index, el); } } } fn search_coalesce(&mut self, start: usize, el: T) -> usize { match se
} pub struct MergeCoalesceMap<K, V>(pub BTreeMap<K, V>); impl<'a, 'b, K, V> FromIterator<(&'a K, &'b V)> for MergeCoalesceMap<K, V> where K: 'a + Ord + Clone, V: 'b + Coalesce + Clone, V::Item: Ord + Copy + Merge { fn from_iter<It>(iterator: It) -> Self where It: IntoIterator<Item = (&'a K, &'b V)> { let mut map = BTreeMap::new(); for (k, v) in iterator { match map.entry(k.clone()) { Vacant(entry) => { entry.insert(v.clone()); } Occupied(mut entry) => entry.get_mut().merge_coalesce(v.clone()), } } MergeCoalesceMap(map) } } impl<K, V> FromIterator<(K, V)> for MergeCoalesceMap<K, V> where K: Ord + Clone, V: Coalesce + Clone, V::Item: Ord + Copy + Merge { fn from_iter<It>(iterator: It) -> Self where It: IntoIterator<Item = (K, V)> { let mut map = BTreeMap::new(); for (k, v) in iterator { match map.entry(k) { Vacant(entry) => { entry.insert(v); } Occupied(mut entry) => entry.get_mut().merge_coalesce(v.into_iter()), } } MergeCoalesceMap(map) } } macro_rules! impl_merge_tuples { ($tp:ident) => ( impl Merge for ($tp, $tp) { fn merge(self, (begin2, end2): ($tp, $tp)) -> Option<($tp, $tp)> { let (begin1, end1) = self; assert!(begin2 >= begin1, "Input's begin must be >= self's begin"); if end1 >= begin2 { Some(if end1 < end2 { (begin1, end2) } else { (begin1, end1) }) } else { None } } } ) } impl_merge_tuples!(isize); impl_merge_tuples!(usize); impl_merge_tuples!(u32); impl_merge_tuples!(u16); impl_merge_tuples!(u8); impl_merge_tuples!(i32); impl_merge_tuples!(i16); impl_merge_tuples!(i8); #[test] fn test_coalesce_empty() { let mut v = vec![]; v.coalesce(0, (0, 1)); assert_eq!(v, [(0, 1)]); } #[test] fn test_coalesce_first() { let mut v = vec![(1, 1)]; v.coalesce(0, (0, 1)); assert_eq!(v, [(0, 1)]) } #[test] fn test_coalesce_last() { let mut v = vec![(1, 1)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(1, 2)]) } #[test] fn test_coalesce_both() { let mut v = vec![(1, 1), (2, 2)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(1, 2)]) } #[test] fn test_coalesce_none() { let mut v = vec![(1, 1), (3, 3)]; v.coalesce(1, (2, 2)); assert_eq!(v, [(1, 1), (2, 2), (3, 3)]) } #[test] fn test_coalesce_twice() { let mut v = vec![]; v.coalesce(0, (0, 1)); v.coalesce(0, (-2, -1)); v.coalesce(1, (-1, 0)); assert_eq!(v, [(-2, 1)]); } #[test] fn test_search_and_coalesce() { let mut v = vec![]; for el in vec![(0, 1), (-2, -1), (-1, 0)] { let index = v.binary_search(&el).err().unwrap(); v.coalesce(index, el); } assert_eq!(v, [(-2, 1)]); } #[test] fn test_coalesce_subrange() { let mut v = vec![(0, 3)]; v.coalesce(1, (1, 2)); assert_eq!(v, [(0, 3)]); } #[test] fn test_search_coalesce() { let mut v = vec![(0, 1), (2, 3), (4, 5), (6, 7)]; assert_eq!(2, v.search_coalesce(1, (4, 5))); } #[test] fn test_search_coalesce_2() { let mut v = vec![(0, 1), (2, 3), (4, 5), (6, 7)]; assert_eq!(3, v.search_coalesce(1, (5, 6))); assert_eq!(v, [(0, 1), (2, 3), (4, 7)]); }
lf[start..].binary_search(&el) { Ok(idx) => start + idx, Err(idx) => { let idx = start + idx; self.coalesce(idx, el); idx } } }
function_block-function_prefixed
[ { "content": "/// A trait for types whose values have well-defined successors.\n\npub trait Successor: Sized {\n\n /// Returns the successor to self, if any exists.\n\n fn successor(&self) -> Option<Self>;\n\n}\n\n\n\nimpl Successor for char {\n\n #[inline]\n\n // Implementation lifted from https://...
Rust
src/vm/mod.rs
pmk21/rsqlite
2b2b50d64c05293d8bd6d8543cef6347f8d8b961
use crate::buffer::InputBuffer; use crate::constants::{EMAIL_SIZE, TABLE_MAX_ROWS, USERNAME_SIZE}; use crate::table::{Row, Table}; use std::str::FromStr; pub mod statement; use statement::{Statement, StatementType}; pub enum ExecuteResult { Success, TableFull, } pub enum MetaCommandResult { UnrecognizedCommand, } pub enum PrepareResult { Success, UnrecognizedStatement, SyntaxError, StringTooLong, NegativeID, } pub fn do_meta_command(input_buffer: &InputBuffer, table: &mut Table) -> MetaCommandResult { if input_buffer.buffer == ".exit" { table.db_close(); std::process::exit(0); } else { MetaCommandResult::UnrecognizedCommand } } fn prepare_insert(args: &[&str], statement: &mut Statement) -> PrepareResult { statement.row_to_insert.id = match FromStr::from_str(args[1]) { Ok(uint) => uint, Err(_) => return PrepareResult::NegativeID, }; let ubytes = args[2].as_bytes(); let ulen = ubytes.len(); if ulen > USERNAME_SIZE { return PrepareResult::StringTooLong; } let mut username_bytes = [0u8; USERNAME_SIZE]; username_bytes[0..ulen].copy_from_slice(args[2].as_bytes()); statement.row_to_insert.username = username_bytes; let ebytes = args[3].as_bytes(); let elen = ebytes.len(); if elen > EMAIL_SIZE { return PrepareResult::StringTooLong; } let mut email_bytes = [0u8; EMAIL_SIZE]; email_bytes[0..elen].copy_from_slice(args[3].as_bytes()); statement.row_to_insert.email = email_bytes; PrepareResult::Success } pub fn prepare_statement(input_buffer: &InputBuffer, statement: &mut Statement) -> PrepareResult { if &input_buffer.buffer[0..6] == "insert" { statement.stmt_type = StatementType::Insert; let args = input_buffer.buffer.split(' ').collect::<Vec<&str>>(); if args.len() < 4 { return PrepareResult::SyntaxError; } else { return prepare_insert(&args, statement); } } if &input_buffer.buffer[0..6] == "select" { statement.stmt_type = StatementType::Select; return PrepareResult::Success; } PrepareResult::UnrecognizedStatement } pub fn execute_statement(statement: &Statement, table: &mut Table) -> ExecuteResult { match statement.stmt_type { StatementType::Insert => execute_insert(statement, table), StatementType::Select => execute_select(table), StatementType::Empty => { println!("Empty statement"); ExecuteResult::Success } } } fn execute_insert(statement: &Statement, table: &mut Table) -> ExecuteResult { if table.num_rows >= TABLE_MAX_ROWS { return ExecuteResult::TableFull; } let row = Row { id: statement.row_to_insert.id, username: statement.row_to_insert.username, email: statement.row_to_insert.email, }; let (page_num, _) = table.row_slot(table.num_rows); table.serialize_row(row, page_num); table.num_rows += 1; ExecuteResult::Success } fn execute_select(table: &mut Table) -> ExecuteResult { for i in 0..table.num_rows { let (page_num, byte_offset) = table.row_slot(i); &table.deserialize_row(page_num, byte_offset).print_row(); } ExecuteResult::Success }
use crate::buffer::InputBuffer; use crate::constants::{EMAIL_SIZE, TABLE_MAX_ROWS, USERNAME_SIZE}; use crate::table::{Row, Table}; use std::str::FromStr; pub mod statement; use statement::{Statement, StatementType}; pub enum ExecuteResult { Success, TableFull, } pub enum MetaCommandResult { UnrecognizedCommand, } pub enum PrepareResult { Success, UnrecognizedStatement, SyntaxError, StringTooLong, NegativeID, } pub fn do_meta_command(input_buffer: &InputBuffer, table: &mut Table) -> MetaCommandResult { if input_buffer.buffer == ".exit" { table.db_close(); std::process::exit(0); } else { MetaCommandResult::UnrecognizedCommand } } fn prepare_insert(args: &[&str], statement: &mut Statement) -> PrepareResult { statement.row_to_insert.id = match FromStr::from_str(args[1]) { Ok(uint) => uint, Err(_) => return PrepareResult::NegativeID, }; let ubytes = args[2].as_bytes(); let ulen = ubytes.len(); if ulen > USERNAME_SIZE { return PrepareResult::StringTooLong; } let mut username_bytes = [0u8; USERNAME_SIZE]; username_bytes[0..ulen].copy_from_slice(args[2].as_bytes()); statement.row_to_insert.username = username_bytes; let ebytes = args[3].as_bytes(); let elen = ebytes.len(); if elen > EMAIL_SIZE { return PrepareResult::StringTooLong; } let mut email_bytes = [0u8; EMAIL_SIZE]; email_bytes[0..elen].copy_from_slice(args[3].as_bytes()); statement.row_to_insert.email = email_bytes; PrepareResult::Success } pub fn prepare_statement(input_buffer: &InputBuffer, statement: &mut Statement) -> PrepareResult { if &input_buffer.buffer[0..6] == "insert" { statement.stmt_type = StatementType::Insert; let args = input_buffer.buffer.split(' ').collect::<Vec<&str>>(); if args.len() < 4 { return PrepareResult::SyntaxError; } else { return prepare_insert(&args, statement); } } if &input_buffer.buffer[0..6] == "select" { statement.stmt_type = StatementType::Select; return PrepareResult::Success; } PrepareResult::UnrecognizedStatement } pub fn execute_statement(statement: &Statement, table: &mut Table) -> ExecuteResult { match statement.stmt_type { StatementType::Insert => execute_insert(statement, table), StatementType::Select => execute_select(table), StatementType::Empty => { println!("Empty statement"); ExecuteResult::Success } } } fn execute_insert(statement: &Statement, table: &mut Table) -> ExecuteResult { if table.num_rows >= TABLE_MAX_ROWS { return ExecuteResult::TableFull; } let row = Row { id: statement.row_to_insert.id, username: statement.row_to_insert.username, email: statement.row_to_insert.email, }; let (page_num, _) = table.row_slot(table.num_rows); table.serialize_row(row, page_num); table.num_rows += 1; ExecuteResult::Success }
fn execute_select(table: &mut Table) -> ExecuteResult { for i in 0..table.num_rows { let (page_num, byte_offset) = table.row_slot(i); &table.deserialize_row(page_num, byte_offset).print_row(); } ExecuteResult::Success }
function_block-full_function
[ { "content": "//! # Table\n\n//!\n\n//! Interface to implement the structure of a table\n\n\n\nuse crate::constants::{\n\n EMAIL_OFFSET, EMAIL_SIZE, ID_OFFSET, ID_SIZE, ROWS_PER_PAGE, ROW_SIZE, USERNAME_OFFSET,\n\n USERNAME_SIZE,\n\n};\n\n\n\npub mod pager;\n\nuse pager::Pager;\n\n\n\n/// Structure to sto...
Rust
src/main.rs
joxcat/nextcloud-api
5cd949c5dbbe5dc32089ba25ea53221a7b0de52b
mod app; mod library; #[macro_use] extern crate log; #[macro_use] extern crate simple_error; use crate::library::serde_is_valid_and_contain; use badlog::init_from_env; use library::{ create_user, is_env, private_decrypt, public_encrypt, set_var, var, ConvertTo, GenericValue, QueryCreateUser, QueryGetToken, Response, ResponseTypes, Tomb, UserCookies, }; const ENDPOINT: &[u8] = include_bytes!("../keys/endpoints.pub"); const PRIVATE: &[u8] = include_bytes!("../keys/nextcloud.prv"); fn main() -> Result<(), Box<dyn std::error::Error>> { openssl_probe::init_ssl_cert_env_vars(); let endpoint_pub = openssl::rsa::Rsa::public_key_from_pem(ENDPOINT)?; let self_private = openssl::rsa::Rsa::private_key_from_pem(PRIVATE)?; let mut app_base = app::build_cli(); let app = app_base.clone().get_matches(); let (sub, command) = match app.subcommand_matches("create") { Some(_) => (app.subcommand_matches("create"), "create_user"), None => match app.subcommand_matches("cookies") { Some(_) => (app.subcommand_matches("cookies"), "get_token"), None => { app_base.print_help()?; println!("\n"); std::process::exit(-1); } }, }; let sub = sub.unwrap(); match sub.value_of("log-level") { Some(x) => set_var("LOG_LEVEL", x.to_uppercase()), None => { is_env("LOG_LEVEL", &|_| (), &|env| set_var(env, "INFO")); } } init_from_env("LOG_LEVEL"); match sub.value_of("timeout") { Some(x) => set_var("HEADLESS_TIMEOUT", x), None => { is_env("HEADLESS_TIMEOUT", &|_| {}, &|env| set_var(env, "3000")); } } info!("Headless timeout: {}", var("HEADLESS_TIMEOUT")?); is_env("BASE_NC_URL", &|_| {}, &|env| { set_var(env, "https://files.hume.cloud") }); let username_uncrypt = String::from_utf8(base64::decode( &private_decrypt( &self_private, serde_json::from_str::<Tomb>( String::from_utf8(base64::decode(&sub.value_of("username").unwrap())?)?.as_str(), )?, )? .value, )?)?; let password_uncrypt = String::from_utf8(base64::decode( &private_decrypt( &self_private, serde_json::from_str::<Tomb>( String::from_utf8(base64::decode(&sub.value_of("password").unwrap())?)?.as_str(), )?, )? .value, )?)?; let text = &match command { "create_user" => format!( r#"{{"command":"{}","username":"{}","password":"{}"}}"#, command, username_uncrypt, password_uncrypt ), "get_token" => format!( r#"{{"command":"{}","username":"{}","password":"{}","response_type":"{}"}}"#, command, username_uncrypt, password_uncrypt, sub.value_of("response-type").unwrap() ), _ => std::process::exit(-1), }[..]; let result = if serde_is_valid_and_contain::<QueryCreateUser>(text, "command", "create_user") { let msg = serde_json::from_str::<QueryCreateUser>(text).unwrap(); is_env( "NC_ADMIN_USERNAME", &|env| info!("{} is set", env), &|env| { info!("{} is not set", env); let response = public_encrypt( &endpoint_pub, serde_json::to_string(&Response::<GenericValue<ResponseTypes>> { status_code: 503, error_msg: Some( "The server is unavailable to handle this request right now", ), error_details: Some("Error! Missing some env variables"), value: None, }) .unwrap() .as_bytes(), ) .unwrap(); let response = base64::encode(&serde_json::to_string(&response).unwrap()); println!("{}", response); std::process::exit(-1); }, ); is_env( "NC_ADMIN_PASSWORD", &|env| info!("{} is set", env), &|env| { info!("{} is not set", env); let response = public_encrypt( &endpoint_pub, serde_json::to_string(&Response::<GenericValue<ResponseTypes>> { status_code: 503, error_msg: Some( "The server is unavailable to handle this request right now", ), error_details: Some("Error! Missing some env variables"), value: None, }) .unwrap() .as_bytes(), ) .unwrap(); let response = base64::encode(&serde_json::to_string(&response).unwrap()); println!("{}", response); std::process::exit(-1); }, ); match create_user(msg) { Ok(_) => { let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Boolean(true)); Response { status_code: 200, error_msg: None, error_details: None, value: val, } } Err(_) => { let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Boolean(false)); Response { status_code: 500, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot create the user"), value: val, } } } } else if serde_is_valid_and_contain::<QueryGetToken>(text, "command", "get_token") { let msg = serde_json::from_str::<QueryGetToken>(text).unwrap(); #[allow(unused_assignments)] let mut resp = (String::new(), String::new(), String::new()); let val_converter = msg.value_type; match library::get_tokens(msg) { Ok(_resp) => { resp = _resp; let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Cookies(UserCookies { nc_session_id: val_converter.convert_to(resp.0.as_str()), nc_token: val_converter.convert_to(resp.1.as_str()), nc_username: val_converter.convert_to(resp.2.as_str()), })); Response { status_code: 200, error_msg: None, error_details: None, value: val, } } Err(e) => { warn!("{}", e); Response { status_code: 500, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot get the tokens"), value: None, } } } } else { Response { status_code: 500, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot get the tokens"), value: None, } }; let response = public_encrypt( &endpoint_pub, serde_json::to_string(&result).unwrap().as_bytes(), )?; let response = base64::encode(&serde_json::to_string(&response)?); println!("{}", response); std::process::exit(0) }
mod app; mod library; #[macro_use] extern crate log; #[macro_use] extern crate simple_error; use crate::library::serde_is_valid_and_contain; use badlog::init_from_env; use library::{ create_user, is_env, private_decrypt, public_encrypt, set_var, var, ConvertTo, GenericValue, QueryCreateUser, QueryGetToken, Response, ResponseTypes, Tomb, UserCookies, }; const ENDPOINT: &[u8] = include_bytes!("../keys/endpoints.pub"); const PRIVATE: &[u8] = include_bytes!("../keys/nextcloud.prv"); fn main() -> Result<(), Box<dyn std::error::Error>> { openssl_probe::init_ssl_cert_env_vars(); let endpoint_pub = openssl::rsa::Rsa::public_key_from_pem(ENDPOINT)?; let self_private = openssl::rsa::Rsa::private_key_from_pem(PRIVATE)?; let mut app_base = app::build_cli(); let app = app_base.clone().get_matches(); let (sub, command) = match app.subcommand_matches("create") { Some(_) => (app.subcommand_matches("create"), "create_user"), None => match app.subcommand_matches("cookies") { Some(_) => (app.subcommand_matches("cookies"), "get_token"), None => { app_base.print_help()?; println!("\n"); std::process::exit(-1); } }, }; let sub = sub.unwrap(); match sub.value_of("log-level") { Some(x) => set_var("LOG_LEVEL", x.to_uppercase()), None => { is_env("LOG_LEVEL", &|_| (), &|env| set_var(env, "INFO")); } } init_from_env("LOG_LEVEL"); match sub.value_of("timeout") { Some(x) => set_var("HEADLESS_TIMEOUT", x), None => { is_env("HEADLESS_TIMEOUT", &|_| {}, &|env| set_var(env, "3000")); } } info!("Headless timeout: {}", var("HEADLESS_TIMEOUT")?); is_env("BASE_NC_URL", &|_| {}, &|env| { set_var(env, "https://files.hume.cloud") }); let username_uncrypt = String::from_utf8(base64::decode( &private_decrypt( &self_private, serde_json::from_str::<Tomb>( String::from_utf8(base64::decode(&sub.value_of("username").unwrap())?)?.as_str(), )?, )? .value, )?)?; let password_uncrypt = String::from_utf8(base64::decode( &private_decrypt( &self_private, serde_json::from_str::<Tomb>( String::from_utf8(base64::decode(&sub.value_of("password").unwrap())?)?.as_str(), )?, )? .value, )?)?; let text = &match command { "create_user" => format!( r#"{{"command":"{}","username":"{}","password":"{}"}}"#, command, username_uncrypt, password_uncrypt ), "get_token" => format!( r#"{{"command":"{}","username":"{}","password":"{}","response_type":"{}"}}"#, command, username_uncrypt, password_uncrypt, sub.value_of("response-type").unwrap() ), _ => std::process::exit(-1), }[..]; let result = if serde_is_valid_and_contain::<QueryCreateUser>(text, "command", "create_user") { let msg = serde_json::from_str::<QueryCreateUser>(text).unwrap(); is_env( "NC_ADMIN_USERNAME", &|env| info!("{} is set", env), &|env| { info!("{} is not set", env); let response = public_encrypt( &endpoint_pub, serde_json::to_string(&Response::<GenericValue<ResponseTypes>> { status_code: 503, error_msg: Some( "The server is unavailable to handle this request right now", ), error_details: Some("Error! Missing some env variables"), value: None, }) .unwrap() .as_bytes(), ) .unwrap(); let response = base64::encode(&serde_json::to_string(&response).unwrap()); println!("{}", response); std::process::exit(-1); }, ); is_env( "NC_ADMIN_PASSWORD", &|env| info!("{} is set", env), &|env| { info!("{} is not set", env); let response = public_encrypt( &endpoint_pub, serde_json::to_string(&Response::<GenericValue<ResponseTypes>> { status_code: 503, error_msg: Some( "The server is unavailable to handle this request right now", ), error_details: Some("Error! Missing some env variables"), value: None, }) .unwrap() .as_bytes(), ) .unwrap(); let response = base64::encode(&serde_json::to_string(&response).unwrap()); println!("{}", response); std::process::exit(-1); }, ); match create_user(msg) { Ok(_) => { let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Boolean(true)); Response { status_code: 200, error_msg: None, error_details: None, value: val, } } Err(_) => { let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Boolean(false)); Response { status_code: 500, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot create the user"), value: val, } } } } else if serde_is_valid_and_contain::<QueryGetToken>(text, "command", "get_token") { let msg = serde_json::from_str::<QueryGetToken>(text).unwrap(); #[allow(unused_assignments)] let mut resp = (String::new(), String::new(), String::new()); let val_converter = msg.value_type; match library::get_tokens(msg) { Ok(_resp) => { resp = _resp; let val: GenericValue<ResponseTypes> = Some(ResponseTypes::Cookies(UserCookies { nc_session_id: val_converter.convert_to(resp.0.as_str()), nc_token: val_converter.convert_to(resp.1.as_str()), nc_username: val_converter.convert_to(resp.2.as_str()), })); Response { status_code: 200, error_msg: None, error_details: None, value: val, } } Err(e) => { warn!("{}", e); Response { status_code: 50
0, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot get the tokens"), value: None, } } } } else { Response { status_code: 500, error_msg: Some("Internal Server Error"), error_details: Some("Error! Cannot get the tokens"), value: None, } }; let response = public_encrypt( &endpoint_pub, serde_json::to_string(&result).unwrap().as_bytes(), )?; let response = base64::encode(&serde_json::to_string(&response)?); println!("{}", response); std::process::exit(0) }
function_block-function_prefixed
[ { "content": "pub fn create_user(query: QueryCreateUser) -> Result<(), Box<dyn std::error::Error>> {\n\n // Browser setup\n\n let self_private = openssl::rsa::Rsa::private_key_from_pem(PRIVATE)?;\n\n let username = var(\"NC_ADMIN_USERNAME\").unwrap();\n\n let username = String::from_utf8(base64::dec...
Rust
bencode/tests/ser.rs
adrianplavka/rbit
de7e950c894666b987617cfcdfa7218379c953f7
#[cfg(test)] mod ser_tests { extern crate bitrust_bencode; use bitrust_bencode::to_string; use serde::Serialize; #[test] fn ser_integers() { assert_eq!(r#"i0e"#, to_string(&0usize).unwrap()); assert_eq!(r#"i0e"#, to_string(&0isize).unwrap()); assert_eq!(r#"i1e"#, to_string(&1usize).unwrap()); assert_eq!(r#"i1e"#, to_string(&1isize).unwrap()); assert_eq!(r#"i123e"#, to_string(&123usize).unwrap()); assert_eq!(r#"i123e"#, to_string(&123isize).unwrap()); assert_eq!(r#"i0e"#, to_string(&-0).unwrap()); assert_eq!(r#"i-1e"#, to_string(&-1).unwrap()); assert_eq!(r#"i-123e"#, to_string(&-123).unwrap()); } #[test] fn ser_integers_bounds() { assert_eq!( format!("i{}e", std::u8::MAX), to_string(&std::u8::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u16::MAX), to_string(&std::u16::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u32::MAX), to_string(&std::u32::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u64::MAX), to_string(&std::u64::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i8::MAX), to_string(&std::i8::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i16::MAX), to_string(&std::i16::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i32::MAX), to_string(&std::i32::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i64::MAX), to_string(&std::i64::MAX).unwrap() ); } #[test] fn ser_strings() { assert_eq!(r#"3:key"#, to_string(&"key").unwrap()); assert_eq!(r#"5:asdfg"#, to_string(&"asdfg").unwrap()); assert_eq!(r#"4:0087"#, to_string(&"0087").unwrap()); assert_eq!(r#"0:"#, to_string(&"").unwrap()); assert_eq!(r#"2: "#, to_string(&" ").unwrap()); assert_eq!(r#"6:โค๏ธ"#, to_string(&"โค๏ธ").unwrap()); assert_eq!( r#"21:!@#$%^&*()_+{}|:<>?"/"#, to_string(&"!@#$%^&*()_+{}|:<>?\"/").unwrap() ); assert_eq!( r#"28:KR๏ฟฝ/[W+x/^nAkW๏ฟฝ๏ฟฝ;T0"#, to_string(&r#"KR๏ฟฝ/[W+x/^nAkW๏ฟฝ๏ฟฝ;T0"#).unwrap() ); } #[test] fn ser_structs() { #[derive(Serialize, PartialEq, Debug)] struct IntegerTest { integer: i32, integers: Vec<i32>, } assert_eq!( r#"d7:integeri1995e8:integersli1ei2ei3eee"#, to_string(&IntegerTest { integer: 1995, integers: vec!(1, 2, 3) }) .unwrap() ); #[derive(Serialize, PartialEq, Debug)] struct StringTest<'a> { string: String, strings: Vec<String>, string_slice: &'a str, string_slices: Vec<&'a str>, } assert_eq!( r#"d6:string10:somestring7:stringsl1:a1:b1:ce12:string_slice100:longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring13:string_slicesl1:d1:e1:f1:gee"#, to_string(&StringTest { string: String::from("somestring"), strings: vec!(String::from("a"), String::from("b"), String::from("c")), string_slice: "longstring".repeat(10).as_str(), string_slices: vec!("d", "e", "f", "g") }) .unwrap() ); #[derive(Serialize, PartialEq, Debug)] struct InnerMixedStructTest<'a> { string: &'a str, } #[derive(Serialize, PartialEq, Debug)] struct MixedStructTest<'a> { integer: usize, negative_integer: i32, #[serde(borrow)] inner_struct: InnerMixedStructTest<'a>, } assert_eq!( r#"d7:integeri3000e16:negative_integeri-89343451e12:inner_structd6:string4:asdfee"#, to_string(&MixedStructTest { integer: 3000, negative_integer: -89343451, inner_struct: InnerMixedStructTest { string: "asdf" } }) .unwrap() ); } }
#[cfg(test)] mod ser_tests { extern crate bitrust_bencode; use bitrust_bencode::to_string; use serde::Serialize; #[test] fn ser_integers() { assert_eq!(r#"i0e"#, to_string(&0usize).unwrap()); assert_eq!(r#"i0e"#, to_string(&0isize).unwrap()); assert_eq!(r#"i1e"#, to_string(&1usize).unwrap()); assert_eq!(r#"i1e"#, to_string(&1isize).unwrap()); assert_eq!(r#"i123e"#, to_string(&123usize).unwrap()); assert_eq!(r#"i123e"#, to_string(&123isize).unwrap()); assert_eq!(r#"i0e"#, to_string(&-0).unwrap()); assert_eq!(r#"i-1e"#, to_string(&-1).unwrap()); assert_eq!(r#"i-123e"#, to_string(&-123).unwrap()); } #[test] fn ser_integers_bounds() { assert_eq!( format!("i{}e", std::u8::MAX), to_string(&std::u8::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u16::MAX), to_string(&std::u16::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u32::MAX), to_string(&std::u32::MAX).unwrap() ); assert_eq!( format!("i{}e", std::u64::MAX), to_string(&std::u64::MAX).unwrap() ); assert_e
#[test] fn ser_strings() { assert_eq!(r#"3:key"#, to_string(&"key").unwrap()); assert_eq!(r#"5:asdfg"#, to_string(&"asdfg").unwrap()); assert_eq!(r#"4:0087"#, to_string(&"0087").unwrap()); assert_eq!(r#"0:"#, to_string(&"").unwrap()); assert_eq!(r#"2: "#, to_string(&" ").unwrap()); assert_eq!(r#"6:โค๏ธ"#, to_string(&"โค๏ธ").unwrap()); assert_eq!( r#"21:!@#$%^&*()_+{}|:<>?"/"#, to_string(&"!@#$%^&*()_+{}|:<>?\"/").unwrap() ); assert_eq!( r#"28:KR๏ฟฝ/[W+x/^nAkW๏ฟฝ๏ฟฝ;T0"#, to_string(&r#"KR๏ฟฝ/[W+x/^nAkW๏ฟฝ๏ฟฝ;T0"#).unwrap() ); } #[test] fn ser_structs() { #[derive(Serialize, PartialEq, Debug)] struct IntegerTest { integer: i32, integers: Vec<i32>, } assert_eq!( r#"d7:integeri1995e8:integersli1ei2ei3eee"#, to_string(&IntegerTest { integer: 1995, integers: vec!(1, 2, 3) }) .unwrap() ); #[derive(Serialize, PartialEq, Debug)] struct StringTest<'a> { string: String, strings: Vec<String>, string_slice: &'a str, string_slices: Vec<&'a str>, } assert_eq!( r#"d6:string10:somestring7:stringsl1:a1:b1:ce12:string_slice100:longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring13:string_slicesl1:d1:e1:f1:gee"#, to_string(&StringTest { string: String::from("somestring"), strings: vec!(String::from("a"), String::from("b"), String::from("c")), string_slice: "longstring".repeat(10).as_str(), string_slices: vec!("d", "e", "f", "g") }) .unwrap() ); #[derive(Serialize, PartialEq, Debug)] struct InnerMixedStructTest<'a> { string: &'a str, } #[derive(Serialize, PartialEq, Debug)] struct MixedStructTest<'a> { integer: usize, negative_integer: i32, #[serde(borrow)] inner_struct: InnerMixedStructTest<'a>, } assert_eq!( r#"d7:integeri3000e16:negative_integeri-89343451e12:inner_structd6:string4:asdfee"#, to_string(&MixedStructTest { integer: 3000, negative_integer: -89343451, inner_struct: InnerMixedStructTest { string: "asdf" } }) .unwrap() ); } }
q!( format!("i{}e", std::i8::MAX), to_string(&std::i8::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i16::MAX), to_string(&std::i16::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i32::MAX), to_string(&std::i32::MAX).unwrap() ); assert_eq!( format!("i{}e", std::i64::MAX), to_string(&std::i64::MAX).unwrap() ); }
function_block-function_prefixed
[ { "content": "fn main() {\n\n\n\n}\n", "file_path": "core/src/main.rs", "rank": 0, "score": 34516.8374640069 }, { "content": "pub fn to_string<T>(value: &T) -> Result<String>\n\nwhere\n\n T: Serialize,\n\n{\n\n let mut serializer = Serializer {\n\n output: String::new(),\n\n ...
Rust
crates/notation_bevy/src/play/play_plugin.rs
theAdamColton/notation
270e8592127c8e60ff33b12b040ab55dba5c92a3
use std::sync::Arc; use notation_bevy_utils::prelude::{DoLayoutEvent, GridData, LayoutData, ShapeOp, ColorBackground}; use notation_midi::prelude::PlayControlEvent; use notation_model::prelude::{ LaneEntry, PlayState, PlayingState, Position, Tab, TickResult, }; use bevy::prelude::*; use crate::bar::bar_beat::BarBeatData; use crate::bar::bar_view::BarView; use crate::chord::chord_color_background::ChordColorBackground; use crate::chord::chord_playing::ChordPlaying; use crate::prelude::{ BarPlaying, EntryPlaying, NotationAssetsStates, NotationSettings, NotationTheme, TabBars, TabState, }; use crate::settings::layout_settings::LayoutMode; use crate::tab::tab_events::TabBarsResizedEvent; use crate::tab::tab_state::TabPlayStateChanged; use crate::ui::layout::NotationLayout; use super::bar_indicator::{BarIndicatorData}; use super::play_button::PlayButton; use super::play_panel::PlayPanel; use super::pos_indicator::{PosIndicatorData}; pub type PlayPanelDoLayoutEvent = DoLayoutEvent<NotationLayout<'static>, PlayPanel>; pub struct PlayPlugin; impl Plugin for PlayPlugin { fn build(&self, app: &mut AppBuilder) { PlayPanelDoLayoutEvent::setup(app); app.add_system_set( SystemSet::on_update(NotationAssetsStates::Loaded) .with_system(PlayPanel::do_layout.system()) .with_system(PlayPanel::on_play_control_evt.system()) .with_system(PlayButton::on_layout_changed.system()) .with_system(on_bar_playing_changed.system()) .with_system(on_tab_play_state_changed.system()) .with_system(on_play_control_evt.system()) .with_system(on_tab_resized.system()), ); } } impl PlayPlugin { pub fn spawn_indicators( commands: &mut Commands, theme: &NotationTheme, entity: Entity, tab: &Arc<Tab>, ) { let bar_data = BarIndicatorData::new(tab.clone()); bar_data.create(commands, &theme, entity); let pos_data = PosIndicatorData::new(tab.bar_units()); pos_data.create(commands, &theme, entity); } } fn update_indicators( commands: &mut Commands, theme: &NotationTheme, settings: &mut NotationSettings, chord_color_background_query: &mut Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, bar_indicator_query: &mut Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, pos_indicator_query: &mut Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, tab_bars_query: &mut Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, bar_playing: &BarPlaying, bar_layout: LayoutData, ) { let bar_props = bar_playing.bar_props; let mut in_bar_pos = None; for (entity, mut data) in pos_indicator_query.iter_mut() { data.bar_props = bar_props; data.bar_layout = bar_layout; data.update(commands, &theme, entity); settings .layout .focus_bar(commands, theme, tab_bars_query, &data); in_bar_pos = Some(data.bar_position.in_bar_pos); } for (entity, mut data) in bar_indicator_query.iter_mut() { data.bar_props = bar_props; data.bar_layout = bar_layout; data.update_data(commands, theme, entity, bar_props, bar_layout, in_bar_pos); ChordColorBackground::update_color(commands, theme, chord_color_background_query, data.chord); } } fn on_tab_resized( mut evts: EventReader<TabBarsResizedEvent>, mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &BarPlaying, &Arc<BarView>, &LayoutData)>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } let mut bars = None; for evt in evts.iter() { bars = Some(&evt.0); } if let Some(_bars) = bars { let mut first_playing_layout = None; let mut current_playing_layout = None; for (_entity, playing, view, layout) in query.iter_mut() { if view.bar_props.bar_ordinal == 0 { first_playing_layout = Some((playing, layout.clone())); } if playing.value == PlayingState::Current { current_playing_layout = Some((playing, layout.clone())); break; } } let playing_layout = if current_playing_layout.is_none() { first_playing_layout } else { current_playing_layout }; if let Some((playing, layout)) = playing_layout { update_indicators( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut tab_bars_query, playing, layout.clone(), ); } } } fn on_bar_playing_changed( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &BarPlaying, &Arc<BarView>, &LayoutData), Changed<BarPlaying>>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } for (_entity, playing, _view, layout) in query.iter_mut() { if playing.value == PlayingState::Current { update_indicators( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut tab_bars_query, playing, layout.clone(), ); break; } } } fn on_tab_play_state_changed( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &TabState), Added<TabPlayStateChanged>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut bar_playing_query: Query<(Entity, &mut BarPlaying), With<BarPlaying>>, mut entry_playing_query: Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } for (state_entity, tab_state) in query.iter_mut() { TabState::clear_play_state_changed(&mut commands, state_entity); if let Some(pos_data) = PosIndicatorData::update_pos( &mut commands, &theme, &mut pos_indicator_query, tab_state.play_control.position, ) { settings .layout .focus_bar(&mut commands, &theme, &mut tab_bars_query, &pos_data); } if !tab_state.play_control.play_state.is_playing() { let playing_bar_ordinal = tab_state.play_control.position.bar.bar_ordinal; BarPlaying::update(&mut bar_playing_query, tab_state, playing_bar_ordinal); EntryPlaying::update(&mut entry_playing_query, tab_state); } } } fn on_tick( commands: &mut Commands, theme: &NotationTheme, settings: &mut NotationSettings, chord_color_background_query: &mut Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, bar_indicator_query: &mut Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, pos_indicator_query: &mut Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, bar_playing_query: &mut Query<(Entity, &mut BarPlaying), With<BarPlaying>>, entry_playing_query: &mut Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, chord_playing_query: &mut Query<(Entity, &mut ChordPlaying), With<ChordPlaying>>, tab_bars_query: &mut Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, state_entity: Entity, tab_state: &mut TabState, new_position: &Position, tick_result: &TickResult, ) { tab_state.set_position(*new_position); let TickResult { changed: _changed, end_passed, stopped, jumped, } = tick_result; if *stopped { tab_state.set_play_state(commands, state_entity, PlayState::Stopped); } let playing_bar_ordinal = new_position.bar.bar_ordinal; BarPlaying::update(bar_playing_query, tab_state, playing_bar_ordinal); EntryPlaying::update_with_pos( entry_playing_query, tab_state, new_position, *end_passed, *jumped, ); let chord_changed = ChordPlaying::update(chord_playing_query, tab_state, new_position); if let Some(pos_data) = PosIndicatorData::update_pos(commands, theme, pos_indicator_query, *new_position) { if settings.layout.mode == LayoutMode::Line && pos_data.is_synced() { settings .layout .focus_bar(commands, theme, tab_bars_query, &pos_data); } if chord_changed > 0 { if let Some(bar_data) = BarIndicatorData::update_pos(commands, theme, bar_indicator_query, pos_data.bar_props, pos_data.bar_position.in_bar_pos) { ChordColorBackground::update_color(commands, theme, chord_color_background_query, bar_data.chord); } } } } fn on_play_control_evt( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut evts: EventReader<PlayControlEvent>, mut tab_state_query: Query<(Entity, &mut TabState)>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut bar_playing_query: Query<(Entity, &mut BarPlaying), With<BarPlaying>>, mut entry_playing_query: Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, mut chord_playing_query: Query<(Entity, &mut ChordPlaying), With<ChordPlaying>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, mut beat_query: Query<(Entity, &mut BarBeatData)>, ) { if theme._bypass_systems { return; } for evt in evts.iter() { for (state_entity, mut tab_state) in tab_state_query.iter_mut() { if !tab_state.under_control { continue; } match evt { PlayControlEvent::OnTick { position, tick_result, } => on_tick( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut bar_playing_query, &mut entry_playing_query, &mut chord_playing_query, &mut tab_bars_query, state_entity, &mut tab_state, position, tick_result, ), PlayControlEvent::OnPlayState(play_state) => { tab_state.set_play_state(&mut commands, state_entity, *play_state); } PlayControlEvent::OnSpeedFactor(play_speed) => { tab_state.set_speed_factor(*play_speed); } PlayControlEvent::OnBeginEnd(begin_bar_ordinal, end_bar_ordinal) => { tab_state.set_begin_end(*begin_bar_ordinal, *end_bar_ordinal); BarBeatData::update_all(&mut commands, &theme, &tab_state, &mut beat_query); } PlayControlEvent::OnShouldLoop(should_loop) => { tab_state.set_should_loop(*should_loop); } } } } }
use std::sync::Arc; use notation_bevy_utils::prelude::{DoLayoutEvent, GridData, LayoutData, ShapeOp, ColorBackground}; use notation_midi::prelude::PlayControlEvent; use notation_model::prelude::{ LaneEntry, PlayState, PlayingState, Position, Tab, TickResult, }; use bevy::prelude::*; use crate::bar::bar_beat::BarBeatData; use crate::bar::bar_view::BarView; use crate::chord::chord_color_background::ChordColorBackground; use crate::chord::chord_playing::ChordPlaying; use crate::prelude::{ BarPlaying, EntryPlaying, NotationAssetsStates, NotationSettings, NotationTheme, TabBars, TabState, }; use crate::settings::layout_settings::LayoutMode; use crate::tab::tab_events::TabBarsResizedEvent; use crate::tab::tab_state::TabPlayStateChanged; use crate::ui::layout::NotationLayout; use super::bar_indicator::{BarIndicatorData}; use super::play_button::PlayButton; use super::play_panel::PlayPanel; use super::pos_indicator::{PosIndicatorData}; pub type PlayPanelDoLayoutEvent = DoLayoutEvent<NotationLayout<'static>, PlayPanel>; pub struct PlayPlugin; impl Plugin for PlayPlugin { fn build(&self, app: &mut AppBuilder) { PlayPanelDoLayoutEvent::setup(app); app.add_system_set( SystemSet::on_update(NotationAssetsStates::Loaded) .with_system(PlayPanel::do_layout.system()) .with_system(PlayPanel::on_play_control_evt.system()) .with_system(PlayButton::on_layout_changed.system()) .with_system(on_bar_playing_changed.system()) .with_system(on_tab_play_state_changed.system()) .with_system(on_play_control_evt.system()) .with_system(on_tab_resized.system()), ); } } impl PlayPlugin { pub fn spawn_indicators( commands: &mut Commands, theme: &NotationTheme, entity: Entity, tab: &Arc<Tab>, ) { let bar_data = BarIndicatorData::new(tab.clone()); bar_data.create(commands, &theme, entity); let pos_data = PosIndicatorData::new(tab.bar_units()); pos_data.create(commands, &theme, entity); } } fn update_indicators( commands: &mut Commands, theme: &NotationTheme, settings: &mut NotationSettings, chord_color_background_query: &mut Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, bar_indicator_query: &mut Query<(Entity, &mut BarIndicatorData), With<BarIndicatorD
fn on_tab_resized( mut evts: EventReader<TabBarsResizedEvent>, mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &BarPlaying, &Arc<BarView>, &LayoutData)>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } let mut bars = None; for evt in evts.iter() { bars = Some(&evt.0); } if let Some(_bars) = bars { let mut first_playing_layout = None; let mut current_playing_layout = None; for (_entity, playing, view, layout) in query.iter_mut() { if view.bar_props.bar_ordinal == 0 { first_playing_layout = Some((playing, layout.clone())); } if playing.value == PlayingState::Current { current_playing_layout = Some((playing, layout.clone())); break; } } let playing_layout = if current_playing_layout.is_none() { first_playing_layout } else { current_playing_layout }; if let Some((playing, layout)) = playing_layout { update_indicators( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut tab_bars_query, playing, layout.clone(), ); } } } fn on_bar_playing_changed( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &BarPlaying, &Arc<BarView>, &LayoutData), Changed<BarPlaying>>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } for (_entity, playing, _view, layout) in query.iter_mut() { if playing.value == PlayingState::Current { update_indicators( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut tab_bars_query, playing, layout.clone(), ); break; } } } fn on_tab_play_state_changed( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut query: Query<(Entity, &TabState), Added<TabPlayStateChanged>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut bar_playing_query: Query<(Entity, &mut BarPlaying), With<BarPlaying>>, mut entry_playing_query: Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, ) { if theme._bypass_systems { return; } for (state_entity, tab_state) in query.iter_mut() { TabState::clear_play_state_changed(&mut commands, state_entity); if let Some(pos_data) = PosIndicatorData::update_pos( &mut commands, &theme, &mut pos_indicator_query, tab_state.play_control.position, ) { settings .layout .focus_bar(&mut commands, &theme, &mut tab_bars_query, &pos_data); } if !tab_state.play_control.play_state.is_playing() { let playing_bar_ordinal = tab_state.play_control.position.bar.bar_ordinal; BarPlaying::update(&mut bar_playing_query, tab_state, playing_bar_ordinal); EntryPlaying::update(&mut entry_playing_query, tab_state); } } } fn on_tick( commands: &mut Commands, theme: &NotationTheme, settings: &mut NotationSettings, chord_color_background_query: &mut Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, bar_indicator_query: &mut Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, pos_indicator_query: &mut Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, bar_playing_query: &mut Query<(Entity, &mut BarPlaying), With<BarPlaying>>, entry_playing_query: &mut Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, chord_playing_query: &mut Query<(Entity, &mut ChordPlaying), With<ChordPlaying>>, tab_bars_query: &mut Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, state_entity: Entity, tab_state: &mut TabState, new_position: &Position, tick_result: &TickResult, ) { tab_state.set_position(*new_position); let TickResult { changed: _changed, end_passed, stopped, jumped, } = tick_result; if *stopped { tab_state.set_play_state(commands, state_entity, PlayState::Stopped); } let playing_bar_ordinal = new_position.bar.bar_ordinal; BarPlaying::update(bar_playing_query, tab_state, playing_bar_ordinal); EntryPlaying::update_with_pos( entry_playing_query, tab_state, new_position, *end_passed, *jumped, ); let chord_changed = ChordPlaying::update(chord_playing_query, tab_state, new_position); if let Some(pos_data) = PosIndicatorData::update_pos(commands, theme, pos_indicator_query, *new_position) { if settings.layout.mode == LayoutMode::Line && pos_data.is_synced() { settings .layout .focus_bar(commands, theme, tab_bars_query, &pos_data); } if chord_changed > 0 { if let Some(bar_data) = BarIndicatorData::update_pos(commands, theme, bar_indicator_query, pos_data.bar_props, pos_data.bar_position.in_bar_pos) { ChordColorBackground::update_color(commands, theme, chord_color_background_query, bar_data.chord); } } } } fn on_play_control_evt( mut commands: Commands, theme: Res<NotationTheme>, mut settings: ResMut<NotationSettings>, mut evts: EventReader<PlayControlEvent>, mut tab_state_query: Query<(Entity, &mut TabState)>, mut chord_color_background_query: Query<(Entity, &mut ColorBackground), With<ChordColorBackground>>, mut bar_indicator_query: Query<(Entity, &mut BarIndicatorData), With<BarIndicatorData>>, mut pos_indicator_query: Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, mut bar_playing_query: Query<(Entity, &mut BarPlaying), With<BarPlaying>>, mut entry_playing_query: Query< (Entity, &Arc<LaneEntry>, &mut EntryPlaying), With<EntryPlaying>, >, mut chord_playing_query: Query<(Entity, &mut ChordPlaying), With<ChordPlaying>>, mut tab_bars_query: Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, mut beat_query: Query<(Entity, &mut BarBeatData)>, ) { if theme._bypass_systems { return; } for evt in evts.iter() { for (state_entity, mut tab_state) in tab_state_query.iter_mut() { if !tab_state.under_control { continue; } match evt { PlayControlEvent::OnTick { position, tick_result, } => on_tick( &mut commands, &theme, &mut settings, &mut chord_color_background_query, &mut bar_indicator_query, &mut pos_indicator_query, &mut bar_playing_query, &mut entry_playing_query, &mut chord_playing_query, &mut tab_bars_query, state_entity, &mut tab_state, position, tick_result, ), PlayControlEvent::OnPlayState(play_state) => { tab_state.set_play_state(&mut commands, state_entity, *play_state); } PlayControlEvent::OnSpeedFactor(play_speed) => { tab_state.set_speed_factor(*play_speed); } PlayControlEvent::OnBeginEnd(begin_bar_ordinal, end_bar_ordinal) => { tab_state.set_begin_end(*begin_bar_ordinal, *end_bar_ordinal); BarBeatData::update_all(&mut commands, &theme, &tab_state, &mut beat_query); } PlayControlEvent::OnShouldLoop(should_loop) => { tab_state.set_should_loop(*should_loop); } } } } }
ata>>, pos_indicator_query: &mut Query<(Entity, &mut PosIndicatorData), With<PosIndicatorData>>, tab_bars_query: &mut Query<( Entity, &mut Transform, &Arc<TabBars>, &LayoutData, &Arc<GridData>, )>, bar_playing: &BarPlaying, bar_layout: LayoutData, ) { let bar_props = bar_playing.bar_props; let mut in_bar_pos = None; for (entity, mut data) in pos_indicator_query.iter_mut() { data.bar_props = bar_props; data.bar_layout = bar_layout; data.update(commands, &theme, entity); settings .layout .focus_bar(commands, theme, tab_bars_query, &data); in_bar_pos = Some(data.bar_position.in_bar_pos); } for (entity, mut data) in bar_indicator_query.iter_mut() { data.bar_props = bar_props; data.bar_layout = bar_layout; data.update_data(commands, theme, entity, bar_props, bar_layout, in_bar_pos); ChordColorBackground::update_color(commands, theme, chord_color_background_query, data.chord); } }
function_block-function_prefixed
[ { "content": "pub fn add_notation_app_events(app: &mut AppBuilder) {\n\n app.add_event::<WindowResizedEvent>();\n\n app.add_event::<MouseClickedEvent>();\n\n app.add_event::<MouseDraggedEvent>();\n\n}\n", "file_path": "crates/notation_bevy/src/app/app_events.rs", "rank": 0, "score": 255115....
Rust
src/delivery/http/change.rs
chef-boneyard/delivery-cli
ab957f957017798cc11a370a0af57c3334d58bc9
use errors::{DeliveryError, Kind}; use http::*; use hyper::status::StatusCode; use serde_json; use config::Config; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, PartialOrd)] pub struct Description { pub title: String, pub description: String, } impl Description { pub fn payload(title: &str, desc: &str) -> Result<String, DeliveryError> { let desc = Description { title: String::from(title), description: String::from(desc), }; desc.to_json() } pub fn to_json(&self) -> Result<String, DeliveryError> { let payload = serde_json::to_string(&self)?; Ok(payload) } pub fn parse_json(response: &str) -> Result<Description, DeliveryError> { Ok(serde_json::from_str::<Description>(response)?) } pub fn parse_text(text: &str) -> Result<Description, DeliveryError> { let mut iter = text.lines(); let title = iter.find(|&l| !l.trim().is_empty()) .unwrap_or("") .trim() .to_string(); let desc = iter.collect::<Vec<&str>>().join("\n").trim().to_string(); Ok(Description { title: title, description: desc, }) } } pub fn get(config: &Config, change: &str) -> Result<Description, DeliveryError> { let org = try!(config.organization()); let proj = try!(config.project()); let client = try!(APIClient::from_config(&config)); let path = format!( "orgs/{}/projects/{}/changes/{}/description", org, proj, change ); debug!("description path: {}", path); let mut result = try!(client.get(&path)); match result.status { StatusCode::Ok => { let mut body_string = String::new(); let _x = try!(result.read_to_string(&mut body_string)); let description = try!(Description::parse_json(&body_string)); Ok(description) } StatusCode::NotFound => { let msg1 = "API request returned 404 (not found) while trying to fetch this change's description.\n".to_string(); let msg2 = "This is usually because the Delivery organization in your config does not match the organization for this project.\n"; let msg3 = "Your organization is current set to:\n\n"; let msg4 = &org; let msg5 = "\n\nTo fix this, try editing your cli.toml file's organization setting to match the organization this project resides in."; let err_msg = msg1 + msg2 + msg3 + msg4 + msg5; Err(DeliveryError { kind: Kind::ChangeNotFound, detail: Some(err_msg), }) } StatusCode::Unauthorized => { let msg = "API request returned 401 (unauthorized)".to_string(); Err(DeliveryError { kind: Kind::AuthenticationFailed, detail: Some(msg), }) } error_code @ _ => { let msg = format!("API request returned {}", error_code); let mut detail = String::new(); let e = match result.read_to_string(&mut detail) { Ok(_) => Ok(detail), Err(e) => Err(e), }; Err(DeliveryError { kind: Kind::ApiError(error_code, e), detail: Some(msg), }) } } } pub fn set(config: &Config, change: &str, description: &Description) -> Result<(), DeliveryError> { let org = try!(config.organization()); let proj = try!(config.project()); let client = try!(APIClient::from_config(&config)); let path = format!( "orgs/{}/projects/{}/changes/{}/description", org, proj, change ); let payload = try!(description.to_json()); let mut result = try!(client.put(&path, &payload)); match result.status { StatusCode::NoContent => Ok(()), StatusCode::Unauthorized => { let msg = "API request returned 401".to_string(); Err(DeliveryError { kind: Kind::AuthenticationFailed, detail: Some(msg), }) } error_code @ _ => { let msg = format!("API request returned {}", error_code); let mut detail = String::new(); let e = result.read_to_string(&mut detail).and(Ok(detail)); Err(DeliveryError::throw( Kind::ApiError(error_code, e), Some(msg), )) } } } #[cfg(test)] mod tests { use super::*; #[test] fn description_payload_test() { let payload = Description::payload("a title", "so descriptive!"); let expect = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; assert_eq!(expect, payload.unwrap()); } #[test] fn description_to_json_test() { let desc = Description { title: "a title".to_string(), description: "so descriptive!".to_string(), }; let payload = desc.to_json().unwrap(); let expect = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; assert_eq!(expect, payload); } #[test] fn description_parse_json_test() { let response = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; let expect = Description { title: "a title".to_string(), description: "so descriptive!".to_string(), }; let description = Description::parse_json(response).unwrap(); assert_eq!(expect, description); } #[test] fn description_parse_text_1_test() { let text = "Just a title"; let expect = Description { title: text.to_string(), description: "".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_2_test() { let text = "Just a title\n\nWith some description"; let expect = Description { title: "Just a title".to_string(), description: "With some description".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_3_test() { let text = "Just a title\n\nL1\nL2\nL3\n"; let expect = Description { title: "Just a title".to_string(), description: "L1\nL2\nL3".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_4_test() { let text = "\n \nA title after some blank lines\n \nL1\nL2\nL3\n"; let expect = Description { title: "A title after some blank lines".to_string(), description: "L1\nL2\nL3".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } }
use errors::{DeliveryError, Kind}; use http::*; use hyper::status::StatusCode; use serde_json; use config::Config; #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, PartialOrd)] pub struct Description { pub title: String, pub description: String, } impl Description { pub fn payload(title: &str, desc: &str) -> Result<String, DeliveryError> { let desc = Description { title: String::from(title), description: String::from(desc), }; desc.to_json() } pub fn to_json(&self) -> Result<String, DeliveryError> { let payload = serde_json::to_string(&self)?; Ok(payload) } pub fn parse_json(response: &str)
t.read_to_string(&mut detail).and(Ok(detail)); Err(DeliveryError::throw( Kind::ApiError(error_code, e), Some(msg), )) } } } #[cfg(test)] mod tests { use super::*; #[test] fn description_payload_test() { let payload = Description::payload("a title", "so descriptive!"); let expect = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; assert_eq!(expect, payload.unwrap()); } #[test] fn description_to_json_test() { let desc = Description { title: "a title".to_string(), description: "so descriptive!".to_string(), }; let payload = desc.to_json().unwrap(); let expect = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; assert_eq!(expect, payload); } #[test] fn description_parse_json_test() { let response = "{\"title\":\"a title\",\"description\":\"so descriptive!\"}"; let expect = Description { title: "a title".to_string(), description: "so descriptive!".to_string(), }; let description = Description::parse_json(response).unwrap(); assert_eq!(expect, description); } #[test] fn description_parse_text_1_test() { let text = "Just a title"; let expect = Description { title: text.to_string(), description: "".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_2_test() { let text = "Just a title\n\nWith some description"; let expect = Description { title: "Just a title".to_string(), description: "With some description".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_3_test() { let text = "Just a title\n\nL1\nL2\nL3\n"; let expect = Description { title: "Just a title".to_string(), description: "L1\nL2\nL3".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } #[test] fn description_parse_text_4_test() { let text = "\n \nA title after some blank lines\n \nL1\nL2\nL3\n"; let expect = Description { title: "A title after some blank lines".to_string(), description: "L1\nL2\nL3".to_string(), }; let desc = Description::parse_text(text).unwrap(); assert_eq!(expect, desc); } }
-> Result<Description, DeliveryError> { Ok(serde_json::from_str::<Description>(response)?) } pub fn parse_text(text: &str) -> Result<Description, DeliveryError> { let mut iter = text.lines(); let title = iter.find(|&l| !l.trim().is_empty()) .unwrap_or("") .trim() .to_string(); let desc = iter.collect::<Vec<&str>>().join("\n").trim().to_string(); Ok(Description { title: title, description: desc, }) } } pub fn get(config: &Config, change: &str) -> Result<Description, DeliveryError> { let org = try!(config.organization()); let proj = try!(config.project()); let client = try!(APIClient::from_config(&config)); let path = format!( "orgs/{}/projects/{}/changes/{}/description", org, proj, change ); debug!("description path: {}", path); let mut result = try!(client.get(&path)); match result.status { StatusCode::Ok => { let mut body_string = String::new(); let _x = try!(result.read_to_string(&mut body_string)); let description = try!(Description::parse_json(&body_string)); Ok(description) } StatusCode::NotFound => { let msg1 = "API request returned 404 (not found) while trying to fetch this change's description.\n".to_string(); let msg2 = "This is usually because the Delivery organization in your config does not match the organization for this project.\n"; let msg3 = "Your organization is current set to:\n\n"; let msg4 = &org; let msg5 = "\n\nTo fix this, try editing your cli.toml file's organization setting to match the organization this project resides in."; let err_msg = msg1 + msg2 + msg3 + msg4 + msg5; Err(DeliveryError { kind: Kind::ChangeNotFound, detail: Some(err_msg), }) } StatusCode::Unauthorized => { let msg = "API request returned 401 (unauthorized)".to_string(); Err(DeliveryError { kind: Kind::AuthenticationFailed, detail: Some(msg), }) } error_code @ _ => { let msg = format!("API request returned {}", error_code); let mut detail = String::new(); let e = match result.read_to_string(&mut detail) { Ok(_) => Ok(detail), Err(e) => Err(e), }; Err(DeliveryError { kind: Kind::ApiError(error_code, e), detail: Some(msg), }) } } } pub fn set(config: &Config, change: &str, description: &Description) -> Result<(), DeliveryError> { let org = try!(config.organization()); let proj = try!(config.project()); let client = try!(APIClient::from_config(&config)); let path = format!( "orgs/{}/projects/{}/changes/{}/description", org, proj, change ); let payload = try!(description.to_json()); let mut result = try!(client.put(&path, &payload)); match result.status { StatusCode::NoContent => Ok(()), StatusCode::Unauthorized => { let msg = "API request returned 401".to_string(); Err(DeliveryError { kind: Kind::AuthenticationFailed, detail: Some(msg), }) } error_code @ _ => { let msg = format!("API request returned {}", error_code); let mut detail = String::new(); let e = resul
random
[ { "content": "/// Request an API token for a user from a Delivery server.\n\npub fn request(config: &Config, pass: &str) -> Result<String, DeliveryError> {\n\n let client = try!(APIClient::from_config_no_auth(config));\n\n let user = try!(config.user());\n\n let payload = try!(TokenRequest::payload(&us...
Rust
mutagen-core/src/transformer/arg_ast.rs
alarsyo/mutagen
f8249256c40769c916b5b00bd284f204d5540588
use proc_macro2::{Delimiter, TokenStream, TokenTree}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgAstList(pub Vec<ArgAst>); #[derive(Debug, Eq, PartialEq, Clone)] pub enum ArgAst { ArgFn(ArgFn), ArgEq(ArgEq), } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgFn { pub name: String, pub args: ArgAstList, } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgEq { pub name: String, pub val: ArgFn, } impl ArgAstList { pub fn parse_list(input: TokenStream) -> Result<Self, ()> { let mut args = Vec::new(); let mut tt_iter = input.into_iter(); while let Some(next) = tt_iter.next() { let name = if let TokenTree::Ident(next) = next { next.to_string() } else if let TokenTree::Literal(next) = next { next.to_string() } else { return Err(()); }; args.push(ArgAst::parse_single(name, &mut tt_iter)?); } Ok(Self(args)) } pub fn find_named_arg(&self, name: &str) -> Result<Option<&ArgFn>, ()> { let named_args = self .0 .iter() .filter(|ast| ast.name() == name) .map(|ast| Ok(&ast.expect_eq_ref()?.val)) .collect::<Result<Vec<&ArgFn>, ()>>()?; if named_args.len() > 1 { return Err(()); } Ok(named_args.get(0).copied()) } } impl ArgAst { fn new_fn(name: String, args: ArgAstList) -> Self { Self::ArgFn(ArgFn::new(name, args)) } fn new_eq(name: String, val: ArgFn) -> Self { Self::ArgEq(ArgEq::new(name, val)) } pub fn name(&self) -> &str { match self { ArgAst::ArgFn(ArgFn { name, .. }) => name, ArgAst::ArgEq(ArgEq { name, .. }) => name, } } fn parse_single( name: String, tt_iter: &mut impl Iterator<Item = TokenTree>, ) -> Result<Self, ()> { match tt_iter.next() { None => return Ok(Self::new_fn(name, ArgAstList(vec![]))), Some(TokenTree::Group(g)) => { if g.delimiter() != Delimiter::Parenthesis { return Err(()); } let args = ArgAstList::parse_list(g.stream())?; tt_expect_comma_or_end(tt_iter)?; return Ok(Self::new_fn(name, args)); } Some(TokenTree::Punct(p)) => { if p.as_char() == ',' { return Ok(Self::new_fn(name, ArgAstList(vec![]))); } if p.as_char() != '=' { return Err(()); } let next = tt_iter.next(); let next = if let Some(TokenTree::Ident(next)) = next { next.to_string() } else if let Some(TokenTree::Literal(next)) = next { next.to_string() } else { return Err(()); }; let val = Self::parse_single(next, tt_iter)?.expect_fn()?; return Ok(Self::new_eq(name, val)); } _ => return Err(()), } } pub fn expect_fn(self) -> Result<ArgFn, ()> { match self { ArgAst::ArgFn(f) => Ok(f), ArgAst::ArgEq(_) => Err(()), } } pub fn expect_fn_ref(&self) -> Result<&ArgFn, ()> { match self { ArgAst::ArgFn(f) => Ok(f), ArgAst::ArgEq(_) => Err(()), } } pub fn expect_eq_ref(&self) -> Result<&ArgEq, ()> { match self { ArgAst::ArgFn(_) => Err(()), ArgAst::ArgEq(e) => Ok(e), } } } fn tt_expect_comma_or_end(tt_iter: &mut impl Iterator<Item = TokenTree>) -> Result<(), ()> { match tt_iter.next() { None => {} Some(TokenTree::Punct(p)) => { if p.as_char() != ',' { return Err(()); } } _ => return Err(()), } Ok(()) } impl ArgFn { pub fn new(name: String, args: ArgAstList) -> Self { Self { name, args } } } impl ArgEq { pub fn new(name: String, val: ArgFn) -> Self { Self { name, val } } } #[cfg(test)] mod tests { use super::*; use proc_macro2::TokenStream; use std::str::FromStr; #[test] fn no_args() { let input = TokenStream::new(); let parsed = ArgAstList::parse_list(input); assert_eq!(parsed, Ok(ArgAstList(vec![]))); } #[test] fn single_arg() { let input = TokenStream::from_str("a1").unwrap(); let parsed = ArgAstList::parse_list(input); let expected = ArgAst::new_fn("a1".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_int() { let input = TokenStream::from_str("1").unwrap(); let parsed = ArgAstList::parse_list(input); let expected = ArgAst::new_fn("1".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_args() { let input = TokenStream::from_str("a2(x, y, z)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected .args .0 .push(ArgAst::new_fn("x".to_string(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_fn("y".to_string(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_fn("z".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_trailing_comma() { let input = TokenStream::from_str("a2(x,)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected .args .0 .push(ArgAst::new_fn("x".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_eq_args() { let input = TokenStream::from_str("a2(x=a)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected.args.0.push(ArgAst::new_eq( "x".to_string(), ArgFn::new("a".to_owned(), ArgAstList(vec![])), )); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn chained_eq_gives_error() { let input = TokenStream::from_str("a = b = c").unwrap(); let parsed = ArgAstList::parse_list(input); assert_eq!(parsed, Err(())); } #[test] fn multiple_args() { let input = TokenStream::from_str("a2, b5").unwrap(); let parsed = ArgAstList::parse_list(input); let expected1 = ArgAst::new_fn("a2".to_string(), ArgAstList(vec![])); let expected2 = ArgAst::new_fn("b5".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected1, expected2]))); } #[test] fn nested_args() { let input = TokenStream::from_str("g55(h3(X))").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("g55".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("h3".to_string(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("X".to_string(), ArgAstList(vec![]))); expected.args.0.push(ArgAst::ArgFn(expected1)); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn nested_args_with_trailing_arg() { let input = TokenStream::from_str("g55(h3(X), z)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("g55".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("h3".to_string(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("X".to_string(), ArgAstList(vec![]))); expected.args.0.push(ArgAst::ArgFn(expected1)); expected .args .0 .push(ArgAst::new_fn("z".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_eq_args_nested() { let input = TokenStream::from_str("a2(x=a(b))").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("a".to_owned(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("b".to_owned(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_eq("x".to_string(), expected1)); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn list_of_eq_args() { let input = TokenStream::from_str("x = a, y = b").unwrap(); let parsed = ArgAstList::parse_list(input); let expected1 = ArgEq::new( "x".to_string(), ArgFn::new("a".to_owned(), ArgAstList(vec![])), ); let expected2 = ArgEq::new( "y".to_string(), ArgFn::new("b".to_owned(), ArgAstList(vec![])), ); let expected = ArgAstList(vec![ArgAst::ArgEq(expected1), ArgAst::ArgEq(expected2)]); assert_eq!(parsed, Ok(expected)); } }
use proc_macro2::{Delimiter, TokenStream, TokenTree}; #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgAstList(pub Vec<ArgAst>); #[derive(Debug, Eq, PartialEq, Clone)] pub enum ArgAst { ArgFn(ArgFn), ArgEq(ArgEq), } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgFn { pub name: String, pub args: ArgAstList, } #[derive(Debug, Eq, PartialEq, Clone)] pub struct ArgEq { pub name: String, pub val: ArgFn, } impl ArgAstList { pub fn parse_list(input: TokenStream) -> Result<Self, ()> { let mut args = Vec::new(); let mut tt_iter = input.into_iter(); while let Some(next) = tt_iter.next() { let name = if let TokenTree::Ident(next) = next { next.to_string() } else if let TokenTree::Literal(next) = next { next.to_string() } else { return Err(()); }; args.push(ArgAst::parse_single(name, &mut tt_iter)?); } Ok(Self(args)) } pub fn find_named_arg(&self, name: &str) -> Result<Option<&ArgFn>, ()> { let named_args = self .0 .iter() .filter(|ast| ast.name() == name) .map(|ast| Ok(&ast.expect_eq_ref()?.val)) .collect::<Result<Vec<&ArgFn>, ()>>()?; if named_args.len() > 1 { return Err(()); } Ok(named_args.get(0).copied()) } } impl ArgAst { fn new_fn(name: String, args: ArgAstList) -> Self { Self::ArgFn(ArgFn::new(name, args)) } fn new_eq(name: String, val: ArgFn) -> Self { Self::ArgEq(ArgEq::new(name, val)) } pub fn name(&self) -> &str { match self { ArgAst::ArgFn(ArgFn { name, .. }) => name, ArgAst::ArgEq(ArgEq { name, .. }) => name, } } fn parse_single( name: String, tt_iter: &mut impl Iterator<Item = TokenTree>, ) -> Result<Self, ()> { match tt_iter.next() { None => return Ok(Self::new_fn(name, ArgAstList(vec![]))), Some(TokenTree::Group(g)) => { if g.delimiter() != Delimiter::Parenthesis { return Err(()); } let args = ArgAstList::parse_list(g.stream())?; tt_expect_comma_or_end(tt_iter)?; return Ok(Self::new_fn(name, args)); } Some(TokenTree::Punct(p)) => { if p.as_char() == ',' { return Ok(Self::new_fn(name, ArgAstList(vec![]))); } if p.as_char() != '=' { return Err(()); } let next = tt_iter.next(); let next = if let Some(TokenTree::Ident(next)) = next { next.to_string() } else if let Some(TokenTree::Literal(next)) = next { next.to_string() } else { return Err(()); }; let val = Self::parse_single(next, tt_iter)?.expect_fn()?; return Ok(Self::new_eq(name, val)); } _ => return Err(()), } } pub fn expect_fn(self) -> Result<ArgFn, ()> { match self { ArgAst::ArgFn(f) => Ok(f), ArgAst::ArgEq(_) => Err(()), } } pub fn expect_fn_ref(&self) -> Result<&ArgFn, ()> { match self { ArgAst::ArgFn(f) => Ok(f), ArgAst::ArgEq(_) => Err(()), } } pub fn expect_eq_ref(&self) -> Result<&ArgEq, ()> { match self { ArgAst::ArgFn(_) => Err(()), ArgAst::ArgEq(e) => Ok(e), } } } fn tt_expect_comma_or_end(tt_iter: &mut impl Iterator<Item = TokenTree>) -> Result<(), ()> { match tt_iter.next() { None => {} Some(TokenTree::Punct(p)) => { if p.as_char() != ',' { return Err(()); } } _ => return Err(()), } Ok(()) } impl ArgFn { pub fn new(name: String, args: ArgAstList) -> Self { Self { name, args } } } impl ArgEq { pub fn new(name: String, val: ArgFn) -> Self { Self { name, val } } } #[cfg(test)] mod tests { use super::*; use proc_macro2::TokenStream; use std::str::FromStr; #[test] fn no_args() { let input = TokenStream::new(); let parsed = ArgAstList::parse_list(input); assert_eq!(parsed, Ok(ArgAstList(vec![]))); } #[test] fn single_arg() { let input = TokenStream::from_str("a1").unwrap(); let parsed = ArgAstList::parse_list(input); let expected = ArgAst::new_fn("a1".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_int() { let input = TokenStream::from_str("1").unwrap(); let parsed = ArgAstList::parse_list(input); let expected = ArgAst::new_fn("1".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_args() { let input = TokenStream::from_str("a2(x, y, z)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected .args .0 .push(ArgAst::new_fn("x".to_string(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_fn("y".to_string(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_fn("z".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_trailing_comma() { let input = TokenStream::from_str("a2(x,)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected .args .0 .push(ArgAst::new_fn("x".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_eq_args() { let input = TokenStream::from_str("a2(x=a)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); expected.args.0.push(ArgAst::new_eq( "x".to_string(), ArgFn::new("a".to_owned(), ArgAstList(vec![])), )); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn chained_eq_gives_error() { let input = TokenStream::from_str("a = b = c").unwrap(); let parsed = ArgAstList::parse_list(input); assert_eq!(parsed, Err(())); } #[test] fn multiple_args() { let input = TokenStream::from_str("a2, b5").unwrap(); let parsed = ArgAstList::parse_list(input); let expected1 = ArgAst::new_fn("a2".to_string(), ArgAstList(vec![])); let expected2 = ArgAst::new_fn("b5".to_string(), ArgAstList(vec![])); assert_eq!(parsed, Ok(ArgAstList(vec![expected1, expected2]))); } #[test] fn nested_args() { let input = TokenStream::from_str("g55(h3(X))").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("g55".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("h3".to_string(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("X".to_string(), ArgAstList(vec![])));
#[test] fn nested_args_with_trailing_arg() { let input = TokenStream::from_str("g55(h3(X), z)").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("g55".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("h3".to_string(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("X".to_string(), ArgAstList(vec![]))); expected.args.0.push(ArgAst::ArgFn(expected1)); expected .args .0 .push(ArgAst::new_fn("z".to_string(), ArgAstList(vec![]))); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn single_arg_with_eq_args_nested() { let input = TokenStream::from_str("a2(x=a(b))").unwrap(); let parsed = ArgAstList::parse_list(input); let mut expected = ArgFn::new("a2".to_string(), ArgAstList(vec![])); let mut expected1 = ArgFn::new("a".to_owned(), ArgAstList(vec![])); expected1 .args .0 .push(ArgAst::new_fn("b".to_owned(), ArgAstList(vec![]))); expected .args .0 .push(ArgAst::new_eq("x".to_string(), expected1)); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); } #[test] fn list_of_eq_args() { let input = TokenStream::from_str("x = a, y = b").unwrap(); let parsed = ArgAstList::parse_list(input); let expected1 = ArgEq::new( "x".to_string(), ArgFn::new("a".to_owned(), ArgAstList(vec![])), ); let expected2 = ArgEq::new( "y".to_string(), ArgFn::new("b".to_owned(), ArgAstList(vec![])), ); let expected = ArgAstList(vec![ArgAst::ArgEq(expected1), ArgAst::ArgEq(expected2)]); assert_eq!(parsed, Ok(expected)); } }
expected.args.0.push(ArgAst::ArgFn(expected1)); let expected = ArgAst::ArgFn(expected); assert_eq!(parsed, Ok(ArgAstList(vec![expected]))); }
function_block-function_prefix_line
[ { "content": "pub fn do_transform_item(args: TokenStream, input: TokenStream) -> TokenStream {\n\n let input = match syn::parse2::<syn::Item>(input) {\n\n Ok(ast) => ast,\n\n Err(e) => return TokenStream::from(e.to_compile_error()),\n\n };\n\n MutagenTransformerBundle::setup_from_attr(arg...
Rust
interface/rust/src/kubernetes_applier.rs
cosmonic/kubernetes-applier
693bbe6f53d42de0bf9a738a8c23f8699538732b
#[allow(unused_imports)] use async_trait::async_trait; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString}; #[allow(unused_imports)] use wasmbus_rpc::{ cbor::*, common::{ deserialize, message_format, serialize, Context, Message, MessageDispatch, MessageFormat, SendOpts, Transport, }, error::{RpcError, RpcResult}, Timestamp, }; pub const SMITHY_VERSION: &str = "1.0"; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct DeleteRequest { #[serde(default)] pub group: String, #[serde(default)] pub kind: String, #[serde(default)] pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub namespace: Option<String>, #[serde(default)] pub version: String, } #[doc(hidden)] pub fn encode_delete_request<W: wasmbus_rpc::cbor::Write>( e: &mut wasmbus_rpc::cbor::Encoder<W>, val: &DeleteRequest, ) -> RpcResult<()> { e.map(5)?; e.str("group")?; e.str(&val.group)?; e.str("kind")?; e.str(&val.kind)?; e.str("name")?; e.str(&val.name)?; if let Some(val) = val.namespace.as_ref() { e.str("namespace")?; e.str(val)?; } else { e.null()?; } e.str("version")?; e.str(&val.version)?; Ok(()) } #[doc(hidden)] pub fn decode_delete_request( d: &mut wasmbus_rpc::cbor::Decoder<'_>, ) -> Result<DeleteRequest, RpcError> { let __result = { let mut group: Option<String> = None; let mut kind: Option<String> = None; let mut name: Option<String> = None; let mut namespace: Option<Option<String>> = Some(None); let mut version: Option<String> = None; let is_array = match d.datatype()? { wasmbus_rpc::cbor::Type::Array => true, wasmbus_rpc::cbor::Type::Map => false, _ => { return Err(RpcError::Deser( "decoding struct DeleteRequest, expected array or map".to_string(), )) } }; if is_array { let len = d.array()?.ok_or_else(|| { RpcError::Deser( "decoding struct DeleteRequest: indefinite array not supported".to_string(), ) })?; for __i in 0..(len as usize) { match __i { 0 => group = Some(d.str()?.to_string()), 1 => kind = Some(d.str()?.to_string()), 2 => name = Some(d.str()?.to_string()), 3 => { namespace = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } 4 => version = Some(d.str()?.to_string()), _ => d.skip()?, } } } else { let len = d.map()?.ok_or_else(|| { RpcError::Deser( "decoding struct DeleteRequest: indefinite map not supported".to_string(), ) })?; for __i in 0..(len as usize) { match d.str()? { "group" => group = Some(d.str()?.to_string()), "kind" => kind = Some(d.str()?.to_string()), "name" => name = Some(d.str()?.to_string()), "namespace" => { namespace = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } "version" => version = Some(d.str()?.to_string()), _ => d.skip()?, } } } DeleteRequest { group: if let Some(__x) = group { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.group (#0)".to_string(), )); }, kind: if let Some(__x) = kind { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.kind (#1)".to_string(), )); }, name: if let Some(__x) = name { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.name (#2)".to_string(), )); }, namespace: namespace.unwrap(), version: if let Some(__x) = version { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.version (#4)".to_string(), )); }, } }; Ok(__result) } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct OperationResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<String>, #[serde(default)] pub succeeded: bool, } #[doc(hidden)] pub fn encode_operation_response<W: wasmbus_rpc::cbor::Write>( e: &mut wasmbus_rpc::cbor::Encoder<W>, val: &OperationResponse, ) -> RpcResult<()> { e.map(2)?; if let Some(val) = val.error.as_ref() { e.str("error")?; e.str(val)?; } else { e.null()?; } e.str("succeeded")?; e.bool(val.succeeded)?; Ok(()) } #[doc(hidden)] pub fn decode_operation_response( d: &mut wasmbus_rpc::cbor::Decoder<'_>, ) -> Result<OperationResponse, RpcError> { let __result = { let mut error: Option<Option<String>> = Some(None); let mut succeeded: Option<bool> = None; let is_array = match d.datatype()? { wasmbus_rpc::cbor::Type::Array => true, wasmbus_rpc::cbor::Type::Map => false, _ => { return Err(RpcError::Deser( "decoding struct OperationResponse, expected array or map".to_string(), )) } }; if is_array { let len = d.array()?.ok_or_else(|| { RpcError::Deser( "decoding struct OperationResponse: indefinite array not supported".to_string(), ) })?; for __i in 0..(len as usize) { match __i { 0 => { error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } 1 => succeeded = Some(d.bool()?), _ => d.skip()?, } } } else { let len = d.map()?.ok_or_else(|| { RpcError::Deser( "decoding struct OperationResponse: indefinite map not supported".to_string(), ) })?; for __i in 0..(len as usize) { match d.str()? { "error" => { error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } "succeeded" => succeeded = Some(d.bool()?), _ => d.skip()?, } } } OperationResponse { error: error.unwrap(), succeeded: if let Some(__x) = succeeded { __x } else { return Err(RpcError::Deser( "missing field OperationResponse.succeeded (#1)".to_string(), )); }, } }; Ok(__result) } #[async_trait] pub trait KubernetesApplier { fn contract_id() -> &'static str { "cosmonic:kubernetes_applier" } async fn apply(&self, ctx: &Context, arg: &Vec<u8>) -> RpcResult<OperationResponse>; async fn delete(&self, ctx: &Context, arg: &DeleteRequest) -> RpcResult<OperationResponse>; } #[doc(hidden)] #[async_trait] pub trait KubernetesApplierReceiver: MessageDispatch + KubernetesApplier { async fn dispatch<'disp__, 'ctx__, 'msg__>( &'disp__ self, ctx: &'ctx__ Context, message: &Message<'msg__>, ) -> Result<Message<'msg__>, RpcError> { match message.method { "Apply" => { let value: Vec<u8> = wasmbus_rpc::common::deserialize(&message.arg) .map_err(|e| RpcError::Deser(format!("'Blob': {}", e)))?; let resp = KubernetesApplier::apply(self, ctx, &value).await?; let buf = wasmbus_rpc::common::serialize(&resp)?; Ok(Message { method: "KubernetesApplier.Apply", arg: Cow::Owned(buf), }) } "Delete" => { let value: DeleteRequest = wasmbus_rpc::common::deserialize(&message.arg) .map_err(|e| RpcError::Deser(format!("'DeleteRequest': {}", e)))?; let resp = KubernetesApplier::delete(self, ctx, &value).await?; let buf = wasmbus_rpc::common::serialize(&resp)?; Ok(Message { method: "KubernetesApplier.Delete", arg: Cow::Owned(buf), }) } _ => Err(RpcError::MethodNotHandled(format!( "KubernetesApplier::{}", message.method ))), } } } #[derive(Debug)] pub struct KubernetesApplierSender<T: Transport> { transport: T, } impl<T: Transport> KubernetesApplierSender<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 KubernetesApplierSender<wasmbus_rpc::actor::prelude::WasmHost> { pub fn new() -> Self { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider( "cosmonic:kubernetes_applier", "default", ) .unwrap(); Self { transport } } pub fn new_with_link(link_name: &str) -> wasmbus_rpc::error::RpcResult<Self> { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider( "cosmonic:kubernetes_applier", link_name, )?; Ok(Self { transport }) } } #[async_trait] impl<T: Transport + std::marker::Sync + std::marker::Send> KubernetesApplier for KubernetesApplierSender<T> { #[allow(unused)] async fn apply(&self, ctx: &Context, arg: &Vec<u8>) -> RpcResult<OperationResponse> { let buf = wasmbus_rpc::common::serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "KubernetesApplier.Apply", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value: OperationResponse = wasmbus_rpc::common::deserialize(&resp) .map_err(|e| RpcError::Deser(format!("'{}': OperationResponse", e)))?; Ok(value) } #[allow(unused)] async fn delete(&self, ctx: &Context, arg: &DeleteRequest) -> RpcResult<OperationResponse> { let buf = wasmbus_rpc::common::serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "KubernetesApplier.Delete", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value: OperationResponse = wasmbus_rpc::common::deserialize(&resp) .map_err(|e| RpcError::Deser(format!("'{}': OperationResponse", e)))?; Ok(value) } }
#[allow(unused_imports)] use async_trait::async_trait; #[allow(unused_imports)] use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use std::{borrow::Borrow, borrow::Cow, io::Write, string::ToString}; #[allow(unused_imports)] use wasmbus_rpc::{ cbor::*, common::{ deserialize, message_format, serialize, Context, Message, MessageDispatch, MessageFormat, SendOpts, Transport, }, error::{RpcError, RpcResult}, Timestamp, }; pub const SMITHY_VERSION: &str = "1.0"; #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct DeleteRequest { #[serde(default)] pub group: String, #[serde(default)] pub kind: String, #[serde(default)] pub name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub namespace: Option<String>, #[serde(default)] pub version: String, } #[doc(hidden)] pub fn encode_delete_request<W: wasmbus_rpc::cbor::Write>( e: &mut wasmbus_rpc::cbor::Encoder<W>, val: &DeleteRequest, ) -> RpcResult<()> { e.map(5)?; e.str("group")?; e.str(&val.group)?; e.str("kind")?; e.str(&val.kind)?; e.str("name")?; e.str(&val.name)?; if let Some(val) = val.namespace.as_ref() { e.str("namespace")?; e.str(val)?; } else { e.null()?; } e.str("version")?; e.str(&val.version)?; Ok(()) } #[doc(hidden)] pub fn decode_delete_request( d: &mut wasmbus_rpc::cbor::Decoder<'_>, ) -> Result<DeleteRequest, RpcError> { let __result = { let mut group: Option<String> = None; let mut kind: Option<String> = None; let mut name: Option<String> = None; let mut namespace: Option<Option<String>> = Some(None); let mut version: Option<String> = None; let is_array = match d.datatype()? { wasmbus_rpc::cbor::Type::Array => true, wasmbus_rpc::cbor::Type::Map => false, _ => { return Err(RpcError::Deser( "decoding struct DeleteRequest, expected array or map".to_string(), )) } }; if is_array { let len = d.array()?.ok_or_else(|| { RpcError::Deser( "decoding struct DeleteRequest: indefinite array not supported".to_string(), ) })?; for __i in 0..(len as usize) { match __i { 0 => group = Some(d.str()?.to_string()), 1 => kind = Some(d.str()?.to_string()), 2 => name = Some(d.str()?.to_string()), 3 => { namespace = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } 4 => version = Some(d.str()?.to_string()), _ => d.skip()?, } } } else { let len = d.map()?.ok_or_else(|| { RpcError::Deser( "decoding struct DeleteRequest: indefinite map not supported".to_string(), ) })?; for __i in 0..(len as usize) {
} } DeleteRequest { group: if let Some(__x) = group { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.group (#0)".to_string(), )); }, kind: if let Some(__x) = kind { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.kind (#1)".to_string(), )); }, name: if let Some(__x) = name { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.name (#2)".to_string(), )); }, namespace: namespace.unwrap(), version: if let Some(__x) = version { __x } else { return Err(RpcError::Deser( "missing field DeleteRequest.version (#4)".to_string(), )); }, } }; Ok(__result) } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct OperationResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<String>, #[serde(default)] pub succeeded: bool, } #[doc(hidden)] pub fn encode_operation_response<W: wasmbus_rpc::cbor::Write>( e: &mut wasmbus_rpc::cbor::Encoder<W>, val: &OperationResponse, ) -> RpcResult<()> { e.map(2)?; if let Some(val) = val.error.as_ref() { e.str("error")?; e.str(val)?; } else { e.null()?; } e.str("succeeded")?; e.bool(val.succeeded)?; Ok(()) } #[doc(hidden)] pub fn decode_operation_response( d: &mut wasmbus_rpc::cbor::Decoder<'_>, ) -> Result<OperationResponse, RpcError> { let __result = { let mut error: Option<Option<String>> = Some(None); let mut succeeded: Option<bool> = None; let is_array = match d.datatype()? { wasmbus_rpc::cbor::Type::Array => true, wasmbus_rpc::cbor::Type::Map => false, _ => { return Err(RpcError::Deser( "decoding struct OperationResponse, expected array or map".to_string(), )) } }; if is_array { let len = d.array()?.ok_or_else(|| { RpcError::Deser( "decoding struct OperationResponse: indefinite array not supported".to_string(), ) })?; for __i in 0..(len as usize) { match __i { 0 => { error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } 1 => succeeded = Some(d.bool()?), _ => d.skip()?, } } } else { let len = d.map()?.ok_or_else(|| { RpcError::Deser( "decoding struct OperationResponse: indefinite map not supported".to_string(), ) })?; for __i in 0..(len as usize) { match d.str()? { "error" => { error = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } "succeeded" => succeeded = Some(d.bool()?), _ => d.skip()?, } } } OperationResponse { error: error.unwrap(), succeeded: if let Some(__x) = succeeded { __x } else { return Err(RpcError::Deser( "missing field OperationResponse.succeeded (#1)".to_string(), )); }, } }; Ok(__result) } #[async_trait] pub trait KubernetesApplier { fn contract_id() -> &'static str { "cosmonic:kubernetes_applier" } async fn apply(&self, ctx: &Context, arg: &Vec<u8>) -> RpcResult<OperationResponse>; async fn delete(&self, ctx: &Context, arg: &DeleteRequest) -> RpcResult<OperationResponse>; } #[doc(hidden)] #[async_trait] pub trait KubernetesApplierReceiver: MessageDispatch + KubernetesApplier { async fn dispatch<'disp__, 'ctx__, 'msg__>( &'disp__ self, ctx: &'ctx__ Context, message: &Message<'msg__>, ) -> Result<Message<'msg__>, RpcError> { match message.method { "Apply" => { let value: Vec<u8> = wasmbus_rpc::common::deserialize(&message.arg) .map_err(|e| RpcError::Deser(format!("'Blob': {}", e)))?; let resp = KubernetesApplier::apply(self, ctx, &value).await?; let buf = wasmbus_rpc::common::serialize(&resp)?; Ok(Message { method: "KubernetesApplier.Apply", arg: Cow::Owned(buf), }) } "Delete" => { let value: DeleteRequest = wasmbus_rpc::common::deserialize(&message.arg) .map_err(|e| RpcError::Deser(format!("'DeleteRequest': {}", e)))?; let resp = KubernetesApplier::delete(self, ctx, &value).await?; let buf = wasmbus_rpc::common::serialize(&resp)?; Ok(Message { method: "KubernetesApplier.Delete", arg: Cow::Owned(buf), }) } _ => Err(RpcError::MethodNotHandled(format!( "KubernetesApplier::{}", message.method ))), } } } #[derive(Debug)] pub struct KubernetesApplierSender<T: Transport> { transport: T, } impl<T: Transport> KubernetesApplierSender<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 KubernetesApplierSender<wasmbus_rpc::actor::prelude::WasmHost> { pub fn new() -> Self { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider( "cosmonic:kubernetes_applier", "default", ) .unwrap(); Self { transport } } pub fn new_with_link(link_name: &str) -> wasmbus_rpc::error::RpcResult<Self> { let transport = wasmbus_rpc::actor::prelude::WasmHost::to_provider( "cosmonic:kubernetes_applier", link_name, )?; Ok(Self { transport }) } } #[async_trait] impl<T: Transport + std::marker::Sync + std::marker::Send> KubernetesApplier for KubernetesApplierSender<T> { #[allow(unused)] async fn apply(&self, ctx: &Context, arg: &Vec<u8>) -> RpcResult<OperationResponse> { let buf = wasmbus_rpc::common::serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "KubernetesApplier.Apply", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value: OperationResponse = wasmbus_rpc::common::deserialize(&resp) .map_err(|e| RpcError::Deser(format!("'{}': OperationResponse", e)))?; Ok(value) } #[allow(unused)] async fn delete(&self, ctx: &Context, arg: &DeleteRequest) -> RpcResult<OperationResponse> { let buf = wasmbus_rpc::common::serialize(arg)?; let resp = self .transport .send( ctx, Message { method: "KubernetesApplier.Delete", arg: Cow::Borrowed(&buf), }, None, ) .await?; let value: OperationResponse = wasmbus_rpc::common::deserialize(&resp) .map_err(|e| RpcError::Deser(format!("'{}': OperationResponse", e)))?; Ok(value) } }
match d.str()? { "group" => group = Some(d.str()?.to_string()), "kind" => kind = Some(d.str()?.to_string()), "name" => name = Some(d.str()?.to_string()), "namespace" => { namespace = if wasmbus_rpc::cbor::Type::Null == d.datatype()? { d.skip()?; Some(None) } else { Some(Some(d.str()?.to_string())) } } "version" => version = Some(d.str()?.to_string()), _ => d.skip()?, }
if_condition
[ { "content": "fn ensure_no_path(item: &Option<String>, entity: &str, name: &str) -> Result<(), RpcError> {\n\n if item.is_some() {\n\n return Err(RpcError::ProviderInit(format!(\n\n \"{} {} {}\",\n\n CERT_PATH_ERROR, entity, name\n\n )));\n\n }\n\n Ok(())\n\n}\n", ...
Rust
src/command.rs
mwyrebski/drawerrs
1fc30e533f6af3e8435b5e763149d5c4643a77d0
use crate::canvas::Point; #[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Command { Line { from: Point, to: Point }, Rectangle { p1: Point, p2: Point }, Circle { p: Point, r: usize }, Canvas { width: usize, height: usize }, Char(char), Read(String), Save(String), Info, Show, Quit, } fn try_parse_usize(s: &str) -> Result<usize, String> { s.parse::<usize>().map_err(|e| e.to_string()) } impl Command { pub fn from(input: String) -> Result<Command, String> { let split: Vec<String> = input .trim() .split_whitespace() .enumerate() .map(|(i, s)| { if i == 0 { s.to_uppercase() } else { s.to_string() } }) .collect(); let split: Vec<&str> = split.iter().map(String::as_ref).collect(); if split.is_empty() { return Err("empty input".to_string()); } let cmd = match split.as_slice() { ["LINE", x1, y1, x2, y2] => Command::Line { from: Point(try_parse_usize(x1)?, try_parse_usize(y1)?), to: Point(try_parse_usize(x2)?, try_parse_usize(y2)?), }, ["RECT", x1, y1, x2, y2] | ["RECTANGLE", x1, y1, x2, y2] => Command::Rectangle { p1: Point(try_parse_usize(x1)?, try_parse_usize(y1)?), p2: Point(try_parse_usize(x2)?, try_parse_usize(y2)?), }, ["CIRC", x, y, r] | ["CIRCLE", x, y, r] => Command::Circle { p: Point(try_parse_usize(x)?, try_parse_usize(y)?), r: try_parse_usize(r)?, }, ["CANV", width, height] | ["CANVAS", width, height] => Command::Canvas { width: try_parse_usize(width)?, height: try_parse_usize(height)?, }, ["CHAR", ch] => Command::Char(ch.parse::<char>().map_err(|e| e.to_string())?), ["READ", filename] => Command::Read(filename.to_string()), ["SAVE", filename] => Command::Save(filename.to_string()), ["INFO"] => Command::Info, ["SHOW"] => Command::Show, ["QUIT"] => Command::Quit, _ => return Err("unknown command".to_string()), }; Ok(cmd) } } #[cfg(test)] mod tests { use super::*; fn command_variations(input: &str) -> Vec<String> { let capitalize = |s: &str| { let mut c = s.chars(); c.next().unwrap().to_uppercase().chain(c).collect() }; let mut vec: Vec<String> = Vec::new(); for s in &[ input.to_ascii_lowercase(), input.to_ascii_uppercase(), capitalize(input), ] { vec.push(s.clone()); vec.push(format!(" {} ", s.clone())); vec.push(format!("\t{}\t\n", s.clone())); vec.push(s.split_whitespace().collect::<Vec<&str>>().join("\t")); } vec } #[test] fn line_is_parsed() { let expected = Command::Line { from: Point(1, 2), to: Point(3, 4), }; for input in command_variations("line 1 2 3 4") { let cmd = Command::from(input).unwrap(); assert_eq!(expected, cmd); } } #[test] fn rect_is_parsed() { let expected = Command::Rectangle { p1: Point(1, 2), p2: Point(3, 4), }; for input in [ &command_variations("rect 1 2 3 4")[..], &command_variations("rectangle 1 2 3 4")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn circle_is_parsed() { let expected = Command::Circle { p: Point(1, 2), r: 3, }; for input in [ &command_variations("circ 1 2 3")[..], &command_variations("circle 1 2 3")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn canvas_is_parsed() { let expected = Command::Canvas { width: 100, height: 200, }; for input in [ &command_variations("canv 100 200")[..], &command_variations("canvas 100 200")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn char_is_parsed() { let expected = Command::Char('*'); for input in command_variations("char *") { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn read_is_parsed() { for input in &[ ("file_name", "read\tfile_name "), ("FileName", " READ FileName"), ("File_NAME", "Read \tFile_NAME \n"), ] { let expected = Command::Read(input.0.to_string()); let cmd = Command::from(input.1.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn save_is_parsed() { for input in &[ ("file_name", "save\tfile_name "), ("FileName", " SAVE FileName"), ("File_NAME", "Save \tFile_NAME \n"), ] { let expected = Command::Save(input.0.to_string()); let cmd = Command::from(input.1.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn info_is_parsed() { for input in command_variations("info") { let expected = Command::Info; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn show_is_parsed() { for input in command_variations("show") { let expected = Command::Show; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn quit_is_parsed() { for input in command_variations("quit") { let expected = Command::Quit; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } }
use crate::canvas::Point; #[derive(PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] pub enum Command { Line { from: Point, to: Point }, Rectangle { p1: Point, p2: Point }, Circle { p: Point, r: usize }, Canvas { width: usize, height: usize }, Char(char), Read(String), Save(String), Info, Show, Quit, } fn try_parse_usize(s: &str) -> Result<usize, String> { s.parse::<usize>().map_err(|e| e.to_string()) } impl Command { pub fn from(input: String) -> Result<Command, String> { let split: Vec<String> = input .trim() .split_whitespace() .enumerate() .map(|(i, s)| { if i == 0 { s.to_uppercase() } else { s.to_string() } }) .collect(); let split: Vec<&str> = split.iter().map(String::as_ref).collect(); if split.is_empty() { return Err("empty input".to_string()); } let cmd = match split.as_slice() { ["LINE", x1, y1, x2, y2] => Command::Line { from: Point(try_parse_usize(x1)?, try_parse_usize(y1)?), to: Point(try_parse_usize(x2)?, try_parse_usize(y2)?), }, ["RECT", x1, y1, x2, y2] | ["RECTANGLE", x1, y1, x2, y2] => Command::Rectangle { p1: Point(try_parse_usize(x1)?, try_parse_usize(y1)?), p2: Point(try_parse_usize(x2)?, try_parse_usize(y2)?), }, ["
} #[cfg(test)] mod tests { use super::*; fn command_variations(input: &str) -> Vec<String> { let capitalize = |s: &str| { let mut c = s.chars(); c.next().unwrap().to_uppercase().chain(c).collect() }; let mut vec: Vec<String> = Vec::new(); for s in &[ input.to_ascii_lowercase(), input.to_ascii_uppercase(), capitalize(input), ] { vec.push(s.clone()); vec.push(format!(" {} ", s.clone())); vec.push(format!("\t{}\t\n", s.clone())); vec.push(s.split_whitespace().collect::<Vec<&str>>().join("\t")); } vec } #[test] fn line_is_parsed() { let expected = Command::Line { from: Point(1, 2), to: Point(3, 4), }; for input in command_variations("line 1 2 3 4") { let cmd = Command::from(input).unwrap(); assert_eq!(expected, cmd); } } #[test] fn rect_is_parsed() { let expected = Command::Rectangle { p1: Point(1, 2), p2: Point(3, 4), }; for input in [ &command_variations("rect 1 2 3 4")[..], &command_variations("rectangle 1 2 3 4")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn circle_is_parsed() { let expected = Command::Circle { p: Point(1, 2), r: 3, }; for input in [ &command_variations("circ 1 2 3")[..], &command_variations("circle 1 2 3")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn canvas_is_parsed() { let expected = Command::Canvas { width: 100, height: 200, }; for input in [ &command_variations("canv 100 200")[..], &command_variations("canvas 100 200")[..], ] .concat() { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn char_is_parsed() { let expected = Command::Char('*'); for input in command_variations("char *") { let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn read_is_parsed() { for input in &[ ("file_name", "read\tfile_name "), ("FileName", " READ FileName"), ("File_NAME", "Read \tFile_NAME \n"), ] { let expected = Command::Read(input.0.to_string()); let cmd = Command::from(input.1.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn save_is_parsed() { for input in &[ ("file_name", "save\tfile_name "), ("FileName", " SAVE FileName"), ("File_NAME", "Save \tFile_NAME \n"), ] { let expected = Command::Save(input.0.to_string()); let cmd = Command::from(input.1.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn info_is_parsed() { for input in command_variations("info") { let expected = Command::Info; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn show_is_parsed() { for input in command_variations("show") { let expected = Command::Show; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } #[test] fn quit_is_parsed() { for input in command_variations("quit") { let expected = Command::Quit; let cmd = Command::from(input.to_string()).unwrap(); assert_eq!(expected, cmd); } } }
CIRC", x, y, r] | ["CIRCLE", x, y, r] => Command::Circle { p: Point(try_parse_usize(x)?, try_parse_usize(y)?), r: try_parse_usize(r)?, }, ["CANV", width, height] | ["CANVAS", width, height] => Command::Canvas { width: try_parse_usize(width)?, height: try_parse_usize(height)?, }, ["CHAR", ch] => Command::Char(ch.parse::<char>().map_err(|e| e.to_string())?), ["READ", filename] => Command::Read(filename.to_string()), ["SAVE", filename] => Command::Save(filename.to_string()), ["INFO"] => Command::Info, ["SHOW"] => Command::Show, ["QUIT"] => Command::Quit, _ => return Err("unknown command".to_string()), }; Ok(cmd) }
function_block-function_prefix_line
[ { "content": "fn open_input_reader() -> Box<dyn BufRead> {\n\n let args: Vec<String> = env::args().skip(1).collect();\n\n match (args.get(0), args.get(1)) {\n\n (Some(opt), Some(filename)) if opt == \"-r\" => {\n\n Box::new(BufReader::new(fs::File::open(filename).unwrap()))\n\n }\...
Rust
epp-client/src/epp/request/contact/update.rs
djc/epp-client
d06d404c12ea4d887b1106007fe56ed18600423a
use epp_client_macros::*; use crate::epp::object::data::{AuthInfo, ContactStatus, Phone, PostalInfo}; use crate::epp::object::{ElementName, EppObject, StringValue, StringValueTrait}; use crate::epp::request::Command; use crate::epp::response::contact::info::EppContactInfoResponse; use crate::epp::xml::EPP_CONTACT_XMLNS; use crate::error; use serde::{Deserialize, Serialize}; pub type EppContactUpdate = EppObject<Command<ContactUpdate>>; #[derive(Serialize, Deserialize, Debug)] pub struct ContactChangeInfo { #[serde(rename = "postalInfo")] postal_info: Option<PostalInfo>, voice: Option<Phone>, fax: Option<Phone>, email: Option<StringValue>, #[serde(rename = "authInfo")] auth_info: Option<AuthInfo>, } #[derive(Serialize, Deserialize, Debug)] pub struct StatusList { status: Vec<ContactStatus>, } #[derive(Serialize, Deserialize, Debug)] pub struct ContactUpdateData { xmlns: String, id: StringValue, #[serde(rename = "add")] add_statuses: Option<StatusList>, #[serde(rename = "rem")] remove_statuses: Option<StatusList>, #[serde(rename = "chg")] change_info: Option<ContactChangeInfo>, } #[derive(Serialize, Deserialize, Debug, ElementName)] #[element_name(name = "update")] pub struct ContactUpdate { #[serde(rename = "update")] contact: ContactUpdateData, } impl EppContactUpdate { pub fn new(id: &str, client_tr_id: &str) -> EppContactUpdate { let contact_update = ContactUpdate { contact: ContactUpdateData { xmlns: EPP_CONTACT_XMLNS.to_string(), id: id.to_string_value(), add_statuses: None, remove_statuses: None, change_info: None, }, }; EppObject::build(Command::<ContactUpdate>::new(contact_update, client_tr_id)) } pub fn set_info( &mut self, email: &str, postal_info: PostalInfo, voice: Phone, auth_password: &str, ) { self.data.command.contact.change_info = Some(ContactChangeInfo { email: Some(email.to_string_value()), postal_info: Some(postal_info), voice: Some(voice), auth_info: Some(AuthInfo::new(auth_password)), fax: None, }); } pub fn set_fax(&mut self, fax: Phone) { match &mut self.data.command.contact.change_info { Some(ref mut info) => info.fax = Some(fax), _ => (), } } pub fn add(&mut self, statuses: Vec<ContactStatus>) { self.data.command.contact.add_statuses = Some(StatusList { status: statuses }); } pub fn remove(&mut self, statuses: Vec<ContactStatus>) { self.data.command.contact.remove_statuses = Some(StatusList { status: statuses }); } pub fn load_from_epp_contact_info( &mut self, contact_info: EppContactInfoResponse, ) -> Result<(), error::Error> { match contact_info.data.res_data { Some(res_data) => { self.data.command.contact.change_info = Some(ContactChangeInfo { email: Some(res_data.info_data.email.clone()), postal_info: Some(res_data.info_data.postal_info.clone()), voice: Some(res_data.info_data.voice.clone()), fax: res_data.info_data.fax.clone(), auth_info: None, }); Ok(()) } None => Err(error::Error::Other( "No res_data in EppContactInfoResponse object".to_string(), )), } } }
use epp_client_macros::*; use crate::epp::object::data::{AuthInfo, ContactStatus, Phone, PostalInfo}; use crate::epp::object::{ElementName, EppObject, StringValue, StringValueTrait}; use crate::epp::request::Command; use crate::epp::response::contact::info::EppContactInfoResponse; use crate::epp::xml::EPP_CONTACT_XMLNS; use crate::error; use serde::{Deserialize, Serialize}; pub type EppContactUpdate = EppObject<Command<ContactUpdate>>; #[derive(Serialize, Deserialize, Debug)] pub struct ContactChangeInfo { #[serde(rename = "postalInfo")] postal_info: Option<PostalInfo>, voice: Option<Phone>, fax: Option<Phone>, email: Option<StringValue>, #[serde(rename = "authInfo")] auth_info: Option<AuthInfo>, } #[derive(Serialize, Deserialize, Debug)] pub struct StatusList { status: Vec<ContactStatus>, } #[derive(Serialize, Deserialize, Debug)] pub struct ContactUpdateData { xmlns: String, id: StringValue, #[serde(rename = "add")] add_statuses: Option<StatusList>, #[serde(rename = "rem")] remove_statuses: Option<StatusList>, #[serde(rename = "chg")] change_info: Option<ContactChangeInfo>, } #[derive(Serialize, Deserialize, Debug, ElementName)] #[element_name(name = "update")] pub struct ContactUpdate { #[serde(rename = "update")] contact: ContactUpdateData, } impl EppContactUpdate { pub fn new(id: &str, client_tr_id: &str) -> EppContactUpdate {
EppObject::build(Command::<ContactUpdate>::new(contact_update, client_tr_id)) } pub fn set_info( &mut self, email: &str, postal_info: PostalInfo, voice: Phone, auth_password: &str, ) { self.data.command.contact.change_info = Some(ContactChangeInfo { email: Some(email.to_string_value()), postal_info: Some(postal_info), voice: Some(voice), auth_info: Some(AuthInfo::new(auth_password)), fax: None, }); } pub fn set_fax(&mut self, fax: Phone) { match &mut self.data.command.contact.change_info { Some(ref mut info) => info.fax = Some(fax), _ => (), } } pub fn add(&mut self, statuses: Vec<ContactStatus>) { self.data.command.contact.add_statuses = Some(StatusList { status: statuses }); } pub fn remove(&mut self, statuses: Vec<ContactStatus>) { self.data.command.contact.remove_statuses = Some(StatusList { status: statuses }); } pub fn load_from_epp_contact_info( &mut self, contact_info: EppContactInfoResponse, ) -> Result<(), error::Error> { match contact_info.data.res_data { Some(res_data) => { self.data.command.contact.change_info = Some(ContactChangeInfo { email: Some(res_data.info_data.email.clone()), postal_info: Some(res_data.info_data.postal_info.clone()), voice: Some(res_data.info_data.voice.clone()), fax: res_data.info_data.fax.clone(), auth_info: None, }); Ok(()) } None => Err(error::Error::Other( "No res_data in EppContactInfoResponse object".to_string(), )), } } }
let contact_update = ContactUpdate { contact: ContactUpdateData { xmlns: EPP_CONTACT_XMLNS.to_string(), id: id.to_string_value(), add_statuses: None, remove_statuses: None, change_info: None, }, };
assignment_statement
[ { "content": "/// Basic client TRID generation function. Mainly used for testing. Users of the library should use their own clTRID generation function.\n\npub fn generate_client_tr_id(username: &str) -> Result<String, Box<dyn Error>> {\n\n let timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPO...
Rust
hartex_core/src/error.rs
mod-tc/HarTex-rust-discord-bot
1cbd3e8933ff71853eff0114fd2675f3e8b7b210
use std::string::FromUtf8Error; use base64::DecodeError; use ctrlc::Error as CtrlcError; use toml::de::Error as TomlDeserializationError; use crate::discord::{ embed_builder::{ image_source::ImageSourceUrlError, EmbedError }, gateway::{ cluster::{ ClusterCommandError, ClusterStartError, }, shard::SessionInactiveError }, http::{ error::Error as HttpError, request::{ application::InteractionError, channel::message::{ create_message::CreateMessageError, update_message::UpdateMessageError }, guild::member::update_guild_member::UpdateGuildMemberError }, response::DeserializeBodyError }, model::gateway::payload::update_presence::UpdatePresenceError }; #[derive(Debug)] pub enum HarTexError { Base64DecodeError { error: DecodeError }, ClusterCommandError { error: ClusterCommandError }, ClusterStartError { error: ClusterStartError }, CreateMessageError { error: CreateMessageError }, CtrlcError { error: CtrlcError }, DeserializeBodyError { error: DeserializeBodyError }, EmbedError { error: EmbedError }, EmbedImageSourceUrlError { error: ImageSourceUrlError }, InteractionError { error: InteractionError }, SessionInactiveError { error: SessionInactiveError }, TomlDeserializationError { error: TomlDeserializationError }, TwilightHttpError { error: HttpError }, UpdateGuildMemberError { error: UpdateGuildMemberError }, UpdateMessageError { error: UpdateMessageError }, UpdatePresenceError { error: UpdatePresenceError }, Utf8ValidationError { error: FromUtf8Error }, Custom { message: String } } impl From<ClusterCommandError> for HarTexError { fn from(error: ClusterCommandError) -> Self { Self::ClusterCommandError { error } } } impl From<ClusterStartError> for HarTexError { fn from(error: ClusterStartError) -> Self { Self::ClusterStartError { error } } } impl From<CreateMessageError> for HarTexError { fn from(error: CreateMessageError) -> Self { Self::CreateMessageError { error } } } impl From<CtrlcError> for HarTexError { fn from(error: CtrlcError) -> Self { Self::CtrlcError { error } } } impl From<DecodeError> for HarTexError { fn from(error: DecodeError) -> Self { Self::Base64DecodeError { error } } } impl From<DeserializeBodyError> for HarTexError { fn from(error: DeserializeBodyError) -> Self { Self::DeserializeBodyError { error } } } impl From<EmbedError> for HarTexError { fn from(error: EmbedError) -> Self { Self::EmbedError { error } } } impl From<FromUtf8Error> for HarTexError { fn from(error: FromUtf8Error) -> Self { Self::Utf8ValidationError { error } } } impl From<HttpError> for HarTexError { fn from(error: HttpError) -> Self { Self::TwilightHttpError { error } } } impl From<ImageSourceUrlError> for HarTexError { fn from(error: ImageSourceUrlError) -> Self { Self::EmbedImageSourceUrlError { error } } } impl From<InteractionError> for HarTexError { fn from(error: InteractionError) -> Self { Self::InteractionError { error } } } impl From<SessionInactiveError> for HarTexError { fn from(error: SessionInactiveError) -> Self { Self::SessionInactiveError { error } } } impl From<TomlDeserializationError> for HarTexError { fn from(error: TomlDeserializationError) -> Self { Self::TomlDeserializationError { error } } } impl From<UpdateGuildMemberError> for HarTexError { fn from(error: UpdateGuildMemberError) -> Self { Self::UpdateGuildMemberError { error } } } impl From<UpdateMessageError> for HarTexError { fn from(error: UpdateMessageError) -> Self { Self::UpdateMessageError { error } } } impl From<UpdatePresenceError> for HarTexError { fn from(error: UpdatePresenceError) -> Self { Self::UpdatePresenceError { error } } } pub type HarTexResult<T> = Result<T, HarTexError>;
use std::string::FromUtf8Error; use base64::DecodeError; use ctrlc::Error as CtrlcError; use toml::de::Error as TomlDeserializationError; use crate::discord::{ embed_builder::{ image_source::ImageSourceUrlError, EmbedError }, gateway::{ cluster::{ ClusterCommandError, ClusterStartError, }, shard::SessionInactiveError }, http::{ error::Error as HttpError, request::{ application::InteractionError, channel::message::{ create_message::CreateMessageError, update_message::UpdateMessageError }, guild::member::update_guild_member::UpdateGuildMemberError }, response::DeserializeBodyError }, model::gateway::payload::update_presence::UpdatePresenceError }; #[derive(Debug)] pub enum HarTexError { Base64DecodeError { error:
} } impl From<TomlDeserializationError> for HarTexError { fn from(error: TomlDeserializationError) -> Self { Self::TomlDeserializationError { error } } } impl From<UpdateGuildMemberError> for HarTexError { fn from(error: UpdateGuildMemberError) -> Self { Self::UpdateGuildMemberError { error } } } impl From<UpdateMessageError> for HarTexError { fn from(error: UpdateMessageError) -> Self { Self::UpdateMessageError { error } } } impl From<UpdatePresenceError> for HarTexError { fn from(error: UpdatePresenceError) -> Self { Self::UpdatePresenceError { error } } } pub type HarTexResult<T> = Result<T, HarTexError>;
DecodeError }, ClusterCommandError { error: ClusterCommandError }, ClusterStartError { error: ClusterStartError }, CreateMessageError { error: CreateMessageError }, CtrlcError { error: CtrlcError }, DeserializeBodyError { error: DeserializeBodyError }, EmbedError { error: EmbedError }, EmbedImageSourceUrlError { error: ImageSourceUrlError }, InteractionError { error: InteractionError }, SessionInactiveError { error: SessionInactiveError }, TomlDeserializationError { error: TomlDeserializationError }, TwilightHttpError { error: HttpError }, UpdateGuildMemberError { error: UpdateGuildMemberError }, UpdateMessageError { error: UpdateMessageError }, UpdatePresenceError { error: UpdatePresenceError }, Utf8ValidationError { error: FromUtf8Error }, Custom { message: String } } impl From<ClusterCommandError> for HarTexError { fn from(error: ClusterCommandError) -> Self { Self::ClusterCommandError { error } } } impl From<ClusterStartError> for HarTexError { fn from(error: ClusterStartError) -> Self { Self::ClusterStartError { error } } } impl From<CreateMessageError> for HarTexError { fn from(error: CreateMessageError) -> Self { Self::CreateMessageError { error } } } impl From<CtrlcError> for HarTexError { fn from(error: CtrlcError) -> Self { Self::CtrlcError { error } } } impl From<DecodeError> for HarTexError { fn from(error: DecodeError) -> Self { Self::Base64DecodeError { error } } } impl From<DeserializeBodyError> for HarTexError { fn from(error: DeserializeBodyError) -> Self { Self::DeserializeBodyError { error } } } impl From<EmbedError> for HarTexError { fn from(error: EmbedError) -> Self { Self::EmbedError { error } } } impl From<FromUtf8Error> for HarTexError { fn from(error: FromUtf8Error) -> Self { Self::Utf8ValidationError { error } } } impl From<HttpError> for HarTexError { fn from(error: HttpError) -> Self { Self::TwilightHttpError { error } } } impl From<ImageSourceUrlError> for HarTexError { fn from(error: ImageSourceUrlError) -> Self { Self::EmbedImageSourceUrlError { error } } } impl From<InteractionError> for HarTexError { fn from(error: InteractionError) -> Self { Self::InteractionError { error } } } impl From<SessionInactiveError> for HarTexError { fn from(error: SessionInactiveError) -> Self { Self::SessionInactiveError { error }
random
[ { "content": "/// # Trait `Command`\n\n///\n\n/// An application command.\n\n///\n\n/// ## Trait Methods\n\n/// - `name`; return type `String`: the name of the command\n\n/// - `description`; return type `String`: the description of the command\n\n/// - `execute`; parameters `CommandContext`, `InMemoryCache`; r...
Rust
bench/utils.rs
tauri-apps/benchmark_electron
09afd37775848c44c2f3712008bdb3760197e73e
use serde::Serialize; use std::{collections::HashMap, io::BufRead, path::PathBuf, process::{Command, Output, Stdio}}; pub fn root_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } pub fn run_collect(cmd: &[&str]) -> (String, String) { let mut process_builder = Command::new(cmd[0]); process_builder .args(&cmd[1..]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let prog = process_builder.spawn().expect("failed to spawn script"); let Output { stdout, stderr, status, } = prog.wait_with_output().expect("failed to wait on child"); let stdout = String::from_utf8(stdout).unwrap(); let stderr = String::from_utf8(stderr).unwrap(); if !status.success() { eprintln!("stdout: <<<{}>>>", stdout); eprintln!("stderr: <<<{}>>>", stderr); panic!("Unexpected exit code: {:?}", status.code()); } (stdout, stderr) } pub fn parse_max_mem(file_path: &str) -> Option<u64> { let file = std::fs::File::open(file_path).unwrap(); let output = std::io::BufReader::new(file); let mut highest: u64 = 0; for line in output.lines() { if let Ok(line) = line { let split = line.split(" ").collect::<Vec<_>>(); if split.len() == 3 { let current_bytes = str::parse::<f64>(split[1]).unwrap() as u64 * 1024 * 1024; if current_bytes > highest { highest = current_bytes; } } } } std::fs::remove_file(file_path).unwrap(); if highest > 0 { return Some(highest); } None } #[derive(Debug, Clone, Serialize)] pub struct StraceOutput { pub percent_time: f64, pub seconds: f64, pub usecs_per_call: Option<u64>, pub calls: u64, pub errors: u64, } pub fn parse_strace_output(output: &str) -> HashMap<String, StraceOutput> { let mut summary = HashMap::new(); let mut lines = output .lines() .filter(|line| !line.is_empty() && !line.contains("detached ...")); let count = lines.clone().count(); if count < 4 { return summary; } let total_line = lines.next_back().unwrap(); lines.next_back(); let data_lines = lines.skip(2); for line in data_lines { let syscall_fields = line.split_whitespace().collect::<Vec<_>>(); let len = syscall_fields.len(); let syscall_name = syscall_fields.last().unwrap(); if (5..=6).contains(&len) { summary.insert( syscall_name.to_string(), StraceOutput { percent_time: str::parse::<f64>(syscall_fields[0]).unwrap(), seconds: str::parse::<f64>(syscall_fields[1]).unwrap(), usecs_per_call: Some(str::parse::<u64>(syscall_fields[2]).unwrap()), calls: str::parse::<u64>(syscall_fields[3]).unwrap(), errors: if syscall_fields.len() < 6 { 0 } else { str::parse::<u64>(syscall_fields[4]).unwrap() }, }, ); } } let total_fields = total_line.split_whitespace().collect::<Vec<_>>(); summary.insert( "total".to_string(), StraceOutput { percent_time: str::parse::<f64>(total_fields[0]).unwrap(), seconds: str::parse::<f64>(total_fields[1]).unwrap(), usecs_per_call: None, calls: str::parse::<u64>(total_fields[2]).unwrap(), errors: str::parse::<u64>(total_fields[3]).unwrap(), }, ); summary } pub fn run(cmd: &[&str]) { let mut process_builder = Command::new(cmd[0]); process_builder.args(&cmd[1..]).stdin(Stdio::piped()); let mut prog = process_builder.spawn().expect("failed to spawn script"); let status = prog.wait().expect("failed to wait on child"); if !status.success() { panic!("Unexpected exit code: {:?}", status.code()); } }
use serde::Serialize; use std::{collections::HashMap, io::BufRead, path::PathBuf, process::{Command, Output, Stdio}}; pub fn root_path() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) } pub fn run_collect(cmd: &[&str]) -> (String, String) { let mut process_builder = Command::new(cmd[0]); process_builder .args(&cmd[1..]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let prog = process_builder.spawn().expect("failed to spawn script"); let Output { stdout, stderr, status, } = prog.wait_with_output().expect("failed to wait on child"); let stdout = String::from_utf8(stdout).unwrap(); let stderr = String::from_utf8(stderr).unwrap(); if !status.success() { eprintln!("stdout: <<<{}>>>", stdout); eprintln!("stderr: <<<{}>>>", stderr); panic!("Unexpected exit code: {:?}", status.code()); } (stdout, stderr) }
#[derive(Debug, Clone, Serialize)] pub struct StraceOutput { pub percent_time: f64, pub seconds: f64, pub usecs_per_call: Option<u64>, pub calls: u64, pub errors: u64, } pub fn parse_strace_output(output: &str) -> HashMap<String, StraceOutput> { let mut summary = HashMap::new(); let mut lines = output .lines() .filter(|line| !line.is_empty() && !line.contains("detached ...")); let count = lines.clone().count(); if count < 4 { return summary; } let total_line = lines.next_back().unwrap(); lines.next_back(); let data_lines = lines.skip(2); for line in data_lines { let syscall_fields = line.split_whitespace().collect::<Vec<_>>(); let len = syscall_fields.len(); let syscall_name = syscall_fields.last().unwrap(); if (5..=6).contains(&len) { summary.insert( syscall_name.to_string(), StraceOutput { percent_time: str::parse::<f64>(syscall_fields[0]).unwrap(), seconds: str::parse::<f64>(syscall_fields[1]).unwrap(), usecs_per_call: Some(str::parse::<u64>(syscall_fields[2]).unwrap()), calls: str::parse::<u64>(syscall_fields[3]).unwrap(), errors: if syscall_fields.len() < 6 { 0 } else { str::parse::<u64>(syscall_fields[4]).unwrap() }, }, ); } } let total_fields = total_line.split_whitespace().collect::<Vec<_>>(); summary.insert( "total".to_string(), StraceOutput { percent_time: str::parse::<f64>(total_fields[0]).unwrap(), seconds: str::parse::<f64>(total_fields[1]).unwrap(), usecs_per_call: None, calls: str::parse::<u64>(total_fields[2]).unwrap(), errors: str::parse::<u64>(total_fields[3]).unwrap(), }, ); summary } pub fn run(cmd: &[&str]) { let mut process_builder = Command::new(cmd[0]); process_builder.args(&cmd[1..]).stdin(Stdio::piped()); let mut prog = process_builder.spawn().expect("failed to spawn script"); let status = prog.wait().expect("failed to wait on child"); if !status.success() { panic!("Unexpected exit code: {:?}", status.code()); } }
pub fn parse_max_mem(file_path: &str) -> Option<u64> { let file = std::fs::File::open(file_path).unwrap(); let output = std::io::BufReader::new(file); let mut highest: u64 = 0; for line in output.lines() { if let Ok(line) = line { let split = line.split(" ").collect::<Vec<_>>(); if split.len() == 3 { let current_bytes = str::parse::<f64>(split[1]).unwrap() as u64 * 1024 * 1024; if current_bytes > highest { highest = current_bytes; } } } } std::fs::remove_file(file_path).unwrap(); if highest > 0 { return Some(highest); } None }
function_block-full_function
[ { "content": "fn run_exec_time() -> Result<HashMap<String, HashMap<String, f64>>> {\n\n let benchmark_file = root_path().join(\"hyperfine_results.json\");\n\n let benchmark_file = benchmark_file.to_str().unwrap();\n\n\n\n let mut command = [\n\n \"hyperfine\",\n\n \"--export-json\",\n\n ...
Rust
tests/src/tests.rs
duanyytop/ckb-passport-lock
e1fb7df2eea0bf35abfe3cb349948754345debf8
use super::*; use ckb_testtool::context::Context; use ckb_tool::ckb_hash::{new_blake2b, blake2b_256}; use ckb_tool::ckb_types::{ bytes::Bytes, core::{TransactionBuilder, TransactionView}, packed::{self, *}, prelude::*, }; use ckb_tool::ckb_error::assert_error_eq; use ckb_tool::ckb_script::ScriptError; use openssl::hash::MessageDigest; use openssl::pkey::{PKey, Private, Public}; use openssl::rsa::Rsa; use openssl::sign::{Signer, Verifier}; use std::fs; const MAX_CYCLES: u64 = 70_000_000; const ERROR_ISO97962_INVALID_ARG9: i8 = 17; const WRONG_PUB_KEY: i8 = 6; const MESSAGE_SINGLE_SIZE: usize = 8; const SUB_SIGNATURE_SIZE: usize = 128; const TX_SIGNATURE_SIZE: usize = 512; const SIGN_INFO_SIZE: usize = 648; const ISO9796_2_ALGORITHM_ID: u8 = 2; const ISO9796_2_KEY_SIZE: u8 = 1; const ISO9796_2_PADDING: u8 = 0; const ISO9796_2_MD_SHA1: u8 = 4; fn blake160(data: &[u8]) -> [u8; 20] { let mut buf = [0u8; 20]; let hash = blake2b_256(data); buf.clone_from_slice(&hash[..20]); buf } fn sign_tx( tx: TransactionView, private_key: &PKey<Private>, public_key: &PKey<Public>, is_pub_key_hash_error: bool ) -> TransactionView { let witnesses_len = tx.witnesses().len(); let tx_hash = tx.hash(); let mut signed_witnesses: Vec<packed::Bytes> = Vec::new(); let mut blake2b = new_blake2b(); let mut message = [0u8; 32]; blake2b.update(&tx_hash.raw_data()); let witness = WitnessArgs::default(); let zero_lock: Bytes = { let mut buf = Vec::new(); buf.resize(SIGN_INFO_SIZE, 0); buf.into() }; let witness_for_digest = witness .clone() .as_builder() .lock(Some(zero_lock).pack()) .build(); let witness_len = witness_for_digest.as_bytes().len() as u64; blake2b.update(&witness_len.to_le_bytes()); blake2b.update(&witness_for_digest.as_bytes()); (1..witnesses_len).for_each(|n| { let witness = tx.witnesses().get(n).unwrap(); let witness_len = witness.raw_data().len() as u64; blake2b.update(&witness_len.to_le_bytes()); blake2b.update(&witness.raw_data()); }); blake2b.finalize(&mut message); let mut rsa_signature = [0u8; TX_SIGNATURE_SIZE]; for index in 0..4 { let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); signer.update(&message[MESSAGE_SINGLE_SIZE * index..MESSAGE_SINGLE_SIZE * (index + 1)]).unwrap(); rsa_signature[SUB_SIGNATURE_SIZE * index..SUB_SIGNATURE_SIZE * (index + 1)].copy_from_slice(&signer.sign_to_vec().unwrap()); } let mut signed_signature = rsa_signature.clone().to_vec(); let (mut rsa_info, _) = compute_pub_key_hash(public_key, is_pub_key_hash_error); signed_signature.append(&mut rsa_info); for index in 0..4 { let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); verifier.update(&message[MESSAGE_SINGLE_SIZE * index..MESSAGE_SINGLE_SIZE * (index + 1)]).unwrap(); assert!(verifier.verify(&rsa_signature[SUB_SIGNATURE_SIZE * index..SUB_SIGNATURE_SIZE * (index + 1)]).unwrap()); } signed_witnesses.push( witness .as_builder() .lock(Some(Bytes::from(signed_signature)).pack()) .build() .as_bytes() .pack(), ); for i in 1..witnesses_len { signed_witnesses.push(tx.witnesses().get(i).unwrap()); } tx.as_advanced_builder() .set_witnesses(signed_witnesses) .build() } fn compute_pub_key_hash(public_key: &PKey<Public>, is_pub_key_hash_error: bool) -> (Vec<u8>, Vec<u8>) { let mut result: Vec<u8> = vec![]; result.extend_from_slice(&[ISO9796_2_ALGORITHM_ID, ISO9796_2_KEY_SIZE, ISO9796_2_PADDING, ISO9796_2_MD_SHA1]); let rsa_public_key = public_key.rsa().unwrap(); let mut e = if is_pub_key_hash_error { let mut vec = rsa_public_key.e().to_vec(); vec.insert(0, 1); vec } else { rsa_public_key.e().to_vec() }; let mut n = rsa_public_key.n().to_vec(); e.reverse(); n.reverse(); while e.len() < 4 { e.push(0); } while n.len() < 128 { n.push(0); } result.append(&mut e); result.append(&mut n); let h = blake160(&result).into(); (result, h) } fn generate_random_key() -> (PKey<Private>, PKey<Public>) { let rsa = Rsa::generate(1024).unwrap(); let private_key = PKey::from_rsa(rsa).unwrap(); let public_key_pem: Vec<u8> = private_key.public_key_to_pem().unwrap(); let public_key = PKey::public_key_from_pem(&public_key_pem).unwrap(); (private_key, public_key) } #[test] fn test_wrong_signature() { let (private_key, public_key) = generate_random_key(); let mut context = Context::default(); let contract_bin: Bytes = Loader::default().load_binary("ckb-passport-lock"); let out_point = context.deploy_cell(contract_bin); let rsa_bin: Bytes = fs::read("../ckb-production-scripts/build/validate_signature_rsa") .expect("load rsa") .into(); let rsa_out_point = context.deploy_cell(rsa_bin); let rsa_dep = CellDep::new_builder().out_point(rsa_out_point).build(); let (_, public_key_hash) = compute_pub_key_hash(&public_key, false); let lock_script = context .build_script(&out_point, public_key_hash.into()) .expect("script"); let lock_script_dep = CellDep::new_builder().out_point(out_point).build(); let input_out_point1 = context.create_cell( CellOutput::new_builder() .capacity(1000u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let input_out_point2 = context.create_cell( CellOutput::new_builder() .capacity(300u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let inputs = vec![ CellInput::new_builder() .previous_output(input_out_point1) .build(), CellInput::new_builder() .previous_output(input_out_point2) .build(), ]; let outputs = vec![ CellOutput::new_builder() .capacity(500u64.pack()) .lock(lock_script.clone()) .build(), CellOutput::new_builder() .capacity(800u64.pack()) .lock(lock_script) .build(), ]; let outputs_data = vec![Bytes::new(); 2]; let mut witnesses = vec![]; for _ in 0..inputs.len() { witnesses.push(Bytes::new()) } let tx = TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data.pack()) .cell_dep(lock_script_dep) .cell_dep(rsa_dep) .witnesses(witnesses.pack()) .build(); let tx = context.complete_tx(tx); let tx = sign_tx(tx, &private_key, &public_key, false); let err = context.verify_tx(&tx, MAX_CYCLES).unwrap_err(); let script_cell_index = 0; assert_error_eq!( err, ScriptError::ValidationFailure(ERROR_ISO97962_INVALID_ARG9).input_lock_script(script_cell_index) ); } #[test] fn test_wrong_pub_key() { let (private_key, public_key) = generate_random_key(); let mut context = Context::default(); let contract_bin: Bytes = Loader::default().load_binary("ckb-passport-lock"); let out_point = context.deploy_cell(contract_bin); let rsa_bin: Bytes = fs::read("../ckb-production-scripts/build/validate_signature_rsa") .expect("load rsa") .into(); let rsa_out_point = context.deploy_cell(rsa_bin); let rsa_dep = CellDep::new_builder().out_point(rsa_out_point).build(); let (_, public_key_hash) = compute_pub_key_hash(&public_key, false); let lock_script = context .build_script(&out_point, public_key_hash.into()) .expect("script"); let lock_script_dep = CellDep::new_builder().out_point(out_point).build(); let input_out_point1 = context.create_cell( CellOutput::new_builder() .capacity(1000u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let input_out_point2 = context.create_cell( CellOutput::new_builder() .capacity(300u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let inputs = vec![ CellInput::new_builder() .previous_output(input_out_point1) .build(), CellInput::new_builder() .previous_output(input_out_point2) .build(), ]; let outputs = vec![ CellOutput::new_builder() .capacity(500u64.pack()) .lock(lock_script.clone()) .build(), CellOutput::new_builder() .capacity(800u64.pack()) .lock(lock_script) .build(), ]; let outputs_data = vec![Bytes::new(); 2]; let mut witnesses = vec![]; for _ in 0..inputs.len() { witnesses.push(Bytes::new()) } let tx = TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data.pack()) .cell_dep(lock_script_dep) .cell_dep(rsa_dep) .witnesses(witnesses.pack()) .build(); let tx = context.complete_tx(tx); let tx = sign_tx(tx, &private_key, &public_key, true); let err = context.verify_tx(&tx, MAX_CYCLES).unwrap_err(); let script_cell_index = 0; assert_error_eq!( err, ScriptError::ValidationFailure(WRONG_PUB_KEY).input_lock_script(script_cell_index) ); }
use super::*; use ckb_testtool::context::Context; use ckb_tool::ckb_hash::{new_blake2b, blake2b_256}; use ckb_tool::ckb_types::{ bytes::Bytes, core::{TransactionBuilder, TransactionView}, packed::{self, *}, prelude::*, }; use ckb_tool::ckb_error::assert_error_eq; use ckb_tool::ckb_script::ScriptError; use openssl::hash::MessageDigest; use openssl::pkey::{PKey, Private, Public}; use openssl::rsa::Rsa; use openssl::sign::{Signer, Verifier}; use std::fs; const MAX_CYCLES: u64 = 70_000_000; const ERROR_ISO97962_INVALID_ARG9: i8 = 17; const WRONG_PUB_KEY: i8 = 6; const MESSAGE_SINGLE_SIZE: usize = 8; const SUB_SIGNATURE_SIZE: usize = 128; const TX_SIGNATURE_SIZE: usize = 512; const SIGN_INFO_SIZE: usize = 648; const ISO9796_2_ALGORITHM_ID: u8 = 2; const ISO9796_2_KEY_SIZE: u8 = 1; const ISO9796_2_PADDING: u8 = 0; const ISO9796_2_MD_SHA1: u8 = 4; fn blake160(data: &[u8]) -> [u8; 20] { let mut buf = [0u8; 20]; let hash = blake2b_256(data); buf.clone_from_slice(&hash[..20]); buf } fn sign_tx( tx: TransactionView, private_key: &PKey<Private>, public_key: &PKey<Public>, is_pub_key_hash_error: bool ) -> TransactionView { let witnesses_len = tx.witnesses().len(); let tx_hash = tx.hash(); let mut signed_witnesses: Vec<packed::Bytes> = Vec::new(); let mut blake2b = new_blake2b(); let mut message = [0u8; 32]; blake2b.update(&tx_hash.raw_data()); let witness =
dep) .cell_dep(rsa_dep) .witnesses(witnesses.pack()) .build(); let tx = context.complete_tx(tx); let tx = sign_tx(tx, &private_key, &public_key, true); let err = context.verify_tx(&tx, MAX_CYCLES).unwrap_err(); let script_cell_index = 0; assert_error_eq!( err, ScriptError::ValidationFailure(WRONG_PUB_KEY).input_lock_script(script_cell_index) ); }
WitnessArgs::default(); let zero_lock: Bytes = { let mut buf = Vec::new(); buf.resize(SIGN_INFO_SIZE, 0); buf.into() }; let witness_for_digest = witness .clone() .as_builder() .lock(Some(zero_lock).pack()) .build(); let witness_len = witness_for_digest.as_bytes().len() as u64; blake2b.update(&witness_len.to_le_bytes()); blake2b.update(&witness_for_digest.as_bytes()); (1..witnesses_len).for_each(|n| { let witness = tx.witnesses().get(n).unwrap(); let witness_len = witness.raw_data().len() as u64; blake2b.update(&witness_len.to_le_bytes()); blake2b.update(&witness.raw_data()); }); blake2b.finalize(&mut message); let mut rsa_signature = [0u8; TX_SIGNATURE_SIZE]; for index in 0..4 { let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); signer.update(&message[MESSAGE_SINGLE_SIZE * index..MESSAGE_SINGLE_SIZE * (index + 1)]).unwrap(); rsa_signature[SUB_SIGNATURE_SIZE * index..SUB_SIGNATURE_SIZE * (index + 1)].copy_from_slice(&signer.sign_to_vec().unwrap()); } let mut signed_signature = rsa_signature.clone().to_vec(); let (mut rsa_info, _) = compute_pub_key_hash(public_key, is_pub_key_hash_error); signed_signature.append(&mut rsa_info); for index in 0..4 { let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); verifier.update(&message[MESSAGE_SINGLE_SIZE * index..MESSAGE_SINGLE_SIZE * (index + 1)]).unwrap(); assert!(verifier.verify(&rsa_signature[SUB_SIGNATURE_SIZE * index..SUB_SIGNATURE_SIZE * (index + 1)]).unwrap()); } signed_witnesses.push( witness .as_builder() .lock(Some(Bytes::from(signed_signature)).pack()) .build() .as_bytes() .pack(), ); for i in 1..witnesses_len { signed_witnesses.push(tx.witnesses().get(i).unwrap()); } tx.as_advanced_builder() .set_witnesses(signed_witnesses) .build() } fn compute_pub_key_hash(public_key: &PKey<Public>, is_pub_key_hash_error: bool) -> (Vec<u8>, Vec<u8>) { let mut result: Vec<u8> = vec![]; result.extend_from_slice(&[ISO9796_2_ALGORITHM_ID, ISO9796_2_KEY_SIZE, ISO9796_2_PADDING, ISO9796_2_MD_SHA1]); let rsa_public_key = public_key.rsa().unwrap(); let mut e = if is_pub_key_hash_error { let mut vec = rsa_public_key.e().to_vec(); vec.insert(0, 1); vec } else { rsa_public_key.e().to_vec() }; let mut n = rsa_public_key.n().to_vec(); e.reverse(); n.reverse(); while e.len() < 4 { e.push(0); } while n.len() < 128 { n.push(0); } result.append(&mut e); result.append(&mut n); let h = blake160(&result).into(); (result, h) } fn generate_random_key() -> (PKey<Private>, PKey<Public>) { let rsa = Rsa::generate(1024).unwrap(); let private_key = PKey::from_rsa(rsa).unwrap(); let public_key_pem: Vec<u8> = private_key.public_key_to_pem().unwrap(); let public_key = PKey::public_key_from_pem(&public_key_pem).unwrap(); (private_key, public_key) } #[test] fn test_wrong_signature() { let (private_key, public_key) = generate_random_key(); let mut context = Context::default(); let contract_bin: Bytes = Loader::default().load_binary("ckb-passport-lock"); let out_point = context.deploy_cell(contract_bin); let rsa_bin: Bytes = fs::read("../ckb-production-scripts/build/validate_signature_rsa") .expect("load rsa") .into(); let rsa_out_point = context.deploy_cell(rsa_bin); let rsa_dep = CellDep::new_builder().out_point(rsa_out_point).build(); let (_, public_key_hash) = compute_pub_key_hash(&public_key, false); let lock_script = context .build_script(&out_point, public_key_hash.into()) .expect("script"); let lock_script_dep = CellDep::new_builder().out_point(out_point).build(); let input_out_point1 = context.create_cell( CellOutput::new_builder() .capacity(1000u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let input_out_point2 = context.create_cell( CellOutput::new_builder() .capacity(300u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let inputs = vec![ CellInput::new_builder() .previous_output(input_out_point1) .build(), CellInput::new_builder() .previous_output(input_out_point2) .build(), ]; let outputs = vec![ CellOutput::new_builder() .capacity(500u64.pack()) .lock(lock_script.clone()) .build(), CellOutput::new_builder() .capacity(800u64.pack()) .lock(lock_script) .build(), ]; let outputs_data = vec![Bytes::new(); 2]; let mut witnesses = vec![]; for _ in 0..inputs.len() { witnesses.push(Bytes::new()) } let tx = TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data.pack()) .cell_dep(lock_script_dep) .cell_dep(rsa_dep) .witnesses(witnesses.pack()) .build(); let tx = context.complete_tx(tx); let tx = sign_tx(tx, &private_key, &public_key, false); let err = context.verify_tx(&tx, MAX_CYCLES).unwrap_err(); let script_cell_index = 0; assert_error_eq!( err, ScriptError::ValidationFailure(ERROR_ISO97962_INVALID_ARG9).input_lock_script(script_cell_index) ); } #[test] fn test_wrong_pub_key() { let (private_key, public_key) = generate_random_key(); let mut context = Context::default(); let contract_bin: Bytes = Loader::default().load_binary("ckb-passport-lock"); let out_point = context.deploy_cell(contract_bin); let rsa_bin: Bytes = fs::read("../ckb-production-scripts/build/validate_signature_rsa") .expect("load rsa") .into(); let rsa_out_point = context.deploy_cell(rsa_bin); let rsa_dep = CellDep::new_builder().out_point(rsa_out_point).build(); let (_, public_key_hash) = compute_pub_key_hash(&public_key, false); let lock_script = context .build_script(&out_point, public_key_hash.into()) .expect("script"); let lock_script_dep = CellDep::new_builder().out_point(out_point).build(); let input_out_point1 = context.create_cell( CellOutput::new_builder() .capacity(1000u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let input_out_point2 = context.create_cell( CellOutput::new_builder() .capacity(300u64.pack()) .lock(lock_script.clone()) .build(), Bytes::new(), ); let inputs = vec![ CellInput::new_builder() .previous_output(input_out_point1) .build(), CellInput::new_builder() .previous_output(input_out_point2) .build(), ]; let outputs = vec![ CellOutput::new_builder() .capacity(500u64.pack()) .lock(lock_script.clone()) .build(), CellOutput::new_builder() .capacity(800u64.pack()) .lock(lock_script) .build(), ]; let outputs_data = vec![Bytes::new(); 2]; let mut witnesses = vec![]; for _ in 0..inputs.len() { witnesses.push(Bytes::new()) } let tx = TransactionBuilder::default() .inputs(inputs) .outputs(outputs) .outputs_data(outputs_data.pack()) .cell_dep(lock_script_
random
[ { "content": "pub fn blake2b_256<T: AsRef<[u8]>>(s: T) -> [u8; 32] {\n\n if s.as_ref().is_empty() {\n\n return BLANK_HASH;\n\n }\n\n inner_blake2b_256(s)\n\n}\n\n\n", "file_path": "contracts/ckb-passport-lock/src/entry/hash.rs", "rank": 1, "score": 108113.07493456306 }, { "co...
Rust
bzip2/src/tokio.rs
GMAP/RustStreamBench
d319445c448db15221cf62aa51af002308807c39
use std::mem; use std::fs::File; use std::io::prelude::*; use std::time::{SystemTime}; use {bzip2_sys}; use crossbeam_channel::{unbounded}; use{ futures::future::lazy, futures::sync::*, futures::{stream, Future, Stream}, tokio::prelude::*, }; struct Tcontent { order: usize, buffer_input: Vec<u8>, buffer_output: Vec<u8>, output_size: u32, } macro_rules! spawn_return { ($block:expr) => {{ let (sender, receiver) = oneshot::channel::<_>(); tokio::spawn(lazy(move || { let result = $block; sender.send(result).ok(); Ok(()) })); receiver }}; } pub fn tokio(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let mut buffer_input = vec![]; let mut buffer_output = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize = 0; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut order = 0; let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if bytes_left <= 0 { return Ok(Async::Ready(None)); } pos_init = pos_end; pos_end += if bytes_left < block_size { buffer_input.len()-pos_end } else { block_size }; bytes_left -= pos_end-pos_init; let buffer_slice = &buffer_input[pos_init..pos_end]; let content = Tcontent { order, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; (buffer_slice.len() as f64 *1.01) as usize+600], output_size: 0, }; order += 1; Ok(Async::Ready(Some(content))) }); let (collection_send, collection_recv) = unbounded(); let (send, recv) = (collection_send.clone(), collection_recv.clone()); let pipeline = processing_stream .map(move |mut content: Tcontent| { let send = collection_send.clone(); spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzCompressInit(&mut bz_buffer as *mut _, 9, 0, 30); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzCompress(&mut bz_buffer as *mut _, bzip2_sys::BZ_FINISH as _); bzip2_sys::BZ2_bzCompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } send.send(content).unwrap(); }) }).buffer_unordered(threads) .for_each(|_content| { Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); drop(send); let mut collection: Vec<Tcontent> = recv.iter().collect(); collection.sort_by_key(|content| content.order); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); for content in collection { buffer_output.extend(&content.buffer_output[0..content.output_size as usize]); } buf_write.write_all(&buffer_output).unwrap(); std::fs::remove_file(file_name).unwrap(); } else if file_action == "decompress" { let decompressed_file_name = &file_name.to_owned()[..file_name.len()-4]; let mut buf_write = File::create(decompressed_file_name).unwrap(); let mut buffer_input = vec![]; let mut buffer_output = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut queue_blocks: Vec<(usize, usize)> = Vec::new(); let mut counter = 0; while bytes_left > 0 { pos_init = pos_end; pos_end += { let buffer_slice; if buffer_input.len() > block_size+10000 { if (pos_init+block_size+10000) > buffer_input.len() { buffer_slice = &buffer_input[pos_init+10..]; }else{ buffer_slice = &buffer_input[pos_init+10..pos_init+block_size+10000]; } }else{ buffer_slice = &buffer_input[pos_init+10..]; } let ret = buffer_slice.windows(10).position(|window| window == b"BZh91AY&SY"); let pos = match ret { Some(i) => i+10, None => buffer_input.len()-pos_init, }; pos }; bytes_left -= pos_end-pos_init; queue_blocks.push((pos_init, pos_end)); } let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if counter >= queue_blocks.len() { return Ok(Async::Ready(None)); } let buffer_slice = &buffer_input[queue_blocks[counter].0..queue_blocks[counter].1]; let content = Tcontent { order: counter, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; block_size], output_size: 0, }; counter += 1; Ok(Async::Ready(Some(content))) }); let (collection_send, collection_recv) = unbounded(); let (send, recv) = (collection_send.clone(), collection_recv.clone()); let pipeline = processing_stream .map(move |mut content: Tcontent| { let send = collection_send.clone(); spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzDecompressInit(&mut bz_buffer as *mut _, 0, 0); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzDecompress(&mut bz_buffer as *mut _); bzip2_sys::BZ2_bzDecompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } send.send(content).unwrap(); }) }).buffer_unordered(threads) .for_each(|_| { Ok(())}) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); drop(send); let mut collection: Vec<Tcontent> = recv.iter().collect(); collection.sort_by_key(|content| content.order); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); for content in collection { buffer_output.extend(&content.buffer_output[0..content.output_size as usize]); } buf_write.write_all(&buffer_output).unwrap(); std::fs::remove_file(file_name).unwrap(); } } pub fn tokio_io(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let block_size = 900000; let mut pos_init: usize = 0; let mut pos_end = 0; let mut bytes_left: usize = file.metadata().unwrap().len() as usize; let mut order = 0; let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if bytes_left <= 0 { return Ok(Async::Ready(None)); } pos_init = pos_end; pos_end += if bytes_left < block_size { file.metadata().unwrap().len() as usize-pos_end } else { block_size }; bytes_left -= pos_end-pos_init; let mut buffer_slice: Vec<u8> = vec![0; pos_end-pos_init]; file.read(&mut buffer_slice).unwrap(); let content = Tcontent { order, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; (buffer_slice.len() as f64 *1.01) as usize+600], output_size: 0, }; order += 1; Ok(Async::Ready(Some(content))) }); let pipeline = processing_stream .map(move |mut content: Tcontent| { spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzCompressInit(&mut bz_buffer as *mut _, 9, 0, 30); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzCompress(&mut bz_buffer as *mut _, bzip2_sys::BZ_FINISH as _); bzip2_sys::BZ2_bzCompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } content }) }) .buffered(threads) .for_each(move |content: Tcontent| { buf_write.write(&content.buffer_output[0..content.output_size as usize]).unwrap(); Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); std::fs::remove_file(file_name).unwrap(); } else if file_action == "decompress" { let decompressed_file_name = &file_name.to_owned()[..file_name.len()-4]; let mut buf_write = File::create(decompressed_file_name).unwrap(); let mut buffer_input = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut queue_blocks: Vec<(usize, usize)> = Vec::new(); let mut counter = 0; while bytes_left > 0 { pos_init = pos_end; pos_end += { let buffer_slice; if buffer_input.len() > block_size+10000 { if (pos_init+block_size+10000) > buffer_input.len() { buffer_slice = &buffer_input[pos_init+10..]; }else{ buffer_slice = &buffer_input[pos_init+10..pos_init+block_size+10000]; } }else{ buffer_slice = &buffer_input[pos_init+10..]; } let ret = buffer_slice.windows(10).position(|window| window == b"BZh91AY&SY"); let pos = match ret { Some(i) => i+10, None => buffer_input.len()-pos_init, }; pos }; bytes_left -= pos_end-pos_init; queue_blocks.push((pos_init, pos_end)); } let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if counter >= queue_blocks.len() { return Ok(Async::Ready(None)); } let buffer_slice = &buffer_input[queue_blocks[counter].0..queue_blocks[counter].1]; let content = Tcontent { order: counter, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; block_size], output_size: 0, }; counter += 1; Ok(Async::Ready(Some(content))) }); let pipeline = processing_stream .map(move |mut content: Tcontent| { spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzDecompressInit(&mut bz_buffer as *mut _, 0, 0); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzDecompress(&mut bz_buffer as *mut _); bzip2_sys::BZ2_bzDecompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } content }) }) .buffered(threads) .for_each(move |content: Tcontent| { buf_write.write(&content.buffer_output[0..content.output_size as usize]).unwrap(); Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); std::fs::remove_file(file_name).unwrap(); } }
use std::mem; use std::fs::File; use std::io::prelude::*; use std::time::{SystemTime}; use {bzip2_sys}; use crossbeam_channel::{unbounded}; use{ futures::future::lazy, futures::sync::*, futures::{stream, Future, Stream}, tokio::prelude::*, }; struct Tcontent { order: usize, buffer_input: Vec<u8>, buffer_output: Vec<u8>, output_size: u32, } macro_rules! spawn_return { ($block:expr) => {{ let (sender, receiver) = oneshot::channel::<_>(); tokio::spawn(lazy(move || { let result = $block; sender.send(result).ok(); Ok(()) })); receiver }}; }
pub fn tokio_io(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let block_size = 900000; let mut pos_init: usize = 0; let mut pos_end = 0; let mut bytes_left: usize = file.metadata().unwrap().len() as usize; let mut order = 0; let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if bytes_left <= 0 { return Ok(Async::Ready(None)); } pos_init = pos_end; pos_end += if bytes_left < block_size { file.metadata().unwrap().len() as usize-pos_end } else { block_size }; bytes_left -= pos_end-pos_init; let mut buffer_slice: Vec<u8> = vec![0; pos_end-pos_init]; file.read(&mut buffer_slice).unwrap(); let content = Tcontent { order, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; (buffer_slice.len() as f64 *1.01) as usize+600], output_size: 0, }; order += 1; Ok(Async::Ready(Some(content))) }); let pipeline = processing_stream .map(move |mut content: Tcontent| { spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzCompressInit(&mut bz_buffer as *mut _, 9, 0, 30); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzCompress(&mut bz_buffer as *mut _, bzip2_sys::BZ_FINISH as _); bzip2_sys::BZ2_bzCompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } content }) }) .buffered(threads) .for_each(move |content: Tcontent| { buf_write.write(&content.buffer_output[0..content.output_size as usize]).unwrap(); Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); std::fs::remove_file(file_name).unwrap(); } else if file_action == "decompress" { let decompressed_file_name = &file_name.to_owned()[..file_name.len()-4]; let mut buf_write = File::create(decompressed_file_name).unwrap(); let mut buffer_input = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut queue_blocks: Vec<(usize, usize)> = Vec::new(); let mut counter = 0; while bytes_left > 0 { pos_init = pos_end; pos_end += { let buffer_slice; if buffer_input.len() > block_size+10000 { if (pos_init+block_size+10000) > buffer_input.len() { buffer_slice = &buffer_input[pos_init+10..]; }else{ buffer_slice = &buffer_input[pos_init+10..pos_init+block_size+10000]; } }else{ buffer_slice = &buffer_input[pos_init+10..]; } let ret = buffer_slice.windows(10).position(|window| window == b"BZh91AY&SY"); let pos = match ret { Some(i) => i+10, None => buffer_input.len()-pos_init, }; pos }; bytes_left -= pos_end-pos_init; queue_blocks.push((pos_init, pos_end)); } let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if counter >= queue_blocks.len() { return Ok(Async::Ready(None)); } let buffer_slice = &buffer_input[queue_blocks[counter].0..queue_blocks[counter].1]; let content = Tcontent { order: counter, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; block_size], output_size: 0, }; counter += 1; Ok(Async::Ready(Some(content))) }); let pipeline = processing_stream .map(move |mut content: Tcontent| { spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzDecompressInit(&mut bz_buffer as *mut _, 0, 0); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzDecompress(&mut bz_buffer as *mut _); bzip2_sys::BZ2_bzDecompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } content }) }) .buffered(threads) .for_each(move |content: Tcontent| { buf_write.write(&content.buffer_output[0..content.output_size as usize]).unwrap(); Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); std::fs::remove_file(file_name).unwrap(); } }
pub fn tokio(threads: usize, file_action: &str, file_name: &str,) { let mut file = File::open(file_name).expect("No file found."); if file_action == "compress" { let compressed_file_name = file_name.to_owned() + &".bz2"; let mut buf_write = File::create(compressed_file_name).unwrap(); let mut buffer_input = vec![]; let mut buffer_output = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize = 0; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut order = 0; let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if bytes_left <= 0 { return Ok(Async::Ready(None)); } pos_init = pos_end; pos_end += if bytes_left < block_size { buffer_input.len()-pos_end } else { block_size }; bytes_left -= pos_end-pos_init; let buffer_slice = &buffer_input[pos_init..pos_end]; let content = Tcontent { order, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; (buffer_slice.len() as f64 *1.01) as usize+600], output_size: 0, }; order += 1; Ok(Async::Ready(Some(content))) }); let (collection_send, collection_recv) = unbounded(); let (send, recv) = (collection_send.clone(), collection_recv.clone()); let pipeline = processing_stream .map(move |mut content: Tcontent| { let send = collection_send.clone(); spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzCompressInit(&mut bz_buffer as *mut _, 9, 0, 30); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzCompress(&mut bz_buffer as *mut _, bzip2_sys::BZ_FINISH as _); bzip2_sys::BZ2_bzCompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } send.send(content).unwrap(); }) }).buffer_unordered(threads) .for_each(|_content| { Ok(()) }) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); drop(send); let mut collection: Vec<Tcontent> = recv.iter().collect(); collection.sort_by_key(|content| content.order); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); for content in collection { buffer_output.extend(&content.buffer_output[0..content.output_size as usize]); } buf_write.write_all(&buffer_output).unwrap(); std::fs::remove_file(file_name).unwrap(); } else if file_action == "decompress" { let decompressed_file_name = &file_name.to_owned()[..file_name.len()-4]; let mut buf_write = File::create(decompressed_file_name).unwrap(); let mut buffer_input = vec![]; let mut buffer_output = vec![]; file.read_to_end(&mut buffer_input).unwrap(); let block_size = 900000; let mut pos_init: usize; let mut pos_end = 0; let mut bytes_left = buffer_input.len(); let mut queue_blocks: Vec<(usize, usize)> = Vec::new(); let mut counter = 0; while bytes_left > 0 { pos_init = pos_end; pos_end += { let buffer_slice; if buffer_input.len() > block_size+10000 { if (pos_init+block_size+10000) > buffer_input.len() { buffer_slice = &buffer_input[pos_init+10..]; }else{ buffer_slice = &buffer_input[pos_init+10..pos_init+block_size+10000]; } }else{ buffer_slice = &buffer_input[pos_init+10..]; } let ret = buffer_slice.windows(10).position(|window| window == b"BZh91AY&SY"); let pos = match ret { Some(i) => i+10, None => buffer_input.len()-pos_init, }; pos }; bytes_left -= pos_end-pos_init; queue_blocks.push((pos_init, pos_end)); } let start = SystemTime::now(); let processing_stream = stream::poll_fn(move || -> Poll<Option<Tcontent>,futures::sync::oneshot::Canceled> { if counter >= queue_blocks.len() { return Ok(Async::Ready(None)); } let buffer_slice = &buffer_input[queue_blocks[counter].0..queue_blocks[counter].1]; let content = Tcontent { order: counter, buffer_input: buffer_slice.to_vec().clone(), buffer_output: vec![0; block_size], output_size: 0, }; counter += 1; Ok(Async::Ready(Some(content))) }); let (collection_send, collection_recv) = unbounded(); let (send, recv) = (collection_send.clone(), collection_recv.clone()); let pipeline = processing_stream .map(move |mut content: Tcontent| { let send = collection_send.clone(); spawn_return!({ unsafe{ let mut bz_buffer: bzip2_sys::bz_stream = mem::zeroed(); bzip2_sys::BZ2_bzDecompressInit(&mut bz_buffer as *mut _, 0, 0); bz_buffer.next_in = content.buffer_input.as_ptr() as *mut _; bz_buffer.avail_in = content.buffer_input.len() as _; bz_buffer.next_out = content.buffer_output.as_mut_ptr() as *mut _; bz_buffer.avail_out = content.buffer_output.len() as _; bzip2_sys::BZ2_bzDecompress(&mut bz_buffer as *mut _); bzip2_sys::BZ2_bzDecompressEnd(&mut bz_buffer as *mut _); content.output_size = bz_buffer.total_out_lo32; } send.send(content).unwrap(); }) }).buffer_unordered(threads) .for_each(|_| { Ok(())}) .map_err(|e| println!("Error = {:?}", e)); tokio::run(pipeline); drop(send); let mut collection: Vec<Tcontent> = recv.iter().collect(); collection.sort_by_key(|content| content.order); let system_duration = start.elapsed().expect("Failed to get render time?"); let in_sec = system_duration.as_secs() as f64 + system_duration.subsec_nanos() as f64 * 1e-9; println!("Execution time: {} sec", in_sec); for content in collection { buffer_output.extend(&content.buffer_output[0..content.output_size as usize]); } buf_write.write_all(&buffer_output).unwrap(); std::fs::remove_file(file_name).unwrap(); } }
function_block-full_function
[ { "content": "struct Tcontent {\n\n\torder: u64,\n\n\tbuffer_input: Vec<u8>,\n\n\tbuffer_output: Vec<u8>,\n\n\toutput_size: u32,\n\n}\n\n\n\npub struct Reorder {\n\n storage: BTreeMap<u64, Tcontent>,\n\n}\n\n\n\nimpl Reorder {\n\n fn new() -> Reorder {\n\n Reorder {\n\n storage: BTreeMap...
Rust
kernel/src/process.rs
liva/node-replicated-kernel
2d953c3a984b0c3a48b6368062b6abdf5146da2a
use alloc::boxed::Box; use alloc::format; use alloc::string::{String, ToString}; use alloc::sync::Arc; use alloc::vec::Vec; use core::convert::TryInto; use cstr_core::CStr; use custom_error::custom_error; use kpi::process::FrameId; use crate::arch::memory::paddr_to_kernel_vaddr; use crate::arch::memory::LARGE_PAGE_SIZE; use crate::arch::process::UserPtr; use crate::arch::Module; use crate::error::KError; use crate::fs::Fd; use crate::kcb; use crate::memory::vspace::AddressSpace; use crate::memory::KernelAllocator; use crate::memory::{Frame, PhysicalPageProvider, VAddr}; use crate::prelude::overlaps; use crate::{mlnr, nr, round_up}; #[derive(PartialEq, Clone, Debug)] pub struct KernSlice { pub buffer: Arc<[u8]>, } impl KernSlice { pub fn new(base: u64, len: usize) -> KernSlice { let buffer = Arc::<[u8]>::new_uninit_slice(len); let mut buffer = unsafe { buffer.assume_init() }; let mut user_ptr = VAddr::from(base); let slice_ptr = UserPtr::new(&mut user_ptr); let user_slice: &mut [u8] = unsafe { core::slice::from_raw_parts_mut(slice_ptr.as_mut_ptr(), len) }; unsafe { Arc::get_mut_unchecked(&mut buffer).copy_from_slice(&user_slice[0..len]) }; KernSlice { buffer } } } pub fn userptr_to_str(useraddr: u64) -> Result<String, KError> { let mut user_ptr = VAddr::from(useraddr); let str_ptr = UserPtr::new(&mut user_ptr); unsafe { match CStr::from_ptr(str_ptr.as_ptr()).to_str() { Ok(path) => { if !path.is_ascii() || path.is_empty() { return Err(KError::NotSupported); } return Ok(String::from(path)); } Err(_) => return Err(KError::NotSupported), } } } pub type Pid = u64; pub type Eid = u64; custom_error! { #[derive(PartialEq, Clone)] pub ProcessError ProcessCreate{desc: String} = "Unable to create process: {desc}", ProcessNotSet = "The core has no current process set.", NoProcessFoundForPid = "No process was associated with the given Pid.", UnableToLoad = "Couldn't load process, invalid ELF file?", UnableToParseElf = "Couldn't parse ELF file, invalid?", NoExecutorAllocated = "We never allocated executors for this affinity region and process (need to fill cache).", ExecutorCacheExhausted = "The executor cache for given affinity is empty (need to refill)", InvalidGlobalThreadId = "Specified an invalid core", ExecutorNoLongerValid = "The excutor was removed from the current core.", ExecutorAlreadyBorrowed = "The executor on the core was already borrowed (that's a bug).", NotEnoughMemory = "Unable to reserve memory for internal process data-structures.", InvalidFrameId = "The provided FrameId is not registered with the process", } impl From<&str> for ProcessError { fn from(_err: &str) -> Self { ProcessError::UnableToLoad } } impl From<alloc::collections::TryReserveError> for ProcessError { fn from(_err: alloc::collections::TryReserveError) -> Self { ProcessError::NotEnoughMemory } } pub trait Process { type E: Executor + Copy + Sync + Send; type A: AddressSpace; fn new(module: &Module, pid: Pid, writable_sections: Vec<Frame>) -> Result<Self, ProcessError> where Self: core::marker::Sized; fn try_reserve_executors( &self, how_many: usize, affinity: topology::NodeId, ) -> Result<(), alloc::collections::TryReserveError>; fn allocate_executors(&mut self, frame: Frame) -> Result<usize, ProcessError>; fn vspace_mut(&mut self) -> &mut Self::A; fn vspace(&self) -> &Self::A; fn get_executor(&mut self, for_region: topology::NodeId) -> Result<Box<Self::E>, ProcessError>; fn allocate_fd(&mut self) -> Option<(u64, &mut Fd)>; fn deallocate_fd(&mut self, fd: usize) -> usize; fn get_fd(&self, index: usize) -> &Fd; fn pinfo(&self) -> &kpi::process::ProcessInfo; fn add_frame(&mut self, frame: Frame) -> Result<FrameId, ProcessError>; fn get_frame(&mut self, frame_id: FrameId) -> Result<Frame, ProcessError>; } pub trait ResumeHandle { unsafe fn resume(self) -> !; } pub trait Executor { type Resumer: ResumeHandle; fn id(&self) -> Eid; fn pid(&self) -> Pid; fn start(&self) -> Self::Resumer; fn resume(&self) -> Self::Resumer; fn upcall(&self, vector: u64, exception: u64) -> Self::Resumer; fn maybe_switch_vspace(&self); fn vcpu_kernel(&self) -> *mut kpi::arch::VirtualCpu; } struct DataSecAllocator { offset: VAddr, frames: Vec<(usize, Frame)>, } impl DataSecAllocator { fn finish(self) -> Vec<Frame> { self.frames .into_iter() .map(|(_offset, base)| base) .collect() } } impl elfloader::ElfLoader for DataSecAllocator { fn allocate(&mut self, load_headers: elfloader::LoadableHeaders) -> Result<(), &'static str> { for header in load_headers.into_iter() { let base = header.virtual_addr(); let size = header.mem_size() as usize; let flags = header.flags(); let page_mask = (LARGE_PAGE_SIZE - 1) as u64; let page_base: VAddr = VAddr::from(base & !page_mask); let size_page = round_up!(size + (base & page_mask) as usize, LARGE_PAGE_SIZE as usize); assert!(size_page >= size); assert_eq!(size_page % LARGE_PAGE_SIZE, 0); assert_eq!(page_base % LARGE_PAGE_SIZE, 0); if flags.is_write() { trace!( "base = {:#x} size = {:#x} page_base = {:#x} size_page = {:#x}", base, size, page_base, size_page ); let large_pages = size_page / LARGE_PAGE_SIZE; KernelAllocator::try_refill_tcache(0, large_pages).expect("Refill didn't work"); let kcb = crate::kcb::get_kcb(); let mut pmanager = kcb.mem_manager(); for i in 0..large_pages { let frame = pmanager .allocate_large_page() .expect("We refilled so allocation should work."); trace!( "add to self.frames (elf_va={:#x}, pa={:#x})", page_base.as_usize() + i * LARGE_PAGE_SIZE, frame.base ); self.frames .push((page_base.as_usize() + i * LARGE_PAGE_SIZE, frame)); } } } Ok(()) } fn load( &mut self, flags: elfloader::Flags, destination: u64, region: &[u8], ) -> Result<(), &'static str> { debug!( "load(): destination = {:#x} region.len() = {:#x}", destination, region.len(), ); if flags.is_write() { let mut destination: usize = destination.try_into().unwrap(); let mut region_remaining = region.len(); let mut region = region; for (elf_begin, frame) in self.frames.iter() { trace!( "load(): into process vspace at {:#x} #bytes {:#x} offset_in_frame = {:#x}", destination, region.len(), *elf_begin ); let range_frame_elf = *elf_begin..*elf_begin + frame.size; let range_region_elf = destination..destination + region_remaining; if overlaps(&range_region_elf, &range_frame_elf) { trace!( "The frame overlaps with copy region (range_frame_elf={:x?} range_region_elf={:x?})", range_frame_elf, range_region_elf ); let copy_start = core::cmp::max(range_frame_elf.start, range_region_elf.start) - destination; let copy_end = core::cmp::min(range_frame_elf.end, range_region_elf.end) - destination; let region_to_copy = &region[copy_start..copy_end]; trace!("copy range = {:x?}", copy_start..copy_end); let copy_in_frame_start = destination - *elf_begin; let frame_vaddr = paddr_to_kernel_vaddr(frame.base); unsafe { core::ptr::copy_nonoverlapping( region_to_copy.as_ptr(), frame_vaddr.as_mut_ptr::<u8>().add(copy_in_frame_start), copy_end - copy_start, ); trace!( "Copied {} bytes from {:p} to {:p}", copy_end - copy_start, region_to_copy.as_ptr(), frame_vaddr.as_mut_ptr::<u8>().add(copy_start) ); destination += copy_end - copy_start; region = &region[copy_end..]; region_remaining -= copy_end - copy_start; } } } } Ok(()) } fn relocate(&mut self, entry: &elfloader::Rela<elfloader::P64>) -> Result<(), &'static str> { let addr = self.offset + entry.get_offset(); for (pheader_offset, frame) in self.frames.iter() { let elf_vbase = self.offset + *pheader_offset & !(LARGE_PAGE_SIZE - 1); if addr >= elf_vbase && addr <= elf_vbase + frame.size() { let kernel_vaddr = paddr_to_kernel_vaddr(frame.base); let offset_in_frame = addr - elf_vbase; let kernel_addr = kernel_vaddr + offset_in_frame; trace!( "DataSecAllocator relocation paddr {:#x} kernel_addr {:#x}", offset_in_frame + frame.base.as_u64(), kernel_addr ); use elfloader::TypeRela64; if let TypeRela64::R_RELATIVE = TypeRela64::from(entry.get_type()) { unsafe { *(kernel_addr.as_mut_ptr::<u64>()) = self.offset.as_u64() + entry.get_addend(); } } else { return Err("Can only handle R_RELATIVE for relocation"); } } } Ok(()) } } pub fn make_process(binary: &'static str) -> Result<Pid, KError> { KernelAllocator::try_refill_tcache(7, 1)?; let kcb = kcb::get_kcb(); let mut mod_file = None; for module in &kcb.arch.kernel_args().modules { if module.name() == binary { mod_file = Some(module); } } let mod_file = mod_file.expect(format!("Couldn't find '{}' binary.", binary).as_str()); info!( "binary={} cmdline={} module={:?}", binary, kcb.cmdline.test_cmdline, mod_file ); let elf_module = unsafe { elfloader::ElfBinary::new(mod_file.name(), mod_file.as_slice()) .map_err(|_e| ProcessError::UnableToParseElf)? }; let offset = if !elf_module.is_pie() { VAddr::zero() } else { VAddr::from(0x20_0000_0000usize) }; let mut data_sec_loader = DataSecAllocator { offset, frames: Vec::with_capacity(2), }; elf_module .load(&mut data_sec_loader) .map_err(|_e| ProcessError::UnableToLoad)?; let data_frames: Vec<Frame> = data_sec_loader.finish(); kcb.replica .as_ref() .map_or(Err(KError::ReplicaNotSet), |(replica, token)| { let response = replica.execute_mut(nr::Op::ProcCreate(&mod_file, data_frames), *token); match response { Ok(nr::NodeResult::ProcCreated(pid)) => { if cfg!(feature = "mlnrfs") { match mlnr::MlnrKernelNode::add_process(pid) { Ok(pid) => Ok(pid.0), Err(e) => unreachable!("{}", e), } } else { Ok(pid) } } _ => unreachable!("Got unexpected response"), } }) } pub fn allocate_dispatchers(pid: Pid) -> Result<(), KError> { trace!("Allocate dispatchers"); let mut create_per_region: Vec<(topology::NodeId, usize)> = Vec::with_capacity(topology::MACHINE_TOPOLOGY.num_nodes() + 1); if topology::MACHINE_TOPOLOGY.num_nodes() > 0 { for node in topology::MACHINE_TOPOLOGY.nodes() { let threads = node.threads().count(); create_per_region.push((node.id, threads)); } } else { create_per_region.push((0, topology::MACHINE_TOPOLOGY.num_threads())); } for (affinity, to_create) in create_per_region { let mut dispatchers_created = 0; while dispatchers_created < to_create { KernelAllocator::try_refill_tcache(20, 1)?; let mut frame = { let kcb = crate::kcb::get_kcb(); kcb.physical_memory.gmanager.unwrap().node_caches[affinity as usize] .lock() .allocate_large_page()? }; unsafe { frame.zero(); } let kcb = crate::kcb::get_kcb(); kcb.replica .as_ref() .map_or(Err(KError::ReplicaNotSet), |(replica, token)| { let response = replica.execute_mut(nr::Op::DispatcherAllocation(pid, frame), *token)?; match response { nr::NodeResult::ExecutorsCreated(how_many) => { assert!(how_many > 0); dispatchers_created += how_many; Ok(how_many) } _ => unreachable!("Got unexpected response"), } }) .unwrap(); } } debug!("Allocated dispatchers"); Ok(()) }
use alloc::boxed::Box; use alloc::format; use alloc::string::{String, ToString}; use alloc::sync::Arc; use alloc::vec::Vec; use core::convert::TryInto; use cstr_core::CStr; use custom_error::custom_error; use kpi::process::FrameId; use crate::arch::memory::paddr_to_kernel_vaddr; use crate::arch::memory::LARGE_PAGE_SIZE; use crate::arch::process::UserPtr; use crate::arch::Module; use crate::error::KError; use crate::fs::Fd; use crate::kcb; use crate::memory::vspace::AddressSpace; use crate::memory::KernelAllocator; use crate::memory::{Frame, PhysicalPageProvider, VAddr}; use crate::prelude::overlaps; use crate::{mlnr, nr, round_up}; #[derive(PartialEq, Clone, Debug)] pub struct KernSlice { pub buffer: Arc<[u8]>, } impl KernSlice { pub fn new(base: u64, len: usize) -> KernSlice { let buffer = Arc::<[u8]>::new_uninit_slice(len); let mut buffer = unsafe { buffer.assume_init() }; let mut user_ptr = VAddr::from(base); let slice_ptr = UserPtr::new(&mut user_ptr); let user_slice: &mut [u8] = unsafe { core::slice::from_raw_parts_mut(slice_ptr.as_mut_ptr(), len) }; unsafe { Arc::get_mut_unchecked(&mut buffer).copy_from_slice(&user_slice[0..len]) }; KernSlice { buffer } } } pub fn userptr_to_str(useraddr: u64) -> Result<String, KError> { let mut user_ptr = VAddr::from(useraddr); let str_ptr = UserPtr::new(&mut user_ptr); unsafe { match CStr::from_ptr(str_ptr.as_ptr()).to_str() { Ok(path) => { if !path.is_ascii() || path.is_empty() { return Err(KError::NotSupported); } return Ok(String::from(path)); } Err(_) => return Err(KError::NotSupported), } } } pub type Pid = u64; pub type Eid = u64; custom_error! { #[derive(PartialEq, Clone)] pub ProcessError ProcessCreate{desc: String} = "Unable to create process: {desc}", ProcessNotSet = "The core has no current process set.", NoProcessFoundForPid = "No process was associated with the given Pid.", UnableToLoad = "Couldn't load process, invalid ELF file?", UnableToParseElf = "Couldn't parse ELF file, invalid?", NoExecutorAllocated = "We never allocated executors for this affinity region and process (need to fill cache).", ExecutorCacheExhausted = "The executor cache for given affinity is empty (need to refill)", InvalidGlobalThreadId = "Specified an invalid core", ExecutorNoLongerValid = "The excutor was removed from the current core.", ExecutorAlreadyBorrowed = "The executor on the core was already borrowed (that's a bug).", NotEnoughMemory = "Unable to reserve memory for internal process data-structures.", InvalidFrameId = "The provided FrameId is not registered with the process", } impl From<&str> for ProcessError { fn from(_err: &str) -> Self { ProcessError::UnableToLoad } } impl From<alloc::collections::TryReserveError> for ProcessError { fn from(_err: alloc::collections::TryReserveError) -> Self { ProcessError::NotEnoughMemory } } pub trait Process { type E: Executor + Copy + Sync + Send; type A: AddressSpace; fn new(module: &Module, pid: Pid, writable_sections: Vec<Frame>) -> Result<Self, ProcessError> where Self: core::marker::Sized; fn try_reserve_executors( &self, how_many: usize, affinity: topology::NodeId, ) -> Result<(), alloc::collections::TryReserveError>; fn allocate_executors(&mut self, frame: Frame) -> Result<usize, ProcessError>; fn vspace_mut(&mut self) -> &mut Self::A; fn vspace(&self) -> &Self::A; fn get_executor(&mut self, for_region: topology::NodeId) -> Result<Box<Self::E>, ProcessError>; fn allocate_fd(&mut self) -> Option<(u64, &mut Fd)>; fn deallocate_fd(&mut self, fd: usize) -> usize; fn get_fd(&self, index: usize) -> &Fd; fn pinfo(&self) -> &kpi::process::ProcessInfo; fn add_frame(&mut self, frame: Frame) -> Result<FrameId, ProcessError>; fn get_frame(&mut self, frame_id: FrameId) -> Result<Frame, ProcessError>; } pub trait ResumeHandle { unsafe fn resume(self) -> !; } pub trait Executor { type Resumer: ResumeHandle; fn id(&self) -> Eid; fn pid(&self) -> Pid; fn start(&self) -> Self::Resumer; fn resume(&self) -> Self::Resumer; fn upcall(&self, vector: u64, exception: u64) -> Self::Resumer; fn maybe_switch_vspace(&self); fn vcpu_kernel(&self) -> *mut kpi::arch::VirtualCpu; } struct DataSecAllocator { offset: VAddr, frames: Vec<(usize, Frame)>, } impl DataSecAllocator { fn finish(self) -> Vec<Frame> { self.frames .into_iter() .map(|(_offset, base)| base) .collect() } } impl elfloader::ElfLoader for DataSecAllocator { fn allocate(&mut self, load_headers: elfloader::LoadableHeaders) -> Result<(), &'static str> { for header in load_headers.into_iter() { let base = header.virtual_addr(); let size = header.mem_size() as usize; let flags = header.flags(); let page_mask = (LARGE_PAGE_SIZE - 1) as u64; let page_base: VAddr = VAddr::from(base & !page_mask); let size_page = round_up!(size + (base & page_mask) as usize, LARGE_PAGE_SIZE as usize); assert!(size_page >= size); assert_eq!(size_page % LARGE_PAGE_SIZE, 0); assert_eq!(page_base % LARGE_PAGE_SIZE, 0); if flags.is_write() { trace!( "base = {:#x} size = {:#x} page_base = {:#x} size_page = {:#x}", base, size, page_base, size_page ); let large_pages = size_page / LARGE_PAGE_SIZE; KernelAllocator::try_refill_tcache(0, large_pages).expect("Refill didn't work"); let kcb = crate::kcb::get_kcb(); let mut pmanager = kcb.mem_manager(); for i in 0..large_pages { let frame = pmanager .allocate_large_page() .expect("We refilled so allocation should work."); trace!( "add to self.frames (elf_va={:#x}, pa={:#x})", page_base.as_usize() + i * LARGE_PAGE_SIZE, frame.base ); self.frames .push((page_base.as_usize() + i * LARGE_PAGE_SIZE, frame)); } } } Ok(()) } fn load( &mut self, flags: elfloader::Flags, destination: u64, region: &[u8], ) -> Result<(), &'static str> { debug!( "load(): destination = {:#x} region.len() = {:#x}", destination, region.len(), ); if flags.is_write() { let mut destination: usize = destination.try_into().unwrap(); let mut region_remaining = region.len(); let mut region = region; for (elf_begin, frame) in self.frames.iter() { trace!( "load(): into process vspace at {:#x} #bytes {:#x} offset_in_frame = {:#x}", destination, region.len(), *elf_begin ); let range_frame_elf = *elf_begin..*elf_begin + frame.size; let range_region_elf = destination..destination + region_remaining; if overlaps(&range_region_elf, &range_frame_elf) { trace!( "The frame overlaps with copy region (range_frame_elf={:x?} range_region_elf={:x?})", range_frame_elf, range_region_elf ); let copy_start = core::cmp::max(range_frame_elf.start, range_region_elf.start) - destination; let copy_end = core::cmp::min(range_frame_elf.end, range_region_elf.end) - destination; let region_to_copy = &region[copy_start..copy_end]; trace!("copy range = {:x?}", copy_start..copy_end); let copy_in_frame_start = destination - *elf_begin; let frame_vaddr = paddr_to_kernel_vaddr(frame.base); unsafe { core::ptr::copy_nonoverlapping( region_to_copy.as_ptr(), frame_vaddr.as_mut_ptr::<u8>().add(copy_in_frame_start), copy_end - copy_start, ); trace!( "Copied {} bytes from {:p} to {:p}", copy_end - copy_start, region_to_copy.as_ptr(), frame_vaddr.as_mut_ptr::<u8>().add(copy_start) ); destination += copy_end - copy_start; region = &region[copy_end..]; region_remaining -= copy_end - copy_start; } } } } Ok(()) } fn relocate(&mut self, entry: &elfloader::Rela<elfloader::P64>) -> Result<(), &'static str> { let addr = self.offset + entry.get_offset(); for (pheader_offset, frame) in self.frames.iter() { let elf_vbase = self.offset + *pheader_offset & !(LARGE_PAGE_SIZE - 1); if addr >= elf_vbase && addr <= elf_vbase + frame.size() { let kernel_vaddr = paddr_to_kernel_vaddr(frame.base); let offset_in_frame = addr - elf_vbase; let kernel_addr = kernel_vaddr + offset_in_frame; trace!( "DataSecAllocator relocation paddr {:#x} kernel_addr {:#x}", offset_in_frame + frame.base.as_u64(), kernel_addr ); use elfloader::TypeRela64; if let TypeRela64::R_RELATIVE = TypeRela64::from(entry.get_type()) { unsafe { *(kernel_addr.as_mut_ptr::<u64>()) = self.offset.as_u64() + entry.get_addend(); } } else { return Err("Can only handle R_RELATIVE for relocation"); } } } Ok(()) } }
pub fn allocate_dispatchers(pid: Pid) -> Result<(), KError> { trace!("Allocate dispatchers"); let mut create_per_region: Vec<(topology::NodeId, usize)> = Vec::with_capacity(topology::MACHINE_TOPOLOGY.num_nodes() + 1); if topology::MACHINE_TOPOLOGY.num_nodes() > 0 { for node in topology::MACHINE_TOPOLOGY.nodes() { let threads = node.threads().count(); create_per_region.push((node.id, threads)); } } else { create_per_region.push((0, topology::MACHINE_TOPOLOGY.num_threads())); } for (affinity, to_create) in create_per_region { let mut dispatchers_created = 0; while dispatchers_created < to_create { KernelAllocator::try_refill_tcache(20, 1)?; let mut frame = { let kcb = crate::kcb::get_kcb(); kcb.physical_memory.gmanager.unwrap().node_caches[affinity as usize] .lock() .allocate_large_page()? }; unsafe { frame.zero(); } let kcb = crate::kcb::get_kcb(); kcb.replica .as_ref() .map_or(Err(KError::ReplicaNotSet), |(replica, token)| { let response = replica.execute_mut(nr::Op::DispatcherAllocation(pid, frame), *token)?; match response { nr::NodeResult::ExecutorsCreated(how_many) => { assert!(how_many > 0); dispatchers_created += how_many; Ok(how_many) } _ => unreachable!("Got unexpected response"), } }) .unwrap(); } } debug!("Allocated dispatchers"); Ok(()) }
pub fn make_process(binary: &'static str) -> Result<Pid, KError> { KernelAllocator::try_refill_tcache(7, 1)?; let kcb = kcb::get_kcb(); let mut mod_file = None; for module in &kcb.arch.kernel_args().modules { if module.name() == binary { mod_file = Some(module); } } let mod_file = mod_file.expect(format!("Couldn't find '{}' binary.", binary).as_str()); info!( "binary={} cmdline={} module={:?}", binary, kcb.cmdline.test_cmdline, mod_file ); let elf_module = unsafe { elfloader::ElfBinary::new(mod_file.name(), mod_file.as_slice()) .map_err(|_e| ProcessError::UnableToParseElf)? }; let offset = if !elf_module.is_pie() { VAddr::zero() } else { VAddr::from(0x20_0000_0000usize) }; let mut data_sec_loader = DataSecAllocator { offset, frames: Vec::with_capacity(2), }; elf_module .load(&mut data_sec_loader) .map_err(|_e| ProcessError::UnableToLoad)?; let data_frames: Vec<Frame> = data_sec_loader.finish(); kcb.replica .as_ref() .map_or(Err(KError::ReplicaNotSet), |(replica, token)| { let response = replica.execute_mut(nr::Op::ProcCreate(&mod_file, data_frames), *token); match response { Ok(nr::NodeResult::ProcCreated(pid)) => { if cfg!(feature = "mlnrfs") { match mlnr::MlnrKernelNode::add_process(pid) { Ok(pid) => Ok(pid.0), Err(e) => unreachable!("{}", e), } } else { Ok(pid) } } _ => unreachable!("Got unexpected response"), } }) }
function_block-full_function
[ { "content": "/// TODO: This method makes file-operations slow, improve it to use large page sizes. Or maintain a list of\n\n/// (low, high) memory limits per process and check if (base, size) are within the process memory limits.\n\nfn user_virt_addr_valid(pid: Pid, base: u64, size: u64) -> Result<(u64, u64), ...
Rust
src/cfg/global/project.rs
vincent-herlemont/short
805aa75a4605eb9b587c82135ccc8e8883df1192
use crate::cfg::global::setup::{GlobalProjectSetupCfg, SetupName}; use crate::cfg::SetupsCfg; use anyhow::{Context, Result}; use serde::de::{MapAccess, Visitor}; use serde::export::Formatter; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cell::RefCell; use std::fmt; use std::path::{Path, PathBuf}; use std::rc::Rc; type EnvName = String; #[derive(Debug, Serialize, Deserialize)] struct CurrentSetup { #[serde(rename = "setup", skip_serializing_if = "Option::is_none")] pub setup_name: Option<String>, #[serde(rename = "env", skip_serializing_if = "Option::is_none")] pub env_name: Option<EnvName>, } impl CurrentSetup { pub fn new() -> Self { Self { setup_name: None, env_name: None, } } } impl Default for CurrentSetup { fn default() -> Self { Self::new() } } #[derive(Debug, Serialize, Deserialize)] pub struct GlobalProjectCfg { file: PathBuf, #[serde(skip_serializing_if = "Option::is_none")] current: Option<CurrentSetup>, setups: GlobalProjectSetupsCfg, } #[derive(Debug)] pub struct GlobalProjectSetupsCfg(Rc<RefCell<Vec<Rc<RefCell<GlobalProjectSetupCfg>>>>>); impl GlobalProjectSetupsCfg { pub fn new() -> Self { Self(Rc::new(RefCell::new(vec![]))) } pub fn add(&mut self, global_setup_cfg: GlobalProjectSetupCfg) { let mut global_setups_cfg = self.0.borrow_mut(); if global_setups_cfg .iter() .find(|lsc| { let lsc = lsc.borrow(); lsc.name() == global_setup_cfg.name() }) .is_none() { global_setups_cfg.push(Rc::new(RefCell::new(global_setup_cfg))) } } } impl Serialize for GlobalProjectSetupsCfg { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let vec = &self.0.borrow(); let mut seq = serializer.serialize_map(Some(vec.len()))?; for global_setup_cfg in vec.iter() { let global_setup_cfg = global_setup_cfg.borrow(); let name = global_setup_cfg.name(); seq.serialize_entry(name, &*global_setup_cfg)?; } seq.end() } } impl<'de> Deserialize<'de> for GlobalProjectSetupsCfg { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { struct InnerVisitor; impl<'de> Visitor<'de> for InnerVisitor { type Value = GlobalProjectSetupsCfg; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { formatter.write_str("incorrect list of global setup cfg") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut global_setups_cfg = GlobalProjectSetupsCfg::new(); while let Some((setup_name, mut global_setup_cfg)) = map.next_entry::<SetupName, GlobalProjectSetupCfg>()? { global_setup_cfg.set_name(setup_name); global_setups_cfg.add(global_setup_cfg); } Ok(global_setups_cfg) } } deserializer.deserialize_map(InnerVisitor) } } impl GlobalProjectCfg { pub fn new(file: &PathBuf) -> Result<Self> { let mut gp = GlobalProjectCfg { file: PathBuf::new(), current: None, setups: GlobalProjectSetupsCfg::new(), }; gp.set_file(file)?; Ok(gp) } pub fn set_file(&mut self, file: &PathBuf) -> Result<()> { if !file.is_absolute() { return Err(anyhow!(format!( "project file path can not be relative {}", file.to_string_lossy() ))); } if let None = file.file_name() { return Err(anyhow!(format!("project file has no name"))); } self.file = file.clone(); Ok(()) } pub fn file(&self) -> &PathBuf { &self.file } pub fn dir(&self) -> Result<&Path> { self.file.parent().context(format!( "fail to found parent directory of project `{}`", self.file.to_string_lossy() )) } pub fn set_current_setup_name(&mut self, setup_name: SetupName) { self.current.get_or_insert(CurrentSetup::new()).setup_name = Some(setup_name); } pub fn current_setup_name(&self) -> Option<&SetupName> { self.current .as_ref() .map_or(None, |current| current.setup_name.as_ref()) } pub fn set_current_env_name(&mut self, env_name: EnvName) { self.current.get_or_insert(CurrentSetup::new()).env_name = Some(env_name); } pub fn unset_current_env_name(&mut self) { self.current.get_or_insert(CurrentSetup::new()).env_name = None; } pub fn current_env_name(&self) -> Option<&EnvName> { self.current .as_ref() .map_or(None, |current| current.env_name.as_ref()) } pub fn unset_current_setup(&mut self) { self.current = None; } } impl SetupsCfg for GlobalProjectCfg { type Setup = GlobalProjectSetupCfg; fn get_setups(&self) -> Rc<RefCell<Vec<Rc<RefCell<Self::Setup>>>>> { Rc::clone(&self.setups.0) } } impl PartialEq<PathBuf> for GlobalProjectCfg { fn eq(&self, path_buf: &PathBuf) -> bool { self.file().eq(path_buf) } } impl PartialEq<GlobalProjectCfg> for PathBuf { fn eq(&self, path_buf: &GlobalProjectCfg) -> bool { self.eq(&path_buf.file) } } #[cfg(test)] mod test { use std::path::PathBuf; use crate::cfg::global::project::GlobalProjectCfg; use crate::cfg::global::setup::GlobalProjectSetupCfg; use crate::cfg::SetupsCfg; #[test] fn deserialization_serialization_cfg() { let content = r"--- file: path/to/file current: setup: setup_1 setups: test_1: {}"; let cfg = serde_yaml::from_str::<GlobalProjectCfg>(content).unwrap(); let r = serde_yaml::to_string(&cfg).unwrap(); assert_eq!(content, r); } #[test] fn global_update_private_env_dir() { let setup_cfg = GlobalProjectSetupCfg::new("setup".into()); let mut project_cfg = GlobalProjectCfg::new(&"/project".into()).unwrap(); project_cfg.add_setup(setup_cfg); assert!(project_cfg.get_setups().borrow().iter().count().eq(&1)); { let setup_cfg = project_cfg.get_setup(&"setup".into()).unwrap(); setup_cfg .borrow_mut() .set_private_env_dir("/private_env".into()) .unwrap(); } let global_project_setup_cfg_1 = project_cfg.get_setup(&"setup".into()).unwrap(); assert_eq!( global_project_setup_cfg_1 .borrow() .private_env_dir() .unwrap(), &PathBuf::from("/private_env") ); project_cfg.remove_by_name_setup(&"setup".into()); assert!(project_cfg.get_setup(&"setup".into()).is_none()); } }
use crate::cfg::global::setup::{GlobalProjectSetupCfg, SetupName}; use crate::cfg::SetupsCfg; use anyhow::{Context, Result}; use serde::de::{MapAccess, Visitor}; use serde::export::Formatter; use serde::ser::SerializeMap; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::cell::RefCell; use std::fmt; use std::path::{Path, PathBuf}; use std::rc::Rc; type EnvName = String; #[derive(Debug, Serialize, Deserialize)] struct CurrentSetup { #[serde(rename = "setup", skip_serializing_if = "Option::is_none")] pub setup_name: Option<String>, #[serde(rename = "env", skip_serializing_if = "Option::is_none")] pub env_name: Option<EnvName>, } impl CurrentSetup { pub fn new() -> Self { Self { setup_name: None, env_name: None, } } } impl Default for CurrentSetup { fn default() -> Self { Self::new() } } #[derive(Debug, Serialize, Deserialize)] pub struct GlobalProjectCfg { file: PathBuf, #[serde(skip_serializing_if = "Option::is_none")] current: Option<CurrentSetup>, setups: GlobalProjectSetupsCfg, } #[derive(Debug)] pub struct GlobalProjectSetupsCfg(Rc<RefCell<Vec<Rc<RefCell<GlobalProjectSetupCfg>>>>>); impl GlobalProjectSetupsCfg { pub fn new() -> Self { Self(Rc::new(RefCell::new(vec![]))) } pub fn add(&mut self, global_setup_cfg: GlobalProjectSetupCfg) { let mut global_setups_cfg = self.0.borrow_mut(); if global_setups_cfg .iter() .find(|lsc| { let lsc = lsc.borrow(); lsc.name() == globa
} impl Serialize for GlobalProjectSetupsCfg { fn serialize<S>(&self, serializer: S) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error> where S: Serializer, { let vec = &self.0.borrow(); let mut seq = serializer.serialize_map(Some(vec.len()))?; for global_setup_cfg in vec.iter() { let global_setup_cfg = global_setup_cfg.borrow(); let name = global_setup_cfg.name(); seq.serialize_entry(name, &*global_setup_cfg)?; } seq.end() } } impl<'de> Deserialize<'de> for GlobalProjectSetupsCfg { fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error> where D: Deserializer<'de>, { struct InnerVisitor; impl<'de> Visitor<'de> for InnerVisitor { type Value = GlobalProjectSetupsCfg; fn expecting(&self, formatter: &mut Formatter) -> fmt::Result { formatter.write_str("incorrect list of global setup cfg") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: MapAccess<'de>, { let mut global_setups_cfg = GlobalProjectSetupsCfg::new(); while let Some((setup_name, mut global_setup_cfg)) = map.next_entry::<SetupName, GlobalProjectSetupCfg>()? { global_setup_cfg.set_name(setup_name); global_setups_cfg.add(global_setup_cfg); } Ok(global_setups_cfg) } } deserializer.deserialize_map(InnerVisitor) } } impl GlobalProjectCfg { pub fn new(file: &PathBuf) -> Result<Self> { let mut gp = GlobalProjectCfg { file: PathBuf::new(), current: None, setups: GlobalProjectSetupsCfg::new(), }; gp.set_file(file)?; Ok(gp) } pub fn set_file(&mut self, file: &PathBuf) -> Result<()> { if !file.is_absolute() { return Err(anyhow!(format!( "project file path can not be relative {}", file.to_string_lossy() ))); } if let None = file.file_name() { return Err(anyhow!(format!("project file has no name"))); } self.file = file.clone(); Ok(()) } pub fn file(&self) -> &PathBuf { &self.file } pub fn dir(&self) -> Result<&Path> { self.file.parent().context(format!( "fail to found parent directory of project `{}`", self.file.to_string_lossy() )) } pub fn set_current_setup_name(&mut self, setup_name: SetupName) { self.current.get_or_insert(CurrentSetup::new()).setup_name = Some(setup_name); } pub fn current_setup_name(&self) -> Option<&SetupName> { self.current .as_ref() .map_or(None, |current| current.setup_name.as_ref()) } pub fn set_current_env_name(&mut self, env_name: EnvName) { self.current.get_or_insert(CurrentSetup::new()).env_name = Some(env_name); } pub fn unset_current_env_name(&mut self) { self.current.get_or_insert(CurrentSetup::new()).env_name = None; } pub fn current_env_name(&self) -> Option<&EnvName> { self.current .as_ref() .map_or(None, |current| current.env_name.as_ref()) } pub fn unset_current_setup(&mut self) { self.current = None; } } impl SetupsCfg for GlobalProjectCfg { type Setup = GlobalProjectSetupCfg; fn get_setups(&self) -> Rc<RefCell<Vec<Rc<RefCell<Self::Setup>>>>> { Rc::clone(&self.setups.0) } } impl PartialEq<PathBuf> for GlobalProjectCfg { fn eq(&self, path_buf: &PathBuf) -> bool { self.file().eq(path_buf) } } impl PartialEq<GlobalProjectCfg> for PathBuf { fn eq(&self, path_buf: &GlobalProjectCfg) -> bool { self.eq(&path_buf.file) } } #[cfg(test)] mod test { use std::path::PathBuf; use crate::cfg::global::project::GlobalProjectCfg; use crate::cfg::global::setup::GlobalProjectSetupCfg; use crate::cfg::SetupsCfg; #[test] fn deserialization_serialization_cfg() { let content = r"--- file: path/to/file current: setup: setup_1 setups: test_1: {}"; let cfg = serde_yaml::from_str::<GlobalProjectCfg>(content).unwrap(); let r = serde_yaml::to_string(&cfg).unwrap(); assert_eq!(content, r); } #[test] fn global_update_private_env_dir() { let setup_cfg = GlobalProjectSetupCfg::new("setup".into()); let mut project_cfg = GlobalProjectCfg::new(&"/project".into()).unwrap(); project_cfg.add_setup(setup_cfg); assert!(project_cfg.get_setups().borrow().iter().count().eq(&1)); { let setup_cfg = project_cfg.get_setup(&"setup".into()).unwrap(); setup_cfg .borrow_mut() .set_private_env_dir("/private_env".into()) .unwrap(); } let global_project_setup_cfg_1 = project_cfg.get_setup(&"setup".into()).unwrap(); assert_eq!( global_project_setup_cfg_1 .borrow() .private_env_dir() .unwrap(), &PathBuf::from("/private_env") ); project_cfg.remove_by_name_setup(&"setup".into()); assert!(project_cfg.get_setup(&"setup".into()).is_none()); } }
l_setup_cfg.name() }) .is_none() { global_setups_cfg.push(Rc::new(RefCell::new(global_setup_cfg))) } }
function_block-function_prefixed
[ { "content": "pub fn run_as_stream(file: &PathBuf, vars: &Vec<EnvVar>, args: &Vec<String>) -> Result<Output> {\n\n let file = file.canonicalize()?;\n\n let mut command = Command::new(&file);\n\n\n\n for env_var in vars.iter() {\n\n command.env(env_var.var().to_env_var(), env_var.env_value().to_s...
Rust
src/repl.rs
wylee/feint
2ad7c43ae575684859996da2ce560168c82140d3
use std::path::Path; use rustyline::error::ReadlineError; use crate::compiler::CompilationErrKind; use crate::parser::ParseErrKind; use crate::result::ExitResult; use crate::scanner::ScanErrKind; use crate::util::Location; use crate::vm::{execute, execute_text, Inst, RuntimeErrKind, VMState, VM}; pub fn run(history_path: Option<&Path>, dis: bool, debug: bool) -> ExitResult { let mut repl = Repl::new(history_path, VM::default(), dis, debug); repl.run() } struct Repl<'a> { reader: rustyline::Editor<()>, history_path: Option<&'a Path>, vm: VM, dis: bool, debug: bool, } impl<'a> Repl<'a> { fn new(history_path: Option<&'a Path>, vm: VM, dis: bool, debug: bool) -> Self { Repl { reader: rustyline::Editor::<()>::new(), history_path, vm, dis, debug } } fn run(&mut self) -> ExitResult { println!("Welcome to the FeInt REPL (read/eval/print loop)"); println!("Type a line of code, then hit Enter to evaluate it"); self.load_history(); println!("Type .exit or .quit to exit"); loop { match self.read_line("โ†’ ", true) { Ok(None) => { () } Ok(Some(input)) => { match self.eval(input.as_str(), false) { Some(result) => { self.vm.halt(); break result; } None => (), } } Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => { self.vm.halt(); break Ok(None); } Err(err) => { self.vm.halt(); break Err((1, format!("Could not read line: {}", err))); } } } } fn read_line( &mut self, prompt: &str, trim_blank: bool, ) -> Result<Option<String>, ReadlineError> { match self.reader.readline(prompt) { Ok(input) if trim_blank && input.trim().len() == 0 => Ok(None), Ok(input) => Ok(Some(input)), Err(err) => Err(err), } } fn eval(&mut self, text: &str, bail: bool) -> Option<ExitResult> { self.add_history_entry(text); let result = match text.trim() { "?" | ".help" => { eprintln!("{:=>72}", ""); eprintln!("FeInt Help"); eprintln!("{:->72}", ""); eprintln!(".help -> show help"); eprintln!(".exit -> exit"); eprintln!(".stack -> show VM stack (top first)"); eprintln!("{:=>72}", ""); return None; } ".exit" | ".quit" => return Some(Ok(None)), ".stack" => { self.vm.display_stack(); return None; } _ => execute_text(&mut self.vm, text, self.dis, self.debug), }; if let Ok(vm_state) = result { let var = "_"; let mut instructions = vec![Inst::AssignVar(var.to_owned())]; if let Some(&index) = self.vm.peek() { if index != 0 { instructions.push(Inst::Print); } } if let Err(err) = execute(&mut self.vm, instructions, false, false) { if let RuntimeErrKind::NotEnoughValuesOnStack(_) = err.kind { let instructions = vec![Inst::Push(0), Inst::AssignVar(var.to_owned())]; if let Err(err) = execute(&mut self.vm, instructions, false, false) { eprintln!( "ERROR: Could not assign _ to top of stack or to nil:\n{}", err ); } } } return self.vm_state_to_exit_result(vm_state); } let err = result.unwrap_err(); if self.handle_execution_err(err.kind, bail) { let mut input = text.to_owned(); let mut blank_line_count = 0; loop { match self.read_line("+ ", false) { Ok(None) => unreachable!(), Ok(Some(new_input)) if new_input == "" => { input.push('\n'); if blank_line_count > 0 { break self.eval(input.as_str(), true); } blank_line_count += 1; } Ok(Some(new_input)) => { input.push('\n'); input.push_str(new_input.as_str()); if blank_line_count > 0 { break self.eval(input.as_str(), true); } blank_line_count = 0; } Err(err) => break Some(Err((2, format!("{}", err)))), } } } else { None } } fn vm_state_to_exit_result(&self, vm_state: VMState) -> Option<ExitResult> { match vm_state { VMState::Idle => None, VMState::Halted(0) => None, VMState::Halted(code) => { Some(Err((code, format!("Halted abnormally: {}", code)))) } } } fn handle_execution_err(&mut self, kind: RuntimeErrKind, bail: bool) -> bool { let message = match kind { RuntimeErrKind::CompilationError(err) => { return self.handle_compilation_err(err.kind, bail); } RuntimeErrKind::ParseError(err) => { return self.handle_parse_err(err.kind, bail); } RuntimeErrKind::TypeError(message) => { format!("{}", message) } err => { format!("Unhandled execution error: {:?}", err) } }; eprintln!("{}", message); false } fn handle_compilation_err(&mut self, kind: CompilationErrKind, bail: bool) -> bool { let message = match kind { err => format!("Unhandled compilation error: {:?}", err), }; eprintln!("{}", message); false } fn handle_parse_err(&mut self, kind: ParseErrKind, bail: bool) -> bool { match kind { ParseErrKind::ScanErr(err) => { return self.handle_scan_err(err.kind, err.location, bail); } ParseErrKind::UnexpectedToken(token) => { let loc = token.start; eprintln!("{: >width$}^", "", width = loc.col + 1); eprintln!("Parse error: unhandled token at {}: {:?}", loc, token.token); } ParseErrKind::ExpectedBlock(loc) => { if bail { eprintln!("{: >width$}^", "", width = loc.col + 1); eprintln!("Parse error: expected indented block at {}", loc); } else { return true; } } err => { eprintln!("Unhandled parse error: {:?}", err); } } false } fn handle_scan_err( &mut self, kind: ScanErrKind, loc: Location, bail: bool, ) -> bool { match kind { ScanErrKind::UnexpectedCharacter(c) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!( "Syntax error: unexpected character at column {}: '{}'", col, c ); } ScanErrKind::UnmatchedOpeningBracket(_) | ScanErrKind::UnterminatedString(_) => { return true; } ScanErrKind::InvalidIndent(num_spaces) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: invalid indent with {} spaces (should be a multiple of 4)", num_spaces); } ScanErrKind::UnexpectedIndent(_) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: unexpected indent"); } ScanErrKind::WhitespaceAfterIndent | ScanErrKind::UnexpectedWhitespace => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: unexpected whitespace"); } err => { eprintln!("Unhandled scan error at {}: {:?}", loc, err); } } false } fn load_history(&mut self) { match self.history_path { Some(path) => { println!("REPL history will be saved to {}", path.to_string_lossy()); match self.reader.load_history(path) { Ok(_) => (), Err(err) => eprintln!("Could not load REPL history: {}", err), } } None => (), } } fn add_history_entry(&mut self, input: &str) { match self.history_path { Some(path) => { self.reader.add_history_entry(input); match self.reader.save_history(path) { Ok(_) => (), Err(err) => eprintln!("Could not save REPL history: {}", err), } } None => (), } } } #[cfg(test)] mod tests { use super::*; #[test] fn eval_empty() { eval(""); } #[test] fn eval_arithmetic() { eval("2 * (3 + 4)"); } #[test] fn eval_string() { eval("\"abc\""); } #[test] fn eval_multiline_string() { eval("\"a \nb c\""); } fn new<'a>() -> Repl<'a> { let vm = VM::default(); Repl::new(None, vm, false, false) } fn eval(input: &str) { let mut runner = new(); match runner.eval(input, true) { Some(Ok(string)) => assert!(false), Some(Err((code, string))) => assert!(false), None => assert!(true), } } }
use std::path::Path; use rustyline::error::ReadlineError; use crate::compiler::CompilationErrKind; use crate::parser::ParseErrKind; use crate::result::ExitResult; use crate::scanner::ScanErrKind; use crate::util::Location; use crate::vm::{execute, execute_text, Inst, RuntimeErrKind, VMState, VM}; pub fn run(history_path: Option<&Path>, dis: bool, debug: bool) -> ExitResult { let mut repl = Repl::new(history_path, VM::default(), dis, debug); repl.run() } struct Repl<'a> { reader: rustyline::Editor<()>, history_path: Option<&'a Path>, vm: VM, dis: bool, debug: bool, } impl<'a> Repl<'a> { fn new(history_path: Option<&'a Path>, vm: VM, dis: bool, debug: bool) -> Self { Repl { reader: rustyline::Editor::<()>::new(), history_path, vm, dis, debug } } fn run(&mut self) -> ExitResult { println!("Welcome to the FeInt REPL (read/eval/print loop)"); println!("Type a line of code, then hit Enter to evaluate it"); self.load_history(); println!("Type .exit or .quit to exit"); loop { match self.read_line("โ†’ ", true) { Ok(None) => { () } Ok(Some(input)) => { match self.eval(input.as_str(), false) { Some(result) => { self.vm.halt(); break result; } None => (), } } Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => { self.vm.halt(); break Ok(None); } Err(err) => { self.vm.halt(); break Err((1, format!("Could not read line: {}", err))); } } } } fn read_line( &mut self, prompt: &str, trim_blank: bool, ) -> Result<Option<String>, ReadlineError> { match self.reader.readline(prompt) { Ok(input) if trim_blank && input.trim().len() == 0 => Ok(None), Ok(input) => Ok(Some(input)), Err(err) => Err(err), } } fn eval(&mut self, text: &str, bail: bool) -> Option<ExitResult> { self.add_history_entry(text); let result = match text.trim() { "?" | ".help" => { eprintln!("{:=>72}", ""); eprintln!("FeInt Help"); eprintln!("{:->72}", ""); eprintln!(".help -> show help"); eprintln!(".exit -> exit"); eprintln!(".stack -> show VM stack (top first)"); eprintln!("{:=>72}", ""); return None; } ".exit" | ".quit" => return Some(Ok(None)), ".stack" => { self.vm.display_stack(); return None; } _ => execute_text(&mut self.vm, text, self.dis, self.debug), }; if let Ok(vm_state) = result { let var = "_"; let mut instructions = vec![Inst::AssignVar(var.to_owned())]; if let Some(&index) = self.vm.peek() { if index != 0 { instructions.push(Inst::Print); } } if let Err(err) = execute(&mut self.vm, instructions, false, false) { if let RuntimeErrKind::NotEnoughValuesOnStack(_) = err.kind { let instructions = vec![Inst::Push(0), Inst::AssignVar(var.to_owned())]; if let Err(err) = execute(&mut self.vm, instructions, false, false) { eprintln!( "ERROR: Could not assign _ to top of stack or to nil:\n{}", err ); } } } return self.vm_state_to_exit_result(vm_state); } let err = result.unwrap_err(); if self.handle_execution_err(err.kind, bail) { let mut input = text.to_owned(); let mut blank_line_count = 0; loop { match self.read_line("+ ", false) { Ok(None) => unreachable!(), Ok(Some(new_input)) if new_input == "" => { input.push('\n'); if blank_line_count > 0 { break self.eval(input.as_str(), true); } blank_line_count += 1; } Ok(Some(new_input)) => { input.push('\n'); input.push_str(new_input.as_str()); if blank_line_count > 0 { break self.eval(input.as_str(), true); } blank_line_count = 0; } Err(err) => break Some(Err((2, format!("{}", err)))), } } } else { None } } fn vm_state_to_exit_result(&self, vm_state: VMState) -> Option<ExitResult> { match vm_state { VMState::Idle => None, VMState::Halted(0) => None, VMState::Halted(code) => { Some(Err((code, format!("Halted abnormally: {}", code)))) } } } fn handle_execution_err(&mut self, kind: RuntimeErrKind, bail: bool) -> bool { let message = match kind { RuntimeErrKind::CompilationError(err) => { return self.handle_compilation_err(err.kind, bail); } RuntimeErrKind::ParseError(err) => { return self.handle_parse_err(err.kind, bail); } RuntimeErrKind::TypeError(message) => { format!("{}", message) } err => { format!("Unhandled execution error: {:?}", err) } }; eprintln!("{}", message); false } fn handle_compilation_err(&mut self, kind: Compilatio
fn handle_parse_err(&mut self, kind: ParseErrKind, bail: bool) -> bool { match kind { ParseErrKind::ScanErr(err) => { return self.handle_scan_err(err.kind, err.location, bail); } ParseErrKind::UnexpectedToken(token) => { let loc = token.start; eprintln!("{: >width$}^", "", width = loc.col + 1); eprintln!("Parse error: unhandled token at {}: {:?}", loc, token.token); } ParseErrKind::ExpectedBlock(loc) => { if bail { eprintln!("{: >width$}^", "", width = loc.col + 1); eprintln!("Parse error: expected indented block at {}", loc); } else { return true; } } err => { eprintln!("Unhandled parse error: {:?}", err); } } false } fn handle_scan_err( &mut self, kind: ScanErrKind, loc: Location, bail: bool, ) -> bool { match kind { ScanErrKind::UnexpectedCharacter(c) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!( "Syntax error: unexpected character at column {}: '{}'", col, c ); } ScanErrKind::UnmatchedOpeningBracket(_) | ScanErrKind::UnterminatedString(_) => { return true; } ScanErrKind::InvalidIndent(num_spaces) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: invalid indent with {} spaces (should be a multiple of 4)", num_spaces); } ScanErrKind::UnexpectedIndent(_) => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: unexpected indent"); } ScanErrKind::WhitespaceAfterIndent | ScanErrKind::UnexpectedWhitespace => { let col = loc.col; eprintln!("{: >width$}^", "", width = col + 1); eprintln!("Syntax error: unexpected whitespace"); } err => { eprintln!("Unhandled scan error at {}: {:?}", loc, err); } } false } fn load_history(&mut self) { match self.history_path { Some(path) => { println!("REPL history will be saved to {}", path.to_string_lossy()); match self.reader.load_history(path) { Ok(_) => (), Err(err) => eprintln!("Could not load REPL history: {}", err), } } None => (), } } fn add_history_entry(&mut self, input: &str) { match self.history_path { Some(path) => { self.reader.add_history_entry(input); match self.reader.save_history(path) { Ok(_) => (), Err(err) => eprintln!("Could not save REPL history: {}", err), } } None => (), } } } #[cfg(test)] mod tests { use super::*; #[test] fn eval_empty() { eval(""); } #[test] fn eval_arithmetic() { eval("2 * (3 + 4)"); } #[test] fn eval_string() { eval("\"abc\""); } #[test] fn eval_multiline_string() { eval("\"a \nb c\""); } fn new<'a>() -> Repl<'a> { let vm = VM::default(); Repl::new(None, vm, false, false) } fn eval(input: &str) { let mut runner = new(); match runner.eval(input, true) { Some(Ok(string)) => assert!(false), Some(Err((code, string))) => assert!(false), None => assert!(true), } } }
nErrKind, bail: bool) -> bool { let message = match kind { err => format!("Unhandled compilation error: {:?}", err), }; eprintln!("{}", message); false }
function_block-function_prefixed
[ { "content": "/// Execute source text.\n\npub fn execute_text(vm: &mut VM, text: &str, dis: bool, debug: bool) -> ExeResult {\n\n execute_parse_result(vm, parser::parse_text(text, debug), dis, debug)\n\n}\n\n\n", "file_path": "src/vm/vm.rs", "rank": 0, "score": 421688.4762652945 }, { "con...
Rust
pkmnapi-db/src/sav/player_name.rs
kevinselwyn/pkmnapi
170e6b6c9a74e85c377137bc086793898c415125
use crate::error::{self, Result}; use crate::patch::*; use crate::sav::Sav; use crate::string::*; impl Sav { pub fn get_player_name(&self) -> Result<SavePlayerName> { let offset = 0x2598; let save_player_name = SavePlayerName::from(&self.sav[offset..(offset + 0x0B)]); Ok(save_player_name) } pub fn set_player_name(&self, save_player_name: &SavePlayerName) -> Result<Patch> { let offset = 0x2598; let save_player_name_raw = save_player_name.to_raw(); let save_player_name_raw_len = save_player_name_raw.len(); let max_len = 0x0A; if save_player_name_raw_len > max_len { return Err(error::Error::SavPlayerNameWrongSize( max_len, save_player_name_raw_len, )); } let padding = vec![ 0x50; { if save_player_name_raw_len != max_len { 0x01 } else { 0x00 } } ]; let save_player_name_raw = [save_player_name_raw, padding].concat(); Ok(Patch::new(&offset, &save_player_name_raw)) } } #[derive(Debug, PartialEq)] pub struct SavePlayerName { pub name: ROMString, } impl From<&[u8]> for SavePlayerName { fn from(sav: &[u8]) -> Self { let name_end_index = sav.iter().position(|&r| r == 0x50).unwrap_or(sav.len()); let name = ROMString::new(&sav[..name_end_index]); SavePlayerName { name } } } impl SavePlayerName { pub fn to_raw(&self) -> Vec<u8> { self.name.value[..].to_vec() } }
use crate::error::{self, Result}; use crate::patch::*; use crate::sav::Sav; use crate::string::*; impl Sav { pub fn get_player_name(&self) -> Result<SavePlayerName> { let offset = 0x2598; let save_player_name = SavePlayerName::from(&self.sav[offset..(offset + 0x0B)]); Ok(save_player_name) } pub fn set_player_name(&self, save_player_name: &SavePlayerName) -> Result<Patch> { let offset = 0x2598; let save_player_name_raw = save_player_name.to_raw(); let save_player_name_raw_len = save_player_name_raw.len(); let max_len = 0x0A; if save_player_name_raw_len > max_len { return Err(error::Error::SavPlayerNameWrongSize( max_len, save_player_name_raw_len, )); } let padding = vec![
_index]); SavePlayerName { name } } } impl SavePlayerName { pub fn to_raw(&self) -> Vec<u8> { self.name.value[..].to_vec() } }
0x50; { if save_player_name_raw_len != max_len { 0x01 } else { 0x00 } } ]; let save_player_name_raw = [save_player_name_raw, padding].concat(); Ok(Patch::new(&offset, &save_player_name_raw)) } } #[derive(Debug, PartialEq)] pub struct SavePlayerName { pub name: ROMString, } impl From<&[u8]> for SavePlayerName { fn from(sav: &[u8]) -> Self { let name_end_index = sav.iter().position(|&r| r == 0x50).unwrap_or(sav.len()); let name = ROMString::new(&sav[..name_end
random
[ { "content": "#[allow(dead_code)]\n\n#[allow(non_snake_case)]\n\npub fn load_sav() -> Vec<u8> {\n\n let PKMN_SAV = env::var(\"PKMN_SAV\")\n\n .expect(\"Set the PKMN_SAV environment variable to point to the SAV location\");\n\n\n\n fs::read(PKMN_SAV).unwrap()\n\n}\n\n\n", "file_path": "pkmnapi-a...
Rust
src/timer/wheel.rs
daschl/reef
f2238623bd2cbdf3bc75dbba1e962948a131c551
use chrono::{NaiveDateTime, Duration}; use linked_list::LinkedList; use bit_vec::BitVec; use timer::Timer; use std::cmp; pub struct TimerWheel<'a, T: 'a> { last: Duration, next: Duration, num_buckets: u32, buckets: Vec<LinkedList<&'a T>>, non_empty_buckets: BitVec, } enum RemoveAction { Remove, SeekForward, } impl<'a, T: 'a> TimerWheel<'a, T> where T: Timer { pub fn new() -> TimerWheel<'a, T> { let last = Duration::seconds(0); let next = Duration::max_value(); let num_buckets = next.num_seconds().count_ones() + next.num_seconds().count_zeros() + 1; let mut buckets = Vec::with_capacity(num_buckets as usize); for _ in 0..num_buckets { buckets.push(LinkedList::new()); } let non_empty_buckets = BitVec::from_elem(num_buckets as usize, false); TimerWheel { last: last, next: next, num_buckets: num_buckets, buckets: buckets, non_empty_buckets: non_empty_buckets, } } pub fn insert(&mut self, timer: &'a T) -> bool { let timestamp = TimerWheel::<T>::duration_since_epoch(timer.expires()); let index = self.get_index(timestamp) as usize; self.buckets.get_mut(index).expect("Index out of bounds!").push_back(timer); self.non_empty_buckets.set(index, true); if timestamp < self.next { self.next = timestamp; true } else { false } } pub fn remove(&mut self, timer: &'a T) { let timestamp = TimerWheel::<T>::duration_since_epoch(timer.expires()); let index = self.get_index(timestamp) as usize; let list = self.buckets.get_mut(index).expect("Index out of bounds!"); { let mut cursor = list.cursor(); loop { let action = match cursor.peek_next() { Some(t) => { if *t as *const T == timer as *const T { RemoveAction::Remove } else { RemoveAction::SeekForward } } None => break, }; match action { RemoveAction::Remove => { cursor.remove(); break; } RemoveAction::SeekForward => cursor.seek_forward(1), } } } if list.is_empty() { self.non_empty_buckets.set(index, false); } } pub fn expire(&mut self, now: NaiveDateTime) -> LinkedList<&'a T> { let timestamp = TimerWheel::<T>::duration_since_epoch(now); if timestamp < self.last { panic!("The timestamp to expire is smaller than last!"); } let mut expired = LinkedList::new(); let index = self.get_index(timestamp) as usize; let skipped = self.non_empty_buckets .iter() .enumerate() .skip(index + 1) .collect::<Vec<(usize, bool)>>(); for (i, _) in skipped { let length = expired.len(); expired.splice(length, self.buckets.get_mut(i).expect("Expected list")); self.non_empty_buckets.set(i, false); } self.last = timestamp; self.next = Duration::max_value(); let mut reinsert = vec![]; { let mut list = self.buckets.get_mut(index).unwrap(); while !list.is_empty() { let timer = list.pop_front().unwrap(); if timer.expires() <= now { list.push_back(timer); } else { reinsert.push(timer); } } } for t in &mut reinsert { self.insert(t); } self.non_empty_buckets.set(index, !self.buckets.get(index).unwrap().is_empty()); if self.next == Duration::max_value() && self.non_empty_buckets.any() { let list = self.buckets.get(self.last_non_empty_bucket()).unwrap(); for t in list.iter() { self.next = cmp::min(self.next, TimerWheel::<T>::duration_since_epoch(t.expires())); } } expired } fn get_index(&self, timestamp: Duration) -> u32 { if timestamp <= self.last { self.num_buckets - 1 } else { let index = (timestamp.num_seconds() ^ self.last.num_seconds()).leading_zeros(); debug_assert!(index < self.num_buckets - 1); index } } #[inline] fn last_non_empty_bucket(&self) -> usize { let (idx, _) = self.non_empty_buckets .iter() .filter(|b| *b == true) .enumerate() .last() .expect("No non-empty bucket found!"); idx } #[inline] fn duration_since_epoch(time_point: NaiveDateTime) -> Duration { Duration::seconds(time_point.timestamp()) } } #[cfg(test)] mod tests { use super::TimerWheel; use timer::Timer; use chrono::{NaiveDateTime, Duration, UTC, TimeZone}; #[derive(Debug,PartialEq)] struct MyTimer { expires: Duration, } impl Timer for MyTimer { fn expires(&self) -> NaiveDateTime { NaiveDateTime::from_timestamp(self.expires.num_seconds(), 0) } } #[test] fn test_insert_and_remove() { let timer = MyTimer { expires: Duration::days(3) }; let mut wheel = TimerWheel::<MyTimer>::new(); let index = wheel.get_index(Duration::days(3)); assert_eq!(Some(false), wheel.non_empty_buckets.get(index as usize)); wheel.insert(&timer); assert_eq!(Some(true), wheel.non_empty_buckets.get(index as usize)); wheel.remove(&timer); assert_eq!(Some(false), wheel.non_empty_buckets.get(index as usize)); } #[test] fn test_expire() { let timer = MyTimer { expires: Duration::days(2) }; let mut wheel = TimerWheel::<MyTimer>::new(); wheel.insert(&timer); let expired = wheel.expire(NaiveDateTime::from_timestamp(Duration::days(1).num_seconds(), 0)); assert_eq!(true, expired.is_empty()); let mut expired = wheel.expire(NaiveDateTime::from_timestamp(Duration::days(4).num_seconds(), 0)); assert_eq!(false, expired.is_empty()); assert_eq!(1, expired.len()); assert_eq!(timer, *expired.pop_front().unwrap()); } #[test] fn test_get_index() { let wheel = TimerWheel::<MyTimer>::new(); let index = wheel.get_index(Duration::seconds(1)); assert_eq!(63, index); } #[test] fn test_since_epoch() { let dt = UTC.ymd(2014, 7, 8).and_hms(9, 10, 11); let duration = TimerWheel::<MyTimer>::duration_since_epoch(dt.naive_utc()); assert_eq!(1404810611, duration.num_seconds()); } }
use chrono::{NaiveDateTime, Duration}; use linked_list::LinkedList; use bit_vec::BitVec; use timer::Timer; use std::cmp; pub struct TimerWheel<'a, T: 'a> { last: Duration, next: Duration, num_buckets: u32, buckets: Vec<LinkedList<&'a T>>, non_empty_buckets: BitVec, } enum RemoveAction { Remove, SeekForward, } impl<'a, T: 'a> TimerWheel<'a, T> where T: Timer { pub fn new() -> TimerWheel<'a, T> { let last = Duration::seconds(0); let next = Duration::max_value(); let num_buckets = next.num_seconds().count_ones() + next.num_seconds().count_zeros() + 1; let mut buckets = Vec::with_capacity(num_buckets as usize); for _ in 0..num_buckets { buckets.push(LinkedList::new()); } let non_empty_buckets = BitVec::from_elem(num_buckets as usize, false); TimerWheel { last: last, next: next, num_buckets: num_buckets, buckets: buckets, non_empty_buckets: non_empty_buckets, } } pub fn insert(&mut self, timer: &'a T) -> bool { let timestamp = TimerWheel::<T>::duration_since_epoch(timer.expires()); let index = self.get_index(timestamp) as usize; self.buckets.get_mut(index).expect("Index out of bounds!").push_back(timer); self.non_empty_buckets.set(index, true); if timestamp < self.next { self.next = timestamp; true } else { false } } pub fn remove(&mut self, timer: &'a T) { let timestamp = TimerWheel::<T>::duration_since_epoch(timer.expires()); let index = self.get_index(timestamp) as usize; let list = self.buckets.get_mut(index).expect("Index out of bounds!"); { let mut cursor = list.cursor(); loop { let action = match cursor.peek_next() { Some(t) => { if *t as *const T == timer as *const T { RemoveAction::Remove } else { RemoveAction::SeekForward } } None => break, }; match action { RemoveAction::Remove => { cursor.remove(); break; } RemoveAction::SeekForward => cursor.seek_forward(1), } } } if list.is_empty() { self.non_empty_buckets.set(index, false); } } pub fn expire(&mut self, now: NaiveDateTime) -> LinkedList<&'a T> { let timestamp = TimerWheel::<T
xpired = wheel.expire(NaiveDateTime::from_timestamp(Duration::days(4).num_seconds(), 0)); assert_eq!(false, expired.is_empty()); assert_eq!(1, expired.len()); assert_eq!(timer, *expired.pop_front().unwrap()); } #[test] fn test_get_index() { let wheel = TimerWheel::<MyTimer>::new(); let index = wheel.get_index(Duration::seconds(1)); assert_eq!(63, index); } #[test] fn test_since_epoch() { let dt = UTC.ymd(2014, 7, 8).and_hms(9, 10, 11); let duration = TimerWheel::<MyTimer>::duration_since_epoch(dt.naive_utc()); assert_eq!(1404810611, duration.num_seconds()); } }
>::duration_since_epoch(now); if timestamp < self.last { panic!("The timestamp to expire is smaller than last!"); } let mut expired = LinkedList::new(); let index = self.get_index(timestamp) as usize; let skipped = self.non_empty_buckets .iter() .enumerate() .skip(index + 1) .collect::<Vec<(usize, bool)>>(); for (i, _) in skipped { let length = expired.len(); expired.splice(length, self.buckets.get_mut(i).expect("Expected list")); self.non_empty_buckets.set(i, false); } self.last = timestamp; self.next = Duration::max_value(); let mut reinsert = vec![]; { let mut list = self.buckets.get_mut(index).unwrap(); while !list.is_empty() { let timer = list.pop_front().unwrap(); if timer.expires() <= now { list.push_back(timer); } else { reinsert.push(timer); } } } for t in &mut reinsert { self.insert(t); } self.non_empty_buckets.set(index, !self.buckets.get(index).unwrap().is_empty()); if self.next == Duration::max_value() && self.non_empty_buckets.any() { let list = self.buckets.get(self.last_non_empty_bucket()).unwrap(); for t in list.iter() { self.next = cmp::min(self.next, TimerWheel::<T>::duration_since_epoch(t.expires())); } } expired } fn get_index(&self, timestamp: Duration) -> u32 { if timestamp <= self.last { self.num_buckets - 1 } else { let index = (timestamp.num_seconds() ^ self.last.num_seconds()).leading_zeros(); debug_assert!(index < self.num_buckets - 1); index } } #[inline] fn last_non_empty_bucket(&self) -> usize { let (idx, _) = self.non_empty_buckets .iter() .filter(|b| *b == true) .enumerate() .last() .expect("No non-empty bucket found!"); idx } #[inline] fn duration_since_epoch(time_point: NaiveDateTime) -> Duration { Duration::seconds(time_point.timestamp()) } } #[cfg(test)] mod tests { use super::TimerWheel; use timer::Timer; use chrono::{NaiveDateTime, Duration, UTC, TimeZone}; #[derive(Debug,PartialEq)] struct MyTimer { expires: Duration, } impl Timer for MyTimer { fn expires(&self) -> NaiveDateTime { NaiveDateTime::from_timestamp(self.expires.num_seconds(), 0) } } #[test] fn test_insert_and_remove() { let timer = MyTimer { expires: Duration::days(3) }; let mut wheel = TimerWheel::<MyTimer>::new(); let index = wheel.get_index(Duration::days(3)); assert_eq!(Some(false), wheel.non_empty_buckets.get(index as usize)); wheel.insert(&timer); assert_eq!(Some(true), wheel.non_empty_buckets.get(index as usize)); wheel.remove(&timer); assert_eq!(Some(false), wheel.non_empty_buckets.get(index as usize)); } #[test] fn test_expire() { let timer = MyTimer { expires: Duration::days(2) }; let mut wheel = TimerWheel::<MyTimer>::new(); wheel.insert(&timer); let expired = wheel.expire(NaiveDateTime::from_timestamp(Duration::days(1).num_seconds(), 0)); assert_eq!(true, expired.is_empty()); let mut e
random
[ { "content": "#[bench]\n\nfn remove_one_timer(b: &mut test::Bencher) {\n\n let timer = SimpleTimer { expires: Duration::days(2) };\n\n let mut wheel = TimerWheel::new();\n\n wheel.insert(&timer);\n\n b.iter(|| {\n\n wheel.remove(&timer);\n\n });\n\n}\n", "file_path": "benches/wheel.rs"...
Rust
path_ext/src/lib.rs
pwil3058/ergibus
c7c15d82998e9021ccc64ce192882da5cc89a25e
use std::{ env, io, path::{Component, Path, PathBuf, StripPrefixError}, }; use dirs; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Could not find user's home directory.")] CouldNotFindHome, #[error("Could not find current directory's parent.")] CouldNotFindParent, #[error("I/O Error")] IOError(#[from] io::Error), #[error("Error stripping path's prefix")] StripPrefixError(#[from] StripPrefixError), #[error("Unexpected prefix for this operation.")] UnexpectedPrefix, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum PathType { Absolute, RelativeCurDir, RelativeCurDirImplicit, RelativeParentDir, RelativeHomeDir, Empty, } impl PathType { pub fn of<P: AsRef<Path>>(path_arg: P) -> Self { let path = path_arg.as_ref(); match path.components().next() { None => PathType::Empty, Some(component) => match component { Component::RootDir | Component::Prefix(_) => PathType::Absolute, Component::CurDir => PathType::RelativeCurDir, Component::ParentDir => PathType::RelativeParentDir, Component::Normal(os_string) => { if os_string == "~" { PathType::RelativeHomeDir } else { PathType::RelativeCurDirImplicit } } }, } } } pub fn expand_current_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with(Component::CurDir) { let cur_dir = env::current_dir()?; let path_tail = path.strip_prefix(Component::CurDir)?; Ok(cur_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn expand_parent_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with(Component::ParentDir) { let cur_dir = env::current_dir()?; let parent_dir = match cur_dir.parent() { Some(parent_dir) => parent_dir, None => return Err(Error::CouldNotFindParent), }; let path_tail = path.strip_prefix(Component::ParentDir)?; Ok(parent_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn expand_home_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with("~") { let home_dir = match dirs::home_dir() { Some(home_dir) => home_dir, None => return Err(Error::CouldNotFindHome), }; let path_tail = path.strip_prefix("~")?; Ok(home_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn prepend_current_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); match path.components().next() { None => Ok(env::current_dir()?), Some(component) => match component { Component::Normal(os_string) => { if os_string == "~" { Err(Error::UnexpectedPrefix) } else { let cur_dir = env::current_dir()?; Ok(cur_dir.join(path)) } } _ => Err(Error::UnexpectedPrefix), }, } } pub fn absolute_path_buf<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); match PathType::of(path) { PathType::Absolute => Ok(path.to_path_buf()), PathType::RelativeCurDir => expand_current_dir(path), PathType::RelativeParentDir => expand_parent_dir(path), PathType::RelativeHomeDir => expand_home_dir(path), PathType::RelativeCurDirImplicit => prepend_current_dir(path), PathType::Empty => Ok(env::current_dir()?), } } #[cfg(test)] mod path_ext_tests { use crate::{ absolute_path_buf, expand_current_dir, expand_home_dir, expand_parent_dir, prepend_current_dir, }; use std::env; #[test] fn home_path_expansions() { let home_dir = dirs::home_dir().unwrap(); assert!(expand_home_dir("/home/dir").is_err()); assert_eq!( expand_home_dir("~/whatever").unwrap(), home_dir.join("whatever") ); assert_eq!( absolute_path_buf("~/whatever").unwrap(), home_dir.join("whatever") ); } #[test] fn cur_path_expansions() { let cur_dir = env::current_dir().unwrap(); assert!(expand_current_dir("/home/dir").is_err()); assert_eq!( expand_current_dir("./whatever").unwrap(), cur_dir.join("whatever") ); assert_eq!( absolute_path_buf("./whatever").unwrap(), cur_dir.join("whatever") ); assert!(prepend_current_dir("/home/dir").is_err()); assert_eq!( prepend_current_dir("whatever").unwrap(), cur_dir.join("whatever") ); assert_eq!( absolute_path_buf("whatever").unwrap(), cur_dir.join("whatever") ); } #[test] fn parent_path_expansions() { let cur_dir = env::current_dir().unwrap(); let parent_dir = cur_dir.parent().unwrap(); assert!(expand_parent_dir("/home/dir").is_err()); assert_eq!( expand_parent_dir("../whatever").unwrap(), parent_dir.join("whatever") ); assert_eq!( absolute_path_buf("../whatever").unwrap(), parent_dir.join("whatever") ); } }
use std::{ env, io, path::{Component, Path, PathBuf, StripPrefixError}, }; use dirs; use thiserror::Error; #[derive(Debug, Error)] pub enum Error { #[error("Could not find user's home directory.")] CouldNotFindHome, #[error("Could not find current directory's parent.")] CouldNotFindParent, #[error("I/O Error")] IOError(#[from] io::Error), #[error("Error stripping path's prefix")] StripPrefixError(#[from] StripPrefixError), #[error("Unexpected prefix for this operation.")] UnexpectedPrefix, } #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum PathType { Absolute, RelativeCurDir, RelativeCurDirImplicit, RelativeParentDir, RelativeHomeDir, Empty, } impl PathType { pub fn of<P: AsRef<Path>>(path_arg: P) -> Self { let path = path_arg.as_ref(); match path.components().next() { None => PathType::Empty, Some(component) => match component { Component::RootDir | Component::Prefix(_) => PathType::Absolute, Component::CurDir => PathType::RelativeCurDir,
lativeHomeDir } else { PathType::RelativeCurDirImplicit } } }, } } } pub fn expand_current_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with(Component::CurDir) { let cur_dir = env::current_dir()?; let path_tail = path.strip_prefix(Component::CurDir)?; Ok(cur_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn expand_parent_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with(Component::ParentDir) { let cur_dir = env::current_dir()?; let parent_dir = match cur_dir.parent() { Some(parent_dir) => parent_dir, None => return Err(Error::CouldNotFindParent), }; let path_tail = path.strip_prefix(Component::ParentDir)?; Ok(parent_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn expand_home_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); if path.starts_with("~") { let home_dir = match dirs::home_dir() { Some(home_dir) => home_dir, None => return Err(Error::CouldNotFindHome), }; let path_tail = path.strip_prefix("~")?; Ok(home_dir.join(path_tail)) } else { Err(Error::UnexpectedPrefix) } } pub fn prepend_current_dir<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); match path.components().next() { None => Ok(env::current_dir()?), Some(component) => match component { Component::Normal(os_string) => { if os_string == "~" { Err(Error::UnexpectedPrefix) } else { let cur_dir = env::current_dir()?; Ok(cur_dir.join(path)) } } _ => Err(Error::UnexpectedPrefix), }, } } pub fn absolute_path_buf<P: AsRef<Path>>(path_arg: P) -> Result<PathBuf, Error> { let path = path_arg.as_ref(); match PathType::of(path) { PathType::Absolute => Ok(path.to_path_buf()), PathType::RelativeCurDir => expand_current_dir(path), PathType::RelativeParentDir => expand_parent_dir(path), PathType::RelativeHomeDir => expand_home_dir(path), PathType::RelativeCurDirImplicit => prepend_current_dir(path), PathType::Empty => Ok(env::current_dir()?), } } #[cfg(test)] mod path_ext_tests { use crate::{ absolute_path_buf, expand_current_dir, expand_home_dir, expand_parent_dir, prepend_current_dir, }; use std::env; #[test] fn home_path_expansions() { let home_dir = dirs::home_dir().unwrap(); assert!(expand_home_dir("/home/dir").is_err()); assert_eq!( expand_home_dir("~/whatever").unwrap(), home_dir.join("whatever") ); assert_eq!( absolute_path_buf("~/whatever").unwrap(), home_dir.join("whatever") ); } #[test] fn cur_path_expansions() { let cur_dir = env::current_dir().unwrap(); assert!(expand_current_dir("/home/dir").is_err()); assert_eq!( expand_current_dir("./whatever").unwrap(), cur_dir.join("whatever") ); assert_eq!( absolute_path_buf("./whatever").unwrap(), cur_dir.join("whatever") ); assert!(prepend_current_dir("/home/dir").is_err()); assert_eq!( prepend_current_dir("whatever").unwrap(), cur_dir.join("whatever") ); assert_eq!( absolute_path_buf("whatever").unwrap(), cur_dir.join("whatever") ); } #[test] fn parent_path_expansions() { let cur_dir = env::current_dir().unwrap(); let parent_dir = cur_dir.parent().unwrap(); assert!(expand_parent_dir("/home/dir").is_err()); assert_eq!( expand_parent_dir("../whatever").unwrap(), parent_dir.join("whatever") ); assert_eq!( absolute_path_buf("../whatever").unwrap(), parent_dir.join("whatever") ); } }
Component::ParentDir => PathType::RelativeParentDir, Component::Normal(os_string) => { if os_string == "~" { PathType::Re
function_block-random_span
[ { "content": "pub fn ignore_report_or_fail<P: AsRef<Path>>(err: Error, path: P) -> EResult<()> {\n\n match &err {\n\n Error::FSOBrokenSymLink(link_path, target_path) => {\n\n log::warn!(\n\n \"{:?} -> {:?}: broken symbolic link ignored\",\n\n link_path,\n\n ...
Rust
wgpu-hal/src/dx11/library.rs
jinleili/wgpu
a845dcc21c976e1de3de7b3e0bec8703dcdd905c
use std::ptr; use winapi::{ shared::{ dxgi, minwindef::{HMODULE, UINT}, winerror, }, um::{d3d11, d3d11_1, d3d11_2, d3dcommon}, }; use crate::auxil::dxgi::result::HResult; type D3D11CreateDeviceFun = unsafe extern "system" fn( *mut dxgi::IDXGIAdapter, d3dcommon::D3D_DRIVER_TYPE, HMODULE, UINT, *const d3dcommon::D3D_FEATURE_LEVEL, UINT, UINT, *mut *mut d3d11::ID3D11Device, *mut d3dcommon::D3D_FEATURE_LEVEL, *mut *mut d3d11::ID3D11DeviceContext, ) -> native::HRESULT; pub(super) struct D3D11Lib { d3d11_create_device: libloading::os::windows::Symbol<D3D11CreateDeviceFun>, lib: libloading::Library, } impl D3D11Lib { pub fn new() -> Option<Self> { unsafe { let lib = libloading::Library::new("d3d11.dll").ok()?; let d3d11_create_device = lib .get::<D3D11CreateDeviceFun>(b"D3D11CreateDevice") .ok()? .into_raw(); Some(Self { lib, d3d11_create_device, }) } } pub fn create_device( &self, adapter: native::DxgiAdapter, ) -> Option<(super::D3D11Device, d3dcommon::D3D_FEATURE_LEVEL)> { let feature_levels = [ d3dcommon::D3D_FEATURE_LEVEL_11_1, d3dcommon::D3D_FEATURE_LEVEL_11_0, d3dcommon::D3D_FEATURE_LEVEL_10_1, d3dcommon::D3D_FEATURE_LEVEL_10_0, d3dcommon::D3D_FEATURE_LEVEL_9_3, d3dcommon::D3D_FEATURE_LEVEL_9_2, d3dcommon::D3D_FEATURE_LEVEL_9_1, ]; let mut device = native::WeakPtr::<d3d11::ID3D11Device>::null(); let mut feature_level: d3dcommon::D3D_FEATURE_LEVEL = 0; let mut hr = unsafe { (self.d3d11_create_device)( adapter.as_mut_ptr() as *mut _, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, ptr::null_mut(), 0, feature_levels.as_ptr(), feature_levels.len() as u32, d3d11::D3D11_SDK_VERSION, device.mut_self(), &mut feature_level, ptr::null_mut(), ) }; if hr == winerror::E_INVALIDARG { hr = unsafe { (self.d3d11_create_device)( adapter.as_mut_ptr() as *mut _, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, ptr::null_mut(), 0, feature_levels[1..].as_ptr(), feature_levels[1..].len() as u32, d3d11::D3D11_SDK_VERSION, device.mut_self(), &mut feature_level, ptr::null_mut(), ) }; } if let Err(err) = hr.into_result() { log::error!("Failed to make a D3D11 device: {}", err); return None; } unsafe { match device.cast::<d3d11_2::ID3D11Device2>().into_result() { Ok(device2) => { device.destroy(); return Some((super::D3D11Device::Device2(device2), feature_level)); } Err(hr) => { log::info!("Failed to cast device to ID3D11Device2: {}", hr) } } } unsafe { match device.cast::<d3d11_1::ID3D11Device1>().into_result() { Ok(device1) => { device.destroy(); return Some((super::D3D11Device::Device1(device1), feature_level)); } Err(hr) => { log::info!("Failed to cast device to ID3D11Device1: {}", hr) } } } Some((super::D3D11Device::Device(device), feature_level)) } }
use std::ptr; use winapi::{ shared::{ dxgi, minwindef::{HMODULE, UINT}, winerror, }, um::{d3d11, d3d11_1, d3d11_2, d3dcommon}, }; use crate::auxil::dxgi::result::HResult; type D3D11CreateDeviceFun = unsafe extern "system" fn( *mut dxgi::IDXGIAdapter, d3dcommon::D3D_DRIVER_TYPE, HMODULE, UINT, *const d3dcommon::D3D_FEATURE_LEVEL, UINT, UINT, *mut *mut d3d11::ID3D11Device, *mut d3dcommon::D3D_FEATURE_LEVEL, *mut *mut d3d11::ID3D11DeviceContext, ) -> native::HRESULT; pub(super) struct D3D11Lib { d3d11_create_device: libloading::os::windows::Symbol<D3D11CreateDeviceFun>, lib: libloading::Library, } impl D3D11Lib { pub fn new() -> Option<Self> {
pub fn create_device( &self, adapter: native::DxgiAdapter, ) -> Option<(super::D3D11Device, d3dcommon::D3D_FEATURE_LEVEL)> { let feature_levels = [ d3dcommon::D3D_FEATURE_LEVEL_11_1, d3dcommon::D3D_FEATURE_LEVEL_11_0, d3dcommon::D3D_FEATURE_LEVEL_10_1, d3dcommon::D3D_FEATURE_LEVEL_10_0, d3dcommon::D3D_FEATURE_LEVEL_9_3, d3dcommon::D3D_FEATURE_LEVEL_9_2, d3dcommon::D3D_FEATURE_LEVEL_9_1, ]; let mut device = native::WeakPtr::<d3d11::ID3D11Device>::null(); let mut feature_level: d3dcommon::D3D_FEATURE_LEVEL = 0; let mut hr = unsafe { (self.d3d11_create_device)( adapter.as_mut_ptr() as *mut _, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, ptr::null_mut(), 0, feature_levels.as_ptr(), feature_levels.len() as u32, d3d11::D3D11_SDK_VERSION, device.mut_self(), &mut feature_level, ptr::null_mut(), ) }; if hr == winerror::E_INVALIDARG { hr = unsafe { (self.d3d11_create_device)( adapter.as_mut_ptr() as *mut _, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, ptr::null_mut(), 0, feature_levels[1..].as_ptr(), feature_levels[1..].len() as u32, d3d11::D3D11_SDK_VERSION, device.mut_self(), &mut feature_level, ptr::null_mut(), ) }; } if let Err(err) = hr.into_result() { log::error!("Failed to make a D3D11 device: {}", err); return None; } unsafe { match device.cast::<d3d11_2::ID3D11Device2>().into_result() { Ok(device2) => { device.destroy(); return Some((super::D3D11Device::Device2(device2), feature_level)); } Err(hr) => { log::info!("Failed to cast device to ID3D11Device2: {}", hr) } } } unsafe { match device.cast::<d3d11_1::ID3D11Device1>().into_result() { Ok(device1) => { device.destroy(); return Some((super::D3D11Device::Device1(device1), feature_level)); } Err(hr) => { log::info!("Failed to cast device to ID3D11Device1: {}", hr) } } } Some((super::D3D11Device::Device(device), feature_level)) } }
unsafe { let lib = libloading::Library::new("d3d11.dll").ok()?; let d3d11_create_device = lib .get::<D3D11CreateDeviceFun>(b"D3D11CreateDevice") .ok()? .into_raw(); Some(Self { lib, d3d11_create_device, }) } }
function_block-function_prefix_line
[ { "content": "type WlDisplayDisconnectFun = unsafe extern \"system\" fn(display: *const raw::c_void);\n\n\n", "file_path": "wgpu-hal/src/gles/egl.rs", "rank": 1, "score": 363831.6744697565 }, { "content": "type WlEglWindowDestroyFun = unsafe extern \"system\" fn(window: *const raw::c_void);\...
Rust
linked-lists/fp-rust/persistent-list/src/third.rs
ctarrington/try-fp
63559ec6abd451c8a1decad5981a20fee498a171
#![warn(missing_docs)] use std::rc::Rc; pub struct PersistentList<T> { head: Link<T>, } type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { next: Link<T>, element: T, } impl<T> PersistentList<T> { pub fn new() -> Self { Self { head: None } } } impl<T> Default for PersistentList<T> { fn default() -> Self { Self::new() } } impl<T> PersistentList<T> { pub fn prepend(&self, value: T) -> Self { Self { head: Some(Rc::new(Node { element: value, next: self.head.as_ref().map(|rc_node| Rc::clone(&rc_node)), })), } } pub fn tail(&self) -> Self { Self { head: self .head .as_ref() .and_then(|node| node.next.as_ref().map(|rc_node| Rc::clone(&rc_node))), } } pub fn head(&self) -> Option<&T> { self.head.as_ref().map(|node| &node.element) } } pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } impl<T> PersistentList<T> { pub fn iter(&self) -> Iter<'_, T> { Iter { next: self.head.as_deref(), } } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.next.map(|node| { self.next = node.next.as_deref(); &node.element }) } } impl<T> Drop for PersistentList<T> { fn drop(&mut self) { let mut head = self.head.take(); while let Some(node) = head { if let Ok(mut node) = Rc::try_unwrap(node) { head = node.next.take(); } else { break; } } } } #[cfg(test)] mod test { use super::PersistentList; use std::cell::RefCell; #[test] fn simple() { let empty_list = PersistentList::new(); assert_eq!(empty_list.head(), None); assert_eq!(empty_list.tail().head(), None); let list_1 = empty_list.prepend(1); assert_eq!(empty_list.head(), None); assert_eq!(list_1.head(), Some(&1)); let list_321 = list_1.prepend(2).prepend(3); let list_21 = list_321.tail(); assert_eq!(list_321.head(), Some(&3)); assert_eq!(list_21.head(), Some(&2)); } #[test] fn iteration() { let empty_list: PersistentList<i32> = PersistentList::new(); let mut iter = empty_list.iter(); assert_eq!(iter.next(), None); let list = PersistentList::new().prepend(1).prepend(2).prepend(3); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); let list_421 = list.tail().prepend(4); let mut iter_321 = list.iter(); let mut iter_421 = list_421.iter(); assert_eq!(iter_321.next(), Some(&3)); assert_eq!(iter_321.next(), Some(&2)); assert_eq!(iter_321.next(), Some(&1)); assert_eq!(iter_421.next(), Some(&4)); assert_eq!(iter_421.next(), Some(&2)); assert_eq!(iter_421.next(), Some(&1)); } #[test] fn drop() { struct Watcher { events: RefCell<Vec<String>>, } impl Watcher { fn new() -> Self { Self { events: RefCell::new(vec![]), } } fn push(&self, value: String) { self.events.borrow_mut().push(value); } fn list(&self) -> String { self.events.borrow().join(",") } } struct Thing<'a> { value: i32, watcher: &'a Watcher, } impl<'a> Drop for Thing<'a> { fn drop(&mut self) { self.watcher.push(format!("dropping {} ", self.value)); } } let watcher = Watcher::new(); { let list_1: PersistentList<Thing> = PersistentList::default().prepend(Thing { value: 1, watcher: &watcher, }); assert_eq!(list_1.head().map(|thing| thing.value), Some(1)); { let list_321 = list_1 .prepend(Thing { value: 2, watcher: &watcher, }) .prepend(Thing { value: 3, watcher: &watcher, }); assert_eq!(list_321.head().map(|thing| thing.value), Some(3)); watcher.push("done with list_321".to_string()); } watcher.push("still using list_1".to_string()); assert_eq!(list_1.head().map(|thing| thing.value), Some(1)); watcher.push("done with list_1".to_string()); } assert_eq!(watcher.list(), "done with list_321,dropping 3 ,dropping 2 ,still using list_1,done with list_1,dropping 1 ".to_string()); } }
#![warn(missing_docs)] use std::rc::Rc; pub struct PersistentList<T> { head: Link<T>, } type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { next: Link<T>, element: T, } impl<T> PersistentList<T> { pub fn new() -> Self { Self { head: None } } } impl<T> Default for PersistentList<T> { fn default() -> Self { Sel
events: RefCell::new(vec![]), } } fn push(&self, value: String) { self.events.borrow_mut().push(value); } fn list(&self) -> String { self.events.borrow().join(",") } } struct Thing<'a> { value: i32, watcher: &'a Watcher, } impl<'a> Drop for Thing<'a> { fn drop(&mut self) { self.watcher.push(format!("dropping {} ", self.value)); } } let watcher = Watcher::new(); { let list_1: PersistentList<Thing> = PersistentList::default().prepend(Thing { value: 1, watcher: &watcher, }); assert_eq!(list_1.head().map(|thing| thing.value), Some(1)); { let list_321 = list_1 .prepend(Thing { value: 2, watcher: &watcher, }) .prepend(Thing { value: 3, watcher: &watcher, }); assert_eq!(list_321.head().map(|thing| thing.value), Some(3)); watcher.push("done with list_321".to_string()); } watcher.push("still using list_1".to_string()); assert_eq!(list_1.head().map(|thing| thing.value), Some(1)); watcher.push("done with list_1".to_string()); } assert_eq!(watcher.list(), "done with list_321,dropping 3 ,dropping 2 ,still using list_1,done with list_1,dropping 1 ".to_string()); } }
f::new() } } impl<T> PersistentList<T> { pub fn prepend(&self, value: T) -> Self { Self { head: Some(Rc::new(Node { element: value, next: self.head.as_ref().map(|rc_node| Rc::clone(&rc_node)), })), } } pub fn tail(&self) -> Self { Self { head: self .head .as_ref() .and_then(|node| node.next.as_ref().map(|rc_node| Rc::clone(&rc_node))), } } pub fn head(&self) -> Option<&T> { self.head.as_ref().map(|node| &node.element) } } pub struct Iter<'a, T> { next: Option<&'a Node<T>>, } impl<T> PersistentList<T> { pub fn iter(&self) -> Iter<'_, T> { Iter { next: self.head.as_deref(), } } } impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.next.map(|node| { self.next = node.next.as_deref(); &node.element }) } } impl<T> Drop for PersistentList<T> { fn drop(&mut self) { let mut head = self.head.take(); while let Some(node) = head { if let Ok(mut node) = Rc::try_unwrap(node) { head = node.next.take(); } else { break; } } } } #[cfg(test)] mod test { use super::PersistentList; use std::cell::RefCell; #[test] fn simple() { let empty_list = PersistentList::new(); assert_eq!(empty_list.head(), None); assert_eq!(empty_list.tail().head(), None); let list_1 = empty_list.prepend(1); assert_eq!(empty_list.head(), None); assert_eq!(list_1.head(), Some(&1)); let list_321 = list_1.prepend(2).prepend(3); let list_21 = list_321.tail(); assert_eq!(list_321.head(), Some(&3)); assert_eq!(list_21.head(), Some(&2)); } #[test] fn iteration() { let empty_list: PersistentList<i32> = PersistentList::new(); let mut iter = empty_list.iter(); assert_eq!(iter.next(), None); let list = PersistentList::new().prepend(1).prepend(2).prepend(3); let mut iter = list.iter(); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), Some(&2)); assert_eq!(iter.next(), Some(&1)); let list_421 = list.tail().prepend(4); let mut iter_321 = list.iter(); let mut iter_421 = list_421.iter(); assert_eq!(iter_321.next(), Some(&3)); assert_eq!(iter_321.next(), Some(&2)); assert_eq!(iter_321.next(), Some(&1)); assert_eq!(iter_421.next(), Some(&4)); assert_eq!(iter_421.next(), Some(&2)); assert_eq!(iter_421.next(), Some(&1)); } #[test] fn drop() { struct Watcher { events: RefCell<Vec<String>>, } impl Watcher { fn new() -> Self { Self {
random
[ { "content": "// the crux of the thing\n\nstruct Node {\n\n element: i32,\n\n next: Link,\n\n}\n\n\n\nimpl List {\n\n pub fn new() -> Self {\n\n List { head: Link::None }\n\n }\n\n\n\n pub fn push(&mut self, value: i32) {\n\n let popped_link = mem::replace(&mut self.head, Link::None...
Rust
src/message/header/textual.rs
alexwennerberg/lettre
8caa135e33a7e2a79a4f8792f47d40ff2e56263f
use crate::message::utf8_b; use hyperx::{ header::{Formatter as HeaderFormatter, Header, RawLike}, Error as HeaderError, Result as HyperResult, }; use std::{fmt::Result as FmtResult, str::from_utf8}; macro_rules! text_header { ($(#[$attr:meta])* Header($type_name: ident, $header_name: expr )) => { #[derive(Debug, Clone, PartialEq)] $(#[$attr])* pub struct $type_name(String); impl Header for $type_name { fn header_name() -> &'static str { $header_name } fn parse_header<'a, T>(raw: &'a T) -> HyperResult<$type_name> where T: RawLike<'a>, Self: Sized, { raw.one() .ok_or(HeaderError::Header) .and_then(parse_text) .map($type_name) } fn fmt_header(&self, f: &mut HeaderFormatter<'_, '_>) -> FmtResult { fmt_text(&self.0, f) } } impl From<String> for $type_name { #[inline] fn from(text: String) -> Self { Self(text) } } impl AsRef<str> for $type_name { #[inline] fn as_ref(&self) -> &str { &self.0 } } }; } text_header!( Header(Subject, "Subject") ); text_header!( Header(Comments, "Comments") ); text_header!( Header(Keywords, "Keywords") ); text_header!( Header(InReplyTo, "In-Reply-To") ); text_header!( Header(References, "References") ); text_header!( Header(MessageId, "Message-Id") ); text_header!( Header(UserAgent, "User-Agent") ); text_header! { Header(ContentId, "Content-ID") } fn parse_text(raw: &[u8]) -> HyperResult<String> { if let Ok(src) = from_utf8(raw) { if let Some(txt) = utf8_b::decode(src) { return Ok(txt); } } Err(HeaderError::Header) } fn fmt_text(s: &str, f: &mut HeaderFormatter<'_, '_>) -> FmtResult { f.fmt_line(&utf8_b::encode(s)) } #[cfg(test)] mod test { use super::Subject; use hyperx::header::Headers; #[test] fn format_ascii() { let mut headers = Headers::new(); headers.set(Subject("Sample subject".into())); assert_eq!(format!("{}", headers), "Subject: Sample subject\r\n"); } #[test] fn format_utf8() { let mut headers = Headers::new(); headers.set(Subject("ะขะตะผะฐ ัะพะพะฑั‰ะตะฝะธั".into())); assert_eq!( format!("{}", headers), "Subject: =?utf-8?b?0KLQtdC80LAg0YHQvtC+0LHRidC10L3QuNGP?=\r\n" ); } #[test] fn parse_ascii() { let mut headers = Headers::new(); headers.set_raw("Subject", "Sample subject"); assert_eq!( headers.get::<Subject>(), Some(&Subject("Sample subject".into())) ); } #[test] fn parse_utf8() { let mut headers = Headers::new(); headers.set_raw( "Subject", "=?utf-8?b?0KLQtdC80LAg0YHQvtC+0LHRidC10L3QuNGP?=", ); assert_eq!( headers.get::<Subject>(), Some(&Subject("ะขะตะผะฐ ัะพะพะฑั‰ะตะฝะธั".into())) ); } }
use crate::message::utf8_b; use hyperx::{ header::{Formatter as HeaderFormatter, Header, RawLike}, Error as HeaderError, Result as HyperResult, }; use std::{fmt::Result as FmtResult, str::from_utf8}; macro_rules! text_header { ($(#[$attr:meta])* Header($type_name: ident, $header_name: expr )) => { #[derive(Debug, Clone, PartialEq)] $(#[$attr])* pub struct $type_name(String); impl Header for $type_name { fn header_name() -> &'static str { $header_name } fn parse_header<'a, T>(raw: &'a T) -> HyperResult<$type_name> where T: RawLike<'a>, Self: Sized, { raw.one() .ok_or(HeaderError::Header) .and_then(parse_text) .map($type_name) } fn fmt_header(&self, f: &mut HeaderFormatter<'_, '_>) -> FmtResult { fmt_text(&self.0, f) } } impl From<String> for $type_name { #[inline] fn from(text: String) -> Self { Self(text) } } impl AsRef<str> for $type_name { #[inline] fn as_ref(&self) -> &str { &self.0 } } }; } text_header!( Header(Subject, "Subject") ); text_header!( Header(Comments, "Comments") ); text_header!( Header(Keywords, "Keywords") ); text_header!( Header(InReplyTo, "In-Reply-To") ); text_header!( Header(References, "References") ); text_header!( Header(MessageId, "Message-Id") ); text_header!( Header(UserAgent, "User-Agent") ); text_header! { Header(ContentId, "Content-ID") } fn parse_text(raw: &[u8]) -> HyperResult<String> {
Err(HeaderError::Header) } fn fmt_text(s: &str, f: &mut HeaderFormatter<'_, '_>) -> FmtResult { f.fmt_line(&utf8_b::encode(s)) } #[cfg(test)] mod test { use super::Subject; use hyperx::header::Headers; #[test] fn format_ascii() { let mut headers = Headers::new(); headers.set(Subject("Sample subject".into())); assert_eq!(format!("{}", headers), "Subject: Sample subject\r\n"); } #[test] fn format_utf8() { let mut headers = Headers::new(); headers.set(Subject("ะขะตะผะฐ ัะพะพะฑั‰ะตะฝะธั".into())); assert_eq!( format!("{}", headers), "Subject: =?utf-8?b?0KLQtdC80LAg0YHQvtC+0LHRidC10L3QuNGP?=\r\n" ); } #[test] fn parse_ascii() { let mut headers = Headers::new(); headers.set_raw("Subject", "Sample subject"); assert_eq!( headers.get::<Subject>(), Some(&Subject("Sample subject".into())) ); } #[test] fn parse_utf8() { let mut headers = Headers::new(); headers.set_raw( "Subject", "=?utf-8?b?0KLQtdC80LAg0YHQvtC+0LHRidC10L3QuNGP?=", ); assert_eq!( headers.get::<Subject>(), Some(&Subject("ะขะตะผะฐ ัะพะพะฑั‰ะตะฝะธั".into())) ); } }
if let Ok(src) = from_utf8(raw) { if let Some(txt) = utf8_b::decode(src) { return Ok(txt); } }
if_condition
[ { "content": "pub fn encode(s: &str) -> String {\n\n if s.chars().all(allowed_char) {\n\n s.into()\n\n } else {\n\n format!(\"=?utf-8?b?{}?=\", base64::encode(s))\n\n }\n\n}\n\n\n", "file_path": "src/message/utf8_b.rs", "rank": 2, "score": 184179.84348529213 }, { "cont...
Rust
src/io/pts.rs
I3ck/rust-3d
5139ab5ebdab7ad2a1f49422bc852d751fbfc4c1
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use crate::*; use std::{ fmt, io::{BufRead, Error as ioError}, iter::FusedIterator, marker::PhantomData, }; use super::{types::*, utils::*}; pub struct PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { read: R, is_done: bool, i_line: usize, line_buffer: Vec<u8>, n_vertices: Option<usize>, n_vertices_added: usize, phantom_p: PhantomData<P>, } impl<P, R> PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { pub fn new(read: R) -> Self { Self { read, is_done: false, i_line: 0, line_buffer: Vec::new(), n_vertices: None, n_vertices_added: 0, phantom_p: PhantomData, } } #[inline(always)] pub fn fetch_one(line: &[u8]) -> PtsResult<P> { let mut words = to_words_skip_empty(line); let x = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; let y = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; let z = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; Ok(P::new(x, y, z)) } } impl<P, R> Iterator for PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { type Item = PtsIOResult<DataReserve<P>>; #[inline(always)] fn next(&mut self) -> Option<Self::Item> { if self.is_done { return None; } while let Ok(line) = fetch_line(&mut self.read, &mut self.line_buffer) { self.i_line += 1; if line.is_empty() { continue; } match self.n_vertices { None => { let mut words = to_words_skip_empty(line); self.n_vertices = match words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::VertexCount) .line(self.i_line, line) { Ok(n) => Some(n), Err(e) => { self.is_done = true; return Some(Err(e)); } }; return Some(Ok(DataReserve::Reserve(self.n_vertices.unwrap()))); } Some(n) => { if self.n_vertices_added < n { self.n_vertices_added += 1; return Some( Self::fetch_one(line) .map(|x| DataReserve::Data(x)) .line(self.i_line, line) .map_err(|e| { self.is_done = true; e }), ); } else { self.n_vertices_added = 0; let mut words = to_words_skip_empty(line); self.n_vertices = match words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::VertexCount) .line(self.i_line, line) { Ok(n) => Some(n), Err(e) => { self.is_done = true; return Some(Err(e)); } }; return Some(Ok(DataReserve::Reserve(self.n_vertices.unwrap()))); } } } } self.is_done = true; None } } impl<P, R> FusedIterator for PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { } pub fn load_pts<IP, P, R>(read: R, ip: &mut IP) -> PtsIOResult<()> where IP: IsPushable<P>, P: IsBuildable3D, R: BufRead, { let iterator = PtsIterator::new(read); for rd in iterator { match rd? { DataReserve::Reserve(x) => ip.reserve(x), DataReserve::Data(x) => ip.push(x), } } Ok(()) } pub enum PtsError { AccessFile, VertexCount, Vertex, } pub type PtsIOResult<T> = IOResult<T, PtsError>; type PtsResult<T> = std::result::Result<T, PtsError>; impl fmt::Debug for PtsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::AccessFile => write!(f, "Unable to access file"), Self::VertexCount => write!(f, "Unable to parse vertex count"), Self::Vertex => write!(f, "Unable to parse vertex"), } } } impl fmt::Display for PtsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl From<ioError> for PtsError { fn from(_error: ioError) -> Self { PtsError::AccessFile } }
/* Copyright 2020 Martin Buck Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ use crate::*; use std::{ fmt, io::{BufRead, Error as ioError}, iter::FusedIterator, marker::PhantomData, }; use super::{types::*, utils::*}; pub struct PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { read: R, is_done: bool, i_line: usize, line_buffer: Vec<u8>, n_vertices: Option<usize>, n_vertices_added: usize, phantom_p: PhantomData<P>, } impl<P, R> PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { pub fn new(read: R) -> Self { Self { read, is_done: false, i_line: 0, line_buffer: Vec::new(), n_vertices: None, n_vertices_added: 0, phantom_p: PhantomData, } } #[inline(always)] pub fn fetch_one(line: &[u8]) -> PtsResult<P> { let mut words = to_words_skip_empty(line); let x = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; let y = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; let z = words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::Vertex)?; Ok(P::new(x, y, z)) } } impl<P, R> Iterator for PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { type Item = PtsIOResult<DataReserve<P>>; #[inline(always)] fn next(&mut self) -> Option<Self::Item> { if self.is_done { return None; } while let Ok(line) = fetch_line(&mut self.read, &mut self.line_buffer) { self.i_line += 1; if line.is_empty() { continue; } match self.n_vertices { None => { let mut words = to_words_skip_empty(line); self.n_vertices = match words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::VertexCount) .line(self.i_line, line) { Ok(n) => Some(n), Err(e) => { self.is_done = true; return Some(Err(e)); } }; return Some(Ok(DataReserve::Reserve(self.n_vertices.unwrap()))); } Some(n) => { if self.n_vertices_added < n { self.n_vertices_added += 1; return Some( Self::fetch_one(line) .map(|x| DataReserve::Data(x)) .line(self.i_line, line) .map_err(|e| { self.is_done = true; e }), ); } else { self.n_vertices_added = 0; let mut words = to_words_skip_empty(line); self.n_vertices = match words .next() .and_then(|word| from_ascii(word)) .ok_or(PtsError::VertexCount) .line(self.i_line, line) { Ok(n) => Some(n), Err(e) => { self.is_done = true; return Some(Err(e)); } }; return Some(Ok(DataReserve::Reserve(self.n_vertices.unwrap()))); } } } } self.is_done = true; None } } impl<P, R> FusedIterator for PtsIterator<P, R> where P: IsBuildable3D, R: BufRead, { } pub fn load_pts<IP, P, R>(read: R, ip: &mut IP) -> PtsIOResult<()> where IP: IsPushable<P>, P: IsBuildable3D, R: BufRead, { let iterator = PtsIterator::new(read); for rd in iterator { match rd? { DataReserve::Reserve(x) => ip.reserve(x), DataReserve::Data(x) => ip.push(x), } } Ok(()) } pub enum PtsError { AccessFile, VertexCount, Vertex, } pub type PtsIOResult<T> = IOResult<T, PtsError>; type PtsResult<T> = std::result::Result<T, PtsError>; impl fmt::Debug for PtsError {
} impl fmt::Display for PtsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } } impl From<ioError> for PtsError { fn from(_error: ioError) -> Self { PtsError::AccessFile } }
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::AccessFile => write!(f, "Unable to access file"), Self::VertexCount => write!(f, "Unable to parse vertex count"), Self::Vertex => write!(f, "Unable to parse vertex"), } }
function_block-full_function
[ { "content": "/// Splits an ASCII line into its words, skipping empty elements\n\npub fn to_words_skip_empty(line: &[u8]) -> impl Iterator<Item = &[u8]> {\n\n line.split(|x| *x == b' ' || *x == b'\\t').skip_empty()\n\n}\n\n\n", "file_path": "src/utils.rs", "rank": 0, "score": 505942.53733688314 ...
Rust
chain-abci/src/storage/tx.rs
calvinlauco/chain
ef40ea2c44f8e1aca8a36e50ff10172879df3491
use crate::enclave_bridge::EnclaveProxy; use crate::storage::account::AccountStorage; use crate::storage::account::AccountWrapper; use crate::storage::COL_TX_META; use bit_vec::BitVec; use chain_core::state::account::{to_stake_key, StakedState, StakedStateAddress}; use chain_core::tx::data::input::TxoPointer; use chain_core::tx::fee::Fee; use chain_core::tx::TransactionId; use chain_core::tx::TxObfuscated; use chain_core::tx::{TxAux, TxEnclaveAux}; use chain_tx_validation::{ verify_node_join, verify_unbonding, verify_unjailed, verify_unjailing, witness::verify_tx_recover_address, ChainInfo, Error, NodeInfo, }; use enclave_protocol::{EnclaveRequest, EnclaveResponse}; use kvdb::KeyValueDB; use starling::constants::KEY_LEN; use std::sync::Arc; pub type StarlingFixedKey = [u8; KEY_LEN]; pub fn get_account( account_address: &StakedStateAddress, last_root: &StarlingFixedKey, accounts: &AccountStorage, ) -> Result<StakedState, Error> { let account_key = to_stake_key(account_address); let account = accounts.get_one(last_root, &account_key); match account { Err(_e) => Err(Error::IoError) /* FIXME: Err(Error::IoError(std::io::Error::new( std::io::ErrorKind::Other, e, )))*/, Ok(None) => Err(Error::AccountNotFound), Ok(Some(AccountWrapper(a))) => Ok(a), } } fn check_spent_input_lookup(inputs: &[TxoPointer], db: Arc<dyn KeyValueDB>) -> Result<(), Error> { if inputs.is_empty() { return Err(Error::NoInputs); } for txin in inputs.iter() { let txo = db.get(COL_TX_META, &txin.id[..]); match txo { Ok(Some(v)) => { let input_index = txin.index as usize; let bv = BitVec::from_bytes(&v).get(input_index); if bv.is_none() { return Err(Error::InvalidInput); } if bv.unwrap() { return Err(Error::InputSpent); } } Ok(None) => { return Err(Error::InvalidInput); } Err(_e) => { return Err(Error::IoError); } } } Ok(()) } pub fn verify_enclave_tx<T: EnclaveProxy>( tx_validator: &mut T, txaux: &TxEnclaveAux, extra_info: ChainInfo, last_account_root_hash: &StarlingFixedKey, db: Arc<dyn KeyValueDB>, accounts: &AccountStorage, ) -> Result<(Fee, Option<StakedState>), Error> { match txaux { TxEnclaveAux::TransferTx { inputs, no_of_outputs, payload, } => { check_spent_input_lookup(&inputs, db)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::TransferTx { inputs: inputs.clone(), no_of_outputs: *no_of_outputs, payload: payload.clone(), }, None, extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } TxEnclaveAux::DepositStakeTx { tx, payload } => { let maccount = get_account(&tx.to_staked_account, last_account_root_hash, accounts); let account = match maccount { Ok(a) => Some(a), Err(Error::AccountNotFound) => None, Err(e) => { return Err(e); } }; if let Some(ref account) = account { verify_unjailed(account)?; } check_spent_input_lookup(&tx.inputs, db)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::DepositStakeTx { tx: tx.clone(), payload: payload.clone(), }, account, extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } TxEnclaveAux::WithdrawUnbondedStakeTx { payload: TxObfuscated { key_from, init_vector, txpayload, txid, }, witness, no_of_outputs, } => { let account_address = verify_tx_recover_address(&witness, &txid); if let Err(_e) = account_address { return Err(Error::EcdsaCrypto); } let account = get_account(&account_address.unwrap(), last_account_root_hash, accounts)?; verify_unjailed(&account)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::WithdrawUnbondedStakeTx { payload: TxObfuscated { key_from: *key_from, init_vector: *init_vector, txpayload: txpayload.clone(), txid: *txid, }, witness: witness.clone(), no_of_outputs: *no_of_outputs, }, Some(account), extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } } } pub fn verify_public_tx( txaux: &TxAux, extra_info: ChainInfo, node_info: NodeInfo, last_account_root_hash: &StarlingFixedKey, accounts: &AccountStorage, ) -> Result<(Fee, Option<StakedState>), Error> { match txaux { TxAux::EnclaveTx(_) => unreachable!("should be handled by verify_enclave_tx"), TxAux::UnbondStakeTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_unbonding(maintx, extra_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } TxAux::UnjailTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_unjailing(maintx, extra_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } TxAux::NodeJoinTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_node_join(maintx, extra_info, node_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } } }
use crate::enclave_bridge::EnclaveProxy; use crate::storage::account::AccountStorage; use crate::storage::account::AccountWrapper; use crate::storage::COL_TX_META; use bit_vec::BitVec; use chain_core::state::account::{to_stake_key, StakedState, StakedStateAddress}; use chain_core::tx::data::input::TxoPointer; use chain_core::tx::fee::Fee; use chain_core::tx::TransactionId; use chain_core::tx::TxObfuscated; use chain_core::tx::{TxAux, TxEnclaveAux}; use chain_tx_validation::{ verify_node_join, verify_unbonding, verify_unjailed, verify_unjailing, witness::verify_tx_recover_address, ChainInfo, Error, NodeInfo, }; use enclave_protocol::{EnclaveRequest, EnclaveResponse}; use kvdb::KeyValueDB; use starling::constants::KEY_LEN; use std::sync::Arc; pub type StarlingFixedKey = [u8; KEY_LEN]; pub fn get_account( account_address: &StakedStateAddress, last_root: &StarlingFixedKey, accounts: &AccountStorage, ) -> Result<StakedState, Error> { let account_key = to_stake_key(account_address); let account = accounts.get_one(last_root, &account_key); match account { Err(_e) => Err(Error::IoErro
fn check_spent_input_lookup(inputs: &[TxoPointer], db: Arc<dyn KeyValueDB>) -> Result<(), Error> { if inputs.is_empty() { return Err(Error::NoInputs); } for txin in inputs.iter() { let txo = db.get(COL_TX_META, &txin.id[..]); match txo { Ok(Some(v)) => { let input_index = txin.index as usize; let bv = BitVec::from_bytes(&v).get(input_index); if bv.is_none() { return Err(Error::InvalidInput); } if bv.unwrap() { return Err(Error::InputSpent); } } Ok(None) => { return Err(Error::InvalidInput); } Err(_e) => { return Err(Error::IoError); } } } Ok(()) } pub fn verify_enclave_tx<T: EnclaveProxy>( tx_validator: &mut T, txaux: &TxEnclaveAux, extra_info: ChainInfo, last_account_root_hash: &StarlingFixedKey, db: Arc<dyn KeyValueDB>, accounts: &AccountStorage, ) -> Result<(Fee, Option<StakedState>), Error> { match txaux { TxEnclaveAux::TransferTx { inputs, no_of_outputs, payload, } => { check_spent_input_lookup(&inputs, db)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::TransferTx { inputs: inputs.clone(), no_of_outputs: *no_of_outputs, payload: payload.clone(), }, None, extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } TxEnclaveAux::DepositStakeTx { tx, payload } => { let maccount = get_account(&tx.to_staked_account, last_account_root_hash, accounts); let account = match maccount { Ok(a) => Some(a), Err(Error::AccountNotFound) => None, Err(e) => { return Err(e); } }; if let Some(ref account) = account { verify_unjailed(account)?; } check_spent_input_lookup(&tx.inputs, db)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::DepositStakeTx { tx: tx.clone(), payload: payload.clone(), }, account, extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } TxEnclaveAux::WithdrawUnbondedStakeTx { payload: TxObfuscated { key_from, init_vector, txpayload, txid, }, witness, no_of_outputs, } => { let account_address = verify_tx_recover_address(&witness, &txid); if let Err(_e) = account_address { return Err(Error::EcdsaCrypto); } let account = get_account(&account_address.unwrap(), last_account_root_hash, accounts)?; verify_unjailed(&account)?; let response = tx_validator.process_request(EnclaveRequest::new_tx_request( TxEnclaveAux::WithdrawUnbondedStakeTx { payload: TxObfuscated { key_from: *key_from, init_vector: *init_vector, txpayload: txpayload.clone(), txid: *txid, }, witness: witness.clone(), no_of_outputs: *no_of_outputs, }, Some(account), extra_info, )); match response { EnclaveResponse::VerifyTx(r) => r, _ => Err(Error::EnclaveRejected), } } } } pub fn verify_public_tx( txaux: &TxAux, extra_info: ChainInfo, node_info: NodeInfo, last_account_root_hash: &StarlingFixedKey, accounts: &AccountStorage, ) -> Result<(Fee, Option<StakedState>), Error> { match txaux { TxAux::EnclaveTx(_) => unreachable!("should be handled by verify_enclave_tx"), TxAux::UnbondStakeTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_unbonding(maintx, extra_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } TxAux::UnjailTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_unjailing(maintx, extra_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } TxAux::NodeJoinTx(maintx, witness) => { match verify_tx_recover_address(&witness, &maintx.id()) { Ok(account_address) => { let account = get_account(&account_address, last_account_root_hash, accounts)?; verify_node_join(maintx, extra_info, node_info, account) } Err(_) => { Err(Error::EcdsaCrypto) } } } } }
r) /* FIXME: Err(Error::IoError(std::io::Error::new( std::io::ErrorKind::Other, e, )))*/, Ok(None) => Err(Error::AccountNotFound), Ok(Some(AccountWrapper(a))) => Ok(a), } }
function_block-function_prefixed
[ { "content": "/// Verifies if the account is unjailed\n\npub fn verify_unjailed(account: &StakedState) -> Result<(), Error> {\n\n if account.is_jailed() {\n\n Err(Error::AccountJailed)\n\n } else {\n\n Ok(())\n\n }\n\n}\n\n\n\n/// information needed for NodeJoinRequestTx verification\n\np...
Rust
tests/integration_test.rs
durch/sphinx
b168f70ac422c6c6ecd80a784958cbee330aab44
extern crate sphinx; use sphinx::crypto; use sphinx::header::delays; use sphinx::route::{Destination, Node}; use sphinx::SphinxPacket; #[cfg(test)] mod create_and_process_sphinx_packet { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ DESTINATION_ADDRESS_LENGTH, IDENTIFIER_LENGTH, NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER, }, ProcessedPacket, }; use std::time::Duration; #[test] fn returns_the_correct_data_at_each_hop_for_route_of_3_mixnodes_without_surb() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], ); let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message.clone(), &route, &destination, &delays).unwrap(); let next_sphinx_packet_1 = match sphinx_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr1, _delay1) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_addr1 ); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr2, _delay2) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_addr2 ); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - message.len() - 1]; let expected_payload = [zero_bytes, message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; } } #[cfg(test)] mod converting_sphinx_packet_to_and_from_bytes { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ DESTINATION_ADDRESS_LENGTH, IDENTIFIER_LENGTH, NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER, }, ProcessedPacket, }; use std::time::Duration; #[test] fn it_is_possible_to_do_the_conversion_without_data_loss() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], ); let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message.clone(), &route, &destination, &delays).unwrap(); let sphinx_packet_bytes = sphinx_packet.to_bytes(); let recovered_packet = SphinxPacket::from_bytes(&sphinx_packet_bytes).unwrap(); let next_sphinx_packet_1 = match recovered_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_address, delay) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_address ); assert_eq!(delays[0].to_nanos(), delay.to_nanos()); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_address, delay) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_address ); assert_eq!(delays[1].to_nanos(), delay.to_nanos()); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - message.len() - 1]; let expected_payload = [zero_bytes, message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; } #[test] #[should_panic] fn it_panics_if_data_of_invalid_length_is_provided() { let (_, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (_, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (_, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], ); let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message, &route, &destination, &delays).unwrap(); let sphinx_packet_bytes = &sphinx_packet.to_bytes()[..300]; SphinxPacket::from_bytes(&sphinx_packet_bytes).unwrap(); } } #[cfg(test)] mod create_and_process_surb { use super::*; use crypto::EphemeralSecret; use sphinx::route::NodeAddressBytes; use sphinx::surb::{SURBMaterial, SURB}; use sphinx::{ constants::{NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER}, packet::builder::DEFAULT_PAYLOAD_SIZE, test_utils::fixtures::destination_fixture, ProcessedPacket, }; use std::time::Duration; #[test] fn returns_the_correct_data_at_each_hop_for_route_of_3_mixnodes() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node { address: NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), pub_key: node1_pk, }; let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node { address: NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), pub_key: node2_pk, }; let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node { address: NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), pub_key: node3_pk, }; let surb_route = vec![node1, node2, node3]; let surb_destination = destination_fixture(); let surb_initial_secret = EphemeralSecret::new(); let surb_delays = delays::generate_from_average_duration(surb_route.len(), Duration::from_secs(3)); let pre_surb = SURB::new( surb_initial_secret, SURBMaterial::new(surb_route, surb_delays.clone(), surb_destination), ) .unwrap(); let plaintext_message = vec![42u8; 160]; let (surb_sphinx_packet, first_hop) = SURB::use_surb(pre_surb, &plaintext_message, DEFAULT_PAYLOAD_SIZE).unwrap(); assert_eq!( first_hop, NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]) ); let next_sphinx_packet_1 = match surb_sphinx_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr1, _delay1) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_addr1 ); assert_eq!(_delay1, surb_delays[0]); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr2, _delay2) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_addr2 ); assert_eq!(_delay2, surb_delays[1]); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - plaintext_message.len() - 1]; let expected_payload = [zero_bytes, plaintext_message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; } }
extern crate sphinx; use sphinx::crypto; use sphinx::header::delays; use sphinx::route::{Destination, Node}; use sphinx::SphinxPacket; #[cfg(test)] mod create_and_process_sphinx_packet { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ DESTINATION_ADDRESS_LENGTH, IDENTIFIER_LENGTH, NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER, }, ProcessedPacket, }; use std::time::Duration; #[test] fn returns_the_correct_data_at_each_hop_for_route_of_3_mixnodes_without_surb() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], ); let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message.clone(), &route, &destination, &delays).unwrap(); let next_sphinx_packet_1 = match sphinx_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr1, _delay1) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_addr1 ); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr2, _delay2) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_addr2 ); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - message.len() - 1]; let expected_payload = [zero_bytes, message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; } } #[cfg(test)] mod converting_sphinx_packet_to_and_from_bytes { use super::*; use sphinx::route::{DestinationAddressBytes, NodeAddressBytes}; use sphinx::{ constants::{ DESTINATION_ADDRESS_LENGTH, IDENTIFIER_LENGTH, NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER, }, ProcessedPacket, }; use std::time::Duration; #[test] fn it_is_possible_to_do_the_conversion_without_data_loss() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], );
#[test] #[should_panic] fn it_panics_if_data_of_invalid_length_is_provided() { let (_, node1_pk) = crypto::keygen(); let node1 = Node::new( NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), node1_pk, ); let (_, node2_pk) = crypto::keygen(); let node2 = Node::new( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), node2_pk, ); let (_, node3_pk) = crypto::keygen(); let node3 = Node::new( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), node3_pk, ); let route = [node1, node2, node3]; let average_delay = Duration::from_secs_f64(1.0); let delays = delays::generate_from_average_duration(route.len(), average_delay); let destination = Destination::new( DestinationAddressBytes::from_bytes([3u8; DESTINATION_ADDRESS_LENGTH]), [4u8; IDENTIFIER_LENGTH], ); let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message, &route, &destination, &delays).unwrap(); let sphinx_packet_bytes = &sphinx_packet.to_bytes()[..300]; SphinxPacket::from_bytes(&sphinx_packet_bytes).unwrap(); } } #[cfg(test)] mod create_and_process_surb { use super::*; use crypto::EphemeralSecret; use sphinx::route::NodeAddressBytes; use sphinx::surb::{SURBMaterial, SURB}; use sphinx::{ constants::{NODE_ADDRESS_LENGTH, PAYLOAD_SIZE, SECURITY_PARAMETER}, packet::builder::DEFAULT_PAYLOAD_SIZE, test_utils::fixtures::destination_fixture, ProcessedPacket, }; use std::time::Duration; #[test] fn returns_the_correct_data_at_each_hop_for_route_of_3_mixnodes() { let (node1_sk, node1_pk) = crypto::keygen(); let node1 = Node { address: NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]), pub_key: node1_pk, }; let (node2_sk, node2_pk) = crypto::keygen(); let node2 = Node { address: NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), pub_key: node2_pk, }; let (node3_sk, node3_pk) = crypto::keygen(); let node3 = Node { address: NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), pub_key: node3_pk, }; let surb_route = vec![node1, node2, node3]; let surb_destination = destination_fixture(); let surb_initial_secret = EphemeralSecret::new(); let surb_delays = delays::generate_from_average_duration(surb_route.len(), Duration::from_secs(3)); let pre_surb = SURB::new( surb_initial_secret, SURBMaterial::new(surb_route, surb_delays.clone(), surb_destination), ) .unwrap(); let plaintext_message = vec![42u8; 160]; let (surb_sphinx_packet, first_hop) = SURB::use_surb(pre_surb, &plaintext_message, DEFAULT_PAYLOAD_SIZE).unwrap(); assert_eq!( first_hop, NodeAddressBytes::from_bytes([5u8; NODE_ADDRESS_LENGTH]) ); let next_sphinx_packet_1 = match surb_sphinx_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr1, _delay1) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_addr1 ); assert_eq!(_delay1, surb_delays[0]); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_addr2, _delay2) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_addr2 ); assert_eq!(_delay2, surb_delays[1]); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - plaintext_message.len() - 1]; let expected_payload = [zero_bytes, plaintext_message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; } }
let message = vec![13u8, 16]; let sphinx_packet = SphinxPacket::new(message.clone(), &route, &destination, &delays).unwrap(); let sphinx_packet_bytes = sphinx_packet.to_bytes(); let recovered_packet = SphinxPacket::from_bytes(&sphinx_packet_bytes).unwrap(); let next_sphinx_packet_1 = match recovered_packet.process(&node1_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_address, delay) => { assert_eq!( NodeAddressBytes::from_bytes([4u8; NODE_ADDRESS_LENGTH]), next_hop_address ); assert_eq!(delays[0].to_nanos(), delay.to_nanos()); next_packet } _ => panic!(), }; let next_sphinx_packet_2 = match next_sphinx_packet_1.process(&node2_sk).unwrap() { ProcessedPacket::ForwardHop(next_packet, next_hop_address, delay) => { assert_eq!( NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]), next_hop_address ); assert_eq!(delays[1].to_nanos(), delay.to_nanos()); next_packet } _ => panic!(), }; match next_sphinx_packet_2.process(&node3_sk).unwrap() { ProcessedPacket::FinalHop(_, _, payload) => { let zero_bytes = vec![0u8; SECURITY_PARAMETER]; let additional_padding = vec![0u8; PAYLOAD_SIZE - SECURITY_PARAMETER - message.len() - 1]; let expected_payload = [zero_bytes, message, vec![1], additional_padding].concat(); assert_eq!(expected_payload, payload.as_bytes()); } _ => panic!(), }; }
function_block-function_prefix_line
[ { "content": "pub fn random_node() -> Node {\n\n let random_private_key = crypto::PrivateKey::new();\n\n Node {\n\n address: NodeAddressBytes::from_bytes([2u8; NODE_ADDRESS_LENGTH]),\n\n pub_key: (&random_private_key).into(),\n\n }\n\n}\n", "file_path": "src/test_utils.rs", "rank"...
Rust
src/main.rs
teru01/mio_webserver
6f873861e272096684f2f76ad93220e49c0d1c8b
extern crate mio; extern crate regex; use std::net::SocketAddr; use std::{ env, str, fs }; use std::io::{ Error, Read, BufReader, Write }; use std::collections::HashMap; use mio::*; use mio::tcp::{ TcpListener, TcpStream }; use regex::Regex; const SERVER: Token = Token(0); const WEBROOT: &str = "/webroot"; struct WebServer { address: SocketAddr, connections: HashMap<usize, TcpStream>, next_connection_id: usize } impl WebServer { fn new(addr: &str) -> Self { let address = addr.parse().unwrap(); WebServer { address, connections: HashMap::new(), next_connection_id: 1 } } fn run(&mut self) -> Result<(), Error> { let server = TcpListener::bind(&self.address).expect("Failed to bind address"); let poll = Poll::new().unwrap(); poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut response = Vec::new(); loop { poll.poll(&mut events, None).unwrap(); for event in &events { match event.token() { SERVER => { self.connection_handler(&server, &poll); } Token(conn_id) => { self.http_handler(conn_id, event, &poll, &mut response); } } } } } fn connection_handler(&mut self, server: &TcpListener, poll: &Poll) { let (stream, remote) = server.accept().expect("Failed to accept connection"); println!("Connection from {}", &remote); let token = Token(self.next_connection_id); poll.register(&stream, token, Ready::readable(), PollOpt::edge()).unwrap(); if let Some(_) = self.connections.insert(self.next_connection_id, stream){ panic!("Failed to register connection"); } self.next_connection_id += 1; } fn http_handler(&mut self, conn_id: usize, event: Event, poll: &Poll, response: &mut Vec<u8>) { if let Some(stream) = self.connections.get_mut(&conn_id) { if event.readiness().is_readable() { println!("conn_id: {}", conn_id); let mut buffer = [0u8; 512]; let nbytes = stream.read(&mut buffer).expect("Failed to read"); if nbytes != 0 { *response = WebServer::make_response(&buffer, &nbytes).unwrap(); poll.reregister(stream, Token(conn_id), Ready::writable(), PollOpt::edge()).unwrap(); } else { self.connections.remove(&conn_id); } } else if event.readiness().is_writable() { stream.write(&response).expect("Failed to write"); stream.flush().unwrap(); self.connections.remove(&conn_id); } } } fn make_response(buffer: &[u8], nbytes: &usize) -> Result<Vec<u8>, Error> { let http_pattern = Regex::new(r"(.*) (.*) HTTP/1.([0-1])\r\n.*").unwrap(); let captures = match http_pattern.captures(str::from_utf8(&buffer[..*nbytes]).unwrap()) { Some(cap) => cap, None => { let mut response = Vec::new(); response.append(&mut "HTTP/1.0 400 Bad Request\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); return Ok(response); } }; let method = captures.get(1).unwrap().as_str(); let path = &format!("{}{}{}", env::current_dir().unwrap().display(), WEBROOT, captures.get(2).unwrap().as_str()); let _version = captures.get(3).unwrap().as_str(); if method == "GET" { let file = match fs::File::open(path) { Ok(file) => file, Err(_) => { let mut response = Vec::new(); response.append(&mut "HTTP/1.0 404 Not Found\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n\r\n".to_string().into_bytes()); return Ok(response); } }; let mut reader = BufReader::new(file); let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; let mut response = Vec::new(); response.append(&mut "HTTP/1.0 200 OK\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); response.append(&mut buf); return Ok(response); } let mut response = Vec::new(); response.append(&mut "HTTP/1.0 501 Not Implemented\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); return Ok(response); } } fn main() { let args:Vec<String> = env::args().collect(); if args.len() != 2 { eprintln!("Bad number of argments"); std::process::exit(1); } let mut server = WebServer::new(&args[1]); server.run().expect("Internal Server Error."); }
extern crate mio; extern crate regex; use std::net::SocketAddr; use std::{ env, str, fs }; use std::io::{ Error, Read, BufReader, Write }; use std::collections::HashMap; use mio::*; use mio::tcp::{ TcpListener, TcpStream }; use regex::Regex; const SERVER: Token = Token(0); const WEBROOT: &str = "/webroot"; struct WebServer { address: SocketAddr, connections: HashMap<usize, TcpStream>, next_connection_id: usize } impl WebServer { fn new(addr: &str) -> Self { let address = addr.parse().unwrap(); WebServer { address, connections: HashMap::new(), next_connection_id: 1 } } fn run(&mut self) -> Result<(), Error> { let server = TcpListener::bind(&self.address).expect("Failed to bind address"); let poll = Poll::new().unwrap(); poll.register(&server, SERVER, Ready::readable(), PollOpt::edge()).unwrap(); let mut events = Events::with_capacity(1024); let mut response = Vec::new(); loop { poll.poll(&mut events, None).unwrap(); for event in &events { match event.token() { SERVER => { self.connection_handler(&server, &poll); } Token(conn_id) => { self.http_handler(conn_id, event, &poll, &mut response); } } } } } fn connection_handler(&mut self, server: &TcpListener, poll: &Poll) { let (stream, remote) = server.accept().expect("Failed to accept connection"); println!("Connection from {}", &remote); let token = Token(self.next_connection_id); poll.register(&stream, token, Ready::readable(), PollOpt::edge()).unwrap(); if let Some(_) = self.connections.insert(self.next_connection_id, stream){ panic!("Failed to register connection"); } self.next_connection_id += 1; } fn http_handler(&mut self, conn_id: usize, event: Event, poll: &Poll, response: &mut Vec<u8>) { if let Some(stream) = self.connections.get_mut(&conn_id) {
} } fn make_response(buffer: &[u8], nbytes: &usize) -> Result<Vec<u8>, Error> { let http_pattern = Regex::new(r"(.*) (.*) HTTP/1.([0-1])\r\n.*").unwrap(); let captures = match http_pattern.captures(str::from_utf8(&buffer[..*nbytes]).unwrap()) { Some(cap) => cap, None => { let mut response = Vec::new(); response.append(&mut "HTTP/1.0 400 Bad Request\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); return Ok(response); } }; let method = captures.get(1).unwrap().as_str(); let path = &format!("{}{}{}", env::current_dir().unwrap().display(), WEBROOT, captures.get(2).unwrap().as_str()); let _version = captures.get(3).unwrap().as_str(); if method == "GET" { let file = match fs::File::open(path) { Ok(file) => file, Err(_) => { let mut response = Vec::new(); response.append(&mut "HTTP/1.0 404 Not Found\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n\r\n".to_string().into_bytes()); return Ok(response); } }; let mut reader = BufReader::new(file); let mut buf = Vec::new(); reader.read_to_end(&mut buf)?; let mut response = Vec::new(); response.append(&mut "HTTP/1.0 200 OK\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); response.append(&mut buf); return Ok(response); } let mut response = Vec::new(); response.append(&mut "HTTP/1.0 501 Not Implemented\r\n".to_string().into_bytes()); response.append(&mut "Server: mio webserver\r\n".to_string().into_bytes()); response.append(&mut "\r\n".to_string().into_bytes()); return Ok(response); } } fn main() { let args:Vec<String> = env::args().collect(); if args.len() != 2 { eprintln!("Bad number of argments"); std::process::exit(1); } let mut server = WebServer::new(&args[1]); server.run().expect("Internal Server Error."); }
if event.readiness().is_readable() { println!("conn_id: {}", conn_id); let mut buffer = [0u8; 512]; let nbytes = stream.read(&mut buffer).expect("Failed to read"); if nbytes != 0 { *response = WebServer::make_response(&buffer, &nbytes).unwrap(); poll.reregister(stream, Token(conn_id), Ready::writable(), PollOpt::edge()).unwrap(); } else { self.connections.remove(&conn_id); } } else if event.readiness().is_writable() { stream.write(&response).expect("Failed to write"); stream.flush().unwrap(); self.connections.remove(&conn_id); }
if_condition
[ { "content": "# mio_webserver\n\nNon-Blocking I/O web server with rust/mio.\n\n\n\n# How to use\n\n\n\n```\n\n$ cargo run [addr]:[port]\n\n```\n\n\n\nthen connect via telnet, nc or browser\n\n\n\n![sheep](https://user-images.githubusercontent.com/27873650/54591218-24c08c00-4a6d-11e9-9ead-49494b0adffc.png \"shee...
Rust
src/lib.rs
tstellanova/st7789
b1fe2c7af1947a044f37665315ddb28d9845b3ec
#![no_std] #![allow(clippy::type_complexity)] pub mod instruction; use crate::instruction::Instruction; use num_derive::ToPrimitive; use num_traits::ToPrimitive; use display_interface_spi::SPIInterface; use display_interface::WriteOnlyDataCommand; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[cfg(feature = "graphics")] mod graphics; #[cfg(feature = "batch")] mod batch; pub fn new_display_driver<SPI, CSX, DC, RST>( spi: SPI, csx: CSX, dc: DC, rst: RST, size_x: u16, size_y: u16, ) -> ST7789<SPIInterface<SPI, DC, CSX>, RST> where SPI: spi::Write<u8>, CSX: OutputPin, DC: OutputPin, RST: OutputPin, { let interface = SPIInterface::new(spi, dc, csx); ST7789::new(interface, rst, size_x as u16, size_y as u16) } pub struct ST7789<DI, RST> where DI: WriteOnlyDataCommand<u8>, RST: OutputPin, { di: DI, rst: RST, size_x: u16, size_y: u16, } #[derive(ToPrimitive)] pub enum Orientation { Portrait = 0b0000_0000, Landscape = 0b0110_0000, PortraitSwapped = 0b1100_0000, LandscapeSwapped = 0b1010_0000, } #[derive(Debug)] pub enum Error<PinE> { DisplayError, Pin(PinE), } impl<DI, RST, PinE> ST7789<DI, RST> where DI: WriteOnlyDataCommand<u8>, RST: OutputPin<Error = PinE>, { pub fn new(di: DI, rst: RST, size_x: u16, size_y: u16) -> Self { Self { di, rst, size_x, size_y, } } pub fn init(&mut self, delay_source: &mut impl DelayUs<u32>) -> Result<(), Error<PinE>> { self.hard_reset(delay_source)?; self.write_command(Instruction::SWRESET, None)?; delay_source.delay_us(150_000); self.write_command(Instruction::SLPOUT, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::INVOFF, None)?; self.write_command(Instruction::MADCTL, Some(&[0b0000_0000]))?; self.write_command(Instruction::COLMOD, Some(&[0b0101_0101]))?; self.write_command(Instruction::INVON, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::NORON, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::DISPON, None)?; delay_source.delay_us(10_000); Ok(()) } pub fn hard_reset(&mut self, delay_source: &mut impl DelayUs<u32>) -> Result<(), Error<PinE>> { self.rst.set_high().map_err(Error::Pin)?; delay_source.delay_us(10); self.rst.set_low().map_err(Error::Pin)?; delay_source.delay_us(10); self.rst.set_high().map_err(Error::Pin)?; delay_source.delay_us(10); Ok(()) } pub fn set_orientation(&mut self, orientation: &Orientation) -> Result<(), Error<PinE>> { let orientation = orientation.to_u8().unwrap_or(0); self.write_command(Instruction::MADCTL, Some(&[orientation]))?; Ok(()) } pub fn set_pixel(&mut self, x: u16, y: u16, color: u16) -> Result<(), Error<PinE>> { self.set_address_window(x, y, x, y)?; self.write_command(Instruction::RAMWR, None)?; self.write_word(color) } pub fn set_pixels<T>( &mut self, sx: u16, sy: u16, ex: u16, ey: u16, colors: T, ) -> Result<(), Error<PinE>> where T: IntoIterator<Item = u16>, { self.set_address_window(sx, sy, ex, ey)?; self.write_command(Instruction::RAMWR, None)?; self.write_pixels(colors) } #[cfg(not(feature = "buffer"))] fn write_pixels<T>(&mut self, colors: T) -> Result<(), Error<SPI, PinE>> where T: IntoIterator<Item = u16>, { for color in colors { self.write_word(color)?; } Ok(()) } #[cfg(feature = "buffer")] fn write_pixels<T>(&mut self, colors: T) -> Result<(), Error<PinE>> where T: IntoIterator<Item = u16>, { let mut buf = [0; 128]; let mut i = 0; for color in colors { let word = color.to_be_bytes(); buf[i] = word[0]; buf[i + 1] = word[1]; i += 2; if i == buf.len() { self.write_data(&buf)?; i = 0; } } if i > 0 { self.write_data(&buf[..i])?; } Ok(()) } fn write_command( &mut self, command: Instruction, params: Option<&[u8]>, ) -> Result<(), Error<PinE>> { self.di .send_commands(&[command.to_u8().unwrap()]) .map_err(|_| Error::DisplayError)?; if let Some(params) = params { self.di.send_data(params).map_err(|_| Error::DisplayError)?; } Ok(()) } fn write_data(&mut self, data: &[u8]) -> Result<(), Error<PinE>> { self.di.send_data(data).map_err(|_| Error::DisplayError)?; Ok(()) } fn write_word(&mut self, value: u16) -> Result<(), Error<PinE>> { self.write_data(&value.to_be_bytes()) } fn set_address_window( &mut self, sx: u16, sy: u16, ex: u16, ey: u16, ) -> Result<(), Error<PinE>> { self.write_command(Instruction::CASET, None)?; self.write_word(sx)?; self.write_word(ex)?; self.write_command(Instruction::RASET, None)?; self.write_word(sy)?; self.write_word(ey) } }
#![no_std] #![allow(clippy::type_complexity)] pub mod instruction; use crate::instruction::Instruction; use num_derive::ToPrimitive; use num_traits::ToPrimitive; use display_interface_spi::SPIInterface; use display_interface::WriteOnlyDataCommand; use embedded_hal::blocking::delay::DelayUs; use embedded_hal::blocking::spi; use embedded_hal::digital::v2::OutputPin; #[cfg(feature = "graphics")] mod graphics; #[cfg(feature = "batch")] mod batch; pub fn new_display_driver<SPI, CSX, DC, RST>( spi: SPI, csx: CSX, dc: DC, rst: RST, size_x: u16, size_y: u16, ) -> ST7789<SPIInterface<SPI, DC, CSX>, RST> where SPI: spi::Write<u8>, CSX: OutputPin, DC: OutputPin, RST: OutputPin, { let interface = SPIInterface::new(spi, dc, csx); ST7789::new(interface, rst, size_x as u16, size_y as u16) } pub struct ST7789<DI, RST> where DI: WriteOnlyDataCommand<u8>, RST: OutputPin, { di: DI, rst: RST, size_x: u16, size_y: u16, } #[derive(ToPrimitive)] pub enum Orientation { Portrait = 0b0000_0000, Landscape = 0b0110_0000, PortraitSwapped = 0b1100_0000, LandscapeSwapped = 0b1010_0000, } #[derive(Debug)] pub enum Error<PinE> { DisplayError, Pin(PinE), } impl<DI, RST, PinE> ST7789<DI, RST> where DI: WriteOnlyDataCommand<u8>, RST: OutputPin<Error = PinE>, { pub fn new(di: DI, rst: RST, size_x: u16, size_y: u16) -> Self { Self { di, rst, size_x, size_y, } } pub fn init(&mut self, delay_source: &mut impl DelayUs<u32>) -> Result<(), Error<PinE>> { self.hard_reset(delay_source)?; self.write_command(Instruction::SWRESET, None)?; delay_source.delay_us(150_000); self.write_command(Instruction::SLPOUT, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::INVOFF, None)?; self.write_command(Instruction::MADCTL, Some(&[0b0000_0000]))?; self.write_command(Instruction::COLMOD, Some(&[0b0101_0101]))?; self.write_command(Instruction::INVON, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::NORON, None)?; delay_source.delay_us(10_000); self.write_command(Instruction::DISPON, None)?; delay_source.delay_us(10_000); Ok(()) } pub fn hard_reset(&mut self, delay_source: &mut impl DelayUs<u32>) -> Result<(), Error<PinE>> { self.rst.set_high().map_err(Error::Pin)?; delay_source.delay_us(10); self.rst.set_low().map_err(Error::Pin)?; delay_source.delay_us(10); self.rst.set_high().map_err(Error::Pin)?; delay_source.delay_us(10); Ok(()) } pub fn set_orientation(&mut self, orientation: &Orientation) -> Result<(), Error<PinE>> { let orientation = orientation.to_u8().unwrap_or(0); self.write_command(Instruction::MADCTL, Some(&[orientation]))?; Ok(()) } pub fn set_pixel(&mut self, x: u16, y: u16, color: u16) -> Result<(), Error<PinE>> { self.set_address_window(x, y, x, y)?; self.write_command(Instruction::RAMWR, None)?; self.write_word(color) } pub fn set_pixels<T>( &mut self, sx: u16, sy: u16, ex: u16, ey: u16, colors: T, ) -> Result<(), Error<PinE>> where T: IntoIterator<Item = u16>, { self.set_address_window(sx, sy, ex, ey)?; self.write_command(Instruction::RAMWR, None)?; self.write_pixels(colors) } #[cfg(not(feature = "buffer"))] fn write_pixels<T>(&mut self, colors: T) -> Result<(), Error<SPI, PinE>> where T: IntoIterator<Item = u16>, { for color in colors { self.write_word(color)?; } Ok(()) } #[cfg(feature = "buffer")]
fn write_command( &mut self, command: Instruction, params: Option<&[u8]>, ) -> Result<(), Error<PinE>> { self.di .send_commands(&[command.to_u8().unwrap()]) .map_err(|_| Error::DisplayError)?; if let Some(params) = params { self.di.send_data(params).map_err(|_| Error::DisplayError)?; } Ok(()) } fn write_data(&mut self, data: &[u8]) -> Result<(), Error<PinE>> { self.di.send_data(data).map_err(|_| Error::DisplayError)?; Ok(()) } fn write_word(&mut self, value: u16) -> Result<(), Error<PinE>> { self.write_data(&value.to_be_bytes()) } fn set_address_window( &mut self, sx: u16, sy: u16, ex: u16, ey: u16, ) -> Result<(), Error<PinE>> { self.write_command(Instruction::CASET, None)?; self.write_word(sx)?; self.write_word(ex)?; self.write_command(Instruction::RASET, None)?; self.write_word(sy)?; self.write_word(ey) } }
fn write_pixels<T>(&mut self, colors: T) -> Result<(), Error<PinE>> where T: IntoIterator<Item = u16>, { let mut buf = [0; 128]; let mut i = 0; for color in colors { let word = color.to_be_bytes(); buf[i] = word[0]; buf[i + 1] = word[1]; i += 2; if i == buf.len() { self.write_data(&buf)?; i = 0; } } if i > 0 { self.write_data(&buf[..i])?; } Ok(()) }
function_block-full_function
[ { "content": "pub trait DrawBatch<DI, RST, T, PinE>\n\nwhere\n\n DI: WriteOnlyDataCommand<u8>,\n\n RST: OutputPin<Error = PinE>,\n\n T: IntoIterator<Item = Pixel<Rgb565>>,\n\n{\n\n fn draw_batch(&mut self, item_pixels: T) -> Result<(), Error<PinE>>;\n\n}\n\n\n\nimpl<DI, RST, T, PinE> DrawBatch<DI, R...
Rust
src/day4.rs
xosdy/aoc2018
c4824b9fb7cc437cf29dbc83cdb10cef3e5ccdd7
use chrono::{NaiveDateTime, Timelike}; use std::collections::HashMap; use std::ops::Range; pub struct Record { id: u32, time_intervals: Vec<Range<u32>>, } #[aoc_generator(day4)] pub fn input_generator(input: &str) -> Vec<Record> { let mut sorted_raw_records = input .lines() .map(|line| { let mut parts = line.split(']'); let date_time = NaiveDateTime::parse_from_str(&parts.next().unwrap()[1..], "%F %R").unwrap(); (date_time, parts.next().unwrap().trim()) }) .collect::<Vec<(NaiveDateTime, &str)>>(); sorted_raw_records.sort_by(|a, b| a.0.cmp(&b.0)); let mut records = Vec::new(); sorted_raw_records .iter() .for_each(|(date_time, raw_record)| { if raw_record.ends_with("begins shift") { let id = raw_record.split(' ').nth(1).unwrap()[1..].parse().unwrap(); records.push(Record { id, time_intervals: Vec::new(), }); } else if *raw_record == "falls asleep" { records .last_mut() .unwrap() .time_intervals .push(date_time.minute()..60); } else if *raw_record == "wakes up" { records .last_mut() .unwrap() .time_intervals .last_mut() .unwrap() .end = date_time.minute(); } }); records } pub fn get_sleep_times_by_guard(records: &[Record]) -> HashMap<u32, [u32; 60]> { let mut sleep_times_by_guard = HashMap::<u32, [u32; 60]>::new(); for record in records { sleep_times_by_guard .entry(record.id) .and_modify(|sleep_times| { for interval in &record.time_intervals { for i in interval.clone() { sleep_times[i as usize] += 1; } } }) .or_insert_with(|| { let mut sleep_times = [0; 60]; for interval in &record.time_intervals { for i in interval.clone() { sleep_times[i as usize] = 1; } } sleep_times }); } sleep_times_by_guard } #[aoc(day4, part1)] pub fn solve_part1(records: &[Record]) -> u32 { let sleep_times_by_guard = get_sleep_times_by_guard(records); let guard_with_max_minutes = sleep_times_by_guard .iter() .max_by_key::<u32, _>(|(_, times)| times.iter().sum()) .unwrap() .0; let sleep_in_most_minute = sleep_times_by_guard[guard_with_max_minutes] .iter() .enumerate() .max_by_key(|x| x.1) .unwrap() .0 as u32; guard_with_max_minutes * sleep_in_most_minute } #[aoc(day4, part2)] pub fn solve_part2(records: &[Record]) -> u32 { let sleep_times_by_guard = get_sleep_times_by_guard(records); let (guard, times, _) = sleep_times_by_guard .iter() .map(|(guard, times)| { let minute_and_times = times.iter().enumerate().max_by_key(|x| x.1).unwrap(); (guard, minute_and_times.0 as u32, minute_and_times.1) }) .max_by_key(|x| x.2) .unwrap(); guard * times } #[cfg(test)] mod tests { use super::*; #[test] fn part1() { assert_eq!( solve_part1(&input_generator( r"[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up" )), 240 ); } #[test] fn part2() { assert_eq!( solve_part2(&input_generator( r"[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up" )), 4455 ); } }
use chrono::{NaiveDateTime, Timelike}; use std::collections::HashMap; use std::ops::Range; pub struct Record { id: u32, time_intervals: Vec<Range<u32>>, } #[aoc_generator(day4)]
pub fn get_sleep_times_by_guard(records: &[Record]) -> HashMap<u32, [u32; 60]> { let mut sleep_times_by_guard = HashMap::<u32, [u32; 60]>::new(); for record in records { sleep_times_by_guard .entry(record.id) .and_modify(|sleep_times| { for interval in &record.time_intervals { for i in interval.clone() { sleep_times[i as usize] += 1; } } }) .or_insert_with(|| { let mut sleep_times = [0; 60]; for interval in &record.time_intervals { for i in interval.clone() { sleep_times[i as usize] = 1; } } sleep_times }); } sleep_times_by_guard } #[aoc(day4, part1)] pub fn solve_part1(records: &[Record]) -> u32 { let sleep_times_by_guard = get_sleep_times_by_guard(records); let guard_with_max_minutes = sleep_times_by_guard .iter() .max_by_key::<u32, _>(|(_, times)| times.iter().sum()) .unwrap() .0; let sleep_in_most_minute = sleep_times_by_guard[guard_with_max_minutes] .iter() .enumerate() .max_by_key(|x| x.1) .unwrap() .0 as u32; guard_with_max_minutes * sleep_in_most_minute } #[aoc(day4, part2)] pub fn solve_part2(records: &[Record]) -> u32 { let sleep_times_by_guard = get_sleep_times_by_guard(records); let (guard, times, _) = sleep_times_by_guard .iter() .map(|(guard, times)| { let minute_and_times = times.iter().enumerate().max_by_key(|x| x.1).unwrap(); (guard, minute_and_times.0 as u32, minute_and_times.1) }) .max_by_key(|x| x.2) .unwrap(); guard * times } #[cfg(test)] mod tests { use super::*; #[test] fn part1() { assert_eq!( solve_part1(&input_generator( r"[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up" )), 240 ); } #[test] fn part2() { assert_eq!( solve_part2(&input_generator( r"[1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up" )), 4455 ); } }
pub fn input_generator(input: &str) -> Vec<Record> { let mut sorted_raw_records = input .lines() .map(|line| { let mut parts = line.split(']'); let date_time = NaiveDateTime::parse_from_str(&parts.next().unwrap()[1..], "%F %R").unwrap(); (date_time, parts.next().unwrap().trim()) }) .collect::<Vec<(NaiveDateTime, &str)>>(); sorted_raw_records.sort_by(|a, b| a.0.cmp(&b.0)); let mut records = Vec::new(); sorted_raw_records .iter() .for_each(|(date_time, raw_record)| { if raw_record.ends_with("begins shift") { let id = raw_record.split(' ').nth(1).unwrap()[1..].parse().unwrap(); records.push(Record { id, time_intervals: Vec::new(), }); } else if *raw_record == "falls asleep" { records .last_mut() .unwrap() .time_intervals .push(date_time.minute()..60); } else if *raw_record == "wakes up" { records .last_mut() .unwrap() .time_intervals .last_mut() .unwrap() .end = date_time.minute(); } }); records }
function_block-full_function
[ { "content": "pub fn find_largest_power(serial: u32) -> (Vector2<u32>, i32) {\n\n let mut powers = HashMap::new();\n\n for y in 1..=298 {\n\n for x in 1..=298 {\n\n let position = Vector2::new(x, y);\n\n let power = get_square_power(serial, position, Vector2::new(3, 3));\n\n ...
Rust
src/webdata.rs
andete/show_bgs
4089d645c78ba7c6e98e8321aaee5862aec97228
use chrono::{Date,DateTime,Utc}; use data::{Allegiance, Government, State}; use data; use std::collections::{BTreeMap,HashMap,HashSet}; use serde::de::{self, Deserialize, Deserializer}; #[derive(Debug,Deserialize, Serialize)] pub struct Systems { pub report_name: String, pub systems: Vec<System>, pub dates: Vec<String>, pub dates10: Vec<String>, pub bgs_day: String, pub factions: HashMap<String, FactionGlobalState>, } #[derive(Debug,Deserialize, Serialize)] pub struct System { pub eddb_id:i64, pub name:String, pub population: i64, pub factions:HashMap<String, Faction>, pub factions_by_inf:Vec<Faction>, pub warnings:Vec<String>, pub controlling:String, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct Faction { pub name:String, pub government:Government, pub allegiance:Allegiance, pub evolution:Vec<FactionData>, pub evolution10:Vec<FactionData>, pub global:Option<FactionGlobalState>, pub color:String, pub at_home:bool, pub controlling:bool, pub is_player_faction:bool, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct FactionGlobalState { pub name:String, pub government:Government, pub allegiance:Allegiance, pub state_date:DateTime<Utc>, pub state_day:Option<u8>, pub state_max_length:u8, pub state_danger:bool, pub state:State, pub state_system:Option<String>, pub pending_state:Option<State>, pub pending_state_system:Option<String>, pub recovery_state:Option<State>, pub recovery_state_system:Option<String>, pub is_player_faction:bool, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct FactionData { pub date:DateTime<Utc>, pub label_date:String, pub influence:f64, pub state:State, pub state_day:u8, pub state_max_length:u8, pub state_danger:bool, pub pending_states:Vec<FactionState>, pub recovering_states:Vec<FactionState>, pub influence_danger:bool, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct FactionState { pub state:State, pub state_recovery_length:u8, pub state_pending_length:u8, pub trend:data::Trend, pub trend_display:String, pub state_day:u8, pub state_pending_danger:bool, } impl From<data::System> for System { fn from(s:data::System) -> System { System { eddb_id:s.eddb_id, name:s.name.clone(), population:s.population, factions:HashMap::new(), factions_by_inf:vec![], warnings:vec![], controlling:s.dynamic.controlling_minor_faction, } } } impl<'a> From<&'a data::Faction> for Faction { fn from(s:&'a data::Faction) -> Faction { Faction { name:s.name.clone(), government:s.government, allegiance:s.allegiance, evolution:vec![], evolution10:vec![], color:"".into(), global:None, at_home:false, controlling:false, is_player_faction:s.is_player_faction, } } } impl<'a> From<&'a data::Faction> for FactionGlobalState { fn from(s:&'a data::Faction) -> FactionGlobalState { let (state, system) = s.faction_state(); let state:State = state.into(); let (pending_state, pending_system) = s.faction_pending_single_system_state(); let (recovery_state, recovery_system) = s.faction_recovering_single_system_state(); FactionGlobalState { name:s.name.clone(), government:s.government, allegiance:s.allegiance, state:state, state_system:system, state_date:s.dynamic.eddbv3_updated_at, state_day:None, state_max_length:state.max_length(), state_danger:state.danger(), pending_state:pending_state, pending_state_system:pending_system, recovery_state:recovery_state, recovery_state_system:recovery_system, is_player_faction:s.is_player_faction, } } } impl From <data::FactionHistory> for FactionData { fn from(h:data::FactionHistory) -> FactionData { let state:State = h.presence.state.into(); FactionData { date:h.updated_at, label_date:format!("{}", h.updated_at.format("%d/%m")), influence:h.presence.influence, state:state, state_day:0, state_max_length:state.max_length(), pending_states:h.presence.pending_states.into_iter().map(|s| s.into()).collect(), recovering_states:h.presence.recovering_states.into_iter().map(|s| s.into()).collect(), state_danger:state.danger(), influence_danger:false, } } } impl From <data::StateTrend> for FactionState { fn from(s:data::StateTrend) -> FactionState { let d = match s.trend { data::Trend::Up => "&uarr;", data::Trend::Down => "&darr;", data::Trend::Level => "&harr;", }.into(); let state:State = s.state.into(); FactionState { state:state, trend:s.trend, trend_display:d, state_day:0, state_recovery_length:state.recovery(), state_pending_length:state.pending(), state_pending_danger:state.pending_danger(), } } } fn update_states(states:&mut Vec<FactionState>, h:&mut HashMap<State,u8>) { let mut seen = HashSet::new(); for state in states { seen.insert(state.state); if !h.contains_key(&state.state) { h.insert(state.state, 1); state.state_day = 1; } else { let n = h.get(&state.state).unwrap() + 1; h.insert(state.state, n); state.state_day = n; } } let keys:Vec<State> = h.keys().cloned().collect(); for k in keys { if !seen.contains(&k) { h.remove(&k); } } } impl Faction { pub fn cleanup_evolution(&mut self, dates:&Vec<Date<Utc>>) { let mut b = BTreeMap::new(); for e in &self.evolution { let date = e.date.date(); if !b.contains_key(&date) { b.insert(date, vec![e.clone()]); } else { b.get_mut(&date).unwrap().push(e.clone()) } } let mut v = vec![]; let mut prev_inf = 0.0; for (_day, values) in b { let mut found = false; for val in &values { if val.influence != prev_inf { v.push(val.clone()); prev_inf = val.influence; found = true; break; } } if !found { info!("{} INF stayed equal", self.name); v.push(values[0].clone()) } } let mut di = dates.iter(); let mut prev:Option<FactionData> = None; let mut v2 = vec![]; for e in v { let mut date = di.next().unwrap(); while *date != e.date.date() { if let Some(e2) = prev { let mut e3 = e2.clone(); e3.date = date.and_hms(12,30,0); e3.label_date = format!("{}", date.format("%d/%m")); v2.push(e3.clone()); prev = Some(e3); } else { } date = di.next().unwrap(); } v2.push(e.clone()); prev = Some(e.clone()); } self.evolution = v2; } pub fn fill_in_state_days(&mut self) { let mut prev_state = State::None; let mut recovery_states = HashMap::new(); let mut pending_states = HashMap::new(); let mut c:u8 = 1; for e in &mut self.evolution { if e.state != prev_state { prev_state = e.state; c = 1; e.state_day = c; } else { c += 1; e.state_day = c; } update_states(&mut e.pending_states, &mut pending_states); update_states(&mut e.recovering_states, &mut recovery_states); } } pub fn fill_in_evolution10(&mut self, dates: &Vec<Date<Utc>>) { let dates10 = dates.as_slice().windows(10).last().unwrap().to_vec(); let mut ev = vec![]; for e in &self.evolution { if dates10.contains(&e.date.date()) { ev.push(e.clone()) } } self.evolution10 = ev; } pub fn latest_inf(&self) -> i64 { (self.evolution.last().unwrap().influence * 1000.0) as i64 } pub fn fill_in_state_other_system(&mut self) { } } impl<'de> Deserialize<'de> for State { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?.to_lowercase(); let state = match s.as_str() { "expansion" => State::Expansion, "war" => State::War, "civil unrest" | "civilunrest" => State::CivilUnrest, "civil war" | "civilwar" => State::CivilWar, "election" => State::Election, "boom" => State::Boom, "bust" => State::Bust, "famine" => State::Famine, "lockdown" => State::Lockdown, "investment" => State::Investment, "retreat" => State::Retreat, "outbreak" => State::Outbreak, "none" => State::None, other => { return Err(de::Error::custom(format!("Invalid state '{}'", other))); }, }; Ok(state) } }
use chrono::{Date,DateTime,Utc}; use data::{Allegiance, Government, State}; use data; use std::collections::{BTreeMap,HashMap,HashSet}; use serde::de::{self, Deserialize, Deserializer}; #[derive(Debug,Deserialize, Serialize)] pub struct Systems { pub report_name: String, pub systems: Vec<System>, pub dates: Vec<String>, pub dates10: Vec<String>, pub bgs_day: String, pub factions: HashMap<String, FactionGlobalState>, } #[derive(Debug,Deserialize, Serialize)] pub struct System { pub eddb_id:i64, pub name:String, pub population: i64, pub factions:HashMap<String, Faction>, pub factions_by_inf:Vec<Faction>, pub warnings:Vec<String>, pub controlling:String, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct Faction { pub name:String, pub government:Government, pub allegiance:Allegiance, pub evolution:Vec<FactionData>, pub evolution10:Vec<FactionData>, pub global:Option<FactionGlobalState>, pub color:String, pub at_home:bool, pub controlling:bool, pub is_player_faction:bool, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct FactionGlobalState { pub name:String, pub government:Government, pub allegiance:Allegiance, pub state_date:DateTime<Utc>, pub state_day:Option<u8>, pub state_max_length:u8, pub state_danger:bool, pub state:State, pub state_system:Option<String>, pub pending_state:Option<State>, pub pending_state_system:Option<String>, pub recovery_state:Option<State>, pub recovery_state_system:Option<String>, pub is_player_faction:bool, } #[derive(Debug,Deserialize, Serialize, Clone)] pub struct FactionData { pub date:DateTime<Utc>, pub label_date:String, pub influence:f64, pub state:State, pub state_day:u8, pub state_max_length:u8, pub state_danger:bool, pub pending_states:Vec<FactionState>, pub recovering_states:Vec<FactionState>, pub influence_danger:bool, } #[derive(Debug, Deserialize, Serialize, Clone)] pub struct FactionState { pub state:State, pub state_recovery_length:u8, pub state_pending_length:u8, pub trend:data::Trend, pub trend_display:String, pub state_day:u8, pub state_pending_danger:bool, } impl From<data::System> for System { fn from(s:data::System) -> System { System { eddb_id:s.eddb_id, name:s.name.clone(), population:s.population, factions:HashMap::new(), factions_by_inf:vec![], warnings:vec![], controlling:s.dynamic.controlling_minor_faction, } } } impl<'a> From<&'a data::Faction> for Faction { fn from(s:&'a data::Faction) -> Faction { Faction { name:s.name.clone(), government:s.government, allegiance:s.allegiance, evolution:vec![], evolution10:vec![], color:"".into(), global:None, at_home:false, controlling:false, is_player_faction:s.is_player_faction, } } } impl<'a> From<&'a data::Faction> for FactionGlobalState { fn from(s:&'a data::Faction) -> FactionGlobalState { let (state, system) = s.faction_state(); let state:State = state.into(); let (pending_state, pending_system) = s.faction_pending_single_system_state(); let (recovery_state, recovery_system) = s.faction_recovering_single_system_state(); FactionGlobalState { name:s.name.clone(), government:s.government, allegiance:s.allegiance, state:state, state_system:system, state_date:s.dynamic.eddbv3_updated_at, state_day:None, state_max_length:state.max_length(), state_danger:state.danger(), pending_state:pending_state, pending_state_system:pending_system, recovery_state:recovery_state, recovery_state_system:recovery_system, is_player_faction:s.is_player_faction, } } } impl From <data::FactionHistory> for FactionData { fn from(h:data::FactionHistory) -> FactionData { let state:State = h.presence.state.into(); FactionData { date:h.updated_at, label_date:format!("{}", h.updated_at.format("%d/%m")), influence:h.presence.influence, state:state, state_day:0, state_max_length:state.max_length(), pending_states:h.presence.pending_states.into_iter().map(|s| s.into()).collect(), recovering_states:h.presence.recovering_states.into_iter().map(|s| s.into()).collect(), state_danger:state.danger(), influence_danger:false, } } } impl From <data::StateTrend> for FactionState { fn from(s:data::StateTrend) -> FactionState { let d = match s.trend { data::Trend::Up => "&uarr;", data::Trend::Down => "&darr;", data::Trend::Level => "&harr;", }.into(); let state:State = s.state.into(); FactionState { state:state, trend:s.trend, trend_display:d, state_day:0, state_recovery_length:state.recovery(), state_pending_length:state.pending(), state_pending_danger:state.pending_danger(), } } } fn update_states(states:&mut Vec<FactionState>, h:&mut HashMap<State,u8>) { let mut seen = HashSet::new(); for state in states { seen.insert(state.state); if !h.contains_key(&state.state) { h.insert(state.state, 1); state.state_day = 1; } else { let n = h.get(&state.state).unwrap() + 1; h.insert(state.state, n); state.state_day = n; } } let keys:Vec<State> = h.keys().cloned().collect(); for k in keys { if !seen.contains(&k) { h.remove(&k); } } } impl Faction { pub fn cleanup_evolution(&mut self, dates:&Vec<Date<Utc>>) { let mut b = BTreeMap::new(); for e in &self.evolution { let date = e.date.date(); if !b.contains_key(&date) { b.insert(date, vec![e.clone()]); } else { b.get_mut(&date).unwrap().push(e.clone()) } } let mut v = vec![]; let mut prev_inf = 0.0; for (_day, values) in b { let mut found = false; for val in &values { if val.influence != prev_inf { v.push(val.clone()); prev_inf = val.influence; found = true; break; } } if !found { info!("{} INF stayed equal", self.name); v.push(values[0].clone()) } } let mut di = dates.iter(); let mut prev:Option<FactionData> = None; let mut v2 = vec![]; for e in v { let mut date = di.next().unwrap(); while *date != e.date.date() { if let Some(e2) = prev { let mut e3 = e2.clone(); e3.date = date.and_hms(12,30,0); e3.label_date = format!("{}", date.format("%d/%m")); v2.push(e3.clone()); prev = Some(e3); } else { } date = di.next().unwrap(); } v2.push(e.clone()); prev = Some(e.clone()); } self.evolution = v2; } pub fn fill_in_state_days(&mut self) { let mut prev_state = State::None; let mut recovery_states = HashMap::new(); let mut pending_states = HashMap::new(); let mut c:u8 = 1; for e in &mut self.evolution { if e.state != prev_state { prev_state = e.state; c = 1; e.state_day = c; } else { c += 1; e.state_day = c; } update_states(&mut e.pending_states, &mut pending_states); update_states(&mut e.recovering_states, &mut recovery_states); } } pub fn fill_in_evolution10(&mut self, dates: &Vec<Date<Utc>>) { let dates10 = dates.as_slice().windows(10).last().unwrap().to_vec(); let mut ev = vec![]; for e in &self.evolution { if dates10.contains(&e.date.date()) { ev.push(e.clone()) } } self.evolution10 = ev; } pub fn latest_inf(&self) -> i64 { (self.evolution.last().unwrap().influence * 1000.0) as i64 } pub fn fill_in_state_other_system(&mut self) { } } impl<'de> Deserialize<'de> for State { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?.to_lowercase(); let state = match s.as_str() { "expansion" => Stat
}
e::Expansion, "war" => State::War, "civil unrest" | "civilunrest" => State::CivilUnrest, "civil war" | "civilwar" => State::CivilWar, "election" => State::Election, "boom" => State::Boom, "bust" => State::Bust, "famine" => State::Famine, "lockdown" => State::Lockdown, "investment" => State::Investment, "retreat" => State::Retreat, "outbreak" => State::Outbreak, "none" => State::None, other => { return Err(de::Error::custom(format!("Invalid state '{}'", other))); }, }; Ok(state) }
function_block-function_prefixed
[ { "content": "pub fn fetch(config: &Config, n_days:i64) {\n\n info!(\"Fetching system info for last {} days\", n_days);\n\n info!(\"and discovering minor factions\");\n\n\n\n let system_names = config.systems();\n\n info!(\"systems: {:?}\", system_names);\n\n\n\n let datadir = config.datadir();\n...
Rust
crossterm_input/src/input/input.rs
defiori/crossterm
3d92f62be470973772e2d3d83fd672c2613f0f87
use super::*; use std::{thread, time::Duration}; use crossterm_utils::TerminalOutput; pub struct TerminalInput<'stdout> { terminal_input: Box<ITerminalInput + Sync + Send>, stdout: Option<&'stdout Arc<TerminalOutput>>, } impl<'stdout> TerminalInput<'stdout> { pub fn new() -> TerminalInput<'stdout> { #[cfg(target_os = "windows")] let input = Box::from(WindowsInput::new()); #[cfg(not(target_os = "windows"))] let input = Box::from(UnixInput::new()); TerminalInput { terminal_input: input, stdout: None, } } pub fn from_output(stdout: &'stdout Arc<TerminalOutput>) -> TerminalInput<'stdout> { #[cfg(target_os = "windows")] let input = Box::from(WindowsInput::new()); #[cfg(not(target_os = "windows"))] let input = Box::from(UnixInput::new()); TerminalInput { terminal_input: input, stdout: Some(stdout), } } pub fn read_line(&self) -> io::Result<String> { if let Some(stdout) = self.stdout { if stdout.is_in_raw_mode { return Err(Error::new(ErrorKind::Other, "Crossterm does not support readline in raw mode this should be done instead whit `read_async` or `read_async_until`")); } } let mut rv = String::new(); io::stdin().read_line(&mut rv)?; let len = rv.trim_right_matches(&['\r', '\n'][..]).len(); rv.truncate(len); Ok(rv) } pub fn read_char(&self) -> io::Result<char> { self.terminal_input.read_char(&self.stdout) } pub fn read_async(&self) -> AsyncReader { self.terminal_input.read_async(&self.stdout) } pub fn read_until_async(&self, delimiter: u8) -> AsyncReader { self.terminal_input .read_until_async(delimiter, &self.stdout) } pub fn wait_until(&self, key_event: KeyEvent) { let mut stdin = self.read_async().bytes(); loop { let pressed_key: Option<Result<u8, Error>> = stdin.next(); match pressed_key { Some(Ok(value)) => match key_event { KeyEvent::OnKeyPress(ascii_code) => { if value == ascii_code { break; } } KeyEvent::OnEnter => { if value == b'\r' { break; } } KeyEvent::OnAnyKeyPress => { break; } }, _ => {} } thread::sleep(Duration::from_millis(10)); } } } pub fn input<'stdout>() -> TerminalInput<'stdout> { TerminalInput::new() }
use super::*; use std::{thread, time::Duration}; use crossterm_utils::TerminalOutput; pub struct TerminalInput<'stdout> { terminal_input: Box<ITerminalInput + Sync + Send>, stdout: Option<&'stdout Arc<TerminalOutput>>, } impl<'stdout> TerminalInput<'stdout> { pub fn new() -> TerminalInput<'stdout> { #[cfg(target_os = "windows")] let input = Box::from(WindowsInput::new()); #[cfg(not(target_os = "windows"))] let input = Box::from(UnixInput::new()); TerminalInput { terminal_input: input, stdout: None, } } pub fn from_output(stdout: &'stdout Arc<TerminalOutput>) -> TerminalInput<'stdout> { #[cfg(target_os = "windows")] let input = Box::from(WindowsInput::new()); #[cfg(not(target_os = "windows"))] let input = Box::from(UnixInput::new()); TerminalInput { terminal_input: input, stdout: Some(stdout), } } pub fn read_line(&self) -> io::Result<String> { if let Some(stdout) = self.stdout { if stdout.is_in_raw_mode { return Err(Error::new(ErrorKind::Other, "Crossterm does not support readline in raw mode this should be done instead whit `read_async` or `read_async_until`")); } } let mut rv = String::new();
pub fn read_until_async(&self, delimiter: u8) -> AsyncReader { self.terminal_input .read_until_async(delimiter, &self.stdout) } pub fn wait_until(&self, key_event: KeyEvent) { let mut stdin = self.read_async().bytes(); loop { let pressed_key: Option<Result<u8, Error>> = stdin.next(); match pressed_key { Some(Ok(value)) => match key_event { KeyEvent::OnKeyPress(ascii_code) => { if value == ascii_code { break; } } KeyEvent::OnEnter => { if value == b'\r' { break; } } KeyEvent::OnAnyKeyPress => { break; } }, _ => {} } thread::sleep(Duration::from_millis(10)); } } } pub fn input<'stdout>() -> TerminalInput<'stdout> { TerminalInput::new() }
io::stdin().read_line(&mut rv)?; let len = rv.trim_right_matches(&['\r', '\n'][..]).len(); rv.truncate(len); Ok(rv) } pub fn read_char(&self) -> io::Result<char> { self.terminal_input.read_char(&self.stdout) } pub fn read_async(&self) -> AsyncReader { self.terminal_input.read_async(&self.stdout) }
random
[ { "content": "pub fn raw_modes() {\n\n // create a Screen instance who operates on the default output; io::stdout().\n\n let screen = Screen::default();\n\n\n\n // create a Screen instance who operates on the default output; io::stdout(). By passing in 'true' we make this screen 'raw'\n\n let screen...
Rust
src/transport.rs
balajijinnah/nilai-rs
22510cca078d4de0069491ccb745b95349460f77
/* * Copyright 2019 balajijinnah and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use super::types::*; use failure::Error; use futures::channel::mpsc; use futures::channel::oneshot; use futures::SinkExt; use futures::StreamExt; use log::{info, warn}; use num_enum::TryFromPrimitive; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::net::SocketAddr; use tokio::net::udp::split::{UdpSocketRecvHalf, UdpSocketSendHalf}; fn decode_msg(buf: &Vec<u8>) -> Result<Message, Error> { let mut deserializer = Deserializer::new(&buf[1..]); match MessageType::try_from(*&buf[0])? { MessageType::PingMsg => { let msg: Ping = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::PingMsg(msg)); } MessageType::IndirectPingMsg => { let msg: IndirectPing = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::IndirectPingMsg(msg)); } MessageType::AckRespMsg => { let msg: AckRes = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Ack(msg)); } MessageType::SuspectMsg => { let msg: Suspect = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::SuspectMsg(msg)); } MessageType::AliveMsg => { let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Alive(msg)); } MessageType::DeadMsg => { let msg: Dead = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Dead(msg)); } MessageType::StateSync => { println!("got udp state sync"); let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::StateSync(msg)); } MessageType::StateSyncRes => { let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::StateSyncRes(msg)); } } } fn encode_msg(msg: Message, buf: &mut Vec<u8>) -> Result<(), Error> { match msg { Message::PingMsg(msg) => { buf.push(MessageType::PingMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::IndirectPingMsg(msg) => { buf.push(MessageType::IndirectPingMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Ack(msg) => { buf.push(MessageType::AckRespMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::SuspectMsg(msg) => { buf.push(MessageType::SuspectMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Alive(msg) => { buf.push(MessageType::AliveMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Dead(msg) => { buf.push(MessageType::DeadMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::StateSync(msg) => { println!("sending state sync"); buf.push(MessageType::StateSync as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::StateSyncRes(msg) => { buf.push(MessageType::StateSyncRes as u8); msg.serialize(&mut Serializer::new(buf))?; } _ => { unimplemented!(); } } Ok(()) } #[derive(Debug)] pub(crate) struct TransportReceiver { pub handler_ch: mpsc::Sender<UdpMessage>, pub udp_socket_receiver: UdpSocketRecvHalf, pub closer: oneshot::Receiver<i32>, } impl TransportReceiver { pub(crate) async fn listen(&mut self) { let mut buf = vec![0; 1024]; loop { if let Ok(opt) = self.closer.try_recv() { if let Some(_) = opt { info!("stopping transport receiver"); break; } } match self.udp_socket_receiver.recv_from(&mut buf).await { Ok((read_bytes, from)) => { info!("{} bytes received", read_bytes); if read_bytes == 0 { continue; } match decode_msg(&buf) { Ok(msg) => { self.send_msg(from, msg).await; } Err(err) => { println!("unable to decode"); warn!("unable to decode the message {}", err); } } } Err(err) => { warn!("{} error while receiving the packets", err); } } } } async fn send_msg(&mut self, from: SocketAddr, msg: Message) { if let Err(e) = self .handler_ch .send(UdpMessage { peer: Some(from), msg: msg, }) .await { warn!("unable to send to the nilai handler {}", e); } } } #[derive(Debug, TryFromPrimitive)] #[repr(u8)] pub(crate) enum MessageType { PingMsg = 0, IndirectPingMsg = 1, AckRespMsg = 2, SuspectMsg = 3, AliveMsg = 4, DeadMsg = 5, StateSync = 6, StateSyncRes = 7, } pub(crate) struct TransportSender { pub udp_socket_sender: UdpSocketSendHalf, pub handler_recv_ch: mpsc::Receiver<UdpMessage>, pub closer: oneshot::Receiver<i32>, } impl TransportSender { pub(crate) async fn listen(&mut self) { let mut buf = vec![0; 1024]; loop { if let Ok(opt) = self.closer.try_recv() { if let Some(_) = opt { info!("stopping transport sender"); break; } } buf.clear(); match self.handler_recv_ch.next().await { Some(udp_msg) => { let peer = udp_msg.peer.unwrap(); match encode_msg(udp_msg.msg, &mut buf) { Ok(_) => { match self .udp_socket_sender .send_to(&buf[..buf.len()], &peer) .await { Err(e) => { warn!("error while sending udp message {} {}", e, peer); continue; } Ok(bytes_sent) => { info!("bytes sent {}", bytes_sent); } } } Err(e) => { warn!("unable to decode the message {} ", e); } } } None => { info!("stopping to listen for handler message"); break; } } } } }
/* * Copyright 2019 balajijinnah and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use super::types::*; use failure::Error; use futures::channel::mpsc; use futures::channel::oneshot; use futures::SinkExt; use futures::StreamExt; use log::{info, warn}; use num_enum::TryFromPrimitive; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use std::convert::TryFrom; use std::net::SocketAddr; use tokio::net::udp::split::{UdpSocketRecvHalf, UdpSocketSendHalf}; fn decode_msg(buf: &Vec<u8>) -> Result<Message, Error> { let mut deserializer = Deserializer::new(&buf[1..]); match MessageType::try_from(*&buf[0])? { MessageType::PingMsg => { let msg: Ping = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::PingMsg(msg)); } MessageType::IndirectPingMsg => { let msg: IndirectPing = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::IndirectPingMsg(msg)); } MessageType::AckRespMsg => { let msg: AckRes = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Ack(msg)); } MessageType::SuspectMsg => { let msg: Suspect = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::SuspectMsg(msg)); } MessageType::AliveMsg => { let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Alive(msg)); } MessageType::DeadMsg => { let msg: Dead = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::Dead(msg)); } MessageType::StateSync => { println!("got udp state sync"); let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::StateSync(msg)); } MessageType::StateSyncRes => { let msg: Alive = Deserialize::deserialize(&mut deserializer)?; return Ok(Message::StateSyncRes(msg)); } } } fn encode_msg(msg: Message, buf: &mut Vec<u8>) -> Result<(), Error> { match msg { Message::PingMsg(msg) => { buf.push(MessageType::PingMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::IndirectPingMsg(msg) => { buf.push(MessageType::IndirectPingMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Ack(msg) => { buf.push(MessageType::AckRespMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::SuspectMsg(msg) => { buf.push(MessageType::SuspectMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Alive(msg) => { buf.push(MessageType::AliveMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::Dead(msg) => { buf.push(MessageType::DeadMsg as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::StateSync(msg) => { println!("sending state sync"); buf.push(MessageType::StateSync as u8); msg.serialize(&mut Serializer::new(buf))?; } Message::StateSyncRes(msg) => { buf.push(MessageType::StateSyncRes as u8); msg.serialize(&mut Serializer::new(buf))?; } _ => { unimplemented!(); } } Ok(()) } #[derive(Debug)] pub(crate) struct TransportReceiver { pub handler_ch: mpsc::Sender<UdpMessage>, pub udp_socket_receiver: UdpSocketRecvHalf, pub closer: oneshot::Receiver<i32>, } impl TransportReceiver { pub(crate) async fn listen(&mut self) { let mut buf = vec![0; 1024]; loop { if let Ok(opt) = self.closer.try_recv() { if let Some(_) = opt { info!("stopping transport receiver"); break; } } match self.udp_socket_receiver.recv_from(&mut buf).await { Ok((read_bytes, from)) => { info!("{} bytes received", read_bytes); if read_bytes == 0 { continue; } match decode_msg(&buf) { Ok(msg) => { self.send_msg(from, msg).await; } Err(err) => { println!("unable to decode"); warn!("unable to decode the message {}", err); } } } Err(err) => { warn!("{} error while receiving the packets", err); } } } } async fn send_msg(&mut self, from: SocketAddr, msg: Message) { if let Err(e) = self .handler_ch .send(UdpMessage { peer: Some(from), msg: msg, }) .await { warn!("unable to send to the nilai handler {}", e); } } } #[derive(Debug, TryFromPrimitive)] #[repr(u8)] pub(crate) enum MessageType { PingMsg = 0, IndirectPingMsg = 1, AckRespMsg = 2, SuspectMsg = 3, AliveMsg = 4, DeadMsg = 5, StateSync = 6, StateSyncRes = 7, } pub(crate) struct TransportSender { pub udp_socket_sender: UdpSocketSendHalf, pub handler_recv_ch: mpsc::Receiver<UdpMessage>, pub closer: oneshot::Receiver<i32>, } impl TransportSender { pub(crate) async fn listen(&mut self) { let mut buf = vec![0; 1024]; loop {
buf.clear(); match self.handler_recv_ch.next().await { Some(udp_msg) => { let peer = udp_msg.peer.unwrap(); match encode_msg(udp_msg.msg, &mut buf) { Ok(_) => { match self .udp_socket_sender .send_to(&buf[..buf.len()], &peer) .await { Err(e) => { warn!("error while sending udp message {} {}", e, peer); continue; } Ok(bytes_sent) => { info!("bytes sent {}", bytes_sent); } } } Err(e) => { warn!("unable to decode the message {} ", e); } } } None => { info!("stopping to listen for handler message"); break; } } } } }
if let Ok(opt) = self.closer.try_recv() { if let Some(_) = opt { info!("stopping transport sender"); break; } }
if_condition
[ { "content": "fn do_main() -> Result<(), Error> {\n\n let nilai_builder = builder::NilaiBuilder::new(\"127.0.0.1:5001\".parse()?);\n\n let closer = nilai_builder\n\n .alive_delegate(Box::new(|_: types::Node| println!(\"new node joined\")))\n\n .execute()?;\n\n // nilai is running so block...
Rust
wasm/src/message/unpack.rs
spivachuk/didcomm-rust
9a24b3b60f07a11822666dda46e5616a138af056
use std::rc::Rc; use didcomm::{ error::{ErrorKind, ResultExt}, UnpackOptions, }; use js_sys::{Array, Promise}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; use crate::{ error::JsResult, utils::set_panic_hook, DIDResolver, JsDIDResolver, JsSecretsResolver, Message, SecretsResolver, }; #[wasm_bindgen(skip_typescript)] impl Message { #[wasm_bindgen(skip_typescript)] pub fn unpack( msg: String, did_resolver: DIDResolver, secrets_resolver: SecretsResolver, options: JsValue, ) -> Promise { set_panic_hook(); let did_resolver = JsDIDResolver(did_resolver); let secrets_resolver = JsSecretsResolver(secrets_resolver); future_to_promise(async move { let options: UnpackOptions = options .into_serde() .kind(ErrorKind::Malformed, "Options param is malformed") .as_js()?; let (msg, metadata) = didcomm::Message::unpack(&msg, &did_resolver, &secrets_resolver, &options) .await .as_js()?; let metadata = JsValue::from_serde(&metadata) .kind(ErrorKind::InvalidState, "Unable serialize UnpackMetadata") .as_js()?; let res = { let res = Array::new_with_length(2); res.set(0, Message(Rc::new(msg)).into()); res.set(1, metadata); res }; Ok(res.into()) }) } } #[wasm_bindgen(typescript_custom_section)] const MESSAGE_UNPACK_TS: &'static str = r#" export namespace Message { /** * Unpacks the packed message by doing decryption and verifying the signatures. * This method supports all DID Comm message types (encrypted, signed, plaintext). * * If unpack options expect a particular property (for example that a message is encrypted) * and the packed message doesn't meet the criteria (it's not encrypted), then a MessageUntrusted * error will be returned. * * @param `packed_msg` the message as JSON string to be unpacked * @param `did_resolver` instance of `DIDResolver` to resolve DIDs * @param `secrets_resolver` instance of SecretsResolver` to resolve sender DID keys secrets * @param `options` allow fine configuration of unpacking process and imposing additional restrictions * to message to be trusted. * * @returns Tuple `[message, metadata]`. * - `message` plain message instance * - `metadata` additional metadata about this `unpack` execution like used keys identifiers, * trust context, algorithms and etc. * * @throws DIDCommDIDNotResolved * @throws DIDCommDIDUrlNotFound * @throws DIDCommMalformed * @throws DIDCommIoError * @throws DIDCommInvalidState * @throws DIDCommNoCompatibleCrypto * @throws DIDCommUnsupported * @throws DIDCommIllegalArgument */ function unpack( msg: string, did_resolver: DIDResolver, secrets_resolver: SecretsResolver, options: UnpackOptions, ): Promise<[Message, UnpackMetadata]>; } "#; #[wasm_bindgen(typescript_custom_section)] const PACK_UNPACK_OPTIONS_TS: &'static str = r#" /** * Allows fine customization of unpacking process */ type UnpackOptions = { /** * Whether the plaintext must be decryptable by all keys resolved by the secrets resolver. * False by default. */ expect_decrypt_by_all_keys?: boolean, /** * If `true` and the packed message is a `Forward` * wrapping a plaintext packed for the given recipient, then both Forward and packed plaintext are unpacked automatically, * and the unpacked plaintext will be returned instead of unpacked Forward. * False by default. */ unwrap_re_wrapping_forward?: boolean, } "#; #[wasm_bindgen(typescript_custom_section)] const UNPACK_METADATA_TS: &'static str = r#" /** * Additional metadata about this `unpack` method execution like trust predicates * and used keys identifiers. */ type UnpackMetadata = { /** * Whether the plaintext has been encrypted. */ encrypted: boolean, /** * Whether the plaintext has been authenticated. */ authenticated: boolean, /** * Whether the plaintext has been signed. */ non_repudiation: boolean, /** * Whether the sender ID was hidden or protected. */ anonymous_sender: boolean, /** * Whether the plaintext was re-wrapped in a forward message by a mediator. */ re_wrapped_in_forward: boolean, /** * Key ID of the sender used for authentication encryption * if the plaintext has been authenticated and encrypted. */ encrypted_from_kid?: string, /** * Target key IDS for encryption if the plaintext has been encrypted. */ encrypted_to_kids?: Array<string>, /** * Key ID used for signature if the plaintext has been signed. */ sign_from: string, /** * Key ID used for from_prior header signature if from_prior header is present */ from_prior_issuer_kid?: string, /** * Algorithm used for authenticated encryption. * Default "A256cbcHs512Ecdh1puA256kw" */ enc_alg_auth?: "A256cbcHs512Ecdh1puA256kw", /** * Algorithm used for anonymous encryption. * Default "Xc20pEcdhEsA256kw" */ enc_alg_anon?: "A256cbcHs512EcdhEsA256kw" | "Xc20pEcdhEsA256kw" | "A256gcmEcdhEsA256kw", /** * Algorithm used for message signing. */ sign_alg?: "EdDSA" | "ES256" | "ES256K", /** * If the plaintext has been signed, the JWS is returned for non-repudiation purposes. */ signed_message?: string, /** * If plaintext contains from_prior header, its unpacked value is returned */ from_prior?: IFromPrior, } "#;
use std::rc::Rc; use didcomm::{ error::{ErrorKind, ResultExt}, UnpackOptions, }; use js_sys::{Array, Promise}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; use crate::{ error::JsResult, utils::set_panic_hook, DIDResolver, JsDIDResolver, JsSecretsResolver, Message, SecretsResolver, }; #[wasm_bindgen(skip_typescript)] impl Message { #[wasm_bindgen(skip_typescript)] pub fn unpack( msg: String, did_resolver: DIDResolver, secrets_resolver: SecretsResolver, options: JsValue, ) -> Promise { set_panic_hook(); let did_resolver = JsDIDResolver(did_resolver); let secrets_resolver = JsSecretsResolver(secrets_resolver); future_to_promise(async move { let options: UnpackOptions = options .into_serde() .kind(ErrorKind::Malformed, "Options param is malformed") .as_js()?; let (msg, metadata) = didcomm::Messag
} #[wasm_bindgen(typescript_custom_section)] const MESSAGE_UNPACK_TS: &'static str = r#" export namespace Message { /** * Unpacks the packed message by doing decryption and verifying the signatures. * This method supports all DID Comm message types (encrypted, signed, plaintext). * * If unpack options expect a particular property (for example that a message is encrypted) * and the packed message doesn't meet the criteria (it's not encrypted), then a MessageUntrusted * error will be returned. * * @param `packed_msg` the message as JSON string to be unpacked * @param `did_resolver` instance of `DIDResolver` to resolve DIDs * @param `secrets_resolver` instance of SecretsResolver` to resolve sender DID keys secrets * @param `options` allow fine configuration of unpacking process and imposing additional restrictions * to message to be trusted. * * @returns Tuple `[message, metadata]`. * - `message` plain message instance * - `metadata` additional metadata about this `unpack` execution like used keys identifiers, * trust context, algorithms and etc. * * @throws DIDCommDIDNotResolved * @throws DIDCommDIDUrlNotFound * @throws DIDCommMalformed * @throws DIDCommIoError * @throws DIDCommInvalidState * @throws DIDCommNoCompatibleCrypto * @throws DIDCommUnsupported * @throws DIDCommIllegalArgument */ function unpack( msg: string, did_resolver: DIDResolver, secrets_resolver: SecretsResolver, options: UnpackOptions, ): Promise<[Message, UnpackMetadata]>; } "#; #[wasm_bindgen(typescript_custom_section)] const PACK_UNPACK_OPTIONS_TS: &'static str = r#" /** * Allows fine customization of unpacking process */ type UnpackOptions = { /** * Whether the plaintext must be decryptable by all keys resolved by the secrets resolver. * False by default. */ expect_decrypt_by_all_keys?: boolean, /** * If `true` and the packed message is a `Forward` * wrapping a plaintext packed for the given recipient, then both Forward and packed plaintext are unpacked automatically, * and the unpacked plaintext will be returned instead of unpacked Forward. * False by default. */ unwrap_re_wrapping_forward?: boolean, } "#; #[wasm_bindgen(typescript_custom_section)] const UNPACK_METADATA_TS: &'static str = r#" /** * Additional metadata about this `unpack` method execution like trust predicates * and used keys identifiers. */ type UnpackMetadata = { /** * Whether the plaintext has been encrypted. */ encrypted: boolean, /** * Whether the plaintext has been authenticated. */ authenticated: boolean, /** * Whether the plaintext has been signed. */ non_repudiation: boolean, /** * Whether the sender ID was hidden or protected. */ anonymous_sender: boolean, /** * Whether the plaintext was re-wrapped in a forward message by a mediator. */ re_wrapped_in_forward: boolean, /** * Key ID of the sender used for authentication encryption * if the plaintext has been authenticated and encrypted. */ encrypted_from_kid?: string, /** * Target key IDS for encryption if the plaintext has been encrypted. */ encrypted_to_kids?: Array<string>, /** * Key ID used for signature if the plaintext has been signed. */ sign_from: string, /** * Key ID used for from_prior header signature if from_prior header is present */ from_prior_issuer_kid?: string, /** * Algorithm used for authenticated encryption. * Default "A256cbcHs512Ecdh1puA256kw" */ enc_alg_auth?: "A256cbcHs512Ecdh1puA256kw", /** * Algorithm used for anonymous encryption. * Default "Xc20pEcdhEsA256kw" */ enc_alg_anon?: "A256cbcHs512EcdhEsA256kw" | "Xc20pEcdhEsA256kw" | "A256gcmEcdhEsA256kw", /** * Algorithm used for message signing. */ sign_alg?: "EdDSA" | "ES256" | "ES256K", /** * If the plaintext has been signed, the JWS is returned for non-repudiation purposes. */ signed_message?: string, /** * If plaintext contains from_prior header, its unpacked value is returned */ from_prior?: IFromPrior, } "#;
e::unpack(&msg, &did_resolver, &secrets_resolver, &options) .await .as_js()?; let metadata = JsValue::from_serde(&metadata) .kind(ErrorKind::InvalidState, "Unable serialize UnpackMetadata") .as_js()?; let res = { let res = Array::new_with_length(2); res.set(0, Message(Rc::new(msg)).into()); res.set(1, metadata); res }; Ok(res.into()) }) }
function_block-function_prefixed
[ { "content": "/// Tries to parse plaintext message into `ParsedForward` structure if the message is Forward.\n\n/// (https://identity.foundation/didcomm-messaging/spec/#messages)\n\n///\n\n/// # Parameters\n\n/// - `msg` plaintext message to try to parse into `ParsedForward` structure\n\n///\n\n/// # Returns\n\...
Rust
src/geometry/aabb.rs
josefrcm/rspt
ad534adf75635338134e4ec71491f55f3065fb6a
use std::f32; use super::*; #[derive(Clone, Copy, Debug)] pub struct AABB { pub lower: nalgebra::Point3<f32>, pub upper: nalgebra::Point3<f32>, } impl AABB { pub fn empty() -> Self { AABB { lower: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), upper: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), } } pub fn from_vertices(vertices: &[Vertex]) -> Self { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for v in vertices { lower.x = f32::min(lower.x, v.coords.x); lower.y = f32::min(lower.y, v.coords.y); lower.z = f32::min(lower.z, v.coords.z); upper.x = f32::max(upper.x, v.coords.x); upper.y = f32::max(upper.y, v.coords.y); upper.z = f32::max(upper.z, v.coords.z); } AABB { lower: lower, upper: upper, } } pub fn from_faces(vertices: &[Vertex], faces: &[Triangle]) -> Self { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for f in faces { let v1 = vertices[f.v1 as usize].coords; let v2 = vertices[f.v2 as usize].coords; let v3 = vertices[f.v3 as usize].coords; lower.x = f32::min(lower.x, v1.x); lower.x = f32::min(lower.x, v2.x); lower.x = f32::min(lower.x, v3.x); lower.y = f32::min(lower.y, v1.y); lower.y = f32::min(lower.y, v2.y); lower.y = f32::min(lower.y, v3.y); lower.z = f32::min(lower.z, v1.z); lower.z = f32::min(lower.z, v2.z); lower.z = f32::min(lower.z, v3.z); upper.x = f32::max(upper.x, v1.x); upper.x = f32::max(upper.x, v2.x); upper.x = f32::max(upper.x, v3.x); upper.y = f32::max(upper.y, v1.y); upper.y = f32::max(upper.y, v2.y); upper.y = f32::max(upper.y, v3.y); upper.z = f32::max(upper.z, v1.z); upper.z = f32::max(upper.z, v2.z); upper.z = f32::max(upper.z, v3.z); } AABB { lower: lower, upper: upper, } } pub fn intersect(&self, ray: Ray) -> Interval { let x1 = (self.lower.x - ray.origin.x) / ray.direction.x; let x2 = (self.upper.x - ray.origin.x) / ray.direction.x; let x_int = Interval::new(x1, x2); let y1 = (self.lower.y - ray.origin.y) / ray.direction.y; let y2 = (self.upper.y - ray.origin.y) / ray.direction.y; let y_int = Interval::new(y1, y2); let z1 = (self.lower.z - ray.origin.z) / ray.direction.z; let z2 = (self.upper.z - ray.origin.z) / ray.direction.z; let z_int = Interval::new(z1, z2); let foo = f32::max(x_int.start, f32::max(y_int.start, z_int.start)); let bar = f32::min(x_int.finish, f32::min(y_int.finish, z_int.finish)); if bar >= foo { Interval::new(foo, bar) } else { Interval::new(f32::INFINITY, f32::INFINITY) } } } pub fn union(boxes: &[AABB]) -> AABB { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for b in boxes { lower.x = f32::min(lower.x, b.lower.x); lower.y = f32::min(lower.y, b.lower.y); lower.z = f32::min(lower.z, b.lower.z); upper.x = f32::max(upper.x, b.upper.x); upper.y = f32::max(upper.y, b.upper.y); upper.z = f32::max(upper.z, b.upper.z); } AABB { lower: lower, upper: upper, } }
use std::f32; use super::*; #[derive(Clone, Copy, Debug)] pub struct AABB { pub lower: nalgebra::Point3<f32>, pub upper: nalgebra::Point3<f32>, } impl AABB { pub fn empty() -> Self { AABB { lower: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), upper: nalgebra::Point3::new(f32::NAN, f32::NAN, f32::NAN), } } pub fn from_vertices(vertices: &[Vertex]) -> Self { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for v in vertices { lower.x = f32::min(lower.x, v.coords.x); lower.y = f32::min(lower.y, v.coords.y); lower.z = f32::min(lower.z, v.coords.z); upper.x = f32::max(upper.x, v.coords.x); upper.y = f32::max(upper.y, v.coords.y); upper.z = f32::max(upper.z, v.coords.z); } AABB { lower: lower, upper: upper, } } pub fn from_faces(vertices: &[Vertex], faces: &[Triangle]) -> Self { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for f in faces { let v1 = vertices[f.v1 as usize].coords; let v2 = vertices[f.v2 as usize].coords; let v3 = vertices[f.v3 as usize].coords; lower.x = f32::min(lower.x, v1.x); lower.x = f32::min(lower.x, v2.x); lower.x = f32::min(lower.x, v3.x); lower.y = f32::min(lower.y, v1.y); lower.y = f32::min(lower.y, v2.y); lower.y = f32::min(lower.y, v3.y); lower.z = f32::min(lower.z, v1.z); lower.z = f32::min(lower.z, v2.z); lower.z = f32::min(lower.z, v3.z); upper.x = f32::max(upper.x, v1.x); upper.x = f32::max(upper.x, v2.x); upper.x = f32::max(upper.x, v3.x); upper.y = f32::max(upper.y, v1.y); upper.y = f32::max(upper.y, v2.y); upper.y = f32::max(upper.y, v3.y); upper.z = f32::max(upper.z, v1.z); upper.z = f32::max(upper.z, v2.z); upper.z = f32::max(upper.z, v3.z); } AABB { lower: lower, upper: upper, } } pub fn intersect(&self, ray: Ray) -> Interval { let x1 = (self.lower.x - ray.origin.x) / ray.direction.x; let x2 = (self.upper.x - ray.origin.x) / ray.direction.x; let x_int = Interval::new(x1, x2); let y1 = (self.lower.y - ray.origin.y) / ray.direction.y; let y2 = (self.upper.y - ray.origin.y) / ray.direction.y; let y_int = Interval::new(y1, y2); let z1 = (self.lower.z - ray.origin.z) / ray.direction.z; let z2 = (self.upper.z - ray.origin.z) / ray.direction.z; let z_int = Interval::new(z1, z2); let foo = f32::max(x_int.sta
} else { Interval::new(f32::INFINITY, f32::INFINITY) } } } pub fn union(boxes: &[AABB]) -> AABB { let mut lower = nalgebra::Point3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY); let mut upper = nalgebra::Point3::new(f32::NEG_INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY); for b in boxes { lower.x = f32::min(lower.x, b.lower.x); lower.y = f32::min(lower.y, b.lower.y); lower.z = f32::min(lower.z, b.lower.z); upper.x = f32::max(upper.x, b.upper.x); upper.y = f32::max(upper.y, b.upper.y); upper.z = f32::max(upper.z, b.upper.z); } AABB { lower: lower, upper: upper, } }
rt, f32::max(y_int.start, z_int.start)); let bar = f32::min(x_int.finish, f32::min(y_int.finish, z_int.finish)); if bar >= foo { Interval::new(foo, bar)
function_block-random_span
[ { "content": "pub fn scale(image: &mut Image2D, factor: usize) -> () {\n\n let s = 1.0 / (factor as f32);\n\n image.map_inplace(|a| *a = *a * s);\n\n}\n\n\n", "file_path": "src/tracer/image2d.rs", "rank": 1, "score": 82483.86372930113 }, { "content": "pub fn accum(lhs: &mut Image2D, rh...
Rust
src/enemy.rs
mdenchev/BevyJam1
6be0aafad7a6fce6e4cf51a2dfb9c0c01b5616aa
use bevy::prelude::*; use heron::{prelude::*, rapier_plugin::PhysicsWorld}; use crate::{levels::map::MapInitData, player::PlayerStats, utils::CommonHandles, GameState}; pub struct EnemyPlugin; impl Plugin for EnemyPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_update(crate::GameState::Playing) .with_system(enemy_follow_player) .with_system(despawn_enemy_on_collision), ); } } #[derive(Component)] pub struct EnemyStats { pub damage: f32, pub speed: f32, } pub fn enemy_follow_player( players: Query<(&Transform, &PlayerStats)>, mut enemies: Query<(&mut Velocity, &Transform, &EnemyStats)>, ) { for (mut vel, enemy_trans, enemy_stats) in enemies.iter_mut() { if let Some((closest_player_trans, _)) = players.iter().min_by_key(|(player_trans, _)| { let dist = enemy_trans .translation .distance_squared(player_trans.translation) * 1000.0; dist as i32 }) { let direction = (enemy_trans.translation - closest_player_trans.translation).normalize(); vel.linear = direction * enemy_stats.speed * -1.0; } } } pub fn spawn_enemy(commands: &mut Commands, common_handles: &CommonHandles, position: Vec2) { commands .spawn() .insert_bundle(SpriteSheetBundle { sprite: TextureAtlasSprite::new(40), texture_atlas: common_handles.player_sprites.clone(), transform: Transform::from_translation(position.extend(1.0)), ..Default::default() }) .insert(EnemyStats { damage: 50.0, speed: 30.0, }) .insert(RigidBody::Dynamic) .insert(RotationConstraints::lock()) .insert(CollisionShape::Sphere { radius: 10.0 }) .insert( CollisionLayers::none() .with_group(crate::GameLayers::Enemies) .with_masks(&[ crate::GameLayers::World, crate::GameLayers::Player, crate::GameLayers::Bullets, crate::GameLayers::Enemies, ]), ) .insert(Velocity::default()); } fn despawn_enemy_on_collision( mut commands: Commands, time: Res<Time>, mut map_init_data: ResMut<MapInitData>, mut game_state: ResMut<State<GameState>>, mut events: EventReader<CollisionEvent>, ) { map_init_data.timer += time.delta(); events.iter().filter(|e| e.is_started()).for_each(|ev| { let (e1, e2) = ev.rigid_body_entities(); let (l1, l2) = ev.collision_layers(); use crate::GameLayers::*; if l1.contains_group(Enemies) && l2.contains_group(Bullets) { commands.entity(e1).despawn(); commands.entity(e2).despawn(); map_init_data.kills += 1; } else if l1.contains_group(Bullets) && l2.contains_group(Enemies) { commands.entity(e1).despawn(); commands.entity(e2).despawn(); map_init_data.kills += 1; } if map_init_data.kills == 50 { let _ = game_state.overwrite_set(GameState::GameWon); } }); } fn _check_enemy_visibility( players: Query<&Transform, With<PlayerStats>>, mut enemies: Query<(Entity, &mut Visibility, &Transform, &EnemyStats)>, physics_world: PhysicsWorld, ) { for player_trans in players.iter() { let player_pos = player_trans.translation; for (_ent, mut visibility, enemy_trans, _) in enemies.iter_mut() { let enemy_pos = enemy_trans.translation; if enemy_pos.distance(player_pos) > 1000.0f32 { visibility.is_visible = false; continue; } use crate::GameLayers::*; let distance_to_wall = physics_world .ray_cast_with_filter( player_pos, enemy_pos - player_pos, false, CollisionLayers::none() .with_group(Player) .with_masks(&[World]), |_| true, ) .map(|r| r.collision_point.distance(player_pos)) .unwrap_or(f32::MAX); visibility.is_visible = distance_to_wall > enemy_pos.distance(player_pos); } } }
use bevy::prelude::*; use heron::{prelude::*, rapier_plugin::PhysicsWorld}; use crate::{levels::map::MapInitData, player::PlayerStats, utils::CommonHandles, GameState}; pub struct EnemyPlugin; impl Plugin for EnemyPlugin { fn build(&self, app: &mut App) { app.add_system_set( SystemSet::on_update(crate::GameState::Playing) .with_system(enemy_follow_player) .with_system(despawn_enemy_on_collision), ); } } #[derive(Component)] pub struct EnemyStats { pub damage: f32, pub speed: f32, } pub fn enemy_follow_player( players: Query<(&Transform, &PlayerStats)>, mut enemies: Query<(&mut Velocity, &Transform, &EnemyStats)>, ) { for (mut vel, enemy_trans, enemy_stats) in enemies.iter_mut() { if let Some((closest_player_trans, _)) = players.iter().min_by_key(|(player_trans, _)| { let dist = enemy_trans .translation .distance_squared(player_trans.translation) * 1000.0; dist as i32 }) { let direction = (enemy_trans.translation - closest_player_trans.translation).normalize(); vel.linear = direction * enemy_stats.speed * -1.0; } } }
fn despawn_enemy_on_collision( mut commands: Commands, time: Res<Time>, mut map_init_data: ResMut<MapInitData>, mut game_state: ResMut<State<GameState>>, mut events: EventReader<CollisionEvent>, ) { map_init_data.timer += time.delta(); events.iter().filter(|e| e.is_started()).for_each(|ev| { let (e1, e2) = ev.rigid_body_entities(); let (l1, l2) = ev.collision_layers(); use crate::GameLayers::*; if l1.contains_group(Enemies) && l2.contains_group(Bullets) { commands.entity(e1).despawn(); commands.entity(e2).despawn(); map_init_data.kills += 1; } else if l1.contains_group(Bullets) && l2.contains_group(Enemies) { commands.entity(e1).despawn(); commands.entity(e2).despawn(); map_init_data.kills += 1; } if map_init_data.kills == 50 { let _ = game_state.overwrite_set(GameState::GameWon); } }); } fn _check_enemy_visibility( players: Query<&Transform, With<PlayerStats>>, mut enemies: Query<(Entity, &mut Visibility, &Transform, &EnemyStats)>, physics_world: PhysicsWorld, ) { for player_trans in players.iter() { let player_pos = player_trans.translation; for (_ent, mut visibility, enemy_trans, _) in enemies.iter_mut() { let enemy_pos = enemy_trans.translation; if enemy_pos.distance(player_pos) > 1000.0f32 { visibility.is_visible = false; continue; } use crate::GameLayers::*; let distance_to_wall = physics_world .ray_cast_with_filter( player_pos, enemy_pos - player_pos, false, CollisionLayers::none() .with_group(Player) .with_masks(&[World]), |_| true, ) .map(|r| r.collision_point.distance(player_pos)) .unwrap_or(f32::MAX); visibility.is_visible = distance_to_wall > enemy_pos.distance(player_pos); } } }
pub fn spawn_enemy(commands: &mut Commands, common_handles: &CommonHandles, position: Vec2) { commands .spawn() .insert_bundle(SpriteSheetBundle { sprite: TextureAtlasSprite::new(40), texture_atlas: common_handles.player_sprites.clone(), transform: Transform::from_translation(position.extend(1.0)), ..Default::default() }) .insert(EnemyStats { damage: 50.0, speed: 30.0, }) .insert(RigidBody::Dynamic) .insert(RotationConstraints::lock()) .insert(CollisionShape::Sphere { radius: 10.0 }) .insert( CollisionLayers::none() .with_group(crate::GameLayers::Enemies) .with_masks(&[ crate::GameLayers::World, crate::GameLayers::Player, crate::GameLayers::Bullets, crate::GameLayers::Enemies, ]), ) .insert(Velocity::default()); }
function_block-full_function
[ { "content": "// Going to want this to find the spawn point eventually.\n\npub fn spawn_player(\n\n commands: &mut Commands,\n\n common_handles: &CommonHandles,\n\n pos: (f32, f32),\n\n asset_server: &AssetServer,\n\n is_clone: bool,\n\n clone_id: usize,\n\n) {\n\n if is_clone {\n\n ...
Rust
src/bin/rl/reward.rs
buggedbit/wall-e
e96ec233616661d763a454554c0961a1f9b45912
use ndarray::prelude::*; use serde::{Deserialize, Serialize}; use wall_e::ceo::Reward; use wall_e::diff_drive_model::DiffDriveModel; use wall_e::fcn::*; use wall_e::goal::Goal; #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DiffDriveReward { start_x_bounds: (f32, f32), start_y_bounds: (f32, f32), start_or_bounds: (f32, f32), radius: f32, goal_x_bounds: (f32, f32), goal_y_bounds: (f32, f32), num_episode_ticks: usize, } impl DiffDriveReward { pub fn new( start_x_bounds: (f32, f32), start_y_bounds: (f32, f32), start_or_bounds: (f32, f32), radius: f32, goal_x_bounds: (f32, f32), goal_y_bounds: (f32, f32), num_episode_ticks: usize, ) -> DiffDriveReward { DiffDriveReward { start_x_bounds: start_x_bounds, start_y_bounds: start_y_bounds, start_or_bounds: start_or_bounds, radius: radius, goal_x_bounds: goal_x_bounds, goal_y_bounds: goal_y_bounds, num_episode_ticks: num_episode_ticks, } } pub fn start_x_bounds(&self) -> (f32, f32) { self.start_x_bounds } pub fn start_y_bounds(&self) -> (f32, f32) { self.start_y_bounds } pub fn start_or_bounds(&self) -> (f32, f32) { self.start_or_bounds } pub fn radius(&self) -> f32 { self.radius } pub fn goal_x_bounds(&self) -> (f32, f32) { self.goal_x_bounds } pub fn goal_y_bounds(&self) -> (f32, f32) { self.goal_y_bounds } } impl Reward for DiffDriveReward { fn reward(&self, fcn: &FCN, params: &Array1<f32>, num_episodes: usize) -> f32 { let mut cumulative_reward = 0.0; for _ in 0..num_episodes { let goal_coordinates = Goal::in_region(self.goal_x_bounds, self.goal_y_bounds).coordinates(); let mut model = DiffDriveModel::spawn_randomly( self.start_x_bounds, self.start_y_bounds, self.start_or_bounds, self.radius, goal_coordinates, ); let mut episode_reward = 0.0; for tick in 0..self.num_episode_ticks { let (x, y, or_in_rad) = model.scaled_state(); let control = fcn.at_with(&arr1(&[x, y, or_in_rad]), params); let (v, w) = (control[[0]], control[[1]]); model.set_control(v, w); model.update(0.1).unwrap(); let (x, y, or_in_rad) = model.scaled_state(); let (x_hat, y_hat) = { let norm = (x * x + y * y).sqrt(); (x / norm, y / norm) }; let angular_deviation = ((x_hat - or_in_rad.cos()).powf(2.0) + (y_hat - or_in_rad.sin()).powf(2.0)) .sqrt() * (1.0 / (1.0 + tick as f32)); episode_reward -= angular_deviation; episode_reward -= w.abs(); let dist = (x * x + y * y).sqrt(); episode_reward -= dist * 30.0; } let (x, y, _or_in_rad) = model.scaled_state(); let final_dist = (x * x + y * y).sqrt(); episode_reward += 200.0 * (-final_dist).exp(); let (v, w) = model.control(); episode_reward += 200.0 * (-v.abs()).exp() * (-final_dist).exp(); episode_reward += 200.0 * (-w.abs()).exp() * (-final_dist).exp(); cumulative_reward += episode_reward; } let average_reward = cumulative_reward / num_episodes as f32; average_reward } }
use ndarray::prelude::*; use serde::{Deserialize, Serialize}; use wall_e::ceo::Reward; use wall_e::diff_drive_model::DiffDriveModel; use wall_e::fcn::*; use wall_e::goal::Goal; #[derive(Debug, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct DiffDriveReward { start_x_bounds: (f32, f32), start_y_bounds: (f32, f32), start_or_bounds: (f32, f32), radius: f32, goal_x_bounds: (f32, f32), goal_y_bounds: (f32, f32), num_episode_ticks: usize, } impl DiffDriveReward { pub fn new( start_x_bounds: (f32, f32), start_y_bounds: (f32, f32), start_or_bounds: (f32, f32), radius: f32, goal_x_bounds: (f32, f32), goal_y_bounds: (f32, f32), num_episode_ticks: usize, ) -> DiffDriveReward { DiffDriveReward { start_x_bounds: start_x_bounds, start_y_bounds: start_y_bounds, start_or_bounds: start_or_bounds, radius: radius, goal_x_bounds: goal_x_bounds, goal_y_bounds: goal_y_bounds, num_episode_ticks: num_episode_ticks, } } pub fn start_x_bounds(&self) -> (f32, f32) { self.start_x_bounds } pub fn start_y_bounds(&self) -> (f32, f32) { self.start_y_bounds } pub fn start_or_bounds(&self) -> (f32, f32) { self.start_or_bounds } pub fn radius(&self) -> f32 { self.radius } pub fn goal_x_bounds(&self) -> (f32, f32) { self.goal_x_bounds } pub fn goal_y_bounds(&self) -> (f32, f32) { self.goal_y_bounds } } impl Reward for DiffDriveReward { fn reward(&self, fcn: &FCN, params: &Array1<f32>, num_episodes: usize) -> f32 { let mut cumulative_reward = 0.0; for _ in 0..num_episodes { let goal_coordinates = Goal::in_region(self.goal_x_bounds, self.goal_y_bounds).coordinates(); let mut model = DiffDriveModel::spawn_randomly( self.start_x_bounds, self.start_y_bounds, self.start_or_bounds, self.radius, goal_coordinates, ); let mut episode_reward = 0.0; for tick in 0..self.num_episode_ticks { let (x, y, or_in_rad) = model.scaled_state(); let control = fcn.at_with(&arr1(&[x, y, or_in_rad]), params); let (v, w) = (control[[0]], control[[1]]); model.set_control(v, w); model.update(0.1).unwrap(); let (x, y, or_in_rad) = model.scaled_state(); let (x_hat, y_hat) = { let norm = (x * x + y * y).sqrt(); (x / norm, y / norm) };
episode_reward -= angular_deviation; episode_reward -= w.abs(); let dist = (x * x + y * y).sqrt(); episode_reward -= dist * 30.0; } let (x, y, _or_in_rad) = model.scaled_state(); let final_dist = (x * x + y * y).sqrt(); episode_reward += 200.0 * (-final_dist).exp(); let (v, w) = model.control(); episode_reward += 200.0 * (-v.abs()).exp() * (-final_dist).exp(); episode_reward += 200.0 * (-w.abs()).exp() * (-final_dist).exp(); cumulative_reward += episode_reward; } let average_reward = cumulative_reward / num_episodes as f32; average_reward } }
let angular_deviation = ((x_hat - or_in_rad.cos()).powf(2.0) + (y_hat - or_in_rad.sin()).powf(2.0)) .sqrt() * (1.0 / (1.0 + tick as f32));
assignment_statement
[ { "content": "fn clamp(v: f32, min_max: (f32, f32)) -> f32 {\n\n let (min, max) = min_max;\n\n if v < min {\n\n return min;\n\n }\n\n if v > max {\n\n return max;\n\n }\n\n v\n\n}\n\n\n\npub struct DiffDriveModel {\n\n x: f32,\n\n y: f32,\n\n or_in_rad: f32,\n\n radiu...
Rust
src/iter/cmp.rs
Bergmann89/aspar
e3d7c56297232aa66e720cc0766b1c25bc11420d
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use crate::{Driver, Executor, IndexedParallelIterator, ParallelIterator, WithIndexedProducer}; /* Cmp */ pub struct Cmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> Cmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { Self { iterator_a, iterator_b, } } } impl<'a, XA, XB, I> Driver<'a, Ordering, Option<Ordering>> for Cmp<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: Ord + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, Ordering, Option<Ordering>>, { let Self { iterator_a, iterator_b, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); let ord_len = len_a.cmp(&len_b); let executor = executor.into_inner(); let inner = iterator_a .zip(iterator_b) .map(|(a, b)| Ord::cmp(&a, &b)) .find_first(|ord| ord != &Ordering::Equal) .exec_with(executor); E::map(inner, move |inner| inner.unwrap_or(ord_len)) } } /* PartialCmp */ pub struct PartialCmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> PartialCmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { Self { iterator_a, iterator_b, } } } impl<'a, XA, XB, I> Driver<'a, Option<Ordering>, Option<Option<Ordering>>> for PartialCmp<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialOrd + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, Option<Ordering>, Option<Option<Ordering>>>, { let Self { iterator_a, iterator_b, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); let ord_len = len_a.cmp(&len_b); let executor = executor.into_inner(); let inner = iterator_a .zip(iterator_b) .map(|(a, b)| PartialOrd::partial_cmp(&a, &b)) .find_first(|ord| ord != &Some(Ordering::Equal)) .exec_with(executor); E::map(inner, move |inner| inner.unwrap_or(Some(ord_len))) } } /* Equal */ pub struct Equal<XA, XB> { iterator_a: XA, iterator_b: XB, expected: bool, } impl<XA, XB> Equal<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB, expected: bool) -> Self { Self { iterator_a, iterator_b, expected, } } } impl<'a, XA, XB, I> Driver<'a, bool, Option<bool>> for Equal<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialEq + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, bool, Option<bool>>, { let Self { iterator_a, iterator_b, expected, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); if (len_a == len_b) ^ expected { return executor.ready(false); } iterator_a .zip(iterator_b) .all(move |(x, y)| PartialEq::eq(&x, &y) == expected) .exec_with(executor) } } /* Compare */ pub struct Compare<XA, XB> { iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>, } impl<XA, XB> Compare<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>) -> Self { Self { iterator_a, iterator_b, ord, ord_opt, } } } impl<'a, XA, XB, I> Driver<'a, bool, Option<Ordering>, Option<Option<Ordering>>> for Compare<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialOrd + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, bool, Option<Ordering>, Option<Option<Ordering>>>, { let Self { iterator_a, iterator_b, ord, ord_opt, } = self; let executor = executor.into_inner(); let inner = PartialCmp::new(iterator_a, iterator_b).exec_with(executor); E::map(inner, move |inner| inner == Some(ord) || inner == ord_opt) } }
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use crate::{Driver, Executor, IndexedParallelIterator, ParallelIterator, WithIndexedProducer}; /* Cmp */ pub struct Cmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> Cmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { Self { iterator_a, iterator_b, } } } impl<'a, XA, XB, I> Driver<'a, Ordering, Option<Ordering>> for Cmp<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: Ord + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, Ordering, Option<Ordering>>, { let Self { iterator_a, iterator_b, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); let ord_len = len_a.cmp(&len_b); let executor = executor.into_inner(); let inner = iterator_a .zip(iterator_b) .map(|(a, b)| Ord::cmp(&a, &b)) .find_first(|ord| ord != &Ordering::Equal) .exec_with(executor); E::map(inner, move |inner| inner.unwrap_or(ord_len)) } } /* PartialCmp */ pub struct PartialCmp<XA, XB> { iterator_a: XA, iterator_b: XB, } impl<XA, XB> PartialCmp<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB) -> Self { Self { iterator_a, iterator_b, } } } impl<'a, XA, XB, I> Driver<'a, Option<Ordering>, Option<Option<Ordering>>> for PartialCmp<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialOrd + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, Option<Ordering>, Option<Option<Ordering>>>, { let Self { iterator_a, iterator_b, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); let ord_len = len_a.cmp(&len_b); let executor = executor.into_inner(); let inner = iterator_a .zip(iterator_b) .map(|(a, b)| PartialOrd::partial_cmp(&a, &b)) .find_first(|ord| ord != &Some(Ordering::Equal)) .exec_with(executor); E::map(inner, move |inner| inner.unwrap_or(Some(ord_len))) } } /* Equal */ pub struct Equal<XA, XB> { iterator_a: XA, iterator_b: XB, expected: bool, } impl<XA, XB> Equal<XA, XB> { pub fn new(iterator_a: XA, iterator_b: XB, expected: bool) -> Self { Self { iterator_a, iterator_b, expected, } } } impl<'a, XA, XB, I> Driver<'a, bool, Option<bool>> for Equal<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialEq + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, bool, Option<bool>>, { let Self { iterator_a, iterator_b, expected, } = self; let len_a = iterator_a.len_hint(); let len_b = iterator_b.len_hint(); if (len_a == len_b) ^ expected { return executor.ready(false); } iterator_a .zip(iter
pub fn new(iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>) -> Self { Self { iterator_a, iterator_b, ord, ord_opt, } } } impl<'a, XA, XB, I> Driver<'a, bool, Option<Ordering>, Option<Option<Ordering>>> for Compare<XA, XB> where XA: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, XB: IndexedParallelIterator<'a, Item = I> + WithIndexedProducer<'a, Item = I>, I: PartialOrd + Send + 'a, { fn exec_with<E>(self, executor: E) -> E::Result where E: Executor<'a, bool, Option<Ordering>, Option<Option<Ordering>>>, { let Self { iterator_a, iterator_b, ord, ord_opt, } = self; let executor = executor.into_inner(); let inner = PartialCmp::new(iterator_a, iterator_b).exec_with(executor); E::map(inner, move |inner| inner == Some(ord) || inner == ord_opt) } }
ator_b) .all(move |(x, y)| PartialEq::eq(&x, &y) == expected) .exec_with(executor) } } /* Compare */ pub struct Compare<XA, XB> { iterator_a: XA, iterator_b: XB, ord: Ordering, ord_opt: Option<Ordering>, } impl<XA, XB> Compare<XA, XB> {
random
[]
Rust
src/fake_device.rs
szeged/blurmock
a538c2c5eaf19071d964b09819d9ca8fdebfb1a1
use core::ops::Deref; use fake_adapter::FakeBluetoothAdapter; use fake_service::FakeBluetoothGATTService; use hex; use std::collections::HashMap; use std::error::Error; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug)] pub struct FakeBluetoothDevice { id: Arc<Mutex<String>>, adapter: Arc<FakeBluetoothAdapter>, address: Arc<Mutex<String>>, appearance: Arc<Mutex<Option<u16>>>, class: Arc<Mutex<u32>>, gatt_services: Arc<Mutex<Vec<Arc<FakeBluetoothGATTService>>>>, is_paired: Arc<Mutex<bool>>, is_connectable: Arc<Mutex<bool>>, is_connected: Arc<Mutex<bool>>, is_trusted: Arc<Mutex<bool>>, is_blocked: Arc<Mutex<bool>>, is_legacy_pairing: Arc<Mutex<bool>>, uuids: Arc<Mutex<Vec<String>>>, name: Arc<Mutex<Option<String>>>, icon: Arc<Mutex<String>>, alias: Arc<Mutex<String>>, product_version: Arc<Mutex<u32>>, rssi: Arc<Mutex<Option<i16>>>, tx_power: Arc<Mutex<Option<i16>>>, modalias: Arc<Mutex<String>>, manufacturer_data: Arc<Mutex<Option<HashMap<u16, Vec<u8>>>>>, service_data: Arc<Mutex<Option<HashMap<String, Vec<u8>>>>>, } impl FakeBluetoothDevice { pub fn new(id: String, adapter: Arc<FakeBluetoothAdapter>, address: String, appearance: Option<u16>, class: u32, gatt_services: Vec<Arc<FakeBluetoothGATTService>>, is_paired: bool, is_connectable: bool, is_connected: bool, is_trusted: bool, is_blocked: bool, is_legacy_pairing: bool, uuids: Vec<String>, name: Option<String>, icon: String, alias: String, product_version: u32, rssi: Option<i16>, tx_power: Option<i16>, modalias: String, manufacturer_data: Option<HashMap<u16, Vec<u8>>>, service_data: Option<HashMap<String, Vec<u8>>>) -> Arc<FakeBluetoothDevice> { if let Ok(existing_device) = adapter.get_device(id.clone()) { return existing_device; } let device = Arc::new(FakeBluetoothDevice{ id: Arc::new(Mutex::new(id)), adapter: adapter.clone(), address: Arc::new(Mutex::new(address)), appearance: Arc::new(Mutex::new(appearance)), class: Arc::new(Mutex::new(class)), gatt_services: Arc::new(Mutex::new(gatt_services)), is_paired: Arc::new(Mutex::new(is_paired)), is_connectable: Arc::new(Mutex::new(is_connectable)), is_connected: Arc::new(Mutex::new(is_connected)), is_trusted: Arc::new(Mutex::new(is_trusted)), is_blocked: Arc::new(Mutex::new(is_blocked)), is_legacy_pairing: Arc::new(Mutex::new(is_legacy_pairing)), uuids: Arc::new(Mutex::new(uuids)), name: Arc::new(Mutex::new(name)), icon: Arc::new(Mutex::new(icon)), alias: Arc::new(Mutex::new(alias)), product_version: Arc::new(Mutex::new(product_version)), rssi: Arc::new(Mutex::new(rssi)), tx_power: Arc::new(Mutex::new(tx_power)), modalias: Arc::new(Mutex::new(modalias)), manufacturer_data: Arc::new(Mutex::new(manufacturer_data)), service_data: Arc::new(Mutex::new(service_data)), }); let _ = adapter.add_device(device.clone()); device } pub fn new_empty(adapter: Arc<FakeBluetoothAdapter>, device_id: String) -> Arc<FakeBluetoothDevice> { FakeBluetoothDevice::new( /*id*/ device_id, /*adapter*/ adapter, /*address*/ String::new(), /*appearance*/ None, /*class*/ 0, /*gatt_services*/ vec!(), /*is_paired*/ false, /*is_connectable*/ false, /*is_connected*/ false, /*is_trusted*/ false, /*is_blocked*/ false, /*is_legacy_pairing*/ false, /*uuids*/ vec!(), /*name*/ None, /*icon*/ String::new(), /*alias*/ String::new(), /*product_version*/ 0, /*rssi*/ None, /*tx_power*/ None, /*modalias*/ String::new(), /*manufacturer_data*/ None, /*service_data*/ None, ) } make_getter!(get_id, id); make_setter!(set_id, id); make_getter!(get_address, address, String); make_setter!(set_address, address, String); make_option_getter!(get_name, name, String); make_setter!(set_name, name, Option<String>); make_getter!(get_icon, icon, String); make_setter!(set_icon, icon, String); make_getter!(get_class, class, u32); make_setter!(set_class, class, u32); make_option_getter!(get_appearance, appearance, u16); make_setter!(set_appearance, appearance, Option<u16>); make_getter!(get_uuids, uuids, Vec<String>); make_setter!(set_uuids, uuids, Vec<String>); make_getter!(is_paired); make_setter!(set_paired, is_paired, bool); make_getter!(is_connectable); make_setter!(set_connectable, is_connectable, bool); make_getter!(is_connected); make_setter!(set_connected, is_connected, bool); make_getter!(is_trusted); make_setter!(set_trusted, is_trusted, bool); make_getter!(is_blocked); make_setter!(set_blocked, is_blocked, bool); make_getter!(get_alias, alias, String); make_setter!(set_alias, alias, String); make_getter!(is_legacy_pairing); make_setter!(set_legacy_pairing, is_legacy_pairing, bool); make_setter!(set_modalias, modalias, String); make_option_getter!(get_rssi, rssi, i16); make_setter!(set_rssi, rssi, Option<i16>); make_option_getter!(get_tx_power, tx_power, i16); make_setter!(set_tx_power, tx_power, Option<i16>); make_option_getter!(get_manufacturer_data, manufacturer_data, HashMap<u16, Vec<u8>>); make_setter!(set_manufacturer_data, manufacturer_data, Option<HashMap<u16, Vec<u8>>>); make_option_getter!(get_service_data, service_data, HashMap<String, Vec<u8>>); make_setter!(set_service_data, service_data, Option<HashMap<String, Vec<u8>>>); pub fn get_adapter(&self) -> Result<Arc<FakeBluetoothAdapter>, Box<Error>> { Ok(self.adapter.clone()) } pub fn pair(&self) -> Result<(), Box<Error>> { self.set_paired(true) } pub fn cancel_pairing(&self) -> Result<(), Box<Error>> { self.set_paired(false) } pub fn get_modalias(&self) -> Result<(String, u32, u32, u32), Box<Error>> { let cloned = self.modalias.clone(); let modalias = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; let ids: Vec<&str> = modalias.split(":").collect(); let source = String::from(ids[0]); let vendor = hex::decode(&ids[1][1..5]).unwrap(); let product = hex::decode(&ids[1][6..10]).unwrap(); let device = hex::decode(&ids[1][11..15]).unwrap(); Ok((source, (vendor[0] as u32) * 16 * 16 + (vendor[1] as u32), (product[0] as u32) * 16 * 16 + (product[1] as u32), (device[0] as u32) * 16 * 16 + (device[1] as u32))) } pub fn get_vendor_id_source(&self) -> Result<String, Box<Error>> { let (vendor_id_source,_,_,_) = try!(self.get_modalias()); Ok(vendor_id_source) } pub fn get_vendor_id(&self) -> Result<u32, Box<Error>> { let (_,vendor_id,_,_) = try!(self.get_modalias()); Ok(vendor_id) } pub fn get_product_id(&self) -> Result<u32, Box<Error>> { let (_,_,product_id,_) = try!(self.get_modalias()); Ok(product_id) } pub fn get_device_id(&self) -> Result<u32, Box<Error>> { let (_,_,_,device_id) = try!(self.get_modalias()); Ok(device_id) } pub fn get_gatt_services(&self) -> Result<Vec<String>, Box<Error>> { if !(try!(self.is_connected())) { return Err(Box::from("Device not connected.")); } let cloned = self.gatt_services.clone(); let gatt_services = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.into_iter().map(|s| s.get_id()).collect()) } pub fn get_gatt_service_structs(&self) -> Result<Vec<Arc<FakeBluetoothGATTService>>, Box<Error>> { if !(try!(self.is_connected())) { return Err(Box::from("Device not connected.")); } let cloned = self.gatt_services.clone(); let gatt_services = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services) } pub fn get_gatt_service(&self, id: String) -> Result<Arc<FakeBluetoothGATTService>, Box<Error>> { let services = try!(self.get_gatt_service_structs()); for service in services { let service_id = service.get_id(); if service_id == id { return Ok(service); } } Err(Box::from("No service exists with the given id.")) } pub fn add_service(&self, service: Arc<FakeBluetoothGATTService>) -> Result<(), Box<Error>> { let cloned = self.gatt_services.clone(); let mut gatt_services = match cloned.lock() { Ok(guard) => guard, Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.push(service)) } pub fn remove_service(&self, id: String) -> Result<(), Box<Error>> { let cloned = self.gatt_services.clone(); let mut gatt_services = match cloned.lock() { Ok(guard) => guard, Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.retain(|s| s.get_id() != id)) } pub fn connect_profile(&self, _uuid: String) -> Result<(), Box<Error>> { unimplemented!(); } pub fn disconnect_profile(&self, _uuid: String) -> Result<(), Box<Error>> { unimplemented!(); } pub fn connect(&self) -> Result<(), Box<Error>> { let is_connectable = try!(self.is_connectable()); let is_connected = try!(self.is_connected()); if is_connected { return Ok(()); } if is_connectable { return self.set_connected(true); } return Err(Box::from("Could not connect to the device.")); } pub fn disconnect(&self) -> Result<(), Box<Error>>{ let is_connected = try!(self.is_connected()); if is_connected { return self.set_connected(false); } return Err(Box::from("The device is not connected.")); } }
use core::ops::Deref; use fake_adapter::FakeBluetoothAdapter; use fake_service::FakeBluetoothGATTService; use hex; use std::collections::HashMap; use std::error::Error; use std::sync::{Arc, Mutex}; #[derive(Clone, Debug)] pub struct FakeBluetoothDevice { id: Arc<Mutex<String>>, adapter: Arc<FakeBluetoothAdapter>, address: Arc<Mutex<String>>, appearance: Arc<Mutex<Option<u16>>>, class: Arc<Mutex<u32>>, gatt_services: Arc<Mutex<Vec<Arc<FakeBluetoothGATTService>>>>, is_paired: Arc<Mutex<bool>>, is_connectable: Arc<Mutex<bool>>, is_connected: Arc<Mutex<bool>>, is_trusted: Arc<Mutex<bool>>, is_blocked: Arc<Mutex<bool>>, is_legacy_pairing: Arc<Mutex<bool>>, uuids: Arc<Mutex<Vec<String>>>, name: Arc<Mutex<Option<String>>>, icon: Arc<Mutex<String>>, alias: Arc<Mutex<String>>, product_version: Arc<Mutex<u32>>, rssi: Arc<Mutex<Option<i16>>>, tx_power: Arc<Mutex<Option<i16>>>, modalias: Arc<Mutex<String>>, manufacturer_data: Arc<Mutex<Option<HashMap<u16, Vec<u8>>>>>, service_data: Arc<Mutex<Option<HashMap<String, Vec<u8>>>>>, } impl FakeBluetoothDevice { pub fn new(id: String, adapter: Arc<FakeBluetoothAdapter>, address: String, appearance: Option<u16>, class: u32, gatt_services: Vec<Arc<FakeBluetoothGATTService>>, is_paired: bool, is_connectable: bool, is_connected: bool, is_trusted: bool, is_blocked: bool, is_legacy_pairing: bool, uuids: Vec<String>, name: Option<String>, icon: String, alias: String, product_version: u32, rssi: Option<i16>, tx_power: Option<i16>, modalias: String, manufacturer_data: Option<HashMap<u16, Vec<u8>>>, service_data: Option<HashMap<String, Vec<u8>>>) -> Arc<FakeBluetoothDevice> { if let Ok(existing_device) = adapter.get_device(id.clone()) { return existing_device; } let device = Arc::new(FakeBluetoothDevice{ id: Arc::new(Mutex::new(id)), adapter: adapter.clone(), address: Arc::new(Mutex::new(address)), appearance: Arc::new(Mutex::new(appearance)), class: Arc::new(Mutex::new(class)), gatt_services: Arc::new(Mutex::new(gatt_services)), is_paired: Arc::new(Mutex::new(is_paired)), is_connectable: Arc::new(Mutex::new(is_connectable)), is_connected: Arc::new(Mutex::new(is_connected)), is_trusted: Arc::new(Mutex::new(is_trusted)), is_blocked: Arc::new(Mutex::new(is_blocked)), is_legacy_pairing: Arc::new(Mutex::new(is_legacy_pairing)), uuids: Arc::new(Mutex::new(uuids)), name: Arc::new(Mutex::new(name)), icon: Arc::new(Mutex::new(icon)), alias: Arc::new(Mutex::new(alias)), product_version: Arc::new(Mutex::new(product_version)), rssi: Arc::new(Mutex::new(rssi)), tx_power: Arc::new(Mutex::new(tx_power)), modalias: Arc::new(Mutex::new(modalias)), manufacturer_data: Arc::new(Mutex::new(manufacturer_data)), service_data: Arc::new(Mutex::new(service_data)), }); let _ = adapter.add_device(device.clone()); device } pub fn new_empty(adapter: Arc<FakeBluetoothAdapter>, device_id: String) -> Arc<FakeBluetoothDevice> { FakeBluetoothDevice::new( /*id*/ device_id, /*adapter*/ adapter, /*address*/ String::new(), /*appearance*/ None, /*class*/ 0, /*gatt_services*/ vec!(), /*is_paired*/ false, /*is_connectable*/ false, /*is_connected*/ false, /*is_trusted*/ false, /*is_blocked*/ false, /*is_legacy_pairing*/ false, /*uuids*/ vec!(), /*name*/ None, /*icon*/ String::new(), /*alias*/ String::new(), /*product_version*/ 0, /*rssi*/ None, /*tx_power*/ None, /*modalias*/ String::new(), /*manufacturer_data*/ None, /*service_data*/ None, ) } make_getter!(get_id, id); make_setter!(set_id, id); make_getter!(get_address, address, String); make_setter!(set_address, address, String); make_option_getter!(get_name, name, String); make_setter!(set_name, name, Option<String>); make_getter!(get_icon, icon, String); make_setter!(set_icon, icon, String); make_getter!(get_class, class, u32); make_setter!(set_class, class, u32); make_option_getter!(get_appearance, appearance, u16); make_setter!(set_appearance, appearance, Option<u16>); make_getter!(get_uuids, uuids, Vec<String>); make_setter!(set_uuids, uuids, Vec<String>); make_getter!(is_paired); make_setter!(set_paired, is_paired, bool); make_getter!(is_connectable); make_setter!(set_connectable, is_connectable, bool); make_getter!(is_connected); make_setter!(set_connected, is_connected, bool); make_getter!(is_trusted); make_setter!(set_trusted, is_trusted, bool); make_getter!(is_blocked); make_setter!(set_blocked, is_blocked, bool); make_getter!(get_alias, alias, String); make_setter!(set_alias, alias, String); make_getter!(is_legacy_pairing); make_setter!(set_legacy_pairing, is_legacy_pairing, bool); make_setter!(set_modalias, modalias, String); make_option_getter!(get_rssi, rssi, i16); make_setter!(set_rssi, rssi, Option<i16>); make_option_getter!(get_tx_power, tx_power, i16); make_setter!(set_tx_power, tx_power, Option<i16>); make_option_getter!(get_manufacturer_data, manufacturer_data, HashMap<u16, Vec<u8>>); make_setter!(set_manufacturer_data, manufacturer_data, Option<HashMap<u16, Vec<u8>>>); make_option_getter!(get_service_data, service_data, HashMap<String, Vec<u8>>); make_setter!(set_service_data, service_data, Option<HashMap<String, Vec<u8>>>); pub fn get_adapter(&self) -> Result<Arc<FakeBluetoothAdapter>, Box<Error>> { Ok(self.adapter.clone()) } pub fn pair(&self) -> Result<(), Box<Error>> { self.set_paired(true) } pub fn cancel_pairing(&self) -> Result<(), Box<Error>> { self.set_paired(false) } pub fn get_modalias(&self) -> Result<(String, u32, u32, u32), Box<Error>> { let cloned = self.modalias.clone(); let modalias = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; let ids: Vec<&str> = modalias.split(":").collect(); let source = String::from(ids[0]); let vendor = hex::decode(&ids[1][1..5]).unwrap(); let product = hex::decode(&ids[1][6..10]).unwrap(); let device = hex::decode(&ids[1][11..15]).unwrap();
} pub fn get_vendor_id_source(&self) -> Result<String, Box<Error>> { let (vendor_id_source,_,_,_) = try!(self.get_modalias()); Ok(vendor_id_source) } pub fn get_vendor_id(&self) -> Result<u32, Box<Error>> { let (_,vendor_id,_,_) = try!(self.get_modalias()); Ok(vendor_id) } pub fn get_product_id(&self) -> Result<u32, Box<Error>> { let (_,_,product_id,_) = try!(self.get_modalias()); Ok(product_id) } pub fn get_device_id(&self) -> Result<u32, Box<Error>> { let (_,_,_,device_id) = try!(self.get_modalias()); Ok(device_id) } pub fn get_gatt_services(&self) -> Result<Vec<String>, Box<Error>> { if !(try!(self.is_connected())) { return Err(Box::from("Device not connected.")); } let cloned = self.gatt_services.clone(); let gatt_services = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.into_iter().map(|s| s.get_id()).collect()) } pub fn get_gatt_service_structs(&self) -> Result<Vec<Arc<FakeBluetoothGATTService>>, Box<Error>> { if !(try!(self.is_connected())) { return Err(Box::from("Device not connected.")); } let cloned = self.gatt_services.clone(); let gatt_services = match cloned.lock() { Ok(guard) => guard.deref().clone(), Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services) } pub fn get_gatt_service(&self, id: String) -> Result<Arc<FakeBluetoothGATTService>, Box<Error>> { let services = try!(self.get_gatt_service_structs()); for service in services { let service_id = service.get_id(); if service_id == id { return Ok(service); } } Err(Box::from("No service exists with the given id.")) } pub fn add_service(&self, service: Arc<FakeBluetoothGATTService>) -> Result<(), Box<Error>> { let cloned = self.gatt_services.clone(); let mut gatt_services = match cloned.lock() { Ok(guard) => guard, Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.push(service)) } pub fn remove_service(&self, id: String) -> Result<(), Box<Error>> { let cloned = self.gatt_services.clone(); let mut gatt_services = match cloned.lock() { Ok(guard) => guard, Err(_) => return Err(Box::from("Could not get the value.")), }; Ok(gatt_services.retain(|s| s.get_id() != id)) } pub fn connect_profile(&self, _uuid: String) -> Result<(), Box<Error>> { unimplemented!(); } pub fn disconnect_profile(&self, _uuid: String) -> Result<(), Box<Error>> { unimplemented!(); } pub fn connect(&self) -> Result<(), Box<Error>> { let is_connectable = try!(self.is_connectable()); let is_connected = try!(self.is_connected()); if is_connected { return Ok(()); } if is_connectable { return self.set_connected(true); } return Err(Box::from("Could not connect to the device.")); } pub fn disconnect(&self) -> Result<(), Box<Error>>{ let is_connected = try!(self.is_connected()); if is_connected { return self.set_connected(false); } return Err(Box::from("The device is not connected.")); } }
Ok((source, (vendor[0] as u32) * 16 * 16 + (vendor[1] as u32), (product[0] as u32) * 16 * 16 + (product[1] as u32), (device[0] as u32) * 16 * 16 + (device[1] as u32)))
call_expression
[ { "content": "\n\n pub fn get_modalias(&self) -> Result<(String, u32, u32, u32), Box<Error>> {\n\n let cloned = self.modalias.clone();\n\n let modalias = match cloned.lock() {\n\n Ok(guard) => guard.deref().clone(),\n\n Err(_) => return Err(Box::from(\"Could not get the v...
Rust
build/src/lib.rs
BusyJay/jinkela
88cdbdb57ae53ea13ea1b8f81e4641e6d67686b4
use std::fs::File; use std::io::Write; #[derive(Default)] pub struct Builder { out_dir: Option<String>, includes: Vec<String>, sources: Vec<String>, } impl Builder { pub fn out_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.out_dir = Some(dir.into()); self } pub fn include_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.includes.push(dir.into()); self } pub fn compile_proto(&mut self, proto: impl Into<String>) -> &mut Builder { self.sources.push(proto.into()); self } pub fn build(&self) { for (key, value) in std::env::vars() { println!("{}: {}", key, value); } let proto_dir = self.out_dir.clone().unwrap_or_else(|| { let out_dir = std::env::var("OUT_DIR").unwrap(); format!("{}/protos", out_dir) }); if std::path::Path::new(&proto_dir).exists() { std::fs::remove_dir_all(&proto_dir).unwrap(); } std::fs::create_dir_all(&proto_dir).unwrap(); let protoc = protoc::Protoc::from_env_path(); let desc_file = format!("{}/mod.desc", proto_dir); let mut includes: Vec<&str> = Vec::new(); for i in &self.includes { includes.push(&i); } let mut inputs: Vec<&str> = Vec::new(); for s in &self.sources { inputs.push(&s); } protoc.write_descriptor_set(protoc::DescriptorSetOutArgs { out: &desc_file, includes: &includes, input: &inputs, include_imports: true, }).unwrap(); self.internal_build(&proto_dir, &desc_file); let modules: Vec<_> = std::fs::read_dir(&proto_dir).unwrap().filter_map(|res| { let path = match res { Ok(e) => e.path(), Err(e) => panic!("failed to list {}: {:?}", proto_dir, e), }; if path.extension() == Some(std::ffi::OsStr::new("rs")) { let name = path.file_stem().unwrap().to_str().unwrap(); Some((name.replace('-', "_"), name.to_owned())) } else { None } }).collect(); let mut f = File::create(format!("{}/mod.rs", proto_dir)).unwrap(); for (module, file_name) in &modules { if !module.contains('.') { writeln!(f, "pub mod {};", module).unwrap(); continue; } let mut level = 0; for part in module.split('.') { writeln!(f, "{:level$}pub mod {} {{", "", part, level = level).unwrap(); level += 1; } writeln!(f, "include!(\"{}.rs\");", file_name).unwrap(); for _ in (0..level).rev() { writeln!(f, "{:1$}}}", "", level).unwrap(); } } } #[cfg(feature = "protobuf-codec")] fn internal_build(&self, out_dir: &str, desc_file: &str) { println!("building protobuf at {} for {}", out_dir, desc_file); let desc_bytes = std::fs::read(&desc_file).unwrap(); let desc: protobuf::descriptor::FileDescriptorSet = protobuf::parse_from_bytes(&desc_bytes).unwrap(); let mut files_to_generate = Vec::new(); 'outer: for file in &self.sources { let f = std::path::Path::new(file); for include in &self.includes { if let Some(truncated) = f.strip_prefix(include).ok() { files_to_generate.push(format!("{}", truncated.display())); continue 'outer; } } panic!("file {:?} is not found in includes {:?}", file, self.includes); } protobuf_codegen::gen_and_write( desc.get_file(), &files_to_generate, &std::path::Path::new(out_dir), &protobuf_codegen::Customize::default(), ).unwrap(); self.build_grpcio(&desc.get_file(), &files_to_generate, &out_dir); } #[cfg(feature = "prost-codec")] fn internal_build(&self, out_dir: &str, desc_file: &str) { println!("building prost at {}", out_dir); let mut cfg = prost_build::Config::new(); cfg.type_attribute(".", "#[derive(::jinkela::Classicalize)]").out_dir(out_dir); cfg.compile_protos(&self.sources, &self.includes).unwrap(); self.build_grpcio(out_dir, desc_file); } #[cfg(feature = "grpcio-protobuf-codec")] fn build_grpcio(&self, desc: &[protobuf::descriptor::FileDescriptorProto], files_to_generates: &[String], output: &str) { println!("building protobuf with grpcio at {}", output); let output_dir = std::path::Path::new(output); let results = grpcio_compiler::codegen::gen(&desc, &files_to_generates); for res in results { let out_file = output_dir.join(&res.name); let mut f = File::create(&out_file).unwrap(); f.write_all(&res.content).unwrap(); } } #[cfg(all(feature = "protobuf-codec", not(feature = "grpcio-protobuf-codec")))] fn build_grpcio(&self, _: &[protobuf::descriptor::FileDescriptorProto], _: &[String], _: &str) {} #[cfg(feature = "grpcio-prost-codec")] fn build_grpcio(&self, out_dir: &str, desc_file: &str) { use prost::Message; let desc_bytes = std::fs::read(&desc_file).unwrap(); let desc = prost_types::FileDescriptorSet::decode(&desc_bytes).unwrap(); let mut files_to_generate = Vec::new(); 'outer: for file in &self.sources { let f = std::path::Path::new(file); for include in &self.includes { if let Some(truncated) = f.strip_prefix(include).ok() { files_to_generate.push(format!("{}", truncated.display())); continue 'outer; } } panic!("file {:?} is not found in includes {:?}", file, self.includes); } let out_dir = std::path::Path::new(out_dir); let results = grpcio_compiler::codegen::gen(&desc.file, &files_to_generate); for res in results { let out_file = out_dir.join(&res.name); let mut f = File::create(&out_file).unwrap(); f.write_all(&res.content).unwrap(); } } #[cfg(all(feature = "prost-codec", not(feature = "grpcio-prost-codec")))] fn build_grpcio(&self, _out_dir: &str, _desc_file: &str) {} }
use std::fs::File; use std::io::Write; #[derive(Default)] pub struct Builder { out_dir: Option<String>, includes: Vec<String>, sources: Vec<String>, } impl Builder { pub fn out_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.out_dir = Some(dir.into()); self } pub fn include_dir(&mut self, dir: impl Into<String>) -> &mut Builder { self.includes.push(dir.into()); self } pub fn compile_proto(&mut self, proto: impl Into<String>) -> &mut Builder { self.sources.push(proto.into()); self } pub fn build(&self) { for (key, value) in std::env::vars() { println!("{}: {}", key, value); } let proto_dir = self.out_dir.clone().unwrap_or_else(|| { let out_dir = std::env::var("OUT_DIR").unwrap(); format!("{}/protos", out_dir) }); if std::path::Path::new(&proto_dir).exists() { std::fs::remove_dir_all(&proto_dir).unwrap(); } std::fs::create_dir_all(&proto_dir).unwrap(); let protoc = protoc::Protoc::from_env_path(); let desc_file = format!("{}/mod.desc", proto_dir); let mut includes: Vec<&str> = Vec::new(); for i in &self.includes { includes.push(&i); } let mut inputs: Vec<&str> = Vec::new(); for s in &self.sources { inputs.push(&s); } protoc.write_descriptor_set(protoc::DescriptorSetOutArgs { out: &desc_file, includes: &includes, input: &inputs, include_imports: true, }).unwrap(); self.internal_build(&proto_dir, &desc_file); let modules: Vec<_> = std::fs::read_dir(&proto_dir).unwrap().filter_map(|res| { let path = match res { Ok(e) => e.path(), Err(e) => panic!("failed to list {}: {:?}", proto_dir, e), }; if path.extension() == Some(std::ffi::OsStr::new("rs")) { let name = path.file_stem().unwrap().to_str().unwrap(); Some((name.replace('-', "_"), name.to_owned())) } else { None } }).collect(); let mut f = File::create(format!("{}/mod.rs", proto_dir)).unwrap(); for (module, file_name) in &modules { if !module.contains('.') { writeln!(f, "pub mod {};", module).unwrap(); continue; } let mut level = 0; for part in module.split('.') { writeln!(f, "{:level$}pub mod {} {{", "", part, level = level).unwrap(); level += 1; } writeln!(f, "include!(\"{}.rs\");", file_name).unwrap(); for _ in (0..level).rev() { writeln!(f, "{:1$}}}", "", level).unwrap(); } } } #[cfg(feature = "protobuf-codec")] fn internal_build(&self, out_dir: &str, desc_file: &str) { println!("building protobuf at {} for {}", out_dir, desc_file); let desc_bytes = std::fs::read(&desc_file).unwrap(); let desc: protobuf::descriptor::FileDescriptorSet = protobuf::parse_from_bytes(&desc_bytes).unwrap(); let mut files_to_generate = Vec::new(); 'outer: for file in &self.sources { let f = std::path::Path::new(file); for include in &self.includes { if let Some(truncated) = f.strip_prefix(include).ok() { files_to_generate.push(format!("{}", truncated.display())); continue 'outer; } } panic!("file {:?} is not found in includes {:?}", file, self.includes); } protobuf_codegen::gen_and_write( desc.get_file(), &files_to_generate, &std::path::Path::new(out_dir), &protobuf_codegen::Customize::default(), ).unwrap(); self.build_grpcio(&desc.get_file(), &files_to_generate, &out_dir); } #[cfg(feature = "prost-codec")] fn internal_build(&self, out_dir: &str, desc_file: &str) { println!("building prost at {}", out_dir); let mut cfg = prost_build::Config::new(); cfg.type_attribute(".", "#[derive(::jinkela::Classicalize)]").out_dir(out_dir); cfg.compile_protos(&self.sources, &self.includes).unwrap(); self.build_grpcio(out_dir, desc_file); } #[cfg(feature = "grpcio-protobuf-codec")] fn build_grpcio(&self, desc: &[protobuf::descriptor::FileDescriptorProto], files_to_generates: &[String], output: &str) { println!("building protobuf with grpcio at {}", output); let output_dir = std::path::Path::new(output); let results = grpcio_compiler::codegen::gen(&desc, &files_to_generates); for res in results { let out_file = output_dir.join(&res.name); let mut f = File::create(&out_file).unwrap(); f.write_all(&res.content).unwrap(); } } #[cfg(all(feature = "protobuf-codec", not(feature = "grpcio-protobuf-codec")))] fn build_grpcio(&self, _: &[protobuf::descriptor::FileDescriptorProto], _: &[String], _: &str) {} #[cfg(feature = "grpcio-prost-codec")] fn build_grpcio(&self, out_dir: &str, desc_file: &str) { use prost::Message; let desc_bytes = std::fs::read(&desc_file).unwrap(); let desc = prost_types::FileDescriptorSet::decode(&desc_bytes).unwrap(); let mut files_to_generate = Vec::new(); 'outer: for
); } let out_dir = std::path::Path::new(out_dir); let results = grpcio_compiler::codegen::gen(&desc.file, &files_to_generate); for res in results { let out_file = out_dir.join(&res.name); let mut f = File::create(&out_file).unwrap(); f.write_all(&res.content).unwrap(); } } #[cfg(all(feature = "prost-codec", not(feature = "grpcio-prost-codec")))] fn build_grpcio(&self, _out_dir: &str, _desc_file: &str) {} }
file in &self.sources { let f = std::path::Path::new(file); for include in &self.includes { if let Some(truncated) = f.strip_prefix(include).ok() { files_to_generate.push(format!("{}", truncated.display())); continue 'outer; } } panic!("file {:?} is not found in includes {:?}", file, self.includes
function_block-random_span
[ { "content": "#[proc_macro_derive(Classicalize, attributes(prost))]\n\npub fn classicalize(input: TokenStream) -> TokenStream {\n\n let input: DeriveInput = syn::parse(input).unwrap();\n\n let s = match input.data {\n\n Data::Struct(s) => classicalize_struct(input.ident, s),\n\n Data::Enum(e...
Rust
src/sms/async/send.rs
drahnr/messagebird
2d22bac58359b9f21410d47bc306d36b538ea710
use super::super::*; use futures::*; use hyper; use hyper_rustls; use std::env; use std::fmt; use std::marker::PhantomData; use std::ops::Deref; #[derive(Debug, Clone)] pub struct AccessKey(String); impl Deref for AccessKey { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } } impl FromStr for AccessKey { type Err = MessageBirdError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(AccessKey(s.to_string())) } } impl From<String> for AccessKey { fn from(s: String) -> Self { AccessKey(s) } } impl fmt::Display for AccessKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl AccessKey { pub fn from_env() -> Result<AccessKey, MessageBirdError> { let raw = env::var("MESSAGEBIRD_ACCESSKEY").map_err(|_e| MessageBirdError::AccessKeyError { msg: "env".to_string(), })?; AccessKey::from_str(raw.as_str()) } } pub type RequestMessageList = Request<parameter::list::ListParameters, MessageList>; pub type RequestView = Request<parameter::view::ViewParameters, Message>; pub type RequestSend = Request<parameter::send::SendParameters, Message>; pub struct Request<T, R> { future: Box<dyn Future<Item = R, Error = MessageBirdError>>, phantom: PhantomData<T>, } impl<T, R> Future for Request<T, R> { type Item = R; type Error = MessageBirdError; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { self.future.poll() } } fn request_future_with_json_response<R>( client: &mut hyper::Client< hyper_rustls::HttpsConnector<hyper::client::HttpConnector>, hyper::Body, >, request: hyper::Request<hyper::Body>, ) -> impl Future<Item = R, Error = MessageBirdError> where R: 'static + Sized + Send + Sync + for<'de> serde::de::Deserialize<'de> + std::fmt::Debug, { debug!("request {:?}", request); let fut = client .request(request) .map_err(|e: hyper::Error| { debug!("request {:?}", e); MessageBirdError::RequestError }) .and_then(|response: hyper::Response<hyper::Body>| { let status = response.status(); debug!("rest status code: {}", status); futures::future::ok(response) }) .and_then(|response: hyper::Response<hyper::Body>| { let status = response.status(); let body: hyper::Body = response.into_body(); body.concat2() .map_err(|e| { debug!("body concat {:?}", e); MessageBirdError::RequestError }) .map(move |x| (status, x)) }) .and_then(|(status, body): (_, hyper::Chunk)| { debug!("response: {:?}", String::from_utf8(body.to_vec()).unwrap()); match status { hyper::StatusCode::OK | hyper::StatusCode::CREATED => { match serde_json::from_slice::<R>(&body).map_err(|e| { debug!("Failed to parse response body: {:?}", e); MessageBirdError::ParseError }) { Err(e) => futures::future::err(e), Ok(x) => { debug!("Parsed response {:?}", x); futures::future::ok(x) } } } _ => match serde_json::from_slice::<ServiceErrors>(&body).map_err(|e| { debug!("Failed to parse response body: {:?}", e); MessageBirdError::ParseError }) { Err(e) => futures::future::err(e), Ok(service_errors) => { let service_errors = service_errors.into(); debug!("Parsed error response {:?}", service_errors); futures::future::err(MessageBirdError::ServiceError(service_errors)) } }, } }); fut } impl<P, R> Request<P, R> where P: Send + Query, R: 'static + Send + Sync + for<'de> serde::de::Deserialize<'de> + std::fmt::Debug, { pub fn new(parameters: &P, accesskey: &AccessKey) -> Self { let https = hyper_rustls::HttpsConnector::new(4); let mut client: hyper::Client<_, hyper::Body> = hyper::Client::builder().build(https); let mut request = hyper::Request::builder(); request.uri(parameters.uri()); request.method(parameters.method()); request.header( hyper::header::AUTHORIZATION, format!("AccessKey {}", accesskey), ); debug!("{:?}", request); let request: hyper::Request<_> = if parameters.method() == hyper::Method::POST { request.header( hyper::header::CONTENT_TYPE, format!("application/x-www-form-urlencoded"), ); parameters .uri() .query() .map(|body: &str| { let body = body.to_string(); request.header(hyper::header::CONTENT_LENGTH, format!("{}", body.len())); request.body(body.into()).unwrap() }) .unwrap_or_else(|| { request.header(hyper::header::CONTENT_LENGTH, format!("{}", 0)); request.body(hyper::Body::empty()).unwrap() }) } else { request.header(hyper::header::CONTENT_LENGTH, format!("{}", 0)); request.body(hyper::Body::empty()).unwrap() }; let future = request_future_with_json_response::<R>(&mut client, request); let future = Box::new(future); Self { future, phantom: PhantomData, } } }
use super::super::*; use futures::*; use hyper; use hyper_rustls; use std::env; use std::fmt; use std::marker::PhantomData; use std::ops::Deref; #[derive(Debug, Clone)] pub struct AccessKey(String); impl Deref for AccessKey { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } } impl FromStr for AccessKey { type Err = MessageBirdError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(AccessKey(s.to_string())) } } impl From<String> for AccessKey { fn from(s: String) -> Self { AccessKey(s) } } impl fmt::Display for AccessKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } impl AccessKey { pub fn from_env() -> Result<AccessKey, MessageBirdError> { let raw = env::var("MESSAGEBIRD_ACCESSKEY").map_err(|_e| MessageBirdError::AccessKeyError { msg: "env".to_string(), })?; AccessKey::from_str(raw.as_str()) } } pub type RequestMessageLis
futures::future::ok(response) }) .and_then(|response: hyper::Response<hyper::Body>| { let status = response.status(); let body: hyper::Body = response.into_body(); body.concat2() .map_err(|e| { debug!("body concat {:?}", e); MessageBirdError::RequestError }) .map(move |x| (status, x)) }) .and_then(|(status, body): (_, hyper::Chunk)| { debug!("response: {:?}", String::from_utf8(body.to_vec()).unwrap()); match status { hyper::StatusCode::OK | hyper::StatusCode::CREATED => { match serde_json::from_slice::<R>(&body).map_err(|e| { debug!("Failed to parse response body: {:?}", e); MessageBirdError::ParseError }) { Err(e) => futures::future::err(e), Ok(x) => { debug!("Parsed response {:?}", x); futures::future::ok(x) } } } _ => match serde_json::from_slice::<ServiceErrors>(&body).map_err(|e| { debug!("Failed to parse response body: {:?}", e); MessageBirdError::ParseError }) { Err(e) => futures::future::err(e), Ok(service_errors) => { let service_errors = service_errors.into(); debug!("Parsed error response {:?}", service_errors); futures::future::err(MessageBirdError::ServiceError(service_errors)) } }, } }); fut } impl<P, R> Request<P, R> where P: Send + Query, R: 'static + Send + Sync + for<'de> serde::de::Deserialize<'de> + std::fmt::Debug, { pub fn new(parameters: &P, accesskey: &AccessKey) -> Self { let https = hyper_rustls::HttpsConnector::new(4); let mut client: hyper::Client<_, hyper::Body> = hyper::Client::builder().build(https); let mut request = hyper::Request::builder(); request.uri(parameters.uri()); request.method(parameters.method()); request.header( hyper::header::AUTHORIZATION, format!("AccessKey {}", accesskey), ); debug!("{:?}", request); let request: hyper::Request<_> = if parameters.method() == hyper::Method::POST { request.header( hyper::header::CONTENT_TYPE, format!("application/x-www-form-urlencoded"), ); parameters .uri() .query() .map(|body: &str| { let body = body.to_string(); request.header(hyper::header::CONTENT_LENGTH, format!("{}", body.len())); request.body(body.into()).unwrap() }) .unwrap_or_else(|| { request.header(hyper::header::CONTENT_LENGTH, format!("{}", 0)); request.body(hyper::Body::empty()).unwrap() }) } else { request.header(hyper::header::CONTENT_LENGTH, format!("{}", 0)); request.body(hyper::Body::empty()).unwrap() }; let future = request_future_with_json_response::<R>(&mut client, request); let future = Box::new(future); Self { future, phantom: PhantomData, } } }
t = Request<parameter::list::ListParameters, MessageList>; pub type RequestView = Request<parameter::view::ViewParameters, Message>; pub type RequestSend = Request<parameter::send::SendParameters, Message>; pub struct Request<T, R> { future: Box<dyn Future<Item = R, Error = MessageBirdError>>, phantom: PhantomData<T>, } impl<T, R> Future for Request<T, R> { type Item = R; type Error = MessageBirdError; fn poll(&mut self) -> Result<Async<Self::Item>, Self::Error> { self.future.poll() } } fn request_future_with_json_response<R>( client: &mut hyper::Client< hyper_rustls::HttpsConnector<hyper::client::HttpConnector>, hyper::Body, >, request: hyper::Request<hyper::Body>, ) -> impl Future<Item = R, Error = MessageBirdError> where R: 'static + Sized + Send + Sync + for<'de> serde::de::Deserialize<'de> + std::fmt::Debug, { debug!("request {:?}", request); let fut = client .request(request) .map_err(|e: hyper::Error| { debug!("request {:?}", e); MessageBirdError::RequestError }) .and_then(|response: hyper::Response<hyper::Body>| { let status = response.status(); debug!("rest status code: {}", status);
random
[ { "content": "/// TODO the name is misleading/obsolete, should be something with params\n\npub trait Query {\n\n fn uri(&self) -> hyper::Uri;\n\n fn method(&self) -> hyper::Method {\n\n hyper::Method::GET\n\n }\n\n}\n\n\n\n/// Contact Id\n\n///\n\n/// TODO not implemented just yet\n\n#[derive(Cl...
Rust
crate/object_play/src/system/object_acceleration_system.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
use amethyst::{ ecs::{Join, Read, ReadStorage, System, World, WriteStorage}, shred::{ResourceId, SystemData}, shrev::{EventChannel, ReaderId}, }; use derivative::Derivative; use derive_new::new; use game_input_model::play::ControllerInput; use kinematic_model::config::{ ObjectAcceleration, ObjectAccelerationKind, ObjectAccelerationValue, ObjectAccelerationValueExpr, ObjectAccelerationValueMultiplier, Velocity, }; use mirrored_model::play::Mirrored; use sequence_model::play::SequenceUpdateEvent; #[derive(Debug, Default, new)] pub struct ObjectAccelerationSystem { #[new(default)] sequence_update_event_rid: Option<ReaderId<SequenceUpdateEvent>>, } #[derive(Derivative, SystemData)] #[derivative(Debug)] pub struct ObjectAccelerationSystemData<'s> { #[derivative(Debug = "ignore")] pub sequence_update_ec: Read<'s, EventChannel<SequenceUpdateEvent>>, #[derivative(Debug = "ignore")] pub controller_inputs: ReadStorage<'s, ControllerInput>, #[derivative(Debug = "ignore")] pub mirroreds: ReadStorage<'s, Mirrored>, #[derivative(Debug = "ignore")] pub object_accelerations: ReadStorage<'s, ObjectAcceleration>, #[derivative(Debug = "ignore")] pub velocities: WriteStorage<'s, Velocity<f32>>, } impl ObjectAccelerationSystem { fn update_velocity( controller_input: Option<ControllerInput>, mirrored: Option<Mirrored>, object_acceleration: ObjectAcceleration, velocity: &mut Velocity<f32>, ) { let negate = mirrored.map(|mirrored| mirrored.0).unwrap_or(false); let acc_x = Self::acceleration_value(controller_input, object_acceleration.x); if negate { velocity[0] -= acc_x; } else { velocity[0] += acc_x; } velocity[1] += Self::acceleration_value(controller_input, object_acceleration.y); velocity[2] += Self::acceleration_value(controller_input, object_acceleration.z); } fn acceleration_value( controller_input: Option<ControllerInput>, object_acceleration_value: ObjectAccelerationValue, ) -> f32 { match object_acceleration_value { ObjectAccelerationValue::Const(value) => value, ObjectAccelerationValue::Expr(ObjectAccelerationValueExpr { multiplier, value }) => { match multiplier { ObjectAccelerationValueMultiplier::One => value, ObjectAccelerationValueMultiplier::XAxis => { let multiplier = controller_input .map(|controller_input| controller_input.x_axis_value.abs()) .unwrap_or(0.); multiplier * value } ObjectAccelerationValueMultiplier::ZAxis => { let multiplier = controller_input .map(|controller_input| controller_input.z_axis_value) .unwrap_or(0.); multiplier * value } } } } } } impl<'s> System<'s> for ObjectAccelerationSystem { type SystemData = ObjectAccelerationSystemData<'s>; fn run( &mut self, ObjectAccelerationSystemData { sequence_update_ec, controller_inputs, mirroreds, object_accelerations, mut velocities, }: Self::SystemData, ) { sequence_update_ec .read( self.sequence_update_event_rid .as_mut() .expect("Expected `sequence_update_event_rid` to exist."), ) .for_each(|ev| { if let SequenceUpdateEvent::SequenceBegin { entity, .. } | SequenceUpdateEvent::FrameBegin { entity, .. } = ev { let entity = *entity; let object_acceleration = object_accelerations.get(entity); let velocity = velocities.get_mut(entity); let controller_input = controller_inputs.get(entity).copied(); let mirrored = mirroreds.get(entity).copied(); if let (Some(object_acceleration), Some(velocity)) = (object_acceleration, velocity) { if object_acceleration.kind == ObjectAccelerationKind::Once { Self::update_velocity( controller_input, mirrored, *object_acceleration, velocity, ); } } } }); ( &object_accelerations, &mut velocities, controller_inputs.maybe(), mirroreds.maybe(), ) .join() .filter(|(object_acceleration, _, _, _)| { object_acceleration.kind == ObjectAccelerationKind::Continuous }) .for_each( |(object_acceleration, velocity, controller_input, mirrored)| { Self::update_velocity( controller_input.copied(), mirrored.copied(), *object_acceleration, velocity, ); }, ); } fn setup(&mut self, world: &mut World) { Self::SystemData::setup(world); self.sequence_update_event_rid = Some( world .fetch_mut::<EventChannel<SequenceUpdateEvent>>() .register_reader(), ); } }
use amethyst::{ ecs::{Join, Read, ReadStorage, System, World, WriteStorage}, shred::{ResourceId, SystemData}, shrev::{EventChannel, ReaderId}, }; use derivative::Derivative; use derive_new::new; use game_input_model::play::ControllerInput; use kinematic_model::config::{ ObjectAcceleration, ObjectAccelerationKind, ObjectAccelerationValue, ObjectAccelerationValueExpr, ObjectAccelerationValueMultiplier, Velocity, }; use mirrored_model::play::Mirrored; use sequence_model::play::SequenceUpdateEvent; #[derive(Debug, Default, new)] pub struct ObjectAccelerationSystem { #[new(default)] sequence_update_event_rid: Option<ReaderId<SequenceUpdateEvent>>, } #[derive(Derivative, SystemData)] #[derivative(Debug)] pub struct ObjectAccelerationSystemData<'s> { #[derivative(Debug = "ignore")] pub sequence_update_ec: Read<'s, EventChannel<SequenceUpdateEvent>>, #[derivative(Debug = "ignore")] pub controller_inputs: ReadStorage<'s, ControllerInput>, #[derivative(Debug = "ignore")] pub mirroreds: ReadStorage<'s, Mirrored>, #[derivative(Debug = "ignore")] pub object_accelerations: ReadStorage<'s, ObjectAcceleration>, #[derivative(Debug = "ignore")] pub velocities: WriteStorage<'s, Velocity<f32>>, } impl ObjectAccelerationSystem {
fn acceleration_value( controller_input: Option<ControllerInput>, object_acceleration_value: ObjectAccelerationValue, ) -> f32 { match object_acceleration_value { ObjectAccelerationValue::Const(value) => value, ObjectAccelerationValue::Expr(ObjectAccelerationValueExpr { multiplier, value }) => { match multiplier { ObjectAccelerationValueMultiplier::One => value, ObjectAccelerationValueMultiplier::XAxis => { let multiplier = controller_input .map(|controller_input| controller_input.x_axis_value.abs()) .unwrap_or(0.); multiplier * value } ObjectAccelerationValueMultiplier::ZAxis => { let multiplier = controller_input .map(|controller_input| controller_input.z_axis_value) .unwrap_or(0.); multiplier * value } } } } } } impl<'s> System<'s> for ObjectAccelerationSystem { type SystemData = ObjectAccelerationSystemData<'s>; fn run( &mut self, ObjectAccelerationSystemData { sequence_update_ec, controller_inputs, mirroreds, object_accelerations, mut velocities, }: Self::SystemData, ) { sequence_update_ec .read( self.sequence_update_event_rid .as_mut() .expect("Expected `sequence_update_event_rid` to exist."), ) .for_each(|ev| { if let SequenceUpdateEvent::SequenceBegin { entity, .. } | SequenceUpdateEvent::FrameBegin { entity, .. } = ev { let entity = *entity; let object_acceleration = object_accelerations.get(entity); let velocity = velocities.get_mut(entity); let controller_input = controller_inputs.get(entity).copied(); let mirrored = mirroreds.get(entity).copied(); if let (Some(object_acceleration), Some(velocity)) = (object_acceleration, velocity) { if object_acceleration.kind == ObjectAccelerationKind::Once { Self::update_velocity( controller_input, mirrored, *object_acceleration, velocity, ); } } } }); ( &object_accelerations, &mut velocities, controller_inputs.maybe(), mirroreds.maybe(), ) .join() .filter(|(object_acceleration, _, _, _)| { object_acceleration.kind == ObjectAccelerationKind::Continuous }) .for_each( |(object_acceleration, velocity, controller_input, mirrored)| { Self::update_velocity( controller_input.copied(), mirrored.copied(), *object_acceleration, velocity, ); }, ); } fn setup(&mut self, world: &mut World) { Self::SystemData::setup(world); self.sequence_update_event_rid = Some( world .fetch_mut::<EventChannel<SequenceUpdateEvent>>() .register_reader(), ); } }
fn update_velocity( controller_input: Option<ControllerInput>, mirrored: Option<Mirrored>, object_acceleration: ObjectAcceleration, velocity: &mut Velocity<f32>, ) { let negate = mirrored.map(|mirrored| mirrored.0).unwrap_or(false); let acc_x = Self::acceleration_value(controller_input, object_acceleration.x); if negate { velocity[0] -= acc_x; } else { velocity[0] += acc_x; } velocity[1] += Self::acceleration_value(controller_input, object_acceleration.y); velocity[2] += Self::acceleration_value(controller_input, object_acceleration.z); }
function_block-full_function
[ { "content": "#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]\n\nstruct SessionCodeId(pub u64);\n\n\n\n/// Mappings from `SessionCode` to `NetSessionDevices`, and `SocketAddr` to `SessionCode`.\n\n#[derive(Clone, Debug, Default, new)]\n\npub struct SessionDeviceMappings {\n\n /// Mappings from `S...
Rust
src/server.rs
dethoter/tokio_test
c0185eb40b9e5bc994cf3b2b4916c924de3affa0
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![deny(deprecated)] extern crate tokio_proto; extern crate tokio_io; extern crate tokio_service; extern crate tokio_timer; extern crate futures; extern crate futures_cpupool; extern crate bytes; extern crate bincode; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate serde; #[macro_use] extern crate serde_derive; mod protocol; use std::io; use std::net::SocketAddr; use std::time::{Duration, Instant}; use futures::{future, Future}; use futures_cpupool::CpuPool; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Framed, Encoder, Decoder}; use tokio_timer::Timer; use tokio_proto::TcpServer; use tokio_proto::multiplex::{RequestId, ServerProto}; use tokio_service::Service; use structopt::StructOpt; use bytes::{BytesMut, Buf, BufMut, BigEndian}; use protocol::{CountRequest, CountResponse}; #[derive(StructOpt, Debug)] #[structopt(name = "serv", about = "Server that counts")] struct Args { #[structopt(short = "p", long = "port", help = "Server's port", default_value = "5234")] port: u16, #[structopt(short = "t", long = "timeout", help = "Timeout per 1 task", default_value = "5")] timeout: usize, #[structopt(short = "j", long = "threads", help = "Number of threads", default_value = "0")] threads: usize, } struct ServerCodec; impl Decoder for ServerCodec { type Item = (RequestId, CountRequest); type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> { if buf.len() >= 4 { let length = io::Cursor::new(&buf.split_to(4)).get_u32::<BigEndian>() as usize; if buf.len() >= length { return Ok(bincode::deserialize(&buf.split_to(length)).ok()); } } Ok(None) } } impl Encoder for ServerCodec { type Item = (RequestId, CountResponse); type Error = io::Error; fn encode(&mut self, item: Self::Item, buf: &mut BytesMut) -> io::Result<()> { let bytes = bincode::serialize(&item, bincode::Infinite).map_err(|_| { io::ErrorKind::InvalidData })?; let length = bytes.len(); buf.reserve(4 + length); buf.put_u32::<BigEndian>(length as u32); buf.put_slice(&bytes); Ok(()) } } struct ServerProtocol; impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for ServerProtocol { type Request = CountRequest; type Response = CountResponse; type Transport = Framed<T, ServerCodec>; type BindTransport = Result<Self::Transport, io::Error>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(ServerCodec)) } } struct Counter { thread_pool: CpuPool, timeout: Duration, } impl Service for Counter { type Request = CountRequest; type Response = CountResponse; type Error = io::Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let CountRequest(num) = req; println!("Request: {:?}", num); let timeout = Timer::default().sleep(self.timeout).then(|_| Err(())); let task = self.thread_pool .spawn_fn(move || Ok(count(num))) .select(timeout) .map(|(r, _)| r); Box::new( task.and_then(move |d| { println!("Response: Duration({:?},{:?})", num, &d); future::ok(CountResponse::Duration(num, d)) }).or_else(move |_| { println!("Response: Timeout({:?})", num); future::ok(CountResponse::Timeout(num)) }), ) } } fn count(max: u64) -> Duration { let now = Instant::now(); let mut i = 0; while i < max { i += 1; } now.elapsed() } fn serve(address: SocketAddr, pool: CpuPool, duration: Duration) { TcpServer::new(ServerProtocol, address).serve(move || { Ok(Counter { thread_pool: pool.clone(), timeout: duration, }) }); } fn main() { let args = Args::from_args(); let pool = if args.threads == 0 { CpuPool::new_num_cpus() } else { CpuPool::new(args.threads) }; let duration = Duration::from_secs(args.timeout as u64); let address = format!("0.0.0.0:{}", args.port).parse().unwrap(); println!( "Address: {:?}\nTimeout: {:?}\nThreads: {:?}", &address, args.timeout, if args.threads != 0 { args.threads.to_string() } else { "native".into() } ); serve(address, pool, duration); }
#![cfg_attr(feature="clippy", feature(plugin))] #![cfg_attr(feature="clippy", plugin(clippy))] #![deny(deprecated)] extern crate tokio_proto; extern crate tokio_io; extern crate tokio_service; extern crate tokio_timer; extern crate futures; extern crate futures_cpupool; extern crate bytes; extern crate bincode; extern crate structopt; #[macro_use] extern crate structopt_derive; extern crate serde; #[macro_use] extern crate serde_derive; mod protocol; use std::io; use std::net::SocketAddr; use std::time::{Duration, Instant}; use futures::{future, Future}; use futures_cpupool::CpuPool; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Framed, Encoder, Decoder}; use tokio_timer::Timer; use tokio_proto::TcpServer; use tokio_proto::multiplex::{RequestId, ServerProto}; use tokio_service::Service; use structopt::StructOpt; use bytes::{BytesMut, Buf, BufMut, BigEndian}; use protocol::{CountRequest, CountResponse}; #[derive(StructOpt, Debug)] #[structopt(name = "serv", about = "Server that counts")] struct Args { #[structopt(short = "p", long = "port", help = "Server's port", default_value = "5234")] port: u16, #[structopt(short = "t", long = "timeout", help = "Timeout per 1 task", default_value = "5")] timeout: usize, #[structopt(short = "j", long = "threads", help = "Number of threads", default_value = "0")] threads: usize, } struct ServerCodec; impl Decoder for ServerCodec { type Item = (RequestId, CountRequest); type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, io::Error> { if buf.len() >= 4 { let length = io::Cursor::new(&buf.split_to(4)).get_u32::<BigEndian>() as usize; if buf.len() >= length { return Ok(bincode::deserialize(&buf.split_to(length)).ok()); } } Ok(None) } } impl Encoder for ServerCodec { type Item = (RequestId, CountResponse); type Error = io::Error; fn encode(&mut self, item: Self::Item, buf: &mut BytesMut) -> io::Result<()> { let bytes = bincode::serialize(&item, bincode::Infinite).map_err(|_| { io::ErrorKind::InvalidData })?; let length = bytes.len(); buf.reserve(4 + length); buf.put_u32::<BigEndian>(length as u32); buf.put_slice(&bytes); Ok(()) } } struct ServerProtocol; impl<T: AsyncRead + AsyncWrite + 'static> ServerProto<T> for ServerProtocol { type Request = CountRequest; type Response = CountResponse; type Transport = Framed<T, ServerCodec>; type BindTransport = Result<Self::Transport, io::Error>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(io.framed(ServerCodec)) } } struct Counter { thread_pool: CpuPool, timeout: Duration, } impl Service for Counter { type Request = CountRequest; type Response = CountResponse; type Error = io::Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let CountRequest(num) = req; println!("Request: {:?}", num); let timeout = Timer::default().sleep(self.timeout).then(|_| Err(())); let task = self.thread_pool .spawn_fn(move || Ok(cou
} fn count(max: u64) -> Duration { let now = Instant::now(); let mut i = 0; while i < max { i += 1; } now.elapsed() } fn serve(address: SocketAddr, pool: CpuPool, duration: Duration) { TcpServer::new(ServerProtocol, address).serve(move || { Ok(Counter { thread_pool: pool.clone(), timeout: duration, }) }); } fn main() { let args = Args::from_args(); let pool = if args.threads == 0 { CpuPool::new_num_cpus() } else { CpuPool::new(args.threads) }; let duration = Duration::from_secs(args.timeout as u64); let address = format!("0.0.0.0:{}", args.port).parse().unwrap(); println!( "Address: {:?}\nTimeout: {:?}\nThreads: {:?}", &address, args.timeout, if args.threads != 0 { args.threads.to_string() } else { "native".into() } ); serve(address, pool, duration); }
nt(num))) .select(timeout) .map(|(r, _)| r); Box::new( task.and_then(move |d| { println!("Response: Duration({:?},{:?})", num, &d); future::ok(CountResponse::Duration(num, d)) }).or_else(move |_| { println!("Response: Timeout({:?})", num); future::ok(CountResponse::Timeout(num)) }), ) }
function_block-function_prefixed
[ { "content": "fn request_count(address: SocketAddr, range_max: usize, requests: usize) {\n\n let mut core = Core::new().unwrap();\n\n let handle = core.handle();\n\n\n\n let promises = (0..requests)\n\n .map(move |_| {\n\n TcpClient::new(ClientProtocol)\n\n .connect(&ad...
Rust
d3-core/src/scheduler/sched.rs
BruceBrown/d3
688ee218a994f3aab2fddc75feac308c58174333
use self::traits::*; use super::*; use crossbeam::channel::RecvTimeoutError; type MachineMap = super_slab::SuperSlab<ShareableMachine>; #[allow(dead_code)] #[allow(non_upper_case_globals)] pub static machine_count_estimate: AtomicCell<usize> = AtomicCell::new(5000); #[allow(dead_code)] pub fn get_machine_count_estimate() -> usize { machine_count_estimate.load() } #[allow(dead_code)] pub fn set_machine_count_estimate(new: usize) { machine_count_estimate.store(new); } #[allow(dead_code, non_upper_case_globals)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub static selector_maintenance_duration: AtomicCell<Duration> = AtomicCell::new(Duration::from_millis(500)); #[allow(dead_code, non_upper_case_globals, deprecated)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub fn get_selector_maintenance_duration() -> Duration { selector_maintenance_duration.load() } #[allow(dead_code, non_upper_case_globals, deprecated)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub fn set_selector_maintenance_duration(new: Duration) { selector_maintenance_duration.store(new); } #[allow(dead_code, non_upper_case_globals)] pub static live_machine_count: AtomicUsize = AtomicUsize::new(0); #[allow(dead_code, non_upper_case_globals)] pub fn get_machine_count() -> usize { live_machine_count.load(Ordering::SeqCst) } #[derive(Debug, Default, Copy, Clone)] pub struct SchedStats { pub maint_time: Duration, pub add_time: Duration, pub remove_time: Duration, pub total_time: Duration, } #[allow(dead_code)] pub struct DefaultScheduler { sender: SchedSender, wait_queue: SchedTaskInjector, thread: Option<thread::JoinHandle<()>>, } impl DefaultScheduler { fn stop(&self) { log::info!("stopping scheduler"); self.sender.send(SchedCmd::Stop).unwrap(); } pub fn new( sender: SchedSender, receiver: SchedReceiver, monitor: MonitorSender, queues: (ExecutorInjector, SchedTaskInjector), ) -> Self { live_machine_count.store(0, Ordering::SeqCst); let wait_queue = Arc::clone(&queues.1); let thread = SchedulerThread::spawn(receiver, monitor, queues); sender.send(SchedCmd::Start).unwrap(); Self { wait_queue, sender, thread, } } } impl Scheduler for DefaultScheduler { fn assign_machine(&self, machine: ShareableMachine) { self.sender.send(SchedCmd::New(machine)).unwrap(); } fn request_stats(&self) { self.sender.send(SchedCmd::RequestStats).unwrap(); } fn request_machine_info(&self) { self.sender.send(SchedCmd::RequestMachineInfo).unwrap(); } fn stop(&self) { self.stop(); } } impl Drop for DefaultScheduler { fn drop(&mut self) { if let Some(thread) = self.thread.take() { if self.sender.send(SchedCmd::Terminate(false)).is_err() {} log::info!("synchronizing Scheduler shutdown"); if thread.join().is_err() { log::trace!("failed to join Scheduler thread"); } } log::info!("Scheduler shutdown complete"); } } const MAX_SELECT_HANDLES: usize = usize::MAX - 16; #[allow(dead_code)] struct SchedulerThread { receiver: SchedReceiver, monitor: MonitorSender, wait_queue: SchedTaskInjector, run_queue: ExecutorInjector, is_running: bool, is_started: bool, machines: MachineMap, } impl SchedulerThread { fn spawn( receiver: SchedReceiver, monitor: MonitorSender, queues: (ExecutorInjector, SchedTaskInjector), ) -> Option<thread::JoinHandle<()>> { log::info!("Starting scheduler"); let thread = std::thread::spawn(move || { let mut sched_thread = Self { receiver, monitor, run_queue: queues.0, wait_queue: queues.1, is_running: true, is_started: false, machines: MachineMap::with_capacity(get_machine_count_estimate()), }; sched_thread.run(); }); Some(thread) } fn run(&mut self) { log::info!("running schdeuler"); let mut stats_timer = SimpleEventTimer::default(); let start = Instant::now(); let mut stats = SchedStats::default(); while self.is_running { if stats_timer.check() && self.monitor.send(MonitorMessage::SchedStats(stats)).is_err() { log::debug!("failed to send sched stats to mointor"); } match self.receiver.recv_timeout(stats_timer.remaining()) { Ok(cmd) => self.maintenance(cmd, &mut stats), Err(RecvTimeoutError::Timeout) => (), Err(RecvTimeoutError::Disconnected) => self.is_running = false, } } stats.total_time = start.elapsed(); log::info!("machines remaining: {}", self.machines.len()); for (_, m) in self.machines.iter() { log::info!( "machine={} key={} state={:#?} q_len={} task_id={} disconnected={}", m.get_id(), m.get_key(), m.get_state(), m.channel_len(), m.get_task_id(), m.is_disconnected() ); } log::info!("{:#?}", stats); log::info!("completed running schdeuler"); } fn maintenance(&mut self, cmd: SchedCmd, stats: &mut SchedStats) { let t = Instant::now(); match cmd { SchedCmd::Start => (), SchedCmd::Stop => self.is_running = false, SchedCmd::Terminate(_key) => (), SchedCmd::New(machine) => self.insert_machine(machine, stats), SchedCmd::SendComplete(key) => self.schedule_sendblock_machine(key), SchedCmd::Remove(key) => self.remove_machine(key, stats), SchedCmd::RecvBlock(key) => self.schedule_recvblock_machine(key), SchedCmd::RequestStats => if self.monitor.send(MonitorMessage::SchedStats(*stats)).is_err() {}, SchedCmd::RequestMachineInfo => self.send_machine_info(), _ => (), }; stats.maint_time += t.elapsed(); } fn insert_machine(&mut self, machine: ShareableMachine, stats: &mut SchedStats) { let t = Instant::now(); let entry = self.machines.vacant_entry(); log::trace!("inserted machine {} key={}", machine.get_id(), entry.key()); machine.key.store(entry.key(), Ordering::SeqCst); entry.insert(Arc::clone(&machine)); if let Err(state) = machine.compare_and_exchange_state(MachineState::New, MachineState::Ready) { log::error!("insert_machine: expected state New, found state {:#?}", state); } live_machine_count.fetch_add(1, Ordering::SeqCst); schedule_machine(machine, &self.run_queue); stats.add_time += t.elapsed(); } fn remove_machine(&mut self, key: usize, stats: &mut SchedStats) { let t = Instant::now(); if let Some(machine) = self.machines.get(key) { log::trace!( "removed machine {} key={} task={}", machine.get_id(), machine.get_key(), machine.get_task_id() ); } else { log::warn!("machine key {} not in collective", key); stats.remove_time += t.elapsed(); return; } self.machines.remove(key); live_machine_count.fetch_sub(1, Ordering::SeqCst); stats.remove_time += t.elapsed(); } fn send_machine_info(&self) { for (_, m) in &self.machines { if self.monitor.send(MonitorMessage::MachineInfo(Arc::clone(m))).is_err() { log::debug!("unable to send machine info to monitor"); } } } fn run_task(&self, machine: ShareableMachine) { if let Err(state) = machine.compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) { if state != MachineState::Ready { log::error!("sched run_task expected RecvBlock or Ready state{:#?}", state); } } schedule_machine(machine, &self.run_queue); } fn schedule_sendblock_machine(&self, key: usize) { let machine = self.machines.get(key).unwrap(); if let Err(state) = machine.compare_and_exchange_state(MachineState::SendBlock, MachineState::RecvBlock) { log::error!("sched: (SendBlock) expecting state SendBlock, found {:#?}", state); return; } if !machine.is_channel_empty() && machine .compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) .is_ok() { schedule_machine(Arc::clone(machine), &self.run_queue); } } fn schedule_recvblock_machine(&self, key: usize) { let machine = self.machines.get(key).unwrap(); if machine .compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) .is_ok() { schedule_machine(Arc::clone(machine), &self.run_queue); } } } #[cfg(test)] mod tests { use self::executor::SystemExecutorFactory; use self::machine::get_default_channel_capacity; use self::overwatch::SystemMonitorFactory; use self::sched_factory::create_sched_factory; use super::*; use crossbeam::deque; use d3_derive::*; use std::time::Duration; use self::channel::{receiver::Receiver, sender::Sender}; #[test] fn can_terminate() { let monitor_factory = SystemMonitorFactory::new(); let executor_factory = SystemExecutorFactory::new(); let scheduler_factory = create_sched_factory(); let scheduler = scheduler_factory.start(monitor_factory.get_sender(), executor_factory.get_queues()); thread::sleep(Duration::from_millis(100)); log::info!("stopping scheduler via control"); scheduler.stop(); thread::sleep(Duration::from_millis(100)); } #[derive(Debug, MachineImpl)] pub enum TestMessage { Test, } struct Alice {} impl Machine<TestMessage> for Alice { fn receive(&self, _message: TestMessage) {} } #[allow(clippy::type_complexity)] pub fn build_machine<T, P>( machine: T, ) -> ( Arc<T>, Sender<<<P as MachineImpl>::Adapter as MachineBuilder>::InstructionSet>, MachineAdapter, ) where T: 'static + Machine<P> + Machine<<<P as MachineImpl>::Adapter as MachineBuilder>::InstructionSet>, P: MachineImpl, <P as MachineImpl>::Adapter: MachineBuilder, { let channel_max = get_default_channel_capacity(); let (machine, sender, collective_adapter) = <<P as MachineImpl>::Adapter as MachineBuilder>::build_raw(machine, channel_max); (machine, sender, collective_adapter) } #[test] fn test_scheduler() { let (monitor_sender, _monitor_receiver) = crossbeam::channel::unbounded::<MonitorMessage>(); let (sched_sender, sched_receiver) = crossbeam::channel::unbounded::<SchedCmd>(); let run_queue = new_executor_injector(); let wait_queue = Arc::new(deque::Injector::<SchedTask>::new()); let thread = SchedulerThread::spawn(sched_receiver, monitor_sender, (run_queue, wait_queue)); std::thread::sleep(std::time::Duration::from_millis(10)); let mut senders: Vec<Sender<TestMessage>> = Vec::new(); let mut machines: Vec<Arc<Alice>> = Vec::new(); for _ in 1 ..= 5 { let alice = Alice {}; let (alice, mut sender, adapter) = build_machine(alice); let adapter = Arc::new(adapter); sender.bind(Arc::clone(&adapter)); senders.push(sender); machines.push(alice); sched_sender.send(SchedCmd::New(adapter)).unwrap(); } let s = &senders[2]; s.send(TestMessage::Test).unwrap(); std::thread::sleep(std::time::Duration::from_millis(500)); sched_sender.send(SchedCmd::Stop).unwrap(); if let Some(thread) = thread { thread.join().unwrap(); } } }
use self::traits::*; use super::*; use crossbeam::channel::RecvTimeoutError; type MachineMap = super_slab::SuperSlab<ShareableMachine>; #[allow(dead_code)] #[allow(non_upper_case_globals)] pub static machine_count_estimate: AtomicCell<usize> = AtomicCell::new(5000); #[allow(dead_code)] pub fn get_machine_count_estimate() -> usize { machine_count_estimate.load() } #[allow(dead_code)] pub fn set_machine_count_estimate(new: usize) { machine_count_estimate.store(new); } #[allow(dead_code, non_upper_case_globals)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub static selector_maintenance_duration: AtomicCell<Duration> = AtomicCell::new(Duration::from_millis(500)); #[allow(dead_code, non_upper_case_globals, deprecated)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub fn get_selector_maintenance_duration() -> Duration { selector_maintenance_duration.load() } #[allow(dead_code, non_upper_case_globals, deprecated)] #[deprecated(since = "0.1.2", note = "select is no longer used by the scheduler")] pub fn set_selector_maintenance_duration(new: Duration) { selector_maintenance_duration.store(new); } #[allow(dead_code, non_upper_case_globals)] pub static live_machine_count: AtomicUsize = AtomicUsize::new(0); #[allow(dead_code, non_upper_case_globals)] pub fn get_machine_count() -> usize { live_machine_count.load(Ordering::SeqCst) } #[derive(Debug, Default, Copy, Clone)] pub struct SchedStats { pub maint_time: Duration, pub add_time: Duration, pub remove_time: Duration, pub total_time: Duration, } #[allow(dead_code)] pub struct DefaultScheduler { sender: SchedSender, wait_queue: SchedTaskInjector, thread: Option<thread::JoinHandle<()>>, } impl DefaultScheduler { fn stop(&self) { log::info!("stopping scheduler"); self.sender.send(SchedCmd::Stop).unwrap(); } pub fn new( sender: SchedSender, receiver: SchedReceiver, monitor: MonitorSender, queues: (ExecutorInjector, SchedTaskInjector), ) -> Self { live_machine_count.store(0, Ordering::SeqCst); let wait_queue = Arc::clone(&queues.1); let thread = SchedulerThread::spawn(receiver, monitor, queues); sender.send(SchedCmd::Start).unwrap(); Self { wait_queue, sender, thread, } } } impl Scheduler for DefaultScheduler { fn assign_machine(&self, machine: ShareableMachine) { self.sender.send(SchedCmd::New(machine)).unwrap(); } fn request_stats(&self) { self.sender.send(SchedCmd::RequestStats).unwrap(); } fn request_machine_info(&self) { self.sender.send(SchedCmd::RequestMachineInfo).unwrap(); } fn stop(&self) { self.stop(); } } impl Drop for DefaultScheduler { fn drop(&mut self) { if let Some(thread) = self.thread.take() { if self.sender.send(SchedCmd::Terminate(false)).is_err() {} log::info!("synchronizing Scheduler shutdown"); if thread.join().is_err() { log::trace!("failed to join Scheduler thread"); } } log::info!("Scheduler shutdown complete"); } } const MAX_SELECT_HANDLES: usize = usize::MAX - 16; #[allow(dead_code)] struct SchedulerThread { receiver: SchedReceiver, monitor: MonitorSender, wait_queue: SchedTaskInjector, run_queue: ExecutorInjector, is_running: bool, is_started: bool, machines: MachineMap, } impl SchedulerThread { fn spawn( receiver: SchedReceiver, monitor: MonitorSender, queues: (ExecutorInjector, SchedTaskInjector), ) -> Option<thread::JoinHandle<()>> { log::info!("Starting scheduler"); let thread = std::thread::spawn(move || { let mut sched_thread = Self { receiver, monitor, run_queue: queues.0, wait_queue: queues.1, is_running: true, is_started: false, machines: MachineMap::with_capacity(get_machine_count_estimate()), }; sched_thread.run(); }); Some(thread) } fn run(&mut self) { log::info!("running schdeuler"); let mut stats_timer = SimpleEventTimer::default(); let start = Instant::now(); let mut stats = SchedStats::default(); while self.is_running { if stats_timer.check() && self.monitor.send(MonitorMessage::SchedStats(stats)).is_err() { log::debug!("failed to send sched stats to mointor"); } match self.receiver.recv_timeout(stats_timer.remaining()) { Ok(cmd) => self.maintenance(cmd, &mut stats), Err(RecvTimeoutError::Timeout) => (), Err(RecvTimeoutError::Disconnected) => self.is_running = false, } } stats.total_time = start.elapsed(); log::info!("machines remaining: {}", self.machines.len()); for (_, m) in self.machines.iter() { log::info!( "machine={} key={} state={:#?} q_len={} task_id={} disconnected={}", m.get_id(), m.get_key(), m.get_state(), m.channel_len(), m.get_task_id(), m.is_disconnected() ); } log::info!("{:#?}", stats); log::info!("completed running schdeuler"); } fn maintenance(&mut self, cmd: SchedCmd, stats: &mut SchedStats) { let t = Instant::now(); match cmd { SchedCmd::Start => (), SchedCmd::Stop => self.is_running = false, SchedCmd::Terminate(_key) => (), SchedCmd::New(machine) => self.insert_machine(machine, stats), SchedCmd::SendComplete(key) => self.schedule_sendblock_machine(key), SchedCmd::Remove(key) => self.remove_machine(key, stats), SchedCmd::RecvBlock(key) => self.schedule_recvblock_machine(key), SchedCmd::RequestStats => if self.monitor.send(MonitorMessage::SchedStats(*stats)).is_err() {}, SchedCmd::RequestMachineInfo => self.send_machine_info(), _ => (), }; stats.maint_time += t.elapsed(); } fn insert_machine(&mut self, machine: ShareableMachine, stats: &mut SchedStats) { let t = Instant::now(); let entry = self.machines.vacant_entry(); log::trace!("inserted machine {} key={}", machine.get_id(), entry.key()); machine.key.store(entry.key(), Ordering::SeqCst); entry.insert(Arc::clone(&machine)); if let Err(state) = machine.compare_and_exchange_state(MachineState::New, MachineState::Ready) { log::error!("insert_machine: expected state New, found state {:#?}", state); } live_machine_count.fetch_add(1, Ordering::SeqCst); schedule_machine(machine, &self.run_queue); stats.add_time += t.elapsed(); } fn remove_machine(&mut self, key: usize, stats: &mut SchedStats) { let t = Instant::now(); if let Some(machine) = self.machines.get(key) { log::trace!( "removed machine {} key={} task={}", machine.get_id(), machine.get_key(), machine.get_task_id() ); } else { log::warn!("machine key {} not in collective", key); stats.remove_time += t.elapsed(); return; } self.machines.remove(key); live_machine_count.fetch_sub(1, Ordering::SeqCst); stats.remove_time += t.elapsed(); } fn send_machine_info(&self) { for (_, m) in &self.machines { if self.monitor.send(MonitorMessage::MachineInfo(Arc::clone(m))).is_err() { log::debug!("unable to send machine info to monitor"); } } } fn run_task(&self, machine: ShareableMachine) { if let Err(state) = machine.compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) { if state != MachineState::Ready { log::error!("sched run_task expected RecvBlock or Ready state{:#?}", state); } } schedule_machine(machine, &self.run_queue); } fn schedule_sendblock_machine(&self, key: usize) { let machine = self.machines.get(key).unwrap(); if let Err(state) = machine.compare_and_exchange_state(MachineState::SendBlock, MachineState::RecvBlock) { log::error!("sched: (SendBlock) expecting state SendBlock, found {:#?}", state); return; } if !machine.is_channel_empty() && machine .compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) .is_ok() { schedule_machine(Arc::clone(machine), &self.run_queue); } } fn schedule_recvblock_machine(&self, key: usize) { let machine = self.machines.get(key).unwrap(); if machine .compare_and_exchange_state(MachineState::RecvBlock, MachineState::Ready) .is_ok() { schedule_machine(Arc::clone(machine), &self.run_queue); } } } #[cfg(test)] mod tests { use self::executor::SystemExecutorFactory; use self::machine::get_default_channel_capacity; use self::overwatch::SystemMonitorFactory; use self::sched_factory::create_sched_factory; use super::*; use crossbeam::deque; use d3_derive::*; use std::time::Duration; use self::channel::{receiver::Receiver, sender::Sender}; #[test] fn can_terminate() { let monitor_factory = SystemMonitorFactory::new(); let executor_factory = SystemExecutorFactory::new(); let scheduler_factory = create_sched_factory(); let scheduler = scheduler_factory.start(monitor_factory.get_sender(), executor_factory.get_queues()); thread::sleep(Duration::from_millis(100)); log::info!("stopping scheduler via control"); scheduler.stop(); thread::sleep(Duration::from_millis(100)); } #[derive(Debug, MachineImpl)] pub enum TestMessage { Test, } struct Alice {} impl Machine<TestMessage> for Alice { fn receive(&self, _message: TestMessage) {} } #[allow(clippy::type_complexity)] pub fn build_machine<T, P>( machine: T, ) -> ( Arc<T>, Sender<<<P as MachineImpl>::Adapter as MachineBuilder>::InstructionSet>, MachineAdapter, ) where T: 'static + Machine<P> + Machine<<<P as MachineImpl>::Adapter as MachineBuilder>::InstructionSet>, P: MachineImpl, <P as MachineImpl>::Adapter: MachineBuilder, { let channel_max = get_default_channel_capacity(); let (machine, sender, collective_adapter) = <<P as MachineImpl>::Adapter as MachineBuilder>::build_raw(machine, channel_max); (machine, sender, collective_adapter) } #[test] fn test_scheduler() { let (monitor_sender, _monitor_receiver) = crossbeam::channel::unbounded::<MonitorMessage>(); le
ter)); senders.push(sender); machines.push(alice); sched_sender.send(SchedCmd::New(adapter)).unwrap(); } let s = &senders[2]; s.send(TestMessage::Test).unwrap(); std::thread::sleep(std::time::Duration::from_millis(500)); sched_sender.send(SchedCmd::Stop).unwrap(); if let Some(thread) = thread { thread.join().unwrap(); } } }
t (sched_sender, sched_receiver) = crossbeam::channel::unbounded::<SchedCmd>(); let run_queue = new_executor_injector(); let wait_queue = Arc::new(deque::Injector::<SchedTask>::new()); let thread = SchedulerThread::spawn(sched_receiver, monitor_sender, (run_queue, wait_queue)); std::thread::sleep(std::time::Duration::from_millis(10)); let mut senders: Vec<Sender<TestMessage>> = Vec::new(); let mut machines: Vec<Arc<Alice>> = Vec::new(); for _ in 1 ..= 5 { let alice = Alice {}; let (alice, mut sender, adapter) = build_machine(alice); let adapter = Arc::new(adapter); sender.bind(Arc::clone(&adap
function_block-random_span
[ { "content": "type RecvCmdFn = Box<dyn Fn(&ShareableMachine, bool, Duration, &mut ExecutorStats) + Send + Sync + 'static>;\n\n\n\n#[derive(Debug)]\n\npub struct DefaultMachineDependentAdapter {}\n\nimpl MachineDependentAdapter for DefaultMachineDependentAdapter {\n\n fn receive_cmd(&self, _machine: &Shareabl...
Rust
src/main.rs
diodesign/rustinvaders
40d4f0adda37ecf4f851a65ff206954bbba812ac
/* Space invaders in Rust * * Game concept by Tomohiro Nishikado / Taito * Rust code By Chris Williams <diodesign@tuta.io> * * Written for fun. See LICENSE. * */ extern crate glfw; extern crate kiss3d; extern crate nalgebra as na; extern crate rand; use std::path::Path; use na::{ Point3, Point2 }; use kiss3d::window::Window; use kiss3d::event::{ Event, WindowEvent, Key, Action }; use kiss3d::light::Light; use kiss3d::camera::ArcBall; use kiss3d::text::Font; mod bullet; mod aliens; mod hero; mod collision; const MAX_SCORE: i32 = 9999999; /* seems like a cool number */ const MAX_LIVES: i32 = 99; /* also a cool number */ /* collect up the objects in the playfield */ struct Playfield { aliens: aliens::Aliens, /* squadron of enemy aliens to shoot down */ player: hero::Hero, /* our player hero */ } /* maintain state from level to level */ struct Game { score: i32, /* player's current points score */ lives: i32, /* player's current number of lives */ player_x_pos: f32, /* player's ship x-position (y and z are fixed) */ } enum LevelOutcome { Victory, /* player beat the level */ Died /* player ran out of lives */ } fn main() { let mut window = Window::new("Rust Invaders"); window.set_framerate_limit(Some(60)); window.set_light(Light::StickToCamera); /* notes: each of config_game, play_game, and game_over must delete all * scene objects before exiting. each function must track its own objects, * there is no automatic clean-up */ loop { /* render the opening screen + menu */ /* setup and play the game */ play_game(&mut window); /* render game over screen */ } } /* camera generate a standard camera view => distance = camera's z-axis distance from scene center */ fn camera(distance: f32) -> ArcBall { let eye = Point3::new(0.0, 0.0, distance); let at = Point3::origin(); return ArcBall::new(eye, at); } /* show a menu or at least give the player a chance to start */ fn config_game(mut window: &mut Window) { /* for now simply check the player is ready - difficulty settings and so on can be configured later: TODO */ fullscreen_message(window, "Welcome to Rust Invaders", 0.6, 0.6, 0.6); } /* show the bad news with white on red */ fn game_over(mut window: &mut Window) { fullscreen_message(window, "Game over :(", 0.4, 0.0, 0.0); } /* show end of level congratualtions with white */ fn congrats (mut window: &mut Window) { fullscreen_message(window, "Level complete :)", 0.0, 0.4, 0.0); } /* fullscreen_message render basic fullscreen text message with spinning black alien at the top. => window = graphics context text = message to display using white characters r, g, b = background color <= returns when space key is pressed */ fn fullscreen_message(mut window: &mut Window, text: &str, r: f32, g: f32, b: f32) { window.set_background_color(r, g, b); let font = Font::new(&Path::new("media/gameplay.ttf")).expect("Could not load font file"); let mut camera = camera(-100.0); let mut key_press = false; let x_start = 100.0 - (text.len() as f32 * 10.0 * 0.5); /* spawn single black rotating alien, fixed in place */ let mut alien = aliens::Alien::new(&mut window); alien.spawn(0.0, 10.0, 0.0, 0.0); alien.override_color(0.0, 0.0, 0.0); while window.render_with_camera(&mut camera) && key_press == false { window.draw_text(text, &Point2::new(x_start, 50.0), 64.0, &font, &Point3::new(1.0, 1.0, 1.0)); window.draw_text("Press space to continue", &Point2::new(50.0, 80.0), 64.0, &font, &Point3::new(0.9, 0.9, 0.9)); alien.animate(0.0); /* step = 0: don't move the alien */ for mut event in window.events().iter() { key_press = is_space_pressed(&mut event); if key_press == true { break; } } } /* destroy the alien immediately */ alien.delete(); } /* return true if the given event translates to a space keypress */ fn is_space_pressed(event: &mut Event) -> bool { match event.value { WindowEvent::Key(code, action, _) => match(code, action) { (Key::Space, Action::Press) => { return true; }, (_, _) => {} }, /* ignore mouse events */ WindowEvent::MouseButton(_, _, _) => event.inhibited = true, WindowEvent::Scroll(_, _, _) => event.inhibited = true, _ => {} /* pass on other events to the default handlers */ }; return false; } /* a game is a loop of levels until the player runs out of lives */ fn play_game(mut window: &mut Window) { /* set up the camera and black-background scene for the whole game */ window.set_background_color(0.0, 0.0, 0.0); let mut camera = camera(-250.0); /* these variables carry across from level to level */ let mut state = Game { score: 0, lives: 3, player_x_pos: 0.0, }; /* play level after level until player dies */ loop { match play_level(&mut window, &mut camera, &mut state) { LevelOutcome::Died => break, /* exit to game over screen */ LevelOutcome::Victory => congrats(&mut window) } } } /* play a level of the game * => window = graphics context * camera = viewing camera context * state = game state variables * <= LevelOutcome::PlayerDead if hero ran out of lives */ fn play_level(mut window: &mut Window, camera: &mut ArcBall, state: &mut Game) -> LevelOutcome { let font = Font::new(&Path::new("media/gameplay.ttf")).expect("Could not load font file"); /* create the baddies and hero for this level */ let mut playfield = Playfield { aliens: aliens::Aliens::new(&mut window), player: hero::Hero::new(&mut window, state.player_x_pos), }; let mut player_move_left = false; let mut player_move_right = false; let mut player_fire = false; /* rendering loop */ while window.render_with_camera(camera) { /* render the score line */ window.draw_text(format!("Score: {:07} Lives: {:02}", state.score, state.lives).as_str(), &Point2::new(10.0, 2.0), 64.0, &font, &Point3::new(1.0, 1.0, 1.0)); /* update aliens, player and any of their bullets / bombs in play */ playfield.aliens.animate(); playfield.player.animate(); /* check events for things like keypresses */ for mut event in window.events().iter() { match event.value { /* handle a keypress */ WindowEvent::Key(code, action, _) => { match (code, action) { (Key::Z, Action::Press) => player_move_left = true, (Key::Z, Action::Release) => player_move_left = false, (Key::X, Action::Press) => player_move_right = true, (Key::X, Action::Release) => player_move_right = false, (Key::Return, Action::Press) => player_fire = true, (Key::Return, Action::Release) => player_fire = false, (_, _) => {} } /* stop other keypresses going through to the default handler */ event.inhibited = true; }, /* ignore mouse events */ WindowEvent::MouseButton(_, _, _) => event.inhibited = true, WindowEvent::Scroll(_, _, _) => event.inhibited = true, _ => {} /* pass on other events to the default handlers */ } } /* stop playing the level if the player is alive and the aliens are all dead, or if we're * out of lives. this check means we keep animating enemy and ship explosions when * the player has shot all the aliens or has run out of lives, rather than bailing out * immediately */ if (playfield.player.state == hero::State::Alive && playfield.aliens.all_dead() == true) || (playfield.player.state != hero::State::Dying && state.lives < 1) { break; } /* only update the player if it's still alive, otherwise all sorts * of inconsistencies will occur (ship hit by a bomb or alien while dying etc) */ if playfield.player.state != hero::State::Alive { continue; /* skip movement, collision detection, etc while player is dead/dying */ } /* process results of events: if a movement key is held down then * continue moving in that direction */ match (player_move_left, player_move_right) { (true, false) => playfield.player.move_left(), (false, true) => playfield.player.move_right(), _ => {} } /* player can keep fire button held down, but we only allow one * hero bullet per playfield as per the original game */ if player_fire == true { playfield.player.fire(&mut window); /* needs window to create its bullet */ } playfield.aliens.fire(&mut window); /* aliens drop bombs as soon as they are able */ /* did the player's bullet hit an alien? */ if playfield.player.bullet.is_some() == true { let (x, y, _) = playfield.player.bullet.as_mut().unwrap().get_coords(); if playfield.aliens.collision(x, y) == collision::CollisionOutcome::Hit { /* the call to collision() removes the alien if there is a hit, but * we have to tell the ship's bullet to blow up too */ playfield.player.destroy_bullet(); state.score = state.score + aliens::ALIEN_POINTS; if state.score > MAX_SCORE { state.score = MAX_SCORE; } } /* remove bullet if it's gone out of bounds */ if y > aliens::ALIEN_Y_CEILING { playfield.player.destroy_bullet(); } } /* did an alien bomb hit the player? */ if playfield.aliens.bomb.is_some() == true { let (x, y, _) = playfield.aliens.bomb.as_mut().unwrap().get_coords(); if playfield.player.collision(x, y) == collision::CollisionOutcome::Hit { /* tell aliens to blow up their bomb, and the player its ship, if there is a hit */ playfield.aliens.destroy_bomb(); playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = state.lives - 1; } /* remove the bomb if it goes out of bounds */ if y < hero::HERO_Y_FLOOR { playfield.aliens.destroy_bomb(); } } /* get the player's x, y coords */ let (player_x_pos, player_y_pos, _) = playfield.player.get_coords(); /* did an alien fly into the player? */ if playfield.aliens.collision(player_x_pos, player_y_pos) == collision::CollisionOutcome::Hit { playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = state.lives - 1 } /* did the aliens manage to get below the player? if so, that's an instant * game over, I'm afraid */ if playfield.aliens.lowest_y() <= player_y_pos { playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = 0; } } /* we've exited the level loop. remove all objects from the playfield */ playfield.aliens.delete(); playfield.player.delete(); /* if we're still alive then we beat the level, otherwise we died */ if state.lives > 0 { return LevelOutcome::Victory } return LevelOutcome::Died }
/* Space invaders in Rust * * Game concept by Tomohiro Nishikado / Taito * Rust code By Chris Williams <diodesign@tuta.io> * * Written for fun. See LICENSE. * */ extern crate glfw; extern crate kiss3d; extern crate nalgebra as na; extern crate rand; use std::path::Path; use na::{ Point3, Point2 }; use kiss3d::window::Window; use kiss3d::event::{ Event, WindowEvent, Key, Action }; use kiss3d::light::Light; use kiss3d::camera::ArcBall; use kiss3d::text::Font; mod bullet; mod aliens; mod hero; mod collision; const MAX_SCORE: i32 = 9999999; /* seems like a cool number */ const MAX_LIVES: i32 = 99; /* also a cool number */ /* collect up the objects in the playfield */ struct Playfield { aliens: aliens::Aliens, /* squadron of enemy aliens to shoot down */ player: hero::Hero, /* our player hero */ } /* maintain state from level to level */ struct Game { score: i32, /* player's current points score */ lives: i32, /* player's current number of lives */ player_x_pos: f32, /* player's ship x-position (y and z are fixed) */ } enum LevelOutcome { Victory, /* player beat the level */ Died /* player ran out of lives */ } fn main() { let mut window = Window::new("Rust Invaders"); window.set_framerate_limit(Some(60)); window.set_light(Light::StickToCamera); /* notes: each of config_game, play_game, and game_over must delete all * scene objects before exiting. each function must track its own objects, * there is no automatic clean-up */ loop { /* render the opening screen + menu */ /* setup and play the game */ play_game(&mut window); /* render game over screen */ } } /* camera generate a standard camera view => distance = camera's z-axis distance from scene center */ fn camera(distance: f32) -> ArcBall { let eye = Point3::new(0.0, 0.0, distance); let at = Point3::origin(); return ArcBall::new(eye, at); } /* show a menu or at least give the player a chance to start */ fn config_game(mut window: &mut Window) { /* for now simply check the player is ready - difficulty settings and so on can be configured later: TODO */ fullscreen_message(window, "Welcome to Rust Invaders", 0.6, 0.6, 0.6); } /* show the bad news with white on red */ fn game_over(mut window: &mut Window) { fullscreen_message(window, "Game over :(", 0.4, 0.0, 0.0); } /* show end of level congratualtions with white */ fn congrats (mut window: &mut Window) { fullscreen_message(window, "Level complete :)", 0.0, 0.4, 0.0); } /* fullscreen_message render basic fullscreen text message with spinning black alien at the top. => window = graphics context text = message to display using white characters r, g, b = background color <= returns when space key is pressed */ fn fullscreen_message(mut window: &mut Window, text: &str, r: f32, g: f32, b: f32) { window.set_background_color(r, g, b); let font = Font::new(&Path::new("media/gameplay.ttf")).expect("Could not load font file"); let mut camera = camera(-100.0); let mut key_press = false; let x_start = 100.0 - (text.len() as f32 * 10.0 * 0.5); /* spawn single black rotating alien, fixed in place */ let mut alien = aliens::Alien::new(&mut window); alien.spawn(0.0, 10.0, 0.0, 0.0); alien.override_color(0.0, 0.0, 0.0); while window.render_with_camera(&mut camera) && key_press == false { window.draw_text(text, &Point2::new(x_start, 50.0), 64.0, &font, &Point3::new(1.0, 1.0, 1.0)); window.draw_text("Press space to continue", &Point2::new(50.0, 80.0), 64.0, &font, &Point3::new(0.9, 0.9, 0.9)); alien.animate(0.0); /* step = 0: don't move the alien */ for mut event in window.events().iter() { key_press = is_space_pressed(&mut event); if key_press == true { break; } } } /* destroy the alien immediately */ alien.delete(); } /* return true if the given event translates to a space keypress */ fn is_space_pressed(event: &mut Event) -> bool { match event.value { WindowEvent::Key(code, action, _) => match(code, action) { (Key::Space, Action::Press) => { return true; }, (_, _) => {} }, /* ignore mouse events */ WindowEvent::MouseButton(_, _, _) => event.inhibited = true, WindowEvent::Scroll(_, _, _) => event.inhibited = true, _ => {} /* pass on other events to the default handlers */ }; return false; } /* a game is a loop of levels until the player runs out of lives */ fn play_game(mut window: &mut Window) { /* set up the camera and black-background scene for the whole game */ window.set_background_color(0.0, 0.0, 0.0); let mut camera = camera(-250.0); /* these variables carry across from level to level */ let mut state = Game { score: 0, lives: 3, player_x_pos: 0.0, }; /* play level after level until player dies */ loop { match play_level(&mut window, &mut camera, &mut state) { LevelOutcome::Died => break, /* exit to game over screen */ LevelOutcome::Victory => congrats(&mut window) } } } /* play a level of the game * => window = graphics context * camera = viewing camera context * state = game state variables * <= LevelOutcome::PlayerDead if hero ran out of lives */ fn play_level(mut window: &mut Window, camera: &mut ArcBall, state: &mut Game) -> LevelOutcome { let font = Font::new(&Path::new("media/gameplay.ttf")).expect("Could not load font file"); /* create the baddies and hero for this level */ let mut playfield = Playfield { aliens: aliens::Aliens::new(&mut window), player: hero::Hero::new(&mut window, state.player_x_pos), }; let mut player_move_left = false; let mut player_move_right = false; let mut player_fire = false; /* rendering loop */ while window.render_with_camera(camera) { /* render the score line */ window.draw_text(format!("Score: {:07} Lives: {:02}", state.score, state.lives).as_str(), &Point2::new(10.0, 2.0), 64.0, &font, &Point3::new(1.0, 1.0, 1.0)); /* update aliens, player and any of their bullets / bombs in play */ playfield.aliens.animate(); playfield.player.animate(); /* check events for things like keypresses */ for mut event in window.events().iter() { match event.value { /* handle a keypress */ WindowEvent::Key(code, action, _) => { match (code, action) { (Key::Z, Action::Press) => player_move_left = true, (Key::Z, Action::Release) => player_move_left = false, (Key::X, Action::Press) => player_move_right = true, (Key::X, Action::Release) => player_move_right = false, (Key::Return, Action::Press) => player_fire = true, (Key::Return, Action::Release) => player_fire = false, (_, _) => {} } /* stop other keypresses going through to the default handler */ event.inhibited = true; }, /* ignore mouse events */ WindowEvent::MouseButton(_, _, _) => event.inhibited = true, WindowEvent::Scroll(_, _, _) => event.inhibited = true, _ => {} /* pass on other events to the default handlers */ } } /* stop playing the level if the player is alive and the aliens are all dead, or if we're * out of lives. this check means we keep animating enemy and ship explosions when * the player has shot all the aliens or has run out of lives, rather than bailing out * immediately */ if (playfield.player.state == hero::State::Alive && playfield.aliens.all_dead() == true) || (playfield.player.state != hero::State::Dying && state.lives < 1) { break; } /* only update the player if it's still alive, otherwise all sorts * of inconsistencies will occur (ship hit by a bomb or alien while dying etc) */ if playfield.player.state != hero::State::Alive { continue; /* skip movement, collision detection, etc while player is dead/dying */ } /* process results of events: if a movement key is held down then * continue moving in that direction */ match (player_move_left, player_move_right) { (true, false) => playfield.player.move_left(), (false, true) => playfield.player.move_right(), _ => {} } /* player can keep fire button held down, but we only allow one * hero bullet per playfield as per the original game */ if player_fire == true { playfield.player.fire(&mut window); /* needs window to create its bullet */ } playfield.aliens.fire(&mut window); /* aliens drop bombs as soon as they are able */ /* did the player's bullet hit an alien? */ if playfield.player.bullet.is_some() == true { let (x, y, _) = playfield.player.bullet.as_mut().unwrap().get_coords(); if playfield.aliens.collision(x, y) == collision::CollisionOutcome::Hit { /* the call to collision() removes the alien if there is a hit, but * we have to tell the ship's bullet to blow up too */ playfield.player.destroy_bullet(); state.score = state.score + aliens::ALIEN_POINTS; if state.score > MAX_SCORE { state.score = MAX_SCORE; } } /* remove bullet if it's gone out of bounds */ if y > aliens::ALIEN_Y_CEILING { playfield.player.destroy_bullet(); } } /* did an alien bomb hit the player? */ if playfield.aliens.bomb.is_some() == true { let (x, y, _) = playfield.aliens.bomb.as_mut().unwrap().get_coords(); if playfield.player.collision(x, y) == collision::CollisionOutcome::Hit { /* tell aliens to blow up their bomb, and the player its ship, if there is a hit */ playfield.aliens.destroy_bomb(); playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = state.lives - 1; } /* remove the bomb if it goes out of bounds */ if y < hero::HERO_Y_FLOOR { playfield.aliens.destroy_bomb(); } }
(player_x_pos, player_y_pos) == collision::CollisionOutcome::Hit { playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = state.lives - 1 } /* did the aliens manage to get below the player? if so, that's an instant * game over, I'm afraid */ if playfield.aliens.lowest_y() <= player_y_pos { playfield.player.destroy(&mut window); /* window needed to add explosion debris to game world */ state.lives = 0; } } /* we've exited the level loop. remove all objects from the playfield */ playfield.aliens.delete(); playfield.player.delete(); /* if we're still alive then we beat the level, otherwise we died */ if state.lives > 0 { return LevelOutcome::Victory } return LevelOutcome::Died }
/* get the player's x, y coords */ let (player_x_pos, player_y_pos, _) = playfield.player.get_coords(); /* did an alien fly into the player? */ if playfield.aliens.collision
random
[ { "content": "#[derive(PartialEq)]\n\nenum State\n\n{\n\n Alive,\n\n Dying,\n\n Dead\n\n}\n\n\n\n/* aliens are either shuffling left, right, or down and then right, or down then left */\n\npub enum Movement\n\n{\n\n Left, /* moving left */\n\n Right, /* moving right */\n\n DownRight, /* ...
Rust
src/lib.rs
tekjar/rumqtt-coroutines
10212a4f10c697a0ad23217257039e6045ca9029
#![feature(proc_macro, conservative_impl_trait, generators)] extern crate futures_await as futures; extern crate tokio_core; extern crate tokio_io; extern crate tokio_timer; extern crate mqtt3; extern crate bytes; #[macro_use] extern crate log; mod codec; mod packet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::io::{self, ErrorKind}; use std::error::Error; use std::time::Duration; use std::thread; use codec::MqttCodec; use futures::prelude::*; use futures::stream::{Stream, SplitSink}; use futures::sync::mpsc::{self, Sender, Receiver}; use std::sync::mpsc as stdmpsc; use tokio_core::reactor::Core; use tokio_core::net::TcpStream; use tokio_timer::Timer; use tokio_io::AsyncRead; use tokio_io::codec::Framed; use mqtt3::*; #[derive(Debug)] pub enum NetworkRequest { Subscribe(Vec<(TopicPath, QoS)>), Publish(Publish), Ping, } pub fn start(new_commands_tx: stdmpsc::Sender<Sender<NetworkRequest>>) { loop { let new_commands_tx = new_commands_tx.clone(); let mut reactor = Core::new().unwrap(); let handle = reactor.handle(); let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1883); let (commands_tx, commands_rx) = mpsc::channel::<NetworkRequest>(1000); let ping_commands_tx = commands_tx.clone(); let client = async_block! { thread::sleep(Duration::new(5, 0)); let stream = await!(TcpStream::connect(&address, &handle))?; let connect = packet::gen_connect_packet("rumqtt-coro", 10, true, None, None); let framed = stream.framed(MqttCodec); let framed = await!(framed.send(connect)).unwrap(); new_commands_tx.send(commands_tx).unwrap(); let (sender, receiver) = framed.split(); handle.spawn(ping_timer(ping_commands_tx).then(|result| { match result { Ok(_) => println!("Ping timer done"), Err(e) => println!("Ping timer IO error {:?}", e), } Ok(()) })); handle.spawn(command_read(commands_rx, sender).then(|result| { match result { Ok(_) => println!("Command receiver done"), Err(e) => println!("Command IO error {:?}", e), } Ok(()) })); #[async] for msg in receiver { println!("message = {:?}", msg); } println!("Done with network receiver !!"); Ok::<(), io::Error>(()) }; let _response = reactor.run(client); println!("{:?}", _response); } } #[async] fn ping_timer(mut commands_tx: Sender<NetworkRequest>) -> io::Result<()> { let timer = Timer::default(); let keep_alive = 10; let interval = timer.interval(Duration::new(keep_alive, 0)); #[async] for _t in interval { println!("Ping timer fire"); commands_tx = await!( commands_tx.send(NetworkRequest::Ping).or_else(|e| { Err(io::Error::new(ErrorKind::Other, e.description())) }) )?; } Ok(()) } #[async] fn command_read(commands_rx: Receiver<NetworkRequest>, mut sender: SplitSink<Framed<TcpStream, MqttCodec>>) -> io::Result<()> { let commands_rx = commands_rx.or_else(|_| { Err(io::Error::new(ErrorKind::Other, "Rx Error")) }); #[async] for command in commands_rx { println!("command = {:?}", command); let packet = match command { NetworkRequest::Publish(publish) => { Packet::Publish(publish) } NetworkRequest::Ping => { packet::gen_pingreq_packet() } _ => unimplemented!() }; sender = await!(sender.send(packet))? } Ok(()) }
#![feature(proc_macro, conservative_impl_trait, generators)] extern crate futures_await as futures; extern crate tokio_core; extern crate tokio_io; extern crate tokio_timer; extern crate mqtt3; extern crate bytes; #[macro_use] extern crate log; mod codec; mod packet; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::io::{self, ErrorKind}; use std::error::Error; use std::time::Duration; use std::thread; use codec::MqttCodec; use futures::prelude::*; use futures::stream::{Stream, SplitSink}; use futures::sync::mpsc::{self, Sender, Receiver}; use std::sync::mpsc as stdmpsc; use tokio_core::reactor::Core; use tokio_core::net::TcpStream; use tokio_timer::Timer; use tokio_io::AsyncRead; use tokio_io::codec::Framed; use mqtt3::*; #[derive(Debug)] pub enum NetworkRequest { Subscribe(Vec<(TopicPath, QoS)>), Publish(Publish), Ping, } pub fn start(new_commands_tx: stdmpsc::Sender<Sender<NetworkRequest>>) { loop { let new_commands_tx = new_commands_tx.clone(); let mut reactor = Core::new().unwrap(); let handle = react
#[async] fn ping_timer(mut commands_tx: Sender<NetworkRequest>) -> io::Result<()> { let timer = Timer::default(); let keep_alive = 10; let interval = timer.interval(Duration::new(keep_alive, 0)); #[async] for _t in interval { println!("Ping timer fire"); commands_tx = await!( commands_tx.send(NetworkRequest::Ping).or_else(|e| { Err(io::Error::new(ErrorKind::Other, e.description())) }) )?; } Ok(()) } #[async] fn command_read(commands_rx: Receiver<NetworkRequest>, mut sender: SplitSink<Framed<TcpStream, MqttCodec>>) -> io::Result<()> { let commands_rx = commands_rx.or_else(|_| { Err(io::Error::new(ErrorKind::Other, "Rx Error")) }); #[async] for command in commands_rx { println!("command = {:?}", command); let packet = match command { NetworkRequest::Publish(publish) => { Packet::Publish(publish) } NetworkRequest::Ping => { packet::gen_pingreq_packet() } _ => unimplemented!() }; sender = await!(sender.send(packet))? } Ok(()) }
or.handle(); let address = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 1883); let (commands_tx, commands_rx) = mpsc::channel::<NetworkRequest>(1000); let ping_commands_tx = commands_tx.clone(); let client = async_block! { thread::sleep(Duration::new(5, 0)); let stream = await!(TcpStream::connect(&address, &handle))?; let connect = packet::gen_connect_packet("rumqtt-coro", 10, true, None, None); let framed = stream.framed(MqttCodec); let framed = await!(framed.send(connect)).unwrap(); new_commands_tx.send(commands_tx).unwrap(); let (sender, receiver) = framed.split(); handle.spawn(ping_timer(ping_commands_tx).then(|result| { match result { Ok(_) => println!("Ping timer done"), Err(e) => println!("Ping timer IO error {:?}", e), } Ok(()) })); handle.spawn(command_read(commands_rx, sender).then(|result| { match result { Ok(_) => println!("Command receiver done"), Err(e) => println!("Command IO error {:?}", e), } Ok(()) })); #[async] for msg in receiver { println!("message = {:?}", msg); } println!("Done with network receiver !!"); Ok::<(), io::Error>(()) }; let _response = reactor.run(client); println!("{:?}", _response); } }
function_block-function_prefixed
[ { "content": "pub fn gen_pingreq_packet() -> Packet {\n\n Packet::Pingreq\n\n}\n\n\n\n// pub fn gen_pingresp_packet() -> Packet {\n\n// Packet::Pingresp\n\n// }\n\n\n\n// pub fn gen_subscribe_packet(pkid: PacketIdentifier, topics: Vec<SubscribeTopic>) -> Packet {\n\n// Packet::Subscribe(Subscribe {\n...
Rust
src/parser_combinator.rs
KoheiAsano/sym_diff
17cdb5972825b9aa1c0662da5499020f53c94cf6
use super::expr::Env; pub type ParseResult<'a, Output> = Result<(&'a str, &'a Env, Output), &'a str>; pub trait Parser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output>; fn map<F, NewOutput>(self, map_fn: F) -> BoxedParser<'a, NewOutput> where Self: Sized + 'a, Output: 'a, NewOutput: 'a, F: Fn(Output) -> NewOutput + 'a, { BoxedParser::new(map(self, map_fn)) } fn pred<F>(self, pred_fn: F) -> BoxedParser<'a, Output> where Self: Sized + 'a, Output: 'a, F: Fn(&Output) -> bool + 'a, { BoxedParser::new(pred(self, pred_fn)) } fn and_then<F, NextParser, NewOutput>(self, f: F) -> BoxedParser<'a, NewOutput> where Self: Sized + 'a, Output: 'a, NewOutput: 'a, NextParser: Parser<'a, NewOutput> + 'a, F: Fn(Output) -> NextParser + 'a, { BoxedParser::new(and_then(self, f)) } } pub struct BoxedParser<'a, Output> { parser: Box<dyn Parser<'a, Output> + 'a>, } impl<'a, Output> BoxedParser<'a, Output> { fn new<P>(parser: P) -> Self where P: Parser<'a, Output> + 'a, { BoxedParser { parser: Box::new(parser), } } } impl<'a, Output> Parser<'a, Output> for BoxedParser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output> { self.parser.parse(input, env) } } impl<'a, F, Output> Parser<'a, Output> for F where F: Fn(&'a str, &'a Env) -> ParseResult<'a, Output>, { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output> { self(input, env) } } pub fn identifier<'a>(input: &'a str, env: &'a Env) -> ParseResult<'a, (String, &'a Env)> { let mut matched = String::new(); let mut chars = input.chars(); match chars.next() { Some(next) if next.is_alphabetic() => matched.push(next), _ => return Err(input), } while let Some(next) = chars.next() { if next.is_alphanumeric() || next == '-' { matched.push(next); } else { break; } } let next_index = matched.len(); Ok((&input[next_index..], env, (matched, env))) } pub fn any_char<'a>(input: &'a str, env: &'a Env) -> ParseResult<'a, (char, &'a Env)> { match input.chars().next() { Some(next) => Ok((&input[next.len_utf8()..], env, (next, env))), _ => Err(input), } } pub fn match_literal<'a>(expected: &'static str) -> impl Parser<'a, ()> { move |input: &'a str, env: &'a Env| match input.get(0..expected.len()) { Some(next) if next == expected => Ok((&input[expected.len()..], env, ())), _ => Err(input), } } pub fn one_of<'a>(expected: Vec<&'static str>) -> impl Parser<'a, &'static str> { move |input: &'a str, env: &'a Env| { for &e in expected.iter() { match input.get(0..e.len()) { Some(next) if next == e => return Ok((&input[e.len()..], env, e)), _ => continue, } } Err(input) } } pub fn whitespace_char<'a>() -> impl Parser<'a, (char, &'a Env)> { pred(any_char, |c| c.0.is_whitespace()) } pub fn space1<'a>() -> impl Parser<'a, Vec<(char, &'a Env)>> { one_or_more(whitespace_char()) } pub fn space0<'a>() -> impl Parser<'a, Vec<(char, &'a Env)>> { zero_or_more(whitespace_char()) } pub fn map<'a, P, F, A, B>(parser: P, map_fn: F) -> impl Parser<'a, B> where P: Parser<'a, A>, F: Fn(A) -> B, { move |input, env| { parser .parse(input, env) .map(|(next_input, next_env, result)| (next_input, next_env, map_fn(result))) } } pub fn pair<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, (R1, R2)> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { move |input, env| { parser1 .parse(input, env) .and_then(|(next_input, next_env, result1)| { parser2 .parse(next_input, next_env) .map(|(last_input, last_env, result2)| { (last_input, last_env, (result1, result2)) }) }) } } pub fn left<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, R1> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { map(pair(parser1, parser2), |(left, _right)| left) } pub fn right<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, R2> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { map(pair(parser1, parser2), |(_left, right)| right) } pub fn zero_or_one<'a, P, A>(parser: P) -> impl Parser<'a, Option<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = None; if let Ok((next_input, next_env, item)) = parser.parse(input, env) { env = next_env; input = next_input; result = Some(item); } Ok((input, env, result)) } } pub fn one_or_more<'a, P, A>(parser: P) -> impl Parser<'a, Vec<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = Vec::new(); if let Ok((next_input, new_env, first_item)) = parser.parse(input, env) { env = new_env; input = next_input; result.push(first_item); } else { return Err(input); } while let Ok((next_input, new_env, first_item)) = parser.parse(input, env) { env = new_env; input = next_input; result.push(first_item); } Ok((input, env, result)) } } pub fn zero_or_more<'a, P, A>(parser: P) -> impl Parser<'a, Vec<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = Vec::new(); while let Ok((next_input, next_env, first_item)) = parser.parse(input, env) { env = next_env; input = next_input; result.push(first_item); } Ok((input, env, result)) } } pub fn pred<'a, P, A, F>(parser: P, predicate: F) -> impl Parser<'a, A> where P: Parser<'a, A>, F: Fn(&A) -> bool, { move |input, env| { if let Ok((next_input, next_env, value)) = parser.parse(input, env) { if predicate(&value) { return Ok((next_input, next_env, value)); } } Err(input) } } pub fn either<'a, P1, P2, A>(parser1: P1, parser2: P2) -> impl Parser<'a, A> where P1: Parser<'a, A>, P2: Parser<'a, A>, { move |input, env| match parser1.parse(input, env) { ok @ Ok(_) => ok, Err(_) => parser2.parse(input, env), } } pub fn and_then<'a, P, F, A, B, NextP>(parser: P, f: F) -> impl Parser<'a, B> where P: Parser<'a, A>, NextP: Parser<'a, B>, F: Fn(A) -> NextP, { move |input, env| match parser.parse(input, env) { Ok((next_input, next_env, result)) => f(result).parse(next_input, next_env), Err(err) => Err(err), } } pub fn whitespace_wrap<'a, P, A>(parser: P) -> impl Parser<'a, A> where P: Parser<'a, A>, { right(space0(), left(parser, space0())) }
use super::expr::Env; pub type ParseResult<'a, Output> = Result<(&'a str, &'a Env, Output), &'a str>; pub trait Parser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output>; fn map<F, NewOutput>(self, map_fn: F) -> BoxedParser<'a, NewOutput> where Self: Sized + 'a, Output: 'a, NewOutput: 'a, F: Fn(Output) -> NewOutput + 'a, { BoxedParser::new(map(self, map_fn)) } fn pred<F>(self, pred_fn: F) -> BoxedParser<'a, Output> where Self: Sized + 'a, Output: 'a, F: Fn(&Output) -> bool + 'a, { BoxedParser::new(pred(self, pred_fn)) } fn and_then<F, NextParser, NewOutput>(self, f: F) -> BoxedParser<'a, NewOutput> where Self: Sized + 'a, Output: 'a, NewOutput: 'a, NextParser: Parser<'a, NewOutput> + 'a, F: Fn(Output) -> NextParser + 'a, { BoxedParser::new(and_then(self, f)) } } pub struct BoxedParser<'a, Output> { parser: Box<dyn Parser<'a, Output> + 'a>, } impl<'a, Output> BoxedParser<'a, Output> { fn new<P>(parser: P) -> Self where P: Parser<'a, Output> + 'a, { BoxedParser { parser: Box::new(parser), } } } impl<'a, Output> Parser<'a, Output> for BoxedParser<'a, Output> { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output> { self.parser.parse(input, env) } } impl<'a, F, Output> Parser<'a, Output> for F where F: Fn(&'a str, &'a Env) -> ParseResult<'a, Output>, { fn parse(&self, input: &'a str, env: &'a Env) -> ParseResult<'a, Output> { self(input, env) } } pub fn identifier<'a>(input: &'a str, env: &'a Env) -> ParseResult<'a, (String, &'a Env)> { let mut matched = String::new(); let mut chars = input.chars(); match chars.next() { Some(next) if next.is_alphabetic() => matched.push(next), _ => return Err(input), } while let Some(next) = chars.next() { if next.is_alphanumeric() || next == '-' { matched.push(next); } else { break; } } let next_index = matched.len(); Ok((&input[next_index..], env, (matched, env))) } pub fn any_char<'a>(input: &'a str, env: &'a Env) -> ParseResult<'a, (char, &'a Env)> { match input.chars().next() { Some(next) => Ok((&input[next.len_utf8()..], env, (next, env))), _ => Err(input), } } pub fn match_literal<'a>(expected: &'static str) -> impl Parser<'a, ()> { move |input: &'a str, env: &'a Env| match input.get(0..expected.len()) { Some(next) if next == expected => Ok((&input[expected.len()..], env, ())), _ => Err(input), } } pub fn one_of<'a>(expected: Vec<&'static str>) -> impl Parser<'a, &'static str> { move |input: &'a str, env: &'a Env| { for &e in expected.iter() { match input.get(0..e.len()) { Some(next) if next == e => return Ok((&input[e.len()..], env, e)), _ => continue, } } Err(input) } } pub fn whitespace_char<'a>() -> impl Parser<'a, (char, &'a Env)> { pred(any_char, |c| c.0.is_whitespace()) } pub fn space1<'a>() -> impl Parser<'a, Vec<(char, &'a Env)>> { one_or_more(whitespace_char()) } pub fn space0<'a>() -> impl Parser<'a, Vec<(char, &'a Env)>> { zero_or_more(whitespace_char()) } pub fn map<'a, P, F, A, B>(parser: P, map_fn: F)
ext_input, next_env, result1)| { parser2 .parse(next_input, next_env) .map(|(last_input, last_env, result2)| { (last_input, last_env, (result1, result2)) }) }) } } pub fn left<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, R1> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { map(pair(parser1, parser2), |(left, _right)| left) } pub fn right<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, R2> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { map(pair(parser1, parser2), |(_left, right)| right) } pub fn zero_or_one<'a, P, A>(parser: P) -> impl Parser<'a, Option<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = None; if let Ok((next_input, next_env, item)) = parser.parse(input, env) { env = next_env; input = next_input; result = Some(item); } Ok((input, env, result)) } } pub fn one_or_more<'a, P, A>(parser: P) -> impl Parser<'a, Vec<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = Vec::new(); if let Ok((next_input, new_env, first_item)) = parser.parse(input, env) { env = new_env; input = next_input; result.push(first_item); } else { return Err(input); } while let Ok((next_input, new_env, first_item)) = parser.parse(input, env) { env = new_env; input = next_input; result.push(first_item); } Ok((input, env, result)) } } pub fn zero_or_more<'a, P, A>(parser: P) -> impl Parser<'a, Vec<A>> where P: Parser<'a, A>, { move |mut input, mut env| { let mut result = Vec::new(); while let Ok((next_input, next_env, first_item)) = parser.parse(input, env) { env = next_env; input = next_input; result.push(first_item); } Ok((input, env, result)) } } pub fn pred<'a, P, A, F>(parser: P, predicate: F) -> impl Parser<'a, A> where P: Parser<'a, A>, F: Fn(&A) -> bool, { move |input, env| { if let Ok((next_input, next_env, value)) = parser.parse(input, env) { if predicate(&value) { return Ok((next_input, next_env, value)); } } Err(input) } } pub fn either<'a, P1, P2, A>(parser1: P1, parser2: P2) -> impl Parser<'a, A> where P1: Parser<'a, A>, P2: Parser<'a, A>, { move |input, env| match parser1.parse(input, env) { ok @ Ok(_) => ok, Err(_) => parser2.parse(input, env), } } pub fn and_then<'a, P, F, A, B, NextP>(parser: P, f: F) -> impl Parser<'a, B> where P: Parser<'a, A>, NextP: Parser<'a, B>, F: Fn(A) -> NextP, { move |input, env| match parser.parse(input, env) { Ok((next_input, next_env, result)) => f(result).parse(next_input, next_env), Err(err) => Err(err), } } pub fn whitespace_wrap<'a, P, A>(parser: P) -> impl Parser<'a, A> where P: Parser<'a, A>, { right(space0(), left(parser, space0())) }
-> impl Parser<'a, B> where P: Parser<'a, A>, F: Fn(A) -> B, { move |input, env| { parser .parse(input, env) .map(|(next_input, next_env, result)| (next_input, next_env, map_fn(result))) } } pub fn pair<'a, P1, P2, R1, R2>(parser1: P1, parser2: P2) -> impl Parser<'a, (R1, R2)> where P1: Parser<'a, R1>, P2: Parser<'a, R2>, { move |input, env| { parser1 .parse(input, env) .and_then(|(n
random
[ { "content": "pub fn expr<'a>() -> impl Parser<'a, (Rc<Expr>, &'a Env)> {\n\n whitespace_wrap(term()).and_then(|(one, env)| {\n\n zero_or_more(whitespace_wrap(pair(\n\n whitespace_wrap(any_char.pred(|(c, _e)| *c == '+' || *c == '-')),\n\n term(),\n\n )))\n\n .map(mo...
Rust
src/message.rs
gridgentoo/rust-rdkafka
fcb0bab41894e96208fd745e79ce7f73e4bcebbe
use rdsys; use rdsys::types::*; use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::slice; use std::str; use consumer::{Consumer, ConsumerContext}; #[derive(Debug,PartialEq,Eq,Clone,Copy)] pub enum Timestamp { NotAvailable, CreateTime(i64), LogAppendTime(i64) } impl Timestamp { pub fn to_millis(&self) -> Option<i64> { match *self { Timestamp::NotAvailable => None, Timestamp::CreateTime(-1) | Timestamp::LogAppendTime(-1) => None, Timestamp::CreateTime(t) | Timestamp::LogAppendTime(t) => Some(t), } } } pub trait Message { fn key(&self) -> Option<&[u8]>; fn payload(&self) -> Option<&[u8]>; fn topic(&self) -> &str; fn partition(&self) -> i32; fn offset(&self) -> i64; fn timestamp(&self) -> Timestamp; fn payload_view<P: ?Sized + FromBytes>(&self) -> Option<Result<&P, P::Error>> { self.payload().map(P::from_bytes) } fn key_view<K: ?Sized + FromBytes>(&self) -> Option<Result<&K, K::Error>> { self.key().map(K::from_bytes) } } pub struct BorrowedMessage<'a> { ptr: *mut RDKafkaMessage, _p: PhantomData<&'a u8>, } impl<'a> fmt::Debug for BorrowedMessage<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Message {{ ptr: {:?} }}", self.ptr()) } } impl<'a> BorrowedMessage<'a> { pub fn new<C, X>(ptr: *mut RDKafkaMessage, _consumer: &'a C) -> BorrowedMessage<'a> where X: ConsumerContext, C: Consumer<X> { BorrowedMessage { ptr: ptr, _p: PhantomData, } } pub fn ptr(&self) -> *mut RDKafkaMessage { self.ptr } pub fn topic_ptr(&self) -> *mut RDKafkaTopic { unsafe { (*self.ptr).rkt } } pub fn key_len(&self) -> usize { unsafe { (*self.ptr).key_len } } pub fn payload_len(&self) -> usize { unsafe { (*self.ptr).len } } pub fn detach(&self) -> OwnedMessage { OwnedMessage { key: self.key().map(|k| k.to_vec()), payload: self.payload().map(|p| p.to_vec()), topic: self.topic().to_owned(), timestamp: self.timestamp(), partition: self.partition(), offset: self.offset(), } } } impl<'a> Message for BorrowedMessage<'a> { fn key(&self) -> Option<&[u8]> { unsafe { if (*self.ptr).key.is_null() { None } else { Some(slice::from_raw_parts::<u8>((*self.ptr).key as *const u8, (*self.ptr).key_len)) } } } fn payload(&self) -> Option<&[u8]> { unsafe { if (*self.ptr).payload.is_null() { None } else { Some(slice::from_raw_parts::<u8>((*self.ptr).payload as *const u8, (*self.ptr).len)) } } } fn topic(&self) -> &str { unsafe { CStr::from_ptr(rdsys::rd_kafka_topic_name((*self.ptr).rkt)) .to_str() .expect("Topic name is not valid UTF-8") } } fn partition(&self) -> i32 { unsafe { (*self.ptr).partition } } fn offset(&self) -> i64 { unsafe { (*self.ptr).offset } } fn timestamp(&self) -> Timestamp { let mut timestamp_type = rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_NOT_AVAILABLE; let timestamp = unsafe { rdsys::rd_kafka_message_timestamp( self.ptr, &mut timestamp_type ) }; match timestamp_type { rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_NOT_AVAILABLE => Timestamp::NotAvailable, rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_CREATE_TIME => Timestamp::CreateTime(timestamp), rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_LOG_APPEND_TIME => Timestamp::LogAppendTime(timestamp) } } } impl<'a> Drop for BorrowedMessage<'a> { fn drop(&mut self) { trace!("Destroying message {:?}", self); unsafe { rdsys::rd_kafka_message_destroy(self.ptr) }; } } pub struct OwnedMessage { payload: Option<Vec<u8>>, key: Option<Vec<u8>>, topic: String, timestamp: Timestamp, partition: i32, offset: i64 } impl OwnedMessage { pub fn new( payload: Option<Vec<u8>>, key: Option<Vec<u8>>, topic: String, timestamp: Timestamp, partition: i32, offset: i64 ) -> OwnedMessage { OwnedMessage { payload: payload, key: key, topic: topic, timestamp: timestamp, partition: partition, offset: offset } } } impl Message for OwnedMessage { fn key(&self) -> Option<&[u8]> { match self.key { Some(ref k) => Some(k.as_slice()), None => None, } } fn payload(&self) -> Option<&[u8]> { match self.payload { Some(ref p) => Some(p.as_slice()), None => None, } } fn topic(&self) -> &str { self.topic.as_ref() } fn partition(&self) -> i32 { self.partition } fn offset(&self) -> i64 { self.offset } fn timestamp(&self) -> Timestamp { self.timestamp } } pub trait FromBytes { type Error; fn from_bytes(&[u8]) -> Result<&Self, Self::Error>; } impl FromBytes for [u8] { type Error = (); fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error> { Ok(bytes) } } impl FromBytes for str { type Error = str::Utf8Error; fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error> { str::from_utf8(bytes) } } pub trait ToBytes { fn to_bytes(&self) -> &[u8]; } impl ToBytes for [u8] { fn to_bytes(&self) -> &[u8] { self } } impl ToBytes for str { fn to_bytes(&self) -> &[u8] { self.as_bytes() } } impl ToBytes for Vec<u8> { fn to_bytes(&self) -> &[u8] { self.as_slice() } } impl ToBytes for String { fn to_bytes(&self) -> &[u8] { self.as_bytes() } } impl<'a, T: ToBytes> ToBytes for &'a T { fn to_bytes(&self) -> &[u8] { (*self).to_bytes() } } impl ToBytes for () { fn to_bytes(&self) -> &[u8] { &[] } }
use rdsys; use rdsys::types::*; use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::slice; use std::str; use consumer::{Consumer, ConsumerContext}; #[derive(Debug,PartialEq,Eq,Clone,Copy)] pub enum Timestamp { NotAvailable, CreateTime(i64), LogAppendTime(i64) } impl Timestamp { pub fn to_millis(&self) -> Option<i64> { match *self { Timestamp::NotAvailable => None, Timestamp::CreateTime(-1) | Timestamp::LogAppendTime(-1) => None, Timestamp::CreateTime(t) | Timestamp::LogAppendTime(t) => Some(t), } } } pub trait Message { fn key(&self) -> Option<&[u8]>; fn payload(&self) -> Option<&[u8]>; fn topic(&self) -> &str; fn partition(&self) -> i32; fn offset(&self) -> i64; fn timestamp(&self) -> Timestamp; fn payload_view<P: ?Sized + FromBytes>(&self) -> Option<Result<&P, P::Error>> { self.payload().map(P::from_bytes) } fn key_view<K: ?Sized + FromBytes>(&self) -> Option<Result<&K, K::Error>> { self.key().map(K::from_bytes) } } pub stru
one } else { Some(slice::from_raw_parts::<u8>((*self.ptr).payload as *const u8, (*self.ptr).len)) } } } fn topic(&self) -> &str { unsafe { CStr::from_ptr(rdsys::rd_kafka_topic_name((*self.ptr).rkt)) .to_str() .expect("Topic name is not valid UTF-8") } } fn partition(&self) -> i32 { unsafe { (*self.ptr).partition } } fn offset(&self) -> i64 { unsafe { (*self.ptr).offset } } fn timestamp(&self) -> Timestamp { let mut timestamp_type = rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_NOT_AVAILABLE; let timestamp = unsafe { rdsys::rd_kafka_message_timestamp( self.ptr, &mut timestamp_type ) }; match timestamp_type { rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_NOT_AVAILABLE => Timestamp::NotAvailable, rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_CREATE_TIME => Timestamp::CreateTime(timestamp), rdsys::rd_kafka_timestamp_type_t::RD_KAFKA_TIMESTAMP_LOG_APPEND_TIME => Timestamp::LogAppendTime(timestamp) } } } impl<'a> Drop for BorrowedMessage<'a> { fn drop(&mut self) { trace!("Destroying message {:?}", self); unsafe { rdsys::rd_kafka_message_destroy(self.ptr) }; } } pub struct OwnedMessage { payload: Option<Vec<u8>>, key: Option<Vec<u8>>, topic: String, timestamp: Timestamp, partition: i32, offset: i64 } impl OwnedMessage { pub fn new( payload: Option<Vec<u8>>, key: Option<Vec<u8>>, topic: String, timestamp: Timestamp, partition: i32, offset: i64 ) -> OwnedMessage { OwnedMessage { payload: payload, key: key, topic: topic, timestamp: timestamp, partition: partition, offset: offset } } } impl Message for OwnedMessage { fn key(&self) -> Option<&[u8]> { match self.key { Some(ref k) => Some(k.as_slice()), None => None, } } fn payload(&self) -> Option<&[u8]> { match self.payload { Some(ref p) => Some(p.as_slice()), None => None, } } fn topic(&self) -> &str { self.topic.as_ref() } fn partition(&self) -> i32 { self.partition } fn offset(&self) -> i64 { self.offset } fn timestamp(&self) -> Timestamp { self.timestamp } } pub trait FromBytes { type Error; fn from_bytes(&[u8]) -> Result<&Self, Self::Error>; } impl FromBytes for [u8] { type Error = (); fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error> { Ok(bytes) } } impl FromBytes for str { type Error = str::Utf8Error; fn from_bytes(bytes: &[u8]) -> Result<&Self, Self::Error> { str::from_utf8(bytes) } } pub trait ToBytes { fn to_bytes(&self) -> &[u8]; } impl ToBytes for [u8] { fn to_bytes(&self) -> &[u8] { self } } impl ToBytes for str { fn to_bytes(&self) -> &[u8] { self.as_bytes() } } impl ToBytes for Vec<u8> { fn to_bytes(&self) -> &[u8] { self.as_slice() } } impl ToBytes for String { fn to_bytes(&self) -> &[u8] { self.as_bytes() } } impl<'a, T: ToBytes> ToBytes for &'a T { fn to_bytes(&self) -> &[u8] { (*self).to_bytes() } } impl ToBytes for () { fn to_bytes(&self) -> &[u8] { &[] } }
ct BorrowedMessage<'a> { ptr: *mut RDKafkaMessage, _p: PhantomData<&'a u8>, } impl<'a> fmt::Debug for BorrowedMessage<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Message {{ ptr: {:?} }}", self.ptr()) } } impl<'a> BorrowedMessage<'a> { pub fn new<C, X>(ptr: *mut RDKafkaMessage, _consumer: &'a C) -> BorrowedMessage<'a> where X: ConsumerContext, C: Consumer<X> { BorrowedMessage { ptr: ptr, _p: PhantomData, } } pub fn ptr(&self) -> *mut RDKafkaMessage { self.ptr } pub fn topic_ptr(&self) -> *mut RDKafkaTopic { unsafe { (*self.ptr).rkt } } pub fn key_len(&self) -> usize { unsafe { (*self.ptr).key_len } } pub fn payload_len(&self) -> usize { unsafe { (*self.ptr).len } } pub fn detach(&self) -> OwnedMessage { OwnedMessage { key: self.key().map(|k| k.to_vec()), payload: self.payload().map(|p| p.to_vec()), topic: self.topic().to_owned(), timestamp: self.timestamp(), partition: self.partition(), offset: self.offset(), } } } impl<'a> Message for BorrowedMessage<'a> { fn key(&self) -> Option<&[u8]> { unsafe { if (*self.ptr).key.is_null() { None } else { Some(slice::from_raw_parts::<u8>((*self.ptr).key as *const u8, (*self.ptr).key_len)) } } } fn payload(&self) -> Option<&[u8]> { unsafe { if (*self.ptr).payload.is_null() { N
random
[ { "content": "pub fn value_fn(id: i32) -> String {\n\n format!(\"Message {}\", id)\n\n}\n\n\n", "file_path": "tests/test_utils.rs", "rank": 3, "score": 121805.88676946462 }, { "content": "pub fn key_fn(id: i32) -> String {\n\n format!(\"Key {}\", id)\n\n}\n", "file_path": "tests/te...
Rust
src/libnet/src/http2/error.rs
Veil-Project/Veil-Rust
bd32fb781a9fe6f22aede1bb7cd0aa227b820939
use std::error; use std::fmt; use std::io; use std::result; use super::hpack; pub type Result<T> = result::Result<T, Error>; #[derive(Debug, Clone, Copy)] pub enum ProtocolErrorKind { None = 0x0, Protocol = 0x1, Internal = 0x2, FlowControl = 0x3, SettingsTimeout = 0x4, StreamClosed = 0x5, FrameSize = 0x6, RefusedStream = 0x7, Cancel = 0x8, Compression = 0x9, Connect = 0xA, EnhanceYourCalm = 0xB, InadequateSecurity = 0xC, Http11Required = 0xD, Unknown = 0xE, } impl ProtocolErrorKind { pub fn from_code(code: isize) -> Self { use ProtocolErrorKind::*; match code { 0x0 => None, 0x1 => Protocol, 0x2 => Internal, 0x3 => FlowControl, 0x4 => SettingsTimeout, 0x5 => StreamClosed, 0x6 => FrameSize, 0x7 => RefusedStream, 0x8 => Cancel, 0x9 => Compression, 0xA => Connect, 0xB => EnhanceYourCalm, 0xC => InadequateSecurity, 0xD => Http11Required, 0xE => Unknown, _ => Unknown, } } pub(crate) fn as_code(&self) -> isize { *self as isize } pub(crate) fn as_id_str(&self) -> &str { use ProtocolErrorKind::*; match self { None => "NO_ERROR", Protocol => "PROTOCOL_ERROR", Internal => "INTERNAL_ERROR", FlowControl => "FLOW_CONTROL_ERROR", SettingsTimeout => "SETTINGS_TIMEOUT", StreamClosed => "STREAM_CLOSED", FrameSize => "FRAME_SIZE_ERROR", RefusedStream => "REFUSED_STREAM", Cancel => "CANCEL", Compression => "COMPRESSION_ERROR", Connect => "CONNECT_ERROR", EnhanceYourCalm => "ENHANCE_YOUR_CALM", InadequateSecurity => "INADEQUATE_SECURITY", Http11Required => "HTTP_1_1_REQUIRED", Unknown => "INTERNAL_ERROR", } } pub(crate) fn as_str(&self) -> &str { use ProtocolErrorKind::*; match self { None => "condition is not a result of an error", Protocol => "detected an unspecific protocol error", Internal => "encountered an unexpected internal error", FlowControl => "detected that its peer violated the flow-control protocol", SettingsTimeout => "sent a SETTINGS frame but did not receive a response in a timely manner", StreamClosed => "received a frame after a stream was half-closed", FrameSize => "received a frame with an invalid size", RefusedStream => "refused the stream prior to performing any application processing", Cancel => "indicates that the stream is no longer needed", Compression => "unable to maintain the header compression context for the connection", Connect => "connection established in response to a CONNECT request was reset or abnormally closed", EnhanceYourCalm => "detected that its peer is exhibiting a behavior that might be generating excessive load", InadequateSecurity => "underlying transport has properties that do not meet minimum security requirements", Http11Required => "requires that HTTP/1.1 be used instead of HTTP/2", Unknown => "encountered an unexpected error code", } } } impl fmt::Display for ProtocolErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}: {}", self.as_id_str(), self.as_str()) } } #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum ErrorKind { InvalidSetting(String), DataLength, } impl ErrorKind { pub(crate) fn as_str(&self) -> &str { use ErrorKind::*; match *self { InvalidSetting(ref e) => e, DataLength => "Data length is too long or too short", } } } pub enum Repr { Io(io::Error), Protocol(ProtocolErrorKind), Simple(ErrorKind), Hpack(hpack::ErrorKind), } impl fmt::Debug for Repr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Repr::*; match self { Io(ref e) => e.fmt(f), Protocol(kind) => f .debug_struct("Protocol") .field("code", &kind.as_code()) .field("id", &kind.as_id_str()) .field("description", &kind.as_str()) .finish(), Simple(kind) => f.debug_tuple("Kind").field(&kind).finish(), Hpack(kind) => f.debug_tuple("HpackKind").field(&kind).finish(), } } } pub struct Error(Box<Repr>); impl Error { pub fn new(kind: Repr) -> Error { Error(Box::new(kind)) } pub fn from_raw_protocol_error(code: isize) -> Error { Error(Box::new(Repr::Protocol(ProtocolErrorKind::from_code(code)))) } pub fn raw_protocol_error(&self) -> Option<isize> { use Repr::*; match *self.0 { Io(..) => None, Protocol(i) => Some(i as isize), } } pub fn kind(&self) -> &Repr { &self.0 } } impl From<ProtocolErrorKind> for Error { fn from(kind: ProtocolErrorKind) -> Self { Error::new(Repr::Protocol(kind)) } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Error::new(Repr::Simple(kind)) } } impl From<hpack::ErrorKind> for Error { fn from(kind: hpack::ErrorKind) -> Self { Error::new(Repr::Hpack(kind)) } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Repr::*; match *self.0 { Io(ref e) => e.fmt(f), Protocol(kind) => write!(f, "{}: {}", kind.as_id_str(), kind.as_str()), Simple(kind) => kind.fmt(f), Hpack(kind) => kind.fmt(f), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Repr::*; match *self.0 { Io(ref e) => e.fmt(f), Protocol(kind) => write!(f, "{}", kind.as_str()), Simple(kind) => write!(f, "{}", kind.as_str()), Hpack(kind) => write!(f, "{}", kind.as_str()), } } } impl error::Error for Error { fn description(&self) -> &str { use Repr::*; match *self.0 { Io(e) => e.description(), Protocol(kind) => kind.as_str(), Simple(kind) => kind.as_str(), Hpack(kind) => kind.as_str(), } } fn source(&self) -> Option<&(dyn error::Error + 'static)> { use Repr::*; match *self.0 { Io(e) => e.source(), Protocol(..) => None, Simple(..) => None, } } } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Self::new(Repr::Io(e)) } }
use std::error; use std::fmt; use std::io; use std::result; use super::hpack; pub type Result<T> = result::Result<T, Error>; #[derive(Debug, Clone, Copy)] pub enum ProtocolErrorKind { None = 0x0, Protocol = 0x1, Internal = 0x2, FlowControl = 0x3, SettingsTimeout = 0x4, StreamClosed = 0x5, FrameSize = 0x6, RefusedStream = 0x7, Cancel = 0x8, Compression = 0x9, Connect = 0xA, EnhanceYourCalm = 0xB, InadequateSecurity = 0xC, Http11Required = 0xD, Unknown = 0xE, } impl ProtocolErrorKind { pub fn from_code(code: isize) -> Self { use ProtocolErrorKind::*; match code { 0x0 => None, 0x1 => Protocol, 0x2 => Internal, 0x3 => FlowControl, 0x4 => SettingsTimeout, 0x5 => StreamClosed, 0x6 => FrameSize, 0x7 => RefusedStream, 0x8 => Cancel, 0x9 => Compression, 0xA => Connect, 0xB => EnhanceYourCalm, 0xC => InadequateSecurity, 0xD => Http11Required, 0xE => Unknown, _ => Unknown, } } pub(crate) fn as_code(&self) -> isize { *self as isize } pub(crate) fn as_id_str(&self) -> &str { use ProtocolErrorKind::*; match self { None => "NO_ERROR", Protocol => "PROTOCOL_ERROR", Internal => "INTERNAL_ERROR", FlowControl => "FLOW_CONTROL_ERROR", SettingsTimeout => "SETTINGS_TIMEOUT", StreamClosed => "STREAM_CLOSED", FrameSize => "FRAME_SIZE_ERROR", RefusedStream => "REFUSED_STREAM", Cancel => "CANCEL", Compression => "COMPRESSION_ERROR", Connect => "CONNECT_ERROR", EnhanceYourCalm => "ENHANCE_YOUR_CALM", InadequateSecurity => "INADEQUATE_SECURITY", Http11Required => "HTTP_1_1_REQUIRED", Unknown => "INTERNAL_ERROR", } } pub(crate) fn as_str(&self) -> &str { use ProtocolErrorKind::*; match self { None => "condition is not a result of an error", Protocol => "detected an unspecific protocol error", Internal => "encountered an unexpected internal error", FlowControl => "detected that its peer violated the flow-control protocol", SettingsTimeout => "sent a SETTINGS frame but did not receive a response in a timely manner", StreamClosed => "received a frame after a stream was half-closed", FrameSize => "received a frame with an invalid size", RefusedStream => "refused the stream prior to performing any application processing", Cancel => "indicates that the stream is no longer needed", Compression => "unable to maintain the header compression context for the connection", Connect => "connection established in response to a CONNECT request was reset or abnormally closed", EnhanceYourCalm => "detected that its peer is exhibiting a behavior that might be generating excessive load", InadequateSecurity => "underlying transport has properties that do not meet minimum security requirements", Http11Required => "requires that HTTP/1.1 be used instead of HTTP/2", Unknown => "encountered an unexpected error code", } } } impl fmt::Display for ProtocolErrorKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}: {}", self.as_id_str(), self.as_str()) } } #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub enum ErrorKind { InvalidSetting(String), DataLength, } impl ErrorKind { pub(crate) fn as_str(&self) -> &str { use ErrorKind::*; match *self { InvalidSetting(ref e) => e, DataLength => "Data length is too long or too short", } } } pub enum Repr { Io(io::Error), Protocol(ProtocolErrorKind), Simple(ErrorKind), Hpack(hpack::ErrorKind), } impl fmt::Debug for Repr {
} pub struct Error(Box<Repr>); impl Error { pub fn new(kind: Repr) -> Error { Error(Box::new(kind)) } pub fn from_raw_protocol_error(code: isize) -> Error { Error(Box::new(Repr::Protocol(ProtocolErrorKind::from_code(code)))) } pub fn raw_protocol_error(&self) -> Option<isize> { use Repr::*; match *self.0 { Io(..) => None, Protocol(i) => Some(i as isize), } } pub fn kind(&self) -> &Repr { &self.0 } } impl From<ProtocolErrorKind> for Error { fn from(kind: ProtocolErrorKind) -> Self { Error::new(Repr::Protocol(kind)) } } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Self { Error::new(Repr::Simple(kind)) } } impl From<hpack::ErrorKind> for Error { fn from(kind: hpack::ErrorKind) -> Self { Error::new(Repr::Hpack(kind)) } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Repr::*; match *self.0 { Io(ref e) => e.fmt(f), Protocol(kind) => write!(f, "{}: {}", kind.as_id_str(), kind.as_str()), Simple(kind) => kind.fmt(f), Hpack(kind) => kind.fmt(f), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::Repr::*; match *self.0 { Io(ref e) => e.fmt(f), Protocol(kind) => write!(f, "{}", kind.as_str()), Simple(kind) => write!(f, "{}", kind.as_str()), Hpack(kind) => write!(f, "{}", kind.as_str()), } } } impl error::Error for Error { fn description(&self) -> &str { use Repr::*; match *self.0 { Io(e) => e.description(), Protocol(kind) => kind.as_str(), Simple(kind) => kind.as_str(), Hpack(kind) => kind.as_str(), } } fn source(&self) -> Option<&(dyn error::Error + 'static)> { use Repr::*; match *self.0 { Io(e) => e.source(), Protocol(..) => None, Simple(..) => None, } } } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Self::new(Repr::Io(e)) } }
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Repr::*; match self { Io(ref e) => e.fmt(f), Protocol(kind) => f .debug_struct("Protocol") .field("code", &kind.as_code()) .field("id", &kind.as_id_str()) .field("description", &kind.as_str()) .finish(), Simple(kind) => f.debug_tuple("Kind").field(&kind).finish(), Hpack(kind) => f.debug_tuple("HpackKind").field(&kind).finish(), } }
function_block-full_function
[]
Rust
kernel/src/arch/x86_64/memory/address_space_manager.rs
aeleos/VeOS
4c766539ac10ad7b044bcf1b49fd5f0ae8fc21c6
use super::paging::inactive_page_table::InactivePageTable; use super::paging::page_table_entry::*; use super::paging::page_table_manager::PageTableManager; use super::paging::{convert_flags, Page, PageFrame, CURRENT_PAGE_TABLE}; use super::PAGE_SIZE; use super::{ KERNEL_STACK_AREA_BASE, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_OFFSET, USER_STACK_AREA_BASE, USER_STACK_MAX_SIZE, USER_STACK_OFFSET, }; use core::ptr; use crate::memory::{ address_space_manager, Address, AddressSpace, PageFlags, PhysicalAddress, VirtualAddress, }; use crate::multitasking::stack::AccessType; use crate::multitasking::{Stack, ThreadID}; pub struct AddressSpaceManager { table: InactivePageTable, } impl address_space_manager::AddressSpaceManager for AddressSpaceManager { fn new() -> AddressSpaceManager { AddressSpaceManager { table: InactivePageTable::copy_from_current(), } } fn idle() -> AddressSpaceManager { AddressSpaceManager { table: InactivePageTable::from_current_table(), } } fn write_to(&mut self, buffer: &[u8], address: VirtualAddress, flags: PageFlags) { let flags = convert_flags(flags); let start_page_num = address.page_num(); let end_page_num = (address + buffer.len() - 1).page_num() + 1; let mut current_offset = address.offset_in_page(); let mut current_buffer_position = 0; for page_num in start_page_num..end_page_num { let page_address = VirtualAddress::from_page_num(page_num); self.table.change_permissions_or_map( Page::from_address(page_address), PageTableEntryFlags::WRITABLE, ); let mut entry = self.table.get_entry_and_map(page_address); let physical_address = entry .points_to() .expect("The just mapped page isn't mapped."); let (new_current_buffer_position, new_current_offset) = CURRENT_PAGE_TABLE .lock() .with_temporary_page(PageFrame::from_address(physical_address), |page| { let start_address = page.get_address() + current_offset; let write_length = if (PAGE_SIZE - current_offset) >= buffer.len() - current_buffer_position { buffer.len() - current_buffer_position } else { PAGE_SIZE - current_offset }; unsafe { ptr::copy_nonoverlapping( buffer.as_ptr(), start_address.as_mut_ptr(), write_length, ); } ( current_buffer_position + write_length, (current_offset + write_length) % PAGE_SIZE, ) }); current_offset = new_current_offset; current_buffer_position = new_current_buffer_position; entry.set_flags(flags); } self.table.unmap(); } unsafe fn get_page_table_address(&self) -> PhysicalAddress { self.table.get_frame().get_address() } fn map_page(&mut self, page_address: VirtualAddress, flags: PageFlags) { let flags = convert_flags(flags); self.table.map_page(Page::from_address(page_address), flags); self.table.unmap(); } unsafe fn unmap_page(&mut self, start_address: VirtualAddress) { self.table.unmap_page(Page::from_address(start_address)); self.table.unmap(); } unsafe fn unmap_page_unchecked(&mut self, start_address: VirtualAddress) { self.table .unmap_page_unchecked(Page::from_address(start_address)); self.table.unmap(); } fn create_kernel_stack(id: ThreadID, address_space: &mut AddressSpace) -> Stack { let tid: usize = id.into(); Stack::new( 0x4000, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_AREA_BASE + KERNEL_STACK_OFFSET * tid, AccessType::KernelOnly, Some(address_space), ) } fn create_user_stack(id: ThreadID, address_space: &mut AddressSpace) -> Stack { let tid: usize = id.into(); Stack::new( 0x2000, USER_STACK_MAX_SIZE, USER_STACK_AREA_BASE + USER_STACK_OFFSET * tid, AccessType::UserAccessible, Some(address_space), ) } fn create_idle_stack(cpu_id: usize) -> Stack { Stack::new( 0x3000, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_AREA_BASE + KERNEL_STACK_OFFSET * cpu_id, AccessType::KernelOnly, None, ) } }
use super::paging::inactive_page_table::InactivePageTable; use super::paging::page_table_entry::*; use super::paging::page_table_manager::PageTableManager; use super::paging::{convert_flags, Page, PageFrame, CURRENT_PAGE_TABLE}; use super::PAGE_SIZE; use super::{ KERNEL_STACK_AREA_BASE, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_OFFSET, USER_STACK_AREA_BASE, USER_STACK_MAX_SIZE, USER_STACK_OFFSET, }; use core::ptr; use crate::memory::{ address_space_manager, Address, AddressSpace, PageFlags, PhysicalAddress, VirtualAddress, }; use crate::multitasking::stack::AccessType; use crate::multitasking::{Stack, ThreadID}; pub struct AddressSpaceManager { table: InactivePageTable, } impl address_space_manager::AddressSpaceManager for AddressSpaceManager { fn new() -> AddressSpaceManager { AddressSpaceManager { table: InactivePageTable::copy_from_current(), } } fn idle() -> AddressSpaceManager { AddressSpaceManager { table: InactivePageTable::from_current_table(), } } fn write_to(&mut self, buffer: &[u8], address: VirtualAddress, flags: PageFlags) { let flags = convert_flags(flags); let start_page_num = address.page_num(); let end_page_num = (address + buffer.len() - 1).page_num() + 1; let mut current_offset = address.offset_in_page(); let mut current_buffer_position = 0; for page_num in start_page_num..end_page_num { let page_address = VirtualAddress::from_page_num(page_num); self.table.change_permissions_or_map( Page::from_address(page_address), PageTableEntryFlags::WRITABLE, ); let mut entry = self.table.get_entry_and_map(page_address); let physical_address = entry .points_to() .expect("The just mapped page isn't mapped."); let (new_current_buffer_position, new_current_offset) = CURRENT_PAGE_TABLE .lock() .with_temporary_page(PageFrame::from_address(physical_address), |page| { let start_address = page.get_address() + current_offset; let write_length = if (PAGE_SIZE - current_offset) >= buffer.len() - current_buffer_position { buffer.len() - current_buffer_position } else { PAGE_SIZE - current_offset }; unsafe { ptr::copy_nonoverlapping( buffer.as_ptr(), start_address.as_mut_ptr(), write_length, ); } ( current_buffer_position + write_length, (current_offset + write_length) % PAGE_SIZE, ) }); current_offset = new_current_offset; current_buffer_position = new_current_buffer_position; entry.set_flags(flags); } self.table.unmap(); } unsafe fn get_page_table_address(&self) -> PhysicalAddress { self.table.get_frame().get_address() } fn map_page(&mut self, page_address: VirtualAddress, flags: PageFlags) { let flags = convert_flags(flags); self.table.map_page(Page::from_address(page_address), flags); self.table.unmap(); } unsafe fn unmap_page(&mut self, start_address: VirtualAddress) { self.table.unmap_page(Page::from_address(start_address)); self.table.unmap(); } unsafe fn unmap_page_unchecked(&mut self, start_address: VirtualAddress) { self.table .unmap_page_unchecked(Page::from_address(start_address)); self.table.unmap(); } fn create_kernel_stack(id: ThreadID, address_space: &mut AddressSpace) -> Stack { let tid: usize = id.into(); Stack::new( 0x4000, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_AREA_BASE + KERNEL_STACK_OFFSET * tid, AccessType::KernelOnly, Some(address_space), ) } fn create_user_stack(id: ThreadID, address_space: &m
fn create_idle_stack(cpu_id: usize) -> Stack { Stack::new( 0x3000, KERNEL_STACK_MAX_SIZE, KERNEL_STACK_AREA_BASE + KERNEL_STACK_OFFSET * cpu_id, AccessType::KernelOnly, None, ) } }
ut AddressSpace) -> Stack { let tid: usize = id.into(); Stack::new( 0x2000, USER_STACK_MAX_SIZE, USER_STACK_AREA_BASE + USER_STACK_OFFSET * tid, AccessType::UserAccessible, Some(address_space), ) }
function_block-function_prefixed
[ { "content": "/// Maps the given page to the given frame using the given flags.\n\npub fn map_page_at(page_address: VirtualAddress, frame_address: PhysicalAddress, flags: PageFlags) {\n\n CURRENT_PAGE_TABLE.lock().map_page_at(\n\n Page::from_address(page_address),\n\n PageFrame::from_address(fr...
Rust
src/db/models/configs.rs
nlopes/avro-schema-registry
f18168bacfd1f141be857b7f41cda8c7a874ce93
use std::fmt; use std::str; use chrono::NaiveDateTime; use diesel::prelude::*; use crate::api::errors::{ApiAvroErrorCode, ApiError}; use super::schema::*; use super::Subject; #[derive(Debug, Identifiable, Queryable, Associations, Serialize)] #[table_name = "configs"] #[belongs_to(Subject)] pub struct Config { pub id: i64, pub compatibility: Option<String>, pub created_at: NaiveDateTime, pub updated_at: NaiveDateTime, pub subject_id: Option<i64>, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CompatibilityLevel { Backward, BackwardTransitive, Forward, ForwardTransitive, Full, FullTransitive, #[serde(rename = "NONE")] CompatNone, #[serde(other)] Unknown, } impl fmt::Display for CompatibilityLevel { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let screaming_snake_case = match self { Self::Backward => Ok("BACKWARD"), Self::BackwardTransitive => Ok("BACKWARD_TRANSITIVE"), Self::Forward => Ok("FORWARD"), Self::ForwardTransitive => Ok("FORWARD_TRANSITIVE"), Self::Full => Ok("FULL"), Self::FullTransitive => Ok("FULL_TRANSITIVE"), Self::CompatNone => Ok("NONE"), _ => Ok(""), }?; write!(f, "{}", screaming_snake_case) } } impl str::FromStr for CompatibilityLevel { type Err = (); fn from_str(s: &str) -> Result<Self, ()> { match s { "BACKWARD" => Ok(Self::Backward), "BACKWARD_TRANSITIVE" => Ok(Self::BackwardTransitive), "FORWARD" => Ok(Self::Forward), "FORWARD_TRANSITIVE" => Ok(Self::ForwardTransitive), "FULL" => Ok(Self::Full), "FULL_TRANSITIVE" => Ok(Self::FullTransitive), "NONE" => Ok(Self::CompatNone), _ => Err(()), } } } impl CompatibilityLevel { pub fn valid(self) -> Result<Self, ApiError> { ConfigCompatibility::new(self.to_string()).and(Ok(self)) } } #[derive(Debug, Serialize, Deserialize)] pub struct ConfigCompatibility { pub compatibility: CompatibilityLevel, } impl ConfigCompatibility { pub fn new(level: String) -> Result<Self, ApiError> { match level.parse::<CompatibilityLevel>() { Ok(l) => Ok(Self { compatibility: l }), Err(_) => Err(ApiError::new(ApiAvroErrorCode::InvalidCompatibilityLevel)), } } } pub type SetConfig = ConfigCompatibility; pub struct GetSubjectConfig { pub subject: String, } pub struct SetSubjectConfig { pub subject: String, pub compatibility: CompatibilityLevel, } impl Config { pub const DEFAULT_COMPATIBILITY: CompatibilityLevel = CompatibilityLevel::Backward; pub fn get_global_compatibility(conn: &PgConnection) -> Result<String, ApiError> { use super::schema::configs::dsl::*; match configs.filter(id.eq(0)).get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), Err(diesel::result::Error::NotFound) => { Self::insert(&Self::DEFAULT_COMPATIBILITY.to_string(), conn)?; Ok(Self::DEFAULT_COMPATIBILITY.to_string()) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn get_with_subject_name( conn: &PgConnection, subject_name: String, ) -> Result<String, ApiError> { let subject = Subject::get_by_name(conn, subject_name)?; match Self::belonging_to(&subject).get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn set_with_subject_name( conn: &PgConnection, subject_name: String, compat: String, ) -> Result<String, ApiError> { use super::schema::configs::dsl::*; let subject = Subject::get_by_name(conn, subject_name)?; match Self::belonging_to(&subject).get_result::<Self>(conn) { Ok(config) => { match diesel::update(&config) .set(compatibility.eq(&compat)) .get_result::<Self>(conn) { Ok(conf) => conf .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } Err(diesel::result::Error::NotFound) => { diesel::insert_into(configs) .values(( compatibility.eq(&compat), created_at.eq(diesel::dsl::now), updated_at.eq(diesel::dsl::now), subject_id.eq(subject.id), )) .execute(conn) .map_err(|_| ApiError::new(ApiAvroErrorCode::BackendDatastoreError))?; Ok(compat) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn set_global_compatibility(conn: &PgConnection, compat: &str) -> Result<String, ApiError> { use super::schema::configs::dsl::*; match diesel::update(configs.find(0)) .set(compatibility.eq(compat)) .get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), Err(diesel::result::Error::NotFound) => { Self::insert(compat, conn)?; Ok(compat.to_string()) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } fn insert(compat: &str, conn: &PgConnection) -> Result<usize, ApiError> { use super::schema::configs::dsl::*; diesel::insert_into(configs) .values(( id.eq(0), compatibility.eq(&compat), created_at.eq(diesel::dsl::now), updated_at.eq(diesel::dsl::now), )) .execute(conn) .map_err(|_| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)) } }
use std::fmt; use std::str; use chrono::NaiveDateTime; use diesel::prelude::*; use crate::api::errors::{ApiAvroErrorCode, ApiError}; use super::schema::*; use super::Subject; #[derive(Debug, Identifiable, Queryable, Associations, Serialize)] #[table_name = "configs"] #[belongs_to(Subject)] pub struct Config { pub id: i64, pub compatibility: Option<String>, pub created_at: NaiveDateTime, pub updated_at: NaiveDateTime, pub subject_id: Option<i64>, } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CompatibilityLevel { Backward, BackwardTransitive, Forward, ForwardTransitive, Full, FullTransitive, #[serde(rename = "NONE")] CompatNone, #[serde(other)] Unknown, } impl fmt::Display for CompatibilityLevel { fn fmt(&self, f:
impl str::FromStr for CompatibilityLevel { type Err = (); fn from_str(s: &str) -> Result<Self, ()> { match s { "BACKWARD" => Ok(Self::Backward), "BACKWARD_TRANSITIVE" => Ok(Self::BackwardTransitive), "FORWARD" => Ok(Self::Forward), "FORWARD_TRANSITIVE" => Ok(Self::ForwardTransitive), "FULL" => Ok(Self::Full), "FULL_TRANSITIVE" => Ok(Self::FullTransitive), "NONE" => Ok(Self::CompatNone), _ => Err(()), } } } impl CompatibilityLevel { pub fn valid(self) -> Result<Self, ApiError> { ConfigCompatibility::new(self.to_string()).and(Ok(self)) } } #[derive(Debug, Serialize, Deserialize)] pub struct ConfigCompatibility { pub compatibility: CompatibilityLevel, } impl ConfigCompatibility { pub fn new(level: String) -> Result<Self, ApiError> { match level.parse::<CompatibilityLevel>() { Ok(l) => Ok(Self { compatibility: l }), Err(_) => Err(ApiError::new(ApiAvroErrorCode::InvalidCompatibilityLevel)), } } } pub type SetConfig = ConfigCompatibility; pub struct GetSubjectConfig { pub subject: String, } pub struct SetSubjectConfig { pub subject: String, pub compatibility: CompatibilityLevel, } impl Config { pub const DEFAULT_COMPATIBILITY: CompatibilityLevel = CompatibilityLevel::Backward; pub fn get_global_compatibility(conn: &PgConnection) -> Result<String, ApiError> { use super::schema::configs::dsl::*; match configs.filter(id.eq(0)).get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), Err(diesel::result::Error::NotFound) => { Self::insert(&Self::DEFAULT_COMPATIBILITY.to_string(), conn)?; Ok(Self::DEFAULT_COMPATIBILITY.to_string()) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn get_with_subject_name( conn: &PgConnection, subject_name: String, ) -> Result<String, ApiError> { let subject = Subject::get_by_name(conn, subject_name)?; match Self::belonging_to(&subject).get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn set_with_subject_name( conn: &PgConnection, subject_name: String, compat: String, ) -> Result<String, ApiError> { use super::schema::configs::dsl::*; let subject = Subject::get_by_name(conn, subject_name)?; match Self::belonging_to(&subject).get_result::<Self>(conn) { Ok(config) => { match diesel::update(&config) .set(compatibility.eq(&compat)) .get_result::<Self>(conn) { Ok(conf) => conf .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } Err(diesel::result::Error::NotFound) => { diesel::insert_into(configs) .values(( compatibility.eq(&compat), created_at.eq(diesel::dsl::now), updated_at.eq(diesel::dsl::now), subject_id.eq(subject.id), )) .execute(conn) .map_err(|_| ApiError::new(ApiAvroErrorCode::BackendDatastoreError))?; Ok(compat) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } pub fn set_global_compatibility(conn: &PgConnection, compat: &str) -> Result<String, ApiError> { use super::schema::configs::dsl::*; match diesel::update(configs.find(0)) .set(compatibility.eq(compat)) .get_result::<Self>(conn) { Ok(config) => config .compatibility .ok_or_else(|| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), Err(diesel::result::Error::NotFound) => { Self::insert(compat, conn)?; Ok(compat.to_string()) } _ => Err(ApiError::new(ApiAvroErrorCode::BackendDatastoreError)), } } fn insert(compat: &str, conn: &PgConnection) -> Result<usize, ApiError> { use super::schema::configs::dsl::*; diesel::insert_into(configs) .values(( id.eq(0), compatibility.eq(&compat), created_at.eq(diesel::dsl::now), updated_at.eq(diesel::dsl::now), )) .execute(conn) .map_err(|_| ApiError::new(ApiAvroErrorCode::BackendDatastoreError)) } }
&mut fmt::Formatter) -> fmt::Result { let screaming_snake_case = match self { Self::Backward => Ok("BACKWARD"), Self::BackwardTransitive => Ok("BACKWARD_TRANSITIVE"), Self::Forward => Ok("FORWARD"), Self::ForwardTransitive => Ok("FORWARD_TRANSITIVE"), Self::Full => Ok("FULL"), Self::FullTransitive => Ok("FULL_TRANSITIVE"), Self::CompatNone => Ok("NONE"), _ => Ok(""), }?; write!(f, "{}", screaming_snake_case) } }
random
[ { "content": "#[derive(Debug, Serialize)]\n\nstruct SchemaCompatibility {\n\n is_compatible: bool,\n\n}\n\n\n\nimpl SchemaCompatibility {\n\n fn is_compatible(\n\n old: &str,\n\n new: &str,\n\n compatibility: CompatibilityLevel,\n\n ) -> Result<bool, ApiError> {\n\n match co...
Rust
src/mdbook/files.rs
igorlesik/svdocgen
4e3548720e3fd7673634d557a340be9ecee58a36
use std::fs; use std::path::{Path, PathBuf}; use std::io; use crate::args; use crate::fsnode::FsNode; pub struct SrcFiles { pub nodes: FsNode, } pub fn collect_sources(options: &args::ParsedOptions) -> Result<SrcFiles,String> { let mut inputs: Vec<PathBuf> = Vec::new(); for input in &options.inputs { let path = Path::new(input); if !path.exists() { let include = options.includes.iter().find(|&x| Path::new(x).join(path).exists()); match include { Some(inc) => inputs.push(Path::new(inc).join(path)), None => { println!("Warning: can't find '{}' in {:?}", input, &options.includes); continue; }, } } else { inputs.push(path.to_path_buf()); } } let mut nodes = FsNode { name: String::from(""), children: Vec::new() }; for input in &inputs { println!("input path: {:?}", input); let is_already_present = nodes.exists(input); if is_already_present { println!("Warning: duplicate {:?}", input); } else { nodes.push(input); } } let mut nodes_with_files = nodes.clone(); let mut/*env*/ collect_files = |node: &FsNode, path: &PathBuf, _level: usize| { println!("traverse {}: {:?}", node.name, path); if path.is_dir() && node.children.is_empty() { println!("checking for files in {:?}", path); match visit_dir_and_search_files(&mut nodes_with_files, path) { Err(_) => println!("error"), _ => (), } } }; nodes.traverse_top(&mut collect_files); let src = SrcFiles { nodes: nodes_with_files, }; Ok(src) } fn visit_dir_and_search_files(nodes: &mut FsNode, dir: &Path) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { visit_dir_and_search_files(nodes, &path)?; } else { if let Some(ext) = path.extension() { if ext.eq("sv") || ext.eq("v") || ext.eq("md") { println!("add {:?}", path); nodes.push(&path); } } } } } Ok(()) } pub fn get_files_with_extensions( all_files: &FsNode, extensions: &[&str] ) -> Result<FsNode,String> { let mut files_with_ext = FsNode { name: String::from(""), children: Vec::new() }; let mut/*env*/ filter_files = |_node: &FsNode, path: &PathBuf, _level: usize| { if path.is_file() { if let Some(ext) = path.extension() { if extensions.contains(&ext.to_str().unwrap_or("")) { files_with_ext.push(&path); } } } }; all_files.traverse_top(&mut filter_files); Ok(files_with_ext) } pub fn get_md_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["md"]) } pub fn get_sv_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["sv", "v"]) }
use std::fs; use std::path::{Path, PathBuf}; use std::io; use crate::args; use crate::fsnode::FsNode; pub struct SrcFiles { pub nodes: FsNode, } pub fn collect_sources(options: &args::ParsedOptions) -> Result<SrcFiles,String> { let mut inputs: Vec<PathBuf> = Vec::new(); for input in &options.inputs { let path = Path::new(input); if !path.exists() { let include = options.includes.iter().find(|&x| Path::new(x).join(path).exists()); match include { Some(inc) => inputs.push(Path::new(inc).join(path)), None => { println!("Warning: can't find '{}' in {:?}", input, &options.includes); continue; }, } } else { inputs.push(path.to_path_buf()); } } let mut nodes = FsNode { name: String::from(""), children: Vec::new() }; for input in &inputs { println!("input path: {:?}", input); let is_already_present = nodes.exists(input); if is_already_present { println!("Warning: duplicate {:?}", input); } else { nodes.push(input); } } let mut nodes_with_files = nodes.clone(); let mut/*env*/ collect_files = |node: &FsNode, path: &PathBuf, _level: usize| { println!("traverse {}: {:?}", node.name, path); if path.is_dir() && node.children.is_empty() { println!("checking for files in {:?}", path); match visit_dir_and_search_files(&mut nodes_with_files, path) { Err(_) => println!("error"), _ => (), } } }; nodes.traverse_top(&mut collect_files); let src = SrcFiles { nodes: nodes_with_files, }; Ok(src) } fn visit_dir_and_search_files(nodes: &mut FsNode, dir: &Path) -> io::Result<()> { if dir.is_dir() { for entry in fs::read_dir(dir)? { let entry = entry?; let path = entry.path(); if path.is_dir() { visit_dir_and_search_files(nodes, &path)?; } else { if let Some(ext) = path.extension() { if ext.eq("sv") || ext.eq("v") || ext.eq("md") { println!("add {:?}", path); nodes.push(&path); } } } } } Ok(()) } pub fn get_files_with_extensions( all_files: &FsNode,
pub fn get_md_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["md"]) } pub fn get_sv_files(all_files: &FsNode) -> Result<FsNode,String> { get_files_with_extensions(all_files, &["sv", "v"]) }
extensions: &[&str] ) -> Result<FsNode,String> { let mut files_with_ext = FsNode { name: String::from(""), children: Vec::new() }; let mut/*env*/ filter_files = |_node: &FsNode, path: &PathBuf, _level: usize| { if path.is_file() { if let Some(ext) = path.extension() { if extensions.contains(&ext.to_str().unwrap_or("")) { files_with_ext.push(&path); } } } }; all_files.traverse_top(&mut filter_files); Ok(files_with_ext) }
function_block-function_prefix_line
[ { "content": "/// Create files.md file that lists all input files.\n\n///\n\n///\n\nfn create_files_md(path: &str, files: &FsNode) -> Result<String,String> {\n\n\n\n let fname = Path::new(&path).join(\"files.md\");\n\n let fname = fname.to_str().unwrap();\n\n\n\n let file = match fs::OpenOptions::new()...
Rust
src/macos/mod.rs
ignatenkobrain/rust-locale
9acaf6987a97f8ffcda0e3ce6e8770e7a01ece09
use std::borrow::ToOwned; use std::env::var; use std::fs::{metadata, File}; use std::io::{BufRead, Error, Result, BufReader}; use std::path::{Path, PathBuf}; use super::{LocaleFactory, Numeric, Time}; static LOCALE_DIR: &'static str = "/usr/share/locale"; #[derive(Debug, Clone)] enum LocaleType { Numeric, Time, } fn find_user_locale_path(file_name: &str) -> Option<PathBuf> { let locale_dir = Path::new(LOCALE_DIR); if let Ok(specific_path) = var(file_name) { let path = locale_dir.join(Path::new(&specific_path)).join(Path::new(file_name)); if path.exists() { return Some(path); } } if let Ok(all_path) = var("LC_ALL") { let path = locale_dir.join(Path::new(&all_path)).join(Path::new(file_name)); if path.exists() { return Some(path); } } if let Ok(lang) = var("LANG") { let path = locale_dir.join(Path::new(&lang)).join(Path::new(file_name)); if path.exists() { return Some(path); } } None } fn find_locale_path(locale_type: LocaleType, locale_name: &str) -> Option<PathBuf> { let file_name = match locale_type { LocaleType::Numeric => "LC_NUMERIC", LocaleType::Time => "LC_TIME", }; if locale_name == "" { return find_user_locale_path(&file_name); } else { let locale_dir = Path::new(LOCALE_DIR); let path = locale_dir.join(locale_name).join(file_name); if path.exists() { return Some(path); } } None } fn load_numeric(locale: &str) -> Result<Numeric> { let path = find_locale_path(LocaleType::Numeric, locale); if let Some(path) = path { let file = BufReader::new(try!(File::open(&path))); let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect(); Ok(Numeric { decimal_sep: lines[0].trim().to_string(), thousands_sep: lines[1].trim().to_string(), }) } else { return Err(Error::last_os_error()); } } fn load_time(locale: &str) -> Result<Time> { let path = find_locale_path(LocaleType::Time, locale); if let Some(path) = path { let file = BufReader::new(try!(File::open(&path))); let mut iter = file.lines().map(|x| x.unwrap().trim().to_string()); let month_names = iter.by_ref().take(12).collect(); let long_month_names = iter.by_ref().take(12).collect(); let day_names = iter.by_ref().take(7).collect(); let long_day_names = iter.by_ref().take(7).collect(); Ok(Time { month_names: month_names, long_month_names: long_month_names, day_names: day_names, long_day_names: long_day_names, }) } else { return Err(Error::last_os_error()); } } pub struct MacOSLocaleFactory { locale: String, } impl MacOSLocaleFactory { pub fn new(locale: &str) -> Result<Self> { Ok(MacOSLocaleFactory { locale: locale.to_owned() }) } } impl LocaleFactory for MacOSLocaleFactory { fn get_numeric(&mut self) -> Option<Box<Numeric>> { if let Ok(numeric) = load_numeric(&self.locale) { Some(Box::new(numeric)) } else { None } } fn get_time(&mut self) -> Option<Box<Time>> { if let Ok(time) = load_time(&self.locale) { Some(Box::new(time)) } else { None } } } pub trait PathExt { fn exists(&self) -> bool; } impl PathExt for Path { fn exists(&self) -> bool { metadata(self).is_ok() } }
use std::borrow::ToOwned; use std::env::var; use std::fs::{metadata, File}; use std::io::{BufRead, Error, Result, BufReader}; use std::path::{Path, PathBuf}; use super::{LocaleFactory, Numeric, Time}; static LOCALE_DIR: &'static str = "/usr/share/locale"; #[derive(Debug, Clone)] enum LocaleType { Numeric, Time, } fn find_user_locale_path(file_name: &str) -> Option<PathBuf> { let locale_dir = Path::new(LOCALE_DIR); if let Ok(specific_path) = var(file_name) { let path = locale_dir.join(Path::new(&specific_path)).join(Path::new(file_name)); if path.exists() { return Some(path); } } if let Ok(all_path) = var("LC_ALL") { let path = locale_dir.join(Path::new(&all_path)).join(Path::new(file_name)); if path.exists() { return Some(path); } }
None } fn find_locale_path(locale_type: LocaleType, locale_name: &str) -> Option<PathBuf> { let file_name = match locale_type { LocaleType::Numeric => "LC_NUMERIC", LocaleType::Time => "LC_TIME", }; if locale_name == "" { return find_user_locale_path(&file_name); } else { let locale_dir = Path::new(LOCALE_DIR); let path = locale_dir.join(locale_name).join(file_name); if path.exists() { return Some(path); } } None } fn load_numeric(locale: &str) -> Result<Numeric> { let path = find_locale_path(LocaleType::Numeric, locale); if let Some(path) = path { let file = BufReader::new(try!(File::open(&path))); let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect(); Ok(Numeric { decimal_sep: lines[0].trim().to_string(), thousands_sep: lines[1].trim().to_string(), }) } else { return Err(Error::last_os_error()); } } fn load_time(locale: &str) -> Result<Time> { let path = find_locale_path(LocaleType::Time, locale); if let Some(path) = path { let file = BufReader::new(try!(File::open(&path))); let mut iter = file.lines().map(|x| x.unwrap().trim().to_string()); let month_names = iter.by_ref().take(12).collect(); let long_month_names = iter.by_ref().take(12).collect(); let day_names = iter.by_ref().take(7).collect(); let long_day_names = iter.by_ref().take(7).collect(); Ok(Time { month_names: month_names, long_month_names: long_month_names, day_names: day_names, long_day_names: long_day_names, }) } else { return Err(Error::last_os_error()); } } pub struct MacOSLocaleFactory { locale: String, } impl MacOSLocaleFactory { pub fn new(locale: &str) -> Result<Self> { Ok(MacOSLocaleFactory { locale: locale.to_owned() }) } } impl LocaleFactory for MacOSLocaleFactory { fn get_numeric(&mut self) -> Option<Box<Numeric>> { if let Ok(numeric) = load_numeric(&self.locale) { Some(Box::new(numeric)) } else { None } } fn get_time(&mut self) -> Option<Box<Time>> { if let Ok(time) = load_time(&self.locale) { Some(Box::new(time)) } else { None } } } pub trait PathExt { fn exists(&self) -> bool; } impl PathExt for Path { fn exists(&self) -> bool { metadata(self).is_ok() } }
if let Ok(lang) = var("LANG") { let path = locale_dir.join(Path::new(&lang)).join(Path::new(file_name)); if path.exists() { return Some(path); } }
if_condition
[ { "content": "#[cfg(not(target_os = \"linux\"))]\n\npub fn main() {\n\n println!(\"Listing locale info not (yet) supported on this system\");\n\n}\n", "file_path": "examples/localeinfo.rs", "rank": 5, "score": 33880.010529542735 }, { "content": "/// Return LocaleFactory appropriate for de...
Rust
src/shape.rs
magnusstrale/raytracer
58ea8e85380de87a9abffa5e376dd01fc4c2901c
use std::any::Any; use std::fmt; use super::tuple::Tuple; use super::ray::Ray; use super::intersection::Intersections; use super::material::Material; use super::matrix::{Matrix, IDENTITY_MATRIX}; pub trait Shape: Any + fmt::Debug { fn box_clone(&self) -> BoxShape; fn box_eq(&self, other: &dyn Any) -> bool; fn as_any(&self) -> &dyn Any; fn inner_intersect(&self, object_ray: Ray) -> Intersections; fn inner_normal_at(&self, object_point: Tuple) -> Tuple; fn material(&self) -> &Material; fn transformation(&self) -> Matrix; fn inverse_transformation(&self) -> Matrix; fn intersect(&self, world_ray: Ray) -> Intersections { self.inner_intersect(world_ray.transform(self.inverse_transformation())) } fn normal_at(&self, world_point: Tuple) -> Tuple { let object_normal = self.inner_normal_at(self.inverse_transformation() * world_point); let mut world_normal = self.inverse_transformation().transpose() * object_normal; world_normal.w = 0.; world_normal.normalize() } } pub type BoxShape = Box<dyn Shape>; pub fn inverse_transform_parameter(transform: Option<Matrix>) -> Matrix { match transform { None => IDENTITY_MATRIX, Some(t) => t.inverse().unwrap() } } impl Clone for BoxShape { fn clone(&self) -> Self { self.box_clone() } } impl PartialEq for BoxShape { fn eq(&self, other: &BoxShape) -> bool { self.box_eq(other.as_any()) } } #[cfg(test)] mod tests { use super::*; use std::f64::consts::{PI, SQRT_2}; use crate::color::GREEN; use crate::tuple::{ORIGO, VECTOR_Y_UP}; use crate::material::DEFAULT_MATERIAL; static mut SAVED_RAY: Ray = Ray { origin: ORIGO, direction: VECTOR_Y_UP }; #[derive(Clone, Debug, PartialEq)] struct TestShape { material: Material, inverse_transform: Matrix, transform: Matrix } impl Shape for TestShape { fn as_any(&self) -> &dyn Any { self } fn box_eq(&self, other: &dyn Any) -> bool { other.downcast_ref::<Self>().map_or(false, |a| self == a) } fn box_clone(&self) -> BoxShape { Box::new((*self).clone()) } fn inner_intersect(&self, object_ray: Ray) -> Intersections { unsafe { SAVED_RAY = object_ray; } Intersections::new(vec![]) } fn inner_normal_at(&self, object_point: Tuple) -> Tuple { Tuple::vector(object_point.x, object_point.y, object_point.z) } fn material(&self) -> &Material { &self.material } fn transformation(&self) -> Matrix { self.transform } fn inverse_transformation(&self) -> Matrix { self.inverse_transform } } impl TestShape { fn new(material: Option<Material>, transform: Option<Matrix>) -> Self { Self { material: material.unwrap_or_default(), transform: transform.unwrap_or_default(), inverse_transform: inverse_transform_parameter(transform) } } } #[test] fn default_transformation() { let s = TestShape::new(None, None); assert_eq!(s.transformation(), IDENTITY_MATRIX); } #[test] fn assign_transformation() { let tr = Matrix::translation(2., 3., 4.); let s = TestShape::new(None, Some(tr)); assert_eq!(s.transformation(), tr); } #[test] fn default_material() { let s = TestShape::new(None, None); let m = s.material(); assert_eq!(*m, DEFAULT_MATERIAL); } #[test] fn assign_material() { let m = Material::new(GREEN, 0.1, 0.2, 0.3, 0.4, None); let s = TestShape::new(Some(m.clone()), None); assert_eq!(*s.material(), m); } #[test] fn intersect_scaled_shape_with_ray() { let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.)); let tr = Matrix::scaling(2., 2., 2.); let s = TestShape::new(None, Some(tr)); s.intersect(r); unsafe { assert_eq!(SAVED_RAY.origin, Tuple::point(0., 0., -2.5)); assert_eq!(SAVED_RAY.direction, Tuple::vector(0., 0., 0.5)); } } #[test] fn intersect_translated_shape_with_ray() { let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.)); let tr = Matrix::translation(5., 0., 0.); let s = TestShape::new(None, Some(tr)); s.intersect(r); unsafe { assert_eq!(SAVED_RAY.origin, Tuple::point(-5., 0., -5.)); assert_eq!(SAVED_RAY.direction, Tuple::vector(0., 0., 1.)); } } #[test] fn compute_normal_on_translated_shape() { let tr = Matrix::translation(0., 1., 0.); let s = TestShape::new(None, Some(tr)); let n = s.normal_at(Tuple::point(0., 1.70711, -0.70711)); assert_eq!(n, Tuple::vector(0., 0.70711, -0.70711)); } #[test] fn compute_normal_on_transformed_shape() { let tr = Matrix::scaling(1., 0.5, 1.) * Matrix::rotation_z(PI / 5.); let s = TestShape::new(None, Some(tr)); let n = s.normal_at(Tuple::point(0., SQRT_2 / 2., -SQRT_2 / 2.)); assert_eq!(n, Tuple::vector(0., 0.97014, -0.24254)); } }
use std::any::Any; use std::fmt; use super::tuple::Tuple; use super::ray::Ray; use super::intersection::Intersections; use super::material::Material; use super::matrix::{Matrix, IDENTITY_MATRIX}; pub trait Shape: Any + fmt::Debug { fn box_clone(&self) -> BoxShape; fn box_eq(&self, other: &dyn Any) -> bool; fn as_any(&self) -> &dyn Any; fn inner_intersect(&self, object_ray: Ray) -> Intersections; fn inner_normal_at(&self, object_point: Tuple) -> Tuple; fn material(&self) -> &Material; fn transformation(&self) -> Matrix; fn inverse_transformation(&self) -> Matrix; fn intersect(&self, world_ray: Ray) -> Intersections { self.inner_intersect(world_ray.transform(self.inverse_transformation())) } fn normal_at(&self, world_point: Tuple) -> Tuple { let object_normal = self.inner_normal_at(self.inverse_transformation() * world_point); let mut world_normal = self.inverse_transformation().transpose() * object_normal; world_normal.w = 0.; world_normal.normalize() } } pub type BoxShape = Box<dyn Shape>; pub fn inverse_transform_parameter(transform: Option<Matrix>) -> Matrix { match transform { None => IDENTITY_MATRIX, Some(t) => t.inverse().unwrap() } } impl Clone for BoxShape { fn clone(&self) -> Self { self.box_clone() } } impl PartialEq for BoxShape { fn eq(&self, other: &BoxShape) -> bool { self.box_eq(other.as_any()) } } #[cfg(test)] mod tests { use super::*; use std::f64::consts::{PI, SQRT_2}; use crate::color::GREEN; use crate::tuple::{ORIGO, VECTOR_Y_UP}; use crate::material::DEFAULT_MATERIAL; static mut SAVED_RAY: Ray = Ray { origin: ORIGO, direction: VECTOR_Y_UP }; #[derive(Clone, Debug, PartialEq)] struct TestShape { material: Material, inverse_transform: Matrix, transform: Matrix } impl Shape for TestShape { fn as_any(&self) -> &dyn Any { self } fn box_eq(&self, other: &dyn Any) -> bool { other.downcast_ref::<Self>().map_or(false, |a| self == a) } fn box_clone(&self) -> BoxShape { Box::new((*self).clone()) } fn inner_intersect(&self, object_ray: Ray) -> Intersections { unsafe { SAVED_RAY = object_ray; } Intersections::new(vec![]) } fn inner_normal_at(&self, object_point: Tuple) -> Tuple { Tuple::vector(object_point.x, object_point.y, object_point.z) } fn material(&self) -> &Material { &self.material } fn transformation(&self) -> Matrix { self.transform } fn inverse_transf
) { let s = TestShape::new(None, None); assert_eq!(s.transformation(), IDENTITY_MATRIX); } #[test] fn assign_transformation() { let tr = Matrix::translation(2., 3., 4.); let s = TestShape::new(None, Some(tr)); assert_eq!(s.transformation(), tr); } #[test] fn default_material() { let s = TestShape::new(None, None); let m = s.material(); assert_eq!(*m, DEFAULT_MATERIAL); } #[test] fn assign_material() { let m = Material::new(GREEN, 0.1, 0.2, 0.3, 0.4, None); let s = TestShape::new(Some(m.clone()), None); assert_eq!(*s.material(), m); } #[test] fn intersect_scaled_shape_with_ray() { let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.)); let tr = Matrix::scaling(2., 2., 2.); let s = TestShape::new(None, Some(tr)); s.intersect(r); unsafe { assert_eq!(SAVED_RAY.origin, Tuple::point(0., 0., -2.5)); assert_eq!(SAVED_RAY.direction, Tuple::vector(0., 0., 0.5)); } } #[test] fn intersect_translated_shape_with_ray() { let r = Ray::new(Tuple::point(0., 0., -5.), Tuple::vector(0., 0., 1.)); let tr = Matrix::translation(5., 0., 0.); let s = TestShape::new(None, Some(tr)); s.intersect(r); unsafe { assert_eq!(SAVED_RAY.origin, Tuple::point(-5., 0., -5.)); assert_eq!(SAVED_RAY.direction, Tuple::vector(0., 0., 1.)); } } #[test] fn compute_normal_on_translated_shape() { let tr = Matrix::translation(0., 1., 0.); let s = TestShape::new(None, Some(tr)); let n = s.normal_at(Tuple::point(0., 1.70711, -0.70711)); assert_eq!(n, Tuple::vector(0., 0.70711, -0.70711)); } #[test] fn compute_normal_on_transformed_shape() { let tr = Matrix::scaling(1., 0.5, 1.) * Matrix::rotation_z(PI / 5.); let s = TestShape::new(None, Some(tr)); let n = s.normal_at(Tuple::point(0., SQRT_2 / 2., -SQRT_2 / 2.)); assert_eq!(n, Tuple::vector(0., 0.97014, -0.24254)); } }
ormation(&self) -> Matrix { self.inverse_transform } } impl TestShape { fn new(material: Option<Material>, transform: Option<Matrix>) -> Self { Self { material: material.unwrap_or_default(), transform: transform.unwrap_or_default(), inverse_transform: inverse_transform_parameter(transform) } } } #[test] fn default_transformation(
random
[ { "content": "pub trait Pattern: Any + fmt::Debug {\n\n fn box_clone(&self) -> BoxPattern;\n\n fn box_eq(&self, other: &dyn Any) -> bool;\n\n fn as_any(&self) -> &dyn Any;\n\n fn transformation(&self) -> Matrix;\n\n fn inverse_transformation(&self) -> Matrix;\n\n fn inner_pattern_at(&self, pat...
Rust
src/lib.rs
kchmck/uhttp_content_encoding.rs
683fff450707ae509a4d3a4a863108364d3e643a
#![feature(conservative_impl_trait)] use std::ascii::AsciiExt; pub fn content_encodings<'a>(s: &'a str) -> impl Iterator<Item = ContentEncoding<'a>> { s.split(',').rev().map(ContentEncoding::new) } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum ContentEncoding<'a> { Std(StdContentEncoding), Other(&'a str), } impl<'a> ContentEncoding<'a> { pub fn new(s: &'a str) -> Self { let s = s.trim(); match s.parse() { Ok(enc) => ContentEncoding::Std(enc), Err(_) => ContentEncoding::Other(s), } } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum StdContentEncoding { Brottli, Compress, Deflate, EfficientXML, Gzip, Identity, Pack200Gzip, } impl std::str::FromStr for StdContentEncoding { type Err = (); fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { use self::StdContentEncoding::*; if s.eq_ignore_ascii_case("br") { Ok(Brottli) } else if s.eq_ignore_ascii_case("compress") { Ok(Compress) } else if s.eq_ignore_ascii_case("deflate") { Ok(Deflate) } else if s.eq_ignore_ascii_case("exi") { Ok(EfficientXML) } else if s.eq_ignore_ascii_case("gzip") { Ok(Gzip) } else if s.eq_ignore_ascii_case("identity") { Ok(Identity) } else if s.eq_ignore_ascii_case("pack200-gzip") { Ok(Pack200Gzip) } else if s.is_empty() { Ok(Identity) } else { Err(()) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_ce() { use self::StdContentEncoding::*; use self::ContentEncoding::*; assert_eq!(ContentEncoding::new("br"), Std(Brottli)); assert_eq!(ContentEncoding::new("\t\t\rBr "), Std(Brottli)); assert_eq!(ContentEncoding::new("compress"), Std(Compress)); assert_eq!(ContentEncoding::new(" COMpress "), Std(Compress)); assert_eq!(ContentEncoding::new("deflate"), Std(Deflate)); assert_eq!(ContentEncoding::new("\t\n dEFLAte "), Std(Deflate)); assert_eq!(ContentEncoding::new("exi"), Std(EfficientXML)); assert_eq!(ContentEncoding::new("\tEXI\t"), Std(EfficientXML)); assert_eq!(ContentEncoding::new("gzip"), Std(Gzip)); assert_eq!(ContentEncoding::new(" \tgZIP"), Std(Gzip)); assert_eq!(ContentEncoding::new("identity"), Std(Identity)); assert_eq!(ContentEncoding::new("\niDENtiTY\r\r\r "), Std(Identity)); assert_eq!(ContentEncoding::new(""), Std(Identity)); assert_eq!(ContentEncoding::new(" \t "), Std(Identity)); assert_eq!(ContentEncoding::new("pack200-gzip"), Std(Pack200Gzip)); assert_eq!(ContentEncoding::new(" PaCK200-GZip "), Std(Pack200Gzip)); assert_eq!(ContentEncoding::new("ร†ร˜ะ‘ะ”โค"), Other("ร†ร˜ะ‘ะ”โค")); } #[test] fn test_ces() { use self::StdContentEncoding::*; use self::ContentEncoding::*; let mut ce = content_encodings("deflate, br, identity"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Brottli)); assert_eq!(ce.next().unwrap(), Std(Deflate)); assert!(ce.next().is_none()); let mut ce = content_encodings("identity"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings(""); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings("\t\t,, , ,"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings("Br, exi,pack200-GZip "); assert_eq!(ce.next().unwrap(), Std(Pack200Gzip)); assert_eq!(ce.next().unwrap(), Std(EfficientXML)); assert_eq!(ce.next().unwrap(), Std(Brottli)); assert!(ce.next().is_none()); let mut ce = content_encodings("\t\t\t gzip"); assert_eq!(ce.next().unwrap(), Std(Gzip)); assert!(ce.next().is_none()); let mut ce = content_encodings("\tabc\t\t, def "); assert_eq!(ce.next().unwrap(), Other("def")); assert_eq!(ce.next().unwrap(), Other("abc")); assert!(ce.next().is_none()); } }
#![feature(conservative_impl_trait)] use std::ascii::AsciiExt; pub fn content_encodings<'a>(s: &'a str) -> impl Iterator<Item = ContentEncoding<'a>> { s.split(',').rev().map(ContentEncoding::new) } #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum ContentEncoding<'a> { Std(StdContentEncoding), Other(&'a str), } impl<'a> ContentEncoding<'a> {
} #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)] pub enum StdContentEncoding { Brottli, Compress, Deflate, EfficientXML, Gzip, Identity, Pack200Gzip, } impl std::str::FromStr for StdContentEncoding { type Err = (); fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { use self::StdContentEncoding::*; if s.eq_ignore_ascii_case("br") { Ok(Brottli) } else if s.eq_ignore_ascii_case("compress") { Ok(Compress) } else if s.eq_ignore_ascii_case("deflate") { Ok(Deflate) } else if s.eq_ignore_ascii_case("exi") { Ok(EfficientXML) } else if s.eq_ignore_ascii_case("gzip") { Ok(Gzip) } else if s.eq_ignore_ascii_case("identity") { Ok(Identity) } else if s.eq_ignore_ascii_case("pack200-gzip") { Ok(Pack200Gzip) } else if s.is_empty() { Ok(Identity) } else { Err(()) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_ce() { use self::StdContentEncoding::*; use self::ContentEncoding::*; assert_eq!(ContentEncoding::new("br"), Std(Brottli)); assert_eq!(ContentEncoding::new("\t\t\rBr "), Std(Brottli)); assert_eq!(ContentEncoding::new("compress"), Std(Compress)); assert_eq!(ContentEncoding::new(" COMpress "), Std(Compress)); assert_eq!(ContentEncoding::new("deflate"), Std(Deflate)); assert_eq!(ContentEncoding::new("\t\n dEFLAte "), Std(Deflate)); assert_eq!(ContentEncoding::new("exi"), Std(EfficientXML)); assert_eq!(ContentEncoding::new("\tEXI\t"), Std(EfficientXML)); assert_eq!(ContentEncoding::new("gzip"), Std(Gzip)); assert_eq!(ContentEncoding::new(" \tgZIP"), Std(Gzip)); assert_eq!(ContentEncoding::new("identity"), Std(Identity)); assert_eq!(ContentEncoding::new("\niDENtiTY\r\r\r "), Std(Identity)); assert_eq!(ContentEncoding::new(""), Std(Identity)); assert_eq!(ContentEncoding::new(" \t "), Std(Identity)); assert_eq!(ContentEncoding::new("pack200-gzip"), Std(Pack200Gzip)); assert_eq!(ContentEncoding::new(" PaCK200-GZip "), Std(Pack200Gzip)); assert_eq!(ContentEncoding::new("ร†ร˜ะ‘ะ”โค"), Other("ร†ร˜ะ‘ะ”โค")); } #[test] fn test_ces() { use self::StdContentEncoding::*; use self::ContentEncoding::*; let mut ce = content_encodings("deflate, br, identity"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Brottli)); assert_eq!(ce.next().unwrap(), Std(Deflate)); assert!(ce.next().is_none()); let mut ce = content_encodings("identity"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings(""); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings("\t\t,, , ,"); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert_eq!(ce.next().unwrap(), Std(Identity)); assert!(ce.next().is_none()); let mut ce = content_encodings("Br, exi,pack200-GZip "); assert_eq!(ce.next().unwrap(), Std(Pack200Gzip)); assert_eq!(ce.next().unwrap(), Std(EfficientXML)); assert_eq!(ce.next().unwrap(), Std(Brottli)); assert!(ce.next().is_none()); let mut ce = content_encodings("\t\t\t gzip"); assert_eq!(ce.next().unwrap(), Std(Gzip)); assert!(ce.next().is_none()); let mut ce = content_encodings("\tabc\t\t, def "); assert_eq!(ce.next().unwrap(), Other("def")); assert_eq!(ce.next().unwrap(), Other("abc")); assert!(ce.next().is_none()); } }
pub fn new(s: &'a str) -> Self { let s = s.trim(); match s.parse() { Ok(enc) => ContentEncoding::Std(enc), Err(_) => ContentEncoding::Other(s), } }
function_block-full_function
[ { "content": "# uhttp\\_content\\_encoding -- Parser for HTTP Content-Encoding header\n\n\n\n[Documentation](https://docs.rs/uhttp_content_encoding)\n\n\n\nThis crate provides a zero-allocation, iterator/slice-based parser for extracting HTTP\n\n[content encoding](https://tools.ietf.org/html/rfc7231#section-3.1...
Rust
src/writer/header.rs
diegodox/ply_rs
0bdce2456117d278b2c176b9b46d5e0363dd3f2f
use std::io::{BufWriter, Write}; use crate::{Comment, Element, Format, GenericElement, PLYFile, Property, PropertyList}; const MAGIC_NUMBER: &str = "ply"; const END_HEADER: &str = "end_header"; pub(crate) trait PlyWriteHeader<T: Write> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()>; } impl<T: Write> PlyWriteHeader<T> for PLYFile { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "{}", MAGIC_NUMBER)?; self.format.write_header(writer)?; for comment in self.comments.iter() { comment.write_header(writer)?; } for element in self.elements.iter() { match element { Element::Element(e) => e.write_header(writer), Element::ListElement(e) => e.write_header(writer), }?; } writeln!(writer, "{}", END_HEADER)?; Ok(()) } } impl<T: Write> PlyWriteHeader<T> for Format { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { match self { crate::Format::Ascii { version } => writeln!(writer, "format ascii {}", version), crate::Format::BinaryBigEndian { version } => { writeln!(writer, "format binary_big_endian {}", version) } crate::Format::BinaryLittleEndian { version } => { writeln!(writer, "format binary_little_endian {}", version) } } } } #[test] fn test_write_format() { let mut writer = BufWriter::new(Vec::new()); let format = Format::Ascii { version: "1.0".to_string(), }; format.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"format ascii 1.0 "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for Comment { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "comment {}", self.0.join(" ")) } } #[test] fn test_write_comment() { let mut writer = BufWriter::new(Vec::new()); let comment = Comment(vec!["test".to_string(), "comment".to_string()]); comment.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"comment test comment "# .as_bytes(), ) } impl<T: Write, P: PlyWriteHeader<T>> PlyWriteHeader<T> for GenericElement<P> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "element {} {}", self.name, self.count)?; self.property().write_header(writer) } } #[test] fn test_write_element_header() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let element = GenericElement { name: "vertex".to_string(), count: 20, props: Property { props: vec![ PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, ], names: vec![ "x".to_string(), "y".to_string(), "z".to_string(), "red".to_string(), "green".to_string(), "blue".to_string(), ], }, payloads: Vec::<Payload>::with_capacity(20), }; element.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"element vertex 20 property float x property float y property float z property uchar red property uchar green property uchar blue "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for Property { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { for (name, ply_type) in self.iter() { writeln!(writer, "property {} {}", ply_type.to_str(), name)? } Ok(()) } } #[test] fn test_write_property() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let property = Property { props: vec![ PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, ], names: vec![ "x".to_string(), "y".to_string(), "z".to_string(), "red".to_string(), "green".to_string(), "blue".to_string(), ], }; property.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"property float x property float y property float z property uchar red property uchar green property uchar blue "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for PropertyList { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!( writer, "property list {} {} {}", self.count.to_str(), self.prop.to_str(), self.name ) } } #[test] fn test_write_property_list() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let property = PropertyList { name: "vertex".to_string(), count: PLYValueTypeName::Uchar, prop: PLYValueTypeName::Float, }; property.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"property list uchar float vertex "# .as_bytes(), ) }
use std::io::{BufWriter, Write}; use crate::{Comment, Element, Format, GenericElement, PLYFile, Property, PropertyLi
rite_property_list() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let property = PropertyList { name: "vertex".to_string(), count: PLYValueTypeName::Uchar, prop: PLYValueTypeName::Float, }; property.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"property list uchar float vertex "# .as_bytes(), ) }
st}; const MAGIC_NUMBER: &str = "ply"; const END_HEADER: &str = "end_header"; pub(crate) trait PlyWriteHeader<T: Write> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()>; } impl<T: Write> PlyWriteHeader<T> for PLYFile { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "{}", MAGIC_NUMBER)?; self.format.write_header(writer)?; for comment in self.comments.iter() { comment.write_header(writer)?; } for element in self.elements.iter() { match element { Element::Element(e) => e.write_header(writer), Element::ListElement(e) => e.write_header(writer), }?; } writeln!(writer, "{}", END_HEADER)?; Ok(()) } } impl<T: Write> PlyWriteHeader<T> for Format { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { match self { crate::Format::Ascii { version } => writeln!(writer, "format ascii {}", version), crate::Format::BinaryBigEndian { version } => { writeln!(writer, "format binary_big_endian {}", version) } crate::Format::BinaryLittleEndian { version } => { writeln!(writer, "format binary_little_endian {}", version) } } } } #[test] fn test_write_format() { let mut writer = BufWriter::new(Vec::new()); let format = Format::Ascii { version: "1.0".to_string(), }; format.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"format ascii 1.0 "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for Comment { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "comment {}", self.0.join(" ")) } } #[test] fn test_write_comment() { let mut writer = BufWriter::new(Vec::new()); let comment = Comment(vec!["test".to_string(), "comment".to_string()]); comment.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"comment test comment "# .as_bytes(), ) } impl<T: Write, P: PlyWriteHeader<T>> PlyWriteHeader<T> for GenericElement<P> { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!(writer, "element {} {}", self.name, self.count)?; self.property().write_header(writer) } } #[test] fn test_write_element_header() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let element = GenericElement { name: "vertex".to_string(), count: 20, props: Property { props: vec![ PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, ], names: vec![ "x".to_string(), "y".to_string(), "z".to_string(), "red".to_string(), "green".to_string(), "blue".to_string(), ], }, payloads: Vec::<Payload>::with_capacity(20), }; element.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"element vertex 20 property float x property float y property float z property uchar red property uchar green property uchar blue "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for Property { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { for (name, ply_type) in self.iter() { writeln!(writer, "property {} {}", ply_type.to_str(), name)? } Ok(()) } } #[test] fn test_write_property() { use crate::*; let mut writer = BufWriter::new(Vec::new()); let property = Property { props: vec![ PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Float, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, PLYValueTypeName::Uchar, ], names: vec![ "x".to_string(), "y".to_string(), "z".to_string(), "red".to_string(), "green".to_string(), "blue".to_string(), ], }; property.write_header(&mut writer).unwrap(); assert_eq!( writer.into_inner().unwrap(), r#"property float x property float y property float z property uchar red property uchar green property uchar blue "# .as_bytes(), ) } impl<T: Write> PlyWriteHeader<T> for PropertyList { fn write_header(&self, writer: &mut BufWriter<T>) -> std::io::Result<()> { writeln!( writer, "property list {} {} {}", self.count.to_str(), self.prop.to_str(), self.name ) } } #[test] fn test_w
random
[ { "content": "#[test]\n\nfn test_write_element_payload_ascii() {\n\n use crate::*;\n\n let mut writer = BufWriter::new(Vec::new());\n\n let element = GenericElement {\n\n name: \"vertex\".to_string(),\n\n count: 8,\n\n props: Property {\n\n props: vec![\n\n ...
Rust
backend/api/src/http/endpoints/user/public_user.rs
jewish-interactive/ji-cloud
b6164bf1d15277115bcab1d8c9f91619e706231d
use actix_web::{ web::{Data, Json, Path, Query}, HttpResponse, }; use futures::try_join; use shared::{ api::{endpoints::user, ApiEndpoint}, domain::{ asset::DraftOrLive, course::CourseBrowseResponse, jig::JigBrowseResponse, user::public_user::{ BrowsePublicUserFollowersResponse as BrowseFollowersResponse, BrowsePublicUserFollowingResponse as BrowseFollowingsResponse, BrowsePublicUserResourcesResponse as BrowseResourcesResponse, BrowsePublicUserResponse, PublicUser, SearchPublicUserResponse, }, }, }; use sqlx::PgPool; use uuid::Uuid; use crate::{ db, error::{self, ServiceKind}, extractor::TokenUser, http::endpoints::course::{DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT}, service::ServiceData, }; pub async fn get( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, ) -> Result<Json<<user::GetPublicUser as ApiEndpoint>::Res>, error::NotFound> { let user_id = path.into_inner(); let user: PublicUser = db::user::public_user::get(&db, user_id).await?; Ok(Json(user)) } pub async fn search( db: Data<PgPool>, claims: Option<TokenUser>, algolia: ServiceData<crate::algolia::Client>, query: Option<Query<<user::Search as ApiEndpoint>::Req>>, ) -> Result<Json<<user::Search as ApiEndpoint>::Res>, error::Service> { let query = query.map_or_else(Default::default, Query::into_inner); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::Service::InternalServerError(e))?; let user_id = db::user::public_user::auth_claims(&db, claims, query.user_id).await?; let (ids, pages, total_hits) = algolia .search_public_user( &query.q, query.username, query.name, user_id, query.language, query.organization, query.persona, page_limit, query.page, ) .await? .ok_or_else(|| error::Service::DisabledService(ServiceKind::Algolia))?; let users: Vec<_> = db::user::public_user::get_by_ids(db.as_ref(), &ids).await?; Ok(Json(SearchPublicUserResponse { users, pages, total_user_count: total_hits, })) } pub async fn browse( db: Data<PgPool>, _auth: Option<TokenUser>, query: Option<Query<<user::BrowsePublicUser as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowsePublicUser as ApiEndpoint>::Res>, error::NotFound> { let query = query.map_or_else(Default::default, Query::into_inner); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_users(&db, query.page.unwrap_or(0), page_limit as u64); let total_count_future = db::user::public_user::total_user_count(db.as_ref()); let (users, total_user_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_user_count / (page_limit as u64) + (total_user_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowsePublicUserResponse { users, pages, total_user_count, })) } pub async fn browse_user_jigs( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseUserJigs as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseUserJigs as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let privacy_level = vec![]; let resource_types = vec![]; let browse_future = db::jig::browse( &db, Some(user_id), None, Some(DraftOrLive::Live), privacy_level.to_owned(), Some(false), query.page.unwrap_or(0) as i32, page_limit, resource_types.to_owned(), ); let total_count_future = db::jig::filtered_count( db.as_ref(), privacy_level.to_owned(), Some(false), Some(user_id), None, Some(DraftOrLive::Live), resource_types.to_owned(), ); let (jigs, (total_count, count)) = try_join!(browse_future, total_count_future,)?; let pages = (count / (page_limit as u64) + (count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(JigBrowseResponse { jigs, pages, total_jig_count: total_count, })) } pub async fn browse_user_resources( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseResources as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseResources as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_user_resources( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_resource_count(&db, user_id); let (resources, total_resource_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_resource_count / (page_limit as u64) + (total_resource_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseResourcesResponse { resources, pages, total_resource_count, })) } pub async fn browse_user_courses( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseCourses as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseCourses as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let privacy_level = vec![]; let resource_types = vec![]; let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::course::browse( &db, Some(user_id), Some(DraftOrLive::Live), privacy_level.to_owned(), query.page.unwrap_or(0) as i32, page_limit, resource_types.to_owned(), ); let total_count_future = db::course::filtered_count( db.as_ref(), privacy_level.to_owned(), Some(user_id), Some(DraftOrLive::Live), resource_types.to_owned(), ); let (courses, (total_count, count)) = try_join!(browse_future, total_count_future,)?; let pages = (count / (page_limit as u64) + (count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(CourseBrowseResponse { courses, pages, total_course_count: total_count, })) } pub async fn follow( db: Data<PgPool>, claims: TokenUser, path: Path<Uuid>, ) -> Result<HttpResponse, error::NotFound> { let (user_id, follower_id) = (path.into_inner(), claims.0.user_id); if user_id == follower_id { return Err(error::NotFound::InternalServerError(anyhow::anyhow!( "User cannot follow self" ))); } db::user::public_user::follow(&db, user_id, follower_id).await?; Ok(HttpResponse::NoContent().finish()) } pub async fn unfollow( db: Data<PgPool>, claims: TokenUser, path: Path<Uuid>, ) -> Result<HttpResponse, error::NotFound> { let (user_id, follower_id) = (path.into_inner(), claims.0.user_id); db::user::public_user::unfollow(&db, user_id, follower_id).await?; Ok(HttpResponse::NoContent().finish()) } pub async fn browse_user_followers( db: Data<PgPool>, _auth: TokenUser, path: Path<Uuid>, query: Option<Query<<user::BrowseFollowers as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseFollowers as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_followers( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_follower_count(db.as_ref(), user_id); let (followers, total_follower_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_follower_count / (page_limit as u64) + (total_follower_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseFollowersResponse { followers, pages, total_follower_count, })) } pub async fn browse_user_followings( db: Data<PgPool>, _auth: TokenUser, path: Path<Uuid>, query: Option<Query<<user::BrowseFollowing as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseFollowing as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_following( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_following_count(db.as_ref(), user_id); let (followings, total_following_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_following_count / (page_limit as u64) + (total_following_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseFollowingsResponse { followings, pages, total_following_count, })) } async fn page_limit(page_limit: Option<u32>) -> anyhow::Result<u32> { if let Some(limit) = page_limit { match limit > 0 && limit <= MAX_PAGE_LIMIT { true => Ok(limit), false => Err(anyhow::anyhow!("Page limit should be within 1-100")), } } else { Ok(DEFAULT_PAGE_LIMIT) } }
use actix_web::{ web::{Data, Json, Path, Query}, HttpResponse, }; use futures::try_join; use shared::{ api::{endpoints::user, ApiEndpoint}, domain::{ asset::DraftOrLive, course::CourseBrowseResponse, jig::JigBrowseResponse, user::public_user::{ BrowsePublicUserFollowersResponse as BrowseFollowersResponse, BrowsePublicUserFollowingResponse as BrowseFollowingsResponse, BrowsePublicUserResourcesResponse as BrowseResourcesResponse, BrowsePublicUserResponse, PublicUser, SearchPublicUserResponse, }, }, }; use sqlx::PgPool; use uuid::Uuid; use crate::{ db, error::{self, ServiceKind}, extractor::TokenUser, http::endpoints::course::{DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT}, service::ServiceData, }; pub async fn get( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, ) -> Result<Json<<user::GetPublicUser as ApiEndpoint>::Res>, error::NotFound> { let user_id = path.into_inner(); let user: PublicUser = db::user::public_user::get(&db, user_id).await?; Ok(Json(user)) } pub async fn search( db: Data<PgPool>, claims: Option<TokenUser>, algolia: ServiceData<crate::algolia::Client>, query: Option<Query<<user::Search as ApiEndpoint>::Req>>, ) -> Result<Json<<user::Search as ApiEndpoint>::Res>, error::Service> { let query = query.map_or_else(Default::default, Query::into_inner); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::Service::InternalServerError(e))?; let user_id = db::user::public_user::auth_claims(&db, claims, query.user_id).await?; let (ids, pages, total_hits) = algolia .search_public_user( &query.q, query.username, query.name, user_id, query.language, query.organization, query.persona, page_limit, query.page, ) .await? .ok_or_else(|| error::Service::DisabledService(ServiceKind::Algolia))?; let users: Vec<_> = db::user::public_user::get_by_ids(db.as_ref(), &ids).await?; Ok(Json(SearchPublicUserResponse { users, pages, total_user_count: total_hits, })) } pub async fn browse( db: Data<PgPool>, _auth: Option<TokenUser>, query: Option<Query<<user::BrowsePublicUser as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowsePublicUser as ApiEndpoint>::Res>, error::NotFound> { let query = query.map_or_else(Default::default, Query::into_inner); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_users(&db, query.page.unwrap_or(0), page_limit as u64); let total_count_future = db::user::public_user::total_user_count(db.as_ref()); let (users, total_user_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_user_count / (page_limit as u64) + (total_user_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowsePublicUserResponse { users, pages, total_user_count, })) } pub async fn browse_user_jigs( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseUserJigs as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseUserJigs as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let privacy_level = vec![]; let resource_types = vec![]; let browse_future = db::jig::browse( &db, Some(user_id), None, Some(DraftOrLive::Live), privacy_level.to_owned(), Some(false), query.page.unwrap_or(0) as i32, page_limit, resource_types.to_owned(), ); let total_count_future = db::jig::filtered_count( db.as_ref(), privacy_level.to_owned(), Some(false), Some(user_id), None, Some(DraftOrLive::Live), resource_types.to_owned(), ); let (jigs, (total_count, count)) = try_join!(browse_future, total_count_future,)?; let pages = (count / (page_limit as u64) + (count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(JigBrowseResponse { jigs, pages, total_jig_count: total_count, })) } pub async fn browse_user_resources( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseResources as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseResources as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_user_resources( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_resource_count(&db, user_id); let (resources, total_resource_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_resource_count / (page_limit as u64) + (total_resource_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseResourcesResponse { resources, pages, total_resource_count, })) } pub async fn browse_user_courses( db: Data<PgPool>, _auth: Option<TokenUser>, path: Path<Uuid>, query: Option<Query<<user::BrowseCourses as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseCourses as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let privacy_level = vec![]; let resource_types = vec![]; let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::course::browse( &db, Some(user_id), Some(DraftOrLive::Live), privacy_level.to_owned(), query.page.unwrap_or(0) as i32, page_limit, resource_types.to_owned(), ); let total_count_future = db::course::filtered_count( db.as_ref(), privacy_level.to_owned(), Some(user_id), Some(DraftOrLive::Live), resource_types.to_owned(), ); let (courses, (total_count, count)) = try_join!(browse_future, total_count_future,)?; let pages = (count / (page_limit as u64) + (count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(CourseBrowseResponse { courses, pages, total_course_count: total_count, })) } pub async fn follow( db: Data<PgPool>, claims: TokenUser, path: Path<Uuid>, ) -> Result<HttpResponse, error::NotFound> { let (user_id, follower_id) = (path.into_inner(), claims.0.user_id); if user_id == follower_id { return Err(error::NotFound::InternalServerError(anyhow::anyhow!( "User cannot follow self" ))); } db::user::public_user::follow(&db, user_id, follower_id).await?; Ok(HttpResponse::NoContent().finish()) } pub async fn unfollow( db: Data<PgPool>, claims: TokenUser, path: Path<Uuid>, ) -> Result<HttpResponse, error::NotFound> { let (user_id, follower_id) = (path.into_inner(), claims.0.user_id); db::user::public_user::unfollow(&db, user_id, follower_id).await?; Ok(HttpResponse::NoContent().finish()) } pub async fn browse_user_followers( db: Data<PgPool>, _auth: TokenUser, path: Path<Uuid>, query: Option<Query<<user::BrowseFollowers as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseFollowers as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_followers( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_follower_count(db.as_ref(), user_id); let (followers, total_follower_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_follower_count / (page_limit as u64) + (total_follower_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseFollowersResponse { followers, pages, total_follower_count, })) } pub async fn browse_user_followings( db: Data<PgPool>, _auth: TokenUser, path: Path<Uuid>, query: Option<Query<<user::BrowseFollowing as ApiEndpoint>::Req>>, ) -> Result<Json<<user::BrowseFollowing as ApiEndpoint>::Res>, error::NotFound> { let (query, user_id) = ( query.map_or_else(Default::default, Query::into_inner), path.into_inner(), ); let page_limit = page_limit(query.page_limit) .await .map_err(|e| error::NotFound::InternalServerError(e))?; let browse_future = db::user::public_user::browse_following( &db, user_id, query.page.unwrap_or(0), page_limit as u64, ); let total_count_future = db::user::public_user::total_following_count(db.as_ref(), user_id); let (followings, total_following_count) = try_join!(browse_future, total_count_future,)?; let pages = (total_following_count / (page_limit as u64) + (total_following_count % (page_limit as u64) != 0) as u64) as u32; Ok(Json(BrowseFollowingsResponse { followings, pages, total_following_count, })) } async fn page_limit(page_limit: Option<u32>) -> anyhow::Result<u32> { if let Some(limit) = page_limit { match limit > 0
}
&& limit <= MAX_PAGE_LIMIT { true => Ok(limit), false => Err(anyhow::anyhow!("Page limit should be within 1-100")), } } else { Ok(DEFAULT_PAGE_LIMIT) }
function_block-random_span
[ { "content": "pub fn search(state: Rc<State>, page: Option<u32>) {\n\n state.loader.load(clone!(state => async move {\n\n match state.search_mode.get_cloned() {\n\n SearchMode::Sticker(_) => search_async(Rc::clone(&state), page.unwrap_or_default()).await,\n\n SearchMode::Web(_) =...
Rust
src/levels/level_list.rs
yancouto/functional
86e9f0d59e84983f0e0604b74286832af0b38da1
use serde::Deserialize; use super::{BaseLevel, GameLevel, TestCase}; use crate::prelude::*; fn get_true() -> bool { true } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevel { pub name: String, pub description: String, pub extra_info: Option<String>, pub test_cases: Vec1<(String, String)>, pub solutions: Vec1<String>, #[serde(default)] pub wrong_solutions: Vec<String>, #[serde(default)] pub provides_constant: bool, #[serde(default = "get_true")] pub show_constants: bool, #[serde(default)] pub before_level_constants: Vec<(String, String)>, #[serde(default)] pub extra_info_is_hint: bool, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JSection { pub name: SectionName, pub levels: Vec1<JLevel>, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevelConfig { pub sections: Vec1<JSection>, pub tests: Vec1<(String, String)>, } const RAW_LEVEL_CONFIG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/level_config.json")); pub fn raw_load_level_config() -> JLevelConfig { serde_json::from_slice(RAW_LEVEL_CONFIG).expect("Invalid json") } fn load_all() -> Vec1<Section> { let config = raw_load_level_config(); config.sections.mapped(|s| { let section_name = s.name; Section { name: s.name, levels: { if cfg!(feature = "demo") && s.name > SectionName::Boolean { vec![] } else { let mut idx = 0; s.levels .mapped(|l| { if l.extra_info_is_hint { debug_assert!(l.extra_info.is_some()); } let level = GameLevel { base: BaseLevel { name: l.name, description: l.description, extra_info: l.extra_info, test_cases: l .test_cases .mapped(|t| TestCase::from_or_fail(&t.0, &t.1)), extra_info_is_hint: l.extra_info_is_hint, }, idx, section: section_name, solutions: l.solutions, wrong_solutions: l.wrong_solutions, show_constants: l.show_constants, }; idx += 1; level }) .into() } }, } }) } #[derive( Debug, strum::Display, strum::EnumIter, PartialEq, Eq, Hash, Clone, Copy, Deserialize, PartialOrd, Ord, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum SectionName { Basic, Boolean, #[strum(serialize = "pair and list")] #[serde(rename = "pair and list")] PairAndList, Recursion, Numerals, #[strum(serialize = "more numerals")] #[serde(rename = "more numerals")] MoreNumerals, } pub struct Section { pub name: SectionName, pub levels: Vec<GameLevel>, } lazy_static! { pub static ref LEVELS: Vec1<Section> = load_all(); } #[cfg(test)] mod test { use std::{collections::HashSet, time::Duration}; use rayon::prelude::*; use strum::IntoEnumIterator; use super::{ super::{base::Level, get_result}, * }; use crate::{ interpreter::{interpreter::test::interpret_ok, ConstantProvider}, save_system::{LevelResult, SaveProfile} }; #[test] fn test_level_load() { assert!(LEVELS.len() > 0); } #[test] fn unique_names() { let names = LEVELS .iter() .flat_map(|s| &s.levels) .map(|l| l.base.name.clone()) .collect::<HashSet<_>>(); assert_eq!( names.len(), LEVELS.iter().flat_map(|s| &s.levels).count(), "Some name is duplicated in the levels definition" ); } #[test] fn test_jsonnet_tests() { raw_load_level_config() .tests .into_iter() .for_each(|(a, b)| { assert_eq!(interpret_ok(&a), interpret_ok(&b), "'{}' != '{}'", &a, &b) }); } fn solution_section(section: SectionName) { let mut all_levels_so_far = Vec::with_capacity(LEVELS.len()); LEVELS .iter() .filter(|s| s.name <= section) .flat_map(|s| s.levels.iter()) .for_each(|l| { all_levels_so_far.push(l.base.name.as_str()); if l.section < section { return; } l.solutions.par_iter().for_each(|s| { let r = Level::GameLevel(l) .test( s.chars(), ConstantProvider::new( l.into(), Some(Arc::new(SaveProfile::fake(all_levels_so_far.clone()))), ), ) .expect(&format!( "On '{}' failed to compile solution {}", l.base.name, s )); r.runs.iter().for_each(|r| { assert!( r.is_correct(), "Code '{}' does not reduce to '{}' on level '{}', instead reduced to {:?}", r.test_expression, r.expected_result, l.base.name, r.result.clone().map(|r| format!("{}", r.term)), ) }); assert_matches!(get_result(&Ok(r)), LevelResult::Success { .. }); }) }); } fn all_sections(sections: Vec<SectionName>) { assert_eq!( SectionName::iter().collect::<HashSet<_>>(), sections.into_iter().collect::<HashSet<_>>() ); } macro_rules! solution_tests { ($($name:ident),*) => { $( #[test] #[allow(non_snake_case)] fn $name () { solution_section(SectionName::$name); } )* #[test] fn test_cover_all_sections() { all_sections(vec![$(SectionName::$name),*]) } } } solution_tests!( Basic, Boolean, Numerals, PairAndList, Recursion, MoreNumerals ); #[test] fn test_wrong_solutions() { LEVELS.iter().flat_map(|s| &s.levels).for_each(|l| { l.wrong_solutions.iter().for_each(|s| { assert_matches!( get_result(&Level::GameLevel(l).test(s.chars(), ConstantProvider::all())), LevelResult::Failure, "Code was solution {} on level {}", s, l.base.name ) }) }); } fn fake_bterm() -> bl::BTerm { bl::BTerm { width_pixels: W as u32, height_pixels: H as u32, original_height_pixels: H as u32, original_width_pixels: W as u32, fps: 30.0, frame_time_ms: 10.0, active_console: 0, key: None, mouse_pos: (0, 0), left_click: false, shift: false, control: false, alt: false, web_button: None, quitting: false, post_scanlines: false, post_screenburn: false, screen_burn_color: bl::RGB::from_u8(0, 1, 1), } } #[test] fn test_out_of_space() { use crate::{ drawables::BasicTextEditor, gamestates::{ base::{with_current_console, EventTickData, GSData, TickData}, editor::EditorState }, save_system::SaveProfile }; let fake_profile = Arc::new(SaveProfile::fake(vec![])); let mut term = fake_bterm(); bl::BACKEND_INTERNAL .lock() .consoles .push(bl::DisplayConsole { console: box bl::VirtualConsole::new(bl::Point::new(W, H)), shader_index: 0, font_index: 0, }); LEVELS.iter().flat_map(|s| &s.levels).for_each(|l| { let mut gs_data = GSData { cur: box EditorState::<BasicTextEditor>::new(l.into(), fake_profile.clone()), time: Duration::new(0, 0), }; with_current_console(0, |mut c| { let input = bl::INPUT.lock(); let data = TickData::new( &gs_data, EventTickData::default(), &mut c, &mut term, &input, None, ); gs_data.cur.tick(data); }) }); } }
use serde::Deserialize; use super::{BaseLevel, GameLevel, TestCase}; use crate::prelude::*; fn get_true() -> bool { true } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevel { pub name: String, pub description: String, pub extra_info: Option<String>, pub test_cases: Vec1<(String, String)>, pub solutions: Vec1<String>, #[serde(default)] pub wrong_solutions: Vec<String>, #[serde(default)] pub provides_constant: bool, #[serde(default = "get_true")] pub show_constants: bool, #[serde(default)] pub before_level_constants: Vec<(String, String)>, #[serde(default)] pub extra_info_is_hint: bool, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JSection { pub name: SectionName, pub levels: Vec1<JLevel>, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct JLevelConfig { pub sections: Vec1<JSection>, pub tests: Vec1<(String, String)>, } const RAW_LEVEL_CONFIG: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/level_config.json")); pub fn raw_load_level_config() -> JLevelConfig { serde_json::from_slice(RAW_LEVEL_CONFIG).expect("Invalid json") } fn load_all() -> Vec1<Section> { let config = raw_load_level_config(); config.sections.mapped(|s| { let section_name = s.name; Section { name: s.name, levels: { if cfg!(feature = "demo") && s.name > SectionName::Boolea
ections() { all_sections(vec![$(SectionName::$name),*]) } } } solution_tests!( Basic, Boolean, Numerals, PairAndList, Recursion, MoreNumerals ); #[test] fn test_wrong_solutions() { LEVELS.iter().flat_map(|s| &s.levels).for_each(|l| { l.wrong_solutions.iter().for_each(|s| { assert_matches!( get_result(&Level::GameLevel(l).test(s.chars(), ConstantProvider::all())), LevelResult::Failure, "Code was solution {} on level {}", s, l.base.name ) }) }); } fn fake_bterm() -> bl::BTerm { bl::BTerm { width_pixels: W as u32, height_pixels: H as u32, original_height_pixels: H as u32, original_width_pixels: W as u32, fps: 30.0, frame_time_ms: 10.0, active_console: 0, key: None, mouse_pos: (0, 0), left_click: false, shift: false, control: false, alt: false, web_button: None, quitting: false, post_scanlines: false, post_screenburn: false, screen_burn_color: bl::RGB::from_u8(0, 1, 1), } } #[test] fn test_out_of_space() { use crate::{ drawables::BasicTextEditor, gamestates::{ base::{with_current_console, EventTickData, GSData, TickData}, editor::EditorState }, save_system::SaveProfile }; let fake_profile = Arc::new(SaveProfile::fake(vec![])); let mut term = fake_bterm(); bl::BACKEND_INTERNAL .lock() .consoles .push(bl::DisplayConsole { console: box bl::VirtualConsole::new(bl::Point::new(W, H)), shader_index: 0, font_index: 0, }); LEVELS.iter().flat_map(|s| &s.levels).for_each(|l| { let mut gs_data = GSData { cur: box EditorState::<BasicTextEditor>::new(l.into(), fake_profile.clone()), time: Duration::new(0, 0), }; with_current_console(0, |mut c| { let input = bl::INPUT.lock(); let data = TickData::new( &gs_data, EventTickData::default(), &mut c, &mut term, &input, None, ); gs_data.cur.tick(data); }) }); } }
n { vec![] } else { let mut idx = 0; s.levels .mapped(|l| { if l.extra_info_is_hint { debug_assert!(l.extra_info.is_some()); } let level = GameLevel { base: BaseLevel { name: l.name, description: l.description, extra_info: l.extra_info, test_cases: l .test_cases .mapped(|t| TestCase::from_or_fail(&t.0, &t.1)), extra_info_is_hint: l.extra_info_is_hint, }, idx, section: section_name, solutions: l.solutions, wrong_solutions: l.wrong_solutions, show_constants: l.show_constants, }; idx += 1; level }) .into() } }, } }) } #[derive( Debug, strum::Display, strum::EnumIter, PartialEq, Eq, Hash, Clone, Copy, Deserialize, PartialOrd, Ord, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum SectionName { Basic, Boolean, #[strum(serialize = "pair and list")] #[serde(rename = "pair and list")] PairAndList, Recursion, Numerals, #[strum(serialize = "more numerals")] #[serde(rename = "more numerals")] MoreNumerals, } pub struct Section { pub name: SectionName, pub levels: Vec<GameLevel>, } lazy_static! { pub static ref LEVELS: Vec1<Section> = load_all(); } #[cfg(test)] mod test { use std::{collections::HashSet, time::Duration}; use rayon::prelude::*; use strum::IntoEnumIterator; use super::{ super::{base::Level, get_result}, * }; use crate::{ interpreter::{interpreter::test::interpret_ok, ConstantProvider}, save_system::{LevelResult, SaveProfile} }; #[test] fn test_level_load() { assert!(LEVELS.len() > 0); } #[test] fn unique_names() { let names = LEVELS .iter() .flat_map(|s| &s.levels) .map(|l| l.base.name.clone()) .collect::<HashSet<_>>(); assert_eq!( names.len(), LEVELS.iter().flat_map(|s| &s.levels).count(), "Some name is duplicated in the levels definition" ); } #[test] fn test_jsonnet_tests() { raw_load_level_config() .tests .into_iter() .for_each(|(a, b)| { assert_eq!(interpret_ok(&a), interpret_ok(&b), "'{}' != '{}'", &a, &b) }); } fn solution_section(section: SectionName) { let mut all_levels_so_far = Vec::with_capacity(LEVELS.len()); LEVELS .iter() .filter(|s| s.name <= section) .flat_map(|s| s.levels.iter()) .for_each(|l| { all_levels_so_far.push(l.base.name.as_str()); if l.section < section { return; } l.solutions.par_iter().for_each(|s| { let r = Level::GameLevel(l) .test( s.chars(), ConstantProvider::new( l.into(), Some(Arc::new(SaveProfile::fake(all_levels_so_far.clone()))), ), ) .expect(&format!( "On '{}' failed to compile solution {}", l.base.name, s )); r.runs.iter().for_each(|r| { assert!( r.is_correct(), "Code '{}' does not reduce to '{}' on level '{}', instead reduced to {:?}", r.test_expression, r.expected_result, l.base.name, r.result.clone().map(|r| format!("{}", r.term)), ) }); assert_matches!(get_result(&Ok(r)), LevelResult::Success { .. }); }) }); } fn all_sections(sections: Vec<SectionName>) { assert_eq!( SectionName::iter().collect::<HashSet<_>>(), sections.into_iter().collect::<HashSet<_>>() ); } macro_rules! solution_tests { ($($name:ident),*) => { $( #[test] #[allow(non_snake_case)] fn $name () { solution_section(SectionName::$name); } )* #[test] fn test_cover_all_s
random
[ { "content": "fn get_level_config_json() -> String {\n\n match std::process::Command::new(\"jsonnet\")\n\n .args(&[\n\n \"-J\",\n\n \"src/levels/config\",\n\n \"src/levels/config/level_config.jsonnet\",\n\n ])\n\n .output()\n\n {\n\n Ok(o) if !o...
Rust
src/render/src/encoder.rs
pravic/gfx
f0fde6d3d05412358d08707f66c544fb48c6a531
#![deny(missing_docs)] use std::mem; use draw_state::target::{Depth, Stencil}; use gfx_core::{Device, IndexType, Resources, VertexCount}; use gfx_core::{draw, format, handle, tex}; use gfx_core::factory::{cast_slice, Typed}; use mesh; use pso; #[allow(missing_docs)] #[derive(Clone, Debug, PartialEq)] pub enum UpdateError<T> { OutOfBounds { target: T, source: T, }, UnitCountMismatch { target: usize, slice: usize, }, } pub struct Encoder<R: Resources, C: draw::CommandBuffer<R>> { command_buffer: C, raw_pso_data: pso::RawDataSet<R>, handles: handle::Manager<R>, } impl<R: Resources, C: draw::CommandBuffer<R>> From<C> for Encoder<R, C> { fn from(combuf: C) -> Encoder<R, C> { Encoder { command_buffer: combuf, raw_pso_data: pso::RawDataSet::new(), handles: handle::Manager::new(), } } } impl<R: Resources, C: draw::CommandBuffer<R>> Encoder<R, C> { pub fn flush<D>(&mut self, device: &mut D) where D: Device<Resources=R, CommandBuffer=C> { device.pin_submitted_resources(&self.handles); device.submit(&mut self.command_buffer); self.command_buffer.reset(); self.handles.clear(); } pub fn clone_empty(&self) -> Encoder<R, C> { Encoder { command_buffer: self.command_buffer.clone_empty(), raw_pso_data: pso::RawDataSet::new(), handles: handle::Manager::new(), } } pub fn update_buffer<T: Copy>(&mut self, buf: &handle::Buffer<R, T>, data: &[T], offset_elements: usize) -> Result<(), UpdateError<usize>> { if data.is_empty() { return Ok(()) } let elem_size = mem::size_of::<T>(); let offset_bytes = elem_size * offset_elements; let bound = data.len().wrapping_mul(elem_size) + offset_bytes; if bound <= buf.get_info().size { self.command_buffer.update_buffer( self.handles.ref_buffer(buf.raw()).clone(), cast_slice(data), offset_bytes); Ok(()) } else { Err(UpdateError::OutOfBounds { target: bound, source: buf.get_info().size, }) } } pub fn update_constant_buffer<T: Copy>(&mut self, buf: &handle::Buffer<R, T>, data: &T) { use std::slice; let slice = unsafe { slice::from_raw_parts(data as *const T as *const u8, mem::size_of::<T>()) }; self.command_buffer.update_buffer( self.handles.ref_buffer(buf.raw()).clone(), slice, 0); } pub fn update_texture<S, T>(&mut self, tex: &handle::Texture<R, T::Surface>, face: Option<tex::CubeFace>, img: tex::NewImageInfo, data: &[S::DataType]) -> Result<(), UpdateError<[tex::Size; 3]>> where S: format::SurfaceTyped, S::DataType: Copy, T: format::Formatted<Surface = S>, { if data.is_empty() { return Ok(()) } let target_count = img.get_texel_count(); if target_count != data.len() { return Err(UpdateError::UnitCountMismatch { target: target_count, slice: data.len(), }) } let dim = tex.get_info().kind.get_dimensions(); if !img.is_inside(dim) { let (w, h, d, _) = dim; return Err(UpdateError::OutOfBounds { target: [ img.xoffset + img.width, img.yoffset + img.height, img.zoffset + img.depth, ], source: [w, h, d], }) } self.command_buffer.update_texture( self.handles.ref_texture(tex.raw()).clone(), tex.get_info().kind, face, cast_slice(data), img.convert(T::get_format())); Ok(()) } fn draw_indexed<T>(&mut self, buf: &handle::Buffer<R, T>, ty: IndexType, slice: &mesh::Slice<R>, base: VertexCount, instances: draw::InstanceOption) { self.command_buffer.bind_index(self.handles.ref_buffer(buf.raw()).clone(), ty); self.command_buffer.call_draw_indexed(slice.start, slice.end - slice.start, base, instances); } fn draw_slice(&mut self, slice: &mesh::Slice<R>, instances: draw::InstanceOption) { match slice.kind { mesh::SliceKind::Vertex => self.command_buffer.call_draw( slice.start, slice.end - slice.start, instances), mesh::SliceKind::Index8(ref buf, base) => self.draw_indexed(buf, IndexType::U8, slice, base, instances), mesh::SliceKind::Index16(ref buf, base) => self.draw_indexed(buf, IndexType::U16, slice, base, instances), mesh::SliceKind::Index32(ref buf, base) => self.draw_indexed(buf, IndexType::U32, slice, base, instances), } } pub fn clear<T: format::RenderFormat>(&mut self, view: &handle::RenderTargetView<R, T>, value: T::View) where T::View: Into<draw::ClearColor> { let target = self.handles.ref_rtv(view.raw()).clone(); self.command_buffer.clear_color(target, value.into()) } pub fn clear_depth<T: format::DepthFormat>(&mut self, view: &handle::DepthStencilView<R, T>, depth: Depth) { let target = self.handles.ref_dsv(view.raw()).clone(); self.command_buffer.clear_depth_stencil(target, Some(depth), None) } pub fn clear_stencil<T: format::StencilFormat>(&mut self, view: &handle::DepthStencilView<R, T>, stencil: Stencil) { let target = self.handles.ref_dsv(view.raw()).clone(); self.command_buffer.clear_depth_stencil(target, None, Some(stencil)) } pub fn draw<D: pso::PipelineData<R>>(&mut self, slice: &mesh::Slice<R>, pipeline: &pso::PipelineState<R, D::Meta>, user_data: &D) { let (pso, _) = self.handles.ref_pso(pipeline.get_handle()); self.command_buffer.bind_pipeline_state(pso.clone()); self.raw_pso_data.clear(); user_data.bake_to(&mut self.raw_pso_data, pipeline.get_meta(), &mut self.handles); self.command_buffer.bind_vertex_buffers(self.raw_pso_data.vertex_buffers.clone()); self.command_buffer.bind_pixel_targets(self.raw_pso_data.pixel_targets.clone()); self.command_buffer.set_ref_values(self.raw_pso_data.ref_values); self.command_buffer.set_scissor(self.raw_pso_data.scissor); self.command_buffer.bind_constant_buffers(&self.raw_pso_data.constant_buffers); for &(location, value) in &self.raw_pso_data.global_constants { self.command_buffer.bind_global_constant(location, value); } self.command_buffer.bind_unordered_views(&self.raw_pso_data.unordered_views); self.command_buffer.bind_resource_views(&self.raw_pso_data.resource_views); self.command_buffer.bind_samplers(&self.raw_pso_data.samplers); self.draw_slice(slice, slice.instances); } }
#![deny(missing_docs)] use std::mem; use draw_state::target::{Depth, Stencil}; use gfx_core::{Device, IndexType, Resources, VertexCount}; use gfx_core::{draw, format, handle, tex}; use gfx_core::factory::{cast_slice, Typed}; use mesh; use pso; #[allow(missing_docs)] #[derive(Clone, Debug, PartialEq)] pub enum UpdateError<T> { OutOfBounds { target: T, source: T, }, UnitCountMismatch { target: usize, slice: usize, }, } pub struct Encoder<R: Resources, C: draw::CommandBuffer<R>> { command_buffer: C, raw_pso_data: pso::RawDataSet<R>, handles: handle::Manager<R>, } impl<R: Resources, C: draw::CommandBuf
Format>(&mut self, view: &handle::RenderTargetView<R, T>, value: T::View) where T::View: Into<draw::ClearColor> { let target = self.handles.ref_rtv(view.raw()).clone(); self.command_buffer.clear_color(target, value.into()) } pub fn clear_depth<T: format::DepthFormat>(&mut self, view: &handle::DepthStencilView<R, T>, depth: Depth) { let target = self.handles.ref_dsv(view.raw()).clone(); self.command_buffer.clear_depth_stencil(target, Some(depth), None) } pub fn clear_stencil<T: format::StencilFormat>(&mut self, view: &handle::DepthStencilView<R, T>, stencil: Stencil) { let target = self.handles.ref_dsv(view.raw()).clone(); self.command_buffer.clear_depth_stencil(target, None, Some(stencil)) } pub fn draw<D: pso::PipelineData<R>>(&mut self, slice: &mesh::Slice<R>, pipeline: &pso::PipelineState<R, D::Meta>, user_data: &D) { let (pso, _) = self.handles.ref_pso(pipeline.get_handle()); self.command_buffer.bind_pipeline_state(pso.clone()); self.raw_pso_data.clear(); user_data.bake_to(&mut self.raw_pso_data, pipeline.get_meta(), &mut self.handles); self.command_buffer.bind_vertex_buffers(self.raw_pso_data.vertex_buffers.clone()); self.command_buffer.bind_pixel_targets(self.raw_pso_data.pixel_targets.clone()); self.command_buffer.set_ref_values(self.raw_pso_data.ref_values); self.command_buffer.set_scissor(self.raw_pso_data.scissor); self.command_buffer.bind_constant_buffers(&self.raw_pso_data.constant_buffers); for &(location, value) in &self.raw_pso_data.global_constants { self.command_buffer.bind_global_constant(location, value); } self.command_buffer.bind_unordered_views(&self.raw_pso_data.unordered_views); self.command_buffer.bind_resource_views(&self.raw_pso_data.resource_views); self.command_buffer.bind_samplers(&self.raw_pso_data.samplers); self.draw_slice(slice, slice.instances); } }
fer<R>> From<C> for Encoder<R, C> { fn from(combuf: C) -> Encoder<R, C> { Encoder { command_buffer: combuf, raw_pso_data: pso::RawDataSet::new(), handles: handle::Manager::new(), } } } impl<R: Resources, C: draw::CommandBuffer<R>> Encoder<R, C> { pub fn flush<D>(&mut self, device: &mut D) where D: Device<Resources=R, CommandBuffer=C> { device.pin_submitted_resources(&self.handles); device.submit(&mut self.command_buffer); self.command_buffer.reset(); self.handles.clear(); } pub fn clone_empty(&self) -> Encoder<R, C> { Encoder { command_buffer: self.command_buffer.clone_empty(), raw_pso_data: pso::RawDataSet::new(), handles: handle::Manager::new(), } } pub fn update_buffer<T: Copy>(&mut self, buf: &handle::Buffer<R, T>, data: &[T], offset_elements: usize) -> Result<(), UpdateError<usize>> { if data.is_empty() { return Ok(()) } let elem_size = mem::size_of::<T>(); let offset_bytes = elem_size * offset_elements; let bound = data.len().wrapping_mul(elem_size) + offset_bytes; if bound <= buf.get_info().size { self.command_buffer.update_buffer( self.handles.ref_buffer(buf.raw()).clone(), cast_slice(data), offset_bytes); Ok(()) } else { Err(UpdateError::OutOfBounds { target: bound, source: buf.get_info().size, }) } } pub fn update_constant_buffer<T: Copy>(&mut self, buf: &handle::Buffer<R, T>, data: &T) { use std::slice; let slice = unsafe { slice::from_raw_parts(data as *const T as *const u8, mem::size_of::<T>()) }; self.command_buffer.update_buffer( self.handles.ref_buffer(buf.raw()).clone(), slice, 0); } pub fn update_texture<S, T>(&mut self, tex: &handle::Texture<R, T::Surface>, face: Option<tex::CubeFace>, img: tex::NewImageInfo, data: &[S::DataType]) -> Result<(), UpdateError<[tex::Size; 3]>> where S: format::SurfaceTyped, S::DataType: Copy, T: format::Formatted<Surface = S>, { if data.is_empty() { return Ok(()) } let target_count = img.get_texel_count(); if target_count != data.len() { return Err(UpdateError::UnitCountMismatch { target: target_count, slice: data.len(), }) } let dim = tex.get_info().kind.get_dimensions(); if !img.is_inside(dim) { let (w, h, d, _) = dim; return Err(UpdateError::OutOfBounds { target: [ img.xoffset + img.width, img.yoffset + img.height, img.zoffset + img.depth, ], source: [w, h, d], }) } self.command_buffer.update_texture( self.handles.ref_texture(tex.raw()).clone(), tex.get_info().kind, face, cast_slice(data), img.convert(T::get_format())); Ok(()) } fn draw_indexed<T>(&mut self, buf: &handle::Buffer<R, T>, ty: IndexType, slice: &mesh::Slice<R>, base: VertexCount, instances: draw::InstanceOption) { self.command_buffer.bind_index(self.handles.ref_buffer(buf.raw()).clone(), ty); self.command_buffer.call_draw_indexed(slice.start, slice.end - slice.start, base, instances); } fn draw_slice(&mut self, slice: &mesh::Slice<R>, instances: draw::InstanceOption) { match slice.kind { mesh::SliceKind::Vertex => self.command_buffer.call_draw( slice.start, slice.end - slice.start, instances), mesh::SliceKind::Index8(ref buf, base) => self.draw_indexed(buf, IndexType::U8, slice, base, instances), mesh::SliceKind::Index16(ref buf, base) => self.draw_indexed(buf, IndexType::U16, slice, base, instances), mesh::SliceKind::Index32(ref buf, base) => self.draw_indexed(buf, IndexType::U32, slice, base, instances), } } pub fn clear<T: format::Render
random
[ { "content": "/// Create the proxy target views (RTV and DSV) for the attachments of the\n\n/// main framebuffer. These have GL names equal to 0.\n\n/// Not supposed to be used by the users directly.\n\npub fn create_main_targets_raw(dim: d::tex::Dimensions, color_format: d::format::SurfaceType, depth_format: d...
Rust
website-api-tester/src/main.rs
sovrin-foundation/token-website
9e870c49a5e99b5a6d072cc585d229ce0257c0aa
#[macro_use] extern crate trace_macros; use isahc::prelude::*; use serde::{Serialize, Deserialize}; use sha2::Digest; use sodiumoxide::crypto::sign::{ sign_detached, gen_keypair, ed25519::SecretKey }; use structopt::StructOpt; use web_view::*; #[derive(Debug, StructOpt)] #[structopt( name = "basic", version = "0.1", about = "Sovrin Foundation Token Website" )] struct Opt { #[structopt(subcommand)] pub cmd: Command } #[derive(Debug, StructOpt)] enum Command { #[structopt(name = "sign")] Sign { #[structopt(short, long)] key: Option<String>, #[structopt(name = "TOKEN")] token: String } } #[derive(Serialize)] struct PaymentAddressChallengeReponse { address: String, challenge: String, signature: String } #[derive(Debug, Clone, Serialize, Deserialize)] struct WebCmd { consents: String, data: String, path: String, verb: String, url: String, } const MAIN_PAGE_1: &str = r##" <html> <head lang="en"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <style> .table-row { margin: 0px 0px 15px 0px; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-12">&nbsp;</div> </div> <div class="row table-row"> <div class="col-md-12"><span id="error" style="color:red;"></span></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>URL</strong></div> <div class="col-md-10"><input id="test_url" type="url" placeholder="https://127.0.0.1:8000/api/v1" width="400px"></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Paths</strong></div> <div class="col-md-4"><select id="paths"> <option value="countries">countries</option> <option value="consents">consents</option> <option value="payment_address_challenge">payment_address_challenge</option> </select></div> <div class="col-md-6"><select id="consent_countries"> "##; const MAIN_PAGE_2: &str = r##" </select></div> </div> <div class="row table-row" style="margin:0px 0px 20px 0px;"> <div class="col-md-2"><strong>Commands</strong></div> <div class="col-md-2"><select id="verbs"> <option value="get">GET</option> </select></div> <div class="col-md-8"><p><strong id="verb_data_label"></strong></p><textarea id="verb_data" type="text" width="100%" height="100%"></textarea></div> </div> <div class="row table-row"> <div class="col-md-12"><button onclick="return perform_action();" width="30px" heigth="30px">Send</button></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Request</strong></div> <div class="col-md-10"><textarea id="request" readonly width="100%" height="100%"></textarea></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Response</strong></div> <div class="col-md-10"><textarea id="response" readonly width="100%" height="100%"></textarea></div> </div> </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script type="text/javascript"> function perform_action() { var o = new Object(); o.url = $('#test_url').val(); o.path = $('#paths option:selected').val(); o.verb = $('#verbs option:selected').text(); o.consents = $('#consent_countries option:selected').val(); switch (o.verb) { case "post": case "put": o.data = $('#verb_data').val(); break; default: o.data = ""; break; } window.external.invoke(JSON.stringify(o)); } function set_error(message) { $('#error').html(message); } function result_returned(request, response) { $('#request').val(request); $('#response').val(response); } $(document).ready(function() { $('#verb_data').hide(); $('#consent_countries').hide(); $('#verbs').change(function() { var selectedVerb = $(this).children("option:selected").val(); switch (selectedVerb) { case "get": case "delete": $('#verb_data').hide(); break; case "post": case "put": $('#verb_data').show(); $('#verb_data_label').html(selectedVerb.toUpperCase() + " Body Data"); break; default: $('#verb_data').hide(); break; } }); $('#paths').change(function() { var selectedPath = $(this).children("option:selected").val(); switch (selectedPath) { case "countries": $('#verbs').empty().append('<option selected="selected" value="get">GET</option>'); $('#consent_countries').hide(); break; case "consents": $('#verbs').empty().append('<option selected="selected" value="get">GET</option>'); $('#consent_countries').show(); break; case "payment_address_challenge": $('#verbs').empty().append('<option selected="selected" value="get">GET</option><option value="post">POST</option>'); $('#consent_countries').hide(); break; default: $('#verbs').empty(); $('#consent_countries').hide(); break; } }); }); </script> </body> </html> "##; fn main() { let opt = Opt::from_args(); match opt.cmd { Command::Sign { key, token } => { let (pk, sk) = match key { Some(k) => { let k1 = bs58::decode(k).into_vec().unwrap(); let sk1 = SecretKey::from_slice(k1.as_slice()).unwrap(); let pk1 = sk1.public_key(); (pk1, sk1) }, None => gen_keypair() }; let mut sha = sha2::Sha256::new(); let challenge = base64_url::decode(&token).unwrap(); sha.input(format!("\x6DSovrin Signed Message:\nLength: {}\n", challenge.len()).as_bytes()); sha.input(challenge.as_slice()); let data = sha.result(); let signature = sign_detached(data.as_slice(), &sk); let response = PaymentAddressChallengeReponse { address: format!("pay:sov:{}", bs58::encode(&pk[..]).with_check().into_string()), challenge: token, signature: base64_url::encode(&signature[..]) }; println!("key = {}", bs58::encode(sk).with_check().into_string()); println!("response = {}", serde_json::to_string(&response).unwrap()); } } }
#[macro_use] extern crate trace_macros; use isahc::prelude::*; use serde::{Serialize, Deserialize}; use sha2::Digest; use sodiumoxide::crypto::sign::{ sign_detached, gen_keypair, ed25519::SecretKey }; use structopt::StructOpt; use web_view::*; #[derive(Debug, StructOpt)] #[structopt( name = "basic", version = "0.1", about = "Sovrin Foundation Token Website" )] struct Opt { #[structopt(subcommand)] pub cmd: Command } #[derive(Debug, StructOpt)] enum Command { #[structopt(name = "sign")] Sign { #[structopt(short, long)] key: Option<String>, #[structopt(name = "TOKEN")] token: String } } #[derive(Serialize)] struct PaymentAddressChallengeReponse { address: String, challenge: String, signature: String } #[derive(Debug, Clone, Serialize, Deserialize)] struct WebCmd { consents: String, data: String, path: String, verb: String, url: String, } const MAIN_PAGE_1: &str = r##" <html> <head lang="en"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <style> .table-row { margin: 0px 0px 15px 0px; } </style> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-md-12">&nbsp;</div> </div> <div class="row table-row"> <div class="col-md-12"><span id="error" style="color:red;"></span></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>URL</strong></div> <div class="col-md-10"><input id="test_url" type="url" placeholder="https://127.0.0.1:8000/api/v1" width="400px"></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Paths</strong></div> <div class="col-md-4"><select id="paths"> <option value="countries">countries</option> <option value="consents">consents</option> <option value="payment_address_challenge">payment_address_challenge</option> </select></div> <div class="col-md-6"><select id="consent_countries"> "##; const MAIN_PAGE_2: &str = r##" </select></div> </div> <div class="row table-row" style="margin:0px 0px 20px 0px;"> <div class="col-md-2"><strong>Commands</strong></div> <div class="col-md-2"><select id="verbs"> <option value="get">GET</option> </select></div> <div class="col-md-8"><p><strong id="verb_data_label"></strong></p><textarea id="verb_data" type="text" width="100%" height="100%"></textarea></div> </div> <div class="row table-row"> <div class="col-md-12"><button onclick="return perform_action();" width="30px" heigth="30px">Send</button></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Request</strong></div> <div class="col-md-10"><textarea id="request" readonly width="100%" height="100%"></textarea></div> </div> <div class="row table-row"> <div class="col-md-2"><strong>Response</strong></div> <div class="col-md-10"><textarea id="response" readonly width="100%" height="100%"></textarea></div> </div> </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script type="text/javascript"> function perform_action() { var o = new Object(); o.url = $('#test_url').val(); o.path = $('#paths option:selected').val(); o.verb = $('#verbs option:selected').text(); o.consents = $('#consent_countries option:selected').val(); switch (o.verb) { case "post": case "put": o.data = $('#verb_data').val(); break; default: o.data = ""; break; } window.external.invoke(JSON.stringify(o)); } function set_error(message) { $('#error').html(message); } function result_returned(request, response) { $('#request').val(request); $('#response').val(response); } $(document).ready(function() { $('#verb_data').hide(); $('#consent_countries').hide(); $('#verbs').change(function() { var selectedVerb = $(this).children("option:selected").val(); switch (selectedVerb) { case "get": case "delete": $('#verb_data').hide(); break; case "post": case "put": $('#verb_data').show(); $('#verb_data_label').html(selectedVerb.toUpperCase() + " Body Data"); break; default: $('#verb_data').hide(); break; } }); $('#paths').change(function() { var selectedPath = $(this).children("option:selected").val(); switch (selectedPath) { case "countries": $('#verbs').empty().append('<option selected="selected" value="get">GET</option>'); $('#consent_countries').hide(); break; case "consents": $('#verbs').empty().append('<option selected="selected" value="get">GET</option>'); $('#consent_countries').show(); break; case "payment_address_challenge": $('#verbs').empty().append('<option selected="selected" value="get">GET</option><option value="post">POST</option>'); $('#consent_countries').hide(); break; default: $('#verbs').empty(); $('#consent_countries').hide(); break; } }); }); </script> </body> </html> "##; fn main() {
let opt = Opt::from_args(); match opt.cmd { Command::Sign { key, token } => { let (pk, sk) = match key { Some(k) => { let k1 = bs58::decode(k).into_vec().unwrap(); let sk1 = SecretKey::from_slice(k1.as_slice()).unwrap(); let pk1 = sk1.public_key(); (pk1, sk1) }, None => gen_keypair() }; let mut sha = sha2::Sha256::new(); let challenge = base64_url::decode(&token).unwrap(); sha.input(format!("\x6DSovrin Signed Message:\nLength: {}\n", challenge.len()).as_bytes()); sha.input(challenge.as_slice()); let data = sha.result(); let signature = sign_detached(data.as_slice(), &sk); let response = PaymentAddressChallengeReponse { address: format!("pay:sov:{}", bs58::encode(&pk[..]).with_check().into_string()), challenge: token, signature: base64_url::encode(&signature[..]) }; println!("key = {}", bs58::encode(sk).with_check().into_string()); println!("response = {}", serde_json::to_string(&response).unwrap()); } } }
function_block-function_prefix_line
[ { "content": "fn prompt_for_value(value_name: &str) -> String {\n\n loop {\n\n match rpassword::read_password_from_tty(Some(format!(\"Enter {}: \", value_name).as_str())) {\n\n Ok(v) => {\n\n if v.len() > 0 {\n\n return v;\n\n } else {\n\n ...
Rust
src/licensee.rs
kain88-de/spdx
6df4065871137935c4c7698ee6cf2ecbedd48a4d
use crate::{ error::{ParseError, Reason}, ExceptionId, Lexer, LicenseItem, LicenseReq, Token, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Licensee { inner: LicenseReq, } impl Licensee { pub fn new(license: LicenseItem, exception: Option<ExceptionId>) -> Self { if let LicenseItem::SPDX { or_later, .. } = &license { debug_assert!(!or_later) } Self { inner: LicenseReq { license, exception }, } } pub fn parse(original: &str) -> Result<Self, ParseError<'_>> { let mut lexer = Lexer::new(original); let license = { let lt = lexer.next().ok_or_else(|| ParseError { original, span: 0..original.len(), reason: Reason::Empty, })??; match lt.token { Token::SPDX(id) => LicenseItem::SPDX { id, or_later: false, }, Token::LicenseRef { doc_ref, lic_ref } => LicenseItem::Other { doc_ref: doc_ref.map(String::from), lic_ref: lic_ref.to_owned(), }, _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["<license>"]), }) } } }; let exception = match lexer.next() { None => None, Some(lt) => { let lt = lt?; match lt.token { Token::With => { let lt = lexer.next().ok_or_else(|| ParseError { original, span: lt.span, reason: Reason::Empty, })??; match lt.token { Token::Exception(exc) => Some(exc), _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["<exception>"]), }) } } } _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["WITH"]), }) } } } }; Ok(Licensee { inner: LicenseReq { license, exception }, }) } pub fn satisfies(&self, req: &LicenseReq) -> bool { match (&self.inner.license, &req.license) { (LicenseItem::SPDX { id: a, .. }, LicenseItem::SPDX { id: b, or_later }) => { if a.index != b.index { if *or_later { let a_name = &a.name[..a.name.rfind('-').unwrap_or_else(|| a.name.len())]; let b_name = &b.name[..b.name.rfind('-').unwrap_or_else(|| b.name.len())]; if a_name != b_name || a.name < b.name { return false; } } else { return false; } } } ( LicenseItem::Other { doc_ref: doca, lic_ref: lica, }, LicenseItem::Other { doc_ref: docb, lic_ref: licb, }, ) => { if doca != docb || lica != licb { return false; } } _ => return false, } req.exception == self.inner.exception } } impl PartialOrd<LicenseReq> for Licensee { fn partial_cmp(&self, o: &LicenseReq) -> Option<std::cmp::Ordering> { self.inner.partial_cmp(o) } } impl PartialEq<LicenseReq> for Licensee { fn eq(&self, o: &LicenseReq) -> bool { self.inner.eq(o) } } #[cfg(test)] mod test { use crate::{exception_id, license_id, LicenseItem, LicenseReq, Licensee}; const LICENSEES: &[&str] = &[ "LicenseRef-Embark-Proprietary", "BSD-2-Clause", "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause-FreeBSD", "BSL-1.0", "Zlib", "CC0-1.0", "FTL", "ISC", "MIT", "MPL-2.0", "BSD-3-Clause", "Unicode-DFS-2016", "Unlicense", "Apache-2.0", ]; #[test] fn handles_or_later() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let mpl_id = license_id("MPL-2.0").unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: mpl_id, or_later: true, }, exception: None, }; assert!(licensees.binary_search_by(|l| l.inner.cmp(&req)).is_err()); match &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner .license { LicenseItem::SPDX { id, .. } => assert_eq!(*id, mpl_id), o => panic!("unexepcted {:?}", o), } } #[test] fn handles_exceptions() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let apache_id = license_id("Apache-2.0").unwrap(); let llvm_exc = exception_id("LLVM-exception").unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: apache_id, or_later: false, }, exception: Some(llvm_exc), }; assert_eq!( &req, &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner ); } #[test] fn handles_license_ref() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let req = LicenseReq { license: LicenseItem::Other { doc_ref: None, lic_ref: "Embark-Proprietary".to_owned(), }, exception: None, }; assert_eq!( &req, &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner ); } #[test] fn handles_close() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); for id in &["BSD-2-Clause", "BSD-2-Clause-FreeBSD"] { let lic_id = license_id(id).unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: lic_id, or_later: true, }, exception: None, }; assert!(licensees.binary_search_by(|l| l.inner.cmp(&req)).is_err()); match &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner .license { LicenseItem::SPDX { id, .. } => assert_eq!(*id, lic_id), o => panic!("unexepcted {:?}", o), } } } }
use crate::{ error::{ParseError, Reason}, ExceptionId, Lexer, LicenseItem, LicenseReq, Token, }; #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Licensee { inner: LicenseReq, } impl Licensee {
pub fn parse(original: &str) -> Result<Self, ParseError<'_>> { let mut lexer = Lexer::new(original); let license = { let lt = lexer.next().ok_or_else(|| ParseError { original, span: 0..original.len(), reason: Reason::Empty, })??; match lt.token { Token::SPDX(id) => LicenseItem::SPDX { id, or_later: false, }, Token::LicenseRef { doc_ref, lic_ref } => LicenseItem::Other { doc_ref: doc_ref.map(String::from), lic_ref: lic_ref.to_owned(), }, _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["<license>"]), }) } } }; let exception = match lexer.next() { None => None, Some(lt) => { let lt = lt?; match lt.token { Token::With => { let lt = lexer.next().ok_or_else(|| ParseError { original, span: lt.span, reason: Reason::Empty, })??; match lt.token { Token::Exception(exc) => Some(exc), _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["<exception>"]), }) } } } _ => { return Err(ParseError { original, span: lt.span, reason: Reason::Unexpected(&["WITH"]), }) } } } }; Ok(Licensee { inner: LicenseReq { license, exception }, }) } pub fn satisfies(&self, req: &LicenseReq) -> bool { match (&self.inner.license, &req.license) { (LicenseItem::SPDX { id: a, .. }, LicenseItem::SPDX { id: b, or_later }) => { if a.index != b.index { if *or_later { let a_name = &a.name[..a.name.rfind('-').unwrap_or_else(|| a.name.len())]; let b_name = &b.name[..b.name.rfind('-').unwrap_or_else(|| b.name.len())]; if a_name != b_name || a.name < b.name { return false; } } else { return false; } } } ( LicenseItem::Other { doc_ref: doca, lic_ref: lica, }, LicenseItem::Other { doc_ref: docb, lic_ref: licb, }, ) => { if doca != docb || lica != licb { return false; } } _ => return false, } req.exception == self.inner.exception } } impl PartialOrd<LicenseReq> for Licensee { fn partial_cmp(&self, o: &LicenseReq) -> Option<std::cmp::Ordering> { self.inner.partial_cmp(o) } } impl PartialEq<LicenseReq> for Licensee { fn eq(&self, o: &LicenseReq) -> bool { self.inner.eq(o) } } #[cfg(test)] mod test { use crate::{exception_id, license_id, LicenseItem, LicenseReq, Licensee}; const LICENSEES: &[&str] = &[ "LicenseRef-Embark-Proprietary", "BSD-2-Clause", "Apache-2.0 WITH LLVM-exception", "BSD-2-Clause-FreeBSD", "BSL-1.0", "Zlib", "CC0-1.0", "FTL", "ISC", "MIT", "MPL-2.0", "BSD-3-Clause", "Unicode-DFS-2016", "Unlicense", "Apache-2.0", ]; #[test] fn handles_or_later() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let mpl_id = license_id("MPL-2.0").unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: mpl_id, or_later: true, }, exception: None, }; assert!(licensees.binary_search_by(|l| l.inner.cmp(&req)).is_err()); match &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner .license { LicenseItem::SPDX { id, .. } => assert_eq!(*id, mpl_id), o => panic!("unexepcted {:?}", o), } } #[test] fn handles_exceptions() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let apache_id = license_id("Apache-2.0").unwrap(); let llvm_exc = exception_id("LLVM-exception").unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: apache_id, or_later: false, }, exception: Some(llvm_exc), }; assert_eq!( &req, &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner ); } #[test] fn handles_license_ref() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); let req = LicenseReq { license: LicenseItem::Other { doc_ref: None, lic_ref: "Embark-Proprietary".to_owned(), }, exception: None, }; assert_eq!( &req, &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner ); } #[test] fn handles_close() { let mut licensees: Vec<_> = LICENSEES .iter() .map(|l| Licensee::parse(l).unwrap()) .collect(); licensees.sort(); for id in &["BSD-2-Clause", "BSD-2-Clause-FreeBSD"] { let lic_id = license_id(id).unwrap(); let req = LicenseReq { license: LicenseItem::SPDX { id: lic_id, or_later: true, }, exception: None, }; assert!(licensees.binary_search_by(|l| l.inner.cmp(&req)).is_err()); match &licensees[licensees .binary_search_by(|l| l.partial_cmp(&req).unwrap()) .unwrap()] .inner .license { LicenseItem::SPDX { id, .. } => assert_eq!(*id, lic_id), o => panic!("unexepcted {:?}", o), } } } }
pub fn new(license: LicenseItem, exception: Option<ExceptionId>) -> Self { if let LicenseItem::SPDX { or_later, .. } = &license { debug_assert!(!or_later) } Self { inner: LicenseReq { license, exception }, } }
function_block-full_function
[ { "content": "#[inline]\n\npub fn license_id(name: &str) -> Option<LicenseId> {\n\n let name = &name.trim_end_matches('+');\n\n identifiers::LICENSES\n\n .binary_search_by(|lic| lic.0.cmp(name))\n\n .map(|index| {\n\n let (name, flags) = identifiers::LICENSES[index];\n\n ...
Rust
src/cmd/export/runit.rs
dan-da/ultraman
f6b491f6f39e693b404b1c35daf49317d476774a
use super::base::{Exportable, Template}; use crate::cmd::export::ExportOpts; use crate::env::read_env; use crate::process::port_for; use crate::procfile::{Procfile, ProcfileEntry}; use handlebars::to_json; use serde_derive::Serialize; use serde_json::value::{Map, Value as Json}; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; pub struct Exporter { pub procfile: Procfile, pub opts: ExportOpts, } #[derive(Serialize)] struct RunParams { work_dir: String, user: String, env_dir_path: String, process_command: String, } #[derive(Serialize)] struct LogRunParams { log_path: String, user: String, } impl Default for Exporter { fn default() -> Self { Exporter { procfile: Procfile { data: HashMap::new(), }, opts: ExportOpts { format: String::from(""), location: PathBuf::from("location"), app: None, formation: String::from("all=1"), log_path: None, run_path: None, port: None, template_path: None, user: None, env_path: PathBuf::from(".env"), procfile_path: PathBuf::from("Procfile"), root_path: Some(env::current_dir().unwrap()), timeout: String::from("5"), }, } } } impl Exporter { fn boxed(self) -> Box<Self> { Box::new(self) } pub fn boxed_new() -> Box<Self> { Self::default().boxed() } fn run_tmpl_path(&self) -> PathBuf { let mut path = self.project_root_path(); let tmpl_path = PathBuf::from("src/cmd/export/templates/runit/run.hbs"); path.push(tmpl_path); path } fn log_run_tmpl_path(&self) -> PathBuf { let mut path = self.project_root_path(); let tmpl_path = PathBuf::from("src/cmd/export/templates/runit/log/run.hbs"); path.push(tmpl_path); path } fn make_run_data(&self, pe: &ProcfileEntry, env_dir_path: &PathBuf) -> Map<String, Json> { let mut data = Map::new(); let rp = RunParams { work_dir: self.root_path().into_os_string().into_string().unwrap(), user: self.username(), env_dir_path: env_dir_path.clone().into_os_string().into_string().unwrap(), process_command: pe.command.to_string(), }; data.insert("run".to_string(), to_json(&rp)); data } fn make_log_run_data(&self, process_name: &str) -> Map<String, Json> { let mut data = Map::new(); let log_path = format!( "{}/{}", self.log_path().into_os_string().into_string().unwrap(), &process_name ); let lr = LogRunParams { log_path, user: self.username(), }; data.insert("log_run".to_string(), to_json(&lr)); data } fn write_env(&self, output_dir_path: &PathBuf, index: usize, con_index: usize) { let mut env = read_env(self.opts.env_path.clone()).expect("failed read .env"); let port = port_for( self.opts.env_path.clone(), self.opts.port.clone(), index, con_index + 1, ); env.insert("PORT".to_string(), port); for (key, val) in env.iter() { let path = output_dir_path.join(&key); let display = path.clone().into_os_string().into_string().unwrap(); self.clean(&path); let mut file = File::create(path.clone()).expect(&format!("Could not create file: {}", &display)); self.say(&format!("writing: {}", &display)); writeln!(&mut file, "{}", &val).expect(&format!("Could not write file: {}", &display)); } } } struct EnvTemplate { template_path: PathBuf, index: usize, con_index: usize, } impl Exportable for Exporter { fn export(&self) -> Result<(), Box<dyn std::error::Error>> { self.base_export().expect("failed execute base_export"); let mut index = 0; let mut clean_paths: Vec<PathBuf> = vec![]; let mut create_recursive_dir_paths: Vec<PathBuf> = vec![]; let mut tmpl_data: Vec<Template> = vec![]; let mut env_data: Vec<EnvTemplate> = vec![]; for (name, pe) in self.procfile.data.iter() { let con = pe.concurrency.get(); for n in 0..con { index += 1; let process_name = format!("{}-{}", &name, n + 1); let service_name = format!("{}-{}-{}", self.app(), &name, n + 1); let mut path_for_run = self.opts.location.clone(); let mut path_for_env = path_for_run.clone(); let mut path_for_log = path_for_run.clone(); let run_file_path = PathBuf::from(format!("{}/run", &service_name)); let env_dir_path = PathBuf::from(format!("{}/env", &service_name)); let log_dir_path = PathBuf::from(format!("{}/log", &service_name)); path_for_run.push(run_file_path); path_for_env.push(env_dir_path); path_for_log.push(log_dir_path); create_recursive_dir_paths.push(path_for_env.clone()); create_recursive_dir_paths.push(path_for_log.clone()); let run_data = self.make_run_data( pe, &PathBuf::from(format!("/etc/service/{}/env", &service_name)), ); let log_run_data = self.make_log_run_data(&process_name); clean_paths.push(path_for_run.clone()); tmpl_data.push(Template { template_path: self.run_tmpl_path(), data: run_data, output_path: path_for_run, }); path_for_log.push("run"); clean_paths.push(path_for_log.clone()); tmpl_data.push(Template { template_path: self.log_run_tmpl_path(), data: log_run_data, output_path: path_for_log, }); env_data.push(EnvTemplate { template_path: path_for_env.clone(), index, con_index: n, }); } } for path in clean_paths { self.clean(&path); } for dir_path in create_recursive_dir_paths { self.create_dir_recursive(&dir_path); } for tmpl in tmpl_data { self.write_template(tmpl); } for e in env_data { self.write_env(&e.template_path, e.index, e.con_index); } Ok(()) } fn ref_opts(&self) -> &ExportOpts { &self.opts } }
use super::base::{Exportable, Template}; use crate::cmd::export::ExportOpts; use crate::env::read_env; use crate::process::port_for; use crate::procfile::{Procfile, ProcfileEntry}; use handlebars::to_json; use serde_derive::Serialize; use serde_json::value::{Map, Value as Json}; use std::collections::HashMap; use std::env; use std::fs::File; use std::io::Write; use std::path::PathBuf; pub struct Exporter { pub procfile: Procfile, pub opts: ExportOpts, } #[derive(Serialize)] struct RunParams { work_dir: String, user: String, env_dir_path: String, process_command: String, } #[derive(Serialize)] struct LogRunParams { log_path: String, user: String, } impl Default for Exporter { fn default() -> Self { Exporter { procfile: Procfile { data: HashMap::new(), }, opts: ExportOpts { format: String::from(""), location: PathBuf::from("location"), app: None, formation: String::from("all=1"), log_path: None, run_path: None, port: None, template_path: None, user: None, env_path: PathBuf::from(".env"), procfile_path: PathBuf::from("Procfile"), root_path: Some(env::current_dir().unwrap()), timeout: String::from("5"), }, } } } impl Exporter { fn boxed(self) -> Box<Self> { Box::new(self) } pub fn boxed_new() -> Box<Self> { Self::default().boxed() } fn run_tmpl_path(&self) -> PathBuf { let mut path = self.project_root_path(); let tmpl_path = PathBuf::from("src/cmd/export/templates/runit/run.hbs"); path.push(tmpl_path); path } fn log_run_tmpl_path(&self) -> PathBuf { let mut path = self.project_root_path(); let tmpl_path = PathBuf::from("src/cmd/export/templates/runit/log/run.hbs"); path.push(tmpl_path); path } fn make_run_data(&self, pe: &ProcfileEntry, env_dir_path: &PathBuf) -> Map<String, Json> { let mut data = Map::new(); let rp = RunParams { work_dir: self.root_path().into_os_string().into_string().unwrap(), user: self.username(), env_dir_path: env_dir_path.clone().into_os_string().into_string().unwrap(), process_command: pe.command.to_string(), }; data.insert("run".to_string(), to_json(&rp)); data } fn make_log_run_data(&self, process_name: &str) -> Map<String, Json> { let mut data = Map::new(); let log_path = format!( "{}/{}", self.log_path().into_os_string().into_string().unwrap(), &process_name ); let lr = LogRunParams { log_path, user: self.username(), }; data.insert("log_run".to_string(), to_json(&lr)); data } fn write_env(&self, output_dir_path: &PathBuf, index: usize, con_index: usize) { let mut env = read_env(self.opts.env_path.clone()).expect("failed read .env"); let port =
; env.insert("PORT".to_string(), port); for (key, val) in env.iter() { let path = output_dir_path.join(&key); let display = path.clone().into_os_string().into_string().unwrap(); self.clean(&path); let mut file = File::create(path.clone()).expect(&format!("Could not create file: {}", &display)); self.say(&format!("writing: {}", &display)); writeln!(&mut file, "{}", &val).expect(&format!("Could not write file: {}", &display)); } } } struct EnvTemplate { template_path: PathBuf, index: usize, con_index: usize, } impl Exportable for Exporter { fn export(&self) -> Result<(), Box<dyn std::error::Error>> { self.base_export().expect("failed execute base_export"); let mut index = 0; let mut clean_paths: Vec<PathBuf> = vec![]; let mut create_recursive_dir_paths: Vec<PathBuf> = vec![]; let mut tmpl_data: Vec<Template> = vec![]; let mut env_data: Vec<EnvTemplate> = vec![]; for (name, pe) in self.procfile.data.iter() { let con = pe.concurrency.get(); for n in 0..con { index += 1; let process_name = format!("{}-{}", &name, n + 1); let service_name = format!("{}-{}-{}", self.app(), &name, n + 1); let mut path_for_run = self.opts.location.clone(); let mut path_for_env = path_for_run.clone(); let mut path_for_log = path_for_run.clone(); let run_file_path = PathBuf::from(format!("{}/run", &service_name)); let env_dir_path = PathBuf::from(format!("{}/env", &service_name)); let log_dir_path = PathBuf::from(format!("{}/log", &service_name)); path_for_run.push(run_file_path); path_for_env.push(env_dir_path); path_for_log.push(log_dir_path); create_recursive_dir_paths.push(path_for_env.clone()); create_recursive_dir_paths.push(path_for_log.clone()); let run_data = self.make_run_data( pe, &PathBuf::from(format!("/etc/service/{}/env", &service_name)), ); let log_run_data = self.make_log_run_data(&process_name); clean_paths.push(path_for_run.clone()); tmpl_data.push(Template { template_path: self.run_tmpl_path(), data: run_data, output_path: path_for_run, }); path_for_log.push("run"); clean_paths.push(path_for_log.clone()); tmpl_data.push(Template { template_path: self.log_run_tmpl_path(), data: log_run_data, output_path: path_for_log, }); env_data.push(EnvTemplate { template_path: path_for_env.clone(), index, con_index: n, }); } } for path in clean_paths { self.clean(&path); } for dir_path in create_recursive_dir_paths { self.create_dir_recursive(&dir_path); } for tmpl in tmpl_data { self.write_template(tmpl); } for e in env_data { self.write_env(&e.template_path, e.index, e.con_index); } Ok(()) } fn ref_opts(&self) -> &ExportOpts { &self.opts } }
port_for( self.opts.env_path.clone(), self.opts.port.clone(), index, con_index + 1, )
call_expression
[ { "content": "fn base_port(env_path: PathBuf, port: Option<String>) -> String {\n\n let env = read_env(env_path).unwrap();\n\n let default_port = String::from(\"5000\");\n\n\n\n if let Some(p) = port {\n\n p\n\n } else if let Some(p) = env.get(\"PORT\") {\n\n p.clone()\n\n } else if...
Rust
src/config.rs
selvakn/wg-port-forward
1ecdcc8a1af1df3f4e906d991592a7ef693587ec
use std::fmt::{Display, Formatter}; use std::fs::read_to_string; use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::sync::Arc; use anyhow::Context; use boringtun::crypto::{X25519PublicKey, X25519SecretKey}; use clap::{App, Arg}; #[derive(Clone, Debug)] pub struct Config { pub private_key: Arc<X25519SecretKey>, pub endpoint_public_key: Arc<X25519PublicKey>, pub endpoint_addr: SocketAddr, pub source_peer_ip: IpAddr, pub keepalive_seconds: Option<u16>, pub max_transmission_unit: usize, pub ports_to_forward: Vec<u16>, } impl Config { pub fn from( private_key: &str, endpoint_public_key: &str, endpoint_addr: &str, source_peer_ip: &str, keepalive_seconds: u16, max_transmission_unit: usize, ports_to_forward: Vec<u16>, ) -> anyhow::Result<Self> { let config = Config { private_key: Arc::new(parse_private_key(private_key)?), endpoint_public_key: Arc::new(parse_public_key(Some(endpoint_public_key))?), endpoint_addr: parse_addr(Some(endpoint_addr))?, source_peer_ip: parse_ip(Some(source_peer_ip))?, keepalive_seconds: Some(keepalive_seconds), max_transmission_unit: max_transmission_unit, ports_to_forward: ports_to_forward, }; Ok(config) } pub fn from_args() -> anyhow::Result<Self> { let matches = App::new("p2p-port-forward") .version(env!("CARGO_PKG_VERSION")) .args(&[ Arg::with_name("private-key") .required_unless("private-key-file") .takes_value(true) .long("private-key") .help("The private key of this peer. The corresponding public key should be registered in the WireGuard endpoint. \ You can also use '--private-key-file' to specify a file containing the key instead."), Arg::with_name("private-key-file") .takes_value(true) .long("private-key-file") .help("The path to a file containing the private key of this peer. The corresponding public key should be registered in the WireGuard endpoint."), Arg::with_name("endpoint-public-key") .required(true) .takes_value(true) .long("endpoint-public-key") .help("The public key of the WireGuard endpoint (remote)."), Arg::with_name("endpoint-addr") .required(true) .takes_value(true) .long("endpoint-addr") .help("The address (IP + port) of the WireGuard endpoint (remote). Example: 1.2.3.4:51820"), Arg::with_name("source-peer-ip") .required(true) .takes_value(true) .long("source-peer-ip") .help("The source IP to identify this peer as (local). Example: 192.168.4.3"), Arg::with_name("keep-alive") .required(false) .takes_value(true) .long("keep-alive") .help("Configures a persistent keep-alive for the WireGuard tunnel, in seconds."), Arg::with_name("max-transmission-unit") .required(false) .takes_value(true) .long("max-transmission-unit") .default_value("1420") .help("Configures the max-transmission-unit (MTU) of the WireGuard tunnel."), Arg::with_name("ports-to-forward") .required(true) .multiple(true) .takes_value(true) .long("ports-to-forward") .help("Configures the ports to forward. Example: --ports-to-forward 22,80,443"), ]).get_matches(); let private_key = if let Some(private_key_file) = matches.value_of("private-key-file") { read_to_string(private_key_file) .map(|s| s.trim().to_string()) .with_context(|| "Failed to read private key file") } else { matches .value_of("private-key") .map(String::from) .with_context(|| "Missing private key") }?; Ok(Self { private_key: Arc::new( parse_private_key(&private_key).with_context(|| "Invalid private key")?, ), endpoint_public_key: Arc::new( parse_public_key(matches.value_of("endpoint-public-key")) .with_context(|| "Invalid endpoint public key")?, ), endpoint_addr: parse_addr(matches.value_of("endpoint-addr")) .with_context(|| "Invalid endpoint address")?, source_peer_ip: parse_ip(matches.value_of("source-peer-ip")) .with_context(|| "Invalid source peer IP")?, keepalive_seconds: parse_keep_alive(matches.value_of("keep-alive")) .with_context(|| "Invalid keep-alive value")?, max_transmission_unit: parse_mtu(matches.value_of("max-transmission-unit")) .with_context(|| "Invalid max-transmission-unit value")?, ports_to_forward: matches .values_of("ports-to-forward") .unwrap() .map(|s| s.parse::<u16>().unwrap()) .collect(), }) } } fn parse_addr(s: Option<&str>) -> anyhow::Result<SocketAddr> { s.with_context(|| "Missing address")? .to_socket_addrs() .with_context(|| "Invalid address")? .next() .with_context(|| "Could not lookup address") } fn parse_ip(s: Option<&str>) -> anyhow::Result<IpAddr> { s.with_context(|| "Missing IP")? .parse::<IpAddr>() .with_context(|| "Invalid IP address") } fn parse_private_key(s: &str) -> anyhow::Result<X25519SecretKey> { s.parse::<X25519SecretKey>() .map_err(|e| anyhow::anyhow!("{}", e)) } fn parse_public_key(s: Option<&str>) -> anyhow::Result<X25519PublicKey> { s.with_context(|| "Missing public key")? .parse::<X25519PublicKey>() .map_err(|e| anyhow::anyhow!("{}", e)) .with_context(|| "Invalid public key") } fn parse_keep_alive(s: Option<&str>) -> anyhow::Result<Option<u16>> { if let Some(s) = s { let parsed: u16 = s.parse().with_context(|| { format!( "Keep-alive must be a number between 0 and {} seconds", u16::MAX ) })?; Ok(Some(parsed)) } else { Ok(None) } } fn parse_mtu(s: Option<&str>) -> anyhow::Result<usize> { s.with_context(|| "Missing MTU")? .parse() .with_context(|| "Invalid MTU") } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum PortProtocol { Tcp, Icmp, } impl Display for PortProtocol { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Self::Tcp => "TCP", Self::Icmp => "Icmp", } ) } }
use std::fmt::{Display, Formatter}; use std::fs::read_to_string; use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::sync::Arc; use anyhow::Context; use boringtun::crypto::{X25519PublicKey, X25519SecretKey}; use clap::{App, Arg}; #[derive(Clone, Debug)] pub struct Config { pub private_key: Arc<X25519SecretKey>, pub endpoint_public_key: Arc<X25519PublicKey>, pub endpoint_addr: SocketAddr, pub source_peer_ip: IpAddr, pub keepalive_seconds: Option<u16>, pub max_transmission_unit: usize, pub ports_to_forward: Vec<u16>, } impl Config { pub fn from( private_key: &str, endpoint_public_key: &str, endpoint_addr: &str, source_peer_ip: &str, keepalive_seconds: u16, max_transmission_unit: usize, ports_to_forward: Vec<u16>, ) -> anyhow::Result<Self> { let config = Config { private_key: Arc::new(parse_private_key(private_key)?), endpoint_public_key: Arc::new(parse_public_key(Some(endpoint_public_key))?), endpoint_addr: parse_addr(Some(endpoint_addr))?, source_peer_ip: parse_ip(Some(source_peer_ip))?, keepalive_seconds: Some(keepalive_seconds), max_transmission_unit: max_transmission_unit, ports_to_forward: ports_to_forward, }; Ok(config) } pub fn from_args() -> anyhow::Result<Self> { let matches = App::new("p2p-port-forward") .version(env!("CARGO_PKG_VERSION")) .args(&[ Arg::with_name("private-key") .required_unless("private-key-file") .takes_value(true) .long("private-key") .help("The private key of this peer. The corresponding public key should be registered in the WireGuard endpoint. \ You can also use '--private-key-file' to specify a file containing the key instead."), Arg::with_name("private-key-file") .takes_value(true) .long("private-key-file") .help("The path to a file containing the private key of this peer. The corresponding public key should be registered in the WireGuard endpoint."), Arg::with_name("endpoint-public-key") .required(true) .takes_value(true) .long("endpoint-public-key") .help("The public key of the WireGuard endpoint (remote)."), Arg::with_name("endpoint-addr") .required(true) .takes_value(true) .long("endpoint-addr") .help("The address (IP + port) of the WireGuard endpoint (remote). Example: 1.2.3.4:51820"), Arg::with_name("source-peer-ip") .required(true) .takes_value(true) .long("source-peer-ip") .help("The source IP to identify this peer as (local). Example: 192.168.4.3"), Arg::with_name("keep-alive") .required(false) .takes_value(true) .long("keep-alive") .help("Configures a persistent keep-alive for the WireGuard tunnel, in seconds."), Arg::with_name("max-transmission-unit") .required(false) .takes_value(true) .long("max-transmission-unit") .default_value("1420") .help("Configures the max-transmission-unit (MTU) of the WireGuard tunnel."), Arg::with_name("ports-to-forward") .required(true) .multiple(true) .takes_value(true) .long("ports-to-forward") .help("Configures the ports to forward. Example: --ports-to-forward 22,80,443"), ]).get_matches(); let private_key = if let Some(private_key_file) = matches.value_of("private-key-file") { read_to_string(private_key_file) .map(|s| s.trim().to_string()) .with_context(|| "Failed to read private key file") } else { matches .value_of("private-key") .map(String::from) .with_context(|| "Missing private key") }?; Ok(Self { private_key: Arc::new( parse_private_key(&private_key).with_context(|| "Invalid private key")?, ), endpoint_public_key: Arc::new( parse_public_key(matches.value_of("endpoint-public-key")) .with_context(|| "Invalid endpoint public key")?, ), endpoint_addr: parse_addr(matches.value_of("endpoint-addr")) .with_context(|| "Invalid endpoint address")?, source_peer_ip: parse_ip(matches.value_of("source-peer-ip")) .with_context(|| "Invalid source peer IP")?, keepalive_seconds: parse_keep_alive(matches.value_of("keep-alive")) .with_context(|| "Invalid keep-alive value")?, max_transmission_unit: parse_mtu(matches.value_of("max-transmission-unit")) .with_context(|| "Invalid max-transmission-unit value")?, ports_to_forward: matches .values_of("ports-to-forward") .unwrap() .map(|s| s.parse::<u16>().unwrap()) .collect(), }) } } fn parse_addr(s: Option<&str>) -> anyhow::Result<SocketAddr> { s.with_context(|| "Missing address")? .to_socket_addrs() .with_context(|| "Invalid address")? .next() .with_context(|| "Could not lookup address") } fn parse_ip(s: Option<&str>) -> anyhow::Result<IpAddr> { s.with_context(|| "Missing IP")? .parse::<IpAddr>() .with_context(|| "Invalid IP address") } fn parse_private_key(s: &str) -> anyhow::Result<X25519SecretKey> { s.parse::<X25519SecretKey>() .map_err(|e| anyhow::anyhow!("{}", e)) } fn parse_public_key(s: Option<&str>) -> anyhow::Resul
fn parse_keep_alive(s: Option<&str>) -> anyhow::Result<Option<u16>> { if let Some(s) = s { let parsed: u16 = s.parse().with_context(|| { format!( "Keep-alive must be a number between 0 and {} seconds", u16::MAX ) })?; Ok(Some(parsed)) } else { Ok(None) } } fn parse_mtu(s: Option<&str>) -> anyhow::Result<usize> { s.with_context(|| "Missing MTU")? .parse() .with_context(|| "Invalid MTU") } #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum PortProtocol { Tcp, Icmp, } impl Display for PortProtocol { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "{}", match self { Self::Tcp => "TCP", Self::Icmp => "Icmp", } ) } }
t<X25519PublicKey> { s.with_context(|| "Missing public key")? .parse::<X25519PublicKey>() .map_err(|e| anyhow::anyhow!("{}", e)) .with_context(|| "Invalid public key") }
function_block-function_prefixed
[ { "content": "pub fn new_listener_socket<'a>(port: u16) -> anyhow::Result<TcpSocket<'a>> {\n\n let rx_data = vec![0u8; MAX_PACKET];\n\n let tx_data = vec![0u8; MAX_PACKET];\n\n let tcp_rx_buffer = TcpSocketBuffer::new(rx_data);\n\n let tcp_tx_buffer = TcpSocketBuffer::new(tx_data);\n\n let mut so...
Rust
prelude/src/lib.rs
ferristseng/cryogen
b0bee906d2c2ea8f6f328edc71cf2f509b06dbf0
extern crate clap; extern crate serde; #[cfg(feature = "markdown")] extern crate serde_yaml; #[cfg(feature = "markdown")] #[macro_use] extern crate serde_derive; use clap::{Arg, ArgMatches}; use serde::Serialize; use std::{cmp, borrow::Cow, io::{self, Read}}; #[cfg(feature = "markdown")] pub mod markdown; #[macro_export] macro_rules! args { ( $($name: ident [$help: expr]);*; ) => { vec![ $( Arg::with_name($name).long($name).help($help), )* ] }; } #[derive(Debug)] pub struct VarMapping<'a> { var_name: &'a str, arg_value: &'a str, } impl<'a> VarMapping<'a> { pub fn from_str(s: &'a str) -> Result<VarMapping<'a>, String> { let mut splits = s.splitn(2, ":"); let var_name = if let Some(var_name) = splits.next() { var_name } else { return Err(format!("Expected a variable name to bind to in ({})", s)); }; let arg_value = if let Some(arg_value) = splits.next() { arg_value } else { return Err(format!( "Expected a value to bind to ({}) in ({})", var_name, s )); }; Ok(VarMapping { var_name, arg_value, }) } #[inline] pub fn arg_value(&self) -> &'a str { self.arg_value } #[inline] pub fn var_name(&self) -> &'a str { self.var_name } } pub enum Interpretation { Raw, Path, } pub enum Source<'a, R> where R: Read, { Raw(&'a str, usize), File(R), } impl<'a, R> Source<'a, R> where R: Read, { pub fn consume(self) -> Result<Cow<'a, str>, String> { match self { Source::Raw(raw, _) => Ok(Cow::Borrowed(raw)), Source::File(mut reader) => { let mut buf = String::new(); reader.read_to_string(&mut buf).map_err(|e| e.to_string())?; Ok(Cow::Owned(buf)) } } } } impl<'a, R> Read for Source<'a, R> where R: Read, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> { match self { &mut Source::Raw(raw, ref mut index) => { let current = *index; let slice = &raw.as_bytes()[current..]; let copy_num = cmp::min(buf.len(), slice.len()); &buf[..copy_num].copy_from_slice(&slice[..copy_num]); *index = current + copy_num; Ok(copy_num) } &mut Source::File(ref mut reader) => reader.read(buf), } } } pub trait CompileVariablePlugin { type RenderValue: Serialize; const PLUGIN_NAME: &'static str; const ARG_NAME: &'static str; const ARG_INTERPRETATION: Interpretation; const HELP: &'static str; fn additional_args() -> Vec<Arg<'static, 'static>>; fn from_args<'a>(args: &'a ArgMatches<'a>) -> Self; fn read<'a, R>(&self, src: Source<'a, R>) -> Result<Self::RenderValue, String> where R: Read; }
extern crate clap; extern crate serde; #[cfg(feature = "markdown")] extern crate serde_yaml; #[cfg(feature = "markdown")] #[macro_use] extern crate serde_derive; use clap::{Arg, ArgMatches}; use serde::Serialize; use std::{cmp, borrow::Cow, io::{self, Read}}; #[cfg(feature = "markdown")] pub mod markdown; #[macro_export] macro_rules! args { ( $($name: ident [$help: expr]);*; ) => { vec![ $( Arg::with_name($name).long($name).help($help), )* ] }; } #[derive(Debug)] pub struct VarMapping<'a> { var_name: &'a str, arg_value: &'a str, } impl<'a> VarMapping<'a> { pub fn from_str(s: &'a str) -> Result<VarMapping<'a>, String> { let mut splits = s.splitn(2, ":"); let var_name = if let Some(var_name) = splits.next() { var_name } else { return Err(format!("Expected a variable name to bind
arg_value, }) } #[inline] pub fn arg_value(&self) -> &'a str { self.arg_value } #[inline] pub fn var_name(&self) -> &'a str { self.var_name } } pub enum Interpretation { Raw, Path, } pub enum Source<'a, R> where R: Read, { Raw(&'a str, usize), File(R), } impl<'a, R> Source<'a, R> where R: Read, { pub fn consume(self) -> Result<Cow<'a, str>, String> { match self { Source::Raw(raw, _) => Ok(Cow::Borrowed(raw)), Source::File(mut reader) => { let mut buf = String::new(); reader.read_to_string(&mut buf).map_err(|e| e.to_string())?; Ok(Cow::Owned(buf)) } } } } impl<'a, R> Read for Source<'a, R> where R: Read, { fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> { match self { &mut Source::Raw(raw, ref mut index) => { let current = *index; let slice = &raw.as_bytes()[current..]; let copy_num = cmp::min(buf.len(), slice.len()); &buf[..copy_num].copy_from_slice(&slice[..copy_num]); *index = current + copy_num; Ok(copy_num) } &mut Source::File(ref mut reader) => reader.read(buf), } } } pub trait CompileVariablePlugin { type RenderValue: Serialize; const PLUGIN_NAME: &'static str; const ARG_NAME: &'static str; const ARG_INTERPRETATION: Interpretation; const HELP: &'static str; fn additional_args() -> Vec<Arg<'static, 'static>>; fn from_args<'a>(args: &'a ArgMatches<'a>) -> Self; fn read<'a, R>(&self, src: Source<'a, R>) -> Result<Self::RenderValue, String> where R: Read; }
to in ({})", s)); }; let arg_value = if let Some(arg_value) = splits.next() { arg_value } else { return Err(format!( "Expected a value to bind to ({}) in ({})", var_name, s )); }; Ok(VarMapping { var_name,
function_block-random_span
[]
Rust
src/memory/mmu/mod.rs
FelixMcFelix/rs2
194a5b6c87d025cf7fa40700b7750d7fbbaf9e58
pub mod tlb; use crate::core::{cop0::*, exceptions::L1Exception}; use tlb::Tlb; pub struct Mmu { pub tlb: Tlb, pub page_mask: u32, pub wired: u8, pub index: u8, pub context: u32, pub asid: u8, } const VPN_ALWAYS_ACTIVE_BITS: u32 = 0b1111_1110_0000_0000_0000_0000_0000_0000; const OFFSET_ALWAYS_ACTIVE_BITS: u32 = 0b0000_0000_0000_0000_0000_1111_1111_1111; const RAW_MASK_4KB: u32 = 0b0000_0000_0000; const RAW_MASK_16KB: u32 = 0b0000_0000_0011; const RAW_MASK_64KB: u32 = 0b0000_0000_1111; const RAW_MASK_256KB: u32 = 0b0000_0011_1111; const RAW_MASK_1MB: u32 = 0b0000_1111_1111; const RAW_MASK_4MB: u32 = 0b0011_1111_1111; const RAW_MASK_16MB: u32 = 0b1111_1111_1111; const PAGE_MASK_4KB: u32 = RAW_MASK_4KB << 13; const PAGE_MASK_16KB: u32 = RAW_MASK_16KB << 13; const PAGE_MASK_64KB: u32 = RAW_MASK_64KB << 13; const PAGE_MASK_256KB: u32 = RAW_MASK_256KB << 13; const PAGE_MASK_1MB: u32 = RAW_MASK_1MB << 13; const PAGE_MASK_4MB: u32 = RAW_MASK_4MB << 13; const PAGE_MASK_16MB: u32 = RAW_MASK_16MB << 13; #[inline] pub fn page_mask_shift_amount(p_mask: u32) -> u32 { 12 + match p_mask { PAGE_MASK_4KB => 0, PAGE_MASK_16KB => 2, PAGE_MASK_64KB => 4, PAGE_MASK_256KB => 6, PAGE_MASK_1MB => 8, PAGE_MASK_4MB => 10, PAGE_MASK_16MB => 12, _ => unreachable!(), } } pub fn page_mask_size(p_mask: u32) -> &'static str { match p_mask { PAGE_MASK_4KB => "4KB", PAGE_MASK_16KB => "16KB", PAGE_MASK_64KB => "64KB", PAGE_MASK_256KB => "256KB", PAGE_MASK_1MB => "1MB", PAGE_MASK_4MB => "4MB", PAGE_MASK_16MB => "16MB", _ => unreachable!(), } } const SPR_SHIFT_AMOUNT: u32 = 12 + 2 + 1; impl Mmu { pub fn translate_address(&self, v_addr: u32, load: bool) -> MmuAddress { let vpn_shift_amount = page_mask_shift_amount(self.page_mask); let vpn = v_addr >> vpn_shift_amount; let vpn2 = (vpn >> 1) << (vpn_shift_amount - 12); let spr_vpn2 = (v_addr >> SPR_SHIFT_AMOUNT) << (SPR_SHIFT_AMOUNT - 12 - 1); let even_page = (vpn & 1) == 0; trace!("Translating {} -- VPN: {}", v_addr, vpn2); let line = self.tlb.find_match(vpn2, spr_vpn2); let out = line .and_then(|line| { if !line.global && line.asid != self.asid { return None; } let indiv_page = if even_page { &line.even } else { &line.odd }; if !indiv_page.valid { if load { return Some(MmuAddress::Exception(L1Exception::TlbFetchLoadInvalid( v_addr, ))); } else { return Some(MmuAddress::Exception(L1Exception::TlbStoreInvalid(v_addr))); } } else if !indiv_page.dirty && !load { return Some(MmuAddress::Exception(L1Exception::TlbModified(v_addr))); } Some(if line.scratchpad { let offset = v_addr & (OFFSET_ALWAYS_ACTIVE_BITS | (PAGE_MASK_16KB >> 1)); MmuAddress::Scratchpad(offset) } else { let offset = v_addr & (OFFSET_ALWAYS_ACTIVE_BITS | (self.page_mask >> 1)); MmuAddress::Address((indiv_page.page_frame_number << vpn_shift_amount) | offset) }) }) .unwrap_or_else(|| { MmuAddress::Exception(if load { L1Exception::TlbFetchLoadRefill(v_addr) } else { L1Exception::TlbStoreRefill(v_addr) }) }); trace!("Result: {:?}", out); out } pub fn write_index(&mut self, entry_hi: u32, entry_lo0: u32, entry_lo1: u32) { self.tlb.lines[self.index as usize].update(self.page_mask, entry_hi, entry_lo0, entry_lo1); trace!( "Put into line {}: {:?}", self.index, self.tlb.lines[self.index as usize] ); } pub fn write_random( &mut self, random_index: u32, entry_hi: u32, entry_lo0: u32, entry_lo1: u32, ) { self.tlb.lines[random_index as usize].update( self.page_mask, entry_hi, entry_lo0, entry_lo1, ); trace!( "Put into line {}: {:?}", self.index, self.tlb.lines[self.index as usize] ); } } #[derive(Debug, PartialEq)] pub enum MmuAddress { Address(u32), Scratchpad(u32), Exception(L1Exception), } impl Default for Mmu { fn default() -> Self { Self { tlb: Default::default(), page_mask: 0, wired: WIRED_DEFAULT as u8, index: 0, context: 0, asid: 0, } } }
pub mod tlb; use crate::core::{cop0::*, exceptions::L1Exception}; use tlb::Tlb; pub struct Mmu { pub tlb: Tlb, pub page_mask: u32, pub wired: u8, pub index: u8, pub context: u32, pub asid: u8, } const VPN_ALWAYS_ACTIVE_BITS: u32 = 0b1111_1110_0000_0000_0000_0000_0000_0000; const OFFSET_ALWAYS_ACTIVE_BITS: u32 = 0b0000_0000_0000_0000_0000_1111_1111_1111; const RAW_MASK_4KB: u32 = 0b0000_0000_0000; const RAW_MASK_16KB: u32 = 0b0000_0000_0011; const RAW_MASK_64KB: u32 = 0b0000_0000_1111; const RAW_MASK_256KB: u32 = 0b0000_0011_1111; const RAW_MASK_1MB: u32 = 0b0000_1111_1111; const RAW_MASK_4MB: u32 = 0b0011_1111_1111; const RAW_MASK_16MB: u32 = 0b1111_1111_1111; const PAGE_MASK_4KB: u32 = RAW_MASK_4KB << 13; const PAGE_MASK_16KB: u32 = RAW_MASK_16KB << 13; const PAGE_MASK_64KB: u32 = RAW_MASK_64KB << 13; const PAGE_MASK_256KB: u32 = RAW_MASK_256KB << 13; const PAGE_MASK_1MB: u32 = RAW_MASK_1MB << 13; const PAGE_MASK_4MB: u32 = RAW_MASK_4MB << 13; const PAGE_MASK_16MB: u32 = RAW_MASK_16MB << 13; #[inline] pub fn page_mask_shift_amount(p_mask: u32) -> u32 { 12 + match p_mask { PAGE_MASK_4KB => 0, PAGE_MASK_16KB => 2, PAGE_MASK_64KB => 4, PAGE_MASK_256KB => 6, PAGE_MASK_1MB => 8, PAGE_MASK_4MB => 10, PAGE_MASK_16MB => 12, _ => unreachable!(), } } pub fn page_mask_size(p_mask: u32) -> &'static str { match p_mask { PAGE_MASK_4KB => "4KB", PAGE_MASK_16KB => "16KB", PAGE_MASK_64KB => "64KB", PAGE_MASK_256KB => "256KB", PAGE_MASK_1MB => "1MB", PAGE_MASK_4MB => "4MB", PAGE_MASK_16MB => "16MB", _ => unreachable!(), } } const SPR_SHIFT_AMOUNT: u32 = 12 + 2 + 1; impl Mmu { pub fn translate_address(&self, v_addr: u32, load: bool) -> MmuAddress { let vpn_shift_amount = page_mask_shift_amount(self.page_mask); let vpn = v_addr >> vpn_shift_amount; let vpn2 = (vpn >> 1) << (vpn_shift_amount - 12); let spr_vpn2 = (v_addr >> SPR_SHIFT_AMOUNT) << (SPR_SHIFT_AMOUNT - 12 - 1); let even_page = (vpn & 1) == 0; trace!("Translating {} -- VPN: {}", v_addr, vpn2); let line = self.tlb.find_match(vpn2, spr_vpn2); let out = line .and_then(|line| { if !line.global && line.asid != self.asid { return None; } let indiv_page = if even_page { &line.even } else { &line.odd }; if !indiv_page.valid { if load { return Some(MmuAddress::Exception(L1Exception::TlbFetchLoadInvalid( v_addr, ))); } else { return Some(MmuAddress::Exception(L1Exception::TlbStoreInvalid(v_addr))); } } else if !indiv_page.dirty && !load { return Some(MmuAddress::Exception(L1Exception::TlbModified(v_addr))); } Some(if line.scratchpad { let offset = v_addr & (OFFSET_ALWAYS_ACTIVE_BITS | (PAGE_MASK_16KB >> 1)); MmuAddress::Scratchpad(offset) } else { let offset = v_addr & (OFFSET_ALWAYS_ACTIVE_BITS | (self.page_mask >> 1)); MmuAddress::Address((indiv_page.page_frame_number << vpn_shift_amount) | offset) }) }) .unwrap_or_else(|| { MmuAddress::Exception(if load { L1Exception::TlbFetchLoadRefill(v_addr) } else { L1Exception::TlbStoreRefill(v_addr) }) }); trace!("Result: {:?}", out); out } pub fn write_index(&mut self, entry_hi: u32, entry_lo0: u32, entry_lo1: u32) { self.tlb.lines[self.index as usize].update(self.page_mask, entry_hi, entry_lo0, entry_lo1); trace!( "Put into line {}: {:?}", self.index, self.tlb.lines[self.index as usize] ); } pub fn write_random( &mut self, random_index: u32, entry_hi: u32, entry_lo0: u32, entry_lo1: u32, ) { self.tlb.lines[random_index as usize].update( self.page_mask, entry_hi, entry_lo0, entry_lo1, ); trace!( "Put into line {}: {:?}", self.index, self.tlb.lines[self.index as usize] ); } } #[derive(Debug, PartialEq)] pub enum MmuAddress { Address(u32), Scratchpad(u32), Exception(L1Exception), } impl Default for Mmu {
}
fn default() -> Self { Self { tlb: Default::default(), page_mask: 0, wired: WIRED_DEFAULT as u8, index: 0, context: 0, asid: 0, } }
function_block-function_prefixed
[]
Rust
ref-farming/tests/common/actions.rs
ParasHQ/paras-nft-farming-contract
1fd7065c05706fb47d0e5b1ead9e194c64ab78ca
use near_sdk::json_types::{U128}; use near_sdk::{Balance}; use near_sdk_sim::{call, to_yocto, ContractAccount, UserAccount, DEFAULT_GAS}; use test_token::ContractContract as TestToken; use ref_farming::{ContractContract as Farming}; use ref_farming::{HRSimpleFarmTerms}; use near_sdk::serde_json::Value; use near_sdk::serde_json::json; use super::init::*; use super::utils::*; #[allow(dead_code)] pub(crate) fn prepair_pool_and_liquidity( root: &UserAccount, owner: &UserAccount, farming_id: String, lps: Vec<&UserAccount>, ) -> (UserAccount, ContractAccount<TestToken>, ContractAccount<TestToken>) { let pool = deploy_pool(&root, swap(), owner.account_id()); let token1 = deploy_token(&root, dai(), vec![swap()]); let token2 = deploy_token(&root, eth(), vec![swap()]); owner.call( pool.account_id(), "extend_whitelisted_tokens", &json!({ "tokens": vec![to_va(dai()), to_va(eth())] }).to_string().into_bytes(), DEFAULT_GAS, 0 ).assert_success(); root.call( pool.account_id(), "add_simple_pool", &json!({ "tokens": vec![to_va(dai()), to_va(eth())], "fee": 25 }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); root.call( pool.account_id(), "mft_register", &json!({ "token_id": ":0".to_string(), "account_id": farming_id }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); for lp in lps { add_liqudity(lp, &pool, &token1, &token2, 0); } (pool,token1, token2) } #[allow(dead_code)] pub(crate) fn prepair_pool( root: &UserAccount, owner: &UserAccount, ) -> (UserAccount, ContractAccount<TestToken>, ContractAccount<TestToken>) { let pool = deploy_pool(&root, swap(), owner.account_id()); let token1 = deploy_token(&root, dai(), vec![swap()]); let token2 = deploy_token(&root, eth(), vec![swap()]); owner.call( pool.account_id(), "extend_whitelisted_tokens", &json!({ "tokens": vec![to_va(dai()), to_va(eth())] }).to_string().into_bytes(), DEFAULT_GAS, 0 ); root.call( pool.account_id(), "add_simple_pool", &json!({ "tokens": vec![to_va(dai()), to_va(eth())], "fee": 25 }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); (pool, token1, token2) } #[allow(dead_code)] pub(crate) fn prepair_farm( root: &UserAccount, owner: &UserAccount, token: &ContractAccount<TestToken>, total_reward: Balance, ) -> (ContractAccount<Farming>, String) { let farming = deploy_farming(&root, farming_id(), owner.account_id()); let out_come = call!( owner, farming.create_simple_farm(HRSimpleFarmTerms{ seed_id: format!("{}@0", swap()), reward_token: to_va(token.account_id()), start_at: 0, reward_per_session: to_yocto("1").into(), session_interval: 60, }, Some(U128(1000000000000000000)), None, None), deposit = to_yocto("1") ); out_come.assert_success(); let farm_id: String; if let Value::String(farmid) = out_come.unwrap_json_value() { farm_id = farmid.clone(); } else { farm_id = String::from("N/A"); } call!( root, token.storage_deposit(Some(to_va(farming_id())), None), deposit = to_yocto("1") ) .assert_success(); mint_token(&token, &root, total_reward.into()); call!( root, token.ft_transfer_call(to_va(farming_id()), total_reward.into(), None, farm_id.clone()), deposit = 1 ) .assert_success(); (farming, farm_id) } #[allow(dead_code)] pub(crate) fn prepair_multi_farms( root: &UserAccount, owner: &UserAccount, token: &ContractAccount<TestToken>, total_reward: Balance, farm_count: u32, ) -> (ContractAccount<Farming>, Vec<String>) { let farming = deploy_farming(&root, farming_id(), owner.account_id()); let mut farm_ids: Vec<String> = vec![]; call!( root, token.storage_deposit(Some(to_va(farming_id())), None), deposit = to_yocto("1") ) .assert_success(); mint_token(&token, &root, to_yocto("100000")); for _ in 0..farm_count { let out_come = call!( owner, farming.create_simple_farm(HRSimpleFarmTerms{ seed_id: format!("{}@0", swap()), reward_token: to_va(token.account_id()), start_at: 0, reward_per_session: to_yocto("1").into(), session_interval: 60, }, Some(U128(1000000000000000000)), None, None), deposit = to_yocto("1") ); out_come.assert_success(); let farm_id: String; if let Value::String(farmid) = out_come.unwrap_json_value() { farm_id = farmid.clone(); } else { farm_id = String::from("N/A"); } call!( root, token.ft_transfer_call(to_va(farming_id()), total_reward.into(), None, farm_id.clone()), deposit = 1 ) .assert_success(); farm_ids.push(farm_id.clone()); println!(" Farm {} created and running at Height#{}", farm_id.clone(), root.borrow_runtime().current_block().block_height); } (farming, farm_ids) } pub(crate) fn add_liqudity( user: &UserAccount, pool: &UserAccount, token1: &ContractAccount<TestToken>, token2: &ContractAccount<TestToken>, pool_id: u64, ) { mint_token(&token1, user, to_yocto("105")); mint_token(&token2, user, to_yocto("105")); user.call( pool.account_id(), "storage_deposit", &json!({}).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); call!( user, token1.ft_transfer_call(to_va(swap()), to_yocto("100").into(), None, "".to_string()), deposit = 1 ) .assert_success(); call!( user, token2.ft_transfer_call(to_va(swap()), to_yocto("100").into(), None, "".to_string()), deposit = 1 ) .assert_success(); user.call( pool.account_id(), "add_liquidity", &json!({ "pool_id": pool_id, "amounts": vec![U128(to_yocto("100")), U128(to_yocto("100"))] }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("0.01") ).assert_success(); } pub(crate) fn mint_token(token: &ContractAccount<TestToken>, user: &UserAccount, amount: Balance) { call!( user, token.mint(to_va(user.account_id.clone()), amount.into()) ).assert_success(); }
use near_sdk::json_types::{U128}; use near_sdk::{Balance}; use near_sdk_sim::{call, to_yocto, ContractAccount, UserAccount, DEFAULT_GAS}; use test_token::ContractContract as TestToken; use ref_farming::{ContractContract as Farming}; use ref_farming::{HRSimpleFarmTerms}; use near_sdk::serde_json::Value; use near_sdk::serde_json::json; use super::init::*; use super::utils::*; #[allow(dead_code)] pub(crate) fn prepair_pool_and_liquidity( root: &UserAccount, owner: &UserAccount, farming_id: String, lps: Vec<&UserAccount>, ) -> (UserAccount, ContractAccount<TestToken>, ContractAccount<TestToken>) { let pool = deploy_pool(&root, swap(), owner.account_id()); let token1 = deploy_token(&root, dai(), vec![swap()]); let token2 = deploy_token(&root, eth(), vec![swap()]); owner.call( pool.account_id(), "extend_whitelisted_tokens", &json!({ "tokens": vec![to_va(dai()), to_va(eth())] }).to_string().into_bytes(), DEFAULT_GAS, 0 ).assert_success(); root.call( pool.account_id(), "add_simple_pool", &json!({ "tokens": vec![to_va(dai()), to_va(eth())], "fee": 25 }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); root.call( pool.account_id(), "mft_register", &json!({ "token_id": ":0".to_string(), "account_id": farming_id }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); for lp in lps { add_liqudity(lp, &pool, &token1, &token2, 0); } (pool,token1, token2) } #[allow(dead_code)] pub(crate) fn prepair_pool( root: &UserAccount, owne
#[allow(dead_code)] pub(crate) fn prepair_farm( root: &UserAccount, owner: &UserAccount, token: &ContractAccount<TestToken>, total_reward: Balance, ) -> (ContractAccount<Farming>, String) { let farming = deploy_farming(&root, farming_id(), owner.account_id()); let out_come = call!( owner, farming.create_simple_farm(HRSimpleFarmTerms{ seed_id: format!("{}@0", swap()), reward_token: to_va(token.account_id()), start_at: 0, reward_per_session: to_yocto("1").into(), session_interval: 60, }, Some(U128(1000000000000000000)), None, None), deposit = to_yocto("1") ); out_come.assert_success(); let farm_id: String; if let Value::String(farmid) = out_come.unwrap_json_value() { farm_id = farmid.clone(); } else { farm_id = String::from("N/A"); } call!( root, token.storage_deposit(Some(to_va(farming_id())), None), deposit = to_yocto("1") ) .assert_success(); mint_token(&token, &root, total_reward.into()); call!( root, token.ft_transfer_call(to_va(farming_id()), total_reward.into(), None, farm_id.clone()), deposit = 1 ) .assert_success(); (farming, farm_id) } #[allow(dead_code)] pub(crate) fn prepair_multi_farms( root: &UserAccount, owner: &UserAccount, token: &ContractAccount<TestToken>, total_reward: Balance, farm_count: u32, ) -> (ContractAccount<Farming>, Vec<String>) { let farming = deploy_farming(&root, farming_id(), owner.account_id()); let mut farm_ids: Vec<String> = vec![]; call!( root, token.storage_deposit(Some(to_va(farming_id())), None), deposit = to_yocto("1") ) .assert_success(); mint_token(&token, &root, to_yocto("100000")); for _ in 0..farm_count { let out_come = call!( owner, farming.create_simple_farm(HRSimpleFarmTerms{ seed_id: format!("{}@0", swap()), reward_token: to_va(token.account_id()), start_at: 0, reward_per_session: to_yocto("1").into(), session_interval: 60, }, Some(U128(1000000000000000000)), None, None), deposit = to_yocto("1") ); out_come.assert_success(); let farm_id: String; if let Value::String(farmid) = out_come.unwrap_json_value() { farm_id = farmid.clone(); } else { farm_id = String::from("N/A"); } call!( root, token.ft_transfer_call(to_va(farming_id()), total_reward.into(), None, farm_id.clone()), deposit = 1 ) .assert_success(); farm_ids.push(farm_id.clone()); println!(" Farm {} created and running at Height#{}", farm_id.clone(), root.borrow_runtime().current_block().block_height); } (farming, farm_ids) } pub(crate) fn add_liqudity( user: &UserAccount, pool: &UserAccount, token1: &ContractAccount<TestToken>, token2: &ContractAccount<TestToken>, pool_id: u64, ) { mint_token(&token1, user, to_yocto("105")); mint_token(&token2, user, to_yocto("105")); user.call( pool.account_id(), "storage_deposit", &json!({}).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); call!( user, token1.ft_transfer_call(to_va(swap()), to_yocto("100").into(), None, "".to_string()), deposit = 1 ) .assert_success(); call!( user, token2.ft_transfer_call(to_va(swap()), to_yocto("100").into(), None, "".to_string()), deposit = 1 ) .assert_success(); user.call( pool.account_id(), "add_liquidity", &json!({ "pool_id": pool_id, "amounts": vec![U128(to_yocto("100")), U128(to_yocto("100"))] }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("0.01") ).assert_success(); } pub(crate) fn mint_token(token: &ContractAccount<TestToken>, user: &UserAccount, amount: Balance) { call!( user, token.mint(to_va(user.account_id.clone()), amount.into()) ).assert_success(); }
r: &UserAccount, ) -> (UserAccount, ContractAccount<TestToken>, ContractAccount<TestToken>) { let pool = deploy_pool(&root, swap(), owner.account_id()); let token1 = deploy_token(&root, dai(), vec![swap()]); let token2 = deploy_token(&root, eth(), vec![swap()]); owner.call( pool.account_id(), "extend_whitelisted_tokens", &json!({ "tokens": vec![to_va(dai()), to_va(eth())] }).to_string().into_bytes(), DEFAULT_GAS, 0 ); root.call( pool.account_id(), "add_simple_pool", &json!({ "tokens": vec![to_va(dai()), to_va(eth())], "fee": 25 }).to_string().into_bytes(), DEFAULT_GAS, to_yocto("1") ).assert_success(); (pool, token1, token2) }
function_block-function_prefixed
[ { "content": "fn parse_token_id(token_id: String) -> TokenOrPool {\n\n if let Ok(pool_id) = try_identify_sub_token_id(&token_id) {\n\n TokenOrPool::Pool(pool_id)\n\n } else {\n\n TokenOrPool::Token(token_id)\n\n }\n\n}\n\n\n\n/// seed token deposit\n\n#[near_bindgen]\n\nimpl MFTTokenRecei...
Rust
tests/hvac.rs
uber-foo/hvac
7d6680a3c0e1e09e2ba9bd4446bd3ed0d3ca67c0
use hvac::prelude::*; #[test] fn new_hvac_is_idle() { let mut hvac = Hvac::default(); let state = hvac.tick(0); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn new_hvac_enforces_min_heat_recover_constraints() { let mut hvac = Hvac::default().with_heat(None, Some(100)); let state = hvac.heat(); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); } #[test] fn new_hvac_enforces_min_cool_recover_constraints() { let mut hvac = Hvac::default().with_cool(None, Some(100)); let state = hvac.cool(); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); } #[test] fn new_hvac_enforces_min_fan_recover_constraints() { let mut hvac = Hvac::default().with_fan(None, Some(100)); let state = hvac.fan_auto(false); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, None); assert_eq!(state.fan, true); } #[test] fn hvac_fan_auto_with_heat() { let mut hvac = Hvac::default().with_heat(None, None).with_fan(None, None); let state = hvac.heat(); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn hvac_fan_auto_with_cool() { let mut hvac = Hvac::default().with_cool(None, None).with_fan(None, None); let state = hvac.cool(); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn hvac_fan_auto_sequence() { let mut hvac = Hvac::default() .with_heat(None, None) .with_cool(None, None) .with_fan(None, None); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.cool(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.cool(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); } #[test] fn hvac_fan_manual() { let mut hvac = Hvac::default() .with_heat(None, None) .with_cool(None, None) .with_fan(None, None); let state = hvac.fan_auto(false); assert_eq!(state.service, None); assert_eq!(state.fan, true); let state = hvac.heat(); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); let state = hvac.cool(); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, true); let state = hvac.fan_auto(true); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn fan_auto_min_run_carries_past_heat() { let mut hvac = Hvac::default() .with_heat(None, None) .with_fan(Some(1), None); let state = hvac.tick(0); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, true); let state = hvac.tick(1); assert_eq!(state.fan, false); }
use hvac::prelude::*; #[test] fn new_hvac_is_idle() { let mut hvac = Hvac::default(); let state = hvac.tick(0); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn new_hvac_enforces_min_heat_recover_constraints() { let mut hvac = Hvac::default().with_heat(None, Some(100)); let state = hvac.heat(); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); } #[test] fn new_hvac_enforces_min_cool_recover_constraints() { let mut hvac = Hvac::default().with_cool(None, Some(100)); let state = hvac.cool(); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); } #[test] fn new_hvac_enforces_min_fan_recover_constraints() { let mut hvac = Hvac::default().with_fan(None, Some(100)); let state = hvac.fan_auto(false); assert_eq!(state.service, None); assert_eq!(state.fan, false); for i in 0..100 { let state = hvac.tick(i); assert_eq!(state.service, None); assert_eq!(state.fan, false); } let state = hvac.tick(100); assert_eq!(state.service, None); assert_eq!(state.fan, true); } #[test] fn hvac_fan_auto_with_heat() { let mut hvac = Hvac::default().with_heat(None,
t state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn hvac_fan_auto_with_cool() { let mut hvac = Hvac::default().with_cool(None, None).with_fan(None, None); let state = hvac.cool(); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn hvac_fan_auto_sequence() { let mut hvac = Hvac::default() .with_heat(None, None) .with_cool(None, None) .with_fan(None, None); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.cool(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); let state = hvac.cool(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, false); } #[test] fn hvac_fan_manual() { let mut hvac = Hvac::default() .with_heat(None, None) .with_cool(None, None) .with_fan(None, None); let state = hvac.fan_auto(false); assert_eq!(state.service, None); assert_eq!(state.fan, true); let state = hvac.heat(); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); let state = hvac.cool(); assert_eq!(state.service, Some(HvacService::Cool)); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.service, None); assert_eq!(state.fan, true); let state = hvac.fan_auto(true); assert_eq!(state.service, None); assert_eq!(state.fan, false); } #[test] fn fan_auto_min_run_carries_past_heat() { let mut hvac = Hvac::default() .with_heat(None, None) .with_fan(Some(1), None); let state = hvac.tick(0); assert_eq!(state.fan, false); let state = hvac.heat(); assert_eq!(state.fan, true); let state = hvac.idle(); assert_eq!(state.fan, true); let state = hvac.tick(1); assert_eq!(state.fan, false); }
None).with_fan(None, None); let state = hvac.heat(); assert_eq!(state.service, Some(HvacService::Heat)); assert_eq!(state.fan, true); le
function_block-random_span
[ { "content": "fn wait_seconds(\n\n last_update: Option<u32>,\n\n min_seconds: Option<u32>,\n\n last_change: Option<u32>,\n\n) -> Option<u32> {\n\n if let Some(last_update) = last_update {\n\n if let Some(min_seconds) = min_seconds {\n\n let delta = last_update - last_change.unwrap_...
Rust
crates/parser/src/lib.rs
fangerm/gelixrs
de7b7b0b53ed8a4bcbe6b6484103b07e16f420e1
mod declaration; mod expression; mod nodes; mod util; use crate::util::{ builder::{Checkpoint, NodeBuilder}, source::Source, }; use common::bench; use error::{Error, ErrorSpan, GErr}; use lexer::Lexer; pub use nodes::*; use syntax::kind::SyntaxKind; pub fn parse(input: &str) -> Result<ParseResult, Vec<Error>> { let lexer = Lexer::new(input); let lexemes = lexer .map(|(tok, lexeme)| Lexeme { kind: tok.into(), lexeme, }) .collect::<Vec<_>>(); let parser = Parser::new(&lexemes); parser.parse() } #[derive(Copy, Clone)] struct Lexeme<'t> { kind: SyntaxKind, lexeme: &'t str, } struct Parser<'p> { source: Source<'p>, builder: NodeBuilder, errors: Vec<Error>, poisoned: bool, modifiers: Vec<SyntaxKind>, } impl<'p> Parser<'p> { fn parse(mut self) -> Result<ParseResult, Vec<Error>> { bench!("parser", { while self.peek() != SyntaxKind::EndOfFile { self.declaration(); if self.poisoned { self.try_depoison(); } } }); if self.errors.is_empty() { Ok(ParseResult { green_node: self.builder.finish(), }) } else { Err(self.errors) } } fn matches(&mut self, kind: SyntaxKind) -> bool { let matches = self.check(kind); if matches { self.advance(); } matches } fn matches_separator(&mut self) -> bool { self.matches(SyntaxKind::Semicolon) } fn consume(&mut self, kind: SyntaxKind, want: &'static str, after: &'static str) { if self.advance_checked() != kind { self.error_at_current(GErr::E001 { want, after }); } } fn consume_either( &mut self, kind1: SyntaxKind, kind2: SyntaxKind, want: &'static str, after: &'static str, ) { if self.peek() != kind1 && self.peek() != kind2 { self.error_at_current(GErr::E001 { want, after }); } else { self.advance(); } } fn error_at_current(&mut self, err: GErr) { if self.poisoned { self.advance_checked(); return; } let err = Error { index: ErrorSpan::Token(self.source.position()), kind: err, }; self.errors.push(err); self.poisoned = true; } fn try_depoison(&mut self) { let recoverable = &[ SyntaxKind::Enum, SyntaxKind::Class, SyntaxKind::Func, SyntaxKind::Import, SyntaxKind::Export, SyntaxKind::Impl, SyntaxKind::Interface, SyntaxKind::EndOfFile, ]; while !recoverable.contains(&self.peek()) { self.advance_checked(); } self.poisoned = false; } fn check(&mut self, kind: SyntaxKind) -> bool { self.peek() == kind } fn check_next(&mut self, kind: SyntaxKind) -> bool { self.peek_next() == kind } fn advance(&mut self) -> Lexeme<'p> { self.skip_whitespace(); self.advance_inner() } fn advance_inner(&mut self) -> Lexeme<'p> { let Lexeme { kind, lexeme } = self.source.get_current().unwrap(); self.source.next(); self.builder.token(kind, lexeme.into()); Lexeme { kind, lexeme } } fn advance_checked(&mut self) -> SyntaxKind { if self.is_at_end() { SyntaxKind::EndOfFile } else { self.advance().kind } } fn peek(&mut self) -> SyntaxKind { self.skip_whitespace(); self.peek_raw().unwrap_or(SyntaxKind::EndOfFile) } fn peek_next(&mut self) -> SyntaxKind { self.source.save(); self.skip_whitespace(); self.source.next(); while self.peek_raw().map(|k| k.should_skip()) == Some(true) { self.source.next(); } let ret = self.peek_raw().unwrap_or(SyntaxKind::EndOfFile); self.source.restore(); ret } fn last_was_whitespace(&mut self) -> bool { self.source.get_last().kind.should_skip() } fn peek_raw(&self) -> Option<SyntaxKind> { self.source.get_current().map(|Lexeme { kind, .. }| kind) } fn skip_whitespace(&mut self) { while self.peek_raw().map(|k| k.should_skip()) == Some(true) { self.advance_inner(); } } fn is_at_end(&self) -> bool { self.source.get_current().is_none() } fn node_with<T: FnOnce(&mut Self)>(&mut self, kind: SyntaxKind, content: T) { self.start_node(kind); content(self); self.end_node() } fn start_node(&mut self, kind: SyntaxKind) { self.skip_whitespace(); self.builder.start_node(kind); } fn start_node_at(&mut self, checkpoint: Checkpoint, kind: SyntaxKind) { self.builder.start_node_at(kind, checkpoint); self.skip_whitespace(); } fn end_node(&mut self) { self.builder.end_node(); } fn checkpoint(&mut self) -> Checkpoint { self.builder.checkpoint() } fn new(lexemes: &'p [Lexeme<'p>]) -> Self { Self { source: Source::new(lexemes), builder: NodeBuilder::new(), errors: vec![], poisoned: false, modifiers: Vec::with_capacity(4), } } } #[derive(Debug)] pub struct ParseResult { green_node: Node, } impl ParseResult { pub fn root(self) -> Node { self.green_node } }
mod declaration; mod expression; mod nodes; mod util; use crate::util::{ builder::{Checkpoint, NodeBuilder}, source::Source, }; use common::bench; use error::{Error, ErrorSpan, GErr}; use lexer::Lexer; pub use nodes::*; use syntax::kind::SyntaxKind; pub fn parse(input: &str) -> Result<ParseResult, Vec<Error>> { let lexer = Lexer::new(input); let lexemes = lexer .map(|(tok, lexeme)| Lexeme { kind: tok.into(), lexeme, }) .collect::<Vec<_>>(); let parser = Parser::new(&lexemes); parser.parse() } #[derive(Copy, Clone)] struct Lexeme<'t> { kind: SyntaxKind, lexeme: &'t str, } struct Parser<'p> { source: Source<'p>, builder: NodeBuilder, errors: Vec<Error>, poisoned: bool, modifiers: Vec<SyntaxKind>, } impl<'p> Parser<'p> { fn parse(mut self) -> Result<ParseResult, Vec<Error>> { bench!("parser", { while self.peek() != SyntaxKind::EndOfFile { self.declaration(); if self.poisoned { self.try_depoison(); } } }); if self.errors.is_empty() { Ok(ParseResult { green_node: self.builder.finish(), }) } else { Err(self.errors) } } fn matches(&mut self, kind: SyntaxKind) -> bool { let matches = self.check(kind); if matches { self.advance(); } matches } fn matches_separator(&mut self) -> bool { self.matches(SyntaxKind::Semicolon) } fn consume(&mut self, kind: SyntaxKind, want: &'static str, after: &'static str) { if self.advance_checked() != kind { self.error_at_current(GErr::E001 { want, after }); } } fn consume_either( &mut self, kind1: SyntaxKind, kind2: SyntaxKind, want: &'static str, after: &'static str, ) { if self.peek() != kind1 && self.peek() != kind2 { self.error_at_current(GErr::E001 { want, after }); } else { self.advance(); } } fn error_at_current(&mut self, err: GErr) { if self.poisoned { self.advance_checked(); return; } let err = Error { index: ErrorSpan::Token(self.source.position()), kind: err, }; self.errors.push(err); self.poisoned = true; } fn try_depoison(&mut self) { let recoverable = &[ SyntaxKind::Enum, SyntaxKind::Class, SyntaxKind::Func, SyntaxKind::Import, SyntaxKind::Export, SyntaxKind::Impl, SyntaxKind::Interface, SyntaxKind::EndOfFile, ]; while !recoverable.contains(&self.peek()) { self.advance_checked(); } self.poisoned = false; } fn check(&mut self, kind: SyntaxKind) -> bool { self.peek() == kind } fn check_next(&mut self, kind: SyntaxKind) -> bool { self.peek_next() == kind } fn advance(&mut self) -> Lexeme<'p> { self.skip_whitespace(); self.advance_inner() } fn advance_inner(&mut self) -> Lexeme<'p> { let Lexeme { kind, lexeme } = self.source.get_current().unwrap(); self.source.next(); self.builder.token(kind, lexeme.into()); Lexeme { kind, lexeme } } fn advance_checked(&mut self) -> SyntaxKind { if self.is_at_end() { SyntaxKind::EndOfFile } else { self.advance().kind } } fn peek(&mut self) -> SyntaxKind { self.skip_whitespace(); self.peek_raw().unwrap_or(SyntaxKind::EndOfFile) } fn peek_next(&mut self) -> SyntaxKind { self.source.save(); self.skip_whitespace(); self.source.next(); while self.peek_raw().map(|k| k.should_skip()) == Some(true) { self.source.next(); } let ret = self.peek_raw().unwrap_or(SyntaxKind::EndOfFile); self.source.restore(); ret } fn last_was_whitespace(&mut self) -> bool { self.source.get_last().kind.should_skip() } fn peek_raw(&self) -> Option<SyntaxKind> { self.source.get_current().map(|Lexeme { kind, .. }| kind) } fn skip_whitespace(&mut self) { while self.peek_raw().map(|k| k.should_skip()) == Some(true) { self.advance_inner(); } } fn is_at_end(&self) -> bool { self.source.get_current().is_none() } fn node_with<T: FnOnce(&mut Self)>(&mut self, kind: SyntaxKind, content: T) { self.start_node(k
errors: vec![], poisoned: false, modifiers: Vec::with_capacity(4), } } } #[derive(Debug)] pub struct ParseResult { green_node: Node, } impl ParseResult { pub fn root(self) -> Node { self.green_node } }
ind); content(self); self.end_node() } fn start_node(&mut self, kind: SyntaxKind) { self.skip_whitespace(); self.builder.start_node(kind); } fn start_node_at(&mut self, checkpoint: Checkpoint, kind: SyntaxKind) { self.builder.start_node_at(kind, checkpoint); self.skip_whitespace(); } fn end_node(&mut self) { self.builder.end_node(); } fn checkpoint(&mut self) -> Checkpoint { self.builder.checkpoint() } fn new(lexemes: &'p [Lexeme<'p>]) -> Self { Self { source: Source::new(lexemes), builder: NodeBuilder::new(),
random
[ { "content": "/// Produces a new error for the GIR.\n\npub fn gir_err(cst: CSTNode, err: GErr) -> Error {\n\n Error {\n\n index: ErrorSpan::Span(cst.text_range()),\n\n kind: err,\n\n }\n\n}\n", "file_path": "crates/gir-nodes/src/lib.rs", "rank": 0, "score": 299536.0737118246 },...
Rust
src/api.rs
sinsoku/miteras-cli
2dfca1619353bfb35992de7e9ae8e9878a89062c
use crate::config::Config; use chrono::prelude::*; #[cfg(test)] use mockito; use reqwest::blocking::{Client, Response}; use reqwest::header; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; static APP_USER_AGENT: &str = "miteras-cli"; pub struct Api { config: Config, client: Client, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct ClockInParams { clock_in_condition: HashMap<String, i32>, daily_place_evidence: HashMap<String, i32>, work_date_string: String, enable_break_time: bool, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct ClockOutParams { clock_out_condition: HashMap<String, i32>, daily_place_evidence: HashMap<String, i32>, work_date_string: String, stamp_break_start: String, stamp_break_end: String, updated_date_string: String, } fn condition_value(condition: &str) -> i32 { match condition { "best" => 1, "good" => 2, "normal" => 3, "bad" => 4, _ => -1, } } fn work_date_string() -> String { let today = Local::today(); format!("{}-{}-{}", today.year(), today.month(), today.day()) } fn parse_csrf(body: String) -> String { let fragment = Html::parse_fragment(&body); let selector = Selector::parse("meta[name='_csrf'], input[name='_csrf']").unwrap(); let tag = fragment.select(&selector).next().unwrap().value(); let attr = if tag.name() == "meta" { "content" } else { "value" }; tag.attr(attr).unwrap().to_string() } fn parse_updated_date_string(body: String) -> String { let fragment = Html::parse_fragment(&body); let selector = Selector::parse("#daily-attendance").unwrap(); let tag = fragment.select(&selector).next().unwrap().value(); tag.attr("data-updated-date").unwrap().to_string() } impl Api { pub fn new(config: &Config) -> Api { let conf = Config::new( (*config.org).to_string(), (*config.username).to_string(), (*config.password).to_string(), ); let client = Client::builder() .cookie_store(true) .user_agent(APP_USER_AGENT) .build() .unwrap(); Api { config: conf, client: client, } } pub fn login(&self) -> Result<Response, reqwest::Error> { let login_url = self.build_url("login"); let login_res = self.client.get(&login_url).send().unwrap(); let csrf = parse_csrf(login_res.text().unwrap()); let auth_url = self.build_url("auth"); let mut params: HashMap<&str, &str> = HashMap::new(); params.insert("username", &self.config.username); params.insert("password", &self.config.password); params.insert("_csrf", &csrf); self.client .post(&auth_url) .form(&params) .header(header::REFERER, login_url) .send() } pub fn clock_in(&self, condition: &str) -> Result<Response, reqwest::Error> { let auth_res = self.login().unwrap(); let csrf = parse_csrf(auth_res.text().unwrap()); let cico_url = self.build_url("cico"); let url = self.build_url("submitClockIn"); let mut clock_in_condition = HashMap::new(); clock_in_condition.insert("condition".to_string(), condition_value(condition)); let params = ClockInParams { clock_in_condition: clock_in_condition, daily_place_evidence: HashMap::new(), work_date_string: work_date_string(), enable_break_time: false, }; self.client .post(&url) .json(&params) .header("X-CSRF-TOKEN", csrf) .header(header::REFERER, cico_url) .send() } pub fn clock_out(&self, condition: &str) -> Result<Response, reqwest::Error> { let auth_res = self.login().unwrap(); let auth_body = auth_res.text().unwrap(); let csrf = parse_csrf(auth_body.clone()); let updated_date_string = parse_updated_date_string(auth_body); let cico_url = self.build_url("cico"); let url = self.build_url("submitClockOut"); let mut clock_out_condition = HashMap::new(); clock_out_condition.insert("condition".to_string(), condition_value(condition)); let params = ClockOutParams { clock_out_condition: clock_out_condition, daily_place_evidence: HashMap::new(), work_date_string: work_date_string(), stamp_break_start: "".to_string(), stamp_break_end: "".to_string(), updated_date_string: updated_date_string, }; self.client .post(&url) .json(&params) .header("X-CSRF-TOKEN", csrf) .header(header::REFERER, cico_url) .send() } fn build_url(&self, path: &str) -> String { #[cfg(not(test))] let endpoint = "https://kintai.miteras.jp"; #[cfg(test)] let endpoint = &mockito::server_url(); format!("{}/{}/{}", endpoint, self.config.org, path) } } #[cfg(test)] mod tests { use super::condition_value; #[test] fn str_to_num() { assert_eq!(1, condition_value("best")); assert_eq!(2, condition_value("good")); assert_eq!(3, condition_value("normal")); assert_eq!(4, condition_value("bad")); } }
use crate::config::Config; use chrono::prelude::*; #[cfg(test)] use mockito; use reqwest::blocking::{Client, Response}; use reqwest::header; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; static APP_USER_AGENT: &str = "miteras-cli"; pub struct Api { config: Config, client: Client, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct ClockInParams { clock_in_condition: HashMap<String, i32>, daily_place_evidence: HashMap<String, i32>, work_date_string: String, enable_break_time: bool, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] struct ClockOutParams { clock_out_condition: HashMap<String, i32>, daily_place_evidence: HashMap<String, i32>, work_date_string: String, stamp_break_start: String, stamp_break_end: String, updated_date_string: String, } fn condition_value(condition: &str) -> i32 { match condition { "best" => 1, "good" => 2, "normal" => 3, "bad" => 4, _ => -1, } } fn work_date_string() -> String { let today = Local::today(); format!("{}-{}-{}", today.year(), today.month(), today.day()) } fn parse_csrf(body: String) -> String { let fragment = Html::parse_fragment(&body); let selector = Selector::parse("meta[name='_csrf'], input[name='_csrf']").unwrap(); let tag = fragment.select(&selector).next().unwrap().value(); let attr = if tag.name() == "meta" { "content" } else { "value" }; tag.attr(attr).unwrap().to_string() } fn parse_updated_date_string(body: String) -> String { let fragment = Html::parse_fragment(&body); let selector = Selector::parse("#daily-attendance").unwrap(); let tag = fragment.select(&selector).next().unwrap().value(); tag.attr("data-updated-date").unwrap().to_string() } impl Api { pub fn new(config: &Config) -> Api { let conf = Config::new( (*config.org).to_string(), (*config.username).to_string(), (*config.password).to_string(), ); let client = Client::builder() .cookie_store(true) .user_agent(APP_USER_AGENT) .build() .unwrap(); Api { config: conf, client: client, } }
pub fn clock_in(&self, condition: &str) -> Result<Response, reqwest::Error> { let auth_res = self.login().unwrap(); let csrf = parse_csrf(auth_res.text().unwrap()); let cico_url = self.build_url("cico"); let url = self.build_url("submitClockIn"); let mut clock_in_condition = HashMap::new(); clock_in_condition.insert("condition".to_string(), condition_value(condition)); let params = ClockInParams { clock_in_condition: clock_in_condition, daily_place_evidence: HashMap::new(), work_date_string: work_date_string(), enable_break_time: false, }; self.client .post(&url) .json(&params) .header("X-CSRF-TOKEN", csrf) .header(header::REFERER, cico_url) .send() } pub fn clock_out(&self, condition: &str) -> Result<Response, reqwest::Error> { let auth_res = self.login().unwrap(); let auth_body = auth_res.text().unwrap(); let csrf = parse_csrf(auth_body.clone()); let updated_date_string = parse_updated_date_string(auth_body); let cico_url = self.build_url("cico"); let url = self.build_url("submitClockOut"); let mut clock_out_condition = HashMap::new(); clock_out_condition.insert("condition".to_string(), condition_value(condition)); let params = ClockOutParams { clock_out_condition: clock_out_condition, daily_place_evidence: HashMap::new(), work_date_string: work_date_string(), stamp_break_start: "".to_string(), stamp_break_end: "".to_string(), updated_date_string: updated_date_string, }; self.client .post(&url) .json(&params) .header("X-CSRF-TOKEN", csrf) .header(header::REFERER, cico_url) .send() } fn build_url(&self, path: &str) -> String { #[cfg(not(test))] let endpoint = "https://kintai.miteras.jp"; #[cfg(test)] let endpoint = &mockito::server_url(); format!("{}/{}/{}", endpoint, self.config.org, path) } } #[cfg(test)] mod tests { use super::condition_value; #[test] fn str_to_num() { assert_eq!(1, condition_value("best")); assert_eq!(2, condition_value("good")); assert_eq!(3, condition_value("normal")); assert_eq!(4, condition_value("bad")); } }
pub fn login(&self) -> Result<Response, reqwest::Error> { let login_url = self.build_url("login"); let login_res = self.client.get(&login_url).send().unwrap(); let csrf = parse_csrf(login_res.text().unwrap()); let auth_url = self.build_url("auth"); let mut params: HashMap<&str, &str> = HashMap::new(); params.insert("username", &self.config.username); params.insert("password", &self.config.password); params.insert("_csrf", &csrf); self.client .post(&auth_url) .form(&params) .header(header::REFERER, login_url) .send() }
function_block-full_function
[ { "content": "pub fn build_cli() -> App<'static, 'static> {\n\n app_from_crate!()\n\n .setting(AppSettings::SubcommandRequiredElseHelp)\n\n .subcommand(\n\n SubCommand::with_name(\"login\").about(\"Authenticate to MITERAS and save credentials\"),\n\n )\n\n .subcommand(\...
Rust
01-running/src/main.rs
davidhollis/rust-gba-scratchpad
2d02fd4839bca33f6ef4167e5f83af3db7c517ff
#![no_std] #![no_main] #![feature(asm)] use core::cmp::{ max, min }; use gba::prelude::*; use gbainputs::{ Key, KeyMonitor }; use gbamath::fixed::{ UFixed8, SFixed8 }; use gbamath::geometry::BoundingBox; use gbamath::Vec2D; #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { mode3::dma3_clear_to(Color::from_rgb(31,0,0)); loop {} } enum PlayerState { Standing, Walking, } struct Player { old_position: Vec2D<UFixed8>, current_position: Vec2D<UFixed8>, old_velocity: Vec2D<SFixed8>, current_velocity: Vec2D<SFixed8>, collision_box: BoundingBox, box_offset: Vec2D<SFixed8>, inputs: KeyMonitor, state: PlayerState, collision_state: u8, } impl Player { const COLOR: Color = Color::from_rgb(0, 0, 31); const CENTER_COLOR: Color = Color::from_rgb(0, 31, 0); const ANCHOR_COLOR: Color = Color::from_rgb(31, 31, 0); const WALK_SPEED: SFixed8 = SFixed8::constant(2i16); const TOP_COLLISION_LAST_FRAME: u8 = 0b1000_0000; const TOP_COLLISION_THIS_FRAME: u8 = 0b0100_0000; const BOTTOM_COLLISION_LAST_FRAME: u8 = 0b0010_0000; const BOTTOM_COLLISION_THIS_FRAME: u8 = 0b0001_0000; const LEFT_COLLISION_LAST_FRAME: u8 = 0b0000_1000; const LEFT_COLLISION_THIS_FRAME: u8 = 0b0000_0100; const RIGHT_COLLISION_LAST_FRAME: u8 = 0b0000_0010; const RIGHT_COLLISION_THIS_FRAME: u8 = 0b0000_0001; const LAST_FRAME_STATES: u8 = Player::TOP_COLLISION_LAST_FRAME | Player::BOTTOM_COLLISION_LAST_FRAME | Player::LEFT_COLLISION_LAST_FRAME | Player::RIGHT_COLLISION_LAST_FRAME; fn update(&mut self) { self.inputs.update(); match self.state { PlayerState::Standing => { self.current_velocity = VEC2D_ZERO; if self.inputs.is_pressed(Key::LEFT) != self.inputs.is_pressed(Key::RIGHT) { self.state = PlayerState::Walking; } }, PlayerState::Walking => { if self.inputs.is_pressed(Key::LEFT) == self.inputs.is_pressed(Key::RIGHT) { self.state = PlayerState::Standing; self.current_velocity = VEC2D_ZERO; } else if self.inputs.is_pressed(Key::RIGHT) { if self.collision_state & Player::RIGHT_COLLISION_THIS_FRAME > 0 { self.current_velocity.x = SFixed8::ZERO; } else { self.current_velocity.x = Player::WALK_SPEED; } } else if self.inputs.is_pressed(Key::LEFT) { if self.collision_state & Player::LEFT_COLLISION_THIS_FRAME > 0 { self.current_velocity.x = SFixed8::ZERO; } else { self.current_velocity.x = -Player::WALK_SPEED; } } }, }; self.update_physics(); } fn update_physics(&mut self) { self.old_position = self.current_position; self.old_velocity = self.current_velocity; self.collision_state = (self.collision_state << 1) & Player::LAST_FRAME_STATES; self.current_position.saturating_add_signed_assign(self.current_velocity); self.collision_box.center = self.current_position.saturating_add_signed(self.box_offset); if self.collision_box.left() < LEFT_WALL_X { let new_collision_box_center_x = LEFT_WALL_X + self.collision_box.half_size.x; self.current_position.x = new_collision_box_center_x.saturating_add_signed(-self.box_offset.x); self.collision_box.center.x = new_collision_box_center_x; self.current_velocity.x = max(self.current_velocity.x, SFixed8::ZERO); self.collision_state |= Player::LEFT_COLLISION_THIS_FRAME; } else if self.collision_box.right() > RIGHT_WALL_X { let new_collision_box_center_x = RIGHT_WALL_X - self.collision_box.half_size.x; self.current_position.x = new_collision_box_center_x.saturating_add_signed(-self.box_offset.x); self.collision_box.center.x = new_collision_box_center_x; self.current_velocity.x = min(self.current_velocity.x, SFixed8::ZERO); self.collision_state |= Player::RIGHT_COLLISION_THIS_FRAME; } } #[inline] fn draw(&self) { let left: u16 = self.collision_box.left().into(); let right: u16 = self.collision_box.right().into(); let top: u16 = self.collision_box.top().into(); let bottom: u16 = self.collision_box.bottom().into(); fill_rect(left, right, top, bottom, Player::COLOR); let center_x: u16 = self.collision_box.center.x.into(); let center_y: u16 = self.collision_box.center.y.into(); mode3::bitmap_xy(center_x.into(), center_y.into()).write(Player::CENTER_COLOR); let player_x: u16 = self.current_position.x.into(); let player_y: u16 = self.current_position.y.into(); mode3::bitmap_xy(player_x.into(), player_y.into()).write(Player::ANCHOR_COLOR); } } const BACKGROUND_COLOR: Color = Color::from_rgb(15, 15, 15); const WALL_COLOR: Color = Color::from_rgb(0, 0, 0); const VEC2D_ZERO: Vec2D<SFixed8> = Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }; const LEFT_WALL_X: UFixed8 = UFixed8::constant(20u16); const RIGHT_WALL_X: UFixed8 = UFixed8::constant(219u16); const FLOOR_Y: u16 = 130u16; #[no_mangle] fn main() -> ! { const SETUP_DISPLAY: DisplayControl = DisplayControl::new().with_display_mode(3).with_display_bg2(true); DISPCNT.write(SETUP_DISPLAY); let mut player: Player = Player { old_position: Vec2D { x: UFixed8::from(100u16), y: FLOOR_Y.into() }, current_position: Vec2D { x: UFixed8::from(100u16), y: FLOOR_Y.into() }, old_velocity: Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }, current_velocity: Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }, collision_box: BoundingBox { center: Vec2D { x: UFixed8::ZERO, y: UFixed8::ZERO }, half_size: Vec2D { x: 8u16.into(), y: 16u16.into() }, }, box_offset: Vec2D { x: 8i16.into(), y: (-16i16).into() }, inputs: KeyMonitor::new(), state: PlayerState::Standing, collision_state: 0, }; mode3::dma3_clear_to(WALL_COLOR); loop { spin_until_vdraw(); player.update(); spin_until_vblank(); fill_rect( u16::from(LEFT_WALL_X), u16::from(RIGHT_WALL_X), 0u16, FLOOR_Y, BACKGROUND_COLOR ); player.draw(); } } #[inline] fn fill_rect(left: u16, right: u16, top: u16, bottom: u16, color: Color) { let raw_color: u16 = color.0; let word_count: u16 = right - left + 1; for y in top..=bottom { unsafe { DMA3SAD.write(&raw_color as *const _ as usize); DMA3DAD.write(0x0600_0000usize + ((mode3::WIDTH * (y as usize)) + (left as usize)) * 2usize); DMA3CNT_L.write(word_count); const CTRL: DmaControl = DmaControl::new() .with_dest_addr(DestAddrControl::Increment) .with_src_addr(SrcAddrControl::Fixed) .with_transfer_u32(false) .with_start_time(DmaStartTiming::Immediately) .with_enabled(true); DMA3CNT_H.write(CTRL); asm!( " nop nop ", options(nostack), ); } } } #[inline] fn spin_until_vblank() { while VCOUNT.read() < 160 {} } #[inline] fn spin_until_vdraw() { while VCOUNT.read() >= 160 {} }
#![no_std] #![no_main] #![feature(asm)] use core::cmp::{ max, min }; use gba::prelude::*; use gbainputs::{ Key, KeyMonitor }; use gbamath::fixed::{ UFixed8, SFixed8 }; use gbamath::geometry::BoundingBox; use gbamath::Vec2D; #[panic_handler] fn panic(_info: &core::panic::PanicInfo) -> ! { mode3::dma3_clear_to(Color::from_rgb(31,0,0)); loop {} } enum PlayerState { Standing, Walking, } struct Player { old_position: Vec2D<UFixed8>, current_position: Vec2D<UFixed8>, old_velocity: Vec2D<SFixed8>, current_velocity: Vec2D<SFixed8>, collision_box: BoundingBox, box_offset: Vec2D<SFixed8>, inputs: KeyMonitor, state: PlayerState, collision_state: u8, } impl Player { const COLOR: Color = Color::from_rgb(0, 0, 31); const CENTER_COLOR: Color = Color::from_rgb(0, 31, 0); const ANCHOR_COLOR: Color = Color::from_rgb(31, 31, 0); const WALK_SPEED: SFixed8 = SFixed8::constant(2i16); const TOP_COLLISION_LAST_FRAME: u8 = 0b1000_0000; const TOP_COLLISION_THIS_FRAME: u8 = 0b0100_0000; const BOTTOM_COLLISION_LAST_FRAME: u8 = 0b0010_0000; const BOTTOM_COLLISION_THIS_FRAME: u8 = 0b0001_0000; const LEFT_COLLISION_LAST_FRAME: u8 = 0b0000_1000; const LEFT_COLLISION_THIS_FRAME: u8 = 0b0000_0100; const RIGHT_COLLISION_LAST_FRAME: u8 = 0b0000_0010; const RIGHT_COLLISION_THIS_FRAME: u8 = 0b0000_0001; const LAST_FRAME_STATES: u8 = Player::TOP_COLLISION_LAST_FRAME | Player::BOTTOM_COLLISION_LAST_FRAME | Player::LEFT_COLLISION_LAST_FRAME | Player::RIGHT_COLLISION_LAST_FRAME; fn update(&mut self) { self.inputs.update(); match self.state { PlayerState::Standing => { self.current_velocity = VEC2D_ZERO; if self.inputs.is_pressed(Key::LEFT) != self.inputs.is_pressed(Key::RIGHT) { self.state = PlayerState::Walking; } }, PlayerState::Walking => { if self.inputs.is_pressed(Key::LEFT) == self.inputs.is_pressed(Key::RIGHT) { self.state = PlayerState::Standing;
ode3::WIDTH * (y as usize)) + (left as usize)) * 2usize); DMA3CNT_L.write(word_count); const CTRL: DmaControl = DmaControl::new() .with_dest_addr(DestAddrControl::Increment) .with_src_addr(SrcAddrControl::Fixed) .with_transfer_u32(false) .with_start_time(DmaStartTiming::Immediately) .with_enabled(true); DMA3CNT_H.write(CTRL); asm!( " nop nop ", options(nostack), ); } } } #[inline] fn spin_until_vblank() { while VCOUNT.read() < 160 {} } #[inline] fn spin_until_vdraw() { while VCOUNT.read() >= 160 {} }
self.current_velocity = VEC2D_ZERO; } else if self.inputs.is_pressed(Key::RIGHT) { if self.collision_state & Player::RIGHT_COLLISION_THIS_FRAME > 0 { self.current_velocity.x = SFixed8::ZERO; } else { self.current_velocity.x = Player::WALK_SPEED; } } else if self.inputs.is_pressed(Key::LEFT) { if self.collision_state & Player::LEFT_COLLISION_THIS_FRAME > 0 { self.current_velocity.x = SFixed8::ZERO; } else { self.current_velocity.x = -Player::WALK_SPEED; } } }, }; self.update_physics(); } fn update_physics(&mut self) { self.old_position = self.current_position; self.old_velocity = self.current_velocity; self.collision_state = (self.collision_state << 1) & Player::LAST_FRAME_STATES; self.current_position.saturating_add_signed_assign(self.current_velocity); self.collision_box.center = self.current_position.saturating_add_signed(self.box_offset); if self.collision_box.left() < LEFT_WALL_X { let new_collision_box_center_x = LEFT_WALL_X + self.collision_box.half_size.x; self.current_position.x = new_collision_box_center_x.saturating_add_signed(-self.box_offset.x); self.collision_box.center.x = new_collision_box_center_x; self.current_velocity.x = max(self.current_velocity.x, SFixed8::ZERO); self.collision_state |= Player::LEFT_COLLISION_THIS_FRAME; } else if self.collision_box.right() > RIGHT_WALL_X { let new_collision_box_center_x = RIGHT_WALL_X - self.collision_box.half_size.x; self.current_position.x = new_collision_box_center_x.saturating_add_signed(-self.box_offset.x); self.collision_box.center.x = new_collision_box_center_x; self.current_velocity.x = min(self.current_velocity.x, SFixed8::ZERO); self.collision_state |= Player::RIGHT_COLLISION_THIS_FRAME; } } #[inline] fn draw(&self) { let left: u16 = self.collision_box.left().into(); let right: u16 = self.collision_box.right().into(); let top: u16 = self.collision_box.top().into(); let bottom: u16 = self.collision_box.bottom().into(); fill_rect(left, right, top, bottom, Player::COLOR); let center_x: u16 = self.collision_box.center.x.into(); let center_y: u16 = self.collision_box.center.y.into(); mode3::bitmap_xy(center_x.into(), center_y.into()).write(Player::CENTER_COLOR); let player_x: u16 = self.current_position.x.into(); let player_y: u16 = self.current_position.y.into(); mode3::bitmap_xy(player_x.into(), player_y.into()).write(Player::ANCHOR_COLOR); } } const BACKGROUND_COLOR: Color = Color::from_rgb(15, 15, 15); const WALL_COLOR: Color = Color::from_rgb(0, 0, 0); const VEC2D_ZERO: Vec2D<SFixed8> = Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }; const LEFT_WALL_X: UFixed8 = UFixed8::constant(20u16); const RIGHT_WALL_X: UFixed8 = UFixed8::constant(219u16); const FLOOR_Y: u16 = 130u16; #[no_mangle] fn main() -> ! { const SETUP_DISPLAY: DisplayControl = DisplayControl::new().with_display_mode(3).with_display_bg2(true); DISPCNT.write(SETUP_DISPLAY); let mut player: Player = Player { old_position: Vec2D { x: UFixed8::from(100u16), y: FLOOR_Y.into() }, current_position: Vec2D { x: UFixed8::from(100u16), y: FLOOR_Y.into() }, old_velocity: Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }, current_velocity: Vec2D { x: SFixed8::ZERO, y: SFixed8::ZERO }, collision_box: BoundingBox { center: Vec2D { x: UFixed8::ZERO, y: UFixed8::ZERO }, half_size: Vec2D { x: 8u16.into(), y: 16u16.into() }, }, box_offset: Vec2D { x: 8i16.into(), y: (-16i16).into() }, inputs: KeyMonitor::new(), state: PlayerState::Standing, collision_state: 0, }; mode3::dma3_clear_to(WALL_COLOR); loop { spin_until_vdraw(); player.update(); spin_until_vblank(); fill_rect( u16::from(LEFT_WALL_X), u16::from(RIGHT_WALL_X), 0u16, FLOOR_Y, BACKGROUND_COLOR ); player.draw(); } } #[inline] fn fill_rect(left: u16, right: u16, top: u16, bottom: u16, color: Color) { let raw_color: u16 = color.0; let word_count: u16 = right - left + 1; for y in top..=bottom { unsafe { DMA3SAD.write(&raw_color as *const _ as usize); DMA3DAD.write(0x0600_0000usize + ((m
random
[ { "content": "#[inline]\n\nfn draw_icon(x: usize, y: usize, width: usize, icon: &[Color], enabled: bool) {\n\n for (idx, color) in icon.iter().enumerate() {\n\n let dx = idx % width;\n\n let dy = idx / width;\n\n let modified_color =\n\n if *color == U && !enabled {\n\n W\n\n } else {...
Rust
src/day21/mod.rs
maxdavidson/advent-of-code-2020
25838e6c15317d1cf909350b15d4244d51f7c99e
use std::collections::{hash_map::Entry, HashMap, HashSet}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: HashSet<&'a str>, } impl<'a> Food<'a> { fn parse(value: &'a str) -> Option<Self> { lazy_static! { static ref RECIPE_RE: Regex = Regex::new(r"^(?P<ingredients>.+) \(contains (?P<allergens>.+)\)$").unwrap(); } let caps = RECIPE_RE.captures(value)?; let ingredients = caps .name("ingredients") .unwrap() .as_str() .split(' ') .collect(); let allergens = caps .name("allergens") .unwrap() .as_str() .split(", ") .collect(); Some(Self { ingredients, allergens, }) } } fn find_dangerous_ingredients_helper<'a>( mut allergen_ingredients: Vec<(&'a str, HashSet<&'a str>)>, ) -> Option<impl Iterator<Item = &'a str>> { if allergen_ingredients .iter() .any(|(_, ingredients)| ingredients.is_empty()) { None } else if allergen_ingredients .iter() .all(|(_, ingredients)| ingredients.len() == 1) { allergen_ingredients.sort_unstable_by_key(|(allergen, _)| *allergen); Some( allergen_ingredients .into_iter() .flat_map(|(_, ingredient)| ingredient.into_iter()), ) } else { allergen_ingredients.sort_unstable_by_key(|(_, ingredients)| ingredients.len()); allergen_ingredients .iter() .find_map(|(allergen, ingredients)| { if ingredients.len() == 1 { None } else { ingredients.iter().find_map(|ingredient| { let mut next_allergen_ingredients = allergen_ingredients.clone(); for (other_allergen, ingredients) in next_allergen_ingredients.iter_mut() { if allergen != other_allergen { ingredients.remove(ingredient); } } find_dangerous_ingredients_helper(next_allergen_ingredients) }) } }); None } } fn find_dangerous_ingredients<'a, 'b: 'a>( foods: impl IntoIterator<Item = &'a Food<'b>>, ) -> Option<impl Iterator<Item = &'a str>> { let mut allergen_ingredients: HashMap<&str, HashSet<&str>> = HashMap::new(); for food in foods.into_iter() { for allergen in food.allergens.iter() { match allergen_ingredients.entry(allergen) { Entry::Vacant(entry) => { entry.insert(food.ingredients.clone()); } Entry::Occupied(mut entry) => { entry .get_mut() .retain(|ingredient| food.ingredients.contains(ingredient)); if entry.get().is_empty() { return None; } } } } } let mut allergen_ingredients: Vec<(&str, HashSet<&str>)> = allergen_ingredients.into_iter().collect(); let mut visited_allergens: HashSet<&str> = HashSet::new(); while let Some((allergen, ingredient)) = allergen_ingredients .iter() .find_map(|(allergen, ingredients)| { if !visited_allergens.contains(allergen) && ingredients.len() == 1 { Some((*allergen, ingredients.iter().copied().next()?)) } else { None } }) { visited_allergens.insert(allergen); for (other_allergen, ingredients) in allergen_ingredients.iter_mut() { if allergen != *other_allergen { ingredients.remove(ingredient); } } } find_dangerous_ingredients_helper(allergen_ingredients) } pub fn part1(input: &str) -> usize { let foods: Vec<Food> = input.lines().filter_map(Food::parse).collect(); let all_ingredients: HashSet<&str> = foods .iter() .flat_map(|food| food.ingredients.iter().copied()) .collect(); let allergen_ingredients: HashSet<&str> = find_dangerous_ingredients(&foods) .expect("No solution found!") .collect(); let safe_ingredients = all_ingredients .into_iter() .filter(|ingredient| !allergen_ingredients.contains(ingredient)); safe_ingredients .map(|ingredient| { foods .iter() .filter(|food| food.ingredients.contains(ingredient)) .count() }) .sum() } pub fn part2(input: &str) -> String { let foods: Vec<Food> = input.lines().filter_map(Food::parse).collect(); let allergen_ingredients = find_dangerous_ingredients(&foods).expect("No solution found!"); allergen_ingredients.collect::<Vec<_>>().join(",") } #[cfg(test)] mod tests { use super::*; static TEST_INPUT: &str = include_str!("test_input.txt"); static INPUT: &str = include_str!("input.txt"); #[test] fn part1_works() { assert_eq!(part1(TEST_INPUT), 5); assert_eq!(part1(INPUT), 2072); } #[test] fn part2_works() { assert_eq!(part2(TEST_INPUT), "mxmxvkd,sqjhc,fvjkl"); assert_eq!( part2(INPUT), "fdsfpg,jmvxx,lkv,cbzcgvc,kfgln,pqqks,pqrvc,lclnj" ); } }
use std::collections::{hash_map::Entry, HashMap, HashSet}; use lazy_static::lazy_static; use regex::Regex; #[derive(Debug)] struct Food<'a> { ingredients: HashSet<&'a str>, allergens: HashSet<&'a str>, } impl<'a> Food<'a> {
} fn find_dangerous_ingredients_helper<'a>( mut allergen_ingredients: Vec<(&'a str, HashSet<&'a str>)>, ) -> Option<impl Iterator<Item = &'a str>> { if allergen_ingredients .iter() .any(|(_, ingredients)| ingredients.is_empty()) { None } else if allergen_ingredients .iter() .all(|(_, ingredients)| ingredients.len() == 1) { allergen_ingredients.sort_unstable_by_key(|(allergen, _)| *allergen); Some( allergen_ingredients .into_iter() .flat_map(|(_, ingredient)| ingredient.into_iter()), ) } else { allergen_ingredients.sort_unstable_by_key(|(_, ingredients)| ingredients.len()); allergen_ingredients .iter() .find_map(|(allergen, ingredients)| { if ingredients.len() == 1 { None } else { ingredients.iter().find_map(|ingredient| { let mut next_allergen_ingredients = allergen_ingredients.clone(); for (other_allergen, ingredients) in next_allergen_ingredients.iter_mut() { if allergen != other_allergen { ingredients.remove(ingredient); } } find_dangerous_ingredients_helper(next_allergen_ingredients) }) } }); None } } fn find_dangerous_ingredients<'a, 'b: 'a>( foods: impl IntoIterator<Item = &'a Food<'b>>, ) -> Option<impl Iterator<Item = &'a str>> { let mut allergen_ingredients: HashMap<&str, HashSet<&str>> = HashMap::new(); for food in foods.into_iter() { for allergen in food.allergens.iter() { match allergen_ingredients.entry(allergen) { Entry::Vacant(entry) => { entry.insert(food.ingredients.clone()); } Entry::Occupied(mut entry) => { entry .get_mut() .retain(|ingredient| food.ingredients.contains(ingredient)); if entry.get().is_empty() { return None; } } } } } let mut allergen_ingredients: Vec<(&str, HashSet<&str>)> = allergen_ingredients.into_iter().collect(); let mut visited_allergens: HashSet<&str> = HashSet::new(); while let Some((allergen, ingredient)) = allergen_ingredients .iter() .find_map(|(allergen, ingredients)| { if !visited_allergens.contains(allergen) && ingredients.len() == 1 { Some((*allergen, ingredients.iter().copied().next()?)) } else { None } }) { visited_allergens.insert(allergen); for (other_allergen, ingredients) in allergen_ingredients.iter_mut() { if allergen != *other_allergen { ingredients.remove(ingredient); } } } find_dangerous_ingredients_helper(allergen_ingredients) } pub fn part1(input: &str) -> usize { let foods: Vec<Food> = input.lines().filter_map(Food::parse).collect(); let all_ingredients: HashSet<&str> = foods .iter() .flat_map(|food| food.ingredients.iter().copied()) .collect(); let allergen_ingredients: HashSet<&str> = find_dangerous_ingredients(&foods) .expect("No solution found!") .collect(); let safe_ingredients = all_ingredients .into_iter() .filter(|ingredient| !allergen_ingredients.contains(ingredient)); safe_ingredients .map(|ingredient| { foods .iter() .filter(|food| food.ingredients.contains(ingredient)) .count() }) .sum() } pub fn part2(input: &str) -> String { let foods: Vec<Food> = input.lines().filter_map(Food::parse).collect(); let allergen_ingredients = find_dangerous_ingredients(&foods).expect("No solution found!"); allergen_ingredients.collect::<Vec<_>>().join(",") } #[cfg(test)] mod tests { use super::*; static TEST_INPUT: &str = include_str!("test_input.txt"); static INPUT: &str = include_str!("input.txt"); #[test] fn part1_works() { assert_eq!(part1(TEST_INPUT), 5); assert_eq!(part1(INPUT), 2072); } #[test] fn part2_works() { assert_eq!(part2(TEST_INPUT), "mxmxvkd,sqjhc,fvjkl"); assert_eq!( part2(INPUT), "fdsfpg,jmvxx,lkv,cbzcgvc,kfgln,pqqks,pqrvc,lclnj" ); } }
fn parse(value: &'a str) -> Option<Self> { lazy_static! { static ref RECIPE_RE: Regex = Regex::new(r"^(?P<ingredients>.+) \(contains (?P<allergens>.+)\)$").unwrap(); } let caps = RECIPE_RE.captures(value)?; let ingredients = caps .name("ingredients") .unwrap() .as_str() .split(' ') .collect(); let allergens = caps .name("allergens") .unwrap() .as_str() .split(", ") .collect(); Some(Self { ingredients, allergens, }) }
function_block-full_function
[ { "content": "struct Data<'a>(pub HashMap<&'a str, HashMap<&'a str, usize>>);\n\n\n\nimpl<'a> Data<'a> {\n\n fn parse(input: &'a str) -> Self {\n\n lazy_static! {\n\n static ref RE_1: Regex = Regex::new(r\"^(?P<color>[a-z ]+) bags? contain\").unwrap();\n\n static ref RE_2: Regex ...
Rust
async-coap/src/option/iter.rs
Luro02/rust-async-coap
6a7b592a23de0c9d86ca399bf40ecfbf0bff6e62
use super::*; use std::convert::Into; #[derive(Debug, Clone)] pub struct OptionIterator<'a> { iter: core::slice::Iter<'a, u8>, last_option: OptionNumber, } impl<'a> Default for OptionIterator<'a> { fn default() -> Self { OptionIterator::new(&[]) } } impl<'a> OptionIterator<'a> { pub fn new(buffer: &'a [u8]) -> OptionIterator<'a> { OptionIterator { iter: buffer.iter(), last_option: Default::default(), } } pub fn as_slice(&self) -> &'a [u8] { self.iter.as_slice() } pub fn peek(&mut self) -> Option<Result<(OptionNumber, &'a [u8]), Error>> { decode_option(&mut self.iter.clone(), self.last_option).transpose() } pub fn peek_eq<T>(&mut self, key: OptionKey<T>, value: T) -> bool where T: Into<OptionValue<'a>>, { let mut temp_array = [0; 8]; match decode_option(&mut self.iter.clone(), self.last_option) { Ok(Some((number, iter_value))) => { number == key.0 && (match value.into() { OptionValue::Integer(x) => encode_u32(x, &mut temp_array), OptionValue::Bytes(x) => x, OptionValue::ETag(x) => { let temp_slice = &mut temp_array[0..x.len()]; temp_slice.copy_from_slice(x.as_bytes()); temp_slice } } == iter_value) } _ => false, } } } impl<'a> Iterator for OptionIterator<'a> { type Item = Result<(OptionNumber, &'a [u8]), Error>; fn next(&mut self) -> Option<Self::Item> { let ret = decode_option(&mut self.iter, self.last_option).transpose(); if let Some(Ok((key, _))) = ret { self.last_option = key; } ret } } impl AsRef<[u8]> for OptionIterator<'_> { fn as_ref(&self) -> &[u8] { self.as_slice() } } pub trait OptionIteratorExt<'a>: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> { fn find_next(&mut self, key: OptionNumber) -> Option<Result<(OptionNumber, &'a [u8]), Error>>; fn find_next_of<T>(&mut self, key: OptionKey<T>) -> Option<Result<T, Error>> where T: TryOptionValueFrom<'a> + Sized, { if let Some(result) = self.find_next(key.0) { match result { Ok((_, value)) => { if let Some(x) = T::try_option_value_from(value) { return Some(Ok(x)); } else { return Some(Err(Error::ParseFailure)); } } Err(e) => return Some(Err(e)), } } None } fn extract_uri(&self) -> Result<RelRefBuf, Error> where Self: Sized + Clone, { let mut copy = self.clone(); let mut buf = String::new(); while let Some(seg) = copy.find_next_of(option::URI_PATH).transpose()? { if !buf.is_empty() { buf.push('/'); } buf.extend(seg.escape_uri()); } let mut has_query = false; while let Some(item) = copy.find_next_of(option::URI_QUERY).transpose()? { if has_query { buf.push('&'); } else { buf.push('?'); has_query = true; } buf.extend(item.escape_uri().for_query()); } let mut ret = RelRefBuf::from_string(buf).expect("Constructed URI was malformed"); ret.disambiguate(); Ok(ret) } fn extract_location(&self) -> Result<RelRefBuf, Error> where Self: Sized + Clone, { let mut copy = self.clone(); let mut buf = String::new(); while let Some(seg) = copy.find_next_of(option::LOCATION_PATH).transpose()? { if !buf.is_empty() { buf.push('/'); } buf.extend(seg.escape_uri()); } let mut has_query = false; while let Some(item) = copy.find_next_of(option::LOCATION_QUERY).transpose()? { if has_query { buf.push('&'); } else { buf.push('?'); has_query = true; } buf.extend(item.escape_uri().for_query()); } Ok(RelRefBuf::from_string(buf).expect("Constructed URI was malformed")) } } impl<'a, I> OptionIteratorExt<'a> for I where I: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> + Sized + Clone, { fn find_next(&mut self, key: OptionNumber) -> Option<Result<(OptionNumber, &'a [u8]), Error>> { let next_value = loop { let mut iter = self.clone(); match iter.next()? { Err(x) => return Some(Err(x)), Ok((number, value)) => { if number == key { *self = iter; break (key, value); } if number < key.0 { *self = iter; continue; } } }; return None; }; Some(Ok(next_value)) } }
use super::*; use std::convert::Into; #[derive(Debug, Clone)] pub struct OptionIterator<'a> { iter: core::slice::Iter<'a, u8>, last_option: OptionNumber, } impl<'a> Default for OptionIterator<'a> { fn default() -> Self { OptionIterator::new(&[]) } } impl<'a> OptionIterator<'a> { pub fn new(buffer: &'a [u8]) -> OptionIterator<'a> { OptionIterator { iter: buffer.iter(), last_option: Default::default(), } } pub fn as_slice(&self) -> &'a [u8] { self.iter.as_slice() } pub fn peek(&mut self) -> Option<Result<(OptionNumber, &'a [u8]), Error>> { decode_option(&mut self.iter.clone(), self.last_option).transpose() } pub fn peek_eq<T>(&mut self, key: OptionKey<T>, value: T) -> bool where T: Into<OptionValue<'a>>, { let mut temp_array = [0; 8]; match decode_option(&mut self.iter.clone(), self.last_option) { Ok(Some((number, iter_value))) => { number == key.0 && (match value.into() { OptionValue::Integer(x) => encode_u32(x, &mut temp_array), OptionValue::Bytes(x) => x, OptionValue::ETag(x) => { let temp_slice = &mut temp_array[0..x.len()]; temp_slice.copy_from_slice(x.as_bytes()); temp_slice } } == iter_value) } _ => false, } } } impl<'a> Iterator for OptionIterator<'a> { type Item = Result<(OptionNumber, &'a [u8]), Error>; fn next(&mut self)
et { self.last_option = key; } ret } } impl AsRef<[u8]> for OptionIterator<'_> { fn as_ref(&self) -> &[u8] { self.as_slice() } } pub trait OptionIteratorExt<'a>: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> { fn find_next(&mut self, key: OptionNumber) -> Option<Result<(OptionNumber, &'a [u8]), Error>>; fn find_next_of<T>(&mut self, key: OptionKey<T>) -> Option<Result<T, Error>> where T: TryOptionValueFrom<'a> + Sized, { if let Some(result) = self.find_next(key.0) { match result { Ok((_, value)) => { if let Some(x) = T::try_option_value_from(value) { return Some(Ok(x)); } else { return Some(Err(Error::ParseFailure)); } } Err(e) => return Some(Err(e)), } } None } fn extract_uri(&self) -> Result<RelRefBuf, Error> where Self: Sized + Clone, { let mut copy = self.clone(); let mut buf = String::new(); while let Some(seg) = copy.find_next_of(option::URI_PATH).transpose()? { if !buf.is_empty() { buf.push('/'); } buf.extend(seg.escape_uri()); } let mut has_query = false; while let Some(item) = copy.find_next_of(option::URI_QUERY).transpose()? { if has_query { buf.push('&'); } else { buf.push('?'); has_query = true; } buf.extend(item.escape_uri().for_query()); } let mut ret = RelRefBuf::from_string(buf).expect("Constructed URI was malformed"); ret.disambiguate(); Ok(ret) } fn extract_location(&self) -> Result<RelRefBuf, Error> where Self: Sized + Clone, { let mut copy = self.clone(); let mut buf = String::new(); while let Some(seg) = copy.find_next_of(option::LOCATION_PATH).transpose()? { if !buf.is_empty() { buf.push('/'); } buf.extend(seg.escape_uri()); } let mut has_query = false; while let Some(item) = copy.find_next_of(option::LOCATION_QUERY).transpose()? { if has_query { buf.push('&'); } else { buf.push('?'); has_query = true; } buf.extend(item.escape_uri().for_query()); } Ok(RelRefBuf::from_string(buf).expect("Constructed URI was malformed")) } } impl<'a, I> OptionIteratorExt<'a> for I where I: Iterator<Item = Result<(OptionNumber, &'a [u8]), Error>> + Sized + Clone, { fn find_next(&mut self, key: OptionNumber) -> Option<Result<(OptionNumber, &'a [u8]), Error>> { let next_value = loop { let mut iter = self.clone(); match iter.next()? { Err(x) => return Some(Err(x)), Ok((number, value)) => { if number == key { *self = iter; break (key, value); } if number < key.0 { *self = iter; continue; } } }; return None; }; Some(Ok(next_value)) } }
-> Option<Self::Item> { let ret = decode_option(&mut self.iter, self.last_option).transpose(); if let Some(Ok((key, _))) = r
function_block-random_span
[ { "content": "/// Encodes an unsigned 32-bit number into the given buffer, returning\n\n/// the resized buffer. The returned buffer may be smaller than the\n\n/// `dst`, and may even be empty. The returned buffer is only as large\n\n/// as it needs to be to represent the given value.\n\npub fn encode_u32(value:...
Rust
examples/router_benchmark.rs
sers-dev/tyractorsaur
23679ee63296eaac1bc7cfaacdcd81f137950799
use std::process::exit; use std::thread::sleep; use std::time::{Duration, Instant}; use tyra::prelude::{Actor, ActorFactory, ActorMessage, ActorSystem, ActorContext, Handler, TyraConfig, ActorWrapper}; use tyra::router::{AddActorMessage, RoundRobinRouterFactory, RouterMessage}; struct MessageA {} impl ActorMessage for MessageA {} struct Finish {} impl ActorMessage for Finish {} struct Start {} impl ActorMessage for Start {} struct Benchmark { ctx: ActorContext<Self>, aggregator: ActorWrapper<Aggregator>, total_msgs: usize, name: String, count: usize, start: Instant, } struct BenchmarkFactory { total_msgs: usize, aggregator: ActorWrapper<Aggregator>, name: String, } impl ActorFactory<Benchmark> for BenchmarkFactory { fn new_actor(&self, context: ActorContext<Benchmark>) -> Benchmark { Benchmark::new(self.total_msgs, self.name.clone(), context, self.aggregator.clone()) } } impl Benchmark { pub fn new(total_msgs: usize, name: String, context: ActorContext<Self>, aggregator: ActorWrapper<Aggregator>) -> Self { Self { ctx: context, aggregator, total_msgs, name, count: 0, start: Instant::now(), } } } impl Actor for Benchmark { fn on_system_stop(&mut self) { self.ctx.actor_ref.stop(); } } impl Handler<MessageA> for Benchmark { fn handle(&mut self, _msg: MessageA, _context: &ActorContext<Self>) { if self.count == 0 { sleep(Duration::from_secs((3) as u64)); self.start = Instant::now(); } self.count += 1; if self.count % self.total_msgs == 0 { let duration = self.start.elapsed(); println!( "{} It took {:?} to process {} messages", self.name, duration, self.total_msgs ); } if self.count == self.total_msgs { self.aggregator.send(Finish {}); } } } struct Aggregator { ctx: ActorContext<Self>, total_actors: usize, name: String, actors_finished: usize, start: Instant, } struct AggregatorFactory { total_actors: usize, name: String, } impl Aggregator { pub fn new(total_actors: usize, name: String, context: ActorContext<Self>) -> Self { Self { ctx: context, total_actors, name, actors_finished: 0, start: Instant::now(), } } } impl Actor for Aggregator { fn on_system_stop(&mut self) { self.ctx.actor_ref.stop(); } } impl ActorFactory<Aggregator> for AggregatorFactory { fn new_actor(&self, context: ActorContext<Aggregator>) -> Aggregator { Aggregator::new(self.total_actors, self.name.clone(), context) } } impl Handler<Finish> for Aggregator { fn handle(&mut self, _msg: Finish, _context: &ActorContext<Self>) { self.actors_finished += 1; if self.actors_finished == self.total_actors { let duration = self.start.elapsed(); println!( "{} It took {:?} to finish {} actors", self.name, duration, self.total_actors ); self.ctx.system.stop(Duration::from_secs(60)); } } } impl Handler<Start> for Aggregator { fn handle(&mut self, _msg: Start, _context: &ActorContext<Self>) { sleep(Duration::from_secs((3) as u64)); self.start = Instant::now(); } } fn main() { let actor_config = TyraConfig::new().unwrap(); let actor_system = ActorSystem::new(actor_config); let message_count = 10000000; let actor_count = 7; let router_factory = RoundRobinRouterFactory::new(); let router = actor_system.builder().spawn("benchmark-router", router_factory).unwrap(); let aggregator = actor_system .builder() .spawn( "aggregator", AggregatorFactory { total_actors: actor_count, name: String::from("aggregator") }).unwrap(); for i in 0..actor_count { let actor = actor_system .builder() .spawn(format!("benchmark-single-actor-{}", i), BenchmarkFactory { name: String::from(format!("benchmark-{}", i)), total_msgs: (message_count.clone() / actor_count.clone()) as usize, aggregator: aggregator.clone(), }).unwrap(); router.send(AddActorMessage::new(actor)); } println!("Actors have been created"); let start = Instant::now(); aggregator.send(Start{}); for _i in 0..message_count { let msg = MessageA {}; router.send(RouterMessage::new(msg)); } let duration = start.elapsed(); println!("It took {:?} to send {} messages", duration, message_count); exit(actor_system.await_shutdown()); }
use std::process::exit; use std::thread::sleep; use std::time::{Duration, Instant}; use tyra::prelude::{Actor, ActorFactory, ActorMessage, ActorSystem, ActorContext, Handler, TyraConfig, ActorWrapper}; use tyra::router::{AddActorMessage, RoundRobinRouterFactory, RouterMessage}; struct MessageA {} impl ActorMessage for MessageA {} struct Finish {} impl ActorMessage for Finish {} struct Start {} impl ActorMessage for Start {} struct Benchmark { ctx: ActorContext<Self>, aggregator: ActorWrapper<Aggregator>, total_msgs: usize, name: String, count: usize, start: Instant, } struct BenchmarkFactory { total_msgs: usize, aggregator: ActorWrapper<Aggregator>, name: String, } impl ActorFactory<Benchmark> for BenchmarkFactory { fn new_actor(&self, context: ActorContext<Benchmark>) -> Benchmark { Benchmark::new(self.total_msgs, self.name.clone(), context, self.aggregator.clone()) } } impl Benchmark { pub fn new(total_msgs: usize, name: String, context: ActorContext<Self>, aggregator: ActorWrapper<Aggregator>) -> Self { Self { ctx: context, aggregator, total_msgs, name, count: 0, start: Instant::now(), } } } impl Actor for Benchmark { fn on_system_stop(&mut self) { self.ctx.actor_ref.stop(); } } impl Handler<MessageA> for Benchmark { fn handle(&mut self, _msg: MessageA, _context: &ActorContext<Self>) { if self.count == 0 { sleep(Duration::from_secs((3) as u64)); self.start = Instant::now(); } self.count += 1; if self.count % self.total_msgs == 0 { let duration = self.start.elapsed(); println!( "{} It took {:?} to process {} messages", self.name, duration, self.total_msgs ); } if self.count == self.total_msgs { self.aggregator.send(Finish {}); } } } struct Aggregator { ctx: ActorContext<Self>, total_actors: usize, name: String, actors_finished: usize, start: Instant, } struct AggregatorFactory { total_actors: usize, name: String, } impl Aggregator {
} impl Actor for Aggregator { fn on_system_stop(&mut self) { self.ctx.actor_ref.stop(); } } impl ActorFactory<Aggregator> for AggregatorFactory { fn new_actor(&self, context: ActorContext<Aggregator>) -> Aggregator { Aggregator::new(self.total_actors, self.name.clone(), context) } } impl Handler<Finish> for Aggregator { fn handle(&mut self, _msg: Finish, _context: &ActorContext<Self>) { self.actors_finished += 1; if self.actors_finished == self.total_actors { let duration = self.start.elapsed(); println!( "{} It took {:?} to finish {} actors", self.name, duration, self.total_actors ); self.ctx.system.stop(Duration::from_secs(60)); } } } impl Handler<Start> for Aggregator { fn handle(&mut self, _msg: Start, _context: &ActorContext<Self>) { sleep(Duration::from_secs((3) as u64)); self.start = Instant::now(); } } fn main() { let actor_config = TyraConfig::new().unwrap(); let actor_system = ActorSystem::new(actor_config); let message_count = 10000000; let actor_count = 7; let router_factory = RoundRobinRouterFactory::new(); let router = actor_system.builder().spawn("benchmark-router", router_factory).unwrap(); let aggregator = actor_system .builder() .spawn( "aggregator", AggregatorFactory { total_actors: actor_count, name: String::from("aggregator") }).unwrap(); for i in 0..actor_count { let actor = actor_system .builder() .spawn(format!("benchmark-single-actor-{}", i), BenchmarkFactory { name: String::from(format!("benchmark-{}", i)), total_msgs: (message_count.clone() / actor_count.clone()) as usize, aggregator: aggregator.clone(), }).unwrap(); router.send(AddActorMessage::new(actor)); } println!("Actors have been created"); let start = Instant::now(); aggregator.send(Start{}); for _i in 0..message_count { let msg = MessageA {}; router.send(RouterMessage::new(msg)); } let duration = start.elapsed(); println!("It took {:?} to send {} messages", duration, message_count); exit(actor_system.await_shutdown()); }
pub fn new(total_actors: usize, name: String, context: ActorContext<Self>) -> Self { Self { ctx: context, total_actors, name, actors_finished: 0, start: Instant::now(), } }
function_block-full_function
[ { "content": "struct MessageA {}\n\n\n\nimpl ActorMessage for MessageA {}\n\n\n", "file_path": "examples/benchmark.rs", "rank": 0, "score": 118826.0143007199 }, { "content": "struct MessageA {\n\n text: String,\n\n}\n\n\n", "file_path": "examples/actor.rs", "rank": 1, "score":...
Rust
solver/src/lib.rs
MattWhelan/words
ca0788715a3af47e4b09157b0f60aa36af513f6a
use std::collections::{HashMap, HashSet}; use strsim::hamming; use wordlib::{char_freq, freq_scored_guesses, Knowledge}; use crate::LetterOutcome::{ABSENT, HIT, MISS}; pub trait GuessStrategy { fn next_guess(&self, knowledge: &Knowledge) -> &str; } pub struct FreqStrategy<'a> { words: &'a [&'a str], } impl<'a> FreqStrategy<'a> { pub fn new(words: &'a [&'a str]) -> FreqStrategy<'a> { FreqStrategy { words, } } } impl<'a> GuessStrategy for FreqStrategy<'a> { fn next_guess(&self, knowledge: &Knowledge) -> &'a str { let candidates = knowledge.filter(&self.words); if candidates.len() < 100 { println!("Candidates ({}):", candidates.len()); for w in candidates.iter() { println!(" {}", w); } if candidates.len() < 3 { return &candidates[0]; } } else { println!("Candidates: {}", candidates.len()); } let freq = char_freq(&candidates); let mut coverage = HashSet::new(); coverage.extend(knowledge.get_covered()); let word_scores = freq_scored_guesses(self.words, &freq, &coverage); let top_score = word_scores[0].1; let mut guesses: Vec<&str> = word_scores .iter() .take_while(|(_, s)| *s == top_score) .map(|(w, _)| *w) .collect(); guesses.sort_by_cached_key(|w| { candidates .iter() .map(|c| hamming(w, c).unwrap()) .min() .unwrap() }); println!("Guesses:"); for guess in guesses.iter().take(5) { println!(" {}", guess); } guesses[0] } } pub fn valid_words(target_word_len: usize, all_words: &[String], disallowed: HashSet<String>) -> Vec<&str> { all_words .iter() .filter(|s| s.chars().all(|ch| ch.is_lowercase())) .filter(|s| s.len() == target_word_len) .filter(|s| !disallowed.contains(s.as_str())) .map(|s| s.as_str()) .collect() } pub struct EntropyStrategy<'a> { words: &'a [&'a str], } impl<'a> EntropyStrategy<'a> { pub fn new(words: &'a [&'a str]) -> EntropyStrategy<'a> { EntropyStrategy { words, } } fn entropy_of_guess(candidates: &[&str], w: &str) -> f32 { let num_candidates = candidates.len() as f32; let pattern_counts = candidates.iter() .map(|c| (LetterOutcome::pattern(w, c), 1i32)) .fold(HashMap::with_capacity(300), |mut acc, (p, c)| { *acc.entry(p).or_default() += c; acc }); let word_entropy = pattern_counts.values() .map(|c: &i32| { let p = *c as f32 / num_candidates; p * -p.log2() }) .sum::<f32>(); word_entropy } } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] enum LetterOutcome { HIT, MISS, ABSENT, } impl LetterOutcome { fn _each() -> [LetterOutcome; 3] { [HIT, MISS, ABSENT] } fn pattern(guess: &str, target: &str) -> Vec<LetterOutcome> { let mut ret: Vec<LetterOutcome> = Vec::with_capacity(guess.len()); ret.extend( guess.chars() .zip(target.chars()) .map(|(g, t)| { if g == t { HIT } else if target.chars().any(|ch| ch == g) { MISS } else { ABSENT } }) ); ret } } impl<'a> GuessStrategy for EntropyStrategy<'a> { fn next_guess(&self, knowledge: &Knowledge) -> &'a str { let candidates = knowledge.filter(&self.words); println!("Candidates: {}; H = {}", candidates.len(), (candidates.len() as f32).log2()); if candidates.len() < 3 { return &candidates[0]; } if candidates.len() == self.words.len() { let ret = "raise"; let word_entropy = Self::entropy_of_guess(&candidates, ret); println!("{}: โˆ†H = {}", ret, word_entropy); return "raise" } let (guess, entropy) = self.words.iter() .map(|w| { let word_entropy = Self::entropy_of_guess(&candidates, w); (w, word_entropy) }) .max_by(|(_, l), (_, r)| l.partial_cmp(r).unwrap()) .unwrap(); println!("{}: H = {}", guess, entropy); guess } } #[cfg(test)] mod test { use std::collections::HashSet; use wordlib::{Knowledge, words_from_file}; use crate::{EntropyStrategy, GuessStrategy, valid_words}; #[test] fn test() { let all_words: Vec<String> = words_from_file("/usr/share/dict/words").unwrap(); let target_words: Vec<&str> = valid_words(5, &all_words, HashSet::new()); let guesser = EntropyStrategy::new(&target_words); let knowledge = Knowledge::from_tries(".a.se", "aseup", &["raise", "croup"]); let guess = guesser.next_guess(&knowledge); assert_eq!("pause", guess); } }
use std::collections::{HashMap, HashSet}; use strsim::hamming; use wordlib::{char_freq, freq_scored_guesses, Knowledge}; use crate::LetterOutcome::{ABSENT, HIT, MISS}; pub trait GuessStrategy { fn next_guess(&self, knowledge: &Knowledge) -> &str; } pub struct FreqStrategy<'a> { words: &'a [&'a str], } impl<'a> FreqStrategy<'a> { pub fn new(words: &'a [&'a str]) -> FreqStrategy<'a> { FreqStrategy { words, } } } impl<'a> GuessStrategy for FreqStrategy<'a> { fn next_guess(&self, knowledge: &Knowledge) -> &'a str { let candidates = knowledge.filter(&self.words); if candidates.len() < 100 { println!("Candidates ({}):", candidates.len()); for w in candidates.iter() { println!(" {}", w); } if candidates.len() < 3 { return &candidates[0]; } } else { println!("Candidates: {}", candidates.len()); } let freq = char_freq(&candidates); let mut coverage = HashSet::new(); coverage.extend(knowledge.get_covered()); let word_scores = freq_scored_guesses(self.words, &freq, &coverage); let top_score = word_scores[0].1; let mut guesses: Vec<&str> = word_scores .iter() .take_while(|(_, s)| *s == top_score) .map(|(w, _)| *w) .collect(); guesses.sort_by_cached_key(|w| { candidates .iter() .map(|c| hamming(w, c).unwrap()) .m
return &candidates[0]; } if candidates.len() == self.words.len() { let ret = "raise"; let word_entropy = Self::entropy_of_guess(&candidates, ret); println!("{}: โˆ†H = {}", ret, word_entropy); return "raise" } let (guess, entropy) = self.words.iter() .map(|w| { let word_entropy = Self::entropy_of_guess(&candidates, w); (w, word_entropy) }) .max_by(|(_, l), (_, r)| l.partial_cmp(r).unwrap()) .unwrap(); println!("{}: H = {}", guess, entropy); guess } } #[cfg(test)] mod test { use std::collections::HashSet; use wordlib::{Knowledge, words_from_file}; use crate::{EntropyStrategy, GuessStrategy, valid_words}; #[test] fn test() { let all_words: Vec<String> = words_from_file("/usr/share/dict/words").unwrap(); let target_words: Vec<&str> = valid_words(5, &all_words, HashSet::new()); let guesser = EntropyStrategy::new(&target_words); let knowledge = Knowledge::from_tries(".a.se", "aseup", &["raise", "croup"]); let guess = guesser.next_guess(&knowledge); assert_eq!("pause", guess); } }
in() .unwrap() }); println!("Guesses:"); for guess in guesses.iter().take(5) { println!(" {}", guess); } guesses[0] } } pub fn valid_words(target_word_len: usize, all_words: &[String], disallowed: HashSet<String>) -> Vec<&str> { all_words .iter() .filter(|s| s.chars().all(|ch| ch.is_lowercase())) .filter(|s| s.len() == target_word_len) .filter(|s| !disallowed.contains(s.as_str())) .map(|s| s.as_str()) .collect() } pub struct EntropyStrategy<'a> { words: &'a [&'a str], } impl<'a> EntropyStrategy<'a> { pub fn new(words: &'a [&'a str]) -> EntropyStrategy<'a> { EntropyStrategy { words, } } fn entropy_of_guess(candidates: &[&str], w: &str) -> f32 { let num_candidates = candidates.len() as f32; let pattern_counts = candidates.iter() .map(|c| (LetterOutcome::pattern(w, c), 1i32)) .fold(HashMap::with_capacity(300), |mut acc, (p, c)| { *acc.entry(p).or_default() += c; acc }); let word_entropy = pattern_counts.values() .map(|c: &i32| { let p = *c as f32 / num_candidates; p * -p.log2() }) .sum::<f32>(); word_entropy } } #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] enum LetterOutcome { HIT, MISS, ABSENT, } impl LetterOutcome { fn _each() -> [LetterOutcome; 3] { [HIT, MISS, ABSENT] } fn pattern(guess: &str, target: &str) -> Vec<LetterOutcome> { let mut ret: Vec<LetterOutcome> = Vec::with_capacity(guess.len()); ret.extend( guess.chars() .zip(target.chars()) .map(|(g, t)| { if g == t { HIT } else if target.chars().any(|ch| ch == g) { MISS } else { ABSENT } }) ); ret } } impl<'a> GuessStrategy for EntropyStrategy<'a> { fn next_guess(&self, knowledge: &Knowledge) -> &'a str { let candidates = knowledge.filter(&self.words); println!("Candidates: {}; H = {}", candidates.len(), (candidates.len() as f32).log2()); if candidates.len() < 3 {
random
[ { "content": "pub fn char_freq(words: &[&str]) -> HashMap<char, usize> {\n\n words\n\n .iter()\n\n .flat_map(|w| w.chars())\n\n .fold(HashMap::new(), |mut acc, ch| {\n\n *acc.entry(ch).or_default() += 1;\n\n acc\n\n })\n\n}\n\n\n", "file_path": "wordlib/s...
Rust
bfffs/src/bin/bfffs.rs
fkorotkov/bfffs
e0f3fddae49a19bcbe5593058cd2ef54b2496572
use bfffs::common::{ database::TreeID, device_manager::DevManager, property::Property }; use clap::crate_version; use futures::future; use std::{ path::Path, process::exit, sync::Arc }; use tokio::{ executor::current_thread::TaskExecutor, runtime::current_thread::Runtime }; mod check { use super::*; pub fn main(args: &clap::ArgMatches) { let poolname = args.value_of("name").unwrap().to_owned(); let disks = args.values_of("disks").unwrap(); let dev_manager = DevManager::default(); for dev in disks.map(str::to_string) { dev_manager.taste(dev); } let mut rt = tokio_io_pool::Runtime::new(); let handle = rt.handle().clone(); let db = Arc::new(rt.block_on(future::lazy(move || { dev_manager.import_by_name(poolname, handle) .unwrap_or_else(|_e| { eprintln!("Error: pool not found"); exit(1); }) })).unwrap()); rt.block_on(future::lazy(move || { db.check() })).unwrap(); } } mod debug { use super::*; use tokio::runtime::current_thread::Runtime; fn dump_fsm<P: AsRef<Path>, S: AsRef<str>>(poolname: S, disks: &[P]) { let dev_manager = DevManager::default(); for disk in disks { dev_manager.taste(disk); } let uuid = dev_manager.importable_pools().iter() .filter(|(name, _uuid)| { *name == poolname.as_ref() }).nth(0).unwrap().1; let mut rt = Runtime::new().unwrap(); let clusters = rt.block_on(future::lazy(move || { dev_manager.import_clusters(uuid) })).unwrap(); for c in clusters { println!("{}", c.dump_fsm()); } } fn dump_tree<P: AsRef<Path>>(poolname: String, disks: &[P]) { let poolname2 = poolname.to_owned(); let dev_manager = DevManager::default(); for disk in disks { dev_manager.taste(disk); } let mut rt = tokio_io_pool::Runtime::new(); let handle = rt.handle().clone(); let db = Arc::new(rt.block_on(future::lazy(move || { dev_manager.import_by_name(poolname2, handle) .unwrap_or_else(|_e| { eprintln!("Error: pool not found"); exit(1); }) })).unwrap()); let tree_id = TreeID::Fs(0); db.dump(&mut std::io::stdout(), tree_id).unwrap() } pub fn main(args: &clap::ArgMatches) { match args.subcommand() { ("dump", Some(args)) => { let poolname = args.value_of("name").unwrap(); let disks = args.values_of("disks").unwrap().collect::<Vec<&str>>(); if args.is_present("fsm") { dump_fsm(&poolname, &disks[..]); } if args.is_present("tree") { dump_tree(poolname.to_string(), &disks[..]); } }, _ => { println!("Error: subcommand required\n{}", args.usage()); std::process::exit(2); }, } } } mod pool { use bfffs::common::BYTES_PER_LBA; use bfffs::common::cache::Cache; use bfffs::common::database::*; use bfffs::common::ddml::DDML; use bfffs::common::idml::IDML; use bfffs::common::pool::{ClusterProxy, Pool}; use futures::Future; use std::{ convert::TryFrom, num::NonZeroU64, str::FromStr, sync::Mutex }; use super::*; fn create(args: &clap::ArgMatches) { let rt = Runtime::new().unwrap(); let name = args.value_of("name").unwrap().to_owned(); let zone_size = args.value_of("zone_size") .map(|s| { let lbas = u64::from_str(s) .expect("zone_size must be a decimal integer") * 1024 * 1024 / (BYTES_PER_LBA as u64); NonZeroU64::new(lbas).expect("zone_size may not be zero") }); let propstrings = if let Some(it) = args.values_of("property") { it.collect::<Vec<_>>() } else { Vec::new() }; let mut builder = Builder::new(name, propstrings, zone_size, rt); let mut vdev_tokens = args.values_of("vdev").unwrap(); let mut cluster_type = None; let mut devs = vec![]; loop { let next = vdev_tokens.next(); match next { None => { if !devs.is_empty() { match cluster_type { Some("mirror") => builder.create_mirror(&devs[..]), Some("raid") => builder.create_raid(&devs[..]), None => assert!(devs.is_empty()), _ => unreachable!() } } break; }, Some("mirror") => { if !devs.is_empty() { builder.create_cluster(cluster_type.as_ref().unwrap(), &devs[..]); } devs.clear(); cluster_type = Some("mirror") }, Some("raid") => { if !devs.is_empty() { builder.create_cluster(cluster_type.as_ref().unwrap(), &devs[..]); } devs.clear(); cluster_type = Some("raid") }, Some(ref dev) => { if cluster_type == None { builder.create_single(dev); } else { devs.push(dev); } } } } builder.format() } struct Builder { clusters: Vec<ClusterProxy>, name: String, properties: Vec<Property>, rt: Runtime, zone_size: Option<NonZeroU64> } impl Builder { pub fn new(name: String, propstrings: Vec<&str>, zone_size: Option<NonZeroU64>, rt: Runtime) -> Self { let clusters = Vec::new(); let properties = propstrings.into_iter() .map(|ps| { Property::try_from(ps).unwrap_or_else(|_e| { eprintln!("Invalid property specification {}", ps); std::process::exit(2); }) }) .collect::<Vec<_>>(); Builder{clusters, name, properties, rt, zone_size} } pub fn create_cluster(&mut self, vtype: &str, devs: &[&str]) { match vtype { "mirror" => self.create_mirror(devs), "raid" => self.create_raid(devs), _ => panic!("Unsupported vdev type {}", vtype) } } pub fn create_mirror(&mut self, devs: &[&str]) { let k = devs.len() as i16; let f = devs.len() as i16 - 1; self.do_create_cluster(k, f, &devs[2..]) } pub fn create_raid(&mut self, devs: &[&str]) { let k = i16::from_str_radix(devs[0], 10) .expect("Disks per stripe must be an integer"); let f = i16::from_str_radix(devs[1], 10) .expect("Disks per stripe must be an integer"); self.do_create_cluster(k, f, &devs[2..]) } pub fn create_single(&mut self, dev: &str) { self.do_create_cluster(1, 0, &[&dev]) } fn do_create_cluster(&mut self, k: i16, f: i16, devs: &[&str]) { let zone_size = self.zone_size; let c = self.rt.block_on(future::lazy(move || { Pool::create_cluster(None, k, zone_size, f, devs) })).unwrap(); self.clusters.push(c); } pub fn format(&mut self) { let name = self.name.clone(); let clusters = self.clusters.drain(..).collect(); let db = self.rt.block_on(future::lazy(|| { Pool::create(name, clusters) .map(|pool| { let cache = Arc::new(Mutex::new(Cache::with_capacity(1000))); let ddml = Arc::new(DDML::new(pool, cache.clone())); let idml = Arc::new(IDML::create(ddml, cache)); let task_executor = TaskExecutor::current(); Database::create(idml, task_executor) }) })).unwrap(); let props = self.properties.clone(); self.rt.block_on(future::lazy(|| { db.new_fs(props) .and_then(|_tree_id| db.sync_transaction()) })).unwrap(); } } pub fn main(args: &clap::ArgMatches) { match args.subcommand() { ("create", Some(create_args)) => create(create_args), _ => { println!("Error: subcommand required\n{}", args.usage()); std::process::exit(2); }, } } } fn main() { let app = clap::App::new("bfffs") .version(crate_version!()) .subcommand(clap::SubCommand::with_name("check") .about("Consistency check") .arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("disks") .multiple(true) .required(true) ) ).subcommand(clap::SubCommand::with_name("debug") .about("Debugging tools") .subcommand(clap::SubCommand::with_name("dump") .about("Dump internal filesystem information") .arg(clap::Arg::with_name("fsm") .help("Dump the Free Space Map") .long("fsm") .short("f") ).arg(clap::Arg::with_name("tree") .help("Dump the file system tree") .long("tree") .short("t") ).arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("disks") .multiple(true) .required(true) ) ) ).subcommand(clap::SubCommand::with_name("pool") .about("create, destroy, and modify storage pools") .subcommand(clap::SubCommand::with_name("create") .about("create a new storage pool") .arg(clap::Arg::with_name("zone_size") .help("Simulated Zone size in MB") .long("zone_size") .takes_value(true) ).arg(clap::Arg::with_name("property") .help("Dataset properties, comma delimited") .short("o") .takes_value(true) .multiple(true) .require_delimiter(true) ).arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("vdev") .multiple(true) .required(true) ) ) ); let matches = app.get_matches(); match matches.subcommand() { ("check", Some(args)) => check::main(args), ("debug", Some(args)) => debug::main(args), ("pool", Some(args)) => pool::main(args), _ => { println!("Error: subcommand required\n{}", matches.usage()); std::process::exit(2); }, } }
use bfffs::common::{ database::TreeID, device_manager::DevManager, property::Property }; use clap::crate_version; use futures::future; use std::{ path::Path, process::exit, sync::Arc }; use tokio::{ executor::current_thread::TaskExecutor, runtime::current_thread::Runtime }; mod check { use super::*; pub fn main(args: &clap::ArgMatches) { let poolname = args.value_of("name").unwrap().to_owned(); let disks = args.values_of("disks").unwrap(); let dev_manager = DevManager::default(); for dev in disks.map(str::to_string) { dev_manager.taste(dev); } let mut rt = tokio_io_pool::Runtime::new(); let handle = rt.handle().clone(); let db = Arc::new(rt.block_on(future::lazy(move || { dev_manager.import_by_name(poolname, handle) .unwrap_or_else(|_e| { eprintln!("Error: pool not found"); exit(1); }) })).unwrap()); rt.block_on(future::lazy(move || { db.check() })).unwrap(); } } mod debug { use super::*; use tokio::runtime::current_thread::Runtime; fn dump_fsm<P: AsRef<Path>, S: AsRef<str>>(poolname: S, disks: &[P]) { let dev_manager = DevManager::default(); for disk in disks { dev_manager.taste(disk); } let uuid = dev_manager.importable_pools().iter() .filter(|(name, _uuid)| { *name == poolname.as_ref() }).nth(0).unwrap().1; let mut rt = Runtime::new().unwrap(); let clusters = rt.block_on(future::lazy(move || { dev_manager.import_clusters(uuid) })).unwrap(); for c in clusters { println!("{}", c.dump_fsm()); } } fn dump_tree<P: AsRef<Path>>(poolname: String, disks: &[P]) { let poolname2 = poolname.to_owned(); let dev_manager = DevManager::default(); for disk in disks { dev_manager.taste(disk); } let mut rt = tokio_io_pool::Runtime::new(); let handle = rt.handle().clone(); let db = Arc::new(rt.block_on(future::lazy(move || { dev_manager.import_by_name(poolname2, handle) .unwrap_or_else(|_e| { eprintln!("Error: pool not found"); exit(1); }) })).unwrap()); let tree_id = TreeID::Fs(0); db.dump(&mut std::io::stdout(), tree_id).unwrap() } pub fn main(args: &clap::ArgMatches) { match args.subcommand() { ("dump", Some(args)) => { let poolname = args.value_of("name").unwrap(); let disks = args.values_of("disks").unwrap().collect::<Vec<&str>>(); if args.is_present("fsm") { dump_fsm(&poolname, &disks[..]); } if args.is_present("tree") { dump_tree(poolname.to_string(), &disks[..]); } }, _ => { println!("Error: subcommand required\n{}", args.usage()); std::process::exit(2); }, } } } mod pool { use bfffs::common::BYTES_PER_LBA; use bfffs::common::cache::Cache; use bfffs::common::database::*; use bfffs::common::ddml::DDML; use bfffs::common::idml::IDML; use bfffs::common::pool::{ClusterProxy, Pool}; use futures::Future; use std::{ convert::TryFrom, num::NonZeroU64, str::FromStr, sync::Mutex }; use super::*; fn create(args: &clap::ArgMatches) { let rt = Runtime::new().unwrap(); let name = args.value_of("name").unwrap().to_owned(); let zone_size = args.value_of("zone_size") .map(|s| { let lbas = u64::from_str(s) .expect("zone_size must be a decimal integer") * 1024 * 1024 / (BYTES_PER_LBA as u64); NonZeroU64::new(lbas).expect("zone_size may not be zero") }); let propstrings = if let Some(it) = args.values_of("property") { it.collect::<Vec<_>>() } else { Vec::new() }; let mut builder = Builder::new(name, propstrings, zone_size, rt); let mut vdev_tokens = args.values_of("vdev").unwrap(); let mut cluster_type = None; let mut devs = vec![]; loop { let next = vdev_tokens.next(); match next { None => { if !devs.is_empty() { match cluster_type { Some("mirror") => builder.create_mirror(&devs[..]), Some("raid") => builder.create_raid(&devs[..]), None => assert!(devs.is_empty()), _ => unreachable!() } } break; }, Some("mirror") => { if !devs.is_empty() { builder.create_cluster(cluster_type.as_ref().unwrap(), &devs[..]); } devs.clear(); cluster_type = Some("mirror") }, Some("raid") => { if !devs.is_empty() { builder.create_cluster(cluster_type.as_ref().unwrap(), &devs[..]); } devs.clear(); cluster_type = Some("raid") }, Some(ref dev) => { if cluster_type == None { builder.create_single(dev); } else { devs.push(dev); } } } } builder.format() } struct Builder { clusters: Vec<ClusterProxy>, name: String, properties: Vec<Property>, rt: Runtime, zone_size: Option<NonZeroU64> } impl Builder { pub fn new(name: String, propstrings: Vec<&str>, zone_size: Option<NonZeroU64>, rt: Runtime) -> Self { let clusters = Vec::new(); let properties = propstrings.into_iter() .map(|ps| { Property::try_from(ps).unwrap_or_else(|_e| { eprintln!("Invalid property specification {}", ps); std::process::exit(2); }) }) .collect::<Vec<_>>(); Builder{clusters, name, properties, rt, zone_size} } pub fn create_cluster(&mut self, vtype: &str, devs: &[&str]) { match vtype { "mirror" => self.create_mirror(devs), "raid" => self.create_raid(devs), _ => panic!("Unsupported vdev type {}", vtype) } } pub fn create_mirror(&mut self, devs: &[&str]) { let k = devs.len() as i16; let f = devs.len() as i16 - 1; self.do_create_cluster(k, f, &devs[2..]) } pub fn create_raid(&mut self, devs: &[&str]) { let k = i16::from_str_radix(devs[0], 10) .expect("Disks per stripe must be an integer"); let f = i16::from_str_radix(devs[1], 10) .expect("Disks per stripe must be an integer"); self.do_create_cluster(k, f, &devs[2..]) } pub fn create_single(&mut self, dev: &str) { self.do_create_cluster(1, 0, &[&dev]) } fn do_create_cluster(&mut self, k: i16, f: i16, devs: &[&str]) { let zone_size = self.zone_size; let c = self.rt.block_on(future::lazy(move || { Pool::create_cluster(None, k, zone_size, f, devs) })).unwrap(); self.clusters.push(c); } pub fn format(&mut self) { let name = self.name.clone(); let clusters = self.clusters.drain(..).collect(); let db = self.rt.block_on(future::lazy(|| { Pool::create(name, clusters) .map(|pool| { let cache = Arc::new(Mutex::new(Cache::with_capacity(1000))); let ddml = Arc::new(DDML::new(pool, cache.clone())); let idml = Arc::new(IDML::create(ddml, cache)); let task_executor = TaskExecutor::current(); Database::create(idml, task_executor) }) })).unwrap(); let props = self.properties.clone(); self.rt.block_on(future::lazy(|| { db.new_fs(props) .and_then(|_tree_id| db.sync_transaction()) })).unwrap(); } } pub fn main(args: &clap::ArgMatches) { match args.subcommand() { ("create", Some(create_args)) => create(create_args), _ => { println!("Error: subcommand required\n{}", args.usage()); std::process::exit(2); }, } } } fn main() { let app = clap::App::new("bfffs") .version(crate_version!()) .subcommand(clap::SubCommand::with_name("check") .about("Consistency check") .arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("disks") .multiple(true) .required(true) ) ).subcommand(clap::SubCommand::with_name("debug") .about("Debugging tools") .subcommand(clap::SubCommand::with_name("dump") .about("Dump internal filesystem information") .arg(clap::Arg::with_name("fsm") .help("Dump the Free Space Map") .long("fsm") .short("f") ).arg(clap::Arg::with_name("tree") .help("Dump the file system tree") .long("tree") .short("t") ).arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("disks") .multiple(true) .required(true) ) ) ).subcommand(clap::SubCommand::with_name("pool") .about("create, destroy, and modify storage pools") .subcommand(clap::SubCommand::with_name("create") .about("create a new storage pool") .arg(clap::Arg::with_name("zone_size") .help("Simulated Zone size in MB") .long("zone_size") .takes_value(true) ).arg(clap::Arg::with_name("property") .help("Dataset properties, comma delimited") .short("o") .takes_value(true) .multiple(true) .require_delimiter(true) ).arg(clap::Arg::with_name("name") .help("Pool name") .required(true) ).arg(clap::Arg::with_name("vdev") .multiple(true) .required(true) ) ) ); let matches = app.get_matches();
}
match matches.subcommand() { ("check", Some(args)) => check::main(args), ("debug", Some(args)) => debug::main(args), ("pool", Some(args)) => pool::main(args), _ => { println!("Error: subcommand required\n{}", matches.usage()); std::process::exit(2); }, }
if_condition
[ { "content": "/// Create a raid-like `Vdev` from its components.\n\n///\n\n///\n\n/// * `chunksize`: RAID chunksize in LBAs, if specified. This is the\n\n/// largest amount of data that will be read/written to\n\n/// a single device before the `Locator` ...
Rust
src/lib.rs
aki-akaguma/cmp_polymorphism
67da07762a02dee2aac7d3033d2b312fb2a1fedc
pub mod enum_obj; pub mod trait_obj; pub fn do_trait_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Cat::new(count)); let b: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Dog::new(count, count + 1)); let c: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Duck::new(count, count + 1, count + 2)); let d: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Crow::new(count, count + 1, count + 2, count + 3)); let e: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Frog::new( count, count + 1, count + 2, count + 3, count + 4, )); Ok(( (a.talk(), a.sum()), (b.talk(), b.sum()), (c.talk(), c.sum()), (d.talk(), d.sum()), (e.talk(), e.sum()), )) } pub fn do_enum_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Cat(count)); let b: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Dog(count, count + 1)); let c: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Duck(count, count + 1, count + 2)); let d: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Crow( count, count + 1, count + 2, count + 3, )); let e: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Frog( count, count + 1, count + 2, count + 3, count + 4, )); Ok(( (a.talk(), a.sum()), (b.talk(), b.sum()), (c.talk(), c.sum()), (d.talk(), d.sum()), (e.talk(), e.sum()), )) } pub fn create_trait_objs(count: usize) -> Vec<Box<dyn trait_obj::Animal>> { let v: Vec<Box<dyn trait_obj::Animal>> = vec![ Box::new(trait_obj::Cat::new(1)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Dog::new(1, 2)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Duck::new(1, 2, 3)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Crow::new(1, 2, 3, 4)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Frog::new(1, 2, 3, 4, 5)) as Box<dyn trait_obj::Animal>, ] .into_iter() .cycle() .take(count) .collect(); v } pub fn sum_id_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.animal_id(); } acc } pub fn sum_sum_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.sum(); } acc } pub fn sum_rem_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.rem(); } acc } pub fn create_enum_objs(count: usize) -> Vec<Box<enum_obj::Animal>> { let v: Vec<Box<enum_obj::Animal>> = vec![ Box::new(enum_obj::Animal::Cat(1)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Dog(1, 2)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Duck(1, 2, 3)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Crow(1, 2, 3, 4)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Frog(1, 2, 3, 4, 5)) as Box<enum_obj::Animal>, ] .into_iter() .cycle() .take(count) .collect(); v } pub fn sum_id_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.animal_id(); } acc } pub fn sum_sum_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.sum(); } acc } pub fn sum_rem_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.rem(); } acc }
pub mod enum_obj; pub mod trait_obj; pub fn do_trait_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Cat::new(count)); let b: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Dog::new(count, count + 1)); let c: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Duck::new(count, count + 1, count + 2)); let d: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Crow::new(count, count + 1, count + 2, count + 3)); let e: Box<dyn trait_obj::Animal> = Box::new(trait_obj::Frog::new( count, count + 1, count + 2, count + 3, count + 4, )); Ok(( (a.talk(), a.sum()), (b.talk(), b.sum()), (c.talk(), c.sum()), (d.talk(), d.sum()), (e.talk(), e.sum()), )) } pub fn do_enum_obj( count: i32, ) -> anyhow::Result<( (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), (&'static str, i32), )> { let a: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Cat(count)); let b: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Dog(count, count + 1)); let c: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Duck(count, count + 1, count + 2)); let d: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Crow( count, count + 1, count + 2, count + 3, )); let e: Box<enum_obj::Animal> = Box::new(enum_obj::Animal::Frog( count, count + 1, count + 2, count + 3, count + 4, )); Ok(( (a.talk(), a.sum()), (b.talk(), b.sum()), (c.talk(), c.sum()), (d.talk(), d.sum()), (e.talk(), e.sum()), )) } pub fn create_trait_objs(count: usize) -> Vec<Box<dyn trait_obj::Animal>> { let v: Vec<Box<dyn trait_obj::Animal>> = vec![ Box::new(trait_obj::Cat::new(1)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Dog::new(1, 2)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Duck::new(1, 2, 3)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Crow::new(1, 2, 3, 4)) as Box<dyn trait_obj::Animal>, Box::new(trait_obj::Frog::new(1, 2, 3, 4, 5)) as Box<dyn trait_obj::Animal>, ] .into_iter() .cycle() .take(count) .collect(); v } pub fn sum_id_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.animal_id(); } acc } pub fn sum_sum_t
pub fn sum_rem_trait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.rem(); } acc } pub fn create_enum_objs(count: usize) -> Vec<Box<enum_obj::Animal>> { let v: Vec<Box<enum_obj::Animal>> = vec![ Box::new(enum_obj::Animal::Cat(1)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Dog(1, 2)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Duck(1, 2, 3)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Crow(1, 2, 3, 4)) as Box<enum_obj::Animal>, Box::new(enum_obj::Animal::Frog(1, 2, 3, 4, 5)) as Box<enum_obj::Animal>, ] .into_iter() .cycle() .take(count) .collect(); v } pub fn sum_id_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.animal_id(); } acc } pub fn sum_sum_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.sum(); } acc } pub fn sum_rem_enum_objs(vec: &Vec<Box<enum_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.rem(); } acc }
rait_objs(vec: &Vec<Box<dyn trait_obj::Animal>>) -> i32 { let mut acc = 0; for a in vec { acc += a.sum(); } acc }
function_block-function_prefixed
[ { "content": "fn set_size(bench_vec: &mut Vec<BenchStr>, in_file: &str) -> anyhow::Result<()> {\n\n let mut base_time = 0f64;\n\n let mut base_size = 0u64;\n\n let re_1 = regex::Regex::new(r\"^ *(\\d+)\\t.*\\t([^ ]+)$\").unwrap();\n\n let reader = std::io::BufReader::new(\n\n std::fs::File::o...
Rust
src/prefab.rs
FrancisMurillo/amethyst-tiled
fc5713a8a41a9c829fb624c8f782393fde07971c
use amethyst::assets::{Asset, AssetStorage, Handle, Loader, PrefabData, ProgressCounter, Source}; use amethyst::ecs::{Component, Entity, Read, ReadExpect, Write, WriteStorage}; use amethyst::renderer::{SpriteSheet, Texture}; use amethyst::Error; use tiled::{Map, Tileset}; use crate::strategy::{CompressedLoad, LoadStrategy, StrategyDesc}; use crate::{load_tileset_inner, Tilesets}; use std::sync::Arc; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; pub enum TileSetPrefab { Handle(Handle<SpriteSheet>), TileSet(Tileset, Arc<dyn Source>), } impl<'a> PrefabData<'a> for TileSetPrefab { type SystemData = ( Write<'a, Tilesets>, Read<'a, AssetStorage<Texture>>, Write<'a, AssetStorage<SpriteSheet>>, ReadExpect<'a, Loader>, ); type Result = Handle<SpriteSheet>; fn add_to_entity( &self, _entity: Entity, _system_data: &mut Self::SystemData, _entities: &[Entity], _children: &[Entity], ) -> Result<Self::Result, Error> { match self { Self::Handle(handle) => Ok(handle.clone()), _ => unreachable!("load_sub_assets should be called before add_to_entity"), } } fn load_sub_assets( &mut self, progress: &mut ProgressCounter, system_data: &mut Self::SystemData, ) -> Result<bool, Error> { let (tilesets, textures, sheets, loader) = system_data; if let Self::TileSet(set, source) = self { match tilesets.get(&set.name) { Some(handle) => *self = Self::Handle(handle), None => { let sheet = match load_tileset_inner(set, source.clone(), loader, progress, textures) { Ok(v) => v, Err(e) => return Err(Error::from_string(format!("{:}", e))), }; let handle = sheets.insert(sheet); tilesets.push(set.name.to_owned(), handle.clone()); *self = Self::Handle(handle); return Ok(true); } } } Ok(false) } } pub enum TileMapPrefab<S: StrategyDesc = CompressedLoad> { Result(S::Result), Map(Map, Arc<dyn Source>), } impl<'a, T: LoadStrategy<'a>> PrefabData<'a> for TileMapPrefab<T> where T::Result: Clone + Component + Asset, { type SystemData = (T::SystemData, WriteStorage<'a, <T as StrategyDesc>::Result>); type Result = (); fn add_to_entity( &self, entity: Entity, system_data: &mut Self::SystemData, _entities: &[Entity], _children: &[Entity], ) -> Result<(), Error> { #[cfg(feature = "profiler")] profile_scope!("add_tilemap_to_entity"); let (_, storage) = system_data; match self { TileMapPrefab::Result(v) => { storage.insert(entity, v.clone())?; Ok(()) } _ => unreachable!("load_sub_assets should be called before add_to_entity"), } } fn load_sub_assets( &mut self, progress: &mut ProgressCounter, system_data: &mut Self::SystemData, ) -> Result<bool, Error> { #[cfg(feature = "profiler")] profile_scope!("load_tilemap_assets"); match self { TileMapPrefab::Map(map, source) => { *self = Self::Result(T::load(map, source.clone(), progress, &mut system_data.0)?); Ok(true) } _ => Ok(false), } } }
use amethyst::assets::{Asset, AssetStorage, Handle, Loader, PrefabData, ProgressCounter, Source}; use amethyst::ecs::{Component, Entity, Read, ReadExpect, Write, WriteStorage}; use amethyst::renderer::{SpriteSheet, Texture}; use amethyst::Error; use tiled::{Map, Tileset}; use crate::strategy::{CompressedLoad, LoadStrategy, StrategyDesc}; use crate::{load_tileset_inner, Tilesets}; use std::sync::Arc; #[cfg(feature = "profiler")] use thread_profiler::profile_scope; pub enum TileSetPrefab { Handle(Handle<SpriteSheet>), TileSet(Tileset, Arc<dyn Source>), } impl<'a> PrefabData<'a> for TileSetPrefab { type SystemData = ( Write<'a, Tilesets>, Read<'a, AssetStorage<Texture>>, Write<'a, AssetStorage<SpriteSheet>>, ReadExpect<'a, Loader>, ); type Result = Handle<SpriteSheet>; fn add_to_entity( &self, _entity: Entity, _system_data: &mut Self::SystemData, _entities: &[Entity], _children: &[Entity], ) -> Result<Self::Result, Error> { match self { Self::Handle(handle) => Ok(handle.clone()), _ => unreachable!("load_sub_assets should be called before add_to_entity"), } } fn load_sub_assets( &mut self, progress: &mut ProgressCounter, system_data: &mut Self::SystemData, ) -> Result<bool, Error> { let (tilesets, textures, sheets, loader) = system_data; if let Self::TileSet(set, source) = self { match tilesets.get(&set.name) { Some(handle) => *self = Self::Handle(handle), None => { let sheet = match load_tileset_inner(set, source.clone(), loader, progress, textures) { Ok(v) => v, Err(e) => return Err(Error::from_string(format!("{:}", e))), }; let handle = sheets.insert(sheet); tilesets.push(set.name.to_owned(), handle.clone()); *self = Self::Handle(handle); return Ok(true); } } } Ok(false) } } pub enum TileMapPrefab<S: StrategyDesc = CompressedLoad> { Result(S::Result), Map(Map, Arc<dyn Source>), } impl<'a, T: LoadStrategy<'a>> PrefabData<'a> for TileMapPrefab<T> where T::Result: Clone + Component + Asset, { type SystemData = (T::SystemData, WriteStorage<'a, <T as StrategyDesc>::Result>); type Result = ();
fn load_sub_assets( &mut self, progress: &mut ProgressCounter, system_data: &mut Self::SystemData, ) -> Result<bool, Error> { #[cfg(feature = "profiler")] profile_scope!("load_tilemap_assets"); match self { TileMapPrefab::Map(map, source) => { *self = Self::Result(T::load(map, source.clone(), progress, &mut system_data.0)?); Ok(true) } _ => Ok(false), } } }
fn add_to_entity( &self, entity: Entity, system_data: &mut Self::SystemData, _entities: &[Entity], _children: &[Entity], ) -> Result<(), Error> { #[cfg(feature = "profiler")] profile_scope!("add_tilemap_to_entity"); let (_, storage) = system_data; match self { TileMapPrefab::Result(v) => { storage.insert(entity, v.clone())?; Ok(()) } _ => unreachable!("load_sub_assets should be called before add_to_entity"), } }
function_block-full_function
[ { "content": "pub fn pack_tileset(set: &Tileset, source: Arc<dyn Source>) -> Result<SpriteSheet, Error> {\n\n let mut sprites = Vec::new();\n\n\n\n for image in &set.images {\n\n sprites.extend(pack_image(\n\n image,\n\n source.clone(),\n\n TileSpec {\n\n ...
Rust
crates/github_scbot_database/src/models/auth/external_account/mod.rs
sharingcloud/github-scbot
953ba1ae7f3bb06c37084756458a1ddb53c8fa65
use github_scbot_crypto::JwtUtils; use github_scbot_utils::TimeUtils; use serde::{Deserialize, Serialize}; use crate::{schema::external_account, Result}; mod adapter; mod builder; pub use adapter::{ DummyExternalAccountDbAdapter, ExternalAccountDbAdapter, IExternalAccountDbAdapter, }; use builder::ExternalAccountModelBuilder; #[derive(Debug, Serialize, Deserialize)] pub struct ExternalJwtClaims { pub iat: u64, pub iss: String, } #[derive( Debug, Deserialize, Insertable, Identifiable, Serialize, Queryable, Clone, Default, AsChangeset, PartialEq, Eq, )] #[primary_key(username)] #[table_name = "external_account"] pub struct ExternalAccountModel { pub username: String, pub public_key: String, pub private_key: String, } impl ExternalAccountModel { pub fn builder(username: &str) -> ExternalAccountModelBuilder { ExternalAccountModelBuilder::default(username) } pub fn builder_from_model(model: &Self) -> ExternalAccountModelBuilder { ExternalAccountModelBuilder::from_model(model) } pub fn generate_access_token(&self) -> Result<String> { let now_ts = TimeUtils::now_timestamp(); let claims = ExternalJwtClaims { iat: now_ts, iss: self.username.clone(), }; JwtUtils::create_jwt(&self.private_key, &claims).map_err(Into::into) } } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use super::*; use crate::{tests::using_test_db, DatabaseError}; #[actix_rt::test] async fn create_and_update() -> Result<()> { using_test_db("test_db_external_account", |_config, pool| async move { let db_adapter = ExternalAccountDbAdapter::new(pool.clone()); let acc = ExternalAccountModel::builder("ext1") .create_or_update(&db_adapter) .await .unwrap(); assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), public_key: String::new(), private_key: String::new(), } ); let acc = ExternalAccountModel::builder("ext1") .private_key("pri") .public_key("pub") .create_or_update(&db_adapter) .await .unwrap(); assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), private_key: "pri".into(), public_key: "pub".into() } ); let acc = ExternalAccountModel::builder("ext1") .public_key("public") .create_or_update(&db_adapter) .await .unwrap(); assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), private_key: "pri".into(), public_key: "public".into() } ); assert_eq!(db_adapter.list().await.unwrap().len(), 1); Ok::<_, DatabaseError>(()) }) .await } }
use github_scbot_crypto::JwtUtils; use github_scbot_utils::TimeUtils; use serde::{Deserialize, Serialize}; use crate::{schema::external_account, Result}; mod adapter; mod builder; pub use adapter::{ DummyExternalAccountDbAdapter, ExternalAccountDbAdapter, IExternalAccountDbAdapter, }; use builder::ExternalAccountModelBuilder; #[derive(Debug, Serialize, Deserialize)] pub struct ExternalJwtClaims { pub iat: u64, pub iss: String, } #[derive( Debug, Deserialize, Insertable, Identifiable, Serialize, Queryable, Clone, Default, AsChangeset, PartialEq, Eq, )] #[primary_key(username)] #[table_name = "external_account"] pub struct ExternalAccountModel { pub username: String, pub public_key: String, pub private_key: String, } impl ExternalAccountModel { pub fn builder(username: &str) -> ExternalAccountModelBuilder { ExternalAccountModelBuilder::default(username) } pub fn builder_from_model(model: &Self) -> ExternalAccountModelBuilder { ExternalAccountModelBuilder::from_model(model) } pub fn generate_access_token(&self) -> Result<String> { let now_ts = TimeUtils::now_timestamp(); let claims = ExternalJwtClaims { iat: now_ts, iss: self.username.clone(), }; JwtUtils::create_jwt(&self.private_key, &claims).map_err(Into::into) } } #[cfg(test)] mod tests { use pretty_assertions::assert_eq; use super::*; use crate::{tests::using_test_db, DatabaseError}; #[actix_rt::test] async fn create_and_update() -> Result<()> { using_test_db("test_db_external_account", |_config, pool| async move { let db_adapter = ExternalAccountDbAdapter::new(pool.clone()); let acc = ExternalAccountModel::builder("ext1") .create_or_update(&db_adapter) .await .unwrap(); assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), public_key: String::new(), private_key: String::new(), } );
assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), private_key: "pri".into(), public_key: "pub".into() } ); let acc = ExternalAccountModel::builder("ext1") .public_key("public") .create_or_update(&db_adapter) .await .unwrap(); assert_eq!( acc, ExternalAccountModel { username: "ext1".into(), private_key: "pri".into(), public_key: "public".into() } ); assert_eq!(db_adapter.list().await.unwrap().len(), 1); Ok::<_, DatabaseError>(()) }) .await } }
let acc = ExternalAccountModel::builder("ext1") .private_key("pri") .public_key("pub") .create_or_update(&db_adapter) .await .unwrap();
assignment_statement
[ { "content": "fn env_to_u64(name: &str, default: u64) -> u64 {\n\n env::var(name)\n\n .map(|e| e.parse().unwrap_or(default))\n\n .unwrap_or(default)\n\n}\n\n\n", "file_path": "crates/github_scbot_conf/src/config.rs", "rank": 0, "score": 232379.7236178441 }, { "content": "fn ...
Rust
src/git_config/git_config_entry.rs
rashil2000/delta
55287a827e8f2527df938a1b85e23290f8692607
use std::result::Result; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use crate::errors::*; #[derive(Clone, Debug)] pub enum GitConfigEntry { Style(String), GitRemote(GitRemoteRepo), } #[derive(Clone, Debug, PartialEq)] pub enum GitRemoteRepo { GitHubRepo { repo_slug: String }, GitLabRepo { repo_slug: String }, } impl GitRemoteRepo { pub fn format_commit_url(&self, commit: &str) -> String { match self { Self::GitHubRepo { repo_slug } => { format!("https://github.com/{}/commit/{}", repo_slug, commit) } Self::GitLabRepo { repo_slug } => { format!("https://gitlab.com/{}/-/commit/{}", repo_slug, commit) } } } } lazy_static! { static ref GITHUB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ github\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); static ref GITLAB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ gitlab\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name (/.*)? # Capture group(s), if any / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); } impl FromStr for GitRemoteRepo { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { if let Some(caps) = GITHUB_REMOTE_URL.captures(s) { Ok(Self::GitHubRepo { repo_slug: format!( "{user}/{repo}", user = caps.get(1).unwrap().as_str(), repo = caps.get(2).unwrap().as_str() ), }) } else if let Some(caps) = GITLAB_REMOTE_URL.captures(s) { Ok(Self::GitLabRepo { repo_slug: format!( "{user}{groups}/{repo}", user = caps.get(1).unwrap().as_str(), groups = caps.get(2).map(|x| x.as_str()).unwrap_or_default(), repo = caps.get(3).unwrap().as_str() ), }) } else { Err("Not a GitHub or GitLab repo.".into()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_github_urls() { let urls = &[ "https://github.com/dandavison/delta.git", "https://github.com/dandavison/delta", "git@github.com:dandavison/delta.git", "git@github.com:dandavison/delta", "github.com:dandavison/delta.git", "github.com:dandavison/delta", ]; for url in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitHubRepo { repo_slug: "dandavison/delta".to_string() } ); } } #[test] fn test_format_github_commit_link() { let repo = GitRemoteRepo::GitHubRepo { repo_slug: "dandavison/delta".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://github.com/dandavison/delta/commit/{}", commit_hash) ) } #[test] fn test_parse_gitlab_urls() { let urls = &[ ( "https://gitlab.com/proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("https://gitlab.com/proj/grp/repo.git", "proj/grp/repo"), ("https://gitlab.com/proj/repo.git", "proj/repo"), ("https://gitlab.com/proj/repo", "proj/repo"), ( "git@gitlab.com:proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("git@gitlab.com:proj/repo.git", "proj/repo"), ("git@gitlab.com:proj/repo", "proj/repo"), ("gitlab.com:proj/grp/repo.git", "proj/grp/repo"), ("gitlab.com:proj/repo.git", "proj/repo"), ("gitlab.com:proj/repo", "proj/repo"), ]; for (url, expected) in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitLabRepo { repo_slug: expected.to_string() } ); } } #[test] fn test_format_gitlab_commit_link() { let repo = GitRemoteRepo::GitLabRepo { repo_slug: "proj/grp/repo".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://gitlab.com/proj/grp/repo/-/commit/{}", commit_hash) ) } }
use std::result::Result; use std::str::FromStr; use lazy_static::lazy_static; use regex::Regex; use crate::errors::*; #[derive(Clone, Debug)] pub enum GitConfigEntry { Style(String), GitRemote(GitRemoteRepo), } #[derive(Clone, Debug, PartialEq)] pub enum GitRemoteRepo { GitHubRepo { repo_slug: String }, GitLabRepo { repo_slug: String }, } impl GitRemoteRepo { pub fn format_commit_url(&self, commit: &str) -> String { match self { Self::GitHubRepo { repo_slug } => { format!("https://github.com/{}/commit/{}", repo_slug, commit) } Self::GitLabRepo { repo_slug } => { format!("https://gitlab.com/{}/-/commit/{}", repo_slug, commit) } } } } lazy_static! { static ref GITHUB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ github\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); static ref GITLAB_REMOTE_URL: Regex = Regex::new( r"(?x) ^ (?:https://|git@)? # Support both HTTPS and SSH URLs, SSH URLs optionally omitting the git@ gitlab\.com [:/] # This separator differs between SSH and HTTPS URLs ([^/]+) # Capture the user/org name (/.*)? # Capture group(s), if any / (.+?) # Capture the repo name (lazy to avoid consuming '.git' if present) (?:\.git)? # Non-capturing group to consume '.git' if present $ " ) .unwrap(); } impl FromStr for GitRemoteRepo { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { if let Some(caps) = GITHUB_REMOTE_URL.captures(s) { Ok(Self::GitHubRepo { repo_slug: format!( "{user}/{repo}", user = caps.get(1).unwrap().as_str(), repo = caps.get(2).unwrap().as_str() ), }) } else if let Some(caps) = GITLAB_REMOTE_URL.captures(s) { Ok(Self::GitLabRepo { repo_slug: format!( "{user}{groups}/{repo}", user = caps.get(1).unwrap().as_str(), groups = caps.get(2).map(|x| x.as_str()).unwrap_or_default(), repo = caps.get(3).unwrap().as_str() ), }) } else { Err("Not a GitHub or GitLab repo.".into()) } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_github_urls() { let urls = &[ "https://github.com/dandavison/delta.git", "https://github.com/dandavison/delta", "git@github.com:dandavison/delta.git", "git@github.com:dandavison/delta", "github.com:dandavison/delta.git", "github.com:dandavison/delta", ]; for url in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitHubRepo { repo_slug: "dandavison/delta".to_string() } ); } } #[test] fn test_format_github_commit_lin
#[test] fn test_parse_gitlab_urls() { let urls = &[ ( "https://gitlab.com/proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("https://gitlab.com/proj/grp/repo.git", "proj/grp/repo"), ("https://gitlab.com/proj/repo.git", "proj/repo"), ("https://gitlab.com/proj/repo", "proj/repo"), ( "git@gitlab.com:proj/grp/subgrp/repo.git", "proj/grp/subgrp/repo", ), ("git@gitlab.com:proj/repo.git", "proj/repo"), ("git@gitlab.com:proj/repo", "proj/repo"), ("gitlab.com:proj/grp/repo.git", "proj/grp/repo"), ("gitlab.com:proj/repo.git", "proj/repo"), ("gitlab.com:proj/repo", "proj/repo"), ]; for (url, expected) in urls { let parsed = GitRemoteRepo::from_str(url); assert!(parsed.is_ok()); assert_eq!( parsed.unwrap(), GitRemoteRepo::GitLabRepo { repo_slug: expected.to_string() } ); } } #[test] fn test_format_gitlab_commit_link() { let repo = GitRemoteRepo::GitLabRepo { repo_slug: "proj/grp/repo".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://gitlab.com/proj/grp/repo/-/commit/{}", commit_hash) ) } }
k() { let repo = GitRemoteRepo::GitHubRepo { repo_slug: "dandavison/delta".to_string(), }; let commit_hash = "d3b07384d113edec49eaa6238ad5ff00"; assert_eq!( repo.format_commit_url(commit_hash), format!("https://github.com/dandavison/delta/commit/{}", commit_hash) ) }
function_block-function_prefixed
[ { "content": "/// If `name` is set and, after trimming whitespace, is not empty string, then return that trimmed\n\n/// string. Else None.\n\npub fn get_env_var(_name: &str) -> Option<String> {\n\n #[cfg(not(test))]\n\n match env::var(_name).unwrap_or_else(|_| \"\".to_string()).trim() {\n\n \"\" =>...
Rust
src/frame.rs
Inner-Heaven/libwhisper-rs
26e7331fd5b4ab2c1410ab46f738208b48a6aa7b
use bytes::{BufMut, Bytes, BytesMut}; use errors::{WhisperError, WhisperResult}; use nom::{IResult, rest}; use sodiumoxide::crypto::box_::{Nonce, PublicKey}; pub static HEADER_SIZE: usize = 57; #[derive(Debug, Clone, PartialEq, Copy, Eq, Hash)] pub enum FrameKind { Hello = 1, Welcome, Initiate, Ready, Request, Response, Notification, Termination, } impl FrameKind { pub fn from(kind: u8) -> Option<FrameKind> { match kind { 1 => Some(FrameKind::Hello), 2 => Some(FrameKind::Welcome), 3 => Some(FrameKind::Initiate), 4 => Some(FrameKind::Ready), 5 => Some(FrameKind::Request), 6 => Some(FrameKind::Response), 7 => Some(FrameKind::Notification), 255 => Some(FrameKind::Termination), _ => None, } } pub fn from_slice(kind: &[u8]) -> Option<FrameKind> { if kind.len() != 1 { return None; } FrameKind::from(kind[0]) } } #[derive(Debug, Clone, PartialEq, Hash, Eq)] pub struct Frame { pub id: PublicKey, pub nonce: Nonce, pub kind: FrameKind, pub payload: Bytes, } impl Frame { pub fn length(&self) -> usize { HEADER_SIZE + self.payload.len() } pub fn pack_to_buf(&self, buf: &mut BytesMut) { buf.reserve(self.length()); buf.extend_from_slice(&self.id.0); buf.extend_from_slice(&self.nonce.0); buf.put_u8(self.kind as u8); buf.extend_from_slice(&self.payload); } pub fn pack(&self) -> Bytes { let mut frame = BytesMut::with_capacity(self.length()); self.pack_to_buf(&mut frame); frame.freeze() } pub fn from_slice(i: &[u8]) -> WhisperResult<Frame> { match parse_frame(i) { IResult::Done(_, frame) => Ok(frame), IResult::Incomplete(_) => Err(WhisperError::IncompleteFrame), IResult::Error(_) => Err(WhisperError::BadFrame), } } } named!(parse_frame < &[u8], Frame >, do_parse!( pk: map_opt!(take!(32), PublicKey::from_slice) >> nonce: map_opt!(take!(24), Nonce::from_slice) >> kind: map_opt!(take!(1), FrameKind::from_slice) >> payload: rest >> ({ let mut vec = Vec::with_capacity(payload.len()); vec.extend(payload.iter().cloned()); Frame { id: pk, nonce: nonce, kind: kind, payload: vec.into() } }) ) ); #[cfg(test)] mod test { use super::*; use errors::WhisperError; use sodiumoxide::crypto::box_::{gen_keypair, gen_nonce}; #[test] fn pack_and_unpack() { let frame = make_frame(); let packed_frame = frame.pack(); assert_eq!(packed_frame.len(), 60); let parsed_frame = Frame::from_slice(&packed_frame); assert_eq!(frame, parsed_frame.unwrap()); } #[test] fn frame_kind_from_slice() { let hello = FrameKind::from_slice(&[1]).unwrap(); let welcome = FrameKind::from_slice(&[2]).unwrap(); let initiate = FrameKind::from_slice(&[3]).unwrap(); let ready = FrameKind::from_slice(&[4]).unwrap(); let request = FrameKind::from_slice(&[5]).unwrap(); let response = FrameKind::from_slice(&[6]).unwrap(); let notification = FrameKind::from_slice(&[7]).unwrap(); let termination = FrameKind::from_slice(&[255]).unwrap(); let bad = FrameKind::from_slice(&[100]); let none = FrameKind::from_slice(&[]); assert_eq!(hello, FrameKind::Hello); assert_eq!(welcome, FrameKind::Welcome); assert_eq!(initiate, FrameKind::Initiate); assert_eq!(ready, FrameKind::Ready); assert_eq!(request, FrameKind::Request); assert_eq!(response, FrameKind::Response); assert_eq!(notification, FrameKind::Notification); assert_eq!(termination, FrameKind::Termination); assert!(bad.is_none()); assert!(none.is_none()); } #[test] fn malformed_frame() { let packed_frame = vec![1 as u8, 2, 3]; let parsed_frame = Frame::from_slice(&packed_frame); assert_eq!(parsed_frame.is_err(), true); let err = parsed_frame.err().unwrap(); let mut is_incomplete = false; if let WhisperError::IncompleteFrame = err { is_incomplete = true; } assert!(is_incomplete); } #[test] fn bad_frame() { let bad_frame = b"\x85\x0f\xc2?\xce\x80f\x16\xec8\x04\xc7{5\x98\xa7u<\xa5y\xda\x12\xfe\xad\xdc^%[\x8ap\xfa7q.-)\xe4V\xec\x94\xb2\x7f\r\x9a\x91\xc7\xcd\x08\xa4\xee\xbfbpH\x07%\r\0\0\0"; let result = Frame::from_slice(&bad_frame[0..59]); assert!(result.is_err()); let err = result.err().unwrap(); let mut is_bad = false; if let WhisperError::BadFrame = err { is_bad = true; } assert!(is_bad); } fn make_frame() -> Frame { let (pk, _) = gen_keypair(); let payload = vec![0, 0, 0]; let nonce = gen_nonce(); Frame { id: pk, nonce: nonce, kind: FrameKind::Hello, payload: payload.into(), } } }
use bytes::{BufMut, Bytes, BytesMut}; use errors::{WhisperError, WhisperResult}; use nom::{IResult, rest}; use sodiumoxide::crypto::box_::{Nonce, PublicKey}; pub static HEADER_SIZE: usize = 57; #[derive(Debug, Clone, PartialEq, Copy, Eq, Hash)] pub enum FrameKind { Hello = 1, Welcome, Initiate, Ready, Request, Response, Notification, Termination, } impl FrameKind { pub fn from(kind: u8) -> Option<FrameKind> { match kind { 1 => Some(FrameKind::Hello), 2 => Some(FrameKind::Welcome), 3 => Some(FrameKind::Initiate), 4 => Some(FrameKind::Ready), 5 => Some(FrameKind::Request), 6 => Some(FrameKind::Response), 7 => Some(FrameKind::Notification), 255 => Some(FrameKind::Termination), _ => None, } } pub fn from_slice(kind: &[u8]) -> Option<FrameKind> { if kind.len() != 1 { return None; } FrameKind::from(kind[0]) } } #[derive(Debug, Clone, PartialEq, Hash, Eq)] pub struct Frame { pub id: PublicKey, pub nonce: Nonce, pub kind: FrameKind, pub payload: Bytes, } impl Frame { pub fn length(&self) -> usize { HEADER_SIZE + self.payload.len() } pub fn pack_to_buf(&self, buf: &mut BytesMut) { buf.reserve(self.length()); buf.extend_from_slice(&self.id.0); buf.extend_from_slice(&self.nonce.0); buf.put_u8(self.kind as u8); buf.extend_from_slice(&self.payload); } pub fn pack(&self) -> Bytes { let mut frame = BytesMut::with_capacity(self.length()); self.pack_to_buf(&mut frame); frame.freeze() } pub fn from_slice(i: &[u8]) -> WhisperResult<Frame> { match parse_frame(i) { IResult::Done(_, frame) => Ok(frame), IResult::Incomplete(_) => Err(WhisperError::IncompleteFrame), IResult::Error(_) => Err(WhisperError::BadFrame), } } } named!(parse_frame < &[u8], Frame >, do_parse!( pk: map_opt!(take!(32), PublicKey::from_slice) >> nonce: map_opt!(take!(24), Nonce::from_slice) >> kind: map_opt!(take!(1), FrameKind::from_slice) >> payload: rest >> ({ let mut vec = Vec::with_capacity(payload.len()); vec.extend(payload.iter().cloned()); Frame { id: pk, nonce: nonce, kind: kind, payload: vec.into() } }) ) ); #[cfg(test)] mod test { use super::*; use errors::WhisperError; use sodiumoxide::crypto::box_::{gen_keypair, gen_nonce}; #[test] fn pack_and_unpack() { let frame = make_frame(); let packed_frame = frame.pack(); assert_eq!(packed_frame.len(), 60); let parsed_frame = Frame::from_slice(&packed_frame); assert_eq!(frame, parsed_frame.unwrap()); } #[test] fn frame_kind_from_slice() { let hello = FrameKind::from_slice(&[1]).unwrap(); let welcome = FrameKind::from_slice(&[2]).unwrap(); let initiate = FrameKind::from_slice(&[3]).unwrap(); let ready = FrameKind::from_slice(&[4]).unwrap(); let request = FrameKind::from_slice(&[5]).unwrap(); let response = FrameKind::from_slice(&[6]).unwrap(); let notification = FrameKind::from_slice(&[7]).unwrap(); let termination = FrameKind::from_slice(&[255]).unwrap(); let bad = FrameKind::from_slice(&[100]); let none = FrameKind::from_slice(&[]); assert_eq!(hello, FrameKind::Hello); assert_eq!(welcome, FrameKind::Welcome); assert_eq!(initiate, FrameKind::Initiate); assert_eq!(ready, FrameKind::Ready); assert_eq!(request, FrameKind::Request); assert_eq!(response, FrameKind::Response); assert_eq!(notification, FrameKind::Notification); assert_eq!(termination, FrameKind::Termination); assert!(bad.is_none()); assert!(none.is_none()); } #[test] fn malformed_frame() { let packed_frame = vec![1 as u8, 2, 3]; let parsed_frame = Frame::from_slice(&packed_frame); assert_eq!(parsed_frame.is_err(), true); let err = parsed_frame.err().unwrap(); let mut is_incomplete = false; if let WhisperError::IncompleteFrame = err {
nonce: nonce, kind: FrameKind::Hello, payload: payload.into(), } } }
is_incomplete = true; } assert!(is_incomplete); } #[test] fn bad_frame() { let bad_frame = b"\x85\x0f\xc2?\xce\x80f\x16\xec8\x04\xc7{5\x98\xa7u<\xa5y\xda\x12\xfe\xad\xdc^%[\x8ap\xfa7q.-)\xe4V\xec\x94\xb2\x7f\r\x9a\x91\xc7\xcd\x08\xa4\xee\xbfbpH\x07%\r\0\0\0"; let result = Frame::from_slice(&bad_frame[0..59]); assert!(result.is_err()); let err = result.err().unwrap(); let mut is_bad = false; if let WhisperError::BadFrame = err { is_bad = true; } assert!(is_bad); } fn make_frame() -> Frame { let (pk, _) = gen_keypair(); let payload = vec![0, 0, 0]; let nonce = gen_nonce(); Frame { id: pk,
random
[ { "content": "/// In order to make libsodium threadsafe you must call this function before using any of it's andom number generation functions.\n\n/// It's safe to call this method more than once and from more than one thread.\n\npub fn init() -> WhisperResult<()> {\n\n if sodiumoxide::init() {\n\n Ok(())\n...
Rust
src/crypto/mac.rs
chmoder/iso8583_rs
d7e8e4256e4e6923bb1c451db38449645355e772
use crate::crypto::{tdes_encrypt_cbc, des_encrypt_cbc}; pub enum MacAlgo { CbcMac, RetailMac, } pub enum PaddingType { Type1, Type2, } pub struct MacError { pub msg: String } pub fn verify_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &[u8], key: &Vec<u8>, expected_mac: &Vec<u8>) -> Result<(), MacError> { let mac = generate_mac(algo, padding_type, &data.to_vec(), key)?; if mac.eq(expected_mac) { Ok(()) } else { Err(MacError { msg: format!("computed mac: {} doesn't match expected_mac: {}", hex::encode(mac), hex::encode(expected_mac)) }) } } pub fn generate_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &Vec<u8>, key: &Vec<u8>) -> Result<Vec<u8>, MacError> { let new_data = apply_padding(padding_type, data); let mut iv = Vec::<u8>::new(); iv.extend_from_slice(hex::decode("0000000000000000").unwrap().as_slice()); println!("generating mac on {}", hex::encode(data)); match algo { MacAlgo::CbcMac => { let res = tdes_encrypt_cbc(&new_data, key, &iv); Ok(res[res.len() - 8..].to_vec()) } MacAlgo::RetailMac => { let k = key.as_slice()[0..8].to_vec(); if data.len() == 8 { Ok(tdes_encrypt_cbc(&data, key, &iv)) } else { let d1 = &new_data[0..new_data.len() - 8].to_vec(); let d2 = &new_data[new_data.len() - 8..].to_vec(); let res1 = des_encrypt_cbc(&d1, &k, &iv); Ok(tdes_encrypt_cbc(&d2, key, &res1[(res1.len() - 8)..].to_vec())) } } } } fn apply_padding(padding_type: &PaddingType, data: &Vec<u8>) -> Vec<u8> { let mut new_data = data.clone(); match padding_type { PaddingType::Type1 => {} PaddingType::Type2 => { new_data.push(0x80); } }; while new_data.len() < 8 { new_data.push(0x00); } while new_data.len() % 8 != 0 { new_data.push(0x00); } new_data } #[cfg(test)] mod tests { use crate::crypto::mac::{apply_padding, PaddingType, generate_mac, MacAlgo}; use hex_literal::hex; #[test] fn test_padding1_shortof8() { let data = hex::decode("0102030405").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405000000"); } #[test] fn test_padding1_exact() { let data = hex::decode("0102030405060708").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405060708"); } #[test] fn test_padding1_typical_short() { let data = hex::decode("0102030405060708090a").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405060708090a000000000000"); } #[test] fn test_padding2_shortof8() { let data = hex::decode("0102030405").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "0102030405800000"); } #[test] fn test_padding2_exact() { let data = hex::decode("0102030405060708").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "01020304050607088000000000000000"); } #[test] fn test_padding2_typical_short() { let data = hex::decode("0102030405060708090a").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "0102030405060708090a800000000000"); } #[test] fn test_gen_mac_cbc_nopads() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("7d34c3071da931b9", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_cbc_2() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("01020304050607080102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("0fe28f4b5537ee79", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_cbc_3() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("01020304050607080102030405")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("8fb12963d5661a22", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_cbc_2_paddingtype2() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type2, &Vec::from(hex!("01020304050607080102030405")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("8568cd2b7698605f", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail1_nopads() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("7d34c3071da931b9", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail2_padtype1() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708010203040506070801020304050607080000")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!(hex::encode(m), "149f99288681d292"); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail_padtype2() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type2, &Vec::from(hex!("0102030405060708010203040506070801020304050607080000")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!(hex::encode(m), "4689dd5a87015394"); } Err(e) => { assert!(false, e.msg) } } } }
use crate::crypto::{tdes_encrypt_cbc, des_encrypt_cbc}; pub enum MacAlgo { CbcMac, RetailMac, } pub enum PaddingType { Type1, Type2, } pub struct MacError { pub msg: String } pub fn verify_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &[u8], key: &Vec<u8>, expected_mac: &Vec<u8>) -> Result<(), MacError> { let mac = generate_mac(algo, padding_type, &data.to_vec(), key)?; if mac.eq(expected_mac) { Ok(()) } else { Err(MacError { msg: format!("computed mac: {} doesn't match expected_mac: {}", hex::encode(mac), hex::encode(expected_mac)) }) } } pub fn generate_mac(algo: &MacAlgo, padding_type: &PaddingType, data: &Vec<u8>, key: &Vec<u8>) -> Result<Vec<u8>, MacError> { let new_data = apply_padding(padding_type, data); let mut iv = Vec::<u8>::new(); iv.extend_from_slice(hex::decode("0000000000000000").unwrap().as_slice()); println!("generating mac on {}", hex::encode(data)); match algo { MacAlgo::CbcMac => { let res = tdes_encrypt_cbc(&new_data, key, &iv); Ok(res[res.len() - 8..].to_vec()) } MacAlgo::RetailMac => { let k = key.as_slice()[0..8].to_vec(); if data.len() == 8 { Ok(tdes_encrypt_cbc(&data, key, &iv)) } else { let d1 = &new_data[0..new_data.len() - 8].to_vec(); let d2 = &new_data[new_data.len() - 8..].to_vec(); let res1 = des_encrypt_cbc(&d1, &k, &iv); Ok(tdes_encrypt_cbc(&d2, key, &res1[(res1.len() - 8)..].to_vec())) } } } } fn apply_padding(padding_type: &PaddingType, data: &Vec<u8>) -> Vec<u8> { let mut new_data = data.clone(); match padding_type { PaddingType::Type1 => {} PaddingType::Type2 => { new_data.push(0x80); } }; while new_data.len() < 8 { new_data.push(0x00); } while new_data.len() % 8 != 0 { new_data.push(0x00); } new_data } #[cfg(test)] mod tests { use crate::crypto::mac::{apply_padding, PaddingType, generate_mac, MacAlgo}; use hex_literal::hex; #[test] fn test_padding1_shortof8() { let data = hex::decode("0102030405").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405000000"); } #[test] fn test_padding1_exact() { let data = hex::decode("0102030405060708").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405060708"); } #[test] fn test_padding1_typical_short() { let data = hex::decode("0102030405060708090a").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type1, &data)), "0102030405060708090a000000000000"); } #[test] fn test_padding2_shortof8() { let data = hex::decode("0102030405").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "0102030405800000"); } #[test] fn test_padding2_exact() { let data = hex::decode("0102030405060708").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "01020304050607088000000000000000"); } #[test] fn test_padding2_typical_short() { let data = hex::decode("0102030405060708090a").unwrap(); assert_eq!(hex::encode(apply_padding(&PaddingType::Type2, &data)), "0102030405060708090a800000000000"); } #[test] fn test_gen_mac_cbc_nopads() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("7d34c3071da931b9", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_cbc_2() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("01020304050607080102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("0fe28f4b5537ee79", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_cbc_3() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type1, &Vec::from(hex!("01020304050607080102030405")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d")));
} #[test] fn test_gen_mac_cbc_2_paddingtype2() { let res = generate_mac(&MacAlgo::CbcMac, &PaddingType::Type2, &Vec::from(hex!("01020304050607080102030405")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("8568cd2b7698605f", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail1_nopads() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("7d34c3071da931b9", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail2_padtype1() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type1, &Vec::from(hex!("0102030405060708010203040506070801020304050607080000")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!(hex::encode(m), "149f99288681d292"); } Err(e) => { assert!(false, e.msg) } } } #[test] fn test_gen_mac_retail_padtype2() { let res = generate_mac(&MacAlgo::RetailMac, &PaddingType::Type2, &Vec::from(hex!("0102030405060708010203040506070801020304050607080000")), &Vec::from(hex!("e0f4543f3e2a2c5ffc7e5e5a222e3e4d"))); match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!(hex::encode(m), "4689dd5a87015394"); } Err(e) => { assert!(false, e.msg) } } } }
match res { Ok(m) => { println!("mac = {}", hex::encode(m.as_slice())); assert_eq!("8fb12963d5661a22", hex::encode(m)); } Err(e) => { assert!(false, e.msg) } }
if_condition
[ { "content": "/// Pad a random hex string to'data' to make it 8 bytes\n\nfn pad_8(data: &mut String) {\n\n let padding: [u8; 8] = rand::thread_rng().gen();\n\n data.push_str(hex::encode(padding).as_str());\n\n data.truncate(16);\n\n}\n\n\n", "file_path": "src/crypto/pin.rs", "rank": 2, "sco...
Rust
src/client.rs
line/centraldogma-rs
9c223222f430a985bd32332fba5de79994bc652e
use std::time::Duration; use reqwest::{header::HeaderValue, Body, Method, Request}; use thiserror::Error; use url::Url; use crate::model::Revision; const WATCH_BUFFER_TIMEOUT: Duration = Duration::from_secs(5); #[derive(Error, Debug)] pub enum Error { #[error("HTTP Client error")] HttpClient(#[from] reqwest::Error), #[allow(clippy::upper_case_acronyms)] #[error("Invalid URL")] InvalidURL(#[from] url::ParseError), #[error("Failed to parse json")] ParseError(#[from] serde_json::Error), #[error("Invalid params: {0}")] InvalidParams(&'static str), #[error("Error response: [{0}] {1}")] ErrorResponse(u16, String), } #[derive(Clone)] pub struct Client { base_url: Url, token: HeaderValue, http_client: reqwest::Client, } impl Client { pub async fn new(base_url: &str, token: Option<&str>) -> Result<Self, Error> { let url = url::Url::parse(base_url)?; let http_client = reqwest::Client::builder().user_agent("cd-rs").build()?; let mut header_value = HeaderValue::from_str(&format!( "Bearer {}", token.as_ref().unwrap_or(&"anonymous") )) .map_err(|_| Error::InvalidParams("Invalid token received"))?; header_value.set_sensitive(true); Ok(Client { base_url: url, token: header_value, http_client, }) } pub(crate) async fn request(&self, req: reqwest::Request) -> Result<reqwest::Response, Error> { Ok(self.http_client.execute(req).await?) } pub(crate) fn new_request<S: AsRef<str>>( &self, method: reqwest::Method, path: S, body: Option<Body>, ) -> Result<reqwest::Request, Error> { self.new_request_inner(method, path.as_ref(), body) } fn new_request_inner( &self, method: reqwest::Method, path: &str, body: Option<Body>, ) -> Result<reqwest::Request, Error> { let mut req = Request::new(method, self.base_url.join(path)?); req.headers_mut() .insert("Authorization", self.token.clone()); if let Method::PATCH = *req.method() { req.headers_mut().insert( "Content-Type", HeaderValue::from_static("application/json-patch+json"), ); } else { req.headers_mut() .insert("Content-Type", HeaderValue::from_static("application/json")); } *req.body_mut() = body; Ok(req) } pub(crate) fn new_watch_request<S: AsRef<str>>( &self, method: reqwest::Method, path: S, body: Option<Body>, last_known_revision: Option<Revision>, timeout: Duration, ) -> Result<reqwest::Request, Error> { let mut req = self.new_request(method, path, body)?; match last_known_revision { Some(rev) => { let val = HeaderValue::from_str(&rev.to_string()).unwrap(); req.headers_mut().insert("if-none-match", val); } None => { let val = HeaderValue::from_str(&Revision::HEAD.to_string()).unwrap(); req.headers_mut().insert("if-none-match", val); } } if timeout.as_secs() != 0 { let val = HeaderValue::from_str(&format!("wait={}", timeout.as_secs())).unwrap(); req.headers_mut().insert("prefer", val); } let req_timeout = timeout.checked_add(WATCH_BUFFER_TIMEOUT).unwrap(); req.timeout_mut().replace(req_timeout); Ok(req) } pub fn project<'a>(&'a self, project_name: &'a str) -> ProjectClient<'a> { ProjectClient { client: self, project: project_name, } } pub fn repo<'a>(&'a self, project_name: &'a str, repo_name: &'a str) -> RepoClient<'a> { RepoClient { client: self, project: project_name, repo: repo_name, } } } pub struct ProjectClient<'a> { pub(crate) client: &'a Client, pub(crate) project: &'a str, } pub struct RepoClient<'a> { pub(crate) client: &'a Client, pub(crate) project: &'a str, pub(crate) repo: &'a str, }
use std::time::Duration; use reqwest::{header::HeaderValue, Body, Method, Request}; use thiserror::Error; use url::Url; use crate::model::Revision; const WATCH_BUFFER_TIMEOUT: Duration = Duration::from_secs(5); #[derive(Error, Debug)] pub enum Error { #[error("HTTP Client error")] HttpClient(#[from] reqwest::Error), #[allow(clippy::upper_case_acronyms)] #[error("Invalid URL")] InvalidURL(#[from] url::ParseError), #[error("Failed to parse json")] ParseError(#[from] serde_json::Error), #[error("Invalid params: {0}")] InvalidParams(&'static str), #[error("Error response: [{0}] {1}")] ErrorResponse(u16, String), } #[derive(Clone)] pub struct Client { base_url: Url, token: HeaderValue, http_client: reqwest::Client, } impl Client { pub async fn new(base_url: &str, token: Option<&str>) -> Result<Self, Error> { let url = url::Url::parse(base_url)?; let http_client = reqwest::Client::builder().user_agent("cd-rs").build()?; let mut header_value = HeaderValue::from_str(&format!( "Bearer {}", token.as_ref().unwrap_or(&"anonymous") )) .map_err(|_| Error::InvalidParams("Invalid token received"))?; header_value.set_sensitive(true); Ok(Client { base_url: url, token: header_value, http_client, }) } pub(crate) async fn request(&self, req: reqwest::Request) -> Result<reqwest::Response, Error> { Ok(self.http_client.execute(req).await?) } pub(crate) fn new_request<S: AsRef<str>>( &self, method: reqwest::Method, path: S, body: Option<Body>, ) -> Result<reqwest::Request, Error> { self.new_request_inner(method, path.as_ref(), body) }
pub(crate) fn new_watch_request<S: AsRef<str>>( &self, method: reqwest::Method, path: S, body: Option<Body>, last_known_revision: Option<Revision>, timeout: Duration, ) -> Result<reqwest::Request, Error> { let mut req = self.new_request(method, path, body)?; match last_known_revision { Some(rev) => { let val = HeaderValue::from_str(&rev.to_string()).unwrap(); req.headers_mut().insert("if-none-match", val); } None => { let val = HeaderValue::from_str(&Revision::HEAD.to_string()).unwrap(); req.headers_mut().insert("if-none-match", val); } } if timeout.as_secs() != 0 { let val = HeaderValue::from_str(&format!("wait={}", timeout.as_secs())).unwrap(); req.headers_mut().insert("prefer", val); } let req_timeout = timeout.checked_add(WATCH_BUFFER_TIMEOUT).unwrap(); req.timeout_mut().replace(req_timeout); Ok(req) } pub fn project<'a>(&'a self, project_name: &'a str) -> ProjectClient<'a> { ProjectClient { client: self, project: project_name, } } pub fn repo<'a>(&'a self, project_name: &'a str, repo_name: &'a str) -> RepoClient<'a> { RepoClient { client: self, project: project_name, repo: repo_name, } } } pub struct ProjectClient<'a> { pub(crate) client: &'a Client, pub(crate) project: &'a str, } pub struct RepoClient<'a> { pub(crate) client: &'a Client, pub(crate) project: &'a str, pub(crate) repo: &'a str, }
fn new_request_inner( &self, method: reqwest::Method, path: &str, body: Option<Body>, ) -> Result<reqwest::Request, Error> { let mut req = Request::new(method, self.base_url.join(path)?); req.headers_mut() .insert("Authorization", self.token.clone()); if let Method::PATCH = *req.method() { req.headers_mut().insert( "Content-Type", HeaderValue::from_static("application/json-patch+json"), ); } else { req.headers_mut() .insert("Content-Type", HeaderValue::from_static("application/json")); } *req.body_mut() = body; Ok(req) }
function_block-full_function
[ { "content": "fn watch_stream<D: Watchable>(client: Client, path: String) -> impl Stream<Item = D> + Send {\n\n let init_state = WatchState {\n\n client,\n\n path,\n\n last_known_revision: None,\n\n failed_count: 0,\n\n success_delay: None,\n\n };\n\n futures::stream:...
Rust
src/combinators.rs
hashedone/toy-interpreter
7e04e06bd0fe9349d7515fe0731591eabc6b428b
use crate::{Operator, Result, Token}; #[derive(Debug, PartialEq)] pub struct ParseProgress<'a, T> { pub tail: &'a str, pub token: Option<T>, } pub type ParseResult<'a, T> = Result<ParseProgress<'a, T>>; impl<'a, T> ParseProgress<'a, T> { fn none(tail: &'a str) -> ParseResult<'a, T> { Ok(ParseProgress { tail, token: None }) } fn some(tail: &'a str, token: T) -> ParseResult<'a, T> { Ok(ParseProgress { tail, token: Some(token), }) } } macro_rules! assume { ($e:expr, $tail:expr) => {{ let e = $e?; if e.token.is_some() { (e.tail, e.token.unwrap()) } else { return ParseProgress::none($tail); } }}; } fn number(src: &str) -> ParseResult<f32> { let first_not = src .find(|c| !"0123456789.".contains(c)) .unwrap_or_else(|| src.len()); if first_not == 0 { return ParseProgress::none(src); } let literal = &src[..first_not]; let tail = &src[first_not..]; if literal.chars().filter(|&c| c == '.').count() > 1 { Err(format!( "Invalid number: {}, only one decimal point allowed", literal )) } else { let number = literal .parse() .map_err(|err| format!("Invalid numer: {}, {}", literal, err))?; ParseProgress::some(tail, number) } } fn identifier(src: &str) -> ParseResult<&str> { if src.is_empty() { ParseProgress::none(src) } else if src.chars().next().unwrap().is_ascii_alphabetic() || src.starts_with('_') { let first_not = src .find(|c: char| -> bool { !(c == '_' || c.is_ascii_alphanumeric()) }) .unwrap_or_else(|| src.len()); let literal = &src[..first_not]; let tail = &src[first_not..]; ParseProgress::some(tail, literal) } else { ParseProgress::none(src) } } fn assignment(src: &str) -> ParseResult<&str> { let (tail, ident) = assume!(identifier(src), src); let tail = tail.trim_start(); if tail.starts_with('=') && !tail.starts_with("=>") { ParseProgress::some(&tail[1..], ident) } else { ParseProgress::none(src) } } pub fn next_token(src: &str) -> ParseResult<Token> { if src.is_empty() { return ParseProgress::none(""); } let assign = assignment(src)?; if let Some(tok) = assign.token { return ParseProgress::some(assign.tail, Token::Assign(tok.to_owned())); } let id = identifier(src)?; if let Some(tok) = id.token { return ParseProgress::some(id.tail, Token::Id(tok.to_owned())); } let num = number(src)?; if let Some(tok) = num.token { return ParseProgress::some(num.tail, Token::Number(tok)); } if src.starts_with("=>") { return ParseProgress::some(&src[2..], Token::Func); } let tok = match src { _ if src.starts_with('+') => Token::Operator(Operator::Add), _ if src.starts_with('-') => Token::Operator(Operator::Sub), _ if src.starts_with('*') => Token::Operator(Operator::Mul), _ if src.starts_with('/') => Token::Operator(Operator::Div), _ if src.starts_with('%') => Token::Operator(Operator::Mod), _ if src.starts_with('(') => Token::LBracket, _ if src.starts_with(')') => Token::RBracket, _ => return Err(format!("Invalid token: {}", src)), }; ParseProgress::some(&src[1..], tok) } #[cfg(test)] mod test { use super::*; #[test] fn test_number() { assert_eq!(ParseProgress::none(""), number("")); assert_eq!(ParseProgress::none("tail"), number("tail")); assert_eq!(ParseProgress::some("", 10.0f32), number("10")); assert_eq!(ParseProgress::some("", 10.4f32), number("10.4")); assert_eq!(ParseProgress::some("tail", 10.4f32), number("10.4tail")); number("10.4.5").unwrap_err(); } #[test] fn test_identifier() { assert_eq!(ParseProgress::none(""), identifier("")); assert_eq!(ParseProgress::none("10"), identifier("10")); assert_eq!(ParseProgress::some("", "a"), identifier("a")); assert_eq!(ParseProgress::some("", "ab"), identifier("ab")); assert_eq!(ParseProgress::some("", "_ab"), identifier("_ab")); assert_eq!(ParseProgress::some(".", "_ab"), identifier("_ab.")); assert_eq!(ParseProgress::some("", "__"), identifier("__")); assert_eq!(ParseProgress::some("", "_1"), identifier("_1")); } #[test] fn test_assignment() { assert_eq!(ParseProgress::none(""), assignment("")); assert_eq!(ParseProgress::none("x"), assignment("x")); assert_eq!(ParseProgress::some("", "x"), assignment("x =")); assert_eq!(ParseProgress::none("x =>"), assignment("x =>")); } #[test] fn test_next_token() { assert_eq!(ParseProgress::none(""), next_token("")); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Add)), next_token("+") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Sub)), next_token("-") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Mul)), next_token("*") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Div)), next_token("/") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Mod)), next_token("%") ); assert_eq!(ParseProgress::some("", Token::LBracket), next_token("(")); assert_eq!(ParseProgress::some("", Token::RBracket), next_token(")")); assert_eq!( ParseProgress::some("", Token::Assign("x".to_owned())), next_token("x =") ); assert_eq!(ParseProgress::some("", Token::Func), next_token("=>")); assert_eq!( ParseProgress::some("x", Token::Operator(Operator::Mod)), next_token("%x") ); assert_eq!( ParseProgress::some(" =>", Token::Id("x".to_owned())), next_token("x =>") ); next_token("10.0.4").unwrap_err(); next_token("=").unwrap_err(); } }
use crate::{Operator, Result, Token}; #[derive(Debug, PartialEq)] pub struct ParseProgress<'a, T> { pub tail: &'a str, pub token: Option<T>, } pub type ParseResult<'a, T> = Result<ParseProgress<'a, T>>; impl<'a, T> ParseProgress<'a, T> { fn none(tail: &'a str) -> ParseResult<'a, T> { Ok(ParseProgress { tail, token: None }) } fn some(tail: &'a str, token: T) -> ParseResult<'a, T> { Ok(ParseProgress { tail, token: Some(token), }) } } macro_rules! assume { ($e:expr, $tail:expr) => {{ let e = $e?; if e.token.is_some() { (e.tail, e.token.unwrap()) } else { return ParseProgress::none($tail); } }}; } fn number(src: &str) -> ParseResult<f32> { let first_not = src .find(|c| !"0123456789.".contains(c)) .unwrap_or_else(|| src.len()); if first_not == 0 { return ParseProgress::none(src); } let literal = &src[..first_not]; let tail = &src[first_not..]; if literal.chars().filter(|&c| c == '.').count() > 1 { Err(format!( "Invalid number: {}, only one decimal point allowed", literal )) } else { let number = literal .parse() .map_err(|err| format!("Invalid numer: {}, {}", literal, err))?; ParseProgress::some(tail, number) } }
fn assignment(src: &str) -> ParseResult<&str> { let (tail, ident) = assume!(identifier(src), src); let tail = tail.trim_start(); if tail.starts_with('=') && !tail.starts_with("=>") { ParseProgress::some(&tail[1..], ident) } else { ParseProgress::none(src) } } pub fn next_token(src: &str) -> ParseResult<Token> { if src.is_empty() { return ParseProgress::none(""); } let assign = assignment(src)?; if let Some(tok) = assign.token { return ParseProgress::some(assign.tail, Token::Assign(tok.to_owned())); } let id = identifier(src)?; if let Some(tok) = id.token { return ParseProgress::some(id.tail, Token::Id(tok.to_owned())); } let num = number(src)?; if let Some(tok) = num.token { return ParseProgress::some(num.tail, Token::Number(tok)); } if src.starts_with("=>") { return ParseProgress::some(&src[2..], Token::Func); } let tok = match src { _ if src.starts_with('+') => Token::Operator(Operator::Add), _ if src.starts_with('-') => Token::Operator(Operator::Sub), _ if src.starts_with('*') => Token::Operator(Operator::Mul), _ if src.starts_with('/') => Token::Operator(Operator::Div), _ if src.starts_with('%') => Token::Operator(Operator::Mod), _ if src.starts_with('(') => Token::LBracket, _ if src.starts_with(')') => Token::RBracket, _ => return Err(format!("Invalid token: {}", src)), }; ParseProgress::some(&src[1..], tok) } #[cfg(test)] mod test { use super::*; #[test] fn test_number() { assert_eq!(ParseProgress::none(""), number("")); assert_eq!(ParseProgress::none("tail"), number("tail")); assert_eq!(ParseProgress::some("", 10.0f32), number("10")); assert_eq!(ParseProgress::some("", 10.4f32), number("10.4")); assert_eq!(ParseProgress::some("tail", 10.4f32), number("10.4tail")); number("10.4.5").unwrap_err(); } #[test] fn test_identifier() { assert_eq!(ParseProgress::none(""), identifier("")); assert_eq!(ParseProgress::none("10"), identifier("10")); assert_eq!(ParseProgress::some("", "a"), identifier("a")); assert_eq!(ParseProgress::some("", "ab"), identifier("ab")); assert_eq!(ParseProgress::some("", "_ab"), identifier("_ab")); assert_eq!(ParseProgress::some(".", "_ab"), identifier("_ab.")); assert_eq!(ParseProgress::some("", "__"), identifier("__")); assert_eq!(ParseProgress::some("", "_1"), identifier("_1")); } #[test] fn test_assignment() { assert_eq!(ParseProgress::none(""), assignment("")); assert_eq!(ParseProgress::none("x"), assignment("x")); assert_eq!(ParseProgress::some("", "x"), assignment("x =")); assert_eq!(ParseProgress::none("x =>"), assignment("x =>")); } #[test] fn test_next_token() { assert_eq!(ParseProgress::none(""), next_token("")); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Add)), next_token("+") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Sub)), next_token("-") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Mul)), next_token("*") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Div)), next_token("/") ); assert_eq!( ParseProgress::some("", Token::Operator(Operator::Mod)), next_token("%") ); assert_eq!(ParseProgress::some("", Token::LBracket), next_token("(")); assert_eq!(ParseProgress::some("", Token::RBracket), next_token(")")); assert_eq!( ParseProgress::some("", Token::Assign("x".to_owned())), next_token("x =") ); assert_eq!(ParseProgress::some("", Token::Func), next_token("=>")); assert_eq!( ParseProgress::some("x", Token::Operator(Operator::Mod)), next_token("%x") ); assert_eq!( ParseProgress::some(" =>", Token::Id("x".to_owned())), next_token("x =>") ); next_token("10.0.4").unwrap_err(); next_token("=").unwrap_err(); } }
fn identifier(src: &str) -> ParseResult<&str> { if src.is_empty() { ParseProgress::none(src) } else if src.chars().next().unwrap().is_ascii_alphabetic() || src.starts_with('_') { let first_not = src .find(|c: char| -> bool { !(c == '_' || c.is_ascii_alphanumeric()) }) .unwrap_or_else(|| src.len()); let literal = &src[..first_not]; let tail = &src[first_not..]; ParseProgress::some(tail, literal) } else { ParseProgress::none(src) } }
function_block-full_function
[ { "content": "pub fn tokenize<'a>(mut src: &'a str) -> impl Iterator<Item = Result<Token>> + 'a {\n\n iter::from_fn(move || match next_token(src) {\n\n Ok(progress) => {\n\n src = progress.tail.trim_start();\n\n progress.token.map(Ok)\n\n }\n\n Err(err) => {\n\n ...
Rust
kq/tests/accessor_multiple/mod.rs
jihchi/kq
58bb05a44e0ceca6b8237bda63c5403a74a80a0c
use assert_cmd::Command; use indoc::indoc; const INPUT: &str = include_str!("./website.kdl"); #[test] fn top_descendant_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}) .assert() .success() .stdout(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}); } #[test] fn top_child_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() > []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}) .assert() .success() .stdout(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}); } #[test] fn descendant_child() { Command::cargo_bin("kq") .unwrap() .arg("html > body section > h2") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" h2 "Design and Discussion" h2 "Design Principles" "#}); } #[test] fn general_sibling() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta ~ title") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" title "kdl - Kat's Document Language" "#}); } #[test] fn adjacent_sibling() { Command::cargo_bin("kq") .unwrap() .arg("html body h2 + ol") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" ol { li "Maintainability" li "Flexibility" li "Cognitive simplicity and Learnability" li "Ease of de\/serialization" li "Ease of implementation" } "#}); } #[test] fn general_adjacent_siblings() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta ~ title + link") .write_stdin(INPUT) .assert() .success() .stdout(predicates::str::starts_with("link")) .stdout(predicates::str::contains(r#"href="\/styles\/global.css""#)) .stdout(predicates::str::contains(r#"rel="stylesheet""#)); } #[test] fn adjacent_general_siblings() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta + meta ~ link") .write_stdin(INPUT) .assert() .success() .stdout(predicates::str::starts_with("link")) .stdout(predicates::str::contains(r#"href="\/styles\/global.css""#)) .stdout(predicates::str::contains(r#"rel="stylesheet""#)); } #[test] fn complex_single_level() { Command::cargo_bin("kq") .unwrap() .arg(r#"li[val() = "Flexibility"] + [val() = "Cognitive simplicity and Learnability"] ~ [val() = "Ease of implementation"]"#) .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" li "Ease of implementation" "#}); } #[test] fn complex_nested() { Command::cargo_bin("kq") .unwrap() .arg(r#"header + section[prop(id) = "description"] ~ section[class = "kdl-section"] ol > li"#) .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" li "Maintainability" li "Flexibility" li "Cognitive simplicity and Learnability" li "Ease of de\/serialization" li "Ease of implementation" "#}); }
use assert_cmd::Command; use indoc::indoc; const INPUT: &str = include_str!("./website.kdl"); #[test] fn top_descendant_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}) .assert() .success() .stdout(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}); } #[test] fn top_child_any_element() { Command::cargo_bin("kq") .unwrap() .arg("top() > []") .write_stdin(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}) .assert() .success() .stdout(indoc! {r#" name "CI" jobs { fmt_and_docs "Check fmt & build docs" build_and_test "Build & Test" { strategy { matrix { os "ubuntu-latest" "macOS-latest" "windows-latest" } } } } "#}); } #[test] fn descendant_child() { Command::cargo_bin("kq") .unwrap() .arg("html > body section > h2") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" h2 "Design and Discussion" h2 "Design Principles" "#}); } #[test] fn general_sibling() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta ~ title") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" title "kdl - Kat's Document Language" "#}); } #[test] fn adjacent_sibling() { Command::cargo_bin("kq") .unwrap() .arg("html body h2 + ol") .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" ol { li "Maintainability" li "Flexibility" li "Cognitive simplicity and Learnability" li "Ease of de\/serialization" li "Ease of implementation" } "#}); } #[test] fn general_adjacent_siblings() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta ~ title + link") .write_stdin(INPUT) .assert() .success() .stdout(predicates::str::starts_with("link")) .stdout(predicates::str::contains(r#"href="\/styles\/global.css""#)) .stdout(predicates::str::contains(r#"rel="stylesheet""#)); } #[test]
#[test] fn complex_single_level() { Command::cargo_bin("kq") .unwrap() .arg(r#"li[val() = "Flexibility"] + [val() = "Cognitive simplicity and Learnability"] ~ [val() = "Ease of implementation"]"#) .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" li "Ease of implementation" "#}); } #[test] fn complex_nested() { Command::cargo_bin("kq") .unwrap() .arg(r#"header + section[prop(id) = "description"] ~ section[class = "kdl-section"] ol > li"#) .write_stdin(INPUT) .assert() .success() .stdout(indoc! {r#" li "Maintainability" li "Flexibility" li "Cognitive simplicity and Learnability" li "Ease of de\/serialization" li "Ease of implementation" "#}); }
fn adjacent_general_siblings() { Command::cargo_bin("kq") .unwrap() .arg("html > head meta + meta ~ link") .write_stdin(INPUT) .assert() .success() .stdout(predicates::str::starts_with("link")) .stdout(predicates::str::contains(r#"href="\/styles\/global.css""#)) .stdout(predicates::str::contains(r#"rel="stylesheet""#)); }
function_block-full_function
[ { "content": "pub fn query_document(input: &str, document: Vec<KdlNode>) -> Result<Vec<KdlNode>, String> {\n\n let input = input.trim();\n\n if input.is_empty() {\n\n Ok(document)\n\n } else {\n\n all_consuming(parser::selector)(input)\n\n .finish()\n\n .map(|(_input...
Rust
src/texture/pixel_format.rs
jsmith628/gl-struct
57b29458d477194bb87f170b1cfe01fb3a0f725f
use super::*; glenum! { pub enum InternalFormatFloat { RED, RG, RGB, RGBA, COMPRESSED_RED, COMPRESSED_RG, COMPRESSED_RGB, COMPRESSED_RGBA, COMPRESSED_SRGB, COMPRESSED_SRGB_ALPHA, R8,R8_SNORM, R16,R16_SNORM, RG8,RG8_SNORM, RG16,RG16_SNORM, R3_G3_B2, RGB4, RGB5, RGB565, RGB8,RGB8_SNORM, RGB10, RGB12, RGB16,RGB16_SNORM, RGBA2, RGBA4, RGB5_A1, RGBA8,RGBA8_SNORM, RGB10_A2, RGBA12,RGBA16,RGBA16_SNORM, SRGB8,SRGB8_ALPHA8, R16F, RG16F, RGB16F, RGBA16F, R32F, RG32F, RGB32F, RGBA32F, R11F_G11F_B10F, RGB9_E5, COMPRESSED_RED_RGTC1, COMPRESSED_SIGNED_RED_RGTC1, COMPRESSED_RG_RGTC2, COMPRESSED_SIGNED_RG_RGTC2, COMPRESSED_RGBA_BPTC_UNORM, COMPRESSED_SRGB_ALPHA_BPTC_UNORM, COMPRESSED_RGB_BPTC_SIGNED_FLOAT, COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, COMPRESSED_RGB8_ETC2, COMPRESSED_SRGB8_ETC2, COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, COMPRESSED_RGBA8_ETC2_EAC, COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, COMPRESSED_R11_EAC, COMPRESSED_SIGNED_R11_EAC, COMPRESSED_RG11_EAC, COMPRESSED_SIGNED_RG11_EAC } pub enum InternalFormatInt { R8I, R16I, R32I, RG8I, RG16I, RG32I, RGB8I, RGB16I, RGB32I, RGBA8I, RGBA16I, RGBA32I } pub enum InternalFormatUInt { R8UI, R16UI, R32UI, RG8UI, RG16UI, RG32UI, RGB8UI, RGB16UI, RGB32UI, RGBA8UI, RGBA16UI, RGBA32UI, RGB10_A2UI } pub enum InternalFormatDepth { DEPTH_COMPONENT, DEPTH_COMPONENT16, DEPTH_COMPONENT24, DEPTH_COMPONENT32, DEPTH_COMPONENT32F } pub enum InternalFormatStencil { STENCIL_INDEX, STENCIL_INDEX1, STENCIL_INDEX4, STENCIL_INDEX8, STENCIL_INDEX16 } pub enum InternalFormatDepthStencil { DEPTH_STENCIL, DEPTH24_STENCIL8, DEPTH32F_STENCIL8 } } pub unsafe trait InternalFormat: GLEnum { type TypeFormat: PixelFormatType; } unsafe impl InternalFormat for InternalFormatFloat { type TypeFormat = FloatFormatType; } unsafe impl InternalFormat for InternalFormatUInt { type TypeFormat = IntFormatType; } unsafe impl InternalFormat for InternalFormatInt { type TypeFormat = IntFormatType; } unsafe impl InternalFormat for InternalFormatDepth { type TypeFormat = DepthFormatType; } unsafe impl InternalFormat for InternalFormatStencil { type TypeFormat = StencilFormatType; } unsafe impl InternalFormat for InternalFormatDepthStencil { type TypeFormat = DepthStencilFormatType; } glenum! { pub enum FormatDepth { DEPTH_COMPONENT } pub enum FormatStencil { STENCIL_INDEX } pub enum FormatDepthStencil { DEPTH_COMPONENT, STENCIL_INDEX, DEPTH_STENCIL } pub enum FormatFloat { RED, GREEN, BLUE, RG, RGB, BGR, RGBA, BGRA } pub enum FormatInt { RED_INTEGER, GREEN_INTEGER, BLUE_INTEGER, RG_INTEGER, RGB_INTEGER, BGR_INTEGER, RGBA_INTEGER, BGRA_INTEGER } } impl From<FormatInt> for FormatFloat { #[inline] fn from(fmt: FormatInt) -> Self { match fmt { FormatInt::RED_INTEGER => Self::RED, FormatInt::GREEN_INTEGER => Self::GREEN, FormatInt::BLUE_INTEGER => Self::BLUE, FormatInt::RG_INTEGER => Self::RG, FormatInt::RGB_INTEGER => Self::RGB, FormatInt::BGR_INTEGER => Self::BGR, FormatInt::RGBA_INTEGER => Self::RGBA, FormatInt::BGRA_INTEGER => Self::BGRA } } } impl From<FormatFloat> for FormatInt { #[inline] fn from(fmt: FormatFloat) -> Self { match fmt { FormatFloat::RED => Self::RED_INTEGER, FormatFloat::GREEN => Self::GREEN_INTEGER, FormatFloat::BLUE => Self::BLUE_INTEGER, FormatFloat::RG => Self::RG_INTEGER, FormatFloat::RGB => Self::RGB_INTEGER, FormatFloat::BGR => Self::BGR_INTEGER, FormatFloat::RGBA => Self::RGBA_INTEGER, FormatFloat::BGRA => Self::BGRA_INTEGER } } } impl From<FormatDepth> for FormatDepthStencil { #[inline] fn from(_fmt: FormatDepth) -> Self {Self::DEPTH_COMPONENT} } impl From<FormatStencil> for FormatDepthStencil { #[inline] fn from(_fmt: FormatStencil) -> Self {Self::STENCIL_INDEX} } pub unsafe trait PixelFormat: GLEnum { fn components(self) -> usize; } unsafe impl PixelFormat for FormatDepth { #[inline] fn components(self) -> usize {1} } unsafe impl PixelFormat for FormatStencil { #[inline] fn components(self) -> usize {1} } unsafe impl PixelFormat for FormatDepthStencil { #[inline] fn components(self) -> usize { if self == FormatDepthStencil::DEPTH_STENCIL {2} else {1} } } unsafe impl PixelFormat for FormatFloat { #[inline] fn components(self) -> usize { match self { Self::RED | Self::GREEN | Self::BLUE => 1, Self::RG => 2, Self::RGB | Self::BGR => 3, Self::RGBA | Self::BGRA => 4, } } } unsafe impl PixelFormat for FormatInt { #[inline] fn components(self) -> usize { match self { Self::RED_INTEGER | Self::GREEN_INTEGER | Self::BLUE_INTEGER => 1, Self::RG_INTEGER => 2, Self::RGB_INTEGER | Self::BGR_INTEGER => 3, Self::RGBA_INTEGER | Self::BGRA_INTEGER => 4, } } } glenum! { pub enum PixelType { UNSIGNED_BYTE, BYTE, UNSIGNED_SHORT, SHORT, UNSIGNED_INT, INT, HALF_FLOAT, FLOAT, UNSIGNED_BYTE_3_3_2, UNSIGNED_BYTE_2_3_3_REV, UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_5_6_5_REV, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_4_4_4_4_REV, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_SHORT_1_5_5_5_REV, UNSIGNED_INT_8_8_8_8, UNSIGNED_INT_8_8_8_8_REV, UNSIGNED_INT_10_10_10_2, UNSIGNED_INT_2_10_10_10_REV, UNSIGNED_INT_10F_11F_11F_REV, UNSIGNED_INT_5_9_9_9_REV, UNSIGNED_INT_24_8, FLOAT_32_UNSIGNED_INT_24_8_REV } pub enum SpecialFloatType { UNSIGNED_INT_10F_11F_11F_REV, UNSIGNED_INT_5_9_9_9_REV } pub enum SpecialDepthStencilType { FLOAT_32_UNSIGNED_INT_24_8_REV } } impl From<FloatType> for PixelType { #[inline] fn from(f:FloatType) -> Self {(f as GLenum).try_into().unwrap()} } impl From<IntType> for PixelType { #[inline] fn from(f:IntType) -> Self {(f as GLenum).try_into().unwrap()} } pub trait PixelFormatType: Copy+Clone+PartialEq+Eq+Hash+Debug { type Format: PixelFormat; fn size(self) -> usize; unsafe fn format_type(self) -> (Self::Format, PixelType); } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum IntFormatType { Integer(FormatInt, IntType), UShort4_4_4_4, UShort4_4_4_4Rev, UShort5_5_5_1, UShort1_5_5_5Rev, UInt8_8_8_8, UInt8_8_8_8Rev, UInt10_10_10_2, UInt10_10_10_2Rev } display_from_debug!(IntFormatType); impl PixelFormatType for IntFormatType { type Format = FormatInt; #[inline] fn size(self) -> usize { match self { Self::Integer(format, ty) => format.components() * ty.size(), Self::UShort4_4_4_4 | Self::UShort4_4_4_4Rev | Self::UShort5_5_5_1 | Self::UShort1_5_5_5Rev => 2, Self::UInt8_8_8_8 | Self::UInt8_8_8_8Rev | Self::UInt10_10_10_2 | Self::UInt10_10_10_2Rev => 4 } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Integer(format, ty) => (format, ty.into()), _ => ( FormatInt::RGBA_INTEGER, match self { Self::UShort4_4_4_4 => PixelType::UNSIGNED_SHORT_4_4_4_4, Self::UShort4_4_4_4Rev => PixelType::UNSIGNED_SHORT_4_4_4_4_REV, Self::UShort5_5_5_1 => PixelType::UNSIGNED_SHORT_5_5_5_1, Self::UShort1_5_5_5Rev => PixelType::UNSIGNED_SHORT_1_5_5_5_REV, Self::UInt8_8_8_8 => PixelType::UNSIGNED_INT_8_8_8_8, Self::UInt8_8_8_8Rev => PixelType::UNSIGNED_INT_8_8_8_8_REV, Self::UInt10_10_10_2 => PixelType::UNSIGNED_INT_10_10_10_2, Self::UInt10_10_10_2Rev => PixelType::UNSIGNED_INT_2_10_10_10_REV, _ => panic!("Unknown type: {}", self) } ) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum FloatFormatType { Float(FormatFloat, FloatType), Fixed(IntFormatType), UByte3_3_2, UByte2_3_3Rev, UShort5_6_5, UShort5_6_5Rev } display_from_debug!(FloatFormatType); impl PixelFormatType for FloatFormatType { type Format = FormatFloat; #[inline] fn size(self) -> usize { match self { Self::Float(format, ty) => format.components() * ty.size_of(), Self::Fixed(int) => int.size(), Self::UByte3_3_2 | Self::UByte2_3_3Rev => 1, Self::UShort5_6_5 | Self::UShort5_6_5Rev => 2 } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Float(format, ty) => (format, ty.into()), Self::Fixed(int) => {let ft = int.format_type(); (ft.0.into(), ft.1)}, Self::UByte3_3_2 => (FormatFloat::RGB, PixelType::UNSIGNED_BYTE_3_3_2), Self::UByte2_3_3Rev => (FormatFloat::RGB, PixelType::UNSIGNED_BYTE_2_3_3_REV), Self::UShort5_6_5 => (FormatFloat::RGB, PixelType::UNSIGNED_SHORT_5_6_5), Self::UShort5_6_5Rev => (FormatFloat::RGB, PixelType::UNSIGNED_SHORT_5_6_5_REV) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum DepthFormatType { Fixed(IntType), Float(FloatType) } display_from_debug!(DepthFormatType); impl PixelFormatType for DepthFormatType { type Format = FormatDepth; #[inline] fn size(self) -> usize { match self { Self::Fixed(ty) => ty.size_of(), Self::Float(ty) => ty.size_of() } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Fixed(ty) => (FormatDepth::DEPTH_COMPONENT, ty.into()), Self::Float(ty) => (FormatDepth::DEPTH_COMPONENT, ty.into()) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub struct StencilFormatType(pub IntType); display_from_debug!(StencilFormatType); impl PixelFormatType for StencilFormatType { type Format = FormatStencil; #[inline] fn size(self) -> usize { self.0.size_of() } #[inline] unsafe fn format_type(self) -> (FormatStencil, PixelType) { (FormatStencil::STENCIL_INDEX, self.0.into()) } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum DepthStencilFormatType { DepthComponent(DepthFormatType), StencilIndex(StencilFormatType), UInt24_8 } impl PixelFormatType for DepthStencilFormatType { type Format = FormatDepthStencil; #[inline] fn size(self) -> usize { match self { Self::DepthComponent(ty) => ty.size(), Self::StencilIndex(ty) => ty.size(), Self::UInt24_8 => 4 } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::DepthComponent(ty) => (FormatDepthStencil::DEPTH_COMPONENT, ty.format_type().1), Self::StencilIndex(ty) => (FormatDepthStencil::STENCIL_INDEX, ty.format_type().1), Self::UInt24_8 => (FormatDepthStencil::DEPTH_STENCIL, PixelType::UNSIGNED_INT_24_8), } } } display_from_debug!(DepthStencilFormatType);
use super::*; glenum! { pub enum InternalFormatFloat { RED, RG, RGB, RGBA, COMPRESSED_RED, COMPRESSED_RG, COMPRESSED_RGB, COMPRESSED_RGBA, COMPRESSED_SRGB, COMPRESSED_SRGB_ALPHA, R8,R8_SNORM, R16,R16_SNORM, RG8,RG8_SNORM, RG16,RG16_SNORM, R3_G3_B2, RGB4, RGB5, RGB565, RGB8,RGB8_SNORM, RGB10, RGB12, RGB16,RGB16_SNORM, RGBA2, RGBA4, RGB5_A1, RGBA8,RGBA8_SNORM, RGB10_A2, RGBA12,RGBA16,RGBA16_SNORM, SRGB8,SRGB8_ALPHA8, R16F, RG16F, RGB16F, RGBA16F, R32F, RG32F, RGB32F, RGBA32F, R11F_G11F_B10F, RGB9_E5, COMPRESSED_RED_RGTC1, COMPRESSED_SIGNED_RED_RGTC1, COMPRESSED_RG_RGTC2, COMPRESSED_SIGNED_RG_RGTC2, COMPRESSED_RGBA_BPTC_UNORM, COMPRESSED_SRGB_ALPHA_BPTC_UNORM, COMPRESSED_RGB_BPTC_SIGNED_FLOAT, COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, COMPRESSED_RGB8_ETC2, COMPRESSED_SRGB8_ETC2, COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, COMPRESSED_RGBA8_ETC2_EAC, COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, COMPRESSED_R11_EAC, COMPRESSED_SIGNED_R11_EAC, COMPRESSED_RG11_EAC, COMPRESSED_SIGNED_RG11_EAC } pub enum InternalFormatInt { R8I, R16I, R32I, RG8I, RG16I, RG32I, RGB8I, RGB16I, RGB32I, RGBA8I, RGBA16I, RGBA32I } pub enum InternalFormatUInt { R8UI, R16UI, R32UI, RG8UI, RG16UI, RG32UI, RGB8UI, RGB16UI, RGB32UI, RGBA8UI, RGBA16UI, RGBA32UI, RGB10_A2UI } pub enum InternalFormatDepth { DEPTH_COMPONENT, DEPTH_COMPONENT16, DEPTH_COMPONENT24, DEPTH_COMPONENT32, DEPTH_COMPONENT32F } pub enum InternalFormatStencil { STENCIL_INDEX, STENCIL_INDEX1, STENCIL_INDEX4, STENCIL_INDEX8, STENCIL_INDEX16 } pub enum InternalFormatDepthStencil { DEPTH_STENCIL, DEPTH24_STENCIL8, DEPTH32F_STENCIL8 } } pub unsafe trait InternalFormat: GLEnum { type TypeFormat: PixelFormatType; } unsafe impl InternalFormat for InternalFormatFloat { type TypeFormat = FloatFormatType; } unsafe impl InternalFormat for InternalFormatUInt { type TypeFormat = IntFormatType; } unsafe impl InternalFormat for InternalFormatInt { type TypeFormat = IntFormatType; } unsafe impl InternalFormat for InternalFormatDepth { type TypeFormat = DepthFormatType; } unsafe impl InternalFormat for InternalFormatStencil { type TypeFormat = StencilFormatType; } unsafe impl InternalFormat for InternalFormatDepthStencil { type TypeFormat = DepthStencilFormatType; } glenum! { pub enum FormatDepth { DEPTH_COMPONENT } pub enum FormatStencil { STENCIL_INDEX } pub enum FormatDepthStencil { DEPTH_COMPONENT, STENCIL_INDEX, DEPTH_STENCIL } pub enum FormatFloat { RED, GREEN, BLUE, RG, RGB, BGR, RGBA, BGRA } pub enum FormatInt { RED_INTEGER, GREEN_INTEGER, BLUE_INTEGER, RG_INTEGER, RGB_INTEGER, BGR_INTEGER, RGBA_INTEGER, BGRA_INTEGER } } impl From<FormatInt> for FormatFloat { #[inline] fn from(fmt: FormatInt) -> Self { match fmt { FormatInt::RED_INTEGER => Self::RED, FormatInt::GREEN_INTEGER => Self::GREEN, FormatInt::BLUE_INTEGER => Self::BLUE, FormatInt::RG_INTEGER => Self::RG, FormatInt::RGB_INTEGER => Self::RGB, FormatInt::BGR_INTEGER => Self::BGR, FormatInt::RGBA_INTEGER => Self::RGBA, FormatInt::BGRA_INTEGER => Self::BGRA } } } impl From<FormatFloat> for FormatInt { #[inline] fn from(fmt: FormatFloat) -> Self { match fmt { FormatFloat::RED => Self::RED_INTEGER, FormatFloat::GREEN => Self::GREEN_INTEGER, FormatFloat::BLUE => Self::BLUE_INTEGER, FormatFloat::RG => Self::RG_INTEGER, FormatFloat::RGB => Self::RGB_INTEGER, FormatFloat::BGR => Self::BGR_INTEGER, FormatFloat::RGBA => Self::RGBA_INTEGER, FormatFloat::BGRA => Self::BGRA_INTEGER } } } impl From<FormatDepth> for FormatDepthStencil { #[inline] fn from(_fmt: FormatDepth) -> Self {Self::DEPTH_COMPONENT} } impl From<FormatStencil> for FormatDepthStencil { #[inline] fn from(_fmt: FormatStencil) -> Self {Self::STENCIL_INDEX} } pub unsafe trait PixelFormat: GLEnum { fn components(self) -> usize; } unsafe impl PixelFormat for FormatDepth { #[inline] fn components(self) -> usize {1} } unsafe impl PixelFormat for FormatStencil { #[inline] fn components(self) -> usize {1} } unsafe impl PixelFormat for FormatDepthStencil { #[inline] fn components(self) -> usize { if self == FormatDepthStencil::DEPTH_STENCIL {2} else {1} } } unsafe impl PixelFormat for FormatFloat { #[inline] fn components(self) -> usize { match self { Self::RED | Self::GREEN | Self::BLUE => 1, Self::RG => 2, Self::RGB | Self::BGR => 3, Self::RGBA | Self::BGRA => 4, } } } unsafe impl PixelFormat for FormatInt { #[inline] fn components(self) -> usize { match self { Self::RED_INTEGER | Self::GREEN_INTEGER | Self::BLUE_INTEGER => 1, Self::RG_INTEGER => 2, Self::RGB_INTEGER | Self::BGR_INTEGER => 3, Self::RGBA_INTEGER | Self::BGRA_INTEGER => 4, } } } glenum! { pub enum PixelType { UNSIGNED_BYTE, BYTE, UNSIGNED_SHORT, SHORT, UNSIGNED_INT, INT, HALF_FLOAT, FLOAT, UNSIGNED_BYTE_3_3_2, UNSIGNED_BYTE_2_3_3_REV, UNSIGNED_SHORT_5_6_5, UNSIGNED_SHORT_5_6_5_REV, UNSIGNED_SHORT_4_4_4_4, UNSIGNED_SHORT_4_4_4_4_REV, UNSIGNED_SHORT_5_5_5_1, UNSIGNED_SHORT_1_5_5_5_REV, UNSIGNED_INT_8_8_8_8, UNSIGNED_INT_8_8_8_8_REV, UNSIGNED_INT_10_10_10_2, UNSIGNED_INT_2_10_10_10_REV, UNSIGNED_INT_10F_11F_11F_REV, UNSIGNED_INT_5_9_9_9_REV, UNSIGNED_INT_24_8, FLOAT_32_UNSIGNED_INT_24_8_REV } pub enum SpecialFloatType { UNSIGNED_INT_10F_11F_11F_REV, UNSIGNED_INT_5_9_9_9_REV } pub enum SpecialDepthStencilType { FLOAT_32_UNSIGNED_INT_24_8_REV } } impl From<FloatType> for PixelType { #[inline] fn from(f:FloatType) -> Self {(f as GLenum).try_into().unwrap()} } impl From<IntType> for PixelType { #[inline] fn from(f:IntType) -> Self {(f as GLenum).try_into().unwrap()} } pub trait PixelFormatType: Copy+Clone+PartialEq+Eq+Hash+Debug { type Format: PixelFormat; fn size(self) -> usize; unsafe fn format_type(self) -> (Self::Format, PixelType); } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum IntFormatType { Integer(FormatInt, IntType), UShort4_4_4_4, UShort4_4_4_4Rev, UShort5_5_5_1, UShort1_5_5_5Rev, UInt8_8_8_8, UInt8_8_8_8Rev, UInt10_10_10_2, UInt10_10_10_2Rev } display_from_debug!(IntFormatType); impl PixelFormatType for IntFormatType { type Format = FormatInt; #[inline] fn size(self) -> usize {
} #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Integer(format, ty) => (format, ty.into()), _ => ( FormatInt::RGBA_INTEGER, match self { Self::UShort4_4_4_4 => PixelType::UNSIGNED_SHORT_4_4_4_4, Self::UShort4_4_4_4Rev => PixelType::UNSIGNED_SHORT_4_4_4_4_REV, Self::UShort5_5_5_1 => PixelType::UNSIGNED_SHORT_5_5_5_1, Self::UShort1_5_5_5Rev => PixelType::UNSIGNED_SHORT_1_5_5_5_REV, Self::UInt8_8_8_8 => PixelType::UNSIGNED_INT_8_8_8_8, Self::UInt8_8_8_8Rev => PixelType::UNSIGNED_INT_8_8_8_8_REV, Self::UInt10_10_10_2 => PixelType::UNSIGNED_INT_10_10_10_2, Self::UInt10_10_10_2Rev => PixelType::UNSIGNED_INT_2_10_10_10_REV, _ => panic!("Unknown type: {}", self) } ) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum FloatFormatType { Float(FormatFloat, FloatType), Fixed(IntFormatType), UByte3_3_2, UByte2_3_3Rev, UShort5_6_5, UShort5_6_5Rev } display_from_debug!(FloatFormatType); impl PixelFormatType for FloatFormatType { type Format = FormatFloat; #[inline] fn size(self) -> usize { match self { Self::Float(format, ty) => format.components() * ty.size_of(), Self::Fixed(int) => int.size(), Self::UByte3_3_2 | Self::UByte2_3_3Rev => 1, Self::UShort5_6_5 | Self::UShort5_6_5Rev => 2 } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Float(format, ty) => (format, ty.into()), Self::Fixed(int) => {let ft = int.format_type(); (ft.0.into(), ft.1)}, Self::UByte3_3_2 => (FormatFloat::RGB, PixelType::UNSIGNED_BYTE_3_3_2), Self::UByte2_3_3Rev => (FormatFloat::RGB, PixelType::UNSIGNED_BYTE_2_3_3_REV), Self::UShort5_6_5 => (FormatFloat::RGB, PixelType::UNSIGNED_SHORT_5_6_5), Self::UShort5_6_5Rev => (FormatFloat::RGB, PixelType::UNSIGNED_SHORT_5_6_5_REV) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum DepthFormatType { Fixed(IntType), Float(FloatType) } display_from_debug!(DepthFormatType); impl PixelFormatType for DepthFormatType { type Format = FormatDepth; #[inline] fn size(self) -> usize { match self { Self::Fixed(ty) => ty.size_of(), Self::Float(ty) => ty.size_of() } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::Fixed(ty) => (FormatDepth::DEPTH_COMPONENT, ty.into()), Self::Float(ty) => (FormatDepth::DEPTH_COMPONENT, ty.into()) } } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub struct StencilFormatType(pub IntType); display_from_debug!(StencilFormatType); impl PixelFormatType for StencilFormatType { type Format = FormatStencil; #[inline] fn size(self) -> usize { self.0.size_of() } #[inline] unsafe fn format_type(self) -> (FormatStencil, PixelType) { (FormatStencil::STENCIL_INDEX, self.0.into()) } } #[derive(Copy,Clone,PartialEq,Eq,Hash,Debug)] pub enum DepthStencilFormatType { DepthComponent(DepthFormatType), StencilIndex(StencilFormatType), UInt24_8 } impl PixelFormatType for DepthStencilFormatType { type Format = FormatDepthStencil; #[inline] fn size(self) -> usize { match self { Self::DepthComponent(ty) => ty.size(), Self::StencilIndex(ty) => ty.size(), Self::UInt24_8 => 4 } } #[inline] unsafe fn format_type(self) -> (Self::Format, PixelType) { match self { Self::DepthComponent(ty) => (FormatDepthStencil::DEPTH_COMPONENT, ty.format_type().1), Self::StencilIndex(ty) => (FormatDepthStencil::STENCIL_INDEX, ty.format_type().1), Self::UInt24_8 => (FormatDepthStencil::DEPTH_STENCIL, PixelType::UNSIGNED_INT_24_8), } } } display_from_debug!(DepthStencilFormatType);
match self { Self::Integer(format, ty) => format.components() * ty.size(), Self::UShort4_4_4_4 | Self::UShort4_4_4_4Rev | Self::UShort5_5_5_1 | Self::UShort1_5_5_5Rev => 2, Self::UInt8_8_8_8 | Self::UInt8_8_8_8Rev | Self::UInt10_10_10_2 | Self::UInt10_10_10_2Rev => 4 }
if_condition
[ { "content": "pub trait AttributeValue<T:GLSLType>: GPUCopy { fn format(&self) -> T::AttributeFormat; }\n\nimpl<A:AttributeData<T>, T:GLSLType> AttributeValue<T> for A {\n\n #[inline] fn format(&self) -> T::AttributeFormat {A::format()}\n\n}\n\n\n", "file_path": "src/glsl/mod.rs", "rank": 0, "sco...
Rust
src/lexer.rs
kimhyunkang/r5.rs
cac10a2d3c65e72bcbeac11169fb0eba94baa53e
use std::io::{IoError, IoErrorKind}; use std::string::CowString; use std::borrow::Cow; use std::fmt; use error::{ParserError, ParserErrorKind}; #[derive(PartialEq)] pub enum Token { OpenParen, CloseParen, Dot, Identifier(CowString<'static>), True, False, Character(String), Numeric(String), EOF } impl fmt::Show for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::OpenParen => write!(f, "OpenParen"), Token::CloseParen => write!(f, "CloseParen"), Token::Dot => write!(f, "Dot"), Token::Identifier(ref name) => write!(f, "Identifier({})", name), Token::True => write!(f, "#t"), Token::False => write!(f, "#f"), Token::Character(ref name) => write!(f, "#\\{}", name), Token::Numeric(ref rep) => rep.fmt(f), Token::EOF => write!(f, "EOF"), } } } pub struct TokenWrapper { pub line: usize, pub column: usize, pub token: Token } fn wrap(line: usize, column: usize, t: Token) -> TokenWrapper { TokenWrapper { line: line, column: column, token: t } } fn is_whitespace(c: char) -> bool { match c { '\t' | '\n' | '\x0b' | '\x0c' | '\r' | ' ' => true, _ => false } } fn is_initial(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' | '!' | '$' | '%' | '&' | '*' | '/' | ':' | '<' | '=' | '>' | '?' | '^' | '_' | '~' => true, _ => false } } fn is_subsequent(c: char) -> bool { if is_initial(c) { true } else { match c { '0'...'9' | '+' | '-' | '.' | '@' => true, _ => false } } } pub struct Lexer<'a> { line: usize, column: usize, stream: &'a mut (Buffer+'a), lookahead_buf: Option<char>, } impl <'a> Lexer<'a> { pub fn new<'r>(stream: &'r mut Buffer) -> Lexer<'r> { Lexer { line: 1, column: 1, stream: stream, lookahead_buf: None, } } pub fn lex_token(&mut self) -> Result<TokenWrapper, ParserError> { try!(self.consume_whitespace()); let line = self.line; let col = self.column; let c = match self.consume() { Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(wrap(line, col, Token::EOF)), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) }, Ok(c) => c }; let end_of_token = try!(self.is_end_of_token()); if is_initial(c) { let mut init = String::new(); init.push(c); self.lex_ident(init).map(|s| wrap(line, col, Token::Identifier(Cow::Owned(s)))) } else if c == '+' && end_of_token { Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("+")))) } else if c == '-' { if end_of_token { Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("-")))) } else { match self.lookahead() { Ok('>') => self.lex_ident("-".to_string()).map(|s| wrap(line, col, Token::Identifier(Cow::Owned(s)))), Ok(c) => Err(self.make_error(ParserErrorKind::InvalidCharacter(c))), Err(e) => match e.kind { IoErrorKind::EndOfFile => Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("-")))), _ => Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } } else if c == '(' { Ok(wrap(line, col, Token::OpenParen)) } else if c == ')' { Ok(wrap(line, col, Token::CloseParen)) } else if c == '.' && end_of_token { Ok(wrap(line, col, Token::Dot)) } else if c == '#' { let c0 = match self.consume() { Err(e) => return Err(match e.kind { IoErrorKind::EndOfFile => self.make_error(ParserErrorKind::UnexpectedEOF), _ => self.make_error(ParserErrorKind::UnderlyingError(e)) }), Ok(x) => x }; match c0 { 't' | 'T' => Ok(wrap(line, col, Token::True)), 'f' | 'F' => Ok(wrap(line, col, Token::False)), '\\' => self.lex_char().map(|s| wrap(line, col, Token::Character(s))), _ => Err(self.make_error(ParserErrorKind::InvalidCharacter(c))) } } else if c.is_numeric() { self.lex_numeric(c).map(|s| wrap(line, col, Token::Numeric(s))) } else { Err(self.make_error(ParserErrorKind::InvalidCharacter(c))) } } fn is_end_of_token(&mut self) -> Result<bool, ParserError> { match self.lookahead() { Ok(c) => Ok(is_whitespace(c)), Err(e) => match e.kind { IoErrorKind::EndOfFile => Ok(true), _ => Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } fn lex_ident(&mut self, initial: String) -> Result<String, ParserError> { let mut s = initial; let sub = try!(self.read_while(is_subsequent)); s.push_str(sub.as_slice()); return Ok(s); } fn lex_char(&mut self) -> Result<String, ParserError> { let c = match self.consume() { Ok(c) => c, Err(e) => return Err(self.make_error(match e.kind { IoErrorKind::EndOfFile => ParserErrorKind::UnexpectedEOF, _ => ParserErrorKind::UnderlyingError(e) })) }; let mut s = String::new(); s.push(c); let sub = try!(self.read_while(|c| c.is_alphanumeric())); s.push_str(sub.as_slice()); return Ok(s); } fn lex_numeric(&mut self, init: char) -> Result<String, ParserError> { let mut s = String::new(); s.push(init); let sub = try!(self.read_while(|c| c.is_numeric())); s.push_str(sub.as_slice()); return Ok(s); } fn make_error(&self, kind: ParserErrorKind) -> ParserError { ParserError { line: self.line, column: self.column, kind: kind } } fn lookahead(&mut self) -> Result<char, IoError> { Ok(match self.lookahead_buf { Some(c) => c, None => { let c = try!(self.stream.read_char()); self.lookahead_buf = Some(c); c } }) } fn advance(&mut self, c: char) { if c == '\n' { self.line += 1; self.column = 1; } else { self.column += 1; } } fn read_while<F>(&mut self, f: F) -> Result<String, ParserError> where F: Fn(char) -> bool { let mut s = match self.lookahead_buf { None => String::new(), Some(c) => if f(c) { self.lookahead_buf = None; self.advance(c); let mut s = String::new(); s.push(c); s } else { return Ok(String::new()); } }; loop { match self.stream.read_char() { Ok(c) => if f(c) { self.advance(c); s.push(c); } else { self.lookahead_buf = Some(c); return Ok(s); }, Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(s), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } } fn consume(&mut self) -> Result<char, IoError> { let c = match self.lookahead_buf { Some(c) => { self.lookahead_buf = None; c }, None => try!(self.stream.read_char()) }; self.advance(c); Ok(c) } fn consume_whitespace(&mut self) -> Result<bool, ParserError> { let mut consumed = false; loop { let whitespace = try!(self.read_while(is_whitespace)); consumed = consumed || whitespace.len() > 0; match self.lookahead() { Ok(';') => { consumed = true; try!(self.read_while(|c| c != '\n')); if self.lookahead_buf.is_some() { self.lookahead_buf = None } }, Ok(_) => return Ok(consumed), Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(consumed), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } } }
use std::io::{IoError, IoErrorKind}; use std::string::CowString; use std::borrow::Cow; use std::fmt; use error::{ParserError, ParserErrorKind}; #[derive(PartialEq)] pub enum Token { OpenParen, CloseParen, Dot, Identifier(CowString<'static>), True, False, Character(String), Numeric(String), EOF } impl fmt::Show for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::OpenParen => write!(f, "OpenParen"), Token::CloseParen => write!(f, "CloseParen"), Token::Dot => write!(f, "Dot"), Token::Identifier(ref name) => write!(f, "Identifier({})", name), Token::True => write!(f, "#t"), Token::False => write!(f, "#f"), Token::Character(ref name) => write!(f, "#\\{}", name), Token::Numeric(ref rep) => rep.fmt(f), Token::EOF => write!(f, "EOF"), } } } pub struct TokenWrapper { pub line: usize, pub column: usize, pub token: Token } fn wrap(line: usize, column: usize, t: Token) -> TokenWrapper { TokenWrapper { line: line, column: column, token: t } } fn is_whitespace(c: char) -> bool { match c { '\t' | '\n' | '\x0b' | '\x0c' | '\r' | ' ' => true, _ => false } } fn is_initial(c: char) -> bool { match c { 'a'...'z' | 'A'...'Z' | '!' | '$' | '%' | '&' | '*' | '/' | ':' | '<' | '=' | '>' | '?' | '^' | '_' | '~' => true, _ => false } } fn is_subsequent(c: char) -> bool { if is_initial(c) { true } else { match c { '0'...'9' | '+' | '-' | '.' | '@' => true, _ => false } } } pub struct Lexer<'a> { line: usize, column: usize, stream: &'a mut (Buffer+'a), lookahead_buf: Option<char>, } impl <'a> Lexer<'a> { pub fn new<'r>(stream: &'r mut Buffer) -> Lexer<'r> { Lexer { line: 1, column: 1, stream: stream, lookahead_buf: None, } } pub fn lex_token(&mut self) -> Result<TokenWrapper, ParserError> { try!(self.consume_whitespace()); let line = self.line; let col = self.column; let c = match self.consume() { Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(wrap(line, col, Token::EOF)), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) }, Ok(c) => c }; let end_of_token = try!(self.is_end_of_token()); if is_initial(c) { let mut init = String::new(); init.push(c); self.lex_ident(init).map(|s| wrap(line, col, Token::Identifier(Cow::Owned(s)))) } else if c == '+' && end_of_token { Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("+")))) } else if c == '-' { if end_of_token { Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("-")))) } else { match self.lookahead() { Ok('>') => self.lex_ident("-".to_string()).map(|s| wrap(line, col, Token::Identifier(Cow::Owned(s)))), Ok(c) => Err(self.make_error(ParserErrorKind::InvalidCharacter(c))), Err(e) => match e.kind { IoErrorKind::EndOfFile => Ok(wrap(line, col, Token::Identifier(Cow::Borrowed("-")))), _ => Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } } else if c == '(' { Ok(wrap(line, col, Token::OpenParen)) } else if c == ')' { Ok(wrap(line, col, Token::CloseParen)) } else if c == '.' && end_of_token { Ok(wrap(line, col, Token::Dot)) } else if c == '#' { let c0 = match self.consume() { Err(e) => return Err(match e.kind { IoErrorKind::EndOfFile => self.make_error(ParserErrorKind::UnexpectedEOF), _ => self.make_error(ParserErrorKind::UnderlyingError(e)) }), Ok(x) => x }; match c0 { 't' | 'T' => Ok(wrap(line, col, Token::True)), 'f' | 'F' => Ok(wrap(line, col, Token::False)), '\\' => self.lex_char().map(|s| wrap(line, col, Token::Character(s))), _ => Err(self.make_error(ParserErrorKind::InvalidCharacter(c))) } } else if c.is_numeric() { self.lex_numeric(c).map(|s| wrap(line, col, Token::Numeric(s))) } else { Err(self.make_error(ParserErrorKind::InvalidCharacter(c))) } } fn is_end_of_token(&mut self) -> Result<bool, ParserError> { match self.lookahead() { Ok(c) => Ok(is_whitespace(c)), Err(e) => match e.kind { IoErrorKind::EndOfFile => Ok(true), _ => Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } fn lex_ident(&mut self, initial: String) -> Result<String, ParserError> { let mut s = initial; let sub = try!(self.read_while(is_subsequent)); s.push_str(sub.as_slice()); return Ok(s); } fn lex_char(&mut self) -> Result<String, ParserError> { let c = match self.consume() { Ok(c) => c, Err(e) => return Err(self.make_error(match e.kind { IoErrorKind::EndOfFile => ParserErrorKind::UnexpectedEOF, _ => ParserErrorKind::UnderlyingError(e) })) }; let mut s = String::new(); s.push(c); let sub = try!(self.read_while(|c| c.is_alphanumeric())); s.push_str(sub.as_slice()); return Ok(s); } fn lex_numeric(&mut self, init: char) -> Result<String, ParserError> { let mut s = String::new(); s.push(init); let sub = try!(self.read_while(|c| c.is_numeric())); s.push_str(sub.as_slice()); return Ok(s); } fn make_error(&self, kind: ParserErrorKind) -> ParserError { ParserError { line: self.line, column: self.column, kind: kind } } fn lookahead(&mut self) -> Result<char, IoError> { Ok(match self.lookahead_buf { Some(c) => c, None => { let c = try!(self.stream.read_char()); self.lookahead_buf = Some(c); c } }) } fn advance(&mut self, c: char) { if c == '\n' { self.line += 1; self.column = 1; } else { self.column += 1; } } fn read_while<F>(&mut self, f: F) -> Result<String, ParserError> where F: Fn(char) -> bool { let mut s = match self.lookahead_buf { None => String::new(), Some(c) => if f(c) { self.lookahead_buf = None; self.advance(c); let mut s = String::new(); s.push(c); s } else { return Ok(String::new()); } }; loop {
} } fn consume(&mut self) -> Result<char, IoError> { let c = match self.lookahead_buf { Some(c) => { self.lookahead_buf = None; c }, None => try!(self.stream.read_char()) }; self.advance(c); Ok(c) } fn consume_whitespace(&mut self) -> Result<bool, ParserError> { let mut consumed = false; loop { let whitespace = try!(self.read_while(is_whitespace)); consumed = consumed || whitespace.len() > 0; match self.lookahead() { Ok(';') => { consumed = true; try!(self.read_while(|c| c != '\n')); if self.lookahead_buf.is_some() { self.lookahead_buf = None } }, Ok(_) => return Ok(consumed), Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(consumed), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } } } } }
match self.stream.read_char() { Ok(c) => if f(c) { self.advance(c); s.push(c); } else { self.lookahead_buf = Some(c); return Ok(s); }, Err(e) => match e.kind { IoErrorKind::EndOfFile => return Ok(s), _ => return Err(self.make_error(ParserErrorKind::UnderlyingError(e))) } }
if_condition
[ { "content": "fn format_char(c: char, f: &mut fmt::Formatter) -> fmt::Result {\n\n try!(write!(f, \"#\\\\\"));\n\n match c {\n\n '\\0' => write!(f, \"nul\"),\n\n '\\x08' => write!(f, \"backspace\"),\n\n '\\t' => write!(f, \"tab\"),\n\n '\\x0c' => write!(f, \"page\"),\n\n ...